[ui] Rose: The rose with her face and words, water by holding, care when needed, her numbers on request

This commit is contained in:
2026-11-02 00:20:59 +01:00
parent 2b5cd719c1
commit 6a3ca84aaa
7 changed files with 484 additions and 1 deletions
+11 -1
View File
@@ -4,18 +4,23 @@
import { en } from './copy/en.js';
import Letter from './letter/Letter.svelte';
import { parseLetter } from './letter/parse.js';
import Rose from './rose/Rose.svelte';
import type { RoseWiring } from './rose/types.js';
import SunsetLine from './sunset/SunsetLine.svelte';
import SunsetPlace from './sunset/SunsetPlace.svelte';
import type { SunsetChoice, SunsetWiring } from './sunset/types.js';
let {
letter = '',
sunset
sunset,
rose
}: {
/** The author's Markdown from docs/LETTER.md. Empty means there is no way to the page. */
letter?: string;
/** Where the sunset is, and how to keep it. Absent, the garden shows no sunset at all. */
sunset?: SunsetWiring;
/** The rose and her care log. Absent, the garden has no rose. */
rose?: RoseWiring;
} = $props();
// --- The sunset (sunset-place.md) ---------------------------------------
@@ -28,6 +33,8 @@
let sunLine = $state<HTMLElement>();
const place = $derived(choice?.kind === 'town' ? choice.town : (sunset?.guess ?? null));
// One zone for the sunset and the rose's days: the chosen town's, else the device's (rose.md R8).
const roseZone = $derived(choice?.kind === 'town' ? choice.town.timeZone : (rose?.deviceZone ?? 'UTC'));
$effect(() => {
const wiring = sunset;
@@ -105,6 +112,9 @@
<main class="shell">
<h1 bind:this={heading} tabindex="-1">{PRODUCT_NAME}</h1>
<p>{en.shell.preparing}</p>
{#if rose}
<Rose wiring={rose} timeZone={roseZone} />
{/if}
{#if sunset && (status === 'asking' || changing)}
<SunsetPlace
guess={sunset.guess}
+41
View File
@@ -10,6 +10,47 @@ export const en = {
/** The one line on the Phase 0 page. True, calm, and asks nothing. */
preparing: 'The garden is being prepared.'
},
rose: {
care: 'Care for her',
water: 'Water',
/** Watering is by feel (GAMEPLAY §1): hold, and let go when the leaves lift. */
waterHint: 'Hold to pour. Let go when her leaves lift.',
leavesLift: 'Her leaves lift.',
plenty: 'That is plenty.',
shade: 'Shade her',
weed: 'Pull the weeds',
petals: 'Gather the petals',
numbers: 'Her numbers',
waterLevel: 'Water',
daysOfCare: 'Days of care',
warmth: 'Warmth',
trend: 'How she is',
/** Never counts absence: no "0 of 7" (rose.md R7). */
warmthDays: (n: number): string => (n === 0 ? 'resting' : n === 1 ? '1 day this week' : `${n} days this week`),
trendWords: { growing: 'growing', steady: 'steady', waiting: 'waiting' },
stageWords: { bud: 'a bud', opening: 'opening', 'half-bloom': 'in half bloom', 'full-bloom': 'in full bloom' },
moodWords: {
content: '',
blushing: ', blushing',
'too-full': ', full of water',
windblown: ', in the wind',
waiting: ', turned a little away, waiting',
thirsty: ', thirsty'
},
picture: (stage: string, mood: string): string => `The rose, ${stage}${mood}.`,
/** What she says. One line at a time; nothing at all when she needs nothing. Never blame. */
says: {
back: 'There you are.',
thanks: 'Thank you.',
wind: 'The wind is pulling at me. Could you shade me?',
thirsty: 'A little water, please. Pour slowly, and stop when my leaves lift.',
dry: 'My soil is getting dry.',
weeds: 'Some weeds came up in the night.',
petals: 'A few of my petals have fallen. Would you gather them?',
tooFull: 'That was a lot of water. I will be fine by tomorrow.'
},
notKept: 'This device could not keep today’s care, so it lasts only until the garden closes.'
},
sunset: {
/** ROADMAP Phase 1, word for word. */
question: 'Where do you want your sunset?',
+1
View File
@@ -2,3 +2,4 @@ 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';
export type { SunsetChoice, SunsetWiring } from './sunset/types.js';
export type { RoseWiring } from './rose/types.js';
+275
View File
@@ -0,0 +1,275 @@
<script lang="ts">
import { careEvent, pour, roseAt, ROSE, type Mood, type RoseNow, type Stage } from '@rosea/engine';
import type { CareEvent } from '@rosea/schema';
import { en } from '../copy/en.js';
import type { RoseWiring } from './types.js';
// The art board's stand-ins until real art is accepted (rose.md R10, docs/ART.md).
import bud from '../../../../art/placeholders/rose-bud.svg?url';
import opening from '../../../../art/placeholders/rose-opening.svg?url';
import halfBloom from '../../../../art/placeholders/rose-half-bloom.svg?url';
import fullBloom from '../../../../art/placeholders/rose-full-bloom.svg?url';
import thirsty from '../../../../art/placeholders/rose-thirsty.svg?url';
import overwatered from '../../../../art/placeholders/rose-overwatered.svg?url';
import windblown from '../../../../art/placeholders/rose-windblown.svg?url';
import blushing from '../../../../art/placeholders/rose-blushing.svg?url';
import waiting from '../../../../art/placeholders/rose-waiting.svg?url';
/**
* The rose. Everything she is comes from the engine's replay of her care log
* (rose.md); this renders it and turns the player's hands into care events.
*/
let { wiring, timeZone }: { wiring: RoseWiring; timeZone: string } = $props();
const STAGE_PICTURE: Record<Stage, string> = { bud, opening, 'half-bloom': halfBloom, 'full-bloom': fullBloom };
const MOOD_PICTURE: Record<Mood, string> = { content: fullBloom, thirsty, 'too-full': overwatered, windblown, blushing, waiting };
let seed = $state<string | null>(null);
let events = $state.raw<readonly CareEvent[]>([]);
let now = $state(0);
let kept = $state(true);
let showNumbers = $state(false);
$effect(() => {
const w = wiring;
now = w.now();
Promise.all([w.identity(), w.loadCare()]).then(
([id, log]) => {
seed = id.publicKey;
events = log;
if (!id.kept) kept = false;
},
(error: unknown) => {
console.error('rose: could not read her care log', error);
kept = false;
}
);
// Wind comes and goes, and a blush fades: look again now and then.
const timer = setInterval(() => (now = w.now()), 30_000);
return () => clearInterval(timer);
});
const rose = $derived<RoseNow | null>(seed === null ? null : roseAt(events, seed, now, timeZone));
function care(act: CareEvent['act'], amount?: number): void {
if (seed === null) return;
now = wiring.now();
const event = careEvent({ now, timeZone, from: seed, to: seed, act, clientVersion: wiring.clientVersion, ...(amount === undefined ? {} : { amount }) });
events = [...events, event];
wiring.appendCare(event).catch((error: unknown) => {
console.error('rose: the device could not keep this care', error);
kept = false;
});
}
// --- Water by feel: hold to pour (GAMEPLAY §1) ---------------------------
/** A full can in this long, held. */
const FULL_CAN_MS = 3000;
const TICK_MS = 50;
let amount = $state(0);
let pouring = $state(false);
let pourTimer: ReturnType<typeof setInterval> | undefined;
const can = $derived(rose ? pour(rose.water, amount) : null);
function startPour(): void {
if (pouring || rose === null) return;
pouring = true;
amount = 0;
pourTimer = setInterval(() => (amount = Math.min(1, amount + TICK_MS / FULL_CAN_MS)), TICK_MS);
}
function stopPour(): void {
if (!pouring) return;
clearInterval(pourTimer);
pouring = false;
if (amount > 0.01) care('water', amount);
amount = 0;
}
$effect(() => () => clearInterval(pourTimer));
const isPourKey = (e: KeyboardEvent): boolean => e.key === ' ' || e.key === 'Enter';
// --- What she says: one line, or nothing --------------------------------
const says = $derived.by(() => {
if (!rose) return '';
const s = en.rose.says;
if (rose.mood === 'blushing') return s.thanks;
if (rose.mood === 'too-full') return s.tooFull;
const need = rose.needs.wind ? s.wind
: rose.water < ROSE.thirsty ? s.thirsty
: rose.needs.water ? s.dry
: rose.needs.weeds ? s.weeds
: rose.needs.petals ? s.petals
: '';
return [rose.drift > 0 ? s.back : '', need].filter(Boolean).join(' ');
});
const picture = $derived(rose ? (rose.stage === 'full-bloom' ? MOOD_PICTURE[rose.mood] : STAGE_PICTURE[rose.stage]) : bud);
const alt = $derived(rose ? en.rose.picture(en.rose.stageWords[rose.stage], en.rose.moodWords[rose.mood]) : '');
const percent = (x: number): string => `${Math.round(Math.max(0, Math.min(1, x)) * 100)} %`;
</script>
{#if rose}
<section class="rose">
<figure>
<img src={picture} {alt} width="120" height="320" class:turned={rose.drift > 0} />
{#if says}
<figcaption class="bubble" aria-live="polite">{says}</figcaption>
{/if}
</figure>
<div class="care" role="group" aria-label={en.rose.care}>
<button
type="button"
class="water"
class:pouring
aria-describedby="rose-water-hint"
onpointerdown={(e) => {
e.preventDefault();
(e.currentTarget as HTMLElement).setPointerCapture?.(e.pointerId);
startPour();
}}
onpointerup={stopPour}
onpointercancel={stopPour}
onkeydown={(e) => {
if (!isPourKey(e)) return;
e.preventDefault();
if (!e.repeat) startPour();
}}
onkeyup={(e) => {
if (isPourKey(e)) stopPour();
}}
onblur={stopPour}
>{en.rose.water}</button>
{#if rose.needs.wind}
<button type="button" onclick={() => care('shade')}>{en.rose.shade}</button>
{/if}
{#if rose.needs.weeds}
<button type="button" onclick={() => care('weed')}>{en.rose.weed}</button>
{/if}
{#if rose.needs.petals}
<button type="button" onclick={() => care('petals')}>{en.rose.petals}</button>
{/if}
</div>
<p id="rose-water-hint" class="hint">{en.rose.waterHint}</p>
{#if pouring && can}
<div class="can">
<meter min="0" max="1.2" low={ROSE.enough} high={ROSE.tooFull} optimum="0.7" value={Math.min(1.2, can.after)} aria-label={en.rose.waterLevel}></meter>
</div>
{/if}
<p class="said" role="status" aria-live="assertive">{pouring && can ? (can.tooFull ? en.rose.plenty : can.leavesLift ? en.rose.leavesLift : '') : ''}</p>
{#if !kept}
<p class="hint">{en.rose.notKept}</p>
{/if}
<button type="button" class="quiet" aria-expanded={showNumbers} aria-controls="rose-numbers" onclick={() => (showNumbers = !showNumbers)}>{en.rose.numbers}</button>
{#if showNumbers}
<dl id="rose-numbers" class="numbers">
<dt>{en.rose.waterLevel}</dt><dd>{percent(rose.water)}</dd>
<dt>{en.rose.daysOfCare}</dt><dd>{rose.daysOfCare}</dd>
<dt>{en.rose.warmth}</dt><dd>{en.rose.warmthDays(rose.warmth)}</dd>
<dt>{en.rose.trend}</dt><dd>{en.rose.trendWords[rose.trend]}</dd>
</dl>
{/if}
</section>
{/if}
<style>
.rose {
display: grid;
justify-items: center;
gap: var(--space-2);
}
figure {
margin: 0;
display: grid;
justify-items: center;
gap: var(--space-2);
}
img {
height: 13rem;
width: auto;
transition: transform 0.6s ease;
}
/* Drift is drawn as waiting: turned a little away, never hurt (CLAUDE.md §8). */
img.turned {
transform: rotate(-4deg) scaleX(-1);
}
.bubble {
max-width: 22rem;
padding: var(--space-2) var(--space-3);
border-radius: 1rem;
background: color-mix(in srgb, var(--rose) 12%, var(--paper));
}
.care {
display: flex;
flex-wrap: wrap;
justify-content: center;
gap: var(--space-2);
}
.care button {
font: inherit;
padding: var(--space-2) var(--space-3);
border-radius: 999px;
border: 1px solid var(--rose);
background: var(--paper);
color: var(--ink);
cursor: pointer;
touch-action: none;
user-select: none;
}
.care button.pouring {
background: color-mix(in srgb, var(--rose) 18%, var(--paper));
}
.hint,
.said {
margin: 0;
color: var(--ink-soft);
font-size: 0.9rem;
}
.said:empty {
display: none;
}
meter {
width: 12rem;
}
.quiet {
font: inherit;
background: none;
border: none;
color: var(--rose);
text-decoration: underline;
cursor: pointer;
}
.numbers {
display: grid;
grid-template-columns: auto auto;
gap: var(--space-1) var(--space-3);
margin: 0;
}
dt {
color: var(--ink-soft);
}
dd {
margin: 0;
}
button:focus-visible {
outline: 2px solid var(--rose);
outline-offset: 2px;
}
</style>
+17
View File
@@ -0,0 +1,17 @@
import type { CareEvent } from '@rosea/schema';
/**
* What the rose needs from the app: her care log, her key, and the clock. The app
* provides it; ui imports neither storage nor identity (CLAUDE.md §2).
*/
export interface RoseWiring {
/** The player's public key, which names the rose. `kept` is false if the device could not keep it. */
readonly identity: () => Promise<{ readonly publicKey: string; readonly kept: boolean }>;
readonly loadCare: () => Promise<CareEvent[]>;
readonly appendCare: (event: CareEvent) => Promise<void>;
readonly clientVersion: string;
/** The device's own zone: the rose's day when no sunset town is chosen (rose.md R8). */
readonly deviceZone: string;
/** The clock. A parameter, so tests and the e2e suite can fix it. */
readonly now: () => number;
}
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />
+138
View File
@@ -0,0 +1,138 @@
import { careEvent, localDay, weedsOn } from '@rosea/engine';
import type { CareEvent } from '@rosea/schema';
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/svelte';
import { tick } from 'svelte';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { en } from '../src/copy/en.js';
import Rose from '../src/rose/Rose.svelte';
import type { RoseWiring } from '../src/rose/types.js';
const ZONE = 'Europe/Prague';
const ME = 'M'.repeat(87);
/** 08:00 in Prague: before any wind can start, so the wind button never surprises a test. */
const MORNING = Date.parse('2026-03-01T08:00:00+01:00');
const DAY = 86_400_000;
function wiring(over: Partial<RoseWiring> & { log?: CareEvent[]; at?: number } = {}): RoseWiring & { appended: CareEvent[] } {
const appended: CareEvent[] = [];
const at = over.at ?? MORNING;
return {
identity: async () => ({ publicKey: ME, kept: true }),
loadCare: async () => over.log ?? [],
appendCare: async (e) => {
appended.push(e);
},
clientVersion: '0.1.0',
deviceZone: ZONE,
now: () => at,
...over,
appended
};
}
const water = (now: number, amount: number): CareEvent => careEvent({ now, timeZone: ZONE, from: ME, to: ME, act: 'water', amount, clientVersion: '0.1.0' });
/** Holds the Water button for `ms`, with the pour's own timer under control. */
async function hold(ms: number, how: 'pointer' | 'keyboard' = 'pointer'): Promise<void> {
const button = screen.getByRole('button', { name: en.rose.water });
vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] });
try {
if (how === 'pointer') await fireEvent.pointerDown(button, { pointerId: 1 });
else await fireEvent.keyDown(button, { key: ' ' });
vi.advanceTimersByTime(ms);
await tick();
} finally {
vi.useRealTimers();
}
}
const release = async (how: 'pointer' | 'keyboard' = 'pointer'): Promise<void> => {
const button = screen.getByRole('button', { name: en.rose.water });
if (how === 'pointer') await fireEvent.pointerUp(button, { pointerId: 1 });
else await fireEvent.keyUp(button, { key: ' ' });
};
afterEach(() => {
cleanup();
vi.useRealTimers();
vi.restoreAllMocks();
});
describe('the rose', () => {
it('a new rose is a bud whose soil is getting dry, and says so', async () => {
render(Rose, { wiring: wiring(), timeZone: ZONE });
expect(await screen.findByRole('img', { name: 'The rose, a bud.' })).toBeTruthy();
expect(screen.getByText(en.rose.says.dry)).toBeTruthy();
});
it('hold Water: the leaves lift while pouring; let go and it is one act of care, and she thanks you', async () => {
const w = wiring();
render(Rose, { wiring: w, timeZone: ZONE });
await screen.findByRole('img');
await hold(1500); // half a can
expect(screen.getByRole('status').textContent).toBe(en.rose.leavesLift);
await release();
expect(w.appended).toHaveLength(1);
expect(w.appended[0]).toMatchObject({ act: 'water', amount: 0.5, localDay: '2026-03-01', from: ME, to: ME });
expect(await screen.findByText(en.rose.says.thanks)).toBeTruthy();
await fireEvent.click(screen.getByRole('button', { name: en.rose.numbers }));
const numbers = document.getElementById('rose-numbers');
expect(numbers?.textContent).toContain(`${en.rose.daysOfCare}1`);
expect(numbers?.textContent).toContain(en.rose.warmthDays(1));
});
it('pouring too long says that is plenty', async () => {
render(Rose, { wiring: wiring({ log: [water(MORNING - 60_000, 0.5)] }), timeZone: ZONE });
await screen.findByRole('img');
await hold(3000);
expect(screen.getByRole('status').textContent).toBe(en.rose.plenty);
});
it('pours with the keyboard too: hold Space, let go', async () => {
const w = wiring();
render(Rose, { wiring: w, timeZone: ZONE });
await screen.findByRole('img');
await hold(1200, 'keyboard');
await release('keyboard');
expect(w.appended[0]).toMatchObject({ act: 'water', amount: 0.4 });
});
it('Pull the weeds shows only on a day with weeds, and goes once they are pulled', async () => {
let day = MORNING;
while (!weedsOn(ME, localDay(day, ZONE))) day += DAY;
const w = wiring({ at: day });
render(Rose, { wiring: w, timeZone: ZONE });
await fireEvent.click(await screen.findByRole('button', { name: en.rose.weed }));
expect(w.appended[0]?.act).toBe('weed');
await waitFor(() => expect(screen.queryByRole('button', { name: en.rose.weed })).toBeNull());
let clear = MORNING;
while (weedsOn(ME, localDay(clear, ZONE))) clear += DAY;
cleanup();
render(Rose, { wiring: wiring({ at: clear }), timeZone: ZONE });
await screen.findByRole('img');
expect(screen.queryByRole('button', { name: en.rose.weed })).toBeNull();
});
it('after weeks away she is turned a little away and waiting, and greets, never blames', async () => {
const log = [water(MORNING - 30 * DAY, 0.5)];
render(Rose, { wiring: wiring({ log }), timeZone: ZONE });
const img = await screen.findByRole('img', { name: /waiting/ });
expect(img.className).toContain('turned');
expect(screen.getByText(new RegExp(`^${en.rose.says.back}`))).toBeTruthy();
await fireEvent.click(screen.getByRole('button', { name: en.rose.numbers }));
expect(document.getElementById('rose-numbers')?.textContent).toContain(en.rose.warmthDays(0));
expect(document.getElementById('rose-numbers')?.textContent).toContain(`${en.rose.daysOfCare}1`);
});
it('if the device cannot keep the care, the care still counts now, and she says it lasts only until closing', async () => {
const error = vi.spyOn(console, 'error').mockImplementation(() => undefined);
const w = wiring({ appendCare: () => Promise.reject(new Error('IndexedDB blocked')) });
render(Rose, { wiring: w, timeZone: ZONE });
await screen.findByRole('img');
await hold(1500);
await release();
expect(await screen.findByText(en.rose.says.thanks)).toBeTruthy();
expect(await screen.findByText(en.rose.notKept)).toBeTruthy();
expect(error).toHaveBeenCalled();
});
});