Codemirror v6 Dynamically Add Multiple Cursors

40 Views Asked by At

Mobile users don't have a CTRL key so what I'm trying to do with my project is user clicks on a button (that is dynamically created from when the editor becomes active) and it toggles a class showing if ctrlKey is active or not (which also happens to toggle a boolean in this function. Reason being is because of the clickAddsSelectionRange documentation requirements) and Codemirror also requires allowMultipleSelections for this to work.

const jsEditor = new EditorView({
  state: EditorState.create({
    extensions: [
      basicSetup, 
      linter(esLint(new eslint.Linter(), config)),
      javascript(),
      EditorView.updateListener.of((v) => {
        if (autoupdate.checked) {
          setTimeout(() => {
            app.updatePreview(autoupdate.checked);
          }, 300);
        }
      }),
    ],
  }),
  parent: document.getElementById('jsEditor'),
  allowMultipleSelections: true,
});
activeEditor = htmlEditor;
let ctrlActive = false;

Inside the basicSetup array I call clickAddsSelectionRange.

EditorView.clickAddsSelectionRange.of(evt => ctrlActive),

The control key is toggled like so...

if (button.dataset.command === "ctrl") {
  ctrlActive = !ctrlActive; // Toggle ctrlActive variable
  button.classList.toggle('text-blue-500');
}

However the function also requires a mouse down event that I'm trying to simulate like so...

const handleTouchStart = e => {
  // Prevent default touch behavior
  e.preventDefault();
  // Simulate mouse down event
  const mouseDownEvent = new MouseEvent('mousedown', {
    bubbles: true,
    cancelable: true,
    view: window,
  });
  button.dispatchEvent(mouseDownEvent);
}
const handleTouchEnd = e => {
  // Prevent default touch behavior
  e.preventDefault();
  // Simulate mouse up event
  const mouseUpEvent = new MouseEvent('mouseup', {
    bubbles: true,
    cancelable: true,
    view: window,
  });
  button.dispatchEvent(mouseUpEvent);
  // Optionally, you can also simulate a click event if needed
  const clickEvent = new MouseEvent('click', {
    bubbles: true,
    cancelable: true,
    view: window,
  });
  button.dispatchEvent(clickEvent);
}

// Add event listeners for touch events
button.addEventListener('touchstart', handleTouchStart);
button.addEventListener('touchend', handleTouchEnd);

However I still haven't managed to dynamically add multiple cursors using Codemirror v6 and not sure what I'm missing or doing wrong. How can I dynamically add multiple cursors to codemirror from the button class when mobile users don't have a CTRL key to press?

0

There are 0 best solutions below