fix(shell): coordinate startup cover and tab stills

This commit is contained in:
CRTkafa 2026-09-30 12:25:46 +07:00
parent 01f2ec0417
commit 5a2e959763
13 changed files with 442 additions and 52 deletions

View file

@ -9,7 +9,7 @@ import {
type IDockviewPanelHeaderProps, type IDockviewPanelProps, type SerializedDockview,
} from 'dockview';
import 'dockview/dist/styles/dockview.css';
import { useEffect, useState, type MouseEvent as ReactMouseEvent } from 'react';
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';
@ -19,7 +19,7 @@ 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 { 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';
@ -31,7 +31,7 @@ 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,
flushLayer, flushSync, 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';
@ -170,8 +170,12 @@ function toggleDeck() {
/** 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;
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;
}
@ -273,7 +277,7 @@ function runShortcut(shortcut: string, id?: string) {
}
// 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;
const panel = id === undefined ? api.activePanel : api.getPanel(id);
switch (shortcut) {
case 'new-tab': addStart(); break;
case 'close-tab': if (panel) closeTab(panel); break;
@ -286,7 +290,7 @@ function runShortcut(shortcut: string, id?: string) {
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 'open-panel': if (id === undefined || panel) openPanel(undefined, panel?.id); break;
case 'media-panel': toggleMedia(); break;
}
}
@ -456,7 +460,7 @@ function Tab(props: IDockviewPanelHeaderProps<TabParams>) {
// 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}
data-panel-id={props.api.id} 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}/>
@ -522,6 +526,7 @@ function markTitlebarGroups() {
}
export default function Shell() {
const contentReadyTabs = useRef(new Set<string>());
const [menu, setMenu] = useState<Menu | null>(null);
const [maximized, setMaximized] = useState(false);
const [palette, setPalette] = useState<PaletteContext | null>(null);
@ -565,29 +570,34 @@ export default function Shell() {
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 }) => {
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) return;
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 previous = (panel.params as WebParams).url;
const favicon = payload.favicon ?? (payload.url && originOf(payload.url) !== originOf(previous) ? '' : undefined);
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.
@ -699,6 +709,24 @@ export default function Shell() {
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<typeof setTimeout> | 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);
@ -782,6 +810,93 @@ export default function Shell() {
});
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<string>();
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<void>(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<void>(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);
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);
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';