figure-modal.tsx 8.6 KB

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