{"version":3,"file":"useMarkRead.mjs","names":[],"sources":["../../../../../src/components/MessageList/hooks/useMarkRead.ts"],"sourcesContent":["import { useCallback, useEffect } from 'react';\nimport { useChannel, useChatContext } from '../../../context';\nimport { useMessagePaginator } from '../../../hooks';\nimport { useStateStore } from '../../../store';\nimport { useThreadContext } from '../../Threads';\nimport type { Channel, ChannelConfig, EventPayload } from 'stream-chat';\nimport { nowNs } from 'stream-chat';\n\nconst readEventsSelector = ({ readEvents }: ChannelConfig) => ({\n  localUnreadCountEnabled: readEvents.localUnreadCountEnabled,\n  readEventsEnabled: readEvents.enabled,\n});\n\nconst hasReadLastMessage = (channel: Channel, userId: string) => {\n  // `latestMessage`, not `anchoredHeadItem`: marking read records `latestMessage`, which skips\n  // messages that do not count as the channel's latest (e.g. error and ephemeral messages).\n  const latestMessageIdInChannel = channel.messagePaginator.latestMessage?.id;\n  const lastReadMessageIdServer = channel.state.read[userId]?.last_read_message_id;\n  return latestMessageIdInChannel === lastReadMessageIdServer;\n};\n\ntype UseMarkReadParams = {\n  hasMoreNewer: boolean;\n  isMessageListScrolledToBottom: boolean;\n  // todo: remove and infer only from useThreadContext return value - if undefined, not a thread list\n  messageListIsThread: boolean;\n  /**\n   * Whether the last message is fully shown. Pass it when the at-bottom flag is thresholded and can\n   * read true while the last message is partly clipped. Defaults to true, so only the flag applies.\n   */\n  isAtTrueBottom?: boolean;\n};\n\n/**\n * Marks the channel or thread read when the user is caught up at the bottom, clears the\n * paginator's unread snapshot on that catch-up, and tells the paginator whether the user is\n * viewing live.\n */\nexport const useMarkRead = ({\n  hasMoreNewer,\n  isAtTrueBottom = true,\n  isMessageListScrolledToBottom,\n  messageListIsThread,\n}: UseMarkReadParams) => {\n  const { client } = useChatContext();\n  const channel = useChannel();\n  const { localUnreadCountEnabled, readEventsEnabled } = useStateStore(\n    channel.configState,\n    readEventsSelector,\n  );\n  const thread = useThreadContext();\n  const messagePaginator = useMessagePaginator();\n\n  const isThreadList = !!thread || messageListIsThread;\n\n  const markRead = useCallback(() => {\n    client.messageDeliveryReporter.throttledMarkRead(thread ?? channel);\n  }, [channel, client.messageDeliveryReporter, thread]);\n\n  // Clears the unread snapshot the separator and banner render from, which the LLC never clears on\n  // `message.read`. Not called on the initial open, so the separator stays where the user left off.\n  const resetUnreadSnapshot = useCallback(() => {\n    const loadedItems = messagePaginator.state.getLatestValue().items ?? [];\n    const previous = messagePaginator.unreadStateSnapshot.getLatestValue();\n    messagePaginator.unreadStateSnapshot.next({\n      ...previous,\n      firstUnreadMessageId: null,\n      lastReadAt: nowNs(),\n      lastReadMessageId:\n        loadedItems[loadedItems.length - 1]?.id ?? previous.lastReadMessageId,\n      unreadCount: 0,\n    });\n  }, [messagePaginator]);\n\n  useEffect(() => {\n    // Live means the tab is visible, the list is at the bottom and no newer messages lie beyond the\n    // loaded window. While live, the LLC skips the own-unread bump on `message.new`, so the\n    // separator and banner do not flash.\n    const pushViewingLive = () =>\n      messagePaginator.setViewingLive(\n        !document.hidden &&\n          isMessageListScrolledToBottom &&\n          isAtTrueBottom &&\n          !hasMoreNewer,\n      );\n\n    pushViewingLive();\n    document.addEventListener('visibilitychange', pushViewingLive);\n\n    return () => {\n      document.removeEventListener('visibilitychange', pushViewingLive);\n      messagePaginator.setViewingLive(false);\n    };\n  }, [hasMoreNewer, isAtTrueBottom, isMessageListScrolledToBottom, messagePaginator]);\n\n  useEffect(() => {\n    // Without read events there is no server-side read state, but a channel counting unread locally\n    // still needs the catch-up; the LLC resets it locally instead of requesting.\n    if (!readEventsEnabled && !localUnreadCountEnabled) return;\n    const shouldMarkRead = () => {\n      const wasMarkedUnread =\n        !!messagePaginator.unreadStateSnapshot.getLatestValue().firstUnreadMessageId;\n\n      const hasUnreadMessages = isThreadList\n        ? (thread?.ownUnreadCount ?? 0) > 0\n        : !!client.user?.id && !hasReadLastMessage(channel, client.user.id);\n\n      return (\n        isAtTrueBottom &&\n        messagePaginator.isViewingLive &&\n        !wasMarkedUnread &&\n        hasUnreadMessages\n      );\n    };\n\n    const onVisibilityChange = () => {\n      if (shouldMarkRead()) {\n        resetUnreadSnapshot();\n        markRead();\n      }\n    };\n\n    const handleMessageNew = (event: EventPayload<'message.new'>) => {\n      const threadUpdated = !!thread && event.message?.parent_id === thread.id;\n      const mainChannelUpdated =\n        !event.message?.parent_id || event.message?.show_in_channel;\n      const activeCollectionUpdated = isThreadList ? threadUpdated : mainChannelUpdated;\n      if (!activeCollectionUpdated) return;\n\n      if (shouldMarkRead()) {\n        resetUnreadSnapshot();\n        markRead();\n      }\n    };\n\n    const subscription = channel.on('message.new', handleMessageNew);\n    document.addEventListener('visibilitychange', onVisibilityChange);\n\n    if (shouldMarkRead()) {\n      markRead();\n    }\n\n    return () => {\n      subscription.unsubscribe();\n      document.removeEventListener('visibilitychange', onVisibilityChange);\n    };\n  }, [\n    channel,\n    client,\n    hasMoreNewer,\n    isAtTrueBottom,\n    isMessageListScrolledToBottom,\n    markRead,\n    resetUnreadSnapshot,\n    isThreadList,\n    localUnreadCountEnabled,\n    messagePaginator,\n    readEventsEnabled,\n    thread,\n  ]);\n};\n"],"mappings":";;;;;;;;AAQA,IAAM,sBAAsB,EAAE,kBAAiC;CAC7D,yBAAyB,WAAW;CACpC,mBAAmB,WAAW;AAChC;AAEA,IAAM,sBAAsB,SAAkB,WAAmB;CAK/D,OAFiC,QAAQ,iBAAiB,eAAe,OACzC,QAAQ,MAAM,KAAK,OAAO,EAAE;AAE9D;;;;;;AAmBA,IAAa,eAAe,EAC1B,cACA,iBAAiB,MACjB,+BACA,0BACuB;CACvB,MAAM,EAAE,WAAW,eAAe;CAClC,MAAM,UAAU,WAAW;CAC3B,MAAM,EAAE,yBAAyB,sBAAsB,cACrD,QAAQ,aACR,kBACF;CACA,MAAM,SAAS,iBAAiB;CAChC,MAAM,mBAAmB,oBAAoB;CAE7C,MAAM,eAAe,CAAC,CAAC,UAAU;CAEjC,MAAM,WAAW,kBAAkB;EACjC,OAAO,wBAAwB,kBAAkB,UAAU,OAAO;CACpE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