@linktr.ee/messaging-react 4.1.0 → 4.1.1-rc-1786771192
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/Card-Be81K6su.cjs +2 -0
- package/dist/{Card-415OfRhw.cjs.map → Card-Be81K6su.cjs.map} +1 -1
- package/dist/Card-Bxat0g1O.cjs +2 -0
- package/dist/Card-Bxat0g1O.cjs.map +1 -0
- package/dist/{Card-DaJtDL7m.js → Card-BzvDr-pU.js} +2 -2
- package/dist/{Card-DaJtDL7m.js.map → Card-BzvDr-pU.js.map} +1 -1
- package/dist/{Card-LPAZ4FjL.js → Card-xYcNcZC_.js} +3 -3
- package/dist/Card-xYcNcZC_.js.map +1 -0
- package/dist/PurchaseStatusBadge-BmqAQEV9.cjs +2 -0
- package/dist/PurchaseStatusBadge-BmqAQEV9.cjs.map +1 -0
- package/dist/{LoadingDots-Ct3WmVlT.js → PurchaseStatusBadge-D1RRsubZ.js} +30 -30
- package/dist/PurchaseStatusBadge-D1RRsubZ.js.map +1 -0
- package/dist/index-CAD8AXBg.cjs +3 -0
- package/dist/index-CAD8AXBg.cjs.map +1 -0
- package/dist/{index-Cxj0F8aQ.js → index-t0Okjl1p.js} +630 -633
- package/dist/index-t0Okjl1p.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.js.map +1 -1
- package/package.json +2 -2
- package/src/components/AttachmentCard/index.tsx +1 -3
- package/src/components/AttachmentCard/utils/icons.ts +2 -2
- package/src/components/ChannelActionsMenu/index.tsx +0 -2
- package/src/components/CustomMessage/LockedAttachment/components/_shared/LockBadge.tsx +0 -2
- package/src/components/CustomMessage/LockedAttachment/index.tsx +0 -1
- package/src/components/CustomMessage/MessageTag.tsx +3 -3
- package/src/components/CustomMessage/StreamAttachmentMessage.tsx +5 -9
- package/src/components/CustomSystemMessage/index.tsx +1 -1
- package/src/components/LinkAttachment/components/_shared/CardThumbnail.tsx +3 -10
- package/src/components/MediaMessage/index.tsx +1 -1
- package/src/components/MessageAttachment/_shared/triggerDownload.ts +0 -2
- package/src/components/MessageAttachment/_shared/useCarousel.ts +0 -2
- package/src/components/MessageAttachment/_shared/useViewer.ts +0 -2
- package/src/components/MessageAttachment/stories/StoryTable.tsx +1 -1
- package/src/stories/mocks.tsx +0 -28
- package/src/testing/createMockMessagingClient.ts +4 -8
- package/src/testing/createMockStreamChatClient.ts +7 -2
- package/src/testing/index.ts +1 -1
- package/dist/Card-415OfRhw.cjs +0 -2
- package/dist/Card-B5ZGxDcH.cjs +0 -2
- package/dist/Card-B5ZGxDcH.cjs.map +0 -1
- package/dist/Card-LPAZ4FjL.js.map +0 -1
- package/dist/LoadingDots-Ct3WmVlT.js.map +0 -1
- package/dist/LoadingDots-D9GGphgM.cjs +0 -2
- package/dist/LoadingDots-D9GGphgM.cjs.map +0 -1
- package/dist/index-B88BeZjY.cjs +0 -3
- package/dist/index-B88BeZjY.cjs.map +0 -1
- package/dist/index-Cxj0F8aQ.js.map +0 -1
- package/src/components/LinkAttachment/components/Composer/index.ts +0 -2
- package/src/components/LinkAttachment/components/Received/index.ts +0 -2
- package/src/components/LinkAttachment/components/Sent/index.ts +0 -2
- package/src/components/MessageBubble/components/Received/index.ts +0 -1
- package/src/components/MessageBubble/components/Sent/index.ts +0 -1
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./index-
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./index-CAD8AXBg.cjs");exports.ActionButton=e.ActionButton;exports.Avatar=e.Avatar;exports.ChannelEmptyState=e.ChannelEmptyState;exports.ChannelList=e.ChannelList;exports.ChannelView=e.ChannelView;exports.CustomMessageProvider=e.CustomMessageProvider;exports.FaqList=e.FaqList;exports.FaqListItem=e.FaqListItem;exports.LinkAttachment=e.LinkAttachment;exports.LockedAttachment=e.LockedAttachment;exports.MediaMessage=e.MediaMessage;exports.MessageAttachment=e.MessageAttachment;exports.MessageBubble=e.MessageBubble;exports.MessagingProvider=e.MessagingProvider;exports.MessagingShell=e.MessagingShell;exports.RichCard=e.RichCard;exports.buildCompactMetaLabel=e.buildCompactMetaLabel;exports.formatFileSize=e.formatFileSize;exports.formatRelativeTime=e.formatRelativeTime;exports.getFileExtensionLabel=e.getFileExtensionLabel;exports.getMessageDisplayText=e.getMessageDisplayText;exports.isLinkAttachment=e.isLinkAttachment;exports.isUuidLike=e.isUuidLike;exports.messageAttachmentGroupPositionFromStream=e.bubbleGroupPositionFromStream;exports.normalizeLanguageCode=e.normalizeLanguageCode;exports.optimizeMessagingAttachmentUrl=e.optimizeMessagingAttachmentUrl;exports.resolveConversationParticipant=e.resolveConversationParticipant;exports.resolveLinkAttachment=e.resolveLinkAttachment;exports.resolveMediaFromMessage=e.resolveMediaFromMessage;exports.resolveParticipantDisplayName=e.resolveParticipantDisplayName;exports.useComposerLocked=e.useComposerLocked;exports.useCustomMessage=e.useCustomMessage;exports.useMessaging=e.useMessaging;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as e, b as t, C as i, c as n, d as o, e as m, F as r, f as l, L as g, h as c, M, i as h, j as L, k as u, l as d, R as p, m as C, n as v, p as A, q as k, s as F, t as b, u as P, v as f, w as x, o as y, x as z, y as S, z as q, B, D, E, G as R } from "./index-
|
|
1
|
+
import { a as e, b as t, C as i, c as n, d as o, e as m, F as r, f as l, L as g, h as c, M, i as h, j as L, k as u, l as d, R as p, m as C, n as v, p as A, q as k, s as F, t as b, u as P, v as f, w as x, o as y, x as z, y as S, z as q, B, D, E, G as R } from "./index-t0Okjl1p.js";
|
|
2
2
|
export {
|
|
3
3
|
e as ActionButton,
|
|
4
4
|
t as Avatar,
|
package/dist/testing.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"testing.cjs","sources":["../src/testing/createMockStreamChatClient.ts","../src/testing/createMockMessagingClient.ts"],"sourcesContent":["import { StreamChat } from 'stream-chat'\n\nimport type { MockMessagingUser } from './createMockMessagingClient'\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nexport interface CreateMockStreamChatClientOptions {\n /**\n * Also replace the connection-dependent client methods (`connectUser`,\n * `disconnectUser`, `userMuteStatus`) with offline no-ops. Needed when the\n * client drives a flow that would otherwise open a WebSocket or throw\n * \"Make sure to await connectUser() first.\" offline. Direct `<Chat client>`\n * rendering (e.g. component stories) does not need this.\n */\n stubConnection?: boolean\n}\n\n/**\n * Builds an offline `StreamChat` for mocks and stories: a real client on a\n * throwaway api key with `userID`/`user` set so `<Chat>` treats it as\n * connected without a backend. The single place that knows how to construct a\n * connectionless Stream client, so a stream-chat version bump only needs\n * updating here rather than in each mock surface.\n */\nexport function createMockStreamChatClient(\n user: MockMessagingUser,\n { stubConnection = false }: CreateMockStreamChatClientOptions = {}\n): StreamChat {\n const client = new StreamChat('mock-api-key', {\n allowServerSideConnect: true,\n })\n client.userID = user.id\n client.user = user as any\n\n if (stubConnection) {\n client.connectUser = async () => ({ me: user }) as any\n client.disconnectUser = async () => undefined\n client.userMuteStatus = (() => false) as any\n }\n\n return client\n}\n\n/* eslint-enable @typescript-eslint/no-explicit-any */\n","import type {\n Channel,\n MessageResponse,\n QueryChannelAPIResponse,\n SendMessageAPIResponse,\n} from 'stream-chat'\nimport { StreamChat } from 'stream-chat'\n\nimport { createMockStreamChatClient } from './createMockStreamChatClient'\n\n/** A participant in the mock conversation. */\nexport interface MockMessagingUser {\n id: string\n name?: string\n image?: string\n}\n\n/**\n * A seed message, authored from the viewer's perspective. `from: 'me'` is the\n * connected user (the viewer); `from: 'them'` is the other participant.\n */\nexport interface MockMessage {\n id?: string\n text?: string\n from: 'me' | 'them'\n /** Stream attachment payloads, rendered by the toolkit's attachment gate. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n attachments?: any[]\n /** e.g. `{ custom_type: 'MESSAGE_WELCOME' }`. */\n metadata?: Record<string, unknown>\n}\n\nexport interface CreateMockMessagingClientOptions {\n /** The connected/viewing user. */\n currentUser: MockMessagingUser\n /** The other party in the direct conversation (e.g. the creator/linker). */\n participant: MockMessagingUser\n /** Seed conversation, oldest-first. */\n messages?: MockMessage[]\n /** Channel id; defaults to `mock-dm`. */\n channelId?: string\n /**\n * Optional canned reply. Called after the viewer sends a message; return the\n * reply text (or a partial message) to have `participant` echo a response, or\n * a falsy value for no reply. Drives the \"send echo\" in `dev:mock-messaging`.\n */\n onSend?: (\n text: string\n ) => string | { text?: string; attachments?: unknown[] } | null | undefined\n}\n\nexport interface MockMessagingClient {\n /** Pass to `<MessagingProvider client={...}>`. */\n client: StreamChat\n /** The seeded direct-conversation channel. */\n channel: Channel\n /** Pass to `<MessagingShell initialParticipantFilter={...}>`. */\n participantFilterId: string\n}\n\nconst REPLY_DELAY_MS = 600\n\n/**\n * Builds an offline Stream client seeded with a single direct conversation, so\n * consumers can render the **real** messaging UI (MessagingProvider →\n * MessagingShell → ChannelView) without a Stream backend — for `dev:mock-*`\n * surfaces and Storybook. It is a real `StreamChat` whose network calls\n * (`connectUser`, `queryChannels`, `channel.watch`, `channel.sendMessage`) are\n * replaced with in-memory behaviour driven by Stream's own channel-state\n * machinery, so rendering fidelity matches production.\n *\n * Ships from `@linktr.ee/messaging-react/testing` and must never be imported by\n * production code.\n */\nexport function createMockMessagingClient({\n currentUser,\n participant,\n messages = [],\n channelId = 'mock-dm',\n onSend,\n}: CreateMockMessagingClientOptions): MockMessagingClient {\n // Offline client marked connected without a WebSocket. `stubConnection` also\n // no-ops connectUser/disconnectUser/userMuteStatus: `MessagingProvider`\n // renders `<Chat client={client}>` directly so it never calls connectUser,\n // and handling the `message.new` events dispatched on send + echo below runs\n // Channel._countMessageAsUnread → client.userMuteStatus, which throws offline.\n const client = createMockStreamChatClient(currentUser, {\n stubConnection: true,\n })\n\n const cid = `messaging:${channelId}`\n\n const toStreamMessage = (\n message: MockMessage,\n index: number\n ): MessageResponse => {\n const author = message.from === 'me' ? currentUser : participant\n // Stagger timestamps oldest-first so the list orders naturally. Must be a\n // Date, not an ISO string: we seed `channel.state.messages` directly\n // (bypassing Stream's wire→Date parsing), and stream-chat-react calls\n // `.getTime()` on `created_at` (e.g. useCooldownTimer / addToMessageList).\n const createdAt = new Date(Date.now() - (messages.length - index) * 60_000)\n return {\n id: message.id ?? `mock-msg-${index}`,\n text: message.text ?? '',\n type: 'regular',\n html: message.text ? `<p>${message.text}</p>` : '',\n user: author,\n attachments: message.attachments ?? [],\n latest_reactions: [],\n own_reactions: [],\n reaction_counts: {},\n reaction_scores: {},\n reply_count: 0,\n status: 'received',\n cid,\n created_at: createdAt,\n updated_at: createdAt,\n mentioned_users: [],\n ...(message.metadata ? { metadata: message.metadata } : {}),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any\n }\n\n const seededMessages = messages.map(toStreamMessage)\n\n const memberState = {\n [currentUser.id]: {\n user: { ...currentUser, is_account: false },\n user_id: currentUser.id,\n role: 'owner',\n is_account: false,\n },\n [participant.id]: {\n user: { ...participant, is_account: true },\n user_id: participant.id,\n role: 'member',\n is_account: true,\n },\n }\n\n const channel = client.channel('messaging', channelId, {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n members: [currentUser.id, participant.id] as any,\n })\n // Read/unread bookkeeping consults channel mute status; without a live\n // connection the real method throws, so report \"not muted\".\n channel.muteStatus = (() => ({\n muted: false,\n createdAt: null,\n expiresAt: null,\n })) as any\n\n // Neutralise the rest of the connection-dependent channel API that\n // stream-chat-react calls during the chat lifecycle. Each of these POSTs to\n // Stream or checks for a live WebSocket and would otherwise throw\n // \"Make sure to await connectUser() first.\" offline. They are fire-and-forget\n // (read receipts, typing) or read-only (pagination, unread) so no-ops are safe.\n /* eslint-disable @typescript-eslint/no-explicit-any */\n channel.markRead = (async () => ({}) as any) as any\n channel.keystroke = (async () => undefined) as any\n channel.stopTyping = (async () => undefined) as any\n channel.sendReaction = (async () => ({}) as any) as any\n channel.deleteReaction = (async () => ({}) as any) as any\n channel.countUnread = (() => 0) as any\n // Pagination: report no older pages so \"load more\" resolves to a no-op.\n channel.query = (async () => ({ messages: [] }) as any) as any\n // Leave/Delete Conversation calls channel.hide(); the real method POSTs to\n // Stream, so no-op it to keep the action working offline.\n channel.hide = (async () => ({}) as any) as any\n /* eslint-enable @typescript-eslint/no-explicit-any */\n\n // Seed state locally instead of fetching. Mirrors the proven ChannelView\n // story mock: override `watch` to populate `state` and return a canned\n // QueryChannelAPIResponse. `stream-chat-react` may call `watch()` again on\n // remount/navigation, so seed only once — otherwise a re-watch would wipe\n // messages added via `sendMessage` + the send-echo reply, resetting the chat.\n let hasSeeded = false\n channel.watch = async () => {\n if (!hasSeeded) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n channel.state.messages = seededMessages as unknown as any[]\n hasSeeded = true\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n channel.state.members = memberState as unknown as any\n return {\n channel: { members: [currentUser.id, participant.id] },\n members: [],\n messages: channel.state.messages,\n watchers: [],\n pinned_messages: [],\n duration: '0ms',\n } as unknown as QueryChannelAPIResponse\n }\n\n const appendMessage = (message: MessageResponse) => {\n // addMessageSorted is Stream's own state mutation (dedupes by id), so the\n // toolkit re-renders through the real channel-state path.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n channel.state.addMessageSorted(message as any)\n client.dispatchEvent({\n type: 'message.new',\n cid,\n message,\n user: message.user ?? undefined,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any)\n }\n\n let sentCount = 0\n let replyCount = 0\n channel.sendMessage = async (message) => {\n const text =\n typeof message === 'string'\n ? message\n : ((message as { text?: string })?.text ?? '')\n const sent = {\n ...toStreamMessage(\n { text, from: 'me', id: `mock-sent-${sentCount++}` },\n seededMessages.length\n ),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ...(typeof message === 'object' ? (message as any) : {}),\n user: currentUser,\n cid,\n } as MessageResponse\n\n // stream-chat-react adds the outgoing message optimistically; addMessageSorted\n // dedupes by id, so confirming here is safe and idempotent.\n appendMessage(sent)\n\n const reply = onSend?.(text)\n if (reply) {\n const replyText = typeof reply === 'string' ? reply : reply.text\n const replyAttachments =\n typeof reply === 'string' ? undefined : reply.attachments\n // Capture a unique id before scheduling: two sends within REPLY_DELAY_MS\n // would otherwise both read the same later `sentCount` at fire time and\n // emit colliding reply ids, so Stream's id-based dedupe drops one echo.\n const replyId = `mock-reply-${replyCount++}`\n setTimeout(() => {\n appendMessage(\n toStreamMessage(\n {\n text: replyText,\n from: 'them',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n attachments: replyAttachments as any,\n id: replyId,\n },\n seededMessages.length\n )\n )\n }, REPLY_DELAY_MS)\n }\n\n return { message: sent } as unknown as SendMessageAPIResponse\n }\n\n // MessagingShell finds the direct conversation via queryChannels; always\n // return the one seeded channel regardless of the filter.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n client.queryChannels = async () => [channel] as any\n\n // Initialise state up-front so first render already has the conversation.\n void channel.watch()\n\n return { client, channel, participantFilterId: participant.id }\n}\n"],"names":["createMockStreamChatClient","user","stubConnection","client","StreamChat","REPLY_DELAY_MS","createMockMessagingClient","currentUser","participant","messages","channelId","onSend","cid","toStreamMessage","message","index","author","createdAt","seededMessages","memberState","channel","hasSeeded","appendMessage","sentCount","replyCount","text","sent","reply","replyText","replyAttachments","replyId"],"mappings":"+GAwBO,SAASA,EACdC,EACA,CAAE,eAAAC,EAAiB,EAAA,EAA6C,CAAA,EACpD,CACZ,MAAMC,EAAS,IAAIC,EAAAA,WAAW,eAAgB,CAC5C,uBAAwB,EAAA,CACzB,EACD,OAAAD,EAAO,OAASF,EAAK,GACrBE,EAAO,KAAOF,EAEVC,IACFC,EAAO,YAAc,UAAa,CAAE,GAAIF,CAAA,GACxCE,EAAO,e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AAM,KACtDE,EACJ,OAAOF,GAAU,SAAW,OAAYA,EAAM,YAI1CG,EAAU,cAAcN,GAAY,GAC1C,WAAW,IAAM,CACfF,EACET,EACE,CACE,KAAMe,EACN,KAAM,OAEN,YAAaC,EACb,GAAIC,CAAA,EAENZ,EAAe,MAAA,CACjB,CAEJ,EAAGb,CAAc,CACnB,CAEA,MAAO,CAAE,QAASqB,CAAA,CACpB,EAKAvB,EAAO,cAAgB,SAAY,CAACiB,CAAO,EAGtCA,EAAQ,MAAA,EAEN,CAAE,OAAAjB,EAAQ,QAAAiB,EAAS,oBAAqBZ,EAAY,EAAA,CAC7D"}
|
|
1
|
+
{"version":3,"file":"testing.cjs","sources":["../src/testing/createMockStreamChatClient.ts","../src/testing/createMockMessagingClient.ts"],"sourcesContent":["import { StreamChat } from 'stream-chat'\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/** A participant in the mock conversation. */\nexport interface MockMessagingUser {\n id: string\n name?: string\n image?: string\n}\n\nexport interface CreateMockStreamChatClientOptions {\n /**\n * Also replace the connection-dependent client methods (`connectUser`,\n * `disconnectUser`, `userMuteStatus`) with offline no-ops. Needed when the\n * client drives a flow that would otherwise open a WebSocket or throw\n * \"Make sure to await connectUser() first.\" offline. Direct `<Chat client>`\n * rendering (e.g. component stories) does not need this.\n */\n stubConnection?: boolean\n}\n\n/**\n * Builds an offline `StreamChat` for mocks and stories: a real client on a\n * throwaway api key with `userID`/`user` set so `<Chat>` treats it as\n * connected without a backend. The single place that knows how to construct a\n * connectionless Stream client, so a stream-chat version bump only needs\n * updating here rather than in each mock surface.\n */\nexport function createMockStreamChatClient(\n user: MockMessagingUser,\n { stubConnection = false }: CreateMockStreamChatClientOptions = {}\n): StreamChat {\n const client = new StreamChat('mock-api-key', {\n allowServerSideConnect: true,\n })\n client.userID = user.id\n client.user = user as any\n\n if (stubConnection) {\n client.connectUser = async () => ({ me: user }) as any\n client.disconnectUser = async () => undefined\n client.userMuteStatus = (() => false) as any\n }\n\n return client\n}\n\n/* eslint-enable @typescript-eslint/no-explicit-any */\n","import type {\n Channel,\n MessageResponse,\n QueryChannelAPIResponse,\n SendMessageAPIResponse,\n} from 'stream-chat'\nimport { StreamChat } from 'stream-chat'\n\nimport {\n createMockStreamChatClient,\n type MockMessagingUser,\n} from './createMockStreamChatClient'\n\n/**\n * A seed message, authored from the viewer's perspective. `from: 'me'` is the\n * connected user (the viewer); `from: 'them'` is the other participant.\n */\nexport interface MockMessage {\n id?: string\n text?: string\n from: 'me' | 'them'\n /** Stream attachment payloads, rendered by the toolkit's attachment gate. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n attachments?: any[]\n /** e.g. `{ custom_type: 'MESSAGE_WELCOME' }`. */\n metadata?: Record<string, unknown>\n}\n\nexport interface CreateMockMessagingClientOptions {\n /** The connected/viewing user. */\n currentUser: MockMessagingUser\n /** The other party in the direct conversation (e.g. the creator/linker). */\n participant: MockMessagingUser\n /** Seed conversation, oldest-first. */\n messages?: MockMessage[]\n /** Channel id; defaults to `mock-dm`. */\n channelId?: string\n /**\n * Optional canned reply. Called after the viewer sends a message; return the\n * reply text (or a partial message) to have `participant` echo a response, or\n * a falsy value for no reply. Drives the \"send echo\" in `dev:mock-messaging`.\n */\n onSend?: (\n text: string\n ) => string | { text?: string; attachments?: unknown[] } | null | undefined\n}\n\nexport interface MockMessagingClient {\n /** Pass to `<MessagingProvider client={...}>`. */\n client: StreamChat\n /** The seeded direct-conversation channel. */\n channel: Channel\n /** Pass to `<MessagingShell initialParticipantFilter={...}>`. */\n participantFilterId: string\n}\n\nconst REPLY_DELAY_MS = 600\n\n/**\n * Builds an offline Stream client seeded with a single direct conversation, so\n * consumers can render the **real** messaging UI (MessagingProvider →\n * MessagingShell → ChannelView) without a Stream backend — for `dev:mock-*`\n * surfaces and Storybook. It is a real `StreamChat` whose network calls\n * (`connectUser`, `queryChannels`, `channel.watch`, `channel.sendMessage`) are\n * replaced with in-memory behaviour driven by Stream's own channel-state\n * machinery, so rendering fidelity matches production.\n *\n * Ships from `@linktr.ee/messaging-react/testing` and must never be imported by\n * production code.\n */\nexport function createMockMessagingClient({\n currentUser,\n participant,\n messages = [],\n channelId = 'mock-dm',\n onSend,\n}: CreateMockMessagingClientOptions): MockMessagingClient {\n // Offline client marked connected without a WebSocket. `stubConnection` also\n // no-ops connectUser/disconnectUser/userMuteStatus: `MessagingProvider`\n // renders `<Chat client={client}>` directly so it never calls connectUser,\n // and handling the `message.new` events dispatched on send + echo below runs\n // Channel._countMessageAsUnread → client.userMuteStatus, which throws offline.\n const client = createMockStreamChatClient(currentUser, {\n stubConnection: true,\n })\n\n const cid = `messaging:${channelId}`\n\n const toStreamMessage = (\n message: MockMessage,\n index: number\n ): MessageResponse => {\n const author = message.from === 'me' ? currentUser : participant\n // Stagger timestamps oldest-first so the list orders naturally. Must be a\n // Date, not an ISO string: we seed `channel.state.messages` directly\n // (bypassing Stream's wire→Date parsing), and stream-chat-react calls\n // `.getTime()` on `created_at` (e.g. useCooldownTimer / addToMessageList).\n const createdAt = new Date(Date.now() - (messages.length - index) * 60_000)\n return {\n id: message.id ?? `mock-msg-${index}`,\n text: message.text ?? '',\n type: 'regular',\n html: message.text ? `<p>${message.text}</p>` : '',\n user: author,\n attachments: message.attachments ?? [],\n latest_reactions: [],\n own_reactions: [],\n reaction_counts: {},\n reaction_scores: {},\n reply_count: 0,\n status: 'received',\n cid,\n created_at: createdAt,\n updated_at: createdAt,\n mentioned_users: [],\n ...(message.metadata ? { metadata: message.metadata } : {}),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any\n }\n\n const seededMessages = messages.map(toStreamMessage)\n\n const memberState = {\n [currentUser.id]: {\n user: { ...currentUser, is_account: false },\n user_id: currentUser.id,\n role: 'owner',\n is_account: false,\n },\n [participant.id]: {\n user: { ...participant, is_account: true },\n user_id: participant.id,\n role: 'member',\n is_account: true,\n },\n }\n\n const channel = client.channel('messaging', channelId, {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n members: [currentUser.id, participant.id] as any,\n })\n // Read/unread bookkeeping consults channel mute status; without a live\n // connection the real method throws, so report \"not muted\".\n channel.muteStatus = (() => ({\n muted: false,\n createdAt: null,\n expiresAt: null,\n })) as any\n\n // Neutralise the rest of the connection-dependent channel API that\n // stream-chat-react calls during the chat lifecycle. Each of these POSTs to\n // Stream or checks for a live WebSocket and would otherwise throw\n // \"Make sure to await connectUser() first.\" offline. They are fire-and-forget\n // (read receipts, typing) or read-only (pagination, unread) so no-ops are safe.\n /* eslint-disable @typescript-eslint/no-explicit-any */\n channel.markRead = (async () => ({}) as any) as any\n channel.keystroke = (async () => undefined) as any\n channel.stopTyping = (async () => undefined) as any\n channel.sendReaction = (async () => ({}) as any) as any\n channel.deleteReaction = (async () => ({}) as any) as any\n channel.countUnread = (() => 0) as any\n // Pagination: report no older pages so \"load more\" resolves to a no-op.\n channel.query = (async () => ({ messages: [] }) as any) as any\n // Leave/Delete Conversation calls channel.hide(); the real method POSTs to\n // Stream, so no-op it to keep the action working offline.\n channel.hide = (async () => ({}) as any) as any\n /* eslint-enable @typescript-eslint/no-explicit-any */\n\n // Seed state locally instead of fetching. Mirrors the proven ChannelView\n // story mock: override `watch` to populate `state` and return a canned\n // QueryChannelAPIResponse. `stream-chat-react` may call `watch()` again on\n // remount/navigation, so seed only once — otherwise a re-watch would wipe\n // messages added via `sendMessage` + the send-echo reply, resetting the chat.\n let hasSeeded = false\n channel.watch = async () => {\n if (!hasSeeded) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n channel.state.messages = seededMessages as unknown as any[]\n hasSeeded = true\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n channel.state.members = memberState as unknown as any\n return {\n channel: { members: [currentUser.id, participant.id] },\n members: [],\n messages: channel.state.messages,\n watchers: [],\n pinned_messages: [],\n duration: '0ms',\n } as unknown as QueryChannelAPIResponse\n }\n\n const appendMessage = (message: MessageResponse) => {\n // addMessageSorted is Stream's own state mutation (dedupes by id), so the\n // toolkit re-renders through the real channel-state path.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n channel.state.addMessageSorted(message as any)\n client.dispatchEvent({\n type: 'message.new',\n cid,\n message,\n user: message.user ?? undefined,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any)\n }\n\n let sentCount = 0\n let replyCount = 0\n channel.sendMessage = async (message) => {\n const text =\n typeof message === 'string'\n ? message\n : ((message as { text?: string })?.text ?? '')\n const sent = {\n ...toStreamMessage(\n { text, from: 'me', id: `mock-sent-${sentCount++}` },\n seededMessages.length\n ),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ...(typeof message === 'object' ? (message as any) : {}),\n user: currentUser,\n cid,\n } as MessageResponse\n\n // stream-chat-react adds the outgoing message optimistically; addMessageSorted\n // dedupes by id, so confirming here is safe and idempotent.\n appendMessage(sent)\n\n const reply = onSend?.(text)\n if (reply) {\n const replyText = typeof reply === 'string' ? reply : reply.text\n const replyAttachments =\n typeof reply === 'string' ? undefined : reply.attachments\n // Capture a unique id before scheduling: two sends within REPLY_DELAY_MS\n // would otherwise both read the same later `sentCount` at fire time and\n // emit colliding reply ids, so Stream's id-based dedupe drops one echo.\n const replyId = `mock-reply-${replyCount++}`\n setTimeout(() => {\n appendMessage(\n toStreamMessage(\n {\n text: replyText,\n from: 'them',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n attachments: replyAttachments as any,\n id: replyId,\n },\n seededMessages.length\n )\n )\n }, REPLY_DELAY_MS)\n }\n\n return { message: sent } as unknown as SendMessageAPIResponse\n }\n\n // MessagingShell finds the direct conversation via queryChannels; always\n // return the one seeded channel regardless of the filter.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n client.queryChannels = async () => [channel] as any\n\n // Initialise state up-front so first render already has the conversation.\n void channel.watch()\n\n return { client, channel, participantFilterId: participant.id }\n}\n"],"names":["createMockStreamChatClient","user","stubConnection","client","StreamChat","REPLY_DELAY_MS","createMockMessagingClient","currentUser","participant","messages","channelId","onSend","cid","toStreamMessage","message","index","author","createdAt","seededMessages","memberState","channel","hasSeeded","appendMessage","sentCount","replyCount","text","sent","reply","replyText","replyAttachments","replyId"],"mappings":"+GA6BO,SAASA,EACdC,EACA,CAAE,eAAAC,EAAiB,EAAA,EAA6C,CAAA,EACpD,CACZ,MAAMC,EAAS,IAAIC,EAAAA,WAAW,eAAgB,CAC5C,uBAAwB,EAAA,CACzB,EACD,OAAAD,EAAO,OAASF,EAAK,GACrBE,EAAO,KAAOF,EAEVC,IACFC,EAAO,YAAc,UAAa,CAAE,GAAIF,CAAA,GACxCE,EAAO,eAAiB,YACxBA,EAAO,gBAAkB,IAAM,KAG1BA,CACT,CCUA,MAAME,EAAiB,IAchB,SAASC,EAA0B,CACxC,YAAAC,EACA,YAAAC,EACA,SAAAC,EAAW,CAAA,EACX,UAAAC,EAAY,UACZ,OAAAC,CACF,EAA0D,CAMxD,MAAMR,EAASH,EAA2BO,EAAa,CACrD,eAAgB,EAAA,CACjB,EAEKK,EAAM,aAAaF,CAAS,GAE5BG,EAAkB,CACtBC,EACAC,IACoB,CACpB,MAAMC,EAASF,EAAQ,OAAS,KAAOP,EAAcC,EAK/CS,EAAY,IAAI,KAAK,KAAK,OAASR,EAAS,OAASM,GAAS,GAAM,EAC1E,MAAO,CACL,GAAID,EAAQ,IAAM,YAAYC,CAAK,GACnC,KAAMD,EAAQ,MAAQ,GACtB,KAAM,UACN,KAAMA,EAAQ,KAAO,MAAMA,EAAQ,IAAI,OAAS,GAChD,KAAME,EACN,YAAaF,EAAQ,aAAe,CAAA,EACpC,iBAAkB,CAAA,EAClB,cAAe,CAAA,EACf,gBAAiB,CAAA,EACjB,gBAAiB,CAAA,EACjB,YAAa,EACb,OAAQ,WACR,IAAAF,EACA,WAAYK,EACZ,WAAYA,EACZ,gBAAiB,CAAA,EACjB,GAAIH,EAAQ,SAAW,CAAE,SAAUA,EAAQ,QAAA,EAAa,CAAA,CAAC,CAG7D,EAEMI,EAAiBT,EAAS,IAAII,CAAe,EAE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X,GAAY,SACfA,GACEA,GAAA,YAAAA,EAA+B,OAAQ,GACzCY,EAAO,CACX,GAAGb,EACD,CAAE,KAAAY,EAAM,KAAM,KAAM,GAAI,aAAaF,GAAW,EAAA,EAChDL,EAAe,MAAA,EAGjB,GAAI,OAAOJ,GAAY,SAAYA,EAAkB,CAAA,EACrD,KAAMP,EACN,IAAAK,CAAA,EAKFU,EAAcI,CAAI,EAElB,MAAMC,EAAQhB,GAAA,YAAAA,EAASc,GACvB,GAAIE,EAAO,CACT,MAAMC,EAAY,OAAOD,GAAU,SAAWA,EAAQA,EAAM,KACtDE,EACJ,OAAOF,GAAU,SAAW,OAAYA,EAAM,YAI1CG,EAAU,cAAcN,GAAY,GAC1C,WAAW,IAAM,CACfF,EACET,EACE,CACE,KAAMe,EACN,KAAM,OAEN,YAAaC,EACb,GAAIC,CAAA,EAENZ,EAAe,MAAA,CACjB,CAEJ,EAAGb,CAAc,CACnB,CAEA,MAAO,CAAE,QAASqB,CAAA,CACpB,EAKAvB,EAAO,cAAgB,SAAY,CAACiB,CAAO,EAGtCA,EAAQ,MAAA,EAEN,CAAE,OAAAjB,EAAQ,QAAAiB,EAAS,oBAAqBZ,EAAY,EAAA,CAC7D"}
|
package/dist/testing.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"testing.js","sources":["../src/testing/createMockStreamChatClient.ts","../src/testing/createMockMessagingClient.ts"],"sourcesContent":["import { StreamChat } from 'stream-chat'\n\nimport type { MockMessagingUser } from './createMockMessagingClient'\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\nexport interface CreateMockStreamChatClientOptions {\n /**\n * Also replace the connection-dependent client methods (`connectUser`,\n * `disconnectUser`, `userMuteStatus`) with offline no-ops. Needed when the\n * client drives a flow that would otherwise open a WebSocket or throw\n * \"Make sure to await connectUser() first.\" offline. Direct `<Chat client>`\n * rendering (e.g. component stories) does not need this.\n */\n stubConnection?: boolean\n}\n\n/**\n * Builds an offline `StreamChat` for mocks and stories: a real client on a\n * throwaway api key with `userID`/`user` set so `<Chat>` treats it as\n * connected without a backend. The single place that knows how to construct a\n * connectionless Stream client, so a stream-chat version bump only needs\n * updating here rather than in each mock surface.\n */\nexport function createMockStreamChatClient(\n user: MockMessagingUser,\n { stubConnection = false }: CreateMockStreamChatClientOptions = {}\n): StreamChat {\n const client = new StreamChat('mock-api-key', {\n allowServerSideConnect: true,\n })\n client.userID = user.id\n client.user = user as any\n\n if (stubConnection) {\n client.connectUser = async () => ({ me: user }) as any\n client.disconnectUser = async () => undefined\n client.userMuteStatus = (() => false) as any\n }\n\n return client\n}\n\n/* eslint-enable @typescript-eslint/no-explicit-any */\n","import type {\n Channel,\n MessageResponse,\n QueryChannelAPIResponse,\n SendMessageAPIResponse,\n} from 'stream-chat'\nimport { StreamChat } from 'stream-chat'\n\nimport { createMockStreamChatClient } from './createMockStreamChatClient'\n\n/** A participant in the mock conversation. */\nexport interface MockMessagingUser {\n id: string\n name?: string\n image?: string\n}\n\n/**\n * A seed message, authored from the viewer's perspective. `from: 'me'` is the\n * connected user (the viewer); `from: 'them'` is the other participant.\n */\nexport interface MockMessage {\n id?: string\n text?: string\n from: 'me' | 'them'\n /** Stream attachment payloads, rendered by the toolkit's attachment gate. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n attachments?: any[]\n /** e.g. `{ custom_type: 'MESSAGE_WELCOME' }`. */\n metadata?: Record<string, unknown>\n}\n\nexport interface CreateMockMessagingClientOptions {\n /** The connected/viewing user. */\n currentUser: MockMessagingUser\n /** The other party in the direct conversation (e.g. the creator/linker). */\n participant: MockMessagingUser\n /** Seed conversation, oldest-first. */\n messages?: MockMessage[]\n /** Channel id; defaults to `mock-dm`. */\n channelId?: string\n /**\n * Optional canned reply. Called after the viewer sends a message; return the\n * reply text (or a partial message) to have `participant` echo a response, or\n * a falsy value for no reply. Drives the \"send echo\" in `dev:mock-messaging`.\n */\n onSend?: (\n text: string\n ) => string | { text?: string; attachments?: unknown[] } | null | undefined\n}\n\nexport interface MockMessagingClient {\n /** Pass to `<MessagingProvider client={...}>`. */\n client: StreamChat\n /** The seeded direct-conversation channel. */\n channel: Channel\n /** Pass to `<MessagingShell initialParticipantFilter={...}>`. */\n participantFilterId: string\n}\n\nconst REPLY_DELAY_MS = 600\n\n/**\n * Builds an offline Stream client seeded with a single direct conversation, so\n * consumers can render the **real** messaging UI (MessagingProvider →\n * MessagingShell → ChannelView) without a Stream backend — for `dev:mock-*`\n * surfaces and Storybook. It is a real `StreamChat` whose network calls\n * (`connectUser`, `queryChannels`, `channel.watch`, `channel.sendMessage`) are\n * replaced with in-memory behaviour driven by Stream's own channel-state\n * machinery, so rendering fidelity matches production.\n *\n * Ships from `@linktr.ee/messaging-react/testing` and must never be imported by\n * production code.\n */\nexport function createMockMessagingClient({\n currentUser,\n participant,\n messages = [],\n channelId = 'mock-dm',\n onSend,\n}: CreateMockMessagingClientOptions): MockMessagingClient {\n // Offline client marked connected without a WebSocket. `stubConnection` also\n // no-ops connectUser/disconnectUser/userMuteStatus: `MessagingProvider`\n // renders `<Chat client={client}>` directly so it never calls connectUser,\n // and handling the `message.new` events dispatched on send + echo below runs\n // Channel._countMessageAsUnread → client.userMuteStatus, which throws offline.\n const client = createMockStreamChatClient(currentUser, {\n stubConnection: true,\n })\n\n const cid = `messaging:${channelId}`\n\n const toStreamMessage = (\n message: MockMessage,\n index: number\n ): MessageResponse => {\n const author = message.from === 'me' ? currentUser : participant\n // Stagger timestamps oldest-first so the list orders naturally. Must be a\n // Date, not an ISO string: we seed `channel.state.messages` directly\n // (bypassing Stream's wire→Date parsing), and stream-chat-react calls\n // `.getTime()` on `created_at` (e.g. useCooldownTimer / addToMessageList).\n const createdAt = new Date(Date.now() - (messages.length - index) * 60_000)\n return {\n id: message.id ?? `mock-msg-${index}`,\n text: message.text ?? '',\n type: 'regular',\n html: message.text ? `<p>${message.text}</p>` : '',\n user: author,\n attachments: message.attachments ?? [],\n latest_reactions: [],\n own_reactions: [],\n reaction_counts: {},\n reaction_scores: {},\n reply_count: 0,\n status: 'received',\n cid,\n created_at: createdAt,\n updated_at: createdAt,\n mentioned_users: [],\n ...(message.metadata ? { metadata: message.metadata } : {}),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any\n }\n\n const seededMessages = messages.map(toStreamMessage)\n\n const memberState = {\n [currentUser.id]: {\n user: { ...currentUser, is_account: false },\n user_id: currentUser.id,\n role: 'owner',\n is_account: false,\n },\n [participant.id]: {\n user: { ...participant, is_account: true },\n user_id: participant.id,\n role: 'member',\n is_account: true,\n },\n }\n\n const channel = client.channel('messaging', channelId, {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n members: [currentUser.id, participant.id] as any,\n })\n // Read/unread bookkeeping consults channel mute status; without a live\n // connection the real method throws, so report \"not muted\".\n channel.muteStatus = (() => ({\n muted: false,\n createdAt: null,\n expiresAt: null,\n })) as any\n\n // Neutralise the rest of the connection-dependent channel API that\n // stream-chat-react calls during the chat lifecycle. Each of these POSTs to\n // Stream or checks for a live WebSocket and would otherwise throw\n // \"Make sure to await connectUser() first.\" offline. They are fire-and-forget\n // (read receipts, typing) or read-only (pagination, unread) so no-ops are safe.\n /* eslint-disable @typescript-eslint/no-explicit-any */\n channel.markRead = (async () => ({}) as any) as any\n channel.keystroke = (async () => undefined) as any\n channel.stopTyping = (async () => undefined) as any\n channel.sendReaction = (async () => ({}) as any) as any\n channel.deleteReaction = (async () => ({}) as any) as any\n channel.countUnread = (() => 0) as any\n // Pagination: report no older pages so \"load more\" resolves to a no-op.\n channel.query = (async () => ({ messages: [] }) as any) as any\n // Leave/Delete Conversation calls channel.hide(); the real method POSTs to\n // Stream, so no-op it to keep the action working offline.\n channel.hide = (async () => ({}) as any) as any\n /* eslint-enable @typescript-eslint/no-explicit-any */\n\n // Seed state locally instead of fetching. Mirrors the proven ChannelView\n // story mock: override `watch` to populate `state` and return a canned\n // QueryChannelAPIResponse. `stream-chat-react` may call `watch()` again on\n // remount/navigation, so seed only once — otherwise a re-watch would wipe\n // messages added via `sendMessage` + the send-echo reply, resetting the chat.\n let hasSeeded = false\n channel.watch = async () => {\n if (!hasSeeded) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n channel.state.messages = seededMessages as unknown as any[]\n hasSeeded = true\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n channel.state.members = memberState as unknown as any\n return {\n channel: { members: [currentUser.id, participant.id] },\n members: [],\n messages: channel.state.messages,\n watchers: [],\n pinned_messages: [],\n duration: '0ms',\n } as unknown as QueryChannelAPIResponse\n }\n\n const appendMessage = (message: MessageResponse) => {\n // addMessageSorted is Stream's own state mutation (dedupes by id), so the\n // toolkit re-renders through the real channel-state path.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n channel.state.addMessageSorted(message as any)\n client.dispatchEvent({\n type: 'message.new',\n cid,\n message,\n user: message.user ?? undefined,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any)\n }\n\n let sentCount = 0\n let replyCount = 0\n channel.sendMessage = async (message) => {\n const text =\n typeof message === 'string'\n ? message\n : ((message as { text?: string })?.text ?? '')\n const sent = {\n ...toStreamMessage(\n { text, from: 'me', id: `mock-sent-${sentCount++}` },\n seededMessages.length\n ),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ...(typeof message === 'object' ? (message as any) : {}),\n user: currentUser,\n cid,\n } as MessageResponse\n\n // stream-chat-react adds the outgoing message optimistically; addMessageSorted\n // dedupes by id, so confirming here is safe and idempotent.\n appendMessage(sent)\n\n const reply = onSend?.(text)\n if (reply) {\n const replyText = typeof reply === 'string' ? reply : reply.text\n const replyAttachments =\n typeof reply === 'string' ? undefined : reply.attachments\n // Capture a unique id before scheduling: two sends within REPLY_DELAY_MS\n // would otherwise both read the same later `sentCount` at fire time and\n // emit colliding reply ids, so Stream's id-based dedupe drops one echo.\n const replyId = `mock-reply-${replyCount++}`\n setTimeout(() => {\n appendMessage(\n toStreamMessage(\n {\n text: replyText,\n from: 'them',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n attachments: replyAttachments as any,\n id: replyId,\n },\n seededMessages.length\n )\n )\n }, REPLY_DELAY_MS)\n }\n\n return { message: sent } as unknown as SendMessageAPIResponse\n }\n\n // MessagingShell finds the direct conversation via queryChannels; always\n // return the one seeded channel regardless of the filter.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n client.queryChannels = async () => [channel] as any\n\n // Initialise state up-front so first render already has the conversation.\n void channel.watch()\n\n return { client, channel, participantFilterId: participant.id }\n}\n"],"names":["createMockStreamChatClient","user","stubConnection","client","StreamChat","REPLY_DELAY_MS","createMockMessagingClient","currentUser","participant","messages","channelId","onSend","cid","toStreamMessage","message","index","author","createdAt","seededMessages","memberState","channel","hasSeeded","appendMessage","sentCount","replyCount","text","sent","reply","replyText","replyAttachments","replyId"],"mappings":";AAwBO,SAASA,EACdC,GACA,EAAE,gBAAAC,IAAiB,GAAA,IAA6C,CAAA,GACpD;AACZ,QAAMC,IAAS,IAAIC,EAAW,gBAAgB;AAAA,IAC5C,wBAAwB;AAAA,EAAA,CACzB;AACD,SAAAD,EAAO,SAASF,EAAK,IACrBE,EAAO,OAAOF,GAEVC,MACFC,EAAO,cAAc,aAAa,EAAE,IAAIF,EAAA,IACxCE,EAAO,iBAAiB;KACxBA,EAAO,kBAAkB,MAAM,MAG1BA;AACT;ACmBA,MAAME,IAAiB;AAchB,SAASC,EAA0B;AAAA,EACxC,aAAAC;AAAA,EACA,aAAAC;AAAA,EACA,UAAAC,IAAW,CAAA;AAAA,EACX,WAAAC,IAAY;AAAA,EACZ,QAAAC;AACF,GAA0D;AAMxD,QAAMR,IAASH,EAA2BO,GAAa;AAAA,IACrD,gBAAgB;AAAA,EAAA,CACjB,GAEKK,IAAM,aAAaF,CAAS,IAE5BG,IAAkB,CACtBC,GACAC,MACoB;AACpB,UAAMC,IAASF,EAAQ,SAAS,OAAOP,IAAcC,GAK/CS,IAAY,IAAI,KAAK,KAAK,SAASR,EAAS,SAASM,KAAS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AAU,WAAWA,IAAQA,EAAM,MACtDE,IACJ,OAAOF,KAAU,WAAW,SAAYA,EAAM,aAI1CG,IAAU,cAAcN,GAAY;AAC1C,iBAAW,MAAM;AACf,QAAAF;AAAA,UACET;AAAA,YACE;AAAA,cACE,MAAMe;AAAA,cACN,MAAM;AAAA;AAAA,cAEN,aAAaC;AAAA,cACb,IAAIC;AAAA,YAAA;AAAA,YAENZ,EAAe;AAAA,UAAA;AAAA,QACjB;AAAA,MAEJ,GAAGb,CAAc;AAAA,IACnB;AAEA,WAAO,EAAE,SAASqB,EAAA;AAAA,EACpB,GAKAvB,EAAO,gBAAgB,YAAY,CAACiB,CAAO,GAGtCA,EAAQ,MAAA,GAEN,EAAE,QAAAjB,GAAQ,SAAAiB,GAAS,qBAAqBZ,EAAY,GAAA;AAC7D;"}
|
|
1
|
+
{"version":3,"file":"testing.js","sources":["../src/testing/createMockStreamChatClient.ts","../src/testing/createMockMessagingClient.ts"],"sourcesContent":["import { StreamChat } from 'stream-chat'\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/** A participant in the mock conversation. */\nexport interface MockMessagingUser {\n id: string\n name?: string\n image?: string\n}\n\nexport interface CreateMockStreamChatClientOptions {\n /**\n * Also replace the connection-dependent client methods (`connectUser`,\n * `disconnectUser`, `userMuteStatus`) with offline no-ops. Needed when the\n * client drives a flow that would otherwise open a WebSocket or throw\n * \"Make sure to await connectUser() first.\" offline. Direct `<Chat client>`\n * rendering (e.g. component stories) does not need this.\n */\n stubConnection?: boolean\n}\n\n/**\n * Builds an offline `StreamChat` for mocks and stories: a real client on a\n * throwaway api key with `userID`/`user` set so `<Chat>` treats it as\n * connected without a backend. The single place that knows how to construct a\n * connectionless Stream client, so a stream-chat version bump only needs\n * updating here rather than in each mock surface.\n */\nexport function createMockStreamChatClient(\n user: MockMessagingUser,\n { stubConnection = false }: CreateMockStreamChatClientOptions = {}\n): StreamChat {\n const client = new StreamChat('mock-api-key', {\n allowServerSideConnect: true,\n })\n client.userID = user.id\n client.user = user as any\n\n if (stubConnection) {\n client.connectUser = async () => ({ me: user }) as any\n client.disconnectUser = async () => undefined\n client.userMuteStatus = (() => false) as any\n }\n\n return client\n}\n\n/* eslint-enable @typescript-eslint/no-explicit-any */\n","import type {\n Channel,\n MessageResponse,\n QueryChannelAPIResponse,\n SendMessageAPIResponse,\n} from 'stream-chat'\nimport { StreamChat } from 'stream-chat'\n\nimport {\n createMockStreamChatClient,\n type MockMessagingUser,\n} from './createMockStreamChatClient'\n\n/**\n * A seed message, authored from the viewer's perspective. `from: 'me'` is the\n * connected user (the viewer); `from: 'them'` is the other participant.\n */\nexport interface MockMessage {\n id?: string\n text?: string\n from: 'me' | 'them'\n /** Stream attachment payloads, rendered by the toolkit's attachment gate. */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n attachments?: any[]\n /** e.g. `{ custom_type: 'MESSAGE_WELCOME' }`. */\n metadata?: Record<string, unknown>\n}\n\nexport interface CreateMockMessagingClientOptions {\n /** The connected/viewing user. */\n currentUser: MockMessagingUser\n /** The other party in the direct conversation (e.g. the creator/linker). */\n participant: MockMessagingUser\n /** Seed conversation, oldest-first. */\n messages?: MockMessage[]\n /** Channel id; defaults to `mock-dm`. */\n channelId?: string\n /**\n * Optional canned reply. Called after the viewer sends a message; return the\n * reply text (or a partial message) to have `participant` echo a response, or\n * a falsy value for no reply. Drives the \"send echo\" in `dev:mock-messaging`.\n */\n onSend?: (\n text: string\n ) => string | { text?: string; attachments?: unknown[] } | null | undefined\n}\n\nexport interface MockMessagingClient {\n /** Pass to `<MessagingProvider client={...}>`. */\n client: StreamChat\n /** The seeded direct-conversation channel. */\n channel: Channel\n /** Pass to `<MessagingShell initialParticipantFilter={...}>`. */\n participantFilterId: string\n}\n\nconst REPLY_DELAY_MS = 600\n\n/**\n * Builds an offline Stream client seeded with a single direct conversation, so\n * consumers can render the **real** messaging UI (MessagingProvider →\n * MessagingShell → ChannelView) without a Stream backend — for `dev:mock-*`\n * surfaces and Storybook. It is a real `StreamChat` whose network calls\n * (`connectUser`, `queryChannels`, `channel.watch`, `channel.sendMessage`) are\n * replaced with in-memory behaviour driven by Stream's own channel-state\n * machinery, so rendering fidelity matches production.\n *\n * Ships from `@linktr.ee/messaging-react/testing` and must never be imported by\n * production code.\n */\nexport function createMockMessagingClient({\n currentUser,\n participant,\n messages = [],\n channelId = 'mock-dm',\n onSend,\n}: CreateMockMessagingClientOptions): MockMessagingClient {\n // Offline client marked connected without a WebSocket. `stubConnection` also\n // no-ops connectUser/disconnectUser/userMuteStatus: `MessagingProvider`\n // renders `<Chat client={client}>` directly so it never calls connectUser,\n // and handling the `message.new` events dispatched on send + echo below runs\n // Channel._countMessageAsUnread → client.userMuteStatus, which throws offline.\n const client = createMockStreamChatClient(currentUser, {\n stubConnection: true,\n })\n\n const cid = `messaging:${channelId}`\n\n const toStreamMessage = (\n message: MockMessage,\n index: number\n ): MessageResponse => {\n const author = message.from === 'me' ? currentUser : participant\n // Stagger timestamps oldest-first so the list orders naturally. Must be a\n // Date, not an ISO string: we seed `channel.state.messages` directly\n // (bypassing Stream's wire→Date parsing), and stream-chat-react calls\n // `.getTime()` on `created_at` (e.g. useCooldownTimer / addToMessageList).\n const createdAt = new Date(Date.now() - (messages.length - index) * 60_000)\n return {\n id: message.id ?? `mock-msg-${index}`,\n text: message.text ?? '',\n type: 'regular',\n html: message.text ? `<p>${message.text}</p>` : '',\n user: author,\n attachments: message.attachments ?? [],\n latest_reactions: [],\n own_reactions: [],\n reaction_counts: {},\n reaction_scores: {},\n reply_count: 0,\n status: 'received',\n cid,\n created_at: createdAt,\n updated_at: createdAt,\n mentioned_users: [],\n ...(message.metadata ? { metadata: message.metadata } : {}),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any\n }\n\n const seededMessages = messages.map(toStreamMessage)\n\n const memberState = {\n [currentUser.id]: {\n user: { ...currentUser, is_account: false },\n user_id: currentUser.id,\n role: 'owner',\n is_account: false,\n },\n [participant.id]: {\n user: { ...participant, is_account: true },\n user_id: participant.id,\n role: 'member',\n is_account: true,\n },\n }\n\n const channel = client.channel('messaging', channelId, {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n members: [currentUser.id, participant.id] as any,\n })\n // Read/unread bookkeeping consults channel mute status; without a live\n // connection the real method throws, so report \"not muted\".\n channel.muteStatus = (() => ({\n muted: false,\n createdAt: null,\n expiresAt: null,\n })) as any\n\n // Neutralise the rest of the connection-dependent channel API that\n // stream-chat-react calls during the chat lifecycle. Each of these POSTs to\n // Stream or checks for a live WebSocket and would otherwise throw\n // \"Make sure to await connectUser() first.\" offline. They are fire-and-forget\n // (read receipts, typing) or read-only (pagination, unread) so no-ops are safe.\n /* eslint-disable @typescript-eslint/no-explicit-any */\n channel.markRead = (async () => ({}) as any) as any\n channel.keystroke = (async () => undefined) as any\n channel.stopTyping = (async () => undefined) as any\n channel.sendReaction = (async () => ({}) as any) as any\n channel.deleteReaction = (async () => ({}) as any) as any\n channel.countUnread = (() => 0) as any\n // Pagination: report no older pages so \"load more\" resolves to a no-op.\n channel.query = (async () => ({ messages: [] }) as any) as any\n // Leave/Delete Conversation calls channel.hide(); the real method POSTs to\n // Stream, so no-op it to keep the action working offline.\n channel.hide = (async () => ({}) as any) as any\n /* eslint-enable @typescript-eslint/no-explicit-any */\n\n // Seed state locally instead of fetching. Mirrors the proven ChannelView\n // story mock: override `watch` to populate `state` and return a canned\n // QueryChannelAPIResponse. `stream-chat-react` may call `watch()` again on\n // remount/navigation, so seed only once — otherwise a re-watch would wipe\n // messages added via `sendMessage` + the send-echo reply, resetting the chat.\n let hasSeeded = false\n channel.watch = async () => {\n if (!hasSeeded) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n channel.state.messages = seededMessages as unknown as any[]\n hasSeeded = true\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n channel.state.members = memberState as unknown as any\n return {\n channel: { members: [currentUser.id, participant.id] },\n members: [],\n messages: channel.state.messages,\n watchers: [],\n pinned_messages: [],\n duration: '0ms',\n } as unknown as QueryChannelAPIResponse\n }\n\n const appendMessage = (message: MessageResponse) => {\n // addMessageSorted is Stream's own state mutation (dedupes by id), so the\n // toolkit re-renders through the real channel-state path.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n channel.state.addMessageSorted(message as any)\n client.dispatchEvent({\n type: 'message.new',\n cid,\n message,\n user: message.user ?? undefined,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } as any)\n }\n\n let sentCount = 0\n let replyCount = 0\n channel.sendMessage = async (message) => {\n const text =\n typeof message === 'string'\n ? message\n : ((message as { text?: string })?.text ?? '')\n const sent = {\n ...toStreamMessage(\n { text, from: 'me', id: `mock-sent-${sentCount++}` },\n seededMessages.length\n ),\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n ...(typeof message === 'object' ? (message as any) : {}),\n user: currentUser,\n cid,\n } as MessageResponse\n\n // stream-chat-react adds the outgoing message optimistically; addMessageSorted\n // dedupes by id, so confirming here is safe and idempotent.\n appendMessage(sent)\n\n const reply = onSend?.(text)\n if (reply) {\n const replyText = typeof reply === 'string' ? reply : reply.text\n const replyAttachments =\n typeof reply === 'string' ? undefined : reply.attachments\n // Capture a unique id before scheduling: two sends within REPLY_DELAY_MS\n // would otherwise both read the same later `sentCount` at fire time and\n // emit colliding reply ids, so Stream's id-based dedupe drops one echo.\n const replyId = `mock-reply-${replyCount++}`\n setTimeout(() => {\n appendMessage(\n toStreamMessage(\n {\n text: replyText,\n from: 'them',\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n attachments: replyAttachments as any,\n id: replyId,\n },\n seededMessages.length\n )\n )\n }, REPLY_DELAY_MS)\n }\n\n return { message: sent } as unknown as SendMessageAPIResponse\n }\n\n // MessagingShell finds the direct conversation via queryChannels; always\n // return the one seeded channel regardless of the filter.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n client.queryChannels = async () => [channel] as any\n\n // Initialise state up-front so first render already has the conversation.\n void channel.watch()\n\n return { client, channel, participantFilterId: participant.id }\n}\n"],"names":["createMockStreamChatClient","user","stubConnection","client","StreamChat","REPLY_DELAY_MS","createMockMessagingClient","currentUser","participant","messages","channelId","onSend","cid","toStreamMessage","message","index","author","createdAt","seededMessages","memberState","channel","hasSeeded","appendMessage","sentCount","replyCount","text","sent","reply","replyText","replyAttachments","replyId"],"mappings":";AA6BO,SAASA,EACdC,GACA,EAAE,gBAAAC,IAAiB,GAAA,IAA6C,CAAA,GACpD;AACZ,QAAMC,IAAS,IAAIC,EAAW,gBAAgB;AAAA,IAC5C,wBAAwB;AAAA,EAAA,CACzB;AACD,SAAAD,EAAO,SAASF,EAAK,IACrBE,EAAO,OAAOF,GAEVC,MACFC,EAAO,cAAc,aAAa,EAAE,IAAIF,EAAA,IACxCE,EAAO,iBAAiB;KACxBA,EAAO,kBAAkB,MAAM,MAG1BA;AACT;ACUA,MAAME,IAAiB;AAchB,SAASC,EAA0B;AAAA,EACxC,aAAAC;AAAA,EACA,aAAAC;AAAA,EACA,UAAAC,IAAW,CAAA;AAAA,EACX,WAAAC,IAAY;AAAA,EACZ,QAAAC;AACF,GAA0D;AAMxD,QAAMR,IAASH,EAA2BO,GAAa;AAAA,IACrD,gBAAgB;AAAA,EAAA,CACjB,GAEKK,IAAM,aAAaF,CAAS,IAE5BG,IAAkB,CACtBC,GACAC,MACoB;AACpB,UAAMC,IAASF,EAAQ,SAAS,OAAOP,IAAcC,GAK/CS,IAAY,IAAI,KAAK,KAAK,SAASR,EAAS,SAASM,KAAS,GAAM;AAC1E,WAAO;AAAA,MACL,IAAID,EAAQ,MAAM,YAAYC,CAAK;AAAA,MACnC,MAAMD,EAAQ,QAAQ;AAAA,MACtB,MAAM;AAAA,MACN,MAAMA,EAAQ,OAAO,MAAMA,EAAQ,IAAI,SAAS;AAAA,MAChD,MAAME;AAAA,MACN,aAAaF,EAAQ,eAAe,CAAA;AAAA,MACpC,kBAAkB,CAAA;AAAA,MAClB,eAAe,CAAA;AAAA,MACf,iBAAiB,CAAA;A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,CAAc;AAAA,IACnB;AAEA,WAAO,EAAE,SAASqB,EAAA;AAAA,EACpB,GAKAvB,EAAO,gBAAgB,YAAY,CAACiB,CAAO,GAGtCA,EAAQ,MAAA,GAEN,EAAE,QAAAjB,GAAQ,SAAAiB,GAAS,qBAAqBZ,EAAY,GAAA;AAC7D;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@linktr.ee/messaging-react",
|
|
3
|
-
"version": "4.1.
|
|
3
|
+
"version": "4.1.1-rc-1786771192",
|
|
4
4
|
"description": "React messaging components built on messaging-core for web applications",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.cjs",
|
|
@@ -50,7 +50,7 @@
|
|
|
50
50
|
"chromatic:local": "yarn storybook:build && chromatic"
|
|
51
51
|
},
|
|
52
52
|
"dependencies": {
|
|
53
|
-
"@linktr.ee/messaging-core": "
|
|
53
|
+
"@linktr.ee/messaging-core": "2.4.0-rc-1786771192",
|
|
54
54
|
"@linktr.ee/messaging-taxonomy": "^0.10.0",
|
|
55
55
|
"@phosphor-icons/react": "^2.1.10"
|
|
56
56
|
},
|
|
@@ -8,12 +8,10 @@ export type {
|
|
|
8
8
|
AttachmentThumbnailProps,
|
|
9
9
|
AttachmentThumbnailVariant,
|
|
10
10
|
} from './Thumbnail'
|
|
11
|
-
export { default as MediaPlayer } from './MediaPlayer'
|
|
12
11
|
export type { MediaPlayerProps } from './MediaPlayer'
|
|
13
|
-
export { renderTypeIcon
|
|
12
|
+
export { renderTypeIcon } from './utils/icons'
|
|
14
13
|
export {
|
|
15
14
|
getSourceType,
|
|
16
|
-
getDocumentIconType,
|
|
17
15
|
type AttachmentSourceType,
|
|
18
16
|
type DocumentIconType,
|
|
19
17
|
} from './utils/mimeType'
|
|
@@ -18,7 +18,7 @@ import React from 'react'
|
|
|
18
18
|
import { getDocumentIconType, getSourceType } from './mimeType'
|
|
19
19
|
import type { AttachmentSourceType } from './mimeType'
|
|
20
20
|
|
|
21
|
-
|
|
21
|
+
const MEDIA_TYPE_ICON: Record<AttachmentSourceType, React.ElementType> =
|
|
22
22
|
{
|
|
23
23
|
video: VideoCameraIcon,
|
|
24
24
|
audio: SpeakerHighIcon,
|
|
@@ -38,7 +38,7 @@ const DOCUMENT_ICON_COMPONENT = {
|
|
|
38
38
|
generic: FileIcon,
|
|
39
39
|
} as const
|
|
40
40
|
|
|
41
|
-
|
|
41
|
+
function getTypeIcon(mimeType: string): React.ElementType {
|
|
42
42
|
const sourceType = getSourceType(mimeType)
|
|
43
43
|
if (sourceType !== 'document') return MEDIA_TYPE_ICON[sourceType]
|
|
44
44
|
return DOCUMENT_ICON_COMPONENT[getDocumentIconType(mimeType)]
|
|
@@ -94,7 +94,6 @@ const LockedAttachment: React.FC<LockedAttachmentProps> = (props) => {
|
|
|
94
94
|
}
|
|
95
95
|
|
|
96
96
|
export default LockedAttachment
|
|
97
|
-
export { default as PurchaseStatusBadge } from './components/_shared/PurchaseStatusBadge'
|
|
98
97
|
export type { PurchaseStatusBadgeProps } from './components/_shared/PurchaseStatusBadge'
|
|
99
98
|
export type {
|
|
100
99
|
PaymentStatus,
|
|
@@ -29,12 +29,12 @@ const SparkleIcon = ({ size = 15 }: { size?: number }) => (
|
|
|
29
29
|
)
|
|
30
30
|
|
|
31
31
|
/** Check if a message is a tip based on metadata */
|
|
32
|
-
|
|
32
|
+
const isTipMessage = (message: LocalMessage): boolean => {
|
|
33
33
|
return message.metadata?.custom_type === MESSAGE_CUSTOM_TYPE.TIP
|
|
34
34
|
}
|
|
35
35
|
|
|
36
36
|
/** Check if a message is a paid message based on metadata */
|
|
37
|
-
|
|
37
|
+
const isPaidMessage = (message: LocalMessage): boolean => {
|
|
38
38
|
return message.metadata?.custom_type === MESSAGE_CUSTOM_TYPE.PAID
|
|
39
39
|
}
|
|
40
40
|
|
|
@@ -63,7 +63,7 @@ export const isMediaAttachmentMessage = (message: LocalMessage): boolean => {
|
|
|
63
63
|
}
|
|
64
64
|
|
|
65
65
|
/** Check if a message has a tip or paid tag (shared layout, distinct copy) */
|
|
66
|
-
|
|
66
|
+
const isTipOrPaidMessage = (message: LocalMessage): boolean => {
|
|
67
67
|
return isTipMessage(message) || isPaidMessage(message)
|
|
68
68
|
}
|
|
69
69
|
|
|
@@ -10,6 +10,7 @@ import {
|
|
|
10
10
|
import { optimizeMessagingAttachmentUrl } from '../../utils/cdnImageUrl'
|
|
11
11
|
import LinkAttachment from '../LinkAttachment'
|
|
12
12
|
import { isPlayableMedia } from '../LinkAttachment/components/_shared/CardThumbnail'
|
|
13
|
+
import { isLinkAttachment } from '../MediaMessage'
|
|
13
14
|
import MessageAttachment from '../MessageAttachment'
|
|
14
15
|
import type { BubbleGroupPosition } from '../MessageAttachment/types'
|
|
15
16
|
|
|
@@ -26,7 +27,7 @@ function trimToUndefined(value?: string | null): string | undefined {
|
|
|
26
27
|
return trimmed ? trimmed : undefined
|
|
27
28
|
}
|
|
28
29
|
|
|
29
|
-
|
|
30
|
+
function normalizeLinkUrl(url: string): string {
|
|
30
31
|
return url
|
|
31
32
|
.trim()
|
|
32
33
|
.replace(/^https?:\/\//i, '')
|
|
@@ -89,7 +90,7 @@ export function linkCardPropsFromStreamAttachment(a: Attachment) {
|
|
|
89
90
|
} as const
|
|
90
91
|
}
|
|
91
92
|
|
|
92
|
-
|
|
93
|
+
function getAttachmentMediaKind(
|
|
93
94
|
attachment: Attachment
|
|
94
95
|
): StreamMediaKind | null {
|
|
95
96
|
if (isLinkAttachment(attachment)) return null
|
|
@@ -112,11 +113,6 @@ export function getAttachmentMediaKind(
|
|
|
112
113
|
return null
|
|
113
114
|
}
|
|
114
115
|
|
|
115
|
-
export function isLinkAttachment(a: Attachment): boolean {
|
|
116
|
-
const ogScrapeUrl = trimToUndefined(a.og_scrape_url)
|
|
117
|
-
return a.type === 'link' || (!!ogScrapeUrl && !a.asset_url)
|
|
118
|
-
}
|
|
119
|
-
|
|
120
116
|
export function buildOrderedAttachmentSegments(
|
|
121
117
|
attachments: Attachment[] | undefined
|
|
122
118
|
): AttachmentSegment[] {
|
|
@@ -159,13 +155,13 @@ export function buildOrderedAttachmentSegments(
|
|
|
159
155
|
return segments
|
|
160
156
|
}
|
|
161
157
|
|
|
162
|
-
|
|
158
|
+
function countMediaSegmentBubbles(
|
|
163
159
|
segments: AttachmentSegment[]
|
|
164
160
|
): number {
|
|
165
161
|
return segments.filter((segment) => segment.type === 'media').length
|
|
166
162
|
}
|
|
167
163
|
|
|
168
|
-
|
|
164
|
+
function bubblePositionInRun(
|
|
169
165
|
index: number,
|
|
170
166
|
total: number,
|
|
171
167
|
streamPosition: BubbleGroupPosition
|
|
@@ -19,7 +19,7 @@ const DM_AGENT_SYSTEM_MESSAGE_FALLBACK_TEXT: Record<DmAgentSystemType, string> =
|
|
|
19
19
|
* explicitly added. Keep in sync with the mobile client (cerberus
|
|
20
20
|
* `CustomMessageSystem`); there is no shared package between the two surfaces.
|
|
21
21
|
*/
|
|
22
|
-
|
|
22
|
+
const SHOW_SYSTEM_MESSAGE_TIMESTAMP_TYPES: readonly AgeSafetySystemType[] =
|
|
23
23
|
['SYSTEM_AGE_SAFETY_BLOCKED']
|
|
24
24
|
|
|
25
25
|
const AGE_SAFETY_SYSTEM_MESSAGE_FALLBACK_TEXT: Record<
|
|
@@ -69,17 +69,10 @@ export const isPlayableMedia = (mimeType?: string, sourceUrl?: string) => {
|
|
|
69
69
|
/**
|
|
70
70
|
* Background colour the LinkAttachment cards switch to when the source is
|
|
71
71
|
* audio — flat neutral around the native `<audio>` chrome regardless of
|
|
72
|
-
* the dark / light variant.
|
|
73
|
-
*
|
|
74
|
-
*
|
|
75
|
-
* measuring contrast against whatever surface it lands on, and contrast needs
|
|
76
|
-
* channels rather than a class name. They are written out twice on purpose:
|
|
77
|
-
* Tailwind only generates utilities it can find as complete literals when it
|
|
78
|
-
* scans `dist`, so building the class from the constant
|
|
79
|
-
* (`` `bg-[${AUDIO_BG}]` ``) would emit nothing at all. `chinContrast.test.ts`
|
|
80
|
-
* asserts the two stay in step.
|
|
72
|
+
* the dark / light variant. Written as a complete literal because Tailwind
|
|
73
|
+
* only generates utilities it can find verbatim when it scans `dist`, so
|
|
74
|
+
* building the class from a hex constant would emit nothing at all.
|
|
81
75
|
*/
|
|
82
|
-
export const AUDIO_BG = '#F2F3F4'
|
|
83
76
|
export const AUDIO_BG_CLASS = 'bg-[#F2F3F4]'
|
|
84
77
|
|
|
85
78
|
/**
|
|
@@ -114,7 +114,7 @@ const LinkCard: React.FC<{
|
|
|
114
114
|
}
|
|
115
115
|
|
|
116
116
|
export function isLinkAttachment(a: Attachment): boolean {
|
|
117
|
-
return a.type === 'link' || (!!a.og_scrape_url && !a.asset_url)
|
|
117
|
+
return a.type === 'link' || (!!a.og_scrape_url?.trim() && !a.asset_url)
|
|
118
118
|
}
|
|
119
119
|
|
|
120
120
|
export function resolveLinkAttachment(
|
|
@@ -23,7 +23,7 @@ export const StoryHeading: React.FC<{
|
|
|
23
23
|
</div>
|
|
24
24
|
)
|
|
25
25
|
|
|
26
|
-
|
|
26
|
+
const ColumnHeader: React.FC<{ children: React.ReactNode }> = ({
|
|
27
27
|
children,
|
|
28
28
|
}) => (
|
|
29
29
|
<p className="mb-3 text-xs font-medium uppercase tracking-wide text-black/40">
|
package/src/stories/mocks.tsx
CHANGED
|
@@ -13,20 +13,6 @@ const mockUser = {
|
|
|
13
13
|
const createMockClient = () =>
|
|
14
14
|
createMockStreamChatClient(mockUser, { stubConnection: true })
|
|
15
15
|
|
|
16
|
-
export const MockChatProvider: React.FC<{ children: React.ReactNode }> = ({
|
|
17
|
-
children,
|
|
18
|
-
}) => {
|
|
19
|
-
const [client] = React.useState(() => createMockClient())
|
|
20
|
-
|
|
21
|
-
React.useEffect(() => {
|
|
22
|
-
return () => {
|
|
23
|
-
client.disconnectUser().catch(console.error)
|
|
24
|
-
}
|
|
25
|
-
}, [client])
|
|
26
|
-
|
|
27
|
-
return <Chat client={client}>{children}</Chat>
|
|
28
|
-
}
|
|
29
|
-
|
|
30
16
|
// Create a mock chat provider with pre-populated channels
|
|
31
17
|
export const MockChatProviderWithChannels: React.FC<{
|
|
32
18
|
children: React.ReactNode
|
|
@@ -145,17 +131,3 @@ export const mockParticipants = [
|
|
|
145
131
|
image: 'https://i.pravatar.cc/150?img=6',
|
|
146
132
|
},
|
|
147
133
|
]
|
|
148
|
-
|
|
149
|
-
// Mock participant source for testing
|
|
150
|
-
export const mockParticipantSource = {
|
|
151
|
-
loadParticipants: async (options?: { search?: string; limit?: number }) => {
|
|
152
|
-
const searchTerm = options?.search || ''
|
|
153
|
-
const filtered = mockParticipants.filter((p) =>
|
|
154
|
-
p.name.toLowerCase().includes(searchTerm.toLowerCase())
|
|
155
|
-
)
|
|
156
|
-
return {
|
|
157
|
-
participants: filtered,
|
|
158
|
-
hasMore: false,
|
|
159
|
-
}
|
|
160
|
-
},
|
|
161
|
-
}
|
|
@@ -6,14 +6,10 @@ import type {
|
|
|
6
6
|
} from 'stream-chat'
|
|
7
7
|
import { StreamChat } from 'stream-chat'
|
|
8
8
|
|
|
9
|
-
import {
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
id: string
|
|
14
|
-
name?: string
|
|
15
|
-
image?: string
|
|
16
|
-
}
|
|
9
|
+
import {
|
|
10
|
+
createMockStreamChatClient,
|
|
11
|
+
type MockMessagingUser,
|
|
12
|
+
} from './createMockStreamChatClient'
|
|
17
13
|
|
|
18
14
|
/**
|
|
19
15
|
* A seed message, authored from the viewer's perspective. `from: 'me'` is the
|
|
@@ -1,9 +1,14 @@
|
|
|
1
1
|
import { StreamChat } from 'stream-chat'
|
|
2
2
|
|
|
3
|
-
import type { MockMessagingUser } from './createMockMessagingClient'
|
|
4
|
-
|
|
5
3
|
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
6
4
|
|
|
5
|
+
/** A participant in the mock conversation. */
|
|
6
|
+
export interface MockMessagingUser {
|
|
7
|
+
id: string
|
|
8
|
+
name?: string
|
|
9
|
+
image?: string
|
|
10
|
+
}
|
|
11
|
+
|
|
7
12
|
export interface CreateMockStreamChatClientOptions {
|
|
8
13
|
/**
|
|
9
14
|
* Also replace the connection-dependent client methods (`connectUser`,
|
package/src/testing/index.ts
CHANGED
|
@@ -3,8 +3,8 @@ export {
|
|
|
3
3
|
type CreateMockMessagingClientOptions,
|
|
4
4
|
type MockMessage,
|
|
5
5
|
type MockMessagingClient,
|
|
6
|
-
type MockMessagingUser,
|
|
7
6
|
} from './createMockMessagingClient'
|
|
7
|
+
export type { MockMessagingUser } from './createMockStreamChatClient'
|
|
8
8
|
|
|
9
9
|
// The rolled-up `testing.d.ts` hoists the ambient `declare module 'stream-chat'`
|
|
10
10
|
// augmentation from stream-custom-data, but rollupTypes only bundles the types
|
package/dist/Card-415OfRhw.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),h=require("@phosphor-icons/react"),d=require("./LoadingDots-D9GGphgM.cjs"),x=require("classnames"),r=({children:s})=>e.jsxs("div",{className:"flex items-center gap-1 text-xs font-medium",children:[e.jsx(h.LockSimpleIcon,{className:"size-3.5 shrink-0 opacity-55",weight:"fill","aria-hidden":!0}),s]}),c=({variant:s="dark"})=>{const a=s==="dark"?"bg-white/25":"bg-black/15";return e.jsxs("div",{className:"flex flex-col gap-2 str-chat__message-text my-1 animate-pulse","aria-hidden":!0,children:[e.jsx("div",{className:x("h-3 w-40 rounded-full",a)}),e.jsx("div",{className:x("h-3 w-24 rounded-full",a)})]})},n=({isMine:s,children:a,className:i})=>e.jsx("div",{className:x("message-locked-attachment-text","relative flex min-w-[225px] max-w-[280px] flex-col gap-1 rounded-[1.5rem] px-4 py-3","text-[0.875rem] leading-[1.3125rem] tracking-[0.14px]",s?"bg-[#1e2330] text-white":"bg-[#f2f1ef] text-black","shadow-[0_1px_2px_rgba(0,0,0,0.08)]",i),children:a}),u=({renderedText:s,amountText:a,placeholderAmountText:i,onDismiss:t})=>e.jsxs(n,{isMine:!0,className:"pr-8",children:[s||e.jsx(c,{variant:"dark"}),e.jsx(r,{children:e.jsx("span",{className:a?"text-white/55":"text-white/30",children:a||i})}),t&&e.jsx("button",{type:"button",onClick:t,className:"absolute right-3 top-3 flex size-6 shrink-0 items-center justify-center rounded-full bg-white/10 text-white hover:bg-white/15","aria-label":"Dismiss attachment",children:e.jsx(h.XIcon,{className:"size-3",weight:"bold"})})]}),j=({amountText:s,placeholderAmountText:a})=>e.jsxs(n,{isMine:!1,children:[e.jsx(c,{variant:"light"}),e.jsx(r,{children:e.jsx("span",{className:"opacity-55",children:s||a})})]}),m=({renderedText:s,amountText:a,paymentStatus:i="pending"})=>{const t=i==="paid";return e.jsxs(n,{isMine:!0,children:[t&&s?s:e.jsx(c,{variant:"dark"}),e.jsxs(r,{children:[a&&e.jsx("span",{className:"text-white/55",children:a}),e.jsx(d.PurchaseStatusBadge,{isMine:!0,paymentStatus:i})]})]})},f=({renderedText:s,amountText:a,paymentStatus:i,onUnlockClick:t,isUnlocking:l=!1})=>{if(i==="paid"&&s)return e.jsxs(n,{isMine:!1,children:[s,e.jsxs(r,{children:[a!=null&&e.jsx("span",{className:"opacity-55",children:a}),e.jsx(d.PurchaseStatusBadge,{isMine:!1,paymentStatus:"paid"})]})]});const o=l?"Unlocking message.":"Unlock this message.";return e.jsx(n,{isMine:!1,children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex flex-1 flex-col gap-2",children:[e.jsx(c,{variant:"light"}),e.jsx("span",{className:"sr-only","aria-live":"polite",children:o}),e.jsx(r,{children:a!=null&&e.jsx("span",{className:"opacity-55",children:a})})]}),e.jsx("button",{type:"button",onClick:t,disabled:l,"aria-label":l?"Unlocking message":"Unlock message","aria-busy":l,title:l?"Unlocking message":"Unlock message",className:"flex size-10 shrink-0 items-center justify-center rounded-full bg-[#121110] text-white hover:bg-[#2a2928]",children:l?e.jsx(d.LoadingDots,{}):e.jsx(h.LockSimpleIcon,{className:"size-4",weight:"fill","aria-hidden":!0})})]})})},g=s=>s.isDraft?e.jsx(u,{...s}):s.isPreview?e.jsx(j,{...s}):s.isMine?e.jsx(m,{...s}):e.jsx(f,{...s});exports.default=g;
|
|
2
|
-
//# sourceMappingURL=Card-415OfRhw.cjs.map
|
package/dist/Card-B5ZGxDcH.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("react/jsx-runtime"),m=require("@phosphor-icons/react"),h=require("react"),g=require("classnames"),v=require("./index-B88BeZjY.cjs"),M=require("./LoadingDots-D9GGphgM.cjs"),I=({variant:t,title:s,placeholderTitle:n="Attachment title",mimeType:i,detail:a,statusBadge:r,action:o,icon:u,trailingAction:d})=>{const l=t==="dark",c=s||n,x=!s,f=u??v.renderTypeIcon(i,{className:g("size-5 shrink-0",l?"text-white/55":"text-black/55"),weight:"regular"});return e.jsxs("div",{className:"px-4 py-3",children:[e.jsxs("div",{className:"flex items-end gap-3",children:[e.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[c.trim()!==""&&e.jsx("p",{className:g("truncate text-base font-medium leading-6",{"text-black/90":!l&&!x,"text-black/30":!l&&x,"text-white/30":l&&x,"text-white":l&&!x}),children:c}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1",children:[f,a!=null&&a!==""&&e.jsx("span",{className:g("text-xs font-medium",l?"text-white/55":"text-black/55"),children:a}),r]})]}),d&&e.jsx("div",{className:"shrink-0",children:d})]}),o]})},S=({paymentStatus:t,mimeType:s,isPlayable:n,isLocked:i})=>{const a=s?v.getSourceType(s):void 0,o=(n??(a==="video"||a==="audio"))&&!i?m.PlayIcon:t==="paid"?m.LockOpenIcon:m.LockSimpleIcon;return e.jsx("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center",children:e.jsx("div",{className:g("flex size-12 items-center justify-center rounded-full bg-black/30 text-white",o===m.PlayIcon&&"group-hover:bg-black/40"),children:e.jsx(o,{className:"size-6",weight:"fill"})})})};function q(t){const s=v.getSourceType(t.mimeType);return s==="video"||s==="audio"}const A=({variant:t,gallery:s,title:n,showLocked:i,paymentStatus:a,topRight:r})=>{const[o,u]=h.useState(0),d=s.length,l=Math.min(o,d-1),c=s[l],x=q(c),f=v.optimizeMessagingAttachmentUrl(c.thumbnailUrl),p=k=>{k.stopPropagation(),u(y=>Math.max(0,y-1))},N=k=>{k.stopPropagation(),u(y=>Math.min(d-1,y+1))},b=l===0,j=l===d-1,w=t==="dark";return e.jsxs("div",{className:g("group relative overflow-hidden rounded-t-md",i?"aspect-[337/386]":void 0),children:[i?e.jsx("div",{className:g("absolute inset-0",w?"bg-white/10":"bg-black/5"),children:c.thumbnailUrl&&e.jsx("img",{src:f??c.thumbnailUrl,alt:"","aria-hidden":!0,draggable:!1,className:"absolute inset-0 h-full w-full scale-110 object-cover blur-[40px]"})}):e.jsx(v.AttachmentThumbnail,{mimeType:c.mimeType,sourceUrl:c.sourceUrl,thumbnailUrl:c.thumbnailUrl,title:n,variant:t,mediaPlayerProps:{autoPlay:!0}},l),i&&e.jsx(S,{paymentStatus:a,isPlayable:x,isLocked:i}),d>1&&e.jsxs(h.Fragment,{children:[e.jsx("button",{type:"button",onClick:p,disabled:b,"aria-label":"Previous item",className:g("absolute left-3 top-1/2 -translate-y-1/2 flex size-7 items-center justify-center rounded-full bg-black/30 text-white transition-opacity",b?"opacity-40":"hover:bg-black/40"),children:e.jsx(m.CaretLeftIcon,{className:"size-5",weight:"bold"})}),e.jsx("button",{type:"button",onClick:N,disabled:j,"aria-label":"Next item",className:g("absolute right-3 top-1/2 -translate-y-1/2 flex size-7 items-center justify-center rounded-full bg-black/30 text-white transition-opacity",j?"opacity-40":"hover:bg-black/40"),children:e.jsx(m.CaretRightIcon,{className:"size-5",weight:"bold"})}),e.jsx("div",{className:"pointer-events-none absolute bottom-10 left-1/2 flex size-8 -translate-x-1/2 items-center justify-center rounded-full bg-black/30",children:e.jsxs("span",{className:"text-xs font-medium leading-none text-white",children:[l+1,"/",d]})})]}),r&&e.jsx("div",{className:"pointer-events-auto absolute right-3 top-3 z-10",children:r})]})},O=({variant:t,mimeType:s,thumbnailUrl:n,title:i,source:a,showLocked:r,paymentStatus:o,topRight:u,containedImage:d=!1})=>{const l=r||a==null?void 0:a.sourceUrl,c=r?n:(a==null?void 0:a.thumbnailUrl)??n,x=v.optimizeMessagingAttachmentUrl(c),f=t==="dark";return e.jsxs("div",{className:"relative overflow-hidden rounded-t-md",children:[r?e.jsxs("div",{className:g("relative aspect-video overflow-hidden",f?"bg-white/10":"bg-black/5"),children:[c?e.jsx("img",{src:x??c,alt:"","aria-hidden":!0,draggable:!1,className:"absolute inset-0 h-full w-full scale-110 object-cover blur-[40px]"}):e.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:v.renderTypeIcon(s,{className:f?"size-12 text-white/20":"size-12 text-black/20",weight:"regular"})}),e.jsx(S,{paymentStatus:o,mimeType:s,isLocked:r})]}):e.jsx(v.AttachmentThumbnail,{mimeType:s,sourceUrl:l,thumbnailUrl:c,title:i,variant:t,containedImage:d,mediaPlayerProps:l?{autoPlay:!0,loop:!0,controls:!0,muted:!1}:void 0}),u&&e.jsx("div",{className:"pointer-events-auto absolute right-3 top-3 z-10",children:u})]})},P=t=>t.length>=2,z=t=>e.jsx(m.ImagesIcon,{className:t==="dark"?"size-5 shrink-0 text-white/55":"size-5 shrink-0 text-black/55"}),U=({variant:t,gallery:s,title:n,showLocked:i,paymentStatus:a,mimeType:r,thumbnailUrl:o,source:u,containedImage:d,topRight:l})=>P(s)?e.jsx(A,{variant:t,gallery:s,title:n,showLocked:i,paymentStatus:a,topRight:l}):e.jsx(O,{variant:t,mimeType:r,thumbnailUrl:o,title:n,source:u,showLocked:i,paymentStatus:a,topRight:l,containedImage:d}),T=({variant:t,children:s,rootRef:n,"data-testid":i})=>e.jsx("div",{ref:n,"data-testid":i,className:g("relative w-[280px] select-none overflow-hidden rounded-md",t==="dark"?"bg-[#1e2330]":"bg-white","shadow-[0_1px_2px_rgba(0,0,0,0.08)]"),children:s}),C=({onToggle:t,isBusy:s,isPreviewVisible:n,children:i})=>t?e.jsx("div",{role:"button",tabIndex:s?-1:0,"aria-label":"Toggle preview","aria-busy":s,"aria-pressed":n,"aria-disabled":s||void 0,onClick:s?void 0:t,onKeyDown:a=>{s||a.target===a.currentTarget&&(a.key==="Enter"||a.key===" ")&&(a.preventDefault(),t())},className:s?"block w-full text-left":"block w-full cursor-pointer text-left",children:i}):e.jsx(h.Fragment,{children:i});function R({isGallery:t,onFetchSource:s,onPreviewClick:n}){const[i,a]=h.useState(),[r,o]=h.useState(!1),[u,d]=h.useState(!1),l=h.useRef(!1),c=h.useCallback(async()=>{if(n==null||n(),r){o(!1);return}if(t){o(!0);return}if(i){o(!0);return}if(s&&!l.current){l.current=!0,d(!0);try{const f=await s();f&&(a(f),o(!0))}finally{l.current=!1,d(!1)}}},[r,t,i,n,s]),x=t||s!=null||n!=null?c:void 0;return{source:i,isPreviewVisible:r,isLoadingPreview:u,handleToggle:c,togglePreview:x}}function G({paymentStatus:t,onFetchSource:s,onUnlockClick:n}){const[i,a]=h.useState(),r=h.useRef(null),o=h.useRef(!1),u=h.useRef(s);u.current=s;const d=h.useCallback(async()=>{var c;if(!o.current){o.current=!0;try{const x=await((c=u.current)==null?void 0:c.call(u));x&&a(x)}finally{o.current=!1}}},[]),l=h.useCallback(()=>{t==="paid"?d():n==null||n()},[t,d,n]);return h.useEffect(()=>{if(!r.current||t!=="paid"||i!==void 0)return;const c=new IntersectionObserver(([x])=>{x.isIntersecting&&(d(),c.disconnect())},{threshold:1});return c.observe(r.current),()=>c.disconnect()},[t,i,d]),{source:i,cardRef:r,handleUnlockClick:l}}const D="mt-3 inline-flex h-10 w-full items-center justify-center gap-2 rounded-full bg-[#121110] px-4 text-sm font-medium leading-none text-white hover:bg-[#2a2928]",_=({isLocked:t,sourceUrl:s,redeemUrl:n,onUnlockClicked:i,onDownloadClicked:a,isUnlocking:r=!1})=>{if(t&&i!=null)return e.jsx("button",{type:"button",onClick:i,disabled:r,"aria-label":r?"Unlocking":"Unlock","aria-busy":r,title:r?"Unlocking":"Unlock",className:D,children:r?e.jsx(M.LoadingDots,{}):e.jsxs(h.Fragment,{children:[e.jsx(m.LockSimpleIcon,{className:"size-4",weight:"fill"}),"Unlock"]})});if(!t&&a!=null){const o=n??s;return o!=null?e.jsxs("a",{href:o,"aria-label":"Download",target:"_blank",rel:"noopener noreferrer",onClick:a,className:`${D} !text-white`,children:[e.jsx(m.DownloadSimpleIcon,{className:"size-4",weight:"bold"}),"Download"]}):e.jsxs("button",{type:"button",onClick:a,"aria-label":"Download",className:D,children:[e.jsx(m.DownloadSimpleIcon,{className:"size-4",weight:"bold"}),"Download"]})}return null},E=({title:t,mimeType:s="application/octet-stream",thumbnailUrl:n,detail:i,amountText:a,placeholderTitle:r,placeholderAmountText:o,gallery:u=[],onDismiss:d,onPreviewClick:l,onFetchSource:c,onEditClick:x})=>{const f=P(u),{source:p,isPreviewVisible:N,isLoadingPreview:b,togglePreview:j}=R({isGallery:f,onFetchSource:c,onPreviewClick:l}),w=!N,k=b,y=e.jsxs(h.Fragment,{children:[e.jsx("span",{className:"text-xs font-medium text-white/55",children:"•"}),e.jsx("span",{className:a?"text-xs font-medium text-white/55":"text-xs font-medium text-white/30",children:a||o})]}),L=d?e.jsx("button",{type:"button",onClick:V=>{V.stopPropagation(),d()},className:"flex size-6 items-center justify-center rounded-full bg-[#121110] text-white","aria-label":"Dismiss attachment",children:e.jsx(m.XIcon,{className:"size-3",weight:"bold"})}):void 0,B=x?e.jsx("button",{type:"button",onClick:x,"aria-label":"Edit attachment",className:"flex size-10 items-center justify-center rounded-full bg-white/10 text-white hover:bg-white/15",children:e.jsx(m.PencilSimpleIcon,{className:"size-5",weight:"regular"})}):void 0;return e.jsxs(T,{variant:"dark",children:[e.jsx(C,{onToggle:j,isBusy:k,isPreviewVisible:!w,children:e.jsx(U,{variant:"dark",gallery:u,title:t,showLocked:w,mimeType:s,thumbnailUrl:n,source:p,topRight:L})}),e.jsx(I,{variant:"dark",title:t,placeholderTitle:r,mimeType:s,detail:i,statusBadge:y,icon:f?z("dark"):void 0,trailingAction:B})]})},$=({title:t,mimeType:s="application/octet-stream",thumbnailUrl:n,detail:i,amountText:a,placeholderTitle:r,placeholderAmountText:o,gallery:u=[]})=>{const d=P(u),l=e.jsxs(h.Fragment,{children:[e.jsx("span",{className:"text-xs font-medium text-black/55",children:"•"}),e.jsx("span",{className:a?"text-xs font-medium text-black/55":"text-xs font-medium text-black/30",children:a||o})]});return e.jsxs(T,{variant:"light",children:[e.jsx(U,{variant:"light",gallery:u,title:t,showLocked:!0,mimeType:s,thumbnailUrl:n}),e.jsx(I,{variant:"light",title:t,placeholderTitle:r,mimeType:s,detail:i,statusBadge:l,icon:d?z("light"):void 0})]})},K=({title:t,mimeType:s="application/octet-stream",thumbnailUrl:n,detail:i,amountText:a,placeholderTitle:r,paymentStatus:o="pending",gallery:u=[],onPreviewClick:d,onFetchSource:l})=>{const c=P(u),{source:x,isPreviewVisible:f,isLoadingPreview:p,togglePreview:N}=R({isGallery:c,onFetchSource:l,onPreviewClick:d}),b=!f,j=p;return e.jsxs(T,{variant:"dark",children:[e.jsx(C,{onToggle:N,isBusy:j,isPreviewVisible:!b,children:e.jsx(U,{variant:"dark",gallery:u,title:t,showLocked:b,paymentStatus:o,mimeType:s,thumbnailUrl:n,source:x})}),e.jsx(I,{variant:"dark",title:t,placeholderTitle:r,mimeType:s,detail:i,statusBadge:e.jsx(M.PurchaseStatusBadge,{isMine:!0,paymentStatus:o,amountText:a}),icon:c?z("dark"):void 0})]})},X=({title:t,amountText:s,thumbnailUrl:n,mimeType:i="application/octet-stream",detail:a,gallery:r=[],onUnlockClick:o,onFetchSource:u,onDownloadClick:d,paymentStatus:l,isUnlocking:c=!1})=>{const x=P(r),{source:f,cardRef:p,handleUnlockClick:N}=G({paymentStatus:l,onFetchSource:u,onUnlockClick:o}),b=f==null?void 0:f.sourceUrl,j=f==null?void 0:f.redeemUrl,w=x?l!=="paid":b===void 0,k=v.getSourceType(i),y=x?void 0:b;return e.jsxs(T,{variant:"light",rootRef:p,"data-testid":"locked-attachment",children:[e.jsx(U,{variant:"light",gallery:r,title:t,showLocked:w,paymentStatus:l,mimeType:i,thumbnailUrl:n,source:f,containedImage:!w&&k==="document"}),e.jsx(I,{variant:"light",title:t,mimeType:i,detail:a,statusBadge:e.jsx(M.PurchaseStatusBadge,{isMine:!1,paymentStatus:l,amountText:s}),icon:x?z("light"):void 0,action:e.jsx(_,{isLocked:w,isUnlocking:c,sourceUrl:y,redeemUrl:j,onUnlockClicked:N,onDownloadClicked:d})})]})},F=t=>t.isDraft?e.jsx(E,{...t}):t.isPreview?e.jsx($,{...t}):t.isMine?e.jsx(K,{...t}):e.jsx(X,{...t});exports.default=F;
|
|
2
|
-
//# sourceMappingURL=Card-B5ZGxDcH.cjs.map
|