atagen

malice

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