use-show-table-icon.ts 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import { useEffect, useState } from 'react';
  2. import type { ViewUpdate } from '@codemirror/view';
  3. import { EditorView } from 'codemirror';
  4. import type { UseCodeMirrorEditor } from '../../services-ext';
  5. import { isInTable } from './insert-new-row-to-table-markdown';
  6. const markdownTableActivatedClass = 'markdown-table-activated';
  7. export const useShowTableIcon = (codeMirrorEditor?: UseCodeMirrorEditor): void => {
  8. const [editorClass, setEditorClass] = useState('');
  9. const editor = codeMirrorEditor?.view;
  10. useEffect(() => {
  11. const handleFocusChanged = () => {
  12. if (editor == null) {
  13. return;
  14. }
  15. if (isInTable(editor)) {
  16. setEditorClass(markdownTableActivatedClass);
  17. }
  18. else {
  19. setEditorClass('');
  20. }
  21. };
  22. const cleanupFunction = codeMirrorEditor?.appendExtensions(
  23. EditorView.updateListener.of((v: ViewUpdate) => {
  24. if (v.transactions.some(tr => tr.selection || tr.docChanged)) {
  25. handleFocusChanged();
  26. }
  27. }),
  28. );
  29. return cleanupFunction;
  30. }, [codeMirrorEditor, editor]);
  31. useEffect(() => {
  32. const cleanupFunction = codeMirrorEditor?.appendExtensions(
  33. EditorView.editorAttributes.of({ class: editorClass }),
  34. );
  35. return cleanupFunction;
  36. }, [codeMirrorEditor, editorClass]);
  37. };