shell: the panel, createPanel(site) (moved from wayBetter for X)
packages/shell/src/panel (waybetter/shell/panel): an app's own tab. An app describes itself (PanelSite: brand and the home page's words, its own sections and their order, its theme store, catalog and the preview component a theme document is drawn in, Make's examples and docs, the install controller, its languages, what its native side serves) and createPanel returns the component for ShellSite.panel. It is in the shell package because it is drawn in the frame and shares its stores, native bridge and language. - Panel.tsx (header, settings search over every settings section, navigation, toasts; Accounts and Updates), nav.ts (which built-in sections an app gets: each shows only when the app serves what it needs; the app's sections in its order), Home.tsx (hero, highlights, About from the app's data), controls.tsx + panel.css. - Appearance.tsx, ThemeBuilder.tsx + builderModel.ts + builder.css, fonts/ (FontBrowser, FontRoles, catalog, the offline Google Fonts list; scripts/google-fonts-catalog.mjs regenerates it): the theme documents are the runtime's, the store, catalog, accents, draft palette, file suffix and preview are the app's (PanelSite.themes). - Plugins.tsx (the plugins list and custom CSS over the host's plugins_*/custom_css_*), StoreSection.tsx, MakePanel.tsx + makeModel.ts + MarkdownDoc.tsx + markdown.ts + make.css (the examples, the theme file and the docs are the app's), Settings.tsx (links and session over settings_get/set with `siteLinks`, keyword alerts, the media panel), FeatureToggles.tsx (useFeatures + FeatureGroups over features_get/set: the app names its flags and groups), PowerSettings.tsx (deck defaults from site.deck: its flags and presets; DeckPreset gets `name` and `hint`), BackupPanel.tsx + backup.css, DeveloperPanel.tsx, LanguageSettings.tsx, compare.ts. - frame: language.ts (createLanguage: follow the site / the system / one language, i18n_set; moved from the app), appI18n.ts (createAppI18n: the app's typed i18n instance, useT, dates and numbers; the app passes React's useSyncExternalStore), formatDate in i18n.ts (ShellI18n.date). - tests/panel.test.ts: every panel key has English and is used, sections per app, the builder model, the font catalog, plugin header rules, the UI kit demos, Markdown, compare. - npm package: exports ./shell/panel, ./shell/panel/*, ./shell/panel/*.css; the build is scripts/build.mjs (the shell is compiled with the runtime sources it imports under one root and its imports are pointed at dist/runtime; stylesheets and the font list are copied). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
7a3f23aa82
commit
ad2a3ad375
44 changed files with 4864 additions and 2 deletions
34
packages/shell/scripts/google-fonts-catalog.mjs
Normal file
34
packages/shell/scripts/google-fonts-catalog.mjs
Normal file
|
|
@ -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`);
|
||||||
101
packages/shell/src/frame/appI18n.ts
Normal file
101
packages/shell/src/frame/appI18n.ts
Normal file
|
|
@ -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<MessageKey>({
|
||||||
|
// 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<Snapshot>(subscribe: (listener: () => void) => () => void, getSnapshot: () => Snapshot, getServerSnapshot?: () => Snapshot): Snapshot;
|
||||||
|
/** A development build: untranslated and malformed messages are logged. */
|
||||||
|
dev?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type AppI18n<Key extends string> = {
|
||||||
|
i18n: I18n<Key>;
|
||||||
|
/** Registers how catalogs load (the app's lazy imports; tests may pass a map). */
|
||||||
|
setCatalogLoader(load: (locale: string) => Promise<Messages | null>): 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<Key extends string>(options: AppI18nOptions): AppI18n<Key> {
|
||||||
|
let loader: ((locale: string) => Promise<Messages | null>) | null = null;
|
||||||
|
const i18n = createI18n<Key>({
|
||||||
|
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),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
@ -15,6 +15,7 @@ export type ShellI18n = {
|
||||||
onChange(listener: (locale: string) => void): () => void;
|
onChange(listener: (locale: string) => void): () => void;
|
||||||
number(value: number, options?: Intl.NumberFormatOptions): string;
|
number(value: number, options?: Intl.NumberFormatOptions): string;
|
||||||
relative(value: number, unit: Intl.RelativeTimeFormatUnit): string;
|
relative(value: number, unit: Intl.RelativeTimeFormatUnit): string;
|
||||||
|
date(value: string | number | Date, options?: Intl.DateTimeFormatOptions): string;
|
||||||
};
|
};
|
||||||
|
|
||||||
let current: ShellI18n | null = null;
|
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);
|
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. */
|
/** "3 minutes ago" style text for a timestamp in the active language. */
|
||||||
export function relativeTime(then: number, now = Date.now()): string {
|
export function relativeTime(then: number, now = Date.now()): string {
|
||||||
if (!current) return new Date(then).toISOString();
|
if (!current) return new Date(then).toISOString();
|
||||||
|
|
|
||||||
|
|
@ -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 { shell, setOverlay, scheduleSync, flushSync, isWeb, tabAction, setProfiles, type TabParams, type WebParams } from './state.ts';
|
||||||
export type { PaletteItem, PaletteAction, PaletteContext } from './paletteModel.ts';
|
export type { PaletteItem, PaletteAction, PaletteContext } from './paletteModel.ts';
|
||||||
export { Icon, Avatar, ICONS, type IconName } from './icons.tsx';
|
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';
|
||||||
|
|
|
||||||
165
packages/shell/src/frame/language.ts
Normal file
165
packages/shell/src/frame/language.ts
Normal file
|
|
@ -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 `<html lang>`), "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<string>;
|
||||||
|
resolved(prefixes?: readonly string[]): Record<string, string>;
|
||||||
|
};
|
||||||
|
|
||||||
|
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<typeof createLanguage>;
|
||||||
|
|
||||||
|
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<unknown> = 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<void> {
|
||||||
|
current.native = isNative;
|
||||||
|
const stored = readStored();
|
||||||
|
current.siteLang = stored?.siteLang ?? null;
|
||||||
|
let fromNative: NativeLanguage | null = null;
|
||||||
|
if (isNative) {
|
||||||
|
try { fromNative = await native.invoke<NativeLanguage>('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<void> {
|
||||||
|
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<void> {
|
||||||
|
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<void> {
|
||||||
|
current.preference = matchLocale([tag], available);
|
||||||
|
await apply();
|
||||||
|
}
|
||||||
|
|
||||||
|
return { initShell, initFollower, state, set, subscribe, forcePreview, storageKey };
|
||||||
|
}
|
||||||
|
|
@ -41,6 +41,10 @@ export type ColumnFlag = { key: string; label: string; hint: string };
|
||||||
export type DeckPreset = {
|
export type DeckPreset = {
|
||||||
id: string;
|
id: string;
|
||||||
label(): 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. */
|
/** Disabled (with this hint) when only one account exists. */
|
||||||
needsTwoAccounts?: () => string;
|
needsTwoAccounts?: () => string;
|
||||||
columns(profiles: readonly string[]): Array<Pick<DeckColumn, 'profile' | 'source'>>;
|
columns(profiles: readonly string[]): Array<Pick<DeckColumn, 'profile' | 'source'>>;
|
||||||
|
|
|
||||||
412
packages/shell/src/panel/Appearance.tsx
Normal file
412
packages/shell/src/panel/Appearance.tsx
Normal file
|
|
@ -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<Option<BackgroundChoice>> => [
|
||||||
|
{ 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.<id>.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<string, unknown>)[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<string>((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 && <Section title={t('wb.appearance.theme')} id="themes" hint={t('wb.appearance.themeHint')}
|
||||||
|
action={<div className="bt-inline">
|
||||||
|
<Button size="sm" tone="ghost" onClick={() => setImporting(!importing)} icon={<Glyph d="M8 2v8m0 0L5 7m3 3 3-3M3 13h10"/>}>{t('wb.common.import')}</Button>
|
||||||
|
<Button size="sm" tone="ghost" onClick={exportTheme} icon={<Glyph d="M8 11V3m0 0L5 6m3-3 3 3M3 13h10"/>}>{t('wb.common.export')}</Button>
|
||||||
|
<Button size="sm" tone="primary" onClick={() => openSection('builder')} icon={<Glyph d="M3 13l.6-2.6L10.5 3.5l2 2-6.9 6.9zM9 5l2 2"/>}>{t('wb.panel.section.builder')}</Button>
|
||||||
|
</div>}>
|
||||||
|
{importing && <ImportPanel onCancel={() => setImporting(false)} onImport={imported}/>}
|
||||||
|
{asking && <div className="bt-import wb-ask" role="alertdialog" aria-label={t('wb.appearance.askFonts')}>
|
||||||
|
<div className="bt-import-drop">
|
||||||
|
<strong>{t('wb.appearance.askFontsTitle', { name: asking.theme.name, fonts: asking.families.join(', ') })}</strong>
|
||||||
|
<p>{t('wb.appearance.askFontsText', { count: asking.families.length })}</p>
|
||||||
|
<div className="bt-inline"><Button size="sm" tone="primary" onClick={() => void downloadFonts(asking.families)}>{t('wb.panel.updates.download')}</Button><Button size="sm" tone="ghost" onClick={() => setAsking(null)}>{t('wb.common.notNow')}</Button></div>
|
||||||
|
</div>
|
||||||
|
</div>}
|
||||||
|
<div className="bt-gallery" role="radiogroup" aria-label={t('wb.appearance.theme')}>
|
||||||
|
{all.map(theme => {
|
||||||
|
const on = theme.id === choice.preset;
|
||||||
|
const isImported = choice.themes.some(item => item.id === theme.id);
|
||||||
|
return <div key={theme.id} className={`bt-theme ${on ? 'is-on' : ''}`}>
|
||||||
|
<button type="button" role="radio" aria-checked={on} className="bt-theme-hit" onClick={() => select(theme.id)} aria-label={`${theme.name}. ${themeDescription(theme)}`}>
|
||||||
|
<ThemePreview theme={on ? effective : theme}/>
|
||||||
|
<span className="bt-theme-info">
|
||||||
|
<span className="bt-theme-title"><strong>{theme.name}</strong>{on && <span className="bt-theme-check" aria-hidden="true"><Glyph d="m4 8.5 2.5 2.5L12 5.5"/></span>}</span>
|
||||||
|
<small>{themeDescription(theme)}</small>
|
||||||
|
<span className="bt-theme-tags"><em>{modeLabel(theme)}</em><em>{fontLabel(theme)}</em>{theme.layout.cards && <em>{t('wb.appearance.timeline.cards')}</em>}{googleFontsUsed(theme).length > 0 && <em>Google Fonts</em>}{isImported && <em className="is-accent">{t('wb.appearance.yours')}</em>}{theme.css && <em>CSS</em>}</span>
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
{isImported && <button type="button" className="bt-theme-remove" aria-label={t('wb.appearance.removeNamed', { name: theme.name })} title={t('wb.appearance.removeTheme')} onClick={() => remove(theme)}><Glyph d="m4.5 4.5 7 7m0-7-7 7"/></button>}
|
||||||
|
</div>;
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</Section>}
|
||||||
|
|
||||||
|
<Section title={searching ? t('wb.appearance.theme') : t('wb.appearance.customize', { name: base.name })} id="customize"
|
||||||
|
hint={searching ? undefined : t('wb.appearance.customizeHint')}
|
||||||
|
action={!searching && hasOverrides(choice) ? <div className="bt-inline">
|
||||||
|
<Button size="sm" tone="ghost" onClick={() => void update({ ...choice, overrides: {}, accent: null })}>{t('wb.common.reset')}</Button>
|
||||||
|
<Button size="sm" onClick={saveAsNew}>{t('wb.appearance.saveAsTheme')}</Button>
|
||||||
|
</div> : undefined}>
|
||||||
|
<Row label={t('wb.appearance.accent')} hint={t('wb.appearance.accentHint')} keywords="color colour highlight link" wide>
|
||||||
|
<ColorField label={t('wb.appearance.accentColor')} value={choice.accent} swatches={[...themes.accents]} autoLabel={t('wb.appearance.theme')} onChange={accent => void update({ ...choice, accent })}/>
|
||||||
|
</Row>
|
||||||
|
<Row label={t('wb.appearance.fonts')} hint={t('wb.appearance.fontsHint')}
|
||||||
|
keywords="typeface typography family font google fonts post text heading numbers code interface window dialogs" wide>
|
||||||
|
<FontRoles font={effective.font} onRole={setRole} compact/>
|
||||||
|
</Row>
|
||||||
|
<Row label={t('wb.appearance.textSize')} hint={t('wb.appearance.textSizeHint')} keywords="font scale bigger smaller zoom">
|
||||||
|
<Slider label={t('wb.appearance.textSize')} min={85} max={120} value={Math.round(effective.font.scale * 100)} format={v => formatPercent(v)}
|
||||||
|
onChange={v => void override({ font: { scale: v / 100 } }, false)} onCommit={v => void override({ font: { scale: v / 100 } })}/>
|
||||||
|
</Row>
|
||||||
|
<Row label={t('wb.appearance.bold')} hint={t('wb.appearance.boldHint')} keywords="font weight heavy">
|
||||||
|
<Segmented label={t('wb.appearance.bold')} size="sm" value={effective.font.bold >= 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') }]}/>
|
||||||
|
</Row>
|
||||||
|
<Row label={t('wb.appearance.corners')} hint={t('wb.appearance.cornersHint')} keywords="radius rounded square shape">
|
||||||
|
<Segmented label={t('wb.appearance.corners')} size="sm" value={cornerValue} onChange={value => { 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) }))}/>
|
||||||
|
</Row>
|
||||||
|
<Row label={t('wb.appearance.avatars')} keywords="profile picture shape">
|
||||||
|
<Segmented label={t('wb.appearance.avatars')} size="sm" value={effective.shape.avatar} onChange={avatar => 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') }]}/>
|
||||||
|
</Row>
|
||||||
|
<Row label={t('wb.appearance.density')} hint={t('wb.appearance.densityHint')} keywords="compact spacing padding">
|
||||||
|
<Segmented label={t('wb.appearance.density')} size="sm" value={effective.layout.density} onChange={density => 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') }]}/>
|
||||||
|
</Row>
|
||||||
|
<Row label={t('wb.appearance.timeline')} hint={t('wb.appearance.timelineHint')} keywords="cards layout frame">
|
||||||
|
<Segmented label={t('wb.appearance.timelineStyle')} size="sm" value={timeline} onChange={value => 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') }]}/>
|
||||||
|
</Row>
|
||||||
|
<Row label={t('wb.appearance.timelineWidth')} keywords="column layout wide narrow">
|
||||||
|
<Slider label={t('wb.appearance.timelineWidth')} min={520} max={820} step={10} value={effective.layout.column} format={v => t('wb.appearance.px', { value: v })}
|
||||||
|
onChange={column => void override({ layout: { column } }, false)} onCommit={column => void override({ layout: { column } })}/>
|
||||||
|
</Row>
|
||||||
|
<Row label={t('wb.appearance.sidebarWidth')} keywords="column layout trends">
|
||||||
|
<Slider label={t('wb.appearance.sidebarWidth')} min={290} max={400} step={10} value={effective.layout.sidebar} format={v => t('wb.appearance.px', { value: v })}
|
||||||
|
onChange={sidebar => void override({ layout: { sidebar } }, false)} onCommit={sidebar => void override({ layout: { sidebar } })}/>
|
||||||
|
</Row>
|
||||||
|
<Row label={t('wb.appearance.background')} hint={t('wb.appearance.backgroundHint')} keywords="wallpaper pattern image photo canvas">
|
||||||
|
<div className="bt-inline">
|
||||||
|
<Select label={t('wb.appearance.background')} value={backgroundChoice(effective.background)} options={backgrounds()} width={170}
|
||||||
|
onChange={kind => { if (kind === 'image') document.getElementById('bt-bg-file')?.click(); else void override({ background: backgroundFor(kind, effective) }); }}/>
|
||||||
|
<input id="bt-bg-file" type="file" hidden accept="image/png,image/jpeg,image/webp,image/gif,image/avif" onChange={event => { void pickImage(event.target.files?.[0]); event.target.value = ''; }}/>
|
||||||
|
</div>
|
||||||
|
</Row>
|
||||||
|
{effective.background.kind === 'image' && <Row label={t('wb.appearance.dim')} hint={t('wb.appearance.dimHint')} keywords="background image">
|
||||||
|
<Slider label={t('wb.appearance.dim')} min={35} max={95} value={Math.round(effective.background.dim * 100)} format={v => formatPercent(v)}
|
||||||
|
onChange={v => void override({ background: { ...(effective.background as Extract<Background, { kind: 'image' }>), dim: v / 100 } }, false)}
|
||||||
|
onCommit={v => void override({ background: { ...(effective.background as Extract<Background, { kind: 'image' }>), dim: v / 100 } })}/>
|
||||||
|
</Row>}
|
||||||
|
<Row label={t('wb.appearance.motion')} hint={t('wb.appearance.motionHint')} keywords="animation transition">
|
||||||
|
<Segmented label={t('wb.appearance.motion')} size="sm" value={effective.effects.motion === 0 ? 0 : effective.effects.motion < 200 ? 140 : 260} onChange={motion => 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') }]}/>
|
||||||
|
</Row>
|
||||||
|
<Row label={t('wb.appearance.hover')} hint={t('wb.appearance.hoverHint')} keywords="effect highlight lift glow">
|
||||||
|
<Segmented label={t('wb.appearance.hoverEffect')} size="sm" value={effective.effects.hover} onChange={hover => 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') }]}/>
|
||||||
|
</Row>
|
||||||
|
<Row label={t('wb.appearance.crt')} hint={t('wb.appearance.crtHint')} keywords="retro terminal effect">
|
||||||
|
<Toggle label={t('wb.appearance.crt')} checked={effective.effects.crt} onChange={crt => void override({ effects: { crt } })}/>
|
||||||
|
</Row>
|
||||||
|
<ThemeCssEditor key={choice.preset} css={effective.css} onApply={text => { void override({ css: { text } }); notify(t('wb.appearance.cssApplied', { name: base.name })); }}/>
|
||||||
|
</Section>
|
||||||
|
|
||||||
|
<Section title={t('wb.appearance.scopes')} id="theme-scopes" hint={searching ? undefined : t('wb.appearance.scopesHint')}>
|
||||||
|
<Row label={t('wb.appearance.chrome')} hint={t('wb.appearance.chromeHint')}
|
||||||
|
keywords="chrome window tabs titlebar panel colors own style">
|
||||||
|
<Toggle label={t('wb.appearance.chrome')} checked={scopes.chrome === 'theme'} onChange={on => void setScopes({ ...scopes, chrome: on ? 'theme' : 'own' }).catch(error => notify(getError(error), true))}/>
|
||||||
|
</Row>
|
||||||
|
<AccountThemes notify={notify}/>
|
||||||
|
<PaneThemes notify={notify}/>
|
||||||
|
</Section>
|
||||||
|
|
||||||
|
<DownloadedFonts notify={notify}/>
|
||||||
|
<CustomCssEditor notify={notify}/>
|
||||||
|
</>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Theme choices for a scope row: follow (the level above) plus every theme with its swatch. */
|
||||||
|
function scopeOptions(follow: string): Array<Option<string>> {
|
||||||
|
// 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: <ThemeDots theme={theme}/> }))];
|
||||||
|
}
|
||||||
|
|
||||||
|
function AccountThemes({ notify }: { notify: Notify }) {
|
||||||
|
const t = useT();
|
||||||
|
const { setScopes, themeName, themeState } = panelThemes().store;
|
||||||
|
const profiles = useProfiles();
|
||||||
|
const { scopes, choice } = useThemeState();
|
||||||
|
return <Row label={t('wb.panel.section.accounts')} hint={t('wb.appearance.accountsHint')} keywords="account profile per account theme login" wide>
|
||||||
|
<div className="wb-scope-list">
|
||||||
|
{profiles.profiles.map(profile => <div key={profile.id} className="wb-scope">
|
||||||
|
<span className="wb-scope-who"><AccountAvatar profile={profile} size={26}/><span><b>{accountName(profile)}</b><small>{scopes.profiles[profile.id] ? t('wb.appearance.ownTheme') : t('wb.appearance.followsApp', { name: themeName(choice.preset) })}</small></span></span>
|
||||||
|
<Select label={t('wb.appearance.themeFor', { name: accountName(profile) })} value={scopes.profiles[profile.id] ?? ''} width={210} options={scopeOptions(t('wb.appearance.followApp'))}
|
||||||
|
onChange={id => void setScopes(assign(themeState().scopes, 'profiles', profile.id, id || null)).catch(error => notify(getError(error), true))}/>
|
||||||
|
</div>)}
|
||||||
|
</div>
|
||||||
|
</Row>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Open site panes, each with the theme it shows and where that comes from. */
|
||||||
|
function PaneThemes({ notify }: { notify: Notify }) {
|
||||||
|
const t = useT();
|
||||||
|
const { setScopes, tabTheme, themeName, themeState } = panelThemes().store;
|
||||||
|
const { scopes } = useThemeState();
|
||||||
|
const [, refresh] = useState(0);
|
||||||
|
useEffect(() => {
|
||||||
|
const api = shell.api;
|
||||||
|
if (!api) return;
|
||||||
|
const bump = () => refresh(n => n + 1);
|
||||||
|
const subs = [api.onDidAddPanel(bump), api.onDidRemovePanel(bump), api.onDidLayoutChange(bump)];
|
||||||
|
return () => subs.forEach(sub => sub.dispose());
|
||||||
|
}, []);
|
||||||
|
const panes = (shell.api?.panels ?? []).filter(panel => (panel.params as WebParams | undefined)?.kind === 'web');
|
||||||
|
return <Row label={t('wb.appearance.panes')} hint={panes.length ? t('wb.appearance.panesHint') : t('wb.appearance.panesEmpty')} keywords="pane split tab per pane theme" wide>
|
||||||
|
{panes.length > 0 && <div className="wb-scope-list">
|
||||||
|
{panes.map(panel => {
|
||||||
|
const params = panel.params as WebParams;
|
||||||
|
const profile = tabProfile(shell.profiles, params.profile);
|
||||||
|
const current = tabTheme({ id: panel.id, profile: profile.id });
|
||||||
|
return <div key={panel.id} className="wb-scope">
|
||||||
|
<span className="wb-scope-who"><ThemeDots theme={current.theme}/><span><b>{panel.api.title || params.url}</b><small>{accountName(profile)} · {current.source === 'pane' ? t('wb.appearance.ownTheme') : current.source === 'account' ? t('wb.appearance.accountTheme', { name: themeName(current.id) }) : t('wb.appearance.appTheme', { name: themeName(current.id) })}</small></span></span>
|
||||||
|
<Select label={t('wb.appearance.themeFor', { name: panel.api.title || t('wb.appearance.pane') })} value={scopes.panes[panel.id] ?? ''} width={210} options={scopeOptions(t('wb.appearance.followAccount'))}
|
||||||
|
onChange={id => void setScopes(assign(themeState().scopes, 'panes', panel.id, id || null)).catch(error => notify(getError(error), true))}/>
|
||||||
|
</div>;
|
||||||
|
})}
|
||||||
|
</div>}
|
||||||
|
</Row>;
|
||||||
|
}
|
||||||
|
|
||||||
|
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 <Section title={title} id="fonts" hint={fonts.length ? t('wb.appearance.downloadedHint', { count: fonts.length, size: bytesLabel(total) }) : t('wb.appearance.downloadedEmpty')}>
|
||||||
|
<Row label={fonts.length ? t('wb.appearance.families') : t('wb.appearance.noneYet')} hint={t('wb.appearance.familiesHint')} keywords="google fonts downloaded remove" wide>
|
||||||
|
{fonts.length > 0 && <ul className="wb-fontlist">
|
||||||
|
{fonts.map(font => <li key={font.family}>
|
||||||
|
<span><b style={{ fontFamily: `"${font.family}", system-ui` }}>{font.family}</b><br/><small>{weightsLabel(font.weights)} · {bytesLabel(font.bytes)}</small></span>
|
||||||
|
<small>{formatDate(font.installedAt, { dateStyle: 'medium' })}</small>
|
||||||
|
<Button size="sm" tone="ghost" onClick={() => void removeFont(font.family).then(() => notify(t('wb.appearance.removedFont', { family: font.family }))).catch(error => notify(getError(error), true))}>{t('wb.common.remove')}</Button>
|
||||||
|
</li>)}
|
||||||
|
</ul>}
|
||||||
|
</Row>
|
||||||
|
</Section>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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 <Row label={label} hint={t('wb.appearance.themeCssHint')} keywords="css stylesheet style code custom" wide>
|
||||||
|
<div className="bt-code is-compact" style={{ width: '100%' }}>
|
||||||
|
<textarea aria-label={t('wb.appearance.themeCssLabel')} spellCheck={false} value={text} placeholder={panelSite().cssExamples?.theme ?? '/* CSS that travels with this theme */'}
|
||||||
|
onChange={event => setText(event.target.value)}
|
||||||
|
onKeyDown={event => { if ((event.ctrlKey || event.metaKey) && event.key === 's') { event.preventDefault(); if (dirty) onApply(text); } }}/>
|
||||||
|
<div className="bt-code-bar">
|
||||||
|
<small>{t('wb.appearance.cssLines', { count: text.split('\n').length })}</small>
|
||||||
|
{dirty && <Button size="sm" tone="ghost" onClick={() => setText(css)}>{t('wb.common.discard')}</Button>}
|
||||||
|
<Button size="sm" tone="primary" disabled={!dirty} onClick={() => onApply(text)}>{t('wb.common.apply')}</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Row>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function Glyph({ d }: { d: string }) {
|
||||||
|
return <svg width="14" height="14" viewBox="0 0 16 16" aria-hidden="true"><path d={d} fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></svg>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ImportPanel({ onImport, onCancel }: { onImport(theme: ThemeSpec, warnings: string[]): void; onCancel(): void }) {
|
||||||
|
const t = useT();
|
||||||
|
const [text, setText] = useState('');
|
||||||
|
const [error, setError] = useState('');
|
||||||
|
const file = useRef<HTMLInputElement>(null);
|
||||||
|
const run = (json: string) => {
|
||||||
|
const parsed = parseThemeJson(json);
|
||||||
|
if ('error' in parsed) { setError(parsed.error); return; }
|
||||||
|
onImport(parsed.theme, parsed.warnings);
|
||||||
|
};
|
||||||
|
return <div className="bt-import">
|
||||||
|
<div className="bt-import-drop" onDragOver={event => event.preventDefault()}
|
||||||
|
onDrop={event => { event.preventDefault(); void event.dataTransfer.files[0]?.text().then(run); }}>
|
||||||
|
<strong>{t('wb.appearance.importTitle')}</strong>
|
||||||
|
<p>{t('wb.appearance.importText')}</p>
|
||||||
|
<div className="bt-inline"><Button size="sm" tone="primary" onClick={() => file.current?.click()}>{t('wb.common.chooseFile')}</Button><Button size="sm" tone="ghost" onClick={onCancel}>{t('wb.common.cancel')}</Button></div>
|
||||||
|
<input ref={file} type="file" hidden accept="application/json,.json" onChange={event => { void event.target.files?.[0]?.text().then(run); event.target.value = ''; }}/>
|
||||||
|
</div>
|
||||||
|
<div className="bt-code is-compact">
|
||||||
|
<textarea aria-label={t('wb.appearance.themeJson')} spellCheck={false} placeholder={`${t('wb.appearance.pasteJson')}\n{ "name": "My theme", "colors": { … } }`} value={text} onChange={event => { setText(event.target.value); setError(''); }}/>
|
||||||
|
<div className="bt-code-bar">
|
||||||
|
{error ? <small className="is-error" role="alert">{error}</small> : <small>{t('wb.appearance.importSafe')}</small>}
|
||||||
|
<Button size="sm" disabled={!text.trim()} onClick={() => run(text)}>{t('wb.appearance.importJson')}</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>;
|
||||||
|
}
|
||||||
|
|
||||||
251
packages/shell/src/panel/BackupPanel.tsx
Normal file
251
packages/shell/src/panel/BackupPanel.tsx
Normal file
|
|
@ -0,0 +1,251 @@
|
||||||
|
// Settings → Backup & sync: export everything into one `.waybetter` file, import one with a preview
|
||||||
|
// and a checkbox per section, and the optional encrypted sync through a folder the owner already
|
||||||
|
// syncs (OneDrive, iCloud Drive, Dropbox...). Files, crypto and the key stay native
|
||||||
|
// (waybetter-host backup.rs and sync.rs behind the app's `backup_*` and `sync_*` commands); nothing
|
||||||
|
// here talks to a server. The sync part shows only with the frame's `sync` feature.
|
||||||
|
|
||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import { ago, diffSections, pickSections, type SectionRow } from '../frame/backupModel.ts';
|
||||||
|
import { invoke } from '../frame/bridge.ts';
|
||||||
|
import { replaceDecks } from '../frame/deckStore.ts';
|
||||||
|
import { useSync, useT } from '../frame/hooks.ts';
|
||||||
|
import { formatDate } from '../frame/i18n.ts';
|
||||||
|
import { hasFeature } from '../frame/site.ts';
|
||||||
|
import { setProfiles } from '../frame/state.ts';
|
||||||
|
import { checkNewer, clearNewer, pushNow, refreshSync, setSyncStatus, shellSections, type SnapshotInfo, type SyncStatus } from '../frame/syncHost.ts';
|
||||||
|
import { loadWorkspaces } from '../frame/workspaces.ts';
|
||||||
|
import { Badge, Button, InputRow, Row, Section, Toggle } from './controls.tsx';
|
||||||
|
import { panelSite, type Notify } from './site.ts';
|
||||||
|
import './backup.css';
|
||||||
|
|
||||||
|
type Json = Record<string, unknown>;
|
||||||
|
const getError = (error: unknown) => (error instanceof Error ? error.message : String(error)).replace(/^(BACKUP|SYNC|VALIDATION): /, '');
|
||||||
|
|
||||||
|
/** Tells the rest of the shell that settings changed under it (import, pull). */
|
||||||
|
async function refreshAfterImport() {
|
||||||
|
await Promise.allSettled([
|
||||||
|
panelSite().themes?.store.loadThemes(),
|
||||||
|
invoke('profiles_get').then(setProfiles),
|
||||||
|
hasFeature('workspaces') ? loadWorkspaces() : undefined,
|
||||||
|
]);
|
||||||
|
window.dispatchEvent(new CustomEvent('bt-settings-imported'));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function BackupPanel({ notify }: { notify: Notify }) {
|
||||||
|
const t = useT();
|
||||||
|
const [preview, setPreview] = useState<{ title: string; subtitle: string; sections: Json; snapshot?: string } | null>(null);
|
||||||
|
const sync = useSync();
|
||||||
|
|
||||||
|
// The titlebar chip "Settings from <computer>" opens this section and asks to review that snapshot.
|
||||||
|
useEffect(() => {
|
||||||
|
const onReview = (event: Event) => { const name = (event as CustomEvent<string | undefined>).detail; if (name) void review(name); };
|
||||||
|
window.addEventListener('bt-sync-review', onReview);
|
||||||
|
return () => window.removeEventListener('bt-sync-review', onReview);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
async function review(name: string) {
|
||||||
|
try {
|
||||||
|
const sections = await invoke<Json>('sync_open', { name });
|
||||||
|
const info = syncStateSnapshot(name);
|
||||||
|
setPreview({ title: t('wb.backup.fromDevice', { device: info?.deviceName ?? t('wb.backup.anotherComputer') }), subtitle: info ? t('wb.backup.syncedAgo', { when: ago(info.createdAt) }) : t('wb.backup.encryptedSnapshot'), sections, snapshot: name });
|
||||||
|
} catch (error) { notify(getError(error), true); }
|
||||||
|
}
|
||||||
|
const syncStateSnapshot = (name: string) => sync.status?.snapshots.find(item => item.name === name) ?? (sync.newer?.name === name ? sync.newer : null);
|
||||||
|
|
||||||
|
if (preview) {
|
||||||
|
return <ImportPreview {...preview} notify={notify}
|
||||||
|
onCancel={async () => {
|
||||||
|
if (preview.snapshot) { await invoke('sync_mark_pulled', { name: preview.snapshot }).catch(() => {}); clearNewer(); }
|
||||||
|
setPreview(null);
|
||||||
|
}}
|
||||||
|
onDone={async () => {
|
||||||
|
if (preview.snapshot) { await invoke('sync_mark_pulled', { name: preview.snapshot }).catch(() => {}); clearNewer(); void refreshSync(); }
|
||||||
|
setPreview(null);
|
||||||
|
}}/>;
|
||||||
|
}
|
||||||
|
return <>
|
||||||
|
<ExportSection notify={notify} onOpen={(title, subtitle, sections) => setPreview({ title, subtitle, sections })}/>
|
||||||
|
{hasFeature('sync') && <SyncSection notify={notify} onReview={review}/>}
|
||||||
|
</>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ExportSection({ notify, onOpen }: { notify: Notify; onOpen(title: string, subtitle: string, sections: Json): void }) {
|
||||||
|
const t = useT();
|
||||||
|
const [drafts, setDrafts] = useState(false);
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
async function exportFile() {
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
const path = await invoke<string | null>('backup_export_file', { includeDrafts: drafts, extra: shellSections() });
|
||||||
|
if (path) notify(t('wb.backup.saved', { file: path.split(/[\\/]/).pop() ?? path }));
|
||||||
|
} catch (error) { notify(getError(error), true); } finally { setBusy(false); }
|
||||||
|
}
|
||||||
|
async function importFile() {
|
||||||
|
try {
|
||||||
|
const opened = await invoke<{ file: string; createdAt?: string; appVersion?: string; sections: Json } | null>('backup_open_file');
|
||||||
|
if (!opened) return;
|
||||||
|
const when = opened.createdAt ? formatDate(opened.createdAt, { dateStyle: 'medium', timeStyle: 'short' }) : t('wb.backup.unknownDate');
|
||||||
|
onOpen(t('wb.backup.importFile', { file: opened.file }), `${t('wb.backup.exportedAt', { when })}${opened.appVersion ? ` · ${panelSite().brand.name} ${opened.appVersion}` : ''}`, opened.sections);
|
||||||
|
} catch (error) { notify(getError(error), true); }
|
||||||
|
}
|
||||||
|
return <Section title={t('wb.backup.title')} hint={t('wb.backup.hint')}>
|
||||||
|
<Row label={t('wb.backup.export')} hint={t('wb.backup.exportHint')} keywords="backup export save file move computer" wide>
|
||||||
|
<div className="bt-inline">
|
||||||
|
<Button tone="primary" disabled={busy} onClick={() => void exportFile()}>{busy ? t('wb.backup.exporting') : t('wb.backup.exportButton')}</Button>
|
||||||
|
<label className="btb-check"><input type="checkbox" checked={drafts} onChange={event => setDrafts(event.target.checked)}/>{t('wb.backup.includeDrafts')}</label>
|
||||||
|
</div>
|
||||||
|
</Row>
|
||||||
|
<Row label={t('wb.backup.import')} hint={t('wb.backup.importHint')} keywords="restore import load file" >
|
||||||
|
<Button onClick={() => void importFile()}>{t('wb.backup.importButton')}</Button>
|
||||||
|
</Row>
|
||||||
|
</Section>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ImportPreview({ title, subtitle, sections, notify, onCancel, onDone }: { title: string; subtitle: string; sections: Json; notify: Notify; onCancel(): void; onDone(): void }) {
|
||||||
|
const t = useT();
|
||||||
|
const [rows, setRows] = useState<SectionRow[] | null>(null);
|
||||||
|
const [chosen, setChosen] = useState<Set<string>>(new Set());
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
useEffect(() => {
|
||||||
|
let alive = true;
|
||||||
|
invoke<Json>('backup_collect', { includeDrafts: false })
|
||||||
|
.catch(() => ({}))
|
||||||
|
.then(current => {
|
||||||
|
if (!alive) return;
|
||||||
|
const next = diffSections({ ...current, ...shellSections() }, sections);
|
||||||
|
setRows(next);
|
||||||
|
setChosen(new Set(next.filter(row => row.checked).map(row => row.section)));
|
||||||
|
});
|
||||||
|
return () => { alive = false; };
|
||||||
|
}, [sections]);
|
||||||
|
|
||||||
|
async function apply() {
|
||||||
|
const { native, local } = pickSections(sections, chosen);
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
const result = Object.keys(native).length ? await invoke<{ applied: string[]; notes: string[] }>('backup_apply', { sections: native }) : { applied: [], notes: [] };
|
||||||
|
const decks = local.decks as { decks?: unknown; settings?: unknown } | undefined;
|
||||||
|
if (decks) replaceDecks(decks.decks, decks.settings);
|
||||||
|
await refreshAfterImport();
|
||||||
|
const count = result.applied.length + (decks ? 1 : 0);
|
||||||
|
notify([t('wb.backup.applied', { count }), ...result.notes].join(' '));
|
||||||
|
onDone();
|
||||||
|
} catch (error) { notify(getError(error), true); } finally { setBusy(false); }
|
||||||
|
}
|
||||||
|
|
||||||
|
const toggle = (section: string, on: boolean) => setChosen(previous => { const next = new Set(previous); if (on) next.add(section); else next.delete(section); return next; });
|
||||||
|
return <Section title={title} hint={subtitle} action={<Button tone="ghost" size="sm" onClick={onCancel}>{t('wb.common.cancel')}</Button>}>
|
||||||
|
{!rows && <div className="btb-loading">{t('wb.backup.comparing')}</div>}
|
||||||
|
{rows && rows.length === 0 && <div className="btb-loading">{t('wb.backup.noKnown')}</div>}
|
||||||
|
{rows && rows.map(row => <label key={row.section} className={`btb-row is-${row.status}`}>
|
||||||
|
<input type="checkbox" checked={chosen.has(row.section)} onChange={event => toggle(row.section, event.target.checked)} aria-label={t('wb.backup.applySection', { section: row.label })}/>
|
||||||
|
<span className="btb-row-body">
|
||||||
|
<span className="btb-row-title">{row.label}
|
||||||
|
{row.status === 'same' ? <Badge>{t('wb.backup.status.same')}</Badge> : row.status === 'new' ? <Badge tone="accent">{t('wb.backup.status.new')}</Badge> : <Badge tone="warn">{t('wb.backup.status.changes')}</Badge>}
|
||||||
|
</span>
|
||||||
|
{row.details.map((line, index) => <span key={index} className="btb-row-line">{line}</span>)}
|
||||||
|
</span>
|
||||||
|
</label>)}
|
||||||
|
{rows && rows.length > 0 && <div className="btb-actions">
|
||||||
|
<span className="btb-actions-note">{t('wb.backup.chosen', { count: chosen.size, total: rows.length })}</span>
|
||||||
|
<Button tone="primary" disabled={busy || chosen.size === 0} onClick={() => void apply()}>{busy ? t('wb.backup.applying') : t('wb.backup.applySelected')}</Button>
|
||||||
|
</div>}
|
||||||
|
</Section>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function SyncSection({ notify, onReview }: { notify: Notify; onReview(name: string): void }) {
|
||||||
|
const t = useT();
|
||||||
|
const sync = useSync();
|
||||||
|
const status = sync.status;
|
||||||
|
const [passphrase, setPassphrase] = useState('');
|
||||||
|
const [confirm, setConfirm] = useState('');
|
||||||
|
const [remember, setRemember] = useState(true);
|
||||||
|
const [busy, setBusy] = useState<string | null>(null);
|
||||||
|
const [deviceName, setDeviceName] = useState('');
|
||||||
|
useEffect(() => { if (!status) void refreshSync(); }, []);
|
||||||
|
useEffect(() => { if (status) setDeviceName(status.deviceName); }, [status?.deviceName]);
|
||||||
|
|
||||||
|
async function act(label: string, action: () => Promise<SyncStatus | unknown>, done?: string) {
|
||||||
|
setBusy(label);
|
||||||
|
try {
|
||||||
|
const result = await action();
|
||||||
|
if (result && typeof result === 'object' && 'device' in (result as object)) setSyncStatus(result as SyncStatus);
|
||||||
|
if (done) notify(done);
|
||||||
|
} catch (error) { notify(getError(error), true); } finally { setBusy(null); }
|
||||||
|
}
|
||||||
|
|
||||||
|
const hint = t('wb.sync.hint');
|
||||||
|
const title = t('wb.sync.title');
|
||||||
|
if (!status) return <Section title={title} hint={hint}><div className="btb-loading">{t('wb.common.loading')}</div></Section>;
|
||||||
|
if (!status.folder) {
|
||||||
|
return <Section title={title} hint={hint}>
|
||||||
|
<Row label={t('wb.sync.folder')} hint={t('wb.sync.folderHint')} keywords="sync cloud onedrive icloud dropbox folder encrypted">
|
||||||
|
<Button tone="primary" onClick={() => void act('folder', () => invoke('sync_choose_folder'))}>{t('wb.sync.chooseFolder')}</Button>
|
||||||
|
</Row>
|
||||||
|
</Section>;
|
||||||
|
}
|
||||||
|
const folderRow = <Row label={t('wb.sync.folder')} hint={<span className="btb-path" title={status.folder}>{status.folder}</span>} keywords="sync folder change stop">
|
||||||
|
<div className="bt-inline">
|
||||||
|
<Button size="sm" onClick={() => void act('folder', () => invoke('sync_choose_folder'))}>{t('wb.sync.change')}</Button>
|
||||||
|
<Button size="sm" tone="ghost" onClick={() => void act('disable', () => invoke('sync_disable'), t('wb.sync.stopped'))}>{t('wb.sync.stop')}</Button>
|
||||||
|
</div>
|
||||||
|
</Row>;
|
||||||
|
|
||||||
|
if (!status.unlocked) {
|
||||||
|
const creating = !status.initialized;
|
||||||
|
const mismatch = creating && confirm.length > 0 && confirm !== passphrase;
|
||||||
|
const ready = passphrase.length >= 8 && (!creating || confirm === passphrase);
|
||||||
|
return <Section title={title} hint={hint}>
|
||||||
|
{folderRow}
|
||||||
|
{status.error && <Row label={t('wb.sync.problem')} hint={status.error}/>}
|
||||||
|
<Row label={creating ? t('wb.sync.choosePass') : t('wb.sync.unlockPass')}
|
||||||
|
hint={creating ? t('wb.sync.choosePassHint') : t('wb.sync.unlockPassHint')}
|
||||||
|
keywords="passphrase password unlock encrypt" wide>
|
||||||
|
<form className="btb-pass" onSubmit={event => { event.preventDefault(); if (ready) void act('unlock', () => invoke('sync_unlock', { passphrase, remember }).then(result => { setPassphrase(''); setConfirm(''); return result; }), creating ? t('wb.sync.setUpDone') : t('wb.sync.unlocked')); }}>
|
||||||
|
<input className="bt-input" type="password" autoComplete="new-password" placeholder={t('wb.sync.passphrase')} aria-label={t('wb.sync.passphraseLabel')} value={passphrase} onChange={event => setPassphrase(event.target.value)}/>
|
||||||
|
{creating && <input className="bt-input" type="password" autoComplete="new-password" placeholder={t('wb.sync.repeat')} aria-label={t('wb.sync.repeatLabel')} value={confirm} onChange={event => setConfirm(event.target.value)}/>}
|
||||||
|
<label className="btb-check"><input type="checkbox" checked={remember} onChange={event => setRemember(event.target.checked)}/>{t('wb.sync.remember')}</label>
|
||||||
|
<Button tone="primary" type="submit" disabled={!ready || busy === 'unlock'}>{busy === 'unlock' ? t('wb.sync.deriving') : creating ? t('wb.sync.setUp') : t('wb.sync.unlock')}</Button>
|
||||||
|
{mismatch && <span className="btb-error">{t('wb.sync.differ')}</span>}
|
||||||
|
</form>
|
||||||
|
</Row>
|
||||||
|
</Section>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const others = status.snapshots.filter(snapshot => snapshot.device !== status.device);
|
||||||
|
const mine = status.snapshots.filter(snapshot => snapshot.device === status.device);
|
||||||
|
return <Section title={title} hint={hint} action={<Badge tone="ok">{t('wb.sync.on')}</Badge>}>
|
||||||
|
{folderRow}
|
||||||
|
<Row label={t('wb.sync.thisComputer')} hint={t('wb.sync.thisComputerHint')} keywords="device name computer">
|
||||||
|
<InputRow label={t('wb.sync.computerName')} value={deviceName} onChange={setDeviceName} button={t('wb.sync.rename')} disabled={!deviceName.trim() || deviceName === status.deviceName}
|
||||||
|
onSubmit={() => void act('name', () => invoke('sync_configure', { autoPush: status.autoPush, deviceName }))}/>
|
||||||
|
</Row>
|
||||||
|
<Row label={t('wb.sync.auto')} hint={t('wb.sync.autoHint')} keywords="auto push automatic">
|
||||||
|
<Toggle label={t('wb.sync.auto')} checked={status.autoPush} onChange={next => void act('auto', () => invoke('sync_configure', { autoPush: next, deviceName: status.deviceName }))}/>
|
||||||
|
</Row>
|
||||||
|
<Row label={t('wb.sync.last')} hint={status.lastPushedAt ? t('wb.sync.lastHint', { when: ago(status.lastPushedAt), count: mine.length }) : t('wb.sync.notYet')} keywords="sync now push">
|
||||||
|
<div className="bt-inline">
|
||||||
|
<Button size="sm" disabled={busy === 'push'} onClick={() => void act('push', () => pushNow(true), t('wb.sync.written'))}>{busy === 'push' ? t('wb.sync.syncing') : t('wb.sync.now')}</Button>
|
||||||
|
<Button size="sm" tone="ghost" disabled={busy === 'check'} onClick={() => void act('check', async () => { const newer = await checkNewer(); notify(newer ? t('wb.sync.newerFrom', { device: newer.deviceName }) : t('wb.sync.nothingNewer')); })}>{t('wb.sync.check')}</Button>
|
||||||
|
</div>
|
||||||
|
</Row>
|
||||||
|
<Row label={t('wb.sync.others')} hint={others.length ? t('wb.sync.othersHint') : t('wb.sync.othersEmpty')} keywords="pull snapshots other computer" wide>
|
||||||
|
{others.length > 0 && <div className="btb-snapshots">
|
||||||
|
{others.slice(0, 6).map(snapshot => <SnapshotRow key={snapshot.name} snapshot={snapshot} fresh={snapshot.createdAt > status.lastPulled} onReview={() => onReview(snapshot.name)}/>)}
|
||||||
|
</div>}
|
||||||
|
</Row>
|
||||||
|
<Row label={t('wb.sync.lock')} hint={status.remembered ? t('wb.sync.lockRemembered') : t('wb.sync.lockSession')} keywords="lock forget key passphrase">
|
||||||
|
<Button size="sm" tone="ghost" onClick={() => void act('lock', () => invoke('sync_lock'), t('wb.sync.locked'))}>{t('wb.sync.lock')}</Button>
|
||||||
|
</Row>
|
||||||
|
</Section>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function SnapshotRow({ snapshot, fresh, onReview }: { snapshot: SnapshotInfo; fresh: boolean; onReview(): void }) {
|
||||||
|
const t = useT();
|
||||||
|
return <div className={`btb-snapshot${fresh ? ' is-fresh' : ''}`}>
|
||||||
|
<span className="btb-snapshot-device">{snapshot.deviceName}</span>
|
||||||
|
<span className="btb-snapshot-when">{ago(snapshot.createdAt)}{fresh ? ` · ${t('wb.sync.new')}` : ''}</span>
|
||||||
|
<Button size="sm" tone={fresh ? 'primary' : 'plain'} onClick={onReview}>{t('wb.sync.review')}</Button>
|
||||||
|
</div>;
|
||||||
|
}
|
||||||
|
|
||||||
70
packages/shell/src/panel/DeveloperPanel.tsx
Normal file
70
packages/shell/src/panel/DeveloperPanel.tsx
Normal file
|
|
@ -0,0 +1,70 @@
|
||||||
|
// Settings → Developer: the live-reload developer mode (off by default). Native code watches the
|
||||||
|
// plugins folder, custom.css and one theme file (waybetter-host devmode.rs); a saved change reloads
|
||||||
|
// in every site tab at once: theme, then custom CSS, then plugins (the old version stopped before
|
||||||
|
// the new one starts). Syntax errors are caught here before anything reloads; errors show with
|
||||||
|
// file, line and column (this list, the titlebar chip and a toast in the site's tabs).
|
||||||
|
|
||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import { invoke } from '../frame/bridge.ts';
|
||||||
|
import { setDevEnabled, setDevErrors, type DevErrorInfo } from '../frame/devHost.ts';
|
||||||
|
import { useDev, useT } from '../frame/hooks.ts';
|
||||||
|
import { Badge, Button, Row, Section, Toggle } from './controls.tsx';
|
||||||
|
import { panelSite, type Notify } from './site.ts';
|
||||||
|
type DevStatus = { enabled: boolean; themeFile: string | null; pluginsFolder: string; errors: DevErrorInfo[] };
|
||||||
|
const getError = (error: unknown) => (error instanceof Error ? error.message : String(error)).replace(/^(DEV|VALIDATION): /, '');
|
||||||
|
const where = (error: DevErrorInfo) => `${error.file}${error.line ? `:${error.line}${error.column ? `:${error.column}` : ''}` : ''}`;
|
||||||
|
|
||||||
|
export function DeveloperPanel({ notify }: { notify: Notify }) {
|
||||||
|
const t = useT();
|
||||||
|
const dev = useDev();
|
||||||
|
const [status, setStatus] = useState<DevStatus | null>(null);
|
||||||
|
const [events, setEvents] = useState<Array<{ text: string; at: number }>>([]);
|
||||||
|
|
||||||
|
const apply = (next: DevStatus) => { setStatus(next); setDevEnabled(next.enabled); setDevErrors(next.errors); };
|
||||||
|
useEffect(() => { invoke<DevStatus>('dev_get').then(apply).catch(() => setStatus(null)); }, []);
|
||||||
|
useEffect(() => {
|
||||||
|
const onEvent = (event: Event) => {
|
||||||
|
const detail = (event as CustomEvent<{ kind: string; target?: string; file?: string | null }>).detail;
|
||||||
|
if (detail.kind !== 'reloaded') return;
|
||||||
|
setEvents(previous => [{ text: t('wb.dev.reloaded', { file: detail.file ?? detail.target ?? '' }), at: Date.now() }, ...previous].slice(0, 6));
|
||||||
|
};
|
||||||
|
window.addEventListener('bt-dev-event', onEvent);
|
||||||
|
return () => window.removeEventListener('bt-dev-event', onEvent);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
async function run(action: () => Promise<DevStatus>, message?: string) {
|
||||||
|
try { apply(await action()); if (message) notify(message); } catch (error) { notify(getError(error), true); }
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!status) return <Section title={t('wb.dev.title')} hint={t('wb.dev.desktopOnly')}><div className="btb-loading">{t('wb.dev.notAvailable')}</div></Section>;
|
||||||
|
const errors = dev.errors;
|
||||||
|
return <>
|
||||||
|
<Section title={t('wb.dev.title')} hint={t('wb.dev.hint')}
|
||||||
|
action={status.enabled ? <Badge tone="ok">{t('wb.dev.watching')}</Badge> : undefined}>
|
||||||
|
<Row label={t('wb.dev.mode')} hint={t('wb.dev.modeHint')} keywords="developer dev mode live reload hot reload watch">
|
||||||
|
<Toggle label={t('wb.dev.mode')} checked={status.enabled}
|
||||||
|
onChange={next => void run(() => invoke<DevStatus>('dev_set', { enabled: next }), next ? t('wb.dev.on') : t('wb.dev.off'))}/>
|
||||||
|
</Row>
|
||||||
|
<Row label={t('wb.dev.pluginsFolder')} hint={<span className="btb-path" title={status.pluginsFolder}>{status.pluginsFolder}</span>} keywords="plugins folder open">
|
||||||
|
<Button size="sm" onClick={() => void invoke('plugins_open_folder').catch(error => notify(getError(error), true))}>{t('wb.plugins.openFolder')}</Button>
|
||||||
|
</Row>
|
||||||
|
{panelSite().themes && <Row label={t('wb.dev.themeFile')} hint={status.themeFile
|
||||||
|
? <span className="btb-path" title={status.themeFile}>{status.themeFile}</span>
|
||||||
|
: t('wb.dev.themeFileHint')} keywords="theme json file watch preview">
|
||||||
|
<div className="bt-inline">
|
||||||
|
<Button size="sm" onClick={() => void run(() => invoke<DevStatus>('dev_pick_theme'))}>{status.themeFile ? t('wb.sync.change') : t('wb.dev.chooseTheme')}</Button>
|
||||||
|
{status.themeFile && <Button size="sm" tone="ghost" onClick={() => void run(() => invoke<DevStatus>('dev_clear_theme'), t('wb.dev.stoppedTheme'))}>{t('wb.dev.stopWatching')}</Button>}
|
||||||
|
</div>
|
||||||
|
</Row>}
|
||||||
|
</Section>
|
||||||
|
<Section title={t('wb.dev.errors')} hint={t('wb.dev.errorsHint')}
|
||||||
|
action={errors.length ? <Badge tone="warn">{errors.length}</Badge> : undefined}>
|
||||||
|
{errors.length === 0
|
||||||
|
? <Row label={t('wb.dev.noErrors')} hint={events.length ? events.map(event => event.text).slice(0, 3).join(' · ') : status.enabled ? t('wb.dev.saveToReload') : t('wb.dev.turnOn')}/>
|
||||||
|
: errors.map((error, index) => <div key={`${error.file}-${index}`} className="btd-error">
|
||||||
|
<code className="btd-where">{where(error)}</code>
|
||||||
|
<span className="btd-message">{error.message}</span>
|
||||||
|
</div>)}
|
||||||
|
</Section>
|
||||||
|
</>;
|
||||||
|
}
|
||||||
49
packages/shell/src/panel/FeatureToggles.tsx
Normal file
49
packages/shell/src/panel/FeatureToggles.tsx
Normal file
|
|
@ -0,0 +1,49 @@
|
||||||
|
// Page tweaks as on/off rows: the app's feature flags (booleans the page runtime applies live in
|
||||||
|
// every site tab), stored natively (waybetter-host `features_get/set`). The mechanism is the
|
||||||
|
// framework's; which flags exist, their groups and their words are the app's: the catalog has
|
||||||
|
// `features.group.<group>`, `features.<flag>.label` and `features.<flag>.description`.
|
||||||
|
//
|
||||||
|
// const [features, choose] = useFeatures(normalizeFeatures, notify);
|
||||||
|
// return features && <FeatureGroups groups={FEATURE_GROUPS} defaults={FEATURE_DEFAULTS} features={features} choose={choose}/>;
|
||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import { invoke } from '../frame/bridge.ts';
|
||||||
|
import { useT } from '../frame/hooks.ts';
|
||||||
|
import { tx } from '../frame/i18n.ts';
|
||||||
|
import { Badge, Row, Section, Toggle } from './controls.tsx';
|
||||||
|
import type { FeatureGroup, Notify } from './site.ts';
|
||||||
|
|
||||||
|
const getError = (error: unknown) => error instanceof Error ? error.message : String(error);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The saved flags (normalized by the app) and a setter that shows a change at once, saves it and
|
||||||
|
* reverts when native code refuses it. Null until loaded.
|
||||||
|
*/
|
||||||
|
export function useFeatures<Config extends Record<string, boolean>>(normalize: (value: unknown) => Config, notify: Notify): [Config | null, (patch: Partial<Config>) => Promise<void>] {
|
||||||
|
const [features, setFeatures] = useState<Config | null>(null);
|
||||||
|
useEffect(() => { invoke<unknown>('features_get').then(value => setFeatures(normalize(value))).catch(err => notify(getError(err), true)); }, []);
|
||||||
|
async function choose(patch: Partial<Config>) {
|
||||||
|
if (!features) return;
|
||||||
|
const next = { ...features, ...patch };
|
||||||
|
setFeatures(next);
|
||||||
|
try { await invoke('features_set', { features: next }); }
|
||||||
|
catch (err) { setFeatures(features); notify(getError(err), true); }
|
||||||
|
}
|
||||||
|
return [features, choose];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One section per group, one toggle per flag; flags that are on by default carry a badge. */
|
||||||
|
export function FeatureGroups<Config extends Record<string, boolean>>({ groups, defaults, features, choose }: {
|
||||||
|
groups: readonly FeatureGroup[];
|
||||||
|
defaults: Config;
|
||||||
|
features: Config;
|
||||||
|
choose(patch: Partial<Config>): void | Promise<void>;
|
||||||
|
}) {
|
||||||
|
const t = useT();
|
||||||
|
return <>
|
||||||
|
{groups.map(group => <Section key={group.id} title={tx(`features.group.${group.id}`)}>
|
||||||
|
{group.features.map(feature => <Row key={feature} label={tx(`features.${feature}.label`)} hint={tx(`features.${feature}.description`)} keywords={feature} badge={defaults[feature] ? <Badge>{t('wb.features.default')}</Badge> : undefined}>
|
||||||
|
<Toggle label={tx(`features.${feature}.label`)} checked={!!features[feature]} onChange={next => void choose({ [feature]: next } as Partial<Config>)}/>
|
||||||
|
</Row>)}
|
||||||
|
</Section>)}
|
||||||
|
</>;
|
||||||
|
}
|
||||||
50
packages/shell/src/panel/Home.tsx
Normal file
50
packages/shell/src/panel/Home.tsx
Normal file
|
|
@ -0,0 +1,50 @@
|
||||||
|
// The panel's home page: the hero (logo, title, version and license chips, two actions), highlight
|
||||||
|
// cards that open sections and the About block. The layout is the framework's; the words are the
|
||||||
|
// app's (`PanelSite.home`).
|
||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import { invoke } from '../frame/bridge.ts';
|
||||||
|
import { useT } from '../frame/hooks.ts';
|
||||||
|
import { NAV_ICONS, navEntries } from './nav.ts';
|
||||||
|
import { NavIcon } from './NavIcon.tsx';
|
||||||
|
import { panelSite, type BuiltinSection } from './site.ts';
|
||||||
|
|
||||||
|
export function Home({ go }: { go(section: string): void }) {
|
||||||
|
useT();
|
||||||
|
const panel = panelSite();
|
||||||
|
const { home, brand } = panel;
|
||||||
|
const [version, setVersion] = useState('');
|
||||||
|
useEffect(() => { panel.version?.().then(setVersion).catch(() => {}); }, []);
|
||||||
|
const entries = navEntries(panel);
|
||||||
|
const icon = (section: string) => entries.find(entry => entry.id === section)?.icon ?? NAV_ICONS[section as BuiltinSection] ?? NAV_ICONS.home;
|
||||||
|
const [before, emphasis, after] = home.title();
|
||||||
|
const foot = home.about?.foot;
|
||||||
|
return <div className="btp-home">
|
||||||
|
<section className="btp-hero">
|
||||||
|
<div className="btp-hero-glow" aria-hidden="true"/>
|
||||||
|
<div className="btp-hero-mark"><img src={brand.logo} alt="" width={64} height={64}/></div>
|
||||||
|
<p className="btp-hero-kicker"><span className="btp-hero-name">{home.kicker.name}</span>{home.kicker.rest}</p>
|
||||||
|
<h1 className="btp-hero-title">{before}<em>{emphasis}</em>{after}</h1>
|
||||||
|
<p className="btp-hero-lede">{home.lede()}</p>
|
||||||
|
<div className="btp-hero-chips">
|
||||||
|
{version && <span className="btp-chip">v{version}</span>}
|
||||||
|
{(home.chips?.() ?? []).map(chip => <span key={chip} className="btp-chip">{chip}</span>)}
|
||||||
|
</div>
|
||||||
|
{home.actions && home.actions.length > 0 && <div className="btp-hero-actions">
|
||||||
|
{home.actions.map((action, index) => <button key={action.section} className={`btp-btn${index === 0 ? ' is-primary' : ''}`} onClick={() => go(action.section)}>{action.label()}</button>)}
|
||||||
|
</div>}
|
||||||
|
</section>
|
||||||
|
{home.highlights && home.highlights.length > 0 && <div className="btp-highlights">
|
||||||
|
{home.highlights.map(item => <button key={item.section} className="btp-highlight" onClick={() => go(item.section)}>
|
||||||
|
<NavIcon d={icon(item.section)}/><strong>{item.title()}</strong><span>{item.text()}</span>
|
||||||
|
</button>)}
|
||||||
|
</div>}
|
||||||
|
{home.about && <section className="btp-about">
|
||||||
|
<div className="btp-group-head"><h2>{home.about.title()}</h2>
|
||||||
|
<p>{home.about.text()}</p></div>
|
||||||
|
{home.about.layers && <ol className="btp-layers">
|
||||||
|
{home.about.layers.map((layer, index) => <li key={index}><span className="btp-layer-n">{String(index + 1).padStart(2, '0')}</span><div><strong>{layer.name()}</strong><span>{layer.text()}</span></div></li>)}
|
||||||
|
</ol>}
|
||||||
|
{foot && <p className="btp-about-foot">{foot.text()} <b>{foot.by}</b>{foot.link && <> · <button className="btp-link" onClick={() => { invoke('open_external_url', { url: foot.link!.url }).catch(() => {}); }}>{foot.link.label}</button></>}</p>}
|
||||||
|
</section>}
|
||||||
|
</div>;
|
||||||
|
}
|
||||||
58
packages/shell/src/panel/LanguageSettings.tsx
Normal file
58
packages/shell/src/panel/LanguageSettings.tsx
Normal file
|
|
@ -0,0 +1,58 @@
|
||||||
|
// Settings → Language: follow the site, follow the system, or pick one of the languages the app has
|
||||||
|
// a catalog for (`PanelSite.languages`, the app's frame/language.ts state). Machine-drafted
|
||||||
|
// translations say so and link to the app's contributor guide.
|
||||||
|
import { useMemo, useSyncExternalStore } from 'react';
|
||||||
|
import { invoke } from '../frame/bridge.ts';
|
||||||
|
import { useT } from '../frame/hooks.ts';
|
||||||
|
import { formatNumber } from '../frame/i18n.ts';
|
||||||
|
import type { LanguagePreference } from '../frame/language.ts';
|
||||||
|
import { Badge, Row, Section, Select, type Option } from './controls.tsx';
|
||||||
|
import { panelSite, type PanelLanguages } from './site.ts';
|
||||||
|
|
||||||
|
/** The language state as a store for React (the snapshot only changes when the state does). */
|
||||||
|
function languageStore(languages: PanelLanguages) {
|
||||||
|
let cached = languages.state();
|
||||||
|
const snapshot = () => {
|
||||||
|
const next = languages.state();
|
||||||
|
if (next.preference !== cached.preference || next.siteLang !== cached.siteLang || next.locale !== cached.locale || next.system !== cached.system) cached = next;
|
||||||
|
return cached;
|
||||||
|
};
|
||||||
|
return { subscribe: (listener: () => void) => languages.subscribe(listener), snapshot };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function LanguageSettings() {
|
||||||
|
const t = useT();
|
||||||
|
const languages = panelSite().languages!;
|
||||||
|
const LANGUAGES = languages.list;
|
||||||
|
const store = useMemo(() => languageStore(languages), [languages]);
|
||||||
|
const current = useSyncExternalStore(store.subscribe, store.snapshot, store.snapshot);
|
||||||
|
const active = LANGUAGES.find(language => language.code === current.locale);
|
||||||
|
const siteLanguage = current.siteLang ? LANGUAGES.find(language => language.code === current.siteLang) : null;
|
||||||
|
const options: Array<Option<LanguagePreference>> = [
|
||||||
|
{ value: 'site', label: t('wb.settings.language.followSite'), hint: siteLanguage ? t('wb.settings.language.followSiteNow', { language: siteLanguage.name }) : t('wb.settings.language.followSiteHint') },
|
||||||
|
{ value: 'system', label: t('wb.settings.language.followSystem'), hint: t('wb.settings.language.followSystemHint') },
|
||||||
|
...LANGUAGES.map(language => ({
|
||||||
|
value: language.code,
|
||||||
|
label: language.name,
|
||||||
|
hint: language.name === language.englishName ? undefined : language.englishName,
|
||||||
|
style: { direction: language.dir },
|
||||||
|
})),
|
||||||
|
];
|
||||||
|
const guide = languages.translateUrl;
|
||||||
|
const open = () => { if (guide) invoke('open_external_url', { url: guide }).catch(() => window.open(guide, '_blank', 'noopener')); };
|
||||||
|
const machine = active && active.status === 'machine';
|
||||||
|
return <Section title={t('wb.settings.language.title')} id="language" hint={t('wb.settings.language.hint')}>
|
||||||
|
<Row label={t('wb.settings.language.label')} keywords={t('wb.settings.language.keywords')}
|
||||||
|
hint={active ? t('wb.settings.language.active', { language: active.name }) : undefined}
|
||||||
|
badge={machine ? <Badge tone="warn">{t('wb.settings.language.machine')}</Badge> : active?.status === 'reviewed' ? <Badge tone="ok">{t('wb.settings.language.reviewed')}</Badge> : undefined}>
|
||||||
|
<Select label={t('wb.settings.language.label')} value={current.preference} options={options} width={240}
|
||||||
|
onChange={value => { void languages.set(value); }}/>
|
||||||
|
</Row>
|
||||||
|
{guide && active && active.code !== 'en' && <Row label={t('wb.settings.language.helpTitle')} keywords="translate translation crowdin contribute"
|
||||||
|
hint={machine
|
||||||
|
? t('wb.settings.language.helpMachine', { language: active.name })
|
||||||
|
: t('wb.settings.language.helpReviewed', { language: active.name, percent: formatNumber(active.coverage, { style: 'percent', maximumFractionDigits: 0 }) })}>
|
||||||
|
<button type="button" className="bt-btn is-plain is-sm" onClick={open}>{t('wb.settings.language.help')}</button>
|
||||||
|
</Row>}
|
||||||
|
</Section>;
|
||||||
|
}
|
||||||
334
packages/shell/src/panel/MakePanel.tsx
Normal file
334
packages/shell/src/panel/MakePanel.tsx
Normal file
|
|
@ -0,0 +1,334 @@
|
||||||
|
// "Make": build a plugin or theme from inside the app. Example plugins in an editor that checks
|
||||||
|
// the header the way the Plugins list reads it (Copy / Download / Open plugins folder: plugins are
|
||||||
|
// installed only by copying a file into the folder, never by the app), a gallery that opens the
|
||||||
|
// real plugin UI kit in the current theme, a live view of the theme API (`api.theme.current()`
|
||||||
|
// and the `--wb-*` variables) and the app's bundled docs. The examples, the theme file and the
|
||||||
|
// docs are the app's (`PanelSite.make`). Everything is local.
|
||||||
|
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||||
|
import { createThemeApi, themeVars, type ResolvedTheme, type ThemeSource } from '../../../runtime/src/themeApi.ts';
|
||||||
|
import type { ThemeChoice } from '../../../runtime/src/themeChoice.ts';
|
||||||
|
import { createUiKit, type UiKit } from '../../../runtime/src/ui.ts';
|
||||||
|
import { invoke } from '../frame/bridge.ts';
|
||||||
|
import { useT } from '../frame/hooks.ts';
|
||||||
|
import { t, tx } from '../frame/i18n.ts';
|
||||||
|
import { setOverlay } from '../frame/state.ts';
|
||||||
|
import { Button, Section, Segmented } from './controls.tsx';
|
||||||
|
import { CREATE_COMMANDS, KIT_DEMOS, cssVarOf, parsePluginHeader, pluginWarnings, validPluginFileName, type KitDemo } from './makeModel.ts';
|
||||||
|
import type { DocLink } from './markdown.ts';
|
||||||
|
import { MarkdownDoc } from './MarkdownDoc.tsx';
|
||||||
|
import { panelSite, type Notify, type PanelMake, type SectionProps } from './site.ts';
|
||||||
|
import './make.css';
|
||||||
|
|
||||||
|
type Tab = 'plugin' | 'kit' | 'theme' | 'docs';
|
||||||
|
/** The docs the intro line links to, when the app bundles them. */
|
||||||
|
const REFERENCE_DOCS = ['PLUGINS.md', 'THEMES.md'];
|
||||||
|
const make = (): PanelMake => panelSite().make!;
|
||||||
|
const runtimeGlobal = () => make().global ?? 'wayBetter';
|
||||||
|
|
||||||
|
const getError = (error: unknown) => error instanceof Error ? error.message : String(error);
|
||||||
|
|
||||||
|
function copy(text: string, notify: Notify, what = t('wb.common.copied')) {
|
||||||
|
navigator.clipboard.writeText(text).then(() => notify(what), () => notify(t('wb.common.clipboardUnavailable'), true));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Saves `text` through the webview's ordinary download (the Downloads folder). */
|
||||||
|
function download(file: string, text: string, type: string) {
|
||||||
|
const url = URL.createObjectURL(new Blob([text], { type }));
|
||||||
|
const anchor = document.createElement('a');
|
||||||
|
anchor.href = url;
|
||||||
|
anchor.download = file;
|
||||||
|
anchor.click();
|
||||||
|
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The persisted theme choice, re-read while the section is open so the explorer stays live. */
|
||||||
|
function useThemeChoice(): ThemeChoice | null {
|
||||||
|
const [choice, setChoice] = useState<ThemeChoice | null>(null);
|
||||||
|
useEffect(() => {
|
||||||
|
const themes = panelSite().themes;
|
||||||
|
if (!themes) return;
|
||||||
|
let alive = true;
|
||||||
|
let last = '';
|
||||||
|
const load = () => themes.store.adapter.load().then(value => {
|
||||||
|
const key = JSON.stringify(value);
|
||||||
|
if (alive && key !== last) { last = key; setChoice(value); }
|
||||||
|
}).catch(() => { if (alive && !last) setChoice(themes.catalog.defaultChoice); });
|
||||||
|
void load();
|
||||||
|
const timer = setInterval(load, 1500);
|
||||||
|
window.addEventListener('focus', load);
|
||||||
|
return () => { alive = false; clearInterval(timer); window.removeEventListener('focus', load); };
|
||||||
|
}, []);
|
||||||
|
return choice;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function MakePanel({ notify, openSection }: SectionProps) {
|
||||||
|
const t = useT();
|
||||||
|
const themes = panelSite().themes;
|
||||||
|
const docs = make().docs ?? {};
|
||||||
|
const docNames = Object.keys(docs);
|
||||||
|
const reference = REFERENCE_DOCS.filter(name => name in docs);
|
||||||
|
const [tab, setTab] = useState<Tab>('plugin');
|
||||||
|
const [doc, setDoc] = useState(docNames[0] ?? '');
|
||||||
|
const [mode, setMode] = useState(themes?.modes?.initial ?? 'dark');
|
||||||
|
const choice = useThemeChoice();
|
||||||
|
const resolved = useMemo(() => choice && themes?.resolved ? themes.resolved(choice, mode) : null, [choice, mode]);
|
||||||
|
const readDoc = (name: string) => { setDoc(name); setTab('docs'); };
|
||||||
|
|
||||||
|
return <div className="bmk">
|
||||||
|
<section className="bmk-intro">
|
||||||
|
<p>{t('wb.make.intro')}</p>
|
||||||
|
<ul className="bmk-commands">
|
||||||
|
{CREATE_COMMANDS.map(item => <li key={item.command}>
|
||||||
|
<span>{item.label}</span>
|
||||||
|
<code>{item.command}</code>
|
||||||
|
<Button size="sm" tone="ghost" label={t('wb.make.copyCommand', { command: item.command })} onClick={() => copy(item.command, notify)}>{t('wb.common.copy')}</Button>
|
||||||
|
</li>)}
|
||||||
|
</ul>
|
||||||
|
{reference.length > 0 && <p className="bmk-muted">{t('wb.make.reference')} {reference.map((name, index) => <span key={name}>{index > 0 && <> ·{' '}</>}
|
||||||
|
<button type="button" className="bmk-doc-link" onClick={() => readDoc(name)}>{name}</button></span>)} {t('wb.make.referenceBundled')}</p>}
|
||||||
|
</section>
|
||||||
|
<div className="bmk-tabs">
|
||||||
|
<Segmented<Tab> label={t('wb.panel.section.make')} value={tab} onChange={setTab} options={[
|
||||||
|
{ value: 'plugin' as Tab, label: t('wb.store.plugin') }, { value: 'kit' as Tab, label: t('wb.make.tab.kit') },
|
||||||
|
...(themes?.resolved ? [{ value: 'theme' as Tab, label: t('wb.make.tab.theme') }] : []),
|
||||||
|
...(docNames.length ? [{ value: 'docs' as Tab, label: t('wb.make.tab.docs') }] : []),
|
||||||
|
]}/>
|
||||||
|
</div>
|
||||||
|
{tab === 'plugin' && <PluginWorkbench notify={notify} openSection={openSection}/>}
|
||||||
|
{tab === 'kit' && <KitGallery resolved={resolved} notify={notify}/>}
|
||||||
|
{tab === 'theme' && <ThemeExplorer choice={choice} resolved={resolved} mode={mode} setMode={setMode} notify={notify} openSection={openSection}/>}
|
||||||
|
{tab === 'docs' && <Docs docs={docs} doc={doc} setDoc={setDoc} notify={notify}/>}
|
||||||
|
</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Plugin examples
|
||||||
|
|
||||||
|
function PluginWorkbench({ notify, openSection }: { notify: Notify; openSection?(section: 'plugins'): void }) {
|
||||||
|
const t = useT();
|
||||||
|
const PLUGIN_EXAMPLES = make().examples;
|
||||||
|
const [exampleId, setExampleId] = useState(PLUGIN_EXAMPLES[0]?.id ?? '');
|
||||||
|
const [edits, setEdits] = useState<Record<string, string>>({});
|
||||||
|
const [names, setNames] = useState<Record<string, string>>({});
|
||||||
|
const example = PLUGIN_EXAMPLES.find(item => item.id === exampleId) ?? PLUGIN_EXAMPLES[0];
|
||||||
|
if (!example) return null;
|
||||||
|
const source = edits[example.id] ?? example.source;
|
||||||
|
const file = names[example.id] ?? example.file;
|
||||||
|
const meta = parsePluginHeader(file, source);
|
||||||
|
const warnings = pluginWarnings(meta, source);
|
||||||
|
const fileOk = validPluginFileName(file);
|
||||||
|
const edited = source !== example.source;
|
||||||
|
|
||||||
|
return <>
|
||||||
|
<Section title={t('wb.make.examples')} hint={t('wb.make.examplesHint')}>
|
||||||
|
<div className="bmk-examples" role="tablist" aria-label={t('wb.make.examples')}>
|
||||||
|
{PLUGIN_EXAMPLES.map(item => <button key={item.id} type="button" role="tab" aria-selected={item.id === example.id}
|
||||||
|
className={`bmk-example ${item.id === example.id ? 'is-on' : ''}`} onClick={() => setExampleId(item.id)}>
|
||||||
|
<strong>{item.title}</strong><span>{item.blurb}</span>
|
||||||
|
</button>)}
|
||||||
|
</div>
|
||||||
|
</Section>
|
||||||
|
<Section title={meta.name} hint={<>{t('wb.make.pluginsList')} <b>{meta.name}</b>{meta.version && ` ${meta.version}`}{meta.author && ` · ${meta.author}`}{meta.description && ` — ${meta.description}`}</>}
|
||||||
|
action={edited ? <Button size="sm" tone="ghost" onClick={() => setEdits(current => { const next = { ...current }; delete next[example.id]; return next; })}>{t('wb.common.reset')}</Button> : undefined}>
|
||||||
|
<div className="bt-code bmk-editor">
|
||||||
|
<textarea aria-label={t('wb.make.source', { file })} spellCheck={false} value={source} rows={Math.min(28, source.split('\n').length + 1)}
|
||||||
|
onChange={event => setEdits(current => ({ ...current, [example.id]: event.target.value }))}/>
|
||||||
|
<div className="bt-code-bar">
|
||||||
|
<label className="bmk-file">
|
||||||
|
<span>{t('wb.make.file')}</span>
|
||||||
|
<input className="bt-input" aria-label={t('wb.make.fileName')} spellCheck={false} value={file} aria-invalid={!fileOk}
|
||||||
|
onChange={event => setNames(current => ({ ...current, [example.id]: event.target.value.trim() }))}/>
|
||||||
|
</label>
|
||||||
|
<Button size="sm" onClick={() => copy(source, notify, t('wb.make.pluginCopied'))}>{t('wb.common.copy')}</Button>
|
||||||
|
<Button size="sm" disabled={!fileOk} onClick={() => { download(file, source, 'text/javascript'); notify(t('wb.make.savedDownloads', { file })); }}>{t('wb.panel.updates.download')}</Button>
|
||||||
|
<Button size="sm" tone="primary" onClick={() => void invoke('plugins_open_folder').catch(error => notify(getError(error), true))}>{t('wb.make.openPluginsFolder')}</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{(warnings.length > 0 || !fileOk) && <ul className="bmk-warnings" role="status">
|
||||||
|
{!fileOk && <li>{t('wb.make.fileRule')}</li>}
|
||||||
|
{warnings.map(warning => <li key={warning}>{warning}</li>)}
|
||||||
|
</ul>}
|
||||||
|
<ol className="bmk-steps">
|
||||||
|
<li>{t('wb.make.step1', { file: fileOk ? file : 'name.plugin.js' })}</li>
|
||||||
|
<li>{t('wb.make.step2Before')} <button type="button" className="bmk-doc-link" onClick={() => openSection?.('plugins')}>{t('wb.panel.section.plugins')}</button>{t('wb.make.step2After')}</li>
|
||||||
|
<li>{t('wb.make.step3')}</li>
|
||||||
|
</ol>
|
||||||
|
</Section>
|
||||||
|
</>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// UI kit gallery: the real kit, drawn in this window with the current theme.
|
||||||
|
|
||||||
|
function KitGallery({ resolved, notify }: { resolved: ResolvedTheme | null; notify: Notify }) {
|
||||||
|
const t = useT();
|
||||||
|
const latest = useRef<ResolvedTheme | null>(resolved);
|
||||||
|
const listeners = useRef(new Set<() => void>());
|
||||||
|
const kit = useRef<{ kit: UiKit; dispose(): void } | null>(null);
|
||||||
|
const [result, setResult] = useState<{ id: string; text: string } | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
latest.current = resolved;
|
||||||
|
for (const listener of [...listeners.current]) listener();
|
||||||
|
}, [resolved]);
|
||||||
|
useEffect(() => {
|
||||||
|
const source: ThemeSource = {
|
||||||
|
current: () => latest.current,
|
||||||
|
onChange: listener => { listeners.current.add(listener); return () => { listeners.current.delete(listener); }; },
|
||||||
|
};
|
||||||
|
const root = createUiKit(window, { theme: createThemeApi(window, source), product: panelSite().brand.name, hostId: 'wb-make-ui', text: key => tx(key, undefined, '') || undefined });
|
||||||
|
kit.current = root.scoped();
|
||||||
|
// Leaving the section closes whatever the gallery opened.
|
||||||
|
return () => { kit.current?.dispose(); kit.current = null; };
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tab webviews are native and sit above this page. A dialog is a shell overlay (the shell rises
|
||||||
|
* above the panes); a toast needs none: its layer is pinned to this panel, like `.btp-toast`.
|
||||||
|
*/
|
||||||
|
async function show(demo: KitDemo) {
|
||||||
|
const ui = kit.current?.kit;
|
||||||
|
if (!ui) return;
|
||||||
|
const h = ui.h;
|
||||||
|
const toast = demo.kind === 'toast';
|
||||||
|
const panel = document.querySelector('.bmk-kit')?.closest('.bt-panel')?.getBoundingClientRect();
|
||||||
|
// The kit adds its host on demand: place it once the demo below has (same task, before paint).
|
||||||
|
// A transformed host is the containing block of the kit's fixed layers.
|
||||||
|
queueMicrotask(() => {
|
||||||
|
const host = document.getElementById('wb-make-ui');
|
||||||
|
if (host) Object.assign(host.style, toast && panel
|
||||||
|
? { inset: 'auto', left: `${panel.left}px`, top: `${panel.top}px`, width: `${panel.width}px`, height: `${panel.height}px`, transform: 'translateZ(0)' }
|
||||||
|
: { inset: '0', left: '', top: '', width: '', height: '', transform: '' });
|
||||||
|
});
|
||||||
|
if (!toast) setOverlay(1);
|
||||||
|
try {
|
||||||
|
let value: unknown;
|
||||||
|
switch (demo.id) {
|
||||||
|
case 'toast': await ui.toast(t('wb.make.demo.linkCopied')).closed; break;
|
||||||
|
case 'toast-success': await ui.toast(t('wb.make.demo.saved'), { tone: 'success' }).closed; break;
|
||||||
|
case 'toast-action': await ui.toast(t('wb.make.demo.postHidden'), { tone: 'warning', action: { label: t('wb.make.demo.undo'), onClick: () => setResult({ id: demo.id, text: t('wb.make.demo.undoClicked') }) } }).closed; break;
|
||||||
|
case 'toast-danger': await ui.toast(t('wb.make.demo.couldNotSave'), { tone: 'danger' }).closed; break;
|
||||||
|
case 'alert': value = await ui.alert({ title: t('wb.make.demo.exported'), message: t('wb.make.demo.exportedText'), tone: 'success' }); break;
|
||||||
|
case 'confirm': value = await ui.confirm({ title: t('wb.make.demo.deleteNote'), message: t('wb.make.demo.cannotUndo'), danger: true }); break;
|
||||||
|
case 'prompt': value = await ui.prompt({ title: t('wb.make.demo.renameList'), label: t('wb.make.demo.name'), value: t('wb.make.demo.reading'), validate: v => v.trim().length < 3 ? t('wb.make.demo.min3') : null }); break;
|
||||||
|
case 'dialog': value = await ui.dialog({
|
||||||
|
title: t('wb.make.demo.myPlugin'), message: t('wb.make.demo.whatHidden'),
|
||||||
|
content: body => body.append(h('label', { class: 'wb-check' }, h('input', { type: 'checkbox' }), t('wb.make.demo.hideTrends'))),
|
||||||
|
actions: [{ label: t('wb.common.cancel') }, { label: t('wb.common.save'), tone: 'primary', default: true }],
|
||||||
|
}).closed; break;
|
||||||
|
}
|
||||||
|
if (demo.kind !== 'toast') setResult({ id: demo.id, text: `→ ${value === undefined ? 'undefined' : JSON.stringify(value)}` });
|
||||||
|
} catch (error) {
|
||||||
|
notify(getError(error), true);
|
||||||
|
} finally {
|
||||||
|
if (!toast) setOverlay(-1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return <Section title={t('wb.make.kitTitle')} hint={t('wb.make.kitHint')}>
|
||||||
|
<div className="bmk-kit">
|
||||||
|
{KIT_DEMOS.map(demo => <div key={demo.id} className="bmk-kit-row">
|
||||||
|
<Button size="sm" tone={demo.kind === 'toast' ? 'plain' : 'primary'} onClick={() => void show(demo)}>{demo.label}</Button>
|
||||||
|
<code className="bmk-kit-code">{demo.code}</code>
|
||||||
|
{result?.id === demo.id && <span className="bmk-kit-result" role="status">{result.text}</span>}
|
||||||
|
</div>)}
|
||||||
|
</div>
|
||||||
|
</Section>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Theme API explorer
|
||||||
|
|
||||||
|
/** What each theme color is for: `make.role.<role>` in the catalogs. */
|
||||||
|
const roleHint = (role: string) => tx(`wb.make.role.${role}`, undefined, '');
|
||||||
|
|
||||||
|
function ThemeExplorer({ choice, resolved, mode, setMode, notify, openSection }: {
|
||||||
|
choice: ThemeChoice | null; resolved: ResolvedTheme | null; mode: string; setMode(mode: string): void; notify: Notify; openSection?(section: 'themes'): void;
|
||||||
|
}) {
|
||||||
|
const t = useT();
|
||||||
|
const themes = panelSite().themes;
|
||||||
|
if (!themes || !choice || !resolved) return <p className="bmk-muted">{t('wb.make.loadingTheme')}</p>;
|
||||||
|
const vars = themeVars(resolved);
|
||||||
|
const spec = themes.catalog.resolve(choice);
|
||||||
|
const modes = themes.modes;
|
||||||
|
const example = make().themeExample;
|
||||||
|
const global = runtimeGlobal();
|
||||||
|
// Font roles, when this build's runtime reports them (`fonts`), else the interface font only.
|
||||||
|
const roles = (resolved as ResolvedTheme & { fonts?: Record<string, unknown> }).fonts;
|
||||||
|
const fontRows: Array<[string, string]> = roles && typeof roles === 'object'
|
||||||
|
? Object.entries(roles).filter((entry): entry is [string, string] => typeof entry[1] === 'string')
|
||||||
|
: [['font', resolved.font]];
|
||||||
|
|
||||||
|
return <>
|
||||||
|
<Section title={`${resolved.name || resolved.id}`} hint={<>{t('wb.make.liveBefore')} <code>{global}.api.theme.current()</code> {t('wb.make.liveMiddle')} <button type="button" className="bmk-doc-link" onClick={() => openSection?.('themes')}>{t('wb.panel.section.themes')}</button> {t('wb.make.liveAfter')}</>}
|
||||||
|
action={resolved.siteDefault && modes ? <Segmented<string> size="sm" label={modes.label()} value={mode} onChange={setMode}
|
||||||
|
options={modes.options.map(option => ({ value: option.value, label: option.label() }))}/> : undefined}>
|
||||||
|
<div className="bmk-facts">
|
||||||
|
<span><b>id</b> {resolved.id}</span>
|
||||||
|
<span><b>mode</b> {resolved.mode}</span>
|
||||||
|
<span><b>siteDefault</b> {String(resolved.siteDefault)}</span>
|
||||||
|
<span><b>radius</b> {resolved.radius}px</span>
|
||||||
|
<span><b>buttonRadius</b> {resolved.buttonRadius}px</span>
|
||||||
|
</div>
|
||||||
|
<div className="bmk-swatches">
|
||||||
|
{(Object.keys(resolved.colors) as Array<keyof ResolvedTheme['colors']>).map(role => {
|
||||||
|
const name = cssVarOf(role);
|
||||||
|
return <button key={role} type="button" className="bmk-swatch" title={t('wb.make.copyVar', { name: `var(${name})` })} onClick={() => copy(`var(${name})`, notify, t('wb.make.copiedVar', { name: `var(${name})` }))}>
|
||||||
|
<span className="bmk-chip" style={{ background: resolved.colors[role] }}/>
|
||||||
|
<span className="bmk-swatch-text"><b>{role}</b><code>{name}</code><small>{resolved.colors[role]} · {roleHint(role)}</small></span>
|
||||||
|
</button>;
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</Section>
|
||||||
|
<Section title={t('wb.appearance.fonts')} hint={t('wb.make.fontsHint')}>
|
||||||
|
<div className="bmk-fonts">
|
||||||
|
{fontRows.map(([role, stack]) => <div key={role} className="bmk-font">
|
||||||
|
<div><b>{role}</b><code>{stack}</code></div>
|
||||||
|
<p style={{ fontFamily: stack }}>The quick brown fox jumps over the lazy dog · 0123456789</p>
|
||||||
|
</div>)}
|
||||||
|
<div className="bmk-facts">
|
||||||
|
<span><b>scale</b> {spec.font.scale}</span><span><b>weight</b> {spec.font.weight}</span><span><b>bold</b> {spec.font.bold}</span>
|
||||||
|
<span><b>tracking</b> {spec.font.tracking}em</span><span><b>leading</b> {spec.font.leading || t('wb.make.siteDefaultLeading')}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Section>
|
||||||
|
<Section title={t('wb.make.inCode')} hint={t('wb.make.inCodeHint')}>
|
||||||
|
<pre className="bt-snippet bmk-pre">{`const theme = ${global}.api.theme.current();\nthis.scope.onThemeChange(theme => this.redraw(theme));\n\n// = ${JSON.stringify(resolved, null, 2).replace(/\n/g, '\n// ')}`}</pre>
|
||||||
|
<pre className="bt-snippet bmk-pre">{`:root {\n${Object.entries(vars).map(([key, value]) => ` ${key}: ${value};`).join('\n')}\n}`}</pre>
|
||||||
|
</Section>
|
||||||
|
{example && <Section title={t('wb.make.themeFile')} hint={t('wb.make.themeFileHint')}>
|
||||||
|
<pre className="bt-snippet bmk-pre">{example.source}</pre>
|
||||||
|
<div className="bmk-actions">
|
||||||
|
<Button size="sm" onClick={() => copy(example.source, notify, t('wb.make.themeCopied'))}>{t('wb.common.copy')}</Button>
|
||||||
|
<Button size="sm" onClick={() => { download(example.file, example.source, 'application/json'); notify(t('wb.make.savedDownloads', { file: example.file })); }}>{t('wb.panel.updates.download')}</Button>
|
||||||
|
</div>
|
||||||
|
</Section>}
|
||||||
|
</>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Bundled docs
|
||||||
|
|
||||||
|
function Docs({ docs, doc, setDoc, notify }: { docs: Readonly<Record<string, string>>; doc: string; setDoc(doc: string): void; notify: Notify }) {
|
||||||
|
const t = useT();
|
||||||
|
const names = Object.keys(docs);
|
||||||
|
const source = docs[doc] ?? '';
|
||||||
|
const root = useRef<HTMLDivElement>(null);
|
||||||
|
const [anchor, setAnchor] = useState<string | null>(null);
|
||||||
|
useEffect(() => {
|
||||||
|
if (anchor) root.current?.querySelector(`#doc-${CSS.escape(anchor)}`)?.scrollIntoView({ block: 'start' });
|
||||||
|
else root.current?.scrollIntoView({ block: 'start' });
|
||||||
|
}, [doc, anchor]);
|
||||||
|
const onLink = (link: DocLink) => {
|
||||||
|
if (link.url) { invoke('open_external_url', { url: link.url }).catch(error => notify(getError(error), true)); return; }
|
||||||
|
if (link.doc && names.includes(link.doc)) setDoc(link.doc);
|
||||||
|
setAnchor(link.anchor ?? null);
|
||||||
|
};
|
||||||
|
return <section className="bmk-docs" ref={root}>
|
||||||
|
<div className="bmk-actions">
|
||||||
|
<Segmented<string> size="sm" label={t('wb.make.document')} value={doc} onChange={next => { setDoc(next); setAnchor(null); }} options={names.map(name => ({ value: name, label: name }))}/>
|
||||||
|
<Button size="sm" tone="ghost" onClick={() => copy(source, notify, t('wb.make.copiedDoc', { doc }))}>{t('wb.make.copyMarkdown')}</Button>
|
||||||
|
</div>
|
||||||
|
<MarkdownDoc source={source} docs={names} onLink={onLink}/>
|
||||||
|
</section>;
|
||||||
|
}
|
||||||
39
packages/shell/src/panel/MarkdownDoc.tsx
Normal file
39
packages/shell/src/panel/MarkdownDoc.tsx
Normal file
|
|
@ -0,0 +1,39 @@
|
||||||
|
// Renders the bundled docs (see markdown.ts) as React text nodes; nothing is parsed as HTML.
|
||||||
|
// Links to the other bundled doc switch docs, `#anchors` scroll, and web links open in the
|
||||||
|
// system browser.
|
||||||
|
import type { ReactNode } from 'react';
|
||||||
|
import { anchorOf, inlineTokens, parseMarkdown, resolveLink, type DocLink } from './markdown.ts';
|
||||||
|
|
||||||
|
function inline(text: string, onLink: (link: DocLink) => void, docs: readonly string[]): ReactNode[] {
|
||||||
|
return inlineTokens(text).map((token, index) => {
|
||||||
|
if (token.kind === 'text') return token.text;
|
||||||
|
if (token.kind === 'code') return <code key={index}>{token.text}</code>;
|
||||||
|
if (token.kind === 'bold') return <strong key={index}>{token.text}</strong>;
|
||||||
|
const link = resolveLink(token.href, docs);
|
||||||
|
return link
|
||||||
|
? <button key={index} type="button" className="bmk-doc-link" title={link.url ?? token.href} onClick={() => onLink(link)}>{inline(token.text, onLink, docs)}</button>
|
||||||
|
: <span key={index}>{token.text}</span>;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function MarkdownDoc({ source, docs, onLink }: { source: string; docs: readonly string[]; onLink(link: DocLink): void }) {
|
||||||
|
const blocks = parseMarkdown(source);
|
||||||
|
return <div className="bmk-doc">{blocks.map((block, index) => {
|
||||||
|
switch (block.kind) {
|
||||||
|
case 'heading': {
|
||||||
|
const Tag = `h${Math.min(block.level + 1, 5)}` as 'h2';
|
||||||
|
return <Tag key={index} id={`doc-${anchorOf(block.text)}`}>{inline(block.text, onLink, docs)}</Tag>;
|
||||||
|
}
|
||||||
|
case 'paragraph': return <p key={index}>{inline(block.text, onLink, docs)}</p>;
|
||||||
|
case 'list': {
|
||||||
|
const List = block.ordered ? 'ol' : 'ul';
|
||||||
|
return <List key={index}>{block.items.map((item, n) => <li key={n}>{inline(item, onLink, docs)}</li>)}</List>;
|
||||||
|
}
|
||||||
|
case 'table': return <div key={index} className="bmk-doc-table"><table>
|
||||||
|
<thead><tr>{block.head.map((cell, n) => <th key={n}>{inline(cell, onLink, docs)}</th>)}</tr></thead>
|
||||||
|
<tbody>{block.rows.map((row, r) => <tr key={r}>{row.map((cell, n) => <td key={n}>{inline(cell, onLink, docs)}</td>)}</tr>)}</tbody>
|
||||||
|
</table></div>;
|
||||||
|
case 'code': return <pre key={index} className="bt-snippet" data-lang={block.lang || undefined}>{block.text}</pre>;
|
||||||
|
}
|
||||||
|
})}</div>;
|
||||||
|
}
|
||||||
4
packages/shell/src/panel/NavIcon.tsx
Normal file
4
packages/shell/src/panel/NavIcon.tsx
Normal file
|
|
@ -0,0 +1,4 @@
|
||||||
|
/** A section's nav icon: a 16x16 stroke path. */
|
||||||
|
export function NavIcon({ d }: { d: string }) {
|
||||||
|
return <svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><path d={d} fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"/></svg>;
|
||||||
|
}
|
||||||
209
packages/shell/src/panel/Panel.tsx
Normal file
209
packages/shell/src/panel/Panel.tsx
Normal file
|
|
@ -0,0 +1,209 @@
|
||||||
|
// The app's panel: a dockview tab in the shell, laid out for a narrow split pane beside the site
|
||||||
|
// first (tab strip) and a side rail from 720px. Night Ink, like the shell chrome. Every control
|
||||||
|
// changes the site live through native commands. A settings search filters every settings section
|
||||||
|
// at once. The framework brings the sections every app has; the app adds its own (`PanelSite`).
|
||||||
|
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
|
||||||
|
import { DEFAULT_PROFILE } from '../profileModel.ts';
|
||||||
|
import { setDefaultAccount } from '../frame/accountModel.ts';
|
||||||
|
import { AccountAvatar, accountLabel, addAccount, openTabs, removeAccount, saveProfiles, signIn, useProfiles } from '../frame/AccountSwitcher.tsx';
|
||||||
|
import { invoke } from '../frame/bridge.ts';
|
||||||
|
import { useT, useUpdateStatus } from '../frame/hooks.ts';
|
||||||
|
import { site } from '../frame/site.ts';
|
||||||
|
import { shell } from '../frame/state.ts';
|
||||||
|
import { Appearance } from './Appearance.tsx';
|
||||||
|
import { BackupPanel } from './BackupPanel.tsx';
|
||||||
|
import { Button, EmptyState, SearchField, SearchProvider } from './controls.tsx';
|
||||||
|
import { DeveloperPanel } from './DeveloperPanel.tsx';
|
||||||
|
import { Home } from './Home.tsx';
|
||||||
|
import { LanguageSettings } from './LanguageSettings.tsx';
|
||||||
|
import { MakePanel } from './MakePanel.tsx';
|
||||||
|
import { navEntries } from './nav.ts';
|
||||||
|
import { NavIcon } from './NavIcon.tsx';
|
||||||
|
import { ScriptPlugins } from './Plugins.tsx';
|
||||||
|
import { PowerSettings } from './PowerSettings.tsx';
|
||||||
|
import { AlertSettings, BrowserSettings, MediaSettingsRows } from './Settings.tsx';
|
||||||
|
import { panelSite, type Notify, type SectionProps } from './site.ts';
|
||||||
|
import { StoreSection } from './StoreSection.tsx';
|
||||||
|
import { ThemeBuilder } from './ThemeBuilder.tsx';
|
||||||
|
import './panel.css';
|
||||||
|
|
||||||
|
const SEARCH_ICON = <svg width="22" height="22" viewBox="0 0 24 24" aria-hidden="true"><circle cx="10.5" cy="10.5" r="6" fill="none" stroke="currentColor" strokeWidth="1.6"/><path d="m15 15 5 5" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg>;
|
||||||
|
const getError = (error: unknown) => error instanceof Error ? error.message : String(error);
|
||||||
|
|
||||||
|
export default function Panel({ section: requested }: { section?: { name: string; nonce: number } }) {
|
||||||
|
const t = useT();
|
||||||
|
const panel = panelSite();
|
||||||
|
const entries = navEntries(panel);
|
||||||
|
const has = (id: string | undefined) => entries.some(entry => entry.id === id);
|
||||||
|
const [section, setSection] = useState<string>(has(requested?.name) ? requested!.name : 'home');
|
||||||
|
const [query, setQuery] = useState('');
|
||||||
|
const go = (id: string) => { if (has(id)) { setSection(id); setQuery(''); } };
|
||||||
|
useEffect(() => { if (requested) go(requested.name); }, [requested?.nonce]);
|
||||||
|
// Sections link to each other (Appearance → Theme Builder).
|
||||||
|
useEffect(() => {
|
||||||
|
const onSection = (event: Event) => go((event as CustomEvent<string>).detail);
|
||||||
|
window.addEventListener('bt-panel-section', onSection);
|
||||||
|
return () => window.removeEventListener('bt-panel-section', onSection);
|
||||||
|
}, []);
|
||||||
|
const [notice, setNotice] = useState<{ id: number; text: string; error: boolean } | null>(null);
|
||||||
|
const notify: Notify = (text, error = false) => setNotice({ id: Date.now(), text, error });
|
||||||
|
useEffect(() => {
|
||||||
|
if (!notice) return;
|
||||||
|
const timer = setTimeout(() => setNotice(null), notice.error ? 8000 : 3200);
|
||||||
|
return () => clearTimeout(timer);
|
||||||
|
}, [notice]);
|
||||||
|
const body = useRef<HTMLElement>(null);
|
||||||
|
useEffect(() => { body.current?.scrollTo({ top: 0 }); }, [section]);
|
||||||
|
const searching = query.trim().length > 0;
|
||||||
|
const entry = entries.find(item => item.id === section);
|
||||||
|
const Custom = entry?.component ?? null;
|
||||||
|
const props: SectionProps = { notify, openSection: go };
|
||||||
|
|
||||||
|
return <div className="btp-root"><div className={`btp ${searching ? 'is-searching' : ''}`}>
|
||||||
|
<header className="btp-head">
|
||||||
|
<div className="btp-brand"><img src={panel.brand.logo} alt="" width={22} height={22}/><strong>{panel.brand.name}</strong></div>
|
||||||
|
<SearchField label={t('wb.panel.search.label')} placeholder={t('wb.panel.search.label')} value={query} onChange={setQuery}/>
|
||||||
|
</header>
|
||||||
|
<nav className="btp-nav" aria-label={t('wb.panel.nav.label')}>
|
||||||
|
{entries.map(item => <button key={item.id} className={!searching && section === item.id ? 'is-on' : ''} aria-current={!searching && section === item.id ? 'page' : undefined}
|
||||||
|
onClick={() => go(item.id)}><NavIcon d={item.icon}/><span>{item.label(t)}</span></button>)}
|
||||||
|
</nav>
|
||||||
|
<main className="btp-body" ref={body}>
|
||||||
|
<div className="btp-page">
|
||||||
|
{searching ? <SearchResults query={query.trim()} {...props} onClear={() => setQuery('')}/> : <>
|
||||||
|
{section !== 'home' && <h1 className="btp-title">{entry?.label(t) ?? ''}</h1>}
|
||||||
|
{Custom && <Custom {...props}/>}
|
||||||
|
{!Custom && section === 'home' && <Home go={go}/>}
|
||||||
|
{!Custom && section === 'themes' && <Appearance notify={notify}/>}
|
||||||
|
{!Custom && section === 'builder' && <ThemeBuilder notify={notify}/>}
|
||||||
|
{!Custom && section === 'plugins' && <ScriptPlugins notify={notify}/>}
|
||||||
|
{!Custom && section === 'store' && <StoreSection notify={notify}/>}
|
||||||
|
{!Custom && section === 'make' && <MakePanel {...props}/>}
|
||||||
|
{!Custom && section === 'accounts' && <Accounts/>}
|
||||||
|
{!Custom && section === 'updates' && <Updates/>}
|
||||||
|
{!Custom && section === 'power' && <PowerSettings notify={notify}/>}
|
||||||
|
{!Custom && section === 'settings' && <SettingsSection {...props}/>}
|
||||||
|
{!Custom && section === 'backup' && <BackupPanel notify={notify}/>}
|
||||||
|
{!Custom && section === 'developer' && <DeveloperPanel notify={notify}/>}
|
||||||
|
</>}
|
||||||
|
</div>
|
||||||
|
</main>
|
||||||
|
{notice && <div key={notice.id} className={`btp-toast ${notice.error ? 'is-error' : ''}`} role={notice.error ? 'alert' : 'status'} onClick={() => setNotice(null)}>{notice.text}</div>}
|
||||||
|
</div></div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Settings: the language, links and session, then what the app serves (alerts, the media panel) and adds. */
|
||||||
|
function SettingsSection(props: SectionProps) {
|
||||||
|
const panel = panelSite();
|
||||||
|
return <>
|
||||||
|
{panel.languages && <LanguageSettings/>}
|
||||||
|
<BrowserSettings notify={props.notify}/>
|
||||||
|
{panel.settings?.alerts && <AlertSettings notify={props.notify}/>}
|
||||||
|
{site().media && <MediaSettingsRows notify={props.notify}/>}
|
||||||
|
{(panel.settings?.extra ?? []).map((Extra, index) => <Extra key={index} {...props}/>)}
|
||||||
|
</>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Every settings section at once, each row filtered by the query; an empty state when nothing matches. */
|
||||||
|
function SearchResults({ query, notify, openSection, onClear }: SectionProps & { query: string; onClear(): void }) {
|
||||||
|
const t = useT();
|
||||||
|
const panel = panelSite();
|
||||||
|
const root = useRef<HTMLDivElement>(null);
|
||||||
|
const [count, setCount] = useState<number | null>(null);
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
const measure = () => setCount(root.current?.querySelectorAll('.bt-row').length ?? 0);
|
||||||
|
measure();
|
||||||
|
// Sections load their values asynchronously; count again once they have rendered.
|
||||||
|
const timer = setTimeout(measure, 250);
|
||||||
|
return () => clearTimeout(timer);
|
||||||
|
});
|
||||||
|
const props: SectionProps = { notify, openSection };
|
||||||
|
return <SearchProvider value={query}>
|
||||||
|
<h1 className="btp-title">{t('wb.panel.search.results')} <span className="btp-title-sub">{t('wb.panel.search.for', { query })}</span></h1>
|
||||||
|
<div ref={root} className="btp-results">
|
||||||
|
{panel.languages && <LanguageSettings/>}
|
||||||
|
{panel.themes && <Appearance notify={notify}/>}
|
||||||
|
{(panel.sections ?? []).filter(section => section.searchable).map(section => <section.component key={section.id} {...props}/>)}
|
||||||
|
<ScriptPlugins notify={notify}/>
|
||||||
|
<BrowserSettings notify={notify}/>
|
||||||
|
{site().deck && <PowerSettings notify={notify}/>}
|
||||||
|
{panel.settings?.alerts && <AlertSettings notify={notify}/>}
|
||||||
|
{site().media && <MediaSettingsRows notify={notify}/>}
|
||||||
|
{(panel.settings?.extra ?? []).map((Extra, index) => <Extra key={index} {...props}/>)}
|
||||||
|
</div>
|
||||||
|
{count === 0 && <EmptyState icon={SEARCH_ICON} title={t('wb.panel.search.none')} action={<Button size="sm" onClick={onClear}>{t('wb.ui.search.clear')}</Button>}>
|
||||||
|
{t('wb.panel.search.noneHint')}
|
||||||
|
</EmptyState>}
|
||||||
|
</SearchProvider>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Accounts
|
||||||
|
|
||||||
|
function Accounts() {
|
||||||
|
const t = useT();
|
||||||
|
const settings = useProfiles();
|
||||||
|
const [confirming, setConfirming] = useState<string | null>(null);
|
||||||
|
const [error, setError] = useState('');
|
||||||
|
async function run(action: () => Promise<unknown>) {
|
||||||
|
setError('');
|
||||||
|
try { await action(); return true; } catch (failure) { setError(getError(failure)); return false; }
|
||||||
|
}
|
||||||
|
|
||||||
|
return <section className="btp-group">
|
||||||
|
<div className="btp-group-head"><h2>{t('wb.panel.section.accounts')}</h2><p>{t('wb.panel.accounts.hint')}</p></div>
|
||||||
|
<div className="btp-list">
|
||||||
|
{settings.profiles.map(profile => {
|
||||||
|
const tabs = openTabs(profile.id);
|
||||||
|
const on = profile.id === settings.active;
|
||||||
|
const label = accountLabel(profile);
|
||||||
|
if (confirming === profile.id) return <div key={profile.id} className="btp-alert" role="alertdialog">
|
||||||
|
{t('wb.panel.accounts.removeConfirm', { name: label.title, tabs })}
|
||||||
|
<span className="btp-row-actions"><button className="btp-btn is-danger" onClick={() => void run(() => removeAccount(settings, profile.id)).then(ok => ok && setConfirming(null))}>{t('wb.common.remove')}</button><button className="btp-btn" onClick={() => setConfirming(null)}>{t('wb.common.cancel')}</button></span>
|
||||||
|
</div>;
|
||||||
|
return <div key={profile.id} className={`btp-account ${on ? 'is-on' : ''}`}>
|
||||||
|
<AccountAvatar profile={profile} size={32}/>
|
||||||
|
<button className="btp-account-name" title={label.state === 'signed-in' ? t('wb.panel.accounts.openFeed') : t('wb.panel.accounts.signInBeside')} onClick={() => shell.openAccount(profile.id)}>
|
||||||
|
<strong>{label.title}</strong><small>{label.detail}{on ? ` · ${t('wb.panel.accounts.newTabsBadge')}` : ''}{tabs ? ` · ${t('wb.panel.accounts.openCount', { count: tabs })}` : ''}</small>
|
||||||
|
</button>
|
||||||
|
{label.state !== 'signed-in' && <button className="btp-btn is-primary" onClick={() => signIn(profile.id)}>{t('wb.panel.accounts.signIn')}</button>}
|
||||||
|
<button className="btp-btn" aria-pressed={on} disabled={on} title={t('wb.panel.accounts.newTabsTitle')} onClick={() => void run(() => saveProfiles(setDefaultAccount(settings, profile.id)))}>{on ? t('wb.panel.accounts.newTabsHere') : t('wb.panel.accounts.useForNewTabs')}</button>
|
||||||
|
{profile.id !== DEFAULT_PROFILE && <button className="btp-btn" onClick={() => setConfirming(profile.id)}>{t('wb.common.remove')}</button>}
|
||||||
|
</div>;
|
||||||
|
})}
|
||||||
|
<button className="btp-link" onClick={() => void run(() => addAccount(settings))}>{t('wb.panel.accounts.add')}</button>
|
||||||
|
</div>
|
||||||
|
{error && <div className="btp-alert" role="alert">{error}</div>}
|
||||||
|
</section>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Updates
|
||||||
|
|
||||||
|
const UPDATE_TEXT = {
|
||||||
|
idle: 'wb.panel.updates.idle',
|
||||||
|
checking: 'wb.panel.updates.checking',
|
||||||
|
upToDate: 'wb.panel.updates.upToDate',
|
||||||
|
downloading: 'wb.panel.updates.downloading',
|
||||||
|
installing: 'wb.panel.updates.installing',
|
||||||
|
ready: 'wb.panel.updates.ready',
|
||||||
|
error: 'wb.panel.updates.error',
|
||||||
|
problem: 'wb.panel.updates.problem',
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
function Updates() {
|
||||||
|
const t = useT();
|
||||||
|
const [status, apply] = useUpdateStatus();
|
||||||
|
return <section className="btp-group">
|
||||||
|
<div className="btp-group-head"><h2>{t('wb.panel.section.updates')}</h2><p>{t('wb.panel.updates.hint')}</p></div>
|
||||||
|
<div className="btp-card">
|
||||||
|
<div><strong>{t(UPDATE_TEXT[status.state])}</strong>
|
||||||
|
{'version' in status && status.version && <small>{t('wb.panel.updates.version', { version: status.version })}</small>}
|
||||||
|
{status.state === 'error' && <small>{status.message}</small>}
|
||||||
|
{status.state === 'ready' && status.notes && <p className="btp-notes">{status.notes}</p>}
|
||||||
|
</div>
|
||||||
|
{status.state === 'ready' && <button className="btp-btn is-primary" onClick={apply}>{t('wb.panel.updates.restart')}</button>}
|
||||||
|
{status.state === 'problem' && <button className="btp-btn" onClick={() => invoke('open_external_url', { url: status.downloadUrl }).catch(() => {})}>{t('wb.panel.updates.download')}</button>}
|
||||||
|
</div>
|
||||||
|
</section>;
|
||||||
|
}
|
||||||
144
packages/shell/src/panel/Plugins.tsx
Normal file
144
packages/shell/src/panel/Plugins.tsx
Normal file
|
|
@ -0,0 +1,144 @@
|
||||||
|
// Plugins: the `*.plugin.js` files in the app's plugins folder (on/off live in every site tab, their
|
||||||
|
// declared permissions, where each came from, removal through the install records) and the custom
|
||||||
|
// CSS editor. Native code serves them (waybetter-host `plugins_*`, `custom_css_*`).
|
||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import { invoke } from '../frame/bridge.ts';
|
||||||
|
import { useT } from '../frame/hooks.ts';
|
||||||
|
import { t as frameText, tx } from '../frame/i18n.ts';
|
||||||
|
import { site } from '../frame/site.ts';
|
||||||
|
import { permissionBadges, type InstallRecord } from '../storeModel.ts';
|
||||||
|
import { Badge, Button, EmptyState, Row, Section, Toggle, useSettingsQuery } from './controls.tsx';
|
||||||
|
import { panelSite } from './site.ts';
|
||||||
|
import './plugins.css';
|
||||||
|
|
||||||
|
/** A `*.plugin.js` file from the local plugins folder (waybetter-host `plugins::ScriptPlugin`). */
|
||||||
|
export type ScriptPlugin = {
|
||||||
|
file: string;
|
||||||
|
name: string;
|
||||||
|
description: string;
|
||||||
|
version: string;
|
||||||
|
author: string;
|
||||||
|
enabled: boolean;
|
||||||
|
/** Declared `@permissions`; null/absent = no line (legacy: full API, full page access). */
|
||||||
|
permissions?: string[] | null;
|
||||||
|
/** Header problems (e.g. an unknown permission name). */
|
||||||
|
problems?: string[];
|
||||||
|
};
|
||||||
|
|
||||||
|
type Notify = (text: string, error?: boolean) => void;
|
||||||
|
const getError = (error: unknown) => error instanceof Error ? error.message : String(error);
|
||||||
|
const PLUG = <svg width="22" height="22" viewBox="0 0 24 24" aria-hidden="true"><path d="M9 3v5M15 3v5M6 8h12v3a6 6 0 0 1-12 0zM12 17v4" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></svg>;
|
||||||
|
|
||||||
|
/** A bundled plugin's name/description in the active language (`plugin.<file stem>.name`), else its header's. */
|
||||||
|
export const pluginText = (plugin: { file: string; name: string; description?: string }) => {
|
||||||
|
const ns = plugin.file.replace(/\.plugin\.js$/i, '');
|
||||||
|
return { name: tx(`plugin.${ns}.name`, undefined, plugin.name), description: tx(`plugin.${ns}.description`, undefined, plugin.description ?? '') };
|
||||||
|
};
|
||||||
|
|
||||||
|
const PLUGIN_EXAMPLE = '/** @name Hello @description Says hi */\nmodule.exports = class {\n start() { console.log("hi"); }\n stop() {}\n};';
|
||||||
|
|
||||||
|
/** BetterDiscord-style JavaScript plugins loaded from the local plugins folder into the site's page. */
|
||||||
|
export function ScriptPlugins({ notify }: { notify: Notify }) {
|
||||||
|
const t = useT();
|
||||||
|
const [plugins, setPlugins] = useState<ScriptPlugin[] | null>(null);
|
||||||
|
const [error, setError] = useState('');
|
||||||
|
const [busy, setBusy] = useState<string | null>(null);
|
||||||
|
const query = useSettingsQuery();
|
||||||
|
|
||||||
|
const [records, setRecords] = useState<Record<string, InstallRecord>>({});
|
||||||
|
const [removing, setRemoving] = useState<string | null>(null);
|
||||||
|
const refresh = () => {
|
||||||
|
invoke<{ items: Record<string, InstallRecord> }>('install_records').then(value => setRecords(value.items ?? {})).catch(() => {});
|
||||||
|
return invoke<ScriptPlugin[]>('plugins_list').then(items => { setPlugins(items); setError(''); }).catch(err => setError(getError(err)));
|
||||||
|
};
|
||||||
|
useEffect(() => {
|
||||||
|
void refresh();
|
||||||
|
// The install screen (links, dropped files, the Store) added or updated one.
|
||||||
|
const again = () => void refresh();
|
||||||
|
window.addEventListener('bt-plugins-changed', again);
|
||||||
|
return () => window.removeEventListener('bt-plugins-changed', again);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
async function remove(plugin: ScriptPlugin) {
|
||||||
|
setRemoving(null);
|
||||||
|
setBusy(plugin.file);
|
||||||
|
try {
|
||||||
|
setPlugins(await invoke<ScriptPlugin[]>('plugin_remove', { file: plugin.file }));
|
||||||
|
notify(t('wb.common.removedNamed', { name: pluginText(plugin).name }));
|
||||||
|
} catch (err) { notify(getError(err), true); }
|
||||||
|
finally { setBusy(null); }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function toggle(plugin: ScriptPlugin) {
|
||||||
|
setBusy(plugin.file);
|
||||||
|
try {
|
||||||
|
setPlugins(await invoke<ScriptPlugin[]>('plugin_set_enabled', { file: plugin.file, enabled: !plugin.enabled }));
|
||||||
|
notify(plugin.enabled ? t('wb.plugins.stopped', { name: pluginText(plugin).name }) : t('wb.plugins.started', { name: pluginText(plugin).name }));
|
||||||
|
} catch (err) { notify(getError(err), true); }
|
||||||
|
finally { setBusy(null); }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Removing a file goes through the install screen's native side (`plugin_remove`).
|
||||||
|
const removable = !!panelSite().store;
|
||||||
|
const folder = <div className="bt-inline">
|
||||||
|
<Button size="sm" onClick={() => void invoke('plugins_open_folder').catch(err => notify(getError(err), true))}>{t('wb.plugins.openFolder')}</Button>
|
||||||
|
<Button size="sm" tone="ghost" onClick={() => void refresh()}>{t('wb.plugins.rescan')}</Button>
|
||||||
|
</div>;
|
||||||
|
|
||||||
|
return <Section title={t('wb.plugins.title')} hint={t('wb.plugins.hint')}
|
||||||
|
action={plugins && plugins.length > 0 ? folder : undefined}>
|
||||||
|
{error && <div className="bt-alert" role="alert">{error}</div>}
|
||||||
|
{plugins?.length === 0 && !query && <EmptyState icon={PLUG} title={t('wb.plugins.none')} action={folder}>
|
||||||
|
{t('wb.plugins.noneHint')}
|
||||||
|
<code className="bt-snippet" style={{ display: 'block' }}>{PLUGIN_EXAMPLE}</code>
|
||||||
|
</EmptyState>}
|
||||||
|
{plugins?.map(plugin => {
|
||||||
|
const record = records[`plugin:${plugin.file}`];
|
||||||
|
const source = record ? (record.source === 'store' ? t('wb.panel.section.store') : record.source === 'link' ? t('wb.plugins.source.link') : t('wb.plugins.source.file')) : null;
|
||||||
|
const text = pluginText(plugin);
|
||||||
|
return <Row key={plugin.file} label={text.name} hint={<>{text.description || plugin.file}{plugin.author ? ` · ${plugin.author}` : ''}
|
||||||
|
<span className="wbx-perms">
|
||||||
|
{permissionBadges(plugin.permissions, frameText, site().name).map(badge => <span key={badge.id} className={`is-${badge.tone}`} title={badge.detail}>{badge.label}</span>)}
|
||||||
|
{source && <span className="is-source" title={record?.url ?? t('wb.plugins.source.fileTitle')}>{source}</span>}
|
||||||
|
{(plugin.problems ?? []).map(problem => <span key={problem} className="is-warn" title={problem}>{t('wb.plugins.headerProblem')}</span>)}
|
||||||
|
</span></>} keywords={`plugin ${plugin.file} ${plugin.name} ${(plugin.permissions ?? ['legacy']).join(' ')}`}
|
||||||
|
badge={<Badge>{plugin.version || t('wb.plugins.noVersion')}</Badge>}>
|
||||||
|
{!removable ? null : removing === plugin.file
|
||||||
|
? <><Button size="sm" tone="danger" onClick={() => void remove(plugin)}>{t('wb.plugins.deleteFile')}</Button><Button size="sm" tone="ghost" onClick={() => setRemoving(null)}>{t('wb.plugins.keep')}</Button></>
|
||||||
|
: <Button size="sm" tone="ghost" disabled={busy === plugin.file} onClick={() => setRemoving(plugin.file)}>{t('wb.common.remove')}</Button>}
|
||||||
|
<Toggle label={t('wb.plugins.enabled', { name: text.name })} checked={plugin.enabled} disabled={busy === plugin.file} onChange={() => void toggle(plugin)}/>
|
||||||
|
</Row>;
|
||||||
|
})}
|
||||||
|
</Section>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Free-form CSS applied to the site's page, like BetterDiscord's Custom CSS. */
|
||||||
|
export function CustomCssEditor({ notify }: { notify: Notify }) {
|
||||||
|
const t = useT();
|
||||||
|
const [css, setCss] = useState('');
|
||||||
|
const [saved, setSaved] = useState('');
|
||||||
|
const [loaded, setLoaded] = useState(false);
|
||||||
|
const query = useSettingsQuery();
|
||||||
|
|
||||||
|
useEffect(() => { invoke<string>('custom_css_get').then(value => { setCss(value); setSaved(value); setLoaded(true); }).catch(err => notify(getError(err), true)); }, []);
|
||||||
|
|
||||||
|
async function apply() {
|
||||||
|
try { await invoke('custom_css_set', { css }); setSaved(css); notify(t('wb.css.applied')); }
|
||||||
|
catch (err) { notify(getError(err), true); }
|
||||||
|
}
|
||||||
|
if (query && !`custom css stylesheet style code ${t('wb.css.title')}`.toLowerCase().includes(query.toLowerCase().trim())) return null;
|
||||||
|
|
||||||
|
const dirty = css !== saved;
|
||||||
|
return <Section title={t('wb.css.title')} hint={t('wb.css.hint')}
|
||||||
|
action={<span className={`bt-status ${dirty ? 'is-warn' : ''}`}>{dirty ? t('wb.css.unsaved') : loaded ? (saved.trim() ? t('wb.css.applied.short') : t('wb.css.empty')) : ''}</span>}>
|
||||||
|
<div className="bt-code">
|
||||||
|
<textarea aria-label={t('wb.css.label')} spellCheck={false} value={css} placeholder={panelSite().cssExamples?.custom ?? '/* CSS for the page */'} onChange={event => setCss(event.target.value)}
|
||||||
|
onKeyDown={event => { if ((event.ctrlKey || event.metaKey) && event.key === 's') { event.preventDefault(); void apply(); } }}/>
|
||||||
|
<div className="bt-code-bar">
|
||||||
|
<small>{t('wb.appearance.cssLines', { count: css.split('\n').length })}</small>
|
||||||
|
{dirty && <Button size="sm" tone="ghost" onClick={() => setCss(saved)}>{t('wb.common.discard')}</Button>}
|
||||||
|
<Button size="sm" tone="primary" disabled={!loaded || !dirty} onClick={() => void apply()}>{t('wb.common.apply')}</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Section>;
|
||||||
|
}
|
||||||
98
packages/shell/src/panel/PowerSettings.tsx
Normal file
98
packages/shell/src/panel/PowerSettings.tsx
Normal file
|
|
@ -0,0 +1,98 @@
|
||||||
|
// Settings → Power User: the deck's defaults (column width, density, default column flags), the
|
||||||
|
// memory guard (columns per page, with the memory one column was measured to take, when the app
|
||||||
|
// says so), parking off-page columns, presets and the list of decks. Stored in the shell
|
||||||
|
// (frame/deckStore.ts); the column kinds, flags and presets are the site's (`site.deck`).
|
||||||
|
|
||||||
|
import { useEffect, useReducer } from 'react';
|
||||||
|
import { COLUMN_WIDTHS, DEFAULT_MAX_VISIBLE } from '../deckModel.ts';
|
||||||
|
import { createDeck, decks, forgetColumn, saveDecks, setDeckSettings, type DeckSettings } from '../frame/deckStore.ts';
|
||||||
|
import { useT } from '../frame/hooks.ts';
|
||||||
|
import { site, type DeckPreset } from '../frame/site.ts';
|
||||||
|
import { shell } from '../frame/state.ts';
|
||||||
|
import { Badge, Button, Row, Section, Segmented, Stepper, Toggle } from './controls.tsx';
|
||||||
|
import { panelSite, type Notify } from './site.ts';
|
||||||
|
|
||||||
|
function useDeckState() {
|
||||||
|
const [, tick] = useReducer((n: number) => n + 1, 0);
|
||||||
|
useEffect(() => { window.addEventListener('bt-decks', tick); return () => window.removeEventListener('bt-decks', tick); }, []);
|
||||||
|
}
|
||||||
|
|
||||||
|
const openDeck = (deckId?: string) => window.dispatchEvent(new CustomEvent('bt-deck-open', { detail: deckId }));
|
||||||
|
|
||||||
|
export function PowerSettings({ notify }: { notify: Notify }) {
|
||||||
|
const t = useT();
|
||||||
|
useDeckState();
|
||||||
|
const settings = decks.settings;
|
||||||
|
const save = (patch: Partial<DeckSettings>, message: string) => { setDeckSettings({ ...settings, ...patch }); notify(message); };
|
||||||
|
const perPage = settings.maxVisible;
|
||||||
|
const guard = perPage > DEFAULT_MAX_VISIBLE;
|
||||||
|
const profiles = shell.profiles.profiles.map(p => p.id);
|
||||||
|
const deckSite = site().deck;
|
||||||
|
const power = panelSite().power;
|
||||||
|
const memory = power?.memory;
|
||||||
|
if (!deckSite) return null;
|
||||||
|
const listed = power?.defaultFlags ?? Object.keys(deckSite.defaultFlags);
|
||||||
|
const preset = (item: DeckPreset) => {
|
||||||
|
const ordered = [shell.profiles.active, ...profiles.filter(id => id !== shell.profiles.active)];
|
||||||
|
const deck = createDeck((item.name ?? item.label)(), item.columns(ordered));
|
||||||
|
openDeck(deck.id);
|
||||||
|
notify(t('wb.power.deckCreated', { name: deck.name }));
|
||||||
|
};
|
||||||
|
|
||||||
|
return <>
|
||||||
|
<Section title={t('wb.power.title')} hint={t('wb.power.hint')}
|
||||||
|
action={<Button size="sm" tone="primary" onClick={() => openDeck()}>{t('wb.power.openDeck')}</Button>}>
|
||||||
|
<Row label={t('wb.power.width')} hint={t('wb.power.widthHint')} keywords="deck width narrow">
|
||||||
|
<Segmented label={t('wb.power.width')} size="sm" value={settings.width} onChange={width => save({ width }, t('wb.power.widthSaved', { width }))}
|
||||||
|
options={COLUMN_WIDTHS.map(width => ({ value: width, label: String(width) }))}/>
|
||||||
|
</Row>
|
||||||
|
<Row label={t('wb.appearance.density')} hint={t('wb.power.densityHint')} keywords="deck compact comfortable spacing">
|
||||||
|
<Segmented label={t('wb.appearance.density')} size="sm" value={settings.density} onChange={density => save({ density }, density === 'compact' ? t('wb.power.densityCompact') : t('wb.power.densityComfortable'))}
|
||||||
|
options={[{ value: 'compact', label: t('wb.appearance.density.compact') }, { value: 'comfortable', label: t('wb.power.comfortable') }]}/>
|
||||||
|
</Row>
|
||||||
|
{deckSite.flags.filter(option => listed.includes(option.key)).map(option =>
|
||||||
|
<Row key={option.key} label={t('wb.power.columnsFlag', { flag: option.label })} hint={option.hint} keywords="deck column default flags autoplay promoted counts">
|
||||||
|
<Toggle label={option.label} checked={settings.flags[option.key] === true}
|
||||||
|
onChange={next => save({ flags: { ...settings.flags, [option.key]: next } }, next ? t('wb.power.flagOn', { flag: option.label }) : t('wb.power.flagOff', { flag: option.label }))}/>
|
||||||
|
</Row>)}
|
||||||
|
</Section>
|
||||||
|
<Section title={t('wb.power.memory')} hint={memory ? t('wb.power.memoryHint', { range: memory.range }) : undefined}>
|
||||||
|
<Row label={t('wb.power.perPage')} hint={!memory ? t('wb.power.perPageSaved', { count: perPage }) : guard
|
||||||
|
? t('wb.power.perPageGuard', { max: DEFAULT_MAX_VISIBLE, mb: perPage * memory.perColumn })
|
||||||
|
: t('wb.power.perPageHint', { count: perPage, mb: perPage * memory.perColumn })}
|
||||||
|
badge={guard ? <Badge tone="warn">{t('wb.power.guard')}</Badge> : undefined} keywords="deck memory ram guard page visible">
|
||||||
|
<Stepper label={t('wb.power.perPage')} value={perPage} min={1} max={12} onChange={maxVisible => save({ maxVisible }, t('wb.power.perPageSaved', { count: maxVisible }))}/>
|
||||||
|
</Row>
|
||||||
|
<Row label={t('wb.power.park')} hint={t('wb.power.parkHint')} keywords="deck memory park low">
|
||||||
|
<Toggle label={t('wb.power.park')} checked={settings.parkOffPage} onChange={parkOffPage => save({ parkOffPage }, parkOffPage ? t('wb.power.parkOn') : t('wb.power.parkOff'))}/>
|
||||||
|
</Row>
|
||||||
|
</Section>
|
||||||
|
<Section title={t('wb.power.decks')} hint={t('wb.power.decksHint')}>
|
||||||
|
{(deckSite.presets ?? []).map(item => {
|
||||||
|
const blocked = !!item.needsTwoAccounts && profiles.length < 2;
|
||||||
|
return <Row key={item.id} label={(item.name ?? item.label)()} hint={item.hint?.()} keywords={`deck preset ${item.needsTwoAccounts ? 'accounts' : item.id}`}>
|
||||||
|
<Button size="sm" disabled={blocked} onClick={() => preset(item)}>{blocked ? t('wb.power.addAccountFirst') : t('wb.common.create')}</Button>
|
||||||
|
</Row>;
|
||||||
|
})}
|
||||||
|
{decks.list.map(deck => <Row key={deck.id} label={deck.name} hint={t('wb.power.columnCount', { count: deck.columns.length })} keywords="deck">
|
||||||
|
<div className="bt-inline">
|
||||||
|
<Button size="sm" onClick={() => openDeck(deck.id)}>{t('wb.common.open')}</Button>
|
||||||
|
<Button size="sm" tone="ghost" onClick={() => {
|
||||||
|
for (const column of deck.columns) forgetColumn(column.tabId);
|
||||||
|
decks.list = decks.list.filter(d => d.id !== deck.id);
|
||||||
|
saveDecks();
|
||||||
|
notify(t('wb.common.removedNamed', { name: deck.name }));
|
||||||
|
}}>{t('wb.common.remove')}</Button>
|
||||||
|
</div>
|
||||||
|
</Row>)}
|
||||||
|
</Section>
|
||||||
|
<Section title={t('wb.power.keys')} hint={power?.keysHint?.()}>
|
||||||
|
<Row label={t('wb.power.key.column')} hint={t('wb.power.key.columnHint')} keywords="deck keys shortcut"/>
|
||||||
|
<Row label={t('wb.power.key.jump')} hint="Alt+1 … Alt+9" keywords="deck keys shortcut"/>
|
||||||
|
<Row label={t('wb.power.key.page')} hint="Alt+PageUp / Alt+PageDown" keywords="deck keys shortcut"/>
|
||||||
|
<Row label={t('wb.power.key.read')} hint="Alt+R / Alt+U" keywords="deck keys shortcut unread"/>
|
||||||
|
{deckSite.compose && <Row label={t('wb.power.key.post')} hint={t('wb.power.key.postHint')} keywords="deck keys shortcut compose"/>}
|
||||||
|
<Row label={t('wb.power.key.toggle')} hint="Ctrl+Shift+D" keywords="deck keys shortcut toggle"/>
|
||||||
|
</Section>
|
||||||
|
</>;
|
||||||
|
}
|
||||||
149
packages/shell/src/panel/Settings.tsx
Normal file
149
packages/shell/src/panel/Settings.tsx
Normal file
|
|
@ -0,0 +1,149 @@
|
||||||
|
// Settings rows every app has: the home page, where links open and session restore (waybetter-host
|
||||||
|
// `settings_get/set`), keyword alerts (`alerts_get/set`) and the media panel's folders and
|
||||||
|
// clipboard history (`media_get/set`). Stored natively; applied live to every tab.
|
||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import { invoke } from '../frame/bridge.ts';
|
||||||
|
import { useT } from '../frame/hooks.ts';
|
||||||
|
import { CLIP_MAX_LIMIT, clampClipMax, folderLabel, withoutFolder, type MediaSettings } from '../frame/mediaModel.ts';
|
||||||
|
import { site } from '../frame/site.ts';
|
||||||
|
import { ChipList, Button, InputRow, Row, Section, Segmented, Stepper, Toggle } from './controls.tsx';
|
||||||
|
import { panelSite, type Notify } from './site.ts';
|
||||||
|
|
||||||
|
/** The shell's settings (waybetter-host `ShellSettings`). */
|
||||||
|
export type ShellSettings = {
|
||||||
|
homeUrl: string;
|
||||||
|
/** Links to other sites: beside the tab (split), a new tab, or the system browser. */
|
||||||
|
externalLinks: 'pane' | 'tab' | 'browser';
|
||||||
|
/** Site pages clicked in the page: the site's in-place navigation, beside, a new tab, or the system browser. */
|
||||||
|
siteLinks: 'same' | 'pane' | 'tab' | 'browser';
|
||||||
|
restoreTabs: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
const getError = (error: unknown) => error instanceof Error ? error.message : String(error);
|
||||||
|
const FOLDER_ICON = <svg width="13" height="13" viewBox="0 0 16 16" aria-hidden="true"><path d="M2 4.5A1.5 1.5 0 0 1 3.5 3h3l1.5 1.5h4.5A1.5 1.5 0 0 1 14 6v5.5a1.5 1.5 0 0 1-1.5 1.5h-9A1.5 1.5 0 0 1 2 11.5z" fill="none" stroke="currentColor" strokeWidth="1.3"/></svg>;
|
||||||
|
|
||||||
|
type Opens = 'same' | 'pane' | 'tab' | 'browser';
|
||||||
|
const OPENS: Record<Opens, string> = { same: 'wb.settings.links.opens.same', pane: 'wb.settings.links.opens.pane', tab: 'wb.settings.links.opens.tab', browser: 'wb.settings.links.opens.browser' };
|
||||||
|
|
||||||
|
/** Home page, where links open, session restore. Stored natively; read by the tab webviews. */
|
||||||
|
export function BrowserSettings({ notify }: { notify: Notify }) {
|
||||||
|
const t = useT();
|
||||||
|
const [settings, setSettings] = useState<ShellSettings | null>(null);
|
||||||
|
const [home, setHome] = useState('');
|
||||||
|
|
||||||
|
useEffect(() => { invoke<ShellSettings>('settings_get').then(value => { setSettings(value); setHome(value.homeUrl); }).catch(err => notify(getError(err), true)); }, []);
|
||||||
|
|
||||||
|
async function save(next: ShellSettings, message: string) {
|
||||||
|
const previous = settings;
|
||||||
|
setSettings(next);
|
||||||
|
try { const saved = await invoke<ShellSettings>('settings_set', { settings: next }); setSettings(saved); setHome(saved.homeUrl); notify(message); }
|
||||||
|
catch (err) { setSettings(previous); notify(getError(err), true); }
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!settings) return null;
|
||||||
|
const siteHome = site().homeUrl;
|
||||||
|
return <Section title={t('wb.settings.links.title')} hint={t('wb.settings.links.hint')}>
|
||||||
|
<Row label={t('wb.settings.home.label')} hint={t('wb.settings.home.hint')} keywords="new tab start url" wide>
|
||||||
|
<div className="bt-inline">
|
||||||
|
<InputRow label={t('wb.settings.home.url')} mono value={home} onChange={setHome} button={t('wb.common.save')} disabled={home === settings.homeUrl}
|
||||||
|
onSubmit={() => void save({ ...settings, homeUrl: home }, t('wb.settings.home.saved'))}/>
|
||||||
|
{settings.homeUrl !== siteHome && <Button tone="ghost" size="sm" onClick={() => void save({ ...settings, homeUrl: siteHome }, t('wb.settings.home.resetDone'))}>{t('wb.settings.home.reset')}</Button>}
|
||||||
|
</div>
|
||||||
|
</Row>
|
||||||
|
<Row label={t('wb.settings.links.external')} hint={t('wb.settings.links.externalHint')} keywords="external open browser pane split side">
|
||||||
|
<Segmented label={t('wb.settings.links.external')} value={settings.externalLinks} onChange={mode => void save({ ...settings, externalLinks: mode }, t('wb.settings.links.externalSaved', { how: t(OPENS[mode as Opens]) }))}
|
||||||
|
options={[{ value: 'pane', label: t('wb.settings.links.beside') }, { value: 'tab', label: t('wb.settings.links.newTab') }, { value: 'browser', label: t('wb.settings.links.browser') }]}/>
|
||||||
|
</Row>
|
||||||
|
<Row label={t('wb.settings.links.site')} hint={t('wb.settings.links.siteHint')} keywords={`${panelSite().settings?.linkKeywords ?? site().name} post profile open pane split side tab`}>
|
||||||
|
<Segmented label={t('wb.settings.links.site')} value={settings.siteLinks} onChange={mode => void save({ ...settings, siteLinks: mode }, t('wb.settings.links.siteSaved', { how: t(OPENS[mode as Opens]) }))}
|
||||||
|
options={[{ value: 'same', label: t('wb.settings.links.sameTab') }, { value: 'pane', label: t('wb.settings.links.beside') }, { value: 'tab', label: t('wb.settings.links.newTab') }, { value: 'browser', label: t('wb.settings.links.browser') }]}/>
|
||||||
|
</Row>
|
||||||
|
<Row label={t('wb.settings.restore.label')} hint={t('wb.settings.restore.hint')} keywords="session">
|
||||||
|
<Toggle label={t('wb.settings.restore.label')} checked={settings.restoreTabs} onChange={next => void save({ ...settings, restoreTabs: next }, next ? t('wb.settings.restore.on') : t('wb.settings.restore.off'))}/>
|
||||||
|
</Row>
|
||||||
|
</Section>;
|
||||||
|
}
|
||||||
|
|
||||||
|
type Alerts = { enabled: boolean; keywords: string[] };
|
||||||
|
export const parseKeywords = (text: string) => text.split(/[,\n]/).map(word => word.trim()).filter(Boolean);
|
||||||
|
const MAX_KEYWORDS = 32;
|
||||||
|
|
||||||
|
/** Keyword alerts: local OS notifications for keywords in items the site already loaded. Native only. */
|
||||||
|
export function AlertSettings({ notify }: { notify: Notify }) {
|
||||||
|
const t = useT();
|
||||||
|
const [alerts, setAlerts] = useState<Alerts | null>(null);
|
||||||
|
const [text, setText] = useState('');
|
||||||
|
|
||||||
|
useEffect(() => { invoke<Alerts>('alerts_get').then(setAlerts).catch(err => notify(getError(err), true)); }, []);
|
||||||
|
|
||||||
|
async function save(next: Alerts, message: string) {
|
||||||
|
const previous = alerts;
|
||||||
|
setAlerts(next);
|
||||||
|
try { setAlerts(await invoke<Alerts>('alerts_set', { settings: next })); notify(message); }
|
||||||
|
catch (err) { setAlerts(previous); notify(getError(err), true); }
|
||||||
|
}
|
||||||
|
function add() {
|
||||||
|
if (!alerts) return;
|
||||||
|
const known = new Set(alerts.keywords.map(word => word.toLowerCase()));
|
||||||
|
const fresh = parseKeywords(text).filter(word => !known.has(word.toLowerCase()));
|
||||||
|
if (!fresh.length) { setText(''); return; }
|
||||||
|
const keywords = [...alerts.keywords, ...fresh].slice(0, MAX_KEYWORDS);
|
||||||
|
setText('');
|
||||||
|
void save({ ...alerts, keywords }, fresh.length === 1 ? t('wb.settings.alerts.watching', { word: fresh[0]! }) : t('wb.settings.alerts.watchingMore', { count: fresh.length }));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!alerts) return null;
|
||||||
|
return <Section title={t('wb.settings.alerts.title')} hint={t('wb.settings.alerts.hint')}>
|
||||||
|
<Row label={t('wb.settings.alerts.label')} hint={alerts.enabled ? t('wb.settings.alerts.onCount', { count: alerts.keywords.length }) : t('wb.common.off')} keywords="keyword notification notify">
|
||||||
|
<Toggle label={t('wb.settings.alerts.title')} checked={alerts.enabled} onChange={next => void save({ ...alerts, enabled: next }, next ? t('wb.settings.alerts.turnedOn') : t('wb.settings.alerts.turnedOff'))}/>
|
||||||
|
</Row>
|
||||||
|
<Row label={t('wb.settings.alerts.keywords')} hint={t('wb.settings.alerts.keywordsHint', { max: MAX_KEYWORDS })} keywords="alert words watch" wide>
|
||||||
|
<div className="bt-stack">
|
||||||
|
<ChipList items={alerts.keywords} empty={t('wb.settings.alerts.none')} onRemove={word => void save({ ...alerts, keywords: alerts.keywords.filter(item => item !== word) }, t('wb.settings.alerts.stopped', { word }))}/>
|
||||||
|
<InputRow label={t('wb.settings.alerts.add')} placeholder="tauri, waybetter" value={text} onChange={setText} button={t('wb.common.add')} disabled={!parseKeywords(text).length || alerts.keywords.length >= MAX_KEYWORDS} onSubmit={add}/>
|
||||||
|
</div>
|
||||||
|
</Row>
|
||||||
|
</Section>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Gallery folders and the opt-in clipboard history for the Media panel (Ctrl+Shift+G). Native only. */
|
||||||
|
export function MediaSettingsRows({ notify }: { notify: Notify }) {
|
||||||
|
const t = useT();
|
||||||
|
const [settings, setSettings] = useState<MediaSettings | null>(null);
|
||||||
|
useEffect(() => { invoke<MediaSettings>('media_get').then(setSettings).catch(err => notify(getError(err), true)); }, []);
|
||||||
|
|
||||||
|
async function save(next: MediaSettings, message?: string) {
|
||||||
|
const previous = settings;
|
||||||
|
setSettings(next);
|
||||||
|
try { setSettings(await invoke<MediaSettings>('media_set', { settings: next })); if (message) notify(message); }
|
||||||
|
catch (err) { setSettings(previous); notify(getError(err), true); }
|
||||||
|
}
|
||||||
|
async function addFolder() {
|
||||||
|
try { setSettings(await invoke<MediaSettings>('gallery_add_folder')); }
|
||||||
|
catch (err) { notify(getError(err), true); }
|
||||||
|
}
|
||||||
|
async function clearHistory() {
|
||||||
|
try { await invoke('clip_remove', { id: null }); notify(t('wb.settings.media.cleared')); }
|
||||||
|
catch (err) { notify(getError(err), true); }
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!settings) return null;
|
||||||
|
return <Section title={t('wb.settings.media.title')} hint={t('wb.settings.media.hint')}>
|
||||||
|
<Row label={t('wb.settings.media.folders')} hint={t('wb.settings.media.foldersHint')} keywords="images pictures screenshots" wide>
|
||||||
|
<div className="bt-stack">
|
||||||
|
<ChipList items={settings.folders} icon={FOLDER_ICON} render={folderLabel} empty={t('wb.settings.media.noFolders')}
|
||||||
|
onRemove={folder => void save(withoutFolder(settings, folder), t('wb.settings.media.folderRemoved'))}/>
|
||||||
|
<div><Button size="sm" onClick={() => void addFolder()} icon={<span aria-hidden="true">+</span>}>{t('wb.settings.media.addFolder')}</Button></div>
|
||||||
|
</div>
|
||||||
|
</Row>
|
||||||
|
<Row label={t('wb.settings.media.clipboard')} hint={t('wb.settings.media.clipboardHint')} keywords="copy paste">
|
||||||
|
<Toggle label={t('wb.settings.media.clipboard')} checked={settings.clipboardEnabled} onChange={next => void save({ ...settings, clipboardEnabled: next }, next ? t('wb.settings.media.clipboardOn') : t('wb.settings.media.clipboardOff'))}/>
|
||||||
|
</Row>
|
||||||
|
{settings.clipboardEnabled && <Row label={t('wb.settings.media.keep')} hint={t('wb.settings.media.keepHint')} keywords="clipboard size">
|
||||||
|
<div className="bt-inline">
|
||||||
|
<Stepper label={t('wb.settings.media.keep')} value={settings.clipboardMax} min={1} max={CLIP_MAX_LIMIT} onChange={value => void save({ ...settings, clipboardMax: clampClipMax(value) })}/>
|
||||||
|
<Button size="sm" tone="ghost" onClick={() => void clearHistory()}>{t('wb.common.clear')}</Button>
|
||||||
|
</div>
|
||||||
|
</Row>}
|
||||||
|
</Section>;
|
||||||
|
}
|
||||||
57
packages/shell/src/panel/StoreSection.tsx
Normal file
57
packages/shell/src/panel/StoreSection.tsx
Normal file
|
|
@ -0,0 +1,57 @@
|
||||||
|
// The wayBetter Store section: the Store view (StoreView.tsx) with the panel's own controls, the
|
||||||
|
// app's built-in and own themes, and removal of installed items. Native code verifies the catalog's
|
||||||
|
// Ed25519 signature, keeps the app's items, then checks each download's sha256. Installing always
|
||||||
|
// goes through the shell's install screen (InstallDialog), never straight from here.
|
||||||
|
import { invoke } from '../frame/bridge.ts';
|
||||||
|
import { useT } from '../frame/hooks.ts';
|
||||||
|
import { relativeTime } from '../frame/i18n.ts';
|
||||||
|
import { site } from '../frame/site.ts';
|
||||||
|
import type { StoreCatalogView, StoreItem } from '../storeModel.ts';
|
||||||
|
import { StoreView, type StoreControls } from '../StoreView.tsx';
|
||||||
|
import '../store.css';
|
||||||
|
import { Badge, Button, EmptyState, SearchField, Segmented, useSettingsQuery } from './controls.tsx';
|
||||||
|
import { panelSite, panelThemes, type Notify } from './site.ts';
|
||||||
|
import { useThemeState } from './themes.ts';
|
||||||
|
import './plugins.css';
|
||||||
|
|
||||||
|
const CONTROLS: Partial<StoreControls> = { Button, SearchField, Segmented, EmptyState, Badge };
|
||||||
|
const RELOAD_ON = ['bt-plugins-changed', 'bt-store-changed'];
|
||||||
|
|
||||||
|
export function StoreSection({ notify }: { notify: Notify }) {
|
||||||
|
const t = useT();
|
||||||
|
const { store, catalog } = panelThemes();
|
||||||
|
const themes = useThemeState();
|
||||||
|
const settingsQuery = useSettingsQuery();
|
||||||
|
if (settingsQuery) return null;
|
||||||
|
const userThemes = themes.choice.themes.map(theme => theme.id);
|
||||||
|
|
||||||
|
async function remove(item: StoreItem, view: StoreCatalogView): Promise<boolean> {
|
||||||
|
if (item.kind === 'plugin' && item.file) {
|
||||||
|
await invoke('plugin_remove', { file: item.file });
|
||||||
|
window.dispatchEvent(new CustomEvent('bt-plugins-changed'));
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
const record = Object.entries(view.records.items).find(([key, value]) => key.startsWith('theme:') && value.storeId === item.id && userThemes.includes(key.slice(6)));
|
||||||
|
const id = record?.[0].slice(6);
|
||||||
|
if (!id) return false;
|
||||||
|
const choice = themes.choice;
|
||||||
|
await store.setChoice({ ...choice, themes: choice.themes.filter(theme => theme.id !== id), ...(choice.preset === id ? { preset: catalog.defaultChoice.preset, overrides: {}, accent: null } : {}) });
|
||||||
|
await invoke('install_forget', { kind: 'theme', name: id });
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return <StoreView
|
||||||
|
t={t}
|
||||||
|
site={site().name}
|
||||||
|
load={refresh => invoke<StoreCatalogView>('store_catalog', { refresh })}
|
||||||
|
controller={panelSite().store!.controller}
|
||||||
|
builtinThemes={catalog.builtins.map(theme => theme.id)}
|
||||||
|
userThemes={userThemes}
|
||||||
|
onRemove={remove}
|
||||||
|
onUse={item => store.setChoice({ ...themes.choice, preset: item.id, overrides: {}, accent: null })}
|
||||||
|
notify={notify}
|
||||||
|
relativeTime={relativeTime}
|
||||||
|
reloadOn={RELOAD_ON}
|
||||||
|
controls={CONTROLS}
|
||||||
|
/>;
|
||||||
|
}
|
||||||
332
packages/shell/src/panel/ThemeBuilder.tsx
Normal file
332
packages/shell/src/panel/ThemeBuilder.tsx
Normal file
|
|
@ -0,0 +1,332 @@
|
||||||
|
// The Theme Builder: a full editor for a theme document with a live preview on the real site panes (a
|
||||||
|
// native, unsaved preview; closing the builder gives every tab its own theme back), the local
|
||||||
|
// miniature and the chrome. Three base colors derive the whole palette; a contrast report shows every
|
||||||
|
// pair the site draws and can fix them; fonts per role with the Google Fonts browser; shape, layout,
|
||||||
|
// background, effects and theme CSS. Undo/redo (Ctrl+Z / Ctrl+Shift+Z), Save as theme, Export, Share.
|
||||||
|
import { useCallback, useEffect, useMemo, useRef, useState, type CSSProperties, type ReactNode } from 'react';
|
||||||
|
import {
|
||||||
|
MAX_CSS_CHARS, MAX_IMAGE_CHARS, isHex, sanitizeSpec,
|
||||||
|
type Background, type EffectsSpec, type FontRole, type FontRoleName, type FontSpec, type LayoutSpec, type Pattern, type ShapeSpec, type ThemeColors, type ThemeSpec,
|
||||||
|
} from '../../../runtime/src/themeSpec.ts';
|
||||||
|
import { chromeVars } from '../frame/chromeTheme.ts';
|
||||||
|
import { useT } from '../frame/hooks.ts';
|
||||||
|
import { formatNumber, t, tx } from '../frame/i18n.ts';
|
||||||
|
import { ThemeDots } from '../frame/PaneTheme.tsx';
|
||||||
|
import {
|
||||||
|
DERIVED_ROLES, autoFix, contrastReport, draftFrom, modeOf, paletteFrom, pinnedRoles, record, redo, startHistory, themeJson, undo, uniqueId, wcagLevel,
|
||||||
|
type DerivedRole, type DraftSite, type History,
|
||||||
|
} from './builderModel.ts';
|
||||||
|
import { Button, ColorField, Segmented, Select, Slider, Toggle, type Option } from './controls.tsx';
|
||||||
|
import { FontRoles } from './fonts/FontRoles.tsx';
|
||||||
|
import { panelSite, panelThemes, type Notify } from './site.ts';
|
||||||
|
import { useThemeState } from './themes.ts';
|
||||||
|
import './builder.css';
|
||||||
|
|
||||||
|
/** Swatches for the three base colors when the app names none. */
|
||||||
|
const BASE_SWATCHES = {
|
||||||
|
bg: ['#000000', '#0b0d12', '#15202b', '#1a1b26', '#2e3440', '#ffffff', '#fbf8f1', '#fdf6e3'],
|
||||||
|
text: ['#e7e9ea', '#eef0f7', '#ffffff', '#c0caf5', '#0f1419', '#2a241d', '#073642', '#000000'],
|
||||||
|
accent: ['#1d9bf0', '#5b8cff', '#7856ff', '#bd93f9', '#f91880', '#ff7a00', '#00ba7c', '#3dff7a'],
|
||||||
|
};
|
||||||
|
const ROLE_LABEL: Record<DerivedRole, string> = { surface: 'wb.builder.role.surface', elevated: 'wb.builder.role.elevated', border: 'wb.builder.role.border', muted: 'wb.builder.role.muted', inverse: 'wb.builder.role.inverse', onInverse: 'wb.builder.role.onInverse', page: 'wb.builder.role.page' };
|
||||||
|
const px = (v: number) => t('wb.appearance.px', { value: v });
|
||||||
|
const pct = (v: number) => t('wb.appearance.percent', { value: v / 100 });
|
||||||
|
const PATTERNS: Pattern[] = ['dots', 'grid', 'diagonal', 'scanlines', 'paper', 'clouds'];
|
||||||
|
type BackgroundKind = 'none' | 'gradient' | 'pattern' | 'image';
|
||||||
|
|
||||||
|
export function ThemeBuilder({ notify }: { notify: Notify }) {
|
||||||
|
const t = useT();
|
||||||
|
const themes = panelThemes();
|
||||||
|
const { allThemes, missingFonts, setChoice, setPreview, themeState } = themes.store;
|
||||||
|
const resolveTheme = themes.catalog.resolve;
|
||||||
|
const ThemePreview = themes.Preview;
|
||||||
|
const draftSite: DraftSite = { colors: themes.draftColors, siteTheme: themes.catalog.defaultChoice.preset };
|
||||||
|
const swatches = themes.baseSwatches ?? BASE_SWATCHES;
|
||||||
|
const { ready, choice } = useThemeState();
|
||||||
|
const [history, setHistory] = useState<History | null>(null);
|
||||||
|
const [live, setLive] = useState(true);
|
||||||
|
const dragFrom = useRef<ThemeSpec | null>(null);
|
||||||
|
|
||||||
|
// Start from the theme that is on now.
|
||||||
|
useEffect(() => { if (ready && !history) setHistory(startHistory(draftFrom(resolveTheme(choice), draftSite))); }, [ready]);
|
||||||
|
const draft = history?.present ?? null;
|
||||||
|
|
||||||
|
// Live on the real site panes and the chrome (debounced), until the builder closes.
|
||||||
|
useEffect(() => {
|
||||||
|
if (!draft) return;
|
||||||
|
const timer = setTimeout(() => void setPreview(live ? draft : null), 120);
|
||||||
|
return () => clearTimeout(timer);
|
||||||
|
}, [draft, live]);
|
||||||
|
useEffect(() => () => { void setPreview(null); }, []);
|
||||||
|
|
||||||
|
/** Applies a change; `commit: false` while a slider drags (one undo step per drag). */
|
||||||
|
const change = useCallback((next: ThemeSpec, commit = true) => {
|
||||||
|
setHistory(current => {
|
||||||
|
if (!current) return current;
|
||||||
|
if (!commit) { dragFrom.current ??= current.present; return record(current, next, { commit: false }); }
|
||||||
|
const from = dragFrom.current ?? undefined;
|
||||||
|
dragFrom.current = null;
|
||||||
|
return record(current, next, { from });
|
||||||
|
});
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Ctrl+Z / Ctrl+Shift+Z / Ctrl+Y anywhere while the builder is open, except inside text fields.
|
||||||
|
useEffect(() => {
|
||||||
|
const onKey = (event: KeyboardEvent) => {
|
||||||
|
const target = event.target as HTMLElement | null;
|
||||||
|
if (target && (target.isContentEditable || (/^(input|textarea)$/i.test(target.tagName) && !/^(range|color|checkbox)$/.test((target as HTMLInputElement).type)))) return;
|
||||||
|
if (!(event.ctrlKey || event.metaKey) || event.altKey) return;
|
||||||
|
const key = event.key.toLowerCase();
|
||||||
|
if (key === 'z' && !event.shiftKey) { event.preventDefault(); setHistory(h => h && undo(h)); }
|
||||||
|
else if ((key === 'z' && event.shiftKey) || key === 'y') { event.preventDefault(); setHistory(h => h && redo(h)); }
|
||||||
|
};
|
||||||
|
window.addEventListener('keydown', onKey);
|
||||||
|
return () => window.removeEventListener('keydown', onKey);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
if (!draft || !history) return <div className="wb-builder is-loading" aria-busy="true"/>;
|
||||||
|
const colors = draft.colors!;
|
||||||
|
const set = <K extends keyof ThemeSpec>(key: K, value: ThemeSpec[K], commit = true) => change({ ...draft, [key]: value }, commit);
|
||||||
|
const setColors = (next: ThemeColors, commit = true) => change({ ...draft, colors: next, mode: modeOf(next) }, commit);
|
||||||
|
const setBase = (role: 'bg' | 'text' | 'accent', value: string) => {
|
||||||
|
const base = { bg: colors.bg, text: colors.text, accent: colors.accent, [role]: value };
|
||||||
|
// A new base re-derives every other role (hand-set roles belong to the old base).
|
||||||
|
setColors(paletteFrom(base));
|
||||||
|
};
|
||||||
|
const setFont = (patch: Partial<FontSpec>, commit = true) => set('font', sanitizeSpec({ name: 'x', font: { ...draft.font, ...patch } }).font, commit);
|
||||||
|
const setRole = (role: FontRoleName, next: FontRole, commit = true) => setFont({ roles: { ...draft.font.roles, [role]: next } }, commit);
|
||||||
|
const setShape = (patch: Partial<ShapeSpec>, commit = true) => set('shape', { ...draft.shape, ...patch }, commit);
|
||||||
|
const setLayout = (patch: Partial<LayoutSpec>, commit = true) => set('layout', { ...draft.layout, ...patch }, commit);
|
||||||
|
const setEffects = (patch: Partial<EffectsSpec>, commit = true) => set('effects', { ...draft.effects, ...patch }, commit);
|
||||||
|
|
||||||
|
const startFrom = (id: string) => {
|
||||||
|
const theme = allThemes(choice).find(item => item.id === id);
|
||||||
|
if (!theme) return;
|
||||||
|
change(draftFrom(id === choice.preset ? resolveTheme(choice) : theme, draftSite));
|
||||||
|
notify(t('wb.builder.startedFrom', { name: theme.name }));
|
||||||
|
};
|
||||||
|
|
||||||
|
async function save() {
|
||||||
|
const state = themeState();
|
||||||
|
const missing = missingFonts(draft!);
|
||||||
|
const id = uniqueId(draft!.name, [...themes.catalog.builtins, ...state.choice.themes].map(theme => theme.id));
|
||||||
|
const theme = sanitizeSpec({ ...draft!, id });
|
||||||
|
try {
|
||||||
|
await setChoice({ ...state.choice, themes: [...state.choice.themes, theme], preset: id, overrides: {}, accent: null });
|
||||||
|
notify(`${t('wb.builder.saved', { name: theme.name })}${missing.length ? ` ${t('wb.builder.savedMissing', { fonts: missing.join(', '), count: missing.length })}` : ''}`);
|
||||||
|
} catch (error) { notify(error instanceof Error ? error.message : String(error), true); }
|
||||||
|
}
|
||||||
|
function exportFile() {
|
||||||
|
const url = URL.createObjectURL(new Blob([themeJson(draft!)], { type: 'application/json' }));
|
||||||
|
const anchor = document.createElement('a');
|
||||||
|
anchor.href = url; anchor.download = `${draft!.id}${themes.fileSuffix ?? '.theme.json'}`; anchor.click();
|
||||||
|
setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||||||
|
}
|
||||||
|
async function share() {
|
||||||
|
try { await navigator.clipboard.writeText(themeJson(draft!)); notify(t('wb.builder.shared')); }
|
||||||
|
catch { notify(t('wb.builder.copyFailed'), true); }
|
||||||
|
}
|
||||||
|
|
||||||
|
const report = contrastReport(colors);
|
||||||
|
const failing = report.filter(check => !check.pass).length;
|
||||||
|
const options: Array<Option<string>> = allThemes(choice).map(theme => ({ value: theme.id, label: theme.name, icon: <ThemeDots theme={theme}/> }));
|
||||||
|
|
||||||
|
return <div className="wb-builder">
|
||||||
|
<div className="wb-builder-bar" role="toolbar" aria-label={t('wb.panel.section.builder')}>
|
||||||
|
<input className="wb-builder-name" aria-label={t('wb.builder.name')} value={draft.name} maxLength={60} spellCheck={false}
|
||||||
|
onChange={event => set('name', event.target.value, false)} onBlur={event => set('name', event.target.value.trim() || t('wb.builder.untitled'))}/>
|
||||||
|
<div className="wb-builder-tools">
|
||||||
|
<Select label={t('wb.builder.startFrom')} value={null} placeholder={t('wb.builder.startFromPlaceholder')} options={options} width={176} onChange={startFrom}/>
|
||||||
|
<span className="wb-divider" aria-hidden="true"/>
|
||||||
|
<IconButton label={t('wb.builder.undo')} disabled={!history.past.length} onClick={() => setHistory(h => h && undo(h))} d="M6 4 3 7l3 3M3 7h7a4 4 0 0 1 0 8H8"/>
|
||||||
|
<IconButton label={t('wb.builder.redo')} disabled={!history.future.length} onClick={() => setHistory(h => h && redo(h))} d="m10 4 3 3-3 3M13 7H6a4 4 0 0 0 0 8h2"/>
|
||||||
|
<span className="wb-divider" aria-hidden="true"/>
|
||||||
|
<label className="wb-live"><Toggle label={t('wb.builder.previewLive')} checked={live} onChange={setLive}/><span>{t('wb.builder.liveOnSite')}</span></label>
|
||||||
|
<Button size="sm" tone="ghost" onClick={() => void share()}>{t('wb.builder.share')}</Button>
|
||||||
|
<Button size="sm" tone="ghost" onClick={exportFile}>{t('wb.common.export')}</Button>
|
||||||
|
<Button size="sm" tone="primary" onClick={() => void save()}>{t('wb.appearance.saveAsTheme')}</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="wb-builder-grid">
|
||||||
|
<div className="wb-builder-controls">
|
||||||
|
<Card title={t('wb.builder.colors')} hint={t('wb.builder.colorsHint')}>
|
||||||
|
<div className="wb-base">
|
||||||
|
{(['bg', 'text', 'accent'] as const).map(role => <div key={role} className="wb-base-item">
|
||||||
|
<div className="wb-base-swatch" style={{ background: colors[role] }}><span style={{ color: role === 'bg' ? colors.text : colors.bg }}>{role === 'bg' ? t('wb.appearance.background') : role === 'text' ? t('wb.builder.text') : t('wb.appearance.accent')}</span><code>{colors[role]}</code></div>
|
||||||
|
<ColorField label={role === 'bg' ? t('wb.builder.backgroundColor') : role === 'text' ? t('wb.builder.textColor') : t('wb.appearance.accentColor')} value={colors[role]} swatches={swatches[role]} onChange={value => value && setBase(role, value)}/>
|
||||||
|
</div>)}
|
||||||
|
</div>
|
||||||
|
<Palette colors={colors} onChange={setColors}/>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Card title={t('wb.builder.contrast')} hint={t('wb.builder.contrastHint')}
|
||||||
|
action={failing ? <Button size="sm" tone="primary" onClick={() => { setColors(autoFix(colors)); notify(t('wb.builder.adjusted', { count: failing })); }}>{t('wb.builder.autoFix', { count: failing })}</Button> : <span className="wb-ok">{t('wb.builder.allPass')}</span>}>
|
||||||
|
<ul className="wb-contrast">
|
||||||
|
{report.map(check => <li key={check.id} className={check.pass ? 'is-pass' : 'is-fail'}>
|
||||||
|
<span className="wb-contrast-sample" style={{ color: check.fg, background: check.bg }}>Aa</span>
|
||||||
|
<span className="wb-contrast-label">{tx(`wb.builder.contrast.${check.id}`, undefined, check.label)}</span>
|
||||||
|
<span className="wb-contrast-ratio"><b>{formatNumber(check.ratio, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}</b>:1</span>
|
||||||
|
<span className="wb-contrast-need">{t('wb.builder.needs', { ratio: check.need })}</span>
|
||||||
|
<span className={`wb-contrast-badge ${check.pass ? 'is-pass' : 'is-fail'}`}>{check.pass ? wcagLevel(check.ratio) : t('wb.builder.tooLow')}</span>
|
||||||
|
</li>)}
|
||||||
|
</ul>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Card title={t('wb.builder.type')} hint={t('wb.builder.typeHint')}>
|
||||||
|
<FontRoles font={draft.font} onRole={setRole}/>
|
||||||
|
<div className="wb-fields">
|
||||||
|
<Field label={t('wb.appearance.textSize')}><Slider label={t('wb.appearance.textSize')} min={85} max={120} value={Math.round(draft.font.scale * 100)} format={pct} onChange={v => setFont({ scale: v / 100 }, false)} onCommit={v => setFont({ scale: v / 100 })}/></Field>
|
||||||
|
<Field label={t('wb.builder.regularWeight')}><Slider label={t('wb.builder.regularWeight')} min={300} max={500} step={10} value={draft.font.weight} format={String} onChange={v => setFont({ weight: v }, false)} onCommit={v => setFont({ weight: v })}/></Field>
|
||||||
|
<Field label={t('wb.appearance.bold')}><Slider label={t('wb.appearance.bold')} min={500} max={800} step={10} value={draft.font.bold} format={String} onChange={v => setFont({ bold: v }, false)} onCommit={v => setFont({ bold: v })}/></Field>
|
||||||
|
<Field label={t('wb.builder.tracking')}><Slider label={t('wb.builder.tracking')} min={-30} max={60} step={2} value={Math.round(draft.font.tracking * 1000)} format={v => `${formatNumber(v / 1000, { minimumFractionDigits: 3, maximumFractionDigits: 3 })} em`} onChange={v => setFont({ tracking: v / 1000 }, false)} onCommit={v => setFont({ tracking: v / 1000 })}/></Field>
|
||||||
|
<Field label={t('wb.builder.leading')}><Slider label={t('wb.builder.leading')} min={115} max={180} step={5} value={draft.font.leading ? Math.round(draft.font.leading * 100) : 115} format={v => v === 115 ? t('wb.builder.leadingSite') : formatNumber(v / 100, { minimumFractionDigits: 2, maximumFractionDigits: 2 })} onChange={v => setFont({ leading: v === 115 ? 0 : v / 100 }, false)} onCommit={v => setFont({ leading: v === 115 ? 0 : v / 100 })}/></Field>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Card title={t('wb.builder.shape')}>
|
||||||
|
<div className="wb-fields">
|
||||||
|
<Field label={t('wb.builder.cardCorners')}><Slider label={t('wb.builder.cardCorners')} min={0} max={28} value={draft.shape.radius} format={px} onChange={v => setShape({ radius: v }, false)} onCommit={v => setShape({ radius: v })}/></Field>
|
||||||
|
<Field label={t('wb.builder.buttons')}><Segmented label={t('wb.builder.buttonShape')} size="sm" value={draft.shape.button >= 100 ? 'pill' : draft.shape.button === 0 ? 'square' : 'soft'}
|
||||||
|
onChange={v => setShape({ button: v === 'pill' ? 9999 : v === 'square' ? 0 : Math.max(4, Math.min(12, draft.shape.radius)) })}
|
||||||
|
options={[{ value: 'square', label: t('wb.appearance.corners.square') }, { value: 'soft', label: t('wb.appearance.corners.soft') }, { value: 'pill', label: t('wb.builder.pill') }]}/></Field>
|
||||||
|
<Field label={t('wb.appearance.avatars')}><Segmented label={t('wb.appearance.avatars')} size="sm" value={draft.shape.avatar} onChange={avatar => setShape({ 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') }]}/></Field>
|
||||||
|
<Field label={t('wb.appearance.density')}><Segmented label={t('wb.appearance.density')} size="sm" value={draft.layout.density} onChange={density => setLayout({ 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') }]}/></Field>
|
||||||
|
<Field label={t('wb.appearance.timeline')}><Segmented label={t('wb.appearance.timelineStyle')} size="sm" value={draft.layout.cards ? 'cards' : draft.layout.frame ? 'framed' : 'flat'}
|
||||||
|
onChange={v => setLayout({ cards: v === 'cards', frame: v === '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') }]}/></Field>
|
||||||
|
<Field label={t('wb.appearance.timelineWidth')}><Slider label={t('wb.appearance.timelineWidth')} min={520} max={820} step={10} value={draft.layout.column} format={px} onChange={column => setLayout({ column }, false)} onCommit={column => setLayout({ column })}/></Field>
|
||||||
|
<Field label={t('wb.appearance.sidebarWidth')}><Slider label={t('wb.appearance.sidebarWidth')} min={290} max={400} step={10} value={draft.layout.sidebar} format={px} onChange={sidebar => setLayout({ sidebar }, false)} onCommit={sidebar => setLayout({ sidebar })}/></Field>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Card title={t('wb.builder.backgroundEffects')}>
|
||||||
|
<BackgroundEditor background={draft.background} colors={colors} notify={notify} onChange={(background, commit) => set('background', background, commit)}/>
|
||||||
|
<div className="wb-fields">
|
||||||
|
<Field label={t('wb.appearance.motion')}><Slider label={t('wb.appearance.motion')} min={0} max={400} step={10} value={draft.effects.motion} format={v => v ? t('wb.builder.ms', { value: v }) : t('wb.common.off')} onChange={motion => setEffects({ motion }, false)} onCommit={motion => setEffects({ motion })}/></Field>
|
||||||
|
<Field label={t('wb.appearance.hover')}><Segmented label={t('wb.appearance.hoverEffect')} size="sm" value={draft.effects.hover} onChange={hover => setEffects({ 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') }]}/></Field>
|
||||||
|
<Field label={t('wb.builder.shadow')}><Segmented label={t('wb.builder.shadow')} size="sm" value={draft.effects.shadow} onChange={shadow => setEffects({ shadow })}
|
||||||
|
options={[{ value: 'none', label: t('wb.appearance.hover.none') }, { value: 'soft', label: t('wb.appearance.corners.soft') }, { value: 'deep', label: t('wb.builder.deep') }]}/></Field>
|
||||||
|
<Field label={t('wb.appearance.crt')}><Toggle label={t('wb.appearance.crt')} checked={draft.effects.crt} onChange={crt => setEffects({ crt })}/></Field>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
|
||||||
|
<Card title={t('wb.appearance.themeCss')} hint={t('wb.builder.cssHint')}>
|
||||||
|
<div className="bt-code is-compact">
|
||||||
|
<textarea aria-label={t('wb.appearance.themeCss')} spellCheck={false} value={draft.css} maxLength={MAX_CSS_CHARS} placeholder={panelSite().cssExamples?.builder ?? '/* CSS that travels with this theme */'}
|
||||||
|
onChange={event => set('css', event.target.value, false)} onBlur={event => set('css', event.target.value)}/>
|
||||||
|
<div className="bt-code-bar"><small>{t('wb.builder.cssLines', { count: draft.css.split('\n').length })}</small></div>
|
||||||
|
</div>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<aside className="wb-builder-preview" aria-label={t('wb.builder.preview')}>
|
||||||
|
<div className="wb-preview-frame">
|
||||||
|
<ChromePreview theme={draft}/>
|
||||||
|
<ThemePreview theme={draft}/>
|
||||||
|
</div>
|
||||||
|
<p className="wb-preview-note">{live ? <><i className="wb-live-dot"/>{t('wb.builder.liveNote')}</> : t('wb.builder.liveOff')}</p>
|
||||||
|
<div className="wb-meta">
|
||||||
|
<label><span>{t('wb.builder.author')}</span><input value={draft.author} maxLength={60} onChange={event => set('author', event.target.value, false)} onBlur={event => set('author', event.target.value.trim())}/></label>
|
||||||
|
<label><span>{t('wb.builder.description')}</span><textarea rows={2} value={draft.description} maxLength={200} onChange={event => set('description', event.target.value, false)} onBlur={event => set('description', event.target.value.trim())}/></label>
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
</div>
|
||||||
|
</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function Card({ title, hint, action, children }: { title: string; hint?: string; action?: ReactNode; children: ReactNode }) {
|
||||||
|
return <section className="wb-card" aria-label={title}>
|
||||||
|
<header><div><h3>{title}</h3>{hint && <p>{hint}</p>}</div>{action}</header>
|
||||||
|
{children}
|
||||||
|
</section>;
|
||||||
|
}
|
||||||
|
const Field = ({ label, children }: { label: string; children: ReactNode }) => <div className="wb-field"><span>{label}</span>{children}</div>;
|
||||||
|
|
||||||
|
function IconButton({ label, d, onClick, disabled }: { label: string; d: string; onClick(): void; disabled?: boolean }) {
|
||||||
|
return <button type="button" className="wb-icon-button" aria-label={label} title={label} disabled={disabled} onClick={onClick}>
|
||||||
|
<svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><path d={d} fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
|
||||||
|
</button>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Every derived role as a swatch; a click opens its color field, "Auto" un-pins it. */
|
||||||
|
function Palette({ colors, onChange }: { colors: ThemeColors; onChange(next: ThemeColors): void }) {
|
||||||
|
const t = useT();
|
||||||
|
const [editing, setEditing] = useState<DerivedRole | null>(null);
|
||||||
|
const pinned = pinnedRoles(colors);
|
||||||
|
const base = { bg: colors.bg, text: colors.text, accent: colors.accent };
|
||||||
|
return <div className="wb-palette">
|
||||||
|
<div className="wb-palette-row" role="list" aria-label={t('wb.builder.paletteRoles')}>
|
||||||
|
{DERIVED_ROLES.map(role => <button key={role} type="button" role="listitem" className={`wb-chip ${editing === role ? 'is-on' : ''}`} aria-expanded={editing === role} onClick={() => setEditing(editing === role ? null : role)}>
|
||||||
|
<span className="wb-chip-swatch" style={{ background: colors[role] }}/>
|
||||||
|
<span className="wb-chip-copy"><b>{t(ROLE_LABEL[role])}</b><small>{pinned[role] ? t('wb.builder.setByHand') : t('wb.builder.derived')} · {colors[role]}</small></span>
|
||||||
|
</button>)}
|
||||||
|
</div>
|
||||||
|
{editing && <div className="wb-palette-edit">
|
||||||
|
<span>{t(ROLE_LABEL[editing])}</span>
|
||||||
|
<ColorField label={t(ROLE_LABEL[editing])} value={pinned[editing] ? colors[editing]! : null} autoLabel={t('wb.builder.auto')} swatches={[]}
|
||||||
|
onChange={value => {
|
||||||
|
const next = { ...pinned } as Partial<Record<DerivedRole, string>>;
|
||||||
|
if (value && isHex(value)) next[editing] = value; else delete next[editing];
|
||||||
|
onChange(paletteFrom(base, next));
|
||||||
|
}}/>
|
||||||
|
</div>}
|
||||||
|
</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function BackgroundEditor({ background, colors, notify, onChange }: { background: Background; colors: ThemeColors; notify: Notify; onChange(next: Background, commit?: boolean): void }) {
|
||||||
|
const t = useT();
|
||||||
|
const file = useRef<HTMLInputElement>(null);
|
||||||
|
const kind: BackgroundKind = background.kind;
|
||||||
|
const page = colors.page ?? colors.bg;
|
||||||
|
const switchTo = (next: BackgroundKind) => {
|
||||||
|
if (next === 'none') onChange({ kind: 'none' });
|
||||||
|
else if (next === 'gradient') onChange({ kind: 'gradient', from: page, to: page, angle: 180, glow: colors.accent });
|
||||||
|
else if (next === 'pattern') onChange({ kind: 'pattern', pattern: 'dots', ink: colors.text, opacity: 0.12, size: 22 });
|
||||||
|
else file.current?.click();
|
||||||
|
};
|
||||||
|
async function pick(input: File | undefined) {
|
||||||
|
if (!input) return;
|
||||||
|
if (!/^image\/(png|jpeg|webp|gif|avif)$/.test(input.type)) { notify(t('wb.appearance.imageType'), true); return; }
|
||||||
|
const url = await new Promise<string>((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(String(reader.result)); reader.onerror = () => reject(reader.error); reader.readAsDataURL(input); });
|
||||||
|
if (url.length > MAX_IMAGE_CHARS) { notify(t('wb.appearance.imageTooLarge'), true); return; }
|
||||||
|
onChange({ kind: 'image', url, fit: 'cover', dim: modeOf(colors) === 'light' ? 0.55 : 0.6 });
|
||||||
|
}
|
||||||
|
return <div className="wb-bg">
|
||||||
|
<Segmented<BackgroundKind> label={t('wb.appearance.background')} size="sm" value={kind} onChange={switchTo}
|
||||||
|
options={[{ value: 'none', label: t('wb.appearance.bg.none') }, { value: 'gradient', label: t('wb.builder.gradient') }, { value: 'pattern', label: t('wb.builder.pattern') }, { value: 'image', label: t('wb.appearance.bg.image') }]}/>
|
||||||
|
<input ref={file} type="file" hidden accept="image/png,image/jpeg,image/webp,image/gif,image/avif" onChange={event => { void pick(event.target.files?.[0]); event.target.value = ''; }}/>
|
||||||
|
{background.kind === 'gradient' && <div className="wb-fields">
|
||||||
|
<Field label={t('wb.builder.from')}><ColorField label={t('wb.builder.gradientStart')} value={background.from} swatches={[page, colors.bg, colors.surface]} onChange={v => v && onChange({ ...background, from: v })}/></Field>
|
||||||
|
<Field label={t('wb.builder.to')}><ColorField label={t('wb.builder.gradientEnd')} value={background.to} swatches={[page, colors.bg, colors.elevated]} onChange={v => v && onChange({ ...background, to: v })}/></Field>
|
||||||
|
<Field label={t('wb.appearance.bg.glow')}><ColorField label={t('wb.appearance.bg.glow')} value={background.glow ?? null} autoLabel={t('wb.appearance.hover.none')} swatches={[colors.accent]} onChange={v => onChange({ ...background, glow: v ?? undefined })}/></Field>
|
||||||
|
<Field label={t('wb.builder.angle')}><Slider label={t('wb.builder.gradientAngle')} min={0} max={360} step={5} value={background.angle} format={v => `${formatNumber(v)}°`} onChange={angle => onChange({ ...background, angle }, false)} onCommit={angle => onChange({ ...background, angle })}/></Field>
|
||||||
|
</div>}
|
||||||
|
{background.kind === 'pattern' && <div className="wb-fields">
|
||||||
|
<Field label={t('wb.builder.pattern')}><Select<Pattern> label={t('wb.builder.pattern')} value={background.pattern} width={160} onChange={pattern => onChange({ ...background, pattern })} options={PATTERNS.map(value => ({ value, label: tx(`wb.appearance.bg.${value}`, undefined, value) }))}/></Field>
|
||||||
|
<Field label={t('wb.builder.ink')}><ColorField label={t('wb.builder.patternInk')} value={background.ink} swatches={[colors.text, colors.accent, '#ffffff']} onChange={v => v && onChange({ ...background, ink: v })}/></Field>
|
||||||
|
<Field label={t('wb.builder.strength')}><Slider label={t('wb.builder.patternStrength')} min={0} max={60} value={Math.round(background.opacity * 100)} format={pct} onChange={v => onChange({ ...background, opacity: v / 100 }, false)} onCommit={v => onChange({ ...background, opacity: v / 100 })}/></Field>
|
||||||
|
<Field label={t('wb.builder.scale')}><Slider label={t('wb.builder.patternScale')} min={2} max={400} value={background.size} format={px} onChange={size => onChange({ ...background, size }, false)} onCommit={size => onChange({ ...background, size })}/></Field>
|
||||||
|
</div>}
|
||||||
|
{background.kind === 'image' && <div className="wb-fields">
|
||||||
|
<Field label={t('wb.builder.dimming')}><Slider label={t('wb.appearance.dim')} min={35} max={95} value={Math.round(background.dim * 100)} format={pct} onChange={v => onChange({ ...background, dim: v / 100 }, false)} onCommit={v => onChange({ ...background, dim: v / 100 })}/></Field>
|
||||||
|
<Field label={t('wb.builder.fit')}><Segmented label={t('wb.builder.photoFit')} size="sm" value={background.fit} onChange={fit => onChange({ ...background, fit })} options={[{ value: 'cover', label: t('wb.builder.cover') }, { value: 'tile', label: t('wb.builder.tile') }]}/></Field>
|
||||||
|
<Field label={t('wb.builder.photo')}><Button size="sm" onClick={() => file.current?.click()}>{t('wb.builder.replace')}</Button></Field>
|
||||||
|
</div>}
|
||||||
|
</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The app's window in the draft: a tab strip and an address bar drawn with the chrome tokens. */
|
||||||
|
function ChromePreview({ theme }: { theme: ThemeSpec }) {
|
||||||
|
const themes = panelThemes();
|
||||||
|
const vars = useMemo(() => chromeVars(themes.store.adapter.chrome(theme)), [theme]);
|
||||||
|
const sample = themes.chromePreview ?? { tabs: ['Home', '@waybetter', panelSite().brand.name] as [string, string, string], chip: panelSite().brand.name, page: 'Home' };
|
||||||
|
return <div className="wb-chrome-preview" style={vars as CSSProperties} aria-hidden="true">
|
||||||
|
<div className="wb-cp-tabs">
|
||||||
|
<span className="wb-cp-tab is-on"><i/>{sample.tabs[0]}</span><span className="wb-cp-tab"><i/>{sample.tabs[1]}</span><span className="wb-cp-tab"><i/>{sample.tabs[2]}</span>
|
||||||
|
</div>
|
||||||
|
<div className="wb-cp-bar"><span className="wb-cp-dot"/><span className="wb-cp-omni"><b>{sample.chip}</b><em>/</em>{sample.page}</span><span className="wb-cp-brand"/></div>
|
||||||
|
</div>;
|
||||||
|
}
|
||||||
34
packages/shell/src/panel/backup.css
Normal file
34
packages/shell/src/panel/backup.css
Normal file
|
|
@ -0,0 +1,34 @@
|
||||||
|
/* Settings → Backup & sync and Developer (BackupPanel.tsx, DeveloperPanel.tsx). Panel tokens (panel.css). */
|
||||||
|
|
||||||
|
.btb-check { display: inline-flex; align-items: center; gap: 7px; color: var(--c-text); font-size: 12.5px; cursor: pointer; user-select: none; }
|
||||||
|
.btb-check input, .btb-row input { width: 15px; height: 15px; margin: 0; accent-color: var(--c-accent); cursor: pointer; }
|
||||||
|
.btb-loading { padding: 14px 16px; color: var(--c-muted); font-size: 12.5px; }
|
||||||
|
.btb-path { display: block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-family: var(--f-mono); font-size: 11.5px; }
|
||||||
|
|
||||||
|
/* Import preview: one row per section. */
|
||||||
|
.btb-row { display: flex; align-items: flex-start; gap: 12px; padding: 12px 16px; border-top: 1px solid var(--c-line-soft); cursor: pointer; }
|
||||||
|
.btb-row:first-child { border-top: 0; }
|
||||||
|
.btb-row input { margin-top: 2px; flex: none; }
|
||||||
|
.btb-row:hover { background: rgba(127, 127, 127, .05); }
|
||||||
|
.btb-row.is-same .btb-row-title { color: var(--c-muted); }
|
||||||
|
.btb-row-body { display: flex; flex-direction: column; gap: 4px; min-width: 0; }
|
||||||
|
.btb-row-title { display: flex; align-items: center; gap: 8px; font-weight: 600; font-size: 13px; }
|
||||||
|
.btb-row-line { color: var(--c-muted); font-size: 12px; line-height: 1.4; overflow-wrap: anywhere; }
|
||||||
|
.btb-actions { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; padding: 12px 16px; border-top: 1px solid var(--c-line-soft); }
|
||||||
|
.btb-actions-note { color: var(--c-muted); font-size: 12px; }
|
||||||
|
|
||||||
|
/* Sync */
|
||||||
|
.btb-pass { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
|
||||||
|
.btb-pass .bt-input { width: 200px; }
|
||||||
|
.btb-error { color: #ff8a80; font-size: 12px; }
|
||||||
|
.btb-snapshots { display: flex; flex-direction: column; gap: 6px; width: 100%; }
|
||||||
|
.btb-snapshot { display: flex; align-items: center; gap: 10px; padding: 8px 10px; border-radius: 9px; background: rgba(127, 127, 127, .06); }
|
||||||
|
.btb-snapshot.is-fresh { background: rgb(var(--c-accent-rgb) / .1); box-shadow: inset 0 0 0 1px rgb(var(--c-accent-rgb) / .3); }
|
||||||
|
.btb-snapshot-device { font-weight: 600; font-size: 12.5px; }
|
||||||
|
.btb-snapshot-when { flex: 1; color: var(--c-muted); font-size: 12px; font-variant-numeric: tabular-nums; }
|
||||||
|
|
||||||
|
/* Developer: load errors */
|
||||||
|
.btd-error { display: flex; flex-direction: column; gap: 4px; padding: 11px 16px; border-top: 1px solid var(--c-line-soft); border-inline-start: 3px solid var(--c-danger); }
|
||||||
|
.btd-error:first-child { border-top: 0; }
|
||||||
|
.btd-where { font: 600 12px/1.3 var(--f-mono); color: #ffb4ab; overflow-wrap: anywhere; }
|
||||||
|
.btd-message { font: 12.5px/1.45 var(--f-mono); color: var(--c-text); overflow-wrap: anywhere; }
|
||||||
232
packages/shell/src/panel/builder.css
Normal file
232
packages/shell/src/panel/builder.css
Normal file
|
|
@ -0,0 +1,232 @@
|
||||||
|
/* Theme Builder, font roles and the font browser. Panel tokens (--c-*, --f-*) from panel.css, so all
|
||||||
|
of it follows the active theme like the rest of the panel. */
|
||||||
|
|
||||||
|
/* ---------------------------------------------------------------------------------------------
|
||||||
|
* Builder layout: controls left, a sticky preview right (stacked under 980px). */
|
||||||
|
.wb-builder { --wb-gap: 14px; display: flex; flex-direction: column; gap: 16px; margin: -4px 0 0; }
|
||||||
|
.wb-builder.is-loading { min-height: 320px; }
|
||||||
|
.btp-page:has(.wb-builder) { max-width: 1320px; }
|
||||||
|
.wb-builder-bar {
|
||||||
|
position: sticky; top: -18px; z-index: 12; display: flex; flex-wrap: wrap; align-items: center; gap: 10px 14px;
|
||||||
|
margin: 0 -4px; padding: 10px 12px; border: 1px solid var(--c-line); border-radius: 14px;
|
||||||
|
background: color-mix(in srgb, var(--c-card) 88%, transparent); backdrop-filter: blur(14px) saturate(1.2);
|
||||||
|
box-shadow: 0 10px 30px -18px rgba(0, 0, 0, .6);
|
||||||
|
}
|
||||||
|
.wb-builder-name { flex: 1 1 200px; min-width: 0; height: 34px; padding: 0 10px; border: 1px solid transparent; border-radius: 9px; background: transparent; color: var(--c-text); font: 650 17px/1 var(--f-ui); letter-spacing: -.02em; }
|
||||||
|
.wb-builder-name:hover { border-color: var(--c-line); }
|
||||||
|
.wb-builder-name:focus { outline: none; border-color: var(--c-accent); background: var(--c-field); }
|
||||||
|
.wb-builder-tools { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }
|
||||||
|
.wb-divider { width: 1px; height: 20px; margin: 0 4px; background: var(--c-line); }
|
||||||
|
.wb-icon-button { display: inline-grid; place-items: center; width: 32px; height: 32px; padding: 0; border: 1px solid var(--c-line); border-radius: 9px; background: var(--c-field); color: var(--c-text); cursor: pointer; transition: background-color .15s, border-color .15s; }
|
||||||
|
.wb-icon-button:hover:not(:disabled) { border-color: var(--c-line-strong); background: var(--c-raise); }
|
||||||
|
.wb-icon-button:disabled { opacity: .38; cursor: default; }
|
||||||
|
.wb-live { display: inline-flex; align-items: center; gap: 8px; margin-inline-end: 4px; color: var(--c-muted); font-size: 12px; font-weight: 520; }
|
||||||
|
|
||||||
|
.wb-builder-grid { display: grid; grid-template-columns: 1fr; gap: 16px; align-items: start; }
|
||||||
|
.wb-builder-controls { display: flex; flex-direction: column; gap: var(--wb-gap); min-width: 0; }
|
||||||
|
.wb-builder-preview { display: flex; flex-direction: column; gap: 10px; min-width: 0; order: -1; }
|
||||||
|
@container panel (min-width: 980px) {
|
||||||
|
.wb-builder-grid { grid-template-columns: minmax(0, 1fr) minmax(360px, 44%); }
|
||||||
|
.wb-builder-preview { order: 0; position: sticky; top: 52px; }
|
||||||
|
}
|
||||||
|
|
||||||
|
.wb-card { padding: 16px 16px 14px; border: 1px solid var(--c-line-soft); border-radius: 14px; background: var(--c-card); }
|
||||||
|
.wb-card > header { display: flex; align-items: flex-start; justify-content: space-between; gap: 12px; margin-bottom: 14px; }
|
||||||
|
.wb-card h3 { margin: 0; font-size: 14px; font-weight: 640; letter-spacing: -.01em; }
|
||||||
|
.wb-card header p { margin: 3px 0 0; max-width: 62ch; color: var(--c-muted); font-size: 12px; line-height: 1.45; }
|
||||||
|
.wb-ok { display: inline-flex; align-items: center; gap: 6px; height: 26px; padding: 0 10px; border-radius: 999px; background: color-mix(in srgb, var(--c-ok) 14%, transparent); color: var(--c-ok); font-size: 12px; font-weight: 600; white-space: nowrap; }
|
||||||
|
|
||||||
|
.wb-fields { display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 12px 18px; margin-top: 14px; }
|
||||||
|
.wb-field { display: flex; flex-direction: column; gap: 7px; min-width: 0; }
|
||||||
|
.wb-field > span { color: var(--c-muted); font-size: 11.5px; font-weight: 560; letter-spacing: .01em; }
|
||||||
|
.wb-field .bt-slider { width: 100%; }
|
||||||
|
|
||||||
|
/* Base colors */
|
||||||
|
.wb-base { display: grid; grid-template-columns: repeat(auto-fill, minmax(180px, 1fr)); gap: 10px; }
|
||||||
|
.wb-base-item { display: flex; flex-direction: column; gap: 9px; padding: 10px; border: 1px solid var(--c-line-soft); border-radius: 12px; background: var(--c-ground); }
|
||||||
|
.wb-base-swatch { position: relative; display: flex; align-items: flex-end; justify-content: space-between; height: 62px; padding: 10px 11px; border-radius: 9px; box-shadow: inset 0 0 0 1px rgb(127 127 127 / .22); }
|
||||||
|
.wb-base-swatch span { font-size: 13px; font-weight: 650; letter-spacing: -.01em; }
|
||||||
|
.wb-base-swatch code { padding: 2px 6px; border: 0; border-radius: 6px; background: rgb(0 0 0 / .32); color: #fff; font: 500 11px/1.4 var(--f-mono); }
|
||||||
|
.wb-base-item .bt-color { flex-wrap: wrap; gap: 6px; }
|
||||||
|
.wb-base-item .bt-swatch { width: 22px; height: 22px; }
|
||||||
|
|
||||||
|
/* Derived palette */
|
||||||
|
.wb-palette { margin-top: 12px; }
|
||||||
|
.wb-palette-row { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 8px; }
|
||||||
|
.wb-chip { display: flex; align-items: center; gap: 9px; min-width: 0; padding: 7px 9px; border: 1px solid var(--c-line-soft); border-radius: 10px; background: var(--c-ground); color: var(--c-text); text-align: start; cursor: pointer; transition: border-color .15s, background-color .15s; }
|
||||||
|
.wb-chip:hover { border-color: var(--c-line-strong); }
|
||||||
|
.wb-chip.is-on { border-color: var(--c-accent); box-shadow: 0 0 0 1px var(--c-accent); }
|
||||||
|
.wb-chip-swatch { flex: none; width: 22px; height: 22px; border-radius: 6px; box-shadow: inset 0 0 0 1px rgb(127 127 127 / .3); }
|
||||||
|
.wb-chip-copy { display: flex; flex-direction: column; min-width: 0; }
|
||||||
|
.wb-chip-copy b { font-size: 12px; font-weight: 600; }
|
||||||
|
.wb-chip-copy small { overflow: hidden; color: var(--c-muted); font: 10.5px/1.4 var(--f-mono); white-space: nowrap; text-overflow: ellipsis; }
|
||||||
|
.wb-palette-edit { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; margin-top: 10px; padding: 10px; border-radius: 10px; background: var(--c-field); }
|
||||||
|
.wb-palette-edit > span { font-size: 12px; font-weight: 600; }
|
||||||
|
|
||||||
|
/* Contrast */
|
||||||
|
.wb-contrast { display: flex; flex-direction: column; gap: 4px; margin: 0; padding: 0; list-style: none; }
|
||||||
|
.wb-contrast li { display: grid; grid-template-columns: 40px 1fr auto auto 76px; align-items: center; gap: 12px; padding: 6px 8px; border-radius: 9px; }
|
||||||
|
.wb-contrast li:hover { background: var(--c-field); }
|
||||||
|
.wb-contrast li.is-fail { background: color-mix(in srgb, var(--c-danger) 7%, transparent); }
|
||||||
|
.wb-contrast-sample { display: grid; place-items: center; width: 40px; height: 28px; border-radius: 7px; box-shadow: inset 0 0 0 1px rgb(127 127 127 / .25); font-size: 14px; font-weight: 700; }
|
||||||
|
.wb-contrast-label { font-size: 12.5px; }
|
||||||
|
.wb-contrast-ratio { font: 12px/1 var(--f-mono); color: var(--c-muted); }
|
||||||
|
.wb-contrast-ratio b { color: var(--c-text); font-weight: 600; }
|
||||||
|
.wb-contrast-need { color: var(--c-faint); font-size: 11.5px; }
|
||||||
|
.wb-contrast-badge { justify-self: end; padding: 3px 7px; border-radius: 6px; font: 600 10.5px/1.2 var(--f-mono); text-align: center; }
|
||||||
|
.wb-contrast-badge.is-pass { background: color-mix(in srgb, var(--c-ok) 14%, transparent); color: var(--c-ok); }
|
||||||
|
.wb-contrast-badge.is-fail { background: color-mix(in srgb, var(--c-danger) 16%, transparent); color: var(--c-danger); }
|
||||||
|
@container panel (max-width: 560px) {
|
||||||
|
.wb-contrast li { grid-template-columns: 40px 1fr auto; }
|
||||||
|
.wb-contrast-need, .wb-contrast-badge { display: none; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Background */
|
||||||
|
.wb-bg .bt-seg { margin-bottom: 2px; }
|
||||||
|
|
||||||
|
/* Preview column */
|
||||||
|
.wb-preview-frame { overflow: hidden; border: 1px solid var(--c-line); border-radius: 14px; background: var(--c-ground); box-shadow: 0 24px 60px -30px rgba(0, 0, 0, .7); }
|
||||||
|
.wb-preview-frame .tp { border-radius: 0; }
|
||||||
|
.wb-preview-note { display: flex; align-items: center; gap: 8px; margin: 0 2px; color: var(--c-muted); font-size: 12px; line-height: 1.4; }
|
||||||
|
.wb-live-dot { flex: none; width: 8px; height: 8px; border-radius: 50%; background: var(--c-ok); box-shadow: 0 0 0 3px color-mix(in srgb, var(--c-ok) 22%, transparent); animation: wb-pulse 2.4s ease-in-out infinite; }
|
||||||
|
@keyframes wb-pulse { 50% { box-shadow: 0 0 0 6px color-mix(in srgb, var(--c-ok) 0%, transparent); } }
|
||||||
|
@media (prefers-reduced-motion: reduce) { .wb-live-dot { animation: none; } }
|
||||||
|
.wb-meta { display: flex; flex-direction: column; gap: 10px; padding: 12px; border: 1px solid var(--c-line-soft); border-radius: 12px; background: var(--c-card); }
|
||||||
|
.wb-meta label { display: flex; flex-direction: column; gap: 5px; }
|
||||||
|
.wb-meta span { color: var(--c-muted); font-size: 11.5px; font-weight: 560; }
|
||||||
|
.wb-meta input, .wb-meta textarea { padding: 7px 9px; border: 1px solid var(--c-line); border-radius: 8px; background: var(--c-field); color: var(--c-text); font: 13px/1.4 var(--f-ui); resize: vertical; }
|
||||||
|
.wb-meta input:focus, .wb-meta textarea:focus { outline: none; border-color: var(--c-accent); }
|
||||||
|
|
||||||
|
/* The chrome in the draft (tokens straight from chromeVars, Night Ink fallbacks). */
|
||||||
|
.wb-chrome-preview { padding: 7px 8px 0; background: var(--wb-c-ground, #07080c); font-family: var(--wb-f-chrome, 'Geist Variable', system-ui, sans-serif); }
|
||||||
|
.wb-cp-tabs { display: flex; gap: 4px; }
|
||||||
|
.wb-cp-tab { display: inline-flex; align-items: center; gap: 7px; height: 26px; padding: 0 12px; border-radius: 8px 8px 0 0; color: var(--wb-c-muted, #8a90a6); font-size: 11.5px; font-weight: 520; }
|
||||||
|
.wb-cp-tab i { width: 10px; height: 10px; border-radius: 3px; background: var(--wb-c-line-strong, #2a3044); }
|
||||||
|
.wb-cp-tab.is-on { background: var(--wb-c-chrome, #0d1017); color: var(--wb-c-text, #eef0f7); }
|
||||||
|
.wb-cp-tab.is-on i { background: var(--wb-c-accent, #1d9bf0); }
|
||||||
|
.wb-cp-bar { display: flex; align-items: center; gap: 8px; margin: 0 -8px; padding: 7px 10px; background: var(--wb-c-chrome, #0d1017); border-bottom: 1px solid var(--wb-c-line-soft, #161a26); }
|
||||||
|
.wb-cp-dot { width: 14px; height: 14px; border-radius: 50%; background: var(--wb-c-raised, #141823); }
|
||||||
|
.wb-cp-omni { flex: 1; display: flex; align-items: center; gap: 7px; height: 24px; padding: 0 9px; border-radius: 7px; background: var(--wb-c-field, #11141c); color: var(--wb-c-text, #eef0f7); font-size: 11.5px; }
|
||||||
|
.wb-cp-omni b { padding: 2px 7px; border-radius: 5px; background: rgb(var(--wb-c-accent-rgb, 29 155 240) / .16); color: var(--wb-c-accent-ink, #cfe6ff); font-weight: 600; }
|
||||||
|
.wb-cp-omni em { color: var(--wb-c-faint, #5d6379); font-style: normal; }
|
||||||
|
.wb-cp-brand { width: 26px; height: 16px; border-radius: 5px; background: linear-gradient(90deg, #4f6bff, #22d3ee 55%, #a855f7); opacity: .85; }
|
||||||
|
|
||||||
|
/* ---------------------------------------------------------------------------------------------
|
||||||
|
* Font roles */
|
||||||
|
.wb-roles { display: flex; flex-direction: column; border: 1px solid var(--c-line-soft); border-radius: 12px; overflow: hidden; }
|
||||||
|
.wb-role + .wb-role { border-top: 1px solid var(--c-line-soft); }
|
||||||
|
.wb-role-main { display: grid; grid-template-columns: minmax(130px, .8fr) minmax(0, 1.4fr) auto; align-items: center; gap: 12px; padding-block: 9px; padding-inline: 14px 10px; }
|
||||||
|
.wb-role-copy { display: flex; flex-direction: column; min-width: 0; }
|
||||||
|
.wb-role-copy strong { font-size: 13px; font-weight: 600; }
|
||||||
|
.wb-role-copy small { color: var(--c-muted); font-size: 11.5px; line-height: 1.35; }
|
||||||
|
.wb-role-font { display: flex; flex-direction: column; align-items: flex-start; gap: 2px; min-width: 0; padding: 7px 11px; border: 1px solid var(--c-line); border-radius: 10px; background: var(--c-field); color: var(--c-text); text-align: start; cursor: pointer; transition: border-color .15s, background-color .15s; }
|
||||||
|
.wb-role-font:hover { border-color: var(--c-line-strong); background: var(--c-raise); }
|
||||||
|
.wb-role-font.is-inherited { border-style: dashed; background: transparent; }
|
||||||
|
.wb-role-sample { max-width: 100%; overflow: hidden; font-size: 17px; line-height: 1.25; white-space: nowrap; text-overflow: ellipsis; }
|
||||||
|
.wb-role-name { display: inline-flex; align-items: center; gap: 6px; color: var(--c-muted); font-size: 11px; }
|
||||||
|
.wb-role-name em { padding: 1px 5px; border-radius: 4px; background: var(--c-accent-soft); color: var(--c-accent); font: 600 9.5px/1.3 var(--f-mono); font-style: normal; letter-spacing: .02em; text-transform: uppercase; }
|
||||||
|
.wb-role-actions { display: flex; align-items: center; justify-content: flex-end; gap: 4px; min-width: 96px; }
|
||||||
|
.wb-role-tune { display: grid; place-items: center; width: 30px; height: 30px; padding: 0; border: 1px solid transparent; border-radius: 8px; background: transparent; color: var(--c-muted); cursor: pointer; }
|
||||||
|
.wb-role-tune:hover, .wb-role-tune[aria-expanded=true] { border-color: var(--c-line); background: var(--c-field); color: var(--c-text); }
|
||||||
|
.wb-role-tune.is-tuned { color: var(--c-accent); }
|
||||||
|
.wb-role-tuning { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 12px 18px; padding: 4px 14px 14px; }
|
||||||
|
.wb-role-tuning label { display: flex; flex-direction: column; gap: 6px; }
|
||||||
|
.wb-role-tuning label.is-inline { flex-direction: row; align-items: center; justify-content: space-between; }
|
||||||
|
.wb-role-tuning label > span { color: var(--c-muted); font-size: 11.5px; font-weight: 560; }
|
||||||
|
.wb-roles.is-compact .wb-role-main { grid-template-columns: minmax(110px, .6fr) minmax(0, 1.4fr) auto; }
|
||||||
|
@container panel (max-width: 560px) {
|
||||||
|
.wb-role-main { grid-template-columns: 1fr auto; }
|
||||||
|
.wb-role-font { grid-column: 1 / -1; grid-row: 2; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------------------------------------------------------------------------------------------
|
||||||
|
* Sheets (font browser): cover the panel, not the window (X panes are native webviews). */
|
||||||
|
.wb-sheet-backdrop { position: absolute; inset: 0; z-index: 60; display: grid; place-items: center; padding: 18px; background: rgb(0 0 0 / .5); backdrop-filter: blur(4px); animation: bt-pop .16s var(--ease); }
|
||||||
|
.wb-sheet { display: flex; flex-direction: column; width: min(1040px, 100%); height: min(720px, 100%); overflow: hidden; border: 1px solid var(--c-line-strong); border-radius: 16px; background: var(--c-card); box-shadow: 0 40px 100px -30px rgba(0, 0, 0, .8), 0 0 0 1px rgb(0 0 0 / .3); }
|
||||||
|
.wb-sheet-head { display: flex; align-items: center; gap: 14px; padding-block: 16px 12px; padding-inline: 20px 16px; border-bottom: 1px solid var(--c-line-soft); }
|
||||||
|
.wb-sheet-head > div:first-child { flex: 1; min-width: 0; }
|
||||||
|
.wb-sheet-head .bt-seg { flex: none; }
|
||||||
|
.wb-sheet-head h2 { margin: 0; font-size: 17px; font-weight: 650; letter-spacing: -.02em; }
|
||||||
|
.wb-sheet-head h2 span { color: var(--c-muted); font-weight: 450; }
|
||||||
|
.wb-sheet-head p { margin: 3px 0 0; color: var(--c-muted); font-size: 12px; }
|
||||||
|
.wb-sheet-close { display: grid; place-items: center; width: 32px; height: 32px; padding: 0; border: 1px solid var(--c-line); border-radius: 9px; background: var(--c-field); color: var(--c-muted); cursor: pointer; }
|
||||||
|
.wb-sheet-close:hover { color: var(--c-text); border-color: var(--c-line-strong); }
|
||||||
|
.wb-sheet-foot { padding: 10px 20px 12px; border-top: 1px solid var(--c-line-soft); color: var(--c-faint); font-size: 11px; line-height: 1.5; }
|
||||||
|
|
||||||
|
.wb-fb-tools { display: flex; flex-wrap: wrap; align-items: center; gap: 10px 14px; padding: 12px 20px; }
|
||||||
|
.wb-fb-search { flex: 1 1 260px; }
|
||||||
|
.wb-fb-cats { display: flex; flex-wrap: wrap; gap: 4px; }
|
||||||
|
.wb-fb-cats button { height: 28px; padding: 0 11px; border: 1px solid var(--c-line); border-radius: 999px; background: transparent; color: var(--c-muted); font-size: 12px; font-weight: 540; cursor: pointer; transition: color .15s, background-color .15s, border-color .15s; }
|
||||||
|
.wb-fb-cats button:hover { color: var(--c-text); border-color: var(--c-line-strong); }
|
||||||
|
.wb-fb-cats button.is-on { background: var(--c-text); border-color: var(--c-text); color: var(--c-ground); }
|
||||||
|
.wb-fb-cats .wb-fb-installed { margin-inline-start: 6px; }
|
||||||
|
.wb-fb-cats .wb-fb-installed.is-on { background: var(--c-accent-soft); border-color: var(--c-accent); color: var(--c-accent); }
|
||||||
|
|
||||||
|
.wb-fb-body { flex: 1; display: grid; grid-template-columns: minmax(0, 1fr) minmax(300px, 1.05fr); min-height: 0; border-top: 1px solid var(--c-line-soft); }
|
||||||
|
@container panel (max-width: 760px) { .wb-fb-body { grid-template-columns: 1fr; grid-template-rows: 1fr auto; } .wb-fb-detail { max-height: 50%; border-inline-start: 0 !important; border-top: 1px solid var(--c-line-soft); } }
|
||||||
|
.wb-fb-list { margin: 0; padding: 6px; overflow-y: auto; list-style: none; scrollbar-width: thin; scrollbar-color: var(--c-line) transparent; outline: none; }
|
||||||
|
.wb-fb-list:focus-visible { box-shadow: inset 0 0 0 2px var(--c-accent); }
|
||||||
|
.wb-fb-list li[role=option] { display: grid; grid-template-columns: 1fr auto; grid-template-areas: 'name tags' 'meta tags'; align-items: center; column-gap: 10px; padding: 8px 12px; border-radius: 10px; cursor: pointer; }
|
||||||
|
.wb-fb-list li.is-active { background: var(--c-field); }
|
||||||
|
.wb-fb-list li.is-on { background: var(--c-accent-soft); box-shadow: inset 0 0 0 1px rgb(var(--c-accent-rgb) / .45); }
|
||||||
|
.wb-fb-name { grid-area: name; overflow: hidden; font-size: 21px; line-height: 1.3; white-space: nowrap; text-overflow: ellipsis; transition: opacity .2s; }
|
||||||
|
.wb-fb-name.is-loading { opacity: .45; }
|
||||||
|
.wb-fb-meta { grid-area: meta; color: var(--c-muted); font-size: 11px; }
|
||||||
|
.wb-fb-tag { grid-area: tags; justify-self: end; padding: 2px 7px; border-radius: 6px; background: var(--c-field); color: var(--c-muted); font: 600 10px/1.4 var(--f-mono); letter-spacing: .02em; }
|
||||||
|
.wb-fb-tag.is-accent { background: var(--c-accent-soft); color: var(--c-accent); }
|
||||||
|
.wb-fb-tag + .wb-fb-tag { grid-row: 2; }
|
||||||
|
.wb-fb-empty { padding: 30px 14px; color: var(--c-muted); text-align: center; }
|
||||||
|
.wb-fb-more { display: flex; justify-content: center; padding: 8px; }
|
||||||
|
|
||||||
|
.wb-fb-detail { display: flex; flex-direction: column; gap: 16px; padding: 18px 20px; overflow-y: auto; border-inline-start: 1px solid var(--c-line-soft); background: var(--c-ground); scrollbar-width: thin; }
|
||||||
|
.wb-fb-detail.is-empty { justify-content: center; color: var(--c-muted); text-align: center; }
|
||||||
|
.wb-fb-hero { display: flex; flex-direction: column; gap: 4px; }
|
||||||
|
.wb-fb-hero-name { font-size: 40px; line-height: 1.1; letter-spacing: -.01em; overflow-wrap: anywhere; }
|
||||||
|
.wb-fb-hero-meta { color: var(--c-muted); font-size: 12px; }
|
||||||
|
.wb-fb-sample { display: flex; flex-direction: column; gap: 8px; padding: 14px; border: 1px solid var(--c-line-soft); border-radius: 12px; background: var(--c-card); }
|
||||||
|
.wb-fb-sample-text { min-height: 2.6em; font-size: 24px; line-height: 1.3; overflow-wrap: anywhere; }
|
||||||
|
.wb-fb-sample textarea { width: 100%; padding: 7px 9px; border: 1px solid var(--c-line); border-radius: 8px; background: var(--c-field); color: var(--c-text); font: 12.5px/1.45 var(--f-ui); resize: none; }
|
||||||
|
.wb-fb-sample textarea:focus { outline: none; border-color: var(--c-accent); }
|
||||||
|
.wb-fb-samples { display: flex; flex-wrap: wrap; gap: 4px; }
|
||||||
|
.wb-fb-samples button { height: 24px; padding: 0 9px; border: 1px solid var(--c-line); border-radius: 999px; background: transparent; color: var(--c-muted); font-size: 11px; cursor: pointer; }
|
||||||
|
.wb-fb-samples button.is-on, .wb-fb-samples button:hover { color: var(--c-text); border-color: var(--c-line-strong); }
|
||||||
|
.wb-fb-field { display: flex; flex-direction: column; gap: 8px; }
|
||||||
|
.wb-fb-field > span { color: var(--c-muted); font-size: 11.5px; font-weight: 600; letter-spacing: .02em; text-transform: uppercase; }
|
||||||
|
.wb-fb-field > small { color: var(--c-faint); font-size: 11.5px; line-height: 1.45; }
|
||||||
|
.wb-fb-range { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
|
||||||
|
.wb-fb-weights { display: flex; flex-wrap: wrap; gap: 4px; }
|
||||||
|
.wb-fb-weights button { min-width: 44px; height: 28px; padding: 0 9px; border: 1px solid var(--c-line); border-radius: 8px; background: var(--c-field); color: var(--c-muted); font: 500 11.5px/1 var(--f-mono); cursor: pointer; }
|
||||||
|
.wb-fb-weights button.is-on { border-color: var(--c-accent); background: var(--c-accent-soft); color: var(--c-text); }
|
||||||
|
.wb-fb-actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: auto; padding-top: 4px; }
|
||||||
|
.wb-fb-error { margin: 0; padding: 8px 10px; border-radius: 8px; background: color-mix(in srgb, var(--c-danger) 12%, transparent); color: var(--c-danger); font-size: 12px; }
|
||||||
|
|
||||||
|
.wb-fb-system { flex: 1; overflow-y: auto; padding: 16px 20px; }
|
||||||
|
.wb-fb-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); gap: 10px; margin: 0 0 18px; padding: 0; list-style: none; }
|
||||||
|
.wb-fb-grid button { display: flex; flex-direction: column; gap: 4px; width: 100%; padding: 14px; border: 1px solid var(--c-line-soft); border-radius: 12px; background: var(--c-ground); color: var(--c-text); text-align: start; cursor: pointer; }
|
||||||
|
.wb-fb-grid button:hover { border-color: var(--c-line-strong); }
|
||||||
|
.wb-fb-grid button.is-on { border-color: var(--c-accent); box-shadow: 0 0 0 1px var(--c-accent); }
|
||||||
|
.wb-fb-grid span { font-size: 18px; }
|
||||||
|
.wb-fb-grid small { color: var(--c-muted); font-size: 12px; }
|
||||||
|
.wb-fb-custom { display: flex; align-items: flex-end; gap: 10px; padding: 14px; border: 1px dashed var(--c-line-strong); border-radius: 12px; }
|
||||||
|
.wb-fb-custom label { flex: 1; display: flex; flex-direction: column; gap: 6px; }
|
||||||
|
.wb-fb-custom label span { color: var(--c-muted); font-size: 12px; }
|
||||||
|
.wb-fb-custom input { height: 34px; padding: 0 10px; border: 1px solid var(--c-line); border-radius: 9px; background: var(--c-field); color: var(--c-text); font-size: 15px; }
|
||||||
|
.wb-fb-custom input:focus { outline: none; border-color: var(--c-accent); }
|
||||||
|
|
||||||
|
/* ---------------------------------------------------------------------------------------------
|
||||||
|
* Appearance: account and pane themes, downloaded fonts */
|
||||||
|
.wb-scope-list { display: flex; flex-direction: column; gap: 2px; width: 100%; }
|
||||||
|
.wb-scope { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 12px; padding: 6px 2px; }
|
||||||
|
.wb-scope-who { display: flex; align-items: center; gap: 10px; min-width: 0; }
|
||||||
|
.wb-scope-who > span:last-child { display: flex; flex-direction: column; min-width: 0; }
|
||||||
|
.wb-scope-who b { overflow: hidden; font-size: 13px; font-weight: 560; white-space: nowrap; text-overflow: ellipsis; }
|
||||||
|
.wb-scope-who small { overflow: hidden; color: var(--c-muted); font-size: 11.5px; white-space: nowrap; text-overflow: ellipsis; }
|
||||||
|
.wb-scope-avatar { display: grid; place-items: center; flex: none; width: 26px; height: 26px; border-radius: 50%; overflow: hidden; color: #fff; font-size: 12px; font-weight: 650; }
|
||||||
|
.wb-scope-avatar img { width: 100%; height: 100%; object-fit: cover; }
|
||||||
|
.wb-scope .wb-dots { margin-inline-end: 2px; }
|
||||||
|
.wb-fontlist { display: flex; flex-direction: column; width: 100%; }
|
||||||
|
.wb-fontlist li { display: grid; grid-template-columns: minmax(0, 1fr) auto auto; align-items: center; gap: 12px; padding: 7px 2px; }
|
||||||
|
.wb-fontlist li + li { border-top: 1px solid var(--c-line-soft); }
|
||||||
|
.wb-fontlist b { font-size: 17px; font-weight: 450; }
|
||||||
|
.wb-fontlist small { color: var(--c-muted); font: 11px/1.4 var(--f-mono); }
|
||||||
|
.wb-fontlist ul { margin: 0; padding: 0; list-style: none; }
|
||||||
116
packages/shell/src/panel/builderModel.ts
Normal file
116
packages/shell/src/panel/builderModel.ts
Normal file
|
|
@ -0,0 +1,116 @@
|
||||||
|
// The Theme Builder's model: a draft theme document with undo/redo, a palette derived from three
|
||||||
|
// base colors, the contrast report the builder shows (and its auto-fix), and export/share JSON.
|
||||||
|
// Pure, so the tests exercise exactly what the builder does.
|
||||||
|
import { THEME_SCHEMA_URL, contrastRatio, relativeLuminance } from '../../../runtime/src/themeApi.ts';
|
||||||
|
import { ensureContrast, sanitizeSpec, slug, type Palette, type ThemeColors, type ThemeSpec } from '../../../runtime/src/themeSpec.ts';
|
||||||
|
import { deriveColors } from '../../../runtime/src/themeTokens.ts';
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// History
|
||||||
|
|
||||||
|
export type History = { past: ThemeSpec[]; present: ThemeSpec; future: ThemeSpec[] };
|
||||||
|
export const MAX_HISTORY = 100;
|
||||||
|
|
||||||
|
export const startHistory = (theme: ThemeSpec): History => ({ past: [], present: theme, future: [] });
|
||||||
|
|
||||||
|
/** A change. `commit: false` updates the present in place (a slider being dragged); the drag's
|
||||||
|
* final commit records one undo step from where the drag started (`from`). */
|
||||||
|
export function record(history: History, next: ThemeSpec, options: { commit?: boolean; from?: ThemeSpec } = {}): History {
|
||||||
|
if (options.commit === false) return { ...history, present: next };
|
||||||
|
const base = options.from ?? history.present;
|
||||||
|
if (JSON.stringify(base) === JSON.stringify(next)) return { ...history, present: next };
|
||||||
|
return { past: [...history.past, base].slice(-MAX_HISTORY), present: next, future: [] };
|
||||||
|
}
|
||||||
|
export function undo(history: History): History {
|
||||||
|
const previous = history.past[history.past.length - 1];
|
||||||
|
if (!previous) return history;
|
||||||
|
return { past: history.past.slice(0, -1), present: previous, future: [history.present, ...history.future] };
|
||||||
|
}
|
||||||
|
export function redo(history: History): History {
|
||||||
|
const next = history.future[0];
|
||||||
|
if (!next) return history;
|
||||||
|
return { past: [...history.past, history.present], present: next, future: history.future.slice(1) };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Drafts and colors
|
||||||
|
|
||||||
|
/** Where a draft starts when its theme keeps the site's own colors, and which theme that is. */
|
||||||
|
export type DraftSite = { colors: Base; siteTheme: string };
|
||||||
|
|
||||||
|
/** A draft to edit from any theme: the site's own look (no colors) starts from `site.colors`. */
|
||||||
|
export function draftFrom(theme: ThemeSpec, site: DraftSite, name = `${theme.name} remix`): ThemeSpec {
|
||||||
|
const colors = theme.colors ?? deriveColors({ ...site.colors }) as ThemeColors;
|
||||||
|
return sanitizeSpec({ ...JSON.parse(JSON.stringify(theme)), id: slug(name), name, author: 'You', description: theme.id === site.siteTheme ? '' : `Based on ${theme.name}.`, colors, mode: theme.mode === 'auto' ? 'dark' : theme.mode });
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Base = { bg: string; text: string; accent: string };
|
||||||
|
export const DERIVED_ROLES = ['surface', 'elevated', 'border', 'muted', 'inverse', 'onInverse', 'page'] as const;
|
||||||
|
export type DerivedRole = typeof DERIVED_ROLES[number];
|
||||||
|
|
||||||
|
/** The full palette from three base colors; `pinned` roles keep the value the owner set by hand. */
|
||||||
|
export function paletteFrom(base: Base, pinned: Partial<Record<DerivedRole, string>> = {}): ThemeColors {
|
||||||
|
const derived = deriveColors(base) as ThemeColors;
|
||||||
|
return { ...derived, inverse: base.text, onInverse: base.bg, page: base.bg, ...pinned };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Which derived roles differ from what the three base colors would give (they are "pinned"). */
|
||||||
|
export function pinnedRoles(colors: ThemeColors): Partial<Record<DerivedRole, string>> {
|
||||||
|
const auto = paletteFrom({ bg: colors.bg, text: colors.text, accent: colors.accent });
|
||||||
|
const out: Partial<Record<DerivedRole, string>> = {};
|
||||||
|
for (const role of DERIVED_ROLES) { const value = colors[role]; if (value && value !== auto[role]) out[role] = value; }
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Light or dark, from the palette itself. */
|
||||||
|
export const modeOf = (colors: Pick<Palette, 'bg' | 'text'>): 'light' | 'dark' => relativeLuminance(colors.bg) < relativeLuminance(colors.text) ? 'dark' : 'light';
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Contrast
|
||||||
|
|
||||||
|
export type ContrastCheck = { id: string; label: string; fg: string; bg: string; ratio: number; need: number; pass: boolean };
|
||||||
|
|
||||||
|
/** The pairs a site's page draws, with the level wayBetter enforces for each (7:1 text, 4.5:1 secondary text, links and labels, 3:1 the button on the page). */
|
||||||
|
export function contrastReport(colors: ThemeColors): ContrastCheck[] {
|
||||||
|
const page = colors.page ?? colors.bg;
|
||||||
|
const inverse = colors.inverse ?? colors.text;
|
||||||
|
const onInverse = colors.onInverse ?? colors.bg;
|
||||||
|
const pairs: Array<[string, string, string, string, number]> = [
|
||||||
|
['text-bg', 'Text on background', colors.text, colors.bg, 7],
|
||||||
|
['text-surface', 'Text on cards and menus', colors.text, colors.surface, 7],
|
||||||
|
['text-page', 'Text on the page canvas', colors.text, page, 7],
|
||||||
|
['muted-bg', 'Secondary text', colors.muted, colors.bg, 4.5],
|
||||||
|
['muted-surface', 'Secondary text on cards', colors.muted, colors.surface, 4.5],
|
||||||
|
['accent-bg', 'Links and accent', colors.accent, colors.bg, 4.5],
|
||||||
|
['accent-elevated', 'Links on hover', colors.accent, colors.elevated, 4.5],
|
||||||
|
['button-label', 'Post button label', onInverse, inverse, 4.5],
|
||||||
|
['button-page', 'Post button on the page', inverse, colors.bg, 3],
|
||||||
|
];
|
||||||
|
return pairs.map(([id, label, fg, bg, need]) => {
|
||||||
|
const ratio = contrastRatio(fg, bg);
|
||||||
|
return { id, label, fg, bg, ratio: Math.round(ratio * 100) / 100, need, pass: ratio >= need - 0.005 };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** WCAG level of a ratio for normal text. */
|
||||||
|
export const wcagLevel = (ratio: number) => ratio >= 7 ? 'AAA' : ratio >= 4.5 ? 'AA' : ratio >= 3 ? 'AA large' : 'Fail';
|
||||||
|
|
||||||
|
/** What the runtime would draw anyway: the palette moved just enough to pass every check. */
|
||||||
|
export const autoFix = (colors: ThemeColors): ThemeColors => ensureContrast(colors);
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Saving and sharing
|
||||||
|
|
||||||
|
/** A unique id for a new theme named `name` among `taken` ids (pass the built-in ones too). */
|
||||||
|
export function uniqueId(name: string, taken: Iterable<string>): string {
|
||||||
|
const used = new Set(taken);
|
||||||
|
const base = slug(name);
|
||||||
|
let id = base;
|
||||||
|
for (let n = 2; used.has(id); n++) id = `${base.slice(0, 36)}-${n}`;
|
||||||
|
return id;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The theme file: sanitized, `$schema` first, pretty-printed. */
|
||||||
|
export function themeJson(theme: ThemeSpec): string {
|
||||||
|
return JSON.stringify({ $schema: THEME_SCHEMA_URL, ...sanitizeSpec(theme) }, null, 2);
|
||||||
|
}
|
||||||
42
packages/shell/src/panel/compare.ts
Normal file
42
packages/shell/src/panel/compare.ts
Normal file
|
|
@ -0,0 +1,42 @@
|
||||||
|
export type ComparedLine = { text: string; changed: boolean };
|
||||||
|
|
||||||
|
/** A bounded line comparison: large documents use prefix/suffix matching. */
|
||||||
|
export function compareLines(previous: string, current: string): { previous: ComparedLine[]; current: ComparedLine[]; simplified: boolean } {
|
||||||
|
const oldLines = previous.split('\n');
|
||||||
|
const newLines = current.split('\n');
|
||||||
|
const oldSame = new Set<number>();
|
||||||
|
const newSame = new Set<number>();
|
||||||
|
const simplified = oldLines.length * newLines.length > 160_000;
|
||||||
|
if (simplified) {
|
||||||
|
let start = 0;
|
||||||
|
while (start < oldLines.length && start < newLines.length && oldLines[start] === newLines[start]) {
|
||||||
|
oldSame.add(start); newSame.add(start); start++;
|
||||||
|
}
|
||||||
|
let oldEnd = oldLines.length - 1;
|
||||||
|
let newEnd = newLines.length - 1;
|
||||||
|
while (oldEnd >= start && newEnd >= start && oldLines[oldEnd] === newLines[newEnd]) {
|
||||||
|
oldSame.add(oldEnd--); newSame.add(newEnd--);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const columns = newLines.length + 1;
|
||||||
|
const lengths = new Uint32Array((oldLines.length + 1) * columns);
|
||||||
|
for (let i = oldLines.length - 1; i >= 0; i--) {
|
||||||
|
for (let j = newLines.length - 1; j >= 0; j--) {
|
||||||
|
lengths[i * columns + j] = oldLines[i] === newLines[j]
|
||||||
|
? lengths[(i + 1) * columns + j + 1] + 1
|
||||||
|
: Math.max(lengths[(i + 1) * columns + j], lengths[i * columns + j + 1]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let i = 0; let j = 0;
|
||||||
|
while (i < oldLines.length && j < newLines.length) {
|
||||||
|
if (oldLines[i] === newLines[j]) { oldSame.add(i++); newSame.add(j++); }
|
||||||
|
else if (lengths[(i + 1) * columns + j] >= lengths[i * columns + j + 1]) i++;
|
||||||
|
else j++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
previous: oldLines.map((text, index) => ({ text, changed: !oldSame.has(index) })),
|
||||||
|
current: newLines.map((text, index) => ({ text, changed: !newSame.has(index) })),
|
||||||
|
simplified,
|
||||||
|
};
|
||||||
|
}
|
||||||
269
packages/shell/src/panel/controls.tsx
Normal file
269
packages/shell/src/panel/controls.tsx
Normal file
|
|
@ -0,0 +1,269 @@
|
||||||
|
// Shared panel controls. One visual language for every setting: a row is label + hint on the left
|
||||||
|
// and one aligned control on the right (stacked under the label in a narrow split pane). Controls
|
||||||
|
// are small, keyboard-first and announce state with the matching ARIA role.
|
||||||
|
import {
|
||||||
|
createContext, useContext, useEffect, useId, useLayoutEffect, useRef, useState,
|
||||||
|
type CSSProperties, type KeyboardEvent, type ReactNode,
|
||||||
|
} from 'react';
|
||||||
|
import { useT } from '../frame/hooks.ts';
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Search: rows hide themselves when they do not match the panel's settings search.
|
||||||
|
|
||||||
|
const SearchContext = createContext('');
|
||||||
|
export const SearchProvider = SearchContext.Provider;
|
||||||
|
export const useSettingsQuery = () => useContext(SearchContext);
|
||||||
|
const matches = (query: string, ...texts: Array<string | undefined>) => {
|
||||||
|
const words = query.toLowerCase().split(/\s+/).filter(Boolean);
|
||||||
|
const hay = texts.filter(Boolean).join(' ').toLowerCase();
|
||||||
|
return words.every(word => hay.includes(word));
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Wraps text so the part matching the settings search is highlighted. */
|
||||||
|
function Mark({ text }: { text: string }) {
|
||||||
|
const query = useSettingsQuery().trim();
|
||||||
|
if (!query) return <>{text}</>;
|
||||||
|
const word = query.split(/\s+/).find(w => text.toLowerCase().includes(w.toLowerCase()));
|
||||||
|
if (!word) return <>{text}</>;
|
||||||
|
const at = text.toLowerCase().indexOf(word.toLowerCase());
|
||||||
|
return <>{text.slice(0, at)}<mark>{text.slice(at, at + word.length)}</mark>{text.slice(at + word.length)}</>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Layout
|
||||||
|
|
||||||
|
export function Section({ title, hint, action, children, id }: { title: string; hint?: ReactNode; action?: ReactNode; children: ReactNode; id?: string }) {
|
||||||
|
return <section className="bt-section" aria-labelledby={id ? `${id}-h` : undefined} data-section={title}>
|
||||||
|
<header className="bt-section-head">
|
||||||
|
<div><h2 id={id ? `${id}-h` : undefined}>{title}</h2>{hint && <p>{hint}</p>}</div>
|
||||||
|
{action && <div className="bt-section-action">{action}</div>}
|
||||||
|
</header>
|
||||||
|
<div className="bt-card">{children}</div>
|
||||||
|
</section>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A setting: label and hint on the left, one control on the right. `wide` puts the control on its own line. */
|
||||||
|
export function Row({ label, hint, children, keywords, wide, badge }: { label: string; hint?: ReactNode; children?: ReactNode; keywords?: string; wide?: boolean; badge?: ReactNode }) {
|
||||||
|
const query = useSettingsQuery();
|
||||||
|
const id = useId();
|
||||||
|
if (query && !matches(query, label, typeof hint === 'string' ? hint : '', keywords)) return null;
|
||||||
|
return <div className={`bt-row ${wide ? 'is-wide' : ''}`} role="group" aria-labelledby={id}>
|
||||||
|
<div className="bt-row-copy">
|
||||||
|
<div className="bt-row-label" id={id}><Mark text={label}/>{badge}</div>
|
||||||
|
{hint && <div className="bt-row-hint">{typeof hint === 'string' ? <Mark text={hint}/> : hint}</div>}
|
||||||
|
</div>
|
||||||
|
{children && <div className="bt-row-control">{children}</div>}
|
||||||
|
</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Badge({ children, tone = 'plain' }: { children: ReactNode; tone?: 'plain' | 'accent' | 'warn' | 'ok' }) {
|
||||||
|
return <span className={`bt-badge is-${tone}`}>{children}</span>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function EmptyState({ icon, title, children, action }: { icon?: ReactNode; title: string; children?: ReactNode; action?: ReactNode }) {
|
||||||
|
return <div className="bt-empty">
|
||||||
|
{icon && <div className="bt-empty-icon" aria-hidden="true">{icon}</div>}
|
||||||
|
<strong>{title}</strong>
|
||||||
|
{children && <p>{children}</p>}
|
||||||
|
{action && <div className="bt-empty-action">{action}</div>}
|
||||||
|
</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Buttons
|
||||||
|
|
||||||
|
type ButtonProps = { children: ReactNode; onClick?: () => void; tone?: 'plain' | 'primary' | 'danger' | 'ghost'; disabled?: boolean; title?: string; icon?: ReactNode; size?: 'sm' | 'md'; type?: 'button' | 'submit'; label?: string };
|
||||||
|
export function Button({ children, onClick, tone = 'plain', disabled, title, icon, size = 'md', type = 'button', label }: ButtonProps) {
|
||||||
|
return <button type={type} className={`bt-btn is-${tone} is-${size}`} disabled={disabled} title={title} aria-label={label} onClick={onClick}>{icon}{children}</button>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Toggle
|
||||||
|
|
||||||
|
export function Toggle({ checked, onChange, label, disabled }: { checked: boolean; onChange(next: boolean): void; label: string; disabled?: boolean }) {
|
||||||
|
return <button type="button" role="switch" aria-checked={checked} aria-label={label} disabled={disabled} className={`bt-toggle ${checked ? 'is-on' : ''}`} onClick={() => onChange(!checked)}>
|
||||||
|
<span className="bt-toggle-knob"/>
|
||||||
|
</button>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Segmented control (2-4 options)
|
||||||
|
|
||||||
|
export type Option<T extends string | number> = { value: T; label: string; hint?: string; icon?: ReactNode; style?: CSSProperties };
|
||||||
|
|
||||||
|
export function Segmented<T extends string | number>({ value, options, onChange, label, size = 'md' }: { value: T | null; options: Array<Option<T>>; onChange(next: T): void; label: string; size?: 'sm' | 'md' }) {
|
||||||
|
const ref = useRef<HTMLDivElement>(null);
|
||||||
|
const [thumb, setThumb] = useState<CSSProperties>({ opacity: 0 });
|
||||||
|
const index = options.findIndex(option => option.value === value);
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
const root = ref.current;
|
||||||
|
const node = root?.querySelectorAll<HTMLElement>('[role="radio"]')[index];
|
||||||
|
if (!root || !node) { setThumb({ opacity: 0 }); return; }
|
||||||
|
setThumb({ opacity: 1, width: node.offsetWidth, transform: `translateX(${node.offsetLeft - 3}px)` });
|
||||||
|
}, [index, options.length]);
|
||||||
|
useEffect(() => {
|
||||||
|
const root = ref.current;
|
||||||
|
if (!root || typeof ResizeObserver === 'undefined') return;
|
||||||
|
const observer = new ResizeObserver(() => {
|
||||||
|
const node = root.querySelectorAll<HTMLElement>('[role="radio"]')[index];
|
||||||
|
if (node) setThumb({ opacity: 1, width: node.offsetWidth, transform: `translateX(${node.offsetLeft - 3}px)` });
|
||||||
|
});
|
||||||
|
observer.observe(root);
|
||||||
|
return () => observer.disconnect();
|
||||||
|
}, [index]);
|
||||||
|
const onKey = (event: KeyboardEvent) => {
|
||||||
|
// Right-to-left layouts put the next option on the left.
|
||||||
|
const rtl = !!ref.current && getComputedStyle(ref.current).direction === 'rtl';
|
||||||
|
const forward = rtl ? 'ArrowLeft' : 'ArrowRight';
|
||||||
|
const back = rtl ? 'ArrowRight' : 'ArrowLeft';
|
||||||
|
const step = event.key === forward || event.key === 'ArrowDown' ? 1 : event.key === back || event.key === 'ArrowUp' ? -1 : 0;
|
||||||
|
if (!step) return;
|
||||||
|
event.preventDefault();
|
||||||
|
const next = options[(Math.max(index, 0) + step + options.length) % options.length]!;
|
||||||
|
onChange(next.value);
|
||||||
|
requestAnimationFrame(() => ref.current?.querySelector<HTMLElement>('[aria-checked="true"]')?.focus());
|
||||||
|
};
|
||||||
|
return <div ref={ref} className={`bt-seg is-${size}`} role="radiogroup" aria-label={label} onKeyDown={onKey}>
|
||||||
|
<span className="bt-seg-thumb" style={thumb} aria-hidden="true"/>
|
||||||
|
{options.map((option, i) => <button key={String(option.value)} type="button" role="radio" aria-checked={i === index} tabIndex={i === index || (index < 0 && i === 0) ? 0 : -1}
|
||||||
|
title={option.hint} style={option.style} className={i === index ? 'is-on' : ''} onClick={() => onChange(option.value)}>{option.icon}{option.label}</button>)}
|
||||||
|
</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Select (listbox popover for longer lists)
|
||||||
|
|
||||||
|
export function Select<T extends string>({ value, options, onChange, label, placeholder: givenPlaceholder, width }: { value: T | null; options: Array<Option<T>>; onChange(next: T): void; label: string; placeholder?: string; width?: number }) {
|
||||||
|
const t = useT();
|
||||||
|
const placeholder = givenPlaceholder ?? t('wb.ui.select.placeholder');
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
const [active, setActive] = useState(0);
|
||||||
|
const root = useRef<HTMLDivElement>(null);
|
||||||
|
const list = useRef<HTMLUListElement>(null);
|
||||||
|
const id = useId();
|
||||||
|
const current = options.find(option => option.value === value);
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return;
|
||||||
|
setActive(Math.max(0, options.findIndex(option => option.value === value)));
|
||||||
|
const close = (event: PointerEvent) => { if (!root.current?.contains(event.target as Node)) setOpen(false); };
|
||||||
|
document.addEventListener('pointerdown', close);
|
||||||
|
return () => document.removeEventListener('pointerdown', close);
|
||||||
|
}, [open]);
|
||||||
|
useEffect(() => { if (open) list.current?.querySelectorAll('li')[active]?.scrollIntoView({ block: 'nearest' }); }, [active, open]);
|
||||||
|
const choose = (option: Option<T>) => { onChange(option.value); setOpen(false); root.current?.querySelector<HTMLElement>('button')?.focus(); };
|
||||||
|
const onKey = (event: KeyboardEvent) => {
|
||||||
|
if (!open && ['ArrowDown', 'ArrowUp', 'Enter', ' '].includes(event.key)) { event.preventDefault(); setOpen(true); return; }
|
||||||
|
if (!open) return;
|
||||||
|
if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); setOpen(false); }
|
||||||
|
else if (event.key === 'ArrowDown') { event.preventDefault(); setActive(i => Math.min(options.length - 1, i + 1)); }
|
||||||
|
else if (event.key === 'ArrowUp') { event.preventDefault(); setActive(i => Math.max(0, i - 1)); }
|
||||||
|
else if (event.key === 'Home') { event.preventDefault(); setActive(0); }
|
||||||
|
else if (event.key === 'End') { event.preventDefault(); setActive(options.length - 1); }
|
||||||
|
else if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); const option = options[active]; if (option) choose(option); }
|
||||||
|
else if (event.key === 'Tab') setOpen(false);
|
||||||
|
};
|
||||||
|
return <div ref={root} className={`bt-select ${open ? 'is-open' : ''}`} style={width ? { width } : undefined} onKeyDown={onKey}>
|
||||||
|
<button type="button" className="bt-select-button" aria-haspopup="listbox" aria-expanded={open} aria-label={`${label}: ${current?.label ?? placeholder}`} aria-controls={id} onClick={() => setOpen(!open)}>
|
||||||
|
<span className="bt-select-value" style={current?.style}>{current?.icon}{current?.label ?? placeholder}</span>
|
||||||
|
<svg width="12" height="12" viewBox="0 0 12 12" aria-hidden="true"><path d="M3 4.5 6 7.5 9 4.5" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/></svg>
|
||||||
|
</button>
|
||||||
|
{open && <ul ref={list} id={id} role="listbox" aria-label={label} className="bt-select-list" aria-activedescendant={`${id}-${active}`}>
|
||||||
|
{options.map((option, i) => <li key={String(option.value)} id={`${id}-${i}`} role="option" aria-selected={option.value === value}
|
||||||
|
className={`${i === active ? 'is-active' : ''} ${option.value === value ? 'is-on' : ''}`} onPointerEnter={() => setActive(i)} onClick={() => choose(option)}>
|
||||||
|
<span className="bt-select-opt" style={option.style}>{option.icon}{option.label}</span>
|
||||||
|
{option.hint && <small>{option.hint}</small>}
|
||||||
|
{option.value === value && <svg className="bt-select-check" width="14" height="14" viewBox="0 0 14 14" aria-hidden="true"><path d="m3 7.5 2.5 2.5L11 4.5" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></svg>}
|
||||||
|
</li>)}
|
||||||
|
</ul>}
|
||||||
|
</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Slider
|
||||||
|
|
||||||
|
export function Slider({ value, min, max, step = 1, onChange, onCommit, label, format }: { value: number; min: number; max: number; step?: number; onChange(next: number): void; onCommit?(next: number): void; label: string; format(value: number): string }) {
|
||||||
|
const pct = ((value - min) / (max - min)) * 100;
|
||||||
|
return <div className="bt-slider">
|
||||||
|
<input type="range" min={min} max={max} step={step} value={value} aria-label={label} aria-valuetext={format(value)} style={{ '--pct': `${pct}%` } as CSSProperties}
|
||||||
|
onChange={event => onChange(Number(event.target.value))}
|
||||||
|
onPointerUp={event => onCommit?.(Number((event.target as HTMLInputElement).value))}
|
||||||
|
onKeyUp={event => onCommit?.(Number((event.target as HTMLInputElement).value))}/>
|
||||||
|
<output>{format(value)}</output>
|
||||||
|
</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Color: swatches, a custom picker and a hex field
|
||||||
|
|
||||||
|
export function ColorField({ value, swatches, onChange, autoLabel, label }: { value: string | null; swatches: string[]; onChange(next: string | null): void; autoLabel?: string; label: string }) {
|
||||||
|
const t = useT();
|
||||||
|
const [draft, setDraft] = useState(value ?? '');
|
||||||
|
useEffect(() => setDraft(value ?? ''), [value]);
|
||||||
|
const custom = value && !swatches.includes(value);
|
||||||
|
const commit = (text: string) => {
|
||||||
|
const hex = text.trim().replace(/^([0-9a-f]{6})$/i, '#$1').toLowerCase();
|
||||||
|
if (/^#[0-9a-f]{6}$/.test(hex)) onChange(hex); else setDraft(value ?? '');
|
||||||
|
};
|
||||||
|
return <div className="bt-color" role="radiogroup" aria-label={label}>
|
||||||
|
{autoLabel && <button type="button" role="radio" aria-checked={!value} className={`bt-swatch is-auto ${!value ? 'is-on' : ''}`} onClick={() => onChange(null)}>{autoLabel}</button>}
|
||||||
|
{swatches.map(color => <button key={color} type="button" role="radio" aria-checked={value === color} aria-label={color} title={color}
|
||||||
|
className={`bt-swatch ${value === color ? 'is-on' : ''}`} style={{ '--sw': color } as CSSProperties} onClick={() => onChange(color)}/>)}
|
||||||
|
<label className={`bt-swatch is-picker ${custom ? 'is-on' : ''}`} title={t('wb.ui.color.pick')} style={custom ? { '--sw': value } as CSSProperties : undefined}>
|
||||||
|
<input type="color" aria-label={t('wb.ui.color.custom', { label })} value={value ?? '#1d9bf0'} onChange={event => onChange(event.target.value.toLowerCase())}/>
|
||||||
|
</label>
|
||||||
|
<input className="bt-hex" aria-label={t('wb.ui.color.hex', { label })} spellCheck={false} maxLength={7} placeholder="#rrggbb" value={draft}
|
||||||
|
onChange={event => setDraft(event.target.value)} onBlur={event => commit(event.target.value)} onKeyDown={event => { if (event.key === 'Enter') commit((event.target as HTMLInputElement).value); }}/>
|
||||||
|
</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Text inputs
|
||||||
|
|
||||||
|
export function TextInput({ value, onChange, placeholder, label, type = 'text', width, onEnter, mono }: { value: string; onChange(next: string): void; placeholder?: string; label: string; type?: string; width?: number | string; onEnter?(): void; mono?: boolean }) {
|
||||||
|
return <input className={`bt-input ${mono ? 'is-mono' : ''}`} type={type} aria-label={label} placeholder={placeholder} value={value} style={width ? { width } : undefined}
|
||||||
|
onChange={event => onChange(event.target.value)} onKeyDown={event => { if (event.key === 'Enter') onEnter?.(); }}/>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** An input with its action button attached (Save, Add…). */
|
||||||
|
export function InputRow({ value, onChange, onSubmit, placeholder, label, button, disabled, mono }: { value: string; onChange(next: string): void; onSubmit(): void; placeholder?: string; label: string; button: string; disabled?: boolean; mono?: boolean }) {
|
||||||
|
return <form className="bt-inputrow" onSubmit={event => { event.preventDefault(); if (!disabled) onSubmit(); }}>
|
||||||
|
<input className={mono ? 'is-mono' : ''} aria-label={label} placeholder={placeholder} value={value} onChange={event => onChange(event.target.value)}/>
|
||||||
|
<button type="submit" disabled={disabled}>{button}</button>
|
||||||
|
</form>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function SearchField({ value, onChange, placeholder, label }: { value: string; onChange(next: string): void; placeholder: string; label: string }) {
|
||||||
|
const t = useT();
|
||||||
|
return <label className="bt-search">
|
||||||
|
<svg width="14" height="14" viewBox="0 0 16 16" aria-hidden="true"><circle cx="7" cy="7" r="4.75" fill="none" stroke="currentColor" strokeWidth="1.5"/><path d="m10.5 10.5 3 3" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>
|
||||||
|
<input type="search" aria-label={label} placeholder={placeholder} value={value} onChange={event => onChange(event.target.value)}
|
||||||
|
onKeyDown={event => { if (event.key === 'Escape' && value) { event.stopPropagation(); onChange(''); } }}/>
|
||||||
|
{value && <button type="button" aria-label={t('wb.ui.search.clear')} onClick={() => onChange('')}>×</button>}
|
||||||
|
</label>;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Chips: removable list items (folders, keywords)
|
||||||
|
|
||||||
|
export function ChipList({ items, onRemove, render, title, empty, icon }: { items: string[]; onRemove(item: string): void; render?(item: string): string; title?(item: string): string; empty?: string; icon?: ReactNode }) {
|
||||||
|
const t = useT();
|
||||||
|
if (!items.length) return empty ? <p className="bt-chips-empty">{empty}</p> : null;
|
||||||
|
return <ul className="bt-chips">
|
||||||
|
{items.map(item => <li key={item} className="bt-chip" title={title?.(item) ?? item}>
|
||||||
|
{icon}<span>{render ? render(item) : item}</span>
|
||||||
|
<button type="button" aria-label={t('wb.ui.chip.remove', { item: render ? render(item) : item })} onClick={() => onRemove(item)}>
|
||||||
|
<svg width="10" height="10" viewBox="0 0 10 10" aria-hidden="true"><path d="m2.5 2.5 5 5m0-5-5 5" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round"/></svg>
|
||||||
|
</button>
|
||||||
|
</li>)}
|
||||||
|
</ul>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Number with − / + buttons. */
|
||||||
|
export function Stepper({ value, min, max, onChange, label, suffix }: { value: number; min: number; max: number; onChange(next: number): void; label: string; suffix?: string }) {
|
||||||
|
const t = useT();
|
||||||
|
return <div className="bt-stepper" role="group" aria-label={label}>
|
||||||
|
<button type="button" aria-label={t('wb.ui.stepper.decrease', { label })} disabled={value <= min} onClick={() => onChange(Math.max(min, value - 1))}>−</button>
|
||||||
|
<output aria-live="polite">{value}{suffix && <small>{suffix}</small>}</output>
|
||||||
|
<button type="button" aria-label={t('wb.ui.stepper.increase', { label })} disabled={value >= max} onClick={() => onChange(Math.min(max, value + 1))}>+</button>
|
||||||
|
</div>;
|
||||||
|
}
|
||||||
236
packages/shell/src/panel/fonts/FontBrowser.tsx
Normal file
236
packages/shell/src/panel/fonts/FontBrowser.tsx
Normal file
|
|
@ -0,0 +1,236 @@
|
||||||
|
// The font browser: every Google Fonts family (offline catalog) with live previews rendered in the
|
||||||
|
// font itself, category filters and search, a detail view with editable sample text and weight
|
||||||
|
// selection, plus the built-in and system fonts. Google fonts are downloaded natively once (woff2
|
||||||
|
// from fonts.googleapis.com / fonts.gstatic.com into app data), then the site's page loads them from bytes.
|
||||||
|
import { useEffect, useMemo, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from 'react';
|
||||||
|
import { createPortal } from 'react-dom';
|
||||||
|
import { FONT_CHOICES, fontStack, sanitizeFonts } from '../../../../runtime/src/themeSpec.ts';
|
||||||
|
import { invoke } from '../../frame/bridge.ts';
|
||||||
|
import { useT } from '../../frame/hooks.ts';
|
||||||
|
import { tx } from '../../frame/i18n.ts';
|
||||||
|
import { Button, Segmented, Slider } from '../controls.tsx';
|
||||||
|
import { panelThemes } from '../site.ts';
|
||||||
|
import { themeStore, useThemeState } from '../themes.ts';
|
||||||
|
import {
|
||||||
|
CATEGORIES, availableWeights, bytesLabel, defaultWeights, loadCatalog, searchFonts, specimenUrl, stackFor, weightsLabel,
|
||||||
|
type CatalogFont, type Category, type Weights,
|
||||||
|
} from './catalog.ts';
|
||||||
|
|
||||||
|
export type FontPick = { family: string[]; source?: 'google' };
|
||||||
|
const PAGE = 60;
|
||||||
|
const SAMPLES = [
|
||||||
|
'The quick brown fox jumps over the lazy dog',
|
||||||
|
'Your timeline, your way. 1,284 likes · 3.2K reposts',
|
||||||
|
'Pijamalı hasta yağız şoföre çabucak güvendi',
|
||||||
|
];
|
||||||
|
|
||||||
|
/** Renders `text` in `font`: the installed family, else a tiny text-subset preview fetched natively. */
|
||||||
|
function FontText({ font, text, weight, className, eager }: { font: CatalogFont; text: string; weight?: number; className?: string; eager?: boolean }) {
|
||||||
|
const ref = useRef<HTMLSpanElement>(null);
|
||||||
|
const [family, setFamily] = useState<string | null>(null);
|
||||||
|
const [visible, setVisible] = useState(!!eager);
|
||||||
|
const { ensureShellFont, isInstalled, previewFont } = themeStore();
|
||||||
|
const installed = isInstalled(font.family);
|
||||||
|
useEffect(() => {
|
||||||
|
if (visible) return;
|
||||||
|
const node = ref.current;
|
||||||
|
if (!node || typeof IntersectionObserver === 'undefined') { setVisible(true); return; }
|
||||||
|
const observer = new IntersectionObserver(entries => { if (entries.some(entry => entry.isIntersecting)) { setVisible(true); observer.disconnect(); } }, { rootMargin: '120px' });
|
||||||
|
observer.observe(node);
|
||||||
|
return () => observer.disconnect();
|
||||||
|
}, [visible]);
|
||||||
|
useEffect(() => {
|
||||||
|
if (!visible || !text) return;
|
||||||
|
let live = true;
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
const load = installed
|
||||||
|
? ensureShellFont(font.family).then(ok => ok ? font.family : null)
|
||||||
|
: previewFont(font.family, font.axis ? { kind: 'range', min: font.axis[0], max: font.axis[1] } : { kind: 'list', values: font.weights.slice(0, 9) }, [...new Set(text)].join('').slice(0, 120));
|
||||||
|
void load.then(name => { if (live) setFamily(name); });
|
||||||
|
}, eager ? 250 : 0);
|
||||||
|
return () => { live = false; clearTimeout(timer); };
|
||||||
|
}, [visible, text, font.family, installed]);
|
||||||
|
return <span ref={ref} className={`${className ?? ''} ${family ? 'is-ready' : 'is-loading'}`}
|
||||||
|
style={{ fontFamily: family ? `"${family}", ${stackFor(font).slice(1).join(', ')}` : undefined, fontWeight: weight }}>{text}</span>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function FontBrowser({ role, current, onPick, onClose }: { role: string; current: string | null; onPick(pick: FontPick): void; onClose(): void }) {
|
||||||
|
const t = useT();
|
||||||
|
const { fonts: installedFonts } = useThemeState();
|
||||||
|
const [tab, setTab] = useState<'google' | 'system'>('google');
|
||||||
|
const [catalog, setCatalog] = useState<CatalogFont[]>([]);
|
||||||
|
const [query, setQuery] = useState('');
|
||||||
|
const [category, setCategory] = useState<Category | 'all'>('all');
|
||||||
|
const [onlyInstalled, setOnlyInstalled] = useState(false);
|
||||||
|
const [limit, setLimit] = useState(PAGE);
|
||||||
|
const [selected, setSelected] = useState<string | null>(current);
|
||||||
|
const [active, setActive] = useState(0);
|
||||||
|
const search = useRef<HTMLInputElement>(null);
|
||||||
|
const list = useRef<HTMLUListElement>(null);
|
||||||
|
const root = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
|
useEffect(() => { void loadCatalog().then(setCatalog); search.current?.focus(); }, []);
|
||||||
|
useEffect(() => {
|
||||||
|
const onKey = (event: KeyboardEvent) => { if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); onClose(); } };
|
||||||
|
window.addEventListener('keydown', onKey, true);
|
||||||
|
return () => window.removeEventListener('keydown', onKey, true);
|
||||||
|
}, [onClose]);
|
||||||
|
|
||||||
|
const installed = useMemo(() => new Set(installedFonts.map(font => font.family)), [installedFonts]);
|
||||||
|
const results = useMemo(() => searchFonts(catalog, { query, category, only: onlyInstalled ? installed : undefined }), [catalog, query, category, onlyInstalled, installed]);
|
||||||
|
useEffect(() => { setLimit(PAGE); setActive(0); list.current?.scrollTo({ top: 0 }); }, [query, category, onlyInstalled]);
|
||||||
|
const shown = results.slice(0, limit);
|
||||||
|
const detail = catalog.find(font => font.family === selected) ?? shown[0] ?? null;
|
||||||
|
|
||||||
|
const onListKey = (event: ReactKeyboardEvent) => {
|
||||||
|
if (!shown.length) return;
|
||||||
|
const move = (index: number) => {
|
||||||
|
const next = Math.max(0, Math.min(shown.length - 1, index));
|
||||||
|
setActive(next);
|
||||||
|
list.current?.querySelectorAll('li')[next]?.scrollIntoView({ block: 'nearest' });
|
||||||
|
};
|
||||||
|
if (event.key === 'ArrowDown') { event.preventDefault(); move(active + 1); }
|
||||||
|
else if (event.key === 'ArrowUp') { event.preventDefault(); if (active === 0 && event.target === list.current) search.current?.focus(); else move(active - 1); }
|
||||||
|
else if (event.key === 'PageDown') { event.preventDefault(); move(active + 8); }
|
||||||
|
else if (event.key === 'PageUp') { event.preventDefault(); move(active - 8); }
|
||||||
|
else if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); setSelected(shown[active]!.family); }
|
||||||
|
};
|
||||||
|
|
||||||
|
// Inside the panel (not the whole window): site panes are native webviews above the shell elsewhere.
|
||||||
|
return createPortal(<div className="wb-sheet-backdrop" onMouseDown={event => { if (event.target === event.currentTarget) onClose(); }}>
|
||||||
|
<div ref={root} className="wb-sheet wb-fb" role="dialog" aria-modal="true" aria-label={t('wb.fonts.chooseFor', { role })}>
|
||||||
|
<header className="wb-sheet-head">
|
||||||
|
<div>
|
||||||
|
<h2>{t('wb.fonts.choose')} <span>{t('wb.fonts.forRole', { role })}</span></h2>
|
||||||
|
<p>{tab === 'google' ? t('wb.fonts.googleCount', { count: catalog.length || 1800 }) : t('wb.fonts.systemHint')}</p>
|
||||||
|
</div>
|
||||||
|
<Segmented<'google' | 'system'> label={t('wb.fonts.source')} size="sm" value={tab} onChange={setTab} options={[{ value: 'google', label: 'Google Fonts' }, { value: 'system', label: t('wb.fonts.builtIn') }]}/>
|
||||||
|
<button type="button" className="wb-sheet-close" aria-label={t('wb.common.close')} onClick={onClose}><svg width="14" height="14" viewBox="0 0 14 14" aria-hidden="true"><path d="m3.5 3.5 7 7m0-7-7 7" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round"/></svg></button>
|
||||||
|
</header>
|
||||||
|
{tab === 'system' ? <SystemFonts current={current} onPick={onPick}/> : <>
|
||||||
|
<div className="wb-fb-tools">
|
||||||
|
<label className="bt-search wb-fb-search">
|
||||||
|
<svg width="14" height="14" viewBox="0 0 16 16" aria-hidden="true"><circle cx="7" cy="7" r="4.75" fill="none" stroke="currentColor" strokeWidth="1.5"/><path d="m10.5 10.5 3 3" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>
|
||||||
|
<input ref={search} type="search" aria-label={t('wb.fonts.search')} placeholder={t('wb.fonts.searchPlaceholder')} value={query}
|
||||||
|
onChange={event => setQuery(event.target.value)}
|
||||||
|
onKeyDown={event => {
|
||||||
|
if (event.key === 'ArrowDown') { event.preventDefault(); list.current?.focus(); setActive(0); }
|
||||||
|
if (event.key === 'Enter' && shown[0]) { event.preventDefault(); setSelected(shown[0].family); }
|
||||||
|
}}/>
|
||||||
|
</label>
|
||||||
|
<div className="wb-fb-cats" role="radiogroup" aria-label={t('wb.fonts.category')}>
|
||||||
|
{CATEGORIES.map(item => <button key={item} type="button" role="radio" aria-checked={category === item} className={category === item ? 'is-on' : ''} onClick={() => setCategory(item)}>{tx(`wb.fonts.category.${item}`)}</button>)}
|
||||||
|
<button type="button" role="checkbox" aria-checked={onlyInstalled} className={`wb-fb-installed ${onlyInstalled ? 'is-on' : ''}`} onClick={() => setOnlyInstalled(!onlyInstalled)}>
|
||||||
|
{t('wb.fonts.downloaded')}{installed.size ? ` · ${installed.size}` : ''}</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="wb-fb-body">
|
||||||
|
<ul ref={list} className="wb-fb-list" role="listbox" tabIndex={0} aria-label={t('wb.fonts.families')} aria-activedescendant={shown[active] ? `wb-fb-${active}` : undefined} onKeyDown={onListKey}>
|
||||||
|
{!catalog.length && <li className="wb-fb-empty">{t('wb.fonts.loadingCatalog')}</li>}
|
||||||
|
{catalog.length > 0 && !shown.length && <li className="wb-fb-empty">{t('wb.fonts.noMatch', { query })}</li>}
|
||||||
|
{shown.map((font, index) => <li key={font.family} id={`wb-fb-${index}`} role="option" aria-selected={font.family === selected}
|
||||||
|
className={`${index === active ? 'is-active' : ''} ${font.family === selected ? 'is-on' : ''}`}
|
||||||
|
onPointerEnter={() => setActive(index)} onClick={() => { setActive(index); setSelected(font.family); }}>
|
||||||
|
<FontText font={font} text={font.family} className="wb-fb-name"/>
|
||||||
|
<span className="wb-fb-meta">{tx(`wb.fonts.categoryName.${font.category}`)} · {font.axis ? t('wb.fonts.variable') : t('wb.fonts.weightCount', { count: font.weights.length })}</span>
|
||||||
|
{installed.has(font.family) && <span className="wb-fb-tag">{t('wb.fonts.downloaded')}</span>}
|
||||||
|
{current === font.family && <span className="wb-fb-tag is-accent">{t('wb.fonts.inUse')}</span>}
|
||||||
|
</li>)}
|
||||||
|
{results.length > limit && <li className="wb-fb-more"><Button size="sm" tone="ghost" onClick={() => setLimit(limit + PAGE)}>{t('wb.fonts.showMore', { count: Math.min(PAGE, results.length - limit), total: results.length })}</Button></li>}
|
||||||
|
</ul>
|
||||||
|
<FontDetail key={detail?.family ?? 'none'} font={detail} role={role} onPick={onPick}/>
|
||||||
|
</div>
|
||||||
|
</>}
|
||||||
|
<footer className="wb-sheet-foot">
|
||||||
|
{t('wb.fonts.footer')}
|
||||||
|
</footer>
|
||||||
|
</div>
|
||||||
|
</div>, document.querySelector('.btp') ?? document.body);
|
||||||
|
}
|
||||||
|
|
||||||
|
function FontDetail({ font, role, onPick }: { font: CatalogFont | null; role: string; onPick(pick: FontPick): void }) {
|
||||||
|
const t = useT();
|
||||||
|
const { installFont } = themeStore();
|
||||||
|
const { fonts } = useThemeState();
|
||||||
|
const [sample, setSample] = useState(SAMPLES[0]!);
|
||||||
|
const [weight, setWeight] = useState(400);
|
||||||
|
const [weights, setWeights] = useState<Weights | null>(font ? defaultWeights(font) : null);
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [error, setError] = useState('');
|
||||||
|
useEffect(() => {
|
||||||
|
if (!font) return;
|
||||||
|
const available = availableWeights(font);
|
||||||
|
setWeight(available.includes(400) ? 400 : available[0] ?? 400);
|
||||||
|
}, [font?.family]);
|
||||||
|
if (!font || !weights) return <div className="wb-fb-detail is-empty"><p>{t('wb.fonts.detailEmpty', { role })}</p></div>;
|
||||||
|
const installed = fonts.find(item => item.family === font.family);
|
||||||
|
const available = availableWeights(font);
|
||||||
|
const pick = async () => {
|
||||||
|
setError('');
|
||||||
|
if (!installed || JSON.stringify(installed.weights) !== JSON.stringify(weights)) {
|
||||||
|
setBusy(true);
|
||||||
|
try { await installFont(font.family, weights); }
|
||||||
|
catch (reason) { setBusy(false); setError(reason instanceof Error ? reason.message : String(reason)); return; }
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
onPick({ family: stackFor(font), source: 'google' });
|
||||||
|
};
|
||||||
|
const toggle = (value: number) => {
|
||||||
|
if (weights.kind !== 'list') return;
|
||||||
|
const values = weights.values.includes(value) ? weights.values.filter(item => item !== value) : [...weights.values, value].sort((a, b) => a - b);
|
||||||
|
if (values.length) setWeights({ kind: 'list', values });
|
||||||
|
};
|
||||||
|
return <div className="wb-fb-detail">
|
||||||
|
<div className="wb-fb-hero">
|
||||||
|
<FontText font={font} text={font.family} className="wb-fb-hero-name" weight={weight} eager/>
|
||||||
|
<span className="wb-fb-hero-meta">{tx(`wb.fonts.categoryName.${font.category}`)} · {font.axis ? t('wb.fonts.variableRange', { min: font.axis[0], max: font.axis[1] }) : t('wb.fonts.weightsList', { weights: font.weights.join(', ') })}{installed ? ` · ${t('wb.fonts.downloadedSize', { size: bytesLabel(installed.bytes) })}` : ''}</span>
|
||||||
|
</div>
|
||||||
|
<div className="wb-fb-sample">
|
||||||
|
<FontText font={font} text={sample || font.family} className="wb-fb-sample-text" weight={weight} eager/>
|
||||||
|
<textarea aria-label={t('wb.fonts.sample')} value={sample} maxLength={120} rows={2} spellCheck={false} onChange={event => setSample(event.target.value)}/>
|
||||||
|
<div className="wb-fb-samples">{SAMPLES.map(text => <button key={text} type="button" className={text === sample ? 'is-on' : ''} onClick={() => setSample(text)}>{text.slice(0, 18)}…</button>)}</div>
|
||||||
|
</div>
|
||||||
|
<div className="wb-fb-field">
|
||||||
|
<span>{t('wb.fonts.previewWeight')}</span>
|
||||||
|
{font.axis
|
||||||
|
? <Slider label={t('wb.fonts.previewWeight')} min={font.axis[0]} max={font.axis[1]} step={10} value={weight} format={v => String(v)} onChange={setWeight}/>
|
||||||
|
: <div className="wb-fb-weights" role="radiogroup" aria-label={t('wb.fonts.previewWeight')}>{available.map(value => <button key={value} type="button" role="radio" aria-checked={weight === value} className={weight === value ? 'is-on' : ''} onClick={() => setWeight(value)}>{value}</button>)}</div>}
|
||||||
|
</div>
|
||||||
|
<div className="wb-fb-field">
|
||||||
|
<span>{t('wb.panel.updates.download')}</span>
|
||||||
|
{weights.kind === 'range'
|
||||||
|
? <div className="wb-fb-range">
|
||||||
|
<Slider label={t('wb.fonts.lightest')} min={font.axis![0]} max={weights.max} step={100} value={weights.min} format={v => t('wb.fonts.fromWeight', { weight: v })} onChange={min => setWeights({ ...weights, min })}/>
|
||||||
|
<Slider label={t('wb.fonts.heaviest')} min={weights.min} max={font.axis![1]} step={100} value={weights.max} format={v => t('wb.fonts.toWeight', { weight: v })} onChange={max => setWeights({ ...weights, max })}/>
|
||||||
|
</div>
|
||||||
|
: <div className="wb-fb-weights" role="group" aria-label={t('wb.fonts.weightsToDownload')}>{available.map(value => <button key={value} type="button" role="checkbox" aria-checked={weights.values.includes(value)} className={weights.values.includes(value) ? 'is-on' : ''} onClick={() => toggle(value)}>{value}</button>)}</div>}
|
||||||
|
<small>{font.axis ? t('wb.fonts.variableFile') : t('wb.fonts.staticFiles')} {weightsLabel(weights)}</small>
|
||||||
|
</div>
|
||||||
|
{error && <p className="wb-fb-error" role="alert">{error}</p>}
|
||||||
|
<div className="wb-fb-actions">
|
||||||
|
<Button tone="primary" disabled={busy} onClick={() => void pick()}>{busy ? t('wb.fonts.downloading') : installed && JSON.stringify(installed.weights) === JSON.stringify(weights) ? t('wb.fonts.useFor', { role }) : t('wb.fonts.downloadUseFor', { role })}</Button>
|
||||||
|
<Button tone="ghost" onClick={() => void invoke('open_external_url', { url: specimenUrl(font.family) }).catch(() => {})}>{t('wb.fonts.license')}</Button>
|
||||||
|
</div>
|
||||||
|
</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function SystemFonts({ current, onPick }: { current: string | null; onPick(pick: FontPick): void }) {
|
||||||
|
const t = useT();
|
||||||
|
const [custom, setCustom] = useState('');
|
||||||
|
const valid = sanitizeFonts([custom.trim()]).length === 1;
|
||||||
|
return <div className="wb-fb-system">
|
||||||
|
<ul className="wb-fb-grid">
|
||||||
|
{(panelThemes().fontChoices ?? FONT_CHOICES).filter(choice => choice.family.length).map(choice => <li key={choice.id}>
|
||||||
|
<button type="button" className={current === choice.family[0] ? 'is-on' : ''} onClick={() => onPick({ family: choice.family })}>
|
||||||
|
<span style={{ fontFamily: fontStack(choice.family) }}>{choice.key ? tx(choice.key, undefined, choice.label) : choice.label}</span>
|
||||||
|
<small style={{ fontFamily: fontStack(choice.family) }}>Aa Bb 0123 · The quick brown fox</small>
|
||||||
|
</button>
|
||||||
|
</li>)}
|
||||||
|
</ul>
|
||||||
|
<form className="wb-fb-custom" onSubmit={event => { event.preventDefault(); if (valid) onPick({ family: [custom.trim(), 'system-ui', 'sans-serif'] }); }}>
|
||||||
|
<label><span>{t('wb.fonts.installedFont')}</span>
|
||||||
|
<input value={custom} placeholder={t('wb.fonts.installedPlaceholder')} onChange={event => setCustom(event.target.value)} style={valid ? { fontFamily: fontStack([custom.trim()]) } : undefined}/></label>
|
||||||
|
<Button type="submit" size="sm" disabled={!valid}>{t('wb.fonts.useIt')}</Button>
|
||||||
|
</form>
|
||||||
|
</div>;
|
||||||
|
}
|
||||||
108
packages/shell/src/panel/fonts/FontRoles.tsx
Normal file
108
packages/shell/src/panel/fonts/FontRoles.tsx
Normal file
|
|
@ -0,0 +1,108 @@
|
||||||
|
// "Which font goes where": one row per font role. Every role inherits the interface font until it
|
||||||
|
// is given its own (from Google Fonts, the bundled Geist fonts or an installed system font), and
|
||||||
|
// every role but the interface can fine-tune weight, size, letter spacing and tabular figures.
|
||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import { FONT_ROLE_NAMES, ROLE_LIMITS, fontStack, sanitizeFonts, type FontRole, type FontRoleName, type FontRoleSpec, type FontSpec } from '../../../../runtime/src/themeSpec.ts';
|
||||||
|
import { useT } from '../../frame/hooks.ts';
|
||||||
|
import { formatNumber, t, tx } from '../../frame/i18n.ts';
|
||||||
|
import { Button, Select, Slider, Toggle } from '../controls.tsx';
|
||||||
|
import { panelSite, panelThemes } from '../site.ts';
|
||||||
|
import { themeStore, useThemeState } from '../themes.ts';
|
||||||
|
import { FontBrowser, type FontPick } from './FontBrowser.tsx';
|
||||||
|
import '../builder.css';
|
||||||
|
|
||||||
|
/** A font role's name and hint in the active language (`fonts.role.<role>.label/.hint`). */
|
||||||
|
export const roleInfo = (role: FontRoleName) => ({ label: tx(`wb.fonts.role.${role}.label`), hint: tx(`wb.fonts.role.${role}.hint`) });
|
||||||
|
|
||||||
|
const WEIGHTS = [100, 200, 300, 400, 500, 600, 700, 800, 900];
|
||||||
|
const spec = (role: FontRole): FontRoleSpec => role === 'inherit' ? { family: [] } : role;
|
||||||
|
const tidy = (next: FontRoleSpec): FontRole => Object.keys(next).length === 1 && !next.family.length ? 'inherit' : next;
|
||||||
|
|
||||||
|
/** The name a role shows: its own first family, or where it inherits from. */
|
||||||
|
export function roleLabel(font: FontSpec, role: FontRoleName): { name: string; inherited: boolean; stack?: string } {
|
||||||
|
const own = font.roles[role];
|
||||||
|
if (own !== 'inherit' && own.family.length) return { name: own.family[0]!, inherited: false, stack: fontStack(own.family) };
|
||||||
|
const siteFont = panelThemes().siteFont;
|
||||||
|
if (role === 'interface') return { name: siteFont, inherited: true };
|
||||||
|
if (role === 'mono') return { name: t('wb.fonts.monospace'), inherited: true, stack: fontStack(['Cascadia Mono', 'Consolas', 'ui-monospace', 'monospace']) };
|
||||||
|
const base = font.roles.interface;
|
||||||
|
if (base !== 'inherit' && base.family.length) return { name: base.family[0]!, inherited: true, stack: fontStack(base.family) };
|
||||||
|
return { name: role === 'chrome' ? `Geist (${panelSite().brand.name})` : siteFont, inherited: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Loads the Google fonts a font spec names into the panel so its labels render in them. */
|
||||||
|
export function useShellFonts(font: FontSpec) {
|
||||||
|
const { fonts } = useThemeState();
|
||||||
|
const { ensureShellFont, isInstalled } = themeStore();
|
||||||
|
useEffect(() => {
|
||||||
|
for (const role of FONT_ROLE_NAMES) {
|
||||||
|
const value = font.roles[role];
|
||||||
|
if (value !== 'inherit' && value.source === 'google' && value.family[0] && isInstalled(value.family[0])) void ensureShellFont(value.family[0]);
|
||||||
|
}
|
||||||
|
}, [font, fonts]);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function FontRoles({ font, onRole, compact }: { font: FontSpec; onRole(role: FontRoleName, next: FontRole, commit?: boolean): void; compact?: boolean }) {
|
||||||
|
const t = useT();
|
||||||
|
const [browsing, setBrowsing] = useState<FontRoleName | null>(null);
|
||||||
|
const [open, setOpen] = useState<FontRoleName | null>(null);
|
||||||
|
useShellFonts(font);
|
||||||
|
const pick = (role: FontRoleName, choice: FontPick) => {
|
||||||
|
const current = spec(font.roles[role]);
|
||||||
|
const next: FontRoleSpec = { ...current, family: sanitizeFonts(choice.family) };
|
||||||
|
if (choice.source) next.source = choice.source; else delete next.source;
|
||||||
|
onRole(role, tidy(next));
|
||||||
|
setBrowsing(null);
|
||||||
|
};
|
||||||
|
return <div className={`wb-roles ${compact ? 'is-compact' : ''}`}>
|
||||||
|
{FONT_ROLE_NAMES.map(role => {
|
||||||
|
const label = roleLabel(font, role);
|
||||||
|
const value = font.roles[role];
|
||||||
|
const own = spec(value);
|
||||||
|
const tuned = role !== 'interface' && (own.weight !== undefined || own.size !== undefined || own.tracking !== undefined || !!own.tabular);
|
||||||
|
const set = (patch: Partial<FontRoleSpec>, commit = true) => {
|
||||||
|
const next: FontRoleSpec = { ...own, ...patch };
|
||||||
|
for (const key of Object.keys(patch) as Array<keyof FontRoleSpec>) if (patch[key] === undefined) delete next[key];
|
||||||
|
onRole(role, tidy(next), commit);
|
||||||
|
};
|
||||||
|
const info = roleInfo(role);
|
||||||
|
return <div key={role} className={`wb-role ${open === role ? 'is-open' : ''}`} role="group" aria-label={info.label}>
|
||||||
|
<div className="wb-role-main">
|
||||||
|
<div className="wb-role-copy">
|
||||||
|
<strong>{info.label}</strong>
|
||||||
|
{!compact && <small>{info.hint}</small>}
|
||||||
|
</div>
|
||||||
|
<button type="button" className={`wb-role-font ${label.inherited ? 'is-inherited' : ''}`} onClick={() => setBrowsing(role)}
|
||||||
|
aria-label={label.inherited ? t('wb.fonts.roleInherited', { role: info.label, font: label.name }) : t('wb.fonts.roleOwn', { role: info.label, font: label.name })}>
|
||||||
|
<span className="wb-role-sample" style={{ fontFamily: label.stack, fontWeight: own.weight, letterSpacing: own.tracking !== undefined ? `${own.tracking}em` : undefined, fontVariantNumeric: own.tabular ? 'tabular-nums' : undefined }}>
|
||||||
|
{role === 'numbers' ? `${formatNumber(1284)} · ${formatNumber(3200, { notation: 'compact' })}` : role === 'mono' ? 'const x = 42;' : label.name}
|
||||||
|
</span>
|
||||||
|
<span className="wb-role-name">{label.inherited ? t('wb.fonts.inherits', { font: label.name }) : label.name}{own.source === 'google' && <em>Google</em>}</span>
|
||||||
|
</button>
|
||||||
|
<div className="wb-role-actions">
|
||||||
|
{role !== 'interface' && <button type="button" className={`wb-role-tune ${tuned ? 'is-tuned' : ''}`} aria-expanded={open === role} aria-label={t('wb.fonts.fineTune', { role: info.label })} title={t('wb.fonts.fineTuneTitle')}
|
||||||
|
onClick={() => setOpen(open === role ? null : role)}>
|
||||||
|
<svg width="14" height="14" viewBox="0 0 16 16" aria-hidden="true"><path d="M3 5h6m3 0h1M3 11h1m3 0h6M9 3.5v3M4 9.5v3" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>
|
||||||
|
</button>}
|
||||||
|
{value !== 'inherit' && <Button size="sm" tone="ghost" onClick={() => onRole(role, 'inherit')} title={t('wb.fonts.inheritAgain')}>{t('wb.common.reset')}</Button>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
{open === role && role !== 'interface' && <div className="wb-role-tuning">
|
||||||
|
<label><span>{t('wb.fonts.weight')}</span>
|
||||||
|
<Select label={t('wb.fonts.roleWeight', { role: info.label })} value={String(own.weight ?? 'auto')} width={130}
|
||||||
|
options={[{ value: 'auto', label: t('wb.fonts.asSite') }, ...WEIGHTS.map(w => ({ value: String(w), label: String(w), style: { fontWeight: w } }))]}
|
||||||
|
onChange={v => set({ weight: v === 'auto' ? undefined : Number(v) })}/></label>
|
||||||
|
<label><span>{t('wb.fonts.size')}</span>
|
||||||
|
<Slider label={t('wb.fonts.roleSize', { role: info.label })} min={ROLE_LIMITS.size[0] * 100} max={ROLE_LIMITS.size[1] * 100} step={1} value={Math.round((own.size ?? 1) * 100)} format={v => t('wb.appearance.percent', { value: v / 100 })}
|
||||||
|
onChange={v => set({ size: v === 100 ? undefined : v / 100 }, false)} onCommit={v => set({ size: v === 100 ? undefined : v / 100 })}/></label>
|
||||||
|
<label><span>{t('wb.fonts.spacing')}</span>
|
||||||
|
<Slider label={t('wb.fonts.roleSpacing', { role: info.label })} min={ROLE_LIMITS.tracking[0] * 1000} max={ROLE_LIMITS.tracking[1] * 1000} step={2} value={Math.round((own.tracking ?? 0) * 1000)} format={v => `${formatNumber(v / 1000, { minimumFractionDigits: 3, maximumFractionDigits: 3 })} em`}
|
||||||
|
onChange={v => set({ tracking: v === 0 ? undefined : v / 1000 }, false)} onCommit={v => set({ tracking: v === 0 ? undefined : v / 1000 })}/></label>
|
||||||
|
<label className="is-inline"><span>{t('wb.fonts.tabular')}</span><Toggle label={t('wb.fonts.roleTabular', { role: info.label })} checked={!!own.tabular} onChange={tabular => set({ tabular: tabular || undefined })}/></label>
|
||||||
|
</div>}
|
||||||
|
</div>;
|
||||||
|
})}
|
||||||
|
{browsing && <FontBrowser role={roleInfo(browsing).label} current={spec(font.roles[browsing]).family[0] ?? null}
|
||||||
|
onPick={choice => pick(browsing, choice)} onClose={() => setBrowsing(null)}/>}
|
||||||
|
</div>;
|
||||||
|
}
|
||||||
80
packages/shell/src/panel/fonts/catalog.ts
Normal file
80
packages/shell/src/panel/fonts/catalog.ts
Normal file
|
|
@ -0,0 +1,80 @@
|
||||||
|
// The Google Fonts catalog the font browser shows: an offline snapshot (googleFontsCatalog.json,
|
||||||
|
// regenerated by packages/shell/scripts/google-fonts-catalog.mjs) of family names, categories and
|
||||||
|
// weights. The list itself is never fetched by the app; only the font files the owner picks are
|
||||||
|
// (natively). Pure helpers, shared with the tests.
|
||||||
|
|
||||||
|
import { textLocale } from '../../frame/i18n.ts';
|
||||||
|
|
||||||
|
export type Category = 'sans' | 'serif' | 'display' | 'handwriting' | 'mono';
|
||||||
|
export type CatalogFont = { family: string; category: Category; axis: [number, number] | null; weights: number[]; rank: number };
|
||||||
|
export type Weights = { kind: 'range'; min: number; max: number } | { kind: 'list'; values: number[] };
|
||||||
|
|
||||||
|
/** Filter chips; labels are `fonts.category.<id>` (short) and `fonts.categoryName.<id>` (full) in the catalogs. */
|
||||||
|
export const CATEGORIES: Array<Category | 'all'> = ['all', 'sans', 'serif', 'display', 'handwriting', 'mono'];
|
||||||
|
|
||||||
|
type Raw = { families: Array<[string, string, [number, number] | null, number[], number]> };
|
||||||
|
const KNOWN = new Set<Category>(['sans', 'serif', 'display', 'handwriting', 'mono']);
|
||||||
|
const NAME = /^[A-Za-z0-9]+( [A-Za-z0-9]+)*$/;
|
||||||
|
|
||||||
|
export function parseCatalog(raw: unknown): CatalogFont[] {
|
||||||
|
const families = (raw as Raw | null)?.families;
|
||||||
|
if (!Array.isArray(families)) return [];
|
||||||
|
return families
|
||||||
|
.filter(([family, category, , weights]) => typeof family === 'string' && NAME.test(family) && family.length <= 48 && KNOWN.has(category as Category) && Array.isArray(weights))
|
||||||
|
.map(([family, category, axis, weights, rank]) => ({
|
||||||
|
family, category: category as Category,
|
||||||
|
axis: Array.isArray(axis) && axis.length === 2 ? [axis[0], axis[1]] as [number, number] : null,
|
||||||
|
weights: weights.filter(w => Number.isInteger(w) && w >= 100 && w <= 1000), rank: Number(rank) || 9999,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
let loaded: Promise<CatalogFont[]> | null = null;
|
||||||
|
/** The bundled catalog, loaded on first use (it is ~90 KB, so it stays out of the shell's first paint). */
|
||||||
|
export function loadCatalog(): Promise<CatalogFont[]> {
|
||||||
|
loaded ??= import('./googleFontsCatalog.json').then(module => parseCatalog(module.default));
|
||||||
|
return loaded;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Search by name (prefix matches first, then popularity), within a category and optionally only installed ones. */
|
||||||
|
export function searchFonts(fonts: CatalogFont[], options: { query?: string; category?: Category | 'all'; only?: Set<string> }): CatalogFont[] {
|
||||||
|
const query = (options.query ?? '').trim().toLowerCase();
|
||||||
|
const list = fonts.filter(font =>
|
||||||
|
(!options.category || options.category === 'all' || font.category === options.category)
|
||||||
|
&& (!options.only || options.only.has(font.family))
|
||||||
|
&& (!query || font.family.toLowerCase().includes(query)));
|
||||||
|
if (!query) return list.sort((a, b) => a.rank - b.rank);
|
||||||
|
const score = (font: CatalogFont) => {
|
||||||
|
const name = font.family.toLowerCase();
|
||||||
|
return name === query ? 0 : name.startsWith(query) ? 1 : name.split(' ').some(word => word.startsWith(query)) ? 2 : 3;
|
||||||
|
};
|
||||||
|
return list.sort((a, b) => score(a) - score(b) || a.rank - b.rank);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What to download by default: the whole weight axis of a variable font, else regular and bold (or the nearest). */
|
||||||
|
export function defaultWeights(font: CatalogFont): Weights {
|
||||||
|
if (font.axis) return { kind: 'range', min: font.axis[0], max: font.axis[1] };
|
||||||
|
const pick = (target: number) => font.weights.reduce((best, w) => Math.abs(w - target) < Math.abs(best - target) ? w : best, font.weights[0] ?? 400);
|
||||||
|
return { kind: 'list', values: [...new Set([pick(400), pick(700)])].sort((a, b) => a - b) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The weights a font can be previewed at (every 100 inside the axis, or the static weights). */
|
||||||
|
export const availableWeights = (font: CatalogFont) => font.axis
|
||||||
|
? Array.from({ length: 9 }, (_, i) => (i + 1) * 100).filter(w => w >= font.axis![0] && w <= font.axis![1])
|
||||||
|
: font.weights;
|
||||||
|
|
||||||
|
/** A stack that falls back sensibly while the font loads, or where it lacks a glyph. */
|
||||||
|
export function stackFor(font: Pick<CatalogFont, 'family' | 'category'>): string[] {
|
||||||
|
const fallback: Record<Category, string[]> = {
|
||||||
|
sans: ['system-ui', 'sans-serif'], serif: ['Georgia', 'serif'], display: ['system-ui', 'sans-serif'],
|
||||||
|
handwriting: ['cursive'], mono: ['ui-monospace', 'monospace'],
|
||||||
|
};
|
||||||
|
return [font.family, ...fallback[font.category]];
|
||||||
|
}
|
||||||
|
|
||||||
|
export const weightsLabel = (weights: Weights) => weights.kind === 'range' ? `${weights.min}–${weights.max}` : weights.values.join(', ');
|
||||||
|
const numberLocale = () => textLocale().split('-x-')[0] || 'en';
|
||||||
|
export const bytesLabel = (bytes: number) => bytes >= 1_000_000
|
||||||
|
? `${new Intl.NumberFormat(numberLocale(), { minimumFractionDigits: 1, maximumFractionDigits: 1 }).format(bytes / 1_000_000)} MB`
|
||||||
|
: `${new Intl.NumberFormat(numberLocale()).format(Math.max(1, Math.round(bytes / 1000)))} KB`;
|
||||||
|
/** Google Fonts' own page for a family (its license and designers), opened in the browser. */
|
||||||
|
export const specimenUrl = (family: string) => `https://fonts.google.com/specimen/${family.replace(/ /g, '+')}`;
|
||||||
1
packages/shell/src/panel/fonts/googleFontsCatalog.json
Normal file
1
packages/shell/src/panel/fonts/googleFontsCatalog.json
Normal file
File diff suppressed because one or more lines are too long
38
packages/shell/src/panel/index.ts
Normal file
38
packages/shell/src/panel/index.ts
Normal file
|
|
@ -0,0 +1,38 @@
|
||||||
|
// The wayBetter panel: `createPanel(site)` gives an app its own tab in the shell (settings, themes
|
||||||
|
// and the Theme Builder, plugins and custom CSS, the Store, Make, accounts, Power User, backup and
|
||||||
|
// sync, developer mode, updates, a settings search). The app describes itself (`PanelSite`): its
|
||||||
|
// brand and home page, its theme catalog and the miniature its themes are previewed in, its own
|
||||||
|
// sections (X: Tweaks, Drafts, My Space), Make's examples and docs, its languages. Each built-in
|
||||||
|
// section shows only when the app serves what it needs. Styles come with the components.
|
||||||
|
//
|
||||||
|
// const Panel = createPanel({ brand: { name: 'wayBetter', logo }, home, themes, sections: [...] });
|
||||||
|
// createShell({ ..., panel: { id: 'app', title: 'wayBetter', component: Panel } }, options);
|
||||||
|
//
|
||||||
|
// The panel speaks through the shell frame (its native API, language and site): call `createShell`
|
||||||
|
// before the panel renders.
|
||||||
|
|
||||||
|
import type { ComponentType } from 'react';
|
||||||
|
import Panel from './Panel.tsx';
|
||||||
|
import { configurePanel, type PanelSite } from './site.ts';
|
||||||
|
|
||||||
|
/** The component the shell frame shows as the app's tab (`ShellSite.panel.component`). */
|
||||||
|
export type PanelComponent = ComponentType<{ section?: { name: string; nonce: number } }>;
|
||||||
|
|
||||||
|
/** Sets the panel's site for every panel module and returns the panel's root component. Call once. */
|
||||||
|
export function createPanel(site: PanelSite): PanelComponent {
|
||||||
|
configurePanel(site);
|
||||||
|
return Panel;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type {
|
||||||
|
PanelSite, PanelSection, PanelHome, PanelThemes, PanelMake, PanelLanguage, PanelLanguages, PluginExample, FeatureGroup, SectionProps, Notify, BuiltinSection,
|
||||||
|
} from './site.ts';
|
||||||
|
export { BUILTIN_SECTIONS, panelSite } from './site.ts';
|
||||||
|
export { NAV_ICONS, navEntries } from './nav.ts';
|
||||||
|
// Building blocks for the app's own sections: the panel's controls and the generic pieces.
|
||||||
|
export {
|
||||||
|
Badge, Button, ChipList, ColorField, EmptyState, InputRow, Row, SearchField, SearchProvider, Section, Segmented, Select, Slider, Stepper, Toggle, useSettingsQuery,
|
||||||
|
type Option,
|
||||||
|
} from './controls.tsx';
|
||||||
|
export { FeatureGroups, useFeatures } from './FeatureToggles.tsx';
|
||||||
|
export { compareLines } from './compare.ts';
|
||||||
72
packages/shell/src/panel/make.css
Normal file
72
packages/shell/src/panel/make.css
Normal file
|
|
@ -0,0 +1,72 @@
|
||||||
|
/* "Make" section: examples, UI kit gallery, theme API explorer, bundled docs. Panel tokens only. */
|
||||||
|
.bmk { display: flex; flex-direction: column; gap: 4px; }
|
||||||
|
.bmk-intro { margin: 0 2px 14px; color: var(--c-text-2); }
|
||||||
|
.bmk-intro p { margin: 0 0 10px; max-width: 70ch; line-height: 1.55; }
|
||||||
|
.bmk-muted, .bmk-intro .bmk-muted { color: var(--c-muted); font-size: 12px; }
|
||||||
|
.bmk-commands { display: grid; gap: 6px; margin: 0 0 10px; padding: 0; list-style: none; }
|
||||||
|
.bmk-commands li { display: grid; grid-template-columns: minmax(120px, 190px) 1fr auto; align-items: center; gap: 10px; padding-block: 6px; padding-inline: 12px 6px; border: 1px solid var(--c-line-soft); border-radius: 10px; background: var(--c-card); }
|
||||||
|
.bmk-commands li > span { color: var(--c-muted); font-size: 12px; }
|
||||||
|
.bmk-commands li > code { overflow-x: auto; white-space: nowrap; background: transparent; border: 0; padding: 0; color: var(--c-text); scrollbar-width: none; }
|
||||||
|
@container panel (max-width: 560px) { .bmk-commands li { grid-template-columns: 1fr auto; } .bmk-commands li > span { grid-column: 1 / -1; } }
|
||||||
|
.bmk-tabs { margin: 0 2px 16px; }
|
||||||
|
.bmk-doc-link { display: inline; padding: 0; border: 0; background: none; color: var(--c-accent); font: inherit; cursor: pointer; text-decoration: underline; text-decoration-color: rgb(var(--c-accent-rgb) / .35); text-underline-offset: 2px; }
|
||||||
|
.bmk-doc-link:hover { text-decoration-color: currentColor; }
|
||||||
|
|
||||||
|
/* Example picker + editor */
|
||||||
|
.bmk-examples { display: grid; grid-template-columns: repeat(auto-fill, minmax(190px, 1fr)); gap: 8px; padding: 10px; }
|
||||||
|
.bmk-example { display: flex; flex-direction: column; gap: 4px; padding: 10px 12px; border: 1px solid var(--c-line-soft); border-radius: 10px; background: var(--c-field); text-align: start; cursor: pointer; transition: border-color .15s, background-color .15s; }
|
||||||
|
.bmk-example strong { font-size: 12.5px; font-weight: 620; }
|
||||||
|
.bmk-example span { color: var(--c-muted); font-size: 11.5px; line-height: 1.45; }
|
||||||
|
.bmk-example:hover { border-color: var(--c-line-strong); }
|
||||||
|
.bmk-example.is-on { border-color: rgb(var(--c-accent-rgb) / .6); background: var(--c-accent-soft); }
|
||||||
|
.bmk-editor textarea { min-height: 260px; }
|
||||||
|
.bmk-editor .bt-code-bar { flex-wrap: wrap; }
|
||||||
|
.bmk-file { display: flex; align-items: center; gap: 8px; margin-inline-end: auto; color: var(--c-faint); font-size: 11.5px; }
|
||||||
|
.bmk-file .bt-input { width: 220px; height: 28px; padding: 0 8px; font: 12px var(--f-mono); }
|
||||||
|
.bmk-file .bt-input[aria-invalid='true'] { border-color: var(--c-danger); }
|
||||||
|
.bmk-warnings { margin: 0; padding-block: 10px; padding-inline: 30px 14px; border-top: 1px solid var(--c-line-soft); color: var(--c-warn); font-size: 12px; }
|
||||||
|
.bmk-steps { margin: 0; padding-block: 12px 14px; padding-inline: 34px 16px; border-top: 1px solid var(--c-line-soft); color: var(--c-text-2); font-size: 12px; line-height: 1.6; }
|
||||||
|
|
||||||
|
/* UI kit gallery */
|
||||||
|
.bmk-kit { display: grid; }
|
||||||
|
.bmk-kit-row { display: grid; grid-template-columns: 140px 1fr; align-items: center; gap: 12px; padding: 9px 12px; }
|
||||||
|
.bmk-kit-row + .bmk-kit-row { border-top: 1px solid var(--c-line-soft); }
|
||||||
|
.bmk-kit-row .bt-btn { justify-content: center; }
|
||||||
|
.bmk-kit-code { overflow-x: auto; white-space: nowrap; scrollbar-width: thin; }
|
||||||
|
.bmk-kit-result { grid-column: 2; color: var(--c-ok); font: 11.5px var(--f-mono); }
|
||||||
|
@container panel (max-width: 520px) { .bmk-kit-row { grid-template-columns: 1fr; } .bmk-kit-result { grid-column: 1; } }
|
||||||
|
|
||||||
|
/* Theme explorer */
|
||||||
|
.bmk-facts { display: flex; flex-wrap: wrap; gap: 6px 14px; padding: 12px 14px; color: var(--c-text-2); font: 11.5px var(--f-mono); }
|
||||||
|
.bmk-facts b { color: var(--c-muted); font-weight: 500; margin-inline-end: 4px; }
|
||||||
|
.bmk-swatches { display: grid; grid-template-columns: repeat(auto-fill, minmax(210px, 1fr)); gap: 6px; padding: 0 10px 12px; }
|
||||||
|
.bmk-swatch { display: flex; align-items: center; gap: 10px; padding: 7px 9px; border: 1px solid var(--c-line-soft); border-radius: 10px; background: var(--c-field); text-align: start; cursor: copy; }
|
||||||
|
.bmk-swatch:hover { border-color: var(--c-line-strong); }
|
||||||
|
.bmk-chip { flex: 0 0 30px; height: 30px; border-radius: 8px; box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .12), 0 0 0 1px rgba(0, 0, 0, .25); }
|
||||||
|
.bmk-swatch-text { display: flex; flex-direction: column; min-width: 0; }
|
||||||
|
.bmk-swatch-text b { font-size: 12px; font-weight: 600; }
|
||||||
|
.bmk-swatch-text code { align-self: flex-start; margin: 2px 0; }
|
||||||
|
.bmk-swatch-text small { color: var(--c-muted); font-size: 11px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||||
|
.bmk-fonts { display: grid; }
|
||||||
|
.bmk-font { display: grid; gap: 4px; padding: 10px 14px; border-bottom: 1px solid var(--c-line-soft); }
|
||||||
|
.bmk-font > div { display: flex; flex-wrap: wrap; align-items: baseline; gap: 8px; }
|
||||||
|
.bmk-font b { font-size: 12px; }
|
||||||
|
.bmk-font p { margin: 0; font-size: 17px; color: var(--c-text); }
|
||||||
|
.bmk-pre { margin: 10px; max-height: 320px; overflow: auto; }
|
||||||
|
.bmk-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 0 10px 12px; }
|
||||||
|
|
||||||
|
/* Bundled docs */
|
||||||
|
.bmk-docs .bmk-actions { padding: 0 2px 12px; }
|
||||||
|
.bmk-doc { max-width: 78ch; color: var(--c-text-2); line-height: 1.6; }
|
||||||
|
.bmk-doc h2, .bmk-doc h3, .bmk-doc h4, .bmk-doc h5 { margin: 22px 0 8px; color: var(--c-text); letter-spacing: -.01em; scroll-margin-top: 12px; }
|
||||||
|
.bmk-doc h2 { font-size: 18px; margin-top: 4px; }
|
||||||
|
.bmk-doc h3 { font-size: 14.5px; }
|
||||||
|
.bmk-doc h4, .bmk-doc h5 { font-size: 13px; }
|
||||||
|
.bmk-doc p, .bmk-doc ul, .bmk-doc ol { margin: 0 0 10px; }
|
||||||
|
.bmk-doc ul, .bmk-doc ol { padding-inline-start: 20px; }
|
||||||
|
.bmk-doc li + li { margin-top: 4px; }
|
||||||
|
.bmk-doc .bt-snippet { margin: 8px 0 14px; }
|
||||||
|
.bmk-doc-table { overflow-x: auto; margin: 6px 0 14px; border: 1px solid var(--c-line-soft); border-radius: 10px; }
|
||||||
|
.bmk-doc table { width: 100%; border-collapse: collapse; font-size: 12px; }
|
||||||
|
.bmk-doc th, .bmk-doc td { padding: 7px 10px; text-align: start; vertical-align: top; border-top: 1px solid var(--c-line-soft); }
|
||||||
|
.bmk-doc th { border-top: 0; background: var(--c-chrome); color: var(--c-text); font-weight: 600; }
|
||||||
87
packages/shell/src/panel/makeModel.ts
Normal file
87
packages/shell/src/panel/makeModel.ts
Normal file
|
|
@ -0,0 +1,87 @@
|
||||||
|
// "Make" section data every app shares: the `npm create waybetter` commands, the UI kit gallery's
|
||||||
|
// calls, and the plugin header rules the Plugins list uses. The example plugins, the example theme
|
||||||
|
// and the bundled docs are the app's (`PanelSite.make`). Pure (no React, no Tauri).
|
||||||
|
|
||||||
|
import { t } from '../frame/i18n.ts';
|
||||||
|
|
||||||
|
export type { PluginExample } from './site.ts';
|
||||||
|
|
||||||
|
/** `npm create waybetter` commands shown in the section (the framework's create-waybetter). */
|
||||||
|
export const CREATE_COMMANDS = [
|
||||||
|
{ get label() { return t('wb.make.create.plugin'); }, command: 'npm create waybetter plugin -- --name "My Plugin"' },
|
||||||
|
{ get label() { return t('wb.make.create.pluginTs'); }, command: 'npm create waybetter plugin -- --name "My Plugin" --ts' },
|
||||||
|
{ get label() { return t('wb.make.create.theme'); }, command: 'npm create waybetter theme -- --name "My Theme" --accent "#3ddc97"' },
|
||||||
|
{ get label() { return t('wb.make.create.app'); }, command: 'npm create waybetter app -- --site kick.com' },
|
||||||
|
];
|
||||||
|
|
||||||
|
/** One UI kit call in the gallery: the code shown is the call the button makes. */
|
||||||
|
export type KitDemo = { id: string; label: string; kind: 'toast' | 'alert' | 'confirm' | 'prompt' | 'dialog'; code: string };
|
||||||
|
|
||||||
|
export const KIT_DEMOS: KitDemo[] = [
|
||||||
|
{ id: 'toast', get label() { return t('wb.make.kit.toast'); }, kind: 'toast', code: "ui.toast('Link copied');" },
|
||||||
|
{ id: 'toast-success', get label() { return t('wb.make.kit.toastSuccess'); }, kind: 'toast', code: "ui.toast('Saved', { tone: 'success' });" },
|
||||||
|
{ id: 'toast-action', get label() { return t('wb.make.kit.toastAction'); }, kind: 'toast', code: "ui.toast('Post hidden', { tone: 'warning', action: { label: 'Undo', onClick: undo } });" },
|
||||||
|
{ id: 'toast-danger', get label() { return t('wb.make.kit.toastDanger'); }, kind: 'toast', code: "ui.toast('Could not save', { tone: 'danger' });" },
|
||||||
|
{ id: 'alert', get label() { return t('wb.make.kit.alert'); }, kind: 'alert', code: "await ui.alert({ title: 'Exported', message: 'Your list was saved to Downloads.', tone: 'success' });" },
|
||||||
|
{ id: 'confirm', get label() { return t('wb.make.kit.confirm'); }, kind: 'confirm', code: "await ui.confirm({ title: 'Delete this note?', message: 'This cannot be undone.', confirmLabel: 'Delete', danger: true });" },
|
||||||
|
{ id: 'prompt', get label() { return t('wb.make.kit.prompt'); }, kind: 'prompt', code: "await ui.prompt({ title: 'Rename list', label: 'Name', value: 'Reading', validate: v => v.trim().length < 3 ? 'Use at least 3 characters.' : null });" },
|
||||||
|
{ id: 'dialog', get label() { return t('wb.make.kit.dialog'); }, kind: 'dialog', code: "ui.dialog({ title: 'My plugin', message: 'What should be hidden?', content: body => body.append(h('label', { class: 'wb-check' }, h('input', { type: 'checkbox' }), 'Hide trends')), actions: [{ label: 'Cancel' }, { label: 'Save', tone: 'primary', default: true }] });" },
|
||||||
|
];
|
||||||
|
|
||||||
|
/** A color role's CSS variable: `onAccent` -> `--wb-on-accent` (the names `themeVars` writes). */
|
||||||
|
export const cssVarOf = (role: string) => `--wb-${role.replace(/[A-Z]/g, c => `-${c.toLowerCase()}`)}`;
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Plugin header: the same rules as the plugin store (waybetter-host `plugins::parse_meta` and
|
||||||
|
// `valid_file_name`), so the editor shows what the Plugins list will show.
|
||||||
|
|
||||||
|
export const PLUGIN_SUFFIX = '.plugin.js';
|
||||||
|
|
||||||
|
export type PluginMeta = { file: string; name: string; description: string; version: string; author: string; header: boolean };
|
||||||
|
|
||||||
|
export function parsePluginHeader(file: string, source: string): PluginMeta {
|
||||||
|
const meta: PluginMeta = { file, name: file.endsWith(PLUGIN_SUFFIX) ? file.slice(0, -PLUGIN_SUFFIX.length) : file, description: '', version: '', author: '', header: false };
|
||||||
|
const trimmed = source.replace(/^+/, '').trimStart();
|
||||||
|
if (!trimmed.startsWith('/**')) return meta;
|
||||||
|
const body = trimmed.slice(3);
|
||||||
|
const end = body.indexOf('*/');
|
||||||
|
if (end < 0) return meta;
|
||||||
|
meta.header = true;
|
||||||
|
for (const raw of body.slice(0, end).split('\n')) {
|
||||||
|
const line = raw.trim().replace(/^\*+/, '').trim();
|
||||||
|
if (!line.startsWith('@')) continue;
|
||||||
|
const rest = line.slice(1);
|
||||||
|
const space = /\s/.exec(rest);
|
||||||
|
const key = space ? rest.slice(0, space.index) : rest;
|
||||||
|
const value = [...(space ? rest.slice(space.index) : '').trim()].filter(ch => !/\p{Cc}/u.test(ch)).slice(0, 300).join('');
|
||||||
|
if (key === 'name' && value) meta.name = value;
|
||||||
|
else if (key === 'description') meta.description = value;
|
||||||
|
else if (key === 'version') meta.version = value;
|
||||||
|
else if (key === 'author') meta.author = value;
|
||||||
|
}
|
||||||
|
return meta;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A bare `name.plugin.js` the plugins folder accepts. */
|
||||||
|
export function validPluginFileName(file: string): boolean {
|
||||||
|
return file.length > PLUGIN_SUFFIX.length && file.length <= 128 && file.endsWith(PLUGIN_SUFFIX) && !file.startsWith('.') && /^[A-Za-z0-9_. -]+$/.test(file);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `Hide Trends` -> `hide-trends.plugin.js`. */
|
||||||
|
export function pluginFileFor(name: string): string {
|
||||||
|
const slug = name.normalize('NFKD').replace(/\p{M}/gu, '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 48).replace(/-+$/, '');
|
||||||
|
return `${slug || 'my-plugin'}${PLUGIN_SUFFIX}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** What the editor warns about before the file is copied into the plugins folder. */
|
||||||
|
export function pluginWarnings(meta: PluginMeta, source: string): string[] {
|
||||||
|
const warnings: string[] = [];
|
||||||
|
if (!meta.header) warnings.push(t('wb.make.warn.header'));
|
||||||
|
else for (const tag of ['name', 'description', 'version', 'author'] as const) {
|
||||||
|
if (tag === 'name' ? meta.name === meta.file.replace(PLUGIN_SUFFIX, '') && !/@name\s+\S/.test(source) : !meta[tag]) warnings.push(t('wb.make.warn.tag', { tag: `@${tag}` }));
|
||||||
|
}
|
||||||
|
if (meta.header && !/^\s*\*?\s*@permissions\b/m.test(source)) warnings.push(t('wb.make.warn.permissions'));
|
||||||
|
if (!/module\.exports\s*=|exports\.default\s*=/.test(source)) warnings.push(t('wb.make.warn.export'));
|
||||||
|
if (!/\bstop\s*\(/.test(source)) warnings.push(t('wb.make.warn.stop'));
|
||||||
|
return warnings;
|
||||||
|
}
|
||||||
89
packages/shell/src/panel/markdown.ts
Normal file
89
packages/shell/src/panel/markdown.ts
Normal file
|
|
@ -0,0 +1,89 @@
|
||||||
|
// Markdown for the bundled docs (PLUGINS.md, THEMES.md), parsed into plain data: headings,
|
||||||
|
// paragraphs, lists, tables, fenced code and inline code/bold/links. Pure; MarkdownDoc.tsx renders
|
||||||
|
// it as React text, never as HTML.
|
||||||
|
|
||||||
|
export type Block =
|
||||||
|
| { kind: 'heading'; level: number; text: string }
|
||||||
|
| { kind: 'paragraph'; text: string }
|
||||||
|
| { kind: 'list'; ordered: boolean; items: string[] }
|
||||||
|
| { kind: 'table'; head: string[]; rows: string[][] }
|
||||||
|
| { kind: 'code'; lang: string; text: string };
|
||||||
|
|
||||||
|
export type DocLink = { doc?: string; anchor?: string; url?: string };
|
||||||
|
|
||||||
|
/** GitHub-style heading anchors: `## Matching the theme: \`api.theme\`` -> `matching-the-theme-apitheme`. */
|
||||||
|
export const anchorOf = (text: string) => text.toLowerCase().replace(/[`*]/g, '').replace(/[^\p{L}\p{N} -]/gu, '').trim().replace(/ /g, '-');
|
||||||
|
|
||||||
|
const cells = (line: string) => line.trim().replace(/^\||\|$/g, '').split(/(?<!\\)\|/).map(cell => cell.trim().replace(/\\\|/g, '|'));
|
||||||
|
|
||||||
|
export function parseMarkdown(source: string): Block[] {
|
||||||
|
const lines = source.replace(/\r\n?/g, '\n').split('\n');
|
||||||
|
const blocks: Block[] = [];
|
||||||
|
for (let i = 0; i < lines.length;) {
|
||||||
|
const line = lines[i]!;
|
||||||
|
const fence = /^```(\w*)/.exec(line);
|
||||||
|
if (fence) {
|
||||||
|
const body: string[] = [];
|
||||||
|
for (i += 1; i < lines.length && !lines[i]!.startsWith('```'); i += 1) body.push(lines[i]!);
|
||||||
|
blocks.push({ kind: 'code', lang: fence[1] ?? '', text: body.join('\n') });
|
||||||
|
i += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const heading = /^(#{1,4})\s+(.*)$/.exec(line);
|
||||||
|
if (heading) { blocks.push({ kind: 'heading', level: heading[1]!.length, text: heading[2]! }); i += 1; continue; }
|
||||||
|
if (/^\s*\|/.test(line) && /^\s*\|[\s:|-]+\|\s*$/.test(lines[i + 1] ?? '')) {
|
||||||
|
const head = cells(line);
|
||||||
|
const rows: string[][] = [];
|
||||||
|
for (i += 2; i < lines.length && /^\s*\|/.test(lines[i]!); i += 1) rows.push(cells(lines[i]!));
|
||||||
|
blocks.push({ kind: 'table', head, rows });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const item = /^(\s*)([-*]|\d+\.)\s+(.*)$/.exec(line);
|
||||||
|
if (item) {
|
||||||
|
const ordered = /\d/.test(item[2]!);
|
||||||
|
const items: string[] = [];
|
||||||
|
while (i < lines.length) {
|
||||||
|
const next = /^(\s*)([-*]|\d+\.)\s+(.*)$/.exec(lines[i]!);
|
||||||
|
if (next) { items.push(next[3]!); i += 1; continue; }
|
||||||
|
// Continuation lines are indented under the item.
|
||||||
|
if (/^\s{2,}\S/.test(lines[i]!) && items.length) { items[items.length - 1] += ` ${lines[i]!.trim()}`; i += 1; continue; }
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
blocks.push({ kind: 'list', ordered, items });
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (!line.trim()) { i += 1; continue; }
|
||||||
|
// The first line always belongs to the paragraph (e.g. a lone `|` line that is not a table).
|
||||||
|
const text: string[] = [line.trim()];
|
||||||
|
for (i += 1; i < lines.length && lines[i]!.trim() && !/^(```|#{1,4}\s|\s*\||\s*([-*]|\d+\.)\s)/.test(lines[i]!); i += 1) text.push(lines[i]!.trim());
|
||||||
|
blocks.push({ kind: 'paragraph', text: text.join(' ') });
|
||||||
|
}
|
||||||
|
return blocks;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Where a Markdown link goes: another bundled doc, an anchor in this one, or the web. */
|
||||||
|
export function resolveLink(href: string, docs: readonly string[]): DocLink | null {
|
||||||
|
if (href.startsWith('#')) return { anchor: href.slice(1) };
|
||||||
|
const local = /^\.?\/?([\w.-]+\.md)(?:#(.*))?$/.exec(href);
|
||||||
|
if (local && docs.includes(local[1]!)) return { doc: local[1], anchor: local[2] };
|
||||||
|
if (/^https:\/\//.test(href)) return { url: href };
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Inline = { kind: 'text'; text: string } | { kind: 'code'; text: string } | { kind: 'bold'; text: string } | { kind: 'link'; text: string; href: string };
|
||||||
|
|
||||||
|
/** Inline code, **bold** and [links](href); everything else is text. */
|
||||||
|
export function inlineTokens(text: string): Inline[] {
|
||||||
|
const out: Inline[] = [];
|
||||||
|
const pattern = /`([^`]+)`|\*\*([^*]+)\*\*|\[([^\]]+)\]\(([^)\s]+)\)/g;
|
||||||
|
let last = 0;
|
||||||
|
for (const match of text.matchAll(pattern)) {
|
||||||
|
if (match.index! > last) out.push({ kind: 'text', text: text.slice(last, match.index) });
|
||||||
|
if (match[1] !== undefined) out.push({ kind: 'code', text: match[1] });
|
||||||
|
else if (match[2] !== undefined) out.push({ kind: 'bold', text: match[2] });
|
||||||
|
else out.push({ kind: 'link', text: match[3]!, href: match[4]! });
|
||||||
|
last = match.index! + match[0].length;
|
||||||
|
}
|
||||||
|
if (last < text.length) out.push({ kind: 'text', text: text.slice(last) });
|
||||||
|
return out;
|
||||||
|
}
|
||||||
56
packages/shell/src/panel/nav.ts
Normal file
56
packages/shell/src/panel/nav.ts
Normal file
|
|
@ -0,0 +1,56 @@
|
||||||
|
// The panel's navigation: the built-in sections (shown when the app serves what each needs) and the
|
||||||
|
// app's own, in the app's order. Pure (no JSX), unit-tested under node.
|
||||||
|
import type { ComponentType } from 'react';
|
||||||
|
import { hasFeature, site } from '../frame/site.ts';
|
||||||
|
import { BUILTIN_SECTIONS, panelSite, type BuiltinSection, type PanelSite, type SectionProps } from './site.ts';
|
||||||
|
|
||||||
|
/** Nav icons of the built-in sections (16x16 stroke paths). */
|
||||||
|
export const NAV_ICONS: Record<BuiltinSection, string> = {
|
||||||
|
home: 'M2.5 7.2 8 2.8l5.5 4.4V13H9.8V9.6H6.2V13H2.5z',
|
||||||
|
themes: 'M8 2.5a5.5 5.5 0 1 0 0 11c.9 0 1.2-.6 1.2-1.1 0-.7-.5-.9-.5-1.5 0-.6.5-1 1.1-1h1.2A2.5 2.5 0 0 0 13.5 7.4 5.3 5.3 0 0 0 8 2.5zM5 7.2h.01M7.2 5h.01M10 5.4h.01',
|
||||||
|
builder: 'M3 13l.6-2.6L10.5 3.5l2 2-6.9 6.9zM9 5l2 2M2.5 3.5h3M4 2v3',
|
||||||
|
plugins: 'M6 2.5v3M10 2.5v3M4 5.5h8V8a4 4 0 0 1-8 0zM8 12v1.5',
|
||||||
|
store: 'M2.8 6 3.8 2.8h8.4L13.2 6M2.8 6h10.4v7.2H2.8zM2.8 6a1.7 1.7 0 0 0 3.5 0 1.7 1.7 0 0 0 3.4 0 1.7 1.7 0 0 0 3.5 0M6.7 13.2V10h2.6v3.2',
|
||||||
|
make: 'M5.5 4.5 2.5 8l3 3.5M10.5 4.5l3 3.5-3 3.5M9.2 3 6.8 13',
|
||||||
|
accounts: 'M6 7.5a2.3 2.3 0 1 0 0-4.6 2.3 2.3 0 0 0 0 4.6zM2 13a4 4 0 0 1 8 0M10.5 3.2a2.3 2.3 0 0 1 0 4.4M12 9.5A3.8 3.8 0 0 1 14 13',
|
||||||
|
updates: 'M13 8a5 5 0 1 1-1.5-3.5M13 2.5v2.8h-2.8',
|
||||||
|
settings: 'M2.5 4.5h11v8h-11zM2.5 7h11M4.5 5.8h.01M6 5.8h.01',
|
||||||
|
power: 'M2.5 3h3v10h-3zM6.5 3h3v10h-3zM10.5 3h3v10h-3z',
|
||||||
|
backup: 'M8 2.5v7M5 6.5l3 3 3-3M3 10.5v2h10v-2',
|
||||||
|
developer: 'M5.5 5 2.5 8l3 3M10.5 5l3 3-3 3',
|
||||||
|
};
|
||||||
|
const BUILTIN_LABELS: Record<BuiltinSection, string> = {
|
||||||
|
home: 'wb.panel.section.home', themes: 'wb.panel.section.themes', builder: 'wb.panel.section.builder', plugins: 'wb.panel.section.plugins',
|
||||||
|
store: 'wb.panel.section.store', make: 'wb.panel.section.make', accounts: 'wb.panel.section.accounts', power: 'wb.panel.section.power',
|
||||||
|
settings: 'wb.panel.section.settings', backup: 'wb.panel.section.backup', developer: 'wb.panel.section.developer', updates: 'wb.panel.section.updates',
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Whether the app serves what a built-in section needs. */
|
||||||
|
function available(id: BuiltinSection, panel: PanelSite): boolean {
|
||||||
|
switch (id) {
|
||||||
|
case 'themes':
|
||||||
|
case 'builder': return !!panel.themes;
|
||||||
|
case 'store': return !!panel.store && !!panel.themes;
|
||||||
|
case 'make': return !!panel.make;
|
||||||
|
case 'power': return !!site().deck;
|
||||||
|
case 'backup': return !!panel.backup;
|
||||||
|
case 'developer': return hasFeature('developer');
|
||||||
|
case 'updates': return !!panel.updates;
|
||||||
|
default: return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export type NavEntry = { id: string; icon: string; label(t: (key: string) => string): string; component: ComponentType<SectionProps> | null };
|
||||||
|
|
||||||
|
/** The panel's sections in nav order: the built-in ones the app serves and the app's own. */
|
||||||
|
export function navEntries(panel: PanelSite = panelSite()): NavEntry[] {
|
||||||
|
const builtin = BUILTIN_SECTIONS.filter(id => available(id, panel));
|
||||||
|
const own = panel.sections ?? [];
|
||||||
|
const known = new Set<string>([...builtin, ...own.map(section => section.id)]);
|
||||||
|
const order = [...(panel.order ?? []).filter(id => known.has(id)), ...[...known].filter(id => !(panel.order ?? []).includes(id))];
|
||||||
|
return order.map(id => {
|
||||||
|
const custom = own.find(section => section.id === id);
|
||||||
|
if (custom) return { id, icon: custom.icon, label: () => custom.label(), component: custom.component };
|
||||||
|
return { id, icon: NAV_ICONS[id as BuiltinSection], label: t => t(BUILTIN_LABELS[id as BuiltinSection]), component: null };
|
||||||
|
});
|
||||||
|
}
|
||||||
388
packages/shell/src/panel/panel.css
Normal file
388
packages/shell/src/panel/panel.css
Normal file
|
|
@ -0,0 +1,388 @@
|
||||||
|
/* wayBetter panel. Night Ink + Geist; narrow split pane first, side rail from 720px.
|
||||||
|
One grammar for every setting: section header, a card of rows, label left, control right. */
|
||||||
|
.btp {
|
||||||
|
/* Follows the active theme like the shell chrome (`--wb-p-*` / `--wb-f-*`, src/shell/themeStore.ts). */
|
||||||
|
--c-ground: var(--wb-p-ground, #07080c); --c-chrome: var(--wb-p-chrome, #0b0d13); --c-card: var(--wb-p-card, #0d1017); --c-field: var(--wb-p-field, #131722); --c-raise: var(--wb-p-raise, #1a1f2d);
|
||||||
|
--c-line: var(--wb-p-line, #20263a); --c-line-soft: var(--wb-p-line-soft, #171b28); --c-line-strong: var(--wb-p-line-strong, #2d3550);
|
||||||
|
--c-text: var(--wb-p-text, #eef0f7); --c-text-2: var(--wb-p-text-2, #c9cfe3); --c-muted: var(--wb-p-muted, #8e95ab); --c-faint: var(--wb-p-faint, #5f667c);
|
||||||
|
--c-accent: var(--wb-p-accent, #7b9cff); --c-accent-ink: var(--wb-p-accent-ink, #0a0f22); --c-accent-rgb: var(--wb-p-accent-rgb, 123 156 255); --c-accent-soft: rgb(var(--c-accent-rgb) / .16);
|
||||||
|
--c-text-rgb: var(--wb-p-text-rgb, 238 240 247); --c-popover: var(--wb-p-popover, #10131c); --c-thumb: var(--wb-p-thumb, linear-gradient(180deg, #252b3d, #1c2130)); --c-track: var(--wb-p-track, #1c2130); --c-knob: var(--wb-p-knob, #aeb4c7);
|
||||||
|
color-scheme: var(--wb-c-scheme, dark);
|
||||||
|
--c-danger: #ff5c6c; --c-ok: #3ddc97; --c-warn: #f6c453;
|
||||||
|
--c-brush: linear-gradient(90deg, #4f6bff, #22d3ee 55%, #a855f7);
|
||||||
|
--f-ui: var(--wb-f-chrome, 'Geist Variable', 'Segoe UI', system-ui, sans-serif); --f-mono: var(--wb-f-mono, 'Geist Mono Variable', ui-monospace, Consolas, monospace);
|
||||||
|
--ease: cubic-bezier(.2, .7, .2, 1);
|
||||||
|
position: relative; height: 100%; display: grid; grid-template-rows: auto auto 1fr; overflow: hidden;
|
||||||
|
background: var(--c-ground); color: var(--c-text); font: 400 13px/1.45 var(--f-ui); letter-spacing: -.003em;
|
||||||
|
-webkit-font-smoothing: antialiased; font-feature-settings: 'ss01', 'cv11';
|
||||||
|
}
|
||||||
|
.btp-root { position: absolute; inset: 0; container-type: inline-size; container-name: panel; }
|
||||||
|
.btp *, .btp *::before, .btp *::after { box-sizing: border-box; }
|
||||||
|
.btp button { font: inherit; color: inherit; }
|
||||||
|
.btp code { padding: 1px 5px; border-radius: 5px; background: var(--c-field); border: 1px solid var(--c-line-soft); font: 11.5px var(--f-mono); color: var(--c-text-2); }
|
||||||
|
.btp mark { background: var(--c-accent-soft); color: var(--c-text); border-radius: 3px; box-shadow: 0 0 0 1px rgb(var(--c-accent-rgb) / .35); }
|
||||||
|
.btp :focus-visible { outline: 2px solid var(--c-accent); outline-offset: 2px; }
|
||||||
|
.btp :is(.bt-search, .bt-inputrow) input:focus-visible, .btp .bt-hex:focus-visible, .btp .bt-code textarea:focus-visible, .btp .btp-input:focus-visible, .btp .bt-input:focus-visible { outline: none; }
|
||||||
|
|
||||||
|
/* Header: brand + settings search */
|
||||||
|
.btp-head { position: relative; display: flex; align-items: center; gap: 12px; padding: 12px 16px; }
|
||||||
|
.btp-head::after { content: ''; position: absolute; left: 0; right: 0; bottom: 0; height: 1px; background: var(--c-brush); opacity: .38; }
|
||||||
|
.btp-brand { display: flex; align-items: center; gap: 9px; flex: 0 0 auto; }
|
||||||
|
.btp-brand img { border-radius: 6px; box-shadow: 0 0 0 1px rgba(255, 255, 255, .06); }
|
||||||
|
.btp-brand strong { font-size: 13.5px; font-weight: 650; letter-spacing: -.015em; }
|
||||||
|
.btp-head .bt-search { margin-inline-start: auto; width: min(320px, 100%); }
|
||||||
|
|
||||||
|
/* Section nav: a scrolling strip in a narrow pane, a rail in a wide one */
|
||||||
|
.btp-nav { display: flex; gap: 2px; padding: 8px 10px; overflow-x: auto; scrollbar-width: none; border-bottom: 1px solid var(--c-line-soft); background: var(--c-chrome); }
|
||||||
|
.btp-nav::-webkit-scrollbar { display: none; }
|
||||||
|
.btp-nav button { position: relative; flex: 0 0 auto; display: flex; align-items: center; gap: 7px; height: 30px; padding: 0 10px; border: 0; border-radius: 8px; background: transparent; color: var(--c-muted); font-weight: 520; cursor: pointer; transition: color .15s, background-color .15s; }
|
||||||
|
.btp-nav button svg { opacity: .8; }
|
||||||
|
.btp-nav button:hover { color: var(--c-text); background: var(--c-field); }
|
||||||
|
.btp-nav button.is-on { color: var(--c-text); background: var(--c-raise); }
|
||||||
|
.btp-nav button.is-on svg { color: var(--c-accent); opacity: 1; }
|
||||||
|
|
||||||
|
.btp-body { overflow-y: auto; scrollbar-width: thin; scrollbar-color: var(--c-line) transparent; }
|
||||||
|
.btp-page { max-width: 860px; padding: 18px 16px 64px; }
|
||||||
|
.btp-title { margin: 2px 0 14px; font-size: 20px; font-weight: 650; letter-spacing: -.025em; }
|
||||||
|
.btp-title-sub { color: var(--c-muted); font-weight: 450; }
|
||||||
|
|
||||||
|
@container panel (min-width: 720px) {
|
||||||
|
.btp { grid-template-columns: 196px 1fr; grid-template-rows: auto 1fr; }
|
||||||
|
.btp-head { grid-column: 1 / -1; padding: 12px 20px; }
|
||||||
|
.btp-nav { flex-direction: column; gap: 1px; padding: 14px 10px; border-bottom: 0; border-inline-end: 1px solid var(--c-line-soft); overflow: visible; }
|
||||||
|
.btp-nav button { height: 32px; padding: 0 10px; }
|
||||||
|
.btp-nav button.is-on::before { content: ''; position: absolute; inset-inline-start: -10px; top: 8px; bottom: 8px; width: 2px; border-start-start-radius: 0; border-start-end-radius: 2px; border-end-end-radius: 2px; border-end-start-radius: 0; background: var(--c-accent); }
|
||||||
|
.btp-page { padding: 26px 32px 72px; }
|
||||||
|
.btp-title { font-size: 22px; margin-bottom: 18px; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Sections and rows */
|
||||||
|
.bt-section { margin-bottom: 22px; }
|
||||||
|
.bt-section-head { display: flex; align-items: flex-end; gap: 12px; margin: 0 2px 8px; }
|
||||||
|
.bt-section-head > div:first-child { flex: 1; min-width: 0; }
|
||||||
|
.bt-section-head h2 { margin: 0; font-size: 13px; font-weight: 620; letter-spacing: -.005em; }
|
||||||
|
.bt-section-head p { margin: 2px 0 0; color: var(--c-muted); font-size: 12px; line-height: 1.45; max-width: 62ch; }
|
||||||
|
.bt-section-action { flex: 0 0 auto; }
|
||||||
|
.bt-card { border: 1px solid var(--c-line-soft); border-radius: 12px; background: var(--c-card); box-shadow: 0 1px 0 rgba(255, 255, 255, .02) inset; }
|
||||||
|
.bt-card:empty { display: none; }
|
||||||
|
.bt-card > .bt-gallery, .bt-card > .bt-import { padding: 12px; }
|
||||||
|
|
||||||
|
.bt-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: center; gap: 8px 20px; padding: 12px 16px; min-height: 52px; }
|
||||||
|
.bt-row + .bt-row, .bt-card > * + .bt-row { border-top: 1px solid var(--c-line-soft); }
|
||||||
|
.bt-row.is-wide { grid-template-columns: minmax(0, 1fr); }
|
||||||
|
.bt-row-copy { min-width: 0; }
|
||||||
|
.bt-row-label { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; font-size: 13px; font-weight: 540; }
|
||||||
|
.bt-row-hint { margin-top: 2px; color: var(--c-muted); font-size: 12px; line-height: 1.45; max-width: 58ch; }
|
||||||
|
.bt-row-control { display: flex; justify-content: flex-end; min-width: 0; }
|
||||||
|
.bt-row.is-wide .bt-row-control { justify-content: flex-start; }
|
||||||
|
|
||||||
|
@container panel (max-width: 460px) {
|
||||||
|
.bt-row { grid-template-columns: minmax(0, 1fr); }
|
||||||
|
.bt-row-control { justify-content: flex-start; }
|
||||||
|
.bt-row:has(> .bt-row-control > .bt-toggle) { grid-template-columns: minmax(0, 1fr) auto; }
|
||||||
|
.bt-section-head { flex-wrap: wrap; align-items: flex-start; }
|
||||||
|
}
|
||||||
|
|
||||||
|
.bt-inline { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
|
||||||
|
.bt-stack { display: flex; flex-direction: column; gap: 10px; width: 100%; }
|
||||||
|
.bt-badge { display: inline-flex; align-items: center; height: 18px; padding: 0 6px; border-radius: 5px; background: var(--c-field); border: 1px solid var(--c-line-soft); color: var(--c-muted); font: 500 10.5px/1 var(--f-mono); letter-spacing: 0; }
|
||||||
|
.bt-badge.is-accent { color: var(--c-accent); border-color: rgb(var(--c-accent-rgb) / .3); background: var(--c-accent-soft); }
|
||||||
|
.bt-status { color: var(--c-muted); font: 11.5px var(--f-mono); }
|
||||||
|
.bt-status.is-warn { color: var(--c-warn); }
|
||||||
|
.bt-alert { margin: 12px; padding: 10px 12px; border: 1px solid rgba(255, 92, 108, .35); border-radius: 10px; background: rgba(255, 92, 108, .08); font-size: 12px; }
|
||||||
|
|
||||||
|
/* Buttons */
|
||||||
|
.bt-btn { display: inline-flex; align-items: center; justify-content: center; gap: 6px; height: 32px; padding: 0 13px; border: 1px solid var(--c-line); border-radius: 9px; background: var(--c-field); color: var(--c-text); font-weight: 540; white-space: nowrap; cursor: pointer; transition: background-color .15s, border-color .15s, transform .1s; }
|
||||||
|
.bt-btn.is-sm { height: 28px; padding: 0 11px; font-size: 12.5px; border-radius: 8px; }
|
||||||
|
.bt-btn:hover:not(:disabled) { border-color: var(--c-line-strong); background: var(--c-raise); }
|
||||||
|
.bt-btn:active:not(:disabled) { transform: translateY(.5px); }
|
||||||
|
.bt-btn:disabled { opacity: .42; cursor: default; }
|
||||||
|
.bt-btn.is-primary { background: var(--c-text); border-color: var(--c-text); color: var(--c-ground); }
|
||||||
|
.bt-btn.is-primary:hover:not(:disabled) { background: color-mix(in srgb, var(--c-text) 88%, var(--c-ground)); border-color: transparent; }
|
||||||
|
.bt-btn.is-ghost { background: transparent; border-color: transparent; color: var(--c-muted); }
|
||||||
|
.bt-btn.is-ghost:hover:not(:disabled) { background: var(--c-field); color: var(--c-text); border-color: transparent; }
|
||||||
|
.bt-btn.is-danger { background: var(--c-danger); border-color: var(--c-danger); color: #fff; }
|
||||||
|
|
||||||
|
/* Toggle */
|
||||||
|
.bt-toggle { position: relative; flex: 0 0 auto; width: 36px; height: 21px; padding: 0; border: 1px solid var(--c-line-strong); border-radius: 999px; background: var(--c-track); cursor: pointer; transition: background-color .18s var(--ease), border-color .18s; }
|
||||||
|
.bt-toggle-knob { position: absolute; top: 2px; left: 2px; width: 15px; height: 15px; border-radius: 50%; background: var(--c-knob); box-shadow: 0 1px 2px rgba(0, 0, 0, .4); transition: transform .2s var(--ease), background-color .18s; }
|
||||||
|
.bt-toggle.is-on { background: var(--c-accent); border-color: var(--c-accent); }
|
||||||
|
.bt-toggle.is-on .bt-toggle-knob { transform: translateX(15px); background: #fff; }
|
||||||
|
.bt-toggle:disabled { opacity: .45; cursor: default; }
|
||||||
|
|
||||||
|
/* Segmented */
|
||||||
|
.bt-seg { position: relative; display: inline-flex; flex-wrap: nowrap; max-width: 100%; padding: 3px; border: 1px solid var(--c-line); border-radius: 10px; background: var(--c-ground); box-shadow: inset 0 1px 2px rgba(0, 0, 0, .35); isolation: isolate; }
|
||||||
|
.bt-seg-thumb { position: absolute; z-index: -1; top: 3px; bottom: 3px; left: 3px; border-radius: 7px; background: var(--c-thumb); box-shadow: 0 0 0 1px var(--c-line-strong), 0 2px 6px rgba(0, 0, 0, .35); transition: transform .22s var(--ease), width .22s var(--ease), opacity .15s; }
|
||||||
|
.bt-seg button { position: relative; display: inline-flex; align-items: center; gap: 5px; height: 26px; padding: 0 12px; border: 0; border-radius: 7px; background: transparent; color: var(--c-muted); font-weight: 520; white-space: nowrap; cursor: pointer; transition: color .15s; }
|
||||||
|
.bt-seg.is-sm button { padding: 0 10px; font-size: 12.5px; }
|
||||||
|
.bt-seg button:hover { color: var(--c-text); }
|
||||||
|
.bt-seg button.is-on { color: var(--c-text); }
|
||||||
|
.bt-seg button:focus-visible { outline-offset: -1px; }
|
||||||
|
|
||||||
|
/* Select */
|
||||||
|
.bt-select { position: relative; min-width: 150px; }
|
||||||
|
.bt-select-button { display: flex; align-items: center; justify-content: space-between; gap: 10px; width: 100%; height: 32px; padding-block: 0; padding-inline: 11px 10px; border: 1px solid var(--c-line); border-radius: 9px; background: var(--c-field); text-align: start; cursor: pointer; transition: border-color .15s; }
|
||||||
|
.bt-select-button:hover, .bt-select.is-open .bt-select-button { border-color: var(--c-line-strong); }
|
||||||
|
.bt-select-button svg { flex: 0 0 auto; color: var(--c-muted); transition: transform .18s var(--ease); }
|
||||||
|
.bt-select.is-open .bt-select-button svg { transform: rotate(180deg); }
|
||||||
|
.bt-select-value { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
|
.bt-select-list { position: absolute; z-index: 30; top: calc(100% + 6px); inset-inline-end: 0; min-width: 100%; width: max-content; max-width: 300px; max-height: 300px; margin: 0; padding: 5px; overflow-y: auto; list-style: none; border: 1px solid var(--c-line-strong); border-radius: 11px; background: var(--c-popover); box-shadow: 0 18px 50px rgba(0, 0, 0, .6), 0 0 0 1px rgba(0, 0, 0, .4); animation: bt-pop .14s var(--ease); scrollbar-width: thin; }
|
||||||
|
.bt-select-list li { position: relative; display: flex; flex-direction: column; justify-content: center; min-height: 32px; padding-block: 5px; padding-inline: 9px 28px; border-radius: 7px; cursor: pointer; }
|
||||||
|
.bt-select-list li.is-active { background: var(--c-raise); }
|
||||||
|
.bt-select-list li.is-on .bt-select-opt { color: var(--c-text); font-weight: 560; }
|
||||||
|
.bt-select-list li small { color: var(--c-muted); font-size: 11px; }
|
||||||
|
.bt-select-opt { font-size: 13.5px; }
|
||||||
|
.bt-select-check { position: absolute; inset-inline-end: 9px; top: 50%; margin-top: -7px; color: var(--c-accent); }
|
||||||
|
@keyframes bt-pop { from { opacity: 0; transform: translateY(-4px) scale(.98); } }
|
||||||
|
|
||||||
|
/* Slider */
|
||||||
|
.bt-slider { display: flex; align-items: center; gap: 12px; width: min(260px, 100%); }
|
||||||
|
.bt-slider input { --pct: 50%; flex: 1; min-width: 0; height: 20px; margin: 0; background: transparent; appearance: none; -webkit-appearance: none; cursor: pointer; }
|
||||||
|
.bt-slider input::-webkit-slider-runnable-track { height: 4px; border-radius: 4px; background: linear-gradient(90deg, var(--c-accent) var(--pct), var(--c-line) var(--pct)); }
|
||||||
|
.bt-slider input::-webkit-slider-thumb { -webkit-appearance: none; width: 16px; height: 16px; margin-top: -6px; border-radius: 50%; background: #fff; box-shadow: 0 0 0 4px rgb(var(--c-accent-rgb) / .22), 0 1px 3px rgba(0, 0, 0, .5); transition: box-shadow .15s; }
|
||||||
|
.bt-slider input:hover::-webkit-slider-thumb { box-shadow: 0 0 0 6px rgb(var(--c-accent-rgb) / .25), 0 1px 3px rgba(0, 0, 0, .5); }
|
||||||
|
.bt-slider input::-moz-range-track { height: 4px; border-radius: 4px; background: var(--c-line); }
|
||||||
|
.bt-slider input::-moz-range-progress { height: 4px; border-radius: 4px; background: var(--c-accent); }
|
||||||
|
.bt-slider input::-moz-range-thumb { width: 16px; height: 16px; border: 0; border-radius: 50%; background: #fff; }
|
||||||
|
.bt-slider output { flex: 0 0 auto; min-width: 54px; padding: 3px 6px; border: 1px solid var(--c-line-soft); border-radius: 6px; background: var(--c-chrome); color: var(--c-text); font: 500 11.5px var(--f-mono); text-align: center; }
|
||||||
|
|
||||||
|
/* Color */
|
||||||
|
.bt-color { display: flex; flex-wrap: wrap; align-items: center; gap: 7px; }
|
||||||
|
.bt-swatch { position: relative; flex: 0 0 auto; width: 26px; height: 26px; padding: 0; border: 0; border-radius: 50%; background: var(--sw, transparent); box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .14); cursor: pointer; transition: transform .15s var(--ease), box-shadow .15s; }
|
||||||
|
.bt-swatch:hover { transform: scale(1.08); }
|
||||||
|
.bt-swatch.is-on { box-shadow: inset 0 0 0 1px rgba(255, 255, 255, .14), 0 0 0 2px var(--c-card), 0 0 0 4px var(--c-text); }
|
||||||
|
.bt-swatch.is-auto { width: auto; height: 26px; padding: 0 11px; border-radius: 999px; background: var(--c-field); box-shadow: inset 0 0 0 1px var(--c-line); color: var(--c-muted); font-size: 12px; font-weight: 540; }
|
||||||
|
.bt-swatch.is-auto.is-on { color: var(--c-text); box-shadow: inset 0 0 0 1px var(--c-line-strong), 0 0 0 2px var(--c-card), 0 0 0 4px var(--c-text); }
|
||||||
|
.bt-swatch.is-picker { display: inline-grid; place-items: center; overflow: hidden; background: conic-gradient(from 90deg, #ff5f6d, #ffd400, #3ddc97, #1d9bf0, #7856ff, #f91880, #ff5f6d); }
|
||||||
|
.bt-swatch.is-picker.is-on { background: var(--sw); }
|
||||||
|
.bt-swatch.is-picker input { position: absolute; inset: 0; width: 100%; height: 100%; opacity: 0; cursor: pointer; }
|
||||||
|
.bt-hex { width: 84px; height: 28px; margin-inline-start: 2px; padding: 0 8px; border: 1px solid var(--c-line); border-radius: 7px; background: var(--c-field); color: var(--c-text); font: 12px var(--f-mono); outline: none; }
|
||||||
|
.bt-hex:focus { border-color: var(--c-accent); }
|
||||||
|
|
||||||
|
/* Inputs */
|
||||||
|
.bt-input, .btp-input { width: 100%; height: 32px; padding: 0 11px; border: 1px solid var(--c-line); border-radius: 9px; background: var(--c-field); color: var(--c-text); font: inherit; outline: none; transition: border-color .15s, box-shadow .15s; }
|
||||||
|
.bt-input.is-mono { font-family: var(--f-mono); font-size: 12px; }
|
||||||
|
.bt-input:focus, .btp-input:focus { border-color: var(--c-accent); box-shadow: 0 0 0 3px var(--c-accent-soft); }
|
||||||
|
.bt-inputrow { display: flex; width: min(420px, 100%); border: 1px solid var(--c-line); border-radius: 9px; background: var(--c-field); overflow: hidden; transition: border-color .15s, box-shadow .15s; }
|
||||||
|
.bt-inputrow:focus-within { border-color: var(--c-accent); box-shadow: 0 0 0 3px var(--c-accent-soft); }
|
||||||
|
.bt-inputrow input { flex: 1; min-width: 0; height: 32px; padding: 0 11px; border: 0; background: transparent; color: var(--c-text); font: inherit; outline: none; }
|
||||||
|
.bt-inputrow input.is-mono { font: 12px var(--f-mono); }
|
||||||
|
.bt-inputrow button { flex: 0 0 auto; padding: 0 14px; border: 0; border-inline-start: 1px solid var(--c-line); background: var(--c-raise); font-weight: 560; cursor: pointer; }
|
||||||
|
.bt-inputrow button:hover:not(:disabled) { background: var(--c-raise); }
|
||||||
|
.bt-inputrow button:disabled { color: var(--c-faint); cursor: default; }
|
||||||
|
|
||||||
|
.bt-search { position: relative; display: flex; align-items: center; height: 30px; padding-block: 0; padding-inline: 10px 8px; gap: 7px; border: 1px solid var(--c-line); border-radius: 9px; background: var(--c-field); color: var(--c-muted); transition: border-color .15s, box-shadow .15s; }
|
||||||
|
.bt-search:focus-within { border-color: var(--c-accent); box-shadow: 0 0 0 3px var(--c-accent-soft); color: var(--c-text); }
|
||||||
|
.bt-search input { flex: 1; min-width: 0; height: 100%; border: 0; background: transparent; color: var(--c-text); font: inherit; outline: none; }
|
||||||
|
.bt-search input::-webkit-search-cancel-button { display: none; }
|
||||||
|
.bt-search input::placeholder { color: var(--c-faint); }
|
||||||
|
.bt-search button { width: 20px; height: 20px; padding: 0; border: 0; border-radius: 5px; background: var(--c-raise); color: var(--c-muted); line-height: 1; cursor: pointer; }
|
||||||
|
|
||||||
|
/* Chips */
|
||||||
|
.bt-chips { display: flex; flex-wrap: wrap; gap: 6px; margin: 0; padding: 0; list-style: none; }
|
||||||
|
.bt-chip { display: inline-flex; align-items: center; gap: 6px; height: 28px; max-width: 100%; padding-block: 0; padding-inline: 10px 4px; border: 1px solid var(--c-line); border-radius: 999px; background: var(--c-field); font-size: 12.5px; animation: bt-pop .16s var(--ease); }
|
||||||
|
.bt-chip > svg { flex: 0 0 auto; color: var(--c-muted); }
|
||||||
|
.bt-chip span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
|
.bt-chip button { display: grid; place-items: center; width: 20px; height: 20px; padding: 0; border: 0; border-radius: 50%; background: transparent; color: var(--c-muted); cursor: pointer; }
|
||||||
|
.bt-chip button:hover { background: rgba(255, 92, 108, .16); color: var(--c-danger); }
|
||||||
|
.bt-chips-empty { margin: 0; color: var(--c-faint); font-size: 12px; }
|
||||||
|
|
||||||
|
.bt-stepper { display: inline-flex; align-items: center; height: 30px; border: 1px solid var(--c-line); border-radius: 9px; background: var(--c-field); overflow: hidden; }
|
||||||
|
.bt-stepper button { width: 30px; height: 100%; border: 0; background: transparent; color: var(--c-muted); font-size: 15px; cursor: pointer; }
|
||||||
|
.bt-stepper button:hover:not(:disabled) { background: var(--c-raise); color: var(--c-text); }
|
||||||
|
.bt-stepper button:disabled { opacity: .35; cursor: default; }
|
||||||
|
.bt-stepper output { min-width: 42px; text-align: center; font: 500 12.5px var(--f-mono); }
|
||||||
|
.bt-stepper output small { margin-inline-start: 2px; color: var(--c-muted); }
|
||||||
|
|
||||||
|
/* Empty state */
|
||||||
|
.bt-empty { display: flex; flex-direction: column; align-items: center; gap: 6px; padding: 30px 20px 28px; text-align: center; }
|
||||||
|
.bt-empty-icon { display: grid; place-items: center; width: 46px; height: 46px; margin-bottom: 6px; border: 1px solid var(--c-line); border-radius: 13px; background: linear-gradient(180deg, var(--c-raise), var(--c-field)); color: var(--c-muted); }
|
||||||
|
.bt-empty strong { font-size: 13.5px; font-weight: 600; }
|
||||||
|
.bt-empty p { max-width: 44ch; margin: 0; color: var(--c-muted); font-size: 12.5px; line-height: 1.5; }
|
||||||
|
.bt-empty-action { margin-top: 10px; }
|
||||||
|
.bt-snippet { margin: 8px 0 2px; padding: 10px 14px; border: 1px solid var(--c-line-soft); border-radius: 9px; background: var(--c-ground); color: var(--c-text-2); font: 11.5px/1.6 var(--f-mono); text-align: start; white-space: pre; overflow-x: auto; max-width: 100%; }
|
||||||
|
|
||||||
|
/* Code editor (Custom CSS, theme JSON) */
|
||||||
|
.bt-code { display: flex; flex-direction: column; }
|
||||||
|
.bt-code textarea { width: 100%; min-height: 200px; padding: 14px 16px; border: 0; border-radius: 12px 12px 0 0; background: transparent; color: var(--c-text-2); font: 12px/1.65 var(--f-mono); resize: vertical; outline: none; tab-size: 2; }
|
||||||
|
.bt-code.is-compact textarea { min-height: 110px; border: 1px solid var(--c-line); border-bottom: 0; background: var(--c-chrome); }
|
||||||
|
.bt-code-bar { display: flex; align-items: center; gap: 8px; padding-block: 8px; padding-inline: 16px 10px; border-top: 1px solid var(--c-line-soft); }
|
||||||
|
.bt-code.is-compact .bt-code-bar { border: 1px solid var(--c-line); border-radius: 0 0 10px 10px; background: var(--c-chrome); }
|
||||||
|
.bt-code-bar small { margin-inline-end: auto; color: var(--c-faint); font-size: 11.5px; }
|
||||||
|
.bt-code-bar small.is-error { color: var(--c-danger); font-family: var(--f-ui); font-size: 12px; }
|
||||||
|
|
||||||
|
/* Theme gallery */
|
||||||
|
.bt-gallery { display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 12px; }
|
||||||
|
.bt-theme { position: relative; }
|
||||||
|
.bt-theme-hit { display: flex; flex-direction: column; width: 100%; padding: 0; overflow: hidden; border: 1px solid var(--c-line); border-radius: 13px; background: var(--c-chrome); text-align: start; cursor: pointer; transition: border-color .18s, box-shadow .18s, transform .18s var(--ease); }
|
||||||
|
.bt-theme-hit:hover { border-color: var(--c-line-strong); transform: translateY(-1px); box-shadow: 0 10px 30px rgba(0, 0, 0, .35); }
|
||||||
|
.bt-theme.is-on .bt-theme-hit { border-color: var(--c-accent); box-shadow: 0 0 0 1px var(--c-accent), 0 12px 36px rgba(59, 90, 200, .22); }
|
||||||
|
.bt-theme-hit .tp { border-bottom: 1px solid var(--c-line-soft); }
|
||||||
|
.bt-theme-info { display: flex; flex-direction: column; gap: 3px; padding: 11px 13px 12px; }
|
||||||
|
.bt-theme-title { display: flex; align-items: center; gap: 8px; }
|
||||||
|
.bt-theme-title strong { font-size: 13.5px; font-weight: 620; letter-spacing: -.01em; }
|
||||||
|
.bt-theme-check { display: grid; place-items: center; width: 18px; height: 18px; margin-inline-start: auto; border-radius: 50%; background: var(--c-accent); color: var(--c-accent-ink); }
|
||||||
|
.bt-theme-info small { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; color: var(--c-muted); font-size: 12px; line-height: 1.4; }
|
||||||
|
.bt-theme-tags { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 5px; }
|
||||||
|
.bt-theme-tags em { padding: 1px 6px; border-radius: 5px; background: var(--c-field); color: var(--c-muted); font: normal 500 10.5px/16px var(--f-mono); }
|
||||||
|
.bt-theme-tags em.is-accent { color: var(--c-accent); background: var(--c-accent-soft); }
|
||||||
|
.bt-theme-remove { position: absolute; top: 8px; inset-inline-end: 8px; display: grid; place-items: center; width: 26px; height: 26px; padding: 0; border: 1px solid rgba(255, 255, 255, .12); border-radius: 8px; background: rgba(7, 8, 12, .72); color: #fff; backdrop-filter: blur(6px); opacity: 0; cursor: pointer; transition: opacity .15s; }
|
||||||
|
.bt-theme:hover .bt-theme-remove, .bt-theme-remove:focus-visible { opacity: 1; }
|
||||||
|
.bt-theme-remove:hover { background: var(--c-danger); border-color: var(--c-danger); }
|
||||||
|
|
||||||
|
.bt-import { display: grid; grid-template-columns: minmax(0, 1fr); gap: 10px; border-bottom: 1px solid var(--c-line-soft); }
|
||||||
|
.bt-import-drop { display: flex; flex-direction: column; gap: 6px; padding: 16px; border: 1px dashed var(--c-line-strong); border-radius: 11px; background: repeating-linear-gradient(135deg, rgba(123, 156, 255, .03) 0 8px, transparent 8px 16px); }
|
||||||
|
.bt-import-drop strong { font-size: 13px; font-weight: 600; }
|
||||||
|
.bt-import-drop p { margin: 0 0 6px; color: var(--c-muted); font-size: 12px; line-height: 1.5; }
|
||||||
|
@container panel (min-width: 620px) { .bt-import { grid-template-columns: 1fr 1fr; } }
|
||||||
|
|
||||||
|
/* Theme preview: a scaled X mock built from the theme document */
|
||||||
|
.tp { position: relative; width: 100%; overflow: hidden; }
|
||||||
|
.tp-stage { position: absolute; top: 0; left: 0; display: flex; justify-content: center; gap: 0; transform-origin: 0 0; color: var(--tp-text); font-family: var(--tp-ui); font-weight: var(--tp-weight); letter-spacing: var(--tp-track); overflow: hidden; }
|
||||||
|
.tp-stage b, .tp-stage strong { font-weight: var(--tp-bold); }
|
||||||
|
.tp-nav { flex: 0 0 auto; display: flex; flex-direction: column; gap: 2px; width: 206px; padding: 10px 12px 0 14px; }
|
||||||
|
.tp-logo { display: grid; place-items: center; width: 50px; height: 50px; }
|
||||||
|
.tp-nav-item { display: flex; align-items: center; gap: 18px; height: 50px; padding: 0 14px; border-radius: var(--tp-pill); }
|
||||||
|
.tp-nav-item.is-on { font-weight: var(--tp-bold); }
|
||||||
|
.tp-post-btn { display: grid; place-items: center; height: 50px; margin: 14px 12px 0 0; border-radius: var(--tp-pill); background: var(--tp-inverse); color: var(--tp-on-inverse); font-weight: var(--tp-bold); }
|
||||||
|
.tp-col { flex: 0 0 auto; height: 100%; background: var(--tp-bg); border-left: 1px solid var(--tp-border); border-right: 1px solid var(--tp-border); overflow: hidden; } /* rtl-ok: symmetric borders (theme preview mock of X) */
|
||||||
|
.tp-col-head { background: color-mix(in srgb, var(--tp-bg) 88%, transparent); border-bottom: 1px solid var(--tp-border); }
|
||||||
|
.tp-col-head > strong { display: block; padding: 14px 16px 0; }
|
||||||
|
.tp-tabs { display: flex; margin-top: 10px; }
|
||||||
|
.tp-tabs span { flex: 1; padding: 12px 0 14px; color: var(--tp-muted); text-align: center; font-weight: 500; }
|
||||||
|
.tp-tabs span.is-on { position: relative; color: var(--tp-text); font-weight: var(--tp-bold); }
|
||||||
|
.tp-tabs span.is-on::after { content: ''; position: absolute; left: 50%; bottom: 0; width: 56px; height: 4px; margin-left: -28px; border-radius: 4px; background: var(--tp-accent); } /* rtl-ok: centred with left: 50% */
|
||||||
|
.tp-feed.is-cards { padding: 6px 0; }
|
||||||
|
.tp-post { display: flex; gap: 12px; padding: var(--tp-pad) 16px; border-bottom: 1px solid var(--tp-border); }
|
||||||
|
.tp-feed.is-cards .tp-post { margin: calc(var(--tp-pad) / 2 + 2px) 12px; border: 1px solid var(--tp-border); border-radius: var(--tp-r); background: var(--tp-surface); }
|
||||||
|
.tp-avatar { flex: 0 0 auto; width: 40px; height: 40px; border-radius: var(--tp-avatar); background: var(--tp-elevated); }
|
||||||
|
.tp-avatar.is-sm { background: linear-gradient(135deg, #1d9bf0, #7856ff); }
|
||||||
|
.tp-post-body { flex: 1; min-width: 0; }
|
||||||
|
.tp-post-meta { display: flex; gap: 5px; white-space: nowrap; overflow: hidden; }
|
||||||
|
.tp-post-meta span { color: var(--tp-muted); }
|
||||||
|
.tp-post p { margin: 2px 0 0; font-family: var(--tp-body); }
|
||||||
|
.tp-media { height: 112px; margin-top: 10px; border: 1px solid var(--tp-border); border-radius: var(--tp-r); background: linear-gradient(135deg, color-mix(in srgb, var(--tp-accent) 70%, #000), color-mix(in srgb, var(--tp-accent) 25%, var(--tp-bg))); overflow: hidden; }
|
||||||
|
.tp-media span { display: block; width: 45%; height: 100%; margin-left: auto; background: radial-gradient(circle at 60% 40%, rgba(255, 255, 255, .35), transparent 60%); } /* rtl-ok: theme preview mock of X, which is LTR */
|
||||||
|
.tp-actions { display: flex; justify-content: space-between; max-width: 420px; margin-top: 10px; color: var(--tp-muted); }
|
||||||
|
.tp-actions span { display: inline-flex; align-items: center; gap: 5px; }
|
||||||
|
.tp-actions span.is-hot { color: #f91880; }
|
||||||
|
.tp-side { flex: 0 0 auto; padding: 8px 0 0 22px; }
|
||||||
|
.tp-searchbox { display: flex; align-items: center; gap: 10px; height: 42px; padding: 0 16px; border: 1px solid var(--tp-border); border-radius: var(--tp-pill); color: var(--tp-muted); background: var(--tp-bg); }
|
||||||
|
.tp-module { margin-top: 14px; padding: 12px 16px 6px; border: 1px solid var(--tp-border); border-radius: var(--tp-r); background: var(--tp-bg); }
|
||||||
|
.tp-module > strong { display: block; margin-bottom: 6px; }
|
||||||
|
.tp-trend { display: flex; flex-direction: column; padding: 7px 0; }
|
||||||
|
.tp-trend small { color: var(--tp-muted); }
|
||||||
|
.tp-follow { display: flex; align-items: center; gap: 10px; padding: 8px 0 10px; }
|
||||||
|
.tp-follow > div { display: flex; flex: 1; flex-direction: column; min-width: 0; }
|
||||||
|
.tp-follow small { color: var(--tp-muted); }
|
||||||
|
.tp-follow-btn { padding: 7px 16px; border-radius: var(--tp-pill); background: var(--tp-inverse); color: var(--tp-on-inverse); font-weight: var(--tp-bold); }
|
||||||
|
.tp-crt { position: absolute; inset: 0; pointer-events: none; background: repeating-linear-gradient(0deg, rgba(0, 0, 0, .16) 0 1px, transparent 1px 3px), radial-gradient(ellipse at center, transparent 60%, rgba(0, 0, 0, .45)); }
|
||||||
|
|
||||||
|
/* Search mode: sections without a matching row disappear */
|
||||||
|
.btp.is-searching .bt-section:not(:has(.bt-row)) { display: none; }
|
||||||
|
.btp-results .bt-section:first-child { margin-top: 0; }
|
||||||
|
|
||||||
|
/* Toast */
|
||||||
|
.btp-toast { position: absolute; left: 50%; bottom: 18px; z-index: 40; max-width: min(520px, calc(100% - 32px)); padding: 10px 14px; border: 1px solid var(--c-line-strong); border-radius: 11px; background: #141824; box-shadow: 0 16px 40px rgba(0, 0, 0, .55); font-size: 12.5px; cursor: pointer; transform: translateX(-50%); animation: bt-toast .22s var(--ease); }
|
||||||
|
.btp-toast.is-error { border-color: rgba(255, 92, 108, .55); background: color-mix(in srgb, var(--c-danger) 12%, var(--c-card)); }
|
||||||
|
@keyframes bt-toast { from { opacity: 0; transform: translate(-50%, 8px); } }
|
||||||
|
|
||||||
|
@media (prefers-reduced-motion: reduce) { .btp *, .btp *::before, .btp *::after { transition: none !important; animation: none !important; } }
|
||||||
|
|
||||||
|
/* ---------------------------------------------------------------------------------------------
|
||||||
|
Lists and editors shared with Drafts, Accounts, Updates and My Space (btp-* grammar). */
|
||||||
|
.btp-group { padding: 0 0 6px; margin-bottom: 18px; }
|
||||||
|
.btp-group-head { margin: 0 2px 10px; }
|
||||||
|
.btp-group-head h2 { margin: 0; font-size: 13px; font-weight: 620; }
|
||||||
|
.btp-group-head p { margin: 2px 0 0; color: var(--c-muted); font-size: 12px; }
|
||||||
|
.btp-muted { color: var(--c-muted); font-size: 12px; margin-inline-end: auto; }
|
||||||
|
.btp-btn { display: inline-flex; align-items: center; height: 30px; padding: 0 12px; border: 1px solid var(--c-line); border-radius: 8px; background: var(--c-field); cursor: pointer; font-weight: 540; white-space: nowrap; transition: border-color .15s, background-color .15s; }
|
||||||
|
.btp-btn:hover:not(:disabled) { border-color: var(--c-line-strong); background: var(--c-raise); }
|
||||||
|
.btp-btn:disabled { opacity: .42; cursor: default; }
|
||||||
|
.btp-btn.is-primary { background: var(--c-text); border-color: var(--c-text); color: var(--c-ground); }
|
||||||
|
.btp-btn.is-danger { background: var(--c-danger); border-color: var(--c-danger); color: #fff; }
|
||||||
|
.btp-link { border: 0; background: none; padding: 6px 0; color: var(--c-accent); cursor: pointer; font-weight: 540; }
|
||||||
|
.btp-row-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; margin-top: 10px; }
|
||||||
|
.btp-alert { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin: 10px 0; padding: 10px 12px; border: 1px solid rgba(255, 92, 108, .35); border-radius: 10px; background: rgba(255, 92, 108, .08); font-size: 12px; }
|
||||||
|
.btp-alert .btp-btn { margin-inline-start: auto; }
|
||||||
|
.btp-toolbar { display: flex; gap: 8px; }
|
||||||
|
.btp-seg { display: inline-flex; gap: 2px; margin: 12px 0 8px; padding: 3px; border: 1px solid var(--c-line); border-radius: 10px; background: var(--c-chrome); }
|
||||||
|
.btp-seg button { height: 26px; padding: 0 11px; border: 0; border-radius: 7px; background: none; color: var(--c-muted); cursor: pointer; font-weight: 520; }
|
||||||
|
.btp-seg button.is-on { background: var(--c-raise); color: var(--c-text); box-shadow: 0 0 0 1px var(--c-line-strong); }
|
||||||
|
.btp-seg span { margin-inline-start: 5px; font: 11px var(--f-mono); opacity: .7; }
|
||||||
|
.btp-list { display: flex; flex-direction: column; gap: 6px; }
|
||||||
|
.btp-list-head { margin: 16px 2px 4px; color: var(--c-muted); font-size: 11px; font-weight: 600; letter-spacing: .06em; text-transform: uppercase; }
|
||||||
|
.btp-list-head span { font-family: var(--f-mono); }
|
||||||
|
.btp-empty { margin: 0; padding: 26px 16px; border: 1px dashed var(--c-line); border-radius: 12px; color: var(--c-muted); font-size: 12.5px; text-align: center; }
|
||||||
|
.btp-item { display: flex; flex-direction: column; gap: 3px; width: 100%; padding: 11px 13px; border: 1px solid var(--c-line-soft); border-radius: 11px; background: var(--c-card); text-align: start; cursor: pointer; transition: border-color .15s, background-color .15s; }
|
||||||
|
.btp-item:hover { border-color: var(--c-line); background: var(--c-field); }
|
||||||
|
.btp-item.is-on { border-color: var(--c-accent); }
|
||||||
|
.btp-item-top { display: flex; align-items: baseline; gap: 8px; }
|
||||||
|
.btp-item-top strong { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: 600; }
|
||||||
|
.btp-item-top small { flex: 0 0 auto; color: var(--c-muted); font: 11px var(--f-mono); }
|
||||||
|
.btp-item-text { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; color: var(--c-muted); font-size: 12px; white-space: pre-wrap; }
|
||||||
|
.btp-item-meta { display: flex; gap: 6px; margin-top: 3px; }
|
||||||
|
.btp-item-meta em { padding: 0 6px; border-radius: 5px; background: var(--c-field); color: var(--c-muted); font: normal 10.5px/17px var(--f-mono); }
|
||||||
|
.btp-item-meta em.is-warn { color: var(--c-warn); }
|
||||||
|
.btp-draft { padding-top: 2px; }
|
||||||
|
.btp-draft-bar { display: flex; align-items: center; justify-content: space-between; margin-bottom: 10px; }
|
||||||
|
.btp-save { font: 11px var(--f-mono); color: var(--c-muted); }
|
||||||
|
.btp-save.is-saved { color: var(--c-ok); }
|
||||||
|
.btp-save.is-error, .btp-save.is-conflict { color: var(--c-danger); }
|
||||||
|
.btp-draft-title { margin-bottom: 8px; font-weight: 600; }
|
||||||
|
.btp-draft-text { height: auto; min-height: 200px; padding: 12px; resize: vertical; line-height: 1.55; }
|
||||||
|
.btp-diff pre { margin: 6px 0 0; padding: 8px 10px; max-height: 180px; overflow: auto; border: 1px solid var(--c-line-soft); border-radius: 9px; background: var(--c-card); font: 11.5px/1.5 var(--f-mono); white-space: pre-wrap; }
|
||||||
|
.btp-diff pre span { display: block; }
|
||||||
|
.btp-diff .is-del { background: rgba(255, 92, 108, .14); }
|
||||||
|
.btp-diff .is-add { background: rgba(61, 220, 151, .14); }
|
||||||
|
.btp-account { display: flex; align-items: center; gap: 10px; padding: 10px 12px; border: 1px solid var(--c-line-soft); border-radius: 11px; background: var(--c-card); }
|
||||||
|
.btp-account.is-on { border-color: var(--c-line-strong); }
|
||||||
|
.btp-account .btp-input { flex: 1; }
|
||||||
|
.btp-dot { flex: 0 0 auto; width: 14px; height: 14px; padding: 0; border: 0; border-radius: 50%; cursor: pointer; box-shadow: 0 0 0 3px var(--c-card), 0 0 0 4px var(--c-line); }
|
||||||
|
.btp-account-name { display: flex; flex: 1; min-width: 0; flex-direction: column; border: 0; background: none; text-align: start; cursor: pointer; }
|
||||||
|
.btp-account-name strong { font-weight: 600; }
|
||||||
|
.btp-account-name small { color: var(--c-muted); font-size: 11.5px; }
|
||||||
|
.btp-account.is-on .btp-account-name small { color: var(--c-accent); }
|
||||||
|
.btp-card { display: flex; flex-wrap: wrap; align-items: center; gap: 12px; padding: 16px; border: 1px solid var(--c-line-soft); border-radius: 12px; background: var(--c-card); }
|
||||||
|
.btp-card > div { flex: 1; min-width: 180px; display: flex; flex-direction: column; gap: 2px; }
|
||||||
|
.btp-card small { color: var(--c-muted); font-size: 12px; }
|
||||||
|
.btp-notes { margin: 6px 0 0; color: var(--c-muted); font-size: 12px; white-space: pre-wrap; }
|
||||||
|
|
||||||
|
/* Home: the wayBetter hero, highlights and About */
|
||||||
|
.btp-hero { position: relative; overflow: hidden; isolation: isolate; padding: 30px 24px 26px; border: 1px solid var(--c-line); border-radius: 18px; background: radial-gradient(120% 90% at 0% 0%, rgba(79, 107, 255, .16), transparent 60%), radial-gradient(90% 80% at 100% 10%, rgba(168, 85, 247, .14), transparent 60%), var(--c-card); }
|
||||||
|
.btp-hero::before { content: ''; position: absolute; left: 0; right: 0; top: 0; height: 2px; background: var(--c-brush); opacity: .9; }
|
||||||
|
.btp-hero-glow { position: absolute; z-index: -1; inset-inline-end: -60px; bottom: -90px; width: 260px; height: 260px; border-radius: 50%; background: radial-gradient(circle, rgba(34, 211, 238, .16), transparent 70%); filter: blur(8px); }
|
||||||
|
.btp-hero-mark { display: inline-grid; place-items: center; width: 76px; height: 76px; margin-bottom: 18px; border-radius: 20px; background: linear-gradient(160deg, rgba(255, 255, 255, .09), rgba(255, 255, 255, .02)); box-shadow: 0 0 0 1px rgba(255, 255, 255, .08), 0 18px 40px -12px rgba(79, 107, 255, .55); }
|
||||||
|
.btp-hero-mark img { border-radius: 14px; }
|
||||||
|
.btp-hero-kicker { margin: 0 0 6px; color: var(--c-muted); font-size: 12.5px; font-weight: 560; letter-spacing: .01em; }
|
||||||
|
.btp-hero-name { background: var(--c-brush); -webkit-background-clip: text; background-clip: text; color: transparent; font-weight: 720; }
|
||||||
|
.btp-hero-title { margin: 0; font-size: clamp(24px, 6cqi, 34px); line-height: 1.08; font-weight: 700; letter-spacing: -.035em; }
|
||||||
|
.btp-hero-title em { font-style: normal; background: var(--c-brush); -webkit-background-clip: text; background-clip: text; color: transparent; }
|
||||||
|
.btp-hero-lede { max-width: 54ch; margin: 12px 0 0; color: var(--c-muted); font-size: 13.5px; line-height: 1.55; }
|
||||||
|
.btp-hero-chips { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 16px; }
|
||||||
|
.btp-chip { display: inline-flex; align-items: center; height: 22px; padding: 0 9px; border: 1px solid var(--c-line-strong); border-radius: 999px; background: rgba(255, 255, 255, .03); color: var(--c-text); font-size: 11.5px; font-weight: 560; font-variant-numeric: tabular-nums; }
|
||||||
|
.btp-hero-actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 20px; }
|
||||||
|
.btp-hero-actions .btp-btn { height: 34px; padding: 0 16px; border-radius: 10px; }
|
||||||
|
|
||||||
|
.btp-highlights { display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: 8px; margin: 12px 0 26px; }
|
||||||
|
.btp-highlight { display: grid; grid-template-columns: auto 1fr; column-gap: 9px; row-gap: 3px; align-items: center; padding: 13px 14px; border: 1px solid var(--c-line-soft); border-radius: 12px; background: var(--c-card); color: var(--c-text); text-align: start; cursor: pointer; transition: border-color .15s, background-color .15s, transform .15s; }
|
||||||
|
.btp-highlight:hover { border-color: var(--c-line-strong); background: var(--c-field); transform: translateY(-1px); }
|
||||||
|
.btp-highlight svg { color: var(--c-accent); }
|
||||||
|
.btp-highlight strong { font-size: 13px; font-weight: 640; }
|
||||||
|
.btp-highlight span { grid-column: 1 / -1; color: var(--c-muted); font-size: 12px; line-height: 1.45; }
|
||||||
|
|
||||||
|
.btp-about .btp-group-head p { max-width: 64ch; line-height: 1.55; font-size: 12.5px; margin-top: 4px; }
|
||||||
|
.btp-layers { display: grid; gap: 1px; margin: 12px 0 0; padding: 0; list-style: none; border: 1px solid var(--c-line-soft); border-radius: 12px; overflow: hidden; background: var(--c-line-soft); }
|
||||||
|
.btp-layers li { display: flex; gap: 14px; align-items: baseline; padding: 13px 16px; background: var(--c-card); }
|
||||||
|
.btp-layers li div { display: grid; gap: 2px; }
|
||||||
|
.btp-layers strong { font-size: 13px; font-weight: 640; }
|
||||||
|
.btp-layers li div span { color: var(--c-muted); font-size: 12px; line-height: 1.45; }
|
||||||
|
.btp-layer-n { flex: 0 0 auto; background: var(--c-brush); -webkit-background-clip: text; background-clip: text; color: transparent; font-size: 12px; font-weight: 720; font-variant-numeric: tabular-nums; }
|
||||||
|
.btp-about-foot { display: flex; align-items: center; gap: 6px; margin: 14px 2px 0; color: var(--c-faint); font-size: 12px; }
|
||||||
|
.btp-about-foot b { color: var(--c-muted); font-weight: 600; }
|
||||||
|
.btp-about-foot .btp-link { padding: 0; font-size: 12px; }
|
||||||
|
|
||||||
|
@container panel (min-width: 720px) {
|
||||||
|
.btp-hero { padding: 40px 36px 34px; }
|
||||||
|
}
|
||||||
|
@media (prefers-reduced-motion: reduce) { .btp-highlight { transition: none; } .btp-highlight:hover { transform: none; } }
|
||||||
18
packages/shell/src/panel/plugins.css
Normal file
18
packages/shell/src/panel/plugins.css
Normal file
|
|
@ -0,0 +1,18 @@
|
||||||
|
/* The Store section is the framework's Store view (waybetter packages/shell store.css, `--wb-*`
|
||||||
|
tokens); here it follows the panel tokens (--c-*), so it follows the theme. */
|
||||||
|
|
||||||
|
.wbs {
|
||||||
|
--wb-text: var(--c-text); --wb-text-2: var(--c-text-2); --wb-text-rgb: var(--c-text-rgb); --wb-muted: var(--c-muted);
|
||||||
|
--wb-card: var(--c-card); --wb-field: var(--c-field);
|
||||||
|
--wb-border: var(--c-line); --wb-border-soft: var(--c-line-soft); --wb-border-strong: var(--c-line-strong);
|
||||||
|
--wb-accent: var(--c-accent); --wb-accent-rgb: var(--c-accent-rgb); --wb-accent-soft: var(--c-accent-soft);
|
||||||
|
--wb-ok: var(--c-ok); --wb-warn: var(--c-warn);
|
||||||
|
--wb-font-mono: var(--f-mono, ui-monospace, monospace); --wb-ease: var(--ease, ease);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Plugins list: permission and source badges (Extensions.tsx). */
|
||||||
|
.wbx-perms { display: inline-flex; flex-wrap: wrap; gap: 4px; margin-inline-start: 6px; vertical-align: middle; }
|
||||||
|
.wbx-perms span { padding: 0 6px; height: 18px; display: inline-flex; align-items: center; border-radius: 5px; font: 500 10.5px/1 var(--f-mono, ui-monospace, monospace); color: var(--c-muted); background: var(--c-field); border: 1px solid var(--c-line-soft); }
|
||||||
|
.wbx-perms span.is-warn { color: var(--c-warn); border-color: color-mix(in srgb, var(--c-warn) 35%, transparent); }
|
||||||
|
.wbx-perms span.is-ok { color: var(--c-ok); border-color: color-mix(in srgb, var(--c-ok) 30%, transparent); }
|
||||||
|
.wbx-perms span.is-source { color: var(--c-accent); border-color: rgb(var(--c-accent-rgb) / .3); }
|
||||||
187
packages/shell/src/panel/site.ts
Normal file
187
packages/shell/src/panel/site.ts
Normal file
|
|
@ -0,0 +1,187 @@
|
||||||
|
// What a wayBetter app tells the panel (its own tab: settings, themes, plugins, the Store, Make,
|
||||||
|
// accounts, backup, developer mode, updates): the brand and the home page's words, its theme
|
||||||
|
// catalog and preview, its own sections and what its native side serves. `createPanel(site)` sets
|
||||||
|
// it; every panel module reads it through `panelSite()`. The shell frame's site (`site()`,
|
||||||
|
// frame/site.ts) is read too: the deck (Power User), the media panel and the native features.
|
||||||
|
|
||||||
|
import type { ComponentType } from 'react';
|
||||||
|
import type { ThemeCatalog, ThemeChoice } from '../../../runtime/src/themeChoice.ts';
|
||||||
|
import type { FontChoice, ThemeColors, ThemeSpec } from '../../../runtime/src/themeSpec.ts';
|
||||||
|
import type { ResolvedTheme } from '../../../runtime/src/themeApi.ts';
|
||||||
|
import type { InstallController } from '../installController.ts';
|
||||||
|
import type { ThemeStore } from '../frame/themeStore.ts';
|
||||||
|
|
||||||
|
/** A short message at the bottom of the panel (`error`: stays longer, announced as an alert). */
|
||||||
|
export type Notify = (text: string, error?: boolean) => void;
|
||||||
|
|
||||||
|
/** What every section gets. */
|
||||||
|
export type SectionProps = {
|
||||||
|
notify: Notify;
|
||||||
|
/** Shows another section of the panel (built-in or the site's). */
|
||||||
|
openSection(id: string): void;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** The sections the framework brings; each shows only when the app serves what it needs. */
|
||||||
|
export const BUILTIN_SECTIONS = ['home', 'themes', 'builder', 'plugins', 'store', 'make', 'accounts', 'power', 'settings', 'backup', 'developer', 'updates'] as const;
|
||||||
|
export type BuiltinSection = typeof BUILTIN_SECTIONS[number];
|
||||||
|
|
||||||
|
/** A section of the app's own (X: Tweaks, Drafts, My Space). */
|
||||||
|
export type PanelSection = {
|
||||||
|
id: string;
|
||||||
|
label(): string;
|
||||||
|
/** The nav icon: a 16x16 stroke path (`d`). */
|
||||||
|
icon: string;
|
||||||
|
component: ComponentType<SectionProps>;
|
||||||
|
/** Its rows also show in the settings search (they filter themselves with `useSettingsQuery`). */
|
||||||
|
searchable?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** The home page: the hero, the highlight cards and the About block, in the app's words. */
|
||||||
|
export type PanelHome = {
|
||||||
|
/** The line above the title: the brand name, then what it is for ("wayBetter" + " for X"). */
|
||||||
|
kicker: { name: string; rest: string };
|
||||||
|
/** The title in three parts; the middle one is emphasized. */
|
||||||
|
title(): [string, string, string];
|
||||||
|
lede(): string;
|
||||||
|
/** Chips after the version chip ("Free & open source", "GPL-3.0"). */
|
||||||
|
chips?(): string[];
|
||||||
|
/** Hero buttons: each opens a section; the first is the primary one. */
|
||||||
|
actions?: ReadonlyArray<{ section: string; label(): string }>;
|
||||||
|
/** Cards under the hero: each opens a section and carries that section's icon. */
|
||||||
|
highlights?: ReadonlyArray<{ section: string; title(): string; text(): string }>;
|
||||||
|
about?: {
|
||||||
|
title(): string;
|
||||||
|
text(): string;
|
||||||
|
/** A numbered list (the framework's layers). */
|
||||||
|
layers?: ReadonlyArray<{ name(): string; text(): string }>;
|
||||||
|
/** "Made by @someone · site": the link opens in the system browser. */
|
||||||
|
foot?: { text(): string; by: string; link?: { label: string; url: string } };
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
/** The app's themes in the panel: Appearance, the Theme Builder, font pickers, Make's theme view. */
|
||||||
|
export type PanelThemes = {
|
||||||
|
/** The app's theme store (the same one the frame gets as `site.themes`). */
|
||||||
|
store: ThemeStore<ThemeChoice, ThemeSpec>;
|
||||||
|
/** The site's built-in themes (`createThemeCatalog`); the first is the site's own look. */
|
||||||
|
catalog: ThemeCatalog;
|
||||||
|
/** Accent swatches offered in Appearance. */
|
||||||
|
accents: readonly string[];
|
||||||
|
/** A miniature of the site drawn from a theme document (the gallery, the builder, the install screen). */
|
||||||
|
Preview: ComponentType<{ theme: ThemeSpec; className?: string }>;
|
||||||
|
/** The name of the site's own typeface, shown where a font role keeps it ("X's Chirp"). */
|
||||||
|
siteFont: string;
|
||||||
|
/** Named font stacks offered besides Google Fonts (default: the runtime's `FONT_CHOICES`). */
|
||||||
|
fontChoices?: readonly FontChoice[];
|
||||||
|
/** The palette a draft starts from when a theme keeps the site's own colors. */
|
||||||
|
draftColors: Pick<ThemeColors, 'bg' | 'text' | 'accent'>;
|
||||||
|
/** Swatches for the builder's three base colors (defaults are neutral). */
|
||||||
|
baseSwatches?: { bg: string[]; text: string[]; accent: string[] };
|
||||||
|
/** File name suffix of an exported theme (default `.theme.json`). */
|
||||||
|
fileSuffix?: string;
|
||||||
|
/** The builder's chrome preview: tab titles and the address chip. */
|
||||||
|
chromePreview?: { tabs: [string, string, string]; chip: string; page: string };
|
||||||
|
/**
|
||||||
|
* Make's theme view: the active theme as plugins see it. `modes` are the site's own display modes
|
||||||
|
* (X: Default, Dim, Lights out), offered while the theme keeps the site's colors.
|
||||||
|
*/
|
||||||
|
resolved?(choice: ThemeChoice, mode: string): ResolvedTheme;
|
||||||
|
modes?: { label(): string; initial: string; options: ReadonlyArray<{ value: string; label(): string }> };
|
||||||
|
};
|
||||||
|
|
||||||
|
/** A plugin example in Make's editor. */
|
||||||
|
export type PluginExample = { id: string; title: string; blurb: string; file: string; source: string };
|
||||||
|
|
||||||
|
/** Make: example plugins, a theme file and the bundled docs, all the app's. */
|
||||||
|
export type PanelMake = {
|
||||||
|
examples: readonly PluginExample[];
|
||||||
|
/** An example theme file (JSON text) and the name it downloads as. */
|
||||||
|
themeExample?: { file: string; source: string };
|
||||||
|
/** Bundled Markdown docs by file name; the first is opened by default. */
|
||||||
|
docs?: Readonly<Record<string, string>>;
|
||||||
|
/** The page runtime's global in the code samples (default `wayBetter`). */
|
||||||
|
global?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** A feature flag group for `FeatureToggles` (the app's page tweaks). */
|
||||||
|
export type FeatureGroup = { id: string; features: readonly string[] };
|
||||||
|
|
||||||
|
/** One language the app has a catalog for (the app's `languages.json`). */
|
||||||
|
export type PanelLanguage = {
|
||||||
|
code: string;
|
||||||
|
name: string;
|
||||||
|
englishName: string;
|
||||||
|
dir: 'ltr' | 'rtl';
|
||||||
|
status: 'source' | 'machine' | 'reviewed';
|
||||||
|
coverage: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** The app's language state (frame/language.ts `createLanguage`). */
|
||||||
|
export type PanelLanguages = {
|
||||||
|
list: readonly PanelLanguage[];
|
||||||
|
state(): { preference: string; siteLang: string | null; system: readonly string[]; locale: string };
|
||||||
|
subscribe(listener: () => void): () => void;
|
||||||
|
set(preference: string): Promise<void>;
|
||||||
|
/** The contributor guide ("Help translate"), opened in the system browser. */
|
||||||
|
translateUrl?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type PanelSite = {
|
||||||
|
/** The header: the brand's name and logo (an image URL). */
|
||||||
|
brand: { name: string; logo: string };
|
||||||
|
home: PanelHome;
|
||||||
|
/** The app's version for the home page's chip. */
|
||||||
|
version?(): Promise<string>;
|
||||||
|
/** The app's own sections. */
|
||||||
|
sections?: readonly PanelSection[];
|
||||||
|
/** Nav order (built-in and site ids). Default: the built-in ones, then the site's. */
|
||||||
|
order?: readonly string[];
|
||||||
|
/** Themes (Appearance, Theme Builder); omit for an app without them. */
|
||||||
|
themes?: PanelThemes;
|
||||||
|
/** The install screen's controller: the Store section, and removing a plugin from the list. */
|
||||||
|
store?: { controller: InstallController<ThemeSpec> };
|
||||||
|
make?: PanelMake;
|
||||||
|
/** The language picker in Settings; omit for an app in one language. */
|
||||||
|
languages?: PanelLanguages;
|
||||||
|
/** Settings: keyword alerts (`alerts_get/set`) and what the app adds under the framework's rows. */
|
||||||
|
settings?: {
|
||||||
|
alerts?: boolean;
|
||||||
|
extra?: ReadonlyArray<ComponentType<SectionProps>>;
|
||||||
|
/** Extra search words for the "links to the site's pages" row ("x twitter"). */
|
||||||
|
linkKeywords?: string;
|
||||||
|
};
|
||||||
|
/** Placeholder CSS in the editors, written with the site's own selectors: custom CSS, a theme's CSS, the builder's. */
|
||||||
|
cssExamples?: { custom?: string; theme?: string; builder?: string };
|
||||||
|
/** Power User (with `site.deck`): what the settings list besides the frame's own. */
|
||||||
|
power?: {
|
||||||
|
/** Column flags offered as deck defaults (default: the flags `site.deck.defaultFlags` names). */
|
||||||
|
defaultFlags?: readonly string[];
|
||||||
|
/** What one column was measured to take, in MB (shown with the columns-per-page guard). */
|
||||||
|
memory?: { perColumn: number; range: string };
|
||||||
|
/** A line above the deck keys (which of the site's own keys keep working in a column). */
|
||||||
|
keysHint?(): string;
|
||||||
|
};
|
||||||
|
/** Backup & export (`backup_*`); the sync part needs the frame's `sync` feature. */
|
||||||
|
backup?: boolean;
|
||||||
|
/** The native updater (`app_ready`, `update_status`, `apply_update`). */
|
||||||
|
updates?: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
let current: PanelSite | null = null;
|
||||||
|
|
||||||
|
/** Sets the panel's site (createPanel). */
|
||||||
|
export function configurePanel(value: PanelSite) {
|
||||||
|
current = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function panelSite(): PanelSite {
|
||||||
|
if (!current) throw new Error('wayBetter panel: createPanel(site) first');
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The app's themes (Appearance, the builder and the font pickers only render with them). */
|
||||||
|
export function panelThemes(): PanelThemes {
|
||||||
|
const themes = panelSite().themes;
|
||||||
|
if (!themes) throw new Error('wayBetter panel: this app has no themes (PanelSite.themes)');
|
||||||
|
return themes;
|
||||||
|
}
|
||||||
9
packages/shell/src/panel/themes.ts
Normal file
9
packages/shell/src/panel/themes.ts
Normal file
|
|
@ -0,0 +1,9 @@
|
||||||
|
// The app's theme store as the panel's components use it (`PanelSite.themes.store`).
|
||||||
|
import { useThemeState as useThemeStateCore } from '../frame/hooks.ts';
|
||||||
|
import { panelThemes } from './site.ts';
|
||||||
|
|
||||||
|
/** The app's theme store (fonts, choice, scopes, preview). */
|
||||||
|
export const themeStore = () => panelThemes().store;
|
||||||
|
|
||||||
|
/** The theme state (global choice, scopes, installed fonts, preview); re-renders on change. */
|
||||||
|
export const useThemeState = () => useThemeStateCore(panelThemes().store);
|
||||||
171
packages/shell/tests/panel.test.ts
Normal file
171
packages/shell/tests/panel.test.ts
Normal file
|
|
@ -0,0 +1,171 @@
|
||||||
|
// The panel's pure parts: its words (every key it uses has English and every English key is used),
|
||||||
|
// which sections an app gets and in what order, the Theme Builder's model, the Google Fonts
|
||||||
|
// catalog, Make's plugin header rules and UI kit demos, and the Markdown the bundled docs use.
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { readFileSync, readdirSync, statSync } from 'node:fs';
|
||||||
|
import { dirname, join } from 'node:path';
|
||||||
|
import test from 'node:test';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
import { themeFromColors, themeVars } from '../../runtime/src/themeApi.ts';
|
||||||
|
import { BASE_EFFECTS, BASE_FONT, BASE_LAYOUT, BASE_SHAPE, sanitizeSpec, type ThemeSpec } from '../../runtime/src/themeSpec.ts';
|
||||||
|
import { configureSite, type ShellSite } from '../src/frame/site.ts';
|
||||||
|
import { autoFix, contrastReport, draftFrom, paletteFrom, pinnedRoles, record, redo, startHistory, themeJson, undo, uniqueId } from '../src/panel/builderModel.ts';
|
||||||
|
import { compareLines } from '../src/panel/compare.ts';
|
||||||
|
import { defaultWeights, parseCatalog, searchFonts, stackFor } from '../src/panel/fonts/catalog.ts';
|
||||||
|
import { CREATE_COMMANDS, KIT_DEMOS, cssVarOf, parsePluginHeader, pluginFileFor, pluginWarnings, validPluginFileName } from '../src/panel/makeModel.ts';
|
||||||
|
import { anchorOf, inlineTokens, parseMarkdown, resolveLink } from '../src/panel/markdown.ts';
|
||||||
|
import { navEntries } from '../src/panel/nav.ts';
|
||||||
|
import { PANEL_MESSAGES } from '../src/panel/panelMessages.ts';
|
||||||
|
import type { PanelSite } from '../src/panel/site.ts';
|
||||||
|
|
||||||
|
const here = dirname(fileURLToPath(import.meta.url));
|
||||||
|
const PANEL = join(here, '../src/panel');
|
||||||
|
const files = (dir: string): string[] => readdirSync(dir).flatMap(name => {
|
||||||
|
const path = join(dir, name);
|
||||||
|
return statSync(path).isDirectory() ? files(path) : [path];
|
||||||
|
});
|
||||||
|
|
||||||
|
test('every key the panel uses has English, and every English key is used', () => {
|
||||||
|
const sources = files(PANEL).filter(file => /\.tsx?$/.test(file) && !file.endsWith('panelMessages.ts')).map(file => readFileSync(file, 'utf8')).join('\n');
|
||||||
|
const used = new Set([...sources.matchAll(/'(wb\.[A-Za-z0-9_.-]+)'/g)].map(match => match[1]!));
|
||||||
|
// Keys built at runtime (`wb.fonts.role.<role>.label`, ...): every key under the prefix counts.
|
||||||
|
const prefixes = [...sources.matchAll(/`(wb\.[A-Za-z0-9_.]+\.)\$\{/g)].map(match => match[1]!);
|
||||||
|
const en = JSON.parse(readFileSync(join(here, '../../waybetter/locales/en.json'), 'utf8')).messages as Record<string, string>;
|
||||||
|
for (const key of used) assert.ok(key in en, `${key} is in the framework catalog`);
|
||||||
|
for (const prefix of prefixes) assert.ok(Object.keys(en).some(key => key.startsWith(prefix)), `${prefix}* is in the framework catalog`);
|
||||||
|
// `wb.fonts.choice.<id>` is named by the runtime's FONT_CHOICES (`key`).
|
||||||
|
for (const key of Object.keys(PANEL_MESSAGES)) {
|
||||||
|
assert.ok(used.has(key) || prefixes.some(prefix => key.startsWith(prefix)) || key.startsWith('wb.fonts.choice.'), `${key} is used`);
|
||||||
|
assert.equal(en[key], PANEL_MESSAGES[key as keyof typeof PANEL_MESSAGES], `${key} is the catalog's English`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const shellSite = (extra: Partial<ShellSite> = {}) => ({
|
||||||
|
name: 'Example', product: 'wayBetter for Example', logo: '', homeUrl: 'https://example.com/home', loginUrl: 'https://example.com/login', logoutUrl: 'https://example.com/logout',
|
||||||
|
isSiteUrl: (url: string) => url.startsWith('https://example.com/'),
|
||||||
|
accounts: { handle: /^\w{1,15}$/, avatarPrefixes: [], handlePrefix: '@' },
|
||||||
|
searchUrl: (text: string) => `https://example.com/search?q=${encodeURIComponent(text)}`,
|
||||||
|
address: () => null,
|
||||||
|
panel: { id: 'app', title: 'App', component: () => null },
|
||||||
|
newTab: { search: () => 'Search', links: [] },
|
||||||
|
palette: { placeholder: () => 'Search', sections: [] },
|
||||||
|
...extra,
|
||||||
|
}) satisfies ShellSite;
|
||||||
|
|
||||||
|
const home: PanelSite['home'] = { kicker: { name: 'wayBetter', rest: ' for Example' }, title: () => ['Example, ', 'better', '.'], lede: () => 'An example.' };
|
||||||
|
|
||||||
|
test('an app gets the sections it serves, in its order', () => {
|
||||||
|
// A small app: no themes, store, decks, backup, developer mode or updater.
|
||||||
|
configureSite(shellSite({ features: { workspaces: false, sync: false, developer: false, pluginCommands: false } }));
|
||||||
|
const small: PanelSite = { brand: { name: 'Example', logo: '' }, home };
|
||||||
|
assert.deepEqual(navEntries(small).map(entry => entry.id), ['home', 'plugins', 'accounts', 'settings']);
|
||||||
|
// Its own sections come after the built-in ones unless it orders them.
|
||||||
|
const Own = () => null;
|
||||||
|
const own: PanelSite = { ...small, sections: [{ id: 'tweaks', label: () => 'Tweaks', icon: 'M0 0', component: Own, searchable: true }] };
|
||||||
|
assert.deepEqual(navEntries(own).map(entry => entry.id), ['home', 'plugins', 'accounts', 'settings', 'tweaks']);
|
||||||
|
const ordered = navEntries({ ...own, order: ['home', 'tweaks', 'plugins', 'nope', 'store'], backup: true, updates: true });
|
||||||
|
assert.deepEqual(ordered.map(entry => entry.id), ['home', 'tweaks', 'plugins', 'accounts', 'settings', 'backup', 'updates']);
|
||||||
|
assert.equal(ordered[1]!.component, Own);
|
||||||
|
assert.equal(ordered[1]!.label(key => key), 'Tweaks');
|
||||||
|
assert.equal(ordered[0]!.label(key => `[${key}]`), '[wb.panel.section.home]');
|
||||||
|
// Developer mode is a frame feature; Power User needs a deck.
|
||||||
|
configureSite(shellSite({
|
||||||
|
deck: { kinds: [], urlFor: () => null, title: () => ({ title: '' }), parseValue: () => '', invalid: () => '', flags: [], defaultFlags: {} },
|
||||||
|
}));
|
||||||
|
assert.deepEqual(navEntries(small).map(entry => entry.id), ['home', 'plugins', 'accounts', 'power', 'settings', 'developer']);
|
||||||
|
});
|
||||||
|
|
||||||
|
const SITE_THEME: ThemeSpec = {
|
||||||
|
id: 'site', name: 'Site default', description: '', author: 'Example', version: 1, mode: 'auto', colors: null,
|
||||||
|
font: BASE_FONT, shape: BASE_SHAPE, layout: BASE_LAYOUT, background: { kind: 'none' }, effects: BASE_EFFECTS, css: '',
|
||||||
|
};
|
||||||
|
const DRAFT_SITE = { colors: { bg: '#000000', text: '#e7e9ea', accent: '#1d9bf0' }, siteTheme: 'site' };
|
||||||
|
|
||||||
|
test('builder: history, palette from three colors, contrast report and auto-fix, export', () => {
|
||||||
|
const draft = draftFrom(SITE_THEME, DRAFT_SITE, 'Mine');
|
||||||
|
assert.ok(draft.colors, "the site's own look gets a real palette to edit");
|
||||||
|
assert.equal(draft.colors!.bg, '#000000');
|
||||||
|
assert.equal(draft.description, '', "the site's own theme is not \"based on\" anything");
|
||||||
|
assert.equal(draftFrom({ ...SITE_THEME, id: 'paper', name: 'Paper' }, DRAFT_SITE).description, 'Based on Paper.');
|
||||||
|
let history = startHistory(draft);
|
||||||
|
const light = { ...draft, colors: paletteFrom({ bg: '#fbf8f1', text: '#8a8a8a', accent: '#ffd400' }) };
|
||||||
|
history = record(history, light);
|
||||||
|
// A slider drag: many in-place updates, one undo step from where it started.
|
||||||
|
const dragged = record(record(history, { ...light, name: 'a' }, { commit: false }), { ...light, name: 'ab' }, { commit: false });
|
||||||
|
const committed = record(dragged, { ...light, name: 'abc' }, { from: light });
|
||||||
|
assert.equal(committed.past.length, 2);
|
||||||
|
assert.equal(undo(committed).present.name, light.name);
|
||||||
|
assert.equal(redo(undo(committed)).present.name, 'abc');
|
||||||
|
assert.equal(undo(undo(undo(committed))).present, draft);
|
||||||
|
const report = contrastReport(light.colors!);
|
||||||
|
assert.ok(report.some(check => !check.pass));
|
||||||
|
assert.ok(contrastReport(autoFix(light.colors!)).every(check => check.pass), 'auto-fix passes every check');
|
||||||
|
const colors = paletteFrom({ bg: '#000000', text: '#ffffff', accent: '#1d9bf0' }, { border: '#ff0000' });
|
||||||
|
assert.deepEqual(pinnedRoles(colors), { border: '#ff0000' });
|
||||||
|
assert.equal(uniqueId('Paper', ['site', 'paper']), 'paper-2', 'built-in ids are taken');
|
||||||
|
assert.equal(uniqueId('Mine', ['mine']), 'mine-2');
|
||||||
|
assert.equal(uniqueId('Mine', []), 'mine');
|
||||||
|
const schema = JSON.parse(readFileSync(join(here, '../../waybetter/theme.schema.json'), 'utf8'));
|
||||||
|
const json = JSON.parse(themeJson(light));
|
||||||
|
assert.equal(json.$schema, schema.$id);
|
||||||
|
assert.deepEqual(sanitizeSpec(json), sanitizeSpec(light));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Google Fonts catalog: parse, search, default weights, fallback stacks', () => {
|
||||||
|
const catalog = parseCatalog({ families: [
|
||||||
|
['Inter', 'sans', [100, 900], [100, 400, 900], 3], ['Lato', 'sans', null, [100, 300, 400, 700, 900], 2],
|
||||||
|
['Fraunces', 'serif', [100, 900], [400], 9], ['Bad/Name', 'sans', null, [400], 1], ['Odd', 'weird', null, [400], 1],
|
||||||
|
] });
|
||||||
|
assert.deepEqual(catalog.map(font => font.family), ['Inter', 'Lato', 'Fraunces']);
|
||||||
|
assert.deepEqual(searchFonts(catalog, {}).map(font => font.family), ['Lato', 'Inter', 'Fraunces'], 'popularity');
|
||||||
|
assert.deepEqual(searchFonts(catalog, { query: 'in' }).map(font => font.family), ['Inter'], 'prefix');
|
||||||
|
assert.deepEqual(searchFonts(catalog, { category: 'serif' }).map(font => font.family), ['Fraunces']);
|
||||||
|
assert.deepEqual(searchFonts(catalog, { only: new Set(['Lato']) }).map(font => font.family), ['Lato']);
|
||||||
|
assert.deepEqual(defaultWeights(catalog[0]!), { kind: 'range', min: 100, max: 900 });
|
||||||
|
assert.deepEqual(defaultWeights(catalog[1]!), { kind: 'list', values: [400, 700] });
|
||||||
|
assert.deepEqual(stackFor(catalog[2]!), ['Fraunces', 'Georgia', 'serif']);
|
||||||
|
// The bundled snapshot parses and only holds names native code accepts.
|
||||||
|
const bundled = parseCatalog(JSON.parse(readFileSync(join(PANEL, 'fonts/googleFontsCatalog.json'), 'utf8')));
|
||||||
|
assert.ok(bundled.length > 1500);
|
||||||
|
assert.ok(bundled.every(font => /^[A-Za-z0-9]+( [A-Za-z0-9]+)*$/.test(font.family) && font.family.length <= 48));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Make: header parsing follows the plugin store (waybetter-host parse_meta)', () => {
|
||||||
|
const source = '/**\n * @name Hide Trends\n * @description Hides trends\n * @version 1.2.0\n * @author Someone\n */\nmodule.exports = class {};';
|
||||||
|
assert.deepEqual(parsePluginHeader('hide.plugin.js', source), { file: 'hide.plugin.js', name: 'Hide Trends', description: 'Hides trends', version: '1.2.0', author: 'Someone', header: true });
|
||||||
|
assert.equal(parsePluginHeader('plain.plugin.js', 'module.exports = {};').name, 'plain', 'no header: the file name');
|
||||||
|
assert.equal(parsePluginHeader('one.plugin.js', ' /** @name One */ module.exports = {};').name, 'One');
|
||||||
|
assert.equal(parsePluginHeader('x.plugin.js', '/**\n * @name \n */').name, 'x', 'an empty @name keeps the file name');
|
||||||
|
assert.equal(parsePluginHeader('x.plugin.js', `/**\n * @description ${'d'.repeat(400)}\n */`).description.length, 300);
|
||||||
|
assert.equal(validPluginFileName('../evil.plugin.js'), false);
|
||||||
|
assert.equal(validPluginFileName('.hidden.plugin.js'), false);
|
||||||
|
assert.equal(validPluginFileName('ok name.plugin.js'), true);
|
||||||
|
assert.equal(pluginFileFor('Hide Trends'), 'hide-trends.plugin.js');
|
||||||
|
assert.deepEqual(pluginWarnings(parsePluginHeader('a.plugin.js', 'console.log(1)'), 'console.log(1)').length, 3);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Make: UI kit demos name real kit calls; color roles map to the --wb-* variables', () => {
|
||||||
|
for (const demo of KIT_DEMOS) assert.ok(demo.code.includes(`ui.${demo.kind}(`), demo.id);
|
||||||
|
const theme = themeFromColors('#101010', '#f0f0f0', '#3ddc97');
|
||||||
|
const vars = themeVars(theme);
|
||||||
|
for (const role of Object.keys(theme.colors)) assert.ok(cssVarOf(role) in vars, role);
|
||||||
|
assert.ok(CREATE_COMMANDS.every(item => item.command.startsWith('npm create waybetter ')));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('Markdown: headings, tables, code and links as data; anchors and doc links resolve', () => {
|
||||||
|
const blocks = parseMarkdown('# Title\n\nSee [the API](./OTHER.md#the-api) and `code`.\n\n| a | b |\n| - | - |\n| 1 | 2 |\n\n```js\nlet x = 1;\n```\n\n- one\n- **two**\n');
|
||||||
|
assert.deepEqual(blocks.map(block => block.kind), ['heading', 'paragraph', 'table', 'code', 'list']);
|
||||||
|
const table = blocks.find(block => block.kind === 'table')!;
|
||||||
|
assert.ok(table.kind === 'table' && table.rows.every(row => row.length === table.head.length));
|
||||||
|
const links = inlineTokens('See [the API](./OTHER.md#the-api) and `code`.').filter(token => token.kind === 'link');
|
||||||
|
assert.equal(links.length, 1);
|
||||||
|
assert.deepEqual(resolveLink('./OTHER.md#the-api', ['OTHER.md']), { doc: 'OTHER.md', anchor: 'the-api' });
|
||||||
|
assert.equal(anchorOf('Matching the theme: `api.theme`'), 'matching-the-theme-apitheme');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('compare: changed lines are marked on both sides', () => {
|
||||||
|
const diff = compareLines('one\ntwo\nthree', 'one\n2\nthree');
|
||||||
|
assert.deepEqual(diff.previous.map(line => line.changed), [false, true, false]);
|
||||||
|
assert.deepEqual(diff.current.map(line => line.changed), [false, true, false]);
|
||||||
|
assert.equal(diff.current[1]!.text, '2');
|
||||||
|
});
|
||||||
|
|
@ -7,6 +7,7 @@
|
||||||
"allowImportingTsExtensions": true,
|
"allowImportingTsExtensions": true,
|
||||||
"rewriteRelativeImportExtensions": true,
|
"rewriteRelativeImportExtensions": true,
|
||||||
"verbatimModuleSyntax": true,
|
"verbatimModuleSyntax": true,
|
||||||
|
"resolveJsonModule": true,
|
||||||
"isolatedModules": true,
|
"isolatedModules": true,
|
||||||
"jsx": "react-jsx",
|
"jsx": "react-jsx",
|
||||||
"declaration": true,
|
"declaration": true,
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,7 @@
|
||||||
"version": "0.4.0",
|
"version": "0.4.0",
|
||||||
"license": "GPL-3.0-or-later",
|
"license": "GPL-3.0-or-later",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"description": "wayBetter: the framework for apps that run the apps you already use in a light native (Tauri) window and extend them in place. Page runtime (DOM/request hubs, plugins, plugin UI kit with themed dialogs and toasts, theme API and theme JSON Schema, theme color model, link routing, account reporting, deck columns, i18n: ICU-lite messages, locale fallback, plugin strings, catalog checks and JSON Schemas), shell models (address bar, panes, decks, profiles, palette, updates), the shell frame (createShell: tabs, splits, address bar, titlebar, palette, account switcher, decks, workspaces, overlays; React + dockview peers) and the Store: install screen and Store view React components (optional React peer), their state and catalog models, the store catalog JSON Schema and the `waybetter store build|sign|verify` command, `waybetter release windows|macos` (signed native releases and the update manifest, configured by waybetter.release.json) and `waybetter/build` (the page runtime bundle, with an optional esbuild peer). No dependencies.",
|
"description": "wayBetter: the framework for apps that run the apps you already use in a light native (Tauri) window and extend them in place. Page runtime (DOM/request hubs, plugins, plugin UI kit with themed dialogs and toasts, theme API and theme JSON Schema, theme color model, link routing, account reporting, deck columns, i18n: ICU-lite messages, locale fallback, plugin strings, catalog checks and JSON Schemas), shell models (address bar, panes, decks, profiles, palette, updates), the shell frame (createShell: tabs, splits, address bar, titlebar, palette, account switcher, decks, workspaces, overlays, the language state; React + dockview peers), the panel (createPanel: an app's own tab with Appearance and the Theme Builder, plugins and custom CSS, the Store, Make, accounts, settings, backup and sync, developer mode, updates; the app adds its sections) and the Store: install screen and Store view React components (optional React peer), their state and catalog models, the store catalog JSON Schema and the `waybetter store build|sign|verify` command, `waybetter release windows|macos` (signed native releases and the update manifest, configured by waybetter.release.json) and `waybetter/build` (the page runtime bundle, with an optional esbuild peer). No dependencies.",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"waybetter",
|
"waybetter",
|
||||||
"tauri",
|
"tauri",
|
||||||
|
|
@ -169,6 +169,15 @@
|
||||||
"types": "./dist/shell/frame/*.d.ts",
|
"types": "./dist/shell/frame/*.d.ts",
|
||||||
"import": "./dist/shell/frame/*.js"
|
"import": "./dist/shell/frame/*.js"
|
||||||
},
|
},
|
||||||
|
"./shell/panel": {
|
||||||
|
"types": "./dist/shell/panel/index.d.ts",
|
||||||
|
"import": "./dist/shell/panel/index.js"
|
||||||
|
},
|
||||||
|
"./shell/panel/*.css": "./dist/shell/panel/*.css",
|
||||||
|
"./shell/panel/*": {
|
||||||
|
"types": "./dist/shell/panel/*.d.ts",
|
||||||
|
"import": "./dist/shell/panel/*.js"
|
||||||
|
},
|
||||||
"./shell/*": {
|
"./shell/*": {
|
||||||
"types": "./dist/shell/*.d.ts",
|
"types": "./dist/shell/*.d.ts",
|
||||||
"import": "./dist/shell/*.js"
|
"import": "./dist/shell/*.js"
|
||||||
|
|
@ -225,7 +234,7 @@
|
||||||
"access": "public"
|
"access": "public"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "node -e \"require('fs').rmSync('dist',{recursive:true,force:true})\" && tsc -p ../runtime/tsconfig.build.json --outDir dist/runtime --inlineSources --declarationMap false && tsc -p ../shell/tsconfig.build.json --outDir dist/shell --inlineSources --declarationMap false && node -e \"const fs=require('fs');fs.copyFileSync('../shell/src/store.css','dist/shell/store.css');for(const f of fs.readdirSync('../shell/src/frame'))if(f.endsWith('.css'))fs.copyFileSync('../shell/src/frame/'+f,'dist/shell/frame/'+f)\"",
|
"build": "node scripts/build.mjs",
|
||||||
"test": "cd ../.. && node --test packages/runtime/tests/*.test.ts packages/shell/tests/*.test.ts packages/waybetter/tests/*.test.mjs",
|
"test": "cd ../.. && node --test packages/runtime/tests/*.test.ts packages/shell/tests/*.test.ts packages/waybetter/tests/*.test.mjs",
|
||||||
"prepublishOnly": "npm run build && npm test"
|
"prepublishOnly": "npm run build && npm test"
|
||||||
},
|
},
|
||||||
|
|
|
||||||
50
packages/waybetter/scripts/build.mjs
Normal file
50
packages/waybetter/scripts/build.mjs
Normal file
|
|
@ -0,0 +1,50 @@
|
||||||
|
// Builds the package's dist/: the page runtime (dist/runtime) and the shell (dist/shell: models,
|
||||||
|
// the Store, the shell frame and the panel) with tsc, then the stylesheets and data files that
|
||||||
|
// travel with the components. Run by `npm run build` (and `prepublishOnly`).
|
||||||
|
//
|
||||||
|
// The shell imports the runtime by source path (`../../../runtime/src/x.ts`), so it is compiled
|
||||||
|
// with both packages under one root and its imports are then pointed at dist/runtime.
|
||||||
|
import { execFileSync } from 'node:child_process';
|
||||||
|
import { cpSync, existsSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
|
||||||
|
import { createRequire } from 'node:module';
|
||||||
|
import { dirname, join, relative } from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
|
||||||
|
const root = join(dirname(fileURLToPath(import.meta.url)), '..');
|
||||||
|
const packages = join(root, '..');
|
||||||
|
const dist = join(root, 'dist');
|
||||||
|
const tsc = createRequire(import.meta.url).resolve('typescript/bin/tsc');
|
||||||
|
const compile = (...args) => execFileSync(process.execPath, [tsc, ...args, '--inlineSources', '--declarationMap', 'false'], { cwd: root, stdio: 'inherit' });
|
||||||
|
const files = dir => readdirSync(dir).flatMap(name => {
|
||||||
|
const path = join(dir, name);
|
||||||
|
return statSync(path).isDirectory() ? files(path) : [path];
|
||||||
|
});
|
||||||
|
|
||||||
|
rmSync(dist, { recursive: true, force: true });
|
||||||
|
compile('-p', join(packages, 'runtime/tsconfig.build.json'), '--outDir', join(dist, 'runtime'));
|
||||||
|
|
||||||
|
// The shell, with the runtime sources it imports, under one root: <tmp>/shell/src and <tmp>/runtime/src.
|
||||||
|
const tmp = join(dist, '.shell');
|
||||||
|
compile('-p', join(packages, 'shell/tsconfig.build.json'), '--rootDir', packages, '--outDir', tmp);
|
||||||
|
renameSync(join(tmp, 'shell/src'), join(dist, 'shell'));
|
||||||
|
rmSync(tmp, { recursive: true, force: true });
|
||||||
|
// `../../../runtime/src/x.js` (from packages/shell/src/<dir>) is `../../runtime/x.js` in dist/shell/<dir>.
|
||||||
|
let rewritten = 0;
|
||||||
|
for (const file of files(join(dist, 'shell'))) {
|
||||||
|
if (!/\.(js|d\.ts)$/.test(file)) continue;
|
||||||
|
const text = readFileSync(file, 'utf8');
|
||||||
|
const next = text.replace(/((?:\.\.\/)+)runtime\/src\//g, (_, up) => `${up.slice(3)}runtime/`);
|
||||||
|
if (next !== text) { writeFileSync(file, next); rewritten += 1; }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stylesheets and data files sit next to the components that import them.
|
||||||
|
const source = join(packages, 'shell/src');
|
||||||
|
let copied = 0;
|
||||||
|
for (const file of files(source)) {
|
||||||
|
if (!/\.(css|json)$/.test(file)) continue;
|
||||||
|
const target = join(dist, 'shell', relative(source, file));
|
||||||
|
if (file.endsWith('.json') && existsSync(target)) continue;
|
||||||
|
cpSync(file, target);
|
||||||
|
copied += 1;
|
||||||
|
}
|
||||||
|
console.log(`dist: runtime and shell built (${rewritten} shell files import the runtime, ${copied} stylesheets and data files copied)`);
|
||||||
|
|
@ -6,6 +6,7 @@
|
||||||
"moduleResolution": "Bundler",
|
"moduleResolution": "Bundler",
|
||||||
"allowImportingTsExtensions": true,
|
"allowImportingTsExtensions": true,
|
||||||
"verbatimModuleSyntax": true,
|
"verbatimModuleSyntax": true,
|
||||||
|
"resolveJsonModule": true,
|
||||||
"isolatedModules": true,
|
"isolatedModules": true,
|
||||||
"jsx": "react-jsx",
|
"jsx": "react-jsx",
|
||||||
"noEmit": true,
|
"noEmit": true,
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue