@collabs/tab-sync
Version:
Collabs cross-tab synchronization using BroadcastChannel
86 lines (85 loc) • 3.06 kB
TypeScript
import { AbstractDoc, CRuntime } from "@collabs/collabs";
import { EventEmitter } from "@collabs/core";
/** Events record for [[TabSyncNetwork]]. */
export interface TabSyncNetworkEventsRecord {
/**
* Emitted when there is an error, e.g., we fail to parse a message.
*/
Error: {
err: unknown;
};
}
/**
* Syncs updates to Collabs documents across different tabs for the same origin,
* using BroadcastChannel.
*
* By default, this only forwards *local* operations to other tabs. Updates from other sources (e.g., a remote server via
* [@collabs/ws-client](https://www.npmjs.com/package/@collabs/ws-client))
* are not sent over the BroadcastChannel, since we expect that other tabs will
* get a copy from their own sources. You can override this with the `allUpdates`
* constructor option.
*
* Likewise, our other providers do not forward or store
* operations from TabSyncNetwork. Instead, it is expected that
* each tab sets up its own providers to forward/store updates.
*/
export declare class TabSyncNetwork extends EventEmitter<TabSyncNetworkEventsRecord> {
/**
* The name of this class's BroadcastChannel,
* set in the constructor.
*
* Default: "@collabs/tab-sync".
*/
readonly bcName: string;
private readonly allUpdates;
private readonly bc;
/** A random senderID for this object. */
private readonly objID;
private readonly subs;
/** Inverse map docID -> Doc. */
private readonly docsByID;
private closed;
readonly isTabSyncNetwork = true;
/**
* Constructs a TabSyncNetwork.
*
* You typically only need one TabSyncNetwork per app, since it
* can [[subscribe]] multiple documents.
*
* @param options.bcName The name of the BroadcastChannel to use.
* Default: "@collabs/tab-sync".
* @param options.allUpdates Set to true to forward all doc updates over
* the BroadcastChannel, not just local operations.
*/
constructor(options?: {
bcName?: string;
allUpdates?: boolean;
});
private sendInternal;
/**
* Subscribes `doc` to updates for `docID`.
*
* `doc` will send and receive updates with other tabs
* that are subscribed to `docID`. It will also sync initial states with
* other tabs, to ensure that they start up-to-date.
*
* @param doc The document to subscribe.
* @param docID An arbitrary string that identifies which updates to use.
* @throws If `doc` is already subscribed to a docID.
* @throws If another doc is subscribed to `docID`.
*/
subscribe(doc: AbstractDoc | CRuntime, docID: string): void;
/**
* Unsubscribes `doc` from its subscribed `docID` (if any).
*
* `doc` will no longer send or receive updates with other tabs.
*/
unsubscribe(doc: AbstractDoc | CRuntime): void;
private bcReceive;
/**
* Closes our BroadcastChannel and unsubscribes all documents.
*
* Future [[subscribe]] calls will throw an error.
*/
close(): void;
}