uiwjs / react-codemirror

CodeMirror 6 component for React. @codemirror https://uiwjs.github.io/react-codemirror/
https://uiwjs.github.io/react-codemirror/
MIT License
1.62k stars 129 forks source link

Format the clipboard value on Paste #368

Open dmtrrk opened 2 years ago

dmtrrk commented 2 years ago

I'm using the Code Mirror to visualize and lint a list of words for the user. My expectation is to auto-format the inserted text e.g. convert a, b, c to 3 lines of a, b and c.

I tried to use:

  1. onPaste event and clipboard.setData('text/plain', myData)
  2. prevent the default paste behavior and insert my custom text instead. But eventually selection is always points to 0, 0, there is no getCursor() interface, so I did not find how to do so
  3. I did not find the way how to replace the entire text with my formatted one (prevent onPaste, format the new text and set it)

Is there a correct approach to do that?

jaywcjlove commented 2 years ago

@dmtrrk Here are some examples: https://github.com/uiwjs/react-markdown-editor/blob/eced98752edced4de4b17d70a0e0e7a94c6237a8/src/commands/image.tsx#L17-L28

const main = view.state.selection.main;
const txt = view.state.sliceDoc(view.state.selection.main.from, view.state.selection.main.to);
view.dispatch({
  changes: {
    from: main.from,
    to: main.to,
    insert: `![](${txt})`,
  },
  selection: EditorSelection.range(main.from + 4, main.to + 4),
  // selection: { anchor: main.from + 4 },
});
jaywcjlove commented 2 years ago

@dmtrrk

cm.getCursor() → cm.state.selection.main.head

The selection, like in the previous version, consists of a number of selection ranges, one of which is considered the main selection.

cm.getCursor() → cm.state.selection.main.head

cm.listSelections() → cm.state.selection.ranges

cm.getSelection() → cm.state.sliceDoc(
  cm.state.selection.main.from,
  cm.state.selection.main.to)

cm.getSelections() → cm.state.selection.ranges.map(
  r => cm.state.sliceDoc(r.from, r.to))

cm.somethingSelected() → cm.state.selection.ranges.some(r => !r.empty)
jaywcjlove commented 2 years ago

@dmtrrk You may need to find your answer here (https://discuss.codemirror.net/)