diff --git a/bun.lock b/bun.lock index 3ad4194..2cb0fb2 100644 --- a/bun.lock +++ b/bun.lock @@ -8,6 +8,8 @@ "@types/node": "^24.0.0", "@types/react": "^19.0.0", "@types/react-dom": "^19.0.0", + "acorn": "^8.15.0", + "dockview": "^4", "typescript": "^5.9.0", }, }, @@ -28,11 +30,28 @@ }, "packages/waybetter": { "name": "waybetter", - "version": "0.2.0", + "version": "0.3.0", + "bin": { + "waybetter": "bin/waybetter.mjs", + }, "devDependencies": { "@types/node": "^24.0.0", "typescript": "^5.9.0", }, + "peerDependencies": { + "acorn": ">=8.0.0", + "dockview": ">=4.0.0", + "esbuild": ">=0.20.0", + "react": ">=18.0.0", + "react-dom": ">=18.0.0", + }, + "optionalPeers": [ + "acorn", + "dockview", + "esbuild", + "react", + "react-dom", + ], }, }, "packages": { @@ -46,10 +65,18 @@ "@waybetter/shell": ["@waybetter/shell@workspace:packages/shell"], + "acorn": ["acorn@8.18.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ=="], + "create-waybetter": ["create-waybetter@workspace:packages/create-waybetter"], "csstype": ["csstype@3.2.3", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="], + "dockview": ["dockview@4.13.1", "", { "dependencies": { "dockview-core": "^4.13.1" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-K8xnYt3Rvkx8MYKHaEsb8aFaPyQclKRRkXS9JcpQPZUgqxumTLnSidgdd6uIfzEps6yJsXoZGQGJ9PtcaKyDcQ=="], + + "dockview-core": ["dockview-core@4.13.1", "", {}, "sha512-+7vR0ZEoL8CNck6NqDVUMqBT22niwBu5CMMI137dZ3c8NDc7c5Si+3dGEqQgM4lNtHBLAtvypo1C4p21J2wkiQ=="], + + "react": ["react@19.3.0", "", {}, "sha512-E8LUcbtBWt20bbl2YoHfx4ZDBdxVTfOKtCZn9cDSJ4l6/nuoApcpIBcj47t2wZoVX8g2ZHuMHbiShgCR1T5Sog=="], + "typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="], "undici-types": ["undici-types@7.24.6", "", {}, "sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg=="], diff --git a/package.json b/package.json index 871971e..2b918a5 100644 --- a/package.json +++ b/package.json @@ -26,6 +26,8 @@ "@types/node": "^24.0.0", "@types/react": "^19.0.0", "@types/react-dom": "^19.0.0", + "acorn": "^8.15.0", + "dockview": "^4", "typescript": "^5.9.0" }, "engines": { diff --git a/packages/shell/README.md b/packages/shell/README.md index fae9571..699bca0 100644 --- a/packages/shell/README.md +++ b/packages/shell/README.md @@ -1,3 +1,6 @@ # shell (internal) -Sources of `waybetter/shell/*`. Published as part of the [`waybetter`](../waybetter/README.md) package; not published on its own. +Sources of `waybetter/shell/*`: the shell models, the Store screens and the shell frame +(`src/frame`, `createShell`). Published as part of the [`waybetter`](../waybetter/README.md) package; +not published on its own. The repository README's "The shell frame" section describes what an app +supplies. diff --git a/packages/shell/src/deckModel.ts b/packages/shell/src/deckModel.ts index a57b9cf..9721a02 100644 --- a/packages/shell/src/deckModel.ts +++ b/packages/shell/src/deckModel.ts @@ -296,3 +296,19 @@ export function moveColumn(columns: readonly T[], id: next.splice(target, 0, item!); return next; } + +/** + * A column still shows its source page (origin, path with the trailing slash ignored, and query); + * otherwise it navigated away (a post, a profile) and its header offers the way back. The page + * runtime uses the same rule (runtime/column.ts `isSourcePage`). + */ +export function isSourcePage(href: string, source: string): boolean { + try { + const a = new URL(href); + const b = new URL(source); + const path = (url: URL) => url.pathname.replace(/\/+$/, '') || '/'; + return a.origin === b.origin && path(a) === path(b) && a.search === b.search; + } catch { + return false; + } +} diff --git a/packages/shell/src/frame/AccountSwitcher.tsx b/packages/shell/src/frame/AccountSwitcher.tsx new file mode 100644 index 0000000..d75a0c7 --- /dev/null +++ b/packages/shell/src/frame/AccountSwitcher.tsx @@ -0,0 +1,275 @@ +import { useEffect, useRef, useState, type KeyboardEvent as ReactKeyboardEvent, type MouseEvent as ReactMouseEvent } from 'react'; +import { createPortal } from 'react-dom'; +import { DEFAULT_PROFILE, accountLabel as accountLabelCore, removeProfile, tabProfile, type Profile, type ProfileSettings } from '../profileModel.ts'; +import { accountAction, addAccountProfile, focusedAccount, moveFocus, setDefaultAccount, tabsByAccount } from './accountModel.ts'; +import { invoke } from './bridge.ts'; +import { decks, forgetColumn, saveDecks } from './deckStore.ts'; +import { usePaneTick, useProfiles, useT } from './hooks.ts'; +import { t, tx } from './i18n.ts'; +import { Avatar, Icon } from './icons.tsx'; +import { site } from './site.ts'; +import { flushSync, paneInfos, setOverlay, setProfiles, shell } from './state.ts'; +import { isTauri } from './windowBinding.ts'; +import './accountSwitcher.css'; + +export { useProfiles } from './hooks.ts'; + +/** What the switcher shows for a profile: the site login once seen, the profile name before. */ +export function accountLabel(profile: Profile) { + return accountLabelCore(profile, site().accounts, key => tx(key, undefined, '') || undefined); +} + +/** Saves natively (Rust validates and owns the data directories); the preview keeps it in memory. */ +export async function saveProfiles(next: ProfileSettings): Promise { + if (!isTauri) { setProfiles(next); return; } + setProfiles(await invoke('profiles_set', { settings: next })); +} + +export const ProfileDot = ({ color, title }: { color: string; title?: string }) => + ; + +export function openTabs(profile: string) { + return tabsByAccount(shell.profiles, paneInfos()).get(profile)?.length ?? 0; +} + +/** The site's own sign-in page for that account, in a new pane beside the focused one. */ +export function signIn(profile: string) { + shell.openAccount(profile, { url: site().loginUrl }); +} + +/** "Add account": a fresh login (its own cookies and storage) whose sign-in opens in a new pane. */ +export async function addAccount(settings: ProfileSettings): Promise { + const next = addAccountProfile(settings); + await saveProfiles(next.settings); + signIn(next.profile); +} + +/** + * Removes an account after the user confirmed: its tabs close first (native code refuses to delete + * the data directory of a profile that still has a tab), then the list is saved and native code + * deletes that login's data on this computer. Never called without the explicit confirm step. + */ +export async function removeAccount(settings: ProfileSettings, id: string): Promise { + if (id === DEFAULT_PROFILE) return; + const tabs = tabsByAccount(settings, paneInfos()).get(id) ?? []; + for (const tab of tabs) shell.api?.getPanel(tab)?.api.close(); + // Start pages of that account fall back to the default one. + for (const panel of shell.api?.panels ?? []) { + const params = panel.params as { kind?: string; profile?: string } | undefined; + if (params?.kind === 'start' && params.profile === id) panel.api.updateParameters({ profile: DEFAULT_PROFILE }); + } + // Deck columns of that account go too (each is a webview in its profile); a compose dock in it closes. + let deckChanged = false; + decks.list = decks.list.map(deck => { + const gone = deck.columns.filter(column => column.profile === id); + if (!gone.length) return deck; + deckChanged = true; + for (const column of gone) forgetColumn(column.tabId); + return { ...deck, columns: deck.columns.filter(column => column.profile !== id) }; + }); + for (const [deckId, compose] of decks.compose) if (compose.profile === id) { decks.compose.delete(deckId); deckChanged = true; } + if (deckChanged) saveDecks(); + // dockview drops closed panels from `api.panels` synchronously (checked in the harness, whose + // profiles_set refuses like native code), so this sync no longer lists the account's tabs. + await flushSync(); + try { + await saveProfiles(removeProfile(settings, id)); + } catch (failure) { + const message = String(failure); + if (/PROFILE: close this profile's tabs/.test(message)) throw new Error(t('wb.acct.notRemoved')); + throw failure; + } +} + +export const AccountAvatar = ({ profile, size }: { profile: Profile; size: number }) => + ; + +/** "Name (@handle)" for titles and labels. */ +export function accountName(profile: Profile): string { + return `${accountLabel(profile).title}${profile.account ? ` (${site().accounts.handlePrefix}${profile.account.handle})` : ''}`; +} + +type RowMenu = { id: string; confirm?: boolean }; + +/** + * Titlebar account switcher. Every entry is a separate site login on this computer (its own + * WebView data directory) that shows the account the site itself reports as signed in there. + * + * One click shows the account: a visible pane of it gets focus, otherwise its home feed (or the + * site's sign-in) opens in a new pane beside the focused one. Shift/Ctrl-click opens a new tab + * instead. Everything else ("Open in new tab", "Use for new tabs", sign out, remove) is in the + * row's "…" menu. The button shows the focused pane's account. + */ +export function AccountSwitcher() { + const t = useT(); + const settings = useProfiles(); + usePaneTick(); + const [open, setOpen] = useState(false); + const [rowMenu, setRowMenu] = useState(null); + const [error, setError] = useState(''); + const [anchor, setAnchor] = useState<{ top: number; right: number }>({ top: 44, right: 12 }); + const button = useRef(null); + const menu = useRef(null); + const panes = paneInfos(); + const activeId = shell.api?.activePanel?.id; + const focused = focusedAccount(settings, panes, activeId); + const tabs = tabsByAccount(settings, panes); + const multi = settings.profiles.length > 1; + const { name: siteName, homeUrl, loginUrl, logoutUrl, isSiteUrl, accounts: rules } = site(); + const handle = (profile: Profile) => `${rules.handlePrefix}${profile.account!.handle}`; + + useEffect(() => { + if (!open) return; + // Native tab webviews would cover the menu. + setOverlay(1); + const onBlur = () => close(); + // Escape while focus is outside the menu (a click on its padding); inside, onMenuKey handles it. + const onKey = (event: KeyboardEvent) => { if (event.key === 'Escape' && !menu.current?.contains(event.target as Node)) close(true); }; + window.addEventListener('blur', onBlur); + window.addEventListener('keydown', onKey); + // Start on the focused pane's account. + // Two lookups: a selector list matches in document order, so it would always pick the first row. + requestAnimationFrame(() => (menu.current?.querySelector('.bt-acct-row.is-focused .bt-acct-main') + ?? menu.current?.querySelector('.bt-acct-main'))?.focus()); + return () => { setOverlay(-1); window.removeEventListener('blur', onBlur); window.removeEventListener('keydown', onKey); }; + }, [open]); + + // The row menu takes focus when it opens; closing it returns focus to its row. + const lastRow = useRef(null); + useEffect(() => { + if (!open) return; + if (rowMenu) { + lastRow.current = rowMenu.id; + requestAnimationFrame(() => menu.current?.querySelector(rowMenu.confirm ? '.bt-acct-confirm button' : '.bt-acct-sub button:not(:disabled)')?.focus()); + } else if (lastRow.current) { + const id = lastRow.current; + lastRow.current = null; + requestAnimationFrame(() => menu.current?.querySelector(`.bt-acct-row[data-profile="${id}"] .bt-acct-main`)?.focus()); + } + }, [rowMenu, open]); + + function close(refocus = false) { + setOpen(false); setRowMenu(null); setError(''); + if (refocus) button.current?.focus(); + } + function toggle() { + const rect = button.current?.getBoundingClientRect(); + if (rect) setAnchor({ top: Math.round(rect.bottom + 6), right: Math.max(8, Math.round(window.innerWidth - rect.right)) }); + setRowMenu(null); setError(''); + setOpen(value => !value); + } + + async function run(action: () => Promise) { + setError(''); + try { await action(); return true; } + catch (failure) { setError(String(failure).replace(/^Error: /, '')); return false; } + } + + /** The main click: focus or open beside; Shift/Ctrl (or "Open in new tab") forces a tab. */ + function pick(profile: string, force = false) { + close(); + shell.openAccount(profile, { force }); + } + + const onMainClick = (profile: string) => (event: ReactMouseEvent) => pick(profile, event.shiftKey || event.ctrlKey || event.metaKey); + + function onMenuKey(event: ReactKeyboardEvent) { + const target = event.target as HTMLElement; + const inSub = !!target.closest('.bt-acct-sub, .bt-acct-confirm'); + if (event.key === 'Escape') { + event.preventDefault(); event.stopPropagation(); + if (rowMenu) setRowMenu(null); else close(true); + return; + } + if (event.key === 'Tab') { event.preventDefault(); close(true); return; } + const scope = inSub ? target.closest('.bt-acct-sub, .bt-acct-confirm')! : menu.current!; + const items = Array.from(scope.querySelectorAll(inSub ? 'button:not(:disabled)' : '.bt-acct-main, .bt-acct-add')); + if (['ArrowDown', 'ArrowUp', 'Home', 'End'].includes(event.key)) { + event.preventDefault(); + items[moveFocus(items.indexOf(target), event.key, items.length)]?.focus(); + return; + } + const row = target.closest('.bt-acct-row')?.dataset.profile; + if (!inSub && row && (event.key === 'ArrowRight' || event.key === 'ContextMenu' || (event.key === 'F10' && event.shiftKey))) { + event.preventDefault(); setRowMenu({ id: row }); return; + } + if (inSub && event.key === 'ArrowLeft') { event.preventDefault(); setRowMenu(null); return; } + // Keyboard Enter/Space clicks carry no modifiers: Shift/Ctrl+Enter forces a new tab here. + if (!inSub && row && event.key === 'Enter' && (event.shiftKey || event.ctrlKey || event.metaKey)) { event.preventDefault(); pick(row, true); } + } + + const buttonLabel = t('wb.acct.buttonLabel', { name: accountName(focused) }); + return <> + + {open && createPortal(
close()} onContextMenu={event => { event.preventDefault(); close(); }}> +
event.stopPropagation()} onKeyDown={onMenuKey}> +
+ {t('wb.acct.title')} + {t('wb.acct.headBefore')} {t('wb.acct.shift')} {t('wb.acct.headAfter')} +
+ {settings.profiles.map(profile => { + const label = accountLabel(profile); + const count = tabs.get(profile.id)?.length ?? 0; + const isFocused = profile.id === focused.id; + const isDefault = profile.id === settings.active; + const action = accountAction(settings, panes, activeId, profile.id, { homeUrl, loginUrl, isSiteUrl }); + const hint = action.type === 'focus' ? (action.paneId === activeId ? t('wb.acct.thisPane') : t('wb.acct.goToPane')) : label.state === 'signed-in' ? t('wb.acct.openBeside') : t('wb.acct.signInBeside'); + const status = label.state === 'signed-in' ? handle(profile) : label.state === 'signed-out' ? t('wb.acct.signedOut', { handle: handle(profile) }) : label.detail; + const sub = rowMenu?.id === profile.id ? rowMenu : null; + return
{ event.preventDefault(); event.stopPropagation(); setRowMenu({ id: profile.id }); }}> +
+ + +
+ {sub && !sub.confirm &&
+ + + {label.state === 'signed-in' + ? + : } + {profile.id !== DEFAULT_PROFILE && } +
} + {sub?.confirm &&
+ {t('wb.acct.removeConfirm', { name: accountName(profile), tabs: count })} +
+ + +
+
} +
; + })} +
+ + {error &&
{error}
} +
+
, document.body)} + ; +} diff --git a/packages/shell/src/frame/AddColumnDialog.tsx b/packages/shell/src/frame/AddColumnDialog.tsx new file mode 100644 index 0000000..00a09da --- /dev/null +++ b/packages/shell/src/frame/AddColumnDialog.tsx @@ -0,0 +1,118 @@ +// "Add column": pick what the column shows (the site's column kinds: `site.deck.kinds`), which +// account it runs in and, for kinds that take one, the value. The shell rises above the tab +// webviews (or hides them) while it is open, so it draws above them. + +import { useEffect, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from 'react'; +import { createPortal } from 'react-dom'; +import { tabProfile } from '../profileModel.ts'; +import { AccountAvatar, accountLabel } from './AccountSwitcher.tsx'; +import { decks, type Deck, type DeckColumn } from './deckStore.ts'; +import { useProfiles, useT } from './hooks.ts'; +import { Icon } from './icons.tsx'; +import { site, type DeckSite } from './site.ts'; +import { setOverlay } from './state.ts'; + +type Input = Pick; + +export function AddColumnDialog({ deck, onClose, onAdd }: { deck: Deck; onClose(): void; onAdd(input: Input): void }) { + const t = useT(); + const profiles = useProfiles(); + const spec = site().deck as DeckSite; + const types = spec.kinds; + const focused = deck.columns.find(c => c.id === decks.focus.get(deck.id)); + const [kind, setKind] = useState(types[0]?.kind ?? ''); + const [profile, setProfile] = useState(tabProfile(profiles, focused?.profile ?? profiles.active).id); + const [value, setValue] = useState(''); + const [caret, setCaret] = useState(0); + const field = useRef(null); + const dialog = useRef(null); + const type = types.find(item => item.kind === kind)!; + const parsed = type.value ? spec.parseValue(kind, value) : ''; + const valid = parsed !== null && (!type.value || parsed !== '') && !!spec.urlFor({ kind, ...(parsed ? { value: parsed } : {}) }); + const completer = spec.completer?.(kind) ?? null; + const chips = completer ? completer.suggest(value, caret, 6) : []; + const handlePrefix = site().accounts.handlePrefix; + + useEffect(() => { + setOverlay(1); + const onBlur = () => onClose(); + window.addEventListener('blur', onBlur); + (dialog.current?.querySelector('[aria-checked="true"]') as HTMLElement | null)?.focus(); + return () => { setOverlay(-1); window.removeEventListener('blur', onBlur); }; + }, []); + useEffect(() => { if (type.value) requestAnimationFrame(() => field.current?.focus()); }, [kind]); + + const submit = () => { + if (!valid) { field.current?.focus(); return; } + onAdd({ profile, source: parsed ? { kind, value: parsed } : { kind } }); + }; + const onKey = (event: ReactKeyboardEvent) => { + if (event.key === 'Escape') { event.preventDefault(); onClose(); } + else if (event.key === 'Enter' && !(event.target as HTMLElement).matches('button')) { event.preventDefault(); submit(); } + else if (['ArrowRight', 'ArrowLeft', 'ArrowDown', 'ArrowUp'].includes(event.key) && (event.target as HTMLElement).getAttribute('role') === 'radio' + && (event.target as HTMLElement).closest('.bt-addcol-types')) { + event.preventDefault(); + const index = types.findIndex(item => item.kind === kind); + const step = event.key === 'ArrowRight' ? 1 : event.key === 'ArrowLeft' ? -1 : event.key === 'ArrowDown' ? 4 : -4; + const next = types[(index + step + types.length) % types.length]!; + setKind(next.kind); + requestAnimationFrame(() => (dialog.current?.querySelector(`[data-kind="${next.kind}"]`) as HTMLElement | null)?.focus()); + } + }; + const acceptChip = (insert: string) => { + if (!completer) return; + const next = completer.apply(value, caret, insert); + setValue(next.text); + setCaret(next.caret); + requestAnimationFrame(() => { field.current?.focus(); field.current?.setSelectionRange(next.caret, next.caret); }); + }; + + return createPortal(
+
event.stopPropagation()} onKeyDown={onKey}> +
+

{t('wb.deck.addColumn')}

+ {t('wb.addcol.to', { deck: deck.name })} + +
+
+ {types.map(item => )} +
+ {type.value &&
+ +
+ + { setValue(event.target.value); setCaret(event.target.selectionStart ?? event.target.value.length); }} + onSelect={() => setCaret(field.current?.selectionStart ?? value.length)} + onKeyDown={event => { if (event.key === 'Tab' && !event.shiftKey && chips[0]) { event.preventDefault(); acceptChip(chips[0].insert); } }}/> +
+ {chips.length > 0 &&
+ {chips.map((chip, index) => )} +
} + {value && parsed === null &&

{spec.invalid(kind)}

} +
} +
+ {t('wb.addcol.account')} +
+ {profiles.profiles.map(p => )} +
+
+
+ ↵ {t('wb.addcol.add')}Esc {t('wb.addcol.close')} + + + +
+
+
, document.body); +} diff --git a/packages/shell/src/frame/CommandPalette.tsx b/packages/shell/src/frame/CommandPalette.tsx new file mode 100644 index 0000000..c8cf1e3 --- /dev/null +++ b/packages/shell/src/frame/CommandPalette.tsx @@ -0,0 +1,116 @@ +import { useEffect, useMemo, useRef, useState, type KeyboardEvent as ReactKeyboardEvent, type ReactNode } from 'react'; +import { createPortal } from 'react-dom'; +import { useT } from './hooks.ts'; +import { t } from './i18n.ts'; +import { Avatar, Icon } from './icons.tsx'; +import { buildItems, moveSelection, type PaletteAction, type PaletteContext, type PaletteItem } from './paletteModel.ts'; +import { hasFeature, site } from './site.ts'; +import { setOverlay } from './state.ts'; + +/** Leading visual for a palette row: the tab's favicon, the account avatar or the item's glyph. */ +function leading(item: PaletteItem, context: PaletteContext): ReactNode { + const [kind, ...rest] = item.id.split(':'); + const key = rest.join(':'); + if (kind === 'tab') { + const favicon = context.tabs.find(tab => `tab:${tab.id}` === item.id)?.favicon; + return favicon ? : ; + } + if (kind === 'profile') { + const profile = context.profiles.find(p => p.id === key); + return ; + } + if (item.icon) return ; + if (kind === 'deck' || kind === 'deck-new') return ; + if (kind === 'deck-add') return ; + if (kind === 'deck-focus') return ; + if (kind === 'ws') return ; + if (kind === 'ws-save') return ; + return ; +} + +const shortHint = (hint: string) => hint.replace(/^https?:\/\/(www\.)?/, ''); + +/** The frame's group names are translated; the site names its own groups; plugin groups are the plugins' names. */ +const GROUPS: Record = { + Tabs: 'wb.palette.group.tabs', Deck: 'wb.palette.group.deck', Workspaces: 'wb.palette.group.workspaces', Profiles: 'wb.palette.group.profiles', +}; +const groupLabel = (group: string) => (GROUPS[group] ? t(GROUPS[group]!) : site().palette.groupLabel?.(group) ?? group); + +/** Ctrl+K palette. The shell rises above the tab webviews (or hides them) while it is open. */ +export function CommandPalette({ context, onRun, onClose }: { context: PaletteContext; onRun: (action: PaletteAction) => void; onClose: () => void }) { + const [query, setQuery] = useState(''); + const [selected, setSelected] = useState(0); + const input = useRef(null); + const list = useRef(null); + const items = useMemo(() => { + const { palette, product, deck, media } = site(); + return buildItems(context, query, { site: palette, product, decks: !!deck, media: !!media, workspaces: hasFeature('workspaces') }); + }, [context, query]); + + useEffect(() => { + setOverlay(1); + input.current?.focus(); + const close = () => onClose(); + window.addEventListener('blur', close); + return () => { setOverlay(-1); window.removeEventListener('blur', close); }; + }, []); + useEffect(() => setSelected(0), [query]); + useEffect(() => { list.current?.querySelector('[aria-selected="true"]')?.scrollIntoView({ block: 'nearest' }); }, [selected]); + + const run = (index: number) => { + const item = items[index]; + if (!item) return; + if (item.action.type === 'complete') { setQuery(item.action.text); input.current?.focus(); return; } + onClose(); + onRun(item.action); + }; + const onKeyDown = (event: ReactKeyboardEvent) => { + if (event.nativeEvent.isComposing) return; + // Ctrl+K again closes, like the shortcut that opened it. + if ((event.ctrlKey || event.metaKey) && !event.altKey && !event.shiftKey && event.key.toLowerCase() === 'k') { event.preventDefault(); event.stopPropagation(); onClose(); return; } + if (event.key === 'ArrowDown' || (event.key === 'Tab' && !event.shiftKey)) { event.preventDefault(); setSelected(i => moveSelection(i, 1, items.length)); } + else if (event.key === 'ArrowUp' || (event.key === 'Tab' && event.shiftKey)) { event.preventDefault(); setSelected(i => moveSelection(i, -1, items.length)); } + else if (event.key === 'Home' && event.ctrlKey) { event.preventDefault(); setSelected(0); } + else if (event.key === 'End' && event.ctrlKey) { event.preventDefault(); setSelected(Math.max(0, items.length - 1)); } + else if (event.key === 'Enter') { event.preventDefault(); run(selected); } + else if (event.key === 'Escape') { event.preventDefault(); onClose(); } + event.stopPropagation(); + }; + + const tr = useT(); + let lastGroup = ''; + return createPortal(
+
event.stopPropagation()} onKeyDown={onKeyDown}> +
+ + setQuery(event.target.value)} role="combobox" aria-expanded="true" aria-controls="bt-palette-list" + aria-activedescendant={items[selected] ? `bt-pal-${selected}` : undefined} spellCheck={false}/> + Esc +
+
+ {items.length === 0 &&
{tr('wb.palette.none')}
} + {items.map((item, index) => { + const heading = item.group !== lastGroup ? item.group : null; + lastGroup = item.group; + return
+ {heading &&
{groupLabel(heading)}
} +
{ if (selected !== index) setSelected(index); }} onClick={() => run(index)}> + {leading(item, context)} + {item.label} + {item.hint && {shortHint(item.hint)}} + +
+
; + })} +
+
+ ↑↓ {tr('wb.palette.navigate')} + ↵ {tr('wb.common.open')} + {tr('wb.web.tabKey')} {tr('wb.palette.next')} + CtrlK {tr('wb.common.close')} +
+
+
, document.body); +} diff --git a/packages/shell/src/frame/DeckView.tsx b/packages/shell/src/frame/DeckView.tsx new file mode 100644 index 0000000..aa57d44 --- /dev/null +++ b/packages/shell/src/frame/DeckView.tsx @@ -0,0 +1,369 @@ +// Decks: site columns side by side in one shell tab (dockview component `deck`). The shell draws +// the deck bar and a header per column; each column's body is a placeholder that a real site tab +// webview (its own account profile) covers, laid out by state.ts. Paging, not pixel scrolling: a +// page holds as many whole columns as fit; the others are parked off-page. Every request and every +// action in a column is the site's own; the shell only navigates, focuses and configures columns +// (native `column_configure`). The kinds of columns are the site's (`site.deck`). + +import type { IDockviewPanelProps } from 'dockview'; +import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type MouseEvent as ReactMouseEvent, type ReactNode } from 'react'; +import { createPortal } from 'react-dom'; +import { COLUMN_GAP, COLUMN_WIDTHS, isSourcePage, layoutColumns, pageOf, unreadTotal } from '../deckModel.ts'; +import { tabProfile } from '../profileModel.ts'; +import { AccountAvatar, accountName } from './AccountSwitcher.tsx'; +import { AddColumnDialog } from './AddColumnDialog.tsx'; +import { invoke } from './bridge.ts'; +import { + addColumn, bump, columnSourceUrl, configureColumn, deckById, decks, patchColumn, removeColumn, shiftColumn, + type Deck, type DeckColumn, +} from './deckStore.ts'; +import { useDecks, useProfiles, useT } from './hooks.ts'; +import { Icon, type IconName } from './icons.tsx'; +import { site } from './site.ts'; +import { scheduleSync, setOverlay, shell, tabAction, type DeckParams } from './state.ts'; +import './deck.css'; + +const emitDecks = () => window.dispatchEvent(new CustomEvent('bt-decks')); +const unreadLabel = (count: number) => (count > 999 ? '999+' : String(count)); +const deckSite = () => site().deck!; + +/** Width of the columns row minus an open compose dock. */ +function columnsWidth(total: number, deckId: string) { + const compose = deckSite().compose; + return compose && decks.compose.has(deckId) ? Math.max(0, total - compose.width - COLUMN_GAP) : total; +} + +// --------------------------------------------------------------------------------------------- +// Deck commands (keys, palette, column menus) + +export type DeckCommand = + | 'column-prev' | 'column-next' | 'column-page-prev' | 'column-page-next' | 'column-mark-read' | 'column-jump-unread' | 'deck-compose' + | `column-${1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9}`; + +/** The row width each deck was last laid out at (for paging from keys). */ +const rowWidths = new Map(); + +/** Focuses a column: it becomes the deck's focused column, its page is shown and its webview gets the keys. */ +export function focusColumn(deckId: string, columnId: string, giveKeys = true) { + const deck = deckById(deckId); + const column = deck?.columns.find(c => c.id === columnId); + if (!deck || !column) return; + decks.focus.set(deckId, columnId); + const width = columnsWidth(rowWidths.get(deckId) ?? window.innerWidth, deckId); + decks.page.set(deckId, pageOf(width, deck.columns, columnId, { maxVisible: decks.settings.maxVisible }, decks.page.get(deckId))); + emitDecks(); + scheduleSync(); + if (giveKeys) requestAnimationFrame(() => tabAction(column.tabId, 'focus')); +} + +export function runDeckCommand(deckId: string, command: string) { + const deck = deckById(deckId); + if (!deck) return; + const focused = deck.columns.find(c => c.id === decks.focus.get(deckId)) ?? deck.columns[0]; + const index = focused ? deck.columns.indexOf(focused) : -1; + const digit = /^column-([1-9])$/.exec(command); + if (digit) { const target = deck.columns[Number(digit[1]) - 1]; if (target) focusColumn(deckId, target.id); return; } + switch (command) { + case 'column-prev': case 'column-next': { + const target = deck.columns[Math.min(deck.columns.length - 1, Math.max(0, index + (command === 'column-next' ? 1 : -1)))]; + if (target) focusColumn(deckId, target.id); + break; + } + case 'column-page-prev': case 'column-page-next': { + const width = columnsWidth(rowWidths.get(deckId) ?? window.innerWidth, deckId); + const layout = layoutColumns(width, deck.columns, (decks.page.get(deckId) ?? 0) + (command === 'column-page-next' ? 1 : -1), { maxVisible: decks.settings.maxVisible }); + decks.page.set(deckId, layout.page); + const first = layout.visible[0]; + if (first) decks.focus.set(deckId, first.id); + emitDecks(); + scheduleSync(); + break; + } + case 'column-mark-read': if (focused) bump(focused, 'read'); break; + case 'column-jump-unread': if (focused) bump(focused, 'jump'); break; + case 'deck-compose': toggleCompose(deckId, focused?.profile); break; + } +} + +export function toggleCompose(deckId: string, profile?: string) { + if (!deckSite().compose) return; + if (decks.compose.has(deckId)) decks.compose.delete(deckId); + else decks.compose.set(deckId, { profile: tabProfile(shell.profiles, profile ?? shell.profiles.active).id }); + emitDecks(); + scheduleSync(); +} + +// --------------------------------------------------------------------------------------------- +// Popovers (the shell rises above the tab webviews, or hides them, while one is open) + +function Popover({ anchor, onClose, children, width = 260, label }: { anchor: DOMRect; onClose(): void; children: ReactNode; width?: number; label: string }) { + useEffect(() => { + setOverlay(1); + const onKey = (event: KeyboardEvent) => { if (event.key === 'Escape') { event.stopPropagation(); onClose(); } }; + window.addEventListener('keydown', onKey, true); + window.addEventListener('blur', onClose); + return () => { setOverlay(-1); window.removeEventListener('keydown', onKey, true); window.removeEventListener('blur', onClose); }; + }, []); + const left = Math.max(8, Math.min(anchor.right - width, window.innerWidth - width - 8)); + const style: CSSProperties = { top: anchor.bottom + 6, left, width }; + return createPortal(
{ event.preventDefault(); onClose(); }}> +
event.stopPropagation()}>{children}
+
, document.body); +} + +function FilterPopover({ deckId, column, anchor, onClose }: { deckId: string; column: DeckColumn; anchor: DOMRect; onClose(): void }) { + const tr = useT(); + const [text, setText] = useState(''); + const input = useRef(null); + useEffect(() => { input.current?.focus(); }, []); + const filters = column.filters; + const set = (patch: Partial) => patchColumn(deckId, column.id, { filters: { ...filters, ...patch } }); + const add = () => { + const terms = text.split(/\n|,(?![^/]*\/[a-z]*$)/).map(t => t.trim()).filter(Boolean).filter(t => t.length <= 200); + if (!terms.length) return; + set({ terms: [...filters.terms, ...terms.filter(t => !filters.terms.includes(t))].slice(0, 32) }); + setText(''); + }; + const toggle = (key: 'hideReplies' | 'hideReposts' | 'mediaOnly', label: string, hint: string) => + ; + return +
{tr('wb.deck.filters')}{deckSite().title(column.source, column.title).title}
+
+ setText(event.target.value)} onKeyDown={event => { if (event.key === 'Enter') { event.preventDefault(); add(); } }}/> + {filters.terms.length > 0 &&
+ {filters.terms.map(term => + {term})} +
} +
+
+ {toggle('hideReplies', tr('wb.deck.hideReplies'), tr('wb.deck.hideRepliesHint'))} + {toggle('hideReposts', tr('wb.deck.hideReposts'), tr('wb.deck.hideRepostsHint'))} + {toggle('mediaOnly', tr('wb.deck.mediaOnly'), tr('wb.deck.mediaOnlyHint'))} +
; +} + +function ColumnMenu({ deck, column, anchor, onClose, onRemove }: { deck: Deck; column: DeckColumn; anchor: DOMRect; onClose(): void; onRemove(): void }) { + const tr = useT(); + const index = deck.columns.indexOf(column); + const item = (label: string, icon: IconName, action: () => void, disabled = false, keys?: string) => + ; + const url = decks.runtime.get(column.tabId)?.url ?? columnSourceUrl(column.source) ?? ''; + return + {item(tr('wb.deck.markRead'), 'check', () => bump(column, 'read'), false, 'Alt R')} + {item(tr('wb.deck.jumpUnread'), 'history', () => bump(column, 'jump'), false, 'Alt U')} +
+ {item(tr('wb.deck.moveLeft'), 'back', () => shiftColumn(deck.id, column.id, -1), index <= 0)} + {item(tr('wb.deck.moveRight'), 'forward', () => shiftColumn(deck.id, column.id, 1), index >= deck.columns.length - 1)} +
+ {tr('wb.deck.width')} + {COLUMN_WIDTHS.map(width => )} +
+
+ {item(tr('wb.shell.menu.duplicate'), 'duplicate', () => addColumn(deck.id, { profile: column.profile, source: column.source, filters: column.filters, flags: column.flags, width: column.width }, column.id))} + {item(tr('wb.deck.openAsTab'), 'external', () => shell.openUrl(url, column.profile), !url)} +
+ {item(tr('wb.deck.remove'), 'trash', onRemove)} +
; +} + +// --------------------------------------------------------------------------------------------- +// One column: header strip + the placeholder its webview covers + +function ColumnView({ deck, column, x, width, focused, number }: { deck: Deck; column: DeckColumn; x: number; width: number; focused: boolean; number: number }) { + const tr = useT(); + const profiles = useProfiles(); + const body = useRef(null); + const [menu, setMenu] = useState(null); + const [leaving, setLeaving] = useState(false); + const spec = deckSite(); + const runtime = decks.runtime.get(column.tabId); + const account = tabProfile(profiles, column.profile); + const type = spec.kinds.find(kind => kind.kind === column.source.kind); + const { title, detail } = spec.title(column.source, column.title); + const source = columnSourceUrl(column.source); + const away = !!(runtime?.url && source && !isSourcePage(runtime.url, source)); + const unread = runtime?.unread ?? 0; + const filtered = column.filters.terms.length > 0 || column.filters.hideReplies || column.filters.hideReposts || column.filters.mediaOnly; + const pageTitle = spec.pageTitle ?? ((text: string) => text); + + useLayoutEffect(() => { + const el = body.current; + if (!el || leaving) return; + shell.placeholders.set(column.tabId, el); + const observer = new ResizeObserver(scheduleSync); + observer.observe(el); + scheduleSync(); + return () => { + observer.disconnect(); + if (shell.placeholders.get(column.tabId) === el) shell.placeholders.delete(column.tabId); + scheduleSync(); + }; + }, [column.tabId, leaving]); + // Position changes (paging, reordering, width) move the webview with the placeholder. + useEffect(() => { scheduleSync(); }, [x, width]); + + const open = (kind: 'filters' | 'menu') => (event: ReactMouseEvent) => + setMenu(menu?.kind === kind ? null : { kind, anchor: event.currentTarget.getBoundingClientRect() }); + const remove = () => { + setLeaving(true); + // The webview hides at once (no placeholder); the header slides out, then the column goes. + const reduced = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches; + setTimeout(() => removeColumn(deck.id, column.id), reduced ? 0 : 180); + }; + + return
{ if (!focused) focusColumn(deck.id, column.id, false); }}> +
+ {away + ? + : } +
+ {title} + {away ? (pageTitle(runtime?.title ?? '') || tr('wb.deck.viewingPost')) : detail ?? `${site().accounts.handlePrefix}${account.account?.handle ?? account.name}`} +
+ {unread > 0 && } + + + + + {number <= 9 && } + {runtime?.loading && } +
+
+
+
+ {menu?.kind === 'filters' && setMenu(null)}/>} + {menu?.kind === 'menu' && setMenu(null)} onRemove={remove}/>} +
; +} + +// --------------------------------------------------------------------------------------------- + +function EmptyDeck({ deck, onAdd }: { deck: Deck; onAdd(): void }) { + const tr = useT(); + const profiles = useProfiles(); + const ids = profiles.profiles.map(p => p.id); + const ordered = [profiles.active, ...ids.filter(id => id !== profiles.active)]; + return
+ +

{tr('wb.deck.title')}

+

{tr('wb.deck.emptyHint', { site: site().name })}

+
+ + {(deckSite().presets ?? []).map(preset => { + const needs = preset.needsTwoAccounts && ids.length < 2 ? preset.needsTwoAccounts() : undefined; + return ; + })} +
+

+ [] {tr('wb.deck.key.columns')} + Alt1–9 {tr('wb.deck.key.jump')} + AltR {tr('wb.deck.key.read')} + {deckSite().compose && CtrlAltN {tr('wb.deck.key.post')}} +

+
; +} + +export function DeckView(props: IDockviewPanelProps) { + const tr = useT(); + useDecks(); + const deckId = props.params.deckId; + const row = useRef(null); + const [rowWidth, setRowWidth] = useState(0); + const [adding, setAdding] = useState(false); + const deck = deckById(deckId); + const compose = deckSite().compose; + + useLayoutEffect(() => { + const el = row.current; + if (!el) return; + const measure = () => { const w = Math.floor(el.getBoundingClientRect().width); rowWidths.set(deckId, w); setRowWidth(w); }; + const observer = new ResizeObserver(measure); + observer.observe(el); + measure(); + return () => observer.disconnect(); + }, [deckId, !!deck]); + useEffect(() => { + const visibility = props.api.onDidVisibilityChange(scheduleSync); + // The palette's "Add column…" opens this deck's dialog. + const add = (event: Event) => { if ((event as CustomEvent).detail === deckId) setAdding(true); }; + window.addEventListener('bt-deck-add', add); + return () => { visibility.dispose(); window.removeEventListener('bt-deck-add', add); }; + }, [props.api, deckId]); + // Every column gets its config before its webview exists (no flash of the site's chrome); + // unmounting the deck forgets what was sent, so reopening it configures again. + useEffect(() => { + if (!deck) return; + for (const column of deck.columns) { + if (decks.sent.has(column.tabId)) continue; + void configureColumn(column, true).then(() => { decks.ready.add(column.tabId); scheduleSync(); }); + } + }); + useEffect(() => () => { + for (const column of deckById(deckId)?.columns ?? []) { decks.sent.delete(column.tabId); decks.ready.delete(column.tabId); } + }, [deckId]); + + if (!deck) { + return

{tr('wb.deck.gone')}

{tr('wb.deck.goneHint')}

+
; + } + const settings = decks.settings; + const width = columnsWidth(rowWidth, deck.id); + const layout = layoutColumns(width, deck.columns, decks.page.get(deck.id) ?? 0, { maxVisible: settings.maxVisible }); + const focusedId = decks.focus.get(deck.id) ?? layout.visible[0]?.id; + const total = unreadTotal(new Map(deck.columns.map(c => [c.tabId, decks.runtime.get(c.tabId)?.unread ?? 0])), deck.columns); + const setPage = (page: number) => { decks.page.set(deck.id, page); emitDecks(); scheduleSync(); }; + const composing = compose && decks.compose.get(deck.id); + const overLimit = deck.columns.length > settings.maxVisible; + + return
+
+ + {deck.name} + {tr('wb.deck.columnCount', { count: deck.columns.length })} + {total > 0 && {tr('wb.deck.newCount', { count: unreadLabel(total) })}} + + {layout.pages > 1 &&
+ + {Array.from({ length: layout.pages }, (_, i) => +
} + {overLimit && {tr('wb.deck.onScreen', { visible: layout.visible.length, total: deck.columns.length })}} + + {compose && } + +
+
+ {deck.columns.length === 0 + ? setAdding(true)}/> + : layout.visible.map(place => { + const column = deck.columns.find(c => c.id === place.id)!; + return ; + })} + {compose && composing && } +
+ {adding && setAdding(false)} onAdd={input => { + const column = addColumn(deck.id, input); + void configureColumn(column, true).then(() => { decks.ready.add(column.tabId); focusColumn(deck.id, column.id, false); }); + setAdding(false); + }}/>} +
; +} + +/** Unread total of a deck on its dockview tab. */ +export function DeckTabBadge({ deckId }: { deckId: string }) { + useDecks(); + const deck = deckById(deckId); + if (!deck) return null; + const total = unreadTotal(new Map(deck.columns.map(c => [c.tabId, decks.runtime.get(c.tabId)?.unread ?? 0])), deck.columns); + return total > 0 ? {unreadLabel(total)} : null; +} diff --git a/packages/shell/src/frame/MediaPanel.tsx b/packages/shell/src/frame/MediaPanel.tsx new file mode 100644 index 0000000..9628217 --- /dev/null +++ b/packages/shell/src/frame/MediaPanel.tsx @@ -0,0 +1,113 @@ +import { useEffect, useState } from 'react'; +import { createPortal } from 'react-dom'; +import { invoke, listen } from './bridge.ts'; +import { useT } from './hooks.ts'; +import { attachTarget, clipPreview, folderLabel, relativeTime, type ClipItem, type GalleryImage, type MediaSettings } from './mediaModel.ts'; +import { site } from './site.ts'; +import { isWeb, setOverlay, shell, type WebParams } from './state.ts'; + +const getError = (error: unknown) => error instanceof Error ? error.message : String(error); + +function targetTab() { + const api = shell.api; + const media = site().media; + if (!api || !media) return null; + const tabs = api.panels.filter(isWeb).map(panel => ({ id: panel.id, url: (panel.params as WebParams).url })); + return attachTarget(tabs, api.activePanel?.id, media.canAttach); +} + +/** Lazily loads one preview (a data URL read natively, only from inside a gallery folder). */ +function Thumb({ command, args, alt }: { command: string; args: Record; alt: string }) { + const [src, setSrc] = useState(null); + useEffect(() => { + let live = true; + invoke(command, args).then(url => { if (live) setSrc(url); }).catch(() => {}); + return () => { live = false; }; + }, [command, JSON.stringify(args)]); + return src ? {alt} : ; +} + +/** + * Media side panel: recent images from the owner's gallery folders and the local clipboard + * history. Choosing an item attaches the image to (or inserts the text into) the composer of the + * active site tab (`site.media.canAttach`). Nothing is posted; the user reviews and sends it themselves. + */ +export function MediaPanel({ onClose }: { onClose: () => void }) { + const t = useT(); + const siteName = site().name; + const [tab, setTab] = useState<'gallery' | 'clipboard'>('gallery'); + const [settings, setSettings] = useState(null); + const [images, setImages] = useState(null); + const [clips, setClips] = useState(null); + const [error, setError] = useState(''); + + const refresh = () => { + invoke('media_get').then(setSettings).catch(err => setError(getError(err))); + invoke('gallery_list', { limit: 60 }).then(setImages).catch(err => setError(getError(err))); + invoke('clip_list').then(setClips).catch(err => setError(getError(err))); + }; + + useEffect(() => { + setOverlay(1); + invoke('shell_focus').catch(() => {}); + refresh(); + const unlisten = listen('clipboard-changed', () => { invoke('clip_list').then(setClips).catch(() => {}); }); + const onKey = (event: KeyboardEvent) => { if (event.key === 'Escape') onClose(); }; + window.addEventListener('keydown', onKey); + return () => { setOverlay(-1); window.removeEventListener('keydown', onKey); unlisten.then(dispose => dispose()).catch(() => {}); }; + }, []); + + const deliver = (command: 'tab_attach_image' | 'tab_insert_text', args: Record) => { + const target = targetTab(); + if (!target) { setError(t('wb.media.noComposer', { site: siteName })); return; } + onClose(); + shell.api?.getPanel(target.id)?.api.setActive(); + // Wait until the tab webview is shown again (the overlay hid it), then attach. Never posts. + setTimeout(() => { + invoke(command, { id: target.id, ...args }).catch(err => console.warn('[shell] media attach failed', err)); + }, 150); + }; + + const addFolder = () => invoke('gallery_add_folder').then(next => { setSettings(next); refresh(); }).catch(err => setError(getError(err))); + const removeClip = (id: string) => invoke('clip_remove', { id }).then(setClips).catch(err => setError(getError(err))); + + return createPortal(
+ +
, document.body); +} diff --git a/packages/shell/src/frame/NewTabPage.tsx b/packages/shell/src/frame/NewTabPage.tsx new file mode 100644 index 0000000..a0c75a2 --- /dev/null +++ b/packages/shell/src/frame/NewTabPage.tsx @@ -0,0 +1,112 @@ +import { useEffect, useRef, useState } from 'react'; +import { tabProfile } from '../profileModel.ts'; +import { invoke } from './bridge.ts'; +import { useProfiles, useSiteText, useT } from './hooks.ts'; +import { Avatar, Icon } from './icons.tsx'; +import { toUrl } from './searchInput.ts'; +import { site } from './site.ts'; +import { shell } from './state.ts'; + +const hostOf = (url: string) => { try { return new URL(url).host.replace(/^www\./, ''); } catch { return url; } }; + +/** Human label for a closed tab without a stored title: the address bar's own reading of the URL. */ +function labelFor(url: string, title: string | undefined): string { + if (title) return title; + const model = site().address(url); + if (!model) return url; + return [model.site.label, ...model.segments.map(segment => segment.label)].join(' / '); +} + +/** + * The new-tab page (and the empty-dock state): one search/address field, the site's quick links, + * recently closed tabs and the account the links open in. Drawn by the shell; it never has a webview. + */ +export function NewTabPage({ panelId, profile: initialProfile, onProfile }: { panelId?: string; profile?: string; onProfile?: (id: string) => void }) { + const profiles = useProfiles(); + useSiteText(); + const [profile, setProfile] = useState(() => tabProfile(profiles, initialProfile ?? profiles.active).id); + const [query, setQuery] = useState(''); + const [, refresh] = useState(0); + const input = useRef(null); + const multi = profiles.profiles.length > 1; + const recent = shell.closed.map((tab, index) => ({ ...tab, index })).reverse().slice(0, 6); + const { logo, newTab, isSiteUrl } = site(); + + useEffect(() => { + const focus = (event: Event) => { + if ((event as CustomEvent).detail !== panelId) return; + input.current?.focus(); + input.current?.select(); + }; + window.addEventListener('bt-focus-address', focus); + return () => window.removeEventListener('bt-focus-address', focus); + }, [panelId]); + + const open = (url: string) => shell.openFromStart(url, profile, panelId); + const pick = (id: string) => { setProfile(id); onProfile?.(id); }; + const reopen = (index: number) => { + const [tab] = shell.closed.splice(index, 1); + refresh(value => value + 1); + if (tab) shell.openFromStart(tab.url, tabProfile(profiles, tab.profile).id, panelId); + }; + const t = useT(); + const search = newTab.search(); + + return
+
+ +
{ event.preventDefault(); if (query.trim()) open(toUrl(query, site().searchUrl)); }}> + + setQuery(event.target.value)} spellCheck={false} autoComplete="off" + aria-label={search} placeholder={search} + onFocus={() => invoke('shell_focus').catch(() => {})} + onKeyDown={event => { if (event.key === 'Escape') { event.preventDefault(); setQuery(''); } }}/> + {t('wb.newtab.enter')} + + + {multi &&
+ {t('wb.newtab.openAs')} + {profiles.profiles.map(item => )} +
} + + {newTab.links.length > 0 &&
+
+ {newTab.links.map(link => { + const url = link.url(shell.homeUrl); + return ; + })} +
+
} + + {recent.length > 0 &&
+

{t('wb.newtab.recent')}

+
    + {recent.map(tab => { + const account = tabProfile(profiles, tab.profile); + return
  • + +
  • ; + })} +
+
} + +
+ CtrlK {t('wb.newtab.commands')} + Ctrl⇧T {t('wb.newtab.reopen')} + Ctrl\ {t('wb.newtab.split')} +
+
+
; +} diff --git a/packages/shell/src/frame/PaneTheme.tsx b/packages/shell/src/frame/PaneTheme.tsx new file mode 100644 index 0000000..bcaacee --- /dev/null +++ b/packages/shell/src/frame/PaneTheme.tsx @@ -0,0 +1,82 @@ +// "Theme for this pane": a menu (tab context menu, the address bar's ⋯ menu) that gives one pane its +// own theme or lets it follow its account's / the global theme again. Pane themes are stored with +// the other scopes (themeStore.ts → native `theme_scopes_set`), which re-themes that tab natively. +// Only with themes (`site.themes`). + +import { useEffect, useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from 'react'; +import { createPortal } from 'react-dom'; +import { useT, useThemeState } from './hooks.ts'; +import { Icon } from './icons.tsx'; +import { site } from './site.ts'; +import { setOverlay, shell } from './state.ts'; +import { assign, themeIdFor } from './themeScopes.ts'; +import type { ThemeDoc, ThemeStore } from './themeStore.ts'; +import './paneTheme.css'; + +type Request = { id: string; profile: string; x: number; y: number }; +let open: (request: Request | null) => void = () => {}; +export const openPaneTheme = (request: Request) => open(request); + +/** Three dots of a theme's page, text and accent. */ +export function ThemeDots({ theme, store }: { theme: Spec; store?: ThemeStore }) { + const themes = (store ?? site().themes) as ThemeStore | undefined; + if (!themes) return null; + const c = themes.adapter.dots(theme); + return ; +} + +export function PaneThemeHost() { + const [request, setRequest] = useState(null); + open = setRequest; + const themes = site().themes; + return request && themes ? setRequest(null)}/> : null; +} + +function PaneThemeMenu({ request, store, onClose }: { request: Request; store: ThemeStore; onClose(): void }) { + const { scopes, choice } = useThemeState(store); + const list = useRef(null); + useEffect(() => { + setOverlay(1); + const onBlur = () => onClose(); + window.addEventListener('blur', onBlur); + requestAnimationFrame(() => list.current?.querySelector('[aria-checked=true]')?.focus()); + return () => { setOverlay(-1); window.removeEventListener('blur', onBlur); }; + }, []); + const own = scopes.panes[request.id]; + const inherited = themeIdFor({ ...scopes, panes: {} }, { profile: request.profile }, store.adapter.preset(choice), id => store.knownTheme(id)); + const pick = (theme: string | null) => { + onClose(); + void store.setScopes(assign(store.themeState().scopes, 'panes', request.id, theme)).catch(() => {}); + }; + const onKey = (event: ReactKeyboardEvent) => { + const items = [...(list.current?.querySelectorAll('button') ?? [])]; + const index = items.indexOf(document.activeElement as HTMLButtonElement); + if (event.key === 'Escape') { event.preventDefault(); onClose(); } + else if (event.key === 'ArrowDown' || event.key === 'ArrowUp') { + event.preventDefault(); + items[(index + (event.key === 'ArrowDown' ? 1 : -1) + items.length) % items.length]?.focus(); + } else if (event.key === 'Home' || event.key === 'End') { event.preventDefault(); items[event.key === 'Home' ? 0 : items.length - 1]?.focus(); } + }; + const t = useT(); + const left = Math.max(8, Math.min(request.x, window.innerWidth - 280)); + const top = Math.max(8, Math.min(request.y, window.innerHeight - 440)); + return createPortal(
{ event.preventDefault(); onClose(); }}> +
event.stopPropagation()} onKeyDown={onKey} ref={list}> +
{t('wb.pane.theme')}
+ +
+
+ {store.allThemes(choice).map(theme => )} +
+
+ +
+
, document.body); +} diff --git a/packages/shell/src/frame/Shell.tsx b/packages/shell/src/frame/Shell.tsx new file mode 100644 index 0000000..73b3596 --- /dev/null +++ b/packages/shell/src/frame/Shell.tsx @@ -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({ + 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; + +/** 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 { + 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({ 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 | 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 [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); + + 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('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).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
+ + void onReady(event)} + /> + {palette && setPalette(null)}/>} + {overlays.map((Overlay, index) => )} + {media && setMedia(false)}/>} + {menu && setMenu(null)}/>} + + {frameless && !maximized && } +
; +} + diff --git a/packages/shell/src/frame/Titlebar.tsx b/packages/shell/src/frame/Titlebar.tsx new file mode 100644 index 0000000..575e8df --- /dev/null +++ b/packages/shell/src/frame/Titlebar.tsx @@ -0,0 +1,96 @@ +import { useEffect, type CSSProperties, type MouseEvent as ReactMouseEvent } from 'react'; +import { RESIZE_BORDER } from '../chrome.ts'; +import { chipFor } from '../updateModel.ts'; +import { AccountSwitcher } from './AccountSwitcher.tsx'; +import { invoke } from './bridge.ts'; +import { useT, useUpdateStatus } from './hooks.ts'; +import { tx } from './i18n.ts'; +import { site } from './site.ts'; +import { TitlebarExtras } from './TitlebarExtras.tsx'; +import { close, minimize, os, startResize, systemMenu, toggleMaximize, type ResizeDirection } from './windowBinding.ts'; + +const isInteractive = (target: EventTarget | null) => + target instanceof Element && !!target.closest('button, input, textarea, a, .dv-tab, [role="button"]'); + +/** Right-click on empty titlebar space: the native system menu (Restore, Move, Size, ...). */ +export function titlebarContextMenu(event: ReactMouseEvent | MouseEvent) { + if (isInteractive(event.target)) return; + event.preventDefault(); + const scale = window.devicePixelRatio || 1; + systemMenu(Math.round(event.screenX * scale), Math.round(event.screenY * scale)); +} + +/** + * The 44px titlebar row. It sits under the dockview root: the top groups' tab headers are + * transparent and let clicks through to the drag layer, the logo and the caption buttons. + */ +export function Titlebar({ maximized }: { maximized: boolean }) { + return
+
+ +
+ + + + {os !== 'macos' && } +
; +} + +/** "Update ready · restart": appears only when a verified update is downloaded (or failed to start). */ +function UpdateChip() { + const [status, apply] = useUpdateStatus(); + const chip = chipFor(status, site().product, key => tx(key, undefined, '') || undefined); + // Widen the tab strip's right reserve while the chip is shown so tabs never sit under it. + useEffect(() => { + const root = document.documentElement; + if (chip) root.dataset.update = chip.kind; else delete root.dataset.update; + return () => { delete root.dataset.update; }; + }, [chip?.kind]); + if (!chip) return null; + if (chip.kind === 'problem') { + return ; + } + return ; +} + +function WindowControls({ maximized }: { maximized: boolean }) { + const t = useT(); + return
+ + + +
; +} + +const CORNER = RESIZE_BORDER * 2; +const GRIPS: Array<[ResizeDirection, CSSProperties]> = [ + ['North', { top: 0, left: CORNER, right: CORNER, height: RESIZE_BORDER, cursor: 'ns-resize' }], + ['South', { bottom: 0, left: CORNER, right: CORNER, height: RESIZE_BORDER, cursor: 'ns-resize' }], + ['West', { left: 0, top: CORNER, bottom: CORNER, width: RESIZE_BORDER, cursor: 'ew-resize' }], + ['East', { right: 0, top: CORNER, bottom: CORNER, width: RESIZE_BORDER, cursor: 'ew-resize' }], + ['NorthWest', { top: 0, left: 0, width: CORNER, height: CORNER, cursor: 'nwse-resize' }], + ['SouthEast', { bottom: 0, right: 0, width: CORNER, height: CORNER, cursor: 'nwse-resize' }], + ['NorthEast', { top: 0, right: 0, width: CORNER, height: CORNER, cursor: 'nesw-resize' }], + ['SouthWest', { bottom: 0, left: 0, width: CORNER, height: CORNER, cursor: 'nesw-resize' }], +]; + +/** + * The shell webview covers the whole frameless window, so the OS never sees its edges: + * these grips start native resize drags. Tab webviews are inset by the same band (Rust clamps too). + */ +export function ResizeGrips() { + return <>{GRIPS.map(([direction, style]) => +