@liveblocks/react 1.11.2 → 1.12.0-lexical2
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/index.d.mts +229 -106
- package/dist/index.d.ts +229 -106
- package/dist/index.js +1979 -1844
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1986 -1851
- package/dist/index.mjs.map +1 -1
- package/package.json +5 -3
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/version.ts","../src/ClientSideSuspense.tsx","../src/liveblocks.tsx","../src/comments/lib/selected-inbox-notifications.ts","../src/lib/retry-error.ts","../src/shared.ts","../src/room.tsx","../src/comments/errors.ts","../src/comments/lib/createIds.ts","../src/comments/lib/select-notification-settings.ts","../src/comments/lib/selected-threads.ts","../src/lib/use-initial.ts","../src/lib/use-latest.ts","../src/lib/use-rerender.ts"],"names":["kInternal","makePoller","nanoid","React","createContext","useCallback","useContext","useEffect","useSyncExternalStore","useSyncExternalStoreWithSelector","console","applyOptimisticUpdates","useState","options","room","other","rootOrNull","subscribers","comment","state","err","metadata","mentionSuggestions","inboxNotification","settings","ContextBundle","POLLING_INTERVAL","shallow"],"mappings":";;;AAAA,SAAS,mBAAmB;;;ACGrB,IAAM,WAAW;AACjB,IAAM,cAAiD;AACvD,IAAM,aAAgD;;;ACJ7D,YAAY,WAAW;AAwBhB,SAAS,mBAAmB,OAA4B;AAC7D,QAAM,CAAC,SAAS,UAAU,IAAU,eAAS,KAAK;AAElD,EAAM,gBAAU,MAAM;AAGpB,eAAW,IAAI;AAAA,EACjB,GAAG,CAAC,CAAC;AAEL,SACE,oCAAO,gBAAN,EAAe,UAAU,MAAM,YAC7B,UAAU,MAAM,SAAS,IAAI,MAAM,QACtC;AAEJ;;;ACzBA,SAAS,aAAAA,YAAW,cAAAC,mBAAkB;AACtC,SAAS,UAAAC,eAAc;AAEvB,OAAOC;AAAA,EACL,iBAAAC;AA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AM;AAAA,MACN,MAAM;AAAA,MACN;AAAA,IACF;AAAA,EACF;AAEA,QAAM,qBAAqB,OAAOT,UAAS,EACxC;AAEH,WAAS,mBAAmB;AAC1B,WAAOQ;AAAA,MACL,mBAAmB;AAAA,MACnB,mBAAmB;AAAA,MACnB,mBAAmB;AAAA,IACrB;AAAA,EACF;AAEA,QAAM,SAA6C;AAAA,IACjD;AAAA,IAEA;AAAA,IACA;AAAA,IAEA;AAAA,IACA;AAAA,IAEA,GAAG;AAAA,IAEH,UAAU;AAAA,MACR;AAAA,MAEA,uBAAuB;AAAA,MACvB,kCACE;AAAA,MAEF;AAAA,MACA;AAAA,MAEA,GAAG,OAAO;AAAA,IACZ;AAAA,IAEA,CAACR,UAAS,GAAG;AAAA,MACX;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAEA,SAAO,OAAO,eAAe,QAAQA,YAAW;AAAA,IAC9C,YAAY;AAAA,EACd,CAAC;AACH;;;AHrfA,SAAS,WAAA2B,gBAAe;AAbxB,YAAY,UAAU,aAAa,UAAU","sourcesContent":["import { detectDupes } from \"@liveblocks/core\";\n\nimport { PKG_FORMAT, PKG_NAME, PKG_VERSION } from \"./version\";\n\ndetectDupes(PKG_NAME, PKG_VERSION, PKG_FORMAT);\n\nexport { ClientSideSuspense } from \"./ClientSideSuspense\";\nexport {\n createLiveblocksContext,\n useLiveblocksContextBundle,\n} from \"./liveblocks\";\nexport { createRoomContext, useRoomContextBundle } from \"./room\";\nexport { useSharedContextBundle } from \"./shared\";\nexport type { MutationContext, UseThreadsOptions } from \"./types\";\n\n// Re-exports from @liveblocks/client, for convenience\nexport type { Json, JsonObject } from \"@liveblocks/client\";\nexport { shallow } from \"@liveblocks/client\";\n","declare const __VERSION__: string;\ndeclare const TSUP_FORMAT: string;\n\nexport const PKG_NAME = \"@liveblocks/react\";\nexport const PKG_VERSION = typeof __VERSION__ === \"string\" && __VERSION__;\nexport const PKG_FORMAT = typeof TSUP_FORMAT === \"string\" && TSUP_FORMAT;\n","import type { ReactElement, ReactNode } from \"react\";\nimport * as React from \"react\";\n\ntype Props = {\n fallback: NonNullable<ReactNode> | null;\n children: () => ReactNode | undefined;\n};\n\n/**\n * Almost like a normal <Suspense> component, except that for server-side\n * renders, the fallback will be used.\n *\n * The child props will have to be provided in a function, i.e. change:\n *\n * <Suspense fallback={<Loading />}>\n * <MyRealComponent a={1} />\n * </Suspense>\n *\n * To:\n *\n * <ClientSideSuspense fallback={<Loading />}>\n * {() => <MyRealComponent a={1} />}\n * </ClientSideSuspense>\n *\n */\nexport function ClientSideSuspense(props: Props): ReactElement {\n const [mounted, setMounted] = React.useState(false);\n\n React.useEffect(() => {\n // Effects are never executed on the server side. The point of this is to\n // delay the flipping of this boolean until after hydration has happened.\n setMounted(true);\n }, []);\n\n return (\n <React.Suspense fallback={props.fallback}>\n {mounted ? props.children() : props.fallback}\n </React.Suspense>\n );\n}\n","import type {\n BaseMetadata,\n BaseUserMeta,\n Client,\n ThreadData,\n} from \"@liveblocks/client\";\nimport type {\n CacheState,\n CacheStore,\n InboxNotificationData,\n InboxNotificationDeleteInfo,\n Store,\n ThreadDeleteInfo,\n} from \"@liveblocks/core\";\nimport { kInternal, makePoller } from \"@liveblocks/core\";\nimport { nanoid } from \"nanoid\";\nimport type { PropsWithChildren } from \"react\";\nimport React, {\n createContext,\n useCallback,\n useContext,\n useEffect,\n} from \"react\";\nimport { useSyncExternalStore } from \"use-sync-external-store/shim/index.js\";\nimport { useSyncExternalStoreWithSelector } from \"use-sync-external-store/shim/with-selector.js\";\n\nimport { selectedInboxNotifications } from \"./comments/lib/selected-inbox-notifications\";\nimport { retryError } from \"./lib/retry-error\";\nimport { createSharedContext } from \"./shared\";\nimport type {\n InboxNotificationsState,\n InboxNotificationsStateSuccess,\n LiveblocksContextBundle,\n UnreadInboxNotificationsCountState,\n UnreadInboxNotificationsCountStateSuccess,\n} from \"./types\";\n\nexport const ContextBundle =\n createContext<LiveblocksContextBundle<BaseUserMeta> | null>(null);\n\n/**\n * @private\n *\n * This is an internal API, use \"createLiveblocksContext\" instead.\n */\nexport function useLiveblocksContextBundle() {\n const bundle = useContext(ContextBundle);\n if (bundle === null) {\n throw new Error(\"LiveblocksProvider is missing from the React tree.\");\n }\n return bundle;\n}\n\nexport const POLLING_INTERVAL = 60 * 1000; // 1 minute\nexport const INBOX_NOTIFICATIONS_QUERY = \"INBOX_NOTIFICATIONS\";\n\nexport function createLiveblocksContext<\n TUserMeta extends BaseUserMeta = BaseUserMeta,\n TThreadMetadata extends BaseMetadata = never,\n>(client: Client): LiveblocksContextBundle<TUserMeta> {\n const shared = createSharedContext<TUserMeta>(client);\n\n const store = client[kInternal]\n .cacheStore as unknown as CacheStore<TThreadMetadata>;\n\n const notifications = client[kInternal].notifications;\n\n function LiveblocksProvider(props: PropsWithChildren) {\n return (\n <ContextBundle.Provider\n value={bundle as unknown as LiveblocksContextBundle<BaseUserMeta>}\n >\n {props.children}\n </ContextBundle.Provider>\n );\n }\n\n // TODO: Unify request cache\n let fetchInboxNotificationsRequest: Promise<{\n inboxNotifications: InboxNotificationData[];\n threads: ThreadData<TThreadMetadata>[];\n deletedThreads: ThreadDeleteInfo[];\n deletedInboxNotifications: InboxNotificationDeleteInfo[];\n meta: {\n requestedAt: Date;\n };\n }> | null = null;\n let inboxNotificationsSubscribers = 0;\n let lastRequestedAt: Date | undefined;\n\n const poller = makePoller(refreshThreadsAndNotifications);\n\n function refreshThreadsAndNotifications() {\n return notifications.getInboxNotifications({ since: lastRequestedAt }).then(\n (result) => {\n lastRequestedAt = result.meta.requestedAt;\n\n store.updateThreadsAndNotifications(\n result.threads,\n result.inboxNotifications,\n result.deletedThreads,\n result.deletedInboxNotifications,\n INBOX_NOTIFICATIONS_QUERY\n );\n },\n () => {\n // TODO: Error handling\n }\n );\n }\n\n function incrementInboxNotificationsSubscribers() {\n inboxNotificationsSubscribers++;\n\n poller.start(POLLING_INTERVAL);\n }\n\n function decrementInboxNotificationsSubscribers() {\n if (inboxNotificationsSubscribers <= 0) {\n console.warn(\n `Internal unexpected behavior. Cannot decrease subscriber count for query \"${INBOX_NOTIFICATIONS_QUERY}\"`\n );\n return;\n }\n\n inboxNotificationsSubscribers--;\n\n if (inboxNotificationsSubscribers <= 0) {\n poller.stop();\n }\n }\n\n async function fetchInboxNotifications(\n { retryCount }: { retryCount: number } = { retryCount: 0 }\n ) {\n if (fetchInboxNotificationsRequest !== null) {\n return fetchInboxNotificationsRequest;\n }\n\n store.setQueryState(INBOX_NOTIFICATIONS_QUERY, {\n isLoading: true,\n });\n\n try {\n fetchInboxNotificationsRequest = notifications.getInboxNotifications();\n\n const result = await fetchInboxNotificationsRequest;\n\n store.updateThreadsAndNotifications(\n result.threads,\n result.inboxNotifications,\n result.deletedThreads,\n result.deletedInboxNotifications,\n INBOX_NOTIFICATIONS_QUERY\n );\n\n /**\n * We set the `lastRequestedAt` to the timestamp returned by the current request if:\n * 1. The `lastRequestedAt`has not been set\n * OR\n * 2. The current `lastRequestedAt` is older than the timestamp returned by the current request\n */\n if (\n lastRequestedAt === undefined ||\n lastRequestedAt > result.meta.requestedAt\n ) {\n lastRequestedAt = result.meta.requestedAt;\n }\n\n poller.start(POLLING_INTERVAL);\n } catch (er) {\n fetchInboxNotificationsRequest = null;\n\n // Retry the action using the exponential backoff algorithm\n retryError(() => {\n void fetchInboxNotifications({\n retryCount: retryCount + 1,\n });\n }, retryCount);\n\n store.setQueryState(INBOX_NOTIFICATIONS_QUERY, {\n isLoading: false,\n error: er as Error,\n });\n }\n return;\n }\n\n function useInboxNotificationsSelectorCallback(\n state: CacheState<BaseMetadata>\n ): InboxNotificationsState {\n const query = state.queries[INBOX_NOTIFICATIONS_QUERY];\n\n if (query === undefined || query.isLoading) {\n return {\n isLoading: true,\n };\n }\n\n if (query.error !== undefined) {\n return {\n error: query.error,\n isLoading: false,\n };\n }\n\n return {\n inboxNotifications: selectedInboxNotifications(state),\n isLoading: false,\n };\n }\n\n function useInboxNotifications(): InboxNotificationsState {\n useEffect(() => {\n void fetchInboxNotifications();\n incrementInboxNotificationsSubscribers();\n\n return () => decrementInboxNotificationsSubscribers();\n }, []);\n\n const result = useSyncExternalStoreWithSelector(\n store.subscribe,\n store.get,\n store.get,\n useInboxNotificationsSelectorCallback\n );\n\n return result;\n }\n\n function useInboxNotificationsSuspenseSelector(\n state: CacheState<BaseMetadata>\n ): InboxNotificationsStateSuccess {\n return {\n inboxNotifications: selectedInboxNotifications(state),\n isLoading: false,\n };\n }\n\n function useInboxNotificationsSuspense(): InboxNotificationsStateSuccess {\n const query = store.get().queries[INBOX_NOTIFICATIONS_QUERY];\n\n if (query === undefined || query.isLoading) {\n throw fetchInboxNotifications();\n }\n\n if (query.error !== undefined) {\n throw query.error;\n }\n\n React.useEffect(() => {\n incrementInboxNotificationsSubscribers();\n\n return () => {\n decrementInboxNotificationsSubscribers();\n };\n }, []);\n\n return useSyncExternalStoreWithSelector(\n store.subscribe,\n store.get,\n store.get,\n useInboxNotificationsSuspenseSelector\n );\n }\n\n function selectUnreadInboxNotificationsCount(\n state: CacheState<BaseMetadata>\n ) {\n let count = 0;\n\n for (const notification of selectedInboxNotifications(state)) {\n if (\n notification.readAt === null ||\n notification.readAt < notification.notifiedAt\n ) {\n count++;\n }\n }\n\n return count;\n }\n\n function useUnreadInboxNotificationsCountSelector(\n state: CacheState<BaseMetadata>\n ): UnreadInboxNotificationsCountState {\n const query = state.queries[INBOX_NOTIFICATIONS_QUERY];\n\n if (query === undefined || query.isLoading) {\n return {\n isLoading: true,\n };\n }\n\n if (query.error !== undefined) {\n return {\n error: query.error,\n isLoading: false,\n };\n }\n\n return {\n isLoading: false,\n count: selectUnreadInboxNotificationsCount(state),\n };\n }\n\n function useUnreadInboxNotificationsCount(): UnreadInboxNotificationsCountState {\n useEffect(() => {\n void fetchInboxNotifications();\n incrementInboxNotificationsSubscribers();\n\n return () => decrementInboxNotificationsSubscribers();\n }, []);\n\n return useSyncExternalStoreWithSelector(\n store.subscribe,\n store.get,\n store.get,\n useUnreadInboxNotificationsCountSelector\n );\n }\n\n function useUnreadInboxNotificationsCountSuspenseSelector(\n state: CacheState<BaseMetadata>\n ): UnreadInboxNotificationsCountStateSuccess {\n return {\n isLoading: false,\n count: selectUnreadInboxNotificationsCount(state),\n };\n }\n\n function useUnreadInboxNotificationsCountSuspense(): UnreadInboxNotificationsCountStateSuccess {\n const query = store.get().queries[INBOX_NOTIFICATIONS_QUERY];\n\n if (query === undefined || query.isLoading) {\n throw fetchInboxNotifications();\n }\n\n React.useEffect(() => {\n incrementInboxNotificationsSubscribers();\n\n return () => {\n decrementInboxNotificationsSubscribers();\n };\n }, []);\n\n return useSyncExternalStoreWithSelector(\n store.subscribe,\n store.get,\n store.get,\n useUnreadInboxNotificationsCountSuspenseSelector\n );\n }\n\n function useMarkInboxNotificationAsRead() {\n return useCallback((inboxNotificationId: string) => {\n const optimisticUpdateId = nanoid();\n const readAt = new Date();\n store.pushOptimisticUpdate({\n type: \"mark-inbox-notification-as-read\",\n id: optimisticUpdateId,\n inboxNotificationId,\n readAt,\n });\n\n notifications.markInboxNotificationAsRead(inboxNotificationId).then(\n () => {\n store.set((state) => {\n const existingNotification =\n state.inboxNotifications[inboxNotificationId];\n\n // If existing notification has been deleted, we return the existing state\n if (existingNotification === undefined) {\n return {\n ...state,\n optimisticUpdates: state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n ),\n };\n }\n\n return {\n ...state,\n inboxNotifications: {\n ...state.inboxNotifications,\n [inboxNotificationId]: {\n ...existingNotification,\n readAt,\n },\n },\n optimisticUpdates: state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n ),\n };\n });\n },\n () => {\n // TODO: Broadcast errors to client\n store.set((state) => ({\n ...state,\n optimisticUpdates: state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n ),\n }));\n }\n );\n }, []);\n }\n\n function useMarkAllInboxNotificationsAsRead() {\n return useCallback(() => {\n const optimisticUpdateId = nanoid();\n const readAt = new Date();\n store.pushOptimisticUpdate({\n type: \"mark-inbox-notifications-as-read\",\n id: optimisticUpdateId,\n readAt,\n });\n\n notifications.markAllInboxNotificationsAsRead().then(\n () => {\n store.set((state) => ({\n ...state,\n inboxNotifications: Object.fromEntries(\n Array.from(Object.entries(state.inboxNotifications)).map(\n ([id, inboxNotification]) => [\n id,\n { ...inboxNotification, readAt },\n ]\n )\n ),\n optimisticUpdates: state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n ),\n }));\n },\n () => {\n // TODO: Broadcast errors to client\n store.set((state) => ({\n ...state,\n optimisticUpdates: state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n ),\n }));\n }\n );\n }, []);\n }\n\n function useThreadFromCache(threadId: string): ThreadData<BaseMetadata> {\n const selector = useCallback(\n (state: CacheState<BaseMetadata>) => {\n const thread = state.threads[threadId];\n\n if (thread === undefined) {\n throw new Error(\n `Internal error: thread with id \"${threadId}\" not found in cache`\n );\n }\n\n return thread;\n },\n [threadId]\n );\n\n return useSyncExternalStoreWithSelector(\n store.subscribe,\n store.get,\n store.get,\n selector\n );\n }\n\n const currentUserIdStore = client[kInternal]\n .currentUserIdStore as unknown as Store<string | null>;\n\n function useCurrentUserId() {\n return useSyncExternalStore(\n currentUserIdStore.subscribe,\n currentUserIdStore.get,\n currentUserIdStore.get\n );\n }\n\n const bundle: LiveblocksContextBundle<TUserMeta> = {\n LiveblocksProvider,\n\n useInboxNotifications,\n useUnreadInboxNotificationsCount,\n\n useMarkInboxNotificationAsRead,\n useMarkAllInboxNotificationsAsRead,\n\n ...shared,\n\n suspense: {\n LiveblocksProvider,\n\n useInboxNotifications: useInboxNotificationsSuspense,\n useUnreadInboxNotificationsCount:\n useUnreadInboxNotificationsCountSuspense,\n\n useMarkInboxNotificationAsRead,\n useMarkAllInboxNotificationsAsRead,\n\n ...shared.suspense,\n },\n\n [kInternal]: {\n useThreadFromCache,\n useCurrentUserId,\n },\n };\n\n return Object.defineProperty(bundle, kInternal, {\n enumerable: false,\n });\n}\n","import type {\n BaseMetadata,\n CacheState,\n InboxNotificationData,\n} from \"@liveblocks/core\";\nimport { applyOptimisticUpdates } from \"@liveblocks/core\";\n\nexport function selectedInboxNotifications<\n TThreadMetadata extends BaseMetadata,\n>(state: CacheState<TThreadMetadata>): InboxNotificationData[] {\n const result = applyOptimisticUpdates(state);\n\n return Object.values(result.inboxNotifications).sort(\n // Sort so that the most recent notifications are first\n (a, b) => b.notifiedAt.getTime() - a.notifiedAt.getTime()\n );\n}\n","const MAX_ERROR_RETRY_COUNT = 5;\n\nconst ERROR_RETRY_INTERVAL = 5000; // 5 seconds\n\n/**\n * Retries an action using the exponential backoff algorithm\n * @param action The action to retry\n * @param retryCount The number of times the action has been retried\n */\nexport function retryError(action: () => void, retryCount: number) {\n if (retryCount >= MAX_ERROR_RETRY_COUNT) return;\n\n const timeout = Math.pow(2, retryCount) * ERROR_RETRY_INTERVAL;\n\n setTimeout(() => {\n void action();\n }, timeout);\n}\n","import { type BaseUserMeta, type Client, kInternal } from \"@liveblocks/core\";\nimport { useCallback, useContext, useEffect } from \"react\";\nimport { useSyncExternalStore } from \"use-sync-external-store/shim/index.js\";\n\nimport { ContextBundle as LiveblocksContextBundle } from \"./liveblocks\";\nimport { ContextBundle as RoomContextBundle } from \"./room\";\nimport type {\n RoomInfoState,\n RoomInfoStateSuccess,\n SharedContextBundle,\n UserState,\n UserStateSuccess,\n} from \"./types\";\n\n/**\n * @private\n *\n * This is an internal API, use `createLiveblocksContext` or `createRoomContext` instead.\n */\nexport function useSharedContextBundle() {\n const roomContextBundle = useContext(RoomContextBundle);\n const liveblocksContextBundle = useContext(LiveblocksContextBundle);\n\n if (roomContextBundle !== null) {\n return roomContextBundle;\n } else if (liveblocksContextBundle !== null) {\n return liveblocksContextBundle;\n } else {\n throw new Error(\n \"LiveblocksProvider or RoomProvider are missing from the React tree.\"\n );\n }\n}\n\nconst missingUserError = new Error(\n \"resolveUsers didn't return anything for this user ID.\"\n);\nconst missingRoomInfoError = new Error(\n \"resolveRoomsInfo didn't return anything for this room ID.\"\n);\n\nexport function createSharedContext<\n TUserMeta extends BaseUserMeta = BaseUserMeta,\n>(client: Client): SharedContextBundle<TUserMeta> {\n const usersStore = client[kInternal].usersStore;\n const roomsInfoStore = client[kInternal].roomsInfoStore;\n\n function useUser(userId: string): UserState<TUserMeta[\"info\"]> {\n const getUserState = useCallback(\n () => usersStore.getState(userId),\n [userId]\n );\n\n useEffect(() => {\n void usersStore.get(userId);\n }, [userId]);\n\n const state = useSyncExternalStore(\n usersStore.subscribe,\n getUserState,\n getUserState\n );\n\n return state\n ? ({\n isLoading: state.isLoading,\n user: state.data,\n // Return an error if `undefined` was returned by `resolveUsers` for this user ID\n error:\n !state.isLoading && !state.data && !state.error\n ? missingUserError\n : state.error,\n } as UserState<TUserMeta[\"info\"]>)\n : { isLoading: true };\n }\n\n function useUserSuspense(userId: string) {\n const getUserState = useCallback(\n () => usersStore.getState(userId),\n [userId]\n );\n const userState = getUserState();\n\n if (!userState || userState.isLoading) {\n throw usersStore.get(userId);\n }\n\n if (userState.error) {\n throw userState.error;\n }\n\n // Throw an error if `undefined` was returned by `resolveUsers` for this user ID\n if (!userState.data) {\n throw missingUserError;\n }\n\n const state = useSyncExternalStore(\n usersStore.subscribe,\n getUserState,\n getUserState\n );\n\n return {\n isLoading: false,\n user: state?.data,\n error: state?.error,\n } as UserStateSuccess<TUserMeta[\"info\"]>;\n }\n\n function useRoomInfo(roomId: string): RoomInfoState {\n const getRoomInfoState = useCallback(\n () => roomsInfoStore.getState(roomId),\n [roomId]\n );\n\n useEffect(() => {\n void roomsInfoStore.get(roomId);\n }, [roomId]);\n\n const state = useSyncExternalStore(\n roomsInfoStore.subscribe,\n getRoomInfoState,\n getRoomInfoState\n );\n\n return state\n ? ({\n isLoading: state.isLoading,\n info: state.data,\n // Return an error if `undefined` was returned by `resolveRoomsInfo` for this room ID\n error:\n !state.isLoading && !state.data && !state.error\n ? missingRoomInfoError\n : state.error,\n } as RoomInfoState)\n : { isLoading: true };\n }\n\n function useRoomInfoSuspense(roomId: string) {\n const getRoomInfoState = useCallback(\n () => roomsInfoStore.getState(roomId),\n [roomId]\n );\n const roomInfoState = getRoomInfoState();\n\n if (!roomInfoState || roomInfoState.isLoading) {\n throw roomsInfoStore.get(roomId);\n }\n\n if (roomInfoState.error) {\n throw roomInfoState.error;\n }\n\n // Throw an error if `undefined` was returned by `resolveRoomsInfo` for this room ID\n if (!roomInfoState.data) {\n throw missingRoomInfoError;\n }\n\n const state = useSyncExternalStore(\n roomsInfoStore.subscribe,\n getRoomInfoState,\n getRoomInfoState\n );\n\n return {\n isLoading: false,\n info: state?.data,\n error: state?.error,\n } as RoomInfoStateSuccess;\n }\n\n const bundle: SharedContextBundle<TUserMeta> = {\n useUser,\n useRoomInfo,\n\n suspense: {\n useUser: useUserSuspense,\n useRoomInfo: useRoomInfoSuspense,\n },\n };\n\n return bundle;\n}\n","import type {\n BaseUserMeta,\n BroadcastOptions,\n Client,\n History,\n Json,\n JsonObject,\n LiveObject,\n LostConnectionEvent,\n LsonObject,\n OthersEvent,\n Room,\n Status,\n User,\n} from \"@liveblocks/client\";\nimport { shallow } from \"@liveblocks/client\";\nimport type {\n BaseMetadata,\n CacheState,\n CacheStore,\n CommentData,\n CommentsEventServerMsg,\n EnterOptions,\n LiveblocksError,\n OptionalPromise,\n ResolveMentionSuggestionsArgs,\n ResolveUsersArgs,\n RoomEventMessage,\n RoomNotificationSettings,\n ThreadData,\n ToImmutable,\n} from \"@liveblocks/core\";\nimport {\n addReaction,\n CommentsApiError,\n console,\n deleteComment,\n deprecateIf,\n errorIf,\n isLiveNode,\n kInternal,\n makeEventSource,\n makePoller,\n NotificationsApiError,\n removeReaction,\n ServerMsgCode,\n stringify,\n upsertComment,\n} from \"@liveblocks/core\";\nimport { nanoid } from \"nanoid\";\nimport * as React from \"react\";\nimport { useSyncExternalStoreWithSelector } from \"use-sync-external-store/shim/with-selector.js\";\n\nimport {\n AddReactionError,\n type CommentsError,\n CreateCommentError,\n CreateThreadError,\n DeleteCommentError,\n EditCommentError,\n EditThreadMetadataError,\n MarkInboxNotificationAsReadError,\n RemoveReactionError,\n UpdateNotificationSettingsError,\n} from \"./comments/errors\";\nimport { createCommentId, createThreadId } from \"./comments/lib/createIds\";\nimport { selectNotificationSettings } from \"./comments/lib/select-notification-settings\";\nimport { selectedInboxNotifications } from \"./comments/lib/selected-inbox-notifications\";\nimport { selectedThreads } from \"./comments/lib/selected-threads\";\nimport { retryError } from \"./lib/retry-error\";\nimport { useInitial } from \"./lib/use-initial\";\nimport { useLatest } from \"./lib/use-latest\";\nimport { useRerender } from \"./lib/use-rerender\";\nimport { createSharedContext } from \"./shared\";\nimport type {\n CommentReactionOptions,\n CreateCommentOptions,\n CreateThreadOptions,\n DeleteCommentOptions,\n EditCommentOptions,\n EditThreadMetadataOptions,\n MutationContext,\n OmitFirstArg,\n RoomContextBundle,\n RoomNotificationSettingsState,\n RoomNotificationSettingsStateSuccess,\n RoomProviderProps,\n ThreadsState,\n ThreadsStateResolved,\n ThreadsStateSuccess,\n ThreadSubscription,\n UseThreadsOptions,\n} from \"./types\";\n\nconst noop = () => {};\nconst identity: <T>(x: T) => T = (x) => x;\n\nconst missing_unstable_batchedUpdates = (\n reactVersion: number,\n roomId: string\n) =>\n `We noticed you’re using React ${reactVersion}. Please pass unstable_batchedUpdates at the RoomProvider level until you’re ready to upgrade to React 18:\n\n import { unstable_batchedUpdates } from \"react-dom\"; // or \"react-native\"\n\n <RoomProvider id=${JSON.stringify(\n roomId\n )} ... unstable_batchedUpdates={unstable_batchedUpdates}>\n ...\n </RoomProvider>\n\nWhy? Please see https://liveblocks.io/docs/platform/troubleshooting#stale-props-zombie-child for more information`;\n\nconst superfluous_unstable_batchedUpdates =\n \"You don’t need to pass unstable_batchedUpdates to RoomProvider anymore, since you’re on React 18+ already.\";\n\nfunction useSyncExternalStore<Snapshot>(\n s: (onStoreChange: () => void) => () => void,\n gs: () => Snapshot,\n gss: undefined | null | (() => Snapshot)\n): Snapshot {\n return useSyncExternalStoreWithSelector(s, gs, gss, identity);\n}\n\nconst STABLE_EMPTY_LIST = Object.freeze([]);\n\nexport const POLLING_INTERVAL = 5 * 60 * 1000; // 5 minutes\n\nconst MENTION_SUGGESTIONS_DEBOUNCE = 500;\n\n// Don't try to inline this. This function is intended to be a stable\n// reference, to avoid a React.useCallback() wrapper.\nfunction alwaysEmptyList() {\n return STABLE_EMPTY_LIST;\n}\n\n// Don't try to inline this. This function is intended to be a stable\n// reference, to avoid a React.useCallback() wrapper.\nfunction alwaysNull() {\n return null;\n}\n\nfunction makeMutationContext<\n TPresence extends JsonObject,\n TStorage extends LsonObject,\n TUserMeta extends BaseUserMeta,\n TRoomEvent extends Json,\n>(\n room: Room<TPresence, TStorage, TUserMeta, TRoomEvent>\n): MutationContext<TPresence, TStorage, TUserMeta> {\n const errmsg =\n \"This mutation cannot be used until connected to the Liveblocks room\";\n\n return {\n get storage() {\n const mutableRoot = room.getStorageSnapshot();\n if (mutableRoot === null) {\n throw new Error(errmsg);\n }\n return mutableRoot;\n },\n\n get self() {\n const self = room.getSelf();\n if (self === null) {\n throw new Error(errmsg);\n }\n return self;\n },\n\n get others() {\n const others = room.getOthers();\n if (room.getSelf() === null) {\n throw new Error(errmsg);\n }\n return others;\n },\n\n setMyPresence: room.updatePresence,\n };\n}\n\nexport const ContextBundle = React.createContext<RoomContextBundle<\n JsonObject,\n LsonObject,\n BaseUserMeta,\n never,\n BaseMetadata\n> | null>(null);\n\n/**\n * @private\n *\n * This is an internal API, use `createRoomContext` instead.\n */\nexport function useRoomContextBundle() {\n const bundle = React.useContext(ContextBundle);\n if (bundle === null) {\n throw new Error(\"RoomProvider is missing from the React tree.\");\n }\n return bundle;\n}\n\ntype Options<TUserMeta extends BaseUserMeta> = {\n /**\n * @deprecated Define 'resolveUsers' in 'createClient' from '@liveblocks/client' instead.\n * Please refer to our Upgrade Guide to learn more, see https://liveblocks.io/docs/platform/upgrading/1.10.\n *\n * A function that returns user info from user IDs.\n */\n resolveUsers?: (\n args: ResolveUsersArgs\n ) => OptionalPromise<(TUserMeta[\"info\"] | undefined)[] | undefined>;\n\n /**\n * @deprecated Define 'resolveMentionSuggestions' in 'createClient' from '@liveblocks/client' instead.\n * Please refer to our Upgrade Guide to learn more, see https://liveblocks.io/docs/platform/upgrading/1.10.\n *\n * A function that returns a list of user IDs matching a string.\n */\n resolveMentionSuggestions?: (\n args: ResolveMentionSuggestionsArgs\n ) => OptionalPromise<string[]>;\n};\n\nexport function createRoomContext<\n TPresence extends JsonObject,\n TStorage extends LsonObject = LsonObject,\n TUserMeta extends BaseUserMeta = BaseUserMeta,\n TRoomEvent extends Json = never,\n TThreadMetadata extends BaseMetadata = never,\n>(\n client: Client,\n options?: Options<TUserMeta>\n): RoomContextBundle<\n TPresence,\n TStorage,\n TUserMeta,\n TRoomEvent,\n TThreadMetadata\n> {\n type TRoom = Room<TPresence, TStorage, TUserMeta, TRoomEvent>;\n type TRoomLeavePair = { room: TRoom; leave: () => void };\n\n // Deprecated option\n if (options?.resolveUsers) {\n throw new Error(\n \"The 'resolveUsers' option has moved to 'createClient' from '@liveblocks/client'. Please refer to our Upgrade Guide to learn more, see https://liveblocks.io/docs/platform/upgrading/1.10.\"\n );\n }\n\n // Deprecated option\n if (options?.resolveMentionSuggestions) {\n throw new Error(\n \"The 'resolveMentionSuggestions' option has moved to 'createClient' from '@liveblocks/client'. Please refer to our Upgrade Guide to learn more, see https://liveblocks.io/docs/platform/upgrading/1.10.\"\n );\n }\n\n const RoomContext = React.createContext<TRoom | null>(null);\n\n const commentsErrorEventSource =\n makeEventSource<CommentsError<TThreadMetadata>>();\n\n const shared = createSharedContext<TUserMeta>(client);\n\n /**\n * RATIONALE:\n * At the \"Outer\" RoomProvider level, we keep a cache and produce\n * a stableEnterRoom function, which we pass down to the real \"Inner\"\n * RoomProvider level.\n *\n * The purpose is to ensure that if `stableEnterRoom(\"my-room\")` is called\n * multiple times for the same room ID, it will always return the exact same\n * (cached) value, so that in total only a single \"leave\" function gets\n * produced and registered in the client.\n *\n * If we didn't use this cache, then in React StrictMode\n * stableEnterRoom(\"my-room\") might get called multiple (at least 4) times,\n * causing more leave functions to be produced in the client, some of which\n * we cannot get a hold on (because StrictMode would discard those results by\n * design). This would make it appear to the Client that the Room is still in\n * use by some party that hasn't called `leave()` on it yet, thus causing the\n * Room to not be freed and destroyed when the component unmounts later.\n */\n function RoomProviderOuter(props: RoomProviderProps<TPresence, TStorage>) {\n const [cache] = React.useState<Map<string, TRoomLeavePair>>(\n () => new Map()\n );\n\n // Produce a version of client.enterRoom() that when called for the same\n // room ID multiple times, will not keep producing multiple leave\n // functions, but instead return the cached one.\n const stableEnterRoom = React.useCallback(\n (\n roomId: string,\n options: EnterOptions<TPresence, TStorage>\n ): TRoomLeavePair => {\n const cached = cache.get(roomId);\n if (cached) return cached;\n\n const rv = client.enterRoom<TPresence, TStorage, TUserMeta, TRoomEvent>(\n roomId,\n options\n );\n\n // Wrap the leave function to also delete the cached value\n const origLeave = rv.leave;\n rv.leave = () => {\n origLeave();\n cache.delete(roomId);\n };\n\n cache.set(roomId, rv);\n return rv;\n },\n [cache]\n );\n\n return <RoomProviderInner {...props} stableEnterRoom={stableEnterRoom} />;\n }\n\n function RoomProviderInner(\n props: RoomProviderProps<TPresence, TStorage> & {\n stableEnterRoom: (\n roomId: string,\n options: EnterOptions<TPresence, TStorage>\n ) => TRoomLeavePair;\n }\n ) {\n const { id: roomId, stableEnterRoom } = props;\n\n if (process.env.NODE_ENV !== \"production\") {\n if (!roomId) {\n throw new Error(\n \"RoomProvider id property is required. For more information: https://liveblocks.io/docs/errors/liveblocks-react/RoomProvider-id-property-is-required\"\n );\n }\n\n if (typeof roomId !== \"string\") {\n throw new Error(\"RoomProvider id property should be a string.\");\n }\n\n const majorReactVersion = parseInt(React.version) || 1;\n const oldReactVersion = majorReactVersion < 18;\n errorIf(\n oldReactVersion && props.unstable_batchedUpdates === undefined,\n missing_unstable_batchedUpdates(majorReactVersion, roomId)\n );\n deprecateIf(\n !oldReactVersion && props.unstable_batchedUpdates !== undefined,\n superfluous_unstable_batchedUpdates\n );\n }\n\n // Note: We'll hold on to the initial value given here, and ignore any\n // changes to this argument in subsequent renders\n const frozenProps = useInitial({\n initialPresence: props.initialPresence,\n initialStorage: props.initialStorage,\n unstable_batchedUpdates: props.unstable_batchedUpdates,\n autoConnect:\n props.autoConnect ??\n props.shouldInitiallyConnect ??\n typeof window !== \"undefined\",\n });\n\n const [{ room }, setRoomLeavePair] = React.useState(() =>\n stableEnterRoom(roomId, {\n ...frozenProps,\n autoConnect: false, // Deliberately using false here on the first render, see below\n })\n );\n\n React.useEffect(() => {\n async function handleCommentEvent(message: CommentsEventServerMsg) {\n // TODO: Error handling\n const info = await room[kInternal].comments.getThread({\n threadId: message.threadId,\n });\n\n // If no thread info was returned (i.e., 404), we remove the thread and relevant inbox notifications from local cache.\n if (!info) {\n store.deleteThread(message.threadId);\n return;\n }\n const { thread, inboxNotification } = info;\n\n const existingThread = store.get().threads[message.threadId];\n\n switch (message.type) {\n case ServerMsgCode.COMMENT_EDITED:\n case ServerMsgCode.THREAD_METADATA_UPDATED:\n case ServerMsgCode.COMMENT_REACTION_ADDED:\n case ServerMsgCode.COMMENT_REACTION_REMOVED:\n case ServerMsgCode.COMMENT_DELETED:\n // If the thread doesn't exist in the local cache, we do not update it with the server data as an optimistic update could have deleted the thread locally.\n if (!existingThread) break;\n\n store.updateThreadAndNotification(thread, inboxNotification);\n break;\n case ServerMsgCode.COMMENT_CREATED:\n store.updateThreadAndNotification(thread, inboxNotification);\n break;\n default:\n break;\n }\n }\n\n return room.events.comments.subscribe(\n (message) => void handleCommentEvent(message)\n );\n }, [room]);\n\n React.useEffect(() => {\n // Retrieve threads that have been updated/deleted since the last time the room requested threads updates\n void getThreadsUpdates(room.id);\n }, [room.id]);\n\n /**\n * Subscribe to the 'online' event to fetch threads/notifications updates when the browser goes back online.\n */\n React.useEffect(() => {\n function handleIsOnline() {\n void getThreadsUpdates(room.id);\n }\n\n window.addEventListener(\"online\", handleIsOnline);\n return () => {\n window.removeEventListener(\"online\", handleIsOnline);\n };\n }, [room.id]);\n\n React.useEffect(() => {\n const pair = stableEnterRoom(roomId, frozenProps);\n\n setRoomLeavePair(pair);\n const { room, leave } = pair;\n\n // In React, it's important to start connecting to the room as an effect,\n // rather than doing this during the initial render. This means that\n // during the initial render (both on the server-side, and on the first\n // hydration on the client-side), the value of the `useStatus()` hook\n // will correctly be \"initial\", and transition to \"connecting\" as an\n // effect.\n if (frozenProps.autoConnect) {\n room.connect();\n }\n\n return () => {\n leave();\n };\n }, [roomId, frozenProps, stableEnterRoom]);\n\n return (\n <RoomContext.Provider value={room}>\n <ContextBundle.Provider\n value={\n bundle as unknown as RoomContextBundle<\n JsonObject,\n LsonObject,\n BaseUserMeta,\n never,\n BaseMetadata\n >\n }\n >\n {props.children}\n </ContextBundle.Provider>\n </RoomContext.Provider>\n );\n }\n\n function connectionIdSelector(\n others: readonly User<TPresence, TUserMeta>[]\n ): number[] {\n return others.map((user) => user.connectionId);\n }\n\n function useRoom(): TRoom {\n const room = React.useContext(RoomContext);\n if (room === null) {\n throw new Error(\"RoomProvider is missing from the React tree.\");\n }\n return room;\n }\n\n function useStatus(): Status {\n const room = useRoom();\n const subscribe = room.events.status.subscribe;\n const getSnapshot = room.getStatus;\n const getServerSnapshot = room.getStatus;\n return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);\n }\n\n function useMyPresence(): [\n TPresence,\n (patch: Partial<TPresence>, options?: { addToHistory: boolean }) => void,\n ] {\n const room = useRoom();\n const subscribe = room.events.myPresence.subscribe;\n const getSnapshot = room.getPresence;\n const presence = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n const setPresence = room.updatePresence;\n return [presence, setPresence];\n }\n\n function useUpdateMyPresence(): (\n patch: Partial<TPresence>,\n options?: { addToHistory: boolean }\n ) => void {\n return useRoom().updatePresence;\n }\n\n function useOthers(): readonly User<TPresence, TUserMeta>[];\n function useOthers<T>(\n selector: (others: readonly User<TPresence, TUserMeta>[]) => T,\n isEqual?: (prev: T, curr: T) => boolean\n ): T;\n function useOthers<T>(\n selector?: (others: readonly User<TPresence, TUserMeta>[]) => T,\n isEqual?: (prev: T, curr: T) => boolean\n ): T | readonly User<TPresence, TUserMeta>[] {\n const room = useRoom();\n const subscribe = room.events.others.subscribe;\n const getSnapshot = room.getOthers;\n const getServerSnapshot = alwaysEmptyList;\n return useSyncExternalStoreWithSelector(\n subscribe,\n getSnapshot,\n getServerSnapshot,\n selector ??\n (identity as (others: readonly User<TPresence, TUserMeta>[]) => T),\n isEqual\n );\n }\n\n function useOthersConnectionIds(): readonly number[] {\n return useOthers(connectionIdSelector, shallow);\n }\n\n function useOthersMapped<T>(\n itemSelector: (other: User<TPresence, TUserMeta>) => T,\n itemIsEqual?: (prev: T, curr: T) => boolean\n ): ReadonlyArray<readonly [connectionId: number, data: T]> {\n const wrappedSelector = React.useCallback(\n (others: readonly User<TPresence, TUserMeta>[]) =>\n others.map(\n (other) => [other.connectionId, itemSelector(other)] as const\n ),\n [itemSelector]\n );\n\n const wrappedIsEqual = React.useCallback(\n (\n a: ReadonlyArray<readonly [connectionId: number, data: T]>,\n b: ReadonlyArray<readonly [connectionId: number, data: T]>\n ): boolean => {\n const eq = itemIsEqual ?? Object.is;\n return (\n a.length === b.length &&\n a.every((atuple, index) => {\n // We know btuple always exist because we checked the array length on the previous line\n const btuple = b[index];\n return atuple[0] === btuple[0] && eq(atuple[1], btuple[1]);\n })\n );\n },\n [itemIsEqual]\n );\n\n return useOthers(wrappedSelector, wrappedIsEqual);\n }\n\n const NOT_FOUND = Symbol();\n\n type NotFound = typeof NOT_FOUND;\n\n function useOther<T>(\n connectionId: number,\n selector: (other: User<TPresence, TUserMeta>) => T,\n isEqual?: (prev: T, curr: T) => boolean\n ): T {\n const wrappedSelector = React.useCallback(\n (others: readonly User<TPresence, TUserMeta>[]) => {\n // TODO: Make this O(1) instead of O(n)?\n const other = others.find(\n (other) => other.connectionId === connectionId\n );\n return other !== undefined ? selector(other) : NOT_FOUND;\n },\n [connectionId, selector]\n );\n\n const wrappedIsEqual = React.useCallback(\n (prev: T | NotFound, curr: T | NotFound): boolean => {\n if (prev === NOT_FOUND || curr === NOT_FOUND) {\n return prev === curr;\n }\n\n const eq = isEqual ?? Object.is;\n return eq(prev, curr);\n },\n [isEqual]\n );\n\n const other = useOthers(wrappedSelector, wrappedIsEqual);\n if (other === NOT_FOUND) {\n throw new Error(\n `No such other user with connection id ${connectionId} exists`\n );\n }\n\n return other;\n }\n\n function useBroadcastEvent(): (\n event: TRoomEvent,\n options?: BroadcastOptions\n ) => void {\n const room = useRoom();\n\n return React.useCallback(\n (\n event: TRoomEvent,\n options: BroadcastOptions = { shouldQueueEventIfNotReady: false }\n ) => {\n room.broadcastEvent(event, options);\n },\n [room]\n );\n }\n\n function useOthersListener(\n callback: (event: OthersEvent<TPresence, TUserMeta>) => void\n ) {\n const room = useRoom();\n const savedCallback = useLatest(callback);\n\n React.useEffect(\n () =>\n room.events.others.subscribe((event) => savedCallback.current(event)),\n [room, savedCallback]\n );\n }\n\n function useLostConnectionListener(\n callback: (event: LostConnectionEvent) => void\n ): void {\n const room = useRoom();\n const savedCallback = useLatest(callback);\n\n React.useEffect(\n () =>\n room.events.lostConnection.subscribe((event) =>\n savedCallback.current(event)\n ),\n [room, savedCallback]\n );\n }\n\n function useErrorListener(callback: (err: LiveblocksError) => void): void {\n const room = useRoom();\n const savedCallback = useLatest(callback);\n\n React.useEffect(\n () => room.events.error.subscribe((e) => savedCallback.current(e)),\n [room, savedCallback]\n );\n }\n\n function useEventListener(\n callback: (data: RoomEventMessage<TPresence, TUserMeta, TRoomEvent>) => void\n ): void {\n const room = useRoom();\n const savedCallback = useLatest(callback);\n\n React.useEffect(() => {\n const listener = (\n eventData: RoomEventMessage<TPresence, TUserMeta, TRoomEvent>\n ) => {\n savedCallback.current(eventData);\n };\n\n return room.events.customEvent.subscribe(listener);\n }, [room, savedCallback]);\n }\n\n function useSelf(): User<TPresence, TUserMeta> | null;\n function useSelf<T>(\n selector: (me: User<TPresence, TUserMeta>) => T,\n isEqual?: (prev: T | null, curr: T | null) => boolean\n ): T | null;\n function useSelf<T>(\n maybeSelector?: (me: User<TPresence, TUserMeta>) => T,\n isEqual?: (prev: T | null, curr: T | null) => boolean\n ): T | User<TPresence, TUserMeta> | null {\n type Snapshot = User<TPresence, TUserMeta> | null;\n type Selection = T | null;\n\n const room = useRoom();\n const subscribe = room.events.self.subscribe;\n const getSnapshot: () => Snapshot = room.getSelf;\n\n const selector =\n maybeSelector ?? (identity as (me: User<TPresence, TUserMeta>) => T);\n const wrappedSelector = React.useCallback(\n (me: Snapshot): Selection => (me !== null ? selector(me) : null),\n [selector]\n );\n\n const getServerSnapshot = alwaysNull;\n\n return useSyncExternalStoreWithSelector(\n subscribe,\n getSnapshot,\n getServerSnapshot,\n wrappedSelector,\n isEqual\n );\n }\n\n function useMutableStorageRoot(): LiveObject<TStorage> | null {\n const room = useRoom();\n const subscribe = room.events.storageDidLoad.subscribeOnce;\n const getSnapshot = room.getStorageSnapshot;\n const getServerSnapshot = alwaysNull;\n return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);\n }\n\n // NOTE: This API exists for backward compatible reasons\n function useStorageRoot(): [root: LiveObject<TStorage> | null] {\n return [useMutableStorageRoot()];\n }\n\n function useHistory(): History {\n return useRoom().history;\n }\n\n function useUndo(): () => void {\n return useHistory().undo;\n }\n\n function useRedo(): () => void {\n return useHistory().redo;\n }\n\n function useCanUndo(): boolean {\n const room = useRoom();\n const subscribe = room.events.history.subscribe;\n const canUndo = room.history.canUndo;\n return useSyncExternalStore(subscribe, canUndo, canUndo);\n }\n\n function useCanRedo(): boolean {\n const room = useRoom();\n const subscribe = room.events.history.subscribe;\n const canRedo = room.history.canRedo;\n return useSyncExternalStore(subscribe, canRedo, canRedo);\n }\n\n function useBatch<T>(): (callback: () => T) => T {\n return useRoom().batch;\n }\n\n function useLegacyKey<TKey extends Extract<keyof TStorage, string>>(\n key: TKey\n ): TStorage[TKey] | null {\n const room = useRoom();\n const rootOrNull = useMutableStorageRoot();\n const rerender = useRerender();\n\n React.useEffect(() => {\n if (rootOrNull === null) {\n return;\n }\n const root = rootOrNull;\n\n let unsubCurr: (() => void) | undefined;\n let curr = root.get(key);\n\n function subscribeToCurr() {\n unsubCurr = isLiveNode(curr)\n ? room.subscribe(curr, rerender)\n : undefined;\n }\n\n function onRootChange() {\n const newValue = root.get(key);\n if (newValue !== curr) {\n unsubCurr?.();\n curr = newValue;\n subscribeToCurr();\n rerender();\n }\n }\n\n subscribeToCurr();\n rerender();\n\n const unsubscribeRoot = room.subscribe(root, onRootChange);\n return () => {\n unsubscribeRoot();\n unsubCurr?.();\n };\n }, [rootOrNull, room, key, rerender]);\n\n if (rootOrNull === null) {\n return null;\n } else {\n return rootOrNull.get(key);\n }\n }\n\n function useStorage<T>(\n selector: (root: ToImmutable<TStorage>) => T,\n isEqual?: (prev: T | null, curr: T | null) => boolean\n ): T | null {\n type Snapshot = ToImmutable<TStorage> | null;\n type Selection = T | null;\n\n const room = useRoom();\n const rootOrNull = useMutableStorageRoot();\n\n const wrappedSelector = React.useCallback(\n (rootOrNull: Snapshot): Selection =>\n rootOrNull !== null ? selector(rootOrNull) : null,\n [selector]\n );\n\n const subscribe = React.useCallback(\n (onStoreChange: () => void) =>\n rootOrNull !== null\n ? room.subscribe(rootOrNull, onStoreChange, { isDeep: true })\n : noop,\n [room, rootOrNull]\n );\n\n const getSnapshot = React.useCallback((): Snapshot => {\n if (rootOrNull === null) {\n return null;\n } else {\n const root = rootOrNull;\n const imm = root.toImmutable();\n return imm;\n }\n }, [rootOrNull]);\n\n const getServerSnapshot = alwaysNull;\n\n return useSyncExternalStoreWithSelector(\n subscribe,\n getSnapshot,\n getServerSnapshot,\n wrappedSelector,\n isEqual\n );\n }\n\n function ensureNotServerSide(): void {\n // Error early if suspense is used in a server-side context\n if (typeof window === \"undefined\") {\n throw new Error(\n \"You cannot use the Suspense version of this hook on the server side. Make sure to only call them on the client side.\\nFor tips, see https://liveblocks.io/docs/api-reference/liveblocks-react#suspense-avoid-ssr\"\n );\n }\n }\n\n function useSuspendUntilStorageLoaded(): void {\n const room = useRoom();\n if (room.getStorageSnapshot() !== null) {\n return;\n }\n\n ensureNotServerSide();\n\n // Throw a _promise_. Suspense will suspend the component tree until this\n // promise resolves (aka until storage has loaded). After that, it will\n // render this component tree again.\n throw new Promise<void>((res) => {\n room.events.storageDidLoad.subscribeOnce(() => res());\n });\n }\n\n function useSuspendUntilPresenceLoaded(): void {\n const room = useRoom();\n if (room.getSelf() !== null) {\n return;\n }\n\n ensureNotServerSide();\n\n // Throw a _promise_. Suspense will suspend the component tree until either\n // until either a presence update event, or a connection status change has\n // happened. After that, it will render this component tree again and\n // re-evaluate the .getSelf() condition above, or re-suspend again until\n // such event happens.\n throw new Promise<void>((res) => {\n room.events.self.subscribeOnce(() => res());\n room.events.status.subscribeOnce(() => res());\n });\n }\n\n function useMutation<\n F extends (\n context: MutationContext<TPresence, TStorage, TUserMeta>,\n ...args: any[]\n ) => any,\n >(callback: F, deps: readonly unknown[]): OmitFirstArg<F> {\n const room = useRoom();\n return React.useMemo(\n () => {\n return ((...args) =>\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n room.batch(() =>\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n callback(\n makeMutationContext(room),\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n ...args\n )\n )) as OmitFirstArg<F>;\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [room, ...deps]\n );\n }\n\n function useStorageSuspense<T>(\n selector: (root: ToImmutable<TStorage>) => T,\n isEqual?: (prev: T, curr: T) => boolean\n ): T {\n useSuspendUntilStorageLoaded();\n return useStorage(\n selector,\n isEqual as (prev: T | null, curr: T | null) => boolean\n ) as T;\n }\n\n function useSelfSuspense(): User<TPresence, TUserMeta>;\n function useSelfSuspense<T>(\n selector: (me: User<TPresence, TUserMeta>) => T,\n isEqual?: (prev: T, curr: T) => boolean\n ): T;\n function useSelfSuspense<T>(\n selector?: (me: User<TPresence, TUserMeta>) => T,\n isEqual?: (prev: T, curr: T) => boolean\n ): T | User<TPresence, TUserMeta> {\n useSuspendUntilPresenceLoaded();\n return useSelf(\n selector as (me: User<TPresence, TUserMeta>) => T,\n isEqual as (prev: T | null, curr: T | null) => boolean\n ) as T | User<TPresence, TUserMeta>;\n }\n\n function useOthersSuspense<T>(\n selector?: (others: readonly User<TPresence, TUserMeta>[]) => T,\n isEqual?: (prev: T, curr: T) => boolean\n ): T | readonly User<TPresence, TUserMeta>[] {\n useSuspendUntilPresenceLoaded();\n return useOthers(\n selector as (others: readonly User<TPresence, TUserMeta>[]) => T,\n isEqual as (prev: T, curr: T) => boolean\n ) as T | readonly User<TPresence, TUserMeta>[];\n }\n\n function useOthersConnectionIdsSuspense(): readonly number[] {\n useSuspendUntilPresenceLoaded();\n return useOthersConnectionIds();\n }\n\n function useOthersMappedSuspense<T>(\n itemSelector: (other: User<TPresence, TUserMeta>) => T,\n itemIsEqual?: (prev: T, curr: T) => boolean\n ): ReadonlyArray<readonly [connectionId: number, data: T]> {\n useSuspendUntilPresenceLoaded();\n return useOthersMapped(itemSelector, itemIsEqual);\n }\n\n function useOtherSuspense<T>(\n connectionId: number,\n selector: (other: User<TPresence, TUserMeta>) => T,\n isEqual?: (prev: T, curr: T) => boolean\n ): T {\n useSuspendUntilPresenceLoaded();\n return useOther(connectionId, selector, isEqual);\n }\n\n function useLegacyKeySuspense<TKey extends Extract<keyof TStorage, string>>(\n key: TKey\n ): TStorage[TKey] {\n useSuspendUntilStorageLoaded();\n return useLegacyKey(key) as TStorage[TKey];\n }\n\n const store = client[kInternal]\n .cacheStore as unknown as CacheStore<TThreadMetadata>;\n\n function onMutationFailure(\n innerError: Error,\n optimisticUpdateId: string,\n createPublicError: (error: Error) => CommentsError<TThreadMetadata>\n ) {\n store.set((state) => ({\n ...state,\n optimisticUpdates: state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n ),\n }));\n\n if (innerError instanceof CommentsApiError) {\n const error = handleApiError(innerError);\n commentsErrorEventSource.notify(createPublicError(error));\n return;\n }\n\n if (innerError instanceof NotificationsApiError) {\n handleApiError(innerError);\n // TODO: Create public error and notify via notificationsErrorEventSource?\n return;\n }\n\n throw innerError;\n }\n\n const subscribersByQuery: Map<string, number> = new Map(); // A map of query keys to the number of subscribers for that query\n const requestsByQuery: Map<string, Promise<any>> = new Map(); // A map of query keys to the promise of the request for that query\n\n const poller = makePoller(refreshThreadsAndNotifications);\n\n async function refreshThreadsAndNotifications() {\n const requests: Promise<any>[] = [];\n\n client[kInternal].getRoomIds().map((roomId) => {\n const room = client.getRoom(roomId);\n if (room === null) return;\n\n // Retrieve threads that have been updated/deleted since the last requestedAt value\n requests.push(getThreadsUpdates(room.id));\n });\n\n await Promise.allSettled(requests);\n }\n\n function incrementQuerySubscribers(queryKey: string) {\n const subscribers = subscribersByQuery.get(queryKey) ?? 0;\n subscribersByQuery.set(queryKey, subscribers + 1);\n\n poller.start(POLLING_INTERVAL);\n }\n\n function decrementQuerySubscribers(queryKey: string) {\n const subscribers = subscribersByQuery.get(queryKey);\n\n if (subscribers === undefined || subscribers <= 0) {\n console.warn(\n `Internal unexpected behavior. Cannot decrease subscriber count for query \"${queryKey}\"`\n );\n return;\n }\n\n subscribersByQuery.set(queryKey, subscribers - 1);\n\n let totalSubscribers = 0;\n for (const subscribers of subscribersByQuery.values()) {\n totalSubscribers += subscribers;\n }\n\n if (totalSubscribers <= 0) {\n poller.stop();\n }\n }\n\n async function getThreadsAndInboxNotifications(\n room: Room<JsonObject, LsonObject, BaseUserMeta, Json>,\n queryKey: string,\n options: UseThreadsOptions<TThreadMetadata>,\n { retryCount }: { retryCount: number } = { retryCount: 0 }\n ) {\n const existingRequest = requestsByQuery.get(queryKey);\n\n // If a request was already made for the query, we do not make another request and return the existing promise of the request\n if (existingRequest !== undefined) return existingRequest;\n\n const request = room[kInternal].comments.getThreads(options);\n\n // Store the promise of the request for the query so that we do not make another request for the same query\n requestsByQuery.set(queryKey, request);\n\n store.setQueryState(queryKey, {\n isLoading: true,\n });\n\n try {\n const result = await request;\n\n store.updateThreadsAndNotifications(\n result.threads,\n result.inboxNotifications,\n result.deletedThreads,\n result.deletedInboxNotifications,\n queryKey\n );\n\n const lastRequestedAt = lastRequestedAtByRoom.get(room.id);\n\n /**\n * We set the `lastRequestedAt` value for the room to the timestamp returned by the current request if:\n * 1. The `lastRequestedAt` value for the room has not been set\n * OR\n * 2. The `lastRequestedAt` value for the room is older than the timestamp returned by the current request\n */\n if (\n lastRequestedAt === undefined ||\n lastRequestedAt > result.meta.requestedAt\n ) {\n lastRequestedAtByRoom.set(room.id, result.meta.requestedAt);\n }\n\n poller.start(POLLING_INTERVAL);\n } catch (err) {\n requestsByQuery.delete(queryKey);\n\n // Retry the action using the exponential backoff algorithm\n retryError(() => {\n void getThreadsAndInboxNotifications(room, queryKey, options, {\n retryCount: retryCount + 1,\n });\n }, retryCount);\n\n // Set the query state to the error state\n store.setQueryState(queryKey, {\n isLoading: false,\n error: err as Error,\n });\n\n return;\n }\n }\n\n const DEFAULT_DEDUPING_INTERVAL = 2000; // 2 seconds\n\n const lastRequestedAtByRoom = new Map<string, Date>(); // A map of room ids to the timestamp when the last request for threads updates was made\n const requestStatusByRoom = new Map<string, boolean>(); // A map of room ids to a boolean indicating whether a request to retrieve threads updates is in progress\n\n /**\n * Retrieve threads that have been updated/deleted since the last time the room requested threads updates and update the local cache with the new data\n * @param roomId The id of the room for which to retrieve threads updates\n */\n async function getThreadsUpdates(roomId: string) {\n const room = client.getRoom(roomId);\n if (room === null) return;\n\n const since = lastRequestedAtByRoom.get(room.id);\n if (since === undefined) return;\n\n const isFetchingThreadsUpdates = requestStatusByRoom.get(room.id) ?? false;\n // If another request to retrieve threads updates for the room is in progress, we do not start a new one\n if (isFetchingThreadsUpdates === true) return;\n\n try {\n // Set the isFetchingThreadsUpdates flag to true to prevent multiple requests to fetch threads updates for the room from being made at the same time\n requestStatusByRoom.set(room.id, true);\n const updates = await room[kInternal].comments.getThreads({ since });\n\n // Set the isFetchingThreadsUpdates flag to false after a certain interval to prevent multiple requests from being made at the same time\n setTimeout(() => {\n requestStatusByRoom.set(room.id, false);\n }, DEFAULT_DEDUPING_INTERVAL);\n\n store.updateThreadsAndNotifications(\n updates.threads,\n updates.inboxNotifications,\n updates.deletedThreads,\n updates.deletedInboxNotifications\n );\n\n // Update the `lastRequestedAt` value for the room to the timestamp returned by the current request\n lastRequestedAtByRoom.set(room.id, updates.meta.requestedAt);\n } catch (err) {\n requestStatusByRoom.set(room.id, false);\n // TODO: Implement error handling\n return;\n }\n }\n\n /**\n * Scroll to the comment with the ID in the hash of the URL based on whether\n * the query is loading and whether the hook should scroll to the comment on load.\n */\n function handleScrollToCommentOnLoad(\n isQueryLoading: boolean,\n shouldScrollOnLoad: boolean,\n state: ThreadsStateResolved<TThreadMetadata>\n ) {\n if (shouldScrollOnLoad === false) return;\n\n if (isQueryLoading === true) return;\n\n const isWindowDefined = typeof window !== \"undefined\";\n if (!isWindowDefined) return;\n\n const hash = window.location.hash;\n const commentId = hash.slice(1);\n\n // If the hash is not a comment ID, we do not scroll to it\n if (!commentId.startsWith(\"cm_\")) return;\n\n // If a comment with the ID does not exist in the DOM, we do not scroll to it\n const comment = document.getElementById(commentId);\n if (comment === null) return;\n\n const comments = state.threads.flatMap((thread) => thread.comments);\n const isCommentInThreads = comments.some(\n (comment) => comment.id === commentId\n );\n\n // If the comment is not in the threads for this hook, we do not scroll to it\n if (!isCommentInThreads) return;\n\n comment.scrollIntoView();\n }\n\n function useThreads(\n options: UseThreadsOptions<TThreadMetadata> = {\n query: { metadata: {} },\n }\n ): ThreadsState<TThreadMetadata> {\n const { scrollOnLoad = true } = options;\n const room = useRoom();\n const queryKey = React.useMemo(\n () => generateQueryKey(room.id, options.query),\n [room, options]\n );\n\n React.useEffect(() => {\n void getThreadsAndInboxNotifications(room, queryKey, options);\n incrementQuerySubscribers(queryKey);\n\n return () => decrementQuerySubscribers(queryKey);\n }, [room, queryKey]); // eslint-disable-line react-hooks/exhaustive-deps\n\n const selector = React.useCallback(\n (state: CacheState<TThreadMetadata>): ThreadsState<TThreadMetadata> => {\n const query = state.queries[queryKey];\n if (query === undefined || query.isLoading) {\n return {\n isLoading: true,\n };\n }\n\n return {\n threads: selectedThreads(room.id, state, options),\n isLoading: false,\n error: query.error,\n };\n },\n [room, queryKey] // eslint-disable-line react-hooks/exhaustive-deps\n );\n\n const state = useSyncExternalStoreWithSelector(\n store.subscribe,\n store.get,\n store.get,\n selector\n );\n\n React.useEffect(\n () => {\n if (state.isLoading === true) return;\n\n handleScrollToCommentOnLoad(state.isLoading, scrollOnLoad, state);\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps -- We only want to run this effect once\n [state.isLoading]\n );\n\n return state;\n }\n\n function useThreadsSuspense(\n options: UseThreadsOptions<TThreadMetadata> = {\n query: { metadata: {} },\n }\n ): ThreadsStateSuccess<TThreadMetadata> {\n const { scrollOnLoad = true } = options;\n\n const room = useRoom();\n const queryKey = React.useMemo(\n () => generateQueryKey(room.id, options.query),\n [room, options]\n );\n\n const query = store.get().queries[queryKey];\n\n if (query === undefined || query.isLoading) {\n throw getThreadsAndInboxNotifications(room, queryKey, options);\n }\n\n if (query.error) {\n throw query.error;\n }\n\n const selector = React.useCallback(\n (\n state: CacheState<TThreadMetadata>\n ): ThreadsStateSuccess<TThreadMetadata> => {\n return {\n threads: selectedThreads(room.id, state, options),\n isLoading: false,\n };\n },\n [room, queryKey] // eslint-disable-line react-hooks/exhaustive-deps\n );\n\n React.useEffect(() => {\n incrementQuerySubscribers(queryKey);\n\n return () => {\n decrementQuerySubscribers(queryKey);\n };\n }, [queryKey]);\n\n const state = useSyncExternalStoreWithSelector(\n store.subscribe,\n store.get,\n store.get,\n selector\n );\n\n React.useEffect(\n () => {\n handleScrollToCommentOnLoad(state.isLoading, scrollOnLoad, state);\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps -- We only want to run this effect once\n [state.isLoading]\n );\n\n return state;\n }\n\n function useCreateThread() {\n const room = useRoom();\n return React.useCallback(\n (\n options: CreateThreadOptions<TThreadMetadata>\n ): ThreadData<TThreadMetadata> => {\n const body = options.body;\n const metadata: TThreadMetadata =\n \"metadata\" in options ? options.metadata : ({} as TThreadMetadata);\n\n const threadId = createThreadId();\n const commentId = createCommentId();\n const createdAt = new Date();\n\n const newComment: CommentData = {\n id: commentId,\n threadId,\n roomId: room.id,\n createdAt,\n type: \"comment\",\n userId: getCurrentUserId(room),\n body,\n reactions: [],\n };\n const newThread: ThreadData<TThreadMetadata> = {\n id: threadId,\n type: \"thread\",\n createdAt,\n updatedAt: createdAt,\n roomId: room.id,\n metadata: metadata as ThreadData<TThreadMetadata>[\"metadata\"],\n comments: [newComment],\n };\n\n const optimisticUpdateId = nanoid();\n\n store.pushOptimisticUpdate({\n type: \"create-thread\",\n thread: newThread,\n id: optimisticUpdateId,\n });\n\n room[kInternal].comments\n .createThread({ threadId, commentId, body, metadata })\n .then(\n (thread) => {\n store.set((state) => ({\n ...state,\n threads: {\n ...state.threads,\n [threadId]: thread,\n },\n optimisticUpdates: state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n ),\n }));\n },\n (err: Error) =>\n onMutationFailure(\n err,\n optimisticUpdateId,\n (err) =>\n new CreateThreadError(err, {\n roomId: room.id,\n threadId,\n commentId,\n body,\n metadata,\n })\n )\n );\n\n return newThread;\n },\n [room]\n );\n }\n\n function useEditThreadMetadata() {\n const room = useRoom();\n return React.useCallback(\n (options: EditThreadMetadataOptions<TThreadMetadata>): void => {\n if (!(\"metadata\" in options)) {\n return;\n }\n\n const threadId = options.threadId;\n const metadata = options.metadata;\n const updatedAt = new Date();\n\n const optimisticUpdateId = nanoid();\n\n store.pushOptimisticUpdate({\n type: \"edit-thread-metadata\",\n metadata,\n id: optimisticUpdateId,\n threadId,\n updatedAt,\n });\n\n room[kInternal].comments\n .editThreadMetadata({ metadata, threadId })\n .then(\n (metadata) => {\n store.set((state) => {\n const existingThread = state.threads[threadId];\n const updatedOptimisticUpdates = state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n );\n\n // If the thread doesn't exist in the cache, we do not update the metadata\n if (existingThread === undefined) {\n return {\n ...state,\n optimisticUpdates: updatedOptimisticUpdates,\n };\n }\n\n // If the thread has been deleted, we do not update the metadata\n if (existingThread.deletedAt !== undefined) {\n return {\n ...state,\n optimisticUpdates: updatedOptimisticUpdates,\n };\n }\n\n if (\n existingThread.updatedAt &&\n existingThread.updatedAt > updatedAt\n ) {\n return {\n ...state,\n optimisticUpdates: updatedOptimisticUpdates,\n };\n }\n\n return {\n ...state,\n threads: {\n ...state.threads,\n [threadId]: {\n ...existingThread,\n metadata: metadata as [TThreadMetadata] extends [never]\n ? Record<string, never>\n : TThreadMetadata,\n },\n },\n optimisticUpdates: updatedOptimisticUpdates,\n };\n });\n },\n (err: Error) =>\n onMutationFailure(\n err,\n optimisticUpdateId,\n (error) =>\n new EditThreadMetadataError(error, {\n roomId: room.id,\n threadId,\n metadata,\n })\n )\n );\n },\n [room]\n );\n }\n\n function useAddReaction() {\n const room = useRoom();\n return React.useCallback(\n ({ threadId, commentId, emoji }: CommentReactionOptions): void => {\n const createdAt = new Date();\n const userId = getCurrentUserId(room);\n\n const optimisticUpdateId = nanoid();\n\n store.pushOptimisticUpdate({\n type: \"add-reaction\",\n threadId,\n commentId,\n reaction: {\n emoji,\n userId,\n createdAt,\n },\n id: optimisticUpdateId,\n });\n\n room[kInternal].comments\n .addReaction({ threadId, commentId, emoji })\n .then(\n (addedReaction) => {\n store.set((state): CacheState<TThreadMetadata> => {\n const existingThread = state.threads[threadId];\n const updatedOptimisticUpdates = state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n );\n\n // If the thread doesn't exist in the cache, we do not update the metadata\n if (existingThread === undefined) {\n return {\n ...state,\n optimisticUpdates: updatedOptimisticUpdates,\n };\n }\n\n return {\n ...state,\n threads: {\n ...state.threads,\n [threadId]: addReaction(\n existingThread,\n commentId,\n addedReaction\n ),\n },\n optimisticUpdates: updatedOptimisticUpdates,\n };\n });\n },\n (err: Error) =>\n onMutationFailure(\n err,\n optimisticUpdateId,\n (error) =>\n new AddReactionError(error, {\n roomId: room.id,\n threadId,\n commentId,\n emoji,\n })\n )\n );\n },\n [room]\n );\n }\n\n function useRemoveReaction() {\n const room = useRoom();\n return React.useCallback(\n ({ threadId, commentId, emoji }: CommentReactionOptions): void => {\n const userId = getCurrentUserId(room);\n\n const removedAt = new Date();\n const optimisticUpdateId = nanoid();\n\n store.pushOptimisticUpdate({\n type: \"remove-reaction\",\n threadId,\n commentId,\n emoji,\n userId,\n removedAt,\n id: optimisticUpdateId,\n });\n\n room[kInternal].comments\n .removeReaction({ threadId, commentId, emoji })\n .then(\n () => {\n store.set((state) => {\n const existingThread = state.threads[threadId];\n const updatedOptimisticUpdates = state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n );\n\n // If the thread doesn't exist in the cache, we do not update the metadata\n if (existingThread === undefined) {\n return {\n ...state,\n optimisticUpdates: updatedOptimisticUpdates,\n };\n }\n\n return {\n ...state,\n threads: {\n ...state.threads,\n [threadId]: removeReaction(\n existingThread,\n commentId,\n emoji,\n userId,\n removedAt\n ),\n },\n optimisticUpdates: updatedOptimisticUpdates,\n };\n });\n },\n (err: Error) =>\n onMutationFailure(\n err,\n optimisticUpdateId,\n (error) =>\n new RemoveReactionError(error, {\n roomId: room.id,\n threadId,\n commentId,\n emoji,\n })\n )\n );\n },\n [room]\n );\n }\n\n function useCreateComment(): (options: CreateCommentOptions) => CommentData {\n const room = useRoom();\n return React.useCallback(\n ({ threadId, body }: CreateCommentOptions): CommentData => {\n const commentId = createCommentId();\n const createdAt = new Date();\n\n const comment: CommentData = {\n id: commentId,\n threadId,\n roomId: room.id,\n type: \"comment\",\n createdAt,\n userId: getCurrentUserId(room),\n body,\n reactions: [],\n };\n\n const optimisticUpdateId = nanoid();\n\n store.pushOptimisticUpdate({\n type: \"create-comment\",\n comment,\n id: optimisticUpdateId,\n });\n\n room[kInternal].comments\n .createComment({ threadId, commentId, body })\n .then(\n (newComment) => {\n store.set((state) => {\n const existingThread = state.threads[threadId];\n const updatedOptimisticUpdates = state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n );\n\n if (existingThread === undefined) {\n return {\n ...state,\n optimisticUpdates: updatedOptimisticUpdates,\n };\n }\n\n const inboxNotification = Object.values(\n state.inboxNotifications\n ).find((notification) => notification.threadId === threadId);\n\n // If the thread has an inbox notification associated with it, we update the notification's `notifiedAt` and `readAt` values\n const updatedInboxNotifications =\n inboxNotification !== undefined\n ? {\n ...state.inboxNotifications,\n [inboxNotification.id]: {\n ...inboxNotification,\n notifiedAt: newComment.createdAt,\n readAt: newComment.createdAt,\n },\n }\n : state.inboxNotifications;\n\n return {\n ...state,\n threads: {\n ...state.threads,\n [threadId]: upsertComment(existingThread, newComment), // Upsert the new comment into the thread comments list (if applicable)\n },\n inboxNotifications: updatedInboxNotifications,\n optimisticUpdates: updatedOptimisticUpdates,\n };\n });\n },\n (err: Error) =>\n onMutationFailure(\n err,\n optimisticUpdateId,\n (err) =>\n new CreateCommentError(err, {\n roomId: room.id,\n threadId,\n commentId,\n body,\n })\n )\n );\n\n return comment;\n },\n [room]\n );\n }\n\n function useEditComment(): (options: EditCommentOptions) => void {\n const room = useRoom();\n return React.useCallback(\n ({ threadId, commentId, body }: EditCommentOptions): void => {\n const editedAt = new Date();\n const optimisticUpdateId = nanoid();\n\n const thread = store.get().threads[threadId];\n if (thread === undefined) {\n console.warn(\n `Internal unexpected behavior. Cannot edit comment in thread \"${threadId}\" because the thread does not exist in the cache.`\n );\n return;\n }\n\n const comment = thread.comments.find(\n (comment) => comment.id === commentId\n );\n\n if (comment === undefined || comment.deletedAt !== undefined) {\n console.warn(\n `Internal unexpected behavior. Cannot edit comment \"${commentId}\" in thread \"${threadId}\" because the comment does not exist in the cache.`\n );\n return;\n }\n\n store.pushOptimisticUpdate({\n type: \"edit-comment\",\n comment: {\n ...comment,\n editedAt,\n body,\n },\n id: optimisticUpdateId,\n });\n\n room[kInternal].comments\n .editComment({ threadId, commentId, body })\n .then(\n (editedComment) => {\n store.set((state) => {\n const existingThread = state.threads[threadId];\n const updatedOptimisticUpdates = state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n );\n\n if (existingThread === undefined) {\n return {\n ...state,\n optimisticUpdates: updatedOptimisticUpdates,\n };\n }\n\n return {\n ...state,\n threads: {\n ...state.threads,\n [threadId]: upsertComment(existingThread, editedComment), // Upsert the edited comment into the thread comments list (if applicable)\n },\n optimisticUpdates: updatedOptimisticUpdates,\n };\n });\n },\n (err: Error) =>\n onMutationFailure(\n err,\n optimisticUpdateId,\n (error) =>\n new EditCommentError(error, {\n roomId: room.id,\n threadId,\n commentId,\n body,\n })\n )\n );\n },\n [room]\n );\n }\n\n function useDeleteComment() {\n const room = useRoom();\n return React.useCallback(\n ({ threadId, commentId }: DeleteCommentOptions): void => {\n const deletedAt = new Date();\n\n const optimisticUpdateId = nanoid();\n\n store.pushOptimisticUpdate({\n type: \"delete-comment\",\n threadId,\n commentId,\n deletedAt,\n id: optimisticUpdateId,\n });\n\n room[kInternal].comments.deleteComment({ threadId, commentId }).then(\n () => {\n store.set((state) => {\n const existingThread = state.threads[threadId];\n const updatedOptimisticUpdates = state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n );\n\n // If thread does not exist, we return the existing state\n if (existingThread === undefined) {\n return {\n ...state,\n optimisticUpdates: updatedOptimisticUpdates,\n };\n }\n\n return {\n ...state,\n threads: {\n ...state.threads,\n [threadId]: deleteComment(\n existingThread,\n commentId,\n deletedAt\n ),\n },\n optimisticUpdates: updatedOptimisticUpdates,\n };\n });\n },\n (err: Error) =>\n onMutationFailure(\n err,\n optimisticUpdateId,\n (error) =>\n new DeleteCommentError(error, {\n roomId: room.id,\n threadId,\n commentId,\n })\n )\n );\n },\n [room]\n );\n }\n\n const resolveMentionSuggestions = client[kInternal].resolveMentionSuggestions;\n const mentionSuggestionsCache = new Map<string, string[]>();\n\n // Simplistic debounced search, we don't need to worry too much about\n // deduping and race conditions as there can only be one search at a time.\n function useMentionSuggestions(search?: string) {\n const room = useRoom();\n const [mentionSuggestions, setMentionSuggestions] =\n React.useState<string[]>();\n const lastInvokedAt = React.useRef<number>();\n\n React.useEffect(() => {\n if (search === undefined || !resolveMentionSuggestions) {\n return;\n }\n\n const resolveMentionSuggestionsArgs = { text: search, roomId: room.id };\n const mentionSuggestionsCacheKey = stringify(\n resolveMentionSuggestionsArgs\n );\n let debounceTimeout: number | undefined;\n let isCanceled = false;\n\n const getMentionSuggestions = async () => {\n try {\n lastInvokedAt.current = performance.now();\n const mentionSuggestions = await resolveMentionSuggestions(\n resolveMentionSuggestionsArgs\n );\n\n if (!isCanceled) {\n setMentionSuggestions(mentionSuggestions);\n mentionSuggestionsCache.set(\n mentionSuggestionsCacheKey,\n mentionSuggestions\n );\n }\n } catch (error) {\n console.error((error as Error)?.message);\n }\n };\n\n if (mentionSuggestionsCache.has(mentionSuggestionsCacheKey)) {\n // If there are already cached mention suggestions, use them immediately.\n setMentionSuggestions(\n mentionSuggestionsCache.get(mentionSuggestionsCacheKey)\n );\n } else if (\n !lastInvokedAt.current ||\n Math.abs(performance.now() - lastInvokedAt.current) >\n MENTION_SUGGESTIONS_DEBOUNCE\n ) {\n // If on the debounce's leading edge (either because it's the first invokation or enough\n // time has passed since the last debounce), get mention suggestions immediately.\n void getMentionSuggestions();\n } else {\n // Otherwise, wait for the debounce delay.\n debounceTimeout = window.setTimeout(() => {\n void getMentionSuggestions();\n }, MENTION_SUGGESTIONS_DEBOUNCE);\n }\n\n return () => {\n isCanceled = true;\n window.clearTimeout(debounceTimeout);\n };\n }, [room.id, search]);\n\n return mentionSuggestions;\n }\n\n function useThreadSubscription(threadId: string): ThreadSubscription {\n const selector = React.useCallback(\n (state: CacheState<BaseMetadata>): ThreadSubscription => {\n const inboxNotification = selectedInboxNotifications(state).find(\n (inboxNotification) => inboxNotification.threadId === threadId\n );\n\n const thread = state.threads[threadId];\n\n if (inboxNotification === undefined || thread === undefined) {\n return {\n status: \"not-subscribed\",\n };\n }\n\n return {\n status: \"subscribed\",\n unreadSince: inboxNotification.readAt,\n };\n },\n [threadId]\n );\n\n return useSyncExternalStoreWithSelector(\n store.subscribe,\n store.get,\n store.get,\n selector\n );\n }\n\n function useMarkThreadAsRead() {\n const room = useRoom();\n\n return React.useCallback(\n (threadId: string) => {\n const inboxNotification = Object.values(\n store.get().inboxNotifications\n ).find((inboxNotification) => inboxNotification.threadId === threadId);\n\n if (!inboxNotification) return;\n\n const optimisticUpdateId = nanoid();\n const now = new Date();\n\n store.pushOptimisticUpdate({\n type: \"mark-inbox-notification-as-read\",\n id: optimisticUpdateId,\n inboxNotificationId: inboxNotification.id,\n readAt: now,\n });\n\n room[kInternal].notifications\n .markInboxNotificationAsRead(inboxNotification.id)\n .then(\n () => {\n store.set((state) => ({\n ...state,\n inboxNotifications: {\n ...state.inboxNotifications,\n [inboxNotification.id]: {\n ...inboxNotification,\n readAt: now,\n },\n },\n optimisticUpdates: state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n ),\n }));\n },\n (err: Error) => {\n onMutationFailure(\n err,\n optimisticUpdateId,\n (error) =>\n new MarkInboxNotificationAsReadError(error, {\n inboxNotificationId: inboxNotification.id,\n })\n );\n return;\n }\n );\n },\n [room]\n );\n }\n\n function makeNotificationSettingsQueryKey(roomId: string) {\n return `${roomId}:NOTIFICATION_SETTINGS`;\n }\n\n async function getInboxNotificationSettings(\n room: Room<JsonObject, LsonObject, BaseUserMeta, Json>,\n queryKey: string,\n { retryCount }: { retryCount: number } = { retryCount: 0 }\n ) {\n const existingRequest = requestsByQuery.get(queryKey);\n\n // If a request was already made for the notifications query, we do not make another request and return the existing promise\n if (existingRequest !== undefined) return existingRequest;\n\n try {\n const request =\n room[kInternal].notifications.getRoomNotificationSettings();\n\n requestsByQuery.set(queryKey, request);\n\n store.setQueryState(queryKey, {\n isLoading: true,\n });\n\n const settings = await request;\n store.updateRoomInboxNotificationSettings(room.id, settings, queryKey);\n } catch (err) {\n requestsByQuery.delete(queryKey);\n\n retryError(() => {\n void getInboxNotificationSettings(room, queryKey, {\n retryCount: retryCount + 1,\n });\n }, retryCount);\n\n store.setQueryState(queryKey, {\n isLoading: false,\n error: err as Error,\n });\n\n return;\n }\n }\n\n function useRoomNotificationSettings(): [\n RoomNotificationSettingsState,\n (settings: Partial<RoomNotificationSettings>) => void,\n ] {\n const room = useRoom();\n\n React.useEffect(() => {\n const queryKey = makeNotificationSettingsQueryKey(room.id);\n void getInboxNotificationSettings(room, queryKey);\n }, [room]);\n\n const updateRoomNotificationSettings = useUpdateRoomNotificationSettings();\n\n const selector = React.useCallback(\n (state: CacheState<BaseMetadata>): RoomNotificationSettingsState => {\n const query = state.queries[makeNotificationSettingsQueryKey(room.id)];\n\n if (query === undefined || query.isLoading) {\n return { isLoading: true };\n }\n\n if (query.error !== undefined) {\n return { isLoading: false, error: query.error };\n }\n\n return {\n isLoading: false,\n settings: selectNotificationSettings(room.id, state),\n };\n },\n [room]\n );\n\n const settings = useSyncExternalStoreWithSelector(\n store.subscribe,\n store.get,\n store.get,\n selector\n );\n\n return React.useMemo(() => {\n return [settings, updateRoomNotificationSettings];\n }, [settings, updateRoomNotificationSettings]);\n }\n\n function useRoomNotificationSettingsSuspense(): [\n RoomNotificationSettingsStateSuccess,\n (settings: Partial<RoomNotificationSettings>) => void,\n ] {\n const updateRoomNotificationSettings = useUpdateRoomNotificationSettings();\n const room = useRoom();\n const queryKey = makeNotificationSettingsQueryKey(room.id);\n const query = store.get().queries[queryKey];\n\n if (query === undefined || query.isLoading) {\n throw getInboxNotificationSettings(room, queryKey);\n }\n\n if (query.error) {\n throw query.error;\n }\n\n const selector = React.useCallback(\n (\n state: CacheState<BaseMetadata>\n ): RoomNotificationSettingsStateSuccess => {\n return {\n isLoading: false,\n settings: selectNotificationSettings(room.id, state),\n };\n },\n [room]\n );\n\n const settings = useSyncExternalStoreWithSelector(\n store.subscribe,\n store.get,\n store.get,\n selector\n );\n\n return React.useMemo(() => {\n return [settings, updateRoomNotificationSettings];\n }, [settings, updateRoomNotificationSettings]);\n }\n\n function useUpdateRoomNotificationSettings() {\n const room = useRoom();\n return React.useCallback(\n (settings: Partial<RoomNotificationSettings>) => {\n const optimisticUpdateId = nanoid();\n\n store.pushOptimisticUpdate({\n id: optimisticUpdateId,\n type: \"update-notification-settings\",\n roomId: room.id,\n settings,\n });\n\n room[kInternal].notifications\n .updateRoomNotificationSettings(settings)\n .then(\n (settings) => {\n store.set((state) => ({\n ...state,\n notificationSettings: {\n [room.id]: settings,\n },\n optimisticUpdates: state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n ),\n }));\n },\n (err: Error) =>\n onMutationFailure(\n err,\n optimisticUpdateId,\n (error) =>\n new UpdateNotificationSettingsError(error, {\n roomId: room.id,\n })\n )\n );\n },\n [room]\n );\n }\n\n function useCurrentUserId() {\n return useSelf((user) => (typeof user.id === \"string\" ? user.id : null));\n }\n\n const bundle: RoomContextBundle<\n TPresence,\n TStorage,\n TUserMeta,\n TRoomEvent,\n TThreadMetadata\n > = {\n RoomContext,\n RoomProvider: RoomProviderOuter,\n\n useRoom,\n useStatus,\n\n useBatch,\n useBroadcastEvent,\n useOthersListener,\n useLostConnectionListener,\n useErrorListener,\n useEventListener,\n\n useHistory,\n useUndo,\n useRedo,\n useCanRedo,\n useCanUndo,\n\n // These are just aliases. The passed-in key will define their return values.\n useList: useLegacyKey,\n useMap: useLegacyKey,\n useObject: useLegacyKey,\n\n useStorageRoot,\n useStorage,\n\n useSelf,\n useMyPresence,\n useUpdateMyPresence,\n useOthers,\n useOthersMapped,\n useOthersConnectionIds,\n useOther,\n\n useMutation,\n\n useThreads,\n\n useCreateThread,\n useEditThreadMetadata,\n useCreateComment,\n useEditComment,\n useDeleteComment,\n useAddReaction,\n useRemoveReaction,\n useMarkThreadAsRead,\n useThreadSubscription,\n\n useRoomNotificationSettings,\n useUpdateRoomNotificationSettings,\n\n ...shared,\n\n suspense: {\n RoomContext,\n RoomProvider: RoomProviderOuter,\n\n useRoom,\n useStatus,\n\n useBatch,\n useBroadcastEvent,\n useOthersListener,\n useLostConnectionListener,\n useErrorListener,\n useEventListener,\n\n useHistory,\n useUndo,\n useRedo,\n useCanRedo,\n useCanUndo,\n\n // Legacy hooks\n useList: useLegacyKeySuspense,\n useMap: useLegacyKeySuspense,\n useObject: useLegacyKeySuspense,\n\n useStorageRoot,\n useStorage: useStorageSuspense,\n\n useSelf: useSelfSuspense,\n useMyPresence,\n useUpdateMyPresence,\n useOthers: useOthersSuspense,\n useOthersMapped: useOthersMappedSuspense,\n useOthersConnectionIds: useOthersConnectionIdsSuspense,\n useOther: useOtherSuspense,\n\n useMutation,\n\n useThreads: useThreadsSuspense,\n\n useCreateThread,\n useEditThreadMetadata,\n useCreateComment,\n useEditComment,\n useDeleteComment,\n useAddReaction,\n useRemoveReaction,\n useMarkThreadAsRead,\n useThreadSubscription,\n\n useRoomNotificationSettings: useRoomNotificationSettingsSuspense,\n useUpdateRoomNotificationSettings,\n\n ...shared.suspense,\n },\n\n [kInternal]: {\n useCurrentUserId,\n hasResolveMentionSuggestions: resolveMentionSuggestions !== undefined,\n useMentionSuggestions,\n },\n };\n\n return Object.defineProperty(bundle, kInternal, {\n enumerable: false,\n });\n}\n\nfunction getCurrentUserId(\n room: Room<JsonObject, LsonObject, BaseUserMeta, Json>\n): string {\n const self = room.getSelf();\n if (self === null || self.id === undefined) {\n return \"anonymous\";\n } else {\n return self.id;\n }\n}\n\nfunction handleApiError(err: CommentsApiError | NotificationsApiError): Error {\n const message = `Request failed with status ${err.status}: ${err.message}`;\n\n // Log details about FORBIDDEN errors\n if (err.details?.error === \"FORBIDDEN\") {\n const detailedMessage = [message, err.details.suggestion, err.details.docs]\n .filter(Boolean)\n .join(\"\\n\");\n\n console.error(detailedMessage);\n }\n\n return new Error(message);\n}\n\nexport function generateQueryKey<TThreadMetadata extends BaseMetadata>(\n roomId: string,\n options: UseThreadsOptions<TThreadMetadata>[\"query\"]\n) {\n return `${roomId}-${stringify(options ?? {})}`;\n}\n","import type {\n BaseMetadata,\n CommentBody,\n PartialNullable,\n} from \"@liveblocks/core\";\n\nexport class CreateThreadError<TMetadata extends BaseMetadata> extends Error {\n constructor(\n public cause: Error,\n public context: {\n roomId: string;\n threadId: string;\n commentId: string;\n body: CommentBody;\n metadata: TMetadata;\n }\n ) {\n super(\"Create thread failed.\");\n this.name = \"CreateThreadError\";\n }\n}\n\nexport class EditThreadMetadataError<\n TMetadata extends BaseMetadata,\n> extends Error {\n constructor(\n public cause: Error,\n public context: {\n roomId: string;\n threadId: string;\n metadata: PartialNullable<TMetadata>;\n }\n ) {\n super(\"Edit thread metadata failed.\");\n this.name = \"EditThreadMetadataError\";\n }\n}\n\nexport class CreateCommentError extends Error {\n constructor(\n public cause: Error,\n public context: {\n roomId: string;\n threadId: string;\n commentId: string;\n body: CommentBody;\n }\n ) {\n super(\"Create comment failed.\");\n this.name = \"CreateCommentError\";\n }\n}\n\nexport class EditCommentError extends Error {\n constructor(\n public cause: Error,\n public context: {\n roomId: string;\n threadId: string;\n commentId: string;\n body: CommentBody;\n }\n ) {\n super(\"Edit comment failed.\");\n this.name = \"EditCommentError\";\n }\n}\n\nexport class DeleteCommentError extends Error {\n constructor(\n public cause: Error,\n public context: {\n roomId: string;\n threadId: string;\n commentId: string;\n }\n ) {\n super(\"Delete comment failed.\");\n this.name = \"DeleteCommentError\";\n }\n}\n\nexport class AddReactionError extends Error {\n constructor(\n public cause: Error,\n public context: {\n roomId: string;\n threadId: string;\n commentId: string;\n emoji: string;\n }\n ) {\n super(\"Add reaction failed.\");\n this.name = \"AddReactionError\";\n }\n}\n\nexport class RemoveReactionError extends Error {\n constructor(\n public cause: Error,\n public context: {\n roomId: string;\n threadId: string;\n commentId: string;\n emoji: string;\n }\n ) {\n super(\"Remove reaction failed.\");\n this.name = \"RemoveReactionError\";\n }\n}\n\nexport class MarkInboxNotificationAsReadError extends Error {\n constructor(\n public cause: Error,\n public context: {\n inboxNotificationId: string;\n }\n ) {\n super(\"Mark inbox notification as read failed.\");\n this.name = \"MarkInboxNotificationAsReadError\";\n }\n}\n\nexport class UpdateNotificationSettingsError extends Error {\n constructor(\n public cause: Error,\n public context: {\n roomId: string;\n }\n ) {\n super(\"Update notification settings failed.\");\n this.name = \"UpdateNotificationSettingsError\";\n }\n}\n\nexport type CommentsError<TThreadMetadata extends BaseMetadata> =\n | CreateThreadError<TThreadMetadata>\n | EditThreadMetadataError<TThreadMetadata>\n | CreateCommentError\n | EditCommentError\n | DeleteCommentError\n | MarkInboxNotificationAsReadError\n | UpdateNotificationSettingsError;\n","import { nanoid } from \"nanoid\";\n\nconst THREAD_ID_PREFIX = \"th\";\nconst COMMENT_ID_PREFIX = \"cm\";\nconst INBOX_NOTIFICATION_ID_PREFIX = \"in\";\n\nfunction createOptimisticId(prefix: string) {\n return `${prefix}_${nanoid()}`;\n}\n\nexport function createThreadId() {\n return createOptimisticId(THREAD_ID_PREFIX);\n}\n\nexport function createCommentId() {\n return createOptimisticId(COMMENT_ID_PREFIX);\n}\n\nexport function createInboxNotificationId() {\n return createOptimisticId(INBOX_NOTIFICATION_ID_PREFIX);\n}\n","import {\n applyOptimisticUpdates,\n type BaseMetadata,\n type CacheState,\n nn,\n type RoomNotificationSettings,\n} from \"@liveblocks/core\";\n\nexport function selectNotificationSettings<\n TThreadMetadata extends BaseMetadata,\n>(\n roomId: string,\n state: CacheState<TThreadMetadata>\n): RoomNotificationSettings {\n const { notificationSettings } = applyOptimisticUpdates(state);\n return nn(notificationSettings[roomId]);\n}\n","import {\n applyOptimisticUpdates,\n type BaseMetadata,\n type CacheState,\n type ThreadData,\n} from \"@liveblocks/core\";\n\nimport type { UseThreadsOptions } from \"../../types\";\n\nexport function selectedThreads<TThreadMetadata extends BaseMetadata>(\n roomId: string,\n state: CacheState<TThreadMetadata>,\n options: UseThreadsOptions<TThreadMetadata>\n): ThreadData<TThreadMetadata>[] {\n const result = applyOptimisticUpdates(state);\n\n // Filter threads to only include the non-deleted threads from the specified room and that match the specified filter options\n const threads = Object.values(result.threads).filter<\n ThreadData<TThreadMetadata>\n >((thread): thread is ThreadData<TThreadMetadata> => {\n if (thread.roomId !== roomId) return false;\n\n // We do not want to include threads that have been marked as deleted\n if (thread.deletedAt !== undefined) {\n return false;\n }\n\n const query = options.query;\n if (!query) return true;\n\n for (const key in query.metadata) {\n if (thread.metadata[key] !== query.metadata[key]) {\n return false;\n }\n }\n\n return true;\n });\n\n // Sort threads by creation date (oldest first)\n return threads.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());\n}\n","import { useState } from \"react\";\n\n/**\n * \"Freezes\" a given value, so that it will return the same value/instance on\n * each subsequent render. This can be used to freeze \"initial\" values for\n * custom hooks, much like how `useState(initialState)` or\n * `useRef(initialValue)` works.\n */\nexport function useInitial<T>(value: T): T {\n return useState(value)[0];\n}\n","import { useEffect, useRef } from \"react\";\n\n/**\n * Keeps a ref in sync with a given value that may or may not change on\n * every render.\n *\n * The purpose of this hook is to return a stable ref that can be passed\n * to a callback function so the callback can be registered but still can\n * access the latest value at a later point in time.\n */\nexport function useLatest<T>(value: T): { readonly current: T } {\n const ref = useRef(value);\n useEffect(() => {\n ref.current = value;\n }, [value]);\n return ref;\n}\n","import { useReducer } from \"react\";\n\n/**\n * Trigger a re-render programmatically, without changing the component's\n * state.\n *\n * @example\n * const rerender = useRerender();\n *\n * return (\n * <button onClick={rerender}>\n * {Math.random()}\n * </button>\n * )\n */\nexport function useRerender(): () => void {\n const [, update] = useReducer(\n // This implementation works by incrementing a hidden counter value that is\n // never consumed. Simply incrementing the counter changes the component's\n // state and, thus, trigger a re-render.\n (x: number): number => x + 1,\n 0\n );\n return update;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/version.ts","../src/ClientSideSuspense.tsx","../src/comments/errors.ts","../src/liveblocks.tsx","../src/lib/retry-error.ts","../src/lib/use-initial.ts","../src/shared.ts","../src/room.tsx","../src/lib/use-latest.ts","../src/lib/use-rerender.ts","../src/use-scroll-to-comment-on-load-effect.ts"],"names":["kInternal","makePoller","raise","nanoid","React","createContext","useCallback","useContext","useEffect","useSyncExternalStore","useSyncExternalStoreWithSelector","useState","console","comment","subscribers","mentionSuggestions","room","other","rootOrNull","state","err","metadata","inboxNotification","settings","_extras","_bundles","POLLING_INTERVAL","getExtrasForClient","makeExtrasForClient","LiveblocksProvider","shallow"],"mappings":";;;AAAA,SAAS,mBAAmB;;;ACGrB,IAAM,WAAW;AACjB,IAAM,cAAiD;AACvD,IAAM,aAAgD;;;ACJ7D,YAAY,WAAW;AAwBhB,SAAS,mBAAmB,OAA4B;AAC7D,QAAM,CAAC,SAAS,UAAU,IAAU,eAAS,KAAK;AAElD,EAAM,gBAAU,MAAM;AAGpB,eAAW,IAAI;AAAA,EACjB,GAAG,CAAC,CAAC;AAEL,SACE,oCAAO,gBAAN,EAAe,UAAU,MAAM,YAC7B,UAAU,MAAM,SAAS,IAAI,MAAM,QACtC;AAEJ;;;ACjCO,IAAM,oBAAN,cAAwD,MAAM;AAAA,EACnE,YACS,OACA,SAOP;AACA,UAAM,uBAAuB;AATtB;AACA;AASP,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,0BAAN,cAA8D,MAAM;AAAA,EACzE,YACS,OACA,SAKP;AACA,UAAM,8BAA8B;AAP7B;AACA;AAOP,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,qBAAN,cAAiC,MAAM;AAAA,EAC5C,YACS,OACA,SAMP;AACA,UAAM,wBAAwB;AARvB;AACA;AAQP,SAAK,OAAO;AAAA,EACd;AACF;AAEO,IAAM,mBAAN,cAA+B,MAAM;AAAA,EAC1C,YACS,OACA,SAMP;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MAAM,mBAAmB,mBAAmB,KAC5CJ,OAAM,+BAA+B,mBAAmB,aAAa;AAEvE,UAAI,kBAAkB,SAAS,UAAU;AACvC,QAAAA;AAAA,UACE,+BAA+B,mBAAmB;AAAA,QACpD;AAAA,MACF;AAEA,YAAM,SACJ,MAAM,QAAQ,kBAAkB,QAAQ,KACxCA;AAAA,QACE,mBAAmB,kBAAkB,QAAQ;AAAA,MAC/C;AAEF,aAAO;AAAA,IACT;AAAA,IACA,CAAC,mBAAmB;AAAA,EACtB;AAEA,SAAOQ;AAAA,IACL,MAAM;AAAA,IACN,MAAM;AAAA,IACN,MAAM;AAAA,IACN;AAAA,EACF;AACF;AAEA,SAAS,4BAA4B,QAAsB;AACzD,QAAM,qBAAqB,OAAOV,UAAS,EAAE;AAC7C,SAAOS;AAAA,IACL,mBAAmB;AAAA,IACnB,mBAAmB;AAAA,IACnB,mBAAmB;AAAA,EACrB;AACF;AAKO,SAAS,kBAAkB;AAChC,SAAOF,YAAW,aAAa;AACjC;AAMO,SAAS,YAAY;AAC1B,SACE,gBAAgB,KAChBL,OAAM,oDAAoD;AAE9D;AAKO,SAAS,mBACd,OACA;AACA,SACE,gBAAAE,OAAA,cAAC,cAAc,UAAd,EAAuB,OAAO,MAAM,UAClC,MAAM,QACT;AAEJ;AAOO,SAAS,mCAAmC;AACjD,QAAM,SAAS,gBAAgB;AAC/B,SAAO,WAAW,OAAO,yBAAyB,MAAM,IAAI;AAC9D;AAOO,SAAS,6BAA6B;AAC3C,QAAM,SAAS,UAAU;AACzB,SAAO,yBAAyB,MAAM;AACxC;AAEO,SAAS,wBAGd,QAAqD;AACrD,SAAO,yBAA+B,MAAM;AAC9C;;;AJpnBA,SAAS,WAAA0B,gBAAe;AAhBxB,YAAY,UAAU,aAAa,UAAU","sourcesContent":["import { detectDupes } from \"@liveblocks/core\";\n\nimport { PKG_FORMAT, PKG_NAME, PKG_VERSION } from \"./version\";\n\ndetectDupes(PKG_NAME, PKG_VERSION, PKG_FORMAT);\n\nexport { ClientSideSuspense } from \"./ClientSideSuspense\";\nexport { CreateThreadError, DeleteCommentError } from \"./comments/errors\";\nexport {\n createLiveblocksContext,\n useClient,\n useLiveblocksContextBundle,\n useLiveblocksContextBundleOrNull,\n} from \"./liveblocks\";\nexport { createRoomContext, useRoomContextBundle } from \"./room\";\nexport { useSharedContextBundle } from \"./shared\";\nexport type { MutationContext, UseThreadsOptions } from \"./types\";\n\n// Re-exports from @liveblocks/client, for convenience\nexport type { Json, JsonObject } from \"@liveblocks/client\";\nexport { shallow } from \"@liveblocks/client\";\n","declare const __VERSION__: string;\ndeclare const TSUP_FORMAT: string;\n\nexport const PKG_NAME = \"@liveblocks/react\";\nexport const PKG_VERSION = typeof __VERSION__ === \"string\" && __VERSION__;\nexport const PKG_FORMAT = typeof TSUP_FORMAT === \"string\" && TSUP_FORMAT;\n","import type { ReactElement, ReactNode } from \"react\";\nimport * as React from \"react\";\n\ntype Props = {\n fallback: NonNullable<ReactNode> | null;\n children: () => ReactNode | undefined;\n};\n\n/**\n * Almost like a normal <Suspense> component, except that for server-side\n * renders, the fallback will be used.\n *\n * The child props will have to be provided in a function, i.e. change:\n *\n * <Suspense fallback={<Loading />}>\n * <MyRealComponent a={1} />\n * </Suspense>\n *\n * To:\n *\n * <ClientSideSuspense fallback={<Loading />}>\n * {() => <MyRealComponent a={1} />}\n * </ClientSideSuspense>\n *\n */\nexport function ClientSideSuspense(props: Props): ReactElement {\n const [mounted, setMounted] = React.useState(false);\n\n React.useEffect(() => {\n // Effects are never executed on the server side. The point of this is to\n // delay the flipping of this boolean until after hydration has happened.\n setMounted(true);\n }, []);\n\n return (\n <React.Suspense fallback={props.fallback}>\n {mounted ? props.children() : props.fallback}\n </React.Suspense>\n );\n}\n","import type {\n BaseMetadata,\n CommentBody,\n PartialNullable,\n} from \"@liveblocks/core\";\n\nexport class CreateThreadError<M extends BaseMetadata> extends Error {\n constructor(\n public cause: Error,\n public context: {\n roomId: string;\n threadId: string;\n commentId: string;\n body: CommentBody;\n metadata: M;\n }\n ) {\n super(\"Create thread failed.\");\n this.name = \"CreateThreadError\";\n }\n}\n\nexport class EditThreadMetadataError<M extends BaseMetadata> extends Error {\n constructor(\n public cause: Error,\n public context: {\n roomId: string;\n threadId: string;\n metadata: PartialNullable<M>;\n }\n ) {\n super(\"Edit thread metadata failed.\");\n this.name = \"EditThreadMetadataError\";\n }\n}\n\nexport class CreateCommentError extends Error {\n constructor(\n public cause: Error,\n public context: {\n roomId: string;\n threadId: string;\n commentId: string;\n body: CommentBody;\n }\n ) {\n super(\"Create comment failed.\");\n this.name = \"CreateCommentError\";\n }\n}\n\nexport class EditCommentError extends Error {\n constructor(\n public cause: Error,\n public context: {\n roomId: string;\n threadId: string;\n commentId: string;\n body: CommentBody;\n }\n ) {\n super(\"Edit comment failed.\");\n this.name = \"EditCommentError\";\n }\n}\n\nexport class DeleteCommentError extends Error {\n constructor(\n public cause: Error,\n public context: {\n roomId: string;\n threadId: string;\n commentId: string;\n }\n ) {\n super(\"Delete comment failed.\");\n this.name = \"DeleteCommentError\";\n }\n}\n\nexport class AddReactionError extends Error {\n constructor(\n public cause: Error,\n public context: {\n roomId: string;\n threadId: string;\n commentId: string;\n emoji: string;\n }\n ) {\n super(\"Add reaction failed.\");\n this.name = \"AddReactionError\";\n }\n}\n\nexport class RemoveReactionError extends Error {\n constructor(\n public cause: Error,\n public context: {\n roomId: string;\n threadId: string;\n commentId: string;\n emoji: string;\n }\n ) {\n super(\"Remove reaction failed.\");\n this.name = \"RemoveReactionError\";\n }\n}\n\nexport class MarkInboxNotificationAsReadError extends Error {\n constructor(\n public cause: Error,\n public context: {\n inboxNotificationId: string;\n }\n ) {\n super(\"Mark inbox notification as read failed.\");\n this.name = \"MarkInboxNotificationAsReadError\";\n }\n}\n\nexport class UpdateNotificationSettingsError extends Error {\n constructor(\n public cause: Error,\n public context: {\n roomId: string;\n }\n ) {\n super(\"Update notification settings failed.\");\n this.name = \"UpdateNotificationSettingsError\";\n }\n}\n\nexport type CommentsError<M extends BaseMetadata> =\n | CreateThreadError<M>\n | EditThreadMetadataError<M>\n | CreateCommentError\n | EditCommentError\n | DeleteCommentError\n | MarkInboxNotificationAsReadError\n | UpdateNotificationSettingsError;\n","import type {\n BaseMetadata,\n BaseUserMeta,\n Client,\n ThreadData,\n} from \"@liveblocks/client\";\nimport type {\n CacheState,\n CacheStore,\n InboxNotificationData,\n InboxNotificationDeleteInfo,\n ThreadDeleteInfo,\n} from \"@liveblocks/core\";\nimport { kInternal, makePoller, raise } from \"@liveblocks/core\";\nimport { nanoid } from \"nanoid\";\nimport type { PropsWithChildren } from \"react\";\nimport React, {\n createContext,\n useCallback,\n useContext,\n useEffect,\n} from \"react\";\nimport { useSyncExternalStore } from \"use-sync-external-store/shim/index.js\";\nimport { useSyncExternalStoreWithSelector } from \"use-sync-external-store/shim/with-selector.js\";\n\nimport { retryError } from \"./lib/retry-error\";\nimport { useInitial } from \"./lib/use-initial\";\nimport type { DU } from \"./shared\";\nimport { createSharedContext } from \"./shared\";\nimport type {\n InboxNotificationsState,\n InboxNotificationsStateSuccess,\n LiveblocksContextBundle,\n UnreadInboxNotificationsCountState,\n UnreadInboxNotificationsCountStateSuccess,\n} from \"./types\";\n\ntype OpaqueClient = Client<BaseUserMeta>;\n\nconst ClientContext = createContext<OpaqueClient | null>(null);\n\nconst _extras = new WeakMap<\n OpaqueClient,\n ReturnType<typeof makeExtrasForClient>\n>();\nconst _bundles = new WeakMap<\n OpaqueClient,\n LiveblocksContextBundle<BaseUserMeta, BaseMetadata>\n>();\n\n// export const POLLING_INTERVAL = 60 * 1000; // 1 minute\nexport const POLLING_INTERVAL = 5 * 1000; // 1 minute\nexport const INBOX_NOTIFICATIONS_QUERY = \"INBOX_NOTIFICATIONS\";\n\nfunction selectorFor_useInboxNotifications(\n client: OpaqueClient,\n state: CacheState<BaseMetadata>\n): InboxNotificationsState {\n const query = state.queries[INBOX_NOTIFICATIONS_QUERY];\n\n if (query === undefined || query.isLoading) {\n return {\n isLoading: true,\n };\n }\n\n if (query.error !== undefined) {\n return {\n error: query.error,\n isLoading: false,\n };\n }\n\n return {\n inboxNotifications:\n client[kInternal].comments.selectedInboxNotifications(state),\n isLoading: false,\n };\n}\n\nfunction selectorFor_useInboxNotificationsSuspense(\n client: OpaqueClient,\n state: CacheState<BaseMetadata>\n): InboxNotificationsStateSuccess {\n return {\n inboxNotifications:\n client[kInternal].comments.selectedInboxNotifications(state),\n isLoading: false,\n };\n}\n\nfunction selectUnreadInboxNotificationsCount(\n client: OpaqueClient,\n state: CacheState<BaseMetadata>\n) {\n let count = 0;\n\n for (const notification of client[\n kInternal\n ].comments.selectedInboxNotifications(state)) {\n if (\n notification.readAt === null ||\n notification.readAt < notification.notifiedAt\n ) {\n count++;\n }\n }\n\n return count;\n}\n\nfunction selectorFor_useUnreadInboxNotificationsCount(\n client: OpaqueClient,\n state: CacheState<BaseMetadata>\n): UnreadInboxNotificationsCountState {\n const query = state.queries[INBOX_NOTIFICATIONS_QUERY];\n\n if (query === undefined || query.isLoading) {\n return {\n isLoading: true,\n };\n }\n\n if (query.error !== undefined) {\n return {\n error: query.error,\n isLoading: false,\n };\n }\n\n return {\n isLoading: false,\n count: selectUnreadInboxNotificationsCount(client, state),\n };\n}\n\nfunction selectorFor_useUnreadInboxNotificationsCountSuspense(\n client: OpaqueClient,\n state: CacheState<BaseMetadata>\n): UnreadInboxNotificationsCountStateSuccess {\n return {\n isLoading: false,\n count: selectUnreadInboxNotificationsCount(client, state),\n };\n}\n\nfunction getOrCreateContextBundle<\n U extends BaseUserMeta,\n M extends BaseMetadata,\n>(client: OpaqueClient): LiveblocksContextBundle<U, M> {\n let bundle = _bundles.get(client);\n if (!bundle) {\n bundle = makeLiveblocksContextBundle(client);\n _bundles.set(client, bundle);\n }\n return bundle as LiveblocksContextBundle<U, M>;\n}\n\n// TODO: Likely a better / more clear name for this helper will arise. I'll\n// rename this later. All of these are implementation details to support inbox\n// notifications on a per-client basis.\nfunction getExtrasForClient<M extends BaseMetadata>(client: OpaqueClient) {\n let extras = _extras.get(client);\n if (!extras) {\n extras = makeExtrasForClient(client);\n _extras.set(client, extras);\n }\n\n return extras as unknown as Omit<typeof extras, \"store\"> & {\n store: CacheStore<M>;\n };\n}\n\nfunction makeExtrasForClient<M extends BaseMetadata>(client: OpaqueClient) {\n const store = client[kInternal].cacheStore as unknown as CacheStore<M>;\n const notifications = client[kInternal].notifications;\n\n let fetchInboxNotificationsRequest: Promise<{\n inboxNotifications: InboxNotificationData[];\n threads: ThreadData<M>[];\n deletedThreads: ThreadDeleteInfo[];\n deletedInboxNotifications: InboxNotificationDeleteInfo[];\n meta: {\n requestedAt: Date;\n };\n }> | null = null;\n\n let lastRequestedAt: Date | undefined;\n\n const poller = makePoller(() =>\n notifications.getInboxNotifications({ since: lastRequestedAt }).then(\n (result) => {\n lastRequestedAt = result.meta.requestedAt;\n\n store.updateThreadsAndNotifications(\n result.threads,\n result.inboxNotifications,\n result.deletedThreads,\n result.deletedInboxNotifications,\n INBOX_NOTIFICATIONS_QUERY\n );\n },\n () => {\n // TODO: Error handling\n }\n )\n );\n\n async function fetchInboxNotifications(\n { retryCount }: { retryCount: number } = { retryCount: 0 }\n ) {\n if (fetchInboxNotificationsRequest !== null) {\n return fetchInboxNotificationsRequest;\n }\n\n store.setQueryState(INBOX_NOTIFICATIONS_QUERY, {\n isLoading: true,\n });\n\n try {\n fetchInboxNotificationsRequest = notifications.getInboxNotifications();\n\n const result = await fetchInboxNotificationsRequest;\n\n store.updateThreadsAndNotifications(\n result.threads,\n result.inboxNotifications,\n result.deletedThreads,\n result.deletedInboxNotifications,\n INBOX_NOTIFICATIONS_QUERY\n );\n\n /**\n * We set the `lastRequestedAt` to the timestamp returned by the current request if:\n * 1. The `lastRequestedAt`has not been set\n * OR\n * 2. The current `lastRequestedAt` is older than the timestamp returned by the current request\n */\n if (\n lastRequestedAt === undefined ||\n lastRequestedAt > result.meta.requestedAt\n ) {\n lastRequestedAt = result.meta.requestedAt;\n }\n\n poller.start(POLLING_INTERVAL);\n } catch (er) {\n fetchInboxNotificationsRequest = null;\n\n // Retry the action using the exponential backoff algorithm\n retryError(() => {\n void fetchInboxNotifications({\n retryCount: retryCount + 1,\n });\n }, retryCount);\n\n store.setQueryState(INBOX_NOTIFICATIONS_QUERY, {\n isLoading: false,\n error: er as Error,\n });\n }\n return;\n }\n\n let inboxNotificationsSubscribers = 0;\n\n function useSubscribeToInboxNotificationsEffect(options?: {\n autoFetch: boolean;\n }) {\n const autoFetch = useInitial(options?.autoFetch ?? true);\n useEffect(() => {\n if (autoFetch) {\n void fetchInboxNotifications();\n }\n\n // Increment\n inboxNotificationsSubscribers++;\n poller.start(POLLING_INTERVAL);\n\n return () => {\n // Decrement\n if (inboxNotificationsSubscribers <= 0) {\n console.warn(\n `Internal unexpected behavior. Cannot decrease subscriber count for query \"${INBOX_NOTIFICATIONS_QUERY}\"`\n );\n return;\n }\n\n inboxNotificationsSubscribers--;\n if (inboxNotificationsSubscribers <= 0) {\n poller.stop();\n }\n };\n }, [autoFetch]);\n }\n\n return {\n store,\n notifications,\n fetchInboxNotifications,\n useSubscribeToInboxNotificationsEffect,\n };\n}\n\nfunction makeLiveblocksContextBundle<\n U extends BaseUserMeta,\n M extends BaseMetadata,\n>(client: Client<U>): LiveblocksContextBundle<U, M> {\n // Bind all hooks to the current client instance\n const useInboxNotificationThread = (inboxNotificationId: string) =>\n useInboxNotificationThread_withClient<M>(client, inboxNotificationId);\n\n const useMarkInboxNotificationAsRead = () =>\n useMarkInboxNotificationAsRead_withClient(client);\n\n const useMarkAllInboxNotificationsAsRead = () =>\n useMarkAllInboxNotificationsAsRead_withClient(client);\n\n function LiveblocksProvider(props: PropsWithChildren) {\n return (\n <ClientContext.Provider value={client}>\n {props.children}\n </ClientContext.Provider>\n );\n }\n\n const shared = createSharedContext<U>(client);\n\n const bundle: LiveblocksContextBundle<U, M> = {\n LiveblocksProvider,\n\n useInboxNotifications: () => useInboxNotifications_withClient(client),\n useUnreadInboxNotificationsCount: () =>\n useUnreadInboxNotificationsCount_withClient(client),\n\n useMarkInboxNotificationAsRead,\n useMarkAllInboxNotificationsAsRead,\n\n useInboxNotificationThread,\n\n ...shared.classic,\n\n suspense: {\n LiveblocksProvider,\n\n useInboxNotifications: () =>\n useInboxNotificationsSuspense_withClient(client),\n useUnreadInboxNotificationsCount: () =>\n useUnreadInboxNotificationsCountSuspense_withClient(client),\n\n useMarkInboxNotificationAsRead,\n useMarkAllInboxNotificationsAsRead,\n\n useInboxNotificationThread,\n\n ...shared.suspense,\n },\n\n [kInternal]: {\n useCurrentUserId: () => useCurrentUserId_withClient(client),\n },\n };\n\n return Object.defineProperty(bundle, kInternal, {\n enumerable: false,\n });\n}\n\nfunction useInboxNotifications_withClient(client: OpaqueClient) {\n const { store, useSubscribeToInboxNotificationsEffect } =\n getExtrasForClient(client);\n\n useSubscribeToInboxNotificationsEffect();\n return useSyncExternalStoreWithSelector(\n store.subscribe,\n store.get,\n store.get,\n () => selectorFor_useInboxNotifications(client, store.get())\n );\n}\n\nfunction useInboxNotificationsSuspense_withClient(client: OpaqueClient) {\n const {\n store,\n fetchInboxNotifications,\n useSubscribeToInboxNotificationsEffect,\n } = getExtrasForClient(client);\n\n const query = store.get().queries[INBOX_NOTIFICATIONS_QUERY];\n\n if (query === undefined || query.isLoading) {\n throw fetchInboxNotifications();\n }\n\n if (query.error !== undefined) {\n throw query.error;\n }\n\n useSubscribeToInboxNotificationsEffect({ autoFetch: false });\n return useSyncExternalStoreWithSelector(\n store.subscribe,\n store.get,\n store.get,\n () => selectorFor_useInboxNotificationsSuspense(client, store.get())\n );\n}\n\nfunction useUnreadInboxNotificationsCount_withClient(client: OpaqueClient) {\n const { store, useSubscribeToInboxNotificationsEffect } =\n getExtrasForClient(client);\n\n useSubscribeToInboxNotificationsEffect();\n return useSyncExternalStoreWithSelector(\n store.subscribe,\n store.get,\n store.get,\n () => selectorFor_useUnreadInboxNotificationsCount(client, store.get())\n );\n}\n\nfunction useUnreadInboxNotificationsCountSuspense_withClient(\n client: OpaqueClient\n) {\n const {\n store,\n fetchInboxNotifications,\n useSubscribeToInboxNotificationsEffect,\n } = getExtrasForClient(client);\n\n const query = store.get().queries[INBOX_NOTIFICATIONS_QUERY];\n\n if (query === undefined || query.isLoading) {\n throw fetchInboxNotifications();\n }\n\n useSubscribeToInboxNotificationsEffect({ autoFetch: false });\n return useSyncExternalStoreWithSelector(\n store.subscribe,\n store.get,\n store.get,\n () =>\n selectorFor_useUnreadInboxNotificationsCountSuspense(client, store.get())\n );\n}\n\nfunction useMarkInboxNotificationAsRead_withClient(client: OpaqueClient) {\n return useCallback(\n (inboxNotificationId: string) => {\n const { store, notifications } = getExtrasForClient(client);\n\n const optimisticUpdateId = nanoid();\n const readAt = new Date();\n store.pushOptimisticUpdate({\n type: \"mark-inbox-notification-as-read\",\n id: optimisticUpdateId,\n inboxNotificationId,\n readAt,\n });\n\n notifications.markInboxNotificationAsRead(inboxNotificationId).then(\n () => {\n store.set((state) => {\n const existingNotification =\n state.inboxNotifications[inboxNotificationId];\n\n // If existing notification has been deleted, we return the existing state\n if (existingNotification === undefined) {\n return {\n ...state,\n optimisticUpdates: state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n ),\n };\n }\n\n return {\n ...state,\n inboxNotifications: {\n ...state.inboxNotifications,\n [inboxNotificationId]: {\n ...existingNotification,\n readAt,\n },\n },\n optimisticUpdates: state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n ),\n };\n });\n },\n () => {\n // TODO: Broadcast errors to client\n store.set((state) => ({\n ...state,\n optimisticUpdates: state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n ),\n }));\n }\n );\n },\n [client]\n );\n}\n\nfunction useMarkAllInboxNotificationsAsRead_withClient(client: OpaqueClient) {\n return useCallback(() => {\n const { store, notifications } = getExtrasForClient(client);\n const optimisticUpdateId = nanoid();\n const readAt = new Date();\n store.pushOptimisticUpdate({\n type: \"mark-inbox-notifications-as-read\",\n id: optimisticUpdateId,\n readAt,\n });\n\n notifications.markAllInboxNotificationsAsRead().then(\n () => {\n store.set((state) => ({\n ...state,\n inboxNotifications: Object.fromEntries(\n Array.from(Object.entries(state.inboxNotifications)).map(\n ([id, inboxNotification]) => [\n id,\n { ...inboxNotification, readAt },\n ]\n )\n ),\n optimisticUpdates: state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n ),\n }));\n },\n () => {\n // TODO: Broadcast errors to client\n store.set((state) => ({\n ...state,\n optimisticUpdates: state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n ),\n }));\n }\n );\n }, [client]);\n}\n\nfunction useInboxNotificationThread_withClient<M extends BaseMetadata>(\n client: OpaqueClient,\n inboxNotificationId: string\n): ThreadData<M> {\n const { store } = getExtrasForClient<M>(client);\n\n const selector = useCallback(\n (state: CacheState<M>) => {\n const inboxNotification =\n state.inboxNotifications[inboxNotificationId] ??\n raise(`Inbox notification with ID \"${inboxNotificationId}\" not found`);\n\n if (inboxNotification.kind !== \"thread\") {\n raise(\n `Inbox notification with ID \"${inboxNotificationId}\" is not of kind \"thread\"`\n );\n }\n\n const thread =\n state.threads[inboxNotification.threadId] ??\n raise(\n `Thread with ID \"${inboxNotification.threadId}\" not found, this inbox notification might not be of kind \"thread\"`\n );\n\n return thread;\n },\n [inboxNotificationId]\n );\n\n return useSyncExternalStoreWithSelector(\n store.subscribe,\n store.get,\n store.get,\n selector\n );\n}\n\nfunction useCurrentUserId_withClient(client: OpaqueClient) {\n const currentUserIdStore = client[kInternal].currentUserIdStore;\n return useSyncExternalStore(\n currentUserIdStore.subscribe,\n currentUserIdStore.get,\n currentUserIdStore.get\n );\n}\n\n/**\n * @private This is an internal API.\n */\nexport function useClientOrNull() {\n return useContext(ClientContext);\n}\n\n/**\n * @beta This is an internal API for now, but it will become public eventually.\n */\n// TODO in 2.0 make public / non-beta\nexport function useClient() {\n return (\n useClientOrNull() ??\n raise(\"LiveblocksProvider is missing from the React tree.\")\n );\n}\n\n/**\n * @beta This is an internal API for now, but it will become public eventually.\n */\nexport function LiveblocksProvider(\n props: PropsWithChildren<{ client: OpaqueClient }>\n) {\n return (\n <ClientContext.Provider value={props.client}>\n {props.children}\n </ClientContext.Provider>\n );\n}\n\n/**\n * @private\n *\n * This is an internal API, use \"createLiveblocksContext\" instead.\n */\nexport function useLiveblocksContextBundleOrNull() {\n const client = useClientOrNull();\n return client !== null ? getOrCreateContextBundle(client) : null;\n}\n\n/**\n * @private\n *\n * This is an internal API, use \"createLiveblocksContext\" instead.\n */\nexport function useLiveblocksContextBundle() {\n const client = useClient();\n return getOrCreateContextBundle(client);\n}\n\nexport function createLiveblocksContext<\n U extends BaseUserMeta = DU,\n M extends BaseMetadata = never, // TODO Change this to DM for 2.0\n>(client: OpaqueClient): LiveblocksContextBundle<U, M> {\n return getOrCreateContextBundle<U, M>(client);\n}\n","const MAX_ERROR_RETRY_COUNT = 5;\n\nconst ERROR_RETRY_INTERVAL = 5000; // 5 seconds\n\n/**\n * Retries an action using the exponential backoff algorithm\n * @param action The action to retry\n * @param retryCount The number of times the action has been retried\n */\nexport function retryError(action: () => void, retryCount: number) {\n if (retryCount >= MAX_ERROR_RETRY_COUNT) return;\n\n const timeout = Math.pow(2, retryCount) * ERROR_RETRY_INTERVAL;\n\n setTimeout(() => {\n void action();\n }, timeout);\n}\n","import { useState } from \"react\";\n\n/**\n * \"Freezes\" a given value, so that it will return the same value/instance on\n * each subsequent render. This can be used to freeze \"initial\" values for\n * custom hooks, much like how `useState(initialState)` or\n * `useRef(initialValue)` works.\n */\nexport function useInitial<T>(value: T): T {\n return useState(value)[0];\n}\n","import type {\n BaseMetadata,\n BaseUserMeta,\n Client,\n Json,\n JsonObject,\n LsonObject,\n} from \"@liveblocks/client\";\nimport { kInternal, raise } from \"@liveblocks/core\";\nimport { useCallback, useEffect } from \"react\";\nimport { useSyncExternalStore } from \"use-sync-external-store/shim/index.js\";\n\nimport { useLiveblocksContextBundleOrNull } from \"./liveblocks\";\nimport { useRoomContextBundleOrNull } from \"./room\";\nimport type {\n RoomInfoState,\n RoomInfoStateSuccess,\n SharedContextBundle,\n UserState,\n UserStateSuccess,\n} from \"./types\";\n\n//\n// Default concrete types for each of the user-provided type placeholders.\n//\n\n/** DP = Default Presence type */\nexport type DP = JsonObject;\n/** DS = Default Storage type */\nexport type DS = LsonObject;\n/** DU = Default UserMeta type */\nexport type DU = BaseUserMeta;\n/** DE = Default (Room)Event type */\nexport type DE = Json;\n/** DM = Default Thread Metadata type */\nexport type DM = BaseMetadata;\n\n/**\n * @private\n *\n * This is an internal API, use `createLiveblocksContext` or `createRoomContext` instead.\n */\nexport function useSharedContextBundle() {\n const roomContextBundle = useRoomContextBundleOrNull();\n const liveblocksContextBundle = useLiveblocksContextBundleOrNull();\n\n if (roomContextBundle !== null) {\n return roomContextBundle;\n } else if (liveblocksContextBundle !== null) {\n return liveblocksContextBundle;\n } else {\n raise(\n \"LiveblocksProvider or RoomProvider are missing from the React tree.\"\n );\n }\n}\n\nconst missingUserError = new Error(\n \"resolveUsers didn't return anything for this user ID.\"\n);\nconst missingRoomInfoError = new Error(\n \"resolveRoomsInfo didn't return anything for this room ID.\"\n);\n\nfunction useUser_withClient<U extends BaseUserMeta>(\n client: Client<U>,\n userId: string\n): UserState<U[\"info\"]> {\n const usersStore = client[kInternal].usersStore;\n\n const getUserState = useCallback(\n () => usersStore.getState(userId),\n [usersStore, userId]\n );\n\n useEffect(() => {\n void usersStore.get(userId);\n }, [usersStore, userId]);\n\n const state = useSyncExternalStore(\n usersStore.subscribe,\n getUserState,\n getUserState\n );\n\n return state\n ? ({\n isLoading: state.isLoading,\n user: state.data,\n // Return an error if `undefined` was returned by `resolveUsers` for this user ID\n error:\n !state.isLoading && !state.data && !state.error\n ? missingUserError\n : state.error,\n } as UserState<U[\"info\"]>)\n : { isLoading: true };\n}\n\nfunction useUserSuspense_withClient<U extends BaseUserMeta>(\n client: Client<U>,\n userId: string\n) {\n const usersStore = client[kInternal].usersStore;\n\n const getUserState = useCallback(\n () => usersStore.getState(userId),\n [usersStore, userId]\n );\n const userState = getUserState();\n\n if (!userState || userState.isLoading) {\n throw usersStore.get(userId);\n }\n\n if (userState.error) {\n throw userState.error;\n }\n\n // Throw an error if `undefined` was returned by `resolveUsers` for this user ID\n if (!userState.data) {\n throw missingUserError;\n }\n\n const state = useSyncExternalStore(\n usersStore.subscribe,\n getUserState,\n getUserState\n );\n\n return {\n isLoading: false,\n user: state?.data,\n error: state?.error,\n } as UserStateSuccess<U[\"info\"]>;\n}\n\nfunction useRoomInfo_withClient(client: Client, roomId: string): RoomInfoState {\n const roomsInfoStore = client[kInternal].roomsInfoStore;\n\n const getRoomInfoState = useCallback(\n () => roomsInfoStore.getState(roomId),\n [roomsInfoStore, roomId]\n );\n\n useEffect(() => {\n void roomsInfoStore.get(roomId);\n }, [roomsInfoStore, roomId]);\n\n const state = useSyncExternalStore(\n roomsInfoStore.subscribe,\n getRoomInfoState,\n getRoomInfoState\n );\n\n return state\n ? ({\n isLoading: state.isLoading,\n info: state.data,\n // Return an error if `undefined` was returned by `resolveRoomsInfo` for this room ID\n error:\n !state.isLoading && !state.data && !state.error\n ? missingRoomInfoError\n : state.error,\n } as RoomInfoState)\n : { isLoading: true };\n}\n\nfunction useRoomInfoSuspense_withClient(client: Client, roomId: string) {\n const roomsInfoStore = client[kInternal].roomsInfoStore;\n\n const getRoomInfoState = useCallback(\n () => roomsInfoStore.getState(roomId),\n [roomsInfoStore, roomId]\n );\n const roomInfoState = getRoomInfoState();\n\n if (!roomInfoState || roomInfoState.isLoading) {\n throw roomsInfoStore.get(roomId);\n }\n\n if (roomInfoState.error) {\n throw roomInfoState.error;\n }\n\n // Throw an error if `undefined` was returned by `resolveRoomsInfo` for this room ID\n if (!roomInfoState.data) {\n throw missingRoomInfoError;\n }\n\n const state = useSyncExternalStore(\n roomsInfoStore.subscribe,\n getRoomInfoState,\n getRoomInfoState\n );\n\n return {\n isLoading: false,\n info: state?.data,\n error: state?.error,\n } as RoomInfoStateSuccess;\n}\n\nexport function createSharedContext<U extends BaseUserMeta>(\n client: Client<U>\n): SharedContextBundle<U> {\n return {\n classic: {\n useUser: (userId: string) => useUser_withClient(client, userId),\n useRoomInfo: (roomId: string) => useRoomInfo_withClient(client, roomId),\n },\n suspense: {\n useUser: (userId: string) => useUserSuspense_withClient(client, userId),\n useRoomInfo: (roomId: string) =>\n useRoomInfoSuspense_withClient(client, roomId),\n },\n };\n}\n","import type {\n BaseMetadata,\n BaseUserMeta,\n BroadcastOptions,\n Client,\n History,\n Json,\n JsonObject,\n LiveObject,\n LostConnectionEvent,\n LsonObject,\n OthersEvent,\n Room,\n Status,\n User,\n} from \"@liveblocks/client\";\nimport { shallow } from \"@liveblocks/client\";\nimport type {\n CacheState,\n CacheStore,\n CommentBody,\n CommentData,\n CommentsEventServerMsg,\n EnterOptions,\n LiveblocksError,\n OptionalPromise,\n PrivateRoomApi,\n ResolveMentionSuggestionsArgs,\n ResolveUsersArgs,\n RoomEventMessage,\n RoomNotificationSettings,\n ThreadData,\n ToImmutable,\n} from \"@liveblocks/core\";\nimport {\n addReaction,\n CommentsApiError,\n console,\n deleteComment,\n deprecateIf,\n errorIf,\n isLiveNode,\n kInternal,\n makeEventSource,\n makePoller,\n NotificationsApiError,\n removeReaction,\n ServerMsgCode,\n stringify,\n upsertComment,\n} from \"@liveblocks/core\";\nimport { nanoid } from \"nanoid\";\nimport * as React from \"react\";\nimport { useSyncExternalStoreWithSelector } from \"use-sync-external-store/shim/with-selector.js\";\n\nimport {\n AddReactionError,\n type CommentsError,\n CreateCommentError,\n CreateThreadError,\n DeleteCommentError,\n EditCommentError,\n EditThreadMetadataError,\n MarkInboxNotificationAsReadError,\n RemoveReactionError,\n UpdateNotificationSettingsError,\n} from \"./comments/errors\";\nimport { retryError } from \"./lib/retry-error\";\nimport { useInitial } from \"./lib/use-initial\";\nimport { useLatest } from \"./lib/use-latest\";\nimport { useRerender } from \"./lib/use-rerender\";\nimport { LiveblocksProvider, useClient, useClientOrNull } from \"./liveblocks\";\nimport type { DP, DS, DU } from \"./shared\";\nimport { createSharedContext } from \"./shared\";\nimport type {\n CommentReactionOptions,\n ComposerFocusCallback,\n CreateCommentOptions,\n DeleteCommentOptions,\n EditCommentOptions,\n EditThreadMetadataOptions,\n IsThreadActiveCallback,\n MutationContext,\n OmitFirstArg,\n RoomContextBundle,\n RoomNotificationSettingsState,\n RoomNotificationSettingsStateSuccess,\n RoomProviderProps,\n ThreadCreateCallback,\n ThreadsState,\n ThreadsStateSuccess,\n ThreadSubscription,\n UseThreadsOptions,\n} from \"./types\";\nimport { useScrollToCommentOnLoadEffect } from \"./use-scroll-to-comment-on-load-effect\";\n\nconst ThreadCreateCallbackContext =\n React.createContext<null | ThreadCreateCallback>(null);\n\nconst ThreadDeleteCallbackContext = React.createContext<\n null | ((threadId: string) => void)\n>(null);\n\nconst ComposerFocusCallbackContext =\n React.createContext<null | ComposerFocusCallback>(null);\n\nconst IsThreadActiveCallbackContext =\n React.createContext<null | IsThreadActiveCallback>(null);\n\ntype CreateThreadOptions<M extends BaseMetadata> = [M] extends [never]\n ? {\n body: CommentBody;\n }\n : { body: CommentBody; metadata: M };\n\nconst noop = () => {};\nconst identity: <T>(x: T) => T = (x) => x;\n\nconst missing_unstable_batchedUpdates = (\n reactVersion: number,\n roomId: string\n) =>\n `We noticed you’re using React ${reactVersion}. Please pass unstable_batchedUpdates at the RoomProvider level until you’re ready to upgrade to React 18:\n\n import { unstable_batchedUpdates } from \"react-dom\"; // or \"react-native\"\n\n <RoomProvider id=${JSON.stringify(\n roomId\n )} ... unstable_batchedUpdates={unstable_batchedUpdates}>\n ...\n </RoomProvider>\n\nWhy? Please see https://liveblocks.io/docs/platform/troubleshooting#stale-props-zombie-child for more information`;\n\nconst superfluous_unstable_batchedUpdates =\n \"You don’t need to pass unstable_batchedUpdates to RoomProvider anymore, since you’re on React 18+ already.\";\n\nfunction useSyncExternalStore<Snapshot>(\n s: (onStoreChange: () => void) => () => void,\n gs: () => Snapshot,\n gss: undefined | null | (() => Snapshot)\n): Snapshot {\n return useSyncExternalStoreWithSelector(s, gs, gss, identity);\n}\n\nconst STABLE_EMPTY_LIST = Object.freeze([]);\n\nexport const POLLING_INTERVAL = 5 * 60 * 1000; // 5 minutes\n\nconst MENTION_SUGGESTIONS_DEBOUNCE = 500;\n\nfunction makeNotificationSettingsQueryKey(roomId: string) {\n return `${roomId}:NOTIFICATION_SETTINGS`;\n}\n\n// Don't try to inline this. This function is intended to be a stable\n// reference, to avoid a React.useCallback() wrapper.\nfunction alwaysEmptyList() {\n return STABLE_EMPTY_LIST;\n}\n\n// Don't try to inline this. This function is intended to be a stable\n// reference, to avoid a React.useCallback() wrapper.\nfunction alwaysNull() {\n return null;\n}\n\nfunction selectorFor_useOthersConnectionIds(\n others: readonly User<JsonObject, BaseUserMeta>[]\n): number[] {\n return others.map((user) => user.connectionId);\n}\n\nfunction makeMutationContext<\n P extends JsonObject,\n S extends LsonObject,\n U extends BaseUserMeta,\n E extends Json,\n>(room: Room<P, S, U, E>): MutationContext<P, S, U> {\n const cannotUseUntil = \"This mutation cannot be used until\";\n const needsPresence = `${cannotUseUntil} connected to the Liveblocks room`;\n const needsStorage = `${cannotUseUntil} storage has been loaded`;\n\n return {\n get storage() {\n const mutableRoot = room.getStorageSnapshot();\n if (mutableRoot === null) {\n throw new Error(needsStorage);\n }\n return mutableRoot;\n },\n\n get self() {\n const self = room.getSelf();\n if (self === null) {\n throw new Error(needsPresence);\n }\n return self;\n },\n\n get others() {\n const others = room.getOthers();\n if (room.getSelf() === null) {\n throw new Error(needsPresence);\n }\n return others;\n },\n\n setMyPresence: room.updatePresence,\n };\n}\n\nfunction getCurrentUserId(\n room: Room<JsonObject, LsonObject, BaseUserMeta, Json>\n): string {\n const self = room.getSelf();\n if (self === null || self.id === undefined) {\n return \"anonymous\";\n } else {\n return self.id;\n }\n}\n\nfunction handleApiError(err: CommentsApiError | NotificationsApiError): Error {\n const message = `Request failed with status ${err.status}: ${err.message}`;\n\n // Log details about FORBIDDEN errors\n if (err.details?.error === \"FORBIDDEN\") {\n const detailedMessage = [message, err.details.suggestion, err.details.docs]\n .filter(Boolean)\n .join(\"\\n\");\n\n console.error(detailedMessage);\n }\n\n return new Error(message);\n}\n\nconst _extras = new WeakMap<\n OpaqueClient,\n ReturnType<typeof makeExtrasForClient>\n>();\nconst _bundles = new WeakMap<\n OpaqueClient,\n RoomContextBundle<JsonObject, LsonObject, BaseUserMeta, Json, BaseMetadata>\n>();\n\nfunction getOrCreateRoomContextBundle<\n P extends JsonObject,\n S extends LsonObject,\n U extends BaseUserMeta,\n E extends Json,\n M extends BaseMetadata,\n>(client: OpaqueClient): RoomContextBundle<P, S, U, E, M> {\n let bundle = _bundles.get(client);\n if (!bundle) {\n bundle = makeRoomContextBundle(client);\n _bundles.set(client, bundle);\n }\n return bundle as unknown as RoomContextBundle<P, S, U, E, M>;\n}\n\n// TODO: Likely a better / more clear name for this helper will arise. I'll\n// rename this later. All of these are implementation details to support inbox\n// notifications on a per-client basis.\nfunction getExtrasForClient<M extends BaseMetadata>(client: OpaqueClient) {\n let extras = _extras.get(client);\n if (!extras) {\n extras = makeExtrasForClient(client);\n _extras.set(client, extras);\n }\n\n return extras as unknown as Omit<typeof extras, \"store\"> & {\n store: CacheStore<M>;\n };\n}\n\nfunction makeExtrasForClient<M extends BaseMetadata>(client: OpaqueClient) {\n const store = client[kInternal].cacheStore as unknown as CacheStore<M>;\n\n const DEFAULT_DEDUPING_INTERVAL = 2000; // 2 seconds\n\n const lastRequestedAtByRoom = new Map<string, Date>(); // A map of room ids to the timestamp when the last request for threads updates was made\n const requestsByQuery = new Map<string, Promise<unknown>>(); // A map of query keys to the promise of the request for that query\n const requestStatusByRoom = new Map<string, boolean>(); // A map of room ids to a boolean indicating whether a request to retrieve threads updates is in progress\n const subscribersByQuery = new Map<string, number>(); // A map of query keys to the number of subscribers for that query\n const mentionSuggestionsCache = new Map<string, string[]>();\n\n const poller = makePoller(refreshThreadsAndNotifications);\n\n async function refreshThreadsAndNotifications() {\n const requests: Promise<unknown>[] = [];\n\n client[kInternal].getRoomIds().map((roomId) => {\n const room = client.getRoom(roomId);\n if (room === null) return;\n\n // Retrieve threads that have been updated/deleted since the last requestedAt value\n requests.push(getThreadsUpdates(room.id));\n });\n\n await Promise.allSettled(requests);\n }\n\n function incrementQuerySubscribers(queryKey: string) {\n const subscribers = subscribersByQuery.get(queryKey) ?? 0;\n subscribersByQuery.set(queryKey, subscribers + 1);\n\n poller.start(POLLING_INTERVAL);\n\n // Decrement in the unsub function\n return () => {\n const subscribers = subscribersByQuery.get(queryKey);\n\n if (subscribers === undefined || subscribers <= 0) {\n console.warn(\n `Internal unexpected behavior. Cannot decrease subscriber count for query \"${queryKey}\"`\n );\n return;\n }\n\n subscribersByQuery.set(queryKey, subscribers - 1);\n\n let totalSubscribers = 0;\n for (const subscribers of subscribersByQuery.values()) {\n totalSubscribers += subscribers;\n }\n\n if (totalSubscribers <= 0) {\n poller.stop();\n }\n };\n }\n\n /**\n * Retrieve threads that have been updated/deleted since the last time the room requested threads updates and update the local cache with the new data\n * @param roomId The id of the room for which to retrieve threads updates\n */\n async function getThreadsUpdates(roomId: string) {\n const room = client.getRoom(roomId);\n if (room === null) return;\n\n const since = lastRequestedAtByRoom.get(room.id);\n if (since === undefined) return;\n\n const isFetchingThreadsUpdates = requestStatusByRoom.get(room.id) ?? false;\n // If another request to retrieve threads updates for the room is in progress, we do not start a new one\n if (isFetchingThreadsUpdates === true) return;\n\n try {\n // Set the isFetchingThreadsUpdates flag to true to prevent multiple requests to fetch threads updates for the room from being made at the same time\n requestStatusByRoom.set(room.id, true);\n const updates = await room[kInternal].comments.getThreads({ since });\n\n // Set the isFetchingThreadsUpdates flag to false after a certain interval to prevent multiple requests from being made at the same time\n setTimeout(() => {\n requestStatusByRoom.set(room.id, false);\n }, DEFAULT_DEDUPING_INTERVAL);\n\n store.updateThreadsAndNotifications(\n updates.threads,\n updates.inboxNotifications,\n updates.deletedThreads,\n updates.deletedInboxNotifications\n );\n\n // Update the `lastRequestedAt` value for the room to the timestamp returned by the current request\n lastRequestedAtByRoom.set(room.id, updates.meta.requestedAt);\n } catch (err) {\n requestStatusByRoom.set(room.id, false);\n // TODO: Implement error handling\n return;\n }\n }\n\n async function getThreadsAndInboxNotifications(\n room: Room<JsonObject, LsonObject, BaseUserMeta, Json>,\n queryKey: string,\n options: UseThreadsOptions<M>,\n { retryCount }: { retryCount: number } = { retryCount: 0 }\n ) {\n const existingRequest = requestsByQuery.get(queryKey);\n\n // If a request was already made for the query, we do not make another request and return the existing promise of the request\n if (existingRequest !== undefined) return existingRequest;\n\n const commentsAPI = (room[kInternal] as PrivateRoomApi<M>).comments;\n const request = commentsAPI.getThreads(options);\n\n // Store the promise of the request for the query so that we do not make another request for the same query\n requestsByQuery.set(queryKey, request);\n\n store.setQueryState(queryKey, {\n isLoading: true,\n });\n\n try {\n const result = await request;\n\n store.updateThreadsAndNotifications(\n result.threads,\n result.inboxNotifications,\n result.deletedThreads,\n result.deletedInboxNotifications,\n queryKey\n );\n\n const lastRequestedAt = lastRequestedAtByRoom.get(room.id);\n\n /**\n * We set the `lastRequestedAt` value for the room to the timestamp returned by the current request if:\n * 1. The `lastRequestedAt` value for the room has not been set\n * OR\n * 2. The `lastRequestedAt` value for the room is older than the timestamp returned by the current request\n */\n if (\n lastRequestedAt === undefined ||\n lastRequestedAt > result.meta.requestedAt\n ) {\n lastRequestedAtByRoom.set(room.id, result.meta.requestedAt);\n }\n\n poller.start(POLLING_INTERVAL);\n } catch (err) {\n requestsByQuery.delete(queryKey);\n\n // Retry the action using the exponential backoff algorithm\n retryError(() => {\n void getThreadsAndInboxNotifications(room, queryKey, options, {\n retryCount: retryCount + 1,\n });\n }, retryCount);\n\n // Set the query state to the error state\n store.setQueryState(queryKey, {\n isLoading: false,\n error: err as Error,\n });\n }\n return;\n }\n\n async function getInboxNotificationSettings(\n room: Room<JsonObject, LsonObject, BaseUserMeta, Json>,\n queryKey: string,\n { retryCount }: { retryCount: number } = { retryCount: 0 }\n ) {\n const existingRequest = requestsByQuery.get(queryKey);\n\n // If a request was already made for the notifications query, we do not make another request and return the existing promise\n if (existingRequest !== undefined) return existingRequest;\n\n try {\n const request =\n room[kInternal].notifications.getRoomNotificationSettings();\n\n requestsByQuery.set(queryKey, request);\n\n store.setQueryState(queryKey, {\n isLoading: true,\n });\n\n const settings = await request;\n store.updateRoomInboxNotificationSettings(room.id, settings, queryKey);\n } catch (err) {\n requestsByQuery.delete(queryKey);\n\n retryError(() => {\n void getInboxNotificationSettings(room, queryKey, {\n retryCount: retryCount + 1,\n });\n }, retryCount);\n\n store.setQueryState(queryKey, {\n isLoading: false,\n error: err as Error,\n });\n }\n return;\n }\n\n const commentsErrorEventSource = makeEventSource<CommentsError<M>>();\n\n function onMutationFailure(\n innerError: Error,\n optimisticUpdateId: string,\n createPublicError: (error: Error) => CommentsError<M>\n ) {\n store.set((state) => ({\n ...state,\n optimisticUpdates: state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n ),\n }));\n\n if (innerError instanceof CommentsApiError) {\n const error = handleApiError(innerError);\n commentsErrorEventSource.notify(createPublicError(error));\n return;\n }\n\n if (innerError instanceof NotificationsApiError) {\n handleApiError(innerError);\n // TODO: Create public error and notify via notificationsErrorEventSource?\n return;\n }\n\n throw innerError;\n }\n\n /** @internal */\n // Simplistic debounced search, we don't need to worry too much about\n // deduping and race conditions as there can only be one search at a time.\n function useMentionSuggestions(search?: string) {\n const room = useRoom();\n const [mentionSuggestions, setMentionSuggestions] =\n React.useState<string[]>();\n const lastInvokedAt = React.useRef<number>();\n\n React.useEffect(() => {\n const resolveMentionSuggestions =\n client[kInternal].resolveMentionSuggestions;\n\n if (search === undefined || !resolveMentionSuggestions) {\n return;\n }\n\n const resolveMentionSuggestionsArgs = { text: search, roomId: room.id };\n const mentionSuggestionsCacheKey = stringify(\n resolveMentionSuggestionsArgs\n );\n let debounceTimeout: number | undefined;\n let isCanceled = false;\n\n const getMentionSuggestions = async () => {\n try {\n lastInvokedAt.current = performance.now();\n const mentionSuggestions = await resolveMentionSuggestions(\n resolveMentionSuggestionsArgs\n );\n\n if (!isCanceled) {\n setMentionSuggestions(mentionSuggestions);\n mentionSuggestionsCache.set(\n mentionSuggestionsCacheKey,\n mentionSuggestions\n );\n }\n } catch (error) {\n console.error((error as Error)?.message);\n }\n };\n\n if (mentionSuggestionsCache.has(mentionSuggestionsCacheKey)) {\n // If there are already cached mention suggestions, use them immediately.\n setMentionSuggestions(\n mentionSuggestionsCache.get(mentionSuggestionsCacheKey)\n );\n } else if (\n !lastInvokedAt.current ||\n Math.abs(performance.now() - lastInvokedAt.current) >\n MENTION_SUGGESTIONS_DEBOUNCE\n ) {\n // If on the debounce's leading edge (either because it's the first invokation or enough\n // time has passed since the last debounce), get mention suggestions immediately.\n void getMentionSuggestions();\n } else {\n // Otherwise, wait for the debounce delay.\n debounceTimeout = window.setTimeout(() => {\n void getMentionSuggestions();\n }, MENTION_SUGGESTIONS_DEBOUNCE);\n }\n\n return () => {\n isCanceled = true;\n window.clearTimeout(debounceTimeout);\n };\n }, [room.id, search]);\n\n return mentionSuggestions;\n }\n\n return {\n store,\n incrementQuerySubscribers,\n commentsErrorEventSource,\n getThreadsUpdates,\n getThreadsAndInboxNotifications,\n getInboxNotificationSettings,\n useMentionSuggestions,\n onMutationFailure,\n };\n}\n\ntype OpaqueClient = Client<BaseUserMeta>;\ntype OpaqueRoom = Room<JsonObject, LsonObject, BaseUserMeta, Json>;\n\ntype RoomLeavePair<\n P extends JsonObject,\n S extends LsonObject,\n U extends BaseUserMeta,\n E extends Json,\n> = {\n room: Room<P, S, U, E>;\n leave: () => void;\n};\n\nconst RoomContext = React.createContext<OpaqueRoom | null>(null);\n\nfunction makeRoomContextBundle<\n P extends JsonObject,\n S extends LsonObject,\n U extends BaseUserMeta,\n E extends Json,\n M extends BaseMetadata,\n>(client: Client<U>): RoomContextBundle<P, S, U, E, M> {\n type TRoom = Room<P, S, U, E>;\n\n function RoomProvider_withImplicitLiveblocksProvider(\n props: RoomProviderProps<P, S>\n ) {\n return (\n <LiveblocksProvider client={client}>\n <RoomProvider {...props} />\n </LiveblocksProvider>\n );\n }\n\n // Bind to typed hooks\n const { useMentionSuggestions } = getExtrasForClient<M>(client);\n\n const shared = createSharedContext<U>(client);\n\n const bundle: RoomContextBundle<P, S, U, E, M> = {\n RoomContext: RoomContext as React.Context<TRoom | null>,\n RoomProvider: RoomProvider_withImplicitLiveblocksProvider,\n\n useRoom: useRoom<P, S, U, E>,\n useStatus,\n\n useBatch,\n useBroadcastEvent: useBroadcastEvent<E>,\n useOthersListener: useOthersListener<P, U>,\n useLostConnectionListener,\n useErrorListener,\n useEventListener: useEventListener<P, U, E>,\n\n useHistory,\n useUndo,\n useRedo,\n useCanRedo,\n useCanUndo,\n\n // These are just aliases. The passed-in key will define their return values.\n useList: useLegacyKey,\n useMap: useLegacyKey,\n useObject: useLegacyKey,\n\n useStorageRoot: useStorageRoot<S>,\n useStorage: make_useStorage<S>(),\n\n useSelf: useSelf<P, U>,\n useMyPresence: useMyPresence<P>,\n useUpdateMyPresence: useUpdateMyPresence<P>,\n useOthers: useOthers<P, U>,\n useOthersMapped: make_useOthersMapped<P, U>(),\n useOthersConnectionIds,\n useOther: make_useOther<P, U>(),\n\n useMutation: make_useMutation<P, S, U, E>(),\n\n useThreads: useThreads<M>,\n\n useCreateThread: useCreateThread<M>,\n useEditThreadMetadata: useEditThreadMetadata<M>,\n useCreateComment,\n useEditComment,\n useDeleteComment,\n useAddReaction: useAddReaction<M>,\n useRemoveReaction,\n useMarkThreadAsRead,\n useThreadSubscription,\n\n useRoomNotificationSettings,\n useUpdateRoomNotificationSettings,\n\n ...shared.classic,\n\n suspense: {\n RoomContext: RoomContext as React.Context<TRoom | null>,\n RoomProvider: RoomProvider_withImplicitLiveblocksProvider,\n\n useRoom: useRoom<P, S, U, E>,\n useStatus,\n\n useBatch,\n useBroadcastEvent: useBroadcastEvent<E>,\n useOthersListener: useOthersListener<P, U>,\n useLostConnectionListener,\n useErrorListener,\n useEventListener: useEventListener<P, U, E>,\n\n useHistory,\n useUndo,\n useRedo,\n useCanRedo,\n useCanUndo,\n\n // Legacy hooks\n useList: useLegacyKeySuspense,\n useMap: useLegacyKeySuspense,\n useObject: useLegacyKeySuspense,\n\n useStorageRoot: useStorageRoot<S>,\n useStorage: make_useStorageSuspense<S>(),\n\n useSelf: useSelfSuspense<P, U>,\n useMyPresence: useMyPresence<P>,\n useUpdateMyPresence: useUpdateMyPresence<P>,\n useOthers: make_useOthersSuspense<P, U>(),\n useOthersMapped: make_useOthersMappedSuspense<P, U>(),\n useOthersConnectionIds: useOthersConnectionIdsSuspense,\n useOther: make_useOtherSuspense<P, U>(),\n\n useMutation: make_useMutation<P, S, U, E>(),\n\n useThreads: useThreadsSuspense<M>,\n\n useCreateThread: useCreateThread<M>,\n useEditThreadMetadata: useEditThreadMetadata<M>,\n useCreateComment,\n useEditComment,\n useDeleteComment,\n useAddReaction: useAddReaction<M>,\n useRemoveReaction,\n useMarkThreadAsRead,\n useThreadSubscription,\n\n useRoomNotificationSettings: useRoomNotificationSettingsSuspense,\n useUpdateRoomNotificationSettings,\n\n ...shared.suspense,\n },\n\n [kInternal]: {\n useCurrentUserId,\n useMentionSuggestions,\n useCommentsErrorListener,\n ThreadCreateCallbackProvider: ThreadCreateCallbackContext.Provider,\n useThreadCreateCallback,\n ThreadDeleteCallbackProvider: ThreadDeleteCallbackContext.Provider,\n useThreadDeleteCallback: useThreadDeleteCallback,\n ComposerFocusCallbackProvider: ComposerFocusCallbackContext.Provider,\n useComposerFocusCallback: useComposerFocusCallback,\n IsThreadActiveCallbackProvider: IsThreadActiveCallbackContext.Provider,\n useIsThreadActiveCallback: useIsThreadActiveCallback,\n },\n };\n\n return Object.defineProperty(bundle, kInternal, {\n enumerable: false,\n });\n}\n\nfunction RoomProvider<\n P extends JsonObject,\n S extends LsonObject,\n U extends BaseUserMeta,\n E extends Json,\n>(props: RoomProviderProps<P, S>) {\n const client = useClient();\n const [cache] = React.useState(\n () => new Map<string, RoomLeavePair<P, S, U, E>>()\n );\n\n // Produce a version of client.enterRoom() that when called for the same\n // room ID multiple times, will not keep producing multiple leave\n // functions, but instead return the cached one.\n const stableEnterRoom = React.useCallback(\n (\n roomId: string,\n options: EnterOptions<P, S>\n ): RoomLeavePair<P, S, U, E> => {\n const cached = cache.get(roomId);\n if (cached) return cached;\n\n const rv = client.enterRoom<P, S, U, E>(roomId, options);\n\n // Wrap the leave function to also delete the cached value\n const origLeave = rv.leave;\n rv.leave = () => {\n origLeave();\n cache.delete(roomId);\n };\n\n cache.set(roomId, rv);\n return rv;\n },\n [client, cache]\n );\n\n //\n // RATIONALE:\n // At the \"Outer\" RoomProvider level, we keep a cache and produce\n // a stableEnterRoom function, which we pass down to the real \"Inner\"\n // RoomProvider level.\n //\n // The purpose is to ensure that if `stableEnterRoom(\"my-room\")` is called\n // multiple times for the same room ID, it will always return the exact same\n // (cached) value, so that in total only a single \"leave\" function gets\n // produced and registered in the client.\n //\n // If we didn't use this cache, then in React StrictMode\n // stableEnterRoom(\"my-room\") might get called multiple (at least 4) times,\n // causing more leave functions to be produced in the client, some of which\n // we cannot get a hold on (because StrictMode would discard those results by\n // design). This would make it appear to the Client that the Room is still in\n // use by some party that hasn't called `leave()` on it yet, thus causing the\n // Room to not be freed and destroyed when the component unmounts later.\n //\n return <RoomProviderInner {...props} stableEnterRoom={stableEnterRoom} />;\n}\n\n/** @internal */\nfunction RoomProviderInner<\n P extends JsonObject,\n S extends LsonObject,\n U extends BaseUserMeta,\n E extends Json,\n>(\n props: RoomProviderProps<P, S> & {\n stableEnterRoom: (\n roomId: string,\n options: EnterOptions<P, S>\n ) => RoomLeavePair<P, S, U, E>;\n }\n) {\n const client = useClient();\n const { id: roomId, stableEnterRoom } = props;\n\n if (process.env.NODE_ENV !== \"production\") {\n if (!roomId) {\n throw new Error(\n \"RoomProvider id property is required. For more information: https://liveblocks.io/docs/errors/liveblocks-react/RoomProvider-id-property-is-required\"\n );\n }\n\n if (typeof roomId !== \"string\") {\n throw new Error(\"RoomProvider id property should be a string.\");\n }\n\n const majorReactVersion = parseInt(React.version) || 1;\n const oldReactVersion = majorReactVersion < 18;\n errorIf(\n oldReactVersion && props.unstable_batchedUpdates === undefined,\n missing_unstable_batchedUpdates(majorReactVersion, roomId)\n );\n deprecateIf(\n !oldReactVersion && props.unstable_batchedUpdates !== undefined,\n superfluous_unstable_batchedUpdates\n );\n }\n\n // Note: We'll hold on to the initial value given here, and ignore any\n // changes to this argument in subsequent renders\n const frozenProps = useInitial({\n initialPresence: props.initialPresence,\n initialStorage: props.initialStorage,\n unstable_batchedUpdates: props.unstable_batchedUpdates,\n autoConnect:\n props.autoConnect ??\n props.shouldInitiallyConnect ??\n typeof window !== \"undefined\",\n });\n\n const [{ room }, setRoomLeavePair] = React.useState(() =>\n stableEnterRoom(roomId, {\n ...frozenProps,\n autoConnect: false, // Deliberately using false here on the first render, see below\n })\n );\n\n React.useEffect(() => {\n const { store } = getExtrasForClient(client);\n\n async function handleCommentEvent(message: CommentsEventServerMsg) {\n // TODO: Error handling\n const info = await room[kInternal].comments.getThread({\n threadId: message.threadId,\n });\n\n // If no thread info was returned (i.e., 404), we remove the thread and relevant inbox notifications from local cache.\n if (!info) {\n store.deleteThread(message.threadId);\n return;\n }\n const { thread, inboxNotification } = info;\n\n const existingThread = store.get().threads[message.threadId];\n\n switch (message.type) {\n case ServerMsgCode.COMMENT_EDITED:\n case ServerMsgCode.THREAD_METADATA_UPDATED:\n case ServerMsgCode.COMMENT_REACTION_ADDED:\n case ServerMsgCode.COMMENT_REACTION_REMOVED:\n case ServerMsgCode.COMMENT_DELETED:\n // If the thread doesn't exist in the local cache, we do not update it with the server data as an optimistic update could have deleted the thread locally.\n if (!existingThread) break;\n\n store.updateThreadAndNotification(thread, inboxNotification);\n break;\n case ServerMsgCode.COMMENT_CREATED:\n store.updateThreadAndNotification(thread, inboxNotification);\n break;\n default:\n break;\n }\n }\n\n return room.events.comments.subscribe(\n (message) => void handleCommentEvent(message)\n );\n }, [client, room]);\n\n React.useEffect(() => {\n const { getThreadsUpdates } = getExtrasForClient(client);\n // Retrieve threads that have been updated/deleted since the last time the room requested threads updates\n void getThreadsUpdates(room.id);\n }, [client, room.id]);\n\n /**\n * Subscribe to the 'online' event to fetch threads/notifications updates when the browser goes back online.\n */\n React.useEffect(() => {\n function handleIsOnline() {\n const { getThreadsUpdates } = getExtrasForClient(client);\n void getThreadsUpdates(room.id);\n }\n\n window.addEventListener(\"online\", handleIsOnline);\n return () => {\n window.removeEventListener(\"online\", handleIsOnline);\n };\n }, [client, room.id]);\n\n React.useEffect(() => {\n const pair = stableEnterRoom(roomId, frozenProps);\n\n setRoomLeavePair(pair);\n const { room, leave } = pair;\n\n // In React, it's important to start connecting to the room as an effect,\n // rather than doing this during the initial render. This means that\n // during the initial render (both on the server-side, and on the first\n // hydration on the client-side), the value of the `useStatus()` hook\n // will correctly be \"initial\", and transition to \"connecting\" as an\n // effect.\n if (frozenProps.autoConnect) {\n room.connect();\n }\n\n return () => {\n leave();\n };\n }, [roomId, frozenProps, stableEnterRoom]);\n\n return (\n <RoomContext.Provider value={room}>{props.children}</RoomContext.Provider>\n );\n}\n\nfunction useRoom<\n P extends JsonObject = never,\n S extends LsonObject = never,\n U extends BaseUserMeta = never,\n E extends Json = never,\n>(): Room<P, S, U, E> {\n const room = React.useContext(RoomContext);\n if (room === null) {\n throw new Error(\"RoomProvider is missing from the React tree.\");\n }\n return room as Room<P, S, U, E>;\n}\n\nfunction useStatus(): Status {\n const room = useRoom();\n const subscribe = room.events.status.subscribe;\n const getSnapshot = room.getStatus;\n const getServerSnapshot = room.getStatus;\n return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);\n}\n\nfunction useBatch<T>(): (callback: () => T) => T {\n return useRoom().batch;\n}\n\nfunction useBroadcastEvent<E extends Json>(): (\n event: E,\n options?: BroadcastOptions\n) => void {\n const room = useRoom<never, never, never, E>();\n return React.useCallback(\n (\n event: E,\n options: BroadcastOptions = { shouldQueueEventIfNotReady: false }\n ) => {\n room.broadcastEvent(event, options);\n },\n [room]\n );\n}\n\nfunction useOthersListener<P extends JsonObject, U extends BaseUserMeta>(\n callback: (event: OthersEvent<P, U>) => void\n) {\n const room = useRoom<P, never, U, never>();\n const savedCallback = useLatest(callback);\n React.useEffect(\n () => room.events.others.subscribe((event) => savedCallback.current(event)),\n [room, savedCallback]\n );\n}\n\nfunction useLostConnectionListener(\n callback: (event: LostConnectionEvent) => void\n): void {\n const room = useRoom();\n const savedCallback = useLatest(callback);\n React.useEffect(\n () =>\n room.events.lostConnection.subscribe((event) =>\n savedCallback.current(event)\n ),\n [room, savedCallback]\n );\n}\n\nfunction useErrorListener(callback: (err: LiveblocksError) => void): void {\n const room = useRoom();\n const savedCallback = useLatest(callback);\n React.useEffect(\n () => room.events.error.subscribe((e) => savedCallback.current(e)),\n [room, savedCallback]\n );\n}\n\nfunction useEventListener<\n P extends JsonObject,\n U extends BaseUserMeta,\n E extends Json,\n>(callback: (data: RoomEventMessage<P, U, E>) => void): void {\n const room = useRoom<P, never, U, E>();\n const savedCallback = useLatest(callback);\n React.useEffect(() => {\n const listener = (eventData: RoomEventMessage<P, U, E>) => {\n savedCallback.current(eventData);\n };\n\n return room.events.customEvent.subscribe(listener);\n }, [room, savedCallback]);\n}\n\nfunction useHistory(): History {\n return useRoom().history;\n}\n\nfunction useUndo(): () => void {\n return useHistory().undo;\n}\n\nfunction useRedo(): () => void {\n return useHistory().redo;\n}\n\nfunction useCanUndo(): boolean {\n const room = useRoom();\n const subscribe = room.events.history.subscribe;\n const canUndo = room.history.canUndo;\n return useSyncExternalStore(subscribe, canUndo, canUndo);\n}\n\nfunction useCanRedo(): boolean {\n const room = useRoom();\n const subscribe = room.events.history.subscribe;\n const canRedo = room.history.canRedo;\n return useSyncExternalStore(subscribe, canRedo, canRedo);\n}\n\nfunction useSelf<P extends JsonObject, U extends BaseUserMeta>(): User<\n P,\n U\n> | null;\nfunction useSelf<T, P extends JsonObject, U extends BaseUserMeta>(\n selector: (me: User<P, U>) => T,\n isEqual?: (prev: T | null, curr: T | null) => boolean\n): T | null;\nfunction useSelf<T, P extends JsonObject, U extends BaseUserMeta>(\n maybeSelector?: (me: User<P, U>) => T,\n isEqual?: (prev: T | null, curr: T | null) => boolean\n): T | User<P, U> | null {\n type Snapshot = User<P, U> | null;\n type Selection = T | null;\n\n const room = useRoom<P, never, U, never>();\n const subscribe = room.events.self.subscribe;\n const getSnapshot: () => Snapshot = room.getSelf;\n\n const selector = maybeSelector ?? (identity as (me: User<P, U>) => T);\n const wrappedSelector = React.useCallback(\n (me: Snapshot): Selection => (me !== null ? selector(me) : null),\n [selector]\n );\n\n const getServerSnapshot = alwaysNull;\n\n return useSyncExternalStoreWithSelector(\n subscribe,\n getSnapshot,\n getServerSnapshot,\n wrappedSelector,\n isEqual\n );\n}\n\nfunction useCurrentUserId() {\n return useSelf((user) => (typeof user.id === \"string\" ? user.id : null));\n}\n\nfunction useMyPresence<P extends JsonObject>(): [\n P,\n (patch: Partial<P>, options?: { addToHistory: boolean }) => void,\n] {\n const room = useRoom<P, never, never, never>();\n const subscribe = room.events.myPresence.subscribe;\n const getSnapshot = room.getPresence;\n const presence = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);\n const setPresence = room.updatePresence;\n return [presence, setPresence];\n}\n\nfunction useUpdateMyPresence<P extends JsonObject>(): (\n patch: Partial<P>,\n options?: { addToHistory: boolean }\n) => void {\n return useRoom<P, never, never, never>().updatePresence;\n}\n\nfunction useOthers<\n P extends JsonObject,\n U extends BaseUserMeta,\n>(): readonly User<P, U>[];\nfunction useOthers<T, P extends JsonObject, U extends BaseUserMeta>(\n selector: (others: readonly User<P, U>[]) => T,\n isEqual?: (prev: T, curr: T) => boolean\n): T;\nfunction useOthers<T, P extends JsonObject, U extends BaseUserMeta>(\n selector?: (others: readonly User<P, U>[]) => T,\n isEqual?: (prev: T, curr: T) => boolean\n): T | readonly User<P, U>[] {\n const room = useRoom<P, never, U, never>();\n const subscribe = room.events.others.subscribe;\n const getSnapshot = room.getOthers;\n const getServerSnapshot = alwaysEmptyList;\n return useSyncExternalStoreWithSelector(\n subscribe,\n getSnapshot,\n getServerSnapshot,\n selector ?? (identity as (others: readonly User<P, U>[]) => T),\n isEqual\n );\n}\n\nfunction make_useOthersMapped<P extends JsonObject, U extends BaseUserMeta>() {\n return function useOthersMapped<T>(\n itemSelector: (other: User<P, U>) => T,\n itemIsEqual?: (prev: T, curr: T) => boolean\n ): ReadonlyArray<readonly [connectionId: number, data: T]> {\n const wrappedSelector = React.useCallback(\n (others: readonly User<P, U>[]) =>\n others.map(\n (other) => [other.connectionId, itemSelector(other)] as const\n ),\n [itemSelector]\n );\n\n const wrappedIsEqual = React.useCallback(\n (\n a: ReadonlyArray<readonly [connectionId: number, data: T]>,\n b: ReadonlyArray<readonly [connectionId: number, data: T]>\n ): boolean => {\n const eq = itemIsEqual ?? Object.is;\n return (\n a.length === b.length &&\n a.every((atuple, index) => {\n // We know btuple always exist because we checked the array length on the previous line\n const btuple = b[index];\n return atuple[0] === btuple[0] && eq(atuple[1], btuple[1]);\n })\n );\n },\n [itemIsEqual]\n );\n\n return useOthers(wrappedSelector, wrappedIsEqual);\n };\n}\n\nfunction useOthersConnectionIds(): readonly number[] {\n return useOthers(selectorFor_useOthersConnectionIds, shallow);\n}\n\nconst NOT_FOUND = Symbol();\n\ntype NotFound = typeof NOT_FOUND;\n\nfunction make_useOther<P extends JsonObject, U extends BaseUserMeta>() {\n return function useOther<T>(\n connectionId: number,\n selector: (other: User<P, U>) => T,\n isEqual?: (prev: T, curr: T) => boolean\n ): T {\n const wrappedSelector = React.useCallback(\n (others: readonly User<P, U>[]) => {\n // TODO: Make this O(1) instead of O(n)?\n const other = others.find(\n (other) => other.connectionId === connectionId\n );\n return other !== undefined ? selector(other) : NOT_FOUND;\n },\n [connectionId, selector]\n );\n\n const wrappedIsEqual = React.useCallback(\n (prev: T | NotFound, curr: T | NotFound): boolean => {\n if (prev === NOT_FOUND || curr === NOT_FOUND) {\n return prev === curr;\n }\n\n const eq = isEqual ?? Object.is;\n return eq(prev, curr);\n },\n [isEqual]\n );\n\n const other = useOthers(wrappedSelector, wrappedIsEqual);\n if (other === NOT_FOUND) {\n throw new Error(\n `No such other user with connection id ${connectionId} exists`\n );\n }\n\n return other;\n };\n}\n\n/** @internal */\nfunction useMutableStorageRoot<S extends LsonObject>(): LiveObject<S> | null {\n const room = useRoom<never, S, never, never>();\n const subscribe = room.events.storageDidLoad.subscribeOnce;\n const getSnapshot = room.getStorageSnapshot;\n const getServerSnapshot = alwaysNull;\n return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot);\n}\n\n// NOTE: This API exists for backward compatible reasons\nfunction useStorageRoot<S extends LsonObject>(): [root: LiveObject<S> | null] {\n return [useMutableStorageRoot<S>()];\n}\n\nfunction make_useStorage<S extends LsonObject>() {\n return function useStorage<T>(\n selector: (root: ToImmutable<S>) => T,\n isEqual?: (prev: T | null, curr: T | null) => boolean\n ): T | null {\n type Snapshot = ToImmutable<S> | null;\n type Selection = T | null;\n\n const room = useRoom<never, S, never, never>();\n const rootOrNull = useMutableStorageRoot<S>();\n\n const wrappedSelector = React.useCallback(\n (rootOrNull: Snapshot): Selection =>\n rootOrNull !== null ? selector(rootOrNull) : null,\n [selector]\n );\n\n const subscribe = React.useCallback(\n (onStoreChange: () => void) =>\n rootOrNull !== null\n ? room.subscribe(rootOrNull, onStoreChange, { isDeep: true })\n : noop,\n [room, rootOrNull]\n );\n\n const getSnapshot = React.useCallback((): Snapshot => {\n if (rootOrNull === null) {\n return null;\n } else {\n const root = rootOrNull;\n const imm = root.toImmutable();\n return imm;\n }\n }, [rootOrNull]);\n\n const getServerSnapshot = alwaysNull;\n\n return useSyncExternalStoreWithSelector(\n subscribe,\n getSnapshot,\n getServerSnapshot,\n wrappedSelector,\n isEqual\n );\n };\n}\n\nfunction useLegacyKey<\n TKey extends Extract<keyof S, string>,\n S extends LsonObject,\n>(key: TKey): S[TKey] | null {\n const room = useRoom<never, S, never, never>();\n const rootOrNull = useMutableStorageRoot<S>();\n const rerender = useRerender();\n\n React.useEffect(() => {\n if (rootOrNull === null) {\n return;\n }\n const root = rootOrNull;\n\n let unsubCurr: (() => void) | undefined;\n let curr = root.get(key);\n\n function subscribeToCurr() {\n unsubCurr = isLiveNode(curr) ? room.subscribe(curr, rerender) : undefined;\n }\n\n function onRootChange() {\n const newValue = root.get(key);\n if (newValue !== curr) {\n unsubCurr?.();\n curr = newValue;\n subscribeToCurr();\n rerender();\n }\n }\n\n subscribeToCurr();\n rerender();\n\n const unsubscribeRoot = room.subscribe(root, onRootChange);\n return () => {\n unsubscribeRoot();\n unsubCurr?.();\n };\n }, [rootOrNull, room, key, rerender]);\n\n if (rootOrNull === null) {\n return null;\n } else {\n return rootOrNull.get(key);\n }\n}\n\nfunction make_useMutation<\n P extends JsonObject,\n S extends LsonObject,\n U extends BaseUserMeta,\n E extends Json,\n>() {\n return function useMutation<\n F extends (context: MutationContext<P, S, U>, ...args: any[]) => any,\n >(callback: F, deps: readonly unknown[]): OmitFirstArg<F> {\n const room = useRoom<P, S, U, E>();\n return React.useMemo(\n () => {\n return ((...args) =>\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n room.batch(() =>\n // eslint-disable-next-line @typescript-eslint/no-unsafe-return\n callback(\n makeMutationContext<P, S, U, E>(room),\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n ...args\n )\n )) as OmitFirstArg<F>;\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [room, ...deps]\n );\n };\n}\n\nfunction useThreads<M extends BaseMetadata>(\n options: UseThreadsOptions<M> = {\n query: { metadata: {} },\n }\n): ThreadsState<M> {\n const { scrollOnLoad = true } = options;\n const client = useClient();\n const room = useRoom();\n const queryKey = React.useMemo(\n () => generateQueryKey(room.id, options.query),\n [room, options]\n );\n\n const { store, getThreadsAndInboxNotifications, incrementQuerySubscribers } =\n getExtrasForClient<M>(client);\n\n React.useEffect(() => {\n void getThreadsAndInboxNotifications(room, queryKey, options);\n return incrementQuerySubscribers(queryKey);\n }, [room, queryKey]); // eslint-disable-line react-hooks/exhaustive-deps\n\n const selector = React.useCallback(\n (state: CacheState<M>): ThreadsState<M> => {\n const query = state.queries[queryKey];\n if (query === undefined || query.isLoading) {\n return {\n isLoading: true,\n };\n }\n\n return {\n threads: client[kInternal].comments.selectedThreads(\n room.id,\n state,\n options\n ),\n isLoading: false,\n error: query.error,\n };\n },\n [room, queryKey] // eslint-disable-line react-hooks/exhaustive-deps\n );\n\n const state = useSyncExternalStoreWithSelector(\n store.subscribe,\n store.get,\n store.get,\n selector\n );\n\n useScrollToCommentOnLoadEffect(scrollOnLoad, state);\n\n return state;\n}\n\nfunction useCommentsErrorListener<M extends BaseMetadata>(\n callback: (error: CommentsError<M>) => void\n) {\n const client = useClient();\n const savedCallback = useLatest(callback);\n const { commentsErrorEventSource } = getExtrasForClient<M>(client);\n\n React.useEffect(() => {\n return commentsErrorEventSource.subscribe(savedCallback.current);\n }, [savedCallback, commentsErrorEventSource]);\n}\n\nfunction useThreadCreateCallback() {\n return React.useContext(ThreadCreateCallbackContext);\n}\n\nfunction useThreadDeleteCallback() {\n return React.useContext(ThreadDeleteCallbackContext);\n}\n\nfunction useComposerFocusCallback() {\n return React.useContext(ComposerFocusCallbackContext);\n}\n\nfunction useIsThreadActiveCallback() {\n return React.useContext(IsThreadActiveCallbackContext);\n}\n\nfunction useCreateThread<M extends BaseMetadata>() {\n const client = useClient();\n const room = useRoom();\n const onCreateThread = useThreadCreateCallback();\n\n return React.useCallback(\n (options: CreateThreadOptions<M>): ThreadData<M> => {\n const body = options.body;\n const metadata: M = \"metadata\" in options ? options.metadata : ({} as M);\n\n const threadId = client[kInternal].comments.createThreadId();\n const commentId = client[kInternal].comments.createCommentId();\n const createdAt = new Date();\n\n const newComment: CommentData = {\n id: commentId,\n threadId,\n roomId: room.id,\n createdAt,\n type: \"comment\",\n userId: getCurrentUserId(room),\n body,\n reactions: [],\n };\n const newThread: ThreadData<M> = {\n id: threadId,\n type: \"thread\",\n createdAt,\n updatedAt: createdAt,\n roomId: room.id,\n metadata: metadata as ThreadData<M>[\"metadata\"],\n comments: [newComment],\n };\n\n const optimisticUpdateId = nanoid();\n\n const { store, onMutationFailure } = getExtrasForClient(client);\n store.pushOptimisticUpdate({\n type: \"create-thread\",\n thread: newThread,\n id: optimisticUpdateId,\n roomId: room.id,\n });\n\n onCreateThread?.(newThread.id);\n\n const commentsAPI = (room[kInternal] as PrivateRoomApi<M>).comments;\n commentsAPI.createThread({ threadId, commentId, body, metadata }).then(\n (thread) => {\n store.set((state) => ({\n ...state,\n threads: {\n ...state.threads,\n [threadId]: thread,\n },\n optimisticUpdates: state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n ),\n }));\n },\n (err: Error) =>\n onMutationFailure(\n err,\n optimisticUpdateId,\n (err) =>\n new CreateThreadError(err, {\n roomId: room.id,\n threadId,\n commentId,\n body,\n metadata,\n })\n )\n );\n\n return newThread;\n },\n [client, room, onCreateThread]\n );\n}\n\nfunction useEditThreadMetadata<M extends BaseMetadata>() {\n const client = useClient();\n const room = useRoom();\n return React.useCallback(\n (options: EditThreadMetadataOptions<M>): void => {\n if (!(\"metadata\" in options)) {\n return;\n }\n\n const threadId = options.threadId;\n const metadata = options.metadata;\n const updatedAt = new Date();\n\n const optimisticUpdateId = nanoid();\n\n const { store, onMutationFailure } = getExtrasForClient(client);\n store.pushOptimisticUpdate({\n type: \"edit-thread-metadata\",\n metadata,\n id: optimisticUpdateId,\n threadId,\n updatedAt,\n });\n\n const commentsAPI = (room[kInternal] as PrivateRoomApi<M>).comments;\n commentsAPI.editThreadMetadata({ metadata, threadId }).then(\n (metadata) => {\n store.set((state) => {\n const existingThread = state.threads[threadId];\n const updatedOptimisticUpdates = state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n );\n\n // If the thread doesn't exist in the cache, we do not update the metadata\n if (existingThread === undefined) {\n return {\n ...state,\n optimisticUpdates: updatedOptimisticUpdates,\n };\n }\n\n // If the thread has been deleted, we do not update the metadata\n if (existingThread.deletedAt !== undefined) {\n return {\n ...state,\n optimisticUpdates: updatedOptimisticUpdates,\n };\n }\n\n if (\n existingThread.updatedAt &&\n existingThread.updatedAt > updatedAt\n ) {\n return {\n ...state,\n optimisticUpdates: updatedOptimisticUpdates,\n };\n }\n\n return {\n ...state,\n threads: {\n ...state.threads,\n [threadId]: {\n ...existingThread,\n metadata: metadata as [M] extends [never]\n ? Record<string, never>\n : M,\n },\n },\n optimisticUpdates: updatedOptimisticUpdates,\n };\n });\n },\n (err: Error) =>\n onMutationFailure(\n err,\n optimisticUpdateId,\n (error) =>\n new EditThreadMetadataError(error, {\n roomId: room.id,\n threadId,\n metadata,\n })\n )\n );\n },\n [client, room]\n );\n}\n\nfunction useCreateComment(): (options: CreateCommentOptions) => CommentData {\n const client = useClient();\n const room = useRoom();\n return React.useCallback(\n ({ threadId, body }: CreateCommentOptions): CommentData => {\n const commentId = client[kInternal].comments.createCommentId();\n const createdAt = new Date();\n\n const comment: CommentData = {\n id: commentId,\n threadId,\n roomId: room.id,\n type: \"comment\",\n createdAt,\n userId: getCurrentUserId(room),\n body,\n reactions: [],\n };\n\n const optimisticUpdateId = nanoid();\n\n const { store, onMutationFailure } = getExtrasForClient(client);\n store.pushOptimisticUpdate({\n type: \"create-comment\",\n comment,\n id: optimisticUpdateId,\n });\n\n room[kInternal].comments\n .createComment({ threadId, commentId, body })\n .then(\n (newComment) => {\n store.set((state) => {\n const existingThread = state.threads[threadId];\n const updatedOptimisticUpdates = state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n );\n\n if (existingThread === undefined) {\n return {\n ...state,\n optimisticUpdates: updatedOptimisticUpdates,\n };\n }\n\n const inboxNotification = Object.values(\n state.inboxNotifications\n ).find(\n (notification) =>\n notification.kind === \"thread\" &&\n notification.threadId === threadId\n );\n\n // If the thread has an inbox notification associated with it, we update the notification's `notifiedAt` and `readAt` values\n const updatedInboxNotifications =\n inboxNotification !== undefined\n ? {\n ...state.inboxNotifications,\n [inboxNotification.id]: {\n ...inboxNotification,\n notifiedAt: newComment.createdAt,\n readAt: newComment.createdAt,\n },\n }\n : state.inboxNotifications;\n\n return {\n ...state,\n threads: {\n ...state.threads,\n [threadId]: upsertComment(existingThread, newComment), // Upsert the new comment into the thread comments list (if applicable)\n },\n inboxNotifications: updatedInboxNotifications,\n optimisticUpdates: updatedOptimisticUpdates,\n };\n });\n },\n (err: Error) =>\n onMutationFailure(\n err,\n optimisticUpdateId,\n (err) =>\n new CreateCommentError(err, {\n roomId: room.id,\n threadId,\n commentId,\n body,\n })\n )\n );\n\n return comment;\n },\n [client, room]\n );\n}\n\nfunction useEditComment(): (options: EditCommentOptions) => void {\n const client = useClient();\n const room = useRoom();\n return React.useCallback(\n ({ threadId, commentId, body }: EditCommentOptions): void => {\n const editedAt = new Date();\n const optimisticUpdateId = nanoid();\n\n const { store, onMutationFailure } = getExtrasForClient(client);\n const thread = store.get().threads[threadId];\n if (thread === undefined) {\n console.warn(\n `Internal unexpected behavior. Cannot edit comment in thread \"${threadId}\" because the thread does not exist in the cache.`\n );\n return;\n }\n\n const comment = thread.comments.find(\n (comment) => comment.id === commentId\n );\n\n if (comment === undefined || comment.deletedAt !== undefined) {\n console.warn(\n `Internal unexpected behavior. Cannot edit comment \"${commentId}\" in thread \"${threadId}\" because the comment does not exist in the cache.`\n );\n return;\n }\n\n store.pushOptimisticUpdate({\n type: \"edit-comment\",\n comment: {\n ...comment,\n editedAt,\n body,\n },\n id: optimisticUpdateId,\n });\n\n room[kInternal].comments.editComment({ threadId, commentId, body }).then(\n (editedComment) => {\n store.set((state) => {\n const existingThread = state.threads[threadId];\n const updatedOptimisticUpdates = state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n );\n\n if (existingThread === undefined) {\n return {\n ...state,\n optimisticUpdates: updatedOptimisticUpdates,\n };\n }\n\n return {\n ...state,\n threads: {\n ...state.threads,\n [threadId]: upsertComment(existingThread, editedComment), // Upsert the edited comment into the thread comments list (if applicable)\n },\n optimisticUpdates: updatedOptimisticUpdates,\n };\n });\n },\n (err: Error) =>\n onMutationFailure(\n err,\n optimisticUpdateId,\n (error) =>\n new EditCommentError(error, {\n roomId: room.id,\n threadId,\n commentId,\n body,\n })\n )\n );\n },\n [client, room]\n );\n}\n\nfunction useDeleteComment() {\n const client = useClient();\n const room = useRoom();\n const onDeleteThread = useThreadDeleteCallback();\n\n return React.useCallback(\n ({ threadId, commentId }: DeleteCommentOptions): void => {\n const deletedAt = new Date();\n\n const optimisticUpdateId = nanoid();\n\n const { store, onMutationFailure } = getExtrasForClient(client);\n store.pushOptimisticUpdate({\n type: \"delete-comment\",\n threadId,\n commentId,\n deletedAt,\n id: optimisticUpdateId,\n roomId: room.id,\n });\n\n const thread = store.get().threads[threadId];\n\n // Only trigger `onDeleteThread` callback if the thread exists in cache and is not already deleted\n if (thread !== undefined && thread.deletedAt === undefined) {\n const newThread = deleteComment(thread, commentId, deletedAt);\n if (newThread.deletedAt !== undefined) {\n onDeleteThread?.(threadId);\n }\n }\n\n room[kInternal].comments.deleteComment({ threadId, commentId }).then(\n () => {\n store.set((state) => {\n const existingThread = state.threads[threadId];\n const updatedOptimisticUpdates = state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n );\n\n // If thread does not exist, we return the existing state\n if (existingThread === undefined) {\n return {\n ...state,\n optimisticUpdates: updatedOptimisticUpdates,\n };\n }\n\n return {\n ...state,\n threads: {\n ...state.threads,\n [threadId]: deleteComment(existingThread, commentId, deletedAt),\n },\n optimisticUpdates: updatedOptimisticUpdates,\n };\n });\n },\n (err: Error) =>\n onMutationFailure(\n err,\n optimisticUpdateId,\n (error) =>\n new DeleteCommentError(error, {\n roomId: room.id,\n threadId,\n commentId,\n })\n )\n );\n },\n [client, room, onDeleteThread]\n );\n}\n\nfunction useAddReaction<M extends BaseMetadata>() {\n const client = useClient();\n const room = useRoom();\n return React.useCallback(\n ({ threadId, commentId, emoji }: CommentReactionOptions): void => {\n const createdAt = new Date();\n const userId = getCurrentUserId(room);\n\n const optimisticUpdateId = nanoid();\n\n const { store, onMutationFailure } = getExtrasForClient<M>(client);\n store.pushOptimisticUpdate({\n type: \"add-reaction\",\n threadId,\n commentId,\n reaction: {\n emoji,\n userId,\n createdAt,\n },\n id: optimisticUpdateId,\n });\n\n room[kInternal].comments.addReaction({ threadId, commentId, emoji }).then(\n (addedReaction) => {\n store.set((state): CacheState<M> => {\n const existingThread = state.threads[threadId];\n const updatedOptimisticUpdates = state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n );\n\n // If the thread doesn't exist in the cache, we do not update the metadata\n if (existingThread === undefined) {\n return {\n ...state,\n optimisticUpdates: updatedOptimisticUpdates,\n };\n }\n\n return {\n ...state,\n threads: {\n ...state.threads,\n [threadId]: addReaction(\n existingThread,\n commentId,\n addedReaction\n ),\n },\n optimisticUpdates: updatedOptimisticUpdates,\n };\n });\n },\n (err: Error) =>\n onMutationFailure(\n err,\n optimisticUpdateId,\n (error) =>\n new AddReactionError(error, {\n roomId: room.id,\n threadId,\n commentId,\n emoji,\n })\n )\n );\n },\n [client, room]\n );\n}\n\nfunction useRemoveReaction() {\n const client = useClient();\n const room = useRoom();\n return React.useCallback(\n ({ threadId, commentId, emoji }: CommentReactionOptions): void => {\n const userId = getCurrentUserId(room);\n\n const removedAt = new Date();\n const optimisticUpdateId = nanoid();\n\n const { store, onMutationFailure } = getExtrasForClient(client);\n store.pushOptimisticUpdate({\n type: \"remove-reaction\",\n threadId,\n commentId,\n emoji,\n userId,\n removedAt,\n id: optimisticUpdateId,\n });\n\n room[kInternal].comments\n .removeReaction({ threadId, commentId, emoji })\n .then(\n () => {\n store.set((state) => {\n const existingThread = state.threads[threadId];\n const updatedOptimisticUpdates = state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n );\n\n // If the thread doesn't exist in the cache, we do not update the metadata\n if (existingThread === undefined) {\n return {\n ...state,\n optimisticUpdates: updatedOptimisticUpdates,\n };\n }\n\n return {\n ...state,\n threads: {\n ...state.threads,\n [threadId]: removeReaction(\n existingThread,\n commentId,\n emoji,\n userId,\n removedAt\n ),\n },\n optimisticUpdates: updatedOptimisticUpdates,\n };\n });\n },\n (err: Error) =>\n onMutationFailure(\n err,\n optimisticUpdateId,\n (error) =>\n new RemoveReactionError(error, {\n roomId: room.id,\n threadId,\n commentId,\n emoji,\n })\n )\n );\n },\n [client, room]\n );\n}\n\nfunction useMarkThreadAsRead() {\n const client = useClient();\n const room = useRoom();\n return React.useCallback(\n (threadId: string) => {\n const { store, onMutationFailure } = getExtrasForClient(client);\n const inboxNotification = Object.values(\n store.get().inboxNotifications\n ).find(\n (inboxNotification) =>\n inboxNotification.kind === \"thread\" &&\n inboxNotification.threadId === threadId\n );\n\n if (!inboxNotification) return;\n\n const optimisticUpdateId = nanoid();\n const now = new Date();\n\n store.pushOptimisticUpdate({\n type: \"mark-inbox-notification-as-read\",\n id: optimisticUpdateId,\n inboxNotificationId: inboxNotification.id,\n readAt: now,\n });\n\n room[kInternal].notifications\n .markInboxNotificationAsRead(inboxNotification.id)\n .then(\n () => {\n store.set((state) => ({\n ...state,\n inboxNotifications: {\n ...state.inboxNotifications,\n [inboxNotification.id]: {\n ...inboxNotification,\n readAt: now,\n },\n },\n optimisticUpdates: state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n ),\n }));\n },\n (err: Error) => {\n onMutationFailure(\n err,\n optimisticUpdateId,\n (error) =>\n new MarkInboxNotificationAsReadError(error, {\n inboxNotificationId: inboxNotification.id,\n })\n );\n return;\n }\n );\n },\n [client, room]\n );\n}\n\nfunction useThreadSubscription(threadId: string): ThreadSubscription {\n const client = useClient();\n const { store } = getExtrasForClient(client);\n\n const selector = React.useCallback(\n (state: CacheState<BaseMetadata>): ThreadSubscription => {\n const inboxNotification = client[kInternal].comments\n .selectedInboxNotifications(state)\n .find(\n (inboxNotification) =>\n inboxNotification.kind === \"thread\" &&\n inboxNotification.threadId === threadId\n );\n\n const thread = state.threads[threadId];\n\n if (inboxNotification === undefined || thread === undefined) {\n return {\n status: \"not-subscribed\",\n };\n }\n\n return {\n status: \"subscribed\",\n unreadSince: inboxNotification.readAt,\n };\n },\n [threadId]\n );\n\n return useSyncExternalStoreWithSelector(\n store.subscribe,\n store.get,\n store.get,\n selector\n );\n}\n\nfunction useRoomNotificationSettings(): [\n RoomNotificationSettingsState,\n (settings: Partial<RoomNotificationSettings>) => void,\n] {\n const client = useClient();\n const room = useRoom();\n const { store } = getExtrasForClient(client);\n\n React.useEffect(() => {\n const { getInboxNotificationSettings } = getExtrasForClient(client);\n const queryKey = makeNotificationSettingsQueryKey(room.id);\n void getInboxNotificationSettings(room, queryKey);\n }, [client, room]);\n\n const updateRoomNotificationSettings = useUpdateRoomNotificationSettings();\n\n const selector = React.useCallback(\n (state: CacheState<BaseMetadata>): RoomNotificationSettingsState => {\n const query = state.queries[makeNotificationSettingsQueryKey(room.id)];\n\n if (query === undefined || query.isLoading) {\n return { isLoading: true };\n }\n\n if (query.error !== undefined) {\n return { isLoading: false, error: query.error };\n }\n\n return {\n isLoading: false,\n settings: client[kInternal].comments.selectNotificationSettings(\n room.id,\n state\n ),\n };\n },\n [room]\n );\n\n const settings = useSyncExternalStoreWithSelector(\n store.subscribe,\n store.get,\n store.get,\n selector\n );\n\n return React.useMemo(() => {\n return [settings, updateRoomNotificationSettings];\n }, [settings, updateRoomNotificationSettings]);\n}\n\nfunction useUpdateRoomNotificationSettings() {\n const client = useClient();\n const room = useRoom();\n return React.useCallback(\n (settings: Partial<RoomNotificationSettings>) => {\n const optimisticUpdateId = nanoid();\n\n const { store, onMutationFailure } = getExtrasForClient(client);\n store.pushOptimisticUpdate({\n id: optimisticUpdateId,\n type: \"update-notification-settings\",\n roomId: room.id,\n settings,\n });\n\n room[kInternal].notifications\n .updateRoomNotificationSettings(settings)\n .then(\n (settings) => {\n store.set((state) => ({\n ...state,\n notificationSettings: {\n [room.id]: settings,\n },\n optimisticUpdates: state.optimisticUpdates.filter(\n (update) => update.id !== optimisticUpdateId\n ),\n }));\n },\n (err: Error) =>\n onMutationFailure(\n err,\n optimisticUpdateId,\n (error) =>\n new UpdateNotificationSettingsError(error, {\n roomId: room.id,\n })\n )\n );\n },\n [client, room]\n );\n}\n\nfunction ensureNotServerSide(): void {\n // Error early if suspense is used in a server-side context\n if (typeof window === \"undefined\") {\n throw new Error(\n \"You cannot use the Suspense version of this hook on the server side. Make sure to only call them on the client side.\\nFor tips, see https://liveblocks.io/docs/api-reference/liveblocks-react#suspense-avoid-ssr\"\n );\n }\n}\n\nfunction useSuspendUntilPresenceLoaded(): void {\n const room = useRoom();\n if (room.getSelf() !== null) {\n return;\n }\n\n ensureNotServerSide();\n\n // Throw a _promise_. Suspense will suspend the component tree until either\n // until either a presence update event, or a connection status change has\n // happened. After that, it will render this component tree again and\n // re-evaluate the .getSelf() condition above, or re-suspend again until\n // such event happens.\n throw new Promise<void>((res) => {\n room.events.self.subscribeOnce(() => res());\n room.events.status.subscribeOnce(() => res());\n });\n}\n\nfunction useSelfSuspense<P extends JsonObject, U extends BaseUserMeta>(): User<\n P,\n U\n>;\nfunction useSelfSuspense<T, P extends JsonObject, U extends BaseUserMeta>(\n selector: (me: User<P, U>) => T,\n isEqual?: (prev: T, curr: T) => boolean\n): T;\nfunction useSelfSuspense<T, P extends JsonObject, U extends BaseUserMeta>(\n selector?: (me: User<P, U>) => T,\n isEqual?: (prev: T, curr: T) => boolean\n): T | User<P, U> {\n useSuspendUntilPresenceLoaded();\n return useSelf(\n selector as (me: User<P, U>) => T,\n isEqual as (prev: T | null, curr: T | null) => boolean\n ) as T | User<P, U>;\n}\n\nfunction make_useOthersSuspense<\n P extends JsonObject,\n U extends BaseUserMeta,\n>() {\n return function useOthersSuspense<T>(\n selector?: (others: readonly User<P, U>[]) => T,\n isEqual?: (prev: T, curr: T) => boolean\n ): T | readonly User<P, U>[] {\n useSuspendUntilPresenceLoaded();\n return useOthers(\n selector as (others: readonly User<P, U>[]) => T,\n isEqual as (prev: T, curr: T) => boolean\n ) as T | readonly User<P, U>[];\n };\n}\n\nfunction useOthersConnectionIdsSuspense(): readonly number[] {\n useSuspendUntilPresenceLoaded();\n return useOthersConnectionIds();\n}\n\nfunction make_useOthersMappedSuspense<\n P extends JsonObject,\n U extends BaseUserMeta,\n>() {\n const useOthersMapped = make_useOthersMapped<P, U>();\n return function <T>(\n itemSelector: (other: User<P, U>) => T,\n itemIsEqual?: (prev: T, curr: T) => boolean\n ): ReadonlyArray<readonly [connectionId: number, data: T]> {\n useSuspendUntilPresenceLoaded();\n return useOthersMapped(itemSelector, itemIsEqual);\n };\n}\n\nfunction make_useOtherSuspense<P extends JsonObject, U extends BaseUserMeta>() {\n const useOther = make_useOther<P, U>();\n return function useOtherSuspense<T>(\n connectionId: number,\n selector: (other: User<P, U>) => T,\n isEqual?: (prev: T, curr: T) => boolean\n ): T {\n useSuspendUntilPresenceLoaded();\n return useOther(connectionId, selector, isEqual);\n };\n}\n\nfunction useSuspendUntilStorageLoaded(): void {\n const room = useRoom();\n if (room.getStorageSnapshot() !== null) {\n return;\n }\n\n ensureNotServerSide();\n\n // Throw a _promise_. Suspense will suspend the component tree until this\n // promise resolves (aka until storage has loaded). After that, it will\n // render this component tree again.\n throw new Promise<void>((res) => {\n room.events.storageDidLoad.subscribeOnce(() => res());\n });\n}\n\nfunction make_useStorageSuspense<S extends LsonObject>() {\n const useStorage = make_useStorage<S>();\n return function useStorageSuspense<T>(\n selector: (root: ToImmutable<S>) => T,\n isEqual?: (prev: T, curr: T) => boolean\n ): T {\n useSuspendUntilStorageLoaded();\n return useStorage(\n selector,\n isEqual as (prev: T | null, curr: T | null) => boolean\n ) as T;\n };\n}\n\nfunction useLegacyKeySuspense<\n TKey extends Extract<keyof S, string>,\n S extends LsonObject,\n>(key: TKey): S[TKey] {\n useSuspendUntilStorageLoaded();\n return useLegacyKey(key) as S[TKey];\n}\n\nfunction useThreadsSuspense<M extends BaseMetadata>(\n options: UseThreadsOptions<M> = {\n query: { metadata: {} },\n }\n): ThreadsStateSuccess<M> {\n const { scrollOnLoad = true } = options;\n\n const client = useClient();\n const room = useRoom();\n const queryKey = React.useMemo(\n () => generateQueryKey(room.id, options.query),\n [room, options]\n );\n\n const { store, getThreadsAndInboxNotifications } =\n getExtrasForClient<M>(client);\n\n const query = store.get().queries[queryKey];\n\n if (query === undefined || query.isLoading) {\n throw getThreadsAndInboxNotifications(room, queryKey, options);\n }\n\n if (query.error) {\n throw query.error;\n }\n\n const selector = React.useCallback(\n (state: CacheState<M>): ThreadsStateSuccess<M> => {\n return {\n threads: client[kInternal].comments.selectedThreads(\n room.id,\n state,\n options\n ),\n isLoading: false,\n };\n },\n [room, queryKey] // eslint-disable-line react-hooks/exhaustive-deps\n );\n\n React.useEffect(() => {\n const { incrementQuerySubscribers } = getExtrasForClient(client);\n return incrementQuerySubscribers(queryKey);\n }, [client, queryKey]);\n\n const state = useSyncExternalStoreWithSelector(\n store.subscribe,\n store.get,\n store.get,\n selector\n );\n\n useScrollToCommentOnLoadEffect(scrollOnLoad, state);\n\n return state;\n}\n\nfunction useRoomNotificationSettingsSuspense(): [\n RoomNotificationSettingsStateSuccess,\n (settings: Partial<RoomNotificationSettings>) => void,\n] {\n const updateRoomNotificationSettings = useUpdateRoomNotificationSettings();\n const client = useClient();\n const room = useRoom();\n const queryKey = makeNotificationSettingsQueryKey(room.id);\n\n const { store, getInboxNotificationSettings } = getExtrasForClient(client);\n const query = store.get().queries[queryKey];\n\n if (query === undefined || query.isLoading) {\n throw getInboxNotificationSettings(room, queryKey);\n }\n\n if (query.error) {\n throw query.error;\n }\n\n const selector = React.useCallback(\n (state: CacheState<BaseMetadata>): RoomNotificationSettingsStateSuccess => {\n return {\n isLoading: false,\n settings: client[kInternal].comments.selectNotificationSettings(\n room.id,\n state\n ),\n };\n },\n [room]\n );\n\n const settings = useSyncExternalStoreWithSelector(\n store.subscribe,\n store.get,\n store.get,\n selector\n );\n\n return React.useMemo(() => {\n return [settings, updateRoomNotificationSettings];\n }, [settings, updateRoomNotificationSettings]);\n}\n\nfunction useRoomOrNull() {\n return React.useContext(RoomContext);\n}\n\n/**\n * @private\n *\n * This is an internal API, use `createRoomContext` instead.\n */\nexport function useRoomContextBundleOrNull() {\n const client = useClientOrNull();\n const room = useRoomOrNull();\n return client && room ? getOrCreateRoomContextBundle(client) : null;\n}\n\n/**\n * @private\n *\n * This is an internal API, use `createRoomContext` instead.\n */\nexport function useRoomContextBundle() {\n const client = useClient();\n return getOrCreateRoomContextBundle(client);\n}\n\ntype Options<U extends BaseUserMeta> = {\n /**\n * @deprecated Define 'resolveUsers' in 'createClient' from '@liveblocks/client' instead.\n * Please refer to our Upgrade Guide to learn more, see https://liveblocks.io/docs/platform/upgrading/1.10.\n *\n * A function that returns user info from user IDs.\n */\n resolveUsers?: (\n args: ResolveUsersArgs\n ) => OptionalPromise<(U[\"info\"] | undefined)[] | undefined>;\n\n /**\n * @deprecated Define 'resolveMentionSuggestions' in 'createClient' from '@liveblocks/client' instead.\n * Please refer to our Upgrade Guide to learn more, see https://liveblocks.io/docs/platform/upgrading/1.10.\n *\n * A function that returns a list of user IDs matching a string.\n */\n resolveMentionSuggestions?: (\n args: ResolveMentionSuggestionsArgs\n ) => OptionalPromise<string[]>;\n};\n\nexport function createRoomContext<\n P extends JsonObject = DP,\n S extends LsonObject = DS,\n U extends BaseUserMeta = DU,\n E extends Json = never, // TODO Change this to DE for 2.0\n M extends BaseMetadata = never, // TODO Change this to DM for 2.0\n>(\n client: OpaqueClient,\n options?: Options<U>\n): RoomContextBundle<P, S, U, E, M> {\n // Deprecated option\n if (options?.resolveUsers) {\n throw new Error(\n \"The 'resolveUsers' option has moved to 'createClient' from '@liveblocks/client'. Please refer to our Upgrade Guide to learn more, see https://liveblocks.io/docs/platform/upgrading/1.10.\"\n );\n }\n\n // Deprecated option\n if (options?.resolveMentionSuggestions) {\n throw new Error(\n \"The 'resolveMentionSuggestions' option has moved to 'createClient' from '@liveblocks/client'. Please refer to our Upgrade Guide to learn more, see https://liveblocks.io/docs/platform/upgrading/1.10.\"\n );\n }\n\n return getOrCreateRoomContextBundle<P, S, U, E, M>(client);\n}\n\nexport function generateQueryKey(\n roomId: string,\n options: UseThreadsOptions<BaseMetadata>[\"query\"]\n) {\n return `${roomId}-${stringify(options ?? {})}`;\n}\n\n// TODO in 2.0 Copy/paste all the docstrings onto these global hooks :(\n// const __1 = useBatch;\n// const __2 = useBroadcastEvent<DE>;\n// const __3 = useOthersListener<DP, DU>;\n// const __4 = useRoom<DP, DS, DU, DE>;\n// const __5 = useStatus;\n// const __6 = useAddReaction<DM>;\n// const __7 = make_useMutation<DP, DS, DU, DE>();\n// const __8 = useCreateThread<DM>;\n// const __9 = useEditThreadMetadata<DM>;\n// const _10 = useEventListener<DP, DU, DE>;\n// const _11 = useMyPresence<DP>;\n// const _12 = useOthersConnectionIds;\n// const _13 = useOthersConnectionIdsSuspense;\n// const _14 = make_useOthersMapped<DP, DU>();\n// const _15 = make_useOthersMappedSuspense<DP, DU>();\n// const _16 = useThreads<DM>;\n// const _17 = useThreadsSuspense<DM>;\n// const _18 = make_useOther<DP, DU>();\n// const _19 = useOthers<DP, DU>;\n// const _20 = make_useOtherSuspense<DP, DU>();\n// const _21 = make_useOthersSuspense<DP, DU>();\n// const _22 = make_useStorage<DS>();\n// const _23 = make_useStorageSuspense<DS>();\n// const _24 = useSelf<DP, DU>;\n// const _25 = useSelfSuspense<DP, DU>;\n// const _26 = useStorageRoot<DS>;\n// const _27 = useUpdateMyPresence<DP>;\n//\n// export {\n// __1 as useBatch,\n// __2 as useBroadcastEvent,\n// __3 as useOthersListener,\n// __4 as useRoom,\n// __5 as useStatus,\n// __6 as useAddReaction,\n// __7 as useMutation,\n// __8 as useCreateThread,\n// __9 as useEditThreadMetadata,\n// _10 as useEventListener,\n// _11 as useMyPresence,\n// _12 as useOthersConnectionIds,\n// _13 as useOthersConnectionIdsSuspense,\n// _14 as useOthersMapped,\n// _15 as useOthersMappedSuspense,\n// _16 as useThreads,\n// _17 as useThreadsSuspense,\n// _18 as useOther,\n// _19 as useOthers,\n// _20 as useOtherSuspense,\n// _21 as useOthersSuspense,\n// _22 as useStorage,\n// _23 as useStorageSuspense,\n// _24 as useSelf,\n// _25 as useSelfSuspense,\n// _26 as useStorageRoot,\n// _27 as useUpdateMyPresence,\n// };\n","import { useEffect, useRef } from \"react\";\n\n/**\n * Keeps a ref in sync with a given value that may or may not change on\n * every render.\n *\n * The purpose of this hook is to return a stable ref that can be passed\n * to a callback function so the callback can be registered but still can\n * access the latest value at a later point in time.\n */\nexport function useLatest<T>(value: T): { readonly current: T } {\n const ref = useRef(value);\n useEffect(() => {\n ref.current = value;\n }, [value]);\n return ref;\n}\n","import { useReducer } from \"react\";\n\n/**\n * Trigger a re-render programmatically, without changing the component's\n * state.\n *\n * @example\n * const rerender = useRerender();\n *\n * return (\n * <button onClick={rerender}>\n * {Math.random()}\n * </button>\n * )\n */\nexport function useRerender(): () => void {\n const [, update] = useReducer(\n // This implementation works by incrementing a hidden counter value that is\n // never consumed. Simply incrementing the counter changes the component's\n // state and, thus, trigger a re-render.\n (x: number): number => x + 1,\n 0\n );\n return update;\n}\n","import type { BaseMetadata } from \"@liveblocks/client\";\nimport * as React from \"react\";\n\nimport type { ThreadsState } from \"./types\";\n\nfunction handleScrollToCommentOnLoad(\n shouldScrollOnLoad: boolean,\n state: ThreadsState<BaseMetadata>\n) {\n if (shouldScrollOnLoad === false) return;\n\n if (state.isLoading) return;\n\n const isWindowDefined = typeof window !== \"undefined\";\n if (!isWindowDefined) return;\n\n const hash = window.location.hash;\n const commentId = hash.slice(1);\n\n // If the hash is not a comment ID, we do not scroll to it\n if (!commentId.startsWith(\"cm_\")) return;\n\n // If a comment with the ID does not exist in the DOM, we do not scroll to it\n const comment = document.getElementById(commentId);\n if (comment === null) return;\n\n const comments = state.threads.flatMap((thread) => thread.comments);\n const isCommentInThreads = comments.some(\n (comment) => comment.id === commentId\n );\n\n // If the comment is not in the threads for this hook, we do not scroll to it\n if (!isCommentInThreads) return;\n\n comment.scrollIntoView();\n}\n\n/**\n * Scroll to the comment with the ID in the hash of the URL based on whether\n * the query is loading and whether the hook should scroll to the comment on load.\n */\nexport function useScrollToCommentOnLoadEffect(\n shouldScrollOnLoad: boolean,\n state: ThreadsState<BaseMetadata>\n) {\n React.useEffect(\n () => {\n handleScrollToCommentOnLoad(shouldScrollOnLoad, state);\n },\n // eslint-disable-next-line react-hooks/exhaustive-deps -- We only want to run this effect once\n [state.isLoading]\n );\n}\n"]}
|