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

157 lines
7.3 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 verified hope library, bundled after validate:library passed (day-sentence.md P5).
import sentences from 'virtual:rosea-library';
// 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(),
// Another tab of the garden chose a town (two-tabs.md).
changes: (listener) => storage.onChange((what) => what === 'place' && listener())
};
// 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) -------------------------------------
// The Android, iOS and desktop apps are installed by being apps (tauri-platforms.md D9):
// they ask to keep the garden after the first care, as an installed PWA does, and never
// show the hint to add the page to the home screen. Keep her safe speaks of the app, not a
// browser (keep-her-safe-apps.md A1).
const inApp = __ROSEA_SHELL__ === 'tauri';
const browserStorage = typeof navigator !== 'undefined' ? navigator.storage : undefined;
const keeping: RoseWiring['keeping'] = {
where: inApp ? 'app' : 'browser',
persisted: async () => (browserStorage?.persisted ? browserStorage.persisted() : null),
persist: async () => (browserStorage?.persist ? browserStorage.persist() : null)
};
const installed = (): boolean =>
inApp ||
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));
}
/**
* Android's save screen, through the app's own bridge (keep-her-safe-apps.md A2): present
* only in the Android app, where `<a download>` does nothing. It answers with a window event,
* true when the file was written, false when the player stepped back (A4).
*/
const androidFile = inApp ? (window as Window & { roseaFile?: { save(name: string, text: string): void } }).roseaFile : undefined;
let saving: Promise<boolean> | undefined;
function saveFile(name: string, text: string): void | Promise<boolean> {
if (androidFile) {
// One save at a time: a second tap while the screen is open waits for the first answer.
if (saving) return saving;
saving = new Promise<boolean>((resolve) => {
const answer = (event: Event): void => {
window.removeEventListener('rosea-file-saved', answer);
saving = undefined;
resolve((event as CustomEvent<unknown>).detail === true);
};
window.addEventListener('rosea-file-saved', answer);
try {
androidFile.save(name, text);
} catch (error) {
console.error('keep: the app could not open the save screen', error);
window.removeEventListener('rosea-file-saved', answer);
saving = undefined;
resolve(false);
}
});
return saving;
}
// 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). In the apps there is no
// worker: this registerSW does nothing, and a new version comes as a new app.
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();
},
sentences,
loadOpened: () => storage.loadOpened(),
appendOpened: (event) => storage.appendOpened(event),
// The player's gardener, chosen at the first open (planet-garden.md G6).
gardener: { load: () => storage.loadGardener(), save: (look) => storage.saveGardener(look) },
// Another tab gave care, opened a petal or brought her back (two-tabs.md).
changes: (listener) => storage.onChange((what) => what === 'log' && listener()),
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)} />