From ae9e7e17ed0a0e3fea951cb1d789f742cce94ea6 Mon Sep 17 00:00:00 2001 From: alina sireneva Date: Fri, 24 Jan 2025 08:08:45 +0300 Subject: [PATCH] feat: persist code --- packages/repl/src/components/editor/Editor.tsx | 15 +++++++++++++-- packages/repl/src/store/tabs.ts | 8 ++++++-- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/packages/repl/src/components/editor/Editor.tsx b/packages/repl/src/components/editor/Editor.tsx index 4096b77..9bd65b9 100644 --- a/packages/repl/src/components/editor/Editor.tsx +++ b/packages/repl/src/components/editor/Editor.tsx @@ -23,6 +23,8 @@ export const self = await tg.getMe() console.log(self) `.trimStart() +const LOCAL_STORAGE_PREFIX = 'repl:tab-content:' + function findChangedTab(a: EditorTab[], b: EditorTab[]) { const set = new Set(a.map(tab => tab.id)) for (const tab of b) { @@ -40,7 +42,6 @@ export default function Editor(props: EditorProps) { let editor: mEditor.IStandaloneCodeEditor | undefined const monacoTheme = useColorModeValue('latte', 'mocha') - // const monacoTheme = () => scheme() === 'dark' ? 'ayu-dark' : 'ayu-light' const modelsByTab = new Map() onMount(async () => { @@ -76,7 +77,8 @@ export default function Editor(props: EditorProps) { await setupMonaco() for (const tab of tabs()) { - const model = mEditor.createModel(tab.main ? DEFAULT_CODE : '', 'typescript', Uri.parse(`file:///${tab.id}.ts`)) + const storedCode = localStorage.getItem(LOCAL_STORAGE_PREFIX + tab.id) + const model = mEditor.createModel(storedCode ?? (tab.main ? DEFAULT_CODE : ''), 'typescript', Uri.parse(`file:///${tab.id}.ts`)) modelsByTab.set(tab.id, model) } @@ -86,6 +88,14 @@ export default function Editor(props: EditorProps) { props.onRun() }) + editor.onDidChangeModelContent(() => { + const currentTab = tabs().find(tab => tab.id === activeTab())! + const content = editor?.getModel()?.getValue() + if (!currentTab || !content) return + + localStorage.setItem(LOCAL_STORAGE_PREFIX + currentTab.id, content) + }) + return () => editor?.dispose() }) @@ -137,6 +147,7 @@ export default function Editor(props: EditorProps) { if (!changed) return modelsByTab.get(changed.id)?.dispose() modelsByTab.delete(changed.id) + localStorage.removeItem(LOCAL_STORAGE_PREFIX + changed.id) } })) diff --git a/packages/repl/src/store/tabs.ts b/packages/repl/src/store/tabs.ts index 0d1a4c5..3b695ad 100644 --- a/packages/repl/src/store/tabs.ts +++ b/packages/repl/src/store/tabs.ts @@ -1,3 +1,4 @@ +import { persistentAtom } from '@nanostores/persistent' import { atom } from 'nanostores' export interface EditorTab { @@ -6,12 +7,15 @@ export interface EditorTab { main: boolean } -export const $tabs = atom([ +export const $tabs = persistentAtom('repl:tabs', [ { id: 'main', fileName: 'main.ts', main: true, }, -]) +], { + encode: JSON.stringify, + decode: JSON.parse, +}) export const $activeTab = atom('main')