import { useState, useMemo, useImperativeHandle } from 'react'; import { Component } from 'components/types'; import { isArray } from 'utils/isType'; const useLayout = (modules: any[], layoutRef: any) => { // 初始化布局 const initialLayout = useMemo(() => { const initialTabs = {}; const initialExchanges = {}; const allModulesMap = {}; const handleModules = (_modules: any[]) => { for (let i = 0, len = _modules.length; i < len; i += 1) { const moduleItem = _modules[i]; const { uuid, type, modules: childModules } = moduleItem; allModulesMap[uuid] = moduleItem; if (isArray(childModules) && childModules.length) { if (type === Component.Basic.Layout.Type.tabs) { initialTabs[uuid] = childModules[0].uuid; } else if (type === Component.Basic.Layout.Type.exchange) { initialExchanges[uuid] = childModules[0].uuid; } handleModules(childModules); } } }; handleModules(modules); return { initialTabs, initialExchanges, allModulesMap, }; }, [modules]); const { initialTabs, initialExchanges, allModulesMap } = initialLayout; const [tabs, updateTabs] = useState(initialTabs); const [exchanges, updateExchanges] = useState(initialExchanges); const [covers, updateCovers] = useState([]); const [modals, updateModals] = useState([]); const [drawers, updateDrawers] = useState([]); // 更新布局状态 const setLayoutState = ( type: Component.Basic.Layout.Type | Component.Basic.Loader.Type, name: string, value: string | boolean, ) => { if (type === Component.Basic.Layout.Type.tabs) { const newTabs = { ...tabs, [name]: value }; updateTabs(newTabs); } else if (type === Component.Basic.Layout.Type.exchange) { const newExchanges = { ...exchanges, [name]: value }; updateExchanges(newExchanges); } else if (type === Component.Basic.Loader.Type.cover) { let newCovers = []; if (value) { newCovers = [...covers, name]; updateCovers(newCovers); } else { newCovers = covers.filter((cover: string) => (cover !== name)); updateCovers(newCovers); } } else if (type === Component.Basic.Loader.Type.modal) { let newModals = []; if (value) { newModals = [...modals, name]; updateModals(newModals); } else { newModals = modals.filter((modal: string) => (modal !== name)); updateModals(newModals); } } else if (type === Component.Basic.Loader.Type.drawer) { let newDrawers = []; if (value) { newDrawers = [...drawers, name]; updateDrawers(newDrawers); } else { newDrawers = drawers.filter((drawer: string) => (drawer !== name)); updateDrawers(newDrawers); } } }; useImperativeHandle(layoutRef, () => ({ setLayoutState, allModulesMap, // eslint-disable-next-line react-hooks/exhaustive-deps }), []); return { tabs, exchanges, covers, modals, drawers, allModulesMap, setLayoutState, }; }; export default useLayout;