refactor node

This commit is contained in:
2026-03-09 14:11:33 +01:00
parent 24efc597b2
commit 9565a425b6
5 changed files with 230 additions and 134 deletions

View File

@@ -1,6 +1,9 @@
import React, { memo, useCallback, useContext } from 'react'
import FlowContext from '../../lib/flowContext'
import { nodePropsAreEqual } from '../../lib/flowUtils'
import React, { useCallback } from 'react'
import {
AbstractNodeProps,
createAbstractNodeComponent,
useAbstractNode,
} from '../../lib/abstractNode'
import {
BaseNode,
BaseNodeContent,
@@ -16,16 +19,15 @@ import { NodeHeaderTitle } from '../base/NodeHeaderTitle'
import { OutputHandle } from '../base/NodeHandles'
import { Variable } from 'lucide-react'
type ValueType = 'string' | 'number' | 'boolean'
export type ValueType = 'string' | 'number' | 'boolean'
type Props = {
id: string
data: {
value?: string | number | boolean
valueType?: ValueType
}
export type VariableNodeData = {
value?: string | number | boolean
valueType?: ValueType
}
type Props = AbstractNodeProps<VariableNodeData>
const DEFAULT_BY_TYPE: Record<ValueType, string | number | boolean> = {
string: '',
number: 0,
@@ -45,26 +47,13 @@ function coerceValue(raw: string, valueType: ValueType): string | number | boole
}
}
export const VariableNode = memo(function VariableNode({ id, data }: Props) {
const ctx = useContext(FlowContext)
const setNodes = ctx?.setNodes
function VariableNodeComponent({ id, data }: Props) {
const { updateData } = useAbstractNode<VariableNodeData>(id, data ?? {})
const valueType: ValueType = data?.valueType ?? 'string'
const value = data?.value ?? DEFAULT_BY_TYPE[valueType]
const displayValue = typeof value === 'string' ? value : String(value)
const updateData = useCallback(
(updates: { value?: string | number | boolean; valueType?: ValueType }) => {
if (!setNodes) return
setNodes((nds: any[]) =>
nds.map((n) =>
n.id === id ? { ...n, data: { ...n.data, ...updates } } : n
)
)
},
[id, setNodes]
)
const onTypeChange = useCallback(
(nextType: string) => {
const type = nextType as ValueType
@@ -85,9 +74,7 @@ export const VariableNode = memo(function VariableNode({ id, data }: Props) {
)
const onBooleanChange = useCallback(
(checked: boolean) => {
updateData({ value: checked })
},
(checked: boolean) => updateData({ value: checked }),
[updateData]
)
@@ -141,8 +128,11 @@ export const VariableNode = memo(function VariableNode({ id, data }: Props) {
</BaseNodeFooter>
</BaseNode>
)
}, nodePropsAreEqual)
}
VariableNode.displayName = 'VariableNode'
export const VariableNode = createAbstractNodeComponent<VariableNodeData>(
'VariableNode',
VariableNodeComponent
)
export default VariableNode