import type { GraphStore, StoreQueryResponse, StoreSnapshot } from '@astrale-os/sdk/client/store' import type { QueryAST } from '@astrale-os/sdk/query' import { useCallback, useEffect, useMemo, useRef, useSyncExternalStore } from 'react' import { useGraphStore } from './store.js' export type GraphResourceState = | 'idle' | 'loading' | 'ready' | 'stale' | 'refreshing' | 'optimistic' | 'failed' export interface GraphResource { readonly state: GraphResourceState /** Current-scope data only. Previous-scope data is never substituted here. */ readonly data: T | undefined readonly error: unknown readonly previous?: { readonly identity: string; readonly data: T } readonly transitioning: boolean readonly live: false readonly sequence: 0 refresh(): Promise readonly more: { readonly has: boolean readonly pending: boolean load(): Promise } } export interface StoreResourceOptions { readonly identity?: string readonly keepPrevious?: boolean readonly window?: 'page' | 'append' readonly merge?: (pages: readonly Output[]) => Output readonly refreshInterval?: number readonly refreshWhen?: 'always' | 'visible' } interface PageRef { readonly after?: string } interface ObserverSnapshot { readonly snapshots: readonly StoreSnapshot[] readonly pendingMore: boolean } class StoreObserver { private readonly listeners = new Set<() => void>() private pages: readonly PageRef[] = Object.freeze([Object.freeze({})]) private unsubs: readonly (() => void)[] = Object.freeze([]) private current: ObserverSnapshot | undefined private morePromise: Promise | null = null private started = false constructor( private readonly store: GraphStore, private readonly query: Query, private readonly size: number, ) {} subscribe = (listener: () => void): (() => void) => { this.listeners.add(listener) return () => this.listeners.delete(listener) } getSnapshot = (): ObserverSnapshot => { if (this.current !== undefined) return this.current this.current = Object.freeze({ snapshots: Object.freeze( this.pages.map((page) => this.store.getSnapshot(this.query, this.pageOptions(page))), ), pendingMore: this.morePromise !== null, }) return this.current } start(): () => void { if (!this.started) { this.started = true this.bindPages() void this.store .read(this.query, { ...this.pageOptions(this.pages[0]!), freshness: 'cached', }) .catch(() => {}) } return () => { this.started = false this.unsubs.forEach((unsubscribe) => unsubscribe()) this.unsubs = Object.freeze([]) } } async refresh(): Promise { await Promise.all( this.pages.map((page) => this.store.read(this.query, { ...this.pageOptions(page), freshness: 'refresh' }), ), ) } hasMore(): boolean { const snapshots = this.getSnapshot().snapshots const last = snapshots[snapshots.length - 1] const response = last === undefined ? undefined : responseOf(last) return response?.page.next !== undefined } loadMore(): Promise { if (this.morePromise !== null) return this.morePromise const snapshots = this.getSnapshot().snapshots const last = snapshots[snapshots.length - 1] const after = last === undefined ? undefined : responseOf(last)?.page.next if (after === undefined) return Promise.resolve() if (this.pages.some((page) => page.after === after)) return Promise.resolve() this.pages = Object.freeze([...this.pages, Object.freeze({ after })]) this.bindPages() this.morePromise = this.store .read(this.query, { ...this.pageOptions({ after }), freshness: 'cached' }) .then(() => {}) .finally(() => { this.morePromise = null this.publish() }) this.publish() return this.morePromise } private pageOptions(page: PageRef) { return Object.freeze({ page: Object.freeze({ size: this.size, ...(page.after === undefined ? {} : { after: page.after }), }), }) } private bindPages(): void { this.unsubs.forEach((unsubscribe) => unsubscribe()) this.unsubs = Object.freeze( this.pages.map((page) => this.store.subscribe(this.query, this.publish, this.pageOptions(page)), ), ) this.publish() } private publish = (): void => { this.current = undefined this.listeners.forEach((listener) => listener()) } } interface PollSubscriber { readonly interval: number readonly when: 'always' | 'visible' readonly refresh: () => Promise } interface PollScheduler { readonly subscribers: Map timer: ReturnType | undefined onVisibility?: () => void } const pollers = new WeakMap>() /** Adapt exact Store pages into a tear-free React resource without a parallel entity cache. */ export function useStoreResource( query: Query | null, pageSize: number, project: (response: StoreQueryResponse) => Output, options: StoreResourceOptions = {}, ): GraphResource { const store = useGraphStore() const observer = useMemo( () => (query === null ? null : new StoreObserver(store, query, positivePage(pageSize))), [store, query, pageSize], ) const subscribe = useCallback( (listener: () => void) => (observer === null ? () => {} : observer.subscribe(listener)), [observer], ) const idle = useMemo>( () => Object.freeze({ snapshots: Object.freeze([]), pendingMore: false }), [], ) const getSnapshot = useCallback(() => observer?.getSnapshot() ?? idle, [observer, idle]) const current = useSyncExternalStore(subscribe, getSnapshot, getSnapshot) useEffect(() => observer?.start(), [observer]) const pollIdentity = query === null ? null : `${options.identity ?? JSON.stringify(query)}\u0000${pageSize}` useEffect(() => { if (query === null || observer === null || options.refreshInterval === undefined) return return retainRefreshScheduler( store, pollIdentity!, () => observer.refresh(), options.refreshInterval, options.refreshWhen ?? 'visible', ) }, [store, query, observer, pollIdentity, options.refreshInterval, options.refreshWhen]) const refresh = useCallback(async (): Promise => observer?.refresh(), [observer]) const loadMore = useCallback(async (): Promise => observer?.loadMore(), [observer]) const identity = options.identity ?? pollIdentity ?? 'idle' const projected = useMemo(() => { const responses: StoreQueryResponse[] = current.snapshots.flatMap((snapshot) => { const response = responseOf(snapshot) return response === undefined ? [] : [response] }) if (responses.length === 0) return undefined const pages = responses.map(project) if ((options.window ?? 'page') === 'page') return pages[0] return options.merge?.(pages) ?? mergeAppendPages(pages) }, [current, project, options.window, options.merge]) const previousRef = useRef<{ readonly identity: string; readonly data: Output } | undefined>( undefined, ) const prior = previousRef.current const previous = options.keepPrevious && prior !== undefined && prior.identity !== identity ? prior : undefined useEffect(() => { if (projected !== undefined) previousRef.current = Object.freeze({ identity, data: projected }) }, [identity, projected]) return useMemo(() => { const snapshots = current.snapshots const state = query === null ? 'idle' : combinedState(snapshots) const failed = snapshots.find((snapshot) => snapshot.state === 'failed') return Object.freeze({ state, data: projected, ...(failed?.state === 'failed' ? { error: failed.error } : { error: undefined }), ...(previous === undefined ? {} : { previous }), transitioning: state === 'loading' || state === 'refreshing', live: false as const, sequence: 0 as const, refresh, more: Object.freeze({ has: observer?.hasMore() ?? false, pending: current.pendingMore, load: loadMore, }), }) }, [current, query, projected, previous, refresh, observer, loadMore]) } function combinedState(snapshots: readonly StoreSnapshot[]): GraphResourceState { if (snapshots.length === 0 || snapshots.some((snapshot) => snapshot.state === 'cold')) return 'loading' for (const state of ['failed', 'loading', 'refreshing', 'optimistic', 'stale'] as const) { if (snapshots.some((snapshot) => snapshot.state === state)) return state } return 'ready' } function responseOf( snapshot: StoreSnapshot, ): StoreQueryResponse | undefined { return 'response' in snapshot ? snapshot.response : undefined } function mergeAppendPages(pages: readonly Output[]): Output { const first = pages[0] if (!Array.isArray(first)) return pages[pages.length - 1] as Output const seen = new Set() const merged: unknown[] = [] for (const page of pages as readonly (readonly unknown[])[]) { for (const value of page) { const identity = value !== null && typeof value === 'object' && 'id' in value ? (value as { readonly id: unknown }).id : value if (seen.has(identity)) continue seen.add(identity) merged.push(value) } } return Object.freeze(merged) as Output } export function retainRefreshScheduler( store: GraphStore, identity: string, refresh: () => Promise, interval: number, when: 'always' | 'visible', ): () => void { if (!Number.isSafeInteger(interval) || interval < 250) { throw new TypeError('refreshInterval must be an integer of at least 250ms.') } let byIdentity = pollers.get(store) if (byIdentity === undefined) { byIdentity = new Map() pollers.set(store, byIdentity) } let scheduler = byIdentity.get(identity) if (scheduler === undefined) { scheduler = { subscribers: new Map(), timer: undefined } byIdentity.set(identity, scheduler) } const token = Symbol(identity) scheduler.subscribers.set(token, { interval, when, refresh }) schedulePoll(scheduler) if (typeof document !== 'undefined' && scheduler.onVisibility === undefined) { scheduler.onVisibility = () => schedulePoll(scheduler!, true) document.addEventListener('visibilitychange', scheduler.onVisibility) } return () => { scheduler!.subscribers.delete(token) if (scheduler!.subscribers.size !== 0) { schedulePoll(scheduler!) return } if (scheduler!.timer !== undefined) clearTimeout(scheduler!.timer) if (typeof document !== 'undefined' && scheduler!.onVisibility !== undefined) { document.removeEventListener('visibilitychange', scheduler!.onVisibility) } byIdentity!.delete(identity) if (byIdentity!.size === 0) pollers.delete(store) } } function schedulePoll(scheduler: PollScheduler, immediate = false): void { if (scheduler.timer !== undefined) clearTimeout(scheduler.timer) const subscribers = [...scheduler.subscribers.values()] if (subscribers.length === 0) return const interval = Math.min(...subscribers.map((subscriber) => subscriber.interval)) scheduler.timer = setTimeout( () => { scheduler.timer = undefined const visible = typeof document === 'undefined' || document.visibilityState !== 'hidden' const eligible = [...scheduler.subscribers.values()].filter( (subscriber) => subscriber.when === 'always' || visible, ) eligible.forEach((subscriber) => void subscriber.refresh().catch(() => {})) schedulePoll(scheduler) }, immediate ? 0 : interval, ) } function positivePage(input: number): number { if (!Number.isSafeInteger(input) || input < 1) { throw new TypeError('Graph resource page size must be a positive safe integer.') } return input }