@ducor/react
Version:
admin template ui interface
55 lines (54 loc) • 2.2 kB
JavaScript
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
import { jsx as _jsx } from "react/jsx-runtime";
import { createContext, useContext, useState } from "react";
// Create the context with a default empty value
var MenuContext = createContext(undefined);
// Provider component
export var MenuProvider = function (_a) {
var children = _a.children;
var _b = useState([]), menu = _b[0], setMenu = _b[1];
// Function to add a new menu item
var addMenuItem = function (item, parentId) {
if (parentId) {
// Find the parent and add the item as a child
setMenu(function (prevMenu) {
return prevMenu.map(function (menuItem) {
return menuItem.id === parentId
? __assign(__assign({}, menuItem), { children: __spreadArray(__spreadArray([], (menuItem.children || []), true), [item], false) }) : menuItem;
});
});
}
else {
// Add to the root menu
setMenu(function (prevMenu) { return __spreadArray(__spreadArray([], prevMenu, true), [item], false); });
}
};
return (_jsx(MenuContext.Provider, { value: { menu: menu, addMenuItem: addMenuItem }, children: children }));
};
// Custom hook to use the MenuContext
export var useMenu = function () {
var context = useContext(MenuContext);
if (!context) {
throw new Error("useMenu must be used within a MenuProvider");
}
return context;
};