[ui] SunsetPlace: Ask where the sunset is, and say when tonight's sunset is

This commit is contained in:
2026-11-02 00:01:51 +01:00
parent 3ed91eea7b
commit 77a865f625
8 changed files with 526 additions and 2 deletions
+1
View File
@@ -23,6 +23,7 @@
"test": "vitest run --reporter=verbose"
},
"dependencies": {
"@rosea/engine": "workspace:*",
"@rosea/schema": "workspace:*"
},
"peerDependencies": {
+114 -2
View File
@@ -1,11 +1,71 @@
<script lang="ts">
import { PRODUCT_NAME } from '@rosea/schema';
import { tick } from 'svelte';
import { en } from './copy/en.js';
import Letter from './letter/Letter.svelte';
import { parseLetter } from './letter/parse.js';
import SunsetLine from './sunset/SunsetLine.svelte';
import SunsetPlace from './sunset/SunsetPlace.svelte';
import type { SunsetChoice, SunsetWiring } from './sunset/types.js';
/** The author's Markdown from docs/LETTER.md. Empty means there is no way to the page. */
let { letter = '' }: { letter?: string } = $props();
let {
letter = '',
sunset
}: {
/** 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;
} = $props();
// --- The sunset (sunset-place.md) ---------------------------------------
let status = $state<'loading' | 'asking' | 'set'>('loading');
let choice = $state<SunsetChoice | null>(null);
let changing = $state(false);
/** False once the device refused to keep the answer: then the garden says it will ask again. */
let kept = $state(true);
let now = $state(0);
let sunLine = $state<HTMLElement>();
const place = $derived(choice?.kind === 'town' ? choice.town : (sunset?.guess ?? null));
$effect(() => {
const wiring = sunset;
if (!wiring) return;
now = wiring.now();
wiring.load().then(
(saved) => {
choice = saved;
status = saved ? 'set' : 'asking';
},
(error: unknown) => {
console.error('sunset: the device could not read the saved town; asking again', error);
kept = false;
status = 'asking';
}
);
// The line speaks of tomorrow once tonight's sunset has passed.
const timer = setInterval(() => (now = wiring.now()), 60_000);
return () => clearInterval(timer);
});
async function choose(next: SunsetChoice): Promise<void> {
if (!sunset) return;
choice = next;
changing = false;
status = 'set';
now = sunset.now();
sunset.save(next).then(
() => (kept = true),
(error: unknown) => {
console.error('sunset: the device could not keep the town', error);
kept = false;
}
);
// The player acted, so focus follows them to the answer.
await tick();
sunLine?.focus();
}
const LETTER_HASH = '#letter';
// Any hash but the letter's is the garden. A bare '#' is not a valid link target.
@@ -45,6 +105,28 @@
<main class="shell">
<h1 bind:this={heading} tabindex="-1">{PRODUCT_NAME}</h1>
<p>{en.shell.preparing}</p>
{#if sunset && (status === 'asking' || changing)}
<SunsetPlace
guess={sunset.guess}
current={changing ? place : null}
search={sunset.search}
focusOnOpen={changing}
onchoose={choose}
{...changing ? { oncancel: () => (changing = false) } : {}}
/>
{:else if sunset && status === 'set'}
<div class="sun" tabindex="-1" bind:this={sunLine}>
{#if place}
<SunsetLine {place} guessed={choice?.kind === 'device-zone'} {now} />
{:else}
<p>{en.sunset.noTown}</p>
{/if}
{#if !kept}
<p class="hint">{en.sunset.notKept}</p>
{/if}
<button type="button" class="quiet" onclick={() => (changing = true)}>{place ? en.sunset.change : en.sunset.choose}</button>
</div>
{/if}
{#if blocks.length > 0}
<a href={LETTER_HASH}>{en.letter.title}</a>
{/if}
@@ -87,4 +169,34 @@
a {
color: var(--rose);
}
.sun {
display: grid;
gap: var(--space-1);
justify-items: center;
margin-top: var(--space-3);
}
.sun:focus {
outline: none;
}
.hint {
font-size: 0.9rem;
}
.quiet {
font: inherit;
background: none;
border: none;
padding: var(--space-1) 0;
color: var(--rose);
text-decoration: underline;
cursor: pointer;
}
.quiet:focus-visible {
outline: 2px solid var(--rose);
outline-offset: 2px;
}
</style>
+21
View File
@@ -10,6 +10,27 @@ export const en = {
/** The one line on the Phase 0 page. True, calm, and asks nothing. */
preparing: 'The garden is being prepared.'
},
sunset: {
/** ROADMAP Phase 1, word for word. */
question: 'Where do you want your sunset?',
why: 'The garden follows the real sun. Choose a town near you. It is kept on this device only.',
searchLabel: 'Town or city',
/** Said aloud as the list changes. Never "not found": a small town is not a mistake. */
found: (n: number): string => (n === 0 ? 'No town by that name here. A larger one nearby will do.' : n === 1 ? 'One town' : `${n} towns`),
skip: (guess: string): string => `Not now. Use ${guess}`,
skipNoGuess: 'Not now',
keep: (town: string): string => `Keep ${town}`,
change: 'Change town',
choose: 'Choose a town',
tonight: (time: string, town: string): string => `Tonight the sun sets at ${time} in ${town}.`,
tomorrow: (time: string, town: string): string => `Tomorrow the sun sets at ${time} in ${town}.`,
polarDay: (time: string, town: string): string => `In ${town} the sun stays up tonight. The light is lowest at ${time}.`,
polarNight: (time: string, town: string): string => `In ${town} the sun stays below the horizon today. The twilight is brightest at ${time}.`,
guessed: "A guess from this device's time zone.",
noTown: 'Choose a town to see when the sun sets.',
/** When the device refuses to keep anything (a private window). Calm, and true. */
notKept: 'This device could not keep your choice, so the garden will ask again next time.'
},
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',
+1
View File
@@ -1,3 +1,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';
+46
View File
@@ -0,0 +1,46 @@
<script lang="ts">
import { localDay, nextInvitation, type NamedPlace } from '@rosea/engine';
import { en } from '../copy/en.js';
/**
* The next sunset, or its polar alternative, in one sentence. The engine says
* when; this only reads it on the town's clock, in the device's own time format
* (sunset-place.md P6).
*/
let { place, guessed = false, now }: { place: NamedPlace; guessed?: boolean; now: number } = $props();
const line = $derived.by(() => {
const { sun, at } = nextInvitation(now, place);
const time = new Intl.DateTimeFormat(undefined, { hour: 'numeric', minute: '2-digit', timeZone: place.timeZone }).format(at);
switch (sun.kind) {
case 'polar-day':
return en.sunset.polarDay(time, place.name);
case 'polar-night':
return en.sunset.polarNight(time, place.name);
case 'sun-sets':
// Tonight's sunset may fall after midnight (sun.md D2), so "tomorrow" only
// when it belongs to a later day than today.
return sun.day > localDay(now, place.timeZone) ? en.sunset.tomorrow(time, place.name) : en.sunset.tonight(time, place.name);
}
});
</script>
<p class="sunset">{line}</p>
{#if guessed}
<p class="hint">{en.sunset.guessed}</p>
{/if}
<style>
p {
margin: 0;
}
.sunset {
font-size: 1.1rem;
}
.hint {
color: var(--ink-soft);
font-size: 0.9rem;
}
</style>
+189
View File
@@ -0,0 +1,189 @@
<script lang="ts">
import type { NamedPlace } from '@rosea/engine';
import { en } from '../copy/en.js';
import type { SunsetChoice } from './types.js';
/**
* "Where do you want your sunset?" A search over towns on the device, and a way
* to say not now. Decides nothing: it reports the answer (sunset-place.md).
*/
let {
guess,
current = null,
search,
focusOnOpen = false,
onchoose,
oncancel
}: {
guess: NamedPlace | null;
/** The town already set, when the player is changing it. */
current?: NamedPlace | null;
search: (query: string) => Promise<readonly NamedPlace[]>;
focusOnOpen?: boolean;
onchoose: (choice: SunsetChoice) => void;
oncancel?: () => void;
} = $props();
const uid = $props.id();
let query = $state('');
// Raw: the towns are handed on as they came, never wrapped in a state Proxy.
let results = $state.raw<readonly NamedPlace[]>([]);
let input = $state<HTMLInputElement>();
// Only the latest query's answer is shown, however the searches finish.
let asked = 0;
$effect(() => {
const q = query;
const ticket = ++asked;
if (q.trim() === '') {
results = [];
return;
}
search(q).then(
(found) => {
if (ticket === asked) results = found;
},
(error: unknown) => {
console.error('sunset: the town search failed', error);
if (ticket === asked) results = [];
}
);
});
$effect(() => {
if (focusOnOpen) input?.focus();
});
const where = (t: NamedPlace): string => [t.region, t.country].filter(Boolean).join(', ');
</script>
<section class="ask" aria-labelledby="{uid}-q">
<h2 id="{uid}-q">{en.sunset.question}</h2>
<p class="why">{en.sunset.why}</p>
<label for="{uid}-search">{en.sunset.searchLabel}</label>
<input
id="{uid}-search"
type="search"
autocomplete="off"
spellcheck="false"
enterkeyhint="search"
bind:value={query}
bind:this={input}
/>
<p class="found" role="status" aria-live="polite">{query.trim() === '' ? '' : en.sunset.found(results.length)}</p>
{#if results.length > 0}
<ul>
{#each results as town (`${town.name}|${town.lat}|${town.lon}`)}
<li>
<button type="button" onclick={() => onchoose({ kind: 'town', town })}>
<span class="name">{town.name}</span>
<span class="where">{where(town)}</span>
</button>
</li>
{/each}
</ul>
{/if}
<div class="other">
{#if current && oncancel}
<button type="button" class="quiet" onclick={oncancel}>{en.sunset.keep(current.name)}</button>
{/if}
<button type="button" class="quiet" onclick={() => onchoose({ kind: 'device-zone' })}>
{guess ? en.sunset.skip(guess.name) : en.sunset.skipNoGuess}
</button>
</div>
</section>
<style>
.ask {
display: grid;
gap: var(--space-2);
width: min(28rem, 100%);
margin-inline: auto;
text-align: start;
}
h2 {
margin: 0;
font-family: var(--font-display);
font-weight: 400;
font-size: 1.4rem;
color: var(--ink);
}
.why,
.found {
margin: 0;
color: var(--ink-soft);
}
.found:empty {
display: none;
}
label {
font-size: 0.95rem;
}
input {
font: inherit;
padding: var(--space-2);
border: 1px solid var(--ink-soft);
border-radius: 0.5rem;
background: var(--paper);
color: var(--ink);
}
ul {
list-style: none;
margin: 0;
padding: 0;
display: grid;
gap: var(--space-1);
}
button {
font: inherit;
cursor: pointer;
border-radius: 0.5rem;
color: var(--ink);
}
li button {
width: 100%;
display: flex;
justify-content: space-between;
gap: var(--space-2);
padding: var(--space-2);
text-align: start;
background: var(--paper);
border: 1px solid color-mix(in srgb, var(--ink-soft) 40%, transparent);
}
.where {
color: var(--ink-soft);
text-align: end;
}
.other {
display: flex;
flex-wrap: wrap;
gap: var(--space-2);
}
.quiet {
background: none;
border: none;
padding: var(--space-1) 0;
color: var(--rose);
text-decoration: underline;
}
button:focus-visible,
input:focus-visible {
outline: 2px solid var(--rose);
outline-offset: 2px;
}
</style>
+19
View File
@@ -0,0 +1,19 @@
import type { NamedPlace } from '@rosea/engine';
/** What the player answered: a town, or "not now" (the guess from the device's zone). */
export type SunsetChoice = { readonly kind: 'town'; readonly town: NamedPlace } | { readonly kind: 'device-zone' };
/**
* Everything the garden needs to ask where the sunset is and to show it. The app
* provides it; ui imports neither content nor storage (CLAUDE.md §2).
*/
export interface SunsetWiring {
/** The device's guess for its own zone, or null for a zone of no place (UTC). */
readonly guess: NamedPlace | null;
/** Towns matching a query. The app loads the town list on the first call. */
readonly search: (query: string) => Promise<readonly NamedPlace[]>;
readonly load: () => Promise<SunsetChoice | null>;
readonly save: (choice: SunsetChoice) => Promise<void>;
/** The clock. A parameter, so tests and the e2e suite can fix it. */
readonly now: () => number;
}
+135
View File
@@ -0,0 +1,135 @@
import { invitation, sunDay, type NamedPlace } from '@rosea/engine';
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/svelte';
import { afterEach, describe, expect, it, vi } from 'vitest';
import Shell from '../src/Shell.svelte';
import { en } from '../src/copy/en.js';
import type { SunsetChoice, SunsetWiring } from '../src/sunset/types.js';
const brno: NamedPlace = { name: 'Brno', region: '', country: 'Czechia', lat: 49.2, lon: 16.61, timeZone: 'Europe/Prague' };
const prague: NamedPlace = { name: 'Prague', region: '', country: 'Czechia', lat: 50.09, lon: 14.46, timeZone: 'Europe/Prague' };
const tromso: NamedPlace = { name: 'Tromsø', region: 'Troms', country: 'Norway', lat: 69.65, lon: 18.96, timeZone: 'Europe/Oslo' };
/** Noon in Prague on 29 March 2026: tonight's sunset is still to come. */
const NOON = Date.parse('2026-03-29T12:00:00+02:00');
/** The time the line must show, read exactly as the component reads it. */
const timeOf = (place: NamedPlace, at: number): string =>
new Intl.DateTimeFormat(undefined, { hour: 'numeric', minute: '2-digit', timeZone: place.timeZone }).format(at);
function wiring(over: Partial<SunsetWiring> & { saved?: SunsetChoice | null } = {}): SunsetWiring & { saves: SunsetChoice[] } {
const saves: SunsetChoice[] = [];
return {
guess: prague,
search: async (q) => [brno, prague].filter((t) => t.name.toLowerCase().startsWith(q.trim().toLowerCase())),
load: async () => over.saved ?? null,
save: async (c) => {
saves.push(c);
},
now: () => NOON,
...over,
saves
};
}
afterEach(() => {
cleanup();
vi.restoreAllMocks();
});
describe('the garden asks where the sunset is', () => {
it('asks when nothing is saved, and does not take focus on first load', async () => {
render(Shell, { sunset: wiring() });
expect(await screen.findByRole('heading', { level: 2, name: en.sunset.question })).toBeTruthy();
expect(screen.getByRole('searchbox', { name: en.sunset.searchLabel })).toBeTruthy();
expect(document.activeElement).toBe(document.body);
});
it('typing lists towns, choosing one shows its sunset, keeps it, and moves focus to the answer', async () => {
const w = wiring();
render(Shell, { sunset: w });
await fireEvent.input(await screen.findByRole('searchbox'), { target: { value: 'br' } });
expect(await screen.findByRole('status')).toHaveProperty('textContent', en.sunset.found(1));
await fireEvent.click(screen.getByRole('button', { name: /Brno/ }));
const at = invitation(sunDay('2026-03-29', brno));
expect(await screen.findByText(en.sunset.tonight(timeOf(brno, at), 'Brno'))).toBeTruthy();
expect(w.saves).toEqual([{ kind: 'town', town: brno }]);
await waitFor(() => expect(document.activeElement?.className).toContain('sun'));
expect(screen.queryByText(en.sunset.guessed)).toBeNull();
});
it('nothing found says a larger town nearby will do, never an error', async () => {
render(Shell, { sunset: wiring() });
await fireEvent.input(await screen.findByRole('searchbox'), { target: { value: 'zz' } });
await waitFor(() => expect(screen.getByRole('status').textContent).toBe(en.sunset.found(0)));
});
it('"not now" uses the guess, saves the device zone, and says it is a guess', async () => {
const w = wiring();
render(Shell, { sunset: w });
await fireEvent.click(await screen.findByRole('button', { name: en.sunset.skip('Prague') }));
const at = invitation(sunDay('2026-03-29', prague));
expect(await screen.findByText(en.sunset.tonight(timeOf(prague, at), 'Prague'))).toBeTruthy();
expect(screen.getByText(en.sunset.guessed)).toBeTruthy();
expect(w.saves).toEqual([{ kind: 'device-zone' }]);
});
it('with no guess (a UTC clock), "not now" asks the player to choose a town', async () => {
render(Shell, { sunset: wiring({ guess: null }) });
await fireEvent.click(await screen.findByRole('button', { name: en.sunset.skipNoGuess }));
expect(await screen.findByText(en.sunset.noTown)).toBeTruthy();
expect(screen.getByRole('button', { name: en.sunset.choose })).toBeTruthy();
});
});
describe('the garden remembers', () => {
it('a saved town shows its sunset at once, with no question', async () => {
render(Shell, { sunset: wiring({ saved: { kind: 'town', town: brno } }) });
expect(await screen.findByText(/in Brno\.$/)).toBeTruthy();
expect(screen.queryByRole('searchbox')).toBeNull();
});
it('after the sunset, it speaks of tomorrow\'s', async () => {
const after = invitation(sunDay('2026-03-29', brno)) + 60_000;
render(Shell, { sunset: wiring({ saved: { kind: 'town', town: brno }, now: () => after }) });
const tomorrow = invitation(sunDay('2026-03-30', brno));
expect(await screen.findByText(en.sunset.tomorrow(timeOf(brno, tomorrow), 'Brno'))).toBeTruthy();
});
it('in polar night it speaks of the noon twilight; in polar day, of the lowest light', async () => {
const winter = Date.parse('2026-12-21T08:00:00+01:00');
render(Shell, { sunset: wiring({ saved: { kind: 'town', town: tromso }, now: () => winter }) });
const noon = sunDay('2026-12-21', tromso).solarNoon;
expect(await screen.findByText(en.sunset.polarNight(timeOf(tromso, noon), 'Tromsø'))).toBeTruthy();
cleanup();
const summer = Date.parse('2026-06-21T12:00:00+02:00');
render(Shell, { sunset: wiring({ saved: { kind: 'town', town: tromso }, now: () => summer }) });
expect(await screen.findByText(/In Tromsø the sun stays up tonight\. The light is lowest at/)).toBeTruthy();
});
it('change town: the search opens with focus, and Keep returns without saving anything', async () => {
const w = wiring({ saved: { kind: 'town', town: brno } });
render(Shell, { sunset: w });
await fireEvent.click(await screen.findByRole('button', { name: en.sunset.change }));
await waitFor(() => expect(document.activeElement).toBe(screen.getByRole('searchbox')));
await fireEvent.click(screen.getByRole('button', { name: en.sunset.keep('Brno') }));
expect(await screen.findByText(/in Brno\.$/)).toBeTruthy();
expect(w.saves).toEqual([]);
});
});
describe('when the device will not keep anything', () => {
it('a failed read still asks, and a failed save still shows the sunset and says it will ask again', async () => {
const error = vi.spyOn(console, 'error').mockImplementation(() => undefined);
const w = wiring({
load: () => Promise.reject(new Error('IndexedDB blocked')),
save: () => Promise.reject(new Error('IndexedDB blocked'))
});
render(Shell, { sunset: w });
await fireEvent.click(await screen.findByRole('button', { name: en.sunset.skip('Prague') }));
expect(await screen.findByText(/in Prague\.$/)).toBeTruthy();
expect(await screen.findByText(en.sunset.notKept)).toBeTruthy();
expect(error).toHaveBeenCalled(); // never swallowed
});
});