-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.svelte
505 lines (476 loc) · 13.6 KB
/
App.svelte
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
<style>
/* Container element for App.svelte */
:global(body),
.main {
display: flex;
flex-direction: column;
flex-wrap: nowrap;
justify-content: flex-start;
align-items: stretch;
gap: 0.5em;
overflow: hidden;
max-height: 100%;
max-width: 100%;
}
.scroll {
overflow: auto;
flex-grow: 1;
/* Padding so the box shadows do not get cut off */
padding-bottom: 5px;
padding-right: 5px;
}
.tabs {
margin-bottom: calc(-0.5em);
max-width: max-content;
position: relative;
}
.keyboardbar {
margin: 0 -0.5em;
padding: 0.25em;
border-top: 1px solid var(--fg-color);
width: 100%;
position: absolute;
display: flex;
flex-direction: column;
justify-content: flex-start;
align-items: stretch;
gap: calc(0.25em + 3px);
}
.buttonbar {
min-height: max-content;
display: flex;
flex-direction: row;
flex-wrap: nowrap;
justify-content: flex-start;
align-items: center;
gap: 0.5ch;
overflow-x: auto;
background-color: var(--bg-color);
z-index: 19;
}
.bottombar {
margin: -0.5em;
padding: 0.25em;
border-top: 1px solid var(--fg-color);
border-bottom: 1px solid var(--fg-color);
min-height: max-content;
display: flex;
flex-direction: row;
flex-wrap: nowrap;
justify-content: flex-start;
align-items: center;
gap: 1ch;
position: relative;
}
.startmenu {
background: none;
position: absolute;
top: calc(-1 * var(--height));
width: 300px;
max-width: 100vw - 2em;
}
.status {
display: flex;
flex-direction: row;
gap: 1ch;
}
kbd {
padding: 0 0.5ch;
box-shadow: 1px 1px 0 0 var(--fg-color);
border: 1px solid var(--fg-color);
margin: 2px;
display: flex;
justify-content: center;
align-items: center;
font-family: monospace, monospace;
}
pre {
font-family: monospace, monospace;
white-space: pre;
margin-bottom: 1em;
tab-size: 4ch;
}
</style>
<script>
import Button from "./Button.svelte";
import CodeEditor from "./CodeEditor.svelte";
import Details from "./Details.svelte";
import Dialog from "./Dialog.svelte";
import FormulaBar from "./FormulaBar.svelte";
import SaveLoad from "./SaveLoad.svelte";
import Settings from "./Settings.svelte";
import ShyMenu from "./ShyMenu.svelte";
import Table from "./Table.svelte";
import Tabs from "./Tabs.svelte";
import { State, Sheet } from "./classes.svelte.js";
import { compressText } from "./compress.js";
import { evalDebounced, functions } from "./formula-functions.svelte.js";
import { debounce, replaceValues } from "./helpers.js";
import { keyboardHandler, keybindings } from "./keyboard.js";
let { urlData } = $props();
let globals = $state(
load(urlData) ?? new State([new Sheet("Sheet 1", 10, 10)]),
);
let table = $state();
let startHeight = $state(0);
let scrollArea = $state();
let imageData = $state();
// svelte-ignore state_referenced_locally
if (!urlData) {
globals.helpOpen = true;
globals.editorOpen = true;
}
function load(dataString) {
let data;
if (!dataString && window.location.hash) {
// TODO: Remove
// Temporary compatibility measure to not break old, uncompressed links
try {
data = JSON.parse(atob(window.location.hash.slice(1)));
} catch (e) {
return undefined;
}
} else if (!dataString) {
return undefined;
} else {
try {
data = JSON.parse(dataString);
} catch {
return undefined;
}
}
return State.load(data);
}
let dontSave = $state(false);
const save = debounce((data) => {
imageData = JSON.stringify(data, replaceValues);
if (dontSave) {
dontSave = false;
return;
}
// TODO: Save to local storage
const compressed = compressText(imageData);
try {
window.history.pushState(data, "", "#" + compressed);
} catch {
// TODO: Figure out a way to push state where values are unclonable (e.g.,
// HTMLElements)
window.history.pushState(undefined, "", "#" + compressed);
}
}, 1000);
$effect(() => {
save({
sheets: [
// Spreads necessary for reactivity
...globals.sheets.map((sheet) => ({
name: sheet.name,
widths: [...sheet.widths],
heights: [...sheet.heights],
// TODO: Transpose for better compression
cells: [
...sheet.cells.map((row) =>
row.map((cell) => ({
formula: cell.formula,
value: cell.get(),
})),
),
],
})),
],
formulaCode: globals.formulaCode,
});
});
Object.entries(window.localStorage)
.filter(([k, _]) => k.startsWith("settings."))
.map(([k, v]) => [k.replace(/^settings\./, ""), JSON.parse(v)])
.forEach(([k, v]) => {
globals.settings[k] = v;
});
$effect(() => {
Object.entries(globals.settings).forEach(([k, v]) => {
window.localStorage.setItem(`settings.${k}`, JSON.stringify(v));
});
});
// Focus the editor when the dialog is opened
// TODO: Is there a better place to put this?
// TODO: If the editor is open, but the text area is defocused, focus on the
// text area when the shortcut key is pressed
let editor = $state();
$effect(() => {
if (globals.editorOpen) {
editor?.focus();
}
});
let codeError = $state("");
$effect(() => {
evalDebounced(globals.formulaCode, (err) => {
codeError = "";
if (err != null) {
codeError = `Error: ${err.message}`;
// TODO: Show stack trace or line nubmer of problematic code
}
});
});
let innerHeight = $state(window.innerHeight);
let visualBottom = $state(window.visualViewport.height);
window.visualViewport.addEventListener("resize", () => {
visualBottom = window.visualViewport.height;
});
let showInputButtons = $derived(
navigator.maxTouchPoints > 1 && Math.abs(innerHeight - visualBottom) > 5,
);
$effect(() => {
// iOS scrolls the formula bar to the middle on focus, this counteracts that
// (if it happens to run after the keyboard is up - inconsistent)
if (showInputButtons && visualBottom) {
window.scrollTo({
top: 0,
behavior: "instant",
});
}
});
</script>
{#snippet printKey(key)}
{#if key == "arrowleft"}
←
{:else if key == "arrowright"}
→
{:else if key == "arrowup"}
↑
{:else if key == "arrowdown"}
↓
{:else if key.length > 1}
{key[0].toLocaleUpperCase() + key.slice(1)}
{:else}
{key}
{/if}
{/snippet}
<svelte:window
onkeydown={(e) => keyboardHandler(e, globals)}
onpopstate={(e) => {
if (e.state == null) {
return;
}
dontSave = true;
globals = Object.assign(State.load(e.state), {
currentSheetIndex: globals.currentSheetIndex,
mode: globals.mode,
helpOpen: globals.helpOpen,
editorOpen: globals.editorOpen,
imageOpen: globals.imageOpen,
elements: globals.elements,
pasteBuffer: globals.pasteBuffer,
});
}}
bind:innerHeight
/>
{#if navigator.maxTouchPoints <= 1}
<!-- Else float the bar above the virtual keyboard -->
<div>
<FormulaBar bind:globals bind:editor={globals.elements.formulaBar} />
</div>
{/if}
<div class="tabs">
<Tabs bind:globals bind:value={globals.currentSheetIndex} />
</div>
<div
bind:this={scrollArea}
class="scroll"
onpointerdown={(e) => {
// Only deselect if clicking outside of the table, and inside the scroll
// area
if (e.target != scrollArea) {
return;
}
globals.deselect();
}}
>
<!--
Set --width and --height default values because if Table is in a Dialog, it
will inherit the width and height of the dialog for table cells.
-->
<Table bind:globals bind:table --width="auto" --height="auto" />
</div>
<Dialog
bind:open={globals.editorOpen}
style="display: flex; flex-direction: column; align-items: stretch; overflow: hidden; gap: 0.25em;"
>
<CodeEditor bind:editor bind:code={globals.formulaCode} />
{#if codeError}
<p style="white-space: pre; overflow-x: auto; flex-shrink: 0;">
{codeError}
</p>
{/if}
</Dialog>
<Dialog top={150} left={150} bind:open={globals.imageOpen}>
<div
style="display: flex; flex-direction: column; gap: 0.5em; padding: 0.5em;"
>
<SaveLoad bind:globals {imageData} />
</div>
</Dialog>
<Dialog top={100} left={100} bind:open={globals.helpOpen}>
<div
style="display: flex; flex-direction: column; gap: 1.5em; padding: 0.5em;"
>
<p>
Code Grid is a spreadsheet built for programmers. You can extend it with
your own formula functions that execute in the browser. Formula functions
can create HTML elements.
</p>
<Details open>
{#snippet summary()}Tutorial{/snippet}
<p>Tutorial TODO</p>
<p>
Go to <a
href="https://github.com/jstrieb/code-grid#api-documentation"
target="_blank">the GitHub README</a
> for an introduction.
</p>
<p>
In the README, there are also several <a
href="https://github.com/jstrieb/code-grid#examples"
target="_blank">example spreadsheets</a
> showcasing some of Code Grid's unique capabilities.
</p>
</Details>
<Details>
{#snippet summary()}Keybindings{/snippet}
<ul style="margin-left: 1.5em; white-space: pre;">
{#each Object.entries(keybindings) as [combo, name]}
<li>
<div
style="display: flex; flex-direction: row; justify-content: flex-start; align-items: center; gap: 0.25ch;"
>
{#each combo.split("+") as key, i}
<kbd>{@render printKey(key)}</kbd
>{#if i < combo.split("+").length - 1}+{/if}
{/each} – {name}
</div>
</li>
{/each}
</ul>
</Details>
<Details>
{#snippet summary()}Formula functions{/snippet}
<ul style:list-style="none">
{#each Object.keys(functions).sort() as formula}
<li>
<Details>
{#snippet summary()}<span style:font-family="monospace, monospace"
>{formula}</span
>{/snippet}
<pre>{functions[formula]?.toString()}</pre>
</Details>
</li>
{/each}
</ul>
</Details>
<Details>
{#snippet summary()}Settings{/snippet}
<Settings bind:globals />
</Details>
</div>
</Dialog>
{#snippet insertTextButton(text)}
<Button
onpointerdown={(e) => {
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
}}
onpointerup={(e) => {
const textarea = document.activeElement;
textarea?.setRangeText?.(
text,
textarea.selectionStart,
textarea.selectionEnd,
"end",
);
// Event (with bubbling) is necessary for Svelte reactive variables to
// update to match the textarea value
textarea.dispatchEvent(new Event("input", { bubbles: true }));
}}
square
style="height: 2em;"
shadow="2px">{text}</Button
>
{/snippet}
{#if navigator.maxTouchPoints > 1}
<!-- Must set top instead of bottom for correct placement on iOS -->
<div class="keyboardbar" style:top="calc({visualBottom}px - 2.5em * 2)">
<FormulaBar bind:globals bind:editor={globals.elements.formulaBar} />
{#if showInputButtons}
<div class="buttonbar">
{@render insertTextButton("=")}
{@render insertTextButton("(")}
{@render insertTextButton(")")}
{@render insertTextButton("[")}
{@render insertTextButton("]")}
{@render insertTextButton("+")}
{@render insertTextButton("-")}
{@render insertTextButton("*")}
{@render insertTextButton("/")}
{@render insertTextButton('"')}
{@render insertTextButton("{")}
{@render insertTextButton("}")}
{@render insertTextButton(";")}
{@render insertTextButton(">")}
{@render insertTextButton("<")}
{@render insertTextButton(":")}
{@render insertTextButton("?")}
</div>
{/if}
</div>
{/if}
<div class="bottombar">
<ShyMenu>
{#snippet menu(builder)}
<div
class="startmenu"
bind:offsetHeight={startHeight}
style:--height="{startHeight}px"
>
{@render builder([
{
text: "Help & Settings",
onclick: () => (globals.helpOpen = !globals.helpOpen),
},
{
text: "Save and Load Spreadsheet as Image",
onclick: () => (globals.imageOpen = !globals.imageOpen),
},
{
text: "Code Editor",
onclick: () => (globals.editorOpen = !globals.editorOpen),
},
{
text: "New Spreadsheet",
onclick: () =>
Object.assign(document.createElement("a"), {
href: Object.assign(new URL(window.location), { hash: "" }),
target: "_blank",
}).click(),
},
{
text: "Code Grid Source Code",
onclick: () => {
Object.assign(document.createElement("a"), {
href: "https://github.com/jstrieb/code-grid",
target: "_blank",
}).click();
},
},
])}
</div>
{/snippet}
{#snippet clickable(handler)}
<Button square onclick={handler} style="height: 2em;">=</Button>
{/snippet}
</ShyMenu>
<div style="flex-grow: 1;"><!-- Spacer --></div>
<div class="status">
<span>{globals.keyQueue.join("")}</span>
<span>-- {globals.mode.toLocaleUpperCase()} --</span>
</div>
</div>