@instantdb/react-common 0.22.75 → 0.22.76
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/commonjs/InstantReactAbstractDatabase.d.ts +8 -6
- package/dist/commonjs/InstantReactAbstractDatabase.d.ts.map +1 -1
- package/dist/commonjs/InstantReactAbstractDatabase.js.map +1 -1
- package/dist/commonjs/InstantReactRoom.js.map +1 -1
- package/dist/commonjs/useQuery.d.ts.map +1 -1
- package/dist/commonjs/useQuery.js +7 -1
- package/dist/commonjs/useQuery.js.map +1 -1
- package/dist/commonjs/useTimeout.d.ts.map +1 -1
- package/dist/commonjs/useTimeout.js +4 -2
- package/dist/commonjs/useTimeout.js.map +1 -1
- package/dist/esm/InstantReactAbstractDatabase.d.ts +8 -6
- package/dist/esm/InstantReactAbstractDatabase.d.ts.map +1 -1
- package/dist/esm/InstantReactAbstractDatabase.js.map +1 -1
- package/dist/esm/InstantReactRoom.js.map +1 -1
- package/dist/esm/useQuery.d.ts.map +1 -1
- package/dist/esm/useQuery.js +7 -1
- package/dist/esm/useQuery.js.map +1 -1
- package/dist/esm/useTimeout.d.ts.map +1 -1
- package/dist/esm/useTimeout.js +4 -2
- package/dist/esm/useTimeout.js.map +1 -1
- package/dist/standalone/index.js +137 -126
- package/dist/standalone/index.umd.cjs +9 -9
- package/package.json +4 -3
- package/src/InstantReactAbstractDatabase.tsx +15 -13
- package/src/InstantReactRoom.ts +1 -1
- package/src/useQuery.ts +4 -1
- package/src/useTimeout.ts +5 -3
- package/tsconfig.json +2 -1
|
@@ -1,17 +1,19 @@
|
|
|
1
1
|
import { Auth, Storage, type AuthState, type User, type ConnectionStatus, type TransactionChunk, type RoomSchemaShape, type InstaQLOptions, type InstantConfig, type PageInfoResponse, InstantCoreDatabase, InstaQLLifecycleState, InstaQLResponse, RoomsOf, InstantSchemaDef, IInstantDatabase, ValidQuery } from '@instantdb/core';
|
|
2
2
|
import { ReactNode } from 'react';
|
|
3
3
|
import { InstantReactRoom } from './InstantReactRoom.ts';
|
|
4
|
-
export default abstract class InstantReactAbstractDatabase<Schema extends InstantSchemaDef<any, any, any>, Config extends InstantConfig<Schema, boolean
|
|
4
|
+
export default abstract class InstantReactAbstractDatabase<Schema extends InstantSchemaDef<any, any, any>, UseDates extends boolean = false, Config extends InstantConfig<Schema, boolean> = InstantConfig<Schema, UseDates>, Rooms extends RoomSchemaShape = RoomsOf<Schema>> implements IInstantDatabase<Schema> {
|
|
5
5
|
tx: import("@instantdb/core").TxChunk<Schema>;
|
|
6
6
|
auth: Auth;
|
|
7
7
|
storage: Storage;
|
|
8
|
-
core: InstantCoreDatabase<Schema,
|
|
8
|
+
core: InstantCoreDatabase<Schema, UseDates>;
|
|
9
9
|
/** @deprecated use `core` instead */
|
|
10
|
-
_core: InstantCoreDatabase<Schema,
|
|
10
|
+
_core: InstantCoreDatabase<Schema, UseDates>;
|
|
11
11
|
static Storage?: any;
|
|
12
12
|
static NetworkListener?: any;
|
|
13
13
|
static EventSourceImpl?: any;
|
|
14
|
-
constructor(config:
|
|
14
|
+
constructor(config: Omit<InstantConfig<Schema, UseDates>, 'useDateObjects'> & {
|
|
15
|
+
useDateObjects?: UseDates;
|
|
16
|
+
}, versions?: {
|
|
15
17
|
[key: string]: string;
|
|
16
18
|
});
|
|
17
19
|
/**
|
|
@@ -115,7 +117,7 @@ export default abstract class InstantReactAbstractDatabase<Schema extends Instan
|
|
|
115
117
|
* auth.user ? { goals: {} } : null,
|
|
116
118
|
* );
|
|
117
119
|
*/
|
|
118
|
-
useQuery: <Q extends ValidQuery<Q, Schema>>(query: null | Q, opts?: InstaQLOptions) => InstaQLLifecycleState<Schema, Q,
|
|
120
|
+
useQuery: <Q extends ValidQuery<Q, Schema>>(query: null | Q, opts?: InstaQLOptions) => InstaQLLifecycleState<Schema, Q, UseDates>;
|
|
119
121
|
/**
|
|
120
122
|
* Listen for the logged in state. This is useful
|
|
121
123
|
* for deciding when to show a login screen.
|
|
@@ -208,7 +210,7 @@ export default abstract class InstantReactAbstractDatabase<Schema extends Instan
|
|
|
208
210
|
* console.log(resp.data.goals)
|
|
209
211
|
*/
|
|
210
212
|
queryOnce: <Q extends ValidQuery<Q, Schema>>(query: Q, opts?: InstaQLOptions) => Promise<{
|
|
211
|
-
data: InstaQLResponse<Schema, Q,
|
|
213
|
+
data: InstaQLResponse<Schema, Q, UseDates>;
|
|
212
214
|
pageInfo: PageInfoResponse<Q>;
|
|
213
215
|
}>;
|
|
214
216
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"InstantReactAbstractDatabase.d.ts","sourceRoot":"","sources":["../../src/InstantReactAbstractDatabase.tsx"],"names":[],"mappings":"AAAA,OAAO,EAEL,IAAI,EACJ,OAAO,EAEP,KAAK,SAAS,EACd,KAAK,IAAI,EACT,KAAK,gBAAgB,EACrB,KAAK,gBAAgB,EACrB,KAAK,eAAe,EAEpB,KAAK,cAAc,EACnB,KAAK,aAAa,EAClB,KAAK,gBAAgB,EACrB,mBAAmB,EAEnB,qBAAqB,EACrB,eAAe,EACf,OAAO,EACP,gBAAgB,EAChB,gBAAgB,EAEhB,UAAU,EACX,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,SAAS,EAMV,MAAM,OAAO,CAAC;AAEf,OAAO,EAAE,gBAAgB,EAAS,MAAM,uBAAuB,CAAC;AAQhE,MAAM,CAAC,OAAO,CAAC,QAAQ,OAAO,4BAA4B,CAExD,MAAM,SAAS,gBAAgB,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,EAC9C,MAAM,SAAS,aAAa,CAAC,MAAM,EAAE,OAAO,
|
|
1
|
+
{"version":3,"file":"InstantReactAbstractDatabase.d.ts","sourceRoot":"","sources":["../../src/InstantReactAbstractDatabase.tsx"],"names":[],"mappings":"AAAA,OAAO,EAEL,IAAI,EACJ,OAAO,EAEP,KAAK,SAAS,EACd,KAAK,IAAI,EACT,KAAK,gBAAgB,EACrB,KAAK,gBAAgB,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gB,CAA0B,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,CAAC;IAC5E,CAAC;IAgKD;;;;;;;;;OASG;IACH,OAAO;QACL,OAAO,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;IAC7B,CAAC;CA6GF;AA1XD,+CA0XC","sourcesContent":["import {\n // types\n Auth,\n Storage,\n txInit,\n type AuthState,\n type User,\n type ConnectionStatus,\n type TransactionChunk,\n type RoomSchemaShape,\n type InstaQLParams,\n type InstaQLOptions,\n type InstantConfig,\n type PageInfoResponse,\n InstantCoreDatabase,\n init as core_init,\n InstaQLLifecycleState,\n InstaQLResponse,\n RoomsOf,\n InstantSchemaDef,\n IInstantDatabase,\n InstantError,\n ValidQuery,\n} from '@instantdb/core';\nimport {\n ReactNode,\n useCallback,\n useEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from 'react';\nimport { useQueryInternal } from './useQuery.ts';\nimport { InstantReactRoom, rooms } from './InstantReactRoom.ts';\n\nconst defaultAuthState = {\n isLoading: true,\n user: undefined,\n error: undefined,\n};\n\nexport default abstract class InstantReactAbstractDatabase<\n // need to pull this schema out to another generic for query params, not sure why\n Schema extends InstantSchemaDef<any, any, any>,\n Config extends InstantConfig<Schema, boolean | undefined> = InstantConfig<\n Schema,\n boolean\n >,\n Rooms extends RoomSchemaShape = RoomsOf<Schema>,\n> implements IInstantDatabase<Schema>\n{\n public tx = txInit<Schema>();\n\n public auth: Auth;\n public storage: Storage;\n public core: InstantCoreDatabase<Schema, Config['useDateObjects']>;\n\n /** @deprecated use `core` instead */\n public _core: InstantCoreDatabase<Schema, Config['useDateObjects']>;\n\n static Storage?: any;\n static NetworkListener?: any;\n static EventSourceImpl?: any;\n\n constructor(config: Config, versions?: { [key: string]: string }) {\n this.core = core_init<Schema, Config['useDateObjects']>(\n config,\n // @ts-expect-error because TS can't resolve subclass statics\n this.constructor.Storage,\n // @ts-expect-error because TS can't resolve subclass statics\n this.constructor.NetworkListener,\n versions,\n // @ts-expect-error because TS can't resolve subclass statics\n this.constructor.EventSourceImpl,\n );\n this._core = this.core;\n this.auth = this.core.auth;\n this.storage = this.core.storage;\n }\n\n /**\n * Returns a unique ID for a given `name`. It's stored in local storage,\n * so you will get the same ID across sessions.\n *\n * This is useful for generating IDs that could identify a local device or user.\n *\n * @example\n * const deviceId = await db.getLocalId('device');\n */\n getLocalId = (name: string): Promise<string> => {\n return this.core.getLocalId(name);\n };\n\n /**\n * A hook that returns a unique ID for a given `name`. localIds are\n * stored in local storage, so you will get the same ID across sessions.\n *\n * Initially returns `null`, and then loads the localId.\n *\n * @example\n * const deviceId = db.useLocalId('device');\n * if (!deviceId) return null; // loading\n * console.log('Device ID:', deviceId)\n */\n useLocalId = (name: string): string | null => {\n const [localId, setLocalId] = useState<string | null>(null);\n\n useEffect(() => {\n let mounted = true;\n const f = async () => {\n const id = await this.getLocalId(name);\n if (!mounted) return;\n setLocalId(id);\n };\n f();\n return;\n }, [name]);\n\n return localId;\n };\n\n /**\n * Obtain a handle to a room, which allows you to listen to topics and presence data\n *\n * If you don't provide a `type` or `id`, Instant will default to `_defaultRoomType` and `_defaultRoomId`\n * as the room type and id, respectively.\n *\n * @see https://instantdb.com/docs/presence-and-topics\n *\n * @example\n * const room = db.room('chat', roomId);\n * const { peers } = db.rooms.usePresence(room);\n */\n room<RoomType extends keyof Rooms>(\n type: RoomType = '_defaultRoomType' as RoomType,\n id: string = '_defaultRoomId',\n ) {\n return new InstantReactRoom<Schema, Rooms, RoomType>(this.core, type, id);\n }\n\n /**\n * Hooks for working with rooms\n *\n * @see https://instantdb.com/docs/presence-and-topics\n *\n * @example\n * const room = db.room('chat', roomId);\n * const { peers } = db.rooms.usePresence(room);\n * const publish = db.rooms.usePublishTopic(room, 'emoji');\n * // ...\n */\n rooms = rooms;\n\n /**\n * Use this to write data! You can create, update, delete, and link objects\n *\n * @see https://instantdb.com/docs/instaml\n *\n * @example\n * // Create a new object in the `goals` namespace\n * const goalId = id();\n * db.transact(db.tx.goals[goalId].update({title: \"Get fit\"}))\n *\n * // Update the title\n * db.transact(db.tx.goals[goalId].update({title: \"Get super fit\"}))\n *\n * // Delete it\n * db.transact(db.tx.goals[goalId].delete())\n *\n * // Or create an association:\n * todoId = id();\n * db.transact([\n * db.tx.todos[todoId].update({ title: 'Go on a run' }),\n * db.tx.goals[goalId].link({todos: todoId}),\n * ])\n */\n transact = (\n chunks: TransactionChunk<any, any> | TransactionChunk<any, any>[],\n ) => {\n return this.core.transact(chunks);\n };\n\n /**\n * Use this to query your data!\n *\n * @see https://instantdb.com/docs/instaql\n *\n * @example\n * // listen to all goals\n * const { isLoading, error, data } = db.useQuery({ goals: {} });\n *\n * // goals where the title is \"Get Fit\"\n * const { isLoading, error, data } = db.useQuery({\n * goals: { $: { where: { title: 'Get Fit' } } },\n * });\n *\n * // all goals, _alongside_ their todos\n * const { isLoading, error, data } = db.useQuery({\n * goals: { todos: {} },\n * });\n *\n * // skip if `user` is not logged in\n * const { isLoading, error, data } = db.useQuery(\n * auth.user ? { goals: {} } : null,\n * );\n */\n useQuery = <Q extends ValidQuery<Q, Schema>>(\n query: null | Q,\n opts?: InstaQLOptions,\n ): InstaQLLifecycleState<Schema, Q, Config['useDateObjects']> => {\n return useQueryInternal<Q, Schema, Config['useDateObjects']>(\n this.core,\n query,\n opts,\n ).state;\n };\n\n /**\n * Listen for the logged in state. This is useful\n * for deciding when to show a login screen.\n *\n * Check out the docs for an example `Login` component too!\n *\n * @see https://instantdb.com/docs/auth\n * @example\n * function App() {\n * const { isLoading, user, error } = db.useAuth()\n * if (isLoading) {\n * return <div>Loading...</div>\n * }\n * if (error) {\n * return <div>Uh oh! {error.message}</div>\n * }\n * if (user) {\n * return <Main user={user} />\n * }\n * return <Login />\n * }\n *\n */\n useAuth = (): AuthState => {\n // We use a ref to store the result of the query.\n // This is becuase `useSyncExternalStore` uses `Object.is`\n // to compare the previous and next state.\n // If we don't use a ref, the state will always be considered different, so\n // the component will always re-render.\n const resultCacheRef = useRef<AuthState>(\n this.core._reactor._currentUserCached,\n );\n\n // Similar to `resultCacheRef`, `useSyncExternalStore` will unsubscribe\n // if `subscribe` changes, so we use `useCallback` to memoize the function.\n const subscribe = useCallback((cb: Function) => {\n const unsubscribe = this.core.subscribeAuth((auth) => {\n resultCacheRef.current = { isLoading: false, ...auth };\n cb();\n });\n\n return unsubscribe;\n }, []);\n\n const state = useSyncExternalStore<AuthState>(\n subscribe,\n () => resultCacheRef.current,\n () => defaultAuthState,\n );\n return state;\n };\n\n /**\n * Subscribe to the currently logged in user.\n * If the user is not logged in, this hook with throw an Error.\n * You will want to protect any calls of this hook with a\n * <db.SignedIn> component, or your own logic based on db.useAuth()\n *\n * @see https://instantdb.com/docs/auth\n * @throws Error indicating user not signed in\n * @example\n * function UserDisplay() {\n * const user = db.useUser()\n * return <div>Logged in as: {user.email}</div>\n * }\n *\n * <db.SignedIn>\n * <UserDisplay />\n * </db.SignedIn>\n *\n */\n useUser = (): User => {\n const { user } = this.useAuth();\n if (!user) {\n throw new InstantError(\n 'useUser must be used within an auth-protected route',\n );\n }\n return user;\n };\n\n /**\n * One time query for the logged in state. This is useful\n * for scenarios where you want to know the current auth\n * state without subscribing to changes.\n *\n * @see https://instantdb.com/docs/auth\n * @example\n * const user = await db.getAuth();\n * console.log('logged in as', user.email)\n */\n getAuth(): Promise<User | null> {\n return this.core.getAuth();\n }\n\n /**\n * Listen for connection status changes to Instant. Use this for things like\n * showing connection state to users\n *\n * @see https://www.instantdb.com/docs/patterns#connection-status\n * @example\n * function App() {\n * const status = db.useConnectionStatus()\n * const connectionState =\n * status === 'connecting' || status === 'opened'\n * ? 'authenticating'\n * : status === 'authenticated'\n * ? 'connected'\n * : status === 'closed'\n * ? 'closed'\n * : status === 'errored'\n * ? 'errored'\n * : 'unexpected state';\n *\n * return <div>Connection state: {connectionState}</div>\n * }\n */\n useConnectionStatus = (): ConnectionStatus => {\n const statusRef = useRef<ConnectionStatus>(\n this.core._reactor.status as ConnectionStatus,\n );\n\n const subscribe = useCallback((cb: Function) => {\n const unsubscribe = this.core.subscribeConnectionStatus((newStatus) => {\n if (newStatus !== statusRef.current) {\n statusRef.current = newStatus;\n cb();\n }\n });\n\n return unsubscribe;\n }, []);\n\n const status = useSyncExternalStore<ConnectionStatus>(\n subscribe,\n () => statusRef.current,\n // For SSR, always return 'connecting' as the initial state\n () => 'connecting',\n );\n\n return status;\n };\n\n /**\n * Use this for one-off queries.\n * Returns local data if available, otherwise fetches from the server.\n * Because we want to avoid stale data, this method will throw an error\n * if the user is offline or there is no active connection to the server.\n *\n * @see https://instantdb.com/docs/instaql\n *\n * @example\n *\n * const resp = await db.queryOnce({ goals: {} });\n * console.log(resp.data.goals)\n */\n queryOnce = <Q extends ValidQuery<Q, Schema>>(\n query: Q,\n opts?: InstaQLOptions,\n ): Promise<{\n data: InstaQLResponse<Schema, Q, Config['useDateObjects']>;\n pageInfo: PageInfoResponse<Q>;\n }> => {\n return this.core.queryOnce(query, opts);\n };\n\n /**\n * Only render children if the user is signed in.\n * @see https://instantdb.com/docs/auth\n *\n * @example\n * <db.SignedIn>\n * <MyComponent />\n * </db.SignedIn>\n *\n */\n SignedIn: React.FC<{\n children: ReactNode;\n }> = ({ children }) => {\n const auth = this.useAuth();\n if (auth.isLoading || auth.error || !auth.user) return null;\n\n return <>{children}</>;\n };\n\n /**\n * Only render children if the user is signed out.\n * @see https://instantdb.com/docs/auth\n *\n * @example\n * <db.SignedOut>\n * <MyComponent />\n * </db.SignedOut>\n *\n */\n SignedOut: React.FC<{\n children: ReactNode;\n }> = ({ children }) => {\n const auth = this.useAuth();\n if (auth.isLoading || auth.error || auth.user) return null;\n return <>{children}</>;\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"InstantReactAbstractDatabase.js","sourceRoot":"","sources":["../../src/InstantReactAbstractDatabase.tsx"],"names":[],"mappings":";;;;;;;;;;;;AAAA,0CAuByB;AACzB,iCAOe;AACf,+CAAiD;AACjD,+DAAgE;AAEhE,MAAM,g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B,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,EAAE,CAAC;YAC5B,IAAI,IAAI,CAAC,SAAS,IAAI,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,IAAI;gBAAE,OAAO,IAAI,CAAC;YAC3D,OAAO,2DAAG,QAAQ,GAAI,CAAC;QACzB,CAAC,CAAC;QA7VA,IAAI,CAAC,IAAI,GAAG,IAAA,WAAS,EACnB,MAAM;QACN,6DAA6D;QAC7D,IAAI,CAAC,WAAW,CAAC,OAAO;QACxB,6DAA6D;QAC7D,IAAI,CAAC,WAAW,CAAC,eAAe,EAChC,QAAQ;QACR,6DAA6D;QAC7D,IAAI,CAAC,WAAW,CAAC,eAAe,CACjC,CAAC;QACF,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,IAAI,CAAC;QACvB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC;QAC3B,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC;IACnC,CAAC;IA2CD;;;;;;;;;;;OAWG;IACH,IAAI,CACF,OAAiB,kBAA8B,EAC/C,KAAa,gBAAgB;QAE7B,OAAO,IAAI,sCAAgB,CAA0B,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,CAAC;IAC5E,CAAC;IA4JD;;;;;;;;;OASG;IACH,OAAO;QACL,OAAO,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;IAC7B,CAAC;CA6GF;AA5XD,+CA4XC","sourcesContent":["import {\n // types\n Auth,\n Storage,\n txInit,\n type AuthState,\n type User,\n type ConnectionStatus,\n type TransactionChunk,\n type RoomSchemaShape,\n type InstaQLParams,\n type InstaQLOptions,\n type InstantConfig,\n type PageInfoResponse,\n InstantCoreDatabase,\n init as core_init,\n InstaQLLifecycleState,\n InstaQLResponse,\n RoomsOf,\n InstantSchemaDef,\n IInstantDatabase,\n InstantError,\n ValidQuery,\n} from '@instantdb/core';\nimport {\n ReactNode,\n useCallback,\n useEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from 'react';\nimport { useQueryInternal } from './useQuery.ts';\nimport { InstantReactRoom, rooms } from './InstantReactRoom.ts';\n\nconst defaultAuthState = {\n isLoading: true,\n user: undefined,\n error: undefined,\n};\n\nexport default abstract class InstantReactAbstractDatabase<\n // need to pull this schema out to another generic for query params, not sure why\n Schema extends InstantSchemaDef<any, any, any>,\n UseDates extends boolean = false,\n Config extends InstantConfig<Schema, boolean> = InstantConfig<\n Schema,\n UseDates\n >,\n Rooms extends RoomSchemaShape = RoomsOf<Schema>,\n> implements IInstantDatabase<Schema>\n{\n public tx = txInit<Schema>();\n\n public auth: Auth;\n public storage: Storage;\n public core: InstantCoreDatabase<Schema, UseDates>;\n\n /** @deprecated use `core` instead */\n public _core: InstantCoreDatabase<Schema, UseDates>;\n\n static Storage?: any;\n static NetworkListener?: any;\n static EventSourceImpl?: any;\n\n constructor(\n config: Omit<InstantConfig<Schema, UseDates>, 'useDateObjects'> & {\n useDateObjects?: UseDates;\n },\n versions?: { [key: string]: string },\n ) {\n this.core = core_init<Schema, UseDates>(\n config,\n // @ts-expect-error because TS can't resolve subclass statics\n this.constructor.Storage,\n // @ts-expect-error because TS can't resolve subclass statics\n this.constructor.NetworkListener,\n versions,\n // @ts-expect-error because TS can't resolve subclass statics\n this.constructor.EventSourceImpl,\n );\n this._core = this.core;\n this.auth = this.core.auth;\n this.storage = this.core.storage;\n }\n\n /**\n * Returns a unique ID for a given `name`. It's stored in local storage,\n * so you will get the same ID across sessions.\n *\n * This is useful for generating IDs that could identify a local device or user.\n *\n * @example\n * const deviceId = await db.getLocalId('device');\n */\n getLocalId = (name: string): Promise<string> => {\n return this.core.getLocalId(name);\n };\n\n /**\n * A hook that returns a unique ID for a given `name`. localIds are\n * stored in local storage, so you will get the same ID across sessions.\n *\n * Initially returns `null`, and then loads the localId.\n *\n * @example\n * const deviceId = db.useLocalId('device');\n * if (!deviceId) return null; // loading\n * console.log('Device ID:', deviceId)\n */\n useLocalId = (name: string): string | null => {\n const [localId, setLocalId] = useState<string | null>(null);\n\n useEffect(() => {\n let mounted = true;\n const f = async () => {\n const id = await this.getLocalId(name);\n if (!mounted) return;\n setLocalId(id);\n };\n f();\n return;\n }, [name]);\n\n return localId;\n };\n\n /**\n * Obtain a handle to a room, which allows you to listen to topics and presence data\n *\n * If you don't provide a `type` or `id`, Instant will default to `_defaultRoomType` and `_defaultRoomId`\n * as the room type and id, respectively.\n *\n * @see https://instantdb.com/docs/presence-and-topics\n *\n * @example\n * const room = db.room('chat', roomId);\n * const { peers } = db.rooms.usePresence(room);\n */\n room<RoomType extends keyof Rooms>(\n type: RoomType = '_defaultRoomType' as RoomType,\n id: string = '_defaultRoomId',\n ) {\n return new InstantReactRoom<Schema, Rooms, RoomType>(this.core, type, id);\n }\n\n /**\n * Hooks for working with rooms\n *\n * @see https://instantdb.com/docs/presence-and-topics\n *\n * @example\n * const room = db.room('chat', roomId);\n * const { peers } = db.rooms.usePresence(room);\n * const publish = db.rooms.usePublishTopic(room, 'emoji');\n * // ...\n */\n rooms = rooms;\n\n /**\n * Use this to write data! You can create, update, delete, and link objects\n *\n * @see https://instantdb.com/docs/instaml\n *\n * @example\n * // Create a new object in the `goals` namespace\n * const goalId = id();\n * db.transact(db.tx.goals[goalId].update({title: \"Get fit\"}))\n *\n * // Update the title\n * db.transact(db.tx.goals[goalId].update({title: \"Get super fit\"}))\n *\n * // Delete it\n * db.transact(db.tx.goals[goalId].delete())\n *\n * // Or create an association:\n * todoId = id();\n * db.transact([\n * db.tx.todos[todoId].update({ title: 'Go on a run' }),\n * db.tx.goals[goalId].link({todos: todoId}),\n * ])\n */\n transact = (\n chunks: TransactionChunk<any, any> | TransactionChunk<any, any>[],\n ) => {\n return this.core.transact(chunks);\n };\n\n /**\n * Use this to query your data!\n *\n * @see https://instantdb.com/docs/instaql\n *\n * @example\n * // listen to all goals\n * const { isLoading, error, data } = db.useQuery({ goals: {} });\n *\n * // goals where the title is \"Get Fit\"\n * const { isLoading, error, data } = db.useQuery({\n * goals: { $: { where: { title: 'Get Fit' } } },\n * });\n *\n * // all goals, _alongside_ their todos\n * const { isLoading, error, data } = db.useQuery({\n * goals: { todos: {} },\n * });\n *\n * // skip if `user` is not logged in\n * const { isLoading, error, data } = db.useQuery(\n * auth.user ? { goals: {} } : null,\n * );\n */\n useQuery = <Q extends ValidQuery<Q, Schema>>(\n query: null | Q,\n opts?: InstaQLOptions,\n ): InstaQLLifecycleState<Schema, Q, UseDates> => {\n return useQueryInternal<Q, Schema, UseDates>(this.core, query, opts).state;\n };\n\n /**\n * Listen for the logged in state. This is useful\n * for deciding when to show a login screen.\n *\n * Check out the docs for an example `Login` component too!\n *\n * @see https://instantdb.com/docs/auth\n * @example\n * function App() {\n * const { isLoading, user, error } = db.useAuth()\n * if (isLoading) {\n * return <div>Loading...</div>\n * }\n * if (error) {\n * return <div>Uh oh! {error.message}</div>\n * }\n * if (user) {\n * return <Main user={user} />\n * }\n * return <Login />\n * }\n *\n */\n useAuth = (): AuthState => {\n // We use a ref to store the result of the query.\n // This is becuase `useSyncExternalStore` uses `Object.is`\n // to compare the previous and next state.\n // If we don't use a ref, the state will always be considered different, so\n // the component will always re-render.\n const resultCacheRef = useRef<AuthState>(\n this.core._reactor._currentUserCached,\n );\n\n // Similar to `resultCacheRef`, `useSyncExternalStore` will unsubscribe\n // if `subscribe` changes, so we use `useCallback` to memoize the function.\n const subscribe = useCallback((cb: Function) => {\n const unsubscribe = this.core.subscribeAuth((auth) => {\n resultCacheRef.current = { isLoading: false, ...auth };\n cb();\n });\n\n return unsubscribe;\n }, []);\n\n const state = useSyncExternalStore<AuthState>(\n subscribe,\n () => resultCacheRef.current,\n () => defaultAuthState,\n );\n return state;\n };\n\n /**\n * Subscribe to the currently logged in user.\n * If the user is not logged in, this hook with throw an Error.\n * You will want to protect any calls of this hook with a\n * <db.SignedIn> component, or your own logic based on db.useAuth()\n *\n * @see https://instantdb.com/docs/auth\n * @throws Error indicating user not signed in\n * @example\n * function UserDisplay() {\n * const user = db.useUser()\n * return <div>Logged in as: {user.email}</div>\n * }\n *\n * <db.SignedIn>\n * <UserDisplay />\n * </db.SignedIn>\n *\n */\n useUser = (): User => {\n const { user } = this.useAuth();\n if (!user) {\n throw new InstantError(\n 'useUser must be used within an auth-protected route',\n );\n }\n return user;\n };\n\n /**\n * One time query for the logged in state. This is useful\n * for scenarios where you want to know the current auth\n * state without subscribing to changes.\n *\n * @see https://instantdb.com/docs/auth\n * @example\n * const user = await db.getAuth();\n * console.log('logged in as', user.email)\n */\n getAuth(): Promise<User | null> {\n return this.core.getAuth();\n }\n\n /**\n * Listen for connection status changes to Instant. Use this for things like\n * showing connection state to users\n *\n * @see https://www.instantdb.com/docs/patterns#connection-status\n * @example\n * function App() {\n * const status = db.useConnectionStatus()\n * const connectionState =\n * status === 'connecting' || status === 'opened'\n * ? 'authenticating'\n * : status === 'authenticated'\n * ? 'connected'\n * : status === 'closed'\n * ? 'closed'\n * : status === 'errored'\n * ? 'errored'\n * : 'unexpected state';\n *\n * return <div>Connection state: {connectionState}</div>\n * }\n */\n useConnectionStatus = (): ConnectionStatus => {\n const statusRef = useRef<ConnectionStatus>(\n this.core._reactor.status as ConnectionStatus,\n );\n\n const subscribe = useCallback((cb: Function) => {\n const unsubscribe = this.core.subscribeConnectionStatus((newStatus) => {\n if (newStatus !== statusRef.current) {\n statusRef.current = newStatus;\n cb();\n }\n });\n\n return unsubscribe;\n }, []);\n\n const status = useSyncExternalStore<ConnectionStatus>(\n subscribe,\n () => statusRef.current,\n // For SSR, always return 'connecting' as the initial state\n () => 'connecting',\n );\n\n return status;\n };\n\n /**\n * Use this for one-off queries.\n * Returns local data if available, otherwise fetches from the server.\n * Because we want to avoid stale data, this method will throw an error\n * if the user is offline or there is no active connection to the server.\n *\n * @see https://instantdb.com/docs/instaql\n *\n * @example\n *\n * const resp = await db.queryOnce({ goals: {} });\n * console.log(resp.data.goals)\n */\n queryOnce = <Q extends ValidQuery<Q, Schema>>(\n query: Q,\n opts?: InstaQLOptions,\n ): Promise<{\n data: InstaQLResponse<Schema, Q, UseDates>;\n pageInfo: PageInfoResponse<Q>;\n }> => {\n return this.core.queryOnce(query, opts);\n };\n\n /**\n * Only render children if the user is signed in.\n * @see https://instantdb.com/docs/auth\n *\n * @example\n * <db.SignedIn>\n * <MyComponent />\n * </db.SignedIn>\n *\n */\n SignedIn: React.FC<{\n children: ReactNode;\n }> = ({ children }) => {\n const auth = this.useAuth();\n if (auth.isLoading || auth.error || !auth.user) return null;\n\n return <>{children}</>;\n };\n\n /**\n * Only render children if the user is signed out.\n * @see https://instantdb.com/docs/auth\n *\n * @example\n * <db.SignedOut>\n * <MyComponent />\n * </db.SignedOut>\n *\n */\n SignedOut: React.FC<{\n children: ReactNode;\n }> = ({ children }) => {\n const auth = this.useAuth();\n if (auth.isLoading || auth.error || auth.user) return null;\n return <>{children}</>;\n };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"InstantReactRoom.js","sourceRoot":"","sources":["../../src/InstantReactRoom.ts"],"names":[],"mappings":";;;AA6DA,wCA0BC;AAiBD,0CAuBC;AAmBD,kCA6CC;AAYD,0CAYC;AAqBD,gDAmEC;AAtSD,iCAOe;AAEf,mDAA6C;AAyBhC,QAAA,0BAA0B,GAAG,IAAK,CAAC;AAEhD,SAAS;AACT,SAAS;AAET;;;;;;;;;;;;GAYG;AACH,SAAgB,cAAc,CAK5B,IAAiD,EACjD,KAAgB,EAChB,OAGQ;IAER,MAAM,UAAU,GAAG,IAAA,cAAM,EAAC,OAAO,CAAC,CAAC;IACnC,UAAU,CAAC,OAAO,GAAG,OAAO,CAAC;IAE7B,IAAA,iBAAS,EAAC,GAAG,EAAE;QACb,MAAM,KAAK,GAAG,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,cAAc,CAC7C,IAAI,CAAC,EAAE,EACP,KAAK,EACL,CAAC,KAAK,EAAE,IAAI,EAAE,EAA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,aAAK,CAAC,kBAAkB,CAAC,IAAI,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;QACzD,CAAC,CAAC;QA9GA,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,IAAI,CAAC;QACvB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;IACf,CAAC;CA2GF;AA/HD,4CA+HC","sourcesContent":["import {\n // types\n type PresenceOpts,\n type PresenceResponse,\n type RoomSchemaShape,\n InstantCoreDatabase,\n InstantSchemaDef,\n} from '@instantdb/core';\n\nimport {\n KeyboardEvent,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from 'react';\n\nimport { useTimeout } from './useTimeout.ts';\n\nexport type PresenceHandle<\n PresenceShape,\n Keys extends keyof PresenceShape,\n> = PresenceResponse<PresenceShape, Keys> & {\n publishPresence: (data: Partial<PresenceShape>) => void;\n};\n\nexport type TypingIndicatorOpts = {\n timeout?: number | null;\n stopOnEnter?: boolean;\n // Perf opt - `active` will always be an empty array\n writeOnly?: boolean;\n};\n\nexport type TypingIndicatorHandle<PresenceShape> = {\n active: PresenceShape[];\n setActive(active: boolean): void;\n inputProps: {\n onKeyDown: (e: KeyboardEvent) => void;\n onBlur: () => void;\n };\n};\n\nexport const defaultActivityStopTimeout = 1_000;\n\n// ------\n// Topics\n\n/**\n * Listen for broadcasted events given a room and topic.\n *\n * @see https://instantdb.com/docs/presence-and-topics\n * @example\n * function App({ roomId }) {\n * const room = db.room('chats', roomId);\n * db.rooms.useTopicEffect(room, 'emoji', (message, peer) => {\n * console.log(peer.name, 'sent', message);\n * });\n * // ...\n * }\n */\nexport function useTopicEffect<\n RoomSchema extends RoomSchemaShape,\n RoomType extends keyof RoomSchema,\n TopicType extends keyof RoomSchema[RoomType]['topics'],\n>(\n room: InstantReactRoom<any, RoomSchema, RoomType>,\n topic: TopicType,\n onEvent: (\n event: RoomSchema[RoomType]['topics'][TopicType],\n peer: RoomSchema[RoomType]['presence'],\n ) => any,\n): void {\n const onEventRef = useRef(onEvent);\n onEventRef.current = onEvent;\n\n useEffect(() => {\n const unsub = room.core._reactor.subscribeTopic(\n room.id,\n topic,\n (event, peer) => {\n onEventRef.current(event, peer);\n },\n );\n\n return unsub;\n }, [room.id, topic]);\n}\n\n/**\n * Broadcast an event to a room.\n *\n * @see https://instantdb.com/docs/presence-and-topics\n * @example\n * function App({ roomId }) {\n * const room = db.room('chat', roomId);\n * const publishTopic = db.rooms.usePublishTopic(room, \"emoji\");\n *\n * return (\n * <button onClick={() => publishTopic({ emoji: \"🔥\" })}>Send emoji</button>\n * );\n * }\n *\n */\nexport function usePublishTopic<\n RoomSchema extends RoomSchemaShape,\n RoomType extends keyof RoomSchema,\n TopicType extends keyof RoomSchema[RoomType]['topics'],\n>(\n room: InstantReactRoom<any, RoomSchema, RoomType>,\n topic: TopicType,\n): (data: RoomSchema[RoomType]['topics'][TopicType]) => void {\n useEffect(() => room.core._reactor.joinRoom(room.id), [room.id]);\n\n const publishTopic = useCallback(\n (data) => {\n room.core._reactor.publishTopic({\n roomType: room.type,\n roomId: room.id,\n topic,\n data,\n });\n },\n [room.id, topic],\n );\n\n return publishTopic;\n}\n\n// ---------\n// Presence\n\n/**\n * Listen for peer's presence data in a room, and publish the current user's presence.\n *\n * @see https://instantdb.com/docs/presence-and-topics\n * @example\n * function App({ roomId }) {\n * const {\n * peers,\n * publishPresence\n * } = db.room(roomType, roomId).usePresence({ keys: [\"name\", \"avatar\"] });\n *\n * // ...\n * }\n */\nexport function usePresence<\n RoomSchema extends RoomSchemaShape,\n RoomType extends keyof RoomSchema,\n Keys extends keyof RoomSchema[RoomType]['presence'],\n>(\n room: InstantReactRoom<any, RoomSchema, RoomType>,\n opts: PresenceOpts<RoomSchema[RoomType]['presence'], Keys> = {},\n): PresenceHandle<RoomSchema[RoomType]['presence'], Keys> {\n const [state, setState] = useState<\n PresenceResponse<RoomSchema[RoomType]['presence'], Keys>\n >(() => {\n return (\n room.core._reactor.getPresence(room.type, room.id, opts) ?? {\n peers: {},\n isLoading: true,\n }\n );\n });\n\n useEffect(() => {\n const unsub = room.core._reactor.subscribePresence(\n room.type,\n room.id,\n opts,\n (data) => {\n setState(data);\n },\n );\n\n return unsub;\n }, [room.id, opts.user, opts.peers?.join(), opts.keys?.join()]);\n\n const publishPresence = useCallback(\n (data) => {\n room.core._reactor.publishPresence(room.type, room.id, data);\n },\n [room.type, room.id],\n );\n const ret = useMemo(() => {\n return {\n ...state,\n publishPresence,\n };\n }, [state, publishPresence]);\n return ret;\n}\n\n/**\n * Publishes presence data to a room\n *\n * @see https://instantdb.com/docs/presence-and-topics\n * @example\n * function App({ roomId, nickname }) {\n * const room = db.room('chat', roomId);\n * db.rooms.useSyncPresence(room, { nickname });\n * }\n */\nexport function useSyncPresence<\n RoomSchema extends RoomSchemaShape,\n RoomType extends keyof RoomSchema,\n>(\n room: InstantReactRoom<any, RoomSchema, RoomType>,\n data: Partial<RoomSchema[RoomType]['presence']>,\n deps?: any[],\n): void {\n useEffect(() => room.core._reactor.joinRoom(room.id, data), [room.id]);\n useEffect(() => {\n return room.core._reactor.publishPresence(room.type, room.id, data);\n }, [room.type, room.id, deps ?? JSON.stringify(data)]);\n}\n\n// -----------------\n// Typing Indicator\n\n/**\n * Manage typing indicator state\n *\n * @see https://instantdb.com/docs/presence-and-topics\n * @example\n * function App({ roomId }) {\n * const room = db.room('chat', roomId);\n * const {\n * active,\n * setActive,\n * inputProps,\n * } = db.rooms.useTypingIndicator(room, \"chat-input\");\n *\n * return <input {...inputProps} />;\n * }\n */\nexport function useTypingIndicator<\n RoomSchema extends RoomSchemaShape,\n RoomType extends keyof RoomSchema,\n>(\n room: InstantReactRoom<any, RoomSchema, RoomType>,\n inputName: string,\n opts: TypingIndicatorOpts = {},\n): TypingIndicatorHandle<RoomSchema[RoomType]['presence']> {\n const timeout = useTimeout();\n\n const observedPresence = rooms.usePresence(room, {\n keys: [inputName],\n });\n\n const active = useMemo(() => {\n const presenceSnapshot = room._core._reactor.getPresence(\n room.type,\n room.id,\n );\n\n return opts?.writeOnly\n ? []\n : Object.values(presenceSnapshot?.peers ?? {}).filter(\n (p) => p[inputName] === true,\n );\n }, [opts?.writeOnly, observedPresence]);\n\n const setActive = useCallback(\n (isActive: boolean) => {\n room.core._reactor.publishPresence(room.type, room.id, {\n [inputName]: isActive,\n } as unknown as Partial<RoomSchema[RoomType]>);\n\n if (!isActive) return;\n\n if (opts?.timeout === null || opts?.timeout === 0) return;\n\n timeout.set(opts?.timeout ?? defaultActivityStopTimeout, () => {\n room.core._reactor.publishPresence(room.type, room.id, {\n [inputName]: null,\n } as Partial<RoomSchema[RoomType]>);\n });\n },\n [room.type, room.id, inputName, opts?.timeout, timeout],\n );\n const onKeyDown = useCallback(\n (e: KeyboardEvent) => {\n const isEnter = opts?.stopOnEnter && e.key === 'Enter';\n const isActive = !isEnter;\n\n setActive(isActive);\n },\n [opts.stopOnEnter, setActive],\n );\n const onBlur = useCallback(() => {\n setActive(false);\n }, [setActive]);\n\n const inputProps = useMemo(() => {\n return { onKeyDown, onBlur };\n }, [onKeyDown, onBlur]);\n\n return {\n active,\n setActive,\n inputProps,\n };\n}\n\n// --------------\n// Hooks\n\nexport const rooms = {\n useTopicEffect,\n usePublishTopic,\n usePresence,\n useSyncPresence,\n useTypingIndicator,\n};\n\n// ------------\n// Class\n\nexport class InstantReactRoom<\n Schema extends InstantSchemaDef<any, any, any>,\n RoomSchema extends RoomSchemaShape,\n RoomType extends keyof RoomSchema,\n> {\n core: InstantCoreDatabase<Schema, boolean>;\n /** @deprecated use `core` instead */\n _core: InstantCoreDatabase<Schema, boolean>;\n type: RoomType;\n id: string;\n\n constructor(\n core: InstantCoreDatabase<Schema, boolean>,\n type: RoomType,\n id: string,\n ) {\n this.core = core;\n this._core = this.core;\n this.type = type;\n this.id = id;\n }\n\n /**\n * @deprecated\n * `db.room(...).useTopicEffect` is deprecated. You can replace it with `db.rooms.useTopicEffect`.\n *\n * @example\n *\n * // Before\n * const room = db.room('chat', 'room-id');\n * room.useTopicEffect('emoji', (message, peer) => { });\n *\n * // After\n * const room = db.room('chat', 'room-id');\n * db.rooms.useTopicEffect(room, 'emoji', (message, peer) => { });\n */\n useTopicEffect = <TopicType extends keyof RoomSchema[RoomType]['topics']>(\n topic: TopicType,\n onEvent: (\n event: RoomSchema[RoomType]['topics'][TopicType],\n peer: RoomSchema[RoomType]['presence'],\n ) => any,\n ): void => {\n rooms.useTopicEffect(this, topic, onEvent);\n };\n\n /**\n * @deprecated\n * `db.room(...).usePublishTopic` is deprecated. You can replace it with `db.rooms.usePublishTopic`.\n *\n * @example\n *\n * // Before\n * const room = db.room('chat', 'room-id');\n * const publish = room.usePublishTopic('emoji');\n *\n * // After\n * const room = db.room('chat', 'room-id');\n * const publish = db.rooms.usePublishTopic(room, 'emoji');\n */\n usePublishTopic = <Topic extends keyof RoomSchema[RoomType]['topics']>(\n topic: Topic,\n ): ((data: RoomSchema[RoomType]['topics'][Topic]) => void) => {\n return rooms.usePublishTopic(this, topic);\n };\n\n /**\n * @deprecated\n * `db.room(...).usePresence` is deprecated. You can replace it with `db.rooms.usePresence`.\n *\n * @example\n *\n * // Before\n * const room = db.room('chat', 'room-id');\n * const { peers } = room.usePresence({ keys: [\"name\", \"avatar\"] });\n *\n * // After\n * const room = db.room('chat', 'room-id');\n * const { peers } = db.rooms.usePresence(room, { keys: [\"name\", \"avatar\"] });\n */\n usePresence = <Keys extends keyof RoomSchema[RoomType]['presence']>(\n opts: PresenceOpts<RoomSchema[RoomType]['presence'], Keys> = {},\n ): PresenceHandle<RoomSchema[RoomType]['presence'], Keys> => {\n return rooms.usePresence(this, opts);\n };\n\n /**\n * @deprecated\n * `db.room(...).useSyncPresence` is deprecated. You can replace it with `db.rooms.useSyncPresence`.\n *\n * @example\n *\n * // Before\n * const room = db.room('chat', 'room-id');\n * room.useSyncPresence(room, { nickname });\n *\n * // After\n * const room = db.room('chat', 'room-id');\n * db.rooms.useSyncPresence(room, { nickname });\n */\n useSyncPresence = (\n data: Partial<RoomSchema[RoomType]['presence']>,\n deps?: any[],\n ): void => {\n return rooms.useSyncPresence(this, data, deps);\n };\n\n /**\n * @deprecated\n * `db.room(...).useTypingIndicator` is deprecated. You can replace it with `db.rooms.useTypingIndicator`.\n *\n * @example\n *\n * // Before\n * const room = db.room('chat', 'room-id');\n * const typing = room.useTypingIndiactor(room, 'chat-input');\n *\n * // After\n * const room = db.room('chat', 'room-id');\n * const typing = db.rooms.useTypingIndiactor(room, 'chat-input');\n */\n useTypingIndicator = (\n inputName: string,\n opts: TypingIndicatorOpts = {},\n ): TypingIndicatorHandle<RoomSchema[RoomType]['presence']> => {\n return rooms.useTypingIndicator(this, inputName, opts);\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"InstantReactRoom.js","sourceRoot":"","sources":["../../src/InstantReactRoom.ts"],"names":[],"mappings":";;;AA6DA,wCA0BC;AAiBD,0CAuBC;AAmBD,kCA6CC;AAYD,0CAYC;AAqBD,gDAmEC;AAtSD,iCAOe;AAEf,mDAA6C;AAyBhC,QAAA,0BAA0B,GAAG,IAAK,CAAC;AAEhD,SAAS;AACT,SAAS;AAET;;;;;;;;;;;;GAYG;AACH,SAAgB,cAAc,CAK5B,IAAiD,EACjD,KAAgB,EAChB,OAGQ;IAER,MAAM,UAAU,GAAG,IAAA,cAAM,EAAC,OAAO,CAAC,CAAC;IACnC,UAAU,CAAC,OAAO,GAAG,OAAO,CAAC;IAE7B,IAAA,iBAAS,EAAC,GAAG,EAAE;QACb,MAAM,KAAK,GAAG,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,cAAc,CAC7C,IAAI,CAAC,EAAE,EACP,KAAK,EACL,CAAC,KAAK,EAAE,IAAI,EAAE,EAAE;YACd,UAAU,CAAC,OAAO,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;QAClC,CAAC,CACF,CAAC;QAEF,OAAO,KAA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I,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,IAAI,CAAC;QACvB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;IACf,CAAC;CA2GF;AA/HD,4CA+HC","sourcesContent":["import {\n // types\n type PresenceOpts,\n type PresenceResponse,\n type RoomSchemaShape,\n InstantCoreDatabase,\n InstantSchemaDef,\n} from '@instantdb/core';\n\nimport {\n KeyboardEvent,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from 'react';\n\nimport { useTimeout } from './useTimeout.ts';\n\nexport type PresenceHandle<\n PresenceShape,\n Keys extends keyof PresenceShape,\n> = PresenceResponse<PresenceShape, Keys> & {\n publishPresence: (data: Partial<PresenceShape>) => void;\n};\n\nexport type TypingIndicatorOpts = {\n timeout?: number | null;\n stopOnEnter?: boolean;\n // Perf opt - `active` will always be an empty array\n writeOnly?: boolean;\n};\n\nexport type TypingIndicatorHandle<PresenceShape> = {\n active: PresenceShape[];\n setActive(active: boolean): void;\n inputProps: {\n onKeyDown: (e: KeyboardEvent) => void;\n onBlur: () => void;\n };\n};\n\nexport const defaultActivityStopTimeout = 1_000;\n\n// ------\n// Topics\n\n/**\n * Listen for broadcasted events given a room and topic.\n *\n * @see https://instantdb.com/docs/presence-and-topics\n * @example\n * function App({ roomId }) {\n * const room = db.room('chats', roomId);\n * db.rooms.useTopicEffect(room, 'emoji', (message, peer) => {\n * console.log(peer.name, 'sent', message);\n * });\n * // ...\n * }\n */\nexport function useTopicEffect<\n RoomSchema extends RoomSchemaShape,\n RoomType extends keyof RoomSchema,\n TopicType extends keyof RoomSchema[RoomType]['topics'],\n>(\n room: InstantReactRoom<any, RoomSchema, RoomType>,\n topic: TopicType,\n onEvent: (\n event: RoomSchema[RoomType]['topics'][TopicType],\n peer: RoomSchema[RoomType]['presence'],\n ) => any,\n): void {\n const onEventRef = useRef(onEvent);\n onEventRef.current = onEvent;\n\n useEffect(() => {\n const unsub = room.core._reactor.subscribeTopic(\n room.id,\n topic,\n (event, peer) => {\n onEventRef.current(event, peer);\n },\n );\n\n return unsub;\n }, [room.id, topic]);\n}\n\n/**\n * Broadcast an event to a room.\n *\n * @see https://instantdb.com/docs/presence-and-topics\n * @example\n * function App({ roomId }) {\n * const room = db.room('chat', roomId);\n * const publishTopic = db.rooms.usePublishTopic(room, \"emoji\");\n *\n * return (\n * <button onClick={() => publishTopic({ emoji: \"🔥\" })}>Send emoji</button>\n * );\n * }\n *\n */\nexport function usePublishTopic<\n RoomSchema extends RoomSchemaShape,\n RoomType extends keyof RoomSchema,\n TopicType extends keyof RoomSchema[RoomType]['topics'],\n>(\n room: InstantReactRoom<any, RoomSchema, RoomType>,\n topic: TopicType,\n): (data: RoomSchema[RoomType]['topics'][TopicType]) => void {\n useEffect(() => room.core._reactor.joinRoom(room.id), [room.id]);\n\n const publishTopic = useCallback(\n (data) => {\n room.core._reactor.publishTopic({\n roomType: room.type,\n roomId: room.id,\n topic,\n data,\n });\n },\n [room.id, topic],\n );\n\n return publishTopic;\n}\n\n// ---------\n// Presence\n\n/**\n * Listen for peer's presence data in a room, and publish the current user's presence.\n *\n * @see https://instantdb.com/docs/presence-and-topics\n * @example\n * function App({ roomId }) {\n * const {\n * peers,\n * publishPresence\n * } = db.room(roomType, roomId).usePresence({ keys: [\"name\", \"avatar\"] });\n *\n * // ...\n * }\n */\nexport function usePresence<\n RoomSchema extends RoomSchemaShape,\n RoomType extends keyof RoomSchema,\n Keys extends keyof RoomSchema[RoomType]['presence'],\n>(\n room: InstantReactRoom<any, RoomSchema, RoomType>,\n opts: PresenceOpts<RoomSchema[RoomType]['presence'], Keys> = {},\n): PresenceHandle<RoomSchema[RoomType]['presence'], Keys> {\n const [state, setState] = useState<\n PresenceResponse<RoomSchema[RoomType]['presence'], Keys>\n >(() => {\n return (\n room.core._reactor.getPresence(room.type, room.id, opts) ?? {\n peers: {},\n isLoading: true,\n }\n );\n });\n\n useEffect(() => {\n const unsub = room.core._reactor.subscribePresence(\n room.type,\n room.id,\n opts,\n (data) => {\n setState(data);\n },\n );\n\n return unsub;\n }, [room.id, opts.user, opts.peers?.join(), opts.keys?.join()]);\n\n const publishPresence = useCallback(\n (data) => {\n room.core._reactor.publishPresence(room.type, room.id, data);\n },\n [room.type, room.id],\n );\n const ret = useMemo(() => {\n return {\n ...state,\n publishPresence,\n };\n }, [state, publishPresence]);\n return ret;\n}\n\n/**\n * Publishes presence data to a room\n *\n * @see https://instantdb.com/docs/presence-and-topics\n * @example\n * function App({ roomId, nickname }) {\n * const room = db.room('chat', roomId);\n * db.rooms.useSyncPresence(room, { nickname });\n * }\n */\nexport function useSyncPresence<\n RoomSchema extends RoomSchemaShape,\n RoomType extends keyof RoomSchema,\n>(\n room: InstantReactRoom<any, RoomSchema, RoomType>,\n data: Partial<RoomSchema[RoomType]['presence']>,\n deps?: any[],\n): void {\n useEffect(() => room.core._reactor.joinRoom(room.id, data), [room.id]);\n useEffect(() => {\n return room.core._reactor.publishPresence(room.type, room.id, data);\n }, [room.type, room.id, deps ?? JSON.stringify(data)]);\n}\n\n// -----------------\n// Typing Indicator\n\n/**\n * Manage typing indicator state\n *\n * @see https://instantdb.com/docs/presence-and-topics\n * @example\n * function App({ roomId }) {\n * const room = db.room('chat', roomId);\n * const {\n * active,\n * setActive,\n * inputProps,\n * } = db.rooms.useTypingIndicator(room, \"chat-input\");\n *\n * return <input {...inputProps} />;\n * }\n */\nexport function useTypingIndicator<\n RoomSchema extends RoomSchemaShape,\n RoomType extends keyof RoomSchema,\n>(\n room: InstantReactRoom<any, RoomSchema, RoomType>,\n inputName: string,\n opts: TypingIndicatorOpts = {},\n): TypingIndicatorHandle<RoomSchema[RoomType]['presence']> {\n const timeout = useTimeout();\n\n const observedPresence = rooms.usePresence(room, {\n keys: [inputName] as (keyof RoomSchema[RoomType]['presence'])[],\n });\n\n const active = useMemo(() => {\n const presenceSnapshot = room._core._reactor.getPresence(\n room.type,\n room.id,\n );\n\n return opts?.writeOnly\n ? []\n : Object.values(presenceSnapshot?.peers ?? {}).filter(\n (p) => p[inputName] === true,\n );\n }, [opts?.writeOnly, observedPresence]);\n\n const setActive = useCallback(\n (isActive: boolean) => {\n room.core._reactor.publishPresence(room.type, room.id, {\n [inputName]: isActive,\n } as unknown as Partial<RoomSchema[RoomType]>);\n\n if (!isActive) return;\n\n if (opts?.timeout === null || opts?.timeout === 0) return;\n\n timeout.set(opts?.timeout ?? defaultActivityStopTimeout, () => {\n room.core._reactor.publishPresence(room.type, room.id, {\n [inputName]: null,\n } as Partial<RoomSchema[RoomType]>);\n });\n },\n [room.type, room.id, inputName, opts?.timeout, timeout],\n );\n const onKeyDown = useCallback(\n (e: KeyboardEvent) => {\n const isEnter = opts?.stopOnEnter && e.key === 'Enter';\n const isActive = !isEnter;\n\n setActive(isActive);\n },\n [opts.stopOnEnter, setActive],\n );\n const onBlur = useCallback(() => {\n setActive(false);\n }, [setActive]);\n\n const inputProps = useMemo(() => {\n return { onKeyDown, onBlur };\n }, [onKeyDown, onBlur]);\n\n return {\n active,\n setActive,\n inputProps,\n };\n}\n\n// --------------\n// Hooks\n\nexport const rooms = {\n useTopicEffect,\n usePublishTopic,\n usePresence,\n useSyncPresence,\n useTypingIndicator,\n};\n\n// ------------\n// Class\n\nexport class InstantReactRoom<\n Schema extends InstantSchemaDef<any, any, any>,\n RoomSchema extends RoomSchemaShape,\n RoomType extends keyof RoomSchema,\n> {\n core: InstantCoreDatabase<Schema, boolean>;\n /** @deprecated use `core` instead */\n _core: InstantCoreDatabase<Schema, boolean>;\n type: RoomType;\n id: string;\n\n constructor(\n core: InstantCoreDatabase<Schema, boolean>,\n type: RoomType,\n id: string,\n ) {\n this.core = core;\n this._core = this.core;\n this.type = type;\n this.id = id;\n }\n\n /**\n * @deprecated\n * `db.room(...).useTopicEffect` is deprecated. You can replace it with `db.rooms.useTopicEffect`.\n *\n * @example\n *\n * // Before\n * const room = db.room('chat', 'room-id');\n * room.useTopicEffect('emoji', (message, peer) => { });\n *\n * // After\n * const room = db.room('chat', 'room-id');\n * db.rooms.useTopicEffect(room, 'emoji', (message, peer) => { });\n */\n useTopicEffect = <TopicType extends keyof RoomSchema[RoomType]['topics']>(\n topic: TopicType,\n onEvent: (\n event: RoomSchema[RoomType]['topics'][TopicType],\n peer: RoomSchema[RoomType]['presence'],\n ) => any,\n ): void => {\n rooms.useTopicEffect(this, topic, onEvent);\n };\n\n /**\n * @deprecated\n * `db.room(...).usePublishTopic` is deprecated. You can replace it with `db.rooms.usePublishTopic`.\n *\n * @example\n *\n * // Before\n * const room = db.room('chat', 'room-id');\n * const publish = room.usePublishTopic('emoji');\n *\n * // After\n * const room = db.room('chat', 'room-id');\n * const publish = db.rooms.usePublishTopic(room, 'emoji');\n */\n usePublishTopic = <Topic extends keyof RoomSchema[RoomType]['topics']>(\n topic: Topic,\n ): ((data: RoomSchema[RoomType]['topics'][Topic]) => void) => {\n return rooms.usePublishTopic(this, topic);\n };\n\n /**\n * @deprecated\n * `db.room(...).usePresence` is deprecated. You can replace it with `db.rooms.usePresence`.\n *\n * @example\n *\n * // Before\n * const room = db.room('chat', 'room-id');\n * const { peers } = room.usePresence({ keys: [\"name\", \"avatar\"] });\n *\n * // After\n * const room = db.room('chat', 'room-id');\n * const { peers } = db.rooms.usePresence(room, { keys: [\"name\", \"avatar\"] });\n */\n usePresence = <Keys extends keyof RoomSchema[RoomType]['presence']>(\n opts: PresenceOpts<RoomSchema[RoomType]['presence'], Keys> = {},\n ): PresenceHandle<RoomSchema[RoomType]['presence'], Keys> => {\n return rooms.usePresence(this, opts);\n };\n\n /**\n * @deprecated\n * `db.room(...).useSyncPresence` is deprecated. You can replace it with `db.rooms.useSyncPresence`.\n *\n * @example\n *\n * // Before\n * const room = db.room('chat', 'room-id');\n * room.useSyncPresence(room, { nickname });\n *\n * // After\n * const room = db.room('chat', 'room-id');\n * db.rooms.useSyncPresence(room, { nickname });\n */\n useSyncPresence = (\n data: Partial<RoomSchema[RoomType]['presence']>,\n deps?: any[],\n ): void => {\n return rooms.useSyncPresence(this, data, deps);\n };\n\n /**\n * @deprecated\n * `db.room(...).useTypingIndicator` is deprecated. You can replace it with `db.rooms.useTypingIndicator`.\n *\n * @example\n *\n * // Before\n * const room = db.room('chat', 'room-id');\n * const typing = room.useTypingIndiactor(room, 'chat-input');\n *\n * // After\n * const room = db.room('chat', 'room-id');\n * const typing = db.rooms.useTypingIndiactor(room, 'chat-input');\n */\n useTypingIndicator = (\n inputName: string,\n opts: TypingIndicatorOpts = {},\n ): TypingIndicatorHandle<RoomSchema[RoomType]['presence']> => {\n return rooms.useTypingIndicator(this, inputName, opts);\n };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useQuery.d.ts","sourceRoot":"","sources":["../../src/useQuery.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,KAAK,cAAc,EAEnB,mBAAmB,EACnB,qBAAqB,EACrB,gBAAgB,EAChB,UAAU,EACX,MAAM,iBAAiB,CAAC;AAoBzB,wBAAgB,gBAAgB,CAC9B,CAAC,SAAS,UAAU,CAAC,CAAC,EAAE,MAAM,CAAC,EAC/B,MAAM,SAAS,gBAAgB,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,EAC9C,QAAQ,SAAS,OAAO,EAExB,KAAK,EAAE,mBAAmB,CAAC,MAAM,EAAE,QAAQ,CAAC,EAC5C,MAAM,EAAE,IAAI,GAAG,CAAC,EAChB,KAAK,CAAC,EAAE,cAAc,GACrB;IACD,KAAK,EAAE,qBAAqB,CAAC,MAAM,EAAE,CAAC,EAAE,QAAQ,CAAC,CAAC;IAClD,KAAK,EAAE,GAAG,CAAC;CACZ,
|
|
1
|
+
{"version":3,"file":"useQuery.d.ts","sourceRoot":"","sources":["../../src/useQuery.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,KAAK,cAAc,EAEnB,mBAAmB,EACnB,qBAAqB,EACrB,gBAAgB,EAChB,UAAU,EACX,MAAM,iBAAiB,CAAC;AAoBzB,wBAAgB,gBAAgB,CAC9B,CAAC,SAAS,UAAU,CAAC,CAAC,EAAE,MAAM,CAAC,EAC/B,MAAM,SAAS,gBAAgB,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,EAC9C,QAAQ,SAAS,OAAO,EAExB,KAAK,EAAE,mBAAmB,CAAC,MAAM,EAAE,QAAQ,CAAC,EAC5C,MAAM,EAAE,IAAI,GAAG,CAAC,EAChB,KAAK,CAAC,EAAE,cAAc,GACrB;IACD,KAAK,EAAE,qBAAqB,CAAC,MAAM,EAAE,CAAC,EAAE,QAAQ,CAAC,CAAC;IAClD,KAAK,EAAE,GAAG,CAAC;CACZ,CA4DA"}
|
|
@@ -35,7 +35,13 @@ function useQueryInternal(_core, _query, _opts) {
|
|
|
35
35
|
return unsubscribe;
|
|
36
36
|
}
|
|
37
37
|
const unsubscribe = _core.subscribeQuery(query, (result) => {
|
|
38
|
-
resultCacheRef.current = Object.assign({ isLoading: !Boolean(result),
|
|
38
|
+
resultCacheRef.current = Object.assign({ isLoading: !Boolean(result),
|
|
39
|
+
// @ts-expect-error: ts thinks this will always be overwritten
|
|
40
|
+
data: undefined,
|
|
41
|
+
// @ts-expect-error: ts thinks this will always be overwritten
|
|
42
|
+
pageInfo: undefined,
|
|
43
|
+
// @ts-expect-error: ts thinks this will always be overwritten
|
|
44
|
+
error: undefined }, result);
|
|
39
45
|
cb();
|
|
40
46
|
});
|
|
41
47
|
return unsubscribe;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useQuery.js","sourceRoot":"","sources":["../../src/useQuery.ts"],"names":[],"mappings":";;AA8BA,
|
|
1
|
+
{"version":3,"file":"useQuery.js","sourceRoot":"","sources":["../../src/useQuery.ts"],"names":[],"mappings":";;AA8BA,4CAuEC;AArGD,0CAUyB;AACzB,iCAAkE;AAElE,MAAM,YAAY,GAAG;IACnB,SAAS,EAAE,IAAI;IACf,IAAI,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;YAC7B,OAAO,WAAW,CAAC;QACrB,CAAC;QAED,MAAM,WAAW,GAAG,KAAK,CAAC,cAAc,CAAc,KAAK,EAAE,CAAC,MAAM,EAAE,EAAE;YACtE,cAAc,CAAC,OAAO,mBACpB,SAAS,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC;gBAC3B,8DAA8D;gBAC9D,IAAI,EAAE,SAAS;gBACf,8DAA8D;gBAC9D,QAAQ,EAAE,SAAS;gBACnB,8DAA8D;gBAC9D,KAAK,EAAE,SAAS,IACb,MAAM,CACV,CAAC;YAEF,EAAE,EAAE,CAAC;QACP,CAAC,CAAC,CAAC;QAEH,OAAO,WAAW,CAAC;IACrB,CAAC;IACD,sDAAsD;IACtD,CAAC,SAAS,CAAC,CACZ,CAAC;IAEF,MAAM,KAAK,GAAG,IAAA,4BAAoB,EAGhC,SAAS,EACT,GAAG,EAAE,CAAC,cAAc,CAAC,OAAO,EAC5B,GAAG,EAAE,CAAC,YAAY,CACnB,CAAC;IACF,OAAO,EAAE,KAAK,EAAE,KAAK,EAAE,CAAC;AAC1B,CAAC","sourcesContent":["import {\n weakHash,\n coerceQuery,\n type InstaQLParams,\n type InstaQLOptions,\n type InstantGraph,\n InstantCoreDatabase,\n InstaQLLifecycleState,\n InstantSchemaDef,\n ValidQuery,\n} from '@instantdb/core';\nimport { useCallback, useRef, useSyncExternalStore } from 'react';\n\nconst defaultState = {\n isLoading: true,\n data: undefined,\n pageInfo: undefined,\n error: undefined,\n} as const;\n\nfunction stateForResult(result: any) {\n return {\n isLoading: !Boolean(result),\n data: undefined,\n pageInfo: undefined,\n error: undefined,\n ...(result ? result : {}),\n };\n}\n\nexport function useQueryInternal<\n Q extends ValidQuery<Q, Schema>,\n Schema extends InstantSchemaDef<any, any, any>,\n UseDates extends boolean,\n>(\n _core: InstantCoreDatabase<Schema, UseDates>,\n _query: null | Q,\n _opts?: InstaQLOptions,\n): {\n state: InstaQLLifecycleState<Schema, Q, UseDates>;\n query: any;\n} {\n if (_query && _opts && 'ruleParams' in _opts) {\n _query = { $$ruleParams: _opts['ruleParams'], ..._query };\n }\n const query = _query ? coerceQuery(_query) : null;\n const queryHash = weakHash(query);\n\n // We use a ref to store the result of the query.\n // This is becuase `useSyncExternalStore` uses `Object.is`\n // to compare the previous and next state.\n // If we don't use a ref, the state will always be considered different, so\n // the component will always re-render.\n const resultCacheRef = useRef<InstaQLLifecycleState<Schema, Q, UseDates>>(\n stateForResult(_core._reactor.getPreviousResult(query)),\n );\n\n // Similar to `resultCacheRef`, `useSyncExternalStore` will unsubscribe\n // if `subscribe` changes, so we use `useCallback` to memoize the function.\n const subscribe = useCallback(\n (cb) => {\n // Update the ref when the query changes to avoid showing stale data\n resultCacheRef.current = stateForResult(\n _core._reactor.getPreviousResult(query),\n );\n\n // Don't subscribe if query is null\n if (!query) {\n const unsubscribe = () => {};\n return unsubscribe;\n }\n\n const unsubscribe = _core.subscribeQuery<Q, UseDates>(query, (result) => {\n resultCacheRef.current = {\n isLoading: !Boolean(result),\n // @ts-expect-error: ts thinks this will always be overwritten\n data: undefined,\n // @ts-expect-error: ts thinks this will always be overwritten\n pageInfo: undefined,\n // @ts-expect-error: ts thinks this will always be overwritten\n error: undefined,\n ...result,\n };\n\n cb();\n });\n\n return unsubscribe;\n },\n // Build a new subscribe function if the query changes\n [queryHash],\n );\n\n const state = useSyncExternalStore<\n InstaQLLifecycleState<Schema, Q, UseDates>\n >(\n subscribe,\n () => resultCacheRef.current,\n () => defaultState,\n );\n return { state, query };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useTimeout.d.ts","sourceRoot":"","sources":["../../src/useTimeout.ts"],"names":[],"mappings":"AAEA,wBAAgB,UAAU;iBAOJ,MAAM,MAAM,MAAM,IAAI;;
|
|
1
|
+
{"version":3,"file":"useTimeout.d.ts","sourceRoot":"","sources":["../../src/useTimeout.ts"],"names":[],"mappings":"AAEA,wBAAgB,UAAU;iBAOJ,MAAM,MAAM,MAAM,IAAI;;EAY3C"}
|
|
@@ -8,11 +8,13 @@ function useTimeout() {
|
|
|
8
8
|
clear();
|
|
9
9
|
}, []);
|
|
10
10
|
function set(delay, fn) {
|
|
11
|
-
|
|
11
|
+
clear();
|
|
12
12
|
timeoutRef.current = setTimeout(fn, delay);
|
|
13
13
|
}
|
|
14
14
|
function clear() {
|
|
15
|
-
|
|
15
|
+
if (timeoutRef.current) {
|
|
16
|
+
clearTimeout(timeoutRef.current);
|
|
17
|
+
}
|
|
16
18
|
}
|
|
17
19
|
return { set, clear };
|
|
18
20
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useTimeout.js","sourceRoot":"","sources":["../../src/useTimeout.ts"],"names":[],"mappings":";;AAEA,
|
|
1
|
+
{"version":3,"file":"useTimeout.js","sourceRoot":"","sources":["../../src/useTimeout.ts"],"names":[],"mappings":";;AAEA,gCAmBC;AArBD,iCAA0C;AAE1C,SAAgB,UAAU;IACxB,MAAM,UAAU,GAAG,IAAA,cAAM,EAAuC,IAAI,CAAC,CAAC;IAEtE,IAAA,iBAAS,EAAC,GAAG,EAAE;QACb,KAAK,EAAE,CAAC;IACV,CAAC,EAAE,EAAE,CAAC,CAAC;IAEP,SAAS,GAAG,CAAC,KAAa,EAAE,EAAc;QACxC,KAAK,EAAE,CAAC;QACR,UAAU,CAAC,OAAO,GAAG,UAAU,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC;IAC7C,CAAC;IAED,SAAS,KAAK;QACZ,IAAI,UAAU,CAAC,OAAO,EAAE,CAAC;YACvB,YAAY,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;QACnC,CAAC;IACH,CAAC;IAED,OAAO,EAAE,GAAG,EAAE,KAAK,EAAE,CAAC;AACxB,CAAC","sourcesContent":["import { useEffect, useRef } from 'react';\n\nexport function useTimeout() {\n const timeoutRef = useRef<null | ReturnType<typeof setTimeout>>(null);\n\n useEffect(() => {\n clear();\n }, []);\n\n function set(delay: number, fn: () => void) {\n clear();\n timeoutRef.current = setTimeout(fn, delay);\n }\n\n function clear() {\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n }\n }\n\n return { set, clear };\n}\n"]}
|
|
@@ -1,17 +1,19 @@
|
|
|
1
1
|
import { Auth, Storage, type AuthState, type User, type ConnectionStatus, type TransactionChunk, type RoomSchemaShape, type InstaQLOptions, type InstantConfig, type PageInfoResponse, InstantCoreDatabase, InstaQLLifecycleState, InstaQLResponse, RoomsOf, InstantSchemaDef, IInstantDatabase, ValidQuery } from '@instantdb/core';
|
|
2
2
|
import { ReactNode } from 'react';
|
|
3
3
|
import { InstantReactRoom } from './InstantReactRoom.ts';
|
|
4
|
-
export default abstract class InstantReactAbstractDatabase<Schema extends InstantSchemaDef<any, any, any>, Config extends InstantConfig<Schema, boolean
|
|
4
|
+
export default abstract class InstantReactAbstractDatabase<Schema extends InstantSchemaDef<any, any, any>, UseDates extends boolean = false, Config extends InstantConfig<Schema, boolean> = InstantConfig<Schema, UseDates>, Rooms extends RoomSchemaShape = RoomsOf<Schema>> implements IInstantDatabase<Schema> {
|
|
5
5
|
tx: import("@instantdb/core").TxChunk<Schema>;
|
|
6
6
|
auth: Auth;
|
|
7
7
|
storage: Storage;
|
|
8
|
-
core: InstantCoreDatabase<Schema,
|
|
8
|
+
core: InstantCoreDatabase<Schema, UseDates>;
|
|
9
9
|
/** @deprecated use `core` instead */
|
|
10
|
-
_core: InstantCoreDatabase<Schema,
|
|
10
|
+
_core: InstantCoreDatabase<Schema, UseDates>;
|
|
11
11
|
static Storage?: any;
|
|
12
12
|
static NetworkListener?: any;
|
|
13
13
|
static EventSourceImpl?: any;
|
|
14
|
-
constructor(config:
|
|
14
|
+
constructor(config: Omit<InstantConfig<Schema, UseDates>, 'useDateObjects'> & {
|
|
15
|
+
useDateObjects?: UseDates;
|
|
16
|
+
}, versions?: {
|
|
15
17
|
[key: string]: string;
|
|
16
18
|
});
|
|
17
19
|
/**
|
|
@@ -115,7 +117,7 @@ export default abstract class InstantReactAbstractDatabase<Schema extends Instan
|
|
|
115
117
|
* auth.user ? { goals: {} } : null,
|
|
116
118
|
* );
|
|
117
119
|
*/
|
|
118
|
-
useQuery: <Q extends ValidQuery<Q, Schema>>(query: null | Q, opts?: InstaQLOptions) => InstaQLLifecycleState<Schema, Q,
|
|
120
|
+
useQuery: <Q extends ValidQuery<Q, Schema>>(query: null | Q, opts?: InstaQLOptions) => InstaQLLifecycleState<Schema, Q, UseDates>;
|
|
119
121
|
/**
|
|
120
122
|
* Listen for the logged in state. This is useful
|
|
121
123
|
* for deciding when to show a login screen.
|
|
@@ -208,7 +210,7 @@ export default abstract class InstantReactAbstractDatabase<Schema extends Instan
|
|
|
208
210
|
* console.log(resp.data.goals)
|
|
209
211
|
*/
|
|
210
212
|
queryOnce: <Q extends ValidQuery<Q, Schema>>(query: Q, opts?: InstaQLOptions) => Promise<{
|
|
211
|
-
data: InstaQLResponse<Schema, Q,
|
|
213
|
+
data: InstaQLResponse<Schema, Q, UseDates>;
|
|
212
214
|
pageInfo: PageInfoResponse<Q>;
|
|
213
215
|
}>;
|
|
214
216
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"InstantReactAbstractDatabase.d.ts","sourceRoot":"","sources":["../../src/InstantReactAbstractDatabase.tsx"],"names":[],"mappings":"AAAA,OAAO,EAEL,IAAI,EACJ,OAAO,EAEP,KAAK,SAAS,EACd,KAAK,IAAI,EACT,KAAK,gBAAgB,EACrB,KAAK,gBAAgB,EACrB,KAAK,eAAe,EAEpB,KAAK,cAAc,EACnB,KAAK,aAAa,EAClB,KAAK,gBAAgB,EACrB,mBAAmB,EAEnB,qBAAqB,EACrB,eAAe,EACf,OAAO,EACP,gBAAgB,EAChB,gBAAgB,EAEhB,UAAU,EACX,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,SAAS,EAMV,MAAM,OAAO,CAAC;AAEf,OAAO,EAAE,gBAAgB,EAAS,MAAM,uBAAuB,CAAC;AAQhE,MAAM,CAAC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CAAC;QACzB,CAAC,CAAC;QAjWA,IAAI,CAAC,IAAI,GAAG,SAAS,CACnB,MAAM;QACN,6DAA6D;QAC7D,IAAI,CAAC,WAAW,CAAC,OAAO;QACxB,6DAA6D;QAC7D,IAAI,CAAC,WAAW,CAAC,eAAe,EAChC,QAAQ;QACR,6DAA6D;QAC7D,IAAI,CAAC,WAAW,CAAC,eAAe,CACjC,CAAC;QACF,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,IAAI,CAAC;QACvB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC;QAC3B,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC;IACnC,CAAC;IA2CD;;;;;;;;;;;OAWG;IACH,IAAI,CACF,OAAiB,kBAA8B,EAC/C,KAAa,gBAAgB;QAE7B,OAAO,IAAI,gBAAgB,CAA0B,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,CAAC;IAC5E,CAAC;IAgKD;;;;;;;;;OASG;IACH,OAAO;QACL,OAAO,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;IAC7B,CAAC;CA6GF","sourcesContent":["import {\n // types\n Auth,\n Storage,\n txInit,\n type AuthState,\n type User,\n type ConnectionStatus,\n type TransactionChunk,\n type RoomSchemaShape,\n type InstaQLParams,\n type InstaQLOptions,\n type InstantConfig,\n type PageInfoResponse,\n InstantCoreDatabase,\n init as core_init,\n InstaQLLifecycleState,\n InstaQLResponse,\n RoomsOf,\n InstantSchemaDef,\n IInstantDatabase,\n InstantError,\n ValidQuery,\n} from '@instantdb/core';\nimport {\n ReactNode,\n useCallback,\n useEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from 'react';\nimport { useQueryInternal } from './useQuery.ts';\nimport { InstantReactRoom, rooms } from './InstantReactRoom.ts';\n\nconst defaultAuthState = {\n isLoading: true,\n user: undefined,\n error: undefined,\n};\n\nexport default abstract class InstantReactAbstractDatabase<\n // need to pull this schema out to another generic for query params, not sure why\n Schema extends InstantSchemaDef<any, any, any>,\n Config extends InstantConfig<Schema, boolean | undefined> = InstantConfig<\n Schema,\n boolean\n >,\n Rooms extends RoomSchemaShape = RoomsOf<Schema>,\n> implements IInstantDatabase<Schema>\n{\n public tx = txInit<Schema>();\n\n public auth: Auth;\n public storage: Storage;\n public core: InstantCoreDatabase<Schema, Config['useDateObjects']>;\n\n /** @deprecated use `core` instead */\n public _core: InstantCoreDatabase<Schema, Config['useDateObjects']>;\n\n static Storage?: any;\n static NetworkListener?: any;\n static EventSourceImpl?: any;\n\n constructor(config: Config, versions?: { [key: string]: string }) {\n this.core = core_init<Schema, Config['useDateObjects']>(\n config,\n // @ts-expect-error because TS can't resolve subclass statics\n this.constructor.Storage,\n // @ts-expect-error because TS can't resolve subclass statics\n this.constructor.NetworkListener,\n versions,\n // @ts-expect-error because TS can't resolve subclass statics\n this.constructor.EventSourceImpl,\n );\n this._core = this.core;\n this.auth = this.core.auth;\n this.storage = this.core.storage;\n }\n\n /**\n * Returns a unique ID for a given `name`. It's stored in local storage,\n * so you will get the same ID across sessions.\n *\n * This is useful for generating IDs that could identify a local device or user.\n *\n * @example\n * const deviceId = await db.getLocalId('device');\n */\n getLocalId = (name: string): Promise<string> => {\n return this.core.getLocalId(name);\n };\n\n /**\n * A hook that returns a unique ID for a given `name`. localIds are\n * stored in local storage, so you will get the same ID across sessions.\n *\n * Initially returns `null`, and then loads the localId.\n *\n * @example\n * const deviceId = db.useLocalId('device');\n * if (!deviceId) return null; // loading\n * console.log('Device ID:', deviceId)\n */\n useLocalId = (name: string): string | null => {\n const [localId, setLocalId] = useState<string | null>(null);\n\n useEffect(() => {\n let mounted = true;\n const f = async () => {\n const id = await this.getLocalId(name);\n if (!mounted) return;\n setLocalId(id);\n };\n f();\n return;\n }, [name]);\n\n return localId;\n };\n\n /**\n * Obtain a handle to a room, which allows you to listen to topics and presence data\n *\n * If you don't provide a `type` or `id`, Instant will default to `_defaultRoomType` and `_defaultRoomId`\n * as the room type and id, respectively.\n *\n * @see https://instantdb.com/docs/presence-and-topics\n *\n * @example\n * const room = db.room('chat', roomId);\n * const { peers } = db.rooms.usePresence(room);\n */\n room<RoomType extends keyof Rooms>(\n type: RoomType = '_defaultRoomType' as RoomType,\n id: string = '_defaultRoomId',\n ) {\n return new InstantReactRoom<Schema, Rooms, RoomType>(this.core, type, id);\n }\n\n /**\n * Hooks for working with rooms\n *\n * @see https://instantdb.com/docs/presence-and-topics\n *\n * @example\n * const room = db.room('chat', roomId);\n * const { peers } = db.rooms.usePresence(room);\n * const publish = db.rooms.usePublishTopic(room, 'emoji');\n * // ...\n */\n rooms = rooms;\n\n /**\n * Use this to write data! You can create, update, delete, and link objects\n *\n * @see https://instantdb.com/docs/instaml\n *\n * @example\n * // Create a new object in the `goals` namespace\n * const goalId = id();\n * db.transact(db.tx.goals[goalId].update({title: \"Get fit\"}))\n *\n * // Update the title\n * db.transact(db.tx.goals[goalId].update({title: \"Get super fit\"}))\n *\n * // Delete it\n * db.transact(db.tx.goals[goalId].delete())\n *\n * // Or create an association:\n * todoId = id();\n * db.transact([\n * db.tx.todos[todoId].update({ title: 'Go on a run' }),\n * db.tx.goals[goalId].link({todos: todoId}),\n * ])\n */\n transact = (\n chunks: TransactionChunk<any, any> | TransactionChunk<any, any>[],\n ) => {\n return this.core.transact(chunks);\n };\n\n /**\n * Use this to query your data!\n *\n * @see https://instantdb.com/docs/instaql\n *\n * @example\n * // listen to all goals\n * const { isLoading, error, data } = db.useQuery({ goals: {} });\n *\n * // goals where the title is \"Get Fit\"\n * const { isLoading, error, data } = db.useQuery({\n * goals: { $: { where: { title: 'Get Fit' } } },\n * });\n *\n * // all goals, _alongside_ their todos\n * const { isLoading, error, data } = db.useQuery({\n * goals: { todos: {} },\n * });\n *\n * // skip if `user` is not logged in\n * const { isLoading, error, data } = db.useQuery(\n * auth.user ? { goals: {} } : null,\n * );\n */\n useQuery = <Q extends ValidQuery<Q, Schema>>(\n query: null | Q,\n opts?: InstaQLOptions,\n ): InstaQLLifecycleState<Schema, Q, Config['useDateObjects']> => {\n return useQueryInternal<Q, Schema, Config['useDateObjects']>(\n this.core,\n query,\n opts,\n ).state;\n };\n\n /**\n * Listen for the logged in state. This is useful\n * for deciding when to show a login screen.\n *\n * Check out the docs for an example `Login` component too!\n *\n * @see https://instantdb.com/docs/auth\n * @example\n * function App() {\n * const { isLoading, user, error } = db.useAuth()\n * if (isLoading) {\n * return <div>Loading...</div>\n * }\n * if (error) {\n * return <div>Uh oh! {error.message}</div>\n * }\n * if (user) {\n * return <Main user={user} />\n * }\n * return <Login />\n * }\n *\n */\n useAuth = (): AuthState => {\n // We use a ref to store the result of the query.\n // This is becuase `useSyncExternalStore` uses `Object.is`\n // to compare the previous and next state.\n // If we don't use a ref, the state will always be considered different, so\n // the component will always re-render.\n const resultCacheRef = useRef<AuthState>(\n this.core._reactor._currentUserCached,\n );\n\n // Similar to `resultCacheRef`, `useSyncExternalStore` will unsubscribe\n // if `subscribe` changes, so we use `useCallback` to memoize the function.\n const subscribe = useCallback((cb: Function) => {\n const unsubscribe = this.core.subscribeAuth((auth) => {\n resultCacheRef.current = { isLoading: false, ...auth };\n cb();\n });\n\n return unsubscribe;\n }, []);\n\n const state = useSyncExternalStore<AuthState>(\n subscribe,\n () => resultCacheRef.current,\n () => defaultAuthState,\n );\n return state;\n };\n\n /**\n * Subscribe to the currently logged in user.\n * If the user is not logged in, this hook with throw an Error.\n * You will want to protect any calls of this hook with a\n * <db.SignedIn> component, or your own logic based on db.useAuth()\n *\n * @see https://instantdb.com/docs/auth\n * @throws Error indicating user not signed in\n * @example\n * function UserDisplay() {\n * const user = db.useUser()\n * return <div>Logged in as: {user.email}</div>\n * }\n *\n * <db.SignedIn>\n * <UserDisplay />\n * </db.SignedIn>\n *\n */\n useUser = (): User => {\n const { user } = this.useAuth();\n if (!user) {\n throw new InstantError(\n 'useUser must be used within an auth-protected route',\n );\n }\n return user;\n };\n\n /**\n * One time query for the logged in state. This is useful\n * for scenarios where you want to know the current auth\n * state without subscribing to changes.\n *\n * @see https://instantdb.com/docs/auth\n * @example\n * const user = await db.getAuth();\n * console.log('logged in as', user.email)\n */\n getAuth(): Promise<User | null> {\n return this.core.getAuth();\n }\n\n /**\n * Listen for connection status changes to Instant. Use this for things like\n * showing connection state to users\n *\n * @see https://www.instantdb.com/docs/patterns#connection-status\n * @example\n * function App() {\n * const status = db.useConnectionStatus()\n * const connectionState =\n * status === 'connecting' || status === 'opened'\n * ? 'authenticating'\n * : status === 'authenticated'\n * ? 'connected'\n * : status === 'closed'\n * ? 'closed'\n * : status === 'errored'\n * ? 'errored'\n * : 'unexpected state';\n *\n * return <div>Connection state: {connectionState}</div>\n * }\n */\n useConnectionStatus = (): ConnectionStatus => {\n const statusRef = useRef<ConnectionStatus>(\n this.core._reactor.status as ConnectionStatus,\n );\n\n const subscribe = useCallback((cb: Function) => {\n const unsubscribe = this.core.subscribeConnectionStatus((newStatus) => {\n if (newStatus !== statusRef.current) {\n statusRef.current = newStatus;\n cb();\n }\n });\n\n return unsubscribe;\n }, []);\n\n const status = useSyncExternalStore<ConnectionStatus>(\n subscribe,\n () => statusRef.current,\n // For SSR, always return 'connecting' as the initial state\n () => 'connecting',\n );\n\n return status;\n };\n\n /**\n * Use this for one-off queries.\n * Returns local data if available, otherwise fetches from the server.\n * Because we want to avoid stale data, this method will throw an error\n * if the user is offline or there is no active connection to the server.\n *\n * @see https://instantdb.com/docs/instaql\n *\n * @example\n *\n * const resp = await db.queryOnce({ goals: {} });\n * console.log(resp.data.goals)\n */\n queryOnce = <Q extends ValidQuery<Q, Schema>>(\n query: Q,\n opts?: InstaQLOptions,\n ): Promise<{\n data: InstaQLResponse<Schema, Q, Config['useDateObjects']>;\n pageInfo: PageInfoResponse<Q>;\n }> => {\n return this.core.queryOnce(query, opts);\n };\n\n /**\n * Only render children if the user is signed in.\n * @see https://instantdb.com/docs/auth\n *\n * @example\n * <db.SignedIn>\n * <MyComponent />\n * </db.SignedIn>\n *\n */\n SignedIn: React.FC<{\n children: ReactNode;\n }> = ({ children }) => {\n const auth = this.useAuth();\n if (auth.isLoading || auth.error || !auth.user) return null;\n\n return <>{children}</>;\n };\n\n /**\n * Only render children if the user is signed out.\n * @see https://instantdb.com/docs/auth\n *\n * @example\n * <db.SignedOut>\n * <MyComponent />\n * </db.SignedOut>\n *\n */\n SignedOut: React.FC<{\n children: ReactNode;\n }> = ({ children }) => {\n const auth = this.useAuth();\n if (auth.isLoading || auth.error || auth.user) return null;\n return <>{children}</>;\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"InstantReactAbstractDatabase.js","sourceRoot":"","sources":["../../src/InstantReactAbstractDatabase.tsx"],"names":[],"mappings":";;;;;;;;;;AAAA,OAAO,EAIL,MAAM,EAWN,IAAI,IAAI,SAAS,EAMjB,YAAY,GAEb,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAEL,WAAW,EACX,SAAS,EACT,MAAM,EACN,QAAQ,EACR,oBAAoB,GACrB,MAAM,OAAO,CAAC;AACf,OAAO,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACjD,OAAO,EAAE,gBAAgB,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAEhE,MAAM,gBAAgB,GAAG;IACvB,SAAS,EAAE,IAAI;IACf,IAAI,EAAE,SAAS;IACf,KAAK,EAAE,SAAS;CACjB,CAAC;AAEF,MAAM,CAAC,OAAO,OAAgB,4BAA4B;IAwBxD,YACE,MAEC,EACD,QAAoC;QAjB/B,OAAE,GAAG,MAAM,EAAU,CAAC;QAkC7B;;;;;;;;WAQG;QACH,eAAU,GAAG,CAAC,IAAY,EAAmB,EAAE;YAC7C,OAAO,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;QACpC,CAAC,CAAC;QAEF;;;;;;;;;;WAUG;QACH,eAAU,GAAG,CAAC,IAAY,EAAiB,EAAE;YAC3C,MAAM,CAAC,OAAO,EAAE,UAAU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CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC;QAC3B,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC;IACnC,CAAC;IA2CD;;;;;;;;;;;OAWG;IACH,IAAI,CACF,OAAiB,kBAA8B,EAC/C,KAAa,gBAAgB;QAE7B,OAAO,IAAI,gBAAgB,CAA0B,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,CAAC,CAAC;IAC5E,CAAC;IA4JD;;;;;;;;;OASG;IACH,OAAO;QACL,OAAO,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC;IAC7B,CAAC;CA6GF","sourcesContent":["import {\n // types\n Auth,\n Storage,\n txInit,\n type AuthState,\n type User,\n type ConnectionStatus,\n type TransactionChunk,\n type RoomSchemaShape,\n type InstaQLParams,\n type InstaQLOptions,\n type InstantConfig,\n type PageInfoResponse,\n InstantCoreDatabase,\n init as core_init,\n InstaQLLifecycleState,\n InstaQLResponse,\n RoomsOf,\n InstantSchemaDef,\n IInstantDatabase,\n InstantError,\n ValidQuery,\n} from '@instantdb/core';\nimport {\n ReactNode,\n useCallback,\n useEffect,\n useRef,\n useState,\n useSyncExternalStore,\n} from 'react';\nimport { useQueryInternal } from './useQuery.ts';\nimport { InstantReactRoom, rooms } from './InstantReactRoom.ts';\n\nconst defaultAuthState = {\n isLoading: true,\n user: undefined,\n error: undefined,\n};\n\nexport default abstract class InstantReactAbstractDatabase<\n // need to pull this schema out to another generic for query params, not sure why\n Schema extends InstantSchemaDef<any, any, any>,\n UseDates extends boolean = false,\n Config extends InstantConfig<Schema, boolean> = InstantConfig<\n Schema,\n UseDates\n >,\n Rooms extends RoomSchemaShape = RoomsOf<Schema>,\n> implements IInstantDatabase<Schema>\n{\n public tx = txInit<Schema>();\n\n public auth: Auth;\n public storage: Storage;\n public core: InstantCoreDatabase<Schema, UseDates>;\n\n /** @deprecated use `core` instead */\n public _core: InstantCoreDatabase<Schema, UseDates>;\n\n static Storage?: any;\n static NetworkListener?: any;\n static EventSourceImpl?: any;\n\n constructor(\n config: Omit<InstantConfig<Schema, UseDates>, 'useDateObjects'> & {\n useDateObjects?: UseDates;\n },\n versions?: { [key: string]: string },\n ) {\n this.core = core_init<Schema, UseDates>(\n config,\n // @ts-expect-error because TS can't resolve subclass statics\n this.constructor.Storage,\n // @ts-expect-error because TS can't resolve subclass statics\n this.constructor.NetworkListener,\n versions,\n // @ts-expect-error because TS can't resolve subclass statics\n this.constructor.EventSourceImpl,\n );\n this._core = this.core;\n this.auth = this.core.auth;\n this.storage = this.core.storage;\n }\n\n /**\n * Returns a unique ID for a given `name`. It's stored in local storage,\n * so you will get the same ID across sessions.\n *\n * This is useful for generating IDs that could identify a local device or user.\n *\n * @example\n * const deviceId = await db.getLocalId('device');\n */\n getLocalId = (name: string): Promise<string> => {\n return this.core.getLocalId(name);\n };\n\n /**\n * A hook that returns a unique ID for a given `name`. localIds are\n * stored in local storage, so you will get the same ID across sessions.\n *\n * Initially returns `null`, and then loads the localId.\n *\n * @example\n * const deviceId = db.useLocalId('device');\n * if (!deviceId) return null; // loading\n * console.log('Device ID:', deviceId)\n */\n useLocalId = (name: string): string | null => {\n const [localId, setLocalId] = useState<string | null>(null);\n\n useEffect(() => {\n let mounted = true;\n const f = async () => {\n const id = await this.getLocalId(name);\n if (!mounted) return;\n setLocalId(id);\n };\n f();\n return;\n }, [name]);\n\n return localId;\n };\n\n /**\n * Obtain a handle to a room, which allows you to listen to topics and presence data\n *\n * If you don't provide a `type` or `id`, Instant will default to `_defaultRoomType` and `_defaultRoomId`\n * as the room type and id, respectively.\n *\n * @see https://instantdb.com/docs/presence-and-topics\n *\n * @example\n * const room = db.room('chat', roomId);\n * const { peers } = db.rooms.usePresence(room);\n */\n room<RoomType extends keyof Rooms>(\n type: RoomType = '_defaultRoomType' as RoomType,\n id: string = '_defaultRoomId',\n ) {\n return new InstantReactRoom<Schema, Rooms, RoomType>(this.core, type, id);\n }\n\n /**\n * Hooks for working with rooms\n *\n * @see https://instantdb.com/docs/presence-and-topics\n *\n * @example\n * const room = db.room('chat', roomId);\n * const { peers } = db.rooms.usePresence(room);\n * const publish = db.rooms.usePublishTopic(room, 'emoji');\n * // ...\n */\n rooms = rooms;\n\n /**\n * Use this to write data! You can create, update, delete, and link objects\n *\n * @see https://instantdb.com/docs/instaml\n *\n * @example\n * // Create a new object in the `goals` namespace\n * const goalId = id();\n * db.transact(db.tx.goals[goalId].update({title: \"Get fit\"}))\n *\n * // Update the title\n * db.transact(db.tx.goals[goalId].update({title: \"Get super fit\"}))\n *\n * // Delete it\n * db.transact(db.tx.goals[goalId].delete())\n *\n * // Or create an association:\n * todoId = id();\n * db.transact([\n * db.tx.todos[todoId].update({ title: 'Go on a run' }),\n * db.tx.goals[goalId].link({todos: todoId}),\n * ])\n */\n transact = (\n chunks: TransactionChunk<any, any> | TransactionChunk<any, any>[],\n ) => {\n return this.core.transact(chunks);\n };\n\n /**\n * Use this to query your data!\n *\n * @see https://instantdb.com/docs/instaql\n *\n * @example\n * // listen to all goals\n * const { isLoading, error, data } = db.useQuery({ goals: {} });\n *\n * // goals where the title is \"Get Fit\"\n * const { isLoading, error, data } = db.useQuery({\n * goals: { $: { where: { title: 'Get Fit' } } },\n * });\n *\n * // all goals, _alongside_ their todos\n * const { isLoading, error, data } = db.useQuery({\n * goals: { todos: {} },\n * });\n *\n * // skip if `user` is not logged in\n * const { isLoading, error, data } = db.useQuery(\n * auth.user ? { goals: {} } : null,\n * );\n */\n useQuery = <Q extends ValidQuery<Q, Schema>>(\n query: null | Q,\n opts?: InstaQLOptions,\n ): InstaQLLifecycleState<Schema, Q, UseDates> => {\n return useQueryInternal<Q, Schema, UseDates>(this.core, query, opts).state;\n };\n\n /**\n * Listen for the logged in state. This is useful\n * for deciding when to show a login screen.\n *\n * Check out the docs for an example `Login` component too!\n *\n * @see https://instantdb.com/docs/auth\n * @example\n * function App() {\n * const { isLoading, user, error } = db.useAuth()\n * if (isLoading) {\n * return <div>Loading...</div>\n * }\n * if (error) {\n * return <div>Uh oh! {error.message}</div>\n * }\n * if (user) {\n * return <Main user={user} />\n * }\n * return <Login />\n * }\n *\n */\n useAuth = (): AuthState => {\n // We use a ref to store the result of the query.\n // This is becuase `useSyncExternalStore` uses `Object.is`\n // to compare the previous and next state.\n // If we don't use a ref, the state will always be considered different, so\n // the component will always re-render.\n const resultCacheRef = useRef<AuthState>(\n this.core._reactor._currentUserCached,\n );\n\n // Similar to `resultCacheRef`, `useSyncExternalStore` will unsubscribe\n // if `subscribe` changes, so we use `useCallback` to memoize the function.\n const subscribe = useCallback((cb: Function) => {\n const unsubscribe = this.core.subscribeAuth((auth) => {\n resultCacheRef.current = { isLoading: false, ...auth };\n cb();\n });\n\n return unsubscribe;\n }, []);\n\n const state = useSyncExternalStore<AuthState>(\n subscribe,\n () => resultCacheRef.current,\n () => defaultAuthState,\n );\n return state;\n };\n\n /**\n * Subscribe to the currently logged in user.\n * If the user is not logged in, this hook with throw an Error.\n * You will want to protect any calls of this hook with a\n * <db.SignedIn> component, or your own logic based on db.useAuth()\n *\n * @see https://instantdb.com/docs/auth\n * @throws Error indicating user not signed in\n * @example\n * function UserDisplay() {\n * const user = db.useUser()\n * return <div>Logged in as: {user.email}</div>\n * }\n *\n * <db.SignedIn>\n * <UserDisplay />\n * </db.SignedIn>\n *\n */\n useUser = (): User => {\n const { user } = this.useAuth();\n if (!user) {\n throw new InstantError(\n 'useUser must be used within an auth-protected route',\n );\n }\n return user;\n };\n\n /**\n * One time query for the logged in state. This is useful\n * for scenarios where you want to know the current auth\n * state without subscribing to changes.\n *\n * @see https://instantdb.com/docs/auth\n * @example\n * const user = await db.getAuth();\n * console.log('logged in as', user.email)\n */\n getAuth(): Promise<User | null> {\n return this.core.getAuth();\n }\n\n /**\n * Listen for connection status changes to Instant. Use this for things like\n * showing connection state to users\n *\n * @see https://www.instantdb.com/docs/patterns#connection-status\n * @example\n * function App() {\n * const status = db.useConnectionStatus()\n * const connectionState =\n * status === 'connecting' || status === 'opened'\n * ? 'authenticating'\n * : status === 'authenticated'\n * ? 'connected'\n * : status === 'closed'\n * ? 'closed'\n * : status === 'errored'\n * ? 'errored'\n * : 'unexpected state';\n *\n * return <div>Connection state: {connectionState}</div>\n * }\n */\n useConnectionStatus = (): ConnectionStatus => {\n const statusRef = useRef<ConnectionStatus>(\n this.core._reactor.status as ConnectionStatus,\n );\n\n const subscribe = useCallback((cb: Function) => {\n const unsubscribe = this.core.subscribeConnectionStatus((newStatus) => {\n if (newStatus !== statusRef.current) {\n statusRef.current = newStatus;\n cb();\n }\n });\n\n return unsubscribe;\n }, []);\n\n const status = useSyncExternalStore<ConnectionStatus>(\n subscribe,\n () => statusRef.current,\n // For SSR, always return 'connecting' as the initial state\n () => 'connecting',\n );\n\n return status;\n };\n\n /**\n * Use this for one-off queries.\n * Returns local data if available, otherwise fetches from the server.\n * Because we want to avoid stale data, this method will throw an error\n * if the user is offline or there is no active connection to the server.\n *\n * @see https://instantdb.com/docs/instaql\n *\n * @example\n *\n * const resp = await db.queryOnce({ goals: {} });\n * console.log(resp.data.goals)\n */\n queryOnce = <Q extends ValidQuery<Q, Schema>>(\n query: Q,\n opts?: InstaQLOptions,\n ): Promise<{\n data: InstaQLResponse<Schema, Q, UseDates>;\n pageInfo: PageInfoResponse<Q>;\n }> => {\n return this.core.queryOnce(query, opts);\n };\n\n /**\n * Only render children if the user is signed in.\n * @see https://instantdb.com/docs/auth\n *\n * @example\n * <db.SignedIn>\n * <MyComponent />\n * </db.SignedIn>\n *\n */\n SignedIn: React.FC<{\n children: ReactNode;\n }> = ({ children }) => {\n const auth = this.useAuth();\n if (auth.isLoading || auth.error || !auth.user) return null;\n\n return <>{children}</>;\n };\n\n /**\n * Only render children if the user is signed out.\n * @see https://instantdb.com/docs/auth\n *\n * @example\n * <db.SignedOut>\n * <MyComponent />\n * </db.SignedOut>\n *\n */\n SignedOut: React.FC<{\n children: ReactNode;\n }> = ({ children }) => {\n const auth = this.useAuth();\n if (auth.isLoading || auth.error || auth.user) return null;\n return <>{children}</>;\n };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"InstantReactRoom.js","sourceRoot":"","sources":["../../src/InstantReactRoom.ts"],"names":[],"mappings":"AASA,OAAO,EAEL,WAAW,EACX,SAAS,EACT,OAAO,EACP,MAAM,EACN,QAAQ,GACT,MAAM,OAAO,CAAC;AAEf,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAyB7C,MAAM,CAAC,MAAM,0BAA0B,GAAG,IAAK,CAAC;AAEhD,SAAS;AACT,SAAS;AAET;;;;;;;;;;;;GAYG;AACH,MAAM,UAAU,cAAc,CAK5B,IAAiD,EACjD,KAAgB,EAChB,OAGQ;IAER,MAAM,UAAU,GAAG,MAAM,CAAC,OAAO,CAAC,CAAC;IACnC,UAAU,CAAC,OAAO,GAAG,OAAO,CAAC;IAE7B,SAAS,CAAC,GAAG,EAAE;QACb,MAAM,KAAK,GAAG,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,cAAc,CAC7C,IAAI,CAAC,EAAE,EACP,KAAK,EACL,CAAC,KAAK,EAAE,IAAI,EAAE,EAAE;YACd,UAAU,CAAC,OAAO,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;QAClC,CAAC,CACF,CAAC;QAEF,OAAO,KAAK,CAAC;IACf,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,EAAE,KAAK,CAAC,CAAC,CAAC;AACvB,CAAC;AAED;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,eAAe,CAK7B,IAAiD,EACjD,KAAgB;IAEhB,SAAS,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC;IAEjE,MAAM,YAAY,GAAG,WAAW,CAC9B,CAAC,IAAI,EAAE,EAAE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AAK,CAAC,cAAc,CAAC,IAAI,EAAE,KAAK,EAAE,OAAO,CAAC,CAAC;QAC7C,CAAC,CAAC;QAEF;;;;;;;;;;;;;WAaG;QACH,oBAAe,GAAG,CAChB,KAAY,EAC6C,EAAE;YAC3D,OAAO,KAAK,CAAC,eAAe,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;QAC5C,CAAC,CAAC;QAEF;;;;;;;;;;;;;WAaG;QACH,gBAAW,GAAG,CACZ,OAA6D,EAAE,EACP,EAAE;YAC1D,OAAO,KAAK,CAAC,WAAW,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;QACvC,CAAC,CAAC;QAEF;;;;;;;;;;;;;WAaG;QACH,oBAAe,GAAG,CAChB,IAA+C,EAC/C,IAAY,EACN,EAAE;YACR,OAAO,KAAK,CAAC,eAAe,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;QACjD,CAAC,CAAC;QAEF;;;;;;;;;;;;;WAaG;QACH,uBAAkB,GAAG,CACnB,SAAiB,EACjB,OAA4B,EAAE,EAC2B,EAAE;YAC3D,OAAO,KAAK,CAAC,kBAAkB,CAAC,IAAI,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;QACzD,CAAC,CAAC;QA9GA,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,IAAI,CAAC;QACvB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;IACf,CAAC;CA2GF","sourcesContent":["import {\n // types\n type PresenceOpts,\n type PresenceResponse,\n type RoomSchemaShape,\n InstantCoreDatabase,\n InstantSchemaDef,\n} from '@instantdb/core';\n\nimport {\n KeyboardEvent,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from 'react';\n\nimport { useTimeout } from './useTimeout.ts';\n\nexport type PresenceHandle<\n PresenceShape,\n Keys extends keyof PresenceShape,\n> = PresenceResponse<PresenceShape, Keys> & {\n publishPresence: (data: Partial<PresenceShape>) => void;\n};\n\nexport type TypingIndicatorOpts = {\n timeout?: number | null;\n stopOnEnter?: boolean;\n // Perf opt - `active` will always be an empty array\n writeOnly?: boolean;\n};\n\nexport type TypingIndicatorHandle<PresenceShape> = {\n active: PresenceShape[];\n setActive(active: boolean): void;\n inputProps: {\n onKeyDown: (e: KeyboardEvent) => void;\n onBlur: () => void;\n };\n};\n\nexport const defaultActivityStopTimeout = 1_000;\n\n// ------\n// Topics\n\n/**\n * Listen for broadcasted events given a room and topic.\n *\n * @see https://instantdb.com/docs/presence-and-topics\n * @example\n * function App({ roomId }) {\n * const room = db.room('chats', roomId);\n * db.rooms.useTopicEffect(room, 'emoji', (message, peer) => {\n * console.log(peer.name, 'sent', message);\n * });\n * // ...\n * }\n */\nexport function useTopicEffect<\n RoomSchema extends RoomSchemaShape,\n RoomType extends keyof RoomSchema,\n TopicType extends keyof RoomSchema[RoomType]['topics'],\n>(\n room: InstantReactRoom<any, RoomSchema, RoomType>,\n topic: TopicType,\n onEvent: (\n event: RoomSchema[RoomType]['topics'][TopicType],\n peer: RoomSchema[RoomType]['presence'],\n ) => any,\n): void {\n const onEventRef = useRef(onEvent);\n onEventRef.current = onEvent;\n\n useEffect(() => {\n const unsub = room.core._reactor.subscribeTopic(\n room.id,\n topic,\n (event, peer) => {\n onEventRef.current(event, peer);\n },\n );\n\n return unsub;\n }, [room.id, topic]);\n}\n\n/**\n * Broadcast an event to a room.\n *\n * @see https://instantdb.com/docs/presence-and-topics\n * @example\n * function App({ roomId }) {\n * const room = db.room('chat', roomId);\n * const publishTopic = db.rooms.usePublishTopic(room, \"emoji\");\n *\n * return (\n * <button onClick={() => publishTopic({ emoji: \"🔥\" })}>Send emoji</button>\n * );\n * }\n *\n */\nexport function usePublishTopic<\n RoomSchema extends RoomSchemaShape,\n RoomType extends keyof RoomSchema,\n TopicType extends keyof RoomSchema[RoomType]['topics'],\n>(\n room: InstantReactRoom<any, RoomSchema, RoomType>,\n topic: TopicType,\n): (data: RoomSchema[RoomType]['topics'][TopicType]) => void {\n useEffect(() => room.core._reactor.joinRoom(room.id), [room.id]);\n\n const publishTopic = useCallback(\n (data) => {\n room.core._reactor.publishTopic({\n roomType: room.type,\n roomId: room.id,\n topic,\n data,\n });\n },\n [room.id, topic],\n );\n\n return publishTopic;\n}\n\n// ---------\n// Presence\n\n/**\n * Listen for peer's presence data in a room, and publish the current user's presence.\n *\n * @see https://instantdb.com/docs/presence-and-topics\n * @example\n * function App({ roomId }) {\n * const {\n * peers,\n * publishPresence\n * } = db.room(roomType, roomId).usePresence({ keys: [\"name\", \"avatar\"] });\n *\n * // ...\n * }\n */\nexport function usePresence<\n RoomSchema extends RoomSchemaShape,\n RoomType extends keyof RoomSchema,\n Keys extends keyof RoomSchema[RoomType]['presence'],\n>(\n room: InstantReactRoom<any, RoomSchema, RoomType>,\n opts: PresenceOpts<RoomSchema[RoomType]['presence'], Keys> = {},\n): PresenceHandle<RoomSchema[RoomType]['presence'], Keys> {\n const [state, setState] = useState<\n PresenceResponse<RoomSchema[RoomType]['presence'], Keys>\n >(() => {\n return (\n room.core._reactor.getPresence(room.type, room.id, opts) ?? {\n peers: {},\n isLoading: true,\n }\n );\n });\n\n useEffect(() => {\n const unsub = room.core._reactor.subscribePresence(\n room.type,\n room.id,\n opts,\n (data) => {\n setState(data);\n },\n );\n\n return unsub;\n }, [room.id, opts.user, opts.peers?.join(), opts.keys?.join()]);\n\n const publishPresence = useCallback(\n (data) => {\n room.core._reactor.publishPresence(room.type, room.id, data);\n },\n [room.type, room.id],\n );\n const ret = useMemo(() => {\n return {\n ...state,\n publishPresence,\n };\n }, [state, publishPresence]);\n return ret;\n}\n\n/**\n * Publishes presence data to a room\n *\n * @see https://instantdb.com/docs/presence-and-topics\n * @example\n * function App({ roomId, nickname }) {\n * const room = db.room('chat', roomId);\n * db.rooms.useSyncPresence(room, { nickname });\n * }\n */\nexport function useSyncPresence<\n RoomSchema extends RoomSchemaShape,\n RoomType extends keyof RoomSchema,\n>(\n room: InstantReactRoom<any, RoomSchema, RoomType>,\n data: Partial<RoomSchema[RoomType]['presence']>,\n deps?: any[],\n): void {\n useEffect(() => room.core._reactor.joinRoom(room.id, data), [room.id]);\n useEffect(() => {\n return room.core._reactor.publishPresence(room.type, room.id, data);\n }, [room.type, room.id, deps ?? JSON.stringify(data)]);\n}\n\n// -----------------\n// Typing Indicator\n\n/**\n * Manage typing indicator state\n *\n * @see https://instantdb.com/docs/presence-and-topics\n * @example\n * function App({ roomId }) {\n * const room = db.room('chat', roomId);\n * const {\n * active,\n * setActive,\n * inputProps,\n * } = db.rooms.useTypingIndicator(room, \"chat-input\");\n *\n * return <input {...inputProps} />;\n * }\n */\nexport function useTypingIndicator<\n RoomSchema extends RoomSchemaShape,\n RoomType extends keyof RoomSchema,\n>(\n room: InstantReactRoom<any, RoomSchema, RoomType>,\n inputName: string,\n opts: TypingIndicatorOpts = {},\n): TypingIndicatorHandle<RoomSchema[RoomType]['presence']> {\n const timeout = useTimeout();\n\n const observedPresence = rooms.usePresence(room, {\n keys: [inputName],\n });\n\n const active = useMemo(() => {\n const presenceSnapshot = room._core._reactor.getPresence(\n room.type,\n room.id,\n );\n\n return opts?.writeOnly\n ? []\n : Object.values(presenceSnapshot?.peers ?? {}).filter(\n (p) => p[inputName] === true,\n );\n }, [opts?.writeOnly, observedPresence]);\n\n const setActive = useCallback(\n (isActive: boolean) => {\n room.core._reactor.publishPresence(room.type, room.id, {\n [inputName]: isActive,\n } as unknown as Partial<RoomSchema[RoomType]>);\n\n if (!isActive) return;\n\n if (opts?.timeout === null || opts?.timeout === 0) return;\n\n timeout.set(opts?.timeout ?? defaultActivityStopTimeout, () => {\n room.core._reactor.publishPresence(room.type, room.id, {\n [inputName]: null,\n } as Partial<RoomSchema[RoomType]>);\n });\n },\n [room.type, room.id, inputName, opts?.timeout, timeout],\n );\n const onKeyDown = useCallback(\n (e: KeyboardEvent) => {\n const isEnter = opts?.stopOnEnter && e.key === 'Enter';\n const isActive = !isEnter;\n\n setActive(isActive);\n },\n [opts.stopOnEnter, setActive],\n );\n const onBlur = useCallback(() => {\n setActive(false);\n }, [setActive]);\n\n const inputProps = useMemo(() => {\n return { onKeyDown, onBlur };\n }, [onKeyDown, onBlur]);\n\n return {\n active,\n setActive,\n inputProps,\n };\n}\n\n// --------------\n// Hooks\n\nexport const rooms = {\n useTopicEffect,\n usePublishTopic,\n usePresence,\n useSyncPresence,\n useTypingIndicator,\n};\n\n// ------------\n// Class\n\nexport class InstantReactRoom<\n Schema extends InstantSchemaDef<any, any, any>,\n RoomSchema extends RoomSchemaShape,\n RoomType extends keyof RoomSchema,\n> {\n core: InstantCoreDatabase<Schema, boolean>;\n /** @deprecated use `core` instead */\n _core: InstantCoreDatabase<Schema, boolean>;\n type: RoomType;\n id: string;\n\n constructor(\n core: InstantCoreDatabase<Schema, boolean>,\n type: RoomType,\n id: string,\n ) {\n this.core = core;\n this._core = this.core;\n this.type = type;\n this.id = id;\n }\n\n /**\n * @deprecated\n * `db.room(...).useTopicEffect` is deprecated. You can replace it with `db.rooms.useTopicEffect`.\n *\n * @example\n *\n * // Before\n * const room = db.room('chat', 'room-id');\n * room.useTopicEffect('emoji', (message, peer) => { });\n *\n * // After\n * const room = db.room('chat', 'room-id');\n * db.rooms.useTopicEffect(room, 'emoji', (message, peer) => { });\n */\n useTopicEffect = <TopicType extends keyof RoomSchema[RoomType]['topics']>(\n topic: TopicType,\n onEvent: (\n event: RoomSchema[RoomType]['topics'][TopicType],\n peer: RoomSchema[RoomType]['presence'],\n ) => any,\n ): void => {\n rooms.useTopicEffect(this, topic, onEvent);\n };\n\n /**\n * @deprecated\n * `db.room(...).usePublishTopic` is deprecated. You can replace it with `db.rooms.usePublishTopic`.\n *\n * @example\n *\n * // Before\n * const room = db.room('chat', 'room-id');\n * const publish = room.usePublishTopic('emoji');\n *\n * // After\n * const room = db.room('chat', 'room-id');\n * const publish = db.rooms.usePublishTopic(room, 'emoji');\n */\n usePublishTopic = <Topic extends keyof RoomSchema[RoomType]['topics']>(\n topic: Topic,\n ): ((data: RoomSchema[RoomType]['topics'][Topic]) => void) => {\n return rooms.usePublishTopic(this, topic);\n };\n\n /**\n * @deprecated\n * `db.room(...).usePresence` is deprecated. You can replace it with `db.rooms.usePresence`.\n *\n * @example\n *\n * // Before\n * const room = db.room('chat', 'room-id');\n * const { peers } = room.usePresence({ keys: [\"name\", \"avatar\"] });\n *\n * // After\n * const room = db.room('chat', 'room-id');\n * const { peers } = db.rooms.usePresence(room, { keys: [\"name\", \"avatar\"] });\n */\n usePresence = <Keys extends keyof RoomSchema[RoomType]['presence']>(\n opts: PresenceOpts<RoomSchema[RoomType]['presence'], Keys> = {},\n ): PresenceHandle<RoomSchema[RoomType]['presence'], Keys> => {\n return rooms.usePresence(this, opts);\n };\n\n /**\n * @deprecated\n * `db.room(...).useSyncPresence` is deprecated. You can replace it with `db.rooms.useSyncPresence`.\n *\n * @example\n *\n * // Before\n * const room = db.room('chat', 'room-id');\n * room.useSyncPresence(room, { nickname });\n *\n * // After\n * const room = db.room('chat', 'room-id');\n * db.rooms.useSyncPresence(room, { nickname });\n */\n useSyncPresence = (\n data: Partial<RoomSchema[RoomType]['presence']>,\n deps?: any[],\n ): void => {\n return rooms.useSyncPresence(this, data, deps);\n };\n\n /**\n * @deprecated\n * `db.room(...).useTypingIndicator` is deprecated. You can replace it with `db.rooms.useTypingIndicator`.\n *\n * @example\n *\n * // Before\n * const room = db.room('chat', 'room-id');\n * const typing = room.useTypingIndiactor(room, 'chat-input');\n *\n * // After\n * const room = db.room('chat', 'room-id');\n * const typing = db.rooms.useTypingIndiactor(room, 'chat-input');\n */\n useTypingIndicator = (\n inputName: string,\n opts: TypingIndicatorOpts = {},\n ): TypingIndicatorHandle<RoomSchema[RoomType]['presence']> => {\n return rooms.useTypingIndicator(this, inputName, opts);\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"InstantReactRoom.js","sourceRoot":"","sources":["../../src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Y,EAC6C,EAAE;YAC3D,OAAO,KAAK,CAAC,eAAe,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;QAC5C,CAAC,CAAC;QAEF;;;;;;;;;;;;;WAaG;QACH,gBAAW,GAAG,CACZ,OAA6D,EAAE,EACP,EAAE;YAC1D,OAAO,KAAK,CAAC,WAAW,CAAC,IAAI,EAAE,IAAI,CAAC,CAAC;QACvC,CAAC,CAAC;QAEF;;;;;;;;;;;;;WAaG;QACH,oBAAe,GAAG,CAChB,IAA+C,EAC/C,IAAY,EACN,EAAE;YACR,OAAO,KAAK,CAAC,eAAe,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC;QACjD,CAAC,CAAC;QAEF;;;;;;;;;;;;;WAaG;QACH,uBAAkB,GAAG,CACnB,SAAiB,EACjB,OAA4B,EAAE,EAC2B,EAAE;YAC3D,OAAO,KAAK,CAAC,kBAAkB,CAAC,IAAI,EAAE,SAAS,EAAE,IAAI,CAAC,CAAC;QACzD,CAAC,CAAC;QA9GA,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC,IAAI,CAAC;QACvB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;IACf,CAAC;CA2GF","sourcesContent":["import {\n // types\n type PresenceOpts,\n type PresenceResponse,\n type RoomSchemaShape,\n InstantCoreDatabase,\n InstantSchemaDef,\n} from '@instantdb/core';\n\nimport {\n KeyboardEvent,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from 'react';\n\nimport { useTimeout } from './useTimeout.ts';\n\nexport type PresenceHandle<\n PresenceShape,\n Keys extends keyof PresenceShape,\n> = PresenceResponse<PresenceShape, Keys> & {\n publishPresence: (data: Partial<PresenceShape>) => void;\n};\n\nexport type TypingIndicatorOpts = {\n timeout?: number | null;\n stopOnEnter?: boolean;\n // Perf opt - `active` will always be an empty array\n writeOnly?: boolean;\n};\n\nexport type TypingIndicatorHandle<PresenceShape> = {\n active: PresenceShape[];\n setActive(active: boolean): void;\n inputProps: {\n onKeyDown: (e: KeyboardEvent) => void;\n onBlur: () => void;\n };\n};\n\nexport const defaultActivityStopTimeout = 1_000;\n\n// ------\n// Topics\n\n/**\n * Listen for broadcasted events given a room and topic.\n *\n * @see https://instantdb.com/docs/presence-and-topics\n * @example\n * function App({ roomId }) {\n * const room = db.room('chats', roomId);\n * db.rooms.useTopicEffect(room, 'emoji', (message, peer) => {\n * console.log(peer.name, 'sent', message);\n * });\n * // ...\n * }\n */\nexport function useTopicEffect<\n RoomSchema extends RoomSchemaShape,\n RoomType extends keyof RoomSchema,\n TopicType extends keyof RoomSchema[RoomType]['topics'],\n>(\n room: InstantReactRoom<any, RoomSchema, RoomType>,\n topic: TopicType,\n onEvent: (\n event: RoomSchema[RoomType]['topics'][TopicType],\n peer: RoomSchema[RoomType]['presence'],\n ) => any,\n): void {\n const onEventRef = useRef(onEvent);\n onEventRef.current = onEvent;\n\n useEffect(() => {\n const unsub = room.core._reactor.subscribeTopic(\n room.id,\n topic,\n (event, peer) => {\n onEventRef.current(event, peer);\n },\n );\n\n return unsub;\n }, [room.id, topic]);\n}\n\n/**\n * Broadcast an event to a room.\n *\n * @see https://instantdb.com/docs/presence-and-topics\n * @example\n * function App({ roomId }) {\n * const room = db.room('chat', roomId);\n * const publishTopic = db.rooms.usePublishTopic(room, \"emoji\");\n *\n * return (\n * <button onClick={() => publishTopic({ emoji: \"🔥\" })}>Send emoji</button>\n * );\n * }\n *\n */\nexport function usePublishTopic<\n RoomSchema extends RoomSchemaShape,\n RoomType extends keyof RoomSchema,\n TopicType extends keyof RoomSchema[RoomType]['topics'],\n>(\n room: InstantReactRoom<any, RoomSchema, RoomType>,\n topic: TopicType,\n): (data: RoomSchema[RoomType]['topics'][TopicType]) => void {\n useEffect(() => room.core._reactor.joinRoom(room.id), [room.id]);\n\n const publishTopic = useCallback(\n (data) => {\n room.core._reactor.publishTopic({\n roomType: room.type,\n roomId: room.id,\n topic,\n data,\n });\n },\n [room.id, topic],\n );\n\n return publishTopic;\n}\n\n// ---------\n// Presence\n\n/**\n * Listen for peer's presence data in a room, and publish the current user's presence.\n *\n * @see https://instantdb.com/docs/presence-and-topics\n * @example\n * function App({ roomId }) {\n * const {\n * peers,\n * publishPresence\n * } = db.room(roomType, roomId).usePresence({ keys: [\"name\", \"avatar\"] });\n *\n * // ...\n * }\n */\nexport function usePresence<\n RoomSchema extends RoomSchemaShape,\n RoomType extends keyof RoomSchema,\n Keys extends keyof RoomSchema[RoomType]['presence'],\n>(\n room: InstantReactRoom<any, RoomSchema, RoomType>,\n opts: PresenceOpts<RoomSchema[RoomType]['presence'], Keys> = {},\n): PresenceHandle<RoomSchema[RoomType]['presence'], Keys> {\n const [state, setState] = useState<\n PresenceResponse<RoomSchema[RoomType]['presence'], Keys>\n >(() => {\n return (\n room.core._reactor.getPresence(room.type, room.id, opts) ?? {\n peers: {},\n isLoading: true,\n }\n );\n });\n\n useEffect(() => {\n const unsub = room.core._reactor.subscribePresence(\n room.type,\n room.id,\n opts,\n (data) => {\n setState(data);\n },\n );\n\n return unsub;\n }, [room.id, opts.user, opts.peers?.join(), opts.keys?.join()]);\n\n const publishPresence = useCallback(\n (data) => {\n room.core._reactor.publishPresence(room.type, room.id, data);\n },\n [room.type, room.id],\n );\n const ret = useMemo(() => {\n return {\n ...state,\n publishPresence,\n };\n }, [state, publishPresence]);\n return ret;\n}\n\n/**\n * Publishes presence data to a room\n *\n * @see https://instantdb.com/docs/presence-and-topics\n * @example\n * function App({ roomId, nickname }) {\n * const room = db.room('chat', roomId);\n * db.rooms.useSyncPresence(room, { nickname });\n * }\n */\nexport function useSyncPresence<\n RoomSchema extends RoomSchemaShape,\n RoomType extends keyof RoomSchema,\n>(\n room: InstantReactRoom<any, RoomSchema, RoomType>,\n data: Partial<RoomSchema[RoomType]['presence']>,\n deps?: any[],\n): void {\n useEffect(() => room.core._reactor.joinRoom(room.id, data), [room.id]);\n useEffect(() => {\n return room.core._reactor.publishPresence(room.type, room.id, data);\n }, [room.type, room.id, deps ?? JSON.stringify(data)]);\n}\n\n// -----------------\n// Typing Indicator\n\n/**\n * Manage typing indicator state\n *\n * @see https://instantdb.com/docs/presence-and-topics\n * @example\n * function App({ roomId }) {\n * const room = db.room('chat', roomId);\n * const {\n * active,\n * setActive,\n * inputProps,\n * } = db.rooms.useTypingIndicator(room, \"chat-input\");\n *\n * return <input {...inputProps} />;\n * }\n */\nexport function useTypingIndicator<\n RoomSchema extends RoomSchemaShape,\n RoomType extends keyof RoomSchema,\n>(\n room: InstantReactRoom<any, RoomSchema, RoomType>,\n inputName: string,\n opts: TypingIndicatorOpts = {},\n): TypingIndicatorHandle<RoomSchema[RoomType]['presence']> {\n const timeout = useTimeout();\n\n const observedPresence = rooms.usePresence(room, {\n keys: [inputName] as (keyof RoomSchema[RoomType]['presence'])[],\n });\n\n const active = useMemo(() => {\n const presenceSnapshot = room._core._reactor.getPresence(\n room.type,\n room.id,\n );\n\n return opts?.writeOnly\n ? []\n : Object.values(presenceSnapshot?.peers ?? {}).filter(\n (p) => p[inputName] === true,\n );\n }, [opts?.writeOnly, observedPresence]);\n\n const setActive = useCallback(\n (isActive: boolean) => {\n room.core._reactor.publishPresence(room.type, room.id, {\n [inputName]: isActive,\n } as unknown as Partial<RoomSchema[RoomType]>);\n\n if (!isActive) return;\n\n if (opts?.timeout === null || opts?.timeout === 0) return;\n\n timeout.set(opts?.timeout ?? defaultActivityStopTimeout, () => {\n room.core._reactor.publishPresence(room.type, room.id, {\n [inputName]: null,\n } as Partial<RoomSchema[RoomType]>);\n });\n },\n [room.type, room.id, inputName, opts?.timeout, timeout],\n );\n const onKeyDown = useCallback(\n (e: KeyboardEvent) => {\n const isEnter = opts?.stopOnEnter && e.key === 'Enter';\n const isActive = !isEnter;\n\n setActive(isActive);\n },\n [opts.stopOnEnter, setActive],\n );\n const onBlur = useCallback(() => {\n setActive(false);\n }, [setActive]);\n\n const inputProps = useMemo(() => {\n return { onKeyDown, onBlur };\n }, [onKeyDown, onBlur]);\n\n return {\n active,\n setActive,\n inputProps,\n };\n}\n\n// --------------\n// Hooks\n\nexport const rooms = {\n useTopicEffect,\n usePublishTopic,\n usePresence,\n useSyncPresence,\n useTypingIndicator,\n};\n\n// ------------\n// Class\n\nexport class InstantReactRoom<\n Schema extends InstantSchemaDef<any, any, any>,\n RoomSchema extends RoomSchemaShape,\n RoomType extends keyof RoomSchema,\n> {\n core: InstantCoreDatabase<Schema, boolean>;\n /** @deprecated use `core` instead */\n _core: InstantCoreDatabase<Schema, boolean>;\n type: RoomType;\n id: string;\n\n constructor(\n core: InstantCoreDatabase<Schema, boolean>,\n type: RoomType,\n id: string,\n ) {\n this.core = core;\n this._core = this.core;\n this.type = type;\n this.id = id;\n }\n\n /**\n * @deprecated\n * `db.room(...).useTopicEffect` is deprecated. You can replace it with `db.rooms.useTopicEffect`.\n *\n * @example\n *\n * // Before\n * const room = db.room('chat', 'room-id');\n * room.useTopicEffect('emoji', (message, peer) => { });\n *\n * // After\n * const room = db.room('chat', 'room-id');\n * db.rooms.useTopicEffect(room, 'emoji', (message, peer) => { });\n */\n useTopicEffect = <TopicType extends keyof RoomSchema[RoomType]['topics']>(\n topic: TopicType,\n onEvent: (\n event: RoomSchema[RoomType]['topics'][TopicType],\n peer: RoomSchema[RoomType]['presence'],\n ) => any,\n ): void => {\n rooms.useTopicEffect(this, topic, onEvent);\n };\n\n /**\n * @deprecated\n * `db.room(...).usePublishTopic` is deprecated. You can replace it with `db.rooms.usePublishTopic`.\n *\n * @example\n *\n * // Before\n * const room = db.room('chat', 'room-id');\n * const publish = room.usePublishTopic('emoji');\n *\n * // After\n * const room = db.room('chat', 'room-id');\n * const publish = db.rooms.usePublishTopic(room, 'emoji');\n */\n usePublishTopic = <Topic extends keyof RoomSchema[RoomType]['topics']>(\n topic: Topic,\n ): ((data: RoomSchema[RoomType]['topics'][Topic]) => void) => {\n return rooms.usePublishTopic(this, topic);\n };\n\n /**\n * @deprecated\n * `db.room(...).usePresence` is deprecated. You can replace it with `db.rooms.usePresence`.\n *\n * @example\n *\n * // Before\n * const room = db.room('chat', 'room-id');\n * const { peers } = room.usePresence({ keys: [\"name\", \"avatar\"] });\n *\n * // After\n * const room = db.room('chat', 'room-id');\n * const { peers } = db.rooms.usePresence(room, { keys: [\"name\", \"avatar\"] });\n */\n usePresence = <Keys extends keyof RoomSchema[RoomType]['presence']>(\n opts: PresenceOpts<RoomSchema[RoomType]['presence'], Keys> = {},\n ): PresenceHandle<RoomSchema[RoomType]['presence'], Keys> => {\n return rooms.usePresence(this, opts);\n };\n\n /**\n * @deprecated\n * `db.room(...).useSyncPresence` is deprecated. You can replace it with `db.rooms.useSyncPresence`.\n *\n * @example\n *\n * // Before\n * const room = db.room('chat', 'room-id');\n * room.useSyncPresence(room, { nickname });\n *\n * // After\n * const room = db.room('chat', 'room-id');\n * db.rooms.useSyncPresence(room, { nickname });\n */\n useSyncPresence = (\n data: Partial<RoomSchema[RoomType]['presence']>,\n deps?: any[],\n ): void => {\n return rooms.useSyncPresence(this, data, deps);\n };\n\n /**\n * @deprecated\n * `db.room(...).useTypingIndicator` is deprecated. You can replace it with `db.rooms.useTypingIndicator`.\n *\n * @example\n *\n * // Before\n * const room = db.room('chat', 'room-id');\n * const typing = room.useTypingIndiactor(room, 'chat-input');\n *\n * // After\n * const room = db.room('chat', 'room-id');\n * const typing = db.rooms.useTypingIndiactor(room, 'chat-input');\n */\n useTypingIndicator = (\n inputName: string,\n opts: TypingIndicatorOpts = {},\n ): TypingIndicatorHandle<RoomSchema[RoomType]['presence']> => {\n return rooms.useTypingIndicator(this, inputName, opts);\n };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useQuery.d.ts","sourceRoot":"","sources":["../../src/useQuery.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,KAAK,cAAc,EAEnB,mBAAmB,EACnB,qBAAqB,EACrB,gBAAgB,EAChB,UAAU,EACX,MAAM,iBAAiB,CAAC;AAoBzB,wBAAgB,gBAAgB,CAC9B,CAAC,SAAS,UAAU,CAAC,CAAC,EAAE,MAAM,CAAC,EAC/B,MAAM,SAAS,gBAAgB,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,EAC9C,QAAQ,SAAS,OAAO,EAExB,KAAK,EAAE,mBAAmB,CAAC,MAAM,EAAE,QAAQ,CAAC,EAC5C,MAAM,EAAE,IAAI,GAAG,CAAC,EAChB,KAAK,CAAC,EAAE,cAAc,GACrB;IACD,KAAK,EAAE,qBAAqB,CAAC,MAAM,EAAE,CAAC,EAAE,QAAQ,CAAC,CAAC;IAClD,KAAK,EAAE,GAAG,CAAC;CACZ,
|
|
1
|
+
{"version":3,"file":"useQuery.d.ts","sourceRoot":"","sources":["../../src/useQuery.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,KAAK,cAAc,EAEnB,mBAAmB,EACnB,qBAAqB,EACrB,gBAAgB,EAChB,UAAU,EACX,MAAM,iBAAiB,CAAC;AAoBzB,wBAAgB,gBAAgB,CAC9B,CAAC,SAAS,UAAU,CAAC,CAAC,EAAE,MAAM,CAAC,EAC/B,MAAM,SAAS,gBAAgB,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,EAC9C,QAAQ,SAAS,OAAO,EAExB,KAAK,EAAE,mBAAmB,CAAC,MAAM,EAAE,QAAQ,CAAC,EAC5C,MAAM,EAAE,IAAI,GAAG,CAAC,EAChB,KAAK,CAAC,EAAE,cAAc,GACrB;IACD,KAAK,EAAE,qBAAqB,CAAC,MAAM,EAAE,CAAC,EAAE,QAAQ,CAAC,CAAC;IAClD,KAAK,EAAE,GAAG,CAAC;CACZ,CA4DA"}
|
package/dist/esm/useQuery.js
CHANGED
|
@@ -32,7 +32,13 @@ export function useQueryInternal(_core, _query, _opts) {
|
|
|
32
32
|
return unsubscribe;
|
|
33
33
|
}
|
|
34
34
|
const unsubscribe = _core.subscribeQuery(query, (result) => {
|
|
35
|
-
resultCacheRef.current = Object.assign({ isLoading: !Boolean(result),
|
|
35
|
+
resultCacheRef.current = Object.assign({ isLoading: !Boolean(result),
|
|
36
|
+
// @ts-expect-error: ts thinks this will always be overwritten
|
|
37
|
+
data: undefined,
|
|
38
|
+
// @ts-expect-error: ts thinks this will always be overwritten
|
|
39
|
+
pageInfo: undefined,
|
|
40
|
+
// @ts-expect-error: ts thinks this will always be overwritten
|
|
41
|
+
error: undefined }, result);
|
|
36
42
|
cb();
|
|
37
43
|
});
|
|
38
44
|
return unsubscribe;
|