From 2bd3ace38d740b943a4cc82148d483dcf2e1e71c Mon Sep 17 00:00:00 2001 From: CRT Date: Tue, 29 Sep 2026 05:47:18 +0000 Subject: [PATCH] create-waybetter: a new app's shell is the framework's shell frame The app skeleton's src/shell/main.tsx calls createShell with the site (pages, account rules, search, address chips, a Home link, a Plugins section) and src/shell/Panel.tsx (the app's own tab: the plugins, switched on or off live); app.css themes it with the --wb-c-* tokens. build.mjs bundles the shell with waybetter/build (JSX, CSS into dist/shell.css) and writes bootScript() as boot.js. desktop.rs keeps the frame's titlebar (custom_titlebar: true) and forwards shortcuts and link drags (BridgeOptions::ALL); the shell capability grants the frame's window calls. Native features the skeleton does not wire up (workspaces, sync, developer mode, plugin commands) are off in the site. Dependencies: react, react-dom, dockview, waybetter ^0.4.0. Tests: sources import only published subpaths (patterns included), main.tsx uses createShell, the shell capability has the resize permission, and the skeleton typechecks with the React types. --- packages/create-waybetter/src/app.js | 268 +++++++++--------- .../create-waybetter/tests/create.test.mjs | 15 +- 2 files changed, 149 insertions(+), 134 deletions(-) diff --git a/packages/create-waybetter/src/app.js b/packages/create-waybetter/src/app.js index 181f897..c9c4a27 100644 --- a/packages/create-waybetter/src/app.js +++ b/packages/create-waybetter/src/app.js @@ -149,6 +149,13 @@ export const HOST_COMMANDS = { }; const permission = command => `allow-${command.replace(/_/g, '-')}`; +/** The shell frame's window calls: its titlebar drag region, resize grips and caption buttons. */ +const WINDOW_PERMISSIONS = [ + 'core:window:allow-start-dragging', 'core:window:allow-start-resize-dragging', 'core:window:allow-internal-toggle-maximize', + 'core:window:allow-minimize', 'core:window:allow-toggle-maximize', 'core:window:allow-is-maximized', 'core:window:allow-close', + 'core:window:allow-set-background-color', +]; + // --------------------------------------------------------------------------------------------- // Icons: a small RGBA PNG (Tauri decodes it for the window icon) and an ICO wrapping it (the // Windows resource). Replace both with real art (`npx tauri icon art.png`). @@ -567,10 +574,9 @@ function desktopRs(o) { 'impl SiteHooks for Site {', ' fn init_scripts(&self, _app: &AppHandle, _tab: &NewTab) -> Vec {', ' vec![', - ' // The framework tab bridge: reports each tab\'s URL and title to the address bar; it', - ' // may call only `tab_report` (shortcut and link-drag forwarding are off: this shell', - ' // does not handle them yet).', - ' bridge::script(BridgeOptions::REPORT_ONLY),', + ' // The framework tab bridge: reports each tab\'s URL and title to the address bar and', + ' // forwards its browser shortcuts and link drags to the shell (the shell frame handles both).', + ' bridge::script(BridgeOptions::ALL),', ' // The runtime checks the origin itself and stays inert on other sites.', ' RUNTIME.to_owned(),', ' ]', @@ -601,8 +607,8 @@ function desktopRs(o) { ' let config = AppConfig {', ' window_size: (1280.0, 820.0),', ' min_window_size: (720.0, 480.0),', - ' // This shell draws no titlebar of its own: keep the OS frame.', - ' custom_titlebar: false,', + ' // The shell frame draws the titlebar (tabs in it, caption buttons on Windows).', + ' custom_titlebar: true,', ' ..AppConfig::new(&SITE, SITE.product)', ' };', ' App::new(config, Site)', @@ -695,7 +701,7 @@ function capabilities(o) { description: 'The trusted local shell: tabs (the wayBetter host\'s layout, actions, profiles and language) and plugins. No generic filesystem or shell APIs.', webviews: [/** policy::SHELL_LABEL */ 'shell'], local: true, - permissions: ['core:event:default', ...HOST_COMMANDS.shell.map(permission), ...COMMANDS.shell.map(permission)], + permissions: ['core:event:default', ...WINDOW_PERMISSIONS, ...HOST_COMMANDS.shell.map(permission), ...COMMANDS.shell.map(permission)], }), }, { @@ -889,116 +895,112 @@ function runtimeTs() { /** @param {AppOptions} o */ function shellTs(o) { + const { handle } = o.site; + const handleChars = handle.extra.replace(/[\\\]^-]/g, ch => `\\${ch}`); return lines( - '// The shell: a trusted local page that fills the window. It draws the toolbar (address chips', - '// from waybetter/shell/addressModel, the account, plugins) and reports where the site tab goes;', - '// native code places the tab\'s own webview over that rectangle (`tabs_sync`).', + '// The shell: the wayBetter shell frame (waybetter/shell/frame) with this site\'s pages and the', + '// app\'s own panel. Tabs in the titlebar, splits, the address bar, the new-tab page, the command', + '// palette (Ctrl+K) and the account switcher are the framework\'s; native code places each tab\'s', + '// webview over its pane (tabs_sync).', '', + "import { createRoot } from 'react-dom/client';", + "import { createI18n } from 'waybetter/i18n';", + "import en from 'waybetter/locales/en.json' with { type: 'json' };", + "import { isSiteUrl } from 'waybetter/runtime/site';", "import { parseAddress } from 'waybetter/shell/addressModel';", - "import { TITLEBAR_H } from 'waybetter/shell/chrome';", + "import { createShell, type ShellSite } from 'waybetter/shell/frame';", "import { ADDRESS_SITE } from '../address.ts';", "import { SITE } from '../site.ts';", + "import { Panel } from './Panel.tsx';", + "import './app.css';", + '', + `const ORIGIN = ${str(o.origin)};`, + '', + '/** English; merge `waybetter/locales/.json` (and your own catalog) for other languages. */', + "const i18n = createI18n({ source: en.messages, available: ['en'] });", + '', + 'const site: ShellSite = {', + ` name: ${str(o.label)},`, + ' product: SITE.product,', + " logo: './icon.png',", + ' homeUrl: `${ORIGIN}/`,', + " // PLACEHOLDER: the site's own sign-in and sign-out pages.", + ' loginUrl: `${ORIGIN}/login`,', + ' logoutUrl: `${ORIGIN}/logout`,', + ' isSiteUrl: url => isSiteUrl(SITE, url),', + ' // Same rules as src-tauri/src/site.rs (valid_handle, avatar_prefixes).', + ` accounts: { handle: /^[A-Za-z0-9${handleChars}]{${handle.min},${handle.max}}$/, avatarPrefixes: [${o.site.avatarPrefixes.map(str).join(', ')}], handlePrefix: '@' },`, + " // PLACEHOLDER: the site's search page.", + ' searchUrl: text => `${ORIGIN}/search?q=${encodeURIComponent(text)}`,', + ' address: url => parseAddress(url, ADDRESS_SITE),', + " panel: { id: 'app', title: SITE.product, component: Panel },", + ' newTab: {', + ` search: () => ${str(`Search ${o.label}`)},`, + " links: [{ id: 'home', label: () => 'Home', icon: 'home', url: home => home }],", + ' },', + ' palette: {', + " placeholder: () => 'Search tabs, pages and settings',", + " sections: [{ id: 'plugins', label: () => 'Plugins', keywords: 'extensions js', icon: 'grid' }],", + ' },', + ' // Native features this app does not wire up yet (waybetter-host workspaces, sync, devmode,', + ' // plugins::commands): the frame shows nothing of them until they are switched on here.', + ' features: { workspaces: false, sync: false, developer: false, pluginCommands: false },', + '};', + '', + 'const { core, event, window: tauriWindow } = window.__TAURI__;', + 'const Shell = createShell(site, { native: { invoke: core.invoke, listen: event.listen, currentWindow: tauriWindow.getCurrentWindow }, i18n });', + "createRoot(document.getElementById('root')!).render();", + ); +} + +function panelTsx() { + return lines( + '// The app\'s own tab (Ctrl+Shift+W, the brand button, Ctrl+K "Plugins"): its settings. Here: the', + '// plugins in the plugins folder, each switched on or off live in every site tab.', + '', + "import { useEffect, useState } from 'react';", '', 'type Plugin = { file: string; name: string; description: string; version: string; author: string; enabled: boolean };', - 'type TabStateEvent = { id: string; url?: string; title?: string; loading?: boolean };', - 'type TabAccountEvent = { id: string; account: { handle: string; name: string; avatar?: string } | null };', '', - "const TAB_ID = '1';", - 'const { invoke } = window.__TAURI__.core;', - 'const { listen } = window.__TAURI__.event;', - '', - 'const $ = (id: string) => document.getElementById(id) as T;', - "const pane = $('pane');", - "const chips = $('chips');", - "const account = $('account');", - "const pluginsButton = $('plugins-button');", - "const pluginsPanel = $('plugins');", - "const status = $('status');", - "document.documentElement.style.setProperty('--toolbar-h', `${TITLEBAR_H}px`);", - "document.title = SITE.product;", - '', - 'let url = `https://${SITE.hosts[0]}/`;', - 'let overlay = false;', - '', - 'function showError(error: unknown) {', - ' status.textContent = String(error);', - ' status.hidden = false;', + 'export function Panel(_props: { section?: { name: string; nonce: number } }) {', + ' const [plugins, setPlugins] = useState([]);', + " const [error, setError] = useState('');", + ' const { invoke } = window.__TAURI__.core;', + " const run = (promise: Promise) => promise.then(list => { if (list) setPlugins(list); setError(''); }, failure => setError(String(failure)));", + " useEffect(() => { void run(invoke('plugins_list')); }, []);", + ' return
', + '

Plugins

', + ' {error &&

{error}

}', + ' {plugins.map(plugin => )}', + " ", + '
;', '}', - '', - '/** Tells native code where the tab goes; hidden while a shell overlay (plugins) is open. */', - 'function sync() {', - ' const rect = pane.getBoundingClientRect();', - ' const items = [{ id: TAB_ID, url, profile: \'default\', x: rect.left, y: rect.top, width: rect.width, height: rect.height, visible: !overlay, parked: false }];', - " invoke('tabs_sync', { items }).catch(showError);", - '}', - '', - 'function renderAddress(href: string) {', - ' const model = parseAddress(href, ADDRESS_SITE);', - ' chips.replaceChildren();', - ' if (!model) return;', - ' for (const part of [{ label: model.site.label, href: model.site.href }, ...model.segments]) {', - " const chip = document.createElement('span');", - " chip.className = 'chip';", - ' chip.textContent = part.label;', - ' chip.title = part.href;', - ' chips.append(chip);', - ' }', - '}', - '', - 'async function renderPlugins() {', - ' const plugins = await invoke(\'plugins_list\');', - ' pluginsPanel.replaceChildren();', - ' for (const plugin of plugins) {', - " const row = document.createElement('label');", - " const toggle = document.createElement('input');", - " toggle.type = 'checkbox';", - ' toggle.checked = plugin.enabled;', - " toggle.addEventListener('change', () => {", - " invoke('plugin_set_enabled', { file: plugin.file, enabled: toggle.checked }).then(renderPlugins, showError);", - ' });', - " const text = document.createElement('span');", - " text.textContent = `${plugin.name} ${plugin.version}`.trim();", - ' row.append(toggle, text);', - ' pluginsPanel.append(row);', - ' }', - " const folder = document.createElement('button');", - " folder.textContent = 'Open plugins folder';", - " folder.addEventListener('click', () => { invoke('plugins_open_folder').catch(showError); });", - ' pluginsPanel.append(folder);', - '}', - '', - "pluginsButton.addEventListener('click', () => {", - ' overlay = !overlay;', - ' pluginsPanel.hidden = !overlay;', - " pluginsButton.setAttribute('aria-expanded', String(overlay));", - ' if (overlay) renderPlugins().catch(showError);', - ' sync();', - '});', - '', - "listen('tab-state', ({ payload }) => {", - ' if (payload.id !== TAB_ID || !payload.url) return;', - ' url = payload.url;', - ' renderAddress(url);', - '});', - "listen('tab-account', ({ payload }) => {", - " account.textContent = payload.account ? `@${payload.account.handle}` : 'Signed out';", - '});', - '', - 'new ResizeObserver(sync).observe(pane);', - 'renderAddress(url);', - 'sync();', ); } function tauriTypes() { return lines( - '// `window.__TAURI__` in the shell (tauri.conf.json: app.withGlobalTauri). Swap for', - '// `@tauri-apps/api` if you prefer imports.', + '// `window.__TAURI__` in the shell (tauri.conf.json: app.withGlobalTauri): what the shell frame and', + '// the panel call. Swap for `@tauri-apps/api` if you prefer imports.', + '', + 'type TauriWindow = {', + ' minimize(): Promise;', + ' toggleMaximize(): Promise;', + ' close(): Promise;', + " startResizeDragging(direction: 'North' | 'South' | 'East' | 'West' | 'NorthEast' | 'NorthWest' | 'SouthEast' | 'SouthWest'): Promise;", + ' isMaximized(): Promise;', + ' onResized(handler: () => void): Promise<() => void>;', + ' setBackgroundColor(color: [number, number, number, number]): Promise;', + '};', '', 'interface Window {', ' __TAURI__: {', ' core: { invoke(command: string, args?: Record): Promise };', ' event: { listen(event: string, handler: (event: { payload: T }) => void): Promise<() => void> };', + ' window: { getCurrentWindow(): TauriWindow };', ' };', '}', ); @@ -1012,41 +1014,33 @@ function indexHtml(o) { '', ' ', ' ', + ' ', ` ${o.product.replace(/[<&]/g, ch => (ch === '<' ? '<' : '&'))}`, + ' ', + ' ', ' ', ' ', '', '', - '
', - ' ', - ' ', - ' ', - '
', - ' ', - ' ', - ' ', - '
', + '
', '', '', ); } /** @param {AppOptions} o */ -function shellCss(o) { +function appCss(o) { return lines( - ':root { color-scheme: dark; --toolbar-h: 44px; --accent: ' + o.site.accent + '; font: 14px/1.4 system-ui, sans-serif; }', - 'html, body { margin: 0; height: 100%; background: #0d0f14; color: #e8eaf0; }', - 'body { display: flex; flex-direction: column; overflow: hidden; }', - '.toolbar { flex: 0 0 var(--toolbar-h); display: flex; align-items: center; gap: 8px; padding: 0 10px; border-bottom: 1px solid #262a35; }', - '.chips { display: flex; gap: 4px; min-width: 0; flex: 1; overflow: hidden; }', - '.chip { padding: 3px 10px; border-radius: 999px; background: #1b1f29; white-space: nowrap; }', - '.chip:first-child { background: var(--accent); color: #000; font-weight: 600; }', - '.account { color: #9aa1b2; }', - 'button { font: inherit; color: inherit; background: #1b1f29; border: 1px solid #2f3442; border-radius: 8px; padding: 5px 12px; cursor: pointer; }', - '.plugins { display: grid; gap: 8px; padding: 16px; }', - '.plugins label { display: flex; gap: 8px; align-items: center; }', - '.status { padding: 8px 12px; background: #3a1418; color: #ffd7d7; }', - '.pane { flex: 1; min-height: 0; }', + "/* The app's own panel. The shell frame's styles come with it (dockview and the frame's CSS,", + ' bundled into dist/shell.css); its colors are the --wb-c-* tokens (Night Ink by default). */', + `:root { --app-accent: ${o.site.accent}; }`, + '.app-panel { height: 100%; box-sizing: border-box; overflow: auto; padding: 24px 28px; color: var(--wb-c-text, #eef0f7); background: var(--wb-c-ground, #07080c); font: 14px/1.45 system-ui, sans-serif; }', + '.app-panel h1 { margin: 0 0 16px; font-size: 18px; }', + '.app-row { display: flex; gap: 10px; align-items: flex-start; padding: 10px 0; border-bottom: 1px solid var(--wb-c-line, #1e2333); }', + '.app-row small { display: block; color: var(--wb-c-muted, #8a90a6); }', + '.app-panel button { margin-top: 16px; font: inherit; color: inherit; background: var(--wb-c-raised, #141823); border: 1px solid var(--wb-c-line, #1e2333); border-radius: 8px; padding: 6px 12px; cursor: pointer; }', + '.app-panel input { accent-color: var(--app-accent); }', + '.app-error { color: #ffb4b4; }', ); } @@ -1076,23 +1070,29 @@ function examplePlugin(o) { function buildMjs() { return lines( - '// Builds the two bundles: the page runtime (one IIFE that native code injects into tabs,', - '// bundled the way every wayBetter app ships it: `waybetter/build`) and the shell (the local page', - '// Tauri serves from dist/).', - "import { copyFileSync, mkdirSync } from 'node:fs';", + '// Builds the page runtime (one IIFE that native code injects into tabs) and the shell (the local', + '// page Tauri serves from dist/: the wayBetter shell frame, bundled with its styles), both with', + "// `waybetter/build`, and writes the shell's first-frame script.", + "import { copyFileSync, mkdirSync, writeFileSync } from 'node:fs';", "import { buildRuntime } from 'waybetter/build';", + "import { bootScript } from 'waybetter/shell/frame/boot';", '', "mkdirSync('dist', { recursive: true });", `await buildRuntime({ entry: 'src/runtime/main.ts', outfile: ${str(APP_OUTPUTS.runtime)} });`, 'await buildRuntime({', - " entry: 'src/shell/main.ts',", + " entry: 'src/shell/main.tsx',", " outfile: 'dist/shell.js',", " format: 'esm',", + " jsx: 'automatic',", ' minify: false,', + ' // CSS imports (dockview, the frame, app.css) are bundled into dist/shell.css.', ' inlineCss: false,', + " // Developer mode's syntax check loads acorn; this app does not switch developer mode on.", + " external: ['acorn'],", '});', + "writeFileSync('dist/boot.js', bootScript());", "copyFileSync('src/shell/index.html', 'dist/index.html');", - "copyFileSync('src/shell/shell.css', 'dist/shell.css');", + "copyFileSync('src-tauri/icons/icon.png', 'dist/icon.png');", "console.log('built dist/ and " + APP_OUTPUTS.runtime + "');", ); } @@ -1126,7 +1126,8 @@ function readme(o) { 'src/site.ts SiteAdapter: the page half of the adapter (PLACEHOLDER selectors)', 'src/address.ts address bar chips for the site\'s pages', 'src/runtime/main.ts page runtime: window.' + o.runtimeGlobal + ' (+ window.wayBetter), plugin API, account report', - 'src/shell/ the shell page: toolbar, plugins, tabs_sync', + 'src/shell/main.tsx the shell: the wayBetter shell frame (createShell) with this site\'s pages', + 'src/shell/Panel.tsx the app\'s own tab (its settings: the plugins)', 'plugins/example.plugin.js written (disabled) into a new plugins folder', 'src-tauri/src/site.rs SiteSpec: the native half (hosts, runtime global, account rules)', 'src-tauri/src/plugins.rs the plugin store (PluginHost)', @@ -1180,8 +1181,8 @@ export function appFiles(o) { release: 'waybetter release windows', 'release:macos': 'waybetter release macos', }, - dependencies: { waybetter: '^0.3.0' }, - devDependencies: { '@tauri-apps/cli': '^2.0.0', esbuild: '^0.25.0', typescript: '^5.9.0' }, + dependencies: { dockview: '^4.0.0', react: '^19.0.0', 'react-dom': '^19.0.0', waybetter: '^0.4.0' }, + devDependencies: { '@tauri-apps/cli': '^2.0.0', '@types/react': '^19.0.0', '@types/react-dom': '^19.0.0', esbuild: '^0.25.0', typescript: '^5.9.0' }, }; const tsconfig = { compilerOptions: { @@ -1190,6 +1191,8 @@ export function appFiles(o) { module: 'ESNext', moduleResolution: 'Bundler', allowImportingTsExtensions: true, + resolveJsonModule: true, + jsx: 'react-jsx', noEmit: true, strict: true, noUnusedLocals: true, @@ -1209,9 +1212,10 @@ export function appFiles(o) { { path: 'src/site.ts', content: siteTs(o) }, { path: 'src/address.ts', content: addressTs(o) }, { path: 'src/runtime/main.ts', content: runtimeTs() }, - { path: 'src/shell/main.ts', content: shellTs(o) }, + { path: 'src/shell/main.tsx', content: shellTs(o) }, + { path: 'src/shell/Panel.tsx', content: panelTsx() }, { path: 'src/shell/index.html', content: indexHtml(o) }, - { path: 'src/shell/shell.css', content: shellCss(o) }, + { path: 'src/shell/app.css', content: appCss(o) }, { path: 'src/tauri.d.ts', content: tauriTypes() }, { path: 'plugins/example.plugin.js', content: examplePlugin(o) }, { path: 'src-tauri/Cargo.toml', content: cargoToml(o) }, diff --git a/packages/create-waybetter/tests/create.test.mjs b/packages/create-waybetter/tests/create.test.mjs index a82df72..045fdc8 100644 --- a/packages/create-waybetter/tests/create.test.mjs +++ b/packages/create-waybetter/tests/create.test.mjs @@ -30,6 +30,11 @@ const PACKAGE = join(ROOT, 'packages/waybetter'); const TSC = join(ROOT, 'node_modules/typescript/bin/tsc'); const SCHEMA = JSON.parse(readFileSync(join(PACKAGE, 'theme.schema.json'), 'utf8')); const EXPORTS = Object.keys(JSON.parse(readFileSync(join(PACKAGE, 'package.json'), 'utf8')).exports); +/** A `waybetter/...` specifier is one of the package's exports (patterns like `./locales/*.json` included). */ +const exported = specifier => { + const sub = `./${specifier.slice('waybetter/'.length)}`; + return EXPORTS.some(key => (key.includes('*') ? sub.startsWith(key.slice(0, key.indexOf('*'))) && sub.endsWith(key.slice(key.indexOf('*') + 1)) : key === sub)); +}; const BIN = join(ROOT, 'packages/create-waybetter/bin/create-waybetter.js'); const work = mkdtempSync(join(tmpdir(), 'create-waybetter-')); @@ -322,8 +327,11 @@ test('app: every site skeleton is consistent across its native and page halves', assert.equal(caps[0].local, true); assert.deepEqual(JSON.parse(file('src-tauri', 'tauri.conf.json')).app.security.capabilities.sort(), ['shell', 'site-tab', 'tab-chrome']); // Every `waybetter/...` import is a published subpath of the package. - const sources = ['src/site.ts', 'src/address.ts', 'src/runtime/main.ts', 'src/shell/main.ts'].map(path => file(...path.split('/'))).join('\n'); - for (const [, specifier] of sources.matchAll(/from '(waybetter\/[^']+)'/g)) assert.ok(EXPORTS.includes(`./${specifier.slice('waybetter/'.length)}`), `${specifier} is exported`); + const sources = ['src/site.ts', 'src/address.ts', 'src/runtime/main.ts', 'src/shell/main.tsx', 'src/shell/Panel.tsx', 'scripts/build.mjs'].map(path => file(...path.split('/'))).join('\n'); + for (const [, specifier] of sources.matchAll(/from '(waybetter\/[^']+)'/g)) assert.ok(exported(specifier), `${specifier} is exported`); + // The shell is the framework's shell frame (createShell), not a copy; it needs the window calls. + assert.match(file('src', 'shell', 'main.tsx'), /createShell\(site, /); + assert.ok(caps[0].permissions.includes('core:window:allow-start-resize-dragging'), 'the frame\'s resize grips'); // Icons Tauri decodes at compile time. const png = readFileSync(join(work, dir, 'src-tauri', 'icons', 'icon.png')); assert.equal(png.subarray(1, 4).toString(), 'PNG'); @@ -358,6 +366,9 @@ test('app: the TypeScript typechecks against the waybetter package', { skip: !pa for (const site of APPS) { const dir = join(work, `app-${site.replace(/\W/g, '-')}`); link(dir, 'waybetter', PACKAGE); + // The shell's React types (the app's own dependencies; the framework's copies stand in). + link(dir, '@types/react', join(ROOT, 'node_modules/@types/react')); + link(dir, '@types/react-dom', join(ROOT, 'node_modules/@types/react-dom')); tsc(join(dir, 'tsconfig.json')); } });