@dnb/eufemia
Version:
DNB Eufemia Design System UI Library
88 lines (87 loc) • 3.16 kB
JavaScript
;
"use client";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = useDependencePaths;
var _react = require("react");
var _index = _interopRequireDefault(require("../../utils/json-pointer/index.js"));
var _Context = _interopRequireDefault(require("../../DataContext/Context.js"));
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function useDependencePaths(dependencePaths, propagateIndeterminateState) {
const {
internalDataRef,
fieldInternalsRef,
handlePathChange,
subscribeDataValue
} = (0, _react.useContext)(_Context.default) || {};
const snapshotVersionRef = (0, _react.useRef)(0);
const subscribe = (0, _react.useCallback)(callback => {
if (!dependencePaths?.length || !subscribeDataValue) {
return () => undefined;
}
const handleUpdate = () => {
snapshotVersionRef.current += 1;
callback();
};
const unsubscribers = dependencePaths.map(path => subscribeDataValue(path, handleUpdate));
return () => {
unsubscribers.forEach(unsubscribe => unsubscribe());
};
}, [dependencePaths, subscribeDataValue]);
const getSnapshot = (0, _react.useCallback)(() => snapshotVersionRef.current, []);
(0, _react.useSyncExternalStore)(subscribe, getSnapshot, getSnapshot);
const data = internalDataRef?.current;
const ariaControlsIds = dependencePaths?.map(path => fieldInternalsRef?.current?.[path]?.id).filter(Boolean).join(' ') || undefined;
const check = ({
key,
whenUndefined = false
}) => {
if (!dependencePaths || !data) {
return undefined;
}
return dependencePaths.every(path => {
if (_index.default.has(data, path)) {
const value = _index.default.get(data, path);
if ((whenUndefined ? typeof value === 'undefined' : false) || value === fieldInternalsRef?.current?.[path]?.props?.[key]) {
return true;
}
}
return undefined;
});
};
const allOn = check({
key: 'valueOn'
});
const allOff = check({
key: 'valueOff',
whenUndefined: true
});
const indeterminate = data ? !allOn && !allOff : undefined;
const keepStateRef = (0, _react.useRef)(undefined);
(0, _react.useMemo)(() => {
if (allOn && !keepStateRef.current) {
keepStateRef.current = true;
} else if (allOff && keepStateRef.current) {
keepStateRef.current = false;
} else {
if (propagateIndeterminateState !== 'auto' && indeterminate) {
keepStateRef.current = propagateIndeterminateState === 'unchecked';
}
}
}, [allOn, allOff, propagateIndeterminateState, indeterminate]);
const setAllStates = (0, _react.useCallback)(checked => {
dependencePaths?.forEach(path => {
const fieldProp = checked ? 'valueOn' : 'valueOff';
const value = fieldInternalsRef?.current?.[path]?.props?.[fieldProp];
handlePathChange?.(path, value);
});
}, [dependencePaths, fieldInternalsRef, handlePathChange]);
return {
setAllStates,
indeterminate,
internalValue: keepStateRef.current,
ariaControlsIds
};
}
//# sourceMappingURL=useDependencePaths.js.map