[ui] LetterSlot: Add the page for A Letter from the Gardener, shown once the author writes it

docs/LETTER.md holds slots as comments only, so the player sees no change
until the author writes. The app bundles the letter at build time, a small
Markdown subset renders without {@html}, only https: and tel: become links,
and lint:copy now reads the letter. Review found turbo replaying a stale
build after the letter changed; docs/LETTER.md is now in its cache key.
This commit is contained in:
2026-11-01 15:39:17 +01:00
parent b871ab9899
commit a200832cfb
23 changed files with 639 additions and 21 deletions
+1
View File
@@ -7,3 +7,4 @@ One row per feature, with its analysis document (CLAUDE.md §5.1). Gaps live in
|:--|:--|:--|:--|:--|
| Workspace, contracts, gates, PWA shell | 0 | Merged to `main` 2026-11-01 (`d11d242`); built, not deployed. Phase 0 gate still open | [phase0-workspace.md](features/phase0-workspace.md) | [feature-phase0-workspace.md](reviews/feature-phase0-workspace.md) |
| Roadmap and gameplay docs, read against the code | 0 | Merged 2026-11-01; Q1–Q7 answered by the author | — | [docs-roadmap-gameplay.md](reviews/docs-roadmap-gameplay.md) |
| The Letter slot: page at `#letter`, empty `docs/LETTER.md` | 0 | On `feature/letter-slot`; built, not deployed. Invisible until the author writes | [letter-slot.md](features/letter-slot.md) | [feature-letter-slot.md](reviews/feature-letter-slot.md) |
+3 -1
View File
@@ -40,7 +40,8 @@ workspace part of Phase 0 is in
| G0.22 | No CI | Open. Every gate ran on this machine only. With G0.13. |
| G0.23 | Source maps are built and would be published | Open. `sourcemap: true`; maps are not precached. Decide with G0.13 whether the repository is public. If not, use `'hidden'`. |
| G0.24 | No art pipeline: `docs/ART.md`, `art/STYLE.md` (drafted with the author), `art/manifest.json` for Phase 1 assets, SVG placeholders, `tools/art-prep` | Open. **Phase 0 gate**: one illustration goes through prompt, paste, automatic checks, review and the author's approval into `art/final/`. |
| G0.25 | No slot for *A Letter from the Gardener* | Open. A page and an empty `docs/LETTER.md` the author fills; agents write no part of its voice. |
| ~~G0.25~~ | ~~No slot for *A Letter from the Gardener*~~ | Closed 2026-11-01 on `feature/letter-slot`. `docs/LETTER.md` holds slots as comments only; the page opens at `#letter` once it has words. 16 ui tests, and e2e on both the empty and a temporary written letter. Mutations caught: the link while empty, any link scheme, focus not moving, *heal* in the letter. |
| G0.27 | The quiet door to real help has no numbers (§5.6 rule 5) | Open. The slot is in `docs/LETTER.md`. Support lines are real-world facts the author must verify, per country, so the door exists only once the letter does. |
| ~~G0.26~~ | ~~Not decided: how the sunset invitation reaches the player on the web~~ | Closed 2026-11-01 by the author (Q6): in-app only on the web, no push server; local notifications through the Tauri shell in Phase 6. Recorded in ROADMAP Phase 0 and CLAUDE.md §8. |
## Design questions — answered
@@ -58,3 +59,4 @@ Raised by GAMEPLAY.md and ROADMAP.md, answered by the author 2026-11-01. Details
| ~~Q6~~ | When the notification decision is due | Phase 0, in-app only (G0.26) |
| ~~Q7~~ | Which phase holds the Amicitia bridge | Phase 3 |
| Q8 | "Nearby days give a little more" | Open as a rule for the Phase 1 Soul review: a gap's cost is never shown |
| Q9 | May the Letter name the book and its author for the one sentence of inspiration (GAMEPLAY §7)? | Open. `lint:copy` refuses those names in the letter as everywhere in the product. A yes needs a written, letter-only exemption. |
+81
View File
@@ -0,0 +1,81 @@
# The Letter slot
Status: on `feature/letter-slot`, reviewed in
[`feature-letter-slot.md`](../reviews/feature-letter-slot.md). Gap: G0.25. Roadmap: Phase 0, *a slot for A Letter
from the Gardener — the author writes it; agents only scaffold the page.*
---
## 1. Why and what, in the player's terms
*A Letter from the Gardener* is the help section. It holds the deeper why, it can be
re-read at any time, and it is never needed to play (GAMEPLAY §4). It also holds the
quiet door to real help (CLAUDE.md §5.6 rule 5).
This branch makes the place for it, not the letter itself. The author writes
`docs/LETTER.md` in plain Markdown, and the app shows it as a page. **Until the author
writes something, the player sees no change at all**: there is no link to an empty
page, no "coming soon" and no dead control.
## 2. Technical architecture
```mermaid
flowchart LR
letter[("docs/LETTER.md<br/>the author's words")]
app["apps/rosea<br/>App.svelte<br/>imports it ?raw at build time"]
ui["packages/ui<br/>letter/parse.ts → blocks<br/>Letter.svelte, Shell.svelte"]
lint["scripts/lint-copy.ts"]
letter -- "bundled, precached" --> app --> ui
lint -. scans .-> letter
```
### Decisions
| # | Decision | Why |
|:--|:--|:--|
| L1 | `docs/LETTER.md` is the only copy of the letter. The app imports it with Vite's `?raw` at build time. | No runtime fetch, so the letter is in the precached bundle and opens offline. One file means the author edits one place, in Markdown. |
| L2 | The scaffold holds only HTML comments: one slot per thing the docs say the letter carries. Comments are dropped when the page is built, so the scaffold renders as nothing. | Agents never write the letter's voice. A heading is voice too, so the slots are comments, not headings. |
| L3 | A small Markdown subset is parsed into blocks in `packages/ui/src/letter/parse.ts`: headings, paragraphs, lists, *emphasis* and links. Everything else is shown as plain text. The component renders the blocks with Svelte, **never `{@html}`**. | No HTML is ever built from text, so nothing in the file can inject markup or script, and the CSP stays `'self'`. The parser lives in `ui` because it is presentation, and `ui → content` is not an allowed dependency. |
| L4 | Only `https:` and `tel:` become links. Anything else, including `http:`, `javascript:` and `data:`, stays text. External links open in a new tab, with `rel="noopener noreferrer"`. | The support door needs web and phone links. Nothing else does. |
| L5 | The page is reached by a link on the home view, at `#letter`. The link exists **only when the letter has content**. With an empty letter, `#letter` shows the home view. | Hash routing works offline without a server rule. An entry point to an empty page is a dead control. |
| L6 | `lint:copy` scans `docs/LETTER.md` with the full list, though it lives in `docs/`. | It is player-facing. The `docs/` exemption (§5.6 rule 4) is for design documents, where the words are being discussed. |
| L7 | When the view changes, focus moves to the new view's heading. | A screen-reader user hears where they are. A hash change alone announces nothing. |
| L8 | `docs/LETTER.md` is in turbo's `globalDependencies`. | Found in review: without it, a changed letter replayed the cached build (`lessons/technical.md`). |
## 3. Risk analysis
| Risk | Where | Defence |
|:--|:--|:--|
| A forbidden or medical word reaches a player through the letter | `docs/LETTER.md` | L6, with a test that the script reads the file. |
| The letter names the book | The "one sentence of inspiration" (GAMEPLAY §7) | `lint:copy` refuses *Saint-Exupéry* and the title in the letter as everywhere else. If the author wants the letter to name its source, that is a decision to write down (Q9), not an exemption made by an agent. |
| Markup or script injected through the file | The renderer | L3 and L4, with tests for `<script>`, `javascript:` and raw HTML. |
| An empty page feels broken or turns the player away | Before the author writes | L5: there is no way to reach it. |
| A link sends the player's address somewhere | Support links | `referrer: no-referrer` is already set, and `noreferrer` is on each link. Leaving the app is the player's own choice, made with a tap. |
| Someone in crisis cannot find the door | Support lines | Not solved here: the numbers are real-world facts the author must verify. The slot exists, and G0.27 tracks the rest. |
Guilt, comparison, rejection, dependence: looked for and none found. The page asks
nothing and counts nothing.
## 4. Gap analysis and the designed solution
| Gap | Solution |
|:--|:--|
| No page for the letter | `Letter.svelte`, reached at `#letter` (L5) |
| No file for the author | `docs/LETTER.md`, slots only (L2) |
| The letter escapes `lint:copy` | L6 |
| No support lines | Slot only; verified numbers are the author's (G0.27) |
## 5. Verification matrix
| Case | Kind | Where |
|:--|:--|:--|
| The scaffold, being only comments, parses to zero blocks | unit | `packages/ui/test/letter-parse.test.ts` |
| Headings, paragraphs across lines, lists, emphasis, links parse as blocks | unit | same |
| `<script>` and raw HTML stay text; `javascript:`, `data:`, `http:` links stay text | unit | same |
| `https:` and `tel:` links render as links with `noopener noreferrer` | unit | `packages/ui/test/Shell.test.ts` |
| Empty letter: no link to it, and `#letter` shows home | unit + e2e | `Shell.test.ts`, `e2e/shell.spec.ts` |
| A letter with content: the link appears, opens the page, *Back* returns, focus moves | unit | `Shell.test.ts` |
| `lint:copy` reads `docs/LETTER.md` and fails on a forbidden word in it | script, run | the review |
| The built app still renders, offline included | e2e, offline | existing suites |
| The written-letter branch of the e2e test, with a temporary sample letter | e2e, run once | the review |
| A changed letter rebuilds the app (`cache miss`) | e2e, run | the review |
+3 -3
View File
@@ -10,9 +10,9 @@ and **how to apply it**.
| `architecture.md` | none yet | Layering, ownership, seams. |
| `design.md` | none yet | Wording, silence, empty states. |
| `art.md` | none yet | The image pipeline. |
| [`code.md`](code.md) | 1 | TypeScript, Svelte, async ordering, Rust. |
| [`technical.md`](technical.md) | 3 | The browser and the build as platforms. |
| [`testing.md`](testing.md) | 3 | What makes a test worth having, and how a passing test lies. |
| [`code.md`](code.md) | 2 | TypeScript, Svelte, async ordering, Rust. |
| [`technical.md`](technical.md) | 4 | The browser and the build as platforms. |
| [`testing.md`](testing.md) | 4 | What makes a test worth having, and how a passing test lies. |
| `privacy.md` | none yet | What could leave the device or make a person findable. (The geocell finding is in the review, not here: it was caught before it cost anything.) |
| [`process.md`](process.md) | 2 | Workflow, commits, credentials, honesty about what shipped. |
+15
View File
@@ -20,3 +20,18 @@ fixed the same way. Check with `grep -n $'\xc2\xa0' file` (the two UTF-8 bytes)
`sed -n Np file | od -c`. Do not use `grep -P '\xA0'`: it matches the last byte of `≠`
and other characters, and raised a false alarm on the review document. Keep
`no-irregular-whitespace` on.
## A Svelte 5 effect that short-circuits never tracks what it skipped
**What happened.** `Shell.svelte` moved focus with
`$effect(() => { if (moved) heading?.focus(); })`. `moved` is a plain variable and was
`false` on the first run, so the effect never read `heading` and had no dependencies.
When the view changed and `heading` was bound to the new `<h1>`, nothing re-ran. The
Shell test caught it: the focus stayed on `<body>`.
**Why it bit.** An effect tracks only the state it actually reads on each run. A
condition that returns early hides every read after it.
**How to apply it.** In an effect, read the state you depend on before any early
return or `&&` (`const target = heading; if (moved) target?.focus();`). Test the
re-run, not just the first run.
+15
View File
@@ -40,3 +40,18 @@ needed for non-CSS style languages or TS features that emit code (enums, decorat
**How to apply it.** Leave `svelte.config.js` as `export default {}` until a component
needs SCSS or emitted TS. Add the preprocessor in the same commit as that need.
## Turbo's cache does not see a file the app imports from outside its package
**What happened.** The app imports `docs/LETTER.md?raw`. With a sample letter written
into the file, `pnpm test:e2e` printed `@rosea/app:build: cache hit` and tested the
*old* bundle, so the link to the letter was missing. Turbo hashes a package's own
files, and `docs/` belongs to no package. Adding `docs/LETTER.md` to
`globalDependencies` in `turbo.json` turned it into a `cache miss`, and the test passed.
**Why it bit.** A build cache keyed on the wrong inputs gives a stale bundle that looks
fresh. This is CLAUDE.md §5.4 again, caused by the build tool and not the service worker.
**How to apply it.** Any file the app bundles from outside its package goes into
`globalDependencies` or the task's `inputs`, in the same commit as the import. To
check, change the file, run the build, and look for `cache miss`.
+15
View File
@@ -43,3 +43,18 @@ firing has not been tested. Without the run, a review can only say "I believe".
**How to apply it.** For every guard a branch adds, apply the inverse change, run the
one suite that should catch it, record CAUGHT or MISSED, and restore the file with
`git checkout`. Commit first, so the restore is exact.
## Fill an empty slot for one run, to test the state it will have later
**What happened.** The Letter's e2e test branches: no link while `docs/LETTER.md` is
empty, and the page opens once it is written. Only the empty branch could run, because
the author has not written the letter. One run with a temporary sample letter took the
other branch. It found the stale-cache bug (`technical.md`), and then passed the
written-letter page, axe included, in a real browser. The scaffold was restored
afterwards.
**Why it bit.** A test written for a future state passes trivially until that state
arrives. Then it fails for the first time on the author's machine, with the author's words.
**How to apply it.** When a test branches on content that does not exist yet, fill the
content temporarily, run the suite, restore it, and record the run in the review.
+74
View File
@@ -0,0 +1,74 @@
# Review — `feature/letter-slot`
Adversarial self-review (CLAUDE.md §5.3). Analysis:
[`features/letter-slot.md`](../features/letter-slot.md). Reviewed 2026-11-01 on
Node 22.11.0, Windows 10. There is no PR: the only remote is Gitea, and this session
cannot open one there.
## Gates — counts, not exit codes
| Gate | Result |
|:--|:--|
| `pnpm lint` | exit 0 |
| `pnpm typecheck` | exit 0; `svelte-check` 0 errors **0 warnings** in ui and app (a bare `href="#"` warning was fixed) |
| `pnpm test` | **130 passed**: schema 15, content 47, engine 52, ui 16 (was 3) |
| `pnpm lint:copy` | **12 files** checked (was 9: `parse.ts`, `Letter.svelte`, `docs/LETTER.md`), 0 problems |
| `pnpm validate:library` | 0 entries; 13 of 13 fixtures rejected |
| `pnpm test:e2e` | **7 passed** (was 6), on the scaffold letter |
| `pnpm test:offline` | **1 passed** |
**Built, not deployed** (§5.4): there is no host. The change is **deliberately
invisible**: with the scaffold letter, the built page looks exactly as before. The
bundle is 8 precache entries, 42.74 KiB.
**The written-letter branch, run once.** `docs/LETTER.md` was given a temporary sample
letter (headings, a paragraph across lines, *emphasis*, an `https:` and a `tel:` link).
e2e: 7 passed, including the page opening from the link, axe with no violations, and
*Back*. Offline: 1 passed. The scaffold was then restored and both suites ran again
green. That run found finding 1.
## Test honesty — bugs put back
| Bug put back | Suite | Result |
|:--|:--|:--|
| `ALLOWED_HREF = /.*/` (any link scheme) | ui unit | CAUGHT: 2 failed |
| The letter link shown while the letter is empty | ui unit | CAUGHT: 2 failed |
| same | e2e | CAUGHT: `toHaveCount(0)` failed |
| The focus effect reads `heading` only after `if (moved)` | ui unit | CAUGHT: focus stayed on `<body>`. This was the first draft's real bug (finding 2). |
| *heal* in the body of `docs/LETTER.md` | `lint:copy` | CAUGHT: `docs/LETTER.md:36 'heal' (medical)` |
| `docs/LETTER.md` missing from turbo's cache key | e2e, written letter | CAUGHT, as the real finding 1 |
Not caught by any test: removing `docs/LETTER.md` from `lint:copy`'s file list. Only
the quoted file count (12) would show it. See finding 6.
## Findings
| # | Area | Finding | Resolution |
|:--|:--|:--|:--|
| 1 | **Correctness** | Turbo hashed only the app package, so after the letter changed, `test:e2e` printed `cache hit` and tested the **old bundle**. A deploy from a warm cache would ship the old letter. | **Fixed**: `docs/LETTER.md` is in `globalDependencies` (L8). Shown as `cache miss` after the change. Lesson: `technical.md`. |
| 2 | Correctness | The first focus effect returned before reading `heading`, so it never re-ran and focus never moved. | **Fixed** before review, caught by the Shell test. Lesson: `code.md`. |
| 3 | **Offline** | The letter opens offline, because it is bundled. A support line given as an `https:` link does **not** work offline, but a `tel:` link does. | **Deferred** to G0.27, with the advice that each support line has a phone number. |
| 4 | **Privacy** | An `https:` link in the letter takes the player to another site. Nothing leaves without their tap, the referrer is stripped (`no-referrer` on the page and `noreferrer` on the link), and it opens in a new tab. Which sites the letter links to is the author's choice. | **Accepted.** |
| 5 | Correctness | The parser has blind spots. A numbered list (`1. …`) without blank lines collapses into one paragraph, and `snake_case_word` makes *case* italic. | **Accepted.** The scaffold says which Markdown works, and anything else shows as text, never as markup. |
| 6 | Test honesty | No test proves `lint:copy` reads `docs/LETTER.md`. It was shown by the *heal* mutation, but deleting the path from `FILES` would pass silently. | **Accepted for now**: the review quotes the file count. Revisit if `lint:copy` grows a file list worth testing. |
| 7 | Correctness | *Back* leaves `#garden` in the address bar. A bookmark at `#garden` or any unknown hash opens the garden. | **Accepted**: harmless, and any hash but `#letter` is home by design. |
| 8 | **Soul** | Once the letter exists, the home view offers one link, *A Letter from the Gardener*. Looked for guilt, comparison, rejection and dependence: the page asks nothing, counts nothing, and is never required (GAMEPLAY §4). Found none. | — |
| 9 | Copyright | The scaffold's comments mention "the book". They are stripped before the page and skipped by `lint:copy`. Whether the letter's own words may name the book is **Q9**, for the author. | **Open**, Q9. |
Looked for and found none:
- **Reachability.** The letter is one-way, from the author to every player. There is
no input.
- **Injection.** No `{@html}` anywhere. Raw HTML and `<script>` stay text (tests), and
only `https:` and `tel:` become links (tests, plus a mutation). Svelte escapes
attribute values.
- **Correctness cases from §5.3.** Clock, DST, partial write and two tabs do not apply:
there is no state. A tab closed on `#letter` reopens on the letter (test: *opens
straight at #letter*).
## What was NOT verified
- **A screen reader.** axe passes on both views, and the focus move is unit-tested.
Nobody has listened to it.
- **Firefox, WebKit and a phone.** Desktop Chromium only.
- **The author's real letter.** Only a sample has rendered.
+2 -1
View File
@@ -467,7 +467,8 @@ No timestamp finer than a day, no precise location, no free text, no link to the
- **Svelte 5 runes, no state library.** A component that decides growth, taming or anything in the sky
is a layering violation and a review **blocker**.
- **Three taps to action, one preferred.** From a cold open, tending the rose is one tap.
- **Every string a player reads lives in `packages/ui/src/copy/`**, and passes `lint:copy`. The
- **Every string a player reads lives in `packages/ui/src/copy/`**, and passes `lint:copy` — except
the Letter, which is the author's Markdown in `docs/LETTER.md` and passes `lint:copy` too. The
interface language is plain English (Czech later). Latin is for the brand only.
- **Silence is a feature.** Sunset, the thanks visit and the end of a planet have moments with no
buttons at all. Do not fill them.
+11 -5
View File
@@ -21,19 +21,25 @@ Rewritten at the end of each session (CLAUDE.md §5.1).
code: [`.agents/reviews/docs-roadmap-gameplay.md`](.agents/reviews/docs-roadmap-gameplay.md).
The author answered Q1–Q7, and the answers are written into both docs and CLAUDE.md.
Merged to `main`.
- **The Letter slot:** on `feature/letter-slot`, not merged yet. `docs/LETTER.md`
holds slots as comments only. Once the author writes in it, a link to the letter
appears in the garden, and the page opens at `#letter`, offline too. Review:
[`.agents/reviews/feature-letter-slot.md`](.agents/reviews/feature-letter-slot.md).
**Phase 0 is not finished.** The roadmap's Phase 0 is more than the workspace. Its
gate needs 60 verified sentences (G0.18) and one illustration through the art
pipeline (G0.24). Also open: the Letter slot (G0.25) and a GitHub remote (G0.13).
pipeline (G0.24). Also open: a GitHub remote (G0.13). The Letter slot is built (G0.25).
The notification decision is made: in-app only on the web (G0.26).
**Waiting on the author.**
1. **Sentences:** an agent may propose public-domain candidates with their sources.
1. **The Letter:** the words in `docs/LETTER.md`, the verified support lines for the
door to real help (G0.27), and Q9 (may the letter name the book).
2. **Sentences:** an agent may propose public-domain candidates with their sources.
Only the author can mark one verified.
2. **`docs/ART.md` and `art/STYLE.md`**, which are needed before the art pipeline.
3. **A GitHub repository** for Pages, and whether it is public (G0.13, G0.23).
4. **Upgrading Node** to ≥ 22.13 on this machine (G0.20).
3. **`docs/ART.md` and `art/STYLE.md`**, which are needed before the art pipeline.
4. **A GitHub repository** for Pages, and whether it is public (G0.13, G0.23).
5. **Upgrading Node** to ≥ 22.13 on this machine (G0.20).
**How this machine works** (not in the code):
+3 -1
View File
@@ -1,5 +1,7 @@
<script lang="ts">
import { Shell } from '@rosea/ui';
// Bundled at build time, so the letter is precached and opens offline (letter-slot.md L1).
import letter from '../../../docs/LETTER.md?raw';
</script>
<Shell />
<Shell {letter} />
+34
View File
@@ -0,0 +1,34 @@
<!--
A Letter from the Gardener: the author's own words, signed by the author.
Agents scaffold this file and never write in it (CLAUDE.md preamble and §1).
How it reaches the player: the app bundles this file at build time and shows
it at #letter, offline included. While this file holds nothing but comments,
the player sees no way to the page.
Markdown that works: # and ## headings, paragraphs, lists with - or *,
*emphasis*, and links to https:// pages or tel: numbers. Anything else is
shown as plain text. `pnpm lint:copy` checks every word outside comments,
as it does for all player-facing text.
The slots below are what GAMEPLAY.md and CLAUDE.md say the letter carries.
Keep, reorder or delete them as you like: comments never reach the player.
-->
<!-- Slot: the one sentence of inspiration (GAMEPLAY §7). -->
<!-- Slot: the river of life and its whirlpools (GAMEPLAY §8, CLAUDE.md §1). -->
<!-- Slot: why the art looks as it does (GAMEPLAY §7). -->
<!-- Slot: what in Rosea was never in the book: berries and rose hips, the
lanterns, the paths, the real sunset, the shared sky, Amicitia (GAMEPLAY §7). -->
<!-- Slot: every feature and every principle, taught (CLAUDE.md §1). -->
<!-- Slot: how the game leads to Amicitia Domi (GAMEPLAY §5, §7). -->
<!-- Slot: the quiet door to real help: verified support lines, as links
(CLAUDE.md §5.6 rule 5, G0.27). Not advice, no clinical claim. -->
<!-- Slot: the signature. -->
+23
View File
@@ -2,6 +2,8 @@ import AxeBuilder from '@axe-core/playwright';
import { expect, test, type Page } from '@playwright/test';
import { PRODUCT_NAME } from '@rosea/schema';
import { en } from '@rosea/ui/copy';
import { parseLetter } from '@rosea/ui/letter';
import { readFileSync } from 'node:fs';
import { BASE, startStaticServer, type StaticServer } from './static-server.js';
let server: StaticServer;
@@ -104,3 +106,24 @@ test('the shell has no accessibility violations', async ({ page }) => {
const results = await new AxeBuilder({ page }).analyze();
expect(results.violations.map((v) => `${v.id}: ${v.help}`)).toEqual([]);
});
// Tests whichever state docs/LETTER.md is in: empty now, the author's words later.
test('the Letter: no way to it while empty, and it opens from the garden once written', async ({ page }) => {
const written = parseLetter(readFileSync(new URL('../docs/LETTER.md', import.meta.url), 'utf8')).length > 0;
await open(page);
const link = page.getByRole('link', { name: en.letter.title });
if (!written) {
await expect(link).toHaveCount(0);
await page.goto(server.url + '#letter');
await expect(page.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME);
return;
}
await link.click();
await expect(page.getByRole('heading', { level: 1 })).toHaveText(en.letter.title);
const results = await new AxeBuilder({ page }).analyze();
expect(results.violations.map((v) => `${v.id}: ${v.help}`)).toEqual([]);
await page.getByRole('link', { name: en.letter.back }).click();
await expect(page.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME);
});
+1
View File
@@ -14,6 +14,7 @@
"default": "./src/index.ts"
},
"./copy": "./src/copy/en.ts",
"./letter": "./src/letter/parse.ts",
"./tokens.css": "./src/tokens.css"
},
"scripts": {
+60 -4
View File
@@ -1,12 +1,55 @@
<script lang="ts">
import { PRODUCT_NAME } from '@rosea/schema';
import { en } from './copy/en.js';
import Letter from './letter/Letter.svelte';
import { parseLetter } from './letter/parse.js';
/** The author's Markdown from docs/LETTER.md. Empty means there is no way to the page. */
let { letter = '' }: { letter?: string } = $props();
const LETTER_HASH = '#letter';
// Any hash but the letter's is the garden. A bare '#' is not a valid link target.
const GARDEN_HASH = '#garden';
const blocks = $derived(parseLetter(letter));
let hash = $state(location.hash);
const view = $derived(hash === LETTER_HASH && blocks.length > 0 ? 'letter' : 'home');
let heading = $state<HTMLHeadingElement>();
// Focus follows the view only after the player moved, never on the first load.
let moved = false;
$effect(() => {
const onChange = (): void => {
moved = true;
hash = location.hash;
};
window.addEventListener('hashchange', onChange);
return () => window.removeEventListener('hashchange', onChange);
});
$effect(() => {
// Read `heading` first: an effect tracks only what it reads, and `moved` is not state.
const target = heading;
if (moved) target?.focus();
});
</script>
<main class="shell">
<h1>{PRODUCT_NAME}</h1>
<p>{en.shell.preparing}</p>
</main>
{#if view === 'letter'}
<main class="shell page">
<h1 bind:this={heading} tabindex="-1">{en.letter.title}</h1>
<Letter {blocks} />
<a href={GARDEN_HASH}>{en.letter.back}</a>
</main>
{:else}
<main class="shell">
<h1 bind:this={heading} tabindex="-1">{PRODUCT_NAME}</h1>
<p>{en.shell.preparing}</p>
{#if blocks.length > 0}
<a href={LETTER_HASH}>{en.letter.title}</a>
{/if}
</main>
{/if}
<style>
.shell {
@@ -18,6 +61,11 @@
text-align: center;
}
.page {
place-content: start center;
text-align: start;
}
h1 {
margin: 0;
font-family: var(--font-display);
@@ -27,8 +75,16 @@
color: var(--rose);
}
h1:focus {
outline: none;
}
p {
margin: 0;
color: var(--ink-soft);
}
a {
color: var(--rose);
}
</style>
+5
View File
@@ -9,6 +9,11 @@ export const en = {
shell: {
/** The one line on the Phase 0 page. True, calm, and asks nothing. */
preparing: 'The garden is being prepared.'
},
letter: {
/** The help section's name (ROADMAP §1). The letter itself is the author's, in docs/LETTER.md. */
title: 'A Letter from the Gardener',
back: 'Back to the garden'
}
} as const;
+1
View File
@@ -1,2 +1,3 @@
export { default as Shell } from './Shell.svelte';
export { en, type Copy } from './copy/en.js';
export { parseLetter, type Inline, type LetterBlock } from './letter/parse.js';
+61
View File
@@ -0,0 +1,61 @@
<script lang="ts">
import type { Inline, LetterBlock } from './parse.js';
let { blocks }: { blocks: readonly LetterBlock[] } = $props();
</script>
{#snippet inlines(parts: readonly Inline[])}
{#each parts as part, i (i)}
{#if part.kind === 'link' && part.href.startsWith('tel:')}
<a href={part.href}>{part.text}</a>
{:else if part.kind === 'link'}
<a href={part.href} target="_blank" rel="noopener noreferrer">{part.text}</a>
{:else if part.kind === 'em'}
<em>{part.text}</em>
{:else}
{part.text}
{/if}
{/each}
{/snippet}
<article class="letter">
{#each blocks as block, i (i)}
{#if block.kind === 'heading' && block.level === 2}
<h2>{@render inlines(block.inlines)}</h2>
{:else if block.kind === 'heading'}
<h3>{@render inlines(block.inlines)}</h3>
{:else if block.kind === 'paragraph'}
<p>{@render inlines(block.inlines)}</p>
{:else}
<ul>
{#each block.items as item, j (j)}
<li>{@render inlines(item)}</li>
{/each}
</ul>
{/if}
{/each}
</article>
<style>
.letter {
max-width: 38rem;
line-height: 1.65;
}
h2,
h3 {
font-family: var(--font-display);
font-weight: 400;
color: var(--rose);
margin: var(--space-4) 0 var(--space-2);
}
p,
ul {
margin: 0 0 var(--space-3);
}
a {
color: var(--rose);
}
</style>
+85
View File
@@ -0,0 +1,85 @@
/**
* The Letter from the Gardener, from the author's Markdown to blocks the page
* renders (.agents/features/letter-slot.md L3, L4).
*
* A deliberately small subset: headings, paragraphs, lists, *emphasis* and
* links. Anything else is shown as the text it is. Nothing here builds HTML,
* so nothing in the file can inject markup or script.
*/
export type Inline =
| { readonly kind: 'text'; readonly text: string }
| { readonly kind: 'em'; readonly text: string }
| { readonly kind: 'link'; readonly text: string; readonly href: string };
export type LetterBlock =
| { readonly kind: 'heading'; readonly level: 2 | 3; readonly inlines: readonly Inline[] }
| { readonly kind: 'paragraph'; readonly inlines: readonly Inline[] }
| { readonly kind: 'list'; readonly items: readonly (readonly Inline[])[] };
/** The support door needs web and phone links, and nothing else does. */
const ALLOWED_HREF = /^(?:https:\/\/\S+|tel:\+?[\d ()-]+)$/i;
// A link target may hold one level of brackets, as in tel:+420 (2) 123.
const INLINE = /\[([^\]\n]+)\]\(((?:[^()\n]|\([^()\n]*\))+)\)|\*([^*\n]+)\*|_([^_\n]+)_/g;
function inlines(source: string): Inline[] {
const parts: Inline[] = [];
const text = (t: string): void => {
if (t === '') return;
const last = parts[parts.length - 1];
if (last?.kind === 'text') parts[parts.length - 1] = { kind: 'text', text: last.text + t };
else parts.push({ kind: 'text', text: t });
};
let at = 0;
for (const m of source.matchAll(INLINE)) {
text(source.slice(at, m.index));
const [, label, href, star, underscore] = m;
if (label !== undefined && href !== undefined) {
if (ALLOWED_HREF.test(href.trim())) parts.push({ kind: 'link', text: label, href: href.trim() });
else text(label);
} else {
parts.push({ kind: 'em', text: star ?? underscore ?? '' });
}
at = m.index + m[0].length;
}
text(source.slice(at));
return parts;
}
export function parseLetter(markdown: string): LetterBlock[] {
// Comments are the author's notes and the scaffold's slots, never the letter.
const lines = markdown.replace(/\r\n?/g, '\n').replace(/<!--[\s\S]*?-->/g, '').split('\n');
const blocks: LetterBlock[] = [];
let paragraph: string[] = [];
let list: Inline[][] = [];
const flush = (): void => {
if (paragraph.length > 0) blocks.push({ kind: 'paragraph', inlines: inlines(paragraph.join(' ')) });
if (list.length > 0) blocks.push({ kind: 'list', items: list });
paragraph = [];
list = [];
};
for (const raw of lines) {
const line = raw.trim();
const heading = /^(#{1,6})\s+(.+)$/.exec(line);
const item = /^[-*]\s+(.+)$/.exec(line);
if (line === '') {
flush();
} else if (heading !== null) {
flush();
blocks.push({ kind: 'heading', level: heading[1] === '#' ? 2 : 3, inlines: inlines(heading[2] ?? '') });
} else if (item !== null) {
if (paragraph.length > 0) flush();
list.push(inlines(item[1] ?? ''));
} else {
if (list.length > 0) flush();
paragraph.push(line);
}
}
flush();
return blocks;
}
+61 -2
View File
@@ -1,10 +1,23 @@
import { PRODUCT_NAME } from '@rosea/schema';
import { cleanup, render, screen } from '@testing-library/svelte';
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/svelte';
import { afterEach, describe, expect, it } from 'vitest';
import Shell from '../src/Shell.svelte';
import { en } from '../src/copy/en.js';
afterEach(cleanup);
afterEach(() => {
cleanup();
window.location.hash = '';
});
const LETTER = [
'# Why',
'',
'A line.',
'',
'[Read](https://example.org) or [call](tel:+420123) or [not](javascript:alert(1)).'
].join('\n');
const h1 = (): HTMLElement => screen.getByRole('heading', { level: 1 });
describe('Shell', () => {
it('names the product in the page heading, from the schema constant', () => {
@@ -24,3 +37,49 @@ describe('Shell', () => {
expect(screen.getByRole('main')).toBeTruthy();
});
});
describe('Shell and the Letter', () => {
it('with an empty letter offers no way to it, and #letter shows the garden', () => {
window.location.hash = '#letter';
render(Shell, { letter: '<!-- Slot: the signature. -->\n' });
expect(h1().textContent).toBe(PRODUCT_NAME);
expect(screen.queryAllByRole('link')).toEqual([]);
});
it('with a letter, a link opens it, Back returns, and focus follows each heading', async () => {
render(Shell, { letter: LETTER });
expect(document.activeElement, 'nothing is focused on first load').toBe(document.body);
await fireEvent.click(screen.getByRole('link', { name: en.letter.title }));
await waitFor(() => expect(h1().textContent).toBe(en.letter.title));
await waitFor(() => expect(document.activeElement).toBe(h1()));
expect(screen.getByRole('heading', { level: 2 }).textContent).toBe('Why');
expect(screen.getByRole('main')).toBeTruthy();
await fireEvent.click(screen.getByRole('link', { name: en.letter.back }));
await waitFor(() => expect(h1().textContent).toBe(PRODUCT_NAME));
await waitFor(() => expect(document.activeElement).toBe(h1()));
});
it('opens straight at #letter, as from a bookmark', () => {
window.location.hash = '#letter';
render(Shell, { letter: LETTER });
expect(h1().textContent).toBe(en.letter.title);
});
it('renders https links in a new tab with no referrer, tel links in place, and nothing else as a link', () => {
window.location.hash = '#letter';
render(Shell, { letter: LETTER });
const read = screen.getByRole('link', { name: 'Read' });
expect(read.getAttribute('href')).toBe('https://example.org');
expect(read.getAttribute('target')).toBe('_blank');
expect(read.getAttribute('rel')).toBe('noopener noreferrer');
const call = screen.getByRole('link', { name: 'call' });
expect(call.getAttribute('href')).toBe('tel:+420123');
expect(call.getAttribute('target')).toBeNull();
expect(screen.queryByRole('link', { name: 'not' })).toBeNull();
expect(screen.getByText(/or not\./)).toBeTruthy();
});
});
+78
View File
@@ -0,0 +1,78 @@
import { describe, expect, it } from 'vitest';
import { parseLetter } from '../src/letter/parse.js';
describe('parseLetter', () => {
it('reads a file of only comments as an empty letter', () => {
const scaffold = '<!--\n A note for the author.\n-->\n\n<!-- Slot: one -->\n<!-- Slot: two -->\n';
expect(parseLetter(scaffold)).toEqual([]);
expect(parseLetter('')).toEqual([]);
expect(parseLetter(' \n\n \r\n')).toEqual([]);
});
it('reads headings, paragraphs joined across lines, and lists', () => {
const md = '# Why\n\nOne line\nand the next.\n\n## How\n- first\n* second\n\nLast.';
expect(parseLetter(md)).toEqual([
{ kind: 'heading', level: 2, inlines: [{ kind: 'text', text: 'Why' }] },
{ kind: 'paragraph', inlines: [{ kind: 'text', text: 'One line and the next.' }] },
{ kind: 'heading', level: 3, inlines: [{ kind: 'text', text: 'How' }] },
{ kind: 'list', items: [[{ kind: 'text', text: 'first' }], [{ kind: 'text', text: 'second' }]] },
{ kind: 'paragraph', inlines: [{ kind: 'text', text: 'Last.' }] }
]);
});
it('maps every heading below the first level to h3', () => {
expect(parseLetter('### Deep\n\n###### Deeper')).toEqual([
{ kind: 'heading', level: 3, inlines: [{ kind: 'text', text: 'Deep' }] },
{ kind: 'heading', level: 3, inlines: [{ kind: 'text', text: 'Deeper' }] }
]);
});
it('reads CRLF files the same as LF', () => {
expect(parseLetter('# A\r\n\r\nB\r\nC')).toEqual(parseLetter('# A\n\nB\nC'));
});
it('reads emphasis and links inside a paragraph', () => {
expect(parseLetter('A *quiet* door: [call](tel:+420 123 456) or [read](https://example.org/x).')).toEqual([
{
kind: 'paragraph',
inlines: [
{ kind: 'text', text: 'A ' },
{ kind: 'em', text: 'quiet' },
{ kind: 'text', text: ' door: ' },
{ kind: 'link', text: 'call', href: 'tel:+420 123 456' },
{ kind: 'text', text: ' or ' },
{ kind: 'link', text: 'read', href: 'https://example.org/x' },
{ kind: 'text', text: '.' }
]
}
]);
});
it('reads a phone number with brackets as one link', () => {
expect(parseLetter('[call](tel:+420 (2) 123)')).toEqual([
{ kind: 'paragraph', inlines: [{ kind: 'link', text: 'call', href: 'tel:+420 (2) 123' }] }
]);
});
it('keeps only the label of a link whose scheme is not https: or tel:', () => {
for (const href of ['javascript:alert(1)', 'data:text/html,x', 'http://example.org', '/relative', 'JavaScript:x']) {
expect(parseLetter(`[label](${href})`), href).toEqual([
{ kind: 'paragraph', inlines: [{ kind: 'text', text: 'label' }] }
]);
}
});
it('never produces markup: raw HTML stays text', () => {
const blocks = parseLetter('<script>alert(1)</script>\n\n<b onclick="x">bold</b>');
expect(blocks).toEqual([
{ kind: 'paragraph', inlines: [{ kind: 'text', text: '<script>alert(1)</script>' }] },
{ kind: 'paragraph', inlines: [{ kind: 'text', text: '<b onclick="x">bold</b>' }] }
]);
});
it('drops a comment in the middle of a paragraph and keeps the words around it', () => {
expect(parseLetter('Before <!-- a note --> after.')).toEqual([
{ kind: 'paragraph', inlines: [{ kind: 'text', text: 'Before after.' }] }
]);
});
});
+4 -3
View File
@@ -4,7 +4,8 @@
* @rosea/content (copy-lint.ts, forbidden.ts) and are tested there.
*
* Not scanned: .agents/ and docs/, where the forbidden words may appear because
* they are being discussed (§5.6 rule 4).
* they are being discussed (§5.6 rule 4). The one exception is docs/LETTER.md:
* it lives with the docs but a player reads it (letter-slot.md L6).
*/
import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
import { extname, join, relative } from 'node:path';
@@ -21,8 +22,8 @@ const TARGETS: readonly { dir: string; ext: readonly string[] }[] = [
{ dir: 'store', ext: ['.md', '.txt', '.json'] }
];
/** Single files: the page shell and the config that builds the web manifest. */
const FILES: readonly string[] = ['apps/rosea/index.html', 'apps/rosea/vite.config.ts'];
/** Single files: the page shell, the config that builds the web manifest, and the Letter. */
const FILES: readonly string[] = ['apps/rosea/index.html', 'apps/rosea/vite.config.ts', 'docs/LETTER.md'];
function walk(dir: string, ext: readonly string[]): string[] {
if (!existsSync(dir)) return [];
+3 -1
View File
@@ -1,7 +1,9 @@
{
"$schema": "https://turbo.build/schema.json",
"ui": "stream",
"globalDependencies": ["content/**"],
// docs/LETTER.md is bundled into the app (letter-slot.md L1). Without it here a
// changed letter replays the cached build and never reaches the player.
"globalDependencies": ["content/**", "docs/LETTER.md"],
"tasks": {
"build": {
"dependsOn": ["^build"],