Update the browser, editor, settings, and installer

This commit is contained in:
Knotty Wyvern
2026-10-12 14:46:21 -07:00
parent 909894b9c8
commit f6eaa52949
163 changed files with 146260 additions and 534 deletions
+112 -23
View File
@@ -1,20 +1,64 @@
<script lang="ts">
import { onMount } from 'svelte';
import { onMount, onDestroy } from 'svelte';
import { invoke, isTauri } from '@tauri-apps/api/core';
import { customThemes, installTheme, parseCustomTheme, removeTheme, type CustomTheme } from './customThemes';
import IconButton from '$lib/ui/IconButton.svelte';
import { APPEARANCE_KEY, DEFAULT_APPEARANCE, parseAppearance, normalizeAppearance, saveAppearance, type Appearance, type ThemeName } from './appearance';
import Icon from '$lib/ui/Icon.svelte';
import { showActionMenu } from '$lib/ui/managedActionMenu';
import { saveBackgroundImage, removeBackgroundImage } from './backgroundImages';
import { APPEARANCE_KEY, DEFAULT_APPEARANCE, BACKGROUND_POSITIONS, BACKGROUND_SIZES, parseAppearance, normalizeAppearance, saveAppearance, exportAppearanceTheme, type Appearance, type ThemeName } from './appearance';
let appearance = $state<Appearance>({ ...DEFAULT_APPEARANCE });
let error = $state('');
let status = $state('');
let exporting = $state(false);
let backgroundInput: HTMLInputElement;
let backgroundRevision = 0;
let installed = $state<CustomTheme[]>([]);
let themeInput: HTMLInputElement;
let closePicker = () => {};
const themes = $derived([{ id: 'default', name: 'RuneStone' }, { id: 'claude', name: 'Claude' }, { id: 'sakura', name: 'Sakura' }, ...installed.map(theme => ({ id: `custom:${theme.id}`, name: theme.name }))]);
onDestroy(() => closePicker());
function picker(event: MouseEvent, mode = false) {
closePicker();
const anchor = event.currentTarget as HTMLButtonElement;
const bounds = anchor.getBoundingClientRect();
const choices = mode ? [{ id: 'light', name: 'Light' }, { id: 'dark', name: 'Dark' }] : themes;
closePicker = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: mode ? 'Appearance' : 'Color theme', parent: anchor.closest('dialog') ?? undefined,
items: choices.map(choice => ({ label: choice.name, radio: true, checked: choice.id === (mode ? appearance.mode : appearance.theme),
run: () => change(mode ? { ...appearance, mode: choice.id as 'light' | 'dark' } : { ...appearance, theme: choice.id as ThemeName }) })) }).close;
}
const positionLabels = ['Center', 'Top left', 'Top center', 'Top right', 'Center left', 'Center right', 'Bottom left', 'Bottom center', 'Bottom right'];
const sizeLabels = ['Fill', 'Fit', 'Actual size'];
function backgroundPicker(event: MouseEvent, field: 'position' | 'size') {
closePicker();
const anchor = event.currentTarget as HTMLButtonElement;
const bounds = anchor.getBoundingClientRect();
const values = field === 'position' ? BACKGROUND_POSITIONS : BACKGROUND_SIZES;
const labels = field === 'position' ? positionLabels : sizeLabels;
closePicker = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: field === 'position' ? 'Image position' : 'Image size', parent: anchor.closest('dialog') ?? undefined,
items: values.map((value, index) => ({ label: labels[index], radio: true, checked: value === appearance.newTabBackground?.[field],
run: () => change({ ...appearance, newTabBackground: { ...appearance.newTabBackground, [field]: value } }) })) }).close;
}
onMount(() => {
const read = () => { try { installed = customThemes(); appearance = parseAppearance(localStorage.getItem(APPEARANCE_KEY)); } catch { error = 'Could not read appearance settings.'; } };
read(); window.addEventListener('storage', read); window.addEventListener('focus', read);
return () => { window.removeEventListener('storage', read); window.removeEventListener('focus', read); };
});
function change(next: Appearance) {
try { saveAppearance(next); appearance = normalizeAppearance(next); error = ''; }
catch { error = 'Could not save appearance settings.'; }
try { saveAppearance(next); appearance = normalizeAppearance(next); error = ''; return true; }
catch { error = 'Could not save appearance settings.'; return false; }
}
function changeOverlay(input: HTMLInputElement) {
const percent = input.valueAsNumber;
if (!Number.isFinite(percent)) return;
change({ ...appearance, newTabBackground: { ...appearance.newTabBackground, overlay: Math.round(Math.max(-100, Math.min(100, percent))) / 100 } });
}
async function removeBackground() {
backgroundRevision++;
const old = appearance.newTabBackground?.imageId;
if (change({ ...appearance, newTabBackground: undefined }) && old) {
try { await removeBackgroundImage(old); } catch { error = 'Could not remove the saved image from storage.'; }
}
}
async function importTheme(file?: File) {
if (!file) return;
@@ -26,30 +70,50 @@
} catch (reason) { error = String(reason); }
finally { themeInput.value = ''; }
}
function exportTemplate() {
const palette = (mode: 'light' | 'dark') => ({ bg: mode === 'dark' ? '#141414' : '#ffffff', text: mode === 'dark' ? '#e6e6e6' : '#202020', accent: mode === 'dark' ? '#82aaff' : '#315fb3' });
const selected = installed.find(item => `custom:${item.id}` === appearance.theme);
const source = selected ?? { schema: 1, id: 'my-theme', name: 'My theme', light: palette('light'), dark: palette('dark') };
const url = URL.createObjectURL(new Blob([JSON.stringify(source, null, 2) + '\n'], { type: 'application/json' }));
const link = document.createElement('a'); link.href = url; link.download = source.id + '.json'; link.click();
setTimeout(() => URL.revokeObjectURL(url), 1000);
async function importBackground(file?: File) {
if (!file) return;
const revision = ++backgroundRevision;
try {
if (!['image/png', 'image/jpeg', 'image/webp', 'image/gif'].includes(file.type)) throw new Error('Choose a PNG, JPEG, WebP, or GIF image.');
const imageId = await saveBackgroundImage(file);
if (revision !== backgroundRevision) { await removeBackgroundImage(imageId); return; }
const old = appearance.newTabBackground?.imageId;
if (change({ ...appearance, newTabBackground: { ...appearance.newTabBackground, image: undefined, imageId, overlay: appearance.newTabBackground?.overlay ?? 0 } })) {
if (old) await removeBackgroundImage(old);
} else await removeBackgroundImage(imageId);
} catch (reason) { if (revision === backgroundRevision) error = String(reason); }
finally { if (revision === backgroundRevision) backgroundInput.value = ''; }
}
async function exportTemplate() {
if (exporting) return;
exporting = true; error = ''; status = '';
try {
const source = exportAppearanceTheme(appearance.theme);
const contents = JSON.stringify(source, null, 2) + '\n';
if (isTauri()) {
const path = await invoke<string | null>('theme_export', { contents, defaultName: source.id + '.json' });
status = path ? `Theme saved to ${path}` : 'Export canceled.';
} else {
const url = URL.createObjectURL(new Blob([contents], { type: 'application/json' }));
const link = document.createElement('a'); link.href = url; link.download = source.id + '.json';
document.body.append(link); link.click(); link.remove();
setTimeout(() => URL.revokeObjectURL(url), 1000);
status = 'Theme download started.';
}
} catch (reason) { error = `Could not export the theme: ${String(reason)}`; }
finally { exporting = false; }
}
</script>
<h2>Appearance</h2>
<p>Choose a color theme and a light or dark appearance.</p>
<div class="card">
<label><span>Color theme</span><select aria-label="Color theme" value={appearance.theme} onchange={event => change({ ...appearance, theme: event.currentTarget.value as ThemeName })}>
<option value="default">RuneStone</option><option value="claude">Claude</option><option value="sakura">Sakura</option>
{#each installed as theme}<option value={`custom:${theme.id}`}>{theme.name}</option>{/each}
</select></label>
<label><span>Appearance</span><select aria-label="Appearance" disabled={appearance.theme === 'sakura'} value={appearance.mode} onchange={event => change({ ...appearance, mode: event.currentTarget.value as 'light' | 'dark' })}>
<option value="light">Light</option><option value="dark">Dark</option>
</select></label>
<div class="setting-row"><span>Color theme</span><button class="picker" aria-label="Color theme" aria-haspopup="menu" onclick={event => picker(event)}>{themes.find(theme => theme.id === appearance.theme)?.name ?? 'RuneStone'}<Icon icon="chevron-down" /></button></div>
<div class="setting-row"><span>Appearance</span><button class="picker" aria-label="Appearance" aria-haspopup="menu" disabled={appearance.theme === 'sakura'} onclick={event => picker(event, true)}>{appearance.mode === 'light' ? 'Light' : 'Dark'}<Icon icon="chevron-down" /></button></div>
</div>
<div class="theme-actions">
<input bind:this={themeInput} type="file" accept=".json,application/json" aria-label="Theme JSON file" hidden onchange={event => { void importTheme(event.currentTarget.files?.[0]); }} />
<button onclick={() => themeInput.click()}>Install theme</button>
<button onclick={exportTemplate}>Export theme template</button>
<button disabled={exporting} onclick={() => void exportTemplate()}>{exporting ? 'Exporting…' : 'Export theme template'}</button>
{#if appearance.theme.startsWith('custom:')}<IconButton icon="trash" label="Remove custom theme" onclick={() => {
try { removeTheme(appearance.theme.slice(7)); installed = customThemes(); change({ ...appearance, theme: 'default' }); }
catch { error = 'Could not remove this theme.'; }
@@ -57,17 +121,42 @@
</div>
<p>Edit the exported JSON colors, then choose Install theme. Each theme has light and dark colors.</p>
{#if appearance.theme === 'sakura'}<p>Sakura uses a light appearance.</p>{/if}
<h3>Background image</h3>
<div class="background-preview" aria-label="Background image preview"><span>Background</span></div>
{#if appearance.newTabBackground}
<div class="card">
<div class="setting-row"><span>Image position</span><button class="picker" aria-label="Image position" aria-haspopup="menu" onclick={event => backgroundPicker(event, 'position')}>{positionLabels[BACKGROUND_POSITIONS.indexOf(appearance.newTabBackground.position ?? 'center')]}<Icon icon="chevron-down" /></button></div>
<div class="setting-row"><span>Image size</span><button class="picker" aria-label="Image size" aria-haspopup="menu" onclick={event => backgroundPicker(event, 'size')}>{sizeLabels[BACKGROUND_SIZES.indexOf(appearance.newTabBackground.size ?? 'cover')]}<Icon icon="chevron-down" /></button></div>
<div class="setting-row"><span>Image overlay</span><div class="overlay-controls"><input type="range" aria-label="Image overlay" min="-100" max="100" value={Math.round((appearance.newTabBackground.overlay ?? 0) * 100)} oninput={event => changeOverlay(event.currentTarget)} /><label class="overlay-value"><input type="number" aria-label="Image overlay percentage" min="-100" max="100" step="1" value={Math.round((appearance.newTabBackground.overlay ?? 0) * 100)} oninput={event => changeOverlay(event.currentTarget)} onblur={event => { event.currentTarget.value = String(Math.round((appearance.newTabBackground?.overlay ?? 0) * 100)); }} /><span>%</span></label></div></div>
</div>
<p>Move left to lighten the image or right to darken it.</p>
{/if}
<div class="theme-actions">
<input bind:this={backgroundInput} type="file" accept="image/png,image/jpeg,image/webp,image/gif" aria-label="Background image file" hidden onchange={event => void importBackground(event.currentTarget.files?.[0])} />
<button onclick={() => backgroundInput.click()}>Choose image…</button>
{#if appearance.newTabBackground}<button onclick={() => void removeBackground()}>Remove image</button>{/if}
<button disabled={!appearance.newTabBackground} onclick={() => void removeBackground()}>Reset background</button>
</div>
<p>PNG, JPEG, WebP, or GIF, up to 50 MiB. The image applies to new tabs on this device.</p>
{#if status}<p role="status">{status}</p>{/if}
{#if error}<p role="alert">{error}</p>{/if}
<style>
h2{margin:0;font-size:var(--rs-settings-heading-size);color:var(--rs-text-strong)}
p{color:var(--rs-text-dim);font-size:var(--rs-settings-description-size);line-height:1.5}
.card{padding:0 var(--rs-settings-row-padding);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg-elevated)}
label{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:var(--rs-settings-gap);padding:var(--rs-settings-row-padding) 0}
label+label{border-top:1px solid var(--rs-border)}
select{min-height:var(--rs-settings-control-height);max-width:100%;padding:4px 8px;background:var(--rs-bg);color:var(--rs-text);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius)}
select:focus-visible{outline:2px solid var(--rs-accent);outline-offset:2px}
label,.setting-row{display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:var(--rs-settings-gap);padding:var(--rs-settings-row-padding) 0}
.setting-row+.setting-row{border-top:1px solid var(--rs-border)}
.picker{display:flex;align-items:center;gap:8px;min-height:var(--rs-settings-control-height);max-width:100%;padding:4px 8px;background:var(--rs-bg);color:var(--rs-text);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius)}
.picker :global(svg){width:14px;height:14px;flex-shrink:0}
.picker:focus-visible{outline:2px solid var(--rs-accent);outline-offset:2px}
.overlay-controls{display:flex;align-items:center;flex-wrap:wrap;gap:var(--rs-settings-gap);max-width:100%}
.overlay-controls input[type=range]{width:160px;max-width:100%;min-width:0}
.overlay-value{padding:0;gap:4px;flex-wrap:nowrap}
.overlay-value input{width:64px;min-height:var(--rs-settings-control-height);box-sizing:border-box;padding:4px 6px;background:var(--rs-bg);color:var(--rs-text);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);font:inherit}
.overlay-value input:focus-visible{outline:2px solid var(--rs-accent);outline-offset:2px}
[role=alert]{color:var(--rs-error)}
.theme-actions{display:flex;gap:var(--rs-settings-gap);flex-wrap:wrap;margin-top:var(--rs-settings-gap)}
.theme-actions button{min-height:var(--rs-settings-control-height);border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);background:var(--rs-bg-elevated);color:var(--rs-text);padding:4px 8px}
h3{margin-top:var(--rs-settings-section-gap);font-size:14px}.background-preview{height:120px;background-color:var(--rs-bg);background-image:var(--rs-background-image,none);background-size:100% 100%,var(--rs-background-size,cover);background-position:center,var(--rs-background-position,center);background-repeat:no-repeat;border:1px solid var(--rs-border);border-radius:var(--rs-control-radius);display:grid;place-items:center;margin-bottom:var(--rs-settings-gap)}.background-preview span{padding:8px 14px;background:var(--rs-bg-elevated);border-radius:var(--rs-control-radius)}
</style>
+75 -5
View File
@@ -1,12 +1,26 @@
import { customThemes } from './customThemes.ts';
import { customThemes, type CustomTheme } from './customThemes.ts';
import { readBackgroundImage } from './backgroundImages.ts';
export const APPEARANCE_KEY = 'runestone.appearance';
export const THEMES = ['default', 'claude', 'sakura'] as const;
export type ThemeName = typeof THEMES[number] | `custom:${string}`;
export type Appearance = { theme: ThemeName; mode: 'light' | 'dark' };
export const BACKGROUND_POSITIONS = ['center', 'top left', 'top', 'top right', 'left', 'right', 'bottom left', 'bottom', 'bottom right'] as const;
export const BACKGROUND_SIZES = ['cover', 'contain', 'auto'] as const;
export type Appearance = { theme: ThemeName; mode: 'light' | 'dark'; newTabBackground?: { image?: string; imageId?: string; overlay?: number; position?: typeof BACKGROUND_POSITIONS[number]; size?: typeof BACKGROUND_SIZES[number] } };
export const DEFAULT_APPEARANCE: Appearance = { theme: 'default', mode: 'dark' };
export function normalizeAppearance(value: { theme?: unknown; mode?: unknown } | null): Appearance {
export function normalizeAppearance(value: { theme?: unknown; mode?: unknown; newTabBackground?: unknown } | null): Appearance {
const theme: ThemeName = typeof value?.theme === 'string' && (/^custom:[a-z][a-z0-9-]{0,63}$/.test(value.theme) || (THEMES as readonly string[]).includes(value.theme)) ? value.theme as ThemeName : 'default';
return { theme, mode: theme === 'sakura' || value?.mode === 'light' ? 'light' : 'dark' };
const result: Appearance = { theme, mode: theme === 'sakura' || value?.mode === 'light' ? 'light' : 'dark' };
const background = value?.newTabBackground;
if (background && typeof background === 'object') {
const source = background as { image?: unknown; imageId?: unknown; overlay?: unknown; position?: unknown; size?: unknown };
const image = typeof source.image === 'string' && source.image.length <= 3_000_000 && /^data:image\/(?:png|jpeg|webp|gif);base64,[a-z0-9+/=]+$/i.test(source.image) ? source.image : undefined;
const imageId = typeof source.imageId === 'string' && /^[0-9a-f-]{36}$/i.test(source.imageId) ? source.imageId : undefined;
const overlay = typeof source.overlay === 'number' && Number.isFinite(source.overlay) ? Math.max(-1, Math.min(1, source.overlay)) : 0;
const position = BACKGROUND_POSITIONS.includes(source.position as typeof BACKGROUND_POSITIONS[number]) ? source.position as typeof BACKGROUND_POSITIONS[number] : 'center';
const size = BACKGROUND_SIZES.includes(source.size as typeof BACKGROUND_SIZES[number]) ? source.size as typeof BACKGROUND_SIZES[number] : 'cover';
if (image || imageId) result.newTabBackground = { ...(image ? { image } : {}), ...(imageId ? { imageId } : {}), overlay, position, size };
}
return result;
}
export function parseAppearance(raw: string | null): Appearance {
try { return normalizeAppearance(JSON.parse(raw || 'null')); }
@@ -28,8 +42,64 @@ const palettes = {
light: ['#fefcfc','#fefcfc','#dbeacb','#f8dbe6','#687788','#513346','#321c2a','#98556c','#ffc9dc'],
},
};
export function exportAppearanceTheme(theme: ThemeName): CustomTheme {
const custom = customThemes().find(item => `custom:${item.id}` === theme);
if (custom) return custom;
const palette = theme === 'sakura' ? { light: palettes.sakura.light, dark: palettes.sakura.light }
: palettes[theme === 'claude' ? 'claude' : 'default'];
return { schema: 1, id: 'my-theme', name: 'My theme',
light: Object.fromEntries(keys.map((key, index) => [key, palette.light[index]])),
dark: Object.fromEntries(keys.map((key, index) => [key, palette.dark[index]])) };
}
const backgroundUrls = new WeakMap<HTMLElement, { image: string; url: string }>();
const backgroundRequests = new WeakMap<HTMLElement, string | undefined>();
async function applySavedBackground(root: HTMLElement, background?: Appearance['newTabBackground']) {
const id = background?.imageId;
backgroundRequests.set(root, id);
if (!id) { applyBackgroundImage(root, background?.image); return; }
const previous = backgroundUrls.get(root);
if (previous?.image === id) { root.style.setProperty('--rs-new-tab-image', `url("${previous.url}")`); return; }
applyBackgroundImage(root);
try {
const file = await readBackgroundImage(id);
if (!file || backgroundRequests.get(root) !== id) return;
const url = URL.createObjectURL(file);
const old = backgroundUrls.get(root);
backgroundUrls.set(root, { image: id, url });
root.style.setProperty('--rs-new-tab-image', `url("${url}")`);
if (old) URL.revokeObjectURL(old.url);
} catch { /* Keep the theme usable if image storage is unavailable. */ }
}
function applyBackgroundImage(root: HTMLElement, image?: string) {
const previous = backgroundUrls.get(root);
if (image && previous?.image === image) {
root.style.setProperty('--rs-new-tab-image', `url("${previous.url}")`);
return;
}
let url: string | undefined;
if (image) {
try {
const [header, data] = image.split(',');
const bytes = Uint8Array.from(atob(data), character => character.charCodeAt(0));
url = URL.createObjectURL(new Blob([bytes], { type: header.slice(5, header.indexOf(';')) }));
} catch { /* Invalid saved image data must not stop the theme update. */ }
}
// Large data URLs exceed Chromium's CSS variable limit. Keep only a short blob URL in CSS.
root.style.setProperty('--rs-new-tab-image', url ? `url("${url}")` : 'none');
if (image && url) backgroundUrls.set(root, { image, url });
else backgroundUrls.delete(root);
if (previous) URL.revokeObjectURL(previous.url);
}
export function applyAppearance(value: Appearance, root = document.documentElement) {
const { theme, mode } = normalizeAppearance(value);
const { theme, mode, newTabBackground } = normalizeAppearance(value);
root.style.setProperty('--rs-new-tab-bg', 'var(--rs-bg)');
const overlay = newTabBackground?.overlay ?? 0;
const shade = overlay < 0 ? '255,255,255' : '0,0,0';
root.style.setProperty('--rs-background-overlay', `linear-gradient(rgba(${shade},${Math.abs(overlay)}),rgba(${shade},${Math.abs(overlay)}))`);
root.style.setProperty('--rs-background-image', newTabBackground ? 'var(--rs-background-overlay), var(--rs-new-tab-image, none)' : 'none');
root.style.setProperty('--rs-background-position', newTabBackground?.position ?? 'center');
root.style.setProperty('--rs-background-size', newTabBackground?.size ?? 'cover');
void applySavedBackground(root, newTabBackground);
root.dataset.theme = mode;
root.dataset.palette = theme;
root.style.colorScheme = mode;
+46
View File
@@ -0,0 +1,46 @@
export const BACKGROUND_IMAGE_LIMIT = 50 * 1024 * 1024;
function database(): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
const request = indexedDB.open('runestone-appearance', 1);
request.onupgradeneeded = () => request.result.createObjectStore('images');
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
export async function saveBackgroundImage(file: Blob): Promise<string> {
if (file.size > BACKGROUND_IMAGE_LIMIT) throw new Error('Choose an image of 50 MiB or less.');
const db = await database();
const id = crypto.randomUUID();
try {
await new Promise<void>((resolve, reject) => {
const transaction = db.transaction('images', 'readwrite');
transaction.objectStore('images').put(file, id);
transaction.oncomplete = () => resolve();
transaction.onerror = () => reject(transaction.error);
transaction.onabort = () => reject(transaction.error);
});
return id;
} finally { db.close(); }
}
export async function readBackgroundImage(id: string): Promise<Blob | undefined> {
const db = await database();
try {
return await new Promise<Blob | undefined>((resolve, reject) => {
const request = db.transaction('images').objectStore('images').get(id);
request.onsuccess = () => resolve(request.result instanceof Blob ? request.result : undefined);
request.onerror = () => reject(request.error);
});
} finally { db.close(); }
}
export async function removeBackgroundImage(id: string): Promise<void> {
const db = await database();
try {
await new Promise<void>((resolve, reject) => {
const transaction = db.transaction('images', 'readwrite');
transaction.objectStore('images').delete(id);
transaction.oncomplete = () => resolve();
transaction.onerror = () => reject(transaction.error);
transaction.onabort = () => reject(transaction.error);
});
} finally { db.close(); }
}
+4 -3
View File
@@ -9,11 +9,12 @@
--rs-settings-section-gap: 16px;
--rs-menu-width: 248px;
--rs-menu-padding: 5px;
--rs-menu-row-height: 26px;
--rs-menu-row-padding: 3px 8px;
--rs-menu-row-height: 30px;
--rs-menu-row-padding: 4px 10px;
--rs-menu-icon-size: 14px;
--rs-menu-icon-gap: 8px;
--rs-menu-font-size: 12px;
--rs-menu-font-size: 13px;
--rs-menu-border: transparent;
--rs-menu-shadow: 0 8px 30px #0006;
--rs-item-selection-radius: var(--rs-control-radius);
--rs-item-selection-bg: color-mix(in srgb, var(--rs-accent) 20%, transparent);