|
1 | 1 | <script lang="ts"> |
2 | | - import { onMount } from "svelte"; |
3 | 2 | import CodeMirror from "svelte-codemirror-editor"; |
4 | 3 | import { keymap } from "@codemirror/view"; |
5 | 4 | import { defaultKeymap, history, historyKeymap } from "@codemirror/commands"; |
|
16 | 15 |
|
17 | 16 | $: inactive = $sessionState === "closed" || $sessionState === "readonly"; |
18 | 17 |
|
19 | | - let value = `-- Welcome to the GLua Editor! |
| 18 | + const STORAGE_KEY = "glua-editor-content"; |
| 19 | + const DEFAULT_CONTENT = `-- Welcome to the GLua Editor! |
20 | 20 |
|
21 | 21 | function hello() |
22 | 22 | print("Hello from the editor!") |
|
25 | 25 | hello() |
26 | 26 | `; |
27 | 27 |
|
28 | | - onMount(() => { |
29 | | - const savedContent = localStorage.getItem("glua-editor-content"); |
30 | | - if (savedContent && savedContent !== "undefined") { |
31 | | - value = savedContent; |
32 | | - } |
33 | | - }); |
| 28 | + // Read synchronously so CodeMirror sees the correct initial value on mount. |
| 29 | + // Doing this in onMount races with CodeMirror's own init and can also let |
| 30 | + // the editor's first on:change overwrite localStorage with the default |
| 31 | + function loadInitialContent(): string { |
| 32 | + const saved = localStorage.getItem(STORAGE_KEY); |
| 33 | + return saved && saved !== "undefined" ? saved : DEFAULT_CONTENT; |
| 34 | + } |
| 35 | +
|
| 36 | + let value = loadInitialContent(); |
| 37 | +
|
| 38 | + // Driven by the bound `value` rather than CodeMirror's on:change event, |
| 39 | + // which can fire with a transient empty string during init and wipe the |
| 40 | + // saved script before the user ever types |
| 41 | + $: if (typeof value === "string") localStorage.setItem(STORAGE_KEY, value); |
34 | 42 |
|
35 | 43 | function runScript() { |
36 | 44 | if (!socket || socket.readyState !== WebSocket.OPEN) return; |
@@ -59,7 +67,6 @@ hello() |
59 | 67 | keymap.of([...defaultKeymap, ...historyKeymap, {key: "Ctrl-Enter", run: () => { runScript(); return true; }}]), |
60 | 68 | gluaTheme |
61 | 69 | ]} |
62 | | - on:change={(e) => localStorage.setItem("glua-editor-content", e.detail.value)} |
63 | 70 | /> |
64 | 71 | </div> |
65 | 72 | <div id="editor-footer"> |
|
0 commit comments