figure-modal.tsx 8.2 KB

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