source-editor.stories.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. import SourceEditor from '../../js/features/source-editor/components/source-editor'
  2. import { ScopeDecorator } from '../decorators/scope'
  3. import { useScope } from '../hooks/use-scope'
  4. import { useMeta } from '../hooks/use-meta'
  5. import React, { FC, useState } from 'react'
  6. import { FileTreePathContext } from '@/features/file-tree/contexts/file-tree-path'
  7. import RangesTracker from '@overleaf/ranges-tracker'
  8. import useExposedState from '@/shared/hooks/use-exposed-state'
  9. import { EditorOpenDocContext } from '@/features/ide-react/context/editor-open-doc-context'
  10. import { DocId } from '../../../types/project-settings'
  11. import { StoryObj } from '@storybook/react'
  12. import { DocumentContainer } from '@/features/ide-react/editor/document-container'
  13. import { EditorPropertiesContext } from '@/features/ide-react/context/editor-properties-context'
  14. type Story = StoryObj<typeof SourceEditor>
  15. const EditorOpenDocProvider: FC<
  16. React.PropsWithChildren<{
  17. initialOpenDocName: string | null
  18. initialDocument: DocumentContainer
  19. }>
  20. > = ({ children, initialOpenDocName, initialDocument }) => {
  21. const [currentDocumentId, setCurrentDocumentId] =
  22. useExposedState<DocId | null>(null, 'editor.open_doc_id')
  23. const [openDocName, setOpenDocName] = useExposedState<string | null>(
  24. initialOpenDocName,
  25. 'editor.open_doc_name'
  26. )
  27. const [currentDocument, setCurrentDocument] =
  28. useState<DocumentContainer | null>(initialDocument)
  29. const value = {
  30. currentDocumentId,
  31. setCurrentDocumentId,
  32. openDocName,
  33. setOpenDocName,
  34. currentDocument,
  35. setCurrentDocument,
  36. }
  37. return (
  38. <EditorOpenDocContext.Provider value={value}>
  39. {children}
  40. </EditorOpenDocContext.Provider>
  41. )
  42. }
  43. const LatexEditorOpenDocProvider: FC<React.PropsWithChildren> = ({
  44. children,
  45. }) => (
  46. <EditorOpenDocProvider
  47. initialOpenDocName="example.tex"
  48. initialDocument={
  49. mockDoc(content.tex, changes.tex) as unknown as DocumentContainer
  50. }
  51. >
  52. {children}
  53. </EditorOpenDocProvider>
  54. )
  55. const MarkdownEditorOpenDocProvider: FC<React.PropsWithChildren> = ({
  56. children,
  57. }) => (
  58. <EditorOpenDocProvider
  59. initialOpenDocName="example.md"
  60. initialDocument={
  61. mockDoc(content.md, changes.md) as unknown as DocumentContainer
  62. }
  63. >
  64. {children}
  65. </EditorOpenDocProvider>
  66. )
  67. const BibtexEditorOpenDocProvider: FC<React.PropsWithChildren> = ({
  68. children,
  69. }) => (
  70. <EditorOpenDocProvider
  71. initialOpenDocName="example.bib"
  72. initialDocument={
  73. mockDoc(content.bib, changes.bib) as unknown as DocumentContainer
  74. }
  75. >
  76. {children}
  77. </EditorOpenDocProvider>
  78. )
  79. const VisualEditorPropertiesProvider: FC<React.PropsWithChildren> = ({
  80. children,
  81. }) => {
  82. const [showVisual, setShowVisual] = useState(true)
  83. const value = {
  84. showVisual,
  85. setShowVisual,
  86. showSymbolPalette: true,
  87. setShowSymbolPalette: () => undefined,
  88. toggleSymbolPalette: () => undefined,
  89. opening: true,
  90. setOpening: () => undefined,
  91. trackChanges: false,
  92. setTrackChanges: () => undefined,
  93. wantTrackChanges: false,
  94. setWantTrackChanges: () => undefined,
  95. errorState: false,
  96. setErrorState: () => undefined,
  97. }
  98. return (
  99. <EditorPropertiesContext.Provider value={value}>
  100. {children}
  101. </EditorPropertiesContext.Provider>
  102. )
  103. }
  104. const FileTreePathProvider: FC<React.PropsWithChildren> = ({ children }) => (
  105. <FileTreePathContext.Provider
  106. value={{
  107. dirname: () => null,
  108. findEntityByPath: () => null,
  109. pathInFolder: () => null,
  110. previewByPath: (path: string) =>
  111. path === 'frog.jpg'
  112. ? {
  113. extension: 'png',
  114. url: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAAEsCAYAAAB5fY51AAABhWlDQ1BJQ0MgcHJvZmlsZQAAKJF9kT1Iw0AcxV9TpaJVETuIOGSogmBBVMRRq1CECqFWaNXB5NIvaNKQpLg4Cq4FBz8Wqw4uzro6uAqC4AeIq4uToouU+L+k0CLWg+N+vLv3uHsHCNUi06y2cUDTbTMRi4qp9KoYeIWAPnShB6Mys4w5SYqj5fi6h4+vdxGe1frcn6NbzVgM8InEs8wwbeIN4ulN2+C8TxxieVklPiceM+mCxI9cVzx+45xzWeCZITOZmCcOEYu5JlaamOVNjXiKOKxqOuULKY9VzluctWKZ1e/JXxjM6CvLXKc5hBgWsQQJIhSUUUARNiK06qRYSNB+tIV/0PVL5FLIVQAjxwJK0CC7fvA/+N2tlZ2c8JKCUaD9xXE+hoHALlCrOM73sePUTgD/M3ClN/ylKjDzSXqloYWPgN5t4OK6oSl7wOUOMPBkyKbsSn6aQjYLvJ/RN6WB/lugc83rrb6P0wcgSV3Fb4CDQ2AkR9nrLd7d0dzbv2fq/f0ARfNylZJUgMQAAAAGYktHRABuAP8AAGHZRr4AAAAJcEhZcwAALiMAAC4jAXilP3YAAAAHdElNRQfnAhELEhgyPeVkAAAAGXRFWHRDb21tZW50AENyZWF0ZWQgd2l0aCBHSU1QV4EOFwAAAyVJREFUeNrt1rEJgDAURVGVNCmS2hS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119. {children}
  120. </FileTreePathContext.Provider>
  121. )
  122. export default {
  123. title: 'Editor / Source Editor',
  124. component: SourceEditor,
  125. decorators: [
  126. (Story: any) => (
  127. <div style={{ height: '90vh' }}>
  128. <Story />
  129. </div>
  130. ),
  131. ],
  132. }
  133. const settings = {
  134. fontSize: 12,
  135. fontFamily: 'monaco',
  136. lineHeight: 'normal',
  137. editorTheme: 'textmate',
  138. overallTheme: '',
  139. mode: 'default',
  140. autoComplete: true,
  141. autoPairDelimiters: true,
  142. trackChanges: true,
  143. syntaxValidation: false,
  144. }
  145. const permissions = {
  146. write: true,
  147. }
  148. export const Latex: Story = {
  149. decorators: [
  150. Story =>
  151. ScopeDecorator(Story, {
  152. mockCompileOnLoad: true,
  153. providers: {
  154. FileTreePathProvider,
  155. EditorOpenDocProvider: LatexEditorOpenDocProvider,
  156. },
  157. }),
  158. (Story, { globals }) => {
  159. // FIXME: useScope has no effect
  160. useScope({
  161. rootFolder: {
  162. name: 'rootFolder',
  163. id: 'root-folder-id',
  164. type: 'folder',
  165. children: [
  166. {
  167. name: 'example.tex.tex',
  168. id: 'example-doc-id',
  169. type: 'doc',
  170. selected: false,
  171. $$hashKey: 'object:89',
  172. },
  173. {
  174. name: 'frog.jpg',
  175. id: 'frog-image-id',
  176. type: 'file',
  177. linkedFileData: null,
  178. created: '2023-05-04T16:11:04.352Z',
  179. $$hashKey: 'object:108',
  180. },
  181. ],
  182. selected: false,
  183. },
  184. settings: {
  185. ...settings,
  186. overallTheme: globals.theme === 'default-' ? '' : globals.theme,
  187. },
  188. permissions,
  189. })
  190. useMeta({
  191. 'ol-showSymbolPalette': true,
  192. })
  193. return <Story />
  194. },
  195. ],
  196. }
  197. export const Markdown: Story = {
  198. decorators: [
  199. Story =>
  200. ScopeDecorator(Story, {
  201. mockCompileOnLoad: true,
  202. providers: {
  203. FileTreePathProvider,
  204. EditorOpenDocProvider: MarkdownEditorOpenDocProvider,
  205. },
  206. }),
  207. (Story, { globals }) => {
  208. // FIXME: useScope has no effect
  209. useScope({
  210. settings: {
  211. ...settings,
  212. overallTheme: globals.theme === 'default-' ? '' : globals.theme,
  213. },
  214. permissions,
  215. })
  216. return <Story />
  217. },
  218. ],
  219. }
  220. export const Visual: Story = {
  221. decorators: [
  222. Story =>
  223. ScopeDecorator(Story, {
  224. mockCompileOnLoad: true,
  225. providers: {
  226. FileTreePathProvider,
  227. EditorOpenDocProvider: LatexEditorOpenDocProvider,
  228. EditorPropertiesProvider: VisualEditorPropertiesProvider,
  229. },
  230. }),
  231. (Story, { globals }) => {
  232. // FIXME: useScope has no effect, so this does nothing
  233. useScope({
  234. settings: {
  235. ...settings,
  236. overallTheme: globals.theme === 'default-' ? '' : globals.theme,
  237. },
  238. permissions,
  239. })
  240. useMeta({
  241. 'ol-mathJaxPath': 'https://unpkg.com/mathjax@3.2.2/es5/tex-svg-full.js',
  242. 'ol-project_id': '63e21c07946dd8c76505f85a',
  243. })
  244. return <Story />
  245. },
  246. ],
  247. }
  248. export const Bibtex: Story = {
  249. decorators: [
  250. Story =>
  251. ScopeDecorator(Story, {
  252. mockCompileOnLoad: true,
  253. providers: {
  254. FileTreePathProvider,
  255. EditorOpenDocProvider: BibtexEditorOpenDocProvider,
  256. },
  257. }),
  258. (Story, { globals }) => {
  259. // FIXME: useScope has no effect
  260. useScope({
  261. settings: {
  262. ...settings,
  263. overallTheme: globals.theme === 'default-' ? '' : globals.theme,
  264. },
  265. permissions,
  266. })
  267. return <Story />
  268. },
  269. ],
  270. }
  271. const MAX_DOC_LENGTH = 2 * 1024 * 1024 // ol-maxDocLength
  272. const mockDoc = (content: string, changes: Array<Record<string, any>> = []) => {
  273. const mockShareJSDoc = {
  274. getText() {
  275. return content
  276. },
  277. on() {
  278. // do nothing
  279. },
  280. insert() {
  281. // do nothing
  282. },
  283. del() {
  284. // do nothing
  285. },
  286. emit: (...args: any[]) => {
  287. console.log(...args)
  288. },
  289. }
  290. return {
  291. doc_id: 'story-doc',
  292. getSnapshot: () => {
  293. return content
  294. },
  295. attachToCM6: (cm6: any) => {
  296. cm6.attachShareJs(mockShareJSDoc, MAX_DOC_LENGTH)
  297. },
  298. detachFromCM6: () => {
  299. // Do nothing
  300. },
  301. getType: () => {
  302. return 'history-ot'
  303. },
  304. on: () => {
  305. // Do nothing
  306. },
  307. off: () => {
  308. // Do nothing
  309. },
  310. setTrackChangesIdSeeds: () => {
  311. // Do nothing
  312. },
  313. setTrackChangesUserId: () => {
  314. // Do nothing
  315. },
  316. getTrackingChanges: () => {
  317. return true
  318. },
  319. getInflightOp: () => {
  320. return null
  321. },
  322. getPendingOp: () => {
  323. return null
  324. },
  325. ranges: new RangesTracker(changes, []),
  326. hasBufferedOps: () => false,
  327. }
  328. }
  329. const changes: Record<string, Array<Record<string, any>>> = {
  330. tex: [
  331. {
  332. id: '1',
  333. op: {
  334. i: 'Your introduction goes here! Simply start writing your document and use the Recompile button to view the updated PDF preview. Examples of commonly used commands and features are listed below, to help you get started.',
  335. p: 583,
  336. },
  337. meta: {
  338. user_id: '1',
  339. ts: new Date().toString(),
  340. },
  341. },
  342. ],
  343. md: [],
  344. bib: [],
  345. }
  346. const content = {
  347. tex: `\\documentclass{article}
  348. % Language setting
  349. % Replace \`english' with e.g. \`spanish' to change the document language
  350. \\usepackage[english]{babel}
  351. % Set page size and margins
  352. % Replace \`letterpaper' with \`a4paper' for UK/EU standard size
  353. \\usepackage[letterpaper,top=2cm,bottom=2cm,left=3cm,right=3cm,marginparwidth=1.75cm]{geometry}
  354. % Useful packages
  355. \\usepackage{amsmath}
  356. \\usepackage{graphicx}
  357. \\usepackage[colorlinks=true, allcolors=blue]{hyperref}
  358. \\title{Your Paper}
  359. \\author{You}
  360. \\begin{document}
  361. \\maketitle
  362. \\begin{abstract}
  363. Your abstract.
  364. \\end{abstract}
  365. \\section{Introduction}
  366. Your introduction goes here! Simply start writing your document and use the Recompile button to view the updated PDF preview. Examples of commonly used commands and features are listed below, to help you get started.
  367. Once you're familiar with the editor, you can find various project settings in the Overleaf menu, accessed via the button in the very top left of the editor. To view tutorials, user guides, and further documentation, please visit our \\href{https://www.overleaf.com/learn}{help library}, or head to our plans page to \\href{https://www.overleaf.com/user/subscription/plans}{choose your plan}.
  368. \\section{Some examples to get started}
  369. \\subsection{How to create Sections and Subsections}
  370. Simply use the section and subsection commands, as in this example document! With Overleaf, all the formatting and numbering is handled automatically according to the template you've chosen. If you're using Rich Text mode, you can also create new section and subsections via the buttons in the editor toolbar.
  371. \\subsection{How to include Figures}
  372. First you have to upload the image file from your computer using the upload link in the file-tree menu. Then use the includegraphics command to include it in your document. Use the figure environment and the caption command to add a number and a caption to your figure. See the code for Figure \\ref{fig:frog} in this section for an example.
  373. Note that your figure will automatically be placed in the most appropriate place for it, given the surrounding text and taking into account other figures or tables that may be close by. You can find out more about adding images to your documents in this help article on \\href{https://www.overleaf.com/learn/how-to/Including_images_on_Overleaf}{including images on Overleaf}.
  374. \\begin{figure}
  375. \\centering
  376. \\includegraphics[width=0.25\\linewidth]{frog.jpg}
  377. \\caption{This frog was uploaded via the file-tree menu.}\\label{fig:frog}
  378. \\end{figure}
  379. \\subsection{How to add Tables}
  380. Use the table and tabular environments for basic tables --- see Table~\\ref{tab:widgets}, for example. For more information, please see this help article on \\href{https://www.overleaf.com/learn/latex/tables}{tables}.
  381. \\begin{table}
  382. \\centering
  383. \\begin{tabular}{l|r}
  384. Item & Quantity \\\\\\hline
  385. Widgets & 42 \\\\
  386. Gadgets & 13
  387. \\end{tabular}
  388. \\caption{\\label{tab:widgets}An example table.}
  389. \\end{table}
  390. \\subsection{How to add Comments and Track Changes}
  391. Comments can be added to your project by highlighting some text and clicking \`\`Add comment'' in the top right of the editor pane. To view existing comments, click on the Review menu in the toolbar above. To reply to a comment, click on the Reply button in the lower right corner of the comment. You can close the Review pane by clicking its name on the toolbar when you're done reviewing for the time being.
  392. Track changes are available on all our \\href{https://www.overleaf.com/user/subscription/plans}{premium plans}, and can be toggled on or off using the option at the top of the Review pane. Track changes allow you to keep track of every change made to the document, along with the person making the change.
  393. \\subsection{How to add Lists}
  394. You can make lists with automatic numbering \\dots
  395. \\begin{enumerate}
  396. \\item Like this,
  397. \\item and like this.
  398. \\end{enumerate}
  399. \\dots or bullet points \\dots
  400. \\begin{itemize}
  401. \\item Like this,
  402. \\item and like this.
  403. \\end{itemize}
  404. \\subsection{How to write Mathematics}
  405. \\LaTeX{} is great at typesetting mathematics. Let $X_1, X_2, \\ldots, X_n$ be a sequence of independent and identically distributed random variables with $\\text{E}[X_i] = \\mu$ and $\\text{Var}[X_i] = \\sigma^2 < \\infty$, and let
  406. \\[S_n = \\frac{X_1 + X_2 + \\cdots + X_n}{n}
  407. = \\frac{1}{n}\\sum_{i}^{n} X_i\\]
  408. denote their mean. Then as $n$ approaches infinity, the random variables $\\sqrt{n}(S_n - \\mu)$ converge in distribution to a normal $\\mathcal{N}(0, \\sigma^2)$.
  409. \\subsection{How to change the margins and paper size}
  410. Usually the template you're using will have the page margins and paper size set correctly for that use-case. For example, if you're using a journal article template provided by the journal publisher, that template will be formatted according to their requirements. In these cases, it's best not to alter the margins directly.
  411. If however you're using a more general template, such as this one, and would like to alter the margins, a common way to do so is via the geometry package. You can find the geometry package loaded in the preamble at the top of this example file, and if you'd like to learn more about how to adjust the settings, please visit this help article on \\href{https://www.overleaf.com/learn/latex/page_size_and_margins}{page size and margins}.
  412. \\subsection{How to change the document language and spell check settings}
  413. Overleaf supports many different languages, including multiple different languages within one document.
  414. To configure the document language, simply edit the option provided to the babel package in the preamble at the top of this example project. To learn more about the different options, please visit this help article on \\href{https://www.overleaf.com/learn/latex/International_language_support}{international language support}.
  415. To change the spell check language, simply open the Overleaf menu at the top left of the editor window, scroll down to the spell check setting, and adjust accordingly.
  416. \\subsection{How to add Citations and a References List}
  417. You can simply upload a \\verb|.bib| file containing your BibTeX entries, created with a tool such as JabRef. You can then cite entries from it, like this: \\cite{greenwade93}. Just remember to specify a bibliography style, as well as the filename of the \\verb|.bib|. You can find a \\href{https://www.overleaf.com/help/97-how-to-include-a-bibliography-using-bibtex}{video tutorial here} to learn more about BibTeX.
  418. If you have an \\href{https://www.overleaf.com/user/subscription/plans}{upgraded account}, you can also import your Mendeley or Zotero library directly as a \\verb|.bib| file, via the upload menu in the file-tree.
  419. \\subsection{Good luck!}
  420. We hope you find Overleaf useful, and do take a look at our \\href{https://www.overleaf.com/learn}{help library} for more tutorials and user guides! Please also let us know if you have any feedback using the Contact Us link at the bottom of the Overleaf menu --- or use the contact form at \\url{https://www.overleaf.com/contact}.
  421. \\bibliographystyle{alpha}
  422. \\bibliography{sample}
  423. \\end{document}`,
  424. md: `# Heading
  425. This is **bold**
  426. This is _italic_`,
  427. bib: `@book{texbook,
  428. author = {Donald E. Knuth},
  429. year = {1986},
  430. title = {The {\\TeX} Book},
  431. publisher = {Addison-Wesley Professional}
  432. }
  433. @book{latex:companion,
  434. author = {Frank Mittelbach and Michel Gossens
  435. and Johannes Braams and David Carlisle
  436. and Chris Rowley},
  437. year = {2004},
  438. title = {The {\\LaTeX} Companion},
  439. publisher = {Addison-Wesley Professional},
  440. edition = {2}
  441. }
  442. @book{latex2e,
  443. author = {Leslie Lamport},
  444. year = {1994},
  445. title = {{\\LaTeX}: a Document Preparation System},
  446. publisher = {Addison Wesley},
  447. address = {Massachusetts},
  448. edition = {2}
  449. }
  450. @article{knuth:1984,
  451. title={Literate Programming},
  452. author={Donald E. Knuth},
  453. journal={The Computer Journal},
  454. volume={27},
  455. number={2},
  456. pages={97--111},
  457. year={1984},
  458. publisher={Oxford University Press}
  459. }
  460. @inproceedings{lesk:1977,
  461. title={Computer Typesetting of Technical Journals on {UNIX}},
  462. author={Michael Lesk and Brian Kernighan},
  463. booktitle={Proceedings of American Federation of
  464. Information Processing Societies: 1977
  465. National Computer Conference},
  466. pages={879--888},
  467. year={1977},
  468. address={Dallas, Texas}
  469. }
  470. `,
  471. }