@adatechnology/conversations-ui 0.15.1 → 0.17.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 +23 -0
- package/dist/{ConversationSimulatorPanel-P6eqTSAO.d.ts → ConversationSimulatorPanel-DSVIch04.d.ts} +3 -1
- package/dist/{chunk-Y326LLEP.js → chunk-7OLYCCLX.js} +1 -1
- package/dist/{chunk-WCZNIJ3M.js → chunk-Z7U22M3K.js} +7 -0
- package/dist/flows/index.d.ts +90 -7
- package/dist/flows/index.js +1151 -455
- package/dist/index.d.ts +36 -5
- package/dist/index.js +88 -23
- package/dist/participant/index.js +1 -1
- package/dist/preview/index.d.ts +13 -29
- package/dist/preview/index.js +2 -2
- package/package.json +2 -2
- package/src/flows/FlowKeywordRoutesField.tsx +105 -0
- package/src/flows/FlowLegend.tsx +2 -2
- package/src/flows/FlowNodeCard.tsx +39 -10
- package/src/flows/FlowNodePanel.tsx +34 -10
- package/src/flows/FlowPalette.tsx +25 -2
- package/src/flows/FlowPossibleNextField.tsx +89 -0
- package/src/flows/FlowRunnerFields.tsx +321 -0
- package/src/flows/FlowWhatsAppPreview.tsx +39 -6
- package/src/flows/flowCanvasModel.test.ts +3 -2
- package/src/flows/flowCanvasModel.ts +28 -1
- package/src/flows/flowEditorOps.ts +41 -4
- package/src/flows/flowGraph.ts +124 -21
- package/src/flows/flowPanelStyles.ts +11 -0
- package/src/flows/flowPossibleNext.test.ts +70 -0
- package/src/flows/flowRunnerEditor.test.ts +116 -0
- package/src/flows/labels.ts +116 -2
- package/src/index.ts +2 -1
- package/src/lib/phone.test.ts +20 -0
- package/src/lib/phone.ts +13 -0
- package/src/preview/createPreviewBridgeClient.test.ts +23 -0
- package/src/preview/createPreviewBridgeClient.ts +13 -8
- package/src/preview/createPreviewWebhookClient.ts +2 -0
- package/src/workspace/ConversationPane.tsx +13 -2
- package/src/workspace/ConversationsWorkspace.tsx +117 -18
- package/src/workspace/index.ts +1 -0
- package/src/workspace/labels.ts +2 -0
- package/src/workspace/workspaceTestContactDom.test.tsx +96 -0
|
@@ -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
|
|
49
|
-
<div key={
|
|
50
|
-
|
|
51
|
-
|
|
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
|
-
|
|
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: '
|
|
362
|
+
estimateNodeHeight({ id: 'd', type: 'action', actionKind: 'send_media' }),
|
|
362
363
|
)
|
|
363
364
|
})
|
|
364
365
|
})
|
|
@@ -19,6 +19,8 @@ import {
|
|
|
19
19
|
isCrossFlowTarget,
|
|
20
20
|
slugifyNodeId,
|
|
21
21
|
targetsOf,
|
|
22
|
+
keywordHandle,
|
|
23
|
+
possibleNextHandle,
|
|
22
24
|
type FlowGraphData,
|
|
23
25
|
type FlowNodeData,
|
|
24
26
|
} from './flowGraph'
|
|
@@ -206,7 +208,8 @@ export function buildFlowEdges(params: {
|
|
|
206
208
|
for (const [nodeId, node] of Object.entries(graph.nodes)) {
|
|
207
209
|
const live = (liveCounts[nodeId] ?? 0) > 0
|
|
208
210
|
|
|
209
|
-
for (const { target, optionId, isDefault } of targetsOf(node)) {
|
|
211
|
+
for (const { target, optionId: answerId, keyword, isDefault, isPossible } of targetsOf(node)) {
|
|
212
|
+
const optionId = keyword !== undefined ? keywordHandle(keyword) : answerId
|
|
210
213
|
// Destino vazio é estado NORMAL, não anomalia: apagar um nó zera quem apontava para ele, e
|
|
211
214
|
// `targetsOf` devolve o `default` mesmo em branco. Emitir a aresta criaria ligação para um nó
|
|
212
215
|
// que não existe — o React Flow a descarta em silêncio, então o sintoma seria uma opção que
|
|
@@ -236,6 +239,20 @@ export function buildFlowEdges(params: {
|
|
|
236
239
|
// repetição na linha de saída, dentro do card (ver `FlowNodeCard`).
|
|
237
240
|
if (source === edgeTarget) continue
|
|
238
241
|
|
|
242
|
+
// Caminho que a action PODE escolher: tracejado como o fallback, nunca animado.
|
|
243
|
+
if (isPossible) {
|
|
244
|
+
edges.push({
|
|
245
|
+
id: `${source}->${edgeTarget}-possible`,
|
|
246
|
+
source,
|
|
247
|
+
target: edgeTarget,
|
|
248
|
+
sourceHandle: possibleNextHandle(target),
|
|
249
|
+
kind: 'fallback',
|
|
250
|
+
crossFlow,
|
|
251
|
+
live: false,
|
|
252
|
+
})
|
|
253
|
+
continue
|
|
254
|
+
}
|
|
255
|
+
|
|
239
256
|
if (isDefault) {
|
|
240
257
|
edges.push({
|
|
241
258
|
id: `${source}->${edgeTarget}-default`,
|
|
@@ -343,6 +360,16 @@ export function newNodeFromSpec(spec: NewNodeSpec, existingIds: ReadonlySet<stri
|
|
|
343
360
|
return { id, type: 'condition', conditionOperator: '>' }
|
|
344
361
|
}
|
|
345
362
|
|
|
363
|
+
if (spec.kind === 'dynamicChoice') {
|
|
364
|
+
const id = slugifyNodeId('nova_escolha_dinamica', existingIds)
|
|
365
|
+
return { id, type: 'dynamic_choice', contextKey: id, question: '' }
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
if (spec.kind === 'message') {
|
|
369
|
+
const id = slugifyNodeId('nova_mensagem', existingIds)
|
|
370
|
+
return { id, type: 'action', directMessage: '' }
|
|
371
|
+
}
|
|
372
|
+
|
|
346
373
|
const id = slugifyNodeId('nova_acao', existingIds)
|
|
347
374
|
return { id, type: 'action', actionKind: spec.actionKind }
|
|
348
375
|
}
|
|
@@ -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, possibleNextOfHandle } from './flowGraph'
|
|
21
21
|
|
|
22
22
|
const NAMESPACE_SEPARATOR = '::'
|
|
23
23
|
|
|
@@ -50,7 +50,10 @@ export function removeNodeAndCleanRefs(
|
|
|
50
50
|
|
|
51
51
|
for (const [id, node] of Object.entries(nodes)) {
|
|
52
52
|
if (id === removedId) continue
|
|
53
|
-
|
|
53
|
+
const cleaned: FlowNodeData = { ...node, next: cleanNext(node.next, removedId) }
|
|
54
|
+
// Destino possível não é linha visível de opção: some junto com o nó apagado.
|
|
55
|
+
if (node.possibleNext) cleaned.possibleNext = node.possibleNext.filter((target) => target !== removedId)
|
|
56
|
+
remaining[id] = cleaned
|
|
54
57
|
}
|
|
55
58
|
|
|
56
59
|
return remaining
|
|
@@ -151,13 +154,30 @@ export function applyConnection(node: FlowNodeData, resolved: ResolvedConnection
|
|
|
151
154
|
|
|
152
155
|
if (resolved.handle === 'next') return { ...node, next: resolved.targetValue }
|
|
153
156
|
|
|
157
|
+
const possible = possibleNextOfHandle(resolved.handle)
|
|
158
|
+
if (possible !== undefined) return withPossibleNext(node, possible, resolved.targetValue)
|
|
159
|
+
|
|
154
160
|
if (resolved.handle === '__default') {
|
|
155
|
-
return { ...node, next: { byAnswer: currentNext?.byAnswer ?? {}, default: resolved.targetValue } }
|
|
161
|
+
return { ...node, next: { ...currentNext, byAnswer: currentNext?.byAnswer ?? {}, default: resolved.targetValue } }
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const keyword = keywordOfHandle(resolved.handle)
|
|
165
|
+
if (keyword !== undefined) {
|
|
166
|
+
return {
|
|
167
|
+
...node,
|
|
168
|
+
next: {
|
|
169
|
+
...currentNext,
|
|
170
|
+
byAnswer: currentNext?.byAnswer ?? {},
|
|
171
|
+
byKeyword: { ...(currentNext?.byKeyword ?? {}), [keyword]: resolved.targetValue },
|
|
172
|
+
default: currentNext?.default ?? '',
|
|
173
|
+
},
|
|
174
|
+
}
|
|
156
175
|
}
|
|
157
176
|
|
|
158
177
|
return {
|
|
159
178
|
...node,
|
|
160
179
|
next: {
|
|
180
|
+
...currentNext,
|
|
161
181
|
byAnswer: { ...(currentNext?.byAnswer ?? {}), [resolved.handle]: resolved.targetValue },
|
|
162
182
|
default: currentNext?.default ?? '',
|
|
163
183
|
},
|
|
@@ -183,18 +203,35 @@ export function isGraphDirty(working: FlowGraphData | undefined, published: Flow
|
|
|
183
203
|
* opção sem `byAnswer` some do card — e some junto o botão que o cliente via no WhatsApp, o que se
|
|
184
204
|
* lê como "o editor apagou minha opção". Vazio mantém a linha visível, cobrando a religação.
|
|
185
205
|
*/
|
|
206
|
+
function withPossibleNext(node: FlowNodeData, replaced: string, target: string | undefined): FlowNodeData {
|
|
207
|
+
const current = node.possibleNext ?? []
|
|
208
|
+
const updated = current.flatMap((entry) => (entry === replaced ? (target ? [target] : []) : [entry]))
|
|
209
|
+
if (!current.includes(replaced) && target) updated.push(target)
|
|
210
|
+
return { ...node, possibleNext: [...new Set(updated)] }
|
|
211
|
+
}
|
|
212
|
+
|
|
186
213
|
export function clearConnection(node: FlowNodeData, handle: string): FlowNodeData {
|
|
214
|
+
// Destino possível sem alvo não tem o que mostrar: desligar é tirá-lo da lista.
|
|
215
|
+
const possible = possibleNextOfHandle(handle)
|
|
216
|
+
if (possible !== undefined) return withPossibleNext(node, possible, undefined)
|
|
217
|
+
|
|
187
218
|
if (handle === 'next' || typeof node.next === 'string' || node.next === undefined) {
|
|
188
219
|
return { ...node, next: '' }
|
|
189
220
|
}
|
|
190
221
|
|
|
191
222
|
if (handle === '__default') {
|
|
192
|
-
return { ...node, next: { byAnswer: node.next.byAnswer ?? {}, default: '' } }
|
|
223
|
+
return { ...node, next: { ...node.next, byAnswer: node.next.byAnswer ?? {}, default: '' } }
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
const keyword = keywordOfHandle(handle)
|
|
227
|
+
if (keyword !== undefined) {
|
|
228
|
+
return { ...node, next: { ...node.next, byKeyword: { ...(node.next.byKeyword ?? {}), [keyword]: '' } } }
|
|
193
229
|
}
|
|
194
230
|
|
|
195
231
|
return {
|
|
196
232
|
...node,
|
|
197
233
|
next: {
|
|
234
|
+
...node.next,
|
|
198
235
|
byAnswer: { ...(node.next.byAnswer ?? {}), [handle]: '' },
|
|
199
236
|
default: node.next.default ?? '',
|
|
200
237
|
},
|
package/src/flows/flowGraph.ts
CHANGED
|
@@ -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,32 @@ 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
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Handle do card para um destino de `possibleNext` — `maybe:<destino>`. A action escolhe o caminho em
|
|
73
|
+
* tempo de execução (o `next` que o handler devolve); o editor só desenha o que o nó declara.
|
|
74
|
+
*/
|
|
75
|
+
export const POSSIBLE_NEXT_HANDLE_PREFIX = 'maybe:'
|
|
76
|
+
export const possibleNextHandle = (target: string): string => `${POSSIBLE_NEXT_HANDLE_PREFIX}${target}`
|
|
77
|
+
export function possibleNextOfHandle(handle: string): string | undefined {
|
|
78
|
+
return handle.startsWith(POSSIBLE_NEXT_HANDLE_PREFIX) ? handle.slice(POSSIBLE_NEXT_HANDLE_PREFIX.length) : undefined
|
|
79
|
+
}
|
|
80
|
+
|
|
51
81
|
export const CROSS_FLOW_PREFIX = 'flow:'
|
|
52
82
|
export const isCrossFlowTarget = (target: string): boolean => target.startsWith(CROSS_FLOW_PREFIX)
|
|
53
83
|
export const crossFlowKey = (target: string): string => target.slice(CROSS_FLOW_PREFIX.length)
|
|
@@ -64,41 +94,79 @@ export function estimateNodeHeight(node: FlowNodeData): number {
|
|
|
64
94
|
const ROW_HEIGHT = 34
|
|
65
95
|
const rowCount =
|
|
66
96
|
node.type === 'action'
|
|
67
|
-
? // Ação de passagem desenha uma linha de saída; terminal não desenha nenhuma.
|
|
68
|
-
|
|
69
|
-
? 1
|
|
70
|
-
: 0
|
|
97
|
+
? // Ação de passagem desenha uma linha de saída; terminal não desenha nenhuma. Cada destino
|
|
98
|
+
// declarado em `possibleNext` é mais uma linha.
|
|
99
|
+
(isPassThroughAction(node) ? 1 : 0) + (node.possibleNext?.length ?? 0)
|
|
71
100
|
: node.type === 'condition'
|
|
72
101
|
? 2
|
|
73
102
|
: node.type === 'menu' || node.questionType === 'choice'
|
|
74
|
-
? (node.options?.length ?? 0) + 1
|
|
75
|
-
: 1
|
|
103
|
+
? (node.options?.length ?? 0) + 1 + keywordCount(node)
|
|
104
|
+
: 1 + keywordCount(node)
|
|
76
105
|
return HEADER_HEIGHT + BODY_HEIGHT + PADDING + rowCount * ROW_HEIGHT
|
|
77
106
|
}
|
|
78
107
|
|
|
79
|
-
|
|
80
|
-
|
|
108
|
+
function keywordCount(node: FlowNodeData): number {
|
|
109
|
+
return typeof node.next === 'object' && node.next?.byKeyword ? Object.keys(node.next.byKeyword).length : 0
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Limites da Meta, lidos do contrato (`WHATSAPP_CHOICE_LIMIT`) — o mesmo número que o módulo usa
|
|
114
|
+
* para recusar a mensagem. Antes eram uma cópia local, e duas cópias divergem sem nada acusar.
|
|
115
|
+
* Nome mantido para não quebrar quem já importa.
|
|
116
|
+
*/
|
|
81
117
|
export const WHATSAPP_LIMITS = {
|
|
82
|
-
MAX_BUTTONS:
|
|
83
|
-
MAX_LIST_ROWS:
|
|
84
|
-
BUTTON_TITLE_MAX:
|
|
85
|
-
LIST_ROW_TITLE_MAX:
|
|
86
|
-
|
|
118
|
+
MAX_BUTTONS: WHATSAPP_CHOICE_LIMIT.BUTTONS,
|
|
119
|
+
MAX_LIST_ROWS: WHATSAPP_CHOICE_LIMIT.LIST_ROWS,
|
|
120
|
+
BUTTON_TITLE_MAX: WHATSAPP_CHOICE_LIMIT.BUTTON_TITLE_LENGTH,
|
|
121
|
+
LIST_ROW_TITLE_MAX: WHATSAPP_CHOICE_LIMIT.LIST_ROW_TITLE_LENGTH,
|
|
122
|
+
LIST_ROW_DESCRIPTION_MAX: WHATSAPP_CHOICE_LIMIT.LIST_ROW_DESCRIPTION_LENGTH,
|
|
123
|
+
LIST_SECTION_TITLE_MAX: WHATSAPP_CHOICE_LIMIT.LIST_SECTION_TITLE_LENGTH,
|
|
124
|
+
BODY_MAX: WHATSAPP_CHOICE_LIMIT.BODY_LENGTH,
|
|
87
125
|
} as const
|
|
88
126
|
|
|
89
|
-
|
|
90
|
-
|
|
127
|
+
/** Caracteres como o contrato conta: por code point, então um emoji vale 1 (e não 2, como `.length`). */
|
|
128
|
+
export function countCharacters(text: string): number {
|
|
129
|
+
return Array.from(text).length
|
|
91
130
|
}
|
|
92
131
|
|
|
93
|
-
|
|
132
|
+
/**
|
|
133
|
+
* Botão com até 3 opções simples; opção com descrição ou seção força lista — é a mesma regra do
|
|
134
|
+
* runner do módulo, para a prévia mostrar o que o cliente vai ver.
|
|
135
|
+
*/
|
|
136
|
+
export function rendersAsButtons(
|
|
137
|
+
options: [string, string][] | undefined,
|
|
138
|
+
optionDetails?: Record<string, FlowOptionDetail>,
|
|
139
|
+
): boolean {
|
|
140
|
+
const hasDetails = (options ?? []).some(
|
|
141
|
+
([id]) => !!optionDetails?.[id]?.description || !!optionDetails?.[id]?.section,
|
|
142
|
+
)
|
|
143
|
+
return !hasDetails && (options?.length ?? 0) <= WHATSAPP_LIMITS.MAX_BUTTONS
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export type FlowNodeTarget = {
|
|
147
|
+
target: string
|
|
148
|
+
optionId?: string
|
|
149
|
+
keyword?: string
|
|
150
|
+
isDefault?: boolean
|
|
151
|
+
/** Destino de `possibleNext`: a action pode escolher, não é garantido. */
|
|
152
|
+
isPossible?: boolean
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function nextTargetsOf(node: FlowNodeData): FlowNodeTarget[] {
|
|
94
156
|
if (!node.next) return []
|
|
95
157
|
if (typeof node.next === 'string') return [{ target: node.next }]
|
|
96
158
|
return [
|
|
97
159
|
...Object.entries(node.next.byAnswer).map(([optionId, target]) => ({ target, optionId })),
|
|
160
|
+
...Object.entries(node.next.byKeyword ?? {}).map(([keyword, target]) => ({ target, keyword })),
|
|
98
161
|
{ target: node.next.default, isDefault: true },
|
|
99
162
|
]
|
|
100
163
|
}
|
|
101
164
|
|
|
165
|
+
export function targetsOf(node: FlowNodeData): FlowNodeTarget[] {
|
|
166
|
+
const possible = (node.possibleNext ?? []).map((target) => ({ target, isPossible: true }))
|
|
167
|
+
return [...nextTargetsOf(node), ...possible]
|
|
168
|
+
}
|
|
169
|
+
|
|
102
170
|
export type GraphIssue = {
|
|
103
171
|
severity: 'error' | 'warning'
|
|
104
172
|
nodeId?: string
|
|
@@ -123,6 +191,11 @@ export function validateGraph(
|
|
|
123
191
|
deadEndQuestion: (id: string) => string
|
|
124
192
|
conditionIncomplete: (id: string) => string
|
|
125
193
|
conditionBranchMissing: (id: string, branch: string) => string
|
|
194
|
+
// Opcionais para não quebrar quem monta os textos à mão; ausentes, vale o texto padrão.
|
|
195
|
+
descriptionTooLong?: (id: string, label: string) => string
|
|
196
|
+
dynamicChoiceWithoutProvider?: (id: string) => string
|
|
197
|
+
choiceDefaultIgnored?: (id: string) => string
|
|
198
|
+
possibleNextIgnored?: (id: string) => string
|
|
126
199
|
},
|
|
127
200
|
): GraphIssue[] {
|
|
128
201
|
const issues: GraphIssue[] = []
|
|
@@ -156,21 +229,51 @@ export function validateGraph(
|
|
|
156
229
|
if (!byAnswer[optionId]) {
|
|
157
230
|
issues.push({ severity: 'warning', nodeId: node.id, message: issueText.optionWithoutTarget(node.id, label) })
|
|
158
231
|
}
|
|
159
|
-
const usesButtons = rendersAsButtons(options)
|
|
160
|
-
if (usesButtons && label
|
|
232
|
+
const usesButtons = rendersAsButtons(options, node.optionDetails)
|
|
233
|
+
if (usesButtons && countCharacters(label) > WHATSAPP_LIMITS.BUTTON_TITLE_MAX) {
|
|
161
234
|
issues.push({ severity: 'error', nodeId: node.id, message: issueText.buttonTitleTooLong(node.id, label) })
|
|
162
235
|
}
|
|
163
|
-
if (!usesButtons && label
|
|
236
|
+
if (!usesButtons && countCharacters(label) > WHATSAPP_LIMITS.LIST_ROW_TITLE_MAX) {
|
|
164
237
|
issues.push({ severity: 'error', nodeId: node.id, message: issueText.listTitleTooLong(node.id, label) })
|
|
165
238
|
}
|
|
239
|
+
const description = node.optionDetails?.[optionId]?.description ?? ''
|
|
240
|
+
if (countCharacters(description) > WHATSAPP_LIMITS.LIST_ROW_DESCRIPTION_MAX) {
|
|
241
|
+
const message =
|
|
242
|
+
issueText.descriptionTooLong?.(node.id, label) ??
|
|
243
|
+
`“${label}” em ${node.id}: a descrição passa de ${WHATSAPP_LIMITS.LIST_ROW_DESCRIPTION_MAX} caracteres.`
|
|
244
|
+
issues.push({ severity: 'error', nodeId: node.id, message })
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
// Com o runner em `reask` (padrão), resposta fora das opções repergunta: um "caso contrário"
|
|
248
|
+
// apontando para outro nó nunca seria seguido. Aviso, não erro — o host pode ligar `default`.
|
|
249
|
+
const defaultTarget = typeof node.next === 'object' && node.next ? node.next.default : ''
|
|
250
|
+
if (defaultTarget && defaultTarget !== node.id && node.unmatchedChoice !== 'default') {
|
|
251
|
+
const message =
|
|
252
|
+
issueText.choiceDefaultIgnored?.(node.id) ??
|
|
253
|
+
`Nó "${node.id}": "caso contrário" só é seguido com "resposta fora das opções" = seguir o caso contrário.`
|
|
254
|
+
issues.push({ severity: 'warning', nodeId: node.id, message })
|
|
166
255
|
}
|
|
167
256
|
if (options.length > WHATSAPP_LIMITS.MAX_LIST_ROWS) {
|
|
168
257
|
issues.push({ severity: 'error', nodeId: node.id, message: issueText.tooManyOptions(node.id, options.length) })
|
|
169
258
|
}
|
|
170
259
|
}
|
|
171
260
|
|
|
261
|
+
// Só a action devolve `next` em tempo de execução: em outro nó a lista desenharia caminho que não existe.
|
|
262
|
+
if ((node.possibleNext?.length ?? 0) > 0 && (node.type !== 'action' || !node.actionKind)) {
|
|
263
|
+
const message =
|
|
264
|
+
issueText.possibleNextIgnored?.(node.id) ??
|
|
265
|
+
`${node.id}: "destinos que a ação pode escolher" só valem em nó de ação com tipo de ação.`
|
|
266
|
+
issues.push({ severity: 'warning', nodeId: node.id, message })
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
if (node.type === 'dynamic_choice' && !node.choiceProvider) {
|
|
270
|
+
const message =
|
|
271
|
+
issueText.dynamicChoiceWithoutProvider?.(node.id) ?? `${node.id}: escolha dinâmica sem provedor de opções.`
|
|
272
|
+
issues.push({ severity: 'error', nodeId: node.id, message })
|
|
273
|
+
}
|
|
274
|
+
|
|
172
275
|
const bodyText = node.question ?? node.directMessage ?? ''
|
|
173
|
-
if (bodyText
|
|
276
|
+
if (countCharacters(bodyText) > WHATSAPP_LIMITS.BODY_MAX) {
|
|
174
277
|
issues.push({ severity: 'error', nodeId: node.id, message: issueText.bodyTooLong(node.id) })
|
|
175
278
|
}
|
|
176
279
|
|
|
@@ -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'
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
3
|
+
*
|
|
4
|
+
* `possibleNext`: destinos que a action pode devolver em tempo de execução. O editor desenha, valida
|
|
5
|
+
* e limpa esses caminhos como qualquer outro, sem mudar o `next` do nó.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { describe, expect, it } from 'bun:test'
|
|
9
|
+
import { buildFlowEdges } from './flowCanvasModel'
|
|
10
|
+
import { applyConnection, clearConnection, removeNodeAndCleanRefs, resolveConnection } from './flowEditorOps'
|
|
11
|
+
import { estimateNodeHeight, possibleNextHandle, validateGraph, type FlowGraphData } from './flowGraph'
|
|
12
|
+
import { DEFAULT_FLOW_EDITOR_LABELS } from './labels'
|
|
13
|
+
|
|
14
|
+
function bookingGraph(): FlowGraphData {
|
|
15
|
+
return {
|
|
16
|
+
key: 'main',
|
|
17
|
+
label: 'Main',
|
|
18
|
+
startNodeId: 'check',
|
|
19
|
+
version: 1,
|
|
20
|
+
nodes: {
|
|
21
|
+
check: { id: 'check', type: 'action', actionKind: 'check_slot', possibleNext: ['full'], next: 'confirm' },
|
|
22
|
+
confirm: { id: 'confirm', type: 'action', directMessage: 'Reservado!' },
|
|
23
|
+
full: { id: 'full', type: 'action', directMessage: 'Lotado.' },
|
|
24
|
+
},
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
describe('possibleNext in the flow editor', () => {
|
|
29
|
+
it('draws a dashed edge from its own handle and keeps the target reachable', () => {
|
|
30
|
+
const graph = bookingGraph()
|
|
31
|
+
const edges = buildFlowEdges({ openKeys: ['main'], graphs: { main: graph }, rootFlowKey: 'main' })
|
|
32
|
+
expect(edges).toContainEqual(
|
|
33
|
+
expect.objectContaining({
|
|
34
|
+
source: 'main::check',
|
|
35
|
+
target: 'main::full',
|
|
36
|
+
sourceHandle: possibleNextHandle('full'),
|
|
37
|
+
kind: 'fallback',
|
|
38
|
+
live: false,
|
|
39
|
+
}),
|
|
40
|
+
)
|
|
41
|
+
const messages = validateGraph(graph, DEFAULT_FLOW_EDITOR_LABELS.validation).map((issue) => issue.message)
|
|
42
|
+
expect(messages.filter((message) => message.includes('full'))).toEqual([])
|
|
43
|
+
})
|
|
44
|
+
|
|
45
|
+
it('flags a broken possible target and possibleNext on a node that cannot branch', () => {
|
|
46
|
+
const graph = bookingGraph()
|
|
47
|
+
graph.nodes.check = { ...graph.nodes.check!, possibleNext: ['ghost'] }
|
|
48
|
+
graph.nodes.confirm = { ...graph.nodes.confirm!, possibleNext: ['full'] }
|
|
49
|
+
const issues = validateGraph(graph, DEFAULT_FLOW_EDITOR_LABELS.validation)
|
|
50
|
+
expect(issues.some((issue) => issue.severity === 'error' && issue.message.includes('ghost'))).toBe(true)
|
|
51
|
+
expect(issues.some((issue) => issue.severity === 'warning' && issue.nodeId === 'confirm')).toBe(true)
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
it('reconnects, disconnects and cleans possible targets without touching next', () => {
|
|
55
|
+
const graphs = { main: bookingGraph() }
|
|
56
|
+
const check = graphs.main.nodes.check!
|
|
57
|
+
const resolved = resolveConnection({
|
|
58
|
+
connection: { source: 'main::check', target: 'main::confirm', sourceHandle: possibleNextHandle('full') },
|
|
59
|
+
graphs,
|
|
60
|
+
})
|
|
61
|
+
expect(resolved && applyConnection(check, resolved)).toMatchObject({ possibleNext: ['confirm'], next: 'confirm' })
|
|
62
|
+
expect(clearConnection(check, possibleNextHandle('full'))).toMatchObject({ possibleNext: [], next: 'confirm' })
|
|
63
|
+
expect(removeNodeAndCleanRefs(graphs.main.nodes, 'full').check).toMatchObject({ possibleNext: [], next: 'confirm' })
|
|
64
|
+
})
|
|
65
|
+
|
|
66
|
+
it('makes the card taller by one row per possible target', () => {
|
|
67
|
+
const check = bookingGraph().nodes.check!
|
|
68
|
+
expect(estimateNodeHeight(check)).toBeGreaterThan(estimateNodeHeight({ ...check, possibleNext: undefined }))
|
|
69
|
+
})
|
|
70
|
+
})
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { describe, expect, it } from 'bun:test'
|
|
6
|
+
import { WHATSAPP_CHOICE_LIMIT } from '@adatechnology/meta-whatsapp-contracts'
|
|
7
|
+
import {
|
|
8
|
+
countCharacters,
|
|
9
|
+
rendersAsButtons,
|
|
10
|
+
targetsOf,
|
|
11
|
+
validateGraph,
|
|
12
|
+
WHATSAPP_LIMITS,
|
|
13
|
+
type FlowGraphData,
|
|
14
|
+
} from './flowGraph'
|
|
15
|
+
import { applyConnection, clearConnection } from './flowEditorOps'
|
|
16
|
+
import { DEFAULT_FLOW_EDITOR_LABELS, mergeFlowEditorLabels } from './labels'
|
|
17
|
+
|
|
18
|
+
describe('editor limits come from the contract', () => {
|
|
19
|
+
it('mirrors WHATSAPP_CHOICE_LIMIT', () => {
|
|
20
|
+
expect(WHATSAPP_LIMITS.MAX_BUTTONS).toBe(WHATSAPP_CHOICE_LIMIT.BUTTONS)
|
|
21
|
+
expect(WHATSAPP_LIMITS.LIST_ROW_DESCRIPTION_MAX).toBe(WHATSAPP_CHOICE_LIMIT.LIST_ROW_DESCRIPTION_LENGTH)
|
|
22
|
+
})
|
|
23
|
+
|
|
24
|
+
it('counts an emoji as one character, like the contract', () => {
|
|
25
|
+
expect(countCharacters('🙋 Atendente')).toBe(11)
|
|
26
|
+
})
|
|
27
|
+
|
|
28
|
+
it('renders a list when an option has a description or section', () => {
|
|
29
|
+
const options: [string, string][] = [['a', 'A']]
|
|
30
|
+
expect(rendersAsButtons(options)).toBe(true)
|
|
31
|
+
expect(rendersAsButtons(options, { a: { description: 'detalhe' } })).toBe(false)
|
|
32
|
+
})
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
describe('keyword routes in the editor', () => {
|
|
36
|
+
const node = {
|
|
37
|
+
id: 'menu',
|
|
38
|
+
type: 'menu' as const,
|
|
39
|
+
options: [['a', 'A']] as [string, string][],
|
|
40
|
+
next: { byAnswer: { a: 'x' }, byKeyword: { horario: 'hours' }, default: 'menu' },
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
it('lists keyword targets', () => {
|
|
44
|
+
expect(targetsOf(node)).toContainEqual({ target: 'hours', keyword: 'horario' })
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
it('keeps keyword routes when connecting an option and edits them through kw: handles', () => {
|
|
48
|
+
const connected = applyConnection(node, { flowKey: 'main', nodeId: 'menu', handle: 'a', targetValue: 'y' })
|
|
49
|
+
expect(connected.next).toMatchObject({ byKeyword: { horario: 'hours' }, byAnswer: { a: 'y' } })
|
|
50
|
+
const rerouted = applyConnection(node, { flowKey: 'main', nodeId: 'menu', handle: 'kw:horario', targetValue: 'z' })
|
|
51
|
+
expect(rerouted.next).toMatchObject({ byKeyword: { horario: 'z' }, byAnswer: { a: 'x' } })
|
|
52
|
+
expect(clearConnection(node, 'kw:horario').next).toMatchObject({ byKeyword: { horario: '' } })
|
|
53
|
+
})
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
describe('validateGraph — runner fields', () => {
|
|
57
|
+
it('flags long descriptions and dynamic choices without provider', () => {
|
|
58
|
+
const graph: FlowGraphData = {
|
|
59
|
+
key: 'main',
|
|
60
|
+
label: 'main',
|
|
61
|
+
startNodeId: 'menu',
|
|
62
|
+
version: 1,
|
|
63
|
+
nodes: {
|
|
64
|
+
menu: {
|
|
65
|
+
id: 'menu',
|
|
66
|
+
type: 'menu',
|
|
67
|
+
options: [['a', 'A']],
|
|
68
|
+
optionDetails: { a: { description: 'x'.repeat(73) } },
|
|
69
|
+
next: { byAnswer: { a: 'slot' }, default: 'menu' },
|
|
70
|
+
},
|
|
71
|
+
slot: { id: 'slot', type: 'dynamic_choice' },
|
|
72
|
+
},
|
|
73
|
+
}
|
|
74
|
+
const messages = validateGraph(graph, DEFAULT_FLOW_EDITOR_LABELS.validation).map((issue) => issue.message)
|
|
75
|
+
expect(messages).toContain('Nó "menu": a descrição de "A" passa de 72 caracteres.')
|
|
76
|
+
expect(messages).toContain('Nó "slot": escolha dinâmica sem provedor de opções.')
|
|
77
|
+
})
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
describe('validateGraph — unmatched choice', () => {
|
|
81
|
+
const base = (unmatchedChoice?: 'reask' | 'default'): FlowGraphData => ({
|
|
82
|
+
key: 'main',
|
|
83
|
+
label: 'main',
|
|
84
|
+
startNodeId: 'menu',
|
|
85
|
+
version: 1,
|
|
86
|
+
nodes: {
|
|
87
|
+
menu: {
|
|
88
|
+
id: 'menu',
|
|
89
|
+
type: 'menu',
|
|
90
|
+
options: [['a', 'A']],
|
|
91
|
+
...(unmatchedChoice ? { unmatchedChoice } : {}),
|
|
92
|
+
next: { byAnswer: { a: 'other' }, default: 'other' },
|
|
93
|
+
},
|
|
94
|
+
other: { id: 'other', type: 'action' },
|
|
95
|
+
},
|
|
96
|
+
})
|
|
97
|
+
|
|
98
|
+
it('warns when a choice default would be ignored by the runner', () => {
|
|
99
|
+
const issues = validateGraph(base(), DEFAULT_FLOW_EDITOR_LABELS.validation)
|
|
100
|
+
expect(issues.some((issue) => issue.severity === 'warning' && issue.message.includes('Caso contrário'))).toBe(true)
|
|
101
|
+
})
|
|
102
|
+
|
|
103
|
+
it('does not warn when the node follows default', () => {
|
|
104
|
+
const issues = validateGraph(base('default'), DEFAULT_FLOW_EDITOR_LABELS.validation)
|
|
105
|
+
expect(issues.some((issue) => issue.message.includes('Caso contrário'))).toBe(false)
|
|
106
|
+
})
|
|
107
|
+
})
|
|
108
|
+
|
|
109
|
+
describe('labels — hosts that build the legend by hand', () => {
|
|
110
|
+
it('accepts a legend without dynamic_choice and merges the default', () => {
|
|
111
|
+
const legend = { question: 'Q', entrada_choice: 'E', action: 'A', menu: 'M', condition: 'C' }
|
|
112
|
+
const merged = mergeFlowEditorLabels({ legend })
|
|
113
|
+
expect(merged.legend.dynamic_choice).toBe(DEFAULT_FLOW_EDITOR_LABELS.legend.dynamic_choice)
|
|
114
|
+
expect(merged.legend.menu).toBe('M')
|
|
115
|
+
})
|
|
116
|
+
})
|