@adatechnology/conversations-ui 0.1.0-rc.23 → 0.1.0-rc.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1252 @@
1
+ import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
2
+ import {
3
+ ReactFlow,
4
+ Background,
5
+ Controls,
6
+ MiniMap,
7
+ MarkerType,
8
+ applyNodeChanges,
9
+ type Node,
10
+ type NodeChange,
11
+ type Edge,
12
+ type Connection,
13
+ type ReactFlowInstance,
14
+ } from '@xyflow/react'
15
+ import '@xyflow/react/dist/style.css'
16
+ import { Plus, Trash2, LayoutGrid, AlertTriangle, AlertCircle, Save, Undo2, Map as MapIcon, Workflow } from 'lucide-react'
17
+
18
+ import { useIsDarkTheme } from '../useDarkMode'
19
+ import { flowNodeTypes, nodeLabel, type FlowNodeCardData } from './FlowNodeCard'
20
+ import { flowPortalNodeTypes, type FlowPortalNodeData } from './FlowPortalNode'
21
+ import { flowGroupHeaderNodeTypes, type FlowGroupHeaderData } from './FlowGroupHeader'
22
+ import { flowGroupFrameNodeTypes, type FlowGroupFrameData } from './FlowGroupFrame'
23
+ import { FlowNodePanel } from './FlowNodePanel'
24
+ import { FlowPalette, type FlowPaletteActionOption, type NewNodeSpec } from './FlowPalette'
25
+ import { FlowMapCanvas } from './FlowMapCanvas'
26
+ import { mergeFlowEditorLabels, type FlowEditorLabels } from './labels'
27
+ import {
28
+ computeAutoLayout,
29
+ slugifyNodeId,
30
+ targetsOf,
31
+ validateGraph,
32
+ isCrossFlowTarget,
33
+ crossFlowKey,
34
+ crossFlowTargetsOf,
35
+ findCollectionChains,
36
+ estimateNodeHeight,
37
+ NODE_CARD_WIDTH,
38
+ CROSS_FLOW_PREFIX,
39
+ type FlowGraphData,
40
+ type FlowNodeData,
41
+ type GraphIssue,
42
+ } from './flowGraph'
43
+
44
+ const RF_NODE_TYPES = {
45
+ ...flowNodeTypes,
46
+ ...flowPortalNodeTypes,
47
+ ...flowGroupHeaderNodeTypes,
48
+ ...flowGroupFrameNodeTypes,
49
+ }
50
+
51
+ const CHAIN_FRAME_PADDING = 36
52
+ const COLUMN_GAP = 360
53
+ const ROW_GAP = 40
54
+ const NS_SEP = '::'
55
+ const FLOW_KEY_PATTERN = /^[a-z0-9_]{2,40}$/
56
+
57
+ const EDGE_COLOR_LINEAR = '#94a3b8'
58
+ const EDGE_COLOR_BRANCH = '#8b5cf6'
59
+ const EDGE_COLOR_FALLBACK = '#cbd5e1'
60
+ const EDGE_COLOR_LIVE = '#3b82f6'
61
+ const EDGE_COLOR_CROSS_FLOW = '#06b6d4'
62
+ const BACKGROUND_COLOR_LIGHT = '#cbd5e1'
63
+ const BACKGROUND_COLOR_DARK = '#334155'
64
+
65
+ /** Onde cada conversa viva está parada agora, para o card pulsar com a contagem. */
66
+ export interface FlowLivePosition {
67
+ currentState: string
68
+ flow: string | null
69
+ nodeId: string | null
70
+ menuNodeId: string | null
71
+ }
72
+
73
+ export interface CreateFlowInput {
74
+ key: string
75
+ label: string
76
+ showInMenu: boolean
77
+ /** Ausente quando `showInMenu` é falso — não há opção de menu para rotular. */
78
+ menuOptionLabel?: string
79
+ }
80
+
81
+ /**
82
+ * Backend de fluxos do host. Funções cruas em vez de um cliente HTTP: o pacote roda em produtos com
83
+ * axios, fetch e react-query, e nenhum deles precisa entrar como dependência daqui.
84
+ */
85
+ export interface FlowsWorkspaceApi {
86
+ getGraphs(): Promise<Record<string, FlowGraphData>>
87
+ saveGraph(key: string, graph: FlowGraphData): Promise<void>
88
+ /**
89
+ * Criar e excluir fluxo são **opcionais por capacidade**: produto cujos fluxos vêm de um seed
90
+ * versionado não expõe rota para isso, e a tela simplesmente não desenha os botões — em vez de
91
+ * oferecer uma ação que estoura no clique.
92
+ */
93
+ createFlow?(input: CreateFlowInput): Promise<void>
94
+ deleteFlow?(key: string): Promise<void>
95
+ /** Contagem de conversas vivas por nó. Ausente, os cards não pulsam e nada é consultado. */
96
+ getLivePositions?(): Promise<FlowLivePosition[]>
97
+ }
98
+
99
+ export interface FlowsWorkspaceProps {
100
+ readonly api: FlowsWorkspaceApi
101
+ /** Fluxo raiz — o que abre por padrão e o único que não pode ser excluído. */
102
+ readonly rootFlowKey?: string
103
+ readonly labels?: Partial<FlowEditorLabels>
104
+ /** Kinds de ação do produto oferecidos na paleta (`trigger_simulation`, `abrir_comanda`…). */
105
+ readonly actionOptions?: readonly FlowPaletteActionOption[]
106
+ /** Seletor de arquivos do nó `send_media` — a biblioteca é do host, então entra por slot. */
107
+ readonly renderMediaPicker?: (node: FlowNodeData) => ReactNode
108
+ /** Intervalo do polling de posições vivas. Só tem efeito com `getLivePositions`. */
109
+ readonly livePollIntervalMs?: number
110
+ readonly className?: string
111
+ }
112
+
113
+ // Um portal por (nó de origem, fluxo alvo) — se duas opções do mesmo nó apontarem pro mesmo
114
+ // fluxo, compartilham um único portal (menos poluição visual, ainda uma ligação por opção).
115
+ function portalNodeId(sourceId: string, target: string): string {
116
+ return `__portal__${sourceId}__${target}`
117
+ }
118
+
119
+ // Namespacing de ids: com fusão editável, nós de fluxos diferentes convivem no mesmo canvas
120
+ // React Flow, que exige ids únicos globalmente — "flowKey::nodeId" evita colisão entre fluxos
121
+ // que reutilizem o mesmo id de nó (ex.: vários fluxos com um nó "root").
122
+ function ns(flowKey: string, nodeId: string): string {
123
+ return `${flowKey}${NS_SEP}${nodeId}`
124
+ }
125
+
126
+ function parseNs(id: string): { flowKey: string; nodeId: string } {
127
+ const index = id.indexOf(NS_SEP)
128
+ return index === -1
129
+ ? { flowKey: '', nodeId: id }
130
+ : { flowKey: id.slice(0, index), nodeId: id.slice(index + NS_SEP.length) }
131
+ }
132
+
133
+ // Um fluxo aberto no canvas de detalhe — o primeiro da lista é o "primário" (dono da paleta,
134
+ // organizar, publicar e excluir-fluxo); os demais chegaram por fusão editável (clique num portal)
135
+ // e ficam com um cabeçalho flutuante pra focar neles sozinhos ou fechar.
136
+ type OpenFlow = { key: string; offset: { x: number; y: number } }
137
+
138
+ // Fecho transitivo de saltos flow:<key> a partir de rootKey — "o fluxo completo": abrir um
139
+ // fluxo já traz junto tudo que ele referencia (e o que essas referências referenciam), sem
140
+ // precisar clicar em cada portal manualmente.
141
+ function autoMergeAll(rootKey: string, graphsSource: Record<string, FlowGraphData>): OpenFlow[] {
142
+ const visited = new Set<string>()
143
+ const queue = [rootKey]
144
+ while (queue.length > 0) {
145
+ const key = queue.shift()!
146
+ if (visited.has(key) || !graphsSource[key]) continue
147
+ visited.add(key)
148
+ for (const target of crossFlowTargetsOf(graphsSource[key]!)) {
149
+ if (!visited.has(target) && graphsSource[target]) queue.push(target)
150
+ }
151
+ }
152
+ return [...visited].map((key) => ({ key, offset: { x: 0, y: 0 } }))
153
+ }
154
+
155
+ // Layout único pra TODOS os nós de TODOS os fluxos abertos juntos — ao contrário de posicionar
156
+ // cada fluxo independente e só deslocar (que não evita sobreposição entre fluxos nem considera a
157
+ // altura real de cada card), aqui o ranqueamento por BFS roda sobre o grafo mesclado inteiro,
158
+ // usando ligações reais (inclusive saltos flow:<key> já resolvidos pro nó inicial do fluxo
159
+ // alvo). Mesma orientação do computeAutoLayout: da esquerda para a direita, um rank por coluna.
160
+ function computeMergedLayout(
161
+ openFlows: readonly OpenFlow[],
162
+ workingGraphs: Record<string, FlowGraphData>,
163
+ primaryFlowKey: string,
164
+ ): Map<string, { x: number; y: number }> {
165
+ const openKeys = new Set(openFlows.map((flow) => flow.key))
166
+
167
+ const nodeByNsId = new Map<string, FlowNodeData>()
168
+ for (const { key } of openFlows) {
169
+ const graph = workingGraphs[key]
170
+ if (!graph) continue
171
+ for (const node of Object.values(graph.nodes)) nodeByNsId.set(ns(key, node.id), node)
172
+ }
173
+
174
+ function forwardEdges(flowKey: string, node: FlowNodeData): string[] {
175
+ const result: string[] = []
176
+ for (const { target } of targetsOf(node)) {
177
+ if (isCrossFlowTarget(target)) {
178
+ const targetFlowKey = crossFlowKey(target)
179
+ const targetGraph = openKeys.has(targetFlowKey) ? workingGraphs[targetFlowKey] : undefined
180
+ if (targetGraph) result.push(ns(targetFlowKey, targetGraph.startNodeId))
181
+ } else if (workingGraphs[flowKey]?.nodes[target]) {
182
+ result.push(ns(flowKey, target))
183
+ }
184
+ }
185
+ return result
186
+ }
187
+
188
+ const rank = new Map<string, number>()
189
+ const primaryGraph = workingGraphs[primaryFlowKey]
190
+ const rootId = primaryGraph ? ns(primaryFlowKey, primaryGraph.startNodeId) : undefined
191
+ if (rootId && nodeByNsId.has(rootId)) {
192
+ rank.set(rootId, 0)
193
+ const queue = [rootId]
194
+ while (queue.length > 0) {
195
+ const id = queue.shift()!
196
+ const node = nodeByNsId.get(id)
197
+ if (!node) continue
198
+ for (const nextId of forwardEdges(parseNs(id).flowKey, node)) {
199
+ if (!rank.has(nextId)) {
200
+ rank.set(nextId, rank.get(id)! + 1)
201
+ queue.push(nextId)
202
+ }
203
+ }
204
+ }
205
+ }
206
+
207
+ // Nós não alcançados a partir do início do fluxo primário (outro fluxo mesclado sem ligação
208
+ // de volta pro primário, ou nó órfão) vão TODOS numa única camada extra abaixo de tudo — uma
209
+ // camada por órfão empurrava cada um para uma linha própria, cada vez mais longe da área
210
+ // visível, e desligar um fio dava a impressão de ter apagado o card.
211
+ const strayRank = Math.max(0, ...rank.values()) + 1
212
+ for (const nsId of nodeByNsId.keys()) {
213
+ if (!rank.has(nsId)) rank.set(nsId, strayRank)
214
+ }
215
+
216
+ const layers = new Map<number, string[]>()
217
+ for (const [nsId, nodeRank] of rank) {
218
+ if (!layers.has(nodeRank)) layers.set(nodeRank, [])
219
+ layers.get(nodeRank)!.push(nsId)
220
+ }
221
+
222
+ const positions = new Map<string, { x: number; y: number }>()
223
+ for (const nodeRank of [...layers.keys()].sort((a, b) => a - b)) {
224
+ // Alinhado pelo topo pelo mesmo motivo de `computeAutoLayout`: coluna centralizada saltava
225
+ // inteira a cada nó a mais num ramo.
226
+ let cursorY = 0
227
+ for (const nsId of layers.get(nodeRank)!) {
228
+ positions.set(nsId, { x: nodeRank * COLUMN_GAP, y: cursorY })
229
+ cursorY += estimateNodeHeight(nodeByNsId.get(nsId)!) + ROW_GAP
230
+ }
231
+ }
232
+ return positions
233
+ }
234
+
235
+ function computeLiveCounts(
236
+ flowKey: string,
237
+ rootFlowKey: string,
238
+ livePositions: readonly FlowLivePosition[] | undefined,
239
+ ): Record<string, number> {
240
+ const counts: Record<string, number> = {}
241
+ for (const position of livePositions ?? []) {
242
+ if (position.flow !== flowKey && flowKey !== rootFlowKey) continue
243
+ const nodeId = flowKey === rootFlowKey ? position.menuNodeId : position.nodeId
244
+ if (!nodeId) continue
245
+ counts[nodeId] = (counts[nodeId] ?? 0) + 1
246
+ }
247
+ return counts
248
+ }
249
+
250
+ // Constrói as ligações de TODOS os fluxos abertos juntos. Um salto "flow:<key>" vira ligação
251
+ // real até o nó inicial do fluxo alvo quando esse fluxo já está mesclado no canvas; caso
252
+ // contrário, continua indo até o portal (pseudo-nó) daquele fluxo, como antes da fusão.
253
+ function buildAllEdges(
254
+ openFlows: readonly OpenFlow[],
255
+ workingGraphs: Record<string, FlowGraphData>,
256
+ rootFlowKey: string,
257
+ livePositions: readonly FlowLivePosition[] | undefined,
258
+ ): Edge[] {
259
+ const openKeys = new Set(openFlows.map((flow) => flow.key))
260
+ const edges: Edge[] = []
261
+
262
+ for (const { key: flowKey } of openFlows) {
263
+ const graph = workingGraphs[flowKey]
264
+ if (!graph) continue
265
+ const liveCounts = computeLiveCounts(flowKey, rootFlowKey, livePositions)
266
+
267
+ for (const [id, node] of Object.entries(graph.nodes)) {
268
+ const isLive = (liveCounts[id] ?? 0) > 0
269
+ for (const { target, optionId, isDefault } of targetsOf(node)) {
270
+ const crossFlow = isCrossFlowTarget(target)
271
+ let targetFlowKey = flowKey
272
+ let rawTargetId = target
273
+ if (crossFlow) {
274
+ const wantedKey = crossFlowKey(target)
275
+ const targetGraph = openKeys.has(wantedKey) ? workingGraphs[wantedKey] : undefined
276
+ if (targetGraph) {
277
+ targetFlowKey = wantedKey
278
+ rawTargetId = targetGraph.startNodeId
279
+ } else {
280
+ rawTargetId = portalNodeId(id, target)
281
+ }
282
+ }
283
+ const source = ns(flowKey, id)
284
+ const edgeTarget = ns(targetFlowKey, rawTargetId)
285
+
286
+ if (optionId === undefined && !isDefault) {
287
+ const color = crossFlow ? EDGE_COLOR_CROSS_FLOW : isLive ? EDGE_COLOR_LIVE : EDGE_COLOR_LINEAR
288
+ edges.push({
289
+ id: `${source}->${edgeTarget}`,
290
+ source,
291
+ target: edgeTarget,
292
+ type: 'bezier',
293
+ animated: isLive,
294
+ style: crossFlow
295
+ ? { stroke: color, strokeWidth: 1.5, strokeDasharray: '3 3' }
296
+ : { stroke: color, strokeWidth: isLive ? 2.5 : 1.5 },
297
+ markerEnd: { type: MarkerType.ArrowClosed, color, width: 18, height: 18 },
298
+ })
299
+ } else if (isDefault) {
300
+ const color = crossFlow ? EDGE_COLOR_CROSS_FLOW : EDGE_COLOR_FALLBACK
301
+ edges.push({
302
+ id: `${source}->${edgeTarget}-default`,
303
+ source,
304
+ sourceHandle: '__default',
305
+ target: edgeTarget,
306
+ type: 'bezier',
307
+ style: { stroke: color, strokeWidth: 1.5, strokeDasharray: '5 4' },
308
+ markerEnd: { type: MarkerType.ArrowClosed, color, width: 16, height: 16 },
309
+ })
310
+ } else {
311
+ const color = crossFlow ? EDGE_COLOR_CROSS_FLOW : isLive ? EDGE_COLOR_LIVE : EDGE_COLOR_BRANCH
312
+ edges.push({
313
+ id: `${source}->${edgeTarget}-${optionId}`,
314
+ source,
315
+ sourceHandle: optionId,
316
+ target: edgeTarget,
317
+ type: 'bezier',
318
+ animated: isLive,
319
+ style: crossFlow
320
+ ? { stroke: color, strokeWidth: 1.75, strokeDasharray: '3 3' }
321
+ : { stroke: color, strokeWidth: isLive ? 2.5 : 1.75 },
322
+ markerEnd: { type: MarkerType.ArrowClosed, color, width: 18, height: 18 },
323
+ })
324
+ }
325
+ }
326
+ }
327
+ }
328
+ return edges
329
+ }
330
+
331
+ function newNodeFromSpec(spec: NewNodeSpec, existingIds: Set<string>): FlowNodeData {
332
+ if (spec.kind === 'question') {
333
+ const id = slugifyNodeId('nova_pergunta', existingIds)
334
+ return { id, type: 'question', questionType: spec.questionType, contextKey: id, question: '' }
335
+ }
336
+ if (spec.kind === 'decision') {
337
+ const id = slugifyNodeId('nova_decisao', existingIds)
338
+ return {
339
+ id,
340
+ type: 'question',
341
+ questionType: 'choice',
342
+ contextKey: id,
343
+ question: '',
344
+ options: [
345
+ ['1', 'Opção 1'],
346
+ ['2', 'Opção 2'],
347
+ ],
348
+ }
349
+ }
350
+ if (spec.kind === 'condition') {
351
+ const id = slugifyNodeId('nova_condicao', existingIds)
352
+ return { id, type: 'condition', conditionOperator: '>' }
353
+ }
354
+ const id = slugifyNodeId('nova_acao', existingIds)
355
+ return { id, type: 'action', actionKind: spec.actionKind }
356
+ }
357
+
358
+ // Remove referências ao nó excluído: destinos apontando para ele viram '' (destino vazio),
359
+ // para a validação sinalizar claramente em vez de manter uma string órfã silenciosa.
360
+ function removeNodeAndCleanRefs(
361
+ nodes: Record<string, FlowNodeData>,
362
+ nodeId: string,
363
+ ): Record<string, FlowNodeData> {
364
+ const { [nodeId]: _removed, ...rest } = nodes
365
+ return Object.fromEntries(
366
+ Object.entries(rest).map(([id, node]) => {
367
+ if (!node.next) return [id, node]
368
+ if (typeof node.next === 'string') {
369
+ return [id, node.next === nodeId ? { ...node, next: undefined } : node]
370
+ }
371
+ return [
372
+ id,
373
+ {
374
+ ...node,
375
+ next: {
376
+ byAnswer: Object.fromEntries(
377
+ Object.entries(node.next.byAnswer).map(([key, value]) => [key, value === nodeId ? '' : value]),
378
+ ),
379
+ default: node.next.default === nodeId ? '' : node.next.default,
380
+ },
381
+ },
382
+ ]
383
+ }),
384
+ )
385
+ }
386
+
387
+ function extractErrorMessage(error: unknown): string | undefined {
388
+ if (error instanceof Error) return error.message
389
+ return undefined
390
+ }
391
+
392
+ const OUTLINE_BUTTON =
393
+ 'inline-flex items-center gap-1.5 rounded-lg border border-gray-200 dark:border-gray-700 px-3 py-1.5 text-xs font-medium text-gray-600 dark:text-gray-300 hover:border-blue-300 disabled:opacity-40 disabled:cursor-not-allowed'
394
+ const PRIMARY_BUTTON =
395
+ 'inline-flex items-center gap-1.5 rounded-lg bg-blue-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-blue-700 disabled:opacity-40 disabled:cursor-not-allowed'
396
+ const DIALOG_INPUT =
397
+ 'w-full 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'
398
+
399
+ /**
400
+ * Editor de fluxograma completo — barra de ações, abas de fluxo, paleta, canvas com fusão
401
+ * editável, painel de nó, mapa de fluxos e diálogos de criar/excluir.
402
+ *
403
+ * É a tela inteira, não as peças: cada produto que remontava esse grid à mão acabava com uma
404
+ * versão diferente do mesmo editor. Customização entra por `labels`, `actionOptions` e
405
+ * `renderMediaPicker` — nunca por cópia do arquivo.
406
+ */
407
+ export function FlowsWorkspace({
408
+ api,
409
+ rootFlowKey = 'menu',
410
+ labels: labelsOverride,
411
+ actionOptions,
412
+ renderMediaPicker,
413
+ livePollIntervalMs = 5000,
414
+ className,
415
+ }: FlowsWorkspaceProps) {
416
+ const labels = useMemo(() => mergeFlowEditorLabels(labelsOverride), [labelsOverride])
417
+ const isDark = useIsDarkTheme()
418
+
419
+ const [graphs, setGraphs] = useState<Record<string, FlowGraphData> | undefined>(undefined)
420
+ const [loadState, setLoadState] = useState<'loading' | 'ready' | 'error'>('loading')
421
+ const [livePositions, setLivePositions] = useState<FlowLivePosition[] | undefined>(undefined)
422
+ const [viewMode, setViewMode] = useState<'detail' | 'map'>('detail')
423
+ const [openFlows, setOpenFlows] = useState<OpenFlow[]>([{ key: rootFlowKey, offset: { x: 0, y: 0 } }])
424
+ const [hasAutoMerged, setHasAutoMerged] = useState(false)
425
+ const [workingGraphs, setWorkingGraphs] = useState<Record<string, FlowGraphData>>({})
426
+ const [editingRef, setEditingRef] = useState<{ flowKey: string; nodeId: string } | null>(null)
427
+ const [saveState, setSaveState] = useState<'idle' | 'saving' | 'success' | 'error'>('idle')
428
+ const [saveErrorMessage, setSaveErrorMessage] = useState<string | undefined>(undefined)
429
+ const [showCreateDialog, setShowCreateDialog] = useState(false)
430
+ const [showDeleteDialog, setShowDeleteDialog] = useState(false)
431
+ const [newFlow, setNewFlow] = useState({ key: '', label: '', showInMenu: false, menuOptionLabel: '' })
432
+ const [flowMutationState, setFlowMutationState] = useState<{ pending: boolean; error?: string }>({ pending: false })
433
+ const [rfNodes, setRfNodes] = useState<Node[]>([])
434
+ const [flowInstance, setFlowInstance] = useState<ReactFlowInstance | null>(null)
435
+ const [pendingFocusNodeId, setPendingFocusNodeId] = useState<string | null>(null)
436
+
437
+ const reloadGraphs = useCallback(async () => {
438
+ try {
439
+ const loaded = await api.getGraphs()
440
+ setGraphs(loaded)
441
+ setLoadState('ready')
442
+ return loaded
443
+ } catch {
444
+ setLoadState('error')
445
+ return undefined
446
+ }
447
+ }, [api])
448
+
449
+ useEffect(() => {
450
+ void reloadGraphs()
451
+ }, [reloadGraphs])
452
+
453
+ // Polling das posições vivas. `active` corta a resposta que chega depois do desmonte — o
454
+ // intervalo é longo o bastante para uma resposta lenta atravessar a troca de tela.
455
+ useEffect(() => {
456
+ const fetchLive = api.getLivePositions
457
+ if (!fetchLive) return
458
+ let active = true
459
+ async function poll(): Promise<void> {
460
+ try {
461
+ const positions = await fetchLive!()
462
+ if (active) setLivePositions(positions)
463
+ } catch {
464
+ // Contagem viva é enfeite: falhar aqui não pode derrubar o editor.
465
+ }
466
+ }
467
+ void poll()
468
+ const timer = setInterval(() => void poll(), livePollIntervalMs)
469
+ return () => {
470
+ active = false
471
+ clearInterval(timer)
472
+ }
473
+ }, [api, livePollIntervalMs])
474
+
475
+ const primaryFlowKey = openFlows[0]?.key ?? rootFlowKey
476
+ const primaryGraph = workingGraphs[primaryFlowKey]
477
+
478
+ // Assim que os fluxos carregam pela primeira vez, mescla automaticamente todo o fecho
479
+ // transitivo referenciado a partir da raiz — "o fluxo completo" aparece de cara, sem precisar
480
+ // clicar em cada portal. Só roda uma vez (hasAutoMerged); depois disso, focar/mesclar/fechar
481
+ // fica inteiramente sob controle do usuário.
482
+ useEffect(() => {
483
+ if (!graphs || hasAutoMerged) return
484
+ setOpenFlows(autoMergeAll(rootFlowKey, graphs))
485
+ setHasAutoMerged(true)
486
+ }, [graphs, hasAutoMerged, rootFlowKey])
487
+
488
+ // Semeia o rascunho local de qualquer fluxo recém-aberto (seleção inicial, foco ou fusão) —
489
+ // nunca sobrescreve um fluxo que já tem rascunho (preserva edições não publicadas mesmo em
490
+ // recargas de fundo).
491
+ useEffect(() => {
492
+ if (!graphs) return
493
+ setWorkingGraphs((prev) => {
494
+ let changed = false
495
+ const next = { ...prev }
496
+ for (const { key } of openFlows) {
497
+ if (!next[key] && graphs[key]) {
498
+ next[key] = graphs[key]
499
+ changed = true
500
+ }
501
+ }
502
+ return changed ? next : prev
503
+ })
504
+ }, [graphs, openFlows])
505
+
506
+ const isFlowDirty = useCallback(
507
+ (key: string): boolean => {
508
+ const working = workingGraphs[key]
509
+ const server = graphs?.[key]
510
+ if (!working || !server) return false
511
+ return JSON.stringify(working) !== JSON.stringify(server)
512
+ },
513
+ [workingGraphs, graphs],
514
+ )
515
+
516
+ const issuesByFlow = useMemo<Record<string, GraphIssue[]>>(() => {
517
+ const map: Record<string, GraphIssue[]> = {}
518
+ for (const { key } of openFlows) {
519
+ const graph = workingGraphs[key]
520
+ if (graph) map[key] = validateGraph(graph, labels.validation)
521
+ }
522
+ return map
523
+ }, [openFlows, workingGraphs, labels])
524
+
525
+ const errorCount = Object.values(issuesByFlow).reduce(
526
+ (sum, list) => sum + list.filter((issue) => issue.severity === 'error').length,
527
+ 0,
528
+ )
529
+ const warningCount = Object.values(issuesByFlow).reduce(
530
+ (sum, list) => sum + list.filter((issue) => issue.severity === 'warning').length,
531
+ 0,
532
+ )
533
+ const dirtyKeys = openFlows.map((flow) => flow.key).filter(isFlowDirty)
534
+ const isDirty = dirtyKeys.length > 0
535
+
536
+ const updateFlow = useCallback((flowKey: string, updater: (graph: FlowGraphData) => FlowGraphData) => {
537
+ setWorkingGraphs((prev) => {
538
+ const graph = prev[flowKey]
539
+ if (!graph) return prev
540
+ return { ...prev, [flowKey]: updater(graph) }
541
+ })
542
+ }, [])
543
+
544
+ // "Focar": troca o fluxo primário e re-mescla o fecho transitivo dele (o fluxo completo
545
+ // referenciado a partir dele) — não isola mais num único fluxo sozinho, já que o padrão
546
+ // agora é sempre mostrar tudo que está conectado.
547
+ const focusFlow = useCallback(
548
+ (key: string) => {
549
+ const others = openFlows.filter((flow) => flow.key !== key)
550
+ if (others.some((flow) => isFlowDirty(flow.key)) && !window.confirm(labels.workspace.unsavedChangesConfirm)) return
551
+ setOpenFlows(graphs ? autoMergeAll(key, graphs) : [{ key, offset: { x: 0, y: 0 } }])
552
+ if (editingRef && editingRef.flowKey !== key) setEditingRef(null)
553
+ },
554
+ [openFlows, isFlowDirty, editingRef, graphs, labels],
555
+ )
556
+
557
+ // "Fechar": remove um fluxo mesclado sem trocar o foco do primário.
558
+ const closeFlow = useCallback(
559
+ (key: string) => {
560
+ if (isFlowDirty(key) && !window.confirm(labels.workspace.unsavedChangesConfirm)) return
561
+ setOpenFlows((prev) => prev.filter((flow) => flow.key !== key))
562
+ setWorkingGraphs((prev) => {
563
+ const { [key]: _removed, ...rest } = prev
564
+ return rest
565
+ })
566
+ if (editingRef?.flowKey === key) setEditingRef(null)
567
+ },
568
+ [isFlowDirty, editingRef, labels],
569
+ )
570
+
571
+ // Fusão editável: mescla o fluxo alvo no mesmo canvas, posicionado à direita do nó de
572
+ // origem que o referenciou, com os nós de verdade (editáveis ali mesmo) em vez de um portal.
573
+ const mergeFlow = useCallback(
574
+ (targetFlowKey: string, source: { flowKey: string; nodeId: string }) => {
575
+ setOpenFlows((prev) => {
576
+ if (prev.some((flow) => flow.key === targetFlowKey)) return prev
577
+ const sourceOpen = prev.find((flow) => flow.key === source.flowKey)
578
+ const sourceGraph = workingGraphs[source.flowKey]
579
+ const sourceLocalPosition =
580
+ sourceGraph?.nodes[source.nodeId]?.position ??
581
+ (sourceGraph ? computeAutoLayout(sourceGraph)[source.nodeId] : undefined) ?? { x: 0, y: 0 }
582
+ const baseOffset = sourceOpen?.offset ?? { x: 0, y: 0 }
583
+ return [
584
+ ...prev,
585
+ {
586
+ key: targetFlowKey,
587
+ offset: {
588
+ x: baseOffset.x + sourceLocalPosition.x + 400,
589
+ y: baseOffset.y + sourceLocalPosition.y,
590
+ },
591
+ },
592
+ ]
593
+ })
594
+ },
595
+ [workingGraphs],
596
+ )
597
+
598
+ // Mais de um fluxo aberto = layout global (ignora node.position individual, recalcula tudo
599
+ // junto pra nunca sobrepor); um só fluxo aberto = comportamento de sempre (respeita posição
600
+ // salva/arrastada, com fallback pro auto-layout daquele fluxo isolado).
601
+ const isMerged = openFlows.length > 1
602
+ const mergedPositions = useMemo(
603
+ () => (isMerged ? computeMergedLayout(openFlows, workingGraphs, primaryFlowKey) : null),
604
+ [isMerged, openFlows, workingGraphs, primaryFlowKey],
605
+ )
606
+
607
+ // Última posição em que cada nó foi desenhado, e ela manda sobre o layout calculado.
608
+ //
609
+ // O layout mesclado é recalculado a cada mudança de topologia: ligar ou desligar um fio mexia
610
+ // no rank de todo mundo e o canvas inteiro saltava de lugar — o card que perdeu a ligação ia
611
+ // parar na faixa dos órfãos e os demais mudavam de coluna, o que se lê como "o card sumiu".
612
+ // Aqui o layout vira só a semente de quem ainda não tem lugar; o resto fica onde está até o
613
+ // usuário arrastar ou pedir "Organizar".
614
+ const renderedPositionsRef = useRef(new Map<string, { x: number; y: number }>())
615
+
616
+ const derivedNodes = useMemo<Node[]>(() => {
617
+ const allNodes: Node[] = []
618
+ for (const { key: flowKey, offset } of openFlows) {
619
+ const graph = workingGraphs[flowKey]
620
+ if (!graph) continue
621
+ const fallbackPositions = mergedPositions ? {} : computeAutoLayout(graph)
622
+ const liveCounts = computeLiveCounts(flowKey, rootFlowKey, livePositions)
623
+ const flowIssues = issuesByFlow[flowKey] ?? []
624
+ const isPrimary = flowKey === primaryFlowKey
625
+
626
+ // Quem recebe fio de alguém neste fluxo. O que sobra (fora o nó inicial) está solto: o card
627
+ // ganha contorno tracejado e pulsa, para desconectar ou criar um nó ficar visivelmente
628
+ // "falta ligar isto aqui" em vez de silencioso.
629
+ const connectedTargets = new Set<string>()
630
+ for (const candidate of Object.values(graph.nodes)) {
631
+ for (const { target } of targetsOf(candidate)) {
632
+ if (!isCrossFlowTarget(target)) connectedTargets.add(target)
633
+ }
634
+ }
635
+
636
+ function resolvePosition(nodeId: string): { x: number; y: number } {
637
+ if (mergedPositions) {
638
+ const nsId = ns(flowKey, nodeId)
639
+ return renderedPositionsRef.current.get(nsId) ?? mergedPositions.get(nsId) ?? { x: 0, y: 0 }
640
+ }
641
+ const local = graph!.nodes[nodeId]?.position ?? fallbackPositions[nodeId] ?? { x: 0, y: 0 }
642
+ return { x: local.x + offset.x, y: local.y + offset.y }
643
+ }
644
+
645
+ for (const node of Object.values(graph.nodes)) {
646
+ const position = resolvePosition(node.id)
647
+ allNodes.push({
648
+ id: ns(flowKey, node.id),
649
+ type: 'flowNode',
650
+ position,
651
+ draggable: true,
652
+ data: {
653
+ node,
654
+ liveCount: liveCounts[node.id] ?? 0,
655
+ isStart: node.id === graph.startNodeId,
656
+ isSelected: editingRef?.flowKey === flowKey && editingRef?.nodeId === node.id,
657
+ isDetached: node.id !== graph.startNodeId && !connectedTargets.has(node.id),
658
+ issues: flowIssues,
659
+ labels,
660
+ onSelect: (nodeId: string) => setEditingRef({ flowKey, nodeId }),
661
+ } satisfies FlowNodeCardData,
662
+ })
663
+
664
+ // Um portal por (nó de origem, fluxo alvo único) — só para saltos cujo fluxo alvo AINDA
665
+ // não está mesclado no canvas (hoje raro, já que abrir um fluxo já mescla tudo que ele
666
+ // referencia — mas serve de rede de segurança pra um fluxo criado depois da fusão
667
+ // inicial); se já estiver mesclado, buildAllEdges liga direto ao nó real.
668
+ const crossFlowTargets = [...new Set(targetsOf(node).map((edge) => edge.target).filter(isCrossFlowTarget))]
669
+ crossFlowTargets.forEach((target, index) => {
670
+ const targetFlowKey = crossFlowKey(target)
671
+ if (openFlows.some((flow) => flow.key === targetFlowKey)) return
672
+ allNodes.push({
673
+ id: ns(flowKey, portalNodeId(node.id, target)),
674
+ type: 'flowPortal',
675
+ draggable: false,
676
+ selectable: false,
677
+ position: { x: position.x + 320, y: position.y + index * 70 },
678
+ data: {
679
+ label: graphs?.[targetFlowKey]?.label ?? targetFlowKey,
680
+ onNavigate: () => mergeFlow(targetFlowKey, { flowKey, nodeId: node.id }),
681
+ } satisfies FlowPortalNodeData,
682
+ })
683
+ })
684
+ }
685
+
686
+ // Moldura decorativa por trás de cada cadeia de perguntas lineares que alimenta uma ação —
687
+ // puramente derivada da topologia do grafo, sem precisar marcar manualmente quais perguntas
688
+ // "pertencem" ao cálculo.
689
+ for (const chain of findCollectionChains(graph)) {
690
+ const chainNodeIds = [...chain.nodeIds, chain.actionNodeId]
691
+ const positions = chainNodeIds.map((id) => resolvePosition(id))
692
+ const minX = Math.min(...positions.map((point) => point.x))
693
+ const maxX = Math.max(...positions.map((point) => point.x)) + NODE_CARD_WIDTH
694
+ const minY = Math.min(...positions.map((point) => point.y))
695
+ const maxY = Math.max(...positions.map((point) => point.y)) + estimateNodeHeight(graph.nodes[chain.actionNodeId]!)
696
+ allNodes.push({
697
+ id: ns(flowKey, `__chain__${chain.actionNodeId}`),
698
+ type: 'flowGroupFrame',
699
+ draggable: false,
700
+ selectable: false,
701
+ zIndex: -1,
702
+ position: { x: minX - CHAIN_FRAME_PADDING, y: minY - CHAIN_FRAME_PADDING - 24 },
703
+ style: {
704
+ width: maxX - minX + CHAIN_FRAME_PADDING * 2,
705
+ height: maxY - minY + CHAIN_FRAME_PADDING * 2 + 24,
706
+ },
707
+ data: {
708
+ label: labels.collectionChain.feeds(nodeLabel(graph.nodes[chain.actionNodeId], labels)),
709
+ } satisfies FlowGroupFrameData,
710
+ })
711
+ }
712
+
713
+ // Cabeçalho flutuante só para fluxos mesclados (o primário já tem controles na barra
714
+ // de cima — paleta, organizar, publicar, excluir).
715
+ if (!isPrimary) {
716
+ const startPosition = resolvePosition(graph.startNodeId)
717
+ allNodes.push({
718
+ id: ns(flowKey, '__group_header__'),
719
+ type: 'flowGroupHeader',
720
+ draggable: false,
721
+ selectable: false,
722
+ position: { x: startPosition.x, y: startPosition.y - 60 },
723
+ data: {
724
+ label: graph.label,
725
+ onFocus: () => focusFlow(flowKey),
726
+ onClose: () => closeFlow(flowKey),
727
+ } satisfies FlowGroupHeaderData,
728
+ })
729
+ }
730
+ }
731
+ return allNodes
732
+ }, [
733
+ openFlows,
734
+ workingGraphs,
735
+ mergedPositions,
736
+ livePositions,
737
+ issuesByFlow,
738
+ primaryFlowKey,
739
+ rootFlowKey,
740
+ editingRef,
741
+ graphs,
742
+ mergeFlow,
743
+ focusFlow,
744
+ closeFlow,
745
+ labels,
746
+ ])
747
+
748
+ const edges = useMemo(
749
+ () => buildAllEdges(openFlows, workingGraphs, rootFlowKey, livePositions),
750
+ [openFlows, workingGraphs, rootFlowKey, livePositions],
751
+ )
752
+
753
+ useEffect(() => {
754
+ setRfNodes(derivedNodes)
755
+ for (const node of derivedNodes) {
756
+ if (node.type === 'flowNode') renderedPositionsRef.current.set(node.id, node.position)
757
+ }
758
+ }, [derivedNodes])
759
+
760
+ // Nó recém-criado ainda não tem ligação, e o layout manda todo órfão para uma faixa abaixo de
761
+ // tudo — num canvas com vários fluxos mesclados isso cai longe da área visível, e o card parece
762
+ // ter sumido. Espera ele existir no canvas e leva a viewport até lá.
763
+ useEffect(() => {
764
+ if (!pendingFocusNodeId || !flowInstance) return
765
+ const target = rfNodes.find((node) => node.id === pendingFocusNodeId)
766
+ if (!target) return
767
+ flowInstance.setCenter(target.position.x + NODE_CARD_WIDTH / 2, target.position.y, { zoom: 1, duration: 400 })
768
+ setPendingFocusNodeId(null)
769
+ }, [pendingFocusNodeId, flowInstance, rfNodes])
770
+
771
+ const onNodesChange = useCallback((changes: NodeChange[]) => {
772
+ setRfNodes((current) => applyNodeChanges(changes, current))
773
+ }, [])
774
+
775
+ const onNodeDragStop = useCallback(
776
+ (_event: unknown, node: Node) => {
777
+ renderedPositionsRef.current.set(node.id, node.position)
778
+ const { flowKey, nodeId } = parseNs(node.id)
779
+ const openFlow = openFlows.find((flow) => flow.key === flowKey)
780
+ if (!openFlow) return
781
+ const localPosition = { x: node.position.x - openFlow.offset.x, y: node.position.y - openFlow.offset.y }
782
+ updateFlow(flowKey, (graph) =>
783
+ graph.nodes[nodeId]
784
+ ? { ...graph, nodes: { ...graph.nodes, [nodeId]: { ...graph.nodes[nodeId]!, position: localPosition } } }
785
+ : graph,
786
+ )
787
+ },
788
+ [openFlows, updateFlow],
789
+ )
790
+
791
+ const onConnect = useCallback(
792
+ (connection: Connection) => {
793
+ const { source, sourceHandle, target } = connection
794
+ if (!source || !target || source === target) return
795
+ const sourceRef = parseNs(source)
796
+ const targetRef = parseNs(target)
797
+
798
+ // Conectar num nó de outro fluxo só faz sentido se for o nó inicial dele — vira um salto
799
+ // "flow:<key>" (o motor do bot não sabe pular pra um nó específico de outro fluxo, só
800
+ // pro início). Conectar num nó do meio de outro fluxo é ignorado silenciosamente.
801
+ let targetValue: string
802
+ if (targetRef.flowKey === sourceRef.flowKey) {
803
+ targetValue = targetRef.nodeId
804
+ } else {
805
+ const targetGraph = workingGraphs[targetRef.flowKey]
806
+ if (!targetGraph || targetGraph.startNodeId !== targetRef.nodeId) return
807
+ targetValue = `${CROSS_FLOW_PREFIX}${targetRef.flowKey}`
808
+ }
809
+
810
+ updateFlow(sourceRef.flowKey, (graph) => {
811
+ const node = graph.nodes[sourceRef.nodeId]
812
+ if (!node) return graph
813
+ const handle = sourceHandle ?? 'next'
814
+ const currentByAnswer = typeof node.next === 'object' && node.next ? node.next.byAnswer : {}
815
+ const currentDefault = typeof node.next === 'object' && node.next ? node.next.default : ''
816
+ const updatedNode: FlowNodeData =
817
+ handle === 'next'
818
+ ? { ...node, next: targetValue }
819
+ : handle === '__default'
820
+ ? { ...node, next: { byAnswer: currentByAnswer, default: targetValue } }
821
+ : { ...node, next: { byAnswer: { ...currentByAnswer, [handle]: targetValue }, default: currentDefault } }
822
+ return { ...graph, nodes: { ...graph.nodes, [sourceRef.nodeId]: updatedNode } }
823
+ })
824
+ },
825
+ [workingGraphs, updateFlow],
826
+ )
827
+
828
+ function handleAddNode(spec: NewNodeSpec) {
829
+ if (!primaryGraph) return
830
+ const newNode = newNodeFromSpec(spec, new Set(Object.keys(primaryGraph.nodes)))
831
+ const maxY = Math.max(0, ...Object.values(primaryGraph.nodes).map((node) => node.position?.y ?? 0))
832
+ newNode.position = { x: 0, y: maxY + 170 }
833
+ updateFlow(primaryFlowKey, (graph) => ({ ...graph, nodes: { ...graph.nodes, [newNode.id]: newNode } }))
834
+ setEditingRef({ flowKey: primaryFlowKey, nodeId: newNode.id })
835
+ setPendingFocusNodeId(ns(primaryFlowKey, newNode.id))
836
+ }
837
+
838
+ function handleNodePanelChange(updated: FlowNodeData) {
839
+ if (!editingRef) return
840
+ updateFlow(editingRef.flowKey, (graph) => ({ ...graph, nodes: { ...graph.nodes, [updated.id]: updated } }))
841
+ setEditingRef(null)
842
+ }
843
+
844
+ function handleNodeDelete(nodeId: string) {
845
+ if (!editingRef) return
846
+ updateFlow(editingRef.flowKey, (graph) => ({ ...graph, nodes: removeNodeAndCleanRefs(graph.nodes, nodeId) }))
847
+ setEditingRef(null)
848
+ }
849
+
850
+ // Único caminho que move card sozinho — as posições são estáveis no resto do tempo, então
851
+ // reorganizar virou uma ação explícita, inclusive com vários fluxos mesclados no canvas.
852
+ function handleOrganize() {
853
+ if (!primaryGraph) return
854
+ renderedPositionsRef.current.clear()
855
+
856
+ if (isMerged) {
857
+ const positions = computeMergedLayout(openFlows, workingGraphs, primaryFlowKey)
858
+ for (const { key, offset } of openFlows) {
859
+ updateFlow(key, (graph) => ({
860
+ ...graph,
861
+ nodes: Object.fromEntries(
862
+ Object.entries(graph.nodes).map(([id, node]) => {
863
+ const position = positions.get(ns(key, id))
864
+ return [
865
+ id,
866
+ position ? { ...node, position: { x: position.x - offset.x, y: position.y - offset.y } } : node,
867
+ ]
868
+ }),
869
+ ),
870
+ }))
871
+ }
872
+ return
873
+ }
874
+
875
+ const positions = computeAutoLayout(primaryGraph)
876
+ updateFlow(primaryFlowKey, (graph) => ({
877
+ ...graph,
878
+ nodes: Object.fromEntries(
879
+ Object.entries(graph.nodes).map(([id, node]) => [id, { ...node, position: positions[id] ?? node.position }]),
880
+ ),
881
+ }))
882
+ }
883
+
884
+ // Descarta o rascunho local e volta ao que está publicado. Sem isso, a única saída de uma
885
+ // edição indesejada era recarregar a página no susto — e recarregar também perde o resto.
886
+ function handleDiscardChanges() {
887
+ if (!graphs || !isDirty) return
888
+ if (!window.confirm(labels.workspace.discardConfirm)) return
889
+ setWorkingGraphs((prev) => {
890
+ const next = { ...prev }
891
+ for (const key of dirtyKeys) {
892
+ const published = graphs[key]
893
+ if (published) next[key] = published
894
+ }
895
+ return next
896
+ })
897
+ renderedPositionsRef.current.clear()
898
+ setEditingRef(null)
899
+ }
900
+
901
+ async function handlePublish() {
902
+ if (dirtyKeys.length === 0 || errorCount > 0) return
903
+ setSaveState('saving')
904
+ setSaveErrorMessage(undefined)
905
+ try {
906
+ await Promise.all(dirtyKeys.map((key) => api.saveGraph(key, workingGraphs[key]!)))
907
+ await reloadGraphs()
908
+ setSaveState('success')
909
+ setTimeout(() => setSaveState('idle'), 3000)
910
+ } catch (error) {
911
+ setSaveState('error')
912
+ setSaveErrorMessage(extractErrorMessage(error))
913
+ }
914
+ }
915
+
916
+ async function handleCreateFlow() {
917
+ const createFlow = api.createFlow
918
+ if (!createFlow) return
919
+ setFlowMutationState({ pending: true })
920
+ try {
921
+ await createFlow({
922
+ key: newFlow.key,
923
+ label: newFlow.label,
924
+ showInMenu: newFlow.showInMenu,
925
+ ...(newFlow.showInMenu ? { menuOptionLabel: newFlow.menuOptionLabel || newFlow.label } : {}),
926
+ })
927
+ await reloadGraphs()
928
+ setOpenFlows([{ key: newFlow.key, offset: { x: 0, y: 0 } }])
929
+ setShowCreateDialog(false)
930
+ setNewFlow({ key: '', label: '', showInMenu: false, menuOptionLabel: '' })
931
+ setFlowMutationState({ pending: false })
932
+ } catch (error) {
933
+ setFlowMutationState({ pending: false, error: extractErrorMessage(error) ?? labels.flowManager.createError })
934
+ }
935
+ }
936
+
937
+ async function handleDeleteFlow() {
938
+ const deleteFlow = api.deleteFlow
939
+ if (!deleteFlow || !primaryGraph) return
940
+ setFlowMutationState({ pending: true })
941
+ try {
942
+ await deleteFlow(primaryGraph.key)
943
+ const reloaded = await reloadGraphs()
944
+ setOpenFlows(reloaded ? autoMergeAll(rootFlowKey, reloaded) : [{ key: rootFlowKey, offset: { x: 0, y: 0 } }])
945
+ setShowDeleteDialog(false)
946
+ setFlowMutationState({ pending: false })
947
+ } catch (error) {
948
+ setFlowMutationState({ pending: false, error: extractErrorMessage(error) ?? labels.flowManager.deleteError })
949
+ }
950
+ }
951
+
952
+ const editingGraph = editingRef ? workingGraphs[editingRef.flowKey] : null
953
+ const editingNode = editingRef && editingGraph ? editingGraph.nodes[editingRef.nodeId] : null
954
+ const otherFlows = useMemo(
955
+ () =>
956
+ Object.values(graphs ?? {})
957
+ .filter((graph) => graph.key !== editingRef?.flowKey)
958
+ .map((graph) => ({ key: graph.key, label: graph.label })),
959
+ [graphs, editingRef?.flowKey],
960
+ )
961
+ const keyIsValid = FLOW_KEY_PATTERN.test(newFlow.key)
962
+ const canCreateFlow = Boolean(api.createFlow)
963
+ const canDeleteFlow = Boolean(api.deleteFlow) && primaryFlowKey !== rootFlowKey
964
+
965
+ return (
966
+ <div className={`space-y-4 h-full flex flex-col ${className ?? ''}`}>
967
+ <div className="flex items-center justify-between flex-wrap gap-3">
968
+ <div>
969
+ <h2 className="text-2xl font-bold text-gray-900 dark:text-gray-100">{labels.workspace.title}</h2>
970
+ <p className="text-gray-500 dark:text-gray-400 text-sm mt-1">{labels.workspace.subtitle}</p>
971
+ </div>
972
+ <div className="flex items-center gap-3">
973
+ {saveState === 'success' && <span className="text-sm text-green-600">{labels.workspace.saveSuccess}</span>}
974
+ {saveState === 'error' && (
975
+ <span className="text-sm text-red-600">{saveErrorMessage ?? labels.workspace.saveError}</span>
976
+ )}
977
+ <button
978
+ type="button"
979
+ onClick={() => setViewMode((mode) => (mode === 'map' ? 'detail' : 'map'))}
980
+ className={OUTLINE_BUTTON}
981
+ >
982
+ {viewMode === 'map' ? <Workflow size={14} aria-hidden="true" /> : <MapIcon size={14} aria-hidden="true" />}
983
+ {viewMode === 'map' ? labels.flowMap.toggleToDetail : labels.flowMap.toggleToMap}
984
+ </button>
985
+ {viewMode === 'detail' && (
986
+ <>
987
+ <button
988
+ type="button"
989
+ onClick={handleOrganize}
990
+ className={OUTLINE_BUTTON}
991
+ title={labels.workspace.organizeTooltip}
992
+ disabled={!primaryGraph}
993
+ >
994
+ <LayoutGrid size={14} aria-hidden="true" /> {labels.workspace.organize}
995
+ </button>
996
+ <button
997
+ type="button"
998
+ onClick={handleDiscardChanges}
999
+ className={OUTLINE_BUTTON}
1000
+ title={labels.workspace.discardTooltip}
1001
+ disabled={!isDirty || saveState === 'saving'}
1002
+ >
1003
+ <Undo2 size={14} aria-hidden="true" /> {labels.workspace.discardChanges}
1004
+ </button>
1005
+ <button
1006
+ type="button"
1007
+ onClick={() => void handlePublish()}
1008
+ className={PRIMARY_BUTTON}
1009
+ disabled={!isDirty || errorCount > 0 || saveState === 'saving'}
1010
+ >
1011
+ <Save size={14} aria-hidden="true" />
1012
+ {saveState === 'saving' ? labels.workspace.saving : labels.workspace.saveGraph}
1013
+ </button>
1014
+ </>
1015
+ )}
1016
+ </div>
1017
+ </div>
1018
+
1019
+ {viewMode === 'detail' && (
1020
+ <div className="flex items-center justify-between gap-2 flex-wrap">
1021
+ <div className="flex items-center gap-2 flex-wrap">
1022
+ {graphs &&
1023
+ Object.values(graphs).map((graph) => (
1024
+ <button
1025
+ key={graph.key}
1026
+ type="button"
1027
+ onClick={() => focusFlow(graph.key)}
1028
+ className={`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${
1029
+ primaryFlowKey === graph.key
1030
+ ? 'bg-blue-600 text-white border-blue-600'
1031
+ : 'bg-white dark:bg-gray-800 text-gray-600 dark:text-gray-300 border-gray-200 dark:border-gray-700 hover:border-blue-300'
1032
+ }`}
1033
+ >
1034
+ {graph.label}
1035
+ </button>
1036
+ ))}
1037
+ {canCreateFlow && (
1038
+ <button
1039
+ type="button"
1040
+ onClick={() => {
1041
+ setFlowMutationState({ pending: false })
1042
+ setShowCreateDialog(true)
1043
+ }}
1044
+ className="inline-flex items-center gap-1 px-3 py-1.5 rounded-full text-xs font-medium border border-dashed border-gray-300 dark:border-gray-600 text-gray-500 dark:text-gray-400 hover:border-blue-400 hover:text-blue-600"
1045
+ >
1046
+ <Plus size={12} aria-hidden="true" /> {labels.flowManager.newFlow}
1047
+ </button>
1048
+ )}
1049
+ </div>
1050
+ <div className="flex items-center gap-2">
1051
+ {primaryGraph && (
1052
+ <FlowPalette
1053
+ onAdd={handleAddNode}
1054
+ labels={labels}
1055
+ {...(actionOptions ? { actionOptions: [...actionOptions] } : {})}
1056
+ />
1057
+ )}
1058
+ {primaryGraph && canDeleteFlow && (
1059
+ <button
1060
+ type="button"
1061
+ onClick={() => {
1062
+ setFlowMutationState({ pending: false })
1063
+ setShowDeleteDialog(true)
1064
+ }}
1065
+ className="inline-flex items-center gap-1.5 rounded-lg border border-red-200 dark:border-red-900 px-3 py-1.5 text-xs font-medium text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-950/30"
1066
+ >
1067
+ <Trash2 size={13} aria-hidden="true" /> {labels.flowManager.deleteFlow}
1068
+ </button>
1069
+ )}
1070
+ </div>
1071
+ </div>
1072
+ )}
1073
+
1074
+ {viewMode === 'detail' && (errorCount > 0 || warningCount > 0) && (
1075
+ <div className="flex items-center gap-4 rounded-lg border border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-800/60 px-3 py-2 text-xs">
1076
+ <span className="font-medium text-gray-600 dark:text-gray-300">{labels.validation.title}:</span>
1077
+ {errorCount > 0 && (
1078
+ <span className="flex items-center gap-1 text-red-600 dark:text-red-400 font-medium">
1079
+ <AlertCircle size={13} aria-hidden="true" /> {labels.validation.errors(errorCount)}
1080
+ </span>
1081
+ )}
1082
+ {warningCount > 0 && (
1083
+ <span className="flex items-center gap-1 text-amber-600 dark:text-amber-400">
1084
+ <AlertTriangle size={13} aria-hidden="true" /> {labels.validation.warnings(warningCount)}
1085
+ </span>
1086
+ )}
1087
+ </div>
1088
+ )}
1089
+
1090
+ <div className="flex-1 rounded-xl border border-gray-200 dark:border-gray-700 overflow-hidden relative">
1091
+ {loadState === 'loading' && <p className="text-center text-gray-400 py-12">{labels.workspace.loading}</p>}
1092
+ {loadState === 'error' && <p className="text-center text-red-500 py-12">{labels.workspace.loadError}</p>}
1093
+ {loadState === 'ready' && graphs && viewMode === 'map' && (
1094
+ <FlowMapCanvas
1095
+ graphs={graphs}
1096
+ rootKey={rootFlowKey}
1097
+ labels={labels}
1098
+ onOpenFlow={(key) => {
1099
+ focusFlow(key)
1100
+ setViewMode('detail')
1101
+ }}
1102
+ />
1103
+ )}
1104
+ {loadState === 'ready' && viewMode === 'detail' && primaryGraph && (
1105
+ <ReactFlow
1106
+ nodes={rfNodes}
1107
+ edges={edges}
1108
+ nodeTypes={RF_NODE_TYPES}
1109
+ onNodesChange={onNodesChange}
1110
+ onNodeDragStop={onNodeDragStop}
1111
+ onConnect={onConnect}
1112
+ onInit={setFlowInstance}
1113
+ fitView
1114
+ proOptions={{ hideAttribution: true }}
1115
+ colorMode={isDark ? 'dark' : 'light'}
1116
+ >
1117
+ <Background color={isDark ? BACKGROUND_COLOR_DARK : BACKGROUND_COLOR_LIGHT} />
1118
+ <Controls />
1119
+ <MiniMap pannable zoomable className="!bg-white dark:!bg-gray-800" />
1120
+ </ReactFlow>
1121
+ )}
1122
+ </div>
1123
+
1124
+ {/* `key` por nó: o painel guarda um rascunho local em estado, e sem remontar ao trocar de nó
1125
+ selecionado ele seguia mostrando (e salvando) os campos do nó anterior. */}
1126
+ {editingNode && editingGraph && (
1127
+ <FlowNodePanel
1128
+ key={`${editingRef?.flowKey}:${editingRef?.nodeId}`}
1129
+ graph={editingGraph}
1130
+ node={editingNode}
1131
+ issues={editingRef ? (issuesByFlow[editingRef.flowKey] ?? []) : []}
1132
+ otherFlows={otherFlows}
1133
+ labels={labels}
1134
+ onClose={() => setEditingRef(null)}
1135
+ onChange={handleNodePanelChange}
1136
+ onDelete={handleNodeDelete}
1137
+ {...(renderMediaPicker ? { renderMediaPicker } : {})}
1138
+ />
1139
+ )}
1140
+
1141
+ {showCreateDialog && canCreateFlow && (
1142
+ <FlowDialog title={labels.flowManager.createTitle} onClose={() => setShowCreateDialog(false)}>
1143
+ <div className="space-y-3">
1144
+ <div>
1145
+ <label className="text-xs font-medium text-gray-500 dark:text-gray-400">{labels.flowManager.label}</label>
1146
+ <input
1147
+ value={newFlow.label}
1148
+ onChange={(event) => setNewFlow((prev) => ({ ...prev, label: event.target.value }))}
1149
+ className={`mt-1 ${DIALOG_INPUT}`}
1150
+ />
1151
+ </div>
1152
+ <div>
1153
+ <label className="text-xs font-medium text-gray-500 dark:text-gray-400">{labels.flowManager.key}</label>
1154
+ <input
1155
+ value={newFlow.key}
1156
+ onChange={(event) => setNewFlow((prev) => ({ ...prev, key: event.target.value.toLowerCase() }))}
1157
+ className={`mt-1 ${DIALOG_INPUT}`}
1158
+ />
1159
+ <p className="text-[11px] text-gray-400 mt-1">
1160
+ {newFlow.key && !keyIsValid ? labels.flowManager.keyInvalid : labels.flowManager.keyHint}
1161
+ </p>
1162
+ </div>
1163
+ <label className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-200">
1164
+ <input
1165
+ type="checkbox"
1166
+ checked={newFlow.showInMenu}
1167
+ onChange={(event) => setNewFlow((prev) => ({ ...prev, showInMenu: event.target.checked }))}
1168
+ />
1169
+ {labels.flowManager.showInMenu}
1170
+ </label>
1171
+ {newFlow.showInMenu && (
1172
+ <div>
1173
+ <label className="text-xs font-medium text-gray-500 dark:text-gray-400">
1174
+ {labels.flowManager.menuOptionLabel}
1175
+ </label>
1176
+ <input
1177
+ value={newFlow.menuOptionLabel}
1178
+ onChange={(event) => setNewFlow((prev) => ({ ...prev, menuOptionLabel: event.target.value }))}
1179
+ placeholder={newFlow.label}
1180
+ className={`mt-1 ${DIALOG_INPUT}`}
1181
+ />
1182
+ </div>
1183
+ )}
1184
+ {flowMutationState.error && <p className="text-xs text-red-600">{flowMutationState.error}</p>}
1185
+ </div>
1186
+ <div className="flex justify-end gap-2 mt-4">
1187
+ <button type="button" className={OUTLINE_BUTTON} onClick={() => setShowCreateDialog(false)}>
1188
+ {labels.nodePanel.cancel}
1189
+ </button>
1190
+ <button
1191
+ type="button"
1192
+ className={PRIMARY_BUTTON}
1193
+ onClick={() => void handleCreateFlow()}
1194
+ disabled={!keyIsValid || !newFlow.label || flowMutationState.pending}
1195
+ >
1196
+ {flowMutationState.pending ? labels.flowManager.creating : labels.flowManager.create}
1197
+ </button>
1198
+ </div>
1199
+ </FlowDialog>
1200
+ )}
1201
+
1202
+ {showDeleteDialog && canDeleteFlow && (
1203
+ <FlowDialog title={labels.flowManager.deleteFlow} onClose={() => setShowDeleteDialog(false)}>
1204
+ <p className="text-sm text-gray-600 dark:text-gray-300">
1205
+ {primaryGraph ? labels.flowManager.deleteConfirm(primaryGraph.label) : ''}
1206
+ </p>
1207
+ {flowMutationState.error && <p className="text-xs text-red-600 mt-2">{flowMutationState.error}</p>}
1208
+ <div className="flex justify-end gap-2 mt-4">
1209
+ <button type="button" className={OUTLINE_BUTTON} onClick={() => setShowDeleteDialog(false)}>
1210
+ {labels.nodePanel.cancel}
1211
+ </button>
1212
+ <button
1213
+ type="button"
1214
+ className="inline-flex items-center gap-1.5 rounded-lg bg-red-600 px-3 py-1.5 text-xs font-medium text-white hover:bg-red-700 disabled:opacity-40"
1215
+ onClick={() => void handleDeleteFlow()}
1216
+ disabled={flowMutationState.pending}
1217
+ >
1218
+ <Trash2 size={13} aria-hidden="true" /> {labels.flowManager.deleteFlow}
1219
+ </button>
1220
+ </div>
1221
+ </FlowDialog>
1222
+ )}
1223
+ </div>
1224
+ )
1225
+ }
1226
+
1227
+ // Diálogo próprio em vez de depender do `Dialog` do produto: o pacote roda em três apps com
1228
+ // bibliotecas de UI diferentes, e exigir uma delas transformaria a tela composta num acoplamento.
1229
+ function FlowDialog({
1230
+ title,
1231
+ onClose,
1232
+ children,
1233
+ }: {
1234
+ title: string
1235
+ onClose: () => void
1236
+ children: ReactNode
1237
+ }) {
1238
+ return (
1239
+ <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 px-4">
1240
+ <div className="absolute inset-0" onClick={onClose} aria-hidden="true" />
1241
+ <div
1242
+ role="dialog"
1243
+ aria-modal="true"
1244
+ aria-label={title}
1245
+ className="relative w-full max-w-md rounded-2xl bg-white dark:bg-gray-800 p-5 shadow-xl"
1246
+ >
1247
+ <h3 className="text-base font-semibold text-gray-900 dark:text-gray-100 mb-3">{title}</h3>
1248
+ {children}
1249
+ </div>
1250
+ </div>
1251
+ )
1252
+ }