94 lines
2.9 KiB
Plaintext
94 lines
2.9 KiB
Plaintext
"use client";
|
|
|
|
// src/utils.ts
|
|
import { useContext, useMemo, useRef, useCallback } from "react";
|
|
import { mergeProps, mergeRefs } from "@heroui/shared-utils";
|
|
var DEFAULT_SLOT = Symbol("default");
|
|
function useObjectRef(ref) {
|
|
const objRef = useRef(null);
|
|
const cleanupRef = useRef(void 0);
|
|
const refEffect = useCallback(
|
|
(instance) => {
|
|
if (typeof ref === "function") {
|
|
const refCallback = ref;
|
|
const refCleanup = refCallback(instance);
|
|
return () => {
|
|
if (typeof refCleanup === "function") {
|
|
refCleanup();
|
|
} else {
|
|
refCallback(null);
|
|
}
|
|
};
|
|
} else if (ref) {
|
|
ref.current = instance;
|
|
return () => {
|
|
ref.current = null;
|
|
};
|
|
}
|
|
},
|
|
[ref]
|
|
);
|
|
return useMemo(
|
|
() => ({
|
|
get current() {
|
|
return objRef.current;
|
|
},
|
|
set current(value) {
|
|
objRef.current = value;
|
|
if (cleanupRef.current) {
|
|
cleanupRef.current();
|
|
cleanupRef.current = void 0;
|
|
}
|
|
if (value != null) {
|
|
cleanupRef.current = refEffect(value);
|
|
}
|
|
}
|
|
}),
|
|
[refEffect]
|
|
);
|
|
}
|
|
function useSlottedContext(context, slot) {
|
|
let ctx = useContext(context);
|
|
if (slot === null) {
|
|
return null;
|
|
}
|
|
if (ctx && typeof ctx === "object" && "slots" in ctx && ctx.slots) {
|
|
let availableSlots = new Intl.ListFormat().format(Object.keys(ctx.slots).map((p) => `"${p}"`));
|
|
if (!slot && !ctx.slots[DEFAULT_SLOT]) {
|
|
throw new Error(`A slot prop is required. Valid slot names are ${availableSlots}.`);
|
|
}
|
|
let slotKey = slot || DEFAULT_SLOT;
|
|
if (!ctx.slots[slotKey]) {
|
|
throw new Error(`Invalid slot "${slot}". Valid slot names are ${availableSlots}.`);
|
|
}
|
|
return ctx.slots[slotKey];
|
|
}
|
|
return ctx;
|
|
}
|
|
function useContextProps(props, ref, context) {
|
|
let ctx = useSlottedContext(context, props.slot) || {};
|
|
let { ref: contextRef, ...contextProps } = ctx;
|
|
let mergedRef = useObjectRef(useMemo(() => mergeRefs(ref, contextRef), [ref, contextRef]));
|
|
let mergedProps = mergeProps(contextProps, props);
|
|
if ("style" in contextProps && contextProps.style && "style" in props && props.style) {
|
|
if (typeof contextProps.style === "function" || typeof props.style === "function") {
|
|
mergedProps.style = (renderProps) => {
|
|
let contextStyle = typeof contextProps.style === "function" ? contextProps.style(renderProps) : contextProps.style;
|
|
let defaultStyle = { ...renderProps.defaultStyle, ...contextStyle };
|
|
let style = typeof props.style === "function" ? props.style({ ...renderProps, defaultStyle }) : props.style;
|
|
return { ...defaultStyle, ...style };
|
|
};
|
|
} else {
|
|
mergedProps.style = { ...contextProps.style, ...props.style };
|
|
}
|
|
}
|
|
return [mergedProps, mergedRef];
|
|
}
|
|
|
|
export {
|
|
DEFAULT_SLOT,
|
|
useObjectRef,
|
|
useSlottedContext,
|
|
useContextProps
|
|
};
|