codemirror / dev

Development repository for the CodeMirror editor project
https://codemirror.net/
Other
5.94k stars 377 forks source link

placeholder with HTMLElement, when shared between multiple views, is only visible on one view #1395

Closed ralismark closed 2 months ago

ralismark commented 5 months ago

Describe the issue

If a single instance of the placeholder extension is created by passing a HTMLElement, then the extension is used in multiple views, the placeholder is only visible in one of them.

This is because when appendChild is used to add the placeholder element, it gets removed from the previous parent.

While there is a way to duplicate an element, I think it would be preferable if you fixed this by letting the user provide a way to create and destroy placeholder elements.

Browser and platform

No response

Reproduction link

https://codemirror.net/try/?c=aW1wb3J0IHttaW5pbWFsU2V0dXAsIEVkaXRvclZpZXd9IGZyb20gImNvZGVtaXJyb3IiCmltcG9ydCB7cGxhY2Vob2xkZXJ9IGZyb20gIkBjb2RlbWlycm9yL3ZpZXciCgpjb25zdCBwbGNFbGVtID0gZG9jdW1lbnQuY3JlYXRlRWxlbWVudCgiZGl2IikKcGxjRWxlbS5pbm5lclRleHQgPSAicGxhY2Vob2xkZXIgZWxlbWVudCEiCgpjb25zdCBwbGMgPSBwbGFjZWhvbGRlcihwbGNFbGVtKQoKZm9yIChjb25zdCBfIG9mIFswLCAxXSkgewogIGNvbnN0IHBhcmVudCA9IGRvY3VtZW50LmNyZWF0ZUVsZW1lbnQoImRpdiIpCiAgZG9jdW1lbnQuYm9keS5hcHBlbmRDaGlsZChwYXJlbnQpCiAgbmV3IEVkaXRvclZpZXcoewogICAgZXh0ZW5zaW9uczogcGxjLAogICAgcGFyZW50OiBwYXJlbnQsCiAgfSkKfQ==

import {minimalSetup, EditorView} from "codemirror"
import {placeholder} from "@codemirror/view"

const plcElem = document.createElement("div")
plcElem.innerText = "placeholder element!"

const plc = placeholder(plcElem)

for (const _ of [0, 1]) {
  const parent = document.createElement("div")
  document.body.appendChild(parent)
  new EditorView({
    extensions: plc,
    parent: parent,
  })
}
loca-tion commented 2 months ago

Issue : A single placeholder element is being reused for multiple CodeMirror editor instances. Since a DOM element can only exist in one place at a time, the placeholder disappears from the first editor when it's added to the second editor.

Approach: To fix this, we need to create a new placeholder element for each editor instance instead of reusing the same one. This ensures that each editor has its own independent placeholder, preventing the DOM element conflict.

loca-tion commented 2 months ago
import {minimalSetup, EditorView} from "codemirror"
import {placeholder} from "@codemirror/view"

const createPlaceholder = () => {
  const plcElem = document.createElement("div");
  plcElem.innerText = "placeholder element!";
  return placeholder(plcElem);
};

for (const _ of [0, 1]) {
  const parent = document.createElement("div");
  document.body.appendChild(parent);
  new EditorView({
    extensions: createPlaceholder(),  // Create a new placeholder for each editor
    parent: parent,
  });
}
marijnh commented 2 months ago

Attached patch makes it so that you can pass in a function to construct the placeholder element.