// 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 { Badge, Button, ColorField, Row, Section, Segmented, Select, Slider, Toggle, useSettingsQuery, type Option } from './controls.tsx'; import { IconPackImport, IconPackReview } from './IconPackInstall.tsx'; import type { IconPack } from '../../../runtime/src/themeIcons.ts'; import { themeDoctor, type DoctorAdvice } from '../../../runtime/src/themeDoctor.ts'; 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 [packReview, setPackReview] = useState<{ pack: IconPack; warnings: string[]; bytes: number } | 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 })}/> {themes.iconPacks?.length ?
{ if (kind === 'image') document.getElementById('bt-bg-file')?.click(); else void override({ background: backgroundFor(kind, effective) }); }}/> { 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))}/>
{(panelSite().appearance?.extra ?? []).map((Extra, index) => window.dispatchEvent(new CustomEvent('bt-panel-section', { detail: id }))}/>)} ; } /** Theme choices for a scope row: follow (the level above) plus every theme with its swatch. */ /** The theme doctor's full report on the theme as it is now: every finding, where it is, what it found, how to fix it. Advice only. */ function DoctorReport({ theme }: { theme: ThemeSpec }) { const t = useT(); const advice = themeDoctor(theme); const words = (item: DoctorAdvice, part: 'found' | 'fix') => t(`wb.doctor.${item.key}.${part}`, item.params); return
{t('wb.doctor.count', { count: advice.length })}}> {advice.length === 0 ?

{t('wb.doctor.empty')}

:
    {advice.map((item, index) =>
  • {t(`wb.doctor.kind.${item.kind}`)}{words(item, 'found')} {t('wb.doctor.where')}: {item.where} {t('wb.doctor.fix')}: {words(item, 'fix')}
  • )}
}
; } 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