Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 08bf515997 | |||
| f8115609b2 | |||
| 450a7e91ff | |||
| 94c976632e | |||
| b6da92a081 | |||
| 7045532187 | |||
| ac7a958f5c | |||
| 3def499b0f | |||
| 8e0e3b8986 | |||
| c286c4adc4 | |||
| 1fe3e2c92f | |||
|
|
d172c4eda3 | ||
|
|
9391e4753f | ||
| 313d070dd4 | |||
| 51d5fb0909 | |||
|
|
0f82576d9f | ||
|
|
8dea8717ea | ||
|
|
0351f1f6e8 | ||
|
|
de6f1849ea | ||
|
|
06d530d061 | ||
| 84770a2d2c | |||
|
|
5bb78b21cf | ||
| 7bac860016 | |||
|
|
d16842a70e | ||
|
|
08b23e0cc4 | ||
| 61e7539f01 | |||
|
|
9440921181 | ||
|
|
73754a0912 | ||
|
|
3e173d2fed | ||
|
|
84b2a93b8e | ||
|
|
20acd3d384 | ||
|
|
5def1bdfb8 | ||
| 66c4c6373b | |||
|
|
14ea0dbab0 | ||
| 0fe9ab2eee | |||
|
|
de9955a24a | ||
| 1499e9a810 | |||
|
|
aa0dfc0ee9 | ||
| 683d3b92f8 | |||
| bf8b889a0e | |||
|
|
f1287a6f3a | ||
| 3203a32b73 | |||
|
|
1dea4b51e5 | ||
| 64edacac4d | |||
|
|
9877154033 | ||
| dce50eeaf6 | |||
|
|
3c868254e5 | ||
|
|
3c92696507 | ||
|
|
9641cfb4f4 | ||
|
|
9b9b495def | ||
| 854b151d80 | |||
| 23bc67a1f0 | |||
|
|
48d6d171da | ||
|
|
814fa4b3ab | ||
|
|
d2d6fbcc00 | ||
|
|
556254f46b | ||
|
|
c657d68615 | ||
|
|
384cd17dac | ||
|
|
9d3343bb31 | ||
|
|
0fe41efb9b | ||
|
|
c4689299ca | ||
|
|
fcabaee59e | ||
|
|
5712068902 | ||
| f320016ddc | |||
| 320aeecc2c | |||
| 7494591624 | |||
| b5e93510e8 | |||
| 271729a5c0 | |||
| 30ae5154f5 | |||
| 2e6d4d042a | |||
| 56bc40abe6 | |||
| eb6efeee91 | |||
| ea238cf77d | |||
|
|
91e93e6887 | ||
| 0931901b24 | |||
| de504f8286 | |||
| 5666299396 | |||
| 6a93664813 | |||
| 7556fed31e | |||
| 098e45f122 | |||
| 596f864668 | |||
|
|
61f434a32d | ||
| afae8a13c9 | |||
|
|
2c271c6ded | ||
|
|
7bc28f9256 | ||
| a6364af8e3 | |||
| ea6dee80ae | |||
|
|
d03ec36107 | ||
|
|
e1ebf7ec91 | ||
|
|
80d3ae1c9b | ||
|
|
c13e90539f | ||
| f0bad585b6 | |||
|
|
577d795189 | ||
|
|
eafa3eda79 | ||
|
|
4177bdcccb | ||
|
|
5d3db9e1f2 | ||
|
|
0c6d4476be | ||
| dc4b1f1818 | |||
|
|
8f8536a805 | ||
|
|
8a05668d84 | ||
|
|
111fa02994 | ||
|
|
0d26b71862 | ||
| 913a66ebf0 | |||
| 78f5f4dbb2 | |||
|
|
76daf7cdca | ||
|
|
5862bbdba2 | ||
|
|
ce16609c76 | ||
|
|
3be90875ec | ||
|
|
c180385476 | ||
|
|
edc6a9a8f1 | ||
|
|
6c22d4f1dc | ||
|
|
8c02b85796 | ||
|
|
0e0cff66ae | ||
| a9a75fc6ff | |||
|
|
32cc8d6ad6 | ||
|
|
a3a500a3d2 | ||
| a129866236 | |||
|
|
571a2de3fa | ||
| 47ad5cc9d6 | |||
|
|
3b61f2babf | ||
|
|
ecdf5e9d29 | ||
| 7a7f5ceee1 | |||
|
|
ef961636c3 | ||
|
|
a773bc4932 | ||
|
|
78a7dbe923 | ||
| 030417f27a | |||
| deb4e0dfe6 | |||
|
|
b13bb9ecb3 | ||
|
|
9b4d92c9de | ||
| 9794714f97 | |||
| dfc74c252a | |||
|
|
cfb8a8641a | ||
| 9ab8bbeb33 | |||
| 7a5fa81be7 | |||
| 1a33fa55d5 | |||
| 747f2d505b | |||
| fa1ce2b50e | |||
| 82dc0d0a9b | |||
|
|
0438cbc8da | ||
|
|
a23dd239ba | ||
|
|
6110292e3b | ||
|
|
14312459f2 | ||
|
|
245eb90f63 | ||
|
|
8ca38c4980 | ||
|
|
34bdccd87c | ||
|
|
ea33ab6daa | ||
|
|
b091f65cea | ||
|
|
8ac43bd73f | ||
|
|
20cc2c682d | ||
|
|
f7725545a5 | ||
|
|
25765c44c5 | ||
|
|
3e57865eca | ||
|
|
c35ac7e5cd | ||
|
|
685abbb19b | ||
|
|
be947a0bf9 | ||
|
|
58df7b833c | ||
|
|
1296f18338 | ||
|
|
95f0dce05f | ||
|
|
a1aece7d36 | ||
|
|
16cc05a33b | ||
|
|
252fabc138 | ||
|
|
e007514af3 | ||
|
|
ba592523d8 | ||
|
|
002e0d608b | ||
|
|
089dcc86e1 | ||
|
|
b6a97046b0 | ||
|
|
40b1e775fe | ||
|
|
45aad35efa | ||
|
|
c2858452e7 | ||
|
|
f1d8db0c61 | ||
|
|
636cad9655 | ||
|
|
d2c2c279e2 | ||
|
|
2299adefb5 | ||
|
|
0386065f2c | ||
|
|
054c584ebc | ||
|
|
da12cb8708 | ||
|
|
931f84fcd1 | ||
|
|
19c1f21610 | ||
|
|
4afd37e7dd | ||
|
|
fd5134e510 | ||
|
|
7216456a27 | ||
|
|
9e34664550 | ||
|
|
5642acf2f9 | ||
|
|
077737830e | ||
|
|
833c477785 | ||
|
|
b8f2bb462e |
|
|
@ -1,3 +1,8 @@
|
|||
// Airbnb's own bans, kept: a `no-restricted-syntax` entry below replaces the whole list.
|
||||
const airbnbRestrictedSyntax = require('eslint-config-airbnb-base/rules/style').rules[
|
||||
'no-restricted-syntax'
|
||||
];
|
||||
|
||||
module.exports = {
|
||||
env: {
|
||||
browser: true,
|
||||
|
|
@ -62,6 +67,21 @@ module.exports = {
|
|||
"@typescript-eslint/no-shadow": "error"
|
||||
},
|
||||
overrides: [
|
||||
{
|
||||
// The one join path: a join is `joinEstateRoom`, which files the DM before it sends the join.
|
||||
files: ['src/**/*.ts', 'src/**/*.tsx'],
|
||||
excludedFiles: ['src/app/features/estate/joinEstateRoom.ts', 'src/**/*.test.*'],
|
||||
rules: {
|
||||
'no-restricted-syntax': [
|
||||
...airbnbRestrictedSyntax,
|
||||
{
|
||||
selector: "CallExpression[callee.property.name='joinRoom']",
|
||||
message:
|
||||
'Join a room through joinEstateRoom (features/estate/joinEstateRoom.ts), the one join path.',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
files: ['*.ts'],
|
||||
rules: {
|
||||
|
|
|
|||
20
.github/workflows/build-pull-request.yml
vendored
|
|
@ -4,12 +4,14 @@ on:
|
|||
pull_request:
|
||||
types: ['opened', 'synchronize']
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-pr-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
build-pull-request:
|
||||
name: Build pull request
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
PR_NUMBER: ${{github.event.number}}
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
|
|
@ -24,17 +26,3 @@ jobs:
|
|||
env:
|
||||
NODE_OPTIONS: '--max_old_space_size=4096'
|
||||
run: npm run build
|
||||
- name: Upload artifact
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: preview
|
||||
path: dist
|
||||
retention-days: 1
|
||||
- name: Save pr number
|
||||
run: echo ${PR_NUMBER} > ./pr.txt
|
||||
- name: Upload pr number
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: pr
|
||||
path: ./pr.txt
|
||||
retention-days: 1
|
||||
|
|
|
|||
4
.github/workflows/docker-pr.yml
vendored
|
|
@ -6,6 +6,10 @@ on:
|
|||
- 'Dockerfile'
|
||||
- '.github/workflows/docker-pr.yml'
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-pr-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
docker-build:
|
||||
runs-on: ubuntu-latest
|
||||
|
|
|
|||
4
.github/workflows/lockfile.yml
vendored
|
|
@ -5,6 +5,10 @@ on:
|
|||
paths:
|
||||
- 'package-lock.json'
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-pr-${{ github.event.pull_request.number }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
lockfile_changes:
|
||||
runs-on: ubuntu-latest
|
||||
|
|
|
|||
7
.github/workflows/rat-dev-preview.yml
vendored
|
|
@ -4,6 +4,13 @@ on:
|
|||
push:
|
||||
branches: ['dev']
|
||||
|
||||
# One run per ref wins: a newer push to dev cancels the older queued or running one, so the run
|
||||
# that builds rat-dev-dist is always the newest. Pull-request runs are other workflows and other
|
||||
# groups; they never cancel it.
|
||||
concurrency:
|
||||
group: rat-dev-preview
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: Build dev preview
|
||||
|
|
|
|||
20
config.json
|
|
@ -1,6 +1,13 @@
|
|||
{
|
||||
"defaultHomeserver": 1,
|
||||
"homeserverList": ["converser.eu", "matrix.org", "mozilla.org", "unredacted.org", "xmr.se"],
|
||||
"defaultHomeserver": 0,
|
||||
"homeserverList": [
|
||||
"gamecult.org",
|
||||
"converser.eu",
|
||||
"matrix.org",
|
||||
"mozilla.org",
|
||||
"unredacted.org",
|
||||
"xmr.se"
|
||||
],
|
||||
"allowCustomHomeservers": true,
|
||||
"featuredCommunities": {
|
||||
"openAsDefault": false,
|
||||
|
|
@ -20,5 +27,14 @@
|
|||
|
||||
"backgroundScene": {
|
||||
"tier": "off"
|
||||
},
|
||||
|
||||
"dings": {
|
||||
"enabled": false
|
||||
},
|
||||
|
||||
"registration": {
|
||||
"enabled": false,
|
||||
"url": ""
|
||||
}
|
||||
}
|
||||
|
|
|
|||
106
docs/file-zone.md
Normal file
|
|
@ -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: <root>, is_falling_back: true, "m.in_reply_to": { event_id: <last thread event> } }`. 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: <file post>, 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: <album root>, "m.in_reply_to": { event_id: <file post> } }`. 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).
|
||||
242
docs/mind-feedback-pages.md
Normal file
|
|
@ -0,0 +1,242 @@
|
|||
# Mind feedback pages
|
||||
|
||||
> The desk reads `gamecult.fork.*` now, not the `org.gamecult.feedback.*` projections named below; see CultLib `contracts/cultnet/governance/fork-card.md` (src/app/features/desk/forkContract.ts).
|
||||
|
||||
Design only. No code exists for this; nothing here is built. Drafted by Kiko Self (2026-11-07) with Heimdall's draft rulings
|
||||
on guests and hiding; placement ruled for this repo by Void. Follow-up `eureka-body:follow_up:ratatoskr-mind-feedback-pages`.
|
||||
Every number below is provisional.
|
||||
|
||||
**Schema owner.** The Huginn kinds, their fields, keys and refusals are specified in `huginn-feedback-kinds-proposal.md` (Eureka Self, 2026-11-07, in
|
||||
`/opt/commons/handoff`), adopted for this page by Void's Persona. Where this page names a field of those kinds it mirrors that proposal; if they differ, the proposal wins.
|
||||
This repo owns only the client: a typed interface mirroring those shapes, and fixtures.
|
||||
|
||||
Each Mind's section in the estate navigator opens on that Mind's **feedback page**: the Mind's open questions with options, its
|
||||
recommendation and what each waits on, answerable by the operator and anyone with an account. It replaces the old Fork Desk
|
||||
(taken from the brief; no trace of it was found in this repo or in the Minds' state).
|
||||
|
||||
## 1. Placement
|
||||
|
||||
Each Mind's navigator section **opens on its feedback page**, rooms below it. A cross-Mind list of everything waiting on a person
|
||||
is wanted later and is not part of this spec. On phones the page folds each question's options and the answer form behind its title,
|
||||
so the section root stays a list of questions, not a wall of forms.
|
||||
|
||||
## 2. Authority
|
||||
|
||||
| Concern | Owner | The page's part |
|
||||
|---|---|---|
|
||||
| The question | a typed `question` document in the **owning Mind's own mind**, key `<campaign>:question:<label>` | a view of it; the page stores and edits nothing |
|
||||
| Which questions appear | the owning Mind, by a `feedback_listing` (the opt-in act) carrying `audience` and `close_grants`; un-listing is a `Withdrawn` resolution on it | shows only what has a listing in force |
|
||||
| An answer | its author. The **receiver (Bifrost) holds the text**; the Mind holds a **text-free `feedback_answer` record** | submits the answer to the receiver |
|
||||
| The ruling | the owning Mind, recorded by her | **never writes one**; links to it once she has |
|
||||
| Status (open, answered, closed) | derived in the Mind from its documents (`closed` is a `Withdrawn` resolution on the question), never written | shows it |
|
||||
| Who answered, and as what | the Bifrost account behind the Heimdall session, plus its role at the moment of the answer | shows it; never takes it from the client |
|
||||
| Close | a `feedback_close_request` the owning Mind honours or declines; it never changes the question's status by itself | offers Close only to a grant holder; **the page writes no ruling** |
|
||||
| Hiding | the owning Mind alone, as a `feedback_hide`; unhide is a `Withdrawn` resolution on it | shows the labelled stub; hides nothing itself |
|
||||
| Erase | Bifrost's erase of an account; the receiver drops the text | shows "erased account" |
|
||||
|
||||
An answer is input to a Mind, not a vote and not a decision. **The page never tallies**: no counts, no totals, no "leading" option, no
|
||||
ordering by popularity, no count of reports or close requests. Only the Mind's ruling picks anything.
|
||||
|
||||
## 3. Receiver and carriers
|
||||
|
||||
- **Schema owner: `huginn-feedback-kinds-proposal.md`.** Four new Huginn kinds, all Eureka's: `feedback_listing` (audience, `close_grants` with no Guest
|
||||
grant, the opt-in act), `feedback_answer` (a text-free record), `feedback_close_request` and `feedback_hide`. Unhide, un-list and "request declined"
|
||||
are `resolution`s on those kinds. This page proposes no kinds.
|
||||
- **Bifrost is the receiver** (Heimdall's side). It verifies the Heimdall session, reads the account, stamps `answerer`, `kind`, weight and `time`,
|
||||
**stores the answer text**, delivers it, serves the projection the page reads, and **does the erase**. A Matrix sender is a different
|
||||
identity authority and never becomes `answerer`.
|
||||
- **Huginn is RUDP-only.** The client never talks to Huginn, and the receiver never writes to it: an admission declared for another instance is refused
|
||||
(`ForeignInstance`), so a receiver "admitting as Kiko" would be unauthenticated by construction.
|
||||
- **Delivery is by mouth.** The receiver delivers each answer or close request to the owning Mind's Persona through the mouth's pending/ack path (a new
|
||||
delivery document, `gamecult.persona.feedback_delivery.v1`, owned by Bifrost). **The Persona admits the text-free record into her own mind** and acks only
|
||||
after it is admitted; a restart redelivers the same record id, which is `AlreadyAdmitted`. The text reaches her turn once, in the delivery, and is never
|
||||
admitted.
|
||||
- Dependencies that must ship first, in the proposal's order: Huginn readers (daemon, CLI, clients), then the Persona organ, then Bifrost's receiver.
|
||||
|
||||
## 4. Mock
|
||||
|
||||
```
|
||||
Kiko > Feedback [synced 2 min ago]
|
||||
--------------------------------------------------------------------------------------
|
||||
Open questions [ Open ] [ Settled ]
|
||||
|
||||
OPEN | asked 6 Nov 2026 09:12 | waiting 1 day
|
||||
Which source feeds audio_spectrum? [ Details v ]
|
||||
The visualizer contract assumes a host-side spectrum ... (3 lines, then "Show more")
|
||||
Waits on: "Overlay-wide effect budget" (open, links to that question)
|
||||
|
||||
( ) A Overlay's own audio only
|
||||
( ) B OBS captured stream Kiko recommends this
|
||||
( ) C Loopback of the mix, microphone excluded
|
||||
( ) Something else: [ up to 2000 characters ]
|
||||
Answers are visible to everyone who can see this question.
|
||||
[ Send answer ]
|
||||
[ Ask Kiko to close this question ] <- only if you hold the close grant on it
|
||||
|
||||
Answers (every one, oldest first)
|
||||
Meta operator B OBS captured stream 6 Nov 21:04
|
||||
Aqua Mind B OBS captured stream 6 Nov 21:40
|
||||
Nibu member C Loopback of the mix 7 Nov 08:12
|
||||
Heimdall Mind "Either, if latency is measured first." 7 Nov 09:02
|
||||
a guest guest A Overlay's own audio only 7 Nov 09:15
|
||||
(answer hidden) guest Hidden by Kiko, 7 Nov, spam
|
||||
Earlier answers by the same person fold under their latest.
|
||||
--------------------------------------------------------------------------------------
|
||||
SETTLED | Kiko ruled: "..." (link to the ruling) | 5 Nov
|
||||
```
|
||||
|
||||
- Each row is the author's name and **kind**, the choice or text, and the time. Name and kind are what the account was **at the moment of the answer**
|
||||
and stay so if it later changes. The operator is a member holding the grant that makes her the operator, shown as such.
|
||||
- The recommendation is stated in words, not colour, and is never preselected.
|
||||
- Answering a settled question is not offered.
|
||||
|
||||
## 5. Data contract
|
||||
|
||||
The **Huginn shapes belong to the proposal** (section 2 there): `feedback_listing`, `feedback_answer`, `feedback_close_request`, `feedback_hide`. The client
|
||||
declares a typed interface that mirrors them as the page's projection and imports nothing it cannot decode from them.
|
||||
|
||||
**Question projection** (`org.gamecult.feedback.question.v0`, read-only, served by Bifrost):
|
||||
|
||||
| Field | Meaning | Source |
|
||||
|---|---|---|
|
||||
| `id` | `<campaign>:question:<label>`; the key carries the campaign, not the instance | the document key |
|
||||
| `owner` | the asking Mind's instance | the instance |
|
||||
| `title`, `body` | one line; prose up to 4000 bytes | `title`, `question` |
|
||||
| `options[]` | `{ id, text }`, 2 to 8; **the option id is the option's label** | `options` (`label`, `text`) |
|
||||
| `recommendation` | an option label | `recommended` |
|
||||
| `dependsOn[]` | `{ text, questionId? }`; an id only where the line cites one verbatim | `depends` (free text) |
|
||||
| `askedAt` | the question's receipt `committed_at` | the receipt; `asked_on` is only a date |
|
||||
| `audience`, `closeGrants[]` | `AccountHolders` or `MembersOnly`, no default; grantees are accounts or the kinds `Member` and `Mind`, **never `Guest`** | the in-force `feedback_listing` |
|
||||
| `status` | `open`, `answered` (with a `rulingId`) or `closed`, derived | the question's resolutions |
|
||||
|
||||
**Answer row** (`org.gamecult.feedback.answer.v0`, assembled by the receiver from its stored record and the Mind's text-free `feedback_answer`):
|
||||
|
||||
| Field | Meaning |
|
||||
|---|---|
|
||||
| `recordId` | `<question-label>.a<N>`, N the receiver's per-question sequence |
|
||||
| `answerer` | the **Bifrost account id** (stable; the authenticator handle is cleared on erase); never a display name, never client-supplied |
|
||||
| `kind` | `Guest`, `User`, `Patron`, `Member` or `Mind`, read from Bifrost's account state **at answer time**; the session carries identity, never role |
|
||||
| `weightPermille` | stamped 0 for a guest, 1000 otherwise; **the page sums nothing** |
|
||||
| `choice` / `text` | an option label, free text up to 2000 characters, or both; at least one. Text exists only in the receiver's store and the projection, never in a mind |
|
||||
| `time` | when the receiver accepted it |
|
||||
|
||||
Invariants: the receiver takes `answerer`, `kind` and weight from the verified session and account state, never from the request body; an unknown option
|
||||
label is refused; the latest record per account is its standing answer, derived at read time; display names are looked up for display and are never keys. An
|
||||
account may answer only while its status is `active`, read at answer time. A guest cannot request close, and a guest grant cannot be written. Answers to a
|
||||
settled question are kept. Nothing is edited or deleted, except the receiver's redaction on erase (section 7).
|
||||
|
||||
## 6. Flow
|
||||
|
||||
```
|
||||
owning Mind's mind --(Bifrost projection)--> page page --(answer, Heimdall session)--> receiver (Bifrost; holds the text)
|
||||
receiver --(mouth delivery)--> owning Mind's Persona --(admits text-free feedback_answer)--> her mind
|
||||
the Mind decides and records the ruling herself --> status derives --> projection updates --> page moves it to Settled
|
||||
```
|
||||
|
||||
1. **View.** The page shows the projection of the questions with a `feedback_listing` in force, filtered by the viewer's kind against `audience`. The mind
|
||||
stays the truth; the projection is rebuilt, never hand-edited, and republished on a heartbeat so freshness is visible.
|
||||
2. **Answer.** The page submits with the person's Heimdall session; the receiver stamps, stores the text and appends the record.
|
||||
3. **Return.** The receiver delivers by mouth; the Persona admits the text-free record and reads the text once. Each arrives as **quoted, attributed data**
|
||||
(record id, author, kind, time), never in an instruction position: text from a guest, user or patron is untrusted, and she records a ruling from it, never
|
||||
an action. The receiver does no keyword screening. She does not quote answer text into memory or a ruling; she cites the record id.
|
||||
4. **Decide.** She records the ruling in her mind. The next projection carries `answered` and the ruling link.
|
||||
5. **Close.** A grant holder's request is delivered as a `feedback_close_request`. The Mind honours it by resolving the question, or declines with a
|
||||
`Recorded` resolution on the request; the request never changes the status itself. The page shows who asked and never how many.
|
||||
|
||||
## 7. Guests, erasure and hiding
|
||||
|
||||
- **Guests may answer** and see what the Mind opted in for their audience; they may not close (refused at the receiver and again by Huginn, and no listing can
|
||||
name a Guest grantee). A guest answer carries weight 0 by construction and is tallied nowhere. Guests see display name and kind only, never a Matrix id,
|
||||
provider handle or GitHub login.
|
||||
- **Erase redacts.** Records are append-only and are **never edited, but may be redacted**. A mind cannot redact: every admission's receipt keeps its exact
|
||||
payload bytes, which is why the text never enters one. When Bifrost erases an account, **the receiver drops that account's answer text and name** and keeps record
|
||||
id, kind and time only. **A content hash is not kept**: an unsalted hash would confirm a guessed text. The author shows as "erased account". The receiver delivers an erase notice and the Persona admits a `feedback_hide` with
|
||||
reason `ErasedAuthor`, the Mind's acknowledgement rather than a moderation call. The honest residue: a Mind's own memory or ruling may already quote an
|
||||
answer, and Huginn cannot redact it; the rule that she cites record ids, never text, is a prompt, not an invariant.
|
||||
- **Only the owning Mind hides**, as a `feedback_hide`: target (an answer or a question), reason from the closed set (`PrivateMatter`, `Abuse`, `Spam`,
|
||||
`OffTopic`, `AuthorRequest`, `ErasedAuthor`) and a line of at most 200 bytes, with its admission receipt as the audit trail. Unhide is a `Withdrawn`
|
||||
resolution on the hide. No count of reports ever hides anything and there is no auto-hide threshold; the operator orders a hide in conversation and the
|
||||
Mind records it.
|
||||
- **Anyone with an account may report** an answer; the receiver delivers it to the Mind as input. The page shows nothing of it and never a count. An author
|
||||
reporting their own answer uses `AuthorRequest` and the Mind honours it.
|
||||
- **What a hidden item shows.** A hidden answer keeps its row (author, kind, time, "Hidden by <Mind>, <date>, <reason>") with its text withheld for every
|
||||
reason. A hidden question shows a stub with its title, body, options and answers withheld; taking a question off the page is a `Withdrawn` resolution on its
|
||||
listing. The answer box says answers are visible to everyone who can see the question.
|
||||
- **Private matter** is never listed. An answer carrying someone's private matter is hidden with `PrivateMatter`.
|
||||
- Guest answers are collected for nothing but delivery to the owning Mind.
|
||||
- **No content hash anywhere.** No answer, close-request or redaction shape in this page carries one. The proposal's `feedback_answer` lists a `content_hash`
|
||||
field; per Heimdall it must go, and Eureka owns that change.
|
||||
|
||||
## 7a. Receiver: credential, store, names
|
||||
|
||||
Source: Bifrost PR #10, `docs/feedback-receiver.md` (design, nothing implemented).
|
||||
|
||||
- **Credential: route 2.** Ratatoskr presents the **OIDC access token Bifrost already issues to chat**, and Bifrost verifies it itself. The client holds no new
|
||||
secret and needs no Heimdall token. The account is the token's subject, `UserAccount.Id`. **The claims check is still open**: which claims the token carries
|
||||
and which Bifrost must verify for this endpoint have not been read.
|
||||
- **Store: a CultCache file** (Eureka's pick), owned and written only by the receiver. **Backups need a stated purge or expiry before any deploy**, so that
|
||||
erased text does not survive in them; the number is left to Eureka and Heimdall.
|
||||
- **Display names.** The receiver must not reuse `CurrentBifrostActor.DisplayName`, which falls back to the GitHub login and then to "Guest". It stores the
|
||||
name at answer time from the member nickname or account display name only, and "an account" when both are empty. Never a provider handle, GitHub login,
|
||||
Heimdall id or Matrix localpart.
|
||||
- **No guest exists until Bifrost PR #9 lands.** On main an active membership is a member, an authenticated or pending one a user, and nobody is a guest, so the
|
||||
guest rules in this page have no account to apply to until then. An answer needs an active account, read at answer time.
|
||||
|
||||
## 8. States
|
||||
|
||||
- **Empty:** "Nothing is waiting on you from Kiko", when it last synced, a link to Settled. Never blank.
|
||||
- **No answers:** "No answers yet", with the question's age.
|
||||
- **Stale projection:** past two heartbeats (provisionally 30 minutes) the header reads "may be out of date"; answering stays possible. A projection that
|
||||
never arrived says "Kiko's questions have not been published yet", not "no questions".
|
||||
- **Long open:** past 14 days (provisional) shows its age; it is not demoted or hidden.
|
||||
- **Blocked:** shows the dependency chip with that question's status; answering stays allowed.
|
||||
- **Settled while answering:** the answer is kept for the Mind and the page says it arrived after the question settled.
|
||||
- **Signed out, expired, or not active:** answers are shown, the form asks to sign in or says why it cannot; nothing typed is lost.
|
||||
- **Send failed:** the text stays in the field with the reason and a retry.
|
||||
|
||||
## 9. Build order
|
||||
|
||||
1. The client's typed interface, mirroring the proposal's shapes and the projections in section 5, and **fixtures** for every state in section 8 plus the
|
||||
guest, erased and hidden rows. The page renders from fixtures; no network.
|
||||
2. The proposal's kinds and migration (Eureka: readers first, then the Persona organ), and the Bifrost account publisher, receiver and mouth delivery
|
||||
(Heimdall). The page switches from fixtures to the projection.
|
||||
|
||||
## 10. Accessibility
|
||||
|
||||
- Semantic structure: `main` with a heading; each question an `article` with its title as a heading; options a `fieldset`/`legend` radio group; the
|
||||
free-text field labelled, with a character counter announced politely. The phone fold is a button with `aria-expanded`.
|
||||
- No meaning by colour alone: status, recommendation, kind, hidden and close-grant are text.
|
||||
- Keyboard: everything reachable in a sensible order; after Send, focus goes to a confirmation naming the question and the answer.
|
||||
- New answers and status changes arrive in an `aria-live="polite"` region, never as a focus steal.
|
||||
- Targets at least 44 px; reduced motion respected; contrast per theme.
|
||||
- Names and answers are user text: `dir="auto"`, control and bidi characters stripped, long words wrap.
|
||||
|
||||
## 11. Still open
|
||||
|
||||
1. **Emergency withhold.** If the owning Mind is away and an answer shows something illegal or dangerous, may the host withhold the text at the receiver?
|
||||
Heimdall leans no: it is a second owner. Meta's fork.
|
||||
2. **How a Mind authenticates to answer** (kind `Mind`): Bifrost has no `Mind` role and the account publisher `gamecult.bifrost.account.v1` does not exist yet.
|
||||
3. **Erase is bounded.** Text a Mind has already quoted into her own documents cannot be redacted; absolute erase would mean the text never enters her turn.
|
||||
4. **`AccountId` grammar**, pinned to Bifrost's account id shape when that publisher lands.
|
||||
5. **Receiver claims.** The OIDC access token's claims for this endpoint (section 7a) are unread.
|
||||
6. **Reader ordering.** Whether an old Huginn reader skips or fails on a mind holding a kind it does not know is unverified (proposal section 6.4); it decides
|
||||
when the first Mind may list a question.
|
||||
|
||||
## 12. The desk: the page as the Fork Desk's descendant
|
||||
|
||||
Added 2026-11-10 by Void from Meta's brief and the original Fork Desk (`/opt/commons/handoff/fork-desk-original/`, Nibu's newest copy; working note `/opt/commons/handoff/ratatoskr-desk-spec-20261110.md`, section 11). The feedback page **is** the desk: one surface, not two. Design only.
|
||||
|
||||
**Keep from the original.**
|
||||
- Questions stream as rows (not one at a time): title, body as context, options with the recommended one marked **in words**, the `depends` line, a free-text note carrying the person's words verbatim, and a "recorded as rulings" list of settled questions with their ruling id. A pick is optional; the note can answer alone.
|
||||
- A **booth Persona**: the owning Mind's pose beside the rows on wide screens, a small fixed corner image on phones, reacting by mood: no forks (neutral), all answered (triumph), none answered (thinking), partway (determined, "N to go"), a pick equal to the recommendation (happy), a different pick (surprised, "a line on why helps"), a cleared pick (note), a failed send (concerned), a new fork arriving (surprised). The rules are a pure function of the forks and the last event (`deskMood`), tested exactly. Poses come from the shared cast art; a Mind without art shows no booth rather than another's face.
|
||||
- Answers save as the person acts, and she can close the page and come back.
|
||||
|
||||
**What changes.**
|
||||
- The row is the section 5 question projection. The page changes nothing about who owns a question, a ruling or a status (section 2).
|
||||
- Phones: each row's options and note fold behind its title (section 1); the entry point is a **"Desk · N open"** line on the Mind's group header in the navigator, hidden at zero. Chromeless: hairlines are allowed, panels, cards and pills are not.
|
||||
- **Answer rule and wire.** The answer rule (the body the client may send, `options_hash`, the counting order, retraction, the stored `desk_answer`) is owned by Heimdall's rule file `/opt/commons/handoff/fork-desk-answer-binding-20261110.md`; the wire is owned by CultLib #72. This section restates neither. The client's part: it sends only what the rule's body allows (never `answerer` or authority), recomputes `options_hash` from what it rendered and refuses to send on a mismatch with the projection's.
|
||||
- **A pick sends at once** (one tap, one record; the latest per account stands, section 5). **The note autosaves as a local draft** and is sent on blur or an explicit Send, never per keystroke. "Saved" says which: sent, or kept on this device.
|
||||
- **Clear pick is a retraction**, a revision of the answer under the retraction rule in Heimdall's rule file (section 1.3a there); the one exception to section 5's "at least one of choice or text" is that rule's, not this page's. Until the receiver implements it, Clear pick clears only an unsent draft.
|
||||
- "Self leans" and a provisional flag exist in the original; the question has no field for either, so the desk shows neither until one exists.
|
||||
|
||||
**Order.** Section 9 step 1 stands: typed interface and fixtures first. The desk's first slice is read-only (note field disabled with a plain sentence that answering opens with sign-in), and answering waits on Bifrost sign-in reaching chat, the wire (CultLib #72) and the receiver.
|
||||
|
|
@ -2,12 +2,17 @@
|
|||
// non-zero when the page or the fake homeserver's log says otherwise.
|
||||
const fs = require('fs');
|
||||
const fails = [];
|
||||
let asserted = 0;
|
||||
exports.expect = (label, ok, detail = '') => {
|
||||
asserted += 1;
|
||||
console.log(`[ASSERT] ${ok ? 'PASS' : 'FAIL'} ${label}${ok ? '' : ` :: ${detail}`}`);
|
||||
if (!ok) fails.push(label);
|
||||
};
|
||||
/** Exit code for the drive: 4 when any assertion failed. */
|
||||
exports.done = () => (fails.length ? 4 : 0);
|
||||
/** Exit code for the drive: 4 when any assertion failed, 5 when none ran (a drive that asserts nothing proves nothing). */
|
||||
exports.done = () => {
|
||||
if (fails.length) return 4;
|
||||
return asserted === 0 ? 5 : 0;
|
||||
};
|
||||
/** The fake homeserver's request log (HSLOG is shared with the server process). */
|
||||
exports.hsLog = () => fs.readFileSync(process.env.HSLOG, 'utf8').split('\n');
|
||||
/** Bodies of the account-data PUTs for m.direct, in order. */
|
||||
|
|
|
|||
35
harness/estate/check.test.ts
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
// @vitest-environment node
|
||||
import { createRequire } from 'module';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
// A drive that asserts nothing proves nothing: its exit code must say so.
|
||||
const fresh = () => {
|
||||
const require = createRequire(import.meta.url);
|
||||
const path = require.resolve('./check.cjs');
|
||||
delete require.cache[path];
|
||||
return require('./check.cjs') as {
|
||||
expect: (label: string, ok: boolean, detail?: string) => void;
|
||||
done: () => number;
|
||||
};
|
||||
};
|
||||
|
||||
describe('estate drive exit code', () => {
|
||||
it('is 5 when no assertion ran', () => {
|
||||
expect(fresh().done()).toBe(5);
|
||||
});
|
||||
|
||||
it('is 0 when assertions ran and all held', () => {
|
||||
vi.spyOn(console, 'log').mockImplementation(() => undefined);
|
||||
const c = fresh();
|
||||
c.expect('holds', true);
|
||||
expect(c.done()).toBe(0);
|
||||
});
|
||||
|
||||
it('is 4 when any assertion failed', () => {
|
||||
vi.spyOn(console, 'log').mockImplementation(() => undefined);
|
||||
const c = fresh();
|
||||
c.expect('holds', true);
|
||||
c.expect('breaks', false, 'detail');
|
||||
expect(c.done()).toBe(4);
|
||||
});
|
||||
});
|
||||
|
|
@ -6,6 +6,7 @@ Chromium. Not shipped, not run by CI.
|
|||
node bundle.cjs <outdir> # esbuild bundle of entry.ts plus an index.html
|
||||
node drive.cjs <outdir> compile # compile and link each stage, JSON report
|
||||
node drive.cjs <outdir> shots <pngdir> # rest, mid pull-back and pulled-back screenshots
|
||||
node gradAxis.cjs <shaders dir> # numeric check that noise gradients are (d/dx, d/dz-as-.y, ...): terrainNormal axis
|
||||
node drive.cjs <outdir> measure # GPU time per pass by timer query, two viewports, two levels
|
||||
node drive.cjs <outdir> variants # the same with source patches (no erosion, no tree, value-only fbm)
|
||||
node drive.cjs <outdir> trace # mean trace steps per pixel and pass ms at three camera poses, PREPASS=0,1 arms
|
||||
|
|
|
|||
30
harness/scene/gradAxis.cjs
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
// Probe: the gradient cultmath_fbm_grad / cultmath_phacelle return for vec3(xz * f, c) is (d/dx, d/dz, d/dc, value),
|
||||
// so the world-z slope is .y, not .z. Compares analytic gradients with central differences at one point.
|
||||
// Usage (playwright + swiftshader): node harness/scene/gradAxis.cjs <repo>/src/app/features/scene/shaders
|
||||
const { chromium } = require('playwright'); const fs=require('fs');
|
||||
const S=process.argv[2];
|
||||
const cm=fs.readFileSync(S+'/CultMath.glsl','utf8'), ph=fs.readFileSync(S+'/CultMath.Phacelle.glsl','utf8');
|
||||
const fs_=`#version 300 es
|
||||
precision highp float; precision highp int;
|
||||
${cm}
|
||||
${ph}
|
||||
out vec4 o;
|
||||
const float F=1.0/520.0;
|
||||
float fb(vec2 p){return cultmath_fbm_grad(vec3(p*F,0.0),4,2.0,0.45).w;}
|
||||
float pc(vec2 p){return cultmath_phacelle(vec3(p/40.0,0.5),vec3(1.5,0.5,0.0),0.0,0.5).cos.w;}
|
||||
void main(){
|
||||
vec2 p=vec2(1234.5,-777.7); float e=0.5;
|
||||
int k=int(gl_FragCoord.x);
|
||||
if(k==0){vec4 g=cultmath_fbm_grad(vec3(p*F,0.0),4,2.0,0.45); o=vec4(g.xyz*F,0.0);} // analytic per metre: x,y,z
|
||||
else if(k==1){o=vec4((fb(p+vec2(e,0))-fb(p-vec2(e,0)))/(2.0*e),(fb(p+vec2(0,e))-fb(p-vec2(0,e)))/(2.0*e),0,0);}
|
||||
else if(k==2){vec4 g=cultmath_phacelle(vec3(p/40.0,0.5),vec3(1.5,0.5,0.0),0.0,0.5).cos; o=vec4(g.xyz/40.0,0.0);}
|
||||
else {o=vec4((pc(p+vec2(e,0))-pc(p-vec2(e,0)))/(2.0*e),(pc(p+vec2(0,e))-pc(p-vec2(0,e)))/(2.0*e),0,0);}
|
||||
}`;
|
||||
(async()=>{const b=await chromium.launch({args:['--use-gl=angle','--use-angle=swiftshader','--enable-unsafe-swiftshader']});
|
||||
const pg=await b.newPage();
|
||||
const r=await pg.evaluate(([src])=>{const c=document.createElement('canvas');const g=c.getContext('webgl2');g.getExtension('EXT_color_buffer_float');
|
||||
const mk=(t,s)=>{const x=g.createShader(t);g.shaderSource(x,s);g.compileShader(x);if(!g.getShaderParameter(x,g.COMPILE_STATUS))throw g.getShaderInfoLog(x);return x};
|
||||
const p=g.createProgram();g.attachShader(p,mk(g.VERTEX_SHADER,'#version 300 es\nvoid main(){vec2 p=vec2(float((gl_VertexID<<1)&2),float(gl_VertexID&2));gl_Position=vec4(p*2.0-1.0,0.0,1.0);}'));g.attachShader(p,mk(g.FRAGMENT_SHADER,src));g.linkProgram(p);g.useProgram(p);
|
||||
const t=g.createTexture();g.bindTexture(g.TEXTURE_2D,t);g.texImage2D(g.TEXTURE_2D,0,g.RGBA32F,4,1,0,g.RGBA,g.FLOAT,null);const f=g.createFramebuffer();g.bindFramebuffer(g.FRAMEBUFFER,f);g.framebufferTexture2D(g.FRAMEBUFFER,g.COLOR_ATTACHMENT0,g.TEXTURE_2D,t,0);g.viewport(0,0,4,1);g.drawArrays(g.TRIANGLES,0,3);
|
||||
const o=new Float32Array(16);g.readPixels(0,0,4,1,g.RGBA,g.FLOAT,o);return Array.from(o)},[fs_]).catch(e=>'ERR '+String(e).slice(0,500));
|
||||
console.log(Array.isArray(r)?['fbm analytic x,y,z','fbm FD dx,dz','phac analytic','phac FD'].map((n,i)=>n+': '+r.slice(i*4,i*4+3).map(v=>v.toExponential(3)).join(' ')).join('\n'):r);await b.close()})();
|
||||
|
|
@ -1,12 +1,29 @@
|
|||
// Standalone page for the ridge scene: full window, no host app. `?tier=still|low|full` picks the
|
||||
// tier, `?probe=1` shows the rAF median/p95 readout. Not shipped.
|
||||
// tier, `?probe=1` shows the rAF median/p95 readout. The bake record (each chunk's cost, from
|
||||
// the scene's `onBake`) and the long tasks the page saw are on `window.bakes` and `window.longTasks`
|
||||
// for a driver to read. Not shipped.
|
||||
import { startBackgroundScene } from '../../src/app/features/scene';
|
||||
import type { SceneTier } from '../../src/app/features/scene';
|
||||
|
||||
const q = new URLSearchParams(location.search);
|
||||
const tier = (q.get('tier') ?? 'full') as SceneTier;
|
||||
const canvas = document.getElementById('c') as HTMLCanvasElement;
|
||||
startBackgroundScene({ tier }, {}, { canvas }).then((scene) => {
|
||||
(window as unknown as { scene: unknown }).scene = scene;
|
||||
const w = window as unknown as { scene: unknown; bakes: unknown[]; longTasks: number[]; firstViewMs: number };
|
||||
w.bakes = [];
|
||||
w.longTasks = [];
|
||||
try {
|
||||
new PerformanceObserver((l) => l.getEntries().forEach((e) => w.longTasks.push(e.duration))).observe({
|
||||
entryTypes: ['longtask'],
|
||||
});
|
||||
} catch {
|
||||
// No long-task entries in this browser.
|
||||
}
|
||||
const t0 = performance.now();
|
||||
startBackgroundScene({ tier }, {}, {
|
||||
canvas,
|
||||
onBake: (b: unknown) => w.bakes.push(b),
|
||||
} as never).then((scene) => {
|
||||
w.firstViewMs = performance.now() - t0;
|
||||
w.scene = scene;
|
||||
document.title = scene ? 'ridge: running' : 'ridge: unavailable (CSS ground)';
|
||||
});
|
||||
|
|
|
|||
|
|
@ -23,7 +23,7 @@
|
|||
|
||||
<link id="favicon" rel="shortcut icon" href="./public/favicon.ico" />
|
||||
|
||||
<link rel="manifest" href="/manifest.json" />
|
||||
<link rel="manifest" href="./manifest.json" />
|
||||
<meta name="mobile-web-app-capable" content="yes" />
|
||||
<meta name="application-name" content="Ratatoskr" />
|
||||
<meta name="apple-mobile-web-app-title" content="Ratatoskr" />
|
||||
|
|
|
|||
2
package-lock.json
generated
|
|
@ -86,6 +86,7 @@
|
|||
"@types/ua-parser-js": "0.7.36",
|
||||
"@typescript-eslint/eslint-plugin": "5.46.1",
|
||||
"@typescript-eslint/parser": "5.46.1",
|
||||
"@vanilla-extract/integration": "6.5.0",
|
||||
"@vitejs/plugin-react": "4.2.0",
|
||||
"buffer": "6.0.3",
|
||||
"cz-conventional-changelog": "3.3.0",
|
||||
|
|
@ -5095,6 +5096,7 @@
|
|||
"version": "6.5.0",
|
||||
"resolved": "https://registry.npmjs.org/@vanilla-extract/integration/-/integration-6.5.0.tgz",
|
||||
"integrity": "sha512-E2YcfO8vA+vs+ua+gpvy1HRqvgWbI+MTlUpxA8FvatOvybuNcWAY0CKwQ/Gpj7rswYKtC6C7+xw33emM6/ImdQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@babel/core": "^7.20.7",
|
||||
"@babel/plugin-syntax-typescript": "^7.20.0",
|
||||
|
|
|
|||
|
|
@ -114,6 +114,7 @@
|
|||
"@types/ua-parser-js": "0.7.36",
|
||||
"@typescript-eslint/eslint-plugin": "5.46.1",
|
||||
"@typescript-eslint/parser": "5.46.1",
|
||||
"@vanilla-extract/integration": "6.5.0",
|
||||
"@vitejs/plugin-react": "4.2.0",
|
||||
"buffer": "6.0.3",
|
||||
"cz-conventional-changelog": "3.3.0",
|
||||
|
|
|
|||
13
preview-demo/poses/README.md
Normal file
|
|
@ -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.
|
||||
17
public/dings/README.md
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
# Dings
|
||||
|
||||
Pre-rendered earcons, served at `public/dings/` and read at runtime by `src/app/features/dings`.
|
||||
Aqua renders the clips; nothing here is synthesised in the browser.
|
||||
|
||||
dings/manifest.json
|
||||
dings/senders/<mxid-localpart>/<motif>.ogg
|
||||
dings/neutral/<motif>.ogg
|
||||
|
||||
`manifest.json` is `{ "neutral": { <motif>: "<path>" }, "senders": { <localpart>: { <motif>: "<path>" } } }`
|
||||
with motif one of `mention`, `dm`, `message`, `invite`; paths are relative to this folder, `.ogg` or `.mp3`.
|
||||
A sender's own clip wins, else the neutral clip, else silence. Without a `manifest.json` the client keeps
|
||||
its stock notification sounds; once one exists, a motif with no clip is silent.
|
||||
|
||||
The set here is Aqua's v4 (AquaSynth merge 21e83ec, staged at minds.gamecult.org/aqua/dings-voices-dd9be66),
|
||||
Nibu on proposal 3 (8 kHz 5-bit smoothed sine) for all four events. Nobody has heard it. The client plays none of it unless the
|
||||
client config sets `"dings": { "enabled": true }` (default off, as in `config.json`).
|
||||
58
public/dings/manifest.json
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
{
|
||||
"neutral": {
|
||||
"mention": "neutral/mention.ogg",
|
||||
"dm": "neutral/dm.ogg",
|
||||
"message": "neutral/message.ogg",
|
||||
"invite": "neutral/invite.ogg"
|
||||
},
|
||||
"senders": {
|
||||
"aqua": {
|
||||
"mention": "senders/aqua/mention.ogg",
|
||||
"dm": "senders/aqua/dm.ogg",
|
||||
"message": "senders/aqua/message.ogg",
|
||||
"invite": "senders/aqua/invite.ogg"
|
||||
},
|
||||
"eureka": {
|
||||
"mention": "senders/eureka/mention.ogg",
|
||||
"dm": "senders/eureka/dm.ogg",
|
||||
"message": "senders/eureka/message.ogg",
|
||||
"invite": "senders/eureka/invite.ogg"
|
||||
},
|
||||
"heimdall": {
|
||||
"mention": "senders/heimdall/mention.ogg",
|
||||
"dm": "senders/heimdall/dm.ogg",
|
||||
"message": "senders/heimdall/message.ogg",
|
||||
"invite": "senders/heimdall/invite.ogg"
|
||||
},
|
||||
"kiko": {
|
||||
"mention": "senders/kiko/mention.ogg",
|
||||
"dm": "senders/kiko/dm.ogg",
|
||||
"message": "senders/kiko/message.ogg",
|
||||
"invite": "senders/kiko/invite.ogg"
|
||||
},
|
||||
"libby": {
|
||||
"mention": "senders/libby/mention.ogg",
|
||||
"dm": "senders/libby/dm.ogg",
|
||||
"message": "senders/libby/message.ogg",
|
||||
"invite": "senders/libby/invite.ogg"
|
||||
},
|
||||
"nibu": {
|
||||
"mention": "senders/nibu/mention.ogg",
|
||||
"dm": "senders/nibu/dm.ogg",
|
||||
"message": "senders/nibu/message.ogg",
|
||||
"invite": "senders/nibu/invite.ogg"
|
||||
},
|
||||
"void": {
|
||||
"mention": "senders/void/mention.ogg",
|
||||
"dm": "senders/void/dm.ogg",
|
||||
"message": "senders/void/message.ogg",
|
||||
"invite": "senders/void/invite.ogg"
|
||||
},
|
||||
"weksa": {
|
||||
"mention": "senders/weksa/mention.ogg",
|
||||
"dm": "senders/weksa/dm.ogg",
|
||||
"message": "senders/weksa/message.ogg",
|
||||
"invite": "senders/weksa/invite.ogg"
|
||||
}
|
||||
}
|
||||
}
|
||||
BIN
public/dings/neutral/dm.ogg
Normal file
BIN
public/dings/neutral/invite.ogg
Normal file
BIN
public/dings/neutral/mention.ogg
Normal file
BIN
public/dings/neutral/message.ogg
Normal file
BIN
public/dings/senders/aqua/dm.ogg
Normal file
BIN
public/dings/senders/aqua/invite.ogg
Normal file
BIN
public/dings/senders/aqua/mention.ogg
Normal file
BIN
public/dings/senders/aqua/message.ogg
Normal file
BIN
public/dings/senders/eureka/dm.ogg
Normal file
BIN
public/dings/senders/eureka/invite.ogg
Normal file
BIN
public/dings/senders/eureka/mention.ogg
Normal file
BIN
public/dings/senders/eureka/message.ogg
Normal file
BIN
public/dings/senders/heimdall/dm.ogg
Normal file
BIN
public/dings/senders/heimdall/invite.ogg
Normal file
BIN
public/dings/senders/heimdall/mention.ogg
Normal file
BIN
public/dings/senders/heimdall/message.ogg
Normal file
BIN
public/dings/senders/kiko/dm.ogg
Normal file
BIN
public/dings/senders/kiko/invite.ogg
Normal file
BIN
public/dings/senders/kiko/mention.ogg
Normal file
BIN
public/dings/senders/kiko/message.ogg
Normal file
BIN
public/dings/senders/libby/dm.ogg
Normal file
BIN
public/dings/senders/libby/invite.ogg
Normal file
BIN
public/dings/senders/libby/mention.ogg
Normal file
BIN
public/dings/senders/libby/message.ogg
Normal file
BIN
public/dings/senders/nibu/dm.ogg
Normal file
BIN
public/dings/senders/nibu/invite.ogg
Normal file
BIN
public/dings/senders/nibu/mention.ogg
Normal file
BIN
public/dings/senders/nibu/message.ogg
Normal file
BIN
public/dings/senders/void/dm.ogg
Normal file
BIN
public/dings/senders/void/invite.ogg
Normal file
BIN
public/dings/senders/void/mention.ogg
Normal file
BIN
public/dings/senders/void/message.ogg
Normal file
BIN
public/dings/senders/weksa/dm.ogg
Normal file
BIN
public/dings/senders/weksa/invite.ogg
Normal file
BIN
public/dings/senders/weksa/mention.ogg
Normal file
BIN
public/dings/senders/weksa/message.ogg
Normal file
|
Before Width: | Height: | Size: 2.3 KiB After Width: | Height: | Size: 9.1 KiB |
|
Before Width: | Height: | Size: 3 KiB After Width: | Height: | Size: 9.4 KiB |
|
Before Width: | Height: | Size: 4 KiB After Width: | Height: | Size: 13 KiB |
|
Before Width: | Height: | Size: 5.6 KiB After Width: | Height: | Size: 18 KiB |
|
Before Width: | Height: | Size: 817 B After Width: | Height: | Size: 2 KiB |
|
Before Width: | Height: | Size: 8.8 KiB After Width: | Height: | Size: 27 KiB |
|
Before Width: | Height: | Size: 1 KiB After Width: | Height: | Size: 2.8 KiB |
|
Before Width: | Height: | Size: 12 KiB After Width: | Height: | Size: 37 KiB |
|
Before Width: | Height: | Size: 1.5 KiB After Width: | Height: | Size: 4.4 KiB |
|
Before Width: | Height: | Size: 2 KiB After Width: | Height: | Size: 6.1 KiB |
|
Before Width: | Height: | Size: 2.3 KiB After Width: | Height: | Size: 7.3 KiB |
|
Before Width: | Height: | Size: 2.4 KiB After Width: | Height: | Size: 7.7 KiB |
|
Before Width: | Height: | Size: 3 KiB After Width: | Height: | Size: 9.4 KiB |
|
Before Width: | Height: | Size: 3.1 KiB After Width: | Height: | Size: 10 KiB |
|
Before Width: | Height: | Size: 3.5 KiB After Width: | Height: | Size: 11 KiB |
|
Before Width: | Height: | Size: 3.8 KiB After Width: | Height: | Size: 12 KiB |
|
Before Width: | Height: | Size: 1.2 KiB After Width: | Height: | Size: 3.4 KiB |
|
Before Width: | Height: | Size: 1.2 KiB After Width: | Height: | Size: 3.5 KiB |
|
Before Width: | Height: | Size: 1.5 KiB After Width: | Height: | Size: 4.4 KiB |
|
Before Width: | Height: | Size: 1.6 KiB After Width: | Height: | Size: 4.6 KiB |
1
public/res/svg/ratatoskr-favicon-highlight.svg
Normal file
|
After Width: | Height: | Size: 22 KiB |
1
public/res/svg/ratatoskr-favicon-unread.svg
Normal file
|
After Width: | Height: | Size: 22 KiB |
1
public/res/svg/ratatoskr-favicon.svg
Normal file
|
After Width: | Height: | Size: 22 KiB |
|
|
@ -1,17 +0,0 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64">
|
||||
<ellipse cx="19" cy="33" rx="13" ry="22" transform="rotate(-15 19 33)" fill="#d9742b"/>
|
||||
<ellipse cx="21" cy="33" rx="7" ry="15" transform="rotate(-15 21 33)" fill="#f0a45d"/>
|
||||
<ellipse cx="36" cy="43" rx="11" ry="14" transform="rotate(0 36 43)" fill="#e0833a"/>
|
||||
<ellipse cx="40" cy="46" rx="6" ry="9" transform="rotate(0 40 46)" fill="#f6dcb8"/>
|
||||
<polygon points="35,19 36,7 43,15" fill="#c9672a"/>
|
||||
<polygon points="44,15 50,7 52,19" fill="#c9672a"/>
|
||||
<circle cx="43" cy="25" r="10" fill="#e0833a"/>
|
||||
<ellipse cx="47" cy="29" rx="5" ry="3.5" transform="rotate(0 47 29)" fill="#f6dcb8"/>
|
||||
<circle cx="46.5" cy="23.5" r="1.8" fill="#1a1a1a"/>
|
||||
<circle cx="47" cy="23" r="0.6" fill="#ffffff"/>
|
||||
<circle cx="52" cy="27.5" r="1.5" fill="#1a1a1a"/>
|
||||
<ellipse cx="33" cy="56" rx="5" ry="2.5" transform="rotate(0 33 56)" fill="#c9672a"/>
|
||||
<ellipse cx="44" cy="56" rx="4.5" ry="2.5" transform="rotate(0 44 56)" fill="#c9672a"/>
|
||||
<circle cx="52" cy="52" r="11" fill="#ffffff"/>
|
||||
<circle cx="52" cy="52" r="8" fill="#45B83B"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 1.1 KiB |
|
|
@ -1,17 +0,0 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64">
|
||||
<ellipse cx="19" cy="33" rx="13" ry="22" transform="rotate(-15 19 33)" fill="#d9742b"/>
|
||||
<ellipse cx="21" cy="33" rx="7" ry="15" transform="rotate(-15 21 33)" fill="#f0a45d"/>
|
||||
<ellipse cx="36" cy="43" rx="11" ry="14" transform="rotate(0 36 43)" fill="#e0833a"/>
|
||||
<ellipse cx="40" cy="46" rx="6" ry="9" transform="rotate(0 40 46)" fill="#f6dcb8"/>
|
||||
<polygon points="35,19 36,7 43,15" fill="#c9672a"/>
|
||||
<polygon points="44,15 50,7 52,19" fill="#c9672a"/>
|
||||
<circle cx="43" cy="25" r="10" fill="#e0833a"/>
|
||||
<ellipse cx="47" cy="29" rx="5" ry="3.5" transform="rotate(0 47 29)" fill="#f6dcb8"/>
|
||||
<circle cx="46.5" cy="23.5" r="1.8" fill="#1a1a1a"/>
|
||||
<circle cx="47" cy="23" r="0.6" fill="#ffffff"/>
|
||||
<circle cx="52" cy="27.5" r="1.5" fill="#1a1a1a"/>
|
||||
<ellipse cx="33" cy="56" rx="5" ry="2.5" transform="rotate(0 33 56)" fill="#c9672a"/>
|
||||
<ellipse cx="44" cy="56" rx="4.5" ry="2.5" transform="rotate(0 44 56)" fill="#c9672a"/>
|
||||
<circle cx="52" cy="52" r="11" fill="#ffffff"/>
|
||||
<circle cx="52" cy="52" r="8" fill="#989898"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 1.1 KiB |
|
Before Width: | Height: | Size: 1,001 B After Width: | Height: | Size: 59 KiB |
|
|
@ -1,10 +1,16 @@
|
|||
// Bakes Midnight Sky and Noonday Sky from src/sky/sun.js into src/sky/baked.ts.
|
||||
// Run `npm run bake:sky` after changing sun.js, skyTokens.js or a moment.
|
||||
// Bakes Midnight Sky and Noonday Sky from src/sky/sun.js into src/sky/baked.ts, with the
|
||||
// atmospheric-scattering tables (src/sky/scatter.js) as `scatter`.
|
||||
// Run `npm run bake:sky` after changing sun.js, skyTokens.js, scatter.js or a moment.
|
||||
import { writeFileSync } from 'node:fs';
|
||||
import { bakeSky } from '../src/sky/skyTokens.js';
|
||||
import { bakeScatter } from '../src/sky/scatter.js';
|
||||
|
||||
const out = new URL('../src/sky/baked.ts', import.meta.url);
|
||||
const baked = { midnight: bakeSky('midnight'), noonday: bakeSky('noonday') };
|
||||
const baked = {
|
||||
midnight: bakeSky('midnight'),
|
||||
noonday: bakeSky('noonday'),
|
||||
scatter: bakeScatter(),
|
||||
};
|
||||
writeFileSync(
|
||||
out,
|
||||
`// Generated by scripts/bake-sky.mjs from src/sky/sun.js. Do not edit.\n` +
|
||||
|
|
|
|||
9
scripts/build-dev-preview.sh
Executable file
|
|
@ -0,0 +1,9 @@
|
|||
#!/usr/bin/env bash
|
||||
# Build this checkout as the offline demo for the standing dev preview: base /void/rat-dev/, the pretend
|
||||
# homeserver, scene tier $TIER (default full). Output: ./dist, ready for the shared publisher
|
||||
# (gamecult-ops scripts/publish-mind-preview.sh dist rat-dev), which owns publishing. Publishes nothing.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
node scripts/sync-poses.mjs >/dev/null
|
||||
VITE_PREVIEW_DEMO=1 CINNY_BASE=/void/rat-dev/ NODE_OPTIONS=--max_old_space_size=4096 nice -n 10 npx vite build
|
||||
node scripts/preview-config.js "${TIER:-full}" --demo
|
||||
|
|
@ -1,17 +1,20 @@
|
|||
// Preview builds: set the background scene tier in dist/config.json (default 'low'); config.json
|
||||
// in the repo stays 'off'. With --demo it also switches on the pretend homeserver (src/preview-demo):
|
||||
// previewDemo true, and the pretend server as the only homeserver. Usage:
|
||||
// node scripts/preview-config.js [tier] [--demo]
|
||||
// in the repo stays 'off'. Previews are static directories with no SPA fallback, so they also switch
|
||||
// to the hash router: a reload on /login/matrix.org would otherwise be an nginx 404. With --demo it
|
||||
// also switches on the pretend homeserver (src/preview-demo): previewDemo true, and the pretend
|
||||
// server as the only homeserver. Usage:
|
||||
// node scripts/preview-config.js [tier] [style] [--demo]
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const demo = args.includes('--demo');
|
||||
const tier = args.find((a) => !a.startsWith('--')) ?? 'low';
|
||||
const [tier = 'low', style] = args.filter((a) => !a.startsWith('--'));
|
||||
const file = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'dist', 'config.json');
|
||||
const config = JSON.parse(fs.readFileSync(file, 'utf8'));
|
||||
config.backgroundScene = { ...config.backgroundScene, tier };
|
||||
config.hashRouter = { enabled: true, basename: '/' };
|
||||
config.backgroundScene = { ...config.backgroundScene, tier, ...(style ? { style } : {}) };
|
||||
if (demo) {
|
||||
config.previewDemo = true;
|
||||
config.defaultHomeserver = 0;
|
||||
|
|
@ -25,4 +28,6 @@ if (demo) {
|
|||
};
|
||||
}
|
||||
fs.writeFileSync(file, `${JSON.stringify(config, null, 2)}\n`);
|
||||
console.log(`${file}: backgroundScene.tier = ${tier}${demo ? ', previewDemo on' : ''}`);
|
||||
console.log(
|
||||
`${file}: backgroundScene.tier = ${tier}${style ? `, style = ${style}` : ''}${demo ? ', previewDemo on' : ''}`
|
||||
);
|
||||
|
|
|
|||
32
src/app/components/ServerConfigsLoader.test.ts
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { loadServerConfigs } from './ServerConfigsLoader';
|
||||
|
||||
const server = (authMetadata: () => Promise<unknown>) =>
|
||||
({
|
||||
getCapabilities: async () => ({}),
|
||||
getMediaConfig: async () => ({ 'm.upload.size': 1 }),
|
||||
getAuthMetadata: authMetadata,
|
||||
} as unknown as Parameters<typeof loadServerConfigs>[0]);
|
||||
|
||||
describe('loadServerConfigs', () => {
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
it('logs nothing when the homeserver has no OIDC (no auth metadata came back)', async () => {
|
||||
const error = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
const configs = await loadServerConfigs(
|
||||
server(async () => {
|
||||
throw new Error('M_UNRECOGNIZED');
|
||||
})
|
||||
);
|
||||
expect(error).not.toHaveBeenCalled();
|
||||
expect(configs.authMetadata).toBeUndefined();
|
||||
expect(configs.mediaConfig).toEqual({ 'm.upload.size': 1 });
|
||||
});
|
||||
|
||||
it('still logs and drops auth metadata that came back malformed', async () => {
|
||||
const error = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
const configs = await loadServerConfigs(server(async () => ({ issuer: 'https://x' })));
|
||||
expect(error).toHaveBeenCalled();
|
||||
expect(configs.authMetadata).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
|
@ -1,5 +1,10 @@
|
|||
import { ReactNode, useCallback, useMemo } from 'react';
|
||||
import { Capabilities, validateAuthMetadata, ValidatedAuthMetadata } from 'matrix-js-sdk';
|
||||
import {
|
||||
Capabilities,
|
||||
MatrixClient,
|
||||
validateAuthMetadata,
|
||||
ValidatedAuthMetadata,
|
||||
} from 'matrix-js-sdk';
|
||||
import { AsyncStatus, useAsyncCallbackValue } from '../hooks/useAsyncCallback';
|
||||
import { useMatrixClient } from '../hooks/useMatrixClient';
|
||||
import { MediaConfig } from '../hooks/useMediaConfig';
|
||||
|
|
@ -14,35 +19,42 @@ export type ServerConfigs = {
|
|||
type ServerConfigsLoaderProps = {
|
||||
children: (configs: ServerConfigs) => ReactNode;
|
||||
};
|
||||
/**
|
||||
* The homeserver's capabilities, media config and OIDC metadata. A homeserver with no OIDC (and the demo's pretend
|
||||
* server) returns no auth metadata: there is nothing to validate, so nothing is logged. Metadata that did come back
|
||||
* and fails validation is logged and dropped.
|
||||
*/
|
||||
export async function loadServerConfigs(
|
||||
mx: Pick<MatrixClient, 'getCapabilities' | 'getMediaConfig' | 'getAuthMetadata'>
|
||||
): Promise<ServerConfigs> {
|
||||
const result = await Promise.allSettled([
|
||||
mx.getCapabilities(),
|
||||
mx.getMediaConfig(),
|
||||
mx.getAuthMetadata(),
|
||||
]);
|
||||
|
||||
const capabilities = promiseFulfilledResult(result[0]);
|
||||
const mediaConfig = promiseFulfilledResult(result[1]);
|
||||
const authMetadata = promiseFulfilledResult(result[2]);
|
||||
let validatedAuthMetadata: ValidatedAuthMetadata | undefined;
|
||||
|
||||
if (authMetadata) {
|
||||
try {
|
||||
validatedAuthMetadata = validateAuthMetadata(authMetadata);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
|
||||
return { capabilities, mediaConfig, authMetadata: validatedAuthMetadata };
|
||||
}
|
||||
|
||||
export function ServerConfigsLoader({ children }: ServerConfigsLoaderProps) {
|
||||
const mx = useMatrixClient();
|
||||
const fallbackConfigs = useMemo(() => ({}), []);
|
||||
|
||||
const [configsState] = useAsyncCallbackValue<ServerConfigs, unknown>(
|
||||
useCallback(async () => {
|
||||
const result = await Promise.allSettled([
|
||||
mx.getCapabilities(),
|
||||
mx.getMediaConfig(),
|
||||
mx.getAuthMetadata(),
|
||||
]);
|
||||
|
||||
const capabilities = promiseFulfilledResult(result[0]);
|
||||
const mediaConfig = promiseFulfilledResult(result[1]);
|
||||
const authMetadata = promiseFulfilledResult(result[2]);
|
||||
let validatedAuthMetadata: ValidatedAuthMetadata | undefined;
|
||||
|
||||
try {
|
||||
validatedAuthMetadata = validateAuthMetadata(authMetadata);
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
|
||||
return {
|
||||
capabilities,
|
||||
mediaConfig,
|
||||
authMetadata: validatedAuthMetadata,
|
||||
};
|
||||
}, [mx])
|
||||
useCallback(() => loadServerConfigs(mx), [mx])
|
||||
);
|
||||
|
||||
const configs: ServerConfigs =
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { globalStyle, style } from '@vanilla-extract/css';
|
||||
import { style } from '@vanilla-extract/css';
|
||||
import { color, config, DefaultReset, toRem } from 'folds';
|
||||
|
||||
export const Editor = style([
|
||||
|
|
@ -12,15 +12,6 @@ export const Editor = style([
|
|||
},
|
||||
]);
|
||||
|
||||
// Over the background scene (html[data-scene]) the composer is a bubble too: half strength, blurred.
|
||||
globalStyle(`:root[data-scene] ${Editor}`, {
|
||||
backgroundColor: [
|
||||
color.SurfaceVariant.Container,
|
||||
`color-mix(in srgb, ${color.SurfaceVariant.Container} 50%, transparent)`,
|
||||
],
|
||||
backdropFilter: 'blur(12px)',
|
||||
});
|
||||
|
||||
export const EditorOptions = style([
|
||||
DefaultReset,
|
||||
{
|
||||
|
|
|
|||
9
src/app/components/logo/logoMark.css.ts
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
import { globalStyle, style } from '@vanilla-extract/css';
|
||||
|
||||
/**
|
||||
* The Ratatoskr mark is white on transparent (Meta's matte). On any light theme (they all carry `prism-light`) a class
|
||||
* of this name darkens it to the dark ink; put it on every <img> that shows the mark on a themed surface. The favicon and
|
||||
* notification icons are files the browser draws and cannot take it.
|
||||
*/
|
||||
export const LogoMark = style({});
|
||||
globalStyle(`body.prism-light .${LogoMark}`, { filter: 'brightness(0.18)' });
|
||||
|
|
@ -31,6 +31,7 @@ export const Reply = style({
|
|||
});
|
||||
|
||||
export const ReplyContent = style({
|
||||
minWidth: 0,
|
||||
opacity: config.opacity.P300,
|
||||
|
||||
selectors: {
|
||||
|
|
@ -39,3 +40,19 @@ export const ReplyContent = style({
|
|||
},
|
||||
},
|
||||
});
|
||||
|
||||
export const ReplyText = style({
|
||||
display: '-webkit-box',
|
||||
WebkitBoxOrient: 'vertical',
|
||||
WebkitLineClamp: 2,
|
||||
overflow: 'hidden',
|
||||
minWidth: 0,
|
||||
maxWidth: '100%',
|
||||
overflowWrap: 'anywhere',
|
||||
wordBreak: 'break-word',
|
||||
});
|
||||
|
||||
export const ReplyWrap = style({
|
||||
minWidth: 0,
|
||||
maxWidth: '100%',
|
||||
});
|
||||
|
|
|
|||
|
|
@ -101,7 +101,14 @@ export const Reply = as<'div', ReplyProps>(
|
|||
const bodyJSX = body ? scaleSystemEmoji(trimReplyFromBody(body)) : fallbackBody;
|
||||
|
||||
return (
|
||||
<Box direction="Row" gap="200" alignItems="Center" {...props} ref={ref}>
|
||||
<Box
|
||||
className={css.ReplyWrap}
|
||||
direction="Row"
|
||||
gap="200"
|
||||
alignItems="Center"
|
||||
{...props}
|
||||
ref={ref}
|
||||
>
|
||||
{threadRootId && (
|
||||
<ThreadIndicator as="button" data-event-id={threadRootId} onClick={onClick} />
|
||||
)}
|
||||
|
|
@ -119,7 +126,7 @@ export const Reply = as<'div', ReplyProps>(
|
|||
onClick={onClick}
|
||||
>
|
||||
{replyEvent !== undefined ? (
|
||||
<Text size="T300" truncate>
|
||||
<Text size="T300" className={css.ReplyText}>
|
||||
{badEncryption ? <MessageBadEncryptedContent /> : bodyJSX}
|
||||
</Text>
|
||||
) : (
|
||||
|
|
|
|||
|
|
@ -30,10 +30,8 @@ type BubbleLayoutProps = {
|
|||
hideBubble?: boolean;
|
||||
/** The sender is the signed-in user: right-aligned, in the accent colour, no avatar. */
|
||||
own?: boolean;
|
||||
/** A Mind's pose portrait; it replaces the avatar and sits beside (wide) or inside (phone) the bubble. */
|
||||
/** A Mind's pose portrait; it replaces the avatar and nests in a corner of the bubble. */
|
||||
pose?: ReactNode;
|
||||
/** On phones the portrait floats on the other side. */
|
||||
alt?: boolean;
|
||||
/** Delay in ms before the first-appearance animation; undefined plays none. */
|
||||
enterDelay?: number;
|
||||
before?: ReactNode;
|
||||
|
|
@ -41,7 +39,7 @@ type BubbleLayoutProps = {
|
|||
};
|
||||
|
||||
export const BubbleLayout = as<'div', BubbleLayoutProps>(
|
||||
({ hideBubble, own, pose, alt, enterDelay, before, header, children, style, ...props }, ref) => {
|
||||
({ hideBubble, own, pose, enterDelay, before, header, children, style, ...props }, ref) => {
|
||||
// `false` is a Mind's message continuing a run: aligned with the portraits, showing none.
|
||||
const poseRow = pose !== undefined;
|
||||
const arrow = !!before && !poseRow && !own;
|
||||
|
|
@ -50,12 +48,7 @@ export const BubbleLayout = as<'div', BubbleLayoutProps>(
|
|||
<Box
|
||||
gap="300"
|
||||
{...props}
|
||||
className={classNames(
|
||||
poseRow && css.BubbleRowPose,
|
||||
pose && css.BubbleRowPortrait,
|
||||
own && css.BubbleRowOwn,
|
||||
props.className
|
||||
)}
|
||||
className={classNames(own && css.BubbleRowOwn, props.className)}
|
||||
style={entering ? { ...style, ['--enter-delay' as string]: `${enterDelay}ms` } : style}
|
||||
ref={ref}
|
||||
>
|
||||
|
|
@ -67,19 +60,9 @@ export const BubbleLayout = as<'div', BubbleLayoutProps>(
|
|||
<Box
|
||||
grow={own ? 'No' : 'Yes'}
|
||||
direction="Column"
|
||||
className={classNames(poseRow && css.BubbleColumnPose, own && css.BubbleColumnOwn)}
|
||||
className={classNames(own && css.BubbleColumnOwn)}
|
||||
>
|
||||
{header && (
|
||||
<div
|
||||
className={classNames(
|
||||
pose && css.BubbleHeaderPose,
|
||||
pose && alt && css.BubbleHeaderPoseAlt,
|
||||
own && css.BubbleHeaderOwn
|
||||
)}
|
||||
>
|
||||
{header}
|
||||
</div>
|
||||
)}
|
||||
{header && <div className={classNames(own && css.BubbleHeaderOwn)}>{header}</div>}
|
||||
{hideBubble ? (
|
||||
children
|
||||
) : (
|
||||
|
|
@ -89,6 +72,7 @@ export const BubbleLayout = as<'div', BubbleLayoutProps>(
|
|||
css.BubbleContent,
|
||||
arrow && css.BubbleContentArrowLeft,
|
||||
poseRow && css.BubbleContentPose,
|
||||
pose && css.BubbleContentPortrait,
|
||||
own && css.BubbleContentOwn,
|
||||
entering && css.EnterBubble
|
||||
)}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { createVar, globalStyle, keyframes, style, styleVariants } from '@vanilla-extract/css';
|
||||
import { recipe, RecipeVariants } from '@vanilla-extract/recipes';
|
||||
import { DefaultReset, color, config, toRem } from 'folds';
|
||||
import { MOBILE_BREAKPOINT } from '../../../hooks/useScreenSize';
|
||||
|
||||
export const StickySection = style({
|
||||
position: 'sticky',
|
||||
|
|
@ -152,37 +153,21 @@ export const BubbleContentArrowLeft = style({
|
|||
borderTopLeftRadius: 0,
|
||||
});
|
||||
|
||||
// Look of the three-doors mock-up (chat.gamecult.org/mockups/three-doors): a Mind's pose sits
|
||||
// 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).
|
||||
// A Mind's pose nests in the corner of its bubble, on phones and wide screens alike: the sprite's
|
||||
// body sits in the bubble's padding and the bubble's edge cuts it, so nothing hangs outside; the
|
||||
// text wraps around its silhouette (shape-outside, traced from the alpha channel) and the bubble
|
||||
// grows to hold it. How much of the art the edge may cut comes from pose/nest.ts.
|
||||
// Displayed width of the whole sprite image; the crop fractions are multiples of it.
|
||||
export const portraitWidth = createVar();
|
||||
const PHONE = 'screen and (max-width: 700px)';
|
||||
const PORTRAIT = toRem(124);
|
||||
const POSE_GUTTER = toRem(14);
|
||||
const PORTRAIT = toRem(190);
|
||||
const PHONE_PORTRAIT = 'min(38vw, 160px)';
|
||||
const PHONE_TEXT_FLOOR = toRem(170);
|
||||
const BUBBLE_PAD = toRem(12);
|
||||
const BUBBLE_CORNER = toRem(6);
|
||||
const POP = 'cubic-bezier(0.34, 1.7, 0.64, 1)';
|
||||
const RISE = 'cubic-bezier(0.34, 1.45, 0.64, 1)';
|
||||
|
||||
export const BubbleRowPose = style({
|
||||
position: 'relative',
|
||||
paddingLeft: `calc(${PORTRAIT} + ${POSE_GUTTER})`,
|
||||
'@media': {
|
||||
[PHONE]: {
|
||||
paddingLeft: 0,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// A row that shows a portrait: room for it to hang above the bubble on phones.
|
||||
export const BubbleRowPortrait = style({
|
||||
minHeight: PORTRAIT,
|
||||
'@media': {
|
||||
[PHONE]: {
|
||||
minHeight: 0,
|
||||
marginTop: toRem(58),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
export const BubbleRowOwn = style({
|
||||
justifyContent: 'flex-end',
|
||||
});
|
||||
|
|
@ -196,48 +181,31 @@ 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.
|
||||
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',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
export const BubbleHeaderPoseAlt = style({
|
||||
'@media': {
|
||||
[PHONE]: {
|
||||
right: 'auto',
|
||||
left: toRem(14),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
export const BubbleColumnPose = style({
|
||||
position: 'relative',
|
||||
});
|
||||
|
||||
// The message body is a flex column, which forms its own block formatting context and would sit
|
||||
// whole beside the floated portrait; as a plain block its lines wrap around the silhouette and
|
||||
// then run the bubble's full width below it.
|
||||
export const BubbleContentPose = style({
|
||||
borderRadius: config.radii.R500,
|
||||
borderTopLeftRadius: BUBBLE_CORNER,
|
||||
display: 'flow-root',
|
||||
overflow: 'clip',
|
||||
padding: BUBBLE_PAD,
|
||||
});
|
||||
|
||||
// A bubble that shows a portrait is at least portrait + a readable column wide, or the text beside
|
||||
// it collapses to a strip.
|
||||
export const BubbleContentPortrait = style({
|
||||
vars: { [portraitWidth]: PORTRAIT },
|
||||
minWidth: `min(100%, calc(${portraitWidth} + ${PHONE_TEXT_FLOOR}))`,
|
||||
'@media': {
|
||||
[PHONE]: {
|
||||
display: 'flow-root',
|
||||
borderTopLeftRadius: config.radii.R500,
|
||||
padding: `${toRem(24)} ${toRem(14)} ${toRem(14)}`,
|
||||
vars: { [portraitWidth]: PHONE_PORTRAIT },
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
globalStyle(`${BubbleContentPose} > div`, {
|
||||
display: 'block',
|
||||
});
|
||||
|
||||
export const BubbleContentOwn = style({
|
||||
backgroundColor: color.Primary.Container,
|
||||
color: color.Primary.OnContainer,
|
||||
|
|
@ -246,52 +214,37 @@ export const BubbleContentOwn = style({
|
|||
borderTopRightRadius: BUBBLE_CORNER,
|
||||
});
|
||||
|
||||
// The button is the visible part of the sprite (the part inside the bubble's corner); the image
|
||||
// inside it is offset by the crop. The inline --pose-* fractions (of the image width) come from
|
||||
// nestView; until the art's size is known the button is simply the whole image.
|
||||
export const PoseButton = style({
|
||||
position: 'absolute',
|
||||
top: 0,
|
||||
left: `calc(-1 * (${PORTRAIT} + ${POSE_GUTTER}))`,
|
||||
width: PORTRAIT,
|
||||
height: PORTRAIT,
|
||||
float: 'left',
|
||||
width: `var(--pose-bw, ${portraitWidth})`,
|
||||
height: 'var(--pose-bh, auto)',
|
||||
// Out into the padding on the top, bottom and outer side, so the bubble's edge is the crop.
|
||||
margin: `calc(-1 * ${BUBBLE_PAD}) ${toRem(6)} calc(-1 * ${BUBBLE_PAD}) calc(-1 * ${BUBBLE_PAD})`,
|
||||
padding: 0,
|
||||
border: 'none',
|
||||
background: 'none',
|
||||
cursor: 'pointer',
|
||||
lineHeight: 0,
|
||||
overflow: 'hidden',
|
||||
shapeMargin: toRem(7),
|
||||
transformOrigin: '50% 90%',
|
||||
'@media': {
|
||||
[PHONE]: {
|
||||
position: 'static',
|
||||
float: 'left',
|
||||
width: 'min(50vw, 210px)',
|
||||
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)',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
export const PoseButtonAlt = style({
|
||||
'@media': {
|
||||
[PHONE]: {
|
||||
float: 'right',
|
||||
margin: `${toRem(-82)} ${toRem(-12)} 0 ${toRem(8)}`,
|
||||
},
|
||||
},
|
||||
float: 'right',
|
||||
margin: `calc(-1 * ${BUBBLE_PAD}) calc(-1 * ${BUBBLE_PAD}) calc(-1 * ${BUBBLE_PAD}) ${toRem(6)}`,
|
||||
});
|
||||
|
||||
export const PosePortrait = style({
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
objectFit: 'contain',
|
||||
objectPosition: 'top',
|
||||
'@media': {
|
||||
[PHONE]: {
|
||||
height: 'auto',
|
||||
},
|
||||
},
|
||||
display: 'block',
|
||||
width: portraitWidth,
|
||||
maxWidth: 'none',
|
||||
height: 'auto',
|
||||
marginLeft: 'var(--pose-ix, 0)',
|
||||
marginTop: 'var(--pose-iy, 0)',
|
||||
});
|
||||
|
||||
const pop = keyframes({
|
||||
|
|
@ -331,6 +284,9 @@ export const BubbleLeftArrow = style({
|
|||
zIndex: 1,
|
||||
});
|
||||
|
||||
// Phone tap target: a sender name is 23 px tall, so the button grows 11 px above and below (44+ px to tap) and the
|
||||
// negative margin takes the growth back out of the layout. Hit area only: no background, border or outline moves.
|
||||
const SCREEN_PHONE = `screen and (max-width: ${MOBILE_BREAKPOINT}px)`;
|
||||
export const Username = style({
|
||||
overflow: 'hidden',
|
||||
whiteSpace: 'nowrap',
|
||||
|
|
@ -338,6 +294,9 @@ export const Username = style({
|
|||
selectors: {
|
||||
'button&': {
|
||||
cursor: 'pointer',
|
||||
'@media': {
|
||||
[SCREEN_PHONE]: { paddingBlock: 11, marginBlock: -11 },
|
||||
},
|
||||
},
|
||||
'button&:hover, button&:focus-visible': {
|
||||
textDecoration: 'underline',
|
||||
|
|
@ -376,16 +335,12 @@ export const MessageTextBody = recipe({
|
|||
|
||||
export type MessageTextBodyVariants = RecipeVariants<typeof MessageTextBody>;
|
||||
|
||||
// The message content is a flex column, which forms its own block formatting context and so sits
|
||||
// whole beside the floated portrait: the text stays as narrow as the gap beside it for the
|
||||
// bubble's full height. As a plain block its lines wrap around the silhouette and then run the
|
||||
// bubble's full width below it.
|
||||
globalStyle(`${BubbleContentPose} > div`, {
|
||||
'@media': {
|
||||
[PHONE]: {
|
||||
display: 'block',
|
||||
},
|
||||
},
|
||||
// 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`, {
|
||||
listStylePosition: 'inside',
|
||||
paddingLeft: 0,
|
||||
});
|
||||
|
||||
// While the background scene runs (html[data-scene]) a chat bubble is the one filled surface in
|
||||
|
|
@ -400,14 +355,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',
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,32 +1,137 @@
|
|||
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 { poseSrc, safeBox } from './poses';
|
||||
import { alphaBounds, nestView, type Box } from './nest';
|
||||
import { silhouette } from './silhouette';
|
||||
|
||||
type PoseAvatarProps = {
|
||||
mind: string;
|
||||
pose: string;
|
||||
userId: string;
|
||||
/** Float on the right on phones. */
|
||||
/** Nest in the bubble's top-right corner instead of the top-left. */
|
||||
alt?: boolean;
|
||||
/** Play the first-appearance pop. */
|
||||
enter?: boolean;
|
||||
onClick: React.MouseEventHandler<HTMLButtonElement>;
|
||||
/** Without it the portrait is a plain image: no button, no tab stop. */
|
||||
onClick?: React.MouseEventHandler<HTMLButtonElement>;
|
||||
};
|
||||
|
||||
// Safe boxes derived from art's alpha, by source; the art is traced once.
|
||||
const traced = new Map<string, { box: Box; size: [number, number] }>();
|
||||
const trace = (img: HTMLImageElement, src: string) => {
|
||||
const hit = traced.get(src);
|
||||
if (hit) return hit;
|
||||
const w = img.naturalWidth;
|
||||
const h = img.naturalHeight;
|
||||
const ctx = document.createElement('canvas').getContext('2d');
|
||||
if (!ctx) return undefined;
|
||||
ctx.canvas.width = w;
|
||||
ctx.canvas.height = h;
|
||||
ctx.drawImage(img, 0, 0);
|
||||
const box = alphaBounds(ctx.getImageData(0, 0, w, h).data, w, h);
|
||||
if (!box) return undefined;
|
||||
const found = { box, size: [w, h] as [number, number] };
|
||||
traced.set(src, found);
|
||||
return found;
|
||||
};
|
||||
|
||||
export function PoseAvatar({ mind, pose, userId, alt, enter, onClick }: PoseAvatarProps) {
|
||||
const src = poseSrc(mind, pose, import.meta.env.BASE_URL);
|
||||
const imgRef = useRef<HTMLImageElement>(null);
|
||||
const [shape, setShape] = useState<string>();
|
||||
const measured = safeBox(mind, pose);
|
||||
const [derived, setDerived] = useState<{ box: Box; size: [number, number] }>();
|
||||
const art = measured ?? (derived?.size ? derived : undefined);
|
||||
// Measured boxes are cropped by the share Aqua's numbers allow; a box traced from the alpha is
|
||||
// already tight to the art, so the bubble may take all of the transparent margin.
|
||||
const view = art && nestView(art.box, art.size, !!alt, measured ? undefined : 1);
|
||||
|
||||
// Art with no measured box: find its extent when it loads.
|
||||
useEffect(() => {
|
||||
setDerived(undefined);
|
||||
const img = imgRef.current;
|
||||
if (!img || measured) return undefined;
|
||||
const find = () => {
|
||||
if (!img.complete || img.naturalWidth === 0) return;
|
||||
try {
|
||||
setDerived(trace(img, src));
|
||||
} catch {
|
||||
setDerived(undefined);
|
||||
}
|
||||
};
|
||||
find();
|
||||
img.addEventListener('load', find);
|
||||
return () => img.removeEventListener('load', find);
|
||||
}, [src, measured]);
|
||||
|
||||
// The bubble text wraps around the portrait's silhouette. Retraced when the art loads, when its
|
||||
// crop is known, and when its width changes with the viewport.
|
||||
useEffect(() => {
|
||||
const img = imgRef.current;
|
||||
if (!img) return undefined;
|
||||
const retrace = () => {
|
||||
if (!img.complete || img.naturalWidth === 0) return;
|
||||
try {
|
||||
const box = img.parentElement;
|
||||
const style = getComputedStyle(img);
|
||||
setShape(
|
||||
silhouette(
|
||||
img,
|
||||
!alt,
|
||||
box
|
||||
? {
|
||||
x: 0 - parseFloat(style.marginLeft || '0'),
|
||||
y: 0 - parseFloat(style.marginTop || '0'),
|
||||
width: box.clientWidth,
|
||||
height: box.clientHeight,
|
||||
}
|
||||
: undefined
|
||||
)
|
||||
);
|
||||
} catch {
|
||||
setShape(undefined);
|
||||
}
|
||||
};
|
||||
retrace();
|
||||
img.addEventListener('load', retrace);
|
||||
const resize = new ResizeObserver(retrace);
|
||||
resize.observe(img);
|
||||
return () => {
|
||||
img.removeEventListener('load', retrace);
|
||||
resize.disconnect();
|
||||
};
|
||||
}, [src, alt, view?.x, view?.y, view?.width, view?.height]);
|
||||
|
||||
// Crop fractions are of the image's width, so one set serves every displayed size.
|
||||
const frac = (px: number) => `calc(${css.portraitWidth} * ${px / (art?.size[0] ?? 1)})`;
|
||||
const cropStyle =
|
||||
art && view
|
||||
? ({
|
||||
'--pose-bw': frac(view.width),
|
||||
'--pose-bh': frac(view.height),
|
||||
'--pose-ix': frac(-view.x),
|
||||
'--pose-iy': frac(-view.y),
|
||||
} as React.CSSProperties)
|
||||
: undefined;
|
||||
|
||||
const Tag = onClick ? 'button' : 'span';
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
<Tag
|
||||
type={onClick ? 'button' : undefined}
|
||||
className={classNames(css.PoseButton, alt && css.PoseButtonAlt, enter && css.EnterPortrait)}
|
||||
// On phones the bubble text wraps around the portrait's silhouette.
|
||||
style={{ shapeOutside: `url(${src})` }}
|
||||
style={{ ...cropStyle, shapeOutside: shape }}
|
||||
data-user-id={userId}
|
||||
data-pose={pose}
|
||||
onClick={onClick}
|
||||
>
|
||||
<img className={css.PosePortrait} src={src} alt={`${mind}, ${pose}`} draggable={false} />
|
||||
</button>
|
||||
<img
|
||||
ref={imgRef}
|
||||
className={css.PosePortrait}
|
||||
src={src}
|
||||
alt={`${mind}, ${pose}`}
|
||||
draggable={false}
|
||||
/>
|
||||
</Tag>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
72
src/app/components/message/pose/nest.test.ts
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import { alphaBounds, nestView } from './nest';
|
||||
import boxes from './safeBoxes.json';
|
||||
|
||||
describe('nestView', () => {
|
||||
// Aqua neutral: 560x374, safe box [144,22,492,317] (right margin 68, top 22).
|
||||
it('crops half the right and top margins for a top-right nest', () => {
|
||||
expect(nestView([144, 22, 492, 317], [560, 374], true)).toEqual({
|
||||
x: 0,
|
||||
y: 11,
|
||||
width: 526,
|
||||
height: 363,
|
||||
});
|
||||
});
|
||||
|
||||
it('crops the left margin instead for a top-left nest', () => {
|
||||
expect(nestView([144, 22, 492, 317], [560, 374], false)).toEqual({
|
||||
x: 72,
|
||||
y: 11,
|
||||
width: 488,
|
||||
height: 363,
|
||||
});
|
||||
});
|
||||
|
||||
it('never crops the top of art already touching it (smug, headband at y=0)', () => {
|
||||
const v = nestView([140, 0, 487, 241], [560, 374], true);
|
||||
expect(v.y).toBe(0);
|
||||
expect(v.height).toBe(374);
|
||||
});
|
||||
|
||||
it('can take the whole margin', () => {
|
||||
expect(nestView([10, 4, 90, 50], [100, 60], true, 1)).toEqual({
|
||||
x: 0,
|
||||
y: 4,
|
||||
width: 90,
|
||||
height: 56,
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps every measured safe box intact at the default share', () => {
|
||||
const aqua = boxes.aqua as Record<string, number[]>;
|
||||
expect(Object.keys(aqua)).toHaveLength(15);
|
||||
Object.values(aqua).forEach(([x0, y0, x1, y1, w, h]) => {
|
||||
const right = nestView([x0, y0, x1, y1], [w, h], true);
|
||||
expect(right.x).toBeLessThanOrEqual(x0);
|
||||
expect(right.x + right.width).toBeGreaterThanOrEqual(x1);
|
||||
expect(right.y).toBeLessThanOrEqual(y0);
|
||||
const left = nestView([x0, y0, x1, y1], [w, h], false);
|
||||
expect(left.x).toBeLessThanOrEqual(x0);
|
||||
expect(left.x + left.width).toBe(w);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('alphaBounds', () => {
|
||||
it('finds the opaque rectangle', () => {
|
||||
const w = 6;
|
||||
const h = 5;
|
||||
const data = new Uint8ClampedArray(w * h * 4);
|
||||
[
|
||||
[2, 1],
|
||||
[4, 3],
|
||||
].forEach(([x, y]) => {
|
||||
data[(y * w + x) * 4 + 3] = 255;
|
||||
});
|
||||
expect(alphaBounds(data, w, h)).toEqual([2, 1, 5, 4]);
|
||||
});
|
||||
|
||||
it('reports nothing for an empty image', () => {
|
||||
expect(alphaBounds(new Uint8ClampedArray(16), 2, 2)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
58
src/app/components/message/pose/nest.ts
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
// A pose nests into the corner of its bubble: the sprite's body sits in the bubble's padding and is
|
||||
// cut off by the bubble's edge, so nothing hangs outside it.
|
||||
|
||||
/** [x0, y0, x1, y1] in image pixels, origin top-left, x1/y1 exclusive. */
|
||||
export type Box = [number, number, number, number];
|
||||
|
||||
// Share of the room between the safe box and the image edge that the bubble edge may cut away.
|
||||
// Aqua's measurement says all of it can go; half leaves the outline a little air.
|
||||
export const CROP_SHARE = 0.5;
|
||||
|
||||
export type NestView = {
|
||||
/** The visible region of the image, in pixels. */
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
height: number;
|
||||
};
|
||||
|
||||
// The part of the image that shows, for a sprite in the bubble's top-right (`right`) or top-left
|
||||
// corner. Only the corner's two sides are cropped: the side towards the bubble's edge and the top.
|
||||
// The far side and the bottom stay whole; the bubble's bottom edge cuts the bust.
|
||||
export const nestView = (
|
||||
safe: Box,
|
||||
size: [number, number],
|
||||
right: boolean,
|
||||
share = CROP_SHARE
|
||||
): NestView => {
|
||||
const [w, h] = size;
|
||||
const [x0, y0, x1] = safe;
|
||||
const side = Math.round(share * (right ? w - x1 : x0));
|
||||
const top = Math.round(share * y0);
|
||||
const x = right ? 0 : side;
|
||||
return { x, y: top, width: w - side, height: h - top };
|
||||
};
|
||||
|
||||
// Bounds of the pixels whose alpha exceeds `min`, as a safe box for art with no measured one.
|
||||
export const alphaBounds = (
|
||||
data: ArrayLike<number>,
|
||||
w: number,
|
||||
h: number,
|
||||
min = 8
|
||||
): Box | undefined => {
|
||||
let x0 = w;
|
||||
let y0 = h;
|
||||
let x1 = 0;
|
||||
let y1 = 0;
|
||||
for (let y = 0; y < h; y += 1) {
|
||||
for (let x = 0; x < w; x += 1) {
|
||||
if (data[(y * w + x) * 4 + 3] > min) {
|
||||
x0 = Math.min(x0, x);
|
||||
x1 = Math.max(x1, x + 1);
|
||||
y0 = Math.min(y0, y);
|
||||
y1 = y + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return x1 > x0 ? [x0, y0, x1, y1] : undefined;
|
||||
};
|
||||
|
|
@ -1,6 +1,10 @@
|
|||
import { describe, expect, it } from 'vitest';
|
||||
import catalogue from './catalogue.json';
|
||||
import { mindOfSender, poseSrc, poseStatusLine, poseStatuses, resolvePose } from './poses';
|
||||
import {
|
||||
mindOfSender,
|
||||
poseSrc,
|
||||
resolvePose,
|
||||
} from './poses';
|
||||
|
||||
describe('resolvePose', () => {
|
||||
it('keeps shared and own-signature labels from the catalogue', () => {
|
||||
|
|
@ -46,38 +50,5 @@ describe('poseSrc', () => {
|
|||
});
|
||||
});
|
||||
|
||||
describe('poseStatuses', () => {
|
||||
const ev = (sender: string, ts: number, label: unknown) => ({
|
||||
sender,
|
||||
localpart: sender,
|
||||
ts,
|
||||
label,
|
||||
});
|
||||
it('reports the latest pose per Mind and when its unbroken run began', () => {
|
||||
const out = poseStatuses([
|
||||
ev('aqua', 1, 'happy'),
|
||||
ev('aqua', 2, 'sigh'),
|
||||
ev('aqua', 3, 'sigh'),
|
||||
ev('alice', 4, 'happy'),
|
||||
ev('eureka', 5, 'probe'),
|
||||
]);
|
||||
expect(out).toEqual([
|
||||
{ mind: 'aqua', pose: 'sigh', since: 2 },
|
||||
{ mind: 'eureka', pose: 'probe', since: 5 },
|
||||
]);
|
||||
});
|
||||
it('treats unknown labels as neutral runs', () => {
|
||||
expect(poseStatuses([ev('void', 1, 'bogus'), ev('void', 2, undefined)])).toEqual([
|
||||
{ mind: 'void', pose: 'neutral', since: 1 },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('poseStatusLine', () => {
|
||||
it('formats the client-status line', () => {
|
||||
const since = new Date(2026, 10, 4, 9, 5).getTime();
|
||||
expect(poseStatusLine({ mind: 'void', pose: 'reading', since })).toBe(
|
||||
'Ratatoskr: Void is reading, since 09:05'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,6 @@
|
|||
import catalogue from './catalogue.json';
|
||||
import safeBoxes from './safeBoxes.json';
|
||||
import type { Box } from './nest';
|
||||
|
||||
// Pose labels travel in the event content under POSE_KEY. The catalogue
|
||||
// (cast-art poses/catalogue.json, synced by `npm run sync:poses`) is the only
|
||||
|
|
@ -40,39 +42,14 @@ export const resolvePose = (mind: string, label: unknown): string => {
|
|||
export const poseSrc = (mind: string, pose: string, base = '/'): string =>
|
||||
`${base}public/poses/${artPath(mind, pose) ?? artPath(mind, NEUTRAL)}`;
|
||||
|
||||
export type PoseStatus = { mind: string; pose: string; since: number };
|
||||
export type PoseEvent = {
|
||||
sender: string;
|
||||
localpart?: string;
|
||||
name?: string;
|
||||
ts: number;
|
||||
label: unknown;
|
||||
};
|
||||
|
||||
// Latest pose per Mind in a room's events (oldest first), and when that pose
|
||||
// began: the first of its unbroken run of messages carrying the same pose.
|
||||
export const poseStatuses = (events: PoseEvent[]): PoseStatus[] => {
|
||||
const bySender = new Map<string, { mind: string; run: { pose: string; ts: number }[] }>();
|
||||
events.forEach((e) => {
|
||||
const mind = mindOfSender(e.localpart, e.name);
|
||||
if (!mind) return;
|
||||
const entry = bySender.get(e.sender) ?? { mind, run: [] };
|
||||
entry.run.push({ pose: resolvePose(mind, e.label), ts: e.ts });
|
||||
bySender.set(e.sender, entry);
|
||||
});
|
||||
return [...bySender.values()].map(({ mind, run }) => {
|
||||
const last = run[run.length - 1];
|
||||
let i = run.length - 1;
|
||||
while (i > 0 && run[i - 1].pose === last.pose) i -= 1;
|
||||
return { mind, pose: last.pose, since: run[i].ts };
|
||||
});
|
||||
};
|
||||
|
||||
const two = (n: number) => String(n).padStart(2, '0');
|
||||
|
||||
// Client-status text. Rendered locally only; it is never sent to a room.
|
||||
export const poseStatusLine = ({ mind, pose, since }: PoseStatus): string => {
|
||||
const d = new Date(since);
|
||||
const name = mind.charAt(0).toUpperCase() + mind.slice(1);
|
||||
return `Ratatoskr: ${name} is ${pose}, since ${two(d.getHours())}:${two(d.getMinutes())}`;
|
||||
// Safe-crop boxes measured from the art's pixels (Aqua, `aqua-pose-crop-boxes-20261110`): the
|
||||
// head and headphones plus outline, which the bubble's edge must not cut. [x0, y0, x1, y1, width,
|
||||
// height] in image pixels. Art with no entry gets its box from the sprite's alpha at load time.
|
||||
const boxes = safeBoxes as Record<string, Record<string, number[]>>;
|
||||
export const safeBox = (
|
||||
mind: string,
|
||||
pose: string
|
||||
): { box: Box; size: [number, number] } | undefined => {
|
||||
const b = Object.prototype.hasOwnProperty.call(boxes, mind) ? boxes[mind][pose] : undefined;
|
||||
return b ? { box: [b[0], b[1], b[2], b[3]], size: [b[4], b[5]] } : undefined;
|
||||
};
|
||||
|
|
|
|||
19
src/app/components/message/pose/safeBoxes.json
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
{
|
||||
"aqua": {
|
||||
"neutral": [144, 22, 492, 317, 560, 374],
|
||||
"happy": [157, 22, 506, 317, 574, 374],
|
||||
"amused": [154, 22, 500, 317, 562, 374],
|
||||
"thinking": [154, 16, 500, 307, 562, 374],
|
||||
"annoyed": [154, 4, 499, 282, 562, 374],
|
||||
"surprised": [141, 5, 485, 282, 560, 374],
|
||||
"concerned": [156, 4, 501, 283, 574, 374],
|
||||
"fretful": [156, 16, 503, 305, 574, 374],
|
||||
"weary": [161, 16, 509, 307, 624, 374],
|
||||
"glare": [160, 5, 508, 282, 624, 374],
|
||||
"smug": [140, 0, 487, 241, 560, 374],
|
||||
"sigh": [154, 0, 500, 241, 574, 374],
|
||||
"charging": [152, 0, 497, 241, 562, 374],
|
||||
"delighted": [159, 0, 507, 241, 624, 374],
|
||||
"content": [144, 16, 492, 306, 560, 374]
|
||||
}
|
||||
}
|
||||
74
src/app/components/message/pose/silhouette.test.ts
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
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();
|
||||
});
|
||||
|
||||
it('traces only the visible part of a cropped portrait, drawn at its offset', () => {
|
||||
const drawImage = vi.fn();
|
||||
const canvas = {
|
||||
width: 0,
|
||||
height: 0,
|
||||
getContext: () => ({
|
||||
canvas,
|
||||
drawImage,
|
||||
getImageData: () => ({ data: new Uint8ClampedArray(40 * 8 * 4) }),
|
||||
}),
|
||||
};
|
||||
vi.stubGlobal('document', { createElement: () => canvas });
|
||||
const img = { clientWidth: 100, clientHeight: 20 } as HTMLImageElement;
|
||||
silhouette(img, true, { x: 0, y: 12, width: 40, height: 8 });
|
||||
expect([canvas.width, canvas.height]).toEqual([40, 8]);
|
||||
expect(drawImage).toHaveBeenCalledWith(img, 0, -12, 100, 20);
|
||||
});
|
||||
});
|
||||
43
src/app/components/message/pose/silhouette.ts
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
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.
|
||||
//
|
||||
// `view` is the part of the displayed image that shows (the button's box, in displayed pixels):
|
||||
// the portrait is cropped by the bubble, so the polygon is traced over what is left of the art.
|
||||
export type View = { x: number; y: number; width: number; height: number };
|
||||
|
||||
export const silhouette = (
|
||||
img: HTMLImageElement,
|
||||
textOnRight: boolean,
|
||||
view?: View
|
||||
): string | undefined => {
|
||||
const w = Math.round(view?.width ?? img.clientWidth);
|
||||
const h = Math.round(view?.height ?? 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 - (view?.x ?? 0), 0 - (view?.y ?? 0), img.clientWidth, img.clientHeight);
|
||||
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`;
|
||||
};
|
||||