ra-core
Version:
Core components of react-admin, a frontend Framework for building admin applications on top of REST services, using ES6, React
81 lines • 3.47 kB
JavaScript
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 * as React from 'react';
import { useMemo, useRef } from 'react';
import { FormGroupsContext, } from './FormGroupsContext';
/**
* This component provides functions through context to manage form groups,
* allowing to link or unlink an input to a group.
* @see FormGroupContextProvider
* @see useFormGroup
* @see useFormGroups
*/
export var FormGroupsProvider = function (_a) {
var children = _a.children;
var formGroups = useRef({});
var subscribers = useRef({});
var formContextValue = useMemo(function () { return ({
/**
* Register a subscriber function for the specified group. The subscriber
* will be called whenever the group content changes (fields added or removed).
*/
subscribe: function (group, subscriber) {
if (!subscribers.current[group]) {
subscribers.current[group] = [];
}
subscribers.current[group].push(subscriber);
return function () {
subscribers.current[group] = subscribers.current[group].filter(function (s) { return s !== subscriber; });
};
},
getGroupFields: function (name) { return formGroups.current[name] || []; },
registerGroup: function (name) {
formGroups.current[name] = formGroups.current[name] || [];
},
unregisterGroup: function (name) {
delete formGroups[name];
},
registerField: function (source, group) {
if (group != null) {
if (!(formGroups.current[group] || []).includes(source)) {
formGroups.current[group] = __spreadArray(__spreadArray([], (formGroups.current[group] || []), true), [
source,
], false);
// Notify subscribers that the group fields have changed
if (subscribers.current[group]) {
subscribers.current[group].forEach(function (subscriber) {
return subscriber();
});
}
}
}
},
unregisterField: function (source, group) {
if (group != null) {
if (!formGroups.current[group]) {
console.warn("Invalid form group ".concat(group));
}
else {
var fields = new Set(formGroups.current[group]);
fields.delete(source);
formGroups.current[group] = Array.from(fields);
// Notify subscribers that the group fields have changed
if (subscribers.current[group]) {
subscribers.current[group].forEach(function (subscriber) {
return subscriber();
});
}
}
}
},
}); }, []);
return (React.createElement(FormGroupsContext.Provider, { value: formContextValue }, children));
};
//# sourceMappingURL=FormGroupsProvider.js.map