figure-modal.tsx 8.5 KB

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