diff --git a/docs/file-zone.md b/docs/file-zone.md new file mode 100644 index 00000000..01b5a4c5 --- /dev/null +++ b/docs/file-zone.md @@ -0,0 +1,106 @@ +# File zone: design sketch + +Status: design only. No code exists. Everything below is a proposal; items marked **UNKNOWN** are not yet verified against the Body. + +Source: Meta ruling 2026-10-31, eureka mind `ratatoskr:ruling:file-zone-looks-like-file-sharing`. + +## What it is + +A file-sharing space beside the room timeline, not a view of it. The zone is **one ordinary Matrix room with threaded discussions, one thread per Mind**. The UI presents each thread as an **album** (title, item count, date) and each post in it as a **file** with an inline player or preview. Matrix is the storage and the fallback: another client sees a normal room with threads and never needs the zone. No homeserver change. + +First use (Aqua): listen to audio in place, mark each clip keep / fix / drop with a one-line reason, export the marks as a file. See `/opt/commons/handoff/aqua-listen-kits-20261108/` (static `listen.html` kits that emit `verdict.json` + `verdict.md`); the zone replaces sending that page around. + +## Matrix event shapes (stock events only) + +- **Zone** = one room, chosen by the client (**UNKNOWN:** how the client knows which room is the zone: a room-account-data flag, a `m.room.create` type, or a configured room id in `config.json`; config is simplest). +- **Album** = a thread root: a text `m.room.message` posted by a Mind, `body` = the album title (the Mind's name, e.g. `void`). One thread per Mind, owned by authorship (the root's sender). **UNKNOWN:** whether a Mind may open more than one (e.g. per kit); the shape allows it with no change, the zone would then list several albums per author. Count and last-activity come from the SDK's thread summary (`unsigned.m.relations.m.thread`); album date = root `origin_server_ts`. Rename = `m.replace` on the root. +- **File** = a post in the thread: an `m.room.message` with `msgtype` `m.audio` / `m.image` / `m.video` / `m.file` and `m.relates_to: { rel_type: "m.thread", event_id: , is_falling_back: true, "m.in_reply_to": { event_id: } }`. The builders in `src/app/features/room/msgContent.ts` already make the content. Delete = redact. +- **Album vs chat thread**: with a single-purpose room, every thread is an album. No marker key is needed. A non-media reply in a thread (chat, a mark) is not a file and is not listed as one. +- **Cover** = first image file in the thread, if any. Loose room messages outside any thread are not shown in the zone; they remain in the timeline. + +## Marks (reactions, plus an optional reply) + +A mark is stock Matrix, so every client shows it. Two reaction sets on the **file post**, and one optional reply: + +- **Verdict** = an `m.annotation` reaction (`m.reaction` event, `m.relates_to: { rel_type: "m.annotation", event_id: , key }`) with key **👍 keep**, **🔧 fix**, **🗑 drop**. One per person per file: choosing another replaces the old one (the client redacts the sender's previous verdict reaction, then sends the new one); tapping the active one clears it. +- **Landed** = a second reaction set, keys **1️⃣ 2️⃣ 3️⃣ 4️⃣ 5️⃣** (keycap digits, 1-5). Also one per person per file, same replace rule. The two sets are independent: a file can have a verdict, a landed score, both or neither. +- **Reason** = an ordinary thread reply under the file: `m.room.message` `m.text`, `m.relates_to: { rel_type: "m.thread", event_id: , "m.in_reply_to": { event_id: } }`. Optional. **Keep needs none**; the UI prompts for one mainly after fix or drop. The latest such reply by the sender under that file is the reason (edits via `m.replace` count). No special key: the reply text is the reason, so nothing is lost if another client wrote it. +- **No private mode.** Marks are room events the moment they are tapped; there is no local-only draft and no "Share" step. Offline taps queue in the SDK's normal send queue. +- Who marked what is read from the reactions' senders, so each listener is distinguishable and the album can show tallies per file. +- Why reactions: one tap, readable in any client, no custom event type, and they can be changed with no history growth beyond a redaction. Reaction keys carry no text, hence the separate reply for the reason. +- **UNKNOWN:** emoji variation selectors. 🗑 and 🔧 and the keycaps may arrive with or without U+FE0F from different clients; match by normalizing (strip U+FE0F) before comparing keys. Also **UNKNOWN:** servers' per-event limits on distinct reaction keys; a handful per file is far below any default. + +## Export + +Client-side only. "Export" builds Aqua's verdict file from the verdict and landed reactions and the reply under each file in one album (one listener's marks per export; that sender is the `listener`) and either downloads it or uploads it into the album. Two files, as the kits write them: `verdict.json` and `verdict.md`. + +`verdict.json` is schema **`aqua.listen.verdict.v1`**, field for field what `buildVerdict` in the kit (`dings/listen.html`, section `buildVerdict`) emits, so Aqua's tooling reads it unchanged: + +``` +{ schema: "aqua.listen.verdict.v1", + kit: { id, title }, // album root: id = root event id (or the kit id if the upload carried one), title = root body + exportedAt, // ISO time of export + seed, consent, // kit-only: zone writes seed: 0 (or omits), consent: true for the sender's own export (see UNKNOWN) + listener, // sender display name + device, // headphones|speakers|null, the sender's most-used mark device, or null + notes, // free text; zone leaves "" in v1 + summary: { total, keep, fix, drop, unanswered }, + clips: [{ position, id, title, group, feel, file, pair, slot, verdict, reason, landed, device }], + pairs: [{ a, b, preferred }] } // empty array when the album has no pairs +``` + +- `clips` has one row per file post in the album, in thread order (`position` = 1-based). The join per file, for the exporting listener: `verdict` = their 👍/🔧/🗑 reaction (keep/fix/drop) or null; `landed` = their keycap reaction (1-5) or null; `reason` = text of their latest reply under the file, or "". A file with no verdict reaction counts as `unanswered` even if it has a reply. `device` per clip is null (reactions cannot carry it); the top-level `device` (headphones|speakers|null) is asked once in the export dialog. +- `pairs`, `seed`, `consent` are optional for the zone: `pairs: []`, no `slot`/`pair` (null) unless the clip metadata supplies them. +- **Where clip metadata comes from.** `id` is the clip id from `org.gamecult.clip`, else the filename stem. `title` = file post `body`; `file` = the post's `filename`/`body`. `group`, `feel`, `pair`, `slot` are kit data that Matrix has no slot for: carry them on the file post as one extra key `org.gamecult.clip: { id, group, feel, pair, slot }` written by whoever uploads the kit (a small uploader script, **UNKNOWN**, not in the first slice; without it those columns export as ""/null and the id falls back to the filename stem). +- `verdict.md` follows `verdictMarkdown` from the same file: header line, count line, the clip table (`# | clip | group | intended feel | verdict | landed (1-5) | device | reason`), pairs table when `pairs` is nonempty, notes. +- To avoid drift, the exporter should be a port of `buildVerdict`/`verdictMarkdown` with the schema string and field order pinned by a test that compares against a fixture produced by the kit. **UNKNOWN:** whether to share code (the kit's `logic.cjs`) rather than port; recommend port, ~80 lines, because the kit is a standalone page. +- **UNKNOWN:** `consent` is a kit-side checkbox before listening. The zone has no such step; recommend writing `true` only if the sender ticks a one-time "include my name in exports" toggle, else `false` and `listener: ""`. +- JSON here is a xenos-boundary export, not state; the room events are the state. + +## Mobile-first layout + +- Phone width is the design width; desktop adds columns. +- Level 1, album list: one column, each row = cover/icon, title, "N files", date. Tap opens. +- Level 2, album: list by default (title, duration/size), grid toggle for images. Audio rows play in place, one at a time (starting a clip stops the last), a persistent mini-player at the bottom with seek. +- Mark controls on each audio row: three large tap targets (👍 keep / 🔧 fix / 🗑 drop) with tallies, a row of five "landed" chips (1-5), and after fix or drop an inline one-line reason field (skippable). Thumb-reachable, no modal. +- Back is one level up; the room timeline stays one tap away (the zone is a sibling view, not a replacement). **UNKNOWN:** where the entry lives in the room header; check `RoomViewHeader.tsx`, `Room.tsx` for how the member drawer and pin menu attach. + +## Upload + +Reuse the composer's pipeline, pointed at an album instead of the main timeline: + +- `createUploadAtom` / `useBindUploadAtom` (`src/app/state/upload.ts`), `UploadCard`, `upload-board` for progress. +- On success, the msgContent builder produces the event; the zone adds the thread relation to the album root before sending (the composer already does this for thread replies, `RoomInput.tsx`). +- "New album" = send the root text event, then upload into its thread. Multi-file drop = N events, sent in order. +- Size limit from `MediaConfigLoader` (server `m.upload.size`). **UNKNOWN:** whether the 32 MB `shelf` kit's clips (42 x ~0.75 MB) should be uploaded individually or batched; individually is the only option without a server change. + +## Existing code to reuse (verified present in the repo) + +| need | where | +|---|---| +| audio player (play/seek/volume, encrypted download) | `src/app/components/message/content/AudioContent.tsx` (210 lines) | +| video, image, generic file | `.../content/VideoContent.tsx`, `ImageContent.tsx`, `FileContent.tsx` | +| full-screen image viewer | `src/app/components/image-viewer/ImageViewer.tsx` | +| media dispatch by msgtype | `src/app/components/RenderMessageContent.tsx`, `message/MsgTypeRenderers.tsx` | +| upload + progress | `state/upload.ts`, `components/upload-card`, `upload-board` | +| event content builders | `features/room/msgContent.ts` | +| thread plumbing | `features/room/message/Message.tsx`, `RoomTimeline.tsx`, `RoomInput.tsx` (thread relation on send) | +| room-scoped file/pin precedent | `features/room/room-pin-menu/RoomPinMenu.tsx` | + +Nothing named "gallery" exists as a feature; `AudioContent` takes its controls as render props (`renderMediaControl`), so it can be rehosted in a row without a fork. **UNKNOWN:** whether `AudioContent` can be rendered outside a timeline event context (it needs only `url`, `info`, `mimeType`, `encInfo`, from the event content, so probably yes). + +## First slice (what to build first) + +Rough lines of TypeScript, tests excluded. + +1. **Read-only albums + album view** (~250 lines): list the room's thread roots as albums (grouped or filterable by author = Mind), open one to list its file posts, rehost `AudioContent` and `ImageContent`. One route/panel plus a header entry. Depends on the thread list the SDK already keeps. +2. **Marks + export** (~240 lines, with the schema port): verdict and landed reaction sets with the replace-one rule, optional reason reply, per-file tallies, the join into `aqua.listen.verdict.v1` and `verdict.json`/`verdict.md` download. This is Aqua's workflow end to end. +3. **Upload into an album** (~150 lines): thread-related send through the existing upload atoms, "new album". + +Slices 1+2 serve the first use case. Each is its own PR. Because marks are ordinary thread replies, there is no separate "publish" slice. + +## Open questions for the Meta + +- How the client identifies the zone room (config id recommended). +- Whether exports are per listener (proposed) or a merged all-listeners file. +- Where `device` comes from, now that reactions cannot carry it (export dialog, proposed). diff --git a/index.html b/index.html index 6bbcc310..2585704c 100644 --- a/index.html +++ b/index.html @@ -23,7 +23,7 @@ - + diff --git a/preview-demo/poses/README.md b/preview-demo/poses/README.md new file mode 100644 index 00000000..a1287f2d --- /dev/null +++ b/preview-demo/poses/README.md @@ -0,0 +1,13 @@ +# Demo pose thumbnails + +These 24 PNGs (about 200 KB, 160 px wide, palette-quantised) are downscaled copies of GameCult's own +Persona art from `/opt/commons/cast-art/poses`. That directory carries no provenance or licence note: +the image model that made the art and the terms it was made under are not recorded. + +They exist only so the dev preview's pretend homeserver (`src/preview-demo/`) can show pose portraits. +The dev workflow copies them into `dist/public/poses`; real builds sync the full art with +`npm run sync:poses` and do not use this folder. + +Strip them if their terms turn out not to allow this: delete this folder and the `Add the demo pose +art` step in `.github/workflows/rat-dev-preview.yml`. Pose portraits in the demo then show broken +images; nothing else depends on them. diff --git a/src/app/components/message/layout/layout.css.ts b/src/app/components/message/layout/layout.css.ts index 502c4156..815c579f 100644 --- a/src/app/components/message/layout/layout.css.ts +++ b/src/app/components/message/layout/layout.css.ts @@ -156,6 +156,8 @@ export const BubbleContentArrowLeft = style({ // beside its bubble on wide screens; on phones it floats inside the bubble, overhanging the top // edge, and the text wraps around its silhouette (shape-outside on the alpha channel). const PHONE = 'screen and (max-width: 700px)'; +const PHONE_PORTRAIT = 'min(38vw, 160px)'; +const PHONE_TEXT_FLOOR = toRem(170); const PORTRAIT = toRem(124); const POSE_GUTTER = toRem(14); const BUBBLE_CORNER = toRem(6); @@ -196,19 +198,19 @@ export const BubbleHeaderOwn = style({ alignSelf: 'flex-end', }); -// Phone: the name is a pill straddling the bubble's top edge, on the side opposite the portrait. +// Phone: name and time are one plain line in flow above the bubble, on the side opposite the +// portrait. It is as wide as the full name needs, up to the room beside the portrait; only a name +// longer than that wraps (and then the time drops below it). It is capped by the viewport, not by +// the column: a short bubble's column is narrower than its own name, and a percentage cap there +// truncated names to one letter. export const BubbleHeaderPose = style({ '@media': { [PHONE]: { - position: 'absolute', - zIndex: 2, - top: toRem(-15), - right: toRem(14), - padding: `0 ${toRem(13)}`, - background: color.Secondary.Container, - border: `1px solid ${color.Secondary.ContainerLine}`, - borderRadius: toRem(999), - whiteSpace: 'nowrap', + alignSelf: 'flex-end', + margin: `0 ${toRem(14)} ${toRem(2)}`, + width: 'max-content', + maxWidth: `calc(100vw - ${PHONE_PORTRAIT} - ${toRem(64)})`, + textAlign: 'right', }, }, }); @@ -216,8 +218,8 @@ export const BubbleHeaderPose = style({ export const BubbleHeaderPoseAlt = style({ '@media': { [PHONE]: { - right: 'auto', - left: toRem(14), + alignSelf: 'flex-start', + textAlign: 'left', }, }, }); @@ -232,6 +234,9 @@ export const BubbleContentPose = style({ '@media': { [PHONE]: { display: 'flow-root', + // A bubble with a portrait is at least portrait + a readable column wide, or the text + // beside the portrait collapses to a strip. + minWidth: `min(100%, calc(${PHONE_PORTRAIT} + ${PHONE_TEXT_FLOOR}))`, borderTopLeftRadius: config.radii.R500, padding: `${toRem(24)} ${toRem(14)} ${toRem(14)}`, }, @@ -262,11 +267,10 @@ export const PoseButton = style({ [PHONE]: { position: 'static', float: 'left', - width: 'min(50vw, 210px)', + width: PHONE_PORTRAIT, height: 'auto', margin: `${toRem(-82)} ${toRem(8)} 0 ${toRem(-12)}`, shapeMargin: toRem(7), - shapeImageThreshold: 0.35, WebkitMaskImage: 'linear-gradient(#000 84%, transparent)', maskImage: 'linear-gradient(#000 84%, transparent)', }, @@ -388,6 +392,51 @@ globalStyle(`${BubbleContentPose} > div`, { }, }); +// The name wraps instead of ellipsising: the header already caps its own width, and Username's own +// nowrap + ellipsis, and the truncate on the Text inside it, clipped long names to "Heimdall o…". +globalStyle(`${BubbleHeaderPose} ${Username}, ${BubbleHeaderPose} ${Username} *`, { + '@media': { + [PHONE]: { + whiteSpace: 'normal', + overflow: 'visible', + textOverflow: 'clip', + overflowWrap: 'break-word', + }, + }, +}); + +// A name too long for one line takes its own lines and the time drops below it, instead of the +// name shrinking to a sliver beside the time (the header's one child is the flex row of both). The +// row hugs the side the header sits on, so a dropped time stays under the name's edge. +globalStyle(`${BubbleHeaderPose} > div`, { + '@media': { + [PHONE]: { + flexWrap: 'wrap', + justifyContent: 'flex-end', + }, + }, +}); + +globalStyle(`${BubbleHeaderPoseAlt} > div`, { + '@media': { + [PHONE]: { + justifyContent: 'flex-start', + }, + }, +}); + +// An outside list marker hangs left of its item's text and ignores the portrait's silhouette, so +// beside a left portrait the number lands under the art. Inside, it is a word on the first line +// and wraps around the silhouette like the rest. +globalStyle(`${BubbleContentPose} ol, ${BubbleContentPose} ul`, { + '@media': { + [PHONE]: { + listStylePosition: 'inside', + paddingLeft: 0, + }, + }, +}); + // While the background scene runs (html[data-scene]) a chat bubble is the one filled surface in // the app: its own colour at half strength over a blur of the scene, so the words stay readable // and the ridge shows through. The arrow wedge is opaque, so it goes. @@ -400,14 +449,6 @@ globalStyle(`${scene} ${BubbleContent}`, { globalStyle(`${scene} ${BubbleContentOwn}`, { backgroundColor: [color.Primary.Container, half(color.Primary.Container)], }); -globalStyle(`${scene} ${BubbleHeaderPose}`, { - '@media': { - [PHONE]: { - backgroundColor: [color.Secondary.Container, half(color.Secondary.Container)], - backdropFilter: 'blur(12px)', - }, - }, -}); globalStyle(`${scene} ${BubbleLeftArrow}`, { display: 'none', }); diff --git a/src/app/components/message/pose/PoseAvatar.tsx b/src/app/components/message/pose/PoseAvatar.tsx index e98d6139..75a4b333 100644 --- a/src/app/components/message/pose/PoseAvatar.tsx +++ b/src/app/components/message/pose/PoseAvatar.tsx @@ -1,7 +1,8 @@ -import React from 'react'; +import React, { useEffect, useRef, useState } from 'react'; import classNames from 'classnames'; import * as css from '../layout/layout.css'; import { poseSrc } from './poses'; +import { silhouette } from './silhouette'; type PoseAvatarProps = { mind: string; @@ -16,17 +17,48 @@ type PoseAvatarProps = { export function PoseAvatar({ mind, pose, userId, alt, enter, onClick }: PoseAvatarProps) { const src = poseSrc(mind, pose, import.meta.env.BASE_URL); + const imgRef = useRef(null); + const [shape, setShape] = useState(); + + // On phones the bubble text wraps around the portrait's silhouette. Retraced when the art + // loads and when the portrait's width changes with the viewport. + useEffect(() => { + const img = imgRef.current; + if (!img) return undefined; + const trace = () => { + if (!img.complete || img.naturalWidth === 0) return; + try { + setShape(silhouette(img, !alt)); + } catch { + setShape(undefined); + } + }; + trace(); + img.addEventListener('load', trace); + const resize = new ResizeObserver(trace); + resize.observe(img); + return () => { + img.removeEventListener('load', trace); + resize.disconnect(); + }; + }, [src, alt]); + return ( ); } diff --git a/src/app/components/message/pose/poses.test.ts b/src/app/components/message/pose/poses.test.ts index ed503abe..81c2f0c6 100644 --- a/src/app/components/message/pose/poses.test.ts +++ b/src/app/components/message/pose/poses.test.ts @@ -1,6 +1,13 @@ import { describe, expect, it } from 'vitest'; import catalogue from './catalogue.json'; -import { mindOfSender, poseSrc, poseStatusLine, poseStatuses, resolvePose } from './poses'; +import { + mindOfSender, + poseSrc, + poseStatusLine, + poseStatuses, + resolvePose, + splitNewestStatus, +} from './poses'; describe('resolvePose', () => { it('keeps shared and own-signature labels from the catalogue', () => { @@ -81,3 +88,17 @@ describe('poseStatusLine', () => { ); }); }); + +describe('splitNewestStatus', () => { + const s = (mind: string, since: number) => ({ mind, pose: 'happy', since }); + + it('picks the status that changed last and keeps the others in their order', () => { + const { newest, rest } = splitNewestStatus([s('eureka', 100), s('void', 300), s('nibu', 200)]); + expect(newest?.mind).toBe('void'); + expect(rest.map((r) => r.mind)).toEqual(['eureka', 'nibu']); + }); + + it('has no newest for an empty list', () => { + expect(splitNewestStatus([])).toEqual({ newest: undefined, rest: [] }); + }); +}); diff --git a/src/app/components/message/pose/poses.ts b/src/app/components/message/pose/poses.ts index a5b705c3..7175196a 100644 --- a/src/app/components/message/pose/poses.ts +++ b/src/app/components/message/pose/poses.ts @@ -68,6 +68,17 @@ export const poseStatuses = (events: PoseEvent[]): PoseStatus[] => { }); }; +// The status that changed last, and the rest in their given order (phones show only the first). +export const splitNewestStatus = ( + statuses: PoseStatus[] +): { newest: PoseStatus | undefined; rest: PoseStatus[] } => { + let newest: PoseStatus | undefined; + statuses.forEach((st) => { + if (!newest || st.since > newest.since) newest = st; + }); + return { newest, rest: statuses.filter((st) => st !== newest) }; +}; + const two = (n: number) => String(n).padStart(2, '0'); // Client-status text. Rendered locally only; it is never sent to a room. diff --git a/src/app/components/message/pose/silhouette.test.ts b/src/app/components/message/pose/silhouette.test.ts new file mode 100644 index 00000000..9deb3f4f --- /dev/null +++ b/src/app/components/message/pose/silhouette.test.ts @@ -0,0 +1,56 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { silhouette } from './silhouette'; + +// A w x h image whose opaque pixels are the given columns [from, to) on each row. +const fakeImage = (w: number, h: number, solid: (y: number) => [number, number] | null) => { + const data = new Uint8ClampedArray(w * h * 4); + for (let y = 0; y < h; y += 1) { + const span = solid(y); + if (span) for (let x = span[0]; x < span[1]; x += 1) data[(y * w + x) * 4 + 3] = 255; + } + const canvas = { + width: 0, + height: 0, + getContext: () => ({ canvas, drawImage: vi.fn(), getImageData: () => ({ data }) }), + }; + vi.stubGlobal('document', { createElement: () => canvas }); + return { clientWidth: w, clientHeight: h } as HTMLImageElement; +}; + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('silhouette', () => { + // Art in columns 20..60 from row 8 down; rows 0..7 are empty. + const art = (y: number): [number, number] | null => (y < 8 ? null : [20, 60]); + + it('hugs the right edge of the art when the text sits to its right', () => { + const poly = silhouette(fakeImage(100, 16, art), true); + expect(poly).toBe( + 'polygon(0px 0, 0px 0px, 0px 4px, 60px 8px, 60px 12px, 60px 16px, 0px 16px) border-box' + ); + }); + + it('hugs the left edge of the art when the text sits to its left', () => { + const poly = silhouette(fakeImage(100, 16, art), false); + expect(poly).toBe( + 'polygon(100px 0, 100px 0px, 100px 4px, 20px 8px, 20px 12px, 20px 16px, 100px 16px) border-box' + ); + }); + + it('takes the widest row of a band, so no row of the art pokes out of the polygon', () => { + // Row 5 reaches x=90; its band's edge row (y=8 covers rows 4..8) must include it. + const poly = silhouette( + fakeImage(100, 16, (y) => (y === 5 ? [20, 90] : null)), + true + ); + expect(poly).toContain('90px 8px'); + }); + + it('has no shape before the image has a size or where there is no canvas', () => { + expect( + silhouette({ clientWidth: 0, clientHeight: 0 } as HTMLImageElement, true) + ).toBeUndefined(); + }); +}); diff --git a/src/app/components/message/pose/silhouette.ts b/src/app/components/message/pose/silhouette.ts new file mode 100644 index 00000000..e9596ded --- /dev/null +++ b/src/app/components/message/pose/silhouette.ts @@ -0,0 +1,34 @@ +const SOLID = 0.35 * 255; +const ROW = 4; + +// The edge of the portrait that the text wraps against, as a polygon in border-box pixels. +// `shape-outside: url()` cannot do this: the browser sizes that image at its natural size and +// anchors it at the margin box, which the phone layout's negative top margin shifts down by the +// overhang, so the exclusion neither matches the art's size nor its place. +export const silhouette = (img: HTMLImageElement, textOnRight: boolean): string | undefined => { + const w = Math.round(img.clientWidth); + const h = Math.round(img.clientHeight); + const ctx = w > 0 && h > 0 ? document.createElement('canvas').getContext('2d') : null; + if (!ctx) return undefined; + ctx.canvas.width = w; + ctx.canvas.height = h; + ctx.drawImage(img, 0, 0, w, h); + const { data } = ctx.getImageData(0, 0, w, h); + const outer = textOnRight ? 0 : w; + const edge: string[] = []; + for (let y = 0; y <= h; y += ROW) { + let x = outer; + // A band's edge is the extreme solid pixel over its rows, so no row pokes out of the polygon. + for (let r = Math.max(0, y - ROW); r < Math.min(h, y + 1); r += 1) { + for (let i = 0; i < w; i += 1) { + const px = textOnRight ? w - 1 - i : i; + if (data[(r * w + px) * 4 + 3] > SOLID) { + x = textOnRight ? Math.max(x, px + 1) : Math.min(x, px); + break; + } + } + } + edge.push(`${x}px ${y}px`); + } + return `polygon(${outer}px 0, ${edge.join(', ')}, ${outer}px ${h}px) border-box`; +}; diff --git a/src/app/components/nav/styles.css.ts b/src/app/components/nav/styles.css.ts index 48b2a4d3..b123f9bc 100644 --- a/src/app/components/nav/styles.css.ts +++ b/src/app/components/nav/styles.css.ts @@ -1,6 +1,15 @@ import { ComplexStyleRule, createVar, style } from '@vanilla-extract/css'; import { RecipeVariants, recipe } from '@vanilla-extract/recipes'; import { ContainerColor, DefaultReset, Disabled, RadiiVariant, color, config, toRem } from 'folds'; +import { surfaceInk } from '../../features/scene/sceneShell.css'; + +// Wash strengths over the scene: rows and labels are faint, and hover, selected and pressed rows +// are three distinct steps above them. +const SCRIM_LABEL = '12%'; +const SCRIM_ROW = '16%'; +const SCRIM_HOVER = '26%'; +const SCRIM_SELECTED = '36%'; +const SCRIM_PRESSED = '48%'; export const NavCategory = style([ DefaultReset, @@ -11,6 +20,13 @@ export const NavCategory = style([ export const NavCategoryHeader = style({ gap: config.space.S100, + selectors: { + // Category labels sit on the scene like the rows do, and need a wash to be read. + ':root[data-scene] &': { + backgroundColor: `color-mix(in srgb, ${surfaceInk} ${SCRIM_LABEL}, transparent)`, + borderRadius: config.radii.R400, + }, + }, }); export const NavLink = style({ @@ -61,6 +77,22 @@ const NavItemBase = style({ '&[data-hover=true]': { backgroundColor: ContainerHover, }, + // While the background scene runs the shell is clear (sceneShell.css.ts); a row is a faint + // wash of the theme's own surface: the terrain stays visible, the text stays readable. Hover, + // the selected row and a press each strengthen it a step. + ':root[data-scene] &': { + backgroundColor: `color-mix(in srgb, ${surfaceInk} ${SCRIM_ROW}, transparent)`, + }, + ':root[data-scene] &:hover, :root[data-scene] &:focus-visible, :root[data-scene] &[data-hover=true]': + { + backgroundColor: `color-mix(in srgb, ${surfaceInk} ${SCRIM_HOVER}, transparent)`, + }, + ':root[data-scene] &[aria-selected=true]': { + backgroundColor: `color-mix(in srgb, ${surfaceInk} ${SCRIM_SELECTED}, transparent)`, + }, + [`:root[data-scene] &:has(.${NavLink}:active)`]: { + backgroundColor: `color-mix(in srgb, ${surfaceInk} ${SCRIM_PRESSED}, transparent)`, + }, [`&:has(.${NavLink}:active)`]: { backgroundColor: ContainerActive, }, diff --git a/src/app/features/estate/EstateNavigator.tsx b/src/app/features/estate/EstateNavigator.tsx index 6fa4bf48..29451c92 100644 --- a/src/app/features/estate/EstateNavigator.tsx +++ b/src/app/features/estate/EstateNavigator.tsx @@ -1,7 +1,7 @@ import React, { MouseEventHandler, ReactNode, useCallback, useMemo, useRef } from 'react'; import { useNavigate } from 'react-router-dom'; import { useAtom, useAtomValue, useSetAtom } from 'jotai'; -import { Avatar, Box, Chip, Icon, IconButton, Icons, Spinner, Text, color } from 'folds'; +import { Avatar, Box, Chip, Icon, IconButton, Icons, Spinner, Text, color, config } from 'folds'; import { PageNav, PageNavContent, PageNavHeader } from '../../components/page'; import { NavButton, @@ -76,9 +76,14 @@ function JoinRow({ room }: { room: EstateRoom }) { - - {room.name} - + + + + + + {room.name} + + {state.status === AsyncStatus.Error && ( { const onTimeline = () => bump((n) => n + 1); @@ -41,13 +48,33 @@ export function RoomViewPoseStatus({ room }: { room: Room }) { ); if (statuses.length === 0) return null; + const { newest, rest } = splitNewestStatus(statuses); + return ( - - {statuses.map((s) => ( - - {poseStatusLine(s)} +
+ {statuses.map((st) => ( + + {poseStatusLine(st)} ))} - + {rest.length > 0 && ( + + )} +
); } diff --git a/src/app/pages/auth/TrainingNotice.tsx b/src/app/pages/auth/TrainingNotice.tsx index 73b1caa0..6aeaf9d4 100644 --- a/src/app/pages/auth/TrainingNotice.tsx +++ b/src/app/pages/auth/TrainingNotice.tsx @@ -1,6 +1,7 @@ import { Box, Checkbox, Text, color, config } from 'folds'; import React from 'react'; -import { TRAINING_NOTICE_TEXT } from '../../utils/trainingNotice'; +import { useClientConfig } from '../../hooks/useClientConfig'; +import { trainingNoticeText } from '../../utils/trainingNotice'; type TrainingNoticeProps = { checked: boolean; @@ -9,6 +10,7 @@ type TrainingNoticeProps = { // Registration only: ticking it is the newcomer's acceptance of the current notice version. export function TrainingNotice({ checked, onToggle }: TrainingNoticeProps) { + const { previewDemo } = useClientConfig(); return ( - {TRAINING_NOTICE_TEXT} + {trainingNoticeText(previewDemo)}
); diff --git a/src/app/state/settings.ts b/src/app/state/settings.ts index 297ab1e8..2b48fb59 100644 --- a/src/app/state/settings.ts +++ b/src/app/state/settings.ts @@ -73,7 +73,9 @@ const defaultSettings: Settings = { isPeopleDrawer: false, memberSortFilterIndex: 0, enterForNewline: false, - composerSpellcheck: defaultComposerSpellcheck(window.matchMedia?.bind(window)), + composerSpellcheck: defaultComposerSpellcheck( + typeof window === 'undefined' ? undefined : window.matchMedia?.bind(window) + ), messageLayout: 2, messageSpacing: '400', hideMembershipEvents: false, diff --git a/src/app/state/upload.ts b/src/app/state/upload.ts index 810c0d2e..84786a29 100644 --- a/src/app/state/upload.ts +++ b/src/app/state/upload.ts @@ -1,9 +1,14 @@ import { atom, useAtom } from 'jotai'; import { atomFamily } from 'jotai/utils'; import { MatrixClient, UploadResponse, UploadProgress, MatrixError } from 'matrix-js-sdk'; -import { useCallback } from 'react'; +import { useCallback, useEffect, useRef } from 'react'; import { useThrottle } from '../hooks/useThrottle'; -import { uploadContent, TUploadContent } from '../utils/matrix'; +import { + ComponentLifecycle, + describeComponentLifecycle, + uploadContent, + TUploadContent, +} from '../utils/matrix'; export enum UploadStatus { Idle = 'idle', @@ -105,22 +110,34 @@ export const useBindUploadAtom = ( const [upload, setUpload] = useAtom(uploadAtom); const { file } = upload; + // For the failure text: renders and unmount of the component that owns this upload. + const life = useRef({ attachedAt: 0, rendersAtAttach: 0, renders: [] }); + if (life.current.renders.length < 50) life.current.renders.push(Date.now()); + useEffect(() => { + const tracked = life.current; + tracked.unmountedAt = undefined; + return () => { + tracked.unmountedAt = Date.now(); + }; + }, []); + const handleProgress = useThrottle( useCallback((progress: UploadProgress) => setUpload({ progress }), [setUpload]), { immediate: true, wait: 200 } ); - const startUpload = useCallback( - () => - uploadContent(mx, file, { - hideFilename, - onPromise: (promise: Promise) => setUpload({ promise }), - onProgress: handleProgress, - onSuccess: (mxc) => setUpload({ mxc }), - onError: (error) => setUpload({ error }), - }), - [mx, file, hideFilename, setUpload, handleProgress] - ); + const startUpload = useCallback(() => { + life.current.attachedAt = Date.now(); + life.current.rendersAtAttach = life.current.renders.length; + return uploadContent(mx, file, { + hideFilename, + describeLifecycle: () => describeComponentLifecycle(life.current), + onPromise: (promise: Promise) => setUpload({ promise }), + onProgress: handleProgress, + onSuccess: (mxc) => setUpload({ mxc }), + onError: (error) => setUpload({ error }), + }); + }, [mx, file, hideFilename, setUpload, handleProgress]); const cancelUpload = useCallback(async () => { if (upload.status === UploadStatus.Loading) { diff --git a/src/app/utils/matrix.ts b/src/app/utils/matrix.ts index 2859dbc3..f0ded881 100644 --- a/src/app/utils/matrix.ts +++ b/src/app/utils/matrix.ts @@ -143,6 +143,270 @@ export type ContentUploadOptions = { onProgress?: (progress: UploadProgress) => void; onSuccess: (mxc: string) => void; onError: (error: MatrixError) => void; + /** Read at failure time: what the owning component did since the upload attached. */ + describeLifecycle?: () => string; +}; + +let lastUserActivity = Date.now(); +export const noteUserActivity = () => { + lastUserActivity = Date.now(); +}; +if (typeof window !== 'undefined') { + ['pointerdown', 'keydown', 'touchstart'].forEach((type) => + window.addEventListener(type, noteUserActivity, { capture: true, passive: true }) + ); +} + +export type AbortCall = { api: string; frames: string }; + +/** What the progress handler saw of one upload, for the failure text. */ +export type UploadTrace = { + startedAt: number; + firstProgressAt?: number; + loaded?: number; + total?: number; + /** Summary of an earlier attempt of the same upload, when this one is a retry. */ + previous?: string; + /** abort() calls the page made while this attempt ran; absent when not probed. */ + aborts?: AbortCall[]; + /** What the owning component did since the upload attached. */ + lifecycle?: string; + /** Upload XHR events and end state, and whether our own signal was aborted. */ + xhr?: string; + signalAborted?: boolean; +}; + +const MAX_FRAMES = 6; +const MAX_ABORT_CALLS = 4; + +/** + * An Error stack as `file:line:col < file:line:col`, at most six frames. The error line and the + * probe's own frame are dropped; origins and function names are not kept. + */ +export const formatAbortStack = (stack: string): string => { + const frames = stack + .split('\n') + .map((l) => l.trim()) + .filter((l) => l.startsWith('at ') || l.includes('@')) + .map((l) => { + const m = /([^/\s()@]+):(\d+):(\d+)\)?$/.exec(l); + return m ? `${m[1]}:${m[2]}:${m[3]}` : undefined; + }) + .filter((f): f is string => f !== undefined) + .slice(1, 1 + MAX_FRAMES); + return frames.length > 0 ? frames.join(' < ') : 'no stack'; +}; + +export type ComponentLifecycle = { + attachedAt: number; + rendersAtAttach: number; + renders: number[]; + unmountedAt?: number; +}; + +/** What the component that owns an upload did after the upload attached to it. */ +export const describeComponentLifecycle = (life: ComponentLifecycle): string => { + const since = life.renders.slice(life.rendersAtAttach); + const quick = since.filter((t) => t - life.attachedAt <= 300).length; + const unmount = + life.unmountedAt === undefined + ? 'not unmounted' + : `unmounted +${life.unmountedAt - life.attachedAt}ms`; + return `component: ${since.length} renders since attach (${quick} within 300ms), ${unmount}`; +}; + +export type XhrRecord = { + xhr: XMLHttpRequest; + method: string; + path: string; + startedAt: number; + events: string[]; +}; + +type Probe = { calls: AbortCall[]; xhrs: XhrRecord[] }; + +const probes = new Set(); +let restoreProbe: (() => void) | undefined; +const xhrTargets = new WeakMap(); + +const XHR_EVENTS = ['loadstart', 'error', 'abort', 'timeout', 'load', 'loadend']; +const MAX_XHR_EVENTS = 12; + +/* eslint-disable no-param-reassign */ +const patchAbort = (proto: { abort: (...a: any[]) => any }, api: string) => { + const original = proto.abort; + const wrapper = function abortProbe(this: unknown, ...args: any[]) { + const frames = formatAbortStack(new Error().stack ?? ''); + probes.forEach(({ calls }) => { + if (calls.length < MAX_ABORT_CALLS) calls.push({ api, frames }); + }); + return original.apply(this, args); + }; + proto.abort = wrapper; + return () => { + if (proto.abort === wrapper) proto.abort = original; + }; +}; + +// Upload XHRs only; the path is kept and the query (it holds the access token) is dropped. +const patchXhr = (proto: XMLHttpRequest) => { + const { open, send } = proto; + const openWrapper = function openProbe(this: XMLHttpRequest, ...args: any[]) { + try { + const url = new URL(String(args[1]), 'http://x'); + if (url.pathname.includes('/upload')) { + xhrTargets.set(this, { method: String(args[0]).toUpperCase(), path: url.pathname }); + } + } catch { + // not a URL we can read; the request is not recorded + } + return (open as any).apply(this, args); + }; + const sendWrapper = function sendProbe(this: XMLHttpRequest, ...args: any[]) { + const target = xhrTargets.get(this); + if (target && probes.size > 0) { + const startedAt = Date.now(); + const events: string[] = []; + const note = (name: string) => () => { + if (events.length < MAX_XHR_EVENTS) events.push(`${name} +${Date.now() - startedAt}ms`); + }; + XHR_EVENTS.forEach((ev) => this.addEventListener(ev, note(ev))); + XHR_EVENTS.forEach((ev) => this.upload?.addEventListener(ev, note(`upload.${ev}`))); + this.upload?.addEventListener( + 'progress', + (() => { + let first = true; + return () => { + if (first) note('upload.progress')(); + first = false; + }; + })() + ); + const record: XhrRecord = { xhr: this, ...target, startedAt, events }; + probes.forEach((probe) => probe.xhrs.push(record)); + } + return (send as any).apply(this, args); + }; + (proto as any).open = openWrapper; + (proto as any).send = sendWrapper; + return () => { + if ((proto as any).open === openWrapper) (proto as any).open = open; + if ((proto as any).send === sendWrapper) (proto as any).send = send; + }; +}; +/* eslint-enable no-param-reassign */ + +const describeXhr = (r: XhrRecord): string => + `${r.method} ${r.path} readyState ${r.xhr.readyState} status ${ + r.xhr.status + } events [${r.events.join(', ')}]`; + +/** + * Records, until stopped, every XMLHttpRequest.abort and AbortController.abort the page makes and + * the lifecycle events and end state of upload XHRs. The prototypes are wrapped while at least one + * probe runs and restored when the last one stops; the wrappers change no behaviour. + */ +export const startAbortProbe = () => { + const probe: Probe = { calls: [], xhrs: [] }; + if (probes.size === 0) { + const restores: (() => void)[] = []; + if (typeof XMLHttpRequest !== 'undefined') { + restores.push(patchAbort(XMLHttpRequest.prototype, 'XHR.abort')); + restores.push(patchXhr(XMLHttpRequest.prototype)); + } + if (typeof AbortController !== 'undefined') { + restores.push(patchAbort(AbortController.prototype, 'AbortController.abort')); + } + restoreProbe = () => restores.forEach((r) => r()); + } + probes.add(probe); + return { + calls: probe.calls, + xhrs: probe.xhrs, + describeXhrs: () => + probe.xhrs.length === 0 ? 'xhr: none seen' : `xhr: ${probe.xhrs.map(describeXhr).join('; ')}`, + stop: () => { + probes.delete(probe); + if (probes.size === 0) { + restoreProbe?.(); + restoreProbe = undefined; + } + }, + }; +}; + +const describeNetwork = (): string => { + const online = + typeof navigator !== 'undefined' && navigator.onLine === false ? 'offline' : 'online'; + const c = typeof navigator !== 'undefined' ? (navigator as any).connection : undefined; + const net = c + ? `${c.effectiveType ?? '?'} rtt ${c.rtt ?? '?'}ms down ${c.downlink ?? '?'}Mbps saveData ${ + c.saveData ? 'on' : 'off' + }` + : 'n/a'; + const tab = typeof document !== 'undefined' ? document.visibilityState : 'n/a'; + return `${online}, net ${net}, tab ${tab}`; +}; + +/** + * Describe why an upload died. The SDK reports an XHR with status 0 as an AbortError + * DOMException with an empty message, so the text carries what the client can observe: file + * size, type and readability, connectivity, tab visibility, idle time, progress, time to fail. + */ +export const uploadFailure = async ( + e: any, + file: TUploadContent, + trace?: UploadTrace +): Promise => { + const now = Date.now(); + const name = typeof e?.name === 'string' && e.name ? e.name : 'Error'; + const message = typeof e?.message === 'string' ? e.message : ''; + let readable: string; + try { + await file.arrayBuffer(); + readable = 'file readable'; + } catch (readErr: any) { + readable = `file unreadable (${readErr?.name ?? 'unknown'})`; + } + const parts = [`${file.size} bytes`, file.type || 'unknown type', readable, describeNetwork()]; + parts.push(`idle ${now - lastUserActivity}ms`); + if (trace) { + parts.push( + trace.firstProgressAt === undefined + ? 'no progress' + : `first progress ${trace.firstProgressAt - trace.startedAt}ms ${trace.loaded ?? 0}/${ + trace.total ?? '?' + }B` + ); + parts.push(`failed after ${now - trace.startedAt}ms`); + if (trace.aborts) { + parts.push( + trace.aborts.length === 0 + ? 'abort calls: none' + : `abort calls: ${trace.aborts.map((a) => `${a.api} ${a.frames}`).join('; ')}` + ); + } + if (trace.xhr) parts.push(trace.xhr); + if (trace.signalAborted !== undefined) parts.push(`signal.aborted ${trace.signalAborted}`); + if (trace.lifecycle) parts.push(trace.lifecycle); + if (trace.previous) parts.push(`retried (attempt 1: ${trace.previous})`); + } + const error = `Upload failed: ${message ? `${name}: ${message}` : name} (${parts.join(', ')})`; + const err = new MatrixError({ error, errcode: name }); + (err as any).cause = e; + return err; +}; + +// An abort before any progress, within this long, is retried once: the request most likely died on +// a reused connection before a byte left, and the failed attempt discards that connection. Nothing +// here has shown that is the cause; the failure text records both attempts so it can be checked. +const RETRY_WINDOW_MS = 3000; + +const copyInMemory = async (file: TUploadContent): Promise => { + const bytes = await file.arrayBuffer(); + return typeof File !== 'undefined' && file instanceof File + ? new File([bytes], file.name, { type: file.type, lastModified: file.lastModified }) + : new Blob([bytes], { type: file.type }); }; export const uploadContent = async ( @@ -150,24 +414,86 @@ export const uploadContent = async ( file: TUploadContent, options: ContentUploadOptions ) => { - const { name, fileType, hideFilename, onProgress, onPromise, onSuccess, onError } = options; - - const uploadPromise = mx.uploadContent(file, { + const { name, - type: fileType, - includeFilename: !hideFilename, - progressHandler: onProgress, - }); - onPromise?.(uploadPromise); - try { - const data = await uploadPromise; - const mxc = data.content_uri; - if (mxc) onSuccess(mxc); - else onError(new MatrixError(data)); - } catch (e: any) { - const error = typeof e?.message === 'string' ? e.message : undefined; - const errcode = typeof e?.name === 'string' ? e.message : undefined; - onError(new MatrixError({ error, errcode })); + fileType, + hideFilename, + onProgress, + onPromise, + onSuccess, + onError, + describeLifecycle, + } = options; + + let previous: string | undefined; + for (let attempt = 1; ; attempt += 1) { + // The browser may hold a picked file as a handle it cannot always re-read (e.g. content://), so + // each attempt uploads a copy held in memory; a file that cannot be read fails here, named. + let body: TUploadContent; + try { + // eslint-disable-next-line no-await-in-loop + body = await copyInMemory(file); + } catch (readErr: any) { + const errcode = readErr?.name || 'Error'; + onError( + new MatrixError({ + error: `Upload failed: file unreadable before upload (${errcode}) (${file.size} bytes, ${ + file.type || 'unknown type' + })`, + errcode, + }) + ); + return; + } + const probe = startAbortProbe(); + const trace: UploadTrace = { startedAt: Date.now(), previous, aborts: probe.calls }; + const abortController = new AbortController(); + try { + const uploadPromise = mx.uploadContent(body, { + name, + type: fileType, + includeFilename: !hideFilename, + abortController, + progressHandler: (progress) => { + if (trace.firstProgressAt === undefined) trace.firstProgressAt = Date.now(); + trace.loaded = progress.loaded; + trace.total = progress.total; + onProgress?.(progress); + }, + }); + onPromise?.(uploadPromise); + try { + // eslint-disable-next-line no-await-in-loop + const data = await uploadPromise; + const mxc = data.content_uri; + if (mxc) onSuccess(mxc); + else onError(new MatrixError(data)); + return; + } catch (e: any) { + const elapsed = Date.now() - trace.startedAt; + trace.xhr = probe.describeXhrs(); + trace.signalAborted = abortController.signal.aborted; + const retry = + attempt === 1 && + e?.name === 'AbortError' && + !abortController.signal.aborted && + trace.firstProgressAt === undefined && + elapsed < RETRY_WINDOW_MS; + if (!retry) { + trace.lifecycle = describeLifecycle?.(); + // eslint-disable-next-line no-await-in-loop + onError(await uploadFailure(e, file, trace)); + return; + } + previous = `AbortError after ${elapsed}ms, no progress, ${ + trace.aborts?.length + ? `abort calls: ${trace.aborts.map((a) => `${a.api} ${a.frames}`).join('; ')}` + : 'abort calls: none' + }, ${trace.xhr}`; + } + } finally { + probe.stop(); + } } }; diff --git a/src/app/utils/trainingNotice.test.ts b/src/app/utils/trainingNotice.test.ts index 0663d2f9..dce3ee90 100644 --- a/src/app/utils/trainingNotice.test.ts +++ b/src/app/utils/trainingNotice.test.ts @@ -4,7 +4,9 @@ import { ROOM_NOTICE_EVENT_TYPE, TRAINING_NOTICE_TEXT, parseRoomNotice, + PREVIEW_NOTICE_TEXT, roomTrainingLine, + trainingNoticeText, } from './trainingNotice'; const lineFor = (content: unknown) => roomTrainingLine(parseRoomNotice(content)); @@ -66,3 +68,23 @@ describe('training notice', () => { expect(lineFor({ version: 1, scope: ['train'] })).toBeUndefined(); }); }); + +describe('training notice on the pretend server', () => { + it('states that nothing is trained instead of the real sentence', () => { + expect(trainingNoticeText(true)).toBe(PREVIEW_NOTICE_TEXT); + expect(PREVIEW_NOTICE_TEXT).not.toContain('may be used to train'); + expect(PREVIEW_NOTICE_TEXT.toLowerCase()).toContain('pretend'); + }); + + it('keeps the ruled sentence everywhere else', () => { + expect(trainingNoticeText(false)).toBe(TRAINING_NOTICE_TEXT); + expect(trainingNoticeText(undefined)).toBe(TRAINING_NOTICE_TEXT); + }); + + it('shows the same text in a train room and at registration', () => { + const notice = parseRoomNotice({ version: 1, scope: 'train' }); + expect(roomTrainingLine(notice, true)).toBe(trainingNoticeText(true)); + expect(roomTrainingLine(notice, false)).toBe(trainingNoticeText(false)); + expect(roomTrainingLine(parseRoomNotice({ version: 1, scope: 'show' }), true)).toBeUndefined(); + }); +}); diff --git a/src/app/utils/trainingNotice.ts b/src/app/utils/trainingNotice.ts index 7f60cce4..e2c1de00 100644 --- a/src/app/utils/trainingNotice.ts +++ b/src/app/utils/trainingNotice.ts @@ -3,6 +3,15 @@ import { StateEvent } from '../../types/matrix/room'; export const TRAINING_NOTICE_TEXT = "Everything said here may be used to train GameCult's AI stewards."; +// The preview build runs against a pretend server where nothing is trained, so the real sentence +// would be false there. The real wording awaits Meta's legal read (Heimdall's consent text, open). +export const PREVIEW_NOTICE_TEXT = + 'Pretend server: nothing you type here is stored or used to train anything.'; + +/** The one sentence every first-typing surface shows: the real one, or the pretend server's. */ +export const trainingNoticeText = (previewDemo?: boolean): string => + previewDemo === true ? PREVIEW_NOTICE_TEXT : TRAINING_NOTICE_TEXT; + /** * Heimdall's ruling: a room's notice is a room state event, not a pinned message. Type below, * state_key '', content `{version, scope}`; scope exactly one of show, study or train. Heimdall's @@ -31,5 +40,7 @@ export const parseRoomNotice = (content: unknown): RoomNotice | undefined => { }; /** The line a room shows: only a notice that says `train` in terms gets the train sentence. */ -export const roomTrainingLine = (notice: RoomNotice | undefined): string | undefined => - notice?.scope === 'train' ? TRAINING_NOTICE_TEXT : undefined; +export const roomTrainingLine = ( + notice: RoomNotice | undefined, + previewDemo?: boolean +): string | undefined => (notice?.scope === 'train' ? trainingNoticeText(previewDemo) : undefined); diff --git a/src/app/utils/uploadAbortProbe.test.ts b/src/app/utils/uploadAbortProbe.test.ts new file mode 100644 index 00000000..557908ef --- /dev/null +++ b/src/app/utils/uploadAbortProbe.test.ts @@ -0,0 +1,171 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { + describeComponentLifecycle, + formatAbortStack, + startAbortProbe, + uploadContent, + uploadFailure, +} from './matrix'; + +const chromeStack = [ + 'Error', + ' at wrapper (https://chat.example/assets/index-abc.js:1:100)', + ' at https://chat.example/assets/index-abc.js:1:200', + ' at Object.cb (https://chat.example/assets/vendor-def.js:7:8)', + ' at https://chat.example/assets/a.js:2:3', + ' at https://chat.example/assets/b.js:4:5', + ' at https://chat.example/assets/c.js:6:7', + ' at https://chat.example/assets/d.js:8:9', + ' at https://chat.example/assets/e.js:10:11', +].join('\n'); + +describe('formatAbortStack', () => { + it('keeps at most six frames as file:line:col, skipping the probe wrapper and the error line', () => { + const out = formatAbortStack(chromeStack); + const frames = out.split(' < '); + expect(frames).toHaveLength(6); + expect(frames[0]).toBe('index-abc.js:1:200'); + expect(out).not.toContain('https://'); + expect(out).not.toContain('wrapper'); + }); + + it('copes with an empty stack', () => { + expect(formatAbortStack('')).toBe('no stack'); + }); +}); + +describe('abort probe', () => { + const original = AbortController.prototype.abort; + + afterEach(() => { + vi.unstubAllGlobals(); + AbortController.prototype.abort = original; + }); + + it('records an AbortController.abort made while it runs, still aborts, and restores afterwards', () => { + const probe = startAbortProbe(); + expect(AbortController.prototype.abort).not.toBe(original); + const c = new AbortController(); + c.abort(); + expect(c.signal.aborted).toBe(true); + probe.stop(); + expect(AbortController.prototype.abort).toBe(original); + expect(probe.calls).toHaveLength(1); + expect(probe.calls[0].api).toBe('AbortController.abort'); + }); + + it('records XMLHttpRequest.prototype.abort and restores it', () => { + const xhrAbort = vi.fn(); + class FakeXhr { + // eslint-disable-next-line class-methods-use-this + abort() { + xhrAbort(); + } + } + vi.stubGlobal('XMLHttpRequest', FakeXhr); + const probe = startAbortProbe(); + new FakeXhr().abort(); + probe.stop(); + expect(xhrAbort).toHaveBeenCalledTimes(1); + expect(probe.calls.map((c) => c.api)).toContain('XHR.abort'); + expect(FakeXhr.prototype.abort.toString()).not.toContain('collectors'); + const after = new FakeXhr(); + after.abort(); + expect(xhrAbort).toHaveBeenCalledTimes(2); + }); + + it('records nothing after stop', () => { + const probe = startAbortProbe(); + probe.stop(); + new AbortController().abort(); + expect(probe.calls).toHaveLength(0); + }); + + it('keeps the wrapper until the last overlapping probe stops, then restores the original', () => { + const a = startAbortProbe(); + const b = startAbortProbe(); + a.stop(); + new AbortController().abort(); + expect(b.calls).toHaveLength(1); + expect(a.calls).toHaveLength(0); + b.stop(); + expect(AbortController.prototype.abort).toBe(original); + }); + + it('restores the original when the upload attempt throws', async () => { + const mx = { uploadContent: () => Promise.reject(new Error('boom')) } as any; + await uploadContent(mx, new Blob(['x']), { onSuccess: vi.fn(), onError: vi.fn() }); + expect(AbortController.prototype.abort).toBe(original); + }); + + it('restores the original when uploadContent itself throws synchronously', async () => { + const mx = { + uploadContent: () => { + throw new Error('sync'); + }, + } as any; + await expect( + uploadContent(mx, new Blob(['x']), { onSuccess: vi.fn(), onError: vi.fn() }) + ).rejects.toThrow('sync'); + expect(AbortController.prototype.abort).toBe(original); + }); +}); + +describe('failure text', () => { + const abort = () => new DOMException('', 'AbortError'); + + it('lists abort calls seen during the attempt', async () => { + const mx = { + uploadContent: () => { + new AbortController().abort(); + return Promise.reject(abort()); + }, + } as any; + const onError = vi.fn(); + await uploadContent(mx, new Blob(['x']), { onSuccess: vi.fn(), onError }); + // retried once: the final message carries the second attempt and attempt 1's summary + const msg = onError.mock.calls[0][0].message; + expect(msg).toContain('abort calls: AbortController.abort'); + expect(msg).toContain('retried (attempt 1: AbortError'); + }); + + it('says none when nothing in the page called abort', async () => { + const err = await uploadFailure(abort(), new Blob(['x']), { + startedAt: Date.now(), + aborts: [], + }); + expect(err.message).toContain('abort calls: none'); + }); + + it('reports the component lifecycle when given', async () => { + const mx = { uploadContent: () => Promise.reject(new Error('Timeout')) } as any; + const onError = vi.fn(); + await uploadContent(mx, new Blob(['x']), { + onSuccess: vi.fn(), + onError, + describeLifecycle: () => 'component remounted 0x, renders 3 (2 within 300ms)', + }); + expect(onError.mock.calls[0][0].message).toContain('renders 3 (2 within 300ms)'); + }); +}); + +describe('describeComponentLifecycle', () => { + it('counts renders after attach and those within 300ms, and reports an unmount', () => { + const text = describeComponentLifecycle({ + attachedAt: 1000, + rendersAtAttach: 1, + renders: [990, 1100, 1250, 1400], + unmountedAt: 1500, + }); + expect(text).toBe('component: 3 renders since attach (2 within 300ms), unmounted +500ms'); + }); + + it('says not unmounted when it was not', () => { + const text = describeComponentLifecycle({ + attachedAt: 1000, + rendersAtAttach: 1, + renders: [990], + }); + expect(text).toBe('component: 0 renders since attach (0 within 300ms), not unmounted'); + }); +}); diff --git a/src/app/utils/uploadFailure.test.ts b/src/app/utils/uploadFailure.test.ts new file mode 100644 index 00000000..ec1e8115 --- /dev/null +++ b/src/app/utils/uploadFailure.test.ts @@ -0,0 +1,100 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { noteUserActivity, uploadFailure } from './matrix'; + +const abort = () => new DOMException('', 'AbortError'); + +describe('uploadFailure', () => { + it('keeps the error name as errcode, never the message', async () => { + const err = await uploadFailure(abort(), new Blob(['abc'], { type: 'image/png' })); + expect(err.errcode).toBe('AbortError'); + }); + + it('never reduces an empty-message error to "Unknown message"', async () => { + const err = await uploadFailure(abort(), new Blob(['abc'])); + expect(err.message).not.toContain('Unknown message'); + expect(err.message).toContain('AbortError'); + }); + + it('reports size and type of the file', async () => { + const err = await uploadFailure(abort(), new Blob(['abcd'], { type: 'image/png' })); + expect(err.message).toContain('4 bytes'); + expect(err.message).toContain('image/png'); + }); + + it('keeps the original error as cause', async () => { + const e = abort(); + const err = await uploadFailure(e, new Blob(['x'])); + expect((err as any).cause).toBe(e); + }); + + it('says whether the browser could still read the file', async () => { + const ok = await uploadFailure(abort(), new Blob(['x'])); + expect(ok.message).toContain('file readable'); + const bad = new Blob(['x']); + (bad as any).arrayBuffer = () => Promise.reject(new DOMException('gone', 'NotReadableError')); + const err = await uploadFailure(abort(), bad); + expect(err.message).toContain('file unreadable (NotReadableError)'); + }); + + it('keeps a real message when the error has one', async () => { + const err = await uploadFailure(new Error('Timeout'), new Blob(['x'])); + expect(err.message).toContain('Timeout'); + expect(err.errcode).toBe('Error'); + }); +}); + +describe('uploadFailure client trace', () => { + const blob = new Blob(['abcd'], { type: 'image/jpeg' }); + + afterEach(() => { + vi.useRealTimers(); + vi.unstubAllGlobals(); + }); + + it('reports connectivity, visibility and idle time at the moment of failure', async () => { + vi.useFakeTimers(); + vi.setSystemTime(10_000); + vi.stubGlobal('navigator', { + onLine: false, + connection: { effectiveType: '3g', rtt: 300, downlink: 1.5, saveData: true }, + }); + vi.stubGlobal('document', { visibilityState: 'hidden' }); + noteUserActivity(); + vi.setSystemTime(13_000); + const err = await uploadFailure(abort(), blob, { startedAt: 12_000 }); + expect(err.message).toContain('offline'); + expect(err.message).toContain('3g rtt 300ms down 1.5Mbps saveData on'); + expect(err.message).toContain('tab hidden'); + expect(err.message).toContain('idle 3000ms'); + expect(err.message).toContain('failed after 1000ms'); + }); + + it('says so when no progress event ever arrived', async () => { + vi.useFakeTimers(); + vi.setSystemTime(5_000); + const err = await uploadFailure(abort(), blob, { startedAt: 4_000 }); + expect(err.message).toContain('no progress'); + }); + + it('reports time to first progress and bytes loaded when some arrived', async () => { + vi.useFakeTimers(); + vi.setSystemTime(9_000); + const err = await uploadFailure(abort(), blob, { + startedAt: 5_000, + firstProgressAt: 5_120, + loaded: 65536, + total: 700000, + }); + expect(err.message).toContain('first progress 120ms'); + expect(err.message).toContain('65536/700000B'); + expect(err.message).toContain('failed after 4000ms'); + }); + + it('copes with a browser that has no connection info or document', async () => { + vi.stubGlobal('navigator', { onLine: true }); + vi.stubGlobal('document', undefined); + const err = await uploadFailure(abort(), blob, { startedAt: Date.now() }); + expect(err.message).toContain('online'); + expect(err.message).toContain('net n/a'); + }); +}); diff --git a/src/app/utils/uploadRetry.test.ts b/src/app/utils/uploadRetry.test.ts new file mode 100644 index 00000000..3e9957c2 --- /dev/null +++ b/src/app/utils/uploadRetry.test.ts @@ -0,0 +1,113 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { uploadContent } from './matrix'; + +const abort = () => new DOMException('', 'AbortError'); +const blob = new Blob(['abcd'], { type: 'image/jpeg' }); + +type Step = (opts: any) => Promise; +const fakeMx = (steps: Step[]) => { + const calls: any[] = []; + const mx = { + uploadContent: vi.fn((_file: unknown, opts: any) => { + calls.push(opts); + return steps[calls.length - 1](opts); + }), + }; + return { mx: mx as any, calls }; +}; +const run = async (mx: any) => { + const onSuccess = vi.fn(); + const onError = vi.fn(); + const onPromise = vi.fn(); + await uploadContent(mx, blob, { onSuccess, onError, onPromise }); + return { onSuccess, onError, onPromise }; +}; + +describe('uploadContent retry', () => { + afterEach(() => vi.useRealTimers()); + + it('retries once when the first attempt aborts at once with no progress', async () => { + const { mx } = fakeMx([ + () => Promise.reject(abort()), + async () => ({ content_uri: 'mxc://a/b' }), + ]); + const r = await run(mx); + expect(mx.uploadContent).toHaveBeenCalledTimes(2); + expect(r.onSuccess).toHaveBeenCalledWith('mxc://a/b'); + expect(r.onError).not.toHaveBeenCalled(); + expect(r.onPromise).toHaveBeenCalledTimes(2); + }); + + it('retries at most once and reports both attempts when the retry fails too', async () => { + const { mx } = fakeMx([() => Promise.reject(abort()), () => Promise.reject(abort())]); + const r = await run(mx); + expect(mx.uploadContent).toHaveBeenCalledTimes(2); + const msg = r.onError.mock.calls[0][0].message; + expect(msg).toContain('retried'); + expect(msg).toContain('attempt 1: AbortError'); + expect(msg).toContain('no progress'); + }); + + it('never retries after a progress event', async () => { + const { mx } = fakeMx([ + (opts) => { + opts.progressHandler({ loaded: 10, total: 100 }); + return Promise.reject(abort()); + }, + async () => ({ content_uri: 'mxc://a/b' }), + ]); + const r = await run(mx); + expect(mx.uploadContent).toHaveBeenCalledTimes(1); + expect(r.onError).toHaveBeenCalledTimes(1); + expect(r.onError.mock.calls[0][0].message).not.toContain('retried'); + }); + + it('never retries after the user cancelled', async () => { + const { mx } = fakeMx([ + (opts) => { + opts.abortController.abort(); + return Promise.reject(abort()); + }, + async () => ({ content_uri: 'mxc://a/b' }), + ]); + const r = await run(mx); + expect(mx.uploadContent).toHaveBeenCalledTimes(1); + expect(r.onError).toHaveBeenCalledTimes(1); + }); + + it('never retries an error that is not an abort', async () => { + const { mx } = fakeMx([() => Promise.reject(new Error('Timeout')), async () => ({})]); + const r = await run(mx); + expect(mx.uploadContent).toHaveBeenCalledTimes(1); + expect(r.onError).toHaveBeenCalledTimes(1); + }); + + it('never retries an abort that took three seconds or more', async () => { + vi.useFakeTimers(); + vi.setSystemTime(0); + const { mx } = fakeMx([ + () => { + vi.setSystemTime(3000); + return Promise.reject(abort()); + }, + async () => ({ content_uri: 'mxc://a/b' }), + ]); + const r = await run(mx); + expect(mx.uploadContent).toHaveBeenCalledTimes(1); + expect(r.onError).toHaveBeenCalledTimes(1); + }); + + it('retries the same abort at 2999ms', async () => { + vi.useFakeTimers(); + vi.setSystemTime(0); + const { mx } = fakeMx([ + () => { + vi.setSystemTime(2999); + return Promise.reject(abort()); + }, + async () => ({ content_uri: 'mxc://a/b' }), + ]); + await run(mx); + expect(mx.uploadContent).toHaveBeenCalledTimes(2); + }); +}); diff --git a/src/app/utils/uploadXhrProbe.test.ts b/src/app/utils/uploadXhrProbe.test.ts new file mode 100644 index 00000000..e72afa3d --- /dev/null +++ b/src/app/utils/uploadXhrProbe.test.ts @@ -0,0 +1,163 @@ +/* eslint-disable class-methods-use-this, @typescript-eslint/no-empty-function, @typescript-eslint/no-unused-vars, no-unused-vars */ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { startAbortProbe, uploadContent } from './matrix'; + +class FakeXhr extends EventTarget { + upload = new EventTarget(); + + readyState = 0; + + status = 0; + + open(_method: string, _url: string) { + this.readyState = 1; + } + + send() { + this.readyState = 2; + } + + abort() {} +} + +const origOpen = FakeXhr.prototype.open; +const origSend = FakeXhr.prototype.send; +const uploadUrl = + 'https://matrix.example/_matrix/media/v3/upload?filename=a.jpg&access_token=SECRET'; + +describe('XHR probe', () => { + afterEach(() => { + vi.unstubAllGlobals(); + FakeXhr.prototype.open = origOpen; + FakeXhr.prototype.send = origSend; + }); + + it('records which events an upload XHR fired and how it ended, without the query string', () => { + vi.stubGlobal('XMLHttpRequest', FakeXhr); + const probe = startAbortProbe(); + const x = new FakeXhr(); + x.open('POST', uploadUrl); + x.send(); + x.upload.dispatchEvent(new Event('loadstart')); + x.upload.dispatchEvent(new Event('error')); + x.dispatchEvent(new Event('error')); + x.readyState = 4; + x.status = 0; + probe.stop(); + expect(probe.xhrs).toHaveLength(1); + const text = probe.describeXhrs(); + expect(text).toContain('POST /_matrix/media/v3/upload'); + expect(text).toContain('readyState 4 status 0'); + expect(text).toContain('upload.loadstart'); + expect(text).toContain('upload.error'); + expect(text).toContain('error'); + expect(text).not.toContain('SECRET'); + expect(text).not.toContain('access_token'); + }); + + it('ignores XHRs that are not uploads', () => { + vi.stubGlobal('XMLHttpRequest', FakeXhr); + const probe = startAbortProbe(); + const x = new FakeXhr(); + x.open('GET', 'https://matrix.example/_matrix/client/v3/sync'); + x.send(); + probe.stop(); + expect(probe.xhrs).toHaveLength(0); + expect(probe.describeXhrs()).toBe('xhr: none seen'); + }); + + it('still calls the real open and send and restores both afterwards', () => { + const open = vi.fn(); + const send = vi.fn(); + FakeXhr.prototype.open = open; + FakeXhr.prototype.send = send; + vi.stubGlobal('XMLHttpRequest', FakeXhr); + const probe = startAbortProbe(); + const x = new FakeXhr(); + x.open('POST', uploadUrl); + x.send(); + expect(open).toHaveBeenCalledWith('POST', uploadUrl); + expect(send).toHaveBeenCalledTimes(1); + probe.stop(); + expect(FakeXhr.prototype.open).toBe(open); + expect(FakeXhr.prototype.send).toBe(send); + }); + + it('records nothing for requests made after stop', () => { + vi.stubGlobal('XMLHttpRequest', FakeXhr); + const probe = startAbortProbe(); + probe.stop(); + const x = new FakeXhr(); + x.open('POST', uploadUrl); + x.send(); + expect(probe.xhrs).toHaveLength(0); + }); +}); + +describe('uploadContent in-memory copy and failure line', () => { + const abort = () => new DOMException('', 'AbortError'); + + it('uploads an in-memory copy with the same bytes, name and type, not the original', async () => { + const file = new File(['abcdef'], 'a.jpg', { type: 'image/jpeg' }); + let sent: any; + const mx = { + uploadContent: vi.fn(async (f: any) => { + sent = f; + return { content_uri: 'mxc://a/b' }; + }), + } as any; + await uploadContent(mx, file, { onSuccess: vi.fn(), onError: vi.fn() }); + expect(sent).not.toBe(file); + expect(sent.type).toBe('image/jpeg'); + expect(sent.name).toBe('a.jpg'); + expect(await sent.text()).toBe('abcdef'); + }); + + it('copies again before the retry', async () => { + const seen: any[] = []; + const mx = { + uploadContent: vi.fn((f: any) => { + seen.push(f); + return seen.length === 1 + ? Promise.reject(abort()) + : Promise.resolve({ content_uri: 'mxc://a/b' }); + }), + } as any; + await uploadContent(mx, new Blob(['xy']), { onSuccess: vi.fn(), onError: vi.fn() }); + expect(seen).toHaveLength(2); + expect(seen[0]).not.toBe(seen[1]); + }); + + it('reports an unreadable file and never starts the upload', async () => { + const bad = new Blob(['x']); + (bad as any).arrayBuffer = () => Promise.reject(new DOMException('gone', 'NotReadableError')); + const mx = { uploadContent: vi.fn() } as any; + const onError = vi.fn(); + await uploadContent(mx, bad, { onSuccess: vi.fn(), onError }); + expect(mx.uploadContent).not.toHaveBeenCalled(); + expect(onError.mock.calls[0][0].message).toContain( + 'unreadable before upload (NotReadableError)' + ); + }); + + it('puts the XHR end state and signal.aborted in the failure line', async () => { + vi.stubGlobal('XMLHttpRequest', FakeXhr); + const mx = { + uploadContent: () => { + const x = new FakeXhr(); + x.open('POST', uploadUrl); + x.send(); + x.upload.dispatchEvent(new Event('error')); + x.readyState = 4; + return Promise.reject(new Error('Timeout')); + }, + } as any; + const onError = vi.fn(); + await uploadContent(mx, new Blob(['x']), { onSuccess: vi.fn(), onError }); + const msg = onError.mock.calls[0][0].message; + expect(msg).toContain('readyState 4 status 0'); + expect(msg).toContain('upload.error'); + expect(msg).toContain('signal.aborted false'); + vi.unstubAllGlobals(); + }); +}); diff --git a/src/preview-demo/fixtures.ts b/src/preview-demo/fixtures.ts index 32d3c7a6..c96a4ccf 100644 --- a/src/preview-demo/fixtures.ts +++ b/src/preview-demo/fixtures.ts @@ -23,6 +23,7 @@ export const USERS: DemoUser[] = [ { id: `@void:${DEMO_SERVER}`, name: 'Void' }, { id: `@nibu:${DEMO_SERVER}`, name: 'Nibu' }, { id: `@visitor:${DEMO_SERVER}`, name: 'Visitor' }, + { id: `@heimdall:${DEMO_SERVER}`, name: 'Heimdall of the Long Watch, Keeper of the Bridge' }, ]; const user = (localpart: string) => `@${localpart}:${DEMO_SERVER}`; @@ -110,6 +111,8 @@ export const ROOMS: DemoRoom[] = [ pose: 'deadpan', minutesAgo: 25, }, + // A long display name: the name pill has to show all of it on a phone. + { from: user('heimdall'), body: 'Ok.', pose: 'thinking', minutesAgo: 20 }, ], }, { diff --git a/src/preview-demo/install.ts b/src/preview-demo/install.ts index 36990a57..a7b66de9 100644 --- a/src/preview-demo/install.ts +++ b/src/preview-demo/install.ts @@ -30,46 +30,18 @@ const BANNER_TEXT = 'preview: pretend server. Any password works.'; const FOREIGN_SESSION_TEXT = 'preview: pretend server. A login for another server is stored here and cannot be used.'; +// In flow, above the app: body becomes a column and the app root takes the rest, so the banner +// never covers the room header or the connection strip. const showBanner = (text: string) => { const el = document.createElement('div'); el.textContent = text; el.setAttribute('role', 'status'); el.style.cssText = - 'position:fixed;top:0;left:50%;transform:translateX(-50%);z-index:2147483647;max-width:96vw;' + - 'padding:0 8px;font:10px/1.5 system-ui,sans-serif;white-space:nowrap;opacity:0.9;color:#1b1b1b;background:#ffc46b;' + - 'border-radius:0 0 6px 6px;pointer-events:none;text-align:center'; - document.body.appendChild(el); -}; - -// The preview host's CSP sandbox has no allow-forms, so the browser cancels a native form -// submission before its submit event fires and no login button works. Deliver the event ourselves; -// nothing is submitted natively. Remove this when the host grants allow-forms to /void/rat-*. -const deliverSubmitEvents = (doc: Document) => { - const submit = (form: HTMLFormElement) => - form.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true })); - doc.addEventListener( - 'click', - (e) => { - const button = (e.target as Element | null)?.closest?.( - 'button[type="submit"], input[type="submit"]' - ); - const form = (button as HTMLButtonElement | null)?.form; - if (!form || (button as HTMLButtonElement).disabled) return; - e.preventDefault(); - submit(form); - }, - true - ); - doc.addEventListener( - 'keydown', - (e) => { - const target = e.target as HTMLInputElement | null; - if (e.key !== 'Enter' || e.isComposing || target?.tagName !== 'INPUT' || !target.form) return; - e.preventDefault(); - submit(target.form); - }, - true - ); + 'flex:none;padding:2px 8px;font:11px/1.4 system-ui,sans-serif;color:#1b1b1b;background:#ffc46b;text-align:center'; + const root = document.getElementById('root'); + document.body.style.cssText += ';display:flex;flex-direction:column'; + if (root) root.style.cssText += ';flex:1;min-height:0;height:auto'; + document.body.insertBefore(el, root); }; const parseBody = (body: unknown): unknown => { @@ -139,7 +111,6 @@ export const installDemo = (win: Window & typeof globalThis = window) => { routeOf(String(url), origin) === 'own' ? realBeacon(url, data) : false; } - deliverSubmitEvents(document); const stored = win.localStorage.getItem('cinny_hs_base_url'); showBanner(stored !== null && stored !== DEMO_ORIGIN ? FOREIGN_SESSION_TEXT : BANNER_TEXT); return server; diff --git a/src/preview-demo/server.test.ts b/src/preview-demo/server.test.ts index e3cc977e..d277b97b 100644 --- a/src/preview-demo/server.test.ts +++ b/src/preview-demo/server.test.ts @@ -237,7 +237,8 @@ describe('the guard', () => { } as unknown as Window & typeof globalThis; vi.stubGlobal('document', { createElement: () => ({ style: {}, setAttribute: vi.fn() }), - body: { appendChild: vi.fn() }, + getElementById: () => null, + body: { style: {}, insertBefore: vi.fn() }, addEventListener: vi.fn(), }); const server = installDemo(win);