@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.
Files changed (39) hide show
  1. package/README.md +23 -0
  2. package/dist/{ConversationSimulatorPanel-P6eqTSAO.d.ts → ConversationSimulatorPanel-DSVIch04.d.ts} +3 -1
  3. package/dist/{chunk-Y326LLEP.js → chunk-7OLYCCLX.js} +1 -1
  4. package/dist/{chunk-WCZNIJ3M.js → chunk-Z7U22M3K.js} +7 -0
  5. package/dist/flows/index.d.ts +90 -7
  6. package/dist/flows/index.js +1151 -455
  7. package/dist/index.d.ts +36 -5
  8. package/dist/index.js +88 -23
  9. package/dist/participant/index.js +1 -1
  10. package/dist/preview/index.d.ts +13 -29
  11. package/dist/preview/index.js +2 -2
  12. package/package.json +2 -2
  13. package/src/flows/FlowKeywordRoutesField.tsx +105 -0
  14. package/src/flows/FlowLegend.tsx +2 -2
  15. package/src/flows/FlowNodeCard.tsx +39 -10
  16. package/src/flows/FlowNodePanel.tsx +34 -10
  17. package/src/flows/FlowPalette.tsx +25 -2
  18. package/src/flows/FlowPossibleNextField.tsx +89 -0
  19. package/src/flows/FlowRunnerFields.tsx +321 -0
  20. package/src/flows/FlowWhatsAppPreview.tsx +39 -6
  21. package/src/flows/flowCanvasModel.test.ts +3 -2
  22. package/src/flows/flowCanvasModel.ts +28 -1
  23. package/src/flows/flowEditorOps.ts +41 -4
  24. package/src/flows/flowGraph.ts +124 -21
  25. package/src/flows/flowPanelStyles.ts +11 -0
  26. package/src/flows/flowPossibleNext.test.ts +70 -0
  27. package/src/flows/flowRunnerEditor.test.ts +116 -0
  28. package/src/flows/labels.ts +116 -2
  29. package/src/index.ts +2 -1
  30. package/src/lib/phone.test.ts +20 -0
  31. package/src/lib/phone.ts +13 -0
  32. package/src/preview/createPreviewBridgeClient.test.ts +23 -0
  33. package/src/preview/createPreviewBridgeClient.ts +13 -8
  34. package/src/preview/createPreviewWebhookClient.ts +2 -0
  35. package/src/workspace/ConversationPane.tsx +13 -2
  36. package/src/workspace/ConversationsWorkspace.tsx +117 -18
  37. package/src/workspace/index.ts +1 -0
  38. package/src/workspace/labels.ts +2 -0
  39. package/src/workspace/workspaceTestContactDom.test.tsx +96 -0
@@ -14,9 +14,10 @@ import {
14
14
  ShoppingBag,
15
15
  RotateCcw,
16
16
  type LucideIcon,
17
+ ListChecks,
17
18
  } from 'lucide-react'
18
- import type { FlowEditorLabels } from './labels'
19
- import { PASS_THROUGH_ACTION_KINDS, type FlowNodeData, type GraphIssue } from './flowGraph'
19
+ import { DEFAULT_FLOW_EDITOR_LABELS, OPTIONAL_RUNNER_FIELD_LABEL_DEFAULTS, type FlowEditorLabels } from './labels'
20
+ import { isPassThroughAction, keywordHandle, possibleNextHandle, type FlowNodeData, type GraphIssue } from './flowGraph'
20
21
 
21
22
  /**
22
23
  * Diâmetro dos pontos de ligação.
@@ -32,6 +33,7 @@ export const NODE_TYPE_COLOR: Record<FlowNodeData['type'], string> = {
32
33
  action: 'border-orange-300 bg-orange-50 dark:bg-orange-950/40 dark:border-orange-800',
33
34
  menu: 'border-emerald-300 bg-emerald-50 dark:bg-emerald-950/40 dark:border-emerald-800',
34
35
  condition: 'border-cyan-300 bg-cyan-50 dark:bg-cyan-950/40 dark:border-cyan-800',
36
+ dynamic_choice: 'border-teal-300 bg-teal-50 dark:bg-teal-950/40 dark:border-teal-800',
35
37
  }
36
38
 
37
39
  const NODE_TYPE_ICON: Record<FlowNodeData['type'], LucideIcon> = {
@@ -40,6 +42,7 @@ const NODE_TYPE_ICON: Record<FlowNodeData['type'], LucideIcon> = {
40
42
  action: Zap,
41
43
  menu: GitBranch,
42
44
  condition: Diamond,
45
+ dynamic_choice: ListChecks,
43
46
  }
44
47
 
45
48
  // Ícone por função da ação — o host estende via `actionKindIcons` (FlowNodeCardData) para
@@ -116,17 +119,30 @@ function selfLoopHandles(node: FlowNodeData): Set<string> {
116
119
  for (const [optionId, target] of Object.entries(node.next.byAnswer ?? {})) {
117
120
  if (target === node.id) loops.add(optionId)
118
121
  }
122
+ for (const [keyword, target] of Object.entries(node.next.byKeyword ?? {})) {
123
+ if (target === node.id) loops.add(keywordHandle(keyword))
124
+ }
119
125
  if (node.next.default === node.id) loops.add('__default')
120
126
 
121
127
  return loops
122
128
  }
123
129
 
124
130
  function sourceRows(node: FlowNodeData, labels: FlowEditorLabels): SourceRowSpec[] {
125
- // Ação de passagem tem saída; ação terminal, não — ver `PASS_THROUGH_ACTION_KINDS`.
131
+ // Ação de passagem tem saída; ação terminal, não — ver `isPassThroughAction`.
126
132
  if (node.type === 'action') {
127
- return node.actionKind && PASS_THROUGH_ACTION_KINDS.includes(node.actionKind)
133
+ const rowLabel =
134
+ labels.runnerFields?.possibleNextRowLabel ?? OPTIONAL_RUNNER_FIELD_LABEL_DEFAULTS.possibleNextRowLabel
135
+ // Destinos que a action pode devolver: linha própria, com o visual esmaecido do "caso contrário".
136
+ const possibleRows = (node.possibleNext ?? []).map((target) => ({
137
+ id: possibleNextHandle(target),
138
+ label: `${rowLabel}: ${target}`,
139
+ isDefault: true,
140
+ isSelfLoop: target === node.id,
141
+ }))
142
+ const nextRows = isPassThroughAction(node)
128
143
  ? [{ id: 'next', label: labels.nodePanel.nextRowLabel, isDefault: false, isSelfLoop: false }]
129
144
  : []
145
+ return [...nextRows, ...possibleRows]
130
146
  }
131
147
 
132
148
  const loops = selfLoopHandles(node)
@@ -136,12 +152,25 @@ function sourceRows(node: FlowNodeData, labels: FlowEditorLabels): SourceRowSpec
136
152
  { id: 'false', label: labels.nodePanel.conditionFalse, isDefault: false, isSelfLoop: loops.has('false') },
137
153
  ]
138
154
  }
155
+ // Palavra-chave é uma saída a mais: "horário" leva à resposta sem o cliente tocar em opção.
156
+ const keywordRows = Object.keys(typeof node.next === 'object' ? (node.next.byKeyword ?? {}) : {}).map((keyword) => ({
157
+ id: keywordHandle(keyword),
158
+ label: `“${keyword}”`,
159
+ isDefault: false,
160
+ isSelfLoop: loops.has(keywordHandle(keyword)),
161
+ }))
139
162
  const isChoice = node.type === 'menu' || node.questionType === 'choice'
140
- if (!isChoice)
163
+ if (!isChoice && typeof node.next !== 'object')
141
164
  return [{ id: 'next', label: labels.nodePanel.nextRowLabel, isDefault: false, isSelfLoop: loops.has('next') }]
165
+ if (!isChoice)
166
+ return [
167
+ ...keywordRows,
168
+ { id: '__default', label: labels.nodePanel.nextRowLabel, isDefault: true, isSelfLoop: loops.has('__default') },
169
+ ]
142
170
  const options = node.options ?? []
143
171
  return [
144
172
  ...options.map(([id, label]) => ({ id, label, isDefault: false, isSelfLoop: loops.has(id) })),
173
+ ...keywordRows,
145
174
  { id: '__default', label: labels.edgeFallbackLabel, isDefault: true, isSelfLoop: loops.has('__default') },
146
175
  ]
147
176
  }
@@ -277,8 +306,10 @@ export function FlowNodeCard({ data }: NodeProps) {
277
306
  <div className="flex items-center justify-between gap-2">
278
307
  <span className="flex items-center gap-1.5 uppercase tracking-wide font-semibold text-gray-500 dark:text-gray-400 text-xs">
279
308
  <Icon size={12} strokeWidth={2.5} />
280
- {isStart && <span className="h-1.5 w-1.5 rounded-full bg-emerald-500" data-cv-tooltip={labels.startNodeTooltip} />}
281
- {labels.legend[node.type]}
309
+ {isStart && (
310
+ <span className="h-1.5 w-1.5 rounded-full bg-emerald-500" data-cv-tooltip={labels.startNodeTooltip} />
311
+ )}
312
+ {labels.legend[node.type] ?? DEFAULT_FLOW_EDITOR_LABELS.legend.dynamic_choice}
282
313
  </span>
283
314
  <div className="flex items-center gap-1">
284
315
  {hasError && (
@@ -321,9 +352,7 @@ export function FlowNodeCard({ data }: NodeProps) {
321
352
  addLabel={labels.quickAdd.fromHandle}
322
353
  isSelfLoop={row.isSelfLoop}
323
354
  selfLoopLabel={labels.legendPanel.selfLoop}
324
- {...(onQuickAdd
325
- ? { onQuickAdd: (params) => onQuickAdd({ nodeId: node.id, ...params }) }
326
- : {})}
355
+ {...(onQuickAdd ? { onQuickAdd: (params) => onQuickAdd({ nodeId: node.id, ...params }) } : {})}
327
356
  />
328
357
  ))}
329
358
  </div>
@@ -2,14 +2,15 @@ import { useState, type ReactNode } from 'react'
2
2
  import { Plus, Trash2, Save, X, AlertTriangle, AlertCircle } from 'lucide-react'
3
3
  import { FlowWhatsAppPreview } from './FlowWhatsAppPreview'
4
4
  import { nodeLabel } from './FlowNodeCard'
5
- import { CROSS_FLOW_PREFIX, CONDITION_OPERATORS, BUILT_IN_ACTION_KINDS, PASS_THROUGH_ACTION_KINDS } from './flowGraph'
6
- import { DEFAULT_FLOW_EDITOR_LABELS, type FlowEditorLabels } from './labels'
5
+ import { CROSS_FLOW_PREFIX, CONDITION_OPERATORS, BUILT_IN_ACTION_KINDS, isPassThroughAction as passesThrough } from './flowGraph'
6
+ import { DEFAULT_FLOW_EDITOR_LABELS, DEFAULT_FLOW_RUNNER_FIELD_LABELS, type FlowEditorLabels } from './labels'
7
+ import { FlowPossibleNextField } from './FlowPossibleNextField'
8
+ import { FlowRunnerFields } from './FlowRunnerFields'
7
9
  import type { FlowGraphData, FlowNodeData, GraphIssue } from './flowGraph'
10
+ import { PANEL_FIELD_CLASSNAME } from './flowPanelStyles'
8
11
 
9
- const SELECT_CLASSNAME =
10
- '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'
11
- const INPUT_CLASSNAME =
12
- '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'
12
+ const SELECT_CLASSNAME = PANEL_FIELD_CLASSNAME
13
+ const INPUT_CLASSNAME = PANEL_FIELD_CLASSNAME
13
14
 
14
15
  function truncateLabel(value: string, max = 60): string {
15
16
  if (!value) return '—'
@@ -21,6 +22,7 @@ function WhatsAppTextField({
21
22
  value,
22
23
  onValueChange,
23
24
  options,
25
+ optionDetails,
24
26
  placeholder,
25
27
  labels,
26
28
  }: {
@@ -28,6 +30,7 @@ function WhatsAppTextField({
28
30
  value: string
29
31
  onValueChange: (value: string) => void
30
32
  options?: [string, string][]
33
+ optionDetails?: FlowNodeData['optionDetails']
31
34
  placeholder?: string
32
35
  labels: FlowEditorLabels
33
36
  }) {
@@ -46,7 +49,7 @@ function WhatsAppTextField({
46
49
  <div>
47
50
  <label className="text-xs font-medium text-gray-500 dark:text-gray-400">{labels.nodePanel.preview}</label>
48
51
  <div className="mt-1">
49
- <FlowWhatsAppPreview body={value} options={options} labels={labels.nodePanel} />
52
+ <FlowWhatsAppPreview body={value} options={options} optionDetails={optionDetails} labels={labels.nodePanel} />
50
53
  </div>
51
54
  </div>
52
55
  </div>
@@ -102,8 +105,9 @@ export function FlowNodePanel({
102
105
  const isFixedLogic = draft.type === 'entrada_choice'
103
106
  const isAction = draft.type === 'action'
104
107
  const isSendMedia = isAction && draft.actionKind === BUILT_IN_ACTION_KINDS.SEND_MEDIA
105
- const isPassThroughAction = isAction && Boolean(draft.actionKind && PASS_THROUGH_ACTION_KINDS.includes(draft.actionKind))
108
+ const isPassThroughAction = passesThrough(draft)
106
109
  const isCondition = draft.type === 'condition'
110
+ const isDynamicChoice = draft.type === 'dynamic_choice'
107
111
  const isStart = graph.startNodeId === node.id
108
112
  const nodeIssues = issues.filter((i) => i.nodeId === node.id)
109
113
  // Chaves já usadas por perguntas deste fluxo — sugestão pro campo de variável da condição,
@@ -238,7 +242,7 @@ export function FlowNodePanel({
238
242
  </div>
239
243
  )}
240
244
 
241
- {!isFixedLogic && !isAction && !isCondition && (
245
+ {!isFixedLogic && !isAction && !isCondition && !isDynamicChoice && (
242
246
  <div>
243
247
  <label className="text-xs font-medium text-gray-500 dark:text-gray-400">
244
248
  {labels.nodePanel.questionType}
@@ -263,7 +267,8 @@ export function FlowNodePanel({
263
267
  <WhatsAppTextField
264
268
  label={labels.nodePanel.question}
265
269
  value={draft.question ?? ''}
266
- options={draft.questionType === 'choice' ? draft.options : undefined}
270
+ options={draft.questionType === 'choice' || draft.type === 'menu' ? draft.options : undefined}
271
+ optionDetails={draft.optionDetails}
267
272
  onValueChange={(value) => setDraft((prev) => ({ ...prev, question: value }))}
268
273
  labels={labels}
269
274
  />
@@ -387,6 +392,25 @@ export function FlowNodePanel({
387
392
  </div>
388
393
  )}
389
394
 
395
+ {!isFixedLogic && !isAction && !isCondition && (
396
+ <FlowRunnerFields
397
+ draft={draft}
398
+ onDraftChange={setDraft}
399
+ renderTargetOptions={nextNodeOptions}
400
+ knownContextKeys={knownContextKeys}
401
+ labels={labels.runnerFields ?? DEFAULT_FLOW_RUNNER_FIELD_LABELS}
402
+ />
403
+ )}
404
+
405
+ {isAction && draft.actionKind && (
406
+ <FlowPossibleNextField
407
+ draft={draft}
408
+ onDraftChange={setDraft}
409
+ renderTargetOptions={nextNodeOptions}
410
+ labels={labels.runnerFields ?? DEFAULT_FLOW_RUNNER_FIELD_LABELS}
411
+ />
412
+ )}
413
+
390
414
  {/* Ação de passagem também escolhe destino: sem isto, o material era enviado e a conversa
391
415
  parava ali, sem caminho para o atendimento. Ação terminal continua sem o campo. */}
392
416
  {(!isAction || isPassThroughAction) && (
@@ -1,14 +1,16 @@
1
1
  import { useEffect, useLayoutEffect, useRef, useState } from 'react'
2
- import { Plus, MessageCircleQuestion, GitBranch, Zap, Diamond, ChevronRight } from 'lucide-react'
2
+ import { Plus, MessageCircleQuestion, GitBranch, Zap, Diamond, ChevronRight, ListChecks, MessageSquareText } from 'lucide-react'
3
3
 
4
4
  import { placeFloatingPanel, type FloatingPlacement } from './flowMenuPlacement'
5
- import { DEFAULT_FLOW_EDITOR_LABELS, type FlowEditorLabels } from './labels'
5
+ import { DEFAULT_FLOW_EDITOR_LABELS, DEFAULT_FLOW_RUNNER_FIELD_LABELS, type FlowEditorLabels } from './labels'
6
6
  import type { FlowActionKind, FlowQuestionType } from './flowGraph'
7
7
 
8
8
  export type NewNodeSpec =
9
9
  | { kind: 'question'; questionType: FlowQuestionType }
10
10
  | { kind: 'decision' }
11
11
  | { kind: 'condition' }
12
+ | { kind: 'dynamicChoice' }
13
+ | { kind: 'message' }
12
14
  | { kind: 'action'; actionKind: FlowActionKind }
13
15
 
14
16
  export interface FlowPaletteActionOption {
@@ -46,6 +48,7 @@ export function FlowPaletteMenu({ onSelect, labels, actionOptions }: FlowPalette
46
48
  const resolvedActionOptions = actionOptions ?? [
47
49
  { actionKind: 'handoff', label: labels.actionKindLabels.handoff ?? 'Encaminhar para atendimento' },
48
50
  ]
51
+ const runnerLabels = labels.runnerFields ?? DEFAULT_FLOW_RUNNER_FIELD_LABELS
49
52
  const [submenu, setSubmenu] = useState<'question' | 'action' | null>(null)
50
53
  const questionTriggerRef = useRef<HTMLButtonElement>(null)
51
54
  const actionTriggerRef = useRef<HTMLButtonElement>(null)
@@ -143,6 +146,26 @@ export function FlowPaletteMenu({ onSelect, labels, actionOptions }: FlowPalette
143
146
  <Diamond size={15} className="text-cyan-500" /> {labels.palette.condition}
144
147
  </button>
145
148
 
149
+ <button
150
+ onMouseEnter={() => setSubmenu(null)}
151
+ onClick={() => select({ kind: 'dynamicChoice' })}
152
+ className="w-full flex items-center gap-2 px-3 py-2 text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700"
153
+ data-cv-tooltip={runnerLabels.paletteDynamicChoiceHint}
154
+ aria-label={runnerLabels.paletteDynamicChoiceHint}
155
+ >
156
+ <ListChecks size={15} className="text-teal-500" aria-hidden="true" /> {runnerLabels.paletteDynamicChoice}
157
+ </button>
158
+
159
+ <button
160
+ onMouseEnter={() => setSubmenu(null)}
161
+ onClick={() => select({ kind: 'message' })}
162
+ className="w-full flex items-center gap-2 px-3 py-2 text-sm text-gray-700 dark:text-gray-200 hover:bg-gray-50 dark:hover:bg-gray-700"
163
+ data-cv-tooltip={runnerLabels.paletteMessageHint}
164
+ aria-label={runnerLabels.paletteMessageHint}
165
+ >
166
+ <MessageSquareText size={15} className="text-orange-500" aria-hidden="true" /> {runnerLabels.paletteMessage}
167
+ </button>
168
+
146
169
  <div className="relative">
147
170
  <button
148
171
  ref={actionTriggerRef}
@@ -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
+ }
@@ -0,0 +1,321 @@
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 { OPTIONAL_RUNNER_FIELD_LABEL_DEFAULTS, 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 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
114
+ const validation = draft.validation ?? {}
115
+ const update = (patch: Partial<FlowAnswerValidation>) => onDraftChange((previous) => withValidation(previous, patch))
116
+
117
+ if (draft.questionType === 'date') {
118
+ return (
119
+ <div className="space-y-2">
120
+ <label className="flex items-center gap-2 text-xs text-gray-600 dark:text-gray-300">
121
+ <input
122
+ type="checkbox"
123
+ checked={validation.minDate === 'today'}
124
+ onChange={(event) => update({ minDate: event.target.checked ? 'today' : undefined })}
125
+ />
126
+ {labels.minDateToday}
127
+ </label>
128
+ <ContextKeyField
129
+ label={labels.afterContextKey}
130
+ value={validation.afterContextKey}
131
+ knownContextKeys={knownContextKeys}
132
+ onValueChange={(afterContextKey) => update({ afterContextKey })}
133
+ />
134
+ </div>
135
+ )
136
+ }
137
+
138
+ if (draft.questionType === 'time') return <TimeValidationFields {...props} />
139
+
140
+ if (draft.questionType === 'int' || draft.questionType === 'money') {
141
+ return (
142
+ <div className="flex gap-2">
143
+ <NumberField label={labels.minValue} value={validation.min} onValueChange={(min) => update({ min })} />
144
+ <NumberField label={labels.maxValue} value={validation.max} onValueChange={(max) => update({ max })} />
145
+ </div>
146
+ )
147
+ }
148
+
149
+ if (!draft.questionType || draft.questionType === 'text') {
150
+ return (
151
+ <div className="flex gap-2">
152
+ <NumberField
153
+ label={labels.minLength}
154
+ value={validation.minLength}
155
+ onValueChange={(minLength) => update({ minLength })}
156
+ />
157
+ <NumberField
158
+ label={labels.maxLength}
159
+ value={validation.maxLength}
160
+ onValueChange={(maxLength) => update({ maxLength })}
161
+ />
162
+ </div>
163
+ )
164
+ }
165
+
166
+ return null
167
+ }
168
+
169
+ function OptionDetailsField({ draft, onDraftChange, labels }: FlowRunnerFieldsProps) {
170
+ const options = draft.options ?? []
171
+ if (options.length === 0) return null
172
+
173
+ function updateDetail(optionId: string, field: 'description' | 'section', value: string) {
174
+ onDraftChange((previous) => {
175
+ const current = previous.optionDetails?.[optionId] ?? {}
176
+ const detail = { ...current, [field]: value || undefined }
177
+ return { ...previous, optionDetails: { ...previous.optionDetails, [optionId]: detail } }
178
+ })
179
+ }
180
+
181
+ return (
182
+ <div className="space-y-2">
183
+ {options.map(([optionId, title]) => (
184
+ <div key={optionId} className="space-y-1">
185
+ <span className="text-[11px] font-medium text-gray-500 dark:text-gray-400">{title || optionId}</span>
186
+ <div className="flex gap-2">
187
+ <input
188
+ value={draft.optionDetails?.[optionId]?.description ?? ''}
189
+ placeholder={labels.optionDescription}
190
+ aria-label={`${labels.optionDescription}: ${title}`}
191
+ onChange={(event) => updateDetail(optionId, 'description', event.target.value)}
192
+ className={`flex-1 ${PANEL_FIELD_CLASSNAME}`}
193
+ />
194
+ <input
195
+ value={draft.optionDetails?.[optionId]?.section ?? ''}
196
+ placeholder={labels.optionSection}
197
+ aria-label={`${labels.optionSection}: ${title}`}
198
+ onChange={(event) => updateDetail(optionId, 'section', event.target.value)}
199
+ className={`w-24 ${PANEL_FIELD_CLASSNAME}`}
200
+ />
201
+ </div>
202
+ </div>
203
+ ))}
204
+ </div>
205
+ )
206
+ }
207
+
208
+ function TextField(props: {
209
+ label: string
210
+ value: string
211
+ hint?: string
212
+ placeholder?: string
213
+ onValueChange: (value: string) => void
214
+ }) {
215
+ return (
216
+ <div>
217
+ <label className={PANEL_LABEL_CLASSNAME}>{props.label}</label>
218
+ <input
219
+ value={props.value}
220
+ placeholder={props.placeholder}
221
+ onChange={(event) => props.onValueChange(event.target.value)}
222
+ className={`w-full mt-1 ${PANEL_FIELD_CLASSNAME}`}
223
+ />
224
+ {props.hint && <p className={PANEL_HINT_CLASSNAME}>{props.hint}</p>}
225
+ </div>
226
+ )
227
+ }
228
+
229
+ export function FlowRunnerFields(props: FlowRunnerFieldsProps) {
230
+ const { draft, onDraftChange, labels } = props
231
+ const isDynamic = draft.type === 'dynamic_choice'
232
+ const isChoice = draft.type === 'menu' || draft.questionType === 'choice'
233
+ const isQuestion = draft.type === 'question' && !isChoice
234
+
235
+ return (
236
+ <div className="pt-2 border-t border-gray-100 dark:border-gray-700 space-y-3">
237
+ <p className="text-xs font-semibold text-gray-700 dark:text-gray-200">{labels.section}</p>
238
+ <p className={PANEL_HINT_CLASSNAME}>{labels.placeholdersHint}</p>
239
+
240
+ {isDynamic && (
241
+ <>
242
+ <TextField
243
+ label={labels.choiceProvider}
244
+ hint={labels.choiceProviderHint}
245
+ value={draft.choiceProvider ?? ''}
246
+ onValueChange={(value) =>
247
+ onDraftChange((previous) => ({ ...previous, choiceProvider: value || undefined }))
248
+ }
249
+ />
250
+ <TextField
251
+ label={labels.contextKey}
252
+ value={draft.contextKey ?? ''}
253
+ onValueChange={(value) => onDraftChange((previous) => ({ ...previous, contextKey: value || undefined }))}
254
+ />
255
+ </>
256
+ )}
257
+
258
+ {isQuestion && <ValidationFields {...props} />}
259
+ {isChoice && <OptionDetailsField {...props} />}
260
+ {isChoice && (
261
+ <div>
262
+ <label className={PANEL_LABEL_CLASSNAME}>{labels.unmatchedChoice}</label>
263
+ <select
264
+ value={draft.unmatchedChoice ?? 'reask'}
265
+ onChange={(event) => {
266
+ const value = event.target.value === 'default' ? 'default' : undefined
267
+ onDraftChange((previous) => ({ ...previous, unmatchedChoice: value }))
268
+ }}
269
+ className={`w-full mt-1 ${PANEL_FIELD_CLASSNAME}`}
270
+ >
271
+ <option value="reask">{labels.unmatchedChoiceReask}</option>
272
+ <option value="default">{labels.unmatchedChoiceDefault}</option>
273
+ </select>
274
+ </div>
275
+ )}
276
+ {(isChoice || isDynamic) && (
277
+ <TextField
278
+ label={labels.listButtonLabel}
279
+ value={draft.listButtonLabel ?? ''}
280
+ onValueChange={(value) => onDraftChange((previous) => ({ ...previous, listButtonLabel: value || undefined }))}
281
+ />
282
+ )}
283
+ {isQuestion && (
284
+ <TextField
285
+ label={labels.skipKeywords}
286
+ hint={labels.skipKeywordsHint}
287
+ value={(draft.skipKeywords ?? []).join(', ')}
288
+ onValueChange={(value) => {
289
+ const keywords = value
290
+ .split(',')
291
+ .map((keyword) => keyword.trim())
292
+ .filter(Boolean)
293
+ onDraftChange((previous) => ({ ...previous, skipKeywords: keywords.length > 0 ? keywords : undefined }))
294
+ }}
295
+ />
296
+ )}
297
+
298
+ <TextField
299
+ label={labels.fallbackMessage}
300
+ placeholder={labels.fallbackPlaceholder}
301
+ value={draft.fallbackMessage ?? ''}
302
+ onValueChange={(value) => onDraftChange((previous) => ({ ...previous, fallbackMessage: value || undefined }))}
303
+ />
304
+ <div>
305
+ <NumberField
306
+ label={labels.maxInvalidAnswers}
307
+ value={draft.maxInvalidAnswers}
308
+ onValueChange={(value) =>
309
+ onDraftChange((previous) => ({
310
+ ...previous,
311
+ maxInvalidAnswers: value && value > 0 ? Math.floor(value) : undefined,
312
+ }))
313
+ }
314
+ />
315
+ <p className={PANEL_HINT_CLASSNAME}>{labels.maxInvalidAnswersHint}</p>
316
+ </div>
317
+
318
+ {(draft.type === 'menu' || draft.type === 'question') && <FlowKeywordRoutesField {...props} />}
319
+ </div>
320
+ )
321
+ }