Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Starter apps: four sample apps in every apps list, removable for good (#7759)
Milind Soni5945ed21f9b9
diff --git a/scripts/bundle-server.mjs b/scripts/bundle-server.mjsindex bed78502d3..002e75d3f0 100644--- a/scripts/bundle-server.mjs+++ b/scripts/bundle-server.mjs@@ -2,7 +2,7 @@// packaged app ships no node_modules. Entry points keep their exact relative// paths under dist-server, where the server locates each proxy by path.import { build } from "esbuild";-import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { copyFileSync, cpSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { fileURLToPath } from "node:url";import { dirname, join } from "node:path";import { serverLocalePlugin } from "./server-locale-plugin.mjs";@@ -159,6 +159,9 @@ const catalogSnapshot = join(root, "dist-server", "model-catalog", "models-dev.smkdirSync(dirname(catalogSnapshot), { recursive: true });copyFileSync(join(server, "model-catalog", "models-dev.snapshot.json"), catalogSnapshot);+// The starter apps' pages (server/local-apps/starters.ts), read from local-apps/starters/ beside the bundle.+cpSync(join(server, "local-apps", "starters"), join(root, "dist-server", "local-apps", "starters"), { recursive: true });+// Pi loads this through its own jiti and supplies TypeBox. Inline our local// policy module so the extension also works without the source checkout;// keep the Pi-owned dependency external and retain the .ts loading contract.diff --git a/scripts/smoke-packaged-server.mjs b/scripts/smoke-packaged-server.mjsindex ebef0ea3d0..a0bba978d3 100644--- a/scripts/smoke-packaged-server.mjs+++ b/scripts/smoke-packaged-server.mjs@@ -10,6 +10,7 @@ import { dirname, isAbsolute, join, resolve } from "node:path";import { fileURLToPath } from "node:url";import { parseArgs, promisify } from "node:util";import { browserBundlePaths, browserBundleSpec } from "../server/browser-bundle-release.ts";+import { STARTER_APPS } from "../server/local-apps/starters.ts";const root = join(dirname(fileURLToPath(import.meta.url)), "..");const { values } = parseArgs({ options: { "browser-bundle": { type: "string" } } });@@ -139,6 +140,17 @@ if (listening) {} catch (error) { searchReport = { error: String(error) }; }}+// The starter apps' pages are files beside the bundle: a fresh data folder lists them, each page served.+let startersReport = null;+if (listening) {+ try {+ const { apps } = await (await fetch(`http://127.0.0.1:${port}/api/local-apps`, { signal: AbortSignal.timeout(5_000) })).json();+ const samples = apps.filter((app) => app.sample);+ const pages = await Promise.all(samples.map(async (app) => (await fetch(`http://127.0.0.1:${port}/api/local-apps/${app.id}/app`, { signal: AbortSignal.timeout(5_000) })).ok));+ startersReport = { ids: samples.map((app) => app.id), served: pages.filter(Boolean).length };+ } catch (error) { startersReport = { error: String(error) }; }+}+let browserReport = null;if (browserBundle && listening) {try {@@ -466,6 +478,11 @@ if (searchReport?.status !== 200 || !Array.isArray(searchReport.body?.hits)) {process.exit(1);}+if (!startersReport || startersReport.error || startersReport.ids.join() !== STARTER_APPS.map((app) => app.id).join() || startersReport.served !== STARTER_APPS.length) {+ console.error("the packaged server did not list and serve its starter apps:", startersReport);+ process.exit(1);+}+if (layerShipped && (!editionReport || editionReport.error || String(editionReport.notice ?? "").includes("no enterprise layer exists"))) {console.error("the packaged server ships an enterprise layer but did not find it:");console.error(JSON.stringify(editionReport, null, 2));@@ -522,6 +539,7 @@ console.log(`packaged server started with no node_modules in reach (port ${port}console.log(`all ${count} spawned proxy paths resolve inside the packaged server dir ✓`);console.log("packaged MCP stdio server reached the API and flushed its final frames ✓");console.log("packaged openmausbot doctor and bots answered from the bundle ✓");+console.log(`packaged server listed and served its ${startersReport.served} starter apps on a fresh data folder ✓`);console.log("packaged backup worker exported an encrypted archive ✓");console.log("packaged loopback trust gate: health serves, a public mutation is refused at service trust ✓");if (launcherReport) console.log("packaged container launcher ran the server as its child and stopped it cleanly ✓");diff --git a/server/index.ts b/server/index.tsindex 71a7f890d7..ab9743f755 100644--- a/server/index.ts+++ b/server/index.ts@@ -468,7 +468,7 @@ import { createAgentCard } from "./chat-widgets.ts";import { botApproval, createChatAppRoutes, createChatApps, createChatAppsMcp, createConnectorGate, createConnectorGateApps } from "./routes/chat-apps.ts";import { buildBotOverview, type BotOverview, connectedAppsFacts } from "./bot-overview.ts";import { ProfileRequestService } from "./profile-requests.ts"; import { browserProfileLabel } from "./bot-browser-profile.ts";-import { ModelRequestService } from "./model-requests.ts"; import { createLocalAppsRoutes } from "./routes/local-apps.ts"; import { createLocalApps } from "./local-apps/service.ts"; import { withLocalAppDocs } from "./local-apps/store.ts";+import { ModelRequestService } from "./model-requests.ts"; import { createLocalAppsRoutes } from "./routes/local-apps.ts"; import { createLocalApps } from "./local-apps/service.ts"; import { withLocalAppDocs } from "./local-apps/store.ts"; import { bundledStarterApps } from "./local-apps/starters.ts";import { TeamSetupError, TeamSetupRequestService } from "./team-setup-requests.ts";import { startsWithoutCloudComputer, teamSetupDecisionText as decisionText, type TeamSetupRequest } from "../shared/team-setup.ts";import { profileRevision, profileSnapshot } from "./profile-revision.ts";@@ -11934,7 +11934,7 @@ ROUTES.push(createBotMessageRoutes({{ emoji, name: person.name ?? person.email, at: Date.now() }),}));const liveRoots = (threadId: string, botId: string | undefined) => { const bot = botId ? store.bot(botId) : store.botByThread(threadId); return bot ? messageFileRootsForThread(bot.id, threadId).filter((root) => root !== ATTACHMENTS_DIR) : null; }; const chatApps = createChatApps({ store, dataDir: DATA_DIR, references: withLocalAppDocs(DATA_DIR), liveRows: liveAppRows, liveRoots, paused: () => workspaceMaintenance.active || moveFreeze.frozen() });-const chatAppsMcp = createChatAppsMcp({ store, apps: chatApps, dataDir: DATA_DIR, keys: mcpKeys, storedServers: () => cfg.mcpServers ?? {}, mountedServers: (bot) => teamConnections.engineMcp(bot), personMcp: teamConnections.personMcp, probeAs: (server) => mcpServersHost.probeAs(server), oauth: mcpOAuth }); const localApps = createLocalApps({ chat: store, docs: chatApps.docs, dataDir: DATA_DIR, sweep: () => void chatApps.sweep() }); ROUTES.push(createLocalAppsRoutes({ apps: localApps, store, visibleFor: (auth) => visibleTo(viewerFor(auth)), threadRefusal: cloudThreadRefusal, live: (auth) => auth.kind !== "session" || sessions.isLive(auth.session.id) }));+const chatAppsMcp = createChatAppsMcp({ store, apps: chatApps, dataDir: DATA_DIR, keys: mcpKeys, storedServers: () => cfg.mcpServers ?? {}, mountedServers: (bot) => teamConnections.engineMcp(bot), personMcp: teamConnections.personMcp, probeAs: (server) => mcpServersHost.probeAs(server), oauth: mcpOAuth }); const localApps = createLocalApps({ chat: store, docs: chatApps.docs, dataDir: DATA_DIR, sweep: () => void chatApps.sweep(), starters: bundledStarterApps() }); ROUTES.push(createLocalAppsRoutes({ apps: localApps, store, visibleFor: (auth) => visibleTo(viewerFor(auth)), threadRefusal: cloudThreadRefusal, live: (auth) => auth.kind !== "session" || sessions.isLive(auth.session.id) }));const pageConnectors = { gate: createConnectorGate({ bot: (id) => store.bot(id) ?? undefined, apps: createConnectorGateApps({ cfg: () => cfg, composio, personApps: () => teamConnections.personApps(), appsAccess: (person) => teamConnections.people.appsAccess(person), policyRefusal: (slugs, serviceSlugs) => managedPolicy.appsCallRefusal(slugs.map((slug) => ({ slug })), serviceSlugs) }), servers: { open: chatAppsMcp.openServer }, decide: (row) => appendDecision(DATA_DIR, row) }), person: (auth: RequestAuth) => (CLOUD_TEAM && auth.kind === "session" ? personKey(auth.session) : null), mayAct: (auth: RequestAuth, botId: string) => ["chat", "edit"].includes(levelOf(auth, botId)), fullAccess: (botId: string, threadId: string) => botApproval(store, botId, threadId) === "full", confined: (threadId: string) => cloudGuestDriven(threadId) || proactive.fence.confines(threadId) }; ROUTES.push(createChatAppRoutes({ store, apps: chatApps, threadRefusal: cloudThreadRefusal, mcpRpc: chatAppsMcp.rpc, data: dataEngine, dataOff: (botId) => serverTurnedOff(store.bot(botId)?.toolsOff, "data"), threadVisible: (auth, threadId) => (auth.kind !== "session" || sessions.isLive(auth.session.id)) && visibleTo(viewerFor(auth)).thread(threadId), connectors: pageConnectors }));const roomReactionNotes = createRoomReactionNotes({ store }), { react } = createReactions({store, noted: roomReactionNotes.noted, inboxAnswer: (input) => teamMessages.reactedIn(input.auth, input.threadId, input.target.id, input.answer, { sendId: input.sendId, sender: messageSender(input.auth) }), reply: (input) => personReplies.deliver({ ...input, about: "message" }),diff --git a/server/local-apps.e2e.test.ts b/server/local-apps.e2e.test.tsindex b7dfdc96cb..bc35002e8e 100644--- a/server/local-apps.e2e.test.ts+++ b/server/local-apps.e2e.test.ts@@ -39,7 +39,8 @@ it("saves a shown page as an app that follows its newest version and outlives itconst saved = await api("/api/local-apps", { method: "POST", body: JSON.stringify({ botId: bot.id, threadId, messageId: page.id }) });expect(saved.status, JSON.stringify(saved.body)).toBe(201);const id = saved.body.app.id as string;- expect((await api("/api/local-apps")).body.apps.map((app: any) => app.id)).toEqual([id]);+ // A fresh server already lists the starter apps, after the one just saved.+ expect((await api("/api/local-apps")).body.apps.map((app: any) => app.sample ? "sample" : app.id)).toEqual([id, "sample", "sample", "sample", "sample"]);plan([{ tool: "update_html", arguments: { app_id: page.id, html: "<h1>Sales v2</h1>" } }]);await cli("send", "--bot", bot.id, "--task", threadId, "--text", "Bigger heading please.");diff --git a/server/local-apps/service.ts b/server/local-apps/service.tsindex a3640f5267..a1bfbb6f06 100644--- a/server/local-apps/service.ts+++ b/server/local-apps/service.ts@@ -8,6 +8,7 @@ import { appRow } from "../chat-apps.ts";import { createPageFiles, PAGE_FILES_PREFIX, type PageFilesViewer } from "../page-files.ts";import type { Message, StoreChange } from "../store.ts";import type { MausColor } from "../../shared/wire.ts";+import { rememberRemovedStarter, seedStarterApps, type StarterSource } from "./starters.ts";import { LocalAppsStore, type LocalAppRecord, type LocalAppVersion } from "./store.ts";/** Where a saved folder page's files load from. They answer while the app still keeps that version, whatever became of@@ -76,9 +77,12 @@ export function createLocalApps(deps: {/** Asked soon after an app is removed, so the versions only it kept are cleared. */sweep?(): void;now?(): number;+ /** The sample apps added at start unless the person removed them. */+ starters?: StarterSource;}): LocalApps {const store = new LocalAppsStore(deps.dataDir);const now = deps.now ?? Date.now;+ if (deps.starters) seedStarterApps({ store, docs: deps.docs, dataDir: deps.dataDir, source: deps.starters, now: now() });const files = createPageFiles({ docs: deps.docs });let sweepTimer: ReturnType<typeof setTimeout> | null = null;@@ -122,7 +126,7 @@ export function createLocalApps(deps: {view: (record) => ({id: record.id, name: record.name, ...(record.icon ? { icon: record.icon } : {}), botId: record.botId, bot: botOf(record.botId), threadId: record.threadId, messageId: record.messageId,versions: record.versions.map(({ rev, at }) => ({ rev, at })), rev: shownRev(record), ...(record.pinnedRev !== undefined ? { pinnedRev: record.pinnedRev } : {}),- createdAt: record.createdAt, updatedAt: record.updatedAt, manifest: record.manifest, chat: chatHas(record.threadId),+ createdAt: record.createdAt, updatedAt: record.updatedAt, manifest: record.manifest, chat: chatHas(record.threadId), ...(record.sample ? { sample: true as const } : {}),}),save({ botId, threadId, messageId, owner }) {const row = pageRow(threadId, messageId);@@ -144,6 +148,7 @@ export function createLocalApps(deps: {return store.update(id, ({ pinnedRev: _was, ...rest }) => ({ ...rest, ...(rev === null ? {} : { pinnedRev: rev }) }), now());},remove(id) {+ if (store.get(id)?.sample) rememberRemovedStarter(deps.dataDir, id);if (!store.remove(id)) return false;if (deps.sweep && !sweepTimer) {sweepTimer = setTimeout(() => { sweepTimer = null; deps.sweep?.(); }, 2_000);diff --git a/server/local-apps/starters.test.ts b/server/local-apps/starters.test.tsnew file mode 100644index 0000000000..207444663c--- /dev/null+++ b/server/local-apps/starters.test.ts@@ -0,0 +1,109 @@+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import { LOCAL_APP_ID } from "../../shared/local-apps.ts";+import { AppDocs } from "../app-docs.ts";+import { createLocalApps } from "./service.ts";+import { bundledStarterApps, removedStartersFile, STARTER_APPS, type StarterApp, type StarterSource } from "./starters.ts";+import { localAppsFile, LocalAppsStore } from "./store.ts";++const dirs: string[] = [];+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });+const fresh = () => { const dir = mkdtempSync(join(tmpdir(), "omb-starters-")); dirs.push(dir); return dir; };++const chat = { messagesFor: () => [], botByThread: () => null, groupByThread: () => null, taskByThread: () => null };+const TWO: StarterApp[] = [+ { id: "la_starter_one_____", name: "One", file: "one.html" },+ { id: "la_starter_two_____", name: "Two", file: "two.html" },+];+const pages = (html: Record<string, string>): StarterSource => ({ apps: TWO, html: (app) => html[app.file] ?? null });+const open = (dataDir: string, starters?: StarterSource) => {+ const apps = createLocalApps({ chat, docs: new AppDocs(join(dataDir, "app-docs")), dataDir, ...(starters ? { starters } : {}), now: () => 1_000 });+ return apps;+};++describe("starter apps", () => {+ it("ship four pages with fixed ids, each found where the server looks", () => {+ expect(STARTER_APPS).toHaveLength(4);+ expect(new Set(STARTER_APPS.map((app) => app.id)).size).toBe(STARTER_APPS.length);+ const source = bundledStarterApps();+ for (const app of STARTER_APPS) {+ expect(app.id).toMatch(LOCAL_APP_ID);+ expect(source.html(app), app.file).toBeTruthy();+ }+ });++ it("make no outside request, keep nothing in the browser, and say they are sample data", () => {+ const source = bundledStarterApps();+ for (const app of STARTER_APPS) {+ const html = source.html(app)!;+ expect(html.match(/(?:https?:)?\/\/[a-z0-9.-]+\.[a-z]{2,}[^\s"'`)]*/gi)?.filter((url) => url !== "http://www.w3.org/2000/svg") ?? [], app.file).toEqual([]);+ expect(html, app.file).not.toMatch(/localStorage|sessionStorage|indexedDB|document\.cookie|window\.hero|window\.__|fonts\.googleapis|\bfetch\(|XMLHttpRequest|WebSocket|mausbot\./);+ expect(html, app.file).toMatch(/sample data/i);+ }+ });++ it("are added once after the person's own apps, from no bot and no chat", () => {+ const dir = fresh();+ const own = new LocalAppsStore(dir).add({ name: "Mine", botId: "b1", threadId: "t1", messageId: "m1", versions: [{ rev: 0, doc: "a".repeat(64), at: 0 }], manifest: { name: "Mine" } });+ const apps = open(dir, pages({ "one.html": "<h1>One</h1>", "two.html": "<h1>Two</h1>" }));+ expect(apps.list().map((app) => app.id)).toEqual([own.id, ...TWO.map((app) => app.id)]);+ const one = apps.view(apps.get(TWO[0]!.id)!);+ expect(one).toMatchObject({ name: "One", sample: true, bot: null, botId: "", threadId: "", chat: false, rev: 0, manifest: { name: "One" } });+ expect(one.manifest.uses).toBeUndefined();+ expect(apps.document(TWO[0]!.id)?.srcdoc).toContain("<h1>One</h1>");+ expect(apps.view(apps.get(own.id)!).sample).toBeUndefined();+ const written = readFileSync(localAppsFile(dir), "utf8");+ open(dir, pages({ "one.html": "<h1>One</h1>", "two.html": "<h1>Two</h1>" }));+ expect(readFileSync(localAppsFile(dir), "utf8")).toBe(written);+ });++ it("stay removed: the removal is remembered across starts and releases", () => {+ const dir = fresh();+ const source = pages({ "one.html": "<h1>One</h1>", "two.html": "<h1>Two</h1>" });+ expect(open(dir, source).remove(TWO[0]!.id)).toBe(true);+ expect(JSON.parse(readFileSync(removedStartersFile(dir), "utf8"))).toEqual({ version: 1, ids: [TWO[0]!.id] });+ const again = open(dir, pages({ "one.html": "<h1>One, newer</h1>", "two.html": "<h1>Two</h1>" }));+ expect(again.list().map((app) => app.id)).toEqual([TWO[1]!.id]);+ expect(again.remove(TWO[1]!.id)).toBe(true);+ expect(open(dir, source).list()).toEqual([]);+ expect(JSON.parse(readFileSync(removedStartersFile(dir), "utf8")).ids).toEqual(TWO.map((app) => app.id));+ });++ it("take a changed page as a new version, keeping the person's name and kept version", () => {+ const dir = fresh();+ const first = open(dir, pages({ "one.html": "<h1>One</h1>" }));+ first.rename(TWO[0]!.id, "My one");+ first.pin(TWO[0]!.id, 0);+ const next = open(dir, pages({ "one.html": "<h1>One, newer</h1>" }));+ const one = next.view(next.get(TWO[0]!.id)!);+ expect(one).toMatchObject({ name: "My one", versions: [{ rev: 0 }, { rev: 1 }], pinnedRev: 0, rev: 0 });+ expect(next.document(TWO[0]!.id, 1)?.srcdoc).toContain("One, newer");+ expect(open(dir, pages({ "one.html": "<h1>One, newer</h1>" })).get(TWO[0]!.id)?.versions).toHaveLength(2);+ });++ it("add nothing when the saved apps or the removals can't be read", () => {+ const unreadable = fresh();+ writeFileSync(localAppsFile(unreadable), JSON.stringify({ version: 2, apps: [{ id: "la_from_a_newer_bu" }] }));+ const before = readFileSync(localAppsFile(unreadable), "utf8");+ expect(open(unreadable, pages({ "one.html": "<h1>One</h1>" })).list()).toEqual([]);+ expect(readFileSync(localAppsFile(unreadable), "utf8")).toBe(before);++ const removals = fresh();+ open(removals, pages({ "one.html": "<h1>One</h1>" }));+ writeFileSync(removedStartersFile(removals), "{not json");+ const broken = open(removals, pages({ "one.html": "<h1>One</h1>", "two.html": "<h1>Two</h1>" }));+ expect(broken.list().map((app) => app.id)).toEqual([TWO[0]!.id]);+ expect(() => broken.remove(TWO[0]!.id)).toThrow();+ expect(readFileSync(removedStartersFile(removals), "utf8")).toBe("{not json");+ expect(broken.get(TWO[0]!.id)).not.toBeNull();+ });++ it("leave out a page that isn't there, and add nothing without a source", () => {+ const dir = fresh();+ expect(open(dir, pages({ "two.html": "<h1>Two</h1>" })).list().map((app) => app.id)).toEqual([TWO[1]!.id]);+ expect(open(fresh()).list()).toEqual([]);+ });+});diff --git a/server/local-apps/starters.ts b/server/local-apps/starters.tsnew file mode 100644index 0000000000..5f66014f88--- /dev/null+++ b/server/local-apps/starters.ts@@ -0,0 +1,100 @@+import { existsSync, mkdirSync, readFileSync } from "node:fs";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";++import { LOCAL_APP_ID } from "../../shared/local-apps.ts";+import type { AppDocs } from "../app-docs.ts";+import { writeFileAtomic } from "../atomic.ts";+import type { LocalAppRecord, LocalAppsStore } from "./store.ts";++/** A sample app every computer and Cloud starts with. Its id never changes: removing it is remembered by that id. */+export interface StarterApp {+ id: string;+ name: string;+ /** The page, a file in the starters folder. */+ file: string;+}++export const STARTER_APPS: readonly StarterApp[] = [+ { id: "la_starter_ledger__", name: "Ledger · household & studio accounts", file: "ledger.html" },+ { id: "la_starter_cohorts_", name: "Cohorts · Q3 activation review", file: "cohorts.html" },+ { id: "la_starter_fleet___", name: "Corridor · Fleet control", file: "fleet.html" },+ { id: "la_starter_bigtable", name: "Rowfall · orders", file: "bigtable.html" },+];++export interface StarterSource {+ apps: readonly StarterApp[];+ html(app: StarterApp): string | null;+}++/** Beside this module in a checkout; under local-apps/starters/ beside the bundled server, where the server build copies+ * them. */+export function bundledStarterApps(apps: readonly StarterApp[] = STARTER_APPS): StarterSource {+ const here = dirname(fileURLToPath(import.meta.url));+ const dir = [join(here, "starters"), join(here, "local-apps", "starters")].find((candidate) => existsSync(candidate));+ return {+ apps,+ html: (app) => {+ if (!dir) return null;+ try { return readFileSync(join(dir, app.file), "utf8"); } catch { return null; }+ },+ };+}++export const removedStartersFile = (dataDir: string) => join(dataDir, "local-apps-removed.json");++/** The starter apps the person removed; null when the file is there but can't be read, so nothing is added back. */+export function readRemovedStarters(dataDir: string): Set<string> | null {+ let text: string;+ try {+ text = readFileSync(removedStartersFile(dataDir), "utf8");+ } catch (error) {+ return (error as NodeJS.ErrnoException).code === "ENOENT" ? new Set() : null;+ }+ try {+ const parsed = JSON.parse(text) as { version?: unknown; ids?: unknown };+ if (parsed.version !== 1 || !Array.isArray(parsed.ids)) return null;+ return new Set(parsed.ids.filter((id): id is string => typeof id === "string" && LOCAL_APP_ID.test(id)));+ } catch {+ return null;+ }+}++/** Throws when it can't be remembered, the removals file unreadable included (writing over it would forget earlier+ * removals): a removal that isn't remembered would come back at the next start. */+export function rememberRemovedStarter(dataDir: string, id: string): void {+ const removed = readRemovedStarters(dataDir);+ if (!removed) throw new Error("The removed starter apps can't be read, so this one can't be removed for good.");+ if (removed.has(id)) return;+ mkdirSync(dataDir, { recursive: true });+ writeFileAtomic(removedStartersFile(dataDir), JSON.stringify({ version: 1, ids: [...removed, id] }), { mode: 0o600 });+}++/**+ * Adds each starter app the store lacks and the person never removed, after their own apps; a starter still kept whose+ * page changed in this release gets the new page as its newest version. Nothing at all when either file can't be read:+ * the person's saved apps are never written over, and a removed starter never comes back.+ */+export function seedStarterApps(args: { store: LocalAppsStore; docs: AppDocs; dataDir: string; source: StarterSource; now: number }): void {+ const { store, docs, source, now } = args;+ if (!store.readable) return;+ const removed = readRemovedStarters(args.dataDir);+ if (!removed) return;+ const added: LocalAppRecord[] = [];+ for (const app of source.apps) {+ if (removed.has(app.id) || !LOCAL_APP_ID.test(app.id)) continue;+ const html = source.html(app);+ if (html === null) continue;+ const put = docs.put({ source: "html", html });+ if (!put.ok) continue;+ const kept = store.get(app.id);+ if (!kept) {+ added.push({ id: app.id, name: app.name, botId: "", threadId: "", messageId: app.id, sample: true, versions: [{ rev: 0, doc: put.doc, at: now }],+ createdAt: now, updatedAt: now, manifest: { name: app.name } });+ continue;+ }+ const newest = kept.versions.at(-1)!;+ if (newest.doc !== put.doc) store.update(app.id, (record) => ({ ...record, versions: [...record.versions, { rev: newest.rev + 1, doc: put.doc, at: now }] }), now);+ }+ store.append(added);+}diff --git a/server/local-apps/starters/bigtable.html b/server/local-apps/starters/bigtable.htmlnew file mode 100644index 0000000000..b0cd476778--- /dev/null+++ b/server/local-apps/starters/bigtable.html@@ -0,0 +1,975 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width,initial-scale=1">+<title>Rowfall · orders</title>+<style>+:root{+ --ui:system-ui,-apple-system,"Segoe UI",Roboto,sans-serif; --mono:ui-monospace,"SF Mono",Menlo,Consolas,monospace;+ --bg:#0e0f11; --panel:#121316; --raise:#17181c; --line:#222429; --line2:#2c2f35;+ --text:#e3e5e9; --dim:#8b9099; --faint:#5b6068; --ghost:#3a3d44;+ --lime:#c6f432; --lime-d:rgba(198,244,50,.12);+}+*{box-sizing:border-box}+html,body{margin:0;height:100%;background:var(--bg);color:var(--text);overflow:hidden}+body{font-family:var(--ui);font-size:13px;-webkit-font-smoothing:antialiased;font-variant-numeric:tabular-nums}+.mono{font-family:var(--mono)}+#app{display:grid;height:100vh;grid-template-columns:1fr auto;grid-template-rows:52px 64px 1fr 34px}+.top{grid-column:1;grid-row:1;display:flex;align-items:center;gap:18px;padding:0 0 0 22px;border-bottom:1px solid var(--line)}+.brand{display:flex;align-items:center;gap:10px}+.wm{font-weight:600;font-size:15px;letter-spacing:-.01em}+.crumb{color:var(--dim);font-size:13px;display:flex;gap:7px;align-items:center}+.crumb b{color:var(--text);font-weight:500}+.crumb i{color:var(--ghost);font-style:normal}+.tag{font-family:var(--mono);font-size:11px;color:var(--dim);border:1px solid var(--line2);border-radius:4px;padding:3px 7px;letter-spacing:.02em}+.tabs{display:flex;gap:2px;margin-left:16px}+.tabs span{font-size:12.5px;color:var(--faint);padding:6px 10px;border-radius:5px}+.tabs span.on{color:var(--text);background:var(--raise)}+.sample{margin-left:auto;margin-right:22px;font-size:12px;color:var(--faint);display:flex;align-items:center;gap:8px}+.sample:before{content:"";width:6px;height:6px;border-radius:50%;background:var(--ghost)}+.qbar{grid-column:1;grid-row:2;display:flex;align-items:center;gap:10px;padding:0 22px;border-bottom:1px solid var(--line);min-width:0}+.tb{font:500 12.5px var(--ui);color:var(--dim);background:transparent;border:1px solid var(--line2);border-radius:6px;height:30px;padding:0 11px;display:flex;align-items:center;gap:7px;cursor:pointer}+.tb:hover{color:var(--text);border-color:#3a3e45}+.tb svg{width:13px;height:13px;stroke:currentColor;fill:none;stroke-width:1.5}+.q{font-family:var(--mono);font-size:13px;color:#b9bdc5;display:flex;align-items:center;gap:8px;margin-left:8px;white-space:nowrap;min-width:0;overflow:hidden;height:36px;padding:0 12px;border-radius:6px;background:#121316;border:1px solid var(--line);flex:1}+.q .kw{color:#6f7580}+.q .id{color:#e3e5e9}+.q .str{color:var(--lime)}+.chip{display:inline-flex;align-items:center;gap:7px;height:24px;padding:0 6px 0 9px;border-radius:5px;background:var(--lime-d);border:1px solid rgba(198,244,50,.35);color:#e9f8b8;font-size:12px;+ transform-origin:left center;animation:chipIn .45s cubic-bezier(.2,.9,.25,1.15) both}+.chip .x{width:14px;height:14px;border-radius:3px;display:grid;place-items:center;color:#9fb35c;cursor:pointer;font-size:12px;line-height:1}+@keyframes chipIn{from{opacity:0;transform:translateY(6px) scale(.85)}to{opacity:1;transform:none}}+.counter{grid-column:2;grid-row:1/3;border-left:1px solid var(--line);border-bottom:1px solid var(--line);width:470px;padding:16px 24px 0 26px;display:flex;flex-direction:column;justify-content:center;gap:4px;background:linear-gradient(180deg,#121316,#0f1012)}+.c-top{display:flex;justify-content:space-between;align-items:baseline;font-family:var(--mono);font-size:11px;letter-spacing:.12em;color:var(--faint);text-transform:uppercase}+.c-top .speed{letter-spacing:.02em;text-transform:none;color:var(--dim)}+.c-main{display:flex;align-items:baseline;gap:12px;justify-content:flex-start}+.c-main .num{font-family:var(--mono);font-weight:500;font-size:50px;letter-spacing:-.035em;color:var(--lime);line-height:1;min-width:262px;text-align:right}+.c-main .of{font-family:var(--mono);font-size:15px;color:var(--dim);white-space:nowrap}+main{grid-column:1/3;grid-row:3;position:relative;display:grid;grid-template-columns:1fr 132px;min-height:0}+#grid{display:block;width:100%;height:100%;cursor:default}+#rail{display:block;width:100%;height:100%;border-left:1px solid var(--line);cursor:pointer;touch-action:none}+.wrap{position:relative;min-width:0;min-height:0}+footer{grid-column:1/3;grid-row:4;border-top:1px solid var(--line);display:flex;align-items:center;gap:22px;padding:0 22px;font-family:var(--mono);font-size:11.5px;color:var(--faint);white-space:nowrap;overflow:hidden}+footer b{color:var(--dim);font-weight:400}+footer .scan{color:var(--dim)}+footer .scan em{font-style:normal;color:var(--text)}+footer .r{margin-left:auto;display:flex;gap:18px}+footer .sep{color:var(--ghost)}+@media (max-width:1600px){+ .counter{width:380px;padding:14px 20px 0 20px}+ .c-main .num{font-size:40px;min-width:210px}+ .c-main .of{font-size:13px}+ main{grid-template-columns:1fr 112px}+ .tabs{display:none}+}+</style>+</head>+<body>+<div id="app">+ <header class="top">+ <div class="brand">+ <svg width="22" height="22" viewBox="0 0 22 22" aria-hidden="true"><rect x="1" y="2" width="20" height="3" rx="1" fill="#c6f432"/><rect x="1" y="7.5" width="20" height="2" rx="1" fill="#e3e5e9" opacity=".85"/><rect x="1" y="12" width="20" height="2" rx="1" fill="#e3e5e9" opacity=".5"/><rect x="1" y="16.5" width="20" height="2" rx="1" fill="#e3e5e9" opacity=".25"/></svg>+ <span class="wm">rowfall</span>+ </div>+ <div class="crumb"><span>marketplace</span><i>/</i><span>sales</span><i>/</i><b>orders</b></div>+ <span class="tag">12 cols · derived · 0 B stored</span>+ <div class="tabs"><span class="on">Rows</span><span>Schema</span><span>Profile</span></div>+ <div class="sample">Sample data · generated in this page</div>+ </header>+ <div class="qbar">+ <button class="tb" id="btnFilter" title="Filter status = delivered"><svg viewBox="0 0 16 16"><path d="M2 3h12l-4.6 5.4V13l-2.8 1.2V8.4z"/></svg>Filter</button>+ <button class="tb" id="btnGroup" title="Group by region, category"><svg viewBox="0 0 16 16"><rect x="2" y="2" width="5" height="5"/><rect x="9" y="2" width="5" height="5"/><rect x="2" y="9" width="5" height="5"/><rect x="9" y="9" width="5" height="5"/></svg>Group by</button>+ <div class="q" id="q"><span class="kw">SELECT</span><span class="id">*</span><span class="kw">FROM</span><span class="id">orders</span><span id="chips" style="display:flex;gap:8px;align-items:center"></span><span class="kw" id="ordkw">ORDER BY</span><span class="id" id="ordcol">order_id</span><span class="kw" id="orddir">ASC</span></div>+ </div>+ <div class="counter">+ <div class="c-top"><span id="clbl">row</span><span class="speed" id="cspeed">at rest</span></div>+ <div class="c-main"><span class="num" id="cnum">1</span><span class="of" id="cof">of 12,000,000</span></div>+ </div>+ <main>+ <div class="wrap"><canvas id="grid"></canvas></div>+ <div class="wrap"><canvas id="rail"></canvas></div>+ </main>+ <footer>+ <span><b>12,000,000</b> rows <span class="sep">·</span> every row derived from its index by a hash <span class="sep">·</span> nothing stored</span>+ <span class="scan" id="scan">profiling…</span>+ <span class="r"><span id="sortnote"></span></span>+ </footer>+</div>++<script>+// ============================================================================================+// Generator. Every row is a pure function of its index. The same source runs in the scan workers.+// ============================================================================================+function makeGen(){+ const N = 12000000, DAYS = 731, EPOCH = Date.UTC(2024,0,1);+ const REGIONS = ["Northmark","Calder Reach","Vellmoor","Orrin Isles","Southfold","Hale Plains"];+ const CATS = ["Home","Electronics","Apparel","Garden","Books","Toys","Grocery","Beauty"];+ const NOUNS = [+ ["Linen throw","Stoneware mug","Walnut tray","Wool rug","Glass carafe","Oak stool","Table lamp","Cotton duvet","Ceramic vase","Wall clock","Bath towel","Candle set"],+ ["Wireless earbuds","Wall charger","USB-C hub","Smart plug","Pocket speaker","E-reader sleeve","Webcam","Keyboard","Power bank","Display cable","LED strip","Tablet stand"],+ ["Rain shell","Merino tee","Denim jacket","Wool beanie","Canvas sneaker","Linen shirt","Fleece vest","Chino","Rib socks","Knit scarf","Leather belt","Hoodie"],+ ["Seed tray","Pruning shears","Hose reel","Clay planter","Compost bin","Trowel","Bird feeder","Raised bed","Watering can","Grow light","Garden gloves","Solar lantern"],+ ["Field guide","Cookbook","Sketchbook","Atlas","Poetry reader","Novel","Puzzle book","Journal","Travel guide","Comic box set","History primer","Notebook set"],+ ["Wooden blocks","Kite","Jigsaw 1000","Plush fox","Train set","Marble run","Card game","Yo-yo","Balsa glider","Stacking rings","Dollhouse","Building kit"],+ ["Olive oil","Green tea","Oat milk","Coffee beans","Rye bread","Honey jar","Sea salt","Pasta","Dark chocolate","Rice","Granola","Hot sauce"],+ ["Face serum","Lip balm","Hand cream","Shampoo","Clay mask","Sunscreen","Body wash","Eye cream","Nail kit","Hair oil","Toner","Soap bar"]];+ const COL = ["sage","charcoal","oat","slate","ember","fern","dune","ink","moss","pearl"];+ const VAR = [COL,COL,COL,COL,["hardcover","paperback","vol. 1","vol. 2","vol. 3","pocket","large print","2nd ed.","boxed","annotated"],COL,+ ["250 g","500 g","1 kg","2 kg","organic","6-pack","12-pack","family","single","sampler"],["15 ml","30 ml","50 ml","100 ml","travel","refill","duo","trio","unscented","sensitive"]];+ const CAT_PRICE = [38,129,46,31,17,27,8.5,23];+ const CAT_MARGIN = [31,8,38,27,22,26,13,44];+ const CAT_W = [.16,.13,.18,.08,.10,.08,.17,.10];+ const REG_W = [.25,.21,.18,.14,.12,.10];++ function h32(x){ x|=0; x^=x>>>16; x=Math.imul(x,0x7feb352d); x^=x>>>15; x=Math.imul(x,0x846ca68b); x^=x>>>16; return x>>>0; }+ const U = 1/4294967296;+ const di = (y,m,d) => Math.round((Date.UTC(y,m-1,d)-EPOCH)/864e5);++ // ---- per-day tables: order density, promotions, mix ----+ const doy = new Uint16Array(DAYS), month = new Uint8Array(DAYS), dow = new Uint8Array(DAYS);+ for (let d=0; d<DAYS; d++){ const t = new Date(EPOCH + d*864e5); dow[d]=t.getUTCDay(); month[d]=t.getUTCMonth();+ doy[d] = Math.round((t - Date.UTC(t.getUTCFullYear(),0,1))/864e5); }+ const ev = new Float64Array(DAYS).fill(1), promo = new Uint8Array(DAYS);+ const setEv = (d, m, p) => { ev[d]=m; promo[d]=p; };+ [[2024,11,28,[2.6,2.15,1.8,1.5]],[2025,11,27,[2.95,2.4,1.95,1.6]],[2024,7,16,[1.8,1.45]],[2025,7,15,[2.05,1.6]]]+ .forEach(([y,m,d,ms]) => ms.forEach((k,j) => setEv(di(y,m,d)+j, k, 1)));+ const OUTAGE = di(2025,3,18); setEv(OUTAGE, 0.42, 0);+ const ORRIN_OPEN = di(2024,6,3);+ const w = new Float64Array(DAYS); let tot = 0;+ const WEEK = [1.13,0.93,0.95,0.97,1.0,1.05,1.17];+ for (let d=0; d<DAYS; d++){+ const y = doy[d];+ const season = 1 + 0.24*Math.exp(-(((y-348)/20)**2)) + 0.07*Math.cos(2*Math.PI*(y-200)/365) - 0.12*Math.exp(-(((y-22)/12)**2));+ const trend = 1 + 0.62*d/DAYS + (d>ORRIN_OPEN ? 0.09*Math.min(1,(d-ORRIN_OPEN)/120) : 0);+ const noise = 1 + 0.05*((h32(d*977+3)*U)-0.5);+ w[d] = trend*WEEK[dow[d]]*season*ev[d]*noise; tot += w[d];+ }+ const C = new Int32Array(DAYS+1); let acc=0;+ for (let d=0; d<DAYS; d++){ acc += w[d]; C[d+1] = Math.round(N*acc/tot); }+ C[DAYS] = N;+ const catCum = new Float64Array(DAYS*8), regCum = new Float64Array(DAYS*6);+ for (let d=0; d<DAYS; d++){+ const m = month[d], y = doy[d];+ const cw = CAT_W.slice();+ const xmas = Math.exp(-(((y-345)/25)**2));+ cw[5] *= 1 + 1.5*xmas; cw[1] *= 1 + 0.75*xmas + (promo[d]?0.6:0);+ cw[3] *= 1 + 1.3*Math.exp(-(((y-130)/38)**2));+ cw[7] *= 1 + 0.25*xmas;+ let s=0; for (let k=0;k<8;k++) s+=cw[k]; let a=0; for (let k=0;k<8;k++){ a+=cw[k]/s; catCum[d*8+k]=a; }+ const rw = REG_W.slice(); rw[3] = d < ORRIN_OPEN ? 0 : REG_W[3]*Math.min(1, 0.25 + 0.75*(d-ORRIN_OPEN)/150);+ s=0; for (let k=0;k<6;k++) s+=rw[k]; a=0; for (let k=0;k<6;k++){ a+=rw[k]/s; regCum[d*6+k]=a; }+ }+ // ---- items ----+ const itemBase = new Float64Array(96*10), itemMg = new Float64Array(960), itemPh = new Float64Array(960);+ for (let g=0; g<960; g++){+ const c = (g/120)|0, h1=h32(g*7919+13)*U, h2=h32(g*104729+7)*U, h3=h32(g*1299709+5)*U;+ const z = (h1+h2+h3-1.5)*2;+ itemBase[g] = CAT_PRICE[c]*Math.exp(0.48*z);+ itemMg[g] = (h32(g*31+1)*U-0.5)*10; itemPh[g] = h3*6.283;+ }+ function dayOf(i){ let lo=0, hi=DAYS-1; while (lo<hi){ const mid=(lo+hi+1)>>1; if (C[mid] <= i) lo=mid; else hi=mid-1; } return lo; }++ // row(i, o): fills o with the fields of row i. Money is in integer cents.+ function row(i, o){+ const b = h32(i ^ 0x5bd1e995) ^ 0x2545f491;+ const r = k => h32(b + Math.imul(k, 0x9e3779b9)) * U;+ const d = dayOf(i); o.day = d;+ const f = (i - C[d]) / (C[d+1] - C[d]);+ let s = Math.floor(86400*(f + 0.45*Math.sin(6.283185307*f)/6.283185307)); o.sec = s<0?0:s>86399?86399:s;+ let u = r(1), k = 0; const ro = d*6; while (k<5 && u > regCum[ro+k]) k++; o.region = k;+ u = r(2); k = 0; const co = d*8; while (k<7 && u > catCum[co+k]) k++; const cat = k; o.cat = cat;+ const it = Math.floor(120*Math.pow(r(3),1.7)); const g = cat*120 + it; o.item = g;+ const pr = promo[d] && r(4) < 0.62;+ let price = Math.max(1, Math.round(itemBase[g]*(1 + 0.045*d/DAYS)))*100 - 1;+ if (pr) price = Math.round(price*0.8);+ o.price = price; o.promo = pr ? 1 : 0;+ const u5 = r(5);+ let q = cat===6 ? 1 + Math.floor(-Math.log(1-u5)*2.4) : 1 + Math.floor(-Math.log(1-u5)*0.52); if (q>24) q=24;+ o.qty = q; o.amount = q*price;+ o.margin = Math.round((CAT_MARGIN[cat] + itemMg[g] + (r(6)-0.5)*18 - (pr?12:0))*10)/10;+ const age = DAYS-1-d, u7 = r(7);+ let st;+ if (age === 0) st = u7<0.68 ? 2 : u7<0.95 ? 1 : 4;+ else if (age <= 1) st = u7<0.3 ? 2 : u7<0.96 ? 1 : 4;+ else if (age <= 5) st = u7<0.78 ? 1 : u7<0.975 ? 0 : 4;+ else {+ const ret = cat===2 ? 0.11 : cat===1 ? 0.05 : cat===6 ? 0.008 : 0.025;+ const can = d === OUTAGE ? 0.21 : 0.022;+ st = u7 < can ? 4 : u7 < can+ret ? 3 : 0;+ }+ o.status = st; o.u8 = r(8);+ return o;+ }+ function itemName(g){ const c=(g/120)|0, k=g%120; return [NOUNS[c][k%12], VAR[c][(k/12)|0]]; }+ return { N, DAYS, EPOCH, C, REGIONS, CATS, OUTAGE, row, dayOf, itemName, itemBase, itemPh, h32, promo, ev };+}++// Worker body (runs inside a Blob worker; makeGen is prepended to it).+function workerMain(){+ const G = makeGen(); const o = {};+ self.onmessage = (e) => {+ const m = e.data;+ if (m.kind === "scan"){+ const { a, b, B } = m, N = G.N;+ const cube = new Float64Array(5*6*8*3), bk = new Float64Array(B*6);+ const qh = new Float64Array(25), ph = new Float64Array(40), ah = new Float64Array(40), mh = new Float64Array(50);+ const seen = new Uint8Array(960);+ for (let i=a; i<b; i++){+ G.row(i, o);+ const c3 = ((o.status*6 + o.region)*8 + o.cat)*3;+ cube[c3]++; cube[c3+1] += o.amount; cube[c3+2] += o.amount*o.margin;+ const bi = Math.floor(i*B/N); bk[bi*6+o.status]++; bk[bi*6+5] += o.amount;+ qh[o.qty]++;+ let x = Math.floor(Math.log10(o.price/100)/3.4*40); ph[x<0?0:x>39?39:x]++;+ x = Math.floor(Math.log10(o.amount/100)/4.4*40); ah[x<0?0:x>39?39:x]++;+ x = Math.floor((o.margin+30)/2); mh[x<0?0:x>49?49:x]++;+ seen[o.item] = 1;+ if (((i-a) & 262143) === 262143) self.postMessage({ kind:"progress", id:m.id, done:i-a+1 });+ }+ self.postMessage({ kind:"scan", id:m.id, cube, bk, qh, ph, ah, mh, seen, rows:b-a }, [cube.buffer, bk.buffer, qh.buffer, ph.buffer, ah.buffer, mh.buffer, seen.buffer]);+ } else if (m.kind === "sort"){+ const { a, b, col, K } = m; const n = b-a;+ const keys = new Uint8Array(n), counts = new Uint32Array(K);+ for (let i=a; i<b; i++){ G.row(i, o); const k = o[col]; keys[i-a] = k; counts[k]++; }+ const off = new Uint32Array(K); for (let k=1;k<K;k++) off[k] = off[k-1] + counts[k-1];+ const out = new Uint32Array(n);+ for (let j=0; j<n; j++) out[off[keys[j]]++] = a + j;+ self.postMessage({ kind:"sort", id:m.id, out, counts }, [out.buffer, counts.buffer]);+ }+ };+}+</script>+<script>+(() => {+"use strict";+const G = makeGen();+const N = G.N;+const STATUS = ["delivered","shipped","processing","returned","cancelled"];+const ST_COL = [ // pill bg, pill text, rail colour+ ["#1d2a1f","#9cc39b","#3c4a3e"], ["#1b2533","#8fb0d9","#38506e"], ["#2f2717","#d8b36a","#7d6431"],+ ["#272033","#b39ad9","#5e4a80"], ["#33201e","#d98a7e","#8a463d"]];+const REDUCED = matchMedia("(prefers-reduced-motion: reduce)").matches;+const $ = (id) => document.getElementById(id);+const grid = $("grid"), rail = $("rail");+const ctx = grid.getContext("2d"), rctx = rail.getContext("2d");+const buf = document.createElement("canvas"), bctx = buf.getContext("2d");+const UI = "system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif", MONO = "ui-monospace, 'SF Mono', Menlo, Consolas, monospace";+const LIME = "#c6f432";++// ---------- formatting (hand-rolled, no toLocaleString in the frame loop) ----------+function fmtInt(n){ n = Math.floor(n); const s = String(n); let out = ""; for (let i=0;i<s.length;i++){ if (i && (s.length-i)%3===0) out += ","; out += s[i]; } return out; }+function fmtCents(c){ const d = Math.floor(c/100), r = c%100; return "$" + fmtInt(d) + "." + (r<10?"0":"") + r; }+function fmtM(cents){ const v = cents/1e8; return v >= 100 ? "$" + v.toFixed(1) + "M" : "$" + v.toFixed(2) + "M"; }+function fmtK(n){ return n >= 1e6 ? (n/1e6).toFixed(2) + "M" : n >= 1e3 ? (n/1e3).toFixed(1) + "k" : String(n); }+const p2 = (n) => (n<10?"0":"") + n;+const DAYSTR = []; const MONTHS = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];+for (let d=0; d<G.DAYS; d++){ const t = new Date(G.EPOCH + d*864e5); DAYSTR.push(t.getUTCFullYear() + "-" + p2(t.getUTCMonth()+1) + "-" + p2(t.getUTCDate())); }+function fmtTs(d, s){ return DAYSTR[d] + " " + p2((s/3600)|0) + ":" + p2(((s/60)|0)%60) + ":" + p2(s%60); }+function pad8(n){ const s = String(n); return "00000000".slice(s.length) + s; }++// ---------- columns ----------+const COLS = [+ { key:"order_id", name:"order_id", type:"varchar", w:122, min:110, sort:"index", pri:9 },+ { key:"ordered_at",name:"ordered_at", type:"timestamp", w:170, min:156, sort:"index", pri:9 },+ { key:"buyer", name:"buyer", type:"varchar", w:96, min:90, pri:1 },+ { key:"region", name:"region", type:"enum(6)", w:126, min:104, sort:"key", K:6, pri:8 },+ { key:"category", name:"category", type:"enum(8)", w:116, min:96, sort:"key", K:8, field:"cat", pri:8 },+ { key:"item", name:"item", type:"varchar", w:236, min:184, grow:3, pri:7 },+ { key:"qty", name:"qty", type:"int32", w:58, min:50, align:"r", pri:6 },+ { key:"unit_price",name:"unit_price", type:"decimal", w:100, min:88, align:"r", pri:4 },+ { key:"amount", name:"amount", type:"decimal", w:116, min:102, align:"r", pri:8 },+ { key:"margin", name:"margin", type:"float · %", w:164, min:128, grow:2, pri:7 },+ { key:"status", name:"status", type:"enum(5)", w:118, min:108, sort:"key", K:5, pri:9 },+ { key:"price_12w", name:"price_12w", type:"list<f64>", w:132, min:104, grow:1, pri:3 }];+const RH = 26, GW = 74, HH = 82;++let W = 0, H = 0, DPR = 1, RW = 0, visCols = [], bodyH = 0, visRows = 0;+function layout(){+ DPR = window.devicePixelRatio || 1;+ const r = grid.parentElement.getBoundingClientRect(), rr = rail.parentElement.getBoundingClientRect();+ W = Math.round(r.width); H = Math.round(r.height); RW = Math.round(rr.width);+ for (const [c, x, w, h] of [[grid, ctx, W, H], [rail, rctx, RW, H]]){ c.width = Math.round(w*DPR); c.height = Math.round(h*DPR); }+ bodyH = H - HH; visRows = Math.ceil(bodyH/RH) + 1;+ buf.width = Math.round(W*DPR); buf.height = Math.round(bodyH*DPR);+ // fit columns+ const avail = W - GW - 16;+ let cols = COLS.slice();+ for (;;){+ const sw = cols.reduce((s,c)=>s+c.w,0), smin = cols.reduce((s,c)=>s+c.min,0);+ if (smin <= avail || cols.length < 4) {+ if (sw <= avail){ const extra = avail - sw, gs = cols.reduce((s,c)=>s+(c.grow||0),0);+ cols = cols.map(c => ({...c, cw: c.w + (gs ? extra*(c.grow||0)/gs : 0)})); }+ else { const k = (sw-avail)/(sw-smin); cols = cols.map(c => ({...c, cw: c.w - (c.w-c.min)*k})); }+ break;+ }+ let lo = 0; for (let i=1;i<cols.length;i++) if (cols[i].pri < cols[lo].pri) lo = i;+ cols.splice(lo, 1);+ }+ let x = GW; for (const c of cols){ c.x = Math.round(x); c.cw = Math.round(c.cw); x += c.cw; }+ visCols = cols;+ railStatic = null;+ dirty = true;+}++// ---------- state ----------+const S = { pos:0, target:0, prevPos:0, vel:0, focus:-1, hover:-1, sortCol:"order_id", dir:1, perm:null, permCol:null,+ mode:"table", glide:null, agg:null, speedRows:0, filterOnly:false };+let dirty = true;+const maxPos = () => Math.max(0, N - Math.floor(bodyH/RH));+function rowAt(r){ // display position -> generator index+ if (S.perm) return S.dir > 0 ? S.perm[r] : S.perm[N-1-r];+ return S.dir > 0 ? r : N-1-r;+}++// ---------- scan (Web Workers over all 12M rows) ----------+const SCAN = { done:false, ms:0, workers:0, progress:0, cube:null, bk:null, qh:null, ph:null, ah:null, mh:null, distinctItems:0, B:2048 };+let workerURL = null, pool = [];+function makeWorkers(n){+ try {+ const src = makeGen.toString() + "\n(" + workerMain.toString() + ")();";+ workerURL = URL.createObjectURL(new Blob([src], { type:"text/javascript" }));+ for (let i=0;i<n;i++) pool.push(new Worker(workerURL));+ return true;+ } catch (e) { pool = []; return false; }+}+function runScan(){+ const n = Math.max(2, Math.min(8, (navigator.hardwareConcurrency || 4) - 1));+ const B = SCAN.B;+ const t0 = performance.now();+ const merge = (res) => {+ if (!SCAN.cube){ SCAN.cube = new Float64Array(res.cube.length); SCAN.bk = new Float64Array(res.bk.length);+ SCAN.qh = new Float64Array(25); SCAN.ph = new Float64Array(40); SCAN.ah = new Float64Array(40); SCAN.mh = new Float64Array(50); SCAN.seen = new Uint8Array(960); }+ for (const k of ["cube","bk","qh","ph","ah","mh"]) { const A = SCAN[k], R = res[k]; for (let i=0;i<A.length;i++) A[i] += R[i]; }+ for (let i=0;i<960;i++) SCAN.seen[i] |= res.seen[i];+ };+ const finish = () => {+ SCAN.ms = performance.now() - t0; SCAN.done = true;+ SCAN.distinctItems = SCAN.seen.reduce((s,v)=>s+v,0);+ railStatic = null; dirty = true; updateFooter(); scanResolve();+ };+ if (makeWorkers(n)){+ SCAN.workers = n;+ const prog = new Array(n).fill(0); let left = n;+ pool.forEach((wk, id) => {+ const a = Math.floor(N*id/n), b = Math.floor(N*(id+1)/n);+ wk.onmessage = (e) => { const m = e.data;+ if (m.kind === "progress"){ prog[id] = m.done; SCAN.progress = prog.reduce((s,v)=>s+v,0)/N; updateFooter(); }+ else if (m.kind === "scan"){ prog[id] = m.rows; merge(m); if (--left === 0) finish(); } };+ wk.postMessage({ kind:"scan", id, a, b, B });+ });+ } else { // main-thread fallback in slices+ SCAN.workers = 0; const o = {}; let i = 0; const CH = 400000;+ const res = { cube:new Float64Array(720), bk:new Float64Array(B*6), qh:new Float64Array(25), ph:new Float64Array(40), ah:new Float64Array(40), mh:new Float64Array(50), seen:new Uint8Array(960) };+ const step = () => { const end = Math.min(N, i+CH);+ for (; i<end; i++){ G.row(i,o); const c3=((o.status*6+o.region)*8+o.cat)*3; res.cube[c3]++; res.cube[c3+1]+=o.amount; res.cube[c3+2]+=o.amount*o.margin;+ const bi=Math.floor(i*B/N); res.bk[bi*6+o.status]++; res.bk[bi*6+5]+=o.amount; res.qh[o.qty]++;+ let x=Math.floor(Math.log10(o.price/100)/3.4*40); res.ph[x<0?0:x>39?39:x]++; x=Math.floor(Math.log10(o.amount/100)/4.4*40); res.ah[x<0?0:x>39?39:x]++;+ x=Math.floor((o.margin+30)/2); res.mh[x<0?0:x>49?49:x]++; res.seen[o.item]=1; }+ SCAN.progress = i/N; updateFooter();+ if (i < N) setTimeout(step, 0); else { merge(res); finish(); } };+ setTimeout(step, 0);+ }+}+let scanResolve; const scanReady = new Promise((ok) => { scanResolve = ok; });++function sortBy(col){ // returns a promise; real counting sort over all rows in the workers+ const field = col.field || col.key, K = col.K;+ if (!pool.length) return Promise.reject(new Error("no workers"));+ const t0 = performance.now(), n = pool.length;+ return new Promise((ok) => {+ const parts = new Array(n); let left = n;+ pool.forEach((wk, id) => {+ const a = Math.floor(N*id/n), b = Math.floor(N*(id+1)/n);+ wk.onmessage = (e) => { if (e.data.kind !== "sort") return; parts[id] = e.data; if (--left === 0) {+ const perm = new Uint32Array(N); let p = 0;+ for (let k=0;k<K;k++) for (let w=0; w<n; w++){ const pt = parts[w]; let off = 0; for (let j=0;j<k;j++) off += pt.counts[j];+ perm.set(pt.out.subarray(off, off+pt.counts[k]), p); p += pt.counts[k]; }+ ok({ perm, ms: performance.now()-t0, workers:n });+ } };+ wk.postMessage({ kind:"sort", id, a, b, col:field, K });+ });+ });+}++// ---------- row data for drawing ----------+const tmp = {};+function rowData(r){+ const i = rowAt(r); G.row(i, tmp);+ const nm = G.itemName(tmp.item);+ return { r, i, id: "MK-" + pad8(i+1), ts: fmtTs(tmp.day, tmp.sec), buyer: "c_" + (Math.floor(tmp.u8*60466176)).toString(36).padStart(5,"0"),+ region: tmp.region, cat: tmp.cat, item: nm[0], variant: nm[1], g: tmp.item, day: tmp.day,+ qty: String(tmp.qty), price: fmtCents(tmp.price), amount: fmtCents(tmp.amount), amountC: tmp.amount, margin: tmp.margin, status: tmp.status, promo: tmp.promo };+}+function spark(g, day){+ const wk = (day/7)|0, base = G.itemBase[g], ph = G.itemPh[g], out = new Array(12);+ for (let j=0;j<12;j++){ const w = wk - 11 + j; out[j] = base*(1 + 0.06*Math.sin(w*0.55 + ph) + 0.05*((G.h32(g*131 + w*7 + 3)/4294967296) - 0.5) + 0.03*w/104); }+ return out;+}++// ---------- pill sprites ----------+const pills = [];+function makePills(){+ pills.length = 0;+ for (let s=0;s<5;s++){+ const c = document.createElement("canvas"), g = c.getContext("2d");+ g.font = `500 11.5px ${UI}`; const tw = Math.ceil(g.measureText(STATUS[s]).width);+ const w = tw + 26, h = 19; c.width = w*DPR; c.height = h*DPR; g.scale(DPR, DPR);+ g.fillStyle = ST_COL[s][0]; g.beginPath(); g.roundRect(0.5, 0.5, w-1, h-1, 9.5); g.fill();+ g.fillStyle = ST_COL[s][1]; g.beginPath(); g.arc(10, h/2, 2.6, 0, 6.283); g.fill();+ g.font = `500 11.5px ${UI}`; g.textBaseline = "middle"; g.fillText(STATUS[s], 17, h/2 + 0.5);+ pills.push({ c, w, h });+ }+}++// ---------- drawing: table ----------+function drawHeader(g, alpha){+ if (alpha <= 0) return;+ g.save(); g.globalAlpha = alpha;+ g.fillStyle = "#121316"; g.fillRect(0, 0, W, HH);+ g.fillStyle = "#222429"; g.fillRect(0, HH-1, W, 1);+ // gutter label+ g.font = `10.5px ${MONO}`; g.fillStyle = "#4b5058"; g.textAlign = "right"; g.textBaseline = "alphabetic";+ g.fillText("#", GW-14, 25);+ for (const c of visCols){+ const x = c.x, w = c.cw, right = c.align === "r";+ const sorted = S.sortCol === c.key;+ g.textAlign = right ? "right" : "left";+ const tx = right ? x + w - 12 : x + 12;+ g.font = `500 13px ${UI}`; g.fillStyle = sorted ? "#f1f3f5" : "#d3d6db"; g.fillText(c.name, tx, 25);+ g.font = `10.5px ${MONO}`; g.fillStyle = "#5b6068"; g.fillText(c.type, tx, 41);+ // sort / filter affordances+ const nameW = (g.font = `500 13px ${UI}`, g.measureText(c.name).width);+ const ax = right ? tx - nameW - 14 : tx + nameW + 7;+ if (c.sort){+ g.fillStyle = sorted ? LIME : "#41454c";+ g.beginPath();+ if (!sorted || S.dir > 0){ g.moveTo(ax, 18); g.lineTo(ax+7, 18); g.lineTo(ax+3.5, 13.5); }+ if (!sorted || S.dir < 0){ g.moveTo(ax, 20.5); g.lineTo(ax+7, 20.5); g.lineTo(ax+3.5, 25); }+ g.fill();+ }+ if (c.key === "status" || c.key === "region" || c.key === "category"){+ const fx = right ? x + 10 : x + w - 22, fy = 15;+ g.strokeStyle = (c.key === "status" && S.agg) ? LIME : "#4b4f57"; g.lineWidth = 1.2;+ g.beginPath(); g.moveTo(fx, fy); g.lineTo(fx+10, fy); g.lineTo(fx+6.2, fy+4.6); g.lineTo(fx+6.2, fy+8.5); g.lineTo(fx+3.8, fy+9.6); g.lineTo(fx+3.8, fy+4.6); g.closePath(); g.stroke();+ }+ // column profile+ drawProfile(g, c, x + 12, 50, w - 24, 22);+ // resize handle+ g.fillStyle = "#26292e"; g.fillRect(x + w - 1, 10, 1, HH - 20);+ g.fillStyle = "#3a3e45"; g.fillRect(x + w - 2.5, HH/2 - 6, 1, 12); g.fillRect(x + w + 0.5, HH/2 - 6, 1, 12);+ }+ g.restore();+}++function histBars(g, arr, x, y, w, h, from, to, color, logY){+ let mx = 0; for (let i=from;i<to;i++) mx = Math.max(mx, logY ? Math.log1p(arr[i]) : arr[i]);+ const n = to-from, bw = w/n;+ g.fillStyle = color;+ for (let i=from;i<to;i++){ const v = logY ? Math.log1p(arr[i]) : arr[i]; const bh = mx ? Math.max(v>0?1:0, v/mx*h) : 0;+ g.fillRect(x + (i-from)*bw, y + h - bh, Math.max(1, bw - 1), bh); }+}+function drawProfile(g, c, x, y, w, h){+ g.textAlign = "left";+ const done = SCAN.done;+ if (!done){+ g.fillStyle = "#1a1b1f"; g.fillRect(x, y + h - 3, w, 3);+ g.fillStyle = "#3a3d44"; g.fillRect(x, y + h - 3, w*SCAN.progress, 3);+ return;+ }+ const grow = PROFILE_T;+ g.save(); g.beginPath(); g.rect(x, y - 2, w*grow + 1, h + 4); g.clip();+ const cube = SCAN.cube;+ const label = (t) => { g.font = `10.5px ${MONO}`; g.fillStyle = "#6a6f78"; g.textBaseline = "middle"; g.fillText(t, x, y + h/2 + 1); g.textBaseline = "alphabetic"; };+ switch (c.key){+ case "order_id": label("12M unique"); break;+ case "buyer": label("hashed id"); break;+ case "item": label(fmtInt(SCAN.distinctItems) + " distinct"); break;+ case "price_12w": label("12 weeks"); break;+ case "ordered_at": { // orders per day, all 731 days (from the day table)+ const C = G.C; let mx = 0; for (let d=0; d<G.DAYS; d++) mx = Math.max(mx, C[d+1]-C[d]);+ g.fillStyle = "#4a4f57"; const bw = w/G.DAYS;+ for (let d=0; d<G.DAYS; d++){ const v = (C[d+1]-C[d])/mx*h; g.fillRect(x + d*bw, y + h - v, Math.max(0.8, bw), v); }+ break; }+ case "region": case "category": case "status": {+ const K = c.key === "region" ? 6 : c.key === "category" ? 8 : 5, cnt = new Float64Array(K);+ for (let s=0;s<5;s++) for (let r=0;r<6;r++) for (let k=0;k<8;k++){ const v = cube[((s*6+r)*8+k)*3]; cnt[c.key==="region"?r:c.key==="category"?k:s] += v; }+ let mx = 0; for (const v of cnt) mx = Math.max(mx, v);+ const bw = w/K;+ for (let k=0;k<K;k++){ const bh = Math.max(2, cnt[k]/mx*h);+ g.fillStyle = c.key === "status" ? ST_COL[k][2] : "#4a4f57"; g.fillRect(x + k*bw, y + h - bh, bw - 2, bh); }+ break; }+ case "qty": histBars(g, SCAN.qh, x, y, w, h, 1, 25, "#4a4f57", true); break;+ case "unit_price": histBars(g, SCAN.ph, x, y, w, h, 0, 40, "#4a4f57"); break;+ case "amount": histBars(g, SCAN.ah, x, y, w, h, 0, 40, "#4a4f57"); break;+ case "margin": {+ let mx = 0; for (const v of SCAN.mh) mx = Math.max(mx, v); const bw = w/50;+ for (let i=0;i<50;i++){ const bh = SCAN.mh[i]/mx*h; g.fillStyle = i < 15 ? "#6b3a33" : "#4a4f57"; g.fillRect(x + i*bw, y + h - bh, Math.max(1, bw-1), bh); }+ g.fillStyle = "#8b9099"; g.fillRect(x + 15*bw - 0.5, y - 1, 1, h + 2);+ break; }+ }+ g.restore();+}++// Draws the rows into g, body coordinates (0 = first row under the header).+function drawRows(g, list, opts){+ const fast = opts && opts.fast;+ const top = Math.floor(S.pos), frac = S.pos - top;+ // zebra + highlight backgrounds+ for (const it of list){+ const y = it.y, h = it.h; if (h <= 0.3) continue;+ g.globalAlpha = it.a;+ g.fillStyle = (it.d.r & 1) ? "#131417" : "#0f1012"; g.fillRect(0, y, W, h);+ if (it.d.r === S.focus){ g.fillStyle = "rgba(198,244,50,0.075)"; g.fillRect(0, y, W, h); g.fillStyle = LIME; g.fillRect(0, y, 3, h); }+ else if (it.d.r === S.hover && !fast){ g.fillStyle = "rgba(255,255,255,0.03)"; g.fillRect(0, y, W, h); }+ }+ g.globalAlpha = 1;+ // gutter separator+ g.fillStyle = "#1c1e22"; g.fillRect(GW - 1, 0, 1, bodyH);+ g.textBaseline = "middle";+ // gutter numbers+ g.font = `11px ${MONO}`; g.textAlign = "right";+ for (const it of list){ if (it.h < 6) continue; g.globalAlpha = it.a;+ g.fillStyle = it.d.r === S.focus ? LIME : "#4d5259"; g.fillText(fmtInt(it.d.r + 1), GW - 14, it.y + it.h/2 + 0.5); }+ for (const c of visCols){+ const x = c.x, w = c.cw, k = c.key;+ if (k === "order_id" || k === "ordered_at" || k === "buyer"){+ g.font = `12px ${MONO}`; g.textAlign = "left";+ for (const it of list){ if (it.h < 6) continue; g.globalAlpha = it.a; const d = it.d;+ g.fillStyle = k === "ordered_at" ? "#aeb3bb" : k === "buyer" ? "#7d838c" : (d.r === S.focus ? "#f4f6f8" : "#c9ccd2");+ g.fillText(k === "order_id" ? d.id : k === "buyer" ? d.buyer : d.ts, x + 12, it.y + it.h/2 + 0.5); }+ } else if (k === "region" || k === "category"){+ g.font = `13px ${UI}`; g.textAlign = "left"; g.fillStyle = "#d5d8dd";+ for (const it of list){ if (it.h < 6) continue; g.globalAlpha = it.a;+ g.fillText(k === "region" ? G.REGIONS[it.d.region] : G.CATS[it.d.cat], x + 12, it.y + it.h/2 + 0.5); }+ } else if (k === "item"){+ g.textAlign = "left";+ for (const it of list){ if (it.h < 6) continue; g.globalAlpha = it.a; const d = it.d;+ g.font = `13px ${UI}`; g.fillStyle = "#eceef1"; g.fillText(d.item, x + 12, it.y + it.h/2 + 0.5);+ const tw = g.measureText(d.item).width;+ g.font = `12px ${UI}`; g.fillStyle = "#6c717a"; if (12 + tw + 8 + 40 < w) g.fillText(d.variant, x + 12 + tw + 7, it.y + it.h/2 + 0.5);+ if (d.promo && w > 200){ g.font = `10px ${MONO}`; g.fillStyle = "#8f9a6a"; g.textAlign = "right"; g.fillText("promo", x + w - 10, it.y + it.h/2 + 0.5); g.textAlign = "left"; }+ }+ } else if (k === "qty" || k === "unit_price" || k === "amount"){+ g.font = k === "amount" ? `500 12.5px ${MONO}` : `12px ${MONO}`; g.textAlign = "right";+ for (const it of list){ if (it.h < 6) continue; g.globalAlpha = it.a; const d = it.d;+ g.fillStyle = k === "amount" ? "#f0f2f4" : k === "qty" ? "#aeb3bb" : "#aeb3bb";+ g.fillText(k === "qty" ? d.qty : k === "unit_price" ? d.price : d.amount, x + w - 12, it.y + it.h/2 + 0.5); }+ } else if (k === "margin"){+ const bx = x + 12, bw = w - 12 - 62, z = bx + bw*0.3;+ g.font = `12px ${MONO}`; g.textAlign = "right";+ for (const it of list){ if (it.h < 6) continue; g.globalAlpha = it.a; const d = it.d, m = d.margin, cy = it.y + it.h/2;+ g.fillStyle = "#24262b"; g.fillRect(bx, cy - 0.5, bw, 1);+ g.fillStyle = "#3a3d44"; g.fillRect(z - 0.5, cy - 6, 1, 12);+ if (m >= 0){ const L = Math.min(bw*0.7, m/60*bw*0.7); g.fillStyle = LIME; g.globalAlpha = it.a*0.82; g.fillRect(z, cy - 3.5, L, 7); }+ else { const L = Math.min(bw*0.3, -m/30*bw*0.3); g.fillStyle = "#d9634f"; g.globalAlpha = it.a*0.82; g.fillRect(z - L, cy - 3.5, L, 7); }+ g.globalAlpha = it.a; g.fillStyle = m < 0 ? "#e38b7c" : "#b6bac1"; g.fillText(m.toFixed(1) + "%", x + w - 12, cy + 0.5); }+ } else if (k === "status"){+ for (const it of list){ if (it.h < 6) continue; g.globalAlpha = it.a; const p = pills[it.d.status];+ g.drawImage(p.c, x + 10, it.y + (it.h - p.h)/2, p.w, p.h); }+ } else if (k === "price_12w"){+ g.lineWidth = 1.25; g.lineJoin = "round";+ for (const it of list){ if (it.h < 14) continue; g.globalAlpha = it.a; const d = it.d; const v = spark(d.g, d.day);+ let lo = Infinity, hi = -Infinity; for (const q of v){ lo = Math.min(lo,q); hi = Math.max(hi,q); }+ const sx = x + 12, sw = w - 34, sy = it.y + 6, sh = it.h - 12, rng = (hi - lo) || 1;+ g.strokeStyle = "#727881"; g.beginPath();+ for (let j=0;j<12;j++){ const px = sx + j*sw/11, py = sy + sh - (v[j]-lo)/rng*sh; j ? g.lineTo(px,py) : g.moveTo(px,py); }+ g.stroke();+ const up = v[11] >= v[0], ly = sy + sh - (v[11]-lo)/rng*sh;+ g.fillStyle = up ? "#d5d8dd" : "#e38b7c"; g.beginPath(); g.arc(sx + sw, ly, 2, 0, 6.283); g.fill();+ g.font = `10px ${MONO}`; g.textAlign = "left"; g.fillStyle = "#5b6068";+ g.fillText((up?"+":"−") + Math.abs((v[11]/v[0]-1)*100).toFixed(0), sx + sw + 5, it.y + it.h/2 + 0.5);+ }+ }+ }+ g.globalAlpha = 1; g.textBaseline = "alphabetic";+ // row hairlines every row (very faint)+ g.fillStyle = "rgba(255,255,255,0.025)";+ for (const it of list){ if (it.h > 2) g.fillRect(GW, it.y + it.h - 1, W - GW, 1); }+}+function tableList(){+ const top = Math.floor(S.pos), frac = S.pos - top, out = [];+ for (let k=0; k<visRows; k++){ const r = top + k; if (r >= N) break; out.push({ d: rowData(r), y: (k - frac)*RH, h: RH, a: 1 }); }+ return out;+}++// ---------- aggregate (pivot) ----------+function pivotData(){+ const cube = SCAN.cube, cell = [], rowT = [], colT = new Array(8).fill(null).map(()=>({n:0,amt:0,gm:0}));+ let grand = { n:0, amt:0, gm:0 };+ for (let r=0;r<6;r++){ const row = []; const rt = { n:0, amt:0, gm:0 };+ for (let c=0;c<8;c++){ const o = ((0*6 + r)*8 + c)*3; const v = { n:cube[o], amt:cube[o+1], gm:cube[o+2] };+ row.push(v); rt.n += v.n; rt.amt += v.amt; rt.gm += v.gm; colT[c].n += v.n; colT[c].amt += v.amt; colT[c].gm += v.gm; }+ cell.push(row); rowT.push(rt); grand.n += rt.n; grand.amt += rt.amt; grand.gm += rt.gm; }+ let maxCell = 0; for (const row of cell) for (const v of row) maxCell = Math.max(maxCell, v.amt);+ const order = [0,1,2,3,4,5].sort((a,b) => rowT[b].amt - rowT[a].amt);+ return { cell, rowT, colT, grand, maxCell, order, maxRow: Math.max(...rowT.map(r=>r.amt)), maxCol: Math.max(...colT.map(c=>c.amt)) };+}+function pivotLayout(){+ const L = {}; L.x0 = 28; L.x1 = W - 28; L.top = 92; // body coords+ L.labW = W > 1500 ? 214 : 170; L.totW = W > 1500 ? 236 : 186;+ L.cellW = (L.x1 - L.x0 - L.labW - L.totW)/8;+ L.headH = 46; const avail = bodyH - L.top - L.headH - 24;+ L.rowH = Math.min(104, Math.floor(avail/7)); L.y0 = L.top + L.headH;+ return L;+}+const ease = (t) => t<=0?0:t>=1?1:t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2;+const easeOut = (t) => t<=0?0:t>=1?1:1-Math.pow(1-t,3);+const clamp01 = (t) => t<0?0:t>1?1:t;++function drawPivot(g, P, L, t){ // t: time in s since group start; P/L data/layout+ const appear = easeOut(clamp01(t/0.6));+ g.save(); g.globalAlpha = appear;+ // title block+ g.textBaseline = "alphabetic"; g.textAlign = "left";+ g.font = `500 22px ${UI}`; g.fillStyle = "#eef0f3"; g.fillText("Σ amount by region × category", L.x0, 42);+ g.font = `12px ${MONO}`; g.fillStyle = "#7d838c";+ g.fillText(`status = 'delivered' · ${fmtInt(P.grand.n)} of 12,000,000 rows → 48 groups · cell: Σ amount, orders, gross margin`, L.x0, 66);+ // grand total+ const gt = easeOut(clamp01((t - 1.6)/1.4));+ g.textAlign = "right"; g.font = `500 34px ${MONO}`; g.fillStyle = LIME;+ g.fillText(fmtM(P.grand.amt*gt), L.x1, 44);+ g.font = `12px ${MONO}`; g.fillStyle = "#7d838c";+ g.fillText(`total · ${(P.grand.gm/P.grand.amt).toFixed(1)}% gross margin · avg ${fmtCents(Math.round(P.grand.amt/P.grand.n))}`, L.x1, 66);+ // header row+ const hy = L.top;+ g.fillStyle = "#1e2024"; g.fillRect(L.x0, hy + L.headH - 1, L.x1 - L.x0, 1);+ g.font = `10.5px ${MONO}`; g.fillStyle = "#5b6068"; g.textAlign = "left"; g.fillText("REGION ↓ Σ", L.x0, hy + 28);+ for (let c=0;c<8;c++){ const x = L.x0 + L.labW + c*L.cellW;+ g.font = `500 13px ${UI}`; g.fillStyle = "#d3d6db"; g.textAlign = "left"; g.fillText(G.CATS[c], x + 12, hy + 22);+ g.font = `10.5px ${MONO}`; g.fillStyle = "#5b6068"; g.fillText((P.colT[c].amt/P.grand.amt*100).toFixed(1) + "% of Σ", x + 12, hy + 37); }+ g.font = `500 13px ${UI}`; g.fillStyle = "#eef0f3"; g.textAlign = "right"; g.fillText("Region total", L.x1 - 12, hy + 22);+ g.font = `10.5px ${MONO}`; g.fillStyle = "#5b6068"; g.fillText("Σ amount · share", L.x1 - 12, hy + 37);+ // rows+ for (let ri=0; ri<6; ri++){+ const r = P.order[ri], y = L.y0 + ri*L.rowH, RT = P.rowT[r];+ g.fillStyle = (ri & 1) ? "#121316" : "#0f1012"; g.fillRect(L.x0, y, L.x1 - L.x0, L.rowH);+ g.fillStyle = "#1c1e22"; g.fillRect(L.x0, y + L.rowH - 1, L.x1 - L.x0, 1);+ g.textAlign = "left"; g.font = `500 16px ${UI}`; g.fillStyle = "#eef0f3"; g.fillText(G.REGIONS[r], L.x0 + 4, y + 34);+ g.font = `11px ${MONO}`; g.fillStyle = "#6c717a"; g.fillText(fmtInt(RT.n) + " orders", L.x0 + 4, y + 54);+ g.fillText((RT.gm/RT.amt).toFixed(1) + "% margin", L.x0 + 4, y + 70);+ for (let c=0;c<8;c++){+ const v = P.cell[r][c], x = L.x0 + L.labW + c*L.cellW;+ const p = easeOut(clamp01((t - 0.9 - c*0.07 - ri*0.05)/1.3));+ const heat = v.amt / P.maxCell;+ g.fillStyle = `rgba(198,244,50,${(0.015 + 0.11*heat*heat)*p})`; g.fillRect(x + 1, y + 1, L.cellW - 2, L.rowH - 3);+ g.fillStyle = "#1c1e22"; g.fillRect(x, y + 8, 1, L.rowH - 16);+ g.textAlign = "left"; g.font = `500 15px ${MONO}`; g.fillStyle = heat > 0.75 ? "#f6ffd6" : "#e3e5e9";+ g.fillText(fmtM(v.amt*p), x + 12, y + 30);+ g.font = `11px ${MONO}`; g.fillStyle = "#6c717a";+ g.fillText(fmtK(Math.round(v.n*p)), x + 12, y + 48);+ const mg = v.gm/v.amt; g.textAlign = "right"; g.fillStyle = mg < 15 ? "#c98a7f" : "#8b9099"; g.fillText(mg.toFixed(1) + "%", x + L.cellW - 12, y + 48);+ const bw = (L.cellW - 24) * (v.amt/P.maxCell) * p;+ g.fillStyle = "#1f2125"; g.fillRect(x + 12, y + L.rowH - 22, L.cellW - 24, 5);+ g.fillStyle = LIME; g.fillRect(x + 12, y + L.rowH - 22, bw, 5);+ }+ const p = easeOut(clamp01((t - 1.3 - ri*0.06)/1.4)), tx = L.x1 - L.totW;+ g.fillStyle = "#26292e"; g.fillRect(tx, y + 8, 1, L.rowH - 16);+ g.textAlign = "right"; g.font = `500 19px ${MONO}`; g.fillStyle = "#f4f6f8"; g.fillText(fmtM(RT.amt*p), L.x1 - 12, y + 32);+ g.font = `11px ${MONO}`; g.fillStyle = "#8b9099"; g.fillText((RT.amt/P.grand.amt*100*p).toFixed(1) + "%", L.x1 - 12, y + 50);+ g.fillStyle = "#1f2125"; g.fillRect(tx + 16, y + L.rowH - 24, L.totW - 28, 8);+ g.fillStyle = LIME; g.fillRect(tx + 16, y + L.rowH - 24, (L.totW - 28)*RT.amt/P.maxRow*p, 8);+ }+ // column totals row+ const ty = L.y0 + 6*L.rowH, th = L.rowH*0.9;+ g.fillStyle = "#17181c"; g.fillRect(L.x0, ty, L.x1 - L.x0, th);+ g.fillStyle = "#3a3d44"; g.fillRect(L.x0, ty, L.x1 - L.x0, 1);+ g.textAlign = "left"; g.font = `500 14px ${UI}`; g.fillStyle = "#eef0f3"; g.fillText("Category total", L.x0 + 4, ty + 30);+ g.font = `11px ${MONO}`; g.fillStyle = "#6c717a"; g.fillText(fmtInt(P.grand.n) + " orders", L.x0 + 4, ty + 50);+ for (let c=0;c<8;c++){ const v = P.colT[c], x = L.x0 + L.labW + c*L.cellW;+ const p = easeOut(clamp01((t - 1.5 - c*0.06)/1.3));+ g.textAlign = "left"; g.font = `500 15px ${MONO}`; g.fillStyle = "#f0f2f4"; g.fillText(fmtM(v.amt*p), x + 12, ty + 30);+ g.font = `11px ${MONO}`; g.fillStyle = "#8b9099"; g.fillText((v.gm/v.amt).toFixed(1) + "% margin", x + 12, ty + 48);+ const bh = (th - 62) * v.amt/P.maxCol * p;+ const bw = (L.cellW - 24) * v.amt/P.maxCol * p; g.fillStyle = "#2a2d33"; g.fillRect(x + 12, ty + th - 14, L.cellW - 24, 4); g.fillStyle = LIME; g.globalAlpha = appear*0.9; g.fillRect(x + 12, ty + th - 14, bw, 4); g.globalAlpha = appear;+ }+ const tx = L.x1 - L.totW; const pp = gt;+ g.textAlign = "right"; g.font = `600 21px ${MONO}`; g.fillStyle = LIME; g.fillText(fmtM(P.grand.amt*pp), L.x1 - 12, ty + 33);+ g.font = `11px ${MONO}`; g.fillStyle = "#8b9099"; g.fillText("grand total · 100%", L.x1 - 12, ty + 51);+ g.restore();+}++// aggregate animation state+function buildAgg(){+ const top = Math.floor(S.pos); const items = []; let delivered = 0, r = top;+ const need = visRows + 4;+ while (delivered < need && r < N){ const d = rowData(r); items.push(d); if (d.status === 0) delivered++; r++; }+ return { t0: performance.now(), items, P: pivotData(), L: pivotLayout(), done: false, start: top, frac: S.pos - top };+}+function aggFrame(){+ const A = S.agg, t = REDUCED ? 99 : (performance.now() - A.t0)/1000;+ // phase 1 (0.15–1.0 s): non-matching rows collapse out. phase 2 (1.05–1.85 s): rows fly into their region row.+ const pf = ease(clamp01((t - 0.15)/0.85)), pg = clamp01((t - 1.05)/0.8);+ const list = []; let y = -A.frac*RH;+ const L = A.L, P = A.P; const rowY = new Array(6); P.order.forEach((r, ri) => { rowY[r] = L.y0 + ri*L.rowH; });+ let j = 0;+ for (const d of A.items){+ const keep = d.status === 0, h = keep ? RH : RH*(1 - pf);+ let yy = y, hh = h, a = keep ? 1 : 1 - pf;+ if (keep && pg > 0){ const e = ease(clamp01(pg*1.25 - j*0.012)); yy = y + (rowY[d.region] + L.rowH/2 - RH/2 - y)*e; a = 1 - e; hh = RH*(1 - 0.6*e); }+ if (a > 0.01 && yy < bodyH && yy + hh > -RH) list.push({ d, y: yy, h: hh, a });+ y += h; if (keep) j++;+ }+ return { list, t, pf, pg };+}++// ---------- rail (minimap + scrollbar) ----------+let railStatic = null;+function buildRailStatic(){+ const c = document.createElement("canvas"); c.width = Math.round(RW*DPR); c.height = Math.round(H*DPR);+ const g = c.getContext("2d"); g.scale(DPR, DPR);+ g.fillStyle = "#101114"; g.fillRect(0, 0, RW, H);+ const top = HH, h = H - HH - 8, lab = RW > 120 ? 50 : 44, bx = lab + 6, bw = RW - bx - 10;+ // header part+ g.font = `10.5px ${MONO}`; g.fillStyle = "#5b6068"; g.textAlign = "left";+ g.fillText("OVERVIEW", 12, 25); g.fillText("orders / hour", 12, 41);+ g.fillStyle = "#222429"; g.fillRect(0, HH - 1, RW, 1);+ // per-pixel buckets by row index: width = order rate (rows per hour of that slice), colour = status mix (scan)+ const C = G.C; const rate = new Float64Array(h); let mx = 0;+ for (let p=0;p<h;p++){+ const i0 = Math.floor(p*N/h), i1 = Math.min(N-1, Math.floor((p+1)*N/h) - 1);+ const d0 = G.dayOf(i0), d1 = G.dayOf(i1);+ // rows per day at the middle of the slice+ const dm = G.dayOf((i0+i1)>>1); rate[p] = (C[dm+1]-C[dm])/24; mx = Math.max(mx, rate[p]);+ }+ for (let p=0;p<h;p++){+ const L = rate[p]/mx*bw, y = top + 4 + p;+ if (SCAN.done){+ const b0 = Math.floor(p*SCAN.B/h), b1 = Math.max(b0+1, Math.floor((p+1)*SCAN.B/h)); const st = [0,0,0,0,0]; let tot = 0;+ for (let b=b0;b<b1;b++) for (let s=0;s<5;s++){ st[s] += SCAN.bk[b*6+s]; tot += SCAN.bk[b*6+s]; }+ let x = bx; for (const s of [0,1,2,3,4]){ const sw = L*st[s]/tot; g.fillStyle = s === 0 ? "#3b3e45" : ST_COL[s][2]; g.fillRect(x, y, sw, 1); x += sw; }+ } else { g.fillStyle = "#26282d"; g.fillRect(bx, y, L, 1); }+ }+ // month ticks+ g.textAlign = "right"; g.font = `9.5px ${MONO}`;+ for (let y=2024; y<=2025; y++) for (let m=0;m<12;m++){+ const d = Math.round((Date.UTC(y,m,1) - G.EPOCH)/864e5); const py = top + 4 + C[d]/N*h;+ g.fillStyle = "#2a2c31"; g.fillRect(lab, py, bw + 6, 1);+ if (m % 3 === 0 || (RW > 120 && m % 2 === 0)){ g.fillStyle = m === 0 ? "#9aa0a8" : "#555a62"; g.fillText(m === 0 ? String(y) : MONTHS[m], lab - 2, py + 3.5); }+ }+ // annotations: outage + peak+ const ann = (d, t) => { const py = top + 4 + (C[d] + C[d+1])/2/N*h; g.fillStyle = "#d9634f"; g.fillRect(RW - 8, py - 0.5, 4, 1); };+ ann(G.OUTAGE);+ return { c, top: top + 4, h };+}+function drawRail(){+ if (!railStatic) railStatic = buildRailStatic();+ const g = rctx; g.setTransform(1,0,0,1,0,0); g.drawImage(railStatic.c, 0, 0); g.setTransform(DPR,0,0,DPR,0,0);+ const { top, h } = railStatic, lab = RW > 120 ? 50 : 44;+ const span = Math.floor(bodyH/RH);+ const y0 = top + S.pos/N*h, th = Math.max(4, span/N*h);+ // trail during fast scrolls+ if (Math.abs(S.speedRows) > 2000){ const len = Math.min(140, Math.abs(S.speedRows)/N*h*6), dir = Math.sign(S.speedRows);+ const gr = g.createLinearGradient(0, y0 - dir*len, 0, y0); gr.addColorStop(0, "rgba(198,244,50,0)"); gr.addColorStop(1, "rgba(198,244,50,0.35)");+ g.fillStyle = gr; g.fillRect(lab + 4, dir > 0 ? y0 - len : y0, RW - lab - 10, len); }+ g.fillStyle = "rgba(198,244,50,0.16)"; g.fillRect(2, y0 - 6, RW - 4, th + 12);+ g.fillStyle = LIME; g.fillRect(2, y0 - 6, 2, th + 12); g.fillRect(2, y0 + th/2 - 0.5, RW - 4, 1);+ g.font = `500 10px ${MONO}`; g.textAlign = "left"; g.fillStyle = LIME;+ const dd = DAYSTR[G.dayOf(rowAt(Math.min(N-1, Math.floor(S.pos))))].slice(2);+ if (!S.perm && S.dir > 0) g.fillText(dd, 8, y0 - 10 < top + 10 ? y0 + th + 18 : y0 - 10);+}++// ---------- main render ----------+let PROFILE_T = 0, profT0 = 0;+function render(){+ ctx.setTransform(DPR,0,0,DPR,0,0);+ let list, aggInfo = null;+ if (S.agg){ aggInfo = aggFrame(); list = aggInfo.list; } else list = tableList();+ const speed = Math.abs(S.speedRows);+ const blur = !S.agg && speed > 1.5;+ const g = blur ? bctx : ctx;+ if (blur){ bctx.setTransform(DPR,0,0,DPR,0,0); bctx.fillStyle = "#0f1012"; bctx.fillRect(0, 0, W, bodyH); }+ else { ctx.fillStyle = "#0f1012"; ctx.fillRect(0, HH, W, bodyH); }+ if (!blur){ ctx.save(); ctx.beginPath(); ctx.rect(0, HH, W, bodyH); ctx.clip(); ctx.translate(0, HH); }+ drawRows(g, list, { fast: blur });+ if (aggInfo && aggInfo.pg > 0) drawPivot(g, S.agg.P, S.agg.L, aggInfo.t - 1.05);+ if (!blur) ctx.restore();+ if (blur){+ // vertical motion smear: average of n shifted copies, length tied to velocity+ const L = Math.min(110, speed*RH*0.55), n = speed > 40 ? 7 : 5;+ ctx.save(); ctx.beginPath(); ctx.rect(0, HH, W, bodyH); ctx.clip();+ ctx.setTransform(1,0,0,1,0,0);+ for (let k=0;k<n;k++){ ctx.globalAlpha = 1/(k+1); ctx.drawImage(buf, 0, Math.round((HH + (k/(n-1) - 0.5)*L)*DPR)); }+ ctx.globalAlpha = 1; ctx.restore(); ctx.setTransform(DPR,0,0,DPR,0,0);+ // keep the gutter separator crisp+ ctx.fillStyle = "#1c1e22"; ctx.fillRect(GW - 1, HH, 1, bodyH);+ }+ const hdrA = aggInfo ? 1 - clamp01(aggInfo.pg*1.6) : 1;+ ctx.fillStyle = "#0f1012"; ctx.fillRect(0, 0, W, HH);+ drawHeader(ctx, hdrA);+ if (aggInfo && hdrA < 1){ // pivot heading area replaces the column header+ ctx.save(); ctx.globalAlpha = 1 - hdrA; ctx.fillStyle = "#222429"; ctx.fillRect(0, HH - 1, W, 1); ctx.restore(); }+ drawRail();+ updateCounter(aggInfo);+}++// ---------- counter / footer ----------+const cnum = $("cnum"), cof = $("cof"), clbl = $("clbl"), cspeed = $("cspeed");+let lastNum = "", lastSpeed = "";+function updateCounter(ai){+ let num, lbl = "row", of = "of 12,000,000", sp;+ if (ai){+ const P = S.agg.P; const v = N - (N - P.grand.n)*ai.pf;+ num = fmtInt(v); lbl = ai.pg > 0.3 ? "matching rows · 48 groups" : "matching rows"; of = "of 12,000,000";+ sp = "where status = 'delivered'";+ } else {+ num = fmtInt(Math.min(N, Math.floor(S.pos + 0.5) + 1));+ const rps = Math.abs(S.speedRows)*60;+ sp = rps < 1 ? "at rest" : (S.speedRows > 0 ? "▼ " : "▲ ") + (rps >= 1e6 ? (rps/1e6).toFixed(2) + "M" : rps >= 1e3 ? (rps/1e3).toFixed(1) + "k" : Math.round(rps)) + " rows/s";+ }+ if (num !== lastNum){ cnum.textContent = num; lastNum = num; }+ if (sp !== lastSpeed){ cspeed.textContent = sp; lastSpeed = sp; }+ if (clbl.textContent !== lbl) clbl.textContent = lbl;+ if (cof.textContent !== of) cof.textContent = of;+}+function updateFooter(){+ const el = $("scan");+ if (!SCAN.done) el.innerHTML = `profiling all rows in ${SCAN.workers || "main-thread"} workers… <em>${Math.round(SCAN.progress*100)}%</em>`;+ else el.innerHTML = `full scan <em>${fmtInt(N)}</em> rows in <em>${(SCAN.ms/1000).toFixed(2)} s</em> · ${SCAN.workers ? SCAN.workers + " workers" : "main thread"} · measured in this page`;+}++// ---------- frame loop ----------+function frame(t){+ if (S.glide) S.glide(t);+ else if (!S.agg){ // wheel smoothing+ const d = S.target - S.pos; if (Math.abs(d) > 0.002){ S.pos += Math.abs(d) < 0.02 ? d : d*0.22; dirty = true; }+ }+ if (SCAN.done && PROFILE_T < 1){ if (!profT0) profT0 = t; PROFILE_T = REDUCED ? 1 : easeOut(clamp01((t - profT0)/900)); dirty = true; }+ const v = S.pos - S.prevPos; S.prevPos = S.pos;+ S.speedRows = v; if (Math.abs(v) > 0.001) dirty = true;+ if (S.agg && !S.agg.done){ dirty = true; if ((performance.now() - S.agg.t0) > 4200) S.agg.done = true; }+ if (dirty){ dirty = false; render(); }+ requestAnimationFrame(frame);+}++// ---------- glides ----------+function glideTo(to, totalS){+ return new Promise((ok) => {+ S.target = S.pos; S.focus = -1;+ const from = S.pos, D = to - from;+ if (REDUCED || Math.abs(D) < 1){ S.pos = S.target = S.prevPos = to; S.focus = to; dirty = true; ok(); return; }+ // velocity profile: smoothstep ramp (Ta), cruise (Tc), exponential settle (Td) that lands exactly on `to`.+ const T = totalS, Ta = T*0.26, Tc = T*0.2, Td = T - Ta - Tc, eps = 0.35, AD = Math.abs(D);+ let lo = 0.5, hi = 40, k = 5, V = 0, R0 = 0;+ for (let it=0; it<60; it++){ k = (lo+hi)/2; V = AD/(Ta/2 + Tc + 1/k); R0 = V/k; if (Math.log(Math.max(1.0001, R0/eps)) - k*Td > 0) lo = k; else hi = k; }+ if (R0 < 2){ k = 3/Td; V = AD/(Ta/2 + Tc + 1/k); R0 = V/k; }+ const eT = Math.exp(-k*Td), sgn = Math.sign(D);+ const posAt = (s) => {+ if (s < Ta){ const u = s/Ta; return V*Ta*(u*u*u - 0.5*u*u*u*u); } // ∫ smoothstep-ish ramp: v = V(3u²-2u³)+ const dA = V*Ta*0.5;+ if (s < Ta + Tc) return dA + V*(s - Ta);+ const tau = Math.min(Td, s - Ta - Tc); const R = R0*(Math.exp(-k*tau) - eT)/(1 - eT);+ return AD - R;+ };+ // correct ramp integral so distance matches exactly+ const scale = AD / (V*Ta*0.5 + V*Tc + R0);+ const t0 = performance.now();+ S.glide = (now) => {+ const s = (now - t0)/1000;+ if (s >= T){ S.pos = S.target = to; S.glide = null; S.focus = to; dirty = true; setTimeout(ok, 260); return; }+ let p = posAt(s); if (s >= Ta + Tc) p = AD - (AD - p); else p *= scale;+ S.pos = from + sgn*Math.min(AD, p); S.target = S.pos; dirty = true;+ };+ });+}+function setChips(list){+ const el = $("chips"); el.innerHTML = "";+ for (const c of list){+ const s = document.createElement("span"); s.className = "chip"; s.innerHTML = c.html + '<span class="x" title="Remove">×</span>';+ s.querySelector(".x").addEventListener("click", () => clearAgg());+ el.appendChild(s);+ }+}+async function aggregate(){+ await scanReady;+ if (S.glide){ S.glide = null; }+ S.target = S.pos; S.speedRows = 0;+ setChips([{ html: '<span class="kw" style="color:#9fb35c">WHERE</span> status = <span class="str">\'delivered\'</span>' }]);+ S.agg = buildAgg(); dirty = true;+ $("ordkw").style.display = $("ordcol").style.display = $("orddir").style.display = "none";+ if (REDUCED){ S.agg.t0 -= 10000; }+ await new Promise((ok) => setTimeout(ok, REDUCED ? 30 : 1000));+ const el = $("chips"); const s = document.createElement("span"); s.className = "chip";+ s.innerHTML = '<span class="kw" style="color:#9fb35c">GROUP BY</span> region, category<span class="x" title="Remove">×</span>'; s.querySelector(".x").addEventListener("click", () => clearAgg());+ el.appendChild(s);+ await new Promise((ok) => setTimeout(ok, REDUCED ? 30 : 3200));+}+function clearAgg(){+ S.agg = null; $("chips").innerHTML = "";+ $("ordkw").style.display = $("ordcol").style.display = $("orddir").style.display = "";+ dirty = true;+}+// ---------- input ----------+function syncOrder(){ $("ordcol").textContent = S.sortCol; $("orddir").textContent = S.dir > 0 ? "ASC" : "DESC"; }+grid.addEventListener("wheel", (e) => {+ e.preventDefault(); if (S.glide || S.agg) return;+ let dy = e.deltaY * (e.deltaMode === 1 ? RH*3 : e.deltaMode === 2 ? bodyH : 1);+ let rows = dy/RH; if (e.shiftKey || e.altKey) rows *= 2500;+ S.target = Math.max(0, Math.min(maxPos(), S.target + rows));+}, { passive:false });+let sorting = false;+grid.addEventListener("click", async (e) => {+ const r = grid.getBoundingClientRect(), x = e.clientX - r.left, y = e.clientY - r.top;+ if (S.agg) return;+ if (y < HH){+ const c = visCols.find((c) => x >= c.x && x < c.x + c.cw); if (!c || !c.sort || sorting) return;+ const same = S.sortCol === c.key;+ if (c.sort === "index"){ S.perm = null; S.dir = same ? -S.dir : 1; S.sortCol = c.key; $("sortnote").textContent = ""; }+ else if (same){ S.dir = -S.dir; }+ else {+ sorting = true; $("sortnote").textContent = `sorting ${fmtInt(N)} rows by ${c.key}…`;+ try { const res = await sortBy(c); S.perm = res.perm; S.dir = 1; S.sortCol = c.key;+ $("sortnote").textContent = `sorted ${fmtInt(N)} rows by ${c.key} in ${(res.ms/1000).toFixed(2)} s · ${res.workers} workers`; }+ catch (err) { $("sortnote").textContent = "sort needs workers"; }+ sorting = false;+ }+ syncOrder(); S.focus = -1; dirty = true; railStatic = railStatic; return;+ }+ const row = Math.floor(S.pos + (y - HH)/RH); if (row >= 0 && row < N){ S.focus = row === S.focus ? -1 : row; dirty = true; }+});+grid.addEventListener("mousemove", (e) => {+ const r = grid.getBoundingClientRect(), y = e.clientY - r.top;+ const row = y < HH ? -1 : Math.floor(S.pos + (y - HH)/RH); if (row !== S.hover){ S.hover = row; dirty = true; }+});+grid.addEventListener("mouseleave", () => { S.hover = -1; dirty = true; });+let railDrag = false;+function railTo(e){+ const r = rail.getBoundingClientRect(), y = e.clientY - r.top; const rs = railStatic || buildRailStatic();+ const span = Math.floor(bodyH/RH);+ const p = Math.max(0, Math.min(maxPos(), (y - rs.top)/rs.h*N - span/2));+ S.pos = S.target = p; dirty = true;+}+rail.addEventListener("pointerdown", (e) => { if (S.glide) return; if (S.agg) clearAgg(); railDrag = true; rail.setPointerCapture(e.pointerId); S.focus = -1; railTo(e); });+rail.addEventListener("pointermove", (e) => { if (railDrag) railTo(e); });+rail.addEventListener("pointerup", () => { railDrag = false; });+$("btnGroup").addEventListener("click", () => { if (!S.agg) aggregate(); });+$("btnFilter").addEventListener("click", () => { if (!S.agg) aggregate(); });+addEventListener("keydown", (e) => {+ if (e.key === "Escape" && S.agg) clearAgg();+ if (S.agg || S.glide) return;+ const page = Math.floor(bodyH/RH) - 1;+ if (e.key === "PageDown") S.target = Math.min(maxPos(), S.target + page);+ if (e.key === "PageUp") S.target = Math.max(0, S.target - page);+ if (e.key === "ArrowDown") S.target = Math.min(maxPos(), S.target + 1);+ if (e.key === "ArrowUp") S.target = Math.max(0, S.target - 1);+ if (e.key === "End") glideTo(maxPos(), 2.4);+ if (e.key === "Home") glideTo(0, 2.4);+});+let rz; addEventListener("resize", () => { cancelAnimationFrame(rz); rz = requestAnimationFrame(() => { layout(); makePills(); }); });++// ---------- boot ----------+(async () => {+ await document.fonts.ready;+ layout(); makePills(); updateFooter();+ // A card picture is 880 px wide and never gets input: the 12M-row scan waits there for a first sign of a person.+ const FIRST = ["pointermove","pointerdown","keydown","wheel","resize"];+ const scanOnce = () => { for (const type of FIRST) removeEventListener(type, scanOnce, true); runScan(); };+ if (innerWidth > 900) runScan(); else for (const type of FIRST) addEventListener(type, scanOnce, true);+ render();+ requestAnimationFrame(() => { document.documentElement.dataset.ready = "1"; });+ requestAnimationFrame(frame);+})();+})();+</script>+</body>+</html>diff --git a/server/local-apps/starters/cohorts.html b/server/local-apps/starters/cohorts.htmlnew file mode 100644index 0000000000..b0dec889d8--- /dev/null+++ b/server/local-apps/starters/cohorts.html@@ -0,0 +1,240 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<title>Cohorts · Q3 activation review</title>+<style>+:root{--bg:#fff;--rail:#fafafb;--ink:#111318;--ink2:#4b5160;--ink3:#8a90a0;--line:#eceef2;--line2:#e2e5eb;--acc:#5b5bd6;--acc2:#e9e9fb;--cmp:#b4b0a6;+ --ui:system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;--mono:ui-monospace,"SF Mono",Menlo,Consolas,monospace}+*{box-sizing:border-box}html,body{margin:0;height:100%;background:var(--bg);color:var(--ink);overflow:hidden}+body{font:14px/1.5 var(--ui);font-feature-settings:"tnum","cv11";-webkit-font-smoothing:antialiased;display:grid;grid-template-columns:clamp(220px,13.5vw,260px) 1fr}+.rail{background:var(--rail);border-right:1px solid var(--line);padding:22px 18px;display:flex;flex-direction:column;gap:22px}+.logo{display:flex;align-items:center;gap:10px;font:600 16px var(--ui);letter-spacing:-.01em}+.logo svg{width:22px;height:22px}+.rl h4{margin:0 0 8px;font:500 11px var(--mono);letter-spacing:.04em;color:var(--ink3);text-transform:uppercase}+.rl a{display:flex;justify-content:space-between;align-items:center;padding:6px 8px;margin:0 -8px;border-radius:6px;color:var(--ink2);text-decoration:none;font-size:13.5px;cursor:pointer}+.rl a.on{background:#fff;color:var(--ink);box-shadow:0 0 0 1px var(--line2)}.rl a small{font:11.5px var(--mono);color:var(--ink3)}+.rl a i{width:7px;height:7px;border-radius:50%;background:var(--acc);margin-right:8px;flex:none}+.rl .seg{justify-content:flex-start}.rl .seg span{flex:1}+.rail .note{margin-top:auto;font-size:12px;color:var(--ink3);line-height:1.5}.rail .note b{color:var(--ink2);font-weight:500}+main{padding:26px clamp(28px,2.6vw,48px) 0;display:flex;flex-direction:column;min-width:0;min-height:0}+.crumb{font:12.5px var(--mono);color:var(--ink3)}+h1{margin:6px 0 2px;font:600 clamp(26px,1.75vw,32px)/1.2 var(--ui);letter-spacing:-.022em}+.meta{font-size:13.5px;color:var(--ink3)}.meta b{color:var(--ink2);font-weight:500}+.sample{display:inline-block;font:500 10.5px var(--mono);letter-spacing:.06em;color:var(--ink2);border:1px solid var(--line2);border-radius:4px;padding:2px 6px;margin-left:8px;text-transform:uppercase;vertical-align:1px}+.segbar{display:flex;align-items:center;gap:22px;margin:18px 0 14px;padding:10px 14px;border:1px solid var(--line2);border-radius:10px}+.segbar .lab{font:500 11px var(--mono);color:var(--ink3);text-transform:uppercase;letter-spacing:.04em}+.grp{display:flex;align-items:center;gap:4px}.grp>span{font-size:12.5px;color:var(--ink3);margin-right:6px}+.chip{border:1px solid var(--line2);background:#fff;border-radius:999px;padding:4px 11px;font:500 12.5px var(--ui);color:var(--ink2);cursor:pointer;transition:background .25s,color .25s,border-color .25s,transform .15s}+.chip.on{background:var(--acc);border-color:var(--acc);color:#fff}.chip.press{transform:scale(.92)}+.segbar .count{margin-left:auto;text-align:right;font-size:13px;color:var(--ink2)}.segbar .count b{font:600 16px var(--ui);color:var(--ink)}+.btn{border:1px solid var(--line2);background:#fff;border-radius:7px;padding:6px 11px;font:500 12.5px var(--ui);color:var(--ink);cursor:pointer}+.grid{flex:1;min-height:0;display:grid;grid-template-columns:1.12fr 1fr;grid-template-rows:1fr auto;gap:0 40px}+.cellx{min-height:0;display:flex;flex-direction:column;padding:14px 0 16px;border-top:1px solid var(--line)}+.cap{display:flex;align-items:baseline;gap:10px;font:11.5px var(--mono);color:var(--ink3)}.cap b{color:var(--acc);font-weight:500}+.cellx h3{margin:4px 0 2px;font:600 16px var(--ui);letter-spacing:-.01em}+.prose{margin:0 0 8px;font-size:14px;color:var(--ink2);max-width:760px}.prose b{color:var(--ink);font-weight:600}.prose em{font-style:normal;color:var(--acc);font-weight:600}+.cv{flex:1;min-height:0;position:relative}.cv canvas{position:absolute;inset:0;width:100%;height:100%}+.col{display:flex;flex-direction:column;min-height:0}+.funnel{display:flex;flex-direction:column;gap:9px;margin-top:6px}+.fs{display:grid;grid-template-columns:150px 1fr 120px;align-items:center;gap:12px}+.fs .nm{font-size:13.5px;color:var(--ink)}.fs .nm small{display:block;font:11px var(--mono);color:var(--ink3)}+.fs .bar{position:relative;height:28px;background:#f6f6f8;border-radius:5px;overflow:hidden}.fs .bar i{position:absolute;left:0;top:0;bottom:0;background:var(--acc);border-radius:5px}+.fs .bar u{position:absolute;left:0;top:0;bottom:0;background:var(--acc2);border-radius:5px;text-decoration:none}+.fs .v{text-align:right;font:500 14px var(--ui)}.fs .v small{display:block;font:11.5px var(--mono);color:#c2410c}+.fs .v small.ok{color:var(--ink3)}+.tip{position:absolute;pointer-events:none;background:var(--ink);color:#fff;font:12px/1.45 var(--ui);padding:8px 10px;border-radius:7px;white-space:nowrap;transform:translate(-50%,-100%);opacity:0;transition:opacity .2s}+.tip b{font-weight:600}+.chip{white-space:nowrap}.segbar .count{white-space:nowrap}.btn{white-space:nowrap}+@media (max-width:1600px){.chip{padding:3px 8px;font-size:11.5px}.segbar{gap:12px}.grp>span,.segbar .lab{display:none}.segbar .count{font-size:12px}.segbar .count b{font-size:14px}.grid{gap:0 28px}}+@media (max-height:950px){#p2,.fs .nm small{display:none}.fs{grid-template-columns:140px 1fr 170px}.fs .v{white-space:nowrap}.fs .v small{display:inline;margin-left:6px}.cellx{padding:10px 0 10px}h1{font-size:24px}.segbar{margin:12px 0 8px;padding:8px 12px}.prose{font-size:13px}.fs .bar{height:22px}.funnel{gap:6px}}+</style>+</head>+<body>+<aside class="rail">+ <div class="logo"><svg viewBox="0 0 22 22"><rect x="1" y="1" width="20" height="20" rx="6" fill="#5b5bd6"/><path d="M6 15V7M10 15v-5M14 15v-3M18 15v-1" stroke="#fff" stroke-width="2" stroke-linecap="round"/></svg>Cohorts</div>+ <div class="rl"><h4>Notebooks</h4><a class="on">Q3 activation review <small>5 cells</small></a><a>Pricing page test <small>8</small></a><a>Mobile onboarding v2 <small>6</small></a><a>Churn reasons, Oct <small>4</small></a></div>+ <div class="rl"><h4>Saved segments</h4><div id="saved"></div></div>+ <div class="rl"><h4>In this notebook</h4><a>1 · Retention by cohort</a><a>2 · Retention curves</a><a>3 · Activation funnel</a><a>4 · Session length</a></div>+ <p class="note"><b>Sample data.</b> 60,000 invented users of an invented product, generated in this page from one seed. Every number is computed from them as you change the segment.</p>+</aside>+<main>+ <div class="crumb">notebooks / q3-activation-review</div>+ <h1>Did the new onboarding keep people around?</h1>+ <div class="meta" id="meta"></div>+ <div class="segbar">+ <span class="lab">Segment</span>+ <div class="grp" data-k="plan"><span>Plan</span></div>+ <div class="grp" data-k="region"><span>Region</span></div>+ <div class="grp" data-k="device"><span>Device</span></div>+ <div class="count" id="count"></div>+ <button class="btn" id="saveSeg">Save segment</button>+ </div>+ <div class="grid">+ <section class="cellx" style="grid-row:1/3">+ <div class="cap"><b>[1]</b> retention_by_cohort · 20 weekly cohorts × 12 weeks</div>+ <h3>Retention by signup week</h3>+ <p class="prose" id="p1"></p>+ <div class="cv" id="heatBox"><canvas id="heat"></canvas><div class="tip" id="tip"></div></div>+ </section>+ <div class="col">+ <section class="cellx" style="flex:1.1">+ <div class="cap"><b>[2]</b> retention_curves · share of the cohort active in week n</div>+ <h3>Before and after the new onboarding</h3>+ <p class="prose" id="p2"></p>+ <div class="cv"><canvas id="curves"></canvas></div>+ </section>+ <section class="cellx" style="flex:1">+ <div class="cap"><b>[3]</b> activation_funnel · first 14 days</div>+ <h3>Where new people stop</h3>+ <div class="funnel" id="funnel"></div>+ </section>+ </div>+ <section class="cellx">+ <div class="cap"><b>[4]</b> session_length · log scale · p50 / p90 / p99</div>+ <h3>How long a session lasts</h3>+ <div class="cv" style="min-height:150px"><canvas id="hist"></canvas></div>+ </section>+ </div>+</main>+<script>+"use strict";+function mulberry32(a){return function(){a|=0;a=a+0x6D2B79F5|0;let t=Math.imul(a^a>>>15,1|a);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296}}+const rnd = mulberry32(915), REDUCED = matchMedia("(prefers-reduced-motion: reduce)").matches;+const $ = (id) => document.getElementById(id);+const N = 60000, C = 20, K = 12, CHANGE = 9; // cohorts, weeks, first cohort with the new onboarding+const DIM = { plan: ["Free", "Plus", "Pro"], region: ["N. America", "Europe", "Asia-Pac", "LatAm"], device: ["Desktop", "Mobile", "Tablet"] };+const W8 = { plan: [.62, .25, .13], region: [.34, .3, .24, .12], device: [.52, .38, .1] };+const pickW = (w) => { let r = rnd(), i = 0; while ((r -= w[i]) > 0 && i < w.length - 1) i++; return i; };+const gauss = () => { let u = 0, v = 0; while (!u) u = rnd(); while (!v) v = rnd(); return Math.sqrt(-2 * Math.log(u)) * Math.cos(6.283 * v); };+// Users: cohort, plan, region, device, a 12-week activity mask, funnel steps, a log-session-length histogram bin per session.+const U = { c: new Uint8Array(N), plan: new Uint8Array(N), region: new Uint8Array(N), device: new Uint8Array(N), mask: new Uint16Array(N), steps: new Uint8Array(N) };+const HB = 48, SESS = new Uint8Array(N * 4); // four sessions per user, binned on log2 seconds+const binOf = (sec) => Math.max(0, Math.min(HB - 1, Math.floor((Math.log2(sec) - 3) * 4))); // 8 s … ~ 8 h+for (let i = 0; i < N; i++) {+ const c = Math.min(C - 1, Math.floor(Math.pow(rnd(), .85) * C)), plan = pickW(W8.plan), region = pickW(W8.region), device = pickW(W8.device);+ U.c[i] = C - 1 - c; U.plan[i] = plan; U.region[i] = region; U.device[i] = device;+ const post = U.c[i] >= CHANGE, eng = Math.exp(.35 * gauss());+ const base = (.36 + .1 * plan + (device === 0 ? .05 : device === 1 ? -.06 : -.02) + (region === 1 ? .03 : region === 3 ? -.04 : 0)) * eng;+ let mask = 0, alive = 1;+ for (let k = 0; k < K; k++) { if (U.c[i] + k >= C) break; const p = k === 0 ? 1 : Math.min(.97, base * (post ? 1.22 : 1) * Math.pow(k + 1, post ? -.33 : -.43) * 1.25);+ alive = rnd() < p ? 1 : 0; if (alive) mask |= 1 << k; }+ U.mask[i] = mask;+ // Funnel: signed up → created a project → invited a teammate → active 3 days in week 1 → started paying.+ let s = 1; const pf = [.78 + (post ? .06 : 0), .46 + .1 * plan - (device === 1 ? .08 : 0), .55 + (post ? .07 : 0), plan > 0 ? .62 : .07];+ for (const q of pf) { if (rnd() < q * Math.min(1.25, eng)) s++; else break; } U.steps[i] = s;+ const med = 240 * (device === 1 ? .55 : device === 2 ? .8 : 1.2) * (1 + .25 * plan) * eng;+ for (let j = 0; j < 4; j++) SESS[i * 4 + j] = binOf(med * Math.exp(1.05 * gauss()));+}+const wk0 = Date.UTC(2026, 6, 1); const wkLabel = (c) => new Date(wk0 + c * 7 * 864e5).toLocaleDateString("en-GB", { day: "numeric", month: "short", timeZone: "UTC" });++// ——————————— aggregates for a segment ———————————+function aggregate(seg){+ const size = new Float64Array(C), act = new Float64Array(C * K), fun = new Float64Array(6), hist = new Float64Array(HB); let n = 0;+ for (let i = 0; i < N; i++) {+ if ((seg.plan >= 0 && U.plan[i] !== seg.plan) || (seg.region >= 0 && U.region[i] !== seg.region) || (seg.device >= 0 && U.device[i] !== seg.device)) continue;+ n++; const c = U.c[i], m = U.mask[i]; size[c]++; for (let k = 0; k < K; k++) if (m >> k & 1) act[c * K + k]++;+ for (let s = 1; s <= U.steps[i]; s++) fun[s]++; for (let j = 0; j < 4; j++) hist[SESS[i * 4 + j]]++;+ }+ const ret = new Float64Array(C * K).fill(NaN); for (let c = 0; c < C; c++) for (let k = 0; k < K && c + k < C; k++) ret[c * K + k] = size[c] ? act[c * K + k] / size[c] : 0;+ const curve = (from, to) => { const out = []; for (let k = 0; k < K; k++) { let a = 0, s = 0; for (let c = from; c < to; c++) if (c + k < C) { a += act[c * K + k]; s += size[c]; } out.push(s ? a / s : NaN); } return out; };+ const pct = (q) => { const tot = hist.reduce((a, b) => a + b, 0); let acc = 0; for (let b = 0; b < HB; b++) { acc += hist[b]; if (acc >= q * tot) return Math.pow(2, b / 4 + 3 + .125); } return 0; };+ return { n, size, ret, before: curve(0, CHANGE), after: curve(CHANGE, C), fun: [...fun.slice(1)], hist, p50: pct(.5), p90: pct(.9), p99: pct(.99) };+}+const ALL = aggregate({ plan: -1, region: -1, device: -1 });+let seg = { plan: -1, region: -1, device: -1 }, A = ALL, shown = ALL, hl = -1, hlT = 0;+const lerp = (a, b, t) => a + (b - a) * t;+function mix(a, b, t){ const m = (x, y) => (Number.isNaN(x) || Number.isNaN(y) ? y : lerp(x, y, t));+ return { n: lerp(a.n, b.n, t), size: b.size, ret: b.ret.map((v, i) => m(a.ret[i], v)), before: b.before.map((v, i) => m(a.before[i], v)), after: b.after.map((v, i) => m(a.after[i], v)),+ fun: b.fun.map((v, i) => lerp(a.fun[i], v, t)), hist: b.hist.map((v, i) => lerp(a.hist[i] / a.n, v / b.n, t) * lerp(a.n, b.n, t)), p50: lerp(a.p50, b.p50, t), p90: lerp(a.p90, b.p90, t), p99: lerp(a.p99, b.p99, t) }; }++// ——————————— drawing ———————————+const DPR = () => devicePixelRatio || 1;+function ctxOf(id){ const c = $(id), r = c.getBoundingClientRect(), d = DPR(); if (c.width !== Math.round(r.width * d) || c.height !== Math.round(r.height * d)) { c.width = Math.round(r.width * d); c.height = Math.round(r.height * d); } const g = c.getContext("2d"); g.setTransform(d, 0, 0, d, 0, 0); g.clearRect(0, 0, r.width, r.height); return [g, r.width, r.height]; }+const RAMP = ["#f4f4fd", "#e3e3fa", "#c9c8f4", "#a6a4ec", "#8482e2", "#6865d8", "#4f4bc4", "#3b36a3", "#2b2780"];+function rampColor(v){ const x = Math.max(0, Math.min(.999, v / .62)) * (RAMP.length - 1), i = Math.floor(x), f = x - i; const a = RAMP[i], b = RAMP[Math.min(RAMP.length - 1, i + 1)];+ const h = (s, o) => parseInt(s.slice(o, o + 2), 16); return `rgb(${Math.round(lerp(h(a, 1), h(b, 1), f))},${Math.round(lerp(h(a, 3), h(b, 3), f))},${Math.round(lerp(h(a, 5), h(b, 5), f))})`; }+let heatGeom = null;+function drawHeat(S){+ const [g, w, h] = ctxOf("heat"); const L = 118, T = 26, cw = (w - L - 10) / K, ch = Math.min(34, (h - T - 8) / C); heatGeom = { L, T, cw, ch };+ g.font = "500 11px ui-monospace, Menlo, Consolas, monospace"; g.fillStyle = "#8a90a0"; g.textAlign = "center";+ for (let k = 0; k < K; k++) g.fillText(k === 0 ? "wk 0" : String(k), L + k * cw + cw / 2, 14);+ for (let c = 0; c < C; c++) { const y = T + c * ch, dim = hl >= 0 && c !== hl ? .62 * hlT : 0;+ g.textAlign = "left"; g.font = "13px system-ui, -apple-system, sans-serif"; g.fillStyle = hl === c ? "#111318" : "#4b5160"; g.fillText(wkLabel(c), 0, y + ch / 2 + 4);+ g.font = "11px ui-monospace, Menlo, Consolas, monospace"; g.fillStyle = "#a0a5b3"; g.textAlign = "right"; g.fillText(Math.round(S.size[c]).toLocaleString("en-US"), L - 12, y + ch / 2 + 4);+ for (let k = 0; k < K; k++) { const v = S.ret[c * K + k]; if (Number.isNaN(v)) continue; const x = L + k * cw;+ g.globalAlpha = 1 - dim; g.fillStyle = k === 0 ? "#efeff3" : rampColor(v); g.beginPath(); g.roundRect(x + 1.5, y + 1.5, cw - 3, ch - 3, 3); g.fill();+ if (k > 0 && cw > 42) { g.fillStyle = v > .34 ? "#fff" : "#3b3f4a"; g.textAlign = "center"; g.font = "500 11.5px system-ui, -apple-system, sans-serif"; g.fillText(`${Math.round(v * 100)}`, x + cw / 2, y + ch / 2 + 4); } }+ g.globalAlpha = 1; }+ // the change, as a rule between cohorts+ const yc = T + CHANGE * ch; g.strokeStyle = "#111318"; g.lineWidth = 1.2; g.setLineDash([4, 3]); g.beginPath(); g.moveTo(0, yc); g.lineTo(w - 6, yc); g.stroke(); g.setLineDash([]);+ g.fillStyle = "#111318"; g.font = "600 11px system-ui, -apple-system, sans-serif"; g.textAlign = "right";+ const lab = "new onboarding ships"; const tw = g.measureText(lab).width; g.fillStyle = "#fff"; g.fillRect(w - 18 - tw - 8, yc - 9, tw + 16, 18); g.fillStyle = "#111318"; g.fillText(lab, w - 18, yc + 4);+ if (hl >= 0) { const y = T + hl * ch; g.globalAlpha = hlT; g.strokeStyle = "#111318"; g.lineWidth = 2; g.beginPath(); g.roundRect(L - 1, y, (C - hl > K ? K : C - hl) * cw + 2, ch, 5); g.stroke(); g.globalAlpha = 1; }+}+function drawCurves(S){+ const [g, w, h] = ctxOf("curves"); const L = 40, B = h - 24, T = 10, X = (k) => L + k / (K - 1) * (w - L - 90), Y = (v) => B - v / .8 * (B - T);+ g.font = "11px ui-monospace, Menlo, Consolas, monospace"; g.fillStyle = "#a0a5b3"; g.textAlign = "right"; g.strokeStyle = "#eceef2"; g.lineWidth = 1;+ for (const v of [0, .2, .4, .6, .8]) { g.beginPath(); g.moveTo(L, Y(v)); g.lineTo(w - 90, Y(v)); g.stroke(); g.fillText(`${v * 100}%`, L - 8, Y(v) + 4); }+ g.textAlign = "center"; for (let k = 0; k < K; k += 2) g.fillText(`wk ${k}`, X(k), h - 6);+ for (let c = 0; c < C; c++) { g.strokeStyle = hl === c ? "rgba(17,19,24,.9)" : c >= CHANGE ? "rgba(91,91,214,.14)" : "rgba(160,155,145,.2)"; g.lineWidth = hl === c ? 2 : 1; g.beginPath(); let on = false;+ for (let k = 1; k < K && c + k < C; k++) { const v = S.ret[c * K + k]; if (Number.isNaN(v)) continue; on ? g.lineTo(X(k), Y(v)) : g.moveTo(X(k), Y(v)); on = true; } g.stroke(); }+ const line = (arr, col, wd, name) => { g.strokeStyle = col; g.lineWidth = wd; g.beginPath(); let last = null; arr.forEach((v, k) => { if (k === 0 || Number.isNaN(v)) return; k === 1 ? g.moveTo(X(k), Y(v)) : g.lineTo(X(k), Y(v)); last = [X(k), Y(v), v]; }); g.stroke();+ if (last) { g.fillStyle = col; g.beginPath(); g.arc(last[0], last[1], 3.5, 0, 6.283); g.fill(); g.font = "600 12px system-ui, -apple-system, sans-serif"; g.textAlign = "left"; g.fillText(`${name} ${Math.round(last[2] * 100)}%`, last[0] + 8, last[1] + 4); } };+ line(S.before, "#a39e93", 2.2, "before"); line(S.after, "#5b5bd6", 2.8, "after");+}+function drawFunnel(S){+ const names = [["Signed up", "account created"], ["Created a project", "within 3 days"], ["Invited a teammate", "within 7 days"], ["Activated", "3 active days, week 1"], ["Started paying", "within 14 days"]];+ if (!$("funnel").children.length) $("funnel").innerHTML = names.map(([a, b]) => `<div class="fs"><span class="nm">${a}<small>${b}</small></span><span class="bar"><u></u><i></i></span><span class="v"></span></div>`).join("");+ [...$("funnel").children].forEach((row, i) => { const v = S.fun[i] / S.fun[0], prev = i ? S.fun[i - 1] / S.fun[0] : 1, allv = ALL.fun[i] / ALL.fun[0];+ row.querySelector("i").style.width = `${v * 100}%`; row.querySelector("u").style.width = `${allv * 100}%`;+ row.querySelector(".v").innerHTML = `${(v * 100).toFixed(1)}%${i ? `<small class="${1 - v / prev > .4 ? "" : "ok"}">−${Math.round((1 - v / prev) * 100)}% from step ${i}</small>` : `<small class="ok">${Math.round(S.fun[0]).toLocaleString("en-US")} people</small>`}`; });+}+function drawHist(S){+ const [g, w, h] = ctxOf("hist"); const L = 8, B = h - 22, T = 40, bw = (w - L * 2) / HB, mx = Math.max(...S.hist);+ for (let b = 0; b < HB; b++) { const v = S.hist[b] / mx, x = L + b * bw; g.fillStyle = "#c9c8f4"; g.fillRect(x + 1, B - v * (B - T), bw - 2, v * (B - T)); }+ const allMx = Math.max(...ALL.hist); g.strokeStyle = "#a39e93"; g.lineWidth = 1.4; g.setLineDash([3, 3]); g.beginPath();+ for (let b = 0; b < HB; b++) { const y = B - (ALL.hist[b] / allMx) * (B - T); b ? g.lineTo(L + b * bw + bw / 2, y) : g.moveTo(L + bw / 2, y); } g.stroke(); g.setLineDash([]);+ const xs = (sec) => L + (Math.log2(sec) - 3) * 4 * bw;+ g.font = "11px ui-monospace, Menlo, Consolas, monospace"; g.fillStyle = "#a0a5b3"; g.textAlign = "center";+ for (const [s, l] of [[10, "10 s"], [60, "1 min"], [300, "5 min"], [1800, "30 min"], [7200, "2 h"]]) g.fillText(l, xs(s), h - 4);+ const fmt = (s) => s < 60 ? `${Math.round(s)} s` : s < 3600 ? `${(s / 60).toFixed(s < 600 ? 1 : 0)} min` : `${(s / 3600).toFixed(1)} h`;+ for (const [q, v, col] of [["p50", S.p50, "#111318"], ["p90", S.p90, "#5b5bd6"], ["p99", S.p99, "#5b5bd6"]]) { const x = xs(v); g.strokeStyle = col; g.lineWidth = 1.5; g.beginPath(); g.moveTo(x, T - 24); g.lineTo(x, B); g.stroke();+ g.fillStyle = col; g.textAlign = "left"; g.font = "600 12px system-ui, -apple-system, sans-serif"; g.fillText(`${q} ${fmt(v)}`, x + 5, T - 12); }+ g.fillStyle = "#a39e93"; g.textAlign = "right"; g.font = "11.5px system-ui, -apple-system, sans-serif"; g.fillText("- - all users, same scale", w - 8, 12);+}+function prose(S){+ const wk4 = (arr) => arr[4], b = wk4(S.before), a = wk4(S.after);+ $("p1").innerHTML = `Each row is the people who signed up that week; each square, the share still active <i>n</i> weeks later. Below the dashed line, week-4 retention is <em>${Math.round(a * 100)}%</em> against <b>${Math.round(b * 100)}%</b> before the change.`;+ $("p2").innerHTML = `Averaged over cohorts, the new onboarding holds <em>${a > b ? "+" : ""}${Math.round((a - b) * 100)} points</em> more people at week 4${S.n < N ? " in this segment" : ""}; the gap stays open through week ${Math.min(...[8, 9, 10].filter((k) => !Number.isNaN(S.after[k])))}.`;+ $("count").innerHTML = `<b>${Math.round(S.n).toLocaleString("en-US")}</b> people · ${Math.round(S.n / N * 100)}% of all`;+}+function render(S){ drawHeat(S); drawCurves(S); drawFunnel(S); drawHist(S); prose(S); }++// ——————————— segment builder ———————————+function chips(){ for (const grp of document.querySelectorAll(".grp")) { const k = grp.dataset.k; grp.querySelectorAll(".chip").forEach((c) => c.remove());+ ["All", ...DIM[k]].forEach((name, i) => { const b = document.createElement("button"); b.className = "chip" + (seg[k] === i - 1 ? " on" : ""); b.textContent = name; b.dataset.v = i - 1; b.onclick = () => setSeg({ ...seg, [k]: i - 1 }); grp.appendChild(b); }); } }+let anim = 0;+function setSeg(next, ms = 900){ seg = next; const from = shown, to = aggregate(seg); A = to; chips();+ return new Promise((ok) => { cancelAnimationFrame(anim); if (REDUCED) { shown = to; render(to); return ok(); } const t0 = performance.now();+ const step = (now) => { const u = Math.min(1, (now - t0) / ms), e = u < .5 ? 4 * u * u * u : 1 - Math.pow(-2 * u + 2, 3) / 2; shown = mix(from, to, e); render(shown); if (u < 1) anim = requestAnimationFrame(step); else { shown = to; render(to); ok(); } }; anim = requestAnimationFrame(step); }); }+const segName = (s) => cap1([s.plan >= 0 ? DIM.plan[s.plan] : "", s.region >= 0 ? DIM.region[s.region] : "", s.device >= 0 ? DIM.device[s.device].toLowerCase() : ""].filter(Boolean).join(" · ") || "Everyone");+const cap1 = (t) => t[0].toUpperCase() + t.slice(1);+let saved = [{ plan: 2, region: -1, device: 1 }, { plan: 0, region: 1, device: -1 }, { plan: -1, region: -1, device: 2 }];+function renderSaved(){ $("saved").innerHTML = saved.map((s, i) => `<a class="seg${JSON.stringify(s) === JSON.stringify(seg) ? " on" : ""}" data-i="${i}"><i></i><span>${segName(s)}</span><small>${(aggregate(s).n / 1000).toFixed(1)}k</small></a>`).join("");+ $("saved").querySelectorAll("a").forEach((a) => a.onclick = async () => { await setSeg(saved[+a.dataset.i]); renderSaved(); }); }+$("saveSeg").onclick = () => { if (!saved.some((s) => JSON.stringify(s) === JSON.stringify(seg))) saved.unshift({ ...seg }); saved = saved.slice(0, 5); renderSaved(); };+// hover a heatmap row+$("heat").addEventListener("pointermove", (e) => { if (!heatGeom) return; const r = $("heat").getBoundingClientRect(), y = e.clientY - r.top, x = e.clientX - r.left, c = Math.floor((y - heatGeom.T) / heatGeom.ch), k = Math.floor((x - heatGeom.L) / heatGeom.cw);+ if (c >= 0 && c < C) { hl = c; hlT = 1; } else hl = -1; render(shown);+ const tip = $("tip"); if (c >= 0 && c < C && k >= 0 && k < K && c + k < C) { tip.style.opacity = 1; tip.style.transform = ""; tip.style.left = `${x}px`; tip.style.top = `${y - 10}px`; tip.innerHTML = `<b>Cohort of ${wkLabel(c)}</b> · week ${k}<br>${Math.round(shown.ret[c * K + k] * 100)}% of ${Math.round(shown.size[c]).toLocaleString("en-US")} still active`; } else tip.style.opacity = 0; });+$("heat").addEventListener("pointerleave", () => { hl = -1; $("tip").style.opacity = 0; render(shown); });++addEventListener("resize", () => render(shown));+(async () => { await document.fonts.ready;+ $("meta").innerHTML = `<b>20</b> weekly cohorts, ${wkLabel(0)} – ${wkLabel(C - 1)} 2026 · <b>${N.toLocaleString("en-US")}</b> people · ${(N * 4).toLocaleString("en-US")} sessions <span class="sample">Sample data</span>`;+ chips(); renderSaved(); render(shown); requestAnimationFrame(() => { document.documentElement.dataset.ready = "1"; }); })();+</script>+</body>+</html>diff --git a/server/local-apps/starters/fleet.html b/server/local-apps/starters/fleet.htmlnew file mode 100644index 0000000000..9cb016da4b--- /dev/null+++ b/server/local-apps/starters/fleet.html@@ -0,0 +1,547 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<title>Corridor · Fleet control</title>+<style>+:root{--bg:#070b10;--panel:rgba(9,13,19,.88);--line:#1c2733;--line2:#26323f;--ink:#d8e2eb;--ink2:#8b9bab;--ink3:#566676;+ --cyan:#3fd0ff;--amber:#ffb020;--red:#ff4d5e;--green:#4fd39a;--mono:ui-monospace,"SF Mono",Menlo,Consolas,monospace;--ui:system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;+ --pw:clamp(300px,18vw,352px)}+*{box-sizing:border-box}html,body{margin:0;height:100%;background:var(--bg);color:var(--ink);font:13px/1.4 var(--ui);overflow:hidden;-webkit-font-smoothing:antialiased}+canvas#map{position:fixed;inset:0;width:100vw;height:100vh;display:block;cursor:grab}canvas#map.drag{cursor:grabbing}canvas#map.hover{cursor:pointer}+.mono{font-family:var(--mono)}+.panel{position:fixed;background:var(--panel);border:1px solid var(--line);border-radius:10px}+.micro{font:500 10px/1 var(--mono);letter-spacing:.12em;text-transform:uppercase;color:var(--ink3)}+/* top bar */+.top{position:fixed;left:24px;right:24px;top:20px;height:60px;display:flex;align-items:center;gap:18px;pointer-events:none}+.brand{display:flex;align-items:center;gap:12px;pointer-events:auto;background:var(--panel);border:1px solid var(--line);border-radius:10px;height:60px;padding:0 18px 0 14px;width:var(--pw)}+.brand svg{width:30px;height:30px}+.brand b{font:600 17px/1 var(--ui);letter-spacing:-.01em}.brand span{display:block;font:11px/1.3 var(--mono);color:var(--ink3);margin-top:4px;letter-spacing:.02em}+.kpis{flex:1;display:flex;height:60px;background:var(--panel);border:1px solid var(--line);border-radius:10px;pointer-events:auto;overflow:hidden}+.kpi{flex:1;padding:10px 16px 0;border-left:1px solid var(--line);min-width:0}.kpi:first-child{border-left:0;flex:1.25}+.kpi .v{font:500 21px/1.2 var(--mono);letter-spacing:-.02em;margin-top:5px;white-space:nowrap}.kpi .v small{font-size:12px;color:var(--ink3);margin-left:4px}+.kpi.clock .v{font-size:24px;color:#fff}.kpi.clock .v small{color:var(--ink2)}+.sim{pointer-events:auto;height:60px;display:flex;flex-direction:column;justify-content:center;align-items:flex-end;gap:6px;background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:0 16px;width:var(--pw)}+.pill{font:500 10px/1 var(--mono);letter-spacing:.1em;text-transform:uppercase;color:var(--ink2);border:1px solid var(--line2);border-radius:20px;padding:5px 9px}+.sim .net{font:11px var(--mono);color:var(--ink3)}+/* left: exceptions */+.exc{left:24px;top:92px;width:var(--pw);bottom:148px;display:flex;flex-direction:column;overflow:hidden}+.ph{display:flex;align-items:center;justify-content:space-between;padding:14px 16px 12px;border-bottom:1px solid var(--line)}+.ph h2{margin:0;font:600 13px/1 var(--ui);letter-spacing:.01em}.ph .count{font:600 11px/1 var(--mono);color:#1a0c0e;background:var(--red);border-radius:10px;padding:4px 7px}+.ph .tabs{display:flex;gap:10px;font:11px var(--mono);color:var(--ink3)}.ph .tabs b{color:var(--ink);font-weight:500}+.list{flex:1;overflow:hidden;position:relative}+.ev{display:grid;grid-template-columns:3px 52px 1fr;gap:0 12px;padding:11px 16px 11px 0;border-bottom:1px solid rgba(28,39,51,.7);transition:transform .45s cubic-bezier(.2,.8,.2,1),opacity .45s,background 1.2s}+.ev.new{background:rgba(255,77,94,.07)}.ev.enter{transform:translateY(-14px);opacity:0}+.ev i{grid-row:span 2;border-radius:0 2px 2px 0}.ev .t{font:500 12px/1.3 var(--mono);color:var(--ink2)}+.ev .ti{font:500 13px/1.3 var(--ui);color:var(--ink);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}+.ev .su{grid-column:3;font:11px/1.4 var(--mono);color:var(--ink3);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.ev .k{grid-column:2;font:10px/1.4 var(--mono);color:var(--ink3);letter-spacing:.06em}+.empty{padding:40px 20px;color:var(--ink3);font:12px var(--mono);text-align:center}+/* right */+.right{right:24px;top:92px;width:var(--pw);bottom:148px;display:flex;flex-direction:column;overflow:hidden}+.dep{padding:12px 16px 4px}+.drow{display:grid;grid-template-columns:1fr auto;gap:6px 10px;padding:9px 0;border-bottom:1px solid rgba(28,39,51,.7)}+.drow .n{font:500 13px var(--ui)}.drow .n small{font:10px var(--mono);color:var(--ink3);margin-left:6px;letter-spacing:.06em}+.drow .p{font:500 13px var(--mono);text-align:right}+.drow canvas{grid-column:span 2;width:100%;height:26px;display:block}+.drow .io{grid-column:span 2;font:10.5px var(--mono);color:var(--ink3);display:flex;justify-content:space-between}+.corr{padding:6px 16px 14px;border-top:1px solid var(--line);flex:1;min-height:0}+.crow{display:grid;grid-template-columns:54px 1fr 64px;align-items:center;gap:10px;padding:7px 0;font:12px var(--mono)}+.crow .nm{color:var(--ink)}.crow .bar{height:6px;border-radius:3px;background:#141c25;overflow:hidden}.crow .bar i{display:block;height:100%;border-radius:3px}+.crow .d{text-align:right;color:var(--ink2)}.crow .via{grid-column:2/4;margin-top:-4px;font:10.5px var(--mono);color:var(--ink3)}+/* vehicle card */+.veh{position:absolute;inset:auto 0 0 0;height:56%;background:#0b1118;border-top:1px solid var(--line2);transform:translateY(102%);transition:transform .55s cubic-bezier(.2,.8,.2,1);display:flex;flex-direction:column}+.veh.on{transform:none}+.vh{display:flex;align-items:flex-start;justify-content:space-between;padding:14px 16px 10px}+.vh .id{font:600 22px/1 var(--mono);letter-spacing:-.02em}.vh .meta{font:11px/1.5 var(--mono);color:var(--ink3);margin-top:6px}+.st{font:500 10px/1 var(--mono);letter-spacing:.08em;text-transform:uppercase;border-radius:12px;padding:5px 8px;border:1px solid}+.vt{padding:0 16px}.vt canvas{width:100%;height:58px;display:block}+.stops{flex:1;overflow:hidden;padding:4px 16px 12px}+.srow{display:grid;grid-template-columns:18px 46px 1fr auto;gap:8px;align-items:center;padding:6px 0;border-bottom:1px solid rgba(28,39,51,.6);font:11.5px var(--mono);color:var(--ink2)}+.srow .num{width:18px;height:18px;border-radius:50%;border:1px solid var(--line2);display:grid;place-items:center;font-size:10px;color:var(--ink3)}+.srow.done .num{background:#15303d;border-color:#2a5466;color:var(--cyan)}.srow .pl{color:var(--ink)}+/* bottom scrubber */+.scrub{left:24px;right:24px;bottom:20px;height:116px;display:grid;grid-template-columns:160px 1fr 290px;align-items:stretch}+.play{display:flex;align-items:center;gap:14px;padding:0 18px;border-right:1px solid var(--line)}+.play button{width:44px;height:44px;border-radius:50%;border:1px solid #2d4a5a;background:#0f2430;color:var(--cyan);display:grid;place-items:center;cursor:pointer}+.play button svg{width:16px;height:16px;fill:currentColor}.play .pz{display:none}.playing .play .pz{display:block}.playing .play .pl{display:none}+.play .tm{font:500 20px/1 var(--mono)}.play .sp{white-space:nowrap;font:10px var(--mono);color:var(--ink3);margin-top:6px;letter-spacing:.06em}+.track{position:relative;cursor:ew-resize;min-height:0;overflow:hidden}.track canvas{position:absolute;left:20px;top:12px;width:calc(100% - 40px);height:calc(100% - 18px);display:block}+.legend{border-left:1px solid var(--line);padding:14px 16px;display:flex;flex-direction:column;gap:9px;font:11px var(--mono);color:var(--ink2)}+.lg{display:flex;align-items:center;gap:7px;white-space:nowrap}.lg i{width:9px;height:9px;border-radius:50%}+.ramp{height:6px;border-radius:3px;background:linear-gradient(90deg,#24323f,#7a5a1c,#ffb020,#ff6a3d,#ff4d5e);margin-top:2px}+.rampl{display:flex;justify-content:space-between;font-size:10px;color:var(--ink3)}+/* map chrome */+.mapui{position:fixed;left:calc(var(--pw) + 44px);bottom:196px;display:flex;flex-direction:column;gap:6px}+.mapui button{width:34px;height:34px;border-radius:8px;border:1px solid var(--line2);background:var(--panel);color:var(--ink2);font:500 16px var(--mono);cursor:pointer}+.scale{position:fixed;left:calc(var(--pw) + 44px);bottom:158px;font:10.5px var(--mono);color:var(--ink2)}+.scale i{display:block;height:6px;border:1px solid var(--ink3);border-top:0;margin-top:4px}+.zoomlvl{position:fixed;left:calc(var(--pw) + 44px);top:96px;font:10.5px var(--mono);color:var(--ink3);letter-spacing:.06em;line-height:1.7}+.zoomlvl b{color:var(--ink2);font-weight:500}+.kpi .micro{white-space:nowrap;overflow:hidden;text-overflow:ellipsis}+@media (max-width:1600px){:root{--pw:280px}.ph .micro{display:none}.kpi{padding:10px 12px 0}}+@media (max-height:950px){.kpi .v{font-size:18px}.kpi.clock .v{font-size:21px}}+</style>+</head>+<body>+<canvas id="map" aria-label="Map of the Kessaly Coast road network with vehicles"></canvas>+<header class="top">+ <div class="brand"><svg viewBox="0 0 30 30" aria-hidden="true"><rect x="1" y="1" width="28" height="28" rx="7" fill="#0f2430" stroke="#2d4a5a"/><path d="M7 21c4-1 5-11 9-11s4 6 7 6" fill="none" stroke="#3fd0ff" stroke-width="2" stroke-linecap="round"/><circle cx="7" cy="21" r="2" fill="#ffb020"/><circle cx="23" cy="16" r="2" fill="#3fd0ff"/></svg>+ <div><b>Corridor</b><span>Kessaly Coast · regional fleet</span></div></div>+ <div class="kpis" id="kpis"></div>+ <div class="sim"><span class="pill">Sample data · simulated day</span><span class="net mono">12 towns · 5 depots · 300 vehicles</span></div>+</header>+<section class="panel exc" aria-label="Exceptions">+ <div class="ph"><h2>Exceptions <span class="mono" style="color:var(--ink3);font-weight:400;margin-left:6px" id="excSub"></span></h2><span class="count" id="excCount">0</span></div>+ <div class="ph" style="padding:9px 16px;border-bottom:1px solid var(--line)"><div class="tabs"><b>All</b><span>Late</span><span>Stopped</span><span>Incidents</span></div><span class="micro">newest first</span></div>+ <div class="list" id="excList"></div>+</section>+<section class="panel right" aria-label="Depots and corridors">+ <div class="ph"><h2>Depots</h2><span class="micro">bay use · 05–22</span></div>+ <div class="dep" id="depots"></div>+ <div class="corr"><div class="ph" style="padding:10px 0 6px;border:0"><h2>Slowest corridors</h2><span class="micro">now · vs free flow</span></div><div id="corr"></div></div>+ <div class="veh" id="veh"></div>+</section>+<section class="panel scrub" id="scrub" aria-label="Day timeline">+ <div class="play"><button id="playBtn" aria-label="Play the day"><svg class="pl" viewBox="0 0 16 16"><path d="M4 2.5v11l9.5-5.5z"/></svg><svg class="pz" viewBox="0 0 16 16"><path d="M3.5 2.5h3v11h-3zM9.5 2.5h3v11h-3z"/></svg></button>+ <div><div class="tm" id="tm">14:20</div><div class="sp">THU · 12 MAR</div></div></div>+ <div class="track" id="track"><canvas id="hist"></canvas></div>+ <div class="legend">+ <div style="display:flex;gap:14px"><span class="lg"><i style="background:var(--cyan)"></i>on time</span><span class="lg"><i style="background:var(--amber)"></i>delayed</span><span class="lg"><i style="background:var(--red)"></i>exception</span></div>+ <div><div class="micro" style="margin-bottom:5px">corridor delay</div><div class="ramp"></div><div class="rampl"><span>free</span><span>+50%</span><span>×2.5</span></div></div>+ </div>+</section>+<div class="zoomlvl" id="zoomlvl"></div>+<div class="scale" id="scale"><span id="scaleTxt">10 km</span><i id="scaleBar"></i></div>+<div class="mapui"><button id="zin" aria-label="Zoom in">+</button><button id="zout" aria-label="Zoom out">−</button><button id="zhome" aria-label="Whole region">⌂</button></div>++<script>+"use strict";+// ———————————————————————————————————————— world ————————————————————————————————————————+// World units are 100 m; the region is 160 × 100 km. Everything below is generated from one seed.+const W = 1600, H = 1000, SEED = 7413;+const REDUCED = matchMedia("(prefers-reduced-motion: reduce)").matches;+function mulberry32(a){return function(){a|=0;a=a+0x6D2B79F5|0;let t=Math.imul(a^a>>>15,1|a);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296}}+const rnd = mulberry32(SEED);+const R = (a, b) => a + (b - a) * rnd();+function hash2(i, j){let h=(Math.imul(i,374761393)+Math.imul(j,668265263)+SEED*97)|0;h=Math.imul(h^(h>>>13),1274126177);return((h^(h>>>16))>>>0)/4294967296}+function vnoise(x, y){const i=Math.floor(x),j=Math.floor(y),fx=x-i,fy=y-j,u=fx*fx*(3-2*fx),v=fy*fy*(3-2*fy);const a=hash2(i,j),b=hash2(i+1,j),c=hash2(i,j+1),d=hash2(i+1,j+1);return a+(b-a)*u+(c-a)*v+(a-b-c+d)*u*v}+function fbm(x, y, o = 6){let s=0,a=.5,f=1;for(let k=0;k<o;k++){s+=a*vnoise(x*f+k*17.3,y*f-k*9.1);f*=2.03;a*=.5}return s}+const clamp = (v, a, b) => v < a ? a : v > b ? b : v, lerp = (a, b, t) => a + (b - a) * t;+const smooth = (a, b, v) => { const t = clamp((v - a) / (b - a), 0, 1); return t * t * (3 - 2 * t); };+const ease = (t) => t < .5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;++const GW = 321, GH = 201, CS = W / (GW - 1);+const hgt = new Float32Array(GW * GH);+function heightAt(x, y){+ const wx = x + 90 * (fbm(x / 240 + 3, y / 240) - .5), wy = y + 90 * (fbm(x / 240, y / 240 + 7) - .5);+ let h = (fbm(wx / 330, wy / 330) - .5) * 1.5 + .95 * (x / W) - .75 * (y / H) - .02;+ h -= .32 * Math.exp(-(((x - 620) / 150) ** 2 + ((y - 560) / 120) ** 2)); // a deep bay+ if (h > 0) { const r = 1 - Math.abs(2 * fbm(x / 170 + 11, y / 170 - 4, 5) - 1); h += .9 * h * h * r * r + .25 * h * r; }+ return h;+}+for (let j = 0; j < GH; j++) for (let i = 0; i < GW; i++) hgt[j * GW + i] = heightAt(i * CS, j * CS);+function hAt(x, y){ const gx = clamp(x / CS, 0, GW - 1.001), gy = clamp(y / CS, 0, GH - 1.001), i = gx | 0, j = gy | 0, fx = gx - i, fy = gy - j, k = j * GW + i;+ return lerp(lerp(hgt[k], hgt[k + 1], fx), lerp(hgt[k + GW], hgt[k + GW + 1], fx), fy); }++// Marching squares: segments of an iso-line over the height grid, as one flat array.+function iso(level, step = 1){+ const out = [];+ for (let j = 0; j < GH - step; j += step) for (let i = 0; i < GW - step; i += step) {+ const a = hgt[j*GW+i]-level, b = hgt[j*GW+i+step]-level, c = hgt[(j+step)*GW+i+step]-level, d = hgt[(j+step)*GW+i]-level;+ const p = [], x0 = i * CS, y0 = j * CS, s = step * CS;+ if ((a > 0) !== (b > 0)) p.push(x0 + s * a / (a - b), y0);+ if ((b > 0) !== (c > 0)) p.push(x0 + s, y0 + s * b / (b - c));+ if ((c > 0) !== (d > 0)) p.push(x0 + s * d / (d - c), y0 + s);+ if ((d > 0) !== (a > 0)) p.push(x0, y0 + s * a / (a - d));+ if (p.length >= 4) out.push(p[0], p[1], p[2], p[3]);+ if (p.length === 8) out.push(p[4], p[5], p[6], p[7]);+ }+ return out;+}+const segPath = (s) => { const p = new Path2D(); for (let k = 0; k < s.length; k += 4) { p.moveTo(s[k], s[k+1]); p.lineTo(s[k+2], s[k+3]); } return p; };+const coast = segPath(iso(0));+const bathy = [-.06, -.14, -.26].map((l) => segPath(iso(l, 2)));+const contours = [.12, .24, .36, .5, .66, .84].map((l) => segPath(iso(l, 1)));++// Land mass: flood fill from the highest point, so towns and roads stay on the mainland.+const main = new Uint8Array(GW * GH);+{ let top = 0; for (let k = 0; k < hgt.length; k++) if (hgt[k] > hgt[top]) top = k;+ const st = [top]; main[top] = 1;+ while (st.length) { const k = st.pop(), i = k % GW, j = (k / GW) | 0;+ for (const [di, dj] of [[1,0],[-1,0],[0,1],[0,-1]]) { const ii = i + di, jj = j + dj; if (ii < 0 || jj < 0 || ii >= GW || jj >= GH) continue; const kk = jj * GW + ii; if (!main[kk] && hgt[kk] > .012) { main[kk] = 1; st.push(kk); } } } }++// Towns: lowland cells near the sea, kept apart.+const NAMES = ["Vessmouth","Kelderby","Orran","Saltreach","Brindlecross","Maraway","Thessel","Duncliff","Pellow Bay","Ostry","Wrenhaven","Hollin"];+const towns = [];+{ const cands = [];+ for (let n = 0; n < 8000; n++) { const x = R(350, 1190), y = R(120, 770), k = Math.round(y / CS) * GW + Math.round(x / CS);+ if (!main[k]) continue; const h = hgt[k]; if (h < .03 || h > .42) continue;+ let near = 99; for (let a = 0; a < 6.28; a += .52) for (const r of [30, 70, 120]) if (hAt(x + Math.cos(a) * r, y + Math.sin(a) * r) < 0) near = Math.min(near, r);+ cands.push({ x, y, s: (near < 99 ? 70 - near * .4 : 0) + rnd() * 110 - h * 60 }); }+ cands.sort((a, b) => b.s - a.s);+ for (const c of cands) { if (towns.length >= 12) break; if (towns.every((t) => Math.hypot(t.x - c.x, t.y - c.y) > 158)) towns.push({ x: c.x, y: c.y }); }+ towns.forEach((t, i) => { t.name = NAMES[i]; t.pop = Math.round(R(8, 30) + (i < 4 ? 40 : 0)); t.id = i; });+}++// Roads: A* over a coarse grid, cheap in valleys and along roads already built, so corridors share alignments.+const AG = 2, AW = Math.floor((GW - 1) / AG) + 1, AH = Math.floor((GH - 1) / AG) + 1, onRoad = new Uint8Array(AW * AH);+function astar(a, b){+ const toI = (p) => Math.round(p.y / CS / AG) * AW + Math.round(p.x / CS / AG);+ const s = toI(a), g = toI(b), gx = g % AW, gy = (g / AW) | 0;+ const cost = new Float32Array(AW * AH).fill(Infinity), from = new Int32Array(AW * AH).fill(-1), heap = [];+ const push = (k, f) => { heap.push([f, k]); let i = heap.length - 1; while (i) { const p = (i - 1) >> 1; if (heap[p][0] <= heap[i][0]) break; [heap[p], heap[i]] = [heap[i], heap[p]]; i = p; } };+ const pop = () => { const top = heap[0], last = heap.pop(); if (heap.length) { heap[0] = last; let i = 0; for (;;) { const l = 2*i+1, r = l+1; let m = i; if (l < heap.length && heap[l][0] < heap[m][0]) m = l; if (r < heap.length && heap[r][0] < heap[m][0]) m = r; if (m === i) break; [heap[m], heap[i]] = [heap[i], heap[m]]; i = m; } } return top; };+ cost[s] = 0; push(s, 0);+ while (heap.length) { const [, k] = pop(); if (k === g) break; const i = k % AW, j = (k / AW) | 0, hk = hgt[j*AG*GW + i*AG];+ for (let dj = -1; dj <= 1; dj++) for (let di = -1; di <= 1; di++) { if (!di && !dj) continue; const ii = i + di, jj = j + dj; if (ii < 0 || jj < 0 || ii >= AW || jj >= AH) continue;+ const kk = jj * AW + ii, gk = jj*AG*GW + ii*AG; if (!main[gk] || hgt[gk] < .015) continue;+ const step = Math.hypot(di, dj), hh = hgt[gk];+ const c = cost[k] + step * (1 + 55 * Math.abs(hh - hk) + 3 * Math.max(0, hh - .1)) * (onRoad[kk] ? .45 : 1);+ if (c < cost[kk]) { cost[kk] = c; from[kk] = k; push(kk, c + .9 * Math.hypot(ii - gx, jj - gy)); } } }+ if (from[g] < 0) return null;+ const cells = []; for (let k = g; k >= 0; k = from[k]) { cells.push(k); onRoad[k] = 1; if (k === s) break; }+ cells.reverse();+ let pts = cells.map((k) => [(k % AW) * AG * CS, ((k / AW) | 0) * AG * CS]);+ pts[0] = [a.x, a.y]; pts[pts.length - 1] = [b.x, b.y];+ for (let it = 0; it < 3; it++) { const q = [pts[0]]; for (let n = 0; n < pts.length - 1; n++) { const [x0, y0] = pts[n], [x1, y1] = pts[n + 1]; q.push([x0*.75+x1*.25, y0*.75+y1*.25], [x0*.25+x1*.75, y0*.25+y1*.75]); } q.push(pts[pts.length - 1]); pts = q; }+ return pts;+}+const edges = [];+{ const n = towns.length, inT = [0], pairs = new Set();+ const key = (a, b) => a < b ? a + "-" + b : b + "-" + a;+ while (inT.length < n) { let best = null; for (const a of inT) for (let b = 0; b < n; b++) if (!inT.includes(b)) { const d = Math.hypot(towns[a].x - towns[b].x, towns[a].y - towns[b].y); if (!best || d < best[2]) best = [a, b, d]; } inT.push(best[1]); pairs.add(key(best[0], best[1])); }+ for (let a = 0; a < n; a++) { const near = towns.map((t, b) => [b, Math.hypot(t.x - towns[a].x, t.y - towns[a].y)]).filter(([b]) => b !== a).sort((p, q) => p[1] - q[1]); for (const [b, d] of near.slice(0, 2)) if (d < 470) pairs.add(key(a, b)); }+ const list = [...pairs].map((k) => k.split("-").map(Number)).sort((p, q) => (towns[q[0]].pop + towns[q[1]].pop) - (towns[p[0]].pop + towns[p[1]].pop));+ let mw = 1, ar = 10;+ for (const [a, b] of list) { const pts = astar(towns[a], towns[b]); if (!pts) continue;+ const big = towns[a].pop + towns[b].pop > 70 && mw <= 5; const len = pts.reduce((s, p, i) => i ? s + Math.hypot(p[0] - pts[i-1][0], p[1] - pts[i-1][1]) : 0, 0);+ edges.push({ id: edges.length, a, b, pts, len, cls: big ? "M" : "A", name: big ? "K" + (mw++) : "R" + (ar++ * 3 % 97), busy: big ? R(.7, 1.1) : R(.3, .7) }); }+}+for (const e of edges) { const c = [0]; for (let i = 1; i < e.pts.length; i++) c.push(c[i-1] + Math.hypot(e.pts[i][0] - e.pts[i-1][0], e.pts[i][1] - e.pts[i-1][1])); e.cum = c; e.path = new Path2D(); e.pts.forEach(([x, y], i) => i ? e.path.lineTo(x, y) : e.path.moveTo(x, y)); }+// Rivers: steepest descent from high ground to the sea.+const rivers = [];+{ const used = []; for (let n = 0; n < 60 && rivers.length < 6; n++) { let i = (R(.3, .98) * GW) | 0, j = (R(.02, .7) * GH) | 0; if (hgt[j*GW+i] < .45 || used.some(([a, b]) => Math.hypot(a - i, b - j) < 40)) continue; used.push([i, j]);+ const pts = [[i * CS, j * CS]]; for (let s = 0; s < 400; s++) { let best = null, bh = hgt[j*GW+i]; for (let dj = -1; dj <= 1; dj++) for (let di = -1; di <= 1; di++) { const ii = i+di, jj = j+dj; if (ii < 0 || jj < 0 || ii >= GW || jj >= GH) continue; const v = hgt[jj*GW+ii] + hash2(ii*7, jj*3) * .004; if (v < bh) { bh = v; best = [ii, jj]; } } if (!best) break; [i, j] = best; pts.push([i * CS, j * CS]); if (bh < 0) break; }+ if (pts.length > 25 && hgt[j*GW+i] < 0) { const p = new Path2D(); pts.forEach(([x, y], k) => k ? p.lineTo(x, y) : p.moveTo(x, y)); rivers.push(p); } } }+// Town streets: radial spokes; every delivery address lies on one.+for (const t of towns) {+ t.spokes = []; const n = 7 + (t.pop > 40 ? 4 : 0);+ for (let s = 0; s < n; s++) { const a = s / n * 6.283 + R(-.2, .2), len = R(22, 34 + t.pop * .45); const pts = [[t.x, t.y]];+ let x = t.x, y = t.y, ang = a; for (let k = 1; k <= 8; k++) { ang += R(-.18, .18); const nx = x + Math.cos(ang) * len / 8, ny = y + Math.sin(ang) * len / 8; if (hAt(nx, ny) < .01) break; x = nx; y = ny; pts.push([x, y]); }+ if (pts.length > 2) t.spokes.push(pts); }+ t.streets = new Path2D(); for (const sp of t.spokes) sp.forEach(([x, y], k) => k ? t.streets.lineTo(x, y) : t.streets.moveTo(x, y));+ for (const r of [9, 16, 24, 31]) if (r < 12 + t.pop * .4) for (let q = 0; q < 3; q++) { const a0 = R(0, 6.283), a1 = a0 + R(.5, 1.6); t.streets.moveTo(t.x + Math.cos(a0) * r, t.y + Math.sin(a0) * r); t.streets.arc(t.x, t.y, r, a0, a1); }+}+// Depots: on the edge of five of the larger towns.+const depots = towns.slice().sort((a, b) => b.pop - a.pop).slice(0, 5).map((t, i) => { const sp = t.spokes[(i * 3) % t.spokes.length]; const p = sp[sp.length - 1]; return { id: i, town: t.id, name: t.name, x: p[0], y: p[1], spoke: (i * 3) % t.spokes.length, bays: 6 + (i === 0 ? 2 : 0) }; });++// Shortest routes between towns (Floyd–Warshall on time).+const NT = towns.length, dist = [], nxt = [];+for (let a = 0; a < NT; a++) { dist.push(new Array(NT).fill(Infinity)); nxt.push(new Array(NT).fill(-1)); dist[a][a] = 0; }+for (const e of edges) { const w = e.len / (e.cls === "M" ? 15 : 10); if (w < dist[e.a][e.b]) { dist[e.a][e.b] = dist[e.b][e.a] = w; nxt[e.a][e.b] = e.b; nxt[e.b][e.a] = e.a; } }+for (let k = 0; k < NT; k++) for (let a = 0; a < NT; a++) for (let b = 0; b < NT; b++) if (dist[a][k] + dist[k][b] < dist[a][b]) { dist[a][b] = dist[a][k] + dist[k][b]; nxt[a][b] = nxt[a][k]; }+const edgeOf = (a, b) => edges.find((e) => (e.a === a && e.b === b) || (e.a === b && e.b === a));++// ———————————————————————————————————————— the day ————————————————————————————————————————+// Minutes since midnight. Congestion: two rush hours plus four incidents on named corridors.+const T0 = 300, T1 = 1320;+const gauss = (t, m, s) => Math.exp(-(((t - m) / s) ** 2));+const rush = (t) => 1.05 * gauss(t, 500, 48) + .9 * gauss(t, 1040, 58) + .28 * gauss(t, 780, 90);+const incidents = [];+{ const motor = edges.filter((e) => e.cls === "M"), all = edges.slice().sort((a, b) => b.busy - a.busy);+ const picks = [[motor[0] ?? all[0], 486, 85, 1.9], [all[3] ?? all[1], 690, 70, 1.6], [motor[1] ?? all[2], 1005, 95, 2.1], [all[6] ?? all[4], 1150, 60, 1.4]];+ for (const [e, t, d, k] of picks) incidents.push({ e: e.id, t0: t, t1: t + d, k }); }+function cong(e, t){ let c = 1 + e.busy * rush(t); for (const i of incidents) if (i.e === e.id) c += i.k * smooth(i.t0, i.t0 + 12, t) * (1 - smooth(i.t1 - 15, i.t1, t)); return c; }++const SPEED = { M: 15, A: 10, L: 4.5 };+const vehicles = [], events = [], arrivals = [];+function polyLen(p){ let s = 0; for (let i = 1; i < p.length; i++) s += Math.hypot(p[i][0] - p[i-1][0], p[i][1] - p[i-1][1]); return s; }+function cumOf(p){ const c = [0]; for (let i = 1; i < p.length; i++) c.push(c[i-1] + Math.hypot(p[i][0] - p[i-1][0], p[i][1] - p[i-1][1])); return c; }+for (let v = 0; v < 300; v++) {+ const dep = depots[v < 60 ? 0 : (v * 7) % 5], home = towns[dep.town], late = rnd() < .3;+ let t = late ? R(560, 830) : R(305, 430), s = t; const start = t;+ const veh = { id: v, code: "V-" + String(101 + ((v * 37) % 900)).padStart(3, "0"), dep: dep.id, pieces: [], stops: [], start, end: 0, km: 0 };+ const P = veh.pieces; let km = 0, stall = rnd() < .09 ? Math.floor(R(1, 4)) : -1, legN = 0;+ const drive = (pts, cls, e) => { const len = polyLen(pts); if (len < .5) return;+ const c = e ? cong(e, t) : 1 + .25 * rush(t), plan = len / SPEED[cls] * (e ? 1.08 + e.busy * (.85 * rush(t) + .12) : 1.15 + .25 * rush(t)), act = len / SPEED[cls] * c * R(.9, 1.12);+ if (stall === legN && e) { stall = -2; const mid = Math.floor(pts.length / 2), a = pts.slice(0, mid + 1), b = pts.slice(mid), la = polyLen(a), d0 = t - s;+ P.push({ k: "d", pts: a, cum: cumOf(a), t0: t, t1: t + act * la / len, d0, d1: d0 + (act - plan) * la / len, km0: km, len: la, e: e.id }); t += act * la / len; s += plan * la / len; km += la;+ const dur = R(26, 58); P.push({ k: "i", x: a[a.length-1][0], y: a[a.length-1][1], t0: t, t1: t + dur, d0: t - s, d1: t - s + dur, km0: km, len: 0, e: e.id });+ events.push({ t: t + 15, kind: "stall", v, title: `Stationary 15+ min on ${e.name}`, sub: `${veh.code} · between ${towns[e.a].name} and ${towns[e.b].name}` }); t += dur;+ const lb = len - la; P.push({ k: "d", pts: b, cum: cumOf(b), t0: t, t1: t + act * lb / len, d0: t - s, d1: t - s + (act - plan) * lb / len, km0: km, len: lb, e: e.id }); t += act * lb / len; s += plan * lb / len; km += lb; return; }+ P.push({ k: "d", pts, cum: cumOf(pts), t0: t, t1: t + act, d0: t - s, d1: t - s + act - plan, km0: km, len, e: e ? e.id : -1 }); t += act; s += plan; km += len; };+ const dwell = (x, y, dur, plan, kind, label) => { P.push({ k: kind, x, y, t0: t, t1: t + dur, d0: t - s, d1: t - s + dur - plan, km0: km, len: 0, e: -1, label }); t += dur; s += plan; };+ const spokeOut = (town, si, frac) => { const sp = towns[town].spokes[si]; const n = Math.max(2, Math.round(sp.length * frac)); return sp.slice(0, n); };+ dwell(dep.x, dep.y, R(14, 26), 20, "s", "Loading at depot");+ let at = home.id, atSpoke = dep.spoke, atFrac = 1;+ const nStops = late ? Math.floor(R(7, 12)) : Math.floor(R(9, 15));+ for (let n = 0; n <= nStops; n++) {+ let to, si, fr;+ if (n === nStops) { to = home.id; si = dep.spoke; fr = 1; }+ else { const w = towns.map((tw, i) => (tw.pop + 8) / (1 + dist[at][i] / 25) ** 1.6 * (i === at ? .5 : 1)); let r = rnd() * w.reduce((a, b) => a + b), i = 0; while ((r -= w[i]) > 0) i++; to = Math.min(i, NT - 1); si = Math.floor(rnd() * towns[to].spokes.length); fr = R(.35, 1); }+ drive(spokeOut(at, atSpoke, atFrac).slice().reverse(), "L", null);+ for (let c = at; c !== to;) { const nb = nxt[c][to]; const e = edgeOf(c, nb); drive(e.a === c ? e.pts : e.pts.slice().reverse(), e.cls, e); c = nb; }+ const out = spokeOut(to, si, fr); drive(out, "L", null); legN++;+ const [x, y] = out[out.length - 1];+ if (n === nStops) { dwell(x, y, R(16, 24), 20, "s", "Unloading at depot"); break; }+ const early = (s - 4) - t; if (early > 0) dwell(x, y, early, early, "s", "Waiting for time window");+ const delay = t - s; arrivals.push({ t, ok: delay <= 10 }); veh.stops.push({ town: to, t, plan: s, delay, x, y, parcels: Math.floor(R(2, 14)) });+ if (delay > 25) events.push({ t, kind: "late", v, title: `Late at stop · +${Math.round(delay)} min`, sub: `${veh.code} · ${towns[to].name}, stop ${n + 1} of ${nStops}` });+ dwell(x, y, Math.max(3, R(5, 16) - Math.min(Math.max(0, delay) * .5, 9)), 9, "s", "Delivery stop");+ at = to; atSpoke = si; atFrac = fr;+ }+ veh.end = t; veh.km = km; vehicles.push(veh);+}+for (const i of incidents) { const e = edges[i.e]; events.push({ t: i.t0 + 6, kind: "incident", title: `Incident on ${e.name} · slow traffic`, sub: `${towns[e.a].name} – ${towns[e.b].name} · up to ×${(1 + e.busy * rush(i.t0) + i.k).toFixed(1)} travel time` }); }+events.sort((a, b) => a.t - b.t); arrivals.sort((a, b) => a.t - b.t);+const okPrefix = []; arrivals.reduce((s, a, i) => (okPrefix[i] = s + (a.ok ? 1 : 0)), 0);++function pieceAt(veh, t){ const P = veh.pieces; if (t < P[0].t0 || t >= P[P.length-1].t1) return null; let lo = 0, hi = P.length - 1; while (lo < hi) { const m = (lo + hi + 1) >> 1; if (P[m].t0 <= t) lo = m; else hi = m - 1; } return P[lo]; }+function posOf(p, t){ if (p.k !== "d") return [p.x, p.y, 0]; const f = clamp((t - p.t0) / (p.t1 - p.t0), 0, 1), d = f * p.len, c = p.cum; let i = 1; while (i < c.length - 1 && c[i] < d) i++;+ const g = (d - c[i-1]) / Math.max(1e-6, c[i] - c[i-1]), a = p.pts[i-1], b = p.pts[i]; return [lerp(a[0], b[0], g), lerp(a[1], b[1], g), Math.atan2(b[1] - a[1], b[0] - a[0])]; }+function stateOf(veh, t){ const p = pieceAt(veh, t); if (!p) return null; const [x, y, ang] = posOf(p, t); const f = p.t1 > p.t0 ? clamp((t - p.t0) / (p.t1 - p.t0), 0, 1) : 0; const delay = lerp(p.d0, p.d1, f);+ const status = p.k === "i" || delay > 40 ? 2 : delay > 10 ? 1 : 0; return { x, y, ang, delay, status, p, km: p.km0 + f * p.len }; }+// Delayed vehicles per 10 minutes, for the scrubber's histogram.+const BUCK = []; for (let t = T0; t < T1; t += 10) { let d = 0, x = 0; for (const v of vehicles) { const s = stateOf(v, t); if (s) { if (s.status === 1) d++; if (s.status === 2) x++; } } BUCK.push([d, x]); }+// Bay use per depot through the day.+const BAYS = depots.map((d) => { const a = []; for (let t = T0; t < T1; t += 10) { let n = 0; for (const v of vehicles) if (v.dep === d.id) { const p = pieceAt(v, t); if (p && p.k === "s" && p.label && p.label.includes("depot")) n++; } a.push(n / d.bays); } return a; });++// ———————————————————————————————————————— terrain raster ————————————————————————————————————————+const RS = 2, terr = document.createElement("canvas"); terr.width = W * RS; terr.height = H * RS;+{ const g = terr.getContext("2d"), img = g.createImageData(terr.width, terr.height), d = img.data, TW = terr.width;+ for (let py = 0; py < terr.height; py++) for (let px = 0; px < TW; px++) {+ const x = px / RS, y = py / RS, h = hAt(x, y), hx = hAt(x + 1.5, y) - hAt(x - 1.5, y), hy = hAt(x, y + 1.5) - hAt(x, y - 1.5), o = (py * TW + px) * 4;+ if (h < 0) { const dd = clamp(-h / .3, 0, 1), sh = Math.exp(-dd * 9); d[o] = 5 + 6 * sh; d[o+1] = 9 + 12 * sh; d[o+2] = 14 + 16 * sh; d[o+3] = 255; continue; }+ const shade = clamp(.5 + (-hx * 1.0 - hy * .7) * 15, 0, 1), e = clamp(h / .9, 0, 1);+ const base = [lerp(27, 44, e), lerp(35, 45, e), lerp(43, 50, e)], lit = lerp(.5, 1.5, shade);+ d[o] = base[0] * lit; d[o+1] = base[1] * lit; d[o+2] = base[2] * lit; d[o+3] = 255; }+ g.putImageData(img, 0, 0); }++// ———————————————————————————————————————— view ————————————————————————————————————————+const cv = document.getElementById("map"), ctx = cv.getContext("2d");+let DPR = 1, VW = 0, VH = 0;+const cam = { x: W / 2, y: H / 2, z: 1 };+const base = () => Math.max(VW / (W * 1.02), VH / (H * 1.02));+const scl = () => base() * cam.z;+const toScreen = (x, y) => [(x - cam.x) * scl() + VW / 2, (y - cam.y) * scl() + VH / 2];+const toWorld = (sx, sy) => [(sx - VW / 2) / scl() + cam.x, (sy - VH / 2) / scl() + cam.y];+function resize(){ DPR = devicePixelRatio || 1; VW = innerWidth; VH = innerHeight; cv.width = VW * DPR; cv.height = VH * DPR; dirty = true; drawHist(); drawDepots(); }+function homeCam(){ const pw = document.querySelector(".exc").offsetWidth, fx0 = pw + 60, fx1 = VW - pw - 60, fy0 = 110, fy1 = VH - 160;+ let x0 = 1e9, y0 = 1e9, x1 = -1e9, y1 = -1e9; for (const t of towns) { x0 = Math.min(x0, t.x); y0 = Math.min(y0, t.y); x1 = Math.max(x1, t.x); y1 = Math.max(y1, t.y); }+ x0 -= 50; x1 += 140; y0 -= 50; y1 += 50; const k = Math.min((fx1 - fx0) / (x1 - x0), (fy1 - fy0) / (y1 - y0));+ return { z: Math.max(1.02, k / base()), x: (x0 + x1) / 2 - ((fx0 + fx1) / 2 - VW / 2) / k, y: (y0 + y1) / 2 - ((fy0 + fy1) / 2 - VH / 2) / k }; }+const S = { t: 1022, playing: false, sel: null, follow: false, hover: null, anim: null };+let dirty = true;++function clampCam(){ cam.z = Math.max(cam.z, 1.02); const k = scl(), hw = VW / 2 / k, hh = VH / 2 / k; cam.x = clamp(cam.x, hw, W - hw); cam.y = clamp(cam.y, hh, H - hh); }+function draw(){+ clampCam(); const k = scl(), g = ctx;+ g.setTransform(DPR, 0, 0, DPR, 0, 0); g.fillStyle = "#070b10"; g.fillRect(0, 0, VW, VH);+ g.setTransform(DPR * k, 0, 0, DPR * k, DPR * (VW / 2 - cam.x * k), DPR * (VH / 2 - cam.y * k));+ g.imageSmoothingQuality = "high"; g.drawImage(terr, 0, 0, W, H);+ const px = 1 / k;+ g.lineJoin = "round"; g.lineCap = "round";+ g.strokeStyle = "rgba(40,66,90,.55)"; g.lineWidth = px; for (const b of bathy) g.stroke(b);+ const ca = .55 - .25 * smooth(2, 6, cam.z); if (ca > .01) { g.strokeStyle = `rgba(60,78,92,${ca})`; g.lineWidth = .8 * px; contours.forEach((c) => g.stroke(c)); }+ g.strokeStyle = "#1f4a66"; for (const r of rivers) { g.lineWidth = 1.6 * px * Math.min(2, cam.z ** .4); g.stroke(r); }+ g.strokeStyle = "#4b7491"; g.lineWidth = 1.4 * px; g.stroke(coast);+ // Streets appear as you zoom.+ const sa = smooth(1.6, 3, cam.z); if (sa > .01) { g.strokeStyle = `rgba(58,74,90,${.9 * sa})`; g.lineWidth = 1.1 * px; for (const t of towns) g.stroke(t.streets); }+ // Roads, then the corridor heat on top.+ for (const e of edges) { g.strokeStyle = e.cls === "M" ? "#0b1016" : "#0a0f14"; g.lineWidth = (e.cls === "M" ? 5 : 3.4) * px; g.stroke(e.path); }+ for (const e of edges) { g.strokeStyle = e.cls === "M" ? "#4a5d70" : "#33424f"; g.lineWidth = (e.cls === "M" ? 2.4 : 1.5) * px; g.stroke(e.path); }+ g.globalCompositeOperation = "lighter";+ for (const e of edges) { const lv = clamp((cong(e, S.t) - 1.3) / 1.4, 0, 1); if (lv < .04) continue;+ const col = lv < .5 ? [255, 176, 32] : [255, lerp(176, 77, (lv - .5) * 2), lerp(32, 94, (lv - .5) * 2)];+ g.strokeStyle = `rgba(${col[0]|0},${col[1]|0},${col[2]|0},${.07 + .16 * lv})`; g.lineWidth = (10 + 18 * lv) * px; g.stroke(e.path);+ g.strokeStyle = `rgba(${col[0]|0},${col[1]|0},${col[2]|0},${.25 + .5 * lv})`; g.lineWidth = (2.2 + 2.2 * lv) * px; g.stroke(e.path); }+ g.globalCompositeOperation = "source-over";+ // The selected vehicle's day: planned path dashed, driven part solid.+ if (S.sel) { const v = S.sel; g.lineWidth = 2 * px; g.setLineDash([5 * px, 5 * px]); g.strokeStyle = "rgba(63,208,255,.45)"; g.beginPath();+ for (const p of v.pieces) if (p.k === "d" && p.t0 >= S.t) p.pts.forEach(([x, y], i) => i ? g.lineTo(x, y) : g.moveTo(x, y)); g.stroke(); g.setLineDash([]);+ g.strokeStyle = "rgba(63,208,255,.9)"; g.lineWidth = 2.6 * px; g.beginPath(); for (const p of v.pieces) if (p.k === "d" && p.t0 < S.t) { const f = clamp((S.t - p.t0) / (p.t1 - p.t0), 0, 1), d = f * p.len; for (let i = 0; i < p.pts.length && p.cum[i] <= d; i++) { const [x, y] = p.pts[i]; i ? g.lineTo(x, y) : g.moveTo(x, y); } } g.stroke(); }+ g.setTransform(DPR, 0, 0, DPR, 0, 0);+ // Depots.+ for (const d of depots) { const [x, y] = toScreen(d.x, d.y); g.fillStyle = "#0b1118"; g.strokeStyle = "#8fa3b5"; g.lineWidth = 1.2; g.fillRect(x - 5, y - 5, 10, 10); g.strokeRect(x - 5, y - 5, 10, 10); g.fillStyle = "#8fa3b5"; g.fillRect(x - 2, y - 2, 4, 4); }+ // Vehicles: clusters when far, individual chevrons when near.+ const ind = smooth(2.2, 3.4, cam.z), cl = 1 - ind, st = [];+ for (const v of vehicles) { const s = stateOf(v, S.t); if (!s) continue; const [x, y] = toScreen(s.x, s.y); if (x < -40 || y < -40 || x > VW + 40 || y > VH + 40) continue; st.push([v, s, x, y]); }+ const COLS = ["#3fd0ff", "#ffb020", "#ff4d5e"];+ if (cl > .01) { const cell = 58, bins = new Map();+ for (const it of st) { const kx = Math.floor(it[2] / cell), ky = Math.floor(it[3] / cell), key = kx * 1000 + ky; let b = bins.get(key); if (!b) bins.set(key, b = { n: 0, x: 0, y: 0, c: [0, 0, 0] }); b.n++; b.x += it[2]; b.y += it[3]; b.c[it[1].status]++; }+ g.globalAlpha = cl;+ for (const b of bins.values()) { const x = b.x / b.n, y = b.y / b.n;+ if (b.n === 1) { const s = b.c.findIndex((c) => c); g.fillStyle = COLS[s]; g.beginPath(); g.arc(x, y, 3.2, 0, 6.283); g.fill(); continue; }+ const r = 9 + Math.sqrt(b.n) * 3.4; g.fillStyle = "rgba(8,13,19,.92)"; g.beginPath(); g.arc(x, y, r, 0, 6.283); g.fill();+ let a0 = -Math.PI / 2; g.lineWidth = 2.6; for (let s = 0; s < 3; s++) { if (!b.c[s]) continue; const a1 = a0 + b.c[s] / b.n * 6.283; g.strokeStyle = COLS[s]; g.beginPath(); g.arc(x, y, r - 1.3, a0 + .06, a1 - .06); g.stroke(); a0 = a1; }+ g.fillStyle = "#e6eef5"; g.font = `600 ${b.n > 9 ? 11 : 11.5}px ui-monospace, Menlo, Consolas, monospace`; g.textAlign = "center"; g.textBaseline = "middle"; g.fillText(b.n, x, y + .5); }+ g.globalAlpha = 1; }+ if (ind > .01) { g.globalAlpha = ind;+ for (const [v, s, x, y] of st) { const col = COLS[s.status];+ if (S.playing || S.anim) { g.strokeStyle = col; g.globalAlpha = ind * .35; g.lineWidth = 2; g.beginPath(); for (let k2 = 0; k2 <= 4; k2++) { const q = stateOf(v, S.t - k2 * 1.6); if (!q) break; const [qx, qy] = toScreen(q.x, q.y); k2 ? g.lineTo(qx, qy) : g.moveTo(qx, qy); } g.stroke(); g.globalAlpha = ind; }+ g.save(); g.translate(x, y); g.rotate(s.ang); g.fillStyle = col; g.strokeStyle = "#060a0e"; g.lineWidth = 1.5; g.beginPath(); g.moveTo(7, 0); g.lineTo(-5, -4.6); g.lineTo(-2.4, 0); g.lineTo(-5, 4.6); g.closePath(); g.stroke(); g.fill(); g.restore();+ if (cam.z > 4.2 && v !== S.sel && (s.status || v === S.hover)) { g.font = "500 10px ui-monospace, Menlo, Consolas, monospace"; g.textAlign = "left"; g.textBaseline = "middle"; g.fillStyle = s.status === 2 ? "#ff8a95" : s.status === 1 ? "#ffc861" : "#9fdcf2"; g.fillText(`${v.code}${s.delay > 1 ? " +" + Math.round(s.delay) : ""}`, x + 10, y - 8); } }+ g.globalAlpha = 1; }+ if (S.sel) { const s = stateOf(S.sel, S.t); if (s) { const [x, y] = toScreen(s.x, s.y), ph = (performance.now() / 900) % 1; g.strokeStyle = `rgba(63,208,255,${1 - ph})`; g.lineWidth = 1.5; g.beginPath(); g.arc(x, y, 10 + ph * 18, 0, 6.283); g.stroke(); g.strokeStyle = "#3fd0ff"; g.beginPath(); g.arc(x, y, 11, 0, 6.283); g.stroke();+ if (ind < .5) { g.save(); g.translate(x, y); g.rotate(s.ang); g.fillStyle = "#3fd0ff"; g.beginPath(); g.moveTo(7, 0); g.lineTo(-5, -4.6); g.lineTo(-2.4, 0); g.lineTo(-5, 4.6); g.fill(); g.restore(); }+ g.font = "600 12px ui-monospace, Menlo, Consolas, monospace"; g.fillStyle = "#e6f7ff"; g.textAlign = "left"; g.fillText(S.sel.code, x + 16, y - 14); } }+ // Labels: towns (big first, no overlaps), depots, corridor names when close.+ const boxes = []; const free = (b) => boxes.every((o) => b[0] > o[2] || b[2] < o[0] || b[1] > o[3] || b[3] < o[1]);+ g.textBaseline = "alphabetic";+ for (const t of towns.slice().sort((a, b) => b.pop - a.pop)) { const [x, y] = toScreen(t.x, t.y); const big = t.pop > 40, fs = big ? 13 : 11.5;+ g.font = `${big ? 600 : 500} ${fs}px ui-monospace, Menlo, Consolas, monospace`; g.letterSpacing = "2px"; const label = t.name.toUpperCase(), w = g.measureText(label).width;+ const ox = cam.z < 2.4 ? 20 : 10, oy = cam.z < 2.4 ? -14 : -7; const bx = [x + ox, y + oy - 13, x + ox + w, y + oy + 3]; if (!free(bx)) continue; boxes.push(bx);+ g.fillStyle = "#e7eef4"; g.beginPath(); g.arc(x, y, big ? 3.6 : 2.6, 0, 6.283); g.fill(); g.strokeStyle = "rgba(7,11,16,.85)"; g.lineWidth = 4; g.textAlign = "left";+ g.strokeText(label, x + ox, y + oy); g.fillStyle = big ? "#e7eef4" : "#b4c2cf"; g.fillText(label, x + ox, y + oy);+ if (cam.z > 1.7) { g.letterSpacing = "0px"; g.font = "10px ui-monospace, Menlo, Consolas, monospace"; g.fillStyle = "#6f8193"; g.strokeText(`pop ${t.pop}k`, x + ox, y + oy + 13); g.fillText(`pop ${t.pop}k`, x + ox, y + oy + 13); } }+ g.letterSpacing = "0px";+ if (cam.z > 1.5) for (const d of depots) { const [x, y] = toScreen(d.x, d.y); g.font = "500 10px ui-monospace, Menlo, Consolas, monospace"; g.fillStyle = "#8fa3b5"; g.textAlign = "left"; g.strokeStyle = "rgba(7,11,16,.85)"; g.lineWidth = 3; g.strokeText(`DEPOT ${d.id + 1}`, x + 9, y + 4); g.fillText(`DEPOT ${d.id + 1}`, x + 9, y + 4); }+ for (const e of edges) { if (e.cls !== "M" && cam.z < 2.2) continue; const m = e.pts[Math.floor(e.pts.length * .5)], [x, y] = toScreen(m[0], m[1]); if (x < 0 || y < 0 || x > VW || y > VH) continue;+ const lab = e.name, w = 8 + lab.length * 7; const bx = [x - w / 2, y - 8, x + w / 2, y + 8]; if (!free(bx)) continue; boxes.push(bx);+ g.fillStyle = e.cls === "M" ? "#1d3a52" : "#1a232c"; g.strokeStyle = e.cls === "M" ? "#3f7092" : "#3a4855"; g.lineWidth = 1; g.beginPath(); g.roundRect(x - w / 2, y - 8, w, 16, 3); g.fill(); g.stroke();+ g.font = "600 10px ui-monospace, Menlo, Consolas, monospace"; g.fillStyle = "#d6e4ef"; g.textAlign = "center"; g.textBaseline = "middle"; g.fillText(lab, x, y + .5); g.textBaseline = "alphabetic"; }+ // Scale bar, zoom readout.+ const kmPx = 10 * k, nice = [1, 2, 5, 10, 20, 50].find((n) => n * kmPx > 70) ?? 50;+ scaleTxt.textContent = `${nice} km`; scaleBar.style.width = `${nice * kmPx}px`;+ zoomlvl.innerHTML = `ZOOM <b>${cam.z.toFixed(1)}×</b> · ${ind > .5 ? "<b>VEHICLES</b>" : "<b>CLUSTERS</b>"}<br>E ${(cam.x / 10).toFixed(1)} · N ${((H - cam.y) / 10).toFixed(1)} km`;+}++// ———————————————————————————————————————— panels ————————————————————————————————————————+const $ = (id) => document.getElementById(id);+const scaleTxt = $("scaleTxt"), scaleBar = $("scaleBar"), zoomlvl = $("zoomlvl");+const hhmm = (t) => `${String(Math.floor(t / 60) % 24).padStart(2, "0")}:${String(Math.floor(t % 60)).padStart(2, "0")}`;+const fmt = new Intl.NumberFormat("en-US");+function kpis(){+ let active = 0, km = 0, del = 0, exc = 0;+ for (const v of vehicles) { const s = stateOf(v, S.t); if (s) { active++; km += s.km; if (s.status === 1) del++; if (s.status === 2) exc++; } else if (S.t >= v.end) km += v.km; }+ let lo = 0, hi = arrivals.length; while (lo < hi) { const m = (lo + hi) >> 1; if (arrivals[m].t <= S.t) lo = m + 1; else hi = m; }+ const done = lo, ok = done ? okPrefix[done - 1] : 0;+ $("kpis").innerHTML = `<div class="kpi clock"><div class="micro">Clock · sim</div><div class="v">${hhmm(S.t)}<small>${S.playing ? "▶ 3 min/s" : "paused"}</small></div></div>+ <div class="kpi"><div class="micro">Active</div><div class="v">${active}<small>/ 300</small></div></div>+ <div class="kpi"><div class="micro">On time</div><div class="v" style="color:${done && ok / done < .88 ? "#ffc861" : "#7fe3b6"}">${done ? (ok / done * 100).toFixed(1) : "—"}<small>%</small></div></div>+ <div class="kpi"><div class="micro">Delivered</div><div class="v">${fmt.format(done)}<small>/ ${fmt.format(arrivals.length)}</small></div></div>+ <div class="kpi"><div class="micro">Driven</div><div class="v">${fmt.format(Math.round(km / 10))}<small>km</small></div></div>+ <div class="kpi"><div class="micro">Delayed · exc</div><div class="v"><span style="color:#ffc861">${del}</span><small>·</small><span style="color:#ff7b87;margin-left:4px">${exc}</span></div></div>`;+ $("tm").textContent = hhmm(S.t);+}+let shownEv = -1;+const COLX = { stall: "#ff4d5e", late: "#ffb020", incident: "#ff6a3d" }, KINDX = { stall: "STOPPED", late: "LATE", incident: "INCIDENT" };+function evEl(e){ const d = document.createElement("div"); d.className = "ev"; d.dataset.v = e.v ?? "";+ d.innerHTML = `<i style="background:${COLX[e.kind]}"></i><span class="t">${hhmm(e.t)}</span><span class="ti">${e.title}</span><span class="k" style="color:${COLX[e.kind]}">${KINDX[e.kind]}</span><span class="su">${e.sub}</span>`; return d; }+function exceptions(){+ let n = 0; while (n < events.length && events[n].t <= S.t) n++;+ if (n === shownEv) return; const list = $("excList");+ $("excCount").textContent = n; $("excSub").textContent = `since 05:00`;+ if (shownEv < 0 || n < shownEv || n - shownEv > 6) { list.innerHTML = ""; for (let i = Math.max(0, n - 14); i < n; i++) list.prepend(evEl(events[i])); if (!n) list.innerHTML = `<div class="empty">No exceptions yet today.</div>`; }+ else { list.querySelector(".empty")?.remove(); for (let i = shownEv; i < n; i++) { const el = evEl(events[i]); el.classList.add("new", "enter"); list.prepend(el);+ requestAnimationFrame(() => requestAnimationFrame(() => el.classList.remove("enter"))); setTimeout(() => el.classList.remove("new"), 1500); }+ while (list.children.length > 14) list.lastElementChild.remove(); }+ shownEv = n;+}+$("excList").addEventListener("click", (e) => { const el = e.target.closest(".ev"); if (el && el.dataset.v !== "") selectVehicle(+el.dataset.v); });+function drawDepots(){+ const bi = clamp(Math.floor((S.t - T0) / 10), 0, BAYS[0].length - 1);+ if (!$("depots").children.length) $("depots").innerHTML = depots.map((d) => `<div class="drow"><span class="n">${d.name}<small>DEPOT ${d.id + 1}</small></span><span class="p" id="dp${d.id}"></span><canvas id="dc${d.id}"></canvas><span class="io" id="di${d.id}"></span></div>`).join("");+ for (const d of depots) {+ const u = BAYS[d.id][bi], c = $("dc" + d.id), w = c.clientWidth, h = c.clientHeight; if (!w) continue; c.width = w * DPR; c.height = h * DPR; const g = c.getContext("2d"); g.scale(DPR, DPR);+ const a = BAYS[d.id], bw = w / a.length;+ for (let i = 0; i < a.length; i++) { const v = clamp(a[i], 0, 1.2) / 1.2; g.fillStyle = i <= bi ? (a[i] > .9 ? "#ffb020" : "#2f8fb3") : "#1a2530"; g.fillRect(i * bw, h - 2 - v * (h - 4), Math.max(1, bw - .6), v * (h - 4) + 1); }+ g.fillStyle = "#e6eef5"; g.fillRect(bi * bw, 0, 1.5, h);+ $("dp" + d.id).textContent = `${Math.round(u * 100)}%`; $("dp" + d.id).style.color = u > .9 ? "#ffc861" : "#d8e2eb";+ let out = 0, home = 0; for (const v of vehicles) if (v.dep === d.id) { if (S.t >= v.start && S.t < v.end) out++; else home++; }+ $("di" + d.id).innerHTML = `<span>${Math.round(u * d.bays)} of ${d.bays} bays</span><span>out ${out} · yard ${home}</span>`;+ }+ const rows = edges.map((e) => ({ e, c: cong(e, S.t) })).sort((a, b) => b.c - a.c).slice(0, 4);+ $("corr").innerHTML = rows.map(({ e, c }) => { const lv = clamp((c - 1) / 1.6, 0, 1); return `<div class="crow"><span class="nm">${e.name}</span><span class="bar"><i style="width:${Math.max(4, lv * 100)}%;background:${lv > .5 ? "#ff6a3d" : lv > .15 ? "#ffb020" : "#2f8fb3"}"></i></span><span class="d">×${c.toFixed(2)}</span><span class="via">${towns[e.a].name} – ${towns[e.b].name} · ${(e.len / 10).toFixed(0)} km</span></div>`; }).join("");+}+function vehCard(){+ const el = $("veh"); const v = S.sel; if (!v) { el.classList.remove("on"); return; }+ el.classList.add("on"); const s = stateOf(v, S.t), d = depots[v.dep];+ const stt = !s ? (S.t < v.start ? ["At depot", "#8b9bab"] : ["Day done", "#8b9bab"]) : s.status === 2 ? ["Exception", "#ff4d5e"] : s.status === 1 ? [`Delayed +${Math.round(s.delay)}`, "#ffb020"] : ["On time", "#3fd0ff"];+ if (!el.dataset.v || +el.dataset.v !== v.id) {+ el.dataset.v = v.id;+ el.innerHTML = `<div class="vh"><div><div class="id">${v.code}</div><div class="meta">${d.name} depot · ${v.stops.length} stops · ${(v.km / 10).toFixed(0)} km<br>shift ${hhmm(v.start)}–${hhmm(v.end)}</div></div><span class="st" id="vst"></span></div>+ <div class="vt"><div class="micro" style="margin-bottom:6px">The day · drive / stop / stationary</div><canvas id="vtl"></canvas></div><div class="stops" id="vstops"></div>`;+ }+ $("vst").textContent = stt[0]; $("vst").style.color = stt[1]; $("vst").style.borderColor = stt[1] + "66";+ const c = $("vtl"), w = c.clientWidth, h = c.clientHeight; c.width = w * DPR; c.height = h * DPR; const g = c.getContext("2d"); g.scale(DPR, DPR);+ const X = (t) => (t - T0) / (T1 - T0) * w;+ g.fillStyle = "#121a23"; g.fillRect(0, 14, w, 18);+ for (const p of v.pieces) { g.fillStyle = p.k === "d" ? (p.d1 > 10 ? "#ffb020" : "#2f8fb3") : p.k === "i" ? "#ff4d5e" : "#4fd39a"; g.globalAlpha = p.t0 < S.t ? 1 : .35; g.fillRect(X(p.t0), p.k === "d" ? 17 : 14, Math.max(1, X(p.t1) - X(p.t0)), p.k === "d" ? 12 : 18); }+ g.globalAlpha = 1; g.fillStyle = "#e6eef5"; g.fillRect(X(S.t), 8, 1.5, 30);+ g.font = "10px ui-monospace, Menlo, Consolas, monospace"; g.fillStyle = "#566676"; for (let hh = 6; hh <= 18; hh += 4) { g.fillText(`${String(hh).padStart(2, "0")}:00`, X(hh * 60) - 14, 50); }+ $("vstops").innerHTML = v.stops.slice(0, 7).map((st, i) => `<div class="srow${st.t <= S.t ? " done" : ""}"><span class="num">${i + 1}</span><span>${hhmm(st.t)}</span><span class="pl">${towns[st.town].name} · ${st.parcels} parcels</span><span style="color:${st.delay > 18 ? "#ff7b87" : st.delay > 10 ? "#ffc861" : "#7fe3b6"}">${st.delay >= 0 ? "+" : "−"}${Math.abs(Math.round(st.delay))} min</span></div>`).join("");+}+const hist = $("hist"), track = $("track");+function drawHist(){+ const w = hist.clientWidth, h = hist.clientHeight; if (!w) return; hist.width = w * DPR; hist.height = h * DPR; const g = hist.getContext("2d"); g.scale(DPR, DPR);+ const X = (t) => (t - T0) / (T1 - T0) * w, top = 22, bh = h - top - 22, mx = Math.max(...BUCK.map(([a, b]) => a + b));+ g.fillStyle = "rgba(63,208,255,.05)"; g.fillRect(0, top, X(S.t), bh);+ BUCK.forEach(([d, x], i) => { const t = T0 + i * 10, x0 = X(t) + 1, bw = X(t + 10) - X(t) - 2, past = t < S.t;+ const hd = d / mx * bh, hx = x / mx * bh; g.fillStyle = past ? "#c7861a" : "#3a3020"; g.fillRect(x0, top + bh - hd - hx, bw, hd); g.fillStyle = past ? "#e0414f" : "#3a2226"; g.fillRect(x0, top + bh - hx, bw, hx); });+ for (const i of incidents) { g.fillStyle = "rgba(255,106,61,.85)"; g.fillRect(X(i.t0), top - 6, X(i.t1) - X(i.t0), 3); }+ g.strokeStyle = "#26323f"; g.beginPath(); g.moveTo(0, top + bh + .5); g.lineTo(w, top + bh + .5); g.stroke();+ g.font = "10.5px ui-monospace, Menlo, Consolas, monospace"; g.textAlign = "center"; for (let hh = 6; hh <= 21; hh++) { const x = X(hh * 60); g.fillStyle = "#26323f"; g.fillRect(x, top + bh, 1, 4); if (hh % 2 === 0) { g.fillStyle = "#6f8193"; g.fillText(`${String(hh).padStart(2, "0")}:00`, x, top + bh + 17); } }+ g.textAlign = "left"; g.fillStyle = "#566676"; g.fillText("DELAYED VEHICLES · PER 10 MIN", 0, 10); g.textAlign = "right"; g.fillStyle = "#ff8a5c"; g.fillText("━ INCIDENTS", w, 10);+ const x = X(S.t); g.fillStyle = "#e6f7ff"; g.fillRect(x - 1, top - 8, 2, bh + 12); g.beginPath(); g.arc(x, top - 8, 4, 0, 6.283); g.fill();+}+let lastPanel = 0;+function panels(force){ const now = performance.now(); if (!force && now - lastPanel < 90) return; lastPanel = now; kpis(); exceptions(); drawDepots(); drawHist(); vehCard(); }++// ———————————————————————————————————————— interaction ————————————————————————————————————————+let drag = null, vel = [0, 0];+cv.addEventListener("pointerdown", (e) => { cancelAnim(); S.follow = false; drag = { x: e.clientX, y: e.clientY, cx: cam.x, cy: cam.y, moved: 0, t: performance.now() }; cv.setPointerCapture(e.pointerId); cv.classList.add("drag"); });+cv.addEventListener("pointermove", (e) => {+ if (drag) { const dx = e.clientX - drag.x, dy = e.clientY - drag.y; drag.moved = Math.max(drag.moved, Math.hypot(dx, dy)); const nx = drag.cx - dx / scl(), ny = drag.cy - dy / scl(); vel = [nx - cam.x, ny - cam.y]; cam.x = nx; cam.y = ny; dirty = true; return; }+ const h = pick(e.clientX, e.clientY); if (h !== S.hover) { S.hover = h; dirty = true; } cv.classList.toggle("hover", !!h);+});+cv.addEventListener("pointerup", (e) => { cv.classList.remove("drag"); const d = drag; drag = null; if (!d) return;+ if (d.moved < 4) { const v = pick(e.clientX, e.clientY); if (v) selectVehicle(v.id, { follow: false }); else if (cam.z < 2.6) { const [x, y] = toWorld(e.clientX, e.clientY); zoomTo(x, y, Math.min(8, cam.z * 2.2), 900); } }+ else if (!REDUCED) glide(); });+function glide(){ const step = () => { vel[0] *= .9; vel[1] *= .9; cam.x += vel[0]; cam.y += vel[1]; dirty = true; if (Math.hypot(...vel) > .02 && !drag) requestAnimationFrame(step); }; requestAnimationFrame(step); }+cv.addEventListener("wheel", (e) => { e.preventDefault(); cancelAnim(); const [wx, wy] = toWorld(e.clientX, e.clientY); const z = clamp(cam.z * Math.exp(-e.deltaY * .0018), 1.02, 14);+ if (REDUCED || Math.abs(e.deltaY) < 60) { cam.z = z; const [ax, ay] = toWorld(e.clientX, e.clientY); cam.x += wx - ax; cam.y += wy - ay; dirty = true; } else zoomAround(e.clientX, e.clientY, z, 420); }, { passive: false });+function zoomAround(sx, sy, z, ms){ const [wx, wy] = toWorld(sx, sy), z0 = cam.z; animate(ms, (u) => { cam.z = Math.exp(lerp(Math.log(z0), Math.log(z), u)); const [ax, ay] = toWorld(sx, sy); cam.x += wx - ax; cam.y += wy - ay; }); }+function pick(sx, sy){ let best = null, bd = cam.z > 2.6 ? 14 : 0; if (!bd) return null; for (const v of vehicles) { const s = stateOf(v, S.t); if (!s) continue; const [x, y] = toScreen(s.x, s.y), d = Math.hypot(x - sx, y - sy); if (d < bd) { bd = d; best = v; } } return best; }+$("zin").onclick = () => zoomAround(VW / 2, VH / 2, Math.min(14, cam.z * 1.8), 500);+$("zout").onclick = () => zoomAround(VW / 2, VH / 2, Math.max(1.02, cam.z / 1.8), 500);+$("zhome").onclick = () => { const h = homeCam(); zoomTo(h.x, h.y, h.z, 900); };+let scrubbing = false;+const scrubTo = (e) => { const r = hist.getBoundingClientRect(); setTime(T0 + clamp((e.clientX - r.left) / r.width, 0, 1) * (T1 - T0)); };+track.addEventListener("pointerdown", (e) => { pause(); scrubbing = true; track.setPointerCapture(e.pointerId); scrubTo(e); });+track.addEventListener("pointermove", (e) => { if (scrubbing) scrubTo(e); });+track.addEventListener("pointerup", () => { scrubbing = false; });+$("playBtn").onclick = () => S.playing ? pause() : playLoop();+addEventListener("keydown", (e) => { if (e.key === " ") { e.preventDefault(); S.playing ? pause() : playLoop(); } if (e.key === "Escape") { S.sel = null; S.follow = false; dirty = true; panels(true); }+ if (e.key === "+" || e.key === "=") $("zin").onclick(); if (e.key === "-") $("zout").onclick(); if (e.key === "ArrowRight") setTime(S.t + 10); if (e.key === "ArrowLeft") setTime(S.t - 10); });++function setTime(t){ S.t = clamp(t, T0, T1 - .01); dirty = true; panels(); }+let playRaf = 0;+function playLoop(){ if (S.t >= T1 - 1) S.t = T0; S.playing = true; document.body.classList.add("playing"); let last = performance.now();+ const step = (now) => { if (!S.playing) return; setTime(S.t + (now - last) / 1000 * 3); last = now; if (S.t >= T1 - .02) return pause(); playRaf = requestAnimationFrame(step); }; playRaf = requestAnimationFrame(step); }+function pause(){ S.playing = false; cancelAnimationFrame(playRaf); document.body.classList.remove("playing"); panels(true); }++// Tweens: one at a time; any manual input cancels.+function animate(ms, fn){ cancelAnim(); return new Promise((ok) => { if (REDUCED || ms <= 0) { fn(1); dirty = true; ok(); return; } const t0 = performance.now(); const a = { ok };+ const step = (now) => { if (S.anim !== a) return ok(); const u = clamp((now - t0) / ms, 0, 1); fn(ease(u), u); dirty = true; if (u < 1) a.raf = requestAnimationFrame(step); else { S.anim = null; ok(); } };+ S.anim = a; a.raf = requestAnimationFrame(step); }); }+function cancelAnim(){ if (S.anim) { cancelAnimationFrame(S.anim.raf); const a = S.anim; S.anim = null; a.ok(); } }+function zoomTo(x, y, z, ms){ const x0 = cam.x, y0 = cam.y, z0 = cam.z;+ return animate(ms, (u) => { cam.z = Math.exp(lerp(Math.log(z0), Math.log(z), u)); const cu = 1 - Math.pow(1 - u, 1.6); cam.x = lerp(x0, x, cu); cam.y = lerp(y0, y, cu); }); }++function selectVehicle(id, opts = {}){ const v = typeof id === "number" ? vehicles[id] : id; if (!v) return; S.sel = v; S.follow = opts.follow !== false; dirty = true; panels(true); }+++function frame(){+ if (S.follow && S.sel && !S.anim) { const s = stateOf(S.sel, S.t); if (s) { cam.x = lerp(cam.x, s.x, .12); cam.y = lerp(cam.y, s.y, .12); dirty = true; } }+ if (dirty || S.sel) { draw(); dirty = false; }+ if (S.anim || S.playing) panels();+ requestAnimationFrame(frame);+}+addEventListener("resize", resize);+(async () => { await document.fonts.ready;+ resize(); Object.assign(cam, homeCam()); panels(true); draw(); requestAnimationFrame(() => { document.documentElement.dataset.ready = "1"; }); requestAnimationFrame(frame); })();+</script>+</body>+</html>diff --git a/server/local-apps/starters/ledger.html b/server/local-apps/starters/ledger.htmlnew file mode 100644index 0000000000..689b909f99--- /dev/null+++ b/server/local-apps/starters/ledger.html@@ -0,0 +1,328 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<title>Ledger · household & studio accounts</title>+<style>+:root{--paper:#f5efe4;--paper2:#efe7d8;--ink:#2b2118;--ink2:#5d4f41;--ink3:#8a7b68;--rule:#d9ccb8;--rule2:#e6dccb;--terra:#c4572e;--over:#b23a1f;+ --serif:ui-serif,"Iowan Old Style","Palatino Linotype",Palatino,Georgia,serif;--text:ui-serif,"Iowan Old Style","Palatino Linotype",Palatino,Georgia,serif;--gx:clamp(36px,2.9vw,56px)}+*{box-sizing:border-box}html,body{margin:0;height:100%;background:var(--paper);color:var(--ink);overflow:hidden}+body{font:16px/1.45 var(--text);font-variant-numeric:lining-nums tabular-nums;-webkit-font-smoothing:antialiased;+ background-image:radial-gradient(rgba(120,90,50,.045) 1px,transparent 1px);background-size:3px 3px}+.page{position:absolute;inset:0;padding:0 var(--gx) 28px;display:grid;grid-template-rows:auto auto 1fr;gap:0}+/* masthead */+.mast{display:grid;grid-template-columns:auto 1fr auto;align-items:end;gap:32px;padding:26px 0 14px;border-bottom:2px solid var(--ink)}+.mast h1{margin:0;font:400 clamp(44px,3.4vw,62px)/.9 var(--serif);font-variation-settings:"opsz" 144;letter-spacing:-.025em}+.mast h1 i{font-weight:300;color:var(--terra)}+.mast .dek{font:italic 17px/1.35 var(--text);color:var(--ink2);padding-bottom:5px;max-width:560px}+.mast .meta{display:flex;align-items:center;gap:22px;padding-bottom:6px;font:13px var(--text);color:var(--ink3)}+.sc{font:600 11px/1 var(--text);letter-spacing:.14em;text-transform:uppercase;color:var(--ink3)}+.years{display:flex;gap:2px;border:1px solid var(--rule);border-radius:2px;padding:2px}+.years b,.years span{font:500 13px var(--text);padding:4px 10px;cursor:pointer}.years b{background:var(--ink);color:var(--paper);font-weight:500}+.sample{border:1px solid var(--ink3);color:var(--ink2);padding:5px 8px 4px;border-radius:2px}+.subbar{display:flex;gap:28px;padding:8px 0;border-bottom:1px solid var(--rule);font:13px var(--text);color:var(--ink3)}+.subbar b{color:var(--ink);font-weight:500}+/* grid */+.body{display:grid;grid-template-columns:1.6fr .85fr;grid-template-rows:minmax(0,40fr) minmax(0,60fr);gap:0 0;min-height:0}+.cell{position:relative;min-height:0;padding:18px 0 0}+.cell+.cell{}+.hd{display:flex;align-items:baseline;justify-content:space-between;gap:16px;margin-bottom:8px}+.hd h2{margin:0;font:400 clamp(22px,1.55vw,28px)/1.1 var(--serif);font-variation-settings:"opsz" 72;letter-spacing:-.01em}+.hd h2 em{font-style:italic;color:var(--ink2)}+.hd .note{font:italic 14px var(--text);color:var(--ink3)}+.river{grid-column:1;grid-row:1;border-right:1px solid var(--rule);padding-right:32px}+.figs{grid-column:2;grid-row:1;padding-left:32px}+.lower{grid-column:1/3;grid-row:2;display:grid;grid-template-columns:1.25fr .8fr 1fr;border-top:1px solid var(--rule);margin-top:14px;min-height:0}+.lower>section{min-height:0;padding:18px 32px 0;border-left:1px solid var(--rule);display:flex;flex-direction:column}+.lower>section:first-child{padding-left:0;border-left:0}.lower>section:last-child{padding-right:0}+svg text{font-family:var(--text)}+/* figures */+.big{font:300 clamp(64px,5.3vw,100px)/.92 var(--serif);font-variation-settings:"opsz" 144;letter-spacing:-.035em;margin:2px 0 6px}+.big small{font-size:.42em;letter-spacing:-.01em;color:var(--ink2);margin-right:4px;vertical-align:.55em}+.lede{font:italic 19px/1.4 var(--text);color:var(--ink2);margin:0 0 14px;max-width:440px}.lede b{font-style:normal;color:var(--ink);font-weight:600}+.trio{display:grid;grid-template-columns:repeat(3,1fr);border-top:1px solid var(--rule);border-bottom:1px solid var(--rule)}+.trio div{padding:10px 14px 10px 0}.trio div+div{padding-left:14px;border-left:1px solid var(--rule)}+.trio .v{font:400 clamp(22px,1.6vw,30px)/1.15 var(--serif);letter-spacing:-.01em;margin-top:6px}+.trio .d{font:13px var(--text);color:var(--ink3)}+.spark{margin-top:12px}+/* treemap */+.tm-crumbs{display:flex;gap:8px;align-items:baseline;font:14px var(--text);color:var(--ink3)}.tm-crumbs a{color:var(--ink2);cursor:pointer;text-decoration:underline;text-decoration-color:var(--rule);text-underline-offset:3px}+.tm-crumbs b{color:var(--ink);font-weight:500}+.tm{position:relative;flex:1;min-height:0;margin:6px 0 24px;overflow:hidden}+.tile{position:absolute;left:0;top:0;overflow:hidden;cursor:pointer;color:#fff8ef;padding:10px 12px;transform-origin:0 0;will-change:transform,opacity;border:1px solid var(--paper)}+.tile .n{font:400 18px/1.1 var(--serif);letter-spacing:-.005em;white-space:nowrap}.tile .a{font:500 14px/1.3 var(--text);opacity:.9;margin-top:4px}.tile .p{font:italic 13px var(--text);opacity:.75}+.tile.sm .n{font-size:14px}.tile.sm .a{font-size:12px}.tile.xs .n,.tile.xs .a,.tile.xs .p{display:none}+.tile:hover{filter:brightness(1.06)}+/* compare */+.cmp{flex:1;min-height:0}+/* envelopes */+.env{display:grid;grid-template-columns:118px 1fr 150px;align-items:center;gap:6px 14px;padding:7px 0}+.env .nm{font:400 17px var(--serif)}.env .st{font:13.5px var(--text);text-align:right;color:var(--ink2)}.env .st.over{color:var(--over);font-weight:600}+.env .track{position:relative;height:26px;border:1px solid var(--rule);background:var(--paper2);border-radius:2px;cursor:ew-resize;touch-action:none}+.env .fill{position:absolute;left:0;top:0;bottom:0;border-radius:1px}+.env .cap{position:absolute;top:-5px;bottom:-5px;width:2px;background:var(--ink);margin-left:-1px}+.env .cap::after{content:"";position:absolute;left:-5px;top:-6px;width:12px;height:12px;border-radius:50%;background:var(--paper);border:2px solid var(--ink)}+.env .cap span{position:absolute;bottom:-20px;left:50%;transform:translateX(-50%);font:12px var(--text);color:var(--ink3);white-space:nowrap}+#rec{flex:1 1 0;min-height:0;overflow:hidden}+.rec{display:grid;grid-template-columns:10px 1fr auto auto;gap:4px 12px;align-items:center;padding:7px 0;border-bottom:1px solid var(--rule2);font:15px var(--text)}+.rec i{width:8px;height:8px;border-radius:50%}.rec .m{font-family:var(--serif);font-size:16px}.rec .am{text-align:right}+.rec .ticks{display:flex;gap:2px}.rec .ticks u{display:block;width:5px;height:11px;background:var(--rule);text-decoration:none}.rec .ticks u.on{background:var(--ink2)}+.rec .nx{grid-column:2/5;font:italic 12.5px var(--text);color:var(--ink3);margin-top:-3px}+.foot{position:absolute;left:var(--gx);right:var(--gx);bottom:8px;display:flex;justify-content:space-between;font:italic 12px var(--text);color:var(--ink3)}+@media (max-width:1600px){.hd h2{font-size:20px;white-space:nowrap}.big{font-size:58px!important}.lede{font-size:15px!important;margin-bottom:8px}.trio .sc{letter-spacing:.05em;font-size:10px;white-space:nowrap}.trio .v{font-size:21px}.trio .d{display:none}+ .env{grid-template-columns:92px 1fr 132px;gap:4px 10px}.env .nm{font-size:15px}.env .st{font-size:12px}.mast .dek{font-size:15px}.hd .note{font-size:12px}#riverNote span{margin-left:8px!important;font-size:12px!important}}+@media (max-height:950px){.env{padding:4px 0}.rec{padding:5px 0}.big{font-size:64px}.lede{font-size:16px;margin-bottom:8px}}+</style>+</head>+<body>+<div class="page">+ <header class="mast">+ <h1>Ledger<i>.</i></h1>+ <p class="dek">The household and the print studio, kept in one book. Three years of every card payment, invoice and sale, read in plain words.</p>+ <div class="meta"><span class="sample sc">Sample data</span><div class="years"><span>2024</span><span>2025</span><b>2026</b><span>All</span></div></div>+ </header>+ <div class="subbar" id="subbar"></div>+ <div class="body">+ <section class="cell river"><div class="hd"><h2>The river <em>— in above, out below</em></h2><span class="note" id="riverNote"></span></div><svg id="river"></svg></section>+ <section class="cell figs" id="figs"></section>+ <div class="lower">+ <section><div class="hd"><h2>Where it went <em>in 2026</em></h2><div class="tm-crumbs" id="crumbs"></div></div><div class="tm" id="tm"></div></section>+ <section><div class="hd"><h2 id="cmpTitle">November, <em>a year apart</em></h2></div><svg class="cmp" id="cmp"></svg></section>+ <section><div class="hd"><h2>Envelopes <em>for November</em></h2><span class="note">drag a pin to re-budget</span></div><div id="env"></div>+ <div class="hd" style="margin-top:16px"><h2>Recurring <em>found in the book</em></h2><span class="note" id="recNote"></span></div><div id="rec"></div></section>+ </div>+ </div>+</div>+<div class="foot"><span id="footL"></span><span>Sample data, generated in this page from one seed · no account is connected</span></div>+<script>+"use strict";+// ——————————————————— data: three years of a household plus a small online print studio ———————————————————+function mulberry32(a){return function(){a|=0;a=a+0x6D2B79F5|0;let t=Math.imul(a^a>>>15,1|a);t=t+Math.imul(t^t>>>7,61|t)^t;return((t^t>>>14)>>>0)/4294967296}}+const rnd = mulberry32(2024), R = (a, b) => a + (b - a) * rnd(), pick = (a) => a[Math.floor(rnd() * a.length)];+const REDUCED = matchMedia("(prefers-reduced-motion: reduce)").matches;+const D0 = Date.UTC(2023, 11, 1), DAYS = 1096, MONTHS = 36;+const CAT = {+ Home: { c: "#8c3b2a" }, Studio: { c: "#7a4e6d" }, Groceries: { c: "#c8743a" }, Dining: { c: "#d9a441" }, Transport: { c: "#6f8f72" },+ Travel: { c: "#4f7a8a" }, Health: { c: "#97a47a" }, Subscriptions: { c: "#b98b73" }, Gifts: { c: "#a69c8d" },+};+const INC = { Salary: "#2f4a3a", "Shop sales": "#5f8a6c", Interest: "#a9bfa5" };+const tx = []; // [day, amount (negative = out), category, sub, merchant]+const add = (d, amt, cat, sub, m) => tx.push([d, Math.round(amt * 100) / 100, cat, sub, m]);+const dateOf = (d) => new Date(D0 + d * 864e5);+for (let d = 0; d < DAYS; d++) {+ const dt = dateOf(d), dow = dt.getUTCDay(), dom = dt.getUTCDate(), mon = dt.getUTCMonth(), yr = dt.getUTCFullYear(), m = (yr - 2023) * 12 + mon - 11;+ const wk = dow > 0 && dow < 6, xmas = mon === 11 || (mon === 10 && dom > 15), summer = mon >= 5 && mon <= 7;+ // Studio: online print sales, many small orders a day, a Christmas rush and a slow summer.+ const orders = Math.round((5.5 + m * .11) * (xmas ? 2.4 : summer ? .75 : 1) * (dow === 0 ? 1.25 : 1) * R(.7, 1.3));+ for (let o = 0; o < orders; o++) add(d, R(9, 24) * (rnd() < .18 ? R(2, 4) : 1), "Income", "Shop sales", pick(["Print order", "Print order", "Print order", "Gift card", "Framed print"]));+ if (dow === 2) add(d, -orders * 7 * R(6.6, 7.6), "Studio", "Printing", pick(["Paperhaus Print", "Paperhaus Print", "Linden Giclée"]));+ if (wk) add(d, -orders * 1.4 * R(2.6, 3.4), "Studio", "Postage", "Parcelway");+ if (dom === 3) add(d, -(5.5 + m * .11) * 30 * 22 * .029, "Studio", "Card fees", "Tillpoint");+ if (dom === 5) { add(d, -24, "Studio", "Software", "Inkwell Pro"); add(d, -16, "Studio", "Software", "Framewise"); add(d, -9, "Studio", "Software", "Hostgrove"); }+ if (dom === 1) add(d, -(m < 13 ? 180 : 210), "Studio", "Co-working", "The Loft Desk");+ if (rnd() < .012) add(d, -R(40, 260), "Studio", "Equipment", pick(["Northlight Supply", "Bench & Bevel"]));+ if (yr === 2025 && mon === 2 && dom === 14) add(d, -1450, "Studio", "Equipment", "Northlight Supply");+ // Salary, with a raise in April 2025, and interest.+ if (dom === 25) add(d, yr > 2025 || (yr === 2025 && mon >= 3) ? 3920 : 3480, "Income", "Salary", "Northfold Agency");+ if (dom === 28) add(d, 18 + m * 1.9, "Income", "Interest", "Saltmarsh Savings");+ // Home.+ if (dom === 1) add(d, -(yr >= 2026 ? 1720 : 1650), "Home", "Rent", "Larchmont Lettings");+ if (dom === 8) add(d, -(68 + 120 * (Math.cos((mon + .5) / 12 * 6.283) * .5 + .5)) * R(.92, 1.08), "Home", "Energy", "Brightwater Energy");+ if (dom === 12 && mon % 3 === 0) add(d, -R(96, 118), "Home", "Water", "Cleartide Water");+ if (dom === 15) add(d, -38, "Home", "Broadband", "Fernline");+ if (dom === 2 && (mon < 1 || mon > 2)) add(d, -148, "Home", "Council tax", "Borough of Ashby");+ if (rnd() < .02) add(d, -R(15, 140), "Home", "Repairs", pick(["Holloway & Sons", "Fixit Depot"]));+ if (yr === 2025 && mon === 8 && (dom === 4 || dom === 26)) add(d, -4200, "Home", "Repairs", "Holloway & Sons");+ // Groceries, dining, coffee.+ if (rnd() < (dow === 6 ? .9 : .28)) add(d, -R(28, 118), "Groceries", "Supermarket", pick(["Pantry & Co", "Pantry & Co", "Greenleaf Market"]));+ if (rnd() < .55) add(d, -R(2.5, 14), "Groceries", "Top-ups", pick(["Corner Larder", "Hollis Bakery", "Corner Larder"]));+ if (wk && rnd() < .78) add(d, -R(2.8, 4.4), "Dining", "Coffee", pick(["Café Mira", "Café Mira", "Small Batch"]));+ if (rnd() < (dow >= 5 || dow === 0 ? .55 : .2) * (xmas ? 1.5 : 1)) add(d, -R(16, 92), "Dining", "Restaurants", pick(["Ember Room", "Noodle Lane", "Sundry Kitchen", "The Gannet"]));+ // Transport.+ if (dom === 1) add(d, -86, "Transport", "Rail pass", "Metroline");+ if (rnd() < .1) add(d, -R(44, 72), "Transport", "Fuel", "Northway Fuel");+ if (rnd() < .06) add(d, -R(4, 18), "Transport", "Parking", "ParkSmart");+ // Health and subscriptions.+ if (dom === 6) add(d, -42, "Health", "Gym", "Forge Gym");+ if (rnd() < .025) add(d, -R(6, 38), "Health", "Pharmacy", "Bellwort Pharmacy");+ if (dom === 9) add(d, -10.99, "Subscriptions", "Streaming", "Reelhouse");+ if (dom === 17) add(d, -11.99, "Subscriptions", "Music", "Tonebox");+ if (dom === 20) add(d, -8, "Subscriptions", "News", "Daily Courant");+ if (mon === 2 && dom === 10) add(d, -79, "Subscriptions", "Storage", "Cloudbox");+ // Travel: trips with flights, stays and spending.+ for (const [y, mo, d1, len, big] of [[2024, 3, 6, 5, 0], [2024, 7, 9, 10, 1], [2025, 1, 14, 4, 0], [2025, 6, 18, 14, 1], [2026, 4, 2, 6, 0], [2026, 7, 12, 9, 1]]) {+ if (yr === y && mon === mo - (dom < d1 - 40 ? 0 : 0) && dom === d1) { add(d - 40, -R(180, 340) * (big ? 2 : 1), "Travel", "Flights", "Skylark Air"); add(d, -R(90, 140) * len, "Travel", "Stays", pick(["Harbour Inn", "Casa Lume"])); }+ if (yr === y && mon === mo && dom >= d1 && dom < d1 + len) add(d, -R(25, 110), "Travel", "Spending", pick(["Local cafés", "Markets", "Museums"]));+ }+ // Gifts, heavy in December.+ if (rnd() < (mon === 11 ? .28 : .03)) add(d, -R(15, 120), "Gifts", "Presents", pick(["Thimble & Twine", "Booknook", "Lark Gifts"]));+}+tx.sort((a, b) => a[0] - b[0]);+const monthOf = (d) => { const dt = dateOf(d); return (dt.getUTCFullYear() - 2023) * 12 + dt.getUTCMonth() - 11; };+const MNAME = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];+const mLabel = (m) => `${MNAME[(m + 11) % 12]} ${2023 + Math.floor((m + 11) / 12)}`;+// Month × category totals.+const inc = Object.fromEntries(Object.keys(INC).map((k) => [k, new Float64Array(MONTHS)]));+const out = Object.fromEntries(Object.keys(CAT).map((k) => [k, new Float64Array(MONTHS)]));+for (const [d, a, c, s] of tx) { const m = monthOf(d); if (c === "Income") inc[s][m] += a; else out[c][m] += -a; }+const sum = (o, m) => Object.values(o).reduce((s, arr) => s + arr[m], 0);+const fmt0 = new Intl.NumberFormat("en-GB", { maximumFractionDigits: 0 }), money = (v) => `£${fmt0.format(Math.round(v))}`;+const kfmt = (v) => Math.abs(v) >= 1000 ? `£${(v / 1000).toFixed(Math.abs(v) >= 1e5 ? 0 : 1)}k` : money(v);+const $ = (id) => document.getElementById(id);+const NS = "http://www.w3.org/2000/svg";+const el = (tag, attrs = {}, parent) => { const e = document.createElementNS(NS, tag); for (const k in attrs) e.setAttribute(k, attrs[k]); parent && parent.appendChild(e); return e; };+const ease = (t) => t < .5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;+function tween(ms, fn){ return new Promise((ok) => { if (REDUCED) { fn(1); return ok(); } const t0 = performance.now(); const step = (now) => { const u = Math.min(1, (now - t0) / ms); fn(ease(u), u); if (u < 1) requestAnimationFrame(step); else ok(); }; requestAnimationFrame(step); }); }+const NOW_M = 35, CMP_M = 23;+const cmpOut = Object.fromEntries(Object.keys(CAT).map((c) => [c, 0])); for (const t of tx) if (t[2] !== "Income" && monthOf(t[0]) === CMP_M && dateOf(t[0]).getUTCDate() <= 26) cmpOut[t[2]] -= t[1];++// ——————————————————— masthead strip, key figures ———————————————————+let totIn = 0, totOut = 0; for (let m = 0; m < MONTHS; m++) { totIn += sum(inc, m); totOut += sum(out, m); }+$("subbar").innerHTML = `<span><b>${fmt0.format(tx.length)}</b> entries</span><span><b>36</b> months, Dec 2023 – Nov 2026</span><span><b>2</b> accounts · household, studio</span><span><b>${Object.keys(CAT).length}</b> categories, <b>${new Set(tx.map((t) => t[4])).size}</b> payees</span><span style="margin-left:auto">Book closed 26 Nov 2026</span>`;+$("footL").textContent = `${fmt0.format(tx.length)} entries · every total on this page is summed from them`;+function figs(){+ const net = totIn - totOut, rate = net / totIn, nIn = sum(inc, NOW_M), nOut = sum(out, NOW_M), pOut = Object.values(cmpOut).reduce((a, b) => a + b, 0);+ $("figs").innerHTML = `<div class="hd"><h2>Three years, <em>in one line</em></h2></div>+ <div class="sc">Kept, after everything</div><div class="big"><small>£</small>${fmt0.format(Math.round(net))}</div>+ <p class="lede">Of every pound that came in, <b>${Math.round(rate * 100)}p</b> stayed. The studio paid for the roof in September 2025, and still left the year ahead.</p>+ <div class="trio"><div><div class="sc">In, November</div><div class="v">${money(nIn)}</div><div class="d">to the 26th</div></div>+ <div><div class="sc">Out, November</div><div class="v">${money(nOut)}</div><div class="d">${nOut > pOut ? "+" : "−"}${Math.abs(Math.round((nOut / pOut - 1) * 100))}% on 1–26 Nov 2025</div></div>+ <div><div class="sc">Studio margin</div><div class="v">${Math.round((1 - out.Studio[NOW_M] / inc["Shop sales"][NOW_M]) * 100)}%</div><div class="d">sales less studio costs</div></div></div>+`;+}++// ——————————————————— the river ———————————————————+let riverGeom = null;+function smoothPath(xs, ys){ let d = `M${xs[0]},${ys[0]}`; for (let i = 0; i < xs.length - 1; i++) { const x0 = xs[Math.max(0, i - 1)], y0 = ys[Math.max(0, i - 1)], x1 = xs[i], y1 = ys[i], x2 = xs[i + 1], y2 = ys[i + 1], x3 = xs[Math.min(xs.length - 1, i + 2)], y3 = ys[Math.min(xs.length - 1, i + 2)];+ d += `C${x1 + (x2 - x0) / 6},${y1 + (y2 - y0) / 6} ${x2 - (x3 - x1) / 6},${y2 - (y3 - y1) / 6} ${x2},${y2}`; } return d; }+function river(){+ const sv = $("river"); sv.innerHTML = ""; const w = sv.parentNode.clientWidth - 32, h = sv.parentNode.clientHeight - 62; sv.setAttribute("width", w); sv.setAttribute("height", h);+ const L = 58, Rr = w - 8, X = (m) => L + m / (MONTHS - 1) * (Rr - L);+ let mxI = 0, mxO = 0; for (let m = 0; m < MONTHS; m++) { mxI = Math.max(mxI, sum(inc, m)); mxO = Math.max(mxO, sum(out, m)); }+ const top = 40, bottom = h - 26, y0 = top + (bottom - top) * mxI / (mxI + mxO), k = (bottom - top) / (mxI + mxO), xs = [...Array(MONTHS).keys()].map(X);+ riverGeom = { X, y0, k, top, bottom, w, h };+ // gridlines+ for (let v = -20000; v <= 30000; v += 10000) { const y = y0 - v * k; if (y < top - 4 || y > bottom + 4) continue; el("line", { x1: L, x2: Rr, y1: y, y2: y, stroke: v ? "#e6dccb" : "#2b2118", "stroke-width": v ? 1 : 1.2 }, sv);+ const t = el("text", { x: L - 10, y: y + 4, "text-anchor": "end", "font-size": 12.5, fill: "#8a7b68" }, sv); t.textContent = v ? `${v > 0 ? "" : "−"}£${Math.abs(v / 1000)}k` : "£0"; }+ const stack = (layers, sign) => { const base = new Float64Array(MONTHS); for (const [name, arr, col] of layers) { const ysA = [...base].map((b) => y0 - sign * b * k), ysB = [...base].map((b, m) => y0 - sign * (b + arr[m]) * k);+ const d = smoothPath(xs, ysB) + "L" + smoothPath([...xs].reverse(), [...ysA].reverse()).slice(1) + "Z"; el("path", { d, fill: col, opacity: .92, "data-layer": name }, sv); for (let m = 0; m < MONTHS; m++) base[m] += arr[m]; } };+ stack(Object.entries(INC).map(([n, c]) => [n, inc[n], c]), 1);+ stack(Object.keys(CAT).map((n) => [n, out[n], CAT[n].c]), -1);+ for (let m = 1; m < MONTHS; m++) if ((m + 11) % 12 === 0) { el("line", { x1: X(m), x2: X(m), y1: top, y2: bottom, stroke: "rgba(43,33,24,.25)", "stroke-dasharray": "2 3" }, sv); const t = el("text", { x: X(m) + 6, y: bottom + 18, "font-size": 13, fill: "#5d4f41", "font-weight": 600 }, sv); t.textContent = 2023 + Math.floor((m + 11) / 12); }+ for (let m = 0; m < MONTHS; m += 3) if ((m + 11) % 12 !== 0 && (X(3) - X(0) > 80 || (m + 11) % 12 !== 2)) { const t = el("text", { x: X(m), y: bottom + 18, "font-size": 12, fill: "#8a7b68", "text-anchor": "middle" }, sv); t.textContent = MNAME[(m + 11) % 12]; }+ // annotations+ const note = (m, val, text, dy, dx = 5, anchor = "start") => { const x = X(m), y = y0 - val * k; el("line", { x1: x, x2: x, y1: y, y2: y + dy, stroke: "#2b2118", "stroke-width": .8 }, sv); el("circle", { cx: x, cy: y, r: 2.6, fill: "#2b2118" }, sv);+ const t = el("text", { x: x + dx, y: y + dy + (dy < 0 ? -4 : 13), "text-anchor": anchor, "font-size": 13.5, "font-style": "italic", fill: "#2b2118" }, sv); t.textContent = text; };+ note(12, sum(inc, 12), "Christmas rush in the shop", -14);+ note(16, sum(inc, 16), "The raise, April", -22);+ note(21, -sum(out, 21), "A new roof, £8,400", -10, -10, "end");+ note(31, -sum(out, 31), "Two weeks by the sea", 22, -6, "end");+ // cursor+ const cur = el("g", { id: "rcur", opacity: 0 }, sv); el("line", { x1: 0, x2: 0, y1: top - 6, y2: bottom, stroke: "#c4572e", "stroke-width": 1.4 }, cur);+ el("rect", { x: -70, y: top - 36, width: 140, height: 22, rx: 2, fill: "#2b2118" }, cur); el("text", { id: "rcurt", x: 0, y: top - 21, "text-anchor": "middle", "font-size": 12.5, fill: "#f5efe4" }, cur);+ const ca = el("g", { id: "rcurA", opacity: 0 }, sv); el("line", { x1: 0, x2: 0, y1: top - 6, y2: bottom, stroke: "#8a7b68", "stroke-width": 1, "stroke-dasharray": "3 3" }, ca);+ sv.onpointermove = (e) => { const r = sv.getBoundingClientRect(); const m = Math.round((e.clientX - r.left - L) / (Rr - L) * (MONTHS - 1)); if (m >= 0 && m < MONTHS) cursor(m); };+}+function riverLegend(){ $("riverNote").innerHTML = [...Object.entries(INC), ["Home", CAT.Home.c], ["Studio", CAT.Studio.c], ["Groceries", CAT.Groceries.c], ["Travel", CAT.Travel.c], ["the rest", "#b5a691"]].map(([n, c]) => `<span style="white-space:nowrap;margin-left:14px;font-style:normal;font-size:13px;color:#5d4f41"><i style="display:inline-block;width:10px;height:10px;background:${c};margin-right:6px;vertical-align:-1px"></i>${n}</span>`).join(""); }+function cursor(mf, which = "rcur"){ if (!riverGeom) return; const m = Math.max(0, Math.min(MONTHS - 1, mf)); const g = $(which); g.setAttribute("opacity", 1); g.setAttribute("transform", `translate(${riverGeom.X(m)},0)`);+ if (which === "rcur") { const mi = Math.round(m); $("rcurt").textContent = `${mLabel(mi)} · net ${kfmt(sum(inc, mi) - sum(out, mi))}`; } }++// ——————————————————— treemap with drill-down ———————————————————+function squarify(items, x, y, w, h){ // items: [{v}], returns rects in place+ const total = items.reduce((s, i) => s + i.v, 0), out = []; let rest = items.slice().sort((a, b) => b.v - a.v), scale = w * h / total;+ while (rest.length) { const short = Math.min(w, h); let row = [], best = Infinity;+ for (const it of rest) { const r = [...row, it], s = r.reduce((a, b) => a + b.v * scale, 0), worst = Math.max(...r.map((q) => Math.max(short * short * q.v * scale / (s * s), s * s / (short * short * q.v * scale)))); if (worst > best) break; best = worst; row = r; }+ const s = row.reduce((a, b) => a + b.v * scale, 0), thick = s / short; let off = 0;+ for (const it of row) { const len = it.v * scale / thick; if (w >= h) out.push({ ...it, x, y: y + off, w: thick, h: len }); else out.push({ ...it, x: x + off, y, w: len, h: thick }); off += len; }+ if (w >= h) { x += thick; w -= thick; } else { y += thick; h -= thick; } rest = rest.slice(row.length); }+ return out; }+const yearTx = tx.filter((t) => t[2] !== "Income" && monthOf(t[0]) >= 25);+function nodeAt(path){ // children of a path [] / [cat] / [cat, sub]+ const map = new Map();+ for (const t of yearTx) { if (path[0] && t[2] !== path[0]) continue; if (path[1] && t[3] !== path[1]) continue; const key = path.length === 0 ? t[2] : path.length === 1 ? t[3] : t[4]; map.set(key, (map.get(key) || 0) - t[1]); }+ return [...map].map(([name, v]) => ({ name, v })); }+const TM = { path: [], tiles: [] };+const tmTotal = () => yearTx.reduce((s, t) => s - t[1], 0);+function shade(hex, f){ const n = parseInt(hex.slice(1), 16), r = n >> 16, g = (n >> 8) & 255, b = n & 255; const m = (c) => Math.round(f > 0 ? c + (255 - c) * f : c * (1 + f)); return `rgb(${m(r)},${m(g)},${m(b)})`; }+function layoutTM(path){ const box = $("tm"), W = box.clientWidth, H = box.clientHeight; const items = nodeAt(path), tot = items.reduce((s, i) => s + i.v, 0);+ return squarify(items, 0, 0, W, H).map((r, i) => ({ ...r, share: r.v / tot, color: path.length ? shade(CAT[path[0]].c, -.18 + (i % 5) * .1) : CAT[r.name].c })); }+function tileEl(r){ const d = document.createElement("div"); d.className = "tile"; d.style.width = `${r.w}px`; d.style.height = `${r.h}px`; d.style.background = r.color; const a = r.w * r.h;+ if (a < 5200 || r.w < 70 || r.h < 40) d.classList.add("xs"); else if (a < 22000 || r.w < 130) d.classList.add("sm");+ d.innerHTML = `<div class="n">${r.name}</div><div class="a">${money(r.v)}</div><div class="p">${(r.share * 100).toFixed(r.share < .1 ? 1 : 0)}%</div>`;+ d.style.transform = `translate(${r.x}px,${r.y}px)`; d.title = `${r.name}: ${money(r.v)}`; d.onclick = () => { if (TM.path.length < 2) drillInto(r.name); }; return d; }+function renderTM(path){ const box = $("tm"); box.innerHTML = ""; TM.path = path; TM.tiles = layoutTM(path).map((r) => { const d = tileEl(r); box.appendChild(d); return { r, d }; }); crumbs(); }+function crumbs(){ const p = TM.path; const parts = [`<a data-l="0">All spending</a>`]; p.forEach((n, i) => parts.push(i === p.length - 1 ? `<b>${n}</b>` : `<a data-l="${i + 1}">${n}</a>`));+ const total = p.length ? nodeAt(p).reduce((s, i) => s + i.v, 0) : tmTotal();+ $("crumbs").innerHTML = parts.join(" <span>›</span> ") + ` <span style="margin-left:10px;font-style:italic">${money(total)}</span>`;+ $("crumbs").querySelectorAll("a").forEach((a) => a.onclick = () => { renderTM(TM.path.slice(0, +a.dataset.l)); }); }+async function drillInto(name, ms = 1300){+ const from = TM.tiles.find((t) => t.r.name === name); if (!from) return; const box = $("tm"), W = box.clientWidth, H = box.clientHeight;+ const next = layoutTM([...TM.path, name]); const sx = from.r.w / W, sy = from.r.h / H;+ const kids = next.map((r) => { const d = tileEl(r); d.style.opacity = 0; box.appendChild(d); return { r, d }; });+ const olds = TM.tiles;+ await tween(ms, (u) => {+ // The parent tile grows to fill the box; its children ride inside it; siblings are pushed out and fade.+ const px = from.r.x * (1 - u), py = from.r.y * (1 - u), pw = from.r.w + (W - from.r.w) * u, ph = from.r.h + (H - from.r.h) * u, kx = pw / from.r.w, ky = ph / from.r.h;+ for (const t of olds) { const cx = (t.r.x - from.r.x) * kx + px, cy = (t.r.y - from.r.y) * ky + py; t.d.style.transform = `translate(${cx}px,${cy}px) scale(${kx},${ky})`; t.d.style.opacity = t === from ? 1 - Math.min(1, u * 1.6) : 1 - u; }+ for (const k of kids) { const x = px + k.r.x * pw / W, y = py + k.r.y * ph / H; k.d.style.transform = `translate(${x}px,${y}px) scale(${pw / W},${ph / H})`; k.d.style.opacity = Math.min(1, u * 1.8); }+ });+ for (const t of olds) t.d.remove(); for (const k of kids) k.d.style.transform = `translate(${k.r.x}px,${k.r.y}px)`;+ TM.path = [...TM.path, name]; TM.tiles = kids; crumbs();+}++// ——————————————————— month comparison ———————————————————+function compare(p = 1){+ const sv = $("cmp"); sv.innerHTML = ""; const w = sv.parentNode.clientWidth - 64, h = sv.parentNode.clientHeight - 70; sv.setAttribute("width", w); sv.setAttribute("height", h);+ const rows = Object.keys(CAT).map((c) => ({ c, a: cmpOut[c], b: out[c][NOW_M] })).sort((x, y) => y.b - x.b);+ const mx = Math.max(...rows.map((r) => Math.max(r.a, r.b))), L = 104, Rr = w - 58, X = (v) => L + Math.sqrt(v / mx) * (Rr - L), rh = Math.min(42, (h - 40) / rows.length);+ for (const v of [100, 1000, 4000]) { const x = X(v); el("line", { x1: x, x2: x, y1: 10, y2: 14 + rh * rows.length, stroke: "#e6dccb" }, sv); const t = el("text", { x, y: 26 + rh * rows.length, "text-anchor": "middle", "font-size": 12, fill: "#8a7b68" }, sv); t.textContent = kfmt(v); }+ rows.forEach((r, i) => { const y = 24 + i * rh, b = r.a + (r.b - r.a) * p;+ const t = el("text", { x: 0, y: y + 5, "font-size": 15, fill: "#2b2118", "font-family": "ui-serif, Georgia, serif" }, sv); t.textContent = r.c;+ el("line", { x1: X(r.a), x2: X(b), y1: y, y2: y, stroke: CAT[r.c].c, "stroke-width": 5, opacity: .5, "stroke-linecap": "round" }, sv);+ el("circle", { cx: X(r.a), cy: y, r: 5, fill: "#f5efe4", stroke: "#8a7b68", "stroke-width": 1.5 }, sv);+ el("circle", { cx: X(b), cy: y, r: 6.5, fill: CAT[r.c].c }, sv);+ const ch = r.a ? (b / r.a - 1) : 0, dt = el("text", { x: w - 2, y: y + 5, "text-anchor": "end", "font-size": 13.5, fill: ch > .15 ? "#b23a1f" : ch < -.15 ? "#3d6b4b" : "#5d4f41", "font-weight": Math.abs(ch) > .15 ? 600 : 400 }, sv);+ dt.textContent = r.a < 1 ? (b > 1 ? "new" : "—") : `${ch >= 0 ? "+" : "−"}${Math.abs(Math.round(ch * 100))}%`; });+ const k = el("g", { transform: `translate(${L},${44 + rh * rows.length})` }, sv); el("circle", { cx: 5, cy: -4, r: 5, fill: "#f5efe4", stroke: "#8a7b68", "stroke-width": 1.5 }, k);+ const a = el("text", { x: 15, y: 0, "font-size": 12.5, fill: "#5d4f41", "font-style": "italic" }, k); a.textContent = "1–26 Nov 2025"; el("circle", { cx: 128, cy: -4, r: 6, fill: "#2b2118" }, k);+ const b2 = el("text", { x: 139, y: 0, "font-size": 12.5, fill: "#5d4f41", "font-style": "italic" }, k); b2.textContent = "1–26 Nov 2026 · √ scale";+}++// ——————————————————— envelopes ———————————————————+const avg6 = (c) => { let s2 = 0; for (let m = NOW_M - 6; m < NOW_M; m++) s2 += out[c][m]; return s2 / 6; };+const ENV_DEFAULT = Object.fromEntries(["Groceries", "Dining", "Transport", "Health", "Subscriptions", "Gifts"].map((c) => [c, Math.round((c === "Dining" ? out[c][NOW_M] * .88 : Math.max(avg6(c) * 1.08, out[c][NOW_M] * 1.12)) / 10) * 10]));+let budgets = { ...ENV_DEFAULT };+const ENV_MAX = Object.fromEntries(Object.keys(ENV_DEFAULT).map((c) => [c, Math.ceil(Math.max(ENV_DEFAULT[c], out[c][NOW_M]) * 1.55 / 50) * 50]));+function envelopes(){+ $("env").innerHTML = Object.keys(ENV_DEFAULT).map((c) => `<div class="env" data-c="${c}"><span class="nm">${c}</span><div class="track"><div class="fill"></div><div class="cap"><span></span></div></div><span class="st"></span></div>`).join("");+ for (const row of $("env").children) { const c = row.dataset.c, tr = row.querySelector(".track");+ const setFrom = (e) => { const r = tr.getBoundingClientRect(); budgets[c] = Math.round(Math.max(10, Math.min(ENV_MAX[c], (e.clientX - r.left) / r.width * ENV_MAX[c])) / 5) * 5; envUpdate(); };+ tr.onpointerdown = (e) => { tr.setPointerCapture(e.pointerId); setFrom(e); tr.onpointermove = setFrom; }; tr.onpointerup = () => { tr.onpointermove = null; }; }+ envUpdate(); }+function envUpdate(){ for (const row of $("env").children) { const c = row.dataset.c, spent = out[c][NOW_M], b = budgets[c], mx = ENV_MAX[c];+ const f = row.querySelector(".fill"), cap = row.querySelector(".cap"), st = row.querySelector(".st"); const over = spent > b;+ f.style.width = `${Math.min(100, spent / mx * 100)}%`; f.style.background = over ? `repeating-linear-gradient(135deg,${CAT[c].c},${CAT[c].c} 5px,${shade(CAT[c].c, .25)} 5px,${shade(CAT[c].c, .25)} 9px)` : CAT[c].c;+ cap.style.left = `${b / mx * 100}%`; cap.querySelector("span").textContent = "";+ st.className = "st" + (over ? " over" : ""); st.innerHTML = (over ? `${money(spent - b)} over` : `${money(b - spent)} left`) + `<span style="color:#8a7b68;font-weight:400"> of ${money(b)}</span>`; } }++// ——————————————————— recurring payments, found by cadence ———————————————————+function recurring(){+ const by = new Map(); for (const t of tx) if (t[1] < 0) { const k = t[4]; if (!by.has(k)) by.set(k, []); by.get(k).push(t); }+ const found = [];+ for (const [m, list] of by) { if (list.length < 6) continue; const gaps = list.slice(1).map((t, i) => t[0] - list[i][0]); const g = gaps.slice().sort((a, b) => a - b)[gaps.length >> 1];+ const amts = list.map((t) => -t[1]), mean = amts.reduce((a, b) => a + b) / amts.length, sd = Math.sqrt(amts.reduce((s, a) => s + (a - mean) ** 2, 0) / amts.length);+ const steady = gaps.filter((x) => Math.abs(x - g) <= 3).length / gaps.length;+ if (g >= 26 && g <= 33 && steady > .8 && sd / mean < .25) found.push({ m, cat: list[0][2], amt: -list[list.length - 1][1], last: list[list.length - 1][0], months: new Set(list.map((t) => monthOf(t[0]))), varies: sd / mean > .03 }); }+ found.sort((a, b) => b.amt - a.amt);+ $("recNote").textContent = `${found.length} monthly, by cadence`;+ $("rec").innerHTML = found.slice(0, 8).map((r) => { const nx = dateOf(r.last + 30.4), ticks = [...Array(12).keys()].map((i) => `<u class="${r.months.has(NOW_M - 11 + i) ? "on" : ""}"></u>`).join("");+ return `<div class="rec"><i style="background:${CAT[r.cat].c}"></i><span class="m">${r.m}</span><span class="ticks" title="last 12 months">${ticks}</span><span class="am">${r.varies ? "≈" : ""}${money(r.amt)}</span><span class="nx">monthly · next ${nx.getUTCDate()} ${MNAME[nx.getUTCMonth()]}${r.varies ? " · amount varies" : ""}</span></div>`; }).join(""); while ($("rec").children.length > 2 && $("rec").getBoundingClientRect().bottom > innerHeight - 34) $("rec").lastElementChild.remove(); }++function renderAll(){ figs(); riverLegend(); river(); renderTM(TM.path); compare(1); envelopes(); recurring(); }+addEventListener("resize", () => renderAll());+(async () => { await document.fonts.ready;+ renderAll(); requestAnimationFrame(() => { document.documentElement.dataset.ready = "1"; }); })();+</script>+</body>+</html>diff --git a/server/local-apps/store.ts b/server/local-apps/store.tsindex 834de3a30b..4b3a575c43 100644--- a/server/local-apps/store.ts+++ b/server/local-apps/store.ts@@ -24,6 +24,8 @@ export interface LocalAppRecord {messageId: string;/** Who saved it, as a person key; absent when it was saved on this computer. */owner?: string;+ /** A starter app: it came with MausBot, from no bot and no chat. */+ sample?: true;versions: LocalAppVersion[];pinnedRev?: number;createdAt: number;@@ -34,14 +36,25 @@ export interface LocalAppRecord {export const localAppsFile = (dataDir: string) => join(dataDir, "local-apps.json");function readRecords(file: string): LocalAppRecord[] {+ return readFile(file) ?? [];+}++/** null when the file is there but isn't one this build reads. */+function readFile(file: string): LocalAppRecord[] | null {+ let text: string;+ try {+ text = readFileSync(file, "utf8");+ } catch (error) {+ return (error as NodeJS.ErrnoException).code === "ENOENT" ? [] : null;+ }try {- const parsed = JSON.parse(readFileSync(file, "utf8")) as { version?: unknown; apps?: unknown };- if (parsed.version !== 1 || !Array.isArray(parsed.apps)) return [];+ const parsed = JSON.parse(text) as { version?: unknown; apps?: unknown };+ if (parsed.version !== 1 || !Array.isArray(parsed.apps)) return null;return parsed.apps.filter((app): app is LocalAppRecord => typeof app?.id === "string" && LOCAL_APP_ID.test(app.id) &&typeof app.name === "string" && typeof app.botId === "string" && typeof app.threadId === "string" && typeof app.messageId === "string" &&Array.isArray(app.versions) && app.versions.length > 0 && app.versions.every((version: LocalAppVersion) => typeof version?.doc === "string" && DOC.test(version.doc) && Number.isInteger(version.rev)));} catch {- return [];+ return null;}}@@ -65,10 +78,14 @@ export function keptVersions(versions: readonly LocalAppVersion[], pinnedRev?: nexport class LocalAppsStore {private records: LocalAppRecord[];private readonly file: string;+ /** False when the file was there but unreadable: it starts empty, and nothing is added for the person. */+ readonly readable: boolean;constructor(dataDir: string) {this.file = localAppsFile(dataDir);- this.records = readRecords(this.file);+ const read = readFile(this.file);+ this.readable = read !== null;+ this.records = read ?? [];}private save(): void {@@ -103,6 +120,14 @@ export class LocalAppsStore {return record;}+ /** After the apps already here, as many as there is room for. */+ append(records: readonly LocalAppRecord[]): void {+ const room = records.filter((record) => !this.get(record.id)).slice(0, Math.max(0, LOCAL_APPS_MAX - this.records.length));+ if (!room.length) return;+ this.records = [...this.records, ...room.map((record) => ({ ...record, versions: keptVersions(record.versions) }))];+ this.save();+ }+update(id: string, change: (record: LocalAppRecord) => LocalAppRecord, now = Date.now()): LocalAppRecord | null {const index = this.records.findIndex((record) => record.id === id);if (index === -1) return null;diff --git a/server/routes/local-apps.test.ts b/server/routes/local-apps.test.tsindex 746ae17539..db74daa8a0 100644--- a/server/routes/local-apps.test.ts+++ b/server/routes/local-apps.test.ts@@ -11,6 +11,7 @@ import { DATA_DIR } from "../config.ts";import type { ModelSelection } from "../contracts.ts";import { json, readBody } from "../harness/http.ts";import { createLocalApps, type LocalApps } from "../local-apps/service.ts";+import { readRemovedStarters, type StarterSource } from "../local-apps/starters.ts";import { localAppDocRefs, localAppsFile } from "../local-apps/store.ts";import { appDocRefs } from "../message-db.ts";import type { RequestAuth } from "../request-auth.ts";@@ -29,12 +30,12 @@ afterEach(async () => {});/** `seen`: which conversations a paired person (x-session) can read; the owner on this computer sees everything. */-async function fixture(seen: (person: string, threadId: string) => boolean = () => true, options: { everything?: boolean; live?: (person: string) => boolean } = {}) {+async function fixture(seen: (person: string, threadId: string) => boolean = () => true, options: { everything?: boolean; live?: (person: string) => boolean; starters?: StarterSource } = {}) {const store = new Store(() => sonnet);const bot = store.createBot({ name: "Scout" });const other = store.createBot({ name: "Other" });const chatApps: ChatApps = createChatApps({ store, dataDir: DATA_DIR, sweeps: false, references: () => [...appDocRefs(), ...localAppDocRefs(DATA_DIR)] });- const localApps: LocalApps = createLocalApps({ chat: store, docs: chatApps.docs, dataDir: DATA_DIR });+ const localApps: LocalApps = createLocalApps({ chat: store, docs: chatApps.docs, dataDir: DATA_DIR, ...(options.starters ? { starters: options.starters } : {}) });closers.push(chatApps, localApps);const routes = [createLocalAppsRoutes({apps: localApps, store,@@ -242,6 +243,22 @@ describe("local apps", () => {expect((await call("DELETE", `/api/local-apps/${bobs}`, undefined, "bob")).body).toEqual({ ok: true });});+ it("shows a starter app to whoever sees everything; only this computer or an admin removes it, and for good", async () => {+ const starters: StarterSource = { apps: [{ id: "la_starter_sample__", name: "Sample", file: "sample.html" }], html: () => "<p>Sample data</p>" };+ const narrow = await fixture(() => true, { starters });+ expect((await narrow.call("GET", "/api/local-apps")).body.apps.map((app: any) => [app.id, app.sample])).toEqual([["la_starter_sample__", true]]);+ expect((await narrow.call("GET", "/api/local-apps", undefined, "ann")).body.apps).toEqual([]);+ expect((await narrow.call("GET", "/api/local-apps/la_starter_sample__/app", undefined, "ann")).status).toBe(404);++ const wide = await fixture(() => true, { everything: true, starters });+ expect((await wide.call("GET", "/api/local-apps", undefined, "bob")).body.apps.map((app: any) => app.id)).toEqual(["la_starter_sample__"]);+ expect((await wide.call("DELETE", "/api/local-apps/la_starter_sample__", undefined, "bob")).status).toBe(403);+ expect((await wide.call("GET", "/api/local-apps/la_starter_sample__/app")).body.srcdoc).toContain("Sample data");+ expect((await wide.call("DELETE", "/api/local-apps/la_starter_sample__")).body).toEqual({ ok: true });+ expect(readRemovedStarters(DATA_DIR)).toEqual(new Set(["la_starter_sample__"]));+ expect((await (await fixture(() => true, { starters })).call("GET", "/api/local-apps")).body.apps).toEqual([]);+ });+it("stops serving a folder app's files once the session that opened it has ended", async () => {let live = true;const { folderPage, save, call, base } = await fixture(() => true, { live: () => live });diff --git a/shared/local-apps.ts b/shared/local-apps.tsindex b70777ed3d..2971395e1e 100644--- a/shared/local-apps.ts+++ b/shared/local-apps.ts@@ -38,6 +38,8 @@ export interface LocalApp {manifest: LocalAppManifest;/** The conversation it came from is still there, so "Go to chat" has somewhere to go. */chat: boolean;+ /** A sample app that came with MausBot: no bot made it and it has no chat (`botId`, `threadId` are empty). */+ sample?: true;}export interface LocalAppsList {diff --git a/src/components/published-apps/LocalAppCard.tsx b/src/components/published-apps/LocalAppCard.tsxindex 299b106324..d1335ad155 100644--- a/src/components/published-apps/LocalAppCard.tsx+++ b/src/components/published-apps/LocalAppCard.tsx@@ -77,7 +77,7 @@ export function LocalAppCard({ app, bot, onOpen, onOpenWindow, onRename, onGoToC}) {const [renaming, setRenaming] = useState(false);const maker = bot?.name ?? app.bot?.name;- const facts = [maker ?? t("localApps.card.botGone"), relativeTime(app.updatedAt)].join(" · ");+ const facts = [maker ?? t(app.sample ? "localApps.card.sample" : "localApps.card.botGone"), relativeTime(app.updatedAt)].join(" · ");const items: SidebarMenuItem[] = [{ key: "rename", label: t("localApps.card.rename"), icon: <Pencil size={16} />, onSelect: () => setRenaming(true) },...(onGoToChat ? [{ key: "chat", label: t("localApps.card.goToChat"), icon: <MessageSquare size={16} />, onSelect: onGoToChat }] : []),diff --git a/src/components/published-apps/LocalAppView.tsx b/src/components/published-apps/LocalAppView.tsxindex 1731627129..2f7b4d5fd4 100644--- a/src/components/published-apps/LocalAppView.tsx+++ b/src/components/published-apps/LocalAppView.tsx@@ -106,7 +106,8 @@ export function LocalAppView({ id, botOf, onBack, onGoToChat, onOpenWindow }: {<div className="flex min-w-0 flex-1 basis-0 items-center gap-2.5">{app && <LocalAppMark app={app} bot={app ? botOf?.(app.botId) : undefined} size="sm" />}<h1 dir="auto" className={cn(TOOL_PAGE_TITLE, "min-w-0 truncate")} title={title}>{title}</h1>- {maker?.name && <span dir="auto" className="shrink-0 truncate text-[13px] text-ink-tertiary max-sm:hidden">{t("localApps.view.by", { bot: maker.name })}</span>}+ {app?.sample ? <span className="shrink-0 truncate text-[13px] text-ink-tertiary max-sm:hidden">{t("localApps.card.sample")}</span>+ : maker?.name && <span dir="auto" className="shrink-0 truncate text-[13px] text-ink-tertiary max-sm:hidden">{t("localApps.view.by", { bot: maker.name })}</span>}{installed && <span className="max-sm:hidden"><InstalledMark /></span>}</div>{app && (@@ -118,7 +119,7 @@ export function LocalAppView({ id, botOf, onBack, onGoToChat, onOpenWindow }: {<MessageSquare size={14} aria-hidden="true" /><span className="max-sm:sr-only">{t("localApps.card.goToChat")}</span></button>)}- {!goToChat && !app.chat && <span className="sr-only">{t("localApps.view.chatGone")}</span>}+ {!goToChat && !app.chat && !app.sample && <span className="sr-only">{t("localApps.view.chatGone")}</span>}{onOpenWindow && (<button type="button" className="ui-icon-button hover:bg-ink/[0.06] hover:text-ink" onClick={onOpenWindow}aria-label={t("localApps.card.openWindow")} title={t("localApps.card.openWindow")}><AppWindowMac size={16} /></button>diff --git a/src/components/published-apps/LocalApps.test.ts b/src/components/published-apps/LocalApps.test.tsindex 7dd6985216..54a969f9bb 100644--- a/src/components/published-apps/LocalApps.test.ts+++ b/src/components/published-apps/LocalApps.test.ts@@ -37,6 +37,7 @@ const app = (id: string, name: string, more: Partial<LocalApp> = {}): LocalApp =});const BOARD = app("la_board0000000000000", "Sales board", { versions: [{ rev: 0, at: NOW }, { rev: 1, at: NOW }, { rev: 2, at: NOW }], rev: 2 });const ROTA = app("la_rota00000000000000", "Staff rota", { chat: false, botId: "gone", bot: null });+const SAMPLE = app("la_starter_ledger__", "Ledger", { chat: false, botId: "", threadId: "", messageId: "la_starter_ledger__", bot: null, sample: true });let root: Root;let host: HTMLElement;@@ -124,6 +125,24 @@ describe("saved apps on the apps page", () => {expect(button(card(BOARD.id), "Open in its own window")).toBeUndefined();});+ it("labels a starter app Sample, with no chat to go to, in its card and its view", async () => {+ saved = [BOARD, SAMPLE];+ await show();+ expect(card(SAMPLE.id).textContent).toContain("Sample · 2 hr ago");+ expect(card(SAMPLE.id).textContent).not.toContain("Bot removed");+ act(() => button(card(SAMPLE.id), "More for Ledger").click());+ expect(menuItem("Go to chat")).toBeUndefined();+ expect(menuItem("Remove")).toBeDefined();+ act(() => button(card(SAMPLE.id), "Open Ledger").click());+ await settle();+ const header = host.querySelector("header")!.textContent;+ expect(header).toContain("Sample");+ expect(header).not.toContain("By ");+ expect(button(host, "Go to chat")).toBeUndefined();+ expect(host.textContent).not.toContain("chat it came from");+ expect(host.querySelector(`[data-local-app-view="${SAMPLE.id}"]`)?.getAttribute("data-local-app-state")).toBe("live");+ });+it("opens an app in its own window on the desktop", async () => {const openWindow = vi.fn(async () => true);vi.stubGlobal("ogb", { localApps: { openWindow, openChat: vi.fn() } });@@ -260,6 +279,16 @@ describe("installing a saved app on this computer", () => {expect(document.querySelector("[role=dialog], [role=alertdialog]")).toBeNull();});+ it("installs a starter app like any saved one", async () => {+ saved = [BOARD, SAMPLE];+ await show();+ act(() => button(card(SAMPLE.id), "More for Ledger").click());+ await act(async () => menuItem("Install on this computer").click());+ await settle();+ expect(bridge.install).toHaveBeenCalledWith({ id: SAMPLE.id, name: "Ledger" });+ expect(card(SAMPLE.id).querySelector("[data-local-app-installed]")).not.toBeNull();+ });+it("says so in one line when a launcher couldn't be written", async () => {bridge.install.mockResolvedValueOnce({ ok: false, reason: "failed" });await show();diff --git a/src/locales/en.json b/src/locales/en.jsonindex e94b846413..0d17ba2ff5 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -7413,6 +7413,7 @@"localApps.card.goToChat": "Go to chat","localApps.card.remove": "Remove","localApps.card.botGone": "Bot removed",+ "localApps.card.sample": "Sample","localApps.removed": "“{name}” removed.","localApps.removeFailed": "“{name}” couldn't be removed. Try again.","localApps.renameFailed": "The new name couldn't be saved. Try again.",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex af80443335..71c2b63ec4 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -7024,6 +7024,7 @@"localApps.card.goToChat": "Ir para o chat","localApps.card.remove": "Remover","localApps.card.botGone": "Bot removido",+ "localApps.card.sample": "Exemplo","localApps.removed": "“{name}” removido.","localApps.removeFailed": "Não foi possível remover “{name}”. Tente de novo.","localApps.renameFailed": "Não foi possível salvar o novo nome. Tente de novo.",