CodeMirrorEditorMain.tsx 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import { useEffect } from 'react';
  2. import type { Extension } from '@codemirror/state';
  3. import { keymap, scrollPastEnd } from '@codemirror/view';
  4. import { GlobalCodeMirrorEditorKey, AcceptedUploadFileType } 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. onUpload?: (files: File[]) => void,
  14. acceptedFileType?: AcceptedUploadFileType,
  15. indentSize?: number,
  16. }
  17. export const CodeMirrorEditorMain = (props: Props): JSX.Element => {
  18. const {
  19. onSave, onChange, onUpload, acceptedFileType, indentSize,
  20. } = props;
  21. const { data: codeMirrorEditor } = useCodeMirrorEditorIsolated(GlobalCodeMirrorEditorKey.MAIN);
  22. const acceptedFileTypeNoOpt = acceptedFileType ?? AcceptedUploadFileType.NONE;
  23. // setup additional extensions
  24. useEffect(() => {
  25. return codeMirrorEditor?.appendExtensions?.(additionalExtensions);
  26. }, [codeMirrorEditor]);
  27. // set handler to save with shortcut key
  28. useEffect(() => {
  29. if (onSave == null) {
  30. return;
  31. }
  32. const extension = keymap.of([
  33. {
  34. key: 'Mod-s',
  35. preventDefault: true,
  36. run: () => {
  37. const doc = codeMirrorEditor?.getDoc();
  38. if (doc != null) {
  39. onSave();
  40. }
  41. return true;
  42. },
  43. },
  44. ]);
  45. const cleanupFunction = codeMirrorEditor?.appendExtensions?.(extension);
  46. return cleanupFunction;
  47. }, [codeMirrorEditor, onSave]);
  48. return (
  49. <CodeMirrorEditor
  50. editorKey={GlobalCodeMirrorEditorKey.MAIN}
  51. onChange={onChange}
  52. onUpload={onUpload}
  53. acceptedFileType={acceptedFileTypeNoOpt}
  54. indentSize={indentSize}
  55. />
  56. );
  57. };