{"version":3,"file":"useAttachmentUploadState.mjs","names":[],"sources":["../../../../../src/components/Attachment/hooks/useAttachmentUploadState.ts"],"sourcesContent":["import { useCallback, useMemo } from 'react';\nimport { isPendingUpload } from 'stream-chat';\nimport type {\n  Attachment,\n  LocalAttachment,\n  SharedLocationResponse,\n  UploadManagerState,\n} from 'stream-chat';\n\nimport { useChatContext } from '../../../context/ChatContext';\nimport { useStateStore } from '../../../store';\n\nexport type AttachmentUploadState = {\n  /**\n   * `true` once every byte has been sent but the server has not answered yet. Browser upload\n   * progress counts bytes written to the connection, so it reaches 100% before the server\n   * confirms; the indicator is indeterminate in that window.\n   */\n  uploadConfirmationPending: boolean;\n  /** `true` only while `client.uploadManager` holds a live record for one of the attachments. */\n  isUploading: boolean;\n  /**\n   * 0-100 while uploading and the transfer length is known, `undefined` otherwise. For several\n   * attachments, their mean.\n   */\n  progress?: number;\n};\n\n/** Marks an ID without a live record in the joined selector key. */\nconst NO_RECORD = '-';\n\n/**\n * `UploadRecord` with `uploadConfirmationPending` optional, for a `stream-chat` older than v9.51\n * whose records lack it; {@link useAttachmentsUploadState} then infers it.\n */\ntype UploadRecordWithConfirmationPending = {\n  uploadConfirmationPending?: boolean;\n  uploadProgress?: number;\n};\n\nconst emptyUploadState: AttachmentUploadState = {\n  isUploading: false,\n  uploadConfirmationPending: false,\n};\n\n/**\n * Reports whether a request for any of the attachments is in flight right now, and how far along\n * it is.\n *\n * The source of truth is `client.uploadManager`, which holds a record only while the request runs.\n * Attachments returned by the API have no `localMetadata`, so they never match and the upload UI\n * stays off for sent messages. A pending `localMetadata.uploadState` only selects candidates: a\n * message that outlives its request (aborted upload, `disconnectUser`, a stale state from an\n * offline store) shows no progress because it has no live record. `localMetadata.uploadProgress`\n * is only a fallback for the progress number.\n *\n * @param attachments - Attachments to track. Ones that are not pending uploads are ignored.\n * @returns The combined upload state of the attachments.\n */\nexport const useAttachmentsUploadState = (\n  attachments: (Attachment | LocalAttachment | SharedLocationResponse | undefined)[],\n): AttachmentUploadState => {\n  const { client } = useChatContext();\n\n  const pending = useMemo(\n    () => attachments.filter(isPendingUpload).map((a) => a.localMetadata),\n    [attachments],\n  );\n  // Stable primitive so the selector identity does not change on every render.\n  const pendingIdsKey = pending.map(({ id }) => id).join(',');\n\n  const selector = useCallback(\n    (state: UploadManagerState) => ({\n      // A joined string rather than an array: useStateStore shallow-compares the selected keys,\n      // so a fresh array would never compare equal. Per ID: `-` without a live record, else\n      // `<progress>:<uploadConfirmationPending>`.\n      recordsKey: pendingIdsKey\n        .split(',')\n        .map((id) => {\n          const record = state.uploads[id] as\n            | UploadRecordWithConfirmationPending\n            | undefined;\n          if (!record) return NO_RECORD;\n\n          const awaiting =\n            record.uploadConfirmationPending === undefined\n              ? ''\n              : record.uploadConfirmationPending\n                ? '1'\n                : '0';\n\n          return `${record.uploadProgress ?? ''}:${awaiting}`;\n        })\n        .join(','),\n    }),\n    [pendingIdsKey],\n  );\n\n  // `client` is absent when rendered outside <Chat>; useStateStore tolerates an undefined store.\n  const { recordsKey } = useStateStore(client?.uploadManager?.state, selector) ?? {};\n\n  if (!pending.length) return emptyUploadState;\n\n  // A record exists only while the request runs: that, not the message payload, means \"uploading\".\n  const entries = (recordsKey?.split(',') ?? []).map((entry, index) => {\n    if (entry === NO_RECORD) return undefined;\n\n    const [reportedProgress, reportedAwaiting] = entry.split(':');\n    const progress =\n      reportedProgress === '' ? pending[index].uploadProgress : Number(reportedProgress);\n\n    return {\n      progress,\n      // Prefer the explicit `UploadRecord.uploadConfirmationPending`. Without it the record is\n      // still live, so 100% can only mean all bytes are sent and confirmation is pending.\n      uploadConfirmationPending:\n        reportedAwaiting === ''\n          ? progress !== undefined && progress >= 100\n          : reportedAwaiting === '1',\n    };\n  });\n\n  const liveEntries = entries.filter((entry) => !!entry);\n  if (!liveEntries.length) return emptyUploadState;\n\n  const values = liveEntries.map(({ progress }) => progress);\n  const known = values.filter((value): value is number => typeof value === 'number');\n\n  return {\n    isUploading: true,\n    // Only report a number once every pending upload has one, so the bar does not jump between\n    // determinate and indeterminate mid-flight.\n    progress:\n      known.length === values.length && known.length\n        ? Math.round(known.reduce((sum, value) => sum + value, 0) / known.length)\n        : undefined,\n    uploadConfirmationPending: liveEntries.some(\n      ({ uploadConfirmationPending }) => uploadConfirmationPending,\n    ),\n  };\n};\n\n/** Single-attachment convenience wrapper around {@link useAttachmentsUploadState}. */\nexport const useAttachmentUploadState = (\n  attachment?: Attachment | LocalAttachment | SharedLocationResponse,\n): AttachmentUploadState =>\n  useAttachmentsUploadState(useMemo(() => [attachment], [attachment]));\n\n// The composer side reads the flag `AttachmentManager` mirrors into `localMetadata`, through\n// `isUploadConfirmationPending` from `stream-chat`. On a message that mirrored value is a frozen\n// snapshot, which is why `useAttachmentsUploadState` reads the live record instead.\n"],"mappings":";;;;;;AA6BA,IAAM,YAAY;AAWlB,IAAM,mBAA0C;CAC9C,aAAa;CACb,2BAA2B;AAC7B;;;;;;;;;;;;;;;AAgBA,IAAa,6BACX,gBAC0B;CAC1B,MAAM,EAAE,WAAW,eAAe;CAElC,MAAM,UAAU,cACR,YAAY,OAAO,eAAe,CAAC,CAAC,KAAK,MAAM,EAAE,aAAa,GACpE,CAAC,WAAW,CACd;CAEA,MAAM,gBAAgB,QAAQ,KAAK,EAAE,SAAS,EAAE,CAAC,CAAC,KAAK,GAAG;CAE1D,MAAM,WAAW,aACd,WAA+B,EAI9B,YAAY,cACT,MAAM,GAAG,CAAC,CACV,KAAK,OAAO;EACX,MAAM,SAAS,MAAM,QAAQ;EAG7B,IAAI,CAAC,QAAQ,OAAO;EAEpB,MAAM,WACJ,OAAO,8BAA8B,KAAA,IACjC,KACA,OAAO,4BACL,MACA;EAER,OAAO,GAAG,OAAO,kBAAkB,GAAG,GAAG;CAC3C,CAAC,CAAC,CACD,KAAK,GAAG,EACb,IACA,CAAC,aAAa,CAChB;CAGA,MAAM,EAAE,eAAe,cAAc,QAAQ,eAAe,OAAO,QAAQ,KAAK,CAAC;CAEjF,IAAI,CA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