import type { Annotation, Annotator, AnnotatorState, Store, StoreChangeEvent } from '@annotorious/core'; type Subscriber = (annotation: T[]) => void; export interface SvelteStore extends Store { subscribe(onChange: Subscriber): void; } export interface SvelteAnnotatorState extends AnnotatorState { store: SvelteStore } export interface SvelteAnnotator extends Annotator { state: SvelteAnnotatorState } /** * A simple wrapper around the event-based store implementation * that adds a Svelte shim, for use with the reactive '$' notation. * Other frameworks might not actually need this. But it's pretty * convenient for everyone using Svelte, as well as for the * basic (Svelte-based) Annotorious standard implementation. */ export const toSvelteStore = (store: Store): SvelteStore => { const subscribe = (onChange: Subscriber) => { // Register a store observer on behalf of the subscriber const shim = (event: StoreChangeEvent) => onChange(event.state); store.observe(shim); // Immediately call the subscriber function with the // current store value, according to the Svelte contract. // https://stackoverflow.com/questions/68220955/how-does-svelte-unsubscribe-actually-work onChange(store.all()); // Return the unsubscribe function return () => store.unobserve(shim); } return { ...store, subscribe } }