import * as stylex from "@stylexjs/stylex";
import { createContext, useContext } from "react";
import {
Dialog as UiSdkDialog,
DialogBackdrop,
DialogClose,
DialogContent,
DialogDescription,
DialogTitle,
DialogTrigger,
} from "@ui-sdk/react/dialog";
import { createSlotRecipeContext } from "#lib/ui-sdk/create-slot-recipe-context.tsx";
import {
defineSlotRecipe,
fromMap,
resolveSlotStyles,
type StyleOverrideProps,
} from "#lib/recipe-props.ts";
import { semanticShadows } from "@stylexblocks/ui/semantic-tokens/shadows.stylex.ts";
import { durations } from '@stylexblocks/ui/tokens/durations.stylex.ts'
import { fontSizes } from '@stylexblocks/ui/tokens/font-sizes.stylex.ts'
import { fontWeights } from '@stylexblocks/ui/tokens/font-weights.stylex.ts'
import { lineHeights } from '@stylexblocks/ui/tokens/line-heights.stylex.ts'
import { semanticColors } from '@stylexblocks/ui/semantic-tokens/colors.stylex.ts'
import { semanticRadii } from '@stylexblocks/ui/semantic-tokens/radii.stylex.ts'
import { sizes } from '@stylexblocks/ui/tokens/sizes.stylex.ts'
import { spacing } from '@stylexblocks/ui/tokens/spacing.stylex.ts'
import { zIndices } from '@stylexblocks/ui/tokens/z-indices.stylex.ts'
const dialogBackdrop = stylex.create({
base: {
position: 'fixed',
left: 0,
top: 0,
width: '100vw',
height: '100dvh',
zIndex: zIndices.layer4,
animationName: {
default: null,
':is([data-open], [data-state="open"])': 'fade-in',
':is([data-closed], [data-state="closed"])': 'fade-out',
},
animationDuration: {
default: null,
':is([data-open], [data-state="open"])': durations.moderate,
':is([data-closed], [data-state="closed"])': durations.faster,
},
},
})
const dialogPositioner = stylex.create({
base: {
display: 'flex',
width: '100vw',
height: '100dvh',
position: 'fixed',
left: 0,
top: 0,
'--dialog-z-index': zIndices.layer4,
zIndex: 'calc(var(--dialog-z-index) + var(--layer-index, 0))',
justifyContent: 'center',
},
})
const dialogPositionerSizes = stylex.create({
cover: {
padding: spacing._10,
},
})
const dialogPositionerPlacements = stylex.create({
center: {
alignItems: 'center',
},
top: {
alignItems: 'flex-start',
},
bottom: {
alignItems: 'flex-end',
},
})
const dialogPositionerScrollBehaviors = stylex.create({
inside: {
overflow: 'hidden',
},
outside: {
overflow: 'auto',
pointerEvents: 'auto',
},
})
const dialogContent = stylex.create({
base: {
display: 'flex',
flexDirection: 'column',
position: 'relative',
width: '100%',
outline: 'none',
fontSize: fontSizes.sm,
lineHeight: lineHeights.sm,
marginBlock: 'var(--dialog-margin, var(--dialog-base-margin))',
zIndex: 'calc(var(--dialog-z-index) + var(--layer-index, 0))',
'--dialog-padding': spacing._6,
'--dialog-radius': semanticRadii.panel,
'--dialog-concentric-radius':
'max(0px, calc(var(--dialog-radius) - var(--dialog-padding)))',
animationDuration: {
default: null,
':is([data-open], [data-state="open"])': durations.moderate,
':is([data-closed], [data-state="closed"])': durations.faster,
},
},
})
const dialogContentSizes = stylex.create({
xs: {
maxWidth: sizes.sm,
},
sm: {
maxWidth: sizes.md,
},
md: {
maxWidth: sizes.lg,
},
lg: {
maxWidth: '2xl',
},
xl: {
maxWidth: '4xl',
},
cover: {
width: '100%',
height: '100%',
'--dialog-margin': '0',
},
full: {
maxWidth: '100vw',
minHeight: '100vh',
'--dialog-margin': '0',
'--dialog-radius': '0px',
borderRadius: 0,
},
})
const dialogContentVariants = stylex.create({
confirm: {
textAlign: 'center',
},
})
const dialogContentPlacements = stylex.create({
center: {
'--dialog-base-margin': 'auto',
marginInline: 'auto',
},
top: {
'--dialog-base-margin': spacing._16,
marginInline: 'auto',
},
bottom: {
'--dialog-base-margin': spacing._16,
marginInline: 'auto',
},
})
const dialogContentScrollBehaviors = stylex.create({
inside: {
maxHeight: 'calc(100% - 7.5rem)',
},
})
const dialogContentMotionPresets = stylex.create({
scale: {
animationName: {
default: null,
':is([data-open], [data-state="open"])': 'scale-in, fade-in',
':is([data-closed], [data-state="closed"])': 'scale-out, fade-out',
},
},
'slide-in-bottom': {
animationName: {
default: null,
':is([data-open], [data-state="open"])': 'slide-from-bottom, fade-in',
':is([data-closed], [data-state="closed"])': 'slide-to-bottom, fade-out',
},
},
'slide-in-top': {
animationName: {
default: null,
':is([data-open], [data-state="open"])': 'slide-from-top, fade-in',
':is([data-closed], [data-state="closed"])': 'slide-to-top, fade-out',
},
},
'slide-in-left': {
animationName: {
default: null,
':is([data-open], [data-state="open"])': 'slide-from-left, fade-in',
':is([data-closed], [data-state="closed"])': 'slide-to-left, fade-out',
},
},
'slide-in-right': {
animationName: {
default: null,
':is([data-open], [data-state="open"])': 'slide-from-right, fade-in',
':is([data-closed], [data-state="closed"])': 'slide-to-right, fade-out',
},
},
})
const dialogHeader = stylex.create({
base: {
display: 'flex',
flex: 0,
paddingInline: spacing._6,
paddingBlock: spacing._4,
paddingBottom: spacing._2,
},
})
const dialogHeaderVariants = stylex.create({
confirm: {
flexDirection: 'column',
alignItems: 'center',
},
})
const dialogBody = stylex.create({
base: {
flex: 1,
paddingInline: spacing._6,
paddingBlock: spacing._4,
},
})
const dialogBodyScrollBehaviors = stylex.create({
inside: {
overflow: 'auto',
},
})
const dialogFooter = stylex.create({
base: {
display: 'flex',
alignItems: 'center',
justifyContent: 'flex-end',
gap: spacing._3,
paddingInline: spacing._6,
paddingTop: spacing._2,
paddingBottom: spacing._4,
},
})
const dialogFooterVariants = stylex.create({
confirm: {
display: 'flex',
flexDirection: 'column-reverse',
justifyContent: 'stretch',
alignItems: 'stretch',
},
})
const dialogTitle = stylex.create({
base: {
fontSize: fontSizes.lg,
lineHeight: lineHeights.lg,
fontWeight: fontWeights.medium,
},
})
const dialogDescription = stylex.create({
base: {
color: semanticColors.fgMuted,
},
})
const dialogCloseTrigger = stylex.create({
base: {
position: 'absolute',
top: spacing._4,
right: spacing._4,
},
})
export type DialogVariant = keyof typeof dialogContentVariants
export type DialogPlacement = keyof typeof dialogPositionerPlacements
export type DialogScrollBehavior = keyof typeof dialogPositionerScrollBehaviors
export type DialogSize = keyof typeof dialogPositionerSizes
export type DialogMotionPreset = keyof typeof dialogContentMotionPresets
// defineSlotRecipe validates the shape at compile time: default values must
// exist in the axis maps, and slot keys must be `styles` or a declared axis.
// Axis maps are looked up by pluralized axis name (`placement` → `placements`).
const dialogRecipe = defineSlotRecipe({
slots: {
backdrop: { styles: dialogBackdrop },
positioner: {
styles: dialogPositioner,
sizes: dialogPositionerSizes,
placements: dialogPositionerPlacements,
scrollBehaviors: dialogPositionerScrollBehaviors,
},
content: {
styles: dialogContent,
sizes: dialogContentSizes,
placements: dialogContentPlacements,
scrollBehaviors: dialogContentScrollBehaviors,
motionPresets: dialogContentMotionPresets,
},
header: { styles: dialogHeader },
body: { styles: dialogBody, scrollBehaviors: dialogBodyScrollBehaviors },
footer: { styles: dialogFooter },
title: { styles: dialogTitle },
description: { styles: dialogDescription },
closeTrigger: { styles: dialogCloseTrigger },
},
defaultVariants: {
size: "md",
placement: "top",
scrollBehavior: "outside",
motionPreset: "scale",
},
});
// Local chrome the recipe leaves to the composition layer: the backdrop's
// fixed fill + wash and the panel's surface (plus real max-widths for the
// `lg`/`xl` steps, whose generated values are Chakra size names).
const chrome = stylex.create({
backdrop: {
position: "fixed",
top: 0,
right: 0,
bottom: 0,
left: 0,
backgroundColor: semanticColors.bgBackdrop,
},
content: {
backgroundColor: semanticColors.bgPanel,
borderRadius: "var(--dialog-radius)",
boxShadow: semanticShadows.overlay,
},
});
// Contained preview mode: keeps the backdrop and panel scoped inside the
// nearest `position: relative` ancestor (paired with `inline` on
// DialogContent so UI SDK skips the browser top layer).
const containedStyles = stylex.create({
backdrop: {
position: "absolute",
top: 0,
right: 0,
bottom: 0,
left: 0,
width: "100%",
height: "100%",
zIndex: 20,
},
content: {
position: "absolute",
zIndex: 30,
},
contentOutside: {
maxHeight: "calc(100% - 2 * var(--dialog-margin, 2rem))",
},
contentInside: {
maxHeight: "calc(100% - 2.5rem)",
},
contentFull: {
maxWidth: "100%",
minHeight: "100%",
},
});
// UI SDK's Description renders a `p` (Ark's is a `div`): drop the UA margins.
const description = stylex.create({
reset: { margin: 0 },
});
const contentSizeFix = stylex.create({
lg: { maxWidth: "42rem" },
xl: { maxWidth: "56rem" },
});
// UI SDK's content is itself the top-layer `[popover]` element, so a wrapper
// positioner can't lay it out. These styles do the positioner's job on the
// content: fixed to the viewport, centered inline by the recipe's
// `marginInline: auto`, and pinned per placement (the recipe's block margins
// then give the top/bottom gap, or `auto` centers it).
const topLayer = stylex.create({
base: {
position: "fixed",
insetInline: 0,
height: "fit-content",
},
// `outside` lets the Ark/Base positioner scroll a tall dialog; here the
// panel itself scrolls within the viewport minus its block margins.
outside: {
maxHeight: "calc(100dvh - 2 * var(--dialog-margin, 4rem))",
overflowY: "auto",
},
inside: {},
});
const topLayerPlacements = stylex.create({
center: { top: 0, bottom: 0 },
top: { top: 0, bottom: "auto" },
bottom: { top: "auto", bottom: 0 },
});
const topLayerSizes = stylex.create({
cover: {
inset: "2.5rem",
width: "auto",
height: "auto",
maxHeight: "none",
},
full: {
inset: 0,
height: "auto",
maxHeight: "none",
},
});
const { withRootProvider, withContext, VariantContext } =
createSlotRecipeContext(dialogRecipe);
const ContainedContext = createContext(false);
const BaseRoot = withRootProvider(UiSdkDialog, "DialogRoot");
function Root({
contained = false,
modal,
closeOnOutsidePress,
placement,
...rest
}: React.ComponentProps<typeof BaseRoot> & { contained?: boolean }) {
const resolvedModal = modal ?? (contained ? false : undefined);
const resolvedCloseOnOutsidePress =
closeOnOutsidePress ?? (contained ? false : undefined);
const resolvedPlacement = placement ?? (contained ? "center" : undefined);
return (
<ContainedContext.Provider value={contained}>
<BaseRoot
{...rest}
modal={resolvedModal}
closeOnOutsidePress={resolvedCloseOnOutsidePress}
placement={resolvedPlacement}
/>
</ContainedContext.Provider>
);
}
Root.displayName = "DialogRoot";
const BackdropElement = DialogBackdrop as React.ElementType;
function Backdrop(
allProps: Omit<React.ComponentProps<typeof DialogBackdrop>, "style"> &
StyleOverrideProps,
) {
const { palette, style, className, ...rest } = allProps as Record<string, unknown>;
const v = useContext(VariantContext);
const contained = useContext(ContainedContext);
const baseBackdrop = chrome.backdrop;
const containedBackdrop = contained ? containedStyles.backdrop : null;
const sx = stylex.props(
...([
palette,
...resolveSlotStyles(dialogRecipe.slots.backdrop, v),
baseBackdrop,
containedBackdrop,
style,
] as unknown as ReadonlyArray<never>),
);
return (
<BackdropElement
{...rest}
className={
typeof className === "string" && className.length > 0
? [sx.className, className].filter(Boolean).join(" ")
: sx.className
}
style={sx.style}
/>
);
}
Backdrop.displayName = "DialogBackdrop";
const ContentElement = DialogContent as React.ElementType;
/**
* UI SDK's content opens in the browser's top layer, so there is no
* positioner part: Content carries the recipe's content slot plus the
* positioner's placement, size and scroll behavior. When `contained` is set
* on `Dialog.Root`, Content switches to `position: absolute` inside its
* nearest `position: relative` ancestor and skips the browser top layer.
*/
function Content(
allProps: Omit<React.ComponentProps<typeof DialogContent>, "style"> & StyleOverrideProps,
) {
const { palette, style, className, inline, initialFocus, ...rest } = allProps as Record<
string,
unknown
>;
const v = useContext(VariantContext);
const contained = useContext(ContainedContext);
// Resolved outside the stylex.props spread: StyleX drops a create() whose
// only use sits inside the cast spread, leaving a dangling reference.
const sizeFix = fromMap(contentSizeFix, v.size);
const base = topLayer.base;
const scroll = fromMap(topLayer, v.scrollBehavior);
const placement = fromMap(topLayerPlacements, v.placement);
const size = fromMap(topLayerSizes, v.size);
const containedBase = contained ? containedStyles.content : null;
const containedScroll = contained
? v.scrollBehavior === "inside"
? containedStyles.contentInside
: containedStyles.contentOutside
: null;
const containedFull = contained && v.size === "full" ? containedStyles.contentFull : null;
const sx = stylex.props(
...([
palette,
...resolveSlotStyles(dialogRecipe.slots.content, v),
chrome.content,
sizeFix,
base,
scroll,
placement,
size,
containedBase,
containedScroll,
containedFull,
style,
] as unknown as ReadonlyArray<never>),
);
return (
<ContentElement
{...rest}
inline={inline ?? (contained ? true : undefined)}
initialFocus={initialFocus ?? (contained ? "none" : undefined)}
className={
typeof className === "string" && className.length > 0
? [sx.className, className].filter(Boolean).join(" ")
: sx.className
}
style={sx.style}
/>
);
}
Content.displayName = "DialogContent";
/**
* Dialog — UI SDK's dialog wearing the dialog slot recipe: the content opens
* in the browser's top layer (no Portal or Positioner needed), traps focus,
* makes the page inert, and waits for the recipe's exit animation before it
* unmounts. `<Dialog.Root size placement scrollBehavior>` resolves the recipe
* once; every part inherits the variants through context and composes via
* `render`. Pass `contained` to scope the backdrop and panel inside a
* `position: relative` preview container.
*/
export const Dialog = {
Root,
Trigger: DialogTrigger,
Backdrop,
Content,
Header: withContext("div", "header", "DialogHeader"),
Body: withContext("div", "body", "DialogBody"),
Footer: withContext("div", "footer", "DialogFooter"),
Title: withContext(DialogTitle, "title", "DialogTitle"),
Description: withContext(
DialogDescription,
(v) => [...resolveSlotStyles(dialogRecipe.slots.description, v), description.reset],
"DialogDescription",
),
Close: withContext(DialogClose, "closeTrigger", "DialogClose"),
};