[ui] KeepSafe: Say what the browser promised, ask it to keep her, save her to a file, bring her back

This commit is contained in:
2026-11-02 00:44:20 +01:00
parent a63232e8d7
commit 512c300973
5 changed files with 308 additions and 8 deletions
+17 -1
View File
@@ -49,7 +49,23 @@ export const en = {
petals: 'A few of my petals have fallen. Would you gather them?', 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.' 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.' notKept: 'This device could not keep today’s care, so it lasts only until the garden closes.',
/** Keeping her (keep-her-safe.md). True and calm: a browser can clear a site's data. */
safe: {
title: 'Keep her safe',
kept: 'This browser has promised to keep her.',
mayClear: 'This browser may clear her if the garden is not opened for a long time. A saved file keeps her for sure.',
unknown: 'This browser decides for itself how long it keeps her. A saved file keeps her for sure.',
ask: 'Ask the browser to keep her',
refused: 'The browser did not promise. A saved file keeps her for sure.',
install: 'On an iPhone or iPad, add the garden to your Home Screen to keep her.',
save: 'Save her to a file',
fileNote: 'The file holds her care and when it was given. It never holds your town.',
bringBack: 'Bring her back from a file',
broughtBack: (n: number): string => (n === 1 ? 'She is back, with 1 act of care.' : `She is back, with ${n} acts of care.`),
alreadyHere: 'Everything in that file is already here.',
notARose: 'That file does not hold a rose.'
}
}, },
sunset: { sunset: {
/** ROADMAP Phase 1, word for word. */ /** ROADMAP Phase 1, word for word. */
+152
View File
@@ -0,0 +1,152 @@
<script lang="ts">
import { en } from '../copy/en.js';
import type { RoseWiring } from './types.js';
/**
* Keeping her (keep-her-safe.md): what the browser has promised, asking it to keep
* her, saving her to a file, and bringing her back from one. Decides nothing; the
* file's shape is checked by storage.
*/
let { wiring, currentKey, today, onrestored }: { wiring: RoseWiring; currentKey: string; today: string; onrestored: () => void } = $props();
const uid = $props.id();
let persisted = $state<boolean | null | undefined>(undefined);
let refused = $state(false);
let said = $state('');
$effect(() => {
wiring.keeping.persisted().then(
(p) => (persisted = p),
(error: unknown) => {
console.error('keep: the browser could not say whether it keeps the garden', error);
persisted = null;
}
);
});
async function ask(): Promise<void> {
try {
const granted = await wiring.keeping.persist();
persisted = granted;
refused = granted !== true;
} catch (error) {
console.error('keep: asking the browser to keep the garden failed', error);
refused = true;
}
}
async function save(): Promise<void> {
try {
const file = await wiring.exportRose(currentKey);
wiring.saveFile(`rose-${today}.json`, JSON.stringify(file, null, 1));
} catch (error) {
console.error('keep: the rose could not be saved to a file', error);
}
}
async function bringBack(event: Event & { currentTarget: HTMLInputElement }): Promise<void> {
const input = event.currentTarget;
const file = input.files?.[0];
if (!file) return;
try {
const { added } = await wiring.importRose(JSON.parse(await file.text()), currentKey);
said = added === 0 ? en.rose.safe.alreadyHere : en.rose.safe.broughtBack(added);
onrestored();
} catch (error) {
// A wrong file is an ordinary thing to choose; the player is told calmly, the console fully.
console.warn('keep: the chosen file is not a rose', error);
said = en.rose.safe.notARose;
} finally {
input.value = '';
}
}
</script>
<section class="safe" aria-labelledby="{uid}-title">
<h3 id="{uid}-title">{en.rose.safe.title}</h3>
{#if persisted !== undefined}
<p>{refused ? en.rose.safe.refused : persisted === true ? en.rose.safe.kept : persisted === false ? en.rose.safe.mayClear : en.rose.safe.unknown}</p>
{/if}
{#if persisted === false && !refused}
<button type="button" class="quiet" onclick={ask}>{en.rose.safe.ask}</button>
{/if}
{#if wiring.installHint}
<p>{en.rose.safe.install}</p>
{/if}
<button type="button" onclick={save}>{en.rose.safe.save}</button>
<p class="note">{en.rose.safe.fileNote}</p>
<label class="file">
<span>{en.rose.safe.bringBack}</span>
<input type="file" accept="application/json,.json" onchange={bringBack} />
</label>
<p class="said" role="status">{said}</p>
</section>
<style>
.safe {
display: grid;
gap: var(--space-2);
justify-items: center;
max-width: 24rem;
text-align: center;
}
h3 {
margin: 0;
font-family: var(--font-display);
font-weight: 400;
font-size: 1.1rem;
}
p {
margin: 0;
}
.note,
.said {
color: var(--ink-soft);
font-size: 0.9rem;
}
.said:empty {
display: none;
}
button,
.file {
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;
}
.quiet {
border: none;
padding: var(--space-1) 0;
color: var(--rose);
text-decoration: underline;
}
.file {
position: relative;
}
/* The real input stays operable and labelled; only its default look is hidden. */
.file input {
position: absolute;
inset: 0;
opacity: 0;
cursor: pointer;
}
.file:focus-within,
button:focus-visible {
outline: 2px solid var(--rose);
outline-offset: 2px;
}
</style>
+33 -5
View File
@@ -1,7 +1,8 @@
<script lang="ts"> <script lang="ts">
import { careEvent, pour, roseAt, ROSE, type Mood, type RoseNow, type Stage } from '@rosea/engine'; import { careEvent, localDay, pour, roseAt, ROSE, type Mood, type RoseNow, type Stage } from '@rosea/engine';
import type { CareEvent } from '@rosea/schema'; import type { CareEvent } from '@rosea/schema';
import { en } from '../copy/en.js'; import { en } from '../copy/en.js';
import KeepSafe from './KeepSafe.svelte';
import type { RoseWiring } from './types.js'; import type { RoseWiring } from './types.js';
// The art board's stand-ins until real art is accepted (rose.md R10, docs/ART.md). // 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 bud from '../../../../art/placeholders/rose-bud.svg?url';
@@ -24,6 +25,9 @@
const MOOD_PICTURE: Record<Mood, string> = { content: fullBloom, thirsty, 'too-full': overwatered, windblown, blushing, waiting }; const MOOD_PICTURE: Record<Mood, string> = { content: fullBloom, thirsty, 'too-full': overwatered, windblown, blushing, waiting };
let seed = $state<string | null>(null); let seed = $state<string | null>(null);
/** Keys she was named by on another device (keep-her-safe.md K2). */
let pastKeys = $state.raw<readonly string[]>([]);
let showSafe = $state(false);
let events = $state.raw<readonly CareEvent[]>([]); let events = $state.raw<readonly CareEvent[]>([]);
let now = $state(0); let now = $state(0);
let kept = $state(true); let kept = $state(true);
@@ -32,10 +36,11 @@
$effect(() => { $effect(() => {
const w = wiring; const w = wiring;
now = w.now(); now = w.now();
Promise.all([w.identity(), w.loadCare()]).then( Promise.all([w.identity(), w.loadCare(), w.pastKeys()]).then(
([id, log]) => { ([id, log, past]) => {
seed = id.publicKey; seed = id.publicKey;
events = log; events = log;
pastKeys = past;
if (!id.kept) kept = false; if (!id.kept) kept = false;
}, },
(error: unknown) => { (error: unknown) => {
@@ -48,7 +53,19 @@
return () => clearInterval(timer); return () => clearInterval(timer);
}); });
const rose = $derived<RoseNow | null>(seed === null ? null : roseAt(events, seed, now, timeZone)); const rose = $derived<RoseNow | null>(seed === null ? null : roseAt(events, [seed, ...pastKeys], now, timeZone));
/** After she is brought back from a file: read her log and keys again. */
function restored(): void {
Promise.all([wiring.loadCare(), wiring.pastKeys()]).then(
([log, past]) => {
events = log;
pastKeys = past;
now = wiring.now();
},
(error: unknown) => console.error('rose: could not read her back after restoring', error)
);
}
function care(act: CareEvent['act'], amount?: number): void { function care(act: CareEvent['act'], amount?: number): void {
if (seed === null) return; if (seed === null) return;
@@ -162,7 +179,10 @@
<p class="hint">{en.rose.notKept}</p> <p class="hint">{en.rose.notKept}</p>
{/if} {/if}
<button type="button" class="quiet" aria-expanded={showNumbers} aria-controls="rose-numbers" onclick={() => (showNumbers = !showNumbers)}>{en.rose.numbers}</button> <div class="more">
<button type="button" class="quiet" aria-expanded={showNumbers} aria-controls="rose-numbers" onclick={() => (showNumbers = !showNumbers)}>{en.rose.numbers}</button>
<button type="button" class="quiet" aria-expanded={showSafe} onclick={() => (showSafe = !showSafe)}>{en.rose.safe.title}</button>
</div>
{#if showNumbers} {#if showNumbers}
<dl id="rose-numbers" class="numbers"> <dl id="rose-numbers" class="numbers">
<dt>{en.rose.waterLevel}</dt><dd>{percent(rose.water)}</dd> <dt>{en.rose.waterLevel}</dt><dd>{percent(rose.water)}</dd>
@@ -171,6 +191,9 @@
<dt>{en.rose.trend}</dt><dd>{en.rose.trendWords[rose.trend]}</dd> <dt>{en.rose.trend}</dt><dd>{en.rose.trendWords[rose.trend]}</dd>
</dl> </dl>
{/if} {/if}
{#if showSafe && seed}
<KeepSafe {wiring} currentKey={seed} today={localDay(now, timeZone)} onrestored={restored} />
{/if}
</section> </section>
{/if} {/if}
@@ -253,6 +276,11 @@
cursor: pointer; cursor: pointer;
} }
.more {
display: flex;
gap: var(--space-3);
}
.numbers { .numbers {
display: grid; display: grid;
grid-template-columns: auto auto; grid-template-columns: auto auto;
+14
View File
@@ -14,4 +14,18 @@ export interface RoseWiring {
readonly deviceZone: string; readonly deviceZone: string;
/** The clock. A parameter, so tests and the e2e suite can fix it. */ /** The clock. A parameter, so tests and the e2e suite can fix it. */
readonly now: () => number; readonly now: () => number;
/** Keys the rose was named by before, on another device (keep-her-safe.md K2). */
readonly pastKeys: () => Promise<string[]>;
/** The rose as a file's contents, and bringing one back. */
readonly exportRose: (currentKey: string) => Promise<unknown>;
readonly importRose: (file: unknown, currentKey: string) => Promise<{ readonly added: number }>;
/** Hands the player a file to keep. */
readonly saveFile: (name: string, text: string) => void;
/** The browser's promise to keep the garden: true, false, or null when it cannot say. */
readonly keeping: {
readonly persisted: () => Promise<boolean | null>;
readonly persist: () => Promise<boolean | null>;
};
/** True on an iPhone or iPad not yet added to the Home Screen, where Safari may clear her. */
readonly installHint: boolean;
} }
+92 -2
View File
@@ -13,8 +13,9 @@ const ME = 'M'.repeat(87);
const MORNING = Date.parse('2026-03-01T08:00:00+01:00'); const MORNING = Date.parse('2026-03-01T08:00:00+01:00');
const DAY = 86_400_000; const DAY = 86_400_000;
function wiring(over: Partial<RoseWiring> & { log?: CareEvent[]; at?: number } = {}): RoseWiring & { appended: CareEvent[] } { function wiring(over: Partial<RoseWiring> & { log?: CareEvent[]; at?: number } = {}): RoseWiring & { appended: CareEvent[]; saved: { name: string; text: string }[] } {
const appended: CareEvent[] = []; const appended: CareEvent[] = [];
const saved: { name: string; text: string }[] = [];
const at = over.at ?? MORNING; const at = over.at ?? MORNING;
return { return {
identity: async () => ({ publicKey: ME, kept: true }), identity: async () => ({ publicKey: ME, kept: true }),
@@ -25,8 +26,17 @@ function wiring(over: Partial<RoseWiring> & { log?: CareEvent[]; at?: number } =
clientVersion: '0.1.0', clientVersion: '0.1.0',
deviceZone: ZONE, deviceZone: ZONE,
now: () => at, now: () => at,
pastKeys: async () => [],
exportRose: async (key) => ({ format: 'rosea-rose', version: 1, keys: [key], events: [...(over.log ?? []), ...appended] }),
importRose: async () => ({ added: 0 }),
saveFile: (name, text) => {
saved.push({ name, text });
},
keeping: { persisted: async () => false, persist: async () => true },
installHint: false,
...over, ...over,
appended appended,
saved
}; };
} }
const water = (now: number, amount: number): CareEvent => careEvent({ now, timeZone: ZONE, from: ME, to: ME, act: 'water', amount, clientVersion: '0.1.0' }); const water = (now: number, amount: number): CareEvent => careEvent({ now, timeZone: ZONE, from: ME, to: ME, act: 'water', amount, clientVersion: '0.1.0' });
@@ -136,3 +146,83 @@ describe('the rose', () => {
expect(error).toHaveBeenCalled(); expect(error).toHaveBeenCalled();
}); });
}); });
// jsdom's File has no text(); every browser the app runs in does. Read it as a browser would.
if (typeof File.prototype.text !== 'function') {
File.prototype.text = function (this: File): Promise<string> {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(String(reader.result));
reader.onerror = () => reject(reader.error);
reader.readAsText(this);
});
};
}
describe('keep her safe (keep-her-safe.md)', () => {
const OLD = 'O'.repeat(87);
const open = async (): Promise<void> => {
await screen.findByRole('img');
await fireEvent.click(screen.getByRole('button', { name: en.rose.safe.title }));
};
it('says the browser may clear her, asks it to keep her on request, and says when it promised', async () => {
render(Rose, { wiring: wiring(), timeZone: ZONE });
await open();
expect(await screen.findByText(en.rose.safe.mayClear)).toBeTruthy();
await fireEvent.click(screen.getByRole('button', { name: en.rose.safe.ask }));
expect(await screen.findByText(en.rose.safe.kept)).toBeTruthy();
expect(screen.queryByRole('button', { name: en.rose.safe.ask })).toBeNull();
});
it('a browser that will not promise is told calmly, and the file is offered', async () => {
render(Rose, { wiring: wiring({ keeping: { persisted: async () => false, persist: async () => false } }), timeZone: ZONE });
await open();
await fireEvent.click(await screen.findByRole('button', { name: en.rose.safe.ask }));
expect(await screen.findByText(en.rose.safe.refused)).toBeTruthy();
});
it('saves her as a dated file holding her care, and says the file never holds the town', async () => {
const log = [water(MORNING - 60_000, 0.5)];
const w = wiring({ log });
render(Rose, { wiring: w, timeZone: ZONE });
await open();
expect(screen.getByText(en.rose.safe.fileNote)).toBeTruthy();
await fireEvent.click(screen.getByRole('button', { name: en.rose.safe.save }));
await waitFor(() => expect(w.saved).toHaveLength(1));
expect(w.saved[0]?.name).toBe('rose-2026-03-01.json');
expect(JSON.parse(w.saved[0]?.text ?? '{}')).toMatchObject({ keys: [ME], events: log });
});
it('bringing her back from a file restores her days of care under her old key', async () => {
const old = [{ ...water(MORNING - 2 * DAY, 0.5), from: OLD, to: OLD }];
let restored = false;
const w = wiring({
loadCare: async () => (restored ? old : []),
pastKeys: async () => (restored ? [OLD] : []),
importRose: async (file) => {
expect(file).toMatchObject({ keys: [OLD] });
restored = true;
return { added: 1 };
}
});
render(Rose, { wiring: w, timeZone: ZONE });
await open();
const input = screen.getByLabelText(en.rose.safe.bringBack) as HTMLInputElement;
const file = new File([JSON.stringify({ format: 'rosea-rose', version: 1, keys: [OLD], events: old })], 'rose.json', { type: 'application/json' });
await fireEvent.change(input, { target: { files: [file] } });
expect(await screen.findByText(en.rose.safe.broughtBack(1))).toBeTruthy();
await fireEvent.click(screen.getByRole('button', { name: en.rose.numbers }));
await waitFor(() => expect(document.getElementById('rose-numbers')?.textContent).toContain(`${en.rose.daysOfCare}1`));
});
it('a file that is not a rose is said calmly, and nothing changes', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
render(Rose, { wiring: wiring({ importRose: () => Promise.reject(new TypeError('storage: this file does not hold a rose')) }), timeZone: ZONE });
await open();
const input = screen.getByLabelText(en.rose.safe.bringBack);
await fireEvent.change(input, { target: { files: [new File(['not json'], 'x.json')] } });
expect(await screen.findByText(en.rose.safe.notARose)).toBeTruthy();
expect(warn).toHaveBeenCalled();
});
});