diff --git a/packages/shell/scripts/google-fonts-catalog.mjs b/packages/shell/scripts/google-fonts-catalog.mjs new file mode 100644 index 0000000..9351471 --- /dev/null +++ b/packages/shell/scripts/google-fonts-catalog.mjs @@ -0,0 +1,34 @@ +// Regenerates src/panel/fonts/googleFontsCatalog.json, the font browser's offline list of Google +// Fonts families (name, category, weight axis or static weights, popularity rank). Development-time +// only: an app never fetches this list; it downloads font files natively when the owner installs +// one (fonts.googleapis.com / fonts.gstatic.com, see waybetter-host gfonts.rs and fonts.rs). +// +// node packages/shell/scripts/google-fonts-catalog.mjs [metadata.json] +// +// Without an argument it reads https://fonts.google.com/metadata/fonts. Only families with a Latin +// subset and a name the native side accepts (letters, digits, single spaces) are kept. +import { readFileSync, writeFileSync } from 'node:fs'; + +const CATEGORY = { 'Sans Serif': 'sans', Serif: 'serif', Display: 'display', Handwriting: 'handwriting', Monospace: 'mono' }; +const NAME = /^[A-Za-z0-9]+( [A-Za-z0-9]+)*$/; + +const text = process.argv[2] + ? readFileSync(process.argv[2], 'utf8') + : await (await fetch('https://fonts.google.com/metadata/fonts')).text(); +const metadata = JSON.parse(text.replace(/^\)\]\}'\s*/, '')); +const families = metadata.familyMetadataList + .filter(font => font.subsets?.includes('latin') && NAME.test(font.family) && font.family.length <= 48 && CATEGORY[font.category]) + .sort((a, b) => a.popularity - b.popularity) + .map((font, rank) => { + const axis = font.axes?.find(item => item.tag === 'wght'); + const weights = Object.keys(font.fonts ?? {}).filter(key => /^\d+$/.test(key)).map(Number).sort((a, b) => a - b); + return [font.family, CATEGORY[font.category], axis ? [axis.min, axis.max] : null, weights, rank + 1]; + }); +const out = { + source: 'https://fonts.google.com/metadata/fonts', + generated: new Date().toISOString().slice(0, 10), + fields: ['family', 'category', 'wghtAxis', 'weights', 'rank'], + families, +}; +writeFileSync(new URL('../src/panel/fonts/googleFontsCatalog.json', import.meta.url), `${JSON.stringify(out)}\n`); +console.log(`${families.length} families`); diff --git a/packages/shell/src/frame/appI18n.ts b/packages/shell/src/frame/appI18n.ts new file mode 100644 index 0000000..e83455f --- /dev/null +++ b/packages/shell/src/frame/appI18n.ts @@ -0,0 +1,101 @@ +// An app's i18n instance for its shell webview (the shell frame, the panel, its own windows): +// English (the app's catalog over the framework's) is always loaded, other catalogs load on +// demand through the loader the app registers (its bundler's lazy imports), and components call +// `useT()` so a language switch re-renders them in place. The frame is bound to the instance. +// +// export const { i18n, t, tx, useT, setCatalogLoader } = createAppI18n({ +// source: { ...frameworkEn.messages, ...appEn.messages }, languages, useSyncExternalStore, dev: import.meta.env.DEV, +// }); +// +// Keys are typed by the app (`MessageKey`: its English catalog's keys and the framework's). The +// app passes React's `useSyncExternalStore`, so this module has no dependency of its own and the +// app's pure modules that use `t` stay testable under node. + +import { createI18n, type I18n, type Messages, type Params } from '../../../runtime/src/i18n.ts'; +import { setShellI18n } from './i18n.ts'; + +/** One language the app has a catalog for (a row of the app's generated `languages.json`). */ +export type AppLanguage = { + code: string; + name: string; + englishName: string; + dir: 'ltr' | 'rtl'; + status: 'source' | 'machine' | 'reviewed'; + reviewers: string[]; + fallback?: string; + /** Share of English messages this catalog translates (its fallback's included), 0..1. */ + coverage: number; +}; + +export type AppI18nOptions = { + /** English: the framework's messages with the app's over them. */ + source: Messages; + /** Every language with a catalog, English first. */ + languages: readonly AppLanguage[]; + /** React's hook (`import { useSyncExternalStore } from 'react'`), for `useT` and `useLocale`. */ + useSyncExternalStore(subscribe: (listener: () => void) => () => void, getSnapshot: () => Snapshot, getServerSnapshot?: () => Snapshot): Snapshot; + /** A development build: untranslated and malformed messages are logged. */ + dev?: boolean; +}; + +export type AppI18n = { + i18n: I18n; + /** Registers how catalogs load (the app's lazy imports; tests may pass a map). */ + setCatalogLoader(load: (locale: string) => Promise): void; + /** The message for `key` in the active language. */ + t(key: Key, params?: Params): string; + /** For keys assembled at runtime (feature ids, section names): `fallback` when the key is unknown. */ + tx(key: string, params?: Params, fallback?: string): string; + /** Re-renders the calling component when the language changes; returns `t`. */ + useT(): (key: Key, params?: Params) => string; + /** The active locale (re-renders on change). */ + useLocale(): string; + /** "3 minutes ago" style text for a timestamp in the active language. */ + relativeTime(then: number, now?: number): string; + /** A date (and time) in the active language: `formatDate(iso, { dateStyle: 'medium' })`. */ + formatDate(value: string | number | Date, options?: Intl.DateTimeFormatOptions): string; + formatNumber(value: number, options?: Intl.NumberFormatOptions): string; +}; + +export function createAppI18n(options: AppI18nOptions): AppI18n { + let loader: ((locale: string) => Promise) | null = null; + const i18n = createI18n({ + source: options.source, + available: options.languages.map(language => language.code), + fallbacks: Object.fromEntries(options.languages.filter(language => language.fallback).map(language => [language.code, language.fallback!])), + load: locale => loader?.(locale) ?? null, + onMissing: options.dev + ? (key, locale, reason) => { if (reason !== 'key' || locale === 'en') console.warn(`[i18n] ${reason} ${locale}: ${key}`); else console.debug(`[i18n] untranslated ${locale}: ${key}`); } + : undefined, + }); + // The wayBetter shell frame and panel speak through this instance. + setShellI18n(i18n); + + const { useSyncExternalStore } = options; + const t = (key: Key, params?: Params) => i18n.t(key, params); + const subscribe = (listener: () => void) => i18n.onChange(listener); + const snapshot = () => i18n.locale; + return { + i18n, + setCatalogLoader(load) { loader = load; }, + t, + tx: (key, params, fallback) => i18n.tx(key, params, fallback), + useT() { + useSyncExternalStore(subscribe, snapshot, snapshot); + return t; + }, + useLocale: () => useSyncExternalStore(subscribe, snapshot, snapshot), + relativeTime(then, now = Date.now()) { + const seconds = Math.round((then - now) / 1000); + const abs = Math.abs(seconds); + if (abs < 45) return i18n.relative(0, 'second'); + if (abs < 3600) return i18n.relative(Math.round(seconds / 60), 'minute'); + if (abs < 86400) return i18n.relative(Math.round(seconds / 3600), 'hour'); + if (abs < 86400 * 30) return i18n.relative(Math.round(seconds / 86400), 'day'); + if (abs < 86400 * 365) return i18n.relative(Math.round(seconds / (86400 * 30)), 'month'); + return i18n.relative(Math.round(seconds / (86400 * 365)), 'year'); + }, + formatDate: (value, formatOptions = { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }) => i18n.date(value, formatOptions), + formatNumber: (value, formatOptions) => i18n.number(value, formatOptions), + }; +} diff --git a/packages/shell/src/frame/i18n.ts b/packages/shell/src/frame/i18n.ts index 67781bc..a0561f1 100644 --- a/packages/shell/src/frame/i18n.ts +++ b/packages/shell/src/frame/i18n.ts @@ -15,6 +15,7 @@ export type ShellI18n = { onChange(listener: (locale: string) => void): () => void; number(value: number, options?: Intl.NumberFormatOptions): string; relative(value: number, unit: Intl.RelativeTimeFormatUnit): string; + date(value: string | number | Date, options?: Intl.DateTimeFormatOptions): string; }; let current: ShellI18n | null = null; @@ -58,6 +59,11 @@ export function formatNumber(value: number, options?: Intl.NumberFormatOptions): return current ? current.number(value, options) : String(value); } +/** A date (and time) in the active language: `formatDate(iso, { dateStyle: 'medium' })`. */ +export function formatDate(value: string | number | Date, options: Intl.DateTimeFormatOptions = { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }): string { + return current ? current.date(value, options) : new Date(value).toISOString(); +} + /** "3 minutes ago" style text for a timestamp in the active language. */ export function relativeTime(then: number, now = Date.now()): string { if (!current) return new Date(then).toISOString(); diff --git a/packages/shell/src/frame/index.ts b/packages/shell/src/frame/index.ts index 6ca09c8..b724124 100644 --- a/packages/shell/src/frame/index.ts +++ b/packages/shell/src/frame/index.ts @@ -53,3 +53,5 @@ export { chromeVars, CHROME_VAR_NAMES, SHELL_UI_FONT, SHELL_MONO_FONT, type Chro export { shell, setOverlay, scheduleSync, flushSync, isWeb, tabAction, setProfiles, type TabParams, type WebParams } from './state.ts'; export type { PaletteItem, PaletteAction, PaletteContext } from './paletteModel.ts'; export { Icon, Avatar, ICONS, type IconName } from './icons.tsx'; +export { createLanguage, resolveLocale, type Language, type LanguageOptions, type LanguagePreference } from './language.ts'; +export { createAppI18n, type AppI18n, type AppI18nOptions, type AppLanguage } from './appI18n.ts'; diff --git a/packages/shell/src/frame/language.ts b/packages/shell/src/frame/language.ts new file mode 100644 index 0000000..0787da6 --- /dev/null +++ b/packages/shell/src/frame/language.ts @@ -0,0 +1,165 @@ +// Which language the app speaks. The owner picks "Follow the site" (default: the language the site +// itself is set to, as its tabs report their ``), "Follow system" (the OS preference, +// read natively) or a language. The shell resolves that to a catalog, switches every window live, +// and hands native code (dialogs, notifications) and site tabs (the page runtime, plugins) exactly +// the strings they need through the shell-only `i18n_set`. Other local windows (a popover) follow +// through localStorage (same origin as the shell). +// +// export const language = createLanguage({ i18n, nativePrefixes: ['x.', 'kit.', 'plugin.', 'native.'], native: { invoke, listen } }); +// await language.initShell(isNative()); +// +// The panel's language picker takes the same object (`PanelSite.languages`). + +import { direction, matchLocale, normalizeLocale } from '../../../runtime/src/i18n.ts'; +import type { Invoke, Listen } from './bridge.ts'; + +/** `site`: follow the site's own language. `system`: follow the OS. Otherwise a catalog tag. */ +export type LanguagePreference = 'site' | 'system' | string; + +/** The part of a waybetter/i18n instance the language state drives. */ +export type LanguageI18n = { + readonly locale: string; + readonly available: readonly string[]; + setLocale(locale: string): Promise; + resolved(prefixes?: readonly string[]): Record; +}; + +export type LanguageOptions = { + i18n: LanguageI18n; + /** Key prefixes native code and site tabs need; the shell hands exactly these over (`i18n_set`). */ + nativePrefixes: readonly string[]; + /** The app's Tauri `invoke` and `listen` (the language is set up before the shell frame is). */ + native: { invoke: Invoke; listen: Listen }; + /** Where the choice is kept for the app's other local windows (default `wb.language`). */ + storageKey?: string; +}; + +type NativeLanguage = { preference?: string; locale?: string; system?: string[] }; +type Stored = { preference: LanguagePreference; locale: string; siteLang?: string | null }; + +/** Where the shell keeps its choice for the app's other local windows (localStorage). */ +export const DEFAULT_STORAGE_KEY = `wb.language`; + +/** The catalog to use for a preference, the site's reported language and the OS preferences. */ +export function resolveLocale(preference: LanguagePreference, siteLang: string | null, system: readonly string[], available: readonly string[]): string { + if (preference === 'site') return matchLocale(siteLang ? [siteLang] : system, available, siteLang ? matchLocale(system, available) : 'en'); + if (preference === 'system') return matchLocale(system, available); + return matchLocale([preference], available, matchLocale(system, available)); +} + +export type Language = ReturnType; + +export function createLanguage(options: LanguageOptions) { + const { i18n, nativePrefixes, native } = options; + const storageKey = options.storageKey ?? DEFAULT_STORAGE_KEY; + const available = i18n.available; + const current = { + preference: 'site' as LanguagePreference, + siteLang: null as string | null, + system: [] as string[], + native: false, + }; + const listeners = new Set<() => void>(); + + function readStored(): Stored | null { + try { + const value = JSON.parse(localStorage.getItem(storageKey) ?? 'null') as Stored | null; + return value && typeof value.locale === 'string' ? value : null; + } catch { + return null; + } + } + + function writeStored(value: Stored) { + try { localStorage.setItem(storageKey, JSON.stringify(value)); } catch { /* the choice still applies this session */ } + } + + function browserLanguages(): string[] { + const list = typeof navigator === 'undefined' ? [] : [...(navigator.languages ?? []), navigator.language]; + return list.filter((tag): tag is string => typeof tag === 'string' && !!normalizeLocale(tag)); + } + + function paint(locale: string) { + const root = document.documentElement; + root.lang = locale; + root.dir = direction(locale); + } + + let syncing: Promise = Promise.resolve(); + + async function apply() { + const locale = resolveLocale(current.preference, current.siteLang, current.system, available); + await i18n.setLocale(locale); + paint(i18n.locale); + writeStored({ preference: current.preference, locale: i18n.locale, siteLang: current.siteLang }); + if (current.native) { + // Serialized: a quick switch must not let an older set of strings land last. + const strings = { locale: i18n.locale, preference: current.preference, messages: i18n.resolved(nativePrefixes) }; + syncing = syncing.then(() => native.invoke('i18n_set', { strings })).catch(error => console.error('[i18n] native strings were not updated', error)); + } + for (const listener of [...listeners]) listener(); + } + + /** + * Shell start: the saved preference (native), the OS languages, the last language the site + * reported, then the catalog; resolves once the first paint can be in the right language. + */ + async function initShell(isNative: boolean): Promise { + current.native = isNative; + const stored = readStored(); + current.siteLang = stored?.siteLang ?? null; + let fromNative: NativeLanguage | null = null; + if (isNative) { + try { fromNative = await native.invoke('i18n_get'); } catch (error) { console.error('[i18n] i18n_get failed', error); } + } + current.preference = fromNative?.preference || stored?.preference || 'site'; + current.system = [...(fromNative?.system ?? []), ...browserLanguages()]; + if (isNative) { + // Site tabs say which language the site is in; "Follow the site" switches with it. + void native.listen<{ lang?: string }>('tab-state', ({ payload }) => { + const lang = normalizeLocale(payload.lang); + if (!lang || lang === current.siteLang) return; + current.siteLang = lang; + if (current.preference === 'site') void apply(); + else writeStored({ preference: current.preference, locale: i18n.locale, siteLang: lang }); + }); + } + await apply(); + } + + /** Another local window (a popover) and previews: the shell's last choice, kept current through storage events. */ + async function initFollower(forced?: string | null): Promise { + const pick = async () => { + const locale = forced ? matchLocale([forced], available) : readStored()?.locale ?? matchLocale(browserLanguages(), available); + await i18n.setLocale(locale); + paint(i18n.locale); + }; + if (!forced) { + window.addEventListener('storage', event => { if (event.key === storageKey) void pick(); }); + } + await pick(); + } + + function state() { + return { preference: current.preference, siteLang: current.siteLang, system: current.system, locale: i18n.locale }; + } + + async function set(preference: LanguagePreference): Promise { + if (preference !== 'site' && preference !== 'system' && !available.includes(preference)) return; + current.preference = preference; + await apply(); + } + + function subscribe(listener: () => void): () => void { + listeners.add(listener); + return () => { listeners.delete(listener); }; + } + + /** Development previews (`?lang=tr`): a fixed language without native code. */ + async function forcePreview(tag: string): Promise { + current.preference = matchLocale([tag], available); + await apply(); + } + + return { initShell, initFollower, state, set, subscribe, forcePreview, storageKey }; +} diff --git a/packages/shell/src/frame/site.ts b/packages/shell/src/frame/site.ts index 689c25c..4a826ca 100644 --- a/packages/shell/src/frame/site.ts +++ b/packages/shell/src/frame/site.ts @@ -41,6 +41,10 @@ export type ColumnFlag = { key: string; label: string; hint: string }; export type DeckPreset = { id: string; label(): string; + /** The new deck's name and the preset's row in settings (default: `label`). */ + name?(): string; + /** What the preset's columns are, for settings. */ + hint?(): string; /** Disabled (with this hint) when only one account exists. */ needsTwoAccounts?: () => string; columns(profiles: readonly string[]): Array>; diff --git a/packages/shell/src/panel/Appearance.tsx b/packages/shell/src/panel/Appearance.tsx new file mode 100644 index 0000000..c586f18 --- /dev/null +++ b/packages/shell/src/panel/Appearance.tsx @@ -0,0 +1,412 @@ +// Appearance: the theme gallery (live previews rendered from each theme document), per-group +// customization on top of the selected theme (fonts per role with the Google Fonts browser), +// account and pane themes, downloaded fonts, import/export of theme JSON and Custom CSS. The theme +// documents, the store and the miniature are the app's (`PanelSite.themes`). +import { useEffect, useRef, useState } from 'react'; +import { THEME_SCHEMA_URL } from '../../../runtime/src/themeApi.ts'; +import type { ThemeChoice } from '../../../runtime/src/themeChoice.ts'; +import { + FONT_CHOICES, MAX_IMAGE_CHARS, fontChoiceOf, googleFontsUsed, parseThemeJson, slug, + type Background, type FontRole, type FontRoleName, type Pattern, type ThemeOverrides, type ThemeSpec, +} from '../../../runtime/src/themeSpec.ts'; +import { AccountAvatar, accountName, useProfiles } from '../frame/AccountSwitcher.tsx'; +import { useT } from '../frame/hooks.ts'; +import { formatDate, t, tx } from '../frame/i18n.ts'; +import { ThemeDots } from '../frame/PaneTheme.tsx'; +import { shell, type WebParams } from '../frame/state.ts'; +import { assign } from '../frame/themeScopes.ts'; +import { tabProfile } from '../profileModel.ts'; +import { Button, ColorField, Row, Section, Segmented, Select, Slider, Toggle, useSettingsQuery, type Option } from './controls.tsx'; +import { bytesLabel, defaultWeights, loadCatalog, weightsLabel } from './fonts/catalog.ts'; +import { FontRoles } from './fonts/FontRoles.tsx'; +import { CustomCssEditor } from './Plugins.tsx'; +import { panelSite, panelThemes, type Notify } from './site.ts'; +import { useThemeState } from './themes.ts'; +import './builder.css'; + +const getError = (error: unknown) => error instanceof Error ? error.message : String(error); + +const CORNERS = [ + { value: 'square', label: 'wb.appearance.corners.square', radius: 0, button: 0 }, + { value: 'crisp', label: 'wb.appearance.corners.crisp', radius: 5, button: 5 }, + { value: 'soft', label: 'wb.appearance.corners.soft', radius: 12, button: 10 }, + { value: 'round', label: 'wb.appearance.corners.round', radius: 16, button: 9999 }, +] as const; +type BackgroundChoice = 'none' | 'glow' | Pattern | 'image'; +const backgrounds = (): Array> => [ + { value: 'none', label: t('wb.appearance.bg.none') }, { value: 'glow', label: t('wb.appearance.bg.glow') }, { value: 'dots', label: t('wb.appearance.bg.dots') }, { value: 'grid', label: t('wb.appearance.bg.grid') }, + { value: 'diagonal', label: t('wb.appearance.bg.diagonal') }, { value: 'scanlines', label: t('wb.appearance.bg.scanlines') }, { value: 'paper', label: t('wb.appearance.bg.paper') }, + { value: 'clouds', label: t('wb.appearance.bg.clouds') }, { value: 'image', label: t('wb.appearance.bg.image'), hint: t('wb.appearance.bg.imageHint') }, +]; + +const modeLabel = (theme: ThemeSpec) => theme.mode === 'auto' ? t('wb.appearance.mode.auto') : theme.mode === 'light' ? t('wb.appearance.mode.light') : t('wb.appearance.mode.dark'); +const fontLabel = (theme: ThemeSpec) => { + const family = theme.font.family; + const choices = panelThemes().fontChoices ?? FONT_CHOICES; + const choice = choices.find(item => item.id === fontChoiceOf(family, choices)); + return (choice?.key ? tx(choice.key, undefined, choice.label) : choice?.label) ?? family[0] ?? panelThemes().siteFont; +}; +/** Built-in themes have translated descriptions (`theme..description` in the app's catalog); imported ones keep their own. */ +export const themeDescription = (theme: ThemeSpec) => tx(`theme.${theme.id}.description`, undefined, theme.description); +const formatPercent = (value: number) => t('wb.appearance.percent', { value: value / 100 }); +const hasOverrides = (choice: ThemeChoice) => !!choice.accent || Object.keys(choice.overrides).length > 0; + +function download(name: string, text: string) { + const url = URL.createObjectURL(new Blob([text], { type: 'application/json' })); + const anchor = document.createElement('a'); + anchor.href = url; anchor.download = name; anchor.click(); + setTimeout(() => URL.revokeObjectURL(url), 1000); +} + +function backgroundFor(kind: BackgroundChoice, theme: ThemeSpec, image?: string): Background { + const base = panelThemes().draftColors; + const text = theme.colors?.text ?? '#8b98a5'; + const light = theme.mode === 'light'; + switch (kind) { + case 'none': return { kind: 'none' }; + case 'glow': return { kind: 'gradient', from: theme.colors?.page ?? theme.colors?.bg ?? base.bg, to: theme.colors?.page ?? theme.colors?.bg ?? base.bg, angle: 180, glow: theme.colors?.accent ?? base.accent }; + case 'image': return { kind: 'image', url: image ?? '', fit: 'cover', dim: light ? 0.55 : 0.6 }; + case 'clouds': return { kind: 'pattern', pattern: 'clouds', ink: light ? '#ffffff' : text, opacity: light ? 0.55 : 0.07, size: 220 }; + case 'dots': return { kind: 'pattern', pattern: 'dots', ink: text, opacity: 0.16, size: 18 }; + case 'grid': return { kind: 'pattern', pattern: 'grid', ink: text, opacity: 0.06, size: 28 }; + case 'diagonal': return { kind: 'pattern', pattern: 'diagonal', ink: text, opacity: 0.06, size: 10 }; + case 'scanlines': return { kind: 'pattern', pattern: 'scanlines', ink: theme.colors?.accent ?? text, opacity: 0.05, size: 4 }; + case 'paper': return { kind: 'pattern', pattern: 'paper', ink: light ? '#7a6a50' : text, opacity: 0.1, size: 180 }; + } +} +const backgroundChoice = (background: Background): BackgroundChoice => + background.kind === 'none' ? 'none' : background.kind === 'gradient' ? 'glow' : background.kind === 'image' ? 'image' : background.pattern; + +/** Asks the panel to show another section (the Theme Builder). */ +const openSection = (section: string) => window.dispatchEvent(new CustomEvent('bt-panel-section', { detail: section })); + +export function Appearance({ notify }: { notify: Notify }) { + const t = useT(); + const themes = panelThemes(); + const { allThemes, installFont, missingFonts, setChoice, setScopes } = themes.store; + const ThemePreview = themes.Preview; + const { ready, choice, scopes } = useThemeState(); + const [importing, setImporting] = useState(false); + const [asking, setAsking] = useState<{ theme: ThemeSpec; families: string[] } | null>(null); + const query = useSettingsQuery(); + + if (!ready) return null; + const effective = themes.catalog.resolve(choice); + const base = themes.catalog.base(choice); + const all = allThemes(choice); + const siteTheme = themes.catalog.defaultChoice.preset; + const suffix = themes.fileSuffix ?? '.theme.json'; + + const update = (next: ThemeChoice, commit = true) => setChoice(next, commit).catch(error => notify(getError(error), true)); + const override = (patch: ThemeOverrides, commit = true) => { + const overrides: ThemeOverrides = { ...choice.overrides }; + for (const [key, value] of Object.entries(patch) as Array<[keyof ThemeOverrides, unknown]>) { + (overrides as Record)[key] = key === 'background' ? value : { ...(choice.overrides[key] as object | undefined), ...(value as object) }; + } + return update({ ...choice, overrides }, commit); + }; + const setRole = (role: FontRoleName, next: FontRole, commit = true) => + override({ font: { roles: { ...(choice.overrides.font?.roles ?? {}), [role]: next } } }, commit); + + function select(id: string) { + if (id === choice.preset) return; + // Customizations belong to the theme they were made on; switching starts clean. + void update({ ...choice, preset: id, overrides: {}, accent: null }); + } + function remove(theme: ThemeSpec) { + const themes = choice.themes.filter(item => item.id !== theme.id); + void update({ ...choice, themes, ...(choice.preset === theme.id ? { preset: siteTheme, overrides: {}, accent: null } : {}) }).then(() => notify(t('wb.appearance.removedTheme', { name: theme.name }))); + } + function add(theme: ThemeSpec, message: string) { + let id = theme.id; + for (let n = 2; all.some(item => item.id === id); n++) id = `${theme.id.slice(0, 36)}-${n}`; + void update({ ...choice, themes: [...choice.themes, { ...theme, id }], preset: id, overrides: {}, accent: null }).then(() => notify(message)); + } + function exportTheme() { + const custom = hasOverrides(choice); + const doc: ThemeSpec = { ...effective, ...(custom ? { id: slug(`${effective.name} custom`), name: t('wb.appearance.customName', { name: effective.name }) } : {}) }; + // `$schema` lets editors validate and complete the file; imports ignore it. + download(`${doc.id}${suffix}`, JSON.stringify({ $schema: THEME_SCHEMA_URL, ...doc }, null, 2)); + } + function saveAsNew() { + const name = t('wb.appearance.savedName', { name: base.name }); + add({ ...effective, id: slug(`${base.name} custom`), name, author: t('wb.appearance.you'), description: t('wb.appearance.basedOn', { name: base.name }) }, t('wb.appearance.saved', { name })); + } + /** An imported theme that names Google fonts asks before anything is downloaded. */ + function imported(theme: ThemeSpec, warnings: string[]) { + setImporting(false); + add(theme, `${t('wb.appearance.imported', { name: theme.name })}${warnings.length ? ` ${warnings.join(' ')}` : ''}`); + const families = missingFonts(theme); + if (families.length) setAsking({ theme, families }); + } + async function downloadFonts(families: string[]) { + setAsking(null); + const catalog = await loadCatalog(); + for (const family of families) { + const font = catalog.find(item => item.family === family); + try { + await installFont(family, font ? defaultWeights(font) : { kind: 'list', values: [400, 700] }); + notify(t('wb.appearance.downloadedFont', { family })); + } catch (error) { notify(`${family}: ${getError(error)}`, true); } + } + } + + const cornerValue = CORNERS.find(corner => corner.radius === effective.shape.radius && corner.button === effective.shape.button)?.value ?? null; + const timeline = effective.layout.cards ? 'cards' : effective.layout.frame ? 'framed' : 'flat'; + + async function pickImage(file: File | undefined) { + if (!file) return; + if (!/^image\/(png|jpeg|webp|gif|avif)$/.test(file.type)) { notify(t('wb.appearance.imageType'), true); return; } + const url = await new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(String(reader.result)); reader.onerror = () => reject(reader.error); reader.readAsDataURL(file); }); + if (url.length > MAX_IMAGE_CHARS) { notify(t('wb.appearance.imageTooLarge'), true); return; } + void override({ background: backgroundFor('image', effective, url) }); + } + + const searching = !!query; + return <> + {!searching &&
+ + + + }> + {importing && setImporting(false)} onImport={imported}/>} + {asking &&
+
+ {t('wb.appearance.askFontsTitle', { name: asking.theme.name, fonts: asking.families.join(', ') })} +

{t('wb.appearance.askFontsText', { count: asking.families.length })}

+
+
+
} +
+ {all.map(theme => { + const on = theme.id === choice.preset; + const isImported = choice.themes.some(item => item.id === theme.id); + return
+ + {isImported && } +
; + })} +
+
} + +
+ + + : undefined}> + + void update({ ...choice, accent })}/> + + + + + + formatPercent(v)} + onChange={v => void override({ font: { scale: v / 100 } }, false)} onCommit={v => void override({ font: { scale: v / 100 } })}/> + + + = 750 ? 800 : effective.font.bold >= 675 ? 700 : 600} + onChange={bold => void override({ font: { bold } })} options={[{ value: 600, label: t('wb.appearance.bold.medium') }, { value: 700, label: t('wb.appearance.bold.bold') }, { value: 800, label: t('wb.appearance.bold.heavy') }]}/> + + + { const corner = CORNERS.find(item => item.value === value)!; void override({ shape: { radius: corner.radius, button: corner.button } }); }} + options={CORNERS.map(corner => ({ value: corner.value, label: t(corner.label) }))}/> + + + void override({ shape: { avatar } })} + options={[{ value: 'circle', label: t('wb.appearance.avatars.circle') }, { value: 'rounded', label: t('wb.appearance.avatars.rounded') }, { value: 'square', label: t('wb.appearance.corners.square') }]}/> + + + void override({ layout: { density } })} + options={[{ value: 'compact', label: t('wb.appearance.density.compact') }, { value: 'default', label: t('wb.appearance.density.default') }, { value: 'comfortable', label: t('wb.appearance.density.roomy') }]}/> + + + void override({ layout: { cards: value === 'cards', frame: value === 'framed' } })} + options={[{ value: 'flat', label: t('wb.appearance.timeline.flat') }, { value: 'framed', label: t('wb.appearance.timeline.framed') }, { value: 'cards', label: t('wb.appearance.timeline.cards') }]}/> + + + t('wb.appearance.px', { value: v })} + onChange={column => void override({ layout: { column } }, false)} onCommit={column => void override({ layout: { column } })}/> + + + t('wb.appearance.px', { value: v })} + onChange={sidebar => void override({ layout: { sidebar } }, false)} onCommit={sidebar => void override({ layout: { sidebar } })}/> + + +
+ { void pickImage(event.target.files?.[0]); event.target.value = ''; }}/> +
+
+ {effective.background.kind === 'image' && + formatPercent(v)} + onChange={v => void override({ background: { ...(effective.background as Extract), dim: v / 100 } }, false)} + onCommit={v => void override({ background: { ...(effective.background as Extract), dim: v / 100 } })}/> + } + + void override({ effects: { motion } })} + options={[{ value: 0, label: t('wb.common.off') }, { value: 140, label: t('wb.appearance.motion.subtle') }, { value: 260, label: t('wb.appearance.motion.lively') }]}/> + + + void override({ effects: { hover } })} + options={[{ value: 'none', label: t('wb.appearance.hover.none') }, { value: 'tint', label: t('wb.appearance.hover.tint') }, { value: 'lift', label: t('wb.appearance.hover.lift') }, { value: 'glow', label: t('wb.appearance.bg.glow') }]}/> + + + void override({ effects: { crt } })}/> + + { void override({ css: { text } }); notify(t('wb.appearance.cssApplied', { name: base.name })); }}/> +
+ +
+ + void setScopes({ ...scopes, chrome: on ? 'theme' : 'own' }).catch(error => notify(getError(error), true))}/> + + + +
+ + + + ; +} + +/** Theme choices for a scope row: follow (the level above) plus every theme with its swatch. */ +function scopeOptions(follow: string): Array> { + // Called during render of components that use useT(), so the labels follow the language. + return [{ value: '', label: follow }, ...panelThemes().store.allThemes().map(theme => ({ value: theme.id, label: theme.name, icon: }))]; +} + +function AccountThemes({ notify }: { notify: Notify }) { + const t = useT(); + const { setScopes, themeName, themeState } = panelThemes().store; + const profiles = useProfiles(); + const { scopes, choice } = useThemeState(); + return +
+ {profiles.profiles.map(profile =>
+ {accountName(profile)}{scopes.profiles[profile.id] ? t('wb.appearance.ownTheme') : t('wb.appearance.followsApp', { name: themeName(choice.preset) })} + void setScopes(assign(themeState().scopes, 'panes', panel.id, id || null)).catch(error => notify(getError(error), true))}/> +
; + })} +
} +
; +} + +function DownloadedFonts({ notify }: { notify: Notify }) { + const t = useT(); + const { removeFont } = panelThemes().store; + const { fonts } = useThemeState(); + const query = useSettingsQuery(); + const title = t('wb.appearance.downloaded'); + if (query && !`downloaded fonts google fonts typeface remove storage ${title}`.toLowerCase().includes(query.toLowerCase().trim())) return null; + const total = fonts.reduce((sum, font) => sum + font.bytes, 0); + return
+ + {fonts.length > 0 &&
    + {fonts.map(font =>
  • + {font.family}
    {weightsLabel(font.weights)} · {bytesLabel(font.bytes)}
    + {formatDate(font.installedAt, { dateStyle: 'medium' })} + +
  • )} +
} +
+
; +} + +/** The selected theme's own CSS: travels with the theme (export, Save as theme); switching themes starts clean, like every customization. */ +function ThemeCssEditor({ css, onApply }: { css: string; onApply(text: string): void }) { + const t = useT(); + const [text, setText] = useState(css); + const query = useSettingsQuery(); + useEffect(() => setText(css), [css]); + const label = t('wb.appearance.themeCss'); + if (query && !`theme css stylesheet style code custom ${label}`.toLowerCase().includes(query.toLowerCase().trim())) return null; + const dirty = text !== css; + return +
+