CodeMirrorEditorMain.tsx 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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 { setDataLine } from '../services/extensions/setDataLine';
  6. import { useCodeMirrorEditorIsolated, useCollaborativeEditorMode } from '../stores';
  7. import { CodeMirrorEditor, CodeMirrorEditorProps } from '.';
  8. const additionalExtensions: Extension[] = [
  9. [
  10. scrollPastEnd(),
  11. setDataLine,
  12. ],
  13. ];
  14. type Props = CodeMirrorEditorProps & {
  15. userName?: string,
  16. pageId?: string,
  17. initialValue?: string,
  18. onOpenEditor?: (markdown: string) => void,
  19. }
  20. export const CodeMirrorEditorMain = (props: Props): JSX.Element => {
  21. const {
  22. acceptedUploadFileType,
  23. indentSize, userName, pageId, initialValue,
  24. editorTheme, editorKeymap,
  25. onSave, onChange, onUpload, onScroll, onOpenEditor,
  26. } = props;
  27. const { data: codeMirrorEditor } = useCodeMirrorEditorIsolated(GlobalCodeMirrorEditorKey.MAIN);
  28. useCollaborativeEditorMode(userName, pageId, initialValue, onOpenEditor, codeMirrorEditor);
  29. // setup additional extensions
  30. useEffect(() => {
  31. return codeMirrorEditor?.appendExtensions?.(additionalExtensions);
  32. }, [codeMirrorEditor]);
  33. // set handler to save with shortcut key
  34. useEffect(() => {
  35. if (onSave == null) {
  36. return;
  37. }
  38. const extension = keymap.of([
  39. {
  40. key: 'Mod-s',
  41. preventDefault: true,
  42. run: () => {
  43. const doc = codeMirrorEditor?.getDoc();
  44. if (doc != null) {
  45. onSave();
  46. }
  47. return true;
  48. },
  49. },
  50. ]);
  51. const cleanupFunction = codeMirrorEditor?.appendExtensions?.(extension);
  52. return cleanupFunction;
  53. }, [codeMirrorEditor, onSave]);
  54. return (
  55. <CodeMirrorEditor
  56. editorKey={GlobalCodeMirrorEditorKey.MAIN}
  57. onChange={onChange}
  58. onSave={onSave}
  59. onUpload={onUpload}
  60. onScroll={onScroll}
  61. acceptedUploadFileType={acceptedUploadFileType}
  62. indentSize={indentSize}
  63. editorTheme={editorTheme}
  64. editorKeymap={editorKeymap}
  65. />
  66. );
  67. };