figure-modal.tsx 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. import OLModal, {
  2. OLModalBody,
  3. OLModalFooter,
  4. OLModalHeader,
  5. OLModalTitle,
  6. } from '@/features/ui/components/ol/ol-modal'
  7. import {
  8. FigureModalProvider,
  9. FigureModalSource,
  10. useFigureModalContext,
  11. useFigureModalExistingFigureContext,
  12. } from './figure-modal-context'
  13. import { FigureModalFooter } from './figure-modal-footer'
  14. import { lazy, memo, Suspense, useCallback, useEffect } from 'react'
  15. import { useCodeMirrorViewContext } from '../codemirror-context'
  16. import { ChangeSpec } from '@codemirror/state'
  17. import { snippet } from '@codemirror/autocomplete'
  18. import {
  19. FigureData,
  20. PastedImageData,
  21. editFigureData,
  22. editFigureDataEffect,
  23. } from '../../extensions/figure-modal'
  24. import { ensureEmptyLine } from '../../extensions/toolbar/commands'
  25. import { useTranslation } from 'react-i18next'
  26. import useEventListener from '../../../../shared/hooks/use-event-listener'
  27. import { prepareLines } from '../../utils/prepare-lines'
  28. import { FeedbackBadge } from '@/shared/components/feedback-badge'
  29. import { FullSizeLoadingSpinner } from '@/shared/components/loading-spinner'
  30. const FigureModalBody = lazy(() => import('./figure-modal-body'))
  31. export const FigureModal = memo(function FigureModal() {
  32. return (
  33. <FigureModalProvider>
  34. <FigureModalContent />
  35. </FigureModalProvider>
  36. )
  37. })
  38. const FigureModalContent = () => {
  39. const { t } = useTranslation()
  40. const getTitle = useCallback(
  41. (state: FigureModalSource) => {
  42. switch (state) {
  43. case FigureModalSource.FILE_UPLOAD:
  44. return t('upload_from_computer')
  45. case FigureModalSource.FILE_TREE:
  46. return t('insert_from_project_files')
  47. case FigureModalSource.FROM_URL:
  48. return t('insert_from_url')
  49. case FigureModalSource.OTHER_PROJECT:
  50. return t('insert_from_another_project')
  51. case FigureModalSource.EDIT_FIGURE:
  52. return t('edit_figure')
  53. default:
  54. return t('insert_image')
  55. }
  56. },
  57. [t]
  58. )
  59. const {
  60. source,
  61. dispatch,
  62. helpShown,
  63. getPath,
  64. width,
  65. includeCaption,
  66. includeLabel,
  67. sourcePickerShown,
  68. } = useFigureModalContext()
  69. const listener = useCallback(
  70. (event: Event) => {
  71. const { detail } = event as CustomEvent<{
  72. source: FigureModalSource
  73. fileId?: string
  74. filePath?: string
  75. }>
  76. dispatch({
  77. source: detail.source,
  78. selectedItemId: detail.fileId,
  79. getPath: detail.filePath ? async () => detail.filePath! : undefined,
  80. })
  81. },
  82. [dispatch]
  83. )
  84. useEffect(() => {
  85. window.addEventListener('figure-modal:open', listener)
  86. return () => {
  87. window.removeEventListener('figure-modal:open', listener)
  88. }
  89. }, [listener])
  90. const { dispatch: updateExistingFigure } =
  91. useFigureModalExistingFigureContext()
  92. const view = useCodeMirrorViewContext()
  93. const hide = useCallback(() => {
  94. dispatch({ source: FigureModalSource.NONE })
  95. view.requestMeasure()
  96. // Wait for the modal to close before focusing the editor
  97. window.setTimeout(() => view.focus(), 0)
  98. }, [dispatch, view])
  99. useEventListener(
  100. 'figure-modal:open-modal',
  101. useCallback(() => {
  102. const figure = view.state.field<FigureData>(editFigureData, false)
  103. if (!figure) {
  104. return
  105. }
  106. updateExistingFigure({
  107. name: figure.file.path,
  108. // The empty string should *not* be a complex argument
  109. hasComplexGraphicsArgument: Boolean(figure.unknownGraphicsArguments),
  110. })
  111. dispatch({
  112. source: FigureModalSource.EDIT_FIGURE,
  113. width: figure.width,
  114. includeCaption: figure.caption !== null,
  115. includeLabel: figure.label !== null,
  116. })
  117. }, [view, dispatch, updateExistingFigure])
  118. )
  119. useEventListener(
  120. 'figure-modal:paste-image',
  121. useCallback(
  122. (image: CustomEvent<PastedImageData>) => {
  123. dispatch({
  124. source: FigureModalSource.FILE_UPLOAD,
  125. pastedImageData: image.detail,
  126. })
  127. },
  128. [dispatch]
  129. )
  130. )
  131. const insert = useCallback(async () => {
  132. const figure = view.state.field<FigureData>(editFigureData, false)
  133. if (!getPath) {
  134. throw new Error('Cannot insert figure without a file path')
  135. }
  136. let path: string
  137. try {
  138. path = await getPath()
  139. } catch (error) {
  140. dispatch({ error: String(error) })
  141. return
  142. }
  143. const labelCommand = includeLabel ? '\\label{fig:enter-label}' : ''
  144. const captionCommand = includeCaption ? '\\caption{Enter Caption}' : ''
  145. if (figure) {
  146. // Updating existing figure
  147. const hadCaptionBefore = figure.caption !== null
  148. const hadLabelBefore = figure.label !== null
  149. const changes: ChangeSpec[] = []
  150. if (!hadCaptionBefore && includeCaption) {
  151. // We should insert a caption
  152. changes.push({
  153. from: figure.graphicsCommand.to,
  154. insert: prepareLines(
  155. ['', captionCommand],
  156. view.state,
  157. figure.graphicsCommand.to
  158. ),
  159. })
  160. }
  161. if (!hadLabelBefore && includeLabel) {
  162. const from = figure.caption?.to ?? figure.graphicsCommand.to
  163. // We should insert a label
  164. changes.push({
  165. from,
  166. insert: prepareLines(['', labelCommand], view.state, from),
  167. })
  168. }
  169. if (hadCaptionBefore && !includeCaption) {
  170. // We should remove the caption
  171. changes.push({
  172. from: figure.caption!.from,
  173. to: figure.caption!.to,
  174. insert: '',
  175. })
  176. }
  177. if (hadLabelBefore && !includeLabel) {
  178. // We should remove th label
  179. changes.push({
  180. from: figure.label!.from,
  181. to: figure.label!.to,
  182. insert: '',
  183. })
  184. }
  185. if (!figure.unknownGraphicsArguments && width) {
  186. // We understood the arguments, and should update the width
  187. if (figure.graphicsCommandArguments !== null) {
  188. changes.push({
  189. from: figure.graphicsCommandArguments.from,
  190. to: figure.graphicsCommandArguments.to,
  191. insert: `width=${width}\\linewidth`,
  192. })
  193. } else {
  194. // Insert new args
  195. changes.push({
  196. from: figure.file.from - 1,
  197. insert: `[width=${width}\\linewidth]`,
  198. })
  199. }
  200. }
  201. changes.push({ from: figure.file.from, to: figure.file.to, insert: path })
  202. view.dispatch({
  203. changes: view.state.changes(changes),
  204. effects: editFigureDataEffect.of(null),
  205. })
  206. } else {
  207. const { pos, suffix } = ensureEmptyLine(
  208. view.state,
  209. view.state.selection.main
  210. )
  211. const widthArgument =
  212. width !== undefined ? `[width=${width}\\linewidth]` : ''
  213. const caption = includeCaption ? `\n\t\\caption{\${Enter Caption}}` : ''
  214. const label = includeLabel ? `\n\t\\label{\${fig:enter-label}}` : ''
  215. snippet(
  216. `\\begin{figure}
  217. \t\\centering
  218. \t\\includegraphics${widthArgument}{${path}}${caption}${label}
  219. \\end{figure}${suffix}\${}`
  220. )(
  221. { state: view.state, dispatch: view.dispatch },
  222. { label: 'figure' },
  223. pos,
  224. pos
  225. )
  226. }
  227. hide()
  228. }, [getPath, view, hide, includeCaption, includeLabel, width, dispatch])
  229. const onDelete = useCallback(() => {
  230. const figure = view.state.field<FigureData>(editFigureData, false)
  231. if (!figure) {
  232. dispatch({ error: "Couldn't remove figure" })
  233. return
  234. }
  235. view.dispatch({
  236. effects: editFigureDataEffect.of(null),
  237. changes: view.state.changes({
  238. from: figure.from,
  239. to: figure.to,
  240. insert: '',
  241. }),
  242. })
  243. dispatch({ sourcePickerShown: false })
  244. hide()
  245. }, [view, hide, dispatch])
  246. const onCancel = useCallback(() => {
  247. dispatch({ sourcePickerShown: false })
  248. view.dispatch({ effects: editFigureDataEffect.of(null) })
  249. hide()
  250. }, [hide, view, dispatch])
  251. if (source === FigureModalSource.NONE) {
  252. return null
  253. }
  254. return (
  255. <OLModal onHide={hide} className="figure-modal" show>
  256. <OLModalHeader closeButton>
  257. <OLModalTitle>
  258. {helpShown
  259. ? t('help')
  260. : sourcePickerShown
  261. ? t('replace_figure')
  262. : getTitle(source)}{' '}
  263. <FeedbackBadge
  264. id="figure-modal-feedback"
  265. url="https://forms.gle/PfEtwceYBNQ32DF4A"
  266. text="Please click to give feedback about editing figures."
  267. />
  268. </OLModalTitle>
  269. </OLModalHeader>
  270. <OLModalBody>
  271. <Suspense fallback={<FullSizeLoadingSpinner minHeight="15rem" />}>
  272. <FigureModalBody />
  273. </Suspense>
  274. </OLModalBody>
  275. <OLModalFooter>
  276. <FigureModalFooter
  277. onInsert={insert}
  278. onCancel={onCancel}
  279. onDelete={onDelete}
  280. />
  281. </OLModalFooter>
  282. </OLModal>
  283. )
  284. }