packages/shell/src/frame (waybetter/shell/frame): the whole shell of an app. An app describes its site (ShellSite: names and pages, account rules, search, address chips and completions, its panel tab, the new-tab page, palette items, deck column kinds and flags and an optional compose dock, the media panel's composer rule, a theme store, overlays, the native features it serves) and passes its Tauri API and i18n instance; createShell returns the root component. - Shell.tsx: dockview host (tabs in the titlebar row, splits, drag-link drops, shortcuts, context menu, deck back-and-forth, session restore, workspace on start, overlay raise); state.ts (pane placeholders, tabs_sync one-in-flight via syncGate, shell_raise layer, profiles, layout). - WebPanel (address bar), NewTabPage, CommandPalette + paletteModel (frame groups; site items), DeckView + AddColumnDialog + deckStore (site column kinds), PaneTheme + themeStore (createThemeStore over the app's ThemeAdapter) + chromeTheme (ChromeTheme input) + themeScopes, Titlebar + TitlebarExtras + icons + brand (wB mark data URI), AccountSwitcher + accountModel, workspaces + workspaceModel, backupModel, syncHost, devHost + devModel, pluginCommandStore, MediaPanel + mediaModel, searchInput, hooks, bridge (installPreviewMocks), i18n, boot.ts (bootScript: the first-frame boot.js), CSS themed with --wb-* tokens. - paneModel: paneVisibility, raiseSupported, cssRgb; deckModel: isSourcePage. - Includes the live-QA titlebar fix (dock ResizeObserver + rAF titlebar marks, dock sized by its insets). - tests/frame.test.ts: every frame key has English and is used, palette order with a site, address fallback, layout gate, boot script, chrome variables, switcher rules, workspaces, deck settings with site flags. - npm package 0.4.0: exports ./shell/frame, ./shell/frame/*, ./shell/frame/*.css (copied by the build); dockview and acorn optional peers; root devDependencies dockview, acorn.
314 lines
14 KiB
TypeScript
314 lines
14 KiB
TypeScript
// Power User Mode: a deck of narrow site columns (TweetDeck-style). Pure model (no Tauri/DOM), so
|
|
// it is unit-tested under node. Every column is a real site tab webview in its own account profile;
|
|
// this model only says which columns exist, which page of them is on screen and where each one
|
|
// goes. What a column shows is the site adapter's business (`urlFor`), what it hides is the page
|
|
// runtime's (runtime/column.ts). Paging, not pixel scrolling: a page is as many whole columns as
|
|
// fit the viewport; the rest are parked off-page (hidden, low memory).
|
|
|
|
/** A column's content, named by the site adapter (e.g. `{ kind: 'search', value: 'from:me' }`). */
|
|
export type ColumnSource = { kind: string; value?: string };
|
|
|
|
/** Per-column filters, applied by the page runtime to the site's items (runtime/column.ts). */
|
|
export type ColumnFilters = {
|
|
/** Keywords (case-insensitive) or `/regex/flags`; a match hides the item. */
|
|
terms: string[];
|
|
hideReplies: boolean;
|
|
hideReposts: boolean;
|
|
mediaOnly: boolean;
|
|
};
|
|
|
|
export type DeckColumn = {
|
|
id: string;
|
|
/** The tab webview id this column runs in (`tab-<tabId>` natively). */
|
|
tabId: string;
|
|
/** Account profile of the column's webview. */
|
|
profile: string;
|
|
source: ColumnSource;
|
|
/** Preferred width in px; a page stretches its columns to fill the viewport. */
|
|
width: number;
|
|
/** Per-column feature flags over the global ones (allow-listed natively). */
|
|
flags: Record<string, boolean>;
|
|
filters: ColumnFilters;
|
|
/** Optional title the user gave the column. */
|
|
title?: string;
|
|
};
|
|
|
|
export type Deck = { id: string; name: string; columns: DeckColumn[] };
|
|
|
|
export const COLUMN_WIDTHS = [320, 360, 400, 480] as const;
|
|
export const DEFAULT_COLUMN_WIDTH = 360;
|
|
export const MIN_COLUMN_WIDTH = 280;
|
|
export const MAX_COLUMN_WIDTH = 640;
|
|
export const MAX_COLUMNS = 24;
|
|
export const MAX_DECKS = 12;
|
|
export const MAX_TERMS = 32;
|
|
export const MAX_TERM_CHARS = 200;
|
|
export const MAX_FLAGS = 16;
|
|
/** Visible columns per page before the memory guard warns. */
|
|
export const DEFAULT_MAX_VISIBLE = 6;
|
|
/** Gap between columns in px. */
|
|
export const COLUMN_GAP = 8;
|
|
|
|
export const emptyFilters = (): ColumnFilters => ({ terms: [], hideReplies: false, hideReposts: false, mediaOnly: false });
|
|
|
|
const ID = /^[a-z0-9][a-z0-9-]{0,39}$/i;
|
|
export const validColumnId = (id: unknown): id is string => typeof id === 'string' && ID.test(id);
|
|
|
|
// eslint-disable-next-line no-control-regex
|
|
const CONTROL = /[\u0000-\u001f\u007f-\u009f]/;
|
|
function cleanText(value: unknown, max: number): string | null {
|
|
if (typeof value !== 'string') return null;
|
|
const trimmed = value.trim();
|
|
if (!trimmed || [...trimmed].length > max || CONTROL.test(trimmed)) return null;
|
|
return trimmed;
|
|
}
|
|
|
|
export function normalizeFilters(value: unknown): ColumnFilters {
|
|
const raw = (value && typeof value === 'object' ? value : {}) as Partial<Record<keyof ColumnFilters, unknown>>;
|
|
const terms: string[] = [];
|
|
for (const term of Array.isArray(raw.terms) ? raw.terms : []) {
|
|
const clean = cleanText(term, MAX_TERM_CHARS);
|
|
if (clean && !terms.includes(clean) && terms.length < MAX_TERMS) terms.push(clean);
|
|
}
|
|
return { terms, hideReplies: raw.hideReplies === true, hideReposts: raw.hideReposts === true, mediaOnly: raw.mediaOnly === true };
|
|
}
|
|
|
|
export function normalizeFlags(value: unknown, allowed?: readonly string[]): Record<string, boolean> {
|
|
const flags: Record<string, boolean> = {};
|
|
if (!value || typeof value !== 'object') return flags;
|
|
for (const [key, flag] of Object.entries(value as Record<string, unknown>)) {
|
|
if (typeof flag !== 'boolean' || !/^[a-zA-Z][a-zA-Z0-9]{0,47}$/.test(key)) continue;
|
|
if (allowed && !allowed.includes(key)) continue;
|
|
if (Object.keys(flags).length >= MAX_FLAGS) break;
|
|
flags[key] = flag;
|
|
}
|
|
return flags;
|
|
}
|
|
|
|
export const clampWidth = (width: unknown): number =>
|
|
typeof width === 'number' && Number.isFinite(width) ? Math.round(Math.min(MAX_COLUMN_WIDTH, Math.max(MIN_COLUMN_WIDTH, width))) : DEFAULT_COLUMN_WIDTH;
|
|
|
|
export type NormalizeOptions = {
|
|
/** Source kinds the site adapter knows; others are dropped. */
|
|
kinds?: readonly string[];
|
|
/** Profile ids that exist; a column of a removed profile moves to `fallbackProfile`. */
|
|
profiles?: readonly string[];
|
|
fallbackProfile?: string;
|
|
/** Allow-listed per-column flags. */
|
|
flags?: readonly string[];
|
|
};
|
|
|
|
export function normalizeColumn(value: unknown, options: NormalizeOptions = {}): DeckColumn | null {
|
|
const raw = (value && typeof value === 'object' ? value : {}) as Record<string, unknown>;
|
|
if (!validColumnId(raw.id) || !validColumnId(raw.tabId)) return null;
|
|
const source = raw.source as Partial<ColumnSource> | undefined;
|
|
const kind = typeof source?.kind === 'string' && /^[a-z][a-z0-9-]{0,23}$/.test(source.kind) ? source.kind : null;
|
|
if (!kind || (options.kinds && !options.kinds.includes(kind))) return null;
|
|
const sourceValue = source?.value === undefined ? undefined : cleanText(source.value, 512);
|
|
if (source?.value !== undefined && sourceValue === null) return null;
|
|
let profile = typeof raw.profile === 'string' && raw.profile ? raw.profile : options.fallbackProfile ?? 'default';
|
|
if (options.profiles && !options.profiles.includes(profile)) profile = options.fallbackProfile ?? options.profiles[0] ?? 'default';
|
|
const title = cleanText(raw.title, 60);
|
|
return {
|
|
id: raw.id,
|
|
tabId: raw.tabId,
|
|
profile,
|
|
source: sourceValue ? { kind, value: sourceValue } : { kind },
|
|
width: clampWidth(raw.width),
|
|
flags: normalizeFlags(raw.flags, options.flags),
|
|
filters: normalizeFilters(raw.filters),
|
|
...(title ? { title } : {}),
|
|
};
|
|
}
|
|
|
|
/** Anything from storage → a bounded deck (unique column and tab ids, at most MAX_COLUMNS). */
|
|
export function normalizeDeck(value: unknown, options: NormalizeOptions = {}): Deck | null {
|
|
const raw = (value && typeof value === 'object' ? value : {}) as Record<string, unknown>;
|
|
if (!validColumnId(raw.id)) return null;
|
|
const name = cleanText(raw.name, 40) ?? 'Deck';
|
|
const columns: DeckColumn[] = [];
|
|
const ids = new Set<string>();
|
|
for (const item of Array.isArray(raw.columns) ? raw.columns : []) {
|
|
if (columns.length >= MAX_COLUMNS) break;
|
|
const column = normalizeColumn(item, options);
|
|
if (!column || ids.has(column.id) || ids.has(`tab:${column.tabId}`)) continue;
|
|
ids.add(column.id);
|
|
ids.add(`tab:${column.tabId}`);
|
|
columns.push(column);
|
|
}
|
|
return { id: raw.id, name, columns };
|
|
}
|
|
|
|
export function normalizeDecks(value: unknown, options: NormalizeOptions = {}): Deck[] {
|
|
const decks: Deck[] = [];
|
|
const tabs = new Set<string>();
|
|
for (const item of Array.isArray(value) ? value : []) {
|
|
if (decks.length >= MAX_DECKS) break;
|
|
const deck = normalizeDeck(item, options);
|
|
if (!deck || decks.some(other => other.id === deck.id)) continue;
|
|
// A tab webview belongs to exactly one column of one deck.
|
|
deck.columns = deck.columns.filter(column => !tabs.has(column.tabId));
|
|
for (const column of deck.columns) tabs.add(column.tabId);
|
|
decks.push(deck);
|
|
}
|
|
return decks;
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------------------------
|
|
// Layout
|
|
|
|
export type PlacedColumn = { id: string; x: number; width: number };
|
|
export type DeckLayout = {
|
|
/** The page shown (clamped into range). */
|
|
page: number;
|
|
pages: number;
|
|
visible: PlacedColumn[];
|
|
/** Columns on other pages: their webviews are hidden (and parked when the setting says so). */
|
|
parked: string[];
|
|
};
|
|
|
|
export type LayoutOptions = { gap?: number; maxVisible?: number };
|
|
|
|
/** How many columns from `start` (forward, or backward with `step` -1) fit `viewportW` (at least one). */
|
|
function fitCount(viewportW: number, widths: readonly number[], start: number, step: 1 | -1, gap: number, maxVisible: number): number {
|
|
let used = 0;
|
|
let count = 0;
|
|
for (let i = start; i >= 0 && i < widths.length && count < maxVisible; i += step) {
|
|
const needed = count ? used + gap + widths[i]! : widths[i]!;
|
|
if (count && needed > viewportW) break;
|
|
used = needed;
|
|
count++;
|
|
}
|
|
return Math.max(1, count);
|
|
}
|
|
|
|
/**
|
|
* Splits columns into pages of whole columns that fit `viewportW` (at least one per page). Pages
|
|
* are filled from the left; the last page is filled from the right end instead, so it is as full as
|
|
* the others (it may repeat columns of the page before) rather than one lone stretched column.
|
|
*/
|
|
export function paginate(viewportW: number, columns: readonly Pick<DeckColumn, 'id' | 'width'>[], options: LayoutOptions = {}): string[][] {
|
|
const gap = options.gap ?? COLUMN_GAP;
|
|
const maxVisible = Math.max(1, Math.floor(options.maxVisible ?? DEFAULT_MAX_VISIBLE));
|
|
const widths = columns.map(column => clampWidth(column.width));
|
|
const pages: string[][] = [];
|
|
let start = 0;
|
|
while (start < columns.length) {
|
|
const count = fitCount(viewportW, widths, start, 1, gap, maxVisible);
|
|
if (start + count >= columns.length && pages.length) {
|
|
// The last page: as many columns as fit, counted back from the end.
|
|
const back = fitCount(viewportW, widths, columns.length - 1, -1, gap, maxVisible);
|
|
pages.push(columns.slice(columns.length - back).map(column => column.id));
|
|
break;
|
|
}
|
|
pages.push(columns.slice(start, start + count).map(column => column.id));
|
|
start += count;
|
|
}
|
|
return pages;
|
|
}
|
|
|
|
/** A page's columns stretch to fill the viewport, but never beyond this factor of their width. */
|
|
export const MAX_STRETCH = 2;
|
|
|
|
/**
|
|
* Where each column of `page` goes in a viewport `viewportW` px wide. The page's columns stretch
|
|
* evenly to fill the width (no ragged gap on the right); a lone column wider than the viewport
|
|
* is squeezed to it. Columns on other pages are `parked`.
|
|
*/
|
|
export function layoutColumns(viewportW: number, columns: readonly Pick<DeckColumn, 'id' | 'width'>[], page: number, options: LayoutOptions = {}): DeckLayout {
|
|
const gap = options.gap ?? COLUMN_GAP;
|
|
const width = Math.max(0, Math.floor(viewportW));
|
|
const pages = paginate(width, columns, options);
|
|
if (!pages.length) return { page: 0, pages: 0, visible: [], parked: [] };
|
|
const index = Math.min(pages.length - 1, Math.max(0, Math.floor(Number.isFinite(page) ? page : 0)));
|
|
const ids = pages[index]!;
|
|
const byId = new Map(columns.map(column => [column.id, clampWidth(column.width)]));
|
|
const preferred = ids.map(id => byId.get(id)!);
|
|
const sum = preferred.reduce((total, w) => total + w, 0);
|
|
const room = Math.max(ids.length, width - gap * (ids.length - 1));
|
|
// Integer px in proportion to the preferred widths; the rounding remainder goes 1 px per column
|
|
// from the left, so the row ends exactly at the viewport edge.
|
|
// Stretch to fill, up to MAX_STRETCH; a page of few columns on a wide screen leaves room at the end.
|
|
const target = Math.min(room, Math.floor(sum * MAX_STRETCH));
|
|
const widths = preferred.map(w => Math.max(1, Math.floor((w * target) / sum)));
|
|
let remainder = target - widths.reduce((total, w) => total + w, 0);
|
|
for (let i = 0; remainder > 0; i = (i + 1) % widths.length, remainder--) widths[i]! += 1;
|
|
const visible: PlacedColumn[] = [];
|
|
let x = 0;
|
|
ids.forEach((id, i) => {
|
|
visible.push({ id, x, width: widths[i]! });
|
|
x += widths[i]! + gap;
|
|
});
|
|
const shown = new Set(ids);
|
|
return { page: index, pages: pages.length, visible, parked: columns.map(c => c.id).filter(id => !shown.has(id)) };
|
|
}
|
|
|
|
/**
|
|
* The page that shows column `id`: `current` when it is on it already (so focusing a column never
|
|
* flips pages needlessly), else the first page that holds it (0 when it is unknown).
|
|
*/
|
|
export function pageOf(viewportW: number, columns: readonly Pick<DeckColumn, 'id' | 'width'>[], id: string, options: LayoutOptions = {}, current?: number): number {
|
|
const pages = paginate(Math.max(0, Math.floor(viewportW)), columns, options);
|
|
if (current !== undefined && pages[current]?.includes(id)) return current;
|
|
const index = pages.findIndex(page => page.includes(id));
|
|
return index < 0 ? 0 : index;
|
|
}
|
|
|
|
/** The column `delta` steps from `focused` (clamped at the ends; the first one when none is focused). */
|
|
export function moveFocus(columns: readonly Pick<DeckColumn, 'id'>[], focused: string | null | undefined, delta: number): string | null {
|
|
if (!columns.length) return null;
|
|
const index = columns.findIndex(column => column.id === focused);
|
|
if (index < 0) return columns[delta < 0 ? columns.length - 1 : 0]!.id;
|
|
return columns[Math.min(columns.length - 1, Math.max(0, index + Math.trunc(delta)))]!.id;
|
|
}
|
|
|
|
/** The URL a column loads: the adapter's `urlFor`, or null for a source it does not know. */
|
|
export function columnUrl(source: ColumnSource, urlFor: (source: ColumnSource) => string | null): string | null {
|
|
try {
|
|
const url = urlFor(source);
|
|
if (!url) return null;
|
|
const parsed = new URL(url);
|
|
return parsed.protocol === 'https:' && !parsed.username && !parsed.password ? parsed.href : null;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/** Unread count to show for a deck: the sum over its columns, capped like the native report (999). */
|
|
export const MAX_UNREAD = 999;
|
|
export function unreadTotal(unread: ReadonlyMap<string, number> | Record<string, number>, columns: readonly Pick<DeckColumn, 'tabId'>[]): number {
|
|
const get = (id: string) => (unread instanceof Map ? unread.get(id) : (unread as Record<string, number>)[id]) ?? 0;
|
|
let total = 0;
|
|
for (const column of columns) {
|
|
const value = get(column.tabId);
|
|
if (Number.isFinite(value) && value > 0) total += Math.floor(value);
|
|
}
|
|
return Math.min(MAX_UNREAD, total);
|
|
}
|
|
|
|
/** Moves column `id` by `delta` places (clamped); returns a new array. */
|
|
export function moveColumn<T extends { id: string }>(columns: readonly T[], id: string, delta: number): T[] {
|
|
const index = columns.findIndex(column => column.id === id);
|
|
if (index < 0) return [...columns];
|
|
const target = Math.min(columns.length - 1, Math.max(0, index + Math.trunc(delta)));
|
|
const next = [...columns];
|
|
const [item] = next.splice(index, 1);
|
|
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;
|
|
}
|
|
}
|