2
0

CodeMirrorEditorMain.tsx 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import { useEffect } from 'react';
  2. import type { Extension } from '@codemirror/state';
  3. import { keymap, scrollPastEnd } from '@codemirror/view';
  4. import { GlobalCodeMirrorEditorKey } from '../consts';
  5. import { useCodeMirrorEditorIsolated } from '../stores';
  6. import { CodeMirrorEditor } from '.';
  7. const additionalExtensions: Extension[] = [
  8. scrollPastEnd(),
  9. ];
  10. type Props = {
  11. onChange?: (value: string) => void,
  12. onSave?: () => void,
  13. }
  14. export const CodeMirrorEditorMain = (props: Props): JSX.Element => {
  15. const {
  16. onSave, onChange,
  17. } = props;
  18. const { data: codeMirrorEditor } = useCodeMirrorEditorIsolated(GlobalCodeMirrorEditorKey.MAIN);
  19. // setup additional extensions
  20. useEffect(() => {
  21. return codeMirrorEditor?.appendExtensions?.(additionalExtensions);
  22. }, [codeMirrorEditor]);
  23. // set handler to save with shortcut key
  24. useEffect(() => {
  25. if (onSave == null) {
  26. return;
  27. }
  28. const extension = keymap.of([
  29. {
  30. key: 'Mod-s',
  31. preventDefault: true,
  32. run: () => {
  33. const doc = codeMirrorEditor?.getDoc();
  34. if (doc != null) {
  35. onSave();
  36. }
  37. return true;
  38. },
  39. },
  40. ]);
  41. const cleanupFunction = codeMirrorEditor?.appendExtensions?.(extension);
  42. return cleanupFunction;
  43. }, [codeMirrorEditor, onSave]);
  44. return (
  45. <CodeMirrorEditor
  46. editorKey={GlobalCodeMirrorEditorKey.MAIN}
  47. onChange={onChange}
  48. />
  49. );
  50. };