UNPKG

channelstate

Version:

A lightweight cross-context state management library built on the BroadcastChannel API.

39 lines (36 loc) 1.21 kB
import { MaybePartial, StoreApi } from '../vanilla.mjs'; type ChannelMessage<T> = { action: 'write'; state: MaybePartial<T>; replace?: boolean; } | { action: 'sync'; receiver?: string; state: MaybePartial<T>; replace?: boolean; } | { action: 'requestSync'; }; type ChannelMessageReceived<T> = ChannelMessage<T> & { sender: string; }; interface ChannelApi<T> extends BroadcastChannel { id: string; postMessage(message: ChannelMessage<T>): void; } interface ChannelStateApi<T> extends StoreApi<T> { id: string; close(): void; } interface CreateChannelStateOptions { /** @default true */ syncOnInit?: boolean; } type ChannelStateCreator<T> = (api: ChannelApi<T>) => { setupStore(): StoreApi<T>; onMessage(message: ChannelMessageReceived<T>): void; onInit?(): void; onClose?(): void; }; declare function createChannelStateImpl<TState>(channelName: string, creator: ChannelStateCreator<TState>): ChannelStateApi<TState>; export { type CreateChannelStateOptions as C, type ChannelStateApi as a, type ChannelMessage as b, type ChannelMessageReceived as c, type ChannelApi as d, type ChannelStateCreator as e, createChannelStateImpl as f };