### Clone the Repository Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/README.md Clone the project repository to your local machine to get started. ```bash git clone https://github.com/nobruf/shadcn-next-workflows.git ``` -------------------------------- ### Install Dependencies Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/README.md Install all the necessary project dependencies using npm. ```bash npm install ``` -------------------------------- ### Run Development Server Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/README.md Start the Next.js development server to view the application locally. ```bash npm run dev ``` -------------------------------- ### Marketing Tag Example Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/types.md Provides a concrete example of a Tag object, specifically for 'marketing' purposes, demonstrating its structure with sample values. ```typescript const marketingTag: Tag = { value: "marketing", label: "Marketing", color: "#ef4444" }; ``` -------------------------------- ### RegisterNodeMetadata Interface Example Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/types.md Example demonstrating how to define metadata for a 'menu' node type. This structure is used to register nodes with the flow builder, providing configuration and rendering details. ```typescript const menuMetadata: RegisterNodeMetadata = { type: "menu", node: memo(MenuNode), detail: { icon: "f7:menu", title: "Menu", description: "Send options to the user", gradientColor: "fuchsia", }, connection: { inputs: 1, outputs: 0, }, defaultData: { question: null, options: [], }, propertyPanel: MenuNodePropertyPanel, }; ``` -------------------------------- ### Derived Registries Example Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/architecture.md Shows examples of derived registries generated from the main Node Registry, including mappings for node types to components and metadata. ```typescript NODE_TYPES: Record>; NODES_METADATA: Record; AVAILABLE_NODES: RegisterNodeMetadata[]; ``` -------------------------------- ### WorkflowCanvas Component Example Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/api-reference-hooks.md An example demonstrating how to integrate the useAddNodeOnEdgeDrop hook into a React component to manage edge drops and node creation. ```typescript import { useAddNodeOnEdgeDrop } from "@/hooks/use-add-node-on-edge-drop"; function WorkflowCanvas() { const { handleOnEdgeDropConnectEnd, floatingMenuWrapperRef, handleAddConnectedNode } = useAddNodeOnEdgeDrop(); return ( <>
); } ``` -------------------------------- ### StartNode Metadata Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/node-components.md Metadata for the Start node, specifying its type, icon, title, connection rules, availability, and default data. ```typescript { type: "start", icon: "solar:play-bold", title: "Start", description: "Start the chatbot flow", connection: { inputs: 0, outputs: 1 }, available: false, defaultData: { label: "Start", deletable: false } } ``` -------------------------------- ### useAddNodeOnEdgeDropStore Hook Usage Example Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/api-reference-stores.md Demonstrates how to use the useAddNodeOnEdgeDropStore hook to access and control the visibility of the add node menu. Requires importing the hook from its module. ```typescript import { useAddNodeOnEdgeDropStore } from "@/stores/add-node-on-edge-drop-state"; function AddNodeFloatingMenu() { const [showMenu, setShowMenu] = useAddNodeOnEdgeDropStore( (s) => [s.showMenu, s.actions.setShowMenu] ); if (!showMenu) return null; return
Add Node Menu
; } ``` -------------------------------- ### Start Node Default Data Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/configuration.md Defines the default properties for a 'Start' node, including its label and deletability status. This node is not available in the sidebar. ```typescript { label: "Start", deletable: false } ``` -------------------------------- ### Start Node Default Data Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/types.md Provides the default data object for a Start node, specifying its label and deletable status. ```typescript { label: "Start", deletable: false, } ``` -------------------------------- ### Initialize and Use Flow Validator Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/configuration.md This example demonstrates how to initialize the useFlowValidator hook and trigger validation. The callback function handles the validation result. ```typescript const [isValidating, validate] = useFlowValidator((isValid) => { if (isValid) { console.log("Flow is ready to save"); } else { console.log("Flow has incomplete connections"); } }); // Trigger validation await validate(); ``` -------------------------------- ### Using NODE_TYPE_DRAG_DATA_FORMAT Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/api-reference-utilities.md Demonstrates how to use the NODE_TYPE_DRAG_DATA_FORMAT constant for setting and getting data during drag-and-drop operations. ```typescript import { NODE_TYPE_DRAG_DATA_FORMAT } from "@/contants/symbols"; // In drag handler const type = e.dataTransfer.getData(NODE_TYPE_DRAG_DATA_FORMAT); // In drag start handler e.dataTransfer.setData(NODE_TYPE_DRAG_DATA_FORMAT, "menu"); ``` -------------------------------- ### StartNodeData Interface Definition Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/types.md Defines the data structure for a Start node, extending BaseNodeData. It includes an optional label property for display. ```typescript interface StartNodeData extends BaseNodeData { label?: string; } ``` -------------------------------- ### Tag Shape Example Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/types.md Illustrates the expected shape of a Tag object, including a unique identifier, display name, and hex color code. ```typescript { value: string; // Unique identifier label: string; // Display name color: string; // Hex color code } ``` -------------------------------- ### Add New Header Gradient Color Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/configuration.md Example of how to add a new custom gradient color to the `HeaderGradientColors` object and use it in node metadata. ```typescript // In types.ts const HeaderGradientColors = { // ... existing crimson: "from-red-900", }; // Use in metadata gradientColor: "crimson" ``` -------------------------------- ### Get Node Detail Metadata Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/api-reference-utilities.md Retrieves metadata (icon, title, description, gradientColor) for a given node type from the registry. Use this to display node information in UI elements like menus or tooltips. Throws an error if the node type is not found. ```typescript import { getNodeDetail } from "@/components/flow-builder/components/blocks/utils"; const menuDetail = getNodeDetail("menu"); console.log(menuDetail.title); // "Menu" console.log(menuDetail.icon); // "f7:menu" ``` -------------------------------- ### useOnNodesDelete Hook Usage Example Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/api-reference-hooks.md This snippet demonstrates how to integrate the `useOnNodesDelete` hook into a React Flow component. It shows how to obtain the current nodes and pass them to the hook, and then use the returned handler for the `onNodesDelete` event. ```typescript import { useOnNodesDelete } from "@/hooks/use-on-nodes-delete"; import { useReactFlow } from "@xyflow/react"; function Canvas() { const { getNodes } = useReactFlow(); const onNodesDelete = useOnNodesDelete(getNodes()); return ; } ``` -------------------------------- ### Get Drag Data for Node Type Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/configuration.md Used in the canvas's `onDrop` to retrieve the node type data that was set during drag start. ```typescript const type = e.dataTransfer.getData(NODE_TYPE_DRAG_DATA_FORMAT); ``` -------------------------------- ### Node Creation: User Initiates Creation Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/data-flow.md Illustrates the initial user interactions for creating a node, including dragging from the sidebar and dropping on the canvas or an edge. ```text User drags node icon from AvailableNodes panel └─> ondragstart event fires └─> Sets MIME data: { "application/flow-builder.node-type": "menu" } ``` ```text User drops on empty canvas area └─> useDragDropFlowBuilder() onDrop handler fires └─> Gets drop coordinates via screenToFlowPosition() └─> Gets node type from dataTransfer MIME data ``` ```text User drags from handle to canvas edge (invalid connection) └─> useAddNodeOnEdgeDrop() onConnectEnd handler fires └─> Shows floating menu at drop position └─> User selects node type from menu ``` -------------------------------- ### User Selects Node Type and Connects Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/data-flow.md Outlines the process after the user selects a node type from the floating menu, including node creation, edge connection, and hiding the menu. ```text User clicks node type in floating menu └─> handleAddConnectedNode(type) fires ├─> Get stored connection metadata ├─> Get drop position ├─> Create node: insertNode(type, dropPosition) ├─> Get fromHandle: metadata.fromHandle (source or target) ├─> If fromHandle.type === "source": │ └─> Connect: source node → new node │ └─> source: fromNode.id │ └─> target: newNode.id ├─> If fromHandle.type === "target": │ └─> Connect: new node → target node │ └─> source: newNode.id │ └─> target: targetNode.id ├─> addEdges() to React Flow └─> Hide menu: setShowMenu(false) ``` -------------------------------- ### User Initiates Connection Flow Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/data-flow.md Illustrates the sequence of events when a user initiates a connection between nodes in React Flow, from drag detection to callback invocation. ```text User drags from handle A on node 1 └─> React Flow detects drag from handle └─> Creates temporary connection indicator └─> If user releases on valid handle: └─> Calls onConnect(connection) callback └─> If user releases on invalid target: └─> May show error or trigger edge-drop menu ``` -------------------------------- ### Programmatically Creating a Node Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/README.md Shows how to use the `useInsertNode` hook to programmatically create and insert a new node into the workflow. This is useful for dynamic node generation. ```typescript import { useInsertNode } from "@/hooks/use-insert-node"; function AddNodeButton() { const insertNode = useInsertNode(); const handleAdd = () => { const node = insertNode("menu", { x: 100, y: 100 }); }; } ``` -------------------------------- ### Node Auto-Adjust Logic Flow Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/data-flow.md Illustrates the sequence of operations for the auto-adjust function, from initial node drag to overlap detection and animation. ```text User drags a node and releases (onNodeDragStop) └─> autoAdjust(node) called ``` -------------------------------- ### User Initiates Invalid Connection Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/data-flow.md Describes the initial user action of attempting to create an invalid connection by dragging from a handle and releasing the mouse. ```text User drags from handle A on node 1 └─> Hovers over another handle or canvas area └─> If connection would be invalid: └─> User releases mouse ``` -------------------------------- ### Get React Component for Node Type Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/api-reference-utilities.md Access the `NODE_TYPES` mapping to retrieve the React component associated with a specific node type. This is essential for rendering nodes in the UI. ```typescript import { NODE_TYPES } from "@/components/flow-builder/components/blocks"; const StartComponent = NODE_TYPES["start"]; ``` -------------------------------- ### actions.sidebar.showNodePropertiesOf Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/api-reference-stores.md Shows the node properties panel for a specific node. Requires the node's ID and type. ```APIDOC ## actions.sidebar.showNodePropertiesOf(node) ### Description Shows the node properties panel for a specific node. ### Method Not applicable (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **node.id** (string) - Yes - Node ID to show properties for - **node.type** (BuilderNodeType) - Yes - Node type (start, end, menu, etc.) ### Request Example ```typescript const { showNodePropertiesOf } = useFlowStore((s) => s.actions.sidebar); showNodePropertiesOf({ id: "node-1", type: "menu" }); ``` ``` -------------------------------- ### Creating a New Tag Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/README.md Demonstrates the creation of a new tag with specific properties using the `actions.sidebar.panels.tags.createTag` method from the flow store. ```typescript const { tags, actions } = useFlowStore(); actions.sidebar.panels.tags.createTag({ value: "priority", label: "Priority", color: "#FF6B6B" }); ``` -------------------------------- ### Get Delete Key Codes with useDeleteKeyCode Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/INDEX.md This hook returns an array of delete key codes if a node is deletable, which can be passed to ReactFlow. It returns null if no delete keys are configured. ```typescript const deleteKeyCode = useDeleteKeyCode(); ``` -------------------------------- ### createNodeWithDefaultData(type, data) Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/api-reference-utilities.md Creates a node object, initializing it with default data for its type and merging any provided overrides. This is useful for creating nodes with standard configurations that can be customized. ```APIDOC ## createNodeWithDefaultData(type, data) ### Description Creates a node with default data for its type, merged with optional overrides. ### Signature ```typescript function createNodeWithDefaultData( type: BuilderNodeType, data?: Partial ): Node ``` ### Parameters #### Path Parameters - **type** (BuilderNodeType) - Required - Node type to create - **data** (Partial) - Optional - Partial node data to merge (e.g., position, selected) ### Returns Complete `Node` object with default data and overrides applied ### Throws `Error` if no default data found for node type ### Example ```typescript import { createNodeWithDefaultData } from "@/components/flow-builder/components/blocks/utils"; const newNode = createNodeWithDefaultData("menu", { position: { x: 100, y: 200 }, selected: true }); // Includes default MenuNodeData merged with position and selected state ``` ``` -------------------------------- ### useFlowValidator Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/api-reference-hooks.md Validates the flow structure ensuring Start node is connected, End node is connected, and no lone nodes exist. It returns the current validation state and a function to trigger validation. ```APIDOC ## useFlowValidator ### Description Validates the flow structure ensuring the Start node is connected, the End node is connected, and no lone nodes exist. This hook is useful for maintaining the integrity of workflow diagrams. ### Signature ```typescript function useFlowValidator( onValidate?: (isValid: boolean) => void ): [boolean, () => void] ``` ### Parameters #### Callback Function - **onValidate** ( (isValid: boolean) => void ) - Optional - Callback function invoked when validation completes. It receives a boolean indicating whether the flow is valid. ### Returns **Type:** `[boolean, () => void]` - **Index 0** (boolean): Current validation state (true if validating). - **Index 1** ( () => void ): Validate function to trigger the validation process. ### Validation Rules - **Start Node:** Must have at least one outgoing edge. - **End Node:** Must have at least one incoming edge. - **No Lone Nodes:** All nodes except Start and End must have both incoming and outgoing edges. - Flow is valid only if all rules pass. ### Example ```typescript import { useFlowValidator } from "@/hooks/use-flow-validator"; function WorkflowCanvas() { const [isValidating, validate] = useFlowValidator((isValid) => { if (isValid) { console.log("Flow is valid!"); } else { console.log("Flow has errors"); } }); const handleSaveClick = async () => { await validate(); }; return ( ); } ``` ``` -------------------------------- ### Use Node Auto Adjust Hook Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/api-reference-hooks.md Automatically repositions nodes to prevent overlaps with animation. Call this hook to get a function that takes a node and adjusts it along with any overlapping nodes. ```typescript import { useNodeAutoAdjust } from "@/hooks/use-node-auto-adjust"; function Canvas() { const autoAdjust = useNodeAutoAdjust(); const handleNodeDragEnd = (event, node) => { autoAdjust(node); }; return ; } ``` -------------------------------- ### Manage Tags using Flow Store Actions Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/configuration.md Illustrates the usage of actions provided by the useFlowStore hook to create, update, delete, and set tags. Ensure tag values correspond to the registry. ```typescript const { tags, actions } = useFlowStore(); // Create new tag actions.sidebar.panels.tags.createTag({ value: "urgent", label: "Urgent", color: "#ff0000" }); // Update existing actions.sidebar.panels.tags.updateTag( { value: "marketing", label: "Marketing", color: "#ef4444" }, { value: "marketing", label: "Marketing Team", color: "#f97316" } ); // Delete tag actions.sidebar.panels.tags.deleteTag({ value: "support", label: "Support", color: "#ef4444" }); // Replace all actions.sidebar.panels.tags.setTags([...newTags]); ``` -------------------------------- ### Validate Flow Structure with useFlowValidator Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/INDEX.md Use this hook to validate the flow structure, ensuring the start and end nodes are connected and there are no isolated nodes. The callback is invoked with a boolean indicating validation status. ```typescript const [isValidating, validate] = useFlowValidator((isValid) => { if (isValid) console.log("Flow ready to save"); }); await validate(); ``` -------------------------------- ### useFlowStore Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/INDEX.md Central store for managing the entire workflow state, including tags, workflow data, and various actions for state mutation. ```APIDOC ## useFlowStore ### Description Central store managing workflow state, including tags, workflow data, and actions for state mutation. ### Signature ```typescript useFlowStore(): IFlowState ``` ### State Shape - `tags` (Tag[]) — Available tags for categorization - `workflow` ({ id, name, nodes, edges, sidebar }) — Complete workflow - `actions` — All state mutators ### Key Actions - `actions.saveWorkflow()` — Return serialized workflow - `actions.setWorkflow(workflow)` — Load workflow - `actions.nodes.{onNodesChange, setNodes, deleteNode}` — Node operations - `actions.edges.{onEdgesChange, onConnect, setEdges, deleteEdge}` — Edge operations - `actions.sidebar.setActivePanel(panel)` — Show/hide panels - `actions.sidebar.panels.tags.{setTags, createTag, updateTag, deleteTag}` — Tag management ### Example ```typescript const { workflow, tags, actions } = useFlowStore(); const handleSave = () => { const saved = actions.saveWorkflow(); console.log(`Saved ${saved.id} with ${saved.nodes.length} nodes`); }; const handleAddTag = () => { actions.sidebar.panels.tags.createTag({ value: "vip", label: "VIP", color: "#FFD700" }); }; ``` ``` -------------------------------- ### Set Show Menu Action Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/api-reference-stores.md Use this action to control the visibility of the floating add-node menu. Pass a boolean value to show or hide the menu. ```typescript setShowMenu(show: boolean): void ``` -------------------------------- ### Retrieve Complete Node Metadata Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/api-reference-utilities.md Use `NODES_METADATA` to get the full metadata for a node type, including internal details not exposed in the basic `NODES` array. This can be used to access properties like the node's icon. ```typescript import { NODES_METADATA } from "@/components/flow-builder/components/blocks"; const menuMeta = NODES_METADATA["menu"]; console.log(menuMeta.__details.icon); ``` -------------------------------- ### Library Utilities Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/INDEX.md Provides utility functions for string manipulation and class merging, along with a constant for drag-and-drop data transfer. ```APIDOC ## cn(...inputs) ### Description Merge Tailwind CSS classes with intelligent conflict resolution. Uses `clsx` for parsing and `tailwind-merge` for merging. ### Method `cn` ### Parameters #### Path Parameters - **inputs** (string[]) - Required - An array of Tailwind CSS class strings to merge. ## truncateMiddle(text, maxLength) ### Description Truncate text in the middle, preserving ellipsis within the specified maximum length. For example, "long-text" becomes "lon...ext". ### Method `truncateMiddle` ### Parameters #### Path Parameters - **text** (string) - Required - The text to truncate. - **maxLength** (number) - Required - The maximum length of the truncated string, including ellipsis. ### Returns The truncated string. ## NODE_TYPE_DRAG_DATA_FORMAT ### Description A MIME type constant used for drag-and-drop data transfer, specifically for node types. ### Value `"application/flow-builder.node-type"` ``` -------------------------------- ### useAddNodeOnEdgeDropStore Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/api-reference-stores.md Hook to access the state and actions for managing the floating menu position and node metadata during edge drops. It returns the current state, including positions, menu visibility, and action methods for state manipulation. ```APIDOC ## useAddNodeOnEdgeDropStore() ### Description Returns edge drop state and actions. This hook provides access to the current state, including anchor and drop positions, menu visibility, and methods to update these states. ### Signature ```typescript useAddNodeOnEdgeDropStore(): AddNodeOnEdgeDropState ``` ### Returns Current state including positions, menu visibility, and action methods. ### Example ```typescript import { useAddNodeOnEdgeDropStore } from "@/stores/add-node-on-edge-drop-state"; function AddNodeFloatingMenu() { const [showMenu, setShowMenu] = useAddNodeOnEdgeDropStore( (s) => [s.showMenu, s.actions.setShowMenu] ); if (!showMenu) return null; return
Add Node Menu
; } ``` ``` -------------------------------- ### useAddNodeOnEdgeDrop Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/api-reference-hooks.md Handles adding a node when dropping on an edge and displays a floating menu to select the node type. It monitors invalid connections, positions the menu respecting viewport boundaries, and supports both mouse and touch events. ```APIDOC ## useAddNodeOnEdgeDrop ### Description Handles adding a node when dropping on an edge. Shows floating menu to select node type. ### Signature ```typescript function useAddNodeOnEdgeDrop(): { handleOnEdgeDropConnectEnd: ( e: MouseEvent | TouchEvent, connectionState: FinalConnectionState ) => void; floatingMenuWrapperRef: React.RefObject; handleAddConnectedNode: (type: BuilderNodeType) => void; } ``` ### Returns | Property | Type | Description | |----------|------|-------------| | handleOnEdgeDropConnectEnd | Function | Call on React Flow's onConnectEnd event | | floatingMenuWrapperRef | RefObject | Ref for the floating menu container | | handleAddConnectedNode | Function | Call to add node when menu item selected | ### Return Type Details #### handleOnEdgeDropConnectEnd(e, connectionState) Shows the floating menu when an invalid connection is attempted. **Parameters:** | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | e | MouseEvent \| TouchEvent | Yes | Drop event from React Flow | | connectionState | FinalConnectionState | Yes | Connection state from React Flow | #### handleAddConnectedNode(type) Creates a new node and connects it to the initiating handle. **Parameters:** | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | type | BuilderNodeType | Yes | Type of node to create | ### Behavior - Monitors invalid connections (isValid=false) - Shows floating menu at drop position - Menu position respects viewport boundaries (20px padding) - Supports both mouse and touch events ### Example ```typescript import { useAddNodeOnEdgeDrop } from "@/hooks/use-add-node-on-edge-drop"; function WorkflowCanvas() { const { handleOnEdgeDropConnectEnd, floatingMenuWrapperRef, handleAddConnectedNode } = useAddNodeOnEdgeDrop(); return ( <>
); } ``` ``` -------------------------------- ### createNodeWithData(type, data, node) Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/api-reference-utilities.md Creates a node object using entirely provided data, rather than defaults, and merges any additional node properties. This offers maximum flexibility in defining a node's initial state. ```APIDOC ## createNodeWithData(type, data, node) ### Description Creates a node with provided data instead of defaults. ### Signature ```typescript function createNodeWithData( type: BuilderNode, data: T, node?: Partial ): Node ``` ### Parameters #### Path Parameters - **type** (BuilderNode) - Required - Node type to create - **data** (T) - Required - Node data object - **node** (Partial) - Optional - Partial node properties to merge ### Returns Complete `Node` object ### Example ```typescript const customNode = createNodeWithData( "menu", { question: "What would you like?", options: [...] }, { position: { x: 50, y: 50 } } ); ``` ``` -------------------------------- ### Display Available Nodes in UI Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/api-reference-utilities.md Iterate over the `AVAILABLE_NODES` array to render a list of nodes that are intended for user selection in the UI. Each node object contains properties like type, icon, title, and description. ```typescript import { AVAILABLE_NODES } from "@/components/flow-builder/components/blocks"; function NodePicker() { return (
{AVAILABLE_NODES.map(node => ( ))}
); } ``` -------------------------------- ### Node Registry Metadata Structure Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/architecture.md Illustrates the structure of metadata objects within the Node Registry, detailing component references, display information, connection details, and default data. ```typescript RegisterNodeMetadata { Component: React.FC; display: { icon: string; title: string; description: string; gradient: string; }; connection: { inputs: number; outputs: number; }; defaultData: any; propertiesPanel?: React.FC; } ``` -------------------------------- ### actions.setShowMenu Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/api-reference-stores.md Controls the visibility of the floating add-node menu. This action allows toggling the menu's display state. ```APIDOC ## actions.setShowMenu(show) ### Description Controls visibility of the floating add-node menu. This action updates the `showMenu` state, determining whether the menu is currently displayed to the user. ### Method ```typescript setShowMenu(show: boolean): void ``` ### Parameters #### Path Parameters - **show** (boolean) - Yes - Whether to show the menu ``` -------------------------------- ### Create a New Tag Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/api-reference-stores.md Adds a new tag to the system. The tag object must include value, label, and color properties. ```typescript const { createTag } = useFlowStore((s) => s.actions.sidebar.panels.tags); createTag({ value: "urgent", label: "Urgent", color: "#ff0000" }); ``` -------------------------------- ### Floating Menu Logic with useAddNodeOnEdgeDrop Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/data-flow.md Details the logic executed by the `useAddNodeOnEdgeDrop` hook when an invalid connection is detected. It covers coordinate adjustments, state updates, and displaying the floating menu. ```typescript useAddNodeOnEdgeDrop() ├─> onConnectEnd(e, connectionState) fires ├─> Check if connection is valid: if (connectionState.isValid) ├─> If invalid: │ ├─> Get drop coordinates from event (mouse/touch) │ ├─> Adjust for floating menu boundaries: │ │ ├─> x = clamp between 20px and containerWidth - 20px │ │ └─> y = clamp between 20px and containerHeight - 20px │ ├─> Convert screen coordinates to flow coordinates: screenToFlowPosition() │ ├─> Store anchor position: setAnchorPosition() │ ├─> Store drop position: setDropPosition() │ ├─> Store connection metadata: setIncomingNodeMetadetails(connectionState) │ └─> Show menu: setShowMenu(true) ``` -------------------------------- ### StartNode Component Signature Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/node-components.md Signature for the StartNode React component, accepting node data and selection state. ```typescript function StartNode({ data, selected, isConnectable }: StartNodeProps): JSX.Element ``` -------------------------------- ### useFlowStore() Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/api-reference-stores.md Hook to access the entire flow state and actions for the workflow builder. It provides reactive access to workflow data, tags, and management functions. ```APIDOC ## useFlowStore() ### Description Returns the entire flow state and actions for managing the workflow builder. ### Signature ```typescript useFlowStore(): IFlowState ``` ### Returns `IFlowState` — Complete workflow state object containing tags, workflow data, and all available actions. ### Example ```typescript import { useFlowStore } from "@/stores/flow-store"; function WorkflowComponent() { const { workflow, tags, actions } = useFlowStore(); const handleSaveWorkflow = () => { const saved = actions.saveWorkflow(); console.log("Saved workflow ID:", saved.id); }; return
Current nodes: {workflow.nodes.length}
; } ``` ``` -------------------------------- ### cn(...inputs) Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/api-reference-utilities.md Merges Tailwind CSS classes intelligently, handling conflicts and utilizing `clsx` for parsing and `tailwind-merge` for resolution. ```APIDOC ## cn(...inputs) ### Description Merges Tailwind CSS classes, handling conflicts intelligently. It uses `clsx` for parsing and `tailwind-merge` for intelligent merging. ### Signature ```typescript function cn(...inputs: ClassValue[]): string ``` ### Parameters #### Path Parameters - **inputs** (ClassValue[]) - Required - Classes from clsx (strings, objects, arrays) ### Returns Merged class string with conflicts resolved ### Example ```typescript import { cn } from "@/lib/utils"; const buttonClass = cn( "px-4 py-2 bg-blue-500", disabled && "opacity-50 cursor-not-allowed" ); // Merges multiple sources without Tailwind conflicts const nodeClass = cn( "border border-gray-200", isSelected && "border-primary ring-2 ring-primary/30" ); ``` ``` -------------------------------- ### actions.setWorkflow(workflow) Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/api-reference-stores.md Replaces the current workflow with the provided workflow data. ```APIDOC ## actions.setWorkflow(workflow) ### Description Replaces the current workflow with provided workflow data. ### Signature ```typescript setWorkflow(workflow: IFlowState["workflow"]): void ``` ### Parameters #### Path Parameters - **workflow** (IFlowState["workflow"]) - Required - Complete workflow object to set ### Example ```typescript actions.setWorkflow({ id: "wf-123", name: "My Workflow", nodes: [], edges: [], sidebar: { active: "none", panels: { nodeProperties: { selectedNode: null } } } }); ``` ``` -------------------------------- ### Set Incoming Node Metadata Action Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/api-reference-stores.md Use this action to set metadata about the connection that triggered the edge drop. Accepts FinalConnectionState or null. ```typescript setIncomingNodeMetadetails(detail: FinalConnectionState | null): void ``` -------------------------------- ### Push to Branch Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/README.md Push your feature branch to the remote repository. ```git git push origin feature/AmazingFeature ``` -------------------------------- ### Node Utilities Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/INDEX.md Provides functions for interacting with node metadata and creating node data structures. ```APIDOC ## getNodeDetail(nodeType) ### Description Get metadata (icon, title, description, gradientColor) for a given node type. ### Method `getNodeDetail` ### Parameters #### Path Parameters - **nodeType** (string) - Required - The type of the node to retrieve details for. ### Throws Throws if the node type is not found in the registry. ## createNodeData(type, data) ### Description Create a bare node structure with a nanoid ID. ### Method `createNodeData` ### Parameters #### Path Parameters - **type** (string) - Required - The type of the node. - **data** (object) - Required - The data for the node. ### Returns Returns `{ id, type, data }`. ## createNodeWithDefaultData(type, overrides?) ### Description Create a node using default values from the registry, merging optional position and selected state. ### Method `createNodeWithDefaultData` ### Parameters #### Path Parameters - **type** (string) - Required - The type of the node. - **overrides** (object) - Optional - Overrides for position, selected state, etc. ### Returns Returns a complete Node object. ## createNodeWithData(type, data, overrides?) ### Description Create a node with custom data instead of defaults. ### Method `createNodeWithData` ### Parameters #### Path Parameters - **type** (string) - Required - The type of the node. - **data** (object) - Required - The custom data for the node. - **overrides** (object) - Optional - Overrides for position, selected state, etc. ### Returns Returns a complete Node object. ``` -------------------------------- ### Create and Insert Node with useInsertNode Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/api-reference-hooks.md Use this hook to create a new node of a specified type and insert it at a given position on the canvas. It automatically deselects previous nodes and selects the new one. ```typescript import { useInsertNode } from "@/hooks/use-insert-node"; function AddNodeButton() { const insertNode = useInsertNode(); const handleAddMenu = () => { const newNode = insertNode("menu", { x: 100, y: 200 }); console.log("Created node:", newNode.id); }; return ; } ``` -------------------------------- ### Create a Feature Branch Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/README.md Create a new branch for your feature when contributing to the project. ```git git checkout -b feature/AmazingFeature ``` -------------------------------- ### Node Creation: Store Update Mechanism Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/data-flow.md Explains how React Flow's internal state updates and the subsequent manual store updates required for node changes. ```typescript React Flow addNodes() └─> Triggers internal React Flow state update └─> Node appears in getNodes() from useReactFlow hook └─> Component re-renders with new node visible ``` -------------------------------- ### Create Node Component Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/node-components.md Implement the React component for your custom node. This component will receive node properties like id, data, and selection state. ```typescript function MyNode({ id, data, selected, isConnectable }: MyNodeProps) { // Render component } ``` -------------------------------- ### Handle Edge Connections Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/api-reference-stores.md Use this function to handle new edge connections created by the user. It requires access to the `onConnect` action from the flow store. ```typescript const { onConnect } = useFlowStore((s) => s.actions.edges); function handleConnect(connection) { onConnect(connection); } ``` -------------------------------- ### Use Workflow Store Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/INDEX.md Access and manipulate workflow state, including saving and loading workflows, managing nodes and edges, and controlling the sidebar. Use this to interact with the central workflow data. ```typescript const { workflow, tags, actions } = useFlowStore(); const handleSave = () => { const saved = actions.saveWorkflow(); console.log(`Saved ${saved.id} with ${saved.nodes.length} nodes`); }; const handleAddTag = () => { actions.sidebar.panels.tags.createTag({ value: "vip", label: "VIP", color: "#FFD700" }); }; ``` -------------------------------- ### Show Properties for a Specific Node Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/api-reference-stores.md Displays the node properties panel for a given node. This requires the node's ID and type. ```typescript const { showNodePropertiesOf } = useFlowStore((s) => s.actions.sidebar); showNodePropertiesOf({ id: "node-1", type: "menu" }); ``` -------------------------------- ### Menu Node Metadata Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/node-components.md Configuration metadata for the Menu Node, specifying its type, icon, title, description, color, connection limits, default data, and associated property panel. ```typescript { type: "menu", icon: "f7:menu", title: "Menu", description: "Send options to the user choosing one of them based on the condition.", gradientColor: "fuchsia", connection: { inputs: 1, outputs: 0 }, defaultData: { question: null, options: [ { id: nanoid(), option: { id: 0, value: "Option 1" } }, { id: nanoid(), option: { id: 1, value: "Option 2" } }, { id: nanoid(), option: { id: 2, value: "Option 3" } } ] }, propertyPanel: MenuNodePropertyPanel } ``` -------------------------------- ### actions.sidebar.panels.tags.setTags Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/api-reference-stores.md Replaces all existing tags with a new array of tags. Use this to completely update the tag list. ```APIDOC ## actions.sidebar.panels.tags.setTags(tags) ### Description Replaces all tags. ### Method Not applicable (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **tags** (Tag[]) - Yes - Array of tags to set ``` -------------------------------- ### Create Node with Default Data and Overrides Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/api-reference-utilities.md Creates a node object using the default data for its type, merged with any optional overrides provided. Use this when you need a node with its standard configuration plus specific properties like position or selection state. ```typescript import { createNodeWithDefaultData } from "@/components/flow-builder/components/blocks/utils"; const newNode = createNodeWithDefaultData("menu", { position: { x: 100, y: 200 }, selected: true }); // Includes default MenuNodeData merged with position and selected state ``` -------------------------------- ### IFlowState Interface Definition Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/api-reference-stores.md Defines the structure of the state managed by the useFlowStore hook, including tags, workflow details, and available actions. ```typescript interface IFlowState { tags: Tag[]; workflow: { id: string; name: string; nodes: Node[]; edges: Edge[]; sidebar: { active: "node-properties" | "available-nodes" | "none"; panels: { nodeProperties: { selectedNode: { id: string; type: BuilderNodeType } | null | undefined; }; }; }; }; actions: Actions["actions"]; } ``` -------------------------------- ### Saving Workflow via API POST Request Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/data-flow.md Demonstrates how to persist a saved workflow object by sending it to a backend API endpoint using a POST request. ```typescript const saved = actions.saveWorkflow(); await fetch("/api/workflows", { method: "POST", body: JSON.stringify(saved) }); ``` -------------------------------- ### Accessing Flow Store Data Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/README.md Demonstrates how to access workflow data, tags, and actions from the `useFlowStore` hook. Use this to read or modify workflow state. ```typescript import { useFlowStore } from "@/stores/flow-store"; function MyComponent() { const { workflow, tags, actions } = useFlowStore(); const save = () => actions.saveWorkflow(); const createTag = (tag) => actions.sidebar.panels.tags.createTag(tag); } ``` -------------------------------- ### useInsertNode Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/INDEX.md Enables the creation and insertion of a new node at a specified position within the flow. It requires the node type and optionally accepts position coordinates. ```APIDOC ## useInsertNode ### Description Creates and inserts node at specified position. ### Parameters Node type, optional position ### Returns Created Node object ### Usage Example ```typescript const insertNode = useInsertNode(); const newNode = insertNode("menu", { x: 100, y: 200 }); ``` ``` -------------------------------- ### Commit Changes Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/README.md Commit your changes with a descriptive message when contributing. ```git git commit -m 'Add some AmazingFeature' ``` -------------------------------- ### actions.setIncomingNodeMetadetails Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/api-reference-stores.md Sets metadata about the connection that triggered the edge drop. This is useful for passing context about the connection to the new node. ```APIDOC ## actions.setIncomingNodeMetadetails(detail) ### Description Sets metadata about the connection that triggered the edge drop. This action updates the `incomingNodeMetadetails` state with information about the connection, which can be used to configure the newly added node. ### Method ```typescript setIncomingNodeMetadetails(detail: FinalConnectionState | null): void ``` ### Parameters #### Path Parameters - **detail** (FinalConnectionState | null) - Yes - Connection state from React Flow or null ``` -------------------------------- ### Map Available Nodes to Buttons Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/INDEX.md Iterates through available nodes and renders a button for each, displaying its title. This is useful for creating UI elements that represent selectable nodes. ```typescript import { AVAILABLE_NODES } from "@/components/flow-builder/components/blocks"; AVAILABLE_NODES.map(n => ( )) ``` -------------------------------- ### Workflow Saving Trigger Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/data-flow.md Describes the initial step when a user initiates the workflow saving process. ```text User clicks Save button └─> actions.saveWorkflow() called ├─> Get current workflow from store ├─> Set state: workflow = workflow ├─> Return workflow object: │ ├─> id: string │ ├─> name: string │ ├─> nodes: Node[] │ └─> edges: Edge[] ``` -------------------------------- ### actions.saveWorkflow() Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/api-reference-stores.md Saves the current workflow state and returns a serialized version of the workflow. ```APIDOC ## actions.saveWorkflow() ### Description Saves the current workflow state and returns the workflow object. ### Signature ```typescript saveWorkflow(): { id: string; name: string; nodes: Node[]; edges: Edge[]; } ``` ### Returns Serialized workflow object containing ID, name, nodes, and edges. ### Example ```typescript const workflow = actions.saveWorkflow(); console.log(`Workflow ${workflow.id} has ${workflow.nodes.length} nodes`); ``` ``` -------------------------------- ### Default Tags Array Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/types.md An array of predefined Tag objects, including 'marketing', 'support', 'lead', and 'new', each with a value, label, and color. ```typescript [ { value: "marketing", label: "Marketing", color: "#ef4444" }, { value: "support", label: "Support", color: "#ef4444" }, { value: "lead", label: "Lead", color: "#eab308" }, { value: "new", label: "New", color: "#22c55e" }, ] ``` -------------------------------- ### Node Creation: Node Insertion Logic Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/data-flow.md Details the `insertNode` function's logic, including position calculation, node data creation, and integration with React Flow's `addNodes`. ```typescript insertNode(type: BuilderNodeType, pos?: XYPosition) ├─> If no position, uses window center ├─> Deselects any previously selected nodes ├─> Calls createNodeWithDefaultData(type, data) │ ├─> Finds metadata for type from NODES registry │ ├─> Gets defaultData from metadata │ ├─> Creates node object with: │ │ ├─> id: nanoid() │ │ ├─> type: BuilderNodeType │ │ ├─> data: defaultData │ │ ├─> position: provided or calculated │ │ └─> selected: true │ └─> Returns complete Node object ├─> Calls addNodes() from React Flow └─> Returns created node ``` -------------------------------- ### Access Default Tags from Flow Store Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/configuration.md Demonstrates how to import and access the 'tags' property from the useFlowStore hook to retrieve default tags. ```typescript import { useFlowStore } from "@/stores/flow-store"; function TagManager() { const tags = useFlowStore((s) => s.tags); // Use tags... } ``` -------------------------------- ### Menu Node Default Data Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/configuration.md Sets the default configuration for a 'Menu' node, including a question and three predefined options. Each option has a unique ID and sequential internal IDs. ```typescript { question: null, options: [ { id: "generated-id-1", option: { id: 0, value: "Option 1" } }, { id: "generated-id-2", option: { id: 1, value: "Option 2" } }, { id: "generated-id-3", option: { id: 2, value: "Option 3" } } ] } ``` -------------------------------- ### actions.edges.setEdges Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/api-reference-stores.md Replaces all existing edges in the workflow with a new set of edges. Use this to completely update the edge configuration. ```APIDOC ## actions.edges.setEdges(edges) ### Description Replaces all edges in the workflow. ### Method Not applicable (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **edges** (Edge[]) - Yes - Array of edges to set ``` -------------------------------- ### actions.sidebar.panels.tags.createTag Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/api-reference-stores.md Adds a new tag to the workflow. The tag object should include value, label, and color properties. ```APIDOC ## actions.sidebar.panels.tags.createTag(tag) ### Description Adds a new tag. ### Method Not applicable (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **tag** (Tag) - Yes - Tag with value, label, and color properties ### Request Example ```typescript const { createTag } = useFlowStore((s) => s.actions.sidebar.panels.tags); createTag({ value: "urgent", label: "Urgent", color: "#ff0000" }); ``` ``` -------------------------------- ### Set Anchor Position Action Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/api-reference-stores.md Use this action to set the anchor position for the floating menu. Requires an object with x and y coordinates in pixels. ```typescript setAnchorPosition(position: { x: number; y: number }): void ``` -------------------------------- ### useFlowStore Hook Usage Source: https://github.com/nobruf/shadcn-next-workflows/blob/main/_autodocs/api-reference-stores.md Demonstrates how to access the flow state and actions from the useFlowStore hook within a React component. Used to display workflow information and trigger save actions. ```typescript import { useFlowStore } from "@/stores/flow-store"; function WorkflowComponent() { const { workflow, tags, actions } = useFlowStore(); const handleSaveWorkflow = () => { const saved = actions.saveWorkflow(); console.log("Saved workflow ID:", saved.id); }; return
Current nodes: {workflow.nodes.length}
; } ```