parent
59cccd55a6
commit
e6333d4c82
@ -0,0 +1,51 @@
|
||||
import { ENTRY_CHANGE_SOURCE_EXTERNAL } from './consts';
|
||||
import type { EntryBus } from './entry-bus';
|
||||
import type { SyncStorageAdapter } from './types';
|
||||
|
||||
export interface StorageAdapterRegistry {
|
||||
busKeyFor(adapter: SyncStorageAdapter, fullKey: string): string;
|
||||
defaultsKeyFor(adapter: SyncStorageAdapter, fullKey: string): string;
|
||||
ensureSubscription(adapter: SyncStorageAdapter, syncTabs: boolean): void;
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
export function createStorageAdapterRegistry(bus: EntryBus): StorageAdapterRegistry {
|
||||
const adapterIds = new WeakMap<SyncStorageAdapter, number>();
|
||||
const adapterDisposers = new Map<number, () => void>();
|
||||
let adapterIdSeq = 0;
|
||||
|
||||
function getAdapterId(target: SyncStorageAdapter): number {
|
||||
let id = adapterIds.get(target);
|
||||
if (id === undefined) {
|
||||
adapterIdSeq += 1;
|
||||
id = adapterIdSeq;
|
||||
adapterIds.set(target, id);
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
function busKeyFor(target: SyncStorageAdapter, fullKey: string): string {
|
||||
return `${getAdapterId(target)}\u0000${fullKey}`;
|
||||
}
|
||||
|
||||
function defaultsKeyFor(target: SyncStorageAdapter, fullKey: string): string {
|
||||
return `${getAdapterId(target)}:${fullKey}`;
|
||||
}
|
||||
|
||||
function ensureSubscription(target: SyncStorageAdapter, syncTabs: boolean): void {
|
||||
if (!syncTabs || !target.onChange) return;
|
||||
const id = getAdapterId(target);
|
||||
if (adapterDisposers.has(id)) return;
|
||||
const detach = target.onChange((changedKey, newValue) => {
|
||||
bus.publish(busKeyFor(target, changedKey), newValue, ENTRY_CHANGE_SOURCE_EXTERNAL);
|
||||
});
|
||||
adapterDisposers.set(id, detach);
|
||||
}
|
||||
|
||||
function dispose(): void {
|
||||
adapterDisposers.forEach((detach) => detach());
|
||||
adapterDisposers.clear();
|
||||
}
|
||||
|
||||
return { busKeyFor, defaultsKeyFor, ensureSubscription, dispose };
|
||||
}
|
||||
Loading…
Reference in new issue