@wordpress/compose
Version:
WordPress higher-order components (HOCs).
81 lines (79 loc) • 2.76 kB
JavaScript
;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// packages/compose/src/hooks/use-merge-refs/index.ts
var use_merge_refs_exports = {};
__export(use_merge_refs_exports, {
default: () => useMergeRefs
});
module.exports = __toCommonJS(use_merge_refs_exports);
var import_element = require("@wordpress/element");
function assignRef(ref, value) {
if (typeof ref === "function") {
const returned = ref(value);
return typeof returned === "function" ? returned : void 0;
} else if (ref && ref.hasOwnProperty("current")) {
ref.current = value;
}
return void 0;
}
function detachRef(ref, index, cleanups) {
const cleanup = cleanups[index];
if (cleanup) {
cleanups[index] = void 0;
cleanup();
} else {
assignRef(ref, null);
}
}
function useMergeRefs(refs) {
const elementRef = (0, import_element.useRef)(null);
const attachedRefsRef = (0, import_element.useRef)([]);
const currentRefsRef = (0, import_element.useRef)(refs);
const cleanupsRef = (0, import_element.useRef)([]);
currentRefsRef.current = refs;
(0, import_element.useLayoutEffect)(() => {
const element = elementRef.current;
if (element === null) {
return;
}
refs.forEach((ref, index) => {
const attachedRef = attachedRefsRef.current[index];
if (ref !== attachedRef) {
detachRef(attachedRef, index, cleanupsRef.current);
cleanupsRef.current[index] = assignRef(ref, element);
}
});
attachedRefsRef.current = refs;
}, refs);
return (0, import_element.useCallback)((value) => {
elementRef.current = value;
if (value === null) {
attachedRefsRef.current.forEach((ref, index) => {
detachRef(ref, index, cleanupsRef.current);
});
attachedRefsRef.current = [];
} else {
attachedRefsRef.current = currentRefsRef.current;
attachedRefsRef.current.forEach((ref, index) => {
cleanupsRef.current[index] = assignRef(ref, value);
});
}
}, []);
}
//# sourceMappingURL=index.cjs.map