web/src/components/form/EditableTitle.svelte
98 lines · 2101 bytes
1<script lang="ts">
2 import { onMount } from 'svelte';
3
4 let title = $state('Inventory');
5 let draft = $state('Inventory');
6 let editing = $state(false);
7 let inputEl: HTMLInputElement | undefined = $state();
8
9 onMount(() => {
10 const stored = localStorage.getItem('userTitle');
11 if (stored) {
12 title = stored;
13 draft = stored;
14 }
15 });
16
17 function startEditing() {
18 draft = title;
19 editing = true;
20 requestAnimationFrame(() => inputEl?.select());
21 }
22
23 function save() {
24 const trimmed = draft.trim() || title;
25 localStorage.setItem('userTitle', trimmed);
26 title = trimmed;
27 draft = trimmed;
28 editing = false;
29 }
30
31 function cancel() {
32 draft = title;
33 editing = false;
34 }
35
36 function handleKeydown(event: KeyboardEvent) {
37 if (event.key === 'Enter') {
38 event.preventDefault();
39 save();
40 }
41 if (event.key === 'Escape') cancel();
42 }
43</script>
44
45<div>
46 {#if editing}
47 <input
48 bind:this={inputEl}
49 bind:value={draft}
50 class="title-input"
51 onkeydown={handleKeydown}
52 onblur={save}
53 aria-label="Inventory name"
54 />
55 {:else}
56 <button class="title-display" onclick={startEditing}>
57 <h2>{title}</h2>
58 </button>
59 {/if}
60 <small>Click the title to edit your inventory name</small>
61</div>
62
63<style>
64 h2 {
65 font-family: var(--font-subtitle);
66 font-weight: bold;
67 font-size: var(--text-4xl);
68 margin: 0;
69 color: var(--accent-3-text);
70 }
71 .title-display {
72 all: unset;
73 cursor: pointer;
74 display: block;
75 padding: var(--space-xs);
76 border-bottom: 2px solid transparent;
77 &:hover,
78 &:focus-visible {
79 border-bottom: 2px solid var(--accent-3);
80 }
81 }
82 .title-input {
83 font-family: var(--font-subtitle);
84 font-weight: bold;
85 font-size: var(--text-4xl);
86 color: var(--accent-3-text);
87 background: transparent;
88 border: none;
89 border-bottom: 2px solid var(--accent-3);
90 outline: none;
91 padding: var(--space-xs);
92 width: 100%;
93 }
94 small {
95 font-size: var(--text-sm);
96 opacity: var(--opacity-dim);
97 }
98</style>