@ducor/react
Version:
admin template ui interface
54 lines (53 loc) • 1.56 kB
JavaScript
import { jsx as _jsx } from "react/jsx-runtime";
import { createContext, useContext, useState } from "react";
export var ScopeContext = createContext(undefined);
var Scope = function (_a) {
var scope = _a.scope, children = _a.children;
var fieldMap = useState(new Map())[0];
// Name might be scoped
var parentScope = useContext(ScopeContext);
var newScope;
// Example:
// parentScope = undefined
// scope = father
// ==> father
if (typeof parentScope === 'undefined') {
newScope = scope;
}
// Example:
// parentScope.scope = father
// scope = bestFriend
// ==> father.bestFriend
else {
newScope = "".concat(parentScope.scope, ".").concat(scope);
}
_jsx(ScopeContext.Provider, { value: { scope: newScope, fieldMap: fieldMap }, children: children });
};
/* ----------------------- useScope ----------------------- */
export function useScope(name) {
var scopeCtx = useContext(ScopeContext);
if (!scopeCtx) {
return undefined;
}
// Example
// scope = "friends[0]"
// name = "friends[0]"
// return "friends[0]"
if (scopeCtx.scope === name) {
return name;
}
// Example
// scope = "friends[0]"
// name = "name"
// return "friends[0].name"
if (scopeCtx.scope && name) {
return "".concat(scopeCtx.scope, ".").concat(name);
}
// Return what was passed
if (name) {
return name;
}
// If nothing passed reuturn the scope
return scopeCtx.scope;
}
export default Scope;