| 13 | }; |
| 14 | |
| 15 | function MonacoContainer({ |
| 16 | config, setValue, setError, monaco, schema, editorCallback, size, dark, |
| 17 | }) { |
| 18 | const [editor, setEditor] = React.useState<any>(null); |
| 19 | const [model, setModel] = React.useState<any>(null); |
| 20 | const [initialized, setInitialized] = React.useState(false); |
| 21 | const { codeFontFamily } = React.useContext(ComponentsContext); |
| 22 | |
| 23 | React.useEffect(() => { |
| 24 | if (!monaco) return; |
| 25 | const interval = setInterval(() => { |
| 26 | monaco.editor.remeasureFonts(); |
| 27 | }, 1000); |
| 28 | return () => clearInterval(interval); // eslint-disable-line consistent-return |
| 29 | }, [monaco]); |
| 30 | |
| 31 | React.useEffect(() => { |
| 32 | const listener = () => { |
| 33 | if (!editor) return; |
| 34 | editor.layout(); |
| 35 | }; |
| 36 | window.addEventListener('resize', listener); |
| 37 | return () => window.removeEventListener('resize', listener); |
| 38 | }, [editor]); |
| 39 | React.useEffect(() => { |
| 40 | if (!editor) return; |
| 41 | editor.layout(); |
| 42 | }, [size]); |
| 43 | React.useEffect(() => { |
| 44 | if (!editor || !model) return; |
| 45 | const decoration = editor.createDecorationsCollection(); |
| 46 | const updateDecoration = () => { |
| 47 | const found = model.findMatches("'[hidden]'", true, false, true, '', true).map((i) => i.range); |
| 48 | decoration.set(found.map((range) => ({ range, options: { inlineClassName: 'decoration-hide' } }))); |
| 49 | }; |
| 50 | updateDecoration(); |
| 51 | const disposable = editor.onDidChangeModelContent(() => { |
| 52 | const val = editor.getValue({ lineEnding: '\n', preserveBOM: false }); |
| 53 | updateDecoration(); |
| 54 | try { |
| 55 | const loaded = yaml.load(val); |
| 56 | schema(loaded); |
| 57 | setValue(val); |
| 58 | setError(''); |
| 59 | } catch (err) { |
| 60 | setError(err.message); |
| 61 | } |
| 62 | }); |
| 63 | return () => disposable.dispose(); // eslint-disable-line |
| 64 | }, [editor, model, setValue, setError, schema]); |
| 65 | const initializeEditor = React.useCallback((element) => { |
| 66 | if (!element || initialized) return; |
| 67 | setInitialized(true); |
| 68 | // eslint-disable-next-line |
| 69 | const model = monaco.editor.createModel(config, 'yaml', monaco.Uri.parse('hydro://system/setting.yaml')); |
| 70 | setModel(model); |
| 71 | const e = monaco.editor.create(element, { |
| 72 | theme: dark ? 'vs-dark' : 'vs-light', |