atagen

malice

public
Star0
Watch0
d07bca5da4ae8096444c8411d8ca0c4bf01dee66
2
ssh://brewery@pls.lobotomise.me:33/atagen/malice.git
web/src/lib/ThemeSettings.svelteSvelte270 lines14.9 KB
1
<script lang="ts">
2
  import { onDestroy } from 'svelte';
3
  import EmojiText from './EmojiText.svelte';
4
  import { get } from 'svelte/store';
5
  import { THEMES, accent, customThemes, theme, themePreview, type ThemeId } from './appearance';
6
  import {
7
    MALICIOUS_PALETTE, THEME_COLOURS, captureTheme, isThemeColour, readThemeFile,
8
    themeDocument, themeStyle, type CustomTheme, type ThemeColour, type ThemeDocument
9
  } from './custom-themes';
10
11
  let draft: ThemeDocument | null = null;
12
  let editingId: CustomTheme['id'] | null = null;
13
  let selectedColour: ThemeColour = 'bg';
14
  let hexInput = '';
15
  let previewApp = false;
16
  let error = '';
17
  let notice = '';
18
  let fileInput: HTMLInputElement;
19
20
  $: selected = $customThemes.find((item) => item.id === $theme);
21
  $: selectedName = selected?.name ?? THEMES.find((item) => item.id === $theme)?.label ?? 'Theme';
22
  $: if (draft) hexInput = draft.colours[selectedColour];
23
  $: themePreview.set(previewApp ? draft : null);
24
25
  onDestroy(() => themePreview.set(null));
26
27
  function chooseTheme(id: ThemeId): void {
28
    draft = null;
29
    previewApp = false;
30
    themePreview.set(null);
31
    accent.set(null);
32
    theme.set(id);
33
    error = '';
34
    notice = '';
35
  }
36
37
  function editTheme(asNew: boolean): void {
38
    themePreview.set(null);
39
    previewApp = false;
40
    editingId = !asNew && selected ? selected.id : null;
41
    draft = selected && !asNew ? themeDocument(selected) : captureTheme(
42
      `${selectedName} custom`, $theme === 'malicious' ? MALICIOUS_PALETTE : selected?.palette
43
    );
44
    selectedColour = 'bg';
45
    error = '';
46
    notice = '';
47
  }
48
49
  function persistThemes(items: CustomTheme[]): void {
50
    localStorage.setItem('malice.customThemes', JSON.stringify(items));
51
    customThemes.set(items);
52
  }
53
54
  function saveTheme(doc: ThemeDocument, id: CustomTheme['id'] | null = null): void {
55
    try {
56
      const saved: CustomTheme = { ...themeDocument(doc), id: id ?? `custom:${crypto.randomUUID()}` };
57
      const items = get(customThemes);
58
      persistThemes(id ? items.map((item) => item.id === id ? saved : item) : [...items, saved]);
59
      chooseTheme(saved.id);
60
      notice = `${saved.name} saved on this device.`;
61
    } catch {
62
      error = 'Could not save the theme. Check that browser storage is available and has space.';
63
    }
64
  }
65
66
  function deleteTheme(): void {
67
    if (!selected) return;
68
    try {
69
      persistThemes($customThemes.filter((item) => item.id !== selected?.id));
70
      chooseTheme('dark');
71
      notice = 'Custom theme deleted.';
72
    } catch {
73
      error = 'Could not delete the theme from browser storage.';
74
    }
75
  }
76
77
  function exportTheme(doc: ThemeDocument): void {
78
    const blob = new Blob([JSON.stringify(themeDocument(doc), null, 2) + '\n'], { type: 'application/json' });
79
    const url = URL.createObjectURL(blob);
80
    const anchor = document.createElement('a');
81
    anchor.href = url;
82
    anchor.download = `${doc.name.replace(/[^\p{L}\p{N}_-]+/gu, '-').replace(/^-|-$/g, '') || 'theme'}.malice-theme.json`;
83
    anchor.click();
84
    setTimeout(() => URL.revokeObjectURL(url), 1000);
85
  }
86
87
  async function importTheme(event: Event): Promise<void> {
88
    const input = event.currentTarget as HTMLInputElement;
89
    const file = input.files?.[0];
90
    input.value = '';
91
    if (!file) return;
92
    error = '';
93
    notice = '';
94
    try {
95
      if (file.size > 65536) throw new Error('Theme files must be smaller than 64 KB.');
96
      const imported = readThemeFile(await file.text());
97
      draft = imported;
98
      editingId = null;
99
      previewApp = false;
100
      selectedColour = 'bg';
101
      notice = 'Theme loaded. Preview it and save to add it to your themes.';
102
    } catch (cause) {
103
      error = cause instanceof Error ? cause.message : 'Could not read the theme file.';
104
    }
105
  }
106
107
  function updateColour(value: string): void {
108
    if (!draft || !isThemeColour(value)) return;
109
    draft = { ...draft, colours: { ...draft.colours, [selectedColour]: value.toLowerCase() } };
110
    error = '';
111
  }
112
113
  function updateHex(): void {
114
    if (!isThemeColour(hexInput)) {
115
      error = 'Enter a hex colour with six digits, or eight digits including opacity.';
116
      return;
117
    }
118
    updateColour(hexInput);
119
  }
120
121
  function updateOpacity(value: string): void {
122
    if (!draft) return;
123
    const alpha = Math.round(Number(value) * 255 / 100);
124
    updateColour(draft.colours[selectedColour].slice(0, 7) + (alpha === 255 ? '' : alpha.toString(16).padStart(2, '0')));
125
  }
126
127
  function addToPalette(): void {
128
    if (!draft || draft.palette.length >= 64) return;
129
    const colour = draft.colours[selectedColour];
130
    if (!draft.palette.includes(colour)) draft = { ...draft, palette: [...draft.palette, colour] };
131
  }
132
133
  function removeFromPalette(): void {
134
    if (draft) draft = { ...draft, palette: draft.palette.filter((colour) => colour !== draft?.colours[selectedColour]) };
135
  }
136
</script>
137
138
<section aria-label="Theme">
139
  <h3 class="sec-h">Theme</h3>
140
  <div class="themes" role="radiogroup" aria-label="Theme">
141
    {#each THEMES as item (item.id)}
142
      <button type="button" role="radio" aria-checked={$theme === item.id} class="theme-opt" class:active={$theme === item.id}
143
        data-swatch={item.id} on:click={() => chooseTheme(item.id)}>
144
        <span class="swatch" aria-hidden="true"></span><EmojiText text={item.label} />
145
      </button>
146
    {/each}
147
    {#each $customThemes as item (item.id)}
148
      <button type="button" role="radio" aria-checked={$theme === item.id} class="theme-opt" class:active={$theme === item.id}
149
        on:click={() => chooseTheme(item.id)}>
150
        <span class="swatch" style:background={item.colours.bg} style:border-color={item.colours.accent} aria-hidden="true"></span>
151
        <span class="theme-name"><EmojiText text={item.name} /></span>
152
      </button>
153
    {/each}
154
  </div>
155
  <div class="toolbar">
156
    <button type="button" class="ghost-btn" on:click={() => editTheme(true)}>Create theme</button>
157
    {#if selected}<button type="button" class="ghost-btn" on:click={() => editTheme(false)}>Edit theme</button>{/if}
158
    <button type="button" class="ghost-btn" on:click={() => fileInput.click()}>Import theme</button>
159
    <button type="button" class="ghost-btn" disabled={draft !== null} on:click={() => exportTheme(captureTheme(selectedName, selected?.palette ?? ($theme === 'malicious' ? MALICIOUS_PALETTE : undefined)))}>Export theme</button>
160
    {#if selected}<button type="button" class="ghost-btn danger" on:click={deleteTheme}>Delete theme</button>{/if}
161
    <input class="file-input" type="file" accept=".json,application/json" aria-label="Import theme file" bind:this={fileInput} on:change={importTheme} />
162
  </div>
163
  {#if !draft}
164
    <div class="accent-row">
165
      <label for="accent-colour">Accent colour</label>
166
      <input id="accent-colour" type="color" value={$accent ?? captureTheme(selectedName).colours.accent.slice(0, 7)} on:input={(event) => accent.set(event.currentTarget.value)} />
167
      <button type="button" class="ghost-btn" disabled={$accent === null} on:click={() => accent.set(null)}>Use theme colour</button>
168
    </div>
169
  {/if}
170
171
  {#if draft}
172
    <div class="editor">
173
      <label class="field">Theme name<input type="text" maxlength="80" bind:value={draft.name} /></label>
174
      <label class="field">Colour scheme
175
        <select bind:value={draft.scheme}><option value="dark">Dark</option><option value="light">Light</option></select>
176
      </label>
177
      <div class="colour-roles" role="radiogroup" aria-label="Colour to edit">
178
        {#each THEME_COLOURS as [key, label] (key)}
179
          <button type="button" role="radio" aria-checked={selectedColour === key} class="role-opt" class:active={selectedColour === key}
180
            on:click={() => selectedColour = key}>
181
            <span class="swatch" style:background={draft.colours[key]} aria-hidden="true"></span>{label}
182
          </button>
183
        {/each}
184
      </div>
185
      <div class="colour-edit">
186
        <input type="color" aria-label="Pick colour" value={draft.colours[selectedColour].slice(0, 7)}
187
          on:input={(event) => updateColour(event.currentTarget.value + draft!.colours[selectedColour].slice(7))} />
188
        <label class="hex-field">Hex colour<input type="text" maxlength="9" spellcheck="false" bind:value={hexInput} on:change={updateHex} aria-invalid={!!error && !isThemeColour(hexInput)} /></label>
189
        <label class="opacity-field">Opacity
190
          <input type="range" min="0" max="100" step="1"
191
            value={Math.round(parseInt(draft.colours[selectedColour].slice(7) || 'ff', 16) / 255 * 100)}
192
            on:input={(event) => updateOpacity(event.currentTarget.value)} />
193
        </label>
194
      </div>
195
      <h4 class="sec-h">Palette</h4>
196
      <div class="palette" aria-label="Theme palette">
197
        {#each draft.palette as colour, index (`${index}-${colour}`)}
198
          <button type="button" class="palette-colour" style:background={colour} title={colour} aria-label={`Use ${colour}`}
199
            on:click={() => updateColour(colour)}></button>
200
        {/each}
201
      </div>
202
      <div class="toolbar">
203
        <button type="button" class="ghost-btn" disabled={draft.palette.length >= 64 || draft.palette.includes(draft.colours[selectedColour])} on:click={addToPalette}>Add colour</button>
204
        <button type="button" class="ghost-btn" disabled={!draft.palette.includes(draft.colours[selectedColour])} on:click={removeFromPalette}>Remove colour</button>
205
      </div>
206
      <label class="field">Sender name lightness
207
        <input type="range" min="0" max="100" step="1" bind:value={draft.nameLightness} />
208
      </label>
209
      <div class="theme-preview" style={themeStyle(draft)} aria-label="Theme preview">
210
        <div class="preview-heading"><span><EmojiText text={draft.name || 'Your theme'} /></span><span class="preview-muted">just now</span></div>
211
        <p>A little room to make your own. <span class="preview-link">A shared link</span></p>
212
        <div class="preview-status"><span class="preview-ok">Connected</span><span class="preview-warn">Warning</span><span class="preview-error">Error</span></div>
213
        <div class="preview-composer"><span class="preview-muted">Write a message…</span><span class="primary-btn" aria-hidden="true">Send</span></div>
214
      </div>
215
      <label class="preview-toggle"><input type="checkbox" bind:checked={previewApp} />Preview across the app</label>
216
      <div class="toolbar">
217
        <button type="button" class="primary-btn" disabled={!draft.name.trim() || !isThemeColour(hexInput)} on:click={() => draft && saveTheme(draft, editingId)}>Save theme</button>
218
        {#if editingId}<button type="button" class="ghost-btn" disabled={!draft.name.trim() || !isThemeColour(hexInput)} on:click={() => draft && saveTheme(draft)}>Save as new</button>{/if}
219
        <button type="button" class="ghost-btn" on:click={() => draft && exportTheme(draft)}>Export draft</button>
220
        <button type="button" class="ghost-btn" on:click={() => { draft = null; previewApp = false; error = ''; notice = ''; }}>Cancel</button>
221
      </div>
222
    </div>
223
  {/if}
224
  {#if error}<p class="theme-error" role="alert"><EmojiText text={error} /></p>{/if}
225
  {#if notice}<p class="theme-notice" role="status"><EmojiText text={notice} /></p>{/if}
226
</section>
227
228
<style>
229
  .sec-h { font-size: 12px; text-transform: uppercase; letter-spacing: 0.08em; color: var(--muted); margin: 0 0 6px; }
230
  .themes { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(130px, 100%), 1fr)); gap: 6px; }
231
  .theme-opt, .role-opt { display: flex; align-items: center; gap: 8px; min-width: 0; padding: 7px 8px; background: var(--bg-soft); border: 1px solid var(--border); border-radius: var(--r-md); color: var(--text); font-size: 13px; cursor: pointer; text-align: left; }
232
  .theme-opt.active, .role-opt.active { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent); }
233
  .theme-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
234
  .swatch { flex: none; width: 18px; height: 18px; border-radius: 50%; border: 1px solid var(--border); }
235
  [data-swatch='system'] .swatch { background: linear-gradient(135deg, #111218 50%, #f7f7fa 50%); }
236
  [data-swatch='dark'] .swatch { background: #111218; }
237
  [data-swatch='light'] .swatch { background: #f7f7fa; }
238
  [data-swatch='black'] .swatch { background: #000; }
239
  [data-swatch='nord'] .swatch { background: #2e3440; }
240
  [data-swatch='malicious'] .swatch { background: #1b2021; border-color: #5abfc9; box-shadow: inset -6px 0 #ffb852; }
241
  .toolbar { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 10px; }
242
  .file-input { display: none; }
243
  .accent-row { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; margin-top: 10px; font-size: 13px; }
244
  .accent-row label { flex: 1; }
245
  input[type='color'] { width: 40px; height: 34px; padding: 2px; border: 1px solid var(--border); border-radius: var(--r-sm); background: var(--panel); cursor: pointer; }
246
  .editor { margin-top: 14px; padding: 12px; border: 1px solid var(--border); border-radius: var(--r-md); }
247
  .field { display: flex; flex-direction: column; gap: 6px; font-size: 13px; color: var(--muted); margin-bottom: 12px; }
248
  input[type='text'], select { min-width: 0; width: 100%; min-height: var(--ctl-h); padding: 6px 8px; background: var(--bg-soft); border: 1px solid var(--border); border-radius: var(--r-sm); color: var(--text); font: inherit; }
249
  .colour-roles { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(140px, 100%), 1fr)); gap: 6px; max-height: 210px; overflow-y: auto; padding: 2px; }
250
  .colour-edit { display: flex; align-items: end; flex-wrap: wrap; gap: 10px; margin: 14px 0; }
251
  .hex-field, .opacity-field { display: flex; flex-direction: column; gap: 4px; font-size: 12px; color: var(--muted); }
252
  .hex-field { flex: 1; min-width: 100px; }
253
  .opacity-field { flex: 1; min-width: 100px; }
254
  input[type='range'] { width: 100%; accent-color: var(--accent); }
255
  .palette { display: flex; flex-wrap: wrap; gap: 6px; }
256
  .palette-colour { width: 28px; height: 28px; border: 1px solid var(--border); border-radius: var(--r-sm); cursor: pointer; }
257
  .toolbar + .field { margin-top: 14px; }
258
  .theme-preview { margin-top: 14px; padding: 12px; border: 1px solid var(--border); border-radius: var(--r-md); background: var(--bg); color: var(--text); font-size: 13px; }
259
  .preview-heading { display: flex; gap: 10px; flex-wrap: wrap; font-weight: 600; }
260
  .preview-muted { color: var(--muted); font-size: 12px; font-weight: 400; }
261
  .preview-link { color: var(--accent); }
262
  .preview-status { display: flex; gap: 10px; flex-wrap: wrap; }
263
  .preview-ok { color: var(--ok-text); }
264
  .preview-warn { color: var(--warn-text); background: var(--warn-bg); }
265
  .preview-error { color: var(--danger-text); background: var(--danger-bg); }
266
  .preview-composer { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px; margin-top: 12px; background: var(--panel); border: 1px solid var(--border); border-radius: var(--r-sm); }
267
  .preview-toggle { display: flex; align-items: center; gap: 6px; font-size: 13px; margin-top: 12px; }
268
  .theme-error { color: var(--danger-text); background: var(--danger-bg); padding: 8px; border-radius: var(--r-sm); }
269
  .theme-notice { color: var(--muted); font-size: 13px; }
270
</style>