|
| 1 | +import { forwardRef, useEffect, useImperativeHandle, useState } from 'react'; |
| 2 | +import { useColorMode } from '@docusaurus/theme-common'; |
| 3 | + |
| 4 | +import { |
| 5 | + compressToEncodedURIComponent, |
| 6 | + decompressFromEncodedURIComponent, |
| 7 | +} from 'lz-string'; |
| 8 | + |
| 9 | +import { createTypeScriptSandbox } from '@typescript/sandbox'; |
| 10 | + |
| 11 | +import styles from './editor.module.scss'; |
| 12 | +import toast from 'react-hot-toast'; |
| 13 | + |
| 14 | +export interface EditorRef { |
| 15 | + getText: () => string; |
| 16 | + setText: (text: string) => void; |
| 17 | + cleanup: () => void; |
| 18 | +} |
| 19 | + |
| 20 | +export interface EditorProps { |
| 21 | + initialText: string; |
| 22 | + dts?: Record<string, string>; |
| 23 | +} |
| 24 | + |
| 25 | +export const Editor = forwardRef<EditorRef, EditorProps>( |
| 26 | + ({ initialText, dts }: EditorProps, ref) => { |
| 27 | + dts ??= {}; |
| 28 | + |
| 29 | + const [sandbox, setSandbox] = |
| 30 | + useState<ReturnType<typeof createTypeScriptSandbox>>(null); |
| 31 | + |
| 32 | + const [ts, setTs] = useState<typeof import('typescript')>(null); |
| 33 | + const [monaco, setMonaco] = useState<typeof import('monaco-editor')>(null); |
| 34 | + |
| 35 | + const { colorMode } = useColorMode(); |
| 36 | + |
| 37 | + useImperativeHandle(ref, () => ({ |
| 38 | + getText: () => sandbox?.getText(), |
| 39 | + setText: (text: string) => { |
| 40 | + sandbox?.setText(text); |
| 41 | + |
| 42 | + // clear the hash, as its not representative of the current state |
| 43 | + window.history.pushState(null, null, '#'); |
| 44 | + }, |
| 45 | + cleanup: () => { |
| 46 | + sandbox.getModel().dispose(); |
| 47 | + sandbox.editor.dispose; |
| 48 | + }, |
| 49 | + })); |
| 50 | + |
| 51 | + useEffect(() => { |
| 52 | + (async () => { |
| 53 | + const [ts, monaco] = (await Promise.all([ |
| 54 | + import('typescript'), |
| 55 | + import('monaco-editor'), |
| 56 | + ])) as [typeof import('typescript'), typeof import('monaco-editor')]; |
| 57 | + |
| 58 | + setTs(ts); |
| 59 | + setMonaco(monaco); |
| 60 | + })(); |
| 61 | + }, []); |
| 62 | + |
| 63 | + useEffect(() => { |
| 64 | + (async () => { |
| 65 | + if (!ts || !monaco) { |
| 66 | + return; |
| 67 | + } |
| 68 | + |
| 69 | + const contents = window.location.hash |
| 70 | + ? decompressFromEncodedURIComponent(window.location.hash.slice(1)) |
| 71 | + : initialText; |
| 72 | + |
| 73 | + const sandbox = createTypeScriptSandbox( |
| 74 | + { |
| 75 | + domID: 'monaco-editor-embed', |
| 76 | + filetype: 'ts', |
| 77 | + text: contents, |
| 78 | + acquireTypes: false, |
| 79 | + monacoSettings: { |
| 80 | + automaticLayout: true, |
| 81 | + }, |
| 82 | + }, |
| 83 | + monaco, |
| 84 | + ts |
| 85 | + ); |
| 86 | + |
| 87 | + Object.keys(dts).forEach((path) => { |
| 88 | + // console.log('Adding', path, 'code:', dts[path]); |
| 89 | + sandbox.languageServiceDefaults.addExtraLib(dts[path], path); |
| 90 | + }); |
| 91 | + |
| 92 | + setSandbox(sandbox); |
| 93 | + |
| 94 | + return () => { |
| 95 | + console.log('Disposing sandbox'); |
| 96 | + sandbox.getModel().dispose(); |
| 97 | + sandbox.editor.dispose(); |
| 98 | + }; |
| 99 | + })(); |
| 100 | + }, [ts, monaco]); |
| 101 | + |
| 102 | + useEffect(() => { |
| 103 | + if (colorMode === 'dark') { |
| 104 | + monaco?.editor?.setTheme('vs-dark'); |
| 105 | + } else { |
| 106 | + monaco?.editor?.setTheme('vs-light'); |
| 107 | + } |
| 108 | + }, [colorMode, monaco]); |
| 109 | + |
| 110 | + useEffect(() => { |
| 111 | + if (!sandbox) { |
| 112 | + return; |
| 113 | + } |
| 114 | + |
| 115 | + const listener = (event: React.KeyboardEvent) => { |
| 116 | + if ((event.ctrlKey || event.metaKey) && event.key === 's') { |
| 117 | + // Encode's the editor contents and sets it as the hash |
| 118 | + const uriComponent = compressToEncodedURIComponent(sandbox.getText()); |
| 119 | + |
| 120 | + if (!window.history?.pushState) { |
| 121 | + toast.error( |
| 122 | + 'Your browser does not support this feature - unable to save.' |
| 123 | + ); |
| 124 | + } else { |
| 125 | + window.history.pushState(null, null, `#${uriComponent}`); |
| 126 | + } |
| 127 | + |
| 128 | + // Copies new URL to clipboard |
| 129 | + if (navigator.clipboard) { |
| 130 | + navigator.clipboard.writeText(window.location.href); |
| 131 | + toast.success('Saved and copied to clipboard'); |
| 132 | + } |
| 133 | + |
| 134 | + // Prevent the default save dialog |
| 135 | + event.preventDefault(); |
| 136 | + } |
| 137 | + }; |
| 138 | + |
| 139 | + document.addEventListener('keydown', listener as any); |
| 140 | + |
| 141 | + return () => { |
| 142 | + document.removeEventListener('keydown', listener as any); |
| 143 | + }; |
| 144 | + }, [sandbox]); |
| 145 | + |
| 146 | + return ( |
| 147 | + <> |
| 148 | + {!sandbox ? <div id="loader">Loading...</div> : null} |
| 149 | + <div |
| 150 | + id="monaco-editor-embed" |
| 151 | + className={styles.editor} |
| 152 | + style={{ height: '800px' }} |
| 153 | + /> |
| 154 | + {/* TODO: Revisit this later. */} |
| 155 | + {/* <div style={{ position: 'absolute', bottom: '2rem', right: '2rem' }}> |
| 156 | + <button>View on TS Playground</button> |
| 157 | + </div> */} |
| 158 | + </> |
| 159 | + ); |
| 160 | + } |
| 161 | +); |
0 commit comments