@base-ui/react
Version:
Base UI is a library of headless ('unstyled') React components and low-level hooks. You gain complete control over your app's CSS and accessibility features.
47 lines (44 loc) • 1.6 kB
JavaScript
'use client';
import { useId } from '@base-ui/utils/useId';
import { useIsoLayoutEffect } from '@base-ui/utils/useIsoLayoutEffect';
import { useToastRootContext } from "../root/ToastRootContext.mjs";
import { hasRenderableChildren } from "./isRenderableNode.mjs";
/**
* Shared logic for `Toast.Title` and `Toast.Description`, which only differ by the rendered tag,
* the fallback content, and which id setter they register with. Resolves the content and returns
* the pieces each part passes to `useRenderElement` and `useToastLabelElement`.
*/
export function useToastLabelPart(idProp, childrenProp, part) {
const {
toast,
setTitleId,
setDescriptionId
} = useToastRootContext();
const setId = part === 'title' ? setTitleId : setDescriptionId;
const children = childrenProp ?? (part === 'title' ? toast.title : toast.description);
const id = useId(idProp);
return {
id,
children,
type: toast.type,
setId
};
}
/**
* Mounts the evaluated label element only when it carries renderable content (so a `render` prop's
* own children count, while a childless styling-only `render` stays conditional), registering the
* generated id with the root while the part renders.
*/
export function useToastLabelElement(element, id, setId) {
const shouldRender = hasRenderableChildren(element);
useIsoLayoutEffect(() => {
if (!shouldRender) {
return undefined;
}
setId(id);
return () => {
setId(currentId => currentId === id ? undefined : currentId);
};
}, [shouldRender, id, setId]);
return shouldRender ? element : null;
}