{"version":3,"file":"useReportLostConnectionSystemNotification.mjs","names":[],"sources":["../../../../../src/components/Chat/hooks/useReportLostConnectionSystemNotification.ts"],"sourcesContent":["import { useCallback, useEffect, useRef } from 'react';\nimport type { ConnectionType } from 'stream-chat';\n\nimport { useChatContext } from '../../../context/ChatContext';\nimport { useTranslationContext } from '../../../context/TranslationContext';\nimport { useNotificationApi } from '../../Notifications/hooks/useNotificationApi';\n\n/**\n * Publishes a persistent system notification while the client cannot reach Stream, and removes it\n * when it can again. Must run under `ChatProvider` and `TranslationProvider`, e.g. from a child of\n * `<Chat>`.\n *\n * The device network and the WebSocket are read separately because either can fail alone. A network\n * report of no connection shows the network message; otherwise a down socket shows the reconnecting\n * message. Both stores are subscribed imperatively so a network flap does not re-render the caller.\n *\n * A socket drop is held for `client.wsConnection.config.offlineNotificationDisplayDelayMs` and\n * cancelled if the socket returns inside that window, since most drops resolve quickly. A network\n * drop is shown immediately.\n */\nexport const useReportLostConnectionSystemNotification = () => {\n  const { t } = useTranslationContext();\n  const { client } = useChatContext();\n  const { addSystemNotification, removeNotification } = useNotificationApi();\n  const notificationIdRef = useRef<string | null>(null);\n  /** The reason being shown. A ref so re-subscribing does not republish what is showing. */\n  const reasonRef = useRef<ConnectionType | null>(null);\n  /**\n   * The socket status as last shown, which can differ from `client.wsConnection.state` while a drop\n   * is held. A ref because the effect re-runs when `t` is replaced and re-seeding would discard the\n   * held drop. Seeded once on mount, so an app that starts offline shows the banner immediately.\n   */\n  const socketOnlineRef = useRef<boolean | null>(null);\n  /** The drop being held, so the socket returning can cancel it. */\n  const heldDropRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n  const cancelHeldDrop = useCallback(() => {\n    if (heldDropRef.current === null) return;\n    clearTimeout(heldDropRef.current);\n    heldDropRef.current = null;\n  }, []);\n\n  const dismissConnectionLostNotification = useCallback(() => {\n    if (!notificationIdRef.current) return;\n    removeNotification(notificationIdRef.current);\n    notificationIdRef.current = null;\n    reasonRef.current = null;\n  }, [removeNotification]);\n\n  // Dismissal is scoped to the mount, not to the subscriptions below. Their dependencies change for\n  // unrelated reasons (`t` is replaced when `Streami18n.init()` resolves), and dismissing in that\n  // cleanup would remove a notification published before init finished.\n  useEffect(\n    () => () => {\n      cancelHeldDrop();\n      dismissConnectionLostNotification();\n    },\n    [cancelHeldDrop, dismissConnectionLostNotification],\n  );\n\n  useEffect(() => {\n    if (!t || !client) return;\n\n    // Keyed by `ConnectionType`, so a connection type added to the client fails type checking here\n    // until its message is decided.\n    const messages: Record<ConnectionType, string> = {\n      network: t('chat.reportLostConnection.waitingNetwork.text', 'Waiting for network…'),\n      ws: t('chat.reportLostConnection.reconnecting.text', 'Reconnecting…'),\n    };\n\n    const show = (reason: ConnectionType) => {\n      if (reasonRef.current === reason) return;\n      // A network drop while \"Reconnecting…\" is showing replaces it with the more specific message.\n      dismissConnectionLostNotification();\n      reasonRef.current = reason;\n      notificationIdRef.current = addSystemNotification({\n        duration: 0,\n        emitter: 'Chat',\n        message: messages[reason],\n        severity: 'loading',\n        // One type for both messages: consumers filter banners on it, and a second type would hide\n        // the socket case from those filters.\n        type: 'system:network:connection:lost',\n      });\n    };\n\n    if (socketOnlineRef.current === null) {\n      socketOnlineRef.current = client.wsConnection.isHealthy;\n    }\n\n    // `=== false`, not `!networkOnline`: `undefined` means unknown and must not read as offline.\n    // The socket's value is a plain boolean.\n    let networkOnline = client.networkConnection.isOnline;\n\n    const sync = () => {\n      if (networkOnline === false) return show('network');\n      if (!socketOnlineRef.current) return show('ws');\n      dismissConnectionLostNotification();\n    };\n\n    const unsubscribeNetwork = client.networkConnection.state.subscribeWithSelector(\n      ({ isOnline }) => ({ isOnline }),\n      ({ isOnline }) => {\n        networkOnline = isOnline;\n        sync();\n      },\n    );\n\n    // `subscribeWithSelector` calls back immediately with the current value. That call is the\n    // seed above, not a transition, and holding it would delay the banner for an app that starts\n    // offline.\n    let seeded = false;\n\n    const unsubscribeSocket = client.wsConnection.state.subscribeWithSelector(\n      ({ isHealthy }) => ({ isHealthy }),\n      ({ isHealthy }) => {\n        if (!seeded) {\n          seeded = true;\n          return;\n        }\n\n        if (isHealthy) {\n          // Recovery is not held. A drop still inside its window is cancelled, so a brief flap\n          // shows nothing.\n          cancelHeldDrop();\n          socketOnlineRef.current = true;\n          sync();\n          return;\n        }\n\n        // A re-subscription during the window can reach here, and restarting the timer would extend\n        // the wait.\n        if (heldDropRef.current !== null) return;\n\n        // The delay is read per drop, so a changed value applies to the next drop without\n        // re-running the effect.\n        heldDropRef.current = setTimeout(() => {\n          heldDropRef.current = null;\n          socketOnlineRef.current = false;\n          sync();\n        }, client.wsConnection.config.offlineNotificationDisplayDelayMs);\n      },\n    );\n\n    // Reflects the current state now rather than waiting for a transition, so a client that is\n    // already offline on mount shows the banner.\n    sync();\n\n    return () => {\n      unsubscribeNetwork();\n      unsubscribeSocket();\n    };\n  }, [\n    addSystemNotification,\n    cancelHeldDrop,\n    client,\n    dismissConnectionLostNotification,\n    t,\n  ]);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;AAoBA,IAAa,kDAAkD;CAC7D,MAAM,EAAE,MAAM,sBAAsB;CACpC,MAAM,EAAE,WAAW,eAAe;CAClC,MAAM,EAAE,uBAAuB,uBAAuB,mBAAmB;CACzE,MAAM,oBAAoB,OAAsB,IAAI;;CAEpD,MAAM,YAAY,OAA8B,IAAI;;;;;;CAMpD,MAAM,kBAAkB,OAAuB,IAAI;;CAEnD,MAAM,cAAc,OAA6C,IAAI;CAErE,MAAM,iBAAiB,kBAAkB;EACvC,IAAI,YAAY,YAAY,MAAM;EAClC,aAAa,YAAY,OAAO;EAChC,YAAY,UAAU;CACxB,GAAG,CAAC,CAAC;CAEL,MAAM,oCAAoC,kBAAkB;EAC1D,IAAI,CAAC,kBAAkB,SAAS;EAChC,mBAAmB,kBAAkB,OAAO;EAC5C,kBAAkB,UAAU;EAC5B,UAAU,UAAU;CACtB,GAAG,CAAC,kBAAkB,CAAC;CAKvB,sBACc;EACV,eAAe;EACf,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