@republicroad/seal-editor 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +13 -0
- package/README.md +127 -0
- package/dist/index.d.ts +2515 -0
- package/dist/index.js +15779 -0
- package/dist/index.js.map +1 -0
- package/dist/schema-BmbNWz7t.js +596 -0
- package/dist/schema-BmbNWz7t.js.map +1 -0
- package/dist/schema.d.ts +868 -0
- package/dist/schema.js +2 -0
- package/dist/style.css +3 -0
- package/package.json +144 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/helpers/dnd-overlay.tsx","../src/lib/utils.ts","../src/components/ui/button.tsx","../src/theming/portal-context.tsx","../src/components/ui/alert-dialog.tsx","../src/components/primitives/app.tsx","../src/components/primitives/avatar.tsx","../src/components/primitives/button.tsx","../src/components/primitives/card.tsx","../src/components/ui/checkbox.tsx","../src/components/primitives/checkbox.tsx","../../../node_modules/.pnpm/dayjs@1.11.13/node_modules/dayjs/dayjs.min.js","../src/components/primitives/shared.ts","../src/components/primitives/date-picker.tsx","../src/components/primitives/divider.tsx","../src/components/ui/context-menu.tsx","../src/components/ui/dropdown-menu.tsx","../src/components/primitives/dropdown.tsx","../src/components/primitives/form.tsx","../src/components/ui/input.tsx","../src/components/primitives/input.tsx","../src/components/primitives/input-number.tsx","../src/components/ui/dialog.tsx","../src/components/primitives/modal.tsx","../src/components/primitives/popconfirm.tsx","../src/components/ui/popover.tsx","../src/components/primitives/popover.tsx","../src/components/primitives/radio.tsx","../src/components/ui/select.tsx","../src/components/primitives/select.tsx","../src/components/primitives/space.tsx","../src/components/primitives/spin.tsx","../src/components/primitives/steps.tsx","../src/components/ui/switch.tsx","../src/components/primitives/switch.tsx","../src/components/ui/tabs.tsx","../src/components/primitives/tabs.tsx","../src/components/primitives/tag.tsx","../src/components/ui/tooltip.tsx","../src/components/primitives/tooltip.tsx","../src/components/primitives/typography.tsx","../src/helpers/wasm.ts","../src/theming/color.ts","../src/theming/dark-ops.ts","../src/theming/presets.ts","../src/theming/derive.ts","../src/theming/compute.ts","../src/theming/i18n-types.ts","../src/theming/messages/en.ts","../src/theming/messages/zh-CN.ts","../src/theming/i18n.tsx","../src/theme.tsx","../src/components/safe-boundary.tsx","../src/components/decision-table/context/dt-dialog.context.tsx","../../../node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/es6/react.js","../src/helpers/use-memoized-selector.ts","../src/components/decision-table/context/dt-store.context.tsx","../src/components/stack.tsx","../src/components/decision-table/dialog/fields-reorder-dialog.tsx","../src/components/decision-table/dialog/dt-dialogs.tsx","../src/reui/icons/animated/outline/cross.tsx","../src/reui/icons/animated/outline/pencil.tsx","../src/reui/icons/animated/outline/play-circle.tsx","../src/reui/icons/animated/outline/refresh-arrow-clockwise.tsx","../src/reui/icons/animated/outline/trash-square.tsx","../src/helpers/file-helpers.ts","../src/helpers/excel.ts","../src/helpers/compose-refs.ts","../src/components/autosize-text-area.tsx","../src/components/code-editor/extensions/completion.ts","../src/components/code-editor/extensions/diagnostic.tsx","../src/helpers/codemirror.ts","../src/components/code-editor/extensions/linter.ts","../src/components/code-editor/extensions/zen.ts","../src/components/code-editor/extensions/types.ts","../src/components/code-editor/theme.ts","../src/components/code-editor/ce-base.tsx","../src/components/code-editor/ce-highlight.tsx","../src/components/code-editor/cell-view-pool.tsx","../src/components/code-editor/ce-highlight-view.tsx","../src/components/code-editor/ce.tsx","../src/components/code-editor/business/focus-helper.ts","../src/components/code-editor/business/expression-builder/constants.ts","../src/components/code-editor/business/expression-builder/op-icon.tsx","../src/components/code-editor/business/expression-builder/op-dropdown.tsx","../src/components/code-editor/business/expression-builder/use-expression-state.ts","../src/components/code-editor/business/expression-builder/value-inputs.tsx","../src/components/code-editor/business/expression-builder/index.tsx","../src/components/code-editor/business/standard-expression-builder.tsx","../src/components/code-editor/ce-preview.tsx","../src/components/decision-table/components/enum-utils.ts","../src/components/confirm-action.tsx","../src/components/decision-table/components/field-edit-popover.tsx","../src/components/decision-table/components/field-type-tags.tsx","../src/components/decision-table/components/input-field-edit.tsx","../src/components/decision-table/components/output-field-edit.tsx","../src/components/decision-table/components/dt-excel-dialog/excel-dnd.tsx","../src/components/decision-table/components/dt-excel-dialog/import-column-row.tsx","../src/components/decision-table/components/dt-excel-dialog/mapping.ts","../src/components/decision-table/components/dt-excel-dialog/index.tsx","../src/components/decision-table/dt-command-bar.tsx","../src/components/decision-table/dt-empty.tsx","../src/components/spaced-text.tsx","../src/components/decision-table/table/table-context-menu.tsx","../src/helpers/components.ts","../src/components/shared/diff-radio.tsx","../src/components/arrow-diff-icon.tsx","../src/components/shared/diff-switch.tsx","../src/components/shared/diff-input.tsx","../src/components/shared/diff-select.tsx","../src/components/shared/diff-ce.tsx","../src/components/shared/diff-text-area.tsx","../src/components/decision-table/util.ts","../src/components/decision-table/table/table-default-cell.tsx","../src/components/diff-icon.tsx","../src/components/text-edit.tsx","../src/components/decision-table/table/table-head-cell.tsx","../src/components/decision-table/table/table-head-row.tsx","../src/helpers/dnd.ts","../src/components/decision-table/table/table-row.tsx","../src/components/decision-table/table/table.tsx","../src/components/decision-table/dt.tsx","../src/helpers/utility.ts","../src/components/decision-graph/dg-types.ts","../src/components/decision-graph/dg-util.ts","../src/components/decision-graph/nodes/specifications/specification-types.ts","../src/components/decision-graph/context/dg-tab-strategy.ts","../src/components/decision-graph/context/undo-redo.ts","../src/components/decision-graph/context/dg-store.context.tsx","../src/components/decision-graph/context/serializer.context.tsx","../src/helpers/node-type.ts","../src/components/decision-graph/diff/comparison.ts","../src/helpers/node-data.ts","../src/components/decision-graph/graph/tab-decision-table.tsx","../src/helpers/platform.ts","../src/helpers/use-persistent-state.ts","../src/reui/badge.tsx","../src/reui/icon-tile.tsx","../src/components/decision-graph/nodes/graph-card.tsx","../src/components/decision-graph/nodes/specifications/colors.ts","../src/components/decision-graph/nodes/decision-node.tsx","../src/components/decision-graph/nodes/graph-node.tsx","../src/components/decision-graph/nodes/specifications/decision-table.specification.tsx","../src/components/expression/context/expression-store.context.tsx","../src/components/expression/expression-command-bar.tsx","../src/components/expression/expression-controller.tsx","../src/helpers/trace.ts","../src/components/expression/expression-item-context-menu.tsx","../src/components/expression/expression-item.tsx","../src/components/expression/expression-list.tsx","../src/components/expression/expression.tsx","../src/components/decision-graph/graph/tab-expression.tsx","../src/components/decision-graph/nodes/specifications/expression.specification.tsx","../src/components/function/helpers/libs.ts","../src/components/decision-graph/graph/tab-function.tsx","../src/components/decision-graph/nodes/specifications/function.specification.tsx","../src/reui/icons/animated/outline/information.tsx","../src/helpers/monaco.ts","../src/components/decision-graph/graph/blur-commit-input.tsx","../src/components/decision-graph/graph/request-definitions.tsx","../src/components/decision-graph/graph/request-example-summary.tsx","../src/helpers/json-path-extractor.ts","../src/components/decision-graph/graph/request-inlay-hints.ts","../src/components/decision-graph/graph/request-examples.tsx","../src/components/decision-graph/graph/json-to-json-schema-dialog.tsx","../src/components/decision-graph/graph/request-schema-editor.tsx","../src/components/decision-graph/graph/request-session-draft.ts","../src/components/decision-graph/graph/use-request-definitions-editing.ts","../src/components/decision-graph/graph/use-request-examples-editing.ts","../src/components/decision-graph/graph/use-request-schema-editing.ts","../src/components/decision-graph/graph/tab-request.tsx","../src/components/decision-graph/nodes/specifications/input.specification.tsx","../src/components/decision-graph/graph/tab-json-schema.tsx","../src/components/decision-graph/nodes/specifications/output.specification.tsx","../src/components/decision-graph/nodes/specifications/switch.specification/diff.ts","../src/components/decision-graph/nodes/specifications/switch.specification/switch-handle.tsx","../src/components/decision-graph/nodes/specifications/switch.specification/switch-node.tsx","../src/components/decision-graph/nodes/specifications/switch.specification/index.tsx","../src/components/decision-graph/diff/utility.ts","../src/components/decision-graph/dg-empty.tsx","../src/helpers/traversal.ts","../src/components/decision-graph/nodes/specifications/specifications.tsx","../src/components/decision-graph/dg-infer.tsx","../src/components/decision-graph/dg-panel.tsx","../src/components/decision-graph/custom-edge.tsx","../src/components/decision-graph/hooks/use-graph-clipboard.ts","../src/components/decision-graph/hooks/use-graph-dnd.ts","../src/components/decision-graph/hooks/use-graph-serializers.ts","../src/components/decision-graph/hooks/use-node-add.ts","../src/components/decision-graph/graph/graph-components.tsx","../src/components/decision-graph/graph/node-inspector.tsx","../src/components/decision-graph/graph/xyflow-theme.ts","../src/components/decision-graph/graph/graph.tsx","../src/components/decision-graph/graph/graph-nodes.tsx","../src/components/decision-graph/graph/graph-excel-dialog/merge-data.ts","../src/components/decision-graph/graph/graph-excel-dialog/index.tsx","../src/components/decision-graph/graph/graph-side-toolbar.tsx","../src/components/decision-graph/graph/graph-tabs.tsx","../src/helpers/custom-function-schema.ts","../src/components/custom-function-table/context/expression-store.context.tsx","../src/components/custom-function-table/expression-command-bar.tsx","../src/components/custom-function-table/expression-controller.tsx","../src/helpers/json-schema.ts","../src/components/custom-function-table/expression-item-context-menu.tsx","../src/components/custom-function-table/expression-item.tsx","../src/components/custom-function-table/expression-list.tsx","../src/components/custom-function-table/expression.tsx","../src/components/decision-graph/graph/tab-custom-function-table.tsx","../src/components/decision-graph/graph/toolbar-anchor.tsx","../src/components/decision-graph/dg-wrapper.tsx","../src/components/decision-graph/dg.tsx","../src/components/decision-graph/nodes/custom-node/index.tsx","../src/components/decision-graph/simulator/simulator-editor.tsx","../src/reui/icons/animated/outline/check-circle.tsx","../src/reui/icons/animated/outline/cross-circle.tsx","../src/components/decision-graph/simulator/simulator-nodes-panel.tsx","../src/reui/icons/animated/outline/link.tsx","../src/components/decision-graph/simulator/simulator-request-toolbar.tsx","../src/components/decision-graph/simulator/use-request-example-persistence.ts","../src/components/decision-graph/simulator/use-simulator-auto-sync.ts","../src/components/decision-graph/simulator/use-simulator-request-binding.ts","../src/components/decision-graph/simulator/use-simulator-request-editor.ts","../src/components/decision-graph/simulator/simulator-request-panel.tsx","../src/components/decision-graph/simulator/dg-simulator.tsx","../src/components/decision-graph/diff/compute-graph-diff.ts","../src/assets/typescript.svg?inline","../src/components/function/function-debugger-log.tsx","../src/components/function/function-debugger.tsx","../src/components/function/helpers/determine-type.ts","../src/components/function/function.tsx","../src/components/function/index.ts"],"sourcesContent":["import React from 'react';\n\nconst cardStyle: React.CSSProperties = {\n display: 'inline-flex',\n alignItems: 'center',\n gap: 8,\n maxWidth: 480,\n padding: '4px 12px',\n background: 'var(--card)',\n border: '1px solid var(--border)',\n borderRadius: 8,\n boxShadow: 'var(--grl-box-shadow-secondary, 0 6px 16px rgba(0,0,0,0.12))',\n fontSize: 12,\n lineHeight: '20px',\n color: 'var(--foreground)',\n cursor: 'grabbing',\n pointerEvents: 'none',\n};\n\nconst chipStyle: React.CSSProperties = {\n maxWidth: 140,\n overflow: 'hidden',\n textOverflow: 'ellipsis',\n whiteSpace: 'nowrap',\n};\n\nexport const DragOverlayCard: React.FC<React.PropsWithChildren> = ({ children }) => (\n <div className='grl-drag-overlay' style={cardStyle}>\n {children}\n </div>\n);\n\nexport const OverlayChip: React.FC<{ children: React.ReactNode; width?: number }> = ({ children, width }) => (\n <span style={{ ...chipStyle, ...(width ? { maxWidth: width } : {}) }}>{children}</span>\n);\n\nexport const OverlayIndexChip: React.FC<{ index: number }> = ({ index }) => (\n <span\n style={{\n minWidth: 20,\n textAlign: 'center',\n padding: '0 4px',\n borderRadius: 4,\n background: 'var(--grl-color-primary-bg, var(--background))',\n color: 'var(--primary)',\n fontWeight: 500,\n }}\n >\n {index + 1}\n </span>\n);\n","import { type ClassValue, clsx } from 'clsx';\nimport { twMerge } from 'tailwind-merge';\n\nexport function cn(...inputs: ClassValue[]) {\n return twMerge(clsx(inputs));\n}\n","import { cn } from '#lib/utils';\nimport { Button as ButtonPrimitive } from '@base-ui/react/button';\nimport { type VariantProps, cva } from 'class-variance-authority';\nimport * as React from 'react';\n\nconst buttonVariants = cva(\n \"appearance-none border-0 border-solid bg-transparent inline-flex shrink-0 items-center justify-center gap-2 rounded-md text-sm font-medium whitespace-nowrap transition-all outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4\",\n {\n variants: {\n variant: {\n default: 'bg-primary text-primary-foreground hover:bg-primary/90',\n destructive:\n 'bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:bg-destructive/60 dark:focus-visible:ring-destructive/40',\n outline:\n 'border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:border-input dark:bg-input/30 dark:hover:bg-input/50',\n secondary: 'bg-secondary text-secondary-foreground hover:bg-secondary/80',\n ghost: 'hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50',\n link: 'text-primary underline-offset-4 hover:underline',\n },\n size: {\n 'default': 'h-9 px-4 py-2 has-[>svg]:px-3',\n 'xs': \"h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3\",\n 'sm': 'h-8 gap-1.5 rounded-md px-3 has-[>svg]:px-2.5',\n 'lg': 'h-10 rounded-md px-6 has-[>svg]:px-4',\n 'icon': 'size-9',\n 'icon-xs': \"size-6 rounded-md [&_svg:not([class*='size-'])]:size-3\",\n 'icon-sm': 'size-8',\n 'icon-lg': 'size-10',\n },\n },\n defaultVariants: {\n variant: 'default',\n size: 'default',\n },\n },\n);\n\nconst Button = React.forwardRef<\n React.ComponentRef<typeof ButtonPrimitive>,\n React.ComponentPropsWithoutRef<typeof ButtonPrimitive> & VariantProps<typeof buttonVariants>\n>(function Button({ className, variant = 'default', size = 'default', ...props }, ref) {\n return (\n <ButtonPrimitive\n ref={ref}\n data-slot='button'\n data-variant={variant}\n data-size={size}\n className={cn(buttonVariants({ variant, size, className }))}\n {...props}\n />\n );\n});\nButton.displayName = 'Button';\n\nexport { Button, buttonVariants };\n","import * as React from 'react';\n\n/**\n * Scoped-injection plumbing (roadmap P3).\n *\n * JdmConfigProvider resolves the nearest `.grl-root` ancestor once on mount\n * and publishes the container element here. Every Radix portal in\n * `components/ui/*` reads it so popovers/dialogs/selects mount INSIDE the\n * island that owns their theme variables — enabling multiple independently-\n * themed islands on one page and bringing the scoped preflight (box-sizing\n * etc.) back over portaled nodes (HK-14 systemic closure).\n *\n * Undefined = no `.grl-root` ancestor → portals fall back to document.body\n * and the provider falls back to global `:root` injection (legacy hosts).\n */\n\nconst GrlContainerContext = React.createContext<HTMLElement | undefined>(undefined);\n\nexport const GrlContainerProvider: React.FC<React.PropsWithChildren<{ container: HTMLElement | undefined }>> = ({\n container,\n children,\n}) => <GrlContainerContext.Provider value={container}>{children}</GrlContainerContext.Provider>;\n\n/** Portal target for `components/ui/*` — the island container, if scoped. */\nexport const useGrlPortalContainer = (): HTMLElement | undefined => React.useContext(GrlContainerContext);\n","'use client';\n\nimport { Button } from '#components/ui/button';\nimport { cn } from '#lib/utils';\nimport { AlertDialog as AlertDialogPrimitive } from '@base-ui/react/alert-dialog';\nimport * as React from 'react';\n\nimport { useGrlPortalContainer } from '../../theming/portal-context';\n\nfunction AlertDialog({ ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Root>) {\n return <AlertDialogPrimitive.Root data-slot='alert-dialog' {...props} />;\n}\n\nfunction AlertDialogTrigger({ ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Trigger>) {\n return <AlertDialogPrimitive.Trigger data-slot='alert-dialog-trigger' {...props} />;\n}\n\nfunction AlertDialogPortal({ ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Portal>) {\n return <AlertDialogPrimitive.Portal data-slot='alert-dialog-portal' {...props} />;\n}\n\nfunction AlertDialogOverlay({ className, ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Backdrop>) {\n return (\n <AlertDialogPrimitive.Backdrop\n data-slot='alert-dialog-overlay'\n className={cn(\n 'fixed inset-0 z-50 bg-black/50 transition-opacity duration-200 data-ending-style:opacity-0 data-starting-style:opacity-0',\n className,\n )}\n {...props}\n />\n );\n}\n\nfunction AlertDialogContent({\n className,\n size = 'default',\n ...props\n}: React.ComponentProps<typeof AlertDialogPrimitive.Popup> & {\n size?: 'default' | 'sm';\n}) {\n const grlContainer = useGrlPortalContainer();\n return (\n <AlertDialogPortal container={grlContainer}>\n <AlertDialogOverlay />\n <AlertDialogPrimitive.Popup\n data-slot='alert-dialog-content'\n data-size={size}\n className={cn(\n // box-border: portaled nodes live outside .grl-root preflight scope (HK-14).\n 'group/alert-dialog-content box-border fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-lg border bg-background p-6 shadow-lg outline-none transition-[opacity,transform] duration-200 data-[size=sm]:max-w-xs data-[size=default]:sm:max-w-lg data-ending-style:scale-95 data-ending-style:opacity-0 data-starting-style:scale-95 data-starting-style:opacity-0',\n className,\n )}\n {...props}\n />\n </AlertDialogPortal>\n );\n}\n\nfunction AlertDialogHeader({ className, ...props }: React.ComponentProps<'div'>) {\n return (\n <div\n data-slot='alert-dialog-header'\n className={cn(\n 'grid grid-rows-[auto_1fr] place-items-center gap-1.5 text-center has-data-[slot=alert-dialog-media]:grid-rows-[auto_auto_1fr] has-data-[slot=alert-dialog-media]:gap-x-6 sm:group-data-[size=default]/alert-dialog-content:place-items-start sm:group-data-[size=default]/alert-dialog-content:text-left sm:group-data-[size=default]/alert-dialog-content:has-data-[slot=alert-dialog-media]:grid-rows-[auto_1fr]',\n className,\n )}\n {...props}\n />\n );\n}\n\nfunction AlertDialogFooter({ className, ...props }: React.ComponentProps<'div'>) {\n return (\n <div\n data-slot='alert-dialog-footer'\n className={cn(\n 'flex flex-col-reverse gap-2 group-data-[size=sm]/alert-dialog-content:grid group-data-[size=sm]/alert-dialog-content:grid-cols-2 sm:flex-row sm:justify-end',\n className,\n )}\n {...props}\n />\n );\n}\n\nfunction AlertDialogTitle({ className, ...props }: React.ComponentProps<typeof AlertDialogPrimitive.Title>) {\n return (\n <AlertDialogPrimitive.Title\n data-slot='alert-dialog-title'\n className={cn(\n 'text-lg font-semibold sm:group-data-[size=default]/alert-dialog-content:group-has-data-[slot=alert-dialog-media]/alert-dialog-content:col-start-2',\n className,\n )}\n {...props}\n />\n );\n}\n\nfunction AlertDialogDescription({\n className,\n ...props\n}: React.ComponentProps<typeof AlertDialogPrimitive.Description>) {\n return (\n <AlertDialogPrimitive.Description\n data-slot='alert-dialog-description'\n className={cn('text-sm text-muted-foreground', className)}\n {...props}\n />\n );\n}\n\nfunction AlertDialogMedia({ className, ...props }: React.ComponentProps<'div'>) {\n return (\n <div\n data-slot='alert-dialog-media'\n className={cn(\n \"mb-2 inline-flex size-16 items-center justify-center rounded-md bg-muted sm:group-data-[size=default]/alert-dialog-content:row-span-2 *:[svg:not([class*='size-'])]:size-8\",\n className,\n )}\n {...props}\n />\n );\n}\n\nfunction AlertDialogAction({\n className,\n variant = 'default',\n size = 'default',\n ...props\n}: React.ComponentProps<typeof AlertDialogPrimitive.Close> &\n Pick<React.ComponentProps<typeof Button>, 'variant' | 'size'>) {\n return (\n <AlertDialogPrimitive.Close\n data-slot='alert-dialog-action'\n render={<Button variant={variant} size={size} className={cn(className)} {...props} />}\n />\n );\n}\n\nfunction AlertDialogCancel({\n className,\n variant = 'outline',\n size = 'default',\n ...props\n}: React.ComponentProps<typeof AlertDialogPrimitive.Close> &\n Pick<React.ComponentProps<typeof Button>, 'variant' | 'size'>) {\n return (\n <AlertDialogPrimitive.Close\n data-slot='alert-dialog-cancel'\n render={<Button variant={variant} size={size} className={cn(className)} {...props} />}\n />\n );\n}\n\nexport {\n AlertDialog,\n AlertDialogAction,\n AlertDialogCancel,\n AlertDialogContent,\n AlertDialogDescription,\n AlertDialogFooter,\n AlertDialogHeader,\n AlertDialogMedia,\n AlertDialogOverlay,\n AlertDialogPortal,\n AlertDialogTitle,\n AlertDialogTrigger,\n};\n","import {\n AlertDialog,\n AlertDialogAction,\n AlertDialogCancel,\n AlertDialogContent,\n AlertDialogDescription,\n AlertDialogFooter,\n AlertDialogHeader,\n AlertDialogTitle,\n} from '#components/ui/alert-dialog';\nimport { cn } from '#lib/utils';\nimport * as React from 'react';\n\nexport interface ConfirmOptions {\n icon?: React.ReactNode;\n title?: React.ReactNode;\n content?: React.ReactNode;\n okText?: string;\n cancelText?: string;\n okButtonProps?: { danger?: boolean };\n onOk?: () => void;\n onCancel?: () => void;\n}\n\ninterface ConfirmItem extends ConfirmOptions {\n id: number;\n}\n\ntype ConfirmGlobalState = {\n seq: number;\n items: ConfirmItem[];\n listeners: Set<(items: ConfirmItem[]) => void>;\n};\n\n/**\n * State lives on globalThis so dev-server HMR (which re-evaluates this\n * module) keeps pending confirms and live subscribers across reloads.\n */\nconst confirmState = ((globalThis as Record<string, unknown>).__JDM_CONFIRM_STATE ??= {\n seq: 0,\n items: [] as ConfirmItem[],\n listeners: new Set<(items: ConfirmItem[]) => void>(),\n}) as ConfirmGlobalState;\n\nconst emitConfirms = () => confirmState.listeners.forEach((listener) => listener(confirmState.items));\n\nconst openConfirm = (options: ConfirmOptions) => {\n confirmState.items = [...confirmState.items, { ...options, id: ++confirmState.seq }];\n emitConfirms();\n};\n\nconst closeConfirm = (id: number) => {\n confirmState.items = confirmState.items.filter((item) => item.id !== id);\n emitConfirms();\n};\n\ninterface AppContextValue {\n modal: { confirm: (options: ConfirmOptions) => void };\n}\n\nconst AppContext = React.createContext<AppContextValue>({\n modal: { confirm: openConfirm },\n});\n\nconst ConfirmHost: React.FC = () => {\n const [items, setItems] = React.useState<ConfirmItem[]>(confirmState.items);\n React.useEffect(() => {\n confirmState.listeners.add(setItems);\n return () => {\n confirmState.listeners.delete(setItems);\n };\n }, []);\n\n return (\n <>\n {items.map((item) => (\n <AlertDialog key={item.id} defaultOpen>\n <AlertDialogContent>\n <AlertDialogHeader>\n <AlertDialogTitle>{item.title}</AlertDialogTitle>\n {item.content ? <AlertDialogDescription render={<div>{item.content}</div>} /> : null}\n </AlertDialogHeader>\n <AlertDialogFooter>\n <AlertDialogCancel\n onClick={() => {\n item.onCancel?.();\n closeConfirm(item.id);\n }}\n >\n {item.cancelText ?? 'Cancel'}\n </AlertDialogCancel>\n <AlertDialogAction\n variant={item.okButtonProps?.danger ? 'destructive' : 'default'}\n onClick={() => {\n item.onOk?.();\n closeConfirm(item.id);\n }}\n >\n {item.okText ?? 'OK'}\n </AlertDialogAction>\n </AlertDialogFooter>\n </AlertDialogContent>\n </AlertDialog>\n ))}\n </>\n );\n};\n\nconst AppProvider: React.FC<{ children?: React.ReactNode; className?: string; style?: React.CSSProperties }> = ({\n children,\n className,\n style,\n}) => (\n <AppContext.Provider value={{ modal: { confirm: openConfirm } }}>\n <div className={cn('h-full', className)} style={style}>\n {children}\n <ConfirmHost />\n </div>\n </AppContext.Provider>\n);\n\nexport const App = Object.assign(AppProvider, {\n useApp: (): AppContextValue => React.useContext(AppContext),\n});\n","import { cn } from '#lib/utils';\nimport * as React from 'react';\n\nexport const Avatar: React.FC<\n Omit<React.HTMLAttributes<HTMLDivElement>, 'children'> & {\n src?: string;\n alt?: string;\n size?: number | 'large' | 'default' | 'small';\n shape?: 'circle' | 'square';\n icon?: React.ReactNode;\n children?: React.ReactNode;\n }\n> = ({ src, alt, size = 'default', shape = 'circle', className, style, children, icon, ...rest }) => {\n const pxSize = typeof size === 'number' ? size : size === 'large' ? 40 : size === 'small' ? 24 : 32;\n return (\n <div\n className={cn(\n 'flex shrink-0 select-none items-center justify-center overflow-hidden bg-muted text-xs font-medium text-muted-foreground',\n shape === 'circle' ? 'rounded-full' : 'rounded-md',\n className,\n )}\n style={{ width: pxSize, height: pxSize, ...style }}\n {...rest}\n >\n {src ? <img src={src} alt={alt} className='size-full object-cover' /> : (children ?? icon)}\n </div>\n );\n};\n","import { Button as UiButton } from '#components/ui/button';\nimport { cn } from '#lib/utils';\nimport { Loader2 } from 'lucide-react';\nimport * as React from 'react';\n\ntype ButtonType = 'primary' | 'default' | 'dashed' | 'text' | 'link';\ntype ButtonSize = 'large' | 'middle' | 'small';\n\nexport interface ButtonProps extends Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, 'type'> {\n type?: ButtonType;\n icon?: React.ReactNode;\n danger?: boolean;\n loading?: boolean;\n size?: ButtonSize;\n block?: boolean;\n shape?: 'circle' | 'round' | 'default';\n href?: string;\n target?: string;\n}\n\nexport const Button = React.forwardRef<HTMLButtonElement, ButtonProps & { ref?: React.Ref<HTMLButtonElement> }>(\n (\n {\n type = 'default',\n icon,\n danger = false,\n loading = false,\n size = 'middle',\n block = false,\n shape,\n href,\n target,\n className,\n children,\n disabled,\n ...rest\n },\n ref,\n ) => {\n const variant = (() => {\n if (danger && type === 'link') return 'link';\n if (danger && type !== 'text') return 'destructive';\n switch (type) {\n case 'primary':\n return danger ? 'destructive' : 'default';\n case 'text':\n return 'ghost';\n case 'link':\n return 'link';\n case 'dashed':\n return 'outline';\n default:\n return 'outline';\n }\n })();\n\n const sizeClass = size === 'large' ? 'h-10 px-6 text-base' : size === 'small' ? 'h-7 px-2.5 text-xs' : undefined;\n\n const inner = (\n <>\n {loading ? <Loader2 className='animate-spin' /> : icon}\n {children}\n </>\n );\n\n if (href) {\n return (\n <a\n ref={ref as React.Ref<HTMLAnchorElement>}\n href={href}\n target={target}\n className={cn(\n 'inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium underline-offset-4 hover:underline',\n variant === 'link' ? 'text-primary' : '',\n danger && type === 'link' && 'text-destructive',\n sizeClass,\n disabled && 'pointer-events-none opacity-50',\n className,\n )}\n >\n {inner}\n </a>\n );\n }\n\n return (\n <UiButton\n ref={ref}\n variant={variant as never}\n className={cn(\n sizeClass,\n type === 'dashed' && 'border-dashed',\n danger && type === 'link' && 'text-destructive',\n danger && type === 'text' && 'text-destructive hover:bg-destructive/10',\n block && 'w-full',\n (shape === 'circle' || shape === 'round') && 'rounded-full',\n !children && icon && 'px-2',\n className,\n )}\n disabled={disabled || loading}\n {...rest}\n >\n {inner}\n </UiButton>\n );\n },\n);\n","import { cn } from '#lib/utils';\nimport * as React from 'react';\n\nexport const Card = React.forwardRef<\n HTMLDivElement,\n React.HTMLAttributes<HTMLDivElement> & {\n hoverable?: boolean;\n styles?: { body?: React.CSSProperties };\n bodyStyle?: React.CSSProperties;\n children?: React.ReactNode;\n }\n>(function Card({ hoverable, className, style, styles, bodyStyle, onClick, children, ...rest }, ref) {\n return (\n <div\n ref={ref}\n className={cn(\n 'rounded-(--grl-border-radius) border bg-card text-card-foreground shadow-xs',\n hoverable && 'cursor-pointer transition-colors hover:border-primary/50',\n className,\n )}\n style={style}\n onClick={onClick}\n {...rest}\n >\n <div className='p-4' style={{ ...bodyStyle, ...styles?.body }}>\n {children}\n </div>\n </div>\n );\n});\n","import { cn } from '#lib/utils';\nimport { Checkbox as CheckboxPrimitive } from '@base-ui/react/checkbox';\nimport { CheckIcon } from 'lucide-react';\nimport * as React from 'react';\n\nfunction Checkbox({ className, ...props }: React.ComponentProps<typeof CheckboxPrimitive.Root>) {\n return (\n <CheckboxPrimitive.Root\n data-slot='checkbox'\n className={cn(\n 'peer size-4 shrink-0 rounded-[4px] border border-input shadow-xs transition-shadow outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 data-disabled:cursor-not-allowed data-disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-checked:border-primary data-checked:bg-primary data-checked:text-primary-foreground dark:bg-input/30 dark:aria-invalid:ring-destructive/40 dark:data-checked:bg-primary',\n className,\n )}\n {...props}\n >\n <CheckboxPrimitive.Indicator\n data-slot='checkbox-indicator'\n className='grid place-content-center text-current transition-none'\n >\n <CheckIcon className='size-3.5' />\n </CheckboxPrimitive.Indicator>\n </CheckboxPrimitive.Root>\n );\n}\n\nexport { Checkbox };\n","import { Checkbox as UiCheckbox } from '#components/ui/checkbox';\nimport { cn } from '#lib/utils';\nimport * as React from 'react';\n\nexport interface CheckboxChangeEvent {\n target: { checked: boolean };\n stopPropagation: () => void;\n}\n\nexport const Checkbox: React.FC<{\n checked?: boolean;\n defaultChecked?: boolean;\n disabled?: boolean;\n className?: string;\n style?: React.CSSProperties;\n onChange?: (event: CheckboxChangeEvent) => void;\n children?: React.ReactNode;\n}> = ({ checked, defaultChecked, disabled, className, style, onChange, children }) => (\n <label className={cn('inline-flex cursor-pointer items-center gap-2 text-sm', className)} style={style}>\n <UiCheckbox\n checked={checked === undefined ? undefined : !!checked}\n defaultChecked={defaultChecked}\n disabled={disabled}\n onCheckedChange={(next) => onChange?.({ target: { checked: next === true }, stopPropagation: () => {} })}\n />\n {children ? <span>{children}</span> : null}\n </label>\n);\n","!function(t,e){\"object\"==typeof exports&&\"undefined\"!=typeof module?module.exports=e():\"function\"==typeof define&&define.amd?define(e):(t=\"undefined\"!=typeof globalThis?globalThis:t||self).dayjs=e()}(this,(function(){\"use strict\";var t=1e3,e=6e4,n=36e5,r=\"millisecond\",i=\"second\",s=\"minute\",u=\"hour\",a=\"day\",o=\"week\",c=\"month\",f=\"quarter\",h=\"year\",d=\"date\",l=\"Invalid Date\",$=/^(\\d{4})[-/]?(\\d{1,2})?[-/]?(\\d{0,2})[Tt\\s]*(\\d{1,2})?:?(\\d{1,2})?:?(\\d{1,2})?[.:]?(\\d+)?$/,y=/\\[([^\\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,M={name:\"en\",weekdays:\"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday\".split(\"_\"),months:\"January_February_March_April_May_June_July_August_September_October_November_December\".split(\"_\"),ordinal:function(t){var e=[\"th\",\"st\",\"nd\",\"rd\"],n=t%100;return\"[\"+t+(e[(n-20)%10]||e[n]||e[0])+\"]\"}},m=function(t,e,n){var r=String(t);return!r||r.length>=e?t:\"\"+Array(e+1-r.length).join(n)+t},v={s:m,z:function(t){var e=-t.utcOffset(),n=Math.abs(e),r=Math.floor(n/60),i=n%60;return(e<=0?\"+\":\"-\")+m(r,2,\"0\")+\":\"+m(i,2,\"0\")},m:function t(e,n){if(e.date()<n.date())return-t(n,e);var r=12*(n.year()-e.year())+(n.month()-e.month()),i=e.clone().add(r,c),s=n-i<0,u=e.clone().add(r+(s?-1:1),c);return+(-(r+(n-i)/(s?i-u:u-i))||0)},a:function(t){return t<0?Math.ceil(t)||0:Math.floor(t)},p:function(t){return{M:c,y:h,w:o,d:a,D:d,h:u,m:s,s:i,ms:r,Q:f}[t]||String(t||\"\").toLowerCase().replace(/s$/,\"\")},u:function(t){return void 0===t}},g=\"en\",D={};D[g]=M;var p=\"$isDayjsObject\",S=function(t){return t instanceof _||!(!t||!t[p])},w=function t(e,n,r){var i;if(!e)return g;if(\"string\"==typeof e){var s=e.toLowerCase();D[s]&&(i=s),n&&(D[s]=n,i=s);var u=e.split(\"-\");if(!i&&u.length>1)return t(u[0])}else{var a=e.name;D[a]=e,i=a}return!r&&i&&(g=i),i||!r&&g},O=function(t,e){if(S(t))return t.clone();var n=\"object\"==typeof e?e:{};return n.date=t,n.args=arguments,new _(n)},b=v;b.l=w,b.i=S,b.w=function(t,e){return O(t,{locale:e.$L,utc:e.$u,x:e.$x,$offset:e.$offset})};var _=function(){function M(t){this.$L=w(t.locale,null,!0),this.parse(t),this.$x=this.$x||t.x||{},this[p]=!0}var m=M.prototype;return m.parse=function(t){this.$d=function(t){var e=t.date,n=t.utc;if(null===e)return new Date(NaN);if(b.u(e))return new Date;if(e instanceof Date)return new Date(e);if(\"string\"==typeof e&&!/Z$/i.test(e)){var r=e.match($);if(r){var i=r[2]-1||0,s=(r[7]||\"0\").substring(0,3);return n?new Date(Date.UTC(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)):new Date(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)}}return new Date(e)}(t),this.init()},m.init=function(){var t=this.$d;this.$y=t.getFullYear(),this.$M=t.getMonth(),this.$D=t.getDate(),this.$W=t.getDay(),this.$H=t.getHours(),this.$m=t.getMinutes(),this.$s=t.getSeconds(),this.$ms=t.getMilliseconds()},m.$utils=function(){return b},m.isValid=function(){return!(this.$d.toString()===l)},m.isSame=function(t,e){var n=O(t);return this.startOf(e)<=n&&n<=this.endOf(e)},m.isAfter=function(t,e){return O(t)<this.startOf(e)},m.isBefore=function(t,e){return this.endOf(e)<O(t)},m.$g=function(t,e,n){return b.u(t)?this[e]:this.set(n,t)},m.unix=function(){return Math.floor(this.valueOf()/1e3)},m.valueOf=function(){return this.$d.getTime()},m.startOf=function(t,e){var n=this,r=!!b.u(e)||e,f=b.p(t),l=function(t,e){var i=b.w(n.$u?Date.UTC(n.$y,e,t):new Date(n.$y,e,t),n);return r?i:i.endOf(a)},$=function(t,e){return b.w(n.toDate()[t].apply(n.toDate(\"s\"),(r?[0,0,0,0]:[23,59,59,999]).slice(e)),n)},y=this.$W,M=this.$M,m=this.$D,v=\"set\"+(this.$u?\"UTC\":\"\");switch(f){case h:return r?l(1,0):l(31,11);case c:return r?l(1,M):l(0,M+1);case o:var g=this.$locale().weekStart||0,D=(y<g?y+7:y)-g;return l(r?m-D:m+(6-D),M);case a:case d:return $(v+\"Hours\",0);case u:return $(v+\"Minutes\",1);case s:return $(v+\"Seconds\",2);case i:return $(v+\"Milliseconds\",3);default:return this.clone()}},m.endOf=function(t){return this.startOf(t,!1)},m.$set=function(t,e){var n,o=b.p(t),f=\"set\"+(this.$u?\"UTC\":\"\"),l=(n={},n[a]=f+\"Date\",n[d]=f+\"Date\",n[c]=f+\"Month\",n[h]=f+\"FullYear\",n[u]=f+\"Hours\",n[s]=f+\"Minutes\",n[i]=f+\"Seconds\",n[r]=f+\"Milliseconds\",n)[o],$=o===a?this.$D+(e-this.$W):e;if(o===c||o===h){var y=this.clone().set(d,1);y.$d[l]($),y.init(),this.$d=y.set(d,Math.min(this.$D,y.daysInMonth())).$d}else l&&this.$d[l]($);return this.init(),this},m.set=function(t,e){return this.clone().$set(t,e)},m.get=function(t){return this[b.p(t)]()},m.add=function(r,f){var d,l=this;r=Number(r);var $=b.p(f),y=function(t){var e=O(l);return b.w(e.date(e.date()+Math.round(t*r)),l)};if($===c)return this.set(c,this.$M+r);if($===h)return this.set(h,this.$y+r);if($===a)return y(1);if($===o)return y(7);var M=(d={},d[s]=e,d[u]=n,d[i]=t,d)[$]||1,m=this.$d.getTime()+r*M;return b.w(m,this)},m.subtract=function(t,e){return this.add(-1*t,e)},m.format=function(t){var e=this,n=this.$locale();if(!this.isValid())return n.invalidDate||l;var r=t||\"YYYY-MM-DDTHH:mm:ssZ\",i=b.z(this),s=this.$H,u=this.$m,a=this.$M,o=n.weekdays,c=n.months,f=n.meridiem,h=function(t,n,i,s){return t&&(t[n]||t(e,r))||i[n].slice(0,s)},d=function(t){return b.s(s%12||12,t,\"0\")},$=f||function(t,e,n){var r=t<12?\"AM\":\"PM\";return n?r.toLowerCase():r};return r.replace(y,(function(t,r){return r||function(t){switch(t){case\"YY\":return String(e.$y).slice(-2);case\"YYYY\":return b.s(e.$y,4,\"0\");case\"M\":return a+1;case\"MM\":return b.s(a+1,2,\"0\");case\"MMM\":return h(n.monthsShort,a,c,3);case\"MMMM\":return h(c,a);case\"D\":return e.$D;case\"DD\":return b.s(e.$D,2,\"0\");case\"d\":return String(e.$W);case\"dd\":return h(n.weekdaysMin,e.$W,o,2);case\"ddd\":return h(n.weekdaysShort,e.$W,o,3);case\"dddd\":return o[e.$W];case\"H\":return String(s);case\"HH\":return b.s(s,2,\"0\");case\"h\":return d(1);case\"hh\":return d(2);case\"a\":return $(s,u,!0);case\"A\":return $(s,u,!1);case\"m\":return String(u);case\"mm\":return b.s(u,2,\"0\");case\"s\":return String(e.$s);case\"ss\":return b.s(e.$s,2,\"0\");case\"SSS\":return b.s(e.$ms,3,\"0\");case\"Z\":return i}return null}(t)||i.replace(\":\",\"\")}))},m.utcOffset=function(){return 15*-Math.round(this.$d.getTimezoneOffset()/15)},m.diff=function(r,d,l){var $,y=this,M=b.p(d),m=O(r),v=(m.utcOffset()-this.utcOffset())*e,g=this-m,D=function(){return b.m(y,m)};switch(M){case h:$=D()/12;break;case c:$=D();break;case f:$=D()/3;break;case o:$=(g-v)/6048e5;break;case a:$=(g-v)/864e5;break;case u:$=g/n;break;case s:$=g/e;break;case i:$=g/t;break;default:$=g}return l?$:b.a($)},m.daysInMonth=function(){return this.endOf(c).$D},m.$locale=function(){return D[this.$L]},m.locale=function(t,e){if(!t)return this.$L;var n=this.clone(),r=w(t,e,!0);return r&&(n.$L=r),n},m.clone=function(){return b.w(this.$d,this)},m.toDate=function(){return new Date(this.valueOf())},m.toJSON=function(){return this.isValid()?this.toISOString():null},m.toISOString=function(){return this.$d.toISOString()},m.toString=function(){return this.$d.toUTCString()},M}(),k=_.prototype;return O.prototype=k,[[\"$ms\",r],[\"$s\",i],[\"$m\",s],[\"$H\",u],[\"$W\",a],[\"$M\",c],[\"$y\",h],[\"$D\",d]].forEach((function(t){k[t[1]]=function(e){return this.$g(e,t[0],t[1])}})),O.extend=function(t,e){return t.$i||(t(e,_,O),t.$i=!0),O},O.locale=w,O.isDayjs=S,O.unix=function(t){return O(1e3*t)},O.en=D[g],O.Ls=D,O.p={},O}));","export const borderlessInputClass =\n 'h-7 rounded-md bg-transparent px-2 text-xs outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50';\n","import { cn } from '#lib/utils';\nimport dayjs, { type Dayjs } from 'dayjs';\nimport * as React from 'react';\n\nimport { borderlessInputClass } from './shared';\n\nexport interface DatePickerProps {\n value?: Dayjs | null;\n onChange?: (date: Dayjs | null) => void;\n disabled?: boolean;\n allowClear?: boolean;\n size?: 'large' | 'middle' | 'small';\n variant?: string;\n format?: string;\n placeholder?: string;\n className?: string;\n style?: React.CSSProperties;\n}\n\nconst toDayjs = (raw: string) => dayjs(raw);\n\nexport const DatePicker: React.FC<DatePickerProps> = ({\n value,\n onChange,\n disabled,\n allowClear = true,\n className,\n style,\n placeholder,\n}) => (\n <input\n type='date'\n value={value?.format ? value.format('YYYY-MM-DD') : ''}\n placeholder={placeholder}\n disabled={disabled}\n onChange={(event) => {\n if (!event.target.value) {\n if (allowClear) onChange?.(null);\n return;\n }\n const parsed = toDayjs(event.target.value);\n if (parsed.isValid()) onChange?.(parsed);\n }}\n className={cn(\n borderlessInputClass,\n 'w-full rounded-md border border-input shadow-xs focus-visible:border-ring',\n className,\n )}\n style={style}\n />\n);\n\nexport const TimePicker: React.FC<DatePickerProps> = ({\n value,\n onChange,\n disabled,\n allowClear = true,\n className,\n style,\n}) => (\n <input\n type='time'\n value={value?.format ? value.format('HH:mm') : ''}\n disabled={disabled}\n onChange={(event) => {\n if (!event.target.value) {\n if (allowClear) onChange?.(null);\n return;\n }\n const parsed = toDayjs(`2000-01-01 ${event.target.value}`);\n if (parsed.isValid()) onChange?.(parsed);\n }}\n className={cn(\n borderlessInputClass,\n 'w-full rounded-md border border-input shadow-xs focus-visible:border-ring',\n className,\n )}\n style={style}\n />\n);\n","import { cn } from '#lib/utils';\nimport * as React from 'react';\n\nexport const Divider: React.FC<{\n type?: 'horizontal' | 'vertical';\n className?: string;\n style?: React.CSSProperties;\n}> = ({ type = 'horizontal', className, style }) => (\n <div\n role='separator'\n className={cn(\n type === 'vertical'\n ? 'mx-1.5 inline-block h-[1.2em] w-px self-center bg-border'\n : 'my-2 w-full border-t border-border',\n className,\n )}\n style={style}\n />\n);\n","'use client';\n\nimport { cn } from '#lib/utils';\nimport { ContextMenu as ContextMenuPrimitive } from '@base-ui/react/context-menu';\nimport * as React from 'react';\n\nimport { useGrlPortalContainer } from '../../theming/portal-context';\n\nfunction ContextMenu(props: React.ComponentProps<typeof ContextMenuPrimitive.Root>) {\n return <ContextMenuPrimitive.Root data-slot='context-menu' {...props} />;\n}\n\nfunction ContextMenuTrigger(props: React.ComponentProps<typeof ContextMenuPrimitive.Trigger>) {\n return <ContextMenuPrimitive.Trigger data-slot='context-menu-trigger' {...props} />;\n}\n\nfunction ContextMenuPortal(props: React.ComponentProps<typeof ContextMenuPrimitive.Portal>) {\n const grlContainer = useGrlPortalContainer();\n return <ContextMenuPrimitive.Portal data-slot='context-menu-portal' container={grlContainer} {...props} />;\n}\n\nconst ContextMenuContent = React.forwardRef<\n React.ComponentRef<typeof ContextMenuPrimitive.Popup>,\n React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Popup> &\n Pick<ContextMenuPrimitive.Positioner.Props, 'side' | 'sideOffset' | 'align' | 'alignOffset'>\n>(({ className, side, sideOffset = 0, align, alignOffset, ...props }, ref) => {\n const grlContainer = useGrlPortalContainer();\n return (\n <ContextMenuPrimitive.Portal container={grlContainer}>\n <ContextMenuPrimitive.Positioner side={side} sideOffset={sideOffset} align={align} alignOffset={alignOffset}>\n <ContextMenuPrimitive.Popup\n ref={ref}\n data-slot='context-menu-content'\n className={cn(\n // box-border: portaled nodes live outside .grl-root preflight scope (HK-14).\n 'box-border z-50 min-w-[8rem] origin-(--transform-origin) overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md transition-[opacity,transform] duration-150 data-ending-style:scale-95 data-ending-style:opacity-0 data-starting-style:scale-95 data-starting-style:opacity-0',\n className,\n )}\n {...props}\n />\n </ContextMenuPrimitive.Positioner>\n </ContextMenuPrimitive.Portal>\n );\n});\nContextMenuContent.displayName = 'ContextMenuContent';\n\nconst ContextMenuItem = React.forwardRef<\n React.ComponentRef<typeof ContextMenuPrimitive.Item>,\n React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Item> & {\n variant?: 'default' | 'destructive';\n }\n>(({ className, variant = 'default', ...props }, ref) => (\n <ContextMenuPrimitive.Item\n ref={ref}\n data-slot='context-menu-item'\n data-variant={variant}\n className={cn(\n \"relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none data-disabled:pointer-events-none data-disabled:opacity-50 data-highlighted:bg-accent data-highlighted:text-accent-foreground data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4\",\n variant === 'destructive' &&\n 'text-destructive data-highlighted:bg-destructive/10 data-highlighted:text-destructive',\n className,\n )}\n {...props}\n />\n));\nContextMenuItem.displayName = 'ContextMenuItem';\n\nfunction ContextMenuSeparator({ className, ...props }: React.ComponentProps<typeof ContextMenuPrimitive.Separator>) {\n return (\n <ContextMenuPrimitive.Separator\n data-slot='context-menu-separator'\n className={cn('-mx-1 my-1 h-px bg-border', className)}\n {...props}\n />\n );\n}\n\n// Base Menu `SubmenuRoot` is a context provider without a DOM ref.\nfunction ContextMenuSub(props: React.ComponentProps<typeof ContextMenuPrimitive.SubmenuRoot>) {\n return <ContextMenuPrimitive.SubmenuRoot data-slot='context-menu-sub' {...props} />;\n}\nContextMenuSub.displayName = 'ContextMenuSub';\n\nconst ContextMenuSubTrigger = React.forwardRef<\n React.ComponentRef<typeof ContextMenuPrimitive.SubmenuTrigger>,\n React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.SubmenuTrigger>\n>(({ className, children, ...props }, ref) => (\n <ContextMenuPrimitive.SubmenuTrigger\n ref={ref}\n data-slot='context-menu-sub-trigger'\n className={cn(\n 'flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-highlighted:bg-accent data-highlighted:text-accent-foreground data-popup-open:bg-accent data-popup-open:text-accent-foreground',\n className,\n )}\n {...props}\n >\n {children}\n </ContextMenuPrimitive.SubmenuTrigger>\n));\nContextMenuSubTrigger.displayName = 'ContextMenuSubTrigger';\n\nconst ContextMenuSubContent = React.forwardRef<\n React.ComponentRef<typeof ContextMenuPrimitive.Popup>,\n React.ComponentPropsWithoutRef<typeof ContextMenuPrimitive.Popup> &\n Pick<ContextMenuPrimitive.Positioner.Props, 'side' | 'sideOffset' | 'align' | 'alignOffset'>\n>(({ className, side = 'right', sideOffset = 0, align, alignOffset, ...props }, ref) => {\n const grlContainer = useGrlPortalContainer();\n return (\n <ContextMenuPrimitive.Portal container={grlContainer}>\n <ContextMenuPrimitive.Positioner side={side} sideOffset={sideOffset} align={align} alignOffset={alignOffset}>\n <ContextMenuPrimitive.Popup\n ref={ref}\n data-slot='context-menu-sub-content'\n className={cn(\n 'box-border z-50 min-w-[8rem] origin-(--transform-origin) overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg transition-[opacity,transform] duration-150 data-ending-style:scale-95 data-ending-style:opacity-0 data-starting-style:scale-95 data-starting-style:opacity-0',\n className,\n )}\n {...props}\n />\n </ContextMenuPrimitive.Positioner>\n </ContextMenuPrimitive.Portal>\n );\n});\nContextMenuSubContent.displayName = 'ContextMenuSubContent';\n\nexport {\n ContextMenu,\n ContextMenuTrigger,\n ContextMenuPortal,\n ContextMenuContent,\n ContextMenuItem,\n ContextMenuSeparator,\n ContextMenuSub,\n ContextMenuSubTrigger,\n ContextMenuSubContent,\n};\n","import { cn } from '#lib/utils';\nimport { Menu as MenuPrimitive } from '@base-ui/react/menu';\nimport { CheckIcon, ChevronRightIcon, CircleIcon } from 'lucide-react';\nimport * as React from 'react';\n\nimport { useGrlPortalContainer } from '../../theming/portal-context';\n\nfunction DropdownMenu({ ...props }: React.ComponentProps<typeof MenuPrimitive.Root>) {\n return <MenuPrimitive.Root data-slot='dropdown-menu' {...props} />;\n}\n\nfunction DropdownMenuPortal({ ...props }: React.ComponentProps<typeof MenuPrimitive.Portal>) {\n return <MenuPrimitive.Portal data-slot='dropdown-menu-portal' {...props} />;\n}\n\nfunction DropdownMenuTrigger({ ...props }: React.ComponentProps<typeof MenuPrimitive.Trigger>) {\n return <MenuPrimitive.Trigger data-slot='dropdown-menu-trigger' {...props} />;\n}\n\nfunction DropdownMenuContent({\n className,\n side,\n sideOffset = 4,\n align,\n alignOffset,\n ...props\n}: React.ComponentProps<typeof MenuPrimitive.Popup> &\n Pick<MenuPrimitive.Positioner.Props, 'side' | 'sideOffset' | 'align' | 'alignOffset'>) {\n const grlContainer = useGrlPortalContainer();\n return (\n <MenuPrimitive.Portal container={grlContainer}>\n <MenuPrimitive.Positioner side={side} sideOffset={sideOffset} align={align} alignOffset={alignOffset}>\n <MenuPrimitive.Popup\n data-slot='dropdown-menu-content'\n className={cn(\n 'z-50 max-h-(--available-height) min-w-[8rem] origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover p-1 text-popover-foreground shadow-md transition-[opacity,transform] duration-150 data-ending-style:scale-95 data-ending-style:opacity-0 data-starting-style:scale-95 data-starting-style:opacity-0',\n className,\n )}\n {...props}\n />\n </MenuPrimitive.Positioner>\n </MenuPrimitive.Portal>\n );\n}\n\nfunction DropdownMenuGroup({ ...props }: React.ComponentProps<typeof MenuPrimitive.Group>) {\n return <MenuPrimitive.Group data-slot='dropdown-menu-group' {...props} />;\n}\n\nfunction DropdownMenuItem({\n className,\n inset,\n variant = 'default',\n ...props\n}: React.ComponentProps<typeof MenuPrimitive.Item> & {\n inset?: boolean;\n variant?: 'default' | 'destructive';\n}) {\n return (\n <MenuPrimitive.Item\n data-slot='dropdown-menu-item'\n data-inset={inset}\n data-variant={variant}\n className={cn(\n \"relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 data-highlighted:bg-accent data-highlighted:text-accent-foreground data-[inset]:pl-8 data-[variant=destructive]:text-destructive data-[variant=destructive]:data-highlighted:bg-destructive/10 data-[variant=destructive]:data-highlighted:text-destructive dark:data-[variant=destructive]:data-highlighted:bg-destructive/20 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground data-[variant=destructive]:*:[svg]:text-destructive!\",\n className,\n )}\n {...props}\n />\n );\n}\n\nfunction DropdownMenuCheckboxItem({\n className,\n children,\n checked,\n ...props\n}: React.ComponentProps<typeof MenuPrimitive.CheckboxItem>) {\n return (\n <MenuPrimitive.CheckboxItem\n data-slot='dropdown-menu-checkbox-item'\n className={cn(\n \"relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 data-highlighted:bg-accent data-highlighted:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4\",\n className,\n )}\n checked={checked}\n {...props}\n >\n <span className='pointer-events-none absolute left-2 flex size-3.5 items-center justify-center'>\n <MenuPrimitive.CheckboxItemIndicator>\n <CheckIcon className='size-4' />\n </MenuPrimitive.CheckboxItemIndicator>\n </span>\n {children}\n </MenuPrimitive.CheckboxItem>\n );\n}\n\nfunction DropdownMenuRadioGroup({ ...props }: React.ComponentProps<typeof MenuPrimitive.RadioGroup>) {\n return <MenuPrimitive.RadioGroup data-slot='dropdown-menu-radio-group' {...props} />;\n}\n\nfunction DropdownMenuRadioItem({\n className,\n children,\n ...props\n}: React.ComponentProps<typeof MenuPrimitive.RadioItem>) {\n return (\n <MenuPrimitive.RadioItem\n data-slot='dropdown-menu-radio-item'\n className={cn(\n \"relative flex cursor-default items-center gap-2 rounded-sm py-1.5 pr-2 pl-8 text-sm outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 data-highlighted:bg-accent data-highlighted:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4\",\n className,\n )}\n {...props}\n >\n <span className='pointer-events-none absolute left-2 flex size-3.5 items-center justify-center'>\n <MenuPrimitive.RadioItemIndicator>\n <CircleIcon className='size-2 fill-current' />\n </MenuPrimitive.RadioItemIndicator>\n </span>\n {children}\n </MenuPrimitive.RadioItem>\n );\n}\n\nfunction DropdownMenuLabel({\n className,\n inset,\n ...props\n}: React.ComponentProps<typeof MenuPrimitive.GroupLabel> & {\n inset?: boolean;\n}) {\n return (\n <MenuPrimitive.GroupLabel\n data-slot='dropdown-menu-label'\n data-inset={inset}\n className={cn('px-2 py-1.5 text-sm font-medium data-[inset]:pl-8', className)}\n {...props}\n />\n );\n}\n\nfunction DropdownMenuSeparator({ className, ...props }: React.ComponentProps<typeof MenuPrimitive.Separator>) {\n return (\n <MenuPrimitive.Separator\n data-slot='dropdown-menu-separator'\n className={cn('-mx-1 my-1 h-px bg-border', className)}\n {...props}\n />\n );\n}\n\nfunction DropdownMenuShortcut({ className, ...props }: React.ComponentProps<'span'>) {\n return (\n <span\n data-slot='dropdown-menu-shortcut'\n className={cn('ml-auto text-xs tracking-widest text-muted-foreground', className)}\n {...props}\n />\n );\n}\n\nfunction DropdownMenuSub({ ...props }: React.ComponentProps<typeof MenuPrimitive.SubmenuRoot>) {\n return <MenuPrimitive.SubmenuRoot data-slot='dropdown-menu-sub' {...props} />;\n}\n\nfunction DropdownMenuSubTrigger({\n className,\n inset,\n children,\n ...props\n}: React.ComponentProps<typeof MenuPrimitive.SubmenuTrigger> & {\n inset?: boolean;\n}) {\n return (\n <MenuPrimitive.SubmenuTrigger\n data-slot='dropdown-menu-sub-trigger'\n data-inset={inset}\n className={cn(\n \"flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-highlighted:bg-accent data-highlighted:text-accent-foreground data-popup-open:bg-accent data-popup-open:text-accent-foreground data-[inset]:pl-8 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground\",\n className,\n )}\n {...props}\n >\n {children}\n <ChevronRightIcon className='ml-auto size-4' />\n </MenuPrimitive.SubmenuTrigger>\n );\n}\n\nfunction DropdownMenuSubContent({\n className,\n side,\n sideOffset = 0,\n align,\n alignOffset,\n ...props\n}: React.ComponentProps<typeof MenuPrimitive.Popup> &\n Pick<MenuPrimitive.Positioner.Props, 'side' | 'sideOffset' | 'align' | 'alignOffset'>) {\n const grlContainer = useGrlPortalContainer();\n return (\n <MenuPrimitive.Portal container={grlContainer}>\n <MenuPrimitive.Positioner side={side} sideOffset={sideOffset} align={align} alignOffset={alignOffset}>\n <MenuPrimitive.Popup\n data-slot='dropdown-menu-sub-content'\n className={cn(\n 'z-50 min-w-[8rem] origin-(--transform-origin) overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg transition-[opacity,transform] duration-150 data-ending-style:scale-95 data-ending-style:opacity-0 data-starting-style:scale-95 data-starting-style:opacity-0',\n className,\n )}\n {...props}\n />\n </MenuPrimitive.Positioner>\n </MenuPrimitive.Portal>\n );\n}\n\nexport {\n DropdownMenu,\n DropdownMenuPortal,\n DropdownMenuTrigger,\n DropdownMenuContent,\n DropdownMenuGroup,\n DropdownMenuLabel,\n DropdownMenuItem,\n DropdownMenuCheckboxItem,\n DropdownMenuRadioGroup,\n DropdownMenuRadioItem,\n DropdownMenuSeparator,\n DropdownMenuShortcut,\n DropdownMenuSub,\n DropdownMenuSubTrigger,\n DropdownMenuSubContent,\n};\n","import {\n ContextMenu,\n ContextMenuContent,\n ContextMenuItem,\n ContextMenuSeparator,\n ContextMenuSub,\n ContextMenuSubContent,\n ContextMenuSubTrigger,\n ContextMenuTrigger,\n} from '#components/ui/context-menu';\nimport {\n DropdownMenu,\n DropdownMenuContent,\n DropdownMenuItem,\n DropdownMenuSeparator,\n DropdownMenuSub,\n DropdownMenuSubContent,\n DropdownMenuSubTrigger,\n DropdownMenuTrigger,\n} from '#components/ui/dropdown-menu';\nimport * as React from 'react';\n\nexport interface MenuItemType {\n key?: string;\n label?: React.ReactNode;\n icon?: React.ReactNode;\n danger?: boolean;\n disabled?: boolean;\n type?: 'divider' | 'group';\n onClick?: (info: { key: string }) => void;\n children?: MenuItemType[];\n}\n\nexport interface MenuProps {\n items?: MenuItemType[];\n onClick?: MenuItemType['onClick'];\n}\n\ntype MenuPrimitiveSet = {\n Item: typeof DropdownMenuItem | typeof ContextMenuItem;\n Separator: typeof DropdownMenuSeparator | typeof ContextMenuSeparator;\n // Radix `Sub` variants are providers without refs and come from different\n // menu implementations, so keep this slot loosely typed.\n Sub: React.ElementType;\n SubTrigger: typeof DropdownMenuSubTrigger | typeof ContextMenuSubTrigger;\n SubContent: typeof DropdownMenuSubContent | typeof ContextMenuSubContent;\n};\n\nconst renderMenuItems = (\n items: MenuItemType[] | undefined,\n onClick: MenuProps['onClick'],\n P: MenuPrimitiveSet,\n): React.ReactNode =>\n // Callers build item arrays with conditional expressions and may leave null\n // entries behind; drop them before touching item.key.\n (items ?? [])\n .filter((item): item is MenuItemType => !!item)\n .map((item, index) => {\n const itemKey = item.key ?? String(index);\n const handleSelect = () => (item.onClick ?? onClick)?.({ key: itemKey });\n return item.type === 'divider' ? (\n <P.Separator key={itemKey} />\n ) : item.children?.length ? (\n <P.Sub key={itemKey}>\n <P.SubTrigger disabled={item.disabled}>{item.label}</P.SubTrigger>\n <P.SubContent>{renderMenuItems(item.children, onClick, P)}</P.SubContent>\n </P.Sub>\n ) : (\n <P.Item\n key={itemKey}\n disabled={item.disabled}\n variant={item.danger ? 'destructive' : 'default'}\n onSelect={handleSelect}\n >\n {item.icon}\n {item.label}\n </P.Item>\n );\n }) ?? null;\n\nconst dropdownPrimitives: MenuPrimitiveSet = {\n Item: DropdownMenuItem,\n Separator: DropdownMenuSeparator,\n Sub: DropdownMenuSub,\n SubTrigger: DropdownMenuSubTrigger,\n SubContent: DropdownMenuSubContent,\n};\n\nconst contextMenuPrimitives: MenuPrimitiveSet = {\n Item: ContextMenuItem,\n Separator: ContextMenuSeparator,\n Sub: ContextMenuSub,\n SubTrigger: ContextMenuSubTrigger,\n SubContent: ContextMenuSubContent,\n};\n\nconst usesContextMenuTrigger = (trigger: Array<'click' | 'hover' | 'contextMenu'> | undefined) =>\n Array.isArray(trigger) && trigger.includes('contextMenu');\n\nexport const Dropdown: React.FC<{\n menu?: MenuProps;\n trigger?: Array<'click' | 'hover' | 'contextMenu'>;\n placement?: string;\n arrow?: boolean;\n overlayStyle?: React.CSSProperties;\n destroyPopupOnHide?: boolean;\n transitionName?: string;\n disabled?: boolean;\n children?: React.ReactNode;\n}> = ({ menu, trigger, children }) => {\n const wrappedChildren = React.isValidElement(children) ? (\n children\n ) : (\n <span className='inline-flex cursor-pointer items-center'>{children}</span>\n );\n\n if (usesContextMenuTrigger(trigger)) {\n return (\n <ContextMenu>\n <ContextMenuTrigger render={wrappedChildren} />\n <ContextMenuContent>{renderMenuItems(menu?.items, menu?.onClick, contextMenuPrimitives)}</ContextMenuContent>\n </ContextMenu>\n );\n }\n\n return (\n <DropdownMenu modal={false}>\n <DropdownMenuTrigger render={wrappedChildren} />\n <DropdownMenuContent align='start'>\n {renderMenuItems(menu?.items, menu?.onClick, dropdownPrimitives)}\n </DropdownMenuContent>\n </DropdownMenu>\n );\n};\n","import { cn } from '#lib/utils';\nimport * as React from 'react';\n\ninterface FormContextValue {\n values: Record<string, unknown>;\n setField: (name: string, value: unknown) => void;\n}\n\nconst FormContext = React.createContext<FormContextValue | null>(null);\n\nexport interface FormProps extends React.HTMLAttributes<HTMLDivElement> {\n layout?: 'horizontal' | 'vertical' | 'inline';\n initialValues?: Record<string, unknown>;\n onValuesChange?: (changed: Record<string, unknown>, values: Record<string, unknown>) => void;\n onFinish?: (values: Record<string, unknown>) => void;\n id?: string;\n}\n\nconst FormRoot: React.FC<FormProps> = ({ initialValues = {}, onValuesChange, className, children, ...rest }) => {\n const [values, setValues] = React.useState<Record<string, unknown>>(initialValues);\n const context = React.useMemo<FormContextValue>(\n () => ({\n values,\n setField: (name, value) => {\n setValues((previous) => {\n const changed = { [name]: value };\n const next = { ...previous, ...changed };\n onValuesChange?.(changed, next);\n return next;\n });\n },\n }),\n [values, onValuesChange],\n );\n\n return (\n <FormContext.Provider value={context}>\n <div className={cn('flex flex-col', className)} {...rest}>\n {children}\n </div>\n </FormContext.Provider>\n );\n};\n\nconst extractValue = (event: unknown, valuePropName?: string): unknown => {\n if (valuePropName) return event;\n if (event && typeof event === 'object' && 'target' in event) {\n const target = (event as { target?: unknown }).target;\n if (target && typeof target === 'object' && 'value' in target) {\n return (target as { value: unknown }).value;\n }\n }\n return event;\n};\n\nconst FormItem: React.FC<{\n name?: string;\n label?: React.ReactNode;\n valuePropName?: string;\n className?: string;\n style?: React.CSSProperties;\n children?: React.ReactNode;\n}> = ({ name, label, valuePropName, className, style, children }) => {\n const context = React.useContext(FormContext);\n let content = children;\n\n if (name && context && React.isValidElement(children)) {\n const original = children.props as Record<string, unknown>;\n const valueProp = valuePropName ?? 'value';\n content = React.cloneElement(children as React.ReactElement<Record<string, unknown>>, {\n [valueProp]: context.values[name],\n onChange: (...args: unknown[]) => {\n context.setField(name, extractValue(args[0], valuePropName));\n (original.onChange as ((...a: unknown[]) => void) | undefined)?.(...args);\n },\n });\n }\n\n return (\n <div className={cn('flex flex-col gap-1.5', className)} style={style}>\n {label}\n {content}\n </div>\n );\n};\n\nexport const Form = Object.assign(FormRoot, { Item: FormItem });\n","import { cn } from '#lib/utils';\nimport * as React from 'react';\n\nfunction Input({ className, type, ...props }: React.ComponentProps<'input'>) {\n return (\n <input\n type={type}\n data-slot='input'\n className={cn(\n 'h-9 w-full min-w-0 rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-xs transition-[color,box-shadow] outline-none selection:bg-primary selection:text-primary-foreground file:inline-flex file:h-7 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:bg-input/30',\n 'focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50',\n 'aria-invalid:border-destructive aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40',\n className,\n )}\n {...props}\n />\n );\n}\n\nexport { Input };\n","import { Input as UiInput } from '#components/ui/input';\nimport { cn } from '#lib/utils';\nimport * as React from 'react';\n\nexport interface InputProps extends Omit<React.InputHTMLAttributes<HTMLInputElement>, 'size' | 'prefix' | 'suffix'> {\n size?: 'large' | 'middle' | 'small';\n allowClear?: boolean;\n bordered?: boolean;\n prefix?: React.ReactNode;\n suffix?: React.ReactNode;\n}\n\nexport const Input = React.forwardRef<HTMLInputElement, InputProps>(function Input(\n { size, allowClear = false, bordered = true, prefix, suffix, value, onChange, className, disabled, ...rest },\n ref,\n) {\n const [internal, setInternal] = React.useState('');\n const current = value !== undefined ? String(value) : internal;\n\n const sizeClass = size === 'large' ? 'h-10 text-base' : size === 'small' ? 'h-8 text-xs' : undefined;\n\n return (\n <div className='relative inline-flex w-full items-center'>\n {prefix ? <span className='absolute left-2.5 flex text-muted-foreground [&_svg]:size-3.5'>{prefix}</span> : null}\n <UiInput\n ref={ref}\n value={current}\n onChange={(event) => {\n setInternal(event.target.value);\n onChange?.(event as never);\n }}\n disabled={disabled}\n className={cn(\n sizeClass,\n !bordered && 'border-0 shadow-none',\n allowClear && 'pr-7',\n prefix && 'pl-7',\n suffix && 'pr-8',\n className,\n )}\n {...rest}\n />\n {suffix ? <span className='absolute right-2 flex text-muted-foreground [&_svg]:size-3.5'>{suffix}</span> : null}\n {allowClear && current ? (\n <button\n type='button'\n aria-label='Clear'\n onClick={() => {\n setInternal('');\n if (onChange) {\n const event = { target: { value: '' } } as unknown as React.ChangeEvent<HTMLInputElement>;\n onChange(event);\n }\n }}\n className='absolute right-2 flex size-4 items-center justify-center rounded-full bg-muted-foreground/30 text-[10px] leading-none text-background hover:bg-muted-foreground/50'\n >\n ✕\n </button>\n ) : null}\n </div>\n );\n});\n\nexport type InputRef = HTMLInputElement;\n","import { cn } from '#lib/utils';\nimport * as React from 'react';\n\nimport { borderlessInputClass } from './shared';\n\nexport const InputNumber: React.FC<{\n value?: number | null;\n defaultValue?: number;\n min?: number;\n max?: number;\n step?: number;\n precision?: number;\n disabled?: boolean;\n size?: 'large' | 'middle' | 'small';\n controls?: boolean;\n variant?: string;\n placeholder?: string;\n className?: string;\n style?: React.CSSProperties;\n onChange?: (value: number | null) => void;\n}> = ({ value, min, max, step, disabled, size, controls, placeholder, className, style, onChange }) => (\n <input\n type='number'\n value={value === undefined || value === null ? '' : value}\n min={min}\n max={max}\n step={step}\n placeholder={placeholder}\n disabled={disabled}\n onChange={(event) => onChange?.(event.target.value === '' ? null : Number(event.target.value))}\n className={cn(\n borderlessInputClass,\n size === 'large' ? 'h-10 text-base' : undefined,\n 'w-full rounded-md border border-input shadow-xs focus-visible:border-ring',\n // controls={false} hides the native spin buttons.\n controls === false &&\n '[appearance:textfield] [&::-webkit-inner-spin-button]:[-webkit-appearance:none] [&::-webkit-outer-spin-button]:[-webkit-appearance:none]',\n className,\n )}\n style={style}\n />\n);\n","'use client';\n\nimport { Button } from '#components/ui/button';\nimport { cn } from '#lib/utils';\nimport { Dialog as DialogPrimitive } from '@base-ui/react/dialog';\nimport { XIcon } from 'lucide-react';\nimport * as React from 'react';\n\nimport { useGrlPortalContainer } from '../../theming/portal-context';\n\nfunction Dialog({ ...props }: React.ComponentProps<typeof DialogPrimitive.Root>) {\n return <DialogPrimitive.Root data-slot='dialog' {...props} />;\n}\n\nfunction DialogTrigger({ ...props }: React.ComponentProps<typeof DialogPrimitive.Trigger>) {\n return <DialogPrimitive.Trigger data-slot='dialog-trigger' {...props} />;\n}\n\nfunction DialogPortal({ ...props }: React.ComponentProps<typeof DialogPrimitive.Portal>) {\n const grlContainer = useGrlPortalContainer();\n return <DialogPrimitive.Portal data-slot='dialog-portal' container={grlContainer} {...props} />;\n}\n\nfunction DialogClose({ ...props }: React.ComponentProps<typeof DialogPrimitive.Close>) {\n return <DialogPrimitive.Close data-slot='dialog-close' {...props} />;\n}\n\nfunction DialogOverlay({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Backdrop>) {\n return (\n <DialogPrimitive.Backdrop\n data-slot='dialog-overlay'\n className={cn(\n 'fixed inset-0 z-50 bg-black/50 transition-opacity duration-200 data-ending-style:opacity-0 data-starting-style:opacity-0',\n className,\n )}\n {...props}\n />\n );\n}\n\nfunction DialogContent({\n className,\n children,\n showCloseButton = true,\n ...props\n}: React.ComponentProps<typeof DialogPrimitive.Popup> & {\n showCloseButton?: boolean;\n}) {\n return (\n <DialogPortal data-slot='dialog-portal'>\n <DialogOverlay />\n <DialogPrimitive.Popup\n data-slot='dialog-content'\n className={cn(\n // box-border: portal mounts under <body>, outside .grl-root, so\n // the scoped preflight's border-box never applies here (HK-14).\n 'box-border fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] -translate-x-1/2 -translate-y-1/2 gap-4 rounded-lg border bg-background p-6 shadow-lg outline-none transition-[opacity,transform] duration-200 data-ending-style:scale-95 data-ending-style:opacity-0 data-starting-style:scale-95 data-starting-style:opacity-0 sm:max-w-lg',\n className,\n )}\n {...props}\n >\n {children}\n {showCloseButton && (\n <DialogPrimitive.Close\n data-slot='dialog-close'\n className=\"absolute top-4 right-4 rounded-xs opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:ring-2 focus:ring-ring focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none data-open:bg-accent data-open:text-muted-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4\"\n >\n <XIcon />\n <span className='sr-only'>Close</span>\n </DialogPrimitive.Close>\n )}\n </DialogPrimitive.Popup>\n </DialogPortal>\n );\n}\n\nfunction DialogHeader({ className, ...props }: React.ComponentProps<'div'>) {\n return (\n <div\n data-slot='dialog-header'\n className={cn('flex flex-col gap-2 text-center sm:text-left', className)}\n {...props}\n />\n );\n}\n\nfunction DialogFooter({\n className,\n showCloseButton = false,\n children,\n ...props\n}: React.ComponentProps<'div'> & {\n showCloseButton?: boolean;\n}) {\n return (\n <div\n data-slot='dialog-footer'\n className={cn('flex flex-col-reverse gap-2 sm:flex-row sm:justify-end', className)}\n {...props}\n >\n {children}\n {showCloseButton && <DialogPrimitive.Close render={<Button variant='outline'>Close</Button>} />}\n </div>\n );\n}\n\nfunction DialogTitle({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Title>) {\n return (\n <DialogPrimitive.Title\n data-slot='dialog-title'\n className={cn('text-lg leading-none font-semibold', className)}\n {...props}\n />\n );\n}\n\nfunction DialogDescription({ className, ...props }: React.ComponentProps<typeof DialogPrimitive.Description>) {\n return (\n <DialogPrimitive.Description\n data-slot='dialog-description'\n className={cn('text-sm text-muted-foreground', className)}\n {...props}\n />\n );\n}\n\nexport {\n Dialog,\n DialogClose,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogOverlay,\n DialogPortal,\n DialogTitle,\n DialogTrigger,\n};\n","import { Button as UiButton } from '#components/ui/button';\nimport { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '#components/ui/dialog';\nimport { cn } from '#lib/utils';\nimport * as React from 'react';\n\nexport const Modal: React.FC<{\n open?: boolean;\n title?: React.ReactNode;\n width?: number | string;\n okText?: React.ReactNode;\n cancelText?: React.ReactNode;\n onOk?: () => void;\n onCancel?: () => void;\n footer?: React.ReactNode | null;\n destroyOnClose?: boolean;\n maskClosable?: boolean;\n centered?: boolean;\n closable?: boolean | Record<string, unknown>;\n okButtonProps?: { danger?: boolean; htmlType?: string; onClick?: () => void; form?: string; disabled?: boolean };\n bodyStyle?: React.CSSProperties;\n getContainer?: () => HTMLElement | false;\n children?: React.ReactNode;\n className?: string;\n}> = ({\n open = false,\n title,\n width = 520,\n okText = 'OK',\n cancelText = 'Cancel',\n onOk,\n onCancel,\n footer,\n destroyOnClose = false,\n centered,\n children,\n className,\n}) => {\n const body = destroyOnClose && !open ? null : children;\n return (\n <Dialog\n open={open}\n onOpenChange={(next) => {\n if (!next) onCancel?.();\n }}\n >\n <DialogContent\n showCloseButton={false}\n className={cn(\n /*\n * Height contract: cap the dialog to the viewport and let ONLY the\n * body scroll, keeping the footer (OK/Cancel) reachable. Radix\n * DialogContent is `fixed top-1/2 -translate-y-1/2`, so without a\n * max-height tall content used to overflow both viewport edges —\n * the Map Excel Data panel was unreachable at its bottom buttons.\n */\n 'grid grid-rows-[auto_minmax(0,1fr)_auto]',\n centered && 'top-[50%]',\n className,\n )}\n style={{\n maxWidth: typeof width === 'number' ? `${width}px` : width,\n maxHeight: 'calc(100dvh - 48px)',\n }}\n >\n {title ? (\n <DialogHeader>\n <DialogTitle>{title}</DialogTitle>\n </DialogHeader>\n ) : null}\n {body ? <div className='min-h-0 overflow-y-auto'>{body}</div> : null}\n {footer !== null ? (\n <DialogFooter className='mt-4'>\n {footer ?? (\n <>\n <UiButton variant='outline' onClick={() => onCancel?.()}>\n {cancelText}\n </UiButton>\n <UiButton onClick={() => onOk?.()}>{okText}</UiButton>\n </>\n )}\n </DialogFooter>\n ) : null}\n </DialogContent>\n </Dialog>\n );\n};\n","import {\n AlertDialog,\n AlertDialogAction,\n AlertDialogCancel,\n AlertDialogContent,\n AlertDialogDescription,\n AlertDialogFooter,\n AlertDialogHeader,\n AlertDialogTitle,\n AlertDialogTrigger,\n} from '#components/ui/alert-dialog';\nimport * as React from 'react';\n\nexport const Popconfirm: React.FC<\n React.HTMLAttributes<HTMLDivElement> & {\n title?: React.ReactNode;\n description?: React.ReactNode;\n okText?: string;\n cancelText?: string;\n onConfirm?: () => void;\n onCancel?: () => void;\n disabled?: boolean;\n children?: React.ReactElement;\n }\n> = ({ title, description, okText = 'OK', cancelText = 'Cancel', onConfirm, onCancel, disabled, children }) => {\n const [open, setOpen] = React.useState(false);\n if (!children) return null;\n return (\n <AlertDialog open={open} onOpenChange={setOpen}>\n {/*\n * Real-DOM wrapper for the trigger: cloning through a non-DOM child\n * (e.g. a Tooltip context wrapping the actual Button — see\n * ImportColumnRow in dt-excel-dialog) drops handlers, so the trigger\n * always renders its own inline span.\n */}\n <AlertDialogTrigger disabled={disabled} render={<span className='inline-flex'>{children}</span>} />\n <AlertDialogContent>\n <AlertDialogHeader>\n <AlertDialogTitle>{title}</AlertDialogTitle>\n {description ? <AlertDialogDescription>{description}</AlertDialogDescription> : null}\n </AlertDialogHeader>\n <AlertDialogFooter>\n <AlertDialogCancel\n onClick={() => {\n onCancel?.();\n setOpen(false);\n }}\n >\n {cancelText}\n </AlertDialogCancel>\n <AlertDialogAction\n onClick={() => {\n onConfirm?.();\n setOpen(false);\n }}\n >\n {okText}\n </AlertDialogAction>\n </AlertDialogFooter>\n </AlertDialogContent>\n </AlertDialog>\n );\n};\n","import { cn } from '#lib/utils';\nimport { Popover as PopoverPrimitive } from '@base-ui/react/popover';\nimport * as React from 'react';\n\nimport { useGrlPortalContainer } from '../../theming/portal-context';\n\nfunction Popover({ ...props }: React.ComponentProps<typeof PopoverPrimitive.Root>) {\n return <PopoverPrimitive.Root data-slot='popover' {...props} />;\n}\n\nfunction PopoverTrigger({ ...props }: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {\n return <PopoverPrimitive.Trigger data-slot='popover-trigger' {...props} />;\n}\n\nfunction PopoverContent({\n className,\n align = 'center',\n alignOffset,\n side = 'bottom',\n sideOffset = 4,\n ...props\n}: React.ComponentProps<typeof PopoverPrimitive.Popup> &\n Pick<PopoverPrimitive.Positioner.Props, 'side' | 'sideOffset' | 'align' | 'alignOffset'>) {\n const grlContainer = useGrlPortalContainer();\n return (\n <PopoverPrimitive.Portal container={grlContainer}>\n <PopoverPrimitive.Positioner side={side} sideOffset={sideOffset} align={align} alignOffset={alignOffset}>\n <PopoverPrimitive.Popup\n data-slot='popover-content'\n className={cn(\n // box-border: portaled nodes live outside .grl-root preflight scope (HK-14).\n 'box-border z-50 w-fit min-w-[18rem] origin-(--transform-origin) rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-hidden transition-[opacity,transform] duration-150 data-ending-style:scale-95 data-ending-style:opacity-0 data-starting-style:scale-95 data-starting-style:opacity-0',\n className,\n )}\n {...props}\n />\n </PopoverPrimitive.Positioner>\n </PopoverPrimitive.Portal>\n );\n}\n\nfunction PopoverHeader({ className, ...props }: React.ComponentProps<'div'>) {\n return <div data-slot='popover-header' className={cn('flex flex-col gap-1 text-sm', className)} {...props} />;\n}\n\nfunction PopoverTitle({ className, ...props }: React.ComponentProps<'h2'>) {\n return <div data-slot='popover-title' className={cn('font-medium', className)} {...props} />;\n}\n\nfunction PopoverDescription({ className, ...props }: React.ComponentProps<'p'>) {\n return <p data-slot='popover-description' className={cn('text-muted-foreground', className)} {...props} />;\n}\n\nexport { Popover, PopoverTrigger, PopoverContent, PopoverHeader, PopoverTitle, PopoverDescription };\n","import {\n Popover as UiPopover,\n PopoverContent as UiPopoverContent,\n PopoverTrigger as UiPopoverTrigger,\n} from '#components/ui/popover';\nimport * as React from 'react';\n\nexport interface PopoverProps {\n open?: boolean;\n defaultOpen?: boolean;\n onOpenChange?: (open: boolean) => void;\n content?: React.ReactNode;\n title?: React.ReactNode;\n trigger?: Array<'click' | 'hover' | 'contextMenu'> | 'click' | 'hover';\n placement?: string;\n destroyTooltipOnHide?: boolean;\n arrow?: boolean;\n overlayClassName?: string;\n disabled?: boolean;\n children?: React.ReactNode;\n}\n\nexport const Popover: React.FC<PopoverProps> = ({ open, onOpenChange, content, children }) => (\n <UiPopover open={open} onOpenChange={onOpenChange}>\n {/*\n * Wrap the child in a real DOM element unconditionally: Base UI\n * `render` merges its handlers into the rendered element, and cloning\n * through a non-DOM subtree (e.g. a Tooltip context provider wrapping a\n * Button — see ImportColumnRow in dt-excel-dialog) silently drops them.\n */}\n <UiPopoverTrigger render={<span className='inline-flex'>{children}</span>} />\n <UiPopoverContent>{content}</UiPopoverContent>\n </UiPopover>\n);\n","import { cn } from '#lib/utils';\nimport * as React from 'react';\n\ninterface RadioContextValue {\n value?: string | number | boolean;\n setValue: (value: string | number | boolean) => void;\n}\n\nconst RadioContext = React.createContext<RadioContextValue>({ setValue: () => {} });\n\nconst RadioGroupRoot: React.FC<{\n value?: string | number | boolean;\n size?: 'large' | 'middle' | 'small';\n disabled?: boolean;\n buttonStyle?: string;\n onChange?: (event: { target: { value: unknown } }) => void;\n className?: string;\n style?: React.CSSProperties;\n children?: React.ReactNode;\n}> = ({ value, disabled, onChange, className, style, children }) => {\n const context = React.useMemo<RadioContextValue>(\n () => ({\n value,\n setValue: (next) => {\n if (!disabled) onChange?.({ target: { value: next } });\n },\n }),\n [value, disabled, onChange],\n );\n\n return (\n <RadioContext.Provider value={context}>\n <div\n role='radiogroup'\n className={cn(\n 'inline-flex rounded-md border bg-muted p-0.5',\n disabled && 'cursor-not-allowed opacity-50',\n className,\n )}\n style={style}\n >\n {children}\n </div>\n </RadioContext.Provider>\n );\n};\n\nconst RadioButton: React.FC<{\n value?: string | number;\n disabled?: boolean;\n className?: string;\n style?: React.CSSProperties;\n children?: React.ReactNode;\n}> = ({ value, disabled, className, style, children }) => {\n const { value: current, setValue } = React.useContext(RadioContext);\n const active = current !== undefined && String(current) === String(value);\n return (\n <button\n type='button'\n disabled={disabled}\n onClick={() => setValue(value!)}\n className={cn(\n 'flex-1 whitespace-nowrap rounded-[4px] px-3 py-1 text-xs transition-colors',\n active ? 'bg-background font-medium shadow-xs' : 'text-muted-foreground hover:text-foreground',\n className,\n )}\n style={style}\n >\n {children}\n </button>\n );\n};\n\nconst RadioItem: React.FC<{\n value?: string | number;\n disabled?: boolean;\n className?: string;\n style?: React.CSSProperties;\n children?: React.ReactNode;\n}> = ({ value, disabled, className, style, children }) => {\n const { value: current, setValue } = React.useContext(RadioContext);\n const active = current !== undefined && String(current) === String(value);\n return (\n <label\n className={cn(\n 'flex cursor-pointer items-center gap-1.5 text-sm',\n active ? 'text-primary' : 'text-foreground',\n disabled && 'cursor-not-allowed opacity-50',\n className,\n )}\n style={style}\n onClick={() => {\n if (!disabled) setValue(value!);\n }}\n >\n <span\n className={cn(\n 'flex size-3.5 items-center justify-center rounded-full border transition-colors',\n active ? 'border-primary' : 'border-input',\n )}\n >\n {active ? <span className='size-2 rounded-full bg-primary' /> : null}\n </span>\n {children}\n </label>\n );\n};\n\nexport const Radio = Object.assign(RadioItem, { Group: RadioGroupRoot, Button: RadioButton });\n\nexport interface RadioGroupProps {\n value?: string | number | boolean;\n disabled?: boolean;\n size?: 'large' | 'middle' | 'small';\n options?: Array<{ label?: React.ReactNode; value: string | number; disabled?: boolean }>;\n onChange?: (event: { target: { value: unknown } }) => void;\n className?: string;\n style?: React.CSSProperties;\n}\n","import { cn } from '#lib/utils';\nimport { Select as SelectPrimitive } from '@base-ui/react/select';\nimport { CheckIcon, ChevronDownIcon, ChevronUpIcon } from 'lucide-react';\nimport * as React from 'react';\n\nimport { useGrlPortalContainer } from '../../theming/portal-context';\n\nfunction Select({ ...props }: React.ComponentProps<typeof SelectPrimitive.Root>) {\n return <SelectPrimitive.Root data-slot='select' {...props} />;\n}\n\nfunction SelectGroup({ ...props }: React.ComponentProps<typeof SelectPrimitive.Group>) {\n return <SelectPrimitive.Group data-slot='select-group' {...props} />;\n}\n\nfunction SelectValue({ ...props }: React.ComponentProps<typeof SelectPrimitive.Value>) {\n return <SelectPrimitive.Value data-slot='select-value' {...props} />;\n}\n\nfunction SelectTrigger({\n className,\n size = 'default',\n children,\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.Trigger> & {\n size?: 'sm' | 'default';\n}) {\n return (\n <SelectPrimitive.Trigger\n data-slot='select-trigger'\n data-size={size}\n className={cn(\n \"flex w-fit items-center justify-between gap-2 rounded-md border border-input bg-transparent px-3 py-2 text-sm whitespace-nowrap shadow-xs transition-[color,box-shadow] outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-destructive/20 data-placeholder:text-muted-foreground data-[size=default]:h-9 data-[size=sm]:h-8 *:data-[slot=select-value]:line-clamp-1 *:data-[slot=select-value]:flex *:data-[slot=select-value]:items-center *:data-[slot=select-value]:gap-2 dark:bg-input/30 dark:hover:bg-input/50 dark:aria-invalid:ring-destructive/40 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground\",\n className,\n )}\n {...props}\n >\n {children}\n <SelectPrimitive.Icon render={<ChevronDownIcon className='size-4 opacity-50' />} />\n </SelectPrimitive.Trigger>\n );\n}\n\nfunction SelectContent({\n className,\n children,\n alignItemWithTrigger = true,\n align = 'center',\n side = 'bottom',\n sideOffset = 0,\n alignOffset,\n ...props\n}: React.ComponentProps<typeof SelectPrimitive.Popup> &\n Pick<SelectPrimitive.Positioner.Props, 'alignItemWithTrigger' | 'side' | 'sideOffset' | 'align' | 'alignOffset'>) {\n const grlContainer = useGrlPortalContainer();\n return (\n <SelectPrimitive.Portal container={grlContainer}>\n <SelectPrimitive.Positioner\n alignItemWithTrigger={alignItemWithTrigger}\n side={side}\n sideOffset={sideOffset}\n align={align}\n alignOffset={alignOffset}\n >\n <SelectPrimitive.Popup\n data-slot='select-content'\n className={cn(\n // box-border: portaled nodes live outside .grl-root preflight scope (HK-14).\n 'box-border relative z-50 max-h-(--available-height) min-w-[8rem] origin-(--transform-origin) overflow-x-hidden overflow-y-auto rounded-md border bg-popover text-popover-foreground shadow-md transition-[opacity,transform] duration-150 data-ending-style:scale-95 data-ending-style:opacity-0 data-starting-style:scale-95 data-starting-style:opacity-0',\n className,\n )}\n {...props}\n >\n <SelectScrollUpButton />\n <SelectPrimitive.List\n className={cn(\n 'p-1',\n alignItemWithTrigger && 'h-(--anchor-height) w-full min-w-(--anchor-width) scroll-my-1',\n )}\n >\n {children}\n </SelectPrimitive.List>\n <SelectScrollDownButton />\n </SelectPrimitive.Popup>\n </SelectPrimitive.Positioner>\n </SelectPrimitive.Portal>\n );\n}\n\nfunction SelectLabel({ className, ...props }: React.ComponentProps<typeof SelectPrimitive.GroupLabel>) {\n return (\n <SelectPrimitive.GroupLabel\n data-slot='select-label'\n className={cn('px-2 py-1.5 text-xs text-muted-foreground', className)}\n {...props}\n />\n );\n}\n\nfunction SelectItem({ className, children, ...props }: React.ComponentProps<typeof SelectPrimitive.Item>) {\n return (\n <SelectPrimitive.Item\n data-slot='select-item'\n className={cn(\n \"relative flex w-full cursor-default items-center gap-2 rounded-sm py-1.5 pr-8 pl-2 text-sm outline-hidden select-none data-disabled:pointer-events-none data-disabled:opacity-50 data-highlighted:bg-accent data-highlighted:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4 [&_svg:not([class*='text-'])]:text-muted-foreground *:[span]:last:flex *:[span]:last:items-center *:[span]:last:gap-2\",\n className,\n )}\n {...props}\n >\n <span data-slot='select-item-indicator' className='absolute right-2 flex size-3.5 items-center justify-center'>\n <SelectPrimitive.ItemIndicator>\n <CheckIcon className='size-4' />\n </SelectPrimitive.ItemIndicator>\n </span>\n <SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>\n </SelectPrimitive.Item>\n );\n}\n\nfunction SelectSeparator({ className, ...props }: React.ComponentProps<typeof SelectPrimitive.Separator>) {\n return (\n <SelectPrimitive.Separator\n data-slot='select-separator'\n className={cn('pointer-events-none -mx-1 my-1 h-px bg-border', className)}\n {...props}\n />\n );\n}\n\nfunction SelectScrollUpButton({ className, ...props }: React.ComponentProps<typeof SelectPrimitive.ScrollUpArrow>) {\n return (\n <SelectPrimitive.ScrollUpArrow\n data-slot='select-scroll-up-button'\n className={cn('flex cursor-default items-center justify-center py-1', className)}\n {...props}\n >\n <ChevronUpIcon className='size-4' />\n </SelectPrimitive.ScrollUpArrow>\n );\n}\n\nfunction SelectScrollDownButton({ className, ...props }: React.ComponentProps<typeof SelectPrimitive.ScrollDownArrow>) {\n return (\n <SelectPrimitive.ScrollDownArrow\n data-slot='select-scroll-down-button'\n className={cn('flex cursor-default items-center justify-center py-1', className)}\n {...props}\n >\n <ChevronDownIcon className='size-4' />\n </SelectPrimitive.ScrollDownArrow>\n );\n}\n\nexport {\n Select,\n SelectContent,\n SelectGroup,\n SelectItem,\n SelectLabel,\n SelectScrollDownButton,\n SelectScrollUpButton,\n SelectSeparator,\n SelectTrigger,\n SelectValue,\n};\n","import {\n SelectContent as SelectPrimitiveContent,\n SelectItem as SelectPrimitiveItem,\n Select as SelectPrimitiveRoot,\n SelectTrigger as SelectPrimitiveTrigger,\n SelectValue as SelectPrimitiveValue,\n} from '#components/ui/select';\nimport { cn } from '#lib/utils';\nimport * as React from 'react';\n\nimport { borderlessInputClass } from './shared';\n\nexport interface SelectOption {\n /** Optional metadata used by the excel-import dialogs */\n id?: string;\n type?: string;\n wrapInQuotes?: boolean;\n /** Extra render node shown in the dropdown list */\n display?: React.ReactNode;\n label?: React.ReactNode;\n value: string | number | boolean;\n disabled?: boolean;\n}\n\nexport interface SelectProps {\n options?: SelectOption[];\n value?: string | number | boolean | Array<string | number>;\n defaultValue?: string | number | boolean | Array<string | number>;\n\n onChange?: (value: any, option?: SelectOption) => void;\n onSelect?: (value: string | number | boolean, option: SelectOption) => void;\n dropdownRender?: (menu: React.ReactNode) => React.ReactNode;\n optionRender?: (option: { data: SelectOption }) => React.ReactNode;\n placeholder?: string;\n disabled?: boolean;\n size?: 'large' | 'middle' | 'small';\n allowClear?: boolean;\n onClear?: () => void;\n optionLabelProp?: string;\n loading?: boolean;\n showSearch?: boolean;\n filterOption?: boolean | ((input: string, option: SelectOption) => boolean);\n mode?: 'multiple' | 'tags';\n variant?: string;\n suffixIcon?: React.ReactNode;\n popupMatchSelectWidth?: boolean | number;\n tokenSeparators?: string[];\n maxCount?: number;\n overlayClassName?: string;\n needConfirm?: boolean;\n className?: string;\n style?: React.CSSProperties;\n}\n\nexport const Select: React.FC<SelectProps> = ({\n options,\n value,\n defaultValue,\n onChange,\n onSelect,\n onClear,\n dropdownRender,\n optionRender,\n placeholder,\n disabled,\n size,\n allowClear,\n loading,\n mode,\n tokenSeparators: _tokenSeparators,\n suffixIcon,\n popupMatchSelectWidth: _popupMatchSelectWidth,\n variant: _variant,\n showSearch: _showSearch,\n filterOption: _filterOption,\n optionLabelProp: _optionLabelProp,\n maxCount: _maxCount,\n className,\n style,\n}) => {\n const list = options ?? [];\n const current = value === undefined || value === null ? undefined : String(value);\n const selected = list.find((option) => String(option.value) === current);\n\n if (mode === 'multiple' || mode === 'tags') {\n const arrayValue = Array.isArray(value) ? (value as Array<string | number>) : [];\n return (\n <input\n value={arrayValue.join(', ')}\n placeholder={placeholder}\n disabled={disabled || loading}\n onChange={(event) =>\n onChange?.(\n event.target.value\n .split(',')\n .map((part) => part.trim())\n .filter(Boolean),\n )\n }\n className={cn(borderlessInputClass, 'w-full rounded-md border border-input shadow-xs', className)}\n style={style}\n />\n );\n }\n\n const menu = (\n <>\n {list.map((option) => (\n <SelectPrimitiveItem key={String(option.value)} value={String(option.value)} disabled={option.disabled}>\n {optionRender ? optionRender({ data: option }) : (option.label ?? String(option.value))}\n </SelectPrimitiveItem>\n ))}\n </>\n );\n\n return (\n <div className='relative inline-flex w-full items-center'>\n <SelectPrimitiveRoot\n value={current}\n defaultValue={defaultValue === undefined ? undefined : String(defaultValue)}\n onValueChange={(next) => {\n if (allowClear && next === current) return;\n const option = list.find((item) => String(item.value) === next) ?? ({} as SelectOption);\n const raw = option.value ?? next;\n onSelect?.(raw, option);\n onChange?.(raw, option);\n }}\n disabled={disabled || loading}\n >\n <SelectPrimitiveTrigger\n className={cn(\n 'w-full justify-between',\n size === 'large' ? 'h-10 text-base' : size === 'small' ? 'h-8 text-xs' : undefined,\n allowClear && !!current && '[&>svg:last-child]:hidden',\n // compat semantics: suffixIcon={null} means no trailing icon.\n suffixIcon === null && '[&>svg:last-child]:hidden',\n className,\n )}\n style={style}\n >\n {/* Base UI Value renders children unconditionally (radix gated them\n on a selected value), so the never-reached placeholder-span\n fallback is intentionally dropped — behavior preserved. */}\n <SelectPrimitiveValue>{selected?.label}</SelectPrimitiveValue>\n </SelectPrimitiveTrigger>\n <SelectPrimitiveContent alignItemWithTrigger={false}>\n {dropdownRender ? dropdownRender(menu) : menu}\n </SelectPrimitiveContent>\n </SelectPrimitiveRoot>\n {allowClear && current ? (\n <button\n type='button'\n aria-label='Clear'\n onClick={() => {\n onClear?.();\n onChange?.(undefined, undefined);\n }}\n className='absolute right-7 flex size-3.5 items-center justify-center rounded-full bg-muted-foreground/30 text-[10px] leading-none text-background hover:bg-muted-foreground/50'\n >\n ✕{' '}\n </button>\n ) : null}\n </div>\n );\n};\n","import { cn } from '#lib/utils';\nimport * as React from 'react';\n\nexport type SpaceProps = React.HTMLAttributes<HTMLDivElement> & {\n size?: number | [number, number] | 'small' | 'middle' | 'large';\n direction?: 'horizontal' | 'vertical';\n wrap?: boolean;\n};\n\nexport const Space: React.FC<SpaceProps> = ({\n size = 8,\n direction = 'horizontal',\n wrap,\n className,\n style,\n ...rest\n}) => {\n const resolved = size === 'small' ? 8 : size === 'middle' ? 16 : size === 'large' ? 24 : size;\n const gap = Array.isArray(resolved) ? `${resolved[1]}px ${resolved[0]}px` : `${resolved}px`;\n return (\n <div\n className={cn(\n direction === 'vertical' ? 'flex flex-col' : 'flex flex-row items-center',\n wrap && (direction === 'vertical' ? '' : 'flex-wrap'),\n className,\n )}\n style={{ gap, ...style }}\n {...rest}\n />\n );\n};\n","import { cn } from '#lib/utils';\nimport { Loader2 } from 'lucide-react';\nimport * as React from 'react';\n\nexport const Spin: React.FC<\n React.HTMLAttributes<HTMLDivElement> & {\n size?: 'large' | 'default' | 'small';\n spinning?: boolean;\n children?: React.ReactNode;\n }\n> = ({ size = 'default', spinning = true, children, className, style, ...rest }) => {\n const spinnerClass = size === 'large' ? 'size-8' : size === 'small' ? 'size-4' : 'size-6';\n\n if (!children) {\n return (\n <div\n role='status'\n className={cn('flex w-full items-center justify-center p-2', className)}\n style={style}\n {...rest}\n >\n <Loader2 className={cn('animate-spin text-muted-foreground', spinnerClass)} />\n </div>\n );\n }\n\n if (!spinning) {\n return <>{children}</>;\n }\n\n return (\n <div className={cn('relative', className)} style={style} {...rest}>\n {children}\n <div className='absolute inset-0 z-10 flex items-center justify-center rounded-(--grl-border-radius) bg-background/60'>\n <Loader2 className={cn('animate-spin text-muted-foreground', spinnerClass)} />\n </div>\n </div>\n );\n};\n","import { cn } from '#lib/utils';\nimport * as React from 'react';\n\nexport const Steps: React.FC<{\n current?: number;\n items?: Array<{ title?: React.ReactNode; description?: React.ReactNode }>;\n}> = ({ current = 0, items = [] }) => (\n <div className='flex w-full items-center'>\n {items.map((item, index) => {\n const state = index < current ? 'done' : index === current ? 'active' : 'pending';\n return (\n <React.Fragment key={index}>\n {index > 0 ? <div className={cn('h-px flex-1', state === 'pending' ? 'bg-border' : 'bg-primary')} /> : null}\n <div className='flex items-center gap-2 px-2'>\n <span\n className={cn(\n 'flex size-6 shrink-0 items-center justify-center rounded-full text-xs font-medium',\n state === 'done' && 'bg-primary text-primary-foreground',\n state === 'active' && 'border-2 border-primary text-primary',\n state === 'pending' && 'border border-border text-muted-foreground',\n )}\n >\n {index + 1}\n </span>\n {item.title ? (\n <span\n className={cn(\n 'whitespace-nowrap text-xs',\n state === 'pending' ? 'text-muted-foreground' : 'font-medium text-foreground',\n )}\n >\n {item.title}\n </span>\n ) : null}\n </div>\n </React.Fragment>\n );\n })}\n </div>\n);\n","import { cn } from '#lib/utils';\nimport { Switch as SwitchPrimitive } from '@base-ui/react/switch';\nimport * as React from 'react';\n\nfunction Switch({\n className,\n size = 'default',\n ...props\n}: React.ComponentProps<typeof SwitchPrimitive.Root> & {\n size?: 'sm' | 'default';\n}) {\n return (\n <SwitchPrimitive.Root\n data-slot='switch'\n data-size={size}\n className={cn(\n 'peer group/switch inline-flex shrink-0 items-center rounded-full border border-transparent shadow-xs transition-all outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 data-disabled:cursor-not-allowed data-disabled:opacity-50 data-[size=default]:h-[1.15rem] data-[size=default]:w-8 data-[size=sm]:h-3.5 data-[size=sm]:w-6 data-checked:bg-primary data-unchecked:bg-input dark:data-unchecked:bg-input/80',\n className,\n )}\n {...props}\n >\n <SwitchPrimitive.Thumb\n data-slot='switch-thumb'\n className={cn(\n 'pointer-events-none block rounded-full bg-background ring-0 transition-transform group-data-[size=default]/switch:size-4 group-data-[size=sm]/switch:size-3 data-checked:translate-x-[calc(100%-2px)] data-unchecked:translate-x-0 dark:data-checked:bg-primary-foreground dark:data-unchecked:bg-foreground',\n )}\n />\n </SwitchPrimitive.Root>\n );\n}\n\nexport { Switch };\n","import { Switch as UiSwitch } from '#components/ui/switch';\nimport { cn } from '#lib/utils';\nimport * as React from 'react';\n\nexport interface SwitchProps {\n checked?: boolean;\n defaultChecked?: boolean;\n disabled?: boolean;\n size?: 'default' | 'small';\n className?: string;\n style?: React.CSSProperties;\n onChange?: (checked: boolean) => void;\n checkedChildren?: React.ReactNode;\n unCheckedChildren?: React.ReactNode;\n}\n\nexport const Switch: React.FC<SwitchProps> = ({\n checked,\n defaultChecked,\n disabled,\n size,\n className,\n style,\n onChange,\n}) => (\n <UiSwitch\n checked={checked === undefined ? undefined : !!checked}\n defaultChecked={defaultChecked}\n disabled={disabled}\n onCheckedChange={(next) => onChange?.(next === true)}\n className={cn(size === 'small' && 'data-checked:translate-x-3.5 h-4 w-7 [&_span]:size-3', className)}\n style={style}\n />\n);\n","'use client';\n\nimport { cn } from '#lib/utils';\nimport { Tabs as TabsPrimitive } from '@base-ui/react/tabs';\nimport { type VariantProps, cva } from 'class-variance-authority';\nimport * as React from 'react';\n\nfunction Tabs({ className, orientation = 'horizontal', ...props }: React.ComponentProps<typeof TabsPrimitive.Root>) {\n return (\n <TabsPrimitive.Root\n data-slot='tabs'\n data-orientation={orientation}\n orientation={orientation}\n className={cn('group/tabs flex gap-2 data-[orientation=horizontal]:flex-col', className)}\n {...props}\n />\n );\n}\n\nconst tabsListVariants = cva(\n 'group/tabs-list inline-flex w-fit items-center justify-center rounded-lg p-[3px] text-muted-foreground group-data-[orientation=horizontal]/tabs:h-9 group-data-[orientation=vertical]/tabs:h-fit group-data-[orientation=vertical]/tabs:flex-col data-[variant=line]:rounded-none',\n {\n variants: {\n variant: {\n default: 'bg-muted',\n line: 'gap-1 bg-transparent',\n },\n },\n defaultVariants: {\n variant: 'default',\n },\n },\n);\n\nfunction TabsList({\n className,\n variant = 'default',\n ...props\n}: React.ComponentProps<typeof TabsPrimitive.List> & VariantProps<typeof tabsListVariants>) {\n return (\n <TabsPrimitive.List\n data-slot='tabs-list'\n data-variant={variant}\n className={cn(tabsListVariants({ variant }), className)}\n {...props}\n />\n );\n}\n\nfunction TabsTrigger({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.Tab>) {\n return (\n <TabsPrimitive.Tab\n data-slot='tabs-trigger'\n className={cn(\n \"relative inline-flex h-[calc(100%-1px)] flex-1 items-center justify-center gap-1.5 rounded-md border border-transparent px-2 py-1 text-sm font-medium whitespace-nowrap text-foreground/60 transition-all group-data-[orientation=vertical]/tabs:w-full group-data-[orientation=vertical]/tabs:justify-start hover:text-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-1 focus-visible:outline-ring aria-disabled:pointer-events-none aria-disabled:opacity-50 group-data-[variant=default]/tabs-list:data-active:shadow-sm group-data-[variant=line]/tabs-list:data-active:shadow-none dark:text-muted-foreground dark:hover:text-foreground [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4\",\n 'group-data-[variant=line]/tabs-list:bg-transparent group-data-[variant=line]/tabs-list:data-active:bg-transparent dark:group-data-[variant=line]/tabs-list:data-active:border-transparent dark:group-data-[variant=line]/tabs-list:data-active:bg-transparent',\n 'data-active:bg-background data-active:text-foreground dark:data-active:border-input dark:data-active:bg-input/30 dark:data-active:text-foreground',\n 'after:absolute after:bg-foreground after:opacity-0 after:transition-opacity group-data-[orientation=horizontal]/tabs:after:inset-x-0 group-data-[orientation=horizontal]/tabs:after:bottom-[-5px] group-data-[orientation=horizontal]/tabs:after:h-0.5 group-data-[orientation=vertical]/tabs:after:inset-y-0 group-data-[orientation=vertical]/tabs:after:-right-1 group-data-[orientation=vertical]/tabs:after:w-0.5 group-data-[variant=line]/tabs-list:data-active:after:opacity-100',\n className,\n )}\n {...props}\n />\n );\n}\n\nfunction TabsContent({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.Panel>) {\n return <TabsPrimitive.Panel data-slot='tabs-content' className={cn('flex-1 outline-none', className)} {...props} />;\n}\n\nexport { Tabs, TabsList, TabsTrigger, TabsContent, tabsListVariants };\n","import { Tabs as UiTabs } from '#components/ui/tabs';\nimport { TabsContent as UiTabsContent } from '#components/ui/tabs';\nimport { TabsList as UiTabsList } from '#components/ui/tabs';\nimport { TabsTrigger as UiTabsTrigger } from '#components/ui/tabs';\nimport { cn } from '#lib/utils';\nimport * as React from 'react';\n\nexport interface TabsItemType {\n key: string;\n label: React.ReactNode;\n children?: React.ReactNode;\n disabled?: boolean;\n}\n\nexport interface TabsProps {\n items?: TabsItemType[];\n activeKey?: string;\n defaultActiveKey?: string;\n onChange?: (key: string) => void;\n type?: 'line' | 'card' | 'editable-card';\n size?: 'large' | 'middle' | 'small';\n className?: string;\n rootClassName?: string;\n style?: React.CSSProperties;\n tabBarExtraContent?: React.ReactNode;\n}\n\nexport const Tabs: React.FC<TabsProps> = ({\n items,\n activeKey,\n defaultActiveKey,\n onChange,\n size,\n className,\n rootClassName,\n style,\n tabBarExtraContent,\n}) => {\n const list = items ?? [];\n const [uncontrolled, setUncontrolled] = React.useState<string>(defaultActiveKey ?? list[0]?.key ?? '');\n const current = activeKey ?? uncontrolled;\n /*\n * Compact inline-tab rhythm (formerly .grl-inline-tabs in tailwind.css,\n * HK-02): expressed as utilities on the DOM we own instead of `!important`\n * overrides fighting injected styles. Transitional detection keeps the\n * three call sites unchanged; prefer passing explicit props going forward.\n */\n const compact = rootClassName?.includes('grl-inline-tabs') ?? false;\n\n const select = (key: string) => {\n if (activeKey === undefined) setUncontrolled(key);\n onChange?.(key);\n };\n\n return (\n <UiTabs value={current} onValueChange={select} style={style} className={cn(rootClassName, className)}>\n <div className='flex w-full items-center justify-between gap-2'>\n {/* compat semantics: antd-era tabs activate on arrow-key focus;\n Base UI defaults to manual activation, so re-enable it here. */}\n <UiTabsList activateOnFocus className={cn(size === 'small' && 'h-8', compact && 'm-0 p-0!')}>\n {list.map((item) => (\n <UiTabsTrigger\n key={item.key}\n value={item.key}\n disabled={item.disabled}\n className={cn(compact && 'px-3.5 text-[13px]')}\n >\n {item.label}\n </UiTabsTrigger>\n ))}\n </UiTabsList>\n {tabBarExtraContent}\n </div>\n {list.map((item) => (\n <UiTabsContent\n key={item.key}\n value={item.key}\n // compat semantics: items without children carry no panel content.\n // Keep the node mounted (Radix/tests may query it) but hide it so\n // shadcn's `flex gap-2` root injects no phantom gap below a\n // standalone bar.\n className={cn(item.children === undefined && 'hidden!')}\n >\n {item.children}\n </UiTabsContent>\n ))}\n </UiTabs>\n );\n};\n","import { cn } from '#lib/utils';\nimport * as React from 'react';\n\nexport const Tag: React.FC<{\n className?: string;\n style?: React.CSSProperties;\n children?: React.ReactNode;\n}> = ({ className, style, children }) => (\n <span className={cn('inline-flex items-center gap-1 rounded-sm px-1.5 py-0.5 text-xs', className)} style={style}>\n {children}\n </span>\n);\n","'use client';\n\nimport { cn } from '#lib/utils';\nimport { Tooltip as TooltipPrimitive } from '@base-ui/react/tooltip';\nimport * as React from 'react';\n\nimport { useGrlPortalContainer } from '../../theming/portal-context';\n\nfunction TooltipProvider({ delay = 0, ...props }: React.ComponentProps<typeof TooltipPrimitive.Provider>) {\n return <TooltipPrimitive.Provider data-slot='tooltip-provider' delay={delay} {...props} />;\n}\n\nfunction Tooltip({ ...props }: React.ComponentProps<typeof TooltipPrimitive.Root>) {\n return <TooltipPrimitive.Root data-slot='tooltip' {...props} />;\n}\n\nfunction TooltipTrigger({ ...props }: React.ComponentProps<typeof TooltipPrimitive.Trigger>) {\n return <TooltipPrimitive.Trigger data-slot='tooltip-trigger' {...props} />;\n}\n\nfunction TooltipContent({\n className,\n sideOffset = 0,\n side,\n align,\n alignOffset,\n children,\n ...props\n}: React.ComponentProps<typeof TooltipPrimitive.Popup> &\n Pick<TooltipPrimitive.Positioner.Props, 'side' | 'sideOffset' | 'align' | 'alignOffset'>) {\n const grlContainer = useGrlPortalContainer();\n return (\n <TooltipPrimitive.Portal container={grlContainer}>\n <TooltipPrimitive.Positioner side={side} sideOffset={sideOffset} align={align} alignOffset={alignOffset}>\n <TooltipPrimitive.Popup\n data-slot='tooltip-content'\n className={cn(\n // box-border: portaled nodes live outside .grl-root preflight scope (HK-14).\n 'box-border z-50 w-fit origin-(--transform-origin) rounded-md bg-foreground px-3 py-1.5 text-xs text-balance text-background shadow-md transition-[opacity,transform] duration-150 data-ending-style:scale-95 data-ending-style:opacity-0 data-starting-style:scale-95 data-starting-style:opacity-0',\n className,\n )}\n {...props}\n >\n {children}\n <TooltipPrimitive.Arrow className='z-50 size-2.5 translate-y-[calc(-50%_-_2px)] rotate-45 rounded-[2px] bg-foreground fill-foreground' />\n </TooltipPrimitive.Popup>\n </TooltipPrimitive.Positioner>\n </TooltipPrimitive.Portal>\n );\n}\n\nexport { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider };\n","import {\n TooltipContent as UiTooltipContent,\n TooltipProvider as UiTooltipProvider,\n Tooltip as UiTooltipRoot,\n TooltipTrigger as UiTooltipTrigger,\n} from '#components/ui/tooltip';\nimport * as React from 'react';\n\nconst placementSideMap: Record<string, 'top' | 'right' | 'bottom' | 'left'> = {\n top: 'top',\n bottom: 'bottom',\n left: 'left',\n right: 'right',\n topLeft: 'top',\n topRight: 'top',\n bottomLeft: 'bottom',\n bottomRight: 'bottom',\n};\n\nexport const Tooltip: React.FC<\n React.HTMLAttributes<HTMLDivElement> & {\n title?: React.ReactNode;\n placement?: keyof typeof placementSideMap;\n open?: boolean;\n children?: React.ReactNode;\n }\n> = ({ title, placement = 'top', children }) => {\n if (!title || !children) {\n return <>{children}</>;\n }\n return (\n <UiTooltipProvider delay={200}>\n <UiTooltipRoot>\n <UiTooltipTrigger\n render={React.isValidElement(children) ? children : <span className='inline-flex'>{children}</span>}\n />\n <UiTooltipContent side={placementSideMap[placement] ?? 'top'}>{title}</UiTooltipContent>\n </UiTooltipRoot>\n </UiTooltipProvider>\n );\n};\n","import { cn } from '#lib/utils';\nimport * as React from 'react';\n\nconst typoColorClass: Record<string, string> = {\n secondary: 'text-muted-foreground',\n success: 'text-[var(--grl-color-success)]',\n warning: 'text-[var(--grl-color-warning)]',\n danger: 'text-[var(--destructive)]',\n};\n\ntype Ellipsis = boolean | { tooltip?: React.ReactNode };\n\ninterface TextProps extends React.HTMLAttributes<HTMLSpanElement> {\n type?: keyof typeof typoColorClass;\n ellipsis?: Ellipsis;\n strong?: boolean;\n}\n\nconst resolveEllipsisTitle = (ellipsis: Ellipsis | undefined) => {\n if (!ellipsis || typeof ellipsis !== 'object') return undefined;\n const tooltip = ellipsis.tooltip;\n if (typeof tooltip === 'string' || typeof tooltip === 'number') return String(tooltip);\n return undefined;\n};\n\nconst Text: React.FC<TextProps> = ({ type, ellipsis, strong, className, style, children, ...rest }) => (\n <span\n title={resolveEllipsisTitle(ellipsis)}\n className={cn(\n 'inline-block max-w-full align-bottom',\n ellipsis && 'truncate',\n strong && 'font-semibold',\n typoColorClass[type ?? ''],\n className,\n )}\n style={style}\n {...rest}\n >\n {children}\n </span>\n);\n\nconst titleLevelClass: Record<number, string> = {\n 1: 'text-2xl font-bold',\n 2: 'text-xl font-bold',\n 3: 'text-lg font-semibold',\n 4: 'text-base font-semibold',\n 5: 'text-sm font-semibold',\n};\n\ninterface TitleProps extends React.HTMLAttributes<HTMLHeadingElement> {\n level?: 1 | 2 | 3 | 4 | 5;\n}\n\nconst Title: React.FC<TitleProps> = ({ level = 1, className, ...rest }) => {\n const Tag = `h${Math.min(Math.max(level, 1), 5)}` as 'h1' | 'h2' | 'h3' | 'h4' | 'h5';\n return <Tag className={cn(titleLevelClass[level], 'm-0', className)} {...rest} />;\n};\n\nconst Paragraph: React.FC<TextProps> = ({ type, className, ...rest }) => (\n <p className={cn(typoColorClass[type ?? ''], className)} {...rest} />\n);\n\ninterface LinkProps extends React.AnchorHTMLAttributes<HTMLAnchorElement> {\n type?: keyof typeof typoColorClass;\n ellipsis?: Ellipsis;\n}\n\nconst Link: React.FC<LinkProps> = ({ type, ellipsis, className, children, ...rest }) => (\n <a\n title={resolveEllipsisTitle(ellipsis)}\n className={cn(\n 'cursor-pointer underline-offset-4 hover:underline',\n ellipsis && 'inline-block max-w-full truncate align-bottom',\n typoColorClass[type ?? ''],\n className,\n )}\n {...rest}\n >\n {children}\n </a>\n);\n\nexport const Typography = Object.assign(({ children }: { children?: React.ReactNode }) => <>{children}</>, {\n Text,\n Title,\n Paragraph,\n Link,\n});\n","import initWasm, { isReady } from '@gorules/zen-engine-wasm';\nimport { useEffect, useState } from 'react';\n\nlet wasmAvailable = false;\nlet wasmInitPromise: Promise<void> | null = null;\nconst wasmListeners = new Set<() => void>();\n\nexport const isWasmAvailable = () => {\n if (wasmAvailable) {\n return true;\n }\n\n try {\n if (isReady()) {\n wasmAvailable = true;\n return wasmAvailable;\n }\n } catch {\n return false;\n }\n};\n\nexport const ensureWasmLoaded = (): Promise<void> => {\n if (isWasmAvailable()) {\n return Promise.resolve();\n }\n\n if (!wasmInitPromise) {\n // Explicit relative URL: resolves against document.baseURI so it works in\n // the dev server (root) and the Pages project sub-path. The glue's\n // import.meta.url default resolves to a build-asset URL that 404s on the\n // static site, and the staticDirs convention uses an absolute path that\n // 404s under https://republicroad.github.io/jdm-editor/.\n const wasmUrl = new URL('zen-engine-wasm/zen_engine_wasm_bg.wasm', document.baseURI).href;\n wasmInitPromise = initWasm({ module_or_path: wasmUrl })\n .then(() => {\n wasmAvailable = true;\n wasmListeners.forEach((fn) => fn());\n wasmListeners.clear();\n })\n .catch(() => {\n wasmInitPromise = null;\n });\n }\n\n return wasmInitPromise;\n};\n\nexport const useWasmReady = (): boolean => {\n const [ready, setReady] = useState(() => !!isWasmAvailable());\n\n useEffect(() => {\n if (isWasmAvailable()) {\n setReady(true);\n return;\n }\n\n const listener = () => setReady(true);\n wasmListeners.add(listener);\n ensureWasmLoaded();\n\n return () => {\n wasmListeners.delete(listener);\n };\n }, []);\n\n return ready;\n};\n","/*\n * Minimal sRGB ↔ OKLab conversion (Björn Ottosson's public-domain matrices),\n * zero dependencies. Enough surface for hue-preserving palette derivation\n * (roadmap P0 phase-2): roundtrip error stays within ±1/255 per channel.\n */\n\ntype Rgb = [number, number, number];\n\nconst srgbToLinearCh = (c: number): number => {\n const v = c / 255;\n return v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;\n};\n\nconst linearToSrgbCh = (v: number): number => {\n const c = v <= 0.0031308 ? v * 12.92 : 1.055 * v ** (1 / 2.4) - 0.055;\n return Math.round(Math.max(0, Math.min(1, c)) * 255);\n};\n\nexport const hexToRgb = (hex: string): Rgb => {\n const n = parseInt(hex.replace('#', ''), 16);\n return [(n >> 16) & 255, (n >> 8) & 255, n & 255];\n};\n\nexport const rgbToHex = ([r, g, b]: Rgb): string =>\n `#${[r, g, b]\n // quantize here by contract: hex is an integer format, so callers may pass\n // fractional channels (e.g. rgba compositing) without producing garbage hex\n .map((x) => Math.round(x).toString(16).padStart(2, '0'))\n .join('')}`;\n\nexport type OkLab = { L: number; a: number; b: number };\n\nexport const hexToOkLab = (hex: string): OkLab => {\n const [r, g, b] = hexToRgb(hex).map(srgbToLinearCh) as Rgb;\n\n const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b);\n const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b);\n const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b);\n\n return {\n L: 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s,\n a: 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s,\n b: 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s,\n };\n};\n\nexport const okLabToHex = ({ L, a, b }: OkLab): string => {\n const l = (L + 0.3963377774 * a + 0.2158037573 * b) ** 3;\n const m = (L - 0.1055613458 * a - 0.0638541728 * b) ** 3;\n const s = (L - 0.0894841775 * a - 1.291485548 * b) ** 3;\n\n const r = 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s;\n const g = -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s;\n const bb = -0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s;\n\n return rgbToHex([linearToSrgbCh(r), linearToSrgbCh(g), linearToSrgbCh(bb)]);\n};\n\nexport type Oklch = { L: number; C: number; H: number };\n\nexport const okLabToOklch = ({ L, a, b }: OkLab): Oklch => ({\n L,\n C: Math.sqrt(a * a + b * b),\n H: ((Math.atan2(b, a) * 180) / Math.PI + 360) % 360,\n});\n\nexport const oklchToOkLab = ({ L, C, H }: Oklch): OkLab => {\n const rad = (H * Math.PI) / 180;\n return { L, a: C * Math.cos(rad), b: C * Math.sin(rad) };\n};\n\n/** Convenience: hex → polar form. */\nexport const hexToOklch = (hex: string): Oklch => okLabToOklch(hexToOkLab(hex));\n\n/** Polar form → hex. Derived palette colors stay near the calibrated in-gamut anchors,\n * so no gamut search is needed; CM clamps at conversion time anyway. */\nexport const oklchToHex = (c: Oklch): string => okLabToHex(oklchToOkLab(c));\n\n/** Shortest signed delta between two hues, in degrees (-180..180]. */\nexport const hueDelta = (fromH: number, toH: number): number => {\n let d = ((((toH - fromH) % 360) + 540) % 360) - 180;\n if (d === -180) d = 180;\n return d;\n};\n\n/* ── WCAG 2.x contrast helpers ────────────────────────────────────────────\n * Used by the theming contrast assertions (contrast.test.ts) so palette\n * derivation cannot ship text pairs below accessibility thresholds. */\n\n/** Composite an sRGB channel value over an opaque background (per channel). */\nconst compositeChannel = (fg: number, alpha: number, bg: number): number => fg * alpha + bg * (1 - alpha);\n\n/** Parse `#rgb`/`#rrggbb` or `rgba()/rgb()` strings into rgba quadruples. */\nexport const parseColor = (value: string): [number, number, number, number] => {\n const v = value.trim();\n if (v.startsWith('#')) {\n const rgb = hexToRgb(v);\n return [rgb[0], rgb[1], rgb[2], 1];\n }\n const m = v.match(/rgba?\\(([^)]+)\\)/i);\n if (!m) return [0, 0, 0, 1];\n const parts = m[1]\n .split(/[,\\s/]+/)\n .filter(Boolean)\n .map(parseFloat);\n return [parts[0], parts[1], parts[2], parts.length > 3 ? parts[3] : 1];\n};\n\n/** Flatten any color (incl. rgba) onto an opaque background, returning hex. */\nexport const flattenOver = (fg: string, bgHex: string): string => {\n const [r, g, b, a] = parseColor(fg);\n const bg = hexToRgb(bgHex);\n return rgbToHex([\n Math.round(compositeChannel(r, a, bg[0])),\n Math.round(compositeChannel(g, a, bg[1])),\n Math.round(compositeChannel(b, a, bg[2])),\n ]);\n};\n\nconst channelLuminance = (c: number): number => {\n const v = c / 255;\n return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;\n};\n\n/** WCAG relative luminance of a hex color. */\nexport const relativeLuminance = (hex: string): number => {\n const [r, g, b] = hexToRgb(hex).map(channelLuminance);\n return 0.2126 * r + 0.7152 * g + 0.0722 * b;\n};\n\n/** WCAG 2.x contrast ratio (1..21) between two colors; rgba flattened first. */\nexport const contrastRatio = (fg: string, bg: string): number => {\n const fgSolid = flattenOver(fg, bg);\n const l1 = relativeLuminance(fgSolid);\n const l2 = relativeLuminance(bg);\n const [hi, lo] = l1 >= l2 ? [l1, l2] : [l2, l1];\n return (hi + 0.05) / (lo + 0.05);\n};\n","/*\n * AUTO-GENERATED by scripts/calibrate-dark (offline run, 2026-08 Batch F).\n * Per-key anchors letting dark-mode brand families follow a custom seed:\n * oh — hue offset from the family default dark seed to the frozen key hue\n * lMul — OKLab-L multiplier (bright variants only), frozen_L / defSeed_L\n * cMul — chroma ratio kept constant across seeds for bright variants\n * Regenerate rather than hand-edit.\n */\nexport type DarkOp = { oh: number; ls?: boolean; lMul?: number; cMul?: number };\n\nexport const DARK_OPS: Record<string, DarkOp> = {\n colorPrimaryHover: {\n oh: -3.49,\n ls: true,\n lMul: 1.1631,\n },\n colorPrimaryActive: {\n oh: -37.45,\n ls: true,\n lMul: 1.2542,\n },\n colorPrimaryBg: {\n oh: 4.46,\n cMul: 0.197,\n },\n colorPrimaryBgHover: {\n oh: 0.52,\n ls: true,\n lMul: 0.4933,\n },\n colorPrimaryBorder: {\n oh: -1.38,\n cMul: 0.421,\n },\n colorPrimaryBorderHover: {\n oh: -4.77,\n ls: true,\n lMul: 0.9999,\n },\n colorPrimaryTextHover: {\n oh: -3.49,\n ls: true,\n lMul: 1.1631,\n },\n colorSuccessBg: {\n oh: 0.27,\n cMul: 0.187,\n },\n colorSuccessBorder: {\n oh: -4.95,\n cMul: 0.525,\n },\n colorErrorBg: {\n oh: -9.71,\n cMul: 0.19,\n },\n colorErrorBorder: {\n oh: -3.23,\n cMul: 0.498,\n },\n colorWarningBg: {\n oh: 2.01,\n cMul: 0.212,\n },\n colorWarningBorder: {\n oh: 4.91,\n cMul: 0.469,\n },\n colorWarningText: {\n oh: 0,\n ls: true,\n lMul: 1,\n },\n};\n","const fontFamily =\n \"-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif\";\n\n/* Frozen compat-calibrated palettes + mode-scoped constants.\n * Golden-guarded by theming/__tests__/derive.test.ts —\n * do not hand-edit without re-running that suite.\n */\n\nexport const MODE_EXTRAS: Record<'light' | 'dark', { borderHover: string; borderFade: string; primaryBgFade: string }> =\n {\n light: { borderHover: '#c3c3c3', borderFade: '#eef0f5', primaryBgFade: '#f8fafc' },\n dark: { borderHover: '#555555', borderFade: '#333333', primaryBgFade: '#141414' },\n };\n\n/** Golden preset (compat-calibrated). Exported for the derive golden test; do\n * not hand-edit without re-running `src/theme/__tests__/derive.test.ts`. */\nexport const lightTokens: Record<string, string | number> = {\n colorPrimary: '#1677ff',\n colorPrimaryHover: '#4096ff',\n colorPrimaryActive: '#0958d9',\n colorPrimaryBg: '#e6f4ff',\n colorPrimaryBgHover: '#bae0ff',\n colorPrimaryBorder: '#91caff',\n colorPrimaryBorderHover: '#69b1ff',\n colorPrimaryTextHover: '#4096ff',\n colorSuccess: '#52c41a',\n colorSuccessBg: '#f6ffed',\n colorSuccessBorder: '#b7eb8f',\n colorError: '#ff4d4f',\n colorErrorBg: '#fff2f0',\n colorErrorBorder: '#ffccc7',\n colorWarning: '#faad14',\n colorWarningBg: '#fffbe6',\n colorWarningBorder: '#ffe58f',\n colorWarningText: '#d48806',\n colorInfo: '#1677ff',\n colorInfoBg: '#e6f4ff',\n colorInfoBorder: '#91caff',\n colorInfoText: '#1677ff',\n /* Field pills / excel column chips (P1 tokenized literals, formerly\n * inline #acccec family — see GRL-STYLE-HACK HK-10..12). */\n colorFieldInput: '#acccec',\n colorFieldInputHover: '#8ab8de',\n colorFieldOutput: '#c7e0ba',\n colorFieldOutputHover: '#a8cc96',\n colorTextLightSolid: '#ffffff',\n colorBgLayout: '#f5f5f5',\n colorBgMask: 'rgba(0, 0, 0, 0.45)',\n colorBgElevated: '#ffffff',\n colorBgContainer: '#ffffff',\n colorBgContainerDisabled: 'rgba(0, 0, 0, 0.04)',\n colorBgTextHover: 'rgba(0, 0, 0, 0.06)',\n colorBorder: '#d9d9d9',\n colorText: 'rgba(0, 0, 0, 0.88)',\n colorTextPlaceholder: 'rgba(0, 0, 0, 0.25)',\n colorTextBase: '#000000',\n colorTextDisabled: 'rgba(0, 0, 0, 0.25)',\n colorTextSecondary: 'rgba(0, 0, 0, 0.65)',\n controlOutline: 'rgba(5, 145, 255, 0.1)',\n fontFamily,\n lineHeight: 1.5714285714285714,\n borderRadius: 6,\n};\n\nexport const darkTokens: Record<string, string | number> = {\n ...lightTokens,\n colorPrimary: '#1668dc',\n colorPrimaryHover: '#3c89e8',\n colorPrimaryActive: '#11a8cd',\n colorPrimaryBg: '#111a2c',\n colorPrimaryBgHover: '#112545',\n colorPrimaryBorder: '#15325b',\n colorPrimaryBorderHover: '#3170b9',\n colorPrimaryTextHover: '#3c89e8',\n colorSuccess: '#49aa19',\n colorSuccessBg: '#162312',\n colorSuccessBorder: '#274902',\n colorError: '#dc4446',\n colorErrorBg: '#2c1618',\n colorErrorBorder: '#58181c',\n colorWarning: '#d89614',\n colorWarningBg: '#2b2111',\n colorWarningBorder: '#594214',\n colorWarningText: '#d89614',\n colorInfo: '#1668dc',\n colorInfoBg: '#111a2c',\n colorInfoBorder: '#15325b',\n colorInfoText: '#1668dc',\n colorBgLayout: '#000000',\n colorBgElevated: '#1d1d1d',\n colorBgContainer: '#141414',\n colorBgContainerDisabled: 'rgba(255, 255, 255, 0.08)',\n colorBgTextHover: 'rgba(255, 255, 255, 0.08)',\n colorBorder: '#424242',\n colorText: 'rgba(255, 255, 255, 0.85)',\n colorTextPlaceholder: 'rgba(255, 255, 255, 0.25)',\n colorTextBase: '#ffffff',\n colorTextDisabled: 'rgba(255, 255, 255, 0.25)',\n colorTextSecondary: 'rgba(255, 255, 255, 0.65)',\n controlOutline: 'rgba(22, 104, 220, 0.25)',\n};\n","/*\n * Seed-derived theming (roadmap P0, zero-dependency).\n *\n * Architecture agreed 2026-08 (\"double track\"):\n * - DEFAULT preset: the hand-calibrated compat tables in `theme.tsx` win\n * byte-for-byte. Nothing about existing rendering changes.\n * - CUSTOM seeds: hosts pass `JdmConfigProvider seeds={{primary, ...}}` and a\n * linear-light mix ladder derives the brand families in light mode;\n * dark mode follows seeds via OKLab hue/lightness transforms. Ladder ratios were\n * reverse-calibrated offline against the compat tables (see golden test);\n * channels land within a few 1/255 steps of the frozen defaults for the\n * default seeds — close enough for re-branded installs,\n * while the defaults never route through it.\n *\n * Phase-2 (Batch F): DARK brand families follow seeds too, via OKLab\n * hue-rotation + lightness scaling around the calibrated anchors in\n * dark-ops.ts — zero-dependency OKLab math lives in color.ts. surfaces are family-independent navy constants in the compat tables and do\n * not decompose into seed mixes (offline spread > 0.6). Dark mode therefore\n * keeps its calibrated constants until P0 phase 2 introduces an OKLCH model.\n */\nimport { hexToOklch, oklchToHex } from './color';\nimport { DARK_OPS } from './dark-ops';\nimport { darkTokens } from './presets';\n\ntype ThemeModeLite = 'light' | 'dark';\n\ntype Rgb = [number, number, number];\n\nconst hexToRgb = (hex: string): Rgb => {\n const n = parseInt(hex.replace('#', ''), 16);\n return [(n >> 16) & 255, (n >> 8) & 255, n & 255];\n};\n\nconst toLinear = (c: number): number => {\n const v = c / 255;\n return v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;\n};\n\nconst toSrgb = (v: number): number => {\n const c = v <= 0.0031308 ? v * 12.92 : 1.055 * v ** (1 / 2.4) - 0.055;\n return Math.round(Math.max(0, Math.min(1, c)) * 255);\n};\n\nconst rgbToHex = ([r, g, b]: Rgb): string =>\n `#${[r, g, b].map((x) => toSrgb(x).toString(16).padStart(2, '0')).join('')}`;\n\n/** Linear-light lerp between `from`/`to` anchors expressed as hex. */\nexport const mixLinear = (fromHex: string, toHex: '#000000' | '#ffffff', t: number): string => {\n const a = hexToRgb(fromHex).map(toLinear) as Rgb;\n const b = hexToRgb(toHex).map(toLinear) as Rgb;\n const out = a.map((ch, i) => ch * (1 - t) + b[i] * t) as Rgb;\n return rgbToHex(out);\n};\n\n/**\n * Per-key ladder for LIGHT brand families.\n * Ratios solved offline so that deriving FROM the default seeds reproduces the\n * compat tables within `CALIBRATION_TOLERANCES` (≤ ~30/255 worst-case on one\n * channel — recorded honestly, not hidden behind the helper).\n */\nexport const LIGHT_LADDER: Record<string, { anchor: '#ffffff' | '#000000'; t: number }> = {\n // primary family (#1677ff)\n colorPrimaryHover: { anchor: '#ffffff', t: 0.096 },\n colorPrimaryBg: { anchor: '#ffffff', t: 0.836 },\n colorPrimaryBgHover: { anchor: '#ffffff', t: 0.587 },\n colorPrimaryBorder: { anchor: '#ffffff', t: 0.388 },\n colorPrimaryBorderHover: { anchor: '#ffffff', t: 0.224 },\n colorPrimaryActive: { anchor: '#000000', t: 0.479 },\n // success family (#52c41a)\n colorSuccessBg: { anchor: '#ffffff', t: 0.92 },\n colorSuccessBorder: { anchor: '#ffffff', t: 0.438 },\n // error family (#ff4d4f)\n colorErrorBg: { anchor: '#ffffff', t: 0.87 },\n colorErrorBorder: { anchor: '#ffffff', t: 0.553 },\n // warning family (#faad14)\n colorWarningBg: { anchor: '#ffffff', t: 0.91 },\n colorWarningBorder: { anchor: '#ffffff', t: 0.633 },\n colorWarningText: { anchor: '#000000', t: 0.487 },\n // field pill hovers (seeds added in P1)\n colorFieldInputHover: { anchor: '#000000', t: 0.24 },\n colorFieldOutputHover: { anchor: '#000000', t: 0.294 },\n};\n\n/** Seeds accepted by the public provider API. */\nexport type ThemeSeeds = {\n primary?: string;\n success?: string;\n error?: string;\n warning?: string;\n info?: string;\n fieldInput?: string;\n fieldOutput?: string;\n};\n\n/** compat-calibrated defaults: passing EXACTLY these equals passing nothing,\n * keeping the frozen preset byte-identical instead of route-through-derived. */\n/** compat-calibrated LIGHT defaults (families + pill pairs). */\n/** compat-calibrated LIGHT defaults (families + pill pairs). */\nexport const DEFAULT_SEEDS: Required<\n Pick<ThemeSeeds, 'primary' | 'success' | 'error' | 'warning' | 'fieldInput' | 'fieldOutput'>\n> = {\n primary: '#1677ff',\n success: '#52c41a',\n error: '#ff4d4f',\n warning: '#faad14',\n fieldInput: '#acccec',\n fieldOutput: '#c7e0ba',\n};\n\n/** Family seeds behind the calibrated DARK preset. */\nexport const DARK_DEF_SEEDS: Record<'primary' | 'success' | 'error' | 'warning', string> = {\n primary: '#1668dc',\n success: '#49aa19',\n error: '#dc4446',\n warning: '#d89614',\n};\n\n/** Family seeds behind the calibrated DARK preset. */\nfunction isDefaultSeedSet(mode: ThemeModeLite, seeds: ThemeSeeds): boolean {\n const defaults =\n mode === 'dark' ? (DARK_DEF_SEEDS as Record<string, string>) : (DEFAULT_SEEDS as Record<string, string>);\n const entries = Object.entries(seeds).filter(([, v]) => v !== undefined);\n if (entries.length === 0) return true;\n if (mode === 'dark') {\n // only family keys matter on the dark axis\n return entries.every(([k, v]) => (DARK_DEF_SEEDS as Record<string, string>)[k] === v);\n }\n return entries.every(([k, v]) => defaults[k] === v);\n}\n\nconst FAMILY_SEED_KEYS = ['primary', 'success', 'error', 'warning'] as const;\n\nfunction deriveDark({ seeds, out }: Required<Pick<DeriveArgs, 'seeds'>> & { out: Record<string, string> }): void {\n const familyOf = (baseKey: string) =>\n FAMILY_SEED_KEYS.find(\n (f) => baseKey.toLowerCase() === `color${f}` || baseKey.toLowerCase().startsWith(`color${f}`),\n )!;\n\n const applyDarkOps = (baseKey: string, seedHex: string) => {\n const seedLch = hexToOklch(seedHex);\n const defL = hexToOklch(DARK_DEF_SEEDS[familyOf(baseKey)]).L;\n // bright variants track the seed's lightness; surfaces keep frozen L\n const lr = clamp(seedLch.L / defL, 0.85, 1.18);\n\n for (const [tokenKey, op] of Object.entries(DARK_OPS)) {\n if (!tokenKey.startsWith(baseKey)) continue;\n const frozen = hexToOklch(String(darkTokens[tokenKey]));\n const L = op.ls ? clamp(frozen.L * lr, 0.12, 0.92) : frozen.L;\n const C = op.cMul !== undefined ? clamp(seedLch.C * op.cMul, 0.01, 0.14) : frozen.C;\n const H = (seedLch.H + op.oh + 360) % 360;\n out[tokenKey] = oklchToHex({ L, C, H });\n }\n };\n\n for (const family of FAMILY_SEED_KEYS) {\n const seed = (seeds as Record<string, string | undefined>)[family];\n if (!seed) continue;\n const cap = family[0].toUpperCase() + family.slice(1);\n out[`color${cap}`] = seed;\n applyDarkOps(`color${cap}`, seed);\n }\n\n if (seeds.info) {\n const sInfo = hexToOklch(seeds.info);\n out.colorInfo = seeds.info;\n out.colorInfoText = seeds.info;\n for (const [tokenKey, op] of Object.entries(DARK_OPS)) {\n if (!tokenKey.startsWith('colorPrimary')) continue;\n const target = tokenKey.replace('colorPrimary', 'colorInfo');\n const frozen = hexToOklch(String(darkTokens[target]));\n const bgLike = /bg|border/i.test(target);\n out[target] = oklchToHex({\n L: frozen.L,\n C: op.cMul ? Math.min(0.14, Math.max(0.01, sInfo.C * op.cMul)) : frozen.C,\n H: (sInfo.H + op.oh + 360) % 360,\n });\n void bgLike;\n }\n }\n}\n\nfunction clamp(v: number, min: number, max: number): number {\n return Math.min(max, Math.max(min, v));\n}\n\nexport type DeriveArgs = {\n mode: 'light' | 'dark';\n seeds?: ThemeSeeds;\n};\n\n/**\n * Overlay derivable brand-family values onto a base token set.\n * Light mode only in v1 (see module header); dark mode ignores seeds.\n * Derived output never overrides keys the host passed through `token=`.\n */\nexport const deriveSeedOverlays = ({ mode, seeds }: DeriveArgs): Record<string, string> => {\n if (!seeds || isDefaultSeedSet(mode, seeds)) {\n return {};\n }\n\n const out: Record<string, string> = {};\n\n if (mode === 'dark') {\n deriveDark({ seeds, out });\n return out;\n }\n\n const applyFamily = (family: string, seed: string) => {\n // the base key IS the seed itself (ladder only covers derivatives)\n const cap = family[0].toUpperCase() + family.slice(1);\n out[`color${cap}`] = seed;\n for (const [tokenKey, op] of Object.entries(LIGHT_LADDER)) {\n if (!tokenKey.toLowerCase().startsWith(`color${family}`.toLowerCase())) continue;\n out[tokenKey] = mixLinear(seed, op.anchor, op.t);\n }\n };\n\n for (const family of FAMILY_SEED_KEYS) {\n const seed = (seeds as Record<string, string | undefined>)[family];\n if (seed) applyFamily(family, seed);\n }\n\n // info mirrors the primary ladder against its own seed\n if (seeds.info) {\n out.colorInfo = seeds.info;\n out.colorInfoText = seeds.info;\n out.colorInfoBg = mixLinear(seeds.info, '#ffffff', LIGHT_LADDER.colorPrimaryBg.t);\n out.colorInfoBorder = mixLinear(seeds.info, '#ffffff', LIGHT_LADDER.colorPrimaryBorder.t);\n }\n\n if (seeds.fieldInput) {\n out.colorFieldInputHover = mixLinear(\n seeds.fieldInput,\n LIGHT_LADDER.colorFieldInputHover.anchor,\n LIGHT_LADDER.colorFieldInputHover.t,\n );\n }\n if (seeds.fieldOutput) {\n out.colorFieldOutputHover = mixLinear(\n seeds.fieldOutput,\n LIGHT_LADDER.colorFieldOutputHover.anchor,\n LIGHT_LADDER.colorFieldOutputHover.t,\n );\n }\n\n return out;\n};\n\n/**\n * Worst accepted post-gamma channel deltas when deriving from the DEFAULT\n * seeds (measured by scripts/probe during calibration; guarded by golden test).\n */\nexport const CALIBRATION_TOLERANCES: Record<string, number> = {\n colorPrimaryHover: 26,\n colorPrimaryBg: 6,\n colorPrimaryBgHover: 16,\n colorPrimaryBorder: 23,\n colorPrimaryBorderHover: 27,\n colorPrimaryActive: 38,\n colorSuccessBg: 9,\n colorSuccessBorder: 35,\n colorErrorBg: 3,\n colorErrorBorder: 3,\n colorWarningBg: 15,\n // warningBorder spread 0.73 offline — worst ladder member; border blends are\n // visually forgiving at pale tints.\n colorWarningBorder: 66,\n // warningText mutes saturation as well as lightness; a one-axis mix cannot\n // nail it (Δ_red 26 at the default seed) — tolerance recorded honestly.\n colorWarningText: 27,\n colorFieldInputHover: 14,\n colorFieldOutputHover: 12,\n};\n","/*\n * Token computation entry (roadmap P0/P4): pure, testable, framework-free.\n *\n * Merge order: calibrated preset ← seed derivation ← explicit overrides.\n * The playground story consumes this directly; GlobalCssVariables is a thin\n * renderer over it. Hex values are the per-mode compat-calibrated presets in\n * presets.ts; seeds only overlay brand families (see derive.ts for the\n * ladder / dark limitation notes).\n */\nimport { type ThemeSeeds, deriveSeedOverlays } from './derive';\nimport { MODE_EXTRAS, darkTokens, lightTokens } from './presets';\n\nexport type ThemeMode = 'light' | 'dark';\n\nconst NODE_COLORS: Record<string, string> = {\n '--node-color-blue': 'var(--grl-color-primary)',\n '--node-color-purple': '#7c4dff',\n '--node-color-orange': '#f76d40',\n '--node-color-green': '#10ac84',\n};\n\n/** Compute the full `--grl-*` map for a mode/seeds/overrides combination. */\nexport const computeTheme = (\n mode: ThemeMode,\n seeds?: ThemeSeeds,\n overrides?: Record<string, unknown>,\n): Record<string, string> => {\n const base = mode === 'dark' ? darkTokens : lightTokens;\n const derived = deriveSeedOverlays({ mode, seeds });\n const t: Record<string, string | number> = {\n ...base,\n ...derived,\n ...(overrides as Record<string, string | number>),\n };\n const extras = MODE_EXTRAS[mode];\n\n return {\n '--grl-color-border': String(t.colorBorder),\n '--grl-color-border-hover': extras.borderHover,\n '--grl-color-border-fade': extras.borderFade,\n '--grl-color-primary': String(t.colorPrimary),\n ...NODE_COLORS,\n '--grl-color-primary-bg': String(t.colorPrimaryBg),\n '--grl-color-primary-bg-fade': extras.primaryBgFade,\n '--grl-color-primary-bg-hover': String(t.colorPrimaryBgHover),\n '--grl-color-primary-border': String(t.colorPrimaryBorder),\n '--grl-color-primary-border-hover': String(t.colorPrimaryBorderHover),\n '--grl-color-primary-text-hover': String(t.colorPrimaryTextHover),\n '--grl-color-success': String(t.colorSuccess),\n '--grl-color-success-bg': String(t.colorSuccessBg),\n '--grl-color-success-border': String(t.colorSuccessBorder),\n '--grl-color-error': String(t.colorError),\n '--grl-color-error-bg': String(t.colorErrorBg),\n '--grl-color-error-border': String(t.colorErrorBorder),\n '--grl-color-warning': String(t.colorWarning),\n '--grl-color-warning-bg': String(t.colorWarningBg),\n '--grl-color-warning-border': String(t.colorWarningBorder),\n '--grl-color-warning-text': String(t.colorWarningText),\n '--grl-color-info': String(t.colorInfo),\n '--grl-color-info-bg': String(t.colorInfoBg),\n '--grl-color-info-border': String(t.colorInfoBorder),\n '--grl-color-info-text': String(t.colorInfoText),\n '--grl-color-field-input': String(t.colorFieldInput),\n '--grl-color-field-input-hover': String(t.colorFieldInputHover),\n '--grl-color-field-output': String(t.colorFieldOutput),\n '--grl-color-field-output-hover': String(t.colorFieldOutputHover),\n '--grl-color-text-light-solid': String(t.colorTextLightSolid),\n '--grl-color-bg-layout': String(t.colorBgLayout),\n '--grl-color-bg-mask': String(t.colorBgMask),\n '--grl-color-bg-elevated': String(t.colorBgElevated),\n '--grl-color-bg-container': String(t.colorBgContainer),\n '--grl-color-bg-container-disabled': String(t.colorBgContainerDisabled),\n '--grl-color-bg-text-hover': String(t.colorBgTextHover),\n '--grl-color-primary-hover': String(t.colorPrimaryHover),\n '--grl-color-primary-active': String(t.colorPrimaryActive),\n '--grl-color-text': String(t.colorText),\n '--grl-color-text-placeholder': String(t.colorTextPlaceholder),\n '--grl-color-text-base': String(t.colorTextBase),\n '--grl-color-text-disabled': String(t.colorTextDisabled),\n '--grl-color-text-secondary': String(t.colorTextSecondary),\n // L2 removal (docs/grl-var-flatten.md): --grl-primary-color(-bg) were\n // exact duplicates of --grl-color-primary(-bg) with zero in-repo\n // consumers; removed with a host migration checklist in that doc.\n '--grl-control-outline': String(t.controlOutline),\n '--grl-font-family': String(t.fontFamily),\n '--grl-line-height': String(t.lineHeight),\n '--grl-border-radius': `${t.borderRadius}px`,\n // raw `--` passthroughs keep host escape-hatch semantics\n ...Object.fromEntries(\n Object.entries(overrides ?? {})\n .filter(([key]) => key.startsWith('--'))\n .map(([key, value]) => [key, String(value)]),\n ),\n };\n};\n","/**\n * Zero-dependency i18n infrastructure (Provider injection, roadmap Option A).\n *\n * Design:\n * - English messages are the source of truth (`TranslationKey` derives from it)\n * - `I18nProvider` resolves translations via fallback chain:\n * consumer overrides → locale messages → English → key itself\n * - `useT()` returns a translate function with `{{param}}` interpolation\n * - Locale switching is a simple context value change (no re-render storm)\n */\n\n/** Flat dot-notation message key, e.g. `'dt.toolbar.import'`. */\nexport type TranslationKey = string;\n\n/** Simple `{{param}}` interpolation parameters. */\nexport type InterpolationParams = Record<string, string | number>;\n\n/** Full message catalog for a single locale. */\nexport type MessageCatalog = Record<string, string>;\n\n/** Parse `{{param}}` placeholders in a template string. */\nexport function interpolate(template: string, params?: InterpolationParams): string {\n if (!params) return template;\n return template.replace(/\\{\\{(\\w+)\\}\\}/g, (_, key) =>\n params[key] !== undefined ? String(params[key]) : `{{${key}}}`,\n );\n}\n","/**\n * English message catalog — source of truth for all user-visible strings.\n * Keys use flat dot notation: `{component}.{context}.{element}`.\n * Chinese translation lives in `zh-CN.ts`.\n */\nexport const en = {\n // ── common ──\n 'common.ok': 'OK',\n 'common.cancel': 'Cancel',\n 'common.remove': 'Remove',\n 'common.delete': 'Delete',\n 'common.retry': 'Retry',\n 'common.close': 'Close',\n 'common.update': 'Update',\n 'common.create': 'Create',\n 'common.convert': 'Convert',\n 'common.format': 'Format',\n 'common.recover': 'Recover',\n 'common.copy': 'Copy',\n\n // ── decision table ──\n 'dt.toolbar.import': 'Import Excel',\n 'dt.toolbar.export': 'Export Excel',\n 'dt.toolbar.addRowAbove': 'Add row above',\n 'dt.toolbar.addRowBelow': 'Add row below',\n 'dt.toolbar.removeRow': 'Remove row',\n 'dt.toolbar.removeRowConfirm': 'Remove row?',\n 'dt.table.column': 'Table column',\n 'dt.table.excelColumn': 'Excel column',\n 'dt.table.selectExcelColumn': 'Select Excel column',\n 'dt.table.description': 'Description',\n 'dt.table.selectDescription': 'Select Excel column for description',\n 'dt.table.reorderFields': 'Reorder fields',\n\n // ── field edit ──\n 'dt.field.input.add': 'Add Input',\n 'dt.field.input.label': 'Input Field',\n 'dt.field.output.add': 'Add Output',\n 'dt.field.output.label': 'Output Field',\n 'dt.field.label': 'Field label',\n 'dt.field.name': 'Name',\n 'dt.field.type': 'Field Type',\n 'dt.field.outputType': 'Output Type',\n 'dt.field.editColumn': 'Edit column',\n 'dt.field.removeColumn': 'Remove column',\n 'dt.field.removeConfirm': 'Remove this column?',\n 'dt.field.wrapQuotes': 'Wrap values in quotes',\n 'dt.field.selectDictionary': 'Select dictionary...',\n 'dt.field.allowCustomValues': 'Allow custom values',\n 'dt.toolbar.simulationIndex': 'Simulation index:',\n\n // ── excel dialog ──\n 'dt.excel.title': 'Map Excel data',\n 'dt.excel.input': 'Input',\n 'dt.excel.output': 'Output',\n 'dt.excel.enterFieldName': 'Enter field name',\n\n // ── decision graph ──\n 'dg.node.decisionTables': 'Decision Tables',\n 'dg.node.expressions': 'Expressions',\n 'dg.node.functions': 'Functions',\n 'dg.node.editExpression': 'Edit Expression',\n // ── version history (appshell panel, kernel catalog) ──\n 'vh.title': 'Version history',\n 'vh.description.some': '{{count}} version(s). Restoring loads that version as the current one.',\n 'vh.description.none': 'No versions yet. Each save creates one.',\n 'vh.loading': 'Loading…',\n 'vh.filter.label': 'Filter versions',\n 'vh.filter.placeholder': 'Filter by name or revision…',\n 'vh.filter.noMatch': 'No versions match \"{{query}}\".',\n 'vh.noChanges': 'No changes',\n 'vh.changes': 'changes',\n 'vh.entry.current': 'current',\n 'vh.entry.auto': 'auto',\n 'vh.entry.pinned': 'pinned',\n 'vh.restore': 'Restore',\n 'vh.rename.title': 'Rename version',\n 'vh.rename.aria': 'Rename version {{revision}}',\n 'vh.name.aria': 'Name version {{revision}}',\n 'vh.name.placeholder': 'Version name',\n 'vh.name.button': 'Name',\n 'vh.pin.title': 'Pin version',\n 'vh.pin.aria': 'Pin version {{revision}}',\n 'vh.unpin.title': 'Unpin version',\n 'vh.unpin.aria': 'Unpin version {{revision}}',\n 'vh.compare.button': 'Compare',\n 'vh.compare.title': 'Compare against this version on the canvas',\n 'vh.compare.aria': 'Compare against version {{revision}}',\n 'vh.compare.exit.button': 'Exit compare',\n 'vh.compare.exit.title': 'Exit compare mode',\n 'vh.compare.exit.aria': 'Exit compare (was against {{revision}})',\n 'vh.compare.entry': 'comparing',\n 'dg.toolbar.uploadJson': 'Upload JSON',\n 'dg.toolbar.uploadExcel': 'Upload Excel',\n 'dg.toolbar.downloadJson': 'Download JSON',\n 'dg.toolbar.downloadExcel': 'Download Excel',\n 'dg.toolbar.searchNodes': 'Search nodes',\n 'dg.toolbar.closeClose': 'Close panel',\n 'dg.toolbar.schema': 'JSON Schema',\n 'dg.tabs.close': 'Close',\n 'dg.tabs.closeAll': 'Close all Tabs',\n 'dg.tabs.closeOthers': 'Close other Tabs',\n 'dg.tabs.closeRight': 'Close Tabs to the right',\n 'dg.tabs.closeLeft': 'Close Tabs to the left',\n 'dg.jsonSchema.title': 'Convert to JSON Schema',\n 'dg.jsonSchema.copyJson': 'Copy JSON',\n 'dg.node.documentation': 'Documentation',\n 'dg.node.duplicate': 'Duplicate',\n 'dg.node.deleteNode': 'Delete node',\n 'dg.schema.formatCode': 'Format code',\n 'dg.schema.importFromJson': 'Import from JSON',\n 'dg.excel.wrapQuotes': 'Wrap value in quotes',\n 'dg.excel.enterFieldName': 'Enter field name',\n 'dg.condition.removeConfirm': 'Remove condition?',\n\n // ── expression ──\n 'expression.placeholder': 'Expression',\n 'expression.key': 'Key',\n 'expression.addRowAbove': 'Add row above',\n 'expression.addRowBelow': 'Add row below',\n\n // ── function ──\n 'func.debugger.copy': 'Copy to clipboard',\n 'func.debugger.copied': 'Copied to clipboard',\n 'func.debugger.formatCode': 'Format code',\n 'func.debugger.importLibrary': 'Import library',\n 'func.debugger.goToDocs': 'Go to documentation',\n 'func.debugger.msSinceRun': 'Time since start of execution of script.',\n 'misc.search': 'Search...',\n 'func.preview.noResults': 'Run simulation to see the results',\n\n // ── safe boundary ──\n 'safe.title': 'Something went wrong',\n 'safe.retry': 'Retry',\n\n // ── request node ──\n 'request': 'Request',\n 'request.dataLabel': 'Example data',\n 'request.dataSourceSaved': 'Data saved',\n 'request.dataTypeMismatchWarning':\n 'The current request data type does not match the definitions. To change the definition, update it in Definitions.',\n 'request.downloadJsonNoData': 'No data available to download',\n 'request.jsonInvalidError': 'Enter valid JSON or JSON5',\n 'request.jsonObjectError': 'Enter a JSON object',\n 'request.saveDataSourceFailed': 'Failed to save data',\n 'request.selectDataSourceFirst': 'Select a data first',\n 'request.typeArray': 'Array',\n 'request.typeBoolean': 'Boolean',\n 'request.typeDatetime': 'Datetime',\n 'request.typeNumber': 'Number',\n 'request.typeObject': 'Object',\n 'request.typeString': 'String',\n 'request.uploadJsonFailed': 'Failed to upload JSON',\n 'request.uploadJsonObjectRequired': 'Uploaded JSON must be an object',\n 'request.uploadJsonSuccess': 'JSON uploaded successfully',\n\n 'request.key': 'Key',\n 'request.type': 'Type',\n 'request.description': 'Description',\n 'request.save': 'Save',\n 'request.schema': 'Schema',\n 'request.addChildField': 'Add child field',\n 'request.addDataSource': 'Add data',\n 'request.addField': 'Add field',\n 'request.childFieldNamePlaceholder': 'Child field name',\n 'request.createDataSource': 'Create data',\n 'request.definitionsTab': 'Definitions',\n 'request.deleteDataSourceConfirm': 'Delete this data?',\n 'request.deleteFieldConfirm': 'Delete this field?',\n 'request.downloadJsonTooltip': 'Download JSON for the current data ',\n 'request.exampleDescriptionPlaceholder': 'Add example description...',\n 'request.exampleFieldSummary': 'Field summary',\n 'request.exampleFieldSummaryAllMatch': 'Fields match definitions',\n 'request.exampleFieldSummaryConflicts': 'Type conflicts',\n 'request.exampleFieldSummaryDefinitions': 'Defined fields',\n 'request.exampleFieldSummaryExtra': 'Extra fields',\n 'request.exampleFieldSummaryMissing': 'Missing fields',\n 'request.examplesTab': 'Data',\n 'request.fieldDefaultValuePlaceholder': 'Default value',\n 'request.fieldDescriptionPlaceholder': 'Field description',\n 'request.fieldNamePlaceholder': 'Field name',\n 'request.formatSchema': 'Format schema',\n 'request.noDataSources': 'No data',\n 'request.noDefinitions': 'No field definitions',\n 'request.schemaPriorityTooltip':\n 'Schema has the highest priority. Definitions and example data sync into schema, but schema remains the source of truth.',\n 'request.simulateTooltip': 'Open simulator',\n 'request.toggleFieldDescriptionsTooltip': 'Toggle field description hints',\n 'request.uploadJsonTooltip': 'Upload JSON for the current data',\n\n // ── custom function ──\n 'cf.key': 'Key',\n 'cf.expression': 'Expression',\n 'cf.function': 'Function',\n 'cf.code': 'Code',\n 'cf.legacy': 'Legacy',\n 'cf.addRow': 'Add Row',\n\n // ── simulator ──\n 'simulator.boundRequestNodeNotFound': 'Bound request node not found',\n 'simulator.requestMustBeObjectToSave': 'The current request must be a JSON object to save',\n 'simulator.description':\n 'Your business context that enters through the Request node, starting the decision process. Supply JSON or JSON5 format.',\n 'simulator.currentBinding': 'Current binding',\n 'simulator.nodeRequired': 'Request node is required to run the graph. Drag-and-drop it from the Components panel.',\n 'simulator.run': 'Run',\n 'simulator.formatSuccess': 'Formatted successfully!',\n 'simulator.formatFailed': 'Failed to format. Invalid JSON format.',\n 'simulator.nothingToCopy': 'Nothing to copy.',\n 'simulator.copiedToClipboard': 'Copied to clipboard!',\n 'simulator.copyFailedInvalidJson': 'Failed to copy. Invalid JSON format.',\n 'simulator.dataRequiredBeforeRun': 'The current request is empty. Please add example data first.',\n 'simulator.invalidFormatTitle': 'Invalid request format',\n 'simulator.invalidFormatDescription': 'Enter a valid JSON or JSON5 object before running.',\n 'simulator.searchPlaceholder': 'Search nodes...',\n 'simulator.clear': 'Clear',\n 'simulator.readyTitle': 'Ready to simulate!',\n 'simulator.readyHint': 'Run a request to see the node trace in action.',\n 'simulator.learnMore': 'Learn more',\n\n // ── misc ──\n 'common.clear': 'Clear',\n 'misc.delete': 'Delete',\n} as const;\n\nexport type TranslationKey = keyof typeof en;\n","/** Chinese (Simplified) message catalog — 全量对译。 */\nexport const zhCN: Record<string, string> = {\n 'common.ok': '确定',\n 'common.cancel': '取消',\n 'common.remove': '移除',\n 'common.delete': '删除',\n 'common.retry': '重试',\n 'common.close': '关闭',\n 'common.update': '更新',\n 'common.create': '创建',\n 'common.convert': '转换',\n 'common.format': '格式化',\n 'common.recover': '恢复',\n 'common.copy': '复制',\n\n 'dt.toolbar.import': '导入 Excel',\n 'dt.toolbar.export': '导出 Excel',\n 'dt.toolbar.addRowAbove': '在上方添加行',\n 'dt.toolbar.addRowBelow': '在下方添加行',\n 'dt.toolbar.removeRow': '删除行',\n 'dt.toolbar.removeRowConfirm': '确定删除该行?',\n 'dt.table.column': '表格列',\n 'dt.table.excelColumn': 'Excel 列',\n 'dt.table.selectExcelColumn': '选择 Excel 列',\n 'dt.table.description': '描述',\n 'dt.table.selectDescription': '选择描述对应的 Excel 列',\n 'dt.table.reorderFields': '调整字段顺序',\n\n 'dt.field.input.add': '添加输入',\n 'dt.field.input.label': '输入字段',\n 'dt.field.output.add': '添加输出',\n 'dt.field.output.label': '输出字段',\n 'dt.field.label': '字段标签',\n 'dt.field.name': '名称',\n 'dt.field.type': '字段类型',\n 'dt.field.outputType': '输出类型',\n 'dt.field.editColumn': '编辑列',\n 'dt.field.removeColumn': '移除列',\n 'dt.field.removeConfirm': '确定移除该列?',\n 'dt.field.wrapQuotes': '值用引号包裹',\n 'dt.field.selectDictionary': '选择字典...',\n 'dt.field.allowCustomValues': '允许自定义值',\n 'dt.toolbar.simulationIndex': '仿真索引:',\n\n 'dt.excel.title': '映射 Excel 数据',\n 'dt.excel.input': '输入',\n 'dt.excel.output': '输出',\n 'dt.excel.enterFieldName': '输入字段名',\n\n 'dg.node.decisionTables': '决策表',\n 'dg.node.expressions': '表达式',\n 'dg.node.functions': '函数',\n 'dg.node.editExpression': '编辑表达式',\n 'vh.title': '版本历史',\n 'vh.description.some': '{{count}} 个版本。恢复会将该版本载入为当前版本。',\n 'vh.description.none': '暂无版本。保存后创建第一个版本。',\n 'vh.loading': '加载中…',\n 'vh.filter.label': '筛选版本',\n 'vh.filter.placeholder': '按名称或版本号筛选…',\n 'vh.filter.noMatch': '没有匹配“{{query}}”的版本。',\n 'vh.noChanges': '无变化',\n 'vh.changes': '处变更',\n 'vh.entry.current': '当前',\n 'vh.entry.auto': '自动',\n 'vh.entry.pinned': '已钉住',\n 'vh.restore': '恢复',\n 'vh.rename.title': '重命名版本',\n 'vh.rename.aria': '重命名版本 {{revision}}',\n 'vh.name.aria': '命名版本 {{revision}}',\n 'vh.name.placeholder': '版本名称',\n 'vh.name.button': '命名',\n 'vh.pin.title': '钉住版本',\n 'vh.pin.aria': '钉住版本 {{revision}}',\n 'vh.unpin.title': '取消钉住',\n 'vh.unpin.aria': '取消钉住版本 {{revision}}',\n 'vh.compare.button': '对比',\n 'vh.compare.title': '在画布上与该版本对比',\n 'vh.compare.aria': '与版本 {{revision}} 对比',\n 'vh.compare.exit.button': '退出对比',\n 'vh.compare.exit.title': '退出对比模式',\n 'vh.compare.exit.aria': '退出对比(此前对比 {{revision}})',\n 'vh.compare.entry': '对比中',\n 'dg.toolbar.uploadJson': '上传 JSON',\n 'dg.toolbar.uploadExcel': '上传 Excel',\n 'dg.toolbar.downloadJson': '下载 JSON',\n 'dg.toolbar.downloadExcel': '下载 Excel',\n 'dg.toolbar.searchNodes': '搜索节点',\n 'dg.toolbar.closeClose': '关闭面板',\n 'dg.toolbar.schema': 'JSON Schema',\n 'dg.tabs.close': '关闭',\n 'dg.tabs.closeAll': '关闭所有标签页',\n 'dg.tabs.closeOthers': '关闭其他标签页',\n 'dg.tabs.closeRight': '关闭右侧标签页',\n 'dg.tabs.closeLeft': '关闭左侧标签页',\n 'dg.jsonSchema.title': '转换为 JSON Schema',\n 'dg.jsonSchema.copyJson': '复制 JSON',\n 'dg.node.documentation': '文档',\n 'dg.node.duplicate': '复制节点',\n 'dg.node.deleteNode': '删除节点',\n 'dg.schema.formatCode': '格式化代码',\n 'dg.schema.importFromJson': '从 JSON 导入',\n 'dg.excel.wrapQuotes': '值包裹引号',\n 'dg.excel.enterFieldName': '输入字段名',\n 'dg.condition.removeConfirm': '移除此条件?',\n\n 'expression.placeholder': '表达式',\n 'expression.key': '键名',\n 'expression.addRowAbove': '在上方添加行',\n 'expression.addRowBelow': '在下方添加行',\n\n 'func.debugger.copy': '复制到剪贴板',\n 'func.debugger.formatCode': '格式化代码',\n 'func.debugger.importLibrary': '导入库',\n 'func.debugger.goToDocs': '前往文档',\n 'func.debugger.msSinceRun': '脚本开始执行至今的时长。',\n 'misc.search': '搜索...',\n 'func.debugger.copied': '已复制到剪贴板',\n 'func.preview.noResults': '运行模拟器以查看结果',\n\n 'safe.title': '出现问题',\n 'safe.retry': '重试',\n\n // ── request node ──\n 'request': '请求',\n 'request.dataLabel': '用例数据',\n 'request.dataSourceSaved': '用例数据保存成功',\n 'request.dataTypeMismatchWarning': '当前请求数据类型格式与定义不吻合,如需要修改定义,请前往请求定义处修改。',\n 'request.downloadJsonNoData': '当前无可下载的数据内容',\n 'request.jsonInvalidError': '请输入合法的 JSON 或 JSON5',\n 'request.jsonObjectError': '请输入 JSON 对象',\n 'request.saveDataSourceFailed': '当前用例数据保存失败',\n 'request.selectDataSourceFirst': '请先选择一条用例数据',\n 'request.typeArray': 'Array',\n 'request.typeBoolean': 'Boolean',\n 'request.typeDatetime': 'Datetime',\n 'request.typeNumber': 'Number',\n 'request.typeObject': 'Object',\n 'request.typeString': 'String',\n 'request.uploadJsonFailed': 'JSON 上传失败',\n 'request.uploadJsonObjectRequired': '上传的 JSON 必须是对象',\n 'request.uploadJsonSuccess': 'JSON 上传成功',\n\n 'request.key': '键',\n 'request.type': '类型',\n 'request.description': '描述',\n 'request.save': '保存',\n 'request.schema': 'Schema',\n 'request.addChildField': '新增子字段',\n 'request.addDataSource': '新增用例数据',\n 'request.addField': '新增字段',\n 'request.childFieldNamePlaceholder': '子字段名',\n 'request.createDataSource': '创建用例数据',\n 'request.definitionsTab': '类型定义',\n 'request.deleteDataSourceConfirm': '确认删除当前用例数据?',\n 'request.deleteFieldConfirm': '确认删除当前字段?',\n 'request.downloadJsonTooltip': '下载当前用例数据 JSON',\n 'request.exampleDescriptionPlaceholder': '添加示例描述...',\n 'request.exampleFieldSummary': '字段摘要',\n 'request.exampleFieldSummaryAllMatch': '字段与定义一致',\n 'request.exampleFieldSummaryConflicts': '类型冲突',\n 'request.exampleFieldSummaryDefinitions': '定义字段',\n 'request.exampleFieldSummaryExtra': '额外字段',\n 'request.exampleFieldSummaryMissing': '缺失字段',\n 'request.examplesTab': '用例数据',\n 'request.fieldDefaultValuePlaceholder': '默认值',\n 'request.fieldDescriptionPlaceholder': '字段描述',\n 'request.fieldNamePlaceholder': '输入字段名',\n 'request.formatSchema': '格式化 Schema',\n 'request.noDataSources': '暂无用例数据',\n 'request.noDefinitions': '暂无字段定义',\n 'request.schemaPriorityTooltip': 'Schema 优先级最高。类型定义和用例数据会同步到 Schema。',\n 'request.simulateTooltip': '打开模拟器',\n 'request.toggleFieldDescriptionsTooltip': '开关字段描述提示',\n 'request.uploadJsonTooltip': '上传用例数据 JSON',\n\n // ── simulator ──\n // ── custom function ──\n 'cf.key': '键',\n 'cf.expression': '表达式',\n 'cf.function': '函数',\n 'cf.code': '代码',\n 'cf.legacy': '旧版',\n 'cf.addRow': '添加行',\n\n // ── simulator ──\n 'simulator.boundRequestNodeNotFound': '未找到已绑定的请求节点',\n 'simulator.requestMustBeObjectToSave': '当前请求内容必须是 JSON 对象才能保存',\n 'simulator.description': '通过请求节点进入的业务上下文,启动决策流程。支持 JSON 或 JSON5 格式。',\n 'simulator.currentBinding': '当前绑定',\n 'simulator.nodeRequired': '需要请求节点才能运行图表。从组件面板拖放一个请求节点。',\n 'simulator.run': '运行',\n 'simulator.formatSuccess': '格式化成功!',\n 'simulator.formatFailed': '格式化失败。无效的 JSON 格式。',\n 'simulator.nothingToCopy': '没有可复制的内容。',\n 'simulator.copiedToClipboard': '已复制到剪贴板!',\n 'simulator.copyFailedInvalidJson': '复制失败。无效的 JSON 格式。',\n 'simulator.dataRequiredBeforeRun': '当前请求参数为空,请先添加用例数据',\n 'simulator.invalidFormatTitle': '请求格式无效',\n 'simulator.invalidFormatDescription': '请输入合法的 JSON 或 JSON5 对象后再运行。',\n 'simulator.searchPlaceholder': '搜索节点...',\n 'simulator.clear': '清空',\n 'simulator.readyTitle': '准备就绪,可以开始模拟!',\n 'simulator.readyHint': '运行一次请求即可查看节点执行轨迹。',\n 'simulator.learnMore': '了解更多',\n\n 'misc.delete': '删除',\n};\n","import * as React from 'react';\n\nimport { type InterpolationParams, interpolate } from './i18n-types';\nimport { type TranslationKey, en } from './messages/en';\nimport { zhCN } from './messages/zh-CN';\n\nexport type { TranslationKey };\n\n/** Built-in locale catalogs. */\nconst BUILTIN: Record<string, Record<string, string>> = {\n en,\n 'zh-CN': zhCN,\n};\n\n/** Consumer-supplied overrides keyed by locale. */\nexport type I18nMessages = Record<string, string>;\n\ntype I18nContextValue = {\n locale: string;\n overrides: I18nMessages | undefined;\n};\n\ntype MessageLookup = (key: string) => string | undefined;\n\nconst I18nContext = React.createContext<I18nContextValue | undefined>(undefined);\n\nfunction getLookup(locale: string, overrides: I18nMessages | undefined): MessageLookup {\n const builtin = BUILTIN[locale] ?? BUILTIN[locale.split('-')[0]] ?? BUILTIN.en;\n return (key: string) => overrides?.[key] ?? builtin[key] ?? en[key as TranslationKey];\n}\n\n/**\n * i18n translate hook. Returns a `t(key, params?)` function.\n *\n * Resolution chain: consumer `messages` overrides → locale catalog → English → key.\n * Supports `{{param}}` interpolation.\n *\n * @example\n * const t = useT();\n * t('dt.toolbar.import') // 'Import Excel'\n */\nexport const useT = (): ((key: TranslationKey | string, params?: InterpolationParams) => string) => {\n const ctx = React.useContext(I18nContext);\n return React.useCallback(\n (key: string, params?: InterpolationParams) => {\n if (!ctx) return interpolate(en[key as TranslationKey] ?? key, params);\n const lookup = getLookup(ctx.locale, ctx.overrides);\n return interpolate(lookup(key) ?? key, params);\n },\n [ctx],\n );\n};\n\n/**\n * Creates a standalone translate function (outside React tree, e.g. for\n * non-component utilities). Does NOT react to context changes.\n */\nexport const createT = (locale: string, overrides?: I18nMessages) => {\n const lookup = getLookup(locale, overrides);\n return (key: string, params?: InterpolationParams) => interpolate(lookup(key) ?? key, params);\n};\n\n/** Internal provider — used by JdmConfigProvider to publish locale + overrides. */\nexport const I18nProvider: React.FC<{\n locale: string;\n overrides?: I18nMessages;\n children: React.ReactNode;\n}> = ({ locale, overrides, children }) => {\n const value = React.useMemo(() => ({ locale, overrides }), [locale, overrides]);\n return <I18nContext.Provider value={value}>{children}</I18nContext.Provider>;\n};\n","import React, { useContext, useLayoutEffect, useMemo, useRef, useState } from 'react';\nimport { Toaster } from 'sonner';\n\nimport { App } from './components/primitives';\nimport { useWasmReady } from './helpers/wasm';\nimport { computeTheme } from './theming/compute';\nimport type { ThemeSeeds } from './theming/derive';\nimport { I18nProvider } from './theming/i18n';\nimport { GrlContainerProvider } from './theming/portal-context';\n\nexport { MODE_EXTRAS, darkTokens, lightTokens } from './theming/presets';\n\nexport type ThemeConfig = {\n mode?: 'light' | 'dark';\n token?: Record<string, unknown>;\n [key: string]: unknown;\n};\n\nexport type DictionaryMap = Record<string, { label: string; value: string }[]>;\n\nconst ThemeModeContext = React.createContext<'light' | 'dark'>('light');\n\n/** Active color scheme set by <JdmConfigProvider mode>. */\nexport const useThemeMode = (): 'light' | 'dark' => useContext(ThemeModeContext);\n\nconst DictionaryContext = React.createContext<DictionaryMap>({});\n\nexport const useDictionaries = (): DictionaryMap => useContext(DictionaryContext);\n\nexport const DictionaryProvider: React.FC<React.PropsWithChildren<{ value: DictionaryMap }>> = ({\n value,\n children,\n}) => <DictionaryContext.Provider value={value}>{children}</DictionaryContext.Provider>;\n\nexport type JdmConfigProviderProps = {\n theme?: ThemeConfig;\n /**\n * Brand seed colors (roadmap P0, one-click retheming). Both modes derive\n * brand families; explicit `theme.token` entries always win.\n */\n seeds?: ThemeSeeds;\n /** BCP 47 locale tag (e.g. `'en'`, `'zh-CN'`). Defaults to `'en'`. */\n locale?: string;\n /** Consumer i18n overrides — highest priority in the resolution chain. */\n messages?: Record<string, string>;\n prefixCls?: string;\n dictionaries?: DictionaryMap;\n children?: React.ReactNode;\n};\n\nexport const JdmConfigProvider: React.FC<JdmConfigProviderProps> = ({\n theme: { mode = 'light' as const, token = {} } = {},\n seeds,\n locale = 'en',\n messages,\n dictionaries,\n children,\n}) => {\n useWasmReady();\n\n const dicts = useMemo(() => dictionaries ?? {}, [dictionaries]);\n\n /* ── Scoped injection (roadmap P3) ─────────────────────────────────────────\n * When the provider mounts inside a `.grl-root` island, tokens become inline\n * properties on THAT container and `data-mode` lives there too — multiple\n * independently-themed islands can coexist, and Radix portals (via\n * GrlContainerProvider) stay inside the island's variable scope, which also\n * brings the scoped preflight over portaled nodes (HK-14).\n * Legacy fallback: no `.grl-root` ancestor → global `:root` style tag +\n * documentElement dataset, exactly as before P3. */\n const anchorRef = useRef<HTMLSpanElement>(null);\n const styleRef = useRef<HTMLStyleElement>(null);\n const [container, setContainer] = useState<HTMLElement | undefined>(undefined);\n\n const exposedTokens = useMemo(() => computeTheme(mode, seeds, token), [mode, seeds, token]);\n\n useLayoutEffect(() => {\n const root = (anchorRef.current?.closest?.('.grl-root') as HTMLElement | null) ?? undefined;\n setContainer(root);\n }, []);\n\n useLayoutEffect(() => {\n const target = (container ?? document.documentElement) as HTMLElement & {\n dataset: Record<string, string>;\n };\n target.dataset.mode = mode;\n return () => {\n delete target.dataset.mode;\n };\n }, [container, mode]);\n\n useLayoutEffect(() => {\n if (container) {\n const keys = Object.keys(exposedTokens);\n for (const key of keys) {\n container.style.setProperty(key, exposedTokens[key]);\n }\n // Text color must be scoped alongside the variables: nothing else in the\n // cascade sets `color`, so in dark mode\n // every input/editor would inherit UA black-on-dark and go invisible.\n container.style.setProperty('color', 'var(--foreground)');\n return () => {\n for (const key of keys) {\n container.style.removeProperty(key);\n }\n container.style.removeProperty('color');\n };\n }\n\n const el = styleRef.current;\n if (el) {\n const cssBlock = Object.entries(exposedTokens)\n .map(([key, value]) => ` ${key}: ${value};`)\n .join('\\n');\n el.textContent = `:root {\\n${cssBlock}\\n color: var(--foreground);\\n}`;\n }\n }, [container, exposedTokens]);\n\n return (\n <ThemeModeContext.Provider value={mode}>\n <DictionaryContext.Provider value={dicts}>\n <App>\n <span ref={anchorRef} style={{ display: 'none' }} data-grl-anchor='' />\n {!container && (\n <style\n ref={styleRef}\n dangerouslySetInnerHTML={{\n __html: (() => {\n const cssBlock = Object.entries(exposedTokens)\n .map(([key, value]) => ` ${key}: ${value};`)\n .join('\\n');\n return `:root {\\n${cssBlock}\\n color: var(--foreground);\\n}`;\n })(),\n }}\n />\n )}\n <GrlContainerProvider container={container}>\n <I18nProvider locale={locale} overrides={messages}>\n <Toaster theme={mode} position='bottom-right' richColors />\n {children}\n </I18nProvider>\n </GrlContainerProvider>\n </App>\n </DictionaryContext.Provider>\n </ThemeModeContext.Provider>\n );\n};\n","import React from 'react';\n\nimport { useT } from '../theming/i18n';\n\ntype SafeBoundaryProps = {\n children: React.ReactNode;\n /** Custom fallback UI shown when an error is caught. */\n fallback?: React.ReactNode;\n /** Called when an error is caught (for logging/telemetry). */\n onError?: (error: Error, errorInfo: React.ErrorInfo) => void;\n};\n\ntype SafeBoundaryState = {\n error: Error | null;\n};\n\nconst DefaultFallback: React.FC<{ message: string; onReset: () => void }> = ({ message, onReset }) => {\n const t = useT();\n return (\n <div\n role='alert'\n style={{\n display: 'flex',\n flexDirection: 'column',\n alignItems: 'center',\n justifyContent: 'center',\n gap: 8,\n padding: 24,\n border: '1px solid var(--grl-color-error-border, #ffccc7)',\n borderRadius: 8,\n background: 'var(--grl-color-error-bg, #fff2f0)',\n color: 'var(--grl-color-text, rgba(0,0,0,0.88))',\n minHeight: 120,\n }}\n >\n <div style={{ fontWeight: 600, fontSize: 14 }}>{t('safe.title')}</div>\n <div style={{ fontSize: 12, opacity: 0.65, wordBreak: 'break-all', maxWidth: 480, textAlign: 'center' }}>\n {message}\n </div>\n <button\n type='button'\n onClick={onReset}\n style={{\n marginTop: 4,\n padding: '4px 16px',\n borderRadius: 6,\n border: '1px solid var(--grl-color-border, #d9d9d9)',\n background: 'var(--grl-color-bg-container, #fff)',\n color: 'inherit',\n cursor: 'pointer',\n fontSize: 13,\n }}\n >\n {t('safe.retry')}\n </button>\n </div>\n );\n};\n\n/**\n * Production-grade error boundary for complex editor surfaces.\n *\n * A rendering crash inside a subtree (xyflow node, CodeMirror, WASM call,\n * etc.) would otherwise unmount the entire component tree. This boundary\n * catches the error, shows a fallback (custom or built-in), and offers a\n * retry button that resets the subtree's React state.\n *\n * Wrap at component entry points (DecisionGraph, DecisionTable, Function,\n * Expression), NOT inside individual leaves — boundary granularity should\n * match the blast-radius the user can tolerate.\n */\nexport class SafeBoundary extends React.Component<SafeBoundaryProps, SafeBoundaryState> {\n state: SafeBoundaryState = { error: null };\n\n static getDerivedStateFromError(error: Error): SafeBoundaryState {\n return { error };\n }\n\n componentDidCatch(error: Error, errorInfo: React.ErrorInfo): void {\n this.props.onError?.(error, errorInfo);\n }\n\n private reset = (): void => {\n this.setState({ error: null });\n };\n\n render(): React.ReactNode {\n if (this.state.error) {\n if (this.props.fallback !== undefined) {\n return this.props.fallback;\n }\n return <DefaultFallback message={this.state.error.message} onReset={this.reset} />;\n }\n\n return this.props.children;\n }\n}\n","import React, { useState } from 'react';\n\nimport type { ColumnType, TableSchemaItem } from './dt-store.context';\n\nexport type TableDialogType = 'reorder';\nexport type TableDialogState = {\n type: TableDialogType;\n item: TableSchemaItem | null;\n columnType: ColumnType;\n};\n\nexport type TableDialogContextState = {\n setDialog: React.Dispatch<React.SetStateAction<TableDialogState | undefined>>;\n dialog: TableDialogState | undefined;\n isDialogActive: (type: TableDialogType) => boolean;\n getContainer?: () => HTMLElement;\n};\n\n// Empty-object default is safe: consumers only render inside\n// DecisionTableDialogProvider, which supplies the real value on mount.\nexport const TableDialogContext = React.createContext<TableDialogContextState>({\n setDialog: () => {},\n dialog: undefined,\n isDialogActive: () => false,\n});\n\nexport const DecisionTableDialogProvider: React.FC<\n React.PropsWithChildren<{\n getContainer?: () => HTMLElement;\n }>\n> = ({ children, getContainer }) => {\n const [dialog, setDialog] = useState<TableDialogState | undefined>(undefined);\n const isDialogActive = (type: TableDialogType) => {\n return dialog?.type === type;\n };\n\n return (\n <TableDialogContext.Provider\n value={{\n dialog,\n setDialog,\n isDialogActive,\n getContainer,\n }}\n >\n {children}\n </TableDialogContext.Provider>\n );\n};\n\nexport const useDecisionTableDialog = () => React.useContext(TableDialogContext);\n","'use strict';\n\n// do not edit .js files directly - edit src/index.jst\n\n\n var envHasBigInt64Array = typeof BigInt64Array !== 'undefined';\n\n\nmodule.exports = function equal(a, b) {\n if (a === b) return true;\n\n if (a && b && typeof a == 'object' && typeof b == 'object') {\n if (a.constructor !== b.constructor) return false;\n\n var length, i, keys;\n if (Array.isArray(a)) {\n length = a.length;\n if (length != b.length) return false;\n for (i = length; i-- !== 0;)\n if (!equal(a[i], b[i])) return false;\n return true;\n }\n\n\n if ((a instanceof Map) && (b instanceof Map)) {\n if (a.size !== b.size) return false;\n for (i of a.entries())\n if (!b.has(i[0])) return false;\n for (i of a.entries())\n if (!equal(i[1], b.get(i[0]))) return false;\n return true;\n }\n\n if ((a instanceof Set) && (b instanceof Set)) {\n if (a.size !== b.size) return false;\n for (i of a.entries())\n if (!b.has(i[0])) return false;\n return true;\n }\n\n if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {\n length = a.length;\n if (length != b.length) return false;\n for (i = length; i-- !== 0;)\n if (a[i] !== b[i]) return false;\n return true;\n }\n\n\n if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;\n if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();\n if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();\n\n keys = Object.keys(a);\n length = keys.length;\n if (length !== Object.keys(b).length) return false;\n\n for (i = length; i-- !== 0;)\n if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;\n\n for (i = length; i-- !== 0;) {\n var key = keys[i];\n\n if (key === '_owner' && a.$$typeof) {\n // React-specific: avoid traversing React elements' _owner.\n // _owner contains circular references\n // and is not needed when comparing the actual elements (and not their owners)\n continue;\n }\n\n if (!equal(a[key], b[key])) return false;\n }\n\n return true;\n }\n\n // true if both NaN, false otherwise\n return a!==a && b!==b;\n};\n","import { useMemo, useRef } from 'react';\n\n/**\n * Stabilizes a selector result with a pluggable equality function, following\n * the same useRef + useMemo pattern as zustand v5's `useShallow`, and keeping\n * the hasMemo semantics of the former `useStoreWithEqualityFn`\n * (use-sync-external-store/with-selector): the comparator is never invoked\n * before a previous result exists, so custom comparators may assume\n * non-undefined arguments.\n */\nexport function useMemoEquality<S, T>(\n selector: (state: S) => T,\n equalityFn: (a: any, b: any) => boolean,\n): (state: S) => T {\n const prev = useRef<T | undefined>(undefined);\n const hasPrev = useRef(false);\n\n return useMemo(\n () => (state: S) => {\n const next = selector(state);\n if (!hasPrev.current) {\n hasPrev.current = true;\n prev.current = next;\n return next;\n }\n return equalityFn(prev.current, next) ? prev.current! : (prev.current = next);\n },\n [selector, equalityFn],\n );\n}\n","import type { Variable, VariableType } from '@gorules/zen-engine-wasm';\nimport equal from 'fast-deep-equal/es6/react';\nimport { produce } from 'immer';\nimport React, { useMemo } from 'react';\nimport { P, match } from 'ts-pattern';\nimport type { StoreApi, UseBoundStore } from 'zustand';\nimport { create, useStore } from 'zustand';\n\nimport type { SchemaSelectProps } from '../../../helpers/components';\nimport { type GetNodeDataResult } from '../../../helpers/node-data';\nimport type { ColumnFieldType, OutputFieldType } from '../../../helpers/schema';\nimport { useMemoEquality } from '../../../helpers/use-memoized-selector';\nimport type { DictionaryMap } from '../../../theme';\nimport type { SimulationTrace, SimulationTraceDataTable } from '../../decision-graph';\nimport type { Diff, DiffMetadata } from '../../decision-graph/dg-types';\nimport type { TableCellProps } from '../table/table-default-cell';\n\nexport type TableExportOptions = {\n name: string;\n};\n\nexport type TableCursor = {\n x: string;\n y: number;\n};\n\nexport type { ColumnFieldType, OutputFieldType };\n\nexport type TableSchemaItem = {\n id: string;\n name: string;\n field?: string;\n defaultValue?: string;\n fieldType?: ColumnFieldType;\n outputFieldType?: OutputFieldType;\n _diff?: DiffMetadata;\n};\n\nexport type HitPolicy = 'first' | 'collect';\nexport type ColumnType = 'inputs' | 'outputs';\n\nexport type DecisionTableType = {\n hitPolicy: HitPolicy | string;\n passThrough?: boolean;\n inputField?: string;\n outputPath?: string;\n executionMode?: 'single' | 'loop';\n inputs: TableSchemaItem[];\n outputs: TableSchemaItem[];\n rules: Record<string, string>[];\n} & Diff;\n\nconst outputTypeDefault = (schemaItem: TableSchemaItem): string => {\n const type = schemaItem.outputFieldType?.type;\n if (!type) return '';\n return match(type)\n .with('string', () => '\"\"')\n .with('string-array', () => '[]')\n .with('boolean', () => 'false')\n .with('number', () => '0')\n .with('date', () => `d('${new Date().toISOString().slice(0, 10)}')`)\n .otherwise(() => '');\n};\n\nconst cleanupTableRule = (\n decisionTable: DecisionTableType,\n rule: Record<string, string>,\n defaultId?: string,\n): Record<string, string> => {\n const outputIds = new Set(decisionTable.outputs.map((o) => o.id));\n const schemaItems = [...decisionTable.inputs, ...decisionTable.outputs];\n const newRule: Record<string, string> = {\n _id: rule._id || crypto.randomUUID(),\n _description: rule._description,\n };\n schemaItems.forEach((schemaItem) => {\n if (defaultId && newRule._id === defaultId) {\n const fallback = outputIds.has(schemaItem.id) ? outputTypeDefault(schemaItem) : '';\n return (newRule[schemaItem.id] = rule?.[schemaItem.id] || schemaItem?.defaultValue || fallback);\n }\n newRule[schemaItem.id] = rule?.[schemaItem.id] || '';\n });\n return newRule;\n};\n\nconst cleanupTableRules = (decisionTable: DecisionTableType, defaultId?: string): Record<string, string>[] => {\n const rules = decisionTable?.rules || [];\n return rules.map((rule) => cleanupTableRule(decisionTable, rule, defaultId));\n};\n\nexport const parseDecisionTable = (decisionTable?: DecisionTableType) => {\n const dt: DecisionTableType = {\n hitPolicy: decisionTable?.hitPolicy || 'first',\n inputs: decisionTable?.inputs || [],\n outputs: decisionTable?.outputs || [],\n rules: decisionTable?.rules || [],\n passThrough: decisionTable?.passThrough ?? false,\n inputField: decisionTable?.inputField,\n outputPath: decisionTable?.outputPath,\n executionMode: decisionTable?.executionMode ?? 'single',\n };\n\n if (decisionTable?._diff) {\n dt._diff = decisionTable._diff;\n }\n\n if (dt.inputs?.length === 0) {\n dt.inputs = [\n {\n id: crypto.randomUUID(),\n name: 'Input',\n },\n ];\n }\n\n if (dt.outputs?.length === 0) {\n dt.outputs = [\n {\n id: crypto.randomUUID(),\n field: 'output',\n name: 'Output',\n },\n ];\n }\n\n dt.rules = dt.rules.map((r) =>\n match(r)\n .with({ _id: P.string.minLength(1) }, () => r)\n .otherwise((r) => ({ ...r, _id: crypto.randomUUID() })),\n );\n\n return dt;\n};\n\nexport type DecisionTablePermission = 'edit:full' | 'edit:rules' | 'edit:values';\nexport type JdmUiMode = 'dev' | 'business';\n/** @deprecated Use JdmUiMode instead */\nexport type DecisionTableMode = JdmUiMode;\n\nexport type DecisionTableStoreType = {\n state: {\n id?: string;\n name?: string;\n decisionTable: DecisionTableType;\n cursor: TableCursor | null;\n\n disabled: boolean;\n disableHitPolicy: boolean;\n\n minColWidth: number;\n colWidth: number;\n\n permission?: DecisionTablePermission;\n mode: JdmUiMode;\n dictionaries?: DictionaryMap;\n\n inputVariableType?: VariableType;\n derivedVariableTypes: Record<string, VariableType>;\n\n inputsSchema?: SchemaSelectProps[];\n outputsSchema?: SchemaSelectProps[];\n\n debugIndex: number;\n calculatedInputData?: Variable;\n\n debug?: {\n snapshot: DecisionTableType;\n trace: SimulationTrace<SimulationTraceDataTable>;\n inputData?: GetNodeDataResult;\n };\n };\n\n actions: {\n setDecisionTable: (val: DecisionTableType) => void;\n setCursor: (cursor: TableCursor | null) => void;\n commitData: (data: string, cursor: TableCursor) => void;\n swapRows: (source: number, target: number) => void;\n addRowAbove: (target?: number) => void;\n addRowBelow: (target?: number) => void;\n removeRow: (target?: number) => void;\n addColumn: (type: ColumnType, column: TableSchemaItem) => void;\n updateColumn: (type: ColumnType, id: string, column: TableSchemaItem) => void;\n removeColumn: (type: ColumnType, id: string) => void;\n reorderColumns: (type: ColumnType, columns: TableSchemaItem[]) => void;\n updateHitPolicy: (hitPolicy: HitPolicy) => void;\n };\n\n listeners: {\n onChange?: (val: DecisionTableType) => void;\n cellRenderer?: (props: TableCellProps) => React.ReactNode | null | undefined;\n onColumnResize?: () => void;\n };\n};\n\ntype ExposedStore<T> = UseBoundStore<StoreApi<T>> & {\n setState: (partial: Partial<T>) => void;\n};\n\n// Empty-object default is safe: consumers only render inside\n// DecisionTableProvider, which supplies the real stores on mount.\nconst DecisionTableStoreContext = React.createContext<{\n stateStore: ExposedStore<DecisionTableStoreType['state']>;\n listenerStore: ExposedStore<DecisionTableStoreType['listeners']>;\n actions: DecisionTableStoreType['actions'];\n}>(\n // Double-cast is intentional: consumers only render inside\n // DecisionTableProvider, which supplies the real stores on mount.\n {} as unknown as {\n stateStore: ExposedStore<DecisionTableStoreType['state']>;\n listenerStore: ExposedStore<DecisionTableStoreType['listeners']>;\n actions: DecisionTableStoreType['actions'];\n },\n);\n\nexport type DecisionTableContextProps = {\n //\n};\n\nexport const DecisionTableProvider: React.FC<React.PropsWithChildren<DecisionTableContextProps>> = (props) => {\n const { children } = props;\n\n const stateStore = useMemo(\n () =>\n create<DecisionTableStoreType['state']>(() => ({\n id: undefined,\n name: undefined,\n decisionTable: parseDecisionTable(),\n cursor: null,\n\n disabled: false,\n disableHitPolicy: false,\n\n colWidth: 200,\n minColWidth: 150,\n\n inputsSchema: undefined,\n outputsSchema: undefined,\n\n mode: 'dev',\n derivedVariableTypes: {},\n inputVariableType: undefined,\n debugIndex: 0,\n debug: undefined,\n })),\n [],\n );\n\n const listenerStore = useMemo(\n () =>\n create<DecisionTableStoreType['listeners']>(() => ({\n onChange: undefined,\n cellRenderer: undefined,\n })),\n [],\n );\n\n const actions = useMemo<DecisionTableStoreType['actions']>(\n () => ({\n setDecisionTable: (decisionTable) => stateStore.setState({ decisionTable }),\n setCursor: (cursor: TableCursor | null) => stateStore.setState({ cursor }),\n commitData: (value: string, cursor: TableCursor) => {\n const { decisionTable } = stateStore.getState();\n\n const updatedDecisionTable = produce(decisionTable, (draft) => {\n const { x, y } = cursor;\n draft.rules[y][x] = value;\n return draft;\n });\n\n stateStore.setState({ decisionTable: updatedDecisionTable });\n listenerStore.getState().onChange?.(updatedDecisionTable);\n },\n swapRows: (source: number, target: number) => {\n const { decisionTable } = stateStore.getState();\n\n const updatedDecisionTable = produce(decisionTable, (draft) => {\n const input = draft?.rules?.[source];\n draft.rules.splice(source, 1);\n draft.rules.splice(target, 0, input);\n return draft;\n });\n\n stateStore.setState({ decisionTable: updatedDecisionTable, cursor: null });\n listenerStore.getState().onChange?.(updatedDecisionTable);\n },\n addRowAbove: (target?: number) => {\n const { decisionTable } = stateStore.getState();\n\n const updatedDecisionTable = produce(decisionTable, (draft) => {\n if (target === undefined) {\n target = 0;\n }\n\n const _id = crypto.randomUUID();\n draft.rules.splice(target, 0, cleanupTableRule(draft, { _id }, _id));\n\n return draft;\n });\n\n stateStore.setState({ decisionTable: updatedDecisionTable });\n listenerStore.getState().onChange?.(updatedDecisionTable);\n\n const { cursor } = stateStore.getState();\n if (cursor && cursor?.y === target) {\n stateStore.setState({ cursor: { x: cursor.x, y: cursor.y + 1 } });\n }\n },\n addRowBelow: (target?: number) => {\n const { decisionTable } = stateStore.getState();\n\n const updatedDecisionTable = produce(decisionTable, (draft) => {\n if (target === undefined) {\n target = draft?.rules?.length;\n } else {\n target += 1;\n }\n\n const _id = crypto.randomUUID();\n draft.rules.splice(target, 0, cleanupTableRule(draft, { _id }, _id));\n return draft;\n });\n stateStore.setState({ decisionTable: updatedDecisionTable });\n listenerStore.getState().onChange?.(updatedDecisionTable);\n\n const { cursor } = stateStore.getState();\n if (cursor && cursor?.y === target) {\n stateStore.setState({ cursor: { x: cursor.x, y: cursor.y - 1 } });\n }\n },\n removeRow: (target?: number) => {\n const { decisionTable } = stateStore.getState();\n\n const updatedDecisionTable = produce(decisionTable, (draft) => {\n if (target === undefined) {\n target = draft?.rules?.length || 0;\n }\n\n draft.rules.splice(target, 1);\n return draft;\n });\n\n stateStore.setState({ decisionTable: updatedDecisionTable });\n listenerStore.getState().onChange?.(updatedDecisionTable);\n },\n addColumn: (type: ColumnType, column: TableSchemaItem) => {\n const { decisionTable } = stateStore.getState();\n\n const updatedDecisionTable = produce(decisionTable, (draft) => {\n draft[type].push(column);\n draft.rules = cleanupTableRules(draft);\n return draft;\n });\n\n stateStore.setState({ decisionTable: updatedDecisionTable });\n listenerStore.getState().onChange?.(updatedDecisionTable);\n },\n updateColumn: (type: ColumnType, id: string, data: TableSchemaItem) => {\n const { decisionTable } = stateStore.getState();\n\n const updatedDecisionTable = produce(decisionTable, (draft) => {\n draft[type] = draft[type].map((item) => {\n if (item.id === id) {\n return {\n ...item,\n name: data?.name,\n field: data?.field,\n defaultValue: data?.defaultValue,\n fieldType: data?.fieldType,\n outputFieldType: data?.outputFieldType,\n };\n }\n return item;\n });\n\n draft.rules = cleanupTableRules(draft);\n return draft;\n });\n\n stateStore.setState({ decisionTable: updatedDecisionTable });\n listenerStore.getState().onChange?.(updatedDecisionTable);\n },\n removeColumn: (type: ColumnType, id: string) => {\n const { decisionTable } = stateStore.getState();\n\n const updatedDecisionTable = parseDecisionTable(\n produce(decisionTable, (draft) => {\n draft[type] = (draft?.[type] || []).filter((item) => item?.id !== id);\n draft.rules = cleanupTableRules(draft);\n return draft;\n }),\n );\n\n stateStore.setState({ decisionTable: updatedDecisionTable, cursor: null });\n listenerStore.getState().onChange?.(updatedDecisionTable);\n },\n reorderColumns: (type: ColumnType, columns: TableSchemaItem[]) => {\n const { decisionTable } = stateStore.getState();\n\n const updatedDecisionTable = produce(decisionTable, (draft) => {\n draft[type] = columns;\n draft.rules = cleanupTableRules(draft);\n return draft;\n });\n\n stateStore.setState({ decisionTable: updatedDecisionTable });\n listenerStore.getState().onChange?.(updatedDecisionTable);\n },\n updateHitPolicy: (hitPolicy: HitPolicy) => {\n const { decisionTable } = stateStore.getState();\n\n const updatedDecisionTable = produce(decisionTable, (draft) => {\n draft.hitPolicy = hitPolicy;\n return draft;\n });\n\n stateStore.setState({ decisionTable: updatedDecisionTable });\n listenerStore.getState().onChange?.(updatedDecisionTable);\n },\n }),\n [],\n );\n\n const value = useMemo(\n () => ({\n stateStore,\n listenerStore,\n actions,\n }),\n [stateStore, listenerStore, actions],\n );\n\n return <DecisionTableStoreContext.Provider value={value}>{children}</DecisionTableStoreContext.Provider>;\n};\n\nexport function useDecisionTableState<T>(\n selector: (state: DecisionTableStoreType['state']) => T,\n equals: (a: any, b: any) => boolean = equal,\n): T {\n return useStore(React.useContext(DecisionTableStoreContext).stateStore, useMemoEquality(selector, equals));\n}\n\nexport function useDecisionTableListeners<T>(\n selector: (state: DecisionTableStoreType['listeners']) => T,\n equals: (a: any, b: any) => boolean = equal,\n): T {\n return useStore(React.useContext(DecisionTableStoreContext).listenerStore, useMemoEquality(selector, equals));\n}\n\nexport function useDecisionTableActions(): DecisionTableStoreType['actions'] {\n return React.useContext(DecisionTableStoreContext).actions;\n}\n\nexport const useDecisionTableRaw = () => React.useContext(DecisionTableStoreContext);\n\nexport default DecisionTableProvider;\n","import React, { useMemo } from 'react';\n\nexport type StackAlignment =\n | 'start'\n | 'end'\n | 'center'\n | 'space-between'\n | 'space-around'\n | 'space-evenly'\n | 'baseline'\n | 'stretch';\n\nexport type StackProps = {\n horizontal?: boolean;\n reversed?: boolean;\n grow?: boolean;\n verticalAlign?: StackAlignment;\n horizontalAlign?: StackAlignment;\n gap?: string | number;\n height?: string | number;\n width?: string | number;\n} & React.HTMLAttributes<HTMLDivElement>;\n\nexport const Stack: React.FC<StackProps> = (props) => {\n const {\n horizontal,\n reversed,\n verticalAlign = 'start',\n horizontalAlign = 'start',\n gap = 8,\n height = 'auto',\n width = '100%',\n grow,\n style,\n ...rest\n } = props;\n\n const flexDirection = useMemo(() => {\n if (horizontal) {\n return !reversed ? 'row' : 'row-reverse';\n }\n return !reversed ? 'column' : 'column-reverse';\n }, [horizontal, reversed]);\n\n return (\n <div\n style={{\n display: 'flex',\n flexDirection,\n justifyContent: !horizontal ? verticalAlign : horizontalAlign,\n alignItems: !horizontal ? horizontalAlign : verticalAlign,\n height,\n width,\n gap,\n flexGrow: grow ? 1 : undefined,\n ...style,\n }}\n {...rest}\n />\n );\n};\n","import {\n DndContext,\n DragOverlay,\n PointerSensor,\n useDraggable,\n useDroppable,\n useSensor,\n useSensors,\n} from '@dnd-kit/core';\nimport React, { useEffect, useRef, useState } from 'react';\n\nimport { DragOverlayCard, OverlayChip } from '../../../helpers/dnd-overlay';\nimport { Card, Form, Modal, Typography } from '../../primitives';\nimport { Stack } from '../../stack';\nimport type { TableSchemaItem } from '../context/dt-store.context';\n\nexport type FieldsReorderProps = {\n fields?: TableSchemaItem[];\n onSuccess?: (columns: TableSchemaItem[]) => void;\n onDismiss?: () => void;\n isOpen?: boolean;\n getContainer?: () => HTMLElement;\n};\n\nconst FieldCard: React.FC<{\n col: TableSchemaItem;\n index: number;\n}> = ({ col, index }) => {\n const {\n attributes,\n listeners,\n setNodeRef: setDragNodeRef,\n setActivatorNodeRef,\n isDragging,\n } = useDraggable({\n id: `field-${col.id}`,\n data: { index },\n });\n\n const { setNodeRef: setDropNodeRef } = useDroppable({\n id: `field-${col.id}`,\n data: { index },\n });\n\n return (\n <Card\n ref={(el) => {\n setDropNodeRef(el);\n setDragNodeRef(el);\n }}\n style={{ opacity: isDragging ? 0 : 1 }}\n bodyStyle={{ padding: '0.5rem' }}\n >\n <div className='hover:cursor-grab'>\n <Stack horizontal verticalAlign='center'>\n <div ref={setActivatorNodeRef} {...listeners} {...attributes}>\n =\n </div>\n <Stack grow gap={0}>\n <Typography.Text>{col.name}</Typography.Text>\n <Typography.Text type='secondary' style={{ fontSize: 12 }}>\n {col.field}\n </Typography.Text>\n </Stack>\n </Stack>\n </div>\n </Card>\n );\n};\n\nconst FieldsDnd: React.FC<\n React.PropsWithChildren<{\n onMove: (draggedId: string, overId: string) => void;\n getColumnById: (id: string) => TableSchemaItem | undefined;\n }>\n> = ({ children, onMove, getColumnById }) => {\n const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 4 } }));\n const [activeId, setActiveId] = useState<string | null>(null);\n const activeColumn = activeId ? getColumnById(activeId) : undefined;\n\n return (\n <DndContext\n sensors={sensors}\n onDragStart={({ active }) => setActiveId(String(active.id).replace(/^field-/, ''))}\n onDragOver={({ active, over }) => {\n if (!over) {\n return;\n }\n\n const draggedId = String(active.id).replace(/^field-/, '');\n const overId = String(over.id).replace(/^field-/, '');\n if (draggedId !== overId) {\n onMove(draggedId, overId);\n }\n }}\n onDragEnd={() => setActiveId(null)}\n onDragCancel={() => setActiveId(null)}\n >\n {children}\n <DragOverlay dropAnimation={null}>\n {activeColumn ? (\n <DragOverlayCard>\n <OverlayChip width={180}>{activeColumn.name}</OverlayChip>\n {activeColumn.field ? (\n <OverlayChip width={140}>\n <span style={{ color: 'var(--grl-color-text-tertiary)' }}>{activeColumn.field}</span>\n </OverlayChip>\n ) : null}\n </DragOverlayCard>\n ) : null}\n </DragOverlay>\n </DndContext>\n );\n};\n\nexport const FieldsReorder: React.FC<FieldsReorderProps> = (props) => {\n const { isOpen, onDismiss, onSuccess, fields, getContainer } = props;\n\n const [columns, setColumns] = useState<TableSchemaItem[]>([]);\n const columnsRef = useRef<TableSchemaItem[]>([]);\n\n useEffect(() => {\n if (isOpen) {\n setColumns([...(fields || [])]);\n }\n }, [isOpen, fields]);\n\n useEffect(() => {\n columnsRef.current = columns;\n }, [columns]);\n\n const moveCardByIds = (draggedId?: string, overId?: string) => {\n if (!draggedId || !overId || draggedId === overId) {\n return;\n }\n\n const list = columnsRef.current;\n const from = list.findIndex((c) => c.id === draggedId);\n const to = list.findIndex((c) => c.id === overId);\n if (from === -1 || to === -1) {\n return;\n }\n\n const tmpList = [...list];\n const element = tmpList.splice(from, 1)[0];\n tmpList.splice(to, 0, element);\n setColumns(tmpList);\n };\n\n return (\n <Modal\n title='Reorder fields'\n open={isOpen}\n onCancel={onDismiss}\n width={360}\n destroyOnClose\n bodyStyle={{ paddingTop: 17 }}\n okText='Update'\n okButtonProps={{\n htmlType: 'submit',\n form: 'fields-reorder-dialog',\n }}\n getContainer={getContainer}\n >\n <Form id='fields-reorder-dialog' onFinish={() => onSuccess?.(columns)}>\n <FieldsDnd onMove={moveCardByIds} getColumnById={(id) => columnsRef.current.find((c) => c.id === id)}>\n <Stack gap={8} horizontalAlign='stretch'>\n {columns.map((column, index) => (\n <FieldCard key={column.id} col={column} index={index} />\n ))}\n </Stack>\n </FieldsDnd>\n </Form>\n </Modal>\n );\n};\n","import React from 'react';\n\nimport { useDecisionTableDialog } from '../context/dt-dialog.context';\nimport { useDecisionTableActions, useDecisionTableState } from '../context/dt-store.context';\nimport { FieldsReorder } from './fields-reorder-dialog';\n\nexport const DecisionTableDialogs: React.FC = () => {\n const { dialog, setDialog, isDialogActive, getContainer } = useDecisionTableDialog();\n\n const tableActions = useDecisionTableActions();\n const { decisionTableFields } = useDecisionTableState(({ decisionTable }) => ({\n decisionTableFields: dialog?.columnType ? decisionTable[dialog.columnType] : undefined,\n }));\n\n return (\n <FieldsReorder\n isOpen={isDialogActive('reorder')}\n fields={decisionTableFields}\n onDismiss={() => setDialog(undefined)}\n onSuccess={(data) => {\n if (!dialog) return;\n tableActions.reorderColumns(dialog.columnType, data);\n setDialog(undefined);\n }}\n getContainer={getContainer}\n />\n );\n};\n","import type { CSSProperties } from 'react';\n\nexport default function CrossIcon({ className, style }: { className?: string; style?: CSSProperties }) {\n return (\n <svg\n width='24'\n height='24'\n viewBox='0 0 24 24'\n fill='none'\n xmlns='http://www.w3.org/2000/svg'\n className={className}\n style={style}\n >\n <path\n d='M19.4325 6.10068C19.8558 5.67731 19.8558 4.9909 19.4325 4.56753C19.0091 4.14416 18.3227 4.14416 17.8993 4.56753L12 10.4668L6.10068 4.56753C5.67731 4.14416 4.9909 4.14416 4.56753 4.56753C4.14416 4.9909 4.14416 5.67731 4.56753 6.10068L10.4668 12L4.56753 17.8993C4.14416 18.3227 4.14416 19.0091 4.56753 19.4325C4.9909 19.8558 5.67731 19.8558 6.10068 19.4325L12 13.5332L17.8993 19.4325C18.3227 19.8558 19.0091 19.8558 19.4325 19.4325C19.8558 19.0091 19.8558 18.3227 19.4325 17.8993L13.5332 12L19.4325 6.10068Z'\n fill='currentColor'\n />\n </svg>\n );\n}\n","import type { CSSProperties } from 'react';\n\nexport default function PencilIcon({ className, style }: { className?: string; style?: CSSProperties }) {\n return (\n <svg\n width='24'\n height='24'\n viewBox='0 0 24 24'\n fill='none'\n xmlns='http://www.w3.org/2000/svg'\n className={className}\n style={style}\n >\n <path\n d='M21.9444 4.92386L19.067 2.04641C18.5364 1.53546 17.8285 1.25 17.0919 1.25C16.3553 1.25 15.6473 1.53546 15.1168 2.04641L12.9913 4.20199L3.56687 13.5863C3.49466 13.664 3.43996 13.7563 3.40645 13.857L1.34111 20.0731C1.27553 20.2534 1.23832 20.4428 1.23082 20.6345C1.23082 20.6345 1.23082 20.6345 1.23082 20.6947C1.22039 21.0456 1.30713 21.3926 1.48147 21.6973C1.48147 21.6973 1.54163 21.7675 1.56168 21.8076C1.63386 21.9317 1.72145 22.0463 1.82235 22.1484C2.00925 22.3391 2.23233 22.4905 2.47853 22.5938C2.72473 22.6971 2.98907 22.7502 3.25606 22.75C3.47781 22.7485 3.69785 22.7112 3.90775 22.6397L10.1238 20.5744C10.225 20.5371 10.3172 20.479 10.3945 20.4039L19.7889 10.9996L21.9444 8.83398C22.2103 8.57296 22.4203 8.2606 22.5616 7.91588C22.7029 7.57116 22.7727 7.2013 22.7666 6.82879C22.7489 6.11145 22.4543 5.42878 21.9444 4.92386ZM9.87319 18.8198L7.51709 16.4738L5.161 14.1177L13.4825 5.80614L18.1947 10.5083L9.87319 18.8198ZM3.41648 21.2461H3.22599C3.13267 21.2395 3.04275 21.2084 2.96531 21.1559C2.87056 21.0626 2.81346 20.9377 2.8049 20.805C2.79598 20.7418 2.79598 20.6777 2.8049 20.6145L2.96531 19.8324L4.1584 21.0255L3.41648 21.2461ZM5.75253 20.4741L3.51674 18.2383L4.4291 15.5113L6.43429 17.5165L8.43948 19.5216L5.75253 20.4741ZM20.8817 7.81133L19.2575 9.44556L14.5453 4.73336L16.1795 3.10916C16.4219 2.86794 16.7499 2.73251 17.0919 2.73251C17.4338 2.73251 17.7619 2.86794 18.0042 3.10916L20.8817 5.98661C21.1229 6.22898 21.2583 6.55702 21.2583 6.89897C21.2583 7.24092 21.1229 7.56896 20.8817 7.81133Z'\n fill='currentColor'\n />\n </svg>\n );\n}\n","import type { CSSProperties } from 'react';\n\nexport default function PlayCircleIcon({ className, style }: { className?: string; style?: CSSProperties }) {\n return (\n <svg\n width='24'\n height='24'\n viewBox='0 0 24 24'\n fill='none'\n xmlns='http://www.w3.org/2000/svg'\n className={className}\n style={style}\n >\n <path\n d='M12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2ZM12 3.5C7.30558 3.5 3.5 7.30558 3.5 12C3.5 16.6944 7.30558 20.5 12 20.5C16.6944 20.5 20.5 16.6944 20.5 12C20.5 7.30558 16.6944 3.5 12 3.5ZM9.89453 8.31738C9.99977 8.30162 10.1126 8.31976 10.2168 8.37988L15.7363 11.5674C15.7987 11.6035 15.8497 11.6496 15.8887 11.7021C16.0576 11.9299 16.0068 12.2772 15.7363 12.4336L10.2168 15.6191C10.1876 15.636 10.1571 15.6488 10.127 15.6592C10.1149 15.6633 10.1029 15.6677 10.0908 15.6709C10.0867 15.672 10.0822 15.6719 10.0781 15.6729C10.0602 15.677 10.0424 15.6805 10.0244 15.6826C10.0208 15.683 10.0172 15.6833 10.0137 15.6836C9.99895 15.685 9.98435 15.6855 9.96973 15.6855C9.93319 15.6857 9.89743 15.6815 9.8623 15.6738C9.85776 15.6728 9.85314 15.672 9.84863 15.6709C9.81483 15.6625 9.7822 15.6508 9.75098 15.6357C9.74643 15.6336 9.74178 15.6312 9.7373 15.6289C9.70696 15.6132 9.67799 15.5948 9.65137 15.5732C9.64698 15.5697 9.64296 15.5652 9.63867 15.5615C9.61268 15.539 9.5874 15.515 9.56641 15.4873C9.56325 15.4831 9.56067 15.478 9.55762 15.4736C9.50138 15.3941 9.46688 15.2963 9.4668 15.1865V8.81348C9.4668 8.54895 9.66323 8.35185 9.89453 8.31738ZM10.9668 13.4541L13.4863 12L10.9668 10.5449V13.4541Z'\n fill='currentColor'\n />\n </svg>\n );\n}\n","import type { CSSProperties } from 'react';\n\nexport default function RefreshArrowClockwiseIcon({ className, style }: { className?: string; style?: CSSProperties }) {\n return (\n <svg\n width='24'\n height='24'\n viewBox='0 0 24 24'\n fill='none'\n xmlns='http://www.w3.org/2000/svg'\n className={className}\n style={style}\n >\n <path\n d='M17.4414 5.5L17.9476 4.94665V4.94665L17.4414 5.5ZM17.1216 18.7795L17.6021 19.3553H17.6021L17.1216 18.7795ZM17.8427 18.1099L18.3815 18.6317L18.3815 18.6317L17.8427 18.1099ZM20.2895 11L20.9085 11.4235C20.692 11.7399 20.2719 11.8421 19.9343 11.6606L20.2895 11ZM19.8235 9.03451L20.5279 8.77719L20.5279 8.77719L19.8235 9.03451ZM17.1448 10.1606C16.78 9.96438 16.6433 9.50961 16.8394 9.1448C17.0356 8.77998 17.4904 8.64327 17.8552 8.83945L17.5 9.5L17.1448 10.1606ZM21.381 8.07649C21.6149 7.73463 22.0817 7.64712 22.4235 7.88102C22.7654 8.11492 22.8529 8.58166 22.619 8.92351L22 8.5L21.381 8.07649ZM19.6925 8.69782L18.9993 8.98422L18.9993 8.98422L19.6925 8.69782ZM19.5 8.2656L18.8234 8.58912L18.8234 8.58912L19.5 8.2656ZM19.3674 8L20.0328 7.65381L19.3674 8ZM17.4485 17.4352C17.7292 17.1306 18.2036 17.1112 18.5082 17.3919C18.8128 17.6726 18.8322 18.1471 18.5515 18.4517L18 17.9435L17.4485 17.4352ZM1.5 12H2.25C2.25 16.5242 6.10038 20.25 10.9235 20.25V21V21.75C5.3377 21.75 0.75 17.4169 0.75 12H1.5ZM10.9235 3V3.75C6.10038 3.75 2.25 7.47578 2.25 12H1.5H0.75C0.75 6.5831 5.3377 2.25 10.9235 2.25V3ZM17.4414 5.5L16.9351 6.05335C15.3786 4.62931 13.2622 3.75 10.9235 3.75V3V2.25C13.6428 2.25 16.119 3.27359 17.9476 4.94665L17.4414 5.5ZM10.9235 21V20.25C13.1181 20.25 15.1168 19.4757 16.641 18.2037L17.1216 18.7795L17.6021 19.3553C15.8127 20.8487 13.4751 21.75 10.9235 21.75V21ZM17.1216 18.7795L16.641 18.2037C16.8734 18.0097 17.0947 17.8042 17.304 17.5881L17.8427 18.1099L18.3815 18.6317C18.1352 18.886 17.875 19.1276 17.6021 19.3553L17.1216 18.7795ZM20.2895 11L19.5598 11.1734C19.5198 11.0052 19.4266 10.5685 19.3385 10.1762C19.2407 9.7413 19.1555 9.39174 19.119 9.29183L19.8235 9.03451L20.5279 8.77719C20.6062 8.99153 20.7149 9.46019 20.8019 9.84721C20.8985 10.2769 20.9809 10.6657 21.0192 10.8266L20.2895 11ZM20.2895 11L19.9343 11.6606L17.1448 10.1606L17.5 9.5L17.8552 8.83945L20.6447 10.3394L20.2895 11ZM20.2895 11L19.6705 10.5765L21.381 8.07649L22 8.5L22.619 8.92351L20.9085 11.4235L20.2895 11ZM19.8235 9.03451L19.119 9.29183C19.0812 9.18836 19.0413 9.08581 18.9993 8.98422L19.6925 8.69782L20.3856 8.41142C20.4355 8.53216 20.483 8.6541 20.5279 8.77719L19.8235 9.03451ZM19.6925 8.69782L18.9993 8.98422C18.9442 8.85082 18.8855 8.71909 18.8234 8.58912L19.5 8.2656L20.1766 7.94207C20.2504 8.09637 20.3201 8.25286 20.3856 8.41142L19.6925 8.69782ZM19.5 8.2656L18.8234 8.58912C18.7843 8.50744 18.7439 8.42645 18.7021 8.34619L19.3674 8L20.0328 7.65381C20.0823 7.74901 20.1303 7.84511 20.1766 7.94207L19.5 8.2656ZM19.3674 8L18.7021 8.34619C18.2556 7.48814 17.6558 6.71273 16.9351 6.05335L17.4414 5.5L17.9476 4.94665C18.7944 5.72135 19.5032 6.63606 20.0328 7.65381L19.3674 8ZM17.8427 18.1099L17.304 17.5881C17.3528 17.5377 17.401 17.4868 17.4485 17.4352L18 17.9435L18.5515 18.4517C18.4956 18.5124 18.4389 18.5724 18.3815 18.6317L17.8427 18.1099Z'\n fill='currentColor'\n />\n </svg>\n );\n}\n","import type { CSSProperties } from 'react';\n\nexport default function TrashSquareIcon({ className, style }: { className?: string; style?: CSSProperties }) {\n return (\n <svg\n width='24'\n height='24'\n viewBox='0 0 24 24'\n fill='none'\n xmlns='http://www.w3.org/2000/svg'\n className={className}\n style={style}\n >\n <path\n d='M16.0301 22.75H7.98015C6.20401 22.7474 4.50138 22.0406 3.24545 20.7847C1.98953 19.5288 1.28279 17.8261 1.28015 16.05V8C1.27488 7.11631 1.44422 6.24028 1.77844 5.42222C2.11267 4.60416 2.60519 3.86017 3.22774 3.23298C3.85028 2.60578 4.59059 2.10774 5.40615 1.76745C6.2217 1.42715 7.09645 1.2513 7.98015 1.25H16.0801C17.8563 1.26585 19.5537 1.98528 20.8002 3.25059C22.0468 4.51589 22.7408 6.22383 22.7301 8V16.1C22.7143 17.8675 22.0018 19.5573 20.7473 20.8024C19.4928 22.0476 17.7977 22.7474 16.0301 22.75ZM7.98015 2.75C7.28885 2.74332 6.60316 2.87455 5.96318 3.13603C5.32321 3.3975 4.74179 3.78396 4.25295 4.2728C3.76411 4.76165 3.37765 5.34306 3.11617 5.98304C2.8547 6.62301 2.72347 7.3087 2.73015 8V16.1C2.73668 16.7829 2.87767 17.4578 3.14505 18.0862C3.41243 18.7146 3.80097 19.2842 4.28848 19.7624C4.77599 20.2406 5.35293 20.6181 5.98635 20.8734C6.61977 21.1286 7.29727 21.2566 7.98015 21.25H16.0801C17.4585 21.2474 18.7796 20.6987 19.7542 19.724C20.7288 18.7494 21.2775 17.4283 21.2801 16.05V8C21.2775 6.62169 20.7288 5.30058 19.7542 4.32596C18.7796 3.35135 17.4585 2.80264 16.0801 2.8L7.98015 2.75ZM9.98015 18.4H14.2201C14.7512 18.4181 15.2694 18.2341 15.6703 17.8853C16.0711 17.5364 16.3248 17.0485 16.3801 16.52L16.7201 11.52C16.7312 11.3216 16.6641 11.1268 16.5333 10.9773C16.4024 10.8277 16.2182 10.7354 16.0201 10.72C15.9213 10.7118 15.8219 10.7236 15.7277 10.7546C15.6335 10.7857 15.5465 10.8353 15.4719 10.9006C15.3973 10.9659 15.3365 11.0455 15.2933 11.1347C15.25 11.224 15.2252 11.321 15.2201 11.42L14.8901 16.42C14.8525 16.5672 14.763 16.6958 14.638 16.7821C14.5131 16.8685 14.3611 16.9068 14.2101 16.89H9.96015C9.62015 16.89 9.28015 16.68 9.26015 16.42L8.86015 11.32C8.85356 11.2149 8.82463 11.1125 8.77529 11.0195C8.72596 10.9266 8.65736 10.8452 8.57407 10.7808C8.49078 10.7164 8.39472 10.6706 8.2923 10.6463C8.18989 10.622 8.08347 10.6199 7.98015 10.64C7.88237 10.6462 7.78685 10.6721 7.69928 10.716C7.61171 10.76 7.53388 10.8211 7.47042 10.8957C7.40697 10.9704 7.35919 11.057 7.32994 11.1506C7.30069 11.2441 7.29056 11.3425 7.30015 11.44L7.70015 16.54C7.765 17.0684 8.02625 17.553 8.43199 17.8976C8.83773 18.2422 9.35826 18.4215 9.89015 18.4H9.98015ZM16.7301 8.11C16.1101 8 15.5001 8 14.9101 7.9L14.7601 6.9C14.6992 6.46647 14.4873 6.06834 14.1617 5.77567C13.8361 5.483 13.4177 5.31457 12.9801 5.3H10.9801C10.544 5.31759 10.1281 5.48884 9.80603 5.78347C9.48395 6.0781 9.27642 6.47713 9.22015 6.91L9.05015 7.91C7.98015 8 7.29015 8.1 7.22015 8.12C7.12037 8.13432 7.02458 8.16888 6.93863 8.22155C6.85269 8.27421 6.77842 8.34389 6.72036 8.42629C6.66231 8.50869 6.6217 8.60208 6.60103 8.70073C6.58036 8.79939 6.58006 8.90123 6.60015 9C6.63206 9.19622 6.74056 9.37174 6.90182 9.488C7.06308 9.60426 7.2639 9.65173 7.46015 9.62C10.4623 9.20183 13.508 9.20183 16.5101 9.62H16.6201C16.7973 9.62234 16.9694 9.56106 17.1052 9.44729C17.241 9.33352 17.3314 9.17481 17.3601 9C17.3788 8.90004 17.3771 8.79736 17.3553 8.69805C17.3335 8.59874 17.292 8.5048 17.2333 8.42181C17.1746 8.33883 17.0998 8.26847 17.0133 8.21491C16.9269 8.16135 16.8306 8.12567 16.7301 8.11ZM10.5901 7.78L10.7001 7.16C10.7001 6.93 10.8801 6.8 10.9901 6.8H12.9901C13.1101 6.8 13.2501 6.94 13.2801 7.16L13.3801 7.78H10.5901Z'\n fill='currentColor'\n />\n </svg>\n );\n}\n","export const saveFile = (filename: string, contents: Blob) => {\n const element = document.createElement('a');\n element.download = filename;\n element.href = URL.createObjectURL(contents);\n element.style.display = 'none';\n document.body.appendChild(element);\n\n element.click();\n\n element.remove();\n};\n","import exceljs from 'exceljs';\nimport { z } from 'zod';\n\nimport type { HitPolicy, TableSchemaItem } from '../components/decision-table/context/dt-store.context';\nimport type { DecisionGraphType, DecisionTableType } from '../index';\nimport { NodeKind } from '../index';\nimport { saveFile } from './file-helpers';\n\ntype DecisionTableNode = {\n id: string;\n name: string;\n} & DecisionTableType;\n\ntype SpreadsheetCell = {\n value?: string;\n note?: string | null;\n};\n\ntype HeaderData = {\n name?: string;\n id: string;\n value?: string;\n _type?: string;\n defaultValue?: string;\n note?: string | null;\n};\n\nexport type RuleData = {\n value?: string;\n headerId: string;\n};\n\ntype ExistingTableData = {\n headers: (TableSchemaItem & { type: 'input' | 'output' })[];\n hitPolicy: HitPolicy | string;\n inputField?: string | null;\n outputPath?: string | null;\n passThrough?: boolean;\n executionMode?: 'single' | 'loop';\n};\n\ntype ParsedSheetData = {\n headers: HeaderData[];\n rules: RuleData[][];\n existingTableData: ExistingTableData;\n};\n\nexport type ParsedExcelData = ParsedSheetData & {\n id: string;\n name: string;\n type: NodeKind;\n position: { x: number; y: number };\n};\n\nexport const exportDecisionTable = async (fileName: string, decisionTableNodes: DecisionTableNode[]) => {\n const { Workbook } = exceljs;\n const workbook = new Workbook();\n\n decisionTableNodes.forEach((decisionTableNode) => {\n let worksheetName: string = decisionTableNode.name;\n let worksheetNameIndex = 0;\n\n if (workbook.getWorksheet(worksheetName)) {\n do {\n worksheetNameIndex++;\n worksheetName = `${decisionTableNode.name} (${worksheetNameIndex})`;\n } while (workbook.getWorksheet(worksheetName));\n }\n\n const worksheet = workbook.addWorksheet(worksheetName);\n\n const columns = [\n ...decisionTableNode.inputs.map((input: any) => ({ title: input.name, type: 'input' })),\n ...decisionTableNode.outputs.map((output: any) => ({ title: output.name, type: 'output' })),\n { title: 'Description', type: 'description' },\n ];\n\n const schemaItems = [...decisionTableNode.inputs, ...decisionTableNode.outputs];\n const rules = decisionTableNode.rules.map((record: any) => {\n const row: string[] = [];\n schemaItems.forEach((schemaItem) => {\n const val = record?.[schemaItem.id || ''];\n const formattedVal = typeof val === 'object' && val !== null ? JSON.stringify(val) : val;\n row.push(formattedVal || '');\n });\n row.push(record?.['_description'] || '');\n return row;\n });\n\n const headerRow = worksheet.addRow(columns.map((col) => col.title));\n headerRow.eachCell((cell, colNumber) => {\n const col = columns[colNumber - 1];\n const cellColor = col?.type === 'input' ? '5e6476' : '63546c';\n\n cell.font = { bold: true, color: { argb: 'FFFFFF' } };\n cell.fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: cellColor } };\n });\n\n rules.forEach((rule) => {\n worksheet.addRow(rule);\n });\n\n worksheet.columns.forEach((_, index) => {\n let minLength = 15;\n const column = worksheet.getColumn(index + 1);\n column.eachCell({ includeEmpty: false }, (cell) => {\n const cellLength = cell.value ? cell.value.toString().length : 0;\n minLength = cellLength > minLength ? cellLength : minLength;\n\n cell.border = {\n top: { style: 'thin' },\n left: { style: 'thin' },\n bottom: { style: 'thin' },\n right: { style: 'thin' },\n };\n });\n column.width = minLength;\n });\n\n worksheet.views = [{ state: 'frozen', xSplit: 0, ySplit: 1 }];\n });\n\n const buffer = await workbook.xlsx.writeBuffer();\n const blob = new Blob([buffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });\n saveFile(`${fileName}.xlsx`, blob);\n};\n\nconst getDecisionTableData = (\n nodeId?: string,\n spreadSheetData: SpreadsheetCell[][] = [],\n defaultTable?: DecisionTableType,\n): ParsedSheetData => {\n let headers: HeaderData[] = [];\n let rules: RuleData[][] = [];\n\n if (nodeId) {\n const columnHeaders: SpreadsheetCell[] = spreadSheetData.splice(0, 3)[2];\n\n headers = columnHeaders.map((columnHeader) => {\n if (columnHeader.value?.toLowerCase() === 'description') {\n return {\n name: columnHeader.value,\n id: '_description',\n };\n }\n\n if (columnHeader.value?.toLowerCase() === 'rule id') {\n return {\n name: columnHeader.value,\n id: '_id',\n };\n }\n\n let headerMeta = {\n name: '',\n type: '',\n id: '',\n };\n\n try {\n headerMeta = JSON.parse(columnHeader.note || '');\n } catch {\n return {\n name: columnHeader.value,\n id: crypto.randomUUID(),\n };\n }\n\n return {\n name: columnHeader.value,\n value: headerMeta?.name,\n _type: headerMeta?.type,\n id: headerMeta?.id,\n defaultValue: '',\n };\n });\n\n rules = spreadSheetData.map((data) => {\n return data.map((d, index) => ({ value: d.value, headerId: headers[index].id }));\n });\n } else {\n headers = spreadSheetData.splice(0, 1)[0].map((columnHeader) => {\n if (columnHeader.value?.toLowerCase() === 'description') {\n return {\n name: columnHeader.value,\n id: '_description',\n };\n }\n\n return {\n name: columnHeader.value,\n id: crypto.randomUUID(),\n };\n });\n\n rules = spreadSheetData.map((data) => {\n return data.map((d, index) => ({ value: d.value, headerId: headers[index].id }));\n });\n }\n\n return {\n headers: headers.filter((item) => item.id !== '_id'),\n rules,\n existingTableData: {\n headers: [\n ...(defaultTable?.inputs || []).map((item) => ({ ...item, type: 'input' as const })),\n ...(defaultTable?.outputs || []).map((item) => ({ ...item, type: 'output' as const })),\n ],\n hitPolicy: defaultTable?.hitPolicy || 'first',\n inputField: defaultTable?.inputField,\n outputPath: defaultTable?.outputPath,\n passThrough: defaultTable?.passThrough,\n executionMode: defaultTable?.executionMode || 'single',\n },\n };\n};\n\nexport const getExcelData = async (buffer: ArrayBuffer, defaultValues?: DecisionTableType | DecisionGraphType) => {\n const { Workbook } = exceljs;\n const excelWorkbook = new Workbook();\n const workbook = await excelWorkbook.xlsx.load(buffer);\n\n const parsedSpreadsheetData: ParsedExcelData[] = [];\n\n workbook.eachSheet((sheet) => {\n const spreadsheetData: SpreadsheetCell[][] = [];\n const spreadsheetName = sheet.name;\n\n sheet.eachRow((row) => {\n const rowData: SpreadsheetCell[] = [];\n\n for (let i = 1; i <= row.cellCount; i++) {\n const cell = row.getCell(i);\n\n const cellNote = cell.note\n ? typeof cell.note === 'object'\n ? cell.note.texts?.map((obj) => obj.text).join('')\n : cell.note\n : null;\n\n rowData.push({ value: cell.value?.toString(), note: cellNote });\n }\n\n spreadsheetData.push(rowData);\n });\n\n const uuidSchema = z.string().uuid().optional();\n\n let nodeId: z.infer<typeof uuidSchema>;\n\n const nodeIdParse = uuidSchema.safeParse(spreadsheetData[0][0].value);\n\n if (nodeIdParse.success) {\n nodeId = nodeIdParse.data;\n }\n\n let defaultTableValues;\n if (defaultValues && typeof defaultValues === 'object' && 'nodes' in defaultValues) {\n defaultTableValues = defaultValues.nodes?.find((node) => node.id === nodeId)?.content;\n } else if (defaultValues && typeof defaultValues === 'object') {\n defaultTableValues = defaultValues as DecisionTableType;\n }\n\n parsedSpreadsheetData.push({\n ...getDecisionTableData(nodeId, spreadsheetData, defaultTableValues),\n id: nodeId || crypto.randomUUID(),\n name: spreadsheetName,\n type: NodeKind.DecisionTable,\n position: { x: 0, y: 0 },\n });\n });\n\n return parsedSpreadsheetData;\n};\n","import type { MutableRefObject, Ref } from 'react';\n\ntype OptionalRef<T> = Ref<T> | undefined;\n\nexport function composeRefs<T>(...refs: [OptionalRef<T>, OptionalRef<T>, ...Array<OptionalRef<T>>]): Ref<T> {\n if (refs.length === 2) {\n // micro-optimize the hot path\n return composeTwoRefs(refs[0], refs[1]) || null;\n }\n\n const composedRef = refs\n .slice(1)\n .reduce(\n (semiCombinedRef: OptionalRef<T>, refToInclude: OptionalRef<T>) => composeTwoRefs(semiCombinedRef, refToInclude),\n refs[0],\n );\n return composedRef || null;\n}\n\ntype NonNullRef<T> = NonNullable<Ref<T>>;\nconst composedRefCache = new WeakMap<NonNullRef<unknown>, WeakMap<NonNullRef<unknown>, NonNullRef<unknown>>>();\n\n/**\n * Imperatively write a value into any React ref shape (callback or object).\n * Module-scope on purpose: react-compiler can't statically see ref-prop\n * mutations through this opaque call, which keeps child→parent handoffs\n * like `scrollApiRef.current = api` legal without eslint-disable markers.\n */\nexport function setRefValue<T>(ref: OptionalRef<T>, instance: null | T): void {\n if (!ref) {\n return;\n }\n\n if (typeof ref === 'function') {\n ref(instance);\n } else {\n (ref as MutableRefObject<T | null>).current = instance;\n }\n}\n\nfunction composeTwoRefs<T>(ref1: OptionalRef<T>, ref2: OptionalRef<T>): OptionalRef<T> {\n if (ref1 && ref2) {\n const ref1Cache = composedRefCache.get(ref1) || new WeakMap<NonNullRef<unknown>, NonNullRef<unknown>>();\n composedRefCache.set(ref1, ref1Cache);\n\n const composedRef =\n ref1Cache.get(ref2) ||\n ((instance: T): void => {\n updateRef(ref1, instance);\n updateRef(ref2, instance);\n });\n ref1Cache.set(ref2, composedRef);\n\n return composedRef as NonNullRef<T>;\n }\n\n if (!ref1) {\n return ref2;\n } else {\n return ref1;\n }\n}\n\nfunction updateRef<T>(ref: NonNullRef<T>, instance: null | T): void {\n setRefValue(ref, instance);\n}\n","import clsx from 'clsx';\nimport React, { useEffect, useRef } from 'react';\n\nimport { composeRefs } from '../helpers/compose-refs';\n\nexport type AutosizeTextAreaProps = {\n maxRows: number;\n noStyle?: boolean;\n value?: string;\n onChange?: React.ChangeEventHandler<HTMLTextAreaElement>;\n placeholder?: string;\n disabled?: boolean;\n readOnly?: boolean;\n className?: string;\n /** Stable hook for tests — emitted as data-testid on the editable node. */\n testId?: string;\n} & Omit<React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>, 'onChange' | 'placeholder'>;\n\nexport const AutosizeTextArea = React.forwardRef<HTMLDivElement, AutosizeTextAreaProps>(\n ({ maxRows, className, value, onChange, placeholder, disabled, readOnly, style, noStyle, testId, ...props }, ref) => {\n const divRef = useRef<HTMLDivElement>(null);\n\n useEffect(() => {\n if (divRef.current && divRef.current.textContent !== value) {\n divRef.current.textContent = value ?? '';\n }\n }, [value]);\n\n const handleInput = (e: React.FormEvent<HTMLDivElement>) => {\n if (onChange) {\n const syntheticEvent = {\n target: { value: e.currentTarget.textContent ?? '' },\n currentTarget: { value: e.currentTarget.textContent ?? '' },\n } as React.ChangeEvent<HTMLTextAreaElement>;\n onChange(syntheticEvent);\n }\n };\n\n return (\n <div\n className={clsx(!noStyle && 'grl-textarea-input', className)}\n ref={composeRefs(divRef, ref)}\n contentEditable={!disabled && !readOnly}\n onInput={handleInput}\n data-placeholder={placeholder}\n aria-disabled={disabled}\n data-testid={testId}\n style={{ '--textarea-max-rows': maxRows, ...style } as React.CSSProperties}\n {...props}\n />\n );\n },\n);\n","import { getCompletions as getCompletionsWasm } from '@gorules/zen-engine-wasm';\n\nimport { isWasmAvailable } from '../../../helpers/wasm';\n\ntype Completion = {\n kind: string;\n label: string;\n detail: string;\n info: string;\n boost?: number;\n};\n\nlet completions: Completion[] = [];\n\nexport const getCompletions = () => {\n if (!isWasmAvailable() || completions.length > 0) {\n return completions;\n }\n\n completions = getCompletionsWasm();\n return completions;\n};\n","type RenderDiagnosticMessageParams = {\n text: string;\n className?: string;\n};\n\nexport const renderDiagnosticMessage = ({ text, className }: RenderDiagnosticMessageParams) => {\n return text.replace(/`([^`]+)`/g, (match, content) => {\n let color;\n if (/^[\"'].*[\"']$/.test(content)) {\n color = '#6aab73'; // Strings\n } else if (/^\\d+$/.test(content)) {\n color = '#57a8f5'; // Numbers\n } else {\n color = '#CE8E6D'; // Everything else\n }\n return `<span class=\"${className}\" style=\"color: ${color};\">${escapeHtml(content)}</span>`;\n });\n};\n\nexport const escapeHtml = (str: string) => {\n return str\n .replaceAll('&', '&')\n .replaceAll('<', '<')\n .replaceAll('>', '>')\n .replaceAll('\"', '"')\n .replaceAll(\"'\", ''');\n};\n","import { linter } from '@codemirror/lint';\n\nexport const codemirror = {\n linter: linter,\n};\n","import type { Diagnostic } from '@codemirror/lint';\nimport { VariableType, validateExpression, validateUnaryExpression } from '@gorules/zen-engine-wasm';\nimport { P, match } from 'ts-pattern';\n\nimport { codemirror } from '../../../helpers/codemirror';\nimport { isWasmAvailable } from '../../../helpers/wasm';\nimport { renderDiagnosticMessage } from './diagnostic';\nimport type { ZenType } from './types';\nimport {\n typeField,\n updateExpectedVariableTypeEffect,\n updateExpressionTypeEffect,\n updateStrictModeEffect,\n updateVariableTypeEffect,\n zenKindToString,\n} from './types';\n\ntype ExpressionError = {\n type: string;\n source: string;\n};\n\nconst extractPosition = (error: string): [number, number] | number | null => {\n try {\n const splitError = error.split(' at ');\n if (splitError.length <= 1) {\n return null;\n }\n\n const positions = splitError.pop()!;\n const trimmed = positions.replace('(', '').replace(')', '');\n const [left, right] = trimmed.split(', ');\n\n if (right) {\n return [parseInt(left), parseInt(right)];\n }\n\n return parseInt(left);\n } catch {\n return null;\n }\n};\n\nconst lintExpression = (type: string, source: string): Diagnostic[] => {\n try {\n if (!isWasmAvailable()) {\n return [];\n }\n\n const error: ExpressionError = match(type)\n .with('standard', () => validateExpression(source))\n .with('unary', () => validateUnaryExpression(source))\n .otherwise(() => null);\n if (!error) {\n return [];\n }\n\n const position = match(extractPosition(error.source))\n .with(P.number, (n) => ({ from: n, to: n }))\n .with([P.number, P.number], ([l, r]) => ({ from: l, to: r }))\n .otherwise(() => ({ from: 0, to: source.length }));\n\n const errorSource = match(error.type)\n .with('parserError', () => 'Parser error')\n .with('lexerError', () => 'Lexer error')\n .with('compilerError', () => 'Compiler error')\n .with('vmError', () => 'VM error')\n .otherwise((n) => n);\n\n return [\n {\n from: position.from,\n to: position.to,\n message: error.source,\n source: errorSource,\n severity: 'error',\n },\n ];\n } catch (err) {\n return [\n {\n from: 0,\n to: source.length,\n message: String(err),\n severity: 'error',\n },\n ];\n }\n};\n\nexport const zenLinter = (type: string) => {\n if (!isWasmAvailable()) {\n return [];\n }\n\n return codemirror.linter(\n (view) => {\n view.dom.setAttribute('data-severity', 'none');\n const tFields = view.state.field(typeField);\n\n const source = view.state.doc.toString();\n const diagnostics = validateZenExpression({\n source,\n expressionType: type as 'standard',\n strict: tFields.strict,\n types: tFields.types,\n expectedVariableType: tFields.expectedVariableType,\n });\n\n if (diagnostics.some((d) => d.severity === 'error')) {\n view.dom.setAttribute('data-severity', 'error');\n } else if (diagnostics.some((d) => d.severity === 'warning')) {\n view.dom.setAttribute('data-severity', 'warning');\n } else if (diagnostics.some((d) => d.severity === 'info')) {\n view.dom.setAttribute('data-severity', 'info');\n } else if (diagnostics.some((d) => d.severity === 'hint')) {\n view.dom.setAttribute('data-severity', 'hint');\n }\n\n return diagnostics;\n },\n {\n needsRefresh: (update) => {\n return update.transactions.some((t) =>\n t.effects.some(\n (effect) =>\n effect.is(updateExpressionTypeEffect) ||\n effect.is(updateVariableTypeEffect) ||\n effect.is(updateExpectedVariableTypeEffect) ||\n effect.is(updateStrictModeEffect),\n ),\n );\n },\n },\n );\n};\n\ntype ValidateZenExpressionParams = {\n source: string;\n expressionType?: 'standard' | 'unary';\n strict?: boolean;\n /** Generated by variableType.typeCheckUnary and variableType.typeCheckUnary **/\n types: ZenType[];\n expectedVariableType?: VariableType;\n};\n\nexport const validateZenExpression = ({\n source,\n expressionType = 'standard',\n strict = false,\n types,\n expectedVariableType,\n}: ValidateZenExpressionParams): Diagnostic[] => {\n if (source.trim().length === 0) {\n return [];\n }\n\n const expressionDiagnostics = source ? lintExpression(expressionType, source) : [];\n const typeDiagnostics: Diagnostic[] = types\n .filter((t) => !!t.error)\n .map((t) =>\n createDiagnostic({\n from: t.span[0],\n to: t.span[1],\n severity: match(t.error as string)\n .with(P.string.startsWith('Hint:'), () => 'hint' as const)\n .with(P.string.startsWith('Info:'), () => 'info' as const)\n .otherwise(() => 'warning' as const),\n message: t.error as string,\n source: 'Type check',\n }),\n );\n\n const diagnostics = [...expressionDiagnostics, ...typeDiagnostics];\n\n if (expressionType === 'unary' && types.length > 0) {\n const expressionResultKind = types[0].kind;\n if (expressionResultKind !== 'Bool') {\n diagnostics.push(\n createDiagnostic({\n from: 0,\n to: source.length,\n severity: strict ? 'error' : 'warning',\n message: `Expected unary expression to evaluate to type \\`bool\\`, received \\`${zenKindToString(expressionResultKind)}\\` instead.`,\n source: 'Type check',\n }),\n );\n }\n } else if (expectedVariableType && types.length > 0) {\n const expressionResultKind = types[0].kind;\n const expressionResultVt = VariableType.fromJson(expressionResultKind);\n const typesEqual = match([strict, expressionResultKind])\n .with([true, 'Any'], () => false)\n .otherwise(() => expressionResultVt.satisfies(expectedVariableType));\n\n if (!typesEqual) {\n diagnostics.push(\n createDiagnostic({\n from: 0,\n to: source.length,\n severity: strict ? 'error' : 'warning',\n message: `Expected expression to evaluate to type \\`${zenKindToString(expectedVariableType.toJson())}\\`, received \\`${zenKindToString(expressionResultKind)}\\` instead.`,\n source: 'Type check',\n }),\n );\n }\n }\n\n return diagnostics;\n};\n\nconst createDiagnostic = (diagnostic: Diagnostic): Diagnostic => {\n diagnostic.renderMessage = (_) => {\n const element = document.createElement('div');\n element.innerHTML = renderDiagnosticMessage({\n text: diagnostic.message,\n className: 'cm-diagnosticMessageToken',\n });\n\n return element;\n };\n\n return diagnostic;\n};\n","import {\n type Completion,\n type CompletionContext,\n type CompletionResult,\n autocompletion,\n closeBrackets,\n closeBracketsKeymap,\n} from '@codemirror/autocomplete';\nimport { history, historyKeymap, insertNewlineAndIndent } from '@codemirror/commands';\nimport { HighlightStyle, LRLanguage, LanguageSupport, syntaxTree } from '@codemirror/language';\nimport type { EditorView } from '@codemirror/view';\nimport { hoverTooltip, keymap } from '@codemirror/view';\nimport { parser as zenParser } from '@gorules/lezer-zen';\nimport { parser as zenTemplateParser } from '@gorules/lezer-zen-template';\nimport { NodeProp, type SyntaxNode, parseMixed } from '@lezer/common';\nimport { tags as t } from '@lezer/highlight';\nimport { P, match } from 'ts-pattern';\n\nimport { getCompletions } from './completion';\nimport { renderDiagnosticMessage } from './diagnostic';\nimport { zenLinter } from './linter';\nimport type { ZenType } from './types';\nimport { buildTypeCompletion, typeField, zenKindToString } from './types';\n\nexport const applyCompletion = (view: EditorView, completion: Completion, from: number, to: number) => {\n const transaction = match(completion.type)\n .with(P.union('function', 'method'), () => {\n const insert = `${completion.label}()`;\n\n return view.state.update({\n changes: { from: from, to: to, insert },\n selection: { anchor: from + insert.length - 1 }, // Place the caret inside the parentheses\n });\n })\n .otherwise(() =>\n view.state.update({\n changes: { from: from, to: to, insert: completion.label },\n selection: { anchor: from + completion.label.length },\n }),\n );\n\n view.dispatch(transaction);\n};\n\nconst makeExtendedCompletions = (): Completion[] =>\n getCompletions().map(\n (c) =>\n ({\n ...c,\n detail: c.detail.replaceAll('`', ''),\n apply: applyCompletion,\n }) satisfies Completion,\n );\n\nconst hasAutoComplete = (n: SyntaxNode | null): boolean => {\n if (!n) {\n return false;\n }\n\n const isAutoComplete = n?.type.prop(NodeProp.group)?.includes('autoComplete') || false;\n return isAutoComplete || hasAutoComplete(n?.parent);\n};\n\nconst makeExpressionCompletion = () => {\n const extendedCompletions = makeExtendedCompletions();\n const topLevelCompletions = extendedCompletions.filter((c) => c.type && ['variable', 'function'].includes(c.type));\n const methodCompletions = (type: ZenType) => {\n return extendedCompletions.filter(\n (s) =>\n s.type === 'method' &&\n match(s as unknown)\n .with({ methodFor: P._ }, ({ methodFor }) => methodFor === type.kind)\n .otherwise(() => false),\n );\n };\n\n return (context: CompletionContext): CompletionResult | null => {\n const tree = syntaxTree(context.state);\n\n const word = context.state.wordAt(context.pos);\n const node = tree.resolveInner(context.pos, -1);\n if (\n !hasAutoComplete(node) ||\n (!context.explicit && context.pos === 0) ||\n (!context.explicit && !word && node.name !== '.')\n ) {\n return null;\n }\n\n const from = word?.from ?? context.pos;\n switch (node.name) {\n case 'Standard':\n case 'VariableName':\n case '[': {\n const tField = context.state.field(typeField);\n\n return {\n from,\n options: [...buildTypeCompletion({ type: 'variable', kind: tField.rootKind }), ...topLevelCompletions],\n validFor: /\\w*/,\n };\n }\n case 'String': {\n const tField = context.state.field(typeField);\n const tBase = autoCompleteSpan(node);\n const targetType = (tField.types ?? []).find((t) => t.span[0] === tBase?.[0] && t.span[1] === tBase[1]);\n if (!targetType) {\n return null;\n }\n\n return {\n from: node.from + 1,\n options: buildTypeCompletion({ kind: targetType.kind }),\n validFor: /\\w*/,\n };\n }\n case '.':\n case 'PropertyName': {\n const tField = context.state.field(typeField);\n const tBase = autoCompleteSpan(node);\n const targetType = (tField.types ?? []).find((t) => t.span[0] === tBase?.[0] && t.span[1] === tBase[1]);\n if (!targetType) {\n return null;\n }\n\n return {\n from,\n options: [...buildTypeCompletion({ kind: targetType.kind }), ...methodCompletions(targetType)],\n validFor: /\\w*/,\n };\n }\n default:\n return null;\n }\n };\n};\n\nconst autoCompleteSpan = (node: SyntaxNode): [number, number] | null => {\n let lastNode = node;\n if (['PropertyExpression', 'PropertyAccess'].includes(lastNode.parent?.name ?? '') && lastNode.parent?.prevSibling) {\n lastNode = lastNode.parent.prevSibling;\n }\n\n let firstNode = lastNode;\n while (firstNode.prevSibling) {\n firstNode = firstNode.prevSibling;\n }\n\n return [firstNode.from, lastNode.to];\n};\n\nconst hoverSpan = (node: SyntaxNode): [number, number] | null => {\n let lastNode = node;\n if (lastNode.parent && ['PropertyExpression', 'PropertyAccess'].includes(lastNode.parent.name)) {\n lastNode = lastNode.parent;\n }\n\n let firstNode = lastNode;\n while (firstNode.prevSibling) {\n firstNode = firstNode.prevSibling;\n }\n\n return [firstNode.from, lastNode.to];\n};\n\nexport const completionExtension = () =>\n autocompletion({\n override: [makeExpressionCompletion()],\n });\n\nexport const hoverExtension = () => {\n const completions = getCompletions();\n\n return hoverTooltip(\n (view, pos) => {\n const word = view.state.wordAt(pos);\n if (!word) {\n return null;\n }\n\n const data = view.state.doc.sliceString(word.from, word.to);\n const details = completions.find((cmp) => cmp.label === data);\n if (details) {\n return {\n pos: word.from,\n end: word.to,\n above: true,\n create() {\n const dom = document.createElement('div');\n dom.classList.add('grl-ce-hover-tooltip');\n dom.style.whiteSpace = 'pre';\n dom.innerHTML = renderDiagnosticMessage({\n text: `<span style=\"font-size: 12px\">${details.info}</span>\\n${details.label}: ${details.detail}\\n`,\n className: 'cm-hoverTooltipMessageToken',\n });\n return { dom };\n },\n };\n }\n\n const tree = syntaxTree(view.state);\n const node = tree.resolveInner(pos, -1);\n\n const tField = view.state.field(typeField);\n const tBase = hoverSpan(node);\n const targetType = (tField.types ?? []).find((t) => t.span[0] === tBase?.[0] && t.span[1] === tBase[1]);\n if (targetType && tBase) {\n const source = view.state.doc.toString();\n\n return {\n pos: tBase[0],\n end: tBase[1],\n above: true,\n create() {\n const dom = document.createElement('div');\n dom.classList.add('grl-ce-hover-tooltip');\n dom.style.whiteSpace = 'pre';\n dom.innerHTML = renderDiagnosticMessage({\n text: `${source.slice(tBase[0], tBase[1])}: \\`${zenKindToString(targetType.kind)}\\``,\n className: 'cm-hoverTooltipMessageToken',\n });\n return { dom };\n },\n };\n }\n\n return null;\n },\n {\n hoverTime: 700,\n hideOnChange: true,\n },\n );\n};\n\nexport const zenStyleLight = HighlightStyle.define([\n { tag: [t.bracket, t.operator, t.variableName, t.propertyName, t.content, t.punctuation], color: '#080808' },\n { tag: [t.number, t.bool], color: '#015cc5' },\n { tag: [t.function(t.variableName), t.keyword, t.self, t.special(t.brace), t.logicOperator], color: '#6f42c1' },\n { tag: [t.string, t.meta, t.name, t.quote], color: '#077d16' },\n { tag: t.invalid, color: '#cb2431' },\n]);\n\nexport const zenStyleDark = HighlightStyle.define([\n { tag: [t.bracket, t.operator, t.variableName, t.propertyName, t.content, t.punctuation], color: '#bdbec4' },\n { tag: [t.number, t.bool], color: '#57a8f5' },\n { tag: [t.function(t.variableName), t.keyword, t.self, t.special(t.brace), t.logicOperator], color: '#c87dbb' },\n { tag: [t.string, t.meta, t.name, t.quote], color: '#6aab73' },\n { tag: t.invalid, color: '#cb2431' },\n]);\n\nexport const zenLanguage = new LanguageSupport(\n LRLanguage.define({\n parser: zenParser,\n name: 'zen',\n languageData: {\n closeBrackets: { brackets: ['(', '[', '{', \"'\", '\"', '`'] },\n wordChars: '$',\n },\n }),\n);\n\nexport const zenTemplateLanguage = new LanguageSupport(\n LRLanguage.define({\n parser: zenTemplateParser.configure({\n wrap: parseMixed((node) => {\n if (node.name === 'ExpressionInner') {\n return { parser: zenParser };\n }\n\n return null;\n }),\n }),\n name: 'zenTemplate',\n languageData: {\n closeBrackets: { brackets: ['(', '[', \"'\", '\"', '{', '`'] },\n wordChars: '$',\n },\n }),\n);\n\ntype extensionOptions = {\n type: 'unary' | 'standard' | 'template';\n lint?: boolean;\n lazy?: boolean;\n};\n\nexport const zenExtensions = ({ type, lint = true, lazy = false }: extensionOptions) => {\n if (lazy) {\n return [type !== 'template' ? zenLanguage : zenTemplateLanguage];\n }\n\n return [\n type !== 'template' ? zenLanguage : zenTemplateLanguage,\n completionExtension(),\n hoverExtension(),\n closeBrackets(),\n lint && zenLinter(type),\n typeField,\n history(),\n keymap.of([\n ...closeBracketsKeymap,\n ...historyKeymap,\n { key: 'Enter', run: insertNewlineAndIndent, shift: insertNewlineAndIndent },\n ]),\n ].filter((ext) => !!ext);\n};\n","import type { Completion } from '@codemirror/autocomplete';\nimport { StateEffect, StateField } from '@codemirror/state';\nimport type { VariableType } from '@gorules/zen-engine-wasm';\nimport { P, match } from 'ts-pattern';\n\nimport { applyCompletion } from './zen';\n\nexport type ZenType = {\n error: string | null;\n kind: any;\n nodeKind: string;\n span: [number, number];\n};\n\ntype TypeField = {\n root?: VariableType;\n expectedVariableType?: VariableType;\n source?: string;\n types: ZenType[];\n rootKind: any;\n expressionType: 'standard' | 'unary';\n strict: boolean;\n};\n\nconst defaultTypeField: TypeField = { types: [], rootKind: 'Any', expressionType: 'standard', strict: false };\n\nexport const updateVariableTypeEffect = StateEffect.define<VariableType | null>();\nexport const updateExpressionTypeEffect = StateEffect.define<'standard' | 'unary'>();\nexport const updateExpectedVariableTypeEffect = StateEffect.define<VariableType | null>();\nexport const updateStrictModeEffect = StateEffect.define<boolean>();\n\nexport const typeField = StateField.define<TypeField>({\n create() {\n return defaultTypeField;\n },\n update(value, transaction) {\n try {\n const updateExpressionType = transaction.effects.find((e) => e.is(updateExpressionTypeEffect));\n const expressionType: TypeField['expressionType'] = match(updateExpressionType)\n .with({ value: P.string }, (e) => e.value)\n .otherwise(() => value.expressionType);\n\n const updateExpectedVariableType = transaction.effects.find((e) => e.is(updateExpectedVariableTypeEffect));\n const expectedVariableType = match(updateExpectedVariableType)\n .with({ value: P.nonNullable }, ({ value }) => value)\n .with({ value: P.nullish }, () => undefined)\n .otherwise(() => value.expectedVariableType);\n\n const updateVariableType = transaction.effects.find((e) => e.is(updateVariableTypeEffect));\n const variableType: VariableType | null = match(updateVariableType)\n .with({ value: P._ }, (e) => e.value)\n .otherwise(() => value.root || null);\n\n const updateStrictMode = transaction.effects.find((e) => e.is(updateStrictModeEffect));\n const strict: boolean = match(updateStrictMode)\n .with({ value: P.boolean }, ({ value }) => value)\n .otherwise(() => value.strict);\n\n if (!variableType) {\n return { ...value, expressionType, expectedVariableType, strict };\n }\n\n // Triggered without effect and no changes, bail\n if (!transaction.docChanged && !updateExpressionType && !updateVariableType) {\n return { ...value, expressionType, expectedVariableType, strict };\n }\n\n const source = transaction.newDoc.toString();\n return {\n source,\n expressionType,\n expectedVariableType,\n strict,\n root: variableType,\n rootKind: variableType.toJson(),\n types: match(expressionType)\n .with('unary', () => variableType.typeCheckUnary(source))\n .otherwise(() => variableType.typeCheck(source)),\n } satisfies TypeField;\n } catch {\n return value;\n }\n },\n compare(a, b) {\n return (\n a.source === b.source &&\n a.expressionType === b.expressionType &&\n a.root === b.root &&\n a.expectedVariableType === b.expectedVariableType &&\n a.strict === b.strict\n );\n },\n});\n\ntype BuildTypeCompletionParams = {\n kind: any;\n type?: string;\n};\n\nexport const buildTypeCompletion = ({ kind, type = 'property' }: BuildTypeCompletionParams): Completion[] => {\n return match(kind)\n .with({ Object: P._ }, (t) =>\n Object.entries(t.Object as object).map(([k, v]) => ({\n label: k,\n type,\n boost: 50,\n detail: zenKindToString(v),\n apply: applyCompletion,\n })),\n )\n .otherwise(() => []);\n};\n\nexport const zenKindToString = (type: unknown): string =>\n match(type)\n .with(P.string, (s) => s.toLowerCase())\n .with({ Object: P._ }, () => 'object')\n .with({ Array: P._ }, (t) => `${zenKindToString(t.Array)}[]`)\n .with({ Const: P.string }, (c) => `\"${c.Const}\"`)\n .with({ Enum: P.array(P.string) }, (t) => t.Enum.map((s) => `\"${s}\"`).join(' | '))\n .otherwise(() => 'unknown');\n","import type { Extension } from '@codemirror/state';\nimport { EditorView } from '@codemirror/view';\n\n/**\n * CodeMirror SKIN as an EditorView.theme() extension (roadmap P2 / Batch D).\n *\n * Everything here used to live as CSS in `tailwind.css` under `.grl-ce …`.\n * That lost the cascade war against CM's runtime-injected unlayered\n * baseTheme and needed !important band-aids (HK-03..07). Inside theme()\n * the declarations ride CodeMirror's own precedence — strictly above\n * baseTheme — so every !important drops away legitimately.\n *\n * Values deliberately reference the SAME custom properties the old CSS did\n * (--grl-* palette + --ce-* rhythm vars). Variable resolution happens at\n * computed-value time on each consumer node, independent of stylesheet\n * layering, which preserves:\n * • data-mode flipping without re-registering anything,\n * • per-instance overrides via [--ce-*] utilities on the host container.\n *\n * Component-owned layout classes (.max-rows/.full-height/.no-style/\n * .grl-ce-single) and the manual CodeHighlighter skeleton remain plain CSS\n * on purpose — see shadcn-theming-roadmap Appendix A, HK-03.\n *\n * Shared skin extension (module-level singleton).\n *\n * Safe to share across every EditorView in the process: the spec is immutable\n * and every value is a `var()` reference, so instances never diverge. Sharing\n * also removes per-instance object allocation for editors mounted en masse\n * (decision-table cells).\n */\nexport const ZEN_SKIN: Extension = EditorView.theme({\n // ── editor shell ────────────────────────────────────────────────────────\n '&': {\n background: 'var(--grl-color-bg-container)',\n width: '100%',\n maxWidth: '100%',\n border: '1px solid var(--border)',\n borderRadius: '6px',\n transition: 'border-color, box-shadow 0.2s cubic-bezier(0.645, 0.045, 0.355, 1)',\n lineHeight: 'var(--ce-lineHeight)',\n },\n '&.cm-focused': {\n outline: 'none',\n boxShadow: '0 0 0 2px var(--grl-control-outline)',\n borderColor: 'var(--grl-color-primary-hover)',\n },\n '&:hover': {\n borderColor: 'var(--grl-color-primary-hover)',\n borderInlineEndWidth: '1px',\n },\n\n '&[data-severity=\"error\"]': {\n background: 'var(--grl-color-error-bg)',\n borderColor: 'var(--grl-color-error-border)',\n },\n '&[data-severity=\"warning\"]': {\n background: 'var(--grl-color-warning-bg)',\n borderColor: 'var(--grl-color-warning-border)',\n },\n '&[data-severity=\"info\"]': {\n background: 'var(--grl-color-info-bg)',\n borderColor: 'var(--grl-color-info-border)',\n },\n\n // lint underline strips (Images stay in CSS alongside highlighter variants)\n '& .cm-lintRange': {\n paddingBottom: '2.5px',\n backgroundPosition: 'left bottom',\n backgroundRepeat: 'repeat-x',\n },\n '& .cm-lintRange-warning': {\n backgroundImage:\n 'url(\\'data:image/svg+xml,<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"6\" height=\"3\">%3Cpath%20d%3D%22m0%202.5%20l2%20-1.5%20l1%200%20l2%201.5%20l1%200%22%20stroke%3D%22%23FFA500%22%20fill%3D%22none%22%20stroke-width%3D%221.2%22%2F%3E</svg>\\')',\n },\n '& .cm-lintRange-error': {\n backgroundImage:\n 'url(\\'data:image/svg+xml,<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"6\" height=\"3\">%3Cpath%20d%3D%22m0%202.5%20l2%20-1.5%20l1%200%20l2%201.5%20l1%200%22%20stroke%3D%22%23FF0000%22%20fill%3D%22none%22%20stroke-width%3D%221.2%22%2F%3E</svg>\\')',\n },\n '& .grl-ce-hover-tooltip': {\n fontFamily: 'var(--grl-font-family)',\n fontSize: '13px',\n background: 'var(--card)',\n border: 'none',\n borderRadius: '6px',\n color: 'var(--foreground)',\n padding: '2px 8px',\n },\n '& .cm-lintPoint': {\n WebkitUserModify: 'read-write-plaintext-only',\n },\n '& .cm-diagnosticMessageToken': {\n padding: '2px 5px 3px',\n borderRadius: '5px',\n background: 'var(--diagnostic-chip-bg)',\n },\n '& .cm-hoverTooltipMessageToken': {\n filter: 'contrast(2) brightness(0.75)',\n },\n\n // ── scroll/content geometry ─────────────────────────────────────────────\n '& .cm-scroller': {\n fontFamily: 'monospace',\n lineHeight: 'inherit',\n },\n '& .cm-widgetBuffer': { display: 'none' },\n '& .cm-placeholder': { display: 'inline' },\n '& .cm-content': {\n padding: 'var(--ce-verticalPadding) var(--ce-horizontalPadding)',\n },\n '& .cm-line': {\n padding: '0',\n caretColor: 'var(--foreground)',\n },\n '& .cm-line:focus-visible': { outline: 'none' },\n\n // ── tooltips / completion / lint popovers ───────────────────────────────\n '& .cm-tooltip': {\n fontFamily: 'var(--grl-font-family)',\n fontSize: '13px',\n background: 'var(--card)',\n border: 'none',\n borderRadius: '6px',\n color: 'var(--foreground)',\n },\n '& .cm-tooltip.cm-tooltip-below': { marginTop: '8px' },\n '& .cm-tooltip > *': {\n border: '1px solid var(--border)',\n borderRadius: '6px',\n },\n '& .cm-tooltip > ul li[aria-selected]': {\n background: 'var(--grl-color-primary-hover)',\n color: 'white',\n },\n '& .cm-tooltip > ul li[aria-selected] .cm-completionDetail': { color: 'white' },\n '& .cm-tooltip .cm-completionMatchedText': {\n textDecoration: 'none',\n color: 'var(--grl-color-primary-hover)',\n },\n '& .cm-tooltip .cm-completionDetail': {\n fontStyle: 'normal',\n color: 'var(--muted-foreground)',\n },\n '& .cm-tooltip .cm-tooltip-section:not(.cm-tooltip-lint)': {\n background: 'var(--tooltip-bg)',\n padding: '4px',\n },\n '& .cm-tooltip .cm-tooltip-lint': {\n background: 'var(--card)',\n border: '1px solid var(--border)',\n padding: '4px',\n color: 'var(--foreground)',\n },\n '& .cm-tooltip .cm-tooltip-lint .cm-diagnostic:not(:last-of-type)': { marginBottom: '4px' },\n '& .cm-tooltip .cm-tooltip-lint .cm-diagnostic-error': {\n borderLeftColor: 'var(--grl-color-error-border)',\n },\n '& .cm-tooltip .cm-tooltip-lint .cm-diagnostic-warning': {\n borderLeftColor: 'var(--grl-color-warning-border)',\n },\n '& .cm-tooltip .cm-diagnosticSource': { fontSize: '75%' },\n\n '& .cm-tooltip-autocomplete ul': { padding: '4px' },\n '& .cm-tooltip-autocomplete li': {\n padding: '4px 4px',\n display: 'flex',\n fontSize: '12px',\n color: 'var(--grl-color-text-base)',\n borderRadius: '4px',\n },\n '& .cm-tooltip-autocomplete li[aria-selected=\"true\"]': {\n backgroundColor: 'var(--border)',\n },\n '& .cm-completionIcon': { marginRight: '4px', opacity: '1' },\n '& .cm-completionIcon::after': {\n color: 'var(--icon-primary)',\n background: 'var(--icon-secondary)',\n borderRadius: '50%',\n border: '1px solid var(--icon-primary)',\n fontSize: '8px',\n width: '2.25ch',\n height: '2.25ch',\n display: 'inline-flex',\n justifyContent: 'center',\n alignItems: 'center',\n opacity: '1',\n },\n '& .cm-completionIcon-function::after': {\n 'content': \"'f'\",\n '--icon-primary': 'var(--destructive)',\n '--icon-secondary': 'var(--grl-color-error-bg)',\n },\n '& .cm-completionIcon-method::after': {\n 'content': \"'m'\",\n '--icon-primary': 'var(--destructive)',\n '--icon-secondary': 'var(--grl-color-error-bg)',\n },\n '& .cm-completionIcon-class::after': {\n 'content': \"'C'\",\n '--icon-primary': 'var(--primary)',\n '--icon-secondary': 'var(--grl-color-primary-bg)',\n },\n '& .cm-completionIcon-interface::after': {\n 'content': \"'I'\",\n '--icon-primary': 'var(--grl-color-success)',\n '--icon-secondary': 'var(--grl-color-success-bg)',\n },\n '& .cm-completionIcon-type::after': {\n 'content': \"'I'\",\n '--icon-primary': 'var(--grl-color-success)',\n '--icon-secondary': 'var(--grl-color-success-bg)',\n },\n '& .cm-completionIcon-variable::after': {\n 'content': \"'v'\",\n '--icon-primary': 'var(--grl-color-warning)',\n '--icon-secondary': 'var(--grl-color-warning-bg)',\n 'filter': 'hue-rotate(-20deg)',\n },\n '& .cm-completionIcon-constant::after': {\n 'content': \"'v'\",\n '--icon-primary': 'var(--grl-color-warning)',\n '--icon-secondary': 'var(--grl-color-warning-bg)',\n 'filter': 'hue-rotate(-20deg)',\n },\n '& .cm-completionIcon-enum::after': {\n 'content': \"'E'\",\n '--icon-primary': 'var(--primary)',\n '--icon-secondary': 'var(--grl-color-primary-bg)',\n 'filter': 'hue-rotate(35deg)',\n },\n '& .cm-completionIcon-property::after': {\n 'content': \"'P'\",\n '--icon-primary': 'var(--primary)',\n '--icon-secondary': 'var(--grl-color-primary-bg)',\n 'filter': 'hue-rotate(40deg)',\n },\n '& .cm-completionIcon-keyword::after': {\n 'content': \"'k'\",\n '--icon-primary': 'var(--grl-color-warning)',\n '--icon-secondary': 'var(--grl-color-warning-bg)',\n 'filter': 'hue-rotate(-20deg)',\n },\n '& .cm-completionIcon-namespace::after': {\n 'content': \"'n'\",\n '--icon-primary': 'var(--grl-color-success)',\n '--icon-secondary': 'var(--grl-color-success-bg)',\n },\n '& .cm-completionIcon-text::after': {\n content: \"'abc'\",\n fontSize: '50%',\n verticalAlign: 'middle',\n },\n});\n","import { bracketMatching, syntaxHighlighting } from '@codemirror/language';\nimport { Compartment, EditorState, type Extension, Text } from '@codemirror/state';\nimport { EditorView, placeholder as placeholderExt } from '@codemirror/view';\nimport { createVariableType } from '@gorules/zen-engine-wasm';\nimport clsx from 'clsx';\nimport { clamp } from 'lodash';\nimport React, { useEffect, useMemo, useRef } from 'react';\nimport { match } from 'ts-pattern';\n\nimport { composeRefs } from '../../helpers/compose-refs';\nimport { isWasmAvailable } from '../../helpers/wasm';\nimport { useThemeMode } from '../../theme';\nimport {\n updateExpectedVariableTypeEffect,\n updateExpressionTypeEffect,\n updateStrictModeEffect,\n updateVariableTypeEffect,\n} from './extensions/types';\nimport { zenExtensions, zenStyleDark, zenStyleLight } from './extensions/zen';\nimport { ZEN_SKIN } from './theme';\n\nconst zenHighlightDark = syntaxHighlighting(zenStyleDark);\nconst zenHighlightLight = syntaxHighlighting(zenStyleLight);\n\nconst editorTheme = (isDark = false) => (isDark ? zenHighlightDark : zenHighlightLight);\n\nconst updateListener = (onChange?: (data: string) => void, onStateChange?: (state: EditorState) => void) =>\n EditorView.updateListener.of((update) => {\n onStateChange?.(update.state);\n if (!update.docChanged) {\n return;\n }\n\n onChange?.(update.state.doc.toString());\n });\n\ntype ExtensionParams = {\n type?: 'standard' | 'unary' | 'template';\n};\n\nexport type CodeEditorBaseProps = {\n maxRows?: number;\n value?: string;\n onChange?: (value: string) => void;\n onStateChange?: (state: EditorState) => void;\n placeholder?: string;\n disabled?: boolean;\n type?: 'unary' | 'standard' | 'template';\n lint?: boolean;\n strict?: boolean;\n fullHeight?: boolean;\n noStyle?: boolean;\n extension?: (params: ExtensionParams) => Extension;\n livePreview?: { input: unknown; fromSimulation: boolean; result?: unknown };\n variableType?: any;\n expectedVariableType?: any;\n lazy?: boolean;\n initialSelection?: { anchor: number; head?: number };\n} & Omit<React.HTMLAttributes<HTMLDivElement>, 'disabled' | 'onChange'>;\n\nexport type CodeEditorBaseRef = HTMLDivElement & {\n codeMirror: EditorView | null;\n};\n\nexport const CodeEditorBase = React.forwardRef<CodeEditorBaseRef, CodeEditorBaseProps>(\n (\n {\n noStyle = false,\n fullHeight = false,\n strict = false,\n maxRows,\n disabled,\n value,\n onChange,\n placeholder,\n className,\n onStateChange,\n type = 'standard',\n extension,\n variableType,\n expectedVariableType,\n lint = true,\n initialSelection,\n style = {},\n ...props\n },\n ref,\n ) => {\n const container = useRef<HTMLDivElement>(null);\n const codeMirror = useRef<EditorView | null>(null);\n const mode = useThemeMode();\n\n const compartment = useMemo(\n () => ({\n zenExtension: new Compartment(),\n theme: new Compartment(),\n placeholder: new Compartment(),\n readOnly: new Compartment(),\n updateListener: new Compartment(),\n userProvided: new Compartment(),\n }),\n [],\n );\n\n useEffect(() => {\n if (!container.current || codeMirror.current) {\n return;\n }\n\n // Strict Mode workaround: defer cleanup to avoid destroying editorView\n let didMount = false;\n queueMicrotask(() => {\n didMount = true;\n });\n\n const clampSelection = (n: number) => clamp(n, 0, value?.length ?? 0);\n\n const editorView = new EditorView({\n parent: container.current,\n state: EditorState.create({\n doc: value,\n selection: initialSelection\n ? {\n head: initialSelection.head ? clampSelection(initialSelection.head) : undefined,\n anchor: clampSelection(initialSelection.anchor),\n }\n : undefined,\n extensions: [\n EditorView.lineWrapping,\n bracketMatching(),\n compartment.zenExtension.of(zenExtensions({ type, lint })),\n compartment.updateListener.of(updateListener(onChange, onStateChange)),\n compartment.theme.of(editorTheme(mode === 'dark')),\n compartment.placeholder.of(placeholder ? placeholderExt(placeholder) : []),\n compartment.readOnly.of(EditorView.editable.of(!disabled)),\n compartment.userProvided.of(extension?.({ type }) ?? []),\n // CM skin, registered LAST so it outranks the syntax-highlight\n // theme above and CM's baseTheme below. A module-level singleton:\n // values are all var() references, so every instance shares the\n // exact same immutable extension (see code-editor/theme.ts).\n ZEN_SKIN,\n ],\n }),\n });\n\n if (initialSelection) {\n editorView.focus();\n }\n\n codeMirror.current = editorView;\n if (container.current) {\n (container.current as CodeEditorBaseRef).codeMirror = editorView;\n }\n\n return () => {\n if (!didMount) return;\n\n editorView.destroy();\n codeMirror.current = null;\n };\n }, []);\n\n useEffect(() => {\n if (!codeMirror.current || value === undefined) {\n return;\n }\n\n const cm = codeMirror.current;\n if (cm.state.doc.eq(Text.of(value.split('\\n')))) {\n return;\n }\n\n const currentHead = cm.state.selection.main.head;\n const newLength = value.length;\n\n cm.dispatch({\n changes: {\n from: 0,\n to: cm.state.doc.length,\n insert: value,\n },\n // Adjust the selection if it would be out of bounds\n ...(currentHead > newLength && { selection: { anchor: newLength } }),\n });\n }, [value]);\n\n useEffect(() => {\n if (!codeMirror.current) {\n return;\n }\n\n codeMirror.current.dispatch({\n effects: compartment.theme.reconfigure(editorTheme(mode === 'dark')),\n });\n }, [mode]);\n\n useEffect(() => {\n if (!codeMirror.current) {\n return;\n }\n\n codeMirror.current.dispatch({\n effects: compartment.placeholder.reconfigure(placeholder ? placeholderExt(placeholder) : []),\n });\n }, [placeholder]);\n\n useEffect(() => {\n if (!codeMirror.current) {\n return;\n }\n\n codeMirror.current.dispatch({\n effects: compartment.readOnly.reconfigure(EditorView.editable.of(!disabled)),\n });\n }, [disabled]);\n\n useEffect(() => {\n if (!codeMirror.current) {\n return;\n }\n\n codeMirror.current.dispatch({\n effects: compartment.updateListener.reconfigure(updateListener(onChange, onStateChange)),\n });\n }, [onChange, onStateChange]);\n\n useEffect(() => {\n if (!codeMirror.current) {\n return;\n }\n\n codeMirror.current.dispatch({\n effects: [\n compartment.zenExtension.reconfigure(zenExtensions({ type, lint })),\n updateExpressionTypeEffect.of(\n match(type)\n .with('unary', () => 'unary' as const)\n .otherwise(() => 'standard' as const),\n ),\n ],\n });\n }, [type, lint]);\n\n useEffect(() => {\n if (!codeMirror.current) {\n return;\n }\n\n codeMirror.current.dispatch({\n effects: compartment.userProvided.reconfigure(extension?.({ type }) ?? []),\n });\n }, [extension, type]);\n\n useEffect(() => {\n if (!codeMirror.current || !isWasmAvailable()) {\n return;\n }\n\n if (variableType === null || variableType === undefined) {\n codeMirror.current.dispatch({\n effects: updateVariableTypeEffect.of(null),\n });\n return;\n }\n\n codeMirror.current.dispatch({\n effects: updateVariableTypeEffect.of(createVariableType(variableType)),\n });\n }, [variableType]);\n\n useEffect(() => {\n if (!codeMirror.current || !isWasmAvailable()) {\n return;\n }\n\n if (expectedVariableType === null || expectedVariableType === undefined) {\n codeMirror.current.dispatch({\n effects: updateExpectedVariableTypeEffect.of(null),\n });\n return;\n }\n\n codeMirror.current.dispatch({\n effects: updateExpectedVariableTypeEffect.of(createVariableType(expectedVariableType)),\n });\n }, [expectedVariableType]);\n\n useEffect(() => {\n if (!codeMirror.current) {\n return;\n }\n\n codeMirror.current.dispatch({\n effects: updateStrictModeEffect.of(strict),\n });\n }, [strict]);\n\n return (\n <div\n ref={composeRefs(container, ref)}\n className={clsx(\n 'grl-ce',\n maxRows && !fullHeight && 'max-rows',\n fullHeight && 'full-height',\n noStyle && 'no-style',\n className,\n )}\n style={{ '--editorMaxRows': maxRows, ...style } as React.CSSProperties}\n data-type={type}\n {...props}\n />\n );\n },\n);\n","import { syntaxTree } from '@codemirror/language';\nimport type { Diagnostic } from '@codemirror/lint';\nimport { EditorState } from '@codemirror/state';\nimport { createVariableType } from '@gorules/zen-engine-wasm';\nimport { highlightCode as lzHighlightCode } from '@lezer/highlight';\nimport clsx from 'clsx';\nimport React, { useCallback, useEffect, useMemo, useState, useTransition } from 'react';\nimport { P, match } from 'ts-pattern';\n\nimport { isWasmAvailable } from '../../helpers/wasm';\nimport { useThemeMode } from '../../theme';\nimport type { CodeEditorBaseProps } from './ce-base';\nimport { escapeHtml, renderDiagnosticMessage } from './extensions/diagnostic';\nimport { validateZenExpression } from './extensions/linter';\nimport { zenExtensions, zenStyleDark, zenStyleLight } from './extensions/zen';\n\nconst STYLE_ID = 'zen-highlight-styles';\nconst injectStyles = (theme: 'light' | 'dark') => {\n const style = theme === 'dark' ? zenStyleDark : zenStyleLight;\n const id = `${STYLE_ID}-${theme}`;\n if (typeof document === 'undefined' || document.getElementById(id)) {\n return;\n }\n\n if (style.module) {\n const styleEl = document.createElement('style');\n styleEl.id = id;\n styleEl.textContent = style.module.getRules();\n\n document.head.appendChild(styleEl);\n }\n};\n\ntype HighlightCodeParams = {\n code: string;\n type?: 'standard' | 'unary' | 'template';\n theme?: 'light' | 'dark';\n placeholder?: string;\n};\n\nexport const highlightCode = ({\n code,\n theme = 'light',\n type = 'standard',\n placeholder,\n}: HighlightCodeParams): string => {\n if (!code.trim()) {\n return `<span class=\"cm-line\">${placeholder ? `<span class=\"cm-placeholder\">${placeholder}</span>` : '<br />'}</span>`;\n }\n\n try {\n const highlightStyle = theme === 'dark' ? zenStyleDark : zenStyleLight;\n const state = EditorState.create({\n doc: code,\n extensions: [zenExtensions({ type, lazy: true })],\n });\n\n const tree = syntaxTree(state);\n if (!tree || tree.length === 0) {\n return escapeHtml(code);\n }\n\n let html = '<span class=\"cm-line\"><span class=\"cm-lintRange\">';\n\n lzHighlightCode(\n code,\n tree,\n highlightStyle,\n (text, classes) => {\n if (classes) {\n html += `<span class=\"${classes}\">${escapeHtml(text)}</span>`;\n } else {\n html += escapeHtml(text);\n }\n },\n () => {\n html += '\\n</span></span><span class=\"cm-line\"><span class=\"cm-lintRange\">';\n },\n );\n\n html += '</span></span>';\n\n return html;\n } catch (error) {\n console.warn('Syntax highlighting failed:', error);\n return escapeHtml(code);\n }\n};\n\nexport type CodeHighlighterProps = CodeEditorBaseProps;\n\nexport const CodeHighlighter = React.forwardRef<HTMLDivElement, CodeHighlighterProps>(\n (\n {\n noStyle = false,\n fullHeight = false,\n strict = false,\n maxRows,\n value,\n className,\n type = 'standard',\n variableType,\n expectedVariableType,\n lint = true,\n placeholder,\n extension: _extension,\n initialSelection: _initialSelection,\n onStateChange: _onStateChange,\n disabled: _disabled,\n onChange: _onChange,\n style = {},\n ...props\n },\n ref,\n ) => {\n const mode = useThemeMode();\n const [tooltip, setTooltip] = useState<{ x: number; y: number; diagnostics: Diagnostic[] } | null>(null);\n const [diagnostics, setDiagnostics] = useState<Diagnostic[] | null>(null);\n const [, startTransition] = useTransition();\n\n useEffect(() => {\n injectStyles(mode);\n }, [mode]);\n\n useEffect(() => {\n if (!diagnostics?.length) {\n setTooltip(null);\n }\n }, [diagnostics]);\n\n const highlighted = useMemo(\n () => highlightCode({ code: value ?? '', type, theme: mode, placeholder }),\n [value, type, mode, placeholder],\n );\n\n useEffect(() => {\n if (!value || !value.trim() || !lint || !isWasmAvailable()) {\n setDiagnostics(null);\n return;\n }\n\n startTransition(() => {\n const types = match([type, variableType])\n .with(['unary', P.nonNullable], () => createVariableType(variableType).typeCheckUnary(value))\n .with(['standard', P.nonNullable], () => createVariableType(variableType).typeCheck(value))\n .otherwise(() => []);\n\n setDiagnostics(\n validateZenExpression({\n source: value,\n expectedVariableType,\n expressionType: type as 'standard',\n strict,\n types,\n }),\n );\n });\n }, [value, lint, variableType, expectedVariableType, type, strict]);\n\n const diagnosticSeverity = useMemo(() => {\n if (!diagnostics) {\n return undefined;\n }\n\n if (diagnostics.some((d) => d.severity === 'error')) {\n return 'error';\n } else if (diagnostics.some((d) => d.severity === 'warning')) {\n return 'warning';\n } else if (diagnostics.some((d) => d.severity === 'info')) {\n return 'info';\n } else if (diagnostics.some((d) => d.severity === 'hint')) {\n return 'hint';\n }\n\n return undefined;\n }, [diagnostics]);\n\n const handleMouseEnter = useCallback(\n (e: React.MouseEvent) => {\n if (!diagnostics?.length) return;\n\n const target = e.currentTarget as HTMLElement;\n const rect = target.getBoundingClientRect();\n\n setTooltip({\n x: rect.left,\n y: rect.bottom,\n diagnostics,\n });\n },\n [diagnostics],\n );\n\n const handleMouseLeave = useCallback(() => {\n setTooltip(null);\n }, []);\n\n return (\n <div\n ref={ref}\n tabIndex={0}\n className={clsx(\n 'grl-ce',\n 'grl-ce-highlighter',\n noStyle && 'no-style',\n maxRows && !fullHeight && 'max-rows',\n fullHeight && 'full-height',\n className,\n )}\n style={{ '--editorMaxRows': maxRows, ...style } as React.CSSProperties}\n {...props}\n >\n <div className={clsx('cm-editor')} data-severity={diagnosticSeverity}>\n <div className={clsx('cm-scroller')}>\n <div\n className={clsx('cm-content', 'cm-lineWrapping')}\n onMouseEnter={handleMouseEnter}\n onMouseLeave={handleMouseLeave}\n dangerouslySetInnerHTML={{ __html: highlighted }}\n />\n </div>\n {tooltip && (\n <div\n className='cm-tooltip-hover cm-tooltip cm-tooltip-below'\n style={{\n position: 'fixed',\n top: `${tooltip.y}px`,\n left: `${tooltip.x}px`,\n }}\n >\n <ul className='cm-tooltip-lint cm-tooltip-section'>\n {tooltip.diagnostics.map((diagnostic, idx) => (\n <li key={idx} className={`cm-diagnostic cm-diagnostic-${diagnostic.severity}`}>\n <span className='cm-diagnosticText'>\n <div\n dangerouslySetInnerHTML={{\n __html: renderDiagnosticMessage({\n text: diagnostic.message,\n className: 'cm-diagnosticMessageToken',\n }),\n }}\n />\n </span>\n {diagnostic.source && <div className='cm-diagnosticSource'>{diagnostic.source}</div>}\n </li>\n ))}\n </ul>\n </div>\n )}\n </div>\n </div>\n );\n },\n);\n","import { syntaxHighlighting } from '@codemirror/language';\nimport { Compartment, EditorState } from '@codemirror/state';\nimport { EditorView, placeholder as placeholderExt } from '@codemirror/view';\nimport React, { createContext, useContext, useEffect, useLayoutEffect, useMemo, useRef } from 'react';\n\nimport { useThemeMode } from '../../theme';\nimport { zenLanguage, zenStyleDark, zenStyleLight, zenTemplateLanguage } from './extensions/zen';\nimport { ZEN_SKIN } from './theme';\n\n/**\n * CellViewPool (roadmap P2 phase-2 revival, §3.6 design).\n *\n * Table-scope pool of read-only display EditorViews. Cells acquire on mount,\n * release on unmount; acquire re-parents `view.dom`, swaps the doc, and\n * reconfigures placeholder/highlight compartments — orders of magnitude\n * cheaper than creating an EditorView per visible cell on every scroll.\n *\n * Soft capacity: requests beyond the cap degrade to standalone create/destroy\n * (never a blank cell). No history, no editing: display only, so nothing\n * user-owned lives in a pooled view and cross-cell bleed is impossible.\n */\n\nexport type DisplayType = 'standard' | 'unary' | 'template';\n\ntype PooledView = {\n view: EditorView;\n ph: Compartment;\n hl: Compartment;\n bucket: DisplayType;\n};\n\nconst languageFor = (type: DisplayType) => (type === 'template' ? zenTemplateLanguage : zenLanguage);\n\nfunction createDisplayView(bucket: DisplayType, dark: boolean, placeholder?: string): PooledView {\n const ph = new Compartment();\n const hl = new Compartment();\n const view = new EditorView({\n state: EditorState.create({\n doc: '',\n extensions: [\n // full skin: pooled display views must be pixel-identical to the live\n // editor they hand off to (content padding, line metrics, caret colors)\n ZEN_SKIN,\n EditorView.editable.of(false),\n EditorState.readOnly.of(true),\n EditorView.lineWrapping,\n languageFor(bucket),\n hl.of(syntaxHighlighting(dark ? zenStyleDark : zenStyleLight)),\n ph.of(placeholder ? placeholderExt(placeholder) : []),\n ],\n }),\n });\n return { view, ph, hl, bucket };\n}\n\nconst configure = (pv: PooledView, dark: boolean, placeholder?: string) => {\n pv.view.dispatch({\n effects: [\n pv.hl.reconfigure(syntaxHighlighting(dark ? zenStyleDark : zenStyleLight)),\n pv.ph.reconfigure(placeholder ? placeholderExt(placeholder) : []),\n ],\n });\n};\n\nconst setDoc = (pv: PooledView, value: string) => {\n // full replacement: `to` is REQUIRED — omitting it turns the change into an\n // insert at 0 and pooled views accumulate previous cells' docs\n pv.view.dispatch({ changes: { from: 0, to: pv.view.state.doc.length, insert: value } });\n};\n\nclass CellViewPoolImpl {\n private free = new Map<DisplayType, PooledView[]>();\n private live = 0;\n\n constructor(readonly capacity: number) {}\n\n get exhausted(): boolean {\n return this.live >= this.capacity;\n }\n\n acquire(bucket: DisplayType, dark: boolean, placeholder?: string): PooledView | null {\n if (this.exhausted) return null;\n const q = this.free.get(bucket);\n const reused = q?.pop();\n if (reused) {\n configure(reused, dark, placeholder);\n return reused;\n }\n this.live += 1;\n return createDisplayView(bucket, dark, placeholder);\n }\n\n release(pv: PooledView): void {\n pv.view.dispatch({\n changes: { from: 0, to: pv.view.state.doc.length, insert: '' },\n selection: { anchor: 0 },\n });\n pv.view.dom.remove();\n const q = this.free.get(pv.bucket) ?? [];\n q.push(pv);\n this.free.set(pv.bucket, q);\n }\n\n destroyAll(): void {\n for (const q of this.free.values()) {\n for (const pv of q) pv.view.destroy();\n }\n this.free.clear();\n }\n}\n\nconst PoolContext = createContext<CellViewPoolImpl | null>(null);\n\nexport const CellViewPoolProvider: React.FC<React.PropsWithChildren<{ capacity?: number }>> = ({\n capacity = 64,\n children,\n}) => {\n const pool = useMemo(() => new CellViewPoolImpl(capacity), [capacity]);\n useEffect(() => () => pool.destroyAll(), [pool]);\n return <PoolContext.Provider value={pool}>{children}</PoolContext.Provider>;\n};\n\nconst usePool = (): CellViewPoolImpl | null => useContext(PoolContext);\n\n/**\n * Attaches a recycled read-only display view to the returned host ref.\n * Falls back to standalone create/destroy when no provider is present or the\n * pool is exhausted.\n */\nexport const useRecycledEditorView = ({\n value,\n type,\n placeholder,\n}: {\n value: string;\n type: DisplayType;\n placeholder?: string;\n}): React.RefCallback<HTMLDivElement> => {\n const pool = usePool();\n const hostRef = useRef<HTMLDivElement | null>(null);\n const pvRef = useRef<PooledView | null>(null);\n const standaloneRef = useRef<EditorView | null>(null);\n const mode = useThemeMode();\n const dark = mode === 'dark';\n\n // mount: acquire or create; unmount: release or destroy\n useLayoutEffect(() => {\n const host = hostRef.current;\n if (!host) return;\n\n const pooled = pool?.acquire(type, dark, placeholder);\n if (pooled) {\n pvRef.current = pooled;\n host.appendChild(pooled.view.dom);\n setDoc(pooled, value);\n pooled.view.requestMeasure();\n } else {\n const created = createDisplayView(type, dark, placeholder);\n pvRef.current = created;\n standaloneRef.current = created.view;\n host.appendChild(created.view.dom);\n created.view.dispatch({ changes: { from: 0, insert: value } });\n created.view.requestMeasure();\n }\n\n return () => {\n const pv = pvRef.current;\n if (!pv) return;\n if (standaloneRef.current === pv.view) {\n pv.view.destroy();\n standaloneRef.current = null;\n } else if (pool) {\n pool.release(pv);\n }\n pvRef.current = null;\n };\n // value remount contract matches the lazy highlighter path\n }, [value, type, dark, placeholder, pool]);\n\n // live reconfiguration while mounted (mode / placeholder)\n useLayoutEffect(() => {\n const pv = pvRef.current;\n if (!pv) return;\n pv.view.dispatch({\n effects: [\n pv.hl.reconfigure(syntaxHighlighting(dark ? zenStyleDark : zenStyleLight)),\n pv.ph.reconfigure(placeholder ? placeholderExt(placeholder) : []),\n ],\n });\n }, [dark, placeholder]);\n\n return React.useCallback((el: HTMLDivElement | null) => {\n hostRef.current = el;\n }, []);\n};\n","import clsx from 'clsx';\nimport React, { forwardRef } from 'react';\n\nimport { type DisplayType, useRecycledEditorView } from './cell-view-pool';\n\n/**\n * Read-only display surface backed by a RECYCLED EditorView from the\n * Table-scope CellViewPool (roadmap §3.6 revival, Phase 1). Falls back to\n * standalone create/destroy when no pool provider is present.\n * Default ON since the V batch (a7d9c719) — opt out with gru-hl-view='0'.\n */\nexport type CodeHighlighterViewProps = {\n value: string;\n type?: DisplayType;\n placeholder?: string;\n className?: string;\n maxRows?: number;\n fullHeight?: boolean;\n noStyle?: boolean;\n style?: React.CSSProperties;\n} & React.HTMLAttributes<HTMLDivElement>;\n\nexport const CodeHighlighterView = forwardRef<HTMLDivElement, CodeHighlighterViewProps>((propsIn, fwdRef) => {\n const {\n value,\n type = 'standard',\n placeholder,\n className,\n maxRows,\n fullHeight,\n noStyle,\n style = {},\n ...handlers\n } = propsIn;\n\n const hostRef = useRecycledEditorView({ value, type, placeholder });\n\n return (\n <div\n ref={(el) => {\n hostRef(el);\n if (typeof fwdRef === 'function') fwdRef(el);\n else if (fwdRef && typeof fwdRef === 'object') fwdRef.current = el;\n }}\n {...handlers}\n className={clsx(\n 'grl-ce',\n 'grl-ce-highlighter-view',\n noStyle && 'no-style',\n maxRows && !fullHeight && 'max-rows',\n fullHeight && 'full-height',\n className,\n )}\n style={{ '--editorMaxRows': maxRows, ...style } as React.CSSProperties}\n />\n );\n});\n","import React, { useCallback, useRef, useState } from 'react';\n\nimport { composeRefs } from '../../helpers/compose-refs';\nimport type { CodeEditorBaseProps, CodeEditorBaseRef } from './ce-base';\nimport { CodeEditorBase } from './ce-base';\nimport { CodeHighlighter } from './ce-highlight';\nimport { CodeHighlighterView } from './ce-highlight-view';\n\n/**\n * Pooled display path (A2 revival) — DEFAULT ON since the major release\n * (Phase 2 guards green; grayscale period complete). Opt OUT with\n * `localStorage.gru-hl-view = '0'` (escape hatch, not a supported config).\n */\nconst highlighterViewEnabled = (): boolean =>\n typeof localStorage === 'undefined' || localStorage.getItem('gru-hl-view') !== '0';\n\nexport type CodeEditorRef = CodeEditorBaseRef;\n\nexport type CodeEditorProps = CodeEditorBaseProps & {\n lazy?: boolean;\n};\n\nconst getCursorPositionFromClick = (\n event: React.MouseEvent,\n containerElement: HTMLElement,\n): CodeEditorProps['initialSelection'] | null => {\n const selection = document.getSelection();\n if (selection && selection.rangeCount > 0) {\n const range = selection.getRangeAt(0);\n\n const startRange = document.createRange();\n startRange.selectNodeContents(containerElement);\n startRange.setEnd(range.startContainer, range.startOffset);\n\n const endRange = document.createRange();\n endRange.selectNodeContents(containerElement);\n endRange.setEnd(range.endContainer, range.endOffset);\n\n return {\n anchor: startRange.toString().length,\n head: endRange.toString().length,\n };\n }\n\n const position = document.caretPositionFromPoint(event.clientX, event.clientY);\n if (!position) {\n return null;\n }\n\n const preRange = document.createRange();\n preRange.selectNodeContents(containerElement);\n preRange.setEnd(position.offsetNode, position.offset);\n\n return { anchor: preRange.toString().length };\n};\n\ntype EditorState = { type: 'lazy' } | { type: 'edit'; initialSelection?: CodeEditorProps['initialSelection'] };\n\nexport const CodeEditor = React.forwardRef<CodeEditorRef, CodeEditorProps>(\n ({ lazy = false, value = '', type = 'standard', disabled, onBlur, ...props }, ref) => {\n const [editorState, setEditorState] = useState<EditorState>(() => (lazy ? { type: 'lazy' } : { type: 'edit' }));\n const containerRef = useRef<HTMLDivElement>(null);\n const isMouseDownRef = useRef(false);\n\n const handleMouseDown = useCallback(\n (event: React.MouseEvent) => {\n isMouseDownRef.current = true;\n\n // Suppress the browser's default caret/selection + focus so the lazy\n // highlighter hands off cleanly to the live editor. This also prevents\n // the cell-level `onFocus` re-render from swallowing the gesture.\n event.preventDefault();\n\n if (disabled || editorState.type !== 'lazy') {\n return;\n }\n\n const selection = containerRef.current\n ? (getCursorPositionFromClick(event, containerRef.current) ?? { anchor: value.length })\n : { anchor: value.length };\n\n setEditorState({ type: 'edit', initialSelection: selection });\n },\n [disabled, editorState.type, value],\n );\n\n const handleMouseUp = useCallback(() => {\n isMouseDownRef.current = false;\n }, []);\n\n const handleClick = useCallback(\n (event: React.MouseEvent) => {\n if (disabled || editorState.type !== 'lazy') {\n return;\n }\n\n const selection = containerRef.current\n ? (getCursorPositionFromClick(event, containerRef.current) ?? undefined)\n : undefined;\n\n setEditorState({ type: 'edit', initialSelection: selection });\n },\n [disabled, editorState.type],\n );\n\n const handleFocus = useCallback(\n (_event: React.FocusEvent<HTMLDivElement, Element>) => {\n if (disabled || editorState.type !== 'lazy' || isMouseDownRef.current) {\n return;\n }\n\n setEditorState({ type: 'edit', initialSelection: { anchor: value.length } });\n },\n [disabled, editorState.type, value],\n );\n\n const handleBlur = useCallback(\n (event: React.FocusEvent<HTMLDivElement, HTMLDivElement>) => {\n onBlur?.(event);\n\n if (lazy) {\n setEditorState({ type: 'lazy' });\n }\n },\n [lazy, onBlur],\n );\n\n // Consumer-supplied DOM handlers must still fire, but internal behavior\n // must never be clobbered when callers pass e.g. onFocus via props\n // (previously `{...props}` sat AFTER these and silently replaced them).\n // Internal handlers run LAST and are post-transition no-ops by guard, so a\n // chained click/focus can never double-trigger the lazy→edit transition.\n const chainMouse =\n (...handlers: (((event: React.MouseEvent<HTMLDivElement>) => void) | undefined)[]) =>\n (event: React.MouseEvent<HTMLDivElement>) => {\n for (const handler of handlers) {\n handler?.(event);\n }\n };\n const chainFocus =\n (...handlers: (((event: React.FocusEvent<HTMLDivElement>) => void) | undefined)[]) =>\n (event: React.FocusEvent<HTMLDivElement>) => {\n for (const handler of handlers) {\n handler?.(event);\n }\n };\n\n const { onClick, onFocus, onMouseDown, onMouseUp, ...restProps } = props;\n\n if (editorState.type === 'edit' || !lazy) {\n return (\n <CodeEditorBase\n ref={ref}\n {...restProps}\n value={value}\n type={type}\n disabled={disabled}\n initialSelection={editorState.type === 'edit' ? editorState.initialSelection : undefined}\n onClick={chainMouse(onClick)}\n onMouseDown={chainMouse(onMouseDown)}\n onMouseUp={chainMouse(onMouseUp)}\n onFocus={chainFocus(onFocus)}\n onBlur={handleBlur}\n />\n );\n }\n\n if (highlighterViewEnabled()) {\n return (\n <CodeHighlighterView\n ref={composeRefs(containerRef, ref)}\n type={type as 'standard' | 'unary' | 'template'}\n value={value}\n placeholder={props.placeholder}\n className={props.className}\n maxRows={props.maxRows}\n fullHeight={props.fullHeight}\n noStyle={props.noStyle}\n style={props.style}\n onClick={handleClick}\n onMouseDown={handleMouseDown}\n onMouseUp={handleMouseUp}\n onFocus={handleFocus}\n />\n );\n }\n\n return (\n <CodeHighlighter\n ref={composeRefs(containerRef, ref)}\n {...restProps}\n type={type}\n value={value}\n disabled={disabled}\n onClick={chainMouse(onClick, handleClick)}\n onFocus={chainFocus(onFocus, handleFocus)}\n onMouseDown={chainMouse(onMouseDown, handleMouseDown)}\n onMouseUp={chainMouse(onMouseUp, handleMouseUp)}\n />\n );\n },\n);\n","import type { CodeEditorBaseRef } from '../ce-base';\n\nexport type BuilderRef = { focus: () => void };\n\nexport const focusBuilderRoot = (el: HTMLElement | null) => {\n if (!el) return;\n const ceEl = el.querySelector<CodeEditorBaseRef>('.grl-ce');\n if (ceEl?.codeMirror) {\n const view = ceEl.codeMirror;\n view.focus();\n view.dispatch({ selection: { anchor: view.state.doc.length } });\n return;\n }\n const input = el.querySelector<HTMLInputElement | HTMLTextAreaElement>('input, textarea');\n if (input) {\n input.focus();\n if ('selectionStart' in input) {\n input.selectionStart = input.selectionEnd = input.value.length;\n }\n }\n};\n","import type { SimpleOperator, SimpleValue } from '@gorules/zen-engine-wasm';\nimport dayjs from 'dayjs';\nimport {\n ArrowLeftRightIcon,\n AsteriskIcon,\n CalendarCheckIcon,\n CalendarIcon,\n CalendarMinusIcon,\n CalendarPlusIcon,\n CircleDotIcon,\n CircleSlashIcon,\n ClockArrowDownIcon,\n ClockArrowUpIcon,\n EqualIcon,\n EqualNotIcon,\n ListIcon,\n ListXIcon,\n type LucideIcon,\n SearchIcon,\n TextCursorInputIcon,\n} from 'lucide-react';\nimport type { CSSProperties } from 'react';\nimport { P, match } from 'ts-pattern';\n\nimport type { ColumnFieldType } from '../../../../helpers/schema';\nimport type { DictionaryMap } from '../../../../theme';\n\nexport const BUILDER_TOKENS: CSSProperties = {\n '--b-font-size': '13px',\n '--b-line-height': '1.5',\n '--b-v-padding': '2px',\n '--b-h-padding': '4px',\n '--b-height': 'calc(var(--b-font-size) * var(--b-line-height) + var(--b-v-padding) * 2)',\n '--b-max-height': 'calc(var(--b-height) * var(--b-max-rows))',\n} as CSSProperties;\n\nexport const BUILDER_BG_VARS: CSSProperties = {\n '--bg-light': 'var(--muted)',\n '--bg-active': 'var(--grl-color-primary-bg)',\n '--color-active-text': 'var(--primary)',\n} as CSSProperties;\n\n// Single-line fields (native input / Radix trigger): fixed compact height,\n// builder side padding and font so every field's box and first-character\n// inset match the autosize textarea.\nexport const FIELD_COMPACT = 'h-[var(--b-height)]! border-0! px-[var(--b-h-padding)]! py-0! text-[13px]!';\n// Multi/tags native input: auto height, min builder height, side padding.\nexport const FIELD_AUTO =\n 'min-h-[var(--b-height)]! h-auto! border-0! px-[var(--b-h-padding)]! text-[13px]! overflow-hidden';\n\nexport type OperatorType = SimpleOperator['type'];\nexport type ValueKind = 'string' | 'number' | 'boolean' | 'date' | 'any';\n\nexport const VALUE_KINDS: { kind: ValueKind; label: string }[] = [\n { kind: 'string', label: 'Text' },\n { kind: 'number', label: 'Number' },\n { kind: 'boolean', label: 'Boolean' },\n { kind: 'date', label: 'Date' },\n];\n\nexport type Op = { type: OperatorType; icon?: LucideIcon; symbol?: string; rotate?: boolean; label: string };\n\nexport const OPS: Op[] = [\n { type: 'eq', icon: EqualIcon, label: 'equals' },\n { type: 'neq', icon: EqualNotIcon, label: 'not equals' },\n { type: 'gt', symbol: '>', label: 'greater than' },\n { type: 'gte', symbol: '≥', label: 'greater or equal' },\n { type: 'lt', symbol: '<', label: 'less than' },\n { type: 'lte', symbol: '≤', label: 'less or equal' },\n { type: 'in', icon: ListIcon, label: 'is one of' },\n { type: 'notIn', icon: ListXIcon, label: 'is not one of' },\n { type: 'between', icon: ArrowLeftRightIcon, label: 'between' },\n { type: 'null', icon: CircleSlashIcon, label: 'is empty' },\n { type: 'notNull', icon: CircleDotIcon, label: 'is not empty' },\n { type: 'any', icon: AsteriskIcon, label: 'any' },\n { type: 'startsWith', icon: TextCursorInputIcon, label: 'starts with' },\n { type: 'endsWith', icon: TextCursorInputIcon, rotate: true, label: 'ends with' },\n { type: 'contains', icon: SearchIcon, label: 'contains' },\n { type: 'dateAfter', icon: CalendarPlusIcon, label: 'after' },\n { type: 'dateBefore', icon: CalendarMinusIcon, label: 'before' },\n { type: 'dateSame', icon: CalendarCheckIcon, label: 'same day' },\n { type: 'dateSameOrAfter', symbol: '≥', label: 'same or after' },\n { type: 'dateSameOrBefore', symbol: '≤', label: 'same or before' },\n { type: 'dateIsToday', icon: CalendarIcon, label: 'is today' },\n { type: 'timeGt', icon: ClockArrowUpIcon, label: 'time after' },\n { type: 'timeGte', icon: ClockArrowUpIcon, label: 'time at or after' },\n { type: 'timeLt', icon: ClockArrowDownIcon, label: 'time before' },\n { type: 'timeLte', icon: ClockArrowDownIcon, label: 'time at or before' },\n { type: 'dayOfWeekIn', icon: CalendarIcon, label: 'day is one of' },\n { type: 'quarterIn', icon: CalendarIcon, label: 'quarter is one of' },\n];\n\nexport const getOp = (type: OperatorType): Op => OPS.find((o) => o.type === type) ?? OPS[0];\n\nexport const OPS_BY_KIND: Record<ValueKind, OperatorType[]> = {\n string: ['eq', 'neq', 'in', 'notIn', 'startsWith', 'endsWith', 'contains', 'null', 'notNull', 'any'],\n number: ['eq', 'neq', 'gt', 'gte', 'lt', 'lte', 'in', 'notIn', 'between', 'null', 'notNull', 'any'],\n boolean: ['eq', 'null', 'notNull', 'any'],\n date: [\n 'dateAfter',\n 'dateBefore',\n 'dateSame',\n 'dateSameOrAfter',\n 'dateSameOrBefore',\n 'dateIsToday',\n 'timeGt',\n 'timeGte',\n 'timeLt',\n 'timeLte',\n 'dayOfWeekIn',\n 'quarterIn',\n 'null',\n 'notNull',\n 'any',\n ],\n any: OPS.map((o) => o.type),\n};\n\nexport const GRID_OPS: Record<ValueKind, OperatorType[]> = {\n string: ['eq', 'neq', 'in', 'startsWith', 'endsWith', 'contains'],\n number: ['eq', 'neq', 'gt', 'gte', 'lt', 'lte'],\n boolean: ['eq', 'null', 'notNull', 'any'],\n date: ['dateAfter', 'dateBefore', 'dateSame', 'dateIsToday', 'dayOfWeekIn', 'quarterIn'],\n any: ['eq', 'neq', 'gt', 'gte', 'lt', 'lte'],\n};\n\nexport const NO_VALUE_OPS: OperatorType[] = ['null', 'notNull', 'any', 'dateIsToday'];\n\nexport const GRANULARITIES = [\n { value: '', label: 'Exact' },\n { value: 'day', label: 'Day' },\n { value: 'week', label: 'Week' },\n { value: 'month', label: 'Month' },\n { value: 'quarter', label: 'Quarter' },\n { value: 'year', label: 'Year' },\n];\n\nexport const getValueKind = (ft?: ColumnFieldType): ValueKind =>\n match(ft?.type)\n .with('string', () => 'string' as const)\n .with('number', () => 'number' as const)\n .with('boolean', () => 'boolean' as const)\n .with('date', () => 'date' as const)\n .otherwise(() => 'any' as const);\n\nexport const enumFilterOption = (input: string, option?: { label?: unknown; value?: unknown }) => {\n const search = input.toLowerCase();\n const hay = [String(option?.label ?? ''), String(option?.value ?? '')].join(' ').toLowerCase();\n return hay.includes(search);\n};\n\nexport const getEnumOptions = (\n ft?: ColumnFieldType,\n dictionaries?: DictionaryMap,\n): { values: { label: string; value: string }[]; loose: boolean } | null => {\n if (ft?.type !== 'string' || !ft.enum) return null;\n const e = ft.enum;\n if (e.type === 'inline') {\n return e.values.length ? { values: e.values, loose: e.loose ?? false } : null;\n }\n const resolved = dictionaries?.[e.ref];\n return resolved?.length ? { values: resolved, loose: e.loose ?? false } : null;\n};\n\nexport const defaultValue = (op: OperatorType, kind: ValueKind): SimpleValue | null =>\n match(op)\n .with(\n P.when((o) => NO_VALUE_OPS.includes(o)),\n () => null,\n )\n .with(\n 'between',\n () => ({ type: 'interval', left: 0, right: 100, leftInclusive: true, rightInclusive: true }) as SimpleValue,\n )\n .with(\n 'in',\n 'notIn',\n () =>\n (kind === 'number' ? { type: 'numberArray', values: [] } : { type: 'stringArray', values: [] }) as SimpleValue,\n )\n .with(\n 'dateAfter',\n 'dateBefore',\n 'dateSame',\n 'dateSameOrAfter',\n 'dateSameOrBefore',\n () => ({ type: 'date', value: dayjs().format('YYYY-MM-DD') }) as SimpleValue,\n )\n .with('timeGt', 'timeGte', 'timeLt', 'timeLte', () => ({ type: 'time', hour: 9, minute: 0 }) as SimpleValue)\n .with('dayOfWeekIn', () => ({ type: 'intArray', values: [1, 2, 3, 4, 5] }) as SimpleValue)\n .with('quarterIn', () => ({ type: 'intArray', values: [1] }) as SimpleValue)\n .with('startsWith', 'endsWith', 'contains', () => ({ type: 'string', value: '' }) as SimpleValue)\n .otherwise(() =>\n match(kind)\n .with('number', () => ({ type: 'number', value: 0 }) as SimpleValue)\n .with('boolean', () => ({ type: 'boolean', value: true }) as SimpleValue)\n .otherwise(() => ({ type: 'string', value: '' }) as SimpleValue),\n );\n","import React from 'react';\n\nimport type { Op } from './constants';\n\nexport const OpIcon: React.FC<{ op: Op; size: number; className?: string }> = ({ op, size, className }) =>\n op.icon ? (\n <op.icon size={size} className={className} style={op.rotate ? { transform: 'rotate(180deg)' } : undefined} />\n ) : (\n <span className={className} style={{ fontSize: size }}>\n {op.symbol}\n </span>\n );\n","import clsx from 'clsx';\nimport { SquareFunctionIcon } from 'lucide-react';\nimport React, { useState } from 'react';\n\nimport { useT } from '../../../../theming/i18n';\nimport { Popover } from '../../../primitives';\nimport { GRID_OPS, OPS_BY_KIND, type OperatorType, VALUE_KINDS, type ValueKind, getOp } from './constants';\nimport { OpIcon } from './op-icon';\n\nexport type OpDropdownProps = {\n kind: ValueKind;\n operator: OperatorType;\n isCustom?: boolean;\n onSelect: (op: OperatorType) => void;\n onKindChange?: (kind: ValueKind) => void;\n onCustomToggle?: () => void;\n disabled?: boolean;\n};\n\nexport const OpDropdown: React.FC<OpDropdownProps> = ({\n kind,\n operator,\n isCustom,\n onSelect,\n onKindChange,\n onCustomToggle,\n disabled,\n}) => {\n const t = useT();\n const [open, setOpen] = useState(false);\n const [search, setSearch] = useState('');\n\n const grid = GRID_OPS[kind].map(getOp);\n const list = OPS_BY_KIND[kind].filter((t) => !GRID_OPS[kind].includes(t)).map(getOp);\n const filtered = list.filter((o) => !search || o.label.toLowerCase().includes(search.toLowerCase()));\n\n const pick = (t: OperatorType) => {\n onSelect(t);\n setOpen(false);\n setSearch('');\n };\n\n const content = (\n <div\n className='bg-popover'\n style={\n {\n '--bg-light': 'var(--muted)',\n '--bg-active': 'var(--grl-color-primary-bg)',\n '--color-active-text': 'var(--primary)',\n } as React.CSSProperties\n }\n >\n {onKindChange && (\n <div className='flex gap-1.5 border-b border-border p-2'>\n {VALUE_KINDS.map((t) => (\n <button\n key={t.kind}\n className={clsx(\n 'cursor-pointer rounded-md border-0 bg-muted px-2.5 py-1 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-accent-foreground',\n t.kind === kind &&\n 'bg-[var(--bg-active)] text-[var(--color-active-text)] hover:bg-[var(--bg-active)] hover:text-[var(--color-active-text)]',\n )}\n onClick={() => onKindChange(t.kind)}\n >\n {t.label}\n </button>\n ))}\n </div>\n )}\n <div className='flex'>\n <div className='grid shrink-0 grid-cols-2 gap-1.5 p-2.5'>\n {grid.map((o) => {\n const isSel = o.type === operator && !isCustom;\n return (\n <button\n key={o.type}\n className={clsx(\n 'flex h-[72px] w-[92px] cursor-pointer flex-col items-center justify-center rounded-xl border border-border bg-card transition-all hover:border-[var(--grl-color-primary-border)] hover:bg-[var(--bg-active)]',\n isSel && 'border-[var(--grl-color-primary-border)] bg-[var(--bg-active)]',\n )}\n onClick={() => pick(o.type)}\n >\n <OpIcon\n op={o}\n size={20}\n className={clsx('mb-1 text-foreground', isSel && 'text-[var(--color-active-text)]')}\n />\n <span\n className={clsx(\n 'text-[11px] text-muted-foreground',\n isSel && 'font-medium text-[var(--color-active-text)]',\n )}\n >\n {o.label}\n </span>\n </button>\n );\n })}\n {onCustomToggle && (\n <button\n className={clsx(\n 'col-span-2 flex h-12 w-auto cursor-pointer flex-row items-center justify-center gap-2 rounded-xl border border-border bg-card transition-all hover:border-[var(--grl-color-primary-border)] hover:bg-[var(--bg-active)]',\n isCustom && 'border-[var(--grl-color-primary-border)] bg-[var(--bg-active)]',\n )}\n onClick={() => {\n onCustomToggle();\n setOpen(false);\n }}\n >\n <SquareFunctionIcon size={20} className='mb-0 text-foreground' />\n <span className='text-[11px] text-muted-foreground'>custom</span>\n </button>\n )}\n </div>\n {list.length > 0 && (\n <div className='flex min-w-[170px] flex-1 flex-col border-l border-border bg-muted/40 p-2.5'>\n <input\n className='mb-1.5 w-full rounded-md border border-input bg-transparent px-2.5 py-1.5 text-xs text-foreground outline-none transition-colors placeholder:text-muted-foreground focus:border-ring focus:ring-1 focus:ring-ring/30'\n placeholder={t('misc.search')}\n value={search}\n onChange={(e) => setSearch(e.target.value)}\n />\n <div className='flex max-h-[208px] flex-col gap-0.5 overflow-y-auto'>\n {filtered.map((o) => {\n const isSel = o.type === operator && !isCustom;\n return (\n <button\n key={o.type}\n className={clsx(\n 'flex w-full cursor-pointer items-center gap-2.5 rounded-md border-0 bg-transparent px-2 py-1.5 text-left transition-colors hover:bg-accent',\n isSel && 'bg-[var(--bg-active)]',\n )}\n onClick={() => pick(o.type)}\n >\n <OpIcon\n op={o}\n size={16}\n className={clsx('w-5 shrink-0 text-muted-foreground', isSel && 'text-[var(--color-active-text)]')}\n />\n <span\n className={clsx(\n 'text-xs text-foreground',\n isSel && 'font-medium text-[var(--color-active-text)]',\n )}\n >\n {o.label}\n </span>\n </button>\n );\n })}\n {!filtered.length && <div className='p-3 text-center text-xs text-muted-foreground'>No matches</div>}\n </div>\n </div>\n )}\n </div>\n </div>\n );\n\n return (\n <Popover\n content={content}\n trigger='click'\n open={open}\n onOpenChange={(v) => {\n setOpen(v);\n if (!v) setSearch('');\n }}\n placement='bottomLeft'\n arrow={false}\n >\n <button\n className='inline-flex cursor-pointer items-center justify-center rounded-md border-0 bg-muted px-2 text-[13px] text-muted-foreground transition-colors min-h-[var(--b-height)] min-w-[26px] enabled:hover:bg-accent enabled:hover:text-accent-foreground disabled:cursor-not-allowed disabled:opacity-50'\n disabled={disabled}\n >\n {isCustom ? <SquareFunctionIcon size={14} /> : <OpIcon op={getOp(operator)} size={14} />}\n </button>\n </Popover>\n );\n};\n","import type { ExpressionBuilderData, SimpleValue } from '@gorules/zen-engine-wasm';\nimport { ExpressionBuilder as ExpressionBuilderWasm } from '@gorules/zen-engine-wasm';\nimport { useCallback, useEffect, useMemo, useState } from 'react';\nimport { match } from 'ts-pattern';\n\nimport { NO_VALUE_OPS, OPS_BY_KIND, type ValueKind } from './constants';\n\nexport const inferKindFromExpr = (data: ExpressionBuilderData): ValueKind | null => {\n if (data.kind !== 'simple') return null;\n const op = data.operator.type;\n if (op.startsWith('date') || op.startsWith('time') || op === 'dayOfWeekIn' || op === 'quarterIn') return 'date';\n if (['startsWith', 'endsWith', 'contains'].includes(op)) return 'string';\n const val = data.value;\n if (!val) return null;\n return match(val.type)\n .with('string', 'stringArray', () => 'string' as const)\n .with('number', 'numberArray', 'interval', () => 'number' as const)\n .with('boolean', () => 'boolean' as const)\n .with('date', 'time', () => 'date' as const)\n .otherwise(() => null);\n};\n\nexport const isExprCompatibleWithKind = (data: ExpressionBuilderData, kind: ValueKind): boolean => {\n if (data.kind !== 'simple') return true;\n const op = data.operator.type;\n if (!OPS_BY_KIND[kind].includes(op)) return false;\n if (NO_VALUE_OPS.includes(op)) return true;\n const val = data.value;\n if (!val) return true;\n return match(kind)\n .with('boolean', () => val.type === 'boolean')\n .with('number', () => ['number', 'numberArray', 'interval'].includes(val.type))\n .with('string', () => ['string', 'stringArray'].includes(val.type))\n .with('date', () => ['date', 'time', 'intArray'].includes(val.type))\n .with('any', () => true)\n .exhaustive();\n};\n\nexport const useExpressionState = (value: string, onChange: (v: string) => void) => {\n const expr = useMemo(() => {\n const e = ExpressionBuilderWasm.parseUnary(value);\n const d = e.toJson() as ExpressionBuilderData;\n e.free();\n return d;\n }, [value]);\n\n const update = useCallback(\n (d: ExpressionBuilderData) => {\n const e = ExpressionBuilderWasm.fromJson(d);\n onChange(e.serialize());\n e.free();\n },\n [onChange],\n );\n\n const setVal = useCallback(\n (v: SimpleValue | null) => {\n if (expr.kind === 'simple') update({ kind: 'simple', operator: expr.operator, value: v });\n },\n [expr, update],\n );\n\n const [isCustom, setIsCustom] = useState(expr.kind === 'complex');\n useEffect(() => {\n if (expr.kind === 'complex') setIsCustom(true);\n }, [expr.kind]);\n\n const toggleCustom = useCallback(() => setIsCustom((v) => !v), []);\n\n return { expr, update, setVal, isCustom, setIsCustom, toggleCustom };\n};\n","import type { SimpleValue } from '@gorules/zen-engine-wasm';\nimport clsx from 'clsx';\nimport dayjs from 'dayjs';\nimport React, { useEffect, useMemo, useState } from 'react';\nimport { match } from 'ts-pattern';\n\nimport { useThemeMode } from '../../../../theme';\nimport { AutosizeTextArea } from '../../../autosize-text-area';\nimport { DatePicker, InputNumber, Select, TimePicker } from '../../../primitives';\nimport {\n FIELD_AUTO,\n FIELD_COMPACT,\n GRANULARITIES,\n type OperatorType,\n type ValueKind,\n enumFilterOption,\n} from './constants';\n\nexport type ValInputProps = {\n value: SimpleValue | null;\n onChange: (v: SimpleValue | null) => void;\n operator: OperatorType;\n kind: ValueKind;\n disabled?: boolean;\n};\n\nexport const ValInput: React.FC<ValInputProps> = ({ value, onChange, operator, kind, disabled }) =>\n match(operator)\n .with('between', () => <IntervalInput value={value} onChange={onChange} disabled={disabled} />)\n .with('in', 'notIn', () => <ArrayInput value={value} onChange={onChange} kind={kind} disabled={disabled} />)\n .with('dateAfter', 'dateBefore', 'dateSame', 'dateSameOrAfter', 'dateSameOrBefore', () => (\n <DateInput value={value} onChange={onChange} disabled={disabled} />\n ))\n .with('timeGt', 'timeGte', 'timeLt', 'timeLte', () => (\n <TimeInput value={value} onChange={onChange} disabled={disabled} />\n ))\n .with('dayOfWeekIn', () => (\n <ChipInput value={value} onChange={onChange} disabled={disabled} options={DAYS} defaultValues={[1, 2, 3, 4, 5]} />\n ))\n .with('quarterIn', () => (\n <ChipInput value={value} onChange={onChange} disabled={disabled} options={QUARTERS} defaultValues={[1]} />\n ))\n .otherwise(() =>\n match(kind)\n .with('boolean', () => <BoolInput value={value} onChange={onChange} disabled={disabled} />)\n .with('number', () => <NumInput value={value} onChange={onChange} disabled={disabled} />)\n .otherwise(() => <StrInput value={value} onChange={onChange} disabled={disabled} />),\n );\n\nexport type SimpleInputProps = { value: SimpleValue | null; onChange: (v: SimpleValue) => void; disabled?: boolean };\n\nconst StrInput: React.FC<SimpleInputProps> = ({ value, onChange, disabled }) => {\n const externalText = value?.type === 'string' ? value.value : '';\n const [text, setText] = useState(externalText);\n useEffect(() => {\n if (text !== externalText) {\n setText(externalText);\n }\n }, [externalText]);\n const commit = () => onChange({ type: 'string', value: text });\n return (\n <AutosizeTextArea\n className='flex-1 min-w-[40px] border-0! shadow-none! [font-family:inherit] text-[13px]! leading-[var(--b-line-height)]! px-[var(--b-h-padding)]! py-[var(--b-v-padding)]! h-auto! min-h-[var(--b-height)] focus:shadow-none!'\n value={text}\n maxRows={3}\n onChange={(e) => setText(e.target.value)}\n onBlur={commit}\n onKeyDown={(e) => e.key === 'Enter' && !e.shiftKey && commit()}\n disabled={disabled}\n />\n );\n};\n\nconst NumInput: React.FC<SimpleInputProps> = ({ value, onChange, disabled }) => (\n <InputNumber\n className={`flex-1 min-w-[40px] ${FIELD_COMPACT}`}\n value={value?.type === 'number' ? value.value : 0}\n onChange={(v) => v !== null && onChange({ type: 'number', value: v })}\n disabled={disabled}\n variant='borderless'\n size='small'\n controls={false}\n />\n);\n\nconst BoolInput: React.FC<SimpleInputProps> = ({ value, onChange, disabled }) => (\n <Select\n className={`min-w-[50px] flex-1 ${FIELD_COMPACT}`}\n value={value?.type === 'boolean' ? value.value : true}\n onChange={(v) => onChange({ type: 'boolean', value: v })}\n disabled={disabled}\n variant='borderless'\n size='small'\n suffixIcon={null}\n popupMatchSelectWidth={80}\n options={[\n { value: true, label: 'true' },\n { value: false, label: 'false' },\n ]}\n />\n);\n\nconst DateInput: React.FC<SimpleInputProps> = ({ value, onChange, disabled }) => {\n const dateVal = value?.type === 'date' ? value.value : dayjs().format('YYYY-MM-DD');\n const granularity = value?.type === 'date' ? value.granularity : undefined;\n return (\n <>\n <DatePicker\n className={`min-w-[100px] min-h-0! ${FIELD_COMPACT}`}\n value={dayjs(dateVal)}\n onChange={(d) => d && onChange({ type: 'date', value: d.format('YYYY-MM-DD'), granularity })}\n disabled={disabled}\n variant='borderless'\n size='small'\n allowClear={false}\n />\n <Select\n className={`min-w-[60px] ${FIELD_COMPACT}`}\n value={granularity ?? ''}\n onChange={(g) => onChange({ type: 'date', value: dateVal, granularity: g || undefined })}\n options={GRANULARITIES}\n disabled={disabled}\n variant='borderless'\n size='small'\n popupMatchSelectWidth={false}\n suffixIcon={null}\n />\n </>\n );\n};\n\nconst TimeInput: React.FC<SimpleInputProps> = ({ value, onChange, disabled }) => (\n <TimePicker\n className={`min-w-[60px] min-h-0! ${FIELD_COMPACT}`}\n value={value?.type === 'time' ? dayjs().hour(value.hour).minute(value.minute) : dayjs().hour(9).minute(0)}\n onChange={(t) => t && onChange({ type: 'time', hour: t.hour(), minute: t.minute() })}\n disabled={disabled}\n variant='borderless'\n size='small'\n format='HH:mm'\n allowClear={false}\n />\n);\n\nconst DAYS = [\n { v: 1, l: 'Mon' },\n { v: 2, l: 'Tue' },\n { v: 3, l: 'Wed' },\n { v: 4, l: 'Thu' },\n { v: 5, l: 'Fri' },\n { v: 6, l: 'Sat' },\n { v: 7, l: 'Sun' },\n];\nconst QUARTERS = [\n { v: 1, l: 'Q1' },\n { v: 2, l: 'Q2' },\n { v: 3, l: 'Q3' },\n { v: 4, l: 'Q4' },\n];\n\nconst ChipInput: React.FC<SimpleInputProps & { options: { v: number; l: string }[]; defaultValues: number[] }> = ({\n value,\n onChange,\n disabled,\n options,\n defaultValues,\n}) => {\n const valid = new Set(options.map((o) => o.v));\n const raw = value?.type === 'intArray' ? value.values : defaultValues;\n const sel = raw.filter((v) => valid.has(v));\n\n useEffect(() => {\n if (sel.length !== raw.length && sel.length > 0) onChange({ type: 'intArray', values: sel });\n }, [sel.length, raw.length]);\n\n const toggle = (v: number) => {\n if (disabled) return;\n const next = sel.includes(v) ? sel.filter((x) => x !== v) : [...sel, v].sort((a, b) => a - b);\n if (next.length) onChange({ type: 'intArray', values: next });\n };\n return (\n <div className='flex flex-wrap items-center gap-1 min-h-[var(--b-height)]'>\n {options.map((o) => (\n <span\n key={o.v}\n className={clsx(\n 'cursor-pointer select-none rounded-full border border-border bg-transparent px-2 py-0.5 text-[11px] font-medium text-muted-foreground transition-colors [font-family:var(--grl-font-family),sans-serif] [&:hover:not(.active):not(.disabled)]:border-[var(--grl-color-primary-border)] [&:hover:not(.active):not(.disabled)]:bg-[var(--bg-active)] [&:hover:not(.active):not(.disabled)]:text-[var(--color-active-text)]',\n sel.includes(o.v) &&\n 'border-[var(--grl-color-primary-border)] bg-[var(--bg-active)] text-[var(--color-active-text)]',\n disabled && 'cursor-not-allowed opacity-50',\n )}\n onClick={() => toggle(o.v)}\n >\n {o.l}\n </span>\n ))}\n </div>\n );\n};\n\nconst ArrayInput: React.FC<SimpleInputProps & { kind: ValueKind }> = ({ value, onChange, kind, disabled }) => {\n const vals = useMemo(\n () =>\n value?.type === 'stringArray' ? value.values : value?.type === 'numberArray' ? value.values.map(String) : [],\n [value],\n );\n return (\n <Select\n className={`flex-1 min-w-0 ${FIELD_AUTO}`}\n mode='tags'\n value={vals}\n onChange={(v: string[]) =>\n kind === 'number'\n ? onChange({ type: 'numberArray', values: v.map((x) => parseFloat(x)).filter((n) => !isNaN(n)) })\n : onChange({ type: 'stringArray', values: v })\n }\n disabled={disabled}\n variant='borderless'\n size='small'\n tokenSeparators={[',']}\n suffixIcon={null}\n />\n );\n};\n\nconst IntervalInput: React.FC<SimpleInputProps> = ({ value, onChange, disabled }) => {\n useThemeMode();\n const iv = value?.type === 'interval' ? value : { left: 0, right: 100, leftInclusive: true, rightInclusive: true };\n const upd = (p: Partial<typeof iv>) => onChange({ type: 'interval', ...iv, ...p });\n return (\n <div className='flex flex-1 items-center gap-0.5 min-h-[var(--b-height)]'>\n <span\n className='cursor-pointer select-none px-0.5 text-sm leading-[var(--b-height)] hover:opacity-70'\n onClick={() => !disabled && upd({ leftInclusive: !iv.leftInclusive })}\n >\n {iv.leftInclusive ? '[' : '('}\n </span>\n <InputNumber\n className={`w-[45px] ${FIELD_COMPACT}`}\n value={iv.left}\n onChange={(v) => v !== null && upd({ left: v })}\n disabled={disabled}\n variant='borderless'\n size='small'\n controls={false}\n />\n <span className='text-muted-foreground'>..</span>\n <InputNumber\n className={`w-[45px] ${FIELD_COMPACT}`}\n value={iv.right}\n onChange={(v) => v !== null && upd({ right: v })}\n disabled={disabled}\n variant='borderless'\n size='small'\n controls={false}\n />\n <span\n className='cursor-pointer select-none px-0.5 text-sm leading-[var(--b-height)] hover:opacity-70'\n onClick={() => !disabled && upd({ rightInclusive: !iv.rightInclusive })}\n >\n {iv.rightInclusive ? ']' : ')'}\n </span>\n </div>\n );\n};\n\nexport const EnumValInput: React.FC<{\n value: SimpleValue | null;\n onChange: (v: SimpleValue) => void;\n operator: OperatorType;\n options: { label: string; value: string }[];\n loose?: boolean;\n disabled?: boolean;\n}> = ({ value, onChange, operator, options, loose, disabled }) =>\n match(operator)\n .with('in', 'notIn', () => (\n <Select\n className={`min-w-0 ${FIELD_AUTO}`}\n mode={loose ? 'tags' : 'multiple'}\n value={value?.type === 'stringArray' ? value.values : []}\n onChange={(v) => onChange({ type: 'stringArray', values: v })}\n options={options}\n disabled={disabled}\n variant='borderless'\n size='small'\n style={{ flex: 1, minWidth: 80 }}\n suffixIcon={null}\n showSearch\n filterOption={enumFilterOption}\n {...(loose ? { tokenSeparators: [','] } : {})}\n />\n ))\n .with('eq', 'neq', () =>\n loose ? (\n <Select\n className={`min-w-0 ${FIELD_AUTO}`}\n mode='tags'\n maxCount={1}\n value={value?.type === 'string' && value.value ? [value.value] : []}\n onChange={(v) => onChange({ type: 'string', value: v[0] ?? '' })}\n options={options}\n disabled={disabled}\n variant='borderless'\n size='small'\n style={{ flex: 1, minWidth: 80 }}\n suffixIcon={null}\n showSearch\n filterOption={enumFilterOption}\n />\n ) : (\n <Select\n className={`min-w-0 ${FIELD_COMPACT}`}\n value={value?.type === 'string' ? value.value : undefined}\n onChange={(v) => onChange({ type: 'string', value: v })}\n options={options}\n disabled={disabled}\n variant='borderless'\n size='small'\n style={{ flex: 1, minWidth: 80 }}\n suffixIcon={null}\n showSearch\n filterOption={enumFilterOption}\n />\n ),\n )\n .otherwise(() => <StrInput value={value} onChange={onChange} disabled={disabled} />);\n","import type { SimpleOperator } from '@gorules/zen-engine-wasm';\nimport React, { useCallback, useImperativeHandle, useRef, useState } from 'react';\nimport { P, match } from 'ts-pattern';\n\nimport type { ColumnFieldType } from '../../../../helpers/schema';\nimport { useDictionaries } from '../../../../theme';\nimport { useT } from '../../../../theming/i18n';\nimport { CodeEditorBase } from '../../ce-base';\nimport { focusBuilderRoot } from '../focus-helper';\nimport {\n BUILDER_BG_VARS,\n BUILDER_TOKENS,\n NO_VALUE_OPS,\n OPS_BY_KIND,\n type OperatorType,\n type ValueKind,\n defaultValue,\n getEnumOptions,\n getOp,\n getValueKind,\n} from './constants';\nimport { OpDropdown } from './op-dropdown';\nimport { inferKindFromExpr, isExprCompatibleWithKind, useExpressionState } from './use-expression-state';\nimport { EnumValInput, ValInput } from './value-inputs';\n\nexport type ExpressionBuilderProps = {\n value: string;\n onChange: (value: string) => void;\n disabled?: boolean;\n fieldType?: ColumnFieldType;\n maxRows?: number;\n};\n\nexport type ExpressionBuilderRef = {\n focus: () => void;\n};\n\nexport const ExpressionBuilder = React.forwardRef<ExpressionBuilderRef, ExpressionBuilderProps>(\n ({ value, onChange, disabled = false, fieldType, maxRows = 3 }, ref) => {\n const rootRef = useRef<HTMLDivElement>(null);\n const dictionaries = useDictionaries();\n const styleVars = { ...BUILDER_TOKENS, ...BUILDER_BG_VARS, '--b-max-rows': maxRows } as React.CSSProperties;\n\n useImperativeHandle(ref, () => ({\n focus: () => focusBuilderRoot(rootRef.current),\n }));\n\n const enumResult = getEnumOptions(fieldType, dictionaries);\n const enumOpts = enumResult?.values ?? null;\n const isLoose = enumResult?.loose ?? false;\n const externalKind = getValueKind(fieldType);\n const isEnum = !!enumOpts?.length;\n const isAutoType = !isEnum && externalKind === 'any';\n const { expr, update, setVal, isCustom, setIsCustom, toggleCustom } = useExpressionState(value, onChange);\n const [localKind, setLocalKind] = useState<ValueKind | null>(null);\n const t = useT();\n const kind = isEnum ? 'string' : isAutoType ? (localKind ?? inferKindFromExpr(expr) ?? 'string') : externalKind;\n const forceCustom = !isAutoType && expr.kind === 'simple' && !isExprCompatibleWithKind(expr, kind);\n\n const setKind = useCallback(\n (newKind: ValueKind) => {\n setLocalKind(newKind);\n const defaultOp = OPS_BY_KIND[newKind][0];\n update({\n kind: 'simple',\n operator: { type: defaultOp } as SimpleOperator,\n value: defaultValue(defaultOp, newKind),\n });\n },\n [update],\n );\n\n const setOp = useCallback(\n (op: OperatorType) => {\n const cur = expr.kind === 'simple' ? expr.value : null;\n const canReuse = (t: string) => cur?.type === t;\n const val = match(op)\n .with(\n P.when((o) => NO_VALUE_OPS.includes(o)),\n () => null,\n )\n .with('between', () => (canReuse('interval') ? cur : defaultValue(op, kind)))\n .with('in', 'notIn', () =>\n canReuse('stringArray') || canReuse('numberArray') ? cur : defaultValue(op, kind),\n )\n .with('dateAfter', 'dateBefore', 'dateSame', 'dateSameOrAfter', 'dateSameOrBefore', () =>\n canReuse('date') ? cur : defaultValue(op, kind),\n )\n .with('timeGt', 'timeGte', 'timeLt', 'timeLte', () => (canReuse('time') ? cur : defaultValue(op, kind)))\n .with('dayOfWeekIn', 'quarterIn', () => (canReuse('intArray') ? cur : defaultValue(op, kind)))\n .with('startsWith', 'endsWith', 'contains', () => (canReuse('string') ? cur : defaultValue(op, kind)))\n .otherwise(() => {\n const expected = kind === 'number' ? 'number' : kind === 'boolean' ? 'boolean' : 'string';\n return canReuse(expected) ? cur : defaultValue(op, kind);\n });\n update({ kind: 'simple', operator: { type: op } as SimpleOperator, value: val });\n },\n [expr, kind, update],\n );\n\n const handleSelectOp = useCallback(\n (op: OperatorType) => {\n setIsCustom(false);\n setOp(op);\n },\n [setOp, setIsCustom],\n );\n\n const dropdownProps = {\n kind,\n operator: expr.kind === 'simple' ? expr.operator.type : ('eq' as OperatorType),\n onSelect: handleSelectOp,\n onKindChange: isAutoType ? setKind : undefined,\n onCustomToggle: toggleCustom,\n disabled,\n };\n\n if (isCustom || forceCustom || expr.kind === 'complex') {\n return (\n <div\n ref={rootRef}\n className='flex items-start gap-1 min-h-[var(--b-height)] text-[var(--b-font-size)] leading-[var(--b-line-height)]'\n style={styleVars}\n >\n <OpDropdown {...dropdownProps} isCustom />\n <CodeEditorBase\n className='min-w-[40px] flex-1 max-h-[var(--b-max-height)] overflow-y-auto'\n style={\n {\n '--ce-lineHeight': 'var(--b-line-height)',\n '--ce-verticalPadding': 'var(--b-v-padding)',\n '--ce-horizontalPadding': 'var(--b-h-padding)',\n } as React.CSSProperties\n }\n value={value}\n onChange={onChange}\n type='unary'\n disabled={disabled}\n noStyle\n maxRows={maxRows}\n placeholder={t('expression.placeholder')}\n />\n </div>\n );\n }\n\n const op = expr.operator.type;\n return (\n <div\n ref={rootRef}\n className='flex items-start gap-1 min-h-[var(--b-height)] text-[var(--b-font-size)] leading-[var(--b-line-height)]'\n style={styleVars}\n >\n <OpDropdown {...dropdownProps} operator={op} />\n {NO_VALUE_OPS.includes(op) ? (\n op !== 'any' && (\n <span className='text-xs leading-[var(--b-height)] text-[var(--muted-foreground)]'>{getOp(op).label}</span>\n )\n ) : isEnum ? (\n <EnumValInput\n value={expr.value}\n onChange={setVal}\n operator={op}\n options={enumOpts}\n loose={isLoose}\n disabled={disabled}\n />\n ) : (\n <ValInput value={expr.value} onChange={setVal} operator={op} kind={kind} disabled={disabled} />\n )}\n </div>\n );\n },\n);\n","import { type StandardExpressionData, parseStandardExpression } from '@gorules/zen-engine-wasm';\nimport dayjs from 'dayjs';\nimport {\n CalendarIcon,\n HashIcon,\n ListIcon,\n type LucideIcon,\n SquareFunctionIcon,\n ToggleLeftIcon,\n TypeIcon,\n} from 'lucide-react';\nimport React, { useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react';\n\nimport type { ColumnEnum, OutputFieldType } from '../../../helpers/schema';\nimport { type DictionaryMap, useDictionaries } from '../../../theme';\nimport { AutosizeTextArea } from '../../autosize-text-area';\nimport { DatePicker, InputNumber, Select } from '../../primitives';\nimport { CodeEditorBase } from '../ce-base';\nimport { focusBuilderRoot } from './focus-helper';\n\nexport type { OutputFieldType };\n\nconst BUILDER_TOKENS: React.CSSProperties = {\n '--b-font-size': '13px',\n '--b-line-height': '1.5',\n '--b-v-padding': '2px',\n '--b-h-padding': '4px',\n '--b-height': 'calc(var(--b-font-size) * var(--b-line-height) + var(--b-v-padding) * 2)',\n '--b-max-height': 'calc(var(--b-height) * var(--b-max-rows))',\n} as React.CSSProperties;\n\n// Single-line fields (native input / Radix trigger): fixed compact height,\n// builder side padding and font so every field matches the autosize textarea.\nconst FIELD_COMPACT = 'h-[var(--b-height)]! border-0! px-[var(--b-h-padding)]! py-0! text-[13px]!';\nconst FIELD_AUTO = 'min-h-[var(--b-height)]! h-auto! border-0! px-[var(--b-h-padding)]! text-[13px]! overflow-hidden';\n\nexport type StandardExpressionBuilderProps = {\n value: string;\n onChange: (value: string) => void;\n disabled?: boolean;\n fieldType?: OutputFieldType;\n maxRows?: number;\n};\n\nconst TYPE_ICONS: Record<Exclude<OutputFieldType['type'], 'auto'>, LucideIcon> = {\n 'string': TypeIcon,\n 'string-array': ListIcon,\n 'number': HashIcon,\n 'boolean': ToggleLeftIcon,\n 'date': CalendarIcon,\n};\n\nconst enumFilterOption = (input: string, option?: { label?: unknown; value?: unknown }) => {\n const search = input.toLowerCase();\n const hay = [String(option?.label ?? ''), String(option?.value ?? '')].join(' ').toLowerCase();\n return hay.includes(search);\n};\n\nconst formatDateValue = (date: string): string => `d('${date}')`;\nconst formatStringValue = (value: string): string => `\"${value}\"`;\nconst formatStringArrayValue = (values: string[]): string =>\n !values.length ? '[]' : `[${values.map((v) => `\"${v.replace(/\"/g, '\\\\\"')}\"`).join(', ')}]`;\n\nconst parseStringArrayValue = (value: string): string[] => {\n if (!value?.trim()) return [];\n try {\n const parsed = JSON.parse(value);\n if (Array.isArray(parsed)) return parsed.map(String);\n } catch {}\n return [];\n};\n\nconst isStringArrayValue = (value: string): boolean => {\n if (!value?.trim() || value.trim() === '[]') return true;\n try {\n return Array.isArray(JSON.parse(value));\n } catch {}\n return false;\n};\n\nconst getEnumOptions = (\n ft?: OutputFieldType,\n dictionaries?: DictionaryMap,\n): { values: { label: string; value: string }[]; loose: boolean } | null => {\n if (!ft) return null;\n if (ft.type !== 'string' && ft.type !== 'string-array') return null;\n const e: ColumnEnum | undefined = ft.enum;\n if (!e) return null;\n if (e.type === 'inline') {\n return e.values.length ? { values: e.values, loose: e.loose ?? false } : null;\n }\n const resolved = dictionaries?.[e.ref];\n return resolved?.length ? { values: resolved, loose: e.loose ?? false } : null;\n};\n\nexport type StandardExpressionBuilderRef = {\n focus: () => void;\n};\n\nexport const StandardExpressionBuilder = React.forwardRef<StandardExpressionBuilderRef, StandardExpressionBuilderProps>(\n ({ value, onChange, disabled = false, fieldType, maxRows = 3 }, ref) => {\n const rootRef = useRef<HTMLDivElement>(null);\n const dictionaries = useDictionaries();\n const ftType = fieldType?.type ?? 'auto';\n const styleVars = { ...BUILDER_TOKENS, '--b-max-rows': maxRows } as React.CSSProperties;\n\n useImperativeHandle(ref, () => ({\n focus: () => focusBuilderRoot(rootRef.current),\n }));\n\n const parsed = useMemo<StandardExpressionData>(() => parseStandardExpression(value), [value]);\n const computeExprMode = () => {\n if (ftType === 'string-array') return !isStringArrayValue(value);\n if (parsed.kind === 'expression') return true;\n if (ftType === 'auto') return false;\n return parsed.kind !== ftType;\n };\n const [isExprMode, setIsExprMode] = useState(computeExprMode);\n\n useEffect(() => {\n setIsExprMode(computeExprMode());\n }, [ftType]);\n\n const forceExprMode =\n ftType !== 'auto' && ftType !== 'string-array' && parsed.kind !== 'expression' && parsed.kind !== ftType;\n\n const TypeIcon = ftType !== 'auto' ? TYPE_ICONS[ftType] : null;\n const enumOptions = getEnumOptions(fieldType, dictionaries);\n\n if (ftType === 'auto' || isExprMode || forceExprMode) {\n return (\n <div\n ref={rootRef}\n className='flex items-start gap-1 min-h-[var(--b-height)] text-[var(--b-font-size)] leading-[var(--b-line-height)]'\n style={styleVars}\n >\n {ftType !== 'auto' && (\n <button\n className='flex shrink-0 cursor-pointer items-center justify-center rounded-md border-0 bg-muted px-1.5 py-[var(--b-v-padding)] text-[11px] text-muted-foreground transition-colors min-h-[var(--b-height)] enabled:hover:bg-accent enabled:hover:text-accent-foreground disabled:cursor-not-allowed disabled:opacity-50'\n onClick={() => {\n if (parsed.kind !== ftType) {\n const t = ftType;\n if (t === 'string') onChange(formatStringValue(''));\n else if (t === 'number') onChange('0');\n else if (t === 'boolean') onChange('true');\n else if (t === 'date') onChange(formatDateValue(dayjs().format('YYYY-MM-DD')));\n }\n setIsExprMode(false);\n }}\n disabled={disabled}\n title='Currently: Expression. Click for value mode.'\n >\n <SquareFunctionIcon size={14} />\n </button>\n )}\n <CodeEditorBase\n className='min-w-[40px] flex-1 max-h-[var(--b-max-height)] overflow-y-auto'\n style={\n {\n '--ce-lineHeight': 'var(--b-line-height)',\n '--ce-verticalPadding': 'var(--b-v-padding)',\n '--ce-horizontalPadding': 'var(--b-h-padding)',\n } as React.CSSProperties\n }\n value={value}\n onChange={onChange}\n type='standard'\n disabled={disabled}\n noStyle\n maxRows={maxRows}\n />\n </div>\n );\n }\n\n return (\n <div\n ref={rootRef}\n className='flex items-start gap-1 min-h-[var(--b-height)] text-[var(--b-font-size)] leading-[var(--b-line-height)]'\n style={styleVars}\n >\n <button\n className='flex shrink-0 cursor-pointer items-center justify-center rounded-md border-0 bg-muted px-1.5 py-[var(--b-v-padding)] text-[11px] text-muted-foreground transition-colors min-h-[var(--b-height)] enabled:hover:bg-accent enabled:hover:text-accent-foreground disabled:cursor-not-allowed disabled:opacity-50'\n onClick={() => setIsExprMode(true)}\n disabled={disabled}\n title='Currently: Value. Click for expression mode.'\n >\n {TypeIcon && <TypeIcon size={14} />}\n </button>\n {ftType === 'string' && !enumOptions && (\n <AutosizeTextArea\n className='flex-1 min-w-[40px] [font-family:inherit] text-[13px]! leading-[var(--b-line-height)]! px-[var(--b-h-padding)]! py-[var(--b-v-padding)]! h-auto! min-h-[var(--b-height)] focus:shadow-none!'\n value={parsed.kind === 'string' ? parsed.value : ''}\n maxRows={maxRows}\n onChange={(e) => onChange(formatStringValue((e.target as unknown as { value: string }).value))}\n disabled={disabled}\n />\n )}\n {ftType === 'string' && enumOptions && (\n <Select\n className={`min-w-[50px] flex-1 ${FIELD_COMPACT}`}\n value={parsed.kind === 'string' ? parsed.value : undefined}\n onChange={(v) => onChange(formatStringValue(v))}\n disabled={disabled}\n variant='borderless'\n size='small'\n suffixIcon={null}\n showSearch\n filterOption={enumFilterOption}\n popupMatchSelectWidth={false}\n options={enumOptions.values.map((v) => ({ label: v.label, value: v.value }))}\n />\n )}\n {ftType === 'string-array' && (\n <Select\n className={`flex-1 min-w-0 ${FIELD_AUTO}`}\n mode={enumOptions && !enumOptions.loose ? 'multiple' : 'tags'}\n value={parseStringArrayValue(value)}\n onChange={(v: string[]) => onChange(formatStringArrayValue(v))}\n disabled={disabled}\n variant='borderless'\n size='small'\n suffixIcon={null}\n showSearch\n filterOption={enumFilterOption}\n popupMatchSelectWidth={false}\n options={enumOptions?.values.map((v) => ({ label: v.label, value: v.value }))}\n />\n )}\n {ftType === 'number' && (\n <InputNumber\n className={`flex-1 min-w-[40px] ${FIELD_COMPACT}`}\n value={parsed.kind === 'number' ? parsed.value : 0}\n onChange={(v) => onChange(String(v ?? 0))}\n disabled={disabled}\n variant='borderless'\n controls={false}\n />\n )}\n {ftType === 'boolean' && (\n <Select\n className={`min-w-[50px] flex-1 ${FIELD_COMPACT}`}\n value={parsed.kind === 'boolean' ? parsed.value : true}\n onChange={(v) => onChange(String(v))}\n disabled={disabled}\n variant='borderless'\n size='small'\n suffixIcon={null}\n popupMatchSelectWidth={80}\n options={[\n { value: true, label: 'true' },\n { value: false, label: 'false' },\n ]}\n />\n )}\n {ftType === 'date' && (\n <DatePicker\n className={`flex-1 min-w-[80px] min-h-0! ${FIELD_COMPACT}`}\n value={(() => {\n const dateStr = parsed.kind === 'date' ? parsed.value : null;\n return dateStr && dayjs(dateStr).isValid() ? dayjs(dateStr) : dayjs();\n })()}\n onChange={(d) => d && onChange(formatDateValue(d.format('YYYY-MM-DD')))}\n disabled={disabled}\n variant='borderless'\n size='small'\n allowClear={false}\n />\n )}\n </div>\n );\n },\n);\n","import { type Variable } from '@gorules/zen-engine-wasm';\nimport stringifyPretty from 'json-stringify-pretty-compact';\nimport { BugIcon } from 'lucide-react';\nimport React, { useMemo } from 'react';\n\nimport { isWasmAvailable } from '../../helpers/wasm';\nimport { Typography } from '../primitives';\nimport { CodeEditor } from './ce';\n\nexport type CodeEditorPreviewProps = {\n initial?: { expression: string; result: unknown };\n expression: string;\n inputData?: Variable;\n noPreviewText?: string;\n};\n\nexport const CodeEditorPreview: React.FC<CodeEditorPreviewProps> = ({\n initial,\n expression,\n inputData,\n noPreviewText = 'Run simulation to see the results',\n}) => {\n const preview = useMemo(() => {\n if (!inputData) {\n return undefined;\n }\n\n if (!isWasmAvailable() || expression === initial?.expression) {\n return { type: 'initial' as const, value: stringifyPretty(initial?.result, { maxLength: 30 }) };\n }\n\n if (!expression) {\n return { type: 'none' as const, value: '-' };\n }\n\n try {\n const value = inputData.evaluateExpression(expression);\n return { type: 'success' as const, value: stringifyPretty(value, { maxLength: 30 }) };\n } catch (err) {\n return { type: 'error' as const, value: String(err) };\n }\n }, [inputData, expression, initial]);\n\n return (\n <div>\n <Typography.Text style={{ fontSize: 12 }}>\n Live Preview <BugIcon size='1em' opacity={0.5} color='#077D16' />\n </Typography.Text>\n <Typography.Text style={{ fontSize: 12, display: 'block' }} type='secondary'>\n {preview?.type === 'initial' ? 'Based on simulation data' : 'Based on live calculation'}\n </Typography.Text>\n <div className='grl-ce-preview'>\n {(preview?.type === 'success' || preview?.type === 'initial') && (\n <CodeEditor value={preview.value} disabled noStyle maxRows={3} />\n )}\n {preview?.type === 'none' && (\n <Typography.Text type='secondary' ellipsis>\n {preview.value}\n </Typography.Text>\n )}\n {preview?.type === 'error' && (\n <Typography.Text type='danger' ellipsis>\n {preview.value}\n </Typography.Text>\n )}\n {!preview && (\n <Typography.Text type='secondary' ellipsis>\n {noPreviewText}\n </Typography.Text>\n )}\n </div>\n </div>\n );\n};\n","import type { ColumnEnum } from '../../../helpers/schema';\n\nexport type EnumMode = 'none' | 'inline' | 'ref';\n\nexport const ENUM_MODE_OPTIONS: { value: EnumMode; label: string }[] = [\n { value: 'none', label: 'None' },\n { value: 'inline', label: 'Inline' },\n { value: 'ref', label: 'Dictionary' },\n];\n\nexport const getEnumMode = (e?: ColumnEnum): EnumMode => {\n if (!e) return 'none';\n return e.type;\n};\n\nexport const parseEnumString = (str: string): { label: string; value: string }[] => {\n if (!str?.trim()) return [];\n return str\n .split('\\n')\n .map((line) => line.trim())\n .filter(Boolean)\n .map((line) => {\n const [label, value] = line.split(';');\n return { label: label.trim(), value: (value ?? label).trim() };\n });\n};\n\nexport const serializeEnumValues = (items?: { label: string; value: string }[]): string => {\n if (!items?.length) return '';\n return items.map((item) => (item.label === item.value ? item.label : `${item.label};${item.value}`)).join('\\n');\n};\n","import { TrashIcon } from 'lucide-react';\nimport React, { useState } from 'react';\nimport { P, match } from 'ts-pattern';\n\nimport type { ButtonProps } from './primitives';\nimport { Button, Tooltip } from './primitives';\n\nexport type ConfirmActionProps = {\n iconOnly?: boolean;\n text?: string;\n confirmText?: string;\n onConfirm?: () => void;\n} & Omit<ButtonProps, 'children'>;\n\nexport const ConfirmAction: React.FC<ConfirmActionProps> = ({\n iconOnly = false,\n text = 'Delete',\n confirmText = 'Really delete?',\n icon = <TrashIcon size='1em' />,\n onClick,\n onBlur,\n onConfirm,\n disabled,\n ...props\n}) => {\n const [isConfirming, setIsConfirming] = useState(false);\n const tooltipOpen = match([iconOnly, disabled])\n .with([P._, true], () => false)\n .with([false, P._], () => false)\n .otherwise(() => undefined);\n\n return (\n <Tooltip open={tooltipOpen} title={isConfirming ? confirmText : text}>\n <Button\n type='text'\n danger={isConfirming}\n icon={icon}\n disabled={disabled}\n onClick={(event) => {\n onClick?.(event);\n if (isConfirming) {\n onConfirm?.();\n setIsConfirming(false);\n return;\n }\n\n setIsConfirming(true);\n }}\n onBlur={(event) => {\n onBlur?.(event);\n setIsConfirming(false);\n }}\n {...props}\n >\n {match([iconOnly, isConfirming])\n .with([false, true], () => confirmText)\n .with([false, false], () => text)\n .otherwise(() => undefined)}\n </Button>\n </Tooltip>\n );\n};\n","import clsx from 'clsx';\nimport { ChevronDownIcon } from 'lucide-react';\nimport React from 'react';\n\nimport { ConfirmAction } from '../../confirm-action';\nimport { Button, Popover } from '../../primitives';\n\ntype FieldEditPopoverProps = {\n value?: string;\n onSubmit: () => void;\n onRemove?: () => void;\n disabled?: boolean;\n open: boolean;\n onOpenChange: (open: boolean) => void;\n triggerClassName?: string;\n children: React.ReactNode;\n mode?: 'edit' | 'create';\n trigger?: React.ReactNode;\n};\n\nexport const FieldEditPopover: React.FC<FieldEditPopoverProps> = ({\n value,\n onSubmit,\n onRemove,\n disabled,\n open,\n onOpenChange,\n triggerClassName,\n children,\n mode = 'edit',\n trigger,\n}) => (\n <Popover\n placement='bottomLeft'\n trigger={['click']}\n destroyTooltipOnHide\n arrow={false}\n open={open}\n onOpenChange={onOpenChange}\n content={\n <div\n className='w-[340px] space-y-3 p-3'\n data-simulation='propagateWithTimeout'\n onKeyDownCapture={(e) => {\n const isSubmit = (e.ctrlKey || e.metaKey) && e.key === 'Enter';\n const isCancel = e.key === 'Escape';\n if (!isSubmit && !isCancel) return;\n\n e.preventDefault();\n e.stopPropagation();\n onOpenChange(false);\n if (!disabled && isSubmit) onSubmit();\n }}\n >\n {children}\n <div\n className={clsx('flex w-full items-center gap-2 pt-1', mode === 'create' ? 'justify-end' : 'justify-between')}\n >\n {mode === 'edit' && <ConfirmAction iconOnly onConfirm={onRemove} disabled={disabled} />}\n <div className='ml-auto flex items-center gap-2'>\n <Button size='small' type='text' onClick={() => onOpenChange(false)}>\n Cancel\n </Button>\n <Button size='small' type='primary' disabled={disabled} onClick={onSubmit}>\n {mode === 'create' ? 'Create' : 'Update'}\n </Button>\n </div>\n </div>\n </div>\n }\n >\n {trigger ?? (\n <span\n className={clsx(\n 'mt-0.5 inline-flex max-w-full cursor-pointer select-none items-center gap-1.5 rounded-md border border-[var(--grl-color-field-input)] bg-[var(--grl-color-field-input)] px-2 py-0.5 text-sm text-black transition-colors hover:border-[var(--grl-color-field-input-hover)] aria-disabled:cursor-not-allowed aria-disabled:opacity-50',\n triggerClassName,\n )}\n onClick={() => onOpenChange(!open)}\n >\n <span className='size-1.5 shrink-0 rounded-full bg-current' />\n <span className='truncate'>{value || '-'}</span>\n <ChevronDownIcon size={12} className='shrink-0 opacity-60' />\n </span>\n )}\n </Popover>\n);\n","import clsx from 'clsx';\nimport React from 'react';\n\nexport type FieldTypeTagsProps<T extends string> = {\n options: { value: T; label: string }[];\n value: T;\n onChange: (value: T) => void;\n disabled?: boolean;\n};\n\nexport const FieldTypeTags = <T extends string>({\n options,\n value,\n onChange,\n disabled,\n}: FieldTypeTagsProps<T>): React.ReactElement => (\n <div className='flex flex-wrap gap-1.5'>\n {options.map((opt) => {\n const selected = value === opt.value;\n return (\n <button\n key={opt.value}\n type='button'\n aria-pressed={selected}\n className={clsx(\n 'cursor-pointer rounded-full border px-3 py-1 text-xs font-medium transition-colors duration-150',\n selected\n ? 'border-primary bg-primary text-primary-foreground shadow-sm'\n : 'border-input bg-transparent text-muted-foreground hover:border-primary/40 hover:bg-accent hover:text-foreground',\n disabled && 'pointer-events-none opacity-50',\n )}\n onClick={() => !disabled && onChange(opt.value)}\n disabled={disabled}\n >\n {opt.label}\n </button>\n );\n })}\n </div>\n);\n","import { type Variable } from '@gorules/zen-engine-wasm';\nimport React, { useEffect, useRef, useState } from 'react';\n\nimport { COLUMN_FIELD_TYPE_OPTIONS, type ColumnEnum, type ColumnFieldType } from '../../../helpers/schema';\nimport { useT } from '../../../theming/i18n';\nimport { AutosizeTextArea } from '../../autosize-text-area';\nimport type { CodeEditorRef } from '../../code-editor';\nimport { CodeEditor } from '../../code-editor';\nimport { CodeEditorPreview } from '../../code-editor/ce-preview';\nimport type { InputRef } from '../../primitives';\nimport { Checkbox, Input, Select } from '../../primitives';\nimport { useDecisionTableState } from '../context/dt-store.context';\nimport { ENUM_MODE_OPTIONS, type EnumMode, getEnumMode, parseEnumString, serializeEnumValues } from './enum-utils';\nimport { FieldEditPopover } from './field-edit-popover';\nimport { FieldTypeTags } from './field-type-tags';\n\nconst FieldLabel: React.FC<{ children: React.ReactNode }> = ({ children }) => (\n <span className='mb-1.5 block text-xs font-medium text-muted-foreground'>{children}</span>\n);\n\ntype InputFieldEditProps = {\n disabled?: boolean;\n value?: string;\n onChange?: (value: string, fieldType?: ColumnFieldType) => void;\n onRemove?: () => void;\n variableType?: unknown;\n inputData?: Variable;\n referenceData?: { field: string; value: unknown };\n fieldType?: ColumnFieldType;\n mode?: 'edit' | 'create';\n trigger?: React.ReactNode;\n onCreate?: (name: string, field: string, fieldType?: ColumnFieldType) => void;\n};\n\nexport const InputFieldEdit: React.FC<InputFieldEditProps> = ({\n value,\n onChange,\n onRemove,\n disabled,\n variableType,\n inputData,\n referenceData,\n fieldType,\n mode = 'edit',\n trigger,\n onCreate,\n}) => {\n const dictionaries = useDecisionTableState((s) => s.dictionaries) ?? {};\n const uiMode = useDecisionTableState((s) => s.mode);\n const showAdvanced = uiMode === 'business';\n const [open, setOpen] = useState(false);\n const t = useT();\n const [innerName, setInnerName] = useState('');\n const [innerValue, setInnerValue] = useState(value);\n const [innerFieldType, setInnerFieldType] = useState<string>(fieldType?.type ?? 'any');\n const ftEnum = fieldType?.type === 'string' ? fieldType.enum : undefined;\n const [enumMode, setEnumMode] = useState<EnumMode>(getEnumMode(ftEnum));\n const [enumText, setEnumText] = useState(ftEnum?.type === 'inline' ? serializeEnumValues(ftEnum.values) : '');\n const [enumRef, setEnumRef] = useState(ftEnum?.type === 'ref' ? ftEnum.ref : '');\n const [enumLoose, setEnumLoose] = useState(ftEnum?.loose ?? false);\n const codeEditor = useRef<CodeEditorRef>(null);\n const nameInput = useRef<InputRef>(null);\n\n useEffect(() => {\n if (open) {\n if (mode === 'create') {\n setInnerName('');\n setInnerValue('');\n setInnerFieldType('any');\n setEnumMode('none');\n setEnumText('');\n setEnumRef('');\n setEnumLoose(false);\n setTimeout(() => {\n codeEditor.current?.codeMirror?.focus();\n });\n } else {\n setInnerValue(value);\n setInnerFieldType(fieldType?.type ?? 'any');\n const e = fieldType?.type === 'string' ? fieldType.enum : undefined;\n setEnumMode(getEnumMode(e));\n setEnumText(e?.type === 'inline' ? serializeEnumValues(e.values) : '');\n setEnumRef(e?.type === 'ref' ? e.ref : '');\n setEnumLoose(e?.loose ?? false);\n if (!codeEditor.current) return;\n\n setTimeout(() => {\n codeEditor.current!.codeMirror?.focus();\n const content = codeEditor.current!.querySelector('.cm-content');\n const selection = window.getSelection();\n if (content && selection) selection.selectAllChildren(content);\n });\n }\n }\n }, [open]);\n\n const buildFieldType = (): ColumnFieldType | undefined => {\n if (!showAdvanced) return fieldType;\n if (innerFieldType === 'any') return undefined;\n if (innerFieldType === 'string') {\n let enumConfig: ColumnEnum | undefined;\n if (enumMode === 'inline') {\n const items = parseEnumString(enumText);\n if (items.length) enumConfig = { type: 'inline', values: items, ...(enumLoose ? { loose: true } : {}) };\n } else if (enumMode === 'ref' && enumRef) {\n enumConfig = { type: 'ref', ref: enumRef, ...(enumLoose ? { loose: true } : {}) };\n }\n return { type: 'string', ...(enumConfig ? { enum: enumConfig } : {}) };\n }\n return { type: innerFieldType } as ColumnFieldType;\n };\n\n const handleSubmit = () => {\n if (mode === 'create') {\n onCreate?.(innerName || 'New field', innerValue ?? '', buildFieldType());\n } else {\n onChange?.(innerValue ?? '', buildFieldType());\n }\n setOpen(false);\n };\n\n return (\n <FieldEditPopover\n value={value}\n onSubmit={handleSubmit}\n onRemove={onRemove}\n disabled={disabled}\n open={open}\n onOpenChange={setOpen}\n mode={mode}\n trigger={trigger}\n >\n <div className='space-y-1.5'>\n <FieldLabel>Input Field</FieldLabel>\n <CodeEditor\n ref={codeEditor}\n value={innerValue}\n onChange={setInnerValue}\n variableType={variableType}\n disabled={disabled}\n className='grl-ce-single'\n style={{ height: 32 }}\n />\n </div>\n <CodeEditorPreview\n expression={innerValue ?? ''}\n inputData={inputData}\n initial={referenceData ? { expression: referenceData.field, result: referenceData.value } : undefined}\n />\n {mode === 'create' && (\n <div className='space-y-1.5'>\n <FieldLabel>Label</FieldLabel>\n <Input\n ref={nameInput}\n value={innerName}\n onChange={(e) => setInnerName(e.target.value)}\n placeholder={t('dt.field.label')}\n disabled={disabled}\n className='h-8'\n />\n </div>\n )}\n {showAdvanced && innerValue?.trim() && (\n <div className='space-y-1.5'>\n <FieldLabel>Type</FieldLabel>\n <FieldTypeTags\n options={COLUMN_FIELD_TYPE_OPTIONS}\n value={innerFieldType as ColumnFieldType['type']}\n onChange={setInnerFieldType}\n disabled={disabled}\n />\n </div>\n )}\n {showAdvanced && innerValue?.trim() && innerFieldType === 'string' && (\n <div className='space-y-2'>\n <FieldLabel>Enum</FieldLabel>\n <FieldTypeTags\n options={\n Object.keys(dictionaries).length ? ENUM_MODE_OPTIONS : ENUM_MODE_OPTIONS.filter((o) => o.value !== 'ref')\n }\n value={enumMode}\n onChange={setEnumMode}\n disabled={disabled}\n />\n {enumMode === 'inline' && (\n <div>\n <AutosizeTextArea\n maxRows={6}\n placeholder={'United States;us\\nCanada;ca\\nMexico'}\n value={enumText}\n onChange={(e) => setEnumText(e.target.value)}\n disabled={disabled}\n className='text-xs'\n />\n <span className='mt-1 block text-[11px] text-muted-foreground'>\n One per line. Use {'\"Label;value\"'} format.\n </span>\n </div>\n )}\n {enumMode === 'ref' && (\n <div>\n <Select\n value={enumRef || undefined}\n onChange={setEnumRef}\n placeholder={t('dt.field.selectDictionary')}\n disabled={disabled}\n className='w-full'\n size='small'\n options={Object.keys(dictionaries).map((k) => ({ label: k, value: k }))}\n />\n </div>\n )}\n {enumMode !== 'none' && (\n <div>\n <Checkbox checked={enumLoose} onChange={(e) => setEnumLoose(e.target.checked)} disabled={disabled}>\n <span className='text-xs'>{t('dt.field.allowCustomValues')}</span>\n </Checkbox>\n </div>\n )}\n </div>\n )}\n </FieldEditPopover>\n );\n};\n","import React, { useEffect, useRef, useState } from 'react';\n\nimport { type ColumnEnum, OUTPUT_FIELD_TYPE_OPTIONS, type OutputFieldType } from '../../../helpers/schema';\nimport { useT } from '../../../theming/i18n';\nimport { AutosizeTextArea } from '../../autosize-text-area';\nimport type { InputRef } from '../../primitives';\nimport { Checkbox, Input, Select } from '../../primitives';\nimport { useDecisionTableState } from '../context/dt-store.context';\nimport { ENUM_MODE_OPTIONS, type EnumMode, getEnumMode, parseEnumString, serializeEnumValues } from './enum-utils';\nimport { FieldEditPopover } from './field-edit-popover';\nimport { FieldTypeTags } from './field-type-tags';\n\nconst FieldLabel: React.FC<{ children: React.ReactNode }> = ({ children }) => (\n <span className='mb-1.5 block text-xs font-medium text-muted-foreground'>{children}</span>\n);\n\nconst getEnumFromFieldType = (ft?: OutputFieldType): ColumnEnum | undefined => {\n if (!ft) return undefined;\n if (ft.type === 'string' || ft.type === 'string-array') return ft.enum;\n return undefined;\n};\n\ntype OutputFieldEditProps = {\n disabled?: boolean;\n value?: string;\n onChange?: (value: string, fieldType?: OutputFieldType) => void;\n onRemove?: () => void;\n fieldType?: OutputFieldType;\n mode?: 'edit' | 'create';\n trigger?: React.ReactNode;\n onCreate?: (name: string, field: string, outputFieldType?: OutputFieldType) => void;\n};\n\nexport const OutputFieldEdit: React.FC<OutputFieldEditProps> = ({\n disabled,\n value,\n onChange,\n onRemove,\n fieldType,\n mode = 'edit',\n trigger,\n onCreate,\n}) => {\n const dictionaries = useDecisionTableState((s) => s.dictionaries) ?? {};\n const uiMode = useDecisionTableState((s) => s.mode);\n const showAdvanced = uiMode === 'business';\n const [open, setOpen] = useState(false);\n const t = useT();\n const [innerName, setInnerName] = useState('');\n const [innerValue, setInnerValue] = useState(value);\n const [innerFieldType, setInnerFieldType] = useState<OutputFieldType['type']>(fieldType?.type ?? 'auto');\n const ftEnum = getEnumFromFieldType(fieldType);\n const [enumMode, setEnumMode] = useState<EnumMode>(getEnumMode(ftEnum));\n const [enumText, setEnumText] = useState(ftEnum?.type === 'inline' ? serializeEnumValues(ftEnum.values) : '');\n const [enumRef, setEnumRef] = useState(ftEnum?.type === 'ref' ? ftEnum.ref : '');\n const [enumLoose, setEnumLoose] = useState(ftEnum?.loose ?? false);\n const input = useRef<InputRef>(null);\n const nameInput = useRef<InputRef>(null);\n\n useEffect(() => {\n if (open) {\n if (mode === 'create') {\n setInnerName('');\n setInnerValue('');\n setInnerFieldType('auto');\n setEnumMode('none');\n setEnumText('');\n setEnumRef('');\n setEnumLoose(false);\n setTimeout(() => {\n input.current?.focus();\n });\n } else {\n setInnerValue(value);\n setInnerFieldType(fieldType?.type ?? 'auto');\n const e = getEnumFromFieldType(fieldType);\n setEnumMode(getEnumMode(e));\n setEnumText(e?.type === 'inline' ? serializeEnumValues(e.values) : '');\n setEnumRef(e?.type === 'ref' ? e.ref : '');\n setEnumLoose(e?.loose ?? false);\n if (!input.current) return;\n\n input.current.focus();\n input.current.select();\n }\n }\n }, [open]);\n\n const supportsEnum = innerFieldType === 'string' || innerFieldType === 'string-array';\n\n const buildOutputFieldType = (): OutputFieldType | undefined => {\n if (!showAdvanced) return fieldType?.type === 'auto' ? undefined : fieldType;\n if (innerFieldType === 'auto') return undefined;\n if (innerFieldType === 'string' || innerFieldType === 'string-array') {\n let enumConfig: ColumnEnum | undefined;\n if (enumMode === 'inline') {\n const items = parseEnumString(enumText);\n if (items.length) enumConfig = { type: 'inline', values: items, ...(enumLoose ? { loose: true } : {}) };\n } else if (enumMode === 'ref' && enumRef) {\n enumConfig = { type: 'ref', ref: enumRef, ...(enumLoose ? { loose: true } : {}) };\n }\n return { type: innerFieldType, ...(enumConfig ? { enum: enumConfig } : {}) };\n }\n return { type: innerFieldType } as OutputFieldType;\n };\n\n const handleSubmit = () => {\n if (mode === 'create') {\n onCreate?.(innerName || 'Output', innerValue ?? 'output', buildOutputFieldType());\n } else {\n onChange?.(innerValue ?? '', buildOutputFieldType());\n }\n setOpen(false);\n };\n\n // Output pill colors tokenized per roadmap P1 (replaces HK-11 literals).\n return (\n <FieldEditPopover\n value={value}\n onSubmit={handleSubmit}\n onRemove={onRemove}\n disabled={disabled}\n open={open}\n onOpenChange={setOpen}\n triggerClassName={\n mode === 'edit'\n ? 'border-[var(--grl-color-field-output)] bg-[var(--grl-color-field-output)] text-black hover:border-[var(--grl-color-field-output-hover)]'\n : undefined\n }\n mode={mode}\n trigger={trigger}\n >\n <div className='space-y-1.5'>\n <FieldLabel>{t('dt.field.output.label')}</FieldLabel>\n <Input\n ref={input}\n value={innerValue}\n onChange={(e) => setInnerValue(e.target.value)}\n readOnly={disabled}\n className='h-8'\n />\n </div>\n {mode === 'create' && (\n <div className='space-y-1.5'>\n <FieldLabel>Label</FieldLabel>\n <Input\n ref={nameInput}\n value={innerName}\n onChange={(e) => setInnerName(e.target.value)}\n placeholder={t('dt.field.label')}\n disabled={disabled}\n className='h-8'\n />\n </div>\n )}\n {showAdvanced && (\n <div className='space-y-1.5'>\n <FieldLabel>Type</FieldLabel>\n <FieldTypeTags\n options={OUTPUT_FIELD_TYPE_OPTIONS}\n value={innerFieldType}\n onChange={setInnerFieldType}\n disabled={disabled}\n />\n </div>\n )}\n {showAdvanced && supportsEnum && (\n <div className='space-y-2'>\n <FieldLabel>Enum</FieldLabel>\n <FieldTypeTags\n options={\n Object.keys(dictionaries).length ? ENUM_MODE_OPTIONS : ENUM_MODE_OPTIONS.filter((o) => o.value !== 'ref')\n }\n value={enumMode}\n onChange={setEnumMode}\n disabled={disabled}\n />\n {enumMode === 'inline' && (\n <div>\n <AutosizeTextArea\n className='text-xs'\n maxRows={6}\n placeholder={'United States;us\\nCanada;ca\\nMexico'}\n value={enumText}\n onChange={(e) => setEnumText(e.target.value)}\n disabled={disabled}\n />\n <span className='mt-1 block text-[11px] text-muted-foreground'>\n One per line. Use {'\"Label;value\"'} format.\n </span>\n </div>\n )}\n {enumMode === 'ref' && (\n <div>\n <Select\n value={enumRef || undefined}\n onChange={setEnumRef}\n placeholder={t('dt.field.selectDictionary')}\n disabled={disabled}\n className='w-full'\n size='small'\n options={Object.keys(dictionaries).map((k) => ({ label: k, value: k }))}\n />\n </div>\n )}\n {enumMode !== 'none' && (\n <div>\n <Checkbox checked={enumLoose} onChange={(e) => setEnumLoose(e.target.checked)} disabled={disabled}>\n <span className='text-xs'>{t('dt.field.allowCustomValues')}</span>\n </Checkbox>\n </div>\n )}\n </div>\n )}\n </FieldEditPopover>\n );\n};\n","import { DndContext, DragOverlay, PointerSensor, useSensor, useSensors } from '@dnd-kit/core';\nimport React, { useState } from 'react';\n\nimport { DragOverlayCard, OverlayChip } from '../../../../helpers/dnd-overlay';\nimport type { ImportColumn } from './types';\n\nexport const ExcelDnd: React.FC<\n React.PropsWithChildren<{\n onMove: (draggedId: string, overId: string) => void;\n getColumnById: (id: string) => ImportColumn | undefined;\n }>\n> = ({ children, onMove, getColumnById }) => {\n const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 4 } }));\n const [activeId, setActiveId] = useState<string | null>(null);\n const activeColumn = activeId ? getColumnById(activeId) : undefined;\n\n return (\n <DndContext\n sensors={sensors}\n onDragStart={({ active }) => setActiveId(String(active.id).replace(/^xl-/, ''))}\n onDragOver={({ active, over }) => {\n if (!over) {\n return;\n }\n\n const draggedId = String(active.id).replace(/^xl-/, '');\n const overId = String(over.id).replace(/^xl-/, '');\n if (draggedId !== overId) {\n onMove(draggedId, overId);\n }\n }}\n onDragEnd={() => setActiveId(null)}\n onDragCancel={() => setActiveId(null)}\n >\n {children}\n <DragOverlay dropAnimation={null}>\n {activeColumn ? (\n <DragOverlayCard>\n <OverlayChip width={160}>{activeColumn.name}</OverlayChip>\n {activeColumn.field ? (\n <OverlayChip width={140}>\n <span style={{ color: 'var(--grl-color-text-tertiary)' }}>{activeColumn.field}</span>\n </OverlayChip>\n ) : null}\n </DragOverlayCard>\n ) : null}\n </DragOverlay>\n </DndContext>\n );\n};\n","import { DeleteOutlined, EditOutlined, HolderOutlined, LeftOutlined } from '#icons';\nimport { useDraggable, useDroppable } from '@dnd-kit/core';\nimport React from 'react';\n\nimport type { ColumnFieldType, OutputFieldType } from '../../../../helpers/schema';\nimport { useT } from '../../../../theming/i18n';\nimport { Button, Checkbox, Popconfirm, Select, Switch, Tooltip, Typography } from '../../../primitives';\nimport { InputFieldEdit } from '../input-field-edit';\nimport { OutputFieldEdit } from '../output-field-edit';\nimport type { ImportColumn } from './types';\n\nexport const ImportColumnRow: React.FC<{\n col: ImportColumn;\n section: 'input' | 'output';\n excelHeaders: { id: string; name?: string; value?: string }[];\n disabled: boolean;\n wrapChecked: boolean;\n onToggle: (enabled: boolean) => void;\n onExcelHeaderChange: (excelHeaderId: string | undefined) => void;\n onWrapChange: (checked: boolean) => void;\n onFieldChange: (field: string, fieldType?: ColumnFieldType, outputFieldType?: OutputFieldType) => void;\n onRemove: () => void;\n}> = ({\n col,\n section,\n excelHeaders,\n disabled,\n wrapChecked,\n onToggle,\n onExcelHeaderChange,\n onWrapChange,\n onFieldChange,\n onRemove,\n}) => {\n const t = useT();\n const {\n attributes,\n listeners,\n setNodeRef: setDragNodeRef,\n setActivatorNodeRef,\n isDragging,\n } = useDraggable({\n id: `xl-${col.id}`,\n data: { id: col.id },\n disabled,\n });\n\n const { setNodeRef: setDropNodeRef } = useDroppable({\n id: `xl-${col.id}`,\n });\n\n const excelOptions = excelHeaders.map((h) => ({\n label: h.name || h.value || h.id,\n value: h.id,\n }));\n\n const editTrigger = (\n <Tooltip title={t('dt.field.editColumn')}>\n <Button type='text' size='small' icon={<EditOutlined />} style={{ padding: 0 }} />\n </Tooltip>\n );\n\n return (\n <div\n ref={(el) => {\n setDragNodeRef(el);\n setDropNodeRef(el);\n }}\n style={{\n display: 'grid',\n gridTemplateColumns: '24px 36px 1fr 12px 1fr 28px 28px 28px',\n gap: '8px',\n alignItems: 'center',\n padding: '6px 0',\n opacity: isDragging ? 0.3 : disabled ? 0.4 : 1,\n }}\n >\n <div\n {...listeners}\n {...attributes}\n ref={setActivatorNodeRef}\n style={{\n cursor: disabled ? 'default' : 'grab',\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n }}\n >\n <HolderOutlined style={{ color: 'var(--grl-color-text-tertiary)' }} />\n </div>\n\n <Switch size='small' checked={!disabled} onChange={onToggle} />\n\n <div\n style={{\n display: 'flex',\n flexDirection: 'column',\n padding: '4px 10px',\n backgroundColor: 'var(--background)',\n borderRadius: '6px',\n border: '1px solid var(--border)',\n minHeight: 36,\n justifyContent: 'center',\n }}\n >\n <Typography.Text style={{ fontSize: 13, lineHeight: '18px' }}>{col.name}</Typography.Text>\n {col.field && (\n <Typography.Text type='secondary' style={{ fontSize: 11, lineHeight: '14px' }}>\n {col.field}\n </Typography.Text>\n )}\n </div>\n\n <LeftOutlined style={{ fontSize: 12, color: 'var(--primary)' }} />\n\n <Select\n allowClear\n style={{ width: '100%' }}\n placeholder={t('dt.table.selectExcelColumn')}\n value={col.excelHeaderId}\n disabled={disabled}\n onChange={(val) => onExcelHeaderChange(val ?? undefined)}\n options={excelOptions}\n />\n\n <div style={{ display: 'flex', justifyContent: 'center' }}>\n <Tooltip title={t('dt.field.wrapQuotes')}>\n <Checkbox disabled={disabled} checked={wrapChecked} onChange={(e) => onWrapChange(e.target.checked)} />\n </Tooltip>\n </div>\n\n {section === 'input' ? (\n <InputFieldEdit\n mode='edit'\n value={col.field}\n fieldType={col.fieldType}\n onChange={(field, fieldType) => onFieldChange(field, fieldType)}\n onRemove={onRemove}\n trigger={editTrigger}\n />\n ) : (\n <OutputFieldEdit\n mode='edit'\n value={col.field}\n fieldType={col.outputFieldType}\n onChange={(field, outputFieldType) => onFieldChange(field, undefined, outputFieldType)}\n onRemove={onRemove}\n trigger={editTrigger}\n />\n )}\n\n <Popconfirm title={t('dt.field.removeConfirm')} okText={t('common.remove')} onConfirm={onRemove}>\n <Tooltip title={t('dt.field.removeColumn')}>\n <Button type='text' size='small' danger icon={<DeleteOutlined />} style={{ padding: 0 }} />\n </Tooltip>\n </Popconfirm>\n </div>\n );\n};\n","import type { ParsedExcelData, RuleData } from '../../../../helpers/excel';\nimport type { ImportColumn, ItemValue, MappedExcelData, TableHeader } from './types';\n\nconst isHeaderMatch = (header1: TableHeader, header2: TableHeader) => {\n return (\n header1.id === header2.id ||\n header1.value?.toLowerCase() === header2.value?.toLowerCase() ||\n header1.label?.toLowerCase() === header2.label?.toLowerCase()\n );\n};\n\n/**\n * Derive the mappable column list from the spreadsheet snapshot: existing\n * table columns are matched against excel headers (by id/value/label) and\n * enriched with their schema metadata. When the sheet has no output column,\n * the last input column is promoted to output so every import yields one.\n */\nexport const buildImportColumns = (spreadSheetData: ParsedExcelData): ImportColumn[] => {\n const existingTableHeaders: TableHeader[] = spreadSheetData.existingTableData.headers\n .filter((h) => h.type !== undefined)\n .map((h) => ({\n id: h.id,\n label: h.name as string,\n value: h.field,\n type: h.type,\n }));\n\n const excelHeaders: TableHeader[] = (spreadSheetData.headers || [])\n .filter((h) => h.id !== '_description' && h.id !== '_id')\n .map((h) => ({\n id: h.id || crypto.randomUUID(),\n label: h.name as string,\n value: h.value,\n type: h._type as 'input' | 'output' | undefined,\n }));\n\n const schemaItems = spreadSheetData.existingTableData.headers;\n\n const importColumns: ImportColumn[] = existingTableHeaders\n .filter((h) => h.type === 'input' || h.type === 'output')\n .map((tableHeader) => {\n const matchedExcel = excelHeaders.find((eh) => isHeaderMatch(eh, tableHeader));\n const schemaItem = schemaItems.find((s) => s.id === tableHeader.id);\n return {\n id: tableHeader.id,\n name: tableHeader.label,\n field: tableHeader.value,\n type: tableHeader.type as 'input' | 'output',\n excelHeaderId: matchedExcel?.id,\n defaultValue: schemaItem?.defaultValue,\n fieldType: schemaItem?.fieldType,\n outputFieldType: schemaItem?.outputFieldType,\n };\n });\n\n // If no outputs exist, make the last input an output\n if (!importColumns.some((c) => c.type === 'output')) {\n const lastInput = [...importColumns].reverse().find((c) => c.type === 'input');\n if (lastInput) {\n lastInput.type = 'output';\n }\n }\n\n return importColumns;\n};\n\nexport type AssembleMappedDataArgs = {\n spreadSheetData: ParsedExcelData;\n columns: ImportColumn[];\n disabledColumns: Record<string, boolean>;\n wrapStates: Record<string, boolean>;\n descriptionExcelId?: string;\n descriptionEnabled: boolean;\n};\n\n/** Build items + rules payload for the mapped excel import. */\nexport const assembleMappedData = ({\n spreadSheetData,\n columns,\n disabledColumns,\n wrapStates,\n descriptionExcelId,\n descriptionEnabled,\n}: AssembleMappedDataArgs): MappedExcelData => {\n const enabled = columns.filter((c) => !disabledColumns[c.id]);\n const inputItems = enabled\n .filter((c) => c.type === 'input')\n .map((c) => ({\n id: c.id,\n label: c.name,\n value: c.field || c.name,\n type: 'input' as const,\n wrapInQuotes: wrapStates[c.id] || false,\n }));\n const outputItems = enabled\n .filter((c) => c.type === 'output')\n .map((c) => ({\n id: c.id,\n label: c.name,\n value: c.field || c.name,\n type: 'output' as const,\n wrapInQuotes: wrapStates[c.id] || false,\n }));\n const items: ItemValue[] = [...inputItems, ...outputItems];\n\n if (descriptionEnabled && descriptionExcelId) {\n items.push({ id: '_description', label: 'Description', value: 'description' });\n }\n\n const wrapLookup = items.reduce(\n (acc, item) => {\n acc[item.id] = item.wrapInQuotes || false;\n return acc;\n },\n {} as Record<string, boolean>,\n );\n\n const rules = spreadSheetData.rules.map((ruleRow) => {\n const ruleData: RuleData[] = [];\n for (const col of enabled) {\n const excelRule = col.excelHeaderId ? ruleRow.find((r) => r.headerId === col.excelHeaderId) : undefined;\n const rawValue = excelRule?.value ?? col.defaultValue ?? '';\n const value =\n wrapLookup[col.id] && rawValue\n ? rawValue\n .split(',')\n .map((s) => `\"${s.trim()}\"`)\n .join(', ')\n : rawValue;\n ruleData.push({ headerId: col.id, value });\n }\n // Add _id\n const idRule = ruleRow.find((r) => r.headerId === '_id');\n if (idRule) ruleData.push(idRule);\n // Add description\n if (descriptionEnabled && descriptionExcelId) {\n const descRule = ruleRow.find((r) => r.headerId === descriptionExcelId);\n ruleData.push({ headerId: '_description', value: descRule?.value ?? '' });\n }\n return ruleData;\n });\n\n return { items, rules };\n};\n","import { LeftOutlined, PlusOutlined } from '#icons';\nimport React, { useCallback, useEffect, useMemo, useState } from 'react';\n\nimport type { ColumnFieldType, OutputFieldType } from '../../../../helpers/schema';\nimport { useT } from '../../../../theming/i18n';\nimport { Button, Modal, Select, Switch, Typography } from '../../../primitives';\nimport { useDecisionTableDialog } from '../../context/dt-dialog.context';\nimport { useDecisionTableState } from '../../context/dt-store.context';\nimport { InputFieldEdit } from '../input-field-edit';\nimport { OutputFieldEdit } from '../output-field-edit';\nimport { ExcelDnd } from './excel-dnd';\nimport { ImportColumnRow } from './import-column-row';\nimport { assembleMappedData, buildImportColumns } from './mapping';\nimport type { DtExcelDialogProps, ImportColumn } from './types';\n\nexport type { MappedExcelData } from './types';\n\nexport const DtExcelDialog: React.FC<DtExcelDialogProps> = ({ excelData, handleSuccess, handleCancel }) => {\n const t = useT();\n const spreadSheetData = useMemo(() => excelData?.[0], [excelData]);\n const { getContainer } = useDecisionTableDialog();\n const { inputVariableType } = useDecisionTableState(({ inputVariableType }) => ({ inputVariableType }));\n\n const [columns, setColumns] = useState<ImportColumn[]>([]);\n const [disabledColumns, setDisabledColumns] = useState<Record<string, boolean>>({});\n const [wrapStates, setWrapStates] = useState<Record<string, boolean>>({});\n const [descriptionExcelId, setDescriptionExcelId] = useState<string | undefined>();\n const [descriptionEnabled, setDescriptionEnabled] = useState(true);\n\n useEffect(() => {\n if (!spreadSheetData) {\n setColumns([]);\n setDisabledColumns({});\n setWrapStates({});\n setDescriptionExcelId(undefined);\n setDescriptionEnabled(true);\n return;\n }\n\n setColumns(buildImportColumns(spreadSheetData));\n\n // Auto-match _description\n const descHeader = spreadSheetData.headers.find((h) => h.id === '_description');\n setDescriptionExcelId(descHeader?.id);\n setDescriptionEnabled(!!descHeader);\n }, [spreadSheetData]);\n\n const excelHeaders = useMemo(() => {\n if (!spreadSheetData) return [];\n return spreadSheetData.headers.filter((h) => h.id !== '_description' && h.id !== '_id');\n }, [spreadSheetData]);\n\n const inputColumns = useMemo(() => columns.filter((c) => c.type === 'input'), [columns]);\n const outputColumns = useMemo(() => columns.filter((c) => c.type === 'output'), [columns]);\n\n const enabledColumns = useMemo(() => columns.filter((c) => !disabledColumns[c.id]), [columns, disabledColumns]);\n const hasEnabledOutput = useMemo(() => enabledColumns.some((c) => c.type === 'output'), [enabledColumns]);\n const isOkDisabled = enabledColumns.length === 0 || !hasEnabledOutput;\n\n const handleFieldChange = useCallback(\n (colId: string, field: string, fieldType?: ColumnFieldType, outputFieldType?: OutputFieldType) => {\n setColumns((prev) =>\n prev.map((c) => {\n if (c.id !== colId) return c;\n return {\n ...c,\n field: field || c.field,\n ...(fieldType !== undefined ? { fieldType } : {}),\n ...(outputFieldType !== undefined ? { outputFieldType } : {}),\n };\n }),\n );\n },\n [],\n );\n\n const handleRemoveColumn = useCallback((colId: string) => {\n setColumns((prev) => prev.filter((c) => c.id !== colId));\n setDisabledColumns((prev) => {\n const updated = { ...prev };\n delete updated[colId];\n return updated;\n });\n setWrapStates((prev) => {\n const updated = { ...prev };\n delete updated[colId];\n return updated;\n });\n }, []);\n\n const handleAddInput = useCallback(\n (name: string, field: string, fieldType?: ColumnFieldType) => {\n const newCol: ImportColumn = {\n id: crypto.randomUUID(),\n name,\n field,\n type: 'input',\n fieldType,\n };\n // Auto-match unmatched Excel header\n const usedExcelIds = new Set(columns.map((c) => c.excelHeaderId).filter(Boolean));\n const unmatchedExcel = excelHeaders.find((eh) => {\n if (usedExcelIds.has(eh.id)) return false;\n const ehLabel = (eh.name || eh.value || '').toLowerCase();\n return ehLabel === name.toLowerCase() || ehLabel === field.toLowerCase();\n });\n if (unmatchedExcel) {\n newCol.excelHeaderId = unmatchedExcel.id;\n }\n setColumns((prev) => [...prev, newCol]);\n },\n [columns, excelHeaders],\n );\n\n const handleAddOutput = useCallback(\n (name: string, field: string, outputFieldType?: OutputFieldType) => {\n const newCol: ImportColumn = {\n id: crypto.randomUUID(),\n name,\n field,\n type: 'output',\n outputFieldType,\n };\n // Auto-match unmatched Excel header\n const usedExcelIds = new Set(columns.map((c) => c.excelHeaderId).filter(Boolean));\n const unmatchedExcel = excelHeaders.find((eh) => {\n if (usedExcelIds.has(eh.id)) return false;\n const ehLabel = (eh.name || eh.value || '').toLowerCase();\n return ehLabel === name.toLowerCase() || ehLabel === field.toLowerCase();\n });\n if (unmatchedExcel) {\n newCol.excelHeaderId = unmatchedExcel.id;\n }\n setColumns((prev) => [...prev, newCol]);\n },\n [columns, excelHeaders],\n );\n\n const onOk = useCallback(() => {\n if (!spreadSheetData) return;\n\n handleSuccess(\n assembleMappedData({\n spreadSheetData,\n columns,\n disabledColumns,\n wrapStates,\n descriptionExcelId,\n descriptionEnabled,\n }),\n );\n }, [spreadSheetData, columns, disabledColumns, wrapStates, descriptionEnabled, descriptionExcelId, handleSuccess]);\n\n const addInputTrigger = (\n <Button type='text' size='small' icon={<PlusOutlined />}>\n Add Input\n </Button>\n );\n\n const addOutputTrigger = (\n <Button type='text' size='small' icon={<PlusOutlined />}>\n Add Output\n </Button>\n );\n\n return (\n <Modal\n title='Map Excel data'\n closable={{ 'aria-label': 'Custom Close Button' }}\n centered\n open={!!spreadSheetData}\n okButtonProps={{ disabled: isOkDisabled }}\n onOk={onOk}\n onCancel={handleCancel}\n destroyOnClose\n width={900}\n getContainer={getContainer}\n >\n <ExcelDnd\n getColumnById={(id) => columns.find((c) => c.id === id)}\n onMove={(draggedId, overId) => {\n setColumns((prev) => {\n const i = prev.findIndex((c) => c.id === draggedId);\n const j = prev.findIndex((c) => c.id === overId);\n if (i === -1 || j === -1 || i === j || prev[i].type !== prev[j].type) {\n return prev;\n }\n\n const next = [...prev];\n const [moved] = next.splice(i, 1);\n next.splice(j, 0, moved);\n return next;\n });\n }}\n >\n <div style={{ padding: '8px 0' }}>\n {/* Inputs Section */}\n <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>\n <Typography.Text strong style={{ fontSize: 13 }}>\n Inputs\n </Typography.Text>\n <InputFieldEdit\n mode='create'\n variableType={inputVariableType}\n onCreate={handleAddInput}\n trigger={addInputTrigger}\n />\n </div>\n <div\n style={{\n border: '1px solid var(--border)',\n borderRadius: 8,\n padding: '4px 12px',\n marginBottom: 16,\n minHeight: 40,\n }}\n >\n {/* Column headers */}\n <div\n style={{\n display: 'grid',\n gridTemplateColumns: '24px 36px 1fr 12px 1fr 28px 28px 28px',\n gap: '8px',\n padding: '6px 0 2px',\n }}\n >\n <div />\n <div />\n <Typography.Text type='secondary' style={{ fontSize: 12, fontWeight: 600 }}>\n Table column\n </Typography.Text>\n <div />\n <Typography.Text type='secondary' style={{ fontSize: 12, fontWeight: 600 }}>\n Excel column\n </Typography.Text>\n <div />\n <div />\n <div />\n </div>\n {inputColumns.length === 0 && (\n <Typography.Text type='secondary' style={{ fontSize: 12, padding: '8px 0', display: 'block' }}>\n No input columns\n </Typography.Text>\n )}\n {inputColumns.map((col) => (\n <ImportColumnRow\n key={col.id}\n col={col}\n section='input'\n excelHeaders={excelHeaders}\n disabled={!!disabledColumns[col.id]}\n wrapChecked={wrapStates[col.id] || false}\n onToggle={(enabled) => {\n setDisabledColumns((prev) => {\n const updated = { ...prev };\n if (enabled) {\n delete updated[col.id];\n } else {\n updated[col.id] = true;\n }\n return updated;\n });\n }}\n onExcelHeaderChange={(excelHeaderId) => {\n setColumns((prev) => prev.map((c) => (c.id === col.id ? { ...c, excelHeaderId } : c)));\n }}\n onWrapChange={(checked) => {\n setWrapStates((prev) => ({ ...prev, [col.id]: checked }));\n }}\n onFieldChange={(field, fieldType, outputFieldType) =>\n handleFieldChange(col.id, field, fieldType, outputFieldType)\n }\n onRemove={() => handleRemoveColumn(col.id)}\n />\n ))}\n </div>\n\n {/* Outputs Section */}\n <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>\n <Typography.Text strong style={{ fontSize: 13 }}>\n Outputs\n </Typography.Text>\n <OutputFieldEdit mode='create' onCreate={handleAddOutput} trigger={addOutputTrigger} />\n </div>\n <div\n style={{\n border: '1px solid var(--border)',\n borderRadius: 8,\n padding: '4px 12px',\n marginBottom: 16,\n minHeight: 40,\n }}\n >\n {outputColumns.length === 0 && (\n <Typography.Text type='secondary' style={{ fontSize: 12, padding: '8px 0', display: 'block' }}>\n No output columns\n </Typography.Text>\n )}\n {outputColumns.map((col) => (\n <ImportColumnRow\n key={col.id}\n col={col}\n section='output'\n excelHeaders={excelHeaders}\n disabled={!!disabledColumns[col.id]}\n wrapChecked={wrapStates[col.id] || false}\n onToggle={(enabled) => {\n setDisabledColumns((prev) => {\n const updated = { ...prev };\n if (enabled) {\n delete updated[col.id];\n } else {\n updated[col.id] = true;\n }\n return updated;\n });\n }}\n onExcelHeaderChange={(excelHeaderId) => {\n setColumns((prev) => prev.map((c) => (c.id === col.id ? { ...c, excelHeaderId } : c)));\n }}\n onWrapChange={(checked) => {\n setWrapStates((prev) => ({ ...prev, [col.id]: checked }));\n }}\n onFieldChange={(field, fieldType, outputFieldType) =>\n handleFieldChange(col.id, field, fieldType, outputFieldType)\n }\n onRemove={() => handleRemoveColumn(col.id)}\n />\n ))}\n </div>\n\n {/* Description Section */}\n <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>\n <Typography.Text strong style={{ fontSize: 13 }}>\n Description\n </Typography.Text>\n </div>\n <div\n style={{\n border: '1px solid var(--border)',\n borderRadius: 8,\n padding: '8px 12px',\n }}\n >\n <div\n style={{\n display: 'grid',\n gridTemplateColumns: '36px 24px 1fr',\n gap: '8px',\n alignItems: 'center',\n }}\n >\n <Switch\n size='small'\n checked={descriptionEnabled}\n onChange={setDescriptionEnabled}\n style={{ minWidth: 28 }}\n />\n <LeftOutlined style={{ fontSize: 12, color: 'var(--primary)' }} />\n <Select\n allowClear\n style={{ width: '100%' }}\n placeholder={t('dt.table.selectDescription')}\n value={descriptionExcelId}\n disabled={!descriptionEnabled}\n onChange={(val) => setDescriptionExcelId(val ?? undefined)}\n options={excelHeaders.map((h) => ({\n label: h.name || h.value || h.id,\n value: h.id,\n }))}\n />\n </div>\n </div>\n </div>\n </ExcelDnd>\n </Modal>\n );\n};\n","import {\n ArrowDownOutlined,\n ArrowUpOutlined,\n CloseOutlined,\n DeleteOutlined,\n ExportOutlined,\n ImportOutlined,\n} from '#icons';\nimport React, { useMemo, useRef, useState } from 'react';\nimport { toast } from 'sonner';\nimport { P, match } from 'ts-pattern';\n\nimport type { ParsedExcelData } from '../../helpers/excel';\nimport { exportDecisionTable, getExcelData } from '../../helpers/excel';\nimport { useT } from '../../theming/i18n';\nimport { Button, Divider, Popconfirm, Select, Tooltip, Typography } from '../primitives';\nimport { Stack } from '../stack';\nimport type { MappedExcelData } from './components/dt-excel-dialog';\nimport { DtExcelDialog } from './components/dt-excel-dialog';\nimport {\n parseDecisionTable,\n useDecisionTableActions,\n useDecisionTableRaw,\n useDecisionTableState,\n} from './context/dt-store.context';\n\nexport const DecisionTableCommandBar: React.FC = () => {\n const [excelData, setExcelData] = useState<ParsedExcelData[] | null>();\n\n const handleDataMapping = (mappedExcelData: MappedExcelData) => {\n const items = mappedExcelData.items;\n const rules = mappedExcelData.rules;\n\n const existingInputs = table.inputs;\n const existingOutputs = table.outputs;\n\n const idRemap: Record<string, string> = {};\n\n const inputs = items\n .filter((item) => item.type === 'input')\n .map((item) => {\n const existing = existingInputs.find((c) => c.name?.toLowerCase() === item.label?.toLowerCase());\n const newId = existing?.id ?? item.id;\n if (newId !== item.id) {\n idRemap[item.id] = newId;\n }\n return {\n id: newId,\n name: item.label,\n field: item.value\n ?.replace(/[^a-zA-Z0-9\\s._]/g, '')\n .trim()\n .replace(/\\s+/g, '.')\n .toLowerCase(),\n fieldType: existing?.fieldType,\n defaultValue: existing?.defaultValue,\n };\n });\n\n const outputs = items\n .filter((item) => item.type === 'output')\n .map((item) => {\n const existing = existingOutputs.find((c) => c.name?.toLowerCase() === item.label?.toLowerCase());\n const newId = existing?.id ?? item.id;\n if (newId !== item.id) {\n idRemap[item.id] = newId;\n }\n return {\n id: newId,\n name: item.label,\n field: item.value\n ?.replace(/[^a-zA-Z0-9\\s._]/g, '')\n .trim()\n .split(/\\s+/)\n .map((word, index) =>\n index === 0 ? word.toLowerCase() : word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(),\n )\n .join(''),\n outputFieldType: existing?.outputFieldType,\n defaultValue: existing?.defaultValue,\n };\n });\n\n const existingRules = table.rules ?? [];\n const reducedRules = rules.map((rule, index) =>\n rule.reduce(\n (acc: Record<string, any> & { _id: string }, item) => {\n const mappedId = idRemap[item.headerId] ?? item.headerId;\n acc[mappedId] = item.value;\n return acc;\n },\n {\n _id: existingRules[index]?._id ?? crypto.randomUUID(),\n },\n ),\n );\n\n const newTable = parseDecisionTable({\n executionMode: 'single',\n hitPolicy: 'first',\n inputs,\n outputs,\n rules: reducedRules,\n passThrough: false,\n });\n\n tableActions.setDecisionTable(newTable);\n listenerStore.getState().onChange?.(newTable);\n\n setExcelData(null);\n };\n\n const handleCancel = () => {\n setExcelData(null);\n };\n const tableActions = useDecisionTableActions();\n const { disabled, debugIndex, traceCount, cursor } = useDecisionTableState(\n ({ disableHitPolicy, disabled, permission, decisionTable, cursor, debugIndex, debug }) => ({\n disableHitPolicy,\n disabled,\n permission,\n cursor,\n debugIndex,\n hitPolicy: decisionTable.hitPolicy,\n diffHitPolicy: decisionTable?._diff?.fields?.hitPolicy,\n traceCount: match(debug?.trace?.traceData)\n .with(P.array(), (some) => some.length)\n .otherwise(() => null),\n }),\n );\n\n const { listenerStore, stateStore } = useDecisionTableRaw();\n const fileInput = useRef<HTMLInputElement>(null);\n\n const table = stateStore.getState().decisionTable;\n\n const exportExcel = async () => {\n try {\n const { decisionTable, name } = stateStore.getState();\n await exportDecisionTable(name ?? 'table', [\n { ...decisionTable, name: 'decision table', id: crypto.randomUUID() },\n ]);\n toast.success('Excel file has been downloaded successfully!');\n } catch (e) {\n console.error('Failed to download Excel file!', e);\n toast.error('Failed to download Excel file!');\n }\n };\n\n const importExcel = () => {\n fileInput?.current?.click?.();\n };\n\n const readExcelFile = async (event: any) => {\n const file = event?.target?.files[0];\n const reader = new FileReader();\n\n try {\n reader.readAsArrayBuffer(file);\n reader.onload = async () => {\n const buffer = reader.result as ArrayBuffer;\n\n if (!buffer) return;\n\n const excelData = await getExcelData(buffer, table);\n\n if (excelData.length === 1) {\n setExcelData(excelData);\n toast.success('Excel file has been uploaded successfully!');\n } else {\n toast.error('Only excel file with a single data sheet can be handled in a table view.');\n }\n };\n } catch {\n toast.error('Failed to upload Excel!');\n }\n };\n\n const traceIndexOptions = useMemo(() => {\n if (!traceCount) {\n return null;\n }\n\n return Array.from({ length: traceCount }).map((_, i) => ({\n label: String(i),\n value: i,\n }));\n }, [debugIndex, traceCount]);\n\n const t = useT();\n\n return (\n <>\n <Stack\n horizontal\n horizontalAlign={'space-between'}\n verticalAlign={'center'}\n className='p-[7px] box-border border-b border-[var(--border)]'\n >\n <Stack gap={8} horizontal className='w-full'>\n <Button type='text' size={'small'} icon={<ExportOutlined />} onClick={exportExcel}>\n {t('dt.toolbar.export')}\n </Button>\n <Button\n type='text'\n size={'small'}\n disabled={disabled}\n icon={<ImportOutlined />}\n onClick={() => importExcel()}\n >\n {t('dt.toolbar.import')}\n </Button>\n {cursor && !disabled && (\n <>\n <Divider\n type={'vertical'}\n style={{\n height: 24,\n }}\n />\n <Tooltip title={t('dt.toolbar.addRowBelow')}>\n <Button\n type='text'\n size={'small'}\n icon={<ArrowDownOutlined />}\n onClick={() => tableActions.addRowBelow(cursor?.y)}\n />\n </Tooltip>\n <Tooltip title={t('dt.toolbar.addRowAbove')}>\n <Button\n type='text'\n size={'small'}\n icon={<ArrowUpOutlined />}\n onClick={() => tableActions.addRowAbove(cursor?.y)}\n />\n </Tooltip>\n <Tooltip>\n <Popconfirm\n title={t('dt.toolbar.removeRowConfirm')}\n okText={t('common.remove')}\n onConfirm={() => tableActions.removeRow(cursor?.y)}\n >\n <Button type='text' danger size={'small'} icon={<DeleteOutlined />} />\n </Popconfirm>\n </Tooltip>\n <Button type='text' size={'small'} icon={<CloseOutlined />} onClick={() => tableActions.setCursor(null)}>\n Deselect\n </Button>\n </>\n )}\n </Stack>\n {traceIndexOptions && (\n <Stack horizontal verticalAlign='center' horizontalAlign='end'>\n <Typography.Text style={{ fontSize: 12 }}>{t('dt.toolbar.simulationIndex')}</Typography.Text>\n <Select\n size='small'\n style={{ fontSize: 12, minWidth: 60 }}\n options={traceIndexOptions}\n onChange={(debugIndex: number) => stateStore.setState({ debugIndex })}\n value={traceIndexOptions.some((t) => t.value === debugIndex) ? debugIndex : 0}\n />\n <Divider type='vertical' />\n </Stack>\n )}\n </Stack>\n <input\n multiple\n hidden\n accept='.xlsx'\n type='file'\n ref={fileInput}\n onChange={readExcelFile}\n onClick={(event) => {\n (event.target as HTMLInputElement).value = '';\n }}\n />\n <DtExcelDialog excelData={excelData} handleSuccess={handleDataMapping} handleCancel={handleCancel} />\n </>\n );\n};\n","import { Variable, VariableType } from '@gorules/zen-engine-wasm';\nimport equal from 'fast-deep-equal/es6/react';\nimport type React from 'react';\nimport { useEffect, useRef } from 'react';\nimport { useDebouncedCallback } from 'use-debounce';\n\nimport type { SchemaSelectProps } from '../../helpers/components';\nimport type { GetNodeDataResult } from '../../helpers/node-data';\nimport { isWasmAvailable } from '../../helpers/wasm';\nimport { type DictionaryMap, useDictionaries } from '../../theme';\nimport type { SimulationTrace, SimulationTraceDataTable } from '../decision-graph';\nimport type { DecisionTableStoreType, JdmUiMode } from './context/dt-store.context';\nimport {\n type DecisionTableType,\n parseDecisionTable,\n useDecisionTableActions,\n useDecisionTableRaw,\n useDecisionTableState,\n} from './context/dt-store.context';\nimport type { TableCellProps } from './table/table-default-cell';\n\nexport type DecisionTableEmptyType = {\n id?: string;\n name?: string;\n defaultValue?: DecisionTableType;\n value?: DecisionTableType;\n disabled?: boolean;\n disableHitPolicy?: boolean;\n cellRenderer?: (props: TableCellProps) => React.JSX.Element | null | undefined;\n inputsSchema?: SchemaSelectProps[];\n outputsSchema?: SchemaSelectProps[];\n permission?: DecisionTableStoreType['state']['permission'];\n mode?: JdmUiMode;\n dictionaries?: DictionaryMap;\n inputVariableType?: VariableType;\n debug?: {\n trace: SimulationTrace<SimulationTraceDataTable>;\n inputData?: GetNodeDataResult;\n snapshot: DecisionTableType;\n };\n minColWidth?: number;\n colWidth?: number;\n onChange?: (val: DecisionTableType) => void;\n};\n\nexport const DecisionTableEmpty: React.FC<DecisionTableEmptyType> = ({\n id,\n name,\n defaultValue,\n value,\n disabled = false,\n disableHitPolicy = false,\n inputsSchema,\n outputsSchema,\n debug,\n colWidth,\n minColWidth,\n cellRenderer,\n permission = 'edit:full',\n mode = 'dev',\n dictionaries,\n onChange,\n inputVariableType,\n}) => {\n const mountedRef = useRef(false);\n const { stateStore, listenerStore } = useDecisionTableRaw();\n const tableActions = useDecisionTableActions();\n const contextDictionaries = useDictionaries();\n const { decisionTable } = useDecisionTableState(({ decisionTable }) => ({\n decisionTable,\n }));\n\n const resolvedDictionaries =\n dictionaries && Object.keys(dictionaries).length > 0 ? dictionaries : contextDictionaries;\n\n const innerChange = useDebouncedCallback((table: DecisionTableType) => {\n onChange?.(table);\n }, 100);\n\n useEffect(() => {\n stateStore.setState({\n id,\n name,\n disabled,\n disableHitPolicy,\n inputsSchema,\n outputsSchema,\n colWidth: colWidth || 200,\n minColWidth: minColWidth || 150,\n permission,\n mode,\n dictionaries: resolvedDictionaries,\n });\n }, [\n id,\n name,\n disabled,\n disableHitPolicy,\n inputsSchema,\n minColWidth,\n colWidth,\n outputsSchema,\n permission,\n mode,\n resolvedDictionaries,\n ]);\n\n useEffect(() => {\n listenerStore.setState({\n cellRenderer,\n onChange: innerChange,\n });\n }, [cellRenderer, innerChange]);\n\n useEffect(() => {\n if (mountedRef.current && value !== undefined && !equal(value, decisionTable)) {\n tableActions.setDecisionTable(parseDecisionTable(value));\n }\n }, [value]);\n\n useEffect(() => {\n tableActions.setDecisionTable(parseDecisionTable(value === undefined ? defaultValue : value));\n mountedRef.current = true;\n\n return () => {\n const { derivedVariableTypes } = stateStore.getState();\n\n Object.values(derivedVariableTypes).forEach((vt) => {\n vt.free();\n });\n };\n }, []);\n\n useEffect(() => {\n if (!debug) {\n stateStore.setState({ debug: undefined });\n return;\n }\n\n stateStore.setState({\n debug: {\n trace: debug.trace,\n snapshot: debug.snapshot,\n inputData: debug.inputData,\n },\n });\n }, [debug]);\n\n useEffect(() => {\n stateStore.setState({ inputVariableType });\n }, [inputVariableType]);\n\n useEffect(() => {\n if (!isWasmAvailable()) {\n return;\n }\n\n const isLoop = (store: DecisionTableStoreType['state']) => {\n return store.debug?.snapshot.executionMode === 'loop';\n };\n\n const applyDebug = (state: DecisionTableStoreType['state']) => {\n const inputData = state.debug?.inputData;\n if (!inputData) {\n return;\n }\n\n const varInputData = new Variable(inputData.data);\n if (isLoop(state)) {\n const newInputData = varInputData.get(state.debugIndex).cloneWith('$nodes', inputData.$nodes);\n stateStore.setState({\n calculatedInputData: newInputData,\n inputVariableType: VariableType.fromVariable(newInputData),\n });\n } else {\n const newInputData = varInputData.cloneWith('$nodes', inputData.$nodes);\n stateStore.setState({\n calculatedInputData: newInputData,\n inputVariableType: VariableType.fromVariable(newInputData),\n });\n }\n };\n\n applyDebug(stateStore.getState());\n return stateStore.subscribe((state, prevState) => {\n if (state.debugIndex === prevState.debugIndex && state.debug === prevState.debug) {\n return;\n }\n\n applyDebug(state);\n });\n }, []);\n\n return null;\n};\n","import React from 'react';\n\nimport { Typography } from './primitives';\nimport { Stack } from './stack';\n\nexport type SpacedTextProps = {\n left: React.ReactNode;\n right?: React.ReactNode;\n gap?: number;\n};\n\nexport const SpacedText: React.FC<SpacedTextProps> = ({ left, right, gap = 16 }) => {\n return (\n <Stack gap={gap} horizontal horizontalAlign='space-between'>\n <Typography.Text style={{ color: 'inherit' }}>{left}</Typography.Text>\n {right && <Typography.Text style={{ color: 'inherit' }}>{right}</Typography.Text>}\n </Stack>\n );\n};\n","import React from 'react';\n\nimport { useT } from '../../../theming/i18n';\nimport { Dropdown } from '../../primitives';\nimport { SpacedText } from '../../spaced-text';\nimport { useDecisionTableActions, useDecisionTableState } from '../context/dt-store.context';\n\nconst ContextMenu: React.FC<React.PropsWithChildren> = (props) => {\n const t = useT();\n const { children } = props;\n\n const tableActions = useDecisionTableActions();\n const { cursor, disabled } = useDecisionTableState(({ cursor, disabled }) => ({\n cursor,\n disabled,\n }));\n\n return (\n <Dropdown\n destroyPopupOnHide\n transitionName=''\n disabled={disabled}\n overlayStyle={{\n minWidth: 270,\n }}\n menu={{\n items: [\n {\n key: 'addRowAbove',\n label: <SpacedText left={t('dt.toolbar.addRowAbove')} />,\n onClick: () => {\n if (cursor) tableActions.addRowAbove(cursor?.y);\n },\n },\n {\n key: 'addRowBelow',\n label: <SpacedText left={t('dt.toolbar.addRowBelow')} />,\n onClick: () => {\n if (cursor) tableActions.addRowBelow(cursor?.y);\n },\n },\n {\n type: 'divider',\n },\n {\n key: 'remove',\n label: <SpacedText left={t('dt.toolbar.removeRow')} />,\n onClick: () => {\n if (cursor) tableActions.removeRow(cursor?.y);\n },\n },\n ],\n }}\n trigger={['contextMenu']}\n >\n {children}\n </Dropdown>\n );\n};\n\nexport const TableContextMenu = React.memo(ContextMenu);\n","import type { DecisionTableStoreType } from '../components/decision-table/context/dt-store.context';\n\nexport type SchemaSelectProps = {\n field: string;\n name?: string;\n items?: SchemaSelectProps[];\n};\nexport const recursiveSelect = (selector: string[], fields: SchemaSelectProps[]): SchemaSelectProps | undefined => {\n const key = selector?.[0];\n if (!key) return;\n const field = fields.find((field) => field.field === key);\n if (field?.items) {\n return recursiveSelect(selector.slice(1), field.items);\n }\n return field;\n};\n\nexport const getPath = (key: string, items: SchemaSelectProps[]): string[] | undefined => {\n if (!key || !items) return;\n for (let i = 0; i < items.length; i++) {\n const item = items[i];\n if (item.field === key) {\n return [item.field];\n }\n\n if (item.items) {\n const path = getPath(key, item.items);\n if (!path) continue;\n return [item.field, ...path];\n }\n }\n};\n\nexport const columnIdSelector = (x: string) => (state: DecisionTableStoreType['state']) =>\n [\n ...state.decisionTable.inputs.map((i: any) => ({\n ...i,\n colType: 'input',\n })),\n ...state.decisionTable.outputs.map((i: any) => ({\n ...i,\n colType: 'output',\n })),\n ].find((c) => c.id === x);\n","import clsx from 'clsx';\nimport React from 'react';\n\nimport type { RadioGroupProps } from '../primitives';\nimport { Radio } from '../primitives';\n\nexport type DiffRadioProps = {\n previousValue?: string;\n displayDiff?: boolean;\n} & RadioGroupProps;\n\nexport const DiffRadio: React.FC<DiffRadioProps> = ({ displayDiff, previousValue, options, ...rest }) => {\n return (\n <Radio.Group {...rest}>\n {(options || []).map((option: any) => (\n <Radio\n value={option.value}\n key={option.value}\n className={clsx([\n displayDiff &&\n option.value === previousValue &&\n 'text-[var(--destructive)] line-through decoration-[var(--destructive)]',\n displayDiff && option.value === rest.value && 'text-[var(--grl-color-success)]',\n ])}\n >\n {option.label}\n </Radio>\n ))}\n </Radio.Group>\n );\n};\n","import { ArrowDownOutlined, ArrowRightOutlined } from '#icons';\nimport React from 'react';\n\nexport const ArrowDiffIcon: React.FC<{ direction?: 'right' | 'down'; size?: 'small' | 'medium' }> = ({\n direction = 'right',\n size = 'small',\n}) => {\n const fontSize = size === 'small' ? 12 : 16;\n if (direction === 'down')\n return (\n <ArrowDownOutlined\n className={'text-modified'}\n style={{\n fontSize,\n }}\n />\n );\n return (\n <ArrowRightOutlined\n className={'text-modified'}\n style={{\n fontSize,\n }}\n />\n );\n};\n","import React from 'react';\n\nimport { ArrowDiffIcon } from '../arrow-diff-icon';\nimport { Space, Switch, type SwitchProps } from '../primitives';\n\nexport type DiffSwitchProps = {\n previousChecked?: boolean;\n displayDiff?: boolean;\n} & SwitchProps;\n\nexport const DiffSwitch: React.FC<DiffSwitchProps> = ({ displayDiff, previousChecked, ...rest }) => {\n return (\n <Space size={4}>\n {displayDiff && (\n <>\n <Switch disabled={rest.disabled} size={'small'} checked={previousChecked} />\n <ArrowDiffIcon />\n </>\n )}\n <Switch size={'small'} {...rest} />\n </Space>\n );\n};\n","import clsx from 'clsx';\nimport React from 'react';\n\nimport { Input, type InputProps } from '../primitives';\n\nexport type DiffInputProps = InputProps & {\n previousValue?: string;\n displayDiff?: boolean;\n};\n\nexport const DiffInput: React.FC<DiffInputProps> = ({ previousValue, displayDiff, ...rest }) => {\n if (displayDiff) {\n return (\n <div className='w-full overflow-hidden border border-[var(--border)] rounded-[var(--grl-border-radius)]'>\n {(previousValue || '')?.length > 0 && (\n <Input\n {...rest}\n value={previousValue}\n onChange={undefined}\n className={clsx(\n rest.className,\n 'border-0 shadow-none focus:shadow-none focus:ring-0 line-through decoration-[var(--destructive)]',\n )}\n />\n )}\n {((rest?.value || '') as string)?.length > 0 && (\n <Input {...rest} className={clsx(rest.className, 'border-0 shadow-none focus:shadow-none focus:ring-0')} />\n )}\n </div>\n );\n }\n return <Input {...rest} />;\n};\n","import clsx from 'clsx';\nimport React from 'react';\n\nimport { ArrowDiffIcon } from '../arrow-diff-icon';\nimport { Select, type SelectProps, Space, type SpaceProps } from '../primitives';\n\nexport type DiffSelectProps = Omit<SelectProps, 'direction'> & {\n previousValue?: string;\n displayDiff?: boolean;\n direction?: SpaceProps['direction'];\n};\n\nexport const DiffSelect: React.FC<DiffSelectProps> = ({\n direction = 'horizontal',\n previousValue,\n displayDiff,\n ...rest\n}) => {\n return (\n <Space size={'small'} direction={direction}>\n {displayDiff && (\n <>\n <Select\n {...rest}\n disabled\n value={previousValue}\n className={clsx(rest.className, 'text-[var(--destructive)] line-through decoration-[var(--destructive)]')}\n onChange={undefined}\n />\n <ArrowDiffIcon />\n </>\n )}\n <Select\n {...rest}\n disabled={rest.disabled || displayDiff}\n className={clsx(rest.className, displayDiff && 'text-[var(--grl-color-success)]')}\n />\n </Space>\n );\n};\n","import clsx from 'clsx';\nimport React from 'react';\n\nimport type { CodeEditorProps, CodeEditorRef } from '../code-editor';\nimport { CodeEditor } from '../code-editor';\n\nexport type DiffCodeEditorProps = CodeEditorProps & {\n displayDiff?: boolean;\n previousValue?: string;\n noStyle?: boolean;\n};\n\nexport const DiffCodeEditor = React.forwardRef<CodeEditorRef, DiffCodeEditorProps>(\n ({ displayDiff, previousValue, noStyle, ...rest }, ref) => {\n if (displayDiff) {\n return (\n <div\n className={clsx(\n 'w-full overflow-hidden border border-[var(--border)] rounded-[var(--grl-border-radius)]',\n noStyle && 'border-0 rounded-none',\n )}\n >\n {(previousValue || '')?.length > 0 && (\n <CodeEditor\n {...rest}\n className={clsx(rest.className, 'line-through decoration-[var(--destructive)]')}\n value={previousValue}\n onChange={undefined}\n disabled={true}\n noStyle\n lint={false}\n />\n )}\n {(rest?.value || '')?.length > 0 && (\n <CodeEditor {...rest} className={rest.className} disabled={true} noStyle lint={false} />\n )}\n </div>\n );\n }\n\n return <CodeEditor ref={ref} noStyle={noStyle} {...rest} />;\n },\n);\n","import clsx from 'clsx';\nimport React, { forwardRef } from 'react';\n\nimport { AutosizeTextArea, type AutosizeTextAreaProps } from '../autosize-text-area';\n\nexport type DiffAutosizeTextAreaProps = AutosizeTextAreaProps & {\n previousValue?: string;\n displayDiff?: boolean;\n noStyle?: boolean;\n};\n\nexport const DiffAutosizeTextArea = forwardRef<HTMLDivElement, DiffAutosizeTextAreaProps>(\n ({ previousValue, displayDiff, noStyle, ...rest }, ref) => {\n if (displayDiff) {\n return (\n <div\n className={clsx(\n 'w-full overflow-hidden border border-[var(--border)] rounded-[var(--grl-border-radius)]',\n noStyle && 'border-0 rounded-none',\n )}\n >\n {(previousValue || '')?.length > 0 && (\n <AutosizeTextArea\n {...rest}\n value={previousValue}\n onChange={undefined}\n className={clsx(\n rest.className,\n 'border-0 shadow-none focus:shadow-none focus:ring-0 line-through decoration-[var(--destructive)]',\n )}\n />\n )}\n {((rest.value || '') as string)?.length > 0 && (\n <AutosizeTextArea\n {...rest}\n className={clsx(rest.className, 'border-0 shadow-none focus:shadow-none focus:ring-0')}\n />\n )}\n </div>\n );\n }\n return <AutosizeTextArea ref={ref} noStyle={noStyle} {...rest} />;\n },\n);\n","import { P, match } from 'ts-pattern';\n\nexport const getReferenceMap = (trace: unknown, index: number) => {\n return match(trace)\n .with({ traceData: { reference_map: P._ } }, (s) => s.traceData.reference_map as Record<string, unknown>)\n .with({ traceData: P.array() }, ({ traceData: arr }) => {\n return (arr[index] as { reference_map?: Record<string, unknown> } | undefined)?.reference_map;\n })\n .otherwise(() => undefined);\n};\n","import type { CellContext } from '@tanstack/react-table';\nimport React, { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';\nimport { P, match } from 'ts-pattern';\n\nimport { columnIdSelector } from '../../../helpers/components';\nimport { isWasmAvailable, useWasmReady } from '../../../helpers/wasm';\nimport type { CodeEditorRef } from '../../code-editor';\nimport {\n type BuilderRef,\n ExpressionBuilder,\n StandardExpressionBuilder,\n focusBuilderRoot,\n} from '../../code-editor/business';\nimport type { DiffMetadata } from '../../decision-graph';\nimport { DiffAutosizeTextArea } from '../../shared';\nimport { DiffCodeEditor } from '../../shared/diff-ce';\nimport {\n type TableSchemaItem,\n useDecisionTableActions,\n useDecisionTableRaw,\n useDecisionTableState,\n} from '../context/dt-store.context';\nimport { getReferenceMap } from '../util';\n\nexport type TableDefaultCellProps = {\n context: CellContext<Record<string, string>, string>;\n} & React.HTMLAttributes<HTMLDivElement>;\n\n/** Runtime-only diff metadata attached to rule rows by the graph differ. */\ntype RuleDiffCarrier = { _diff?: { fields?: Record<string, DiffMetadata> } };\n\n/** Optional per-table custom cell renderer injected through table meta. */\ntype CellMetaWithRenderer = {\n getCell?: (args: TableCellProps) => React.ReactNode;\n};\n\nexport const TableDefaultCell = memo<TableDefaultCellProps>(({ context, ...props }) => {\n const {\n row: { index },\n column: { id },\n table,\n } = context;\n\n const tableActions = useDecisionTableActions();\n const { disabled, value, diff } = useDecisionTableState(({ decisionTable, disabled }) => ({\n value: decisionTable?.rules?.[index]?.[id],\n diff: (decisionTable?.rules?.[index] as RuleDiffCarrier | undefined)?._diff?.fields?.[id],\n disabled,\n }));\n\n const column = useDecisionTableState(\n columnIdSelector(id),\n (a, b) => a?.id !== undefined && b?.id !== undefined && a?.id === b?.id,\n );\n\n const [inner, setInner] = useState(value);\n useLayoutEffect(() => {\n if (inner !== value) {\n setInner(value);\n }\n }, [value]);\n\n const commit = useCallback(\n (val: string) => {\n setInner(val);\n tableActions.commitData(val, { x: id, y: index });\n },\n [tableActions, setInner],\n );\n\n return (\n <div\n data-cell-wrapper\n className='flex items-stretch w-full h-full leading-0 [&>*]:grow [&_.grl-ce]:h-full [&_.grl-ce_.cm-editor]:h-full'\n onFocus={() => tableActions.setCursor({ x: id, y: index })}\n onContextMenu={() => tableActions.setCursor({ x: id, y: index })}\n {...props}\n >\n {(table.options.meta as CellMetaWithRenderer | undefined)?.getCell?.({\n disabled,\n column,\n value: inner,\n diff,\n onChange: commit,\n index,\n }) || (\n <TableInputCell disabled={disabled} column={column} value={inner} onChange={commit} diff={diff} index={index} />\n )}\n </div>\n );\n});\n\nexport type TableCellProps = {\n column?: ({ colType: string } & TableSchemaItem) | undefined;\n value: string;\n diff?: DiffMetadata | undefined;\n onChange: (value: string) => void;\n disabled?: boolean;\n index: number;\n};\n\nenum LocalVariableKind {\n Root,\n Derived,\n}\n\nconst TableInputCell: React.FC<TableCellProps> = ({ column, value, onChange, disabled, diff, index }) => {\n const id = useMemo(() => crypto.randomUUID(), []);\n const textAreaDivRef = useRef<HTMLDivElement>(null);\n const codeEditorRef = useRef<CodeEditorRef>(null);\n const containerRef = useRef<HTMLDivElement>(null);\n const builderRef = useRef<BuilderRef>(null);\n const raw = useDecisionTableRaw();\n const wasmReady = useWasmReady();\n\n const {\n inputVariableType,\n localVariableType,\n mode: rawMode,\n } = useDecisionTableState(({ inputVariableType, derivedVariableTypes, mode }) => ({\n inputVariableType,\n mode,\n localVariableType: match(column)\n .with({ colType: 'input', field: P.string }, (c) => ({\n type: LocalVariableKind.Derived,\n value: derivedVariableTypes[c.field] ?? null,\n }))\n .otherwise(() => ({ type: LocalVariableKind.Root, value: inputVariableType })),\n }));\n\n // Business mode requires WASM; fall back to dev mode until it's ready\n const mode = wasmReady ? rawMode : 'dev';\n\n useEffect(() => {\n if (!inputVariableType) {\n return;\n }\n\n if (!column?.field || localVariableType.type !== LocalVariableKind.Derived) {\n return;\n }\n\n const state = raw.stateStore.getState();\n\n const resultingType = inputVariableType.clone();\n const calculatedType = inputVariableType.calculateType(column.field);\n resultingType.set('$', calculatedType);\n\n raw.stateStore.setState({\n derivedVariableTypes: {\n ...state.derivedVariableTypes,\n [column.field]: resultingType,\n },\n });\n }, [inputVariableType, column]);\n\n useEffect(() => {\n const anchor = containerRef.current ?? textAreaDivRef.current;\n if (!anchor) return;\n\n const parentContainer = anchor.closest('[data-cell-wrapper]')! as HTMLElement;\n const eventListener = (e: Event) => {\n const target = e.target as HTMLElement;\n if (target.closest('.cm-editor, input, textarea, select, button, .ant-select')) return;\n\n if (builderRef.current) {\n builderRef.current.focus();\n } else {\n focusBuilderRoot(anchor);\n }\n };\n\n parentContainer.style.cursor = 'text';\n parentContainer.addEventListener('click', eventListener);\n\n return () => {\n parentContainer.style.cursor = '';\n parentContainer.removeEventListener('click', eventListener);\n };\n }, []);\n\n if (!column) {\n return (\n <DiffAutosizeTextArea\n id={id}\n ref={textAreaDivRef}\n className='border-0! w-full bg-transparent py-[9px] px-3 text-sm opacity-70 focus:shadow-none!'\n maxRows={3}\n value={value}\n disabled={disabled}\n displayDiff={diff?.status === 'modified'}\n previousValue={diff?.previousValue}\n spellCheck={false}\n onChange={(e) => onChange(e.target.value)}\n />\n );\n }\n\n const isInputColumn = column.colType === 'input' && column.field;\n const isOutputColumn = column.colType === 'output';\n\n if (mode === 'business' && isInputColumn) {\n return (\n // py/px mirror the pre-refactor cell padding (7px/8px): 23.5px builder\n // + 14px padding = 37.5px, exactly the dev-mode CodeMirror cell height.\n <div ref={containerRef} className='relative w-full py-[7px] px-2 [--b-font-size:14px]'>\n <TableInputCellStatus index={index} columnId={column.id} />\n <ExpressionBuilder\n ref={builderRef}\n value={value ?? ''}\n onChange={onChange}\n disabled={disabled}\n fieldType={column.fieldType}\n />\n </div>\n );\n }\n\n if (mode === 'business' && isOutputColumn) {\n return (\n <div ref={containerRef} className='relative w-full py-[7px] px-2 [--b-font-size:14px]'>\n <StandardExpressionBuilder\n ref={builderRef}\n value={value ?? ''}\n onChange={onChange}\n disabled={disabled}\n fieldType={column.outputFieldType}\n />\n </div>\n );\n }\n\n return (\n <div ref={containerRef} className='relative w-full [--b-font-size:14px]'>\n {column.colType === 'input' && <TableInputCellStatus index={index} columnId={column.id} />}\n <DiffCodeEditor\n lazy\n ref={codeEditorRef}\n id={id}\n type={match(column)\n .with({ colType: 'input', field: P.string }, () => 'unary' as const)\n .otherwise(() => 'standard' as const)}\n className='[--ce-verticalPadding:9px] [--ce-horizontalPadding:0.75rem] [&_.cm-editor]:border-0! [&_.cm-editor]:shadow-none! [&_.cm-editor]:rounded-none [&_.cm-editor]:w-full [&_.cm-editor]:bg-transparent!'\n noStyle\n displayDiff={diff?.status === 'modified'}\n previousValue={diff?.previousValue}\n variableType={localVariableType.value}\n maxRows={3}\n value={value}\n disabled={disabled}\n onChange={onChange}\n />\n </div>\n );\n};\n\nconst TableInputCellStatus: React.FC<{ columnId: string; index: number }> = React.memo(({ columnId, index }) => {\n const inputData = useDecisionTableState(({ calculatedInputData }) => calculatedInputData);\n const expressionContext = useDecisionTableState(({ debug, debugIndex }) => {\n if (!isWasmAvailable() || !debug) {\n return;\n }\n\n const { trace, snapshot } = debug;\n const referenceMap = getReferenceMap(trace, debugIndex);\n if (!referenceMap) {\n return null;\n }\n\n const columnDef = snapshot.inputs.find((i) => i.id === columnId);\n if (!columnDef) {\n return null;\n }\n\n if (!(index in snapshot.rules)) {\n return null;\n }\n\n const expression = snapshot.rules[index]?.[columnId]?.trim();\n if (!columnDef.field) {\n return { type: 'standard' as const, expression };\n }\n\n if (!(columnDef.field in referenceMap)) {\n return { type: 'skip' as const };\n }\n\n return { type: 'unary' as const, expression, $: referenceMap[columnDef.field] };\n });\n\n const status = useMemo<'hit' | 'no-hit' | 'skip' | null>(() => {\n if (!inputData || !expressionContext) {\n return null;\n }\n\n const { type, expression, $ } = expressionContext;\n if (type === 'skip') {\n return 'skip';\n }\n\n if (!expression) {\n return 'hit';\n }\n\n try {\n let isOk: boolean;\n if (type === 'unary') {\n const newInputData = inputData.cloneWith('$', $);\n isOk = newInputData.evaluateUnaryExpression(expression);\n } else {\n isOk = inputData.evaluateExpression(expression) === true;\n }\n\n return isOk ? 'hit' : 'no-hit';\n } catch {\n return 'no-hit';\n }\n }, [inputData, expressionContext]);\n\n if (!status) {\n return null;\n }\n\n switch (status) {\n case 'hit':\n return (\n <div\n className='absolute top-0.5 left-0.5 z-[5] opacity-80 rounded-full h-[5px] w-[5px] border border-[var(--grl-color-success)] bg-[var(--grl-color-success)]'\n data-status={status}\n />\n );\n case 'no-hit':\n return (\n <div\n className='absolute top-0.5 left-0.5 z-[5] opacity-80 rounded-full h-[5px] w-[5px] border border-[var(--grl-color-border-hover)]'\n data-status={status}\n />\n );\n case 'skip':\n return null;\n }\n});\n","import { DragOutlined, MinusSquareOutlined, PlusSquareOutlined } from '#icons';\nimport React from 'react';\nimport { match } from 'ts-pattern';\n\nimport type { DiffStatus } from './decision-graph/dg-types';\n\nexport const DiffIcon: React.FC<{\n status?: DiffStatus;\n style?: React.CSSProperties;\n className?: string;\n}> = ({ status, style, className }) => {\n return match(status)\n .with('removed', () => (\n <MinusSquareOutlined\n className={className}\n style={{\n color: 'var(--destructive)',\n ...(style || {}),\n }}\n />\n ))\n .with('added', () => (\n <PlusSquareOutlined\n className={className}\n style={{\n color: 'var(--grl-color-success)',\n ...(style || {}),\n }}\n />\n ))\n .with('modified', () => (\n <span\n className={className}\n style={{\n width: style?.fontSize ?? 14,\n height: style?.fontSize ?? 14,\n border: '1.5px solid var(--grl-color-warning)',\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n position: 'relative',\n boxSizing: 'border-box',\n ...(style || {}),\n }}\n >\n <span\n style={{\n width: 3,\n height: 3,\n backgroundColor: 'var(--grl-color-warning)',\n borderRadius: '50%',\n }}\n />\n </span>\n ))\n .with('moved', () => (\n <DragOutlined\n className={className}\n style={{\n color: 'var(--grl-color-info)',\n ...(style || {}),\n }}\n />\n ))\n .otherwise(() => null);\n};\n","import clsx from 'clsx';\nimport React, { useEffect, useRef, useState } from 'react';\n\nimport { Typography } from './primitives';\n\ntype TextEditProps = {\n onChange?: (text: string) => void;\n value?: string;\n disabled?: boolean;\n} & Omit<React.HTMLAttributes<HTMLDivElement>, 'onChange' | 'children'>;\n\nexport const TextEdit: React.FC<TextEditProps> = ({ className, value, onChange, disabled, ...props }) => {\n const [contentEditing, setContentEditing] = useState(false);\n const inputRef = useRef<HTMLInputElement>(null);\n\n useEffect(() => {\n if (inputRef.current && contentEditing) {\n inputRef.current.value = value as string;\n inputRef.current.focus();\n inputRef.current.select();\n }\n }, [contentEditing]);\n\n return (\n <div className={clsx('mr-2 flex max-w-[140px] flex-col', className)} {...props}>\n {!contentEditing && (\n <Typography.Text\n className={clsx(\n 'w-min max-w-full truncate rounded border border-transparent px-[5px] py-px text-sm! leading-[1.2] transition-colors hover:bg-[var(--accent)]',\n )}\n onClick={() => {\n if (!disabled) {\n setContentEditing(true);\n }\n }}\n >\n {value}\n </Typography.Text>\n )}\n {contentEditing && (\n <input\n ref={inputRef}\n className={clsx(\n 'nodrag rounded border border-[var(--grl-color-primary-border)] bg-transparent px-[5px] py-px text-sm! leading-[1.2] text-inherit outline-none!',\n )}\n onBlur={(e) => {\n if (e.target.value?.trim?.()?.length > 0) {\n onChange?.(inputRef?.current?.value as string);\n }\n e.preventDefault();\n setContentEditing(false);\n }}\n onKeyDown={(e) => {\n if (e.key === 'Enter') {\n e.currentTarget.blur();\n e.preventDefault();\n } else if (e.key === 'Escape') {\n if (inputRef.current) {\n inputRef.current.value = value as string;\n }\n setContentEditing(false);\n e.preventDefault();\n }\n }}\n />\n )}\n </div>\n );\n};\n","import { PlusOutlined, SwapOutlined } from '#icons';\nimport clsx from 'clsx';\nimport React from 'react';\n\nimport { useT } from '../../../theming/i18n';\nimport { DiffIcon } from '../../diff-icon';\nimport { Button, Tooltip, Typography } from '../../primitives';\nimport { Stack } from '../../stack';\nimport { TextEdit } from '../../text-edit';\nimport { InputFieldEdit } from '../components/input-field-edit';\nimport { OutputFieldEdit } from '../components/output-field-edit';\nimport { useDecisionTableDialog } from '../context/dt-dialog.context';\nimport type { DecisionTablePermission } from '../context/dt-store.context';\nimport { type TableSchemaItem, useDecisionTableActions, useDecisionTableState } from '../context/dt-store.context';\nimport { getReferenceMap } from '../util';\n\nconst TEXT_REMOVED = 'text-[var(--destructive)] line-through decoration-[var(--destructive)]';\n\nexport type TableHeadCellProps = {\n permission?: DecisionTablePermission;\n disabled?: boolean;\n};\n\nexport type TableHeadCellFieldProps = {\n permission?: DecisionTablePermission;\n disabled?: boolean;\n schema: TableSchemaItem;\n};\n\nexport const TableHeadCellInput: React.FC<TableHeadCellProps> = ({ permission, disabled }) => {\n const t = useT();\n const inputs = useDecisionTableState((store) => store.decisionTable?.inputs);\n const tableActions = useDecisionTableActions();\n const { setDialog } = useDecisionTableDialog();\n const { inputData, inputVariableType } = useDecisionTableState(({ calculatedInputData, inputVariableType }) => ({\n inputData: calculatedInputData,\n inputVariableType,\n }));\n\n return (\n <div className='flex items-center h-full w-full min-h-0 box-border py-1 px-2'>\n <Stack horizontal horizontalAlign='space-between' verticalAlign='center'>\n <Stack gap={0} className='overflow-hidden' verticalAlign={'center'}>\n <Typography.Text className={'truncate grl-dt-text-primary'}>Inputs</Typography.Text>\n </Stack>\n {(permission === 'edit:full' || permission === 'edit:rules') && (\n <div className='flex'>\n {inputs?.length > 1 && (\n <Tooltip title={t('dt.table.reorderFields')}>\n <Button\n className='grl-dt-text-secondary'\n icon={<SwapOutlined />}\n size={'small'}\n type={'text'}\n disabled={disabled}\n onClick={() => {\n setDialog({\n type: 'reorder',\n columnType: 'inputs',\n item: null,\n });\n }}\n />\n </Tooltip>\n )}\n <InputFieldEdit\n mode='create'\n disabled={disabled}\n variableType={inputVariableType}\n inputData={inputData}\n trigger={\n <Button\n className='grl-dt-text-secondary'\n size={'small'}\n type={'text'}\n icon={<PlusOutlined />}\n disabled={disabled}\n />\n }\n onCreate={(name, field, fieldType) => {\n tableActions.addColumn('inputs', {\n id: crypto.randomUUID(),\n name,\n field: field || undefined,\n fieldType,\n });\n }}\n />\n </div>\n )}\n </Stack>\n </div>\n );\n};\n\nexport const TableHeadCellOutput: React.FC<TableHeadCellProps> = ({ permission, disabled }) => {\n const t = useT();\n const outputs = useDecisionTableState((store) => store.decisionTable?.outputs);\n const tableActions = useDecisionTableActions();\n const { setDialog } = useDecisionTableDialog();\n\n return (\n <div className='flex items-center h-full w-full min-h-0 box-border py-1 px-2'>\n <Stack horizontal horizontalAlign={'space-between'} verticalAlign={'center'}>\n <Stack gap={0} className='overflow-hidden' verticalAlign={'center'}>\n <Typography.Text className={'truncate grl-dt-text-primary'}>Outputs</Typography.Text>\n </Stack>\n {permission === 'edit:full' && (\n <div className='flex'>\n {outputs?.length > 1 && (\n <Tooltip title={t('dt.table.reorderFields')}>\n <Button\n className='grl-dt-text-secondary'\n icon={<SwapOutlined />}\n size={'small'}\n type={'text'}\n disabled={disabled}\n onClick={() => {\n setDialog({\n type: 'reorder',\n columnType: 'outputs',\n item: null,\n });\n }}\n />\n </Tooltip>\n )}\n <OutputFieldEdit\n mode='create'\n disabled={disabled}\n trigger={\n <Button\n className='grl-dt-text-secondary'\n size={'small'}\n type={'text'}\n icon={<PlusOutlined />}\n disabled={disabled}\n />\n }\n onCreate={(name, field, outputFieldType) => {\n tableActions.addColumn('outputs', {\n id: crypto.randomUUID(),\n name,\n field: field || 'output',\n outputFieldType,\n });\n }}\n />\n </div>\n )}\n </Stack>\n </div>\n );\n};\n\nexport const TableHeadCellInputField: React.FC<TableHeadCellFieldProps> = ({ permission, disabled, schema }) => {\n const tableActions = useDecisionTableActions();\n const { inputData, inputVariableType } = useDecisionTableState(({ calculatedInputData, inputVariableType }) => ({\n inputData: calculatedInputData,\n inputVariableType,\n }));\n\n const referenceData = useDecisionTableState(({ debug, debugIndex }) => {\n if (!debug) {\n return undefined;\n }\n\n const { trace, snapshot } = debug;\n const snapshotField = snapshot.inputs.find((i) => i.id === schema.id);\n if (!snapshotField?.field) {\n return undefined;\n }\n\n const referenceMap = getReferenceMap(trace, debugIndex);\n return {\n field: snapshotField.field,\n value: referenceMap?.[snapshotField.field],\n };\n });\n\n return (\n <div className={clsx(['flex items-center h-full w-full min-h-0 box-border py-1 px-2'])}>\n <Stack horizontal horizontalAlign={'space-between'} verticalAlign={'center'}>\n <Stack gap={0} className='overflow-hidden'>\n {schema?._diff?.fields?.name?.status === 'modified' && (\n <Typography.Text className={clsx(['truncate', 'grl-dt-text-primary', TEXT_REMOVED])}>\n {schema?._diff?.fields?.name?.previousValue}\n </Typography.Text>\n )}\n <TextEdit\n className={clsx(['truncate', 'grl-dt-text-primary'])}\n value={schema.name}\n onChange={(name) => {\n tableActions.updateColumn('inputs', schema.id, { ...schema, name });\n }}\n />\n {schema?._diff?.fields?.field?.status && (\n <Typography.Text\n className={clsx(['truncate', 'grl-dt-text-secondary', TEXT_REMOVED])}\n type='secondary'\n style={{ fontSize: 12 }}\n >\n {schema?._diff?.fields?.field?.previousValue}\n </Typography.Text>\n )}\n <InputFieldEdit\n value={schema.field}\n variableType={inputVariableType}\n inputData={inputData}\n referenceData={referenceData}\n fieldType={schema.fieldType}\n disabled={disabled || (permission !== 'edit:full' && permission !== 'edit:rules')}\n onRemove={() => {\n tableActions.removeColumn('inputs', schema.id);\n }}\n onChange={(field, fieldType) => {\n tableActions.updateColumn('inputs', schema.id, { ...schema, field, fieldType });\n }}\n />\n </Stack>\n <Stack horizontal gap={2} verticalAlign={'center'} style={{ width: 'auto' }}>\n <DiffIcon status={schema?._diff?.status} style={{ fontSize: 16 }} />\n </Stack>\n </Stack>\n </div>\n );\n};\n\nexport const TableHeadCellOutputField: React.FC<TableHeadCellFieldProps> = ({ permission, disabled, schema }) => {\n const tableActions = useDecisionTableActions();\n\n return (\n <div className={clsx(['flex items-center h-full w-full min-h-0 box-border py-1 px-2'])}>\n <Stack horizontal horizontalAlign='space-between' verticalAlign={'center'}>\n <Stack gap={0} className='overflow-hidden' verticalAlign={'center'}>\n {schema?._diff?.fields?.name?.status === 'modified' && (\n <Typography.Text className={clsx(['truncate', 'grl-dt-text-primary', TEXT_REMOVED])}>\n {schema?._diff?.fields?.name?.previousValue}\n </Typography.Text>\n )}\n <TextEdit\n className={clsx(['truncate', 'grl-dt-text-primary'])}\n value={schema.name}\n onChange={(name) => {\n tableActions.updateColumn('outputs', schema.id, { ...schema, name });\n }}\n />\n {schema?._diff?.fields?.field?.status === 'modified' && (\n <Typography.Text\n className={clsx(['truncate', 'grl-dt-text-secondary', TEXT_REMOVED])}\n type='secondary'\n style={{ fontSize: 12 }}\n >\n {schema?._diff?.fields?.field?.previousValue}\n </Typography.Text>\n )}\n <OutputFieldEdit\n value={schema.field}\n fieldType={schema.outputFieldType}\n disabled={disabled || permission !== 'edit:full'}\n onRemove={() => {\n tableActions.removeColumn('outputs', schema.id);\n }}\n onChange={(field, outputFieldType) => {\n tableActions.updateColumn('outputs', schema.id, { ...schema, field, outputFieldType });\n }}\n />\n </Stack>\n <Stack\n horizontal\n gap={2}\n verticalAlign={'center'}\n style={{\n width: 'auto',\n }}\n >\n <DiffIcon\n status={schema?._diff?.status}\n style={{\n fontSize: 16,\n }}\n />\n </Stack>\n </Stack>\n </div>\n );\n};\n","import type { HeaderGroup } from '@tanstack/react-table';\nimport { flexRender } from '@tanstack/react-table';\nimport clsx from 'clsx';\nimport React from 'react';\nimport { match } from 'ts-pattern';\n\nexport const TableHeadRow: React.FC<{ headerGroup: HeaderGroup<any> }> = ({ headerGroup }) => (\n <tr key={headerGroup.id}>\n <th\n colSpan={1}\n style={{ width: 72 }}\n className='h-10 box-border text-left relative font-normal shadow-[inset_0_0_0_0.3px_var(--border)] [&_button]:text-[var(--muted-foreground)]'\n />\n {headerGroup.headers.map((header) => {\n const context = header.getContext();\n const parent = context.header.column.parent?.id;\n\n const parentKind = match(parent)\n .with('inputs', () => 'input')\n .with('outputs', () => 'output')\n .otherwise(() => undefined);\n\n const selfKind = match(context.column.id)\n .with('inputs', () => 'input')\n .with('outputs', () => 'output')\n .with('_description', () => 'description')\n .otherwise(() => undefined);\n\n return (\n <th\n key={header.id}\n colSpan={header.colSpan}\n data-self={selfKind}\n data-parent={parentKind}\n className={clsx(\n 'h-10 box-border text-left relative font-normal bg-[var(--table-color)] shadow-[inset_0_0_0_0.3px_var(--border)] [&_button]:text-[var(--muted-foreground)]',\n (selfKind === 'input' || selfKind === 'output') && 'text-black',\n )}\n style={\n selfKind !== 'description'\n ? {\n width: header.getSize(),\n }\n : {\n minWidth: header.getSize(),\n width: '100%',\n }\n }\n >\n {!header.isPlaceholder && flexRender(header.column.columnDef.header, context)}\n {header.column.getCanResize() && (\n <div\n className={clsx(\n 'absolute -right-[5px] top-0 z-[1] h-full w-[10px] cursor-col-resize select-none touch-none',\n \"after:content-[''] after:mx-auto after:block after:w-[3px] after:h-full after:rounded-[3px] after:transition-all after:duration-100 hover:after:bg-[var(--grl-color-primary-hover)]\",\n selfKind === 'description' && 'right-0! w-4!',\n header.column.getIsResizing() && 'isResizing',\n )}\n onMouseDown={header.getResizeHandler()}\n onTouchStart={header.getResizeHandler()}\n />\n )}\n </th>\n );\n })}\n </tr>\n);\n","type BoxLike = {\n top: number;\n height: number;\n};\n\nexport const getDropDirection = (\n activeBox: BoxLike | null | undefined,\n targetBox: DOMRect | null | undefined,\n): 'up' | 'down' => {\n if (!activeBox || !targetBox) {\n return 'up';\n }\n\n return activeBox.top + activeBox.height / 2 > targetBox.top + targetBox.height / 2 ? 'down' : 'up';\n};\n","import { useDndContext, useDraggable, useDroppable } from '@dnd-kit/core';\nimport type { Row } from '@tanstack/react-table';\nimport { flexRender } from '@tanstack/react-table';\nimport type { VirtualItem } from '@tanstack/react-virtual';\nimport clsx from 'clsx';\nimport React, { useEffect, useRef } from 'react';\nimport { P, match } from 'ts-pattern';\n\nimport { composeRefs } from '../../../helpers/compose-refs';\nimport { getDropDirection } from '../../../helpers/dnd';\nimport type { DiffMetadata } from '../../decision-graph';\nimport { Typography } from '../../primitives';\nimport { useDecisionTableActions, useDecisionTableState } from '../context/dt-store.context';\n\nexport const TableRow: React.FC<{\n ref?: React.Ref<HTMLTableRowElement>;\n row: Row<Record<string, string>>;\n disabled?: boolean;\n virtualItem: VirtualItem;\n onResize?: (node: HTMLElement) => void;\n}> = ({ ref, row, disabled, virtualItem, onResize }) => {\n const trRef = useRef<HTMLTableRowElement>(null);\n const tableActions = useDecisionTableActions();\n const { cursor, isActive } = useDecisionTableState(({ cursor, debug, debugIndex }) => ({\n cursor,\n isActive: match(debug?.trace.traceData)\n .with(P.array(), (t) => t?.[debugIndex]?.rule?._id === row.id)\n .otherwise((t) => t?.rule?._id === row.id),\n }));\n\n const {\n attributes,\n listeners,\n setNodeRef: setDragNodeRef,\n setActivatorNodeRef,\n isDragging,\n } = useDraggable({\n id: `dtrow-${row.id}`,\n data: { index: row.index },\n disabled: !!disabled,\n });\n\n const { setNodeRef: setDropNodeRef, isOver } = useDroppable({\n id: `dtrow-drop-${row.id}`,\n data: { index: row.index },\n });\n\n const dndContext = useDndContext();\n const direction = isOver\n ? getDropDirection(dndContext.active?.rect.current.translated, trRef.current?.getBoundingClientRect())\n : 'up';\n\n useEffect(() => {\n if (!trRef.current) {\n return;\n }\n\n onResize?.(trRef.current);\n const resizeObserver = new ResizeObserver((entries) => {\n entries.forEach((entry) => {\n if (!entry.target.hasAttribute('data-virtual-index')) {\n return;\n }\n // Skip 0-height measurements from display:none (tab hidden) to avoid\n // the virtualizer caching incorrect sizes and causing a layout jump on return.\n if (entry.contentRect.height === 0) {\n return;\n }\n\n onResize?.(entry.target as HTMLElement);\n });\n });\n\n resizeObserver.observe(trRef.current);\n return () => {\n resizeObserver.disconnect();\n };\n }, []);\n\n const diff = useDecisionTableState(({ decisionTable }) => {\n if (!decisionTable._diff) {\n return undefined;\n }\n\n return decisionTable.rules.find((r) => r._id === row.original._id)?._diff as DiffMetadata | undefined;\n });\n\n const diffStatus = diff?.status;\n\n return (\n <tr\n ref={composeRefs(\n trRef,\n ref,\n setDropNodeRef as React.Ref<HTMLTableRowElement>,\n setDragNodeRef as React.Ref<HTMLTableRowElement>,\n )}\n className={clsx(\n 'relative w-fit min-h-[36px]',\n \"after:content-[''] after:absolute after:left-0 after:right-0 after:bg-[var(--primary)]\",\n isOver && direction === 'down' && 'after:bottom-0 after:h-[2px]',\n isOver && direction === 'up' && 'after:top-0 after:h-[2px]',\n !diffStatus && isActive && 'bg-[var(--grl-color-success-bg)]',\n !diffStatus &&\n disabled &&\n 'bg-black/[0.02] [&_[contenteditable]]:bg-transparent [&_[contenteditable]]:text-[var(--muted-foreground)]',\n !diffStatus &&\n cursor?.y === virtualItem.index &&\n !disabled &&\n 'selected bg-[var(--grl-color-primary-bg-fade)] [&>td:first-of-type]:bg-[var(--grl-color-primary-bg-fade)]',\n diffStatus === 'added' && 'bg-[var(--grl-color-success-bg)]',\n diffStatus === 'removed' && 'bg-[var(--grl-color-error-bg)]',\n )}\n style={{\n opacity: isDragging ? 0.5 : 1,\n }}\n data-virtual-index={virtualItem.index}\n >\n <td\n className={clsx(\n 'py-[2px] px-[14px] shadow-[inset_0_0_0_0.3px_var(--border)] outline-[1.5px] outline-transparent -outline-offset-[1.5px]',\n diffStatus ? 'bg-transparent!' : 'bg-[var(--table-color)]!',\n !disabled && 'cursor-grab',\n )}\n ref={disabled ? undefined : setActivatorNodeRef}\n {...(disabled ? {} : listeners)}\n {...attributes}\n onContextMenuCapture={() => tableActions.setCursor({ x: 'id', y: virtualItem.index })}\n >\n <div className='w-full h-full flex items-start justify-end pt-[6px]'>\n <Typography>{virtualItem.index + 1}</Typography>\n </div>\n </td>\n {row.getVisibleCells().map((cell) => (\n <td\n key={cell.id}\n className={clsx(\n 'min-h-[36px] p-0 outline-[1.5px] outline-transparent -outline-offset-[1.5px] shadow-[inset_0_0_0_0.3px_var(--border)]',\n !disabled && cursor?.x === cell.column.id && cursor?.y === virtualItem.index && 'outline-[var(--border)]',\n diff?.fields?.[cell?.column?.id]?.status === 'modified' && 'bg-[var(--grl-color-warning-bg)]',\n diff?.fields?.[cell?.column?.id]?.status === 'added' && 'bg-[var(--grl-color-success-bg)]',\n diff?.fields?.[cell?.column?.id]?.status === 'removed' && 'bg-[var(--grl-color-error-bg)]',\n )}\n style={{ width: cell.column.getSize() }}\n >\n {flexRender(cell.column.columnDef.cell, cell.getContext())}\n </td>\n ))}\n </tr>\n );\n};\n","import { PlusCircleOutlined } from '#icons';\nimport type { ColumnDef, Table as ReactTable } from '@tanstack/react-table';\nimport { getCoreRowModel, useReactTable } from '@tanstack/react-table';\nimport { useVirtualizer } from '@tanstack/react-virtual';\nimport clsx from 'clsx';\nimport equal from 'fast-deep-equal/es6/react';\nimport React, { useCallback, useEffect, useRef, useState } from 'react';\nimport { z } from 'zod';\n\nimport { setRefValue } from '../../../helpers/compose-refs';\nimport { useThemeMode } from '../../../theme';\nimport { CellViewPoolProvider } from '../../code-editor/cell-view-pool';\nimport { Button, Typography } from '../../primitives';\nimport { useDecisionTableActions, useDecisionTableListeners, useDecisionTableState } from '../context/dt-store.context';\nimport { TableContextMenu } from './table-context-menu';\nimport { TableDefaultCell } from './table-default-cell';\nimport {\n TableHeadCellInput,\n TableHeadCellInputField,\n TableHeadCellOutput,\n TableHeadCellOutputField,\n} from './table-head-cell';\nimport { TableHeadRow } from './table-head-row';\nimport { TableRow } from './table-row';\n\nexport type TableScrollApi = {\n getTopRowIndex: () => number;\n scrollToRowIndex: (index: number) => void;\n};\n\nexport type TableProps = {\n id?: string;\n maxHeight: string | number;\n scrollContainerRef?: React.MutableRefObject<HTMLDivElement | null>;\n scrollApiRef?: React.MutableRefObject<TableScrollApi | null>;\n};\n\ntype ColumnSizing = Record<string, number>;\n\nconst columnSizeKey = (id: string) => `jdm-editor:decisionTable:columns:${id}`;\n\nconst loadColumnSizing = (id?: string) => {\n if (!id) {\n return {};\n }\n\n try {\n const sizeData = localStorage.getItem(columnSizeKey(id));\n const jsonData = JSON.parse(sizeData ?? '{}');\n return z.record(z.string(), z.number()).parse(jsonData);\n } catch {\n return {};\n }\n};\n\nexport const Table: React.FC<TableProps> = ({ id, maxHeight, scrollContainerRef, scrollApiRef }) => {\n const mode = useThemeMode();\n\n // Child→parent ref handoff happens inside the opaque setRefValue/composeRefs\n // helpers, so react-compiler sees no direct prop mutation here.\n const setContainerRef = useCallback(\n (el: HTMLDivElement | null) => {\n (tableContainerRef as React.MutableRefObject<HTMLDivElement | null>).current = el;\n setRefValue(scrollContainerRef, el);\n },\n [scrollContainerRef],\n );\n\n const tableActions = useDecisionTableActions();\n const { cellRenderer } = useDecisionTableListeners(({ cellRenderer }) => ({ cellRenderer }));\n const [columnSizing, setColumnSizing] = useState<ColumnSizing>(() => loadColumnSizing(id));\n\n const { permission, disabled, inputs, outputs, colWidth, minColWidth } = useDecisionTableState(\n ({ permission, disabled, minColWidth, colWidth, decisionTable }) => ({\n permission,\n disabled,\n minColWidth,\n colWidth,\n inputs: decisionTable.inputs,\n outputs: decisionTable.outputs,\n }),\n );\n\n const { rules } = useDecisionTableState(\n ({ decisionTable }) => ({\n rules: decisionTable.rules,\n }),\n (prev, curr) =>\n equal(\n prev.rules.map((i: any) => i?._id),\n curr.rules.map((i: any) => i?._id),\n ),\n );\n\n const columns = React.useMemo<ColumnDef<any>[]>(\n () => [\n {\n id: 'inputs',\n minSize: minColWidth,\n size: colWidth,\n enableResizing: true,\n header: () => <TableHeadCellInput permission={permission} disabled={disabled} />,\n columns: [\n ...(inputs || []).map((input: any) => {\n return {\n accessorKey: input.id,\n id: input.id,\n minSize: minColWidth,\n size: colWidth,\n header: () => <TableHeadCellInputField schema={input} permission={permission} disabled={disabled} />,\n };\n }),\n ],\n },\n {\n id: 'outputs',\n minSize: minColWidth,\n size: minColWidth,\n header: () => <TableHeadCellOutput disabled={disabled} permission={permission} />,\n columns: [\n ...(outputs || []).map((output: any) => {\n return {\n accessorKey: output.id,\n minSize: minColWidth,\n size: colWidth,\n header: () => <TableHeadCellOutputField schema={output} permission={permission} disabled={disabled} />,\n };\n }),\n ],\n },\n {\n id: '_description',\n accessorKey: '_description',\n header: () => (\n <div className='flex items-center h-full w-full min-h-0 box-border py-1 px-2'>\n <Typography.Text className='truncate grl-dt-text-primary'>Description</Typography.Text>\n </div>\n ),\n minSize: minColWidth,\n size: colWidth,\n },\n ],\n [permission, disabled, inputs, outputs],\n );\n\n const table = useReactTable({\n data: rules,\n columnResizeMode: 'onChange',\n getRowId: (row) => row._id,\n columns,\n getCoreRowModel: getCoreRowModel(),\n defaultColumn: {\n cell: (context) => <TableDefaultCell context={context} />,\n },\n meta: {\n getCell: cellRenderer,\n },\n ...(!id\n ? {}\n : {\n state: { columnSizing },\n onColumnSizingChange: setColumnSizing,\n }),\n });\n\n const tableContainerRef = useRef<HTMLDivElement>(null);\n\n useEffect(() => {\n const el = tableContainerRef.current;\n if (!el) return;\n\n let wasVisible = el.offsetWidth > 0;\n\n const resizeObserver = new ResizeObserver((entries) => {\n for (const entry of entries) {\n if (!(entry.target instanceof HTMLDivElement)) continue;\n entry.target.style.setProperty('--dt-container-width', `${entry.contentRect.width}px`);\n\n const isVisible = entry.contentRect.width > 0;\n if (!wasVisible && isVisible) {\n el.scrollTop = 0;\n el.style.opacity = '0';\n requestAnimationFrame(() => {\n requestAnimationFrame(() => {\n el.style.opacity = '';\n });\n });\n }\n wasVisible = isVisible;\n }\n });\n\n resizeObserver.observe(el);\n\n return () => {\n resizeObserver.disconnect();\n };\n }, []);\n\n useEffect(() => {\n if (!id) {\n return;\n }\n\n setColumnSizing(loadColumnSizing(id));\n }, [id]);\n\n useEffect(() => {\n if (!id) {\n return;\n }\n\n localStorage.setItem(columnSizeKey(id), JSON.stringify(columnSizing));\n }, [columnSizing]);\n\n return (\n <div\n ref={setContainerRef}\n className='relative flex-1 overflow-auto'\n style={{ maxHeight, overflowY: 'auto' }}\n data-theme={mode}\n >\n <StyledTable width={table.getCenterTotalSize()}>\n <thead className='bg-[var(--table-color)] border-[var(--border)] m-0 sticky top-0 z-10'>\n {table\n .getHeaderGroups()\n .filter((_, i) => i === 0)\n .map((headerGroup) => (\n <TableHeadRow key={headerGroup.id} headerGroup={headerGroup} />\n ))}\n </thead>\n </StyledTable>\n <StyledTable width={table.getCenterTotalSize()}>\n <thead className='bg-[var(--table-color)] border-[var(--border)] m-0 sticky top-0 z-10'>\n {table\n .getHeaderGroups()\n .filter((_, i) => i === 1)\n .map((headerGroup) => (\n <TableHeadRow key={headerGroup.id} headerGroup={headerGroup} />\n ))}\n </thead>\n <TableContextMenu>\n <TableBody tableContainerRef={tableContainerRef} table={table} scrollApiRef={scrollApiRef} />\n </TableContextMenu>\n <tfoot className='bg-[var(--card)]'>\n <tr>\n <td colSpan={inputs.length + outputs.length + 2}>\n <div className='p-2 sticky bottom-0'>\n <Button\n className='max-w-[var(--dt-container-width)] transition-[background-color]! duration-200 [transition-timing-function:cubic-bezier(0.645,0.045,0.355,1)]!'\n type='link'\n disabled={disabled}\n icon={<PlusCircleOutlined />}\n onClick={() => tableActions.addRowBelow()}\n >\n Add row\n </Button>\n </div>\n </td>\n </tr>\n </tfoot>\n </StyledTable>\n </div>\n );\n};\n\ntype TableBodyProps = {\n tableContainerRef: React.RefObject<HTMLDivElement | null>;\n table: ReactTable<any>;\n scrollApiRef?: React.MutableRefObject<TableScrollApi | null>;\n} & Omit<React.HTMLAttributes<HTMLTableSectionElement>, 'children'>;\n\nconst TableBody = React.forwardRef<HTMLTableSectionElement, TableBodyProps>(\n ({ table, tableContainerRef, scrollApiRef, ...props }, ref) => {\n const tableActions = useDecisionTableActions();\n const { disabled, cursor } = useDecisionTableState(({ disabled, cursor }) => ({\n disabled,\n cursor,\n }));\n\n const { rows } = table.getRowModel();\n const virtualizer = useVirtualizer({\n getScrollElement: () => tableContainerRef.current,\n estimateSize: () => 38,\n indexAttribute: 'data-virtual-index',\n count: rows.length,\n overscan: 5,\n });\n\n useEffect(() => {\n if (!scrollApiRef) return;\n setRefValue(scrollApiRef, {\n getTopRowIndex: () => {\n const offset = tableContainerRef.current?.scrollTop ?? 0;\n return virtualizer.getVirtualItemForOffset(offset)?.index ?? 0;\n },\n scrollToRowIndex: (index) => virtualizer.scrollToIndex(index, { align: 'start' }),\n });\n return () => {\n setRefValue(scrollApiRef, null);\n };\n }, [virtualizer, scrollApiRef]);\n\n const virtualItems = virtualizer.getVirtualItems();\n const totalSize = virtualizer.getTotalSize();\n\n const paddingTop = virtualItems.length > 0 ? virtualItems?.[0]?.start || 0 : 0;\n const paddingBottom = virtualItems.length > 0 ? totalSize - (virtualItems?.[virtualItems.length - 1]?.end || 0) : 0;\n\n const onKeyDown = useCallback((e: React.KeyboardEvent) => {\n if (disabled) {\n return;\n }\n\n if (e.code === 'ArrowUp' && (e.metaKey || e.altKey)) {\n if (cursor) tableActions.addRowAbove(cursor.y);\n }\n if (e.code === 'ArrowDown' && (e.metaKey || e.altKey)) {\n if (cursor) tableActions.addRowBelow(cursor.y);\n }\n if (e.code === 'Backspace' && (e.metaKey || e.altKey)) {\n if (cursor) tableActions.removeRow(cursor.y);\n }\n }, []);\n\n return (\n <tbody ref={ref} {...props} onKeyDown={onKeyDown}>\n {/* Display-view pool for the lazy highlighter-view path (roadmap §3.6):\n DOM-less provider, lives for the whole table, default cap 64. */}\n <CellViewPoolProvider>\n {paddingTop > 0 && (\n <tr>\n <td\n className='p-0 outline-[1.5px] outline-transparent -outline-offset-[1.5px] shadow-[inset_0_0_0_0.3px_var(--border)]'\n style={{ height: `${paddingTop}px` }}\n />\n </tr>\n )}\n {virtualItems.map((item) => {\n const row = rows[item.index];\n\n return (\n <TableRow\n key={item.key}\n virtualItem={item}\n row={row}\n disabled={disabled}\n onResize={virtualizer.measureElement}\n />\n );\n })}\n {paddingBottom > 0 && (\n <tr>\n <td\n className='p-0 outline-[1.5px] outline-transparent -outline-offset-[1.5px] shadow-[inset_0_0_0_0.3px_var(--border)]'\n style={{ height: `${paddingBottom}px` }}\n />\n </tr>\n )}\n </CellViewPoolProvider>\n </tbody>\n );\n },\n);\n\nconst StyledTable: React.FC<React.HTMLAttributes<HTMLTableElement> & { width: number }> = ({\n style,\n className,\n width,\n ...props\n}) => {\n return (\n <table\n className={clsx(\n 'border-collapse table-fixed [font-family:arial,sans-serif] w-fit bg-[var(--grl-color-bg-container)] h-px min-w-full',\n className,\n )}\n style={{ width, ...style }}\n {...props}\n />\n );\n};\n","import { DndContext, DragOverlay, PointerSensor, useSensor, useSensors } from '@dnd-kit/core';\nimport React, { useEffect, useRef, useState } from 'react';\n\nimport { DragOverlayCard, OverlayChip, OverlayIndexChip } from '../../helpers/dnd-overlay';\nimport { DictionaryProvider } from '../../theme';\nimport { SafeBoundary } from '../safe-boundary';\nimport { DecisionTableDialogProvider } from './context/dt-dialog.context';\nimport type { DecisionTableContextProps } from './context/dt-store.context';\nimport {\n DecisionTableProvider,\n useDecisionTableActions,\n useDecisionTableRaw,\n useDecisionTableState,\n} from './context/dt-store.context';\nimport { DecisionTableDialogs } from './dialog/dt-dialogs';\nimport { DecisionTableCommandBar } from './dt-command-bar';\nimport type { DecisionTableEmptyType } from './dt-empty';\nimport { DecisionTableEmpty } from './dt-empty';\nimport type { TableScrollApi } from './table/table';\nimport { Table } from './table/table';\n\nexport type { TableScrollApi } from './table/table';\n\nexport type DecisionTableProps = {\n id?: string;\n tableHeight: string | number;\n mountDialogsOnBody?: boolean;\n scrollContainerRef?: React.MutableRefObject<HTMLDivElement | null>;\n scrollApiRef?: React.MutableRefObject<TableScrollApi | null>;\n} & DecisionTableContextProps &\n DecisionTableEmptyType;\n\nexport const DecisionTable: React.FC<DecisionTableProps> = ({\n id,\n tableHeight,\n mountDialogsOnBody = false,\n scrollContainerRef,\n scrollApiRef,\n ...props\n}) => {\n const [_, setMounted] = useState(false);\n const ref = useRef<HTMLDivElement>(null);\n\n useEffect(() => {\n setMounted(true);\n }, []);\n\n const getContainer = () => ref.current as HTMLElement;\n\n return (\n <SafeBoundary>\n <div\n ref={ref}\n className='text-sm h-full flex min-h-px flex-col pr-1 [--table-color:var(--background)]'\n style={{ background: 'var(--card)' }}\n >\n {ref.current && (\n <DecisionTableProvider>\n <DecisionTableDnd>\n <DecisionTableDialogProvider getContainer={mountDialogsOnBody ? undefined : getContainer}>\n <DecisionTableCommandBar />\n <DictionaryBridge>\n <Table\n id={id}\n maxHeight={tableHeight}\n scrollContainerRef={scrollContainerRef}\n scrollApiRef={scrollApiRef}\n />\n </DictionaryBridge>\n <DecisionTableDialogs />\n <DecisionTableEmpty {...props} />\n </DecisionTableDialogProvider>\n </DecisionTableDnd>\n </DecisionTableProvider>\n )}\n </div>\n </SafeBoundary>\n );\n};\n\nconst DecisionTableDnd: React.FC<React.PropsWithChildren> = ({ children }) => {\n const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 4 } }));\n const actions = useDecisionTableActions();\n const { stateStore } = useDecisionTableRaw();\n const [activeRowIndex, setActiveRowIndex] = useState<number | null>(null);\n\n // Read the rule imperatively at render time instead of subscribing to the\n // whole rules list - a deep-equal subscription here would run on every\n // cell commit for zero benefit (overlay content is fixed during a drag).\n const activeRule = activeRowIndex == null ? undefined : stateStore.getState().decisionTable.rules[activeRowIndex];\n\n return (\n <DndContext\n sensors={sensors}\n onDragStart={({ active }) => {\n const index = active.data.current?.index;\n if (typeof index === 'number') {\n setActiveRowIndex(index);\n }\n }}\n onDragEnd={({ active, over }) => {\n setActiveRowIndex(null);\n if (!over) {\n return;\n }\n\n const from = active.data.current?.index;\n const to = over.data.current?.index;\n if (from === undefined || to === undefined || from === to) {\n return;\n }\n\n actions.swapRows(from, to);\n }}\n onDragCancel={() => setActiveRowIndex(null)}\n >\n {children}\n <DragOverlay dropAnimation={null}>\n {activeRule ? (\n <DragOverlayCard>\n <OverlayIndexChip index={activeRowIndex ?? 0} />\n {[\n ...(stateStore.getState().decisionTable.inputs || []),\n ...(stateStore.getState().decisionTable.outputs || []),\n ].map((schemaItem) => (\n <OverlayChip key={schemaItem.id} width={110}>\n {activeRule[schemaItem.id]}\n </OverlayChip>\n ))}\n {activeRule._description ? (\n <OverlayChip width={160}>\n <span style={{ color: 'var(--grl-color-text-tertiary)' }}>{activeRule._description}</span>\n </OverlayChip>\n ) : null}\n </DragOverlayCard>\n ) : null}\n </DragOverlay>\n </DndContext>\n );\n};\n\nconst DictionaryBridge: React.FC<React.PropsWithChildren> = ({ children }) => {\n const dictionaries = useDecisionTableState((s) => s.dictionaries) ?? {};\n return <DictionaryProvider value={dictionaries}>{children}</DictionaryProvider>;\n};\n","const unsecuredCopyToClipboard = (text: string) => {\n const textArea = document.createElement('textarea');\n textArea.value = text;\n document.body.appendChild(textArea);\n textArea.focus();\n textArea.select();\n try {\n document.execCommand('copy');\n } catch (err) {\n console.error('Unable to copy to clipboard', err);\n }\n document.body.removeChild(textArea);\n};\n\nexport const copyToClipboard = async (content: string) => {\n if (window.isSecureContext && navigator.clipboard) {\n await navigator.clipboard.writeText(content);\n } else {\n unsecuredCopyToClipboard(content);\n }\n};\n\nexport const pasteFromClipboard = async (): Promise<string> => {\n try {\n return navigator.clipboard.readText();\n } catch {\n return '';\n }\n};\n\nexport const get = <T>(obj: any, path: string, defaultValue: T): T => {\n return path.split('.').reduce((a, c) => (a && a[c] ? a[c] : defaultValue || null), obj) as T;\n};\n\nexport const smartSplit = (str: string): string[] => {\n if (!str || typeof str !== 'string') {\n return [''];\n }\n\n const regex = /;;(?=(?:[^\"'`]*[\"'`][^\"'`]*[\"'`])*[^\"'`]*$)/;\n return str.split(regex);\n};\n\nexport const toOperatorExprArray = (value: string | string[]): string[] => {\n if (Array.isArray(value)) {\n return value;\n }\n\n return smartSplit(value);\n};\n\nexport const toOperatorExprString = (value: string | string[]): string => {\n if (Array.isArray(value)) {\n return value.join(';;');\n }\n\n return value;\n};\n\nexport const toOperatorExprDisplay = (value: string | string[]): string => {\n if (Array.isArray(value)) {\n return JSON.stringify(value);\n }\n\n return value;\n};\n\nexport const parseOperatorExprInput = (text: string): string | string[] => {\n const trimmed = text.trim();\n if (trimmed.startsWith('[') && trimmed.endsWith(']')) {\n try {\n const parsed: unknown = JSON.parse(trimmed);\n if (Array.isArray(parsed) && parsed.every((item) => typeof item === 'string')) {\n return parsed;\n }\n } catch {\n // fall through\n }\n }\n\n return text.includes(';;') ? smartSplit(text) : text;\n};\n\nexport const normalizeOperatorExprValue = (value: unknown): unknown => {\n if (typeof value === 'string' && value.includes(';;')) {\n return smartSplit(value);\n }\n\n return value;\n};\n\nexport const normalizeCustomNodeExpressions = <T extends { type?: string }>(nodes: T[]): T[] =>\n nodes.map((node) => {\n if (node?.type !== 'customNode') {\n return node;\n }\n\n const content = (node as { content?: { config?: any } }).content;\n const config = content?.config;\n if (!config || !Array.isArray(config.expressions)) {\n return node;\n }\n\n return {\n ...node,\n content: {\n ...content,\n config: {\n ...config,\n expressions: config.expressions.map((expr: any) => ({\n ...expr,\n value: normalizeOperatorExprValue(expr?.value),\n })),\n expr_asts: Array.isArray(config.expr_asts)\n ? config.expr_asts.map((ast: any) => ({ ...ast, value: normalizeOperatorExprValue(ast?.value) }))\n : config.expr_asts,\n },\n },\n };\n });\n","import type { z } from 'zod';\n\nimport type { nodeSchema } from '../../helpers/schema';\n\nexport const privateSymbol = Symbol('private');\n\nexport type Position = {\n x: number;\n y: number;\n};\n\ntype NodeSchema = z.infer<typeof nodeSchema>;\n\nexport type DiffStatus = 'added' | 'removed' | 'modified' | 'unchanged' | 'moved';\n\nexport type Diff<T = any> = {\n _diff?: DiffMetadata<T>;\n};\n\nexport type DiffMetadata<T = any> = {\n status?: DiffStatus;\n previousValue?: T;\n previousIndex?: number;\n currentIndex?: number;\n fields?: Record<string, DiffMetadata>;\n};\n\nexport type DecisionNode<T = any> = {\n id: string;\n name: string;\n description?: string;\n type?: NodeSchema['type'] | string;\n content?: T;\n position: Position;\n [privateSymbol]?: {\n dimensions?: { height?: number; width?: number };\n selected?: boolean;\n };\n _diff?: {\n status: DiffStatus;\n fields?: Record<string, DiffMetadata>;\n };\n};\n\nexport type DecisionEdge = {\n id: string;\n name?: string;\n sourceId: string;\n targetId: string;\n sourceHandle?: string | null;\n targetHandle?: string | null;\n type?: string;\n _diff?: {\n status: DiffStatus;\n };\n};\n\nexport type DecisionGraphType = {\n nodes: DecisionNode[];\n edges: DecisionEdge[];\n};\n\nexport type UserResolver = () => Promise<{\n user?: string;\n}> | null;\n","import type { Edge, Node } from '@xyflow/react';\nimport { MarkerType } from '@xyflow/react';\n\nimport type { DecisionEdge, DecisionNode } from './dg-types';\nimport { privateSymbol } from './dg-types';\n\nexport const mapToDecisionEdge = (edge: Edge): DecisionEdge => {\n return {\n id: edge?.id,\n sourceId: edge?.source,\n type: edge?.type,\n targetId: edge?.target,\n name: edge?.label as string,\n sourceHandle: edge.sourceHandle ?? undefined,\n targetHandle: edge.targetHandle ?? undefined,\n };\n};\n\nexport const mapToGraphNode = (node: DecisionNode): Node => {\n return {\n id: node.id,\n type: node.type,\n position: node.position,\n height: node[privateSymbol]?.dimensions?.height,\n width: node[privateSymbol]?.dimensions?.width,\n selected: node[privateSymbol]?.selected,\n data: {\n name: node.name,\n kind: node?.content?.kind,\n },\n };\n};\nexport const mapToGraphNodes = (nodes: DecisionNode[]): Node[] => {\n return nodes.map(mapToGraphNode);\n};\n\nexport const mapToGraphEdge = (edge: DecisionEdge): Edge => {\n return {\n id: edge.id,\n source: edge.sourceId,\n type: edge?.type || 'edge',\n target: edge.targetId,\n label: edge.name,\n sourceHandle: edge.sourceHandle,\n targetHandle: edge.targetHandle,\n markerEnd: { type: MarkerType.ArrowClosed, width: 20, height: 20 },\n };\n};\n\nexport const mapToGraphEdges = (edges: DecisionEdge[]): Edge[] => {\n return edges.filter((edge) => edge.sourceId && edge.targetId).map(mapToGraphEdge);\n};\n","import { type VariableType } from '@gorules/zen-engine-wasm';\nimport type { NodeProps } from '@xyflow/react';\nimport type React from 'react';\n\nimport type { DecisionNode } from '../../dg-types';\nimport type { DecisionNodeProps } from '../decision-node';\n\nexport enum NodeKind {\n Input = 'inputNode',\n Output = 'outputNode',\n DecisionTable = 'decisionTableNode',\n Function = 'functionNode',\n Expression = 'expressionNode',\n Switch = 'switchNode',\n}\n\nexport type MinimalNodeProps = Pick<NodeProps, 'id' | 'selected'> & { data: any };\nexport type MinimalNodeSpecification = Pick<\n NodeSpecification,\n 'color' | 'icon' | 'displayName' | 'documentationUrl' | 'helper' | 'renderSettings'\n>;\n\ntype GenerateNodeParams = {\n index: number;\n};\n\nexport type InferTypeData<T> = {\n input: VariableType;\n content: T;\n};\n\nexport type NodeSpecification<T = any> = {\n icon?: React.ReactNode;\n type: string;\n color?: DecisionNodeProps['color'];\n group?: string;\n displayName: string | React.ReactNode;\n documentationUrl?: string;\n shortDescription?: string;\n helper?: string | React.ReactNode;\n renderTab?: (props: { id: string; user?: string; customFunctions?: any }) => React.ReactNode;\n getDiffContent?: (current: T, previous: T) => T;\n generateNode: (params: GenerateNodeParams) => Omit<DecisionNode<T>, 'position' | 'id' | 'type'>;\n renderNode: React.FC<MinimalNodeProps & { specification: MinimalNodeSpecification }>;\n renderSettings?: React.FC<{ id: string }>;\n inferTypes?: {\n needsUpdate: (content: T, prevContent: T) => boolean;\n determineOutputType: (state: InferTypeData<T>) => VariableType;\n };\n\n onNodeAdd?: (node: DecisionNode<T>) => Promise<DecisionNode<T>>;\n};\n","import type { DecisionGraphStoreType } from './dg-store.context';\n\ntype StateSlice = Partial<Pick<DecisionGraphStoreType['state'], 'openTabs' | 'activeTab'>>;\n\n/** Tab id reserved for the graph canvas itself. */\nexport const GRAPH_TAB_ID = 'graph';\n\n/**\n * Resolve the state patch for activating a tab: 'graph' always activates;\n * an already-open tab just becomes active; otherwise it is appended and\n * activated.\n */\nexport const applyOpenTab = (openTabs: string[], id: string): StateSlice => {\n if (id === GRAPH_TAB_ID) {\n return { activeTab: GRAPH_TAB_ID };\n }\n\n if (openTabs.includes(id)) {\n return { activeTab: id };\n }\n\n return { openTabs: [...openTabs, id], activeTab: id };\n};\n\n/**\n * Resolve the state patch for closing a tab. Supported actions mirror the\n * context menu: close (single), close-all, close-other, close-right,\n * close-left. When the previously active tab no longer exists after the\n * operation, activation falls back to the tab left of the closed position\n * (verbatim legacy behaviour, including its index-based quirk) or to\n * 'graph'.\n */\nexport const applyCloseTab = (openTabs: string[], activeTab: string, id: string, action?: string): StateSlice => {\n const index = openTabs?.findIndex((i) => i === id);\n const tab = openTabs?.[index];\n\n const updatedTabs = matchAction(openTabs, action, tab, index);\n\n const updatedState: StateSlice = {\n openTabs: updatedTabs,\n };\n\n const newActiveTabId = updatedTabs?.find((i) => i === activeTab);\n if (!newActiveTabId) {\n updatedState.activeTab = updatedTabs?.[index - 1] ?? 'graph';\n }\n\n return updatedState;\n};\n\nconst matchAction = (\n openTabs: string[],\n action: string | undefined,\n tab: string | undefined,\n index: number,\n): string[] => {\n switch (action) {\n case undefined:\n case 'close':\n return openTabs.filter((openId) => openId !== tab);\n case 'close-all':\n return [];\n case 'close-other':\n return openTabs.filter((openId) => openId === tab);\n case 'close-right':\n return openTabs.slice(0, index + 1);\n case 'close-left':\n return openTabs.slice(index);\n default:\n return openTabs;\n }\n};\n","/**\n * Undo/redo stack for decision graph editing (S009-A).\n *\n * Snapshot approach: each `push` captures the pre-mutation graph; `undo` and\n * `redo` move the pointer between past and future. Text-edit debouncing is\n * handled by the caller (merge rapid updates into one push).\n */\nexport function createUndoRedoStack<T>(maxSize = 100) {\n let past: T[] = [];\n let future: T[] = [];\n\n return {\n /** Push a pre-mutation snapshot; clears the redo stack */\n push(state: T): void {\n past.push(state);\n if (past.length > maxSize) past.shift();\n future = [];\n },\n undo(current: T): T | null {\n const prev = past.pop();\n if (prev === undefined) return null;\n future.push(current);\n return prev;\n },\n redo(current: T): T | null {\n const next = future.pop();\n if (next === undefined) return null;\n past.push(current);\n return next;\n },\n get canUndo(): boolean {\n return past.length > 0;\n },\n get canRedo(): boolean {\n return future.length > 0;\n },\n clear(): void {\n past = [];\n future = [];\n },\n };\n}\n","import { type VariableType } from '@gorules/zen-engine-wasm';\nimport type { Monaco } from '@monaco-editor/react';\nimport type { EdgeChange, NodeChange, ReactFlowInstance, useEdgesState, useNodesState } from '@xyflow/react';\nimport equal from 'fast-deep-equal/es6/react';\nimport type { WritableDraft } from 'immer';\nimport { produce } from 'immer';\nimport React, { type MutableRefObject, createRef, useMemo, useRef } from 'react';\nimport { match } from 'ts-pattern';\nimport type { StoreApi, UseBoundStore } from 'zustand';\nimport { create, useStore } from 'zustand';\n\nimport { useMemoEquality } from '../../../helpers/use-memoized-selector';\nimport { normalizeCustomNodeExpressions } from '../../../helpers/utility';\nimport type { DictionaryMap } from '../../../theme';\nimport type { CodeEditorProps } from '../../code-editor';\nimport type { JdmUiMode } from '../../decision-table/context/dt-store.context';\nimport type { DecisionEdge, DecisionGraphType, DecisionNode } from '../dg-types';\nimport { privateSymbol } from '../dg-types';\nimport { mapToGraphEdge, mapToGraphEdges, mapToGraphNode, mapToGraphNodes } from '../dg-util';\nimport type { useGraphClipboard } from '../hooks/use-graph-clipboard';\nimport type { CustomNodeSpecification } from '../nodes/custom-node';\nimport { NodeKind, type NodeSpecification } from '../nodes/specifications/specification-types';\nimport type { Simulation } from '../simulator/simulation.types';\nimport { applyCloseTab, applyOpenTab } from './dg-tab-strategy';\nimport { createUndoRedoStack } from './undo-redo';\n\nexport type PanelType = {\n id: string;\n icon: React.ReactNode;\n title: string;\n renderPanel?: () => React.ReactNode;\n hideHeader?: boolean;\n onClick?: () => void;\n};\n\ntype DraftUpdateCallback<T> = (draft: WritableDraft<T>) => WritableDraft<T>;\n\nexport type ViewConfigPermission = 'edit:values' | 'edit:rules' | 'edit:full';\n\nexport type ViewConfig = {\n enabled: boolean;\n description?: string;\n permissions?: Record<string, ViewConfigPermission | null | undefined> | null;\n};\n\nexport enum NodeTypeKind {\n Input,\n Output,\n InferredInput,\n InferredOutput,\n}\n\nexport type SetDecisionGraphOptions = {\n skipOnChangeEvent?: boolean;\n};\n\nexport type SimulatorExampleBinding = {\n nodeId: string;\n sourceIndex: number;\n sourceName?: string;\n} | null;\n\nexport type DecisionGraphStoreType = {\n state: {\n id?: string;\n hideLeftToolbar?: boolean;\n components: NodeSpecification[];\n disabled?: boolean;\n decisionGraph: DecisionGraphType;\n hoveredEdgeId: string | null;\n openTabs: string[];\n activeTab: string;\n\n viewConfigCta?: string;\n viewConfig?: ViewConfig;\n\n name: string;\n\n canUndo: boolean;\n canRedo: boolean;\n\n customNodes: CustomNodeSpecification<object, any>[];\n\n panels?: PanelType[];\n activePanel?: string;\n onPanelsChange?: (val?: string) => void;\n\n simulate?: Simulation;\n\n user: string;\n\n simulatorRequest?: string;\n simulatorExampleBinding?: SimulatorExampleBinding;\n\n compactMode?: boolean;\n\n dictionaries?: DictionaryMap;\n mode?: JdmUiMode;\n\n nodeTypes: Record<string, Partial<Record<NodeTypeKind, VariableType>>>;\n globalType: Record<string, VariableType>;\n };\n\n references: {\n nodesState: MutableRefObject<ReturnType<typeof useNodesState>>;\n edgesState: MutableRefObject<ReturnType<typeof useEdgesState>>;\n reactFlowInstance: MutableRefObject<ReactFlowInstance | null>;\n graphClipboard: MutableRefObject<ReturnType<typeof useGraphClipboard>>;\n };\n\n actions: {\n setDecisionGraph: (val: Partial<DecisionGraphType>, options?: SetDecisionGraphOptions) => void;\n\n undo: () => void;\n redo: () => void;\n commitUndo: () => void;\n\n handleNodesChange: (nodesChange: NodeChange[]) => void;\n handleEdgesChange: (edgesChange: EdgeChange[]) => void;\n\n setNodes: (nodes: DecisionNode[]) => void;\n addNodes: (nodes: DecisionNode[]) => void;\n updateNode: (id: string, updater: DraftUpdateCallback<DecisionNode>) => void;\n removeNodes: (ids: string[]) => void;\n\n duplicateNodes: (ids: string[]) => void;\n copyNodes: (ids: string[]) => void;\n pasteNodes: () => void;\n\n setEdges: (edges: DecisionEdge[]) => void;\n addEdges: (edge: DecisionEdge[]) => void;\n removeEdges: (ids: string[]) => void;\n removeEdgeByHandleId: (handleId: string) => void;\n setHoveredEdgeId: (edgeId: string | null) => void;\n\n closeTab: (id: string, action?: string) => void;\n openTab: (id: string) => void;\n goToNode: (id: string) => void;\n\n setActivePanel: (panel?: string) => void;\n\n setCompactMode: (mode: boolean) => void;\n toggleCompactMode: () => void;\n\n setNodeType: (id: string, kind: NodeTypeKind, vt: VariableType) => void;\n removeNodeType: (id: string, kind?: NodeTypeKind) => void;\n\n setSimulatorRequest: (req: string) => void;\n setSimulatorExampleBinding: (binding?: SimulatorExampleBinding) => void;\n\n triggerNodeSelect: (id: string, mode: 'toggle' | 'only') => void;\n };\n\n listeners: {\n onChange?: (val: DecisionGraphType) => void;\n onPanelsChange?: (val?: string) => void;\n onReactFlowInit?: (instance: ReactFlowInstance) => void;\n onCodeExtension?: CodeEditorProps['extension'];\n onFunctionReady?: (monaco: Monaco) => void;\n onViewConfigCta?: () => void;\n };\n};\n\nexport type ExposedStore<T> = UseBoundStore<StoreApi<T>> & {\n setState: (partial: Partial<T>) => void;\n};\n\n// Empty-object default is safe: consumers only render inside\n// DecisionGraphProvider, which supplies the real stores on mount.\nexport const DecisionGraphStoreContext = React.createContext<{\n stateStore: ExposedStore<DecisionGraphStoreType['state']>;\n listenerStore: ExposedStore<DecisionGraphStoreType['listeners']>;\n referenceStore: ExposedStore<DecisionGraphStoreType['references']>;\n actions: DecisionGraphStoreType['actions'];\n}>(\n // Double-cast is intentional: consumers only render inside\n // DecisionGraphProvider, which supplies the real stores on mount.\n {} as unknown as {\n stateStore: ExposedStore<DecisionGraphStoreType['state']>;\n listenerStore: ExposedStore<DecisionGraphStoreType['listeners']>;\n referenceStore: ExposedStore<DecisionGraphStoreType['references']>;\n actions: DecisionGraphStoreType['actions'];\n },\n);\n\nexport type DecisionGraphContextProps = {\n //\n};\n\nexport const DecisionGraphProvider: React.FC<React.PropsWithChildren<DecisionGraphContextProps>> = (props) => {\n const { children } = props;\n\n const stateStore = useMemo(\n () =>\n create<DecisionGraphStoreType['state']>()(() => ({\n id: undefined,\n simulate: undefined,\n decisionGraph: { nodes: [], edges: [] },\n hoveredEdgeId: null,\n openTabs: [],\n activeTab: 'graph',\n name: 'graph.json',\n disabled: false,\n components: [],\n customNodes: [],\n activePanel: undefined,\n panels: [],\n user: '',\n compactMode: localStorage.getItem('jdm-compact-mode') === 'true',\n nodeTypes: {},\n globalType: {},\n canUndo: false,\n canRedo: false,\n })),\n [],\n );\n\n const undoRedoStack = useMemo(() => createUndoRedoStack<DecisionGraphType>(100), []);\n\n // updateNode 防抖:500ms 内同一节点的连续编辑合并为一步\n const editDebounceRef = useRef<{ nodeId: string | null; timer: ReturnType<typeof setTimeout> | null }>({\n nodeId: null,\n timer: null,\n });\n\n // 节点拖拽会话追踪:首次 position 变更时 pushUndo(捕获拖拽前位置)\n const dragSessionRef = useRef(false);\n\n const listenerStore = useMemo(\n () =>\n create<DecisionGraphStoreType['listeners']>(() => ({\n onChange: undefined,\n onPanelsChange: undefined,\n })),\n [],\n );\n\n const referenceStore = useMemo(\n () =>\n create<DecisionGraphStoreType['references']>(() => ({\n nodesState: createRef() as MutableRefObject<ReturnType<typeof useNodesState>>,\n edgesState: createRef() as MutableRefObject<ReturnType<typeof useEdgesState>>,\n graphClipboard: createRef() as MutableRefObject<ReturnType<typeof useGraphClipboard>>,\n reactFlowInstance: createRef() as MutableRefObject<ReactFlowInstance | null>,\n })),\n [],\n );\n\n const actions = useMemo<DecisionGraphStoreType['actions']>(() => {\n const pushUndo = () => {\n const { decisionGraph } = stateStore.getState();\n undoRedoStack.push(JSON.parse(JSON.stringify(decisionGraph)));\n stateStore.setState({ canUndo: undoRedoStack.canUndo, canRedo: undoRedoStack.canRedo });\n };\n\n return {\n undo: () => {\n const current = stateStore.getState().decisionGraph;\n const prev = undoRedoStack.undo(current);\n if (prev === null) return;\n stateStore.setState({ decisionGraph: prev, canUndo: undoRedoStack.canUndo, canRedo: undoRedoStack.canRedo });\n listenerStore.getState().onChange?.(prev);\n },\n redo: () => {\n const current = stateStore.getState().decisionGraph;\n const next = undoRedoStack.redo(current);\n if (next === null) return;\n stateStore.setState({ decisionGraph: next, canUndo: undoRedoStack.canUndo, canRedo: undoRedoStack.canRedo });\n listenerStore.getState().onChange?.(next);\n },\n commitUndo: () => {\n pushUndo();\n },\n handleNodesChange: (changes = []) => {\n const { nodesState } = referenceStore.getState();\n const { decisionGraph } = stateStore.getState();\n\n // 拖拽会话追踪:首次拖拽 position 变更时 pushUndo(捕获拖拽前位置)\n const positionChanges = changes.filter((c): c is NodeChange & { type: 'position' } => c.type === 'position');\n if (positionChanges.length > 0) {\n const isDragStart = positionChanges.some((c) => 'dragging' in c && c.dragging === true);\n const isDragEnd = positionChanges.some((c) => 'dragging' in c && c.dragging === false);\n if (isDragStart && !dragSessionRef.current) {\n pushUndo();\n dragSessionRef.current = true;\n }\n if (isDragEnd) {\n dragSessionRef.current = false;\n }\n }\n\n const [, , onNodesChange] = nodesState.current;\n\n let hasChanges = false;\n\n onNodesChange?.(changes);\n const newDecisionGraph = produce(decisionGraph, (draft) => {\n changes.forEach((c) =>\n match(c)\n .with({ type: 'position' }, (p) => {\n const node = draft.nodes.find((n) => n.id === p.id);\n if (node && p.position && !equal(node.position, p.position)) {\n hasChanges = true;\n node.position = p.position;\n }\n })\n .with({ type: 'dimensions' }, (d) => {\n const node = draft.nodes.find((n) => n.id === d.id);\n if (node && !equal(node[privateSymbol]?.dimensions, d.dimensions)) {\n hasChanges = true;\n node[privateSymbol] ??= {};\n node[privateSymbol].dimensions = { height: d.dimensions?.height, width: d.dimensions?.width };\n }\n })\n .with({ type: 'select' }, (s) => {\n const node = draft.nodes.find((n) => n.id === s.id);\n\n if (node && node[privateSymbol]?.selected !== s.selected) {\n hasChanges = true;\n node[privateSymbol] ??= {};\n node[privateSymbol].selected = s.selected;\n }\n })\n .otherwise(() => {\n // No-op\n }),\n );\n });\n\n if (!hasChanges) {\n return;\n }\n\n stateStore.setState({ decisionGraph: newDecisionGraph });\n listenerStore.getState().onChange?.(newDecisionGraph);\n },\n handleEdgesChange: (changes = []) => {\n const { decisionGraph } = stateStore.getState();\n const { edgesState } = referenceStore.getState();\n\n const hasStructuralChange = changes.some((c) => c.type === 'remove' || c.type === 'add');\n if (hasStructuralChange) pushUndo();\n\n edgesState?.current?.[2](changes);\n if (changes.find((c) => c.type === 'remove')) {\n const newDecisionGraph = produce(decisionGraph, (draft) => {\n const edges = (draft.edges || [])\n .map((edge) => {\n const change = changes.find((change) => 'id' in change && change.id === edge.id);\n if (change?.type === 'remove') {\n return null;\n }\n return edge;\n })\n .filter((node) => !!node) as DecisionEdge[];\n draft.edges = edges;\n });\n\n stateStore.setState({ decisionGraph: newDecisionGraph });\n listenerStore.getState().onChange?.(newDecisionGraph);\n }\n },\n setNodes: (nodes: DecisionNode[] = []) => {\n const { nodesState } = referenceStore.getState();\n const { decisionGraph } = stateStore.getState();\n nodesState?.current?.[1](mapToGraphNodes(nodes));\n\n const newDecisionGraph = produce(decisionGraph, (draft) => {\n draft.nodes = nodes;\n });\n\n stateStore.setState({ decisionGraph: newDecisionGraph });\n listenerStore.getState().onChange?.(newDecisionGraph);\n },\n addNodes: (nodes: DecisionNode[]) => {\n const { nodesState } = referenceStore.getState();\n const { decisionGraph } = stateStore.getState();\n pushUndo();\n\n const hasInput = nodesState.current[0]?.some((n) => n.type === NodeKind.Input);\n if (hasInput) {\n nodes = nodes.filter((n) => n.type !== NodeKind.Input);\n }\n\n nodesState.current[1]?.((n) => n.concat(mapToGraphNodes(nodes)));\n const newDecisionGraph = produce(decisionGraph, (draft) => {\n draft.nodes = (draft.nodes || []).concat(nodes);\n });\n\n stateStore.setState({ decisionGraph: newDecisionGraph });\n listenerStore.getState().onChange?.(newDecisionGraph);\n },\n duplicateNodes: (ids) => {\n const { nodesState, edgesState } = referenceStore.getState();\n const { decisionGraph } = stateStore.getState();\n pushUndo();\n\n let nodes = (decisionGraph?.nodes || []).filter((n) => ids.includes(n.id));\n\n const hasInput = nodesState.current[0]?.some((n) => n.type === NodeKind.Input);\n if (hasInput) {\n nodes = nodes.filter((n) => n.type !== NodeKind.Input);\n }\n\n if (nodes.length === 0) {\n return;\n }\n\n const nodeIds: Record<string, string> = nodes.reduce(\n (acc, curr) => ({\n ...acc,\n [curr.id]: crypto.randomUUID(),\n }),\n {},\n );\n\n const newNodes = nodes.map<DecisionNode>((node) => ({\n ...node,\n id: nodeIds[node.id],\n position: {\n x: node.position?.x || 0,\n y: (node.position?.y || 0) + 140,\n },\n }));\n\n const oldNodeIds = Object.keys(nodeIds);\n const newEdges: DecisionEdge[] = [];\n\n if (newNodes.length > 0) {\n (edgesState.current?.[0] || []).forEach((edge) => {\n if (oldNodeIds.includes(edge.source) && oldNodeIds.includes(edge.target)) {\n newEdges.push({\n id: crypto.randomUUID(),\n type: edge.type,\n sourceId: nodeIds[edge.source],\n targetId: nodeIds[edge.target],\n sourceHandle: edge.sourceHandle ?? undefined,\n targetHandle: edge.targetHandle ?? undefined,\n });\n }\n });\n }\n\n nodesState.current[1]?.((n) => n.concat(newNodes.map(mapToGraphNode)));\n edgesState.current[1]?.((e) => e.concat(newEdges.map(mapToGraphEdge)));\n const newDecisionGraph = produce(decisionGraph, (draft) => {\n draft.nodes.push(...newNodes);\n draft.edges.push(...newEdges);\n });\n\n stateStore.setState({ decisionGraph: newDecisionGraph });\n listenerStore.getState().onChange?.(newDecisionGraph);\n },\n copyNodes: (ids) => {\n const { graphClipboard, nodesState } = referenceStore.getState();\n if (!graphClipboard.current || !nodesState.current) {\n return;\n }\n\n const [nodes] = nodesState.current;\n const copyNodes = nodes.filter((n) => ids.includes(n.id));\n\n graphClipboard.current.copyNodes(copyNodes);\n },\n pasteNodes: () => {\n const { graphClipboard } = referenceStore.getState();\n graphClipboard.current?.pasteNodes?.();\n },\n removeNodes: (ids = []) => {\n const { nodesState, edgesState } = referenceStore.getState();\n const { decisionGraph, nodeTypes } = stateStore.getState();\n pushUndo();\n\n nodesState.current[1]?.((nodes) => nodes.filter((n) => ids.every((id) => n.id !== id)));\n edgesState.current[1]?.((edges) =>\n edges.filter((e) =>\n ids.every((id) => e.source !== id && e.target !== id && e.sourceHandle !== id && e.targetHandle !== id),\n ),\n );\n\n const newDecisionGraph = produce(decisionGraph, (draft) => {\n const nodes = draft.nodes || [];\n const edges = draft.edges || [];\n draft.nodes = nodes.filter((n) => ids.every((id) => n.id !== id));\n draft.edges = edges.filter((e) =>\n ids.every((id) => e.sourceId !== id && e.targetId !== id && e.sourceHandle !== id && e.targetHandle !== id),\n );\n });\n\n const newNodeTypes = produce(nodeTypes, (draft) => {\n ids.forEach((id) => {\n if (id in draft) {\n delete draft[id];\n }\n });\n });\n\n stateStore.setState({ decisionGraph: newDecisionGraph, nodeTypes: newNodeTypes });\n listenerStore.getState().onChange?.(newDecisionGraph);\n },\n addEdges: (edges: DecisionEdge[]) => {\n const { edgesState } = referenceStore.getState();\n const { decisionGraph } = stateStore.getState();\n\n edgesState.current?.[1]?.((els) => els.concat(edges.map(mapToGraphEdge)));\n const newDecisionGraph = produce(decisionGraph, (draft) => {\n draft.edges = (draft.edges || []).concat(edges);\n });\n\n stateStore.setState({ decisionGraph: newDecisionGraph });\n listenerStore.getState().onChange?.(newDecisionGraph);\n },\n setEdges: (edges = []) => {\n const { edgesState } = referenceStore.getState();\n const { decisionGraph } = stateStore.getState();\n\n edgesState?.current?.[1]?.(mapToGraphEdges(edges));\n const newDecisionGraph = produce(decisionGraph, (draft) => {\n draft.edges = edges;\n });\n\n stateStore.setState({ decisionGraph: newDecisionGraph });\n listenerStore.getState().onChange?.(newDecisionGraph);\n },\n removeEdges: (ids) => {\n const { edgesState } = referenceStore.getState();\n const { decisionGraph } = stateStore.getState();\n\n edgesState?.current?.[1]?.((edges) => edges.filter((e) => !ids.find((id) => e.id === id)));\n const newDecisionGraph = produce(decisionGraph, (draft) => {\n draft.edges = draft.edges.filter((e) => !ids.find((id) => e.id === id));\n });\n\n stateStore.setState({ decisionGraph: newDecisionGraph });\n listenerStore.getState().onChange?.(newDecisionGraph);\n },\n removeEdgeByHandleId: (handleId: string) => {\n if (!handleId) return;\n const { edgesState } = referenceStore.getState();\n const { decisionGraph } = stateStore.getState();\n edgesState?.current?.[1]?.((edges) => edges.filter((e) => e.sourceHandle !== handleId));\n const newDecisionGraph = produce(decisionGraph, (draft) => {\n draft.edges = draft.edges.filter((e) => e.sourceHandle !== handleId);\n });\n\n stateStore.setState({ decisionGraph: newDecisionGraph });\n listenerStore.getState().onChange?.(newDecisionGraph);\n },\n updateNode: (id, updater) => {\n // Debounced undo: first edit of a session captures pre-edit state;\n // rapid consecutive edits on the same node merge into one undo step\n const isContinuation = editDebounceRef.current.nodeId === id && editDebounceRef.current.timer !== null;\n if (!isContinuation) {\n pushUndo();\n }\n if (editDebounceRef.current.timer) clearTimeout(editDebounceRef.current.timer);\n editDebounceRef.current.nodeId = id;\n editDebounceRef.current.timer = setTimeout(() => {\n editDebounceRef.current.nodeId = null;\n editDebounceRef.current.timer = null;\n }, 500);\n\n const { decisionGraph } = stateStore.getState();\n const { nodesState } = referenceStore.getState();\n const [nodes, setNodes] = nodesState.current;\n\n const newDecisionGraph = produce(decisionGraph, (draft) => {\n const node = (draft.nodes ?? []).find((node) => node?.id === id);\n if (!node) {\n return;\n }\n\n updater(node);\n });\n\n const changedNode = newDecisionGraph.nodes.find((n) => n.id === id);\n if (!changedNode) {\n return;\n }\n\n const graphChangedNode = mapToGraphNode(changedNode as DecisionNode);\n const existingGraphNode = nodes.find((n) => n.id === id);\n if (!equal(graphChangedNode, existingGraphNode)) {\n setNodes((nodes) => nodes.map((n) => (n.id === id ? graphChangedNode : n)));\n }\n\n stateStore.setState({ decisionGraph: newDecisionGraph });\n listenerStore.getState().onChange?.(newDecisionGraph);\n },\n setDecisionGraph: (graph, options = {}) => {\n const { decisionGraph } = stateStore.getState();\n const { edgesState, nodesState } = referenceStore.getState();\n const { skipOnChangeEvent = false } = options;\n\n const newDecisionGraph = produce(decisionGraph, (draft) => {\n Object.assign(draft, graph);\n if (draft.nodes) {\n draft.nodes = normalizeCustomNodeExpressions(draft.nodes);\n }\n });\n\n edgesState?.current?.[1](mapToGraphEdges(newDecisionGraph?.edges ?? []));\n nodesState?.current?.[1](mapToGraphNodes(newDecisionGraph?.nodes ?? []));\n stateStore.setState({\n decisionGraph: newDecisionGraph,\n });\n if (!skipOnChangeEvent) {\n listenerStore.getState().onChange?.(newDecisionGraph);\n }\n },\n setHoveredEdgeId: (edgeId) => stateStore.setState({ hoveredEdgeId: edgeId }),\n goToNode: (id: string) => {\n if (stateStore.getState().activeTab !== 'graph') {\n return;\n }\n\n const { reactFlowInstance } = referenceStore.getState();\n if (!reactFlowInstance.current) {\n return;\n }\n\n const node = reactFlowInstance.current.getNode(id);\n if (!node) {\n return;\n }\n\n reactFlowInstance.current.fitView({ nodes: [node], duration: 1_000, maxZoom: 1.25 });\n },\n openTab: (id: string) => {\n const { openTabs } = stateStore.getState();\n stateStore.setState(applyOpenTab(openTabs, id));\n },\n closeTab: (id: string, action?: string) => {\n const { openTabs, activeTab } = stateStore.getState();\n stateStore.setState(applyCloseTab(openTabs, activeTab, id, action));\n },\n setActivePanel: (panel?: string) => {\n const { panels } = stateStore.getState();\n const updatedState: Partial<DecisionGraphStoreType['state']> = {\n activePanel: panel === undefined ? undefined : (panels || []).find((p) => p.id === panel)?.id,\n };\n listenerStore.getState()?.onPanelsChange?.(panel);\n stateStore.setState(updatedState);\n },\n setCompactMode: (mode: boolean) => {\n const updatedState: Partial<DecisionGraphStoreType['state']> = {\n compactMode: mode,\n };\n localStorage.setItem('jdm-compact-mode', `${mode}`);\n stateStore.setState(updatedState);\n },\n toggleCompactMode: () => {\n const { compactMode } = stateStore.getState();\n const mode = !compactMode;\n const updatedState: Partial<DecisionGraphStoreType['state']> = {\n compactMode: mode,\n };\n localStorage.setItem('jdm-compact-mode', `${mode}`);\n stateStore.setState(updatedState);\n },\n setNodeType: (id, kind, vt) => {\n const { nodeTypes } = stateStore.getState();\n\n const newNodeTypes = produce(nodeTypes, (draft) => {\n draft[id] ??= {};\n draft[id][kind] = vt;\n });\n\n stateStore.setState({ nodeTypes: newNodeTypes });\n },\n setSimulatorRequest: (req) => {\n stateStore.setState({ simulatorRequest: req });\n },\n setSimulatorExampleBinding: (binding) => {\n stateStore.setState({ simulatorExampleBinding: binding });\n },\n removeNodeType: (id, kind) => {\n const { nodeTypes } = stateStore.getState();\n\n const newNodeTypes = produce(nodeTypes, (draft) => {\n if (!(id in draft)) {\n return;\n }\n\n if (kind) {\n if (kind in draft[id]) {\n delete draft[id][kind];\n }\n } else {\n delete draft[id];\n }\n });\n\n stateStore.setState({ nodeTypes: newNodeTypes });\n },\n triggerNodeSelect: (id, mode) => {\n const { decisionGraph } = stateStore.getState();\n const { nodesState, edgesState } = referenceStore.getState();\n const [, setNodes] = nodesState.current;\n const [, setEdges] = edgesState.current;\n\n const newDecisionGraph = produce(decisionGraph, (draft) => {\n const chosenNode = draft.nodes.find((n) => n.id === id);\n if (!chosenNode) {\n return;\n }\n\n if (mode === 'only') {\n draft.nodes.forEach((n) => {\n if (n[privateSymbol]) {\n n[privateSymbol].selected = false;\n }\n });\n }\n\n chosenNode[privateSymbol] ??= {};\n chosenNode[privateSymbol].selected = match(mode)\n .with('only', () => true)\n .otherwise(() => !chosenNode[privateSymbol]?.selected);\n });\n\n setNodes(mapToGraphNodes(newDecisionGraph.nodes));\n if (mode == 'only') {\n setEdges((edges) =>\n edges.map((e) => ({\n ...e,\n selected: false,\n })),\n );\n }\n stateStore.setState({ decisionGraph: newDecisionGraph });\n listenerStore.getState().onChange?.(newDecisionGraph);\n },\n };\n }, []);\n\n const value = useMemo(\n () => ({\n stateStore,\n referenceStore,\n listenerStore,\n actions,\n }),\n [stateStore, referenceStore, listenerStore, actions],\n );\n\n return <DecisionGraphStoreContext.Provider value={value}>{children}</DecisionGraphStoreContext.Provider>;\n};\n\nexport function useDecisionGraphState<T>(\n selector: (state: DecisionGraphStoreType['state']) => T,\n equals: (a: any, b: any) => boolean = equal,\n): T {\n return useStore(React.useContext(DecisionGraphStoreContext).stateStore, useMemoEquality(selector, equals));\n}\n\nexport function useDecisionGraphListeners<T>(\n selector: (state: DecisionGraphStoreType['listeners']) => T,\n equals: (a: any, b: any) => boolean = equal,\n): T {\n return useStore(React.useContext(DecisionGraphStoreContext).listenerStore, useMemoEquality(selector, equals));\n}\n\nexport function useDecisionGraphReferences<T>(\n selector: (state: DecisionGraphStoreType['references']) => T,\n equals: (a: any, b: any) => boolean = equal,\n): T {\n return useStore(React.useContext(DecisionGraphStoreContext).referenceStore, useMemoEquality(selector, equals));\n}\n\nexport function useDecisionGraphActions(): DecisionGraphStoreType['actions'] {\n return React.useContext(DecisionGraphStoreContext).actions;\n}\n\nexport function useDecisionGraphRaw() {\n return React.useContext(DecisionGraphStoreContext);\n}\n\nexport const useNodeDiff = (id: string) => {\n const { diff, contentDiff } = useDecisionGraphState((s) => {\n const node = (s?.decisionGraph?.nodes ?? []).find((node) => node.id === id);\n\n return {\n diff: node?._diff,\n contentDiff: node?.content?._diff,\n };\n });\n return {\n diff,\n contentDiff,\n };\n};\n\nexport const useEdgeDiff = (id: string) => {\n const { diff } = useDecisionGraphState((s) => {\n const edge = (s?.decisionGraph?.edges ?? []).find((edge) => edge.id === id);\n\n return {\n diff: edge?._diff,\n };\n });\n return {\n diff,\n };\n};\n\nexport default DecisionGraphProvider;\n","import React, { createContext, useContext, useEffect, useMemo, useRef } from 'react';\n\nexport type Slice<T = unknown> = {\n serialize: () => T;\n restore: (state: T) => void;\n};\n\nexport type TabSnapshot = Record<string, unknown>;\n\nexport type DecisionGraphSnapshot = {\n graph?: Record<string, unknown>;\n tabs?: Record<string, TabSnapshot>;\n};\n\ntype Registry = {\n registerGraph: (key: string, slice: Slice) => () => void;\n registerTab: (tabId: string, key: string, slice: Slice) => () => void;\n serialize: () => DecisionGraphSnapshot;\n restore: (snapshot: DecisionGraphSnapshot) => void;\n};\n\nconst SerializerContext = createContext<Registry | null>(null);\n\nexport const SerializerProvider: React.FC<React.PropsWithChildren> = ({ children }) => {\n const graphSlices = useRef(new Map<string, Slice>());\n const tabSlices = useRef(new Map<string, Map<string, Slice>>());\n const pendingGraph = useRef(new Map<string, unknown>());\n const pendingTabs = useRef(new Map<string, Map<string, unknown>>());\n\n const registry = useMemo<Registry>(() => {\n const tryRestore = (slice: Slice, value: unknown, label: string) => {\n try {\n slice.restore(value);\n } catch (err) {\n console.warn(`Failed to restore \"${label}\"`, err);\n }\n };\n\n return {\n registerGraph: (key, slice) => {\n graphSlices.current.set(key, slice);\n if (pendingGraph.current.has(key)) {\n const pending = pendingGraph.current.get(key);\n pendingGraph.current.delete(key);\n tryRestore(slice, pending, `graph.${key}`);\n }\n return () => {\n if (graphSlices.current.get(key) === slice) graphSlices.current.delete(key);\n };\n },\n registerTab: (tabId, key, slice) => {\n if (!tabSlices.current.has(tabId)) tabSlices.current.set(tabId, new Map());\n tabSlices.current.get(tabId)!.set(key, slice);\n\n const pendingForTab = pendingTabs.current.get(tabId);\n if (pendingForTab?.has(key)) {\n const pending = pendingForTab.get(key);\n pendingForTab.delete(key);\n if (pendingForTab.size === 0) pendingTabs.current.delete(tabId);\n tryRestore(slice, pending, `tabs.${tabId}.${key}`);\n }\n return () => {\n const bag = tabSlices.current.get(tabId);\n if (bag?.get(key) === slice) {\n bag.delete(key);\n if (bag.size === 0) tabSlices.current.delete(tabId);\n }\n };\n },\n serialize: () => {\n const snapshot: DecisionGraphSnapshot = {};\n const graph: Record<string, unknown> = {};\n for (const [key, slice] of graphSlices.current) {\n try {\n const value = slice.serialize();\n if (value !== undefined) graph[key] = value;\n } catch (err) {\n console.warn(`Failed to serialize graph.${key}`, err);\n }\n }\n if (Object.keys(graph).length > 0) snapshot.graph = graph;\n\n const tabs: Record<string, TabSnapshot> = {};\n for (const [tabId, bag] of tabSlices.current) {\n const tabBag: TabSnapshot = {};\n for (const [key, slice] of bag) {\n try {\n const value = slice.serialize();\n if (value !== undefined) tabBag[key] = value;\n } catch (err) {\n console.warn(`Failed to serialize tabs.${tabId}.${key}`, err);\n }\n }\n if (Object.keys(tabBag).length > 0) tabs[tabId] = tabBag;\n }\n if (Object.keys(tabs).length > 0) snapshot.tabs = tabs;\n\n return snapshot;\n },\n restore: (snapshot) => {\n pendingGraph.current.clear();\n pendingTabs.current.clear();\n\n for (const [key, value] of Object.entries(snapshot?.graph ?? {})) {\n const slice = graphSlices.current.get(key);\n if (slice) tryRestore(slice, value, `graph.${key}`);\n else pendingGraph.current.set(key, value);\n }\n\n for (const [tabId, bag] of Object.entries(snapshot?.tabs ?? {})) {\n for (const [key, value] of Object.entries(bag ?? {})) {\n const slice = tabSlices.current.get(tabId)?.get(key);\n if (slice) {\n tryRestore(slice, value, `tabs.${tabId}.${key}`);\n } else {\n if (!pendingTabs.current.has(tabId)) pendingTabs.current.set(tabId, new Map());\n pendingTabs.current.get(tabId)!.set(key, value);\n }\n }\n }\n },\n };\n }, []);\n\n return <SerializerContext.Provider value={registry}>{children}</SerializerContext.Provider>;\n};\n\nexport const useSerializerRegistry = (): Registry | null => useContext(SerializerContext);\n\nfunction useSlice<T>(\n registerFn: ((slice: Slice) => () => void) | null,\n slice: Slice<T>,\n deps: React.DependencyList,\n): void {\n const sliceRef = useRef(slice);\n sliceRef.current = slice;\n\n useEffect(() => {\n if (!registerFn) return;\n return registerFn({\n serialize: () => sliceRef.current.serialize(),\n restore: (state) => sliceRef.current.restore(state as T),\n });\n }, deps);\n}\n\nexport function useGraphSerializer<T = unknown>(\n key: string | null | undefined,\n slice: Slice<T>,\n deps: React.DependencyList = [],\n): void {\n const registry = useContext(SerializerContext);\n const registerFn = registry && key ? (s: Slice) => registry.registerGraph(key, s) : null;\n useSlice(registerFn, slice, [registry, key, ...deps]);\n}\n\nexport function useTabSerializer<T = unknown>(\n tabId: string | null | undefined,\n key: string | null | undefined,\n slice: Slice<T>,\n deps: React.DependencyList = [],\n): void {\n const registry = useContext(SerializerContext);\n const registerFn = registry && tabId && key ? (s: Slice) => registry.registerTab(tabId, key, s) : null;\n useSlice(registerFn, slice, [registry, tabId, key, ...deps]);\n}\n","import { VariableType } from '@gorules/zen-engine-wasm';\nimport { useMemo } from 'react';\n\nimport {\n type DecisionGraphStoreType,\n NodeTypeKind,\n useDecisionGraphState,\n} from '../components/decision-graph/context/dg-store.context';\nimport { isWasmAvailable } from './wasm';\n\ntype NodeTypeParams = {\n attachGlobals?: boolean;\n disabled?: boolean;\n};\n\nconst getNodeType = (nodeTypes: DecisionGraphStoreType['state']['nodeTypes'], id: string) =>\n nodeTypes[id]?.[NodeTypeKind.Input] ??\n nodeTypes[id]?.[NodeTypeKind.InferredInput] ??\n VariableType.fromJson({ Object: {} });\n\nexport const useNodeType = (id: string, { attachGlobals = true, disabled = false }: NodeTypeParams = {}) => {\n const typeInfo = useDecisionGraphState(({ nodeTypes, globalType }) => {\n if (!isWasmAvailable() || disabled) {\n return undefined;\n }\n\n return { nodeTypes, globalType };\n });\n\n return useMemo(() => {\n if (!typeInfo?.nodeTypes) {\n return undefined;\n }\n\n const nodeType = getNodeType(typeInfo.nodeTypes, id);\n if (!attachGlobals) {\n return nodeType;\n }\n\n Object.entries(typeInfo?.globalType ?? {}).forEach(([k, v]) => nodeType.set(k, v));\n return nodeType;\n }, [typeInfo?.globalType, typeInfo?.nodeTypes, attachGlobals]);\n};\n","import type { DiffMetadata } from '../dg-types';\n\nexport const addStrikethrough = (text?: string): string => {\n if (!text) return '';\n const strikethroughChar = '\\u0336';\n return Array.from(text)\n .map((char) => char + strikethroughChar)\n .join('');\n};\n\nexport const buildDiffString = (currentValue: string, previousValue: string): string => {\n return [addStrikethrough(previousValue), '->', currentValue].join(' ');\n};\n\nexport const compareStringFields = (field1?: string | null, field2?: string | null): boolean => {\n const value1 = (field1 ?? '').trim();\n const value2 = (field2 ?? '').trim();\n\n return value1 === value2;\n};\n\ntype UnifiedItem<T> = T & {\n originalIndex: number;\n isRemoved?: boolean;\n};\n\ninterface BaseItem {\n id?: string;\n _id?: string;\n\n [key: string]: any;\n}\n\ninterface DiffOptions<T extends BaseItem> {\n idField?: 'id' | '_id';\n compareFields?: (\n current: T,\n previous: T,\n ) => {\n hasChanges: boolean;\n fields?: Record<string, DiffMetadata>;\n };\n}\n\nexport const compareAndUnifyLists = <T extends BaseItem>(\n newList: T[],\n oldList: T[],\n options: DiffOptions<T> = {},\n): T[] => {\n const { idField = 'id', compareFields } = options;\n\n const getId = (item: T) => item[idField] || item['_id'];\n\n const oldMap = new Map(oldList.map((item, index) => [getId(item), { ...item, index }]));\n const newMap = new Map(newList.map((item, index) => [getId(item), { ...item, index }]));\n\n const unifiedList: UnifiedItem<T>[] = [];\n\n const insertions = new Set<number>();\n const removals = new Set<number>();\n\n newList.forEach((item, index) => {\n if (!oldMap.has(getId(item))) {\n insertions.add(index);\n }\n });\n\n oldList.forEach((item, index) => {\n if (!newMap.has(getId(item))) {\n removals.add(index);\n }\n });\n\n const isRealPositionChange = (oldIndex: number, newIndex: number): boolean => {\n const insertionsBefore = Array.from(insertions).filter((i) => i < newIndex).length;\n const removalsBefore = Array.from(removals).filter((i) => i < oldIndex).length;\n\n const adjustedNewIndex = newIndex - insertionsBefore;\n const adjustedOldIndex = oldIndex - removalsBefore;\n\n return adjustedOldIndex !== adjustedNewIndex;\n };\n\n newList.forEach((item, newIndex) => {\n const oldItem = oldMap.get(getId(item));\n\n if (!oldItem) {\n unifiedList.push({\n ...item,\n originalIndex: newIndex,\n _diff: {\n status: 'added',\n newIndex,\n },\n });\n } else {\n const isPositionChanged = isRealPositionChange(oldItem.index, newIndex);\n const changes = compareFields ? compareFields(item, oldItem) : { hasChanges: false };\n\n if (changes.hasChanges || isPositionChanged) {\n unifiedList.push({\n ...item,\n originalIndex: newIndex,\n _diff: {\n status: 'modified',\n positionChanged: isPositionChanged,\n previousIndex: oldItem.index,\n newIndex,\n ...(changes.fields ? { fields: changes.fields } : {}),\n },\n });\n } else {\n unifiedList.push({\n ...item,\n originalIndex: newIndex,\n _diff: {\n status: 'unchanged',\n },\n });\n }\n }\n });\n\n oldList.forEach((item, oldIndex) => {\n if (!newMap.has(getId(item))) {\n let insertIndex = oldIndex;\n // @ts-expect-error error should not happen here\n while (insertIndex < unifiedList.length && oldMap.get(getId(unifiedList[insertIndex]))?.index < oldIndex) {\n insertIndex++;\n }\n\n unifiedList.splice(insertIndex, 0, {\n ...item,\n originalIndex: oldIndex,\n isRemoved: true,\n _diff: {\n status: 'removed',\n previousIndex: oldIndex,\n },\n });\n }\n });\n\n // Clean up utility properties before returning\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n return unifiedList.map(({ originalIndex, isRemoved, ...item }) => item as unknown as T);\n};\n","import type { DecisionGraphType, SimulationTrace } from '../components';\n\ntype NodeDataParams = {\n trace: Record<string, SimulationTrace>;\n decisionGraph: DecisionGraphType;\n};\n\nexport type GetNodeDataResult = { data: unknown; $nodes: unknown; $?: unknown };\n\nexport const getNodeData = (nodeId: string, { trace, decisionGraph }: NodeDataParams): GetNodeDataResult => {\n const data = Object.values(trace).find((t) => t.id === nodeId)?.input;\n const $nodes = Object.fromEntries(\n Object.values(trace)\n .map((t) => {\n const node = decisionGraph.nodes.find((n) => n.id === t.id);\n if (!node || node.type === 'outputNode') {\n return null;\n }\n\n return [t.name, t.output];\n })\n .filter((s) => !!s),\n );\n\n return { data, $nodes };\n};\n","import React, { useMemo, useRef } from 'react';\nimport { P, match } from 'ts-pattern';\n\nimport { getNodeData } from '../../../helpers/node-data';\nimport { get } from '../../../helpers/utility';\nimport { isWasmAvailable } from '../../../helpers/wasm';\nimport type { DecisionTableType, TableScrollApi } from '../../decision-table';\nimport { DecisionTable } from '../../decision-table';\nimport type { DecisionTablePermission } from '../../decision-table/context/dt-store.context';\nimport { useDecisionGraphActions, useDecisionGraphState } from '../context/dg-store.context';\nimport { useTabSerializer } from '../context/serializer.context';\nimport type { NodeDecisionTableData } from '../nodes/specifications/decision-table.specification';\nimport type { SimulationTrace, SimulationTraceDataTable } from '../simulator/simulation.types';\n\ntype TableScrollSnapshot = { rowIndex: number; scrollLeft: number };\n\nexport type TabDecisionTableProps = {\n id: string;\n};\n\nexport const TabDecisionTable: React.FC<TabDecisionTableProps> = ({ id }) => {\n const graphActions = useDecisionGraphActions();\n const scrollContainerRef = useRef<HTMLDivElement | null>(null);\n const scrollApiRef = useRef<TableScrollApi | null>(null);\n\n useTabSerializer<TableScrollSnapshot>(id, 'scroll', {\n serialize: () => ({\n rowIndex: scrollApiRef.current?.getTopRowIndex() ?? 0,\n scrollLeft: scrollContainerRef.current?.scrollLeft ?? 0,\n }),\n restore: (snapshot) => {\n if (!snapshot) return;\n let attempts = 0;\n const apply = () => {\n const api = scrollApiRef.current;\n const el = scrollContainerRef.current;\n if (!api || !el || el.scrollHeight <= el.clientHeight) {\n if (attempts++ < 60) requestAnimationFrame(apply);\n return;\n }\n api.scrollToRowIndex(snapshot.rowIndex);\n el.scrollLeft = snapshot.scrollLeft;\n };\n requestAnimationFrame(apply);\n },\n });\n const { nodeName, nodeTrace, inputData, nodeSnapshot, viewConfig, dictionaries, mode } = useDecisionGraphState(\n ({ simulate, decisionGraph, viewConfig, dictionaries, mode }) => ({\n nodeName: decisionGraph.nodes.find((n) => n.id === id)?.name,\n nodeTrace: match(simulate)\n .with({ result: P.nonNullable }, ({ result }) => result.trace[id] as SimulationTrace<SimulationTraceDataTable>)\n .otherwise(() => null),\n inputData: match(simulate)\n .with({ result: P.nonNullable }, ({ result }) => getNodeData(id, { trace: result.trace, decisionGraph }))\n .otherwise(() => null),\n nodeSnapshot: match(simulate)\n .with(\n { result: P.nonNullable },\n ({ result }) => (result.snapshot?.nodes || []).find((n) => n.id === id)?.content as DecisionTableType,\n )\n .otherwise(() => null),\n viewConfig,\n dictionaries,\n mode,\n }),\n );\n\n const { disabled, content } = useDecisionGraphState(({ disabled, decisionGraph }) => ({\n disabled,\n content: (decisionGraph?.nodes ?? []).find((node) => node.id === id)?.content as NodeDecisionTableData,\n }));\n\n const debug = useMemo(() => {\n if (!nodeTrace || !inputData || !nodeSnapshot) {\n return undefined;\n }\n\n if (!isWasmAvailable()) {\n return { trace: nodeTrace, snapshot: nodeSnapshot };\n }\n\n const extendedInputData = { ...inputData };\n if (content?.inputField) {\n extendedInputData.data = get(extendedInputData.data, content.inputField, {});\n }\n\n return { trace: nodeTrace, inputData: extendedInputData, snapshot: nodeSnapshot };\n }, [nodeTrace, nodeSnapshot, inputData]);\n\n return (\n <DecisionTable\n id={id}\n name={nodeName}\n tableHeight={'100%'}\n value={content as DecisionTableType}\n scrollContainerRef={scrollContainerRef}\n scrollApiRef={scrollApiRef}\n disabled={disabled}\n permission={viewConfig?.enabled ? (viewConfig?.permissions?.[id] as DecisionTablePermission) : 'edit:full'}\n dictionaries={dictionaries}\n mode={mode}\n debug={debug}\n onChange={(val) => {\n graphActions.updateNode(id, (draft) => {\n Object.assign(draft.content, val);\n return draft;\n });\n }}\n />\n );\n};\n","const isMac = navigator.platform.includes('Mac');\n\nconst keyMaps: Record<string, string> = {\n Ctrl: '⌘',\n Backspace: '⌫',\n Alt: '⌥',\n};\n\nexport const platform = {\n shortcut: (s: string): string => {\n if (!isMac) return s;\n\n return Object.keys(keyMaps).reduce((acc, key) => acc.replaceAll(key, keyMaps[key]), s);\n },\n};\n","import type { Dispatch, SetStateAction } from 'react';\nimport { useEffect, useState } from 'react';\n\nconst memoryCache: Record<string, unknown> = {};\n\nexport const usePersistentState = <S>(\n key: string,\n defaultValue?: S,\n): [S | undefined, Dispatch<SetStateAction<S | undefined>>] => {\n const [state, setState] = useState(() => (memoryCache?.[key] as S) ?? defaultValue);\n\n useEffect(() => {\n memoryCache[key] = state;\n }, [state]);\n\n return [state, setState];\n};\n","import { cn } from '#lib/utils';\nimport { mergeProps } from '@base-ui/react/merge-props';\nimport { useRender } from '@base-ui/react/use-render';\nimport { type VariantProps, cva } from 'class-variance-authority';\n\n// 本地化裁剪版(reui/badge 上游含 20+ 扩展色变体;kernel 主题无 info/success 等\n// 扩展 token,且 tailwind 会把 cva 字面量类全量产出——裁到 kernel 实际使用的变体,\n// 保住 style.css 预算。需要新变体时从 appshell 的 reui/badge.tsx 拷贝单个变体。)\nconst badgeVariants = cva(\n [\n 'relative inline-flex shrink-0 items-center justify-center w-fit border border-transparent font-medium whitespace-nowrap outline-none transition-shadow',\n 'focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background disabled:pointer-events-none disabled:opacity-50',\n '[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*=size-])]:size-3',\n ],\n {\n variants: {\n variant: {\n default: 'bg-primary text-primary-foreground',\n outline: 'border-border bg-transparent dark:bg-input/32',\n secondary: 'bg-secondary text-secondary-foreground',\n destructive: 'bg-destructive text-white',\n },\n size: {\n xs: 'px-1 py-0.25 text-[0.6rem] leading-none h-4 min-w-4 gap-1',\n sm: 'px-1 py-0.25 text-[0.625rem] leading-none h-4.5 min-w-4.5 gap-1',\n default: 'px-1.25 py-0.5 text-xs h-5 min-w-5 gap-1',\n lg: 'px-1.5 py-0.5 text-xs h-5.5 min-w-5.5 gap-1',\n xl: 'px-2 py-0.75 text-sm h-6 min-w-6 gap-1.5',\n },\n /** `default`: active style radius. `full`: pill radius. */\n radius: {\n default: 'rounded-sm',\n full: 'rounded-full',\n },\n },\n defaultVariants: {\n variant: 'default',\n size: 'default',\n radius: 'default',\n },\n },\n);\n\ninterface BadgeProps extends useRender.ComponentProps<'span'> {\n variant?: VariantProps<typeof badgeVariants>['variant'];\n size?: VariantProps<typeof badgeVariants>['size'];\n radius?: VariantProps<typeof badgeVariants>['radius'];\n}\n\nfunction Badge({ className, variant, size, radius, render, ...props }: BadgeProps) {\n const defaultProps = {\n 'data-slot': 'badge',\n 'className': cn(badgeVariants({ variant, size, radius, className })),\n };\n\n return useRender({\n defaultTagName: 'span',\n render,\n props: mergeProps<'span'>(defaultProps, props),\n });\n}\n\nexport { Badge, badgeVariants, type BadgeProps };\n","// Title: Icon Tile\n// Description: Square container that gives icons a consistent surface\nimport { cn } from '#lib/utils';\nimport { mergeProps } from '@base-ui/react/merge-props';\nimport { useRender } from '@base-ui/react/use-render';\nimport { type VariantProps, cva } from 'class-variance-authority';\n\n/**\n * CSS variable architecture:\n *\n * The root owns four variables so every part of the tile stays in proportion\n * and stays overridable from a single `className`:\n *\n * --icon-tile-size tile width/height\n * --icon-tile-icon-size glyph size applied to child svgs\n * --icon-tile-radius corner radius (also drives the nested inner card)\n * --icon-tile-inset gap between the outer ring and the inner card\n *\n * The `frame` and `soft` variants paint their inner card with an `::after`\n * pseudo element instead of a wrapper node. `isolate` makes the root a stacking\n * context, so the negative z-index pseudo paints above the root background but\n * below the in-flow icon - no extra DOM, and `render` composition keeps working.\n *\n * Tone: `soft` and `solid` derive every fill and border from `currentColor`, so\n * a single text color class (e.g. `text-success`) retints the whole tile. They\n * default to `text-primary`; override it to recolor without touching internals.\n */\nconst iconTileVariants = cva(\n [\n 'relative inline-flex shrink-0 items-center justify-center align-middle',\n 'size-(--icon-tile-size) rounded-(--icon-tile-radius)',\n '[&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*=size-])]:size-(--icon-tile-icon-size)',\n ],\n {\n variants: {\n variant: {\n /** Plain bordered surface. The quiet default for list rows and toolbars. */\n outline: 'border border-border bg-background dark:bg-input/32',\n /**\n * Tinted double container: an opacity-filled outer ring with no border\n * around a bordered inner card, all derived from `currentColor`. The\n * quiet, colorful sibling of `frame`. Retint with a text color class.\n */\n soft: [\n 'isolate p-(--icon-tile-inset) text-primary bg-current/10',\n 'after:absolute after:-z-10 after:inset-(--icon-tile-inset)',\n 'after:rounded-[calc(var(--icon-tile-radius)-var(--icon-tile-inset))]',\n 'after:border after:border-current/20 after:bg-current/5',\n ],\n /** Filled tone with a contrasting glyph. Retint with `bg-*` + a text color. */\n solid: 'bg-primary text-primary-foreground',\n },\n size: {\n xs: '[--icon-tile-size:--spacing(6)] [--icon-tile-icon-size:--spacing(3.5)] [--icon-tile-inset:--spacing(0.5)]',\n sm: '[--icon-tile-size:--spacing(8)] [--icon-tile-icon-size:--spacing(4)] [--icon-tile-inset:--spacing(0.5)]',\n default:\n '[--icon-tile-size:--spacing(10)] [--icon-tile-icon-size:--spacing(4.5)] [--icon-tile-inset:--spacing(0.75)]',\n },\n /**\n * `default`: active style radius. `full`: circular.\n * The plain value is the fallback outside a style scope; the `style-*`\n * tokens win by specificity inside one, and survive the registry\n * transform as the single resolved value per generated style.\n *\n * Each style token is clamped to a fraction of the tile. A flat radius\n * is a circle once it reaches half the box, so the soft styles used to\n * render `xs` (24px) and `sm` (32px) as plain circles and swallow the\n * `full` variant's meaning. Clamping keeps one corner ratio at every\n * size instead, so a tile still reads as the same shape when it scales.\n * Luma and Rhea take the gentler quarter ratio; Maia stays at a third.\n */\n radius: {\n default:\n '[--icon-tile-radius:min(var(--radius-md),calc(var(--icon-tile-size)/3))] [--icon-tile-radius:min(var(--radius-md),calc(var(--icon-tile-size)/3))]',\n full: '[--icon-tile-radius:calc(infinity*1px)]',\n },\n },\n defaultVariants: {\n variant: 'outline',\n size: 'default',\n radius: 'default',\n },\n },\n);\n\ninterface IconTileProps extends useRender.ComponentProps<'span'> {\n variant?: VariantProps<typeof iconTileVariants>['variant'];\n size?: VariantProps<typeof iconTileVariants>['size'];\n radius?: VariantProps<typeof iconTileVariants>['radius'];\n}\n\nfunction IconTile({\n className,\n variant = 'outline',\n size = 'default',\n radius = 'default',\n render,\n ...props\n}: IconTileProps) {\n const defaultProps = {\n 'data-slot': 'icon-tile',\n 'data-variant': variant,\n 'data-size': size,\n 'className': cn(iconTileVariants({ variant, size, radius, className })),\n };\n\n return useRender({\n defaultTagName: 'span',\n render,\n props: mergeProps<'span'>(defaultProps, props),\n });\n}\n\nexport { IconTile, iconTileVariants, type IconTileProps };\n","import { cn } from '#lib/utils';\nimport React from 'react';\n\nexport type GraphCardProps = React.HTMLAttributes<HTMLDivElement>;\n\nexport const GraphCard: React.FC<GraphCardProps> = ({ className, ...props }) => {\n return (\n <div\n className={cn(\n 'relative flex flex-col border border-[var(--border)] bg-[var(--node-background)]',\n 'cursor-grab rounded-[var(--node-border-radius)] [transition:var(--grl-transition)]',\n 'group-hover/dn:border-[var(--grl-color-border-hover)]',\n className,\n )}\n {...props}\n />\n );\n};\n","export enum NodeColor {\n Blue = 'var(--node-color-blue)',\n Purple = 'var(--node-color-purple)',\n Orange = 'var(--node-color-orange)',\n Green = 'var(--node-color-green)',\n}\n","import { CloseOutlined, MoreOutlined } from '#icons';\nimport { Badge } from '#reui/badge';\nimport { IconTile } from '#reui/icon-tile';\nimport clsx from 'clsx';\nimport React, { useEffect, useState } from 'react';\nimport { match } from 'ts-pattern';\n\nimport { DiffIcon } from '../../diff-icon';\nimport { Button, Dropdown, type MenuProps, Typography } from '../../primitives';\nimport { TextEdit } from '../../text-edit';\nimport { GraphCard } from './graph-card';\nimport { NodeColor } from './specifications/colors';\n\nexport type DecisionNodeProps = {\n name?: string;\n icon: React.ReactNode;\n type: React.ReactNode;\n helper?: (React.ReactNode | false)[];\n disabled?: boolean;\n isSelected?: boolean;\n children?: React.ReactNode;\n actions?: React.ReactNode[];\n status?: 'error' | 'success' | 'warning';\n diffStatus?: 'removed' | 'added' | 'modified' | 'moved';\n noBodyPadding?: boolean;\n color?: 'primary' | 'secondary' | string;\n menuItems?: MenuProps['items'];\n onNameChange?: (name: string) => void;\n compactMode?: boolean;\n listMode?: boolean;\n details?: React.ReactNode;\n detailsOpen?: boolean;\n detailsTitle?: string;\n onDetailsClose?: () => void;\n};\n\nexport const DecisionNode: React.FC<DecisionNodeProps> = ({\n icon,\n name,\n type,\n children,\n actions = [],\n disabled = false,\n isSelected = false,\n noBodyPadding = false,\n color = 'primary',\n onNameChange,\n menuItems = [],\n status,\n diffStatus,\n compactMode,\n listMode,\n helper,\n details,\n detailsOpen = false,\n detailsTitle = 'Details',\n onDetailsClose,\n}) => {\n const nodeColor = match(color)\n .with('primary', () => NodeColor.Blue)\n .otherwise((c) => c);\n\n const cardBorder =\n diffStatus === 'added'\n ? 'border-[var(--grl-color-success)] group-hover/dn:border-[var(--grl-color-success)]'\n : diffStatus === 'moved'\n ? 'border-[var(--grl-color-info)] group-hover/dn:border-[var(--grl-color-info)]'\n : diffStatus === 'modified'\n ? 'border-[var(--grl-color-warning)] group-hover/dn:border-[var(--grl-color-warning)]'\n : diffStatus === 'removed'\n ? 'border-[var(--destructive)] group-hover/dn:border-[var(--destructive)]'\n : isSelected\n ? 'border-[var(--grl-color-primary-active)] group-hover/dn:border-[var(--grl-color-primary-active)]'\n : '';\n\n const cardList = listMode ? 'rounded-none border-0 border-b border-b-[var(--grl-color-border-fade)]' : '';\n\n const statusBg =\n status === 'success'\n ? '[--node-background:var(--grl-color-success-bg)]'\n : status === 'error'\n ? '[--node-background:var(--grl-color-error-bg)]'\n : status === 'warning'\n ? '[--node-background:var(--grl-color-warning-bg)]'\n : '';\n\n return (\n <div\n className={clsx(\n 'group/dn flex flex-col gap-2',\n '[--node-border-radius:8px] [--node-horizontal-padding:8px] [--node-small-text:12px]',\n '[--node-color:var(--primary)] [--node-background:var(--grl-color-bg-container)]',\n statusBg,\n )}\n style={\n {\n '--node-color': nodeColor,\n } as React.CSSProperties\n }\n onKeyDown={(e) => e.stopPropagation()}\n data-diff={diffStatus}\n data-compact={compactMode || undefined}\n >\n <GraphCard className={clsx(cardBorder, cardList)}>\n <div className='absolute -top-5 w-full h-4 text-[10px] font-bold flex justify-end items-center gap-1'>\n {Array.isArray(helper) &&\n helper\n .filter((h) => !!h)\n .map((h, i) => (\n <div\n key={i}\n className='flex justify-center items-center rounded-2xl w-4 h-4 text-[10px] font-bold text-[var(--muted-foreground)]'\n >\n {h}\n </div>\n ))}\n {status === 'error' && (\n <div className='flex justify-center items-center rounded-2xl w-4 h-4 text-[10px] font-bold bg-[var(--destructive)] text-white'>\n <CloseOutlined />\n </div>\n )}\n <DiffIcon status={diffStatus} style={{ fontSize: 16 }} />\n </div>\n <div className={'grid p-2 gap-1.5 grid-cols-[min-content_1fr_min-content] items-center box-border min-h-10'}>\n <IconTile variant='solid' size='xs' className='bg-[var(--node-color)] text-white' aria-hidden>\n {icon}\n </IconTile>\n <div className='flex min-w-0 flex-col gap-0.5'>\n <TextEdit onChange={onNameChange} disabled={disabled} value={name} />\n {type != null && type !== '' && (\n <Badge variant='secondary' size='xs' className='w-fit max-w-full truncate'>\n {type}\n </Badge>\n )}\n </div>\n {menuItems.length > 0 && (\n <div className={clsx('nodrag')}>\n <Dropdown trigger={['click']} overlayStyle={{ minWidth: 250 }} menu={{ items: menuItems }}>\n <Button type='text' size={'small'} icon={<MoreOutlined />} />\n </Dropdown>\n </div>\n )}\n </div>\n {children && (\n <div\n className={clsx(\n 'p-2 border-t border-t-[var(--border)]',\n actions.length === 0 && 'rounded-[0_0_var(--node-border-radius)_var(--node-border-radius)]',\n noBodyPadding && 'p-0!',\n )}\n >\n {children}\n </div>\n )}\n {actions.length > 0 && (\n <div\n className={clsx(\n 'nodrag bg-[var(--grl-color-primary-bg-fade)] overflow-hidden',\n 'rounded-b-[var(--node-border-radius)] border-t border-t-[var(--grl-color-border-fade)]',\n )}\n >\n <div className='flex [&_button]:py-0.5 [&_button]:px-2 [&_button]:text-xs [&_button]:h-auto [&_button]:rounded-none [&_button]:text-[var(--muted-foreground)]'>\n {actions}\n </div>\n </div>\n )}\n </GraphCard>\n <TransitionMount state={detailsOpen} timeout={100}>\n {(stage, shouldMount) =>\n shouldMount && (\n <GraphCard\n className='nodrag'\n style={{\n transition: '0.1s ease-in-out',\n transform: stage === 'enter' ? 'translateY(0)' : 'translateY(-10px)',\n opacity: stage === 'enter' ? 1 : 0,\n }}\n >\n <div className='flex flex-col'>\n <div className='flex items-center justify-between pl-2.5 bg-[var(--grl-color-primary-bg-fade)] rounded-t-[var(--node-border-radius)] border-b border-b-[var(--border)]'>\n <Typography.Text className='text-xs! text-[var(--muted-foreground)]'>{detailsTitle}</Typography.Text>\n <Button\n type={'text'}\n size={'small'}\n className='text-[var(--muted-foreground)] [font-size:0]!'\n icon={<CloseOutlined style={{ fontSize: 8 }} />}\n onClick={onDetailsClose}\n />\n </div>\n <div className='flex flex-col p-2.5 gap-0.5 [&_.settings-form_.grl-ce]:text-xs'>{details}</div>\n </div>\n </GraphCard>\n )\n }\n </TransitionMount>\n </div>\n );\n};\n\nconst TRANSITION_TIMEOUT = 100;\n\nconst TransitionMount: React.FC<{\n state: boolean;\n timeout?: number;\n children: (stage: 'enter' | 'leave', shouldMount: boolean) => React.ReactNode;\n}> = ({ state, timeout = TRANSITION_TIMEOUT, children }) => {\n const [shouldMount, setShouldMount] = useState(state);\n const [stage, setStage] = useState<'enter' | 'leave'>(state ? 'enter' : 'leave');\n\n useEffect(() => {\n if (state) {\n setShouldMount(true);\n const frame = requestAnimationFrame(() => setStage('enter'));\n return () => cancelAnimationFrame(frame);\n }\n\n setStage('leave');\n const timer = setTimeout(() => setShouldMount(false), timeout);\n return () => clearTimeout(timer);\n }, [state, timeout]);\n\n return <>{children(stage, shouldMount)}</>;\n};\n","import { BookOutlined, CopyOutlined, DeleteOutlined, EditOutlined, PlusOutlined } from '#icons';\nimport type { HandleProps } from '@xyflow/react';\nimport { Handle, NodeToolbar, Position } from '@xyflow/react';\nimport clsx from 'clsx';\nimport React from 'react';\nimport { P, match } from 'ts-pattern';\n\nimport { platform } from '../../../helpers/platform';\nimport { usePersistentState } from '../../../helpers/use-persistent-state';\nimport { useT } from '../../../theming/i18n';\nimport type { MenuProps } from '../../primitives';\nimport { App, Button, Typography } from '../../primitives';\nimport { SpacedText } from '../../spaced-text';\nimport { useDecisionGraphActions, useDecisionGraphState, useNodeDiff } from '../context/dg-store.context';\nimport type { DecisionNodeProps } from './decision-node';\nimport { DecisionNode } from './decision-node';\nimport type { MinimalNodeSpecification } from './specifications/specification-types';\n\nenum Details {\n Settings,\n}\n\nexport type GraphNodeProps = {\n id: string;\n handleLeft?: boolean | Partial<HandleProps>;\n handleRight?: boolean | Partial<HandleProps>;\n className?: string;\n specification: MinimalNodeSpecification;\n displayError?: boolean;\n} & Partial<DecisionNodeProps>;\n\nexport const GraphNode = React.forwardRef<HTMLDivElement, GraphNodeProps>(\n (\n {\n id,\n handleLeft = true,\n handleRight = true,\n className,\n specification,\n name,\n displayError,\n isSelected,\n helper,\n actions,\n ...decisionNodeProps\n },\n ref,\n ) => {\n const t = useT();\n const [hovered, setHovered] = React.useState(false);\n const [currentDetails, setCurrentDetails] = usePersistentState<Details>(`node:details:${id}`, Details.Settings);\n const [detailsOpen, setDetailsOpen] = usePersistentState<boolean>(`node:detailsOpen:${id}`, false);\n const graphActions = useDecisionGraphActions();\n const { modal } = App.useApp();\n const { nodeError, nodeTrace, disabled, compactMode } = useDecisionGraphState(\n ({ simulate, disabled, compactMode }) => ({\n disabled,\n nodeTrace: match(simulate)\n .with({ result: P._ }, ({ result }) => result?.trace?.[id])\n .otherwise(() => null),\n nodeError: match(simulate)\n .with({ error: { data: { nodeId: id } } }, ({ error }) => error)\n .otherwise(() => null),\n compactMode,\n }),\n );\n\n const { diff } = useNodeDiff(id);\n\n const Settings = specification.renderSettings;\n\n const openSettings = () => {\n setDetailsOpen(currentDetails === Details.Settings ? !detailsOpen : true);\n setCurrentDetails(Details.Settings);\n };\n\n const confirmDelete = () =>\n modal.confirm({\n icon: null,\n title: t('dg.node.deleteNode'),\n content: (\n <Typography.Text>\n Are you sure you want to delete <Typography.Text strong>{name}</Typography.Text> node.\n </Typography.Text>\n ),\n okButtonProps: { danger: true },\n onOk: () => graphActions.removeNodes([id]),\n });\n\n const menuItems = [\n specification.documentationUrl\n ? {\n key: 'documentation',\n label: <SpacedText left={t('dg.node.documentation')} right={<BookOutlined />} />,\n onClick: () => window.open(specification.documentationUrl, '_href'),\n }\n : null,\n specification.documentationUrl ? { key: 'divider-1', type: 'divider' } : null,\n !displayError && {\n key: 'copy-clipboard',\n label: <SpacedText left={t('func.debugger.copy')} right={platform.shortcut('Ctrl + C')} />,\n onClick: () => graphActions.copyNodes([id]),\n },\n !displayError && {\n key: 'duplicate',\n disabled,\n label: <SpacedText left={t('dg.node.duplicate')} right={platform.shortcut('Ctrl + D')} />,\n onClick: () => graphActions.duplicateNodes([id]),\n },\n !displayError && { key: 'divider-2', type: 'divider' },\n {\n key: 'delete',\n danger: true,\n label: <SpacedText left={t('common.delete')} right={platform.shortcut('Backspace')} />,\n disabled,\n onClick: confirmDelete,\n },\n ].filter((i) => i !== null && i !== false);\n\n return (\n <div\n className={clsx('grl-graph-node', className)}\n style={{ minWidth: 220, maxWidth: 220 }}\n ref={ref}\n onMouseEnter={() => setHovered(true)}\n onMouseLeave={() => setHovered(false)}\n onClick={(event) => {\n const isToggle = match(navigator.platform.includes('Mac'))\n .with(true, () => event.metaKey)\n .otherwise(() => event.ctrlKey);\n\n graphActions.triggerNodeSelect(id, isToggle ? 'toggle' : 'only');\n }}\n >\n {/* WS1-R2:悬停/选中显现的快捷工具栏(flow-1 node toolbar 模式) */}\n <NodeToolbar isVisible={isSelected || hovered} position={Position.Top} offset={10}>\n <div className='nodrag nopan flex items-center gap-0.5 rounded-md border border-[var(--border)] bg-[var(--grl-color-bg-container)] p-0.5 shadow-md'>\n {Settings && (\n <Button\n type='text'\n size='small'\n className='h-6 w-6 p-0'\n aria-label='Settings'\n icon={<EditOutlined />}\n onClick={openSettings}\n />\n )}\n <Button\n type='text'\n size='small'\n className='h-6 w-6 p-0'\n aria-label='Copy'\n icon={<CopyOutlined />}\n onClick={() => graphActions.copyNodes([id])}\n />\n <Button\n type='text'\n size='small'\n className='h-6 w-6 p-0'\n aria-label='Duplicate'\n disabled={disabled}\n icon={<PlusOutlined />}\n onClick={() => graphActions.duplicateNodes([id])}\n />\n <Button\n type='text'\n size='small'\n className='h-6 w-6 p-0 text-[var(--destructive)]'\n aria-label='Delete'\n disabled={disabled}\n icon={<DeleteOutlined />}\n onClick={confirmDelete}\n />\n </div>\n </NodeToolbar>\n {handleLeft && (\n <Handle\n className={clsx('grl-graph-node__handle-left', compactMode && 'compact')}\n type='target'\n position={Position.Left}\n {...(typeof handleLeft !== 'boolean' ? handleLeft : {})}\n />\n )}\n <DecisionNode\n menuItems={menuItems as MenuProps['items']}\n {...decisionNodeProps}\n disabled={disabled}\n icon={specification.icon}\n color={specification.color}\n type={specification.displayName}\n helper={helper}\n name={name}\n details={Settings ? <Settings id={id} /> : undefined}\n detailsOpen={detailsOpen}\n detailsTitle={match(currentDetails)\n .with(Details.Settings, () => 'Settings')\n .otherwise(() => undefined)}\n onDetailsClose={() => setDetailsOpen(false)}\n actions={\n !Settings\n ? actions\n : [\n ...(actions ?? []),\n <Button key='settings' type='text' style={{ marginLeft: 'auto' }} onClick={openSettings}>\n Settings\n </Button>,\n ]\n }\n status={match([nodeTrace, nodeError, displayError])\n .with([P._, P._, true], () => 'error' as const)\n .with([P._, P.not(P.nullish), P._], () => 'error' as const)\n .with([P.not(P.nullish), P._, P._], () => 'success' as const)\n .otherwise(() => undefined)}\n diffStatus={match([diff])\n .with([{ status: 'added' }], () => 'added' as const)\n .with([{ status: 'modified' }], () => 'modified' as const)\n .with([{ status: 'removed' }], () => 'removed' as const)\n .with([{ status: 'moved' }], () => 'moved' as const)\n .otherwise(() => undefined)}\n onNameChange={(name) => {\n graphActions.updateNode(id, (draft) => {\n draft.name = name;\n return draft;\n });\n }}\n compactMode={compactMode}\n />\n {handleRight && (\n <Handle\n className={clsx('grl-graph-node__handle-right', compactMode && 'compact')}\n type='source'\n position={Position.Right}\n {...(typeof handleRight !== 'boolean' ? handleRight : {})}\n />\n )}\n </div>\n );\n },\n);\n","import { ArrowRightOutlined, SyncOutlined } from '#icons';\nimport { VariableType } from '@gorules/zen-engine-wasm';\nimport equal from 'fast-deep-equal/es6/react';\nimport { produce } from 'immer';\nimport _ from 'lodash';\nimport { Grid3x3Icon } from 'lucide-react';\nimport React from 'react';\nimport type { z } from 'zod';\n\nimport { useNodeType } from '../../../../helpers/node-type';\nimport type { decisionTableSchema } from '../../../../helpers/schema';\nimport { Button, Form, Space } from '../../../primitives';\nimport { DiffCodeEditor, DiffInput, DiffRadio, DiffSwitch } from '../../../shared';\nimport { useDecisionGraphActions, useDecisionGraphState, useNodeDiff } from '../../context/dg-store.context';\nimport type { Diff, DiffMetadata } from '../../dg-types';\nimport { compareAndUnifyLists } from '../../diff/comparison';\nimport { TabDecisionTable } from '../../graph/tab-decision-table';\nimport { GraphNode } from '../graph-node';\nimport { NodeKind } from './specification-types';\nimport type { NodeSpecification } from './specification-types';\n\ntype InferredContent = z.infer<typeof decisionTableSchema>['content'];\n\nexport type NodeDecisionTableData = Omit<InferredContent, 'inputs' | 'outputs' | 'rules'> &\n Diff & {\n rules: (InferredContent['rules'][0] & Diff)[];\n inputs: (InferredContent['inputs'][0] & Diff)[];\n outputs: (InferredContent['outputs'][0] & Diff)[];\n };\n\nexport const decisionTableSpecification: NodeSpecification<NodeDecisionTableData> = {\n type: NodeKind.DecisionTable,\n icon: <Grid3x3Icon size='1em' />,\n displayName: 'Decision table',\n documentationUrl: 'https://gorules.io/docs/user-manual/decision-modeling/decisions/decision-tables',\n shortDescription: 'Rules spreadsheet',\n renderTab: ({ id }) => <TabDecisionTable id={id} />,\n getDiffContent: (current, previous) => {\n return produce(current, (draft) => {\n const fields: DiffMetadata['fields'] = {};\n if ((current.executionMode ?? 'single') !== (previous.executionMode ?? 'single')) {\n _.set(fields, 'executionMode', {\n status: 'modified',\n previousValue: previous.executionMode,\n });\n }\n\n if ((current.hitPolicy ?? 'first') !== (previous.hitPolicy ?? 'first')) {\n _.set(fields, 'hitPolicy', {\n status: 'modified',\n previousValue: previous.hitPolicy,\n });\n }\n\n if ((current.inputField ?? '') !== (previous.inputField ?? '')) {\n _.set(fields, 'inputField', {\n status: 'modified',\n previousValue: previous.inputField,\n });\n }\n\n if ((current.outputPath ?? '') !== (previous.outputPath ?? '')) {\n _.set(fields, 'outputPath', {\n status: 'modified',\n previousValue: previous.outputPath,\n });\n }\n\n if ((current.passThrough ?? false) !== (previous.passThrough ?? false)) {\n _.set(fields, 'passThrough', {\n status: 'modified',\n previousValue: previous.passThrough,\n });\n }\n\n const inputs = compareAndUnifyLists(current?.inputs || [], previous?.inputs || [], {\n compareFields: (current, previous) => {\n const hasNameChange = (current.name ?? '') !== (previous.name ?? '');\n const hasFieldChange = (current.field ?? '') !== (previous.field ?? '');\n const hasDefaultValueChange = (current.defaultValue ?? '') !== (previous.defaultValue ?? '');\n\n return {\n hasChanges: hasNameChange || hasFieldChange || hasDefaultValueChange,\n fields: {\n ...(hasNameChange && {\n name: {\n status: 'modified',\n previousValue: previous.name,\n },\n }),\n ...(hasFieldChange && {\n field: {\n status: 'modified',\n previousValue: previous.field,\n },\n }),\n ...(hasDefaultValueChange && {\n defaultValue: {\n status: 'modified',\n previousValue: previous.defaultValue,\n },\n }),\n },\n };\n },\n });\n\n const outputs = compareAndUnifyLists(current?.outputs || [], previous?.outputs || [], {\n compareFields: (current, previous) => {\n const hasNameChange = (current.name ?? '') !== (previous.name ?? '');\n const hasFieldChange = (current.field ?? '') !== (previous.field ?? '');\n const hasDefaultValueChange = (current.defaultValue ?? '') !== (previous.defaultValue ?? '');\n\n return {\n hasChanges: hasNameChange || hasFieldChange || hasDefaultValueChange,\n fields: {\n ...(hasNameChange && {\n name: {\n status: 'modified',\n previousValue: previous.name,\n },\n }),\n ...(hasFieldChange && {\n field: {\n status: 'modified',\n previousValue: previous.field,\n },\n }),\n ...(hasDefaultValueChange && {\n defaultValue: {\n status: 'modified',\n previousValue: previous.defaultValue,\n },\n }),\n },\n };\n },\n });\n\n const rules = compareAndUnifyLists(current?.rules || [], previous?.rules || [], {\n idField: '_id',\n compareFields: (current, previous) => {\n const hasDescriptionChange = (current._description ?? '') !== (previous._description ?? '');\n\n const inputChanges: any = {};\n inputs.forEach((input) => {\n if (input._diff?.status === 'added') {\n inputChanges[input.id] = {\n status: 'added',\n };\n } else if (input._diff?.status === 'removed') {\n inputChanges[input.id] = {\n status: 'removed',\n };\n } else if ((current?.[input.id] ?? '') !== (previous?.[input.id] ?? '')) {\n inputChanges[input.id] = {\n status: 'modified',\n previousValue: previous?.[input.id],\n };\n }\n });\n\n const outputChanges: any = {};\n outputs.forEach((output) => {\n if (output?._diff?.status === 'added') {\n outputChanges[output.id] = {\n status: 'added',\n };\n } else if (output?._diff?.status === 'removed') {\n outputChanges[output.id] = {\n status: 'removed',\n };\n } else if ((current?.[output.id] ?? '') !== (previous?.[output.id] ?? '')) {\n outputChanges[output.id] = {\n status: 'modified',\n previousValue: previous?.[output.id],\n };\n }\n });\n\n return {\n hasChanges:\n hasDescriptionChange || Object.keys(inputChanges).length > 0 || Object.keys(outputChanges).length > 0,\n fields: {\n ...(hasDescriptionChange && {\n _description: {\n status: 'modified',\n previousValue: previous._description,\n },\n }),\n ...inputChanges,\n ...outputChanges,\n },\n };\n },\n });\n\n draft.inputs = inputs;\n draft.outputs = outputs;\n draft.rules = rules;\n\n if (\n inputs.find(\n (input) =>\n input?._diff?.status === 'modified' ||\n input?._diff?.status === 'added' ||\n input?._diff?.status === 'removed',\n )\n ) {\n _.set(fields, 'inputs', {\n status: 'modified',\n });\n }\n\n if (\n outputs.find(\n (output) =>\n output?._diff?.status === 'modified' ||\n output?._diff?.status === 'added' ||\n output?._diff?.status === 'removed',\n )\n ) {\n _.set(fields, 'outputs', {\n status: 'modified',\n });\n }\n\n if (\n rules.find(\n (rule) =>\n rule?._diff?.status === 'modified' || rule?._diff?.status === 'added' || rule?._diff?.status === 'removed',\n )\n ) {\n _.set(fields, 'rules', {\n status: 'modified',\n });\n }\n\n if (Object.keys(fields).length > 0) {\n draft._diff = {\n status: 'modified',\n fields,\n };\n }\n\n return draft;\n });\n },\n inferTypes: {\n needsUpdate: (content, prevContent) => !equal(content, prevContent),\n determineOutputType: ({ content, input }) => {\n let nodeInput = input.clone();\n let determinedType = VariableType.fromJson({ Object: {} });\n if (content.inputField) {\n nodeInput = input.calculateType(content.inputField);\n }\n\n if (content.executionMode === 'loop') {\n nodeInput = nodeInput.arrayItem();\n }\n\n const outputs = (content?.outputs || []).filter((output) => !!output.field);\n outputs.forEach((output) => {\n for (const rule of content.rules) {\n if (!rule[output.id]) {\n continue;\n }\n\n const calculatedType = nodeInput.calculateType(rule[output.id]);\n const jsonType = calculatedType.toJson();\n if (jsonType !== 'Any' && jsonType !== 'Null') {\n determinedType.set(output.field, calculatedType);\n return;\n }\n }\n\n determinedType.setJson(output.field, 'Any');\n });\n\n if (content.hitPolicy === 'collect') {\n determinedType = determinedType.toArray();\n }\n\n if (content.executionMode === 'loop') {\n determinedType = determinedType.toArray();\n }\n\n if (content.outputPath) {\n const newType = VariableType.fromJson({ Object: {} });\n newType.set(content.outputPath, determinedType);\n determinedType = newType;\n }\n\n if (content.passThrough) {\n determinedType = input.merge(determinedType);\n }\n\n return determinedType;\n },\n },\n generateNode: ({ index }) => ({\n name: `decisionTable${index}`,\n content: {\n hitPolicy: 'first',\n inputs: [\n {\n id: crypto.randomUUID(),\n name: 'Input',\n },\n ],\n outputs: [\n {\n id: crypto.randomUUID(),\n field: 'output',\n name: 'Output',\n },\n ],\n rules: [],\n inputField: null,\n outputPath: null,\n passThrough: true,\n executionMode: 'single',\n },\n }),\n renderNode: ({ id, data, selected, specification }) => {\n const graphActions = useDecisionGraphActions();\n const { passThrough, executionMode } = useDecisionGraphState(({ decisionGraph }) => {\n const content = (decisionGraph?.nodes ?? []).find((node) => node.id === id)?.content as NodeDecisionTableData;\n return {\n passThrough: content?.passThrough || false,\n executionMode: content?.executionMode,\n };\n });\n\n return (\n <GraphNode\n id={id}\n specification={specification}\n name={data.name}\n isSelected={selected}\n helper={[executionMode === 'loop' && <SyncOutlined />, passThrough && <ArrowRightOutlined />]}\n actions={[\n <Button key='edit-table' type='text' onClick={() => graphActions.openTab(id)}>\n Edit Table\n </Button>,\n ]}\n />\n );\n },\n renderSettings: ({ id }) => {\n const graphActions = useDecisionGraphActions();\n const inputType = useNodeType(id);\n const { contentDiff } = useNodeDiff(id);\n\n const { fields, disabled } = useDecisionGraphState(({ decisionGraph, disabled }) => {\n const content = (decisionGraph?.nodes ?? []).find((node) => node.id === id)?.content as NodeDecisionTableData;\n return {\n disabled,\n fields: {\n passThrough: content?.passThrough || false,\n inputField: content?.inputField,\n outputPath: content?.outputPath,\n executionMode: content?.executionMode || 'single',\n hitPolicy: content?.hitPolicy || 'first',\n },\n };\n });\n\n const updateNode = (data: Partial<NodeDecisionTableData>) => {\n graphActions.updateNode(id, (draft) => {\n Object.assign(draft.content, data);\n return draft;\n });\n };\n\n return (\n <div className={'settings-form'}>\n <Form.Item label={'Hit Policy'}>\n <Space direction={'vertical'} size={2}>\n <DiffRadio\n size={'small'}\n previousValue={contentDiff?.fields?.hitPolicy?.previousValue}\n displayDiff={contentDiff?.fields?.hitPolicy?.status === 'modified'}\n disabled={disabled}\n value={fields?.hitPolicy}\n onChange={(e) => updateNode({ hitPolicy: e?.target?.value as 'first' | 'collect' })}\n options={[\n {\n value: 'first',\n label: 'First',\n },\n {\n value: 'collect',\n label: 'Collect',\n },\n ]}\n />\n </Space>\n </Form.Item>\n <Form.Item label='Passthrough'>\n <DiffSwitch\n disabled={disabled}\n size={'small'}\n displayDiff={contentDiff?.fields?.passThrough?.status === 'modified'}\n checked={fields?.passThrough}\n previousChecked={contentDiff?.fields?.passThrough?.previousValue}\n onChange={(e) => updateNode({ passThrough: e })}\n />\n </Form.Item>\n <Form.Item label='Input field'>\n <DiffCodeEditor\n variableType={inputType}\n disabled={disabled}\n displayDiff={contentDiff?.fields?.inputField?.status === 'modified'}\n previousValue={contentDiff?.fields?.inputField?.previousValue}\n style={{ fontSize: 12, lineHeight: '20px', width: '100%' }}\n expectedVariableType={fields?.executionMode === 'loop' ? { Array: 'Any' } : undefined}\n maxRows={4}\n value={fields?.inputField ?? ''}\n onChange={(val) => updateNode({ inputField: val?.trim() || null })}\n />\n </Form.Item>\n <Form.Item label='Output path'>\n <DiffInput\n size={'small'}\n readOnly={disabled}\n displayDiff={contentDiff?.fields?.outputPath?.status === 'modified'}\n previousValue={contentDiff?.fields?.outputPath?.previousValue}\n value={fields?.outputPath ?? ''}\n onChange={(e) => updateNode({ outputPath: e?.target?.value?.trim() || null })}\n />\n </Form.Item>\n <Form.Item label='Execution mode'>\n <DiffRadio\n size={'small'}\n disabled={disabled}\n displayDiff={contentDiff?.fields?.executionMode?.status === 'modified'}\n previousValue={contentDiff?.fields?.executionMode?.previousValue}\n value={fields?.executionMode}\n onChange={(e) => updateNode({ executionMode: e?.target?.value as 'loop' | 'single' })}\n options={[\n {\n value: 'single',\n label: 'Single',\n },\n {\n value: 'loop',\n label: 'Loop',\n },\n ]}\n />\n </Form.Item>\n </div>\n );\n },\n};\n","import type { Variable, VariableType } from '@gorules/zen-engine-wasm';\nimport equal from 'fast-deep-equal/es6/react';\nimport { produce } from 'immer';\nimport React, { useMemo } from 'react';\nimport type { z } from 'zod';\nimport type { StoreApi, UseBoundStore } from 'zustand';\nimport { create, useStore } from 'zustand';\n\nimport { type GetNodeDataResult } from '../../../helpers/node-data';\nimport type { expressionNodeSchema } from '../../../helpers/schema';\nimport { useMemoEquality } from '../../../helpers/use-memoized-selector';\nimport type { SimulationTrace, SimulationTraceDataExpression } from '../../decision-graph';\nimport type { DiffMetadata } from '../../decision-graph/dg-types';\n\n// Empty-object default is safe: consumers only render inside\n// ExpressionStoreProvider, which supplies the real store on mount.\nconst ExpressionStoreContext = React.createContext<\n UseBoundStore<StoreApi<ExpressionStore>> & {\n setState: (partial: Partial<ExpressionStore>) => void;\n }\n>(\n // Double-cast is intentional: consumers only render inside\n // ExpressionStoreProvider, which supplies the real store on mount.\n {} as unknown as UseBoundStore<StoreApi<ExpressionStore>> & {\n setState: (partial: Partial<ExpressionStore>) => void;\n },\n);\n\nexport type ExpressionEntry = {\n id: string;\n key: string;\n value: string;\n _diff?: DiffMetadata;\n};\n\nexport type ExpressionPermission = 'edit:full' | 'edit:values' | 'view';\n\nexport type ExpressionStore = {\n disabled: boolean;\n\n permission?: ExpressionPermission;\n\n addRowAbove: (index?: number, data?: Partial<ExpressionEntry>) => void;\n addRowBelow: (index?: number, data?: Partial<ExpressionEntry>) => void;\n\n expressions: ExpressionEntry[];\n setExpressions: (expressions: ExpressionEntry[]) => void;\n\n swapRows: (sourceIndex: number, targetIndex: number) => void;\n updateRow: (index: number, update: Partial<Omit<ExpressionEntry, 'id'>>) => void;\n removeRow: (index: number) => void;\n\n inputVariableType?: VariableType;\n\n debugIndex: number;\n calculatedInputData?: Variable;\n debug?: ExpressionDebug;\n};\n\nexport type ExpressionDebug = {\n snapshot: z.infer<typeof expressionNodeSchema>['content'];\n trace: SimulationTrace<SimulationTraceDataExpression>;\n inputData?: GetNodeDataResult;\n};\n\ntype ExpressionStoreProviderProps = {\n //\n};\n\nexport const createExpression = (data: Partial<ExpressionEntry> = {}): ExpressionEntry => ({\n id: crypto.randomUUID(),\n key: '',\n value: '',\n ...data,\n});\n\nexport const ExpressionStoreProvider: React.FC<React.PropsWithChildren<ExpressionStoreProviderProps>> = ({\n children,\n}) => {\n const store = useMemo(\n () =>\n create<ExpressionStore>((set) => ({\n disabled: false,\n debugIndex: 0,\n addRowAbove: (index = 0) => {\n set(\n produce<ExpressionStore>((draft) => {\n draft.expressions.splice(index, 0, createExpression());\n return draft;\n }),\n );\n },\n addRowBelow: (index) => {\n set(\n produce<ExpressionStore>((draft) => {\n index = index ?? draft.expressions.length - 1;\n draft.expressions.splice(index + 1, 0, createExpression());\n\n return draft;\n }),\n );\n },\n expressions: [],\n setExpressions: (expressions) => {\n set({ expressions });\n },\n swapRows: (sourceIndex, targetIndex) => {\n set(\n produce<ExpressionStore>((draft) => {\n const [input] = draft.expressions.splice(sourceIndex, 1);\n draft.expressions.splice(targetIndex, 0, input);\n\n return draft;\n }),\n );\n },\n removeRow: (index) => {\n set(\n produce<ExpressionStore>((draft) => {\n draft.expressions.splice(index, 1);\n return draft;\n }),\n );\n },\n updateRow: (index, update) => {\n set(\n produce<ExpressionStore>((draft) => {\n draft.expressions[index] = {\n ...draft.expressions[index],\n ...update,\n };\n\n return draft;\n }),\n );\n },\n })),\n [],\n );\n\n return <ExpressionStoreContext.Provider value={store}>{children}</ExpressionStoreContext.Provider>;\n};\n\nexport function useExpressionStore<T>(\n selector: (state: ExpressionStore) => T,\n equals: (a: any, b: any) => boolean = equal,\n): T {\n return useStore(React.useContext(ExpressionStoreContext), useMemoEquality(selector, equals));\n}\n\nexport const useExpressionStoreRaw = () => React.useContext(ExpressionStoreContext);\n","import React, { useMemo } from 'react';\nimport { P, match } from 'ts-pattern';\n\nimport { Select, Typography } from '../primitives';\nimport { Stack } from '../stack';\nimport { useExpressionStoreRaw } from './context/expression-store.context';\n\nexport const ExpressionCommandBar: React.FC = () => {\n const expressionStore = useExpressionStoreRaw();\n const debugIndex = expressionStore((state) => state.debugIndex);\n const traceCount = expressionStore((state) =>\n match(state.debug?.trace?.traceData)\n .with(P.array(), (some) => some.length)\n .otherwise(() => null),\n );\n\n const traceIndexOptions = useMemo(() => {\n if (!traceCount) {\n return null;\n }\n\n return Array.from({ length: traceCount }).map((_, i) => ({\n label: String(i),\n value: i,\n }));\n }, [debugIndex, traceCount]);\n\n if (!traceIndexOptions) {\n return null;\n }\n\n return (\n <Stack\n horizontal\n horizontalAlign={'space-between'}\n verticalAlign={'center'}\n className={'p-[7px] box-border border-b border-[var(--border)]'}\n >\n <Stack gap={8} horizontal className='w-full' />\n {traceIndexOptions && (\n <Stack horizontal verticalAlign='center' horizontalAlign='end'>\n <Typography.Text style={{ fontSize: 12 }}>Simulation index:</Typography.Text>\n <Select\n size='small'\n style={{ fontSize: 12, minWidth: 60 }}\n options={traceIndexOptions}\n onChange={(debugIndex: number) => expressionStore.setState({ debugIndex })}\n value={traceIndexOptions.some((t) => t.value === debugIndex) ? debugIndex : 0}\n />\n </Stack>\n )}\n </Stack>\n );\n};\n","import equal from 'fast-deep-equal/es6/react';\nimport type React from 'react';\nimport { useEffect, useRef } from 'react';\n\nimport type { ExpressionEntry, ExpressionStore } from './context/expression-store.context';\nimport { useExpressionStore, useExpressionStoreRaw } from './context/expression-store.context';\n\nexport type ExpressionControllerProps = {\n disabled?: boolean;\n defaultValue?: ExpressionEntry[];\n permission?: ExpressionStore['permission'];\n value?: ExpressionEntry[];\n onChange?: (value: ExpressionEntry[]) => void;\n};\n\nexport const ExpressionController: React.FC<ExpressionControllerProps> = ({\n value,\n onChange,\n defaultValue = [],\n disabled = false,\n permission = 'edit:full',\n}) => {\n const mounted = useRef<boolean>(false);\n const store = useExpressionStoreRaw();\n const { setExpressions, expressions } = useExpressionStore(({ setExpressions, expressions }) => ({\n setExpressions,\n expressions,\n }));\n\n useEffect(() => {\n store.setState({\n disabled,\n permission,\n });\n }, [disabled, permission]);\n\n useEffect(() => {\n if (!onChange) {\n return;\n }\n\n return store.subscribe((state, prevState) => {\n if (!equal(state.expressions, prevState.expressions)) {\n onChange?.(state.expressions);\n }\n });\n }, [store, onChange]);\n\n useEffect(() => {\n if (mounted.current && value && !equal(value, expressions)) {\n setExpressions(value);\n }\n }, [value]);\n\n useEffect(() => {\n if (value) {\n setExpressions(value);\n } else if (defaultValue) {\n setExpressions(defaultValue);\n }\n mounted.current = true;\n }, []);\n\n return null;\n};\n","import { P, match } from 'ts-pattern';\n\nexport const getTrace = <T>(data: T | T[], n: number): T => {\n return match(data)\n .with(P.array(), (a) => {\n const arr = a as T[];\n const index = match(n)\n .with(P.number.between(0, arr.length - 1), (x) => x)\n .otherwise(() => 0);\n\n return arr[index];\n })\n .otherwise((d) => d);\n};\n","import React from 'react';\n\nimport { useT } from '../../theming/i18n';\nimport { Dropdown } from '../primitives';\nimport { SpacedText } from '../spaced-text';\nimport { useExpressionStore } from './context/expression-store.context';\n\ntype ExpressionItemContextMenuProps = {\n index: number;\n children: React.ReactNode;\n};\n\nexport const ExpressionItemContextMenu: React.FC<ExpressionItemContextMenuProps> = ({ index, children }) => {\n const { addRowAbove, addRowBelow, disabled } = useExpressionStore(({ addRowBelow, addRowAbove, disabled }) => ({\n addRowBelow,\n addRowAbove,\n disabled,\n }));\n const t = useT();\n\n return (\n <Dropdown\n destroyPopupOnHide\n transitionName=''\n disabled={disabled}\n overlayStyle={{ minWidth: 200 }}\n trigger={['contextMenu']}\n menu={{\n items: [\n {\n key: 'addRowAbove',\n label: <SpacedText left={t('expression.addRowAbove')} />,\n onClick: () => {\n addRowAbove(index);\n },\n },\n {\n key: 'addRowBelow',\n label: <SpacedText left={t('expression.addRowBelow')} />,\n onClick: () => {\n addRowBelow(index);\n },\n },\n ],\n }}\n >\n {children}\n </Dropdown>\n );\n};\n","import { useDndContext, useDraggable, useDroppable } from '@dnd-kit/core';\nimport type { VariableType } from '@gorules/zen-engine-wasm';\nimport clsx from 'clsx';\nimport { GripVerticalIcon } from 'lucide-react';\nimport React, { useRef, useState } from 'react';\n\nimport { getDropDirection } from '../../helpers/dnd';\nimport { getTrace } from '../../helpers/trace';\nimport { useT } from '../../theming/i18n';\nimport { CodeEditorPreview } from '../code-editor/ce-preview';\nimport { ConfirmAction } from '../confirm-action';\nimport { DiffIcon } from '../diff-icon';\nimport { Typography } from '../primitives';\nimport { DiffAutosizeTextArea } from '../shared';\nimport { DiffCodeEditor } from '../shared/diff-ce';\nimport type { ExpressionEntry } from './context/expression-store.context';\nimport { useExpressionStore } from './context/expression-store.context';\nimport { ExpressionItemContextMenu } from './expression-item-context-menu';\n\nexport type ExpressionItemProps = {\n expression: ExpressionEntry;\n index: number;\n variableType?: VariableType;\n};\n\nexport const ExpressionItem: React.FC<ExpressionItemProps> = ({ expression, index, variableType }) => {\n const [isFocused, setIsFocused] = useState(false);\n const t = useT();\n const expressionRef = useRef<HTMLDivElement | null>(null);\n const { updateRow, removeRow, disabled, permission } = useExpressionStore(\n ({ updateRow, removeRow, disabled, permission }) => ({\n updateRow,\n removeRow,\n disabled,\n permission,\n }),\n );\n\n const onChange = (update: Partial<Omit<ExpressionEntry, 'id'>>) => {\n updateRow(index, update);\n };\n\n const onRemove = () => {\n removeRow(index);\n };\n\n const actionDisabled = permission !== 'edit:full' || disabled;\n\n const {\n attributes,\n listeners,\n setNodeRef: setDragNodeRef,\n setActivatorNodeRef,\n isDragging,\n } = useDraggable({\n id: `expr-${expression.id ?? index}`,\n data: { index },\n disabled: actionDisabled,\n });\n\n const { setNodeRef: setDropNodeRef, isOver } = useDroppable({\n id: `expr-drop-${expression.id ?? index}`,\n data: { index },\n });\n\n const dndContext = useDndContext();\n const direction = isOver\n ? getDropDirection(dndContext.active?.rect.current.translated, expressionRef.current?.getBoundingClientRect())\n : 'up';\n\n const diffStatus = expression?._diff?.status;\n const diffBg =\n diffStatus === 'added'\n ? 'bg-[var(--grl-color-success-bg)]'\n : diffStatus === 'removed'\n ? 'bg-[var(--grl-color-error-bg)]'\n : diffStatus === 'modified'\n ? 'bg-[var(--grl-color-warning-bg)]'\n : 'bg-[var(--grl-color-bg-container)]';\n\n return (\n <div\n ref={(el) => {\n expressionRef.current = el;\n setDropNodeRef(el);\n setDragNodeRef(el);\n }}\n className={clsx(\n 'group/item relative grid grid-cols-[40px_minmax(240px,1.1fr)_3fr_40px] items-start focus-within:[box-shadow:0_0_0_1px_var(--border)]',\n \"after:absolute after:left-0 after:right-0 after:bg-[var(--primary)] after:content-['']\",\n isOver && direction === 'down' && 'after:-bottom-px after:h-[2px]',\n isOver && direction === 'up' && 'after:-top-px after:h-[2px]',\n diffBg,\n )}\n style={{ opacity: !isDragging ? 1 : 0.5 }}\n >\n <div\n ref={setActivatorNodeRef}\n {...listeners}\n {...attributes}\n className='box-border flex h-full items-start justify-center border-r border-[var(--grl-color-border-fade)] pt-[15px] text-[var(--muted-foreground)] cursor-grab aria-disabled:cursor-not-allowed'\n aria-disabled={actionDisabled}\n >\n <div className='flex content-center gap-[3px] opacity-50 [&>span]:leading-[1.4]'>\n {expression?._diff?.status ? (\n <DiffIcon\n status={expression?._diff?.status}\n style={{\n fontSize: 16,\n }}\n />\n ) : (\n <GripVerticalIcon size={10} />\n )}\n </div>\n </div>\n <div className='box-border h-full border-r border-[var(--grl-color-border-fade)]'>\n <ExpressionItemContextMenu index={index}>\n <DiffAutosizeTextArea\n noStyle\n className='min-h-full py-3 px-3 text-[13px] leading-[1.5em] [font-family:var(--mono-font-family)] focus:shadow-none'\n placeholder={t('expression.key')}\n maxRows={10}\n readOnly={permission !== 'edit:full' || disabled}\n displayDiff={expression?._diff?.fields?.key?.status === 'modified'}\n previousValue={expression?._diff?.fields?.key?.previousValue}\n value={expression?.key}\n onChange={(e) => onChange({ key: e.target.value })}\n />\n </ExpressionItemContextMenu>\n </div>\n <div className='relative box-border h-full text-[13px]'>\n <ExpressionItemContextMenu index={index}>\n <div>\n <DiffCodeEditor\n // Consolidated on --ce-* tokens (HK-13): geometry now flows through\n // the same custom properties decision-table cells use (12px rhythm),\n // placeholder via the semantic token. pr-[60px] stays — reserved\n // right gutter for item controls.\n className='[--ce-verticalPadding:12px] [--ce-horizontalPadding:12px] [&_.cm-content]:pr-[60px]! [&_.cm-placeholder]:text-[color:var(--grl-color-text-placeholder)]!'\n placeholder={t('expression.placeholder')}\n maxRows={9}\n disabled={disabled}\n value={expression?.value}\n displayDiff={expression?._diff?.fields?.value?.status === 'modified'}\n previousValue={expression?._diff?.fields?.value?.previousValue}\n onChange={(value) => onChange({ value })}\n variableType={variableType}\n onFocus={() => setIsFocused(true)}\n onBlur={() => setIsFocused(false)}\n noStyle={true}\n />\n <ResultOverlay expression={expression} />\n </div>\n </ExpressionItemContextMenu>\n </div>\n <div className='flex h-full box-border items-center justify-center [&>button]:hidden group-hover/item:[&>button]:flex group-focus-within/item:[&>button]:flex'>\n <ConfirmAction iconOnly disabled={permission !== 'edit:full' || disabled} onConfirm={onRemove} />\n {isFocused && <LivePreview id={expression.id} value={expression.value} />}\n </div>\n </div>\n );\n};\n\nconst LivePreview = React.memo<{ id: string; value: string }>(({ id, value }) => {\n const { inputData, initial } = useExpressionStore(({ debug, debugIndex, calculatedInputData }) => {\n const snapshot = (debug?.snapshot?.expressions ?? []).find((e) => e.id === id);\n const trace = snapshot?.key ? getTrace(debug?.trace.traceData, debugIndex)?.[snapshot.key] : undefined;\n\n return {\n inputData: calculatedInputData,\n initial: snapshot && trace ? { expression: snapshot.value, result: trace.result } : undefined,\n };\n });\n\n return (\n <div className='absolute top-full right-0 z-[5] rounded-br-lg border-t border-[var(--background)] bg-[var(--background)] p-2 w-[400px] max-w-[50%] overflow-x-auto whitespace-nowrap opacity-100 [pointer-events:bounding-box] hover:opacity-50 [&_.grl-ce-preview]:bg-white'>\n <CodeEditorPreview expression={value} inputData={inputData} initial={initial} />\n </div>\n );\n});\n\nconst ResultOverlay: React.FC<{ expression: ExpressionEntry }> = ({ expression }) => {\n const { trace } = useExpressionStore(({ debug, debugIndex }) => ({\n trace: getTrace(debug?.trace?.traceData, debugIndex)?.[expression.key]?.result,\n }));\n if (trace === undefined) {\n return null;\n }\n\n return (\n <div className='absolute top-1/2 right-[3px] -translate-y-1/2 rounded border border-[var(--grl-color-success-border)] bg-[var(--grl-color-success-bg)] px-1.5 py-0.5 max-h-[calc(100%-5px)] max-w-[50%] overflow-x-auto whitespace-nowrap [&>span]:text-xs [&>span]:[font-family:var(--mono-font-family)]'>\n <Typography.Text\n ellipsis={{ tooltip: (trace ?? undefined) as React.ReactNode }}\n style={{ maxWidth: 60, overflow: 'hidden' }}\n >\n = {JSON.stringify(trace)}\n </Typography.Text>\n </div>\n );\n};\n","import { PlusCircleOutlined } from '#icons';\nimport type { VariableType } from '@gorules/zen-engine-wasm';\nimport clsx from 'clsx';\nimport equal from 'fast-deep-equal/es6/react';\nimport React, { useEffect, useState } from 'react';\n\nimport { isWasmAvailable } from '../../helpers/wasm';\nimport { Button, Typography } from '../primitives';\nimport { useExpressionStore } from './context/expression-store.context';\nimport { ExpressionItem } from './expression-item';\n\nexport type ExpressionListProps = {\n //\n};\n\nexport const ExpressionList: React.FC<ExpressionListProps> = ({}) => {\n const { expressions, addRowBelow, permission, disabled, inputVariableType } = useExpressionStore(\n ({ expressions, addRowBelow, permission, disabled, inputVariableType }) => ({\n expressions,\n addRowBelow,\n permission,\n disabled,\n inputVariableType,\n }),\n equal,\n );\n\n const [variableType, setVariableType] = useState<VariableType>();\n\n useEffect(() => {\n if (!isWasmAvailable() || !inputVariableType) {\n return;\n }\n\n const resultingVariableType = inputVariableType.clone();\n expressions\n .filter((e) => e.key.length > 0)\n .forEach((expr) => {\n const calculatedType = resultingVariableType.calculateType(expr.value);\n resultingVariableType.set(`$.${expr.key}`, calculatedType);\n });\n\n setVariableType(resultingVariableType);\n }, [expressions, inputVariableType]);\n\n const listClass = 'flex flex-col box-border gap-px pb-px bg-[var(--grl-color-border-fade)]';\n const itemClass =\n 'relative grid grid-cols-[40px_minmax(240px,1.1fr)_3fr_40px] items-start bg-[var(--grl-color-bg-container)] focus-within:[box-shadow:0_0_0_1px_var(--border)]';\n const thClass = 'p-3 pointer-events-none';\n\n return (\n <>\n <div className={listClass}>\n <div className={clsx(itemClass, 'sticky top-0 z-[15] [&>span]:text-xs')}>\n <div className={clsx(thClass, 'h-full')} />\n <Typography.Text type='secondary' className={thClass}>\n Key\n </Typography.Text>\n <Typography.Text type='secondary' className={thClass}>\n Expression\n </Typography.Text>\n <div />\n </div>\n {(expressions || []).map((expression, index) => (\n <ExpressionItem key={expression.id} expression={expression} index={index} variableType={variableType} />\n ))}\n </div>\n {permission === 'edit:full' && !disabled && (\n <div className='py-2 mb-[60px]'>\n <Button icon={<PlusCircleOutlined />} type='link' onClick={() => addRowBelow()}>\n Add row\n </Button>\n </div>\n )}\n </>\n );\n};\n","import { DndContext, DragOverlay, PointerSensor, useSensor, useSensors } from '@dnd-kit/core';\nimport { Variable, VariableType } from '@gorules/zen-engine-wasm';\nimport equal from 'fast-deep-equal/es6/react';\nimport React, { useEffect, useRef, useState } from 'react';\n\nimport { DragOverlayCard, OverlayChip, OverlayIndexChip } from '../../helpers/dnd-overlay';\nimport { isWasmAvailable } from '../../helpers/wasm';\nimport { SafeBoundary } from '../safe-boundary';\nimport type { ExpressionDebug } from './context/expression-store.context';\nimport { ExpressionStoreProvider, useExpressionStoreRaw } from './context/expression-store.context';\nimport { ExpressionCommandBar } from './expression-command-bar';\nimport type { ExpressionControllerProps } from './expression-controller';\nimport { ExpressionController } from './expression-controller';\nimport { ExpressionList } from './expression-list';\n\nexport type ExpressionProps = {\n inputVariableType?: VariableType;\n debug?: ExpressionDebug;\n hideCommandBar?: boolean;\n} & ExpressionControllerProps;\n\nexport const Expression: React.FC<ExpressionProps> = ({ debug, hideCommandBar, inputVariableType, ...props }) => {\n const [_, setMounted] = useState(false);\n const container = useRef<HTMLDivElement>(null);\n\n useEffect(() => {\n setMounted(true);\n }, []);\n\n return (\n <SafeBoundary>\n <div ref={container}>\n {container.current && (\n <ExpressionStoreProvider>\n <ExpressionDnd>\n <ExpressionController {...props} />\n {!hideCommandBar && <ExpressionCommandBar />}\n <ExpressionList />\n <SimulateDataSync debug={debug} inputVariableType={inputVariableType} />\n </ExpressionDnd>\n </ExpressionStoreProvider>\n )}\n </div>\n </SafeBoundary>\n );\n};\n\nconst ExpressionDnd: React.FC<React.PropsWithChildren> = ({ children }) => {\n const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 4 } }));\n const store = useExpressionStoreRaw();\n const [activeIndex, setActiveIndex] = useState<number | null>(null);\n\n // Imperative read: entry content cannot change mid-drag, and a\n // subscription would re-render on every keystroke in any item.\n const activeEntry = activeIndex == null ? undefined : store.getState().expressions[activeIndex];\n\n return (\n <DndContext\n sensors={sensors}\n onDragStart={({ active }) => {\n const index = active.data.current?.index;\n if (typeof index === 'number') {\n setActiveIndex(index);\n }\n }}\n onDragEnd={({ active, over }) => {\n setActiveIndex(null);\n if (!over) {\n return;\n }\n\n const from = active.data.current?.index;\n const to = over.data.current?.index;\n if (from === undefined || to === undefined || from === to) {\n return;\n }\n\n store.getState().swapRows(from, to);\n }}\n onDragCancel={() => setActiveIndex(null)}\n >\n {children}\n <DragOverlay dropAnimation={null}>\n {activeEntry ? (\n <DragOverlayCard>\n <OverlayIndexChip index={activeIndex ?? 0} />\n {activeEntry.key ? <OverlayChip width={140}>{activeEntry.key}</OverlayChip> : null}\n {activeEntry.value ? (\n <OverlayChip width={180}>\n <span style={{ color: 'var(--grl-color-text-tertiary)' }}>{activeEntry.value}</span>\n </OverlayChip>\n ) : null}\n </DragOverlayCard>\n ) : null}\n </DragOverlay>\n </DndContext>\n );\n};\n\nconst SimulateDataSync: React.FC<Pick<ExpressionProps, 'debug' | 'inputVariableType'>> = ({\n debug,\n inputVariableType,\n}) => {\n const expressionStoreRaw = useExpressionStoreRaw();\n\n useEffect(() => {\n expressionStoreRaw.setState({ inputVariableType });\n }, [inputVariableType]);\n\n useEffect(() => {\n const currentState = expressionStoreRaw.getState();\n if (equal(currentState.debug, debug)) {\n return;\n }\n\n expressionStoreRaw.setState({ debug });\n }, [debug]);\n\n useEffect(() => {\n if (!isWasmAvailable()) {\n return;\n }\n\n const isLoop = (store: { debug?: ExpressionDebug; debugIndex: number }) => {\n return store.debug?.snapshot.executionMode === 'loop';\n };\n\n const applyDebug = (state: { debug?: ExpressionDebug; debugIndex: number }) => {\n const inputData = state.debug?.inputData;\n if (!inputData) {\n return;\n }\n\n const varInputData = new Variable(inputData.data);\n if (isLoop(state)) {\n let newInputData = varInputData.get(state.debugIndex).cloneWith('$nodes', inputData.$nodes);\n if (inputData.$) {\n newInputData = newInputData.cloneWith('$', inputData.$);\n }\n\n expressionStoreRaw.setState({\n calculatedInputData: newInputData,\n inputVariableType: VariableType.fromVariable(newInputData),\n });\n } else {\n let newInputData = varInputData.cloneWith('$nodes', inputData.$nodes);\n if (inputData.$) {\n newInputData = newInputData.cloneWith('$', inputData.$);\n }\n\n expressionStoreRaw.setState({\n calculatedInputData: newInputData,\n inputVariableType: VariableType.fromVariable(newInputData),\n });\n }\n };\n\n applyDebug(expressionStoreRaw.getState());\n return expressionStoreRaw.subscribe((state, prevState) => {\n if (state.debugIndex === prevState.debugIndex && state.debug === prevState.debug) {\n return;\n }\n\n applyDebug(state);\n });\n }, []);\n\n return null;\n};\n","import React, { useMemo, useRef } from 'react';\nimport { P, match } from 'ts-pattern';\nimport type { z } from 'zod';\n\nimport type { GetNodeDataResult } from '../../../helpers/node-data';\nimport { getNodeData } from '../../../helpers/node-data';\nimport type { expressionNodeSchema } from '../../../helpers/schema';\nimport { get } from '../../../helpers/utility';\nimport { isWasmAvailable } from '../../../helpers/wasm';\nimport { Expression } from '../../expression';\nimport type { ExpressionPermission } from '../../expression/context/expression-store.context';\nimport { useDecisionGraphActions, useDecisionGraphState } from '../context/dg-store.context';\nimport { useTabSerializer } from '../context/serializer.context';\nimport type { NodeExpressionData } from '../nodes/specifications/expression.specification';\nimport type { SimulationTrace, SimulationTraceDataExpression } from '../simulator/simulation.types';\n\ntype ScrollPosition = { top: number; left: number };\n\nexport type TabExpressionProps = {\n id: string;\n};\n\nexport const TabExpression: React.FC<TabExpressionProps> = ({ id }) => {\n const graphActions = useDecisionGraphActions();\n const scrollContainerRef = useRef<HTMLDivElement | null>(null);\n\n useTabSerializer<ScrollPosition>(id, 'scroll', {\n serialize: () => {\n const el = scrollContainerRef.current;\n if (!el) return { top: 0, left: 0 };\n return { top: el.scrollTop, left: el.scrollLeft };\n },\n restore: (position) => {\n if (!position) return;\n let attempts = 0;\n const apply = () => {\n const el = scrollContainerRef.current;\n if (!el || el.scrollHeight <= el.clientHeight) {\n if (attempts++ < 60) requestAnimationFrame(apply);\n return;\n }\n el.scrollTop = position.top;\n el.scrollLeft = position.left;\n };\n requestAnimationFrame(apply);\n },\n });\n\n const { disabled, content } = useDecisionGraphState(({ disabled, decisionGraph }) => ({\n disabled,\n content: (decisionGraph?.nodes ?? []).find((node) => node.id === id)?.content as NodeExpressionData,\n }));\n\n const { nodeTrace, inputData, nodeSnapshot, viewConfig } = useDecisionGraphState(\n ({ simulate, decisionGraph, viewConfig }) => ({\n nodeTrace: match(simulate)\n .with(\n { result: P.nonNullable },\n ({ result }) => result.trace[id] as SimulationTrace<SimulationTraceDataExpression>,\n )\n .otherwise(() => null),\n inputData: match(simulate)\n .with({ result: P.nonNullable }, ({ result }) => getNodeData(id, { trace: result.trace, decisionGraph }))\n .otherwise(() => null),\n nodeSnapshot: match(simulate)\n .with(\n { result: P.nonNullable },\n ({ result }) =>\n (result.snapshot?.nodes || []).find((n) => n.id === id)?.content as z.infer<\n typeof expressionNodeSchema\n >['content'],\n )\n .otherwise(() => null),\n viewConfig,\n }),\n );\n\n const debug = useMemo(() => {\n if (!nodeTrace || !inputData || !nodeSnapshot) {\n return undefined;\n }\n\n if (!isWasmAvailable()) {\n return { trace: nodeTrace, snapshot: nodeSnapshot };\n }\n\n const $data = Object.fromEntries(\n Object.entries(nodeTrace?.traceData ?? {}).map(([k, v]) => [k, safeJson(v.result)]),\n );\n const extendedInputData: GetNodeDataResult = {\n ...inputData,\n $: $data,\n };\n\n if (content?.inputField) {\n extendedInputData.data = get(extendedInputData.data, content.inputField, {});\n }\n\n return { trace: nodeTrace, inputData: extendedInputData, snapshot: nodeSnapshot };\n }, [nodeTrace, nodeSnapshot, inputData]);\n\n return (\n <div ref={scrollContainerRef} style={{ height: '100%', overflowY: 'auto', boxSizing: 'border-box' }}>\n <Expression\n value={content?.expressions}\n disabled={disabled}\n permission={(viewConfig?.enabled ? viewConfig?.permissions?.[id] : 'edit:full') as ExpressionPermission}\n debug={debug}\n onChange={(val) => {\n graphActions.updateNode(id, (draft) => {\n draft.content.expressions = val;\n return draft;\n });\n }}\n />\n </div>\n );\n};\n\nconst safeJson = (data: string): unknown => {\n try {\n return JSON.parse(data);\n } catch {\n return null;\n }\n};\n","import { ArrowRightOutlined, SyncOutlined } from '#icons';\nimport { VariableType } from '@gorules/zen-engine-wasm';\nimport equal from 'fast-deep-equal/es6/react';\nimport { produce } from 'immer';\nimport _ from 'lodash';\nimport { HashIcon } from 'lucide-react';\nimport React from 'react';\nimport type { z } from 'zod';\n\nimport { useNodeType } from '../../../../helpers/node-type';\nimport type { expressionNodeSchema } from '../../../../helpers/schema';\nimport { Button, Form } from '../../../primitives';\nimport { DiffInput, DiffRadio, DiffSwitch } from '../../../shared';\nimport { DiffCodeEditor } from '../../../shared/diff-ce';\nimport { useDecisionGraphActions, useDecisionGraphState, useNodeDiff } from '../../context/dg-store.context';\nimport { type Diff, type DiffMetadata } from '../../dg-types';\nimport { compareAndUnifyLists, compareStringFields } from '../../diff/comparison';\nimport { TabExpression } from '../../graph/tab-expression';\nimport { GraphNode } from '../graph-node';\nimport type { NodeDecisionTableData } from './decision-table.specification';\nimport type { NodeSpecification } from './specification-types';\nimport { NodeKind } from './specification-types';\n\nexport type Expression = {\n id: string;\n key?: string;\n value?: string;\n};\n\ntype InferredContent = z.infer<typeof expressionNodeSchema>['content'];\n\nexport type NodeExpressionData = Omit<InferredContent, 'expressions'> &\n Diff & {\n expressions: (InferredContent['expressions'][0] & Diff)[];\n };\n\nexport const expressionSpecification: NodeSpecification<NodeExpressionData> = {\n type: NodeKind.Expression,\n icon: <HashIcon size='1em' />,\n displayName: 'Expression',\n documentationUrl: 'https://gorules.io/docs/user-manual/decision-modeling/decisions/expression',\n shortDescription: 'Mapping utility',\n renderTab: ({ id }) => <TabExpression id={id} />,\n getDiffContent: (current, previous) => {\n const newContent = produce(current, (draft) => {\n const fields: DiffMetadata['fields'] = {};\n\n if ((current.executionMode || false) !== (previous.executionMode || false)) {\n _.set(fields, 'executionMode', {\n status: 'modified',\n previousValue: previous.executionMode,\n });\n }\n\n if (!compareStringFields(current.inputField, previous.inputField)) {\n _.set(fields, 'inputField', {\n status: 'modified',\n previousValue: previous.inputField,\n });\n }\n\n if (!compareStringFields(current.outputPath, previous.outputPath)) {\n _.set(fields, 'outputPath', {\n status: 'modified',\n previousValue: previous.outputPath,\n });\n }\n\n if ((current.passThrough || false) !== (previous.passThrough || false)) {\n _.set(fields, 'passThrough', {\n status: 'modified',\n previousValue: previous.passThrough,\n });\n }\n\n const expressions = compareAndUnifyLists(current?.expressions || [], previous?.expressions || [], {\n compareFields: (current, previous) => {\n const hasKeyChange = !compareStringFields(current.key, previous.key);\n const hasValueChange = !compareStringFields(current.value, previous.value);\n\n return {\n hasChanges: hasKeyChange || hasValueChange,\n fields: {\n ...(hasKeyChange && {\n key: {\n status: 'modified',\n previousValue: previous.key,\n },\n }),\n ...(hasValueChange && {\n value: {\n status: 'modified',\n previousValue: previous.value,\n },\n }),\n },\n };\n },\n });\n\n draft.expressions = expressions;\n\n if (\n expressions.find(\n (expr) =>\n expr?._diff?.status === 'modified' || expr?._diff?.status === 'added' || expr?._diff?.status === 'removed',\n )\n ) {\n _.set(fields, 'expressions', {\n status: 'modified',\n });\n }\n\n if (Object.keys(fields).length > 0) {\n draft._diff = {\n status: 'modified',\n fields,\n };\n }\n\n return draft;\n });\n return newContent;\n },\n inferTypes: {\n needsUpdate: (content, prevContent) => !equal(content, prevContent),\n determineOutputType: ({ input, content }) => {\n let nodeInput = input.clone();\n let determinedType = VariableType.fromJson({ Object: {} });\n if (content.inputField) {\n nodeInput = input.calculateType(content.inputField);\n }\n\n if (content.executionMode === 'loop') {\n nodeInput = nodeInput.arrayItem();\n }\n\n (content.expressions || []).forEach((expression) => {\n if (!expression.key || !expression.value) {\n return;\n }\n\n const calculatedType = nodeInput.calculateType(expression.value);\n\n nodeInput.set(`$.${expression.key}`, calculatedType);\n determinedType.set(expression.key, calculatedType);\n });\n\n if (content.executionMode === 'loop') {\n determinedType = determinedType.toArray();\n }\n\n if (content.outputPath) {\n const newType = VariableType.fromJson({ Object: {} });\n newType.set(content.outputPath, determinedType);\n determinedType = newType;\n }\n\n if (content.passThrough) {\n determinedType = input.merge(determinedType);\n }\n\n return determinedType;\n },\n },\n generateNode: ({ index }) => ({\n name: `expression${index}`,\n content: {\n inputField: null,\n outputPath: null,\n expressions: [],\n passThrough: true,\n executionMode: 'single',\n },\n }),\n renderNode: ({ id, data, selected, specification }) => {\n const graphActions = useDecisionGraphActions();\n const { passThrough, executionMode } = useDecisionGraphState(({ decisionGraph }) => {\n const content = (decisionGraph?.nodes ?? []).find((node) => node.id === id)?.content as NodeExpressionData;\n return {\n passThrough: content?.passThrough || false,\n executionMode: content?.executionMode,\n };\n });\n\n return (\n <GraphNode\n id={id}\n specification={specification}\n name={data.name}\n isSelected={selected}\n actions={[\n <Button key='edit-table' type='text' onClick={() => graphActions.openTab(id)}>\n Edit Expression\n </Button>,\n ]}\n helper={[executionMode === 'loop' && <SyncOutlined />, passThrough && <ArrowRightOutlined />]}\n />\n );\n },\n renderSettings: ({ id }) => {\n const graphActions = useDecisionGraphActions();\n const inputType = useNodeType(id);\n const { contentDiff } = useNodeDiff(id);\n const { fields, disabled } = useDecisionGraphState(({ decisionGraph, disabled }) => {\n const content = (decisionGraph?.nodes ?? []).find((node) => node.id === id)?.content as NodeDecisionTableData;\n return {\n disabled,\n fields: {\n passThrough: content?.passThrough || false,\n inputField: content?.inputField,\n outputPath: content?.outputPath,\n executionMode: content?.executionMode || 'single',\n },\n };\n });\n\n const updateNode = (data: Partial<NodeExpressionData>) => {\n graphActions.updateNode(id, (draft) => {\n Object.assign(draft.content, data);\n return draft;\n });\n };\n\n return (\n <div className={'settings-form'}>\n <Form.Item label='Passthrough'>\n <DiffSwitch\n disabled={disabled}\n size={'small'}\n displayDiff={contentDiff?.fields?.passThrough?.status === 'modified'}\n checked={fields?.passThrough}\n previousChecked={contentDiff?.fields?.passThrough?.previousValue}\n onChange={(e) => updateNode({ passThrough: e })}\n />\n </Form.Item>\n <Form.Item label='Input field'>\n <DiffCodeEditor\n variableType={inputType}\n disabled={disabled}\n displayDiff={contentDiff?.fields?.inputField?.status === 'modified'}\n previousValue={contentDiff?.fields?.inputField?.previousValue}\n style={{ fontSize: 12, lineHeight: '20px', width: '100%' }}\n expectedVariableType={fields?.executionMode === 'loop' ? { Array: 'Any' } : undefined}\n maxRows={4}\n value={fields?.inputField ?? ''}\n onChange={(val) => {\n updateNode({ inputField: val?.trim() || null });\n }}\n />\n </Form.Item>\n <Form.Item label='Output path'>\n <DiffInput\n size={'small'}\n readOnly={disabled}\n displayDiff={contentDiff?.fields?.outputPath?.status === 'modified'}\n previousValue={contentDiff?.fields?.outputPath?.previousValue}\n value={fields?.outputPath ?? ''}\n onChange={(e) => updateNode({ outputPath: e?.target?.value?.trim() || null })}\n />\n </Form.Item>\n <Form.Item label='Execution mode'>\n <DiffRadio\n size={'small'}\n disabled={disabled}\n displayDiff={contentDiff?.fields?.executionMode?.status === 'modified'}\n previousValue={contentDiff?.fields?.executionMode?.previousValue}\n value={fields?.executionMode}\n onChange={(e) => updateNode({ executionMode: e?.target?.value as 'loop' | 'single' })}\n options={[\n {\n value: 'single',\n label: 'Single',\n },\n {\n value: 'loop',\n label: 'Loop',\n },\n ]}\n />\n </Form.Item>\n </div>\n );\n },\n};\n","// Raw .d.ts sources are inlined for CodeMirror completions. Vite's client\n// types declare `*?raw` modules, so only the @types-scoped path below needs\n// an explicit suppression.\n// @ts-expect-error -- no module declaration for the @types-scoped ?raw path\nimport bigJs from '@types/big.js/index.d.ts?raw';\nimport dayjs from 'dayjs/index.d.ts?raw';\n\nimport defaultFn from './default-function.js?raw';\nimport globalDts from './global.d.ts?raw';\nimport http from './http.d.ts?raw';\nimport zen from './zen.d.ts?raw';\nimport zod from './zod.d.ts?raw';\n\nexport type FunctionLibrary = {\n name: string;\n tagline: string;\n typeDef: string;\n importName?: string;\n documentationUrl?: string;\n};\n\nexport const functionLibraries: FunctionLibrary[] = [\n {\n name: 'big.js',\n tagline: 'Arbitrary-precision decimal arithmetic',\n importName: 'Big',\n typeDef: bigJs,\n documentationUrl: 'https://mikemcl.github.io/big.js/',\n },\n {\n name: 'dayjs',\n tagline: 'Date utilities',\n typeDef: dayjs,\n documentationUrl: 'https://day.js.org/docs/en/parse/parse',\n },\n {\n name: 'http',\n tagline: 'Promise based HTTP client',\n typeDef: http,\n documentationUrl: 'https://docs.gorules.io/reference/http',\n },\n {\n name: 'zen',\n tagline: 'Rules engine utilities',\n typeDef: zen,\n documentationUrl: 'https://docs.gorules.io/reference/zen',\n },\n {\n name: 'zod',\n tagline: 'Schema validation',\n importName: 'z',\n typeDef: zod,\n documentationUrl: 'https://zod.dev/',\n },\n];\n\nexport const functionDefinitions = {\n globals: {\n 'global.d.ts': globalDts,\n },\n};\n\nexport const defaultFunctionValue = defaultFn;\n","import type { Monaco } from '@monaco-editor/react';\nimport type { editor } from 'monaco-editor';\nimport React, { Suspense, useEffect, useMemo, useRef, useState } from 'react';\nimport { P, match } from 'ts-pattern';\n\nimport { useNodeType } from '../../../helpers/node-type';\nimport type { FunctionPermission } from '../../function';\nimport { Spin } from '../../primitives';\nimport {\n useDecisionGraphActions,\n useDecisionGraphListeners,\n useDecisionGraphState,\n useNodeDiff,\n} from '../context/dg-store.context';\nimport { useTabSerializer } from '../context/serializer.context';\nimport { FunctionKind, useFunctionKind } from '../nodes/specifications/function.specification';\nimport type { SimulationTrace, SimulationTraceDataFunction } from '../simulator/simulation.types';\n\nconst Function = React.lazy(async () => {\n const functionImport = await import('../../function');\n return { default: functionImport.Function };\n});\n\nexport type TabFunctionProps = {\n id: string;\n};\n\nexport const TabFunction: React.FC<TabFunctionProps> = ({ id }) => {\n const kind = useFunctionKind(id);\n const graphActions = useDecisionGraphActions();\n const onFunctionReady = useDecisionGraphListeners((s) => s.onFunctionReady);\n const [monaco, setMonaco] = useState<Monaco>();\n const editorRef = useRef<editor.IStandaloneCodeEditor | null>(null);\n const pendingViewStateRef = useRef<editor.ICodeEditorViewState | null>(null);\n\n useTabSerializer<editor.ICodeEditorViewState | null>(id, 'monaco', {\n serialize: () => editorRef.current?.saveViewState() ?? pendingViewStateRef.current ?? null,\n restore: (state) => {\n if (!state) return;\n if (editorRef.current) {\n editorRef.current.restoreViewState(state);\n } else {\n pendingViewStateRef.current = state;\n }\n },\n });\n const nodeType = useNodeType(id);\n const { nodeTrace, disabled, content, nodeError, viewConfig } = useDecisionGraphState(\n ({ simulate, disabled, decisionGraph, viewConfig }) => ({\n nodeTrace: match(simulate)\n .with({ result: P._ }, ({ result }) => result?.trace?.[id])\n .otherwise(() => null),\n nodeError: match(simulate)\n .with({ error: { data: { nodeId: id } } }, ({ error }) => error)\n .otherwise(() => null),\n disabled,\n content: (decisionGraph?.nodes ?? []).find((node) => node.id === id)?.content,\n viewConfig,\n }),\n );\n\n const { diff, contentDiff } = useNodeDiff(id);\n\n const previousValue = useMemo(() => {\n return kind === FunctionKind.Stable\n ? contentDiff?.fields?.source?.previousValue\n : diff?.fields?.content?.previousValue;\n }, [diff, contentDiff]);\n\n useEffect(() => {\n if (!monaco) {\n return;\n }\n\n const extraLibs = monaco.languages.typescript.javascriptDefaults.getExtraLibs();\n const newExtraLibs = Object.entries(extraLibs).map(([key, value]) => ({\n filePath: key,\n content: value.content,\n }));\n\n monaco.languages.typescript.javascriptDefaults.setExtraLibs(newExtraLibs);\n onFunctionReady?.(monaco);\n }, [monaco, onFunctionReady]);\n\n return (\n <Suspense fallback={<Spin />}>\n <Function\n onMonacoReady={(monaco) => setMonaco(monaco)}\n onEditorMount={(editor) => {\n editorRef.current = editor;\n if (pendingViewStateRef.current) {\n editor.restoreViewState(pendingViewStateRef.current);\n pendingViewStateRef.current = null;\n }\n }}\n value={kind === FunctionKind.Stable ? content.source : content}\n previousValue={typeof previousValue === 'string' ? previousValue : undefined}\n error={nodeError ?? undefined}\n inputData={nodeType}\n permission={(viewConfig?.enabled ? viewConfig?.permissions?.[id] : 'edit:full') as FunctionPermission}\n onChange={(val) => {\n graphActions.updateNode(id, (draft) => {\n if (kind === FunctionKind.Stable) {\n draft.content = { source: val };\n } else {\n draft.content = val;\n }\n\n return draft;\n });\n }}\n disabled={disabled}\n trace={nodeTrace as SimulationTrace<SimulationTraceDataFunction>}\n />\n </Suspense>\n );\n};\n","import { WarningFilled } from '#icons';\nimport _ from 'lodash';\nimport React from 'react';\nimport { P, match } from 'ts-pattern';\n\nimport { defaultFunctionValue } from '../../../function/helpers/libs';\nimport { Button, Tooltip, Typography } from '../../../primitives';\nimport { useDecisionGraphActions, useDecisionGraphState } from '../../context/dg-store.context';\nimport type { DiffMetadata } from '../../dg-types';\nimport { TabFunction } from '../../graph/tab-function';\nimport { GraphNode } from '../graph-node';\nimport { NodeColor } from './colors';\nimport type { NodeSpecification } from './specification-types';\nimport { NodeKind } from './specification-types';\n\nexport type NodeFunctionData =\n | string\n | {\n source: string;\n };\n\nexport const functionSpecification: NodeSpecification<NodeFunctionData> = {\n type: NodeKind.Function,\n icon: <Typography.Text style={{ color: 'white', fontSize: 'inherit' }}>JS</Typography.Text>,\n displayName: 'Function',\n documentationUrl: 'https://gorules.io/docs/user-manual/decision-modeling/decisions/functions',\n shortDescription: 'Javascript lambda',\n color: NodeColor.Orange,\n renderTab: ({ id }) => <TabFunction id={id} />,\n getDiffContent: (current, previous): any => {\n const fields: DiffMetadata['fields'] = {};\n const kind = match(current)\n .with(P.string, () => FunctionKind.Deprecated)\n .otherwise(() => FunctionKind.Stable);\n\n match([current, previous])\n .with([P.string, P.string], ([current, previous]) => {\n if (current !== previous) {\n _.set(fields, 'source', {\n previousValue: previous,\n status: 'modified',\n });\n }\n })\n .with([{ source: P.string }, { source: P.string }], ([current, previous]) => {\n if (current?.source !== previous?.source) {\n _.set(fields, 'source', {\n previousValue: previous.source,\n status: 'modified',\n });\n }\n })\n .otherwise(() => {\n // do nothing\n });\n\n const hasModifications = Object.keys(fields).length > 0;\n return {\n ...(kind === FunctionKind.Deprecated ? { source: current } : (current as { source: string })),\n ...(hasModifications && {\n _diff: {\n status: 'modified',\n fields,\n },\n }),\n };\n },\n generateNode: ({ index }) => ({\n name: `function${index}`,\n content: {\n source: defaultFunctionValue,\n },\n }),\n renderNode: ({ id, data, selected, specification }) => {\n const graphActions = useDecisionGraphActions();\n const kind = useFunctionKind(id);\n return (\n <GraphNode\n id={id}\n specification={{\n ...specification,\n displayName:\n kind === FunctionKind.Stable ? (\n 'Function'\n ) : (\n <span>\n {'Function v1 '}\n <DeprecatedFunctionWarning />\n </span>\n ),\n }}\n name={data.name}\n isSelected={selected}\n helper={[kind === FunctionKind.Deprecated && <DeprecatedFunctionWarning size={16} />]}\n actions={[\n <Button key='edit-function' type='text' onClick={() => graphActions.openTab(id)}>\n Edit Function\n </Button>,\n ]}\n />\n );\n },\n};\n\nexport enum FunctionKind {\n Deprecated,\n Stable,\n}\n\nexport const useFunctionKind = (id: string) => {\n const { kind } = useDecisionGraphState((s) => ({\n kind: match(s.decisionGraph.nodes.find((n) => n.id === id)?.content)\n .with(P.string, () => FunctionKind.Deprecated)\n .otherwise(() => FunctionKind.Stable),\n }));\n\n return kind;\n};\n\nconst DeprecatedFunctionWarning: React.FC<{ size?: number }> = ({ size }) => (\n <Tooltip\n placement='top'\n title='Function v1 will be deprecated in one of the upcoming releases. To use a new Function, drag and drop a new Function Node and copy your logic. For more information click \"Documentation\". '\n >\n <WarningFilled style={{ color: 'var(--grl-color-warning-text)', fontSize: size }} />\n </Tooltip>\n);\n","export default function InformationIcon({ className }: { className?: string }) {\n return (\n <svg\n width='24'\n height='24'\n viewBox='0 0 24 24'\n fill='none'\n xmlns='http://www.w3.org/2000/svg'\n className={className}\n >\n <path\n d='M21.92 9.9951L20.51 8.57366C20.4595 8.51914 20.431 8.4478 20.43 8.37345V6.37142C20.4273 5.62183 20.128 4.90384 19.5976 4.37474C19.0671 3.84563 18.3488 3.54854 17.6 3.54855H15.6C15.563 3.54908 15.5263 3.54227 15.492 3.52853C15.4577 3.51479 15.4264 3.49437 15.4 3.46847L14 2.04702C13.4596 1.53521 12.7439 1.25 12 1.25C11.2561 1.25 10.5404 1.53521 9.99998 2.04702L8.58998 3.46847C8.56358 3.49437 8.53231 3.51479 8.49798 3.52853C8.46366 3.54227 8.42695 3.54908 8.38998 3.54855H6.38998C5.64288 3.55119 4.92713 3.84944 4.39885 4.37826C3.87057 4.90708 3.57262 5.62356 3.56998 6.37142V8.37345C3.56723 8.44744 3.53896 8.51818 3.48998 8.57366L2.07998 9.9951C1.81633 10.2574 1.6071 10.5694 1.46432 10.913C1.32155 11.2566 1.24805 11.625 1.24805 11.9971C1.24805 12.3693 1.32155 12.7377 1.46432 13.0813C1.6071 13.4249 1.81633 13.7368 2.07998 13.9992L3.48998 15.4006C3.54073 15.4509 3.5695 15.5193 3.56998 15.5908V17.5928C3.56998 18.3441 3.86814 19.0647 4.39887 19.596C4.9296 20.1272 5.64942 20.4257 6.39998 20.4257H8.39998C8.43725 20.4225 8.47474 20.4281 8.50946 20.442C8.54419 20.4559 8.57518 20.4778 8.59998 20.5058L9.99998 21.9172C10.2621 22.1811 10.5737 22.3906 10.9169 22.5335C11.2602 22.6764 11.6282 22.75 12 22.75C12.3717 22.75 12.7398 22.6764 13.083 22.5335C13.4263 22.3906 13.7379 22.1811 14 21.9172L15.41 20.5058C15.4348 20.4778 15.4658 20.4559 15.5005 20.442C15.5352 20.4281 15.5727 20.4225 15.61 20.4257H17.61C18.3605 20.4257 19.0804 20.1272 19.6111 19.596C20.1418 19.0647 20.44 18.3441 20.44 17.5928V15.5908C20.4405 15.5193 20.4692 15.4509 20.52 15.4006L21.92 13.9992C22.1836 13.7368 22.3929 13.4249 22.5356 13.0813C22.6784 12.7377 22.7519 12.3693 22.7519 11.9971C22.7519 11.625 22.6784 11.2566 22.5356 10.913C22.3929 10.5694 22.1836 10.2574 21.92 9.9951ZM20.86 12.9281L19.45 14.3495C19.2837 14.5124 19.152 14.7071 19.0626 14.9221C18.9733 15.1371 18.9282 15.3679 18.93 15.6008V17.6028C18.9274 17.9551 18.7864 18.2922 18.5375 18.5413C18.2887 18.7905 17.9519 18.9316 17.6 18.9342H15.6C15.3658 18.9316 15.1335 18.9764 14.9169 19.0658C14.7004 19.1552 14.5042 19.2875 14.34 19.4547L12.93 20.8661C12.6757 21.1062 12.3395 21.2399 11.99 21.2399C11.6405 21.2399 11.3042 21.1062 11.05 20.8661L9.64998 19.4447C9.48543 19.278 9.28912 19.146 9.07269 19.0566C8.85626 18.9672 8.62411 18.9222 8.38998 18.9242H6.38998C6.03805 18.9216 5.70128 18.7804 5.45242 18.5313C5.20356 18.2822 5.0626 17.9451 5.05998 17.5928V15.5908C5.0618 15.3579 5.01668 15.1271 4.92734 14.9121C4.83799 14.6971 4.70624 14.5024 4.53998 14.3395L3.13998 12.9181C3.01692 12.7953 2.91928 12.6494 2.85266 12.4888C2.78604 12.3282 2.75174 12.156 2.75174 11.9821C2.75174 11.8082 2.78604 11.636 2.85266 11.4754C2.91928 11.3148 3.01692 11.1689 3.13998 11.0462L4.54998 9.63473C4.71563 9.46934 4.84688 9.2727 4.93614 9.05621C5.02539 8.83972 5.07089 8.60766 5.06998 8.37345V6.37142C5.07262 6.02006 5.21391 5.68399 5.46305 5.43647C5.71219 5.18896 6.04897 5.05006 6.39998 5.05007H8.39998C8.87191 5.04862 9.32439 4.86169 9.65998 4.52955L11.07 3.1081C11.3242 2.86806 11.6605 2.73436 12.01 2.73436C12.3595 2.73436 12.6957 2.86806 12.95 3.1081L14.36 4.52955C14.6956 4.86169 15.1481 5.04862 15.62 5.05007H17.62C17.971 5.05006 18.3078 5.18896 18.5569 5.43647C18.8061 5.68399 18.9473 6.02006 18.95 6.37142V8.37345C18.9514 8.84586 19.1382 9.2988 19.47 9.63473L20.88 11.0462C21.0017 11.1702 21.0978 11.3171 21.1627 11.4785C21.2277 11.6398 21.2601 11.8124 21.2583 11.9863C21.2564 12.1602 21.2203 12.332 21.1519 12.4919C21.0836 12.6518 20.9844 12.7966 20.86 12.9181V12.9281ZM12 13.3987C12.2652 13.3987 12.5196 13.2932 12.7071 13.1055C12.8946 12.9178 13 12.6632 13 12.3977V7.73295C13 7.46746 12.8946 7.21285 12.7071 7.02513C12.5196 6.8374 12.2652 6.73193 12 6.73193C11.7348 6.73193 11.4804 6.8374 11.2929 7.02513C11.1053 7.21285 11 7.46746 11 7.73295V12.3977C11 12.6632 11.1053 12.9178 11.2929 13.1055C11.4804 13.2932 11.7348 13.3987 12 13.3987ZM13.25 16.011C13.25 16.7021 12.6903 17.2623 12 17.2623C11.3096 17.2623 10.75 16.7021 10.75 16.011C10.75 15.32 11.3096 14.7598 12 14.7598C12.6903 14.7598 13.25 15.32 13.25 16.011Z'\n fill='currentColor'\n />\n </svg>\n );\n}\n","import type { Monaco } from '@monaco-editor/react';\nimport { loader } from '@monaco-editor/react';\n\ndeclare global {\n interface Window {\n monaco?: Monaco;\n }\n}\n\nif (self.monaco) {\n loader.config({ monaco: self.monaco });\n}\n","import { CheckOutlined, CloseOutlined } from '#icons';\nimport React, { useEffect, useRef, useState } from 'react';\n\nimport { Button, Input, Space, Tooltip } from '../../primitives';\n\nexport type BlurCommitInputProps = {\n disabled?: boolean;\n placeholder?: string;\n value: string;\n onCommit: (value: string) => void;\n onExit?: () => void;\n blurBehavior?: 'save' | 'cancel';\n saveLabel?: string;\n cancelLabel?: string;\n showActions?: boolean;\n};\n\nexport const BlurCommitInput: React.FC<BlurCommitInputProps> = ({\n disabled,\n placeholder,\n value,\n onCommit,\n onExit,\n blurBehavior = 'save',\n saveLabel = 'Save',\n cancelLabel = 'Cancel',\n showActions = false,\n}) => {\n const [draft, setDraft] = useState(value);\n const lastCommittedValueRef = useRef(value);\n const blurCommitTimerRef = useRef<number | null>(null);\n\n useEffect(() => {\n setDraft(value);\n lastCommittedValueRef.current = value;\n }, [value]);\n\n useEffect(() => {\n return () => {\n if (blurCommitTimerRef.current !== null) {\n window.clearTimeout(blurCommitTimerRef.current);\n }\n };\n }, []);\n\n const commitDraft = () => {\n if (draft === lastCommittedValueRef.current) {\n return;\n }\n\n lastCommittedValueRef.current = draft;\n onCommit(draft);\n };\n\n const scheduleCommitDraft = () => {\n if (blurCommitTimerRef.current !== null) {\n window.clearTimeout(blurCommitTimerRef.current);\n }\n\n blurCommitTimerRef.current = window.setTimeout(() => {\n blurCommitTimerRef.current = null;\n commitDraft();\n }, 0);\n };\n\n const cancelScheduledCommit = () => {\n if (blurCommitTimerRef.current === null) {\n return;\n }\n\n window.clearTimeout(blurCommitTimerRef.current);\n blurCommitTimerRef.current = null;\n };\n\n const handleSave = () => {\n cancelScheduledCommit();\n commitDraft();\n onExit?.();\n };\n\n const handleCancel = () => {\n cancelScheduledCommit();\n setDraft(value);\n onExit?.();\n };\n\n return (\n <Input\n disabled={disabled}\n placeholder={placeholder}\n value={draft}\n onChange={(event) => setDraft(event.target.value)}\n onBlur={() => {\n if (blurBehavior === 'cancel') {\n handleCancel();\n } else {\n scheduleCommitDraft();\n onExit?.();\n }\n }}\n onFocus={cancelScheduledCommit}\n onKeyDown={(event) => {\n if (event.key === 'Enter') {\n handleSave();\n }\n }}\n suffix={\n showActions ? (\n <Space size={4}>\n <Tooltip title={saveLabel}>\n <Button\n type='text'\n size='small'\n icon={<CheckOutlined style={{ fontSize: 12 }} />}\n onMouseDown={(e) => e.preventDefault()}\n onClick={handleSave}\n />\n </Tooltip>\n <Tooltip title={cancelLabel}>\n <Button\n type='text'\n size='small'\n icon={<CloseOutlined style={{ fontSize: 12 }} />}\n onMouseDown={(e) => e.preventDefault()}\n onClick={handleCancel}\n />\n </Tooltip>\n </Space>\n ) : undefined\n }\n />\n );\n};\n","import { DeleteOutlined, DownOutlined, PlusCircleOutlined, PlusOutlined, RightOutlined } from '#icons';\nimport React from 'react';\n\nimport type { RequestDefinition, RequestDefinitionType } from '../../../helpers/request-schema';\nimport { useT } from '../../../theming/i18n';\nimport { Button, Popconfirm, Select, Tooltip } from '../../primitives';\nimport { BlurCommitInput } from './blur-commit-input';\n\nexport type RequestDefinitionsProps = {\n rootDefinitions: RequestDefinition[];\n childrenMap: Map<string, RequestDefinition[]>;\n collapsedPaths: Record<string, boolean>;\n disabled: boolean;\n definitionTypeOptions: Array<{ value: RequestDefinitionType; label: string }>;\n onAdd: () => void;\n onUpdateName: (index: number, name: string) => void;\n onUpdateType: (index: number, type: RequestDefinitionType) => void;\n onUpdateDescription: (index: number, description: string) => void;\n onUpdateDefaultValue: (index: number, defaultValue: string) => void;\n onAddChild: (index: number) => void;\n onRemove: (index: number) => void;\n onToggleCollapse: (path: string) => void;\n getDefinitionIndex: (definitionId: string) => number;\n};\n\ntype DefinitionCardProps = Omit<RequestDefinitionsProps, 'rootDefinitions' | 'onAdd'> & {\n definition: RequestDefinition;\n definitionIndex: number;\n};\n\nconst GRID_COLS =\n 'grid grid-cols-[minmax(120px,200px)_minmax(100px,150px)_minmax(100px,150px)_minmax(180px,320px)_88px] gap-3 items-start';\n\nconst DefinitionCard: React.FC<DefinitionCardProps> = ({\n definition,\n childrenMap,\n collapsedPaths,\n disabled,\n definitionTypeOptions,\n definitionIndex,\n onUpdateName,\n onUpdateType,\n onUpdateDescription,\n onUpdateDefaultValue,\n onAddChild,\n onRemove,\n onToggleCollapse,\n getDefinitionIndex,\n}) => {\n const t = useT();\n\n const childDefinitions = childrenMap.get(definition.path) ?? [];\n const hasChildDefinitions = childDefinitions.length > 0;\n const canAddChild = definition.type === 'object' || hasChildDefinitions;\n const canToggleChildren = hasChildDefinitions;\n const isCollapsed = Boolean(collapsedPaths[definition.path]);\n const depthOffset = `calc(min(${definition.depth} * 12px, 24px) + 4px)`;\n\n const isInTree = definition.depth > 0;\n\n return (\n <div\n key={definition.id}\n className={isInTree ? 'overflow-visible' : 'overflow-hidden rounded-xl border border-border bg-card shadow-sm'}\n >\n <div className={`${GRID_COLS} p-3 ${isInTree ? '!px-0' : ''}`}>\n <div\n className='relative min-w-0 pl-[var(--depth-offset)] [--depth-offset:4px]'\n style={{ '--depth-offset': depthOffset } as React.CSSProperties}\n >\n <div className='flex w-full min-w-0 items-center gap-2'>\n {definition.depth > 0 && (\n <span aria-hidden className='pointer-events-none absolute inset-y-1.5 left-0 w-px bg-border opacity-70' />\n )}\n {canToggleChildren ? (\n <Button\n type='text'\n size='small'\n disabled={disabled}\n className='!h-6 !w-6 shrink-0 !p-0 opacity-60'\n icon={\n isCollapsed ? <RightOutlined style={{ fontSize: 11 }} /> : <DownOutlined style={{ fontSize: 11 }} />\n }\n onClick={() => onToggleCollapse(definition.path)}\n />\n ) : (\n <span aria-hidden className='h-6 w-6 shrink-0' />\n )}\n <BlurCommitInput\n disabled={disabled}\n placeholder={\n definition.depth > 0 ? t('request.childFieldNamePlaceholder') : t('request.fieldNamePlaceholder')\n }\n value={definition.name}\n onCommit={(nextValue) => onUpdateName(definitionIndex, nextValue)}\n />\n </div>\n </div>\n <Select\n disabled={disabled}\n options={definitionTypeOptions}\n value={definition.type}\n onChange={(value) => onUpdateType(definitionIndex, value)}\n />\n <BlurCommitInput\n disabled={disabled}\n placeholder={t('request.fieldDefaultValuePlaceholder')}\n value={definition.defaultValue ?? ''}\n onCommit={(nextValue) => onUpdateDefaultValue(definitionIndex, nextValue)}\n />\n <BlurCommitInput\n disabled={disabled}\n placeholder={t('request.fieldDescriptionPlaceholder')}\n value={definition.description}\n onCommit={(nextValue) => onUpdateDescription(definitionIndex, nextValue)}\n />\n <div className='flex items-center justify-end gap-1'>\n {canAddChild && (\n <Tooltip title={t('request.addChildField')}>\n <Button\n type='text'\n size='small'\n disabled={disabled || !definition.name.trim()}\n icon={<PlusOutlined />}\n onClick={() => onAddChild(definitionIndex)}\n />\n </Tooltip>\n )}\n <Popconfirm\n title={t('request.deleteFieldConfirm')}\n okText={t('common.delete')}\n cancelText={t('common.cancel')}\n disabled={disabled}\n onConfirm={() => onRemove(definitionIndex)}\n >\n <Button danger type='text' disabled={disabled} icon={<DeleteOutlined />} />\n </Popconfirm>\n </div>\n </div>\n\n {hasChildDefinitions && !isCollapsed && (\n <div className='relative mx-3 mb-3 flex flex-col gap-1.5 pb-2 pl-[22px]'>\n <span\n aria-hidden\n className='pointer-events-none absolute bottom-2.5 left-2 top-1 w-px bg-border opacity-70'\n />\n {childDefinitions.map((childDefinition) => (\n <DefinitionCard\n key={childDefinition.id}\n definition={childDefinition}\n childrenMap={childrenMap}\n collapsedPaths={collapsedPaths}\n disabled={disabled}\n definitionTypeOptions={definitionTypeOptions}\n definitionIndex={getDefinitionIndex(childDefinition.id)}\n onUpdateName={onUpdateName}\n onUpdateType={onUpdateType}\n onUpdateDescription={onUpdateDescription}\n onUpdateDefaultValue={onUpdateDefaultValue}\n onAddChild={onAddChild}\n onRemove={onRemove}\n onToggleCollapse={onToggleCollapse}\n getDefinitionIndex={getDefinitionIndex}\n />\n ))}\n </div>\n )}\n </div>\n );\n};\n\nexport const RequestDefinitions: React.FC<RequestDefinitionsProps> = ({\n rootDefinitions,\n childrenMap,\n collapsedPaths,\n disabled,\n definitionTypeOptions,\n onAdd,\n onUpdateName,\n onUpdateType,\n onUpdateDescription,\n onUpdateDefaultValue,\n onAddChild,\n onRemove,\n onToggleCollapse,\n getDefinitionIndex,\n}) => {\n const t = useT();\n\n return (\n <div className='flex h-full min-h-0 flex-col gap-2'>\n <div className='min-h-0 flex-1 space-y-2.5 overflow-y-auto'>\n <div\n className={`${GRID_COLS} rounded-xl border border-border bg-muted/40 px-3.5 py-3 text-xs font-semibold uppercase tracking-wide text-foreground opacity-70`}\n >\n <span>{t('request.key')}</span>\n <span>{t('request.type')}</span>\n <span>{t('request.fieldDefaultValuePlaceholder')}</span>\n <span>{t('request.description')}</span>\n <span />\n </div>\n\n {rootDefinitions.length === 0 ? (\n <div className='flex flex-col items-center gap-1 py-10 text-xs text-muted-foreground'>\n <span>{t('request.noDefinitions')}</span>\n </div>\n ) : (\n rootDefinitions.map((definition) => (\n <DefinitionCard\n key={definition.id}\n definition={definition}\n childrenMap={childrenMap}\n collapsedPaths={collapsedPaths}\n disabled={disabled}\n definitionTypeOptions={definitionTypeOptions}\n definitionIndex={getDefinitionIndex(definition.id)}\n onUpdateName={onUpdateName}\n onUpdateType={onUpdateType}\n onUpdateDescription={onUpdateDescription}\n onUpdateDefaultValue={onUpdateDefaultValue}\n onAddChild={onAddChild}\n onRemove={onRemove}\n onToggleCollapse={onToggleCollapse}\n getDefinitionIndex={getDefinitionIndex}\n />\n ))\n )}\n </div>\n\n <div className='pb-3 pt-0.5'>\n <Button className='!pl-0' type='link' icon={<PlusCircleOutlined />} disabled={disabled} onClick={onAdd}>\n {t('request.addField')}\n </Button>\n </div>\n </div>\n );\n};\n","import React from 'react';\n\nimport type { RequestDefinition, RequestDefinitionType } from '../../../helpers/request-schema';\nimport { useT } from '../../../theming/i18n';\nimport { Space, Typography } from '../../primitives';\n\nexport type RequestExampleSummaryData = {\n definitions: RequestDefinition[];\n conflicts: Array<{ path: string; nextType: RequestDefinitionType }>;\n missing: RequestDefinition[];\n extra: string[];\n};\n\nexport type RequestExampleSummaryProps = {\n summary: RequestExampleSummaryData | null;\n getDefinitionTypeLabel: (type: RequestDefinitionType) => string;\n};\n\nexport const RequestExampleSummary: React.FC<RequestExampleSummaryProps> = ({ summary, getDefinitionTypeLabel }) => {\n const t = useT();\n\n if (!summary) {\n return null;\n }\n\n const { definitions, conflicts, missing, extra } = summary;\n const hasIssues = missing.length > 0 || extra.length > 0 || conflicts.length > 0;\n\n return (\n <div className='space-y-1'>\n <div className='flex items-center justify-between'>\n <Typography.Text strong className='text-xs'>\n {t('request.exampleFieldSummary')}\n </Typography.Text>\n <Space size={10} className='flex-wrap'>\n <Typography.Text type='secondary' className='text-xs'>\n {t('request.exampleFieldSummaryDefinitions')}: {definitions.length}\n </Typography.Text>\n <Typography.Text className='text-xs text-warning-foreground'>\n {t('request.exampleFieldSummaryMissing')}: {missing.length}\n </Typography.Text>\n <Typography.Text type='secondary' className='text-xs'>\n {t('request.exampleFieldSummaryExtra')}: {extra.length}\n </Typography.Text>\n <Typography.Text type='secondary' className='text-xs'>\n {t('request.exampleFieldSummaryConflicts')}: {conflicts.length}\n </Typography.Text>\n </Space>\n </div>\n\n {!hasIssues ? (\n <Typography.Text type='secondary' className='text-xs'>\n {t('request.exampleFieldSummaryAllMatch')}\n </Typography.Text>\n ) : (\n <div className='space-y-0.5'>\n {missing.map((definition) => (\n <div key={definition.id} className='flex items-center gap-2 text-xs'>\n <span className='h-1.5 w-1.5 shrink-0 rounded-full bg-warning-foreground' />\n <span className='truncate' title={definition.path}>\n {definition.path}\n </span>\n <Typography.Text type='secondary' className='shrink-0 text-xs'>\n {t('request.exampleFieldSummaryMissing')} · {getDefinitionTypeLabel(definition.type)}\n </Typography.Text>\n </div>\n ))}\n {extra.map((entryPath) => (\n <div key={`extra-${entryPath}`} className='flex items-center gap-2 text-xs'>\n <span className='h-1.5 w-1.5 shrink-0 rounded-full bg-sky-500' />\n <span className='truncate' title={entryPath}>\n {entryPath}\n </span>\n <Typography.Text type='secondary' className='shrink-0 text-xs'>\n {t('request.exampleFieldSummaryExtra')}\n </Typography.Text>\n </div>\n ))}\n {conflicts.map((conflict) => (\n <div key={`conflict-${conflict.path}`} className='flex items-center gap-2 text-xs'>\n <span className='h-1.5 w-1.5 shrink-0 rounded-full bg-destructive' />\n <span className='truncate' title={conflict.path}>\n {conflict.path}\n </span>\n <Typography.Text type='secondary' className='shrink-0 text-xs'>\n {t('request.exampleFieldSummaryConflicts')} · {getDefinitionTypeLabel(conflict.nextType)}\n </Typography.Text>\n </div>\n ))}\n </div>\n )}\n </div>\n );\n};\n","export interface JsonFieldInfo {\n path: string;\n name: string;\n line: number;\n column: number;\n lineEnd: number;\n lineEndColumn: number;\n}\n\nconst isWhitespace = (char: string): boolean => {\n return /\\s/.test(char);\n};\n\nconst isQuote = (char: string): boolean => {\n return char === '\"' || char === \"'\";\n};\n\nconst parseString = (\n text: string,\n startIndex: number,\n currentLine: number,\n currentColumn: number,\n): { value: string; endIndex: number; endLine: number; endColumn: number } => {\n const quoteChar = text[startIndex];\n let value = '';\n let i = startIndex + 1;\n let line = currentLine;\n let column = currentColumn;\n let escaped = false;\n\n while (i < text.length) {\n const char = text[i];\n\n if (escaped) {\n value += char;\n escaped = false;\n } else if (char === '\\\\') {\n escaped = true;\n } else if (char === quoteChar) {\n return { value, endIndex: i, endLine: line, endColumn: column + 1 };\n } else {\n value += char;\n }\n\n if (char === '\\n') {\n line++;\n column = 1;\n } else {\n column++;\n }\n i++;\n }\n\n return { value, endIndex: text.length - 1, endLine: line, endColumn: column };\n};\n\nexport const extractJsonFields = (jsonText: string): JsonFieldInfo[] => {\n const fields: JsonFieldInfo[] = [];\n const pathStack: string[] = [];\n let i = 0;\n let line = 1;\n let column = 1;\n\n // Precompute, for every line, the column just past its last non-whitespace char,\n // so each field's end position can be looked up in O(1) instead of rescanning the file.\n const lineEndByLine: number[] = [0];\n let scanLine = 1;\n let scanColumn = 1;\n let lastNonWhitespaceColumn = 1;\n for (let idx = 0; idx < jsonText.length; idx++) {\n const char = jsonText[idx];\n if (char === '\\n') {\n lineEndByLine[scanLine] = lastNonWhitespaceColumn + 1;\n scanLine++;\n scanColumn = 1;\n lastNonWhitespaceColumn = 1;\n } else {\n if (!isWhitespace(char)) {\n lastNonWhitespaceColumn = scanColumn;\n }\n scanColumn++;\n }\n }\n lineEndByLine[scanLine] = lastNonWhitespaceColumn + 1;\n\n const skipWhitespace = () => {\n while (i < jsonText.length && isWhitespace(jsonText[i])) {\n if (jsonText[i] === '\\n') {\n line++;\n column = 1;\n } else {\n column++;\n }\n i++;\n }\n };\n\n const parseValue = () => {\n skipWhitespace();\n\n if (i >= jsonText.length) return;\n\n const char = jsonText[i];\n\n if (char === '{') {\n parseObject();\n } else if (char === '[') {\n parseArray();\n } else if (isQuote(char)) {\n const result = parseString(jsonText, i, line, column);\n i = result.endIndex + 1;\n line = result.endLine;\n column = result.endColumn;\n } else if (char === 't' || char === 'f') {\n // true or false\n while (i < jsonText.length && /[a-z]/.test(jsonText[i])) {\n i++;\n column++;\n }\n } else if (char === 'n') {\n // null\n while (i < jsonText.length && /[a-z]/.test(jsonText[i])) {\n i++;\n column++;\n }\n } else if (char === '-' || /[0-9]/.test(char)) {\n // number\n while (i < jsonText.length && /[0-9.eE+\\-]/.test(jsonText[i])) {\n i++;\n column++;\n }\n }\n };\n\n const parseObject = () => {\n i++; // skip {\n column++;\n skipWhitespace();\n\n while (i < jsonText.length && jsonText[i] !== '}') {\n skipWhitespace();\n\n if (jsonText[i] === '}') break;\n\n // Parse key\n if (!isQuote(jsonText[i])) break;\n\n const keyStartLine = line;\n const keyStartColumn = column;\n const result = parseString(jsonText, i, line, column);\n const key = result.value;\n\n i = result.endIndex + 1;\n line = result.endLine;\n column = result.endColumn;\n\n const fieldPath = pathStack.length > 0 ? `${pathStack.join('.')}.${key}` : key;\n\n // Find the end of this line\n const lineEndInfo = lineEndByLine[keyStartLine] ?? 1;\n\n fields.push({\n path: fieldPath,\n name: key,\n line: keyStartLine,\n column: keyStartColumn,\n lineEnd: keyStartLine,\n lineEndColumn: lineEndInfo,\n });\n\n skipWhitespace();\n\n // Expect colon\n if (jsonText[i] !== ':') break;\n i++;\n column++;\n\n skipWhitespace();\n\n // Parse value\n const valueChar = jsonText[i];\n if (valueChar === '{') {\n pathStack.push(key);\n parseObject();\n pathStack.pop();\n } else if (valueChar === '[') {\n pathStack.push(key);\n parseArray();\n pathStack.pop();\n } else {\n parseValue();\n }\n\n skipWhitespace();\n\n // Expect comma or end\n if (jsonText[i] === ',') {\n i++;\n column++;\n }\n }\n\n if (i < jsonText.length && jsonText[i] === '}') {\n i++;\n column++;\n }\n };\n\n const parseArray = () => {\n i++; // skip [\n column++;\n skipWhitespace();\n\n let index = 0;\n while (i < jsonText.length && jsonText[i] !== ']') {\n skipWhitespace();\n\n if (jsonText[i] === ']') break;\n\n const valueChar = jsonText[i];\n if (valueChar === '{') {\n pathStack.push(String(index));\n parseObject();\n pathStack.pop();\n } else if (valueChar === '[') {\n pathStack.push(String(index));\n parseArray();\n pathStack.pop();\n } else {\n parseValue();\n }\n\n index++;\n skipWhitespace();\n\n if (jsonText[i] === ',') {\n i++;\n column++;\n }\n }\n\n if (i < jsonText.length && jsonText[i] === ']') {\n i++;\n column++;\n }\n };\n\n parseValue();\n\n return fields;\n};\n","import type * as monacoModule from 'monaco-editor';\nimport type { editor, languages } from 'monaco-editor';\n\nimport { extractJsonFields } from '../../../helpers/json-path-extractor';\nimport type { RequestDefinition } from '../../../helpers/request-schema';\n\nexport function registerJsonInlayHintsProvider(\n monaco: typeof monacoModule,\n targetModel: editor.ITextModel,\n getDefinitions: () => RequestDefinition[],\n): { dispose(): void } {\n return monaco.languages.registerInlayHintsProvider('json', {\n provideInlayHints: (model: editor.ITextModel): languages.InlayHintList => {\n try {\n if (model !== targetModel) {\n return { hints: [], dispose: () => {} };\n }\n\n const jsonText = model.getValue();\n const fields = extractJsonFields(jsonText);\n const descriptionMap = new Map<string, string>();\n\n const definitions = getDefinitions();\n definitions.forEach((def) => {\n if (def.description && def.description.trim()) {\n descriptionMap.set(def.path, def.description.trim());\n }\n });\n\n const hints: languages.InlayHint[] = [];\n\n fields.forEach((field) => {\n const description = descriptionMap.get(field.path);\n if (description) {\n hints.push({\n kind: monaco.languages.InlayHintKind.Type,\n position: {\n lineNumber: field.lineEnd,\n column: field.lineEndColumn,\n },\n label: `// ${description}`,\n paddingLeft: true,\n });\n }\n });\n\n return { hints, dispose: () => {} };\n } catch {\n return { hints: [], dispose: () => {} };\n }\n },\n });\n}\n","import { CommentOutlined, DeleteOutlined, FormatPainterOutlined, PlusOutlined } from '#icons';\nimport { Editor } from '@monaco-editor/react';\nimport type * as monacoModule from 'monaco-editor';\nimport type { editor } from 'monaco-editor';\nimport React, { useCallback, useEffect, useRef, useState } from 'react';\n\nimport type { RequestDefinition, RequestDefinitionType, RequestExampleSource } from '../../../helpers/request-schema';\nimport { useT } from '../../../theming/i18n';\nimport { AutosizeTextArea } from '../../autosize-text-area';\nimport { Button, Card, Popconfirm, Tooltip, Typography } from '../../primitives';\nimport { BlurCommitInput } from './blur-commit-input';\nimport { RequestExampleSummary, type RequestExampleSummaryData } from './request-example-summary';\nimport { registerJsonInlayHintsProvider } from './request-inlay-hints';\n\nexport type RequestExamplesProps = {\n sources: RequestExampleSource[];\n activeSourceIndex: number;\n editingSourceIndex: number | null;\n activeSource: RequestExampleSource | null;\n activeDescriptionDraft: string;\n activeJsonDraft: string;\n disabled: boolean;\n definitionDrafts: RequestDefinition[];\n onSourceSelect: (index: number) => void;\n onSourceAdd: () => void;\n onSourceRemove: (index: number) => void;\n onSourceRename: (index: number, name: string) => void;\n onEnterEditing: (index: number) => void;\n onSourceRenameExit: () => void;\n onDescriptionChange: (value: string) => void;\n onDescriptionCommit: () => void;\n onJsonChange: (value: string) => void;\n onJsonCommit: () => void;\n onFormat: () => void;\n onJsonEditorMount: (instance: editor.IStandaloneCodeEditor) => void;\n summary: RequestExampleSummaryData | null;\n getDefinitionTypeLabel: (type: RequestDefinitionType) => string;\n editorOptions: Record<string, unknown>;\n};\n\nexport const RequestExamples: React.FC<RequestExamplesProps> = ({\n sources,\n activeSourceIndex,\n editingSourceIndex,\n activeSource,\n activeDescriptionDraft,\n activeJsonDraft,\n disabled,\n definitionDrafts,\n onSourceSelect,\n onSourceAdd,\n onSourceRemove,\n onSourceRename,\n onEnterEditing,\n onSourceRenameExit,\n onDescriptionChange,\n onDescriptionCommit,\n onJsonChange,\n onJsonCommit,\n onFormat,\n onJsonEditorMount,\n summary,\n getDefinitionTypeLabel,\n editorOptions,\n}) => {\n const t = useT();\n const [inlayHintsEnabled, setInlayHintsEnabled] = useState(true);\n const blurDisposableRef = useRef<{ dispose: () => void } | null>(null);\n const inlayHintsDisposableRef = useRef<{ dispose: () => void } | null>(null);\n const inlayHintsEnabledRef = useRef(inlayHintsEnabled);\n const monacoInstanceRef = useRef<typeof monacoModule | null>(null);\n const inlayHintsModelRef = useRef<editor.ITextModel | null>(null);\n const onJsonCommitRef = useRef(onJsonCommit);\n const definitionDraftsRef = useRef(definitionDrafts);\n\n useEffect(() => {\n inlayHintsEnabledRef.current = inlayHintsEnabled;\n }, [inlayHintsEnabled]);\n\n const syncInlayHintsProvider = useCallback(() => {\n inlayHintsDisposableRef.current?.dispose();\n inlayHintsDisposableRef.current = null;\n\n const model = inlayHintsModelRef.current;\n const monacoInstance = monacoInstanceRef.current;\n if (inlayHintsEnabledRef.current && monacoInstance && model) {\n inlayHintsDisposableRef.current = registerJsonInlayHintsProvider(\n monacoInstance,\n model,\n () => definitionDraftsRef.current,\n );\n }\n }, []);\n\n useEffect(() => {\n syncInlayHintsProvider();\n }, [inlayHintsEnabled, syncInlayHintsProvider]);\n\n useEffect(() => {\n onJsonCommitRef.current = onJsonCommit;\n });\n\n useEffect(() => {\n definitionDraftsRef.current = definitionDrafts;\n });\n\n useEffect(() => {\n return () => {\n blurDisposableRef.current?.dispose();\n blurDisposableRef.current = null;\n inlayHintsDisposableRef.current?.dispose();\n inlayHintsDisposableRef.current = null;\n };\n }, []);\n\n if (sources.length === 0) {\n return (\n <div className='flex h-full min-h-0 flex-col'>\n <Card className='rounded-xl'>\n <div className='flex flex-col items-center gap-3 py-10 text-xs text-muted-foreground'>\n <span>{t('request.noDataSources')}</span>\n <Button type='primary' icon={<PlusOutlined />} disabled={disabled} onClick={onSourceAdd}>\n {t('request.createDataSource')}\n </Button>\n </div>\n </Card>\n </div>\n );\n }\n\n return (\n <div className='flex h-full min-h-0 flex-col'>\n <div className='flex min-h-0 flex-1 gap-4'>\n <div className='flex w-[220px] shrink-0 flex-col gap-2 overflow-y-auto'>\n {sources.map((source, index) => (\n <div\n key={source.id}\n role='button'\n tabIndex={disabled ? -1 : 0}\n aria-pressed={index === activeSourceIndex}\n className={`flex items-center gap-1 rounded-lg border px-2 py-1.5 transition-colors ${\n index === activeSourceIndex ? 'border-primary/40 bg-primary/10' : 'border-transparent hover:bg-muted/60'\n }`}\n onClick={() => {\n onSourceSelect(index);\n }}\n onKeyDown={(event) => {\n if (event.key === 'Enter' || event.key === ' ') {\n event.preventDefault();\n onSourceSelect(index);\n }\n }}\n >\n <div\n className='min-w-0 flex-1'\n onDoubleClick={(event) => {\n event.stopPropagation();\n if (!disabled) {\n onEnterEditing(index);\n }\n }}\n >\n {editingSourceIndex === index ? (\n <BlurCommitInput\n disabled={disabled}\n value={source.name}\n blurBehavior='cancel'\n saveLabel={t('request.save')}\n cancelLabel={t('common.cancel')}\n showActions={true}\n onCommit={(nextName) => {\n const trimmedName = nextName.trim();\n if (trimmedName) {\n onSourceRename(index, trimmedName);\n }\n }}\n onExit={onSourceRenameExit}\n />\n ) : (\n <Tooltip title={source.description ? `${source.name} — ${source.description}` : source.name}>\n <Typography.Text className='block truncate'>{source.name}</Typography.Text>\n </Tooltip>\n )}\n </div>\n <Popconfirm\n title={t('request.deleteDataSourceConfirm')}\n okText={t('common.delete')}\n cancelText={t('common.cancel')}\n onConfirm={() => onSourceRemove(index)}\n >\n <Button\n danger\n type='text'\n size='small'\n disabled={disabled}\n icon={<DeleteOutlined />}\n onClick={(event) => event.stopPropagation()}\n />\n </Popconfirm>\n </div>\n ))}\n <Tooltip title={t('request.addDataSource')} placement='bottom'>\n <Button type='dashed' size='small' disabled={disabled} icon={<PlusOutlined />} onClick={onSourceAdd} />\n </Tooltip>\n </div>\n\n <div className='flex h-full min-h-0 flex-1 flex-col gap-1.5'>\n <div className='flex items-center justify-between gap-2'>\n <Typography.Text strong className='truncate'>\n {activeSource?.name}\n </Typography.Text>\n <div className='flex items-center gap-1'>\n <Tooltip title={t('request.toggleFieldDescriptionsTooltip')} placement='bottomRight'>\n <Button\n type='text'\n size='small'\n shape='circle'\n icon={<CommentOutlined />}\n className={inlayHintsEnabled ? 'text-primary' : undefined}\n onClick={() => setInlayHintsEnabled((prev) => !prev)}\n disabled={disabled}\n />\n </Tooltip>\n <Tooltip title={t('common.format')} placement='bottomRight'>\n <Button\n type='text'\n size='small'\n shape='circle'\n icon={<FormatPainterOutlined />}\n onClick={onFormat}\n disabled={disabled}\n />\n </Tooltip>\n </div>\n </div>\n <AutosizeTextArea\n className='rounded-md border border-border px-2 py-1 text-xs'\n value={activeDescriptionDraft}\n onChange={(event) => onDescriptionChange(event.target.value)}\n onBlur={onDescriptionCommit}\n placeholder={t('request.exampleDescriptionPlaceholder')}\n disabled={disabled}\n maxRows={4}\n />\n <div className='min-h-0 flex-1 overflow-hidden rounded-md border border-border bg-card'>\n <Editor\n height='100%'\n language='json'\n value={activeJsonDraft}\n onMount={(instance, monacoInstance) => {\n blurDisposableRef.current?.dispose();\n blurDisposableRef.current = instance.onDidBlurEditorText(() => {\n onJsonCommitRef.current();\n });\n\n const model = instance.getModel();\n monacoInstanceRef.current = monacoInstance;\n inlayHintsModelRef.current = model;\n syncInlayHintsProvider();\n onJsonEditorMount(instance);\n }}\n onChange={(value) => onJsonChange(value ?? '')}\n theme={(editorOptions as { theme?: string })?.theme ?? 'light'}\n options={{\n ...editorOptions,\n readOnly: disabled,\n inlayHints: {\n enabled: inlayHintsEnabled ? 'on' : 'off',\n },\n }}\n />\n </div>\n <RequestExampleSummary summary={summary} getDefinitionTypeLabel={getDefinitionTypeLabel} />\n </div>\n </div>\n </div>\n );\n};\n","import { Editor } from '@monaco-editor/react';\nimport json5 from 'json5';\nimport React, { useEffect, useState } from 'react';\nimport { toast } from 'sonner';\nimport toJsonSchema from 'to-json-schema';\n\nimport { copyToClipboard } from '../../../helpers/utility';\nimport { useThemeMode } from '../../../theme';\nimport { useT } from '../../../theming/i18n';\nimport { Modal, Spin, Typography } from '../../primitives';\n\nexport type JsonToJsonSchemaDialogProps = {\n id?: string;\n onSuccess?: (payload: { schema: string; model: string }) => void;\n onDismiss?: () => void;\n isOpen?: boolean;\n model?: string;\n};\n\nexport const JsonToJsonSchemaDialog: React.FC<JsonToJsonSchemaDialogProps> = (props) => {\n const { isOpen, onDismiss, onSuccess, model } = props;\n\n const mode = useThemeMode();\n\n const t = useT();\n const [value, setValue] = useState<string>('');\n\n useEffect(() => {\n if (isOpen && model) {\n setValue(model);\n }\n }, [isOpen]);\n\n return (\n <Modal\n title='Convert to JSON Schema'\n open={isOpen}\n destroyOnClose\n onCancel={onDismiss}\n width={540}\n okText='Convert'\n onOk={() => {\n try {\n onSuccess?.({\n schema: JSON.stringify(toJsonSchema(json5.parse(value)), null, 2),\n model: value,\n });\n } catch (e: any) {\n toast.error(e?.message);\n }\n }}\n >\n <Typography.Text>Type or paste JSON or JSON5 model here and covert it to JSON Schema</Typography.Text>\n <Editor\n loading={<Spin size='large' />}\n language='javascript'\n theme={mode === 'dark' ? 'vs-dark' : 'light'}\n height='400px'\n onChange={(val) => setValue(val || '')}\n value={value || ''}\n onMount={(editor, monaco) => {\n monaco.languages.typescript.javascriptDefaults.setDiagnosticsOptions({\n noSyntaxValidation: true,\n });\n\n monaco.languages.typescript.javascriptDefaults.setModeConfiguration({\n codeActions: false,\n inlayHints: false,\n });\n\n editor.addAction({\n id: 'copy-json',\n label: t('dg.jsonSchema.copyJson'),\n contextMenuGroupId: 'utils',\n run: async (editor) => {\n try {\n await copyToClipboard(JSON.stringify(json5.parse(editor.getValue())));\n toast.success('Copied to clipboard!');\n } catch {\n toast.error('Failed to copy to clipboard.');\n }\n },\n });\n\n editor.addAction({\n id: 'format',\n label: 'Format',\n contextMenuGroupId: 'utils',\n precondition: '!editorReadonly',\n run: (editor) => {\n const formatted = JSON.stringify(json5.parse(editor.getValue()), null, 2);\n editor.setValue(formatted);\n },\n });\n }}\n options={{\n automaticLayout: true,\n minimap: { enabled: false },\n fontSize: 12,\n fontFamily: 'var(--mono-font-family)',\n tabSize: 2,\n lineDecorationsWidth: 2,\n find: {\n addExtraSpaceOnTop: false,\n seedSearchStringFromSelection: 'never',\n },\n scrollbar: {\n verticalSliderSize: 4,\n verticalScrollbarSize: 4,\n horizontalScrollbarSize: 4,\n horizontalSliderSize: 4,\n },\n lineNumbersMinChars: 3,\n }}\n />\n </Modal>\n );\n};\n","import { Editor } from '@monaco-editor/react';\nimport type { editor } from 'monaco-editor';\nimport React, { useEffect, useRef } from 'react';\n\nimport { useT } from '../../../theming/i18n';\nimport { JsonToJsonSchemaDialog } from './json-to-json-schema-dialog';\n\nexport type RequestSchemaEditorProps = {\n schemaDraft: string;\n disabled: boolean;\n onSchemaChange: (value: string) => void;\n onSchemaCommit: () => void;\n jsonToJsonSchemaOpen: boolean;\n onConvertSuccess: (result: { schema: string; model: string }) => void;\n onDismissConvert: () => void;\n onEditorMount: (instance: editor.IStandaloneCodeEditor) => void;\n editorOptions: Record<string, unknown>;\n nodeId: string;\n};\n\nexport const RequestSchemaEditor: React.FC<RequestSchemaEditorProps> = ({\n schemaDraft,\n disabled,\n onSchemaChange,\n onSchemaCommit,\n jsonToJsonSchemaOpen,\n onConvertSuccess,\n onDismissConvert,\n onEditorMount,\n editorOptions,\n nodeId,\n}) => {\n useT();\n const blurDisposableRef = useRef<{ dispose: () => void } | null>(null);\n\n useEffect(() => {\n return () => {\n blurDisposableRef.current?.dispose();\n blurDisposableRef.current = null;\n };\n }, []);\n\n return (\n <div className='flex h-full min-h-0 flex-col gap-2'>\n <div className='min-h-0 flex-1 overflow-hidden rounded-md border border-border bg-card'>\n <Editor\n height='100%'\n language='json'\n value={schemaDraft}\n onMount={(instance) => {\n blurDisposableRef.current?.dispose();\n blurDisposableRef.current = instance.onDidBlurEditorText(() => {\n onSchemaCommit();\n });\n onEditorMount(instance);\n }}\n onChange={(value) => onSchemaChange(value ?? '')}\n theme={(editorOptions as { theme?: string })?.theme ?? 'light'}\n options={{\n ...editorOptions,\n readOnly: disabled,\n }}\n />\n </div>\n <JsonToJsonSchemaDialog\n isOpen={jsonToJsonSchemaOpen}\n onDismiss={onDismissConvert}\n onSuccess={onConvertSuccess}\n model={localStorage.getItem(`${nodeId}-request-model`) || undefined}\n />\n </div>\n );\n};\n","import { useTabSerializer } from '../context/serializer.context';\n\n/**\n * TabRequest 的 UI 会话草稿(serializer tab slice 载荷)。\n * 捕获 700ms 防抖窗口内尚未落 content 的在途编辑——历史条目=完整现场的一部分。\n */\nexport type RequestSessionDraft = {\n activeTab?: string;\n schemaDraft?: string;\n activeSourceIndex?: number;\n activeExampleJsonDraft?: string;\n activeDescriptionDraft?: string;\n};\n\nexport type RequestSessionSnapshotInput = {\n activeTab: string;\n schemaDraft?: string;\n activeSourceIndex?: number;\n activeExampleJsonDraft?: string;\n activeDescriptionDraft?: string;\n};\n\nexport function buildRequestSessionDraft(input: RequestSessionSnapshotInput): RequestSessionDraft {\n const draft: RequestSessionDraft = { activeTab: input.activeTab };\n if (input.schemaDraft !== undefined) draft.schemaDraft = input.schemaDraft;\n if (input.activeSourceIndex !== undefined) draft.activeSourceIndex = input.activeSourceIndex;\n if (input.activeExampleJsonDraft !== undefined) draft.activeExampleJsonDraft = input.activeExampleJsonDraft;\n if (input.activeDescriptionDraft !== undefined) draft.activeDescriptionDraft = input.activeDescriptionDraft;\n return draft;\n}\n\nexport type RequestSessionDraftAppliers = {\n setActiveTab: (tab: string) => void;\n setSchemaDraft?: (value: string) => void;\n setActiveSourceIndex?: (index: number) => void;\n setActiveExampleJsonDraft?: (value: string) => void;\n setActiveDescriptionDraft?: (value: string) => void;\n};\n\n/** 将快照草稿回填到编辑器(缺省字段跳过;无草稿时整体跳过) */\nexport function applyRequestSessionDraft(\n draft: RequestSessionDraft | undefined,\n appliers: RequestSessionDraftAppliers,\n): void {\n if (!draft) return;\n if (draft.activeTab !== undefined) appliers.setActiveTab(draft.activeTab);\n if (draft.schemaDraft !== undefined && appliers.setSchemaDraft) appliers.setSchemaDraft(draft.schemaDraft);\n if (draft.activeSourceIndex !== undefined && appliers.setActiveSourceIndex)\n appliers.setActiveSourceIndex(draft.activeSourceIndex);\n if (draft.activeExampleJsonDraft !== undefined && appliers.setActiveExampleJsonDraft)\n appliers.setActiveExampleJsonDraft(draft.activeExampleJsonDraft);\n if (draft.activeDescriptionDraft !== undefined && appliers.setActiveDescriptionDraft)\n appliers.setActiveDescriptionDraft(draft.activeDescriptionDraft);\n}\n\n/** TabRequest 便捷封装:注册 request 会话草稿 slice(泛型承载宿主的 tab 键枚举) */\nexport function useRequestSessionDraftSerializer(\n tabId: string,\n snapshot: RequestSessionSnapshotInput,\n appliers: RequestSessionDraftAppliers,\n): void {\n useTabSerializer<RequestSessionDraft>(tabId, 'request', {\n serialize: () => buildRequestSessionDraft(snapshot),\n restore: (draft) => applyRequestSessionDraft(draft, appliers),\n });\n}\n","import { useEffect, useMemo, useRef, useState } from 'react';\n\nimport {\n type RequestContentLike,\n type RequestDefinition,\n type RequestDefinitionType,\n buildRequestSchemaFromDefinitions,\n getRequestDefinitions,\n normalizeRequestDefinitionOrders,\n normalizeRequestFieldKey,\n parseRequestSchemaValue,\n stringifyRequestSchemaValue,\n} from '../../../helpers/request-schema';\nimport type { TranslationKey } from '../../../theming/i18n';\n\nconst definitionRootKey = '__root__';\n\nconst buildDefinitionPath = (parentPath: string | null | undefined, name: string) =>\n parentPath ? `${parentPath}.${name}` : name;\n\nconst buildDefinitionDraftPath = (parentPath: string | null | undefined, id: string) =>\n parentPath ? `${parentPath}.__draft_${id}` : `__draft_${id}`;\n\nconst createDefinitionDraft = (parentPath?: string | null, depth = 0, name = ''): RequestDefinition => {\n const id = crypto.randomUUID();\n const trimmedName = name.trim();\n\n return {\n id,\n path: trimmedName ? buildDefinitionPath(parentPath, trimmedName) : buildDefinitionDraftPath(parentPath, id),\n name,\n type: 'string',\n description: '',\n format: '',\n order: 0,\n depth,\n parentPath: parentPath ?? null,\n source: 'schema.properties',\n };\n};\n\nconst createRequestDefinitionSyncSignature = (\n definitions: Array<\n Pick<RequestDefinition, 'path' | 'name' | 'type' | 'description' | 'format' | 'parentPath' | 'depth'>\n >,\n) =>\n JSON.stringify(\n definitions\n .filter((definition) => definition.name.trim())\n .map((definition) => ({\n path: definition.path,\n name: definition.name,\n type: definition.type,\n description: definition.description,\n format: definition.format,\n parentPath: definition.parentPath,\n depth: definition.depth,\n })),\n );\n\nconst mergePersistedDefinitionsWithLocalDraftOrder = (\n previousDefinitions: RequestDefinition[],\n persistedDefinitions: RequestDefinition[],\n) => {\n const persistedByPath = new Map(persistedDefinitions.map((definition) => [definition.path, definition]));\n const availablePaths = new Set(persistedDefinitions.map((definition) => definition.path));\n const mergedDefinitions: RequestDefinition[] = [];\n\n previousDefinitions.forEach((definition) => {\n if (!definition.name.trim()) {\n if (definition.parentPath === null || availablePaths.has(definition.parentPath)) {\n mergedDefinitions.push(definition);\n }\n\n return;\n }\n\n const persistedDefinition = persistedByPath.get(definition.path);\n if (!persistedDefinition) {\n return;\n }\n\n persistedByPath.delete(definition.path);\n mergedDefinitions.push({\n ...persistedDefinition,\n id: definition.id,\n });\n });\n\n mergedDefinitions.push(...persistedByPath.values());\n return mergedDefinitions;\n};\n\ntype UseRequestDefinitionsEditingParams = {\n id: string;\n content: RequestContentLike | undefined;\n t: (key: TranslationKey) => string;\n sourceSchemaValue: unknown;\n updateNodeSchema: (nextSchema: string) => void;\n};\n\nexport const useRequestDefinitionsEditing = ({\n id,\n content,\n t,\n sourceSchemaValue,\n updateNodeSchema,\n}: UseRequestDefinitionsEditingParams) => {\n const persistedDefinitions = useMemo(\n () => getRequestDefinitions(content),\n [content?.schema, content?.schemaUI, content?.inputs],\n );\n const [definitionDrafts, setDefinitionDrafts] = useState<RequestDefinition[]>(persistedDefinitions);\n const definitionDraftsRef = useRef<RequestDefinition[]>(definitionDrafts);\n const [collapsedDefinitionPaths, setCollapsedDefinitionPaths] = useState<Record<string, true>>({});\n const persistedDefinitionSignature = useMemo(\n () => createRequestDefinitionSyncSignature(persistedDefinitions),\n [persistedDefinitions],\n );\n const pendingDefinitionSyncSignatureRef = useRef<string | null>(null);\n const previousNodeIdRef = useRef(id);\n\n useEffect(() => {\n definitionDraftsRef.current = definitionDrafts;\n }, [definitionDrafts]);\n\n useEffect(() => {\n if (previousNodeIdRef.current === id) {\n return;\n }\n\n previousNodeIdRef.current = id;\n pendingDefinitionSyncSignatureRef.current = null;\n }, [id]);\n\n useEffect(() => {\n setDefinitionDrafts((previousDefinitions) => {\n const isLocalDefinitionSync =\n pendingDefinitionSyncSignatureRef.current !== null &&\n pendingDefinitionSyncSignatureRef.current === persistedDefinitionSignature;\n pendingDefinitionSyncSignatureRef.current = null;\n\n if (isLocalDefinitionSync) {\n const mergedDefinitions = mergePersistedDefinitionsWithLocalDraftOrder(\n previousDefinitions,\n persistedDefinitions,\n );\n\n return mergedDefinitions;\n }\n\n const pendingDefinitions = previousDefinitions.filter((definition) => !definition.name.trim());\n if (pendingDefinitions.length === 0) {\n return persistedDefinitions;\n }\n\n const availablePaths = new Set(persistedDefinitions.map((definition) => definition.path));\n const safePendingDefinitions = pendingDefinitions.filter(\n (definition) => definition.parentPath === null || availablePaths.has(definition.parentPath),\n );\n\n return [...persistedDefinitions, ...safePendingDefinitions];\n });\n }, [id, persistedDefinitionSignature, persistedDefinitions]);\n\n const definitionChildrenMap = useMemo(() => {\n const map = new Map<string, RequestDefinition[]>();\n definitionDrafts.forEach((definition) => {\n const key = definition.parentPath ?? definitionRootKey;\n const current = map.get(key) ?? [];\n current.push(definition);\n map.set(key, current);\n });\n\n return map;\n }, [definitionDrafts]);\n\n const rootDefinitions = useMemo(() => definitionChildrenMap.get(definitionRootKey) ?? [], [definitionChildrenMap]);\n\n const definitionTypeOptions = useMemo<Array<{ value: RequestDefinitionType; label: string }>>(\n () => [\n { value: 'string', label: t('request.typeString') },\n { value: 'number', label: t('request.typeNumber') },\n { value: 'array', label: t('request.typeArray') },\n { value: 'object', label: t('request.typeObject') },\n { value: 'datetime', label: t('request.typeDatetime') },\n { value: 'boolean', label: t('request.typeBoolean') },\n ],\n [t],\n );\n\n const persistDefinitions = (nextDefinitions: RequestDefinition[]) => {\n const normalizedDefinitions = normalizeRequestDefinitionOrders(nextDefinitions);\n const hasValidDefinitions = normalizedDefinitions.some(\n (definition) => definition.name.trim() && definition.path.trim(),\n );\n pendingDefinitionSyncSignatureRef.current = createRequestDefinitionSyncSignature(normalizedDefinitions);\n setDefinitionDrafts(normalizedDefinitions);\n\n if (!hasValidDefinitions) {\n const currentSchema = parseRequestSchemaValue(sourceSchemaValue);\n const nextSchemaObject =\n currentSchema && Array.isArray(currentSchema.examples)\n ? {\n ...currentSchema,\n type: 'object',\n properties: {},\n }\n : null;\n\n updateNodeSchema(nextSchemaObject ? stringifyRequestSchemaValue(nextSchemaObject) : '');\n return;\n }\n\n updateNodeSchema(buildRequestSchemaFromDefinitions(sourceSchemaValue, normalizedDefinitions));\n };\n\n const getBranchEndIndex = <T extends { path: string }>(items: T[], path: string) => {\n const prefix = `${path}.`;\n let endIndex = items.findIndex((item) => item.path === path);\n if (endIndex < 0) {\n return items.length;\n }\n\n endIndex += 1;\n while (endIndex < items.length && items[endIndex].path.startsWith(prefix)) {\n endIndex += 1;\n }\n\n return endIndex;\n };\n\n const updateDefinitionDescription = (index: number, description: string) => {\n persistDefinitions(\n definitionDrafts.map((definition, currentIndex) =>\n currentIndex === index\n ? {\n ...definition,\n description,\n }\n : definition,\n ),\n );\n };\n\n const updateDefinitionDefaultValue = (index: number, defaultValue: string) => {\n persistDefinitions(\n definitionDrafts.map((definition, currentIndex) =>\n currentIndex === index\n ? {\n ...definition,\n defaultValue: defaultValue.trim() || undefined,\n }\n : definition,\n ),\n );\n };\n\n const updateDefinitionName = (index: number, name: string) => {\n const target = definitionDrafts[index];\n if (!target) {\n return;\n }\n\n const normalizedName = normalizeRequestFieldKey(name);\n const hasChildDefinitions = definitionDrafts.some((definition) => definition.parentPath === target.path);\n if (hasChildDefinitions && !normalizedName) {\n return;\n }\n\n const nextPath = normalizedName\n ? buildDefinitionPath(target.parentPath, normalizedName)\n : buildDefinitionDraftPath(target.parentPath, target.id);\n const nextDefinitions = definitionDrafts.map((definition) => {\n if (definition.path !== target.path && !definition.path.startsWith(`${target.path}.`)) {\n return definition;\n }\n\n if (definition.path === target.path) {\n return {\n ...definition,\n name: normalizedName,\n path: nextPath,\n };\n }\n\n const suffix = definition.path.slice(target.path.length);\n const descendantPath = nextPath ? `${nextPath}${suffix}` : suffix.replace(/^\\./, '');\n const segments = descendantPath.split('.').filter(Boolean);\n const nextName = definition.name.trim() ? (segments[segments.length - 1] ?? definition.name) : definition.name;\n\n return {\n ...definition,\n path: descendantPath,\n name: nextName,\n parentPath: segments.length > 1 ? segments.slice(0, -1).join('.') : null,\n depth: Math.max(segments.length - 1, 0),\n };\n });\n\n persistDefinitions(nextDefinitions);\n };\n\n const updateDefinitionType = (index: number, nextType: RequestDefinitionType) => {\n const target = definitionDrafts[index];\n if (!target) {\n return;\n }\n\n const nextFormat =\n nextType === 'datetime'\n ? target.format || 'date-time'\n : nextType === 'string'\n ? target.type === 'datetime'\n ? ''\n : target.format\n : '';\n const nextDefinitions = definitionDrafts\n .filter((definition, currentIndex) => {\n if (currentIndex === index) {\n return true;\n }\n\n if (nextType === 'object') {\n return true;\n }\n\n return !definition.path.startsWith(`${target.path}.`);\n })\n .map((definition, currentIndex) =>\n currentIndex === index\n ? {\n ...definition,\n type: nextType,\n format: nextFormat,\n }\n : definition,\n );\n\n persistDefinitions(nextDefinitions);\n };\n\n const removeDefinition = (index: number) => {\n const target = definitionDrafts[index];\n if (!target) {\n return;\n }\n\n persistDefinitions(\n definitionDrafts.filter(\n (definition) => definition.path !== target.path && !definition.path.startsWith(`${target.path}.`),\n ),\n );\n };\n\n const addDefinition = () => {\n persistDefinitions([...definitionDrafts, createDefinitionDraft(null, 0, '')]);\n };\n\n const addChildDefinition = (index: number) => {\n const parent = definitionDrafts[index];\n if (!parent || parent.type !== 'object' || !parent.path.trim()) {\n return;\n }\n\n const insertAt = getBranchEndIndex(definitionDrafts, parent.path);\n const nextDefinitions = [...definitionDrafts];\n nextDefinitions.splice(insertAt, 0, createDefinitionDraft(parent.path, parent.depth + 1, ''));\n persistDefinitions(nextDefinitions);\n };\n\n const toggleDefinitionCollapsed = (path: string) => {\n setCollapsedDefinitionPaths((previousState) => {\n const nextState = { ...previousState };\n\n if (nextState[path]) {\n delete nextState[path];\n } else {\n nextState[path] = true;\n }\n\n return nextState;\n });\n };\n\n const getDefinitionIndex = (definitionId: string) =>\n definitionDrafts.findIndex((definition) => definition.id === definitionId);\n\n const getDefinitionTypeLabel = (defType: RequestDefinitionType) =>\n definitionTypeOptions.find((option) => option.value === defType)?.label ?? defType;\n\n return {\n definitionDrafts,\n definitionChildrenMap,\n rootDefinitions,\n definitionTypeOptions,\n collapsedDefinitionPaths,\n toggleDefinitionCollapsed,\n addDefinition,\n addChildDefinition,\n removeDefinition,\n updateDefinitionName,\n updateDefinitionType,\n updateDefinitionDescription,\n updateDefinitionDefaultValue,\n getDefinitionIndex,\n getDefinitionTypeLabel,\n };\n};\n","import json5 from 'json5';\nimport type React from 'react';\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport { toast } from 'sonner';\n\nimport { saveFile } from '../../../helpers/file-helpers';\nimport {\n type RequestContentLike,\n type RequestDefinition,\n type RequestExampleSource,\n buildRequestExampleTemplateFromDefinitions,\n collectExampleDataPaths,\n formatJsonDraft,\n formatRequestExampleSourceName,\n getPathValue,\n getRequestExampleDataDefinitionConflicts,\n getRequestExampleSources,\n isRecord,\n mergeRequestExampleDefaultsByDefinitions,\n normalizeRequestExampleDataByDefinitions,\n updateRequestSchemaExamples,\n} from '../../../helpers/request-schema';\nimport type { TranslationKey } from '../../../theming/i18n';\nimport type { useDecisionGraphActions } from '../context/dg-store.context';\nimport { type SimulatorExampleBinding } from '../context/dg-store.context';\n\ntype UseRequestExamplesEditingParams = {\n id: string;\n content: RequestContentLike | undefined;\n t: (key: TranslationKey) => string;\n graphActions: ReturnType<typeof useDecisionGraphActions>;\n panels?: Array<{ id: string }>;\n activeGraphTabId?: string;\n simulatorExampleBinding: SimulatorExampleBinding | undefined;\n nodeName?: string;\n sourceSchemaValue: unknown;\n updateNodeSchema: (nextSchema: string) => void;\n definitionDrafts: RequestDefinition[];\n};\n\nexport const useRequestExamplesEditing = ({\n id,\n content,\n t,\n graphActions,\n panels,\n activeGraphTabId,\n simulatorExampleBinding,\n nodeName,\n sourceSchemaValue,\n updateNodeSchema,\n definitionDrafts,\n}: UseRequestExamplesEditingParams) => {\n const fileInputRef = useRef<HTMLInputElement>(null);\n const activeExampleSourceIdRef = useRef<string | null>(null);\n const [activeSourceIndex, setActiveSourceIndex] = useState(0);\n const [editingSourceIndex, setEditingSourceIndex] = useState<number | null>(null);\n const [exampleJsonDrafts, setExampleJsonDrafts] = useState<Record<string, string>>({});\n const [exampleJsonDirtyBySourceId, setExampleJsonDirtyBySourceId] = useState<Record<string, boolean>>({});\n const [descriptionDrafts, setDescriptionDrafts] = useState<Record<string, string>>({});\n\n const exampleSources = useMemo(\n () => getRequestExampleSources(content, { dataLabel: t('request.dataLabel') }),\n [content, t],\n );\n const getExampleSourceName = (index: number) => formatRequestExampleSourceName(index, t('request.dataLabel'));\n const activeSource = exampleSources[activeSourceIndex] ?? null;\n const normalizeExampleData = useCallback(\n (data?: Record<string, unknown>, definitions = definitionDrafts) =>\n normalizeRequestExampleDataByDefinitions(isRecord(data) ? data : {}, definitions),\n [definitionDrafts],\n );\n const getPreparedExampleData = useCallback(\n (data?: Record<string, unknown>) =>\n normalizeRequestExampleDataByDefinitions(\n mergeRequestExampleDefaultsByDefinitions(isRecord(data) ? data : {}, definitionDrafts),\n definitionDrafts,\n ),\n [definitionDrafts],\n );\n const mergedExampleData = useMemo(\n () => (activeSource ? mergeRequestExampleDefaultsByDefinitions(activeSource.data, definitionDrafts) : null),\n [activeSource, definitionDrafts],\n );\n const activeExampleJsonDraft = useMemo(() => {\n if (!activeSource) {\n return '';\n }\n\n return exampleJsonDrafts[activeSource.id] ?? formatJsonDraft(mergedExampleData);\n }, [activeSource, exampleJsonDrafts, mergedExampleData]);\n const activeDescriptionDraft = useMemo(() => {\n if (!activeSource) {\n return '';\n }\n\n return descriptionDrafts[activeSource.id] ?? activeSource.description ?? '';\n }, [activeSource, descriptionDrafts]);\n const exampleFieldSummary = useMemo(() => {\n if (!activeSource || !mergedExampleData) {\n return null;\n }\n\n const validDefinitions = definitionDrafts.filter((definition) => definition.name.trim() && definition.path.trim());\n const conflicts = getRequestExampleDataDefinitionConflicts(mergedExampleData, validDefinitions);\n const missing = validDefinitions.filter(\n (definition) => getPathValue(mergedExampleData, definition.path.trim()) === undefined,\n );\n const dataPaths = collectExampleDataPaths(mergedExampleData);\n const definitionPaths = validDefinitions.map((definition) => definition.path.trim());\n const extra = dataPaths.filter(\n (dataPath) =>\n !definitionPaths.some(\n (definitionPath) => dataPath === definitionPath || dataPath.startsWith(`${definitionPath}.`),\n ),\n );\n\n return {\n definitions: validDefinitions,\n conflicts,\n missing,\n extra,\n };\n }, [activeSource, definitionDrafts, mergedExampleData]);\n const exampleSourcesSyncSignature = useMemo(\n () => JSON.stringify(exampleSources.map((source) => ({ name: source.name, data: source.data }))),\n [exampleSources],\n );\n const previousExampleSourcesSyncSignatureRef = useRef<string | null>(null);\n\n useEffect(() => {\n if (activeSourceIndex <= Math.max(exampleSources.length - 1, 0)) {\n return;\n }\n\n setActiveSourceIndex(Math.max(exampleSources.length - 1, 0));\n }, [activeSourceIndex, exampleSources.length]);\n\n useEffect(() => {\n if (exampleSources.length > 0 || simulatorExampleBinding?.nodeId !== id) {\n return;\n }\n\n graphActions.setSimulatorExampleBinding(null);\n }, [exampleSources.length, graphActions, id, simulatorExampleBinding]);\n\n useEffect(() => {\n const previousSignature = previousExampleSourcesSyncSignatureRef.current;\n previousExampleSourcesSyncSignatureRef.current = exampleSourcesSyncSignature;\n\n if (previousSignature === null || previousSignature === exampleSourcesSyncSignature) {\n return;\n }\n\n const isCurrentRequestActive = activeGraphTabId === id;\n const isSimulatorBoundToCurrentRequest = simulatorExampleBinding?.nodeId === id;\n\n if (!isCurrentRequestActive && !isSimulatorBoundToCurrentRequest) {\n return;\n }\n\n if (exampleSources.length === 0) {\n if (activeSourceIndex !== 0) {\n setActiveSourceIndex(0);\n }\n\n graphActions.setSimulatorRequest('');\n graphActions.setSimulatorExampleBinding(null);\n return;\n }\n\n const preferredSourceIndex = isSimulatorBoundToCurrentRequest\n ? simulatorExampleBinding.sourceIndex\n : activeSourceIndex;\n const safeSourceIndex = Math.max(0, Math.min(preferredSourceIndex, exampleSources.length - 1));\n const nextSource = exampleSources[safeSourceIndex];\n\n if (!nextSource) {\n return;\n }\n\n if (activeSourceIndex !== safeSourceIndex) {\n setActiveSourceIndex(safeSourceIndex);\n }\n\n const preparedExampleData = getPreparedExampleData(nextSource.data);\n const nextRequest = JSON.stringify(preparedExampleData, null, 2);\n\n graphActions.setSimulatorRequest(nextRequest);\n graphActions.setSimulatorExampleBinding({\n nodeId: id,\n sourceIndex: safeSourceIndex,\n sourceName: nextSource.name,\n });\n }, [\n activeGraphTabId,\n activeSourceIndex,\n exampleSources,\n exampleSources.length,\n exampleSourcesSyncSignature,\n getPreparedExampleData,\n graphActions,\n id,\n simulatorExampleBinding,\n ]);\n\n useEffect(() => {\n exampleSources.forEach((source) => {\n setExampleJsonDrafts((previousState) => {\n const isDirty = exampleJsonDirtyBySourceId[source.id] === true;\n if (isDirty) {\n return previousState;\n }\n\n const nextDraft = formatJsonDraft(mergeRequestExampleDefaultsByDefinitions(source.data, definitionDrafts));\n if (previousState[source.id] === nextDraft) {\n return previousState;\n }\n\n return {\n ...previousState,\n [source.id]: nextDraft,\n };\n });\n });\n }, [definitionDrafts, exampleJsonDirtyBySourceId, exampleSources]);\n\n useEffect(() => {\n if (simulatorExampleBinding?.nodeId !== id) {\n return;\n }\n\n if (simulatorExampleBinding.sourceIndex < 0 || simulatorExampleBinding.sourceIndex >= exampleSources.length) {\n return;\n }\n\n if (simulatorExampleBinding.sourceIndex === activeSourceIndex) {\n return;\n }\n\n setActiveSourceIndex(simulatorExampleBinding.sourceIndex);\n }, [activeSourceIndex, exampleSources.length, id, simulatorExampleBinding]);\n\n useEffect(() => {\n if (activeGraphTabId !== id || !activeSource) {\n return;\n }\n\n if (\n simulatorExampleBinding?.nodeId === id &&\n simulatorExampleBinding.sourceIndex !== activeSourceIndex &&\n simulatorExampleBinding.sourceIndex >= 0 &&\n simulatorExampleBinding.sourceIndex < exampleSources.length\n ) {\n return;\n }\n\n const hasMatchedBinding =\n simulatorExampleBinding?.nodeId === id &&\n simulatorExampleBinding.sourceIndex === activeSourceIndex &&\n simulatorExampleBinding.sourceName === activeSource.name;\n\n if (hasMatchedBinding) {\n return;\n }\n\n graphActions.setSimulatorExampleBinding({\n nodeId: id,\n sourceIndex: activeSourceIndex,\n sourceName: activeSource.name,\n });\n }, [\n activeGraphTabId,\n activeSource,\n activeSourceIndex,\n exampleSources.length,\n graphActions,\n id,\n simulatorExampleBinding,\n ]);\n\n useEffect(() => {\n activeExampleSourceIdRef.current = activeSource?.id ?? null;\n }, [activeSource]);\n\n const openSimulatorPanel = useCallback(() => {\n const simulatorPanel = panels?.find((panel) => panel.id === 'simulator');\n if (simulatorPanel) {\n graphActions.setActivePanel(simulatorPanel.id);\n }\n }, [panels, graphActions]);\n\n const syncExampleToSimulator = (source?: RequestExampleSource | null, sourceIndex = activeSourceIndex) => {\n if (!source) {\n graphActions.setSimulatorRequest('');\n graphActions.setSimulatorExampleBinding(null);\n return;\n }\n\n const preparedExampleData = getPreparedExampleData(source.data);\n const nextRequest = JSON.stringify(preparedExampleData, null, 2);\n graphActions.setSimulatorRequest(nextRequest);\n graphActions.setSimulatorExampleBinding({\n nodeId: id,\n sourceIndex,\n sourceName: source.name,\n });\n };\n\n const persistExamples = (\n nextSources: RequestExampleSource[],\n nextActiveIndex = activeSourceIndex,\n options?: {\n syncToSimulator?: boolean;\n },\n ) => {\n const normalizedNextSources = nextSources.map((source) => ({\n ...source,\n data: normalizeExampleData(source.data),\n }));\n const examplesMeta = normalizedNextSources.map((source) => ({\n name: source.name,\n description: source.description,\n }));\n const nextSchema = updateRequestSchemaExamples(\n sourceSchemaValue,\n normalizedNextSources.map((source) => source.data),\n examplesMeta,\n );\n updateNodeSchema(nextSchema);\n\n const safeIndex = Math.max(0, Math.min(nextActiveIndex, normalizedNextSources.length - 1));\n setActiveSourceIndex(safeIndex);\n const shouldSyncToSimulator = options?.syncToSimulator ?? true;\n\n if (shouldSyncToSimulator) {\n syncExampleToSimulator(normalizedNextSources[safeIndex], safeIndex);\n }\n };\n\n const handleExampleJsonChange = (nextValue: string) => {\n const activeSourceId = activeExampleSourceIdRef.current ?? activeSource?.id;\n if (!activeSourceId) {\n return;\n }\n\n setExampleJsonDrafts((previousState) => ({\n ...previousState,\n [activeSourceId]: nextValue,\n }));\n setExampleJsonDirtyBySourceId((previousState) => ({\n ...previousState,\n [activeSourceId]: true,\n }));\n };\n\n const commitExampleJson = () => {\n const activeSourceId = activeExampleSourceIdRef.current ?? activeSource?.id;\n if (!activeSourceId) {\n return;\n }\n\n const activeSourceById = exampleSources.find((source) => source.id === activeSourceId);\n const nextDraft = exampleJsonDrafts[activeSourceId] ?? (activeSourceById && formatJsonDraft(activeSourceById.data));\n\n if (!nextDraft || nextDraft.trim() === '') {\n return;\n }\n\n let parsedValue: unknown;\n try {\n parsedValue = json5.parse(nextDraft);\n } catch {\n toast.warning(t('request.jsonInvalidError'));\n return;\n }\n\n if (!isRecord(parsedValue)) {\n toast.warning(t('request.jsonObjectError'));\n return;\n }\n\n const nextSourceIndex = exampleSources.findIndex((source) => source.id === activeSourceId);\n const nextSources = exampleSources.map((source) =>\n source.id === activeSourceId\n ? {\n ...source,\n data: parsedValue,\n }\n : source,\n );\n\n persistExamples(nextSources, nextSourceIndex, { syncToSimulator: false });\n setExampleJsonDrafts((previousState) => ({\n ...previousState,\n [activeSourceId]: formatJsonDraft(parsedValue),\n }));\n setExampleJsonDirtyBySourceId((previousState) => ({\n ...previousState,\n [activeSourceId]: false,\n }));\n };\n\n const handleDescriptionChange = (nextValue: string) => {\n const activeSourceId = activeExampleSourceIdRef.current ?? activeSource?.id;\n if (!activeSourceId) {\n return;\n }\n\n setDescriptionDrafts((previousState) => ({\n ...previousState,\n [activeSourceId]: nextValue,\n }));\n };\n\n const commitDescription = () => {\n const activeSourceId = activeExampleSourceIdRef.current ?? activeSource?.id;\n if (!activeSourceId) {\n return;\n }\n\n const activeSourceById = exampleSources.find((source) => source.id === activeSourceId);\n const nextDraft = descriptionDrafts[activeSourceId] ?? activeSourceById?.description ?? '';\n const currentDescription = activeSourceById?.description ?? '';\n\n if (nextDraft === currentDescription) {\n return;\n }\n\n const nextSourceIndex = exampleSources.findIndex((source) => source.id === activeSourceId);\n const nextSources = exampleSources.map((source) =>\n source.id === activeSourceId\n ? {\n ...source,\n description: nextDraft.trim() || undefined,\n }\n : source,\n );\n\n persistExamples(nextSources, nextSourceIndex, { syncToSimulator: false });\n };\n\n const addExampleSource = useCallback(() => {\n const baseExampleSources = exampleSources;\n const nextSources = [\n ...baseExampleSources,\n {\n id: crypto.randomUUID(),\n name: getExampleSourceName(baseExampleSources.length),\n data: normalizeRequestExampleDataByDefinitions(\n buildRequestExampleTemplateFromDefinitions(definitionDrafts),\n definitionDrafts,\n ),\n source: 'schema.examples' as const,\n },\n ];\n\n persistExamples(nextSources, nextSources.length - 1);\n }, [exampleSources, definitionDrafts, persistExamples, t]);\n\n const removeExampleSource = (index: number) => {\n const baseExampleSources = exampleSources;\n const nextSources = baseExampleSources.filter((_, currentIndex) => currentIndex !== index);\n persistExamples(nextSources, Math.max(index - 1, 0));\n };\n\n const getSafeJsonFileName = useCallback(\n (name?: string) => {\n const trimmed = (name ?? '').trim();\n const baseName = trimmed.length > 0 ? trimmed : nodeName || t('request');\n const normalized = baseName\n .replace(/\\.json$/i, '')\n .replace(/[\\\\/:*?\"<>|]/g, '-')\n .trim();\n\n return `${normalized || t('request')}.json`;\n },\n [nodeName, t],\n );\n\n const handleUploadJson = async (event: React.ChangeEvent<HTMLInputElement>) => {\n const file = event.target.files?.[0];\n if (!file) {\n return;\n }\n\n try {\n const text = await file.text();\n const parsed = json5.parse(text);\n\n if (!isRecord(parsed)) {\n toast.error(t('request.uploadJsonObjectRequired'));\n return;\n }\n\n const nextSourceName = file.name.replace(/\\.json$/i, '') || getExampleSourceName(exampleSources.length);\n const nextSourceData = parsed as Record<string, unknown>;\n\n if (exampleSources.length === 0) {\n persistExamples(\n [\n {\n id: crypto.randomUUID(),\n name: nextSourceName,\n data: nextSourceData,\n source: 'schema.examples',\n },\n ],\n 0,\n );\n } else {\n persistExamples(\n exampleSources.map((source, index) =>\n index === activeSourceIndex\n ? {\n ...source,\n name: nextSourceName,\n data: nextSourceData,\n source: 'schema.examples',\n }\n : source,\n ),\n activeSourceIndex,\n );\n }\n\n toast.success(t('request.uploadJsonSuccess'));\n } catch (error: any) {\n console.warn('[request-node] failed to upload json', {\n nodeId: id,\n error,\n });\n toast.error(error?.message || t('request.uploadJsonFailed'));\n }\n };\n\n const handleDownloadJson = useCallback(() => {\n if (!activeSource) {\n toast.warning(t('request.downloadJsonNoData'));\n return;\n }\n\n const payload = JSON.stringify(getPreparedExampleData(activeSource.data), null, 2);\n saveFile(getSafeJsonFileName(activeSource.name), new Blob([payload], { type: 'application/json' }));\n }, [activeSource, getPreparedExampleData, getSafeJsonFileName, t]);\n\n return {\n exampleSources,\n activeSourceIndex,\n setActiveSourceIndex,\n editingSourceIndex,\n setEditingSourceIndex,\n activeSource,\n activeExampleJsonDraft,\n activeDescriptionDraft,\n exampleFieldSummary,\n fileInputRef,\n addExampleSource,\n removeExampleSource,\n persistExamples,\n handleExampleJsonChange,\n commitExampleJson,\n handleDescriptionChange,\n commitDescription,\n handleUploadJson,\n handleDownloadJson,\n openSimulatorPanel,\n syncExampleToSimulator,\n };\n};\n","import { useEffect, useMemo, useRef, useState } from 'react';\n\nimport {\n type RequestContentLike,\n getRequestSchemaSourceValue,\n hasOwn,\n isRecord,\n parseRequestSchemaValue,\n resolveRequestSchemaValue,\n setRequestSchemaValue,\n stringifyRequestSchemaValue,\n} from '../../../helpers/request-schema';\nimport type { useDecisionGraphActions } from '../context/dg-store.context';\n\ntype UseRequestSchemaEditingParams = {\n id: string;\n type?: string;\n content: RequestContentLike | undefined;\n graphActions: ReturnType<typeof useDecisionGraphActions>;\n};\n\nexport const useRequestSchemaEditing = ({ id, type, content, graphActions }: UseRequestSchemaEditingParams) => {\n const [jsonToJsonSchemaOpen, setJsonToJsonSchemaOpen] = useState(false);\n\n const sourceSchemaValue = useMemo(\n () => getRequestSchemaSourceValue(content),\n [content?.schema, content?.schemaUI, content?.inputs],\n );\n const schemaObject = useMemo(\n () => resolveRequestSchemaValue(content, { includeExamples: true }),\n [content?.schema, content?.schemaUI, content?.inputs],\n );\n const schemaText = useMemo(() => stringifyRequestSchemaValue(schemaObject), [schemaObject]);\n const persistedSchemaText = useMemo(\n () => stringifyRequestSchemaValue(sourceSchemaValue) || schemaText,\n [sourceSchemaValue, schemaText],\n );\n\n const [schemaDraft, setSchemaDraft] = useState(persistedSchemaText);\n const [isSchemaDraftDirty, setIsSchemaDraftDirty] = useState(false);\n const schemaDraftRef = useRef(schemaDraft);\n const persistedSchemaTextRef = useRef(persistedSchemaText);\n const pendingExternalSchemaDraftValueRef = useRef<string | null>(null);\n const initializedSchemaSyncNodeIdsRef = useRef<Set<string>>(new Set());\n const contentSchemaRef = useRef(sourceSchemaValue);\n const previousNodeIdRef = useRef(id);\n const pendingSchemaCommitRef = useRef<string | null>(null);\n\n const applyExternalSchemaDraft = (nextValue: string, options?: { dirty?: boolean }) => {\n pendingExternalSchemaDraftValueRef.current = nextValue;\n schemaDraftRef.current = nextValue;\n setSchemaDraft(nextValue);\n\n if (options?.dirty !== undefined) {\n setIsSchemaDraftDirty(options.dirty);\n }\n };\n\n useEffect(() => {\n schemaDraftRef.current = schemaDraft;\n }, [schemaDraft]);\n\n useEffect(() => {\n persistedSchemaTextRef.current = persistedSchemaText;\n }, [persistedSchemaText]);\n\n useEffect(() => {\n contentSchemaRef.current = sourceSchemaValue;\n }, [sourceSchemaValue]);\n\n useEffect(() => {\n if (previousNodeIdRef.current === id) {\n return;\n }\n\n previousNodeIdRef.current = id;\n pendingSchemaCommitRef.current = null;\n applyExternalSchemaDraft(persistedSchemaText, { dirty: false });\n }, [id, persistedSchemaText]);\n\n useEffect(() => {\n if (isSchemaDraftDirty) {\n return;\n }\n\n if (pendingSchemaCommitRef.current !== null) {\n if (persistedSchemaText !== pendingSchemaCommitRef.current) {\n return;\n }\n\n pendingSchemaCommitRef.current = null;\n }\n\n if (schemaDraftRef.current === persistedSchemaText) {\n return;\n }\n\n applyExternalSchemaDraft(persistedSchemaText);\n }, [isSchemaDraftDirty, persistedSchemaText]);\n\n const updateNodeSchema = (nextSchema: string) => {\n graphActions.updateNode(id, (draft) => {\n draft.content ??= {};\n if (type === 'input') {\n setRequestSchemaValue(draft.content as Record<string, any>, nextSchema);\n } else {\n draft.content.schema = nextSchema;\n }\n return draft;\n });\n };\n\n useEffect(() => {\n if (initializedSchemaSyncNodeIdsRef.current.has(id)) {\n return;\n }\n\n const sourceSchemaObj = parseRequestSchemaValue(sourceSchemaValue);\n const hasPersistedSchemaProperties = Boolean(\n sourceSchemaObj && hasOwn(sourceSchemaObj, 'properties') && isRecord(sourceSchemaObj.properties),\n );\n const hasLegacyInputs = (content?.inputs ?? []).length > 0;\n const nextSchemaText = schemaText.trim();\n\n if (hasPersistedSchemaProperties) {\n initializedSchemaSyncNodeIdsRef.current.add(id);\n return;\n }\n\n if (!hasLegacyInputs || !nextSchemaText) {\n return;\n }\n\n initializedSchemaSyncNodeIdsRef.current.add(id);\n pendingSchemaCommitRef.current = nextSchemaText;\n applyExternalSchemaDraft(nextSchemaText, { dirty: false });\n updateNodeSchema(nextSchemaText);\n\n if (import.meta.env.DEV) {\n console.log('[request-tab] initialized schema from legacy inputs', {\n nodeId: id,\n hasLegacyInputs,\n nextSchemaText,\n });\n }\n }, [content?.inputs, id, schemaText, sourceSchemaValue]);\n\n const commitSchemaDraft = () => {\n const nextSchemaDraft = schemaDraftRef.current;\n const trimmedSchemaDraft = nextSchemaDraft.trim();\n\n if (!trimmedSchemaDraft) {\n pendingSchemaCommitRef.current = null;\n\n if (stringifyRequestSchemaValue(contentSchemaRef.current).trim()) {\n pendingSchemaCommitRef.current = '';\n updateNodeSchema('');\n }\n\n applyExternalSchemaDraft('', { dirty: false });\n return;\n }\n\n if (!parseRequestSchemaValue(nextSchemaDraft)) {\n return;\n }\n\n if (nextSchemaDraft === persistedSchemaTextRef.current) {\n pendingSchemaCommitRef.current = null;\n setIsSchemaDraftDirty(false);\n return;\n }\n\n pendingSchemaCommitRef.current = nextSchemaDraft;\n updateNodeSchema(nextSchemaDraft);\n setIsSchemaDraftDirty(false);\n };\n\n const handleSchemaDraftChange = (nextValue: string) => {\n if (\n pendingExternalSchemaDraftValueRef.current !== null &&\n nextValue === pendingExternalSchemaDraftValueRef.current\n ) {\n pendingExternalSchemaDraftValueRef.current = null;\n schemaDraftRef.current = nextValue;\n setSchemaDraft(nextValue);\n return;\n }\n\n pendingExternalSchemaDraftValueRef.current = null;\n pendingSchemaCommitRef.current = null;\n schemaDraftRef.current = nextValue;\n setSchemaDraft(nextValue);\n setIsSchemaDraftDirty(true);\n };\n\n const handleConvertToJsonSchemaSuccess = ({ schema, model }: { schema: string; model: string }) => {\n localStorage.setItem(`${id}-request-model`, model);\n\n const currentSchema = parseRequestSchemaValue(sourceSchemaValue);\n const convertedSchema = parseRequestSchemaValue(schema);\n const nextSchemaObject =\n convertedSchema && currentSchema?.examples\n ? {\n ...convertedSchema,\n examples: currentSchema.examples,\n }\n : convertedSchema;\n const nextSchemaText = nextSchemaObject ? stringifyRequestSchemaValue(nextSchemaObject) : schema;\n\n pendingSchemaCommitRef.current = nextSchemaText;\n applyExternalSchemaDraft(nextSchemaText, { dirty: false });\n updateNodeSchema(nextSchemaText);\n };\n\n return {\n sourceSchemaValue,\n schemaDraft,\n jsonToJsonSchemaOpen,\n setJsonToJsonSchemaOpen,\n updateNodeSchema,\n handleSchemaDraftChange,\n commitSchemaDraft,\n handleConvertToJsonSchemaSuccess,\n };\n};\n","import {\n CloudDownloadOutlined,\n CloudUploadOutlined,\n FormatPainterOutlined,\n ImportOutlined,\n PlayCircleOutlined,\n PlusOutlined,\n} from '#icons';\nimport InformationIcon from '#reui/icons/animated/outline/information';\nimport type { DragDropManager } from 'dnd-core';\nimport type { editor } from 'monaco-editor';\nimport React, { useMemo, useRef, useState } from 'react';\n\nimport '../../../helpers/monaco';\nimport { useThemeMode } from '../../../theme';\nimport { useT } from '../../../theming/i18n';\nimport { Button, Space, Tabs, Tooltip } from '../../primitives';\nimport { useDecisionGraphActions, useDecisionGraphState } from '../context/dg-store.context';\nimport { RequestDefinitions } from './request-definitions';\nimport { RequestExamples } from './request-examples';\nimport { RequestSchemaEditor } from './request-schema-editor';\nimport { useRequestSessionDraftSerializer } from './request-session-draft';\nimport { useRequestDefinitionsEditing } from './use-request-definitions-editing';\nimport { useRequestExamplesEditing } from './use-request-examples-editing';\nimport { useRequestSchemaEditing } from './use-request-schema-editing';\n\nexport type TabRequestProps = {\n id: string;\n manager?: DragDropManager;\n menuList?: unknown[];\n type?: string;\n};\n\nenum RequestTabKey {\n Definitions = 'definitions',\n Examples = 'examples',\n Schema = 'schema',\n}\n\nconst editorOptions: editor.IStandaloneEditorConstructionOptions = {\n automaticLayout: true,\n contextmenu: false,\n fontSize: 13,\n fontFamily: 'var(--mono-font-family)',\n tabSize: 2,\n minimap: { enabled: false },\n overviewRulerBorder: false,\n scrollbar: {\n verticalSliderSize: 4,\n verticalScrollbarSize: 4,\n horizontalScrollbarSize: 4,\n horizontalSliderSize: 4,\n },\n};\n\nexport const TabRequest: React.FC<TabRequestProps> = ({ id, type }) => {\n const t = useT();\n const mode = useThemeMode();\n const graphActions = useDecisionGraphActions();\n const [activeTab, setActiveTab] = useState<RequestTabKey>(RequestTabKey.Definitions);\n const schemaEditorRef = useRef<editor.IStandaloneCodeEditor | undefined>(undefined);\n const exampleJsonEditorRef = useRef<editor.IStandaloneCodeEditor | undefined>(undefined);\n\n const {\n disabled: disabledRaw,\n content,\n nodeName,\n panels,\n activePanel,\n activeGraphTabId,\n simulatorExampleBinding,\n } = useDecisionGraphState(({ disabled, decisionGraph, panels, activePanel, activeTab, simulatorExampleBinding }) => ({\n disabled,\n content: (decisionGraph?.nodes ?? []).find((node) => node.id === id)?.content,\n nodeName: (decisionGraph?.nodes ?? []).find((node) => node.id === id)?.name ?? t('request'),\n panels,\n activePanel,\n activeGraphTabId: activeTab,\n simulatorExampleBinding,\n }));\n const disabled = disabledRaw ?? false;\n\n const {\n sourceSchemaValue,\n schemaDraft,\n jsonToJsonSchemaOpen,\n setJsonToJsonSchemaOpen,\n updateNodeSchema,\n handleSchemaDraftChange,\n commitSchemaDraft,\n handleConvertToJsonSchemaSuccess,\n } = useRequestSchemaEditing({ id, type, content, graphActions });\n const {\n definitionDrafts,\n definitionChildrenMap,\n rootDefinitions,\n definitionTypeOptions,\n collapsedDefinitionPaths,\n toggleDefinitionCollapsed,\n addDefinition,\n addChildDefinition,\n removeDefinition,\n updateDefinitionName,\n updateDefinitionType,\n updateDefinitionDescription,\n updateDefinitionDefaultValue,\n getDefinitionIndex,\n getDefinitionTypeLabel,\n } = useRequestDefinitionsEditing({\n id,\n content,\n t,\n sourceSchemaValue,\n updateNodeSchema,\n });\n const {\n exampleSources,\n activeSourceIndex,\n setActiveSourceIndex,\n editingSourceIndex,\n setEditingSourceIndex,\n activeSource,\n activeExampleJsonDraft,\n activeDescriptionDraft,\n exampleFieldSummary,\n fileInputRef,\n addExampleSource,\n removeExampleSource,\n persistExamples,\n handleExampleJsonChange,\n commitExampleJson,\n handleDescriptionChange,\n commitDescription,\n handleUploadJson,\n handleDownloadJson,\n openSimulatorPanel,\n syncExampleToSimulator,\n } = useRequestExamplesEditing({\n id,\n content,\n t,\n graphActions,\n panels,\n activeGraphTabId,\n simulatorExampleBinding,\n nodeName,\n sourceSchemaValue,\n updateNodeSchema,\n definitionDrafts,\n });\n\n // UI 会话草稿快照:捕获 700ms 防抖窗口内的在途编辑(schema/示例/描述/页签),\n // 随 {graph, tabs} 快照入库——保存/重开零丢失\n useRequestSessionDraftSerializer(\n id,\n {\n activeTab,\n schemaDraft,\n activeSourceIndex,\n activeExampleJsonDraft,\n activeDescriptionDraft,\n },\n {\n setActiveTab: (tab) => setActiveTab(tab as RequestTabKey),\n setSchemaDraft: handleSchemaDraftChange,\n setActiveExampleJsonDraft: handleExampleJsonChange,\n setActiveDescriptionDraft: handleDescriptionChange,\n setActiveSourceIndex: setActiveSourceIndex,\n },\n );\n\n const renderTabBarExtraContent = () => {\n if (activeTab === RequestTabKey.Examples) {\n return (\n <Space size='small' className='mr-2'>\n <Button type='text' size='small' disabled={disabled} icon={<PlusOutlined />} onClick={addExampleSource}>\n {t('request.addDataSource')}\n </Button>\n <Tooltip title={t('request.uploadJsonTooltip')}>\n <Button\n type='text'\n size='small'\n disabled={disabled}\n icon={<CloudUploadOutlined />}\n onClick={() => fileInputRef.current?.click()}\n >\n {t('dg.toolbar.uploadJson')}\n </Button>\n </Tooltip>\n <Tooltip title={t('request.downloadJsonTooltip')}>\n <Button\n type='text'\n size='small'\n disabled={!activeSource}\n icon={<CloudDownloadOutlined />}\n onClick={handleDownloadJson}\n >\n {t('dg.toolbar.downloadJson')}\n </Button>\n </Tooltip>\n <Tooltip title={t('request.simulateTooltip')} placement='bottomRight'>\n <Button\n type='text'\n size='small'\n icon={<PlayCircleOutlined />}\n disabled={disabled || activePanel === 'simulator'}\n onClick={openSimulatorPanel}\n />\n </Tooltip>\n </Space>\n );\n }\n\n if (activeTab === RequestTabKey.Schema) {\n return (\n <Space size='small' className='mr-2'>\n <Tooltip title={t('request.formatSchema')} placement='bottomRight'>\n <Button\n type='text'\n size='small'\n shape='circle'\n icon={<FormatPainterOutlined />}\n onClick={() => {\n const formatAction = schemaEditorRef.current?.getAction?.('editor.action.formatDocument');\n formatAction?.run();\n }}\n disabled={disabled}\n />\n </Tooltip>\n <Tooltip title={t('dg.jsonSchema.title')} placement='bottomRight'>\n <Button\n type='text'\n size='small'\n shape='circle'\n icon={<ImportOutlined />}\n onClick={() => setJsonToJsonSchemaOpen(true)}\n disabled={disabled}\n />\n </Tooltip>\n </Space>\n );\n }\n\n return null;\n };\n\n const themedEditorOptions = useMemo(\n () => ({\n ...editorOptions,\n theme: mode === 'dark' ? 'vs-dark' : 'light',\n }),\n [mode],\n );\n\n return (\n <div className='relative box-border flex h-full flex-col overflow-hidden bg-[var(--card)]'>\n <div className='flex shrink-0 items-center border-b border-b-border px-3'>\n <Tabs\n size='small'\n className='w-full'\n activeKey={activeTab}\n onChange={(nextKey) => {\n setActiveTab(nextKey as RequestTabKey);\n }}\n items={[\n { key: RequestTabKey.Definitions, label: t('request.definitionsTab') },\n { key: RequestTabKey.Examples, label: t('request.examplesTab') },\n {\n key: RequestTabKey.Schema,\n label: (\n <span>\n {t('request.schema')}\n <Tooltip title={t('request.schemaPriorityTooltip')}>\n <span className='ml-1 inline-flex align-super opacity-50 [&_svg]:block'>\n <InformationIcon className='size-2.5' />\n </span>\n </Tooltip>\n </span>\n ),\n },\n ]}\n tabBarExtraContent={renderTabBarExtraContent()}\n />\n </div>\n <div className='flex min-h-0 flex-1 flex-col overflow-hidden p-3'>\n {activeTab === RequestTabKey.Definitions && (\n <RequestDefinitions\n rootDefinitions={rootDefinitions}\n childrenMap={definitionChildrenMap}\n collapsedPaths={collapsedDefinitionPaths}\n disabled={disabled}\n definitionTypeOptions={definitionTypeOptions}\n onAdd={addDefinition}\n onUpdateName={updateDefinitionName}\n onUpdateType={updateDefinitionType}\n onUpdateDescription={updateDefinitionDescription}\n onUpdateDefaultValue={updateDefinitionDefaultValue}\n onAddChild={addChildDefinition}\n onRemove={removeDefinition}\n onToggleCollapse={toggleDefinitionCollapsed}\n getDefinitionIndex={getDefinitionIndex}\n />\n )}\n\n {activeTab === RequestTabKey.Examples && (\n <React.Fragment>\n <input\n hidden\n accept='application/json'\n type='file'\n ref={fileInputRef}\n onChange={handleUploadJson}\n onClick={(event) => {\n (event.target as HTMLInputElement).value = '';\n }}\n />\n <RequestExamples\n sources={exampleSources}\n activeSourceIndex={activeSourceIndex}\n editingSourceIndex={editingSourceIndex}\n activeSource={activeSource}\n activeDescriptionDraft={activeDescriptionDraft}\n activeJsonDraft={activeExampleJsonDraft}\n disabled={disabled}\n definitionDrafts={definitionDrafts}\n onSourceSelect={(index) => {\n setActiveSourceIndex(index);\n syncExampleToSimulator(exampleSources[index], index);\n }}\n onSourceAdd={addExampleSource}\n onSourceRemove={removeExampleSource}\n onSourceRename={(index, name) => {\n const trimmedName = name.trim();\n if (trimmedName) {\n persistExamples(\n exampleSources.map((item, currentIndex) =>\n currentIndex === index ? { ...item, name: trimmedName } : item,\n ),\n index,\n { syncToSimulator: false },\n );\n }\n }}\n onEnterEditing={(index) => setEditingSourceIndex(index)}\n onSourceRenameExit={() => setEditingSourceIndex(null)}\n onDescriptionChange={handleDescriptionChange}\n onDescriptionCommit={commitDescription}\n onJsonChange={handleExampleJsonChange}\n onJsonCommit={commitExampleJson}\n onFormat={() => {\n const formatAction = exampleJsonEditorRef.current?.getAction?.('editor.action.formatDocument');\n formatAction?.run();\n }}\n onJsonEditorMount={(instance) => {\n exampleJsonEditorRef.current = instance;\n }}\n summary={exampleFieldSummary}\n getDefinitionTypeLabel={getDefinitionTypeLabel}\n editorOptions={themedEditorOptions}\n />\n </React.Fragment>\n )}\n\n {activeTab === RequestTabKey.Schema && (\n <RequestSchemaEditor\n schemaDraft={schemaDraft}\n disabled={disabled}\n onSchemaChange={handleSchemaDraftChange}\n onSchemaCommit={commitSchemaDraft}\n jsonToJsonSchemaOpen={jsonToJsonSchemaOpen}\n onConvertSuccess={handleConvertToJsonSchemaSuccess}\n onDismissConvert={() => setJsonToJsonSchemaOpen(false)}\n onEditorMount={(instance) => {\n schemaEditorRef.current = instance;\n }}\n editorOptions={themedEditorOptions}\n nodeId={id}\n />\n )}\n </div>\n </div>\n );\n};\n","import { BookOutlined, DeleteOutlined } from '#icons';\nimport { produce } from 'immer';\nimport _ from 'lodash';\nimport { ArrowRightToLineIcon } from 'lucide-react';\nimport React from 'react';\nimport type { z } from 'zod';\n\nimport { platform } from '../../../../helpers/platform';\nimport { type inputNodeSchema } from '../../../../helpers/schema';\nimport { useT } from '../../../../theming/i18n';\nimport { App } from '../../../primitives';\nimport { Button, Typography } from '../../../primitives';\nimport { SpacedText } from '../../../spaced-text';\nimport { useDecisionGraphActions, useDecisionGraphState } from '../../context/dg-store.context';\nimport type { Diff, DiffMetadata } from '../../dg-types';\nimport { TabRequest } from '../../graph/tab-request';\nimport { GraphNode } from '../graph-node';\nimport { NodeColor } from './colors';\nimport type { NodeSpecification } from './specification-types';\nimport { NodeKind } from './specification-types';\n\ntype InferredContent = z.infer<typeof inputNodeSchema>['content'];\n\nexport type NodeInputData = InferredContent & Diff;\n\nexport const inputSpecification: NodeSpecification<NodeInputData> = {\n type: NodeKind.Input,\n icon: <ArrowRightToLineIcon size='1em' />,\n displayName: 'Request',\n color: NodeColor.Green,\n documentationUrl: 'https://gorules.io/docs/user-manual/decision-modeling/decisions',\n shortDescription: 'Provides input context',\n generateNode: () => ({\n name: 'request',\n content: {\n schema: '',\n expressions: [],\n inputField: null,\n outputPath: null,\n },\n }),\n renderTab: ({ id }) => <TabRequest id={id} type={'input'} />,\n renderNode: ({ id, data, selected, specification }) => {\n const graphActions = useDecisionGraphActions();\n const { disabled } = useDecisionGraphState(({ disabled }) => ({\n disabled,\n }));\n const { modal } = App.useApp();\n const t = useT();\n\n return (\n <GraphNode\n id={id}\n specification={specification}\n name={data.name}\n isSelected={selected}\n handleLeft={false}\n actions={[\n <Button key='edit-table' type='text' onClick={() => graphActions.openTab(id)}>\n Configure\n </Button>,\n ]}\n menuItems={[\n {\n key: 'documentation',\n icon: <BookOutlined />,\n label: 'Documentation',\n onClick: () => window.open(specification.documentationUrl, '_href'),\n },\n {\n key: 'delete',\n icon: <DeleteOutlined />,\n danger: true,\n label: <SpacedText left={t('common.delete')} right={platform.shortcut('Backspace')} />,\n disabled,\n onClick: () =>\n modal.confirm({\n icon: null,\n title: t('dg.node.deleteNode'),\n content: (\n <Typography.Text>\n Are you sure you want to delete <Typography.Text strong>{data.name}</Typography.Text> node.\n </Typography.Text>\n ),\n okButtonProps: { danger: true },\n onOk: () => graphActions.removeNodes([id]),\n }),\n },\n ]}\n />\n );\n },\n getDiffContent: (current, previous): any => {\n const fields: DiffMetadata['fields'] = {};\n return produce(current || {}, (draft) => {\n if ((current?.schema || '')?.trim?.() !== (previous?.schema || '')?.trim?.()) {\n _.set(fields, 'schema', {\n previousValue: previous?.schema || '',\n status: 'modified',\n });\n }\n\n const hasModifications = Object.keys(fields).length > 0;\n\n if (hasModifications) {\n draft._diff = {\n status: 'modified',\n fields,\n };\n }\n return draft;\n });\n },\n};\n","import { FormatPainterOutlined, ImportOutlined } from '#icons';\nimport InformationIcon from '#reui/icons/animated/outline/information';\nimport { DiffEditor, Editor } from '@monaco-editor/react';\nimport { type editor } from 'monaco-editor';\nimport React, { useEffect, useMemo, useRef, useState } from 'react';\nimport { PanelGroup } from 'react-resizable-panels';\nimport { match } from 'ts-pattern';\nimport { useThrottledCallback } from 'use-debounce';\n\nimport { useThemeMode } from '../../../theme';\nimport { useT } from '../../../theming/i18n';\nimport { Button, Space, Spin, Tabs, Tooltip } from '../../primitives';\nimport { useDecisionGraphActions, useDecisionGraphState, useNodeDiff } from '../context/dg-store.context';\nimport { useTabSerializer } from '../context/serializer.context';\nimport { JsonToJsonSchemaDialog } from './json-to-json-schema-dialog';\n\nconst schemaTooltip = 'Provide JSON Schema format. If no JSON Schema is provided, validation will be skipped.';\n\nconst monacoOptions: editor.IStandaloneEditorConstructionOptions = {\n automaticLayout: true,\n contextmenu: false,\n fontSize: 13,\n fontFamily: 'var(--mono-font-family)',\n tabSize: 2,\n minimap: { enabled: false },\n overviewRulerBorder: false,\n scrollbar: {\n verticalSliderSize: 4,\n verticalScrollbarSize: 4,\n horizontalScrollbarSize: 4,\n horizontalSliderSize: 4,\n },\n};\n\nenum TabKey {\n Schema = 'Schema',\n}\n\nexport type TabJsonSchemaProps = {\n id: string;\n type?: 'input' | 'output';\n};\n\nexport const TabJsonSchema: React.FC<TabJsonSchemaProps> = ({ id, type = 'input' }) => {\n const graphActions = useDecisionGraphActions();\n\n const language = 'json';\n\n const mode = useThemeMode();\n\n const t = useT();\n const [jsonToJsonSchemaOpen, setJsonToJsonSchemaOpen] = useState(false);\n\n const [activeTab, setActiveTab] = useState(TabKey.Schema);\n\n const [editor, setEditor] = useState<editor.IStandaloneCodeEditor>();\n const [diffEditor, setDiffEditor] = useState<editor.IStandaloneDiffEditor>();\n const pendingViewStateRef = useRef<editor.ICodeEditorViewState | null>(null);\n const resizeEditor = useThrottledCallback(() => editor?.layout(), 100, { trailing: true });\n const resizeDiffEditor = useThrottledCallback(() => diffEditor?.layout(), 100, { trailing: true });\n\n useTabSerializer<editor.ICodeEditorViewState | null>(id, 'monaco', {\n serialize: () => editor?.saveViewState() ?? pendingViewStateRef.current ?? null,\n restore: (state) => {\n if (!state) return;\n if (editor) {\n editor.restoreViewState(state);\n } else {\n pendingViewStateRef.current = state;\n }\n },\n });\n\n useEffect(() => {\n if (editor && pendingViewStateRef.current) {\n editor.restoreViewState(pendingViewStateRef.current);\n pendingViewStateRef.current = null;\n }\n }, [editor]);\n\n const { disabled, content } = useDecisionGraphState(({ simulate, disabled, decisionGraph }) => ({\n nodeError: match(simulate)\n .with({ error: { data: { nodeId: id } } }, ({ error }) => error)\n .otherwise(() => null),\n disabled,\n content: (decisionGraph?.nodes ?? []).find((node) => node.id === id)?.content,\n }));\n\n const { contentDiff } = useNodeDiff(id);\n\n const previousValue = useMemo(() => {\n return contentDiff?.fields?.schema?.previousValue;\n }, [contentDiff]);\n\n useEffect(() => {\n window.addEventListener('resize', resizeEditor);\n return () => window.removeEventListener('resize', resizeEditor);\n }, [resizeEditor, editor]);\n\n useEffect(() => {\n window.addEventListener('resize', resizeDiffEditor);\n return () => window.removeEventListener('resize', resizeDiffEditor);\n }, [resizeDiffEditor, diffEditor]);\n\n return (\n <div\n className='relative box-border flex flex-col'\n data-theme={mode}\n style={\n {\n 'height': '100%',\n '--color-text': 'var(--grl-color-text-base)',\n '--color-background-elevated': 'var(--card)',\n '--color-border': 'var(--border)',\n '--line-height': 1.5,\n } as React.CSSProperties\n }\n >\n <PanelGroup className='flex-1' direction='horizontal' autoSaveId={`jdm-editor:${type}:schema:layout`}>\n <div className='h-full w-full'>\n <div className='flex h-full flex-col overflow-hidden bg-[var(--card)]'>\n <div className='flex shrink-0 items-center border-b border-b-[var(--border)] bg-[var(--grl-color-primary-bg-fade)]'>\n <Tabs\n rootClassName='grl-inline-tabs'\n size='small'\n style={{ width: '100%' }}\n items={Object.values(TabKey).map((t) => ({\n key: t,\n label: (\n <span>\n {t}{' '}\n <Tooltip title={schemaTooltip}>\n <span className='ml-1 inline-flex align-super opacity-50 [&_svg]:block'>\n <InformationIcon className='size-2.5' />\n </span>\n </Tooltip>\n </span>\n ),\n }))}\n activeKey={activeTab}\n onChange={(t) => setActiveTab(t as TabKey)}\n tabBarExtraContent={\n <Space style={{ marginRight: 8 }} size={'small'}>\n <Tooltip title={t('dg.schema.formatCode')} placement='bottomRight'>\n <Button\n size='small'\n type='text'\n disabled={disabled}\n icon={<FormatPainterOutlined />}\n onClick={() => editor?.getAction?.('editor.action.formatDocument')?.run?.()}\n />\n </Tooltip>\n <Tooltip title={t('dg.schema.importFromJson')} placement='bottomRight'>\n <Button\n type='text'\n size={'small'}\n disabled={disabled}\n icon={<ImportOutlined />}\n onClick={() => {\n setJsonToJsonSchemaOpen(true);\n }}\n />\n </Tooltip>\n </Space>\n }\n />\n </div>\n <div className='grow overflow-y-auto'>\n {match(activeTab)\n .with(TabKey.Schema, () =>\n previousValue !== undefined ? (\n <DiffEditor\n loading={<Spin size='large' />}\n language={language}\n original={previousValue}\n modified={content?.schema}\n onMount={(editor) => setDiffEditor(editor)}\n theme={mode === 'dark' ? 'vs-dark' : 'light'}\n height='100%'\n options={{\n ...monacoOptions,\n readOnly: true,\n }}\n />\n ) : (\n <Editor\n loading={<Spin size='large' />}\n language={language}\n value={content?.schema || ''}\n onMount={(editor) => setEditor(editor)}\n onChange={(value) => {\n graphActions.updateNode(id, (draft) => {\n draft.content = { schema: value };\n return draft;\n });\n }}\n theme={mode === 'dark' ? 'vs-dark' : 'light'}\n height='100%'\n options={{\n ...monacoOptions,\n readOnly: disabled,\n }}\n />\n ),\n )\n .exhaustive()}\n </div>\n <JsonToJsonSchemaDialog\n isOpen={jsonToJsonSchemaOpen}\n onDismiss={() => setJsonToJsonSchemaOpen(false)}\n onSuccess={({ schema, model }) => {\n localStorage.setItem(`${id}-model`, model);\n graphActions.updateNode(id, (draft) => {\n draft.content = { schema };\n return draft;\n });\n setJsonToJsonSchemaOpen(false);\n }}\n model={localStorage.getItem(`${id}-model`) || undefined}\n />\n </div>\n </div>\n </PanelGroup>\n </div>\n );\n};\n","import { produce } from 'immer';\nimport _ from 'lodash';\nimport { ArrowRightFromLineIcon } from 'lucide-react';\nimport React from 'react';\nimport type { z } from 'zod';\n\nimport type { outputNodeSchema } from '../../../../helpers/schema';\nimport { Button } from '../../../primitives';\nimport { useDecisionGraphActions } from '../../context/dg-store.context';\nimport type { Diff, DiffMetadata } from '../../dg-types';\nimport { TabJsonSchema } from '../../graph/tab-json-schema';\nimport { GraphNode } from '../graph-node';\nimport { NodeColor } from './colors';\nimport type { NodeSpecification } from './specification-types';\nimport { NodeKind } from './specification-types';\n\ntype InferredContent = z.infer<typeof outputNodeSchema>['content'];\n\nexport type NodeOutputData = InferredContent & Diff;\n\nexport const outputSpecification: NodeSpecification<NodeOutputData> = {\n type: NodeKind.Output,\n icon: <ArrowRightFromLineIcon size='1em' />,\n color: NodeColor.Green,\n displayName: 'Response',\n documentationUrl: 'https://gorules.io/docs/user-manual/decision-modeling/decisions',\n shortDescription: 'Outputs the context',\n generateNode: () => ({ name: 'response', content: { schema: '' } }),\n renderTab: ({ id }) => <TabJsonSchema id={id} type={'output'} />,\n renderNode: ({ id, data, selected, specification }) => {\n const graphActions = useDecisionGraphActions();\n return (\n <GraphNode\n id={id}\n specification={specification}\n name={data.name}\n isSelected={selected}\n handleRight={false}\n actions={[\n <Button key='edit-table' type='text' onClick={() => graphActions.openTab(id)}>\n Configure\n </Button>,\n ]}\n />\n );\n },\n getDiffContent: (current, previous): any => {\n const fields: DiffMetadata['fields'] = {};\n return produce(current || {}, (draft) => {\n if ((current?.schema || '')?.trim?.() !== (previous?.schema || '')?.trim?.()) {\n _.set(fields, 'schema', {\n previousValue: previous?.schema || '',\n status: 'modified',\n });\n }\n\n const hasModifications = Object.keys(fields).length > 0;\n\n if (hasModifications) {\n draft._diff = {\n status: 'modified',\n fields,\n };\n }\n return draft;\n });\n },\n};\n","import { produce } from 'immer';\nimport _ from 'lodash';\n\nimport type { DiffMetadata } from '../../../dg-types';\nimport { compareAndUnifyLists } from '../../../diff/comparison';\nimport type { NodeSwitchData } from './types';\n\n/** Compute statement-level + node-level diff metadata between two switch contents. */\nexport const diffSwitchContent = (current: NodeSwitchData, previous: NodeSwitchData): NodeSwitchData => {\n return produce(current, (draft) => {\n const fields: DiffMetadata['fields'] = {};\n if ((current.hitPolicy ?? '') !== (previous.hitPolicy ?? '')) {\n _.set(fields, 'hitPolicy', {\n status: 'modified',\n previousValue: current.hitPolicy,\n });\n }\n\n const statements = compareAndUnifyLists(current?.statements || [], previous?.statements || [], {\n compareFields: (current, previous) => {\n const hasConditionChange = (current.condition ?? '') !== previous.condition;\n\n return {\n hasChanges: hasConditionChange,\n fields: {\n ...(hasConditionChange && {\n condition: {\n status: 'modified',\n previousValue: previous.condition,\n },\n }),\n },\n };\n },\n });\n\n draft.statements = statements;\n if (\n statements.find(\n (statement) =>\n statement?._diff?.status === 'modified' ||\n statement?._diff?.status === 'added' ||\n statement?._diff?.status === 'removed',\n )\n ) {\n _.set(fields, 'statements', {\n status: 'modified',\n });\n }\n\n if (Object.keys(fields).length > 0) {\n draft._diff = {\n status: 'modified',\n fields,\n };\n }\n return draft;\n });\n};\n","import { DeleteOutlined } from '#icons';\nimport type { VariableType } from '@gorules/zen-engine-wasm';\nimport { Handle, Position } from '@xyflow/react';\nimport clsx from 'clsx';\nimport React, { useLayoutEffect, useState } from 'react';\n\nimport { useT } from '../../../../../theming/i18n';\nimport { Button, Popconfirm } from '../../../../primitives';\nimport { DiffCodeEditor } from '../../../../shared/diff-ce';\nimport type { DiffMetadata } from '../../../dg-types';\n\nconst useSyncedValue = (value: string | undefined): [string | undefined, (val: string) => void] => {\n const [inner, setInner] = useState(value);\n useLayoutEffect(() => {\n if (inner !== value) {\n setInner(value);\n }\n }, [value]);\n\n return [inner, setInner];\n};\n\nexport const SwitchHandle: React.FC<{\n id?: string;\n value?: string;\n isDefault?: boolean;\n diff?: DiffMetadata;\n onChange?: (value: string) => void;\n onSetIsDefault?: (isDefault: boolean) => void;\n onDelete?: () => void;\n disabled?: boolean;\n isActive?: boolean;\n configurable?: boolean;\n hitPolicy: 'first' | 'collect';\n totalStatements: number;\n index: number;\n variableType?: VariableType;\n}> = ({\n id,\n value,\n diff,\n onChange,\n disabled,\n configurable = true,\n onDelete,\n isActive,\n index = 0,\n isDefault = false,\n onSetIsDefault,\n totalStatements,\n hitPolicy,\n variableType,\n}) => {\n const t = useT();\n const [inner, setInner] = useSyncedValue(value);\n const handleChange = (val: string) => {\n setInner(val);\n onChange?.(val);\n };\n\n const isLastIndex = index === totalStatements - 1;\n\n const isElse =\n isDefault && hitPolicy === 'first' && isLastIndex && index > 0 && (value || '')?.trim?.()?.length === 0;\n\n return (\n <div\n className={clsx(\n isActive && 'bg-[var(--grl-color-success-bg)]',\n diff?.status === 'added' && 'bg-[var(--grl-color-success-bg)]',\n diff?.status === 'modified' && 'bg-[var(--grl-color-warning-bg)]',\n diff?.status === 'removed' && 'bg-[var(--grl-color-error-bg)]',\n )}\n >\n <div className={clsx('relative flex flex-row px-(--node-horizontal-padding) py-1')}>\n {(index === 0 || hitPolicy === 'collect') && (\n <Button disabled={disabled} className={clsx('text-xs font-medium')} size={'small'} type={'text'}>\n If\n </Button>\n )}\n {hitPolicy !== 'collect' && index > 0 && (\n <Button\n className={clsx('text-xs font-medium', isElse && 'text-[var(--grl-color-text-disabled)]')}\n size={'small'}\n type={'text'}\n disabled={disabled}\n onClick={() => {\n if (isLastIndex && hitPolicy === 'first') {\n onSetIsDefault?.(false);\n }\n }}\n >\n Else If\n </Button>\n )}\n {hitPolicy !== 'collect' && index > 0 && isLastIndex && (\n <Button\n className={clsx('text-xs font-medium', !isElse && 'text-[var(--grl-color-text-disabled)]')}\n size={'small'}\n type={'text'}\n disabled={disabled}\n onClick={() => {\n if (isLastIndex && hitPolicy === 'first') {\n onSetIsDefault?.(true);\n }\n }}\n >\n Else\n </Button>\n )}\n <div\n style={{\n flexGrow: 1,\n }}\n />\n {!disabled && configurable && (\n <Popconfirm\n title={t('dg.condition.removeConfirm')}\n okText={t('common.remove')}\n onConfirm={() => onDelete?.()}\n >\n <Button\n className='text-[var(--grl-color-text-disabled)]'\n size='small'\n type='text'\n icon={<DeleteOutlined />}\n />\n </Popconfirm>\n )}\n <Handle\n id={id}\n type='source'\n position={Position.Right}\n className={clsx(isActive && 'border-[var(--grl-color-success)]! bg-[var(--grl-color-success-bg)]!')}\n />\n </div>\n {!isElse && (\n <div className='flex px-(--node-horizontal-padding) pb-[7px] pt-0'>\n <DiffCodeEditor\n style={{\n fontSize: 12,\n lineHeight: '20px',\n width: '100%',\n }}\n displayDiff={diff?.fields?.condition?.status === 'modified'}\n previousValue={diff?.fields?.condition?.previousValue}\n value={inner}\n maxRows={4}\n disabled={disabled}\n onChange={handleChange}\n variableType={variableType}\n />\n </div>\n )}\n </div>\n );\n};\n\nexport const SwitchHandleCompact: React.FC<{\n id?: string;\n value?: string;\n isDefault?: boolean;\n diff?: DiffMetadata;\n onChange?: (value: string) => void;\n onSetIsDefault?: (isDefault: boolean) => void;\n onDelete?: () => void;\n disabled?: boolean;\n isActive?: boolean;\n configurable?: boolean;\n hitPolicy: 'first' | 'collect';\n totalStatements: number;\n index: number;\n variableType?: VariableType;\n}> = ({ id, value, diff, onChange, disabled, configurable = true, onDelete, isActive, variableType }) => {\n const t = useT();\n const [inner, setInner] = useSyncedValue(value);\n const handleChange = (val: string) => {\n setInner(val);\n onChange?.(val);\n };\n\n return (\n <div\n className={clsx(\n isActive && 'bg-[var(--grl-color-success-bg)]',\n diff?.status === 'added' && 'bg-[var(--grl-color-success-bg)]',\n diff?.status === 'modified' && 'bg-[var(--grl-color-warning-bg)]',\n diff?.status === 'removed' && 'bg-[var(--grl-color-error-bg)]',\n )}\n >\n <div className={clsx('flex p-[8px_10px] [&_.cm-editor]:pr-3.5')}>\n <DiffCodeEditor\n style={{\n fontSize: 12,\n lineHeight: '20px',\n width: '100%',\n }}\n displayDiff={diff?.fields?.condition?.status === 'modified'}\n previousValue={diff?.fields?.condition?.previousValue}\n value={inner}\n maxRows={4}\n disabled={disabled}\n onChange={handleChange}\n variableType={variableType}\n />\n </div>\n {!disabled && configurable && (\n <div className='absolute right-3.5 top-2.5'>\n <Popconfirm\n title={t('dg.condition.removeConfirm')}\n okText={t('common.remove')}\n onConfirm={() => onDelete?.()}\n >\n <Button\n className='text-[var(--grl-color-text-disabled)]'\n size='small'\n type='text'\n icon={<DeleteOutlined />}\n />\n </Popconfirm>\n </div>\n )}\n <Handle\n id={id}\n type='source'\n position={Position.Right}\n className={clsx(isActive && 'border-[var(--grl-color-success)]! bg-[var(--grl-color-success-bg)]!')}\n />\n </div>\n );\n};\n","import { ArrowRightOutlined, DownOutlined } from '#icons';\nimport clsx from 'clsx';\nimport React, { useMemo } from 'react';\nimport { useInView } from 'react-intersection-observer';\nimport { P, match } from 'ts-pattern';\n\nimport { useNodeType } from '../../../../../helpers/node-type';\nimport { Button, Dropdown, Typography } from '../../../../primitives';\nimport { useDecisionGraphActions, useDecisionGraphState } from '../../../context/dg-store.context';\nimport type { SimulationTrace, SimulationTraceDataSwitch } from '../../../simulator/simulation.types';\nimport { GraphNode } from '../../graph-node';\nimport type { MinimalNodeProps, NodeSpecification } from '../specification-types';\nimport { SwitchHandle, SwitchHandleCompact } from './switch-handle';\nimport type { NodeSwitchData, SwitchStatement } from './types';\n\nexport const SwitchNode: React.FC<\n MinimalNodeProps & {\n specification: Pick<NodeSpecification, 'displayName' | 'icon' | 'documentationUrl'>;\n }\n> = ({ id, data, selected, specification }) => {\n const graphActions = useDecisionGraphActions();\n const { ref: inViewRef, inView } = useInView({ delay: 1_000 });\n const { content, disabled, nodeTrace, compactMode, isGraphActive } = useDecisionGraphState(\n ({ decisionGraph, disabled, simulate, compactMode, activeTab }) => ({\n nodeTrace: match(simulate)\n .with({ result: P._ }, ({ result }) => result?.trace?.[id] as SimulationTrace<SimulationTraceDataSwitch>)\n .otherwise(() => null),\n content: (decisionGraph?.nodes || []).find((n) => n?.id === id)?.content as NodeSwitchData | undefined,\n disabled,\n compactMode,\n isGraphActive: activeTab === 'graph',\n }),\n );\n\n const nodeType = useNodeType(id, { disabled: !isGraphActive || !inView });\n const statements: SwitchStatement[] = content?.statements || [];\n const hitPolicy = content?.hitPolicy || 'first';\n\n const changeHitPolicy = (hitPolicy: string) => {\n graphActions.updateNode(id, (node) => {\n node.content.hitPolicy = hitPolicy;\n return node;\n });\n };\n\n const Handle = useMemo(() => (compactMode ? SwitchHandleCompact : SwitchHandle), [compactMode]);\n\n return (\n <GraphNode\n id={id}\n ref={inViewRef}\n className={clsx(['h-auto w-[220px] rounded p-0'])}\n specification={specification}\n name={data.name}\n handleRight={false}\n helper={[<ArrowRightOutlined key='arrow-right' />]}\n noBodyPadding\n isSelected={selected}\n actions={[\n <Button\n key='add condition'\n type='text'\n disabled={disabled}\n onClick={() => {\n if (hitPolicy === 'first' && statements?.length > 0) {\n graphActions.updateNode(id, (draft) => {\n draft.content.statements = ((draft.content.statements || []) as SwitchStatement[]).map((statement) => {\n if (statement.isDefault) {\n statement.isDefault = false;\n }\n return statement;\n });\n draft.content.statements.push({ id: crypto.randomUUID(), condition: '', isDefault: true });\n return draft;\n });\n } else {\n graphActions.updateNode(id, (draft) => {\n draft.content.statements = ((draft.content.statements || []) as SwitchStatement[]).map((statement) => {\n if (statement.isDefault) {\n statement.isDefault = false;\n }\n return statement;\n });\n draft.content.statements.push({ id: crypto.randomUUID(), condition: '', isDefault: false });\n return draft;\n });\n }\n }}\n >\n Add Condition\n </Button>,\n <Dropdown\n key='hitPolicy'\n trigger={['click']}\n placement='bottomRight'\n menu={{\n items: [\n {\n key: 'first',\n label: 'First',\n onClick: () => changeHitPolicy('first'),\n disabled,\n },\n {\n key: 'collect',\n label: 'Collect',\n disabled,\n onClick: () => {\n graphActions.updateNode(id, (draft) => {\n draft.content.statements = ((draft.content.statements || []) as SwitchStatement[]).map(\n (statement) => {\n if (statement.isDefault) {\n statement.isDefault = false;\n }\n return statement;\n },\n );\n return draft;\n });\n changeHitPolicy('collect');\n },\n },\n ],\n }}\n >\n <Button type='text' style={{ textTransform: 'capitalize', marginLeft: 'auto' }}>\n {hitPolicy} <DownOutlined />\n </Button>\n </Dropdown>,\n ]}\n >\n <div className='flex w-full flex-col items-stretch'>\n <div className='nodrag box-border flex w-full flex-col'>\n {!(statements?.length > 0) && (\n <Typography.Text type={'secondary'} className={'px-3'}>\n No conditions\n </Typography.Text>\n )}\n {statements.map((statement, index) => (\n <Handle\n key={statement.id}\n index={index}\n value={statement.condition}\n diff={statement?._diff}\n id={statement.id}\n isDefault={statement.isDefault}\n totalStatements={statements.length}\n disabled={disabled}\n hitPolicy={hitPolicy}\n variableType={nodeType}\n onSetIsDefault={(val) => {\n graphActions.updateNode(id, (draft) => {\n const draftStatement = draft.content.statements.find((s: SwitchStatement) => {\n return s.id === statement.id;\n });\n if (val) {\n draftStatement.condition = '';\n }\n draftStatement.isDefault = val;\n return draft;\n });\n }}\n isActive={match(nodeTrace?.traceData)\n .with({ statements: P.array(P._) }, ({ statements }) =>\n statements.some((s) => typeof s === 'object' && s && 'id' in s && s.id === statement?.id),\n )\n .otherwise(() => false)}\n onDelete={() => {\n graphActions.updateNode(id, (draft) => {\n draft.content.statements = draft.content.statements.filter(\n (s: SwitchStatement) => s?.id !== statement?.id,\n );\n\n if ((draft.content.statements || []).length === 1) {\n draft.content.statements = ((draft.content.statements || []) as SwitchStatement[]).map(\n (statement) => {\n if (statement.isDefault) {\n statement.isDefault = false;\n }\n return statement;\n },\n );\n }\n\n return draft;\n });\n graphActions.removeEdgeByHandleId(statement?.id as string);\n }}\n onChange={(condition) => {\n graphActions.updateNode(id, (draft) => {\n const draftStatement = draft.content.statements.find((s: SwitchStatement) => {\n return s.id === statement.id;\n });\n\n draftStatement.condition = condition;\n return draft;\n });\n }}\n />\n ))}\n </div>\n </div>\n </GraphNode>\n );\n};\n","import { SplitIcon } from 'lucide-react';\nimport React from 'react';\n\nimport { NodeColor } from '../colors';\nimport type { NodeSpecification } from '../specification-types';\nimport { NodeKind } from '../specification-types';\nimport { diffSwitchContent } from './diff';\nimport { SwitchNode } from './switch-node';\nimport type { NodeSwitchData } from './types';\n\nexport type { NodeSwitchData, SwitchStatement } from './types';\n\nexport const switchSpecification: NodeSpecification<NodeSwitchData> = {\n type: NodeKind.Switch,\n icon: <SplitIcon size='1em' />,\n displayName: 'Switch',\n documentationUrl: 'https://gorules.io/docs/user-manual/decision-modeling/decisions/switch',\n shortDescription: 'Conditional branching',\n color: NodeColor.Purple,\n getDiffContent: (current, previous) => {\n return diffSwitchContent(current, previous);\n },\n inferTypes: {\n needsUpdate: () => false,\n determineOutputType: (state) => state.input,\n },\n generateNode: ({ index }) => ({\n name: `switch${index}`,\n content: {\n hitPolicy: 'first',\n statements: [{ id: crypto.randomUUID(), condition: '', isDefault: false }],\n },\n }),\n renderNode: ({ specification, ...props }) => <SwitchNode specification={specification} {...props} />,\n};\n","import _ from 'lodash';\nimport { P, match } from 'ts-pattern';\n\nimport type { DecisionEdge, DecisionGraphType, DecisionNode, DiffMetadata } from '../dg-types';\nimport type { CustomNodeSpecification } from '../nodes/custom-node';\nimport { decisionTableSpecification } from '../nodes/specifications/decision-table.specification';\nimport { expressionSpecification } from '../nodes/specifications/expression.specification';\nimport { functionSpecification } from '../nodes/specifications/function.specification';\nimport { inputSpecification } from '../nodes/specifications/input.specification';\nimport { outputSpecification } from '../nodes/specifications/output.specification';\nimport { NodeKind, type NodeSpecification } from '../nodes/specifications/specification-types';\nimport { switchSpecification } from '../nodes/specifications/switch.specification';\n\nexport type ProcessNodesOptions = {\n components: NodeSpecification[];\n customNodes: CustomNodeSpecification<object, any>[];\n};\n\nexport const calculateDiffGraph = (\n currentGraph: DecisionGraphType,\n previousGraph: DecisionGraphType,\n options?: ProcessNodesOptions,\n): DecisionGraphType => {\n const nodes = processNodes(currentGraph?.nodes ?? [], previousGraph?.nodes ?? [], options);\n const edges = processEdges(currentGraph?.edges ?? [], previousGraph?.edges ?? []);\n return {\n nodes,\n edges,\n };\n};\n\nexport const processNodes = (\n currentNodes: DecisionNode<any>[],\n previousNodes: DecisionNode<any>[],\n options?: ProcessNodesOptions,\n) => {\n const components = options?.components || [];\n const customNodes = options?.customNodes || [];\n\n // Start with all new version nodes\n const nodesMap = new Map();\n\n // Process new version nodes first\n (currentNodes || []).forEach((newNode) => {\n const oldNode = (previousNodes || []).find((n) => n.id === newNode.id);\n\n if (!oldNode) {\n // Added node\n nodesMap.set(newNode.id, {\n ...newNode,\n _diff: {\n status: 'added',\n },\n });\n } else {\n const fields: DiffMetadata['fields'] = {};\n\n if (oldNode.position.x !== newNode.position.x || oldNode.position.y !== newNode.position.y) {\n _.set(fields, 'position', {\n status: 'moved',\n previousValue: oldNode.position,\n });\n }\n\n if (oldNode.name !== newNode.name) {\n _.set(fields, 'name', {\n status: 'modified',\n previousValue: oldNode.name,\n });\n }\n\n const calculatedContent = match([newNode.type, oldNode.type])\n .with([NodeKind.Output, NodeKind.Output], () =>\n outputSpecification?.getDiffContent?.(newNode?.content, oldNode?.content),\n )\n .with([NodeKind.Input, NodeKind.Input], () =>\n inputSpecification?.getDiffContent?.(newNode?.content, oldNode?.content),\n )\n .with([NodeKind.Expression, NodeKind.Expression], () =>\n expressionSpecification?.getDiffContent?.(newNode?.content, oldNode?.content),\n )\n .with([NodeKind.DecisionTable, NodeKind.DecisionTable], () =>\n decisionTableSpecification?.getDiffContent?.(newNode?.content, oldNode?.content),\n )\n .with([NodeKind.Function, NodeKind.Function], () => {\n const content: any = functionSpecification?.getDiffContent?.(newNode?.content, oldNode?.content);\n return match(newNode?.content)\n .with(P.string, () => {\n if (content?._diff?.fields?.source?.status === 'modified') {\n _.set(fields, 'content', {\n status: 'modified',\n previousValue: content?._diff?.fields?.source?.previousValue,\n });\n }\n return content?.source;\n })\n .otherwise(() => content);\n })\n .with([NodeKind.Switch, NodeKind.Switch], () =>\n switchSpecification?.getDiffContent?.(newNode?.content, oldNode?.content),\n )\n .otherwise(() => {\n const component = components.find((cmp) => cmp.type === newNode.type);\n if (component) {\n return component?.getDiffContent?.(newNode?.content, oldNode?.content);\n }\n\n const customNode = customNodes.find(\n (node) => newNode?.type === 'customNode' && newNode?.content?.kind === node?.kind,\n );\n if (customNode) {\n return customNode?.calculateDiff?.(newNode?.content, oldNode?.content);\n }\n\n return null;\n });\n\n if (\n Object.keys(fields || {}).filter((key) => key !== 'position').length > 0 ||\n calculatedContent?._diff?.status === 'modified'\n ) {\n nodesMap.set(newNode.id, {\n ...newNode,\n content: calculatedContent ?? newNode.content,\n _diff: {\n status: 'modified',\n fields,\n },\n });\n } else if (Object.keys(fields || {}).length === 1 && fields?.position?.status === 'moved') {\n nodesMap.set(newNode.id, {\n ...newNode,\n content: calculatedContent ?? newNode.content,\n _diff: {\n status: 'moved',\n fields,\n },\n });\n } else {\n nodesMap.set(newNode.id, {\n ...newNode,\n _diff: {\n status: 'unchanged',\n },\n });\n }\n }\n });\n\n // Add deleted nodes from old version\n (previousNodes || []).forEach((oldNode) => {\n if (!nodesMap.has(oldNode.id)) {\n nodesMap.set(oldNode.id, {\n ...oldNode,\n _diff: {\n status: 'removed',\n },\n });\n }\n });\n\n return Array.from(nodesMap.values());\n};\n\nexport const processEdges = (currentEdges: DecisionEdge[], previousEdges: DecisionEdge[]) => {\n const edgesMap = new Map();\n\n // Process new version edges\n (currentEdges || []).forEach((newEdge) => {\n const oldEdge = (previousEdges || []).find((e) => e.id === newEdge.id);\n\n if (!oldEdge) {\n edgesMap.set(newEdge.id, {\n ...newEdge,\n _diff: {\n status: 'added',\n },\n });\n } else {\n edgesMap.set(newEdge.id, {\n ...newEdge,\n _diff: {\n status: 'unchanged',\n },\n });\n }\n });\n\n // Add deleted edges from old version\n (previousEdges || []).forEach((oldEdge) => {\n if (!edgesMap.has(oldEdge.id)) {\n edgesMap.set(oldEdge.id, {\n ...oldEdge,\n _diff: {\n status: 'removed',\n },\n });\n }\n });\n\n return Array.from(edgesMap.values());\n};\n","import equal from 'fast-deep-equal/es6/react';\nimport type React from 'react';\nimport { useEffect, useRef } from 'react';\nimport { useDebouncedCallback } from 'use-debounce';\n\nimport type { DictionaryMap } from '../../theme';\nimport type { JdmUiMode } from '../decision-table/context/dt-store.context';\nimport {\n type DecisionGraphStoreType,\n useDecisionGraphActions,\n useDecisionGraphRaw,\n useDecisionGraphState,\n} from './context/dg-store.context';\nimport { type DecisionGraphType } from './dg-types';\nimport { calculateDiffGraph } from './diff/utility';\n\nexport type DecisionGraphEmptyType = {\n id?: string;\n defaultValue?: DecisionGraphType;\n value?: DecisionGraphType;\n\n disabled?: boolean;\n\n /**\n * 画布 diff 对比模式(P2):提供基线图后,画布叠加差异标记(新增/删除/修改\n * 节点与边按 _diff 元数据染色,见 decision-node)。建议配合 `disabled` 使用\n * (只读对比);diff 标注仅存在于渲染投影,切回正常模式即消失。\n */\n diffBaseline?: DecisionGraphType;\n\n components?: DecisionGraphStoreType['state']['components'];\n customNodes?: DecisionGraphStoreType['state']['customNodes'];\n\n hideLeftToolbar?: DecisionGraphStoreType['state']['hideLeftToolbar'];\n\n name?: DecisionGraphStoreType['state']['name'];\n\n viewConfigCta?: DecisionGraphStoreType['state']['viewConfigCta'];\n viewConfig?: DecisionGraphStoreType['state']['viewConfig'];\n onViewConfigCta?: DecisionGraphStoreType['listeners']['onViewConfigCta'];\n\n defaultActivePanel?: string;\n panels?: DecisionGraphStoreType['state']['panels'];\n onPanelsChange?: DecisionGraphStoreType['listeners']['onPanelsChange'];\n\n simulate?: DecisionGraphStoreType['state']['simulate'];\n\n dictionaries?: DictionaryMap;\n mode?: JdmUiMode;\n\n onChange?: DecisionGraphStoreType['listeners']['onChange'];\n onReactFlowInit?: DecisionGraphStoreType['listeners']['onReactFlowInit'];\n\n onCodeExtension?: DecisionGraphStoreType['listeners']['onCodeExtension'];\n onFunctionReady?: DecisionGraphStoreType['listeners']['onFunctionReady'];\n};\n\nexport const DecisionGraphEmpty: React.FC<DecisionGraphEmptyType> = ({\n id,\n defaultValue,\n value,\n name,\n disabled = false,\n diffBaseline,\n onChange,\n components,\n customNodes,\n defaultActivePanel,\n hideLeftToolbar,\n panels,\n simulate,\n dictionaries,\n mode,\n viewConfigCta,\n viewConfig,\n onViewConfigCta,\n onPanelsChange,\n onReactFlowInit,\n onCodeExtension,\n onFunctionReady,\n}) => {\n const mountedRef = useRef(false);\n const graphActions = useDecisionGraphActions();\n const { stateStore, listenerStore } = useDecisionGraphRaw();\n const { decisionGraph, openTabs, activeTab } = useDecisionGraphState(({ decisionGraph, openTabs, activeTab }) => ({\n decisionGraph,\n openTabs,\n activeTab,\n }));\n\n const innerChange = useDebouncedCallback((graph: DecisionGraphType) => {\n onChange?.(graph);\n }, 100);\n\n useEffect(() => {\n if (viewConfig?.enabled) {\n const filtered = openTabs.filter((tab) => !!viewConfig?.permissions?.[tab]);\n\n stateStore.setState({\n openTabs: filtered,\n activeTab: !!viewConfig?.permissions?.[activeTab] ? activeTab : 'graph',\n });\n }\n }, [viewConfig]);\n\n useEffect(() => {\n stateStore.setState({\n id,\n disabled,\n components: Array.isArray(components) ? components : [],\n customNodes: Array.isArray(customNodes) ? customNodes : [],\n panels,\n viewConfig,\n viewConfigCta,\n hideLeftToolbar,\n dictionaries,\n mode,\n });\n }, [id, disabled, components, customNodes, panels, viewConfig, viewConfigCta, hideLeftToolbar, dictionaries, mode]);\n\n useEffect(() => {\n stateStore.setState({ name: name ?? 'graph.json' });\n }, [name]);\n\n useEffect(() => {\n stateStore.setState({ simulate });\n }, [simulate]);\n\n useEffect(() => {\n listenerStore.setState({\n onReactFlowInit,\n onPanelsChange,\n onCodeExtension,\n onFunctionReady,\n onViewConfigCta,\n });\n }, [onReactFlowInit, onPanelsChange, onCodeExtension, onFunctionReady, onViewConfigCta]);\n\n useEffect(() => {\n listenerStore.setState({ onChange: innerChange });\n }, [innerChange]);\n\n useEffect(() => {\n // diff 对比模式下由下方「diffBaseline 重算」effect 接管渲染投影,此处跳过\n if (value === undefined || diffBaseline) {\n return;\n }\n if (mountedRef.current && !equal(value, decisionGraph)) {\n graphActions.setDecisionGraph(value);\n }\n }, [value, diffBaseline]);\n\n useEffect(() => {\n if (value !== undefined) {\n graphActions.setDecisionGraph(\n diffBaseline\n ? calculateDiffGraph(value, diffBaseline, { customNodes: customNodes ?? [], components: components ?? [] })\n : value,\n );\n } else if (defaultValue !== undefined) {\n graphActions.setDecisionGraph(defaultValue);\n }\n\n stateStore.setState({\n activePanel: defaultActivePanel,\n hideLeftToolbar,\n });\n mountedRef.current = true;\n }, []);\n\n // diffBaseline 变化(切换对比版本 / 移除对比)→ 重算渲染投影或恢复裸图\n useEffect(() => {\n if (value === undefined) {\n return;\n }\n if (diffBaseline) {\n graphActions.setDecisionGraph(\n calculateDiffGraph(value, diffBaseline, { customNodes: customNodes ?? [], components: components ?? [] }),\n );\n } else if (mountedRef.current) {\n graphActions.setDecisionGraph(value);\n }\n }, [diffBaseline]);\n\n return null;\n};\n","import { type Edge, type Node, getIncomers, getOutgoers } from '@xyflow/react';\nimport equal from 'fast-deep-equal/es6/react';\n\nimport type { DecisionGraphType, DecisionNode } from '../components';\nimport { mapToGraphEdges, mapToGraphNodes } from '../components/decision-graph/dg-util';\n\ntype GraphWalkerCache = {\n digest: ReturnType<typeof decisionGraphPathDigest>;\n iterator: CachedGraphIterator;\n};\n\nexport const createGraphWalker = () => {\n let cache: GraphWalkerCache | null = null;\n\n return {\n walk: function* (decisionGraph: DecisionGraphType): Generator<WalkGraphReturn> {\n const digest = decisionGraphPathDigest(decisionGraph);\n if (cache && equal(digest, cache.digest)) {\n yield* walkCachedGraph(decisionGraph, cache.iterator);\n return;\n }\n\n const iterator = [];\n for (const res of walkGraph(decisionGraph)) {\n iterator.push({ id: res.node.id, incomers: res.incomers.map((n) => n.id) });\n yield res;\n }\n\n cache = { digest, iterator };\n },\n };\n};\n\nexport type GraphWalker = ReturnType<typeof createGraphWalker>;\n\nconst decisionGraphPathDigest = (graph: DecisionGraphType) => {\n const nodes = graph.nodes.map((n) => n.id);\n const edges = graph.edges;\n\n return { nodes, edges };\n};\n\ntype WalkGraphReturn = {\n node: DecisionNode;\n incomers: DecisionNode[];\n};\n\nfunction* walkGraph(decisionGraph: DecisionGraphType): Generator<WalkGraphReturn> {\n const nodes = mapToGraphNodes(decisionGraph.nodes);\n const edges = mapToGraphEdges(decisionGraph.edges);\n\n const begin = decisionGraph.nodes.find((n) => n.type === 'inputNode');\n const beginRf = nodes.find((n) => n.id === begin?.id);\n if (!begin || !beginRf) {\n return;\n }\n\n // TODO: Perf - Skip recalculating has cycle, or find a nicer way to check (as it's blocked on graph level)\n if (hasCycle(beginRf, nodes, edges)) {\n return;\n }\n\n yield { node: begin, incomers: [] };\n const visited = new Set<string>();\n\n visited.add(begin.id);\n\n const stack = getOutgoers(beginRf, nodes, edges);\n while (stack.length > 0) {\n const current = stack.pop()!;\n if (visited.has(current.id)) {\n continue;\n }\n\n const incomers = getIncomers(current, nodes, edges);\n const unvisitedIncomers = incomers.filter((incomer) => !visited.has(incomer.id));\n\n if (unvisitedIncomers.length > 0) {\n stack.push(current, ...unvisitedIncomers);\n continue;\n }\n\n visited.add(current.id);\n const decisionNode = decisionGraph.nodes.find((n) => n.id === current.id);\n if (decisionNode) {\n const mappedIncomers = decisionGraph.nodes.filter((n) => incomers.some((inc) => inc.id === n.id));\n yield { node: decisionNode, incomers: mappedIncomers };\n }\n\n const outgoers = getOutgoers(current, nodes, edges);\n stack.push(...outgoers);\n }\n}\n\ntype CachedGraphIterator = Array<{ id: string; incomers: string[] }>;\n\nfunction* walkCachedGraph(decisionGraph: DecisionGraphType, path: CachedGraphIterator): Generator<WalkGraphReturn> {\n for (const part of path) {\n const node = decisionGraph.nodes.find((n) => n.id === part.id);\n if (!node) {\n continue;\n }\n\n const incomers = decisionGraph.nodes.filter((n) => part.incomers.includes(n.id));\n yield { node, incomers };\n }\n}\n\nconst hasCycle = (begin: Node, nodes: Node[], edges: Edge[]): boolean => {\n const visited = new Set<string>();\n const recursionStack = new Set<string>();\n\n const dfs = (node: Node): boolean => {\n visited.add(node.id);\n recursionStack.add(node.id);\n\n const outgoers = getOutgoers(node, nodes, edges);\n for (const outgoer of outgoers) {\n if (!visited.has(outgoer.id)) {\n if (dfs(outgoer)) {\n return true;\n }\n } else if (recursionStack.has(outgoer.id)) {\n return true;\n }\n }\n\n recursionStack.delete(node.id);\n return false;\n };\n\n return dfs(begin);\n};\n","import { decisionTableSpecification } from './decision-table.specification';\nimport { expressionSpecification } from './expression.specification';\nimport { functionSpecification } from './function.specification';\nimport { inputSpecification } from './input.specification';\nimport { outputSpecification } from './output.specification';\nimport { NodeKind } from './specification-types';\nimport type { NodeSpecification } from './specification-types';\nimport { switchSpecification } from './switch.specification';\n\nfunction makeNodeSpecification<T extends Record<NodeKind, V>, V extends NodeSpecification>(o: T): Readonly<T> {\n return o;\n}\n\nexport const nodeSpecification = makeNodeSpecification({\n [NodeKind.Input]: inputSpecification,\n [NodeKind.Output]: outputSpecification,\n [NodeKind.DecisionTable]: decisionTableSpecification,\n [NodeKind.Expression]: expressionSpecification,\n [NodeKind.Function]: functionSpecification,\n [NodeKind.Switch]: switchSpecification,\n});\n","import { VariableType } from '@gorules/zen-engine-wasm';\nimport equal from 'fast-deep-equal/es6/react';\nimport { produce } from 'immer';\nimport { useEffect } from 'react';\nimport { P, match } from 'ts-pattern';\n\nimport type { GraphWalker } from '../../helpers/traversal';\nimport { createGraphWalker } from '../../helpers/traversal';\nimport { isWasmAvailable } from '../../helpers/wasm';\nimport type { DecisionGraphStoreType } from './context/dg-store.context';\nimport { NodeTypeKind, useDecisionGraphRaw } from './context/dg-store.context';\nimport type { NodeKind } from './nodes/specifications/specification-types';\nimport { nodeSpecification } from './nodes/specifications/specifications';\n\nexport const DecisionGraphInferTypes = () => {\n const { stateStore } = useDecisionGraphRaw();\n\n // Set variable types based on trace\n useEffect(() => {\n if (!isWasmAvailable()) {\n return;\n }\n\n return stateStore.subscribe(({ simulate, nodeTypes, decisionGraph }, prevState) => {\n try {\n if (equal(simulate, prevState?.simulate)) {\n return;\n }\n\n const trace = match(simulate)\n .with({ result: P.nonNullable }, ({ result }) => result.trace)\n .otherwise(() => null);\n if (trace === null) {\n const newNodeTypes = produce(nodeTypes, (draft) => {\n Object.values(draft).forEach((nt) => {\n delete nt[NodeTypeKind.Input];\n delete nt[NodeTypeKind.Output];\n });\n });\n\n stateStore.setState({ nodeTypes: newNodeTypes });\n return;\n }\n\n const traceValues = Object.values(trace);\n if (traceValues.length === 0) {\n return;\n }\n\n const newNodeTypes = produce(nodeTypes, (draft) => {\n traceValues.forEach((t) => {\n const node = decisionGraph.nodes.find((n) => n.id === t.id);\n if (node?.type === 'inputNode') {\n return;\n }\n\n draft[t.id] ??= {};\n\n draft[t.id][NodeTypeKind.Output] = new VariableType(t.output ?? {});\n draft[t.id][NodeTypeKind.Input] = new VariableType(t.input ?? {});\n });\n });\n\n stateStore.setState({ nodeTypes: newNodeTypes });\n } catch (err) {\n console.error('error occurred while setting up variable types from trace', err);\n }\n });\n }, []);\n\n // Infer types for nodes\n useEffect(() => {\n if (!isWasmAvailable()) {\n return;\n }\n\n const graphWalker = createGraphWalker();\n return stateStore.subscribe((state, prevState) => {\n try {\n const stateDigest = inferTypesStateDigest(state);\n const prevStateDigest = inferTypesStateDigest(prevState);\n const needUpdate = inferTypesNeedsUpdate(state, prevState);\n if (equal(stateDigest, prevStateDigest) && !needUpdate) {\n return;\n }\n\n const infer = inferNodeTypes(state, prevState, graphWalker);\n if (infer.isModified) {\n stateStore.setState({ nodeTypes: infer.nodeTypes });\n }\n } catch (err) {\n console.error('error occurred during node type inference', err);\n }\n });\n }, []);\n\n useEffect(() => {\n if (!isWasmAvailable()) {\n return;\n }\n\n return stateStore.subscribe((state, prevState) => {\n try {\n const stateDigest = globalTypesStateDigest(state);\n const prevStateDigest = globalTypesStateDigest(prevState);\n if (equal(stateDigest, prevStateDigest)) {\n return;\n }\n\n const $nodesType = VariableType.fromJson({ Object: {} });\n state.decisionGraph.nodes.forEach((node) => {\n const nodeType = state.nodeTypes[node.id];\n const nodeOutput =\n nodeType?.[NodeTypeKind.Output] ??\n nodeType?.[NodeTypeKind.InferredOutput] ??\n VariableType.fromJson({ Object: {} });\n\n $nodesType.set(node.name, nodeOutput);\n });\n\n stateStore.setState({ globalType: { $nodes: $nodesType } });\n } catch (err) {\n console.error('error occurred while global node types', err);\n }\n });\n }, []);\n\n return null;\n};\n\ntype NodeTypes = DecisionGraphStoreType['state']['nodeTypes'];\n\ntype InferNodeTypes = (\n state: DecisionGraphStoreType['state'],\n prevState: DecisionGraphStoreType['state'],\n graphWalker: GraphWalker,\n) => { nodeTypes: NodeTypes; isModified: boolean };\n\nconst inferNodeTypes: InferNodeTypes = ({ decisionGraph, nodeTypes, customNodes }, prevState, graphWalker) => {\n let isModified = false;\n const newNodeTypes = produce(nodeTypes, (draft) => {\n for (const { node, incomers } of graphWalker.walk(decisionGraph)) {\n if (node.type === 'inputNode') {\n return;\n }\n\n const incomerTypes = incomers\n .map((inc) => {\n const type = draft[inc.id] ?? {};\n return type[NodeTypeKind.Output] ?? type[NodeTypeKind.InferredOutput];\n })\n .filter((t) => !!t)\n .map((t) => t.clone());\n const inferredInputType = match(incomerTypes.length)\n .with(1, () => incomerTypes[0])\n .otherwise(() => VariableType.fromIncoming(incomerTypes));\n\n const currentInputType = draft?.[node.id]?.[NodeTypeKind.InferredInput];\n // Mutation block\n if (!currentInputType?.equal(inferredInputType)) {\n isModified = true;\n draft[node.id] ??= {};\n draft[node.id][NodeTypeKind.InferredInput] = inferredInputType;\n }\n\n const inferTypes =\n nodeSpecification[node.type as NodeKind]?.inferTypes ??\n customNodes.find((n) => n.kind === node.type)?.inferTypes;\n if (!inferTypes) {\n return;\n }\n\n const input =\n draft?.[node.id]?.[NodeTypeKind.Input] ??\n draft?.[node.id]?.[NodeTypeKind.InferredInput] ??\n VariableType.fromJson('Any');\n\n const prevInput =\n prevState.nodeTypes?.[node.id]?.[NodeTypeKind.Input] ??\n prevState.nodeTypes?.[node.id]?.[NodeTypeKind.InferredInput] ??\n VariableType.fromJson('Any');\n\n const prevContent = prevState.decisionGraph.nodes.find((n) => n.id === node.id)?.content;\n const needsUpdate = inferTypes.needsUpdate(node.content, prevContent) || !input.equal(prevInput);\n if (!needsUpdate && draft?.[node.id]?.[NodeTypeKind.InferredOutput]) {\n return;\n }\n\n const inferredOutputType = inferTypes.determineOutputType({ input, content: node.content });\n const currentOutputType = draft?.[node.id]?.[NodeTypeKind.InferredOutput];\n // Mutation block\n if (!currentOutputType?.equal(inferredOutputType)) {\n isModified = true;\n draft[node.id] ??= {};\n draft[node.id][NodeTypeKind.InferredOutput] = inferredOutputType;\n }\n }\n });\n\n return {\n isModified,\n nodeTypes: newNodeTypes,\n };\n};\n\nconst inferTypesStateDigest = ({ decisionGraph, nodeTypes, customNodes }: DecisionGraphStoreType['state']) => {\n const edgesData = decisionGraph.edges;\n const nodesData = decisionGraph.nodes.map(({ id, type }) => ({ id, type }));\n const customNodesData = customNodes.map((cn) => cn.kind);\n\n const typesData = Object.entries(nodeTypes).map(([id, value]) => ({\n id,\n input: variableTypeHash(value[NodeTypeKind.Input]),\n output: variableTypeHash(value[NodeTypeKind.Output]),\n }));\n\n const inputNodeId = decisionGraph.nodes.find((n) => n.type === 'inputNode')?.id;\n const inputNodeType = match(nodeTypes?.[inputNodeId ?? '']?.[NodeTypeKind.InferredOutput])\n .with(P.nonNullable, (type) => type.hash())\n .otherwise(() => null);\n\n return { edgesData, nodesData, typesData, customNodesData, inputNodeType };\n};\n\nconst inferTypesNeedsUpdate = (\n { decisionGraph, customNodes }: DecisionGraphStoreType['state'],\n prevState: DecisionGraphStoreType['state'],\n) => {\n const nodesNeedUpdate = decisionGraph.nodes.map((node) => {\n const inferTypes =\n nodeSpecification[node.type as NodeKind]?.inferTypes ?? customNodes.find((n) => n.kind === node.type)?.inferTypes;\n\n if (!inferTypes) {\n return false;\n }\n\n const prevNode = prevState.decisionGraph.nodes.find((n) => n.id === node.id);\n if (!prevNode) {\n return true;\n }\n\n return inferTypes.needsUpdate(node.content, prevNode.content);\n });\n\n return nodesNeedUpdate.some((up) => up);\n};\n\ndeclare module '@gorules/zen-engine-wasm' {\n interface VariableType {\n __hash: string;\n }\n}\n\nconst variableTypeHash = (vt?: VariableType): string | undefined => {\n if (!vt) {\n return undefined;\n }\n\n if (vt.__hash) {\n return vt.__hash;\n }\n\n vt.__hash = vt.hash();\n return vt.__hash;\n};\n\nconst globalTypesStateDigest = (state: DecisionGraphStoreType['state']) => {\n const nodeInfo = state.decisionGraph.nodes.map((node) => {\n const nodeType = state.nodeTypes[node.id];\n const typ = nodeType?.[NodeTypeKind.Output] ?? nodeType?.[NodeTypeKind.InferredOutput];\n return {\n id: node.id,\n type: variableTypeHash(typ),\n name: node.name,\n };\n });\n\n return { nodeInfo };\n};\n","import { CloseOutlined } from '#icons';\nimport { Resizable } from 're-resizable';\nimport React, { useMemo } from 'react';\n\nimport { useT } from '../../theming/i18n';\nimport { Button, Tooltip, Typography } from '../primitives';\nimport { useDecisionGraphActions, useDecisionGraphState } from './context/dg-store.context';\n\nconst heightKey = 'jdmEditor:graphPanel:height';\n\nexport const GraphPanel: React.FC = () => {\n const t = useT();\n const graphActions = useDecisionGraphActions();\n const { panels, activePanel: activePanelId } = useDecisionGraphState(({ panels, activePanel }) => ({\n panels,\n activePanel,\n }));\n\n const activePanel = useMemo(() => {\n return activePanelId === undefined ? undefined : (panels || []).find((panel) => panel.id === activePanelId);\n }, [activePanelId, panels]);\n\n const defaultHeight = useMemo(() => {\n return Number.parseFloat(localStorage.getItem(heightKey) ?? '') ?? 300;\n }, [activePanel]);\n\n if (!activePanel) return null;\n\n return (\n <Resizable\n className={\n // grid-area:bottom — full-width row under the canvas (template lives\n // in styles/tailwind.css; without the placement auto-positioning\n // drops this panel into the narrow right column).\n '[grid-area:bottom] relative flex h-full w-full flex-col border-t border-t-[var(--border)] bg-[var(--grl-color-primary-bg-fade)]'\n }\n defaultSize={{ height: defaultHeight }}\n handleStyles={{\n bottom: { display: 'none' },\n left: { display: 'none' },\n topLeft: { display: 'none' },\n topRight: { display: 'none' },\n right: { display: 'none' },\n bottomLeft: { display: 'none' },\n bottomRight: { display: 'none' },\n }}\n maxHeight={500}\n minHeight={150}\n onResize={(event, direction, elementRef) => {\n localStorage.setItem(heightKey, elementRef.clientHeight.toString());\n }}\n >\n {!activePanel.hideHeader && (\n <div\n className={\n 'flex flex-row items-center justify-start gap-2 border-b border-b-[var(--border)] py-1 pl-2 pr-1 [&>span]:text-[13px]'\n }\n >\n <div className={'grow'}>\n <Typography.Text style={{ fontSize: 13 }}>{activePanel.title}</Typography.Text>\n </div>\n <div className={'shrink'}>\n <Tooltip placement='topLeft' title={t('dg.toolbar.closeClose')}>\n <Button\n size={'small'}\n type={'text'}\n icon={<CloseOutlined style={{ fontSize: 12 }} />}\n onClick={() => graphActions.setActivePanel(undefined)}\n />\n </Tooltip>\n </div>\n </div>\n )}\n <div className={'min-h-0 flex-1 overflow-hidden'}>{activePanel?.renderPanel?.()}</div>\n </Resizable>\n );\n};\n","import { DeleteOutlined, PlusOutlined } from '#icons';\nimport type { EdgeProps } from '@xyflow/react';\nimport { BaseEdge, EdgeLabelRenderer, getBezierPath } from '@xyflow/react';\nimport clsx from 'clsx';\nimport React from 'react';\nimport { match } from 'ts-pattern';\n\nimport { nodeSchema } from '../../helpers/schema';\nimport { Button } from '../primitives';\nimport { useDecisionGraphActions, useDecisionGraphState, useEdgeDiff } from './context/dg-store.context';\nimport { nodeSpecification } from './nodes/specifications/specifications';\n\ntype PickerItem = {\n /** 内置节点 type;customNode 时恒为 'customNode' 并附加 component */\n type: string;\n component?: string;\n label: React.ReactNode;\n icon: React.ReactNode;\n};\n\ntype AnySpec = {\n type?: string;\n kind?: string;\n generateNode?: (o: { index: number }) => { name: string; config?: unknown };\n};\n\n/** WS1-R3:连接线\"+\"选型插入(flow-1 connector 模式)——规范清单 = 内置 + 自定义组件 */\nconst usePickerItems = (): PickerItem[] => {\n const components = useDecisionGraphState(({ components }) => components);\n const allSpecs = [\n ...(Object.values(nodeSpecification) as unknown as AnySpec[]),\n ...((components ?? []) as unknown as AnySpec[]),\n ];\n return allSpecs.map((spec) => ({\n type: spec.kind ? 'customNode' : (spec.type ?? 'customNode'),\n component: spec.kind,\n label: spec.kind\n ? ((spec as { displayName?: React.ReactNode }).displayName ?? spec.kind)\n : ((spec as { displayName?: React.ReactNode }).displayName ?? ''),\n icon: (spec as { icon?: React.ReactNode }).icon,\n }));\n};\n\nexport const CustomEdge: React.FC<EdgeProps & { sourceHandle?: string | null; targetHandle?: string | null }> = (\n props,\n) => {\n const graphActions = useDecisionGraphActions();\n const {\n id,\n source,\n target,\n sourceHandle,\n targetHandle,\n sourceX,\n sourceY,\n targetX,\n targetY,\n sourcePosition,\n targetPosition,\n style = {},\n markerEnd,\n } = props;\n const { isHovered, disabled, decisionGraph, components } = useDecisionGraphState(\n ({ hoveredEdgeId, disabled, decisionGraph, components }) => ({\n isHovered: hoveredEdgeId === id,\n disabled,\n decisionGraph,\n components,\n }),\n );\n\n const { diff } = useEdgeDiff(id);\n const [picking, setPicking] = React.useState(false);\n const pickerItems = usePickerItems();\n\n const [edgePath, labelX, labelY] = getBezierPath({\n sourceX,\n sourceY,\n sourcePosition,\n targetX,\n targetY,\n targetPosition,\n });\n\n const insertBetween = async (item: PickerItem) => {\n setPicking(false);\n const existingCount = (decisionGraph?.nodes ?? []).filter((n) =>\n item.type === 'customNode' ? n.content?.kind === item.component : n.type === item.type,\n ).length;\n const allSpecs = [...Object.values(nodeSpecification), ...(components as unknown as AnySpec[])] as AnySpec[];\n const spec =\n item.type === 'customNode'\n ? allSpecs.find((s) => s.kind === item.component)\n : allSpecs.find((s) => s.type === item.type);\n if (!spec?.generateNode) return;\n const partialNode = spec.generateNode({ index: existingCount + 1 });\n\n const position = { x: labelX - 110, y: labelY - 20 };\n const newNode =\n item.type === 'customNode'\n ? {\n id: crypto.randomUUID(),\n type: 'customNode',\n name: partialNode.name,\n position,\n content: { kind: item.component, config: partialNode?.config },\n }\n : { id: crypto.randomUUID(), type: item.type, position, ...partialNode };\n\n const parsed = nodeSchema.safeParse(newNode);\n if (!parsed.success) return;\n\n // 插入并重连:source→new→target,移除原边\n graphActions.addNodes([parsed.data]);\n graphActions.addEdges([\n {\n id: crypto.randomUUID(),\n sourceId: source,\n sourceHandle: sourceHandle ?? undefined,\n targetId: newNode.id,\n type: 'edge',\n },\n {\n id: crypto.randomUUID(),\n sourceId: newNode.id,\n targetId: target,\n targetHandle: targetHandle ?? undefined,\n type: 'edge',\n },\n ]);\n graphActions.removeEdges([id]);\n };\n\n return (\n <>\n <BaseEdge\n path={edgePath}\n markerEnd={markerEnd}\n style={{\n ...(style || {}),\n stroke: match(diff)\n .with({ status: 'added' }, () => 'var(--grl-color-success)')\n .with({ status: 'removed' }, () => 'var(--destructive)')\n .otherwise(() => undefined),\n }}\n />\n <EdgeLabelRenderer>\n <div\n className={\n 'nodrag nopan absolute z-[1000] flex items-center justify-center gap-1 text-xs pointer-events-auto'\n }\n style={{\n transform: `translate(-50%, -50%) translate(${labelX}px,${labelY}px)`,\n }}\n >\n {!disabled && picking && (\n <>\n <div className='fixed inset-0 -z-10' onClick={() => setPicking(false)} />\n <div\n className='absolute bottom-full mb-1 max-h-44 w-48 overflow-y-auto rounded-md border border-[var(--border)] bg-[var(--grl-color-bg-container)] p-1 shadow-md'\n data-slot='edge-node-picker'\n >\n {pickerItems.map((item) => (\n <button\n key={`${item.type}:${item.component ?? ''}`}\n type='button'\n className='flex w-full items-center gap-2 rounded-sm px-2 py-1 text-left text-xs hover:bg-[var(--accent)]'\n onClick={() => void insertBetween(item)}\n >\n <span className='flex h-4 w-4 items-center justify-center'>{item.icon}</span>\n <span className='truncate'>{item.label}</span>\n </button>\n ))}\n </div>\n </>\n )}\n {!disabled && (\n <Button\n type='primary'\n shape='round'\n icon={<PlusOutlined />}\n className='grl-edge-add-button'\n data-visible={isHovered || picking}\n onClick={() => setPicking((p) => !p)}\n />\n )}\n {!disabled && (\n <Button\n type='primary'\n shape='round'\n icon={<DeleteOutlined />}\n danger\n className={clsx('grl-edge-delete-button')}\n data-visible={isHovered && !picking}\n onClick={() => graphActions.removeEdges([id])}\n />\n )}\n </div>\n </EdgeLabelRenderer>\n </>\n );\n};\n\nexport const edgeFunction = (outer: any) => (props: any) => <CustomEdge {...props} {...outer} />;\n","import type { Node, ReactFlowInstance, XYPosition } from '@xyflow/react';\nimport { type RefObject, useCallback, useMemo } from 'react';\nimport { toast } from 'sonner';\n\nimport { copyToClipboard, pasteFromClipboard } from '../../../helpers/utility';\nimport { useDecisionGraphActions, useDecisionGraphRaw } from '../context/dg-store.context';\nimport { type DecisionEdge, type DecisionNode } from '../dg-types';\n\ntype ClipboardData = {\n nodes: DecisionNode[];\n edges?: DecisionEdge[];\n};\n\nconst isClipboardData = (data: any): data is ClipboardData => {\n if (typeof data !== 'object') return false;\n return Array.isArray(data?.nodes);\n};\n\nexport const useGraphClipboard = (\n reactFlow: RefObject<ReactFlowInstance | null>,\n wrapper: RefObject<HTMLDivElement | null>,\n) => {\n const raw = useDecisionGraphRaw();\n const graphActions = useDecisionGraphActions();\n\n const copyNodes = useCallback(\n async (nodes: Node[]) => {\n try {\n if (!reactFlow.current) {\n return;\n }\n\n const copyNodes = (raw.stateStore.getState()?.decisionGraph?.nodes || []).filter((n) =>\n nodes.some((node) => node.id === n.id),\n );\n\n const copyNodeIds = copyNodes.map((n) => n.id);\n const copyEdges: DecisionEdge[] = [];\n\n if (copyNodes.length > 0) {\n const edges = reactFlow.current.getEdges();\n edges.forEach((edge) => {\n if (copyNodeIds.includes(edge.source) && copyNodeIds.includes(edge.target)) {\n copyEdges.push({\n id: edge.id,\n type: edge.type,\n sourceId: edge.source,\n targetId: edge.target,\n sourceHandle: edge.sourceHandle ?? undefined,\n targetHandle: edge.targetHandle ?? undefined,\n });\n }\n });\n }\n\n const clipboardData: ClipboardData = {\n nodes: copyNodes,\n edges: copyEdges,\n };\n\n await copyToClipboard(JSON.stringify(clipboardData));\n toast.success('Copied to clipboard!');\n } catch (e: any) {\n toast.error(e.message);\n }\n },\n [raw],\n );\n\n const pasteNodes = useCallback(async () => {\n try {\n if (!reactFlow?.current) {\n return;\n }\n\n const clipboardText = await pasteFromClipboard();\n if (!clipboardText) {\n return;\n }\n const clipboardData = JSON.parse(clipboardText);\n\n if (!isClipboardData(clipboardData)) {\n throw new Error('invalid clipboard');\n }\n\n const nodeIds: Record<string, string> = clipboardData.nodes.reduce(\n (acc, curr) => ({\n ...acc,\n [curr.id]: crypto.randomUUID(),\n }),\n {},\n );\n\n const copyNodeIds = Object.keys(nodeIds);\n const anchor = reactFlow.current.getNodes().find((n) => copyNodeIds.includes(n.id));\n const copyAnchor = clipboardData.nodes.find((n) => n.id === anchor?.id);\n const gravityCenter = {\n x: clipboardData.nodes.reduce((acc, n) => acc + n.position.x, 0) / clipboardData.nodes.length,\n y: clipboardData.nodes.reduce((acc, n) => acc + n.position.y, 0) / clipboardData.nodes.length,\n } as XYPosition;\n\n const nodes = clipboardData.nodes.map((n: DecisionNode) => {\n const position: XYPosition = {\n x: n?.position?.x || 0,\n y: n?.position?.y || 0,\n };\n\n if (anchor && copyAnchor) {\n const isAnchor = n.id === anchor.id;\n\n if (isAnchor) {\n position.x = anchor.position.x;\n position.y = anchor.position.y - 20;\n } else {\n position.x = anchor.position.x - copyAnchor.position.x + n.position.x;\n position.y = anchor.position.y - copyAnchor.position.y + n.position.y - 20;\n }\n } else if (wrapper.current) {\n const rect = wrapper.current.getBoundingClientRect();\n const rectCenter = {\n x: rect.left + rect.width / 2,\n y: rect.top + rect.height / 2,\n };\n\n const projection = reactFlow.current!.screenToFlowPosition(rectCenter);\n\n position.x = n.position.x + projection.x - gravityCenter.x / 2;\n position.y = n.position.y + projection.y - gravityCenter.y / 2;\n }\n\n return {\n ...n,\n position,\n id: nodeIds[n.id],\n };\n });\n\n const edges = (clipboardData.edges || []).map<DecisionEdge>((e) => ({\n id: crypto.randomUUID(),\n type: e.type,\n sourceId: nodeIds[e.sourceId],\n targetId: nodeIds[e.targetId],\n sourceHandle: e.sourceHandle ?? undefined,\n targetHandle: e.targetHandle ?? undefined,\n }));\n\n graphActions.addNodes(nodes);\n graphActions.addEdges(edges);\n toast.success('Pasted from clipboard!');\n\n if (anchor) {\n try {\n await copyToClipboard(JSON.stringify({ nodes }));\n } catch {\n //\n }\n }\n } catch {\n toast.error('Failed to paste from clipboard');\n }\n }, [reactFlow, wrapper]);\n\n return useMemo(\n () => ({\n copyNodes,\n pasteNodes,\n }),\n [copyNodes, pasteNodes],\n );\n};\n","import type { ReactFlowInstance, XYPosition } from '@xyflow/react';\nimport type { DragEvent, MutableRefObject } from 'react';\nimport { toast } from 'sonner';\nimport { P, match } from 'ts-pattern';\n\nimport { nodeSchema } from '../../../helpers/schema';\nimport type { DecisionGraphStoreType } from '../context/dg-store.context';\n\ntype AddNodes = DecisionGraphStoreType['actions']['addNodes'];\n\n/**\n * Palette drag-and-drop handlers: translate the drop point into flow\n * coordinates, then either hydrate a serialized node payload or delegate to\n * the node-add pipeline.\n */\nexport const useGraphDnd = ({\n reactFlowWrapper,\n reactFlowInstance,\n addNodes,\n addNode,\n}: {\n reactFlowWrapper: MutableRefObject<HTMLDivElement | null>;\n reactFlowInstance: MutableRefObject<ReactFlowInstance | null>;\n addNodes: AddNodes;\n addNode: (type: string, position?: XYPosition, component?: string) => Promise<void>;\n}) => {\n const onDrop = (event: DragEvent) => {\n event.preventDefault();\n event.stopPropagation();\n if (!reactFlowWrapper.current || !reactFlowInstance.current) {\n return;\n }\n\n let elementPosition: XYPosition;\n\n try {\n elementPosition = JSON.parse(event.dataTransfer.getData('relativePosition'));\n } catch {\n return;\n }\n\n const position = reactFlowInstance.current.screenToFlowPosition({\n x: event.clientX,\n y: event.clientY,\n }) as XYPosition;\n\n position.x -= Math.round((elementPosition.x * 226) / 10) * 10;\n position.y -= Math.round((elementPosition.y * 60) / 10) * 10;\n\n const nodeData = event.dataTransfer.getData('nodeData');\n if (nodeData) {\n try {\n const jsonData = JSON.parse(nodeData);\n addNodes([nodeSchema.parse({ ...jsonData, position })]);\n } catch (err) {\n toast.error('Failed to create a node');\n console.error(err);\n }\n\n return;\n }\n\n const type = event.dataTransfer.getData('nodeType');\n const component = match(event.dataTransfer.getData('customNodeComponent'))\n .with(P.string, (c) => c)\n .otherwise(() => undefined);\n\n void addNode(type, position, component);\n };\n\n const onDragOver = (event: any) => {\n event.preventDefault();\n event.dataTransfer.dropEffect = 'move';\n };\n\n return { onDrop, onDragOver };\n};\n","import type { ReactFlowInstance, Viewport } from '@xyflow/react';\nimport type { MutableRefObject } from 'react';\n\nimport type { DecisionGraphStoreType, ExposedStore } from '../context/dg-store.context';\nimport { useGraphSerializer } from '../context/serializer.context';\n\ntype TabsSlice = { openTabs: string[]; activeTab: string };\n\nexport const componentsOpenedKey = 'jdm-components-opened';\n\n/**\n * Registers the graph-level persistence slices (viewport, open tabs,\n * components-panel visibility) with the serializer registry.\n */\nexport const useGraphSerializers = ({\n reactFlowInstance,\n onRestoreViewport,\n stateStore,\n componentsOpened,\n setComponentsOpened,\n}: {\n reactFlowInstance: MutableRefObject<ReactFlowInstance | null>;\n onRestoreViewport: (viewport: Viewport) => void;\n stateStore: ExposedStore<DecisionGraphStoreType['state']>;\n componentsOpened: boolean;\n setComponentsOpened: (value: boolean) => void;\n}) => {\n useGraphSerializer<Viewport>('viewport', {\n serialize: () => reactFlowInstance.current?.getViewport() ?? { x: 0, y: 0, zoom: 1 },\n restore: (viewport) => {\n if (!viewport) return;\n onRestoreViewport(viewport);\n reactFlowInstance.current?.setViewport(viewport);\n },\n });\n\n useGraphSerializer<TabsSlice>('tabs', {\n serialize: () => {\n const { openTabs, activeTab } = stateStore.getState();\n return { openTabs, activeTab };\n },\n restore: ({ openTabs, activeTab } = { openTabs: [], activeTab: 'graph' }) => {\n stateStore.setState({ openTabs: openTabs ?? [], activeTab: activeTab ?? 'graph' });\n },\n });\n\n useGraphSerializer<boolean>('componentsOpened', {\n serialize: () => componentsOpened,\n restore: (value) => {\n if (typeof value !== 'boolean') return;\n setComponentsOpened(value);\n localStorage.setItem(componentsOpenedKey, `${value}`);\n },\n });\n};\n","import type { ReactFlowInstance, XYPosition } from '@xyflow/react';\nimport type { MutableRefObject } from 'react';\nimport { toast } from 'sonner';\nimport { P, match } from 'ts-pattern';\n\nimport { nodeSchema } from '../../../helpers/schema';\nimport type { DecisionGraphStoreType } from '../context/dg-store.context';\nimport type { DecisionNode } from '../dg-types';\nimport type { CustomNodeSpecification } from '../nodes/custom-node';\nimport type { NodeSpecification } from '../nodes/specifications/specification-types';\nimport { nodeSpecification } from '../nodes/specifications/specifications';\n\n/**\n * Node-creation pipeline shared by palette drops and programmatic adds:\n * resolve the specification, generate the node, run optional onNodeAdd,\n * validate against the schema and commit to the store.\n */\nexport const useNodeAdd = ({\n reactFlowWrapper,\n reactFlowInstance,\n customNodes,\n components,\n addNodes,\n}: {\n reactFlowWrapper: MutableRefObject<HTMLDivElement | null>;\n reactFlowInstance: MutableRefObject<ReactFlowInstance | null>;\n customNodes: CustomNodeSpecification<object, any>[];\n components: NodeSpecification[];\n addNodes: DecisionGraphStoreType['actions']['addNodes'];\n}) => {\n const addNodeInner = async (type: string, position?: XYPosition, component?: string) => {\n if (!reactFlowWrapper.current || !reactFlowInstance.current) {\n return;\n }\n\n if (!position) {\n const rect = reactFlowWrapper.current.getBoundingClientRect();\n const rectCenter = {\n x: rect.left + rect.width / 2,\n y: rect.top + rect.height / 2,\n };\n\n position = reactFlowInstance.current.screenToFlowPosition(rectCenter);\n }\n\n const customSpecification = match(type)\n .with('customNode', () => customNodes.find((node) => node.kind === component))\n .otherwise(() => {\n const allSpecifications = [...Object.values(nodeSpecification), ...components];\n return allSpecifications.find((s) => s.type === type);\n });\n if (!customSpecification) {\n toast.error(`Unknown node type ${type} - ${component}.`);\n return;\n }\n\n let newNode: DecisionNode | null = match(customSpecification)\n .with({ kind: P.string }, (specification) => {\n const existingCount =\n (reactFlowInstance.current?.getNodes() || []).filter((n) => n.data?.kind === specification.kind).length + 1;\n\n const partialNode = specification.generateNode({ index: existingCount });\n return {\n id: crypto.randomUUID(),\n type: 'customNode',\n name: partialNode.name,\n position: position as XYPosition,\n content: {\n kind: specification.kind,\n config: partialNode?.config,\n },\n } satisfies DecisionNode;\n })\n .with({ type: P.string }, (specification) => {\n const existingCount =\n (reactFlowInstance.current?.getNodes() || []).filter((n) => n.type === specification.type).length + 1;\n const partialNode = specification.generateNode({ index: existingCount });\n\n return {\n id: crypto.randomUUID(),\n type: specification.type,\n position: position as XYPosition,\n ...partialNode,\n } satisfies DecisionNode;\n })\n .otherwise(() => null);\n if (!newNode) {\n toast.error(`Unknown node type ${type} - ${component}.`);\n return;\n }\n\n if (customSpecification.onNodeAdd) {\n try {\n newNode = await customSpecification.onNodeAdd(newNode);\n } catch {\n return;\n }\n }\n\n const parsed = nodeSchema.safeParse(newNode);\n if (parsed.success) {\n return addNodes([nodeSchema.parse(newNode)]);\n }\n toast.error(parsed.error?.message);\n };\n\n return addNodeInner;\n};\n","import type { XYPosition } from '@xyflow/react';\nimport clsx from 'clsx';\nimport React, { useCallback, useMemo, useState } from 'react';\nimport { match } from 'ts-pattern';\n\nimport { Input } from '../../primitives';\nimport { useDecisionGraphState } from '../context/dg-store.context';\nimport { DecisionNode } from '../nodes/decision-node';\nimport { NodeKind, type NodeSpecification } from '../nodes/specifications/specification-types';\nimport { nodeSpecification } from '../nodes/specifications/specifications';\n\nexport type GraphComponentsProps = {\n inputDisabled?: boolean;\n components?: React.ReactNode[];\n disabled?: boolean;\n collapsed?: boolean;\n};\n\nexport const GraphComponents: React.FC<GraphComponentsProps> = React.memo(({ inputDisabled, disabled, collapsed }) => {\n const customComponents = useDecisionGraphState((store) => store.components || []);\n const customNodes = useDecisionGraphState((store) => store.customNodes || []);\n\n const [search, setSearch] = useState('');\n\n const onDragStart = useCallback((event: React.DragEvent, nodeType: string, component?: string) => {\n const target = event.target as HTMLDivElement;\n if (!target) {\n return;\n }\n\n const { offsetX, offsetY } = event.nativeEvent;\n const { height, width } = target.getBoundingClientRect();\n\n const positionData: XYPosition = {\n x: offsetX / width,\n y: offsetY / height,\n };\n\n event.dataTransfer.effectAllowed = 'move';\n event.dataTransfer.setData('nodeType', nodeType);\n event.dataTransfer.setData('relativePosition', JSON.stringify(positionData));\n if (component) {\n event.dataTransfer.setData('customNodeComponent', component);\n }\n }, []);\n\n const innerGroups = useMemo<Record<string, NodeSpecification[]>>(() => {\n const initialGroups: Record<string, NodeSpecification[]> = {\n core: Object.values(nodeSpecification),\n };\n if (customComponents?.length > 0) {\n initialGroups.extended = customComponents;\n }\n\n (customNodes || []).forEach((node) => {\n const group = node.group?.trim?.() || '';\n if (group.length > 0) {\n if (initialGroups?.[group]) {\n initialGroups[group].push({ ...node, type: 'customNode' });\n } else {\n initialGroups[group] = [{ ...node, type: 'customNode' }];\n }\n }\n });\n\n (customNodes || []).forEach((node) => {\n if (!node?.group) {\n if (initialGroups?.['custom']) {\n initialGroups['custom'].push({ ...node, type: 'customNode' });\n } else {\n initialGroups['custom'] = [{ ...node, type: 'customNode' }];\n }\n }\n });\n\n return initialGroups;\n }, [customComponents, customNodes]);\n\n const groups = useMemo<Record<string, NodeSpecification[]>>(() => {\n return Object.keys(innerGroups).reduce((acc, key) => {\n return {\n ...acc,\n [key]: (innerGroups[key] || []).filter(\n (el) =>\n !(search?.trim?.().length > 0) ||\n (el.type || '').toLowerCase().indexOf(search.toLowerCase()) > -1 ||\n ((el.displayName || '') as string).toLowerCase().indexOf(search.toLowerCase()) > -1 ||\n (el.shortDescription || '').toLowerCase().indexOf(search.toLowerCase()) > -1 ||\n (el.group || '').toLowerCase().indexOf(search.toLowerCase()) > -1,\n ),\n };\n }, {});\n }, [innerGroups, search]);\n\n const customCount = customComponents.length + customNodes.length;\n\n return (\n <div>\n {customCount > 5 && (\n <Input\n placeholder={'Search components...'}\n value={search}\n onChange={(e) => setSearch(e.target.value || '')}\n allowClear\n className={'sticky top-0 z-[1] h-auto rounded-none border-0 shadow-none text-[13px]'}\n />\n )}\n <div className={'flex grow flex-col'}>\n {Object.keys(groups).map((group) => {\n return match(group)\n .with(\n 'core',\n () =>\n groups['core']?.length > 0 && (\n <React.Fragment key={group}>\n {(groups['core'] || []).map((node) => (\n <React.Fragment key={'kind' in node ? (node.kind as string) : node.type}>\n <DragDecisionNode\n collapsed={collapsed}\n disabled={match(node.type)\n .with(NodeKind.Input, () => disabled || inputDisabled)\n .otherwise(() => disabled)}\n specification={node}\n onDragStart={(event) =>\n nodeSpecification[node.type as NodeKind] !== undefined\n ? onDragStart(event, node.type)\n : onDragStart(event, 'customNode', 'kind' in node ? (node.kind as string) : '')\n }\n />\n </React.Fragment>\n ))}\n </React.Fragment>\n ),\n )\n .otherwise(\n (group) =>\n groups[group]?.length > 0 && (\n <React.Fragment key={group}>\n {(groups?.[group] || []).map((customNode) => (\n <DragDecisionNode\n collapsed={collapsed}\n key={'kind' in customNode ? (customNode.kind as string) : customNode.type}\n disabled={disabled}\n specification={customNode}\n onDragStart={(event) =>\n group === 'extended'\n ? onDragStart(event, customNode.type)\n : onDragStart(event, 'customNode', 'kind' in customNode ? (customNode.kind as string) : '')\n }\n />\n ))}\n </React.Fragment>\n ),\n );\n })}\n </div>\n </div>\n );\n});\n\nconst DragDecisionNode: React.FC<\n {\n specification: Pick<NodeSpecification, 'color' | 'icon' | 'displayName' | 'shortDescription'>;\n disabled?: boolean;\n collapsed?: boolean;\n } & React.HTMLAttributes<HTMLDivElement>\n> = ({ specification, disabled = false, collapsed, ...props }) => {\n return (\n <div className={clsx('draggable-component cursor-grab [transform:translate(0)]')} draggable={!disabled} {...props}>\n <div style={{ pointerEvents: 'none' }}>\n <DecisionNode\n listMode\n compactMode\n color={specification.color}\n icon={specification.icon}\n name={collapsed ? undefined : (specification.displayName as string)}\n type={specification.shortDescription}\n />\n </div>\n </div>\n );\n};\n","import { CloseOutlined } from '#icons';\nimport { Badge } from '#reui/badge';\nimport { IconTile } from '#reui/icon-tile';\nimport { Panel, useOnSelectionChange } from '@xyflow/react';\nimport React from 'react';\n\nimport { Button } from '../../primitives';\nimport { useDecisionGraphState } from '../context/dg-store.context';\nimport { nodeSpecification } from '../nodes/specifications/specifications';\n\n/**\n * WS1-R5:停靠式检查器(flow-2 docked inspector 模式)。\n * 选中带 renderSettings 的节点时,画布右上停靠展示该节点的设置面板;\n * 关闭仅收起面板,重新选择节点即再次打开。\n */\nexport const NodeInspector: React.FC = () => {\n const [selected, setSelected] = React.useState<{ id: string; type: string; kind?: string; name?: string } | null>(\n null,\n );\n const [closed, setClosed] = React.useState(false);\n const customNodes = useDecisionGraphState(({ customNodes }) => customNodes);\n\n useOnSelectionChange({\n onChange: ({ nodes }) => {\n const first = nodes[nodes.length - 1];\n if (!first) {\n setSelected(null);\n return;\n }\n setSelected({\n id: first.id,\n type: String(first.type ?? ''),\n kind: typeof first.data?.kind === 'string' ? first.data.kind : undefined,\n name: typeof first.data?.name === 'string' ? first.data.name : undefined,\n });\n setClosed(false);\n },\n });\n\n if (!selected || closed) {\n return null;\n }\n\n const specification =\n selected.type === 'customNode'\n ? customNodes.find((c) => c.kind === selected.kind)\n : (nodeSpecification as Record<string, unknown>)[selected.type];\n const Settings = (specification as { renderSettings?: React.ComponentType<{ id: string }> } | undefined)\n ?.renderSettings;\n\n if (!Settings) {\n return null;\n }\n\n return (\n <Panel position='top-right' style={{ margin: 10, maxWidth: 320, width: 'max-content' }}>\n <div\n className='nodrag nopan flex max-h-[60vh] w-72 flex-col overflow-hidden rounded-lg border border-[var(--border)] bg-[var(--grl-color-bg-container)] shadow-md'\n data-slot='node-inspector'\n >\n <div className='flex items-center gap-2 border-b border-b-[var(--border)] p-2'>\n <IconTile variant='soft' size='xs' aria-hidden>\n {(specification as { icon?: React.ReactNode } | undefined)?.icon}\n </IconTile>\n <div className='flex min-w-0 flex-1 flex-col gap-0.5'>\n <span className='truncate text-xs font-medium'>{selected.name}</span>\n {selected.type !== 'customNode' && (\n <Badge variant='secondary' size='xs' className='w-fit max-w-full truncate'>\n {String((specification as { displayName?: React.ReactNode } | undefined)?.displayName ?? '')}\n </Badge>\n )}\n </div>\n <Button\n type='text'\n size='small'\n className='h-6 w-6 p-0'\n aria-label='Close inspector'\n icon={<CloseOutlined style={{ fontSize: 10 }} />}\n onClick={() => setClosed(true)}\n />\n </div>\n <div className='flex flex-col gap-1 overflow-y-auto p-2.5 [&_.settings-form_.grl-ce]:text-xs'>\n <Settings id={selected.id} />\n </div>\n </div>\n </Panel>\n );\n};\n","/**\n * React Flow 以自有 --xy-* 变量绘制画布部件(controls/minimap/连线/选区/归因等);\n * 将变量映射到设计 token(--border/--primary/--card/…,见 styles/tokens.css)后,\n * 画布外观随主题与暗色模式联动,而非停留在 xyflow 出厂默认。\n * 移植自 ReUI flow-1 块(flow-canvas.tsx 的 FLOW_THEME)。与 .grl-dg .react-flow__*\n * 元素级覆盖正交:变量层给默认色,元素层仍可覆盖具体部件。\n */\nexport const XYFLOW_THEME = [\n '[--xy-background-color:transparent]',\n '[--xy-background-pattern-color:var(--border)]',\n '[--xy-edge-stroke:color-mix(in_oklab,var(--muted-foreground)_45%,transparent)]',\n '[--xy-edge-stroke-selected:var(--primary)]',\n '[--xy-edge-stroke-width:1]',\n '[--xy-edge-label-background-color:var(--card)]',\n '[--xy-edge-label-color:var(--muted-foreground)]',\n '[--xy-connectionline-stroke:var(--primary)]',\n '[--xy-connectionline-stroke-width:1]',\n '[--xy-handle-background-color:var(--primary)]',\n '[--xy-handle-border-color:var(--card)]',\n '[--xy-controls-button-background-color:var(--card)]',\n '[--xy-controls-button-background-color-hover:var(--muted)]',\n '[--xy-controls-button-border-color:var(--border)]',\n '[--xy-controls-button-color:var(--foreground)]',\n '[--xy-controls-button-color-hover:var(--foreground)]',\n '[--xy-controls-box-shadow:none]',\n '[--xy-minimap-background-color:var(--card)]',\n '[--xy-minimap-mask-background-color:color-mix(in_oklab,var(--muted)_70%,transparent)]',\n '[--xy-minimap-node-background-color:color-mix(in_oklab,var(--muted-foreground)_35%,transparent)]',\n '[--xy-selection-background-color:color-mix(in_oklab,var(--primary)_8%,transparent)]',\n '[--xy-selection-border:1px_dashed_var(--primary)]',\n '[--xy-attribution-background-color:transparent]',\n].join(' ');\n","import { CompressOutlined, LeftOutlined, RightOutlined, WarningOutlined } from '#icons';\nimport type { Connection, Edge, Node, ProOptions, ReactFlowInstance, Viewport } from '@xyflow/react';\nimport {\n Background,\n ControlButton,\n Controls,\n MiniMap,\n ReactFlow,\n SelectionMode,\n getOutgoers,\n useEdgesState,\n useNodesState,\n} from '@xyflow/react';\nimport '@xyflow/react/dist/style.css';\nimport clsx from 'clsx';\nimport equal from 'fast-deep-equal';\nimport React, { type MutableRefObject, forwardRef, useImperativeHandle, useMemo, useRef, useState } from 'react';\n\nimport { useT } from '../../../theming/i18n';\nimport { App, Button, Typography } from '../../primitives';\nimport {\n type DecisionGraphStoreType,\n type ExposedStore,\n useDecisionGraphActions,\n useDecisionGraphListeners,\n useDecisionGraphRaw,\n useDecisionGraphReferences,\n useDecisionGraphState,\n} from '../context/dg-store.context';\nimport { type DecisionGraphSnapshot, useSerializerRegistry } from '../context/serializer.context';\nimport { edgeFunction } from '../custom-edge';\nimport { mapToDecisionEdge } from '../dg-util';\nimport { useGraphClipboard } from '../hooks/use-graph-clipboard';\nimport { useGraphDnd } from '../hooks/use-graph-dnd';\nimport { componentsOpenedKey, useGraphSerializers } from '../hooks/use-graph-serializers';\nimport { useNodeAdd } from '../hooks/use-node-add';\nimport type { CustomNodeSpecification } from '../nodes/custom-node';\nimport { GraphNode } from '../nodes/graph-node';\nimport type { MinimalNodeProps } from '../nodes/specifications/specification-types';\nimport { NodeKind } from '../nodes/specifications/specification-types';\nimport { nodeSpecification } from '../nodes/specifications/specifications';\nimport { GraphComponents } from './graph-components';\nimport { NodeInspector } from './node-inspector';\nimport { XYFLOW_THEME } from './xyflow-theme';\n\nexport type GraphProps = {\n className?: string;\n onDisableTabs?: (val: boolean) => void;\n reactFlowProOptions?: ProOptions;\n};\n\nexport type GraphRef = DecisionGraphStoreType['actions'] & {\n stateStore: ExposedStore<DecisionGraphStoreType['state']>;\n serialize: () => DecisionGraphSnapshot;\n restore: (snapshot: DecisionGraphSnapshot) => void;\n};\n\nconst defaultNodeTypes = Object.entries(nodeSpecification).reduce(\n (acc, [key, value]) => ({\n ...acc,\n [key]: React.memo(\n (props: MinimalNodeProps) => value.renderNode({ specification: value, ...props }),\n (prevProps, nextProps) => {\n return (\n prevProps.id === nextProps.id &&\n prevProps.selected === nextProps.selected &&\n equal(prevProps.data, nextProps.data)\n );\n },\n ),\n }),\n {},\n);\n\nconst edgeTypes = {\n edge: React.memo(edgeFunction(null)),\n};\n\nexport const Graph = forwardRef<GraphRef, GraphProps>(function GraphInner({ reactFlowProOptions, className }, ref) {\n const reactFlowWrapper = useRef<HTMLDivElement>(null);\n const reactFlowInstance = useRef<ReactFlowInstance>(null);\n\n const nodesState = useNodesState<Node>([]);\n const edgesState = useEdgesState<Edge>([]);\n\n const [componentsOpened, setComponentsOpened] = useState(() => {\n const localStorageKey = localStorage.getItem(componentsOpenedKey);\n if (!localStorageKey) {\n localStorage.setItem(componentsOpenedKey, 'true');\n return true;\n }\n return localStorage.getItem(componentsOpenedKey) === 'true';\n });\n\n const initialViewport = useRef<Viewport | undefined>(undefined);\n\n const raw = useDecisionGraphRaw();\n const registry = useSerializerRegistry();\n const graphActions = useDecisionGraphActions();\n const graphReferences = useDecisionGraphReferences((s) => s);\n const { onReactFlowInit } = useDecisionGraphListeners(({ onReactFlowInit }) => ({ onReactFlowInit }));\n const { modal } = App.useApp();\n const { disabled, hasInputNode, components, customNodes, id } = useDecisionGraphState(\n ({ id, disabled, components, customNodes, decisionGraph }) => ({\n id,\n disabled,\n components,\n customNodes,\n hasInputNode: (decisionGraph?.nodes || []).some((n) => n.type === NodeKind.Input),\n }),\n );\n\n graphReferences.nodesState.current = nodesState;\n graphReferences.edgesState.current = edgesState;\n graphReferences.graphClipboard.current = useGraphClipboard(reactFlowInstance, reactFlowWrapper);\n graphReferences.reactFlowInstance.current = reactFlowInstance.current;\n\n const customNodeRenderer = useMemo(() => {\n return React.memo(\n (props: MinimalNodeProps) => {\n const t = useT();\n const { openTab } = useDecisionGraphActions();\n const node = customNodes.find((node) => node.kind === props?.data?.kind) as CustomNodeSpecification<\n object,\n string\n >;\n\n if (!node) {\n console.warn('node not found', props, customNodes);\n return (\n <GraphNode\n id={props.id}\n specification={{\n displayName: `${props.data?.kind}`,\n color: 'var(--destructive)',\n icon: <WarningOutlined />,\n }}\n name={props?.data?.name}\n isSelected={props.selected}\n displayError\n noBodyPadding\n handleLeft={true}\n handleRight={true}\n actions={[\n <Button key='edit-expression' type='text' onClick={() => openTab(props.id)}>\n {t('dg.node.editExpression')}\n </Button>,\n ]}\n />\n );\n }\n\n return node.renderNode({\n specification: node,\n ...props,\n });\n },\n (prevProps, nextProps) => {\n return (\n prevProps.id === nextProps.id &&\n prevProps.selected === nextProps.selected &&\n equal(prevProps.data, nextProps.data)\n );\n },\n );\n }, [customNodes]);\n\n const nodeTypes = useMemo<Record<string, React.FC<any>>>(() => {\n return components.reduce(\n (acc, component) => ({\n ...acc,\n [component.type]: React.memo(\n (props: MinimalNodeProps) => component.renderNode({ specification: component, ...props }),\n (prevProps, nextProps) => {\n return (\n prevProps.id === nextProps.id &&\n prevProps.selected === nextProps.selected &&\n equal(prevProps.data, nextProps.data)\n );\n },\n ),\n }),\n { ...defaultNodeTypes, customNode: customNodeRenderer },\n );\n }, [components, customNodeRenderer]);\n\n const addNodeInner = useNodeAdd({\n reactFlowWrapper,\n reactFlowInstance,\n customNodes,\n components,\n addNodes: graphActions.addNodes,\n });\n\n const isValidConnection = (connection: Connection | Edge): boolean => {\n // Disallow self-reference\n if (connection.source === connection.target) {\n return false;\n }\n\n if (disabled) {\n return false;\n }\n\n const [nodes] = nodesState;\n const [edges] = edgesState;\n\n const hasDuplicate = edges.some(\n (edge) =>\n edge.source === connection.source &&\n edge.target === connection.target &&\n (edge.sourceHandle ?? null) === (connection.sourceHandle ?? null) &&\n (edge.targetHandle ?? null) === (connection.targetHandle ?? null),\n );\n\n const target = nodes.find((node) => node.id === connection.target);\n if (!target || target.id === connection.source) {\n return false;\n }\n\n const hasCycle = (node: Node, visited = new Set()) => {\n if (visited.has(node.id)) {\n return false;\n }\n\n visited.add(node.id);\n\n for (const outgoer of getOutgoers(node, nodes, edges)) {\n if (outgoer.id === connection.source) return true;\n if (hasCycle(outgoer, visited)) return true;\n }\n };\n\n return !hasDuplicate && !hasCycle(target);\n };\n\n const { onDrop, onDragOver } = useGraphDnd({\n reactFlowWrapper,\n reactFlowInstance,\n addNodes: graphActions.addNodes,\n addNode: addNodeInner,\n });\n\n const onConnect = (params: any) => {\n const edge = {\n ...params,\n type: 'edge',\n id: crypto.randomUUID(),\n };\n\n if (disabled) return;\n graphActions.addEdges([mapToDecisionEdge(edge)]);\n };\n\n useGraphSerializers({\n reactFlowInstance,\n onRestoreViewport: (viewport) => {\n initialViewport.current = viewport;\n },\n stateStore: raw.stateStore,\n componentsOpened,\n setComponentsOpened,\n });\n\n useImperativeHandle(ref, () => ({\n ...graphActions,\n stateStore: raw.stateStore,\n serialize: () => registry?.serialize() ?? {},\n restore: (snapshot) => registry?.restore(snapshot ?? {}),\n }));\n\n return (\n <div\n className={clsx([\n 'relative h-full w-full flex-1 min-h-0 bg-[var(--grl-color-bg-container)] outline-none focus:outline-none focus-within:outline-none',\n className,\n ])}\n tabIndex={0}\n onKeyDown={(e) => {\n if (e.key === 'v' && e.metaKey && !disabled) {\n graphActions.pasteNodes();\n }\n }}\n >\n <div\n style={{\n width: '100%',\n height: '100%',\n position: 'relative',\n display: 'flex',\n }}\n >\n <div\n tabIndex={0}\n className={'h-full w-full flex-1 flex-row outline-none!'}\n onKeyDown={(e) => {\n const [nodes] = nodesState;\n const [edges] = edgesState;\n\n if (e.key === 'c' && e.metaKey) {\n const selectedNodeIds = nodesState[0].filter((n) => n.selected).map(({ id }) => id);\n if (selectedNodeIds.length === 0) {\n return;\n }\n\n graphActions.copyNodes(selectedNodeIds);\n e.preventDefault();\n } else if (e.key === 'd' && e.metaKey) {\n if (!disabled) {\n const selectedNodeIds = nodes.filter((n) => n.selected).map(({ id }) => id);\n if (selectedNodeIds.length === 0) {\n return;\n }\n\n graphActions.duplicateNodes(selectedNodeIds);\n }\n e.preventDefault();\n } else if (e.key === 'Backspace') {\n if (!disabled) {\n const selectedNodes = nodes.filter((n) => n.selected);\n const selectedEdges = edges.filter((e) => e.selected);\n\n if (selectedNodes.length > 0) {\n const length = selectedNodes.length;\n const text = length > 1 ? 'nodes' : 'node';\n modal.confirm({\n icon: null,\n title: `Delete ${text}`,\n content: (\n <Typography.Text>\n Are you sure you want to delete {length > 1 ? `${length} ${text}` : text}?\n </Typography.Text>\n ),\n okButtonProps: { danger: true },\n onOk: () => {\n if (selectedEdges.length > 0) {\n graphActions.removeEdges(selectedEdges.map((e) => e.id));\n }\n graphActions.removeNodes(selectedNodes.map((n) => n.id));\n },\n });\n } else if (selectedEdges.length > 0) {\n graphActions.removeEdges(selectedEdges.map((e) => e.id));\n }\n }\n e.stopPropagation();\n e.preventDefault();\n }\n }}\n >\n <div className={clsx(['react-flow'], XYFLOW_THEME)} ref={reactFlowWrapper}>\n <ReactFlow\n deleteKeyCode={null}\n elevateEdgesOnSelect={false}\n elevateNodesOnSelect={true}\n zoomOnDoubleClick={false}\n connectionRadius={35}\n nodes={nodesState[0]}\n edges={edgesState[0]}\n defaultViewport={initialViewport.current}\n fitView={!initialViewport.current}\n fitViewOptions={{ padding: 0.15 }}\n onInit={(instance) => {\n (reactFlowInstance as MutableRefObject<ReactFlowInstance>).current = instance;\n if (initialViewport.current) {\n instance.setViewport(initialViewport.current);\n }\n onReactFlowInit?.(instance);\n }}\n snapToGrid={true}\n snapGrid={[5, 5]}\n minZoom={0.25}\n selectionMode={SelectionMode.Partial}\n nodeTypes={nodeTypes}\n edgeTypes={edgeTypes}\n onDrop={onDrop}\n onDragOver={onDragOver}\n onConnect={onConnect}\n isValidConnection={isValidConnection}\n proOptions={reactFlowProOptions}\n nodesConnectable={!disabled}\n nodesDraggable={!disabled}\n edgesReconnectable={!disabled}\n onNodesChange={graphActions.handleNodesChange}\n onEdgesChange={graphActions.handleEdgesChange}\n onNodesDelete={(e) => {\n e.forEach((node) => {\n graphActions.closeTab(node?.id);\n });\n }}\n onEdgeMouseEnter={(_, edge) => graphActions.setHoveredEdgeId(edge.id)}\n onEdgeMouseLeave={() => graphActions.setHoveredEdgeId(null)}\n >\n <Controls showInteractive={false}>\n <ControlButton onClick={() => graphActions.toggleCompactMode()}>\n <CompressOutlined />\n </ControlButton>\n </Controls>\n <MiniMap pannable zoomable position='bottom-left' />\n <Background id={id} color='var(--border)' gap={20} />\n <NodeInspector />\n </ReactFlow>\n </div>\n </div>\n {!disabled && (\n <div\n className={clsx(\n 'flex h-full min-h-0 flex-col border-l border-l-[var(--border)] bg-[var(--grl-color-bg-container)]',\n !componentsOpened ? 'w-10 min-w-10' : 'w-[260px] min-w-[260px]',\n )}\n >\n <div className='box-border flex flex-row items-center border-b border-b-[var(--border)] bg-[var(--grl-color-primary-bg-fade)] px-3 py-1.5'>\n {componentsOpened && (\n <div className='flex flex-1 items-center'>\n <Typography.Text strong style={{ marginBottom: 0 }}>\n Components\n </Typography.Text>{' '}\n <Typography.Text type='secondary' style={{ fontSize: 10, marginLeft: 5 }}>\n (Drag-and-drop)\n </Typography.Text>\n </div>\n )}\n <Button\n type={'text'}\n size='small'\n icon={\n componentsOpened ? (\n <RightOutlined style={{ fontSize: 12 }} />\n ) : (\n <LeftOutlined style={{ fontSize: 12 }} />\n )\n }\n onClick={() => {\n const value = !componentsOpened;\n setComponentsOpened(!componentsOpened);\n localStorage.setItem(componentsOpenedKey, `${value}`);\n }}\n />\n </div>\n <div className='min-h-0 flex-1 overflow-y-auto'>\n <GraphComponents inputDisabled={hasInputNode} collapsed={!componentsOpened} disabled={disabled} />\n </div>\n </div>\n )}\n </div>\n </div>\n );\n});\n","import { CloseOutlined, SearchOutlined } from '#icons';\nimport clsx from 'clsx';\nimport React, { useMemo, useState } from 'react';\nimport { match } from 'ts-pattern';\n\nimport { useT } from '../../../theming/i18n';\nimport { Avatar, Button, Input, Space, Typography } from '../../primitives';\nimport { useDecisionGraphActions, useDecisionGraphListeners, useDecisionGraphState } from '../context/dg-store.context';\nimport { type DecisionNode } from '../dg-types';\nimport { NodeColor } from '../nodes/specifications/colors';\nimport { NodeKind } from '../nodes/specifications/specification-types';\nimport { nodeSpecification } from '../nodes/specifications/specifications';\n\nconst { Title, Text } = Typography;\n\nexport type GraphComponentsProps = {\n className?: string;\n};\n\nexport const GraphNodes: React.FC<GraphComponentsProps> = React.memo(({ className }) => {\n const t = useT();\n const { decisionGraph, customComponents, viewConfig, viewConfigCta } = useDecisionGraphState((store) => ({\n decisionGraph: store.decisionGraph || [],\n customComponents: store.components,\n activeTabId: store.activeTab,\n viewConfig: store.viewConfig,\n viewConfigCta: store.viewConfigCta,\n }));\n\n const { openTab } = useDecisionGraphActions();\n const onViewConfigCta = useDecisionGraphListeners((s) => s.onViewConfigCta);\n\n const nodes = useMemo(() => {\n return (decisionGraph?.nodes || [])\n .filter((node) => (viewConfig?.enabled ? !!viewConfig?.permissions?.[node.id] : true))\n .map((node) => {\n const kind = node.type as NodeKind;\n const specification =\n nodeSpecification[node.type as NodeKind] || (customComponents || []).find((cmp) => cmp.type === node.type);\n\n return {\n id: node.id,\n type: node.type,\n name: node.name,\n disabled: match(kind)\n .with(NodeKind.Function, () => false)\n .with(NodeKind.DecisionTable, () => false)\n .with(NodeKind.Expression, () => false)\n .otherwise(() => true),\n position: node.position,\n icon: specification?.icon,\n ...(node?._diff ? { _diff: node._diff } : {}),\n };\n });\n }, [decisionGraph, viewConfig]);\n\n const [search, setSearch] = useState('');\n\n const ConfigItem = ({ node }: { node: DecisionNode }) => {\n const specification = nodeSpecification?.[node?.type as NodeKind];\n\n return (\n <div\n className={clsx(\n 'cursor-pointer rounded-(--grl-border-radius) border bg-card text-card-foreground shadow-xs transition-colors hover:border-primary/50',\n node?._diff?.status,\n )}\n onClick={() => openTab(node.id)}\n >\n <div className='p-4'>\n <div className={'flex items-center gap-3'}>\n <Avatar\n size={24}\n shape='square'\n style={{\n background: specification?.color || NodeColor.Blue,\n fontSize: 16,\n lineHeight: '22px',\n borderRadius: 3,\n }}\n icon={specification?.icon}\n />\n <div style={{ flex: 1 }}>\n <Text style={{ margin: 0, fontSize: 14, marginBottom: node?.description ? '4px' : 0 }}>{node.name}</Text>\n {node?.description && (\n <Text type='secondary' style={{ fontSize: '14px' }}>\n {node?.description}\n </Text>\n )}\n </div>\n </div>\n </div>\n </div>\n );\n };\n\n const nodeGroups = useMemo(() => {\n const filtered = nodes.filter((node) =>\n search.trim()?.length > 0 ? node.name?.toLowerCase?.()?.indexOf?.(search?.trim?.()?.toLowerCase?.()) > -1 : true,\n );\n\n return [\n {\n title: 'Decision Tables',\n nodes: filtered.filter((node) => node.type === NodeKind.DecisionTable),\n },\n {\n title: 'Expressions',\n nodes: filtered.filter((node) => node.type === NodeKind.Expression),\n },\n {\n title: 'Functions',\n nodes: filtered.filter((node) => node.type === NodeKind.Function),\n },\n ];\n }, [search, nodes]);\n\n const isEmpty = (nodes?.length || 0) === 0;\n\n return (\n <div\n className={clsx([\n 'relative hidden h-full w-full flex-1 min-h-0 overflow-y-auto bg-[var(--background)] p-6 outline-none focus:outline-none focus-within:outline-none',\n className,\n ])}\n >\n <div className={'mx-auto w-full max-w-[1200px]'}>\n <div className={'mb-8'}>\n <div className={'flex justify-between'}>\n <Title level={4} style={{ margin: 0, marginBottom: '8px' }}>\n {isEmpty ? 'Decision View Not Configured' : 'Decision View'}\n </Title>\n {viewConfigCta && (\n <Button\n type={'primary'}\n onClick={() => {\n onViewConfigCta?.();\n }}\n >\n {viewConfigCta}\n </Button>\n )}\n </div>\n {!isEmpty ? (\n <Text type='secondary'>\n {viewConfig?.description || 'Configure business rules for your decision model'}\n </Text>\n ) : (\n <>\n {decisionGraph?.nodes?.length > 0 ? (\n <Text type='secondary'>\n This decision model contains multiple components, but no view has been configured yet.\n </Text>\n ) : (\n <Text type='secondary'>{`This decision model doesn't contain any component.`}</Text>\n )}\n </>\n )}\n </div>\n\n {!isEmpty && (\n <div className={'flex items-center justify-between mb-8'}>\n <Space>\n <Input\n placeholder={t('dg.toolbar.searchNodes')}\n prefix={<SearchOutlined />}\n style={{ width: 350 }}\n onChange={(e) => setSearch(e.target.value)}\n value={search}\n />\n {search?.trim()?.length > 0 && (\n <Button type='text' size={'small'} icon={<CloseOutlined />} onClick={() => setSearch('')}>\n Clear\n </Button>\n )}\n </Space>\n <Text\n type='secondary'\n style={{\n whiteSpace: 'nowrap',\n }}\n >\n {nodes?.length || 0} configurable items\n </Text>\n </div>\n )}\n\n {nodeGroups\n .filter((group) => group?.nodes?.length > 0)\n .map((group) => (\n <div key={group.title} className={'mb-8'}>\n <Title level={5} style={{ marginBottom: '16px' }}>\n {group.title}\n </Title>\n <div className='grid grid-cols-1 gap-4 sm:grid-cols-2 md:grid-cols-3'>\n {group.nodes.map((node) => (\n <ConfigItem key={node.id} node={node} />\n ))}\n </div>\n </div>\n ))}\n </div>\n </div>\n );\n});\n","import type { ParsedExcelData } from '../../../../helpers/excel';\nimport type { ItemValue, MergedDataItem, SelectedItems, TableHeader } from './types';\n\nexport const isHeaderMatch = (header1: TableHeader, header2: TableHeader) => {\n return (\n header1.id === header2.id ||\n header1.value?.toLowerCase() === header2.value?.toLowerCase() ||\n header1.label?.toLowerCase() === header2.label?.toLowerCase()\n );\n};\n\nexport const mergeHeaders = (newHeader: TableHeader, existingHeader?: TableHeader) => {\n if (existingHeader) {\n return {\n id: newHeader.id,\n label: newHeader.label || existingHeader.label,\n value: newHeader.value || existingHeader.value,\n type: newHeader.type || existingHeader.type,\n };\n }\n\n return {\n ...newHeader,\n value: newHeader.value || newHeader.label,\n };\n};\n\n/** Merge excel headers with the table's existing headers, keeping unmatched ones. */\nexport const buildMergedItems = (existingTableHeaders: TableHeader[], newTableHeaders: TableHeader[]): ItemValue[] => {\n const items = [\n ...newTableHeaders.map((newTableHeader) => {\n const existingHeader = existingTableHeaders.find((header) => isHeaderMatch(header, newTableHeader));\n\n return mergeHeaders(newTableHeader, existingHeader);\n }),\n ...existingTableHeaders.filter(\n (existingTableHeader) => !newTableHeaders.some((newHeader) => isHeaderMatch(newHeader, existingTableHeader)),\n ),\n ];\n\n if (!items.some((item) => item.id === '_description')) {\n items.push({\n id: '_description',\n label: 'DESCRIPTION',\n value: 'description',\n });\n }\n\n return items;\n};\n\n/**\n * Auto-pick input/output roles: second-to-last matched column becomes output\n * when a description column exists, otherwise the last non-description match.\n */\nexport const buildAutoSelection = (matchingHeaders: ItemValue[]): Record<string, ItemValue> => {\n return matchingHeaders.reduce((acc, tableHeader, index) => {\n const hasDescription = matchingHeaders.some((header) => header.value === 'description');\n const hasOutputAlready = matchingHeaders.slice(0, index).some((header) => header.type === 'output');\n\n let shouldBeOutput;\n\n if (hasDescription) {\n // If there's description, set second-to-last as output\n shouldBeOutput = index === matchingHeaders.length - 2 && !hasOutputAlready;\n } else {\n // If no description, set last as output (excluding if it IS description)\n shouldBeOutput = index === matchingHeaders.length - 1 && tableHeader.value !== 'description' && !hasOutputAlready;\n }\n\n return {\n ...acc,\n [tableHeader.id]: {\n id: tableHeader.id,\n label: tableHeader.label,\n value: tableHeader.value,\n type: shouldBeOutput ? 'output' : tableHeader.type,\n },\n };\n }, {});\n};\n\n/** Assemble the final per-sheet node payloads from the user's selections. */\nexport const assembleMergedData = (\n excelData: ParsedExcelData[],\n selectedItems: SelectedItems,\n headerWrapStates: Record<string, Record<string, boolean>>,\n): MergedDataItem[] => {\n return Object.keys(selectedItems).map((stepKey, index) => {\n const stepItems = selectedItems[stepKey];\n const stepWrapStates = headerWrapStates[stepKey] || {};\n\n const items = Object.keys(stepItems).map((key) => ({\n ...stepItems[key],\n wrapInQuotes: stepWrapStates[key] || false,\n ...(stepItems[key].value !== 'description' && {\n type: stepItems[key].type ?? 'input',\n }),\n }));\n\n const wrap = items.reduce(\n (acc, item) => {\n acc[item.id] = item.wrapInQuotes || false;\n return acc;\n },\n {} as Record<string, boolean>,\n );\n\n const selectedHeaderIds = Object.keys(stepItems);\n\n const rules = (excelData[index].rules || []).map((rulesData) => {\n return rulesData\n .filter((rule) => [...selectedHeaderIds, '_id'].includes(rule.headerId))\n .map((rule) => ({\n headerId: stepItems[rule.headerId]?.id ?? rule.headerId,\n value: wrap[stepItems[rule.headerId]?.id ?? rule.headerId]\n ? rule.value\n ? rule.value\n .split(',')\n .map((s) => `\"${s.trim()}\"`)\n .join(', ')\n : ''\n : rule.value,\n }));\n });\n\n return {\n items,\n rules,\n id: excelData[index].id,\n name: excelData[index].name,\n type: excelData[index].type,\n position: excelData[index].position,\n hitPolicy: excelData[index].existingTableData.hitPolicy,\n inputField: excelData[index].existingTableData.inputField,\n outputPath: excelData[index].existingTableData.outputPath,\n passThrough: excelData[index].existingTableData.passThrough,\n executionMode: excelData[index].existingTableData.executionMode,\n };\n });\n};\n","import { PlusOutlined, SwapOutlined } from '#icons';\nimport InformationIcon from '#reui/icons/animated/outline/information';\nimport { isEmpty } from 'lodash';\nimport React, { Fragment, useEffect, useMemo, useState } from 'react';\n\nimport { useT } from '../../../../theming/i18n';\nimport {\n Button,\n Checkbox,\n Divider,\n Input,\n Modal,\n Radio,\n Select,\n Steps,\n Tag,\n Tooltip,\n Typography,\n} from '../../../primitives';\nimport { assembleMergedData, buildAutoSelection, buildMergedItems } from './merge-data';\nimport type { GraphExcelDialogProps, ItemValue, SelectedItems } from './types';\n\nexport type { MergedDataItem } from './types';\n\n// Column chip colors share the field-pill tokens (roadmap P1, replaces HK-12\n// literals; CSS var() keeps runtime retheming live).\nconst dataTypeConfig = {\n ['input']: { label: 'Input', color: 'var(--grl-color-field-input)' },\n ['output']: { label: 'Output', color: 'var(--grl-color-field-output)' },\n};\n\nconst stepKeyOf = (step: number) => `step${step}`;\n\nexport const GraphExcelDialog: React.FC<GraphExcelDialogProps> = ({ excelData, handleSuccess, handleCancel }) => {\n const t = useT();\n const [currentStep, setCurrentStep] = useState<number>(0);\n const steps = useMemo(() => excelData?.map((item) => ({ key: item.id, title: item.name })), [excelData]);\n\n const [items, setItems] = useState<ItemValue[]>([]);\n const [newItemName, setNewItemName] = useState<string>('');\n\n const [headerWrapStates, setHeaderWrapStates] = useState<Record<string, Record<string, boolean>>>({});\n\n const [selectedItems, setSelectedItems] = useState<SelectedItems | null>(null);\n\n useEffect(() => {\n if (!excelData) {\n setSelectedItems(null);\n setCurrentStep(0);\n setNewItemName('');\n setHeaderWrapStates({});\n\n return;\n }\n const existingTableHeaders = excelData[currentStep].existingTableData.headers\n .map((tableHeader) => ({\n ...tableHeader,\n value: tableHeader.field,\n label: tableHeader.name as string,\n type: tableHeader.type,\n }))\n .filter((header) => header.value);\n\n const newTableHeaders = (excelData[currentStep]?.headers || []).map((header) => ({\n id: header.id || crypto.randomUUID(),\n value: header.id === '_description' ? 'description' : header.value,\n label: header.name as string,\n ...(header.id !== '_description' && { type: header._type as 'input' | 'output' | undefined }),\n }));\n\n const mergedItems = buildMergedItems(existingTableHeaders, newTableHeaders);\n setItems(mergedItems);\n\n const matchingHeaders = mergedItems.filter((item) => {\n return newTableHeaders.some((excelHeader) => excelHeader.id === item.id);\n });\n\n if (matchingHeaders.length) {\n const selectedItemsMap = buildAutoSelection(matchingHeaders);\n\n setSelectedItems((prevItems) => {\n const stepKey = stepKeyOf(currentStep);\n const currentStepData = (prevItems || {})[stepKey];\n\n if (currentStepData) {\n return prevItems;\n }\n\n return {\n ...(prevItems || {}),\n [stepKey]: selectedItemsMap,\n };\n });\n }\n }, [excelData, currentStep]);\n\n return (\n <Modal\n className='grl-graph-excel-dialog'\n title='Map Excel data'\n closable={{ 'aria-label': 'Custom Close Button' }}\n centered\n open={!!excelData}\n onCancel={handleCancel}\n destroyOnClose={true}\n width={880}\n footer={[\n <Button key='cancel' onClick={handleCancel}>\n Cancel\n </Button>,\n ]}\n >\n <Steps current={currentStep} items={steps} />\n <div\n style={{\n display: 'grid',\n gridTemplateColumns: '1fr auto 1fr auto 0.1fr',\n gap: '16px 24px',\n alignItems: 'center',\n justifyContent: 'center',\n padding: '12px',\n }}\n >\n <Typography.Text\n style={{\n fontSize: '12px',\n fontWeight: 600,\n color: 'var(--muted-foreground)',\n marginBottom: '-8px',\n }}\n >\n Excel columns\n </Typography.Text>\n {/*placeholder for grid*/}\n <div />\n <Typography.Text\n style={{\n fontSize: '12px',\n fontWeight: 600,\n color: 'var(--muted-foreground)',\n marginBottom: '-8px',\n }}\n >\n Decision table columns\n </Typography.Text>\n <Typography.Text\n style={{\n fontSize: '12px',\n fontWeight: 600,\n color: 'var(--muted-foreground)',\n marginBottom: '-8px',\n }}\n >\n Data type\n </Typography.Text>\n {/*placeholder for grid*/}\n <div style={{ display: 'flex', justifyContent: 'center', marginBottom: '-8px' }}>\n <Tooltip title={t('dg.excel.wrapQuotes')}>\n <span className='inline-flex cursor-pointer text-[var(--muted-foreground)] [&_svg]:block'>\n <InformationIcon className='size-3.5' />\n </span>\n </Tooltip>\n </div>\n {excelData?.[currentStep]?.headers.map((header, index) => (\n <Fragment key={index}>\n <div className='flex h-9 items-center rounded-lg border border-[var(--border)] bg-[var(--background)] px-3'>\n <Typography.Text>{header.name || header.value}</Typography.Text>\n </div>\n\n <SwapOutlined\n style={{\n fontSize: '16px',\n color: 'var(--primary)',\n }}\n />\n\n <Select\n key={header.id}\n style={{ width: '100%' }}\n placeholder='select field'\n optionLabelProp='display'\n value={selectedItems?.[stepKeyOf(currentStep)]?.[header.id]?.value}\n allowClear\n onClear={() => {\n setSelectedItems((prevItems) => {\n const stepKey = stepKeyOf(currentStep);\n const currentStepData = { ...(prevItems || {})[stepKey] };\n delete currentStepData[header.id];\n return {\n ...(prevItems || {}),\n [stepKey]: currentStepData,\n };\n });\n\n setHeaderWrapStates((prev) => {\n const stepKey = stepKeyOf(currentStep);\n const updated = { ...prev[stepKey] };\n delete updated[header.id];\n return { ...prev, [stepKey]: updated };\n });\n }}\n onSelect={(_, option) => {\n const { id, label, value, type, wrapInQuotes } = option as {\n id: string;\n label: string;\n value?: string;\n type?: 'input' | 'output';\n wrapInQuotes?: boolean;\n };\n\n setSelectedItems((prevItems) => {\n const stepKey = stepKeyOf(currentStep);\n const currentStepData = { ...(prevItems || {})[stepKey] };\n const clearedHeaderIds: string[] = [];\n\n Object.keys(currentStepData).forEach((key) => {\n if (\n key !== header.id &&\n (currentStepData[key].value === value || currentStepData[key].label === label)\n ) {\n clearedHeaderIds.push(key);\n delete currentStepData[key];\n }\n });\n\n if (clearedHeaderIds.length > 0) {\n setHeaderWrapStates((prev) => {\n const stepData = { ...(prev[stepKey] || {}) };\n clearedHeaderIds.forEach((id) => delete stepData[id]);\n return { ...prev, [stepKey]: stepData };\n });\n }\n\n return {\n ...(prevItems || {}),\n [stepKey]: {\n ...currentStepData,\n [header.id]: { id, label, value, type, wrapInQuotes },\n },\n };\n });\n }}\n dropdownRender={(menu) => (\n <Fragment>\n {menu}\n <Divider style={{ margin: '8px 0' }} />\n <div style={{ display: 'flex', alignItems: 'center', gap: '4px', padding: '0 8px 4px' }}>\n <div\n style={{\n flex: 2,\n display: 'flex',\n flexDirection: 'column',\n gap: '8px',\n justifyContent: 'center',\n alignItems: 'center',\n }}\n >\n <Input\n placeholder={t('dg.excel.enterFieldName')}\n value={newItemName}\n onChange={(event) => setNewItemName(event.target.value)}\n />\n </div>\n <div style={{ flex: 1, display: 'flex', justifyContent: 'center' }}>\n <Button\n type='text'\n icon={<PlusOutlined />}\n onClick={() => {\n setItems([\n ...items,\n {\n value: newItemName,\n label: newItemName,\n id: crypto.randomUUID(),\n },\n ]);\n setNewItemName('');\n }}\n >\n Add item\n </Button>\n </div>\n </div>\n </Fragment>\n )}\n optionRender={(option) => {\n const dataType = option.data.type as keyof typeof dataTypeConfig;\n return (\n <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>\n <span>{option.data.label}</span>\n {dataType && (\n <Tag style={{ background: dataTypeConfig[dataType].color }}>{dataTypeConfig[dataType].label}</Tag>\n )}\n </div>\n );\n }}\n options={items\n .filter((item): item is ItemValue & { value: string } => Boolean(item.value))\n .map((item) => {\n return {\n id: item.id,\n label: item.label,\n value: item.value,\n type: item.type,\n wrapInQuotes: item.wrapInQuotes,\n display: (\n <div\n style={{\n display: 'flex',\n justifyContent: 'space-between',\n alignItems: 'center',\n width: '100%',\n }}\n >\n <span>{item.label}</span>\n </div>\n ),\n };\n })}\n />\n {selectedItems && selectedItems?.[stepKeyOf(currentStep)]?.[header.id]?.value !== 'description' ? (\n <Radio.Group\n disabled={!selectedItems?.[stepKeyOf(currentStep)]?.[header.id]}\n value={selectedItems[stepKeyOf(currentStep)]?.[header.id]?.type ?? 'input'}\n onChange={(e) => {\n setSelectedItems((prev) => {\n const stepKey = stepKeyOf(currentStep);\n const currentStepData = (prev || {})[stepKey];\n return {\n ...(prev || {}),\n [stepKey]: {\n ...(currentStepData || {}),\n [header.id]: {\n ...((currentStepData || {})[header.id] || {}),\n type: e.target.value as ItemValue['type'],\n },\n },\n };\n });\n }}\n buttonStyle='solid'\n style={{ width: '100%', display: 'flex' }}\n >\n <Radio.Button value='input' style={{ flex: 1, textAlign: 'center' }}>\n Input\n </Radio.Button>\n <Radio.Button value='output' style={{ flex: 1, textAlign: 'center' }}>\n Output\n </Radio.Button>\n </Radio.Group>\n ) : (\n /** placeholder for grid */\n <div />\n )}\n {selectedItems?.[stepKeyOf(currentStep)]?.[header.id]?.value !== 'description' ? (\n <div style={{ display: 'flex', justifyContent: 'center' }}>\n <Checkbox\n disabled={!selectedItems?.[stepKeyOf(currentStep)]?.[header.id]}\n checked={headerWrapStates[stepKeyOf(currentStep)]?.[header.id] || false}\n onChange={(e) => {\n setHeaderWrapStates((prev) => {\n const stepKey = stepKeyOf(currentStep);\n return {\n ...prev,\n [stepKey]: {\n ...(prev[stepKey] || {}),\n [header.id]: e.target.checked,\n },\n };\n });\n }}\n />\n </div>\n ) : (\n /** placeholder for grid */\n <div />\n )}\n </Fragment>\n ))}\n </div>\n <div style={{ marginTop: 24 }}>\n {currentStep < (excelData || []).length - 1 && (\n <Button\n type='primary'\n disabled={!selectedItems?.[stepKeyOf(currentStep)] || isEmpty(selectedItems[stepKeyOf(currentStep)])}\n onClick={() => {\n setCurrentStep(currentStep + 1);\n }}\n >\n Next\n </Button>\n )}\n {currentStep === (excelData || []).length - 1 && (\n <Button\n type='primary'\n disabled={!selectedItems?.[stepKeyOf(currentStep)] || isEmpty(selectedItems[stepKeyOf(currentStep)])}\n onClick={() => {\n if (selectedItems && excelData) {\n handleSuccess(assembleMergedData(excelData, selectedItems, headerWrapStates));\n }\n }}\n >\n Done\n </Button>\n )}\n {currentStep > 0 && (\n <Button\n style={{ margin: '0 8px' }}\n onClick={() => {\n setCurrentStep(currentStep - 1);\n }}\n >\n Previous\n </Button>\n )}\n </div>\n </Modal>\n );\n};\n","import { CloudDownloadOutlined, CloudUploadOutlined } from '#icons';\nimport React, { Fragment, useRef, useState } from 'react';\nimport { toast } from 'sonner';\n\nimport type { ParsedExcelData } from '../../../helpers/excel';\nimport { exportDecisionTable, getExcelData } from '../../../helpers/excel';\nimport { decisionModelSchema } from '../../../helpers/schema';\nimport { useT } from '../../../theming/i18n';\nimport { parseDecisionTable } from '../../decision-table/context/dt-store.context';\nimport type { MenuProps } from '../../primitives';\nimport { Button, Dropdown, Tooltip } from '../../primitives';\nimport { useDecisionGraphActions, useDecisionGraphRaw, useDecisionGraphState } from '../context/dg-store.context';\nimport { type DecisionEdge, type DecisionNode } from '../dg-types';\nimport { NodeKind } from '../nodes/specifications/specification-types';\nimport type { MergedDataItem } from './graph-excel-dialog';\nimport { GraphExcelDialog } from './graph-excel-dialog';\n\nconst DecisionContentType = 'application/vnd.gorules.decision';\n\nexport type GraphSideToolbarProps = {\n //\n};\n\nexport const GraphSideToolbar: React.FC<GraphSideToolbarProps> = () => {\n const t = useT();\n const decisionGraphRaw = useDecisionGraphRaw();\n const fileInput = useRef<HTMLInputElement>(null);\n const excelFileInput = useRef<HTMLInputElement>(null);\n const [excelGraphData, setExcelGraphData] = useState<ParsedExcelData[] | null>();\n\n const { setDecisionGraph, setActivePanel } = useDecisionGraphActions();\n const { disabled, panels, activePanel, viewConfig } = useDecisionGraphState(\n ({ disabled, panels, activePanel, viewConfig }) => ({\n disabled,\n panels,\n activePanel,\n viewConfig,\n }),\n );\n\n const handleUploadInput = async (event: any) => {\n const fileList = event?.target?.files as FileList;\n const reader = new FileReader();\n reader.onload = function (e) {\n try {\n const parsed: any = JSON.parse(e?.target?.result as string);\n if (parsed?.contentType !== DecisionContentType) {\n throw new Error('Invalid content type');\n }\n\n const nodes: DecisionNode[] = Array.isArray(parsed?.nodes) ? parsed.nodes : [];\n const nodeIds = nodes.map((node) => node.id);\n\n const edges: DecisionEdge[] = (parsed.edges as DecisionEdge[]).filter(\n (edge) => nodeIds.includes(edge?.targetId) && nodeIds.includes(edge?.sourceId),\n );\n\n const modelParsed = decisionModelSchema.safeParse({\n nodes,\n edges,\n settings: parsed?.settings,\n });\n\n if (!modelParsed.success) {\n toast.error(modelParsed.error?.message);\n return;\n }\n\n setDecisionGraph(modelParsed.data);\n } catch (e: any) {\n toast.error(e.message);\n }\n };\n\n reader.readAsText(Array.from(fileList)?.[0], 'UTF-8');\n };\n\n const uploadJDMExcel = (event: any) => {\n const file = event?.target?.files[0];\n const fileReader = new FileReader();\n\n try {\n fileReader.readAsArrayBuffer(file);\n fileReader.onload = async () => {\n const buffer = fileReader.result as ArrayBuffer;\n\n if (!buffer) return;\n const { decisionGraph } = decisionGraphRaw.stateStore.getState();\n\n const excelData = await getExcelData(buffer, decisionGraph);\n\n setExcelGraphData(excelData);\n\n toast.success('Excel file has been uploaded successfully!');\n };\n } catch {\n toast.error('Failed to upload Excel!');\n }\n };\n\n const handleDataMapping = (mappedExcelData: MergedDataItem[]) => {\n const nodesFromExcel: DecisionNode[] = mappedExcelData.map((excelData) => {\n const inputs = excelData.items\n .filter((item) => item.type === 'input')\n .map((item) => ({\n id: item.id,\n name: item.label,\n field: item.value\n ?.replace(/[^a-zA-Z0-9\\s._]/g, '')\n .trim()\n .replace(/\\s+/g, '.')\n .toLowerCase(),\n }));\n\n const outputs = excelData.items\n .filter((item) => item.type === 'output')\n .map((item) => ({\n id: item.id,\n name: item.label,\n field: item.value\n ?.replace(/[^a-zA-Z0-9\\s._]/g, '')\n .trim()\n .split(/\\s+/)\n .map((word, index) =>\n index === 0 ? word.toLowerCase() : word.charAt(0).toUpperCase() + word.slice(1).toLowerCase(),\n )\n .join(''),\n }));\n\n const reducedRules = excelData.rules.map((rule) =>\n rule.reduce(\n (acc: Record<string, any> & { _id: string }, item) => {\n acc[item.headerId] = item.value;\n return acc;\n },\n {\n _id: crypto.randomUUID(),\n },\n ),\n );\n\n return {\n id: excelData.id,\n name: excelData.name,\n type: NodeKind.DecisionTable,\n content: {\n ...parseDecisionTable({\n inputs,\n outputs,\n rules: reducedRules,\n executionMode: excelData.executionMode || 'single',\n hitPolicy: excelData.hitPolicy || 'first',\n passThrough: excelData.passThrough,\n }),\n inputField: excelData.inputField,\n outputPath: excelData.outputPath,\n },\n position: excelData.position,\n };\n });\n\n const { decisionGraph } = decisionGraphRaw.stateStore.getState();\n\n const updatedNodes = decisionGraph.nodes.map((node) => {\n let _node = node;\n // updating existing nodes\n nodesFromExcel.forEach((excelNode) => {\n if (excelNode.id === node.id) _node = { ...node, content: excelNode.content };\n });\n\n return _node;\n });\n\n // filtering new nodes and setting them proper position\n const newNodes = nodesFromExcel\n .filter((node) => !updatedNodes.some((existingNode) => existingNode.id === node.id))\n .map((newNode, index) => ({\n ...newNode,\n type: NodeKind.DecisionTable,\n position: (() => {\n const findAvailablePosition = (x: number, y: number) => {\n const position = { x, y };\n\n if (decisionGraph.nodes.some((node) => node.position.x === position.x && node.position.y === position.y)) {\n return findAvailablePosition(x + 250, y);\n }\n\n return position;\n };\n\n const availablePosition = findAvailablePosition(0, 0);\n\n return { x: availablePosition.x + index * 250, y: 0 };\n })(),\n }));\n\n const modelParsed = decisionModelSchema.safeParse({\n nodes: [...updatedNodes, ...newNodes],\n edges: decisionGraph.edges,\n });\n\n if (!modelParsed.success) {\n toast.error(modelParsed.error?.message);\n return;\n }\n\n setDecisionGraph(modelParsed.data);\n setExcelGraphData(null);\n };\n\n const downloadJDM = async () => {\n try {\n const { name, decisionGraph } = decisionGraphRaw.stateStore.getState();\n // create file in browser\n const fileName = `${name.replaceAll('.json', '')}.json`;\n const json = JSON.stringify(\n {\n contentType: DecisionContentType,\n nodes: decisionGraph.nodes,\n edges: decisionGraph.edges,\n },\n null,\n 2,\n );\n const blob = new Blob([json], { type: 'application/json' });\n const href = URL.createObjectURL(blob);\n\n // create \"a\" HTLM element with href to file\n const link = window.document.createElement('a');\n link.href = href;\n link.download = fileName;\n window.document.body.appendChild(link);\n link.click();\n\n // clean up \"a\" element & remove ObjectURL\n window.document.body.removeChild(link);\n URL.revokeObjectURL(href);\n } catch (e: any) {\n toast.error(e.message);\n }\n };\n\n const downloadJDMExcel = async () => {\n try {\n const { name, decisionGraph, viewConfig } = decisionGraphRaw.stateStore.getState();\n const fileName = name.replaceAll('.json', '');\n\n const decisionTableNodes = decisionGraph.nodes\n .filter((node) => node.type === NodeKind.DecisionTable)\n .filter((node) => (viewConfig?.enabled ? !!viewConfig?.permissions?.[node.id] : true))\n .map((decisionTable) => ({\n ...decisionTable.content,\n id: decisionTable.id,\n name: decisionTable.name,\n }));\n\n await exportDecisionTable(fileName, decisionTableNodes);\n toast.success('Excel file has been downloaded successfully!');\n } catch {\n toast.error('Failed to download Excel file!');\n }\n };\n\n const uploadItems: MenuProps['items'] = [\n !viewConfig?.enabled && {\n key: 'upload-json',\n label: t('dg.toolbar.uploadJson'),\n onClick: () => fileInput?.current?.click?.(),\n },\n {\n key: 'upload-excel',\n label: t('dg.toolbar.uploadExcel'),\n onClick: () => excelFileInput?.current?.click?.(),\n },\n ].filter((item) => !!item);\n\n const downloadItems: MenuProps['items'] = [\n !viewConfig?.enabled && {\n key: 'download-json',\n label: t('dg.toolbar.downloadJson'),\n onClick: () => downloadJDM(),\n },\n {\n key: 'download-excel',\n label: t('dg.toolbar.downloadExcel'),\n onClick: () => downloadJDMExcel(),\n },\n ].filter((item) => !!item);\n\n return (\n <Fragment>\n <div className={'[grid-area:sidebar] flex h-full min-h-0 bg-[var(--grl-color-bg-container)]'}>\n <input\n hidden\n accept='application/json'\n type='file'\n ref={fileInput}\n onChange={handleUploadInput}\n onClick={(event) => {\n (event.target as HTMLInputElement).value = '';\n }}\n />\n <input\n hidden\n accept='.xlsx'\n type='file'\n ref={excelFileInput}\n onChange={uploadJDMExcel}\n onClick={(event) => {\n (event.target as HTMLInputElement).value = '';\n }}\n />\n <div className='flex w-12 min-w-12 flex-col items-center justify-between gap-2 border-r border-r-[var(--border)] py-2'>\n <div className={'flex flex-col items-center gap-2'}>\n {!disabled && (\n <Dropdown menu={{ items: uploadItems }} placement='bottomRight' trigger={['click']} arrow>\n <Button type={'text'} disabled={disabled} icon={<CloudUploadOutlined />} />\n </Dropdown>\n )}\n <Dropdown menu={{ items: downloadItems }} placement='bottomRight' trigger={['click']} arrow>\n <Button type={'text'} icon={<CloudDownloadOutlined />} />\n </Dropdown>\n </div>\n <div className={'flex flex-col items-center gap-2'}>\n {(panels || []).map((panel) => {\n const isActive = activePanel === panel.id;\n return (\n <Tooltip\n key={panel.id}\n title={`${!isActive ? 'Open' : 'Close'} ${panel.title.toLowerCase()} panel`}\n placement={'right'}\n >\n <Button\n key={panel.id}\n type='text'\n icon={panel.icon}\n style={{ background: isActive ? 'rgba(0, 0, 0, 0.1)' : undefined }}\n onClick={() => {\n if (panel?.onClick) return panel.onClick();\n if (panel?.renderPanel) setActivePanel(isActive ? undefined : panel.id);\n }}\n />\n </Tooltip>\n );\n })}\n </div>\n </div>\n </div>\n\n <GraphExcelDialog\n excelData={excelGraphData}\n handleSuccess={handleDataMapping}\n handleCancel={() => {\n setExcelGraphData(null);\n }}\n />\n </Fragment>\n );\n};\n","import { CloseOutlined, DeploymentUnitOutlined, UnorderedListOutlined } from '#icons';\nimport clsx from 'clsx';\nimport React, { useMemo } from 'react';\n\nimport { useT } from '../../../theming/i18n';\nimport { DiffIcon } from '../../diff-icon';\nimport type { TabsProps } from '../../primitives';\nimport { Avatar, Button, Dropdown, Tabs } from '../../primitives';\nimport { useDecisionGraphActions, useDecisionGraphState } from '../context/dg-store.context';\nimport type { DiffStatus } from '../dg-types';\nimport { NodeColor } from '../nodes/specifications/colors';\nimport type { NodeKind } from '../nodes/specifications/specification-types';\nimport { nodeSpecification } from '../nodes/specifications/specifications';\n\nexport type GraphTabsProps = {\n disabled?: boolean;\n tabBarExtraContent?: TabsProps['tabBarExtraContent'];\n};\n\ntype NonUndefined<T> = T extends undefined ? never : T;\ntype TabItem = NonUndefined<TabsProps['items']>[number];\n\nexport const GraphTabs: React.FC<GraphTabsProps> = ({ disabled, tabBarExtraContent }) => {\n const graphActions = useDecisionGraphActions();\n const { openNodes, activeNodeId, viewConfig } = useDecisionGraphState(\n ({ decisionGraph, activeTab, openTabs, viewConfig }) => ({\n activeNodeId: (decisionGraph?.nodes ?? []).find((node) => node.id === activeTab)?.id,\n openNodes: (openTabs || [])\n .map((tab) => {\n const node = (decisionGraph?.nodes ?? []).find((node) => node.id === tab);\n if (!node) return undefined;\n return {\n id: node?.id,\n name: node.name,\n type: node.type,\n diff: node?._diff,\n };\n })\n .filter((node) => !!node),\n viewConfig,\n }),\n );\n\n const defaultItems = useMemo(() => {\n return [\n {\n key: 'graph',\n label: (\n <TabLabel\n total={openNodes?.length}\n icon={viewConfig?.enabled ? <UnorderedListOutlined /> : <DeploymentUnitOutlined />}\n name={viewConfig?.enabled ? 'Nodes' : 'Graph'}\n active={!activeNodeId || activeNodeId === 'graph'}\n />\n ),\n },\n ];\n }, [viewConfig, openNodes, activeNodeId]);\n\n return (\n <div>\n <Tabs\n type='line'\n size='small'\n className={clsx(\n 'max-w-full [box-sizing:content-box] border-b border-b-[var(--border)] bg-[var(--grl-color-bg-container)]',\n '[&_[role=tablist]]:m-0',\n )}\n activeKey={activeNodeId || 'graph'}\n onChange={(val) => graphActions.openTab(val)}\n tabBarExtraContent={tabBarExtraContent}\n items={[\n ...defaultItems,\n ...openNodes.map((node, index) => {\n const specification = nodeSpecification[node.type as NodeKind];\n\n return {\n disabled,\n key: node.id,\n label: (\n <TabLabel\n onContextClick={(action) => {\n graphActions.closeTab(node.id, action);\n }}\n icon={specification?.icon}\n name={node?.name ?? node?.type}\n diffStatus={node?.diff?.status}\n color={specification?.color}\n index={index}\n active={node.id === activeNodeId}\n total={openNodes?.length}\n onClose={() => graphActions.closeTab(node.id)}\n />\n ),\n } satisfies TabItem;\n }),\n ]}\n />\n </div>\n );\n};\n\nconst TabLabel: React.FC<{\n index?: number;\n total?: number;\n icon?: React.ReactNode;\n name?: string;\n color?: string;\n diffStatus?: string;\n onClose?: () => void;\n active?: boolean;\n onContextClick?: (action: string) => void;\n}> = ({ total = 0, index = -1, icon, name, active, diffStatus, color = NodeColor.Blue, onClose, onContextClick }) => {\n const t = useT();\n const items = [\n total > 0 &&\n index !== -1 && {\n key: 'close',\n label: 'Close',\n onClick: () => onContextClick?.('close'),\n },\n total > 0 &&\n index !== -1 && {\n key: 'close-all',\n label: t('dg.tabs.closeAll'),\n onClick: () => onContextClick?.('close-all'),\n },\n total > 0 &&\n index !== -1 && {\n key: 'close-other',\n label: t('dg.tabs.closeOthers'),\n onClick: () => onContextClick?.('close-other'),\n },\n total > 0 &&\n index + 1 < total && {\n key: 'close-right',\n label: t('dg.tabs.closeRight'),\n onClick: () => onContextClick?.('close-right'),\n },\n total > 0 &&\n index > 0 && {\n key: 'close-left',\n label: t('dg.tabs.closeLeft'),\n onClick: () => onContextClick?.('close-left'),\n },\n ].filter((item) => !!item);\n\n const content = (\n <div\n className='group/tab flex items-center gap-1.5 px-3 py-[9px] transition-opacity duration-100 ease-in data-[active=false]:opacity-75 hover:opacity-100'\n data-active={active}\n >\n <Avatar\n size='small'\n shape='square'\n style={{\n background: color,\n fontSize: 11,\n width: 18,\n height: 18,\n lineHeight: '18px',\n borderRadius: 3,\n }}\n icon={icon}\n />\n {name}\n <DiffIcon\n status={diffStatus as DiffStatus}\n style={{\n fontSize: 16,\n }}\n />\n {onClose && (\n <Button\n className='opacity-0 transition-opacity duration-100 ease-in group-hover/tab:opacity-100! group-data-[active=true]/tab:opacity-100!'\n type='text'\n size='small'\n style={{ height: 20, width: 20, color: 'black', borderRadius: '50%', lineHeight: 0 }}\n icon={<CloseOutlined style={{ fontSize: 10 }} />}\n onClick={(e) => {\n e.stopPropagation();\n onClose?.();\n }}\n />\n )}\n </div>\n );\n\n // No context actions (e.g. the reserved Graph tab) → no menu wrapper at all.\n if (!onContextClick || items.length === 0) {\n return content;\n }\n\n return (\n <Dropdown menu={{ items }} trigger={['contextMenu']}>\n {content}\n </Dropdown>\n );\n};\n","import { smartSplit } from './utility';\n\nexport const emptyCustomFunctionReturnSchema = {};\n\nexport const normalizeFunctionReturns = (returns?: any) => {\n if (!returns || typeof returns !== 'object' || Array.isArray(returns)) {\n return emptyCustomFunctionReturnSchema;\n }\n\n return returns;\n};\n\nexport const normalizeFunctionDefinition = (func: any, namespace?: string) => ({\n ...func,\n namespace: func?.namespace ?? namespace,\n returns: normalizeFunctionReturns(func?.returns),\n});\n\nexport const normalizeCustomFunctions = (customFunctions?: any): any[] => {\n if (!Array.isArray(customFunctions)) {\n return [];\n }\n\n return customFunctions.flatMap((item: any) => {\n if (Array.isArray(item?.tools)) {\n return item.tools.map((tool: any) => normalizeFunctionDefinition(tool, item?.name));\n }\n\n return item?.name ? [normalizeFunctionDefinition(item)] : [];\n });\n};\n\nexport const getFunctionReturnSchema = (funcmeta?: any) => normalizeFunctionReturns(funcmeta?.returns);\n\nexport const isFunctionExpressionValue = (value: unknown): value is string | string[] =>\n Array.isArray(value) || (typeof value === 'string' && value.includes(';;'));\n\nexport const isFunctionExpression = (expression?: { type?: string; value?: unknown } | null) =>\n expression?.type === 'function' || isFunctionExpressionValue(expression?.value);\n\nexport const getFunctionNameFromValue = (value?: unknown): string | null => {\n if (Array.isArray(value)) {\n const functionName = value[0]?.trim();\n return functionName ? functionName : null;\n }\n\n if (typeof value !== 'string' || !value.trim()) {\n return null;\n }\n\n const [functionName] = smartSplit(value);\n const trimmedFunctionName = functionName?.trim();\n\n return trimmedFunctionName ? trimmedFunctionName : null;\n};\n\nexport const findCustomFunctionDefinition = (customFunctions: any[], functionName?: string | null) => {\n if (!functionName) {\n return undefined;\n }\n\n return customFunctions.find((func: any) => func?.name === functionName);\n};\n\nexport const LEGACY_CUSTOM_FUNCTION_KIND = 'UDF';\n\nexport type FunctionScopeMode = 'scoped' | 'legacy' | 'free';\n\nexport type FunctionScope = {\n mode: FunctionScopeMode;\n functions: any[];\n};\n\n/**\n * kind 约定(单 token):'UDF' → legacy(自由全函数);namespace 名(集合容器节点) → scoped;其余 → free(现状行为)。\n * schema 函数一律落在 ns 容器内,不存在独立的函数名 kind。\n */\nexport const resolveFunctionScope = (kind?: string | null, customFunctions?: any): FunctionScope => {\n const namespaces = Array.isArray(customFunctions) ? customFunctions.filter(Boolean) : [];\n const allFunctions = normalizeCustomFunctions(namespaces);\n\n if (!kind) {\n return { mode: 'free', functions: allFunctions };\n }\n\n if (kind === LEGACY_CUSTOM_FUNCTION_KIND) {\n return { mode: 'legacy', functions: allFunctions };\n }\n\n const namespaceContainer = namespaces.find((ns: any) => ns?.name === kind);\n if (namespaceContainer) {\n return { mode: 'scoped', functions: normalizeCustomFunctions([namespaceContainer]) };\n }\n\n return { mode: 'free', functions: allFunctions };\n};\n\nexport const buildDefaultFunctionExpression = (funcDef: any) => {\n const properties = funcDef?.parameters?.properties ?? {};\n const argExprs: Record<string, string> = {};\n const args = Object.keys(properties).map((argName: string) => {\n argExprs[argName] = properties[argName]?.default ?? '';\n return argExprs[argName];\n });\n\n return {\n type: 'function' as const,\n value: [funcDef?.name ?? '', ...args],\n funcmeta: funcDef,\n arg_exprs: argExprs,\n returnSchema: getFunctionReturnSchema(funcDef),\n };\n};\n\n/**\n * 打开节点时治愈函数作用域漂移:scoped 档 value[0] 不在集合内时重置为首函数;legacy/free 不治愈。\n * 返回 null 表示无需治愈。\n */\nexport const healExpressionsForScope = (expressions: any, scope?: FunctionScope): any[] | null => {\n if (!scope || scope.mode !== 'scoped' || !Array.isArray(expressions)) {\n return null;\n }\n\n const [primaryFunction] = scope.functions;\n if (!primaryFunction?.name) {\n return null;\n }\n\n const allowed = scope.functions.map((func: any) => func?.name).filter(Boolean);\n\n let changed = false;\n const healed = expressions.map((expression: any) => {\n if (!isFunctionExpression(expression)) {\n return expression;\n }\n\n const functionName = getFunctionNameFromValue(expression.value);\n if (!functionName || allowed.includes(functionName)) {\n return expression;\n }\n\n changed = true;\n return { ...expression, ...buildDefaultFunctionExpression(primaryFunction) };\n });\n\n return changed ? healed : null;\n};\n","import type { Variable, VariableType } from '@gorules/zen-engine-wasm';\nimport equal from 'fast-deep-equal/es6/react';\nimport { produce } from 'immer';\nimport React, { useMemo } from 'react';\nimport type { z } from 'zod';\nimport type { StoreApi, UseBoundStore } from 'zustand';\nimport { create, useStore } from 'zustand';\n\nimport { type GetNodeDataResult } from '../../../helpers/node-data';\nimport type { expressionNodeSchema } from '../../../helpers/schema';\nimport { useMemoEquality } from '../../../helpers/use-memoized-selector';\nimport type { SimulationTrace, SimulationTraceDataExpression } from '../../decision-graph';\nimport type { DiffMetadata } from '../../decision-graph/dg-types';\n\nconst ExpressionStoreContext = React.createContext<\n UseBoundStore<StoreApi<ExpressionStore>> & {\n setState: (partial: Partial<ExpressionStore>) => void;\n }\n>({} as any);\n\nexport type ExpressionEntry = {\n id: string;\n key: string;\n value: string | string[];\n _diff?: DiffMetadata;\n type?: string;\n returnSchema?: any;\n // 保留这些字段用于向后兼容,但在新的存储结构中不再使用\n funcmeta?: any;\n arg_exprs?: Record<string, any>;\n expr_ast?: any[];\n};\n\nexport type ExpressionPermission = 'edit:full' | 'edit:values' | 'view';\n\nexport type ExpressionStore = {\n disabled: boolean;\n configurable?: boolean;\n\n permission?: ExpressionPermission;\n\n addRowAbove: (index?: number, data?: Partial<ExpressionEntry>) => void;\n addRowBelow: (index?: number, data?: Partial<ExpressionEntry>) => void;\n\n expressions: ExpressionEntry[];\n setExpressions: (expressions: ExpressionEntry[]) => void;\n\n /** 数组移动语义:摘除 source 行并插入 target 位(拖拽重排用;相邻步等价交换) */\n moveRows: (sourceIndex: number, targetIndex: number) => void;\n /** @deprecated 兼容别名:内部转调 moveRows */\n swapRows: (sourceIndex: number, targetIndex: number) => void;\n updateRow: (index: number, update: Partial<Omit<ExpressionEntry, 'id'>>) => void;\n removeRow: (index: number) => void;\n\n inputVariableType?: VariableType;\n\n debugIndex: number;\n calculatedInputData?: Variable;\n debug?: {\n snapshot: z.infer<typeof expressionNodeSchema>['content'];\n trace: SimulationTrace<SimulationTraceDataExpression>;\n inputData?: GetNodeDataResult;\n };\n};\n\ntype ExpressionStoreProviderProps = {\n //\n};\n\nexport const createExpression = (data: Partial<ExpressionEntry> = {}): ExpressionEntry => ({\n id: crypto.randomUUID(),\n key: '',\n value: '',\n ...data,\n});\n\nexport const ExpressionStoreProvider: React.FC<React.PropsWithChildren<ExpressionStoreProviderProps>> = ({\n children,\n}) => {\n const store = useMemo(\n () =>\n create<ExpressionStore>((set, get) => ({\n disabled: false,\n debugIndex: 0,\n addRowAbove: (index = 0) => {\n set(\n produce<ExpressionStore>((draft) => {\n draft.expressions.splice(index, 0, createExpression());\n return draft;\n }),\n );\n },\n addRowBelow: (index) => {\n set(\n produce<ExpressionStore>((draft) => {\n index = index ?? draft.expressions.length - 1;\n draft.expressions.splice(index + 1, 0, createExpression());\n\n return draft;\n }),\n );\n },\n expressions: [],\n setExpressions: (expressions) => {\n set({ expressions });\n },\n moveRows: (sourceIndex, targetIndex) => {\n set(\n produce<ExpressionStore>((draft) => {\n const [input] = draft.expressions.splice(sourceIndex, 1);\n draft.expressions.splice(targetIndex, 0, input);\n\n return draft;\n }),\n );\n },\n swapRows: (sourceIndex, targetIndex) => {\n get().moveRows(sourceIndex, targetIndex);\n },\n removeRow: (index) => {\n set(\n produce<ExpressionStore>((draft) => {\n draft.expressions.splice(index, 1);\n return draft;\n }),\n );\n },\n updateRow: (index, update) => {\n set(\n produce<ExpressionStore>((draft) => {\n draft.expressions[index] = {\n ...draft.expressions[index],\n ...update,\n };\n\n return draft;\n }),\n );\n },\n })),\n [],\n );\n\n return <ExpressionStoreContext.Provider value={store}>{children}</ExpressionStoreContext.Provider>;\n};\n\nexport function useExpressionStore<T>(\n selector: (state: ExpressionStore) => T,\n equals: (a: any, b: any) => boolean = equal,\n): T {\n return useStore(React.useContext(ExpressionStoreContext), useMemoEquality(selector, equals));\n}\n\nexport const useExpressionStoreRaw = () => React.useContext(ExpressionStoreContext);\n","import React, { useMemo } from 'react';\nimport { P, match } from 'ts-pattern';\n\nimport { useT } from '../../theming/i18n';\nimport { Select, Typography } from '../primitives';\nimport { Stack } from '../stack';\nimport { useExpressionStore, useExpressionStoreRaw } from './context/expression-store.context';\n\nexport const ExpressionCommandBar: React.FC = () => {\n const t = useT();\n const expressionStore = useExpressionStoreRaw();\n const { debugIndex, traceCount } = useExpressionStore(({ debug, debugIndex }) => ({\n debugIndex,\n traceCount: match(debug?.trace?.traceData)\n .with(P.array(), (some) => some.length)\n .otherwise(() => null),\n }));\n\n const traceIndexOptions = useMemo(() => {\n if (!traceCount) {\n return null;\n }\n\n return Array.from({ length: traceCount }).map((_, i) => ({\n label: String(i),\n value: i,\n }));\n }, [debugIndex, traceCount]);\n\n if (!traceIndexOptions) {\n return null;\n }\n\n return (\n <Stack horizontal horizontalAlign={'space-between'} verticalAlign={'center'} className={'grl-dt__command-bar'}>\n <Stack gap={8} horizontal className='full-width' />\n {traceIndexOptions && (\n <Stack horizontal verticalAlign='center' horizontalAlign='end'>\n <Typography.Text style={{ fontSize: 12 }}>{t('dt.toolbar.simulationIndex')}</Typography.Text>\n <Select\n size='small'\n style={{ fontSize: 12, minWidth: 60 }}\n options={traceIndexOptions}\n onChange={(debugIndex: number) => expressionStore.setState({ debugIndex })}\n value={traceIndexOptions.some((t) => t.value === debugIndex) ? debugIndex : 0}\n />\n </Stack>\n )}\n </Stack>\n );\n};\n","import equal from 'fast-deep-equal/es6/react';\nimport type React from 'react';\nimport { useEffect, useRef } from 'react';\n\nimport { type FunctionScope, healExpressionsForScope } from '../../helpers/custom-function-schema';\nimport type { ExpressionEntry, ExpressionStore } from './context/expression-store.context';\nimport { useExpressionStore, useExpressionStoreRaw } from './context/expression-store.context';\n\nexport type ExpressionControllerProps = {\n disabled?: boolean;\n defaultValue?: ExpressionEntry[];\n permission?: ExpressionStore['permission'];\n value?: ExpressionEntry[];\n onChange?: (value: ExpressionEntry[]) => void;\n functionScope?: FunctionScope;\n};\n\nexport const ExpressionController: React.FC<ExpressionControllerProps> = ({\n value,\n onChange,\n defaultValue = [],\n disabled = false,\n permission = 'edit:full',\n functionScope,\n}) => {\n const mounted = useRef<boolean>(false);\n const store = useExpressionStoreRaw();\n const { setExpressions, expressions } = useExpressionStore(({ setExpressions, expressions }) => ({\n setExpressions,\n expressions,\n }));\n\n useEffect(() => {\n store.setState({\n disabled,\n permission,\n });\n }, [disabled, permission]);\n\n useEffect(() => {\n if (!onChange) {\n return;\n }\n\n return store.subscribe((state, prevState) => {\n if (!equal(state.expressions, prevState.expressions)) {\n onChange?.(state.expressions);\n }\n });\n }, [store, onChange]);\n\n useEffect(() => {\n if (mounted.current && value && !equal(value, expressions)) {\n setExpressions(value);\n }\n }, [value]);\n\n useEffect(() => {\n if (value) {\n const healed = healExpressionsForScope(value, functionScope);\n setExpressions(healed ?? value);\n } else if (defaultValue) {\n setExpressions(defaultValue);\n }\n mounted.current = true;\n }, []);\n\n return null;\n};\n","import { VariableType } from '@gorules/zen-engine-wasm';\n\ntype JsonSchema = {\n type?: string | string[];\n properties?: Record<string, JsonSchema>;\n items?: JsonSchema | JsonSchema[];\n oneOf?: JsonSchema[];\n anyOf?: JsonSchema[];\n allOf?: JsonSchema[];\n nullable?: boolean;\n};\n\nconst normalizeType = (schema: JsonSchema): string | undefined => {\n if (Array.isArray(schema.type)) {\n const preferredType = schema.type.find((type) => type !== 'null');\n return preferredType ?? schema.type[0];\n }\n\n return schema.type;\n};\n\nexport const jsonSchemaToVariableType = (schema?: JsonSchema | null): VariableType => {\n if (!schema || typeof schema !== 'object') {\n return VariableType.fromJson('Any');\n }\n\n if (Array.isArray(schema.oneOf) && schema.oneOf.length > 0) {\n return jsonSchemaToVariableType(schema.oneOf[0]);\n }\n\n if (Array.isArray(schema.anyOf) && schema.anyOf.length > 0) {\n return jsonSchemaToVariableType(schema.anyOf[0]);\n }\n\n if (Array.isArray(schema.allOf) && schema.allOf.length > 0) {\n return schema.allOf.reduce(\n (acc, item) => acc.merge(jsonSchemaToVariableType(item)),\n VariableType.fromJson({ Object: {} }),\n );\n }\n\n const schemaType = normalizeType(schema);\n switch (schemaType) {\n case 'object': {\n const objectType = VariableType.fromJson({ Object: {} });\n Object.entries(schema.properties ?? {}).forEach(([key, value]) => {\n objectType.set(key, jsonSchemaToVariableType(value));\n });\n\n return objectType;\n }\n case 'array': {\n const itemSchema = Array.isArray(schema.items) ? schema.items[0] : schema.items;\n return jsonSchemaToVariableType(itemSchema).toArray();\n }\n case 'string':\n return VariableType.fromJson('String');\n case 'boolean':\n return VariableType.fromJson('Bool');\n case 'number':\n case 'integer':\n return VariableType.fromJson('Number');\n case 'null':\n return VariableType.fromJson('Null');\n default: {\n if (schema.properties) {\n return jsonSchemaToVariableType({ ...schema, type: 'object' });\n }\n\n if (schema.items) {\n return jsonSchemaToVariableType({ ...schema, type: 'array' });\n }\n\n if (schema.nullable) {\n return VariableType.fromJson('Null');\n }\n\n return VariableType.fromJson('Any');\n }\n }\n};\n","import React from 'react';\n\nimport { useT } from '../../theming/i18n';\nimport { Dropdown } from '../primitives';\nimport { SpacedText } from '../spaced-text';\nimport { useExpressionStore } from './context/expression-store.context';\n\ntype ExpressionItemContextMenuProps = {\n index: number;\n children: React.ReactNode;\n};\n\nexport const ExpressionItemContextMenu: React.FC<ExpressionItemContextMenuProps> = ({ index, children }) => {\n const t = useT();\n const { addRowAbove, addRowBelow, disabled } = useExpressionStore(({ addRowBelow, addRowAbove, disabled }) => ({\n addRowBelow,\n addRowAbove,\n disabled,\n }));\n\n return (\n <Dropdown\n destroyPopupOnHide\n transitionName=''\n disabled={disabled}\n overlayStyle={{ minWidth: 200 }}\n trigger={['contextMenu']}\n menu={{\n items: [\n {\n key: 'addRowAbove',\n label: <SpacedText left={t('expression.addRowAbove')} />,\n onClick: () => {\n addRowAbove(index);\n },\n },\n {\n key: 'addRowBelow',\n label: <SpacedText left={t('expression.addRowBelow')} />,\n onClick: () => {\n addRowBelow(index);\n },\n },\n ],\n }}\n >\n {children}\n </Dropdown>\n );\n};\n","import { useSortable } from '@dnd-kit/sortable';\nimport type { VariableType } from '@gorules/zen-engine-wasm';\nimport clsx from 'clsx';\nimport equal from 'fast-deep-equal/es6/react';\nimport { GripVerticalIcon } from 'lucide-react';\nimport React, { useEffect, useMemo, useRef, useState } from 'react';\n\nimport { composeRefs } from '../../helpers/compose-refs';\nimport {\n type FunctionScope,\n emptyCustomFunctionReturnSchema,\n getFunctionReturnSchema,\n isFunctionExpression,\n normalizeCustomFunctions,\n normalizeFunctionReturns,\n} from '../../helpers/custom-function-schema';\nimport { getTrace } from '../../helpers/trace';\nimport { parseOperatorExprInput, smartSplit, toOperatorExprArray, toOperatorExprDisplay } from '../../helpers/utility';\nimport { useT } from '../../theming/i18n';\nimport { CodeEditor } from '../code-editor';\nimport { CodeEditorPreview } from '../code-editor/ce-preview';\nimport { ConfirmAction } from '../confirm-action';\nimport { DiffIcon } from '../diff-icon';\nimport { Select, Tabs, Typography } from '../primitives';\nimport { DiffAutosizeTextArea } from '../shared';\nimport { DiffCodeEditor } from '../shared/diff-ce';\nimport type { ExpressionEntry } from './context/expression-store.context';\nimport { useExpressionStore } from './context/expression-store.context';\nimport { ExpressionItemContextMenu } from './expression-item-context-menu';\n\nexport type ExpressionItemProps = {\n expression: ExpressionEntry;\n index: number;\n variableType?: VariableType;\n customFunctions?: any;\n functionScope?: FunctionScope;\n};\n\nconst emptyReturnSchema = emptyCustomFunctionReturnSchema;\n\nexport const ExpressionItem: React.FC<ExpressionItemProps> = ({\n expression,\n index,\n variableType,\n customFunctions,\n functionScope,\n}) => {\n const t = useT();\n const [isFocused, setIsFocused] = useState(false);\n const [editMode, setEditMode] = useState<'code' | 'function'>('function');\n const expressionRef = useRef<HTMLDivElement>(null);\n const scopeMode = functionScope?.mode ?? 'free';\n const normalizedCustomFunctions = useMemo(() => normalizeCustomFunctions(customFunctions), [customFunctions]);\n const availableFunctions = useMemo(\n () => (scopeMode === 'scoped' ? (functionScope?.functions ?? []) : normalizedCustomFunctions),\n [scopeMode, functionScope, normalizedCustomFunctions],\n );\n const hasCustomFunctions = availableFunctions.length > 0;\n\n const getEnumOptions = (argDef?: any) => {\n if (!Array.isArray(argDef?.enum) || argDef.enum.length === 0) {\n return [];\n }\n\n return argDef.enum.map((item: unknown) => ({\n label: String(item),\n value: String(item),\n }));\n };\n\n const stripExpressionStringQuotes = (value: string) => {\n if (value.length >= 2 && value.startsWith('\"') && value.endsWith('\"')) {\n return value.slice(1, -1);\n }\n\n return value;\n };\n\n const toEnumExpressionValue = (value: string, argDef?: any) => {\n const isStringEnum =\n argDef?.type === 'string' ||\n (Array.isArray(argDef?.enum) && argDef.enum.every((item: unknown) => typeof item === 'string'));\n\n if (isStringEnum) {\n return JSON.stringify(value);\n }\n\n return value;\n };\n\n const splitFunctionParts = (value: string | string[], expectedArgCount?: number): string[] => {\n if (Array.isArray(value)) {\n return value;\n }\n\n const str = value;\n const parts = smartSplit(str);\n if (expectedArgCount === undefined) {\n return parts;\n }\n\n const expectedPartCount = expectedArgCount + 1;\n if (parts.length === expectedPartCount) {\n return parts;\n }\n\n const simpleParts = str.split(';;');\n if (simpleParts.length === expectedPartCount) {\n return simpleParts;\n }\n\n if (parts.length < expectedPartCount && simpleParts.length > expectedPartCount) {\n return [...simpleParts.slice(0, expectedPartCount - 1), simpleParts.slice(expectedPartCount - 1).join(';;')];\n }\n\n return parts;\n };\n\n const parseFunctionValue = (\n value: string | string[],\n fallbackReturnSchema: any = expression.returnSchema ?? emptyReturnSchema,\n ) => {\n if (!value || (typeof value === 'string' && !value.trim())) {\n return null;\n }\n\n const parts = toOperatorExprArray(value);\n const funcName = parts[0];\n\n const funcDef = normalizedCustomFunctions.find((f: any) => f.name === funcName);\n if (!funcDef) {\n if (parts.length === 0) {\n return null;\n }\n\n const args = parts.slice(1);\n const properties: Record<string, any> = {};\n args.forEach((_arg, index) => {\n properties[`arg${index}`] = {\n type: 'string',\n description: `Parameter ${index + 1}`,\n default: '',\n };\n });\n\n return {\n funcmeta: {\n name: funcName,\n parameters: {\n properties,\n type: 'object',\n title: funcName,\n },\n returns: normalizeFunctionReturns(fallbackReturnSchema),\n },\n arg_exprs: args.reduce(\n (acc, arg, index) => {\n acc[`arg${index}`] = arg;\n return acc;\n },\n {} as Record<string, any>,\n ),\n };\n }\n\n const argExprs: Record<string, string> = {};\n if (funcDef.parameters && funcDef.parameters.properties) {\n const properties = funcDef.parameters.properties;\n const propertyNames = Object.keys(properties);\n const partsForArgs = splitFunctionParts(value, propertyNames.length);\n const args = partsForArgs.slice(1);\n\n propertyNames.forEach((argName: string, index: number) => {\n const argValue = args[index];\n argExprs[argName] =\n argValue !== undefined && argValue !== null ? String(argValue) : (properties[argName].default ?? '');\n });\n }\n\n return {\n funcmeta: funcDef,\n arg_exprs: argExprs,\n };\n };\n\n const currentFunctionInfo = useMemo(() => {\n const isFunctionType = isFunctionExpression(expression);\n\n if (!isFunctionType) {\n return null;\n }\n\n if (expression.funcmeta) {\n if (expression.funcmeta.parameters?.properties) {\n const argExprs: Record<string, string> = {};\n const properties = expression.funcmeta.parameters.properties;\n const parsedFromValue = parseFunctionValue(expression.value, expression.returnSchema ?? emptyReturnSchema);\n\n Object.keys(properties).forEach((argName) => {\n const parsedValue = parsedFromValue?.arg_exprs?.[argName];\n if (parsedValue !== undefined && parsedValue !== null) {\n argExprs[argName] = String(parsedValue);\n return;\n }\n\n const currentValue = expression.arg_exprs?.[argName];\n if (currentValue !== undefined && currentValue !== null) {\n argExprs[argName] = typeof currentValue === 'object' ? String(parsedValue ?? '') : String(currentValue);\n } else {\n argExprs[argName] = properties[argName].default ?? '';\n }\n });\n\n return {\n funcmeta: expression.funcmeta,\n arg_exprs: argExprs,\n };\n }\n\n return {\n funcmeta: expression.funcmeta,\n arg_exprs: expression.arg_exprs || {},\n };\n }\n\n return parseFunctionValue(expression.value, expression.returnSchema ?? emptyReturnSchema);\n }, [expression.type, expression.funcmeta, expression.arg_exprs, expression.value, normalizedCustomFunctions]);\n\n const { updateRow, removeRow, disabled, permission, configurable } = useExpressionStore(\n ({ updateRow, removeRow, disabled, permission, configurable }) => ({\n updateRow,\n removeRow,\n disabled,\n permission,\n configurable: configurable ?? permission === 'edit:full',\n }),\n );\n\n useEffect(() => {\n if (isFunctionExpression(expression) && currentFunctionInfo?.funcmeta) {\n setEditMode('function');\n }\n }, [expression.type, expression.value]);\n\n useEffect(() => {\n if (!isFunctionExpression(expression) || !currentFunctionInfo?.funcmeta) {\n return;\n }\n\n const nextReturnSchema = getFunctionReturnSchema(currentFunctionInfo.funcmeta);\n if (equal(expression.returnSchema, nextReturnSchema)) {\n return;\n }\n\n updateRow(index, {\n type: 'function',\n returnSchema: nextReturnSchema,\n });\n }, [index, expression.type, expression.value, expression.returnSchema, currentFunctionInfo, updateRow]);\n\n const onChange = (update: Partial<Omit<ExpressionEntry, 'id'>>) => {\n updateRow(index, update);\n };\n\n const buildFunctionValue = (funcmeta: any, argExprs: Record<string, any>): string[] => {\n const properties = funcmeta?.parameters?.properties ?? {};\n const argValues = Object.keys(properties).map((argName) => String(argExprs?.[argName] ?? ''));\n return [funcmeta?.name ?? '', ...argValues];\n };\n\n const onSelectFunction = (funcName: string, option: any) => {\n const funcmeta = option?.fun;\n if (!funcmeta) {\n return;\n }\n\n const properties = funcmeta?.parameters?.properties ?? {};\n const argExprs: Record<string, string> = {};\n Object.keys(properties).forEach((argName) => {\n argExprs[argName] = properties[argName].default ?? '';\n });\n\n onChange({\n value: buildFunctionValue(funcmeta, argExprs),\n type: 'function',\n returnSchema: getFunctionReturnSchema(funcmeta),\n funcmeta,\n arg_exprs: argExprs,\n });\n };\n\n const onArgChange = (argName: string, argValue: string) => {\n const currentInfo = currentFunctionInfo;\n if (!currentInfo?.funcmeta) {\n return;\n }\n\n const nextArgExprs: Record<string, any> = { ...currentInfo.arg_exprs };\n nextArgExprs[argName] = argValue;\n\n onChange({\n value: buildFunctionValue(currentInfo.funcmeta, nextArgExprs),\n type: 'function',\n arg_exprs: nextArgExprs,\n });\n };\n\n const onRemove = () => {\n removeRow(index);\n };\n\n const {\n attributes: dragAttributes,\n listeners: dragListeners,\n setNodeRef: setDragNodeRef,\n setActivatorNodeRef,\n isDragging,\n isSorting: _isSorting,\n over,\n } = useSortable({\n id: expression.id,\n data: { index },\n disabled: !(permission === 'edit:full' && !disabled),\n });\n\n const isDropping = Boolean(over) && over?.id !== expression.id;\n const overIndex = over?.data.current?.index;\n const direction = isDropping && typeof overIndex === 'number' && overIndex > index ? 'down' : 'up';\n\n const setExpressionRefs = composeRefs(expressionRef, setDragNodeRef as React.Ref<HTMLDivElement>);\n\n const functionOptions = availableFunctions.map((func: any) => ({\n value: func.name,\n label: func.name,\n fun: func,\n }));\n\n return (\n <div\n ref={setExpressionRefs}\n className={clsx(\n 'expression-list-item',\n 'expression-list__item',\n isDropping && direction === 'down' && 'dropping-down',\n isDropping && direction === 'up' && 'dropping-up',\n expression?._diff?.status && `expression-list__item--${expression?._diff?.status}`,\n )}\n style={{ opacity: !isDragging ? 1 : 0.5 }}\n >\n <div ref={setActivatorNodeRef} className='expression-list-item__drag' {...dragListeners} {...dragAttributes}>\n <div className='expression-list-item__drag__inner'>\n {expression?._diff?.status ? (\n <DiffIcon\n status={expression?._diff?.status}\n style={{\n fontSize: 16,\n }}\n />\n ) : (\n <GripVerticalIcon size={10} />\n )}\n </div>\n </div>\n <div className='expression-list-item__key'>\n <ExpressionItemContextMenu index={index}>\n <DiffAutosizeTextArea\n noStyle\n placeholder={t('cf.key')}\n testId={`cf-key-${expression.id}`}\n maxRows={10}\n readOnly={permission !== 'edit:full' || disabled}\n displayDiff={expression?._diff?.fields?.key?.status === 'modified'}\n previousValue={expression?._diff?.fields?.key?.previousValue}\n value={expression?.key}\n onChange={(e) => onChange({ key: e.target.value })}\n />\n </ExpressionItemContextMenu>\n </div>\n <div className='expression-list-item__code'>\n <Tabs\n activeKey={hasCustomFunctions ? editMode : 'code'}\n onChange={(key) => setEditMode(key as 'code' | 'function')}\n size='small'\n items={[\n ...(hasCustomFunctions\n ? [\n {\n key: 'function',\n label: t('cf.function'),\n children: (\n <div className='function-mode-container'>\n <div className='function-select-container'>\n <Select\n value={currentFunctionInfo?.funcmeta?.name || undefined}\n placeholder={t('cf.function')}\n style={{ minWidth: 200, width: 240 }}\n onChange={(value, item: any) => onSelectFunction(value, item)}\n options={functionOptions}\n disabled={!configurable || disabled}\n />\n </div>\n <div className='function-args-container'>\n <div className='function-args-list'>\n {currentFunctionInfo?.funcmeta?.parameters?.properties &&\n Object.keys(currentFunctionInfo.funcmeta.parameters.properties).map((argName: string) => {\n const argDef = currentFunctionInfo.funcmeta.parameters.properties[argName];\n const placeholder = argDef?.description || '';\n const requiredArgs = currentFunctionInfo.funcmeta?.parameters?.required;\n const isRequired = Array.isArray(requiredArgs) && requiredArgs.includes(argName);\n\n let value = '';\n const argValue = currentFunctionInfo?.arg_exprs?.[argName];\n if (argValue !== undefined && argValue !== null) {\n value = typeof argValue === 'object' ? argDef?.default || '' : String(argValue);\n } else {\n value = argDef?.default || '';\n }\n\n const enumOptions = getEnumOptions(argDef);\n\n return (\n <div key={argName} className='function-arg-row'>\n <Typography.Text\n className='function-arg-row__label'\n ellipsis={{ tooltip: argDef?.description || argName }}\n >\n {argName}\n {isRequired && <span className='function-arg-row__required'>*</span>}\n </Typography.Text>\n {enumOptions.length > 0 ? (\n <Select\n className='function-arg-row__editor'\n placeholder={placeholder}\n value={value ? stripExpressionStringQuotes(value) : undefined}\n options={enumOptions}\n style={{ width: '100%' }}\n onChange={(nextValue) =>\n onArgChange(argName, toEnumExpressionValue(nextValue, argDef))\n }\n disabled={!configurable || disabled}\n />\n ) : (\n <CodeEditor\n key={argName}\n noStyle\n lint={false}\n className='function-arg-code-editor'\n placeholder={placeholder}\n value={value}\n maxRows={3}\n disabled={!configurable || disabled}\n variableType={variableType}\n onChange={(nextValue) => onArgChange(argName, nextValue)}\n />\n )}\n </div>\n );\n })}\n </div>\n </div>\n <ResultOverlay expression={expression} placement='inline' />\n </div>\n ),\n },\n ]\n : []),\n {\n key: 'code',\n label: t('cf.code'),\n children: (\n <ExpressionItemContextMenu index={index}>\n <div className='code-mode-container'>\n <div className='code-editor-container'>\n <DiffCodeEditor\n className='expression-list-item__value'\n placeholder='Expression'\n maxRows={9}\n disabled={disabled}\n value={toOperatorExprDisplay(expression?.value)}\n displayDiff={expression?._diff?.fields?.value?.status === 'modified'}\n previousValue={toOperatorExprDisplay(expression?._diff?.fields?.value?.previousValue ?? '')}\n onChange={(value) => onChange({ value: parseOperatorExprInput(value) })}\n variableType={variableType}\n onFocus={() => setIsFocused(true)}\n onBlur={() => setIsFocused(false)}\n noStyle={true}\n />\n </div>\n <ResultOverlay expression={expression} placement='inline' />\n </div>\n </ExpressionItemContextMenu>\n ),\n },\n ]}\n />\n </div>\n <div className='expression-list-item__action'>\n {<ConfirmAction iconOnly disabled={permission !== 'edit:full' || disabled} onConfirm={onRemove} />}\n {isFocused && <LivePreview id={expression.id} value={expression.value} />}\n </div>\n </div>\n );\n};\n\nconst LivePreview = React.memo<{ id: string; value: string | string[] }>(({ id, value }) => {\n const { inputData, initial } = useExpressionStore(({ debug, debugIndex, calculatedInputData }) => {\n const snapshot = (debug?.snapshot?.expressions ?? []).find((e) => e.id === id);\n const trace = snapshot?.key ? getTrace(debug?.trace.traceData, debugIndex)?.[snapshot.key] : undefined;\n\n return {\n inputData: calculatedInputData,\n initial:\n snapshot && trace ? { expression: toOperatorExprDisplay(snapshot.value), result: trace.result } : undefined,\n };\n });\n\n return (\n <div className='expression-list-item__livePreview'>\n <CodeEditorPreview expression={toOperatorExprDisplay(value)} inputData={inputData} initial={initial} />\n </div>\n );\n});\n\nconst ResultOverlay: React.FC<{ expression: ExpressionEntry; placement?: 'floating' | 'inline' }> = ({\n expression,\n placement = 'floating',\n}) => {\n const { trace } = useExpressionStore(({ debug, debugIndex }) => ({\n trace: resolveExpressionResult({\n traceData: getTrace(debug?.trace?.traceData, debugIndex),\n output: getTrace(debug?.trace?.output, debugIndex),\n outputPath: debug?.snapshot?.outputPath,\n key: expression.key,\n }),\n }));\n\n if (trace === undefined) {\n return null;\n }\n\n const traceText = formatTraceText(trace);\n\n return (\n <div\n className={clsx(\n 'expression-list-item__resultOverlay',\n placement === 'inline' && 'expression-list-item__resultOverlay--inline',\n )}\n >\n <Typography.Text\n ellipsis={{\n tooltip: <div className='expression-list-item__resultOverlayTooltip'>{traceText}</div>,\n }}\n style={{ maxWidth: placement === 'inline' ? 220 : 60, overflow: 'hidden' }}\n >\n = {traceText}\n </Typography.Text>\n </div>\n );\n};\n\nconst resolveExpressionResult = ({\n traceData,\n output,\n outputPath,\n key,\n}: {\n traceData: unknown;\n output: unknown;\n outputPath?: string | null;\n key?: string;\n}) => {\n if (!key) {\n return undefined;\n }\n\n const traceEntry = readObjectValue(traceData, key);\n if (isRecord(traceEntry) && Object.prototype.hasOwnProperty.call(traceEntry, 'result')) {\n return traceEntry.result;\n }\n\n if (traceEntry !== undefined) {\n return traceEntry;\n }\n\n const scopedOutput = outputPath ? readPathValue(output, outputPath) : output;\n const scopedOutputValue = readObjectValue(scopedOutput, key);\n if (scopedOutputValue !== undefined) {\n return scopedOutputValue;\n }\n\n return readObjectValue(output, key);\n};\n\nconst readObjectValue = (data: unknown, key: string) => {\n if (!isRecord(data) || !Object.prototype.hasOwnProperty.call(data, key)) {\n return undefined;\n }\n\n return data[key];\n};\n\nconst readPathValue = (data: unknown, path: string) => {\n return path.split('.').reduce<unknown>((current, part) => readObjectValue(current, part), data);\n};\n\nconst isRecord = (data: unknown): data is Record<string, unknown> => {\n return !!data && typeof data === 'object' && !Array.isArray(data);\n};\n\nconst formatTraceText = (data: unknown) => {\n const json = JSON.stringify(data);\n return json === undefined ? String(data) : json;\n};\n","import { PlusCircleOutlined } from '#icons';\nimport { SortableContext, verticalListSortingStrategy } from '@dnd-kit/sortable';\nimport type { VariableType } from '@gorules/zen-engine-wasm';\nimport clsx from 'clsx';\nimport equal from 'fast-deep-equal/es6/react';\nimport React, { useEffect, useState } from 'react';\n\nimport type { FunctionScope } from '../../helpers/custom-function-schema';\nimport { isFunctionExpressionValue } from '../../helpers/custom-function-schema';\nimport { jsonSchemaToVariableType } from '../../helpers/json-schema';\nimport { isWasmAvailable } from '../../helpers/wasm';\nimport { useT } from '../../theming/i18n';\nimport { Button, Tag, Typography } from '../primitives';\nimport { useExpressionStore } from './context/expression-store.context';\nimport { ExpressionItem } from './expression-item';\n\nexport type ExpressionListProps = {\n customFunctions?: any;\n functionScope?: FunctionScope;\n};\n\nconst emptyReturnSchema = {};\n\nexport const ExpressionList: React.FC<ExpressionListProps> = ({ customFunctions, functionScope }) => {\n const t = useT();\n const scopeMode = functionScope?.mode ?? 'free';\n const { expressions, addRowBelow, permission, disabled, inputVariableType } = useExpressionStore(\n ({ expressions, addRowBelow, permission, disabled, inputVariableType }) => ({\n expressions,\n addRowBelow,\n permission,\n disabled,\n inputVariableType,\n }),\n equal,\n );\n\n const [variableType, setVariableType] = useState<VariableType>();\n\n useEffect(() => {\n if (!isWasmAvailable() || !inputVariableType) {\n return;\n }\n\n const resultingVariableType = inputVariableType.clone();\n expressions\n .filter((e) => e.key.length > 0)\n .forEach((expr) => {\n const isFunctionExpression = expr.type === 'function' || isFunctionExpressionValue(expr.value);\n const calculatedType = isFunctionExpression\n ? jsonSchemaToVariableType(expr.returnSchema ?? emptyReturnSchema)\n : resultingVariableType.calculateType(Array.isArray(expr.value) ? expr.value.join(';;') : expr.value);\n resultingVariableType.set(`$.${expr.key}`, calculatedType);\n });\n\n setVariableType(resultingVariableType);\n }, [expressions, inputVariableType]);\n\n return (\n <>\n <div className={'expression-list'}>\n <SortableContext items={expressions.map((e) => e.id)} strategy={verticalListSortingStrategy}>\n <div className={clsx('expression-list__item', 'expression-list__item--heading')}>\n <div className={'expression-list__item__th expression-list__item__th--order'} />\n <Typography.Text type='secondary' className={'expression-list__item__th expression-list__item__th--key'}>\n {t('cf.key')}\n </Typography.Text>\n <Typography.Text type='secondary' className={'expression-list__item__th'}>\n {t('cf.expression')}\n </Typography.Text>\n <div className={'expression-list__item__th expression-list__item__th--scope'}>\n {scopeMode === 'legacy' && <Tag>{t('cf.legacy')}</Tag>}\n </div>\n </div>\n {(expressions || []).map((expression, index) => (\n <ExpressionItem\n key={expression.id}\n expression={expression}\n index={index}\n variableType={variableType}\n customFunctions={customFunctions}\n functionScope={functionScope}\n />\n ))}\n </SortableContext>\n </div>\n {permission === 'edit:full' && !disabled && (\n <div className={'expression-list__button-wrapper'}>\n <Button\n className='expression-list__button'\n icon={<PlusCircleOutlined />}\n type='link'\n onClick={() => addRowBelow()}\n >\n {t('cf.addRow')}\n </Button>\n </div>\n )}\n </>\n );\n};\n","import {\n type DragEndEvent,\n type DragOverEvent,\n DndContext,\n type SensorDescriptor,\n type SensorOptions,\n KeyboardSensor,\n MeasuringStrategy,\n PointerSensor,\n closestCenter,\n useSensor,\n useSensors,\n} from '@dnd-kit/core';\nimport { sortableKeyboardCoordinates } from '@dnd-kit/sortable';\nimport { Variable, VariableType } from '@gorules/zen-engine-wasm';\nimport equal from 'fast-deep-equal/es6/react';\nimport React, { useEffect } from 'react';\n\nimport type { FunctionScope } from '../../helpers/custom-function-schema';\nimport { isWasmAvailable } from '../../helpers/wasm';\nimport type { ExpressionEntry, ExpressionStore } from './context/expression-store.context';\nimport { ExpressionStoreProvider, useExpressionStoreRaw } from './context/expression-store.context';\nimport { ExpressionCommandBar } from './expression-command-bar';\nimport type { ExpressionControllerProps } from './expression-controller';\nimport { ExpressionController } from './expression-controller';\nimport { ExpressionList } from './expression-list';\n\nexport type CustomFunctionProps = {\n value?: ExpressionEntry[];\n onChange?: (value: ExpressionEntry[]) => void;\n defaultValue?: ExpressionEntry[];\n disabled?: boolean;\n permission?: 'edit:full' | 'edit:values' | 'view';\n /**\n * Deliberately opaque in public props: wasm/zod-typed shapes crash\n * Storybook docgen (SB_DOCS-TOOLS_0001). The component re-narrows them\n * internally before use.\n */\n inputVariableType?: unknown;\n debug?: unknown;\n hideCommandBar?: boolean;\n customFunctions?: any;\n functionScope?: unknown;\n};\nexport const CustomFunction: React.FC<CustomFunctionProps> = ({\n customFunctions,\n debug,\n hideCommandBar,\n inputVariableType,\n functionScope,\n ...props\n}) => {\n const sensors = useSensors(\n useSensor(PointerSensor, { activationConstraint: { distance: 4 } }),\n // Keyboard reorder: focus the row handle, Space/Enter to pick up, arrows to\n // move, Space/Enter to drop, Escape to cancel; the sortable coordinate\n // getter snaps arrow-moves to the neighbouring row.\n useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),\n );\n\n return (\n <ExpressionStoreProvider>\n <ExpressionDndBoard sensors={sensors}>\n <ExpressionController\n {...(props as ExpressionControllerProps)}\n functionScope={functionScope as FunctionScope | undefined}\n />\n {!hideCommandBar && <ExpressionCommandBar />}\n <ExpressionList customFunctions={customFunctions} functionScope={functionScope as FunctionScope | undefined} />\n <SimulateDataSync debug={debug} inputVariableType={inputVariableType} />\n </ExpressionDndBoard>\n </ExpressionStoreProvider>\n );\n};\n\ntype ExpressionDndBoardProps = {\n sensors: SensorDescriptor<SensorOptions>[];\n children: React.ReactNode;\n};\n\n/** DndContext 壳:必须在 ExpressionStoreProvider 内渲染——重排回调读写真实 store */\nconst ExpressionDndBoard: React.FC<ExpressionDndBoardProps> = ({ sensors, children }) => {\n const expressionStoreRaw = useExpressionStoreRaw();\n\n // 拖拽中实时重排(roadmap 3.2 落点修正):items 随 over 即时更新,\n // 后续箭头移动基于新排列计算——落点确定,不再依赖拖放瞬间的投影推算\n const reorderLive = ({ active, over }: DragEndEvent | DragOverEvent) => {\n if (!over) {\n return;\n }\n\n const from = active.data.current?.index;\n const to = over.data.current?.index;\n if (from === undefined || to === undefined || from === to) {\n return;\n }\n\n expressionStoreRaw.getState().moveRows(from, to);\n };\n\n return (\n <DndContext\n sensors={sensors}\n // rows reorder mid-drag, so droppable rects must be re-measured\n measuring={{ droppable: { strategy: MeasuringStrategy.Always } }}\n // 垂直列表标准碰撞检测(行高内容驱动、不固定,closestCorners 在此不稳)\n collisionDetection={closestCenter}\n onDragOver={reorderLive}\n onDragEnd={reorderLive}\n >\n {children}\n </DndContext>\n );\n};\n\nconst SimulateDataSync: React.FC<Pick<CustomFunctionProps, 'debug' | 'inputVariableType'>> = ({\n debug: debugUnknown,\n inputVariableType,\n}) => {\n const debug = debugUnknown as ExpressionStore['debug'];\n const expressionStoreRaw = useExpressionStoreRaw();\n\n useEffect(() => {\n expressionStoreRaw.setState({ inputVariableType: inputVariableType as VariableType | undefined });\n }, [inputVariableType]);\n\n useEffect(() => {\n const currentState = expressionStoreRaw.getState();\n if (equal(currentState.debug, debug)) {\n return;\n }\n\n expressionStoreRaw.setState({ debug });\n }, [debug]);\n\n useEffect(() => {\n if (!isWasmAvailable()) {\n return;\n }\n\n const isLoop = (store: ExpressionStore) => {\n return store.debug?.snapshot.executionMode === 'loop';\n };\n\n const applyDebug = (state: ExpressionStore) => {\n const inputData = state.debug?.inputData;\n if (!inputData) {\n return;\n }\n\n const varInputData = new Variable(inputData.data);\n if (isLoop(state)) {\n let newInputData = varInputData.get(state.debugIndex).cloneWith('$nodes', inputData.$nodes);\n if (inputData.$) {\n newInputData = newInputData.cloneWith('$', inputData.$);\n }\n\n expressionStoreRaw.setState({\n calculatedInputData: newInputData,\n inputVariableType: VariableType.fromVariable(newInputData),\n });\n } else {\n let newInputData = varInputData.cloneWith('$nodes', inputData.$nodes);\n if (inputData.$) {\n newInputData = newInputData.cloneWith('$', inputData.$);\n }\n\n expressionStoreRaw.setState({\n calculatedInputData: newInputData,\n inputVariableType: VariableType.fromVariable(newInputData),\n });\n }\n };\n\n applyDebug(expressionStoreRaw.getState());\n return expressionStoreRaw.subscribe((state, prevState) => {\n if (state.debugIndex === prevState.debugIndex && state.debug === prevState.debug) {\n return;\n }\n\n applyDebug(state);\n });\n }, []);\n\n return null;\n};\n","import React, { useMemo } from 'react';\nimport { P, match } from 'ts-pattern';\nimport type { z } from 'zod';\n\nimport { resolveFunctionScope } from '../../../helpers/custom-function-schema';\nimport type { GetNodeDataResult } from '../../../helpers/node-data';\nimport { getNodeData } from '../../../helpers/node-data';\nimport { useNodeType } from '../../../helpers/node-type';\nimport type { customNodeSchema } from '../../../helpers/schema';\nimport { get, toOperatorExprArray } from '../../../helpers/utility';\nimport { isWasmAvailable } from '../../../helpers/wasm';\nimport { CustomFunction } from '../../custom-function-table';\nimport type { ExpressionPermission } from '../../custom-function-table/context/expression-store.context';\nimport { useDecisionGraphActions, useDecisionGraphState } from '../context/dg-store.context';\nimport type { SimulationTrace, SimulationTraceDataExpression } from '../simulator/simulation.types';\n\nexport type TabCustomFunctionProps = {\n id: string;\n user?: string;\n customFunctions?: any;\n};\n\nexport const CustomFunctionTable: React.FC<TabCustomFunctionProps> = ({ id, user, customFunctions }) => {\n const graphActions = useDecisionGraphActions();\n const nodeType = useNodeType(id, { attachGlobals: false });\n const { disabled, content, globalType } = useDecisionGraphState(({ disabled, decisionGraph, globalType }) => ({\n disabled,\n content: (decisionGraph?.nodes ?? []).find((node) => node.id === id)?.content,\n globalType,\n }));\n\n const { nodeTrace, inputData, nodeSnapshot, viewConfig } = useDecisionGraphState(\n ({ simulate, decisionGraph, viewConfig }) => ({\n nodeTrace: match(simulate)\n .with(\n { result: P.nonNullable },\n ({ result }) => result.trace[id] as SimulationTrace<SimulationTraceDataExpression>,\n )\n .otherwise(() => null),\n inputData: match(simulate)\n .with({ result: P.nonNullable }, ({ result }) => getNodeData(id, { trace: result.trace, decisionGraph }))\n .otherwise(() => null),\n nodeSnapshot: match(simulate)\n .with(\n { result: P.nonNullable },\n ({ result }) =>\n result.snapshot?.nodes?.find((n) => n.id === id)?.content as z.infer<typeof customNodeSchema>['content'],\n )\n .otherwise(() => null),\n viewConfig,\n }),\n );\n\n const functionScope = useMemo(\n () => resolveFunctionScope((content as { kind?: string } | undefined)?.kind, customFunctions),\n [content?.kind, customFunctions],\n );\n\n const inputVariableType = useMemo(() => {\n if (!nodeType) {\n return undefined;\n }\n\n let scopedType = nodeType.clone();\n if (content?.config?.inputField) {\n scopedType = scopedType.calculateType(content.config.inputField);\n }\n\n if (content?.config?.executionMode === 'loop') {\n scopedType = scopedType.arrayItem();\n }\n\n Object.entries(globalType ?? {}).forEach(([key, value]) => scopedType.set(key, value));\n\n return scopedType;\n }, [nodeType, content?.config?.inputField, content?.config?.executionMode, globalType]);\n\n const debug = useMemo(() => {\n if (!nodeTrace || !inputData || !nodeSnapshot) {\n return undefined;\n }\n\n if (!isWasmAvailable()) {\n return { trace: nodeTrace, snapshot: nodeSnapshot.config };\n }\n\n const $data = Object.fromEntries(\n Object.entries(nodeTrace.traceData || {}).map(([k, v]) => [k, safeJson(v.result)]),\n );\n const extendedInputData: GetNodeDataResult = {\n ...inputData,\n $: $data,\n };\n\n if (content?.config?.inputField) {\n extendedInputData.data = get(extendedInputData.data, content.config.inputField, {});\n }\n\n return { trace: nodeTrace, inputData: extendedInputData, snapshot: nodeSnapshot.config };\n }, [nodeTrace, nodeSnapshot, inputData]);\n\n return (\n <div style={{ height: '100%', overflowY: 'auto', boxSizing: 'border-box' }}>\n <CustomFunction\n value={content?.config?.expressions}\n disabled={disabled}\n permission={(viewConfig?.enabled ? viewConfig?.permissions?.[id] : 'edit:full') as ExpressionPermission}\n customFunctions={customFunctions}\n functionScope={functionScope}\n debug={debug as any}\n inputVariableType={inputVariableType}\n onChange={(val: any) => {\n graphActions.updateNode(id, (draft) => {\n draft.content.config.expressions = val;\n\n draft.content.config.expr_asts = (val ?? []).map((expr: any) => ({\n id: expr?.id,\n key: expr?.key,\n value: expr?.value ? toOperatorExprArray(expr.value) : [''],\n }));\n\n draft.content.config.meta = {\n user: user ?? '',\n proj: user ?? '',\n };\n return draft;\n });\n }}\n />\n </div>\n );\n};\n\nconst safeJson = (data: string): unknown => {\n try {\n return JSON.parse(data);\n } catch {\n return null;\n }\n};\n","import React from 'react';\n\nimport { SafeBoundary } from '../../safe-boundary';\nimport { useDecisionGraphState } from '../context/dg-store.context';\n\n/**\n * 工具栏注入项(S005 P1 中性锚点,皮肤无感知):\n * 渲染在页签条右端(原生操作之后),group 变化处出现分隔线。\n * 宿主/皮肤注入建议 host: 前缀 id(kernel 不强制,appshell 映射层校验)。\n */\nexport type ToolbarItem = {\n /** 全局唯一 */\n id: string;\n /**\n * 语义分组;组变化处渲染分隔线。保留组名:'export' | 'simulate';\n * 缺省 = 独立组(最右分隔线后)。\n */\n group?: string;\n /** 组内排序 hint,缺省 0;同 hint 按数组序稳定排序 */\n order?: number;\n /** 惰性渲染;disabled 随画布态传入 */\n render: (ctx: { disabled: boolean }) => React.ReactNode;\n};\n\n/** 组间按首次出现序,组内按 order 后数组序(稳定排序) */\nexport const clusterToolbarItems = (items: ToolbarItem[]): ToolbarItem[] => {\n const buckets: { group: string; items: ToolbarItem[] }[] = [];\n for (const item of items) {\n const group = item.group ?? '';\n let bucket = buckets.find((b) => b.group === group);\n if (!bucket) {\n bucket = { group, items: [] };\n buckets.push(bucket);\n }\n bucket.items.push(item);\n }\n return buckets.flatMap((bucket) =>\n bucket.items\n .map((item, index) => ({ item, index }))\n .sort((a, b) => (a.item.order ?? 0) - (b.item.order ?? 0) || a.index - b.index)\n .map(({ item }) => item),\n );\n};\n\n/** render 调用必须发生在边界内部子组件——ErrorBoundary 捕获不到自身 render 期的抛错 */\nconst SlotRenderer: React.FC<{ item: ToolbarItem; disabled: boolean }> = ({ item, disabled }) => {\n return <>{item.render({ disabled })}</>;\n};\n\n/**\n * 工具栏锚点:无注入项时渲染 null(零开销,见 docs/design/skin-layout-slots.md §6-1);\n * 每个注入项独立 SafeBoundary——槽位抛错降级为该槽位不渲染,不拖垮编辑器。\n */\nexport const ToolbarAnchor: React.FC<{ items?: ToolbarItem[] }> = ({ items }) => {\n const { disabled = false } = useDecisionGraphState(({ disabled }) => ({ disabled }));\n\n if (!items || items.length === 0) {\n return null;\n }\n\n const clustered = clusterToolbarItems(items);\n const groups: string[] = [];\n for (const item of clustered) {\n if (!groups.includes(item.group ?? '')) groups.push(item.group ?? '');\n }\n\n return (\n <div aria-label='toolbar-items' className='ml-1 flex items-center gap-1 border-l border-[var(--border)] pl-2'>\n {groups.map((group, gi) => (\n <React.Fragment key={group || `__anonymous_${gi}`}>\n {gi > 0 && <span aria-hidden className='mx-1 h-4 w-px bg-[var(--border)]' />}\n {clustered\n .filter((item) => (item.group ?? '') === group)\n .map((item) => (\n <SafeBoundary\n key={item.id}\n fallback={null}\n onError={(error) => console.error(`[jdm-editor] toolbar item \"${item.id}\" crashed:`, error)}\n >\n <SlotRenderer item={item} disabled={disabled} />\n </SafeBoundary>\n ))}\n </React.Fragment>\n ))}\n </div>\n );\n};\n","import type { ProOptions } from '@xyflow/react';\nimport '@xyflow/react/dist/style.css';\nimport clsx from 'clsx';\nimport React, { forwardRef, useEffect, useRef, useState } from 'react';\nimport { match } from 'ts-pattern';\n\nimport { useDecisionGraphRaw, useDecisionGraphState } from './context/dg-store.context';\nimport { GraphPanel } from './dg-panel';\nimport type { UserResolver } from './dg-types';\nimport type { GraphRef } from './graph/graph';\nimport { Graph } from './graph/graph';\nimport { GraphNodes } from './graph/graph-nodes';\nimport { GraphSideToolbar } from './graph/graph-side-toolbar';\nimport type { GraphTabsProps } from './graph/graph-tabs';\nimport { GraphTabs } from './graph/graph-tabs';\nimport { CustomFunctionTable } from './graph/tab-custom-function-table';\nimport type { ToolbarItem } from './graph/toolbar-anchor';\nimport { ToolbarAnchor } from './graph/toolbar-anchor';\nimport { decisionTableSpecification } from './nodes/specifications/decision-table.specification';\nimport { expressionSpecification } from './nodes/specifications/expression.specification';\nimport { functionSpecification } from './nodes/specifications/function.specification';\nimport { inputSpecification } from './nodes/specifications/input.specification';\nimport { outputSpecification } from './nodes/specifications/output.specification';\nimport { NodeKind } from './nodes/specifications/specification-types';\n\nexport type DecisionGraphWrapperProps = {\n reactFlowProOptions?: ProOptions;\n tabBarExtraContent?: GraphTabsProps['tabBarExtraContent'];\n /**\n * 工具栏注入项(S005 P1):渲染在页签条右端、原生操作之后,group 变化处\n * 出现分隔线。无注入项时零渲染(与不传完全一致)。\n */\n toolbarItems?: ToolbarItem[];\n userResolver?: UserResolver;\n customFunctions?: any;\n};\n\nconst ResolveUserEffect: React.FC<{ userResolver?: UserResolver }> = ({ userResolver }) => {\n const { stateStore } = useDecisionGraphRaw();\n\n useEffect(() => {\n if (!userResolver) {\n return;\n }\n\n let cancelled = false;\n (async () => {\n try {\n const result = await userResolver();\n if (!cancelled && result) {\n stateStore.setState({ user: result.user ?? '' });\n }\n } catch (err) {\n console.warn('[jdm-editor] userResolver failed:', err);\n if (!cancelled) {\n stateStore.setState({ user: '' });\n }\n }\n })();\n\n return () => {\n cancelled = true;\n };\n }, [userResolver]);\n\n return null;\n};\n\nexport const DecisionGraphWrapper = React.memo(\n forwardRef<GraphRef, DecisionGraphWrapperProps>(function DecisionGraphWrapperInner(\n { reactFlowProOptions, tabBarExtraContent, toolbarItems, userResolver, customFunctions },\n ref,\n ) {\n const [disableTabs, setDisableTabs] = useState(false);\n const { hasActiveNode, viewConfig, hideLeftToolbar } = useDecisionGraphState(\n ({ decisionGraph, activeTab, viewConfig, hideLeftToolbar }) => {\n return {\n hasActiveNode: (decisionGraph?.nodes ?? []).some((node) => node.id === activeTab),\n viewConfig,\n hideLeftToolbar,\n };\n },\n );\n\n // 无注入项时保持原 tabBarExtraContent 引用不变——零注入零 DOM 差异\n const tabsExtra =\n toolbarItems && toolbarItems.length > 0 ? (\n <>\n {tabBarExtraContent}\n <ToolbarAnchor items={toolbarItems} />\n </>\n ) : (\n tabBarExtraContent\n );\n\n return (\n <>\n <ResolveUserEffect userResolver={userResolver} />\n {!hideLeftToolbar && <GraphSideToolbar />}\n <div className={'[grid-area:graph] flex flex-1 flex-col gap-1 overflow-hidden bg-white'}>\n <GraphTabs disabled={disableTabs} tabBarExtraContent={tabsExtra} />\n\n <Graph\n ref={ref}\n className={clsx([!hasActiveNode && !viewConfig?.enabled && 'flex flex-col', hasActiveNode && 'hidden'])}\n reactFlowProOptions={reactFlowProOptions}\n onDisableTabs={setDisableTabs}\n />\n <GraphNodes className={clsx([!hasActiveNode && viewConfig?.enabled && 'flex flex-col'])} />\n <TabContents customFunctions={customFunctions} />\n </div>\n <GraphPanel />\n </>\n );\n }),\n);\n\nconst TabContents: React.FC<{ customFunctions?: any }> = React.memo(({ customFunctions }) => {\n const { openNodes, activeNodeId, components, user, customNodes } = useDecisionGraphState(\n ({ decisionGraph, openTabs, activeTab, components, user, customNodes }) => {\n const activeNodeId = (decisionGraph?.nodes ?? []).find((node) => node.id === activeTab)?.id;\n const openNodes = (decisionGraph?.nodes ?? []).filter((node) => openTabs.includes(node.id));\n\n return {\n openNodes: openNodes.map(({ id, type, content }) => ({\n id,\n type,\n kind: (content as { kind?: unknown } | undefined)?.kind,\n })),\n activeNodeId,\n components,\n user,\n customNodes,\n };\n },\n );\n\n const containerRef = useRef<HTMLDivElement>(null);\n\n return (\n <div style={{ display: 'contents' }} ref={containerRef}>\n {openNodes.map((node) => (\n <div\n key={node?.id}\n className={clsx([\n 'relative h-full w-full flex-1 min-h-0 bg-[var(--grl-color-bg-container)] outline-none focus:outline-none focus-within:outline-none',\n activeNodeId === node?.id ? 'flex flex-col' : 'hidden',\n ])}\n >\n {match(node?.type)\n .with(NodeKind.DecisionTable, () => decisionTableSpecification?.renderTab?.({ id: node?.id, user }))\n .with(NodeKind.Function, () => functionSpecification?.renderTab?.({ id: node?.id, user }))\n .with(NodeKind.Expression, () => expressionSpecification?.renderTab?.({ id: node?.id, user }))\n .with(NodeKind.Input, () => inputSpecification?.renderTab?.({ id: node?.id, user }))\n .with(NodeKind.Output, () => outputSpecification?.renderTab?.({ id: node?.id, user }))\n\n .otherwise(() => {\n const component = components.find((cmp) => cmp.type === node.type);\n if (component) {\n return component?.renderTab?.({ id: node.id, user, customFunctions });\n }\n\n const kind = (node as { kind?: unknown })?.kind;\n if (kind) {\n const customSpec = customNodes?.find((n) => n.kind === kind);\n if (customSpec?.renderTab) {\n return customSpec.renderTab({ id: node.id, user, customFunctions });\n }\n // 无自定义 renderTab 的 kind 节点(容器/旧版 UDF)回退到\n // 自定义函数表格——与 zrule 行为一致\n return <CustomFunctionTable id={node.id} user={user} customFunctions={customFunctions} />;\n }\n\n return null;\n })}\n </div>\n ))}\n </div>\n );\n});\n","import { ReactFlowProvider } from '@xyflow/react';\nimport clsx from 'clsx';\nimport { forwardRef } from 'react';\n\nimport { SafeBoundary } from '../safe-boundary';\nimport type { DecisionGraphContextProps } from './context/dg-store.context';\nimport { DecisionGraphProvider } from './context/dg-store.context';\nimport { SerializerProvider } from './context/serializer.context';\nimport type { DecisionGraphEmptyType } from './dg-empty';\nimport { DecisionGraphEmpty } from './dg-empty';\nimport { DecisionGraphInferTypes } from './dg-infer';\nimport type { DecisionGraphWrapperProps } from './dg-wrapper';\nimport { DecisionGraphWrapper } from './dg-wrapper';\nimport type { GraphRef } from './graph/graph';\n\nexport type DecisionGraphProps = {} & DecisionGraphWrapperProps & DecisionGraphContextProps & DecisionGraphEmptyType;\n\nexport type DecisionGraphRef = GraphRef;\n\nexport const DecisionGraph = forwardRef<DecisionGraphRef, DecisionGraphProps>(\n ({ reactFlowProOptions, tabBarExtraContent, toolbarItems, userResolver, ...props }, ref) => {\n return (\n <SafeBoundary>\n <div className={clsx(['grl-dg', props?.hideLeftToolbar && 'hidden-left-toolbar'])}>\n <ReactFlowProvider>\n <DecisionGraphProvider>\n <SerializerProvider>\n <DecisionGraphWrapper\n ref={ref}\n reactFlowProOptions={reactFlowProOptions}\n tabBarExtraContent={tabBarExtraContent}\n toolbarItems={toolbarItems}\n userResolver={userResolver}\n customFunctions={props.customFunctions}\n />\n <DecisionGraphInferTypes />\n <DecisionGraphEmpty {...props} />\n </SerializerProvider>\n </DecisionGraphProvider>\n </ReactFlowProvider>\n </div>\n </SafeBoundary>\n );\n },\n);\n","import { DownOutlined } from '#icons';\nimport { type VariableType } from '@gorules/zen-engine-wasm';\nimport type { XYPosition } from '@xyflow/react';\nimport React, { useState } from 'react';\nimport { match } from 'ts-pattern';\n\nimport { useT } from '../../../../theming/i18n';\nimport { CodeEditor } from '../../../code-editor';\nimport { Button, Checkbox, Form, Typography } from '../../../primitives';\nimport { useDecisionGraphActions, useDecisionGraphState } from '../../context/dg-store.context';\nimport { type DecisionNode } from '../../dg-types';\nimport { GraphNode } from '../graph-node';\nimport type { InferTypeData, MinimalNodeProps, MinimalNodeSpecification } from '../specifications/specification-types';\n\ntype CustomDecisionNode<T> = {\n id: string;\n name: string;\n description?: string;\n type?: string;\n content?: T;\n position: XYPosition;\n};\n\ntype GenerateNodeParams = {\n index: number;\n};\n\nexport type CustomNodeSpecification<Data extends object, Component extends string> = {\n kind: Component;\n color?: string;\n icon?: React.ReactNode;\n displayName: string;\n group?: string;\n documentationUrl?: string;\n shortDescription?: string;\n renderTab?: (props: { id: string; user?: string; customFunctions?: any }) => React.ReactNode;\n calculateDiff?: (current: any, previous: any) => [any, any];\n generateNode: (params: GenerateNodeParams) => Omit<DecisionNode, 'position' | 'id' | 'type' | 'content'> & {\n config?: Data;\n };\n renderNode: React.FC<MinimalNodeProps & { specification: MinimalNodeSpecification }>;\n\n inferTypes?: {\n needsUpdate: (state: InferTypeData<Data>, prevState: InferTypeData<Data>) => boolean;\n determineOutputType: (state: InferTypeData<Data>) => VariableType;\n };\n\n onNodeAdd?: (node: CustomDecisionNode<{ kind: Component; config: Data }>) => Promise<\n CustomDecisionNode<{\n kind: Component;\n config: Data;\n }>\n >;\n};\n\ntype BoolInput = {\n control: 'bool';\n label?: string;\n};\n\ntype TextInput = {\n control: 'text';\n label?: string;\n};\n\ntype InputTypeMap = {\n bool: boolean;\n text: string;\n};\n\ntype InputSchema<Name extends string> = {\n name: Name;\n} & (BoolInput | TextInput);\n\ntype ControlToType<T> = T extends keyof InputTypeMap ? InputTypeMap[T] : never;\n\ntype SplitPath<Path extends string, Obj> = Path extends `${infer Prefix}.${infer Rest}`\n ? { [K in Prefix]: SplitPath<Rest, Obj> }\n : { [K in Path]: Obj };\n\ntype CreateDynamicType<T extends ReadonlyArray<unknown>, Result = {}> = T extends readonly [infer First, ...infer Rest]\n ? First extends { control: infer Control extends string; name: infer Name extends string }\n ? CreateDynamicType<Rest, Result & SplitPath<Name, ControlToType<Control>>>\n : Result\n : Result;\n\nexport type BaseNode<\n Component extends string,\n InputName extends string,\n Inputs extends InputSchema<InputName>[],\n NodeData extends object = CreateDynamicType<Inputs>,\n> = {\n kind: Component;\n icon?: React.ReactNode;\n color?: string;\n displayName: string;\n shortDescription?: string;\n group?: string;\n handleLeft?: boolean;\n handleRight?: boolean;\n inputs?: [...Inputs];\n generateNode?: CustomNodeSpecification<NodeData, Component>['generateNode'];\n renderNode?: CustomNodeSpecification<NodeData, Component>['renderNode'];\n onNodeAdd?: CustomNodeSpecification<NodeData, Component>['onNodeAdd'];\n};\n\nexport const createJdmNode = <\n Component extends string,\n InputName extends string,\n Inputs extends InputSchema<InputName>[],\n>(\n n: BaseNode<Component, InputName, Inputs>,\n): CustomNodeSpecification<any, Component> => {\n return {\n kind: n.kind,\n icon: n.icon,\n color: n.color,\n displayName: n.displayName,\n group: n.group,\n shortDescription: n.shortDescription,\n generateNode:\n n.generateNode ||\n (({ index }) => ({\n name: `${n.kind || n.displayName}${index}`,\n })),\n onNodeAdd: n.onNodeAdd,\n renderNode: n.renderNode\n ? n.renderNode\n : ({ id, specification, data, selected }) => {\n const [open, setOpen] = useState(false);\n const t = useT();\n const { updateNode, openTab } = useDecisionGraphActions();\n const node = useDecisionGraphState((state) => (state.decisionGraph?.nodes || []).find((n) => n.id === id));\n const nodeData = node?.content?.config;\n return (\n <GraphNode\n id={id}\n specification={specification}\n name={data.name}\n isSelected={selected}\n noBodyPadding\n handleLeft={n.handleLeft}\n handleRight={n.handleRight}\n actions={[\n <Button key='edit-expression' type='text' onClick={() => openTab(id)}>\n {t('dg.node.editExpression')}\n </Button>,\n ...(n?.inputs\n ? [\n <Button\n key='edit-table'\n type='text'\n style={{ marginLeft: 'auto', transform: open ? 'rotate(180deg)' : undefined }}\n onClick={() => setOpen((o) => !o)}\n >\n <DownOutlined />\n </Button>,\n ]\n : []),\n ]}\n >\n {open && n?.inputs && (\n <Form\n className='p-2 text-xs [&_.grl-ce]:text-xs'\n layout='vertical'\n initialValues={nodeData}\n onValuesChange={(_, values) => {\n updateNode(id, (draft) => {\n draft.content.config = values;\n return draft;\n });\n }}\n >\n {(n?.inputs || []).map(({ name, control, label }) => {\n const formItem = match({ control })\n .with({ control: 'text' }, () => <CodeEditor type='template' />)\n .with({ control: 'bool' }, () => (\n <Checkbox>\n <Typography.Text style={{ fontSize: 12 }}>{label}</Typography.Text>\n </Checkbox>\n ))\n .exhaustive();\n\n const outerLabel = match({ control })\n .with({ control: 'bool' }, () => null)\n .otherwise(() => <Typography.Text style={{ fontSize: 12 }}>{label}</Typography.Text>);\n\n const valuePropName = match({ control })\n .with({ control: 'bool' }, () => 'checked')\n .otherwise(() => undefined);\n\n return (\n <Form.Item\n key={name}\n name={name as string}\n label={outerLabel}\n valuePropName={valuePropName}\n style={{\n marginBottom: 4,\n }}\n >\n {formItem}\n </Form.Item>\n );\n })}\n </Form>\n )}\n </GraphNode>\n );\n },\n };\n};\n","import { Editor } from '@monaco-editor/react';\nimport json5 from 'json5';\nimport React from 'react';\nimport { toast } from 'sonner';\n\nimport { copyToClipboard } from '../../../helpers/utility';\nimport { useThemeMode } from '../../../theme';\nimport { useT } from '../../../theming/i18n';\nimport { Spin } from '../../primitives';\n\ntype SimulatorEditorProps = {\n value?: string;\n onChange?: (value: string | undefined) => void;\n readOnly?: boolean;\n};\n\nexport const SimulatorEditor: React.FC<SimulatorEditorProps> = ({ value, onChange, readOnly }) => {\n const mode = useThemeMode();\n\n const t = useT();\n\n return (\n <Editor\n loading={<Spin size='large' />}\n language='javascript'\n value={value}\n onChange={onChange}\n theme={mode === 'dark' ? 'vs-dark' : 'light'}\n height='100%'\n onMount={(editor, monaco) => {\n monaco.languages.typescript.javascriptDefaults.setDiagnosticsOptions({\n noSyntaxValidation: true,\n });\n\n monaco.languages.typescript.javascriptDefaults.setModeConfiguration({\n codeActions: false,\n inlayHints: false,\n });\n\n editor.addAction({\n id: 'copy-json',\n label: t('dg.jsonSchema.copyJson'),\n contextMenuGroupId: 'utils',\n run: async (editor) => {\n try {\n await copyToClipboard(JSON.stringify(json5.parse(editor.getValue())));\n toast.success('Copied to clipboard!');\n } catch {\n toast.error('Failed to copy to clipboard.');\n }\n },\n });\n\n editor.addAction({\n id: 'format',\n label: 'Format',\n contextMenuGroupId: 'utils',\n precondition: '!editorReadonly',\n run: (editor) => {\n const formatted = JSON.stringify(json5.parse(editor.getValue()), null, 2);\n editor.setValue(formatted);\n },\n });\n }}\n options={{\n readOnly: readOnly,\n automaticLayout: true,\n minimap: { enabled: false },\n fontSize: 12,\n fontFamily: 'var(--mono-font-family)',\n tabSize: 2,\n lineDecorationsWidth: 2,\n find: {\n addExtraSpaceOnTop: false,\n seedSearchStringFromSelection: 'never',\n },\n scrollbar: {\n verticalSliderSize: 4,\n verticalScrollbarSize: 4,\n horizontalScrollbarSize: 4,\n horizontalSliderSize: 4,\n },\n lineNumbersMinChars: 3,\n }}\n />\n );\n};\n","export default function CheckCircleIcon({ className }: { className?: string }) {\n return (\n <svg\n width='24'\n height='24'\n viewBox='0 0 24 24'\n fill='none'\n xmlns='http://www.w3.org/2000/svg'\n className={className}\n >\n <path\n d='M12 2.43256C13.8923 2.43256 15.742 2.99368 17.3154 4.04496C18.8887 5.09625 20.115 6.59048 20.8392 8.3387C21.5633 10.0869 21.7528 12.0106 21.3836 13.8665C21.0144 15.7224 20.1032 17.4272 18.7652 18.7652C17.4272 20.1032 15.7224 21.0144 13.8665 21.3836C12.0106 21.7528 10.0869 21.5633 8.3387 20.8392C6.59048 20.115 5.09625 18.8887 4.04497 17.3154C2.99368 15.742 2.43256 13.8923 2.43256 12C2.43256 9.46255 3.44056 7.02904 5.2348 5.2348C7.02904 3.44055 9.46256 2.43256 12 2.43256ZM11.0484 13.5144L7.90698 10.3628C7.72346 10.1908 7.48305 10.0925 7.23163 10.0865C7.04278 10.0884 6.85866 10.1458 6.70222 10.2516C6.54579 10.3574 6.42397 10.5069 6.35195 10.6815C6.27993 10.8561 6.2609 11.0481 6.29724 11.2334C6.33358 11.4187 6.42367 11.5892 6.55628 11.7237L10.373 15.5507C10.5604 15.7176 10.8026 15.8097 11.0535 15.8097C11.3044 15.8097 11.5466 15.7176 11.734 15.5507L17.4642 9.81023C17.5968 9.67576 17.6869 9.50523 17.7232 9.3199C17.7596 9.13457 17.7405 8.94264 17.6685 8.76805C17.5965 8.59346 17.4747 8.44393 17.3182 8.33812C17.1618 8.23231 16.9777 8.17489 16.7888 8.17302C16.5374 8.17899 16.297 8.27735 16.1135 8.4493L11.0586 13.5656M12 1C9.82441 1 7.69767 1.64514 5.88873 2.85383C4.07979 4.06253 2.66989 5.78049 1.83733 7.79048C1.00477 9.80047 0.786929 12.0122 1.21137 14.146C1.6358 16.2798 2.68345 18.2398 4.22183 19.7782C5.76021 21.3165 7.72022 22.3642 9.85401 22.7886C11.9878 23.2131 14.1995 22.9952 16.2095 22.1627C18.2195 21.3301 19.9375 19.9202 21.1462 18.1113C22.3549 16.3023 23 14.1756 23 12C22.9973 9.08345 21.8375 6.28713 19.7752 4.22482C17.7129 2.1625 14.9166 1.00271 12 1Z'\n fill='currentColor'\n />\n </svg>\n );\n}\n","export default function CrossCircleIcon({ className }: { className?: string }) {\n return (\n <svg\n width='24'\n height='24'\n viewBox='0 0 24 24'\n fill='none'\n xmlns='http://www.w3.org/2000/svg'\n className={className}\n >\n <path\n d='M12 2.43256C13.8923 2.43256 15.742 2.99368 17.3154 4.04496C18.8887 5.09625 20.115 6.59048 20.8392 8.3387C21.5633 10.0869 21.7528 12.0106 21.3836 13.8665C21.0144 15.7224 20.1032 17.4272 18.7652 18.7652C17.4272 20.1032 15.7224 21.0144 13.8665 21.3836C12.0106 21.7528 10.0869 21.5633 8.3387 20.8392C6.59048 20.115 5.09625 18.8887 4.04497 17.3154C2.99368 15.742 2.43256 13.8923 2.43256 12C2.43256 9.46255 3.44056 7.02904 5.2348 5.2348C7.02904 3.44055 9.46256 2.43256 12 2.43256ZM12 10.6186L9.29861 7.90698C9.10939 7.73149 8.86086 7.63398 8.60279 7.63398C8.34473 7.63398 8.0962 7.73149 7.90698 7.90698C7.7315 8.09619 7.63399 8.34473 7.63399 8.60279C7.63399 8.86085 7.7315 9.10939 7.90698 9.2986L10.6493 12L7.90698 14.7014C7.7315 14.8906 7.63399 15.1391 7.63399 15.3972C7.63399 15.6553 7.7315 15.9038 7.90698 16.093C8.09437 16.2599 8.33653 16.3521 8.58744 16.3521C8.83836 16.3521 9.08052 16.2599 9.26791 16.093L12 13.3507L14.7014 16.093C14.8906 16.2685 15.1391 16.366 15.3972 16.366C15.6553 16.366 15.9038 16.2685 16.093 16.093C16.2599 15.9056 16.3521 15.6635 16.3521 15.4126C16.3521 15.1616 16.2599 14.9195 16.093 14.7321L13.3507 12L16.093 9.2986C16.2685 9.10939 16.366 8.86085 16.366 8.60279C16.366 8.34473 16.2685 8.09619 16.093 7.90698C15.9056 7.74012 15.6635 7.64793 15.4126 7.64793C15.1616 7.64793 14.9195 7.74012 14.7321 7.90698L12 10.6493M12 1C9.82441 1 7.69767 1.64514 5.88873 2.85383C4.07979 4.06253 2.66989 5.78049 1.83733 7.79048C1.00477 9.80047 0.786929 12.0122 1.21137 14.146C1.6358 16.2798 2.68345 18.2398 4.22183 19.7782C5.76021 21.3165 7.72022 22.3642 9.85401 22.7886C11.9878 23.2131 14.1995 22.9952 16.2095 22.1627C18.2195 21.3301 19.9375 19.9202 21.1462 18.1113C22.3549 16.3023 23 14.1756 23 12C22.9973 9.08345 21.8375 6.28713 19.7752 4.22482C17.7129 2.1625 14.9166 1.00271 12 1Z'\n fill='currentColor'\n />\n </svg>\n );\n}\n","import { ClearOutlined } from '#icons';\nimport CheckCircleIcon from '#reui/icons/animated/outline/check-circle';\nimport CrossCircleIcon from '#reui/icons/animated/outline/cross-circle';\nimport clsx from 'clsx';\nimport React, { useMemo } from 'react';\nimport { P, match } from 'ts-pattern';\n\nimport { useT } from '../../../theming/i18n';\nimport { Button, Spin, Tooltip, Typography } from '../../primitives';\nimport type { ViewConfig } from '../context/dg-store.context';\nimport { NodeKind } from '../nodes/specifications/specification-types';\nimport type { Simulation, SimulationTrace } from './simulation.types';\n\ntype SimulatorNodesPanelStatus = 'success' | 'error' | 'not-run';\n\nexport type SimulatorNodesPanelProps = {\n search?: string;\n onSearchChange: (search: string) => void;\n loading?: boolean;\n simulate?: Simulation;\n nodeTypes?: Record<string, string | undefined>;\n viewConfig?: ViewConfig;\n selectedNode: string;\n onSelectNode: (nodeId: string) => void;\n onClear?: () => void;\n onGoToNode: (nodeId: string) => void;\n};\n\nexport const SimulatorNodesPanel: React.FC<SimulatorNodesPanelProps> = ({\n search,\n onSearchChange,\n loading = false,\n simulate,\n nodeTypes,\n viewConfig,\n selectedNode,\n onSelectNode,\n onClear,\n onGoToNode,\n}) => {\n const t = useT();\n\n const traces = useMemo<Array<SimulationTrace & { nodeId: string }>>(() => {\n if (!simulate) {\n return [];\n }\n\n if (!('result' in simulate)) {\n return [];\n }\n\n return Object.entries(simulate.result?.trace ?? {})\n .filter(([id]) => (viewConfig?.enabled ? !!viewConfig?.permissions?.[id] : true))\n .map(([key, data]) => ({ ...data, nodeId: key }))\n .filter((trace) => ![NodeKind.Input].includes(nodeTypes?.[trace.nodeId] as NodeKind))\n .filter((trace) => trace.name.toLowerCase().includes(search?.toLowerCase() ?? ''))\n .sort((a, b) => (a.order ?? 0) - (b.order ?? 0));\n }, [simulate, viewConfig, nodeTypes, search]);\n\n return (\n <React.Fragment>\n <div className='flex items-center justify-between gap-2 border-b border-border px-3 py-2'>\n <input\n className='h-7 w-full min-w-0 rounded-md border border-border bg-muted/40 px-2 text-xs outline-none focus:border-primary/50'\n type='text'\n placeholder={t('simulator.searchPlaceholder')}\n value={search}\n onChange={(event) => onSearchChange(event.target.value)}\n />\n <div className='flex shrink-0 items-center gap-1'>\n {onClear && (\n <Tooltip title={t('simulator.clear')} placement='bottomRight'>\n <Button size='small' type='text' icon={<ClearOutlined />} onClick={() => onClear?.()} />\n </Tooltip>\n )}\n </div>\n </div>\n <div className='min-h-0 flex-1 overflow-y-auto p-2'>\n <Spin spinning={loading}>\n <div className='flex flex-col gap-0.5'>\n {!simulate && (\n <Typography.Text type='secondary' className='mt-14 block text-center' style={{ fontSize: 13 }}>\n {t('simulator.readyTitle')}\n <br />\n {t('simulator.readyHint')}\n <br />\n <Typography.Link\n href='https://docs.gorules.io/docs/simulator'\n target='_blank'\n className='mt-1 inline-block'\n style={{ fontSize: 13 }}\n >\n {t('simulator.learnMore')}\n </Typography.Link>\n </Typography.Text>\n )}\n {'graph'.includes(search?.toLowerCase() ?? '') && simulate && (\n <div\n className={clsx(\n 'flex cursor-pointer items-center justify-between gap-2 rounded-md px-2 py-1.5 hover:bg-muted/60',\n selectedNode === 'graph' && 'bg-primary/10',\n )}\n onClick={() => onSelectNode('graph')}\n >\n <Typography.Text data-role='name' className='flex min-w-0 items-center [&>svg]:align-[-3px]'>\n <StatusIcon\n status={match(simulate)\n .with({ error: P.nonNullable }, () => 'error' as const)\n .with({ result: P.nonNullable }, () => 'success' as const)\n .otherwise(() => 'not-run' as const)}\n />\n <span className='truncate'>Graph</span>\n </Typography.Text>\n <Typography.Text type='secondary' data-role='performance'>\n {match(simulate)\n .with({ result: P._ }, ({ result }) => result?.performance)\n .otherwise(() => undefined)}\n </Typography.Text>\n </div>\n )}\n {traces.map((trace) => (\n <div\n key={trace.nodeId}\n className={clsx(\n 'flex cursor-pointer items-center justify-between gap-2 rounded-md px-2 py-1.5 hover:bg-muted/60',\n trace.nodeId === selectedNode && 'bg-primary/10',\n )}\n onClick={() => onSelectNode(trace.nodeId)}\n onDoubleClick={() => onGoToNode(trace.nodeId)}\n >\n <Typography.Text\n data-role='name'\n className='flex min-w-0 items-center [&>svg]:align-[-3px]'\n title={trace.name}\n >\n <StatusIcon status={trace.nodeId === simulate?.error?.data?.nodeId ? 'error' : 'success'} />\n <span className='truncate'>{trace.name}</span>\n </Typography.Text>\n <Typography.Text type='secondary' data-role='performance'>\n {trace.performance}\n </Typography.Text>\n </div>\n ))}\n </div>\n </Spin>\n </div>\n </React.Fragment>\n );\n};\n\nconst StatusIcon: React.FC<{ status: SimulatorNodesPanelStatus }> = ({ status }) => {\n if (status === 'not-run') {\n return null;\n }\n\n if (status === 'success') {\n return <CheckCircleIcon className='mr-1.5 size-3 shrink-0 text-[var(--grl-color-success)] opacity-60' />;\n }\n\n return <CrossCircleIcon className='mr-1 size-3 shrink-0 text-[var(--grl-color-error)]' />;\n};\n","import type { CSSProperties } from 'react';\n\nexport default function LinkIcon({ className, style }: { className?: string; style?: CSSProperties }) {\n return (\n <svg\n width='24'\n height='24'\n viewBox='0 0 24 24'\n fill='none'\n xmlns='http://www.w3.org/2000/svg'\n className={className}\n style={style}\n stroke='currentColor'\n strokeWidth='2'\n strokeLinecap='round'\n strokeLinejoin='round'\n >\n <path d='M9 17H7A5 5 0 0 1 7 7h2' />\n <path d='M15 7h2a5 5 0 1 1 0 10h-2' />\n <path d='M8 12h8' />\n </svg>\n );\n}\n","import { CopyOutlined, FormatPainterOutlined, PlayCircleOutlined } from '#icons';\nimport InformationIcon from '#reui/icons/animated/outline/information';\nimport LinkIcon from '#reui/icons/animated/outline/link';\nimport React from 'react';\n\nimport type { TranslationKey } from '../../../theming/i18n';\nimport { Button, Select, Tooltip, Typography } from '../../primitives';\n\nexport type SimulatorRequestToolbarProps = {\n t: (key: TranslationKey) => string;\n shouldShowSimulatorSourceSelect: boolean;\n boundRequestSourceIndex: number;\n sourceOptions: Array<{ value: number; label: string }>;\n bindingName?: string;\n hasInputNode?: boolean;\n loading?: boolean;\n onSourceChange: (sourceIndex: number) => void;\n onFormat: () => void;\n onCopy: () => void;\n onRun?: () => void;\n};\n\nexport const SimulatorRequestToolbar: React.FC<SimulatorRequestToolbarProps> = ({\n t,\n shouldShowSimulatorSourceSelect,\n boundRequestSourceIndex,\n sourceOptions,\n bindingName,\n hasInputNode,\n loading,\n onSourceChange,\n onFormat,\n onCopy,\n onRun,\n}) => {\n return (\n <div className='flex items-center justify-between gap-2 border-b border-border px-3 py-2'>\n <Tooltip title={t('simulator.description')}>\n <Typography.Text\n className='min-w-0 shrink cursor-help overflow-hidden text-ellipsis whitespace-nowrap'\n style={{ fontSize: 13 }}\n >\n {t('request')}\n <span className='ml-1 inline-flex align-super opacity-50 [&_svg]:block'>\n <InformationIcon className='size-2.5' />\n </span>\n </Typography.Text>\n </Tooltip>\n {shouldShowSimulatorSourceSelect && (\n <Tooltip title={t('simulator.currentBinding')}>\n <div className='flex min-w-0 items-center gap-1'>\n <LinkIcon className='size-3 shrink-0 text-[var(--muted-foreground)]' />\n <Select\n size='small'\n value={boundRequestSourceIndex}\n options={sourceOptions}\n popupMatchSelectWidth={false}\n onChange={onSourceChange}\n />\n </div>\n </Tooltip>\n )}\n {bindingName && !shouldShowSimulatorSourceSelect && (\n <Typography.Text type='secondary' className='flex min-w-0 items-center gap-1 text-xs'>\n <Tooltip title={t('simulator.currentBinding')}>\n <LinkIcon className='size-3 shrink-0 text-[var(--muted-foreground)]' />\n </Tooltip>\n <span className='truncate'>{bindingName}</span>\n </Typography.Text>\n )}\n <div className='flex shrink-0 items-center gap-1'>\n {onRun && (\n <React.Fragment>\n <Tooltip title={!hasInputNode ? t('simulator.nodeRequired') : undefined}>\n <Tooltip title={t('common.format')}>\n <Button size='small' type='text' shape='circle' icon={<FormatPainterOutlined />} onClick={onFormat} />\n </Tooltip>\n </Tooltip>\n <Tooltip title={t('dg.jsonSchema.copyJson')}>\n <Button size='small' type='text' shape='circle' icon={<CopyOutlined />} onClick={onCopy} />\n </Tooltip>\n <Tooltip title={t('simulator.run')}>\n <Button\n size='small'\n type='primary'\n shape='circle'\n loading={loading}\n icon={<PlayCircleOutlined />}\n disabled={!hasInputNode}\n onClick={onRun}\n />\n </Tooltip>\n </React.Fragment>\n )}\n </div>\n </div>\n );\n};\n","import json5 from 'json5';\nimport { toast } from 'sonner';\n\nimport {\n formatRequestExampleSourceName,\n getRequestDefinitions,\n getRequestExampleDataDefinitionConflicts,\n getRequestExampleSources,\n normalizeRequestExampleDataByDefinitions,\n resolveRequestSchemaValue,\n setRequestSchemaValue,\n updateRequestSchemaExamples,\n} from '../../../helpers/request-schema';\nimport type { TranslationKey } from '../../../theming/i18n';\nimport { type SimulatorExampleBinding, useDecisionGraphRaw } from '../context/dg-store.context';\n\nexport type RequestExampleBinding = NonNullable<SimulatorExampleBinding>;\n\nexport type UseRequestExamplePersistenceParams = {\n t: (key: TranslationKey) => string;\n requestValue: string | undefined;\n resolvedSimulatorExampleBinding: RequestExampleBinding | null;\n onRequestValueChange: (nextValue: string) => void;\n onMarkEdited: () => void;\n onExternalChange?: (nextValue: string) => void;\n};\n\nexport type PersistRequestToExampleSourceOptions = {\n silentWhenUnbound?: boolean;\n showSuccessMessage?: boolean;\n requestValueOverride?: string;\n silentOnError?: boolean;\n validateDefinitionTypes?: boolean;\n triggeredBy?: 'manual-save' | 'auto-sync';\n};\n\nexport const useRequestExamplePersistence = ({\n t,\n requestValue,\n resolvedSimulatorExampleBinding,\n onRequestValueChange,\n onMarkEdited,\n onExternalChange,\n}: UseRequestExamplePersistenceParams) => {\n const { stateStore, actions } = useDecisionGraphRaw();\n\n const savePreparedRequestToExampleSource = ({\n activeExampleBinding,\n preparedParsed,\n triggeredBy,\n showSuccessMessage = true,\n }: {\n activeExampleBinding: RequestExampleBinding;\n preparedParsed: Record<string, unknown>;\n triggeredBy: 'manual-save' | 'auto-sync';\n showSuccessMessage?: boolean;\n }) => {\n const { decisionGraph } = stateStore.getState();\n const targetNode = decisionGraph.nodes.find((node) => node.id === activeExampleBinding.nodeId);\n\n if (!targetNode) {\n toast.error(t('simulator.boundRequestNodeNotFound'));\n return null;\n }\n\n const currentSources = getRequestExampleSources(targetNode.content, { dataLabel: t('request.dataLabel') });\n const currentBoundSource = currentSources[activeExampleBinding.sourceIndex];\n const formatted = JSON.stringify(preparedParsed, null, 2);\n\n if (currentBoundSource && JSON.stringify(currentBoundSource.data) === JSON.stringify(preparedParsed)) {\n if (import.meta.env.DEV) {\n console.log('[simulator-request] skipped saving unchanged example source', {\n binding: activeExampleBinding,\n triggeredBy,\n });\n }\n\n if (showSuccessMessage) {\n toast.success(t('request.dataSourceSaved'));\n }\n\n return {\n context: preparedParsed,\n formatted,\n };\n }\n\n const nextSources = [...currentSources];\n\n while (nextSources.length <= activeExampleBinding.sourceIndex) {\n nextSources.push({\n id: crypto.randomUUID(),\n name: formatRequestExampleSourceName(nextSources.length, t('request.dataLabel')),\n data: {},\n source: 'schema.examples',\n });\n }\n\n nextSources[activeExampleBinding.sourceIndex] = {\n ...nextSources[activeExampleBinding.sourceIndex],\n id: nextSources[activeExampleBinding.sourceIndex]?.id ?? crypto.randomUUID(),\n name:\n activeExampleBinding.sourceName ??\n nextSources[activeExampleBinding.sourceIndex]?.name ??\n formatRequestExampleSourceName(activeExampleBinding.sourceIndex, t('request.dataLabel')),\n data: preparedParsed,\n source: 'schema.examples',\n };\n\n actions.updateNode(activeExampleBinding.nodeId, (draft) => {\n draft.content ??= {};\n if (draft.type === 'inputNode') {\n const currentSchema = resolveRequestSchemaValue(draft.content, { includeExamples: true });\n setRequestSchemaValue(\n draft.content as Record<string, any>,\n updateRequestSchemaExamples(\n currentSchema,\n nextSources.map((source) => source.data),\n ),\n );\n } else {\n draft.content.schema = updateRequestSchemaExamples(\n draft.content?.schema,\n nextSources.map((source) => source.data),\n );\n }\n return draft;\n });\n\n onRequestValueChange(formatted);\n onMarkEdited();\n onExternalChange?.(formatted);\n actions.setSimulatorRequest(formatted);\n actions.setSimulatorExampleBinding({\n ...activeExampleBinding,\n sourceName: nextSources[activeExampleBinding.sourceIndex]?.name,\n });\n\n if (import.meta.env.DEV) {\n console.log('[simulator-request] saved simulator request to bound example source', {\n binding: activeExampleBinding,\n preparedParsed,\n currentBoundSource,\n nextSources,\n triggeredBy,\n });\n }\n\n if (showSuccessMessage) {\n toast.success(t('request.dataSourceSaved'));\n }\n\n return {\n context: preparedParsed,\n formatted,\n };\n };\n\n const persistRequestToExampleSource = (options?: PersistRequestToExampleSourceOptions) => {\n const {\n silentWhenUnbound = false,\n showSuccessMessage = true,\n requestValueOverride,\n silentOnError = false,\n validateDefinitionTypes = false,\n triggeredBy = 'manual-save',\n } = options ?? {};\n\n const activeExampleBinding = resolvedSimulatorExampleBinding;\n\n if (!activeExampleBinding) {\n if (!silentWhenUnbound) {\n toast.warning(t('request.selectDataSourceFirst'));\n }\n return null;\n }\n\n try {\n const sourceRequestValue = requestValueOverride ?? requestValue;\n const parsed = (sourceRequestValue || '').trim().length === 0 ? {} : json5.parse(sourceRequestValue || '{}');\n\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n if (!silentOnError) {\n toast.error(t('simulator.requestMustBeObjectToSave'));\n }\n return null;\n }\n\n const { decisionGraph } = stateStore.getState();\n const targetNode = decisionGraph.nodes.find((node) => node.id === activeExampleBinding.nodeId);\n\n if (!targetNode) {\n if (!silentOnError) {\n toast.error(t('simulator.boundRequestNodeNotFound'));\n }\n return null;\n }\n\n const requestDefinitions = getRequestDefinitions(targetNode.content);\n const parsedRecord = parsed as Record<string, unknown>;\n const definitionTypeConflicts = validateDefinitionTypes\n ? getRequestExampleDataDefinitionConflicts(parsedRecord, requestDefinitions)\n : [];\n\n if (definitionTypeConflicts.length > 0) {\n if (!silentOnError) {\n toast.warning(t('request.dataTypeMismatchWarning'));\n }\n return null;\n }\n\n const preparedParsed = normalizeRequestExampleDataByDefinitions(parsedRecord, requestDefinitions);\n\n return savePreparedRequestToExampleSource({\n activeExampleBinding,\n preparedParsed,\n triggeredBy,\n showSuccessMessage,\n });\n } catch (error) {\n if (import.meta.env.DEV) {\n console.warn('[simulator-request] failed to save simulator request to example source', {\n binding: activeExampleBinding,\n requestValue,\n error,\n triggeredBy,\n });\n }\n\n if (!silentOnError) {\n toast.error(t('request.saveDataSourceFailed'));\n }\n return null;\n }\n };\n\n return {\n persistRequestToExampleSource,\n };\n};\n","import { useEffect, useRef } from 'react';\n\nexport const AUTO_SYNC_DEBOUNCE_MS = 700;\n\nexport type UseSimulatorAutoSyncParams = {\n /** 绑定解析成功且存在 input 节点时启用 */\n enabled: boolean;\n /** 编辑器当前内容 */\n requestValue: string | undefined;\n /** schema.examples 当前序列化签名(外部变更检测) */\n requestSourcesSignature: string;\n /** 命中绑定源下标;<0 表示无可绑定源 */\n boundRequestSourceIndex: number;\n /** 编辑器内容持久化到 schema.examples(含类型归一,静默) */\n onSyncToSchema: () => void;\n /** schema 侧数据推送到编辑器(外部编辑反写) */\n onPushToEditor: () => void;\n /** 防抖时长(默认 700ms;测试注入短时长) */\n debounceMs?: number;\n};\n\n/**\n * Simulator 用例数据双向自动同步:\n * - 编辑器变更(去抖,静默)→ onSyncToSchema\n * - schema.examples 外部变更(签名守卫防回灌)→ onPushToEditor\n * - flush():源切换/卸载前冲刷未落盘编辑\n */\nexport const useSimulatorAutoSync = ({\n enabled,\n requestValue,\n requestSourcesSignature,\n boundRequestSourceIndex,\n onSyncToSchema,\n onPushToEditor,\n debounceMs = AUTO_SYNC_DEBOUNCE_MS,\n}: UseSimulatorAutoSyncParams) => {\n const pendingAutoSyncRef = useRef<number | null>(null);\n const lastAutoSyncedRequestRef = useRef<string | undefined>(undefined);\n const requestValueRef = useRef(requestValue);\n requestValueRef.current = requestValue;\n const lastPushedSourcesSignatureRef = useRef<string | undefined>(undefined);\n const callbacksRef = useRef({ onSyncToSchema, onPushToEditor });\n callbacksRef.current = { onSyncToSchema, onPushToEditor };\n\n /** 冲刷未落盘编辑(源切换前调用,以当前编辑器内容立即持久化) */\n const flush = () => {\n if (pendingAutoSyncRef.current === null) {\n return;\n }\n window.clearTimeout(pendingAutoSyncRef.current);\n pendingAutoSyncRef.current = null;\n lastAutoSyncedRequestRef.current = requestValueRef.current;\n callbacksRef.current.onSyncToSchema();\n };\n\n // 编辑器 → schema(去抖,静默)\n useEffect(() => {\n if (!enabled) {\n return;\n }\n if (requestValue === lastAutoSyncedRequestRef.current) {\n return;\n }\n if (pendingAutoSyncRef.current !== null) {\n window.clearTimeout(pendingAutoSyncRef.current);\n }\n pendingAutoSyncRef.current = window.setTimeout(() => {\n pendingAutoSyncRef.current = null;\n lastAutoSyncedRequestRef.current = requestValueRef.current;\n callbacksRef.current.onSyncToSchema();\n }, debounceMs);\n return () => {\n if (pendingAutoSyncRef.current !== null) {\n window.clearTimeout(pendingAutoSyncRef.current);\n pendingAutoSyncRef.current = null;\n }\n };\n }, [debounceMs, enabled, requestValue]);\n\n // schema → 编辑器(签名守卫防回灌)\n useEffect(() => {\n if (!enabled) {\n return;\n }\n if (requestSourcesSignature === lastPushedSourcesSignatureRef.current) {\n return;\n }\n lastPushedSourcesSignatureRef.current = requestSourcesSignature;\n if (boundRequestSourceIndex >= 0) {\n callbacksRef.current.onPushToEditor();\n }\n }, [boundRequestSourceIndex, enabled, requestSourcesSignature]);\n\n return { flush };\n};\n","import { useMemo } from 'react';\n\nimport { getRequestDefinitions, getRequestExampleSources } from '../../../helpers/request-schema';\nimport type { RequestContentLike, RequestDefinition, RequestExampleSource } from '../../../helpers/request-schema';\nimport type { SimulatorExampleBinding } from '../context/dg-store.context';\n\nexport type ResolvedSimulatorExampleBinding = {\n nodeId: string;\n sourceIndex: number;\n sourceName?: string;\n};\n\nexport type UseSimulatorRequestBindingParams = {\n inputNodeContent?: unknown;\n inputNodeId?: string;\n simulatorExampleBinding?: SimulatorExampleBinding | null;\n dataLabel?: string;\n};\n\nexport type SimulatorRequestBinding = {\n requestSources: RequestExampleSource[];\n boundRequestSourceIndex: number;\n defaultRequestSourceIndex: number;\n defaultRequestSource?: RequestExampleSource;\n resolvedSimulatorExampleBinding: ResolvedSimulatorExampleBinding | null;\n currentBindingIdentity: string | null;\n requestDefinitions: RequestDefinition[];\n sourceOptions: Array<{ value: number; label: string }>;\n bindingName?: string;\n shouldShowSimulatorSourceSelect: boolean;\n};\n\nexport const useSimulatorRequestBinding = ({\n inputNodeContent,\n inputNodeId,\n simulatorExampleBinding,\n dataLabel = 'Data',\n}: UseSimulatorRequestBindingParams): SimulatorRequestBinding => {\n const requestContent = inputNodeContent as RequestContentLike | null | undefined;\n const requestSources = useMemo(\n () => getRequestExampleSources(requestContent, { dataLabel }),\n [requestContent, dataLabel],\n );\n const boundRequestSourceIndex = useMemo(() => {\n if (!simulatorExampleBinding || simulatorExampleBinding.nodeId !== inputNodeId) {\n return -1;\n }\n\n return requestSources[simulatorExampleBinding.sourceIndex] ? simulatorExampleBinding.sourceIndex : -1;\n }, [inputNodeId, requestSources, simulatorExampleBinding]);\n const defaultRequestSourceIndex =\n boundRequestSourceIndex >= 0 ? boundRequestSourceIndex : requestSources.length > 0 ? 0 : -1;\n const defaultRequestSource = defaultRequestSourceIndex >= 0 ? requestSources[defaultRequestSourceIndex] : undefined;\n const resolvedSimulatorExampleBinding = useMemo<ResolvedSimulatorExampleBinding | null>(() => {\n if (!inputNodeId || defaultRequestSourceIndex < 0 || !defaultRequestSource) {\n return null;\n }\n\n return {\n nodeId: inputNodeId,\n sourceIndex: defaultRequestSourceIndex,\n sourceName: defaultRequestSource.name,\n };\n }, [defaultRequestSource, defaultRequestSourceIndex, inputNodeId]);\n const currentBindingIdentity = useMemo(\n () => (simulatorExampleBinding ? `${simulatorExampleBinding.nodeId}:${simulatorExampleBinding.sourceIndex}` : null),\n [simulatorExampleBinding],\n );\n const requestDefinitions = useMemo(() => getRequestDefinitions(requestContent), [requestContent]);\n const sourceOptions = useMemo(\n () => requestSources.map((source, index) => ({ value: index, label: source.name })),\n [requestSources],\n );\n const bindingName = useMemo(\n () => (boundRequestSourceIndex >= 0 ? requestSources[boundRequestSourceIndex]?.name : undefined),\n [boundRequestSourceIndex, requestSources],\n );\n const shouldShowSimulatorSourceSelect = Boolean(bindingName) && Boolean(inputNodeId) && requestSources.length > 1;\n\n return {\n requestSources,\n boundRequestSourceIndex,\n defaultRequestSourceIndex,\n defaultRequestSource,\n resolvedSimulatorExampleBinding,\n currentBindingIdentity,\n requestDefinitions,\n sourceOptions,\n bindingName,\n shouldShowSimulatorSourceSelect,\n };\n};\n","import { useEffect, useRef, useState } from 'react';\n\nexport type UseSimulatorRequestEditorParams = {\n defaultRequest?: string;\n simulatorRequest?: string;\n currentBindingIdentity?: string | null;\n onExternalChange?: (nextValue: string) => void;\n};\n\nexport const useSimulatorRequestEditor = ({\n defaultRequest,\n simulatorRequest,\n currentBindingIdentity,\n onExternalChange,\n}: UseSimulatorRequestEditorParams) => {\n const [requestValue, setRequestValue] = useState(defaultRequest);\n const [userHasEdited, setUserHasEdited] = useState(false);\n const [isApplyingExternalRequest, setIsApplyingExternalRequest] = useState(false);\n const switchAnimationTimerRef = useRef<number | null>(null);\n const previousBindingIdentityRef = useRef<string | null | undefined>(null);\n const previousSimulatorRequestRef = useRef<string | undefined>(undefined);\n\n useEffect(\n () => () => {\n if (switchAnimationTimerRef.current !== null) {\n window.clearTimeout(switchAnimationTimerRef.current);\n }\n },\n [],\n );\n\n useEffect(() => {\n const previousBindingIdentity = previousBindingIdentityRef.current;\n const hasSwitchedExampleSource =\n currentBindingIdentity !== null && currentBindingIdentity !== previousBindingIdentity;\n previousBindingIdentityRef.current = currentBindingIdentity;\n\n if (!hasSwitchedExampleSource) {\n return;\n }\n\n if (switchAnimationTimerRef.current !== null) {\n window.clearTimeout(switchAnimationTimerRef.current);\n }\n\n setIsApplyingExternalRequest(true);\n switchAnimationTimerRef.current = window.setTimeout(() => {\n setIsApplyingExternalRequest(false);\n switchAnimationTimerRef.current = null;\n }, 320);\n }, [currentBindingIdentity]);\n\n useEffect(() => {\n if (simulatorRequest === undefined || simulatorRequest === previousSimulatorRequestRef.current) {\n return;\n }\n\n previousSimulatorRequestRef.current = simulatorRequest;\n setRequestValue(simulatorRequest);\n setUserHasEdited(true);\n onExternalChange?.(simulatorRequest);\n\n if (import.meta.env.DEV) {\n console.log('[simulator-request] applied external simulatorRequest', {\n simulatorRequest,\n });\n }\n }, [onExternalChange, simulatorRequest]);\n\n useEffect(() => {\n if (defaultRequest !== undefined && defaultRequest !== requestValue) {\n setRequestValue(defaultRequest);\n }\n }, [defaultRequest]);\n\n return {\n requestValue,\n setRequestValue,\n userHasEdited,\n setUserHasEdited,\n isApplyingExternalRequest,\n };\n};\n","import { VariableType } from '@gorules/zen-engine-wasm';\nimport json5 from 'json5';\nimport React, { useEffect } from 'react';\nimport { toast } from 'sonner';\n\nimport {\n getRequestDefinitions,\n mergeRequestExampleDefaultsByDefinitions,\n normalizeRequestExampleDataByDefinitions,\n normalizeRequestJsonKeys,\n resolveRequestSchemaValue,\n} from '../../../helpers/request-schema';\nimport { copyToClipboard } from '../../../helpers/utility';\nimport { isWasmAvailable } from '../../../helpers/wasm';\nimport { useT } from '../../../theming/i18n';\nimport { Spin } from '../../primitives';\nimport { NodeTypeKind, useDecisionGraphRaw, useDecisionGraphState } from '../context/dg-store.context';\nimport type { DecisionGraphType } from '../dg-types';\nimport { SimulatorEditor } from './simulator-editor';\nimport { SimulatorRequestToolbar } from './simulator-request-toolbar';\nimport { useRequestExamplePersistence } from './use-request-example-persistence';\nimport { useSimulatorAutoSync } from './use-simulator-auto-sync';\nimport { useSimulatorRequestBinding } from './use-simulator-request-binding';\nimport { useSimulatorRequestEditor } from './use-simulator-request-editor';\n\nexport type SimulatorRequestPanelProps = {\n defaultRequest?: string;\n onChange?: (contextJson: string) => void;\n hasInputNode?: boolean;\n loading?: boolean;\n onRun?: (payload: { graph: DecisionGraphType; context: unknown }) => void;\n};\n\nexport const SimulatorRequestPanel: React.FC<SimulatorRequestPanelProps> = ({\n onChange,\n hasInputNode,\n loading,\n onRun,\n defaultRequest,\n}) => {\n const t = useT();\n const { stateStore, actions } = useDecisionGraphRaw();\n\n const { simulatorRequest, simulatorExampleBinding, inputNodeContent, inputNodeId } = useDecisionGraphState(\n ({ simulatorRequest, simulatorExampleBinding, decisionGraph }) => {\n const inputNode = decisionGraph?.nodes?.find((node) => node.type === 'inputNode');\n return {\n simulatorRequest,\n simulatorExampleBinding,\n inputNodeContent: inputNode?.content,\n inputNodeId: inputNode?.id,\n };\n },\n );\n const {\n requestSources,\n boundRequestSourceIndex,\n defaultRequestSourceIndex,\n defaultRequestSource,\n resolvedSimulatorExampleBinding,\n currentBindingIdentity,\n requestDefinitions,\n sourceOptions,\n bindingName,\n shouldShowSimulatorSourceSelect,\n } = useSimulatorRequestBinding({\n inputNodeContent,\n inputNodeId,\n simulatorExampleBinding,\n dataLabel: t('request.dataLabel'),\n });\n const { requestValue, setRequestValue, userHasEdited, setUserHasEdited, isApplyingExternalRequest } =\n useSimulatorRequestEditor({\n defaultRequest,\n simulatorRequest,\n currentBindingIdentity,\n onExternalChange: onChange,\n });\n\n const handleSourceChange = (sourceIndex: number) => {\n const source = requestSources[sourceIndex];\n\n if (!inputNodeId || !source) {\n return;\n }\n\n flushPendingAutoSync();\n\n const mergedData = mergeRequestExampleDefaultsByDefinitions(source.data, requestDefinitions);\n const normalizedData = normalizeRequestExampleDataByDefinitions(mergedData, requestDefinitions);\n const formattedRequest = JSON.stringify(normalizedData, null, 2);\n\n actions.setSimulatorRequest(formattedRequest);\n actions.setSimulatorExampleBinding({\n nodeId: inputNodeId,\n sourceIndex,\n sourceName: source.name,\n });\n };\n\n useEffect(() => {\n if (!defaultRequestSource) {\n return;\n }\n\n if (\n inputNodeId &&\n defaultRequestSourceIndex >= 0 &&\n resolvedSimulatorExampleBinding &&\n (simulatorExampleBinding?.nodeId !== inputNodeId ||\n simulatorExampleBinding.sourceIndex !== defaultRequestSourceIndex ||\n simulatorExampleBinding.sourceName !== defaultRequestSource.name)\n ) {\n actions.setSimulatorExampleBinding(resolvedSimulatorExampleBinding);\n }\n\n if (userHasEdited) {\n return;\n }\n\n const mergedDefaultData = mergeRequestExampleDefaultsByDefinitions(defaultRequestSource.data, requestDefinitions);\n const formattedContent = JSON.stringify(\n normalizeRequestExampleDataByDefinitions(mergedDefaultData, requestDefinitions),\n null,\n 2,\n );\n if (formattedContent && formattedContent !== requestValue) {\n setRequestValue(formattedContent);\n actions.setSimulatorRequest(formattedContent);\n onChange?.(formattedContent);\n }\n }, [\n actions,\n defaultRequestSource,\n defaultRequestSourceIndex,\n inputNodeId,\n onChange,\n requestDefinitions,\n requestValue,\n resolvedSimulatorExampleBinding,\n simulatorExampleBinding,\n userHasEdited,\n ]);\n\n useEffect(() => {\n if (!isWasmAvailable()) {\n return;\n }\n\n const { decisionGraph } = stateStore.getState();\n const requestNode = decisionGraph.nodes.find((node) => node.type === 'inputNode');\n if (!requestNode) {\n return;\n }\n\n try {\n const value = requestValue ? json5.parse(requestValue) : 'Any';\n actions.setNodeType(requestNode.id, NodeTypeKind.InferredOutput, new VariableType(value));\n } catch {\n // Skip\n }\n }, [requestValue]);\n\n const { persistRequestToExampleSource } = useRequestExamplePersistence({\n t,\n requestValue,\n resolvedSimulatorExampleBinding,\n onRequestValueChange: setRequestValue,\n onMarkEdited: () => setUserHasEdited(true),\n onExternalChange: onChange,\n });\n\n const requestSourcesSignature = JSON.stringify(requestSources.map((source) => source.data));\n\n const { flush: flushPendingAutoSync } = useSimulatorAutoSync({\n enabled: Boolean(hasInputNode && resolvedSimulatorExampleBinding),\n requestValue,\n requestSourcesSignature,\n boundRequestSourceIndex,\n onSyncToSchema: () => {\n persistRequestToExampleSource({\n validateDefinitionTypes: false,\n silentWhenUnbound: true,\n showSuccessMessage: false,\n silentOnError: true,\n triggeredBy: 'auto-sync',\n });\n },\n onPushToEditor: () => {\n if (boundRequestSourceIndex < 0 || !requestSources[boundRequestSourceIndex]) {\n return;\n }\n\n const mergedData = mergeRequestExampleDefaultsByDefinitions(\n requestSources[boundRequestSourceIndex].data,\n requestDefinitions,\n );\n const normalizedData = normalizeRequestExampleDataByDefinitions(mergedData, requestDefinitions);\n actions.setSimulatorRequest(JSON.stringify(normalizedData, null, 2));\n },\n });\n\n const handleFormat = () => {\n try {\n const parsed = json5.parse(requestValue || '');\n const normalizedParsed = normalizeRequestJsonKeys(parsed);\n const formatted = JSON.stringify(normalizedParsed, null, 2);\n setRequestValue(formatted);\n setUserHasEdited(true);\n actions.setSimulatorRequest(formatted);\n onChange?.(formatted);\n toast.success(t('simulator.formatSuccess'));\n } catch {\n toast.error(t('simulator.formatFailed'));\n }\n };\n\n const handleCopy = async () => {\n try {\n if (!requestValue || requestValue.trim().length === 0) {\n toast.warning(t('simulator.nothingToCopy'));\n return;\n }\n\n const parsed = json5.parse(requestValue);\n const jsonString = JSON.stringify(parsed);\n\n await copyToClipboard(jsonString);\n toast.success(t('simulator.copiedToClipboard'));\n } catch {\n toast.error(t('simulator.copyFailedInvalidJson'));\n }\n };\n\n const handleRun = () => {\n if (!onRun) {\n return;\n }\n\n try {\n const parsed = (requestValue || '').trim().length === 0 ? null : json5.parse(requestValue || '');\n const hasRequestDefinitions = getRequestDefinitions(inputNodeContent).length > 0;\n const hasRequestSchema = Boolean(resolveRequestSchemaValue(inputNodeContent));\n\n if ((hasRequestDefinitions || hasRequestSchema) && parsed === null) {\n toast.warning(t('simulator.dataRequiredBeforeRun'));\n return;\n }\n\n onRun({\n graph: stateStore.getState().decisionGraph,\n context: parsed,\n });\n } catch {\n toast.error(t('simulator.invalidFormatTitle'), {\n description: t('simulator.invalidFormatDescription'),\n });\n }\n };\n\n return (\n <React.Fragment>\n <SimulatorRequestToolbar\n t={t}\n shouldShowSimulatorSourceSelect={shouldShowSimulatorSourceSelect}\n boundRequestSourceIndex={boundRequestSourceIndex}\n sourceOptions={sourceOptions}\n bindingName={bindingName}\n hasInputNode={hasInputNode}\n loading={loading}\n onSourceChange={handleSourceChange}\n onFormat={handleFormat}\n onCopy={handleCopy}\n onRun={onRun ? handleRun : undefined}\n />\n <div className='relative min-h-0 flex-1 overflow-hidden'>\n <div className='absolute inset-0'>\n <SimulatorEditor\n value={requestValue}\n onChange={(text) => {\n setRequestValue(text);\n setUserHasEdited(true);\n actions.setSimulatorRequest(text ?? '');\n onChange?.(text ?? '');\n }}\n />\n </div>\n {isApplyingExternalRequest && (\n <div className='absolute inset-0 z-10 flex items-center justify-center bg-background/40'>\n <Spin size='small' />\n </div>\n )}\n </div>\n </React.Fragment>\n );\n};\n","import CrossIcon from '#reui/icons/animated/outline/cross';\nimport json5 from 'json5';\nimport React, { useState } from 'react';\nimport { Panel, PanelGroup, PanelResizeHandle } from 'react-resizable-panels';\nimport { P, match } from 'ts-pattern';\n\nimport '../../../helpers/monaco';\nimport { usePersistentState } from '../../../helpers/use-persistent-state';\nimport { useT } from '../../../theming/i18n';\nimport { Button, Tabs, Tooltip } from '../../primitives';\nimport { useDecisionGraphRaw, useDecisionGraphState } from '../context/dg-store.context';\nimport { NodeKind } from '../nodes/specifications/specification-types';\nimport { SimulatorEditor } from './simulator-editor';\nimport { SimulatorNodesPanel } from './simulator-nodes-panel';\nimport { SimulatorRequestPanel, type SimulatorRequestPanelProps } from './simulator-request-panel';\n\nenum SimulationSegment {\n Output = 'Output',\n Input = 'Input',\n Trace = 'Trace',\n}\n\nexport type GraphSimulatorProps = {\n onClear?: () => void;\n loading?: boolean;\n defaultRequest?: SimulatorRequestPanelProps['defaultRequest'];\n onChange?: SimulatorRequestPanelProps['onChange'];\n onRun?: SimulatorRequestPanelProps['onRun'];\n leftPanel?: React.FC<SimulatorRequestPanelProps>;\n};\n\nexport const GraphSimulator: React.FC<GraphSimulatorProps> = ({\n defaultRequest,\n onChange,\n onRun,\n onClear,\n loading = false,\n leftPanel: LeftPanel = SimulatorRequestPanel,\n}) => {\n const t = useT();\n const [search, setSearch] = usePersistentState<string>('simulation.search', '');\n const [segment, setSegment] = usePersistentState<SimulationSegment>('simulation.segment', SimulationSegment.Output);\n\n const { viewConfig } = useDecisionGraphState((state) => ({\n viewConfig: state.viewConfig,\n }));\n\n const { actions } = useDecisionGraphRaw();\n const { nodeTypes, simulate, hasInputNode } = useDecisionGraphState(({ decisionGraph, simulate }) => ({\n simulate,\n hasInputNode: decisionGraph.nodes.some((n) => n.type === NodeKind.Input),\n nodeTypes: (decisionGraph.nodes ?? []).reduce<Record<string, string | undefined>>(\n (acc, curr) => ({\n ...acc,\n [curr.id]: curr.type,\n }),\n {},\n ),\n }));\n\n const [selectedNode, setSelectedNode] = useState<string>('graph');\n\n return (\n <PanelGroup\n className='h-full w-full bg-[var(--grl-color-primary-bg-fade)]'\n direction='horizontal'\n autoSaveId='jdm-editor:simulator:layout'\n >\n <Panel minSize={20} defaultSize={38} className='flex w-[300px] flex-col'>\n <LeftPanel\n defaultRequest={defaultRequest}\n loading={loading}\n hasInputNode={hasInputNode}\n onRun={onRun}\n onChange={onChange}\n />\n </Panel>\n <PanelResizeHandle />\n <Panel minSize={20} maxSize={20} className={'flex w-[260px] flex-col'}>\n <SimulatorNodesPanel\n search={search}\n onSearchChange={setSearch}\n loading={loading}\n simulate={simulate}\n nodeTypes={nodeTypes}\n viewConfig={viewConfig}\n selectedNode={selectedNode}\n onSelectNode={setSelectedNode}\n onClear={() => {\n onClear?.();\n setSelectedNode('graph');\n setSearch('');\n }}\n onGoToNode={(nodeId) => actions.goToNode(nodeId)}\n />\n </Panel>\n <PanelResizeHandle />\n <Panel minSize={30} defaultSize={42} className={'flex min-w-[300px] flex-1 flex-col'}>\n <div className='flex h-9 select-none items-center justify-between gap-1 border-b border-b-[var(--border)] pl-0 pr-2'>\n <Tabs\n size='small'\n style={{ width: '100%' }}\n onChange={(tab) => setSegment(tab as SimulationSegment)}\n items={Object.values(SimulationSegment).map((s) => ({\n key: s,\n label: s,\n }))}\n tabBarExtraContent={\n <Tooltip title={t('dg.toolbar.closeClose')} placement='bottomRight'>\n <Button\n type='text'\n icon={<CrossIcon className='size-3' />}\n onClick={() => actions.setActivePanel(undefined)}\n />\n </Tooltip>\n }\n />\n </div>\n <div className={'min-h-0 flex-1 overflow-y-auto'}>\n <SimulatorEditor\n readOnly\n value={match(simulate)\n .with({ result: P._ }, ({ result }) =>\n match(selectedNode)\n .with('graph', () =>\n displaySegment(\n {\n traceData: result?.trace,\n output: result?.result,\n },\n segment ?? SimulationSegment.Output,\n ),\n )\n .otherwise(() => displaySegment(result?.trace[selectedNode], segment ?? SimulationSegment.Output)),\n )\n .otherwise(() => '')}\n />\n </div>\n </Panel>\n </PanelGroup>\n );\n};\n\nconst displaySegment = (data: unknown, segment: SimulationSegment) => {\n const jsonData = match([segment, data])\n .with([SimulationSegment.Output, { output: P._ }], ([, { output }]) => output)\n .with([SimulationSegment.Input, { input: P._ }], ([, { input }]) => input)\n .with([SimulationSegment.Trace, { trace: P._ }], ([, { trace }]) => trace)\n .with([SimulationSegment.Trace, { traceData: P._ }], ([, { traceData }]) => traceData)\n .otherwise(() => ({}));\n\n return json5.stringify(jsonData, undefined, 2);\n};\n","import type { DecisionGraphType } from '../dg-types';\n\n/** 单个节点/边的变更描述(name/kind 便于面板按类型展示) */\nexport type GraphNodeChange = {\n id: string;\n /** 变更后名称(removed 条目为变更前名称) */\n name?: string;\n /** 节点 type / 边 type(customNode kind 等) */\n kind?: string;\n /** 内容发生变化的顶层字段名列表(可选增强) */\n fields?: string[];\n};\n\nexport type GraphDiff = {\n addedNodes: GraphNodeChange[];\n removedNodes: GraphNodeChange[];\n modifiedNodes: GraphNodeChange[];\n addedEdges: GraphNodeChange[];\n removedEdges: GraphNodeChange[];\n modifiedEdges: GraphNodeChange[];\n /** 全部为空 = true(内容相同;仅位置变化也算无变化) */\n unchanged: boolean;\n};\n\n/** 运行时元数据不参与内容比较:position 属于布局(spec 验收 #2),_diff 是图内 diff 染色残留 */\nconst IGNORED_NODE_KEYS = new Set(['position', '_diff']);\nconst IGNORED_EDGE_KEYS = new Set(['_diff']);\n\n/** 递归排序对象键后再序列化——语义相等即字符串相等,不受键插入顺序影响 */\nconst canonicalize = (value: unknown): string => {\n if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'undefined';\n if (Array.isArray(value)) return `[${value.map(canonicalize).join(',')}]`;\n const entries = Object.entries(value as Record<string, unknown>)\n .filter(([, v]) => v !== undefined)\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonicalize(v)}`).join(',')}}`;\n};\n\ntype Item = { id: string; name?: string; type?: string; [key: string]: unknown };\n\nconst strip = (item: Item, ignored: Set<string>): Record<string, unknown> =>\n Object.fromEntries(Object.entries(item).filter(([k]) => !ignored.has(k)));\n\nconst changedFields = (a: Item, b: Item, ignored: Set<string>): string[] => {\n const keys = new Set([...Object.keys(strip(a, ignored)), ...Object.keys(strip(b, ignored))]);\n return [...keys].filter(\n (k) => canonicalize((a as Record<string, unknown>)[k]) !== canonicalize((b as Record<string, unknown>)[k]),\n );\n};\n\nconst diffById = (aItems: Item[], bItems: Item[], ignored: Set<string>) => {\n const aMap = new Map(aItems.map((item) => [item.id, item]));\n const bMap = new Map(bItems.map((item) => [item.id, item]));\n\n const added: GraphNodeChange[] = [];\n const removed: GraphNodeChange[] = [];\n const modified: GraphNodeChange[] = [];\n\n for (const [id, item] of bMap) {\n if (!aMap.has(id)) {\n added.push({ id, name: item.name, kind: item.type });\n }\n }\n for (const [id, item] of aMap) {\n const incoming = bMap.get(id);\n if (!incoming) {\n removed.push({ id, name: item.name, kind: item.type });\n continue;\n }\n const fields = changedFields(item, incoming, ignored);\n if (fields.length > 0) {\n modified.push({ id, name: incoming.name ?? item.name, kind: incoming.type ?? item.type, fields });\n }\n }\n\n return { added, removed, modified };\n};\n\n/**\n * 版本对比纯函数引擎(P1 面板变更清单):按 id 结构化 diff 两版图 JSON。\n *\n * - 节点/边分别以 id 为身份:added = b 有 a 无;removed = a 有 b 无;\n * modified = 双方都有且规范化内容不等(键序无关、忽略 position/_diff)\n * - modified 条目携带字段级 `fields` 明细\n * - 无副作用、无 React 依赖;`unchanged` 供面板显示「无变化」\n */\nexport const computeGraphDiff = (a: DecisionGraphType, b: DecisionGraphType): GraphDiff => {\n const nodes = diffById((a.nodes ?? []) as unknown as Item[], (b.nodes ?? []) as unknown as Item[], IGNORED_NODE_KEYS);\n const edges = diffById((a.edges ?? []) as unknown as Item[], (b.edges ?? []) as unknown as Item[], IGNORED_EDGE_KEYS);\n\n return {\n addedNodes: nodes.added,\n removedNodes: nodes.removed,\n modifiedNodes: nodes.modified,\n addedEdges: edges.added,\n removedEdges: edges.removed,\n modifiedEdges: edges.modified,\n unchanged:\n nodes.added.length +\n nodes.removed.length +\n nodes.modified.length +\n edges.added.length +\n edges.removed.length +\n edges.modified.length ===\n 0,\n };\n};\n","export default \"data:image/svg+xml,%3csvg%20id='fi_5968381'%20enable-background='new%200%200%20512%20512'%20height='512'%20viewBox='0%200%20512%20512'%20width='512'%20xmlns='http://www.w3.org/2000/svg'%3e%3cg%3e%3cpath%20d='m50%200h412c27.614%200%2050%2022.386%2050%2050v412c0%2027.614-22.386%2050-50%2050h-412c-27.614%200-50-22.386-50-50v-412c0-27.614%2022.386-50%2050-50z'%20fill='%233178c6'%3e%3c/path%3e%3cpath%20d='m50%200h412c27.614%200%2050%2022.386%2050%2050v412c0%2027.614-22.386%2050-50%2050h-412c-27.614%200-50-22.386-50-50v-412c0-27.614%2022.386-50%2050-50z'%20fill='%233178c6'%3e%3c/path%3e%3cpath%20clip-rule='evenodd'%20d='m316.939%20407.424v50.061c8.138%204.172%2017.763%207.3%2028.875%209.386s22.823%203.129%2035.135%203.129c21.219%200%2044.448-3.035%2062.602-14.784%2018.064-11.691%2026.449-31.14%2026.449-52.172%200-15.637-4.851-30.684-15.807-42.081-16.429-17.091-39.516-24.022-60.255-34.183-10.389-5.09-24.727-12.992-24.727-26.361%200-3.441.887-6.543%202.661-9.307%207.132-11.113%2022.973-13.376%2035.057-13.376%2013.717%200%2028.189%203.071%2040.926%208.76%204.434%201.982%208.529%204.276%2012.285%206.884v-46.776c-7.616-2.92-15.937-5.084-24.962-6.492s-19.381-2.112-31.066-2.112c-11.895%200-23.163%201.278-33.805%203.833s-20.006%206.544-28.093%2011.967c-8.086%205.424-14.476%2012.333-19.171%2020.729-4.695%208.395-7.043%2018.433-7.043%2030.114%200%2014.914%204.304%2027.638%2012.912%2038.172%208.607%2010.533%2021.675%2019.45%2039.204%2026.751%2011.792%204.822%2024.053%209.581%2034.665%2016.739%207.355%204.96%2014.007%2011.877%2014.007%2021.275%200%206.821-3.856%2012.604-9.468%2016.192-8.303%205.308-18.936%206.492-28.563%206.492-10.851%200-21.597-1.903-32.24-5.71-10.641-3.806-20.501-9.516-29.578-17.13zm-84.159-123.342h64.22v-41.082h-179v41.082h63.906v182.918h50.874z'%20fill='%23fff'%20fill-rule='evenodd'%3e%3c/path%3e%3c/g%3e%3c/svg%3e\"","import React from 'react';\nimport { JSONTree } from 'react-json-tree';\nimport { toast } from 'sonner';\n\nimport { copyToClipboard } from '../../helpers/utility';\nimport { useThemeMode } from '../../theme';\nimport { useT } from '../../theming/i18n';\nimport { Dropdown, Tooltip } from '../primitives';\n\nexport type FunctionDebuggerLogProps = {\n lines: string[];\n msSinceRun: number | null;\n};\n\ntype JsonTheme = {\n string: string;\n constants: string;\n number: string;\n type: string;\n error: string;\n info: string;\n};\n\nconst themes: Record<'dark' | 'light', JsonTheme> = {\n dark: {\n string: '#CE9178',\n number: '#B5CEA8',\n constants: '#569CD6',\n type: '#3DC9B0',\n error: '#E51400',\n info: 'rgba(0, 0, 0, 0.65)',\n },\n light: {\n string: '#A31515',\n number: '#098658',\n constants: '#0000FF',\n type: '#008080',\n error: '#E51400',\n info: 'rgba(0, 0, 0, 0.65)',\n },\n};\n\nexport const FunctionDebuggerLog: React.FC<FunctionDebuggerLogProps> = ({ lines, msSinceRun }) => {\n const mode = useThemeMode();\n const t = useT();\n const jsonTheme = themes[mode ?? 'light'];\n\n return (\n <div className='flex items-start justify-between border-b border-[var(--grl-color-border-fade)] pl-4 pr-6 text-xs leading-[var(--grl-line-height)] text-[var(--grl-color-text-base)] [font-family:var(--mono-font-family)]'>\n <Dropdown\n trigger={['contextMenu']}\n menu={{\n items: [\n {\n key: 'copy',\n label: t('func.debugger.copy'),\n onClick: async () => {\n await copyToClipboard(lines.length === 1 ? lines[0] : `[${lines.join(', ')}]`);\n toast.success('Copied to clipboard');\n },\n },\n ],\n }}\n >\n <div className='grl-function__debugger__log__values'>\n {lines.map((line, i) => {\n const data = safeParseJson(line);\n\n return (\n <JSONTree\n key={i}\n data={data}\n shouldExpandNodeInitially={() => false}\n labelRenderer={(keyPath: readonly (string | number)[], nodeType) => {\n const parts: React.ReactNode[] = [];\n\n const lastPart = keyPath?.[0];\n if (lastPart !== 'root') {\n parts.push(\n <>\n <span style={{ color: jsonTheme.constants }}>{lastPart}</span>\n {': '}\n </>,\n );\n }\n\n if (keyPath.length >= 1) {\n let paths = [...keyPath];\n paths.pop();\n paths = paths.reverse();\n\n parts.push(objectRenderer(jsonTheme)(lens(data, paths), nodeType));\n }\n\n return <>{parts}</>;\n }}\n valueRenderer={valueRenderer(jsonTheme)}\n theme={\n {\n base00: 'var(--card)',\n base03: 'var(--grl-color-text-base)',\n base0B: 'var(--grl-color-text-base)',\n base0D: 'var(--grl-color-text-base)',\n /*\n * Inline-tab flow + zero root indent — replaces the former\n * .grl-function__debugger__log__values !important stylesheet\n * war (HK-01). `value` stylable replicates library defaults\n * for deeper levels; only top-level roots collapse\n * flush-left like before. Escape-hatch cast: react-json-tree's\n * union type doesn't model base16 strings alongside function\n * stylables, though its runtime merge handles both.\n */\n tree: {\n display: 'inline-block',\n },\n value: (\n styling: { style?: React.CSSProperties },\n _nodeType: string,\n keyPath: readonly (string | number)[],\n ) => ({\n style: {\n ...(styling?.style ?? {}),\n paddingTop: '0.25em',\n paddingRight: 0,\n marginLeft: (keyPath?.length ?? 0) > 1 ? '0.875em' : 0,\n WebkitUserSelect: 'text',\n MozUserSelect: 'text',\n wordWrap: 'break-word',\n paddingLeft: (keyPath?.length ?? 0) > 1 ? '2.125em' : 0,\n textIndent: '-0.5em',\n wordBreak: 'break-all',\n } as React.CSSProperties,\n }),\n } as React.ComponentProps<typeof JSONTree>['theme']\n }\n />\n );\n })}\n </div>\n </Dropdown>\n <div className='pt-[1ch] opacity-50'>\n {msSinceRun !== null && <Tooltip title={t('func.debugger.msSinceRun')}>{msSinceRun}ms</Tooltip>}\n </div>\n </div>\n );\n};\n\nconst objectRenderer =\n (jsonTheme: JsonTheme) =>\n (data: any, nodeType: string): React.ReactNode => {\n if (nodeType === 'Object') {\n const objectData = data as Record<string, any>;\n const objectEntries = Object.entries(objectData);\n const renders = objectEntries.reduce(\n (acc: React.ReactNode[], [key, value], currentIndex) => [\n ...acc,\n <span key={key}>\n {key}: {valueRenderer(jsonTheme)(stringifyJsonData(value), value)}\n {currentIndex !== objectEntries.length - 1 && <>{', '}</>}\n </span>,\n ],\n [] satisfies React.ReactNode[],\n );\n\n return (\n <>\n {' {'}\n {renders}\n {'}'}\n </>\n );\n } else if (nodeType === 'Array') {\n const arrayData = data as unknown[];\n const renders = arrayData.reduce<React.ReactNode[]>(\n (acc, value, currentIndex) => [\n ...acc,\n <span key={currentIndex}>\n {valueRenderer(jsonTheme)(stringifyJsonData(value), value)}\n {currentIndex !== arrayData.length - 1 && <>{', '}</>}\n </span>,\n ],\n [],\n );\n\n return (\n <>\n {arrayData.length > 2 ? `(${arrayData.length})` : ''} [{renders}]\n </>\n );\n } else {\n return null;\n }\n };\n\nconst stringifyJsonData = (value: unknown): string => {\n switch (true) {\n case Array.isArray(value):\n return `Array(${(value as unknown[]).length})`;\n case typeof value === 'object':\n return '{...}';\n default:\n return JSON.stringify(value);\n }\n};\n\nconst valueRenderer =\n (jsonTheme: JsonTheme) =>\n (valueAsStr: unknown, value: unknown): React.ReactNode => {\n const valueAsString = valueAsStr as string;\n if (typeof value === 'string') {\n if (valueAsString.startsWith('\"Error:')) {\n return <span style={{ color: jsonTheme.error }}>{valueAsString.slice(1, -1)}</span>;\n }\n\n if (valueAsString.startsWith('\"Info:')) {\n return <span style={{ color: jsonTheme.info }}>{valueAsString.slice(1, -1)}</span>;\n }\n\n return <span style={{ color: jsonTheme.string }}>{valueAsString}</span>;\n } else if (typeof value === 'boolean') {\n return <span style={{ color: jsonTheme.constants }}>{valueAsString}</span>;\n } else if (typeof value === 'number') {\n return <span style={{ color: jsonTheme.number }}>{valueAsString}</span>;\n }\n\n return valueAsString;\n };\n\nconst lens = (obj: any, path: (string | number)[]) => path.reduce((o, key) => (o && o[key] ? o[key] : null), obj);\n\nconst safeParseJson = (data: string): unknown => {\n if (typeof data !== 'string') {\n return undefined;\n }\n\n data = data.trim();\n if (!data) {\n return undefined;\n }\n\n try {\n return JSON.parse(data);\n } catch {\n return `[UNSERIALIZED]: ${data}`;\n }\n};\n","import { ExportOutlined, FormatPainterOutlined, PlusOutlined } from '#icons';\nimport type { editor } from 'monaco-editor';\nimport React, { useMemo, useState } from 'react';\nimport { match } from 'ts-pattern';\n\nimport typeScriptIcon from '../../assets/typescript.svg?inline';\nimport { useT } from '../../theming/i18n';\nimport type { SimulationTrace, SimulationTraceDataFunction } from '../decision-graph/simulator/simulation.types';\nimport { Button, Tabs, Tooltip, Typography } from '../primitives';\nimport { FunctionDebuggerLog } from './function-debugger-log';\nimport { type FunctionLibrary } from './helpers/libs';\n\nenum TabKey {\n Console = 'Console',\n Libraries = 'Libraries',\n}\n\nexport type FunctionDebuggerProps = {\n trace?: SimulationTrace<SimulationTraceDataFunction>;\n editor?: editor.IStandaloneCodeEditor;\n editorValue?: string;\n libraries: FunctionLibrary[];\n disabled?: boolean;\n};\n\nexport const FunctionDebugger: React.FC<FunctionDebuggerProps> = ({\n trace,\n editor,\n libraries = [],\n editorValue,\n disabled,\n}) => {\n const traceLog = trace?.traceData?.log || [];\n const [activeTab, setActiveTab] = useState<TabKey>(TabKey.Console);\n\n const t = useT();\n\n return (\n <div className='h-full border-l border-[var(--border)]'>\n <div className='flex h-full flex-col overflow-hidden bg-[var(--card)]'>\n <div className='flex shrink-0 items-center border-b border-[var(--border)] bg-[var(--grl-color-primary-bg-fade)]'>\n <Tabs\n rootClassName='grl-inline-tabs'\n size='small'\n style={{ width: '100%' }}\n items={Object.values(TabKey).map((t) => ({ key: t, label: t }))}\n activeKey={activeTab}\n onChange={(t) => setActiveTab(t as TabKey)}\n tabBarExtraContent={\n <div style={{ marginRight: 8 }}>\n <Tooltip title={t('func.debugger.formatCode')} placement='bottomLeft'>\n <Button\n size='small'\n type='text'\n icon={<FormatPainterOutlined />}\n onClick={() => editor?.getAction?.('editor.action.formatDocument')?.run?.()}\n />\n </Tooltip>\n </div>\n }\n />\n </div>\n <div className='grow overflow-y-auto'>\n {match(activeTab)\n .with(TabKey.Console, () => (\n <>\n {traceLog.length === 0 && (\n <FunctionDebuggerLog\n lines={['\"Info: Use console.log and run simulation to debug your code.\"']}\n msSinceRun={null}\n />\n )}\n\n {traceLog.map((log, i) => (\n <FunctionDebuggerLog key={i} lines={log.lines} msSinceRun={log.msSinceRun} />\n ))}\n </>\n ))\n .with(TabKey.Libraries, () => (\n <div className='flex flex-col'>\n {libraries.map((lib) => (\n <FunctionLibraryItem\n key={lib.name}\n lib={lib}\n disabled={disabled}\n editorValue={editorValue}\n onImport={() => {\n if (!editor) {\n return;\n }\n\n const importStatement = `import ${lib.importName ?? lib.name} from '${lib.name}';`;\n editor.setValue(importStatement + '\\n' + editor.getValue());\n }}\n />\n ))}\n </div>\n ))\n .exhaustive()}\n </div>\n </div>\n </div>\n );\n};\n\nconst FunctionLibraryItem: React.FC<{\n lib: FunctionLibrary;\n onImport?: () => void;\n editorValue?: string;\n disabled?: boolean;\n}> = ({ lib, onImport, editorValue, disabled }) => {\n const t = useT();\n const canImport = useMemo(() => {\n if (!editorValue) {\n return true;\n }\n\n return !editorValue.includes(`from \"${lib.name}\"`) && !editorValue.includes(`from '${lib.name}'`);\n }, [lib.name, editorValue]);\n\n return (\n <div\n key={lib.name}\n className='flex items-center gap-2 border-b border-[var(--grl-color-border-fade)] p-2 no-underline'\n >\n <img alt='TypeScript Library' src={typeScriptIcon} height={18} />\n <Typography.Text strong>{lib.name}</Typography.Text>\n <Typography.Text type='secondary' style={{ fontSize: 12, marginTop: 1.5 }}>\n {lib.tagline}\n </Typography.Text>\n <div className='ml-auto flex gap-2'>\n <Tooltip title={t('func.debugger.importLibrary')} placement='bottomLeft'>\n <Button\n type='text'\n size='small'\n icon={<PlusOutlined />}\n disabled={!canImport || disabled}\n onClick={onImport}\n />\n </Tooltip>\n <Tooltip title={t('func.debugger.goToDocs')} placement='bottomLeft'>\n <Button\n type='text'\n size='small'\n icon={<ExportOutlined />}\n href={lib.documentationUrl}\n target='_blank'\n disabled={!lib.documentationUrl}\n />\n </Tooltip>\n </div>\n </div>\n );\n};\n","import type { VariableType, VariableTypeJson } from '@gorules/zen-engine-wasm';\nimport { P, match } from 'ts-pattern';\n\nexport const variableTypeToTypescript = (variableType: VariableType) => {\n const json = variableType.toJson();\n return vtJsonToTypescript(json);\n};\n\nconst vtJsonToTypescript = (vtj: VariableTypeJson): string =>\n match(vtj)\n .with('String', () => 'string')\n .with('Bool', () => 'boolean')\n .with('Number', () => 'number')\n .with('Null', () => 'null')\n .with('Any', () => 'any')\n .with({ Object: P.select() }, (obj) => {\n const innerObject = Object.entries(obj)\n .map(([key, value]) => [key, vtJsonToTypescript(value)].join(':'))\n .join(',');\n\n return `{${innerObject}}`;\n })\n .with({ Array: P.select() }, (arr) => `${vtJsonToTypescript(arr)}[]`)\n .with({ Const: P.select() }, (c) => `\"${c}\"`)\n .with({ Enum: [P._, P.select()] }, (en) => en.map((e) => `\"${e}\"`).join(' | '))\n .exhaustive();\n","import { createVariableType } from '@gorules/zen-engine-wasm';\nimport { DiffEditor, Editor, type Monaco, useMonaco } from '@monaco-editor/react';\nimport type { editor } from 'monaco-editor';\nimport React, { useEffect, useRef, useState } from 'react';\nimport { Panel, PanelGroup, PanelResizeHandle } from 'react-resizable-panels';\nimport { useDebouncedCallback, useThrottledCallback } from 'use-debounce';\n\nimport '../../helpers/monaco';\nimport { isWasmAvailable } from '../../helpers/wasm';\nimport { useThemeMode } from '../../theme';\nimport type { SimulationTrace, SimulationTraceDataFunction } from '../decision-graph/simulator/simulation.types';\nimport { Spin } from '../primitives';\nimport { SafeBoundary } from '../safe-boundary';\nimport { FunctionDebugger } from './function-debugger';\nimport { variableTypeToTypescript } from './helpers/determine-type';\nimport { type FunctionLibrary, functionDefinitions, functionLibraries } from './helpers/libs';\n\n// monaco 的 MarkerSeverity 是固定数值枚举(editor.api.d.ts);以本地字面量\n// 引用使 monaco 在内核内保持纯类型依赖——消费方打包器即使错误地把 tsconfig\n// paths 应用于运行时解析,也不会有任何 monaco 值导入入口(S008 加固)。\nconst MarkerSeverity = { Hint: 1, Info: 2, Warning: 4, Error: 8 } as const;\n\nexport type FunctionPermission = 'edit:full';\n\nexport type FunctionProps = {\n disabled?: boolean;\n defaultValue?: string;\n disableDebug?: boolean;\n language?: string;\n value?: string;\n previousValue?: string;\n onChange?: (value: string) => void;\n trace?: SimulationTrace<SimulationTraceDataFunction>;\n onMonacoReady?: (monaco: Monaco) => void;\n onEditorMount?: (editor: editor.IStandaloneCodeEditor) => void;\n libraries?: FunctionLibrary[];\n inputData?: unknown;\n permission?: FunctionPermission;\n error?: {\n data: { nodeId: string; source?: string };\n };\n};\n\nexport const Function: React.FC<FunctionProps> = ({\n disabled = false,\n disableDebug,\n language = 'javascript',\n defaultValue,\n value,\n onChange,\n trace,\n onMonacoReady,\n onEditorMount,\n error,\n inputData,\n previousValue,\n permission = 'edit:full',\n libraries = functionLibraries,\n}) => {\n const monaco = useMonaco();\n const mountedRef = useRef(false);\n const mode = useThemeMode();\n const [innerValue, setInnerValue] = useState<string>();\n const [decorations, setDecorations] = useState<editor.IEditorDecorationsCollection>();\n\n const innerChange = useDebouncedCallback((val: string) => {\n onChange?.(val);\n }, 100);\n\n const [editor, setEditor] = useState<editor.IStandaloneCodeEditor>();\n const [diffEditor, setDiffEditor] = useState<editor.IStandaloneDiffEditor>();\n const resizeEditor = useThrottledCallback(() => editor?.layout(), 100, { trailing: true });\n const resizeDiffEditor = useThrottledCallback(() => diffEditor?.layout(), 100, { trailing: true });\n\n useEffect(() => {\n window.addEventListener('resize', resizeEditor);\n return () => window.removeEventListener('resize', resizeEditor);\n }, [resizeEditor, editor]);\n\n useEffect(() => {\n window.addEventListener('resize', resizeDiffEditor);\n return () => window.removeEventListener('resize', resizeDiffEditor);\n }, [resizeDiffEditor, diffEditor]);\n\n useEffect(() => {\n if (!monaco) return;\n\n monaco.languages.typescript.javascriptDefaults.setCompilerOptions({\n target: monaco.languages.typescript.ScriptTarget.ES2020,\n module: monaco.languages.typescript.ModuleKind.ESNext,\n moduleResolution: monaco.languages.typescript.ModuleResolutionKind.NodeJs,\n allowSyntheticDefaultImports: true,\n allowNonTsExtensions: true,\n allowJs: true,\n checkJs: true,\n lib: ['es2023'],\n });\n\n monaco.languages.typescript.javascriptDefaults.setDiagnosticsOptions({\n noSyntaxValidation: false,\n noSemanticValidation: false,\n noSuggestionDiagnostics: false,\n onlyVisible: false,\n });\n\n monaco.languages.typescript.javascriptDefaults.setExtraLibs(\n functionLibraries.map((lib) => ({\n content: `declare module '${lib.name}' { ${lib.typeDef} }`,\n filePath: lib.name,\n })),\n );\n\n Object.entries(functionDefinitions.globals).forEach(([pkg, types]) => {\n monaco.languages.typescript.javascriptDefaults.addExtraLib(types, `ts:${pkg}`);\n });\n\n onMonacoReady?.(monaco);\n }, [monaco, libraries]);\n\n useEffect(() => {\n if (mountedRef.current && value !== undefined && value !== innerValue) {\n setInnerValue(value);\n }\n }, [value]);\n\n useEffect(() => {\n setInnerValue(value === undefined ? defaultValue : value);\n mountedRef.current = true;\n }, []);\n\n useEffect(() => {\n if (!monaco) return;\n\n let data = 'any';\n if (isWasmAvailable()) {\n data = variableTypeToTypescript(createVariableType(inputData));\n }\n\n monaco.languages.typescript.javascriptDefaults.addExtraLib(\n `\n type Input = ${data};\n type Output = Promise<any>;\n \n type Handler = (input: Input) => Output; \n `,\n 'ts:input.d.ts',\n );\n }, [monaco, inputData]);\n\n useEffect(() => {\n if (!monaco) {\n return;\n }\n\n const model = monaco.editor.getModels()?.[0];\n if (!model) {\n return;\n }\n\n monaco.editor.setModelMarkers(model, 'gorules', []);\n }, [innerValue, monaco]);\n\n useEffect(() => {\n if (!decorations) {\n return;\n }\n\n decorations.clear();\n setDecorations(undefined);\n }, [innerValue]);\n\n useEffect(() => {\n try {\n if (!error || !monaco) {\n return;\n }\n\n const results = /Error:(\\[.*])?(:?\\d+)?(:\\d+)?(.*)/s.exec(error.data.source ?? '');\n if (!results || results.length === 0) {\n return;\n }\n\n const line = parseFloat((results?.[2] ?? '').replace(/^:/, ''));\n const errorMessage = results?.[4] ?? '';\n if (!line || !errorMessage) {\n return;\n }\n\n const model = monaco.editor.getModels()[0];\n if (!model) {\n return;\n }\n\n const range = new monaco.Range(\n line,\n model.getLineFirstNonWhitespaceColumn(line),\n line,\n model.getLineLastNonWhitespaceColumn(line),\n );\n\n monaco.editor.setModelMarkers(model, 'gorules', [\n {\n severity: MarkerSeverity.Error,\n message: errorMessage,\n startLineNumber: range.startLineNumber,\n endLineNumber: range.endLineNumber,\n startColumn: range.startColumn,\n endColumn: range.endColumn,\n },\n ]);\n\n const editor = monaco.editor.getEditors()[0];\n if (!editor) {\n return;\n }\n\n const decorations = editor.createDecorationsCollection([\n {\n range,\n options: {\n hoverMessage: { value: errorMessage },\n isWholeLine: true,\n className: 'grl-function__errorLineContent',\n },\n },\n ]);\n\n setDecorations((curr) => {\n curr?.clear?.();\n return decorations;\n });\n } catch {\n //\n }\n }, [error, editor]);\n\n return (\n <SafeBoundary>\n <div\n className='relative box-border flex flex-col'\n style={\n {\n 'height': '100%',\n '--color-text': 'var(--grl-color-text-base)',\n '--color-background-elevated': 'var(--card)',\n '--color-border': 'var(--border)',\n '--line-height': 1.5,\n } as React.CSSProperties\n }\n >\n <PanelGroup className='flex-1' direction='horizontal' autoSaveId='jdm-editor:function:layout'>\n <Panel defaultSize={70} minSize={50}>\n {previousValue ? (\n <DiffEditor\n loading={<Spin size='large' />}\n language={language}\n original={previousValue}\n modified={innerValue}\n onMount={(editor) => setDiffEditor(editor)}\n theme={mode === 'dark' ? 'vs-dark' : 'light'}\n height='100%'\n options={{\n ...monacoOptions,\n readOnly: true,\n }}\n />\n ) : (\n <Editor\n loading={<Spin size='large' />}\n language={language}\n value={innerValue}\n onMount={(editor) => {\n setEditor(editor);\n onEditorMount?.(editor);\n }}\n onChange={(value) => {\n setInnerValue(value ?? '');\n innerChange(value ?? '');\n }}\n theme={mode === 'dark' ? 'vs-dark' : 'light'}\n height='100%'\n options={{\n ...monacoOptions,\n readOnly: disabled || permission !== 'edit:full',\n }}\n />\n )}\n </Panel>\n {!disableDebug && (\n <>\n <PanelResizeHandle />\n <Panel minSize={25}>\n {!disableDebug && (\n <FunctionDebugger\n libraries={functionLibraries}\n trace={trace}\n editor={editor}\n editorValue={value}\n disabled={disabled || permission !== 'edit:full'}\n />\n )}\n </Panel>\n </>\n )}\n </PanelGroup>\n </div>\n </SafeBoundary>\n );\n};\n\nconst monacoOptions: editor.IStandaloneEditorConstructionOptions = {\n automaticLayout: true,\n contextmenu: false,\n fontSize: 13,\n fontFamily: 'var(--mono-font-family)',\n tabSize: 2,\n minimap: { enabled: false },\n overviewRulerBorder: false,\n scrollbar: {\n verticalSliderSize: 4,\n verticalScrollbarSize: 4,\n horizontalScrollbarSize: 4,\n horizontalSliderSize: 4,\n },\n};\n","export * from './function';\n"],"x_google_ignoreList":[11,54],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;aAEM,KAAiC;CACrC,SAAS;CACT,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