Deck columns (Power User Mode): shell deckModel (bounded decks, paging layout, focus, unread totals), runtime column mode (hide site chrome, fill width, filters, unread tracking, no requests), host ColumnConfig bounds, TabRole, deck shortcuts, capped unread in TabState; column boxes skip rail rules
This commit is contained in:
parent
965a85f359
commit
f05bae07b2
10 changed files with 1170 additions and 7 deletions
|
|
@ -50,7 +50,8 @@ crates/waybetter-host/ Rust: security policy, profiles, plugin store, hotfi
|
||||||
src/plugins.rs *.plugin.js store, custom CSS, bundled-plugin upgrades
|
src/plugins.rs *.plugin.js store, custom CSS, bundled-plugin upgrades
|
||||||
src/hotfix.rs signed data-only hotfix channel (minisign)
|
src/hotfix.rs signed data-only hotfix channel (minisign)
|
||||||
src/update.rs silent-update scheduling and crash handshake
|
src/update.rs silent-update scheduling and crash handshake
|
||||||
src/tabs.rs TabLayout/TabState/OpenRequest, link modes, shortcut and drag validation
|
src/tabs.rs TabLayout/TabState/OpenRequest, link modes, shortcut and drag validation,
|
||||||
|
deck ColumnConfig bounds and unread caps
|
||||||
src/host.rs (feature "tauri") webview helpers, shell events, system menu
|
src/host.rs (feature "tauri") webview helpers, shell events, system menu
|
||||||
packages/runtime/src/ page runtime core (TypeScript, no dependencies)
|
packages/runtime/src/ page runtime core (TypeScript, no dependencies)
|
||||||
site.ts SiteAdapter (the page half of the adapter) + configureRuntime
|
site.ts SiteAdapter (the page half of the adapter) + configureRuntime
|
||||||
|
|
@ -60,11 +61,13 @@ packages/runtime/src/ page runtime core (TypeScript, no dependencies)
|
||||||
themeApi.ts the active theme as values + --wb-* CSS variables (api.theme)
|
themeApi.ts the active theme as values + --wb-* CSS variables (api.theme)
|
||||||
themeTokens.ts OKLab color model: maps the site's palette onto a theme's axis
|
themeTokens.ts OKLab color model: maps the site's palette onto a theme's axis
|
||||||
paneNav.ts split view: park the site's navigation rail in redundant panes
|
paneNav.ts split view: park the site's navigation rail in redundant panes
|
||||||
|
column.ts deck columns: hide site chrome, fill the width, filters, unread count
|
||||||
linkRouting.ts divert in-page clicks to a pane/tab/browser per setting
|
linkRouting.ts divert in-page clicks to a pane/tab/browser per setting
|
||||||
accountReport.ts report the signed-in account of this tab's profile
|
accountReport.ts report the signed-in account of this tab's profile
|
||||||
packages/shell/src/ shell core (TypeScript, no dependencies)
|
packages/shell/src/ shell core (TypeScript, no dependencies)
|
||||||
addressModel.ts address bar chips (site pages named by the adapter)
|
addressModel.ts address bar chips (site pages named by the adapter)
|
||||||
paneModel.ts beside-pane reuse, redundant rails, navRedundant for tabs_sync
|
paneModel.ts beside-pane reuse, redundant rails, navRedundant for tabs_sync
|
||||||
|
deckModel.ts decks of site columns: bounded storage model, paging layout, focus
|
||||||
linkDrop.ts dropping links into the dock
|
linkDrop.ts dropping links into the dock
|
||||||
profileModel.ts profiles and account labels
|
profileModel.ts profiles and account labels
|
||||||
palette.ts command palette scoring/ranking
|
palette.ts command palette scoring/ranking
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,7 @@
|
||||||
//! Everything a tab page sends is validated here before it reaches the shell.
|
//! Everything a tab page sends is validated here before it reaches the shell.
|
||||||
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::collections::BTreeMap;
|
||||||
use url::Url;
|
use url::Url;
|
||||||
|
|
||||||
/// Shell events emitted by the host.
|
/// Shell events emitted by the host.
|
||||||
|
|
@ -34,6 +35,18 @@ pub struct TabLayout {
|
||||||
/// Another site pane of the same account already shows the site's navigation rail.
|
/// Another site pane of the same account already shows the site's navigation rail.
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
pub nav_redundant: bool,
|
pub nav_redundant: bool,
|
||||||
|
/// An ordinary pane, or a Power User Mode deck column (the page hides the site chrome itself).
|
||||||
|
#[serde(default)]
|
||||||
|
pub role: TabRole,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a tab webview is in the shell's layout.
|
||||||
|
#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum TabRole {
|
||||||
|
#[default]
|
||||||
|
Pane,
|
||||||
|
Column,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn default_profile() -> String {
|
fn default_profile() -> String {
|
||||||
|
|
@ -55,6 +68,9 @@ pub struct TabState {
|
||||||
pub favicon: Option<String>,
|
pub favicon: Option<String>,
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
pub focused: Option<bool>,
|
pub focused: Option<bool>,
|
||||||
|
/// A deck column's unread count (capped at [`MAX_UNREAD`]); only ever a number about this tab.
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub unread: Option<u16>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TabState {
|
impl TabState {
|
||||||
|
|
@ -72,10 +88,19 @@ impl TabState {
|
||||||
}),
|
}),
|
||||||
focused,
|
focused,
|
||||||
loading: None,
|
loading: None,
|
||||||
|
unread: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Unread counts shown on deck column headers are capped here ("999+").
|
||||||
|
pub const MAX_UNREAD: u16 = 999;
|
||||||
|
|
||||||
|
/// A reported unread count, capped at [`MAX_UNREAD`].
|
||||||
|
pub fn cap_unread(count: u64) -> u16 {
|
||||||
|
count.min(MAX_UNREAD as u64) as u16
|
||||||
|
}
|
||||||
|
|
||||||
/// A new-window request from a tab that the shell opens as a tab or a pane (`tab-open`).
|
/// A new-window request from a tab that the shell opens as a tab or a pane (`tab-open`).
|
||||||
#[derive(Clone, Serialize, Debug)]
|
#[derive(Clone, Serialize, Debug)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
|
|
@ -119,10 +144,13 @@ pub fn new_window_mode<'a>(on_site: bool, site_mode: &'a str, external_mode: &'a
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Browser shortcuts a tab may forward to the shell while it has keyboard focus.
|
/// Browser shortcuts a tab may forward to the shell while it has keyboard focus. The `column-*` and
|
||||||
pub const SHORTCUTS: [&str; 15] = [
|
/// `deck-*` names are Power User Mode keys (deck columns forward them; the shell acts on its deck).
|
||||||
|
pub const SHORTCUTS: &[&str] = &[
|
||||||
"command-palette", "new-tab", "close-tab", "reopen-tab", "focus-address", "next-tab", "prev-tab", "reload",
|
"command-palette", "new-tab", "close-tab", "reopen-tab", "focus-address", "next-tab", "prev-tab", "reload",
|
||||||
"back", "forward", "split-right", "split-down", "open-panel", "find", "hard-reload",
|
"back", "forward", "split-right", "split-down", "open-panel", "find", "hard-reload",
|
||||||
|
"column-prev", "column-next", "column-1", "column-2", "column-3", "column-4", "column-5", "column-6", "column-7",
|
||||||
|
"column-8", "column-9", "column-page-prev", "column-page-next", "column-mark-read", "deck-compose", "deck-toggle",
|
||||||
];
|
];
|
||||||
|
|
||||||
pub fn valid_shortcut(shortcut: &str) -> bool {
|
pub fn valid_shortcut(shortcut: &str) -> bool {
|
||||||
|
|
@ -181,6 +209,87 @@ pub fn memory_target(visible: bool, parked: bool) -> MemoryTarget {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Power User Mode: what the shell may tell a deck column's page (`column_configure`, shell-only).
|
||||||
|
/// Everything is data for the page runtime's column module (hide site chrome, density, filters,
|
||||||
|
/// unread tracking); nothing here can make the page request or act.
|
||||||
|
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
|
||||||
|
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||||
|
pub struct ColumnConfig {
|
||||||
|
/// The column's own page; must be on the site.
|
||||||
|
pub url: String,
|
||||||
|
/// Source kind (site-defined), e.g. "home" or "search".
|
||||||
|
pub kind: String,
|
||||||
|
pub density: String,
|
||||||
|
#[serde(default)]
|
||||||
|
pub filters: ColumnFilters,
|
||||||
|
/// Per-column feature flags over the global ones; names must be allow-listed by the app.
|
||||||
|
#[serde(default)]
|
||||||
|
pub flags: BTreeMap<String, bool>,
|
||||||
|
#[serde(default = "yes")]
|
||||||
|
pub unread: bool,
|
||||||
|
#[serde(default)]
|
||||||
|
pub read_seq: u32,
|
||||||
|
#[serde(default)]
|
||||||
|
pub jump_seq: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn yes() -> bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
|
||||||
|
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||||
|
pub struct ColumnFilters {
|
||||||
|
#[serde(default)]
|
||||||
|
pub terms: Vec<String>,
|
||||||
|
#[serde(default)]
|
||||||
|
pub hide_replies: bool,
|
||||||
|
#[serde(default)]
|
||||||
|
pub hide_reposts: bool,
|
||||||
|
#[serde(default)]
|
||||||
|
pub media_only: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const MAX_COLUMN_TERMS: usize = 32;
|
||||||
|
pub const MAX_COLUMN_TERM_CHARS: usize = 200;
|
||||||
|
pub const MAX_COLUMN_FLAGS: usize = 16;
|
||||||
|
|
||||||
|
impl ColumnConfig {
|
||||||
|
/// Bounds every field: the URL is exactly on the site, at most 32 filter terms of at most 200
|
||||||
|
/// characters without control characters, known densities, allow-listed flags only.
|
||||||
|
pub fn validated(mut self, site: &crate::site::SiteSpec, allowed_flags: &[&str]) -> Result<Self, String> {
|
||||||
|
if self.url.len() > 2048 {
|
||||||
|
return Err("VALIDATION: column URL too long".into());
|
||||||
|
}
|
||||||
|
let url = parse_web_url(&self.url)?;
|
||||||
|
if !site.is_origin(&url) {
|
||||||
|
return Err("VALIDATION: a column shows a page of the site".into());
|
||||||
|
}
|
||||||
|
self.url = url.to_string();
|
||||||
|
if self.kind.is_empty()
|
||||||
|
|| self.kind.len() > 24
|
||||||
|
|| !self.kind.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
|
||||||
|
{
|
||||||
|
return Err("VALIDATION: invalid column kind".into());
|
||||||
|
}
|
||||||
|
if !matches!(self.density.as_str(), "compact" | "comfortable") {
|
||||||
|
return Err("VALIDATION: invalid column density".into());
|
||||||
|
}
|
||||||
|
if self.filters.terms.len() > MAX_COLUMN_TERMS {
|
||||||
|
return Err("VALIDATION: too many column filters".into());
|
||||||
|
}
|
||||||
|
for term in &self.filters.terms {
|
||||||
|
if term.trim().is_empty() || term.chars().count() > MAX_COLUMN_TERM_CHARS || term.chars().any(char::is_control) {
|
||||||
|
return Err("VALIDATION: invalid column filter".into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if self.flags.len() > MAX_COLUMN_FLAGS || self.flags.keys().any(|key| !allowed_flags.contains(&key.as_str())) {
|
||||||
|
return Err("VALIDATION: column flag not allowed".into());
|
||||||
|
}
|
||||||
|
Ok(self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Hands a JSON value to a member of the page runtime: `window.<global>.<member>.<method>(value)`
|
/// Hands a JSON value to a member of the page runtime: `window.<global>.<member>.<method>(value)`
|
||||||
/// when the runtime exists, else parked in `window.<queue>` for the runtime to pick up at start.
|
/// when the runtime exists, else parked in `window.<queue>` for the runtime to pick up at start.
|
||||||
/// `json` must be serialized JSON (never page-supplied text).
|
/// `json` must be serialized JSON (never page-supplied text).
|
||||||
|
|
@ -253,7 +362,64 @@ mod tests {
|
||||||
#[test]
|
#[test]
|
||||||
fn layouts_default_to_the_default_profile() {
|
fn layouts_default_to_the_default_profile() {
|
||||||
let layout: TabLayout = serde_json::from_str(r#"{"id":"a","url":"https://a.test/","x":0,"y":0,"width":1,"height":1,"visible":true}"#).unwrap();
|
let layout: TabLayout = serde_json::from_str(r#"{"id":"a","url":"https://a.test/","x":0,"y":0,"width":1,"height":1,"visible":true}"#).unwrap();
|
||||||
assert_eq!((layout.profile.as_str(), layout.nav_redundant), ("default", false));
|
assert_eq!((layout.profile.as_str(), layout.nav_redundant, layout.role), ("default", false, TabRole::Pane));
|
||||||
|
let column: TabLayout =
|
||||||
|
serde_json::from_str(r#"{"id":"a","url":"https://a.test/","x":0,"y":0,"width":1,"height":1,"visible":true,"role":"column"}"#).unwrap();
|
||||||
|
assert_eq!(column.role, TabRole::Column);
|
||||||
|
assert!(serde_json::from_str::<TabLayout>(r#"{"id":"a","url":"u","x":0,"y":0,"width":1,"height":1,"visible":true,"role":"popup"}"#).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn deck_shortcuts_are_known_and_unread_is_capped() {
|
||||||
|
for name in [
|
||||||
|
"column-prev", "column-next", "column-1", "column-9", "column-page-prev", "column-page-next", "column-mark-read", "deck-compose",
|
||||||
|
"deck-toggle",
|
||||||
|
] {
|
||||||
|
assert!(valid_shortcut(name), "{name}");
|
||||||
|
}
|
||||||
|
assert!(!valid_shortcut("column-10") && !valid_shortcut("column-0") && !valid_shortcut("deck-post"));
|
||||||
|
assert_eq!((cap_unread(0), cap_unread(12), cap_unread(999), cap_unread(1_000_000)), (0, 12, 999, 999));
|
||||||
|
let state = TabState { id: "a".into(), unread: Some(3), ..Default::default() };
|
||||||
|
assert_eq!(serde_json::to_value(state).unwrap(), serde_json::json!({ "id": "a", "unread": 3 }));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn column(json: serde_json::Value) -> Result<ColumnConfig, String> {
|
||||||
|
serde_json::from_value::<ColumnConfig>(json)
|
||||||
|
.map_err(|error| error.to_string())?
|
||||||
|
.validated(&crate::site::testing::SITE, &["autoplayOff", "hideAds"])
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn column_config_is_bounded() {
|
||||||
|
let base = serde_json::json!({ "url": "https://x.com/home", "kind": "home", "density": "compact" });
|
||||||
|
let ok = column(base.clone()).unwrap();
|
||||||
|
assert!(ok.unread && ok.filters.terms.is_empty() && ok.read_seq == 0);
|
||||||
|
let full = serde_json::json!({
|
||||||
|
"url": "https://x.com/search?q=a&f=live", "kind": "search", "density": "comfortable",
|
||||||
|
"filters": { "terms": ["gm", "/^rt\\b/i"], "hideReplies": true, "hideReposts": false, "mediaOnly": true },
|
||||||
|
"flags": { "autoplayOff": true, "hideAds": false }, "unread": false, "readSeq": 4, "jumpSeq": 1
|
||||||
|
});
|
||||||
|
let full = column(full).unwrap();
|
||||||
|
assert_eq!((full.filters.terms.len(), full.flags.len(), full.unread, full.read_seq), (2, 2, false, 4));
|
||||||
|
let with = |key: &str, value: serde_json::Value| {
|
||||||
|
let mut json = base.clone();
|
||||||
|
json[key] = value;
|
||||||
|
column(json)
|
||||||
|
};
|
||||||
|
assert!(with("url", "https://evil.test/home".into()).is_err(), "other sites");
|
||||||
|
assert!(with("url", "javascript:alert(1)".into()).is_err());
|
||||||
|
assert!(with("url", format!("https://x.com/{}", "a".repeat(2100)).into()).is_err());
|
||||||
|
assert!(with("kind", "Home!".into()).is_err());
|
||||||
|
assert!(with("density", "tiny".into()).is_err());
|
||||||
|
assert!(with("flags", serde_json::json!({ "evalScript": true })).is_err(), "flags are allow-listed");
|
||||||
|
assert!(with("flags", serde_json::json!({ "autoplayOff": "yes" })).is_err());
|
||||||
|
assert!(with("filters", serde_json::json!({ "terms": vec!["t"; 33] })).is_err(), "at most 32 terms");
|
||||||
|
assert!(with("filters", serde_json::json!({ "terms": ["x".repeat(201)] })).is_err(), "at most 200 characters");
|
||||||
|
assert!(with("filters", serde_json::json!({ "terms": ["ok".repeat(100)] })).is_ok(), "exactly 200 is fine");
|
||||||
|
assert!(with("filters", serde_json::json!({ "terms": ["a\nb"] })).is_err(), "no control characters");
|
||||||
|
assert!(with("filters", serde_json::json!({ "terms": [" "] })).is_err());
|
||||||
|
assert!(with("filters", serde_json::json!({ "script": "x" })).is_err(), "unknown fields");
|
||||||
|
assert!(with("extra", true.into()).is_err(), "unknown fields");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|
|
||||||
453
packages/runtime/src/column.ts
Normal file
453
packages/runtime/src/column.ts
Normal file
|
|
@ -0,0 +1,453 @@
|
||||||
|
// Power User Mode, page side: a site tab that is a deck column (see shell/deckModel.ts). The shell
|
||||||
|
// lays the column out; native code hands this module the column's config. Here the page hides the
|
||||||
|
// site's chrome (rail, side column, floating buttons), lets the content column fill the width,
|
||||||
|
// applies the column's density and filters, and tracks unread items. It never makes a request and
|
||||||
|
// never clicks anything on its own except what the adapter's `prepare` does (navigation only, e.g.
|
||||||
|
// selecting one of the site's own timeline tabs). Unread items are counted from what the site has
|
||||||
|
// rendered: new item ids above the ones already seen, not yet scrolled into view. Only the count
|
||||||
|
// leaves the page (the adapter reports it through its own bridge).
|
||||||
|
|
||||||
|
import { watchDom, type DomWatchHandle } from './domHub.ts';
|
||||||
|
|
||||||
|
export type ColumnDensity = 'compact' | 'comfortable';
|
||||||
|
|
||||||
|
export type ColumnFiltersConfig = { terms: string[]; hideReplies: boolean; hideReposts: boolean; mediaOnly: boolean };
|
||||||
|
|
||||||
|
/** What native code delivers for one column (validated there too; see waybetter-host `ColumnConfig`). */
|
||||||
|
export type ColumnConfig = {
|
||||||
|
/** The column's own page (its source); chrome that only makes sense elsewhere hides only here. */
|
||||||
|
url: string;
|
||||||
|
density: ColumnDensity;
|
||||||
|
filters: ColumnFiltersConfig;
|
||||||
|
/** Count unread items and report them. */
|
||||||
|
unread: boolean;
|
||||||
|
/** Increments when the shell asks to mark everything read / jump to the first unread item. */
|
||||||
|
readSeq: number;
|
||||||
|
jumpSeq: number;
|
||||||
|
/** Source kind (adapter-defined), for `prepare`. */
|
||||||
|
kind: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ItemKind = { reply: boolean; repost: boolean; media: boolean };
|
||||||
|
|
||||||
|
export type ColumnSite = {
|
||||||
|
/** Prefix of the attributes/ids this module owns (`data-<prefix>-column`, `<prefix>-column-css`). */
|
||||||
|
prefix: string;
|
||||||
|
/** The site's content column; it fills the column width. */
|
||||||
|
keep: string;
|
||||||
|
/** Always hidden in a column. */
|
||||||
|
hide: readonly string[];
|
||||||
|
/** Hidden only on the column's own page (e.g. a page title the column header repeats). */
|
||||||
|
sourceHide?: readonly string[];
|
||||||
|
/** Items for filters and the unread tracker. */
|
||||||
|
itemSelector: string;
|
||||||
|
/** The element hidden for a filtered item (default: the item itself). */
|
||||||
|
container?(item: Element): Element;
|
||||||
|
/** A stable id for an item (e.g. a post id), or null to ignore it. */
|
||||||
|
itemId(item: Element): string | null;
|
||||||
|
itemKind?(item: Element): ItemKind;
|
||||||
|
itemText?(item: Element): string;
|
||||||
|
/** Items the site announces but has not rendered yet (e.g. a "Show 12 posts" button); 0 = none. */
|
||||||
|
pendingCount?(doc: Document): number;
|
||||||
|
/** Site CSS for the column (density-aware); every rule should be scoped to `html[data-<prefix>-column]`. */
|
||||||
|
css?(density: ColumnDensity): string;
|
||||||
|
/** Navigation-only setup on the source page (e.g. select a timeline tab); true once done. */
|
||||||
|
prepare?(doc: Document, config: ColumnConfig): boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ColumnHandle = {
|
||||||
|
set(config: unknown): void;
|
||||||
|
markRead(): void;
|
||||||
|
jumpToUnread(): void;
|
||||||
|
/** Current unread count (tracked + pending), 0 when off. */
|
||||||
|
unread(): number;
|
||||||
|
dispose(): void;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ColumnWindow = Window & typeof globalThis;
|
||||||
|
|
||||||
|
const MAX_TERMS = 32;
|
||||||
|
const MAX_TERM_CHARS = 200;
|
||||||
|
const MAX_IDS = 2000;
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Config and filters (pure)
|
||||||
|
|
||||||
|
export function normalizeColumnConfig(value: unknown): ColumnConfig | null {
|
||||||
|
if (!value || typeof value !== 'object') return null;
|
||||||
|
const raw = value as Record<string, unknown>;
|
||||||
|
if (typeof raw.url !== 'string' || raw.url.length > 2048) return null;
|
||||||
|
const filters = (raw.filters && typeof raw.filters === 'object' ? raw.filters : {}) as Record<string, unknown>;
|
||||||
|
const terms = (Array.isArray(filters.terms) ? filters.terms : [])
|
||||||
|
.filter((term): term is string => typeof term === 'string' && term.trim().length > 0 && term.length <= MAX_TERM_CHARS)
|
||||||
|
.slice(0, MAX_TERMS);
|
||||||
|
const seq = (n: unknown) => (typeof n === 'number' && Number.isFinite(n) && n >= 0 ? Math.floor(n) : 0);
|
||||||
|
return {
|
||||||
|
url: raw.url,
|
||||||
|
density: raw.density === 'comfortable' ? 'comfortable' : 'compact',
|
||||||
|
filters: { terms, hideReplies: filters.hideReplies === true, hideReposts: filters.hideReposts === true, mediaOnly: filters.mediaOnly === true },
|
||||||
|
unread: raw.unread !== false,
|
||||||
|
readSeq: seq(raw.readSeq),
|
||||||
|
jumpSeq: seq(raw.jumpSeq),
|
||||||
|
kind: typeof raw.kind === 'string' && raw.kind.length <= 24 ? raw.kind : '',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `/pattern/flags` → RegExp (flags i, m, s, u only); anything else is a plain keyword. Invalid → null. */
|
||||||
|
export function parseTerm(term: string): RegExp | string | null {
|
||||||
|
const text = term.trim();
|
||||||
|
if (!text) return null;
|
||||||
|
const match = /^\/(.+)\/([imsu]*)$/.exec(text);
|
||||||
|
if (!match) return text.toLowerCase();
|
||||||
|
try {
|
||||||
|
return new RegExp(match[1]!, match[2]!.includes('i') ? match[2] : `${match[2]}i`);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export type FilterInput = { text: string } & ItemKind;
|
||||||
|
|
||||||
|
/** A predicate that says whether an item is hidden by the column's filters. */
|
||||||
|
export function compileFilters(filters: ColumnFiltersConfig): (item: FilterInput) => boolean {
|
||||||
|
const terms = filters.terms.map(parseTerm).filter((term): term is RegExp | string => term !== null);
|
||||||
|
const active = terms.length > 0 || filters.hideReplies || filters.hideReposts || filters.mediaOnly;
|
||||||
|
if (!active) return () => false;
|
||||||
|
return item => {
|
||||||
|
if (filters.hideReplies && item.reply) return true;
|
||||||
|
if (filters.hideReposts && item.repost) return true;
|
||||||
|
if (filters.mediaOnly && !item.media) return true;
|
||||||
|
if (!terms.length) return false;
|
||||||
|
const lower = item.text.toLowerCase();
|
||||||
|
for (const term of terms) {
|
||||||
|
if (typeof term === 'string' ? lower.includes(term) : term.test(item.text)) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Same page: origin, path (trailing slash ignored) and query. */
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// Unread tracking (pure: fed with the rendered items in document order)
|
||||||
|
|
||||||
|
export type UnreadTracker = {
|
||||||
|
/**
|
||||||
|
* The rendered items, top to bottom, and which of them are on screen right now. The first
|
||||||
|
* non-empty observation is the baseline (read). Later, an id rendered above the topmost read
|
||||||
|
* id and not on screen is unread; ids below it are older items (read).
|
||||||
|
*/
|
||||||
|
observe(ordered: readonly string[], onScreen: ReadonlySet<string>): void;
|
||||||
|
/** An item came on screen. */
|
||||||
|
seen(id: string): void;
|
||||||
|
markRead(): void;
|
||||||
|
count(): number;
|
||||||
|
/** The unread item closest to the read ones (the next one to read, scrolling up), if rendered. */
|
||||||
|
nextUnread(ordered: readonly string[]): string | null;
|
||||||
|
isUnread(id: string): boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function createUnreadTracker(): UnreadTracker {
|
||||||
|
const read = new Set<string>();
|
||||||
|
const unread = new Set<string>();
|
||||||
|
let baseline = false;
|
||||||
|
const remember = (set: Set<string>, id: string) => {
|
||||||
|
set.add(id);
|
||||||
|
if (set.size > MAX_IDS) set.delete(set.values().next().value as string);
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
observe(ordered, onScreen) {
|
||||||
|
if (!ordered.length) return;
|
||||||
|
if (!baseline) {
|
||||||
|
baseline = true;
|
||||||
|
for (const id of ordered) remember(read, id);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const topRead = ordered.findIndex(id => read.has(id));
|
||||||
|
ordered.forEach((id, index) => {
|
||||||
|
if (read.has(id) || unread.has(id)) {
|
||||||
|
if (onScreen.has(id) && unread.delete(id)) remember(read, id);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (topRead >= 0 && index < topRead && !onScreen.has(id)) remember(unread, id);
|
||||||
|
else remember(read, id);
|
||||||
|
});
|
||||||
|
},
|
||||||
|
seen(id) {
|
||||||
|
if (unread.delete(id)) remember(read, id);
|
||||||
|
},
|
||||||
|
markRead() {
|
||||||
|
for (const id of unread) remember(read, id);
|
||||||
|
unread.clear();
|
||||||
|
},
|
||||||
|
count: () => unread.size,
|
||||||
|
nextUnread(ordered) {
|
||||||
|
for (let i = ordered.length - 1; i >= 0; i--) if (unread.has(ordered[i]!)) return ordered[i]!;
|
||||||
|
return null;
|
||||||
|
},
|
||||||
|
isUnread: id => unread.has(id),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------------------------
|
||||||
|
// The page module
|
||||||
|
|
||||||
|
const names = (site: ColumnSite) => ({
|
||||||
|
style: `${site.prefix}-column-css`,
|
||||||
|
column: `data-${site.prefix}-column`,
|
||||||
|
home: `data-${site.prefix}-column-home`,
|
||||||
|
density: `data-${site.prefix}-density`,
|
||||||
|
filtered: `data-${site.prefix}-filtered`,
|
||||||
|
unread: `data-${site.prefix}-unread`,
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Pure: the module's stylesheet. Every rule is scoped to the column attribute on <html>. */
|
||||||
|
export function buildColumnCss(site: ColumnSite, density: ColumnDensity): string {
|
||||||
|
const n = names(site);
|
||||||
|
const root = `html[${n.column}]`;
|
||||||
|
const rules = [
|
||||||
|
site.hide.length ? `${root} :is(${site.hide.join(', ')}) { display: none !important; }` : '',
|
||||||
|
site.sourceHide?.length ? `${root}[${n.home}] :is(${site.sourceHide.join(', ')}) { display: none !important; }` : '',
|
||||||
|
`${root} ${site.keep} { width: 100% !important; max-width: none !important; min-width: 0 !important; flex: 1 1 auto !important; }`,
|
||||||
|
`${root} [${n.filtered}] { display: none !important; }`,
|
||||||
|
// Narrow columns scroll without a scrollbar (the deck header shows where you are: unread count).
|
||||||
|
`${root} { scrollbar-width: none; }`,
|
||||||
|
site.css?.(density) ?? '',
|
||||||
|
];
|
||||||
|
return rules.filter(Boolean).join('\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
export type ColumnOptions = {
|
||||||
|
/** Called with the unread count (tracked + pending) whenever it changes, at most every 250 ms. */
|
||||||
|
onUnread?(count: number): void;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function installColumnMode(win: ColumnWindow, site: ColumnSite, options: ColumnOptions = {}): ColumnHandle {
|
||||||
|
const doc = win.document;
|
||||||
|
const n = names(site);
|
||||||
|
const root = () => doc.documentElement as HTMLElement | null;
|
||||||
|
let config: ColumnConfig | null = null;
|
||||||
|
let matcher: (item: FilterInput) => boolean = () => false;
|
||||||
|
let tracker = createUnreadTracker();
|
||||||
|
let watch: DomWatchHandle | null = null;
|
||||||
|
let observer: IntersectionObserver | null = null;
|
||||||
|
const observed = new WeakSet<Element>();
|
||||||
|
const ids = new WeakMap<Element, string>();
|
||||||
|
let prepared = false;
|
||||||
|
let lastReported = -1;
|
||||||
|
let reportTimer = 0;
|
||||||
|
let lastUrl = '';
|
||||||
|
let lastSeq = { read: -1, jump: -1 };
|
||||||
|
|
||||||
|
const onSource = () => !!config && isSourcePage(win.location.href, config.url);
|
||||||
|
|
||||||
|
const ensureStyle = () => {
|
||||||
|
if (!config) return;
|
||||||
|
let style = doc.getElementById(n.style) as HTMLStyleElement | null;
|
||||||
|
if (!style) {
|
||||||
|
const parent = doc.head || root();
|
||||||
|
if (!parent) return;
|
||||||
|
style = doc.createElement('style');
|
||||||
|
style.id = n.style;
|
||||||
|
parent.appendChild(style);
|
||||||
|
}
|
||||||
|
const css = buildColumnCss(site, config.density);
|
||||||
|
if (style.textContent !== css) style.textContent = css;
|
||||||
|
};
|
||||||
|
|
||||||
|
const kindOf = (item: Element): ItemKind => site.itemKind?.(item) ?? { reply: false, repost: false, media: false };
|
||||||
|
const textOf = (item: Element) => site.itemText?.(item) ?? item.textContent ?? '';
|
||||||
|
|
||||||
|
/** The column is on screen: the page is visible and the webview has a real size (hosts shrink a
|
||||||
|
* hidden tab webview to a pixel, and not every engine reports it as hidden). */
|
||||||
|
const shown = () => doc.visibilityState !== 'hidden' && win.innerWidth > 40 && win.innerHeight > 40;
|
||||||
|
const onScreen = (item: Element) => {
|
||||||
|
if (!shown()) return false;
|
||||||
|
const box = item.getBoundingClientRect();
|
||||||
|
const height = win.innerHeight || doc.documentElement.clientHeight;
|
||||||
|
// Mostly in view: its top is on screen and at least 40 px (or all of it) is visible.
|
||||||
|
return box.bottom > 0 && box.top < height && Math.min(box.bottom, height) - Math.max(box.top, 0) >= Math.min(40, box.height);
|
||||||
|
};
|
||||||
|
|
||||||
|
const pending = () => {
|
||||||
|
try { return Math.max(0, Math.floor(site.pendingCount?.(doc) ?? 0)); } catch { return 0; }
|
||||||
|
};
|
||||||
|
|
||||||
|
const report = () => {
|
||||||
|
if (!options.onUnread) return;
|
||||||
|
const count = config?.unread ? Math.min(999, tracker.count() + pending()) : 0;
|
||||||
|
if (count === lastReported) return;
|
||||||
|
if (reportTimer) return;
|
||||||
|
reportTimer = win.setTimeout(() => {
|
||||||
|
reportTimer = 0;
|
||||||
|
const now = config?.unread ? Math.min(999, tracker.count() + pending()) : 0;
|
||||||
|
if (now === lastReported) return;
|
||||||
|
lastReported = now;
|
||||||
|
try { options.onUnread?.(now); } catch { /* reporting is best effort */ }
|
||||||
|
}, 250);
|
||||||
|
};
|
||||||
|
|
||||||
|
const ensureObserver = () => {
|
||||||
|
if (observer || typeof win.IntersectionObserver !== 'function') return;
|
||||||
|
observer = new win.IntersectionObserver(entries => {
|
||||||
|
if (!shown()) return;
|
||||||
|
let changed = false;
|
||||||
|
for (const entry of entries) {
|
||||||
|
if (!entry.isIntersecting) continue;
|
||||||
|
const id = ids.get(entry.target);
|
||||||
|
if (id && tracker.isUnread(id)) { tracker.seen(id); changed = true; }
|
||||||
|
if (id) entry.target.removeAttribute(n.unread);
|
||||||
|
}
|
||||||
|
if (changed) report();
|
||||||
|
}, { threshold: [0, 0.5, 1] });
|
||||||
|
};
|
||||||
|
|
||||||
|
const items = (): Element[] => Array.from(doc.querySelectorAll(site.itemSelector));
|
||||||
|
|
||||||
|
const scan = () => {
|
||||||
|
if (!config) return;
|
||||||
|
const html = root();
|
||||||
|
if (!html) return;
|
||||||
|
// A config delivered at document start arrives before the parser has created <html>.
|
||||||
|
if (!html.hasAttribute(n.column)) html.setAttribute(n.column, '');
|
||||||
|
if (html.getAttribute(n.density) !== config.density) html.setAttribute(n.density, config.density);
|
||||||
|
ensureStyle();
|
||||||
|
const source = onSource();
|
||||||
|
if (source) html.setAttribute(n.home, '');
|
||||||
|
else html.removeAttribute(n.home);
|
||||||
|
if (win.location.href !== lastUrl) { lastUrl = win.location.href; prepared = false; }
|
||||||
|
if (source && !prepared && site.prepare) {
|
||||||
|
try { prepared = site.prepare(doc, config); } catch { prepared = true; }
|
||||||
|
}
|
||||||
|
const list = items();
|
||||||
|
const ordered: string[] = [];
|
||||||
|
const visible = new Set<string>();
|
||||||
|
for (const item of list) {
|
||||||
|
const container = site.container?.(item) ?? item;
|
||||||
|
let hidden = false;
|
||||||
|
if (source) {
|
||||||
|
try { hidden = matcher({ text: textOf(item), ...kindOf(item) }); } catch { hidden = false; }
|
||||||
|
}
|
||||||
|
if (hidden) container.setAttribute(n.filtered, '');
|
||||||
|
else if (container.hasAttribute(n.filtered)) container.removeAttribute(n.filtered);
|
||||||
|
if (!source || !config.unread || hidden) continue;
|
||||||
|
let id: string | null = null;
|
||||||
|
try { id = site.itemId(item); } catch { id = null; }
|
||||||
|
if (!id || ordered.includes(id)) continue;
|
||||||
|
ids.set(item, id);
|
||||||
|
ordered.push(id);
|
||||||
|
if (onScreen(item)) visible.add(id);
|
||||||
|
ensureObserver();
|
||||||
|
if (observer && !observed.has(item)) { observed.add(item); observer.observe(item); }
|
||||||
|
}
|
||||||
|
if (source && config.unread) {
|
||||||
|
tracker.observe(ordered, visible);
|
||||||
|
for (const item of list) {
|
||||||
|
const id = ids.get(item);
|
||||||
|
if (!id) continue;
|
||||||
|
if (tracker.isUnread(id)) item.setAttribute(n.unread, '');
|
||||||
|
else if (item.hasAttribute(n.unread)) item.removeAttribute(n.unread);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
report();
|
||||||
|
};
|
||||||
|
|
||||||
|
const onKey = (event: KeyboardEvent) => {
|
||||||
|
if (!config || !event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return;
|
||||||
|
const key = event.key.toLowerCase();
|
||||||
|
if (key !== 'r' && key !== 'u') return;
|
||||||
|
event.preventDefault();
|
||||||
|
event.stopImmediatePropagation();
|
||||||
|
if (key === 'r') handle.markRead();
|
||||||
|
else handle.jumpToUnread();
|
||||||
|
};
|
||||||
|
|
||||||
|
const onVisibility = () => { if (shown()) watch?.schedule(); };
|
||||||
|
|
||||||
|
const start = () => {
|
||||||
|
if (watch) return;
|
||||||
|
watch = watchDom(win, scan, { phase: 'write' });
|
||||||
|
win.addEventListener('keydown', onKey, true);
|
||||||
|
doc.addEventListener('visibilitychange', onVisibility);
|
||||||
|
win.addEventListener('resize', onVisibility);
|
||||||
|
win.addEventListener('scroll', onScroll, { passive: true });
|
||||||
|
};
|
||||||
|
|
||||||
|
let scrollFrame = 0;
|
||||||
|
const onScroll = () => {
|
||||||
|
if (scrollFrame) return;
|
||||||
|
scrollFrame = win.requestAnimationFrame(() => { scrollFrame = 0; report(); });
|
||||||
|
};
|
||||||
|
|
||||||
|
const stop = () => {
|
||||||
|
watch?.dispose();
|
||||||
|
watch = null;
|
||||||
|
observer?.disconnect();
|
||||||
|
observer = null;
|
||||||
|
win.removeEventListener('keydown', onKey, true);
|
||||||
|
doc.removeEventListener('visibilitychange', onVisibility);
|
||||||
|
win.removeEventListener('resize', onVisibility);
|
||||||
|
win.removeEventListener('scroll', onScroll);
|
||||||
|
if (reportTimer) { win.clearTimeout(reportTimer); reportTimer = 0; }
|
||||||
|
const html = root();
|
||||||
|
html?.removeAttribute(n.column);
|
||||||
|
html?.removeAttribute(n.home);
|
||||||
|
html?.removeAttribute(n.density);
|
||||||
|
doc.getElementById(n.style)?.remove();
|
||||||
|
for (const el of Array.from(doc.querySelectorAll(`[${n.filtered}], [${n.unread}]`))) {
|
||||||
|
el.removeAttribute(n.filtered);
|
||||||
|
el.removeAttribute(n.unread);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handle: ColumnHandle = {
|
||||||
|
set(value) {
|
||||||
|
const next = normalizeColumnConfig(value);
|
||||||
|
if (!next) {
|
||||||
|
if (config) { config = null; stop(); lastReported = -1; options.onUnread?.(0); }
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const first = !config;
|
||||||
|
const sourceChanged = !!config && config.url !== next.url;
|
||||||
|
config = next;
|
||||||
|
matcher = compileFilters(next.filters);
|
||||||
|
if (first || sourceChanged) { tracker = createUnreadTracker(); prepared = false; }
|
||||||
|
const html = root();
|
||||||
|
html?.setAttribute(n.column, '');
|
||||||
|
html?.setAttribute(n.density, next.density);
|
||||||
|
if (!first && lastSeq.read >= 0 && next.readSeq !== lastSeq.read) handle.markRead();
|
||||||
|
if (!first && lastSeq.jump >= 0 && next.jumpSeq !== lastSeq.jump) handle.jumpToUnread();
|
||||||
|
lastSeq = { read: next.readSeq, jump: next.jumpSeq };
|
||||||
|
ensureStyle();
|
||||||
|
start();
|
||||||
|
watch?.schedule();
|
||||||
|
if (!next.unread) report();
|
||||||
|
},
|
||||||
|
markRead() {
|
||||||
|
tracker.markRead();
|
||||||
|
for (const el of Array.from(doc.querySelectorAll(`[${n.unread}]`))) el.removeAttribute(n.unread);
|
||||||
|
report();
|
||||||
|
},
|
||||||
|
jumpToUnread() {
|
||||||
|
const list = items();
|
||||||
|
const ordered = list.map(item => ids.get(item)).filter((id): id is string => !!id);
|
||||||
|
const target = tracker.nextUnread(ordered);
|
||||||
|
const element = target ? list.find(item => ids.get(item) === target) : null;
|
||||||
|
if (element) (site.container?.(element) ?? element).scrollIntoView({ block: 'start' });
|
||||||
|
else if (pending() > 0) win.scrollTo({ top: 0 });
|
||||||
|
},
|
||||||
|
unread: () => (config?.unread ? Math.min(999, tracker.count() + pending()) : 0),
|
||||||
|
dispose() { config = null; stop(); },
|
||||||
|
};
|
||||||
|
return handle;
|
||||||
|
}
|
||||||
|
|
@ -4,6 +4,7 @@
|
||||||
import { configureDomHub } from './domHub.ts';
|
import { configureDomHub } from './domHub.ts';
|
||||||
import { configureNetHub } from './netHub.ts';
|
import { configureNetHub } from './netHub.ts';
|
||||||
import type { AccountSite } from './accountReport.ts';
|
import type { AccountSite } from './accountReport.ts';
|
||||||
|
import type { ColumnSite } from './column.ts';
|
||||||
import type { LinkSite } from './linkRouting.ts';
|
import type { LinkSite } from './linkRouting.ts';
|
||||||
import type { RailSite } from './paneNav.ts';
|
import type { RailSite } from './paneNav.ts';
|
||||||
import type { PluginApiSite } from './pluginApi.ts';
|
import type { PluginApiSite } from './pluginApi.ts';
|
||||||
|
|
@ -25,6 +26,8 @@ export type SiteAdapter = {
|
||||||
plugins: PluginApiSite;
|
plugins: PluginApiSite;
|
||||||
/** Split-view rail hiding; omit when the site has no navigation rail. */
|
/** Split-view rail hiding; omit when the site has no navigation rail. */
|
||||||
rail?: RailSite;
|
rail?: RailSite;
|
||||||
|
/** Power User Mode: how a site tab becomes a narrow deck column (runtime/column.ts); omit = no decks. */
|
||||||
|
column?: ColumnSite;
|
||||||
/** Signed-in account reader for the account switcher. */
|
/** Signed-in account reader for the account switcher. */
|
||||||
account?: AccountSite;
|
account?: AccountSite;
|
||||||
/** Which in-page clicks the "links to site pages" setting may divert. */
|
/** Which in-page clicks the "links to site pages" setting may divert. */
|
||||||
|
|
|
||||||
106
packages/runtime/tests/column.test.ts
Normal file
106
packages/runtime/tests/column.test.ts
Normal file
|
|
@ -0,0 +1,106 @@
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import test from 'node:test';
|
||||||
|
import {
|
||||||
|
buildColumnCss, compileFilters, createUnreadTracker, isSourcePage, normalizeColumnConfig, parseTerm, type ColumnSite,
|
||||||
|
} from '../src/column.ts';
|
||||||
|
|
||||||
|
const SITE: ColumnSite = {
|
||||||
|
prefix: 'demo',
|
||||||
|
keep: '#content',
|
||||||
|
hide: ['nav.rail', '.fab'],
|
||||||
|
sourceHide: ['.page-title'],
|
||||||
|
itemSelector: 'article',
|
||||||
|
itemId: item => item.getAttribute('data-id'),
|
||||||
|
css: density => `html[data-demo-column][data-demo-density="${density}"] article { padding: 0 }`,
|
||||||
|
};
|
||||||
|
|
||||||
|
const item = (text: string, kind: Partial<{ reply: boolean; repost: boolean; media: boolean }> = {}) =>
|
||||||
|
({ text, reply: false, repost: false, media: false, ...kind });
|
||||||
|
|
||||||
|
test('column: config is normalized and bounded', () => {
|
||||||
|
assert.equal(normalizeColumnConfig(null), null);
|
||||||
|
assert.equal(normalizeColumnConfig({ url: 5 }), null);
|
||||||
|
const config = normalizeColumnConfig({
|
||||||
|
url: 'https://site.test/home', density: 'weird', filters: { terms: ['ok', '', 7, 'x'.repeat(201), ...Array(40).fill('t')], mediaOnly: 'yes' },
|
||||||
|
readSeq: -3, jumpSeq: 2.7, kind: 'home',
|
||||||
|
})!;
|
||||||
|
assert.equal(config.density, 'compact');
|
||||||
|
assert.equal(config.filters.terms.length, 32);
|
||||||
|
assert.equal(config.filters.terms[0], 'ok');
|
||||||
|
assert.equal(config.filters.mediaOnly, false);
|
||||||
|
assert.deepEqual([config.readSeq, config.jumpSeq, config.unread], [0, 2, true]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('column: terms are keywords or /regex/flags; bad regexes are skipped', () => {
|
||||||
|
assert.equal(parseTerm(' Crypto '), 'crypto');
|
||||||
|
const re = parseTerm('/gm+\\b/');
|
||||||
|
assert.ok(re instanceof RegExp && re.flags.includes('i'), 'regexes are case-insensitive');
|
||||||
|
assert.equal(parseTerm('/(unclosed/'), null);
|
||||||
|
assert.equal(parseTerm('/a/g'), '/a/g', 'only i, m, s, u flags make a regex');
|
||||||
|
assert.equal(parseTerm(' '), null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('column: filters hide replies, reposts, non-media and matching text', () => {
|
||||||
|
const none = compileFilters({ terms: [], hideReplies: false, hideReposts: false, mediaOnly: false });
|
||||||
|
assert.equal(none(item('anything', { reply: true })), false);
|
||||||
|
const f = compileFilters({ terms: ['giveaway', '/^gm\\b/', '/(bad/'], hideReplies: true, hideReposts: true, mediaOnly: false });
|
||||||
|
assert.equal(f(item('Huge GIVEAWAY today')), true);
|
||||||
|
assert.equal(f(item('GM frens')), true);
|
||||||
|
assert.equal(f(item('a normal post')), false);
|
||||||
|
assert.equal(f(item('normal', { reply: true })), true);
|
||||||
|
assert.equal(f(item('normal', { repost: true })), true);
|
||||||
|
const media = compileFilters({ terms: [], hideReplies: false, hideReposts: false, mediaOnly: true });
|
||||||
|
assert.equal(media(item('text only')), true);
|
||||||
|
assert.equal(media(item('photo', { media: true })), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('column: the source page is compared by origin, path and query', () => {
|
||||||
|
assert.equal(isSourcePage('https://site.test/home/', 'https://site.test/home'), true);
|
||||||
|
assert.equal(isSourcePage('https://site.test/search?q=a&f=live', 'https://site.test/search?q=a&f=live'), true);
|
||||||
|
assert.equal(isSourcePage('https://site.test/search?q=b&f=live', 'https://site.test/search?q=a&f=live'), false);
|
||||||
|
assert.equal(isSourcePage('https://site.test/home/status/1', 'https://site.test/home'), false);
|
||||||
|
assert.equal(isSourcePage('https://other.test/home', 'https://site.test/home'), false);
|
||||||
|
assert.equal(isSourcePage('nonsense', 'https://site.test/home'), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('column: CSS is scoped to the column attribute and hides chrome', () => {
|
||||||
|
const css = buildColumnCss(SITE, 'comfortable');
|
||||||
|
for (const line of css.split('\n').filter(Boolean)) assert.match(line, /^html\[data-demo-column\]/, line);
|
||||||
|
assert.match(css, /:is\(nav\.rail, \.fab\) \{ display: none !important; \}/);
|
||||||
|
assert.match(css, /html\[data-demo-column\]\[data-demo-column-home\] :is\(\.page-title\)/);
|
||||||
|
assert.match(css, /#content \{ width: 100% !important; max-width: none !important/);
|
||||||
|
assert.match(css, /\[data-demo-filtered\] \{ display: none !important; \}/);
|
||||||
|
assert.match(css, /data-demo-density="comfortable"/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('unread: first render is the baseline; new ids above the read ones count until seen', () => {
|
||||||
|
const t = createUnreadTracker();
|
||||||
|
t.observe([], new Set());
|
||||||
|
t.observe(['c', 'b', 'a'], new Set(['c', 'b', 'a']));
|
||||||
|
assert.equal(t.count(), 0, 'baseline');
|
||||||
|
// Two new posts rendered above while the user is scrolled down (not on screen).
|
||||||
|
t.observe(['e', 'd', 'c', 'b', 'a'], new Set(['a']));
|
||||||
|
assert.equal(t.count(), 2);
|
||||||
|
assert.equal(t.nextUnread(['e', 'd', 'c', 'b', 'a']), 'd', 'the one closest to what was read');
|
||||||
|
// Older posts loaded below are read.
|
||||||
|
t.observe(['e', 'd', 'c', 'b', 'a', 'z', 'y'], new Set());
|
||||||
|
assert.equal(t.count(), 2);
|
||||||
|
t.seen('d');
|
||||||
|
assert.equal(t.count(), 1);
|
||||||
|
// A new post rendered while on screen is read at once.
|
||||||
|
t.observe(['f', 'e', 'd', 'c'], new Set(['f']));
|
||||||
|
assert.equal(t.count(), 1);
|
||||||
|
assert.equal(t.isUnread('e'), true);
|
||||||
|
t.markRead();
|
||||||
|
assert.equal(t.count(), 0);
|
||||||
|
assert.equal(t.nextUnread(['f', 'e']), null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('unread: items rendered on screen again are marked read by observe', () => {
|
||||||
|
const t = createUnreadTracker();
|
||||||
|
t.observe(['a'], new Set());
|
||||||
|
t.observe(['b', 'a'], new Set());
|
||||||
|
assert.equal(t.count(), 1);
|
||||||
|
t.observe(['b', 'a'], new Set(['b']));
|
||||||
|
assert.equal(t.count(), 0);
|
||||||
|
});
|
||||||
298
packages/shell/src/deckModel.ts
Normal file
298
packages/shell/src/deckModel.ts
Normal file
|
|
@ -0,0 +1,298 @@
|
||||||
|
// 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;
|
||||||
|
}
|
||||||
|
|
@ -4,7 +4,9 @@
|
||||||
// different accounts keep theirs: the rail's account button is the only in-page sign of which
|
// different accounts keep theirs: the rail's account button is the only in-page sign of which
|
||||||
// account a pane is.
|
// account a pane is.
|
||||||
|
|
||||||
export type PaneBox = { id: string; url: string; profile: string; x: number; y: number; visible: boolean };
|
/** `role`: 'column' boxes are deck columns (Power User Mode); they hide the site's chrome themselves
|
||||||
|
* and never take part in the rail rules. Missing = an ordinary pane. */
|
||||||
|
export type PaneBox = { id: string; url: string; profile: string; x: number; y: number; visible: boolean; role?: 'pane' | 'column' };
|
||||||
|
|
||||||
/** `besideOf`: the source group ids whose "beside" links this group's tabs were opened for. */
|
/** `besideOf`: the source group ids whose "beside" links this group's tabs were opened for. */
|
||||||
export type GroupBox = { id: string; left: number; top: number; right: number; bottom: number; besideOf?: readonly string[] };
|
export type GroupBox = { id: string; left: number; top: number; right: number; bottom: number; besideOf?: readonly string[] };
|
||||||
|
|
@ -30,7 +32,7 @@ export function redundantNavPanes(panes: readonly PaneBox[], isSiteUrl: (url: st
|
||||||
const lead = new Map<string, PaneBox>();
|
const lead = new Map<string, PaneBox>();
|
||||||
const redundant = new Set<string>();
|
const redundant = new Set<string>();
|
||||||
const ordered = panes
|
const ordered = panes
|
||||||
.filter(pane => pane.visible && isSiteUrl(pane.url))
|
.filter(pane => pane.visible && pane.role !== 'column' && isSiteUrl(pane.url))
|
||||||
.sort((a, b) => a.x - b.x || a.y - b.y || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
|
.sort((a, b) => a.x - b.x || a.y - b.y || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
|
||||||
for (const pane of ordered) {
|
for (const pane of ordered) {
|
||||||
if (lead.has(pane.profile)) redundant.add(pane.id);
|
if (lead.has(pane.profile)) redundant.add(pane.id);
|
||||||
|
|
|
||||||
122
packages/shell/tests/deckModel.test.ts
Normal file
122
packages/shell/tests/deckModel.test.ts
Normal file
|
|
@ -0,0 +1,122 @@
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import test from 'node:test';
|
||||||
|
import {
|
||||||
|
COLUMN_GAP, MAX_COLUMNS, MAX_TERMS, columnUrl, layoutColumns, moveColumn, moveFocus, normalizeDeck, normalizeDecks, pageOf, paginate, unreadTotal,
|
||||||
|
type ColumnSource,
|
||||||
|
} from '../src/deckModel.ts';
|
||||||
|
import { redundantNavPanes, withNavRedundant, type PaneBox } from '../src/paneModel.ts';
|
||||||
|
|
||||||
|
const col = (id: string, width = 360) => ({ id, width });
|
||||||
|
|
||||||
|
test('deck: normalizeDeck bounds everything it reads', () => {
|
||||||
|
const columns = Array.from({ length: MAX_COLUMNS + 5 }, (_, i) => ({
|
||||||
|
id: `c${i}`, tabId: `t${i}`, profile: 'default', source: { kind: 'home' }, width: 9999,
|
||||||
|
flags: { disableVideoAutoplay: true, evil: 'yes', notAllowed: true }, filters: { terms: ['a', 'a', '', 'x'.repeat(201), ...Array.from({ length: 40 }, (_, j) => `t${j}`)], hideReplies: 1 },
|
||||||
|
}));
|
||||||
|
const deck = normalizeDeck({ id: 'd1', name: ' Monitor ', columns }, { kinds: ['home'], flags: ['disableVideoAutoplay'] })!;
|
||||||
|
assert.equal(deck.name, 'Monitor');
|
||||||
|
assert.equal(deck.columns.length, MAX_COLUMNS);
|
||||||
|
const first = deck.columns[0]!;
|
||||||
|
assert.equal(first.width, 640, 'width clamped');
|
||||||
|
assert.deepEqual(first.flags, { disableVideoAutoplay: true }, 'only allow-listed boolean flags');
|
||||||
|
assert.equal(first.filters.terms.length, MAX_TERMS);
|
||||||
|
assert.equal(first.filters.terms[0], 'a', 'duplicates and empty/oversized terms dropped');
|
||||||
|
assert.ok(!first.filters.terms.includes('x'.repeat(201)));
|
||||||
|
assert.equal(first.filters.hideReplies, false, 'non-boolean filter flags are off');
|
||||||
|
assert.equal(normalizeDeck({ id: 'bad id!', columns: [] }), null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('deck: unknown kinds, duplicate ids and removed profiles', () => {
|
||||||
|
const deck = normalizeDeck({
|
||||||
|
id: 'd', columns: [
|
||||||
|
{ id: 'a', tabId: 'ta', profile: 'pgone', source: { kind: 'home' } },
|
||||||
|
{ id: 'a', tabId: 'tb', source: { kind: 'home' } },
|
||||||
|
{ id: 'b', tabId: 'ta', source: { kind: 'home' } },
|
||||||
|
{ id: 'c', tabId: 'tc', source: { kind: 'rocket' } },
|
||||||
|
{ id: 'd', tabId: 'td', source: { kind: 'search', value: 'from:me' }, title: 'Mine' },
|
||||||
|
],
|
||||||
|
}, { kinds: ['home', 'search'], profiles: ['default', 'p1'], fallbackProfile: 'default' })!;
|
||||||
|
assert.deepEqual(deck.columns.map(c => c.id), ['a', 'd']);
|
||||||
|
assert.equal(deck.columns[0]!.profile, 'default');
|
||||||
|
assert.deepEqual(deck.columns[1]!.source, { kind: 'search', value: 'from:me' });
|
||||||
|
assert.equal(deck.columns[1]!.title, 'Mine');
|
||||||
|
const decks = normalizeDecks([deck, { ...deck, id: 'other' }, { ...deck }]);
|
||||||
|
assert.deepEqual(decks.map(d => d.id), ['d', 'other']);
|
||||||
|
assert.equal(decks[1]!.columns.length, 0, 'a tab webview belongs to one deck only');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('deck: paging fills whole columns per page and respects maxVisible', () => {
|
||||||
|
const columns = ['a', 'b', 'c', 'd', 'e'].map(id => col(id));
|
||||||
|
assert.deepEqual(paginate(1500, columns), [['a', 'b', 'c', 'd'], ['b', 'c', 'd', 'e']], 'the last page is filled from the end');
|
||||||
|
assert.deepEqual(paginate(1500, columns, { maxVisible: 2 }), [['a', 'b'], ['c', 'd'], ['d', 'e']]);
|
||||||
|
assert.deepEqual(paginate(1500, columns.slice(0, 4)), [['a', 'b', 'c', 'd']]);
|
||||||
|
assert.deepEqual(paginate(200, columns.slice(0, 2)), [['a'], ['b']], 'a column wider than the viewport still gets a page');
|
||||||
|
assert.deepEqual(paginate(1000, []), []);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('deck: layout stretches a page to the viewport edge and parks the rest', () => {
|
||||||
|
const columns = ['a', 'b', 'c', 'd', 'e'].map(id => col(id));
|
||||||
|
const layout = layoutColumns(1500, columns, 0);
|
||||||
|
assert.equal(layout.pages, 2);
|
||||||
|
assert.deepEqual(layout.parked, ['e']);
|
||||||
|
assert.equal(layout.visible.length, 4);
|
||||||
|
const last = layout.visible.at(-1)!;
|
||||||
|
assert.equal(last.x + last.width, 1500, 'the row ends at the edge');
|
||||||
|
for (let i = 1; i < layout.visible.length; i++) {
|
||||||
|
const prev = layout.visible[i - 1]!;
|
||||||
|
assert.equal(layout.visible[i]!.x, prev.x + prev.width + COLUMN_GAP);
|
||||||
|
assert.ok(Math.abs(layout.visible[i]!.width - prev.width) <= 3, 'even stretch');
|
||||||
|
}
|
||||||
|
const second = layoutColumns(1500, columns, 7);
|
||||||
|
assert.equal(second.page, 1, 'page clamped');
|
||||||
|
assert.deepEqual(second.visible.map(c => c.id), ['b', 'c', 'd', 'e']);
|
||||||
|
assert.deepEqual(second.parked, ['a']);
|
||||||
|
const squeezed = layoutColumns(300, [col('w', 480)], 0);
|
||||||
|
assert.deepEqual(squeezed.visible, [{ id: 'w', x: 0, width: 300 }]);
|
||||||
|
const lone = layoutColumns(1600, [col('x')], 0);
|
||||||
|
assert.deepEqual(lone.visible, [{ id: 'x', x: 0, width: 720 }], 'a lone column stretches at most 2x');
|
||||||
|
assert.deepEqual(layoutColumns(1000, [], 3), { page: 0, pages: 0, visible: [], parked: [] });
|
||||||
|
});
|
||||||
|
|
||||||
|
test('deck: focus moves are clamped, pageOf finds a column', () => {
|
||||||
|
const columns = ['a', 'b', 'c'].map(id => col(id));
|
||||||
|
assert.equal(moveFocus(columns, 'a', -1), 'a');
|
||||||
|
assert.equal(moveFocus(columns, 'a', 1), 'b');
|
||||||
|
assert.equal(moveFocus(columns, 'c', 5), 'c');
|
||||||
|
assert.equal(moveFocus(columns, null, 1), 'a');
|
||||||
|
assert.equal(moveFocus(columns, 'gone', -1), 'c');
|
||||||
|
assert.equal(moveFocus([], 'a', 1), null);
|
||||||
|
assert.equal(pageOf(740, columns, 'c'), 1);
|
||||||
|
assert.equal(pageOf(740, columns, 'b', {}, 1), 1, 'stays on the current page when it shows the column');
|
||||||
|
assert.equal(pageOf(740, columns, 'a', {}, 1), 0);
|
||||||
|
assert.equal(pageOf(740, columns, 'nope'), 0);
|
||||||
|
assert.deepEqual(moveColumn(columns, 'c', -5).map(c => c.id), ['c', 'a', 'b']);
|
||||||
|
assert.deepEqual(moveColumn(columns, 'a', 1).map(c => c.id), ['b', 'a', 'c']);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('deck: column URLs come from the adapter and must be plain https', () => {
|
||||||
|
const urlFor = (source: ColumnSource) => source.kind === 'home' ? 'https://site.test/home'
|
||||||
|
: source.kind === 'bad' ? 'javascript:alert(1)' : source.kind === 'cred' ? 'https://u:p@site.test/' : null;
|
||||||
|
assert.equal(columnUrl({ kind: 'home' }, urlFor), 'https://site.test/home');
|
||||||
|
for (const kind of ['bad', 'cred', 'nope']) assert.equal(columnUrl({ kind }, urlFor), null, kind);
|
||||||
|
assert.equal(columnUrl({ kind: 'x' }, () => { throw new Error('boom'); }), null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('deck: unread total sums columns and caps at 999', () => {
|
||||||
|
const columns = [{ tabId: 'a' }, { tabId: 'b' }, { tabId: 'c' }];
|
||||||
|
assert.equal(unreadTotal(new Map([['a', 3], ['b', 4]]), columns), 7);
|
||||||
|
assert.equal(unreadTotal({ a: 900, b: 900, c: -5 }, columns), 999);
|
||||||
|
assert.equal(unreadTotal({ other: 5 }, columns), 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('panes: deck columns never take part in the rail rules', () => {
|
||||||
|
const onSite = (url: string) => url.startsWith('https://site.test/');
|
||||||
|
const box = (id: string, x: number, role?: 'pane' | 'column'): PaneBox => ({ id, url: 'https://site.test/feed', profile: 'default', x, y: 0, visible: true, ...(role ? { role } : {}) });
|
||||||
|
// A column left of a pane does not make that pane redundant, and is never redundant itself.
|
||||||
|
assert.deepEqual([...redundantNavPanes([box('col', 0, 'column'), box('pane', 400)], onSite)], []);
|
||||||
|
assert.deepEqual([...redundantNavPanes([box('col1', 0, 'column'), box('col2', 400, 'column')], onSite)], []);
|
||||||
|
assert.deepEqual([...redundantNavPanes([box('p1', 0, 'pane'), box('col', 400, 'column'), box('p2', 800)], onSite)], ['p2']);
|
||||||
|
const memory = new Map<string, boolean>();
|
||||||
|
const items = withNavRedundant([box('col', 0, 'column'), box('col2', 400, 'column')], onSite, memory);
|
||||||
|
assert.deepEqual(items.map(item => item.navRedundant), [false, false]);
|
||||||
|
});
|
||||||
|
|
@ -41,6 +41,7 @@ pieces. The source comments document each module's contract.
|
||||||
**Runtime**
|
**Runtime**
|
||||||
|
|
||||||
- `accountReport`: reports the signed-in account seen in the page's own UI.
|
- `accountReport`: reports the signed-in account seen in the page's own UI.
|
||||||
|
- `column`: a site tab as a narrow deck column: hides the site's chrome, lets its content fill the width, per-column filters (keywords, `/regex/`, replies, reposts, media only) and an unread count from what the site rendered. Makes no requests.
|
||||||
- `domHub`: one `MutationObserver` and one animation frame shared by every DOM feature.
|
- `domHub`: one `MutationObserver` and one animation frame shared by every DOM feature.
|
||||||
- `linkRouting`: routes clicks on the app's own links per the "links to app pages" setting.
|
- `linkRouting`: routes clicks on the app's own links per the "links to app pages" setting.
|
||||||
- `netHub`: one shared fetch/XHR hook for URL rewrites, gates and passive JSON taps.
|
- `netHub`: one shared fetch/XHR hook for URL rewrites, gates and passive JSON taps.
|
||||||
|
|
@ -55,6 +56,7 @@ pieces. The source comments document each module's contract.
|
||||||
|
|
||||||
- `addressModel`: `parseAddress(url, site)` for the address bar's breadcrumb chips.
|
- `addressModel`: `parseAddress(url, site)` for the address bar's breadcrumb chips.
|
||||||
- `chrome`: layout constants for the custom titlebar and toolbar.
|
- `chrome`: layout constants for the custom titlebar and toolbar.
|
||||||
|
- `deckModel`: decks of site columns (TweetDeck-style): bounded model, paging layout (whole columns per page, parked off-page columns), focus moves, unread totals.
|
||||||
- `linkDrop`: a dragged link dropped into the dock opens as a tab or split pane.
|
- `linkDrop`: a dragged link dropped into the dock opens as a tab or split pane.
|
||||||
- `palette`: command palette fuzzy scoring, ranking and selection movement.
|
- `palette`: command palette fuzzy scoring, ranking and selection movement.
|
||||||
- `paneModel`: pane geometry: where a "beside" link opens, which panes keep the rail.
|
- `paneModel`: pane geometry: where a "beside" link opens, which panes keep the rail.
|
||||||
|
|
|
||||||
|
|
@ -3,7 +3,7 @@
|
||||||
"version": "0.2.0",
|
"version": "0.2.0",
|
||||||
"license": "GPL-3.0-or-later",
|
"license": "GPL-3.0-or-later",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"description": "wayBetter: the framework for apps that run the apps you already use in a light native (Tauri) window and extend them in place. Page runtime (DOM/request hubs, plugins, plugin UI kit with themed dialogs and toasts, theme API and theme JSON Schema, theme color model, link routing, account reporting) and shell models (address bar, panes, profiles, palette, updates). No dependencies.",
|
"description": "wayBetter: the framework for apps that run the apps you already use in a light native (Tauri) window and extend them in place. Page runtime (DOM/request hubs, plugins, plugin UI kit with themed dialogs and toasts, theme API and theme JSON Schema, theme color model, link routing, account reporting, deck columns) and shell models (address bar, panes, decks, profiles, palette, updates). No dependencies.",
|
||||||
"keywords": [
|
"keywords": [
|
||||||
"waybetter",
|
"waybetter",
|
||||||
"tauri",
|
"tauri",
|
||||||
|
|
@ -28,6 +28,10 @@
|
||||||
"types": "./dist/runtime/accountReport.d.ts",
|
"types": "./dist/runtime/accountReport.d.ts",
|
||||||
"import": "./dist/runtime/accountReport.js"
|
"import": "./dist/runtime/accountReport.js"
|
||||||
},
|
},
|
||||||
|
"./runtime/column": {
|
||||||
|
"types": "./dist/runtime/column.d.ts",
|
||||||
|
"import": "./dist/runtime/column.js"
|
||||||
|
},
|
||||||
"./runtime/domHub": {
|
"./runtime/domHub": {
|
||||||
"types": "./dist/runtime/domHub.d.ts",
|
"types": "./dist/runtime/domHub.d.ts",
|
||||||
"import": "./dist/runtime/domHub.js"
|
"import": "./dist/runtime/domHub.js"
|
||||||
|
|
@ -76,6 +80,10 @@
|
||||||
"types": "./dist/shell/chrome.d.ts",
|
"types": "./dist/shell/chrome.d.ts",
|
||||||
"import": "./dist/shell/chrome.js"
|
"import": "./dist/shell/chrome.js"
|
||||||
},
|
},
|
||||||
|
"./shell/deckModel": {
|
||||||
|
"types": "./dist/shell/deckModel.d.ts",
|
||||||
|
"import": "./dist/shell/deckModel.js"
|
||||||
|
},
|
||||||
"./shell/linkDrop": {
|
"./shell/linkDrop": {
|
||||||
"types": "./dist/shell/linkDrop.d.ts",
|
"types": "./dist/shell/linkDrop.d.ts",
|
||||||
"import": "./dist/shell/linkDrop.js"
|
"import": "./dist/shell/linkDrop.js"
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue