use-show-table-icon.ts 1.3 KB

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