editor.js/src/components/utils/mutations.ts
VikhorKonstantin 8138ce95b2
fix issue #2523 (#2639)
* fix isMutationBelongsToElement function: make it return true if the whole text node is deleted inside of some descendant of the passed element

* isMutationBelongsToElement function shouldn't return true if some of the ancestors of the passed element were added or deleted, only if the element itself

* add test case verifying that 'onChange' is fired when the whole text inside some nested  descendant of the block is removed

* replace introduced dependency with ToolMock

* add comment explaining isMutationBelongsToElement behaviour in case of adding/removing the passed element itself

* fix formatting

* added some more explanation

* added record to the changelog

---------

Co-authored-by: Peter Savchenko <specc.dev@gmail.com>
2024-02-28 20:08:08 +03:00

36 lines
1 KiB
TypeScript

/**
* Check if passed mutation belongs to a passed element
*
* @param mutationRecord - mutation to check
* @param element - element that is expected to contain mutation
*/
export function isMutationBelongsToElement(mutationRecord: MutationRecord, element: Element): boolean {
const { type, target, addedNodes, removedNodes } = mutationRecord;
/**
* Covers all types of mutations happened to the element or it's descendants with the only one exception - removing/adding the element itself;
*/
if (element.contains(target)) {
return true;
}
/**
* In case of removing/adding the element itself, mutation type will be 'childList' and 'removedNodes'/'addedNodes' will contain the element.
*/
if (type === 'childList') {
const elementAddedItself = Array.from(addedNodes).some(node => node === element);
if (elementAddedItself) {
return true;
}
const elementRemovedItself = Array.from(removedNodes).some(node => node === element);
if (elementRemovedItself) {
return true;
}
}
return false;
}