facebookarchive / draft-js

A React framework for building text editors.
https://draftjs.org/
MIT License
22.56k stars 2.64k forks source link

EditorState.createWithContent() returning orphans entities of previous editorState #3138

Open MamorukunBE opened 2 years ago

MamorukunBE commented 2 years ago

Hi from Belgium.

To make it short before going into details (if needed): I am using "draft-js": "^0.11.7" in which I save the page color in an entity (type: "pageColor") not linked to any character (because the page color has to stay available even if the user selects all and delete). Then, when loading the document, I simply scan all entities (editorContent.getAllEntities()) for the one of type "pageColor" and extract its data into CSS.

Everything works fine with that method... except that their is no function to delete an entity outside any selection AND that such "orphan entities" seems to be forgotten by draftjs when cleaning an editor state. Result: in my website, the editor state is well cleaned when I get out of the editor route, but when I come back and create a fresh editor state using EditorState.createWithContent(), the resulting state contains that/those orphan (stacked) entity(ies) related to page color of the previous state(s). In other words, any new document will have the page color of the previous one!

Anyway for me to completely clean whatever buffer is holding those "orphan entities" ?

EDIT: The only way I have found to solve that problem is by "forcing all those unused pageColor entities to default color" using the fellowing function. But it doesn't solve the problem of orphan entities stacking each time I recreate a new doccument :(

function PostprocessEditorContent(editorContent, loadedDocumentHasPageColor) {
  // Keep only the first instance of pageColor entity, if needed (orphan entities are
  // not automaticaly cleaned and we don't know yet how to delete such entities!)
  //---------------------------------------------------------------------------------
  let contentReversedEntities = editorContent.getAllEntities().toArray().sort(ReverseSortEntitiesByCreationTime);
  let mainPageColorFound = false;
  for (let i = 0; i < contentReversedEntities.length; i++) {
    if (contentReversedEntities[i].type === 'pageColor')
      if (loadedDocumentHasPageColor && !mainPageColorFound) mainPageColorFound = true;   // Keep the loaded page color entity
      else contentReversedEntities[i].data.color = 'var(--text-bg-color)';    // And set all the other entries to default color
  }
  return editorContent;
}