use-show-table-icon.ts 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import { useEffect, useState } from 'react';
  2. import { ViewUpdate } from '@codemirror/view';
  3. import { EditorView } from 'codemirror';
  4. import { UseCodeMirrorEditor } from '../codemirror-editor';
  5. import { isInTable } from './insert-new-row-to-table-markdown';
  6. const markdownTableActivatedClass = 'markdown-table-activated';
  7. export const useShowTableIcon = (codeMirrorEditor?: UseCodeMirrorEditor): { editorClass: string } => {
  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 cursorPositionListener = EditorView.updateListener.of((v: ViewUpdate) => {
  23. if (v.transactions.some(tr => tr.selection || tr.docChanged)) {
  24. handleFocusChanged();
  25. }
  26. });
  27. const cleanupFunction = codeMirrorEditor?.appendExtensions(cursorPositionListener);
  28. return cleanupFunction;
  29. }, [codeMirrorEditor, editor]);
  30. return { editorClass };
  31. };