use-included-file.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import { useCodeMirrorStateContext } from '@/features/source-editor/components/codemirror-context'
  2. import { useFileTreePathContext } from '@/features/file-tree/contexts/file-tree-path'
  3. import { useEditorManagerContext } from '@/features/ide-react/context/editor-manager-context'
  4. import { useCallback } from 'react'
  5. import { EditorState } from '@codemirror/state'
  6. import { resolveCommandNode } from '@/features/source-editor/extensions/command-tooltip'
  7. import {
  8. FilePathArgument,
  9. LiteralArgContent,
  10. } from '@/features/source-editor/lezer-latex/latex.terms.mjs'
  11. export const useIncludedFile = (argumentType: string) => {
  12. const state = useCodeMirrorStateContext()
  13. const { findEntityByPath } = useFileTreePathContext()
  14. const { openDocWithId } = useEditorManagerContext()
  15. const openIncludedFile = useCallback(() => {
  16. const name = readIncludedPath(state, argumentType)
  17. if (name) {
  18. // TODO: find in relative path or root folder
  19. for (const extension of ['.tex', '']) {
  20. const result = findEntityByPath(`${name}${extension}`)
  21. if (result) {
  22. return openDocWithId(result.entity._id)
  23. }
  24. }
  25. // TODO: handle file not found
  26. }
  27. }, [argumentType, findEntityByPath, openDocWithId, state])
  28. return { openIncludedFile }
  29. }
  30. const readIncludedPath = (
  31. state: EditorState,
  32. argumentType: string | number
  33. ) => {
  34. const commandNode = resolveCommandNode(state)
  35. const argumentNode = commandNode
  36. ?.getChild(argumentType)
  37. ?.getChild(FilePathArgument)
  38. ?.getChild(LiteralArgContent)
  39. if (argumentNode) {
  40. return state.sliceDoc(argumentNode.from, argumentNode.to)
  41. }
  42. }