@gntik-ai/blocks 0.9.0 → 0.11.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 (162) hide show
  1. package/dist/index.d.ts +426 -55
  2. package/dist/index.js +2275 -639
  3. package/dist/index.js.map +1 -1
  4. package/package.json +6 -6
  5. package/src/auth/ForgotPasswordForm/ForgotPasswordForm.labels.test.tsx +179 -0
  6. package/src/auth/ForgotPasswordForm/ForgotPasswordForm.tsx +59 -24
  7. package/src/auth/ForgotPasswordForm/block.meta.ts +22 -1
  8. package/src/auth/ForgotPasswordForm/examples/Labels.tsx +29 -0
  9. package/src/auth/MfaChallenge/MfaChallenge.labels.test.tsx +139 -0
  10. package/src/auth/MfaChallenge/MfaChallenge.tsx +69 -23
  11. package/src/auth/MfaChallenge/block.meta.ts +29 -1
  12. package/src/auth/MfaChallenge/examples/Labels.tsx +28 -0
  13. package/src/auth/ResetPasswordForm/ResetPasswordForm.labels.test.tsx +104 -0
  14. package/src/auth/ResetPasswordForm/ResetPasswordForm.tsx +42 -15
  15. package/src/auth/ResetPasswordForm/block.meta.ts +17 -1
  16. package/src/auth/ResetPasswordForm/examples/Labels.tsx +28 -0
  17. package/src/auth/SignInForm/SignInForm.labels.test.tsx +137 -0
  18. package/src/auth/SignInForm/SignInForm.tsx +43 -16
  19. package/src/auth/SignInForm/block.meta.ts +22 -1
  20. package/src/auth/SignInForm/examples/Labels.tsx +29 -0
  21. package/src/auth/SignUpForm/SignUpForm.labels.test.tsx +217 -0
  22. package/src/auth/SignUpForm/SignUpForm.tsx +65 -26
  23. package/src/auth/SignUpForm/block.meta.ts +27 -1
  24. package/src/auth/SignUpForm/examples/Labels.tsx +29 -0
  25. package/src/auth/SsoButtons/SsoButtons.labels.test.tsx +30 -0
  26. package/src/auth/SsoButtons/SsoButtons.tsx +10 -2
  27. package/src/auth/SsoButtons/block.meta.ts +8 -1
  28. package/src/auth/SsoButtons/examples/Labels.tsx +24 -0
  29. package/src/auth/shared.i18n.test.tsx +71 -0
  30. package/src/auth/shared.tsx +48 -11
  31. package/src/billing/CostBreakdown/CostBreakdown.test.tsx +10 -0
  32. package/src/billing/CostBreakdown/CostBreakdown.tsx +50 -43
  33. package/src/billing/SpendVsBudget/SpendVsBudget.test.tsx +10 -0
  34. package/src/billing/SpendVsBudget/SpendVsBudget.tsx +35 -31
  35. package/src/builders/FlowBuilder/FlowBuilder.test.tsx +237 -2
  36. package/src/builders/FlowBuilder/FlowBuilder.tsx +101 -29
  37. package/src/builders/FlowBuilder/block.meta.ts +1 -1
  38. package/src/builders/FlowBuilder/connections.ts +30 -12
  39. package/src/builders/FlowBuilder/examples/ControlledGraph.tsx +8 -0
  40. package/src/builders/FlowBuilder/graph-state.ts +78 -0
  41. package/src/builders/LogViewer/LogViewer.labels.test.tsx +90 -0
  42. package/src/builders/LogViewer/LogViewer.levels.test.tsx +49 -0
  43. package/src/builders/LogViewer/LogViewer.tsx +72 -18
  44. package/src/builders/LogViewer/LogViewer.wrap.test.tsx +181 -0
  45. package/src/builders/LogViewer/block.meta.ts +19 -1
  46. package/src/builders/LogViewer/examples/Spanish.tsx +30 -0
  47. package/src/builders/LogViewer/examples/Wrap.tsx +62 -0
  48. package/src/builders/LogViewer/use-wrapped-log-rows.ts +42 -0
  49. package/src/data-display/ChartCard/ChartCard.locale.test.tsx +15 -0
  50. package/src/data-display/ChartCard/ChartCard.test.tsx +9 -0
  51. package/src/data-display/ChartCard/ChartCard.tsx +81 -67
  52. package/src/data-display/ChartCard/block.meta.ts +1 -1
  53. package/src/data-display/DescriptionListCard/DescriptionListCard.labels.test.tsx +73 -0
  54. package/src/data-display/DescriptionListCard/DescriptionListCard.options.test.tsx +64 -0
  55. package/src/data-display/DescriptionListCard/DescriptionListCard.tsx +74 -23
  56. package/src/data-display/DescriptionListCard/block.meta.ts +11 -1
  57. package/src/data-display/DescriptionListCard/examples/Spanish.tsx +29 -0
  58. package/src/feedback/EmptyStates/EmptyStates.labels.test.tsx +185 -0
  59. package/src/feedback/EmptyStates/EmptyStates.tsx +101 -30
  60. package/src/feedback/EmptyStates/NoAccessEmpty.options.test.tsx +38 -0
  61. package/src/feedback/EmptyStates/block.meta.ts +73 -1
  62. package/src/feedback/EmptyStates/examples/Spanish.tsx +48 -0
  63. package/src/feedback/ErrorPanel/ErrorPanel.labels.test.tsx +99 -0
  64. package/src/feedback/ErrorPanel/ErrorPanel.tsx +38 -9
  65. package/src/feedback/ErrorPanel/block.meta.ts +19 -1
  66. package/src/feedback/ErrorPanel/examples/Spanish.tsx +30 -0
  67. package/src/feedback/InlineCallout/InlineCallout.labels.test.tsx +62 -0
  68. package/src/feedback/InlineCallout/InlineCallout.tsx +22 -9
  69. package/src/feedback/InlineCallout/block.meta.ts +9 -1
  70. package/src/feedback/InlineCallout/examples/Spanish.tsx +19 -0
  71. package/src/feedback/Skeletons/Skeletons.labels.test.tsx +24 -0
  72. package/src/forms/CreateApiKeyDialog/CreateApiKeyDialog.labels.test.tsx +115 -0
  73. package/src/forms/CreateApiKeyDialog/CreateApiKeyDialog.tsx +63 -21
  74. package/src/forms/CreateApiKeyDialog/block.meta.ts +22 -1
  75. package/src/forms/CreateApiKeyDialog/examples/Labels.tsx +29 -0
  76. package/src/forms/CredentialDisclosureDialog/CredentialDisclosureDialog.labels.test.tsx +165 -0
  77. package/src/forms/CredentialDisclosureDialog/CredentialDisclosureDialog.tsx +31 -8
  78. package/src/forms/CredentialDisclosureDialog/SecretCopy.tsx +16 -8
  79. package/src/forms/CredentialDisclosureDialog/block.meta.ts +19 -1
  80. package/src/forms/CredentialDisclosureDialog/examples/Labels.tsx +38 -0
  81. package/src/forms/DangerZone/ConfirmDestructiveDialog.tsx +17 -3
  82. package/src/forms/DangerZone/DangerZone.labels.test.tsx +87 -0
  83. package/src/forms/DangerZone/DangerZone.tsx +20 -5
  84. package/src/forms/DangerZone/block.meta.ts +10 -1
  85. package/src/forms/DangerZone/examples/Labels.tsx +29 -0
  86. package/src/forms/DateRangeFilter/DateRangeFilter.labels.test.tsx +52 -0
  87. package/src/forms/DateRangeFilter/DateRangeFilter.tsx +11 -3
  88. package/src/forms/DateRangeFilter/block.meta.ts +8 -1
  89. package/src/forms/DateRangeFilter/examples/Labels.tsx +28 -0
  90. package/src/forms/DialogWizard/DialogWizard.labels.test.tsx +37 -0
  91. package/src/forms/DialogWizard/DialogWizard.tsx +13 -2
  92. package/src/forms/DialogWizard/block.meta.ts +7 -1
  93. package/src/forms/DialogWizard/examples/Labels.tsx +39 -0
  94. package/src/forms/FileUploadPanel/FileUploadPanel.labels.test.tsx +126 -0
  95. package/src/forms/FileUploadPanel/FileUploadPanel.test.tsx +22 -1
  96. package/src/forms/FileUploadPanel/FileUploadPanel.tsx +85 -22
  97. package/src/forms/FileUploadPanel/block.meta.ts +22 -1
  98. package/src/forms/FileUploadPanel/examples/Labels.tsx +29 -0
  99. package/src/forms/FileUploadPanel/fixtures.ts +0 -12
  100. package/src/forms/FileUploadPanel/format-bytes.test.ts +8 -0
  101. package/src/forms/FormSection/FormSection.labels.test.tsx +37 -0
  102. package/src/forms/FormSection/FormSection.tsx +14 -3
  103. package/src/forms/FormSection/block.meta.ts +7 -1
  104. package/src/forms/FormSection/examples/Labels.tsx +27 -0
  105. package/src/forms/InviteMembersDialog/InviteMembersDialog.labels.test.tsx +87 -0
  106. package/src/forms/InviteMembersDialog/InviteMembersDialog.tsx +51 -16
  107. package/src/forms/InviteMembersDialog/block.meta.ts +20 -1
  108. package/src/forms/InviteMembersDialog/examples/Labels.tsx +28 -0
  109. package/src/forms/SettingsRow/SettingsRow.labels.test.tsx +33 -0
  110. package/src/forms/SettingsRow/SettingsRow.tsx +14 -3
  111. package/src/forms/SettingsRow/block.meta.ts +7 -1
  112. package/src/forms/SettingsRow/examples/Labels.tsx +27 -0
  113. package/src/forms/ValidationSummary/ValidationSummary.labels.test.tsx +47 -0
  114. package/src/forms/ValidationSummary/ValidationSummary.tsx +9 -3
  115. package/src/forms/ValidationSummary/block.meta.ts +6 -1
  116. package/src/forms/ValidationSummary/examples/Labels.tsx +24 -0
  117. package/src/forms/index.ts +5 -1
  118. package/src/forms/translated-content.tsx +12 -0
  119. package/src/page-chrome/PageHeader/PageHeader.labels.test.tsx +56 -0
  120. package/src/page-chrome/PageHeader/PageHeader.options.test.tsx +34 -0
  121. package/src/page-chrome/PageHeader/PageHeader.tsx +26 -5
  122. package/src/page-chrome/PageHeader/block.meta.ts +8 -1
  123. package/src/page-chrome/PageHeader/examples/Labels.tsx +16 -0
  124. package/src/page-chrome/PageHeader/examples/Spanish.tsx +11 -0
  125. package/src/scheduling/AgendaList/AgendaList.test.tsx +25 -0
  126. package/src/scheduling/AgendaList/AgendaList.tsx +7 -2
  127. package/src/scheduling/AgendaList/AgendaListLocale.test.tsx +11 -0
  128. package/src/scheduling/AgendaList/block.meta.ts +1 -1
  129. package/src/scheduling/AgendaList/examples/Locale.tsx +29 -0
  130. package/src/scheduling/MonthCalendar/MonthCalendar.test.tsx +111 -1
  131. package/src/scheduling/MonthCalendar/MonthCalendar.tsx +19 -9
  132. package/src/scheduling/MonthCalendar/block.meta.ts +1 -1
  133. package/src/scheduling/MonthCalendar/examples/Locale.tsx +19 -0
  134. package/src/scheduling/WeekCalendar/WeekCalendar.test.tsx +73 -2
  135. package/src/scheduling/WeekCalendar/WeekCalendar.tsx +26 -12
  136. package/src/scheduling/WeekCalendar/block.meta.ts +1 -1
  137. package/src/scheduling/WeekCalendar/examples/Locale.tsx +19 -0
  138. package/src/scheduling/shared/dates.test.ts +75 -0
  139. package/src/scheduling/shared/dates.ts +46 -22
  140. package/src/scheduling/shared/useSchedulingClock.ts +13 -0
  141. package/src/shell/GlobalSearch/GlobalSearch.test.tsx +12 -0
  142. package/src/shell/GlobalSearch/fixtures.ts +2 -2
  143. package/src/tables/DataTable/DataTable.cross-page-selection.test.tsx +322 -0
  144. package/src/tables/DataTable/DataTable.labels.test.tsx +74 -0
  145. package/src/tables/DataTable/DataTable.server-pagination.test.tsx +1 -1
  146. package/src/tables/DataTable/DataTable.single-select.test.tsx +47 -7
  147. package/src/tables/DataTable/DataTable.test.tsx +55 -0
  148. package/src/tables/DataTable/DataTable.tsx +134 -67
  149. package/src/tables/DataTable/block.meta.ts +21 -3
  150. package/src/tables/DataTable/data-table-props.ts +14 -5
  151. package/src/tables/DataTable/data-table-row.tsx +7 -3
  152. package/src/tables/DataTable/data-table-utils.ts +2 -0
  153. package/src/tables/DataTable/examples/client-selection.tsx +33 -0
  154. package/src/tables/DataTable/examples/paginated-single-selection.tsx +46 -0
  155. package/src/tables/DataTable/examples/server-pagination.tsx +55 -15
  156. package/src/tables/DataTable/labels.ts +4 -0
  157. package/src/tables/DataTable/selection-strip.tsx +31 -0
  158. package/src/tables/DataTable/single-selection.tsx +0 -7
  159. package/src/tables/DataTable/use-multiple-selection.ts +86 -0
  160. package/src/tables/PaginationFooter/PaginationFooter.i18n.test.tsx +26 -0
  161. package/src/test/OptInDefaults.test.tsx +27 -0
  162. package/src/test/fixtures/opt-in-defaults.json +10 -0
@@ -1,6 +1,6 @@
1
1
  import { useEffect, useRef, useState, useSyncExternalStore, type ReactNode } from 'react';
2
2
  import { Play } from '@gntik-ai/icons';
3
- import { FlowCanvas, useFlowState, type FlowNode, type FlowNodeData, type FlowNodeKind } from '@gntik-ai/flow';
3
+ import { FlowCanvas, type FlowCanvasProps, type FlowNode, type FlowNodeData, type FlowNodeKind } from '@gntik-ai/flow';
4
4
  import { Button, ResizablePanel, ResizablePanelGroup, ResizeHandle, cn } from '@gntik-ai/ui';
5
5
  import {
6
6
  builderConsole,
@@ -14,20 +14,51 @@ import {
14
14
  import type { FlowBuilderExtensions } from './extensions';
15
15
  import { useDecoratedNodes } from './decorated-nodes';
16
16
  import { useConnections } from './connections';
17
+ import { useBuilderGraph } from './graph-state';
17
18
  import { FlowProblems } from './problems';
18
19
  import { NodeInspector, NodePalette, RunConsole } from './parts';
19
20
 
20
21
  export type { ConsoleEntry, FlowEdge, PaletteItem } from './fixtures';
22
+ /** Shared starter graph for hosts that also need its value before the first edit. */
23
+ export { builderNodes, builderEdges } from './fixtures';
21
24
  /** Graph types re-exported so apps can type nodes without depending on @gntik-ai/flow. */
22
25
  export type { FlowNode, FlowNodeData, FlowNodeKind, FlowTone } from '@gntik-ai/flow';
23
26
 
24
27
  export type { FlowConnection, FlowConnectionRejection, FlowValidationIssue } from './extensions';
25
28
  export type { FlowNodeRenderer, FlowHandle, FlowNodeRenderProps } from '@gntik-ai/flow';
26
29
 
30
+ export interface FlowGraph<Kind extends string = FlowNodeKind> {
31
+ nodes: FlowNode<Kind | FlowNodeKind>[];
32
+ edges: FlowEdge[];
33
+ }
34
+
35
+ export interface FlowGraphChange {
36
+ type: 'add' | 'delete' | 'move' | 'connect' | 'update';
37
+ nodeIds: string[];
38
+ edgeIds: string[];
39
+ }
40
+
41
+ /** Persist graph content without canvas selection, drag or measurement state. */
42
+ export function cleanFlowGraph<Kind extends string>(graph: FlowGraph<Kind>): FlowGraph<Kind> {
43
+ return {
44
+ ...graph,
45
+ nodes: graph.nodes.map((original) => {
46
+ const node = { ...original };
47
+ delete node.selected;
48
+ delete node.dragging;
49
+ delete node.measured;
50
+ return node;
51
+ }),
52
+ };
53
+ }
54
+
27
55
  export interface FlowBuilderProps<Kind extends string = FlowNodeKind> extends FlowBuilderExtensions {
28
56
  title?: string;
29
57
  nodes?: FlowNode<Kind | FlowNodeKind>[];
30
58
  edges?: FlowEdge[];
59
+ /** Controlled graph content. Canvas selection, measurements and active drags stay local. */
60
+ graph?: FlowGraph<Kind>;
61
+ onGraphChange?: (graph: FlowGraph<Kind>, change: FlowGraphChange) => void;
31
62
  palette?: PaletteItem[];
32
63
  /**
33
64
  * Console output (controlled). Run and Clear then report the next list through
@@ -49,10 +80,7 @@ export interface FlowBuilderProps<Kind extends string = FlowNodeKind> extends Fl
49
80
  * of them) to log the real run; return nothing to log a simulated run. While a returned
50
81
  * promise is pending the Run button shows a loading state; a rejection is logged as an error.
51
82
  */
52
- onRun?: (graph: {
53
- nodes: FlowNode<Kind | FlowNodeKind>[];
54
- edges: FlowEdge[];
55
- }) => FlowRunResult | Promise<FlowRunResult>;
83
+ onRun?: (graph: FlowGraph<Kind>) => FlowRunResult | Promise<FlowRunResult>;
56
84
  className?: string;
57
85
  }
58
86
 
@@ -90,6 +118,8 @@ export function FlowBuilder<Kind extends string = FlowNodeKind>({
90
118
  title = 'Untitled flow',
91
119
  nodes: initialNodes = builderNodes,
92
120
  edges: initialEdges = builderEdges,
121
+ graph,
122
+ onGraphChange,
93
123
  palette = builderPalette,
94
124
  consoleEntries,
95
125
  defaultConsoleEntries = builderConsole,
@@ -111,17 +141,15 @@ export function FlowBuilder<Kind extends string = FlowNodeKind>({
111
141
  }: FlowBuilderProps<Kind>) {
112
142
  const runMode = mode === 'run';
113
143
  const root = useRef<HTMLElement>(null);
144
+ const flow = useRef<
145
+ Parameters<NonNullable<FlowCanvasProps<FlowNode<Kind | FlowNodeKind>, FlowEdge>['onInit']>>[0] | null
146
+ >(null);
114
147
  const wide = useIsWide();
115
148
  const panelAs = TitleTag === 'h2' ? 'h3' : TitleTag === 'h3' ? 'h4' : 'h5';
116
- const {
117
- nodes,
118
- edges,
119
- setNodes,
120
- setEdges,
121
- onNodesChange,
122
- onEdgesChange,
123
- onConnect: defaultConnect,
124
- } = useFlowState<FlowNode<Kind | FlowNodeKind>, FlowEdge>(initialNodes, initialEdges);
149
+ const { nodes, edges, setNodes, setEdges, onNodesChange, onEdgesChange } = useBuilderGraph<Kind>(
150
+ { nodes: initialNodes, edges: initialEdges },
151
+ graph,
152
+ );
125
153
  const [innerLog, setInnerLog] = useState<ConsoleEntry[]>(defaultConsoleEntries);
126
154
  const log = consoleEntries ?? innerLog;
127
155
  const latestLog = useRef(log);
@@ -135,7 +163,9 @@ export function FlowBuilder<Kind extends string = FlowNodeKind>({
135
163
 
136
164
  const addNode = (item: PaletteItem) => {
137
165
  seq.current += 1;
138
- const id = `${item.kind}-${seq.current}`;
166
+ let suffix = 1;
167
+ while (nodes.some((node) => node.id === `${item.kind}-${suffix}`)) suffix += 1;
168
+ const id = `${item.kind}-${suffix}`;
139
169
  const right = nodes.reduce((max, n) => Math.max(max, n.position.x), -256);
140
170
  const slim = item.kind === 'trigger' || item.kind === 'router';
141
171
  const node: FlowNode = {
@@ -147,15 +177,19 @@ export function FlowBuilder<Kind extends string = FlowNodeKind>({
147
177
  selected: true,
148
178
  data: { title: `New ${item.title.toLowerCase()}`, subtitle: item.description },
149
179
  };
150
- setNodes((ns) => [...ns.map((n) => (n.selected ? { ...n, selected: false } : n)), node]);
180
+ const next = [...nodes.map((n) => (n.selected ? { ...n, selected: false } : n)), node];
181
+ setNodes(next);
182
+ onGraphChange?.(cleanFlowGraph({ nodes: next, edges }), { type: 'add', nodeIds: [id], edgeIds: [] });
151
183
  };
152
184
 
153
- const updateNode = (id: string, patch: Partial<FlowNodeData>) =>
154
- setNodes((ns) => ns.map((n) => (n.id === id ? { ...n, data: { ...n.data, ...patch } } : n)));
185
+ const updateNode = (id: string, patch: Partial<FlowNodeData>) => {
186
+ const next = nodes.map((n) => (n.id === id ? { ...n, data: { ...n.data, ...patch } } : n));
187
+ setNodes(next);
188
+ onGraphChange?.(cleanFlowGraph({ nodes: next, edges }), { type: 'update', nodeIds: [id], edgeIds: [] });
189
+ };
155
190
 
156
191
  const deleteNode = (id: string) => {
157
- setNodes((ns) => ns.filter((n) => n.id !== id));
158
- setEdges((es) => es.filter((e) => e.source !== id && e.target !== id));
192
+ void flow.current?.deleteElements({ nodes: [{ id }] });
159
193
  };
160
194
 
161
195
  const commitLog = (next: ConsoleEntry[]) => {
@@ -205,12 +239,21 @@ export function FlowBuilder<Kind extends string = FlowNodeKind>({
205
239
  commitLog([]);
206
240
  };
207
241
 
208
- const connections = useConnections(nodes, setEdges, defaultConnect, {
209
- onConnect: onConnected,
210
- onConnectEdge,
211
- isValidConnection,
212
- onConnectionRejected,
213
- });
242
+ const connections = useConnections(
243
+ nodes,
244
+ edges,
245
+ (edge) => {
246
+ const next = [...edges, edge];
247
+ setEdges(next);
248
+ onGraphChange?.(cleanFlowGraph({ nodes, edges: next }), { type: 'connect', nodeIds: [], edgeIds: [edge.id] });
249
+ },
250
+ {
251
+ onConnect: onConnected,
252
+ onConnectEdge,
253
+ isValidConnection,
254
+ onConnectionRejected,
255
+ },
256
+ );
214
257
 
215
258
  const issues = validationIssues ?? NO_ISSUES;
216
259
  const displayedNodes = useDecoratedNodes(nodes, issues, nodeStatus, runMode);
@@ -228,11 +271,40 @@ export function FlowBuilder<Kind extends string = FlowNodeKind>({
228
271
  height={h}
229
272
  nodes={displayedNodes}
230
273
  edges={edges}
231
- onNodesChange={(changes) =>
274
+ onInit={(instance) => {
275
+ flow.current = instance;
276
+ }}
277
+ onDelete={({ nodes: deletedNodes, edges: deletedEdges }) => {
278
+ if (runMode) return;
279
+ const nodeIds = deletedNodes.map((node) => node.id);
280
+ const edgeIds = deletedEdges.map((edge) => edge.id);
281
+ const next = {
282
+ nodes: nodes.filter((node) => !nodeIds.includes(node.id)),
283
+ edges: edges.filter((edge) => !edgeIds.includes(edge.id)),
284
+ };
285
+ setNodes(next.nodes);
286
+ setEdges(next.edges);
287
+ onGraphChange?.(cleanFlowGraph(next), { type: 'delete', nodeIds, edgeIds });
288
+ }}
289
+ onNodesChange={(changes) => {
232
290
  onNodesChange(
233
291
  runMode ? changes.filter((change) => change.type === 'select' || change.type === 'dimensions') : changes,
234
- )
235
- }
292
+ );
293
+ if (runMode) return;
294
+ const moves = changes
295
+ .filter((change) => change.type === 'position')
296
+ .filter((change) => change.dragging === false);
297
+ if (!moves.length) return;
298
+ const next = nodes.map((node) => {
299
+ const move = moves.find((change) => change.id === node.id);
300
+ return move?.type === 'position' && move.position ? { ...node, position: move.position } : node;
301
+ });
302
+ onGraphChange?.(cleanFlowGraph({ nodes: next, edges }), {
303
+ type: 'move',
304
+ nodeIds: moves.map((move) => move.id),
305
+ edgeIds: [],
306
+ });
307
+ }}
236
308
  onEdgesChange={(changes) =>
237
309
  onEdgesChange(runMode ? changes.filter((change) => change.type === 'select') : changes)
238
310
  }
@@ -5,7 +5,7 @@ export const meta: BlockMeta = {
5
5
  family: 'builders',
6
6
  status: 'beta',
7
7
  description:
8
- 'Visual flow editor with optional nodeTypes for named handles (branch-arm, parallel and sequence examples), onConnectEdge for edge type/data mapping, isValidConnection and onConnectionRejected for rules, onConnect for accepted connections, validationIssues for node/flow problems, mode="run" for a read-only canvas, nodeStatus for live badges, and onNodeSelect for pointer/keyboard selection. Optional nodeTypes registers kit-owned {type, handles:[{id,kind,position?,label?}], render, decorations?} definitions (no React Flow NodeProps). Keep nodeTypes and its renderer definitions stable (module scope or useMemo) across nodeStatus updates: recreating the array rebuilds custom node components and remounts them, defeating per-node memoization. onConnectEdge({source,target,sourceType,targetType,sourceHandle,targetHandle}) returns {type,data}; examples/extensions.tsx maps branch arm-0 to {kind: "branch-arm", armIndex: 0}, parallel branch to {kind: "parallel"}, and sequence next to {kind: "sequence"}. isValidConnection returns true, false, or {code,nodeId?,message}; onConnectionRejected reports {code,nodeId,message} once (nodeId defaults to the source) so consumers can forward it into validationIssues and control its lifetime, while onConnect reports accepted connections only. validationIssues decorates nodes with an icon and accessible text; node issues select and focus their node, and flow issues have no node link. mode="run" removes the Run action, palette, inspector and graph mutation while keeping labelled keyboard-selectable nodes, pan/zoom, fit controls and the wide-screen minimap. nodeStatus maps node IDs to FlowTone badges (running, degraded, failed, paused, done, handoff, review); onNodeSelect(id) handles pointer and keyboard selection. RunFlowExample shows live updates with per-node memoization. FlowNode defaults to the built-in FlowNodeKind union; use FlowNode<string> (or a custom kind union) for custom graphs, inferred by FlowBuilder and WorkflowBuilderPage. Custom renderers use kit status overlays and issue decorations by default; set decorations:"consumer" when render owns them, using data.decoration with accessible text and icons (for example, render:({data}) => <NodeCard title={data.title} tone={data.decoration?.status} />). FlowCanvas showInteractiveControls=false retains zoom/fit without the editing toggle. Named handles are keyboard controls: Enter or Space starts or completes a connection in edit mode; handles are disabled in run mode.',
8
+ 'FlowGraph<Kind> is {nodes,edges}; FlowGraphChange names the edit type and affected nodeIds/edgeIds. Optional onGraphChange(graph, change) reports each committed add, delete, move, connect or inspector update once, omitting selected, dragging and measured from nodes. Inspector updates report every value change: hosts persisting every call should debounce. Selection, measurement, panel resizing, rejected connections and run mode report nothing. Optional graph controls content: render the parent graph without applying edits locally, while selection, measured sizes and active drag positions stay internal by stable node id. nodes/edges remain initial values when uncontrolled. onRun keeps the canvas node objects. builderNodes and builderEdges expose the shared starter graph; cleanFlowGraph(graph) returns a graph without transient node fields for persistence. examples/ControlledGraph.tsx shows graph={graph} onGraphChange={setGraph}. Palette ids skip existing kind-n ids. Visual flow editor with optional nodeTypes for named handles (branch-arm, parallel and sequence examples), onConnectEdge for edge type/data mapping, isValidConnection and onConnectionRejected for rules, onConnect for accepted connections, validationIssues for node/flow problems, mode="run" for a read-only canvas, nodeStatus for live badges, and onNodeSelect for pointer/keyboard selection. Optional nodeTypes registers kit-owned {type, handles:[{id,kind,position?,label?}], render, decorations?} definitions (no React Flow NodeProps). Keep nodeTypes and its renderer definitions stable (module scope or useMemo) across nodeStatus updates: recreating the array rebuilds custom node components and remounts them, defeating per-node memoization. onConnectEdge({source,target,sourceType,targetType,sourceHandle,targetHandle}) returns {type,data}; examples/extensions.tsx maps branch arm-0 to {kind: "branch-arm", armIndex: 0}, parallel branch to {kind: "parallel"}, and sequence next to {kind: "sequence"}. isValidConnection returns true, false, or {code,nodeId?,message}; onConnectionRejected reports {code,nodeId,message} once (nodeId defaults to the source) so consumers can forward it into validationIssues and control its lifetime, while onConnect reports accepted connections only. validationIssues decorates nodes with an icon and accessible text; node issues select and focus their node, and flow issues have no node link. mode="run" removes the Run action, palette, inspector and graph mutation while keeping labelled keyboard-selectable nodes, pan/zoom, fit controls and the wide-screen minimap. nodeStatus maps node IDs to FlowTone badges (running, degraded, failed, paused, done, handoff, review); onNodeSelect(id) handles pointer and keyboard selection. RunFlowExample shows live updates with per-node memoization. FlowNode defaults to the built-in FlowNodeKind union; use FlowNode<string> (or a custom kind union) for custom graphs, inferred by FlowBuilder and WorkflowBuilderPage. Custom renderers use kit status overlays and issue decorations by default; set decorations:"consumer" when render owns them, using data.decoration with accessible text and icons (for example, render:({data}) => <NodeCard title={data.title} tone={data.decoration?.status} />). FlowCanvas showInteractiveControls=false retains zoom/fit without the editing toggle. Named handles are keyboard controls: Enter or Space starts or completes a connection in edit mode; handles are disabled in run mode.',
9
9
  uses: [
10
10
  'FlowCanvas',
11
11
  'useFlowState',
@@ -1,4 +1,4 @@
1
- import { useRef, type Dispatch, type SetStateAction } from 'react';
1
+ import { useRef } from 'react';
2
2
  import type { FlowCanvasProps, FlowNode } from '@gntik-ai/flow';
3
3
  import type { FlowBuilderExtensions, FlowConnection, FlowConnectionRejection } from './extensions';
4
4
  import type { FlowEdge } from './fixtures';
@@ -8,8 +8,8 @@ type Candidate = Parameters<NonNullable<FlowCanvasProps<FlowNode<string>, FlowEd
8
8
 
9
9
  export function useConnections(
10
10
  nodes: FlowNode<string>[],
11
- setEdges: Dispatch<SetStateAction<FlowEdge[]>>,
12
- defaultConnect: Connect,
11
+ edges: FlowEdge[],
12
+ commit: (edge: FlowEdge) => void,
13
13
  props: FlowBuilderExtensions,
14
14
  ) {
15
15
  const pending = useRef<FlowConnectionRejection | null>(null);
@@ -52,15 +52,33 @@ export function useConnections(
52
52
  }
53
53
  if (props.onConnectEdge) {
54
54
  const mapped = props.onConnectEdge(describe(c));
55
- setEdges((es) => [
56
- ...es,
57
- {
58
- ...c,
59
- ...mapped,
60
- id: `edge-${++seq.current}-${c.source}-${c.target}`,
61
- },
62
- ]);
63
- } else defaultConnect(c);
55
+ let id: string;
56
+ do {
57
+ id = `edge-${++seq.current}-${c.source}-${c.target}`;
58
+ } while (edges.some((edge) => edge.id === id));
59
+ commit({ ...c, ...mapped, id });
60
+ } else if (
61
+ c.source &&
62
+ c.target &&
63
+ !edges.some(
64
+ (edge) =>
65
+ edge.source === c.source &&
66
+ edge.target === c.target &&
67
+ (edge.sourceHandle || null) === (c.sourceHandle || null) &&
68
+ (edge.targetHandle || null) === (c.targetHandle || null),
69
+ )
70
+ ) {
71
+ // Match useFlowState's default edge shape and duplicate-connection behavior.
72
+ const edge: FlowEdge = {
73
+ ...c,
74
+ id: `xy-edge__${c.source}${c.sourceHandle || ''}-${c.target}${c.targetHandle || ''}`,
75
+ type: 'smoothstep',
76
+ animated: true,
77
+ };
78
+ if (edge.sourceHandle === null) delete edge.sourceHandle;
79
+ if (edge.targetHandle === null) delete edge.targetHandle;
80
+ commit(edge);
81
+ }
64
82
  props.onConnect?.(describe(c));
65
83
  };
66
84
  return { connect, validate, finish, reset };
@@ -0,0 +1,8 @@
1
+ import { useState } from 'react';
2
+ import { FlowBuilder, builderNodes, builderEdges, cleanFlowGraph, type FlowGraph } from '../FlowBuilder';
3
+
4
+ /** Apply reported graph content while the builder retains canvas selection and drag state. */
5
+ export default function ControlledGraph() {
6
+ const [graph, setGraph] = useState<FlowGraph>(() => cleanFlowGraph({ nodes: builderNodes, edges: builderEdges }));
7
+ return <FlowBuilder graph={graph} onGraphChange={setGraph} />;
8
+ }
@@ -0,0 +1,78 @@
1
+ import { useMemo, useState, type Dispatch, type SetStateAction } from 'react';
2
+ import { useFlowState, type FlowNode, type FlowNodeKind } from '@gntik-ai/flow';
3
+ import type { FlowGraph } from './FlowBuilder';
4
+ import type { FlowEdge } from './fixtures';
5
+
6
+ type Overlay<Kind extends string> = Partial<Pick<FlowNode<Kind>, 'selected' | 'measured' | 'dragging' | 'position'>>;
7
+
8
+ /** Parent graph content with a local overlay for canvas-only state. */
9
+ export function useBuilderGraph<Kind extends string>(initial: FlowGraph<Kind>, graph?: FlowGraph<Kind>) {
10
+ type Node = FlowNode<Kind | FlowNodeKind>;
11
+ const local = useFlowState<Node, FlowEdge>(initial.nodes, initial.edges);
12
+ const [overlay, setOverlay] = useState<Record<string, Overlay<Kind | FlowNodeKind>>>({});
13
+ const [edgeSelection, setEdgeSelection] = useState<Record<string, boolean>>({});
14
+ const nodes = useMemo(
15
+ () =>
16
+ graph ? graph.nodes.map((node) => (overlay[node.id] ? { ...node, ...overlay[node.id] } : node)) : local.nodes,
17
+ [graph, overlay, local.nodes],
18
+ );
19
+ const edges = useMemo(
20
+ () =>
21
+ graph
22
+ ? graph.edges.map((edge) => (edge.id in edgeSelection ? { ...edge, selected: edgeSelection[edge.id] } : edge))
23
+ : local.edges,
24
+ [graph, edgeSelection, local.edges],
25
+ );
26
+ const setNodes: Dispatch<SetStateAction<Node[]>> = (action) => {
27
+ if (!graph) return local.setNodes(action);
28
+ const next = typeof action === 'function' ? action(nodes) : action;
29
+ setOverlay(
30
+ Object.fromEntries(
31
+ next.map((node) => [
32
+ node.id,
33
+ {
34
+ selected: node.selected,
35
+ measured: node.measured,
36
+ dragging: node.dragging,
37
+ ...(node.dragging ? { position: node.position } : {}),
38
+ },
39
+ ]),
40
+ ),
41
+ );
42
+ };
43
+ const setEdges: Dispatch<SetStateAction<FlowEdge[]>> = (action) => {
44
+ if (!graph) return local.setEdges(action);
45
+ const next = typeof action === 'function' ? action(edges) : action;
46
+ setEdgeSelection(Object.fromEntries(next.map((edge) => [edge.id, edge.selected ?? false])));
47
+ };
48
+ const onNodesChange: typeof local.onNodesChange = (changes) => {
49
+ if (!graph) return local.onNodesChange(changes);
50
+ setOverlay((previous) => {
51
+ const next = { ...previous };
52
+ for (const change of changes) {
53
+ if (change.type === 'select') next[change.id] = { ...next[change.id], selected: change.selected };
54
+ if (change.type === 'dimensions' && change.dimensions)
55
+ next[change.id] = { ...next[change.id], measured: change.dimensions };
56
+ if (change.type === 'position') {
57
+ const rest = { ...next[change.id] };
58
+ delete rest.position;
59
+ next[change.id] = {
60
+ ...rest,
61
+ dragging: change.dragging,
62
+ ...(change.dragging && change.position ? { position: change.position } : {}),
63
+ };
64
+ }
65
+ }
66
+ return next;
67
+ });
68
+ };
69
+ const onEdgesChange: typeof local.onEdgesChange = (changes) => {
70
+ if (!graph) return local.onEdgesChange(changes);
71
+ setEdgeSelection((previous) => {
72
+ const next = { ...previous };
73
+ for (const change of changes) if (change.type === 'select') next[change.id] = change.selected;
74
+ return next;
75
+ });
76
+ };
77
+ return { nodes, edges, setNodes, setEdges, onNodesChange, onEdgesChange };
78
+ }
@@ -0,0 +1,90 @@
1
+ import { render, screen } from '@testing-library/react';
2
+ import userEvent from '@testing-library/user-event';
3
+ import { I18nProvider, es } from '@gntik-ai/ui';
4
+ import { LogViewer, type LogViewerLabels } from './LogViewer';
5
+ import { makeLogLines } from './fixtures';
6
+ import { expectNoAxeViolations } from '../../test/a11y';
7
+
8
+ const lines = makeLogLines(3);
9
+
10
+ it('localizes log chrome and state changes without translating or changing copied log data', async () => {
11
+ const user = userEvent.setup();
12
+ render(
13
+ <I18nProvider locale="es">
14
+ <LogViewer lines={lines} onSelectLine={() => {}} />
15
+ </I18nProvider>,
16
+ );
17
+ expect(screen.getByRole('heading', { name: es['logViewer.title'] })).toHaveTextContent('Registros');
18
+ expect(screen.getByRole('log')).toHaveAccessibleName(es['logViewer.title']);
19
+ expect(screen.getByRole('group', { name: es['logViewer.levelFilter'] })).toBeVisible();
20
+ const search = screen.getByRole('searchbox', { name: es['logViewer.searchLabel'] });
21
+ expect(search).toHaveAttribute('placeholder', es['logViewer.searchPlaceholder']);
22
+ expect(screen.getByPlaceholderText(es['logViewer.searchPlaceholder'])).toBe(search);
23
+ expect(screen.getByRole('switch', { name: es['logViewer.follow'] })).toBeChecked();
24
+ expect(screen.getByText('3 de 3')).toBeVisible();
25
+ expect(screen.getByRole('button', { name: 'Inspeccionar evento 12:00:00.000' })).toBeVisible();
26
+ for (const line of lines) {
27
+ expect(screen.getByText(line.message)).toBeVisible();
28
+ expect(screen.getAllByText(line.level.toUpperCase())[0]).toBeVisible();
29
+ }
30
+ await user.click(screen.getByRole('button', { name: 'Copiar línea 12:00:00.000' }));
31
+ expect(screen.getByRole('button', { name: es['common.copied'] })).toBeVisible();
32
+ expect(await navigator.clipboard.readText()).toBe('12:00:00.000 INFO [api] GET /v1/projects 200 in 42ms');
33
+ await user.type(search, 'no-match');
34
+ expect(screen.getByText('0 de 3')).toBeVisible();
35
+ expect(screen.getByText(es['logViewer.empty'])).toBeVisible();
36
+ expect(document.body.textContent).not.toContain('{');
37
+ await expectNoAxeViolations();
38
+ });
39
+
40
+ it('keeps English defaults byte-identical without a provider', () => {
41
+ const { rerender } = render(<LogViewer lines={lines} onSelectLine={() => {}} />);
42
+ expect(screen.getByRole('heading', { name: 'Logs' })).toBeVisible();
43
+ expect(screen.getByRole('group', { name: 'Log levels' })).toBeVisible();
44
+ expect(screen.getByRole('searchbox', { name: 'Search logs' })).toHaveAttribute('placeholder', 'Search…');
45
+ expect(screen.getByRole('switch', { name: 'Follow' })).toBeVisible();
46
+ expect(screen.getByText('3 of 3')).toBeVisible();
47
+ expect(screen.getByRole('button', { name: 'Copy line 12:00:00.000' })).toBeVisible();
48
+ expect(screen.getByRole('button', { name: 'Inspect event 12:00:00.000' })).toBeVisible();
49
+ rerender(<LogViewer lines={[]} />);
50
+ expect(screen.getByText('No lines match the current filters.')).toBeVisible();
51
+ });
52
+
53
+ it('renders every override verbatim, falls back per key, and gives title precedence', async () => {
54
+ const user = userEvent.setup();
55
+ const labels: LogViewerLabels = {
56
+ title: 'Custom logs',
57
+ levelFilter: 'Custom levels',
58
+ searchLabel: 'Custom search',
59
+ searchPlaceholder: 'Custom placeholder',
60
+ follow: 'Custom follow',
61
+ count: (visible, total) => `${visible}/${total} custom`,
62
+ empty: 'Custom empty',
63
+ inspect: (timestamp) => `Inspect: ${timestamp}`,
64
+ copy: (timestamp) => `Copy: ${timestamp}`,
65
+ copied: 'Custom copied',
66
+ };
67
+ const view = (overrides: Partial<LogViewerLabels>, title?: string) => (
68
+ <I18nProvider locale="es">
69
+ <LogViewer lines={lines} labels={overrides} title={title} onSelectLine={() => {}} />
70
+ </I18nProvider>
71
+ );
72
+ const { rerender } = render(view(labels));
73
+ expect(screen.getByRole('heading', { name: labels.title })).toBeVisible();
74
+ expect(screen.getByRole('group', { name: labels.levelFilter })).toBeVisible();
75
+ expect(screen.getByRole('searchbox', { name: labels.searchLabel })).toHaveAttribute(
76
+ 'placeholder',
77
+ labels.searchPlaceholder,
78
+ );
79
+ expect(screen.getByRole('switch', { name: labels.follow })).toBeVisible();
80
+ expect(screen.getByText('3/3 custom')).toBeVisible();
81
+ expect(screen.getByRole('button', { name: 'Inspect: 12:00:00.000' })).toBeVisible();
82
+ await user.click(screen.getByRole('button', { name: 'Copy: 12:00:00.000' }));
83
+ expect(screen.getByRole('button', { name: labels.copied })).toBeVisible();
84
+ await user.type(screen.getByRole('searchbox'), 'no-match');
85
+ expect(screen.getByText(labels.empty)).toBeVisible();
86
+ rerender(view({ title: 'Override' }, 'Explicit title'));
87
+ expect(screen.getByRole('heading', { name: 'Explicit title' })).toBeVisible();
88
+ expect(screen.getByRole('switch', { name: es['logViewer.follow'] })).toBeVisible();
89
+ expect(screen.getByText(es['logViewer.empty'])).toBeVisible();
90
+ });
@@ -0,0 +1,49 @@
1
+ import { render, screen, within } from '@testing-library/react';
2
+ import { I18nProvider } from '@gntik-ai/ui';
3
+ import { LogViewer } from './LogViewer';
4
+ import { makeLogLines } from './fixtures';
5
+
6
+ it('uses Spanish catalog names for chips and filter options', () => {
7
+ const lines = makeLogLines(20);
8
+ render(
9
+ <I18nProvider locale="es">
10
+ <LogViewer lines={lines} height={600} />
11
+ </I18nProvider>,
12
+ );
13
+ const chips = { debug: 'DEBUG', info: 'INFO', warn: 'AVISO', error: 'ERROR' };
14
+ const options = { debug: 'debug', info: 'info', warn: 'aviso', error: 'error' };
15
+ const rows = screen.getByRole('log').querySelectorAll('[data-slot="log-line"]');
16
+ expect(rows).toHaveLength(20);
17
+ lines.forEach((line, i) => {
18
+ expect(within(rows[i] as HTMLElement).getByText(chips[line.level])).toBeVisible();
19
+ });
20
+ for (const level of ['debug', 'info', 'warn', 'error'] as const) {
21
+ const count = lines.filter((line) => line.level === level).length;
22
+ expect(screen.getByRole('button', { name: `${options[level]}${count}` })).toHaveTextContent(
23
+ `${options[level]}${count}`,
24
+ );
25
+ }
26
+ });
27
+
28
+ it.each([
29
+ [{ debug: 'Trace', info: 'Notice', warn: 'Caution', error: 'Failure' }, ['Trace', 'Notice', 'Caution', 'Failure']],
30
+ [{ warn: 'Caution' }, ['DEBUG', 'INFO', 'Caution', 'ERROR']],
31
+ ] as const)('renders level overrides verbatim and falls back per level: %j', (levels, expected) => {
32
+ const lines = makeLogLines(10);
33
+ render(
34
+ <I18nProvider locale="es">
35
+ <LogViewer lines={lines} labels={{ levels }} />
36
+ </I18nProvider>,
37
+ );
38
+ for (const [i, level] of (['debug', 'info', 'warn', 'error'] as const).entries()) {
39
+ const line = lines.find((line) => line.level === level)!;
40
+ const row = screen.getByText(line.message).closest('[data-slot="log-line"]') as HTMLElement;
41
+ expect(within(row).getByText(expected[i]!)).toBeVisible();
42
+ const option = levels[level as keyof typeof levels] ?? level;
43
+ expect(
44
+ screen.getByRole('button', {
45
+ name: `${option}${lines.filter((line) => line.level === level).length}`,
46
+ }),
47
+ ).toBeVisible();
48
+ }
49
+ });