figure-modal.tsx 8.4 KB

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