[storage] TwoTabs: Announce each write to the other tabs after it commits

This commit is contained in:
2026-11-07 15:06:43 +01:00
parent 0861125472
commit 102ac44675
2 changed files with 172 additions and 3 deletions
+52 -3
View File
@@ -79,6 +79,11 @@ export interface Storage {
* here is appended. Nothing is edited or removed. Rejects a file that is not a rose.
*/
importRose(file: unknown, currentKey: string): Promise<{ readonly added: number; readonly petals: number }>;
/**
* Hears what another tab of the garden wrote (two-tabs.md): `'log'` or `'place'`,
* after it committed. Read storage again on it. Returns the way to stop hearing.
*/
onChange(listener: (what: Change) => void): () => void;
close(): void;
}
@@ -188,12 +193,44 @@ class RoseaDatabase extends Dexie {
}
}
/** What another tab changed (two-tabs.md W2): only which part, never the data. */
export type Change = 'log' | 'place';
/** The channel every tab of the garden announces its writes on (two-tabs.md W1). */
export const CHANGES_CHANNEL = `${DATABASE_NAME}-changes`;
/**
* Opens the player's database. `options` lets a test pass fake-indexeddb; the app
* passes nothing and gets the browser's IndexedDB.
* passes nothing and gets the browser's IndexedDB. `settings.channel` names the
* channel writes are announced on (null: none), so tests can keep theirs apart.
*/
export function openStorage(options?: DexieOptions): Storage {
export function openStorage(options?: DexieOptions, settings: { readonly channel?: string | null } = {}): Storage {
const db = new RoseaDatabase(options);
const channelName = settings.channel === undefined ? CHANGES_CHANNEL : settings.channel;
// Where BroadcastChannel does not exist, each tab simply keeps its own view (W5).
const channel = channelName !== null && typeof BroadcastChannel === 'function' ? new BroadcastChannel(channelName) : null;
const listeners = new Set<(what: Change) => void>();
if (channel) {
channel.onmessage = (message: MessageEvent<unknown>) => {
const what = message.data;
if (what !== 'log' && what !== 'place') return;
for (const listener of listeners) {
try {
listener(what);
} catch (error) {
console.error('storage: a listener for changes in another tab failed', error);
}
}
};
}
/** Called only after a write committed, so the other tab reads what was written. A tab never hears itself (W3). */
const announce = (what: Change): void => {
try {
channel?.postMessage(what);
} catch (error) {
console.warn('storage: could not tell the other tabs about a change; they will see it on their next load', error);
}
};
const asIdentity = (row: KeyRow | undefined): Identity | null => {
const id = row ? { publicKey: row.publicKey, privateKey: row.privateKey } : null;
return id && isIdentity(id) ? id : null;
@@ -211,11 +248,13 @@ export function openStorage(options?: DexieOptions): Storage {
const plain = asSunsetPlace(place);
if (plain === null) throw new TypeError('storage: refusing to save a sunset place of an unknown shape');
await db.profile.put({ key: SUNSET_PLACE, value: plain });
announce('place');
},
async appendCare(event) {
const plain = asCareEvent(event);
if (plain === null) throw new TypeError('storage: refusing to append a care event of an unknown shape');
await db.events.add({ event: plain });
announce('log');
},
async loadCare() {
const rows = await db.events.orderBy('id').toArray();
@@ -233,6 +272,7 @@ export function openStorage(options?: DexieOptions): Storage {
const plain = asSentenceOpened(event);
if (plain === null) throw new TypeError('storage: refusing to append an opened petal of an unknown shape');
await db.events.add({ event: plain });
announce('log');
},
async loadOpened() {
const rows = await db.events.orderBy('id').toArray();
@@ -276,7 +316,7 @@ export function openStorage(options?: DexieOptions): Storage {
async importRose(file, currentKey) {
const rose = asRoseFile(file);
if (rose === null) throw new TypeError('storage: this file does not hold a rose');
return db.transaction('rw', db.events, db.profile, async () => {
const result = await db.transaction('rw', db.events, db.profile, async () => {
const row = await db.profile.get(PAST_KEYS);
const past = isKeyList(row?.value) ? row.value : [];
const keys = [...new Set([...past, ...rose.keys])].filter((k) => k !== currentKey);
@@ -289,8 +329,17 @@ export function openStorage(options?: DexieOptions): Storage {
await db.events.bulkAdd([...added, ...petals].map((event) => ({ event })));
return { added: added.length, petals: petals.length };
});
// After the commit: her keys and her log both changed for the other tabs.
announce('log');
return result;
},
onChange(listener) {
listeners.add(listener);
return () => listeners.delete(listener);
},
close() {
listeners.clear();
channel?.close();
db.close();
}
};