ra-core
Version:
Core components of react-admin, a frontend Framework for building admin applications on top of REST services, using ES6, React
313 lines • 15.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 __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.useConfigureAdminRouterFromChildren = void 0;
var React = __importStar(require("react"));
var react_1 = require("react");
var useLogout_1 = __importDefault(require("../auth/useLogout"));
var usePermissions_1 = __importDefault(require("../auth/usePermissions"));
var useResourceDefinitionContext_1 = require("./useResourceDefinitionContext");
/**
* This hook inspects the CoreAdminRouter children and returns them separated in three groups:
* - Custom routes without layout
* - Custom routes with layout
* - Resources
*
* It also returns a status:
* - loading: still loading children from a function child
* - empty: no resources were provided among children
* - ready: admin is ready to be rendered
*
* @example
* const {
* customRoutesWithLayout,
* customRoutesWithoutLayout,
* resources,
* status,
* } = useConfigureAdminRouterFromChildren(children);
*/
var useConfigureAdminRouterFromChildren = function (children) {
var _a = (0, usePermissions_1.default)(), permissions = _a.permissions, isPending = _a.isPending;
// Whenever children are updated, update our custom routes and resources
var _b = useRoutesAndResourcesFromChildren(children, permissions, isPending), routesAndResources = _b[0], status = _b[1];
// Whenever the resources change, we must ensure they're all registered
useRegisterResources(routesAndResources.resources, permissions);
return {
customRoutesWithLayout: routesAndResources.customRoutesWithLayout,
customRoutesWithoutLayout: routesAndResources.customRoutesWithoutLayout,
status: status,
resources: routesAndResources.resources,
};
};
exports.useConfigureAdminRouterFromChildren = useConfigureAdminRouterFromChildren;
/**
* A hook that determine the routes and resources from React nodes and permissions.
* Returns a tuple with the routes and resources as a single object, and the status.
* @param children React nodes to inspect
* @param permissions The permissions
*/
var useRoutesAndResourcesFromChildren = function (children, permissions, isLoading) {
// Gather custom routes and resources that were declared as direct children of CoreAdminRouter
// e.g. Not returned from the child function (if any)
// We need to know right away whether some resources were declared to correctly
// initialize the status at the next stop
var doLogout = (0, useLogout_1.default)();
var _a = useRoutesAndResourcesState(getRoutesAndResourceFromNodes(children)), routesAndResources = _a[0], setRoutesAndResources = _a[1], mergeRoutesAndResources = _a[2];
var _b = (0, react_1.useState)(function () {
return getStatus(__assign({ children: children }, routesAndResources));
}), status = _b[0], setStatus = _b[1];
if (!status) {
throw new Error('Status should be defined');
}
(0, react_1.useEffect)(function () {
var resolveChildFunction = function (childFunc) { return __awaiter(void 0, void 0, void 0, function () {
var childrenFuncResult;
return __generator(this, function (_a) {
try {
childrenFuncResult = childFunc(permissions);
if (childrenFuncResult === null || childrenFuncResult === void 0 ? void 0 : childrenFuncResult.then) {
childrenFuncResult.then(function (resolvedChildren) {
mergeRoutesAndResources(getRoutesAndResourceFromNodes(resolvedChildren));
setStatus('ready');
});
}
else {
mergeRoutesAndResources(getRoutesAndResourceFromNodes(childrenFuncResult));
setStatus('ready');
}
}
catch (error) {
console.error(error);
doLogout();
}
return [2 /*return*/];
});
}); };
var updateFromChildren = function () { return __awaiter(void 0, void 0, void 0, function () {
var functionChild, newRoutesAndResources;
return __generator(this, function (_a) {
functionChild = getSingleChildFunction(children);
newRoutesAndResources = getRoutesAndResourceFromNodes(children);
setRoutesAndResources(newRoutesAndResources);
setStatus(functionChild
? 'loading'
: newRoutesAndResources.resources.length > 0 ||
newRoutesAndResources.customRoutesWithLayout.length >
0 ||
newRoutesAndResources.customRoutesWithoutLayout.length >
0
? 'ready'
: 'empty');
if (functionChild) {
resolveChildFunction(functionChild);
}
return [2 /*return*/];
});
}); };
if (!isLoading) {
updateFromChildren();
}
}, [
children,
doLogout,
isLoading,
mergeRoutesAndResources,
permissions,
setRoutesAndResources,
setStatus,
]);
return [routesAndResources, status];
};
/*
* A hook that store the routes and resources just like setState but also provides an additional function
* to merge new routes and resources with the existing ones.
*/
var useRoutesAndResourcesState = function (initialState) {
var _a = (0, react_1.useState)(initialState), routesAndResources = _a[0], setRoutesAndResources = _a[1];
var mergeRoutesAndResources = (0, react_1.useCallback)(function (newRoutesAndResources) {
setRoutesAndResources(function (previous) { return ({
customRoutesWithLayout: previous.customRoutesWithLayout.concat(newRoutesAndResources.customRoutesWithLayout),
customRoutesWithoutLayout: previous.customRoutesWithoutLayout.concat(newRoutesAndResources.customRoutesWithoutLayout),
resources: previous.resources.concat(newRoutesAndResources.resources),
}); });
}, []);
return [routesAndResources, setRoutesAndResources, mergeRoutesAndResources];
};
/**
* A hook that register resources and unregister them when the calling component is unmounted.
* @param resources: An array of Resource elements
* @param permissions: The permissions
*/
var useRegisterResources = function (resources, permissions) {
var _a = (0, useResourceDefinitionContext_1.useResourceDefinitionContext)(), register = _a.register, unregister = _a.unregister;
(0, react_1.useEffect)(function () {
resources.forEach(function (resource) {
if (typeof resource.type.registerResource === 'function') {
var definition = resource.type.registerResource(resource.props, permissions);
register(definition);
}
else {
throw new Error('When using a custom Resource element, it must have a static registerResource method accepting its props and returning a ResourceDefinition');
}
});
return function () {
resources.forEach(function (resource) {
if (typeof resource.type.registerResource === 'function') {
var definition = resource.type.registerResource(resource.props, permissions);
unregister(definition);
}
else {
throw new Error('When using a custom Resource element, it must have a static registerResource method accepting its props and returning a ResourceDefinition');
}
});
};
}, [permissions, register, resources, unregister]);
};
var getStatus = function (_a) {
var children = _a.children, resources = _a.resources, customRoutesWithLayout = _a.customRoutesWithLayout, customRoutesWithoutLayout = _a.customRoutesWithoutLayout;
return getSingleChildFunction(children)
? 'loading'
: resources.length > 0 ||
customRoutesWithLayout.length > 0 ||
customRoutesWithoutLayout.length > 0
? 'ready'
: 'empty';
};
/**
* Inspect the children of a CoreAdminRouter to see if one of them is a function.
* Throws an error if there are more than one function child.
* Returns the function child if one was provided, or null otherwise.
*/
var getSingleChildFunction = function (children) {
var childrenArray = Array.isArray(children) ? children : [children];
var functionChildren = childrenArray.filter(function (child) { return typeof child === 'function'; });
if (functionChildren.length > 1) {
throw new Error('You can only provide one function child to AdminRouter');
}
if (functionChildren.length === 0) {
return null;
}
return functionChildren[0];
};
/**
* Inspect the children and return an object with the following keys:
* - customRoutesWithLayout: an array of the custom routes to render inside the layout
* - customRoutesWithoutLayout: an array of custom routes to render outside the layout
* - resources: an array of resources elements
*/
var getRoutesAndResourceFromNodes = function (children) {
var customRoutesWithLayout = [];
var customRoutesWithoutLayout = [];
var resources = [];
if (typeof children === 'function') {
return {
customRoutesWithLayout: [],
customRoutesWithoutLayout: [],
resources: [],
};
}
// @ts-ignore
react_1.Children.forEach(children, function (element) {
if (!React.isValidElement(element)) {
// Ignore non-elements. This allows people to more easily inline
// conditionals in their route config.
return;
}
if (element.type === react_1.Fragment) {
var customRoutesFromFragment = getRoutesAndResourceFromNodes(element.props.children);
customRoutesWithLayout.push.apply(customRoutesWithLayout, customRoutesFromFragment.customRoutesWithLayout);
customRoutesWithoutLayout.push.apply(customRoutesWithoutLayout, customRoutesFromFragment.customRoutesWithoutLayout);
resources.push.apply(resources, customRoutesFromFragment.resources);
}
if (element.type.raName === 'CustomRoutes') {
var customRoutesElement = element;
if (customRoutesElement.props.noLayout) {
customRoutesWithoutLayout.push(customRoutesElement.props.children);
}
else {
customRoutesWithLayout.push(customRoutesElement.props.children);
}
}
else if (element.type.raName === 'Resource') {
resources.push(element);
}
});
return {
customRoutesWithLayout: customRoutesWithLayout,
customRoutesWithoutLayout: customRoutesWithoutLayout,
resources: resources,
};
};
//# sourceMappingURL=useConfigureAdminRouterFromChildren.js.map
;