Skip to content

Commit

Permalink
Adding detect key events and fixing back space issue
Browse files Browse the repository at this point in the history
The backspace update from editor-js#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.
  • Loading branch information
donnfelker committed Apr 14, 2024
1 parent a6dc6a6 commit ba4b604
Showing 1 changed file with 36 additions and 17 deletions.
53 changes: 36 additions & 17 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down Expand Up @@ -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()
}
}))
}

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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;
Expand Down

0 comments on commit ba4b604

Please sign in to comment.