@linktr.ee/messaging-react 4.4.0-rc-1787552892 → 4.4.0

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.
Files changed (45) hide show
  1. package/dist/AttachmentCard-BqwWgqvi.js +369 -0
  2. package/dist/AttachmentCard-BqwWgqvi.js.map +1 -0
  3. package/dist/AttachmentCard-DUrgGRsq.cjs +2 -0
  4. package/dist/AttachmentCard-DUrgGRsq.cjs.map +1 -0
  5. package/dist/Card-BIbqWagz.cjs +2 -0
  6. package/dist/Card-BIbqWagz.cjs.map +1 -0
  7. package/dist/Card-C7uLQbYz.js +105 -0
  8. package/dist/Card-C7uLQbYz.js.map +1 -0
  9. package/dist/Card-Ds1FMcUj.cjs +2 -0
  10. package/dist/Card-Ds1FMcUj.cjs.map +1 -0
  11. package/dist/Card-f51K6V7Y.js +498 -0
  12. package/dist/Card-f51K6V7Y.js.map +1 -0
  13. package/dist/LoadingDots-BSk_UeS0.cjs +2 -0
  14. package/dist/LoadingDots-BSk_UeS0.cjs.map +1 -0
  15. package/dist/LoadingDots-B_WiXBeQ.js +73 -0
  16. package/dist/LoadingDots-B_WiXBeQ.js.map +1 -0
  17. package/dist/assets/index.css +2 -1
  18. package/dist/index.cjs +3 -2
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.js +3925 -38
  21. package/dist/index.js.map +1 -1
  22. package/dist/rolldown-runtime-BocRIvOZ.cjs +1 -0
  23. package/dist/testing.cjs +2 -2
  24. package/dist/testing.cjs.map +1 -1
  25. package/dist/testing.js +106 -118
  26. package/dist/testing.js.map +1 -1
  27. package/package.json +5 -5
  28. package/src/components/MessageAttachment/_shared/MediaStackGrid.test.tsx +28 -0
  29. package/src/components/MessageAttachment/_shared/MediaStackGrid.tsx +22 -14
  30. package/dist/Card-Be81K6su.cjs +0 -2
  31. package/dist/Card-Be81K6su.cjs.map +0 -1
  32. package/dist/Card-BzvDr-pU.js +0 -112
  33. package/dist/Card-BzvDr-pU.js.map +0 -1
  34. package/dist/Card-ChcosZir.js +0 -1034
  35. package/dist/Card-ChcosZir.js.map +0 -1
  36. package/dist/Card-KU88ECCR.cjs +0 -2
  37. package/dist/Card-KU88ECCR.cjs.map +0 -1
  38. package/dist/PurchaseStatusBadge-BmqAQEV9.cjs +0 -2
  39. package/dist/PurchaseStatusBadge-BmqAQEV9.cjs.map +0 -1
  40. package/dist/PurchaseStatusBadge-D1RRsubZ.js +0 -59
  41. package/dist/PurchaseStatusBadge-D1RRsubZ.js.map +0 -1
  42. package/dist/index-Dg235rZT.js +0 -5364
  43. package/dist/index-Dg235rZT.js.map +0 -1
  44. package/dist/index-WEbnLVHC.cjs +0 -3
  45. package/dist/index-WEbnLVHC.cjs.map +0 -1
@@ -0,0 +1 @@
1
+ var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,s)=>(s=n==null?{}:e(i(n)),o(r||!n||!n.__esModule||!a.call(n,`default`)?t(s,`default`,{value:n,enumerable:!0}):s,n));Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return s}});
package/dist/testing.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const b=require("stream-chat");function v(s,{stubConnection:n=!1}={}){const a=new b.StreamChat("mock-api-key",{allowServerSideConnect:!0});return a.userID=s.id,a.user=s,n&&(a.connectUser=async()=>({me:s}),a.disconnectUser=async()=>{},a.userMuteStatus=(()=>!1)),a}const w=600;function x({currentUser:s,participant:n,messages:a=[],channelId:y="mock-dm",onSend:d}){const r=v(s,{stubConnection:!0}),u=`messaging:${y}`,l=(t,c)=>{const i=t.from==="me"?s:n,o=new Date(Date.now()-(a.length-c)*6e4);return{id:t.id??`mock-msg-${c}`,text:t.text??"",type:"regular",html:t.text?`<p>${t.text}</p>`:"",user:i,attachments:t.attachments??[],latest_reactions:[],own_reactions:[],reaction_counts:{},reaction_scores:{},reply_count:0,status:"received",cid:u,created_at:o,updated_at:o,mentioned_users:[],...t.metadata?{metadata:t.metadata}:{}}},m=a.map(l),_={[s.id]:{user:{...s,is_account:!1},user_id:s.id,role:"owner",is_account:!1},[n.id]:{user:{...n,is_account:!0},user_id:n.id,role:"member",is_account:!0}},e=r.channel("messaging",y,{members:[s.id,n.id]});e.muteStatus=()=>({muted:!1,createdAt:null,expiresAt:null}),e.markRead=(async()=>({})),e.keystroke=(async()=>{}),e.stopTyping=(async()=>{}),e.sendReaction=(async()=>({})),e.deleteReaction=(async()=>({})),e.countUnread=(()=>0),e.query=(async()=>({messages:[]})),e.hide=(async()=>({}));let h=!1;e.watch=async()=>(h||(e.state.messages=m,h=!0),e.state.members=_,{channel:{members:[s.id,n.id]},members:[],messages:e.state.messages,watchers:[],pinned_messages:[],duration:"0ms"});const f=t=>{e.state.addMessageSorted(t),r.dispatchEvent({type:"message.new",cid:u,message:t,user:t.user??void 0})};let p=0,g=0;return e.sendMessage=async t=>{const c=typeof t=="string"?t:(t==null?void 0:t.text)??"",i={...l({text:c,from:"me",id:`mock-sent-${p++}`},m.length),...typeof t=="object"?t:{},user:s,cid:u};f(i);const o=d==null?void 0:d(c);if(o){const M=typeof o=="string"?o:o.text,k=typeof o=="string"?void 0:o.attachments,C=`mock-reply-${g++}`;setTimeout(()=>{f(l({text:M,from:"them",attachments:k,id:C},m.length))},w)}return{message:i}},r.queryChannels=async()=>[e],e.watch(),{client:r,channel:e,participantFilterId:n.id}}exports.createMockMessagingClient=x;
2
- //# sourceMappingURL=testing.cjs.map
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});let e=require("stream-chat");function t(t,{stubConnection:n=!1}={}){let r=new e.StreamChat(`mock-api-key`,{allowServerSideConnect:!0});return r.userID=t.id,r.user=t,n&&(r.connectUser=async()=>({me:t}),r.disconnectUser=async()=>void 0,r.userMuteStatus=(()=>!1)),r}var n=600;function r({currentUser:e,participant:r,messages:i=[],channelId:a=`mock-dm`,onSend:o}){let s=t(e,{stubConnection:!0}),c=`messaging:${a}`,l=(t,n)=>{let a=t.from===`me`?e:r,o=new Date(Date.now()-(i.length-n)*6e4);return{id:t.id??`mock-msg-${n}`,text:t.text??``,type:`regular`,html:t.text?`<p>${t.text}</p>`:``,user:a,attachments:t.attachments??[],latest_reactions:[],own_reactions:[],reaction_counts:{},reaction_scores:{},reply_count:0,status:`received`,cid:c,created_at:o,updated_at:o,mentioned_users:[],...t.metadata?{metadata:t.metadata}:{}}},u=i.map(l),d={[e.id]:{user:{...e,is_account:!1},user_id:e.id,role:`owner`,is_account:!1},[r.id]:{user:{...r,is_account:!0},user_id:r.id,role:`member`,is_account:!0}},f=s.channel(`messaging`,a,{members:[e.id,r.id]});f.muteStatus=()=>({muted:!1,createdAt:null,expiresAt:null}),f.markRead=(async()=>({})),f.keystroke=(async()=>void 0),f.stopTyping=(async()=>void 0),f.sendReaction=(async()=>({})),f.deleteReaction=(async()=>({})),f.countUnread=(()=>0),f.query=(async()=>({messages:[]})),f.hide=(async()=>({}));let p=!1;f.watch=async()=>(p||=(f.state.messages=u,!0),f.state.members=d,{channel:{members:[e.id,r.id]},members:[],messages:f.state.messages,watchers:[],pinned_messages:[],duration:`0ms`});let m=e=>{f.state.addMessageSorted(e),s.dispatchEvent({type:`message.new`,cid:c,message:e,user:e.user??void 0})},h=0,g=0;return f.sendMessage=async t=>{let r=typeof t==`string`?t:t?.text??``,i={...l({text:r,from:`me`,id:`mock-sent-${h++}`},u.length),...typeof t==`object`?t:{},user:e,cid:c};m(i);let a=o?.(r);if(a){let e=typeof a==`string`?a:a.text,t=typeof a==`string`?void 0:a.attachments,r=`mock-reply-${g++}`;setTimeout(()=>{m(l({text:e,from:`them`,attachments:t,id:r},u.length))},n)}return{message:i}},s.queryChannels=async()=>[f],f.watch(),{client:s,channel:f,participantFilterId:r.id}}exports.createMockMessagingClient=r;
2
+ //# sourceMappingURL=testing.cjs.map
@@ -1 +1 @@
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 })\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,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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"}
1
+ {"version":3,"file":"testing.cjs","names":[],"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 })\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, particip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,CACT,IAAM,EAAY,OAAO,GAAU,SAAW,EAAQ,EAAM,KACtD,EACJ,OAAO,GAAU,SAAW,IAAA,GAAY,EAAM,YAI1C,EAAU,cAAc,MAC9B,eAAiB,CACf,EACE,EACE,CACE,KAAM,EACN,KAAM,OAEN,YAAa,EACb,GAAI,CACN,EACA,EAAe,MACjB,CACF,CACF,EAAG,CAAc,CACnB,CAEA,MAAO,CAAE,QAAS,CAAK,CACzB,EAKA,EAAO,cAAgB,SAAY,CAAC,CAAO,EAG3C,EAAa,MAAM,EAEZ,CAAE,SAAQ,UAAS,oBAAqB,EAAY,EAAG,CAChE"}
package/dist/testing.js CHANGED
@@ -1,120 +1,108 @@
1
- import { StreamChat as g } from "stream-chat";
2
- function v(s, { stubConnection: n = !1 } = {}) {
3
- const a = new g("mock-api-key", {
4
- allowServerSideConnect: !0
5
- });
6
- return a.userID = s.id, a.user = s, n && (a.connectUser = async () => ({ me: s }), a.disconnectUser = async () => {
7
- }, a.userMuteStatus = (() => !1)), a;
1
+ import { StreamChat as e } from "stream-chat";
2
+ //#region src/testing/createMockStreamChatClient.ts
3
+ function t(t, { stubConnection: n = !1 } = {}) {
4
+ let r = new e("mock-api-key", { allowServerSideConnect: !0 });
5
+ return r.userID = t.id, r.user = t, n && (r.connectUser = async () => ({ me: t }), r.disconnectUser = async () => void 0, r.userMuteStatus = (() => !1)), r;
8
6
  }
9
- const C = 600;
10
- function S({
11
- currentUser: s,
12
- participant: n,
13
- messages: a = [],
14
- channelId: y = "mock-dm",
15
- onSend: d
16
- }) {
17
- const r = v(s, {
18
- stubConnection: !0
19
- }), u = `messaging:${y}`, l = (t, c) => {
20
- const i = t.from === "me" ? s : n, o = new Date(Date.now() - (a.length - c) * 6e4);
21
- return {
22
- id: t.id ?? `mock-msg-${c}`,
23
- text: t.text ?? "",
24
- type: "regular",
25
- html: t.text ? `<p>${t.text}</p>` : "",
26
- user: i,
27
- attachments: t.attachments ?? [],
28
- latest_reactions: [],
29
- own_reactions: [],
30
- reaction_counts: {},
31
- reaction_scores: {},
32
- reply_count: 0,
33
- status: "received",
34
- cid: u,
35
- created_at: o,
36
- updated_at: o,
37
- mentioned_users: [],
38
- ...t.metadata ? { metadata: t.metadata } : {}
39
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
40
- };
41
- }, m = a.map(l), p = {
42
- [s.id]: {
43
- user: { ...s, is_account: !1 },
44
- user_id: s.id,
45
- role: "owner",
46
- is_account: !1
47
- },
48
- [n.id]: {
49
- user: { ...n, is_account: !0 },
50
- user_id: n.id,
51
- role: "member",
52
- is_account: !0
53
- }
54
- }, e = r.channel("messaging", y, {
55
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
56
- members: [s.id, n.id]
57
- });
58
- e.muteStatus = () => ({
59
- muted: !1,
60
- createdAt: null,
61
- expiresAt: null
62
- }), e.markRead = (async () => ({})), e.keystroke = (async () => {
63
- }), e.stopTyping = (async () => {
64
- }), e.sendReaction = (async () => ({})), e.deleteReaction = (async () => ({})), e.countUnread = (() => 0), e.query = (async () => ({ messages: [] })), e.hide = (async () => ({}));
65
- let h = !1;
66
- e.watch = async () => (h || (e.state.messages = m, h = !0), e.state.members = p, {
67
- channel: { members: [s.id, n.id] },
68
- members: [],
69
- messages: e.state.messages,
70
- watchers: [],
71
- pinned_messages: [],
72
- duration: "0ms"
73
- });
74
- const f = (t) => {
75
- e.state.addMessageSorted(t), r.dispatchEvent({
76
- type: "message.new",
77
- cid: u,
78
- message: t,
79
- user: t.user ?? void 0
80
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
81
- });
82
- };
83
- let _ = 0, k = 0;
84
- return e.sendMessage = async (t) => {
85
- const c = typeof t == "string" ? t : (t == null ? void 0 : t.text) ?? "", i = {
86
- ...l(
87
- { text: c, from: "me", id: `mock-sent-${_++}` },
88
- m.length
89
- ),
90
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
91
- ...typeof t == "object" ? t : {},
92
- user: s,
93
- cid: u
94
- };
95
- f(i);
96
- const o = d == null ? void 0 : d(c);
97
- if (o) {
98
- const w = typeof o == "string" ? o : o.text, x = typeof o == "string" ? void 0 : o.attachments, M = `mock-reply-${k++}`;
99
- setTimeout(() => {
100
- f(
101
- l(
102
- {
103
- text: w,
104
- from: "them",
105
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
106
- attachments: x,
107
- id: M
108
- },
109
- m.length
110
- )
111
- );
112
- }, C);
113
- }
114
- return { message: i };
115
- }, r.queryChannels = async () => [e], e.watch(), { client: r, channel: e, participantFilterId: n.id };
7
+ //#endregion
8
+ //#region src/testing/createMockMessagingClient.ts
9
+ var n = 600;
10
+ function r({ currentUser: e, participant: r, messages: i = [], channelId: a = "mock-dm", onSend: o }) {
11
+ let s = t(e, { stubConnection: !0 }), c = `messaging:${a}`, l = (t, n) => {
12
+ let a = t.from === "me" ? e : r, o = /* @__PURE__ */ new Date(Date.now() - (i.length - n) * 6e4);
13
+ return {
14
+ id: t.id ?? `mock-msg-${n}`,
15
+ text: t.text ?? "",
16
+ type: "regular",
17
+ html: t.text ? `<p>${t.text}</p>` : "",
18
+ user: a,
19
+ attachments: t.attachments ?? [],
20
+ latest_reactions: [],
21
+ own_reactions: [],
22
+ reaction_counts: {},
23
+ reaction_scores: {},
24
+ reply_count: 0,
25
+ status: "received",
26
+ cid: c,
27
+ created_at: o,
28
+ updated_at: o,
29
+ mentioned_users: [],
30
+ ...t.metadata ? { metadata: t.metadata } : {}
31
+ };
32
+ }, u = i.map(l), d = {
33
+ [e.id]: {
34
+ user: {
35
+ ...e,
36
+ is_account: !1
37
+ },
38
+ user_id: e.id,
39
+ role: "owner",
40
+ is_account: !1
41
+ },
42
+ [r.id]: {
43
+ user: {
44
+ ...r,
45
+ is_account: !0
46
+ },
47
+ user_id: r.id,
48
+ role: "member",
49
+ is_account: !0
50
+ }
51
+ }, f = s.channel("messaging", a, { members: [e.id, r.id] });
52
+ f.muteStatus = () => ({
53
+ muted: !1,
54
+ createdAt: null,
55
+ expiresAt: null
56
+ }), f.markRead = (async () => ({})), f.keystroke = (async () => void 0), f.stopTyping = (async () => void 0), f.sendReaction = (async () => ({})), f.deleteReaction = (async () => ({})), f.countUnread = (() => 0), f.query = (async () => ({ messages: [] })), f.hide = (async () => ({}));
57
+ let p = !1;
58
+ f.watch = async () => (p ||= (f.state.messages = u, !0), f.state.members = d, {
59
+ channel: { members: [e.id, r.id] },
60
+ members: [],
61
+ messages: f.state.messages,
62
+ watchers: [],
63
+ pinned_messages: [],
64
+ duration: "0ms"
65
+ });
66
+ let m = (e) => {
67
+ f.state.addMessageSorted(e), s.dispatchEvent({
68
+ type: "message.new",
69
+ cid: c,
70
+ message: e,
71
+ user: e.user ?? void 0
72
+ });
73
+ }, h = 0, g = 0;
74
+ return f.sendMessage = async (t) => {
75
+ let r = typeof t == "string" ? t : t?.text ?? "", i = {
76
+ ...l({
77
+ text: r,
78
+ from: "me",
79
+ id: `mock-sent-${h++}`
80
+ }, u.length),
81
+ ...typeof t == "object" ? t : {},
82
+ user: e,
83
+ cid: c
84
+ };
85
+ m(i);
86
+ let a = o?.(r);
87
+ if (a) {
88
+ let e = typeof a == "string" ? a : a.text, t = typeof a == "string" ? void 0 : a.attachments, r = `mock-reply-${g++}`;
89
+ setTimeout(() => {
90
+ m(l({
91
+ text: e,
92
+ from: "them",
93
+ attachments: t,
94
+ id: r
95
+ }, u.length));
96
+ }, n);
97
+ }
98
+ return { message: i };
99
+ }, s.queryChannels = async () => [f], f.watch(), {
100
+ client: s,
101
+ channel: f,
102
+ participantFilterId: r.id
103
+ };
116
104
  }
117
- export {
118
- S as createMockMessagingClient
119
- };
120
- //# sourceMappingURL=testing.js.map
105
+ //#endregion
106
+ export { r as createMockMessagingClient };
107
+
108
+ //# sourceMappingURL=testing.js.map
@@ -1 +1 @@
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 })\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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F,GAAW,GAAA;AAAA,QAChDL,EAAe;AAAA,MAAA;AAAA;AAAA,MAGjB,GAAI,OAAOJ,KAAY,WAAYA,IAAkB,CAAA;AAAA,MACrD,MAAMP;AAAA,MACN,KAAAK;AAAA,IAAA;AAKF,IAAAU,EAAcI,CAAI;AAElB,UAAMC,IAAQhB,KAAA,gBAAAA,EAASc;AACvB,QAAIE,GAAO;AACT,YAAMC,IAAY,OAAOD,KAAU,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","names":[],"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 })\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"],"mappings":";;AA6BA,SAAgB,EACd,GACA,EAAE,oBAAiB,OAA6C,CAAC,GACrD;CACZ,IAAM,IAAS,IAAI,EAAW,gBAAgB,EAC5C,wBAAwB,GAC1B,CAAC;CAUD,OATA,EAAO,SAAS,EAAK,IACrB,EAAO,OAAO,GAEV,MACF,EAAO,cAAc,aAAa,EAAE,IAAI,EAAK,IAC7C,EAAO,iBAAiB,YAAY,KAAA,GACpC,EAAO,wBAAwB,MAG1B;AACT;;;ACUA,IAAM,IAAiB;AAcvB,SAAgB,EAA0B,EACxC,gBACA,gBACA,cAAW,CAAC,GACZ,eAAY,WACZ,aACwD;CAMxD,IAAM,IAAS,EAA2B,GAAa,EACrD,gBAAgB,GAClB,CAAC,GAEK,IAAM,aAAa,KAEnB,KACJ,GACA,MACoB;EACpB,IAAM,IAAS,EAAQ,SAAS,OAAO,IAAc,GAK/C,oBAAY,IAAI,KAAK,KAAK,IAAI,KAAK,EAAS,SAAS,KAAS,GAAM;EAC1E,OAAO;GACL,IAAI,EAAQ,MAAM,YAAY;GAC9B,MAAM,EAAQ,QAAQ;GACtB,MAAM;GACN,MAAM,EAAQ,OAAO,MAAM,EAAQ,KAAK,QAAQ;GAChD,MAAM;GACN,aAAa,EAAQ,eAAe,CAAC;GACrC,kBAAkB,CAAC;GACnB,eAAe,CAAC;GAChB,iBAAiB,CAAC;GAClB,iBAAiB,CAAC;GAClB,aAAa;GACb,QAAQ;GACR;GACA,YAAY;GACZ,YAAY;GACZ,iBAAiB,CAAC;GAClB,GAAI,EAAQ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AAY;EACvC,IAAM,IACJ,OAAO,KAAY,WACf,IACE,GAA+B,QAAQ,IACzC,IAAO;GACX,GAAG,EACD;IAAE;IAAM,MAAM;IAAM,IAAI,aAAa;GAAc,GACnD,EAAe,MACjB;GAEA,GAAI,OAAO,KAAY,WAAY,IAAkB,CAAC;GACtD,MAAM;GACN;EACF;EAIA,EAAc,CAAI;EAElB,IAAM,IAAQ,IAAS,CAAI;EAC3B,IAAI,GAAO;GACT,IAAM,IAAY,OAAO,KAAU,WAAW,IAAQ,EAAM,MACtD,IACJ,OAAO,KAAU,WAAW,KAAA,IAAY,EAAM,aAI1C,IAAU,cAAc;GAC9B,iBAAiB;IACf,EACE,EACE;KACE,MAAM;KACN,MAAM;KAEN,aAAa;KACb,IAAI;IACN,GACA,EAAe,MACjB,CACF;GACF,GAAG,CAAc;EACnB;EAEA,OAAO,EAAE,SAAS,EAAK;CACzB,GAKA,EAAO,gBAAgB,YAAY,CAAC,CAAO,GAG3C,EAAa,MAAM,GAEZ;EAAE;EAAQ;EAAS,qBAAqB,EAAY;CAAG;AAChE"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@linktr.ee/messaging-react",
3
- "version": "4.4.0-rc-1787552892",
3
+ "version": "4.4.0",
4
4
  "description": "React messaging components built on messaging-core for web applications",
5
5
  "type": "module",
6
6
  "main": "dist/index.cjs",
@@ -50,8 +50,8 @@
50
50
  "chromatic:local": "yarn storybook:build && chromatic"
51
51
  },
52
52
  "dependencies": {
53
- "@linktr.ee/messaging-core": "2.5.0-rc-1787552892",
54
- "@linktr.ee/messaging-taxonomy": "^0.10.0",
53
+ "@linktr.ee/messaging-core": "^2.5.0",
54
+ "@linktr.ee/messaging-taxonomy": "^0.11.0",
55
55
  "@phosphor-icons/react": "^2.1.10"
56
56
  },
57
57
  "devDependencies": {
@@ -68,7 +68,7 @@
68
68
  "@testing-library/user-event": "^14.5.1",
69
69
  "@types/react": "^18.3.24",
70
70
  "@types/react-dom": "^18.3.7",
71
- "@vitejs/plugin-react": "^4.2.1",
71
+ "@vitejs/plugin-react": "^5.2.0",
72
72
  "@vitest/ui": "^4.1.10",
73
73
  "autoprefixer": "^10.4.20",
74
74
  "chromatic": "^17.4.0",
@@ -83,7 +83,7 @@
83
83
  "tailwindcss": "^3.4.17",
84
84
  "tailwindcss-animate": "^1.0.7",
85
85
  "typescript": "5.9.2",
86
- "vite": "^6.0.7",
86
+ "vite": "^8.2.1",
87
87
  "vite-plugin-dts": "^3.7.0",
88
88
  "vitest": "^4.1.10"
89
89
  },
@@ -47,6 +47,34 @@ describe('MediaStackGrid', () => {
47
47
  })
48
48
  })
49
49
 
50
+ it.each([
51
+ [2, '+3', 'tile 2'],
52
+ [3, '+2', 'tile 3'],
53
+ ])(
54
+ 'shows overflow on the last visible tile when maxVisible is %s',
55
+ (maxVisible, badge, lastTile) => {
56
+ const { container } = renderWithProviders(
57
+ <MediaStackGrid tiles={tiles(5)} maxVisible={maxVisible} />
58
+ )
59
+ expect(container.querySelectorAll('span')).toHaveLength(maxVisible)
60
+ expect(screen.getByText(badge)).toBeInTheDocument()
61
+ expect(screen.getByText(badge).parentElement).toHaveTextContent(lastTile)
62
+ }
63
+ )
64
+
65
+ it('shows overflow on the single visible tile', () => {
66
+ const { container } = renderWithProviders(
67
+ <MediaStackGrid tiles={tiles(3)} maxVisible={1} />
68
+ )
69
+ expect(container.querySelectorAll('span')).toHaveLength(1)
70
+ expect(screen.getByText('+2').parentElement).toHaveTextContent('tile 1')
71
+ })
72
+
73
+ it('does not show overflow when all tiles are visible', () => {
74
+ renderWithProviders(<MediaStackGrid tiles={tiles(3)} maxVisible={3} />)
75
+ expect(screen.queryByText(/^\+/)).toBeNull()
76
+ })
77
+
50
78
  it('renders activatable buttons with labels and indexes', () => {
51
79
  const onActivate = vi.fn()
52
80
  renderWithProviders(
@@ -133,6 +133,18 @@ const MediaStackGrid: React.FC<MediaStackGridProps> = ({
133
133
 
134
134
  const visible = tiles.slice(0, Math.min(total, maxVisible))
135
135
  const overflow = total - visible.length
136
+ const overflowBadge =
137
+ overflow > 0 ? (
138
+ // `aria-hidden` because the tile's own label already reads
139
+ // "… 4 of 9" — announcing "+5" on top of that just makes the
140
+ // user do the arithmetic twice.
141
+ <div
142
+ aria-hidden
143
+ className="absolute inset-0 flex items-center justify-center bg-[#040403]/50 text-2xl font-bold leading-[28px] tracking-[-0.24px] text-white"
144
+ >
145
+ +{overflow}
146
+ </div>
147
+ ) : null
136
148
 
137
149
  const renderTile = (
138
150
  tile: MediaStackTile,
@@ -192,7 +204,7 @@ const MediaStackGrid: React.FC<MediaStackGridProps> = ({
192
204
  )}
193
205
  style={singleTileStyle}
194
206
  >
195
- {renderTile(visible[0], 0)}
207
+ {renderTile(visible[0], 0, overflowBadge)}
196
208
  </div>
197
209
  )
198
210
  }
@@ -205,7 +217,13 @@ const MediaStackGrid: React.FC<MediaStackGridProps> = ({
205
217
  className
206
218
  )}
207
219
  >
208
- {visible.map((tile, index) => renderTile(tile, index))}
220
+ {visible.map((tile, index) =>
221
+ renderTile(
222
+ tile,
223
+ index,
224
+ index === visible.length - 1 ? overflowBadge : null
225
+ )
226
+ )}
209
227
  </div>
210
228
  )
211
229
  }
@@ -220,7 +238,7 @@ const MediaStackGrid: React.FC<MediaStackGridProps> = ({
220
238
  >
221
239
  <div className="row-span-2">{renderTile(visible[0], 0)}</div>
222
240
  {renderTile(visible[1], 1)}
223
- {renderTile(visible[2], 2)}
241
+ {renderTile(visible[2], 2, overflowBadge)}
224
242
  </div>
225
243
  )
226
244
  }
@@ -245,17 +263,7 @@ const MediaStackGrid: React.FC<MediaStackGridProps> = ({
245
263
  return renderTile(
246
264
  tile,
247
265
  index,
248
- isLastWithOverflow ? (
249
- // `aria-hidden` because the tile's own label already reads
250
- // "… 4 of 9" — announcing "+5" on top of that just makes the
251
- // user do the arithmetic twice.
252
- <div
253
- aria-hidden
254
- className="absolute inset-0 flex items-center justify-center bg-[#040403]/50 text-2xl font-bold leading-[28px] tracking-[-0.24px] text-white"
255
- >
256
- +{overflow}
257
- </div>
258
- ) : null
266
+ isLastWithOverflow ? overflowBadge : null
259
267
  )
260
268
  })}
261
269
  </div>
@@ -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("./PurchaseStatusBadge-BmqAQEV9.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-Be81K6su.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"Card-Be81K6su.cjs","sources":["../src/components/CustomMessage/LockedAttachment/components/_shared/PriceLockRow.tsx","../src/components/CustomMessage/LockedAttachment/components/_shared/SkeletonTextLines.tsx","../src/components/CustomMessage/LockedAttachment/components/_shared/TextShell.tsx","../src/components/CustomMessage/LockedAttachment/components/Text/Card.tsx"],"sourcesContent":["import { LockSimpleIcon } from '@phosphor-icons/react'\nimport type React from 'react'\n\n/**\n * The lock-icon + amount/status row shared by every LockedAttachment text-mode\n * card. Only the wrapper and the leading lock icon are shared — the amount and\n * any trailing status live in `children`, since they genuinely differ per card\n * (placeholder fallback vs. paid badge vs. bare amount).\n */\nconst PriceLockRow: React.FC<React.PropsWithChildren> = ({ children }) => (\n <div className=\"flex items-center gap-1 text-xs font-medium\">\n <LockSimpleIcon\n className=\"size-3.5 shrink-0 opacity-55\"\n weight=\"fill\"\n aria-hidden\n />\n {children}\n </div>\n)\n\nexport default PriceLockRow\n","import classNames from 'classnames'\nimport React from 'react'\n\nexport interface SkeletonTextLinesProps {\n /** Matches the bubble it sits in — \"dark\" for the sender's own bubble. */\n variant: 'light' | 'dark'\n}\n\n/**\n * Two skeleton bars standing in for the redacted text of a paid text-only\n * message — the real content is never sent to the client until purchase, so\n * there's nothing to render yet.\n *\n * Uses explicit black/white (not `bg-current`) because Tailwind doesn't\n * support opacity modifiers on the `current` color — `bg-current/30` silently\n * produces no CSS rule at all.\n */\nconst SkeletonTextLines: React.FC<SkeletonTextLinesProps> = ({\n variant = 'dark',\n}) => {\n const colour = variant === 'dark' ? 'bg-white/25' : 'bg-black/15'\n\n return (\n <div\n className=\"flex flex-col gap-2 str-chat__message-text my-1 animate-pulse\"\n aria-hidden\n >\n <div className={classNames('h-3 w-40 rounded-full', colour)} />\n <div className={classNames('h-3 w-24 rounded-full', colour)} />\n </div>\n )\n}\n\nexport default SkeletonTextLines\n","import classNames from 'classnames'\nimport React from 'react'\n\n/**\n * Chat-bubble chrome for a paid text-only message/preview. Deliberately\n * doesn't lean on `.str-chat`'s CSS variables (`--str-chat__message-bubble-*`)\n * — this renders in the Composer preview too, which sits outside any\n * `.str-chat` ancestor, so every value here (radius, colour, type scale) is\n * hardcoded to match the Figma spec directly.\n */\nconst TextShell: React.FC<\n React.PropsWithChildren<{ isMine: boolean; className?: string }>\n> = ({ isMine, children, className }) => (\n <div\n className={classNames(\n 'message-locked-attachment-text',\n 'relative flex min-w-[225px] max-w-[280px] flex-col gap-1 rounded-[1.5rem] px-4 py-3',\n 'text-[0.875rem] leading-[1.3125rem] tracking-[0.14px]',\n isMine ? 'bg-[#1e2330] text-white' : 'bg-[#f2f1ef] text-black',\n 'shadow-[0_1px_2px_rgba(0,0,0,0.08)]',\n className\n )}\n >\n {children}\n </div>\n)\n\nexport default TextShell\n","import { LockSimpleIcon, XIcon } from '@phosphor-icons/react'\nimport type React from 'react'\n\nimport LoadingDots from '../_shared/LoadingDots'\nimport PriceLockRow from '../_shared/PriceLockRow'\nimport PurchaseStatusBadge from '../_shared/PurchaseStatusBadge'\nimport SkeletonTextLines from '../_shared/SkeletonTextLines'\nimport TextShell from '../_shared/TextShell'\n\nimport type {\n TextCardDraftProps,\n TextCardOtherProps,\n TextCardOwnProps,\n TextCardPreviewProps,\n TextCardProps,\n} from './types'\n\nexport type { TextCardProps } from './types'\n\nconst DraftTextCard: React.FC<TextCardDraftProps> = ({\n renderedText,\n amountText,\n placeholderAmountText,\n onDismiss,\n}) => (\n <TextShell isMine className=\"pr-8\">\n {renderedText || <SkeletonTextLines variant=\"dark\" />}\n <PriceLockRow>\n <span className={amountText ? 'text-white/55' : 'text-white/30'}>\n {amountText || placeholderAmountText}\n </span>\n </PriceLockRow>\n {onDismiss && (\n <button\n type=\"button\"\n onClick={onDismiss}\n 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\"\n aria-label=\"Dismiss attachment\"\n >\n <XIcon className=\"size-3\" weight=\"bold\" />\n </button>\n )}\n </TextShell>\n)\n\nconst PreviewTextCard: React.FC<TextCardPreviewProps> = ({\n amountText,\n placeholderAmountText,\n}) => (\n <TextShell isMine={false}>\n <SkeletonTextLines variant=\"light\" />\n <PriceLockRow>\n <span className=\"opacity-55\">{amountText || placeholderAmountText}</span>\n </PriceLockRow>\n </TextShell>\n)\n\nconst OwnTextCard: React.FC<TextCardOwnProps> = ({\n renderedText,\n amountText,\n paymentStatus = 'pending',\n}) => {\n const isPaid = paymentStatus === 'paid'\n\n return (\n <TextShell isMine>\n {isPaid && renderedText ? (\n renderedText\n ) : (\n <SkeletonTextLines variant=\"dark\" />\n )}\n <PriceLockRow>\n {amountText && <span className=\"text-white/55\">{amountText}</span>}\n <PurchaseStatusBadge isMine paymentStatus={paymentStatus} />\n </PriceLockRow>\n </TextShell>\n )\n}\n\nconst OtherTextCard: React.FC<TextCardOtherProps> = ({\n renderedText,\n amountText,\n paymentStatus,\n onUnlockClick,\n isUnlocking = false,\n}) => {\n const isPaid = paymentStatus === 'paid'\n\n if (isPaid && renderedText) {\n return (\n <TextShell isMine={false}>\n {renderedText}\n <PriceLockRow>\n {amountText != null && (\n <span className=\"opacity-55\">{amountText}</span>\n )}\n <PurchaseStatusBadge isMine={false} paymentStatus=\"paid\" />\n </PriceLockRow>\n </TextShell>\n )\n }\n\n const ariaLabel = isUnlocking ? 'Unlocking message.' : 'Unlock this message.'\n\n return (\n <TextShell isMine={false}>\n <div className=\"flex items-center gap-3\">\n <div className=\"flex flex-1 flex-col gap-2\">\n <SkeletonTextLines variant=\"light\" />\n <span className=\"sr-only\" aria-live=\"polite\">\n {ariaLabel}\n </span>\n <PriceLockRow>\n {amountText != null && (\n <span className=\"opacity-55\">{amountText}</span>\n )}\n </PriceLockRow>\n </div>\n <button\n type=\"button\"\n onClick={onUnlockClick}\n disabled={isUnlocking}\n aria-label={isUnlocking ? 'Unlocking message' : 'Unlock message'}\n aria-busy={isUnlocking}\n title={isUnlocking ? 'Unlocking message' : 'Unlock message'}\n className=\"flex size-10 shrink-0 items-center justify-center rounded-full bg-[#121110] text-white hover:bg-[#2a2928]\"\n >\n {isUnlocking ? (\n <LoadingDots />\n ) : (\n <LockSimpleIcon className=\"size-4\" weight=\"fill\" aria-hidden />\n )}\n </button>\n </div>\n </TextShell>\n )\n}\n\nconst TextCard: React.FC<TextCardProps> = (props) => {\n if (props.isDraft) {\n return <DraftTextCard {...props} />\n } else if (props.isPreview) {\n return <PreviewTextCard {...props} />\n } else if (props.isMine) {\n return <OwnTextCard {...props} />\n } else {\n return <OtherTextCard {...props} />\n }\n}\n\nexport default TextCard\n"],"names":["PriceLockRow","children","jsxs","jsx","LockSimpleIcon","SkeletonTextLines","variant","colour","classNames","TextShell","isMine","className","DraftTextCard","renderedText","amountText","placeholderAmountText","onDismiss","XIcon","PreviewTextCard","OwnTextCard","paymentStatus","isPaid","PurchaseStatusBadge","OtherTextCard","onUnlockClick","isUnlocking","ariaLabel","LoadingDots","TextCard","props"],"mappings":"gOASMA,EAAkD,CAAC,CAAE,SAAAC,KACzDC,EAAAA,KAAC,MAAA,CAAI,UAAU,8CACb,SAAA,CAAAC,EAAAA,IAACC,EAAAA,eAAA,CACC,UAAU,+BACV,OAAO,OACP,cAAW,EAAA,CAAA,EAEZH,CAAA,EACH,ECAII,EAAsD,CAAC,CAC3D,QAAAC,EAAU,MACZ,IAAM,CACJ,MAAMC,EAASD,IAAY,OAAS,cAAgB,cAEpD,OACEJ,EAAAA,KAAC,MAAA,CACC,UAAU,gEACV,cAAW,GAEX,SAAA,CAAAC,EAAAA,IAAC,MAAA,CAAI,UAAWK,EAAW,wBAAyBD,CAAM,EAAG,QAC5D,MAAA,CAAI,UAAWC,EAAW,wBAAyBD,CAAM,CAAA,CAAG,CAAA,CAAA,CAAA,CAGnE,ECrBME,EAEF,CAAC,CAAE,OAAAC,EAAQ,SAAAT,EAAU,UAAAU,KACvBR,EAAAA,IAAC,MAAA,CACC,UAAWK,EACT,iCACA,sFACA,wDACAE,EAAS,0BAA4B,0BACrC,sCACAC,CAAA,EAGD,SAAAV,CAAA,CACH,ECLIW,EAA8C,CAAC,CACnD,aAAAC,EACA,WAAAC,EACA,sBAAAC,EACA,UAAAC,CACF,IACEd,EAAAA,KAACO,EAAA,CAAU,OAAM,GAAC,UAAU,OACzB,SAAA,CAAAI,GAAg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