file-tree-item-drop.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import { EditorView } from '@codemirror/view'
  2. import { hasImageExtension } from '@/features/source-editor/utils/file'
  3. import { FigureModalSource } from '@/features/source-editor/components/figure-modal/figure-modal-context'
  4. import { EditorSelection } from '@codemirror/state'
  5. export const fileTreeItemDrop = () =>
  6. EditorView.domEventHandlers({
  7. dragover(event) {
  8. // TODO: detect a drag from the file tree?
  9. if (event.dataTransfer) {
  10. event.preventDefault()
  11. }
  12. },
  13. drop(event, view) {
  14. if (event.dataTransfer) {
  15. const fileId = event.dataTransfer.getData(
  16. 'application/x-overleaf-file-id'
  17. )
  18. const filePath = event.dataTransfer.getData(
  19. 'application/x-overleaf-file-path'
  20. )
  21. if (fileId && filePath) {
  22. event.preventDefault()
  23. const pos = view.posAtCoords(event)
  24. if (pos !== null) {
  25. handleDroppedFile(view, pos, fileId, filePath)
  26. }
  27. }
  28. }
  29. },
  30. })
  31. const withoutExtension = (filename: string) =>
  32. filename.substring(0, filename.lastIndexOf('.'))
  33. const handleDroppedFile = (
  34. view: EditorView,
  35. pos: number,
  36. fileId: string,
  37. filePath: string
  38. ) => {
  39. if (filePath.endsWith('.bib')) {
  40. view.focus()
  41. const insert = `\\bibliography{${withoutExtension(filePath)}}`
  42. view.dispatch({
  43. changes: { from: pos, insert },
  44. selection: EditorSelection.cursor(pos + insert.length),
  45. })
  46. return
  47. }
  48. if (filePath.endsWith('.tex')) {
  49. view.focus()
  50. const insert = `\\input{${withoutExtension(filePath)}}`
  51. view.dispatch({
  52. changes: { from: pos, insert },
  53. selection: EditorSelection.cursor(pos + insert.length),
  54. })
  55. return
  56. }
  57. if (hasImageExtension(filePath)) {
  58. view.focus()
  59. view.dispatch({
  60. selection: EditorSelection.cursor(pos),
  61. })
  62. window.dispatchEvent(
  63. new CustomEvent('figure-modal:open', {
  64. detail: {
  65. source: FigureModalSource.FILE_TREE,
  66. fileId,
  67. filePath,
  68. },
  69. })
  70. )
  71. return
  72. }
  73. return null
  74. }