shell: the shell frame, createShell(site) (moved from wayBetter for X)

packages/shell/src/frame (waybetter/shell/frame): the whole shell of an app. An app describes its
site (ShellSite: names and pages, account rules, search, address chips and completions, its panel
tab, the new-tab page, palette items, deck column kinds and flags and an optional compose dock, the
media panel's composer rule, a theme store, overlays, the native features it serves) and passes
its Tauri API and i18n instance; createShell returns the root component.

- Shell.tsx: dockview host (tabs in the titlebar row, splits, drag-link drops, shortcuts, context
  menu, deck back-and-forth, session restore, workspace on start, overlay raise); state.ts (pane
  placeholders, tabs_sync one-in-flight via syncGate, shell_raise layer, profiles, layout).
- WebPanel (address bar), NewTabPage, CommandPalette + paletteModel (frame groups; site items),
  DeckView + AddColumnDialog + deckStore (site column kinds), PaneTheme + themeStore
  (createThemeStore over the app's ThemeAdapter) + chromeTheme (ChromeTheme input) + themeScopes,
  Titlebar + TitlebarExtras + icons + brand (wB mark data URI), AccountSwitcher + accountModel,
  workspaces + workspaceModel, backupModel, syncHost, devHost + devModel, pluginCommandStore,
  MediaPanel + mediaModel, searchInput, hooks, bridge (installPreviewMocks), i18n, boot.ts
  (bootScript: the first-frame boot.js), CSS themed with --wb-* tokens.
- paneModel: paneVisibility, raiseSupported, cssRgb; deckModel: isSourcePage.
- Includes the live-QA titlebar fix (dock ResizeObserver + rAF titlebar marks, dock sized by its
  insets).
- tests/frame.test.ts: every frame key has English and is used, palette order with a site,
  address fallback, layout gate, boot script, chrome variables, switcher rules, workspaces,
  deck settings with site flags.
- npm package 0.4.0: exports ./shell/frame, ./shell/frame/*, ./shell/frame/*.css (copied by the
  build); dockview and acorn optional peers; root devDependencies dockview, acorn.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
CRTkafa 2026-09-29 12:47:10 +07:00
parent 37e3d8e5fc
commit 60faed66be
49 changed files with 6442 additions and 6 deletions

View file

@ -0,0 +1,807 @@
// The shell: a trusted local page that fills the window and hosts the dock (dockview): tabs in the
// titlebar row, splits, the new-tab page, decks, the app's panel tab, link drags into the dock,
// keyboard shortcuts, overlays (menus, palette, dialogs) and session layout persistence. Each web
// tab is a native child webview that native code places over its pane (`tabs_sync`, state.ts).
import {
DockviewReact, themeDark,
type DockviewApi, type DockviewGroupPanel, type DockviewReadyEvent, type IDockviewHeaderActionsProps, type IDockviewPanel,
type IDockviewPanelHeaderProps, type IDockviewPanelProps, type SerializedDockview,
} from 'dockview';
import 'dockview/dist/styles/dockview.css';
import { useEffect, useState, type MouseEvent as ReactMouseEvent } from 'react';
import { createPortal } from 'react-dom';
import { carriesLink, dropUrl, placementFor, type Placement as DropPlacement } from '../linkDrop.ts';
import { besideGroup } from '../paneModel.ts';
import { tabProfile } from '../profileModel.ts';
import { accountAction } from './accountModel.ts';
import { accountLabel } from './AccountSwitcher.tsx';
import { invoke, listen } from './bridge.ts';
import { CommandPalette } from './CommandPalette.tsx';
import { DeckTabBadge, DeckView, focusColumn, runDeckCommand } from './DeckView.tsx';
import { createDeck, deckById, decks, findColumnTab, loadDecks, setRuntime } from './deckStore.ts';
import { installDevHost } from './devHost.ts';
import { useProfiles, useT } from './hooks.ts';
import { t } from './i18n.ts';
import { Icon, type IconName } from './icons.tsx';
import { MediaPanel } from './MediaPanel.tsx';
import { NewTabPage } from './NewTabPage.tsx';
import type { PaletteAction, PaletteContext } from './paletteModel.ts';
import { PaneThemeHost, openPaneTheme } from './PaneTheme.tsx';
import { focusedCommands, installPluginCommands, notePanelActive, refreshPluginNames, runPluginCommand } from './pluginCommandStore.ts';
import { hasFeature, site } from './site.ts';
import {
isWeb, loadLayout, newTabId, paneInfos, panelId, patchParams, saveLayoutSoon, scheduleSync, setOverlay, setProfiles, shell, tabAction,
type DeckParams, type PanelParams, type StartParams, type TabParams, type WebParams,
} from './state.ts';
import { installSyncHost } from './syncHost.ts';
import { ResizeGrips, Titlebar, titlebarContextMenu } from './Titlebar.tsx';
import { openWorkspaceSave } from './TitlebarExtras.tsx';
import { WebPanel } from './WebPanel.tsx';
import { frameless, isTauri, onMaximizedChange, os } from './windowBinding.ts';
import { loadWorkspaces, restoreWorkspace, workspaceList, workspaces } from './workspaces.ts';
import './shell.css';
type Placement = { referencePanel: string; direction: 'within' | 'right' | 'below' };
/** A development build (createShell's `dev`): the shell keeps the devtools shortcut. */
let devBuild = false;
export function setDevBuild(value: boolean) {
devBuild = value;
}
/** Opens a web tab. `profile` defaults to the switcher's active account. */
const originOf = (url: string) => { try { return new URL(url).origin; } catch { return ''; } };
function addWeb(url: string, placement?: Placement | DropPlacement, activate = true, profile = shell.profiles.active, besideOf?: string): IDockviewPanel | undefined {
const api = shell.api;
if (!api) return;
const valid = placement && ('referencePanel' in placement ? !!api.getPanel(placement.referencePanel)
: 'referenceGroup' in placement ? !!api.getGroup(placement.referenceGroup) : true);
const reference = valid ? placement : undefined;
return api.addPanel<WebParams>({
id: newTabId(),
component: 'web',
title: t('wb.shell.tab.new'),
params: { kind: 'web', url, profile: tabProfile(shell.profiles, profile).id, ...(besideOf ? { besideOf } : {}) },
position: reference ?? (api.activeGroup ? { referenceGroup: api.activeGroup, direction: 'within' } : undefined),
inactive: !activate,
});
}
/**
* The "pane" link setting: opens `url` in the side pane right of `source`'s group: split once, then
* reused. A link clicked inside a side pane stays in that pane instead of splitting again.
*/
function openBeside(url: string, source: IDockviewPanel, activate: boolean, profile?: string) {
const api = shell.api;
if (!api) return;
const origin = isWeb(source) ? (source.params as WebParams).besideOf : undefined;
if (origin) { addWeb(url, { referenceGroup: source.group.id, direction: 'within' }, activate, profile, origin); return; }
const box = (group: DockviewGroupPanel) => {
const rect = group.element.getBoundingClientRect();
const besideOf = group.panels.map(panel => (panel.params as Partial<WebParams> | undefined)?.besideOf).filter((id): id is string => !!id);
return { id: group.id, left: rect.left, top: rect.top, right: rect.right, bottom: rect.bottom, besideOf };
};
const target = besideGroup(box(source.group), api.groups.map(box));
addWeb(url, target ? { referenceGroup: target, direction: 'within' } : { referencePanel: source.id, direction: 'right' }, activate, profile, source.group.id);
}
/** Opens the new-tab page (shell-drawn, no webview) in the active group; links from it keep `profile`. */
function addStart(profile = shell.profiles.active, placement?: Placement): IDockviewPanel | undefined {
const api = shell.api;
if (!api) return;
const reference = placement && api.getPanel(placement.referencePanel) ? placement : undefined;
const panel = api.addPanel<StartParams>({
id: newTabId(),
component: 'start',
title: t('wb.shell.tab.new'),
params: { kind: 'start', profile: tabProfile(shell.profiles, profile).id },
position: reference ?? (api.activeGroup ? { referenceGroup: api.activeGroup, direction: 'within' } : undefined),
});
focusAddress(panel.id);
return panel;
}
/** A link chosen on a new-tab page opens in that page's place; the page itself goes away. */
function openFromStart(url: string, profile: string, startId?: string) {
const start = startId ? shell.api?.getPanel(startId) : undefined;
if (!start) { addWeb(url, undefined, true, profile); return; }
const group = start.group;
addWeb(url, { referenceGroup: group.id, direction: 'within', index: group.panels.indexOf(start) }, true, profile);
start.api.close();
}
/**
* Account switcher click: a visible pane of that account gets focus; otherwise its home feed (or the
* site's sign-in) opens in a new pane right of the focused one. `force` opens a tab in the focused
* group instead; `url` opens that page of the account (e.g. the site's sign-out) beside.
*/
function openAccount(profile: string, options: { force?: boolean; url?: string } = {}) {
const api = shell.api;
if (!api) return;
const active = api.activePanel;
const { homeUrl, loginUrl, isSiteUrl } = site();
const action = options.url
? { type: 'open' as const, url: options.url, profile: tabProfile(shell.profiles, profile).id, where: 'beside' as const }
: accountAction(shell.profiles, paneInfos(), active?.id, profile, { force: options.force, homeUrl, loginUrl, isSiteUrl });
if (action.type === 'focus') {
const panel = api.getPanel(action.paneId);
panel?.api.setActive();
if (panel) tabAction(panel.id, 'focus');
return;
}
const placement = active ? { referencePanel: active.id, direction: action.where === 'tab' ? 'within' as const : 'right' as const } : undefined;
addWeb(action.url, placement, true, action.profile);
}
// ---------------------------------------------------------------------------------------------
// Decks of site columns (DeckView.tsx; only with `site.deck`)
const deckPanelId = (deckId: string) => `deck-${deckId}`;
/** The last focused tab that is not a deck, for Ctrl+Shift+D back and forth. */
let lastNonDeck: string | null = null;
/** Opens (or focuses) a deck tab; with no deck yet, creates one. */
function openDeck(deckId?: string) {
const api = shell.api;
if (!api || !site().deck) return;
const deck = (deckId && deckById(deckId)) || decks.list[0] || createDeck(t('wb.shell.deck.default'));
const existing = api.getPanel(deckPanelId(deck.id));
if (existing) { existing.api.setActive(); return; }
api.addPanel<DeckParams>({
id: deckPanelId(deck.id), component: 'deck', title: deck.name, params: { kind: 'deck', deckId: deck.id },
position: api.activeGroup ? { referenceGroup: api.activeGroup, direction: 'within' } : undefined,
});
}
/** Ctrl+Shift+D: to the deck, and from the deck back to the tab you came from. */
function toggleDeck() {
const api = shell.api;
const active = api?.activePanel;
if (active && (active.params as TabParams).kind === 'deck') {
const back = lastNonDeck ? api?.getPanel(lastNonDeck) : undefined;
back?.api.setActive();
if (back && isWeb(back)) tabAction(back.id, 'focus');
return;
}
openDeck();
}
/** The deck a shortcut is about: the column's deck (keys pressed in a column), else the active deck tab. */
function deckFor(id?: string): string | null {
const found = id ? findColumnTab(id) : null;
if (found) return found.deck.id;
const params = shell.api?.activePanel?.params as TabParams | undefined;
return params?.kind === 'deck' ? params.deckId : null;
}
function openPanel(section?: string, from?: string) {
const api = shell.api;
if (!api) return;
const existing = api.getPanel(panelId());
const nonce = Date.now();
if (existing) {
if (section) existing.api.updateParameters({ section, nonce });
existing.api.setActive();
return;
}
// Open beside the site so both stay visible; a second group means split view.
const reference = from && api.getPanel(from) ? { referencePanel: from, direction: 'right' as const } : undefined;
api.addPanel<PanelParams>({ id: panelId(), component: 'panel', title: site().panel.title, params: { kind: 'panel', section, nonce }, position: reference });
}
function closeTab(panel: IDockviewPanel) {
if ((panel.params as TabParams).pinned) return;
if (isWeb(panel)) { const { url, profile } = panel.params as WebParams; shell.closed.push({ url, profile, title: panel.api.title || undefined }); }
panel.api.close();
}
export function splitTab(panel: IDockviewPanel, direction: 'right' | 'below') {
// A lone tab cannot be moved out of its group, so split opens a copy of it instead.
if (panel.group.panels.length > 1) {
panel.api.moveTo({ group: panel.group, position: direction === 'right' ? 'right' : 'bottom' });
} else if (isWeb(panel)) {
const { url, profile } = panel.params as WebParams;
addWeb(url, { referencePanel: panel.id, direction }, true, profile);
}
}
function cycleTabs(step: number) {
const group = shell.api?.activeGroup;
if (!group || group.panels.length < 2) return;
const index = group.panels.findIndex(panel => panel.id === group.activePanel?.id);
group.panels[(index + step + group.panels.length) % group.panels.length]?.api.setActive();
}
function focusAddress(id: string) {
invoke('shell_focus').catch(() => {});
requestAnimationFrame(() => window.dispatchEvent(new CustomEvent('bt-focus-address', { detail: id })));
}
let togglePalette: () => void = () => {};
let toggleMedia: () => void = () => {};
function paletteContext(): PaletteContext {
const panels = shell.api?.panels.filter(isWeb) ?? [];
const deck = site().deck;
return {
tabs: panels.map(panel => ({ id: panel.id, title: panel.api.title ?? '', url: (panel.params as WebParams).url, favicon: (panel.params as WebParams).favicon })),
profiles: shell.profiles.profiles.map(({ id, name, color }) => ({ id, name, color })),
activeProfile: shell.profiles.active,
decks: deck ? decks.list.map(item => ({
id: item.id, name: item.name,
columns: item.columns.map(column => ({ id: column.id, title: deck.title(column.source, column.title).title, profile: column.profile })),
})) : undefined,
activeDeck: (() => { const params = shell.api?.activePanel?.params as TabParams | undefined; return params?.kind === 'deck' ? params.deckId : undefined; })(),
workspaces: hasFeature('workspaces') ? workspaceList() : undefined,
activeWorkspace: workspaces.active ?? undefined,
// Plugin commands of the focused site tab (they run there).
commands: focusedCommands(),
};
}
/** Palette actions only navigate; account changes are completed by the user on the site's own pages. */
function runPalette(action: PaletteAction) {
const api = shell.api;
if (!api) return;
switch (action.type) {
case 'focus-tab': api.getPanel(action.id)?.api.setActive(); break;
case 'new-tab': shell.newTab(action.profile); break;
case 'panel': openPanel(action.section, api.activePanel?.id); break;
case 'open': addWeb(action.url); break;
case 'media': toggleMedia(); break;
case 'deck': openDeck(action.deckId); break;
case 'deck-new': openDeck(createDeck(`Deck ${decks.list.length + 1}`).id); break;
case 'deck-add': openDeck(action.deckId); requestAnimationFrame(() => window.dispatchEvent(new CustomEvent('bt-deck-add', { detail: action.deckId }))); break;
case 'deck-focus': openDeck(action.deckId); requestAnimationFrame(() => focusColumn(action.deckId, action.columnId)); break;
case 'plugin-command': runPluginCommand(action.tab, action.command); break;
case 'workspace': void restoreWorkspace(action.id); break;
case 'workspace-save': openWorkspaceSave(); break;
}
}
function runShortcut(shortcut: string, id?: string) {
const api = shell.api;
if (!api) return;
if (shortcut === 'command-palette') { togglePalette(); return; }
if (shortcut === 'deck-toggle') { toggleDeck(); return; }
if (shortcut.startsWith('column-') || shortcut === 'deck-compose') {
const deckId = deckFor(id);
if (deckId) runDeckCommand(deckId, shortcut);
return;
}
// A browser shortcut pressed inside a deck column acts on its deck tab.
if (id && !api.getPanel(id) && findColumnTab(id)) id = deckPanelId(findColumnTab(id)!.deck.id);
const panel = (id && api.getPanel(id)) || api.activePanel;
switch (shortcut) {
case 'new-tab': addStart(); break;
case 'close-tab': if (panel) closeTab(panel); break;
case 'reopen-tab': { const tab = shell.closed.pop(); if (tab) addWeb(tab.url, undefined, true, tab.profile); break; }
case 'focus-address': if (panel && (isWeb(panel) || (panel.params as TabParams).kind === 'start')) focusAddress(panel.id); break;
case 'next-tab': cycleTabs(1); break;
case 'prev-tab': cycleTabs(-1); break;
case 'reload': case 'hard-reload': if (panel && isWeb(panel)) tabAction(panel.id, 'reload'); break;
case 'back': if (panel && isWeb(panel)) tabAction(panel.id, 'back'); break;
case 'forward': if (panel && isWeb(panel)) tabAction(panel.id, 'forward'); break;
case 'split-right': if (panel) splitTab(panel, 'right'); break;
case 'split-down': if (panel) splitTab(panel, 'below'); break;
case 'open-panel': openPanel(undefined, panel?.id); break;
case 'media-panel': toggleMedia(); break;
}
}
const editable = (target: EventTarget | null) => {
const el = target as HTMLElement | null;
return !!el && (el.isContentEditable || /^(input|textarea|select)$/i.test(el.tagName));
};
/** Deck keys pressed in the shell itself (a column header, the deck bar) while a deck tab is active. */
function deckShortcutFor(event: KeyboardEvent): string | null {
const mod = event.ctrlKey || event.metaKey;
if (mod && event.shiftKey && !event.altKey && event.code === 'KeyD') return 'deck-toggle';
if ((shell.api?.activePanel?.params as TabParams | undefined)?.kind !== 'deck' || editable(event.target)) return null;
if (event.ctrlKey && event.altKey && !event.shiftKey && event.code === 'KeyN') return 'deck-compose';
if (event.altKey && !mod && !event.shiftKey) {
const digit = /^Digit([1-9])$/.exec(event.code);
if (digit) return `column-${digit[1]}`;
if (event.key === 'PageUp') return 'column-page-prev';
if (event.key === 'PageDown') return 'column-page-next';
if (event.code === 'KeyR') return 'column-mark-read';
if (event.code === 'KeyU') return 'column-jump-unread';
}
if (!mod && !event.altKey && event.key === '[') return 'column-prev';
if (!mod && !event.altKey && event.key === ']') return 'column-next';
return null;
}
function shortcutFor(event: KeyboardEvent): string | null {
const deck = site().deck ? deckShortcutFor(event) : null;
if (deck) return deck;
const mod = event.ctrlKey || event.metaKey;
const key = event.key.toLowerCase();
if (mod && !event.altKey) {
if (key === 't') return event.shiftKey ? 'reopen-tab' : 'new-tab';
if (key === 'w') return event.shiftKey ? 'open-panel' : 'close-tab';
if (key === 'l') return 'focus-address';
if (key === 'g' && event.shiftKey) return 'media-panel';
if (key === 'k' && !event.shiftKey) return 'command-palette';
if (key === 'tab') return event.shiftKey ? 'prev-tab' : 'next-tab';
if (key === 'r') return 'reload';
if (event.code === 'Backslash' || event.code === 'IntlBackslash') return event.shiftKey ? 'split-down' : 'split-right';
}
if (event.altKey && !mod && key === 'arrowleft') return 'back';
if (event.altKey && !mod && key === 'arrowright') return 'forward';
return null;
}
// ---------------------------------------------------------------------------------------------
// Link drags: a link dragged out of a tab (or in from another app) drops as a new tab or split.
/**
* While active, the native tab webviews are hidden so the OS drag reaches the shell and dockview's
* drop zones. `internal`: a drag that started in the shell itself (tab moves, list reordering).
*/
const linkDrag = {
active: false, internal: false, url: null as string | null, from: undefined as string | undefined,
lastOver: 0, sawOver: false, blockedUntil: 0, timer: undefined as ReturnType<typeof setInterval> | undefined,
};
function beginLinkDrag(from?: string, url?: string) {
if (linkDrag.internal) return;
if (!linkDrag.active) {
// A tab that keeps announcing drags that never reach the shell cannot keep the panes hidden.
if (Date.now() < linkDrag.blockedUntil) return;
Object.assign(linkDrag, { active: true, sawOver: false, lastOver: Date.now(), url: null, from: undefined });
setOverlay(1);
document.querySelector('.bt-shell')?.classList.add('bt-shell--link-drag');
// Esc or a drop outside the window may end the drag without any event here.
linkDrag.timer = setInterval(() => { if (Date.now() - linkDrag.lastOver > 1500) endLinkDrag(true); }, 250);
}
if (url) { linkDrag.url = url; linkDrag.from = from; }
}
function endLinkDrag(timedOut = false) {
if (!linkDrag.active) return;
clearInterval(linkDrag.timer);
if (timedOut && !linkDrag.sawOver) linkDrag.blockedUntil = Date.now() + 5000;
Object.assign(linkDrag, { active: false, url: null, from: undefined, timer: undefined });
document.querySelector('.bt-shell')?.classList.remove('bt-shell--link-drag');
setOverlay(-1);
}
/** Opens the dropped link where it was dropped, in the source tab's account (else the active one). */
function dropLink(event: DragEvent, placement: DropPlacement | undefined) {
const url = dropUrl(type => event.dataTransfer?.getData(type) ?? '', linkDrag.url);
const source = linkDrag.from ? shell.api?.getPanel(linkDrag.from) : undefined;
const profile = source && isWeb(source) ? (source.params as WebParams).profile : shell.profiles.active;
endLinkDrag();
if (url) addWeb(url, placement, true, profile);
}
const dragTypes = (event: DragEvent) => Array.from(event.dataTransfer?.types ?? []);
// ---------------------------------------------------------------------------------------------
type Menu = { x: number; y: number; panel: IDockviewPanel };
let openMenu: (menu: Menu) => void = () => {};
function ContextMenu({ menu, onClose }: { menu: Menu; onClose: () => void }) {
const t = useT();
const { panel } = menu;
const params = panel.params as TabParams;
const web = params.kind === 'web' ? params : null;
const group = panel.group;
useEffect(() => {
setOverlay(1);
const close = () => onClose();
const onKey = (event: KeyboardEvent) => { if (event.key === 'Escape') onClose(); };
window.addEventListener('blur', close);
window.addEventListener('keydown', onKey);
return () => { setOverlay(-1); window.removeEventListener('blur', close); window.removeEventListener('keydown', onKey); };
}, []);
const item = (label: string, icon: IconName, action: () => void, disabled = false, keys?: string) =>
<button role="menuitem" disabled={disabled} onClick={() => { onClose(); action(); }}>
<Icon name={icon}/><span className="bt-menu-label">{label}</span>{keys && <span className="bt-menu-keys">{keys}</span>}
</button>;
const others = group.panels.filter(other => other.id !== panel.id && !(other.params as TabParams).pinned);
return createPortal(<div className="bt-menu-backdrop" onMouseDown={onClose} onContextMenu={event => { event.preventDefault(); onClose(); }}>
<div className="bt-menu bt-pop" role="menu" style={{ left: Math.max(8, Math.min(menu.x, window.innerWidth - 248)), top: Math.max(8, Math.min(menu.y, window.innerHeight - 360)) }} onMouseDown={event => event.stopPropagation()}>
{item(params.pinned ? t('wb.shell.menu.unpin') : t('wb.shell.menu.pin'), params.pinned ? 'unpin' : 'pin', () => {
panel.api.updateParameters({ pinned: !params.pinned });
if (!params.pinned) panel.api.moveTo({ group, index: 0 });
saveLayoutSoon();
})}
{web && item(t('wb.shell.menu.duplicate'), 'duplicate', () => addWeb(web.url, { referencePanel: panel.id, direction: 'within' }, true, web.profile))}
{web && item(t('wb.shell.menu.reload'), 'reload', () => tabAction(panel.id, 'reload'), false, 'Ctrl R')}
<hr/>
{item(t('wb.shell.menu.splitRight'), 'split', () => splitTab(panel, 'right'), !web && group.panels.length < 2, 'Ctrl \\')}
{item(t('wb.shell.menu.splitDown'), 'splitDown', () => splitTab(panel, 'below'), !web && group.panels.length < 2, 'Ctrl ⇧ \\')}
{web && <>
<hr/>
{site().themes && item(t('wb.shell.menu.paneTheme'), 'palette', () => openPaneTheme({ id: panel.id, profile: tabProfile(shell.profiles, web.profile).id, x: menu.x, y: menu.y }))}
{item(t('wb.shell.menu.copyLink'), 'copy', () => void navigator.clipboard?.writeText(web.url))}
{item(t('wb.shell.menu.openBrowser'), 'external', () => invoke('open_external_url', { url: web.url }).catch(() => {}))}
</>}
<hr/>
{item(t('wb.shell.menu.close'), 'close', () => closeTab(panel), !!params.pinned, 'Ctrl W')}
{item(t('wb.shell.menu.closeOthers'), 'closeOthers', () => others.forEach(closeTab), others.length === 0)}
</div>
</div>, document.body);
}
function Favicon({ params }: { params: TabParams }) {
const t = useT();
const [broken, setBroken] = useState(false);
useEffect(() => setBroken(false), [params.kind === 'web' ? params.favicon : '']);
if (params.kind === 'panel') return <img className="bt-favicon" src={site().logo} alt=""/>;
if (params.kind === 'start') return <Icon name="sparkle" className="bt-favicon bt-favicon--glyph"/>;
if (params.kind === 'deck') return <Icon name="grid" className="bt-favicon bt-favicon--glyph bt-favicon--deck"/>;
if (params.loading) return <span className="bt-favicon bt-spinner" role="img" aria-label={t('wb.common.loading')}/>;
if (params.favicon && !broken) return <img key={params.favicon} className="bt-favicon bt-favicon--img" src={params.favicon} alt="" onError={() => setBroken(true)}/>;
return <Icon name="globe" className="bt-favicon bt-favicon--glyph"/>;
}
function Tab(props: IDockviewPanelHeaderProps<TabParams>) {
const t = useT();
const profiles = useProfiles();
const [title, setTitle] = useState(props.api.title ?? '');
useEffect(() => { const sub = props.api.onDidTitleChange(event => setTitle(event.title)); return () => sub.dispose(); }, [props.api]);
const params = props.params;
const panel = shell.api?.getPanel(props.api.id);
const onContextMenu = (event: ReactMouseEvent) => { event.preventDefault(); if (panel) openMenu({ x: event.clientX, y: event.clientY, panel }); };
const account = params.kind !== 'panel' && params.kind !== 'deck' && profiles.profiles.length > 1 ? tabProfile(profiles, params.profile) : null;
const accountName = account ? `${accountLabel(account).title}${account.account ? ` (${site().accounts.handlePrefix}${account.account.handle})` : ''}` : '';
const loading = params.kind === 'web' && !!params.loading;
// Titles saved by older sessions (or before the page reports one) said "New tab" in English.
const shown = params.kind === 'start' || !title || title === 'New tab' ? t('wb.shell.tab.new') : title;
return <div className={`bt-tab${params.pinned ? ' pinned bt-tab--pinned' : ''}${loading ? ' bt-tab--loading' : ''}`}
title={account ? `${shown} · ${accountName}` : shown} onContextMenu={onContextMenu}
onAuxClick={event => { if (event.button === 1 && panel) { event.preventDefault(); closeTab(panel); } }}>
<span className="bt-tab-icon">
<Favicon params={params}/>
{account && <span className="bt-tab-account" style={{ background: account.color }} aria-label={t('wb.shell.tab.account', { name: accountName })}/>}
</span>
{!params.pinned && <span className="bt-tab-title">{shown}</span>}
{params.kind === 'deck' && <DeckTabBadge deckId={params.deckId}/>}
{!params.pinned && <button className="bt-tab-close" title={t('wb.shell.tab.closeTitle')} aria-label={t('wb.shell.menu.close')} onPointerDown={event => event.stopPropagation()} onClick={event => { event.stopPropagation(); if (panel) closeTab(panel); }}>
<Icon name="close"/></button>}
</div>;
}
function GroupActions(props: IDockviewHeaderActionsProps) {
const t = useT();
return <div className="bt-group-actions">
<button className="bt-icon bt-newtab" title={t('wb.shell.tab.newTitle')} aria-label={t('wb.shell.tab.new')} onClick={() => addStart(undefined, { referencePanel: props.group.activePanel?.id ?? '', direction: 'within' })}>
<Icon name="plus"/></button>
</div>;
}
function AppPanel(props: IDockviewPanelProps<PanelParams>) {
const section = props.params.section ? { name: props.params.section, nonce: props.params.nonce ?? 0 } : undefined;
const Panel = site().panel.component;
return <div className="bt-panel"><Panel section={section}/></div>;
}
function StartPanel(props: IDockviewPanelProps<StartParams>) {
return <NewTabPage panelId={props.api.id} profile={props.params.profile}
onProfile={profile => { props.api.updateParameters({ profile }); saveLayoutSoon(); }}/>;
}
/** Every tab closed: the dock shows the new-tab page itself. */
function Watermark() {
return <NewTabPage/>;
}
const components = { web: WebPanel, panel: AppPanel, start: StartPanel, deck: DeckView };
/**
* Groups whose top edge touches the dock top host their tabs in the titlebar row: their header is
* TITLEBAR_H tall and transparent, the empty part drags the window. The leftmost one leaves room
* for the logo, the rightmost one for the caption buttons.
*/
function markTitlebarGroups() {
const api = shell.api;
const dock = document.querySelector('.bt-dock');
if (!api || !dock) return;
const bounds = dock.getBoundingClientRect();
document.querySelector('.bt-shell')?.classList.toggle('bt-shell--empty', api.groups.length === 0);
for (const group of api.groups) {
const el = group.element;
const rect = el.getBoundingClientRect();
const top = group.api.location.type === 'grid' && Math.abs(rect.top - bounds.top) < 1;
el.classList.toggle('bt-group--in-titlebar', top);
el.classList.toggle('bt-group--tb-left', top && Math.abs(rect.left - bounds.left) < 1);
el.classList.toggle('bt-group--tb-right', top && Math.abs(rect.right - bounds.right) < 1);
const voidContainer = el.querySelector('.dv-void-container');
if (voidContainer) {
if (top) voidContainer.setAttribute('data-tauri-drag-region', '');
else voidContainer.removeAttribute('data-tauri-drag-region');
}
}
}
export default function Shell() {
const [menu, setMenu] = useState<Menu | null>(null);
const [maximized, setMaximized] = useState(false);
const [palette, setPalette] = useState<PaletteContext | null>(null);
const [media, setMedia] = useState(false);
const { overlays = [] } = site();
openMenu = setMenu;
togglePalette = () => { invoke('shell_focus').catch(() => {}); void refreshPluginNames(); setPalette(open => open ? null : paletteContext()); };
toggleMedia = () => { if (isTauri && site().media) setMedia(open => !open); };
shell.split = (id, direction) => { const panel = shell.api?.getPanel(id); if (panel) splitTab(panel, direction); };
shell.openPanel = from => openPanel(undefined, from);
shell.newTab = profile => { addStart(profile); };
shell.openFromStart = openFromStart;
shell.openAccount = openAccount;
shell.openUrl = (url, profile) => { addWeb(url, undefined, true, profile); };
shell.openPanelSection = section => openPanel(section, shell.api?.activePanel?.id);
useEffect(() => {
document.documentElement.dataset.os = os;
if (!isTauri) return;
const unlisten = onMaximizedChange(value => setMaximized(value));
return () => { unlisten.then(dispose => dispose()).catch(() => {}); };
}, []);
// Maximize/restore changes the resize-band inset: re-send the tab rectangles once laid out.
useEffect(() => { requestAnimationFrame(() => { markTitlebarGroups(); scheduleSync(); }); }, [maximized]);
// Plugin palette commands, developer mode (live reload) and encrypted folder sync.
useEffect(() => {
if (!isTauri) return;
const off = [
hasFeature('pluginCommands') ? installPluginCommands() : null,
hasFeature('developer') ? installDevHost() : null,
hasFeature('sync') ? installSyncHost() : null,
].filter((dispose): dispose is () => void => !!dispose);
return () => off.forEach(dispose => dispose());
}, []);
// The site's own settings and events (e.g. X's Twitter/X wording).
useEffect(() => site().start?.(), []);
useEffect(() => {
const unlisten = [
// A tab saw its account sign in or out (native code already saved it): refresh the switcher.
listen<unknown>('profiles-changed', ({ payload }) => setProfiles(payload)),
listen<{ id: string; url?: string; title?: string; loading?: boolean; favicon?: string; focused?: boolean; unread?: number }>('tab-state', ({ payload }) => {
const panel = shell.api?.getPanel(payload.id);
if (!panel) {
// A deck column (or a deck's compose dock) reports about its own webview.
const found = findColumnTab(payload.id);
if (!found) return;
setRuntime(payload.id, { url: payload.url, title: payload.title, loading: payload.loading, unread: payload.unread });
if (found.compose) site().deck?.compose?.navigated?.(payload.id, payload.url, payload.loading);
if (payload.focused && found.column && decks.focus.get(found.deck.id) !== found.column.id) {
decks.focus.set(found.deck.id, found.column.id);
window.dispatchEvent(new CustomEvent('bt-decks'));
}
return;
}
// Another site must not keep the previous one's icon until (or unless) it reports its own.
const previous = (panel.params as WebParams).url;
const favicon = payload.favicon ?? (payload.url && originOf(payload.url) !== originOf(previous) ? '' : undefined);
patchParams(panel, { url: payload.url, loading: payload.loading, favicon, title: payload.title });
if (payload.title !== undefined) panel.api.setTitle(payload.title || (panel.params as WebParams).url);
// A click into a visible pane makes it the active tab. A tab that is no longer shown (a link it
// opened just took its place in the group) reports a late focus too: it must not jump back.
if (payload.focused && !panel.api.isActive && panel.api.isVisible) panel.api.setActive();
saveLayoutSoon();
}),
listen<{ url: string; from?: string; background: boolean; beside?: boolean }>('tab-open', ({ payload }) => {
// Links opened from a tab stay in that tab's account; they never jump to another login.
const source = payload.from ? shell.api?.getPanel(payload.from) : undefined;
const column = payload.from && !source ? findColumnTab(payload.from) : null;
const profile = source && isWeb(source) ? (source.params as WebParams).profile
: column ? (column.column?.profile ?? decks.compose.get(column.deck.id)?.profile ?? shell.profiles.active) : shell.profiles.active;
if (column) { addWeb(payload.url, undefined, !payload.background, profile); return; }
if (payload.beside && source) { openBeside(payload.url, source, !payload.background, profile); return; }
addWeb(payload.url, payload.from ? { referencePanel: payload.from, direction: 'within' } : undefined, !payload.background, profile);
}),
listen<{ id: string; shortcut: string }>('tab-shortcut', ({ payload }) => runShortcut(payload.shortcut, payload.id)),
listen<{ from: string; section?: string }>('open-panel', ({ payload }) => openPanel(payload.section, payload.from)),
// A tab's link drag: `start` carries the natively validated link, `enter` is an external drag.
listen<{ id: string; phase: 'start' | 'enter' | 'end'; url?: string }>('link-drag', ({ payload }) => {
if (payload.phase === 'end') endLinkDrag();
else if (shell.api?.getPanel(payload.id)) beginLinkDrag(payload.id, payload.url);
}),
];
const onKey = (event: KeyboardEvent) => {
const shortcut = shortcutFor(event);
if (shortcut) {
// Leave text editing shortcuts (e.g. Ctrl+L/T in inputs) alone except tab management.
event.preventDefault();
runShortcut(shortcut);
return;
}
if (!isTauri) return;
// Browser-engine keys that make no sense in the shell itself (the tab webviews handle their own).
const mod = event.ctrlKey || event.metaKey;
const key = event.key.toLowerCase();
if (event.key === 'F5') { event.preventDefault(); runShortcut('reload'); return; }
if (mod && !event.altKey && (key === 'p' || key === 'f')) { event.preventDefault(); return; }
if (mod && event.shiftKey && key === 'i' && !devBuild) event.preventDefault();
};
const onContextMenu = (event: MouseEvent) => {
const target = event.target as Element | null;
if (target?.closest?.('input, textarea')) return;
if (frameless && target?.closest?.('.bt-group--in-titlebar .dv-void-container')) { titlebarContextMenu(event); return; }
event.preventDefault();
};
const onMouseUp = (event: MouseEvent) => {
if (event.button !== 3 && event.button !== 4) return;
event.preventDefault();
runShortcut(event.button === 3 ? 'back' : 'forward');
};
// The app's settings ask for a deck tab.
const onDeckOpen = (event: Event) => openDeck((event as CustomEvent<string | undefined>).detail);
window.addEventListener('bt-deck-open', onDeckOpen);
if (isTauri) {
window.addEventListener('contextmenu', onContextMenu);
window.addEventListener('mouseup', onMouseUp);
}
const relayout = () => { markTitlebarGroups(); scheduleSync(); };
// Native webviews cover drop zones; hide them for the duration of a tab drag.
let dragging = false;
const dragStart = () => { linkDrag.internal = true; endLinkDrag(); if (!dragging) { dragging = true; setOverlay(1); } };
const dragEnd = () => { linkDrag.internal = false; if (dragging) { dragging = false; setOverlay(-1); } };
// A link dragged in from another app straight onto the shell chrome.
const dragEnter = (event: DragEvent) => { if (!linkDrag.internal && carriesLink(dragTypes(event))) beginLinkDrag(); };
const dragOver = (event: DragEvent) => {
if (!linkDrag.active) return;
linkDrag.lastOver = Date.now();
linkDrag.sawOver = true;
// Anywhere outside dockview's zones (e.g. the titlebar of an empty dock) still accepts: new tab.
event.preventDefault();
if (event.dataTransfer) event.dataTransfer.dropEffect = 'copy';
};
// Dockview stops propagation of drops it handled; this only sees drops outside its zones.
const drop = (event: DragEvent) => { if (linkDrag.active) { event.preventDefault(); dropLink(event, undefined); } };
window.addEventListener('keydown', onKey);
window.addEventListener('resize', relayout);
// `resize` fires before dockview has laid its groups out at the new size (its own
// ResizeObserver does that), so the titlebar marks read stale rects there: the group at the
// right edge lost `bt-group--tb-right` and its tabs ran under the titlebar buttons. The dock's
// size changes are marked again one frame later, once dockview's own observer has laid out
// (measured live: marking inside the same observer pass still read the old rects).
const dockElement = document.querySelector('.bt-dock');
let markFrame = 0;
const dockResize = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(() => {
cancelAnimationFrame(markFrame);
markFrame = requestAnimationFrame(markTitlebarGroups);
});
if (dockElement) dockResize?.observe(dockElement);
document.addEventListener('dragstart', dragStart, true);
document.addEventListener('dragend', dragEnd, true);
document.addEventListener('drop', dragEnd, true);
document.addEventListener('dragenter', dragEnter, true);
document.addEventListener('dragover', dragOver);
document.addEventListener('drop', drop);
return () => {
endLinkDrag();
unlisten.forEach(promise => promise.then(dispose => dispose(), () => {}));
window.removeEventListener('keydown', onKey);
window.removeEventListener('resize', relayout);
dockResize?.disconnect();
cancelAnimationFrame(markFrame);
window.removeEventListener('bt-deck-open', onDeckOpen);
window.removeEventListener('contextmenu', onContextMenu);
window.removeEventListener('mouseup', onMouseUp);
document.removeEventListener('dragstart', dragStart, true);
document.removeEventListener('dragend', dragEnd, true);
document.removeEventListener('drop', dragEnd, true);
document.removeEventListener('dragenter', dragEnter, true);
document.removeEventListener('dragover', dragOver);
document.removeEventListener('drop', drop);
};
}, []);
const onReady = async (event: DockviewReadyEvent) => {
const api: DockviewApi = event.api;
shell.api = api;
// Chrome colors and fonts follow the theme; panes with their own theme follow theirs.
site().themes?.attachDock(api);
let restoreTabs = true;
try {
const settings = await invoke<{ homeUrl: string; restoreTabs: boolean }>('settings_get');
shell.homeUrl = settings.homeUrl;
restoreTabs = settings.restoreTabs;
} catch { /* Defaults. */ }
// Profiles before the first tabs_sync, so restored tabs open in their own account right away.
try { setProfiles(await invoke('profiles_get')); } catch { /* Default profile only. */ }
loadDecks(shell.profiles.profiles.map(profile => profile.id), shell.profiles.active);
// A workspace chosen to open on start replaces the previous session's layout.
const startWorkspace = isTauri && hasFeature('workspaces') ? (await loadWorkspaces()).default : null;
const saved = startWorkspace ? null : loadLayout() as SerializedDockview | null;
if (startWorkspace) await restoreWorkspace(startWorkspace);
shell.restoring = true;
try {
if (saved) {
api.fromJSON(saved);
// Layouts saved before a rename still carry the old panel title.
api.getPanel(panelId())?.api.setTitle(site().panel.title);
for (const panel of [...api.panels]) {
const params = panel.params as TabParams;
if (params.kind === 'web') patchParams(panel, { loading: false });
// Without session restore only pinned tabs come back.
if (!restoreTabs && !params.pinned) panel.api.close();
}
}
} catch (error) {
console.warn('[shell] layout restore failed', error);
api.clear();
} finally {
shell.restoring = false;
}
// A restored deck tab counts: deck sessions come back to their deck, not a new Home tab.
if (!api.panels.some(panel => isWeb(panel) || (panel.params as TabParams | undefined)?.kind === 'deck')) addWeb(shell.homeUrl);
api.onDidLayoutChange(() => { markTitlebarGroups(); scheduleSync(); saveLayoutSoon(); });
api.onDidAddGroup(() => requestAnimationFrame(markTitlebarGroups));
api.onDidRemoveGroup(() => requestAnimationFrame(markTitlebarGroups));
// The titlebar switcher highlights the focused pane's account.
const paneChanged = () => window.dispatchEvent(new CustomEvent('bt-active-pane'));
api.onDidActivePanelChange(event => {
if (event && (event.params as TabParams | undefined)?.kind !== 'deck') lastNonDeck = event.id;
notePanelActive(event?.id);
scheduleSync();
paneChanged();
});
// A renamed deck renames its tab.
window.addEventListener('bt-decks', () => {
for (const panel of api.panels) {
const params = panel.params as TabParams;
if (params.kind !== 'deck') continue;
const name = deckById(params.deckId)?.name;
if (name && panel.api.title !== name) panel.api.setTitle(name);
}
});
api.onDidLayoutChange(paneChanged);
paneChanged();
api.onDidRemovePanel(scheduleSync);
api.onDidAddPanel(scheduleSync);
// Dockview's overflow list (the "N more tabs" button) is a shell popover: hide the tab webviews while it is open.
const popover = document.querySelector('.bt-dock .dv-popover-anchor');
if (popover) {
let shown = false;
new MutationObserver(() => {
const open = popover.childElementCount > 0;
if (open !== shown) { shown = open; setOverlay(open ? 1 : -1); }
}).observe(popover, { childList: true });
}
// External (non-panel) drags that carry a link get dockview's split/tab drop zones.
api.onUnhandledDragOverEvent(event => {
if (!linkDrag.internal && (linkDrag.active || carriesLink(dragTypes(event.nativeEvent)))) event.accept();
});
api.onDidDrop(event => {
if (linkDrag.internal || !(linkDrag.active || carriesLink(dragTypes(event.nativeEvent)))) return;
const tabIndex = event.panel && event.group ? event.group.panels.indexOf(event.panel) : -1;
dropLink(event.nativeEvent, placementFor({ position: event.position, groupId: event.group?.id, tabIndex: tabIndex >= 0 ? tabIndex : undefined }));
});
markTitlebarGroups();
scheduleSync();
};
const chrome = frameless ? (maximized ? 'maximized' : 'restored') : 'native';
return <div className="bt-shell" data-chrome={chrome}>
<Titlebar maximized={maximized}/>
<DockviewReact
className="bt-dock"
theme={themeDark}
components={components}
defaultTabComponent={Tab}
rightHeaderActionsComponent={GroupActions}
watermarkComponent={Watermark}
onReady={event => void onReady(event)}
/>
{palette && <CommandPalette context={palette} onRun={runPalette} onClose={() => setPalette(null)}/>}
{overlays.map((Overlay, index) => <Overlay key={index}/>)}
{media && <MediaPanel onClose={() => setMedia(false)}/>}
{menu && <ContextMenu menu={menu} onClose={() => setMenu(null)}/>}
<PaneThemeHost/>
{frameless && !maximized && <ResizeGrips/>}
</div>;
}