|
| 1 | +import type { UiNodeInputAttributes } from '@ory/client' |
| 2 | +import type { UiNode } from '@ory/client' |
| 3 | +import type { ReactElement } from 'react' |
| 4 | + |
| 5 | +import { UiNodeTypeEnum } from '@ory/client' |
| 6 | +import { useEffect } from 'react' |
| 7 | +import { useCallback } from 'react' |
| 8 | + |
| 9 | +import { useFlowNode } from '../hooks' |
| 10 | +import { useValue } from '../hooks' |
| 11 | + |
| 12 | +type OnChangeCallback = (event: Date | boolean | number | string) => void |
| 13 | + |
| 14 | +export interface FlowUiInputNode extends Omit<UiNode, 'attributes'> { |
| 15 | + attributes: UiNodeInputAttributes |
| 16 | +} |
| 17 | + |
| 18 | +export interface FlowInputNodeProps { |
| 19 | + name: string |
| 20 | + defaultValue?: string |
| 21 | + children: (node: FlowUiInputNode, value: string, callback: OnChangeCallback) => ReactElement |
| 22 | +} |
| 23 | + |
| 24 | +export const FlowInputNode = ({ |
| 25 | + name, |
| 26 | + defaultValue, |
| 27 | + children, |
| 28 | +}: FlowInputNodeProps): ReactElement | null => { |
| 29 | + const node = useFlowNode(name) |
| 30 | + const [value, setValue] = useValue(name) |
| 31 | + |
| 32 | + useEffect(() => { |
| 33 | + if (!value && defaultValue) { |
| 34 | + setValue(defaultValue) |
| 35 | + } |
| 36 | + }, [defaultValue]) // eslint-disable-line react-hooks/exhaustive-deps |
| 37 | + |
| 38 | + const onChange = useCallback( |
| 39 | + (event: Date | boolean | number | string) => { |
| 40 | + setValue(event) |
| 41 | + }, |
| 42 | + [setValue] |
| 43 | + ) |
| 44 | + |
| 45 | + if (node && node.type === UiNodeTypeEnum.Input && typeof children === 'function') { |
| 46 | + return children(node as FlowUiInputNode, value, onChange) |
| 47 | + } |
| 48 | + |
| 49 | + return null |
| 50 | +} |
0 commit comments