Add interface languages and improve themes and workspace controls for 0.1.36

This commit is contained in:
Knotty Wyvern
2026-10-15 10:55:59 -07:00
parent b066359b66
commit 68e86ab6eb
98 changed files with 5499 additions and 874 deletions
+54 -37
View File
@@ -1,4 +1,5 @@
<script lang="ts">
import { t } from "$lib/i18n";
import { onMount, onDestroy } from 'svelte';
import { invoke, isTauri } from '@tauri-apps/api/core';
import { customThemes, installTheme, parseCustomTheme, removeTheme, type CustomTheme } from './customThemes';
@@ -18,37 +19,37 @@
let closePicker = () => {};
const themes = $derived([...BUILTIN_THEMES, ...installed.map(theme => ({ id: `custom:${theme.id}` as ThemeName, name: theme.name }))].flatMap(theme =>
themeModes(theme.id).map(mode => ({
theme: theme.id, mode, name: themeModes(theme.id).length === 1 ? theme.name : `${theme.name} ${mode === 'light' ? 'Light' : 'Dark'}`,
theme: theme.id, mode, name: themeModes(theme.id).length === 1 ? theme.name : `${theme.name} ${mode === 'light' ? $t('Light') : $t('Dark')}`,
}))));
onDestroy(() => closePicker());
function picker(event: MouseEvent) {
closePicker();
const anchor = event.currentTarget as HTMLButtonElement;
const bounds = anchor.getBoundingClientRect();
closePicker = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: 'Color theme', parent: anchor.closest('dialog') ?? undefined,
closePicker = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: $t('Color theme'), parent: anchor.closest('dialog') ?? undefined,
items: themes.map(choice => ({ label: choice.name, radio: true, checked: choice.theme === appearance.theme && choice.mode === appearance.mode,
run: () => change({ ...appearance, theme: choice.theme, mode: choice.mode }) })) }).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'];
const positionLabels = $derived([$t('Center'), $t('Top left'), $t('Top center'), $t('Top right'), $t('Center left'), $t('Center right'), $t('Bottom left'), $t('Bottom center'), $t('Bottom right')]);
const sizeLabels = $derived([$t('Fill'), $t('Fit'), $t('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,
closePicker = showActionMenu({ x: bounds.left, y: bounds.bottom + 4, label: field === 'position' ? $t('Image position') : $t('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.'; } };
const read = () => { try { installed = customThemes(); appearance = parseAppearance(localStorage.getItem(APPEARANCE_KEY)); } catch { error = $t('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 = ''; return true; }
catch { error = 'Could not save appearance settings.'; return false; }
catch { error = $t('Could not save appearance settings.'); return false; }
}
function changeOverlay(input: HTMLInputElement) {
const percent = input.valueAsNumber;
@@ -59,14 +60,14 @@
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.'; }
try { await removeBackgroundImage(old); } catch { error = $t('Could not remove the saved image from storage.'); }
}
}
async function importTheme(file?: File) {
if (!file) return;
try {
if (file.size > 65536) throw new Error('Choose a theme smaller than 64 KiB.');
const theme = parseCustomTheme(JSON.parse(await file.text()));
if (file.size > 65536) throw new Error($t('Choose a theme smaller than 64 KiB.'));
const theme = parseCustomTheme(JSON.parse(await file.text()), appearance.mode);
installTheme(theme); installed = customThemes();
change({ ...appearance, theme: `custom:${theme.id}` });
} catch (reason) { error = String(reason); }
@@ -76,7 +77,7 @@
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.');
if (!['image/png', 'image/jpeg', 'image/webp', 'image/gif'].includes(file.type)) throw new Error($t('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;
@@ -90,59 +91,65 @@
if (exporting) return;
exporting = true; error = ''; status = '';
try {
const source = exportAppearanceTheme(appearance.theme);
const source = exportAppearanceTheme(appearance.theme, appearance.mode);
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.';
status = path ? $t('Theme saved to {path}', { path }) : $t('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.';
status = $t('Theme download started.');
}
} catch (reason) { error = `Could not export the theme: ${String(reason)}`; }
} catch (reason) { error = $t('Could not export the theme: {error}', { error: String(reason) }); }
finally { exporting = false; }
}
</script>
<h2>Appearance</h2>
<p>Choose a color theme variant.</p>
<h2>{$t("Appearance")}</h2>
<p>{$t("Choose a color theme variant.")}</p>
<div class="card">
<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.theme === appearance.theme && theme.mode === appearance.mode)?.name ?? 'RuneStone Dark'}<Icon icon="chevron-down" /></button></div>
<div class="setting-row"><span>{$t("Color theme")}</span><button class="picker" aria-label={$t("Color theme")} aria-haspopup="menu" onclick={event => picker(event)}>{themes.find(theme => theme.theme === appearance.theme && theme.mode === appearance.mode)?.name ?? 'RuneStone Dark'}<Icon icon="chevron-down" /></button></div>
</div>
<div class="theme-preview" role="img" aria-label="Color theme preview">
<div class="theme-preview" role="img" aria-label={$t("Color theme preview")}>
<div class="preview-sidebar" aria-hidden="true"><span></span><span></span><span></span></div>
<div class="preview-document" aria-hidden="true"><strong>RuneStone</strong><span class="preview-prose">A place for your ideas.</span><span class="preview-selection">Selected text</span><span class="preview-link">Link</span><code class="preview-code"><span class="preview-keyword">const</span> name = <span class="preview-string">"RuneStone"</span>;<br /><span class="preview-function">show</span>(name, <span class="preview-number">42</span>);</code></div>
<div class="preview-document" aria-hidden="true"><strong>RuneStone</strong><span class="preview-prose">{$t("A place for your ideas.")}</span><span class="preview-selection">{$t("Selected text")}</span><span class="preview-link">{$t("Link")}</span><code class="preview-code"><span class="preview-keyword">const</span> name = <span class="preview-string">"RuneStone"</span>;<br /><span class="preview-function">show</span>(name, <span class="preview-number">42</span>);</code></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 disabled={exporting} onclick={() => void exportTemplate()}>{exporting ? 'Exporting…' : 'Export theme template'}</button>
{#if appearance.theme.startsWith('custom:')}<IconButton icon="trash" label="Remove custom theme" onclick={() => {
<input bind:this={themeInput} type="file" accept=".json,application/json" aria-label={$t("Theme JSON file")} hidden onchange={event => { void importTheme(event.currentTarget.files?.[0]); }} />
<button onclick={() => themeInput.click()}>{$t("Install theme")}</button>
<button disabled={exporting} onclick={() => void exportTemplate()}>{exporting ? $t('Exporting…') : $t('Export theme template')}</button>
{#if appearance.theme.startsWith('custom:')}<IconButton icon="trash" label={$t("Remove custom theme")} onclick={() => {
try { removeTheme(appearance.theme.slice(7)); installed = customThemes(); change({ ...appearance, theme: 'default' }); }
catch { error = 'Could not remove this theme.'; }
}} />{/if}
</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>
<p>{$t("Edit the exported JSON colors and fonts, then choose Install theme. The template contains one color palette and font families.")}</p>
{#if appearance.theme === 'sakura'}<p>{$t("Sakura uses a light appearance.")}</p>{/if}
<h3>{$t("Transparency")}</h3>
<div class="card">
<label><span>{$t("Transparent surfaces")}</span><input type="checkbox" role="switch" checked={appearance.transparency?.enabled !== false} onchange={event => change({ ...appearance, transparency: { amount: appearance.transparency?.amount ?? 18, enabled: event.currentTarget.checked } })} /></label>
<div class="setting-row"><label for="surface-transparency">{$t("Transparency amount")}</label><div class="overlay-controls"><input id="surface-transparency" type="range" min="0" max="100" step="1" disabled={appearance.transparency?.enabled === false} value={appearance.transparency?.amount ?? 18} oninput={event => change({ ...appearance, transparency: { enabled: true, amount: event.currentTarget.valueAsNumber } })} /><output for="surface-transparency">{appearance.transparency?.amount ?? 18}%</output></div></div>
</div>
<p>{$t("Turn off transparency to use opaque surfaces and reduce compositing work. Text and icons remain opaque.")}</p>
<h3>{$t("Background image")}</h3>
<div class="background-preview" aria-label={$t("Background image preview")}><span>{$t("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 class="setting-row"><span>{$t("Image position")}</span><button class="picker" aria-label={$t("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>{$t("Image size")}</span><button class="picker" aria-label={$t("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>{$t("Image overlay")}</span><div class="overlay-controls"><input type="range" aria-label={$t("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={$t("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>
<p>{$t("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>
<input bind:this={backgroundInput} type="file" accept="image/png,image/jpeg,image/webp,image/gif" aria-label={$t("Background image file")} hidden onchange={event => void importBackground(event.currentTarget.files?.[0])} />
<button onclick={() => backgroundInput.click()}>{$t("Choose image…")}</button>
{#if appearance.newTabBackground}<button onclick={() => void removeBackground()}>{$t("Remove image")}</button>{/if}
<button disabled={!appearance.newTabBackground} onclick={() => void removeBackground()}>{$t("Reset background")}</button>
</div>
<p>PNG, JPEG, WebP, or GIF, up to 50 MiB. The image applies to new tabs on this device.</p>
<p>{$t("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>
@@ -170,6 +177,16 @@
.preview-number{color:var(--rs-syntax-number,var(--rs-special))}
.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}
input[type=checkbox]{accent-color:var(--rs-accent)}
.overlay-controls input[type=range]{appearance:none;background:transparent;height:var(--rs-settings-control-height);margin:0;cursor:pointer}
.overlay-controls input[type=range]::-webkit-slider-runnable-track{height:6px;background:var(--rs-bg-active);border:1px solid var(--rs-text-dim);border-radius:var(--rs-control-radius)}
.overlay-controls input[type=range]::-webkit-slider-thumb{appearance:none;width:18px;height:18px;margin-top:-7px;background:var(--rs-accent);border:2px solid var(--rs-text-strong);border-radius:50%}
.overlay-controls input[type=range]::-moz-range-track{height:4px;background:var(--rs-bg-active);border:1px solid var(--rs-text-dim);border-radius:var(--rs-control-radius)}
.overlay-controls input[type=range]::-moz-range-thumb{width:14px;height:14px;background:var(--rs-accent);border:2px solid var(--rs-text-strong);border-radius:50%}
.overlay-controls input[type=range]:focus-visible{outline:2px solid var(--rs-accent);outline-offset:2px;border-radius:var(--rs-control-radius)}
.overlay-controls input[type=range]:disabled{cursor:default}
.overlay-controls input[type=range]:disabled::-webkit-slider-thumb{background:var(--rs-text-dim)}
.overlay-controls input[type=range]:disabled::-moz-range-thumb{background:var(--rs-text-dim)}
.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}
+3 -1
View File
@@ -1,8 +1,10 @@
<script lang="ts">
import { syncLocale } from '$lib/i18n';
import { onMount } from 'svelte';
import { APPEARANCE_KEY, applyAppearance, parseAppearance } from './appearance';
import { CUSTOM_THEMES_KEY } from './customThemes';
onMount(() => {
const stopLocale = syncLocale();
const read = () => {
try {
const raw = localStorage.getItem(APPEARANCE_KEY);
@@ -17,7 +19,7 @@
read();
window.addEventListener('storage', sync);
window.addEventListener('focus', read);
return () => { window.removeEventListener('storage', sync); window.removeEventListener('focus', read); };
return () => { stopLocale(); window.removeEventListener('storage', sync); window.removeEventListener('focus', read); };
});
</script>
+62 -19
View File
@@ -1,4 +1,4 @@
import { customThemes, type CustomTheme } from './customThemes.ts';
import { customThemes, FONT_ROLES, type ThemeFonts, type ThemeColors, type CustomTheme } from './customThemes.ts';
import { readBackgroundImage } from './backgroundImages.ts';
import { characterTheme, characterSyntax, SYNTAX_ROLES } from './characterThemes.ts';
export const APPEARANCE_KEY = 'runestone.appearance';
@@ -11,17 +11,22 @@ export const BUILTIN_THEMES = [
const LEGACY_THEME_IDS: Record<string, typeof THEMES[number]> = { holo: 'harvest-moon', asuka: 'crimson-pilot', malfoid: 'silver-serpent' };
export function themeModes(theme: string): readonly ('light' | 'dark')[] {
const character = characterTheme(theme);
return character ? [character.mode] : theme === 'sakura' ? ['light'] : ['light', 'dark'];
return theme.startsWith('custom:') ? [customThemeMode(customThemes().find(item => `custom:${item.id}` === theme)?.colors)] : character ? [character.mode] : theme === 'sakura' ? ['light'] : ['light', 'dark'];
}
export type ThemeName = typeof THEMES[number] | `custom:${string}`;
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 type Appearance = { transparency?: { enabled: boolean; amount: number }; 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; newTabBackground?: unknown } | null): Appearance {
export function normalizeAppearance(value: { theme?: unknown; mode?: unknown; newTabBackground?: unknown; transparency?: unknown } | null): Appearance {
const savedTheme = typeof value?.theme === 'string' && Object.hasOwn(LEGACY_THEME_IDS, value.theme) ? LEGACY_THEME_IDS[value.theme] : value?.theme;
const theme: ThemeName = typeof savedTheme === 'string' && (/^custom:[a-z][a-z0-9-]{0,63}$/.test(savedTheme) || (THEMES as readonly string[]).includes(savedTheme)) ? savedTheme as ThemeName : 'default';
const result: Appearance = { theme, mode: characterTheme(theme)?.mode ?? (theme === 'sakura' || value?.mode === 'light' ? 'light' : 'dark') };
const selectedCustom = theme.startsWith('custom:') ? customThemes(value?.mode === 'light' ? 'light' : 'dark').find(item => `custom:${item.id}` === theme) : undefined;
const result: Appearance = { theme, mode: selectedCustom ? customThemeMode(selectedCustom.colors) : characterTheme(theme)?.mode ?? (theme === 'sakura' || value?.mode === 'light' ? 'light' : 'dark') };
if (value?.transparency && typeof value.transparency === 'object') {
const source = value.transparency as { enabled?: unknown; amount?: unknown };
result.transparency = { enabled: source.enabled !== false, amount: typeof source.amount === 'number' && Number.isFinite(source.amount) ? Math.max(0, Math.min(100, Math.round(source.amount))) : 18 };
}
const background = value?.newTabBackground;
if (background && typeof background === 'object') {
const source = background as { image?: unknown; imageId?: unknown; overlay?: unknown; position?: unknown; size?: unknown };
@@ -61,23 +66,56 @@ function builtinPalette(theme: ThemeName) {
if (character) return { light: character.surfaces, dark: character.surfaces };
return palettes[theme === 'claude' ? 'claude' : 'default'];
}
export function exportAppearanceTheme(theme: ThemeName): CustomTheme {
const custom = customThemes().find(item => `custom:${item.id}` === theme);
if (custom) return custom;
const palette = builtinPalette(theme);
const syntax = characterSyntax(theme);
const extra = characterTheme(theme) ? { ...syntax, 'accent-2': characterTheme(theme)!.secondary } : {};
return { schema: 1, id: 'my-theme', name: 'My theme',
light: { ...Object.fromEntries(keys.map((key, index) => [key, palette.light[index]])), ...extra },
dark: { ...Object.fromEntries(keys.map((key, index) => [key, palette.dark[index]])), ...extra } };
export function customThemeMode(colors?: ThemeColors): 'light' | 'dark' {
const hex = colors?.bg?.slice(1) ?? '141414';
const full = hex.length <= 4 ? [...hex.slice(0, 3)].map(value => value + value).join('') : hex.slice(0, 6);
const rgb = [0, 2, 4].map(index => parseInt(full.slice(index, index + 2), 16) / 255)
.map(value => value <= .04045 ? value / 12.92 : ((value + .055) / 1.055) ** 2.4);
return rgb[0] * .2126 + rgb[1] * .7152 + rgb[2] * .0722 > .179 ? 'light' : 'dark';
}
export function exportAppearanceTheme(theme: ThemeName, mode: 'light' | 'dark' = 'dark'): CustomTheme {
const custom = customThemes(mode).find(item => `custom:${item.id}` === theme);
if (custom) mode = customThemeMode(custom.colors);
mode = characterTheme(theme)?.mode ?? (theme === 'sakura' ? 'light' : mode);
const palette = builtinPalette(theme)[mode];
const colors: ThemeColors = Object.fromEntries(keys.map((key, index) => [key, palette[index]]));
colors['accent-2'] = characterTheme(theme)?.secondary ?? (theme === 'claude' ? '#6a9bcc' : theme === 'sakura' ? '#607fa9' : colors.accent);
const semantic = mode === 'light' ? ['#b42323', '#8a5700', '#806600', '#287b29', '#7740a5'] : ['#f44747', '#d68a00', '#cca700', '#89d185', '#c792ea'];
if (theme === 'claude') { semantic[3] = '#788c5d'; semantic[4] = '#6a9bcc'; }
if (theme === 'sakura') { semantic[3] = '#618c71'; semantic[4] = '#cb6b91'; }
(['error', 'warn-hot', 'warn', 'ok', 'special'] as const).forEach((key, index) => colors[key] = semantic[index]);
const syntax = theme === 'sakura' ? ['#cb6b91', '#98556c', '#618c71', '#69a2bd', '#607fa9', '#687788'] : [colors.special, colors.accent, colors.text, colors['accent-2'], colors['accent-2'], colors['text-dim']];
(['parameter', 'keyword', 'local', 'static', 'instance', 'global'] as const).forEach((key, index) => colors[`syntax-${key}`] = syntax[index]);
Object.assign(colors, { 'syntax-string': colors.ok, 'syntax-number': colors.special, 'syntax-comment': colors['text-dim'], 'syntax-type': colors['accent-2'], 'syntax-function': colors['accent-2'] }, characterSyntax(theme));
return { schema: 2, id: custom?.id ?? 'my-theme', name: custom?.name ?? 'My theme', colors: { ...colors, ...custom?.colors }, fonts: { ...themeFonts(theme), ...custom?.fonts } };
}
export function themeFonts(theme: ThemeName): Required<ThemeFonts> {
const ui = '"Segoe UI Variable Text", "Segoe UI", ui-sans-serif, system-ui, sans-serif';
const prose = '"Segoe UI Variable Display", "Segoe UI", "Helvetica Neue", ui-sans-serif, system-ui, sans-serif';
const mono = '"Cascadia Mono", "Cascadia Code", "JetBrains Mono", "Fira Code", Consolas, ui-monospace, monospace';
const fonts = { ui, prose, heading: prose, mono };
if (theme === 'claude') return { ...fonts, ui: '"Lora", Georgia, serif', prose: '"Lora", Georgia, serif', heading: '"Poppins", Arial, sans-serif' };
if (theme === 'harvest-moon') return { ...fonts, ui: 'Candara, "Trebuchet MS", "Segoe UI", sans-serif', prose: 'Constantia, Georgia, "Times New Roman", serif', heading: 'Constantia, Georgia, "Times New Roman", serif' };
if (theme === 'crimson-pilot') return { ...fonts, ui: 'Bahnschrift, "Trebuchet MS", Arial, sans-serif', prose: '"Segoe UI", "Helvetica Neue", Arial, sans-serif', heading: 'Bahnschrift, "Trebuchet MS", Arial, sans-serif' };
if (theme === 'silver-serpent') return { ...fonts, ui: 'Corbel, "Segoe UI", "Helvetica Neue", Arial, sans-serif', prose: '"Palatino Linotype", "Book Antiqua", Palatino, Georgia, serif', heading: '"Palatino Linotype", "Book Antiqua", Palatino, Georgia, serif' };
return fonts;
}
export function applyTransparency(value: Appearance['transparency'], root: HTMLElement) {
const supplied = value?.amount ?? 18;
const amount = value?.enabled === false ? 0 : Number.isFinite(supplied) ? Math.max(0, Math.min(100, supplied)) : 18;
root.dataset.transparency = amount ? 'on' : 'off';
root.style.setProperty('--rs-surface-opacity', `${100 - amount}%`);
root.style.setProperty('--rs-editor-surface-opacity', `${100 - amount * 10 / 18}%`);
root.style.setProperty('--rs-hover-surface-opacity', `${100 - amount * 8 / 18}%`);
root.style.setProperty('--rs-transparent-plugin-bg', amount ? 'transparent' : 'var(--rs-bg)');
}
const backgroundUrls = new WeakMap<HTMLElement, { image: string; url: string }>();
const backgroundRequests = new WeakMap<HTMLElement, string | undefined>();
function applyBackgroundSurfaces(root: HTMLElement, hasImage: boolean) {
root.style.setProperty('--rs-workarea-sidebar-bg', hasImage ? 'var(--rs-image-sidebar-bg)' : 'var(--rs-bg-elevated)');
root.style.setProperty('--rs-workarea-editor-bg', hasImage ? 'var(--rs-image-editor-bg)' : 'var(--rs-bg)');
root.style.setProperty('--rs-workarea-surface-opacity', hasImage ? '82%' : '100%');
root.style.setProperty('--rs-workarea-plugin-bg', hasImage ? 'transparent' : 'var(--rs-bg)');
root.style.setProperty('--rs-workarea-surface-opacity', hasImage ? 'var(--rs-surface-opacity)' : '100%');
root.style.setProperty('--rs-workarea-plugin-bg', hasImage ? 'var(--rs-transparent-plugin-bg)' : 'var(--rs-bg)');
}
async function applySavedBackground(root: HTMLElement, background?: Appearance['newTabBackground']) {
const id = background?.imageId;
@@ -120,7 +158,11 @@ function applyBackgroundImage(root: HTMLElement, image?: string) {
if (previous) URL.revokeObjectURL(previous.url);
}
export function applyAppearance(value: Appearance, root = document.documentElement) {
const { theme, mode, newTabBackground } = normalizeAppearance(value);
const normalized = normalizeAppearance(value);
const { theme, newTabBackground } = normalized;
const custom = theme.startsWith('custom:') ? customThemes(normalized.mode).find(item => item.id === theme.slice(7)) : undefined;
const mode = custom ? customThemeMode(custom.colors) : normalized.mode;
applyTransparency(normalized.transparency, root);
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';
@@ -132,6 +174,8 @@ export function applyAppearance(value: Appearance, root = document.documentEleme
root.dataset.theme = mode;
root.dataset.palette = theme;
root.style.colorScheme = mode;
const fonts = { ...themeFonts(theme), ...custom?.fonts };
FONT_ROLES.forEach(role => root.style.setProperty(`--rs-font-${role}`, fonts[role]));
const palette = builtinPalette(theme)[mode];
keys.forEach((key, index) => root.style.setProperty(`--rs-${key}`, palette[index]));
root.style.setProperty('--rs-accent-2', characterTheme(theme)?.secondary ?? (theme === 'claude' ? '#6a9bcc' : theme === 'sakura' ? '#607fa9' : 'var(--rs-accent)'));
@@ -149,8 +193,7 @@ export function applyAppearance(value: Appearance, root = document.documentEleme
['parameter', 'keyword', 'local', 'static', 'instance', 'global'].forEach((key, index) => root.style.setProperty(`--rs-syntax-${key}`, syntax[index]));
for (const [key, color] of Object.entries(characterSyntax(theme))) root.style.setProperty(`--rs-${key}`, color);
root.style.setProperty('--rs-danger', 'var(--rs-error)');
const custom = theme.startsWith('custom:') ? customThemes().find(item => item.id === theme.slice(7)) : undefined;
if (custom) for (const [key, color] of Object.entries(custom[mode])) root.style.setProperty(`--rs-${key}`, color);
if (custom) for (const [key, color] of Object.entries(custom.colors)) root.style.setProperty(`--rs-${key}`, color);
window.dispatchEvent(new CustomEvent('runestone-theme-changed'));
}
export function saveAppearance(value: Appearance) {
+53 -8
View File
@@ -1,13 +1,16 @@
export const CUSTOM_THEMES_KEY = "runestone.custom-themes";
export const COLOR_TOKENS = ["bg", "bg-elevated", "bg-active", "border", "text", "text-dim", "text-strong", "accent", "accent-2", "selection", "error", "warn", "warn-hot", "ok", "special", "syntax-parameter", "syntax-keyword", "syntax-local", "syntax-static", "syntax-instance", "syntax-global", "syntax-string", "syntax-number", "syntax-comment", "syntax-type", "syntax-function"] as const;
export type ThemeColors = Partial<Record<typeof COLOR_TOKENS[number], string>>;
export type CustomTheme = { schema: 1; id: string; name: string; light: ThemeColors; dark: ThemeColors };
export const FONT_ROLES = ['ui', 'prose', 'heading', 'mono'] as const;
export type ThemeFonts = Partial<Record<typeof FONT_ROLES[number], string>>;
export type CustomTheme = { schema: 2; id: string; name: string; colors: ThemeColors; fonts?: ThemeFonts };
export type LegacyCustomTheme = { schema: 1; id: string; name: string; light: ThemeColors; dark: ThemeColors };
export function parseCustomTheme(input: unknown): CustomTheme {
export function parseCustomTheme(input: unknown, legacyMode: "light" | "dark" = "dark"): CustomTheme {
if (!input || typeof input !== "object") throw new Error("Choose a RuneStone theme JSON file.");
const value = input as Record<string, unknown>;
if (value.schema !== 1 || typeof value.id !== "string" || !/^[a-z][a-z0-9-]{0,63}$/.test(value.id)
|| typeof value.name !== "string" || !value.name.trim() || value.name.length > 80) throw new Error("The theme needs schema 1, an ID, and a name.");
if ((value.schema !== 1 && value.schema !== 2) || typeof value.id !== "string" || !/^[a-z][a-z0-9-]{0,63}$/.test(value.id)
|| typeof value.name !== "string" || !value.name.trim() || value.name.length > 80) throw new Error("The theme needs schema 2, an ID, and a name.");
const colors = (mode: string): ThemeColors => {
const source = value[mode];
if (!source || typeof source !== "object" || Array.isArray(source)) throw new Error(`The theme needs ${mode} colors.`);
@@ -20,13 +23,55 @@ export function parseCustomTheme(input: unknown): CustomTheme {
if (!result.bg || !result.text || !result.accent) throw new Error(`The ${mode} palette needs bg, text, and accent.`);
return result;
};
return { schema: 1, id: value.id, name: value.name.trim(), light: colors("light"), dark: colors("dark") };
if (value.schema === 1) { colors("light"); colors("dark"); }
let fonts: ThemeFonts | undefined;
if (value.fonts !== undefined) {
if (!value.fonts || typeof value.fonts !== 'object' || Array.isArray(value.fonts)) throw new Error('Use an object for theme fonts.');
fonts = {};
for (const [role, stack] of Object.entries(value.fonts)) {
if (!(FONT_ROLES as readonly string[]).includes(role)) throw new Error(`Unknown theme font: ${role}`);
if (typeof stack !== 'string' || stack.length > 512 || !/^[\p{L}\p{N} _,'"-]+$/u.test(stack) || !stack.trim()
|| stack.split(',').some(family => !/^(?:"[^"\n]+"|'[^'\n]+'|[\p{L}\p{N}_ -]+)$/u.test(family.trim()))) throw new Error(`Use a font family stack for ${role}.`);
fonts[role as keyof ThemeFonts] = stack.trim();
}
}
return { schema: 2, id: value.id, name: value.name.trim(), colors: colors(value.schema === 1 ? legacyMode : "colors"), ...(fonts ? { fonts } : {}) };
}
export function customThemes(): CustomTheme[] {
const pendingLegacy = new Map<string, CustomTheme[]>();
export function customThemes(legacyMode?: "light" | "dark"): CustomTheme[] {
try {
const stored = JSON.parse(localStorage.getItem(CUSTOM_THEMES_KEY) || "[]");
return Array.isArray(stored) ? stored.flatMap(value => { try { return [parseCustomTheme(value)]; } catch { return []; } }) : [];
const raw = localStorage.getItem(CUSTOM_THEMES_KEY) || "[]";
const pending = pendingLegacy.get(raw);
if (pending) return pending.map(theme => ({ ...theme, colors: { ...theme.colors } }));
const stored = JSON.parse(raw);
if (!Array.isArray(stored)) return [];
if (!legacyMode) {
try { legacyMode = JSON.parse(localStorage.getItem('runestone.appearance') || 'null')?.mode === 'light' ? 'light' : 'dark'; }
catch { legacyMode = 'dark'; }
}
const parsed = stored.flatMap(value => { try { return [parseCustomTheme(value, legacyMode)]; } catch { return []; } });
if (stored.some(value => value?.schema === 1)) {
// Retain both original palettes before converting the saved selection to one palette.
try {
const backupKey = `${CUSTOM_THEMES_KEY}.legacy`;
const backup = JSON.parse(localStorage.getItem(backupKey) || '[]');
if (!Array.isArray(backup)) throw new Error('Invalid legacy backup');
const originals = backup;
for (const value of stored.filter(value => value?.schema === 1)) {
if (!originals.some(item => JSON.stringify(item) === JSON.stringify(value))) originals.push(value);
}
localStorage.setItem(backupKey, JSON.stringify(originals));
localStorage.setItem(CUSTOM_THEMES_KEY, JSON.stringify(stored.map(value => {
try { return parseCustomTheme(value, legacyMode); } catch { return value; }
})));
} catch {
// Storage failures must not hide readable themes or change their chosen palette.
pendingLegacy.set(raw, parsed);
}
}
return parsed;
} catch { return []; }
}
+11 -7
View File
@@ -6,11 +6,15 @@
--rs-tooltip-shadow: 0 4px 16px #0005;
--rs-tooltip-font-size: 12px;
--rs-control-radius: 5px;
--rs-image-control-bg: color-mix(in srgb, var(--rs-bg) 82%, transparent);
--rs-image-control-hover-bg: color-mix(in srgb, var(--rs-bg-active) 92%, transparent);
--rs-image-sidebar-bg: color-mix(in srgb, var(--rs-bg-elevated) 82%, transparent);
--rs-image-editor-bg: color-mix(in srgb, var(--rs-bg) 90%, transparent);
--rs-code-block-bg: color-mix(in srgb, var(--rs-bg-elevated) 82%, transparent);
--rs-surface-opacity: 82%;
--rs-editor-surface-opacity: 90%;
--rs-hover-surface-opacity: 92%;
--rs-transparent-plugin-bg: transparent;
--rs-image-control-bg: color-mix(in srgb, var(--rs-bg) var(--rs-surface-opacity), transparent);
--rs-image-control-hover-bg: color-mix(in srgb, var(--rs-bg-active) var(--rs-hover-surface-opacity), transparent);
--rs-image-sidebar-bg: color-mix(in srgb, var(--rs-bg-elevated) var(--rs-surface-opacity), transparent);
--rs-image-editor-bg: color-mix(in srgb, var(--rs-bg) var(--rs-editor-surface-opacity), transparent);
--rs-code-block-bg: color-mix(in srgb, var(--rs-bg-elevated) var(--rs-surface-opacity), transparent);
--rs-workarea-sidebar-bg: var(--rs-bg-elevated);
--rs-workarea-editor-bg: var(--rs-bg);
--rs-workarea-surface-opacity: 100%;
@@ -30,8 +34,8 @@
--rs-menu-icon-gap: 8px;
--rs-menu-font-size: 13px;
--rs-menu-border: transparent;
--rs-menu-bg: color-mix(in srgb, var(--rs-bg-elevated) 82%, transparent);
--rs-menu-active-bg: color-mix(in srgb, var(--rs-bg-active) 82%, transparent);
--rs-menu-bg: color-mix(in srgb, var(--rs-bg-elevated) var(--rs-surface-opacity), transparent);
--rs-menu-active-bg: color-mix(in srgb, var(--rs-bg-active) var(--rs-surface-opacity), 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);