Files
Rosea/apps/rosea/src/App.svelte
T

108 lines
4.8 KiB
Svelte

<script lang="ts">
import { guessTown } from '@rosea/content/guess';
import { createIdentity } from '@rosea/identity';
import { openStorage } from '@rosea/storage';
import { Shell, type RoseWiring, type SunsetWiring } from '@rosea/ui';
import { registerSW } from 'virtual:pwa-register';
import { version } from '../package.json';
// Bundled at build time, so the letter is precached and opens offline (letter-slot.md L1).
import letter from '../../../docs/LETTER.md?raw';
// The device's own zone, read here and nowhere else: the engine never asks the
// device anything (CLAUDE.md §2). Only the zone's name; never GPS, never a lookup.
const deviceZone = new Intl.DateTimeFormat().resolvedOptions().timeZone;
const storage = openStorage();
// The town list is large, so it loads on the first search (sunset-place.md P5).
// A failed load is forgotten, so the next keystroke tries again.
let towns: Promise<typeof import('@rosea/content/places')> | undefined;
const loadTowns = (): Promise<typeof import('@rosea/content/places')> =>
(towns ??= import('@rosea/content/places').catch((error: unknown) => {
towns = undefined;
throw error;
}));
const sunset: SunsetWiring = {
guess: guessTown(deviceZone),
search: async (query) => (await loadTowns()).searchTowns(query),
load: () => storage.loadSunsetPlace(),
save: (choice) => storage.saveSunsetPlace(choice),
now: () => Date.now()
};
// The player's key names their rose (rose.md). Kept once; if the device will not
// keep it, this visit still has a rose, under a key that lasts until closing.
let identity: ReturnType<RoseWiring['identity']> | undefined;
async function findIdentity(): ReturnType<RoseWiring['identity']> {
try {
const kept = await storage.loadIdentity();
if (kept) return { publicKey: kept.publicKey, kept: true };
} catch (error) {
console.error('identity: the device could not read the kept key', error);
}
const fresh = await createIdentity();
try {
return { publicKey: (await storage.keepIdentity(fresh)).publicKey, kept: true };
} catch (error) {
console.error('identity: the device could not keep the key; this visit uses one that lasts until closing', error);
return { publicKey: fresh.publicKey, kept: false };
}
}
// --- Keeping her (keep-her-safe.md) -------------------------------------
const browserStorage = typeof navigator !== 'undefined' ? navigator.storage : undefined;
const keeping: RoseWiring['keeping'] = {
persisted: async () => (browserStorage?.persisted ? browserStorage.persisted() : null),
persist: async () => (browserStorage?.persist ? browserStorage.persist() : null)
};
const installed = (): boolean =>
matchMedia('(display-mode: standalone)').matches || (navigator as Navigator & { standalone?: boolean }).standalone === true;
// An installed app is asked once, after the first care of a visit: by then there is
// something to lose, and installed apps are not met with a permission prompt (K5).
let askedToKeep = false;
function keepAfterCare(): void {
if (askedToKeep || !installed()) return;
askedToKeep = true;
keeping.persist().catch((error: unknown) => console.error('keep: asking the browser to keep the garden failed', error));
}
function saveFile(name: string, text: string): void {
// A file made here and handed over; nothing is sent anywhere.
const url = URL.createObjectURL(new Blob([text], { type: 'application/json' }));
const a = Object.assign(document.createElement('a'), { href: url, download: name });
document.body.append(a);
a.click();
a.remove();
setTimeout(() => URL.revokeObjectURL(url), 10_000);
}
// --- A new version waiting (calm-refresh.md) ----------------------------
// The worker is registered here so the page hears when a new version has installed
// and waits. It is offered, never swapped in by itself (U2).
let updateReady = $state(false);
const updateSW = registerSW({
onNeedRefresh: () => (updateReady = true),
onRegisterError: (error: unknown) => console.error('update: the service worker could not be registered', error)
});
const rose: RoseWiring = {
identity: () => (identity ??= findIdentity()),
loadCare: () => storage.loadCare(),
appendCare: async (event) => {
await storage.appendCare(event);
keepAfterCare();
},
clientVersion: version,
deviceZone,
now: () => Date.now(),
pastKeys: () => storage.loadPastKeys(),
exportRose: (currentKey) => storage.exportRose(currentKey),
importRose: (file, currentKey) => storage.importRose(file, currentKey),
saveFile,
keeping,
installHint: /iPhone|iPad|iPod/.test(navigator.userAgent) && !installed()
};
</script>
<Shell {letter} {sunset} {rose} {updateReady} onrefresh={() => void updateSW(true)} />