figure-modal.tsx 7.9 KB

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