Share my setup, panel: Backup & sync gets "Share my setup" (Copy link, Save file) and "Use a setup" (paste a waybetter://setup link or open a file, then What will change with Apply and Cancel); shown only for an app that sets PanelSite.setup; English words

This commit is contained in:
CRTkafa 2026-10-01 04:43:24 +07:00
parent 83671c2782
commit ea18b0223f
6 changed files with 222 additions and 2 deletions

View file

@ -32,6 +32,8 @@ const getError = (error: unknown) => error instanceof Error ? error.message : St
const listeners = new Set<(state: ModeState) => void>(); const listeners = new Set<(state: ModeState) => void>();
let cached: ModeState | null = null; let cached: ModeState | null = null;
const share = (next: ModeState) => { cached = next; for (const listener of listeners) listener(next); }; const share = (next: ModeState) => { cached = next; for (const listener of listeners) listener(next); };
/** Tells the mode screens a mode was stored from elsewhere (an imported setup). */
export const rememberModeState = share;
/** The mode state, loaded once and shared by the first-run screen and Settings. Null until loaded (or without modes). */ /** The mode state, loaded once and shared by the first-run screen and Settings. Null until loaded (or without modes). */
export function useModeState(): [ModeState | null, (next: ModeState) => void] { export function useModeState(): [ModeState | null, (next: ModeState) => void] {
@ -74,7 +76,7 @@ const presetSeen = (table: FeatureTable, state: ModeState) =>
invoke<ModeState>('mode_set', { mode: state.mode, onboarded: state.onboarded, preset: modeById(table, state.mode)?.flags ?? {} }); invoke<ModeState>('mode_set', { mode: state.mode, onboarded: state.onboarded, preset: modeById(table, state.mode)?.flags ?? {} });
/** A flag as the owner knows it: the feature's label, or the area's name for its switch. */ /** A flag as the owner knows it: the feature's label, or the area's name for its switch. */
function flagName(table: FeatureTable, id: string): string { export function flagName(table: FeatureTable, id: string): string {
const area = table.areas.find(entry => areaFlag(entry.id) === id); const area = table.areas.find(entry => areaFlag(entry.id) === id);
if (area) return area.name; if (area) return area.name;
const feature = table.features.find(entry => entry.id === id); const feature = table.features.find(entry => entry.id === id);

View file

@ -22,6 +22,7 @@ import { NavIcon } from './NavIcon.tsx';
import { ModeSettings, Onboarding, useModeState } from './Modes.tsx'; import { ModeSettings, Onboarding, useModeState } from './Modes.tsx';
import { AreaPlugins } from './PluginFeatures.tsx'; import { AreaPlugins } from './PluginFeatures.tsx';
import { ScriptPlugins } from './Plugins.tsx'; import { ScriptPlugins } from './Plugins.tsx';
import { ShareSetup } from './ShareSetup.tsx';
import { PowerSettings } from './PowerSettings.tsx'; import { PowerSettings } from './PowerSettings.tsx';
import { AlertSettings, BrowserSettings, MediaSettingsRows } from './Settings.tsx'; import { AlertSettings, BrowserSettings, MediaSettingsRows } from './Settings.tsx';
import { panelSite, type Notify, type SectionProps } from './site.ts'; import { panelSite, type Notify, type SectionProps } from './site.ts';
@ -91,7 +92,7 @@ export default function Panel({ section: requested }: { section?: { name: string
{!Custom && section === 'updates' && <Updates/>} {!Custom && section === 'updates' && <Updates/>}
{!Custom && section === 'power' && <PowerSettings notify={notify}/>} {!Custom && section === 'power' && <PowerSettings notify={notify}/>}
{!Custom && section === 'settings' && <SettingsSection {...props}/>} {!Custom && section === 'settings' && <SettingsSection {...props}/>}
{!Custom && section === 'backup' && <BackupPanel notify={notify}/>} {!Custom && section === 'backup' && <><BackupPanel notify={notify}/><ShareSetup notify={notify}/></>}
{!Custom && section === 'developer' && <DeveloperPanel notify={notify}/>} {!Custom && section === 'developer' && <DeveloperPanel notify={notify}/>}
</>} </>}
</div> </div>

View file

@ -0,0 +1,152 @@
// Settings → Backup & sync → "Share my setup" (setupModel.ts): the look, the mode and which
// features are on, as one `waybetter://setup` link or one small file, and the way back in: paste a
// link, open a file, or open a link from outside (the host forwards its text, `setup-link`). Nothing
// is applied before the owner has seen "What will change" and pressed Apply. The section shows only
// when the app names itself (`PanelSite.setup`).
import { useEffect, useRef, useState } from 'react';
import { modeById, normalizeFlags, sparseFlags, type Flags } from '../../../runtime/src/featureTable.ts';
import type { ThemeChoice } from '../../../runtime/src/themeChoice.ts';
import { invoke } from '../frame/bridge.ts';
import { useT } from '../frame/hooks.ts';
import { tx } from '../frame/i18n.ts';
import { Button, InputRow, Row, Section } from './controls.tsx';
import { flagName, rememberModeState, type ModeState } from './Modes.tsx';
import { featureTable, flagsChanged } from './PluginFeatures.tsx';
import { SETUP_FILE_SUFFIX, applySetup, makeSetup, readSetup, setupFile, setupLink, setupPlan, type ReadSetup, type SetupPlan, type SetupState, type SharedSetup } from './setupModel.ts';
import { panelSite, type Notify } from './site.ts';
/** The event the shell raises when the host hands it a `waybetter://setup` link opened from outside. */
export const SETUP_LINK_EVENT = 'wb-setup-link';
let pendingLink: string | null = null;
/** Keeps a link opened from outside until the section is on screen to preview it. */
export function receiveSetupLink(text: string) {
pendingLink = text;
window.dispatchEvent(new CustomEvent(SETUP_LINK_EVENT));
}
async function currentState(): Promise<SetupState> {
const site = panelSite();
const table = featureTable()!;
await site.themes?.store.loadThemes();
const choice = site.themes?.store.themeState().choice as ThemeChoice | undefined;
const flags = normalizeFlags(table, await invoke<unknown>('features_get'));
const mode = table.modes.length ? (await invoke<ModeState>('mode_get')).mode : null;
return { ...(choice ? { theme: { preset: choice.preset, accent: choice.accent, ...(choice.icons ? { icons: choice.icons } : {}) } } : {}), mode, flags };
}
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);
}
type Preview = { setup: SharedSetup; plan: SetupPlan; dropped: string[]; now: SetupState };
export function ShareSetup({ notify }: { notify: Notify }) {
const site = panelSite();
return site.setup && featureTable() ? <ShareSetupOf app={site.setup.app} notify={notify}/> : null;
}
function ShareSetupOf({ app, notify }: { app: string; notify: Notify }) {
const t = useT();
const site = panelSite();
const table = featureTable()!;
const [text, setText] = useState('');
const [preview, setPreview] = useState<Preview | null>(null);
const [busy, setBusy] = useState(false);
const file = useRef<HTMLInputElement>(null);
const store = site.themes?.store;
const error = (read: Extract<ReadSetup, { ok: false }>) => read.error === 'app'
? (read.app ? t('wb.setup.err.app', { app: read.app }) : t('wb.setup.err.appUnknown'))
: t(`wb.setup.err.${read.error}`);
async function open(input: string) {
const read = readSetup(input, app, table);
if (!read.ok) { notify(error(read), true); return; }
try {
const now = await currentState();
const themes = new Set(store?.allThemes().map(theme => theme.id) ?? []);
const packs = new Set(site.themes?.iconPacks?.map(pack => pack.id) ?? []);
setPreview({ setup: read.setup, plan: setupPlan(table, now, read.setup, themes, packs), dropped: read.dropped, now });
} catch (err) { notify(err instanceof Error ? err.message : String(err), true); }
}
// A link opened from outside (the host's `setup-link` event, forwarded by the shell).
useEffect(() => {
const take = () => { const link = pendingLink; pendingLink = null; if (link) void open(link); };
take();
window.addEventListener(SETUP_LINK_EVENT, take);
return () => window.removeEventListener(SETUP_LINK_EVENT, take);
}, []);
async function share(kind: 'link' | 'file') {
try {
const setup = makeSetup(app, table, await currentState());
if (kind === 'file') { download(`setup${SETUP_FILE_SUFFIX}`, setupFile(setup)); return; }
await navigator.clipboard.writeText(setupLink(setup)).then(() => notify(t('wb.setup.linkCopied')), () => notify(t('wb.common.clipboardUnavailable'), true));
} catch (err) { notify(err instanceof Error ? err.message : String(err), true); }
}
async function apply() {
if (!preview) return;
setBusy(true);
try {
const { plan, now } = preview;
const next = applySetup(table, now, plan);
if (plan.on.length || plan.off.length) {
await invoke('features_set', { features: sparseFlags(table, next.flags as Flags) });
flagsChanged();
}
if (store && next.theme && (plan.theme || plan.accent || plan.icons)) {
const choice = store.themeState().choice as ThemeChoice;
const { icons: _icons, ...rest } = choice;
await store.setChoice({ ...rest, preset: next.theme.preset, accent: next.theme.accent, ...(plan.theme ? { overrides: {} } : {}), ...(next.theme.icons ? { icons: next.theme.icons } : {}) });
}
if (plan.mode) rememberModeState(await invoke<ModeState>('mode_set', { mode: next.mode, onboarded: true, preset: modeById(table, next.mode)?.flags ?? {} }));
setPreview(null);
setText('');
notify(t('wb.setup.applied'));
} catch (err) { notify(err instanceof Error ? err.message : String(err), true); }
finally { setBusy(false); }
}
const themeName = (id: string) => store?.themeName(id) ?? id;
const iconName = (id: string | undefined) => id === undefined ? t('wb.appearance.icons.theme') : id === 'site' ? t('wb.appearance.icons.site') : site.themes?.iconPacks?.find(pack => pack.id === id)?.name ?? id;
const modeName = (id: string | null) => id ? tx(modeById(table, id)?.name ?? id, undefined, id) : t('wb.setup.modeNone');
const names = (ids: readonly string[]) => ids.map(id => flagName(table, id)).join(', ');
return <Section title={t('wb.setup.title')} hint={t('wb.setup.hint')} id="setup">
<Row label={t('wb.setup.shareLabel')} hint={t('wb.setup.private')} keywords="share setup link export copy send friend">
<div className="bt-inline">
<Button tone="primary" onClick={() => void share('link')}>{t('wb.setup.copyLink')}</Button>
<Button onClick={() => void share('file')}>{t('wb.setup.saveFile')}</Button>
</div>
</Row>
<Row label={t('wb.setup.useLabel')} hint={t('wb.setup.useHint')} keywords="import setup link apply" wide>
<div className="bt-inline">
<InputRow value={text} onChange={setText} onSubmit={() => void open(text)} placeholder="waybetter://setup?…" label={t('wb.setup.paste')} button={t('wb.setup.preview')} disabled={!text.trim()} mono/>
<Button onClick={() => file.current?.click()}>{t('wb.setup.openFile')}</Button>
<input ref={file} type="file" hidden accept="application/json,.json" onChange={event => { void event.target.files?.[0]?.text().then(open); event.target.value = ''; }}/>
</div>
</Row>
{preview && <Row label={t('wb.setup.changes')} wide>
<div className="wbf-ask" role="alertdialog" aria-label={t('wb.setup.changes')}>
{preview.plan.same && <small>{t('wb.setup.same')}</small>}
{preview.plan.theme && <small>{t('wb.setup.theme', { from: themeName(preview.plan.theme.from), to: themeName(preview.plan.theme.to) })}</small>}
{preview.plan.accent && <small>{t('wb.setup.accent', { to: preview.plan.accent.to ?? t('wb.setup.accentTheme') })}</small>}
{preview.plan.icons && <small>{t('wb.setup.icons', { to: iconName(preview.plan.icons.to) })}</small>}
{preview.plan.mode && <small>{t('wb.setup.mode', { from: modeName(preview.plan.mode.from), to: modeName(preview.plan.mode.to) })}</small>}
{preview.plan.on.length > 0 && <small>{t('wb.modes.turnsOn', { list: names(preview.plan.on) })}</small>}
{preview.plan.off.length > 0 && <small>{t('wb.modes.turnsOff', { list: names(preview.plan.off) })}</small>}
{preview.plan.missingTheme && <small>{t('wb.setup.missingTheme', { id: preview.plan.missingTheme })}</small>}
{preview.plan.missingIcons && <small>{t('wb.setup.missingIcons', { id: preview.plan.missingIcons })}</small>}
{preview.dropped.length > 0 && <small>{t('wb.setup.dropped', { list: preview.dropped.join(', ') })}</small>}
{!preview.plan.same && <Button size="sm" tone="primary" disabled={busy} onClick={() => void apply()}>{t('wb.setup.apply')}</Button>}
<Button size="sm" tone="ghost" onClick={() => setPreview(null)}>{t('wb.common.cancel')}</Button>
</div>
</Row>}
</Section>;
}

View file

@ -493,6 +493,36 @@ export const PANEL_MESSAGES = {
'wb.modes.turnsOff': 'Turns off: {list}', 'wb.modes.turnsOff': 'Turns off: {list}',
'wb.modes.turnsOn': 'Turns on: {list}', 'wb.modes.turnsOn': 'Turns on: {list}',
'wb.modes.use': 'Use this mode', 'wb.modes.use': 'Use this mode',
'wb.setup.title': 'Share my setup',
'wb.setup.hint': 'Your theme, icons, mode and which features are on, as one link or one small file. Anyone can use it to start from what you have.',
'wb.setup.shareLabel': 'Your setup',
'wb.setup.private': 'Nothing about you goes in it: no accounts, profiles, notes, drafts, keywords or starred messages.',
'wb.setup.copyLink': 'Copy link',
'wb.setup.linkCopied': 'Setup link copied.',
'wb.setup.saveFile': 'Save file',
'wb.setup.useLabel': 'Use a setup',
'wb.setup.useHint': 'Paste a waybetter://setup link or open a setup file. You see what would change before anything does.',
'wb.setup.paste': 'Setup link',
'wb.setup.preview': 'Preview',
'wb.setup.openFile': 'Open file…',
'wb.setup.changes': 'What will change',
'wb.setup.same': 'Nothing would change: this is already your setup.',
'wb.setup.theme': 'Theme: {from} → {to}',
'wb.setup.accent': 'Accent color: {to}',
'wb.setup.accentTheme': "the theme's own",
'wb.setup.icons': 'Icons: {to}',
'wb.setup.mode': 'Mode: {from} → {to}',
'wb.setup.modeNone': 'none',
'wb.setup.missingTheme': 'The theme “{id}” is not installed here, so yours stays.',
'wb.setup.missingIcons': 'The icon pack “{id}” is not installed here, so yours stays.',
'wb.setup.dropped': 'Left out, this version does not know them: {list}',
'wb.setup.apply': 'Apply',
'wb.setup.applied': 'Setup applied.',
'wb.setup.err.format': 'This is not a wayBetter setup.',
'wb.setup.err.version': 'This setup comes from a newer version. Update the app to use it.',
'wb.setup.err.app': 'This setup is for another app ({app}).',
'wb.setup.err.appUnknown': 'This setup is for another app.',
'wb.setup.err.size': 'This is too large to be a setup.',
'wb.panel.accounts.add': '+ Add account', 'wb.panel.accounts.add': '+ Add account',
'wb.panel.accounts.hint': 'Each account is its own {site} sign-in on this computer and stays signed in across restarts. Click one to open its feed beside this pane.', 'wb.panel.accounts.hint': 'Each account is its own {site} sign-in on this computer and stays signed in across restarts. Click one to open its feed beside this pane.',
'wb.panel.accounts.newTabsBadge': 'new tabs', 'wb.panel.accounts.newTabsBadge': 'new tabs',

View file

@ -184,6 +184,11 @@ export type PanelSite = {
}; };
/** Backup & export (`backup_*`); the sync part needs the frame's `sync` feature. */ /** Backup & export (`backup_*`); the sync part needs the frame's `sync` feature. */
backup?: boolean; backup?: boolean;
/**
* "Share my setup" under Backup & sync (ShareSetup.tsx; needs `features`): the app's id, which a
* setup carries so it never applies to another app. Absent: no such section.
*/
setup?: { app: string };
/** The native updater (`app_ready`, `update_status`, `apply_update`). */ /** The native updater (`app_ready`, `update_status`, `apply_update`). */
updates?: boolean; updates?: boolean;
}; };

View file

@ -1137,6 +1137,36 @@
"wb.modes.turnsOff": "Turns off: {list}", "wb.modes.turnsOff": "Turns off: {list}",
"wb.modes.turnsOn": "Turns on: {list}", "wb.modes.turnsOn": "Turns on: {list}",
"wb.modes.use": "Use this mode", "wb.modes.use": "Use this mode",
"wb.setup.title": "Share my setup",
"wb.setup.hint": "Your theme, icons, mode and which features are on, as one link or one small file. Anyone can use it to start from what you have.",
"wb.setup.shareLabel": "Your setup",
"wb.setup.private": "Nothing about you goes in it: no accounts, profiles, notes, drafts, keywords or starred messages.",
"wb.setup.copyLink": "Copy link",
"wb.setup.linkCopied": "Setup link copied.",
"wb.setup.saveFile": "Save file",
"wb.setup.useLabel": "Use a setup",
"wb.setup.useHint": "Paste a waybetter://setup link or open a setup file. You see what would change before anything does.",
"wb.setup.paste": "Setup link",
"wb.setup.preview": "Preview",
"wb.setup.openFile": "Open file…",
"wb.setup.changes": "What will change",
"wb.setup.same": "Nothing would change: this is already your setup.",
"wb.setup.theme": "Theme: {from} → {to}",
"wb.setup.accent": "Accent color: {to}",
"wb.setup.accentTheme": "the theme's own",
"wb.setup.icons": "Icons: {to}",
"wb.setup.mode": "Mode: {from} → {to}",
"wb.setup.modeNone": "none",
"wb.setup.missingTheme": "The theme “{id}” is not installed here, so yours stays.",
"wb.setup.missingIcons": "The icon pack “{id}” is not installed here, so yours stays.",
"wb.setup.dropped": "Left out, this version does not know them: {list}",
"wb.setup.apply": "Apply",
"wb.setup.applied": "Setup applied.",
"wb.setup.err.format": "This is not a wayBetter setup.",
"wb.setup.err.version": "This setup comes from a newer version. Update the app to use it.",
"wb.setup.err.app": "This setup is for another app ({app}).",
"wb.setup.err.appUnknown": "This setup is for another app.",
"wb.setup.err.size": "This is too large to be a setup.",
"wb.features.soon": "Its features arrive in a later update.", "wb.features.soon": "Its features arrive in a later update.",
"wb.menu.label": "Settings and more", "wb.menu.label": "Settings and more",
"wb.menu.accountsRow": "Settings and more…", "wb.menu.accountsRow": "Settings and more…",