// 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, useRef, 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 { openAppMenu } from './AppMenu.tsx'; import { invoke, listen } from './bridge.ts'; import { CommandPalette } from './CommandPalette.tsx'; import { DeckTabBadge, DeckView, focusColumn, runDeckCommand } from './DeckView.tsx'; import { openFind, stepFind } from './FindBar.tsx'; import { columnSourceUrl, 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 { initDiag } from './diag.ts'; import { installSafeMode } from './safeStore.ts'; import { hasFeature, site } from './site.ts'; import { flushLayer, flushSync, isWeb, loadLayout, newTabId, paneInfos, panelId, patchParams, resync, 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 { stepZoom, zoomTarget } from './zoomStore.ts'; import './shell.css'; type Placement = { referencePanel: string; direction: 'within' | 'right' | 'below' }; /** How long the startup cover waits, once the window is shown, for the visible site tabs to say they painted. */ export const STARTUP_CONTENT_WAIT = 8000; /** 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({ 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 | 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({ 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; /** The last web tab that was in front (Ctrl+F from the app's own tab searches it). */ let lastWeb: string | null = null; /** * The web tab Ctrl+F searches: the one given, else the last web tab that was in front and is still * on screen, else the first web tab on screen. The app's own tab has no page to search. */ function findTarget(panel: IDockviewPanel | undefined): IDockviewPanel | undefined { if (panel && isWeb(panel)) return panel; const shown = (shell.api?.panels ?? []).filter(item => isWeb(item) && item.api.isVisible); return shown.find(item => item.id === lastWeb) ?? shown[0]; } /** 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({ 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 { if (id !== undefined) { const found = findColumnTab(id); if (found) return found.deck.id; const params = shell.api?.getPanel(id)?.params as TabParams | undefined; return params?.kind === 'deck' ? params.deckId : null; } 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({ 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; case 'find': runShortcut('find'); break; case 'menu': openAppMenu({ keyboard: true }); break; } } function runShortcut(shortcut: string, id?: string) { const api = shell.api; if (!api) return; if (shortcut === 'command-palette') { togglePalette(); return; } // Alt+F / F10: the app menu, opened for the keyboard (pressed again, it closes). if (shortcut === 'app-menu') { openAppMenu({ keyboard: true, toggle: true }); return; } // Page zoom of the tab the keys were pressed in (a deck column zooms itself), else the pane in front. if (shortcut === 'zoom-in' || shortcut === 'zoom-out' || shortcut === 'zoom-reset') { void stepZoom(shortcut === 'zoom-in' ? 1 : shortcut === 'zoom-out' ? -1 : 0, id ?? zoomTarget()); return; } if (shortcut === 'deck-toggle') { toggleDeck(); return; } if (shortcut.startsWith('column-') || shortcut === 'deck-compose') { const deckId = deckFor(id); if (deckId) runDeckCommand(deckId, shortcut); return; } // Find in page in a deck column: that column's own find bar (the keys were pressed in it, or it is the // focused column of the deck in front). if (shortcut === 'find' || shortcut === 'find-next' || shortcut === 'find-previous') { const column = id && !api.getPanel(id) ? id : id === undefined && (api.activePanel?.params as TabParams | undefined)?.kind === 'deck' ? zoomTarget() : null; if (column && findColumnTab(column)?.column) { if (shortcut !== 'find') stepFind(column, shortcut === 'find-next' ? 1 : -1); else if (hasFeature('find')) openFind(column); 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 === undefined ? api.activePanel : api.getPanel(id); switch (shortcut) { case 'new-tab': addStart(); break; // Find in page: the find bar of that tab (the one the keys were pressed in, else the one in front). case 'find': { const target = findTarget(panel); if (target && hasFeature('find')) { target.api.setActive(); openFind(target.id); } break; } case 'find-next': case 'find-previous': { const target = findTarget(panel); if (target) stepFind(target.id, shortcut === 'find-next' ? 1 : -1); 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': if (id === undefined || 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 === 'f' && !event.shiftKey && hasFeature('find')) return 'find'; 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 (hasFeature('zoom')) { if (key === '=' || key === '+' || event.code === 'NumpadAdd') return 'zoom-in'; if (key === '-' || event.code === 'NumpadSubtract') return 'zoom-out'; if (key === '0' || event.code === 'Numpad0') return 'zoom-reset'; } } if (event.key === 'F3' && !mod && !event.altKey) return event.shiftKey ? 'find-previous' : 'find-next'; // The app menu, like a browser's: F10, and Alt+F where Alt is not a typing key (not on macOS). if (event.key === 'F10' && !mod && !event.altKey && !event.shiftKey) return 'app-menu'; if (event.altKey && !mod && !event.shiftKey && event.code === 'KeyF' && os !== 'macos') return 'app-menu'; 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 | 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) => ; const others = group.panels.filter(other => other.id !== panel.id && !(other.params as TabParams).pinned); return createPortal(
{ event.preventDefault(); onClose(); }}>
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')}
{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 && <>
{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(() => {}))} }
{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)}
, 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 ; if (params.kind === 'start') return ; if (params.kind === 'deck') return ; if (params.loading) return ; if (params.favicon && !broken) return setBroken(true)}/>; return ; } function Tab(props: IDockviewPanelHeaderProps) { 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
{ if (event.button === 1 && panel) { event.preventDefault(); closeTab(panel); } }}> {account && } {!params.pinned && {shown}} {params.kind === 'deck' && } {!params.pinned && }
; } function GroupActions(props: IDockviewHeaderActionsProps) { const t = useT(); return
; } function AppPanel(props: IDockviewPanelProps) { const section = props.params.section ? { name: props.params.section, nonce: props.params.nonce ?? 0 } : undefined; const Panel = site().panel.component; return
; } function StartPanel(props: IDockviewPanelProps) { return { props.api.updateParameters({ profile }); saveLayoutSoon(); }}/>; } /** Every tab closed: the dock shows the new-tab page itself. */ function Watermark() { return ; } 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 contentReadyTabs = useRef(new Set()); const [menu, setMenu] = useState(null); const [maximized, setMaximized] = useState(false); const [palette, setPalette] = useState(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); shell.shortcut = name => runShortcut(name); shell.run = runPalette; 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()); }, []); // Safe mode for this run (the host's flag): the titlebar says so and the chrome drops its theme. useEffect(() => (hasFeature('safeMode') ? installSafeMode() : undefined), []); // The site's own settings and events (e.g. X's Twitter/X wording). useEffect(() => site().start?.(), []); // Focus and layering diagnostics, when the app was started with them (`--diag`). useEffect(() => { void initDiag(); }, []); useEffect(() => { const unlisten = [ // A tab saw its account sign in or out (native code already saved it): refresh the switcher. listen('profiles-changed', ({ payload }) => setProfiles(payload)), listen<{ id: string; url?: string; title?: string; loading?: boolean; favicon?: string; focused?: boolean; unread?: number; contentReady?: boolean }>('tab-state', ({ payload }) => { const panel = shell.api?.getPanel(payload.id); const previousUrl = panel ? (panel.params as WebParams).url : decks.runtime.get(payload.id)?.url; if (payload.loading || (payload.url && previousUrl && payload.url !== previousUrl)) contentReadyTabs.current.delete(payload.id); if (payload.contentReady) contentReadyTabs.current.add(payload.id); const notifyStartup = () => window.dispatchEvent(new Event('bt-tab-startup-state')); if (!panel) { // A deck column (or a deck's compose dock) reports about its own webview. const found = findColumnTab(payload.id); if (!found) { notifyStartup(); 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')); } notifyStartup(); return; } // Another site must not keep the previous one's icon until (or unless) it reports its own. const favicon = payload.favicon ?? (payload.url && originOf(payload.url) !== originOf((panel.params as WebParams).url) ? '' : 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(); notifyStartup(); }), 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); }), // Native code builds every tab webview anew (safe mode switched): it needs the layout again. listen('tabs-rebuild', () => resync()), 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).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; // Establish the cover before any restore-triggered sync creates a visible native tab. // This also keeps the no-raise path from exposing X while a late still is captured. let coverActive = isTauri && !!site().deferWindowShow; let coverWatchdog: ReturnType | undefined; const releaseStartupCover = () => { if (!coverActive) return; coverActive = false; clearTimeout(coverWatchdog); setOverlay(-1); document.documentElement.classList.remove('bt-startup-cover'); }; if (coverActive) { document.documentElement.classList.add('bt-startup-cover'); setOverlay(1); // Guard shell initialization if settings or native startup never complete. // Once shell_ready succeeds, semantic X readiness owns this cover. coverWatchdog = setTimeout(releaseStartupCover, 10_000); } 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; if (event && isWeb(event)) lastWeb = 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(); if (isTauri && site().deferWindowShow) { // React commits dock placeholders after Dockview's ready callback. Keep the native // window hidden until their real bounds have been sent and its restored panes exist. for (let attempt = 0; attempt < 40; attempt++) { const visibleWeb = api.panels.filter(panel => isWeb(panel) && panel.api.isVisible); const webReady = visibleWeb.every(panel => { const element = shell.placeholders.get(panel.id); const rect = element?.getBoundingClientRect(); return !!rect && rect.width > 1 && rect.height > 1; }); // On the first run Dockview can report no visible panels for a frame after addPanel. // An empty `every()` must not reveal the native window before the loading shape mounts. const visibleDeck = api.panels.some(panel => (panel.params as TabParams | undefined)?.kind === 'deck' && panel.api.isVisible); const deckReady = api.panels.every(panel => { const params = panel.params as TabParams | undefined; if (params?.kind !== 'deck' || !panel.api.isVisible) return true; const deck = deckById(params.deckId); if (!deck) return true; return deck.columns.every(column => decks.ready.has(column.tabId)) && (deck.columns.length === 0 || deck.columns.some(column => { const element = shell.placeholders.get(column.tabId); const rect = element?.isConnected ? element.getBoundingClientRect() : null; return !!rect && rect.width > 1 && rect.height > 1; })); }); if ((visibleWeb.length > 0 || visibleDeck) && webReady && deckReady) break; await new Promise(resolve => setTimeout(resolve, 50)); } const origin = new URL(site().homeUrl).origin; const matchesSite = (url: string | null | undefined) => { try { return !!url && new URL(url).origin === origin; } catch { return false; } }; const visibleSiteIds = () => { const ids = new Set(); for (const panel of api.panels.filter(panel => panel.api.isVisible)) { const params = panel.params as TabParams; if (params.kind === 'web' && matchesSite(params.url)) ids.add(panel.id); if (params.kind === 'deck') { for (const column of deckById(params.deckId)?.columns ?? []) { const rect = shell.placeholders.get(column.tabId)?.getBoundingClientRect(); const url = decks.runtime.get(column.tabId)?.url ?? columnSourceUrl(column.source); if (decks.ready.has(column.tabId) && rect && rect.width > 1 && rect.height > 1 && matchesSite(url)) { ids.add(column.tabId); } } } } return ids; }; const coverIds = visibleSiteIds(); if (!coverIds.size) releaseStartupCover(); await flushLayer(); try { await flushSync(); // Give the shell webview two paint opportunities after its placeholder DOM is committed. await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve()))); await invoke('shell_ready'); // The global watchdog protects initialization. Once shown, the visible X tabs // keep the shell cover until content is ready or the tab is no longer visible. clearTimeout(coverWatchdog); if (coverIds.size && coverActive) { // Keep the shell's loading shape over the native tab until X has a real page. // The toolbar remains usable to reload a slow or offline page. await new Promise(resolve => { const done = () => { const visible = visibleSiteIds(); return [...coverIds].every(id => !visible.has(id) || contentReadyTabs.current.has(id)); }; if (done()) { resolve(); return; } const check = () => { if (done()) finish(); }; const finish = () => { clearInterval(poll); clearTimeout(limit); window.removeEventListener('bt-tab-startup-state', check); resolve(); }; // Dockview closes and deck layout changes do not always emit tab-state. const poll = setInterval(check, 200); // Never longer than this: a page that never says it painted (its script failed, the // engine held its frames back) shows as it is rather than behind a cover for good. const limit = setTimeout(finish, STARTUP_CONTENT_WAIT); window.addEventListener('bt-tab-startup-state', check); }); // The X DOM signal can precede its separate native WebView surface by a frame. // Give that surface one compositor turn before exposing it under the shell. await new Promise(resolve => setTimeout(resolve, 100)); } } finally { releaseStartupCover(); } } }; const chrome = frameless ? (maximized ? 'maximized' : 'restored') : 'native'; return
void onReady(event)} /> {palette && setPalette(null)}/>} {overlays.map((Overlay, index) => )} {media && setMedia(false)}/>} {menu && setMenu(null)}/>} {frameless && !maximized && }
; }