@adatechnology/conversations-ui 0.18.0 → 0.19.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.
package/README.md CHANGED
@@ -26,6 +26,14 @@ Telas de conversa parametrizáveis por endpoint, tema e capacidades. Subpaths: `
26
26
  - **`contextLabels`** troca o vocabulário do painel de contexto embutido (`title`, `empty`,
27
27
  `notCollected`, ...), sem precisar desenhar o resumo em `renderAboveTranscript`.
28
28
 
29
+ ### Paginação de mensagens (`ConversationsApi.fetchMessages`)
30
+
31
+ "Carregar mensagens anteriores" pede a página com o cursor composto da mensagem mais antiga da tela:
32
+ `fetchMessages(conversationId, { limit, before: <timestamp>, beforeId: <id> })`. O servidor devolve só as
33
+ estritamente anteriores a ela na ordem `(createdAt, id)`; assim mensagens gravadas no mesmo instante da
34
+ fronteira nem somem nem se repetem. Host que só entende `before` pode ignorar `beforeId` (pagina como antes).
35
+ O `meta-whatsapp-module` aceita `beforeId` em `ListMessagesUseCase` / `MessageRepository.listByConversation`.
36
+
29
37
  ## Visão do participante (`/participant`)
30
38
 
31
39
  Tela de conversa do lado de **quem conversa com a empresa** (app de campo, portal do cliente). Não usa
@@ -144,9 +144,16 @@ interface ConversationTemplate {
144
144
  bodyText?: string | null;
145
145
  }
146
146
  interface ConversationsApi {
147
+ /**
148
+ * `before` e `beforeId` formam o cursor composto `(createdAt, id)` da mensagem mais antiga já na tela:
149
+ * só voltam as estritamente anteriores a ela nessa ordem, então duas mensagens no mesmo instante nunca
150
+ * ficam de fora nem se repetem na virada de página. Host que só entende `before` ignora `beforeId` e
151
+ * pagina como antes.
152
+ */
147
153
  fetchMessages(conversationId: string, params?: {
148
154
  limit?: number;
149
155
  before?: string;
156
+ beforeId?: string;
150
157
  }): Promise<MessagePayload[]>;
151
158
  fetchConversations(params?: ListConversationsParams): Promise<ConversationSummary[] | ConversationPage>;
152
159
  sendMessage(conversationId: string, text: string): Promise<MessagePayload>;
package/dist/index.d.ts CHANGED
@@ -2,8 +2,8 @@ import * as react from 'react';
2
2
  import react__default, { ReactNode, CSSProperties, UIEvent, FormEvent, RefObject, KeyboardEvent } from 'react';
3
3
  import { M as MessagePayload, I as InteractiveSelection, a as MessageTranscription, C as ConversationChannel, e as InteractivePayload, f as ConversationsFeatures, Q as QuickReply$1, T as TranscriptionMode, g as QueuedAttachment, b as QuickReplyInput, c as QuickReplyAttachment, h as ConversationVariable, i as ChannelFilter, j as ChannelFilterOption } from './quickReply.types-DzWH3NYV.js';
4
4
  export { k as CHANNEL_CAPABILITIES, l as CHANNEL_FILTER_ALL, m as CONVERSATION_CHANNEL, n as ChannelCapabilities, d as ConversationsTheme, o as ConversationsUIConfig, D as DEFAULT_CONVERSATION_CHANNEL, F as FormatContactHandleParams, H as HANDLE_KIND, p as HandleKind, q as InteractiveOption, r as InteractiveSection, s as QUICK_REPLY_ATTACHMENT_LIMIT, R as REOPEN_MECHANISM, t as ReopenMechanism, S as StoredAttachmentSendResult, u as TranscriptionStatus, v as capabilitiesOf, w as channelFiltersFor, x as contactFlag, y as formatContactHandle } from './quickReply.types-DzWH3NYV.js';
5
- import { R as ResolveMediaUrl, C as ConversationSummary, L as ListConversationsParams, b as ConversationsApi, S as SSEProvider, Q as ListDocumentsParams, d as ConversationDocument, U as ConversationTemplate, j as ConversationSimulatorClient, l as ConversationSimulatorPanelLabels, P as PreviewUploadedMedia } from './ConversationSimulatorPanel-DSVIch04.js';
6
- export { A as AudioRecorderButton, f as AudioRecorderButtonLabels, g as AudioRecorderButtonProps, V as CompanyDocument, W as CompanyDocumentPage, X as ConversationDocumentPage, a as ConversationEventSource, c as ConversationPage, D as DEFAULT_AUDIO_RECORDER_BUTTON_LABELS, Y as MediaRenderer, Z as MediaRendererProps, y as SendSimulatorMediaParams, z as SimulatorMediaKind } from './ConversationSimulatorPanel-DSVIch04.js';
5
+ import { R as ResolveMediaUrl, C as ConversationSummary, L as ListConversationsParams, b as ConversationsApi, S as SSEProvider, Q as ListDocumentsParams, d as ConversationDocument, U as ConversationTemplate, j as ConversationSimulatorClient, l as ConversationSimulatorPanelLabels, P as PreviewUploadedMedia } from './ConversationSimulatorPanel-bkKpi-1c.js';
6
+ export { A as AudioRecorderButton, f as AudioRecorderButtonLabels, g as AudioRecorderButtonProps, V as CompanyDocument, W as CompanyDocumentPage, X as ConversationDocumentPage, a as ConversationEventSource, c as ConversationPage, D as DEFAULT_AUDIO_RECORDER_BUTTON_LABELS, Y as MediaRenderer, Z as MediaRendererProps, y as SendSimulatorMediaParams, z as SimulatorMediaKind } from './ConversationSimulatorPanel-bkKpi-1c.js';
7
7
  import { ChannelCapability } from '@adatechnology/conversation-contracts';
8
8
  export { ChannelCapability } from '@adatechnology/conversation-contracts';
9
9
  import '@adatechnology/meta-whatsapp-contracts/testing';
@@ -1714,6 +1714,7 @@ interface UseConversationMessagesResult {
1714
1714
  declare function useConversationMessages(conversationId: string, params?: {
1715
1715
  limit?: number;
1716
1716
  before?: string;
1717
+ beforeId?: string;
1717
1718
  }): UseConversationMessagesResult;
1718
1719
 
1719
1720
  type UseScrollToLatestMessageParams = {
package/dist/index.js CHANGED
@@ -4081,6 +4081,9 @@ function shouldFetchOlderMessages(state) {
4081
4081
  if (state.isLoading || !state.hasMore) return false;
4082
4082
  return Boolean(state.oldestMessage);
4083
4083
  }
4084
+ function buildOlderMessagesRequest(oldestMessage) {
4085
+ return { limit: OLDER_MESSAGES_PAGE_LIMIT, before: oldestMessage.timestamp, beforeId: oldestMessage.id };
4086
+ }
4084
4087
  function pageIndicatesMoreOlderMessages(pageLength, limit) {
4085
4088
  return pageLength >= limit;
4086
4089
  }
@@ -4092,7 +4095,7 @@ function useConversationMessages(conversationId, params) {
4092
4095
  const { api } = context;
4093
4096
  const { data, loading, error, refetch } = useAsyncResource(
4094
4097
  () => api.fetchMessages(conversationId, params),
4095
- [conversationId, params?.limit, params?.before]
4098
+ [conversationId, params?.limit, params?.before, params?.beforeId]
4096
4099
  );
4097
4100
  const [olderMessages, setOlderMessages] = useState15([]);
4098
4101
  const [hasMoreOlderMessages, setHasMoreOlderMessages] = useState15(true);
@@ -4115,10 +4118,7 @@ function useConversationMessages(conversationId, params) {
4115
4118
  loadingOlderMessagesRef.current = true;
4116
4119
  setLoadingOlderMessages(true);
4117
4120
  try {
4118
- const olderPage = await api.fetchMessages(conversationId, {
4119
- limit: OLDER_MESSAGES_PAGE_LIMIT,
4120
- before: oldestMessage.timestamp
4121
- });
4121
+ const olderPage = await api.fetchMessages(conversationId, buildOlderMessagesRequest(oldestMessage));
4122
4122
  if (!pageIndicatesMoreOlderMessages(olderPage.length, OLDER_MESSAGES_PAGE_LIMIT)) setHasMoreOlderMessages(false);
4123
4123
  setOlderMessages((current) => prependOlderMessages(current, olderPage));
4124
4124
  } finally {
@@ -1,6 +1,6 @@
1
1
  import { M as MessagePayload } from '../quickReply.types-DzWH3NYV.js';
2
- import { C as ConversationSummary, a as ConversationEventSource, b as ConversationsApi, L as ListConversationsParams, c as ConversationPage, S as SSEProvider, d as ConversationDocument, P as PreviewUploadedMedia, e as PreviewWebhookClient, R as ResolveMediaUrl } from '../ConversationSimulatorPanel-DSVIch04.js';
3
- export { A as AudioRecorderButton, f as AudioRecorderButtonLabels, g as AudioRecorderButtonProps, h as ConversationPreview, i as ConversationPreviewProps, j as ConversationSimulatorClient, k as ConversationSimulatorPanel, l as ConversationSimulatorPanelLabels, m as ConversationSimulatorPanelProps, n as CreatePreviewMediaUploaderParams, o as CreatePreviewWebhookClientParams, D as DEFAULT_AUDIO_RECORDER_BUTTON_LABELS, p as DEFAULT_CONVERSATION_SIMULATOR_PANEL_LABELS, q as DEFAULT_MEDIA_UPLOAD_PATH, r as PreviewInProductionError, s as PreviewMediaUploadRejectedError, t as PreviewMediaUploadRequest, u as PreviewUploadedMedia, v as PreviewWebhookRejectedError, w as SIMULATOR_FILE_MEDIA_KINDS, x as SendPreviewMediaParams, y as SendSimulatorMediaParams, z as SimulatorMediaKind, T as ToSimulatorClientParams, B as acceptsMediaKind, E as assertPreviewEnvironment, F as createPreviewMediaPoster, G as createPreviewMediaUploader, H as createPreviewWebhookClient, I as isConversationSimulatorClient, J as mediaKindOf, K as mediaTypeOf, M as signPreviewPayload, N as simulatorPanelLabelsOf, O as toConversationSimulatorClient } from '../ConversationSimulatorPanel-DSVIch04.js';
2
+ import { C as ConversationSummary, a as ConversationEventSource, b as ConversationsApi, L as ListConversationsParams, c as ConversationPage, S as SSEProvider, d as ConversationDocument, P as PreviewUploadedMedia, e as PreviewWebhookClient, R as ResolveMediaUrl } from '../ConversationSimulatorPanel-bkKpi-1c.js';
3
+ export { A as AudioRecorderButton, f as AudioRecorderButtonLabels, g as AudioRecorderButtonProps, h as ConversationPreview, i as ConversationPreviewProps, j as ConversationSimulatorClient, k as ConversationSimulatorPanel, l as ConversationSimulatorPanelLabels, m as ConversationSimulatorPanelProps, n as CreatePreviewMediaUploaderParams, o as CreatePreviewWebhookClientParams, D as DEFAULT_AUDIO_RECORDER_BUTTON_LABELS, p as DEFAULT_CONVERSATION_SIMULATOR_PANEL_LABELS, q as DEFAULT_MEDIA_UPLOAD_PATH, r as PreviewInProductionError, s as PreviewMediaUploadRejectedError, t as PreviewMediaUploadRequest, u as PreviewUploadedMedia, v as PreviewWebhookRejectedError, w as SIMULATOR_FILE_MEDIA_KINDS, x as SendPreviewMediaParams, y as SendSimulatorMediaParams, z as SimulatorMediaKind, T as ToSimulatorClientParams, B as acceptsMediaKind, E as assertPreviewEnvironment, F as createPreviewMediaPoster, G as createPreviewMediaUploader, H as createPreviewWebhookClient, I as isConversationSimulatorClient, J as mediaKindOf, K as mediaTypeOf, M as signPreviewPayload, N as simulatorPanelLabelsOf, O as toConversationSimulatorClient } from '../ConversationSimulatorPanel-bkKpi-1c.js';
4
4
  import { PreviewInboundCommand } from '@adatechnology/meta-whatsapp-contracts/testing';
5
5
  export { PreviewInboundCommand } from '@adatechnology/meta-whatsapp-contracts/testing';
6
6
  import * as react from 'react';
@@ -708,7 +708,9 @@ function createMockConversationsApi(params) {
708
708
  return withLatency(() => {
709
709
  const allMessages = params.store.listMessages(conversationId);
710
710
  const before = fetchParams?.before;
711
- const messages = before ? allMessages.filter((message) => message.timestamp < before) : allMessages;
711
+ const beforeId = fetchParams?.beforeId;
712
+ const isOlder = (message) => before === void 0 ? true : message.timestamp < before || beforeId !== void 0 && message.timestamp === before && message.id < beforeId;
713
+ const messages = before ? allMessages.filter(isOlder) : allMessages;
712
714
  const limit = fetchParams?.limit;
713
715
  return limit ? messages.slice(-limit) : messages;
714
716
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adatechnology/conversations-ui",
3
- "version": "0.18.0",
3
+ "version": "0.19.0",
4
4
  "description": "WhatsApp conversation UI components — parametrizável por endpoint, tema e feature flags",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -36,7 +36,7 @@
36
36
  "lucide-react": "^1.21.0",
37
37
  "tailwind-merge": "^3.6.0",
38
38
  "@adatechnology/conversation-contracts": "0.7.0",
39
- "@adatechnology/meta-whatsapp-contracts": "0.10.0"
39
+ "@adatechnology/meta-whatsapp-contracts": "0.11.0"
40
40
  },
41
41
  "peerDependencies": {
42
42
  "@xyflow/react": "^12",
@@ -1,6 +1,7 @@
1
1
  import { describe, expect, it } from 'bun:test'
2
2
 
3
3
  import {
4
+ buildOlderMessagesRequest,
4
5
  dedupeMessagesById,
5
6
  pageIndicatesMoreOlderMessages,
6
7
  prependOlderMessages,
@@ -88,3 +89,15 @@ describe('preservação do histórico ao chegar mensagem nova (SSE/polling)', ()
88
89
  expect(after.map((message) => message.id)).toEqual(['1', '2', '3', '4'])
89
90
  })
90
91
  })
92
+
93
+ describe('buildOlderMessagesRequest', () => {
94
+ it('usa a mensagem mais antiga como cursor composto (timestamp + id)', () => {
95
+ const oldest = buildMessage('msg-7', '2026-09-01T10:00:00.123Z')
96
+
97
+ expect(buildOlderMessagesRequest(oldest)).toEqual({
98
+ limit: 50,
99
+ before: '2026-09-01T10:00:00.123Z',
100
+ beforeId: 'msg-7',
101
+ })
102
+ })
103
+ })
@@ -65,6 +65,18 @@ export function shouldFetchOlderMessages(state: LoadOlderMessagesGuardState): bo
65
65
  return Boolean(state.oldestMessage)
66
66
  }
67
67
 
68
+ /**
69
+ * Pedido da página anterior: o cursor é a mensagem mais antiga da tela, por `(timestamp, id)`. Mandar
70
+ * só o timestamp deixava de fora (ou repetia) mensagens gravadas no mesmo instante da fronteira.
71
+ */
72
+ export function buildOlderMessagesRequest(oldestMessage: MessagePayload): {
73
+ limit: number
74
+ before: string
75
+ beforeId: string
76
+ } {
77
+ return { limit: OLDER_MESSAGES_PAGE_LIMIT, before: oldestMessage.timestamp, beforeId: oldestMessage.id }
78
+ }
79
+
68
80
  /** A página veio menor que o limite pedido: não há mais nada antes dela para buscar. */
69
81
  export function pageIndicatesMoreOlderMessages(pageLength: number, limit: number): boolean {
70
82
  return pageLength >= limit
@@ -75,7 +87,7 @@ export function pageIndicatesMoreOlderMessages(pageLength: number, limit: number
75
87
  // por cima, como o pacote já oferece). Requer <ConversationsProvider> como ancestral.
76
88
  export function useConversationMessages(
77
89
  conversationId: string,
78
- params?: { limit?: number; before?: string },
90
+ params?: { limit?: number; before?: string; beforeId?: string },
79
91
  ): UseConversationMessagesResult {
80
92
  const context = useConversations()
81
93
  if (!context) {
@@ -85,7 +97,7 @@ export function useConversationMessages(
85
97
 
86
98
  const { data, loading, error, refetch } = useAsyncResource(
87
99
  () => api.fetchMessages(conversationId, params),
88
- [conversationId, params?.limit, params?.before],
100
+ [conversationId, params?.limit, params?.before, params?.beforeId],
89
101
  )
90
102
 
91
103
  const [olderMessages, setOlderMessages] = useState<MessagePayload[]>([])
@@ -122,10 +134,7 @@ export function useConversationMessages(
122
134
  loadingOlderMessagesRef.current = true
123
135
  setLoadingOlderMessages(true)
124
136
  try {
125
- const olderPage = await api.fetchMessages(conversationId, {
126
- limit: OLDER_MESSAGES_PAGE_LIMIT,
127
- before: oldestMessage.timestamp,
128
- })
137
+ const olderPage = await api.fetchMessages(conversationId, buildOlderMessagesRequest(oldestMessage))
129
138
  if (!pageIndicatesMoreOlderMessages(olderPage.length, OLDER_MESSAGES_PAGE_LIMIT)) setHasMoreOlderMessages(false)
130
139
  setOlderMessages((current) => prependOlderMessages(current, olderPage))
131
140
  } finally {
@@ -110,9 +110,16 @@ export function createMockConversationsApi(params: CreateMockConversationsApiPar
110
110
  return withLatency(() => {
111
111
  const allMessages = params.store.listMessages(conversationId)
112
112
  const before = fetchParams?.before
113
+ const beforeId = fetchParams?.beforeId
113
114
  // Mesma semântica do backend real: com `before`, corta tudo a partir dessa mensagem (ela
114
- // não volta) para simular a paginação de "carregar mensagens anteriores" no preview.
115
- const messages = before ? allMessages.filter((message) => message.timestamp < before) : allMessages
115
+ // não volta) para simular a paginação de "carregar mensagens anteriores" no preview. Com
116
+ // `beforeId` o cursor é `(timestamp, id)`: no mesmo instante, só as de id menor.
117
+ const isOlder = (message: MessagePayload): boolean =>
118
+ before === undefined
119
+ ? true
120
+ : message.timestamp < before ||
121
+ (beforeId !== undefined && message.timestamp === before && message.id < beforeId)
122
+ const messages = before ? allMessages.filter(isOlder) : allMessages
116
123
  const limit = fetchParams?.limit
117
124
  return limit ? messages.slice(-limit) : messages
118
125
  })
@@ -175,3 +175,29 @@ describe('roteiro padrão', () => {
175
175
  expect(store.listMessages(WAITING_CONVERSATION_ID).at(-1)?.sender).toBe('agent')
176
176
  })
177
177
  })
178
+
179
+ describe('createMockConversationsApi — cursor composto de mensagens', () => {
180
+ const conversationId = 'cursor-conversation'
181
+ const instant = '2026-09-01T10:00:00.000Z'
182
+
183
+ function apiWithSameInstantMessages() {
184
+ const store = createStore()
185
+ const messages = ['a', 'b', 'c'].map((id) =>
186
+ store.appendMessage({ conversationId, content: id, direction: 'inbound', sender: 'customer' }),
187
+ )
188
+ const rewritten = messages.map((message, index) => ({ ...message, id: `id-${index}`, timestamp: instant }))
189
+ const customStore = { ...store, listMessages: () => rewritten } as PreviewStore
190
+ return createMockConversationsApi({ store: customStore, latencyMs: 0 })
191
+ }
192
+
193
+ it('com beforeId, no mesmo instante só voltam as de id menor (nenhuma some, nenhuma repete)', async () => {
194
+ const api = apiWithSameInstantMessages()
195
+ const page = await api.fetchMessages(conversationId, { before: instant, beforeId: 'id-2' })
196
+ expect(page.map((message) => message.id)).toEqual(['id-0', 'id-1'])
197
+ })
198
+
199
+ it('sem beforeId mantém o corte só por timestamp', async () => {
200
+ const api = apiWithSameInstantMessages()
201
+ expect(await api.fetchMessages(conversationId, { before: instant })).toEqual([])
202
+ })
203
+ })
@@ -96,7 +96,16 @@ export interface ConversationTemplate {
96
96
  }
97
97
 
98
98
  export interface ConversationsApi {
99
- fetchMessages(conversationId: string, params?: { limit?: number; before?: string }): Promise<MessagePayload[]>
99
+ /**
100
+ * `before` e `beforeId` formam o cursor composto `(createdAt, id)` da mensagem mais antiga já na tela:
101
+ * só voltam as estritamente anteriores a ela nessa ordem, então duas mensagens no mesmo instante nunca
102
+ * ficam de fora nem se repetem na virada de página. Host que só entende `before` ignora `beforeId` e
103
+ * pagina como antes.
104
+ */
105
+ fetchMessages(
106
+ conversationId: string,
107
+ params?: { limit?: number; before?: string; beforeId?: string },
108
+ ): Promise<MessagePayload[]>
100
109
  fetchConversations(params?: ListConversationsParams): Promise<ConversationSummary[] | ConversationPage>
101
110
  sendMessage(conversationId: string, text: string): Promise<MessagePayload>
102
111
  sendMedia(