this repo has no description
1import { atom } from 'jotai';
2import { atomFamily } from 'jotai/utils';
3import type { EsavDocument, QueryState, LogEntry } from './types';
4const MAX_LOG_SIZE = 500;
5
6/**
7 * Manages the WebSocket instance itself.
8 * Should only be written to by the provider.
9 */
10export const websocketAtom = atom<WebSocket | null>(null);
11
12/**
13 * Tracks the current status of the WebSocket connection.
14 */
15export const websocketStatusAtom = atom<'connecting' | 'open' | 'closed'>('closed');
16
17/**
18 * A global, normalized cache for all documents received from the server.
19 * Maps a document URI (at://...) to its full data.
20 * This prevents data duplication across multiple queries.
21 */
22export const documentsAtom = atom<Record<string, EsavDocument>>({});
23
24/**
25 * A family of atoms to hold the state for each individual query.
26 * You get the state for a query by providing its unique queryId.
27 */
28export const queryStateFamily = atomFamily((_queryId: string) =>
29 atom<QueryState | null>(null)
30);
31
32/**
33 * Tracks active subscriptions and their component usage count.
34 * This is an internal atom used by our hooks to know when to
35 * send `subscribe` and `unsubscribe` messages.
36 */
37export const activeSubscriptionsAtom = atom<
38 Record<string, { count: number; esQuery: Record<string, any> }>
39>({});
40
41
42/**
43 * Holds the array of log entries for display.
44 */
45export const logEntriesAtom = atom<LogEntry[]>([]);
46
47let logIdCounter = 0;
48
49/**
50 * A "write-only" atom to add a new entry to the log.
51 * This encapsulates the logic for creating a new entry with an ID and timestamp.
52 * Any component can call this to add a log without needing to know the implementation details.
53 */
54export const addLogEntryAtom = atom(
55 null,
56 (get, set, newEntry: Omit<LogEntry, 'id' | 'timestamp'>) => {
57 const entry: LogEntry = {
58 id: logIdCounter++,
59 timestamp: new Date(),
60 ...newEntry,
61 };
62 const currentLog = get(logEntriesAtom);
63 const newLog = [entry, ...currentLog];
64 if (newLog.length > MAX_LOG_SIZE) {
65 newLog.length = MAX_LOG_SIZE;
66 }
67 set(logEntriesAtom, newLog);
68 }
69);
70
71export const queryCacheAtom = atom<Record<string, QueryState>>({});