Command palette

@yasinsensoy/web

Web · APIs and utilities

Utilities

Passes its props to its single child instead of rendering its own element.

19 exports

Import

import {
  Slot,
  cn,
  cx,
  composeRefs,
  useComposedRefs,
  mergeClasses,
  prefersReducedMotion,
  scrollBehavior,
  variants,
} from "@yasinsensoy/web";

Slot

componentServer component

Passes its props to its single child instead of rendering its own element. The asChild prop on components works through this; e.g. used to give a Button's look to a Next.js Link element.

Merge rules:

  • className values are merged with cn; the child's wins.
  • style objects are merged; the child's wins (CSS anchor names from both are kept).
  • Both event handlers starting with on run; the child's first.
  • aria-describedby ID lists are merged.
  • refs are merged.
  • For other props the child's value wins.
Slot({ children, ref, ...slotProps }: SlotProps): ReactElement<ChildProps, string | JSXElementConstructor<any>> | null

Examples

function Button({ asChild, ...props }: ButtonProps) {
  const Comp = asChild ? Slot : "button";
  return <Comp className="..." {...props} />;
}

<Button asChild>
  <Link href="/about">About</Link>
</Button>

cn

function

Conditionally joins class names and keeps only the last of conflicting Tailwind classes.

All components use it so their own classes can be safely overridden by a className passed from outside. Uses no external dependency; replaces the clsx + tailwind-merge pair.

cn(...inputs: ClassValue[]): string

Examples

cn("px-4 py-2", isActive && "bg-primary", { "opacity-50": disabled });
// => "px-4 py-2 bg-primary opacity-50"

cn("px-4 py-2 bg-primary", "bg-red-500 px-6");
// => "py-2 bg-red-500 px-6"

cx

function

Conditionally joins class names; does not resolve conflicts. Works like clsx and is faster than cn. Use it where you are sure there will be no conflicts.

cx(...inputs: ClassValue[]): string

Examples

cx("a", false && "b", ["c", { d: true }]); // => "a c d"

composeRefs

function

Combines several refs into a single ref callback. Used to attach both the component's own ref and the user's ref to one element. Supports React 19's ref cleanup functions.

composeRefs(...refs: PossibleRef<T>[]): RefCallback<T>

Examples

<div ref={composeRefs(localRef, props.ref)} />

Hook version of composeRefs. Returns the same callback as long as the refs do not change, so React does not reattach the ref on every render.

useComposedRefs(...refs: PossibleRef<T>[]): RefCallback<T>

Examples

function Input({ ref, ...props }: ComponentProps<"input">) {
  const localRef = useRef<HTMLInputElement>(null);
  return <input ref={useComposedRefs(localRef, ref)} {...props} />;
}

mergeClasses

function

Resolves conflicting Tailwind classes; of classes targeting the same property, only the last remains.

In Tailwind, which class wins depends on its order in the generated CSS, not in className. So the result of a combination like "px-4 px-2" is unpredictable. This function lets a className passed to a component safely override the component's own classes.

Scope: common groups of Tailwind v4's default utilities (spacing, sizing, color, typography, borders, layout, effects and transforms). Unknown classes are left untouched.

mergeClasses(className: string): string

Examples

mergeClasses("px-4 py-2 bg-primary hover:bg-primary/90 bg-red-500");
// => "px-4 py-2 hover:bg-primary/90 bg-red-500"

mergeClasses("px-4 p-2"); // => "p-2"
mergeClasses("p-2 px-4"); // => "p-2 px-4" (px partially overrides p)

Has the user turned on "reduce motion" in the OS? Returns false on the server and in environments without matchMedia.

prefersReducedMotion(): boolean

Examples

if (!prefersReducedMotion()) element.animate(...);

Scroll behavior for scrollTo / scrollIntoView: "auto" (instant) if motion is reduced, otherwise "smooth".

scrollBehavior(): ScrollBehavior

Examples

element.scrollIntoView({ block: "nearest", behavior: scrollBehavior() });

variants

function

Creates a typed function that generates classes from a component's variants. Same idea as class-variance-authority (cva), with no external dependency. Since the result is merged with cn, a className passed from outside overrides conflicting classes.

variants(config: VariantsConfig<V>): VariantsFunction<V>

Examples

const button = variants({
  base: "inline-flex items-center rounded-md font-medium",
  variants: {
    variant: {
      primary: "bg-primary text-primary-foreground",
      outline: "border border-input bg-background",
    },
    size: { sm: "h-8 px-3 text-sm", md: "h-10 px-4" },
    block: { true: "w-full" },
  },
  compoundVariants: [{ variant: "outline", size: "sm", className: "border-2" }],
  defaultVariants: { variant: "primary", size: "md" },
});

button({ size: "sm", block: true, className: "mt-2" });

// Type of the component props:
type ButtonVariants = VariantProps<typeof button>;

Placement of a floating element (Menu, Popover, Tooltip…) relative to its trigger: the side and the alignment on that side.

  • "auto": The component picks the best place itself and moves elsewhere if it does not fit on screen. Menu/Popover start below with left edges aligned; without room they align right or flip to the top. Tooltip starts centered on top.
  • "top", "bottom", "left", "right": Centered on that side (same as "top-center").
  • "bottom-left": Below; left edge aligned with the trigger's left edge, opening to the right. "bottom-right" aligns right edges, opening to the left. "top-left", "top-right" the same way on top.
  • "right-top": On the right; top edges aligned, opening downward. "right-bottom" aligns bottom edges, opening upward. "left-top", "left-bottom" the same way on the left.

If the chosen placement does not fit, it flips to the opposite side and/or alignment.

type Placement = "auto" | Side | `${"top" | "bottom"}-${"left" | "center" | "right"}` | `${"left" | "right"}-${"top" | "center" | "bottom"}`

Value types accepted by cn.

  • string and number are added as-is.
  • false, null, undefined and empty values other than 0 are ignored.
  • Arrays are flattened.
  • For objects, keys with truthy values are added.
type ClassValue = string | number | bigint | boolean | null | undefined | ClassValue[] | { readonly [className: string]: unknown; }

SlotProps

interface

Props of the Slot component.

Extends: HTMLAttributes<HTMLElement>

NameTypeDescription
children?ReactNodeA single React element to pass the props to.
ref?Ref<HTMLElement>Ref merged with the child's own ref.

Tone

type

Semantic color of components. The same names are used across the library (web and React Native) (Button, Badge, Alert, Progress, toast…).

  • primary: the theme's primary color.
  • neutral: uncolored, plain.
  • danger: errors and irreversible actions.
  • success: success and confirmation.
  • warning: warning.
type Tone = "primary" | "neutral" | "danger" | "success" | "warning"

Size

type

Common component sizes.

type Size = "sm" | "md" | "lg"

Variant definition: a value → class map for each variant name.

type VariantSchema = Record<string, Record<string, ClassValue>>

Selection object generated from a variant schema.

type VariantSelection = { [K in keyof V]?: StringToBoolean<keyof V[K]> | null | undefined; }

Configuration of the variants function.

NameTypeDescription
base?ClassValueBase classes always added.
variants?VVariants and the classes of each value.
defaultVariants?VariantSelection<V>Variant values used when nothing is selected.
compoundVariants?Array<{ [K in keyof V]?: StringToBoolean<keyof V[K]> | ReadonlyArray<StringToBoolean<keyof V[K]>>; } & { className: ClassValue; }>Classes added when several variants are selected together. If a condition is given as an array, any of its values matching is enough.

Function generated by variants.

type VariantsFunction = (props?: VariantSelection<V> & { className?: ClassValue; }) => string

Infers the type of the variant selections accepted by a function created with variants. Used when defining component props.

type VariantProps = Omit<NonNullable<Parameters<F>[0]>, "className">

Examples

interface ButtonProps extends ComponentProps<"button">, VariantProps<typeof button> {}