symbol-palette.ts 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. import { ViewPlugin } from '@codemirror/view'
  2. import { EditorSelection } from '@codemirror/state'
  3. /**
  4. * A custom extension that listens for an `editor:insert-symbol` event and inserts the given content into the document.
  5. */
  6. export const symbolPalette = () => {
  7. return ViewPlugin.define(view => {
  8. const listener = (event: Event) => {
  9. const symbol = (event as CustomEvent<{ command: string }>).detail
  10. view.focus()
  11. const spec = view.state.changeByRange(range => {
  12. const changeSet = view.state.changes([
  13. {
  14. from: range.from,
  15. to: range.to,
  16. insert: symbol.command,
  17. },
  18. ])
  19. return {
  20. range: EditorSelection.cursor(changeSet.mapPos(range.to, 1)),
  21. changes: changeSet,
  22. }
  23. })
  24. view.dispatch(spec, {
  25. scrollIntoView: true,
  26. })
  27. }
  28. window.addEventListener('editor:insert-symbol', listener)
  29. return {
  30. destroy() {
  31. window.removeEventListener('editor:insert-symbol', listener)
  32. },
  33. }
  34. })
  35. }