From ba4b604da7c36612f6ed85186b42d38dacb4777f Mon Sep 17 00:00:00 2001 From: Donn Felker Date: Sat, 13 Apr 2024 20:22:28 -0400 Subject: [PATCH] Adding detect key events and fixing back space issue The backspace update from #95 worked, but the event listeners are lost when the toggleTune is invoked. This PR adds the listeners back after the tune is invoked. The listeners are lost because replaceWith does not propogate the existing listeners to the new element. --- src/index.js | 53 +++++++++++++++++++++++++++++++++++----------------- 1 file changed, 36 insertions(+), 17 deletions(-) diff --git a/src/index.js b/src/index.js index 186a41d..51c6604 100644 --- a/src/index.js +++ b/src/index.js @@ -124,21 +124,7 @@ export default class List { this._elements.wrapper.appendChild(this._make('li', this.CSS.item)); } - if (!this.readOnly) { - // detect keydown on the last item to escape List - this._elements.wrapper.addEventListener('keydown', (event) => { - const [ENTER, BACKSPACE] = [13, 8]; // key codes - - switch (event.keyCode) { - case ENTER: - this.getOutofList(event); - break; - case BACKSPACE: - this.backspace(event); - break; - } - }, false); - } + this.detectKeyEvents() return this._elements.wrapper; } @@ -207,7 +193,10 @@ export default class List { ...item, isActive: this._data.style === item.name, closeOnActivate: true, - onActivate: () => this.toggleTune(item.name) + onActivate: () => { + this.toggleTune(item.name) + this.detectKeyEvents() + } })) } @@ -360,6 +349,29 @@ export default class List { return currentNode.closest(`.${this.CSS.item}`); } + + /** + * Add keydown listeners for escaping from a list and + * back space events. + */ + detectKeyEvents() { + if (!this.readOnly) { + // detect keydown on the last item to escape List + this._elements.wrapper.addEventListener('keydown', (event) => { + const [ENTER, BACKSPACE] = [13, 8]; // key codes + + switch (event.keyCode) { + case ENTER: + this.getOutofList(event); + break; + case BACKSPACE: + this.backspace(event); + break; + } + }, false); + } + } + /** * Get out from List Tool * by Enter on the empty last item @@ -397,7 +409,14 @@ export default class List { */ backspace(event) { const items = this._elements.wrapper.querySelectorAll('.' + this.CSS.item), - firstItem = items[0]; + firstItem = items[0]; + + if (this.currentItem.textContent.trim() === '') { + const target = this.currentItem; + window.requestIdleCallback(() => { + target.parentElement.removeChild(target); + }) + } if (!firstItem) { return;