@mantine/form
Version:
Mantine form management library
53 lines (52 loc) • 2.32 kB
JavaScript
"use client";
require("../../_virtual/_rolldown/runtime.cjs");
const require_get_path = require("../../paths/get-path.cjs");
let react = require("react");
//#region packages/@mantine/form/src/hooks/use-form-watch/use-form-watch.ts
function useFormWatch({ $values, $status, cascadeUpdates }) {
const subscribers = (0, react.useRef)({});
return {
subscribers,
watch: (0, react.useCallback)((path, callback) => {
(0, react.useEffect)(() => {
subscribers.current[path] = subscribers.current[path] || [];
subscribers.current[path].push(callback);
return () => {
subscribers.current[path] = subscribers.current[path].filter((cb) => cb !== callback);
};
}, [callback]);
}, []),
getFieldSubscribers: (0, react.useCallback)((path) => {
const result = subscribers.current[path]?.map((callback) => (input) => callback({
previousValue: require_get_path.getPath(path, input.previousValues),
value: require_get_path.getPath(path, input.updatedValues),
touched: $status.isTouched(path),
dirty: $status.isDirty(path)
})) ?? [];
for (const subscriptionKey in subscribers.current) {
const isParent = String(path).startsWith(`${subscriptionKey}.`);
const isChild = String(subscriptionKey).startsWith(`${path}.`);
if (isParent || cascadeUpdates && isChild) result.push(...subscribers.current[subscriptionKey].map((cb) => (input) => cb({
previousValue: require_get_path.getPath(subscriptionKey, input.previousValues),
value: require_get_path.getPath(subscriptionKey, input.updatedValues),
touched: $status.isTouched(subscriptionKey),
dirty: $status.isDirty(subscriptionKey)
})));
}
return result;
}, []),
notifyWatchSubscribers: (0, react.useCallback)((previousValues) => {
Object.keys(subscribers.current).forEach((path) => {
if (require_get_path.getPath(path, $values.refValues.current) !== require_get_path.getPath(path, previousValues)) subscribers.current[path]?.forEach((cb) => cb({
previousValue: require_get_path.getPath(path, previousValues),
value: require_get_path.getPath(path, $values.refValues.current),
touched: $status.isTouched(path),
dirty: $status.isDirty(path)
}));
});
}, [])
};
}
//#endregion
exports.useFormWatch = useFormWatch;
//# sourceMappingURL=use-form-watch.cjs.map