import type { ReadableToken, TimelineEvent, TimelineFamilyToken, TimelineManageable, TimelineToken, TimelineUpdate, TransactionToken, TransactionUpdateHandler, UpdateHandler, } from "atom.io" import type { Canonical } from "atom.io/foundations/canonical" import { arbitrary } from "../arbitrary.ts" import type { Store } from "../store/index.ts" import { findTimelineInStore } from "../timeline/index.ts" import type { RootStore } from "../transaction/index.ts" import type { Fn } from "../utility-types.ts" import { subscribeToState } from "./subscribe-to-state.ts" import { subscribeToTimeline } from "./subscribe-to-timeline.ts" import { subscribeToTransaction } from "./subscribe-to-transaction.ts" export function subscribeInStore( store: Store, token: ReadableToken, handleUpdate: UpdateHandler, key?: string, ): () => void export function subscribeInStore( store: Store, token: TransactionToken, handleUpdate: TransactionUpdateHandler, key?: string, ): () => void export function subscribeInStore( store: Store, token: TimelineToken, handleUpdate: (update: TimelineEvent | `clear` | `redo` | `undo`) => void, key?: string, ): () => void export function subscribeInStore< K extends Canonical, M extends TimelineManageable, >( store: RootStore, family: TimelineFamilyToken, memberKey: NoInfer, handleUpdate: (update: TimelineUpdate) => void, key?: string, ): () => void export function subscribeInStore( store: Store, ...params: | [ token: ReadableToken | TimelineToken | TransactionToken, handleUpdate: | TransactionUpdateHandler | UpdateHandler | ((update: TimelineUpdate) => void), key?: string, ] | [ family: TimelineFamilyToken, memberKey: Canonical, handleUpdate: (update: TimelineUpdate) => void, key?: string, ] ): () => void export function subscribeInStore(store: Store, ...params: any[]): () => void { let token: ReadableToken | TimelineToken | TransactionToken let handleUpdate: (update: any) => void let key: string if (params[0].type === `timeline_family`) { token = findTimelineInStore( store as RootStore, params[0], params[1] as Canonical, ) handleUpdate = params[2] as (update: any) => void key = params[3] ?? arbitrary() } else { token = params[0] handleUpdate = params[1] as (update: any) => void key = (params[2] as string | undefined) ?? arbitrary() } switch (token.type) { case `atom`: case `mutable_atom`: case `readonly_pure_selector`: case `readonly_held_selector`: case `writable_pure_selector`: case `writable_held_selector`: return subscribeToState(store, token, key, handleUpdate) case `transaction`: return subscribeToTransaction(store, token, key, handleUpdate) case `timeline`: return subscribeToTimeline(store, token, key, handleUpdate) } }