Files
loki/widget/changes.ts
CatoandClaude Opus 5.5 9d5d0c4694 feat(widget): Loki's own look, in Loki's light or dark mode, with one scroll (#1227)
* feat(widget): Loki's own look, in Loki's light or dark mode, with one scroll

The site widget took its colours from the fleet's shared tokens, whose
accent is OrangeCat's warm orange, and was dark only: on a client's light
site the owner saw an orange-ringed black panel and asked why Loki's widget
looked like OrangeCat.

- Themes are generated from Loki's own globals.css, light and dark. The
  accent is the ink; the warm colour is only the focus ring and a picked
  element's outline on the host page.
- Every widget stylesheet reads var(--lk-*), defined for both modes on the
  shadow host; widget/theme-mode.ts picks one. The owner gets the mode they
  chose in Loki (user_preferences.theme, saved by ThemeSync via
  PUT /api/me/theme, returned with their changes and remembered per site);
  everyone else gets their device's setting, followed live.
- The panel is one column with one scroll area (the thread) between a fixed
  header and composer. The whole card used to scroll too, which hid the
  composer below a laptop's fold and nested scrolls on phones.
- The desktop card no longer greys out the site it invites you to use; the
  phone sheet opens at two thirds of the screen with a lighter scrim.
- About is a segmented control that fits a 320px phone on one line.
- The walkthrough card follows the same mode; its ring uses the highlight
  so it reads on light and dark sites.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018LMe5Uv6mfWJibAiCaNbbk

* fix(widget): the launcher is findable — Loki's mark at full strength

On the owner's phone, signed out of the owner pass, AOZ showed a grey
pencil at 38% opacity and 85% size, and the owner said the widget was gone.
Without the launcher there is no way to the sign-in that brings owner mode
back. The resting launcher is now Loki's spiral at full strength with a
hairline and a soft lift off the page, on phones and desktop; it still
fades while the page scrolls.

Also: the user_theme migration is renumbered 0107 after main's 0106.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018LMe5Uv6mfWJibAiCaNbbk

* fix(widget): keep the shared chat's thread bounded however chatkit nests it

CI's widget-kit-browser (needs @bitbaum/chatkit, so it only runs there)
failed one check: the chat thread no longer had a max-height once the panel
became a flex column. The flex layout bounds it only when the wrap is a
direct child, so the cap is back as a backstop, and the test now pins the
outcome — the thread scrolls and ends inside a card that fits the screen —
instead of the mechanism.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018LMe5Uv6mfWJibAiCaNbbk

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-15 10:40:11 -07:00

304 lines
11 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* "Your changes" — the loop closing on the owner's own site.
*
* Until now the panel's story ended at "On it — Loki tells you when", and on
* the site Loki never did: the telling went to a push notification and a
* Telegram chat, and the page the owner came back to said nothing. This strip
* is the other half of that sentence. It lists what the owner asked for and
* where each thing is (Building · On its way · Live · Needs you), asks Loki
* again every half minute while something is moving, and when a change goes
* live since the last look, Loki says so — in the thread when the panel is
* open, beside the launcher when it is not — with one tap to see it.
*
* Words come from the server (owner-view.ts). This side renders, remembers
* what it has already seen (localStorage, per site), and notices the one
* transition that matters.
*/
import { h } from "./dom";
import { knownFor, parseKnown, type KnownFix } from "./known-fixes";
import { isThemePreference, type ThemePreference } from "./theme-mode";
export type OwnerChange = {
id: string;
text: string;
at: string;
label: string;
tone: "neutral" | "accent" | "warning" | "positive";
detail: string;
live: boolean;
settled: boolean;
href: string | null;
action: string | null;
};
/** Mirrors OWNER_CHANGES_MAX in src/lib/feedback/owner-view.ts. */
export const CHANGES_MAX = 12;
/** Rows shown before "all N in Loki". The strip sits above the thread. */
export const CHANGES_SHOWN = 3;
export const CHANGES_POLL_MS = 30_000;
/** Stop asking after this long with nothing moving — a tab left open all day
* must not poll Loki all day. */
export const CHANGES_POLL_FOR_MS = 2 * 60 * 60_000;
const seenKey = (token: string) => `loki-changes-seen:${token}`;
/** What this browser last saw of each change: live or not. */
export function readSeen(token: string): Record<string, boolean> {
try {
const raw = JSON.parse(localStorage.getItem(seenKey(token)) ?? "{}") as unknown;
if (!raw || typeof raw !== "object") return {};
const out: Record<string, boolean> = {};
for (const [k, v] of Object.entries(raw)) if (typeof v === "boolean") out[k] = v;
return out;
} catch {
return {};
}
}
export function writeSeen(token: string, seen: Record<string, boolean>): void {
try {
localStorage.setItem(seenKey(token), JSON.stringify(seen));
} catch {
/* storage blocked: the announcement may repeat next visit */
}
}
/**
* The changes that went live since the last look. A change never seen before
* is not announced — the first open after a long absence should not shout
* about everything that ever shipped — only one this browser saw building.
*/
export function newlyLive(
prev: Record<string, boolean>,
next: readonly OwnerChange[],
): OwnerChange[] {
return next.filter((c) => c.live && prev[c.id] === false);
}
export function toSeen(next: readonly OwnerChange[]): Record<string, boolean> {
return Object.fromEntries(next.map((c) => [c.id, c.live]));
}
/**
* The collapsed line: what is moving and what landed, in the order the owner
* cares — what needs them, what is being built, what is waiting its turn,
* what is live. "Your changes · 1 needs you · 1 building · 2 live".
*/
export function changesSummary(changes: readonly OwnerChange[], visitors = 0): string {
const count = (label: string) => changes.filter((c) => c.label === label).length;
const parts = [
["needs you", count("Needs you")],
["building", count("Building") + count("Starting")],
["in line", count("In line")],
["on its way", count("On its way")],
["live", changes.filter((c) => c.live).length],
]
.filter(([, n]) => (n as number) > 0)
.map(([w, n]) => `${n} ${w}`);
if (visitors) parts.push(`${visitors} from visitors`);
return parts.length ? `Your changes · ${parts.join(" · ")}` : `Your changes · ${changes.length}`;
}
export function parseChanges(body: unknown): OwnerChange[] {
const raw = (body as { changes?: unknown })?.changes;
if (!Array.isArray(raw)) return [];
return raw
.map((c) => (c ?? {}) as Partial<OwnerChange>)
.filter(
(c) => typeof c.id === "string" && typeof c.text === "string" && typeof c.label === "string",
)
.map((c) => ({
id: c.id as string,
text: String(c.text).slice(0, 200),
at: typeof c.at === "string" ? c.at : "",
label: String(c.label).slice(0, 40),
tone: (["neutral", "accent", "warning", "positive"] as const).includes(
c.tone as OwnerChange["tone"],
)
? (c.tone as OwnerChange["tone"])
: "neutral",
detail: typeof c.detail === "string" ? c.detail.slice(0, 300) : "",
live: c.live === true,
settled: c.settled === true,
href: typeof c.href === "string" && /^https?:\/\//.test(c.href) ? c.href : null,
action: typeof c.action === "string" ? c.action.slice(0, 40) : null,
}))
.slice(0, CHANGES_MAX);
}
export function createChanges(opts: {
apiBase: string;
token: string;
pass: () => string | null;
/** A change went live since this browser last looked. */
onLive: (change: OwnerChange) => void;
/** The server no longer honours the pass. */
onPassRefused: () => void;
/** The owner's light/dark choice in Loki, each time the server reports it. */
onTheme?: (pref: ThemePreference) => void;
/** The list was re-read: cards keyed to a fix follow its status. */
onUpdate?: () => void;
}) {
// One line until opened, like the notes above it: "Your changes · 1
// building · 2 live ›". It was a header, three rows and a "See it →" line
// under each — the busiest block on the panel, open all the time.
const el = h("div", "yours");
el.style.display = "none";
const head = h("button", "yours-head");
head.type = "button";
head.setAttribute("aria-expanded", "false");
const summary = h("span", "yours-sum");
const chev = h("span", "thoughts-chev", "›");
chev.setAttribute("aria-hidden", "true");
head.append(summary, chev);
const body = h("div", "yours-body");
body.style.display = "none";
const list = h("div", "yours-list");
const all = h("a", "yours-all");
all.target = "_blank";
all.rel = "noopener";
// Visitors' notes are not the owner's changes; they are counted, and read
// in Loki, where the inbox has the room to show who said what.
const visitorsLine = h("a", "yours-visitors");
visitorsLine.target = "_blank";
visitorsLine.rel = "noopener";
visitorsLine.style.display = "none";
body.append(list, all, visitorsLine);
el.append(head, body);
let open = false;
head.addEventListener("click", () => {
open = !open;
head.setAttribute("aria-expanded", String(open));
el.classList.toggle("open", open);
body.style.display = open ? "" : "none";
});
let changes: OwnerChange[] = [];
/** Every keyed fix the server knows, open or settled (known-fixes.ts). */
let known: KnownFix[] = [];
let firstRead: (() => void) | null = null;
/** Settles after the first answer (or refusal), so Watch can look before it speaks. */
const ready = new Promise<void>((resolve) => {
firstRead = resolve;
});
let inbox: string | null = null;
let visitors = 0;
let timer = 0;
let startedAt = 0;
let inflight = false;
function render() {
list.textContent = "";
el.style.display = changes.length || visitors ? "" : "none";
summary.textContent = changesSummary(changes, visitors);
el.classList.toggle(
"needs-you",
changes.some((c) => c.tone === "warning"),
);
visitorsLine.style.display = visitors && inbox ? "" : "none";
if (visitors && inbox) {
visitorsLine.textContent = `${visitors} note${visitors === 1 ? "" : "s"} from visitors, in Loki →`;
visitorsLine.href = inbox;
}
for (const c of changes.slice(0, CHANGES_SHOWN)) {
// The row IS the link when there is somewhere to go — no second line.
const row = c.href
? h("a", `yours-row tone-${c.tone}`)
: h("div", `yours-row tone-${c.tone}`);
if (row instanceof HTMLAnchorElement && c.href) {
row.href = c.href;
row.rel = "noopener";
row.target = "_blank";
}
row.title = c.detail;
const text = h("span", "yours-text", c.text);
const status = h("span", "yours-status", c.label);
row.append(h("span", "yours-dot"), text, status);
list.appendChild(row);
}
const more = changes.length - CHANGES_SHOWN;
all.textContent = more > 0 ? `All ${changes.length} in Loki →` : "Open in Loki →";
all.style.display = inbox ? "" : "none";
if (inbox) all.href = inbox;
}
async function refresh(): Promise<void> {
const pass = opts.pass();
if (!pass) {
firstRead?.();
firstRead = null;
return;
}
if (inflight) return;
inflight = true;
try {
const res = await fetch(`${opts.apiBase}/api/widget/owner/changes`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ token: opts.token, ownerPass: pass }),
});
const body = (await res.json().catch(() => null)) as {
owner?: boolean;
inbox?: unknown;
visitors?: unknown;
theme?: unknown;
} | null;
if (!res.ok || !body) return;
if (body.owner === false) {
opts.onPassRefused();
return;
}
// The mode the owner chose in Loki — the panel follows it (theme-mode.ts).
if (isThemePreference(body.theme)) opts.onTheme?.(body.theme);
const next = parseChanges(body);
known = parseKnown(body);
opts.onUpdate?.();
inbox = typeof body.inbox === "string" && /^https?:\/\//.test(body.inbox) ? body.inbox : null;
visitors =
typeof body.visitors === "number" && body.visitors > 0 ? Math.floor(body.visitors) : 0;
const prev = readSeen(opts.token);
for (const c of newlyLive(prev, next)) opts.onLive(c);
writeSeen(opts.token, { ...prev, ...toSeen(next) });
changes = next;
render();
// Keep asking only while something can still change.
if (!next.some((c) => !c.settled)) stop();
} catch {
/* Loki unreachable: the strip keeps what it had */
} finally {
inflight = false;
firstRead?.();
firstRead = null;
}
}
function stop() {
window.clearInterval(timer);
timer = 0;
}
/** Ask now, then every half minute while something is moving. */
function start() {
if (!opts.pass()) return;
void refresh();
if (timer) return;
startedAt = Date.now();
timer = window.setInterval(() => {
if (Date.now() - startedAt > CHANGES_POLL_FOR_MS) return stop();
void refresh();
}, CHANGES_POLL_MS);
}
return {
el,
refresh,
start,
stop,
count: () => changes.length,
/** The fix a remark's key already has, if any — see known-fixes.ts. */
known: (key: string) => knownFor(known, key),
/** Resolves once Loki has answered (or could not), never later than the caller's own wait. */
ready: () => ready,
};
}