{"version":3,"sources":["../../../src/hooks/useNotifications.ts"],"sourcesContent":["import { checkNotificationMatchesFilter, isSameFilter, Notification, NotificationFilter, NovuError } from '@novu/js';\nimport { useCallback, useEffect, useState } from 'react';\nimport { useDataRef } from './internal/useDataRef';\nimport { useWebSocketEvent } from './internal/useWebsocketEvent';\nimport { useNovu, useRealtime } from './NovuProvider';\n\n/**\n * Props for the useNotifications hook.\n *\n * @example\n * ```tsx\n * // Get unread notifications\n * const { notifications } = useNotifications({\n *   read: false\n * });\n *\n * // Get unseen notifications with specific tags\n * const { notifications } = useNotifications({\n *   seen: false,\n *   tags: ['important']\n * });\n *\n * // Get notifications (auto-updates in real time when new notifications arrive)\n * const { notifications } = useNotifications({\n *   read: false\n * });\n *\n * // Get notifications from a specific time period\n * const { notifications } = useNotifications({\n *   createdGte: 1704067200000,\n *   createdLte: 1735689599999\n * });\n *\n * // Opt out of the built-in realtime updates and drive them yourself\n * const { notifications, refetch } = useNotifications({\n *   read: false,\n *   realtime: false,\n * });\n * ```\n */\nexport type UseNotificationsProps = {\n  tags?: NotificationFilter['tags'];\n  data?: NotificationFilter['data'];\n  read?: NotificationFilter['read'];\n  archived?: NotificationFilter['archived'];\n  snoozed?: NotificationFilter['snoozed'];\n  seen?: NotificationFilter['seen'];\n  severity?: NotificationFilter['severity'];\n  createdGte?: NotificationFilter['createdGte'];\n  createdLte?: NotificationFilter['createdLte'];\n  limit?: number;\n  /**\n   * When `false`, disables the WebSocket subscription that auto-injects\n   * newly received notifications into the list. Built-in mutations like\n   * `readAll`, `seenAll`, `archiveAll`, and `archiveAllRead` continue to\n   * update local state. Use this when you want to drive new-notification updates yourself (e.g.\n   * via your own `novu.on('notifications.notification_received', ...)`\n   * handler combined with `refetch()`).\n   *\n   * When set, this prop takes precedence over the `realtime` config on\n   * `<NovuProvider />`. When omitted, the provider value (default `true`) is used.\n   */\n  realtime?: boolean;\n  onSuccess?: (data: Notification[]) => void;\n  onError?: (error: NovuError) => void;\n};\n\nexport type UseNotificationsResult = {\n  notifications?: Notification[];\n  error?: NovuError;\n  isLoading: boolean;\n  isFetching: boolean;\n  hasMore: boolean;\n  readAll: () => Promise<{\n    data?: void | undefined;\n    error?: NovuError | undefined;\n  }>;\n  seenAll: () => Promise<{\n    data?: void | undefined;\n    error?: NovuError | undefined;\n  }>;\n  archiveAll: () => Promise<{\n    data?: void | undefined;\n    error?: NovuError | undefined;\n  }>;\n  archiveAllRead: () => Promise<{\n    data?: void | undefined;\n    error?: NovuError | undefined;\n  }>;\n  refetch: () => Promise<void>;\n  fetchMore: () => Promise<void>;\n};\n\nexport const useNotifications = (props?: UseNotificationsProps): UseNotificationsResult => {\n  const {\n    tags,\n    data: dataFilter,\n    read,\n    archived = false,\n    snoozed = false,\n    seen,\n    severity,\n    createdGte,\n    createdLte,\n    limit = 10,\n    realtime: propsRealtime,\n    onSuccess,\n    onError,\n  } = props || {};\n  const limitRef = useDataRef<number | undefined>(limit);\n  const filterRef = useDataRef<NotificationFilter>({\n    tags,\n    data: dataFilter,\n    read,\n    archived,\n    snoozed,\n    seen,\n    severity,\n    createdGte,\n    createdLte,\n  });\n  const novu = useNovu();\n  const providerRealtime = useRealtime();\n  const realtime = propsRealtime ?? providerRealtime;\n  const [data, setData] = useState<Array<Notification>>();\n  const [error, setError] = useState<NovuError>();\n  const [isLoading, setIsLoading] = useState(true);\n  const [isFetching, setIsFetching] = useState(false);\n  const [hasMore, setHasMore] = useState(false);\n  const length = data?.length;\n  const after = length ? data[length - 1].id : undefined;\n  const afterRef = useDataRef<string | undefined>(after);\n\n  useEffect(() => {\n    const listener = ({\n      data,\n    }: {\n      data: { notifications: Notification[]; hasMore: boolean; filter: NotificationFilter };\n    }) => {\n      if (!data || !isSameFilter(filterRef.current, data.filter)) {\n        return;\n      }\n\n      // the event is called with the list of all notifications cached matching the current filter\n      setData(data.notifications);\n      setHasMore(data.hasMore);\n    };\n\n    const cleanup = novu.on('notifications.list.updated', listener);\n\n    return () => {\n      cleanup();\n    };\n  }, [filterRef, novu]);\n\n  useWebSocketEvent({\n    event: 'notifications.notification_received',\n    enabled: realtime,\n    eventHandler: ({ result: notification }) => {\n      const currentFilter = filterRef.current;\n      const matches = checkNotificationMatchesFilter(notification, currentFilter);\n      if (matches) {\n        // the limit and after props are used to create a cache key\n        // the first batch of notifications in the cache doesn't include the after prop and we want to push to the first batch\n        const cacheKey = { ...currentFilter, limit: limitRef.current };\n        novu.notifications.cache.unshift(cacheKey, notification);\n      }\n    },\n  });\n\n  const fetchNotifications = useCallback(\n    async (options?: { refetch: boolean }) => {\n      if (options?.refetch) {\n        setError(undefined);\n        setIsLoading(true);\n        setIsFetching(false);\n      }\n      setIsFetching(true);\n\n      const response = await novu.notifications.list({\n        ...filterRef.current,\n        limit,\n        after: options?.refetch ? undefined : afterRef.current,\n      });\n\n      if (response.error) {\n        setError(response.error);\n        onError?.(response.error);\n        setIsLoading(false);\n        setIsFetching(false);\n      } else if (response.data) {\n        const responseData = response.data;\n        onSuccess?.(responseData.notifications);\n        setData(responseData.notifications);\n        setHasMore(responseData.hasMore);\n        setIsLoading(false);\n        setIsFetching(false);\n      }\n    },\n    [novu, filterRef, afterRef, limit, onError, onSuccess]\n  );\n\n  useEffect(() => {\n    novu.notifications.clearCache({ filter: filterRef.current });\n    fetchNotifications({ refetch: true });\n  }, [filterRef, novu, JSON.stringify(filterRef.current), fetchNotifications]);\n\n  const refetch = useCallback(() => {\n    novu.notifications.clearCache({ filter: filterRef.current });\n    return fetchNotifications({ refetch: true });\n  }, [filterRef, novu, fetchNotifications]);\n\n  const fetchMore = useCallback(async () => {\n    if (!hasMore || isFetching) return;\n\n    return fetchNotifications();\n  }, [hasMore, isFetching, fetchNotifications]);\n\n  const readAll = useCallback(async () => {\n    return await novu.notifications.readAll({ tags: filterRef.current.tags, data: filterRef.current.data });\n  }, [filterRef, novu]);\n\n  const seenAll = useCallback(async () => {\n    return await novu.notifications.seenAll({ tags: filterRef.current.tags, data: filterRef.current.data });\n  }, [filterRef, novu]);\n\n  const archiveAll = useCallback(async () => {\n    return await novu.notifications.archiveAll({ tags: filterRef.current.tags, data: filterRef.current.data });\n  }, [filterRef, novu]);\n\n  const archiveAllRead = useCallback(async () => {\n    return await novu.notifications.archiveAllRead({ tags: filterRef.current.tags, data: filterRef.current.data });\n  }, [filterRef, novu]);\n\n  return {\n    readAll,\n    seenAll,\n    archiveAll,\n    archiveAllRead,\n    notifications: data,\n    error,\n    isLoading,\n    isFetching,\n    refetch,\n    fetchMore,\n    hasMore,\n  };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,gBAA0G;AAC1G,mBAAiD;AACjD,wBAA2B;AAC3B,+BAAkC;AAClC,0BAAqC;AAyF9B,IAAM,mBAAmB,CAAC,UAA0D;AACzF,QAAM;AAAA,IACJ;AAAA,IACA,MAAM;AAAA,IACN;AAAA,IACA,WAAW;AAAA,IACX,UAAU;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,QAAQ;AAAA,IACR,UAAU;AAAA,IACV;AAAA,IACA;AAAA,EACF,IAAI,SAAS,CAAC;AACd,QAAM,eAAW,8BAA+B,KAAK;AACrD,QAAM,gBAAY,8BAA+B;AAAA,IAC/C;AAAA,IACA,MAAM;AAAA,IACN;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,CAAC;AACD,QAAM,WAAO,6BAAQ;AACrB,QAAM,uBAAmB,iCAAY;AACrC,QAAM,WAAW,iBAAiB;AAClC,QAAM,CAAC,MAAM,OAAO,QAAI,uBAA8B;AACtD,QAAM,CAAC,OAAO,QAAQ,QAAI,uBAAoB;AAC9C,QAAM,CAAC,WAAW,YAAY,QAAI,uBAAS,IAAI;AAC/C,QAAM,CAAC,YAAY,aAAa,QAAI,uBAAS,KAAK;AAClD,QAAM,CAAC,SAAS,UAAU,QAAI,uBAAS,KAAK;AAC5C,QAAM,SAAS,6BAA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