/* eslint-disable @typescript-eslint/no-explicit-any */ import { useState, useCallback } from 'react'; import type { SetStateAction, Dispatch } from 'react'; import { applyNodeChanges, applyEdgeChanges } from '../utils/changes'; import type { Node, NodeChange, Edge, EdgeChange } from '../types'; type ApplyChanges = (changes: ChangesType[], items: ItemType[]) => ItemType[]; type OnChange = (changes: ChangesType[]) => void; // returns a hook that can be used liked this: // const [nodes, setNodes, onNodesChange] = useNodesState(initialNodes); function createUseItemsState( applyChanges: ApplyChanges ): ( initialItems: Node[] ) => [Node[], Dispatch[]>>, OnChange]; function createUseItemsState( applyChanges: ApplyChanges ): ( initialItems: Edge[] ) => [Edge[], Dispatch[]>>, OnChange]; function createUseItemsState( applyChanges: ApplyChanges ): (initialItems: any[]) => [any[], Dispatch>, OnChange] { return (initialItems: any[]) => { const [items, setItems] = useState(initialItems); const onItemsChange = useCallback((changes: any[]) => setItems((items: any) => applyChanges(changes, items)), []); return [items, setItems, onItemsChange]; }; } export const useNodesState = createUseItemsState(applyNodeChanges); export const useEdgesState = createUseItemsState(applyEdgeChanges);