@adatechnology/conversations-ui 0.16.0 → 0.18.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/{chunk-Y326LLEP.js → chunk-7OLYCCLX.js} +1 -1
- package/dist/{chunk-WCZNIJ3M.js → chunk-Z7U22M3K.js} +7 -0
- package/dist/flows/index.d.ts +52 -6
- package/dist/flows/index.js +470 -245
- package/dist/index.d.ts +77 -3
- package/dist/index.js +148 -23
- package/dist/participant/index.js +1 -1
- package/dist/preview/index.js +2 -2
- package/package.json +2 -2
- package/src/flows/FlowNodeCard.tsx +17 -7
- package/src/flows/FlowNodePanel.tsx +10 -0
- package/src/flows/FlowPossibleNextField.tsx +89 -0
- package/src/flows/FlowRunnerFields.tsx +70 -16
- package/src/flows/FlowsWorkspace.tsx +8 -2
- package/src/flows/flowCanvasModel.ts +16 -1
- package/src/flows/flowEditorOps.ts +19 -2
- package/src/flows/flowGraph.ts +108 -11
- package/src/flows/flowLabelValidation.test.ts +92 -0
- package/src/flows/flowPossibleNext.test.ts +70 -0
- package/src/flows/index.ts +3 -0
- package/src/flows/labels.ts +39 -1
- package/src/index.ts +11 -1
- package/src/lib/phone.test.ts +20 -0
- package/src/lib/phone.ts +13 -0
- package/src/quickReplies/createMetaWhatsAppQuickRepliesClient.test.ts +113 -0
- package/src/quickReplies/createMetaWhatsAppQuickRepliesClient.ts +111 -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
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
3
|
+
*
|
|
4
|
+
* Destinos que uma action pode devolver em `next` (`possibleNext`). Não muda o que o bot faz — o
|
|
5
|
+
* handler decide na hora —; serve para o mapa desenhar esses caminhos e a validação não acusar o
|
|
6
|
+
* destino de inalcançável.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type { ReactNode } from 'react'
|
|
10
|
+
import { Plus, Trash2 } from 'lucide-react'
|
|
11
|
+
import type { FlowNodeData } from './flowGraph'
|
|
12
|
+
import { OPTIONAL_RUNNER_FIELD_LABEL_DEFAULTS, type FlowRunnerFieldLabels } from './labels'
|
|
13
|
+
import { PANEL_FIELD_CLASSNAME, PANEL_HINT_CLASSNAME, PANEL_LABEL_CLASSNAME } from './flowPanelStyles'
|
|
14
|
+
|
|
15
|
+
export type FlowPossibleNextFieldProps = {
|
|
16
|
+
draft: FlowNodeData
|
|
17
|
+
onDraftChange: (update: (previous: FlowNodeData) => FlowNodeData) => void
|
|
18
|
+
renderTargetOptions: () => ReactNode
|
|
19
|
+
labels: FlowRunnerFieldLabels
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function withPossibleNext(node: FlowNodeData, targets: string[]): FlowNodeData {
|
|
23
|
+
return { ...node, possibleNext: targets.length > 0 ? targets : undefined }
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function FlowPossibleNextField({
|
|
27
|
+
draft,
|
|
28
|
+
onDraftChange,
|
|
29
|
+
renderTargetOptions,
|
|
30
|
+
labels,
|
|
31
|
+
}: FlowPossibleNextFieldProps) {
|
|
32
|
+
const defaults = OPTIONAL_RUNNER_FIELD_LABEL_DEFAULTS
|
|
33
|
+
const targets = draft.possibleNext ?? []
|
|
34
|
+
const addLabel = labels.addPossibleNext ?? defaults.addPossibleNext
|
|
35
|
+
const removeLabel = labels.removePossibleNext ?? defaults.removePossibleNext
|
|
36
|
+
const fieldLabel = labels.possibleNext ?? defaults.possibleNext
|
|
37
|
+
|
|
38
|
+
function updateTarget(index: number, value: string) {
|
|
39
|
+
const next = targets.map((target, targetIndex) => (targetIndex === index ? value : target))
|
|
40
|
+
onDraftChange((previous) => withPossibleNext(previous, next))
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
return (
|
|
44
|
+
<div className="pt-2 border-t border-gray-100 dark:border-gray-700">
|
|
45
|
+
<div className="flex items-center justify-between">
|
|
46
|
+
<label className={PANEL_LABEL_CLASSNAME}>{fieldLabel}</label>
|
|
47
|
+
<button
|
|
48
|
+
type="button"
|
|
49
|
+
aria-label={addLabel}
|
|
50
|
+
onClick={() => onDraftChange((previous) => withPossibleNext(previous, [...targets, '']))}
|
|
51
|
+
className="text-xs text-blue-600 hover:underline flex items-center gap-1"
|
|
52
|
+
>
|
|
53
|
+
<Plus size={12} aria-hidden="true" /> {addLabel}
|
|
54
|
+
</button>
|
|
55
|
+
</div>
|
|
56
|
+
<p className={PANEL_HINT_CLASSNAME}>{labels.possibleNextHint ?? defaults.possibleNextHint}</p>
|
|
57
|
+
<div className="space-y-2 mt-1">
|
|
58
|
+
{targets.map((target, index) => (
|
|
59
|
+
<div key={index} className="flex items-center gap-2">
|
|
60
|
+
<select
|
|
61
|
+
value={target}
|
|
62
|
+
aria-label={fieldLabel}
|
|
63
|
+
onChange={(event) => updateTarget(index, event.target.value)}
|
|
64
|
+
className={`flex-1 ${PANEL_FIELD_CLASSNAME}`}
|
|
65
|
+
>
|
|
66
|
+
<option value="">—</option>
|
|
67
|
+
{renderTargetOptions()}
|
|
68
|
+
</select>
|
|
69
|
+
<button
|
|
70
|
+
type="button"
|
|
71
|
+
aria-label={removeLabel}
|
|
72
|
+
onClick={() =>
|
|
73
|
+
onDraftChange((previous) =>
|
|
74
|
+
withPossibleNext(
|
|
75
|
+
previous,
|
|
76
|
+
targets.filter((_, targetIndex) => targetIndex !== index),
|
|
77
|
+
),
|
|
78
|
+
)
|
|
79
|
+
}
|
|
80
|
+
className="text-gray-400 hover:text-red-600"
|
|
81
|
+
>
|
|
82
|
+
<Trash2 size={14} aria-hidden="true" />
|
|
83
|
+
</button>
|
|
84
|
+
</div>
|
|
85
|
+
))}
|
|
86
|
+
</div>
|
|
87
|
+
</div>
|
|
88
|
+
)
|
|
89
|
+
}
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
|
|
9
9
|
import type { ReactNode } from 'react'
|
|
10
10
|
import type { FlowAnswerValidation, FlowNodeData } from './flowGraph'
|
|
11
|
-
import type
|
|
11
|
+
import { OPTIONAL_RUNNER_FIELD_LABEL_DEFAULTS, type FlowRunnerFieldLabels } from './labels'
|
|
12
12
|
import { FlowKeywordRoutesField } from './FlowKeywordRoutesField'
|
|
13
13
|
import { PANEL_FIELD_CLASSNAME, PANEL_HINT_CLASSNAME, PANEL_LABEL_CLASSNAME } from './flowPanelStyles'
|
|
14
14
|
|
|
@@ -50,7 +50,67 @@ function NumberField(props: {
|
|
|
50
50
|
)
|
|
51
51
|
}
|
|
52
52
|
|
|
53
|
-
function
|
|
53
|
+
function ContextKeyField(props: {
|
|
54
|
+
label: string
|
|
55
|
+
hint?: string
|
|
56
|
+
value: string | undefined
|
|
57
|
+
knownContextKeys: readonly string[]
|
|
58
|
+
onValueChange: (value: string | undefined) => void
|
|
59
|
+
}) {
|
|
60
|
+
return (
|
|
61
|
+
<div>
|
|
62
|
+
<label className={PANEL_LABEL_CLASSNAME}>{props.label}</label>
|
|
63
|
+
<input
|
|
64
|
+
value={props.value ?? ''}
|
|
65
|
+
list="runner-context-keys"
|
|
66
|
+
onChange={(event) => props.onValueChange(event.target.value || undefined)}
|
|
67
|
+
className={`w-full mt-1 ${PANEL_FIELD_CLASSNAME}`}
|
|
68
|
+
/>
|
|
69
|
+
<datalist id="runner-context-keys">
|
|
70
|
+
{props.knownContextKeys.map((key) => (
|
|
71
|
+
<option key={key} value={key} />
|
|
72
|
+
))}
|
|
73
|
+
</datalist>
|
|
74
|
+
{props.hint && <p className={PANEL_HINT_CLASSNAME}>{props.hint}</p>}
|
|
75
|
+
</div>
|
|
76
|
+
)
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function TimeValidationFields({ draft, onDraftChange, knownContextKeys, labels }: FlowRunnerFieldsProps) {
|
|
80
|
+
const validation = draft.validation ?? {}
|
|
81
|
+
const update = (patch: Partial<FlowAnswerValidation>) => onDraftChange((previous) => withValidation(previous, patch))
|
|
82
|
+
const defaults = OPTIONAL_RUNNER_FIELD_LABEL_DEFAULTS
|
|
83
|
+
const timeInput = (label: string, value: string | undefined, onValueChange: (value: string | undefined) => void) => (
|
|
84
|
+
<div className="flex-1">
|
|
85
|
+
<label className={PANEL_LABEL_CLASSNAME}>{label}</label>
|
|
86
|
+
<input
|
|
87
|
+
type="time"
|
|
88
|
+
value={value ?? ''}
|
|
89
|
+
onChange={(event) => onValueChange(event.target.value || undefined)}
|
|
90
|
+
className={`w-full mt-1 ${PANEL_FIELD_CLASSNAME}`}
|
|
91
|
+
/>
|
|
92
|
+
</div>
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
return (
|
|
96
|
+
<div className="space-y-2">
|
|
97
|
+
<div className="flex gap-2">
|
|
98
|
+
{timeInput(labels.minTime ?? defaults.minTime, validation.minTime, (minTime) => update({ minTime }))}
|
|
99
|
+
{timeInput(labels.maxTime ?? defaults.maxTime, validation.maxTime, (maxTime) => update({ maxTime }))}
|
|
100
|
+
</div>
|
|
101
|
+
<ContextKeyField
|
|
102
|
+
label={labels.timeWindowsContextKey ?? defaults.timeWindowsContextKey}
|
|
103
|
+
hint={labels.timeWindowsContextKeyHint ?? defaults.timeWindowsContextKeyHint}
|
|
104
|
+
value={validation.windowsContextKey}
|
|
105
|
+
knownContextKeys={knownContextKeys}
|
|
106
|
+
onValueChange={(windowsContextKey) => update({ windowsContextKey })}
|
|
107
|
+
/>
|
|
108
|
+
</div>
|
|
109
|
+
)
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function ValidationFields(props: FlowRunnerFieldsProps) {
|
|
113
|
+
const { draft, onDraftChange, knownContextKeys, labels } = props
|
|
54
114
|
const validation = draft.validation ?? {}
|
|
55
115
|
const update = (patch: Partial<FlowAnswerValidation>) => onDraftChange((previous) => withValidation(previous, patch))
|
|
56
116
|
|
|
@@ -65,24 +125,18 @@ function ValidationFields({ draft, onDraftChange, knownContextKeys, labels }: Fl
|
|
|
65
125
|
/>
|
|
66
126
|
{labels.minDateToday}
|
|
67
127
|
</label>
|
|
68
|
-
<
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
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>
|
|
128
|
+
<ContextKeyField
|
|
129
|
+
label={labels.afterContextKey}
|
|
130
|
+
value={validation.afterContextKey}
|
|
131
|
+
knownContextKeys={knownContextKeys}
|
|
132
|
+
onValueChange={(afterContextKey) => update({ afterContextKey })}
|
|
133
|
+
/>
|
|
82
134
|
</div>
|
|
83
135
|
)
|
|
84
136
|
}
|
|
85
137
|
|
|
138
|
+
if (draft.questionType === 'time') return <TimeValidationFields {...props} />
|
|
139
|
+
|
|
86
140
|
if (draft.questionType === 'int' || draft.questionType === 'money') {
|
|
87
141
|
return (
|
|
88
142
|
<div className="flex gap-2">
|
|
@@ -171,6 +171,11 @@ export interface FlowsWorkspaceProps {
|
|
|
171
171
|
* pacote a adivinhar a escala tipográfica de cada produto.
|
|
172
172
|
*/
|
|
173
173
|
readonly showHeader?: boolean
|
|
174
|
+
/**
|
|
175
|
+
* Valor de exemplo por variável usada em rótulo de botão e linha de lista (`{ buttonName: 'Pernoite' }`).
|
|
176
|
+
* Com exemplo, o validador mede o texto interpolado; sem, só avisa quando a marcação escrita passa do limite.
|
|
177
|
+
*/
|
|
178
|
+
readonly variableExamples?: Readonly<Record<string, string>>
|
|
174
179
|
readonly className?: string
|
|
175
180
|
}
|
|
176
181
|
|
|
@@ -245,6 +250,7 @@ export function FlowsWorkspace({
|
|
|
245
250
|
renderMediaPicker,
|
|
246
251
|
livePollIntervalMs = 5000,
|
|
247
252
|
showHeader = true,
|
|
253
|
+
variableExamples,
|
|
248
254
|
className,
|
|
249
255
|
}: FlowsWorkspaceProps) {
|
|
250
256
|
const labels = useMemo(() => mergeFlowEditorLabels(labelsOverride), [labelsOverride])
|
|
@@ -358,10 +364,10 @@ export function FlowsWorkspace({
|
|
|
358
364
|
const map: Record<string, GraphIssue[]> = {}
|
|
359
365
|
for (const key of openFlowKeys) {
|
|
360
366
|
const graph = workingGraphs[key]
|
|
361
|
-
if (graph) map[key] = validateGraph(graph, labels.validation)
|
|
367
|
+
if (graph) map[key] = validateGraph(graph, labels.validation, { variableExamples })
|
|
362
368
|
}
|
|
363
369
|
return map
|
|
364
|
-
}, [openFlowKeys, workingGraphs, labels])
|
|
370
|
+
}, [openFlowKeys, workingGraphs, labels, variableExamples])
|
|
365
371
|
|
|
366
372
|
const errorCount = Object.values(issuesByFlow).reduce(
|
|
367
373
|
(sum, list) => sum + list.filter((issue) => issue.severity === 'error').length,
|
|
@@ -20,6 +20,7 @@ import {
|
|
|
20
20
|
slugifyNodeId,
|
|
21
21
|
targetsOf,
|
|
22
22
|
keywordHandle,
|
|
23
|
+
possibleNextHandle,
|
|
23
24
|
type FlowGraphData,
|
|
24
25
|
type FlowNodeData,
|
|
25
26
|
} from './flowGraph'
|
|
@@ -207,7 +208,7 @@ export function buildFlowEdges(params: {
|
|
|
207
208
|
for (const [nodeId, node] of Object.entries(graph.nodes)) {
|
|
208
209
|
const live = (liveCounts[nodeId] ?? 0) > 0
|
|
209
210
|
|
|
210
|
-
for (const { target, optionId: answerId, keyword, isDefault } of targetsOf(node)) {
|
|
211
|
+
for (const { target, optionId: answerId, keyword, isDefault, isPossible } of targetsOf(node)) {
|
|
211
212
|
const optionId = keyword !== undefined ? keywordHandle(keyword) : answerId
|
|
212
213
|
// Destino vazio é estado NORMAL, não anomalia: apagar um nó zera quem apontava para ele, e
|
|
213
214
|
// `targetsOf` devolve o `default` mesmo em branco. Emitir a aresta criaria ligação para um nó
|
|
@@ -238,6 +239,20 @@ export function buildFlowEdges(params: {
|
|
|
238
239
|
// repetição na linha de saída, dentro do card (ver `FlowNodeCard`).
|
|
239
240
|
if (source === edgeTarget) continue
|
|
240
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
|
+
|
|
241
256
|
if (isDefault) {
|
|
242
257
|
edges.push({
|
|
243
258
|
id: `${source}->${edgeTarget}-default`,
|
|
@@ -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, keywordOfHandle } 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,6 +154,9 @@ 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
161
|
return { ...node, next: { ...currentNext, byAnswer: currentNext?.byAnswer ?? {}, default: resolved.targetValue } }
|
|
156
162
|
}
|
|
@@ -197,7 +203,18 @@ export function isGraphDirty(working: FlowGraphData | undefined, published: Flow
|
|
|
197
203
|
* opção sem `byAnswer` some do card — e some junto o botão que o cliente via no WhatsApp, o que se
|
|
198
204
|
* lê como "o editor apagou minha opção". Vazio mantém a linha visível, cobrando a religação.
|
|
199
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
|
+
|
|
200
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
|
+
|
|
201
218
|
if (handle === 'next' || typeof node.next === 'string' || node.next === undefined) {
|
|
202
219
|
return { ...node, next: '' }
|
|
203
220
|
}
|
package/src/flows/flowGraph.ts
CHANGED
|
@@ -68,6 +68,16 @@ export function keywordOfHandle(handle: string): string | undefined {
|
|
|
68
68
|
return handle.startsWith(KEYWORD_HANDLE_PREFIX) ? handle.slice(KEYWORD_HANDLE_PREFIX.length) : undefined
|
|
69
69
|
}
|
|
70
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
|
+
|
|
71
81
|
export const CROSS_FLOW_PREFIX = 'flow:'
|
|
72
82
|
export const isCrossFlowTarget = (target: string): boolean => target.startsWith(CROSS_FLOW_PREFIX)
|
|
73
83
|
export const crossFlowKey = (target: string): string => target.slice(CROSS_FLOW_PREFIX.length)
|
|
@@ -84,10 +94,9 @@ export function estimateNodeHeight(node: FlowNodeData): number {
|
|
|
84
94
|
const ROW_HEIGHT = 34
|
|
85
95
|
const rowCount =
|
|
86
96
|
node.type === 'action'
|
|
87
|
-
? // Ação de passagem desenha uma linha de saída; terminal não desenha nenhuma.
|
|
88
|
-
|
|
89
|
-
? 1
|
|
90
|
-
: 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)
|
|
91
100
|
: node.type === 'condition'
|
|
92
101
|
? 2
|
|
93
102
|
: node.type === 'menu' || node.questionType === 'choice'
|
|
@@ -109,6 +118,7 @@ export const WHATSAPP_LIMITS = {
|
|
|
109
118
|
MAX_BUTTONS: WHATSAPP_CHOICE_LIMIT.BUTTONS,
|
|
110
119
|
MAX_LIST_ROWS: WHATSAPP_CHOICE_LIMIT.LIST_ROWS,
|
|
111
120
|
BUTTON_TITLE_MAX: WHATSAPP_CHOICE_LIMIT.BUTTON_TITLE_LENGTH,
|
|
121
|
+
LIST_BUTTON_LABEL_MAX: WHATSAPP_CHOICE_LIMIT.LIST_BUTTON_LABEL_LENGTH,
|
|
112
122
|
LIST_ROW_TITLE_MAX: WHATSAPP_CHOICE_LIMIT.LIST_ROW_TITLE_LENGTH,
|
|
113
123
|
LIST_ROW_DESCRIPTION_MAX: WHATSAPP_CHOICE_LIMIT.LIST_ROW_DESCRIPTION_LENGTH,
|
|
114
124
|
LIST_SECTION_TITLE_MAX: WHATSAPP_CHOICE_LIMIT.LIST_SECTION_TITLE_LENGTH,
|
|
@@ -120,6 +130,44 @@ export function countCharacters(text: string): number {
|
|
|
120
130
|
return Array.from(text).length
|
|
121
131
|
}
|
|
122
132
|
|
|
133
|
+
const PLACEHOLDER_PATTERN = /\{\{\s*([\w.]+)\s*\}\}/g
|
|
134
|
+
|
|
135
|
+
export type MeasuredLabel = {
|
|
136
|
+
/** Caracteres do texto como o cliente o leria; sem exemplo para uma variável, ela vale 0 (mínimo certo). */
|
|
137
|
+
readonly length: number
|
|
138
|
+
/** `true` quando alguma `{{variável}}` ficou sem exemplo: o tamanho real só se sabe em tempo de execução. */
|
|
139
|
+
readonly isApproximate: boolean
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Mede um rótulo com `{{variável}}` sobre o texto interpolado com o exemplo da variável. Sem exemplo,
|
|
144
|
+
* mede o texto sem ela — contar a marcação escrita daria erro falso (`{{nome}}` vale 8 e a variável
|
|
145
|
+
* real pode ter 4).
|
|
146
|
+
*/
|
|
147
|
+
export function measureLabel(label: string, variableExamples: Readonly<Record<string, string>> = {}): MeasuredLabel {
|
|
148
|
+
let isApproximate = false
|
|
149
|
+
const text = label.replace(PLACEHOLDER_PATTERN, (_placeholder, key: string) => {
|
|
150
|
+
const example = variableExamples[key]
|
|
151
|
+
if (example === undefined) isApproximate = true
|
|
152
|
+
return example ?? ''
|
|
153
|
+
})
|
|
154
|
+
return { length: countCharacters(text), isApproximate }
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
type LabelVerdict = 'ok' | 'too-long' | 'may-be-too-long'
|
|
158
|
+
|
|
159
|
+
/** Erro só quando o mínimo certo já passa do teto; aviso quando só a marcação escrita passa e a variável não tem exemplo. */
|
|
160
|
+
function judgeLabel(label: string, max: number, variableExamples: Readonly<Record<string, string>>): LabelVerdict {
|
|
161
|
+
const measured = measureLabel(label, variableExamples)
|
|
162
|
+
if (measured.length > max) return 'too-long'
|
|
163
|
+
return measured.isApproximate && countCharacters(label) > max ? 'may-be-too-long' : 'ok'
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export type ValidateGraphOptions = {
|
|
167
|
+
/** Valor de exemplo por variável (`{ buttonName: 'Pernoite' }`), usado para medir rótulos de botão e linha de lista. */
|
|
168
|
+
readonly variableExamples?: Readonly<Record<string, string>>
|
|
169
|
+
}
|
|
170
|
+
|
|
123
171
|
/**
|
|
124
172
|
* Botão com até 3 opções simples; opção com descrição ou seção força lista — é a mesma regra do
|
|
125
173
|
* runner do módulo, para a prévia mostrar o que o cliente vai ver.
|
|
@@ -134,9 +182,16 @@ export function rendersAsButtons(
|
|
|
134
182
|
return !hasDetails && (options?.length ?? 0) <= WHATSAPP_LIMITS.MAX_BUTTONS
|
|
135
183
|
}
|
|
136
184
|
|
|
137
|
-
export
|
|
138
|
-
|
|
139
|
-
|
|
185
|
+
export type FlowNodeTarget = {
|
|
186
|
+
target: string
|
|
187
|
+
optionId?: string
|
|
188
|
+
keyword?: string
|
|
189
|
+
isDefault?: boolean
|
|
190
|
+
/** Destino de `possibleNext`: a action pode escolher, não é garantido. */
|
|
191
|
+
isPossible?: boolean
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function nextTargetsOf(node: FlowNodeData): FlowNodeTarget[] {
|
|
140
195
|
if (!node.next) return []
|
|
141
196
|
if (typeof node.next === 'string') return [{ target: node.next }]
|
|
142
197
|
return [
|
|
@@ -146,6 +201,11 @@ export function targetsOf(
|
|
|
146
201
|
]
|
|
147
202
|
}
|
|
148
203
|
|
|
204
|
+
export function targetsOf(node: FlowNodeData): FlowNodeTarget[] {
|
|
205
|
+
const possible = (node.possibleNext ?? []).map((target) => ({ target, isPossible: true }))
|
|
206
|
+
return [...nextTargetsOf(node), ...possible]
|
|
207
|
+
}
|
|
208
|
+
|
|
149
209
|
export type GraphIssue = {
|
|
150
210
|
severity: 'error' | 'warning'
|
|
151
211
|
nodeId?: string
|
|
@@ -174,8 +234,15 @@ export function validateGraph(
|
|
|
174
234
|
descriptionTooLong?: (id: string, label: string) => string
|
|
175
235
|
dynamicChoiceWithoutProvider?: (id: string) => string
|
|
176
236
|
choiceDefaultIgnored?: (id: string) => string
|
|
237
|
+
possibleNextIgnored?: (id: string) => string
|
|
238
|
+
buttonTitleMayBeTooLong?: (id: string, label: string) => string
|
|
239
|
+
listTitleMayBeTooLong?: (id: string, label: string) => string
|
|
240
|
+
listButtonLabelTooLong?: (id: string, label: string) => string
|
|
241
|
+
listButtonLabelMayBeTooLong?: (id: string, label: string) => string
|
|
177
242
|
},
|
|
243
|
+
settings: ValidateGraphOptions = {},
|
|
178
244
|
): GraphIssue[] {
|
|
245
|
+
const examples = settings.variableExamples ?? {}
|
|
179
246
|
const issues: GraphIssue[] = []
|
|
180
247
|
const nodeIds = new Set(Object.keys(graph.nodes))
|
|
181
248
|
const isValidTarget = (target: string) => nodeIds.has(target) || isCrossFlowTarget(target)
|
|
@@ -208,11 +275,17 @@ export function validateGraph(
|
|
|
208
275
|
issues.push({ severity: 'warning', nodeId: node.id, message: issueText.optionWithoutTarget(node.id, label) })
|
|
209
276
|
}
|
|
210
277
|
const usesButtons = rendersAsButtons(options, node.optionDetails)
|
|
211
|
-
|
|
212
|
-
|
|
278
|
+
const titleMax = usesButtons ? WHATSAPP_LIMITS.BUTTON_TITLE_MAX : WHATSAPP_LIMITS.LIST_ROW_TITLE_MAX
|
|
279
|
+
const titleVerdict = judgeLabel(label, titleMax, examples)
|
|
280
|
+
if (titleVerdict === 'too-long') {
|
|
281
|
+
const tooLong = usesButtons ? issueText.buttonTitleTooLong : issueText.listTitleTooLong
|
|
282
|
+
issues.push({ severity: 'error', nodeId: node.id, message: tooLong(node.id, label) })
|
|
213
283
|
}
|
|
214
|
-
if (
|
|
215
|
-
|
|
284
|
+
if (titleVerdict === 'may-be-too-long') {
|
|
285
|
+
const message =
|
|
286
|
+
(usesButtons ? issueText.buttonTitleMayBeTooLong : issueText.listTitleMayBeTooLong)?.(node.id, label) ??
|
|
287
|
+
`Nó "${node.id}": "${label}" tem variável e pode passar de ${titleMax} caracteres; confira o valor real.`
|
|
288
|
+
issues.push({ severity: 'warning', nodeId: node.id, message })
|
|
216
289
|
}
|
|
217
290
|
const description = node.optionDetails?.[optionId]?.description ?? ''
|
|
218
291
|
if (countCharacters(description) > WHATSAPP_LIMITS.LIST_ROW_DESCRIPTION_MAX) {
|
|
@@ -222,6 +295,22 @@ export function validateGraph(
|
|
|
222
295
|
issues.push({ severity: 'error', nodeId: node.id, message })
|
|
223
296
|
}
|
|
224
297
|
}
|
|
298
|
+
const listButtonLabel = node.listButtonLabel
|
|
299
|
+
const listButtonVerdict = listButtonLabel
|
|
300
|
+
? judgeLabel(listButtonLabel, WHATSAPP_LIMITS.LIST_BUTTON_LABEL_MAX, examples)
|
|
301
|
+
: 'ok'
|
|
302
|
+
if (listButtonLabel && listButtonVerdict === 'too-long') {
|
|
303
|
+
const message =
|
|
304
|
+
issueText.listButtonLabelTooLong?.(node.id, listButtonLabel) ??
|
|
305
|
+
`Nó "${node.id}": o botão da lista "${listButtonLabel}" passa de ${WHATSAPP_LIMITS.LIST_BUTTON_LABEL_MAX} caracteres.`
|
|
306
|
+
issues.push({ severity: 'error', nodeId: node.id, message })
|
|
307
|
+
}
|
|
308
|
+
if (listButtonLabel && listButtonVerdict === 'may-be-too-long') {
|
|
309
|
+
const message =
|
|
310
|
+
issueText.listButtonLabelMayBeTooLong?.(node.id, listButtonLabel) ??
|
|
311
|
+
`Nó "${node.id}": o botão da lista "${listButtonLabel}" tem variável e pode passar de ${WHATSAPP_LIMITS.LIST_BUTTON_LABEL_MAX} caracteres; confira o valor real.`
|
|
312
|
+
issues.push({ severity: 'warning', nodeId: node.id, message })
|
|
313
|
+
}
|
|
225
314
|
// Com o runner em `reask` (padrão), resposta fora das opções repergunta: um "caso contrário"
|
|
226
315
|
// apontando para outro nó nunca seria seguido. Aviso, não erro — o host pode ligar `default`.
|
|
227
316
|
const defaultTarget = typeof node.next === 'object' && node.next ? node.next.default : ''
|
|
@@ -236,6 +325,14 @@ export function validateGraph(
|
|
|
236
325
|
}
|
|
237
326
|
}
|
|
238
327
|
|
|
328
|
+
// Só a action devolve `next` em tempo de execução: em outro nó a lista desenharia caminho que não existe.
|
|
329
|
+
if ((node.possibleNext?.length ?? 0) > 0 && (node.type !== 'action' || !node.actionKind)) {
|
|
330
|
+
const message =
|
|
331
|
+
issueText.possibleNextIgnored?.(node.id) ??
|
|
332
|
+
`${node.id}: "destinos que a ação pode escolher" só valem em nó de ação com tipo de ação.`
|
|
333
|
+
issues.push({ severity: 'warning', nodeId: node.id, message })
|
|
334
|
+
}
|
|
335
|
+
|
|
239
336
|
if (node.type === 'dynamic_choice' && !node.choiceProvider) {
|
|
240
337
|
const message =
|
|
241
338
|
issueText.dynamicChoiceWithoutProvider?.(node.id) ?? `${node.id}: escolha dinâmica sem provedor de opções.`
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) 2026 Ada Technology. MIT License.
|
|
3
|
+
*
|
|
4
|
+
* Rótulo de botão/linha com `{{variável}}`: o validador mede o texto interpolado, não a marcação.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { describe, expect, it } from 'bun:test'
|
|
8
|
+
import { validateGraph, measureLabel, type FlowGraphData } from './flowGraph'
|
|
9
|
+
import { DEFAULT_FLOW_EDITOR_LABELS } from './labels'
|
|
10
|
+
|
|
11
|
+
function menuGraph(label: string, extra: Record<string, unknown> = {}): FlowGraphData {
|
|
12
|
+
return {
|
|
13
|
+
key: 'main',
|
|
14
|
+
label: 'Main',
|
|
15
|
+
version: 1,
|
|
16
|
+
startNodeId: 'menu',
|
|
17
|
+
nodes: {
|
|
18
|
+
menu: {
|
|
19
|
+
id: 'menu',
|
|
20
|
+
type: 'menu',
|
|
21
|
+
question: 'Escolha',
|
|
22
|
+
options: [['a', label]],
|
|
23
|
+
next: { byAnswer: { a: 'menu' }, default: 'menu' },
|
|
24
|
+
...extra,
|
|
25
|
+
},
|
|
26
|
+
},
|
|
27
|
+
} as FlowGraphData
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const validate = (graph: FlowGraphData, variableExamples?: Record<string, string>) =>
|
|
31
|
+
validateGraph(graph, DEFAULT_FLOW_EDITOR_LABELS.validation, variableExamples ? { variableExamples } : {})
|
|
32
|
+
|
|
33
|
+
describe('measureLabel', () => {
|
|
34
|
+
it('measures the interpolated example, not the marker', () => {
|
|
35
|
+
expect(measureLabel('✅ {{buttonName}}', { buttonName: 'Pernoite' })).toEqual({ length: 10, isApproximate: false })
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
it('counts a variable without example as zero and flags the measure as approximate', () => {
|
|
39
|
+
expect(measureLabel('✅ {{buttonName}}')).toEqual({ length: 2, isApproximate: true })
|
|
40
|
+
})
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
describe('validateGraph — labels with variables', () => {
|
|
44
|
+
const LONG_MARKER = '✅ {{nameButtonTitle}}'
|
|
45
|
+
|
|
46
|
+
it('does not error on a long marker without example; it warns', () => {
|
|
47
|
+
const issues = validate(menuGraph(LONG_MARKER))
|
|
48
|
+
expect(issues.filter((issue) => issue.severity === 'error')).toEqual([])
|
|
49
|
+
expect(issues.some((issue) => issue.severity === 'warning' && issue.message.includes('pode passar de 20'))).toBe(
|
|
50
|
+
true,
|
|
51
|
+
)
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
it('passes silently when the example fits', () => {
|
|
55
|
+
expect(validate(menuGraph(LONG_MARKER), { nameButtonTitle: 'Pernoite' })).toEqual([])
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
it('errors when the example does not fit the button limit', () => {
|
|
59
|
+
const issues = validate(menuGraph(LONG_MARKER), { nameButtonTitle: 'Pacote de fim de semana inteiro' })
|
|
60
|
+
expect(issues.map((issue) => issue.severity)).toEqual(['error'])
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
it('errors when the fixed part alone passes the limit', () => {
|
|
64
|
+
const issues = validate(menuGraph('Texto fixo bem comprido demais {{x}}'))
|
|
65
|
+
expect(issues.map((issue) => issue.severity)).toEqual(['error'])
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
it('keeps the strict check for labels without variables', () => {
|
|
69
|
+
const issues = validate(menuGraph('Um rótulo comprido demais para botão'))
|
|
70
|
+
expect(issues.map((issue) => issue.severity)).toEqual(['error'])
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
it('uses the list row limit (24) when the node renders a list', () => {
|
|
74
|
+
const graph = menuGraph('{{unitName}} 12345678901234', { optionDetails: { a: { description: 'x' } } })
|
|
75
|
+
expect(validate(graph, { unitName: 'Centro' }).filter((issue) => issue.severity === 'error')).toEqual([])
|
|
76
|
+
expect(validate(graph, { unitName: 'Unidade Centro' }).map((issue) => issue.severity)).toEqual(['error'])
|
|
77
|
+
})
|
|
78
|
+
|
|
79
|
+
it('validates the list button label the same way', () => {
|
|
80
|
+
expect(validate(menuGraph('A', { listButtonLabel: 'Horários {{unit}}' })).map((issue) => issue.severity)).toEqual(
|
|
81
|
+
[],
|
|
82
|
+
)
|
|
83
|
+
expect(
|
|
84
|
+
validate(menuGraph('A', { listButtonLabel: 'Horários {{unit}}' }), { unit: 'Unidade Centro' }).map(
|
|
85
|
+
(issue) => issue.severity,
|
|
86
|
+
),
|
|
87
|
+
).toEqual(['error'])
|
|
88
|
+
expect(
|
|
89
|
+
validate(menuGraph('A', { listButtonLabel: 'Ver todos os horários disponíveis' })).map((i) => i.severity),
|
|
90
|
+
).toEqual(['error'])
|
|
91
|
+
})
|
|
92
|
+
})
|
|
@@ -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
|
+
})
|