@adatechnology/conversations-ui 0.15.1 → 0.16.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.
@@ -0,0 +1,267 @@
1
+ /**
2
+ * Copyright (c) 2026 Ada Technology. MIT License.
3
+ *
4
+ * Campos do painel de nó que o runner de fluxo do módulo interpreta: validação da resposta,
5
+ * tentativas, mensagem de nova tentativa, palavras de pular, descrição/seção das opções e o
6
+ * provedor da escolha dinâmica. Separado do `FlowNodePanel` para o painel continuar legível.
7
+ */
8
+
9
+ import type { ReactNode } from 'react'
10
+ import type { FlowAnswerValidation, FlowNodeData } from './flowGraph'
11
+ import type { FlowRunnerFieldLabels } from './labels'
12
+ import { FlowKeywordRoutesField } from './FlowKeywordRoutesField'
13
+ import { PANEL_FIELD_CLASSNAME, PANEL_HINT_CLASSNAME, PANEL_LABEL_CLASSNAME } from './flowPanelStyles'
14
+
15
+ export type FlowRunnerFieldsProps = {
16
+ draft: FlowNodeData
17
+ onDraftChange: (update: (previous: FlowNodeData) => FlowNodeData) => void
18
+ renderTargetOptions: () => ReactNode
19
+ knownContextKeys: readonly string[]
20
+ labels: FlowRunnerFieldLabels
21
+ }
22
+
23
+ function toNumber(value: string): number | undefined {
24
+ if (value.trim() === '') return undefined
25
+ const parsed = Number(value)
26
+ return Number.isFinite(parsed) ? parsed : undefined
27
+ }
28
+
29
+ function withValidation(node: FlowNodeData, patch: Partial<FlowAnswerValidation>): FlowNodeData {
30
+ const merged: FlowAnswerValidation = { ...node.validation, ...patch }
31
+ const cleaned = Object.fromEntries(Object.entries(merged).filter(([, value]) => value !== undefined && value !== ''))
32
+ return { ...node, validation: Object.keys(cleaned).length > 0 ? (cleaned as FlowAnswerValidation) : undefined }
33
+ }
34
+
35
+ function NumberField(props: {
36
+ label: string
37
+ value: number | undefined
38
+ onValueChange: (value: number | undefined) => void
39
+ }) {
40
+ return (
41
+ <div className="flex-1">
42
+ <label className={PANEL_LABEL_CLASSNAME}>{props.label}</label>
43
+ <input
44
+ type="number"
45
+ value={props.value ?? ''}
46
+ onChange={(event) => props.onValueChange(toNumber(event.target.value))}
47
+ className={`w-full mt-1 ${PANEL_FIELD_CLASSNAME}`}
48
+ />
49
+ </div>
50
+ )
51
+ }
52
+
53
+ function ValidationFields({ draft, onDraftChange, knownContextKeys, labels }: FlowRunnerFieldsProps) {
54
+ const validation = draft.validation ?? {}
55
+ const update = (patch: Partial<FlowAnswerValidation>) => onDraftChange((previous) => withValidation(previous, patch))
56
+
57
+ if (draft.questionType === 'date') {
58
+ return (
59
+ <div className="space-y-2">
60
+ <label className="flex items-center gap-2 text-xs text-gray-600 dark:text-gray-300">
61
+ <input
62
+ type="checkbox"
63
+ checked={validation.minDate === 'today'}
64
+ onChange={(event) => update({ minDate: event.target.checked ? 'today' : undefined })}
65
+ />
66
+ {labels.minDateToday}
67
+ </label>
68
+ <div>
69
+ <label className={PANEL_LABEL_CLASSNAME}>{labels.afterContextKey}</label>
70
+ <input
71
+ value={validation.afterContextKey ?? ''}
72
+ list="runner-context-keys"
73
+ onChange={(event) => update({ afterContextKey: event.target.value || undefined })}
74
+ className={`w-full mt-1 ${PANEL_FIELD_CLASSNAME}`}
75
+ />
76
+ <datalist id="runner-context-keys">
77
+ {knownContextKeys.map((key) => (
78
+ <option key={key} value={key} />
79
+ ))}
80
+ </datalist>
81
+ </div>
82
+ </div>
83
+ )
84
+ }
85
+
86
+ if (draft.questionType === 'int' || draft.questionType === 'money') {
87
+ return (
88
+ <div className="flex gap-2">
89
+ <NumberField label={labels.minValue} value={validation.min} onValueChange={(min) => update({ min })} />
90
+ <NumberField label={labels.maxValue} value={validation.max} onValueChange={(max) => update({ max })} />
91
+ </div>
92
+ )
93
+ }
94
+
95
+ if (!draft.questionType || draft.questionType === 'text') {
96
+ return (
97
+ <div className="flex gap-2">
98
+ <NumberField
99
+ label={labels.minLength}
100
+ value={validation.minLength}
101
+ onValueChange={(minLength) => update({ minLength })}
102
+ />
103
+ <NumberField
104
+ label={labels.maxLength}
105
+ value={validation.maxLength}
106
+ onValueChange={(maxLength) => update({ maxLength })}
107
+ />
108
+ </div>
109
+ )
110
+ }
111
+
112
+ return null
113
+ }
114
+
115
+ function OptionDetailsField({ draft, onDraftChange, labels }: FlowRunnerFieldsProps) {
116
+ const options = draft.options ?? []
117
+ if (options.length === 0) return null
118
+
119
+ function updateDetail(optionId: string, field: 'description' | 'section', value: string) {
120
+ onDraftChange((previous) => {
121
+ const current = previous.optionDetails?.[optionId] ?? {}
122
+ const detail = { ...current, [field]: value || undefined }
123
+ return { ...previous, optionDetails: { ...previous.optionDetails, [optionId]: detail } }
124
+ })
125
+ }
126
+
127
+ return (
128
+ <div className="space-y-2">
129
+ {options.map(([optionId, title]) => (
130
+ <div key={optionId} className="space-y-1">
131
+ <span className="text-[11px] font-medium text-gray-500 dark:text-gray-400">{title || optionId}</span>
132
+ <div className="flex gap-2">
133
+ <input
134
+ value={draft.optionDetails?.[optionId]?.description ?? ''}
135
+ placeholder={labels.optionDescription}
136
+ aria-label={`${labels.optionDescription}: ${title}`}
137
+ onChange={(event) => updateDetail(optionId, 'description', event.target.value)}
138
+ className={`flex-1 ${PANEL_FIELD_CLASSNAME}`}
139
+ />
140
+ <input
141
+ value={draft.optionDetails?.[optionId]?.section ?? ''}
142
+ placeholder={labels.optionSection}
143
+ aria-label={`${labels.optionSection}: ${title}`}
144
+ onChange={(event) => updateDetail(optionId, 'section', event.target.value)}
145
+ className={`w-24 ${PANEL_FIELD_CLASSNAME}`}
146
+ />
147
+ </div>
148
+ </div>
149
+ ))}
150
+ </div>
151
+ )
152
+ }
153
+
154
+ function TextField(props: {
155
+ label: string
156
+ value: string
157
+ hint?: string
158
+ placeholder?: string
159
+ onValueChange: (value: string) => void
160
+ }) {
161
+ return (
162
+ <div>
163
+ <label className={PANEL_LABEL_CLASSNAME}>{props.label}</label>
164
+ <input
165
+ value={props.value}
166
+ placeholder={props.placeholder}
167
+ onChange={(event) => props.onValueChange(event.target.value)}
168
+ className={`w-full mt-1 ${PANEL_FIELD_CLASSNAME}`}
169
+ />
170
+ {props.hint && <p className={PANEL_HINT_CLASSNAME}>{props.hint}</p>}
171
+ </div>
172
+ )
173
+ }
174
+
175
+ export function FlowRunnerFields(props: FlowRunnerFieldsProps) {
176
+ const { draft, onDraftChange, labels } = props
177
+ const isDynamic = draft.type === 'dynamic_choice'
178
+ const isChoice = draft.type === 'menu' || draft.questionType === 'choice'
179
+ const isQuestion = draft.type === 'question' && !isChoice
180
+
181
+ return (
182
+ <div className="pt-2 border-t border-gray-100 dark:border-gray-700 space-y-3">
183
+ <p className="text-xs font-semibold text-gray-700 dark:text-gray-200">{labels.section}</p>
184
+ <p className={PANEL_HINT_CLASSNAME}>{labels.placeholdersHint}</p>
185
+
186
+ {isDynamic && (
187
+ <>
188
+ <TextField
189
+ label={labels.choiceProvider}
190
+ hint={labels.choiceProviderHint}
191
+ value={draft.choiceProvider ?? ''}
192
+ onValueChange={(value) =>
193
+ onDraftChange((previous) => ({ ...previous, choiceProvider: value || undefined }))
194
+ }
195
+ />
196
+ <TextField
197
+ label={labels.contextKey}
198
+ value={draft.contextKey ?? ''}
199
+ onValueChange={(value) => onDraftChange((previous) => ({ ...previous, contextKey: value || undefined }))}
200
+ />
201
+ </>
202
+ )}
203
+
204
+ {isQuestion && <ValidationFields {...props} />}
205
+ {isChoice && <OptionDetailsField {...props} />}
206
+ {isChoice && (
207
+ <div>
208
+ <label className={PANEL_LABEL_CLASSNAME}>{labels.unmatchedChoice}</label>
209
+ <select
210
+ value={draft.unmatchedChoice ?? 'reask'}
211
+ onChange={(event) => {
212
+ const value = event.target.value === 'default' ? 'default' : undefined
213
+ onDraftChange((previous) => ({ ...previous, unmatchedChoice: value }))
214
+ }}
215
+ className={`w-full mt-1 ${PANEL_FIELD_CLASSNAME}`}
216
+ >
217
+ <option value="reask">{labels.unmatchedChoiceReask}</option>
218
+ <option value="default">{labels.unmatchedChoiceDefault}</option>
219
+ </select>
220
+ </div>
221
+ )}
222
+ {(isChoice || isDynamic) && (
223
+ <TextField
224
+ label={labels.listButtonLabel}
225
+ value={draft.listButtonLabel ?? ''}
226
+ onValueChange={(value) => onDraftChange((previous) => ({ ...previous, listButtonLabel: value || undefined }))}
227
+ />
228
+ )}
229
+ {isQuestion && (
230
+ <TextField
231
+ label={labels.skipKeywords}
232
+ hint={labels.skipKeywordsHint}
233
+ value={(draft.skipKeywords ?? []).join(', ')}
234
+ onValueChange={(value) => {
235
+ const keywords = value
236
+ .split(',')
237
+ .map((keyword) => keyword.trim())
238
+ .filter(Boolean)
239
+ onDraftChange((previous) => ({ ...previous, skipKeywords: keywords.length > 0 ? keywords : undefined }))
240
+ }}
241
+ />
242
+ )}
243
+
244
+ <TextField
245
+ label={labels.fallbackMessage}
246
+ placeholder={labels.fallbackPlaceholder}
247
+ value={draft.fallbackMessage ?? ''}
248
+ onValueChange={(value) => onDraftChange((previous) => ({ ...previous, fallbackMessage: value || undefined }))}
249
+ />
250
+ <div>
251
+ <NumberField
252
+ label={labels.maxInvalidAnswers}
253
+ value={draft.maxInvalidAnswers}
254
+ onValueChange={(value) =>
255
+ onDraftChange((previous) => ({
256
+ ...previous,
257
+ maxInvalidAnswers: value && value > 0 ? Math.floor(value) : undefined,
258
+ }))
259
+ }
260
+ />
261
+ <p className={PANEL_HINT_CLASSNAME}>{labels.maxInvalidAnswersHint}</p>
262
+ </div>
263
+
264
+ {(draft.type === 'menu' || draft.type === 'question') && <FlowKeywordRoutesField {...props} />}
265
+ </div>
266
+ )
267
+ }
@@ -2,14 +2,30 @@ import { List } from 'lucide-react'
2
2
  import { parseWhatsAppFormatting } from '../lib/whatsapp-formatting'
3
3
  import { WhatsAppMessagePreview } from '../lib/WhatsAppMessagePreview'
4
4
  import { DEFAULT_FLOW_EDITOR_LABELS, type FlowEditorLabels } from './labels'
5
- import { rendersAsButtons, WHATSAPP_LIMITS } from './flowGraph'
5
+ import { rendersAsButtons, WHATSAPP_LIMITS, type FlowOptionDetail } from './flowGraph'
6
6
 
7
7
  export interface FlowWhatsAppPreviewProps {
8
8
  body: string
9
9
  options?: [string, string][]
10
+ /** Descrição e seção por id de opção — com qualquer uma, a mensagem sai como lista. */
11
+ optionDetails?: Record<string, FlowOptionDetail>
10
12
  labels?: FlowEditorLabels['nodePanel']
11
13
  }
12
14
 
15
+ type PreviewSection = { title?: string; rows: [string, string][] }
16
+
17
+ /** Agrupa como o runner agrupa: seções na ordem em que aparecem, opções sem seção juntas. */
18
+ function groupBySection(options: [string, string][], optionDetails?: Record<string, FlowOptionDetail>): PreviewSection[] {
19
+ const sections: PreviewSection[] = []
20
+ for (const option of options.slice(0, WHATSAPP_LIMITS.MAX_LIST_ROWS)) {
21
+ const title = optionDetails?.[option[0]]?.section?.trim() || undefined
22
+ const existing = sections.find((section) => section.title === title)
23
+ if (existing) existing.rows.push(option)
24
+ else sections.push({ title, rows: [option] })
25
+ }
26
+ return sections
27
+ }
28
+
13
29
  // Espelha como o WhatsApp REALMENTE renderiza a mensagem do nó: bolha de texto e, quando há
14
30
  // opções, botões (≤3) ou lista (4+) — para o editor mostrar exatamente o que o cliente verá.
15
31
  // Consome a mesma bolha/formatação do pacote (parseWhatsAppFormatting, T6.5) — T7.3 elimina a
@@ -17,13 +33,14 @@ export interface FlowWhatsAppPreviewProps {
17
33
  export function FlowWhatsAppPreview({
18
34
  body,
19
35
  options,
36
+ optionDetails,
20
37
  labels = DEFAULT_FLOW_EDITOR_LABELS.nodePanel,
21
38
  }: FlowWhatsAppPreviewProps) {
22
39
  if (!body && (!options || options.length === 0)) {
23
40
  return <p className="text-xs text-gray-400 dark:text-gray-500 italic px-1">{labels.previewPlaceholder}</p>
24
41
  }
25
42
 
26
- const usesButtons = rendersAsButtons(options)
43
+ const usesButtons = rendersAsButtons(options, optionDetails)
27
44
  const hasOptions = (options?.length ?? 0) > 0
28
45
 
29
46
  return (
@@ -45,10 +62,26 @@ export function FlowWhatsAppPreview({
45
62
 
46
63
  {hasOptions && !usesButtons && (
47
64
  <div className="mt-1.5 rounded-lg bg-white dark:bg-gray-700 shadow-sm divide-y divide-gray-100 dark:divide-gray-600 overflow-hidden">
48
- {options!.slice(0, WHATSAPP_LIMITS.MAX_LIST_ROWS).map(([id, label]) => (
49
- <div key={id} className="flex items-center gap-2 px-3 py-1.5 text-sm text-gray-800 dark:text-gray-100">
50
- <span className="h-3.5 w-3.5 rounded-full border border-gray-300 dark:border-gray-500 shrink-0" />
51
- {label || <span className="italic text-gray-400">{labels.previewEmptyOption}</span>}
65
+ {groupBySection(options!, optionDetails).map((section, sectionIndex) => (
66
+ <div key={section.title ?? `section-${sectionIndex}`}>
67
+ {section.title && (
68
+ <p className="px-3 pt-1.5 text-[11px] font-medium uppercase text-cyan-700 dark:text-cyan-400">
69
+ {section.title}
70
+ </p>
71
+ )}
72
+ {section.rows.map(([id, label]) => (
73
+ <div key={id} className="flex items-center gap-2 px-3 py-1.5 text-sm text-gray-800 dark:text-gray-100">
74
+ <span className="h-3.5 w-3.5 rounded-full border border-gray-300 dark:border-gray-500 shrink-0" />
75
+ <span className="min-w-0">
76
+ {label || <span className="italic text-gray-400">{labels.previewEmptyOption}</span>}
77
+ {optionDetails?.[id]?.description && (
78
+ <span className="block text-xs text-gray-500 dark:text-gray-400">
79
+ {optionDetails[id]!.description}
80
+ </span>
81
+ )}
82
+ </span>
83
+ </div>
84
+ ))}
52
85
  </div>
53
86
  ))}
54
87
  </div>
@@ -356,9 +356,10 @@ describe('estimateNodeHeight em nó de ação', () => {
356
356
  expect(passThrough).toBeGreaterThan(terminal)
357
357
  })
358
358
 
359
- it('ação sem kind conta como terminal, em vez de estourar', () => {
359
+ // Ação sem kind é nó de mensagem: o runner envia o texto e segue, então o card tem uma saída.
360
+ it('ação sem kind conta como passagem (nó de mensagem)', () => {
360
361
  expect(estimateNodeHeight({ id: 'c', type: 'action' })).toBe(
361
- estimateNodeHeight({ id: 'd', type: 'action', actionKind: 'handoff' }),
362
+ estimateNodeHeight({ id: 'd', type: 'action', actionKind: 'send_media' }),
362
363
  )
363
364
  })
364
365
  })
@@ -19,6 +19,7 @@ import {
19
19
  isCrossFlowTarget,
20
20
  slugifyNodeId,
21
21
  targetsOf,
22
+ keywordHandle,
22
23
  type FlowGraphData,
23
24
  type FlowNodeData,
24
25
  } from './flowGraph'
@@ -206,7 +207,8 @@ export function buildFlowEdges(params: {
206
207
  for (const [nodeId, node] of Object.entries(graph.nodes)) {
207
208
  const live = (liveCounts[nodeId] ?? 0) > 0
208
209
 
209
- for (const { target, optionId, isDefault } of targetsOf(node)) {
210
+ for (const { target, optionId: answerId, keyword, isDefault } of targetsOf(node)) {
211
+ const optionId = keyword !== undefined ? keywordHandle(keyword) : answerId
210
212
  // Destino vazio é estado NORMAL, não anomalia: apagar um nó zera quem apontava para ele, e
211
213
  // `targetsOf` devolve o `default` mesmo em branco. Emitir a aresta criaria ligação para um nó
212
214
  // que não existe — o React Flow a descarta em silêncio, então o sintoma seria uma opção que
@@ -343,6 +345,16 @@ export function newNodeFromSpec(spec: NewNodeSpec, existingIds: ReadonlySet<stri
343
345
  return { id, type: 'condition', conditionOperator: '>' }
344
346
  }
345
347
 
348
+ if (spec.kind === 'dynamicChoice') {
349
+ const id = slugifyNodeId('nova_escolha_dinamica', existingIds)
350
+ return { id, type: 'dynamic_choice', contextKey: id, question: '' }
351
+ }
352
+
353
+ if (spec.kind === 'message') {
354
+ const id = slugifyNodeId('nova_mensagem', existingIds)
355
+ return { id, type: 'action', directMessage: '' }
356
+ }
357
+
346
358
  const id = slugifyNodeId('nova_acao', existingIds)
347
359
  return { id, type: 'action', actionKind: spec.actionKind }
348
360
  }
@@ -17,7 +17,7 @@ import type { FlowGraphData, FlowNodeData, FlowNodeNext } from '@adatechnology/m
17
17
 
18
18
  // A constante vem do `flowGraph`, que já a define, e não do contracts: duas fontes do mesmo prefixo
19
19
  // divergem em silêncio, e o sintoma seria salto entre fluxos que o motor do bot não reconhece.
20
- import { CROSS_FLOW_PREFIX, crossFlowTargetsOf } from './flowGraph'
20
+ import { CROSS_FLOW_PREFIX, crossFlowTargetsOf, keywordOfHandle } from './flowGraph'
21
21
 
22
22
  const NAMESPACE_SEPARATOR = '::'
23
23
 
@@ -152,12 +152,26 @@ export function applyConnection(node: FlowNodeData, resolved: ResolvedConnection
152
152
  if (resolved.handle === 'next') return { ...node, next: resolved.targetValue }
153
153
 
154
154
  if (resolved.handle === '__default') {
155
- return { ...node, next: { byAnswer: currentNext?.byAnswer ?? {}, default: resolved.targetValue } }
155
+ return { ...node, next: { ...currentNext, byAnswer: currentNext?.byAnswer ?? {}, default: resolved.targetValue } }
156
+ }
157
+
158
+ const keyword = keywordOfHandle(resolved.handle)
159
+ if (keyword !== undefined) {
160
+ return {
161
+ ...node,
162
+ next: {
163
+ ...currentNext,
164
+ byAnswer: currentNext?.byAnswer ?? {},
165
+ byKeyword: { ...(currentNext?.byKeyword ?? {}), [keyword]: resolved.targetValue },
166
+ default: currentNext?.default ?? '',
167
+ },
168
+ }
156
169
  }
157
170
 
158
171
  return {
159
172
  ...node,
160
173
  next: {
174
+ ...currentNext,
161
175
  byAnswer: { ...(currentNext?.byAnswer ?? {}), [resolved.handle]: resolved.targetValue },
162
176
  default: currentNext?.default ?? '',
163
177
  },
@@ -189,12 +203,18 @@ export function clearConnection(node: FlowNodeData, handle: string): FlowNodeDat
189
203
  }
190
204
 
191
205
  if (handle === '__default') {
192
- return { ...node, next: { byAnswer: node.next.byAnswer ?? {}, default: '' } }
206
+ return { ...node, next: { ...node.next, byAnswer: node.next.byAnswer ?? {}, default: '' } }
207
+ }
208
+
209
+ const keyword = keywordOfHandle(handle)
210
+ if (keyword !== undefined) {
211
+ return { ...node, next: { ...node.next, byKeyword: { ...(node.next.byKeyword ?? {}), [keyword]: '' } } }
193
212
  }
194
213
 
195
214
  return {
196
215
  ...node,
197
216
  next: {
217
+ ...node.next,
198
218
  byAnswer: { ...(node.next.byAnswer ?? {}), [handle]: '' },
199
219
  default: node.next.default ?? '',
200
220
  },
@@ -12,8 +12,10 @@ import type {
12
12
  FlowNodeNext,
13
13
  FlowNodeData,
14
14
  FlowGraphData,
15
+ FlowOptionDetail,
16
+ FlowAnswerValidation,
15
17
  } from '@adatechnology/meta-whatsapp-contracts'
16
- import { FLOW_ACTION_KIND } from '@adatechnology/meta-whatsapp-contracts'
18
+ import { FLOW_ACTION_KIND, WHATSAPP_CHOICE_LIMIT } from '@adatechnology/meta-whatsapp-contracts'
17
19
 
18
20
  export type {
19
21
  FlowNodeType,
@@ -23,6 +25,8 @@ export type {
23
25
  FlowNodeNext,
24
26
  FlowNodeData,
25
27
  FlowGraphData,
28
+ FlowOptionDetail,
29
+ FlowAnswerValidation,
26
30
  }
27
31
 
28
32
  export const CONDITION_OPERATORS: FlowConditionOperator[] = ['>', '>=', '<', '<=', '==', '!=', 'contains']
@@ -48,6 +52,22 @@ export const BUILT_IN_ACTION_KINDS = FLOW_ACTION_KIND
48
52
  */
49
53
  export const PASS_THROUGH_ACTION_KINDS: readonly string[] = ['send_media']
50
54
 
55
+ /**
56
+ * Ação que segue para o `next`. Nó de ação SEM `actionKind` é nó de mensagem: o runner do módulo
57
+ * envia o `directMessage` e continua, então ele precisa de saída no editor.
58
+ */
59
+ export function isPassThroughAction(node: FlowNodeData): boolean {
60
+ if (node.type !== 'action') return false
61
+ return !node.actionKind || PASS_THROUGH_ACTION_KINDS.includes(node.actionKind)
62
+ }
63
+
64
+ /** Handle do card para uma rota de `next.byKeyword` — `kw:<palavra>`, separado dos ids de opção. */
65
+ export const KEYWORD_HANDLE_PREFIX = 'kw:'
66
+ export const keywordHandle = (keyword: string): string => `${KEYWORD_HANDLE_PREFIX}${keyword}`
67
+ export function keywordOfHandle(handle: string): string | undefined {
68
+ return handle.startsWith(KEYWORD_HANDLE_PREFIX) ? handle.slice(KEYWORD_HANDLE_PREFIX.length) : undefined
69
+ }
70
+
51
71
  export const CROSS_FLOW_PREFIX = 'flow:'
52
72
  export const isCrossFlowTarget = (target: string): boolean => target.startsWith(CROSS_FLOW_PREFIX)
53
73
  export const crossFlowKey = (target: string): string => target.slice(CROSS_FLOW_PREFIX.length)
@@ -65,36 +85,63 @@ export function estimateNodeHeight(node: FlowNodeData): number {
65
85
  const rowCount =
66
86
  node.type === 'action'
67
87
  ? // Ação de passagem desenha uma linha de saída; terminal não desenha nenhuma.
68
- node.actionKind && PASS_THROUGH_ACTION_KINDS.includes(node.actionKind)
88
+ isPassThroughAction(node)
69
89
  ? 1
70
90
  : 0
71
91
  : node.type === 'condition'
72
92
  ? 2
73
93
  : node.type === 'menu' || node.questionType === 'choice'
74
- ? (node.options?.length ?? 0) + 1
75
- : 1
94
+ ? (node.options?.length ?? 0) + 1 + keywordCount(node)
95
+ : 1 + keywordCount(node)
76
96
  return HEADER_HEIGHT + BODY_HEIGHT + PADDING + rowCount * ROW_HEIGHT
77
97
  }
78
98
 
79
- // Limites reais da API do WhatsApp para mensagens interativas: até 3 opções o bot envia
80
- // BOTÕES (título ≤ 20 chars); com 4+ envia LISTA (até 10 itens, título ≤ 24 chars).
99
+ function keywordCount(node: FlowNodeData): number {
100
+ return typeof node.next === 'object' && node.next?.byKeyword ? Object.keys(node.next.byKeyword).length : 0
101
+ }
102
+
103
+ /**
104
+ * Limites da Meta, lidos do contrato (`WHATSAPP_CHOICE_LIMIT`) — o mesmo número que o módulo usa
105
+ * para recusar a mensagem. Antes eram uma cópia local, e duas cópias divergem sem nada acusar.
106
+ * Nome mantido para não quebrar quem já importa.
107
+ */
81
108
  export const WHATSAPP_LIMITS = {
82
- MAX_BUTTONS: 3,
83
- MAX_LIST_ROWS: 10,
84
- BUTTON_TITLE_MAX: 20,
85
- LIST_ROW_TITLE_MAX: 24,
86
- BODY_MAX: 1024,
109
+ MAX_BUTTONS: WHATSAPP_CHOICE_LIMIT.BUTTONS,
110
+ MAX_LIST_ROWS: WHATSAPP_CHOICE_LIMIT.LIST_ROWS,
111
+ BUTTON_TITLE_MAX: WHATSAPP_CHOICE_LIMIT.BUTTON_TITLE_LENGTH,
112
+ LIST_ROW_TITLE_MAX: WHATSAPP_CHOICE_LIMIT.LIST_ROW_TITLE_LENGTH,
113
+ LIST_ROW_DESCRIPTION_MAX: WHATSAPP_CHOICE_LIMIT.LIST_ROW_DESCRIPTION_LENGTH,
114
+ LIST_SECTION_TITLE_MAX: WHATSAPP_CHOICE_LIMIT.LIST_SECTION_TITLE_LENGTH,
115
+ BODY_MAX: WHATSAPP_CHOICE_LIMIT.BODY_LENGTH,
87
116
  } as const
88
117
 
89
- export function rendersAsButtons(options: [string, string][] | undefined): boolean {
90
- return (options?.length ?? 0) <= WHATSAPP_LIMITS.MAX_BUTTONS
118
+ /** Caracteres como o contrato conta: por code point, então um emoji vale 1 (e não 2, como `.length`). */
119
+ export function countCharacters(text: string): number {
120
+ return Array.from(text).length
91
121
  }
92
122
 
93
- export function targetsOf(node: FlowNodeData): { target: string; optionId?: string; isDefault?: boolean }[] {
123
+ /**
124
+ * Botão com até 3 opções simples; opção com descrição ou seção força lista — é a mesma regra do
125
+ * runner do módulo, para a prévia mostrar o que o cliente vai ver.
126
+ */
127
+ export function rendersAsButtons(
128
+ options: [string, string][] | undefined,
129
+ optionDetails?: Record<string, FlowOptionDetail>,
130
+ ): boolean {
131
+ const hasDetails = (options ?? []).some(
132
+ ([id]) => !!optionDetails?.[id]?.description || !!optionDetails?.[id]?.section,
133
+ )
134
+ return !hasDetails && (options?.length ?? 0) <= WHATSAPP_LIMITS.MAX_BUTTONS
135
+ }
136
+
137
+ export function targetsOf(
138
+ node: FlowNodeData,
139
+ ): { target: string; optionId?: string; keyword?: string; isDefault?: boolean }[] {
94
140
  if (!node.next) return []
95
141
  if (typeof node.next === 'string') return [{ target: node.next }]
96
142
  return [
97
143
  ...Object.entries(node.next.byAnswer).map(([optionId, target]) => ({ target, optionId })),
144
+ ...Object.entries(node.next.byKeyword ?? {}).map(([keyword, target]) => ({ target, keyword })),
98
145
  { target: node.next.default, isDefault: true },
99
146
  ]
100
147
  }
@@ -123,6 +170,10 @@ export function validateGraph(
123
170
  deadEndQuestion: (id: string) => string
124
171
  conditionIncomplete: (id: string) => string
125
172
  conditionBranchMissing: (id: string, branch: string) => string
173
+ // Opcionais para não quebrar quem monta os textos à mão; ausentes, vale o texto padrão.
174
+ descriptionTooLong?: (id: string, label: string) => string
175
+ dynamicChoiceWithoutProvider?: (id: string) => string
176
+ choiceDefaultIgnored?: (id: string) => string
126
177
  },
127
178
  ): GraphIssue[] {
128
179
  const issues: GraphIssue[] = []
@@ -156,21 +207,43 @@ export function validateGraph(
156
207
  if (!byAnswer[optionId]) {
157
208
  issues.push({ severity: 'warning', nodeId: node.id, message: issueText.optionWithoutTarget(node.id, label) })
158
209
  }
159
- const usesButtons = rendersAsButtons(options)
160
- if (usesButtons && label.length > WHATSAPP_LIMITS.BUTTON_TITLE_MAX) {
210
+ const usesButtons = rendersAsButtons(options, node.optionDetails)
211
+ if (usesButtons && countCharacters(label) > WHATSAPP_LIMITS.BUTTON_TITLE_MAX) {
161
212
  issues.push({ severity: 'error', nodeId: node.id, message: issueText.buttonTitleTooLong(node.id, label) })
162
213
  }
163
- if (!usesButtons && label.length > WHATSAPP_LIMITS.LIST_ROW_TITLE_MAX) {
214
+ if (!usesButtons && countCharacters(label) > WHATSAPP_LIMITS.LIST_ROW_TITLE_MAX) {
164
215
  issues.push({ severity: 'error', nodeId: node.id, message: issueText.listTitleTooLong(node.id, label) })
165
216
  }
217
+ const description = node.optionDetails?.[optionId]?.description ?? ''
218
+ if (countCharacters(description) > WHATSAPP_LIMITS.LIST_ROW_DESCRIPTION_MAX) {
219
+ const message =
220
+ issueText.descriptionTooLong?.(node.id, label) ??
221
+ `“${label}” em ${node.id}: a descrição passa de ${WHATSAPP_LIMITS.LIST_ROW_DESCRIPTION_MAX} caracteres.`
222
+ issues.push({ severity: 'error', nodeId: node.id, message })
223
+ }
224
+ }
225
+ // Com o runner em `reask` (padrão), resposta fora das opções repergunta: um "caso contrário"
226
+ // apontando para outro nó nunca seria seguido. Aviso, não erro — o host pode ligar `default`.
227
+ const defaultTarget = typeof node.next === 'object' && node.next ? node.next.default : ''
228
+ if (defaultTarget && defaultTarget !== node.id && node.unmatchedChoice !== 'default') {
229
+ const message =
230
+ issueText.choiceDefaultIgnored?.(node.id) ??
231
+ `Nó "${node.id}": "caso contrário" só é seguido com "resposta fora das opções" = seguir o caso contrário.`
232
+ issues.push({ severity: 'warning', nodeId: node.id, message })
166
233
  }
167
234
  if (options.length > WHATSAPP_LIMITS.MAX_LIST_ROWS) {
168
235
  issues.push({ severity: 'error', nodeId: node.id, message: issueText.tooManyOptions(node.id, options.length) })
169
236
  }
170
237
  }
171
238
 
239
+ if (node.type === 'dynamic_choice' && !node.choiceProvider) {
240
+ const message =
241
+ issueText.dynamicChoiceWithoutProvider?.(node.id) ?? `${node.id}: escolha dinâmica sem provedor de opções.`
242
+ issues.push({ severity: 'error', nodeId: node.id, message })
243
+ }
244
+
172
245
  const bodyText = node.question ?? node.directMessage ?? ''
173
- if (bodyText.length > WHATSAPP_LIMITS.BODY_MAX) {
246
+ if (countCharacters(bodyText) > WHATSAPP_LIMITS.BODY_MAX) {
174
247
  issues.push({ severity: 'error', nodeId: node.id, message: issueText.bodyTooLong(node.id) })
175
248
  }
176
249
 
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Copyright (c) 2026 Ada Technology. MIT License.
3
+ *
4
+ * Classes dos campos do painel de nó, compartilhadas para os campos novos baterem com os vizinhos.
5
+ */
6
+
7
+ export const PANEL_FIELD_CLASSNAME =
8
+ 'border border-gray-200 dark:border-gray-600 dark:bg-gray-700 dark:text-gray-100 rounded-xl px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-400 focus:border-transparent transition-all'
9
+
10
+ export const PANEL_LABEL_CLASSNAME = 'text-xs font-medium text-gray-500 dark:text-gray-400'
11
+ export const PANEL_HINT_CLASSNAME = 'text-[11px] text-gray-400 dark:text-gray-500 mt-1'