codex-team / codex-team/editor.js

Memory leak in Shortcuts class

Open
#2,631 6 comments 2 reactions 0 assignees View on GitHub
good first issue
Dominant language
TypeScript
Stars
31.9k
Forks
2.2k
Avg merge
1d 1h
Merged PRs (30d)
1

Description

**Editor.js Version**

v2.29.0

**Issue description**

Hi!

I've found a memory leak in the Shortcuts class. When you remove the shortcut for an element you don't check if the element's shortcuts are empty and left the element in the registeredShortcuts map (with an empty array):

https://github.com/codex-team/editor.js/blob/b619946e8f23ebc9ccfc41ef653439278e99491e/src/components/utils/shortcuts.ts#L89

If you create a new EditorJS and destroys it, you will see a bunch of detached elements referenced by registeredShortcuts map.

**Steps to reproduce:**

You can reproduce the issue with this simple html:

```


Remove




let editor = new EditorJS({
holder: 'editor',
});

function remove() {
document.querySelector('#editor').remove();
editor.isReady.then(() => {
editor.destroy();
editor = undefined;
});
}
document.querySelector('#remove').addEventListener('click', remove);

```

Press "Remove" button and take a snapshot in Chrome dev tools. You will see detached HTMLDivElement's referenced by registeredShortcuts:

![screenshot](https://github.com/codex-team/editor.js/assets/480573/e3a904bd-be0d-47c6-bf73-489ef44ea308)

If you remove the element from the map when the shortcuts array is empty, the problem disappears:

```js
const newShortcuts = shortcuts.filter(el => el !== shortcut);

newShortcuts.length===0?
this.registeredShortcuts.delete(element):
this.registeredShortcuts.set(element, newShortcuts);
```

![screenshot2](https://github.com/codex-team/editor.js/assets/480573/a45fef11-38ee-48c6-9c92-9ccdb3a2aa5e)

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.