figure-modal.tsx 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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. view.focus()
  97. }, [dispatch, view])
  98. useEventListener(
  99. 'figure-modal:open-modal',
  100. useCallback(() => {
  101. const figure = view.state.field<FigureData>(editFigureData, false)
  102. if (!figure) {
  103. return
  104. }
  105. updateExistingFigure({
  106. name: figure.file.path,
  107. // The empty string should *not* be a complex argument
  108. hasComplexGraphicsArgument: Boolean(figure.unknownGraphicsArguments),
  109. })
  110. dispatch({
  111. source: FigureModalSource.EDIT_FIGURE,
  112. width: figure.width,
  113. includeCaption: figure.caption !== null,
  114. includeLabel: figure.label !== null,
  115. })
  116. }, [view, dispatch, updateExistingFigure])
  117. )
  118. useEventListener(
  119. 'figure-modal:paste-image',
  120. useCallback(
  121. (image: CustomEvent<PastedImageData>) => {
  122. dispatch({
  123. source: FigureModalSource.FILE_UPLOAD,
  124. pastedImageData: image.detail,
  125. })
  126. },
  127. [dispatch]
  128. )
  129. )
  130. const insert = useCallback(async () => {
  131. const figure = view.state.field<FigureData>(editFigureData, false)
  132. if (!getPath) {
  133. throw new Error('Cannot insert figure without a file path')
  134. }
  135. let path: string
  136. try {
  137. path = await getPath()
  138. } catch (error) {
  139. dispatch({ error: String(error) })
  140. return
  141. }
  142. const labelCommand = includeLabel ? '\\label{fig:enter-label}' : ''
  143. const captionCommand = includeCaption ? '\\caption{Enter Caption}' : ''
  144. if (figure) {
  145. // Updating existing figure
  146. const hadCaptionBefore = figure.caption !== null
  147. const hadLabelBefore = figure.label !== null
  148. const changes: ChangeSpec[] = []
  149. if (!hadCaptionBefore && includeCaption) {
  150. // We should insert a caption
  151. changes.push({
  152. from: figure.graphicsCommand.to,
  153. insert: prepareLines(
  154. ['', captionCommand],
  155. view.state,
  156. figure.graphicsCommand.to
  157. ),
  158. })
  159. }
  160. if (!hadLabelBefore && includeLabel) {
  161. const from = figure.caption?.to ?? figure.graphicsCommand.to
  162. // We should insert a label
  163. changes.push({
  164. from,
  165. insert: prepareLines(['', labelCommand], view.state, from),
  166. })
  167. }
  168. if (hadCaptionBefore && !includeCaption) {
  169. // We should remove the caption
  170. changes.push({
  171. from: figure.caption!.from,
  172. to: figure.caption!.to,
  173. insert: '',
  174. })
  175. }
  176. if (hadLabelBefore && !includeLabel) {
  177. // We should remove th label
  178. changes.push({
  179. from: figure.label!.from,
  180. to: figure.label!.to,
  181. insert: '',
  182. })
  183. }
  184. if (!figure.unknownGraphicsArguments && width) {
  185. // We understood the arguments, and should update the width
  186. if (figure.graphicsCommandArguments !== null) {
  187. changes.push({
  188. from: figure.graphicsCommandArguments.from,
  189. to: figure.graphicsCommandArguments.to,
  190. insert: `width=${width}\\linewidth`,
  191. })
  192. } else {
  193. // Insert new args
  194. changes.push({
  195. from: figure.file.from - 1,
  196. insert: `[width=${width}\\linewidth]`,
  197. })
  198. }
  199. }
  200. changes.push({ from: figure.file.from, to: figure.file.to, insert: path })
  201. view.dispatch({
  202. changes: view.state.changes(changes),
  203. effects: editFigureDataEffect.of(null),
  204. })
  205. } else {
  206. const { pos, suffix } = ensureEmptyLine(
  207. view.state,
  208. view.state.selection.main
  209. )
  210. const widthArgument =
  211. width !== undefined ? `[width=${width}\\linewidth]` : ''
  212. const caption = includeCaption ? `\n\t\\caption{\${Enter Caption}}` : ''
  213. const label = includeLabel ? `\n\t\\label{\${fig:enter-label}}` : ''
  214. snippet(
  215. `\\begin{figure}
  216. \t\\centering
  217. \t\\includegraphics${widthArgument}{${path}}${caption}${label}
  218. \\end{figure}${suffix}\${}`
  219. )(
  220. { state: view.state, dispatch: view.dispatch },
  221. { label: 'figure' },
  222. pos,
  223. pos
  224. )
  225. }
  226. hide()
  227. }, [getPath, view, hide, includeCaption, includeLabel, width, dispatch])
  228. const onDelete = useCallback(() => {
  229. const figure = view.state.field<FigureData>(editFigureData, false)
  230. if (!figure) {
  231. dispatch({ error: "Couldn't remove figure" })
  232. return
  233. }
  234. view.dispatch({
  235. effects: editFigureDataEffect.of(null),
  236. changes: view.state.changes({
  237. from: figure.from,
  238. to: figure.to,
  239. insert: '',
  240. }),
  241. })
  242. dispatch({ sourcePickerShown: false })
  243. hide()
  244. }, [view, hide, dispatch])
  245. const onCancel = useCallback(() => {
  246. dispatch({ sourcePickerShown: false })
  247. view.dispatch({ effects: editFigureDataEffect.of(null) })
  248. hide()
  249. }, [hide, view, dispatch])
  250. if (source === FigureModalSource.NONE) {
  251. return null
  252. }
  253. return (
  254. <OLModal onHide={hide} className="figure-modal" show>
  255. <OLModalHeader closeButton>
  256. <OLModalTitle>
  257. {helpShown
  258. ? t('help')
  259. : sourcePickerShown
  260. ? t('replace_figure')
  261. : getTitle(source)}{' '}
  262. <FeedbackBadge
  263. id="figure-modal-feedback"
  264. url="https://forms.gle/PfEtwceYBNQ32DF4A"
  265. text="Please click to give feedback about editing figures."
  266. />
  267. </OLModalTitle>
  268. </OLModalHeader>
  269. <OLModalBody>
  270. <Suspense fallback={<FullSizeLoadingSpinner minHeight="15rem" />}>
  271. <FigureModalBody />
  272. </Suspense>
  273. </OLModalBody>
  274. <OLModalFooter>
  275. <FigureModalFooter
  276. onInsert={insert}
  277. onCancel={onCancel}
  278. onDelete={onDelete}
  279. />
  280. </OLModalFooter>
  281. </OLModal>
  282. )
  283. }