Utils
cn, variants, expr, safe URLs and the shared helpers of the primitives and compositions (plus the theme CSS in styles/)
Install
npx ui8kit add utilsPreview
No static preview for this item: it needs content or a parent that this page cannot supply. The code is below.
Code
Point the CLI at this runtime once, then add the item:
npx ui8kit init --yes --framework svelte --dir src --registry-url https://registry.buildy.tw/svelte --strict-cdnnpx ui8kit add utilsimport { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
/**
* Merge class values with Tailwind conflict resolution.
* Mirrors shadcn's `cn` = clsx + tailwind-merge.
* Caller-supplied classes win over recipe classes.
*/
export function cn(...inputs: ClassValue[]): string {
return twMerge(clsx(inputs));
}
/**
* Dev-only warnings switch, bundle-agnostic (no ESM-only meta property, so the utils work in ESM, CJS, IIFE / classic
* script bundles, e.g. the web components). On when `globalThis.__UI8KIT_DEV__ === true`, or when a bundler
* defines `process.env.NODE_ENV` as "development".
*/
export function isDevEnv(): boolean {
const g = globalThis as { __UI8KIT_DEV__?: unknown; process?: { env?: { NODE_ENV?: string } } };
if (typeof g.__UI8KIT_DEV__ === "boolean") return g.__UI8KIT_DEV__;
try {
return g.process?.env?.NODE_ENV === "development";
} catch {
return false;
}
}
/**
* Tiny attribute-logic helpers used by generated components. One
* implementation per runtime family keeps every default-resolution decision
* table byte-identical across React, Svelte, and Vue (mirrors `expr.go`).
*/
export const trimStr = (v: string | number | null | undefined): string =>
v === null || v === undefined ? "" : String(v).trim();
export const isSetStr = (v: string | null | undefined): boolean => trimStr(v) !== "";
export const isSetNum = (v: number | null | undefined): boolean => (v ?? 0) > 0;
/**
* `trim(v) === "" ? fallback : trim(v)` — DefaultInputType-style defaults.
* Generic so enum-typed props keep their literal union through the default.
*/
export const defaultIfEmpty = <T extends string>(v: T | null | undefined, fallback: T): T => {
const t = trimStr(v) as T;
return t === "" ? fallback : t;
};
/** Whitelist: returns `trim(v)` when in `allowed`, otherwise `fallback`. */
export const oneOfOr = <T extends string>(
v: string | null | undefined,
fallback: T,
...allowed: T[]
): T => {
const t = trimStr(v) as T;
return allowed.includes(t) ? t : fallback;
};
export const oneOfOrLower = <T extends string>(
v: string | null | undefined,
fallback: T,
...allowed: T[]
): T => {
const t = trimStr(v).toLowerCase() as T;
return allowed.includes(t) ? t : fallback;
};
/** Decision table: `mapping[trim(v)] ?? fallback`. */
export const mapOr = <T extends string>(
v: string | null | undefined,
mapping: Record<string, T>,
fallback: T
): T => mapping[trimStr(v)] ?? fallback;
export const mapOrLower = <T extends string>(
v: string | null | undefined,
mapping: Record<string, T>,
fallback: T
): T => mapping[trimStr(v).toLowerCase()] ?? fallback;
/** Integer decision table: `mapping[v] ?? fallback`. */
export const intMapOr = <T extends string>(
v: number | null | undefined,
mapping: Record<number, T>,
fallback: T
): T => mapping[v ?? 0] ?? fallback;
/** Null-safe string equality (both sides normalized to ""). */
export const eqStr = (a: string | null | undefined, b: string | null | undefined): boolean =>
(a ?? "") === (b ?? "");
/** ARIA state stringification: always "true"/"false", never omitted. */
export const boolStr = (v: boolean | null | undefined): "true" | "false" =>
v ? "true" : "false";
/** Tri-state ARIA state: "true"/"false" when set, "" when unset (attribute omitted). */
export const optBoolStr = (v: boolean | null | undefined): "true" | "false" | "" =>
v === true ? "true" : v === false ? "false" : "";
/** Concatenation of trimmed parts (icon `Prefix + Name`). */
export const concatTrim = (...parts: (string | null | undefined)[]): string =>
parts.map(trimStr).join("");
/** Omit-if-empty attribute value: `""` → `undefined` so the attr is dropped. */
export const orUndef = <T extends string>(v: T | null | undefined): Exclude<T, ""> | undefined => {
const t = trimStr(v);
return t === "" ? undefined : (String(v) as Exclude<T, "">);
};
/**
* Sync a form control's live `value` property (never an attribute, so SSR
* markup is untouched). `undefined` leaves the current selection alone, so
* the children's initial `selected` state stays in charge. Usable directly as
* a Svelte action (`use:syncValue={value}`) and from Solid refs / WC renderers.
*/
export function syncValue(node: { value: string }, value?: string | null): { update(v?: string | null): void } {
const apply = (v?: string | null): void => {
if (v !== undefined && v !== null && node.value !== v) node.value = v;
};
apply(value);
return { update: apply };
}
const DATA_IMAGE = /^data:image\/(png|jpeg|gif|webp|avif|svg\+xml)[;,]/;
/**
* URL attribute value: "" for javascript:, vbscript: and data: (ASCII whitespace/control chars removed,
* case-insensitive). `dataImage` (only `<img src>`) allows data:image/(png|jpeg|gif|webp|avif|svg+xml).
*/
export const safeUrl = (v: string | null | undefined, dataImage = false): string => {
const k = String(v ?? "").replace(/[\u0000-\u0020]/g, "").toLowerCase();
return /^(javascript|vbscript|data):/.test(k) && !(dataImage && DATA_IMAGE.test(k)) ? "" : (v ?? "");
};
/** Per-element rest rule: `img` allows data:image in `src`; `blank` lists optional attrs (lowercase) omitted when blank. */
export type RestRule = { readonly img?: boolean; readonly blank?: readonly string[] };
const URL_KEYS = new Set(["href", "src", "action", "formaction", "poster", "cite", "background", "xlink:href", "xlinkhref"]);
/** True when a rest entry must be omitted: an unsafe URL or a blank optional attribute (`value` is never in `blank`). */
export function dropRestKey(k: string, v: unknown, rule?: RestRule): boolean {
if (typeof v !== "string") return false;
const key = k.toLowerCase();
if (rule?.blank?.includes(key) && v.trim() === "") return true;
return v !== "" && URL_KEYS.has(key) && safeUrl(v, rule?.img === true && key === "src") === "";
}
/** Rest props / caller attrs without unsafe URLs and blank optional attributes; identity when clean. */
export function safeRest<T extends object>(rest: T, rule?: RestRule): T {
const bad = Object.keys(rest).filter((k) => dropRestKey(k, (rest as Record<string, unknown>)[k], rule));
if (bad.length === 0) return rest;
const out = { ...rest } as Record<string, unknown>;
for (const k of bad) delete out[k];
return out as T;
}
export { cn } from "./cn";
export { isDevEnv } from "./env";
export type { RecipeKey, VariantRecipe } from "./recipe-types";
export {
compose,
composeRecipe,
recipeToVariants,
type RecipeSelection,
type Variants,
} from "./variants";
export { BOX_TAGS, TEXT_TAGS, TagGroup, isAllowedTag, resolveTag, type BoxTag, type TextTag } from "./tags";
export * from "./expr";
/**
* Type helpers to derive literal unions from `*.variants.json` recipes.
* Usage:
* import buttonRecipe from "./button.variants.json";
* type ButtonVariant = RecipeKey<typeof buttonRecipe, "variant">;
* // ^? "default" | "destructive" | "ghost" | ...
*/
export type VariantRecipe = {
id: string;
base: string;
keys: string[];
defaults: Record<string, string>;
byKey: Record<string, Record<string, string>>;
};
/**
* Extract the literal union of variant keys for a given recipe dimension.
* Empty string (used as a fallback in some JSON recipes) is excluded so
* consumers get only meaningful values in autocomplete.
*/
export type RecipeKey<
R extends VariantRecipe,
K extends keyof R["byKey"] & string,
> = Exclude<keyof R["byKey"][K] & string, "">;
// Mirrors src/domain/tags.ts (the SSOT). DO NOT EDIT in generated output.
import { isDevEnv } from "./env";
export const BOX_TAGS = [
"div", "section", "article", "aside", "header", "footer", "main", "nav", "figure", "search",
"ul", "ol", "li", "dl", "dt", "dd", "fieldset",
"table", "thead", "tbody", "tfoot", "tr", "th", "td", "caption", "colgroup", "col",
] as const;
export const TEXT_TAGS = [
"p", "span", "h1", "h2", "h3", "h4", "h5", "h6", "blockquote", "figcaption", "pre", "code",
"small", "strong", "em", "time", "legend", "del", "ins",
] as const;
export type BoxTag = (typeof BOX_TAGS)[number];
export type TextTag = (typeof TEXT_TAGS)[number];
export const TagGroup = { Box: "Box", Text: "Text" } as const;
export type TagGroup = (typeof TagGroup)[keyof typeof TagGroup];
const groups: Record<TagGroup, ReadonlySet<string>> = {
Box: new Set<string>(BOX_TAGS),
Text: new Set<string>(TEXT_TAGS),
};
const warned = new Set<string>();
export function isAllowedTag(tag: string, group: TagGroup): boolean {
return groups[group]?.has(tag.trim().toLowerCase()) ?? false;
}
export function resolveTag(tag: string | undefined, fallback: string, group: TagGroup): string {
const t = tag?.trim().toLowerCase() ?? "";
if (!t) return fallback;
if (isAllowedTag(t, group)) return t;
if (isDevEnv()) {
const key = `${group}:${t}`;
if (!warned.has(key)) {
warned.add(key);
console.warn(`[resolveTag] "${t}" is not an allowed ${group} tag; using "${fallback}".`);
}
}
return fallback;
}
import { cn } from "./cn";
import { isDevEnv } from "./env";
import type { RecipeKey, VariantRecipe } from "./recipe-types";
export type { RecipeKey, VariantRecipe };
export type Variants = {
id?: string;
base: string;
keys: string[];
defaults: Record<string, string>;
byKey: Record<string, Record<string, string>>;
};
export function recipeToVariants<R extends VariantRecipe>(recipe: R): Variants {
return {
id: recipe.id,
base: recipe.base,
keys: recipe.keys,
defaults: recipe.defaults ?? {},
byKey: recipe.byKey,
};
}
/**
* Merge base, variant selections, and optional tail classes.
* Mirrors the canonical `composeRecipe`.
*/
export function compose(
v: Variants,
selection: Record<string, string>,
...extra: (string | undefined | null | false)[]
): string {
const parts: string[] = [];
if (v.base.trim() !== "") {
parts.push(v.base.trim());
}
for (const key of v.keys) {
const choices = v.byKey[key];
if (!choices) continue;
const selected = (selection[key] ?? "").trim();
const fallback = (v.defaults[key] ?? "").trim();
const choice = selected || fallback;
if (!choice) {
if (isDevEnv() && Object.keys(choices).length > 0) {
throw new Error(
`[compose] missing default for key "${key}" (recipe id: ${String(v.id ?? "?")})`
);
}
continue;
}
const cls = choices[choice];
if (cls !== undefined) {
if (cls.trim() !== "") parts.push(cls.trim());
} else if (isDevEnv()) {
throw new Error(
`[compose] unknown variant "${choice}" for key "${key}" (recipe id: ${String(v.id ?? "?")})`
);
}
// Unknown choices are silently dropped in production to avoid leaking
// typos into the DOM as literal class names.
}
return cn(...parts, ...extra);
}
/** Selection type for `composeRecipe`. */
export type RecipeSelection<R extends VariantRecipe> = {
[K in keyof R["byKey"] & string]?: RecipeKey<R, K> | undefined;
};
/** Compose classes from a typed recipe. */
export function composeRecipe<R extends VariantRecipe>(
recipe: R,
selection: RecipeSelection<R>,
...extra: (string | undefined | null | false)[]
): string {
return compose(recipeToVariants(recipe), selection as Record<string, string>, ...extra);
}
/* Code generated by compose-gen. DO NOT EDIT. */
/* Entry of the styles: theme tokens and the kit CSS. @source makes Tailwind v4 scan the compositions and the installed primitives. */
@import "./theme.css";
@import "./kit.css";
@source "../";
@source "../kit";
/* Kit-wide CSS: base layer, input glyph utilities, focus ring. Colors and the one corner token (--radius) come from theme.css (shadcn neutral);
shadows: only floating layers have one (shadow-md, shadow-lg), set in their specs; nothing here draws one. */
@layer base {
html, body { margin: 0; background: var(--color-background); color: var(--color-foreground); }
body { -webkit-font-smoothing: antialiased; text-rendering: geometricPrecision; overflow-x: hidden; }
button { cursor: pointer; }
html { -webkit-text-size-adjust: 100%; color-scheme: light; }
}
/* the box of a checkbox: its corner is the theme radius scaled to the 16-20px box (0.4 x 10px = 4px), so it never reads as a radio */
@utility checkbox-glyph {
display: inline-grid; place-content: center; border-radius: calc(var(--radius) * 0.4);
&::before { content: ""; width: 8px; height: 6px; opacity: 0; background: currentColor;
clip-path: polygon(0 55%, 14% 40%, 38% 64%, 86% 0, 100% 15%, 38% 95%); }
&:checked { color: var(--color-primary-foreground); }
&:checked::before { opacity: 1; }
}
/* a number field without the browser spin buttons (NumberField draws its own minus and plus) */
@utility number-bare {
appearance: textfield; -moz-appearance: textfield;
&::-webkit-inner-spin-button, &::-webkit-outer-spin-button { -webkit-appearance: none; margin: 0; }
}
@utility radio-glyph {
display: inline-grid; place-content: center;
&::before { content: ""; width: var(--dot); height: var(--dot); border-radius: 9999px; background: var(--color-primary-foreground); opacity: 0; }
&:checked::before { opacity: 1; }
}
@utility switch-knob {
&::before { content: ""; position: absolute; top: 50%; left: var(--pad); width: var(--knob); height: var(--knob); border-radius: 9999px;
background: var(--color-background); translate: 0 -50%; transition: left .15s; }
&:checked::before { left: calc(100% - var(--pad) - var(--knob)); }
}
@utility progress-bar {
&::-webkit-progress-bar { background: transparent; }
&::-webkit-progress-value { background: var(--bar); border-radius: var(--radius); }
&::-moz-progress-bar { background: var(--bar); border-radius: var(--radius); }
&::-webkit-meter-bar { background: transparent; border: 0; }
&::-webkit-meter-optimum-value { background: var(--bar); }
}
/* Focus ring sits above utility shadows. Keyboard only. The 4px halo is gray unless the element sets a ring colour
(shadcn style, e.g. focus-visible:ring-destructive/20 on the destructive variants); --tw-ring-color does not inherit. */
:where(a, button, input, select, textarea, summary, [role="tab"], [role="menuitem"], [role="menuitemradio"], [role="option"], [role="treeitem"], [role="radio"], [role="switch"], [tabindex]):focus-visible {
outline: none;
box-shadow: var(--tw-inset-shadow, 0 0 #0000), var(--tw-inset-ring-shadow, 0 0 #0000), 0 0 0 4px var(--tw-ring-color, rgb(128 128 128 / 0.15)), var(--tw-shadow, 0 0 #0000);
}
[data-slot="prompt-input"]:focus-within, [data-slot="smartbox"]:focus-within { box-shadow: 0 0 0 4px rgb(128 128 128 / 0.15), inset 0 0 0 1px var(--color-border); }
[data-slot="prompt-input"] textarea:focus-visible, [data-slot="smartbox"] input:focus-visible { box-shadow: none; }
[data-slot="file-tree-item"]:focus-visible, [data-slot="editor-tab"]:focus-visible, [data-slot="icon-tab"]:focus-visible, [data-slot="dropdown-item"]:focus-visible {
box-shadow: inset 0 0 0 2px rgb(128 128 128 / 0.15), inset 0 0 0 1px var(--color-muted-foreground);
}
:where([data-screen]) :focus:not(:focus-visible) { outline: none; }
::selection { background: color-mix(in srgb, var(--color-primary) 15%, transparent); }
/* The disclosure indicator: the Lucide chevron-down drawn in the text colour; the Summary brick turns it over when its
details open (group-open:rotate-180), so an accordion needs no script. */
[data-slot="summary-indicator"] {
display: inline-block;
background-color: currentColor;
mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E") center / contain no-repeat;
}
/* Per-element tokens (UI8KIT-2.0 §11): badge, button, card, alert, media. An unset token falls back to the value of the utility class the
rule matches (p-6, px-4 h-10, ...), stated explicitly: a revert-layer fallback inside var() is not supported by every
browser (there the property became unset: buttons and badges lost their padding and height).
A skin or a scope (a wrapper, the magazine specimen) sets only the ones it wants.
Radius: --radius-badge|button|card|alert|media (unset: var(--radius); the badge unset: the pill). Only elements that carry plain `rounded` follow it.
Shadow: --shadow-card|alert|media (unset: the spec's own: none). A full box-shadow layer, e.g. var(--shadow-sm) or 0 0 #0000.
Density: data-density-badge|button|card|alert = compact | default | comfortable, on the element or any ancestor, sets --pad-*:
card 16/24/32 (padding of a default card), alert inline 8/8/16 with --min-alert 24/32/40,
button inline 12/16/20 and height 32/40/48 (default size), badge inline 8/12/16 and height 20/24/28 (default size).
4px steps only inside controls (button, badge); card and alert stay on the 8px step. */
[data-slot="button"].rounded { border-radius: var(--radius-button, var(--radius)); }
[data-slot="card"].rounded { border-radius: var(--radius-card, var(--radius)); }
[data-slot="alert"].rounded { border-radius: var(--radius-alert, var(--radius)); }
[data-slot="media-frame"].rounded { border-radius: var(--radius-media, var(--radius)); }
[data-slot="badge"].rounded-full { border-radius: var(--radius-badge, calc(infinity * 1px)); }
[data-slot="card"] { --tw-shadow: var(--shadow-card, 0 0 #0000); }
[data-slot="alert"] { --tw-shadow: var(--shadow-alert, 0 0 #0000); }
[data-slot="media-frame"] { --tw-shadow: var(--shadow-media, 0 0 #0000); }
[data-slot="card"].p-6 { padding: var(--pad-card, calc(var(--spacing) * 6)); }
[data-slot="alert"].px-2 { padding-inline: var(--pad-alert, calc(var(--spacing) * 2)); }
[data-slot="alert"].min-h-8 { min-height: var(--min-alert, calc(var(--spacing) * 8)); }
[data-slot="button"].px-4.h-10 { padding-inline: var(--pad-button, calc(var(--spacing) * 4)); height: var(--h-button, calc(var(--spacing) * 10)); }
[data-slot="badge"].px-3.h-6 { padding-inline: var(--pad-badge, calc(var(--spacing) * 3)); height: var(--h-badge, calc(var(--spacing) * 6)); }
[data-density-card="compact"] { --pad-card: 16px; }
[data-density-card="comfortable"] { --pad-card: 32px; }
[data-density-alert="compact"] { --pad-alert: 8px; --min-alert: 24px; }
[data-density-alert="comfortable"] { --pad-alert: 16px; --min-alert: 40px; }
[data-density-button="compact"] { --pad-button: 12px; --h-button: 32px; }
[data-density-button="comfortable"] { --pad-button: 20px; --h-button: 48px; }
[data-density-badge="compact"] { --pad-badge: 8px; --h-badge: 20px; }
[data-density-badge="comfortable"] { --pad-badge: 16px; --h-badge: 28px; }
/* Owned by codegen-x (UI8Kit 3: ui8kit/codegen ships no theme). Forked from vendor/codegen 2309848; adds --destructive-foreground (AA). */
@import "tailwindcss";
/* shadcn/ui neutral theme (Tailwind v4, written as hsl() for old browsers; same colours as the oklch values published at https://ui.shadcn.com/docs/theming
("Default Theme CSS", base color neutral). Dark mode: the .dark class or data-theme="dark" on an ancestor. */
@custom-variant dark (&:is(.dark *, [data-theme="dark"] *));
/* The one corner token. Plain `rounded` reads the bare --radius theme key, so every corner of the kit follows it
(shadcn keeps --radius in :root; here it sits in @theme so that `rounded` resolves to it; same value, 0.625rem). */
@theme {
--radius: 0.625rem;
}
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--color-card: var(--card);
--color-card-foreground: var(--card-foreground);
--color-popover: var(--popover);
--color-popover-foreground: var(--popover-foreground);
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
--color-secondary: var(--secondary);
--color-secondary-foreground: var(--secondary-foreground);
--color-muted: var(--muted);
--color-muted-foreground: var(--muted-foreground);
--color-accent: var(--accent);
--color-accent-foreground: var(--accent-foreground);
--color-destructive: var(--destructive);
--color-destructive-foreground: var(--destructive-foreground);
--color-destructive-hover: var(--destructive-hover);
--color-border: var(--border);
--color-input: var(--input);
--color-ring: var(--ring);
--color-chart-1: var(--chart-1);
--color-chart-2: var(--chart-2);
--color-chart-3: var(--chart-3);
--color-chart-4: var(--chart-4);
--color-chart-5: var(--chart-5);
--color-sidebar: var(--sidebar);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-ring: var(--sidebar-ring);
--radius-sm: calc(var(--radius) * 0.6);
--radius-md: calc(var(--radius) * 0.8);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) * 1.4);
--radius-2xl: calc(var(--radius) * 1.8);
--radius-3xl: calc(var(--radius) * 2.2);
--radius-4xl: calc(var(--radius) * 2.6);
}
:root {
--background: hsl(0 0% 100%);
--foreground: hsl(0 0% 4%);
--card: hsl(0 0% 100%);
--card-foreground: hsl(0 0% 4%);
--popover: hsl(0 0% 100%);
--popover-foreground: hsl(0 0% 4%);
--primary: hsl(0 0% 9%);
--primary-foreground: hsl(0 0% 98%);
--secondary: hsl(0 0% 96%);
--secondary-foreground: hsl(0 0% 9%);
--muted: hsl(0 0% 96%);
--muted-foreground: hsl(0 0% 43.5%);
--accent: hsl(0 0% 96%);
--accent-foreground: hsl(0 0% 9%);
--destructive: hsl(0.6 88.4% 48%); /* L 52.5% -> 48%: white text reaches AA (4.70) */
--destructive-foreground: hsl(0 0% 100%);
--destructive-hover: hsl(0.6 88.4% 42%); /* 6 points away from the foreground: hover keeps AA */
--border: hsl(0 0% 90%);
--input: hsl(0 0% 90%);
--ring: hsl(0 0% 63%);
--chart-1: hsl(18 100% 48%);
--chart-2: hsl(174.7 100% 29.5%);
--chart-3: hsl(196 72% 23%);
--chart-4: hsl(43.6 100% 50%);
--chart-5: hsl(36.3 100% 49.7%);
--sidebar: hsl(0 0% 98%);
--sidebar-foreground: hsl(0 0% 4%);
--sidebar-primary: hsl(0 0% 9%);
--sidebar-primary-foreground: hsl(0 0% 98%);
--sidebar-accent: hsl(0 0% 96%);
--sidebar-accent-foreground: hsl(0 0% 9%);
--sidebar-border: hsl(0 0% 90%);
--sidebar-ring: hsl(0 0% 63%);
}
:is(.dark, [data-theme="dark"]) {
--background: hsl(0 0% 4%);
--foreground: hsl(0 0% 98%);
--card: hsl(0 0% 9%);
--card-foreground: hsl(0 0% 98%);
--popover: hsl(0 0% 9%);
--popover-foreground: hsl(0 0% 98%);
--primary: hsl(0 0% 90%);
--primary-foreground: hsl(0 0% 9%);
--secondary: hsl(0 0% 15%);
--secondary-foreground: hsl(0 0% 98%);
--muted: hsl(0 0% 15%);
--muted-foreground: hsl(0 0% 63%);
--accent: hsl(0 0% 15%);
--accent-foreground: hsl(0 0% 98%);
--destructive: hsl(356.1 62.4% 52%);
--destructive-foreground: hsl(0 0% 100%);
--destructive-hover: hsl(356.1 62.4% 46%);
--border: hsl(0 0% 100% / 10%);
--input: hsl(0 0% 100% / 15%);
--ring: hsl(0 0% 45%);
--chart-1: hsl(225.3 84.1% 49%);
--chart-2: hsl(160 100% 37%);
--chart-3: hsl(36.3 100% 49.7%);
--chart-4: hsl(273.3 100% 63.8%);
--chart-5: hsl(345 100% 56%);
--sidebar: hsl(0 0% 9%);
--sidebar-foreground: hsl(0 0% 98%);
--sidebar-primary: hsl(225.3 84.1% 49%);
--sidebar-primary-foreground: hsl(0 0% 98%);
--sidebar-accent: hsl(0 0% 15%);
--sidebar-accent-foreground: hsl(0 0% 98%);
--sidebar-border: hsl(0 0% 100% / 10%);
--sidebar-ring: hsl(0 0% 45%);
}
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
}
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
// Framework-free: the function takes the node and returns the cleanup. Svelte: call it from an action or an effect; React: call it in an effect.
export type DismissReason = "escape" | "outside";
const stack: object[] = []; // topmost dismissable layer handles Escape first (menu inside off-canvas sidebar, …)
/** Escape and pointer-down outside the node call onDismiss. Returns the cleanup. */
export function dismissable(node: HTMLElement, opts: () => { onDismiss: (reason: DismissReason) => void; ignore?: () => (Element | null | undefined)[]; outside?: boolean }): () => void {
{
const layer = {};
stack.push(layer);
const { onDismiss, ignore = () => [], outside = true } = opts();
const onKey = (e: KeyboardEvent) => {
if (e.key !== "Escape" || e.defaultPrevented || stack[stack.length - 1] !== layer) return;
e.preventDefault(); e.stopPropagation();
onDismiss("escape");
};
const onDown = (e: PointerEvent) => {
if (!outside || stack[stack.length - 1] !== layer) return;
const t = e.target as Node | null;
if (!t || node.contains(t) || ignore().some((el) => el?.contains(t))) return;
onDismiss("outside");
};
document.addEventListener("keydown", onKey, true);
document.addEventListener("pointerdown", onDown, true);
return () => {
document.removeEventListener("keydown", onKey, true);
document.removeEventListener("pointerdown", onDown, true);
const i = stack.indexOf(layer); if (i >= 0) stack.splice(i, 1);
};
}
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
// Framework-free: the function takes the node and returns the cleanup. Svelte: call it from an action or an effect; React: call it in an effect.
import { focusables } from "./focusable";
/** Tab/Shift+Tab cycle inside `node`; on cleanup focus returns to the element focused before. */
export function trapFocus(node: HTMLElement): () => void {
const previous = document.activeElement as HTMLElement | null;
if (!node.contains(previous)) queueMicrotask(() => focusables(node)[0]?.focus());
const onKey = (e: KeyboardEvent) => {
if (e.key !== "Tab") return;
const items = focusables(node);
if (!items.length) { e.preventDefault(); return; }
const first = items[0], last = items[items.length - 1], cur = document.activeElement;
if (e.shiftKey && (cur === first || !node.contains(cur))) { e.preventDefault(); last.focus(); }
else if (!e.shiftKey && (cur === last || !node.contains(cur))) { e.preventDefault(); first.focus(); }
};
node.addEventListener("keydown", onKey);
return () => { node.removeEventListener("keydown", onKey); /* after the page is no longer inert */ requestAnimationFrame(() => { if (previous?.isConnected) previous.focus(); }); };
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
// Small headless helpers shared by the interactive primitives (menus, dialogs, tabs, off-canvas sidebar).
export const FOCUSABLE = 'a[href],button:not([disabled]),input:not([disabled]):not([type="hidden"]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])';
/** visible, tabbable descendants of `root` in DOM order */
export function focusables(root: HTMLElement): HTMLElement[] {
return [...root.querySelectorAll<HTMLElement>(FOCUSABLE)].filter((el) => !el.closest("[inert]") && el.getClientRects().length > 0 && getComputedStyle(el).visibility !== "hidden");
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
export { FOCUSABLE, focusables } from "./focusable";
export { moveFocus, typeahead, type RovingOptions } from "./roving";
export { lockScroll } from "./scroll-lock";
export { dismissable, type DismissReason } from "./dismiss";
export { trapFocus } from "./focus-trap";
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
// Arrow-key navigation over a list of focusable items (menus, listboxes, tab lists, trees).
export type RovingOptions = { orientation?: "vertical" | "horizontal" | "both"; loop?: boolean; activate?: boolean };
/** Handles ArrowUp/Down/Left/Right, Home, End. Returns true when the key was consumed. */
export function moveFocus(e: KeyboardEvent, items: HTMLElement[], { orientation = "vertical", loop = true, activate = false }: RovingOptions = {}): boolean {
if (!items.length || e.altKey || e.ctrlKey || e.metaKey) return false;
const prev = orientation !== "horizontal" ? ["ArrowUp"] : [];
const next = orientation !== "horizontal" ? ["ArrowDown"] : [];
if (orientation !== "vertical") { prev.push("ArrowLeft"); next.push("ArrowRight"); }
const cur = items.indexOf(document.activeElement as HTMLElement);
let idx = -1;
if (next.includes(e.key)) idx = cur < 0 ? 0 : cur + 1;
else if (prev.includes(e.key)) idx = cur < 0 ? items.length - 1 : cur - 1;
else if (e.key === "Home") idx = 0;
else if (e.key === "End") idx = items.length - 1;
else return false;
if (idx >= items.length) idx = loop ? 0 : items.length - 1;
if (idx < 0) idx = loop ? items.length - 1 : 0;
e.preventDefault();
const el = items[idx];
el.focus();
if (activate) el.click();
return true;
}
/** type-ahead: focus the next item whose text starts with the typed characters (reset after 600 ms) */
export function typeahead() {
let buf = "", t: ReturnType<typeof setTimeout> | undefined;
return (e: KeyboardEvent, items: HTMLElement[]): boolean => {
if (e.key.length !== 1 || e.ctrlKey || e.metaKey || e.altKey || e.key === " ") return false;
buf += e.key.toLowerCase();
clearTimeout(t); t = setTimeout(() => (buf = ""), 600);
const start = Math.max(0, items.indexOf(document.activeElement as HTMLElement) + (buf.length === 1 ? 1 : 0));
const ordered = [...items.slice(start), ...items.slice(0, start)];
const hit = ordered.find((el) => (el.textContent ?? "").trim().toLowerCase().startsWith(buf));
if (hit) { hit.focus(); e.preventDefault(); return true; }
return false;
};
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
// Reference-counted page scroll lock (off-canvas sidebar, modal dialog). Compensates the scrollbar width on desktop.
let count = 0;
let saved = { overflow: "", paddingRight: "" };
export function lockScroll(): () => void {
const root = document.documentElement;
if (count++ === 0) {
const sw = window.innerWidth - root.clientWidth;
saved = { overflow: root.style.overflow, paddingRight: root.style.paddingRight };
root.style.overflow = "hidden";
if (sw > 0) root.style.paddingRight = `${sw}px`;
root.setAttribute("data-scroll-locked", "");
}
let released = false;
return () => {
if (released) return; released = true;
if (--count === 0) {
root.style.overflow = saved.overflow; root.style.paddingRight = saved.paddingRight;
root.removeAttribute("data-scroll-locked");
}
};
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
/** Merge class values. Caller-supplied classes win over recipe classes. */
export function cn(...inputs: ClassValue[]): string {
return twMerge(clsx(inputs));
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
export function isDevEnv(): boolean {
try {
const env = (import.meta as unknown as { env?: { DEV?: boolean } }).env;
if (env && typeof env.DEV === "boolean") return env.DEV;
} catch {
// import.meta may be unavailable in some contexts
}
return false;
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
/**
* Tiny attribute-logic helpers used by generated components. One
* implementation per runtime family keeps every default-resolution decision
* table byte-identical across React, Svelte, and Vue (mirrors `expr.go`).
*/
export const trimStr = (v: string | number | null | undefined): string =>
v === null || v === undefined ? "" : String(v).trim();
export const isSetStr = (v: string | null | undefined): boolean => trimStr(v) !== "";
export const isSetNum = (v: number | null | undefined): boolean => (v ?? 0) > 0;
/**
* `trim(v) === "" ? fallback : trim(v)` — DefaultInputType-style defaults.
* Generic so enum-typed props keep their literal union through the default.
*/
export const defaultIfEmpty = <T extends string>(v: T | null | undefined, fallback: T): T => {
const t = trimStr(v) as T;
return t === "" ? fallback : t;
};
/** Whitelist: returns `trim(v)` when in `allowed`, otherwise `fallback`. */
export const oneOfOr = <T extends string>(
v: string | null | undefined,
fallback: T,
...allowed: T[]
): T => {
const t = trimStr(v) as T;
return allowed.includes(t) ? t : fallback;
};
export const oneOfOrLower = <T extends string>(
v: string | null | undefined,
fallback: T,
...allowed: T[]
): T => {
const t = trimStr(v).toLowerCase() as T;
return allowed.includes(t) ? t : fallback;
};
/** Decision table: `mapping[trim(v)] ?? fallback`. */
export const mapOr = <T extends string>(
v: string | null | undefined,
mapping: Record<string, T>,
fallback: T
): T => mapping[trimStr(v)] ?? fallback;
export const mapOrLower = <T extends string>(
v: string | null | undefined,
mapping: Record<string, T>,
fallback: T
): T => mapping[trimStr(v).toLowerCase()] ?? fallback;
/** Integer decision table: `mapping[v] ?? fallback`. */
export const intMapOr = <T extends string>(
v: number | null | undefined,
mapping: Record<number, T>,
fallback: T
): T => mapping[v ?? 0] ?? fallback;
/** Null-safe string equality (both sides normalized to ""). */
export const eqStr = (a: string | null | undefined, b: string | null | undefined): boolean =>
(a ?? "") === (b ?? "");
/** ARIA state stringification: always "true"/"false", never omitted. */
export const boolStr = (v: boolean | null | undefined): "true" | "false" =>
v ? "true" : "false";
/** Concatenation of trimmed parts (icon `Prefix + Name`). */
export const concatTrim = (...parts: (string | null | undefined)[]): string =>
parts.map(trimStr).join("");
/** Omit-if-empty attribute value: `""` → `undefined` so the attr is dropped. */
export const orUndef = (v: string | null | undefined): string | undefined => {
const t = trimStr(v);
return t === "" ? undefined : String(v);
};
export type HeadingLevel = 1 | 2 | 3 | 4 | 5 | 6;
/** h1–h6 from a heading level; 0/undefined/out-of-range default to h2. */
export const titleTag = (order: HeadingLevel | number | null | undefined): string => {
switch (order) {
case 1:
return "h1";
case 3:
return "h3";
case 4:
return "h4";
case 5:
return "h5";
case 6:
return "h6";
default:
return "h2";
}
};
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
// Text and number formatting shared by every generated organism and screen. Pure functions, no runtime dependency.
/** fills {0}, {1}... of a content template */
export function tpl(template: string | undefined, ...values: Array<string | number | undefined>): string {
return (template ?? "").replace(/\{(\d+)\}/g, (_m, i: string) => String(values[Number(i)] ?? ""));
}
const nf = new Intl.NumberFormat("en-US");
export function fmtNumber(n: number): string {
return nf.format(n);
}
/** digits of the minor unit (ISO 4217): cents for most currencies, none for JPY and KRW */
export function minorDigits(currency: string): number {
return currency === "JPY" || currency === "KRW" ? 0 : 2;
}
const moneyCache = new Map<string, Intl.NumberFormat>();
/** money in integer minor units (Codex v0.4: 1250 = 12.50 USD) -> "$12.50"; whole amounts drop the fraction: 1499_00 -> "$1,499" */
export function fmtMoney(minor: number, currency: string): string {
const d = minorDigits(currency);
const cents = Math.round(minor);
const frac = d > 0 && cents % 10 ** d !== 0 ? d : 0;
const key = `${currency}:${frac}`;
let f = moneyCache.get(key);
if (!f) {
f = new Intl.NumberFormat("en-US", { style: "currency", currency, minimumFractionDigits: frac, maximumFractionDigits: frac });
moneyCache.set(key, f);
}
return f.format(cents / 10 ** d);
}
/** a content word by key (the status of a record -> its label); the key itself when the dictionary has no entry */
export function at(dict: Record<string, string> | undefined, key: string): string {
return dict?.[key] ?? key;
}
/** the page numbers a pager shows: the first, the last and the neighbours of the current page; null is a gap */
export function pageWindow(page: number, pages: number): (number | null)[] {
const keep = new Set([1, pages, page - 1, page, page + 1].filter((n) => n >= 1 && n <= pages));
const out: (number | null)[] = [];
let prev = 0;
for (const n of [...keep].sort((a, b) => a - b)) {
if (n - prev > 1) out.push(null);
out.push(n);
prev = n;
}
return out;
}
/** a responsive column variant of Grid capped by the number of items, so no column stays empty: ("1-4", 3) -> "1-3", ("2-6", 4) -> "2-4" */
export function fitCols(cols: string, n: number): string {
const m = /^(\d+)-(\d+)$/.exec(cols);
if (!m) return cols;
const lo = Number(m[1]), hi = Number(m[2]);
if (n >= hi) return cols;
const top = Math.max(lo, n);
const known = ["1-2", "1-3", "1-4", "2-3", "2-4", "2-6", "3-6"];
for (let h = top; h > lo; h--) if (known.includes(`${lo}-${h}`)) return `${lo}-${h}`;
return String(Math.min(lo, Math.max(n, 1)));
}
/** a label of segments joined by ", " without a segment equal (case-insensitive) to the one before it:
* "Footer, Footer, Centered" -> "Footer, Centered" */
export function uniqLabel(label: string | undefined): string {
const parts = (label ?? "").split(", ");
return parts.filter((s, i) => i === 0 || s.toLowerCase() !== (parts[i - 1] ?? "").toLowerCase()).join(", ");
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
/**
* Trusted markup. A prop of type `TrustedHtml` carries markup from a trusted source (the `|html` pipe of readPath: the body of a
* Codex entry, or the host), and an `html` view node prints it without escaping. Every other value is text, and is escaped.
* The marker is React's own shape, `{ __html }`; a value without it (a plain string) is escaped by `htmlOf`, so markup is
* printed raw only when it was marked trusted. The same rules on every runtime: og_html (PHP, Python) and Html (Go).
*/
export type TrustedHtml = { readonly __html: string };
/** marks markup as trusted: only for a source the app trusts (the Codex body), never for user input */
export const trustHtml = (html: string): TrustedHtml => ({ __html: html });
export const isTrustedHtml = (v: unknown): v is TrustedHtml =>
v !== null && typeof v === "object" && typeof (v as { __html?: unknown }).__html === "string";
const ENTITIES: Record<string, string> = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" };
/** text as markup: & < > " ' as entities */
export const escapeHtml = (s: string): string => s.replace(/[&<>"']/g, (c) => ENTITIES[c]!);
/** the markup an `html` node prints: the trusted markup as it is, any other value escaped as text (nothing for null and booleans, like a text node) */
export const htmlOf = (v: TrustedHtml | string | number | boolean | null | undefined): string =>
isTrustedHtml(v) ? v.__html : v === null || v === undefined || typeof v === "boolean" ? "" : escapeHtml(String(v));
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
export { cn } from "./cn";
export { isDevEnv } from "./env";
export { variants, type VariantFn, type VariantKey, type VariantSelection, type VariantTable } from "./variants";
export { TagGroup, isAllowedTag, resolveTag } from "./tags";
export * from "./expr";
export { tpl, fmtNumber, fmtMoney, minorDigits, at, pageWindow, fitCols, uniqLabel } from "./format";
export * from "./a11y";
export { type TrustedHtml, trustHtml, isTrustedHtml, escapeHtml, htmlOf } from "./html";
export { decodeEntities, isSafeUrl, urlOf, srcsetOf, cssValue, srcsetUrls, styleOf, isSafeAttrName, attrValueOf, URL_ATTRS, IMAGE_ATTRS, URL_SCHEMES, NAMED_ENTITIES } from "./safe";
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
/**
* Output safety of the organism runtime (the same rules in PHP Runtime.php, Python runtime.py and Go dyn.go; the shared vectors
* are in packages/compose-gen/runtimes/core/test/safety-vectors.json). An allowlist, not a denylist:
* - a URL (href, src, action, formaction, poster, cite, background, data, xlink:href) is kept only when, read as a browser
* reads it (entities decoded, ASCII whitespace and control characters removed), it is a path or a reference with no scheme
* (`/path`, `#a`, `?q`, `page.html`) or its scheme is http, https, mailto or tel; an image URL may also be
* data:image/(png|jpeg|gif|webp|avif|svg+xml). A protocol-relative URL (`//host`, `/\host`, `\\host`) is refused.
* Anything else is "" (javascript:, vbscript:, data:text/html, livescript:, also behind case, entities or whitespace).
* - a srcset is checked candidate by candidate (each URL an image URL); one bad candidate refuses the whole value.
* - a style is refused ("") when a url(...) inside it is not an image URL, or it holds expression(, a script scheme,
* -moz-binding, behavior: or a CSS escape (a backslash).
* - an attribute name is printed only when it matches ^[a-zA-Z_:][-a-zA-Z0-9_:.]*$ and does not start with "on".
*/
/** the named character references the check decodes (those that spell URL syntax, whitespace or the markup characters) */
export const NAMED_ENTITIES: Readonly<Record<string, string>> = {
Tab: "\t", NewLine: "\n", colon: ":", sol: "/", bsol: "\\", lpar: "(", rpar: ")", amp: "&", lt: "<", gt: ">", quot: '"', apos: "'",
nbsp: "\u00a0", period: ".", comma: ",", excl: "!", num: "#", quest: "?", equals: "=", plus: "+", semi: ";", percnt: "%", lowbar: "_",
ast: "*", commat: "@", dollar: "$", Hat: "^", grave: "`", lsqb: "[", rsqb: "]", lcub: "{", rcub: "}", verbar: "|", vert: "|",
};
export const URL_SCHEMES: readonly string[] = ["http", "https", "mailto", "tel"];
const DATA_IMAGE = /^data:image\/(png|jpeg|gif|webp|avif|svg\+xml)[;,]/;
const ENTITY = /&(?:#[xX]([0-9a-fA-F]{1,8});?|#([0-9]{1,10});?|([a-zA-Z][a-zA-Z0-9]{0,31});)/g;
const fromCode = (n: number): string => (n > 0 && n <= 0x10ffff && !(n >= 0xd800 && n <= 0xdfff) ? String.fromCodePoint(n) : "\ufffd");
/** character references decoded as a browser would (numeric with or without `;`, the named ones of NAMED_ENTITIES), up to 3 rounds */
export function decodeEntities(s: string): string {
let out = s;
for (let i = 0; i < 3 && out.includes("&"); i++) {
out = out.replace(ENTITY, (m, hex: string | undefined, dec: string | undefined, name: string | undefined) =>
hex !== undefined ? fromCode(parseInt(hex, 16)) : dec !== undefined ? fromCode(parseInt(dec, 10)) : NAMED_ENTITIES[name!] ?? m);
}
return out;
}
/** the value as a URL parser sees it: entities decoded, ASCII whitespace and control characters (C0, space, DEL) removed */
const compact = (s: string): string => decodeEntities(s).replace(/[\u0000-\u0020\u007f]+/g, "");
/** true when the URL is allowed (see the file comment); `image`: data:image/* too */
export function isSafeUrl(v: string, image = false): boolean {
const k = compact(v);
if (/^[/\\]{2}/.test(k)) return false;
const m = /^([a-zA-Z][a-zA-Z0-9+.-]*):/.exec(k);
// no scheme: a path, unless a ":" comes before any "/" (as written or decoded), which templ.URL refuses too (one rule everywhere)
if (!m) return !/^[^/]*:/.test(k) && !/^[^/]*:/.test(v);
const scheme = m[1]!.toLowerCase();
if (scheme === "data") return image && DATA_IMAGE.test(k.toLowerCase());
return URL_SCHEMES.includes(scheme);
}
const str = (v: unknown): string => (typeof v === "string" ? v : typeof v === "number" ? String(v) : "");
/** a URL attribute value: the value when it is allowed, else "" (another non-string is ""); undefined and null stay as they are (the attribute is left out) */
export function urlOf<T>(v: T, image = false): string | Extract<T, null | undefined> {
if (v === undefined || v === null) return v as Extract<T, null | undefined>;
const s = str(v);
return isSafeUrl(s, image) ? s : "";
}
/** the URLs of a srcset, candidate by candidate (the URL of a candidate runs to the first whitespace; trailing commas end it) */
export function srcsetUrls(v: string): string[] {
const s = decodeEntities(v), out: string[] = [];
let i = 0;
const ws = (c: string | undefined) => c !== undefined && /[\t\n\f\r ]/.test(c);
while (i < s.length) {
while (i < s.length && (ws(s[i]) || s[i] === ",")) i++;
if (i >= s.length) break;
let j = i;
while (j < s.length && !ws(s[j])) j++;
let url = s.slice(i, j);
const cut = /,+$/.exec(url);
if (cut) { url = url.slice(0, -cut[0].length); out.push(url); i = j; continue; }
out.push(url);
let depth = 0;
while (j < s.length && (depth > 0 || s[j] !== ",")) { if (s[j] === "(") depth++; else if (s[j] === ")") depth = Math.max(0, depth - 1); j++; }
i = j + 1;
}
return out;
}
/** a srcset value: the value when every candidate URL is an allowed image URL, else "" */
export function srcsetOf<T>(v: T): string | Extract<T, null | undefined> {
if (v === undefined || v === null) return v as Extract<T, null | undefined>;
const s = str(v);
return srcsetUrls(s).every((u) => isSafeUrl(u, true)) ? s : "";
}
/** a value of an inline style declaration (the css op): kept when it is plain (numbers, words, %, #, +, -, ., commas and spaces), else ""; no url(), no ; */
export const cssValue = (v: unknown): string => { const s = str(v); return /^[-+.%#a-zA-Z0-9 ,]*$/.test(s) ? s : ""; };
/** a style value: "" when it could load or run something (see the file comment), else the value */
export function styleOf(v: unknown): string {
const s = str(v), d = decodeEntities(s), k = compact(s).toLowerCase();
if (d.includes("\\") || /expression\(|javascript:|vbscript:|-moz-binding|behavior:/.test(k)) return "";
for (const m of d.matchAll(/url\(([^)]*)\)?/gi)) if (!isSafeUrl(m[1]!.replace(/^[ \t\n\r\f\v]+|[ \t\n\r\f\v]+$/g, "").replace(/^(["'])([^]*)\1$/, "$2"), true)) return "";
return s;
}
/** an attribute name that may be printed: a valid XML-ish name, not an event handler (on*) */
export const isSafeAttrName = (name: string): boolean => /^[a-zA-Z_:][-a-zA-Z0-9_:.]*$/.test(name) && !/^on/i.test(name);
/** the attributes whose value is a URL (a srcset and a style have their own checks) */
export const URL_ATTRS: readonly string[] = ["href", "src", "action", "formaction", "poster", "cite", "background", "data", "xlink:href"];
/** the URL attributes whose URL is an image (data:image/* allowed) */
export const IMAGE_ATTRS: readonly string[] = ["src", "poster", "background"];
/** the value of attribute `name` as it may be printed: URL, srcset and style checked, any other value as it is */
export function attrValueOf(name: string, v: unknown): unknown {
const n = name.toLowerCase();
if (n === "srcset" || n === "imagesrcset") return srcsetOf(v);
if (n === "style") return styleOf(v);
if (URL_ATTRS.includes(n)) return urlOf(v, IMAGE_ATTRS.includes(n));
return v;
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
// Code generated by tagsgen. DO NOT EDIT.
import { isDevEnv } from "./env";
export const TagGroup = {
Layout: "Layout",
BoxAllowed: "BoxAllowed",
BlockText: "BlockText",
Inline: "Inline",
Heading: "Heading",
List: "List",
ListItem: "ListItem",
Form: "Form",
FormControl: "FormControl",
FormLabel: "FormLabel",
Table: "Table",
TableSection: "TableSection",
TableRow: "TableRow",
TableCell: "TableCell",
TableColumn: "TableColumn",
Media: "Media",
Disclosure: "Disclosure",
Container: "Container",
Stack: "Stack",
Group: "Group",
Text: "Text",
} as const;
export type TagGroup = (typeof TagGroup)[keyof typeof TagGroup];
const layoutTags = new Set(["div", "section", "article", "aside", "header", "footer", "main", "nav", "figure", "search", "hgroup"]);
const boxAllowedTags = new Set(["div"]);
const blockTextTags = new Set(["p", "blockquote", "figcaption", "address", "pre"]);
const inlineTags = new Set(["span", "em", "strong", "small", "abbr", "cite", "code", "kbd", "mark", "time", "data", "var", "samp", "sub", "sup", "b", "i", "u", "s", "q", "dfn", "bdo", "bdi", "ins", "del"]);
const headingTags = new Set(["h1", "h2", "h3", "h4", "h5", "h6"]);
const listTags = new Set(["ul", "ol", "dl", "menu"]);
const listItemTags = new Set(["li", "dt", "dd"]);
const formTags = new Set(["form", "fieldset"]);
const formControlTags = new Set(["input", "textarea", "select", "button", "option", "optgroup", "datalist", "output", "meter", "progress"]);
const formLabelTags = new Set(["label", "legend"]);
const tableTags = new Set(["table"]);
const tableSectionTags = new Set(["thead", "tbody", "tfoot"]);
const tableRowTags = new Set(["tr"]);
const tableCellTags = new Set(["th", "td"]);
const tableColumnTags = new Set(["colgroup", "col"]);
const mediaTags = new Set(["img", "picture", "source"]);
const disclosureTags = new Set(["details", "summary"]);
const containerTags = new Set(["div", "main", "section"]);
const stackTags = new Set(["div", "ul", "ol"]);
const groupTags = new Set(["div", "fieldset", "dl"]);
function oneOf(tag: string, options: Set<string>): boolean {
return options.has(tag);
}
const warnedTagFallbacks = new Set<string>();
function warnTagFallback(tag: string, fallback: string, group: TagGroup): void {
if (!isDevEnv()) return;
const key = `${group}:${tag}:${fallback}`;
if (warnedTagFallbacks.has(key)) return;
warnedTagFallbacks.add(key);
console.warn(`[resolveTag] disallowed tag "${tag}" for group "${group}", fallback "${fallback}" used.`);
}
export function isAllowedTag(tag: string, group: TagGroup): boolean {
const t = tag.trim().toLowerCase();
switch (group) {
case TagGroup.Layout:
return oneOf(t, layoutTags);
case TagGroup.BoxAllowed:
return oneOf(t, boxAllowedTags);
case TagGroup.BlockText:
return oneOf(t, blockTextTags);
case TagGroup.Inline:
return oneOf(t, inlineTags);
case TagGroup.Heading:
return oneOf(t, headingTags);
case TagGroup.List:
return oneOf(t, listTags);
case TagGroup.ListItem:
return oneOf(t, listItemTags);
case TagGroup.Form:
return oneOf(t, formTags);
case TagGroup.FormControl:
return oneOf(t, formControlTags);
case TagGroup.FormLabel:
return oneOf(t, formLabelTags);
case TagGroup.Table:
return oneOf(t, tableTags);
case TagGroup.TableSection:
return oneOf(t, tableSectionTags);
case TagGroup.TableRow:
return oneOf(t, tableRowTags);
case TagGroup.TableCell:
return oneOf(t, tableCellTags);
case TagGroup.TableColumn:
return oneOf(t, tableColumnTags);
case TagGroup.Media:
return oneOf(t, mediaTags);
case TagGroup.Disclosure:
return oneOf(t, disclosureTags);
case TagGroup.Container:
return oneOf(t, containerTags);
case TagGroup.Stack:
return oneOf(t, stackTags);
case TagGroup.Group:
return oneOf(t, groupTags);
case TagGroup.Text:
return blockTextTags.has(t) || inlineTags.has(t);
default:
return false;
}
}
export function resolveTag(tag: string | undefined, fallback: string, group: TagGroup): string {
const t = tag?.trim().toLowerCase() ?? "";
if (!t) return fallback;
if (isAllowedTag(t, group)) return t;
warnTagFallback(t, fallback, group);
return fallback;
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
import { cn } from "./cn";
import { isDevEnv } from "./env";
/**
* A shadcn/cva-style variant table, without the dependency (same idea as `cva` from class-variance-authority).
*
* const badgeVariants = variants({
* base: "inline-flex items-center",
* variants: { size: { sm: "h-5 px-2", lg: "h-8 px-3" } },
* defaultVariants: { size: "sm" },
* compoundVariants: [{ size: "lg", shape: "rounded", class: "rounded-lg" }],
* });
* badgeVariants({ size: "lg" }); // "inline-flex items-center h-8 px-3"
*
* Classes come in this order: base, each variant in table order, then the matching compound variants.
* tailwind-merge (`cn`) resolves conflicts, the later class wins. A compound value may list alternatives: "32|lg".
*/
export type VariantTable = {
base?: string;
variants: Record<string, Record<string, string>>;
defaultVariants: Record<string, string>;
compoundVariants?: Array<{ class: string } & Record<string, string>>;
};
/** the props a table accepts: one optional value per variant */
export type VariantSelection<T extends VariantTable> = {
[K in keyof T["variants"]]?: (keyof T["variants"][K] & string) | undefined;
};
/** a variant function: call it with the selected values, read `.table` for the types */
export type VariantFn<T extends VariantTable> = ((selection?: VariantSelection<T>) => string) & { table: T };
/** the values of one variant of a table: `VariantKey<typeof badgeVariants, "size">` is `"sm" | "lg"` */
export type VariantKey<F extends { table: VariantTable }, K extends keyof F["table"]["variants"]> = Exclude<
keyof F["table"]["variants"][K] & string,
""
>;
export function variants<T extends VariantTable>(table: T): VariantFn<T> {
const pick = (selection: Record<string, string | undefined>, key: string): string =>
(selection[key] ?? "").trim() || (table.defaultVariants[key] ?? "").trim();
const fn = (selection: VariantSelection<T> = {}): string => {
const sel = selection as Record<string, string | undefined>;
const parts: string[] = [table.base ?? ""];
for (const [key, choices] of Object.entries(table.variants)) {
const choice = pick(sel, key);
const cls = choices[choice];
// a typo in development is an error; in production the unknown value is dropped
if (cls === undefined && isDevEnv()) throw new Error(`[variants] unknown value "${choice}" for "${key}"`);
parts.push(cls ?? "");
}
for (const compound of table.compoundVariants ?? []) {
const matches = Object.entries(compound).every(([k, want]) => k === "class" || want.split("|").includes(pick(sel, k)));
if (matches) parts.push(compound.class);
}
return cn(...parts.map((p) => p.trim()).filter(Boolean));
};
return Object.assign(fn, { table });
}
Point the CLI at this runtime once, then add the item:
npx ui8kit init --yes --framework react --dir src --registry-url https://registry.buildy.tw/react --strict-cdnnpx ui8kit add utilsimport { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
/**
* Merge class values with Tailwind conflict resolution.
* Mirrors shadcn's `cn` = clsx + tailwind-merge.
* Caller-supplied classes win over recipe classes.
*/
export function cn(...inputs: ClassValue[]): string {
return twMerge(clsx(inputs));
}
/**
* Dev-only warnings switch, bundle-agnostic (no ESM-only meta property, so the utils work in ESM, CJS, IIFE / classic
* script bundles, e.g. the web components). On when `globalThis.__UI8KIT_DEV__ === true`, or when a bundler
* defines `process.env.NODE_ENV` as "development".
*/
export function isDevEnv(): boolean {
const g = globalThis as { __UI8KIT_DEV__?: unknown; process?: { env?: { NODE_ENV?: string } } };
if (typeof g.__UI8KIT_DEV__ === "boolean") return g.__UI8KIT_DEV__;
try {
return g.process?.env?.NODE_ENV === "development";
} catch {
return false;
}
}
/**
* Tiny attribute-logic helpers used by generated components. One
* implementation per runtime family keeps every default-resolution decision
* table byte-identical across React, Svelte, and Vue (mirrors `expr.go`).
*/
export const trimStr = (v: string | number | null | undefined): string =>
v === null || v === undefined ? "" : String(v).trim();
export const isSetStr = (v: string | null | undefined): boolean => trimStr(v) !== "";
export const isSetNum = (v: number | null | undefined): boolean => (v ?? 0) > 0;
/**
* `trim(v) === "" ? fallback : trim(v)` — DefaultInputType-style defaults.
* Generic so enum-typed props keep their literal union through the default.
*/
export const defaultIfEmpty = <T extends string>(v: T | null | undefined, fallback: T): T => {
const t = trimStr(v) as T;
return t === "" ? fallback : t;
};
/** Whitelist: returns `trim(v)` when in `allowed`, otherwise `fallback`. */
export const oneOfOr = <T extends string>(
v: string | null | undefined,
fallback: T,
...allowed: T[]
): T => {
const t = trimStr(v) as T;
return allowed.includes(t) ? t : fallback;
};
export const oneOfOrLower = <T extends string>(
v: string | null | undefined,
fallback: T,
...allowed: T[]
): T => {
const t = trimStr(v).toLowerCase() as T;
return allowed.includes(t) ? t : fallback;
};
/** Decision table: `mapping[trim(v)] ?? fallback`. */
export const mapOr = <T extends string>(
v: string | null | undefined,
mapping: Record<string, T>,
fallback: T
): T => mapping[trimStr(v)] ?? fallback;
export const mapOrLower = <T extends string>(
v: string | null | undefined,
mapping: Record<string, T>,
fallback: T
): T => mapping[trimStr(v).toLowerCase()] ?? fallback;
/** Integer decision table: `mapping[v] ?? fallback`. */
export const intMapOr = <T extends string>(
v: number | null | undefined,
mapping: Record<number, T>,
fallback: T
): T => mapping[v ?? 0] ?? fallback;
/** Null-safe string equality (both sides normalized to ""). */
export const eqStr = (a: string | null | undefined, b: string | null | undefined): boolean =>
(a ?? "") === (b ?? "");
/** ARIA state stringification: always "true"/"false", never omitted. */
export const boolStr = (v: boolean | null | undefined): "true" | "false" =>
v ? "true" : "false";
/** Tri-state ARIA state: "true"/"false" when set, "" when unset (attribute omitted). */
export const optBoolStr = (v: boolean | null | undefined): "true" | "false" | "" =>
v === true ? "true" : v === false ? "false" : "";
/** Concatenation of trimmed parts (icon `Prefix + Name`). */
export const concatTrim = (...parts: (string | null | undefined)[]): string =>
parts.map(trimStr).join("");
/** Omit-if-empty attribute value: `""` → `undefined` so the attr is dropped. */
export const orUndef = <T extends string>(v: T | null | undefined): Exclude<T, ""> | undefined => {
const t = trimStr(v);
return t === "" ? undefined : (String(v) as Exclude<T, "">);
};
/**
* Sync a form control's live `value` property (never an attribute, so SSR
* markup is untouched). `undefined` leaves the current selection alone, so
* the children's initial `selected` state stays in charge. Usable directly as
* a Svelte action (`use:syncValue={value}`) and from Solid refs / WC renderers.
*/
export function syncValue(node: { value: string }, value?: string | null): { update(v?: string | null): void } {
const apply = (v?: string | null): void => {
if (v !== undefined && v !== null && node.value !== v) node.value = v;
};
apply(value);
return { update: apply };
}
const DATA_IMAGE = /^data:image\/(png|jpeg|gif|webp|avif|svg\+xml)[;,]/;
/**
* URL attribute value: "" for javascript:, vbscript: and data: (ASCII whitespace/control chars removed,
* case-insensitive). `dataImage` (only `<img src>`) allows data:image/(png|jpeg|gif|webp|avif|svg+xml).
*/
export const safeUrl = (v: string | null | undefined, dataImage = false): string => {
const k = String(v ?? "").replace(/[\u0000-\u0020]/g, "").toLowerCase();
return /^(javascript|vbscript|data):/.test(k) && !(dataImage && DATA_IMAGE.test(k)) ? "" : (v ?? "");
};
/** Per-element rest rule: `img` allows data:image in `src`; `blank` lists optional attrs (lowercase) omitted when blank. */
export type RestRule = { readonly img?: boolean; readonly blank?: readonly string[] };
const URL_KEYS = new Set(["href", "src", "action", "formaction", "poster", "cite", "background", "xlink:href", "xlinkhref"]);
/** True when a rest entry must be omitted: an unsafe URL or a blank optional attribute (`value` is never in `blank`). */
export function dropRestKey(k: string, v: unknown, rule?: RestRule): boolean {
if (typeof v !== "string") return false;
const key = k.toLowerCase();
if (rule?.blank?.includes(key) && v.trim() === "") return true;
return v !== "" && URL_KEYS.has(key) && safeUrl(v, rule?.img === true && key === "src") === "";
}
/** Rest props / caller attrs without unsafe URLs and blank optional attributes; identity when clean. */
export function safeRest<T extends object>(rest: T, rule?: RestRule): T {
const bad = Object.keys(rest).filter((k) => dropRestKey(k, (rest as Record<string, unknown>)[k], rule));
if (bad.length === 0) return rest;
const out = { ...rest } as Record<string, unknown>;
for (const k of bad) delete out[k];
return out as T;
}
export { cn } from "./cn";
export { isDevEnv } from "./env";
export type { RecipeKey, VariantRecipe } from "./recipe-types";
export {
compose,
composeRecipe,
recipeToVariants,
type RecipeSelection,
type Variants,
} from "./variants";
export { BOX_TAGS, TEXT_TAGS, TagGroup, isAllowedTag, resolveTag, type BoxTag, type TextTag } from "./tags";
export * from "./expr";
/**
* Type helpers to derive literal unions from `*.variants.json` recipes.
* Usage:
* import buttonRecipe from "./button.variants.json";
* type ButtonVariant = RecipeKey<typeof buttonRecipe, "variant">;
* // ^? "default" | "destructive" | "ghost" | ...
*/
export type VariantRecipe = {
id: string;
base: string;
keys: string[];
defaults: Record<string, string>;
byKey: Record<string, Record<string, string>>;
};
/**
* Extract the literal union of variant keys for a given recipe dimension.
* Empty string (used as a fallback in some JSON recipes) is excluded so
* consumers get only meaningful values in autocomplete.
*/
export type RecipeKey<
R extends VariantRecipe,
K extends keyof R["byKey"] & string,
> = Exclude<keyof R["byKey"][K] & string, "">;
// Mirrors src/domain/tags.ts (the SSOT). DO NOT EDIT in generated output.
import { isDevEnv } from "./env";
export const BOX_TAGS = [
"div", "section", "article", "aside", "header", "footer", "main", "nav", "figure", "search",
"ul", "ol", "li", "dl", "dt", "dd", "fieldset",
"table", "thead", "tbody", "tfoot", "tr", "th", "td", "caption", "colgroup", "col",
] as const;
export const TEXT_TAGS = [
"p", "span", "h1", "h2", "h3", "h4", "h5", "h6", "blockquote", "figcaption", "pre", "code",
"small", "strong", "em", "time", "legend", "del", "ins",
] as const;
export type BoxTag = (typeof BOX_TAGS)[number];
export type TextTag = (typeof TEXT_TAGS)[number];
export const TagGroup = { Box: "Box", Text: "Text" } as const;
export type TagGroup = (typeof TagGroup)[keyof typeof TagGroup];
const groups: Record<TagGroup, ReadonlySet<string>> = {
Box: new Set<string>(BOX_TAGS),
Text: new Set<string>(TEXT_TAGS),
};
const warned = new Set<string>();
export function isAllowedTag(tag: string, group: TagGroup): boolean {
return groups[group]?.has(tag.trim().toLowerCase()) ?? false;
}
export function resolveTag(tag: string | undefined, fallback: string, group: TagGroup): string {
const t = tag?.trim().toLowerCase() ?? "";
if (!t) return fallback;
if (isAllowedTag(t, group)) return t;
if (isDevEnv()) {
const key = `${group}:${t}`;
if (!warned.has(key)) {
warned.add(key);
console.warn(`[resolveTag] "${t}" is not an allowed ${group} tag; using "${fallback}".`);
}
}
return fallback;
}
import { cn } from "./cn";
import { isDevEnv } from "./env";
import type { RecipeKey, VariantRecipe } from "./recipe-types";
export type { RecipeKey, VariantRecipe };
export type Variants = {
id?: string;
base: string;
keys: string[];
defaults: Record<string, string>;
byKey: Record<string, Record<string, string>>;
};
export function recipeToVariants<R extends VariantRecipe>(recipe: R): Variants {
return {
id: recipe.id,
base: recipe.base,
keys: recipe.keys,
defaults: recipe.defaults ?? {},
byKey: recipe.byKey,
};
}
/**
* Merge base, variant selections, and optional tail classes.
* Mirrors the canonical `composeRecipe`.
*/
export function compose(
v: Variants,
selection: Record<string, string>,
...extra: (string | undefined | null | false)[]
): string {
const parts: string[] = [];
if (v.base.trim() !== "") {
parts.push(v.base.trim());
}
for (const key of v.keys) {
const choices = v.byKey[key];
if (!choices) continue;
const selected = (selection[key] ?? "").trim();
const fallback = (v.defaults[key] ?? "").trim();
const choice = selected || fallback;
if (!choice) {
if (isDevEnv() && Object.keys(choices).length > 0) {
throw new Error(
`[compose] missing default for key "${key}" (recipe id: ${String(v.id ?? "?")})`
);
}
continue;
}
const cls = choices[choice];
if (cls !== undefined) {
if (cls.trim() !== "") parts.push(cls.trim());
} else if (isDevEnv()) {
throw new Error(
`[compose] unknown variant "${choice}" for key "${key}" (recipe id: ${String(v.id ?? "?")})`
);
}
// Unknown choices are silently dropped in production to avoid leaking
// typos into the DOM as literal class names.
}
return cn(...parts, ...extra);
}
/** Selection type for `composeRecipe`. */
export type RecipeSelection<R extends VariantRecipe> = {
[K in keyof R["byKey"] & string]?: RecipeKey<R, K> | undefined;
};
/** Compose classes from a typed recipe. */
export function composeRecipe<R extends VariantRecipe>(
recipe: R,
selection: RecipeSelection<R>,
...extra: (string | undefined | null | false)[]
): string {
return compose(recipeToVariants(recipe), selection as Record<string, string>, ...extra);
}
/* Code generated by compose-gen. DO NOT EDIT. */
/* Entry of the styles: theme tokens and the kit CSS. @source makes Tailwind v4 scan the compositions and the installed primitives. */
@import "./theme.css";
@import "./kit.css";
@source "../";
@source "../kit";
/* Kit-wide CSS: base layer, input glyph utilities, focus ring. Colors and the one corner token (--radius) come from theme.css (shadcn neutral);
shadows: only floating layers have one (shadow-md, shadow-lg), set in their specs; nothing here draws one. */
@layer base {
html, body { margin: 0; background: var(--color-background); color: var(--color-foreground); }
body { -webkit-font-smoothing: antialiased; text-rendering: geometricPrecision; overflow-x: hidden; }
button { cursor: pointer; }
html { -webkit-text-size-adjust: 100%; color-scheme: light; }
}
/* the box of a checkbox: its corner is the theme radius scaled to the 16-20px box (0.4 x 10px = 4px), so it never reads as a radio */
@utility checkbox-glyph {
display: inline-grid; place-content: center; border-radius: calc(var(--radius) * 0.4);
&::before { content: ""; width: 8px; height: 6px; opacity: 0; background: currentColor;
clip-path: polygon(0 55%, 14% 40%, 38% 64%, 86% 0, 100% 15%, 38% 95%); }
&:checked { color: var(--color-primary-foreground); }
&:checked::before { opacity: 1; }
}
/* a number field without the browser spin buttons (NumberField draws its own minus and plus) */
@utility number-bare {
appearance: textfield; -moz-appearance: textfield;
&::-webkit-inner-spin-button, &::-webkit-outer-spin-button { -webkit-appearance: none; margin: 0; }
}
@utility radio-glyph {
display: inline-grid; place-content: center;
&::before { content: ""; width: var(--dot); height: var(--dot); border-radius: 9999px; background: var(--color-primary-foreground); opacity: 0; }
&:checked::before { opacity: 1; }
}
@utility switch-knob {
&::before { content: ""; position: absolute; top: 50%; left: var(--pad); width: var(--knob); height: var(--knob); border-radius: 9999px;
background: var(--color-background); translate: 0 -50%; transition: left .15s; }
&:checked::before { left: calc(100% - var(--pad) - var(--knob)); }
}
@utility progress-bar {
&::-webkit-progress-bar { background: transparent; }
&::-webkit-progress-value { background: var(--bar); border-radius: var(--radius); }
&::-moz-progress-bar { background: var(--bar); border-radius: var(--radius); }
&::-webkit-meter-bar { background: transparent; border: 0; }
&::-webkit-meter-optimum-value { background: var(--bar); }
}
/* Focus ring sits above utility shadows. Keyboard only. The 4px halo is gray unless the element sets a ring colour
(shadcn style, e.g. focus-visible:ring-destructive/20 on the destructive variants); --tw-ring-color does not inherit. */
:where(a, button, input, select, textarea, summary, [role="tab"], [role="menuitem"], [role="menuitemradio"], [role="option"], [role="treeitem"], [role="radio"], [role="switch"], [tabindex]):focus-visible {
outline: none;
box-shadow: var(--tw-inset-shadow, 0 0 #0000), var(--tw-inset-ring-shadow, 0 0 #0000), 0 0 0 4px var(--tw-ring-color, rgb(128 128 128 / 0.15)), var(--tw-shadow, 0 0 #0000);
}
[data-slot="prompt-input"]:focus-within, [data-slot="smartbox"]:focus-within { box-shadow: 0 0 0 4px rgb(128 128 128 / 0.15), inset 0 0 0 1px var(--color-border); }
[data-slot="prompt-input"] textarea:focus-visible, [data-slot="smartbox"] input:focus-visible { box-shadow: none; }
[data-slot="file-tree-item"]:focus-visible, [data-slot="editor-tab"]:focus-visible, [data-slot="icon-tab"]:focus-visible, [data-slot="dropdown-item"]:focus-visible {
box-shadow: inset 0 0 0 2px rgb(128 128 128 / 0.15), inset 0 0 0 1px var(--color-muted-foreground);
}
:where([data-screen]) :focus:not(:focus-visible) { outline: none; }
::selection { background: color-mix(in srgb, var(--color-primary) 15%, transparent); }
/* The disclosure indicator: the Lucide chevron-down drawn in the text colour; the Summary brick turns it over when its
details open (group-open:rotate-180), so an accordion needs no script. */
[data-slot="summary-indicator"] {
display: inline-block;
background-color: currentColor;
mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E") center / contain no-repeat;
}
/* Per-element tokens (UI8KIT-2.0 §11): badge, button, card, alert, media. An unset token falls back to the value of the utility class the
rule matches (p-6, px-4 h-10, ...), stated explicitly: a revert-layer fallback inside var() is not supported by every
browser (there the property became unset: buttons and badges lost their padding and height).
A skin or a scope (a wrapper, the magazine specimen) sets only the ones it wants.
Radius: --radius-badge|button|card|alert|media (unset: var(--radius); the badge unset: the pill). Only elements that carry plain `rounded` follow it.
Shadow: --shadow-card|alert|media (unset: the spec's own: none). A full box-shadow layer, e.g. var(--shadow-sm) or 0 0 #0000.
Density: data-density-badge|button|card|alert = compact | default | comfortable, on the element or any ancestor, sets --pad-*:
card 16/24/32 (padding of a default card), alert inline 8/8/16 with --min-alert 24/32/40,
button inline 12/16/20 and height 32/40/48 (default size), badge inline 8/12/16 and height 20/24/28 (default size).
4px steps only inside controls (button, badge); card and alert stay on the 8px step. */
[data-slot="button"].rounded { border-radius: var(--radius-button, var(--radius)); }
[data-slot="card"].rounded { border-radius: var(--radius-card, var(--radius)); }
[data-slot="alert"].rounded { border-radius: var(--radius-alert, var(--radius)); }
[data-slot="media-frame"].rounded { border-radius: var(--radius-media, var(--radius)); }
[data-slot="badge"].rounded-full { border-radius: var(--radius-badge, calc(infinity * 1px)); }
[data-slot="card"] { --tw-shadow: var(--shadow-card, 0 0 #0000); }
[data-slot="alert"] { --tw-shadow: var(--shadow-alert, 0 0 #0000); }
[data-slot="media-frame"] { --tw-shadow: var(--shadow-media, 0 0 #0000); }
[data-slot="card"].p-6 { padding: var(--pad-card, calc(var(--spacing) * 6)); }
[data-slot="alert"].px-2 { padding-inline: var(--pad-alert, calc(var(--spacing) * 2)); }
[data-slot="alert"].min-h-8 { min-height: var(--min-alert, calc(var(--spacing) * 8)); }
[data-slot="button"].px-4.h-10 { padding-inline: var(--pad-button, calc(var(--spacing) * 4)); height: var(--h-button, calc(var(--spacing) * 10)); }
[data-slot="badge"].px-3.h-6 { padding-inline: var(--pad-badge, calc(var(--spacing) * 3)); height: var(--h-badge, calc(var(--spacing) * 6)); }
[data-density-card="compact"] { --pad-card: 16px; }
[data-density-card="comfortable"] { --pad-card: 32px; }
[data-density-alert="compact"] { --pad-alert: 8px; --min-alert: 24px; }
[data-density-alert="comfortable"] { --pad-alert: 16px; --min-alert: 40px; }
[data-density-button="compact"] { --pad-button: 12px; --h-button: 32px; }
[data-density-button="comfortable"] { --pad-button: 20px; --h-button: 48px; }
[data-density-badge="compact"] { --pad-badge: 8px; --h-badge: 20px; }
[data-density-badge="comfortable"] { --pad-badge: 16px; --h-badge: 28px; }
/* Owned by codegen-x (UI8Kit 3: ui8kit/codegen ships no theme). Forked from vendor/codegen 2309848; adds --destructive-foreground (AA). */
@import "tailwindcss";
/* shadcn/ui neutral theme (Tailwind v4, written as hsl() for old browsers; same colours as the oklch values published at https://ui.shadcn.com/docs/theming
("Default Theme CSS", base color neutral). Dark mode: the .dark class or data-theme="dark" on an ancestor. */
@custom-variant dark (&:is(.dark *, [data-theme="dark"] *));
/* The one corner token. Plain `rounded` reads the bare --radius theme key, so every corner of the kit follows it
(shadcn keeps --radius in :root; here it sits in @theme so that `rounded` resolves to it; same value, 0.625rem). */
@theme {
--radius: 0.625rem;
}
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--color-card: var(--card);
--color-card-foreground: var(--card-foreground);
--color-popover: var(--popover);
--color-popover-foreground: var(--popover-foreground);
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
--color-secondary: var(--secondary);
--color-secondary-foreground: var(--secondary-foreground);
--color-muted: var(--muted);
--color-muted-foreground: var(--muted-foreground);
--color-accent: var(--accent);
--color-accent-foreground: var(--accent-foreground);
--color-destructive: var(--destructive);
--color-destructive-foreground: var(--destructive-foreground);
--color-destructive-hover: var(--destructive-hover);
--color-border: var(--border);
--color-input: var(--input);
--color-ring: var(--ring);
--color-chart-1: var(--chart-1);
--color-chart-2: var(--chart-2);
--color-chart-3: var(--chart-3);
--color-chart-4: var(--chart-4);
--color-chart-5: var(--chart-5);
--color-sidebar: var(--sidebar);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-ring: var(--sidebar-ring);
--radius-sm: calc(var(--radius) * 0.6);
--radius-md: calc(var(--radius) * 0.8);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) * 1.4);
--radius-2xl: calc(var(--radius) * 1.8);
--radius-3xl: calc(var(--radius) * 2.2);
--radius-4xl: calc(var(--radius) * 2.6);
}
:root {
--background: hsl(0 0% 100%);
--foreground: hsl(0 0% 4%);
--card: hsl(0 0% 100%);
--card-foreground: hsl(0 0% 4%);
--popover: hsl(0 0% 100%);
--popover-foreground: hsl(0 0% 4%);
--primary: hsl(0 0% 9%);
--primary-foreground: hsl(0 0% 98%);
--secondary: hsl(0 0% 96%);
--secondary-foreground: hsl(0 0% 9%);
--muted: hsl(0 0% 96%);
--muted-foreground: hsl(0 0% 43.5%);
--accent: hsl(0 0% 96%);
--accent-foreground: hsl(0 0% 9%);
--destructive: hsl(0.6 88.4% 48%); /* L 52.5% -> 48%: white text reaches AA (4.70) */
--destructive-foreground: hsl(0 0% 100%);
--destructive-hover: hsl(0.6 88.4% 42%); /* 6 points away from the foreground: hover keeps AA */
--border: hsl(0 0% 90%);
--input: hsl(0 0% 90%);
--ring: hsl(0 0% 63%);
--chart-1: hsl(18 100% 48%);
--chart-2: hsl(174.7 100% 29.5%);
--chart-3: hsl(196 72% 23%);
--chart-4: hsl(43.6 100% 50%);
--chart-5: hsl(36.3 100% 49.7%);
--sidebar: hsl(0 0% 98%);
--sidebar-foreground: hsl(0 0% 4%);
--sidebar-primary: hsl(0 0% 9%);
--sidebar-primary-foreground: hsl(0 0% 98%);
--sidebar-accent: hsl(0 0% 96%);
--sidebar-accent-foreground: hsl(0 0% 9%);
--sidebar-border: hsl(0 0% 90%);
--sidebar-ring: hsl(0 0% 63%);
}
:is(.dark, [data-theme="dark"]) {
--background: hsl(0 0% 4%);
--foreground: hsl(0 0% 98%);
--card: hsl(0 0% 9%);
--card-foreground: hsl(0 0% 98%);
--popover: hsl(0 0% 9%);
--popover-foreground: hsl(0 0% 98%);
--primary: hsl(0 0% 90%);
--primary-foreground: hsl(0 0% 9%);
--secondary: hsl(0 0% 15%);
--secondary-foreground: hsl(0 0% 98%);
--muted: hsl(0 0% 15%);
--muted-foreground: hsl(0 0% 63%);
--accent: hsl(0 0% 15%);
--accent-foreground: hsl(0 0% 98%);
--destructive: hsl(356.1 62.4% 52%);
--destructive-foreground: hsl(0 0% 100%);
--destructive-hover: hsl(356.1 62.4% 46%);
--border: hsl(0 0% 100% / 10%);
--input: hsl(0 0% 100% / 15%);
--ring: hsl(0 0% 45%);
--chart-1: hsl(225.3 84.1% 49%);
--chart-2: hsl(160 100% 37%);
--chart-3: hsl(36.3 100% 49.7%);
--chart-4: hsl(273.3 100% 63.8%);
--chart-5: hsl(345 100% 56%);
--sidebar: hsl(0 0% 9%);
--sidebar-foreground: hsl(0 0% 98%);
--sidebar-primary: hsl(225.3 84.1% 49%);
--sidebar-primary-foreground: hsl(0 0% 98%);
--sidebar-accent: hsl(0 0% 15%);
--sidebar-accent-foreground: hsl(0 0% 98%);
--sidebar-border: hsl(0 0% 100% / 10%);
--sidebar-ring: hsl(0 0% 45%);
}
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
}
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
// Framework-free: the function takes the node and returns the cleanup. Svelte: call it from an action or an effect; React: call it in an effect.
export type DismissReason = "escape" | "outside";
const stack: object[] = []; // topmost dismissable layer handles Escape first (menu inside off-canvas sidebar, …)
/** Escape and pointer-down outside the node call onDismiss. Returns the cleanup. */
export function dismissable(node: HTMLElement, opts: () => { onDismiss: (reason: DismissReason) => void; ignore?: () => (Element | null | undefined)[]; outside?: boolean }): () => void {
{
const layer = {};
stack.push(layer);
const { onDismiss, ignore = () => [], outside = true } = opts();
const onKey = (e: KeyboardEvent) => {
if (e.key !== "Escape" || e.defaultPrevented || stack[stack.length - 1] !== layer) return;
e.preventDefault(); e.stopPropagation();
onDismiss("escape");
};
const onDown = (e: PointerEvent) => {
if (!outside || stack[stack.length - 1] !== layer) return;
const t = e.target as Node | null;
if (!t || node.contains(t) || ignore().some((el) => el?.contains(t))) return;
onDismiss("outside");
};
document.addEventListener("keydown", onKey, true);
document.addEventListener("pointerdown", onDown, true);
return () => {
document.removeEventListener("keydown", onKey, true);
document.removeEventListener("pointerdown", onDown, true);
const i = stack.indexOf(layer); if (i >= 0) stack.splice(i, 1);
};
}
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
// Framework-free: the function takes the node and returns the cleanup. Svelte: call it from an action or an effect; React: call it in an effect.
import { focusables } from "./focusable";
/** Tab/Shift+Tab cycle inside `node`; on cleanup focus returns to the element focused before. */
export function trapFocus(node: HTMLElement): () => void {
const previous = document.activeElement as HTMLElement | null;
if (!node.contains(previous)) queueMicrotask(() => focusables(node)[0]?.focus());
const onKey = (e: KeyboardEvent) => {
if (e.key !== "Tab") return;
const items = focusables(node);
if (!items.length) { e.preventDefault(); return; }
const first = items[0], last = items[items.length - 1], cur = document.activeElement;
if (e.shiftKey && (cur === first || !node.contains(cur))) { e.preventDefault(); last.focus(); }
else if (!e.shiftKey && (cur === last || !node.contains(cur))) { e.preventDefault(); first.focus(); }
};
node.addEventListener("keydown", onKey);
return () => { node.removeEventListener("keydown", onKey); /* after the page is no longer inert */ requestAnimationFrame(() => { if (previous?.isConnected) previous.focus(); }); };
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
// Small headless helpers shared by the interactive primitives (menus, dialogs, tabs, off-canvas sidebar).
export const FOCUSABLE = 'a[href],button:not([disabled]),input:not([disabled]):not([type="hidden"]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])';
/** visible, tabbable descendants of `root` in DOM order */
export function focusables(root: HTMLElement): HTMLElement[] {
return [...root.querySelectorAll<HTMLElement>(FOCUSABLE)].filter((el) => !el.closest("[inert]") && el.getClientRects().length > 0 && getComputedStyle(el).visibility !== "hidden");
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
export { FOCUSABLE, focusables } from "./focusable";
export { moveFocus, typeahead, type RovingOptions } from "./roving";
export { lockScroll } from "./scroll-lock";
export { dismissable, type DismissReason } from "./dismiss";
export { trapFocus } from "./focus-trap";
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
// Arrow-key navigation over a list of focusable items (menus, listboxes, tab lists, trees).
export type RovingOptions = { orientation?: "vertical" | "horizontal" | "both"; loop?: boolean; activate?: boolean };
/** Handles ArrowUp/Down/Left/Right, Home, End. Returns true when the key was consumed. */
export function moveFocus(e: KeyboardEvent, items: HTMLElement[], { orientation = "vertical", loop = true, activate = false }: RovingOptions = {}): boolean {
if (!items.length || e.altKey || e.ctrlKey || e.metaKey) return false;
const prev = orientation !== "horizontal" ? ["ArrowUp"] : [];
const next = orientation !== "horizontal" ? ["ArrowDown"] : [];
if (orientation !== "vertical") { prev.push("ArrowLeft"); next.push("ArrowRight"); }
const cur = items.indexOf(document.activeElement as HTMLElement);
let idx = -1;
if (next.includes(e.key)) idx = cur < 0 ? 0 : cur + 1;
else if (prev.includes(e.key)) idx = cur < 0 ? items.length - 1 : cur - 1;
else if (e.key === "Home") idx = 0;
else if (e.key === "End") idx = items.length - 1;
else return false;
if (idx >= items.length) idx = loop ? 0 : items.length - 1;
if (idx < 0) idx = loop ? items.length - 1 : 0;
e.preventDefault();
const el = items[idx];
el.focus();
if (activate) el.click();
return true;
}
/** type-ahead: focus the next item whose text starts with the typed characters (reset after 600 ms) */
export function typeahead() {
let buf = "", t: ReturnType<typeof setTimeout> | undefined;
return (e: KeyboardEvent, items: HTMLElement[]): boolean => {
if (e.key.length !== 1 || e.ctrlKey || e.metaKey || e.altKey || e.key === " ") return false;
buf += e.key.toLowerCase();
clearTimeout(t); t = setTimeout(() => (buf = ""), 600);
const start = Math.max(0, items.indexOf(document.activeElement as HTMLElement) + (buf.length === 1 ? 1 : 0));
const ordered = [...items.slice(start), ...items.slice(0, start)];
const hit = ordered.find((el) => (el.textContent ?? "").trim().toLowerCase().startsWith(buf));
if (hit) { hit.focus(); e.preventDefault(); return true; }
return false;
};
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
// Reference-counted page scroll lock (off-canvas sidebar, modal dialog). Compensates the scrollbar width on desktop.
let count = 0;
let saved = { overflow: "", paddingRight: "" };
export function lockScroll(): () => void {
const root = document.documentElement;
if (count++ === 0) {
const sw = window.innerWidth - root.clientWidth;
saved = { overflow: root.style.overflow, paddingRight: root.style.paddingRight };
root.style.overflow = "hidden";
if (sw > 0) root.style.paddingRight = `${sw}px`;
root.setAttribute("data-scroll-locked", "");
}
let released = false;
return () => {
if (released) return; released = true;
if (--count === 0) {
root.style.overflow = saved.overflow; root.style.paddingRight = saved.paddingRight;
root.removeAttribute("data-scroll-locked");
}
};
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
/** Merge class values. Caller-supplied classes win over recipe classes. */
export function cn(...inputs: ClassValue[]): string {
return twMerge(clsx(inputs));
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
export function isDevEnv(): boolean {
try {
const env = (import.meta as unknown as { env?: { DEV?: boolean } }).env;
if (env && typeof env.DEV === "boolean") return env.DEV;
} catch {
// import.meta may be unavailable in some contexts
}
return false;
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
/**
* Tiny attribute-logic helpers used by generated components. One
* implementation per runtime family keeps every default-resolution decision
* table byte-identical across React, Svelte, and Vue (mirrors `expr.go`).
*/
export const trimStr = (v: string | number | null | undefined): string =>
v === null || v === undefined ? "" : String(v).trim();
export const isSetStr = (v: string | null | undefined): boolean => trimStr(v) !== "";
export const isSetNum = (v: number | null | undefined): boolean => (v ?? 0) > 0;
/**
* `trim(v) === "" ? fallback : trim(v)` — DefaultInputType-style defaults.
* Generic so enum-typed props keep their literal union through the default.
*/
export const defaultIfEmpty = <T extends string>(v: T | null | undefined, fallback: T): T => {
const t = trimStr(v) as T;
return t === "" ? fallback : t;
};
/** Whitelist: returns `trim(v)` when in `allowed`, otherwise `fallback`. */
export const oneOfOr = <T extends string>(
v: string | null | undefined,
fallback: T,
...allowed: T[]
): T => {
const t = trimStr(v) as T;
return allowed.includes(t) ? t : fallback;
};
export const oneOfOrLower = <T extends string>(
v: string | null | undefined,
fallback: T,
...allowed: T[]
): T => {
const t = trimStr(v).toLowerCase() as T;
return allowed.includes(t) ? t : fallback;
};
/** Decision table: `mapping[trim(v)] ?? fallback`. */
export const mapOr = <T extends string>(
v: string | null | undefined,
mapping: Record<string, T>,
fallback: T
): T => mapping[trimStr(v)] ?? fallback;
export const mapOrLower = <T extends string>(
v: string | null | undefined,
mapping: Record<string, T>,
fallback: T
): T => mapping[trimStr(v).toLowerCase()] ?? fallback;
/** Integer decision table: `mapping[v] ?? fallback`. */
export const intMapOr = <T extends string>(
v: number | null | undefined,
mapping: Record<number, T>,
fallback: T
): T => mapping[v ?? 0] ?? fallback;
/** Null-safe string equality (both sides normalized to ""). */
export const eqStr = (a: string | null | undefined, b: string | null | undefined): boolean =>
(a ?? "") === (b ?? "");
/** ARIA state stringification: always "true"/"false", never omitted. */
export const boolStr = (v: boolean | null | undefined): "true" | "false" =>
v ? "true" : "false";
/** Concatenation of trimmed parts (icon `Prefix + Name`). */
export const concatTrim = (...parts: (string | null | undefined)[]): string =>
parts.map(trimStr).join("");
/** Omit-if-empty attribute value: `""` → `undefined` so the attr is dropped. */
export const orUndef = (v: string | null | undefined): string | undefined => {
const t = trimStr(v);
return t === "" ? undefined : String(v);
};
export type HeadingLevel = 1 | 2 | 3 | 4 | 5 | 6;
/** h1–h6 from a heading level; 0/undefined/out-of-range default to h2. */
export const titleTag = (order: HeadingLevel | number | null | undefined): string => {
switch (order) {
case 1:
return "h1";
case 3:
return "h3";
case 4:
return "h4";
case 5:
return "h5";
case 6:
return "h6";
default:
return "h2";
}
};
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
// Text and number formatting shared by every generated organism and screen. Pure functions, no runtime dependency.
/** fills {0}, {1}... of a content template */
export function tpl(template: string | undefined, ...values: Array<string | number | undefined>): string {
return (template ?? "").replace(/\{(\d+)\}/g, (_m, i: string) => String(values[Number(i)] ?? ""));
}
const nf = new Intl.NumberFormat("en-US");
export function fmtNumber(n: number): string {
return nf.format(n);
}
/** digits of the minor unit (ISO 4217): cents for most currencies, none for JPY and KRW */
export function minorDigits(currency: string): number {
return currency === "JPY" || currency === "KRW" ? 0 : 2;
}
const moneyCache = new Map<string, Intl.NumberFormat>();
/** money in integer minor units (Codex v0.4: 1250 = 12.50 USD) -> "$12.50"; whole amounts drop the fraction: 1499_00 -> "$1,499" */
export function fmtMoney(minor: number, currency: string): string {
const d = minorDigits(currency);
const cents = Math.round(minor);
const frac = d > 0 && cents % 10 ** d !== 0 ? d : 0;
const key = `${currency}:${frac}`;
let f = moneyCache.get(key);
if (!f) {
f = new Intl.NumberFormat("en-US", { style: "currency", currency, minimumFractionDigits: frac, maximumFractionDigits: frac });
moneyCache.set(key, f);
}
return f.format(cents / 10 ** d);
}
/** a content word by key (the status of a record -> its label); the key itself when the dictionary has no entry */
export function at(dict: Record<string, string> | undefined, key: string): string {
return dict?.[key] ?? key;
}
/** the page numbers a pager shows: the first, the last and the neighbours of the current page; null is a gap */
export function pageWindow(page: number, pages: number): (number | null)[] {
const keep = new Set([1, pages, page - 1, page, page + 1].filter((n) => n >= 1 && n <= pages));
const out: (number | null)[] = [];
let prev = 0;
for (const n of [...keep].sort((a, b) => a - b)) {
if (n - prev > 1) out.push(null);
out.push(n);
prev = n;
}
return out;
}
/** a responsive column variant of Grid capped by the number of items, so no column stays empty: ("1-4", 3) -> "1-3", ("2-6", 4) -> "2-4" */
export function fitCols(cols: string, n: number): string {
const m = /^(\d+)-(\d+)$/.exec(cols);
if (!m) return cols;
const lo = Number(m[1]), hi = Number(m[2]);
if (n >= hi) return cols;
const top = Math.max(lo, n);
const known = ["1-2", "1-3", "1-4", "2-3", "2-4", "2-6", "3-6"];
for (let h = top; h > lo; h--) if (known.includes(`${lo}-${h}`)) return `${lo}-${h}`;
return String(Math.min(lo, Math.max(n, 1)));
}
/** a label of segments joined by ", " without a segment equal (case-insensitive) to the one before it:
* "Footer, Footer, Centered" -> "Footer, Centered" */
export function uniqLabel(label: string | undefined): string {
const parts = (label ?? "").split(", ");
return parts.filter((s, i) => i === 0 || s.toLowerCase() !== (parts[i - 1] ?? "").toLowerCase()).join(", ");
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
/**
* Trusted markup. A prop of type `TrustedHtml` carries markup from a trusted source (the `|html` pipe of readPath: the body of a
* Codex entry, or the host), and an `html` view node prints it without escaping. Every other value is text, and is escaped.
* The marker is React's own shape, `{ __html }`; a value without it (a plain string) is escaped by `htmlOf`, so markup is
* printed raw only when it was marked trusted. The same rules on every runtime: og_html (PHP, Python) and Html (Go).
*/
export type TrustedHtml = { readonly __html: string };
/** marks markup as trusted: only for a source the app trusts (the Codex body), never for user input */
export const trustHtml = (html: string): TrustedHtml => ({ __html: html });
export const isTrustedHtml = (v: unknown): v is TrustedHtml =>
v !== null && typeof v === "object" && typeof (v as { __html?: unknown }).__html === "string";
const ENTITIES: Record<string, string> = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" };
/** text as markup: & < > " ' as entities */
export const escapeHtml = (s: string): string => s.replace(/[&<>"']/g, (c) => ENTITIES[c]!);
/** the markup an `html` node prints: the trusted markup as it is, any other value escaped as text (nothing for null and booleans, like a text node) */
export const htmlOf = (v: TrustedHtml | string | number | boolean | null | undefined): string =>
isTrustedHtml(v) ? v.__html : v === null || v === undefined || typeof v === "boolean" ? "" : escapeHtml(String(v));
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
export { cn } from "./cn";
export { isDevEnv } from "./env";
export { variants, type VariantFn, type VariantKey, type VariantSelection, type VariantTable } from "./variants";
export { TagGroup, isAllowedTag, resolveTag } from "./tags";
export * from "./expr";
export { tpl, fmtNumber, fmtMoney, minorDigits, at, pageWindow, fitCols, uniqLabel } from "./format";
export * from "./a11y";
export { type TrustedHtml, trustHtml, isTrustedHtml, escapeHtml, htmlOf } from "./html";
export { decodeEntities, isSafeUrl, urlOf, srcsetOf, cssValue, srcsetUrls, styleOf, isSafeAttrName, attrValueOf, URL_ATTRS, IMAGE_ATTRS, URL_SCHEMES, NAMED_ENTITIES } from "./safe";
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
/**
* Output safety of the organism runtime (the same rules in PHP Runtime.php, Python runtime.py and Go dyn.go; the shared vectors
* are in packages/compose-gen/runtimes/core/test/safety-vectors.json). An allowlist, not a denylist:
* - a URL (href, src, action, formaction, poster, cite, background, data, xlink:href) is kept only when, read as a browser
* reads it (entities decoded, ASCII whitespace and control characters removed), it is a path or a reference with no scheme
* (`/path`, `#a`, `?q`, `page.html`) or its scheme is http, https, mailto or tel; an image URL may also be
* data:image/(png|jpeg|gif|webp|avif|svg+xml). A protocol-relative URL (`//host`, `/\host`, `\\host`) is refused.
* Anything else is "" (javascript:, vbscript:, data:text/html, livescript:, also behind case, entities or whitespace).
* - a srcset is checked candidate by candidate (each URL an image URL); one bad candidate refuses the whole value.
* - a style is refused ("") when a url(...) inside it is not an image URL, or it holds expression(, a script scheme,
* -moz-binding, behavior: or a CSS escape (a backslash).
* - an attribute name is printed only when it matches ^[a-zA-Z_:][-a-zA-Z0-9_:.]*$ and does not start with "on".
*/
/** the named character references the check decodes (those that spell URL syntax, whitespace or the markup characters) */
export const NAMED_ENTITIES: Readonly<Record<string, string>> = {
Tab: "\t", NewLine: "\n", colon: ":", sol: "/", bsol: "\\", lpar: "(", rpar: ")", amp: "&", lt: "<", gt: ">", quot: '"', apos: "'",
nbsp: "\u00a0", period: ".", comma: ",", excl: "!", num: "#", quest: "?", equals: "=", plus: "+", semi: ";", percnt: "%", lowbar: "_",
ast: "*", commat: "@", dollar: "$", Hat: "^", grave: "`", lsqb: "[", rsqb: "]", lcub: "{", rcub: "}", verbar: "|", vert: "|",
};
export const URL_SCHEMES: readonly string[] = ["http", "https", "mailto", "tel"];
const DATA_IMAGE = /^data:image\/(png|jpeg|gif|webp|avif|svg\+xml)[;,]/;
const ENTITY = /&(?:#[xX]([0-9a-fA-F]{1,8});?|#([0-9]{1,10});?|([a-zA-Z][a-zA-Z0-9]{0,31});)/g;
const fromCode = (n: number): string => (n > 0 && n <= 0x10ffff && !(n >= 0xd800 && n <= 0xdfff) ? String.fromCodePoint(n) : "\ufffd");
/** character references decoded as a browser would (numeric with or without `;`, the named ones of NAMED_ENTITIES), up to 3 rounds */
export function decodeEntities(s: string): string {
let out = s;
for (let i = 0; i < 3 && out.includes("&"); i++) {
out = out.replace(ENTITY, (m, hex: string | undefined, dec: string | undefined, name: string | undefined) =>
hex !== undefined ? fromCode(parseInt(hex, 16)) : dec !== undefined ? fromCode(parseInt(dec, 10)) : NAMED_ENTITIES[name!] ?? m);
}
return out;
}
/** the value as a URL parser sees it: entities decoded, ASCII whitespace and control characters (C0, space, DEL) removed */
const compact = (s: string): string => decodeEntities(s).replace(/[\u0000-\u0020\u007f]+/g, "");
/** true when the URL is allowed (see the file comment); `image`: data:image/* too */
export function isSafeUrl(v: string, image = false): boolean {
const k = compact(v);
if (/^[/\\]{2}/.test(k)) return false;
const m = /^([a-zA-Z][a-zA-Z0-9+.-]*):/.exec(k);
// no scheme: a path, unless a ":" comes before any "/" (as written or decoded), which templ.URL refuses too (one rule everywhere)
if (!m) return !/^[^/]*:/.test(k) && !/^[^/]*:/.test(v);
const scheme = m[1]!.toLowerCase();
if (scheme === "data") return image && DATA_IMAGE.test(k.toLowerCase());
return URL_SCHEMES.includes(scheme);
}
const str = (v: unknown): string => (typeof v === "string" ? v : typeof v === "number" ? String(v) : "");
/** a URL attribute value: the value when it is allowed, else "" (another non-string is ""); undefined and null stay as they are (the attribute is left out) */
export function urlOf<T>(v: T, image = false): string | Extract<T, null | undefined> {
if (v === undefined || v === null) return v as Extract<T, null | undefined>;
const s = str(v);
return isSafeUrl(s, image) ? s : "";
}
/** the URLs of a srcset, candidate by candidate (the URL of a candidate runs to the first whitespace; trailing commas end it) */
export function srcsetUrls(v: string): string[] {
const s = decodeEntities(v), out: string[] = [];
let i = 0;
const ws = (c: string | undefined) => c !== undefined && /[\t\n\f\r ]/.test(c);
while (i < s.length) {
while (i < s.length && (ws(s[i]) || s[i] === ",")) i++;
if (i >= s.length) break;
let j = i;
while (j < s.length && !ws(s[j])) j++;
let url = s.slice(i, j);
const cut = /,+$/.exec(url);
if (cut) { url = url.slice(0, -cut[0].length); out.push(url); i = j; continue; }
out.push(url);
let depth = 0;
while (j < s.length && (depth > 0 || s[j] !== ",")) { if (s[j] === "(") depth++; else if (s[j] === ")") depth = Math.max(0, depth - 1); j++; }
i = j + 1;
}
return out;
}
/** a srcset value: the value when every candidate URL is an allowed image URL, else "" */
export function srcsetOf<T>(v: T): string | Extract<T, null | undefined> {
if (v === undefined || v === null) return v as Extract<T, null | undefined>;
const s = str(v);
return srcsetUrls(s).every((u) => isSafeUrl(u, true)) ? s : "";
}
/** a value of an inline style declaration (the css op): kept when it is plain (numbers, words, %, #, +, -, ., commas and spaces), else ""; no url(), no ; */
export const cssValue = (v: unknown): string => { const s = str(v); return /^[-+.%#a-zA-Z0-9 ,]*$/.test(s) ? s : ""; };
/** a style value: "" when it could load or run something (see the file comment), else the value */
export function styleOf(v: unknown): string {
const s = str(v), d = decodeEntities(s), k = compact(s).toLowerCase();
if (d.includes("\\") || /expression\(|javascript:|vbscript:|-moz-binding|behavior:/.test(k)) return "";
for (const m of d.matchAll(/url\(([^)]*)\)?/gi)) if (!isSafeUrl(m[1]!.replace(/^[ \t\n\r\f\v]+|[ \t\n\r\f\v]+$/g, "").replace(/^(["'])([^]*)\1$/, "$2"), true)) return "";
return s;
}
/** an attribute name that may be printed: a valid XML-ish name, not an event handler (on*) */
export const isSafeAttrName = (name: string): boolean => /^[a-zA-Z_:][-a-zA-Z0-9_:.]*$/.test(name) && !/^on/i.test(name);
/** the attributes whose value is a URL (a srcset and a style have their own checks) */
export const URL_ATTRS: readonly string[] = ["href", "src", "action", "formaction", "poster", "cite", "background", "data", "xlink:href"];
/** the URL attributes whose URL is an image (data:image/* allowed) */
export const IMAGE_ATTRS: readonly string[] = ["src", "poster", "background"];
/** the value of attribute `name` as it may be printed: URL, srcset and style checked, any other value as it is */
export function attrValueOf(name: string, v: unknown): unknown {
const n = name.toLowerCase();
if (n === "srcset" || n === "imagesrcset") return srcsetOf(v);
if (n === "style") return styleOf(v);
if (URL_ATTRS.includes(n)) return urlOf(v, IMAGE_ATTRS.includes(n));
return v;
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
// Code generated by tagsgen. DO NOT EDIT.
import { isDevEnv } from "./env";
export const TagGroup = {
Layout: "Layout",
BoxAllowed: "BoxAllowed",
BlockText: "BlockText",
Inline: "Inline",
Heading: "Heading",
List: "List",
ListItem: "ListItem",
Form: "Form",
FormControl: "FormControl",
FormLabel: "FormLabel",
Table: "Table",
TableSection: "TableSection",
TableRow: "TableRow",
TableCell: "TableCell",
TableColumn: "TableColumn",
Media: "Media",
Disclosure: "Disclosure",
Container: "Container",
Stack: "Stack",
Group: "Group",
Text: "Text",
} as const;
export type TagGroup = (typeof TagGroup)[keyof typeof TagGroup];
const layoutTags = new Set(["div", "section", "article", "aside", "header", "footer", "main", "nav", "figure", "search", "hgroup"]);
const boxAllowedTags = new Set(["div"]);
const blockTextTags = new Set(["p", "blockquote", "figcaption", "address", "pre"]);
const inlineTags = new Set(["span", "em", "strong", "small", "abbr", "cite", "code", "kbd", "mark", "time", "data", "var", "samp", "sub", "sup", "b", "i", "u", "s", "q", "dfn", "bdo", "bdi", "ins", "del"]);
const headingTags = new Set(["h1", "h2", "h3", "h4", "h5", "h6"]);
const listTags = new Set(["ul", "ol", "dl", "menu"]);
const listItemTags = new Set(["li", "dt", "dd"]);
const formTags = new Set(["form", "fieldset"]);
const formControlTags = new Set(["input", "textarea", "select", "button", "option", "optgroup", "datalist", "output", "meter", "progress"]);
const formLabelTags = new Set(["label", "legend"]);
const tableTags = new Set(["table"]);
const tableSectionTags = new Set(["thead", "tbody", "tfoot"]);
const tableRowTags = new Set(["tr"]);
const tableCellTags = new Set(["th", "td"]);
const tableColumnTags = new Set(["colgroup", "col"]);
const mediaTags = new Set(["img", "picture", "source"]);
const disclosureTags = new Set(["details", "summary"]);
const containerTags = new Set(["div", "main", "section"]);
const stackTags = new Set(["div", "ul", "ol"]);
const groupTags = new Set(["div", "fieldset", "dl"]);
function oneOf(tag: string, options: Set<string>): boolean {
return options.has(tag);
}
const warnedTagFallbacks = new Set<string>();
function warnTagFallback(tag: string, fallback: string, group: TagGroup): void {
if (!isDevEnv()) return;
const key = `${group}:${tag}:${fallback}`;
if (warnedTagFallbacks.has(key)) return;
warnedTagFallbacks.add(key);
console.warn(`[resolveTag] disallowed tag "${tag}" for group "${group}", fallback "${fallback}" used.`);
}
export function isAllowedTag(tag: string, group: TagGroup): boolean {
const t = tag.trim().toLowerCase();
switch (group) {
case TagGroup.Layout:
return oneOf(t, layoutTags);
case TagGroup.BoxAllowed:
return oneOf(t, boxAllowedTags);
case TagGroup.BlockText:
return oneOf(t, blockTextTags);
case TagGroup.Inline:
return oneOf(t, inlineTags);
case TagGroup.Heading:
return oneOf(t, headingTags);
case TagGroup.List:
return oneOf(t, listTags);
case TagGroup.ListItem:
return oneOf(t, listItemTags);
case TagGroup.Form:
return oneOf(t, formTags);
case TagGroup.FormControl:
return oneOf(t, formControlTags);
case TagGroup.FormLabel:
return oneOf(t, formLabelTags);
case TagGroup.Table:
return oneOf(t, tableTags);
case TagGroup.TableSection:
return oneOf(t, tableSectionTags);
case TagGroup.TableRow:
return oneOf(t, tableRowTags);
case TagGroup.TableCell:
return oneOf(t, tableCellTags);
case TagGroup.TableColumn:
return oneOf(t, tableColumnTags);
case TagGroup.Media:
return oneOf(t, mediaTags);
case TagGroup.Disclosure:
return oneOf(t, disclosureTags);
case TagGroup.Container:
return oneOf(t, containerTags);
case TagGroup.Stack:
return oneOf(t, stackTags);
case TagGroup.Group:
return oneOf(t, groupTags);
case TagGroup.Text:
return blockTextTags.has(t) || inlineTags.has(t);
default:
return false;
}
}
export function resolveTag(tag: string | undefined, fallback: string, group: TagGroup): string {
const t = tag?.trim().toLowerCase() ?? "";
if (!t) return fallback;
if (isAllowedTag(t, group)) return t;
warnTagFallback(t, fallback, group);
return fallback;
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
import { cn } from "./cn";
import { isDevEnv } from "./env";
/**
* A shadcn/cva-style variant table, without the dependency (same idea as `cva` from class-variance-authority).
*
* const badgeVariants = variants({
* base: "inline-flex items-center",
* variants: { size: { sm: "h-5 px-2", lg: "h-8 px-3" } },
* defaultVariants: { size: "sm" },
* compoundVariants: [{ size: "lg", shape: "rounded", class: "rounded-lg" }],
* });
* badgeVariants({ size: "lg" }); // "inline-flex items-center h-8 px-3"
*
* Classes come in this order: base, each variant in table order, then the matching compound variants.
* tailwind-merge (`cn`) resolves conflicts, the later class wins. A compound value may list alternatives: "32|lg".
*/
export type VariantTable = {
base?: string;
variants: Record<string, Record<string, string>>;
defaultVariants: Record<string, string>;
compoundVariants?: Array<{ class: string } & Record<string, string>>;
};
/** the props a table accepts: one optional value per variant */
export type VariantSelection<T extends VariantTable> = {
[K in keyof T["variants"]]?: (keyof T["variants"][K] & string) | undefined;
};
/** a variant function: call it with the selected values, read `.table` for the types */
export type VariantFn<T extends VariantTable> = ((selection?: VariantSelection<T>) => string) & { table: T };
/** the values of one variant of a table: `VariantKey<typeof badgeVariants, "size">` is `"sm" | "lg"` */
export type VariantKey<F extends { table: VariantTable }, K extends keyof F["table"]["variants"]> = Exclude<
keyof F["table"]["variants"][K] & string,
""
>;
export function variants<T extends VariantTable>(table: T): VariantFn<T> {
const pick = (selection: Record<string, string | undefined>, key: string): string =>
(selection[key] ?? "").trim() || (table.defaultVariants[key] ?? "").trim();
const fn = (selection: VariantSelection<T> = {}): string => {
const sel = selection as Record<string, string | undefined>;
const parts: string[] = [table.base ?? ""];
for (const [key, choices] of Object.entries(table.variants)) {
const choice = pick(sel, key);
const cls = choices[choice];
// a typo in development is an error; in production the unknown value is dropped
if (cls === undefined && isDevEnv()) throw new Error(`[variants] unknown value "${choice}" for "${key}"`);
parts.push(cls ?? "");
}
for (const compound of table.compoundVariants ?? []) {
const matches = Object.entries(compound).every(([k, want]) => k === "class" || want.split("|").includes(pick(sel, k)));
if (matches) parts.push(compound.class);
}
return cn(...parts.map((p) => p.trim()).filter(Boolean));
};
return Object.assign(fn, { table });
}
Point the CLI at this runtime once, then add the item:
npx ui8kit init --yes --framework vue --dir src --registry-url https://registry.buildy.tw/vue --strict-cdnnpx ui8kit add utilsimport { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
/**
* Merge class values with Tailwind conflict resolution.
* Mirrors shadcn's `cn` = clsx + tailwind-merge.
* Caller-supplied classes win over recipe classes.
*/
export function cn(...inputs: ClassValue[]): string {
return twMerge(clsx(inputs));
}
/**
* Dev-only warnings switch, bundle-agnostic (no ESM-only meta property, so the utils work in ESM, CJS, IIFE / classic
* script bundles, e.g. the web components). On when `globalThis.__UI8KIT_DEV__ === true`, or when a bundler
* defines `process.env.NODE_ENV` as "development".
*/
export function isDevEnv(): boolean {
const g = globalThis as { __UI8KIT_DEV__?: unknown; process?: { env?: { NODE_ENV?: string } } };
if (typeof g.__UI8KIT_DEV__ === "boolean") return g.__UI8KIT_DEV__;
try {
return g.process?.env?.NODE_ENV === "development";
} catch {
return false;
}
}
/**
* Tiny attribute-logic helpers used by generated components. One
* implementation per runtime family keeps every default-resolution decision
* table byte-identical across React, Svelte, and Vue (mirrors `expr.go`).
*/
export const trimStr = (v: string | number | null | undefined): string =>
v === null || v === undefined ? "" : String(v).trim();
export const isSetStr = (v: string | null | undefined): boolean => trimStr(v) !== "";
export const isSetNum = (v: number | null | undefined): boolean => (v ?? 0) > 0;
/**
* `trim(v) === "" ? fallback : trim(v)` — DefaultInputType-style defaults.
* Generic so enum-typed props keep their literal union through the default.
*/
export const defaultIfEmpty = <T extends string>(v: T | null | undefined, fallback: T): T => {
const t = trimStr(v) as T;
return t === "" ? fallback : t;
};
/** Whitelist: returns `trim(v)` when in `allowed`, otherwise `fallback`. */
export const oneOfOr = <T extends string>(
v: string | null | undefined,
fallback: T,
...allowed: T[]
): T => {
const t = trimStr(v) as T;
return allowed.includes(t) ? t : fallback;
};
export const oneOfOrLower = <T extends string>(
v: string | null | undefined,
fallback: T,
...allowed: T[]
): T => {
const t = trimStr(v).toLowerCase() as T;
return allowed.includes(t) ? t : fallback;
};
/** Decision table: `mapping[trim(v)] ?? fallback`. */
export const mapOr = <T extends string>(
v: string | null | undefined,
mapping: Record<string, T>,
fallback: T
): T => mapping[trimStr(v)] ?? fallback;
export const mapOrLower = <T extends string>(
v: string | null | undefined,
mapping: Record<string, T>,
fallback: T
): T => mapping[trimStr(v).toLowerCase()] ?? fallback;
/** Integer decision table: `mapping[v] ?? fallback`. */
export const intMapOr = <T extends string>(
v: number | null | undefined,
mapping: Record<number, T>,
fallback: T
): T => mapping[v ?? 0] ?? fallback;
/** Null-safe string equality (both sides normalized to ""). */
export const eqStr = (a: string | null | undefined, b: string | null | undefined): boolean =>
(a ?? "") === (b ?? "");
/** ARIA state stringification: always "true"/"false", never omitted. */
export const boolStr = (v: boolean | null | undefined): "true" | "false" =>
v ? "true" : "false";
/** Tri-state ARIA state: "true"/"false" when set, "" when unset (attribute omitted). */
export const optBoolStr = (v: boolean | null | undefined): "true" | "false" | "" =>
v === true ? "true" : v === false ? "false" : "";
/** Concatenation of trimmed parts (icon `Prefix + Name`). */
export const concatTrim = (...parts: (string | null | undefined)[]): string =>
parts.map(trimStr).join("");
/** Omit-if-empty attribute value: `""` → `undefined` so the attr is dropped. */
export const orUndef = <T extends string>(v: T | null | undefined): Exclude<T, ""> | undefined => {
const t = trimStr(v);
return t === "" ? undefined : (String(v) as Exclude<T, "">);
};
/**
* Sync a form control's live `value` property (never an attribute, so SSR
* markup is untouched). `undefined` leaves the current selection alone, so
* the children's initial `selected` state stays in charge. Usable directly as
* a Svelte action (`use:syncValue={value}`) and from Solid refs / WC renderers.
*/
export function syncValue(node: { value: string }, value?: string | null): { update(v?: string | null): void } {
const apply = (v?: string | null): void => {
if (v !== undefined && v !== null && node.value !== v) node.value = v;
};
apply(value);
return { update: apply };
}
const DATA_IMAGE = /^data:image\/(png|jpeg|gif|webp|avif|svg\+xml)[;,]/;
/**
* URL attribute value: "" for javascript:, vbscript: and data: (ASCII whitespace/control chars removed,
* case-insensitive). `dataImage` (only `<img src>`) allows data:image/(png|jpeg|gif|webp|avif|svg+xml).
*/
export const safeUrl = (v: string | null | undefined, dataImage = false): string => {
const k = String(v ?? "").replace(/[\u0000-\u0020]/g, "").toLowerCase();
return /^(javascript|vbscript|data):/.test(k) && !(dataImage && DATA_IMAGE.test(k)) ? "" : (v ?? "");
};
/** Per-element rest rule: `img` allows data:image in `src`; `blank` lists optional attrs (lowercase) omitted when blank. */
export type RestRule = { readonly img?: boolean; readonly blank?: readonly string[] };
const URL_KEYS = new Set(["href", "src", "action", "formaction", "poster", "cite", "background", "xlink:href", "xlinkhref"]);
/** True when a rest entry must be omitted: an unsafe URL or a blank optional attribute (`value` is never in `blank`). */
export function dropRestKey(k: string, v: unknown, rule?: RestRule): boolean {
if (typeof v !== "string") return false;
const key = k.toLowerCase();
if (rule?.blank?.includes(key) && v.trim() === "") return true;
return v !== "" && URL_KEYS.has(key) && safeUrl(v, rule?.img === true && key === "src") === "";
}
/** Rest props / caller attrs without unsafe URLs and blank optional attributes; identity when clean. */
export function safeRest<T extends object>(rest: T, rule?: RestRule): T {
const bad = Object.keys(rest).filter((k) => dropRestKey(k, (rest as Record<string, unknown>)[k], rule));
if (bad.length === 0) return rest;
const out = { ...rest } as Record<string, unknown>;
for (const k of bad) delete out[k];
return out as T;
}
export { cn } from "./cn";
export { isDevEnv } from "./env";
export type { RecipeKey, VariantRecipe } from "./recipe-types";
export {
compose,
composeRecipe,
recipeToVariants,
type RecipeSelection,
type Variants,
} from "./variants";
export { BOX_TAGS, TEXT_TAGS, TagGroup, isAllowedTag, resolveTag, type BoxTag, type TextTag } from "./tags";
export * from "./expr";
/**
* Type helpers to derive literal unions from `*.variants.json` recipes.
* Usage:
* import buttonRecipe from "./button.variants.json";
* type ButtonVariant = RecipeKey<typeof buttonRecipe, "variant">;
* // ^? "default" | "destructive" | "ghost" | ...
*/
export type VariantRecipe = {
id: string;
base: string;
keys: string[];
defaults: Record<string, string>;
byKey: Record<string, Record<string, string>>;
};
/**
* Extract the literal union of variant keys for a given recipe dimension.
* Empty string (used as a fallback in some JSON recipes) is excluded so
* consumers get only meaningful values in autocomplete.
*/
export type RecipeKey<
R extends VariantRecipe,
K extends keyof R["byKey"] & string,
> = Exclude<keyof R["byKey"][K] & string, "">;
// Mirrors src/domain/tags.ts (the SSOT). DO NOT EDIT in generated output.
import { isDevEnv } from "./env";
export const BOX_TAGS = [
"div", "section", "article", "aside", "header", "footer", "main", "nav", "figure", "search",
"ul", "ol", "li", "dl", "dt", "dd", "fieldset",
"table", "thead", "tbody", "tfoot", "tr", "th", "td", "caption", "colgroup", "col",
] as const;
export const TEXT_TAGS = [
"p", "span", "h1", "h2", "h3", "h4", "h5", "h6", "blockquote", "figcaption", "pre", "code",
"small", "strong", "em", "time", "legend", "del", "ins",
] as const;
export type BoxTag = (typeof BOX_TAGS)[number];
export type TextTag = (typeof TEXT_TAGS)[number];
export const TagGroup = { Box: "Box", Text: "Text" } as const;
export type TagGroup = (typeof TagGroup)[keyof typeof TagGroup];
const groups: Record<TagGroup, ReadonlySet<string>> = {
Box: new Set<string>(BOX_TAGS),
Text: new Set<string>(TEXT_TAGS),
};
const warned = new Set<string>();
export function isAllowedTag(tag: string, group: TagGroup): boolean {
return groups[group]?.has(tag.trim().toLowerCase()) ?? false;
}
export function resolveTag(tag: string | undefined, fallback: string, group: TagGroup): string {
const t = tag?.trim().toLowerCase() ?? "";
if (!t) return fallback;
if (isAllowedTag(t, group)) return t;
if (isDevEnv()) {
const key = `${group}:${t}`;
if (!warned.has(key)) {
warned.add(key);
console.warn(`[resolveTag] "${t}" is not an allowed ${group} tag; using "${fallback}".`);
}
}
return fallback;
}
import { cn } from "./cn";
import { isDevEnv } from "./env";
import type { RecipeKey, VariantRecipe } from "./recipe-types";
export type { RecipeKey, VariantRecipe };
export type Variants = {
id?: string;
base: string;
keys: string[];
defaults: Record<string, string>;
byKey: Record<string, Record<string, string>>;
};
export function recipeToVariants<R extends VariantRecipe>(recipe: R): Variants {
return {
id: recipe.id,
base: recipe.base,
keys: recipe.keys,
defaults: recipe.defaults ?? {},
byKey: recipe.byKey,
};
}
/**
* Merge base, variant selections, and optional tail classes.
* Mirrors the canonical `composeRecipe`.
*/
export function compose(
v: Variants,
selection: Record<string, string>,
...extra: (string | undefined | null | false)[]
): string {
const parts: string[] = [];
if (v.base.trim() !== "") {
parts.push(v.base.trim());
}
for (const key of v.keys) {
const choices = v.byKey[key];
if (!choices) continue;
const selected = (selection[key] ?? "").trim();
const fallback = (v.defaults[key] ?? "").trim();
const choice = selected || fallback;
if (!choice) {
if (isDevEnv() && Object.keys(choices).length > 0) {
throw new Error(
`[compose] missing default for key "${key}" (recipe id: ${String(v.id ?? "?")})`
);
}
continue;
}
const cls = choices[choice];
if (cls !== undefined) {
if (cls.trim() !== "") parts.push(cls.trim());
} else if (isDevEnv()) {
throw new Error(
`[compose] unknown variant "${choice}" for key "${key}" (recipe id: ${String(v.id ?? "?")})`
);
}
// Unknown choices are silently dropped in production to avoid leaking
// typos into the DOM as literal class names.
}
return cn(...parts, ...extra);
}
/** Selection type for `composeRecipe`. */
export type RecipeSelection<R extends VariantRecipe> = {
[K in keyof R["byKey"] & string]?: RecipeKey<R, K> | undefined;
};
/** Compose classes from a typed recipe. */
export function composeRecipe<R extends VariantRecipe>(
recipe: R,
selection: RecipeSelection<R>,
...extra: (string | undefined | null | false)[]
): string {
return compose(recipeToVariants(recipe), selection as Record<string, string>, ...extra);
}
/* Code generated by compose-gen. DO NOT EDIT. */
/* Entry of the styles: theme tokens and the kit CSS. @source makes Tailwind v4 scan the compositions and the installed primitives. */
@import "./theme.css";
@import "./kit.css";
@source "../";
@source "../kit";
/* Kit-wide CSS: base layer, input glyph utilities, focus ring. Colors and the one corner token (--radius) come from theme.css (shadcn neutral);
shadows: only floating layers have one (shadow-md, shadow-lg), set in their specs; nothing here draws one. */
@layer base {
html, body { margin: 0; background: var(--color-background); color: var(--color-foreground); }
body { -webkit-font-smoothing: antialiased; text-rendering: geometricPrecision; overflow-x: hidden; }
button { cursor: pointer; }
html { -webkit-text-size-adjust: 100%; color-scheme: light; }
}
/* the box of a checkbox: its corner is the theme radius scaled to the 16-20px box (0.4 x 10px = 4px), so it never reads as a radio */
@utility checkbox-glyph {
display: inline-grid; place-content: center; border-radius: calc(var(--radius) * 0.4);
&::before { content: ""; width: 8px; height: 6px; opacity: 0; background: currentColor;
clip-path: polygon(0 55%, 14% 40%, 38% 64%, 86% 0, 100% 15%, 38% 95%); }
&:checked { color: var(--color-primary-foreground); }
&:checked::before { opacity: 1; }
}
/* a number field without the browser spin buttons (NumberField draws its own minus and plus) */
@utility number-bare {
appearance: textfield; -moz-appearance: textfield;
&::-webkit-inner-spin-button, &::-webkit-outer-spin-button { -webkit-appearance: none; margin: 0; }
}
@utility radio-glyph {
display: inline-grid; place-content: center;
&::before { content: ""; width: var(--dot); height: var(--dot); border-radius: 9999px; background: var(--color-primary-foreground); opacity: 0; }
&:checked::before { opacity: 1; }
}
@utility switch-knob {
&::before { content: ""; position: absolute; top: 50%; left: var(--pad); width: var(--knob); height: var(--knob); border-radius: 9999px;
background: var(--color-background); translate: 0 -50%; transition: left .15s; }
&:checked::before { left: calc(100% - var(--pad) - var(--knob)); }
}
@utility progress-bar {
&::-webkit-progress-bar { background: transparent; }
&::-webkit-progress-value { background: var(--bar); border-radius: var(--radius); }
&::-moz-progress-bar { background: var(--bar); border-radius: var(--radius); }
&::-webkit-meter-bar { background: transparent; border: 0; }
&::-webkit-meter-optimum-value { background: var(--bar); }
}
/* Focus ring sits above utility shadows. Keyboard only. The 4px halo is gray unless the element sets a ring colour
(shadcn style, e.g. focus-visible:ring-destructive/20 on the destructive variants); --tw-ring-color does not inherit. */
:where(a, button, input, select, textarea, summary, [role="tab"], [role="menuitem"], [role="menuitemradio"], [role="option"], [role="treeitem"], [role="radio"], [role="switch"], [tabindex]):focus-visible {
outline: none;
box-shadow: var(--tw-inset-shadow, 0 0 #0000), var(--tw-inset-ring-shadow, 0 0 #0000), 0 0 0 4px var(--tw-ring-color, rgb(128 128 128 / 0.15)), var(--tw-shadow, 0 0 #0000);
}
[data-slot="prompt-input"]:focus-within, [data-slot="smartbox"]:focus-within { box-shadow: 0 0 0 4px rgb(128 128 128 / 0.15), inset 0 0 0 1px var(--color-border); }
[data-slot="prompt-input"] textarea:focus-visible, [data-slot="smartbox"] input:focus-visible { box-shadow: none; }
[data-slot="file-tree-item"]:focus-visible, [data-slot="editor-tab"]:focus-visible, [data-slot="icon-tab"]:focus-visible, [data-slot="dropdown-item"]:focus-visible {
box-shadow: inset 0 0 0 2px rgb(128 128 128 / 0.15), inset 0 0 0 1px var(--color-muted-foreground);
}
:where([data-screen]) :focus:not(:focus-visible) { outline: none; }
::selection { background: color-mix(in srgb, var(--color-primary) 15%, transparent); }
/* The disclosure indicator: the Lucide chevron-down drawn in the text colour; the Summary brick turns it over when its
details open (group-open:rotate-180), so an accordion needs no script. */
[data-slot="summary-indicator"] {
display: inline-block;
background-color: currentColor;
mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E") center / contain no-repeat;
}
/* Per-element tokens (UI8KIT-2.0 §11): badge, button, card, alert, media. An unset token falls back to the value of the utility class the
rule matches (p-6, px-4 h-10, ...), stated explicitly: a revert-layer fallback inside var() is not supported by every
browser (there the property became unset: buttons and badges lost their padding and height).
A skin or a scope (a wrapper, the magazine specimen) sets only the ones it wants.
Radius: --radius-badge|button|card|alert|media (unset: var(--radius); the badge unset: the pill). Only elements that carry plain `rounded` follow it.
Shadow: --shadow-card|alert|media (unset: the spec's own: none). A full box-shadow layer, e.g. var(--shadow-sm) or 0 0 #0000.
Density: data-density-badge|button|card|alert = compact | default | comfortable, on the element or any ancestor, sets --pad-*:
card 16/24/32 (padding of a default card), alert inline 8/8/16 with --min-alert 24/32/40,
button inline 12/16/20 and height 32/40/48 (default size), badge inline 8/12/16 and height 20/24/28 (default size).
4px steps only inside controls (button, badge); card and alert stay on the 8px step. */
[data-slot="button"].rounded { border-radius: var(--radius-button, var(--radius)); }
[data-slot="card"].rounded { border-radius: var(--radius-card, var(--radius)); }
[data-slot="alert"].rounded { border-radius: var(--radius-alert, var(--radius)); }
[data-slot="media-frame"].rounded { border-radius: var(--radius-media, var(--radius)); }
[data-slot="badge"].rounded-full { border-radius: var(--radius-badge, calc(infinity * 1px)); }
[data-slot="card"] { --tw-shadow: var(--shadow-card, 0 0 #0000); }
[data-slot="alert"] { --tw-shadow: var(--shadow-alert, 0 0 #0000); }
[data-slot="media-frame"] { --tw-shadow: var(--shadow-media, 0 0 #0000); }
[data-slot="card"].p-6 { padding: var(--pad-card, calc(var(--spacing) * 6)); }
[data-slot="alert"].px-2 { padding-inline: var(--pad-alert, calc(var(--spacing) * 2)); }
[data-slot="alert"].min-h-8 { min-height: var(--min-alert, calc(var(--spacing) * 8)); }
[data-slot="button"].px-4.h-10 { padding-inline: var(--pad-button, calc(var(--spacing) * 4)); height: var(--h-button, calc(var(--spacing) * 10)); }
[data-slot="badge"].px-3.h-6 { padding-inline: var(--pad-badge, calc(var(--spacing) * 3)); height: var(--h-badge, calc(var(--spacing) * 6)); }
[data-density-card="compact"] { --pad-card: 16px; }
[data-density-card="comfortable"] { --pad-card: 32px; }
[data-density-alert="compact"] { --pad-alert: 8px; --min-alert: 24px; }
[data-density-alert="comfortable"] { --pad-alert: 16px; --min-alert: 40px; }
[data-density-button="compact"] { --pad-button: 12px; --h-button: 32px; }
[data-density-button="comfortable"] { --pad-button: 20px; --h-button: 48px; }
[data-density-badge="compact"] { --pad-badge: 8px; --h-badge: 20px; }
[data-density-badge="comfortable"] { --pad-badge: 16px; --h-badge: 28px; }
/* Owned by codegen-x (UI8Kit 3: ui8kit/codegen ships no theme). Forked from vendor/codegen 2309848; adds --destructive-foreground (AA). */
@import "tailwindcss";
/* shadcn/ui neutral theme (Tailwind v4, written as hsl() for old browsers; same colours as the oklch values published at https://ui.shadcn.com/docs/theming
("Default Theme CSS", base color neutral). Dark mode: the .dark class or data-theme="dark" on an ancestor. */
@custom-variant dark (&:is(.dark *, [data-theme="dark"] *));
/* The one corner token. Plain `rounded` reads the bare --radius theme key, so every corner of the kit follows it
(shadcn keeps --radius in :root; here it sits in @theme so that `rounded` resolves to it; same value, 0.625rem). */
@theme {
--radius: 0.625rem;
}
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--color-card: var(--card);
--color-card-foreground: var(--card-foreground);
--color-popover: var(--popover);
--color-popover-foreground: var(--popover-foreground);
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
--color-secondary: var(--secondary);
--color-secondary-foreground: var(--secondary-foreground);
--color-muted: var(--muted);
--color-muted-foreground: var(--muted-foreground);
--color-accent: var(--accent);
--color-accent-foreground: var(--accent-foreground);
--color-destructive: var(--destructive);
--color-destructive-foreground: var(--destructive-foreground);
--color-destructive-hover: var(--destructive-hover);
--color-border: var(--border);
--color-input: var(--input);
--color-ring: var(--ring);
--color-chart-1: var(--chart-1);
--color-chart-2: var(--chart-2);
--color-chart-3: var(--chart-3);
--color-chart-4: var(--chart-4);
--color-chart-5: var(--chart-5);
--color-sidebar: var(--sidebar);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-ring: var(--sidebar-ring);
--radius-sm: calc(var(--radius) * 0.6);
--radius-md: calc(var(--radius) * 0.8);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) * 1.4);
--radius-2xl: calc(var(--radius) * 1.8);
--radius-3xl: calc(var(--radius) * 2.2);
--radius-4xl: calc(var(--radius) * 2.6);
}
:root {
--background: hsl(0 0% 100%);
--foreground: hsl(0 0% 4%);
--card: hsl(0 0% 100%);
--card-foreground: hsl(0 0% 4%);
--popover: hsl(0 0% 100%);
--popover-foreground: hsl(0 0% 4%);
--primary: hsl(0 0% 9%);
--primary-foreground: hsl(0 0% 98%);
--secondary: hsl(0 0% 96%);
--secondary-foreground: hsl(0 0% 9%);
--muted: hsl(0 0% 96%);
--muted-foreground: hsl(0 0% 43.5%);
--accent: hsl(0 0% 96%);
--accent-foreground: hsl(0 0% 9%);
--destructive: hsl(0.6 88.4% 48%); /* L 52.5% -> 48%: white text reaches AA (4.70) */
--destructive-foreground: hsl(0 0% 100%);
--destructive-hover: hsl(0.6 88.4% 42%); /* 6 points away from the foreground: hover keeps AA */
--border: hsl(0 0% 90%);
--input: hsl(0 0% 90%);
--ring: hsl(0 0% 63%);
--chart-1: hsl(18 100% 48%);
--chart-2: hsl(174.7 100% 29.5%);
--chart-3: hsl(196 72% 23%);
--chart-4: hsl(43.6 100% 50%);
--chart-5: hsl(36.3 100% 49.7%);
--sidebar: hsl(0 0% 98%);
--sidebar-foreground: hsl(0 0% 4%);
--sidebar-primary: hsl(0 0% 9%);
--sidebar-primary-foreground: hsl(0 0% 98%);
--sidebar-accent: hsl(0 0% 96%);
--sidebar-accent-foreground: hsl(0 0% 9%);
--sidebar-border: hsl(0 0% 90%);
--sidebar-ring: hsl(0 0% 63%);
}
:is(.dark, [data-theme="dark"]) {
--background: hsl(0 0% 4%);
--foreground: hsl(0 0% 98%);
--card: hsl(0 0% 9%);
--card-foreground: hsl(0 0% 98%);
--popover: hsl(0 0% 9%);
--popover-foreground: hsl(0 0% 98%);
--primary: hsl(0 0% 90%);
--primary-foreground: hsl(0 0% 9%);
--secondary: hsl(0 0% 15%);
--secondary-foreground: hsl(0 0% 98%);
--muted: hsl(0 0% 15%);
--muted-foreground: hsl(0 0% 63%);
--accent: hsl(0 0% 15%);
--accent-foreground: hsl(0 0% 98%);
--destructive: hsl(356.1 62.4% 52%);
--destructive-foreground: hsl(0 0% 100%);
--destructive-hover: hsl(356.1 62.4% 46%);
--border: hsl(0 0% 100% / 10%);
--input: hsl(0 0% 100% / 15%);
--ring: hsl(0 0% 45%);
--chart-1: hsl(225.3 84.1% 49%);
--chart-2: hsl(160 100% 37%);
--chart-3: hsl(36.3 100% 49.7%);
--chart-4: hsl(273.3 100% 63.8%);
--chart-5: hsl(345 100% 56%);
--sidebar: hsl(0 0% 9%);
--sidebar-foreground: hsl(0 0% 98%);
--sidebar-primary: hsl(225.3 84.1% 49%);
--sidebar-primary-foreground: hsl(0 0% 98%);
--sidebar-accent: hsl(0 0% 15%);
--sidebar-accent-foreground: hsl(0 0% 98%);
--sidebar-border: hsl(0 0% 100% / 10%);
--sidebar-ring: hsl(0 0% 45%);
}
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
}
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
// Framework-free: the function takes the node and returns the cleanup. Svelte: call it from an action or an effect; React: call it in an effect.
export type DismissReason = "escape" | "outside";
const stack: object[] = []; // topmost dismissable layer handles Escape first (menu inside off-canvas sidebar, …)
/** Escape and pointer-down outside the node call onDismiss. Returns the cleanup. */
export function dismissable(node: HTMLElement, opts: () => { onDismiss: (reason: DismissReason) => void; ignore?: () => (Element | null | undefined)[]; outside?: boolean }): () => void {
{
const layer = {};
stack.push(layer);
const { onDismiss, ignore = () => [], outside = true } = opts();
const onKey = (e: KeyboardEvent) => {
if (e.key !== "Escape" || e.defaultPrevented || stack[stack.length - 1] !== layer) return;
e.preventDefault(); e.stopPropagation();
onDismiss("escape");
};
const onDown = (e: PointerEvent) => {
if (!outside || stack[stack.length - 1] !== layer) return;
const t = e.target as Node | null;
if (!t || node.contains(t) || ignore().some((el) => el?.contains(t))) return;
onDismiss("outside");
};
document.addEventListener("keydown", onKey, true);
document.addEventListener("pointerdown", onDown, true);
return () => {
document.removeEventListener("keydown", onKey, true);
document.removeEventListener("pointerdown", onDown, true);
const i = stack.indexOf(layer); if (i >= 0) stack.splice(i, 1);
};
}
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
// Framework-free: the function takes the node and returns the cleanup. Svelte: call it from an action or an effect; React: call it in an effect.
import { focusables } from "./focusable";
/** Tab/Shift+Tab cycle inside `node`; on cleanup focus returns to the element focused before. */
export function trapFocus(node: HTMLElement): () => void {
const previous = document.activeElement as HTMLElement | null;
if (!node.contains(previous)) queueMicrotask(() => focusables(node)[0]?.focus());
const onKey = (e: KeyboardEvent) => {
if (e.key !== "Tab") return;
const items = focusables(node);
if (!items.length) { e.preventDefault(); return; }
const first = items[0], last = items[items.length - 1], cur = document.activeElement;
if (e.shiftKey && (cur === first || !node.contains(cur))) { e.preventDefault(); last.focus(); }
else if (!e.shiftKey && (cur === last || !node.contains(cur))) { e.preventDefault(); first.focus(); }
};
node.addEventListener("keydown", onKey);
return () => { node.removeEventListener("keydown", onKey); /* after the page is no longer inert */ requestAnimationFrame(() => { if (previous?.isConnected) previous.focus(); }); };
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
// Small headless helpers shared by the interactive primitives (menus, dialogs, tabs, off-canvas sidebar).
export const FOCUSABLE = 'a[href],button:not([disabled]),input:not([disabled]):not([type="hidden"]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])';
/** visible, tabbable descendants of `root` in DOM order */
export function focusables(root: HTMLElement): HTMLElement[] {
return [...root.querySelectorAll<HTMLElement>(FOCUSABLE)].filter((el) => !el.closest("[inert]") && el.getClientRects().length > 0 && getComputedStyle(el).visibility !== "hidden");
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
export { FOCUSABLE, focusables } from "./focusable";
export { moveFocus, typeahead, type RovingOptions } from "./roving";
export { lockScroll } from "./scroll-lock";
export { dismissable, type DismissReason } from "./dismiss";
export { trapFocus } from "./focus-trap";
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
// Arrow-key navigation over a list of focusable items (menus, listboxes, tab lists, trees).
export type RovingOptions = { orientation?: "vertical" | "horizontal" | "both"; loop?: boolean; activate?: boolean };
/** Handles ArrowUp/Down/Left/Right, Home, End. Returns true when the key was consumed. */
export function moveFocus(e: KeyboardEvent, items: HTMLElement[], { orientation = "vertical", loop = true, activate = false }: RovingOptions = {}): boolean {
if (!items.length || e.altKey || e.ctrlKey || e.metaKey) return false;
const prev = orientation !== "horizontal" ? ["ArrowUp"] : [];
const next = orientation !== "horizontal" ? ["ArrowDown"] : [];
if (orientation !== "vertical") { prev.push("ArrowLeft"); next.push("ArrowRight"); }
const cur = items.indexOf(document.activeElement as HTMLElement);
let idx = -1;
if (next.includes(e.key)) idx = cur < 0 ? 0 : cur + 1;
else if (prev.includes(e.key)) idx = cur < 0 ? items.length - 1 : cur - 1;
else if (e.key === "Home") idx = 0;
else if (e.key === "End") idx = items.length - 1;
else return false;
if (idx >= items.length) idx = loop ? 0 : items.length - 1;
if (idx < 0) idx = loop ? items.length - 1 : 0;
e.preventDefault();
const el = items[idx];
el.focus();
if (activate) el.click();
return true;
}
/** type-ahead: focus the next item whose text starts with the typed characters (reset after 600 ms) */
export function typeahead() {
let buf = "", t: ReturnType<typeof setTimeout> | undefined;
return (e: KeyboardEvent, items: HTMLElement[]): boolean => {
if (e.key.length !== 1 || e.ctrlKey || e.metaKey || e.altKey || e.key === " ") return false;
buf += e.key.toLowerCase();
clearTimeout(t); t = setTimeout(() => (buf = ""), 600);
const start = Math.max(0, items.indexOf(document.activeElement as HTMLElement) + (buf.length === 1 ? 1 : 0));
const ordered = [...items.slice(start), ...items.slice(0, start)];
const hit = ordered.find((el) => (el.textContent ?? "").trim().toLowerCase().startsWith(buf));
if (hit) { hit.focus(); e.preventDefault(); return true; }
return false;
};
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
// Reference-counted page scroll lock (off-canvas sidebar, modal dialog). Compensates the scrollbar width on desktop.
let count = 0;
let saved = { overflow: "", paddingRight: "" };
export function lockScroll(): () => void {
const root = document.documentElement;
if (count++ === 0) {
const sw = window.innerWidth - root.clientWidth;
saved = { overflow: root.style.overflow, paddingRight: root.style.paddingRight };
root.style.overflow = "hidden";
if (sw > 0) root.style.paddingRight = `${sw}px`;
root.setAttribute("data-scroll-locked", "");
}
let released = false;
return () => {
if (released) return; released = true;
if (--count === 0) {
root.style.overflow = saved.overflow; root.style.paddingRight = saved.paddingRight;
root.removeAttribute("data-scroll-locked");
}
};
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
/** Merge class values. Caller-supplied classes win over recipe classes. */
export function cn(...inputs: ClassValue[]): string {
return twMerge(clsx(inputs));
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
export function isDevEnv(): boolean {
try {
const env = (import.meta as unknown as { env?: { DEV?: boolean } }).env;
if (env && typeof env.DEV === "boolean") return env.DEV;
} catch {
// import.meta may be unavailable in some contexts
}
return false;
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
/**
* Tiny attribute-logic helpers used by generated components. One
* implementation per runtime family keeps every default-resolution decision
* table byte-identical across React, Svelte, and Vue (mirrors `expr.go`).
*/
export const trimStr = (v: string | number | null | undefined): string =>
v === null || v === undefined ? "" : String(v).trim();
export const isSetStr = (v: string | null | undefined): boolean => trimStr(v) !== "";
export const isSetNum = (v: number | null | undefined): boolean => (v ?? 0) > 0;
/**
* `trim(v) === "" ? fallback : trim(v)` — DefaultInputType-style defaults.
* Generic so enum-typed props keep their literal union through the default.
*/
export const defaultIfEmpty = <T extends string>(v: T | null | undefined, fallback: T): T => {
const t = trimStr(v) as T;
return t === "" ? fallback : t;
};
/** Whitelist: returns `trim(v)` when in `allowed`, otherwise `fallback`. */
export const oneOfOr = <T extends string>(
v: string | null | undefined,
fallback: T,
...allowed: T[]
): T => {
const t = trimStr(v) as T;
return allowed.includes(t) ? t : fallback;
};
export const oneOfOrLower = <T extends string>(
v: string | null | undefined,
fallback: T,
...allowed: T[]
): T => {
const t = trimStr(v).toLowerCase() as T;
return allowed.includes(t) ? t : fallback;
};
/** Decision table: `mapping[trim(v)] ?? fallback`. */
export const mapOr = <T extends string>(
v: string | null | undefined,
mapping: Record<string, T>,
fallback: T
): T => mapping[trimStr(v)] ?? fallback;
export const mapOrLower = <T extends string>(
v: string | null | undefined,
mapping: Record<string, T>,
fallback: T
): T => mapping[trimStr(v).toLowerCase()] ?? fallback;
/** Integer decision table: `mapping[v] ?? fallback`. */
export const intMapOr = <T extends string>(
v: number | null | undefined,
mapping: Record<number, T>,
fallback: T
): T => mapping[v ?? 0] ?? fallback;
/** Null-safe string equality (both sides normalized to ""). */
export const eqStr = (a: string | null | undefined, b: string | null | undefined): boolean =>
(a ?? "") === (b ?? "");
/** ARIA state stringification: always "true"/"false", never omitted. */
export const boolStr = (v: boolean | null | undefined): "true" | "false" =>
v ? "true" : "false";
/** Concatenation of trimmed parts (icon `Prefix + Name`). */
export const concatTrim = (...parts: (string | null | undefined)[]): string =>
parts.map(trimStr).join("");
/** Omit-if-empty attribute value: `""` → `undefined` so the attr is dropped. */
export const orUndef = (v: string | null | undefined): string | undefined => {
const t = trimStr(v);
return t === "" ? undefined : String(v);
};
export type HeadingLevel = 1 | 2 | 3 | 4 | 5 | 6;
/** h1–h6 from a heading level; 0/undefined/out-of-range default to h2. */
export const titleTag = (order: HeadingLevel | number | null | undefined): string => {
switch (order) {
case 1:
return "h1";
case 3:
return "h3";
case 4:
return "h4";
case 5:
return "h5";
case 6:
return "h6";
default:
return "h2";
}
};
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
// Text and number formatting shared by every generated organism and screen. Pure functions, no runtime dependency.
/** fills {0}, {1}... of a content template */
export function tpl(template: string | undefined, ...values: Array<string | number | undefined>): string {
return (template ?? "").replace(/\{(\d+)\}/g, (_m, i: string) => String(values[Number(i)] ?? ""));
}
const nf = new Intl.NumberFormat("en-US");
export function fmtNumber(n: number): string {
return nf.format(n);
}
/** digits of the minor unit (ISO 4217): cents for most currencies, none for JPY and KRW */
export function minorDigits(currency: string): number {
return currency === "JPY" || currency === "KRW" ? 0 : 2;
}
const moneyCache = new Map<string, Intl.NumberFormat>();
/** money in integer minor units (Codex v0.4: 1250 = 12.50 USD) -> "$12.50"; whole amounts drop the fraction: 1499_00 -> "$1,499" */
export function fmtMoney(minor: number, currency: string): string {
const d = minorDigits(currency);
const cents = Math.round(minor);
const frac = d > 0 && cents % 10 ** d !== 0 ? d : 0;
const key = `${currency}:${frac}`;
let f = moneyCache.get(key);
if (!f) {
f = new Intl.NumberFormat("en-US", { style: "currency", currency, minimumFractionDigits: frac, maximumFractionDigits: frac });
moneyCache.set(key, f);
}
return f.format(cents / 10 ** d);
}
/** a content word by key (the status of a record -> its label); the key itself when the dictionary has no entry */
export function at(dict: Record<string, string> | undefined, key: string): string {
return dict?.[key] ?? key;
}
/** the page numbers a pager shows: the first, the last and the neighbours of the current page; null is a gap */
export function pageWindow(page: number, pages: number): (number | null)[] {
const keep = new Set([1, pages, page - 1, page, page + 1].filter((n) => n >= 1 && n <= pages));
const out: (number | null)[] = [];
let prev = 0;
for (const n of [...keep].sort((a, b) => a - b)) {
if (n - prev > 1) out.push(null);
out.push(n);
prev = n;
}
return out;
}
/** a responsive column variant of Grid capped by the number of items, so no column stays empty: ("1-4", 3) -> "1-3", ("2-6", 4) -> "2-4" */
export function fitCols(cols: string, n: number): string {
const m = /^(\d+)-(\d+)$/.exec(cols);
if (!m) return cols;
const lo = Number(m[1]), hi = Number(m[2]);
if (n >= hi) return cols;
const top = Math.max(lo, n);
const known = ["1-2", "1-3", "1-4", "2-3", "2-4", "2-6", "3-6"];
for (let h = top; h > lo; h--) if (known.includes(`${lo}-${h}`)) return `${lo}-${h}`;
return String(Math.min(lo, Math.max(n, 1)));
}
/** a label of segments joined by ", " without a segment equal (case-insensitive) to the one before it:
* "Footer, Footer, Centered" -> "Footer, Centered" */
export function uniqLabel(label: string | undefined): string {
const parts = (label ?? "").split(", ");
return parts.filter((s, i) => i === 0 || s.toLowerCase() !== (parts[i - 1] ?? "").toLowerCase()).join(", ");
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
/**
* Trusted markup. A prop of type `TrustedHtml` carries markup from a trusted source (the `|html` pipe of readPath: the body of a
* Codex entry, or the host), and an `html` view node prints it without escaping. Every other value is text, and is escaped.
* The marker is React's own shape, `{ __html }`; a value without it (a plain string) is escaped by `htmlOf`, so markup is
* printed raw only when it was marked trusted. The same rules on every runtime: og_html (PHP, Python) and Html (Go).
*/
export type TrustedHtml = { readonly __html: string };
/** marks markup as trusted: only for a source the app trusts (the Codex body), never for user input */
export const trustHtml = (html: string): TrustedHtml => ({ __html: html });
export const isTrustedHtml = (v: unknown): v is TrustedHtml =>
v !== null && typeof v === "object" && typeof (v as { __html?: unknown }).__html === "string";
const ENTITIES: Record<string, string> = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" };
/** text as markup: & < > " ' as entities */
export const escapeHtml = (s: string): string => s.replace(/[&<>"']/g, (c) => ENTITIES[c]!);
/** the markup an `html` node prints: the trusted markup as it is, any other value escaped as text (nothing for null and booleans, like a text node) */
export const htmlOf = (v: TrustedHtml | string | number | boolean | null | undefined): string =>
isTrustedHtml(v) ? v.__html : v === null || v === undefined || typeof v === "boolean" ? "" : escapeHtml(String(v));
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
export { cn } from "./cn";
export { isDevEnv } from "./env";
export { variants, type VariantFn, type VariantKey, type VariantSelection, type VariantTable } from "./variants";
export { TagGroup, isAllowedTag, resolveTag } from "./tags";
export * from "./expr";
export { tpl, fmtNumber, fmtMoney, minorDigits, at, pageWindow, fitCols, uniqLabel } from "./format";
export * from "./a11y";
export { type TrustedHtml, trustHtml, isTrustedHtml, escapeHtml, htmlOf } from "./html";
export { decodeEntities, isSafeUrl, urlOf, srcsetOf, cssValue, srcsetUrls, styleOf, isSafeAttrName, attrValueOf, URL_ATTRS, IMAGE_ATTRS, URL_SCHEMES, NAMED_ENTITIES } from "./safe";
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
/**
* Output safety of the organism runtime (the same rules in PHP Runtime.php, Python runtime.py and Go dyn.go; the shared vectors
* are in packages/compose-gen/runtimes/core/test/safety-vectors.json). An allowlist, not a denylist:
* - a URL (href, src, action, formaction, poster, cite, background, data, xlink:href) is kept only when, read as a browser
* reads it (entities decoded, ASCII whitespace and control characters removed), it is a path or a reference with no scheme
* (`/path`, `#a`, `?q`, `page.html`) or its scheme is http, https, mailto or tel; an image URL may also be
* data:image/(png|jpeg|gif|webp|avif|svg+xml). A protocol-relative URL (`//host`, `/\host`, `\\host`) is refused.
* Anything else is "" (javascript:, vbscript:, data:text/html, livescript:, also behind case, entities or whitespace).
* - a srcset is checked candidate by candidate (each URL an image URL); one bad candidate refuses the whole value.
* - a style is refused ("") when a url(...) inside it is not an image URL, or it holds expression(, a script scheme,
* -moz-binding, behavior: or a CSS escape (a backslash).
* - an attribute name is printed only when it matches ^[a-zA-Z_:][-a-zA-Z0-9_:.]*$ and does not start with "on".
*/
/** the named character references the check decodes (those that spell URL syntax, whitespace or the markup characters) */
export const NAMED_ENTITIES: Readonly<Record<string, string>> = {
Tab: "\t", NewLine: "\n", colon: ":", sol: "/", bsol: "\\", lpar: "(", rpar: ")", amp: "&", lt: "<", gt: ">", quot: '"', apos: "'",
nbsp: "\u00a0", period: ".", comma: ",", excl: "!", num: "#", quest: "?", equals: "=", plus: "+", semi: ";", percnt: "%", lowbar: "_",
ast: "*", commat: "@", dollar: "$", Hat: "^", grave: "`", lsqb: "[", rsqb: "]", lcub: "{", rcub: "}", verbar: "|", vert: "|",
};
export const URL_SCHEMES: readonly string[] = ["http", "https", "mailto", "tel"];
const DATA_IMAGE = /^data:image\/(png|jpeg|gif|webp|avif|svg\+xml)[;,]/;
const ENTITY = /&(?:#[xX]([0-9a-fA-F]{1,8});?|#([0-9]{1,10});?|([a-zA-Z][a-zA-Z0-9]{0,31});)/g;
const fromCode = (n: number): string => (n > 0 && n <= 0x10ffff && !(n >= 0xd800 && n <= 0xdfff) ? String.fromCodePoint(n) : "\ufffd");
/** character references decoded as a browser would (numeric with or without `;`, the named ones of NAMED_ENTITIES), up to 3 rounds */
export function decodeEntities(s: string): string {
let out = s;
for (let i = 0; i < 3 && out.includes("&"); i++) {
out = out.replace(ENTITY, (m, hex: string | undefined, dec: string | undefined, name: string | undefined) =>
hex !== undefined ? fromCode(parseInt(hex, 16)) : dec !== undefined ? fromCode(parseInt(dec, 10)) : NAMED_ENTITIES[name!] ?? m);
}
return out;
}
/** the value as a URL parser sees it: entities decoded, ASCII whitespace and control characters (C0, space, DEL) removed */
const compact = (s: string): string => decodeEntities(s).replace(/[\u0000-\u0020\u007f]+/g, "");
/** true when the URL is allowed (see the file comment); `image`: data:image/* too */
export function isSafeUrl(v: string, image = false): boolean {
const k = compact(v);
if (/^[/\\]{2}/.test(k)) return false;
const m = /^([a-zA-Z][a-zA-Z0-9+.-]*):/.exec(k);
// no scheme: a path, unless a ":" comes before any "/" (as written or decoded), which templ.URL refuses too (one rule everywhere)
if (!m) return !/^[^/]*:/.test(k) && !/^[^/]*:/.test(v);
const scheme = m[1]!.toLowerCase();
if (scheme === "data") return image && DATA_IMAGE.test(k.toLowerCase());
return URL_SCHEMES.includes(scheme);
}
const str = (v: unknown): string => (typeof v === "string" ? v : typeof v === "number" ? String(v) : "");
/** a URL attribute value: the value when it is allowed, else "" (another non-string is ""); undefined and null stay as they are (the attribute is left out) */
export function urlOf<T>(v: T, image = false): string | Extract<T, null | undefined> {
if (v === undefined || v === null) return v as Extract<T, null | undefined>;
const s = str(v);
return isSafeUrl(s, image) ? s : "";
}
/** the URLs of a srcset, candidate by candidate (the URL of a candidate runs to the first whitespace; trailing commas end it) */
export function srcsetUrls(v: string): string[] {
const s = decodeEntities(v), out: string[] = [];
let i = 0;
const ws = (c: string | undefined) => c !== undefined && /[\t\n\f\r ]/.test(c);
while (i < s.length) {
while (i < s.length && (ws(s[i]) || s[i] === ",")) i++;
if (i >= s.length) break;
let j = i;
while (j < s.length && !ws(s[j])) j++;
let url = s.slice(i, j);
const cut = /,+$/.exec(url);
if (cut) { url = url.slice(0, -cut[0].length); out.push(url); i = j; continue; }
out.push(url);
let depth = 0;
while (j < s.length && (depth > 0 || s[j] !== ",")) { if (s[j] === "(") depth++; else if (s[j] === ")") depth = Math.max(0, depth - 1); j++; }
i = j + 1;
}
return out;
}
/** a srcset value: the value when every candidate URL is an allowed image URL, else "" */
export function srcsetOf<T>(v: T): string | Extract<T, null | undefined> {
if (v === undefined || v === null) return v as Extract<T, null | undefined>;
const s = str(v);
return srcsetUrls(s).every((u) => isSafeUrl(u, true)) ? s : "";
}
/** a value of an inline style declaration (the css op): kept when it is plain (numbers, words, %, #, +, -, ., commas and spaces), else ""; no url(), no ; */
export const cssValue = (v: unknown): string => { const s = str(v); return /^[-+.%#a-zA-Z0-9 ,]*$/.test(s) ? s : ""; };
/** a style value: "" when it could load or run something (see the file comment), else the value */
export function styleOf(v: unknown): string {
const s = str(v), d = decodeEntities(s), k = compact(s).toLowerCase();
if (d.includes("\\") || /expression\(|javascript:|vbscript:|-moz-binding|behavior:/.test(k)) return "";
for (const m of d.matchAll(/url\(([^)]*)\)?/gi)) if (!isSafeUrl(m[1]!.replace(/^[ \t\n\r\f\v]+|[ \t\n\r\f\v]+$/g, "").replace(/^(["'])([^]*)\1$/, "$2"), true)) return "";
return s;
}
/** an attribute name that may be printed: a valid XML-ish name, not an event handler (on*) */
export const isSafeAttrName = (name: string): boolean => /^[a-zA-Z_:][-a-zA-Z0-9_:.]*$/.test(name) && !/^on/i.test(name);
/** the attributes whose value is a URL (a srcset and a style have their own checks) */
export const URL_ATTRS: readonly string[] = ["href", "src", "action", "formaction", "poster", "cite", "background", "data", "xlink:href"];
/** the URL attributes whose URL is an image (data:image/* allowed) */
export const IMAGE_ATTRS: readonly string[] = ["src", "poster", "background"];
/** the value of attribute `name` as it may be printed: URL, srcset and style checked, any other value as it is */
export function attrValueOf(name: string, v: unknown): unknown {
const n = name.toLowerCase();
if (n === "srcset" || n === "imagesrcset") return srcsetOf(v);
if (n === "style") return styleOf(v);
if (URL_ATTRS.includes(n)) return urlOf(v, IMAGE_ATTRS.includes(n));
return v;
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
// Code generated by tagsgen. DO NOT EDIT.
import { isDevEnv } from "./env";
export const TagGroup = {
Layout: "Layout",
BoxAllowed: "BoxAllowed",
BlockText: "BlockText",
Inline: "Inline",
Heading: "Heading",
List: "List",
ListItem: "ListItem",
Form: "Form",
FormControl: "FormControl",
FormLabel: "FormLabel",
Table: "Table",
TableSection: "TableSection",
TableRow: "TableRow",
TableCell: "TableCell",
TableColumn: "TableColumn",
Media: "Media",
Disclosure: "Disclosure",
Container: "Container",
Stack: "Stack",
Group: "Group",
Text: "Text",
} as const;
export type TagGroup = (typeof TagGroup)[keyof typeof TagGroup];
const layoutTags = new Set(["div", "section", "article", "aside", "header", "footer", "main", "nav", "figure", "search", "hgroup"]);
const boxAllowedTags = new Set(["div"]);
const blockTextTags = new Set(["p", "blockquote", "figcaption", "address", "pre"]);
const inlineTags = new Set(["span", "em", "strong", "small", "abbr", "cite", "code", "kbd", "mark", "time", "data", "var", "samp", "sub", "sup", "b", "i", "u", "s", "q", "dfn", "bdo", "bdi", "ins", "del"]);
const headingTags = new Set(["h1", "h2", "h3", "h4", "h5", "h6"]);
const listTags = new Set(["ul", "ol", "dl", "menu"]);
const listItemTags = new Set(["li", "dt", "dd"]);
const formTags = new Set(["form", "fieldset"]);
const formControlTags = new Set(["input", "textarea", "select", "button", "option", "optgroup", "datalist", "output", "meter", "progress"]);
const formLabelTags = new Set(["label", "legend"]);
const tableTags = new Set(["table"]);
const tableSectionTags = new Set(["thead", "tbody", "tfoot"]);
const tableRowTags = new Set(["tr"]);
const tableCellTags = new Set(["th", "td"]);
const tableColumnTags = new Set(["colgroup", "col"]);
const mediaTags = new Set(["img", "picture", "source"]);
const disclosureTags = new Set(["details", "summary"]);
const containerTags = new Set(["div", "main", "section"]);
const stackTags = new Set(["div", "ul", "ol"]);
const groupTags = new Set(["div", "fieldset", "dl"]);
function oneOf(tag: string, options: Set<string>): boolean {
return options.has(tag);
}
const warnedTagFallbacks = new Set<string>();
function warnTagFallback(tag: string, fallback: string, group: TagGroup): void {
if (!isDevEnv()) return;
const key = `${group}:${tag}:${fallback}`;
if (warnedTagFallbacks.has(key)) return;
warnedTagFallbacks.add(key);
console.warn(`[resolveTag] disallowed tag "${tag}" for group "${group}", fallback "${fallback}" used.`);
}
export function isAllowedTag(tag: string, group: TagGroup): boolean {
const t = tag.trim().toLowerCase();
switch (group) {
case TagGroup.Layout:
return oneOf(t, layoutTags);
case TagGroup.BoxAllowed:
return oneOf(t, boxAllowedTags);
case TagGroup.BlockText:
return oneOf(t, blockTextTags);
case TagGroup.Inline:
return oneOf(t, inlineTags);
case TagGroup.Heading:
return oneOf(t, headingTags);
case TagGroup.List:
return oneOf(t, listTags);
case TagGroup.ListItem:
return oneOf(t, listItemTags);
case TagGroup.Form:
return oneOf(t, formTags);
case TagGroup.FormControl:
return oneOf(t, formControlTags);
case TagGroup.FormLabel:
return oneOf(t, formLabelTags);
case TagGroup.Table:
return oneOf(t, tableTags);
case TagGroup.TableSection:
return oneOf(t, tableSectionTags);
case TagGroup.TableRow:
return oneOf(t, tableRowTags);
case TagGroup.TableCell:
return oneOf(t, tableCellTags);
case TagGroup.TableColumn:
return oneOf(t, tableColumnTags);
case TagGroup.Media:
return oneOf(t, mediaTags);
case TagGroup.Disclosure:
return oneOf(t, disclosureTags);
case TagGroup.Container:
return oneOf(t, containerTags);
case TagGroup.Stack:
return oneOf(t, stackTags);
case TagGroup.Group:
return oneOf(t, groupTags);
case TagGroup.Text:
return blockTextTags.has(t) || inlineTags.has(t);
default:
return false;
}
}
export function resolveTag(tag: string | undefined, fallback: string, group: TagGroup): string {
const t = tag?.trim().toLowerCase() ?? "";
if (!t) return fallback;
if (isAllowedTag(t, group)) return t;
warnTagFallback(t, fallback, group);
return fallback;
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
import { cn } from "./cn";
import { isDevEnv } from "./env";
/**
* A shadcn/cva-style variant table, without the dependency (same idea as `cva` from class-variance-authority).
*
* const badgeVariants = variants({
* base: "inline-flex items-center",
* variants: { size: { sm: "h-5 px-2", lg: "h-8 px-3" } },
* defaultVariants: { size: "sm" },
* compoundVariants: [{ size: "lg", shape: "rounded", class: "rounded-lg" }],
* });
* badgeVariants({ size: "lg" }); // "inline-flex items-center h-8 px-3"
*
* Classes come in this order: base, each variant in table order, then the matching compound variants.
* tailwind-merge (`cn`) resolves conflicts, the later class wins. A compound value may list alternatives: "32|lg".
*/
export type VariantTable = {
base?: string;
variants: Record<string, Record<string, string>>;
defaultVariants: Record<string, string>;
compoundVariants?: Array<{ class: string } & Record<string, string>>;
};
/** the props a table accepts: one optional value per variant */
export type VariantSelection<T extends VariantTable> = {
[K in keyof T["variants"]]?: (keyof T["variants"][K] & string) | undefined;
};
/** a variant function: call it with the selected values, read `.table` for the types */
export type VariantFn<T extends VariantTable> = ((selection?: VariantSelection<T>) => string) & { table: T };
/** the values of one variant of a table: `VariantKey<typeof badgeVariants, "size">` is `"sm" | "lg"` */
export type VariantKey<F extends { table: VariantTable }, K extends keyof F["table"]["variants"]> = Exclude<
keyof F["table"]["variants"][K] & string,
""
>;
export function variants<T extends VariantTable>(table: T): VariantFn<T> {
const pick = (selection: Record<string, string | undefined>, key: string): string =>
(selection[key] ?? "").trim() || (table.defaultVariants[key] ?? "").trim();
const fn = (selection: VariantSelection<T> = {}): string => {
const sel = selection as Record<string, string | undefined>;
const parts: string[] = [table.base ?? ""];
for (const [key, choices] of Object.entries(table.variants)) {
const choice = pick(sel, key);
const cls = choices[choice];
// a typo in development is an error; in production the unknown value is dropped
if (cls === undefined && isDevEnv()) throw new Error(`[variants] unknown value "${choice}" for "${key}"`);
parts.push(cls ?? "");
}
for (const compound of table.compoundVariants ?? []) {
const matches = Object.entries(compound).every(([k, want]) => k === "class" || want.split("|").includes(pick(sel, k)));
if (matches) parts.push(compound.class);
}
return cn(...parts.map((p) => p.trim()).filter(Boolean));
};
return Object.assign(fn, { table });
}
Point the CLI at this runtime once, then add the item:
npx ui8kit init --yes --framework solid --dir src --registry-url https://registry.buildy.tw/solid --strict-cdnnpx ui8kit add utilsimport { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
/**
* Merge class values with Tailwind conflict resolution.
* Mirrors shadcn's `cn` = clsx + tailwind-merge.
* Caller-supplied classes win over recipe classes.
*/
export function cn(...inputs: ClassValue[]): string {
return twMerge(clsx(inputs));
}
/**
* Dev-only warnings switch, bundle-agnostic (no ESM-only meta property, so the utils work in ESM, CJS, IIFE / classic
* script bundles, e.g. the web components). On when `globalThis.__UI8KIT_DEV__ === true`, or when a bundler
* defines `process.env.NODE_ENV` as "development".
*/
export function isDevEnv(): boolean {
const g = globalThis as { __UI8KIT_DEV__?: unknown; process?: { env?: { NODE_ENV?: string } } };
if (typeof g.__UI8KIT_DEV__ === "boolean") return g.__UI8KIT_DEV__;
try {
return g.process?.env?.NODE_ENV === "development";
} catch {
return false;
}
}
/**
* Tiny attribute-logic helpers used by generated components. One
* implementation per runtime family keeps every default-resolution decision
* table byte-identical across React, Svelte, and Vue (mirrors `expr.go`).
*/
export const trimStr = (v: string | number | null | undefined): string =>
v === null || v === undefined ? "" : String(v).trim();
export const isSetStr = (v: string | null | undefined): boolean => trimStr(v) !== "";
export const isSetNum = (v: number | null | undefined): boolean => (v ?? 0) > 0;
/**
* `trim(v) === "" ? fallback : trim(v)` — DefaultInputType-style defaults.
* Generic so enum-typed props keep their literal union through the default.
*/
export const defaultIfEmpty = <T extends string>(v: T | null | undefined, fallback: T): T => {
const t = trimStr(v) as T;
return t === "" ? fallback : t;
};
/** Whitelist: returns `trim(v)` when in `allowed`, otherwise `fallback`. */
export const oneOfOr = <T extends string>(
v: string | null | undefined,
fallback: T,
...allowed: T[]
): T => {
const t = trimStr(v) as T;
return allowed.includes(t) ? t : fallback;
};
export const oneOfOrLower = <T extends string>(
v: string | null | undefined,
fallback: T,
...allowed: T[]
): T => {
const t = trimStr(v).toLowerCase() as T;
return allowed.includes(t) ? t : fallback;
};
/** Decision table: `mapping[trim(v)] ?? fallback`. */
export const mapOr = <T extends string>(
v: string | null | undefined,
mapping: Record<string, T>,
fallback: T
): T => mapping[trimStr(v)] ?? fallback;
export const mapOrLower = <T extends string>(
v: string | null | undefined,
mapping: Record<string, T>,
fallback: T
): T => mapping[trimStr(v).toLowerCase()] ?? fallback;
/** Integer decision table: `mapping[v] ?? fallback`. */
export const intMapOr = <T extends string>(
v: number | null | undefined,
mapping: Record<number, T>,
fallback: T
): T => mapping[v ?? 0] ?? fallback;
/** Null-safe string equality (both sides normalized to ""). */
export const eqStr = (a: string | null | undefined, b: string | null | undefined): boolean =>
(a ?? "") === (b ?? "");
/** ARIA state stringification: always "true"/"false", never omitted. */
export const boolStr = (v: boolean | null | undefined): "true" | "false" =>
v ? "true" : "false";
/** Tri-state ARIA state: "true"/"false" when set, "" when unset (attribute omitted). */
export const optBoolStr = (v: boolean | null | undefined): "true" | "false" | "" =>
v === true ? "true" : v === false ? "false" : "";
/** Concatenation of trimmed parts (icon `Prefix + Name`). */
export const concatTrim = (...parts: (string | null | undefined)[]): string =>
parts.map(trimStr).join("");
/** Omit-if-empty attribute value: `""` → `undefined` so the attr is dropped. */
export const orUndef = <T extends string>(v: T | null | undefined): Exclude<T, ""> | undefined => {
const t = trimStr(v);
return t === "" ? undefined : (String(v) as Exclude<T, "">);
};
/**
* Sync a form control's live `value` property (never an attribute, so SSR
* markup is untouched). `undefined` leaves the current selection alone, so
* the children's initial `selected` state stays in charge. Usable directly as
* a Svelte action (`use:syncValue={value}`) and from Solid refs / WC renderers.
*/
export function syncValue(node: { value: string }, value?: string | null): { update(v?: string | null): void } {
const apply = (v?: string | null): void => {
if (v !== undefined && v !== null && node.value !== v) node.value = v;
};
apply(value);
return { update: apply };
}
const DATA_IMAGE = /^data:image\/(png|jpeg|gif|webp|avif|svg\+xml)[;,]/;
/**
* URL attribute value: "" for javascript:, vbscript: and data: (ASCII whitespace/control chars removed,
* case-insensitive). `dataImage` (only `<img src>`) allows data:image/(png|jpeg|gif|webp|avif|svg+xml).
*/
export const safeUrl = (v: string | null | undefined, dataImage = false): string => {
const k = String(v ?? "").replace(/[\u0000-\u0020]/g, "").toLowerCase();
return /^(javascript|vbscript|data):/.test(k) && !(dataImage && DATA_IMAGE.test(k)) ? "" : (v ?? "");
};
/** Per-element rest rule: `img` allows data:image in `src`; `blank` lists optional attrs (lowercase) omitted when blank. */
export type RestRule = { readonly img?: boolean; readonly blank?: readonly string[] };
const URL_KEYS = new Set(["href", "src", "action", "formaction", "poster", "cite", "background", "xlink:href", "xlinkhref"]);
/** True when a rest entry must be omitted: an unsafe URL or a blank optional attribute (`value` is never in `blank`). */
export function dropRestKey(k: string, v: unknown, rule?: RestRule): boolean {
if (typeof v !== "string") return false;
const key = k.toLowerCase();
if (rule?.blank?.includes(key) && v.trim() === "") return true;
return v !== "" && URL_KEYS.has(key) && safeUrl(v, rule?.img === true && key === "src") === "";
}
/** Rest props / caller attrs without unsafe URLs and blank optional attributes; identity when clean. */
export function safeRest<T extends object>(rest: T, rule?: RestRule): T {
const bad = Object.keys(rest).filter((k) => dropRestKey(k, (rest as Record<string, unknown>)[k], rule));
if (bad.length === 0) return rest;
const out = { ...rest } as Record<string, unknown>;
for (const k of bad) delete out[k];
return out as T;
}
export { cn } from "./cn";
export { isDevEnv } from "./env";
export type { RecipeKey, VariantRecipe } from "./recipe-types";
export {
compose,
composeRecipe,
recipeToVariants,
type RecipeSelection,
type Variants,
} from "./variants";
export { BOX_TAGS, TEXT_TAGS, TagGroup, isAllowedTag, resolveTag, type BoxTag, type TextTag } from "./tags";
export * from "./expr";
/**
* Type helpers to derive literal unions from `*.variants.json` recipes.
* Usage:
* import buttonRecipe from "./button.variants.json";
* type ButtonVariant = RecipeKey<typeof buttonRecipe, "variant">;
* // ^? "default" | "destructive" | "ghost" | ...
*/
export type VariantRecipe = {
id: string;
base: string;
keys: string[];
defaults: Record<string, string>;
byKey: Record<string, Record<string, string>>;
};
/**
* Extract the literal union of variant keys for a given recipe dimension.
* Empty string (used as a fallback in some JSON recipes) is excluded so
* consumers get only meaningful values in autocomplete.
*/
export type RecipeKey<
R extends VariantRecipe,
K extends keyof R["byKey"] & string,
> = Exclude<keyof R["byKey"][K] & string, "">;
// Mirrors src/domain/tags.ts (the SSOT). DO NOT EDIT in generated output.
import { isDevEnv } from "./env";
export const BOX_TAGS = [
"div", "section", "article", "aside", "header", "footer", "main", "nav", "figure", "search",
"ul", "ol", "li", "dl", "dt", "dd", "fieldset",
"table", "thead", "tbody", "tfoot", "tr", "th", "td", "caption", "colgroup", "col",
] as const;
export const TEXT_TAGS = [
"p", "span", "h1", "h2", "h3", "h4", "h5", "h6", "blockquote", "figcaption", "pre", "code",
"small", "strong", "em", "time", "legend", "del", "ins",
] as const;
export type BoxTag = (typeof BOX_TAGS)[number];
export type TextTag = (typeof TEXT_TAGS)[number];
export const TagGroup = { Box: "Box", Text: "Text" } as const;
export type TagGroup = (typeof TagGroup)[keyof typeof TagGroup];
const groups: Record<TagGroup, ReadonlySet<string>> = {
Box: new Set<string>(BOX_TAGS),
Text: new Set<string>(TEXT_TAGS),
};
const warned = new Set<string>();
export function isAllowedTag(tag: string, group: TagGroup): boolean {
return groups[group]?.has(tag.trim().toLowerCase()) ?? false;
}
export function resolveTag(tag: string | undefined, fallback: string, group: TagGroup): string {
const t = tag?.trim().toLowerCase() ?? "";
if (!t) return fallback;
if (isAllowedTag(t, group)) return t;
if (isDevEnv()) {
const key = `${group}:${t}`;
if (!warned.has(key)) {
warned.add(key);
console.warn(`[resolveTag] "${t}" is not an allowed ${group} tag; using "${fallback}".`);
}
}
return fallback;
}
import { cn } from "./cn";
import { isDevEnv } from "./env";
import type { RecipeKey, VariantRecipe } from "./recipe-types";
export type { RecipeKey, VariantRecipe };
export type Variants = {
id?: string;
base: string;
keys: string[];
defaults: Record<string, string>;
byKey: Record<string, Record<string, string>>;
};
export function recipeToVariants<R extends VariantRecipe>(recipe: R): Variants {
return {
id: recipe.id,
base: recipe.base,
keys: recipe.keys,
defaults: recipe.defaults ?? {},
byKey: recipe.byKey,
};
}
/**
* Merge base, variant selections, and optional tail classes.
* Mirrors the canonical `composeRecipe`.
*/
export function compose(
v: Variants,
selection: Record<string, string>,
...extra: (string | undefined | null | false)[]
): string {
const parts: string[] = [];
if (v.base.trim() !== "") {
parts.push(v.base.trim());
}
for (const key of v.keys) {
const choices = v.byKey[key];
if (!choices) continue;
const selected = (selection[key] ?? "").trim();
const fallback = (v.defaults[key] ?? "").trim();
const choice = selected || fallback;
if (!choice) {
if (isDevEnv() && Object.keys(choices).length > 0) {
throw new Error(
`[compose] missing default for key "${key}" (recipe id: ${String(v.id ?? "?")})`
);
}
continue;
}
const cls = choices[choice];
if (cls !== undefined) {
if (cls.trim() !== "") parts.push(cls.trim());
} else if (isDevEnv()) {
throw new Error(
`[compose] unknown variant "${choice}" for key "${key}" (recipe id: ${String(v.id ?? "?")})`
);
}
// Unknown choices are silently dropped in production to avoid leaking
// typos into the DOM as literal class names.
}
return cn(...parts, ...extra);
}
/** Selection type for `composeRecipe`. */
export type RecipeSelection<R extends VariantRecipe> = {
[K in keyof R["byKey"] & string]?: RecipeKey<R, K> | undefined;
};
/** Compose classes from a typed recipe. */
export function composeRecipe<R extends VariantRecipe>(
recipe: R,
selection: RecipeSelection<R>,
...extra: (string | undefined | null | false)[]
): string {
return compose(recipeToVariants(recipe), selection as Record<string, string>, ...extra);
}
/* Code generated by compose-gen. DO NOT EDIT. */
/* Entry of the styles: theme tokens and the kit CSS. @source makes Tailwind v4 scan the compositions and the installed primitives. */
@import "./theme.css";
@import "./kit.css";
@source "../";
@source "../kit";
/* Kit-wide CSS: base layer, input glyph utilities, focus ring. Colors and the one corner token (--radius) come from theme.css (shadcn neutral);
shadows: only floating layers have one (shadow-md, shadow-lg), set in their specs; nothing here draws one. */
@layer base {
html, body { margin: 0; background: var(--color-background); color: var(--color-foreground); }
body { -webkit-font-smoothing: antialiased; text-rendering: geometricPrecision; overflow-x: hidden; }
button { cursor: pointer; }
html { -webkit-text-size-adjust: 100%; color-scheme: light; }
}
/* the box of a checkbox: its corner is the theme radius scaled to the 16-20px box (0.4 x 10px = 4px), so it never reads as a radio */
@utility checkbox-glyph {
display: inline-grid; place-content: center; border-radius: calc(var(--radius) * 0.4);
&::before { content: ""; width: 8px; height: 6px; opacity: 0; background: currentColor;
clip-path: polygon(0 55%, 14% 40%, 38% 64%, 86% 0, 100% 15%, 38% 95%); }
&:checked { color: var(--color-primary-foreground); }
&:checked::before { opacity: 1; }
}
/* a number field without the browser spin buttons (NumberField draws its own minus and plus) */
@utility number-bare {
appearance: textfield; -moz-appearance: textfield;
&::-webkit-inner-spin-button, &::-webkit-outer-spin-button { -webkit-appearance: none; margin: 0; }
}
@utility radio-glyph {
display: inline-grid; place-content: center;
&::before { content: ""; width: var(--dot); height: var(--dot); border-radius: 9999px; background: var(--color-primary-foreground); opacity: 0; }
&:checked::before { opacity: 1; }
}
@utility switch-knob {
&::before { content: ""; position: absolute; top: 50%; left: var(--pad); width: var(--knob); height: var(--knob); border-radius: 9999px;
background: var(--color-background); translate: 0 -50%; transition: left .15s; }
&:checked::before { left: calc(100% - var(--pad) - var(--knob)); }
}
@utility progress-bar {
&::-webkit-progress-bar { background: transparent; }
&::-webkit-progress-value { background: var(--bar); border-radius: var(--radius); }
&::-moz-progress-bar { background: var(--bar); border-radius: var(--radius); }
&::-webkit-meter-bar { background: transparent; border: 0; }
&::-webkit-meter-optimum-value { background: var(--bar); }
}
/* Focus ring sits above utility shadows. Keyboard only. The 4px halo is gray unless the element sets a ring colour
(shadcn style, e.g. focus-visible:ring-destructive/20 on the destructive variants); --tw-ring-color does not inherit. */
:where(a, button, input, select, textarea, summary, [role="tab"], [role="menuitem"], [role="menuitemradio"], [role="option"], [role="treeitem"], [role="radio"], [role="switch"], [tabindex]):focus-visible {
outline: none;
box-shadow: var(--tw-inset-shadow, 0 0 #0000), var(--tw-inset-ring-shadow, 0 0 #0000), 0 0 0 4px var(--tw-ring-color, rgb(128 128 128 / 0.15)), var(--tw-shadow, 0 0 #0000);
}
[data-slot="prompt-input"]:focus-within, [data-slot="smartbox"]:focus-within { box-shadow: 0 0 0 4px rgb(128 128 128 / 0.15), inset 0 0 0 1px var(--color-border); }
[data-slot="prompt-input"] textarea:focus-visible, [data-slot="smartbox"] input:focus-visible { box-shadow: none; }
[data-slot="file-tree-item"]:focus-visible, [data-slot="editor-tab"]:focus-visible, [data-slot="icon-tab"]:focus-visible, [data-slot="dropdown-item"]:focus-visible {
box-shadow: inset 0 0 0 2px rgb(128 128 128 / 0.15), inset 0 0 0 1px var(--color-muted-foreground);
}
:where([data-screen]) :focus:not(:focus-visible) { outline: none; }
::selection { background: color-mix(in srgb, var(--color-primary) 15%, transparent); }
/* The disclosure indicator: the Lucide chevron-down drawn in the text colour; the Summary brick turns it over when its
details open (group-open:rotate-180), so an accordion needs no script. */
[data-slot="summary-indicator"] {
display: inline-block;
background-color: currentColor;
mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E") center / contain no-repeat;
}
/* Per-element tokens (UI8KIT-2.0 §11): badge, button, card, alert, media. An unset token falls back to the value of the utility class the
rule matches (p-6, px-4 h-10, ...), stated explicitly: a revert-layer fallback inside var() is not supported by every
browser (there the property became unset: buttons and badges lost their padding and height).
A skin or a scope (a wrapper, the magazine specimen) sets only the ones it wants.
Radius: --radius-badge|button|card|alert|media (unset: var(--radius); the badge unset: the pill). Only elements that carry plain `rounded` follow it.
Shadow: --shadow-card|alert|media (unset: the spec's own: none). A full box-shadow layer, e.g. var(--shadow-sm) or 0 0 #0000.
Density: data-density-badge|button|card|alert = compact | default | comfortable, on the element or any ancestor, sets --pad-*:
card 16/24/32 (padding of a default card), alert inline 8/8/16 with --min-alert 24/32/40,
button inline 12/16/20 and height 32/40/48 (default size), badge inline 8/12/16 and height 20/24/28 (default size).
4px steps only inside controls (button, badge); card and alert stay on the 8px step. */
[data-slot="button"].rounded { border-radius: var(--radius-button, var(--radius)); }
[data-slot="card"].rounded { border-radius: var(--radius-card, var(--radius)); }
[data-slot="alert"].rounded { border-radius: var(--radius-alert, var(--radius)); }
[data-slot="media-frame"].rounded { border-radius: var(--radius-media, var(--radius)); }
[data-slot="badge"].rounded-full { border-radius: var(--radius-badge, calc(infinity * 1px)); }
[data-slot="card"] { --tw-shadow: var(--shadow-card, 0 0 #0000); }
[data-slot="alert"] { --tw-shadow: var(--shadow-alert, 0 0 #0000); }
[data-slot="media-frame"] { --tw-shadow: var(--shadow-media, 0 0 #0000); }
[data-slot="card"].p-6 { padding: var(--pad-card, calc(var(--spacing) * 6)); }
[data-slot="alert"].px-2 { padding-inline: var(--pad-alert, calc(var(--spacing) * 2)); }
[data-slot="alert"].min-h-8 { min-height: var(--min-alert, calc(var(--spacing) * 8)); }
[data-slot="button"].px-4.h-10 { padding-inline: var(--pad-button, calc(var(--spacing) * 4)); height: var(--h-button, calc(var(--spacing) * 10)); }
[data-slot="badge"].px-3.h-6 { padding-inline: var(--pad-badge, calc(var(--spacing) * 3)); height: var(--h-badge, calc(var(--spacing) * 6)); }
[data-density-card="compact"] { --pad-card: 16px; }
[data-density-card="comfortable"] { --pad-card: 32px; }
[data-density-alert="compact"] { --pad-alert: 8px; --min-alert: 24px; }
[data-density-alert="comfortable"] { --pad-alert: 16px; --min-alert: 40px; }
[data-density-button="compact"] { --pad-button: 12px; --h-button: 32px; }
[data-density-button="comfortable"] { --pad-button: 20px; --h-button: 48px; }
[data-density-badge="compact"] { --pad-badge: 8px; --h-badge: 20px; }
[data-density-badge="comfortable"] { --pad-badge: 16px; --h-badge: 28px; }
/* Owned by codegen-x (UI8Kit 3: ui8kit/codegen ships no theme). Forked from vendor/codegen 2309848; adds --destructive-foreground (AA). */
@import "tailwindcss";
/* shadcn/ui neutral theme (Tailwind v4, written as hsl() for old browsers; same colours as the oklch values published at https://ui.shadcn.com/docs/theming
("Default Theme CSS", base color neutral). Dark mode: the .dark class or data-theme="dark" on an ancestor. */
@custom-variant dark (&:is(.dark *, [data-theme="dark"] *));
/* The one corner token. Plain `rounded` reads the bare --radius theme key, so every corner of the kit follows it
(shadcn keeps --radius in :root; here it sits in @theme so that `rounded` resolves to it; same value, 0.625rem). */
@theme {
--radius: 0.625rem;
}
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--color-card: var(--card);
--color-card-foreground: var(--card-foreground);
--color-popover: var(--popover);
--color-popover-foreground: var(--popover-foreground);
--color-primary: var(--primary);
--color-primary-foreground: var(--primary-foreground);
--color-secondary: var(--secondary);
--color-secondary-foreground: var(--secondary-foreground);
--color-muted: var(--muted);
--color-muted-foreground: var(--muted-foreground);
--color-accent: var(--accent);
--color-accent-foreground: var(--accent-foreground);
--color-destructive: var(--destructive);
--color-destructive-foreground: var(--destructive-foreground);
--color-destructive-hover: var(--destructive-hover);
--color-border: var(--border);
--color-input: var(--input);
--color-ring: var(--ring);
--color-chart-1: var(--chart-1);
--color-chart-2: var(--chart-2);
--color-chart-3: var(--chart-3);
--color-chart-4: var(--chart-4);
--color-chart-5: var(--chart-5);
--color-sidebar: var(--sidebar);
--color-sidebar-foreground: var(--sidebar-foreground);
--color-sidebar-primary: var(--sidebar-primary);
--color-sidebar-primary-foreground: var(--sidebar-primary-foreground);
--color-sidebar-accent: var(--sidebar-accent);
--color-sidebar-accent-foreground: var(--sidebar-accent-foreground);
--color-sidebar-border: var(--sidebar-border);
--color-sidebar-ring: var(--sidebar-ring);
--radius-sm: calc(var(--radius) * 0.6);
--radius-md: calc(var(--radius) * 0.8);
--radius-lg: var(--radius);
--radius-xl: calc(var(--radius) * 1.4);
--radius-2xl: calc(var(--radius) * 1.8);
--radius-3xl: calc(var(--radius) * 2.2);
--radius-4xl: calc(var(--radius) * 2.6);
}
:root {
--background: hsl(0 0% 100%);
--foreground: hsl(0 0% 4%);
--card: hsl(0 0% 100%);
--card-foreground: hsl(0 0% 4%);
--popover: hsl(0 0% 100%);
--popover-foreground: hsl(0 0% 4%);
--primary: hsl(0 0% 9%);
--primary-foreground: hsl(0 0% 98%);
--secondary: hsl(0 0% 96%);
--secondary-foreground: hsl(0 0% 9%);
--muted: hsl(0 0% 96%);
--muted-foreground: hsl(0 0% 43.5%);
--accent: hsl(0 0% 96%);
--accent-foreground: hsl(0 0% 9%);
--destructive: hsl(0.6 88.4% 48%); /* L 52.5% -> 48%: white text reaches AA (4.70) */
--destructive-foreground: hsl(0 0% 100%);
--destructive-hover: hsl(0.6 88.4% 42%); /* 6 points away from the foreground: hover keeps AA */
--border: hsl(0 0% 90%);
--input: hsl(0 0% 90%);
--ring: hsl(0 0% 63%);
--chart-1: hsl(18 100% 48%);
--chart-2: hsl(174.7 100% 29.5%);
--chart-3: hsl(196 72% 23%);
--chart-4: hsl(43.6 100% 50%);
--chart-5: hsl(36.3 100% 49.7%);
--sidebar: hsl(0 0% 98%);
--sidebar-foreground: hsl(0 0% 4%);
--sidebar-primary: hsl(0 0% 9%);
--sidebar-primary-foreground: hsl(0 0% 98%);
--sidebar-accent: hsl(0 0% 96%);
--sidebar-accent-foreground: hsl(0 0% 9%);
--sidebar-border: hsl(0 0% 90%);
--sidebar-ring: hsl(0 0% 63%);
}
:is(.dark, [data-theme="dark"]) {
--background: hsl(0 0% 4%);
--foreground: hsl(0 0% 98%);
--card: hsl(0 0% 9%);
--card-foreground: hsl(0 0% 98%);
--popover: hsl(0 0% 9%);
--popover-foreground: hsl(0 0% 98%);
--primary: hsl(0 0% 90%);
--primary-foreground: hsl(0 0% 9%);
--secondary: hsl(0 0% 15%);
--secondary-foreground: hsl(0 0% 98%);
--muted: hsl(0 0% 15%);
--muted-foreground: hsl(0 0% 63%);
--accent: hsl(0 0% 15%);
--accent-foreground: hsl(0 0% 98%);
--destructive: hsl(356.1 62.4% 52%);
--destructive-foreground: hsl(0 0% 100%);
--destructive-hover: hsl(356.1 62.4% 46%);
--border: hsl(0 0% 100% / 10%);
--input: hsl(0 0% 100% / 15%);
--ring: hsl(0 0% 45%);
--chart-1: hsl(225.3 84.1% 49%);
--chart-2: hsl(160 100% 37%);
--chart-3: hsl(36.3 100% 49.7%);
--chart-4: hsl(273.3 100% 63.8%);
--chart-5: hsl(345 100% 56%);
--sidebar: hsl(0 0% 9%);
--sidebar-foreground: hsl(0 0% 98%);
--sidebar-primary: hsl(225.3 84.1% 49%);
--sidebar-primary-foreground: hsl(0 0% 98%);
--sidebar-accent: hsl(0 0% 15%);
--sidebar-accent-foreground: hsl(0 0% 98%);
--sidebar-border: hsl(0 0% 100% / 10%);
--sidebar-ring: hsl(0 0% 45%);
}
@layer base {
* {
@apply border-border outline-ring/50;
}
body {
@apply bg-background text-foreground;
}
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
// Framework-free: the function takes the node and returns the cleanup. Svelte: call it from an action or an effect; React: call it in an effect.
export type DismissReason = "escape" | "outside";
const stack: object[] = []; // topmost dismissable layer handles Escape first (menu inside off-canvas sidebar, …)
/** Escape and pointer-down outside the node call onDismiss. Returns the cleanup. */
export function dismissable(node: HTMLElement, opts: () => { onDismiss: (reason: DismissReason) => void; ignore?: () => (Element | null | undefined)[]; outside?: boolean }): () => void {
{
const layer = {};
stack.push(layer);
const { onDismiss, ignore = () => [], outside = true } = opts();
const onKey = (e: KeyboardEvent) => {
if (e.key !== "Escape" || e.defaultPrevented || stack[stack.length - 1] !== layer) return;
e.preventDefault(); e.stopPropagation();
onDismiss("escape");
};
const onDown = (e: PointerEvent) => {
if (!outside || stack[stack.length - 1] !== layer) return;
const t = e.target as Node | null;
if (!t || node.contains(t) || ignore().some((el) => el?.contains(t))) return;
onDismiss("outside");
};
document.addEventListener("keydown", onKey, true);
document.addEventListener("pointerdown", onDown, true);
return () => {
document.removeEventListener("keydown", onKey, true);
document.removeEventListener("pointerdown", onDown, true);
const i = stack.indexOf(layer); if (i >= 0) stack.splice(i, 1);
};
}
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
// Framework-free: the function takes the node and returns the cleanup. Svelte: call it from an action or an effect; React: call it in an effect.
import { focusables } from "./focusable";
/** Tab/Shift+Tab cycle inside `node`; on cleanup focus returns to the element focused before. */
export function trapFocus(node: HTMLElement): () => void {
const previous = document.activeElement as HTMLElement | null;
if (!node.contains(previous)) queueMicrotask(() => focusables(node)[0]?.focus());
const onKey = (e: KeyboardEvent) => {
if (e.key !== "Tab") return;
const items = focusables(node);
if (!items.length) { e.preventDefault(); return; }
const first = items[0], last = items[items.length - 1], cur = document.activeElement;
if (e.shiftKey && (cur === first || !node.contains(cur))) { e.preventDefault(); last.focus(); }
else if (!e.shiftKey && (cur === last || !node.contains(cur))) { e.preventDefault(); first.focus(); }
};
node.addEventListener("keydown", onKey);
return () => { node.removeEventListener("keydown", onKey); /* after the page is no longer inert */ requestAnimationFrame(() => { if (previous?.isConnected) previous.focus(); }); };
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
// Small headless helpers shared by the interactive primitives (menus, dialogs, tabs, off-canvas sidebar).
export const FOCUSABLE = 'a[href],button:not([disabled]),input:not([disabled]):not([type="hidden"]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])';
/** visible, tabbable descendants of `root` in DOM order */
export function focusables(root: HTMLElement): HTMLElement[] {
return [...root.querySelectorAll<HTMLElement>(FOCUSABLE)].filter((el) => !el.closest("[inert]") && el.getClientRects().length > 0 && getComputedStyle(el).visibility !== "hidden");
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
export { FOCUSABLE, focusables } from "./focusable";
export { moveFocus, typeahead, type RovingOptions } from "./roving";
export { lockScroll } from "./scroll-lock";
export { dismissable, type DismissReason } from "./dismiss";
export { trapFocus } from "./focus-trap";
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
// Arrow-key navigation over a list of focusable items (menus, listboxes, tab lists, trees).
export type RovingOptions = { orientation?: "vertical" | "horizontal" | "both"; loop?: boolean; activate?: boolean };
/** Handles ArrowUp/Down/Left/Right, Home, End. Returns true when the key was consumed. */
export function moveFocus(e: KeyboardEvent, items: HTMLElement[], { orientation = "vertical", loop = true, activate = false }: RovingOptions = {}): boolean {
if (!items.length || e.altKey || e.ctrlKey || e.metaKey) return false;
const prev = orientation !== "horizontal" ? ["ArrowUp"] : [];
const next = orientation !== "horizontal" ? ["ArrowDown"] : [];
if (orientation !== "vertical") { prev.push("ArrowLeft"); next.push("ArrowRight"); }
const cur = items.indexOf(document.activeElement as HTMLElement);
let idx = -1;
if (next.includes(e.key)) idx = cur < 0 ? 0 : cur + 1;
else if (prev.includes(e.key)) idx = cur < 0 ? items.length - 1 : cur - 1;
else if (e.key === "Home") idx = 0;
else if (e.key === "End") idx = items.length - 1;
else return false;
if (idx >= items.length) idx = loop ? 0 : items.length - 1;
if (idx < 0) idx = loop ? items.length - 1 : 0;
e.preventDefault();
const el = items[idx];
el.focus();
if (activate) el.click();
return true;
}
/** type-ahead: focus the next item whose text starts with the typed characters (reset after 600 ms) */
export function typeahead() {
let buf = "", t: ReturnType<typeof setTimeout> | undefined;
return (e: KeyboardEvent, items: HTMLElement[]): boolean => {
if (e.key.length !== 1 || e.ctrlKey || e.metaKey || e.altKey || e.key === " ") return false;
buf += e.key.toLowerCase();
clearTimeout(t); t = setTimeout(() => (buf = ""), 600);
const start = Math.max(0, items.indexOf(document.activeElement as HTMLElement) + (buf.length === 1 ? 1 : 0));
const ordered = [...items.slice(start), ...items.slice(0, start)];
const hit = ordered.find((el) => (el.textContent ?? "").trim().toLowerCase().startsWith(buf));
if (hit) { hit.focus(); e.preventDefault(); return true; }
return false;
};
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
// Reference-counted page scroll lock (off-canvas sidebar, modal dialog). Compensates the scrollbar width on desktop.
let count = 0;
let saved = { overflow: "", paddingRight: "" };
export function lockScroll(): () => void {
const root = document.documentElement;
if (count++ === 0) {
const sw = window.innerWidth - root.clientWidth;
saved = { overflow: root.style.overflow, paddingRight: root.style.paddingRight };
root.style.overflow = "hidden";
if (sw > 0) root.style.paddingRight = `${sw}px`;
root.setAttribute("data-scroll-locked", "");
}
let released = false;
return () => {
if (released) return; released = true;
if (--count === 0) {
root.style.overflow = saved.overflow; root.style.paddingRight = saved.paddingRight;
root.removeAttribute("data-scroll-locked");
}
};
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
import { clsx, type ClassValue } from "clsx";
import { twMerge } from "tailwind-merge";
/** Merge class values. Caller-supplied classes win over recipe classes. */
export function cn(...inputs: ClassValue[]): string {
return twMerge(clsx(inputs));
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
export function isDevEnv(): boolean {
try {
const env = (import.meta as unknown as { env?: { DEV?: boolean } }).env;
if (env && typeof env.DEV === "boolean") return env.DEV;
} catch {
// import.meta may be unavailable in some contexts
}
return false;
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
/**
* Tiny attribute-logic helpers used by generated components. One
* implementation per runtime family keeps every default-resolution decision
* table byte-identical across React, Svelte, and Vue (mirrors `expr.go`).
*/
export const trimStr = (v: string | number | null | undefined): string =>
v === null || v === undefined ? "" : String(v).trim();
export const isSetStr = (v: string | null | undefined): boolean => trimStr(v) !== "";
export const isSetNum = (v: number | null | undefined): boolean => (v ?? 0) > 0;
/**
* `trim(v) === "" ? fallback : trim(v)` — DefaultInputType-style defaults.
* Generic so enum-typed props keep their literal union through the default.
*/
export const defaultIfEmpty = <T extends string>(v: T | null | undefined, fallback: T): T => {
const t = trimStr(v) as T;
return t === "" ? fallback : t;
};
/** Whitelist: returns `trim(v)` when in `allowed`, otherwise `fallback`. */
export const oneOfOr = <T extends string>(
v: string | null | undefined,
fallback: T,
...allowed: T[]
): T => {
const t = trimStr(v) as T;
return allowed.includes(t) ? t : fallback;
};
export const oneOfOrLower = <T extends string>(
v: string | null | undefined,
fallback: T,
...allowed: T[]
): T => {
const t = trimStr(v).toLowerCase() as T;
return allowed.includes(t) ? t : fallback;
};
/** Decision table: `mapping[trim(v)] ?? fallback`. */
export const mapOr = <T extends string>(
v: string | null | undefined,
mapping: Record<string, T>,
fallback: T
): T => mapping[trimStr(v)] ?? fallback;
export const mapOrLower = <T extends string>(
v: string | null | undefined,
mapping: Record<string, T>,
fallback: T
): T => mapping[trimStr(v).toLowerCase()] ?? fallback;
/** Integer decision table: `mapping[v] ?? fallback`. */
export const intMapOr = <T extends string>(
v: number | null | undefined,
mapping: Record<number, T>,
fallback: T
): T => mapping[v ?? 0] ?? fallback;
/** Null-safe string equality (both sides normalized to ""). */
export const eqStr = (a: string | null | undefined, b: string | null | undefined): boolean =>
(a ?? "") === (b ?? "");
/** ARIA state stringification: always "true"/"false", never omitted. */
export const boolStr = (v: boolean | null | undefined): "true" | "false" =>
v ? "true" : "false";
/** Concatenation of trimmed parts (icon `Prefix + Name`). */
export const concatTrim = (...parts: (string | null | undefined)[]): string =>
parts.map(trimStr).join("");
/** Omit-if-empty attribute value: `""` → `undefined` so the attr is dropped. */
export const orUndef = (v: string | null | undefined): string | undefined => {
const t = trimStr(v);
return t === "" ? undefined : String(v);
};
export type HeadingLevel = 1 | 2 | 3 | 4 | 5 | 6;
/** h1–h6 from a heading level; 0/undefined/out-of-range default to h2. */
export const titleTag = (order: HeadingLevel | number | null | undefined): string => {
switch (order) {
case 1:
return "h1";
case 3:
return "h3";
case 4:
return "h4";
case 5:
return "h5";
case 6:
return "h6";
default:
return "h2";
}
};
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
// Text and number formatting shared by every generated organism and screen. Pure functions, no runtime dependency.
/** fills {0}, {1}... of a content template */
export function tpl(template: string | undefined, ...values: Array<string | number | undefined>): string {
return (template ?? "").replace(/\{(\d+)\}/g, (_m, i: string) => String(values[Number(i)] ?? ""));
}
const nf = new Intl.NumberFormat("en-US");
export function fmtNumber(n: number): string {
return nf.format(n);
}
/** digits of the minor unit (ISO 4217): cents for most currencies, none for JPY and KRW */
export function minorDigits(currency: string): number {
return currency === "JPY" || currency === "KRW" ? 0 : 2;
}
const moneyCache = new Map<string, Intl.NumberFormat>();
/** money in integer minor units (Codex v0.4: 1250 = 12.50 USD) -> "$12.50"; whole amounts drop the fraction: 1499_00 -> "$1,499" */
export function fmtMoney(minor: number, currency: string): string {
const d = minorDigits(currency);
const cents = Math.round(minor);
const frac = d > 0 && cents % 10 ** d !== 0 ? d : 0;
const key = `${currency}:${frac}`;
let f = moneyCache.get(key);
if (!f) {
f = new Intl.NumberFormat("en-US", { style: "currency", currency, minimumFractionDigits: frac, maximumFractionDigits: frac });
moneyCache.set(key, f);
}
return f.format(cents / 10 ** d);
}
/** a content word by key (the status of a record -> its label); the key itself when the dictionary has no entry */
export function at(dict: Record<string, string> | undefined, key: string): string {
return dict?.[key] ?? key;
}
/** the page numbers a pager shows: the first, the last and the neighbours of the current page; null is a gap */
export function pageWindow(page: number, pages: number): (number | null)[] {
const keep = new Set([1, pages, page - 1, page, page + 1].filter((n) => n >= 1 && n <= pages));
const out: (number | null)[] = [];
let prev = 0;
for (const n of [...keep].sort((a, b) => a - b)) {
if (n - prev > 1) out.push(null);
out.push(n);
prev = n;
}
return out;
}
/** a responsive column variant of Grid capped by the number of items, so no column stays empty: ("1-4", 3) -> "1-3", ("2-6", 4) -> "2-4" */
export function fitCols(cols: string, n: number): string {
const m = /^(\d+)-(\d+)$/.exec(cols);
if (!m) return cols;
const lo = Number(m[1]), hi = Number(m[2]);
if (n >= hi) return cols;
const top = Math.max(lo, n);
const known = ["1-2", "1-3", "1-4", "2-3", "2-4", "2-6", "3-6"];
for (let h = top; h > lo; h--) if (known.includes(`${lo}-${h}`)) return `${lo}-${h}`;
return String(Math.min(lo, Math.max(n, 1)));
}
/** a label of segments joined by ", " without a segment equal (case-insensitive) to the one before it:
* "Footer, Footer, Centered" -> "Footer, Centered" */
export function uniqLabel(label: string | undefined): string {
const parts = (label ?? "").split(", ");
return parts.filter((s, i) => i === 0 || s.toLowerCase() !== (parts[i - 1] ?? "").toLowerCase()).join(", ");
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
/**
* Trusted markup. A prop of type `TrustedHtml` carries markup from a trusted source (the `|html` pipe of readPath: the body of a
* Codex entry, or the host), and an `html` view node prints it without escaping. Every other value is text, and is escaped.
* The marker is React's own shape, `{ __html }`; a value without it (a plain string) is escaped by `htmlOf`, so markup is
* printed raw only when it was marked trusted. The same rules on every runtime: og_html (PHP, Python) and Html (Go).
*/
export type TrustedHtml = { readonly __html: string };
/** marks markup as trusted: only for a source the app trusts (the Codex body), never for user input */
export const trustHtml = (html: string): TrustedHtml => ({ __html: html });
export const isTrustedHtml = (v: unknown): v is TrustedHtml =>
v !== null && typeof v === "object" && typeof (v as { __html?: unknown }).__html === "string";
const ENTITIES: Record<string, string> = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'" };
/** text as markup: & < > " ' as entities */
export const escapeHtml = (s: string): string => s.replace(/[&<>"']/g, (c) => ENTITIES[c]!);
/** the markup an `html` node prints: the trusted markup as it is, any other value escaped as text (nothing for null and booleans, like a text node) */
export const htmlOf = (v: TrustedHtml | string | number | boolean | null | undefined): string =>
isTrustedHtml(v) ? v.__html : v === null || v === undefined || typeof v === "boolean" ? "" : escapeHtml(String(v));
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
export { cn } from "./cn";
export { isDevEnv } from "./env";
export { variants, type VariantFn, type VariantKey, type VariantSelection, type VariantTable } from "./variants";
export { TagGroup, isAllowedTag, resolveTag } from "./tags";
export * from "./expr";
export { tpl, fmtNumber, fmtMoney, minorDigits, at, pageWindow, fitCols, uniqLabel } from "./format";
export * from "./a11y";
export { type TrustedHtml, trustHtml, isTrustedHtml, escapeHtml, htmlOf } from "./html";
export { decodeEntities, isSafeUrl, urlOf, srcsetOf, cssValue, srcsetUrls, styleOf, isSafeAttrName, attrValueOf, URL_ATTRS, IMAGE_ATTRS, URL_SCHEMES, NAMED_ENTITIES } from "./safe";
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
/**
* Output safety of the organism runtime (the same rules in PHP Runtime.php, Python runtime.py and Go dyn.go; the shared vectors
* are in packages/compose-gen/runtimes/core/test/safety-vectors.json). An allowlist, not a denylist:
* - a URL (href, src, action, formaction, poster, cite, background, data, xlink:href) is kept only when, read as a browser
* reads it (entities decoded, ASCII whitespace and control characters removed), it is a path or a reference with no scheme
* (`/path`, `#a`, `?q`, `page.html`) or its scheme is http, https, mailto or tel; an image URL may also be
* data:image/(png|jpeg|gif|webp|avif|svg+xml). A protocol-relative URL (`//host`, `/\host`, `\\host`) is refused.
* Anything else is "" (javascript:, vbscript:, data:text/html, livescript:, also behind case, entities or whitespace).
* - a srcset is checked candidate by candidate (each URL an image URL); one bad candidate refuses the whole value.
* - a style is refused ("") when a url(...) inside it is not an image URL, or it holds expression(, a script scheme,
* -moz-binding, behavior: or a CSS escape (a backslash).
* - an attribute name is printed only when it matches ^[a-zA-Z_:][-a-zA-Z0-9_:.]*$ and does not start with "on".
*/
/** the named character references the check decodes (those that spell URL syntax, whitespace or the markup characters) */
export const NAMED_ENTITIES: Readonly<Record<string, string>> = {
Tab: "\t", NewLine: "\n", colon: ":", sol: "/", bsol: "\\", lpar: "(", rpar: ")", amp: "&", lt: "<", gt: ">", quot: '"', apos: "'",
nbsp: "\u00a0", period: ".", comma: ",", excl: "!", num: "#", quest: "?", equals: "=", plus: "+", semi: ";", percnt: "%", lowbar: "_",
ast: "*", commat: "@", dollar: "$", Hat: "^", grave: "`", lsqb: "[", rsqb: "]", lcub: "{", rcub: "}", verbar: "|", vert: "|",
};
export const URL_SCHEMES: readonly string[] = ["http", "https", "mailto", "tel"];
const DATA_IMAGE = /^data:image\/(png|jpeg|gif|webp|avif|svg\+xml)[;,]/;
const ENTITY = /&(?:#[xX]([0-9a-fA-F]{1,8});?|#([0-9]{1,10});?|([a-zA-Z][a-zA-Z0-9]{0,31});)/g;
const fromCode = (n: number): string => (n > 0 && n <= 0x10ffff && !(n >= 0xd800 && n <= 0xdfff) ? String.fromCodePoint(n) : "\ufffd");
/** character references decoded as a browser would (numeric with or without `;`, the named ones of NAMED_ENTITIES), up to 3 rounds */
export function decodeEntities(s: string): string {
let out = s;
for (let i = 0; i < 3 && out.includes("&"); i++) {
out = out.replace(ENTITY, (m, hex: string | undefined, dec: string | undefined, name: string | undefined) =>
hex !== undefined ? fromCode(parseInt(hex, 16)) : dec !== undefined ? fromCode(parseInt(dec, 10)) : NAMED_ENTITIES[name!] ?? m);
}
return out;
}
/** the value as a URL parser sees it: entities decoded, ASCII whitespace and control characters (C0, space, DEL) removed */
const compact = (s: string): string => decodeEntities(s).replace(/[\u0000-\u0020\u007f]+/g, "");
/** true when the URL is allowed (see the file comment); `image`: data:image/* too */
export function isSafeUrl(v: string, image = false): boolean {
const k = compact(v);
if (/^[/\\]{2}/.test(k)) return false;
const m = /^([a-zA-Z][a-zA-Z0-9+.-]*):/.exec(k);
// no scheme: a path, unless a ":" comes before any "/" (as written or decoded), which templ.URL refuses too (one rule everywhere)
if (!m) return !/^[^/]*:/.test(k) && !/^[^/]*:/.test(v);
const scheme = m[1]!.toLowerCase();
if (scheme === "data") return image && DATA_IMAGE.test(k.toLowerCase());
return URL_SCHEMES.includes(scheme);
}
const str = (v: unknown): string => (typeof v === "string" ? v : typeof v === "number" ? String(v) : "");
/** a URL attribute value: the value when it is allowed, else "" (another non-string is ""); undefined and null stay as they are (the attribute is left out) */
export function urlOf<T>(v: T, image = false): string | Extract<T, null | undefined> {
if (v === undefined || v === null) return v as Extract<T, null | undefined>;
const s = str(v);
return isSafeUrl(s, image) ? s : "";
}
/** the URLs of a srcset, candidate by candidate (the URL of a candidate runs to the first whitespace; trailing commas end it) */
export function srcsetUrls(v: string): string[] {
const s = decodeEntities(v), out: string[] = [];
let i = 0;
const ws = (c: string | undefined) => c !== undefined && /[\t\n\f\r ]/.test(c);
while (i < s.length) {
while (i < s.length && (ws(s[i]) || s[i] === ",")) i++;
if (i >= s.length) break;
let j = i;
while (j < s.length && !ws(s[j])) j++;
let url = s.slice(i, j);
const cut = /,+$/.exec(url);
if (cut) { url = url.slice(0, -cut[0].length); out.push(url); i = j; continue; }
out.push(url);
let depth = 0;
while (j < s.length && (depth > 0 || s[j] !== ",")) { if (s[j] === "(") depth++; else if (s[j] === ")") depth = Math.max(0, depth - 1); j++; }
i = j + 1;
}
return out;
}
/** a srcset value: the value when every candidate URL is an allowed image URL, else "" */
export function srcsetOf<T>(v: T): string | Extract<T, null | undefined> {
if (v === undefined || v === null) return v as Extract<T, null | undefined>;
const s = str(v);
return srcsetUrls(s).every((u) => isSafeUrl(u, true)) ? s : "";
}
/** a value of an inline style declaration (the css op): kept when it is plain (numbers, words, %, #, +, -, ., commas and spaces), else ""; no url(), no ; */
export const cssValue = (v: unknown): string => { const s = str(v); return /^[-+.%#a-zA-Z0-9 ,]*$/.test(s) ? s : ""; };
/** a style value: "" when it could load or run something (see the file comment), else the value */
export function styleOf(v: unknown): string {
const s = str(v), d = decodeEntities(s), k = compact(s).toLowerCase();
if (d.includes("\\") || /expression\(|javascript:|vbscript:|-moz-binding|behavior:/.test(k)) return "";
for (const m of d.matchAll(/url\(([^)]*)\)?/gi)) if (!isSafeUrl(m[1]!.replace(/^[ \t\n\r\f\v]+|[ \t\n\r\f\v]+$/g, "").replace(/^(["'])([^]*)\1$/, "$2"), true)) return "";
return s;
}
/** an attribute name that may be printed: a valid XML-ish name, not an event handler (on*) */
export const isSafeAttrName = (name: string): boolean => /^[a-zA-Z_:][-a-zA-Z0-9_:.]*$/.test(name) && !/^on/i.test(name);
/** the attributes whose value is a URL (a srcset and a style have their own checks) */
export const URL_ATTRS: readonly string[] = ["href", "src", "action", "formaction", "poster", "cite", "background", "data", "xlink:href"];
/** the URL attributes whose URL is an image (data:image/* allowed) */
export const IMAGE_ATTRS: readonly string[] = ["src", "poster", "background"];
/** the value of attribute `name` as it may be printed: URL, srcset and style checked, any other value as it is */
export function attrValueOf(name: string, v: unknown): unknown {
const n = name.toLowerCase();
if (n === "srcset" || n === "imagesrcset") return srcsetOf(v);
if (n === "style") return styleOf(v);
if (URL_ATTRS.includes(n)) return urlOf(v, IMAGE_ATTRS.includes(n));
return v;
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
// Code generated by tagsgen. DO NOT EDIT.
import { isDevEnv } from "./env";
export const TagGroup = {
Layout: "Layout",
BoxAllowed: "BoxAllowed",
BlockText: "BlockText",
Inline: "Inline",
Heading: "Heading",
List: "List",
ListItem: "ListItem",
Form: "Form",
FormControl: "FormControl",
FormLabel: "FormLabel",
Table: "Table",
TableSection: "TableSection",
TableRow: "TableRow",
TableCell: "TableCell",
TableColumn: "TableColumn",
Media: "Media",
Disclosure: "Disclosure",
Container: "Container",
Stack: "Stack",
Group: "Group",
Text: "Text",
} as const;
export type TagGroup = (typeof TagGroup)[keyof typeof TagGroup];
const layoutTags = new Set(["div", "section", "article", "aside", "header", "footer", "main", "nav", "figure", "search", "hgroup"]);
const boxAllowedTags = new Set(["div"]);
const blockTextTags = new Set(["p", "blockquote", "figcaption", "address", "pre"]);
const inlineTags = new Set(["span", "em", "strong", "small", "abbr", "cite", "code", "kbd", "mark", "time", "data", "var", "samp", "sub", "sup", "b", "i", "u", "s", "q", "dfn", "bdo", "bdi", "ins", "del"]);
const headingTags = new Set(["h1", "h2", "h3", "h4", "h5", "h6"]);
const listTags = new Set(["ul", "ol", "dl", "menu"]);
const listItemTags = new Set(["li", "dt", "dd"]);
const formTags = new Set(["form", "fieldset"]);
const formControlTags = new Set(["input", "textarea", "select", "button", "option", "optgroup", "datalist", "output", "meter", "progress"]);
const formLabelTags = new Set(["label", "legend"]);
const tableTags = new Set(["table"]);
const tableSectionTags = new Set(["thead", "tbody", "tfoot"]);
const tableRowTags = new Set(["tr"]);
const tableCellTags = new Set(["th", "td"]);
const tableColumnTags = new Set(["colgroup", "col"]);
const mediaTags = new Set(["img", "picture", "source"]);
const disclosureTags = new Set(["details", "summary"]);
const containerTags = new Set(["div", "main", "section"]);
const stackTags = new Set(["div", "ul", "ol"]);
const groupTags = new Set(["div", "fieldset", "dl"]);
function oneOf(tag: string, options: Set<string>): boolean {
return options.has(tag);
}
const warnedTagFallbacks = new Set<string>();
function warnTagFallback(tag: string, fallback: string, group: TagGroup): void {
if (!isDevEnv()) return;
const key = `${group}:${tag}:${fallback}`;
if (warnedTagFallbacks.has(key)) return;
warnedTagFallbacks.add(key);
console.warn(`[resolveTag] disallowed tag "${tag}" for group "${group}", fallback "${fallback}" used.`);
}
export function isAllowedTag(tag: string, group: TagGroup): boolean {
const t = tag.trim().toLowerCase();
switch (group) {
case TagGroup.Layout:
return oneOf(t, layoutTags);
case TagGroup.BoxAllowed:
return oneOf(t, boxAllowedTags);
case TagGroup.BlockText:
return oneOf(t, blockTextTags);
case TagGroup.Inline:
return oneOf(t, inlineTags);
case TagGroup.Heading:
return oneOf(t, headingTags);
case TagGroup.List:
return oneOf(t, listTags);
case TagGroup.ListItem:
return oneOf(t, listItemTags);
case TagGroup.Form:
return oneOf(t, formTags);
case TagGroup.FormControl:
return oneOf(t, formControlTags);
case TagGroup.FormLabel:
return oneOf(t, formLabelTags);
case TagGroup.Table:
return oneOf(t, tableTags);
case TagGroup.TableSection:
return oneOf(t, tableSectionTags);
case TagGroup.TableRow:
return oneOf(t, tableRowTags);
case TagGroup.TableCell:
return oneOf(t, tableCellTags);
case TagGroup.TableColumn:
return oneOf(t, tableColumnTags);
case TagGroup.Media:
return oneOf(t, mediaTags);
case TagGroup.Disclosure:
return oneOf(t, disclosureTags);
case TagGroup.Container:
return oneOf(t, containerTags);
case TagGroup.Stack:
return oneOf(t, stackTags);
case TagGroup.Group:
return oneOf(t, groupTags);
case TagGroup.Text:
return blockTextTags.has(t) || inlineTags.has(t);
default:
return false;
}
}
export function resolveTag(tag: string | undefined, fallback: string, group: TagGroup): string {
const t = tag?.trim().toLowerCase() ?? "";
if (!t) return fallback;
if (isAllowedTag(t, group)) return t;
warnTagFallback(t, fallback, group);
return fallback;
}
// Code generated by packages/kit-compose/src/organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
import { cn } from "./cn";
import { isDevEnv } from "./env";
/**
* A shadcn/cva-style variant table, without the dependency (same idea as `cva` from class-variance-authority).
*
* const badgeVariants = variants({
* base: "inline-flex items-center",
* variants: { size: { sm: "h-5 px-2", lg: "h-8 px-3" } },
* defaultVariants: { size: "sm" },
* compoundVariants: [{ size: "lg", shape: "rounded", class: "rounded-lg" }],
* });
* badgeVariants({ size: "lg" }); // "inline-flex items-center h-8 px-3"
*
* Classes come in this order: base, each variant in table order, then the matching compound variants.
* tailwind-merge (`cn`) resolves conflicts, the later class wins. A compound value may list alternatives: "32|lg".
*/
export type VariantTable = {
base?: string;
variants: Record<string, Record<string, string>>;
defaultVariants: Record<string, string>;
compoundVariants?: Array<{ class: string } & Record<string, string>>;
};
/** the props a table accepts: one optional value per variant */
export type VariantSelection<T extends VariantTable> = {
[K in keyof T["variants"]]?: (keyof T["variants"][K] & string) | undefined;
};
/** a variant function: call it with the selected values, read `.table` for the types */
export type VariantFn<T extends VariantTable> = ((selection?: VariantSelection<T>) => string) & { table: T };
/** the values of one variant of a table: `VariantKey<typeof badgeVariants, "size">` is `"sm" | "lg"` */
export type VariantKey<F extends { table: VariantTable }, K extends keyof F["table"]["variants"]> = Exclude<
keyof F["table"]["variants"][K] & string,
""
>;
export function variants<T extends VariantTable>(table: T): VariantFn<T> {
const pick = (selection: Record<string, string | undefined>, key: string): string =>
(selection[key] ?? "").trim() || (table.defaultVariants[key] ?? "").trim();
const fn = (selection: VariantSelection<T> = {}): string => {
const sel = selection as Record<string, string | undefined>;
const parts: string[] = [table.base ?? ""];
for (const [key, choices] of Object.entries(table.variants)) {
const choice = pick(sel, key);
const cls = choices[choice];
// a typo in development is an error; in production the unknown value is dropped
if (cls === undefined && isDevEnv()) throw new Error(`[variants] unknown value "${choice}" for "${key}"`);
parts.push(cls ?? "");
}
for (const compound of table.compoundVariants ?? []) {
const matches = Object.entries(compound).every(([k, want]) => k === "class" || want.split("|").includes(pick(sel, k)));
if (matches) parts.push(compound.class);
}
return cn(...parts.map((p) => p.trim()).filter(Boolean));
};
return Object.assign(fn, { table });
}
Point the CLI at this runtime once, then add the item:
npx ui8kit init --yes --framework templ --dir src --registry-url https://registry.buildy.tw/templ --strict-cdnnpx ui8kit add utilsmodule github.com/ui8kit/codegen/generated/templ
go 1.26.0
require github.com/a-h/templ v0.3.1070
github.com/a-h/templ v0.3.1070 h1:3iCOXHXqFXa99OQzgkUOLJbNzv/QjFGLwKZkBAg+ADA=
github.com/a-h/templ v0.3.1070/go.mod h1:iIqB3g2RHBe/WlnPwa+Bvhh1TKXHWLRnBD9NWHOLm78=
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
// Code generated by packages/kit-compose/src/server-organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
package uiutils
import (
"strings"
"unicode"
)
func mergeTailwind(classes ...string) string {
var tokens []string
for _, chunk := range classes {
for _, part := range strings.Fields(chunk) {
tokens = append(tokens, part)
}
}
if len(tokens) == 0 {
return ""
}
// tailwind-merge semantics: each class has one group; a later class removes the earlier classes
// of its own group and of the groups it overrides (p-2 removes an earlier px-4, not the reverse).
type item struct {
token string
key string
}
kept := make([]item, 0, len(tokens))
for _, token := range tokens {
prefix, key, removes := classKey(token)
if key != "" {
drop := map[string]bool{key: true}
for _, g := range removes {
drop[prefix+g] = true
}
next := kept[:0]
for _, it := range kept {
if !drop[it.key] {
next = append(next, it)
}
}
kept = next
}
kept = append(kept, item{token: token, key: key})
}
out := make([]string, 0, len(kept))
for _, it := range kept {
out = append(out, it.token)
}
return strings.Join(out, " ")
}
// classKey: the variant prefix, the conflict key (prefix + group) and the groups this class overrides.
func classKey(token string) (prefix, key string, removes []string) {
prefix, core := splitVariant(token)
if core == "" {
return "", "", nil
}
groups := utilityGroups(core)
if len(groups) == 0 {
// no known group: only the same class conflicts with itself (tailwind-merge keeps the last of duplicates)
return prefix, "=" + token, nil
}
return prefix, prefix + groups[0], groups[1:]
}
func splitVariant(token string) (prefix, core string) {
depth := 0
cut := -1
for i, r := range token {
switch r {
case '[':
depth++
case ']':
if depth > 0 {
depth--
}
case ':':
if depth == 0 {
cut = i
}
}
}
if cut == -1 {
return "", strings.TrimPrefix(token, "!")
}
return token[:cut+1], strings.TrimPrefix(token[cut+1:], "!")
}
func utilityGroups(core string) []string {
switch core {
case "block", "inline", "inline-block", "inline-flex", "flex", "grid", "contents", "hidden":
return []string{"display"}
case "flex-row", "flex-col", "flex-row-reverse", "flex-col-reverse":
return []string{"flex-direction"}
case "static", "relative", "absolute", "fixed", "sticky":
return []string{"position"}
case "isolate", "isolation-auto":
return []string{"isolation"}
}
// rings: the width (ring, ring-2) and the colour (ring-primary) are separate groups, as in tailwind-merge
for _, kind := range []string{"inset-ring", "ring"} {
if core == kind {
return []string{kind + "-width"}
}
if rest, ok := strings.CutPrefix(core, kind+"-"); ok {
if isNumber(rest) {
return []string{kind + "-width"}
}
return []string{kind + "-color"}
}
}
if group, ok := prefixGroup(core, [][2]string{
{"gap-x-", "gap-x"},
{"gap-y-", "gap-y"},
{"items-", "align-items"},
{"justify-", "justify-content"},
{"self-", "align-self"},
{"content-", "align-content"},
{"overflow-x-", "overflow-x"},
{"overflow-y-", "overflow-y"},
{"inset-x-", "inset-x"},
{"inset-y-", "inset-y"},
{"min-w-", "min-width"},
{"min-h-", "min-height"},
{"max-w-", "max-width"},
{"max-h-", "max-height"},
{"shadow-", "shadow"},
{"ring-", "ring"},
{"rounded-", "rounded"},
{"leading-", "leading"},
{"tracking-", "tracking"},
{"opacity-", "opacity"},
{"z-", "z"},
{"top-", "top"},
{"right-", "right"},
{"bottom-", "bottom"},
{"left-", "left"},
}); ok {
return []string{group}
}
switch {
case strings.HasPrefix(core, "gap-"):
return []string{"gap", "gap-x", "gap-y"}
case strings.HasPrefix(core, "inset-"):
return []string{"inset", "inset-x", "inset-y", "top", "right", "bottom", "left"}
case strings.HasPrefix(core, "overflow-"):
return []string{"overflow", "overflow-x", "overflow-y"}
case core == "border" || (strings.HasPrefix(core, "border-") && isNumber(core[7:])):
return []string{"border-width", "border-w-x", "border-w-y", "border-w-t", "border-w-r", "border-w-b", "border-w-l", "border-w-s", "border-w-e"}
case len(core) >= 8 && strings.HasPrefix(core, "border-") && strings.Contains("xytrblse", core[7:8]) && (len(core) == 8 || (core[8] == '-' && isNumber(core[9:]))):
side := core[7:8]
if side == "x" {
return []string{"border-w-x", "border-w-r", "border-w-l", "border-w-s", "border-w-e"}
}
if side == "y" {
return []string{"border-w-y", "border-w-t", "border-w-b"}
}
return []string{"border-w-" + side}
case core == "text-left" || core == "text-center" || core == "text-right" || core == "text-justify" || core == "text-start" || core == "text-end":
return []string{"text-align"}
case core == "rounded":
return []string{"rounded"}
case core == "shadow" || core == "shadow-none":
return []string{"shadow"}
case core == "flex-1" || core == "flex-auto" || core == "flex-none" || core == "flex-initial":
return []string{"flex-size", "flex-grow", "flex-shrink", "flex-basis"}
case core == "grow" || strings.HasPrefix(core, "grow-"):
return []string{"flex-grow"}
case core == "shrink" || core == "shrink-0":
return []string{"flex-shrink"}
}
if strings.HasPrefix(core, "size-") {
return []string{"size", "width", "height"}
}
if strings.HasPrefix(core, "w-") {
return []string{"width"}
}
if strings.HasPrefix(core, "h-") {
return []string{"height"}
}
if strings.HasPrefix(core, "p-") && !hasDirectionPrefix(core, "p") {
return []string{"padding", "padding-x", "padding-y", "padding-t", "padding-r", "padding-b", "padding-l", "padding-s", "padding-e"}
}
if g, ok := spaceAxis(core, "p"); ok {
return g
}
if strings.HasPrefix(core, "m-") && !hasDirectionPrefix(core, "m") {
return []string{"margin", "margin-x", "margin-y", "margin-t", "margin-r", "margin-b", "margin-l", "margin-s", "margin-e"}
}
if g, ok := spaceAxis(core, "m"); ok {
return g
}
if strings.HasPrefix(core, "bg-") {
return []string{"bg"}
}
if isTextSize(core) {
return []string{"text-size", "leading"}
}
if strings.HasPrefix(core, "text-") {
return []string{"text-color"}
}
if strings.HasPrefix(core, "font-") && isFontWeight(core) {
return []string{"font-weight"}
}
return nil
}
func prefixGroup(core string, prefixes [][2]string) (string, bool) {
for _, pair := range prefixes {
if strings.HasPrefix(core, pair[0]) {
return pair[1], true
}
}
return "", false
}
func hasDirectionPrefix(core, kind string) bool {
for _, dir := range []string{"x-", "y-", "t-", "r-", "b-", "l-", "s-", "e-"} {
if strings.HasPrefix(core, kind+dir) {
return true
}
}
return false
}
func spaceAxis(core, kind string) ([]string, bool) {
switch {
case strings.HasPrefix(core, kind+"x-"):
return []string{kindName(kind) + "-x", kindName(kind) + "-r", kindName(kind) + "-l", kindName(kind) + "-s", kindName(kind) + "-e"}, true
case strings.HasPrefix(core, kind+"y-"):
return []string{kindName(kind) + "-y", kindName(kind) + "-t", kindName(kind) + "-b"}, true
case strings.HasPrefix(core, kind+"t-"):
return []string{kindName(kind) + "-t"}, true
case strings.HasPrefix(core, kind+"r-"):
return []string{kindName(kind) + "-r"}, true
case strings.HasPrefix(core, kind+"b-"):
return []string{kindName(kind) + "-b"}, true
case strings.HasPrefix(core, kind+"l-"):
return []string{kindName(kind) + "-l"}, true
}
return nil, false
}
func kindName(kind string) string {
if kind == "p" {
return "padding"
}
return "margin"
}
func isTextSize(core string) bool {
switch core {
case "text-xs", "text-sm", "text-base", "text-lg", "text-xl", "text-2xl", "text-3xl", "text-4xl", "text-5xl", "text-6xl", "text-7xl", "text-8xl", "text-9xl":
return true
}
if strings.HasPrefix(core, "text-[") {
rest := strings.TrimPrefix(core, "text-[")
if rest == "" {
return false
}
return unicode.IsDigit(rune(rest[0])) || rest[0] == '.'
}
return false
}
func isFontWeight(core string) bool {
switch core {
case "font-thin", "font-extralight", "font-light", "font-normal", "font-medium", "font-semibold", "font-bold", "font-extrabold", "font-black":
return true
}
return false
}
// isNumber: a bare number (2, 0.5) or an arbitrary length ([3px])
func isNumber(s string) bool {
if strings.HasPrefix(s, "[") {
return true
}
if s == "" {
return false
}
for _, c := range s {
if (c < '0' || c > '9') && c != '.' {
return false
}
}
return true
}
// Code generated by packages/kit-compose/src/server-organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
package uiutils
// The dynamic values of the generated organisms: props, records and labels travel as `any` (JSON shapes: string,
// float64, bool, nil, []any, map[string]any), read with the same rules as the TypeScript output (JS truthiness,
// strict equality, String(), clsx + tailwind-merge for classes). Every helper is nil-safe, like `?.` in TypeScript.
import (
"fmt"
"encoding/json"
"math"
"strconv"
"strings"
"github.com/a-h/templ"
)
// Get reads a path of fields: Get(plan, "price", "amount"); `length` of a list or a text is its size.
func Get(v any, path ...string) any {
for _, k := range path {
switch x := v.(type) {
case map[string]any:
v = x[k]
case []any:
if k == "length" {
v = float64(len(x))
} else if i, err := strconv.Atoi(k); err == nil && i >= 0 && i < len(x) {
v = x[i]
} else {
return nil
}
case string:
if k != "length" {
return nil
}
v = float64(len([]rune(x)))
default:
return nil
}
}
return v
}
// num is the number of a value (int, float64), and whether it is one.
func num(v any) (float64, bool) {
switch x := v.(type) {
case float64:
return x, true
case int:
return float64(x), true
case int64:
return float64(x), true
case float32:
return float64(x), true
}
return 0, false
}
// fmtNum is String(n) of JavaScript for the numbers the views print: 3, 2.5, -1.
func fmtNum(f float64) string {
if math.IsNaN(f) {
return "NaN"
}
if f == math.Trunc(f) && math.Abs(f) < 1e21 {
return strconv.FormatFloat(f, 'f', -1, 64)
}
return strconv.FormatFloat(f, 'g', -1, 64)
}
// S is String(v) for a value read into a string slot; nil is the empty string.
func S(v any) string {
switch x := v.(type) {
case nil:
return ""
case string:
return x
case bool:
if x {
return "true"
}
return "false"
}
if f, ok := num(v); ok {
return fmtNum(f)
}
b, _ := json.Marshal(v)
return string(b)
}
// Text is what a text node shows: React and Svelte print nothing for nil and booleans.
func Text(v any) string {
if _, ok := v.(bool); ok {
return ""
}
return S(v)
}
var htmlEntities = strings.NewReplacer("&", "&", "<", "<", ">", ">", `"`, """, "'", "'")
// Html is the markup an html node prints (through templ.Raw): the trusted markup ({"__html": "..."}, a TrustedHtml prop) as it is;
// any other value is text, escaped (& < > " ' as entities, like htmlOf of the TypeScript runtimes).
func Html(v any) string {
if m, ok := v.(map[string]any); ok {
if s, ok := m["__html"].(string); ok {
return s
}
}
return htmlEntities.Replace(Text(v))
}
// T is the truthiness of JavaScript: nil, false, 0, NaN and "" are false.
func T(v any) bool {
switch x := v.(type) {
case nil:
return false
case bool:
return x
case string:
return x != ""
}
if f, ok := num(v); ok {
return f != 0 && !math.IsNaN(f)
}
return true
}
// N is Number(v): numbers as they are, numeric strings parsed, booleans 0 or 1, the rest 0.
func N(v any) float64 {
if f, ok := num(v); ok {
return f
}
switch x := v.(type) {
case string:
f, err := strconv.ParseFloat(strings.TrimSpace(x), 64)
if err == nil {
return f
}
case bool:
if x {
return 1
}
}
return 0
}
// I is an int for an int prop of a brick (Size: 16).
func I(v any) int { return int(math.Round(N(v))) }
// Eq is strict equality (===) of two values.
func Eq(a, b any) bool {
fa, okA := num(a)
fb, okB := num(b)
if okA || okB {
return okA && okB && fa == fb
}
switch x := a.(type) {
case nil:
return b == nil
case string:
y, ok := b.(string)
return ok && x == y
case bool:
y, ok := b.(bool)
return ok && x == y
}
return false
}
// Lt and friends compare numbers, or two texts by their code units.
func cmp(a, b any) (int, bool) {
if x, ok := a.(string); ok {
if y, ok2 := b.(string); ok2 {
return strings.Compare(x, y), true
}
}
if a == nil || b == nil {
return 0, false
}
fa, fb := N(a), N(b)
switch {
case fa < fb:
return -1, true
case fa > fb:
return 1, true
}
return 0, true
}
func Lt(a, b any) bool { c, ok := cmp(a, b); return ok && c < 0 }
func Gt(a, b any) bool { c, ok := cmp(a, b); return ok && c > 0 }
func Le(a, b any) bool { c, ok := cmp(a, b); return ok && c <= 0 }
func Ge(a, b any) bool { c, ok := cmp(a, b); return ok && c >= 0 }
// Add is `a + b`: text when either side is text, else a sum.
func Add(a, b any) any {
_, sa := a.(string)
_, sb := b.(string)
if sa || sb {
return S(a) + S(b)
}
return N(a) + N(b)
}
func Sub(a, b any) any { return N(a) - N(b) }
func Mul(a, b any) any { return N(a) * N(b) }
func Div(a, b any) any { return N(a) / N(b) }
// And and Or keep the value of JavaScript: the first falsy (And) or truthy (Or) operand, else the last.
func And(vs ...any) any {
var last any
for _, v := range vs {
if !T(v) {
return v
}
last = v
}
return last
}
func Or(vs ...any) any {
var last any
for _, v := range vs {
if T(v) {
return v
}
last = v
}
return last
}
// Coalesce is `a ?? b ?? c`.
func Coalesce(vs ...any) any {
for _, v := range vs {
if v != nil {
return v
}
}
return nil
}
// Def is a prop with its default: the default when the prop is nil.
func Def(v, d any) any {
if v == nil {
return d
}
return v
}
// Cond is `c ? a : b` (both sides are pure values, read eagerly).
func Cond(c bool, a, b any) any {
if c {
return a
}
return b
}
// L is a list to range over; nil and other values are empty.
func L(v any) []any {
switch x := v.(type) {
case []any:
return x
case []string:
out := make([]any, len(x))
for i, s := range x {
out[i] = s
}
return out
case []map[string]any:
out := make([]any, len(x))
for i, s := range x {
out[i] = s
}
return out
}
return nil
}
// Len is `x?.length ?? 0`.
func Len(v any) any {
switch x := v.(type) {
case string:
return float64(len([]rune(x)))
case nil:
return float64(0)
}
return float64(len(L(v)))
}
// List is a literal array.
func List(vs ...any) any { return vs }
// Group is a literal object; Spread copies the fields of a named group first (`{ ...BASE, mode: "two" }`).
func Spread(base any, fields map[string]any) any {
out := map[string]any{}
if m, ok := base.(map[string]any); ok {
for k, v := range m {
out[k] = v
}
}
for k, v := range fields {
out[k] = v
}
return out
}
// Str is String(x) with undefined kept undefined.
func Str(v any) any {
if v == nil {
return nil
}
return S(v)
}
// SP is the nullable string of v for a *string field: nil stays nil (unset), anything else is S(v).
func SP(v any) *string {
if v == nil {
return nil
}
s := S(v)
return &s
}
// Has is `x != null`.
func Has(v any) bool { return v != nil }
// Cnv is cn(...) over values: clsx skips the falsy ones, tailwind-merge resolves conflicts.
func Cnv(vs ...any) string {
parts := make([]string, 0, len(vs))
for _, v := range vs {
if T(v) {
parts = append(parts, S(v))
}
}
return mergeTailwind(parts...)
}
// Tpl fills {0}, {1}... of a content template.
func Tpl(t any, vals ...any) string {
s := S(t)
var b strings.Builder
for i := 0; i < len(s); i++ {
if s[i] == '{' {
j := i + 1
for j < len(s) && s[j] >= '0' && s[j] <= '9' {
j++
}
if j > i+1 && j < len(s) && s[j] == '}' {
n, _ := strconv.Atoi(s[i+1 : j])
if n < len(vals) {
b.WriteString(S(vals[n]))
}
i = j
continue
}
}
b.WriteByte(s[i])
}
return b.String()
}
// group writes the integer part of a number with en-US thousands separators.
func group(f float64, decimals int) string {
s := strconv.FormatFloat(math.Abs(f), 'f', decimals, 64)
intPart, frac, _ := strings.Cut(s, ".")
var b strings.Builder
for i, c := range intPart {
if i > 0 && (len(intPart)-i)%3 == 0 {
b.WriteByte(',')
}
b.WriteRune(c)
}
out := b.String()
if frac != "" {
frac = strings.TrimRight(frac, "0")
if frac != "" {
out += "." + frac
}
}
if f < 0 && out != "0" {
out = "-" + out
}
return out
}
// Num is Intl.NumberFormat("en-US"): grouped, up to 3 decimals.
func Num(v any) string { return group(N(v), 3) }
var currencySymbols = map[string]string{"USD": "$", "EUR": "€", "GBP": "£", "JPY": "¥", "INR": "₹", "CAD": "CA$", "AUD": "A$"}
// MinorDigits is the digits of the minor unit (ISO 4217): 2, or 0 for JPY and KRW.
func MinorDigits(c string) int {
if c == "JPY" || c == "KRW" {
return 0
}
return 2
}
// Money formats integer minor units (Codex v0.4: 1250 = 12.50) like Intl.NumberFormat("en-US", {style: "currency"}),
// without the fraction when the amount is whole: 149900 -> "$1,499", 1250 -> "$12.50".
func Money(amount, currency any) string {
c := S(currency)
sym, ok := currencySymbols[c]
if !ok {
sym = c + "\u00a0"
}
minor := math.Round(N(amount))
sign := ""
if minor < 0 {
sign, minor = "-", -minor
}
d := MinorDigits(c)
unit := math.Pow(10, float64(d))
whole := math.Floor(minor / unit)
out := sign + sym + group(whole, 0)
if rest := minor - whole*unit; d > 0 && rest != 0 {
out += fmt.Sprintf(".%0*d", d, int(rest))
}
return out
}
// At is a content word by key, the key itself when the dictionary has no entry.
func At(dict, key any) string {
if v := Get(dict, S(key)); v != nil {
return S(v)
}
return S(key)
}
// PageWindow is the pages a pager shows: the first, the last and the neighbours of the current one; nil is a gap.
func PageWindow(pageV, pagesV any) any {
page, pages := int(N(pageV)), int(N(pagesV))
keep := map[int]bool{}
for _, n := range []int{1, pages, page - 1, page, page + 1} {
if n >= 1 && n <= pages {
keep[n] = true
}
}
out := []any{}
prev := 0
for n := 1; n <= pages; n++ {
if !keep[n] {
continue
}
if n-prev > 1 {
out = append(out, nil)
}
out = append(out, float64(n))
prev = n
}
return out
}
// FitCols caps a responsive column variant of Grid by the number of items: ("1-4", 3) -> "1-3".
func FitCols(colsV, nV any) string {
cols, n := S(colsV), int(N(nV))
lo, hi, ok := strings.Cut(cols, "-")
l, e1 := strconv.Atoi(lo)
h, e2 := strconv.Atoi(hi)
if !ok || e1 != nil || e2 != nil {
return cols
}
if n >= h {
return cols
}
top := l
if n > top {
top = n
}
known := map[string]bool{"1-2": true, "1-3": true, "1-4": true, "2-3": true, "2-4": true, "2-6": true, "3-6": true}
for k := top; k > l; k-- {
if known[strconv.Itoa(l)+"-"+strconv.Itoa(k)] {
return strconv.Itoa(l) + "-" + strconv.Itoa(k)
}
}
m := n
if m < 1 {
m = 1
}
if l < m {
m = l
}
return strconv.Itoa(m)
}
// Uniq drops a segment of a ", " label equal (case-insensitive) to the one before it.
func Uniq(v any) string {
parts := strings.Split(S(v), ", ")
out := make([]string, 0, len(parts))
for i, s := range parts {
if i == 0 || !strings.EqualFold(s, parts[i-1]) {
out = append(out, s)
}
}
return strings.Join(out, ", ")
}
// Words splits a text at its spaces.
func Words(v any) any {
out := []any{}
for _, w := range strings.Split(S(v), " ") {
out = append(out, w)
}
return out
}
// Nbsp makes every space a no-break space.
func Nbsp(v any) string { return strings.ReplaceAll(S(v), " ", "\u00a0") }
// Nth is `list?.[i]`.
func Nth(list, i any) any {
l := L(list)
n := int(N(i))
if n < 0 || n >= len(l) {
return nil
}
return l[n]
}
// Range is [0 .. n-1].
func Range(n any) any {
out := []any{}
for i := 0; i < int(N(n)); i++ {
out = append(out, float64(i))
}
return out
}
func Max(vs ...any) any {
m := math.Inf(-1)
for _, v := range vs {
m = math.Max(m, N(v))
}
return m
}
func Min(vs ...any) any {
m := math.Inf(1)
for _, v := range vs {
m = math.Min(m, N(v))
}
return m
}
// Round is Math.round (halves up).
func Round(v any) any { return math.Floor(N(v) + 0.5) }
// Count is how many items have a truthy field.
func Count(items, field any) any {
n := 0
for _, it := range L(items) {
if T(Get(it, S(field))) {
n++
}
}
return float64(n)
}
// Where keeps the items whose field equals the value; an empty value keeps all.
func Where(items, field, value any) any {
if !T(value) {
return L(items)
}
out := []any{}
for _, it := range L(items) {
if Eq(Get(it, S(field)), value) {
out = append(out, it)
}
}
return out
}
// Match keeps the items whose text field contains the query, ignoring case; an empty query keeps all.
func Match(items, field, query any) any {
if !T(query) {
return L(items)
}
q := strings.ToLower(S(query))
out := []any{}
for _, it := range L(items) {
if strings.Contains(strings.ToLower(S(Get(it, S(field)))), q) {
out = append(out, it)
}
}
return out
}
// Pick is the item whose id equals the value.
func Pick(items, id any) any {
for _, it := range L(items) {
if Eq(Get(it, "id"), id) {
return it
}
}
return nil
}
// SumBy is the sum of a * b over the items.
func SumBy(items any, a, b string) any {
s := 0.0
for _, it := range L(items) {
s += N(Get(it, a)) * N(Get(it, b))
}
return s
}
// FirstOf is a field of the first item, "" for none.
func FirstOf(items any, field string) any {
l := L(items)
if len(l) == 0 {
return ""
}
return Coalesce(Get(l[0], field), "")
}
// MaxBy is the largest field of the items, 0 for none.
func MaxBy(items any, field string) any {
m := 0.0
for _, it := range L(items) {
m = math.Max(m, N(Get(it, field)))
}
return m
}
// Css is an inline style from (property, value, unit) triples: "height:12px;width:50%".
func Css(triples ...any) string {
parts := []string{}
for i := 0; i+2 < len(triples); i += 3 {
parts = append(parts, S(triples[i])+":"+CSSValue(triples[i+1])+S(triples[i+2]))
}
return strings.Join(parts, ";")
}
// Variant is a class string of a recipe table (shadcn/cva style): base, each key in order, the matching compounds.
func Variant(r VariantRecipe, compound []map[string]string, sel map[string]any) string {
pick := func(k string) string {
if v := strings.TrimSpace(S(sel[k])); v != "" {
return v
}
return strings.TrimSpace(r.Defaults[k])
}
parts := []string{r.Base}
for _, k := range r.Keys {
parts = append(parts, r.ByKey[k][pick(k)])
}
for _, c := range compound {
ok := true
for k, want := range c {
if k == "class" {
continue
}
hit := false
for _, w := range strings.Split(want, "|") {
if w == pick(k) {
hit = true
}
}
ok = ok && hit
}
if ok {
parts = append(parts, c["class"])
}
}
keep := []string{}
for _, p := range parts {
if p = strings.TrimSpace(p); p != "" {
keep = append(keep, p)
}
}
return mergeTailwind(keep...)
}
// Recipe is a parsed recipe file with its compound variants.
type Recipe struct {
VariantRecipe
}
// MustRecipe parses an embedded *.variants.json.
func MustRecipe(data []byte) Recipe {
var r Recipe
if err := json.Unmarshal(data, &r); err != nil {
panic(err)
}
return r
}
// Of is the class string of a recipe for a selection.
func (r Recipe) Of(sel map[string]any) string {
return Variant(r.VariantRecipe, r.VariantRecipe.Compound, sel)
}
// MustJSON parses embedded JSON into `any` (the kit presets).
func MustJSON(data []byte) any {
var v any
if err := json.Unmarshal(data, &v); err != nil {
panic(err)
}
return v
}
// As converts a dynamic value into a typed one through JSON (the items of a brick: []BreadcrumbItem).
func As[T any](v any) T {
var out T
b, err := json.Marshal(v)
if err == nil {
_ = json.Unmarshal(b, &out)
}
return out
}
// Attrs are free DOM attributes from (name, value) pairs, as React prints them: nil is left out, a boolean of a
// data-* or aria-* attribute is its text, a boolean of another attribute is present or absent, a number is its text.
func Attrs(kv ...any) templ.Attributes {
out := templ.Attributes{}
for i := 0; i+1 < len(kv); i += 2 {
k, v := S(kv[i]), kv[i+1]
if !IsSafeAttrName(k) {
continue
}
if _, isBool := v.(bool); !isBool && v != nil {
v = AttrValue(k, v)
}
switch x := v.(type) {
case nil:
continue
case bool:
if strings.HasPrefix(k, "data-") || strings.HasPrefix(k, "aria-") {
out[k] = S(x)
} else if x {
out[k] = true
}
default:
out[k] = S(v)
}
}
return out
}
// Code generated by packages/kit-compose/src/server-organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
package uiutils
import "strings"
// Tiny attribute-logic helpers used by generated components. One
// implementation per runtime family keeps every default-resolution decision
// table identical across Templ, React, Svelte, and Vue (mirrors expr.ts).
// TrimStr trims surrounding whitespace.
func TrimStr(v string) string { return strings.TrimSpace(v) }
// IsSetStr reports whether the trimmed string is non-empty.
func IsSetStr(v string) bool { return strings.TrimSpace(v) != "" }
// DefaultIfEmpty returns fallback when the trimmed value is empty.
func DefaultIfEmpty(v, fallback string) string {
t := strings.TrimSpace(v)
if t == "" {
return fallback
}
return t
}
// OneOfOr returns the trimmed value when in allowed, otherwise fallback.
func OneOfOr(v, fallback string, allowed ...string) string {
t := strings.TrimSpace(v)
for _, a := range allowed {
if t == a {
return t
}
}
return fallback
}
// OneOfOrLower lowercases before the whitelist check.
func OneOfOrLower(v, fallback string, allowed ...string) string {
return OneOfOr(strings.ToLower(strings.TrimSpace(v)), fallback, allowed...)
}
// MapOr is a decision table: mapping[trim(v)] or fallback.
func MapOr(v string, mapping map[string]string, fallback string) string {
if out, ok := mapping[strings.TrimSpace(v)]; ok {
return out
}
return fallback
}
// MapOrLower lowercases before the table lookup.
func MapOrLower(v string, mapping map[string]string, fallback string) string {
return MapOr(strings.ToLower(strings.TrimSpace(v)), mapping, fallback)
}
// IntMapOr is an integer decision table: mapping[v] or fallback.
func IntMapOr(v int, mapping map[int]string, fallback string) string {
if out, ok := mapping[v]; ok {
return out
}
return fallback
}
// BoolStr stringifies ARIA state: always "true"/"false", never omitted.
func BoolStr(v bool) string {
if v {
return "true"
}
return "false"
}
// ConcatTrim concatenates trimmed parts (icon Prefix + Name).
func ConcatTrim(parts ...string) string {
var b strings.Builder
for _, p := range parts {
b.WriteString(strings.TrimSpace(p))
}
return b.String()
}
// If is an eager ternary for value selection in attribute expressions.
func If[T any](cond bool, then, els T) T {
if cond {
return then
}
return els
}
// Code generated by packages/kit-compose/src/server-organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
package uiutils
// HeadingLevel maps to h1–h6 (default h2 when zero or out of range).
type HeadingLevel int
const (
H1 HeadingLevel = 1
H2 HeadingLevel = 2
H3 HeadingLevel = 3
H4 HeadingLevel = 4
H5 HeadingLevel = 5
H6 HeadingLevel = 6
)
// TitleTag returns h1-h6 from order.
func TitleTag(order HeadingLevel) string {
switch int(order) {
case 1:
return "h1"
case 3:
return "h3"
case 4:
return "h4"
case 5:
return "h5"
case 6:
return "h6"
default:
return "h2"
}
}
// Code generated by packages/kit-compose/src/server-organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
package uiutils
// Output safety of the organism runtime, the same rules as assets/ts/safe.ts, Runtime.php and runtime.py (shared vectors:
// packages/compose-gen/runtimes/core/test/safety-vectors.json). An allowlist: a URL is kept when, read as a browser reads it
// (entities decoded, ASCII whitespace and control characters removed), it has no scheme and is not protocol-relative
// (//host, /\host, \\host), or its scheme is http, https, mailto or tel; an image URL may also be data:image/*. A srcset is
// checked candidate by candidate, a style by its url(...) and script forms; an attribute name must be a valid name, not on*.
import (
"regexp"
"strconv"
"strings"
)
// NamedEntities are the named character references the URL check decodes.
var NamedEntities = map[string]string{
"Tab": "\t", "NewLine": "\n", "colon": ":", "sol": "/", "bsol": "\\", "lpar": "(", "rpar": ")", "amp": "&", "lt": "<", "gt": ">",
"quot": `"`, "apos": "'", "nbsp": "\u00a0", "period": ".", "comma": ",", "excl": "!", "num": "#", "quest": "?", "equals": "=",
"plus": "+", "semi": ";", "percnt": "%", "lowbar": "_", "ast": "*", "commat": "@", "dollar": "$", "Hat": "^", "grave": "`",
"lsqb": "[", "rsqb": "]", "lcub": "{", "rcub": "}", "verbar": "|", "vert": "|",
}
// URLSchemes are the schemes a URL may name.
var URLSchemes = []string{"http", "https", "mailto", "tel"}
// URLAttrs are the attributes whose value is a URL; ImageAttrs those whose URL is an image.
var URLAttrs = []string{"href", "src", "action", "formaction", "poster", "cite", "background", "data", "xlink:href"}
var ImageAttrs = []string{"src", "poster", "background"}
var (
entityRe = regexp.MustCompile(`&(?:#[xX]([0-9a-fA-F]{1,8});?|#([0-9]{1,10});?|([a-zA-Z][a-zA-Z0-9]{0,31});)`)
controlRe = regexp.MustCompile(`[\x00-\x20\x7f]+`)
networkRe = regexp.MustCompile(`^[/\\]{2}`)
schemeRe = regexp.MustCompile(`^([a-zA-Z][a-zA-Z0-9+.\-]*):`)
dataImageRe = regexp.MustCompile(`^data:image/(png|jpeg|gif|webp|avif|svg\+xml)[;,]`)
styleBadRe = regexp.MustCompile(`expression\(|javascript:|vbscript:|-moz-binding|behavior:`)
styleURLRe = regexp.MustCompile(`(?i)url\(([^)]*)\)?`)
quotedRe = regexp.MustCompile(`(?s)^"(.*)"$|^'(.*)'$`)
colonFirstRe = regexp.MustCompile(`^[^/]*:`)
cssValueRe = regexp.MustCompile(`^[-+.%#a-zA-Z0-9 ,]*$`)
attrNameRe = regexp.MustCompile(`^[a-zA-Z_:][-a-zA-Z0-9_:.]*$`)
trailComma = regexp.MustCompile(`,+$`)
)
func fromCode(n uint64, ok bool) string {
if !ok || n == 0 || n > 0x10FFFF || (n >= 0xD800 && n <= 0xDFFF) {
return "\uFFFD"
}
return string(rune(n))
}
// DecodeEntities decodes character references as a browser would (numeric with or without ;, the named ones of NamedEntities), up to 3 rounds.
func DecodeEntities(s string) string {
for i := 0; i < 3 && strings.Contains(s, "&"); i++ {
s = entityRe.ReplaceAllStringFunc(s, func(m string) string {
g := entityRe.FindStringSubmatch(m)
if g[1] != "" {
n, err := strconv.ParseUint(g[1], 16, 64)
return fromCode(n, err == nil)
}
if g[2] != "" {
n, err := strconv.ParseUint(g[2], 10, 64)
return fromCode(n, err == nil)
}
if r, ok := NamedEntities[g[3]]; ok {
return r
}
return m
})
}
return s
}
func compact(s string) string { return controlRe.ReplaceAllString(DecodeEntities(s), "") }
func has(list []string, s string) bool {
for _, x := range list {
if x == s {
return true
}
}
return false
}
// IsSafeURL is true when the URL is allowed; image: data:image/* too.
func IsSafeURL(v string, image bool) bool {
k := compact(v)
if networkRe.MatchString(k) {
return false
}
m := schemeRe.FindStringSubmatch(k)
if m == nil {
// no scheme: a path, unless a ":" comes before any "/" (as written or decoded), as templ.URL
return !colonFirstRe.MatchString(k) && !colonFirstRe.MatchString(v)
}
scheme := strings.ToLower(m[1])
if scheme == "data" {
return image && dataImageRe.MatchString(strings.ToLower(k))
}
return has(URLSchemes, scheme)
}
func safeStr(v any) string {
switch x := v.(type) {
case string:
return x
case float64, float32, int, int64, int32:
return S(x)
}
return ""
}
// URL is a URL attribute value: the value when allowed, else "".
func URL(v any, image bool) string {
s := safeStr(v)
if IsSafeURL(s, image) {
return s
}
return ""
}
// SrcsetURLs are the URLs of a srcset, candidate by candidate.
func SrcsetURLs(v string) []string {
s := DecodeEntities(v)
out := []string{}
n := len(s)
ws := func(c byte) bool { return c == '\t' || c == '\n' || c == '\f' || c == '\r' || c == ' ' }
i := 0
for i < n {
for i < n && (ws(s[i]) || s[i] == ',') {
i++
}
if i >= n {
break
}
j := i
for j < n && !ws(s[j]) {
j++
}
u := s[i:j]
if cut := trailComma.FindString(u); cut != "" {
out = append(out, u[:len(u)-len(cut)])
i = j
continue
}
out = append(out, u)
depth := 0
for j < n && (depth > 0 || s[j] != ',') {
if s[j] == '(' {
depth++
} else if s[j] == ')' && depth > 0 {
depth--
}
j++
}
i = j + 1
}
return out
}
// Srcset is a srcset value: the value when every candidate is an allowed image URL, else "".
func Srcset(v any) string {
s := safeStr(v)
for _, u := range SrcsetURLs(s) {
if !IsSafeURL(u, true) {
return ""
}
}
return s
}
// Style is a style value: "" when a url(...) is not an image URL or it holds a script form or a CSS escape, else the value.
func Style(v any) string {
s := safeStr(v)
d := DecodeEntities(s)
k := strings.ToLower(compact(s))
if strings.Contains(d, `\`) || styleBadRe.MatchString(k) {
return ""
}
for _, m := range styleURLRe.FindAllStringSubmatch(d, -1) {
arg := strings.Trim(m[1], " \t\n\r\f\v")
if q := quotedRe.FindStringSubmatch(arg); q != nil {
arg = q[1] + q[2]
}
if !IsSafeURL(arg, true) {
return ""
}
}
return s
}
// CSSValue is a value of an inline style declaration (the css op): kept when plain (numbers, words, %, #, +, -, ., commas, spaces), else "".
func CSSValue(v any) string {
s := safeStr(v)
if cssValueRe.MatchString(s) {
return s
}
return ""
}
// IsSafeAttrName is true for an attribute name that may be printed: a valid name, not an event handler (on*).
func IsSafeAttrName(name string) bool {
return attrNameRe.MatchString(name) && !strings.HasPrefix(strings.ToLower(name), "on")
}
// AttrValue is the value of attribute name as it may be printed: URL, srcset and style checked.
func AttrValue(name string, v any) any {
n := strings.ToLower(name)
switch {
case n == "srcset" || n == "imagesrcset":
return Srcset(v)
case n == "style":
return Style(v)
case has(URLAttrs, n):
return URL(v, has(ImageAttrs, n))
}
return v
}
// Code generated by packages/kit-compose/src/server-organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
// Code generated by tagsgen. DO NOT EDIT.
// TagGroup restricts HTML tags for one primitive semantic group.
// Source of truth: utils/tags.json.
package uiutils
import "strings"
// TagGroup restricts which HTML tags a primitive may render.
type TagGroup int
const (
TagGroupLayout TagGroup = iota
TagGroupBoxAllowed
TagGroupBlockText
TagGroupInline
TagGroupHeading
TagGroupList
TagGroupListItem
TagGroupForm
TagGroupFormControl
TagGroupFormLabel
TagGroupTable
TagGroupTableSection
TagGroupTableRow
TagGroupTableCell
TagGroupTableColumn
TagGroupMedia
TagGroupDisclosure
TagGroupContainer
TagGroupStack
TagGroupGroup
TagGroupText
)
// ResolveTag returns tag when allowed for group, otherwise fallback.
func ResolveTag(tag, fallback string, group TagGroup) string {
t := strings.TrimSpace(strings.ToLower(tag))
if t == "" {
return fallback
}
if IsAllowedTag(t, group) {
return t
}
return fallback
}
// IsAllowedTag reports whether tag is valid for the semantic group.
func IsAllowedTag(tag string, group TagGroup) bool {
t := strings.TrimSpace(strings.ToLower(tag))
switch group {
case TagGroupLayout:
return oneOf(t, "div", "section", "article", "aside", "header", "footer", "main", "nav", "figure", "search", "hgroup")
case TagGroupBoxAllowed:
return oneOf(t, "div")
case TagGroupBlockText:
return oneOf(t, "p", "blockquote", "figcaption", "address", "pre")
case TagGroupInline:
return oneOf(t, "span", "em", "strong", "small", "abbr", "cite", "code", "kbd", "mark", "time", "data", "var", "samp", "sub", "sup", "b", "i", "u", "s", "q", "dfn", "bdo", "bdi", "ins", "del")
case TagGroupHeading:
return oneOf(t, "h1", "h2", "h3", "h4", "h5", "h6")
case TagGroupList:
return oneOf(t, "ul", "ol", "dl", "menu")
case TagGroupListItem:
return oneOf(t, "li", "dt", "dd")
case TagGroupForm:
return oneOf(t, "form", "fieldset")
case TagGroupFormControl:
return oneOf(t, "input", "textarea", "select", "button", "option", "optgroup", "datalist", "output", "meter", "progress")
case TagGroupFormLabel:
return oneOf(t, "label", "legend")
case TagGroupTable:
return oneOf(t, "table")
case TagGroupTableSection:
return oneOf(t, "thead", "tbody", "tfoot")
case TagGroupTableRow:
return oneOf(t, "tr")
case TagGroupTableCell:
return oneOf(t, "th", "td")
case TagGroupTableColumn:
return oneOf(t, "colgroup", "col")
case TagGroupMedia:
return oneOf(t, "img", "picture", "source")
case TagGroupDisclosure:
return oneOf(t, "details", "summary")
case TagGroupContainer:
return oneOf(t, "div", "main", "section")
case TagGroupStack:
return oneOf(t, "div", "ul", "ol")
case TagGroupGroup:
return oneOf(t, "div", "fieldset", "dl")
case TagGroupText:
return IsAllowedTag(t, TagGroupBlockText) || IsAllowedTag(t, TagGroupInline)
default:
return false
}
}
func oneOf(value string, options ...string) bool {
for _, opt := range options {
if value == opt {
return true
}
}
return false
}
// Code generated by packages/kit-compose/src/server-organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
// Package uiutils holds shared Go helpers for generated UI8Kit bricks.
package uiutils
import (
"fmt"
"strings"
"github.com/a-h/templ"
)
// Variants groups a base utility chain and keyed variant maps (cva-style).
type Variants struct {
Base string
Keys []string
ByKey map[string]map[string]string
Defaults map[string]string
Compound []map[string]string
}
// Compose merges Base, variant selections, and optional tail classes.
func Compose(v Variants, selection map[string]string, extra ...string) string {
var parts []string
if strings.TrimSpace(v.Base) != "" {
parts = append(parts, strings.TrimSpace(v.Base))
}
for _, key := range v.Keys {
choices, ok := v.ByKey[key]
if !ok {
continue
}
choice := strings.TrimSpace(selection[key])
if choice == "" {
choice = strings.TrimSpace(v.Defaults[key])
}
if choice == "" {
if len(choices) > 0 {
panic(fmt.Sprintf("[Compose] missing default for key %q", key))
}
continue
}
if cls, ok2 := choices[choice]; ok2 {
if strings.TrimSpace(cls) != "" {
parts = append(parts, cls)
}
}
// Unknown choices are silently dropped to avoid leaking typos into
// the DOM as literal class names.
}
for _, c := range v.Compound {
ok := true
for k, want := range c {
if k == "class" {
continue
}
got := strings.TrimSpace(selection[k])
if got == "" {
got = strings.TrimSpace(v.Defaults[k])
}
hit := false
for _, w := range strings.Split(want, "|") {
if w == got {
hit = true
}
}
ok = ok && hit
}
if ok && strings.TrimSpace(c["class"]) != "" {
parts = append(parts, c["class"])
}
}
parts = append(parts, extra...)
return Cn(parts...)
}
// Cn joins class fragments and resolves Tailwind conflicts (last class wins),
// matching the JS `cn` = clsx + tailwind-merge used by HostingPanel kit.
func Cn(classes ...string) string {
return mergeTailwind(classes...)
}
// MergeAttrs merges attribute maps left to right.
func MergeAttrs(parts ...templ.Attributes) templ.Attributes {
out := templ.Attributes{}
for _, attrs := range parts {
for k, v := range attrs {
out[k] = v
}
}
return out
}
// Code generated by packages/kit-compose/src/server-organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
package uiutils
import (
"encoding/json"
"fmt"
)
// VariantRecipe is the JSON shape for *.variants.json (shared with React CVA recipes).
type VariantRecipe struct {
ID string `json:"id"`
Base string `json:"base"`
Keys []string `json:"keys"`
Defaults map[string]string `json:"defaults"`
ByKey map[string]map[string]string `json:"byKey"`
Meta map[string]string `json:"meta,omitempty"`
Compound []map[string]string `json:"compound,omitempty"`
}
// ToVariants converts a recipe into the in-memory CVA map used by Compose.
func (r VariantRecipe) ToVariants() Variants {
return Variants{
Base: r.Base,
Keys: r.Keys,
ByKey: r.ByKey,
Defaults: r.Defaults,
Compound: r.Compound,
}
}
// ParseVariantRecipe unmarshals *.variants.json bytes.
func ParseVariantRecipe(data []byte) (VariantRecipe, error) {
var recipe VariantRecipe
if err := json.Unmarshal(data, &recipe); err != nil {
return VariantRecipe{}, fmt.Errorf("variants JSON: %w", err)
}
if recipe.ByKey == nil {
return VariantRecipe{}, fmt.Errorf("variants JSON: missing byKey")
}
return recipe, nil
}
// MustParseVariantRecipe parses recipe JSON or panics (for generated init blocks).
func MustParseVariantRecipe(data []byte) VariantRecipe {
recipe, err := ParseVariantRecipe(data)
if err != nil {
panic(err)
}
return recipe
}
// Code generated by @ui8kit/codegen. DO NOT EDIT.
package uiutils
import (
"strings"
"unicode"
)
func mergeTailwind(classes ...string) string {
var tokens []string
for _, chunk := range classes {
for _, part := range strings.Fields(chunk) {
tokens = append(tokens, part)
}
}
if len(tokens) == 0 {
return ""
}
// tailwind-merge semantics: each class has one group; a later class removes the earlier classes
// of its own group and of the groups it overrides (p-2 removes an earlier px-4, not the reverse).
type item struct {
token string
key string
}
kept := make([]item, 0, len(tokens))
for _, token := range tokens {
prefix, key, removes := classKey(token)
if key != "" {
drop := map[string]bool{key: true}
for _, g := range removes {
drop[prefix+g] = true
}
next := kept[:0]
for _, it := range kept {
if !drop[it.key] {
next = append(next, it)
}
}
kept = next
}
kept = append(kept, item{token: token, key: key})
}
out := make([]string, 0, len(kept))
for _, it := range kept {
out = append(out, it.token)
}
return strings.Join(out, " ")
}
// classKey: the variant prefix, the conflict key (prefix + group) and the groups this class overrides.
func classKey(token string) (prefix, key string, removes []string) {
prefix, core := splitVariant(token)
if core == "" {
return "", "", nil
}
groups := utilityGroups(core)
if len(groups) == 0 {
// no known group: only the same class conflicts with itself (tailwind-merge keeps the last of duplicates)
return prefix, "=" + token, nil
}
return prefix, prefix + groups[0], groups[1:]
}
func splitVariant(token string) (prefix, core string) {
depth := 0
cut := -1
for i, r := range token {
switch r {
case '[':
depth++
case ']':
if depth > 0 {
depth--
}
case ':':
if depth == 0 {
cut = i
}
}
}
if cut == -1 {
return "", strings.TrimPrefix(token, "!")
}
return token[:cut+1], strings.TrimPrefix(token[cut+1:], "!")
}
func utilityGroups(core string) []string {
switch core {
case "block", "inline", "inline-block", "inline-flex", "flex", "grid", "contents", "hidden":
return []string{"display"}
case "flex-row", "flex-col", "flex-row-reverse", "flex-col-reverse":
return []string{"flex-direction"}
case "static", "relative", "absolute", "fixed", "sticky":
return []string{"position"}
case "isolate", "isolation-auto":
return []string{"isolation"}
case "object-contain", "object-cover", "object-fill", "object-none", "object-scale-down":
return []string{"object-fit"}
case "object-bottom", "object-center", "object-left", "object-left-bottom", "object-left-top", "object-right", "object-right-bottom", "object-right-top", "object-top":
return []string{"object-position"}
}
if strings.HasPrefix(core, "aspect-") {
return []string{"aspect"}
}
// rings: the width (ring, ring-2) and the colour (ring-primary) are separate groups, as in tailwind-merge
// ring-offset-N (width) and ring-offset-<color> are their own groups; they never touch ring width/colour
if rest, ok := strings.CutPrefix(core, "ring-offset-"); ok {
if isNumber(rest) {
return []string{"ring-offset-width"}
}
return []string{"ring-offset-color"}
}
for _, kind := range []string{"inset-ring", "ring"} {
if core == kind {
return []string{kind + "-width"}
}
if rest, ok := strings.CutPrefix(core, kind+"-"); ok {
if isNumber(rest) {
return []string{kind + "-width"}
}
return []string{kind + "-color"}
}
}
if group, ok := prefixGroup(core, [][2]string{
{"gap-x-", "gap-x"},
{"gap-y-", "gap-y"},
{"items-", "align-items"},
{"justify-", "justify-content"},
{"self-", "align-self"},
{"content-", "align-content"},
{"overflow-x-", "overflow-x"},
{"overflow-y-", "overflow-y"},
{"inset-x-", "inset-x"},
{"inset-y-", "inset-y"},
{"min-w-", "min-width"},
{"min-h-", "min-height"},
{"max-w-", "max-width"},
{"max-h-", "max-height"},
{"shadow-", "shadow"},
{"ring-", "ring"},
{"rounded-", "rounded"},
{"leading-", "leading"},
{"tracking-", "tracking"},
{"opacity-", "opacity"},
{"z-", "z"},
{"top-", "top"},
{"right-", "right"},
{"bottom-", "bottom"},
{"left-", "left"},
}); ok {
return []string{group}
}
switch {
case strings.HasPrefix(core, "gap-"):
return []string{"gap", "gap-x", "gap-y"}
case strings.HasPrefix(core, "inset-"):
return []string{"inset", "inset-x", "inset-y", "top", "right", "bottom", "left"}
case strings.HasPrefix(core, "overflow-"):
return []string{"overflow", "overflow-x", "overflow-y"}
case core == "border" || (strings.HasPrefix(core, "border-") && isNumber(core[7:])):
return []string{"border-width", "border-w-x", "border-w-y", "border-w-t", "border-w-r", "border-w-b", "border-w-l", "border-w-s", "border-w-e"}
case len(core) >= 8 && strings.HasPrefix(core, "border-") && strings.Contains("xytrblse", core[7:8]) && (len(core) == 8 || (core[8] == '-' && isNumber(core[9:]))):
side := core[7:8]
if side == "x" {
return []string{"border-w-x", "border-w-r", "border-w-l", "border-w-s", "border-w-e"}
}
if side == "y" {
return []string{"border-w-y", "border-w-t", "border-w-b"}
}
return []string{"border-w-" + side}
case core == "text-left" || core == "text-center" || core == "text-right" || core == "text-justify" || core == "text-start" || core == "text-end":
return []string{"text-align"}
case core == "rounded":
return []string{"rounded"}
case core == "shadow" || core == "shadow-none":
return []string{"shadow"}
case core == "flex-1" || core == "flex-auto" || core == "flex-none" || core == "flex-initial":
return []string{"flex-size", "flex-grow", "flex-shrink", "flex-basis"}
case core == "grow" || strings.HasPrefix(core, "grow-"):
return []string{"flex-grow"}
case core == "shrink" || core == "shrink-0":
return []string{"flex-shrink"}
}
if strings.HasPrefix(core, "size-") {
return []string{"size", "width", "height"}
}
if strings.HasPrefix(core, "w-") {
return []string{"width"}
}
if strings.HasPrefix(core, "h-") {
return []string{"height"}
}
if strings.HasPrefix(core, "p-") && !hasDirectionPrefix(core, "p") {
return []string{"padding", "padding-x", "padding-y", "padding-t", "padding-r", "padding-b", "padding-l", "padding-s", "padding-e"}
}
if g, ok := spaceAxis(core, "p"); ok {
return g
}
if strings.HasPrefix(core, "m-") && !hasDirectionPrefix(core, "m") {
return []string{"margin", "margin-x", "margin-y", "margin-t", "margin-r", "margin-b", "margin-l", "margin-s", "margin-e"}
}
if g, ok := spaceAxis(core, "m"); ok {
return g
}
if strings.HasPrefix(core, "bg-") {
return []string{"bg"}
}
if isTextSize(core) {
return []string{"text-size", "leading"}
}
if strings.HasPrefix(core, "text-") {
return []string{"text-color"}
}
if strings.HasPrefix(core, "font-") && isFontWeight(core) {
return []string{"font-weight"}
}
return nil
}
func prefixGroup(core string, prefixes [][2]string) (string, bool) {
for _, pair := range prefixes {
if strings.HasPrefix(core, pair[0]) {
return pair[1], true
}
}
return "", false
}
func hasDirectionPrefix(core, kind string) bool {
for _, dir := range []string{"x-", "y-", "t-", "r-", "b-", "l-", "s-", "e-"} {
if strings.HasPrefix(core, kind+dir) {
return true
}
}
return false
}
func spaceAxis(core, kind string) ([]string, bool) {
switch {
case strings.HasPrefix(core, kind+"x-"):
return []string{kindName(kind) + "-x", kindName(kind) + "-r", kindName(kind) + "-l", kindName(kind) + "-s", kindName(kind) + "-e"}, true
case strings.HasPrefix(core, kind+"y-"):
return []string{kindName(kind) + "-y", kindName(kind) + "-t", kindName(kind) + "-b"}, true
case strings.HasPrefix(core, kind+"t-"):
return []string{kindName(kind) + "-t"}, true
case strings.HasPrefix(core, kind+"r-"):
return []string{kindName(kind) + "-r"}, true
case strings.HasPrefix(core, kind+"b-"):
return []string{kindName(kind) + "-b"}, true
case strings.HasPrefix(core, kind+"l-"):
return []string{kindName(kind) + "-l"}, true
}
return nil, false
}
func kindName(kind string) string {
if kind == "p" {
return "padding"
}
return "margin"
}
func isTextSize(core string) bool {
switch core {
case "text-xs", "text-sm", "text-base", "text-lg", "text-xl", "text-2xl", "text-3xl", "text-4xl", "text-5xl", "text-6xl", "text-7xl", "text-8xl", "text-9xl":
return true
}
if strings.HasPrefix(core, "text-[") {
rest := strings.TrimPrefix(core, "text-[")
if rest == "" {
return false
}
return unicode.IsDigit(rune(rest[0])) || rest[0] == '.'
}
return false
}
func isFontWeight(core string) bool {
switch core {
case "font-thin", "font-extralight", "font-light", "font-normal", "font-medium", "font-semibold", "font-bold", "font-extrabold", "font-black":
return true
}
return false
}
// isNumber: a bare number (2, 0.5) or an arbitrary length ([3px])
func isNumber(s string) bool {
if strings.HasPrefix(s, "[") {
return true
}
if s == "" {
return false
}
for _, c := range s {
if (c < '0' || c > '9') && c != '.' {
return false
}
}
return true
}
// Code generated by @ui8kit/codegen. DO NOT EDIT.
package uiutils
import "strings"
// Tiny attribute-logic helpers used by generated components. One
// implementation per runtime family keeps every default-resolution decision
// table identical across Templ, React, Svelte, and Vue (mirrors expr.ts).
// TrimStr trims surrounding whitespace.
func TrimStr(v string) string { return strings.TrimSpace(v) }
// IsSetStr reports whether the trimmed string is non-empty.
func IsSetStr(v string) bool { return strings.TrimSpace(v) != "" }
// DefaultIfEmpty returns fallback when the trimmed value is empty.
func DefaultIfEmpty(v, fallback string) string {
t := strings.TrimSpace(v)
if t == "" {
return fallback
}
return t
}
// OneOfOr returns the trimmed value when in allowed, otherwise fallback.
func OneOfOr(v, fallback string, allowed ...string) string {
t := strings.TrimSpace(v)
for _, a := range allowed {
if t == a {
return t
}
}
return fallback
}
// OneOfOrLower lowercases before the whitelist check.
func OneOfOrLower(v, fallback string, allowed ...string) string {
return OneOfOr(strings.ToLower(strings.TrimSpace(v)), fallback, allowed...)
}
// MapOr is a decision table: mapping[trim(v)] or fallback.
func MapOr(v string, mapping map[string]string, fallback string) string {
if out, ok := mapping[strings.TrimSpace(v)]; ok {
return out
}
return fallback
}
// MapOrLower lowercases before the table lookup.
func MapOrLower(v string, mapping map[string]string, fallback string) string {
return MapOr(strings.ToLower(strings.TrimSpace(v)), mapping, fallback)
}
// IntMapOr is an integer decision table: mapping[v] or fallback.
func IntMapOr(v int, mapping map[int]string, fallback string) string {
if out, ok := mapping[v]; ok {
return out
}
return fallback
}
// BoolStr stringifies ARIA state: always "true"/"false", never omitted.
func BoolStr(v bool) string {
if v {
return "true"
}
return "false"
}
// OptBoolStr stringifies tri-state ARIA state: "true"/"false" when set, "" when nil (attribute omitted).
func OptBoolStr(v *bool) string {
if v == nil {
return ""
}
return BoolStr(*v)
}
// ConcatTrim concatenates trimmed parts (icon Prefix + Name).
func ConcatTrim(parts ...string) string {
var b strings.Builder
for _, p := range parts {
b.WriteString(strings.TrimSpace(p))
}
return b.String()
}
// If is an eager ternary for value selection in attribute expressions.
func If[T any](cond bool, then, els T) T {
if cond {
return then
}
return els
}
// Code generated by @ui8kit/codegen. DO NOT EDIT.
// Source of truth: src/domain/tags.ts.
package uiutils
import "strings"
// TagGroup restricts which HTML tags a polymorphic primitive may render.
type TagGroup int
const (
TagGroupBox TagGroup = iota
TagGroupText
)
// ResolveTag returns tag when allowed for group, otherwise fallback.
func ResolveTag(tag, fallback string, group TagGroup) string {
t := strings.TrimSpace(strings.ToLower(tag))
if t == "" || !IsAllowedTag(t, group) {
return fallback
}
return t
}
// IsAllowedTag reports whether tag is valid for the group.
func IsAllowedTag(tag string, group TagGroup) bool {
t := strings.TrimSpace(strings.ToLower(tag))
switch group {
case TagGroupBox:
return oneOf(t, "div", "section", "article", "aside", "header", "footer", "main", "nav", "figure", "search", "ul", "ol", "li", "dl", "dt", "dd", "fieldset", "table", "thead", "tbody", "tfoot", "tr", "th", "td", "caption", "colgroup", "col")
case TagGroupText:
return oneOf(t, "p", "span", "h1", "h2", "h3", "h4", "h5", "h6", "blockquote", "figcaption", "pre", "code", "small", "strong", "em", "time", "legend", "del", "ins")
}
return false
}
func oneOf(value string, options ...string) bool {
for _, o := range options {
if value == o {
return true
}
}
return false
}
// Code generated by @ui8kit/codegen. DO NOT EDIT.
// Package uiutils holds shared Go helpers for generated UI8Kit bricks.
package uiutils
import (
"fmt"
"strings"
"github.com/a-h/templ"
)
// Variants groups a base utility chain and keyed variant maps (cva-style).
type Variants struct {
Base string
Keys []string
ByKey map[string]map[string]string
Defaults map[string]string
Compound []map[string]string
}
// Compose merges Base, variant selections, and optional tail classes.
func Compose(v Variants, selection map[string]string, extra ...string) string {
var parts []string
if strings.TrimSpace(v.Base) != "" {
parts = append(parts, strings.TrimSpace(v.Base))
}
for _, key := range v.Keys {
choices, ok := v.ByKey[key]
if !ok {
continue
}
choice := strings.TrimSpace(selection[key])
if choice == "" {
choice = strings.TrimSpace(v.Defaults[key])
}
if choice == "" {
if len(choices) > 0 {
panic(fmt.Sprintf("[Compose] missing default for key %q", key))
}
continue
}
if cls, ok2 := choices[choice]; ok2 {
if strings.TrimSpace(cls) != "" {
parts = append(parts, cls)
}
}
// Unknown choices are silently dropped to avoid leaking typos into
// the DOM as literal class names.
}
for _, c := range v.Compound {
ok := true
for k, want := range c {
if k == "class" {
continue
}
got := strings.TrimSpace(selection[k])
if got == "" {
got = strings.TrimSpace(v.Defaults[k])
}
hit := false
for _, w := range strings.Split(want, "|") {
if w == got {
hit = true
}
}
ok = ok && hit
}
if ok && strings.TrimSpace(c["class"]) != "" {
parts = append(parts, c["class"])
}
}
parts = append(parts, extra...)
return Cn(parts...)
}
// Cn joins class fragments and resolves Tailwind conflicts (last class wins),
// matching the JS `cn` = clsx + tailwind-merge used by HostingPanel kit.
func Cn(classes ...string) string {
return mergeTailwind(classes...)
}
// MergeAttrs merges attribute maps left to right.
func MergeAttrs(parts ...templ.Attributes) templ.Attributes {
out := templ.Attributes{}
for _, attrs := range parts {
for k, v := range attrs {
out[k] = v
}
}
return out
}
// URLAttrs are the attributes whose value is a URL (SafeURL in every runtime).
var URLAttrs = map[string]bool{"href": true, "src": true, "action": true, "formaction": true, "poster": true, "cite": true, "background": true, "xlink:href": true}
// SafeURL returns "" for javascript:, vbscript: and data: URLs (ASCII whitespace/control chars removed, case-insensitive).
func SafeURL(v string) string {
if unsafeURL(v, false) {
return ""
}
return v
}
// SafeImgURL is SafeURL for <img src>: data:image/(png|jpeg|gif|webp|avif|svg+xml) placeholders are allowed.
func SafeImgURL(v string) string {
if unsafeURL(v, true) {
return ""
}
return v
}
func unsafeURL(v string, dataImage bool) bool {
b := make([]byte, 0, len(v))
for i := 0; i < len(v); i++ {
if v[i] > 0x20 {
b = append(b, v[i])
}
}
s := strings.ToLower(string(b))
if dataImage && strings.HasPrefix(s, "data:image/") {
rest := s[len("data:image/"):]
for _, t := range []string{"png", "jpeg", "gif", "webp", "avif", "svg+xml"} {
if strings.HasPrefix(rest, t) && len(rest) > len(t) && (rest[len(t)] == ';' || rest[len(t)] == ',') {
return false
}
}
}
for _, p := range []string{"javascript:", "vbscript:", "data:"} {
if strings.HasPrefix(s, p) {
return true
}
}
return false
}
// HasAttr reports whether the caller's Attrs set name (case-insensitive): Attrs win over the named attribute.
func HasAttr(a templ.Attributes, name string) bool {
for k := range a {
if strings.EqualFold(k, name) {
return true
}
}
return false
}
// RestAttrs is the Attrs map as rendered: unsafe URLs (data:image allowed in <img src> when img) and blank
// optional attributes (blank lists them, lowercase; never value) are dropped.
func RestAttrs(a templ.Attributes, img bool, blank ...string) templ.Attributes {
out := templ.Attributes{}
for k, v := range a {
key := strings.ToLower(k)
if s, ok := v.(string); ok {
if strings.TrimSpace(s) == "" && contains(blank, key) {
continue
}
if s != "" && URLAttrs[key] && unsafeURL(s, img && key == "src") {
continue
}
}
out[k] = v
}
return out
}
func contains(list []string, s string) bool {
for _, x := range list {
if x == s {
return true
}
}
return false
}
// SafeAttrs drops URL attributes with an unsafe URL from an Attrs map.
func SafeAttrs(a templ.Attributes) templ.Attributes {
out := templ.Attributes{}
for k, v := range a {
if s, ok := v.(string); ok && URLAttrs[strings.ToLower(k)] && SafeURL(s) == "" && s != "" {
continue
}
out[k] = v
}
return out
}
// Code generated by @ui8kit/codegen. DO NOT EDIT.
package uiutils
import (
"encoding/json"
"fmt"
)
// VariantRecipe is the JSON shape for *.variants.json (shared with React CVA recipes).
type VariantRecipe struct {
ID string `json:"id"`
Base string `json:"base"`
Keys []string `json:"keys"`
Defaults map[string]string `json:"defaults"`
ByKey map[string]map[string]string `json:"byKey"`
Meta map[string]string `json:"meta,omitempty"`
Compound []map[string]string `json:"compound,omitempty"`
}
// ToVariants converts a recipe into the in-memory CVA map used by Compose.
func (r VariantRecipe) ToVariants() Variants {
return Variants{
Base: r.Base,
Keys: r.Keys,
ByKey: r.ByKey,
Defaults: r.Defaults,
Compound: r.Compound,
}
}
// ParseVariantRecipe unmarshals *.variants.json bytes.
func ParseVariantRecipe(data []byte) (VariantRecipe, error) {
var recipe VariantRecipe
if err := json.Unmarshal(data, &recipe); err != nil {
return VariantRecipe{}, fmt.Errorf("variants JSON: %w", err)
}
if recipe.ByKey == nil {
return VariantRecipe{}, fmt.Errorf("variants JSON: missing byKey")
}
return recipe, nil
}
// MustParseVariantRecipe parses recipe JSON or panics (for generated init blocks).
func MustParseVariantRecipe(data []byte) VariantRecipe {
recipe, err := ParseVariantRecipe(data)
if err != nil {
panic(err)
}
return recipe
}
Point the CLI at this runtime once, then add the item:
npx ui8kit init --yes --framework twig --dir src --registry-url https://registry.buildy.tw/twig --strict-cdnnpx ui8kit add utils{
"name": "ui8kit/twig-kit",
"description": "UI8Kit Twig primitives and compositions (installed by the ui8kit CLI)",
"require": {
"php": ">=8.2",
"twig/twig": "^3.0"
},
"autoload": {
"psr-4": {
"UI8Kit\\Twig\\": "runtime/",
"CodegenX\\Compose\\Twig\\": "compose/",
"CodegenX\\Organisms\\Twig\\": "organisms/"
}
}
}
<?php
// Code generated by packages/kit-compose/src/server-organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
declare(strict_types=1);
namespace CodegenX\Organisms\Twig;
/**
* cn: clsx-joined class fragments with tailwind-merge conflict resolution (the last class of a group wins, and a
* class removes the earlier classes of the groups it overrides: p-2 removes px-4, not the reverse). Port of cn_merge.go.
*/
final class CnMerge
{
public static function merge(array $classes): string
{
$tokens = [];
foreach ($classes as $chunk) {
foreach (preg_split('/\s+/', trim((string) $chunk)) ?: [] as $t) {
if ($t !== '') {
$tokens[] = $t;
}
}
}
$kept = [];
foreach ($tokens as $token) {
[$prefix, $key, $removes] = self::classKey($token);
if ($key !== '') {
$drop = [$key => true];
foreach ($removes as $g) {
$drop[$prefix . $g] = true;
}
$kept = array_values(array_filter($kept, fn ($it) => !isset($drop[$it[1]])));
}
$kept[] = [$token, $key];
}
return implode(' ', array_map(fn ($it) => $it[0], $kept));
}
private static function classKey(string $token): array
{
[$prefix, $core] = self::splitVariant($token);
if ($core === '') {
return ['', '', []];
}
$groups = self::utilityGroups($core);
if (!$groups) {
return [$prefix, '=' . $token, []];
}
return [$prefix, $prefix . $groups[0], array_slice($groups, 1)];
}
private static function splitVariant(string $token): array
{
$depth = 0;
$cut = -1;
$n = strlen($token);
for ($i = 0; $i < $n; $i++) {
$c = $token[$i];
if ($c === '[') {
$depth++;
} elseif ($c === ']') {
if ($depth > 0) {
$depth--;
}
} elseif ($c === ':' && $depth === 0) {
$cut = $i;
}
}
if ($cut === -1) {
return ['', self::noBang($token)];
}
return [substr($token, 0, $cut + 1), self::noBang(substr($token, $cut + 1))];
}
private static function noBang(string $s): string
{
return str_starts_with($s, '!') ? substr($s, 1) : $s;
}
private static function utilityGroups(string $core): array
{
switch ($core) {
case 'block': case 'inline': case 'inline-block': case 'inline-flex': case 'flex': case 'grid': case 'contents': case 'hidden':
return ['display'];
case 'flex-row': case 'flex-col': case 'flex-row-reverse': case 'flex-col-reverse':
return ['flex-direction'];
case 'static': case 'relative': case 'absolute': case 'fixed': case 'sticky':
return ['position'];
case 'isolate': case 'isolation-auto':
return ['isolation'];
}
foreach (['inset-ring', 'ring'] as $kind) {
if ($core === $kind) {
return [$kind . '-width'];
}
if (str_starts_with($core, $kind . '-')) {
$rest = substr($core, strlen($kind) + 1);
return [self::isNumber($rest) ? $kind . '-width' : $kind . '-color'];
}
}
$prefixes = [
['gap-x-', 'gap-x'], ['gap-y-', 'gap-y'], ['items-', 'align-items'], ['justify-', 'justify-content'],
['self-', 'align-self'], ['content-', 'align-content'], ['overflow-x-', 'overflow-x'], ['overflow-y-', 'overflow-y'],
['inset-x-', 'inset-x'], ['inset-y-', 'inset-y'], ['min-w-', 'min-width'], ['min-h-', 'min-height'],
['max-w-', 'max-width'], ['max-h-', 'max-height'], ['shadow-', 'shadow'], ['ring-', 'ring'], ['rounded-', 'rounded'],
['leading-', 'leading'], ['tracking-', 'tracking'], ['opacity-', 'opacity'], ['z-', 'z'], ['top-', 'top'],
['right-', 'right'], ['bottom-', 'bottom'], ['left-', 'left'],
];
foreach ($prefixes as [$p, $g]) {
if (str_starts_with($core, $p)) {
return [$g];
}
}
if (str_starts_with($core, 'gap-')) {
return ['gap', 'gap-x', 'gap-y'];
}
if (str_starts_with($core, 'inset-')) {
return ['inset', 'inset-x', 'inset-y', 'top', 'right', 'bottom', 'left'];
}
if (str_starts_with($core, 'overflow-')) {
return ['overflow', 'overflow-x', 'overflow-y'];
}
if ($core === 'border' || (str_starts_with($core, 'border-') && self::isNumber(substr($core, 7)))) {
return ['border-width', 'border-w-x', 'border-w-y', 'border-w-t', 'border-w-r', 'border-w-b', 'border-w-l', 'border-w-s', 'border-w-e'];
}
if (strlen($core) >= 8 && str_starts_with($core, 'border-') && str_contains('xytrblse', $core[7])
&& (strlen($core) === 8 || ($core[8] === '-' && self::isNumber(substr($core, 9))))) {
$side = $core[7];
if ($side === 'x') {
return ['border-w-x', 'border-w-r', 'border-w-l', 'border-w-s', 'border-w-e'];
}
if ($side === 'y') {
return ['border-w-y', 'border-w-t', 'border-w-b'];
}
return ['border-w-' . $side];
}
if (in_array($core, ['text-left', 'text-center', 'text-right', 'text-justify', 'text-start', 'text-end'], true)) {
return ['text-align'];
}
if ($core === 'rounded') {
return ['rounded'];
}
if ($core === 'shadow' || $core === 'shadow-none') {
return ['shadow'];
}
if (in_array($core, ['flex-1', 'flex-auto', 'flex-none', 'flex-initial'], true)) {
return ['flex-size', 'flex-grow', 'flex-shrink', 'flex-basis'];
}
if ($core === 'grow' || str_starts_with($core, 'grow-')) {
return ['flex-grow'];
}
if ($core === 'shrink' || $core === 'shrink-0') {
return ['flex-shrink'];
}
if (str_starts_with($core, 'size-')) {
return ['size', 'width', 'height'];
}
if (str_starts_with($core, 'w-')) {
return ['width'];
}
if (str_starts_with($core, 'h-')) {
return ['height'];
}
foreach (['p' => 'padding', 'm' => 'margin'] as $kind => $name) {
if (str_starts_with($core, $kind . '-') && !self::hasDirectionPrefix($core, $kind)) {
return [$name, "$name-x", "$name-y", "$name-t", "$name-r", "$name-b", "$name-l", "$name-s", "$name-e"];
}
$axis = self::spaceAxis($core, $kind, $name);
if ($axis) {
return $axis;
}
}
if (str_starts_with($core, 'bg-')) {
return ['bg'];
}
if (self::isTextSize($core)) {
return ['text-size', 'leading'];
}
if (str_starts_with($core, 'text-')) {
return ['text-color'];
}
if (in_array($core, ['font-thin', 'font-extralight', 'font-light', 'font-normal', 'font-medium', 'font-semibold', 'font-bold', 'font-extrabold', 'font-black'], true)) {
return ['font-weight'];
}
return [];
}
private static function hasDirectionPrefix(string $core, string $kind): bool
{
foreach (['x-', 'y-', 't-', 'r-', 'b-', 'l-', 's-', 'e-'] as $d) {
if (str_starts_with($core, $kind . $d)) {
return true;
}
}
return false;
}
private static function spaceAxis(string $core, string $kind, string $n): array
{
if (str_starts_with($core, $kind . 'x-')) {
return ["$n-x", "$n-r", "$n-l", "$n-s", "$n-e"];
}
if (str_starts_with($core, $kind . 'y-')) {
return ["$n-y", "$n-t", "$n-b"];
}
foreach (['t', 'r', 'b', 'l'] as $s) {
if (str_starts_with($core, $kind . $s . '-')) {
return ["$n-$s"];
}
}
return [];
}
private static function isTextSize(string $core): bool
{
if (in_array($core, ['text-xs', 'text-sm', 'text-base', 'text-lg', 'text-xl', 'text-2xl', 'text-3xl', 'text-4xl', 'text-5xl', 'text-6xl', 'text-7xl', 'text-8xl', 'text-9xl'], true)) {
return true;
}
if (str_starts_with($core, 'text-[')) {
$rest = substr($core, 6);
return $rest !== '' && (ctype_digit($rest[0]) || $rest[0] === '.');
}
return false;
}
private static function isNumber(string $s): bool
{
if (str_starts_with($s, '[')) {
return true;
}
return $s !== '' && strspn($s, '0123456789.') === strlen($s);
}
}
<?php
// Code generated by packages/kit-compose/src/server-organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
declare(strict_types=1);
namespace CodegenX\Organisms\Twig;
use Twig\Environment;
use Twig\Extension\AbstractExtension;
use Twig\Loader\FilesystemLoader;
use Twig\TwigFunction;
/**
* The og_* functions (organism templates) of the generated templates. Register it on an Environment whose loader has the package folder
* as a root (templates are included as ui/<brick>/<part>.html.twig and blocks/<organism>.html.twig).
*/
final class OrganismExtension extends AbstractExtension
{
private Runtime $rt;
public function __construct(string $root)
{
$this->rt = new Runtime($root);
}
/** an Environment over the package folder with the extension registered (autoescape html, lenient variables) */
public static function environment(string $root, array $options = []): Environment
{
$env = new Environment(new FilesystemLoader([$root]), $options + ['autoescape' => 'html', 'strict_variables' => false, 'cache' => false]);
$env->addExtension(new self($root));
return $env;
}
public function getFunctions(): array
{
$static = [
'get', 'field', 's', 'text', 'html', 't', 'n', 'i', 'eq', 'lt', 'gt', 'le', 'ge', 'add', 'sub', 'mul', 'div', 'and', 'or',
'coalesce', 'def', 'l', 'len', 'spread', 'str', 'has', 'cnv', 'tpl', 'num', 'money', 'at', 'page_window',
'fit_cols', 'uniq', 'words', 'nbsp', 'nth', 'range', 'max', 'min', 'round', 'count', 'where', 'match', 'pick',
'sum_by', 'first_of', 'max_by', 'css', 'attrs', 'is_set_str', 'default_if_empty', 'map_or', 'int_map_or',
'bool_str', 'concat_trim', 'cn', 'resolve_tag', 'title_tag', 'url', 'srcset', 'style', 'slot', 'markup',
];
$fns = [];
foreach ($static as $name) {
$fns[] = new TwigFunction('og_' . $name, [Runtime::class, lcfirst(str_replace('_', '', ucwords($name, '_')))]);
}
$fns[] = new TwigFunction('og_attr_html', [Runtime::class, 'attrHtml'], ['is_safe' => ['html']]);
$fns[] = new TwigFunction('og_compose', [$this->rt, 'compose']);
$fns[] = new TwigFunction('og_recipe', [$this->rt, 'recipe']);
$fns[] = new TwigFunction('og_preset', [$this->rt, 'preset']);
$fns[] = new TwigFunction('og_lucide', [$this->rt, 'lucide'], ['is_safe' => ['html']]);
return $fns;
}
}
<?php
// Code generated by packages/kit-compose/src/server-organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
declare(strict_types=1);
namespace CodegenX\Organisms\Twig;
/**
* The helpers of the generated templates. Values are the JSON shapes of the TypeScript props (string, int/float,
* bool, null, list, map) and are read with the rules of the TypeScript output: JS truthiness, strict equality,
* String(), clsx + tailwind-merge. Every helper is null-safe, like `?.`. Port of the Go runtime (dyn.go, expr.go,
* utils.go) so all static runtimes print the same DOM.
*/
final class Runtime
{
/** @var array<string, mixed> parsed JSON files (recipes, presets, the Lucide registry) */
private array $json = [];
public function __construct(private readonly string $root)
{
}
public function json(string $path): mixed
{
if (!array_key_exists($path, $this->json)) {
$text = file_get_contents($this->root . '/' . $path);
if ($text === false) {
throw new \RuntimeException("ui8kit: cannot read $path");
}
$this->json[$path] = json_decode($text, true, 512, JSON_THROW_ON_ERROR);
}
return $this->json[$path];
}
// ---------------------------------------------------------------- values
private static function isNum(mixed $v): bool
{
return is_int($v) || is_float($v);
}
/** a path of fields: get(plan, ['price', 'amount']); `length` of a list or a text is its size */
public static function get(mixed $v, array $path): mixed
{
foreach ($path as $k) {
$k = (string) $k;
if (is_array($v)) {
if (array_is_list($v) && ($k === 'length' || ctype_digit($k))) {
if ($k === 'length') {
$v = count($v);
} else {
$v = $v[(int) $k] ?? null;
}
} else {
$v = $v[$k] ?? null;
}
} elseif (is_string($v) && $k === 'length') {
$v = mb_strlen($v);
} else {
return null;
}
}
return $v;
}
/** a field of a brick record (BreadcrumbItem): the JSON key matched without regard to case, as Go json does */
public static function field(mixed $item, string $name, mixed $zero): mixed
{
if (!is_array($item)) {
return $zero;
}
if (array_key_exists($name, $item)) {
return $item[$name] ?? $zero;
}
foreach ($item as $k => $v) {
if (strcasecmp((string) $k, $name) === 0) {
return $v ?? $zero;
}
}
return $zero;
}
/** String(n) of JavaScript for the numbers the views print: 3, 2.5, -1 */
public static function fmtNum(int|float $f): string
{
if (is_int($f)) {
return (string) $f;
}
if (is_nan($f)) {
return 'NaN';
}
if (is_infinite($f)) {
return $f > 0 ? 'Infinity' : '-Infinity';
}
if ($f == floor($f) && abs($f) < 1e21) {
return sprintf('%.0f', $f);
}
return json_encode($f);
}
public static function s(mixed $v): string
{
if ($v === null) {
return '';
}
if (is_string($v)) {
return $v;
}
if (is_bool($v)) {
return $v ? 'true' : 'false';
}
if (self::isNum($v)) {
return self::fmtNum($v);
}
if ($v instanceof \Stringable) {
return (string) $v;
}
return json_encode($v, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}
/** what a text node shows: nothing for null and booleans */
public static function text(mixed $v): string
{
return is_bool($v) ? '' : self::s($v);
}
/**
* the markup an html node prints (printed with |raw, |noescape): the trusted markup ({"__html": "..."}, a TrustedHtml prop) as it
* is; any other value is text, escaped (& < > " ' as entities, like htmlOf of the TypeScript runtimes)
*/
public static function html(mixed $v): string
{
if (is_array($v) && isset($v['__html']) && is_string($v['__html'])) {
return $v['__html'];
}
return strtr(self::text($v), ['&' => '&', '<' => '<', '>' => '>', '"' => '"', "'" => ''']);
}
/**
* a slot prop printed in place (|raw, |noescape): the markup the calling template captured ({"__html": "..."}, made by
* markup()) as it is; any other value (a plain string from a caller) is text, escaped, so a sub-template called directly
* with a string prints no markup of it
*/
public static function slot(mixed $v): string
{
return self::html($v);
}
/** captured markup (a fill of a slot) as a TrustedHtml marker, which slot() prints as it is */
public static function markup(mixed $v): array
{
return ['__html' => $v === null ? '' : (string) $v];
}
// ---------------------------------------------------------------- output safety (assets/ts/safe.ts, test/safety-vectors.json)
/** the named character references the URL check decodes */
public const NAMED_ENTITIES = [
'Tab' => "\t", 'NewLine' => "\n", 'colon' => ':', 'sol' => '/', 'bsol' => '\\', 'lpar' => '(', 'rpar' => ')', 'amp' => '&',
'lt' => '<', 'gt' => '>', 'quot' => '"', 'apos' => "'", 'nbsp' => "\u{00a0}", 'period' => '.', 'comma' => ',', 'excl' => '!',
'num' => '#', 'quest' => '?', 'equals' => '=', 'plus' => '+', 'semi' => ';', 'percnt' => '%', 'lowbar' => '_', 'ast' => '*',
'commat' => '@', 'dollar' => '$', 'Hat' => '^', 'grave' => '`', 'lsqb' => '[', 'rsqb' => ']', 'lcub' => '{', 'rcub' => '}',
'verbar' => '|', 'vert' => '|',
];
public const URL_SCHEMES = ['http', 'https', 'mailto', 'tel'];
public const URL_ATTRS = ['href', 'src', 'action', 'formaction', 'poster', 'cite', 'background', 'data', 'xlink:href'];
public const IMAGE_ATTRS = ['src', 'poster', 'background'];
private static function fromCode(int|float $n): string
{
return $n > 0 && $n <= 0x10FFFF && !($n >= 0xD800 && $n <= 0xDFFF) ? (string) mb_chr((int) $n, 'UTF-8') : "\u{FFFD}";
}
/** character references decoded as a browser would (numeric with or without ;, the named ones of NAMED_ENTITIES), up to 3 rounds */
public static function decodeEntities(string $s): string
{
for ($i = 0; $i < 3 && str_contains($s, '&'); $i++) {
$s = (string) preg_replace_callback('/&(?:#[xX]([0-9a-fA-F]{1,8});?|#([0-9]{1,10});?|([a-zA-Z][a-zA-Z0-9]{0,31});)/u', static function (array $m): string {
if (($m[1] ?? '') !== '') {
return self::fromCode(hexdec($m[1]));
}
if (($m[2] ?? '') !== '') {
return self::fromCode((float) $m[2]);
}
return self::NAMED_ENTITIES[$m[3] ?? ''] ?? $m[0];
}, $s);
}
return $s;
}
private static function compact(string $s): string
{
return (string) preg_replace('/[\x00-\x20\x7F]+/u', '', self::decodeEntities($s));
}
/** true when the URL is allowed: no scheme and not //host, or http(s), mailto, tel; an image also data:image/* */
public static function isSafeUrl(string $v, bool $image = false): bool
{
$k = self::compact($v);
if (preg_match('#^[/\\\\]{2}#', $k) === 1) {
return false;
}
if (preg_match('/^([a-zA-Z][a-zA-Z0-9+.\-]*):/', $k, $m) !== 1) {
// no scheme: a path, unless a ':' comes before any '/' (as written or decoded), as templ.URL
return preg_match('#^[^/]*:#', $k) !== 1 && preg_match('#^[^/]*:#', $v) !== 1;
}
$scheme = strtolower($m[1]);
if ($scheme === 'data') {
return $image && preg_match('#^data:image/(png|jpeg|gif|webp|avif|svg\+xml)[;,]#', strtolower($k)) === 1;
}
return in_array($scheme, self::URL_SCHEMES, true);
}
private static function safeStr(mixed $v): string
{
return is_string($v) ? $v : (self::isNum($v) ? self::fmtNum($v) : '');
}
/** a URL attribute value: the value when allowed, else '' */
public static function url(mixed $v, bool $image = false): string
{
$s = self::safeStr($v);
return self::isSafeUrl($s, $image) ? $s : '';
}
/** the URLs of a srcset, candidate by candidate */
public static function srcsetUrls(string $v): array
{
$s = self::decodeEntities($v);
$out = [];
$n = strlen($s);
$i = 0;
$ws = static fn (string $c): bool => $c === "\t" || $c === "\n" || $c === "\f" || $c === "\r" || $c === ' ';
while ($i < $n) {
while ($i < $n && ($ws($s[$i]) || $s[$i] === ',')) {
$i++;
}
if ($i >= $n) {
break;
}
$j = $i;
while ($j < $n && !$ws($s[$j])) {
$j++;
}
$url = substr($s, $i, $j - $i);
if (preg_match('/,+$/', $url, $cut) === 1) {
$out[] = substr($url, 0, -strlen($cut[0]));
$i = $j;
continue;
}
$out[] = $url;
$depth = 0;
while ($j < $n && ($depth > 0 || $s[$j] !== ',')) {
if ($s[$j] === '(') {
$depth++;
} elseif ($s[$j] === ')') {
$depth = max(0, $depth - 1);
}
$j++;
}
$i = $j + 1;
}
return $out;
}
/** a srcset value: the value when every candidate is an allowed image URL, else '' */
public static function srcset(mixed $v): string
{
$s = self::safeStr($v);
foreach (self::srcsetUrls($s) as $u) {
if (!self::isSafeUrl($u, true)) {
return '';
}
}
return $s;
}
/** a style value: '' when a url(...) is not an image URL or it holds a script form or a CSS escape, else the value */
public static function style(mixed $v): string
{
$s = self::safeStr($v);
$d = self::decodeEntities($s);
$k = strtolower(self::compact($s));
if (str_contains($d, '\\') || preg_match('/expression\(|javascript:|vbscript:|-moz-binding|behavior:/', $k) === 1) {
return '';
}
preg_match_all('/url\(([^)]*)\)?/i', $d, $all);
foreach ($all[1] as $arg) {
$u = (string) preg_replace('/^(["\'])(.*)\1$/s', '$2', trim($arg, " \t\n\r\f\v"));
if (!self::isSafeUrl($u, true)) {
return '';
}
}
return $s;
}
/** a value of an inline style declaration (the css op): kept when plain (numbers, words, %, #, +, -, ., commas, spaces), else '' */
public static function cssValue(mixed $v): string
{
$s = self::safeStr($v);
return preg_match('/^[-+.%#a-zA-Z0-9 ,]*$/', $s) === 1 ? $s : '';
}
/** an attribute name that may be printed: a valid name, not an event handler (on*) */
public static function isSafeAttrName(string $name): bool
{
return preg_match('/^[a-zA-Z_:][-a-zA-Z0-9_:.]*$/', $name) === 1 && preg_match('/^on/i', $name) !== 1;
}
/** the value of attribute $name as it may be printed: URL, srcset and style checked */
public static function attrValue(string $name, mixed $v): mixed
{
$n = strtolower($name);
if ($n === 'srcset' || $n === 'imagesrcset') {
return self::srcset($v);
}
if ($n === 'style') {
return self::style($v);
}
if (in_array($n, self::URL_ATTRS, true)) {
return self::url($v, in_array($n, self::IMAGE_ATTRS, true));
}
return $v;
}
/** JS truthiness: null, false, 0, NaN and '' are false */
public static function t(mixed $v): bool
{
if ($v === null) {
return false;
}
if (is_bool($v)) {
return $v;
}
if (is_string($v)) {
return $v !== '';
}
if (self::isNum($v)) {
return $v != 0 && !is_nan((float) $v);
}
if ($v instanceof \Stringable) {
return (string) $v !== '';
}
return true;
}
/** Number(v) */
public static function n(mixed $v): float
{
if (self::isNum($v)) {
return (float) $v;
}
if (is_string($v) && is_numeric(trim($v))) {
return (float) trim($v);
}
if (is_bool($v)) {
return $v ? 1.0 : 0.0;
}
return 0.0;
}
/** an int for an int prop of a brick */
public static function i(mixed $v): int
{
return (int) round(self::n($v));
}
/** strict equality (===) */
public static function eq(mixed $a, mixed $b): bool
{
$na = self::isNum($a);
$nb = self::isNum($b);
if ($na || $nb) {
return $na && $nb && (float) $a == (float) $b;
}
if ($a === null || is_string($a) || is_bool($a)) {
return $a === $b;
}
return false;
}
private static function cmp(mixed $a, mixed $b): ?int
{
if (is_string($a) && is_string($b)) {
return strcmp($a, $b) <=> 0;
}
if ($a === null || $b === null) {
return null;
}
return self::n($a) <=> self::n($b);
}
public static function lt(mixed $a, mixed $b): bool { $c = self::cmp($a, $b); return $c !== null && $c < 0; }
public static function gt(mixed $a, mixed $b): bool { $c = self::cmp($a, $b); return $c !== null && $c > 0; }
public static function le(mixed $a, mixed $b): bool { $c = self::cmp($a, $b); return $c !== null && $c <= 0; }
public static function ge(mixed $a, mixed $b): bool { $c = self::cmp($a, $b); return $c !== null && $c >= 0; }
/** `a + b`: text when either side is text, else a sum */
public static function add(mixed $a, mixed $b): string|float
{
if (is_string($a) || is_string($b)) {
return self::s($a) . self::s($b);
}
return self::n($a) + self::n($b);
}
public static function sub(mixed $a, mixed $b): float { return self::n($a) - self::n($b); }
public static function mul(mixed $a, mixed $b): float { return self::n($a) * self::n($b); }
public static function div(mixed $a, mixed $b): float { return fdiv(self::n($a), self::n($b)); }
/** the first falsy operand, else the last (JS &&) */
public static function and(array $vs): mixed
{
$last = null;
foreach ($vs as $v) {
if (!self::t($v)) {
return $v;
}
$last = $v;
}
return $last;
}
/** the first truthy operand, else the last (JS ||) */
public static function or(array $vs): mixed
{
$last = null;
foreach ($vs as $v) {
if (self::t($v)) {
return $v;
}
$last = $v;
}
return $last;
}
public static function coalesce(array $vs): mixed
{
foreach ($vs as $v) {
if ($v !== null) {
return $v;
}
}
return null;
}
/** a prop with its default: the default when the prop is null */
public static function def(mixed $v, mixed $d): mixed
{
return $v ?? $d;
}
/** a list to loop over; null and other values are empty */
public static function l(mixed $v): array
{
return is_array($v) && array_is_list($v) ? $v : [];
}
public static function len(mixed $v): int
{
if (is_string($v)) {
return mb_strlen($v);
}
return count(self::l($v));
}
/** a literal group with the fields of a named group first (`{ ...BASE, mode: "two" }`) */
public static function spread(mixed $base, array $fields): array
{
$out = is_array($base) && !array_is_list($base) ? $base : [];
foreach ($fields as $k => $v) {
$out[$k] = $v;
}
return $out;
}
/** String(x) with undefined kept undefined */
public static function str(mixed $v): ?string
{
return $v === null ? null : self::s($v);
}
public static function has(mixed $v): bool
{
return $v !== null;
}
/** cn over values: clsx skips the falsy ones, tailwind-merge resolves conflicts */
public static function cnv(array $vs): string
{
$parts = [];
foreach ($vs as $v) {
if (self::t($v)) {
$parts[] = self::s($v);
}
}
return CnMerge::merge($parts);
}
/** {0}, {1}... of a content template */
public static function tpl(mixed $t, array $vals): string
{
return preg_replace_callback('/\{(\d+)\}/', fn ($m) => (int) $m[1] < count($vals) ? self::s($vals[(int) $m[1]]) : '', self::s($t));
}
private static function group(float $f, int $decimals): string
{
$s = number_format(abs($f), $decimals, '.', '');
[$int, $frac] = array_pad(explode('.', $s, 2), 2, '');
$out = '';
$n = strlen($int);
for ($i = 0; $i < $n; $i++) {
if ($i > 0 && ($n - $i) % 3 === 0) {
$out .= ',';
}
$out .= $int[$i];
}
$frac = rtrim($frac, '0');
if ($frac !== '') {
$out .= '.' . $frac;
}
if ($f < 0 && $out !== '0') {
$out = '-' . $out;
}
return $out;
}
/** Intl.NumberFormat("en-US"): grouped, up to 3 decimals */
public static function num(mixed $v): string
{
return self::group(self::n($v), 3);
}
private const CURRENCY = ['USD' => '$', 'EUR' => "\u{20AC}", 'GBP' => "\u{00A3}", 'JPY' => "\u{00A5}", 'INR' => "\u{20B9}", 'CAD' => 'CA$', 'AUD' => 'A$'];
/** digits of the minor unit (ISO 4217): 2, or 0 for JPY and KRW */
public static function minorDigits(string $c): int
{
return in_array($c, ['JPY', 'KRW'], true) ? 0 : 2;
}
/** integer minor units (Codex v0.4: 1250 = 12.50) -> "$12.50"; whole amounts without the fraction: 149900 -> "$1,499" */
public static function money(mixed $amount, mixed $currency): string
{
$c = self::s($currency);
$sym = self::CURRENCY[$c] ?? $c . "\u{00A0}";
$minor = (int) round(self::n($amount));
$sign = $minor < 0 ? '-' : '';
$minor = abs($minor);
$d = self::minorDigits($c);
$unit = 10 ** $d;
$whole = intdiv($minor, $unit);
$rest = $minor % $unit;
$out = $sign . $sym . self::group((float) $whole, 0);
return $d > 0 && $rest !== 0 ? $out . '.' . str_pad((string) $rest, $d, '0', STR_PAD_LEFT) : $out;
}
/** a content word by key, the key itself when the dictionary has no entry */
public static function at(mixed $dict, mixed $key): string
{
$v = self::get($dict, [self::s($key)]);
return $v !== null ? self::s($v) : self::s($key);
}
/** the pages a pager shows: the first, the last and the neighbours of the current one; null is a gap */
public static function pageWindow(mixed $pageV, mixed $pagesV): array
{
$page = (int) self::n($pageV);
$pages = (int) self::n($pagesV);
$keep = [];
foreach ([1, $pages, $page - 1, $page, $page + 1] as $n) {
if ($n >= 1 && $n <= $pages) {
$keep[$n] = true;
}
}
$out = [];
$prev = 0;
for ($n = 1; $n <= $pages; $n++) {
if (!isset($keep[$n])) {
continue;
}
if ($n - $prev > 1) {
$out[] = null;
}
$out[] = $n;
$prev = $n;
}
return $out;
}
/** a responsive column variant capped by the number of items: ("1-4", 3) -> "1-3" */
public static function fitCols(mixed $colsV, mixed $nV): string
{
$cols = self::s($colsV);
$n = (int) self::n($nV);
if (!preg_match('/^(-?\d+)-(-?\d+)$/', $cols, $m)) {
return $cols;
}
[$l, $h] = [(int) $m[1], (int) $m[2]];
if ($n >= $h) {
return $cols;
}
$top = max($l, $n);
$known = ['1-2', '1-3', '1-4', '2-3', '2-4', '2-6', '3-6'];
for ($k = $top; $k > $l; $k--) {
if (in_array("$l-$k", $known, true)) {
return "$l-$k";
}
}
return (string) min(max($n, 1), $l);
}
/** drops a segment of a ", " label equal (case-insensitive) to the one before it */
public static function uniq(mixed $v): string
{
$parts = explode(', ', self::s($v));
$out = [];
foreach ($parts as $i => $s) {
if ($i === 0 || strcasecmp($s, $parts[$i - 1]) !== 0) {
$out[] = $s;
}
}
return implode(', ', $out);
}
public static function words(mixed $v): array
{
return explode(' ', self::s($v));
}
public static function nbsp(mixed $v): string
{
return str_replace(' ', "\u{00A0}", self::s($v));
}
public static function nth(mixed $list, mixed $i): mixed
{
$l = self::l($list);
$n = (int) self::n($i);
return $n >= 0 && $n < count($l) ? $l[$n] : null;
}
public static function range(mixed $n): array
{
$c = (int) self::n($n);
return $c > 0 ? range(0, $c - 1) : [];
}
public static function max(array $vs): float
{
$m = -INF;
foreach ($vs as $v) {
$m = max($m, self::n($v));
}
return $m;
}
public static function min(array $vs): float
{
$m = INF;
foreach ($vs as $v) {
$m = min($m, self::n($v));
}
return $m;
}
/** Math.round (halves up) */
public static function round(mixed $v): float
{
return floor(self::n($v) + 0.5);
}
public static function count(mixed $items, mixed $field): int
{
$n = 0;
foreach (self::l($items) as $it) {
if (self::t(self::get($it, [self::s($field)]))) {
$n++;
}
}
return $n;
}
public static function where(mixed $items, mixed $field, mixed $value): array
{
if (!self::t($value)) {
return self::l($items);
}
return array_values(array_filter(self::l($items), fn ($it) => self::eq(self::get($it, [self::s($field)]), $value)));
}
public static function match(mixed $items, mixed $field, mixed $query): array
{
if (!self::t($query)) {
return self::l($items);
}
$q = mb_strtolower(self::s($query));
return array_values(array_filter(self::l($items), fn ($it) => str_contains(mb_strtolower(self::s(self::get($it, [self::s($field)]))), $q)));
}
public static function pick(mixed $items, mixed $id): mixed
{
foreach (self::l($items) as $it) {
if (self::eq(self::get($it, ['id']), $id)) {
return $it;
}
}
return null;
}
public static function sumBy(mixed $items, string $a, string $b): float
{
$s = 0.0;
foreach (self::l($items) as $it) {
$s += self::n(self::get($it, [$a])) * self::n(self::get($it, [$b]));
}
return $s;
}
public static function firstOf(mixed $items, string $field): mixed
{
$l = self::l($items);
return $l ? (self::get($l[0], [$field]) ?? '') : '';
}
public static function maxBy(mixed $items, string $field): float
{
$m = 0.0;
foreach (self::l($items) as $it) {
$m = max($m, self::n(self::get($it, [$field])));
}
return $m;
}
/** an inline style from (property, value, unit) triples */
public static function css(array $triples): string
{
$parts = [];
for ($i = 0; $i + 2 < count($triples); $i += 3) {
$parts[] = self::s($triples[$i]) . ':' . self::cssValue($triples[$i + 1]) . self::s($triples[$i + 2]);
}
return implode(';', $parts);
}
/** the class string of a recipe table for a selection (organisms: base, each key, the matching compounds) */
public function recipe(string $path, array $sel): string
{
$r = $this->json($path);
$pick = function (string $k) use ($r, $sel): string {
$v = trim(self::s($sel[$k] ?? null));
return $v !== '' ? $v : trim((string) ($r['defaults'][$k] ?? ''));
};
$parts = [(string) ($r['base'] ?? '')];
foreach ($r['keys'] ?? [] as $k) {
$parts[] = (string) ($r['byKey'][$k][$pick($k)] ?? '');
}
foreach ($r['compound'] ?? [] as $c) {
if (self::compoundHits($c, $pick)) {
$parts[] = (string) ($c['class'] ?? '');
}
}
return CnMerge::merge(array_filter(array_map('trim', $parts), fn ($p) => $p !== ''));
}
private static function compoundHits(array $c, callable $pick): bool
{
foreach ($c as $k => $want) {
if ($k === 'class') {
continue;
}
if (!in_array($pick((string) $k), explode('|', (string) $want), true)) {
return false;
}
}
return true;
}
/** a preset value of the kit */
public function preset(string $path, array $keys): mixed
{
return self::get(self::get($this->json($path), ['values']), $keys);
}
/** free DOM attributes from (name, value) pairs, as React prints them */
public static function attrs(array $kv): array
{
$out = [];
for ($i = 0; $i + 1 < count($kv); $i += 2) {
$k = self::s($kv[$i]);
$v = $kv[$i + 1];
if ($v === null || !self::isSafeAttrName($k)) {
continue;
}
if (!is_bool($v)) {
$v = self::attrValue($k, $v);
}
if (is_bool($v)) {
if (str_starts_with($k, 'data-') || str_starts_with($k, 'aria-')) {
$out[$k] = self::s($v);
} elseif ($v) {
$out[$k] = true;
}
continue;
}
$out[$k] = self::s($v);
}
return $out;
}
/** an attribute map as markup (` name="value"`, a bare name for true, nothing for null and false) */
public static function attrHtml(mixed $attrs): string
{
if (!is_array($attrs)) {
return '';
}
$out = '';
foreach ($attrs as $k => $v) {
if ($v === null || $v === false || !self::isSafeAttrName((string) $k)) {
continue;
}
$name = (string) $k;
$out .= $v === true ? " $name" : " $name=\"" . htmlspecialchars(self::s(self::attrValue($name, $v)), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '"';
}
return $out;
}
// ---------------------------------------------------------------- bricks (expr.go, utils.go, tags.go)
public static function isSetStr(mixed $v): bool
{
return trim(self::s($v)) !== '';
}
public static function defaultIfEmpty(mixed $v, string $fallback): string
{
$t = trim(self::s($v));
return $t === '' ? $fallback : $t;
}
/** a decision table over a trimmed text: mapping[trim(v)] or the fallback */
public static function mapOr(mixed $v, array $mapping, string $fallback, bool $lower = false): string
{
$t = trim(self::s($v));
if ($lower) {
$t = strtolower($t);
}
return array_key_exists($t, $mapping) ? (string) $mapping[$t] : $fallback;
}
public static function intMapOr(mixed $v, array $mapping, string $fallback): string
{
$n = self::i($v);
return array_key_exists($n, $mapping) ? (string) $mapping[$n] : $fallback;
}
public static function boolStr(mixed $v): string
{
return self::t($v) ? 'true' : 'false';
}
public static function concatTrim(array $parts): string
{
return implode('', array_map(fn ($p) => trim(self::s($p)), $parts));
}
/** class fragments merged with tailwind-merge (strings only, empty ones skipped) */
public static function cn(array $parts): string
{
return CnMerge::merge(array_map(fn ($p) => self::s($p), $parts));
}
/** the brick class contract: recipe base, the selected variants (defaults for empty), compounds, then the tail */
public function compose(string $path, array $selection, array $extra): string
{
$r = $this->json($path);
$parts = [];
if (trim((string) ($r['base'] ?? '')) !== '') {
$parts[] = trim((string) $r['base']);
}
$pick = function (string $k) use ($r, $selection): string {
$c = trim(self::s($selection[$k] ?? null));
return $c !== '' ? $c : trim((string) ($r['defaults'][$k] ?? ''));
};
foreach ($r['keys'] ?? [] as $key) {
$choices = $r['byKey'][$key] ?? null;
if ($choices === null) {
continue;
}
$choice = $pick($key);
if ($choice === '') {
if ($choices) {
throw new \RuntimeException("[compose] missing default for key $key");
}
continue;
}
if (isset($choices[$choice]) && trim((string) $choices[$choice]) !== '') {
$parts[] = (string) $choices[$choice];
}
}
foreach ($r['compound'] ?? [] as $c) {
if (self::compoundHits($c, $pick) && trim((string) ($c['class'] ?? '')) !== '') {
$parts[] = (string) $c['class'];
}
}
return self::cn([...$parts, ...$extra]);
}
/** the tag of a primitive: the requested one when the allow-list has it, else the fallback */
public static function resolveTag(mixed $tag, string $fallback, array $allowed): string
{
$t = strtolower(trim(self::s($tag)));
return $t !== '' && in_array($t, $allowed, true) ? $t : $fallback;
}
/** h1-h6 from a level, h2 by default */
public static function titleTag(mixed $level): string
{
$n = self::i($level);
return $n >= 1 && $n <= 6 ? "h$n" : 'h2';
}
/** the inner markup of a Lucide glyph: its nodes with attributes in name order (circle for an unknown name) */
public function lucide(mixed $name): string
{
$icons = $this->json('icons/lucide-icons.json')['icons'];
$nodes = $icons[self::s($name)] ?? $icons['circle'];
$out = '';
foreach ($nodes as [$tag, $attrs]) {
ksort($attrs, SORT_STRING);
$out .= '<' . $tag;
foreach ($attrs as $k => $v) {
$out .= ' ' . $k . '="' . htmlspecialchars((string) $v, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '"';
}
$out .= '></' . $tag . '>';
}
return $out;
}
}
<?php
// Code generated by @ui8kit/codegen. DO NOT EDIT.
declare(strict_types=1);
namespace UI8Kit\Twig;
/**
* Class contracts of every primitive. Recipes are the shared *.variants.json
* files, inlined verbatim; merge order and tailwind-merge semantics match cn()
* in the TS runtimes and Cn/Compose in Go.
*/
final class Classes
{
public const RECIPES = [
'icon' => [
'base' => 'inline-flex shrink-0 items-center justify-center',
'byKey' => [
'size' => [
'xs' => 'size-3',
'sm' => 'size-4',
'md' => 'size-5',
'lg' => 'size-6',
'xl' => 'size-8',
],
],
'defaults' => [
'size' => 'sm',
],
'id' => 'ui.icon',
'keys' => [
'size',
],
],
];
/**
* Box classes without rendering — the asChild replacement for custom roots.
*
* @param array{class?: string, tag?: string} $p
*/
public static function boxClasses(array $p = []): string
{
return Rt::cn([($p['class'] ?? '')]);
}
/**
* Text classes without rendering — the asChild replacement for custom roots.
*
* @param array{class?: string, tag?: string} $p
*/
public static function textClasses(array $p = []): string
{
return Rt::cn([($p['class'] ?? '')]);
}
/**
* Button classes without rendering — the asChild replacement for custom roots.
*
* @param array{class?: string, type?: string, form?: string, href?: string, disabled?: bool, pressed?: bool, expanded?: bool, ariaLabel?: string, ariaPressed?: string, ariaExpanded?: string, ariaControls?: string} $p
*/
public static function buttonClasses(array $p = []): string
{
return Rt::cn([($p['class'] ?? '')]);
}
/**
* Link classes without rendering — the asChild replacement for custom roots.
*
* @param array{class?: string, href?: string, target?: string, rel?: string, external?: bool, download?: string, ariaCurrent?: string, ariaLabel?: string} $p
*/
public static function linkClasses(array $p = []): string
{
return Rt::cn([($p['class'] ?? '')]);
}
/**
* Label classes without rendering — the asChild replacement for custom roots.
*
* @param array{class?: string, htmlFor?: string} $p
*/
public static function labelClasses(array $p = []): string
{
return Rt::cn([($p['class'] ?? '')]);
}
/**
* Form classes without rendering — the asChild replacement for custom roots.
*
* @param array{class?: string, id?: string, name?: string, action?: string, method?: string, encType?: string, noValidate?: bool, autoComplete?: string, target?: string, ariaLabel?: string, ariaLabelledBy?: string, ariaDescribedBy?: string} $p
*/
public static function formClasses(array $p = []): string
{
return Rt::cn([($p['class'] ?? '')]);
}
/**
* Input classes without rendering — the asChild replacement for custom roots.
*
* @param array{class?: string, type?: string, id?: string, name?: string, value?: string, placeholder?: string, min?: string, max?: string, step?: string, required?: bool, disabled?: bool, readOnly?: bool, ariaInvalid?: string, ariaDescribedBy?: string} $p
*/
public static function inputClasses(array $p = []): string
{
return Rt::cn([($p['class'] ?? '')]);
}
/**
* Textarea classes without rendering — the asChild replacement for custom roots.
*
* @param array{class?: string, id?: string, name?: string, value?: string, placeholder?: string, rows?: string, required?: bool, disabled?: bool, readOnly?: bool, ariaInvalid?: string, ariaDescribedBy?: string} $p
*/
public static function textareaClasses(array $p = []): string
{
return Rt::cn([($p['class'] ?? '')]);
}
/**
* Select classes without rendering — the asChild replacement for custom roots.
*
* @param array{class?: string, id?: string, name?: string, value?: string, multiple?: bool, required?: bool, disabled?: bool, ariaInvalid?: string, ariaDescribedBy?: string} $p
*/
public static function selectClasses(array $p = []): string
{
return Rt::cn(['pr-2', ($p['class'] ?? '')]);
}
/**
* Checkbox classes without rendering — the asChild replacement for custom roots.
*
* @param array{class?: string, id?: string, name?: string, value?: string, checked?: bool, required?: bool, disabled?: bool, ariaInvalid?: string, ariaDescribedBy?: string} $p
*/
public static function checkboxClasses(array $p = []): string
{
return Rt::cn([($p['class'] ?? '')]);
}
/**
* Radio classes without rendering — the asChild replacement for custom roots.
*
* @param array{class?: string, id?: string, name?: string, value?: string, checked?: bool, required?: bool, disabled?: bool, ariaInvalid?: string, ariaDescribedBy?: string} $p
*/
public static function radioClasses(array $p = []): string
{
return Rt::cn([($p['class'] ?? '')]);
}
/**
* Switch classes without rendering — the asChild replacement for custom roots.
*
* @param array{class?: string, checked?: bool, disabled?: bool, id?: string, name?: string, value?: string, ariaLabel?: string, ariaLabelledBy?: string} $p
*/
public static function switchClasses(array $p = []): string
{
return Rt::cn([($p['class'] ?? '')]);
}
/**
* Image classes without rendering — the asChild replacement for custom roots.
*
* @param array{class?: string, src?: string, alt?: string, srcSet?: string, sizes?: string, width?: string, height?: string, loading?: string, decoding?: string} $p
*/
public static function imageClasses(array $p = []): string
{
return Rt::cn([($p['class'] ?? '')]);
}
/**
* Picture classes without rendering — the asChild replacement for custom roots.
*
* @param array{class?: string} $p
*/
public static function pictureClasses(array $p = []): string
{
return Rt::cn([($p['class'] ?? '')]);
}
/**
* Icon classes without rendering — the asChild replacement for custom roots.
*
* @param array{size?: string, class?: string, label?: string} $p
*/
public static function iconClasses(array $p = []): string
{
return Rt::compose(self::RECIPES['icon'], ['size' => ($p['size'] ?? '')], [($p['class'] ?? '')]);
}
/**
* Dialog classes without rendering — the asChild replacement for custom roots.
*
* @param array{class?: string, id?: string, open?: bool, ariaLabelledBy?: string, ariaDescribedBy?: string, ariaLabel?: string} $p
*/
public static function dialogClasses(array $p = []): string
{
return Rt::cn([($p['class'] ?? '')]);
}
/**
* Disclosure classes without rendering — the asChild replacement for custom roots.
*
* @param array{class?: string, open?: bool, name?: string} $p
*/
public static function disclosureClasses(array $p = []): string
{
return Rt::cn([($p['class'] ?? '')]);
}
/**
* Summary classes without rendering — the asChild replacement for custom roots.
*
* @param array{class?: string} $p
*/
public static function summaryClasses(array $p = []): string
{
return Rt::cn([($p['class'] ?? '')]);
}
/**
* Meter classes without rendering — the asChild replacement for custom roots.
*
* @param array{class?: string, value?: string, min?: string, max?: string, low?: string, high?: string, optimum?: string, ariaLabel?: string} $p
*/
public static function meterClasses(array $p = []): string
{
return Rt::cn([($p['class'] ?? '')]);
}
/**
* Progress classes without rendering — the asChild replacement for custom roots.
*
* @param array{class?: string, value?: string, max?: string, ariaLabel?: string} $p
*/
public static function progressClasses(array $p = []): string
{
return Rt::cn([($p['class'] ?? '')]);
}
/**
* Separator classes without rendering — the asChild replacement for custom roots.
*
* @param array{class?: string, orientation?: string, decorative?: bool} $p
*/
public static function separatorClasses(array $p = []): string
{
return Rt::cn([($p['class'] ?? '')]);
}
}
<?php
// Code generated by @ui8kit/codegen. DO NOT EDIT.
declare(strict_types=1);
namespace UI8Kit\Twig;
/**
* cn: clsx-joined class fragments with tailwind-merge conflict resolution (the last class of a group wins, and a
* class removes the earlier classes of the groups it overrides: p-2 removes px-4, not the reverse). Port of cn_merge.go.
*/
final class CnMerge
{
public static function merge(array $classes): string
{
$tokens = [];
foreach ($classes as $chunk) {
foreach (preg_split('/\s+/', trim((string) $chunk)) ?: [] as $t) {
if ($t !== '') {
$tokens[] = $t;
}
}
}
$kept = [];
foreach ($tokens as $token) {
[$prefix, $key, $removes] = self::classKey($token);
if ($key !== '') {
$drop = [$key => true];
foreach ($removes as $g) {
$drop[$prefix . $g] = true;
}
$kept = array_values(array_filter($kept, fn ($it) => !isset($drop[$it[1]])));
}
$kept[] = [$token, $key];
}
return implode(' ', array_map(fn ($it) => $it[0], $kept));
}
private static function classKey(string $token): array
{
[$prefix, $core] = self::splitVariant($token);
if ($core === '') {
return ['', '', []];
}
$groups = self::utilityGroups($core);
if (!$groups) {
return [$prefix, '=' . $token, []];
}
return [$prefix, $prefix . $groups[0], array_slice($groups, 1)];
}
private static function splitVariant(string $token): array
{
$depth = 0;
$cut = -1;
$n = strlen($token);
for ($i = 0; $i < $n; $i++) {
$c = $token[$i];
if ($c === '[') {
$depth++;
} elseif ($c === ']') {
if ($depth > 0) {
$depth--;
}
} elseif ($c === ':' && $depth === 0) {
$cut = $i;
}
}
if ($cut === -1) {
return ['', self::noBang($token)];
}
return [substr($token, 0, $cut + 1), self::noBang(substr($token, $cut + 1))];
}
private static function noBang(string $s): string
{
return str_starts_with($s, '!') ? substr($s, 1) : $s;
}
private static function utilityGroups(string $core): array
{
switch ($core) {
case 'block': case 'inline': case 'inline-block': case 'inline-flex': case 'flex': case 'grid': case 'contents': case 'hidden':
return ['display'];
case 'flex-row': case 'flex-col': case 'flex-row-reverse': case 'flex-col-reverse':
return ['flex-direction'];
case 'static': case 'relative': case 'absolute': case 'fixed': case 'sticky':
return ['position'];
case 'isolate': case 'isolation-auto':
return ['isolation'];
case 'object-contain': case 'object-cover': case 'object-fill': case 'object-none': case 'object-scale-down':
return ['object-fit'];
case 'object-bottom': case 'object-center': case 'object-left': case 'object-left-bottom': case 'object-left-top': case 'object-right': case 'object-right-bottom': case 'object-right-top': case 'object-top':
return ['object-position'];
}
if (str_starts_with($core, 'aspect-')) {
return ['aspect'];
}
// ring-offset-N (width) and ring-offset-<color> are their own groups
if (str_starts_with($core, 'ring-offset-')) {
return [self::isNumber(substr($core, 12)) ? 'ring-offset-width' : 'ring-offset-color'];
}
foreach (['inset-ring', 'ring'] as $kind) {
if ($core === $kind) {
return [$kind . '-width'];
}
if (str_starts_with($core, $kind . '-')) {
$rest = substr($core, strlen($kind) + 1);
return [self::isNumber($rest) ? $kind . '-width' : $kind . '-color'];
}
}
$prefixes = [
['gap-x-', 'gap-x'], ['gap-y-', 'gap-y'], ['items-', 'align-items'], ['justify-', 'justify-content'],
['self-', 'align-self'], ['content-', 'align-content'], ['overflow-x-', 'overflow-x'], ['overflow-y-', 'overflow-y'],
['inset-x-', 'inset-x'], ['inset-y-', 'inset-y'], ['min-w-', 'min-width'], ['min-h-', 'min-height'],
['max-w-', 'max-width'], ['max-h-', 'max-height'], ['shadow-', 'shadow'], ['ring-', 'ring'], ['rounded-', 'rounded'],
['leading-', 'leading'], ['tracking-', 'tracking'], ['opacity-', 'opacity'], ['z-', 'z'], ['top-', 'top'],
['right-', 'right'], ['bottom-', 'bottom'], ['left-', 'left'],
];
foreach ($prefixes as [$p, $g]) {
if (str_starts_with($core, $p)) {
return [$g];
}
}
if (str_starts_with($core, 'gap-')) {
return ['gap', 'gap-x', 'gap-y'];
}
if (str_starts_with($core, 'inset-')) {
return ['inset', 'inset-x', 'inset-y', 'top', 'right', 'bottom', 'left'];
}
if (str_starts_with($core, 'overflow-')) {
return ['overflow', 'overflow-x', 'overflow-y'];
}
if ($core === 'border' || (str_starts_with($core, 'border-') && self::isNumber(substr($core, 7)))) {
return ['border-width', 'border-w-x', 'border-w-y', 'border-w-t', 'border-w-r', 'border-w-b', 'border-w-l', 'border-w-s', 'border-w-e'];
}
if (strlen($core) >= 8 && str_starts_with($core, 'border-') && str_contains('xytrblse', $core[7])
&& (strlen($core) === 8 || ($core[8] === '-' && self::isNumber(substr($core, 9))))) {
$side = $core[7];
if ($side === 'x') {
return ['border-w-x', 'border-w-r', 'border-w-l', 'border-w-s', 'border-w-e'];
}
if ($side === 'y') {
return ['border-w-y', 'border-w-t', 'border-w-b'];
}
return ['border-w-' . $side];
}
if (in_array($core, ['text-left', 'text-center', 'text-right', 'text-justify', 'text-start', 'text-end'], true)) {
return ['text-align'];
}
if ($core === 'rounded') {
return ['rounded'];
}
if ($core === 'shadow' || $core === 'shadow-none') {
return ['shadow'];
}
if (in_array($core, ['flex-1', 'flex-auto', 'flex-none', 'flex-initial'], true)) {
return ['flex-size', 'flex-grow', 'flex-shrink', 'flex-basis'];
}
if ($core === 'grow' || str_starts_with($core, 'grow-')) {
return ['flex-grow'];
}
if ($core === 'shrink' || $core === 'shrink-0') {
return ['flex-shrink'];
}
if (str_starts_with($core, 'size-')) {
return ['size', 'width', 'height'];
}
if (str_starts_with($core, 'w-')) {
return ['width'];
}
if (str_starts_with($core, 'h-')) {
return ['height'];
}
foreach (['p' => 'padding', 'm' => 'margin'] as $kind => $name) {
if (str_starts_with($core, $kind . '-') && !self::hasDirectionPrefix($core, $kind)) {
return [$name, "$name-x", "$name-y", "$name-t", "$name-r", "$name-b", "$name-l", "$name-s", "$name-e"];
}
$axis = self::spaceAxis($core, $kind, $name);
if ($axis) {
return $axis;
}
}
if (str_starts_with($core, 'bg-')) {
return ['bg'];
}
if (self::isTextSize($core)) {
return ['text-size', 'leading'];
}
if (str_starts_with($core, 'text-')) {
return ['text-color'];
}
if (in_array($core, ['font-thin', 'font-extralight', 'font-light', 'font-normal', 'font-medium', 'font-semibold', 'font-bold', 'font-extrabold', 'font-black'], true)) {
return ['font-weight'];
}
return [];
}
private static function hasDirectionPrefix(string $core, string $kind): bool
{
foreach (['x-', 'y-', 't-', 'r-', 'b-', 'l-', 's-', 'e-'] as $d) {
if (str_starts_with($core, $kind . $d)) {
return true;
}
}
return false;
}
private static function spaceAxis(string $core, string $kind, string $n): array
{
if (str_starts_with($core, $kind . 'x-')) {
return ["$n-x", "$n-r", "$n-l", "$n-s", "$n-e"];
}
if (str_starts_with($core, $kind . 'y-')) {
return ["$n-y", "$n-t", "$n-b"];
}
foreach (['t', 'r', 'b', 'l'] as $s) {
if (str_starts_with($core, $kind . $s . '-')) {
return ["$n-$s"];
}
}
return [];
}
private static function isTextSize(string $core): bool
{
if (in_array($core, ['text-xs', 'text-sm', 'text-base', 'text-lg', 'text-xl', 'text-2xl', 'text-3xl', 'text-4xl', 'text-5xl', 'text-6xl', 'text-7xl', 'text-8xl', 'text-9xl'], true)) {
return true;
}
if (str_starts_with($core, 'text-[')) {
$rest = substr($core, 6);
return $rest !== '' && (ctype_digit($rest[0]) || $rest[0] === '.');
}
return false;
}
private static function isNumber(string $s): bool
{
if (str_starts_with($s, '[')) {
return true;
}
return $s !== '' && strspn($s, '0123456789.') === strlen($s);
}
}
<?php
// Code generated by @ui8kit/codegen. DO NOT EDIT.
declare(strict_types=1);
namespace UI8Kit\Twig;
/**
* UI8Kit PHP runtime helpers used by the generated Twig and Latte templates.
* One implementation of every decision-table primitive; mirrors
* runtime/go/expr.go + utils.go and runtime/ts/expr.ts so all runtimes
* resolve defaults identically. Variadic Go helpers take arrays here so
* Twig and Latte call them with the same shape.
*/
final class Rt
{
private static function s(mixed $v): string
{
return is_bool($v) ? ($v ? 'true' : 'false') : (string) ($v ?? '');
}
/** cn = clsx join + tailwind-merge conflict resolution (CnMerge, port of cn_merge.go). */
public static function cn(array $classes): string
{
return CnMerge::merge(array_map([self::class, 's'], $classes));
}
/** Omit-if-empty attribute value: blank → null so the attribute is dropped. */
public static function orNull(mixed $v): ?string
{
$s = self::s($v);
return trim($s) === '' ? null : $s;
}
public static function isSetStr(mixed $v): bool
{
return trim(self::s($v)) !== '';
}
public static function defaultIfEmpty(mixed $v, string $fallback): string
{
$t = trim(self::s($v));
return $t === '' ? $fallback : $t;
}
public static function oneOfOr(mixed $v, string $fallback, array $allowed): string
{
$t = trim(self::s($v));
return in_array($t, $allowed, true) ? $t : $fallback;
}
public static function oneOfOrLower(mixed $v, string $fallback, array $allowed): string
{
return self::oneOfOr(strtolower(trim(self::s($v))), $fallback, $allowed);
}
/** Decision table: mapping[trim(v)] ?? fallback. */
public static function mapOr(mixed $v, array $mapping, string $fallback): string
{
$k = trim(self::s($v));
return array_key_exists($k, $mapping) ? (string) $mapping[$k] : $fallback;
}
public static function mapOrLower(mixed $v, array $mapping, string $fallback): string
{
return self::mapOr(strtolower(trim(self::s($v))), $mapping, $fallback);
}
/** Integer decision table: mapping[v] ?? fallback. */
public static function intMapOr(mixed $v, array $mapping, string $fallback): string
{
$k = (int) ($v ?? 0);
return array_key_exists($k, $mapping) ? (string) $mapping[$k] : $fallback;
}
/** ARIA state stringification: always 'true'/'false', never omitted. */
public static function boolStr(mixed $v): string
{
return $v ? 'true' : 'false';
}
/** Tri-state ARIA state: 'true'/'false' when set, '' when null (attribute omitted). */
public static function optBoolStr(mixed $v): string
{
return $v === null ? '' : ($v ? 'true' : 'false');
}
/** Concatenation of trimmed parts (icon Prefix + Name). */
public static function concatTrim(array $parts): string
{
$out = '';
foreach ($parts as $p) {
$out .= trim(self::s($p));
}
return $out;
}
/** Returns tag when allowed for the group, otherwise fallback (tag groups: Tags::GROUPS). */
public static function resolveTag(mixed $tag, string $fallback, string $group): string
{
$t = strtolower(trim(self::s($tag)));
if ($t === '') {
return $fallback;
}
return in_array($t, Tags::GROUPS[$group] ?? [], true) ? $t : $fallback;
}
/**
* Merge recipe base, keyed variant selections, compound variants and tail
* classes (Go Compose). Recipe shape is *.variants.json: base, keys,
* defaults, byKey, compound. Unknown choices are silently dropped.
*/
public static function compose(array $recipe, array $selection, array $extra = []): string
{
$parts = [];
$base = trim((string) ($recipe['base'] ?? ''));
if ($base !== '') {
$parts[] = $base;
}
$pick = static function (string $key) use ($recipe, $selection): string {
$choice = trim(self::s($selection[$key] ?? ''));
return $choice !== '' ? $choice : trim((string) ($recipe['defaults'][$key] ?? ''));
};
foreach (($recipe['keys'] ?? []) as $key) {
$choices = $recipe['byKey'][$key] ?? null;
if ($choices === null) {
continue;
}
$choice = $pick($key);
if ($choice === '') {
if (count($choices) > 0) {
throw new \LogicException("[compose] missing default for key \"$key\"");
}
continue;
}
$cls = $choices[$choice] ?? null;
if ($cls !== null && trim((string) $cls) !== '') {
$parts[] = (string) $cls;
}
}
foreach (($recipe['compound'] ?? []) as $c) {
$ok = true;
foreach ($c as $k => $want) {
if ($k === 'class') {
continue;
}
$ok = $ok && in_array($pick((string) $k), explode('|', (string) $want), true);
}
if ($ok && trim((string) ($c['class'] ?? '')) !== '') {
$parts[] = (string) $c['class'];
}
}
return self::cn([...$parts, ...$extra]);
}
/**
* Attribute string for Twig templates. Computed attrs first, caller
* attrs merged last so the caller wins. null/false omit, true prints a
* bare boolean attribute, everything else stringifies and escapes.
*/
private const URL_ATTRS = ['href', 'src', 'action', 'formaction', 'poster', 'cite', 'background', 'xlink:href'];
/** URL attribute value: '' for javascript:, vbscript: and data: (ASCII whitespace/control chars removed, case-insensitive). */
public static function safeUrl(mixed $v): string
{
$s = self::s($v);
return self::unsafeUrl($s, false) ? '' : $s;
}
private static function unsafeUrl(string $s, bool $dataImage): bool
{
$k = strtolower((string) preg_replace('/[\x00-\x20]/', '', $s));
if ($dataImage && preg_match('#^data:image/(png|jpeg|gif|webp|avif|svg\+xml)[;,]#', $k)) {
return false;
}
return (bool) preg_match('/^(javascript|vbscript|data):/', $k);
}
/** Optional URL attribute: null (omitted) when unset, blank or an unsafe scheme, else the value as given. */
public static function urlOrNull(mixed $v): ?string
{
$s = self::s($v);
return trim($s) === '' || self::unsafeUrl($s, false) ? null : $s;
}
/** urlOrNull for <img src>: data:image/(png|jpeg|gif|webp|avif|svg+xml) placeholders are allowed. */
public static function imgUrlOrNull(mixed $v): ?string
{
$s = self::s($v);
return trim($s) === '' || self::unsafeUrl($s, true) ? null : $s;
}
/** Drops URL attributes with an unsafe URL (kept for callers of 3.2; generated templates use restAttrs). */
public static function safeAttrs(array $attrs): array
{
foreach ($attrs as $name => $value) {
if (is_string($value) && $value !== '' && in_array(strtolower((string) $name), self::URL_ATTRS, true) && self::safeUrl($value) === '') {
unset($attrs[$name]);
}
}
return $attrs;
}
/**
* The caller's attrs as rendered: an unsafe URL (data:image allowed in <img src> when $img) or a blank optional
* attribute ($blank, lowercase names; never value) becomes null. The key stays, so the caller still wins over
* the named attribute of the same name and the attribute is omitted.
*/
public static function restAttrs(array $attrs, bool $img = false, array $blank = []): array
{
foreach ($attrs as $name => $value) {
if (!is_string($value)) {
continue;
}
$key = strtolower((string) $name);
if (trim($value) === '' && in_array($key, $blank, true)) {
$attrs[$name] = null;
} elseif ($value !== '' && in_array($key, self::URL_ATTRS, true) && self::unsafeUrl($value, $img && $key === 'src')) {
$attrs[$name] = null;
}
}
return $attrs;
}
/** Twig attribute string: named attrs, then the caller's attrs (restAttrs) merged last so the caller wins. */
public static function attrs(array $attrs, array $rest = [], bool $img = false, array $blank = []): string
{
$out = '';
foreach (array_merge($attrs, self::restAttrs($rest, $img, $blank)) as $name => $value) {
if ($value === null || $value === false) {
continue;
}
if ($value === true) {
$out .= ' ' . $name;
continue;
}
$out .= ' ' . $name . '="' . htmlspecialchars(self::s($value), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '"';
}
return $out;
}
}
<?php
// Code generated by @ui8kit/codegen. DO NOT EDIT.
// Source of truth: src/domain/tags.ts.
declare(strict_types=1);
namespace UI8Kit\Twig;
/** Allowed tags per semantic group (polymorphic Tag props). */
final class Tags
{
public const GROUPS = [
'Box' => ['div', 'section', 'article', 'aside', 'header', 'footer', 'main', 'nav', 'figure', 'search', 'ul', 'ol', 'li', 'dl', 'dt', 'dd', 'fieldset', 'table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td', 'caption', 'colgroup', 'col'],
'Text' => ['p', 'span', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'figcaption', 'pre', 'code', 'small', 'strong', 'em', 'time', 'legend', 'del', 'ins'],
];
}
<?php
// Code generated by @ui8kit/codegen. DO NOT EDIT.
declare(strict_types=1);
namespace UI8Kit\Twig;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;
/**
* Twig bindings for the UI8Kit runtime — thin delegates to Rt and the
* generated Classes helpers. Register once per environment:
*
* $twig->addExtension(new \UI8Kit\Twig\TwigExtension());
*
* `ui8kit_classes('buttonClasses', {variant: 'outline'})` is the asChild
* replacement: compose a part's classes for a custom root element.
*/
final class TwigExtension extends AbstractExtension
{
public function getFunctions(): array
{
return [
new TwigFunction('ui8kit_attrs', [Rt::class, 'attrs'], ['is_safe' => ['html']]),
new TwigFunction('ui8kit_cn', [Rt::class, 'cn']),
new TwigFunction('ui8kit_or_null', [Rt::class, 'orNull']),
new TwigFunction('ui8kit_is_set_str', [Rt::class, 'isSetStr']),
new TwigFunction('ui8kit_default_if_empty', [Rt::class, 'defaultIfEmpty']),
new TwigFunction('ui8kit_one_of_or', [Rt::class, 'oneOfOr']),
new TwigFunction('ui8kit_one_of_or_lower', [Rt::class, 'oneOfOrLower']),
new TwigFunction('ui8kit_map_or', [Rt::class, 'mapOr']),
new TwigFunction('ui8kit_map_or_lower', [Rt::class, 'mapOrLower']),
new TwigFunction('ui8kit_int_map_or', [Rt::class, 'intMapOr']),
new TwigFunction('ui8kit_bool_str', [Rt::class, 'boolStr']),
new TwigFunction('ui8kit_opt_bool_str', [Rt::class, 'optBoolStr']),
new TwigFunction('ui8kit_concat_trim', [Rt::class, 'concatTrim']),
new TwigFunction('ui8kit_safe_url', [Rt::class, 'safeUrl']),
new TwigFunction('ui8kit_url_or_null', [Rt::class, 'urlOrNull']),
new TwigFunction('ui8kit_img_url_or_null', [Rt::class, 'imgUrlOrNull']),
new TwigFunction('ui8kit_resolve_tag', [Rt::class, 'resolveTag']),
new TwigFunction('ui8kit_classes', static fn (string $method, array $props = []): string => \call_user_func([Classes::class, $method], $props)),
];
}
}
Point the CLI at this runtime once, then add the item:
npx ui8kit init --yes --framework latte --dir src --registry-url https://registry.buildy.tw/latte --strict-cdnnpx ui8kit add utils{
"name": "ui8kit/latte-kit",
"description": "UI8Kit Latte primitives and compositions (installed by the ui8kit CLI)",
"require": {
"php": ">=8.2",
"latte/latte": "^3.0"
},
"autoload": {
"psr-4": {
"UI8Kit\\Latte\\": "runtime/",
"CodegenX\\Compose\\Latte\\": "compose/",
"CodegenX\\Organisms\\Latte\\": "organisms/"
}
}
}
<?php
// Code generated by packages/kit-compose/src/server-organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
declare(strict_types=1);
namespace CodegenX\Organisms\Latte;
/**
* cn: clsx-joined class fragments with tailwind-merge conflict resolution (the last class of a group wins, and a
* class removes the earlier classes of the groups it overrides: p-2 removes px-4, not the reverse). Port of cn_merge.go.
*/
final class CnMerge
{
public static function merge(array $classes): string
{
$tokens = [];
foreach ($classes as $chunk) {
foreach (preg_split('/\s+/', trim((string) $chunk)) ?: [] as $t) {
if ($t !== '') {
$tokens[] = $t;
}
}
}
$kept = [];
foreach ($tokens as $token) {
[$prefix, $key, $removes] = self::classKey($token);
if ($key !== '') {
$drop = [$key => true];
foreach ($removes as $g) {
$drop[$prefix . $g] = true;
}
$kept = array_values(array_filter($kept, fn ($it) => !isset($drop[$it[1]])));
}
$kept[] = [$token, $key];
}
return implode(' ', array_map(fn ($it) => $it[0], $kept));
}
private static function classKey(string $token): array
{
[$prefix, $core] = self::splitVariant($token);
if ($core === '') {
return ['', '', []];
}
$groups = self::utilityGroups($core);
if (!$groups) {
return [$prefix, '=' . $token, []];
}
return [$prefix, $prefix . $groups[0], array_slice($groups, 1)];
}
private static function splitVariant(string $token): array
{
$depth = 0;
$cut = -1;
$n = strlen($token);
for ($i = 0; $i < $n; $i++) {
$c = $token[$i];
if ($c === '[') {
$depth++;
} elseif ($c === ']') {
if ($depth > 0) {
$depth--;
}
} elseif ($c === ':' && $depth === 0) {
$cut = $i;
}
}
if ($cut === -1) {
return ['', self::noBang($token)];
}
return [substr($token, 0, $cut + 1), self::noBang(substr($token, $cut + 1))];
}
private static function noBang(string $s): string
{
return str_starts_with($s, '!') ? substr($s, 1) : $s;
}
private static function utilityGroups(string $core): array
{
switch ($core) {
case 'block': case 'inline': case 'inline-block': case 'inline-flex': case 'flex': case 'grid': case 'contents': case 'hidden':
return ['display'];
case 'flex-row': case 'flex-col': case 'flex-row-reverse': case 'flex-col-reverse':
return ['flex-direction'];
case 'static': case 'relative': case 'absolute': case 'fixed': case 'sticky':
return ['position'];
case 'isolate': case 'isolation-auto':
return ['isolation'];
}
foreach (['inset-ring', 'ring'] as $kind) {
if ($core === $kind) {
return [$kind . '-width'];
}
if (str_starts_with($core, $kind . '-')) {
$rest = substr($core, strlen($kind) + 1);
return [self::isNumber($rest) ? $kind . '-width' : $kind . '-color'];
}
}
$prefixes = [
['gap-x-', 'gap-x'], ['gap-y-', 'gap-y'], ['items-', 'align-items'], ['justify-', 'justify-content'],
['self-', 'align-self'], ['content-', 'align-content'], ['overflow-x-', 'overflow-x'], ['overflow-y-', 'overflow-y'],
['inset-x-', 'inset-x'], ['inset-y-', 'inset-y'], ['min-w-', 'min-width'], ['min-h-', 'min-height'],
['max-w-', 'max-width'], ['max-h-', 'max-height'], ['shadow-', 'shadow'], ['ring-', 'ring'], ['rounded-', 'rounded'],
['leading-', 'leading'], ['tracking-', 'tracking'], ['opacity-', 'opacity'], ['z-', 'z'], ['top-', 'top'],
['right-', 'right'], ['bottom-', 'bottom'], ['left-', 'left'],
];
foreach ($prefixes as [$p, $g]) {
if (str_starts_with($core, $p)) {
return [$g];
}
}
if (str_starts_with($core, 'gap-')) {
return ['gap', 'gap-x', 'gap-y'];
}
if (str_starts_with($core, 'inset-')) {
return ['inset', 'inset-x', 'inset-y', 'top', 'right', 'bottom', 'left'];
}
if (str_starts_with($core, 'overflow-')) {
return ['overflow', 'overflow-x', 'overflow-y'];
}
if ($core === 'border' || (str_starts_with($core, 'border-') && self::isNumber(substr($core, 7)))) {
return ['border-width', 'border-w-x', 'border-w-y', 'border-w-t', 'border-w-r', 'border-w-b', 'border-w-l', 'border-w-s', 'border-w-e'];
}
if (strlen($core) >= 8 && str_starts_with($core, 'border-') && str_contains('xytrblse', $core[7])
&& (strlen($core) === 8 || ($core[8] === '-' && self::isNumber(substr($core, 9))))) {
$side = $core[7];
if ($side === 'x') {
return ['border-w-x', 'border-w-r', 'border-w-l', 'border-w-s', 'border-w-e'];
}
if ($side === 'y') {
return ['border-w-y', 'border-w-t', 'border-w-b'];
}
return ['border-w-' . $side];
}
if (in_array($core, ['text-left', 'text-center', 'text-right', 'text-justify', 'text-start', 'text-end'], true)) {
return ['text-align'];
}
if ($core === 'rounded') {
return ['rounded'];
}
if ($core === 'shadow' || $core === 'shadow-none') {
return ['shadow'];
}
if (in_array($core, ['flex-1', 'flex-auto', 'flex-none', 'flex-initial'], true)) {
return ['flex-size', 'flex-grow', 'flex-shrink', 'flex-basis'];
}
if ($core === 'grow' || str_starts_with($core, 'grow-')) {
return ['flex-grow'];
}
if ($core === 'shrink' || $core === 'shrink-0') {
return ['flex-shrink'];
}
if (str_starts_with($core, 'size-')) {
return ['size', 'width', 'height'];
}
if (str_starts_with($core, 'w-')) {
return ['width'];
}
if (str_starts_with($core, 'h-')) {
return ['height'];
}
foreach (['p' => 'padding', 'm' => 'margin'] as $kind => $name) {
if (str_starts_with($core, $kind . '-') && !self::hasDirectionPrefix($core, $kind)) {
return [$name, "$name-x", "$name-y", "$name-t", "$name-r", "$name-b", "$name-l", "$name-s", "$name-e"];
}
$axis = self::spaceAxis($core, $kind, $name);
if ($axis) {
return $axis;
}
}
if (str_starts_with($core, 'bg-')) {
return ['bg'];
}
if (self::isTextSize($core)) {
return ['text-size', 'leading'];
}
if (str_starts_with($core, 'text-')) {
return ['text-color'];
}
if (in_array($core, ['font-thin', 'font-extralight', 'font-light', 'font-normal', 'font-medium', 'font-semibold', 'font-bold', 'font-extrabold', 'font-black'], true)) {
return ['font-weight'];
}
return [];
}
private static function hasDirectionPrefix(string $core, string $kind): bool
{
foreach (['x-', 'y-', 't-', 'r-', 'b-', 'l-', 's-', 'e-'] as $d) {
if (str_starts_with($core, $kind . $d)) {
return true;
}
}
return false;
}
private static function spaceAxis(string $core, string $kind, string $n): array
{
if (str_starts_with($core, $kind . 'x-')) {
return ["$n-x", "$n-r", "$n-l", "$n-s", "$n-e"];
}
if (str_starts_with($core, $kind . 'y-')) {
return ["$n-y", "$n-t", "$n-b"];
}
foreach (['t', 'r', 'b', 'l'] as $s) {
if (str_starts_with($core, $kind . $s . '-')) {
return ["$n-$s"];
}
}
return [];
}
private static function isTextSize(string $core): bool
{
if (in_array($core, ['text-xs', 'text-sm', 'text-base', 'text-lg', 'text-xl', 'text-2xl', 'text-3xl', 'text-4xl', 'text-5xl', 'text-6xl', 'text-7xl', 'text-8xl', 'text-9xl'], true)) {
return true;
}
if (str_starts_with($core, 'text-[')) {
$rest = substr($core, 6);
return $rest !== '' && (ctype_digit($rest[0]) || $rest[0] === '.');
}
return false;
}
private static function isNumber(string $s): bool
{
if (str_starts_with($s, '[')) {
return true;
}
return $s !== '' && strspn($s, '0123456789.') === strlen($s);
}
}
<?php
// Code generated by packages/kit-compose/src/server-organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
declare(strict_types=1);
namespace CodegenX\Organisms\Latte;
use Latte\Engine;
use Latte\Loaders\FileLoader;
use Latte\Runtime\Html;
/**
* The og_* functions (organism templates) of the generated templates. engine() makes a Latte Engine over the package folder (templates are
* rendered as ui/<brick>/<part>.latte and blocks/<organism>.latte) with the functions registered. og_include renders
* another template with only the given variables and returns its markup.
*/
final class OrganismExtension extends \Latte\Extension
{
private Runtime $rt;
public function __construct(string $root, private readonly Engine $engine)
{
$this->rt = new Runtime($root);
}
/** an Engine over the package folder with the extension added; templates compile to $tempDir when given, else in memory */
public static function engine(string $root, ?string $tempDir = null): Engine
{
$latte = new Engine();
$latte->setLoader(new FileLoader($root));
$latte->setTempDirectory($tempDir);
$latte->addExtension(new self($root, $latte));
return $latte;
}
public function getFunctions(): array
{
$static = [
'get', 'field', 's', 'text', 'html', 't', 'n', 'i', 'eq', 'lt', 'gt', 'le', 'ge', 'add', 'sub', 'mul', 'div', 'and', 'or',
'coalesce', 'def', 'l', 'len', 'spread', 'str', 'has', 'cnv', 'tpl', 'num', 'money', 'at', 'page_window',
'fit_cols', 'uniq', 'words', 'nbsp', 'nth', 'range', 'max', 'min', 'round', 'count', 'where', 'match', 'pick',
'sum_by', 'first_of', 'max_by', 'css', 'attrs', 'is_set_str', 'default_if_empty', 'map_or', 'int_map_or',
'bool_str', 'concat_trim', 'cn', 'resolve_tag', 'title_tag', 'url', 'srcset', 'style', 'slot', 'markup',
];
$fns = [];
foreach ($static as $name) {
$fns['og_' . $name] = [Runtime::class, lcfirst(str_replace('_', '', ucwords($name, '_')))];
}
$fns['og_attr_html'] = fn (mixed $a): Html => new Html(Runtime::attrHtml($a));
$fns['og_compose'] = [$this->rt, 'compose'];
$fns['og_recipe'] = [$this->rt, 'recipe'];
$fns['og_preset'] = [$this->rt, 'preset'];
$fns['og_lucide'] = fn (mixed $name): Html => new Html($this->rt->lucide($name));
$fns['og_include'] = fn (string $template, array $vars = []): Html => new Html($this->engine->renderToString($template, $vars));
return $fns;
}
}
<?php
// Code generated by packages/kit-compose/src/server-organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
declare(strict_types=1);
namespace CodegenX\Organisms\Latte;
/**
* The helpers of the generated templates. Values are the JSON shapes of the TypeScript props (string, int/float,
* bool, null, list, map) and are read with the rules of the TypeScript output: JS truthiness, strict equality,
* String(), clsx + tailwind-merge. Every helper is null-safe, like `?.`. Port of the Go runtime (dyn.go, expr.go,
* utils.go) so all static runtimes print the same DOM.
*/
final class Runtime
{
/** @var array<string, mixed> parsed JSON files (recipes, presets, the Lucide registry) */
private array $json = [];
public function __construct(private readonly string $root)
{
}
public function json(string $path): mixed
{
if (!array_key_exists($path, $this->json)) {
$text = file_get_contents($this->root . '/' . $path);
if ($text === false) {
throw new \RuntimeException("ui8kit: cannot read $path");
}
$this->json[$path] = json_decode($text, true, 512, JSON_THROW_ON_ERROR);
}
return $this->json[$path];
}
// ---------------------------------------------------------------- values
private static function isNum(mixed $v): bool
{
return is_int($v) || is_float($v);
}
/** a path of fields: get(plan, ['price', 'amount']); `length` of a list or a text is its size */
public static function get(mixed $v, array $path): mixed
{
foreach ($path as $k) {
$k = (string) $k;
if (is_array($v)) {
if (array_is_list($v) && ($k === 'length' || ctype_digit($k))) {
if ($k === 'length') {
$v = count($v);
} else {
$v = $v[(int) $k] ?? null;
}
} else {
$v = $v[$k] ?? null;
}
} elseif (is_string($v) && $k === 'length') {
$v = mb_strlen($v);
} else {
return null;
}
}
return $v;
}
/** a field of a brick record (BreadcrumbItem): the JSON key matched without regard to case, as Go json does */
public static function field(mixed $item, string $name, mixed $zero): mixed
{
if (!is_array($item)) {
return $zero;
}
if (array_key_exists($name, $item)) {
return $item[$name] ?? $zero;
}
foreach ($item as $k => $v) {
if (strcasecmp((string) $k, $name) === 0) {
return $v ?? $zero;
}
}
return $zero;
}
/** String(n) of JavaScript for the numbers the views print: 3, 2.5, -1 */
public static function fmtNum(int|float $f): string
{
if (is_int($f)) {
return (string) $f;
}
if (is_nan($f)) {
return 'NaN';
}
if (is_infinite($f)) {
return $f > 0 ? 'Infinity' : '-Infinity';
}
if ($f == floor($f) && abs($f) < 1e21) {
return sprintf('%.0f', $f);
}
return json_encode($f);
}
public static function s(mixed $v): string
{
if ($v === null) {
return '';
}
if (is_string($v)) {
return $v;
}
if (is_bool($v)) {
return $v ? 'true' : 'false';
}
if (self::isNum($v)) {
return self::fmtNum($v);
}
if ($v instanceof \Stringable) {
return (string) $v;
}
return json_encode($v, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}
/** what a text node shows: nothing for null and booleans */
public static function text(mixed $v): string
{
return is_bool($v) ? '' : self::s($v);
}
/**
* the markup an html node prints (printed with |raw, |noescape): the trusted markup ({"__html": "..."}, a TrustedHtml prop) as it
* is; any other value is text, escaped (& < > " ' as entities, like htmlOf of the TypeScript runtimes)
*/
public static function html(mixed $v): string
{
if (is_array($v) && isset($v['__html']) && is_string($v['__html'])) {
return $v['__html'];
}
return strtr(self::text($v), ['&' => '&', '<' => '<', '>' => '>', '"' => '"', "'" => ''']);
}
/**
* a slot prop printed in place (|raw, |noescape): the markup the calling template captured ({"__html": "..."}, made by
* markup()) as it is; any other value (a plain string from a caller) is text, escaped, so a sub-template called directly
* with a string prints no markup of it
*/
public static function slot(mixed $v): string
{
return self::html($v);
}
/** captured markup (a fill of a slot) as a TrustedHtml marker, which slot() prints as it is */
public static function markup(mixed $v): array
{
return ['__html' => $v === null ? '' : (string) $v];
}
// ---------------------------------------------------------------- output safety (assets/ts/safe.ts, test/safety-vectors.json)
/** the named character references the URL check decodes */
public const NAMED_ENTITIES = [
'Tab' => "\t", 'NewLine' => "\n", 'colon' => ':', 'sol' => '/', 'bsol' => '\\', 'lpar' => '(', 'rpar' => ')', 'amp' => '&',
'lt' => '<', 'gt' => '>', 'quot' => '"', 'apos' => "'", 'nbsp' => "\u{00a0}", 'period' => '.', 'comma' => ',', 'excl' => '!',
'num' => '#', 'quest' => '?', 'equals' => '=', 'plus' => '+', 'semi' => ';', 'percnt' => '%', 'lowbar' => '_', 'ast' => '*',
'commat' => '@', 'dollar' => '$', 'Hat' => '^', 'grave' => '`', 'lsqb' => '[', 'rsqb' => ']', 'lcub' => '{', 'rcub' => '}',
'verbar' => '|', 'vert' => '|',
];
public const URL_SCHEMES = ['http', 'https', 'mailto', 'tel'];
public const URL_ATTRS = ['href', 'src', 'action', 'formaction', 'poster', 'cite', 'background', 'data', 'xlink:href'];
public const IMAGE_ATTRS = ['src', 'poster', 'background'];
private static function fromCode(int|float $n): string
{
return $n > 0 && $n <= 0x10FFFF && !($n >= 0xD800 && $n <= 0xDFFF) ? (string) mb_chr((int) $n, 'UTF-8') : "\u{FFFD}";
}
/** character references decoded as a browser would (numeric with or without ;, the named ones of NAMED_ENTITIES), up to 3 rounds */
public static function decodeEntities(string $s): string
{
for ($i = 0; $i < 3 && str_contains($s, '&'); $i++) {
$s = (string) preg_replace_callback('/&(?:#[xX]([0-9a-fA-F]{1,8});?|#([0-9]{1,10});?|([a-zA-Z][a-zA-Z0-9]{0,31});)/u', static function (array $m): string {
if (($m[1] ?? '') !== '') {
return self::fromCode(hexdec($m[1]));
}
if (($m[2] ?? '') !== '') {
return self::fromCode((float) $m[2]);
}
return self::NAMED_ENTITIES[$m[3] ?? ''] ?? $m[0];
}, $s);
}
return $s;
}
private static function compact(string $s): string
{
return (string) preg_replace('/[\x00-\x20\x7F]+/u', '', self::decodeEntities($s));
}
/** true when the URL is allowed: no scheme and not //host, or http(s), mailto, tel; an image also data:image/* */
public static function isSafeUrl(string $v, bool $image = false): bool
{
$k = self::compact($v);
if (preg_match('#^[/\\\\]{2}#', $k) === 1) {
return false;
}
if (preg_match('/^([a-zA-Z][a-zA-Z0-9+.\-]*):/', $k, $m) !== 1) {
// no scheme: a path, unless a ':' comes before any '/' (as written or decoded), as templ.URL
return preg_match('#^[^/]*:#', $k) !== 1 && preg_match('#^[^/]*:#', $v) !== 1;
}
$scheme = strtolower($m[1]);
if ($scheme === 'data') {
return $image && preg_match('#^data:image/(png|jpeg|gif|webp|avif|svg\+xml)[;,]#', strtolower($k)) === 1;
}
return in_array($scheme, self::URL_SCHEMES, true);
}
private static function safeStr(mixed $v): string
{
return is_string($v) ? $v : (self::isNum($v) ? self::fmtNum($v) : '');
}
/** a URL attribute value: the value when allowed, else '' */
public static function url(mixed $v, bool $image = false): string
{
$s = self::safeStr($v);
return self::isSafeUrl($s, $image) ? $s : '';
}
/** the URLs of a srcset, candidate by candidate */
public static function srcsetUrls(string $v): array
{
$s = self::decodeEntities($v);
$out = [];
$n = strlen($s);
$i = 0;
$ws = static fn (string $c): bool => $c === "\t" || $c === "\n" || $c === "\f" || $c === "\r" || $c === ' ';
while ($i < $n) {
while ($i < $n && ($ws($s[$i]) || $s[$i] === ',')) {
$i++;
}
if ($i >= $n) {
break;
}
$j = $i;
while ($j < $n && !$ws($s[$j])) {
$j++;
}
$url = substr($s, $i, $j - $i);
if (preg_match('/,+$/', $url, $cut) === 1) {
$out[] = substr($url, 0, -strlen($cut[0]));
$i = $j;
continue;
}
$out[] = $url;
$depth = 0;
while ($j < $n && ($depth > 0 || $s[$j] !== ',')) {
if ($s[$j] === '(') {
$depth++;
} elseif ($s[$j] === ')') {
$depth = max(0, $depth - 1);
}
$j++;
}
$i = $j + 1;
}
return $out;
}
/** a srcset value: the value when every candidate is an allowed image URL, else '' */
public static function srcset(mixed $v): string
{
$s = self::safeStr($v);
foreach (self::srcsetUrls($s) as $u) {
if (!self::isSafeUrl($u, true)) {
return '';
}
}
return $s;
}
/** a style value: '' when a url(...) is not an image URL or it holds a script form or a CSS escape, else the value */
public static function style(mixed $v): string
{
$s = self::safeStr($v);
$d = self::decodeEntities($s);
$k = strtolower(self::compact($s));
if (str_contains($d, '\\') || preg_match('/expression\(|javascript:|vbscript:|-moz-binding|behavior:/', $k) === 1) {
return '';
}
preg_match_all('/url\(([^)]*)\)?/i', $d, $all);
foreach ($all[1] as $arg) {
$u = (string) preg_replace('/^(["\'])(.*)\1$/s', '$2', trim($arg, " \t\n\r\f\v"));
if (!self::isSafeUrl($u, true)) {
return '';
}
}
return $s;
}
/** a value of an inline style declaration (the css op): kept when plain (numbers, words, %, #, +, -, ., commas, spaces), else '' */
public static function cssValue(mixed $v): string
{
$s = self::safeStr($v);
return preg_match('/^[-+.%#a-zA-Z0-9 ,]*$/', $s) === 1 ? $s : '';
}
/** an attribute name that may be printed: a valid name, not an event handler (on*) */
public static function isSafeAttrName(string $name): bool
{
return preg_match('/^[a-zA-Z_:][-a-zA-Z0-9_:.]*$/', $name) === 1 && preg_match('/^on/i', $name) !== 1;
}
/** the value of attribute $name as it may be printed: URL, srcset and style checked */
public static function attrValue(string $name, mixed $v): mixed
{
$n = strtolower($name);
if ($n === 'srcset' || $n === 'imagesrcset') {
return self::srcset($v);
}
if ($n === 'style') {
return self::style($v);
}
if (in_array($n, self::URL_ATTRS, true)) {
return self::url($v, in_array($n, self::IMAGE_ATTRS, true));
}
return $v;
}
/** JS truthiness: null, false, 0, NaN and '' are false */
public static function t(mixed $v): bool
{
if ($v === null) {
return false;
}
if (is_bool($v)) {
return $v;
}
if (is_string($v)) {
return $v !== '';
}
if (self::isNum($v)) {
return $v != 0 && !is_nan((float) $v);
}
if ($v instanceof \Stringable) {
return (string) $v !== '';
}
return true;
}
/** Number(v) */
public static function n(mixed $v): float
{
if (self::isNum($v)) {
return (float) $v;
}
if (is_string($v) && is_numeric(trim($v))) {
return (float) trim($v);
}
if (is_bool($v)) {
return $v ? 1.0 : 0.0;
}
return 0.0;
}
/** an int for an int prop of a brick */
public static function i(mixed $v): int
{
return (int) round(self::n($v));
}
/** strict equality (===) */
public static function eq(mixed $a, mixed $b): bool
{
$na = self::isNum($a);
$nb = self::isNum($b);
if ($na || $nb) {
return $na && $nb && (float) $a == (float) $b;
}
if ($a === null || is_string($a) || is_bool($a)) {
return $a === $b;
}
return false;
}
private static function cmp(mixed $a, mixed $b): ?int
{
if (is_string($a) && is_string($b)) {
return strcmp($a, $b) <=> 0;
}
if ($a === null || $b === null) {
return null;
}
return self::n($a) <=> self::n($b);
}
public static function lt(mixed $a, mixed $b): bool { $c = self::cmp($a, $b); return $c !== null && $c < 0; }
public static function gt(mixed $a, mixed $b): bool { $c = self::cmp($a, $b); return $c !== null && $c > 0; }
public static function le(mixed $a, mixed $b): bool { $c = self::cmp($a, $b); return $c !== null && $c <= 0; }
public static function ge(mixed $a, mixed $b): bool { $c = self::cmp($a, $b); return $c !== null && $c >= 0; }
/** `a + b`: text when either side is text, else a sum */
public static function add(mixed $a, mixed $b): string|float
{
if (is_string($a) || is_string($b)) {
return self::s($a) . self::s($b);
}
return self::n($a) + self::n($b);
}
public static function sub(mixed $a, mixed $b): float { return self::n($a) - self::n($b); }
public static function mul(mixed $a, mixed $b): float { return self::n($a) * self::n($b); }
public static function div(mixed $a, mixed $b): float { return fdiv(self::n($a), self::n($b)); }
/** the first falsy operand, else the last (JS &&) */
public static function and(array $vs): mixed
{
$last = null;
foreach ($vs as $v) {
if (!self::t($v)) {
return $v;
}
$last = $v;
}
return $last;
}
/** the first truthy operand, else the last (JS ||) */
public static function or(array $vs): mixed
{
$last = null;
foreach ($vs as $v) {
if (self::t($v)) {
return $v;
}
$last = $v;
}
return $last;
}
public static function coalesce(array $vs): mixed
{
foreach ($vs as $v) {
if ($v !== null) {
return $v;
}
}
return null;
}
/** a prop with its default: the default when the prop is null */
public static function def(mixed $v, mixed $d): mixed
{
return $v ?? $d;
}
/** a list to loop over; null and other values are empty */
public static function l(mixed $v): array
{
return is_array($v) && array_is_list($v) ? $v : [];
}
public static function len(mixed $v): int
{
if (is_string($v)) {
return mb_strlen($v);
}
return count(self::l($v));
}
/** a literal group with the fields of a named group first (`{ ...BASE, mode: "two" }`) */
public static function spread(mixed $base, array $fields): array
{
$out = is_array($base) && !array_is_list($base) ? $base : [];
foreach ($fields as $k => $v) {
$out[$k] = $v;
}
return $out;
}
/** String(x) with undefined kept undefined */
public static function str(mixed $v): ?string
{
return $v === null ? null : self::s($v);
}
public static function has(mixed $v): bool
{
return $v !== null;
}
/** cn over values: clsx skips the falsy ones, tailwind-merge resolves conflicts */
public static function cnv(array $vs): string
{
$parts = [];
foreach ($vs as $v) {
if (self::t($v)) {
$parts[] = self::s($v);
}
}
return CnMerge::merge($parts);
}
/** {0}, {1}... of a content template */
public static function tpl(mixed $t, array $vals): string
{
return preg_replace_callback('/\{(\d+)\}/', fn ($m) => (int) $m[1] < count($vals) ? self::s($vals[(int) $m[1]]) : '', self::s($t));
}
private static function group(float $f, int $decimals): string
{
$s = number_format(abs($f), $decimals, '.', '');
[$int, $frac] = array_pad(explode('.', $s, 2), 2, '');
$out = '';
$n = strlen($int);
for ($i = 0; $i < $n; $i++) {
if ($i > 0 && ($n - $i) % 3 === 0) {
$out .= ',';
}
$out .= $int[$i];
}
$frac = rtrim($frac, '0');
if ($frac !== '') {
$out .= '.' . $frac;
}
if ($f < 0 && $out !== '0') {
$out = '-' . $out;
}
return $out;
}
/** Intl.NumberFormat("en-US"): grouped, up to 3 decimals */
public static function num(mixed $v): string
{
return self::group(self::n($v), 3);
}
private const CURRENCY = ['USD' => '$', 'EUR' => "\u{20AC}", 'GBP' => "\u{00A3}", 'JPY' => "\u{00A5}", 'INR' => "\u{20B9}", 'CAD' => 'CA$', 'AUD' => 'A$'];
/** digits of the minor unit (ISO 4217): 2, or 0 for JPY and KRW */
public static function minorDigits(string $c): int
{
return in_array($c, ['JPY', 'KRW'], true) ? 0 : 2;
}
/** integer minor units (Codex v0.4: 1250 = 12.50) -> "$12.50"; whole amounts without the fraction: 149900 -> "$1,499" */
public static function money(mixed $amount, mixed $currency): string
{
$c = self::s($currency);
$sym = self::CURRENCY[$c] ?? $c . "\u{00A0}";
$minor = (int) round(self::n($amount));
$sign = $minor < 0 ? '-' : '';
$minor = abs($minor);
$d = self::minorDigits($c);
$unit = 10 ** $d;
$whole = intdiv($minor, $unit);
$rest = $minor % $unit;
$out = $sign . $sym . self::group((float) $whole, 0);
return $d > 0 && $rest !== 0 ? $out . '.' . str_pad((string) $rest, $d, '0', STR_PAD_LEFT) : $out;
}
/** a content word by key, the key itself when the dictionary has no entry */
public static function at(mixed $dict, mixed $key): string
{
$v = self::get($dict, [self::s($key)]);
return $v !== null ? self::s($v) : self::s($key);
}
/** the pages a pager shows: the first, the last and the neighbours of the current one; null is a gap */
public static function pageWindow(mixed $pageV, mixed $pagesV): array
{
$page = (int) self::n($pageV);
$pages = (int) self::n($pagesV);
$keep = [];
foreach ([1, $pages, $page - 1, $page, $page + 1] as $n) {
if ($n >= 1 && $n <= $pages) {
$keep[$n] = true;
}
}
$out = [];
$prev = 0;
for ($n = 1; $n <= $pages; $n++) {
if (!isset($keep[$n])) {
continue;
}
if ($n - $prev > 1) {
$out[] = null;
}
$out[] = $n;
$prev = $n;
}
return $out;
}
/** a responsive column variant capped by the number of items: ("1-4", 3) -> "1-3" */
public static function fitCols(mixed $colsV, mixed $nV): string
{
$cols = self::s($colsV);
$n = (int) self::n($nV);
if (!preg_match('/^(-?\d+)-(-?\d+)$/', $cols, $m)) {
return $cols;
}
[$l, $h] = [(int) $m[1], (int) $m[2]];
if ($n >= $h) {
return $cols;
}
$top = max($l, $n);
$known = ['1-2', '1-3', '1-4', '2-3', '2-4', '2-6', '3-6'];
for ($k = $top; $k > $l; $k--) {
if (in_array("$l-$k", $known, true)) {
return "$l-$k";
}
}
return (string) min(max($n, 1), $l);
}
/** drops a segment of a ", " label equal (case-insensitive) to the one before it */
public static function uniq(mixed $v): string
{
$parts = explode(', ', self::s($v));
$out = [];
foreach ($parts as $i => $s) {
if ($i === 0 || strcasecmp($s, $parts[$i - 1]) !== 0) {
$out[] = $s;
}
}
return implode(', ', $out);
}
public static function words(mixed $v): array
{
return explode(' ', self::s($v));
}
public static function nbsp(mixed $v): string
{
return str_replace(' ', "\u{00A0}", self::s($v));
}
public static function nth(mixed $list, mixed $i): mixed
{
$l = self::l($list);
$n = (int) self::n($i);
return $n >= 0 && $n < count($l) ? $l[$n] : null;
}
public static function range(mixed $n): array
{
$c = (int) self::n($n);
return $c > 0 ? range(0, $c - 1) : [];
}
public static function max(array $vs): float
{
$m = -INF;
foreach ($vs as $v) {
$m = max($m, self::n($v));
}
return $m;
}
public static function min(array $vs): float
{
$m = INF;
foreach ($vs as $v) {
$m = min($m, self::n($v));
}
return $m;
}
/** Math.round (halves up) */
public static function round(mixed $v): float
{
return floor(self::n($v) + 0.5);
}
public static function count(mixed $items, mixed $field): int
{
$n = 0;
foreach (self::l($items) as $it) {
if (self::t(self::get($it, [self::s($field)]))) {
$n++;
}
}
return $n;
}
public static function where(mixed $items, mixed $field, mixed $value): array
{
if (!self::t($value)) {
return self::l($items);
}
return array_values(array_filter(self::l($items), fn ($it) => self::eq(self::get($it, [self::s($field)]), $value)));
}
public static function match(mixed $items, mixed $field, mixed $query): array
{
if (!self::t($query)) {
return self::l($items);
}
$q = mb_strtolower(self::s($query));
return array_values(array_filter(self::l($items), fn ($it) => str_contains(mb_strtolower(self::s(self::get($it, [self::s($field)]))), $q)));
}
public static function pick(mixed $items, mixed $id): mixed
{
foreach (self::l($items) as $it) {
if (self::eq(self::get($it, ['id']), $id)) {
return $it;
}
}
return null;
}
public static function sumBy(mixed $items, string $a, string $b): float
{
$s = 0.0;
foreach (self::l($items) as $it) {
$s += self::n(self::get($it, [$a])) * self::n(self::get($it, [$b]));
}
return $s;
}
public static function firstOf(mixed $items, string $field): mixed
{
$l = self::l($items);
return $l ? (self::get($l[0], [$field]) ?? '') : '';
}
public static function maxBy(mixed $items, string $field): float
{
$m = 0.0;
foreach (self::l($items) as $it) {
$m = max($m, self::n(self::get($it, [$field])));
}
return $m;
}
/** an inline style from (property, value, unit) triples */
public static function css(array $triples): string
{
$parts = [];
for ($i = 0; $i + 2 < count($triples); $i += 3) {
$parts[] = self::s($triples[$i]) . ':' . self::cssValue($triples[$i + 1]) . self::s($triples[$i + 2]);
}
return implode(';', $parts);
}
/** the class string of a recipe table for a selection (organisms: base, each key, the matching compounds) */
public function recipe(string $path, array $sel): string
{
$r = $this->json($path);
$pick = function (string $k) use ($r, $sel): string {
$v = trim(self::s($sel[$k] ?? null));
return $v !== '' ? $v : trim((string) ($r['defaults'][$k] ?? ''));
};
$parts = [(string) ($r['base'] ?? '')];
foreach ($r['keys'] ?? [] as $k) {
$parts[] = (string) ($r['byKey'][$k][$pick($k)] ?? '');
}
foreach ($r['compound'] ?? [] as $c) {
if (self::compoundHits($c, $pick)) {
$parts[] = (string) ($c['class'] ?? '');
}
}
return CnMerge::merge(array_filter(array_map('trim', $parts), fn ($p) => $p !== ''));
}
private static function compoundHits(array $c, callable $pick): bool
{
foreach ($c as $k => $want) {
if ($k === 'class') {
continue;
}
if (!in_array($pick((string) $k), explode('|', (string) $want), true)) {
return false;
}
}
return true;
}
/** a preset value of the kit */
public function preset(string $path, array $keys): mixed
{
return self::get(self::get($this->json($path), ['values']), $keys);
}
/** free DOM attributes from (name, value) pairs, as React prints them */
public static function attrs(array $kv): array
{
$out = [];
for ($i = 0; $i + 1 < count($kv); $i += 2) {
$k = self::s($kv[$i]);
$v = $kv[$i + 1];
if ($v === null || !self::isSafeAttrName($k)) {
continue;
}
if (!is_bool($v)) {
$v = self::attrValue($k, $v);
}
if (is_bool($v)) {
if (str_starts_with($k, 'data-') || str_starts_with($k, 'aria-')) {
$out[$k] = self::s($v);
} elseif ($v) {
$out[$k] = true;
}
continue;
}
$out[$k] = self::s($v);
}
return $out;
}
/** an attribute map as markup (` name="value"`, a bare name for true, nothing for null and false) */
public static function attrHtml(mixed $attrs): string
{
if (!is_array($attrs)) {
return '';
}
$out = '';
foreach ($attrs as $k => $v) {
if ($v === null || $v === false || !self::isSafeAttrName((string) $k)) {
continue;
}
$name = (string) $k;
$out .= $v === true ? " $name" : " $name=\"" . htmlspecialchars(self::s(self::attrValue($name, $v)), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '"';
}
return $out;
}
// ---------------------------------------------------------------- bricks (expr.go, utils.go, tags.go)
public static function isSetStr(mixed $v): bool
{
return trim(self::s($v)) !== '';
}
public static function defaultIfEmpty(mixed $v, string $fallback): string
{
$t = trim(self::s($v));
return $t === '' ? $fallback : $t;
}
/** a decision table over a trimmed text: mapping[trim(v)] or the fallback */
public static function mapOr(mixed $v, array $mapping, string $fallback, bool $lower = false): string
{
$t = trim(self::s($v));
if ($lower) {
$t = strtolower($t);
}
return array_key_exists($t, $mapping) ? (string) $mapping[$t] : $fallback;
}
public static function intMapOr(mixed $v, array $mapping, string $fallback): string
{
$n = self::i($v);
return array_key_exists($n, $mapping) ? (string) $mapping[$n] : $fallback;
}
public static function boolStr(mixed $v): string
{
return self::t($v) ? 'true' : 'false';
}
public static function concatTrim(array $parts): string
{
return implode('', array_map(fn ($p) => trim(self::s($p)), $parts));
}
/** class fragments merged with tailwind-merge (strings only, empty ones skipped) */
public static function cn(array $parts): string
{
return CnMerge::merge(array_map(fn ($p) => self::s($p), $parts));
}
/** the brick class contract: recipe base, the selected variants (defaults for empty), compounds, then the tail */
public function compose(string $path, array $selection, array $extra): string
{
$r = $this->json($path);
$parts = [];
if (trim((string) ($r['base'] ?? '')) !== '') {
$parts[] = trim((string) $r['base']);
}
$pick = function (string $k) use ($r, $selection): string {
$c = trim(self::s($selection[$k] ?? null));
return $c !== '' ? $c : trim((string) ($r['defaults'][$k] ?? ''));
};
foreach ($r['keys'] ?? [] as $key) {
$choices = $r['byKey'][$key] ?? null;
if ($choices === null) {
continue;
}
$choice = $pick($key);
if ($choice === '') {
if ($choices) {
throw new \RuntimeException("[compose] missing default for key $key");
}
continue;
}
if (isset($choices[$choice]) && trim((string) $choices[$choice]) !== '') {
$parts[] = (string) $choices[$choice];
}
}
foreach ($r['compound'] ?? [] as $c) {
if (self::compoundHits($c, $pick) && trim((string) ($c['class'] ?? '')) !== '') {
$parts[] = (string) $c['class'];
}
}
return self::cn([...$parts, ...$extra]);
}
/** the tag of a primitive: the requested one when the allow-list has it, else the fallback */
public static function resolveTag(mixed $tag, string $fallback, array $allowed): string
{
$t = strtolower(trim(self::s($tag)));
return $t !== '' && in_array($t, $allowed, true) ? $t : $fallback;
}
/** h1-h6 from a level, h2 by default */
public static function titleTag(mixed $level): string
{
$n = self::i($level);
return $n >= 1 && $n <= 6 ? "h$n" : 'h2';
}
/** the inner markup of a Lucide glyph: its nodes with attributes in name order (circle for an unknown name) */
public function lucide(mixed $name): string
{
$icons = $this->json('icons/lucide-icons.json')['icons'];
$nodes = $icons[self::s($name)] ?? $icons['circle'];
$out = '';
foreach ($nodes as [$tag, $attrs]) {
ksort($attrs, SORT_STRING);
$out .= '<' . $tag;
foreach ($attrs as $k => $v) {
$out .= ' ' . $k . '="' . htmlspecialchars((string) $v, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '"';
}
$out .= '></' . $tag . '>';
}
return $out;
}
}
<?php
// Code generated by @ui8kit/codegen. DO NOT EDIT.
declare(strict_types=1);
namespace UI8Kit\Latte;
/**
* Class contracts of every primitive. Recipes are the shared *.variants.json
* files, inlined verbatim; merge order and tailwind-merge semantics match cn()
* in the TS runtimes and Cn/Compose in Go.
*/
final class Classes
{
public const RECIPES = [
'icon' => [
'base' => 'inline-flex shrink-0 items-center justify-center',
'byKey' => [
'size' => [
'xs' => 'size-3',
'sm' => 'size-4',
'md' => 'size-5',
'lg' => 'size-6',
'xl' => 'size-8',
],
],
'defaults' => [
'size' => 'sm',
],
'id' => 'ui.icon',
'keys' => [
'size',
],
],
];
/**
* Box classes without rendering — the asChild replacement for custom roots.
*
* @param array{class?: string, tag?: string} $p
*/
public static function boxClasses(array $p = []): string
{
return Rt::cn([($p['class'] ?? '')]);
}
/**
* Text classes without rendering — the asChild replacement for custom roots.
*
* @param array{class?: string, tag?: string} $p
*/
public static function textClasses(array $p = []): string
{
return Rt::cn([($p['class'] ?? '')]);
}
/**
* Button classes without rendering — the asChild replacement for custom roots.
*
* @param array{class?: string, type?: string, form?: string, href?: string, disabled?: bool, pressed?: bool, expanded?: bool, ariaLabel?: string, ariaPressed?: string, ariaExpanded?: string, ariaControls?: string} $p
*/
public static function buttonClasses(array $p = []): string
{
return Rt::cn([($p['class'] ?? '')]);
}
/**
* Link classes without rendering — the asChild replacement for custom roots.
*
* @param array{class?: string, href?: string, target?: string, rel?: string, external?: bool, download?: string, ariaCurrent?: string, ariaLabel?: string} $p
*/
public static function linkClasses(array $p = []): string
{
return Rt::cn([($p['class'] ?? '')]);
}
/**
* Label classes without rendering — the asChild replacement for custom roots.
*
* @param array{class?: string, htmlFor?: string} $p
*/
public static function labelClasses(array $p = []): string
{
return Rt::cn([($p['class'] ?? '')]);
}
/**
* Form classes without rendering — the asChild replacement for custom roots.
*
* @param array{class?: string, id?: string, name?: string, action?: string, method?: string, encType?: string, noValidate?: bool, autoComplete?: string, target?: string, ariaLabel?: string, ariaLabelledBy?: string, ariaDescribedBy?: string} $p
*/
public static function formClasses(array $p = []): string
{
return Rt::cn([($p['class'] ?? '')]);
}
/**
* Input classes without rendering — the asChild replacement for custom roots.
*
* @param array{class?: string, type?: string, id?: string, name?: string, value?: string, placeholder?: string, min?: string, max?: string, step?: string, required?: bool, disabled?: bool, readOnly?: bool, ariaInvalid?: string, ariaDescribedBy?: string} $p
*/
public static function inputClasses(array $p = []): string
{
return Rt::cn([($p['class'] ?? '')]);
}
/**
* Textarea classes without rendering — the asChild replacement for custom roots.
*
* @param array{class?: string, id?: string, name?: string, value?: string, placeholder?: string, rows?: string, required?: bool, disabled?: bool, readOnly?: bool, ariaInvalid?: string, ariaDescribedBy?: string} $p
*/
public static function textareaClasses(array $p = []): string
{
return Rt::cn([($p['class'] ?? '')]);
}
/**
* Select classes without rendering — the asChild replacement for custom roots.
*
* @param array{class?: string, id?: string, name?: string, value?: string, multiple?: bool, required?: bool, disabled?: bool, ariaInvalid?: string, ariaDescribedBy?: string} $p
*/
public static function selectClasses(array $p = []): string
{
return Rt::cn(['pr-2', ($p['class'] ?? '')]);
}
/**
* Checkbox classes without rendering — the asChild replacement for custom roots.
*
* @param array{class?: string, id?: string, name?: string, value?: string, checked?: bool, required?: bool, disabled?: bool, ariaInvalid?: string, ariaDescribedBy?: string} $p
*/
public static function checkboxClasses(array $p = []): string
{
return Rt::cn([($p['class'] ?? '')]);
}
/**
* Radio classes without rendering — the asChild replacement for custom roots.
*
* @param array{class?: string, id?: string, name?: string, value?: string, checked?: bool, required?: bool, disabled?: bool, ariaInvalid?: string, ariaDescribedBy?: string} $p
*/
public static function radioClasses(array $p = []): string
{
return Rt::cn([($p['class'] ?? '')]);
}
/**
* Switch classes without rendering — the asChild replacement for custom roots.
*
* @param array{class?: string, checked?: bool, disabled?: bool, id?: string, name?: string, value?: string, ariaLabel?: string, ariaLabelledBy?: string} $p
*/
public static function switchClasses(array $p = []): string
{
return Rt::cn([($p['class'] ?? '')]);
}
/**
* Image classes without rendering — the asChild replacement for custom roots.
*
* @param array{class?: string, src?: string, alt?: string, srcSet?: string, sizes?: string, width?: string, height?: string, loading?: string, decoding?: string} $p
*/
public static function imageClasses(array $p = []): string
{
return Rt::cn([($p['class'] ?? '')]);
}
/**
* Picture classes without rendering — the asChild replacement for custom roots.
*
* @param array{class?: string} $p
*/
public static function pictureClasses(array $p = []): string
{
return Rt::cn([($p['class'] ?? '')]);
}
/**
* Icon classes without rendering — the asChild replacement for custom roots.
*
* @param array{size?: string, class?: string, label?: string} $p
*/
public static function iconClasses(array $p = []): string
{
return Rt::compose(self::RECIPES['icon'], ['size' => ($p['size'] ?? '')], [($p['class'] ?? '')]);
}
/**
* Dialog classes without rendering — the asChild replacement for custom roots.
*
* @param array{class?: string, id?: string, open?: bool, ariaLabelledBy?: string, ariaDescribedBy?: string, ariaLabel?: string} $p
*/
public static function dialogClasses(array $p = []): string
{
return Rt::cn([($p['class'] ?? '')]);
}
/**
* Disclosure classes without rendering — the asChild replacement for custom roots.
*
* @param array{class?: string, open?: bool, name?: string} $p
*/
public static function disclosureClasses(array $p = []): string
{
return Rt::cn([($p['class'] ?? '')]);
}
/**
* Summary classes without rendering — the asChild replacement for custom roots.
*
* @param array{class?: string} $p
*/
public static function summaryClasses(array $p = []): string
{
return Rt::cn([($p['class'] ?? '')]);
}
/**
* Meter classes without rendering — the asChild replacement for custom roots.
*
* @param array{class?: string, value?: string, min?: string, max?: string, low?: string, high?: string, optimum?: string, ariaLabel?: string} $p
*/
public static function meterClasses(array $p = []): string
{
return Rt::cn([($p['class'] ?? '')]);
}
/**
* Progress classes without rendering — the asChild replacement for custom roots.
*
* @param array{class?: string, value?: string, max?: string, ariaLabel?: string} $p
*/
public static function progressClasses(array $p = []): string
{
return Rt::cn([($p['class'] ?? '')]);
}
/**
* Separator classes without rendering — the asChild replacement for custom roots.
*
* @param array{class?: string, orientation?: string, decorative?: bool} $p
*/
public static function separatorClasses(array $p = []): string
{
return Rt::cn([($p['class'] ?? '')]);
}
}
<?php
// Code generated by @ui8kit/codegen. DO NOT EDIT.
declare(strict_types=1);
namespace UI8Kit\Latte;
/**
* cn: clsx-joined class fragments with tailwind-merge conflict resolution (the last class of a group wins, and a
* class removes the earlier classes of the groups it overrides: p-2 removes px-4, not the reverse). Port of cn_merge.go.
*/
final class CnMerge
{
public static function merge(array $classes): string
{
$tokens = [];
foreach ($classes as $chunk) {
foreach (preg_split('/\s+/', trim((string) $chunk)) ?: [] as $t) {
if ($t !== '') {
$tokens[] = $t;
}
}
}
$kept = [];
foreach ($tokens as $token) {
[$prefix, $key, $removes] = self::classKey($token);
if ($key !== '') {
$drop = [$key => true];
foreach ($removes as $g) {
$drop[$prefix . $g] = true;
}
$kept = array_values(array_filter($kept, fn ($it) => !isset($drop[$it[1]])));
}
$kept[] = [$token, $key];
}
return implode(' ', array_map(fn ($it) => $it[0], $kept));
}
private static function classKey(string $token): array
{
[$prefix, $core] = self::splitVariant($token);
if ($core === '') {
return ['', '', []];
}
$groups = self::utilityGroups($core);
if (!$groups) {
return [$prefix, '=' . $token, []];
}
return [$prefix, $prefix . $groups[0], array_slice($groups, 1)];
}
private static function splitVariant(string $token): array
{
$depth = 0;
$cut = -1;
$n = strlen($token);
for ($i = 0; $i < $n; $i++) {
$c = $token[$i];
if ($c === '[') {
$depth++;
} elseif ($c === ']') {
if ($depth > 0) {
$depth--;
}
} elseif ($c === ':' && $depth === 0) {
$cut = $i;
}
}
if ($cut === -1) {
return ['', self::noBang($token)];
}
return [substr($token, 0, $cut + 1), self::noBang(substr($token, $cut + 1))];
}
private static function noBang(string $s): string
{
return str_starts_with($s, '!') ? substr($s, 1) : $s;
}
private static function utilityGroups(string $core): array
{
switch ($core) {
case 'block': case 'inline': case 'inline-block': case 'inline-flex': case 'flex': case 'grid': case 'contents': case 'hidden':
return ['display'];
case 'flex-row': case 'flex-col': case 'flex-row-reverse': case 'flex-col-reverse':
return ['flex-direction'];
case 'static': case 'relative': case 'absolute': case 'fixed': case 'sticky':
return ['position'];
case 'isolate': case 'isolation-auto':
return ['isolation'];
case 'object-contain': case 'object-cover': case 'object-fill': case 'object-none': case 'object-scale-down':
return ['object-fit'];
case 'object-bottom': case 'object-center': case 'object-left': case 'object-left-bottom': case 'object-left-top': case 'object-right': case 'object-right-bottom': case 'object-right-top': case 'object-top':
return ['object-position'];
}
if (str_starts_with($core, 'aspect-')) {
return ['aspect'];
}
// ring-offset-N (width) and ring-offset-<color> are their own groups
if (str_starts_with($core, 'ring-offset-')) {
return [self::isNumber(substr($core, 12)) ? 'ring-offset-width' : 'ring-offset-color'];
}
foreach (['inset-ring', 'ring'] as $kind) {
if ($core === $kind) {
return [$kind . '-width'];
}
if (str_starts_with($core, $kind . '-')) {
$rest = substr($core, strlen($kind) + 1);
return [self::isNumber($rest) ? $kind . '-width' : $kind . '-color'];
}
}
$prefixes = [
['gap-x-', 'gap-x'], ['gap-y-', 'gap-y'], ['items-', 'align-items'], ['justify-', 'justify-content'],
['self-', 'align-self'], ['content-', 'align-content'], ['overflow-x-', 'overflow-x'], ['overflow-y-', 'overflow-y'],
['inset-x-', 'inset-x'], ['inset-y-', 'inset-y'], ['min-w-', 'min-width'], ['min-h-', 'min-height'],
['max-w-', 'max-width'], ['max-h-', 'max-height'], ['shadow-', 'shadow'], ['ring-', 'ring'], ['rounded-', 'rounded'],
['leading-', 'leading'], ['tracking-', 'tracking'], ['opacity-', 'opacity'], ['z-', 'z'], ['top-', 'top'],
['right-', 'right'], ['bottom-', 'bottom'], ['left-', 'left'],
];
foreach ($prefixes as [$p, $g]) {
if (str_starts_with($core, $p)) {
return [$g];
}
}
if (str_starts_with($core, 'gap-')) {
return ['gap', 'gap-x', 'gap-y'];
}
if (str_starts_with($core, 'inset-')) {
return ['inset', 'inset-x', 'inset-y', 'top', 'right', 'bottom', 'left'];
}
if (str_starts_with($core, 'overflow-')) {
return ['overflow', 'overflow-x', 'overflow-y'];
}
if ($core === 'border' || (str_starts_with($core, 'border-') && self::isNumber(substr($core, 7)))) {
return ['border-width', 'border-w-x', 'border-w-y', 'border-w-t', 'border-w-r', 'border-w-b', 'border-w-l', 'border-w-s', 'border-w-e'];
}
if (strlen($core) >= 8 && str_starts_with($core, 'border-') && str_contains('xytrblse', $core[7])
&& (strlen($core) === 8 || ($core[8] === '-' && self::isNumber(substr($core, 9))))) {
$side = $core[7];
if ($side === 'x') {
return ['border-w-x', 'border-w-r', 'border-w-l', 'border-w-s', 'border-w-e'];
}
if ($side === 'y') {
return ['border-w-y', 'border-w-t', 'border-w-b'];
}
return ['border-w-' . $side];
}
if (in_array($core, ['text-left', 'text-center', 'text-right', 'text-justify', 'text-start', 'text-end'], true)) {
return ['text-align'];
}
if ($core === 'rounded') {
return ['rounded'];
}
if ($core === 'shadow' || $core === 'shadow-none') {
return ['shadow'];
}
if (in_array($core, ['flex-1', 'flex-auto', 'flex-none', 'flex-initial'], true)) {
return ['flex-size', 'flex-grow', 'flex-shrink', 'flex-basis'];
}
if ($core === 'grow' || str_starts_with($core, 'grow-')) {
return ['flex-grow'];
}
if ($core === 'shrink' || $core === 'shrink-0') {
return ['flex-shrink'];
}
if (str_starts_with($core, 'size-')) {
return ['size', 'width', 'height'];
}
if (str_starts_with($core, 'w-')) {
return ['width'];
}
if (str_starts_with($core, 'h-')) {
return ['height'];
}
foreach (['p' => 'padding', 'm' => 'margin'] as $kind => $name) {
if (str_starts_with($core, $kind . '-') && !self::hasDirectionPrefix($core, $kind)) {
return [$name, "$name-x", "$name-y", "$name-t", "$name-r", "$name-b", "$name-l", "$name-s", "$name-e"];
}
$axis = self::spaceAxis($core, $kind, $name);
if ($axis) {
return $axis;
}
}
if (str_starts_with($core, 'bg-')) {
return ['bg'];
}
if (self::isTextSize($core)) {
return ['text-size', 'leading'];
}
if (str_starts_with($core, 'text-')) {
return ['text-color'];
}
if (in_array($core, ['font-thin', 'font-extralight', 'font-light', 'font-normal', 'font-medium', 'font-semibold', 'font-bold', 'font-extrabold', 'font-black'], true)) {
return ['font-weight'];
}
return [];
}
private static function hasDirectionPrefix(string $core, string $kind): bool
{
foreach (['x-', 'y-', 't-', 'r-', 'b-', 'l-', 's-', 'e-'] as $d) {
if (str_starts_with($core, $kind . $d)) {
return true;
}
}
return false;
}
private static function spaceAxis(string $core, string $kind, string $n): array
{
if (str_starts_with($core, $kind . 'x-')) {
return ["$n-x", "$n-r", "$n-l", "$n-s", "$n-e"];
}
if (str_starts_with($core, $kind . 'y-')) {
return ["$n-y", "$n-t", "$n-b"];
}
foreach (['t', 'r', 'b', 'l'] as $s) {
if (str_starts_with($core, $kind . $s . '-')) {
return ["$n-$s"];
}
}
return [];
}
private static function isTextSize(string $core): bool
{
if (in_array($core, ['text-xs', 'text-sm', 'text-base', 'text-lg', 'text-xl', 'text-2xl', 'text-3xl', 'text-4xl', 'text-5xl', 'text-6xl', 'text-7xl', 'text-8xl', 'text-9xl'], true)) {
return true;
}
if (str_starts_with($core, 'text-[')) {
$rest = substr($core, 6);
return $rest !== '' && (ctype_digit($rest[0]) || $rest[0] === '.');
}
return false;
}
private static function isNumber(string $s): bool
{
if (str_starts_with($s, '[')) {
return true;
}
return $s !== '' && strspn($s, '0123456789.') === strlen($s);
}
}
<?php
// Code generated by @ui8kit/codegen. DO NOT EDIT.
declare(strict_types=1);
namespace UI8Kit\Latte;
/**
* UI8Kit PHP runtime helpers used by the generated Twig and Latte templates.
* One implementation of every decision-table primitive; mirrors
* runtime/go/expr.go + utils.go and runtime/ts/expr.ts so all runtimes
* resolve defaults identically. Variadic Go helpers take arrays here so
* Twig and Latte call them with the same shape.
*/
final class Rt
{
private static function s(mixed $v): string
{
return is_bool($v) ? ($v ? 'true' : 'false') : (string) ($v ?? '');
}
/** cn = clsx join + tailwind-merge conflict resolution (CnMerge, port of cn_merge.go). */
public static function cn(array $classes): string
{
return CnMerge::merge(array_map([self::class, 's'], $classes));
}
/** Omit-if-empty attribute value: blank → null so the attribute is dropped. */
public static function orNull(mixed $v): ?string
{
$s = self::s($v);
return trim($s) === '' ? null : $s;
}
public static function isSetStr(mixed $v): bool
{
return trim(self::s($v)) !== '';
}
public static function defaultIfEmpty(mixed $v, string $fallback): string
{
$t = trim(self::s($v));
return $t === '' ? $fallback : $t;
}
public static function oneOfOr(mixed $v, string $fallback, array $allowed): string
{
$t = trim(self::s($v));
return in_array($t, $allowed, true) ? $t : $fallback;
}
public static function oneOfOrLower(mixed $v, string $fallback, array $allowed): string
{
return self::oneOfOr(strtolower(trim(self::s($v))), $fallback, $allowed);
}
/** Decision table: mapping[trim(v)] ?? fallback. */
public static function mapOr(mixed $v, array $mapping, string $fallback): string
{
$k = trim(self::s($v));
return array_key_exists($k, $mapping) ? (string) $mapping[$k] : $fallback;
}
public static function mapOrLower(mixed $v, array $mapping, string $fallback): string
{
return self::mapOr(strtolower(trim(self::s($v))), $mapping, $fallback);
}
/** Integer decision table: mapping[v] ?? fallback. */
public static function intMapOr(mixed $v, array $mapping, string $fallback): string
{
$k = (int) ($v ?? 0);
return array_key_exists($k, $mapping) ? (string) $mapping[$k] : $fallback;
}
/** ARIA state stringification: always 'true'/'false', never omitted. */
public static function boolStr(mixed $v): string
{
return $v ? 'true' : 'false';
}
/** Tri-state ARIA state: 'true'/'false' when set, '' when null (attribute omitted). */
public static function optBoolStr(mixed $v): string
{
return $v === null ? '' : ($v ? 'true' : 'false');
}
/** Concatenation of trimmed parts (icon Prefix + Name). */
public static function concatTrim(array $parts): string
{
$out = '';
foreach ($parts as $p) {
$out .= trim(self::s($p));
}
return $out;
}
/** Returns tag when allowed for the group, otherwise fallback (tag groups: Tags::GROUPS). */
public static function resolveTag(mixed $tag, string $fallback, string $group): string
{
$t = strtolower(trim(self::s($tag)));
if ($t === '') {
return $fallback;
}
return in_array($t, Tags::GROUPS[$group] ?? [], true) ? $t : $fallback;
}
/**
* Merge recipe base, keyed variant selections, compound variants and tail
* classes (Go Compose). Recipe shape is *.variants.json: base, keys,
* defaults, byKey, compound. Unknown choices are silently dropped.
*/
public static function compose(array $recipe, array $selection, array $extra = []): string
{
$parts = [];
$base = trim((string) ($recipe['base'] ?? ''));
if ($base !== '') {
$parts[] = $base;
}
$pick = static function (string $key) use ($recipe, $selection): string {
$choice = trim(self::s($selection[$key] ?? ''));
return $choice !== '' ? $choice : trim((string) ($recipe['defaults'][$key] ?? ''));
};
foreach (($recipe['keys'] ?? []) as $key) {
$choices = $recipe['byKey'][$key] ?? null;
if ($choices === null) {
continue;
}
$choice = $pick($key);
if ($choice === '') {
if (count($choices) > 0) {
throw new \LogicException("[compose] missing default for key \"$key\"");
}
continue;
}
$cls = $choices[$choice] ?? null;
if ($cls !== null && trim((string) $cls) !== '') {
$parts[] = (string) $cls;
}
}
foreach (($recipe['compound'] ?? []) as $c) {
$ok = true;
foreach ($c as $k => $want) {
if ($k === 'class') {
continue;
}
$ok = $ok && in_array($pick((string) $k), explode('|', (string) $want), true);
}
if ($ok && trim((string) ($c['class'] ?? '')) !== '') {
$parts[] = (string) $c['class'];
}
}
return self::cn([...$parts, ...$extra]);
}
/**
* Attribute string for Twig templates. Computed attrs first, caller
* attrs merged last so the caller wins. null/false omit, true prints a
* bare boolean attribute, everything else stringifies and escapes.
*/
private const URL_ATTRS = ['href', 'src', 'action', 'formaction', 'poster', 'cite', 'background', 'xlink:href'];
/** URL attribute value: '' for javascript:, vbscript: and data: (ASCII whitespace/control chars removed, case-insensitive). */
public static function safeUrl(mixed $v): string
{
$s = self::s($v);
return self::unsafeUrl($s, false) ? '' : $s;
}
private static function unsafeUrl(string $s, bool $dataImage): bool
{
$k = strtolower((string) preg_replace('/[\x00-\x20]/', '', $s));
if ($dataImage && preg_match('#^data:image/(png|jpeg|gif|webp|avif|svg\+xml)[;,]#', $k)) {
return false;
}
return (bool) preg_match('/^(javascript|vbscript|data):/', $k);
}
/** Optional URL attribute: null (omitted) when unset, blank or an unsafe scheme, else the value as given. */
public static function urlOrNull(mixed $v): ?string
{
$s = self::s($v);
return trim($s) === '' || self::unsafeUrl($s, false) ? null : $s;
}
/** urlOrNull for <img src>: data:image/(png|jpeg|gif|webp|avif|svg+xml) placeholders are allowed. */
public static function imgUrlOrNull(mixed $v): ?string
{
$s = self::s($v);
return trim($s) === '' || self::unsafeUrl($s, true) ? null : $s;
}
/** Drops URL attributes with an unsafe URL (kept for callers of 3.2; generated templates use restAttrs). */
public static function safeAttrs(array $attrs): array
{
foreach ($attrs as $name => $value) {
if (is_string($value) && $value !== '' && in_array(strtolower((string) $name), self::URL_ATTRS, true) && self::safeUrl($value) === '') {
unset($attrs[$name]);
}
}
return $attrs;
}
/**
* The caller's attrs as rendered: an unsafe URL (data:image allowed in <img src> when $img) or a blank optional
* attribute ($blank, lowercase names; never value) becomes null. The key stays, so the caller still wins over
* the named attribute of the same name and the attribute is omitted.
*/
public static function restAttrs(array $attrs, bool $img = false, array $blank = []): array
{
foreach ($attrs as $name => $value) {
if (!is_string($value)) {
continue;
}
$key = strtolower((string) $name);
if (trim($value) === '' && in_array($key, $blank, true)) {
$attrs[$name] = null;
} elseif ($value !== '' && in_array($key, self::URL_ATTRS, true) && self::unsafeUrl($value, $img && $key === 'src')) {
$attrs[$name] = null;
}
}
return $attrs;
}
/** Twig attribute string: named attrs, then the caller's attrs (restAttrs) merged last so the caller wins. */
public static function attrs(array $attrs, array $rest = [], bool $img = false, array $blank = []): string
{
$out = '';
foreach (array_merge($attrs, self::restAttrs($rest, $img, $blank)) as $name => $value) {
if ($value === null || $value === false) {
continue;
}
if ($value === true) {
$out .= ' ' . $name;
continue;
}
$out .= ' ' . $name . '="' . htmlspecialchars(self::s($value), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') . '"';
}
return $out;
}
}
<?php
// Code generated by @ui8kit/codegen. DO NOT EDIT.
// Source of truth: src/domain/tags.ts.
declare(strict_types=1);
namespace UI8Kit\Latte;
/** Allowed tags per semantic group (polymorphic Tag props). */
final class Tags
{
public const GROUPS = [
'Box' => ['div', 'section', 'article', 'aside', 'header', 'footer', 'main', 'nav', 'figure', 'search', 'ul', 'ol', 'li', 'dl', 'dt', 'dd', 'fieldset', 'table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td', 'caption', 'colgroup', 'col'],
'Text' => ['p', 'span', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'figcaption', 'pre', 'code', 'small', 'strong', 'em', 'time', 'legend', 'del', 'ins'],
];
}
Point the CLI at this runtime once, then add the item:
npx ui8kit init --yes --framework jinja2 --dir src --registry-url https://registry.buildy.tw/jinja2 --strict-cdnnpx ui8kit add utils# Code generated by packages/kit-compose/src/server-organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
"""The helpers of the codegen-x organism templates for Jinja2 (blocks/<organism>.html.j2, called with `p` and `children`):
`register(env, root)` adds them as og_* globals to the kit + compose Environment."""
from __future__ import annotations
import functools
from typing import Any
from jinja2 import Environment, pass_environment
from jinja2.runtime import Undefined
from markupsafe import Markup
from . import runtime as rt
def _plain(v: Any) -> Any:
if isinstance(v, Undefined):
return None
if isinstance(v, list):
return [_plain(x) for x in v]
return v
def _wrap(f: Any, safe: bool = False) -> Any:
@functools.wraps(f)
def call(*args: Any) -> Any:
out = f(*[_plain(a) for a in args])
return Markup(out) if safe else out
return call
@pass_environment
def _include(env: Environment, name: Any, vars: Any) -> Markup:
return Markup(env.get_template(str(name)).render(_plain(vars) or {}))
def _merge(a: Any, b: Any) -> dict:
return {**(_plain(a) or {}), **(_plain(b) or {})}
_NAMES = {
"and": "and_", "or": "or_", "def": "def_", "len": "len_", "str": "str_", "range": "range_", "max": "max_", "min": "min_", "round": "round_", "html": "html_",
}
_PLAIN = [
"get", "field", "s", "text", "html", "t", "n", "i", "eq", "lt", "gt", "le", "ge", "add", "sub", "mul", "div", "and", "or", "coalesce", "def", "l",
"len", "spread", "str", "has", "cnv", "tpl", "num", "money", "at", "page_window", "fit_cols", "uniq", "words", "nbsp", "nth", "range",
"max", "min", "round", "count", "where", "match", "pick", "sum_by", "first_of", "max_by", "css", "attrs", "is_set_str", "default_if_empty",
"map_or", "int_map_or", "bool_str", "concat_trim", "cn", "resolve_tag", "title_tag", "compose", "recipe", "preset", "url", "srcset", "style", "slot", "markup",
]
def register(env: Environment, root: str) -> Environment:
"""registers the og_* helpers of the organism templates (blocks/*) on an Environment whose loader also finds the
compositions (compose/*) and the kit primitives (ui/*); root holds blocks/recipes, blocks/presets and icons/"""
rt.set_root(root)
for name in _PLAIN:
env.globals["og_" + name] = _wrap(getattr(rt, _NAMES.get(name, name)))
env.globals["og_attr_html"] = _wrap(rt.attr_html, safe=True)
env.globals["og_lucide"] = _wrap(rt.lucide, safe=True)
env.globals["og_include"] = _include
env.globals["og_merge"] = _merge
return env
# Code generated by packages/kit-compose/src/server-organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
"""cn: class fragments joined with tailwind-merge conflict resolution (the last class of a group wins, and a class removes
the earlier classes of the groups it overrides: p-2 removes px-4, not the reverse). Port of cn_merge.go."""
from __future__ import annotations
_DISPLAY = {"block", "inline", "inline-block", "inline-flex", "flex", "grid", "contents", "hidden"}
_PREFIXES = [
("gap-x-", "gap-x"), ("gap-y-", "gap-y"), ("items-", "align-items"), ("justify-", "justify-content"),
("self-", "align-self"), ("content-", "align-content"), ("overflow-x-", "overflow-x"), ("overflow-y-", "overflow-y"),
("inset-x-", "inset-x"), ("inset-y-", "inset-y"), ("min-w-", "min-width"), ("min-h-", "min-height"),
("max-w-", "max-width"), ("max-h-", "max-height"), ("shadow-", "shadow"), ("ring-", "ring"), ("rounded-", "rounded"),
("leading-", "leading"), ("tracking-", "tracking"), ("opacity-", "opacity"), ("z-", "z"), ("top-", "top"),
("right-", "right"), ("bottom-", "bottom"), ("left-", "left"),
]
_TEXT_SIZES = {"text-xs", "text-sm", "text-base", "text-lg", "text-xl"} | {f"text-{n}xl" for n in range(2, 10)}
_WEIGHTS = {f"font-{w}" for w in ("thin", "extralight", "light", "normal", "medium", "semibold", "bold", "extrabold", "black")}
def _is_number(s: str) -> bool:
if s.startswith("["):
return True
return s != "" and all(c in "0123456789." for c in s)
def _split_variant(token: str) -> tuple[str, str]:
depth, cut = 0, -1
for i, c in enumerate(token):
if c == "[":
depth += 1
elif c == "]":
depth = max(0, depth - 1)
elif c == ":" and depth == 0:
cut = i
core = token if cut == -1 else token[cut + 1:]
core = core[1:] if core.startswith("!") else core
return ("" if cut == -1 else token[:cut + 1]), core
def _has_direction(core: str, kind: str) -> bool:
return any(core.startswith(kind + d) for d in ("x-", "y-", "t-", "r-", "b-", "l-", "s-", "e-"))
def _space_axis(core: str, kind: str, n: str) -> list[str]:
if core.startswith(kind + "x-"):
return [f"{n}-x", f"{n}-r", f"{n}-l", f"{n}-s", f"{n}-e"]
if core.startswith(kind + "y-"):
return [f"{n}-y", f"{n}-t", f"{n}-b"]
for s in "trbl":
if core.startswith(kind + s + "-"):
return [f"{n}-{s}"]
return []
def _groups(core: str) -> list[str]:
if core in _DISPLAY:
return ["display"]
if core in ("flex-row", "flex-col", "flex-row-reverse", "flex-col-reverse"):
return ["flex-direction"]
if core in ("static", "relative", "absolute", "fixed", "sticky"):
return ["position"]
if core in ("isolate", "isolation-auto"):
return ["isolation"]
for kind in ("inset-ring", "ring"):
if core == kind:
return [kind + "-width"]
if core.startswith(kind + "-"):
return [kind + ("-width" if _is_number(core[len(kind) + 1:]) else "-color")]
for p, g in _PREFIXES:
if core.startswith(p):
return [g]
if core.startswith("gap-"):
return ["gap", "gap-x", "gap-y"]
if core.startswith("inset-"):
return ["inset", "inset-x", "inset-y", "top", "right", "bottom", "left"]
if core.startswith("overflow-"):
return ["overflow", "overflow-x", "overflow-y"]
if core == "border" or (core.startswith("border-") and _is_number(core[7:])):
return ["border-width"] + [f"border-w-{s}" for s in "xytrblse"]
if len(core) >= 8 and core.startswith("border-") and core[7] in "xytrblse" and (len(core) == 8 or (core[8] == "-" and _is_number(core[9:]))):
side = core[7]
if side == "x":
return ["border-w-x", "border-w-r", "border-w-l", "border-w-s", "border-w-e"]
if side == "y":
return ["border-w-y", "border-w-t", "border-w-b"]
return ["border-w-" + side]
if core in ("text-left", "text-center", "text-right", "text-justify", "text-start", "text-end"):
return ["text-align"]
if core == "rounded":
return ["rounded"]
if core in ("shadow", "shadow-none"):
return ["shadow"]
if core in ("flex-1", "flex-auto", "flex-none", "flex-initial"):
return ["flex-size", "flex-grow", "flex-shrink", "flex-basis"]
if core == "grow" or core.startswith("grow-"):
return ["flex-grow"]
if core in ("shrink", "shrink-0"):
return ["flex-shrink"]
if core.startswith("size-"):
return ["size", "width", "height"]
if core.startswith("w-"):
return ["width"]
if core.startswith("h-"):
return ["height"]
for kind, n in (("p", "padding"), ("m", "margin")):
if core.startswith(kind + "-") and not _has_direction(core, kind):
return [n] + [f"{n}-{s}" for s in "xytrblse"]
axis = _space_axis(core, kind, n)
if axis:
return axis
if core.startswith("bg-"):
return ["bg"]
if core in _TEXT_SIZES or (core.startswith("text-[") and len(core) > 6 and (core[6].isdigit() or core[6] == ".")):
return ["text-size", "leading"]
if core.startswith("text-"):
return ["text-color"]
if core in _WEIGHTS:
return ["font-weight"]
return []
def merge(classes: list[str]) -> str:
kept: list[tuple[str, str]] = []
for chunk in classes:
for token in str(chunk).split():
prefix, core = _split_variant(token)
key = ""
removes: list[str] = []
if core:
g = _groups(core)
if g:
key, removes = prefix + g[0], g[1:]
else:
key = "=" + token
if key:
drop = {key} | {prefix + r for r in removes}
kept = [it for it in kept if it[1] not in drop]
kept.append((token, key))
return " ".join(t for t, _ in kept)
# Code generated by packages/kit-compose/src/server-organisms.ts from packages/compose-gen/specs (compose-gen organism emitters on kit-compose). DO NOT EDIT.
"""The helpers of the generated templates. Values are the JSON shapes of the TypeScript props (str, int/float, bool,
None, list, dict) read with the rules of the TypeScript output: JS truthiness, strict equality, String(), clsx +
tailwind-merge. Every helper is None-safe, like `?.`. Port of the Go runtime (dyn.go, expr.go, utils.go) and of the PHP
runtime of the Twig package, so every static runtime prints the same DOM."""
from __future__ import annotations
import html
import json
import math
import os
import re
from typing import Any
from .cn_merge import merge
_ROOT = ""
_JSON: dict[str, Any] = {}
def set_root(root: str) -> None:
global _ROOT
_ROOT = root
def load_json(path: str) -> Any:
if path not in _JSON:
with open(os.path.join(_ROOT, path), encoding="utf-8") as f:
_JSON[path] = json.load(f)
return _JSON[path]
# ------------------------------------------------------------------ values
def _num(v: Any) -> bool:
return isinstance(v, (int, float)) and not isinstance(v, bool)
def get(v: Any, path: list) -> Any:
"""a path of fields: get(plan, ['price', 'amount']); `length` of a list or a text is its size"""
for k in path:
k = str(k)
if isinstance(v, list):
if k == "length":
v = len(v)
elif k.isdigit() and int(k) < len(v):
v = v[int(k)]
else:
return None
elif isinstance(v, dict):
v = v.get(k)
elif isinstance(v, str) and k == "length":
v = len(v)
else:
return None
return v
def field(item: Any, name: str, zero: Any) -> Any:
"""a field of a brick record: the JSON key matched without regard to case, as Go json does"""
if not isinstance(item, dict):
return zero
if name in item:
return zero if item[name] is None else item[name]
for k, v in item.items():
if str(k).lower() == name.lower():
return zero if v is None else v
return zero
def fmt_num(f: Any) -> str:
"""String(n) of JavaScript for the numbers the views print"""
if isinstance(f, int):
return str(f)
if math.isnan(f):
return "NaN"
if math.isinf(f):
return "Infinity" if f > 0 else "-Infinity"
if f == math.floor(f) and abs(f) < 1e21:
return "%d" % int(f)
return repr(f)
def s(v: Any) -> str:
if v is None:
return ""
if isinstance(v, str):
return v
if isinstance(v, bool):
return "true" if v else "false"
if _num(v):
return fmt_num(v)
return json.dumps(v, separators=(",", ":"), ensure_ascii=False)
def text(v: Any) -> str:
"""what a text node shows: nothing for None and booleans"""
return "" if isinstance(v, bool) else s(v)
_ENTITIES = {"&": "&", "<": "<", ">": ">", '"': """, "'": "'"}
def html_(v: Any) -> str:
"""the markup an html node prints (with |safe): the trusted markup ({"__html": "..."}, a TrustedHtml prop) as it is; any other
value is text, escaped (& < > " ' as entities, like htmlOf of the TypeScript runtimes)"""
if isinstance(v, dict) and isinstance(v.get("__html"), str):
return v["__html"]
return "".join(_ENTITIES.get(c, c) for c in text(v))
def slot(v: Any) -> str:
"""a slot prop printed in place (|safe): the markup the calling template captured ({"__html": ...}, made by markup()) as it
is; any other value (a plain string from a caller) is text, escaped"""
return html_(v)
def markup(v: Any) -> dict:
"""captured markup (a fill of a slot) as a TrustedHtml marker, which slot() prints as it is"""
return {"__html": "" if v is None else str(v)}
# ------------------------------------------------------------------ output safety (assets/ts/safe.ts, test/safety-vectors.json)
NAMED_ENTITIES = {
"Tab": "\t", "NewLine": "\n", "colon": ":", "sol": "/", "bsol": "\\", "lpar": "(", "rpar": ")", "amp": "&", "lt": "<", "gt": ">",
"quot": '"', "apos": "'", "nbsp": "\u00a0", "period": ".", "comma": ",", "excl": "!", "num": "#", "quest": "?", "equals": "=",
"plus": "+", "semi": ";", "percnt": "%", "lowbar": "_", "ast": "*", "commat": "@", "dollar": "$", "Hat": "^", "grave": "`",
"lsqb": "[", "rsqb": "]", "lcub": "{", "rcub": "}", "verbar": "|", "vert": "|",
}
URL_SCHEMES = ["http", "https", "mailto", "tel"]
URL_ATTRS = ["href", "src", "action", "formaction", "poster", "cite", "background", "data", "xlink:href"]
IMAGE_ATTRS = ["src", "poster", "background"]
_ENTITY = re.compile(r"&(?:#[xX]([0-9a-fA-F]{1,8});?|#([0-9]{1,10});?|([a-zA-Z][a-zA-Z0-9]{0,31});)")
_DATA_IMAGE = re.compile(r"^data:image/(png|jpeg|gif|webp|avif|svg\+xml)[;,]")
def _from_code(n: int) -> str:
return chr(n) if 0 < n <= 0x10FFFF and not (0xD800 <= n <= 0xDFFF) else "\ufffd"
def decode_entities(v: str) -> str:
"""character references decoded as a browser would (numeric with or without ;, the named ones of NAMED_ENTITIES), up to 3 rounds"""
def one(m: "re.Match[str]") -> str:
if m.group(1) is not None:
return _from_code(int(m.group(1), 16))
if m.group(2) is not None:
return _from_code(int(m.group(2), 10))
return NAMED_ENTITIES.get(m.group(3), m.group(0))
i = 0
while i < 3 and "&" in v:
v = _ENTITY.sub(one, v)
i += 1
return v
def _compact(v: str) -> str:
return re.sub(r"[\x00-\x20\x7f]+", "", decode_entities(v))
def is_safe_url(v: str, image: bool = False) -> bool:
"""true when the URL is allowed: no scheme and not //host, or http(s), mailto, tel; an image also data:image/*"""
k = _compact(v)
if re.match(r"^[/\\]{2}", k):
return False
m = re.match(r"^([a-zA-Z][a-zA-Z0-9+.\-]*):", k)
if not m:
# no scheme: a path, unless a ":" comes before any "/" (as written or decoded), as templ.URL
return not re.match(r"^[^/]*:", k) and not re.match(r"^[^/]*:", v)
scheme = m.group(1).lower()
if scheme == "data":
return image and bool(_DATA_IMAGE.match(k.lower()))
return scheme in URL_SCHEMES
def _str(v: Any) -> str:
return v if isinstance(v, str) else fmt_num(v) if _num(v) else ""
def url(v: Any, image: bool = False) -> str:
"""a URL attribute value: the value when allowed, else ''"""
x = _str(v)
return x if is_safe_url(x, image) else ""
def srcset_urls(v: str) -> list:
"""the URLs of a srcset, candidate by candidate"""
x, out, i = decode_entities(v), [], 0
n = len(x)
ws = lambda c: c in "\t\n\f\r " # noqa: E731
while i < n:
while i < n and (ws(x[i]) or x[i] == ","):
i += 1
if i >= n:
break
j = i
while j < n and not ws(x[j]):
j += 1
u = x[i:j]
cut = re.search(r",+$", u)
if cut:
out.append(u[: -len(cut.group(0))])
i = j
continue
out.append(u)
depth = 0
while j < n and (depth > 0 or x[j] != ","):
if x[j] == "(":
depth += 1
elif x[j] == ")":
depth = max(0, depth - 1)
j += 1
i = j + 1
return out
def srcset(v: Any) -> str:
"""a srcset value: the value when every candidate is an allowed image URL, else ''"""
x = _str(v)
return x if all(is_safe_url(u, True) for u in srcset_urls(x)) else ""
def style(v: Any) -> str:
"""a style value: '' when a url(...) is not an image URL or it holds a script form or a CSS escape, else the value"""
x = _str(v)
d, k = decode_entities(x), _compact(x).lower()
if "\\" in d or re.search(r"expression\(|javascript:|vbscript:|-moz-binding|behavior:", k):
return ""
for m in re.finditer(r"url\(([^)]*)\)?", d, re.I):
arg = re.sub(r"^(['\"])(.*)\1$", r"\2", m.group(1).strip(" \t\n\r\f\v"), flags=re.S)
if not is_safe_url(arg, True):
return ""
return x
def css_value(v: Any) -> str:
"""a value of an inline style declaration (the css op): kept when plain (numbers, words, %, #, +, -, ., commas, spaces), else ''"""
x = _str(v)
return x if re.fullmatch(r"[-+.%#a-zA-Z0-9 ,]*", x) else ""
def is_safe_attr_name(name: str) -> bool:
"""an attribute name that may be printed: a valid name, not an event handler (on*)"""
return bool(re.fullmatch(r"[a-zA-Z_:][-a-zA-Z0-9_:.]*", name)) and not re.match(r"on", name, re.I)
def attr_value(name: str, v: Any) -> Any:
"""the value of attribute name as it may be printed: URL, srcset and style checked"""
n = name.lower()
if n in ("srcset", "imagesrcset"):
return srcset(v)
if n == "style":
return style(v)
if n in URL_ATTRS:
return url(v, n in IMAGE_ATTRS)
return v
def t(v: Any) -> bool:
"""JS truthiness: None, False, 0, NaN and '' are false"""
if v is None:
return False
if isinstance(v, bool):
return v
if isinstance(v, str):
return v != ""
if _num(v):
return v != 0 and not math.isnan(v)
return True
def n(v: Any) -> float:
if _num(v):
return float(v)
if isinstance(v, bool):
return 1.0 if v else 0.0
if isinstance(v, str):
try:
return float(v.strip())
except ValueError:
return 0.0
return 0.0
def _round_half_away(f: float) -> float:
return math.copysign(math.floor(abs(f) + 0.5), f)
def i(v: Any) -> int:
return int(_round_half_away(n(v)))
def eq(a: Any, b: Any) -> bool:
"""strict equality (===)"""
if _num(a) or _num(b):
return _num(a) and _num(b) and float(a) == float(b)
if a is None:
return b is None
if isinstance(a, bool) or isinstance(b, bool):
return isinstance(a, bool) and isinstance(b, bool) and a == b
if isinstance(a, str):
return isinstance(b, str) and a == b
return False
def _cmp(a: Any, b: Any) -> int | None:
if isinstance(a, str) and isinstance(b, str):
return (a > b) - (a < b)
if a is None or b is None:
return None
x, y = n(a), n(b)
return (x > y) - (x < y)
def lt(a, b): c = _cmp(a, b); return c is not None and c < 0
def gt(a, b): c = _cmp(a, b); return c is not None and c > 0
def le(a, b): c = _cmp(a, b); return c is not None and c <= 0
def ge(a, b): c = _cmp(a, b); return c is not None and c >= 0
def add(a: Any, b: Any) -> Any:
if isinstance(a, str) or isinstance(b, str):
return s(a) + s(b)
return n(a) + n(b)
def sub(a, b): return n(a) - n(b)
def mul(a, b): return n(a) * n(b)
def div(a: Any, b: Any) -> float:
x, y = n(a), n(b)
if y == 0:
return math.nan if x == 0 or math.isnan(x) else math.copysign(math.inf, x) * math.copysign(1, y)
return x / y
def and_(vs: list) -> Any:
last = None
for v in vs:
if not t(v):
return v
last = v
return last
def or_(vs: list) -> Any:
last = None
for v in vs:
if t(v):
return v
last = v
return last
def coalesce(vs: list) -> Any:
return next((v for v in vs if v is not None), None)
def def_(v: Any, d: Any) -> Any:
"""a prop with its default: the default when the prop is None or missing"""
return d if v is None else v
def l(v: Any) -> list:
return v if isinstance(v, list) else []
def len_(v: Any) -> int:
return len(v) if isinstance(v, str) else len(l(v))
def spread(base: Any, fields: dict) -> dict:
out = dict(base) if isinstance(base, dict) else {}
out.update(fields)
return out
def str_(v: Any) -> Any:
return None if v is None else s(v)
def has(v: Any) -> bool:
return v is not None
def cnv(vs: list) -> str:
return merge([s(v) for v in vs if t(v)])
def tpl(tmpl: Any, vals: list) -> str:
return re.sub(r"\{(\d+)\}", lambda m: s(vals[int(m.group(1))]) if int(m.group(1)) < len(vals) else "", s(tmpl))
def _group(f: float, decimals: int) -> str:
whole, _, frac = f"{abs(f):.{decimals}f}".partition(".")
out = f"{int(whole):,}"
frac = frac.rstrip("0")
if frac:
out += "." + frac
if f < 0 and out != "0":
out = "-" + out
return out
def num(v: Any) -> str:
return _group(n(v), 3)
_CURRENCY = {"USD": "$", "EUR": "\u20ac", "GBP": "\u00a3", "JPY": "\u00a5", "INR": "\u20b9", "CAD": "CA$", "AUD": "A$"}
def minor_digits(c: str) -> int:
return 0 if c in ("JPY", "KRW") else 2
def money(amount: Any, currency: Any) -> str:
"""integer minor units (Codex v0.4: 1250 = 12.50) -> "$12.50"; whole amounts without the fraction"""
c = s(currency)
sym = _CURRENCY.get(c, c + "\u00a0")
minor = int(_round_half_away(n(amount)))
sign = "-" if minor < 0 else ""
minor = abs(minor)
d = minor_digits(c)
whole, rest = divmod(minor, 10 ** d)
out = sign + sym + _group(float(whole), 0)
if d and rest:
out += "." + str(rest).zfill(d)
return out
def at(d: Any, key: Any) -> str:
v = get(d, [s(key)])
return s(v) if v is not None else s(key)
def page_window(page_v: Any, pages_v: Any) -> list:
page, pages = int(n(page_v)), int(n(pages_v))
keep = {x for x in (1, pages, page - 1, page, page + 1) if 1 <= x <= pages}
out: list = []
prev = 0
for x in range(1, pages + 1):
if x not in keep:
continue
if x - prev > 1:
out.append(None)
out.append(x)
prev = x
return out
def fit_cols(cols_v: Any, n_v: Any) -> str:
cols, cnt = s(cols_v), int(n(n_v))
m = re.fullmatch(r"(-?\d+)-(-?\d+)", cols)
if not m:
return cols
lo, hi = int(m.group(1)), int(m.group(2))
if cnt >= hi:
return cols
known = {"1-2", "1-3", "1-4", "2-3", "2-4", "2-6", "3-6"}
for k in range(max(lo, cnt), lo, -1):
if f"{lo}-{k}" in known:
return f"{lo}-{k}"
return str(min(max(cnt, 1), lo))
def uniq(v: Any) -> str:
parts = s(v).split(", ")
return ", ".join(p for idx, p in enumerate(parts) if idx == 0 or p.lower() != parts[idx - 1].lower())
def words(v: Any) -> list: return s(v).split(" ")
def nbsp(v: Any) -> str: return s(v).replace(" ", "\u00a0")
def nth(lst: Any, idx: Any) -> Any:
xs, k = l(lst), int(n(idx))
return xs[k] if 0 <= k < len(xs) else None
def range_(c: Any) -> list: return list(range(max(0, int(n(c)))))
def max_(vs: list) -> float: return max([-math.inf] + [n(v) for v in vs])
def min_(vs: list) -> float: return min([math.inf] + [n(v) for v in vs])
def round_(v: Any) -> float: return float(math.floor(n(v) + 0.5))
def count(items: Any, f: Any) -> int:
return sum(1 for it in l(items) if t(get(it, [s(f)])))
def where(items: Any, f: Any, value: Any) -> list:
if not t(value):
return l(items)
return [it for it in l(items) if eq(get(it, [s(f)]), value)]
def match(items: Any, f: Any, query: Any) -> list:
if not t(query):
return l(items)
q = s(query).lower()
return [it for it in l(items) if q in s(get(it, [s(f)])).lower()]
def pick(items: Any, ident: Any) -> Any:
return next((it for it in l(items) if eq(get(it, ["id"]), ident)), None)
def sum_by(items: Any, a: str, b: str) -> float:
return sum((n(get(it, [a])) * n(get(it, [b])) for it in l(items)), 0.0)
def first_of(items: Any, f: str) -> Any:
xs = l(items)
if not xs:
return ""
v = get(xs[0], [f])
return "" if v is None else v
def max_by(items: Any, f: str) -> float:
return max([0.0] + [n(get(it, [f])) for it in l(items)])
def css(triples: list) -> str:
return ";".join(s(triples[k]) + ":" + css_value(triples[k + 1]) + s(triples[k + 2]) for k in range(0, len(triples) - 2, 3))
def _compound_hits(c: dict, pick_: Any) -> bool:
return all(pick_(k) in str(w).split("|") for k, w in c.items() if k != "class")
def recipe(path: str, sel: dict) -> str:
"""the class string of a recipe table for a selection (organisms: base, each key, the matching compounds)"""
r = load_json(path)
def pick_(k: str) -> str:
v = s(sel.get(k)).strip()
return v or str((r.get("defaults") or {}).get(k, "")).strip()
parts = [str(r.get("base", ""))]
parts += [str((r.get("byKey") or {}).get(k, {}).get(pick_(k), "")) for k in r.get("keys", [])]
parts += [str(c.get("class", "")) for c in r.get("compound", []) or [] if _compound_hits(c, pick_)]
return merge([p.strip() for p in parts if p.strip()])
def preset(path: str, keys: list) -> Any:
return get(get(load_json(path), ["values"]), keys)
def attrs(kv: list) -> dict:
"""free DOM attributes from (name, value) pairs, as React prints them"""
out: dict = {}
for k in range(0, len(kv) - 1, 2):
name, v = s(kv[k]), kv[k + 1]
if v is None or not is_safe_attr_name(name):
continue
if not isinstance(v, bool):
v = attr_value(name, v)
if isinstance(v, bool):
if name.startswith("data-") or name.startswith("aria-"):
out[name] = s(v)
elif v:
out[name] = True
continue
out[name] = s(v)
return out
def attr_html(a: Any) -> str:
"""an attribute map as markup: ` name="value"`, a bare name for True, nothing for None and False"""
if not isinstance(a, dict):
return ""
out = ""
for k, v in a.items():
if v is None or v is False or not is_safe_attr_name(str(k)):
continue
name = str(k)
out += f" {name}" if v is True else f' {name}="{html.escape(s(attr_value(name, v)), quote=True)}"'
return out
# ------------------------------------------------------------------ bricks (expr.go, utils.go, tags.go)
def is_set_str(v: Any) -> bool: return s(v).strip() != ""
def default_if_empty(v: Any, fallback: str) -> str:
x = s(v).strip()
return x or fallback
def map_or(v: Any, mapping: dict, fallback: str, lower: bool = False) -> str:
x = s(v).strip()
if lower:
x = x.lower()
return str(mapping[x]) if x in mapping else fallback
def int_map_or(v: Any, mapping: dict, fallback: str) -> str:
k = i(v)
return str(mapping[k]) if k in mapping else fallback
def bool_str(v: Any) -> str: return "true" if t(v) else "false"
def concat_trim(parts: list) -> str: return "".join(s(p).strip() for p in parts)
def cn(parts: list) -> str: return merge([s(p) for p in parts])
def compose(path: str, selection: dict, extra: list) -> str:
"""the brick class contract: recipe base, the selected variants (defaults for empty), compounds, then the tail"""
r = load_json(path)
defaults = r.get("defaults") or {}
def pick_(k: str) -> str:
c = s(selection.get(k)).strip()
return c or str(defaults.get(k, "")).strip()
parts = [str(r["base"]).strip()] if str(r.get("base", "")).strip() else []
for key in r.get("keys", []):
choices = (r.get("byKey") or {}).get(key)
if choices is None:
continue
choice = pick_(key)
if not choice:
if choices:
raise ValueError(f"[compose] missing default for key {key}")
continue
if str(choices.get(choice, "")).strip():
parts.append(str(choices[choice]))
for c in r.get("compound", []) or []:
if _compound_hits(c, pick_) and str(c.get("class", "")).strip():
parts.append(str(c["class"]))
return cn(parts + list(extra))
def resolve_tag(tag: Any, fallback: str, allowed: list) -> str:
x = s(tag).strip().lower()
return x if x and x in allowed else fallback
def title_tag(level: Any) -> str:
k = i(level)
return f"h{k}" if 1 <= k <= 6 else "h2"
def lucide(name: Any) -> str:
"""the inner markup of a Lucide glyph: its nodes with attributes in name order (circle for an unknown name)"""
icons = load_json("icons/lucide-icons.json")["icons"]
nodes = icons.get(s(name)) or icons["circle"]
out = ""
for tag, a in nodes:
out += "<" + tag + "".join(f' {k}="{html.escape(str(a[k]), quote=True)}"' for k in sorted(a)) + "></" + tag + ">"
return out
Jinja2>=3.1,<4
MarkupSafe>=2.1
# Code generated by @ui8kit/codegen. DO NOT EDIT.
"""UI8Kit primitives for Jinja2.
`environment()` returns a Jinja2 Environment over the generated folder with
the `ui_*` helpers and one `<name>_classes(p)` global per part (the
server-composition escape hatch: Jinja2 has no asChild).
Templates are `ui/<brick>/<part>.html.j2`, rendered with `p` (canonical
PascalCase props, e.g. {"Variant": "outline", "Class": "...", "Attrs": {...}})
and `children` (pre-rendered markup).
SECURITY: `children` is printed with `|safe` — it is trusted HTML. Never pass
unescaped user input as `children`; escape it first (markupsafe.escape) or
render it through another template. Props are always autoescaped.
"""
from __future__ import annotations
import functools
import os
from typing import Any
from jinja2 import ChainableUndefined, Environment, FileSystemLoader
from jinja2.runtime import Undefined
from markupsafe import Markup
from . import runtime as rt
from .classes import CLASS_EXPRESSIONS
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
def _plain(v: Any) -> Any:
if isinstance(v, Undefined):
return None
if isinstance(v, list):
return [_plain(x) for x in v]
return v
def _wrap(f: Any, safe: bool = False) -> Any:
@functools.wraps(f)
def call(*args: Any) -> Any:
out = f(*[_plain(a) for a in args])
return Markup(out) if safe else out
return call
_NAMES = {"def": "def_"}
_PLAIN = [
"def", "field", "s", "truthy", "eq", "is_set_str", "default_if_empty", "map_or", "int_map_or",
"bool_str", "opt_bool_str", "concat_trim", "cn", "compose", "resolve_tag", "safe_url", "has_attr",
]
VOID_TAGS = frozenset(
["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr"]
)
def environment(root: str | None = None, **options: Any) -> Environment:
"""An Environment over the generated jinja2 folder (autoescape on, chainable undefined)."""
root = root or ROOT
rt.set_root(root)
env = Environment(loader=FileSystemLoader(root), autoescape=True, undefined=ChainableUndefined, **options)
for name in _PLAIN:
env.globals["ui_" + name] = _wrap(getattr(rt, _NAMES.get(name, name)))
env.globals["ui_attr_html"] = _wrap(rt.attr_html, safe=True)
env.globals["ui_is_void"] = lambda t: str(t) in VOID_TAGS
for name, source in CLASS_EXPRESSIONS.items():
env.globals[name] = _classes_fn(env, source)
return env
def _classes_fn(env: Environment, source: str) -> Any:
expr = env.compile_expression(source)
def classes(p: Any = None) -> str:
"""Composes the part's classes without rendering (recipe → static → extra → state → Class)."""
return str(expr(p=_plain(p) or {}) or "")
return classes
# Code generated by @ui8kit/codegen. DO NOT EDIT.
"""Classes contract of every part as a Jinja expression over `p`.
`environment()` registers each entry as a global `<name>_classes(p)` — the
server-composition escape hatch for custom root elements (no asChild in
Jinja2): `<a class="{{ button_classes({'Variant': 'outline'}) }}" href="/x">`.
"""
CLASS_EXPRESSIONS = {
"box_classes": "ui_cn([ui_def(p['Class'], '')])",
"text_classes": "ui_cn([ui_def(p['Class'], '')])",
"button_classes": "ui_cn([ui_def(p['Class'], '')])",
"link_classes": "ui_cn([ui_def(p['Class'], '')])",
"label_classes": "ui_cn([ui_def(p['Class'], '')])",
"form_classes": "ui_cn([ui_def(p['Class'], '')])",
"input_classes": "ui_cn([ui_def(p['Class'], '')])",
"textarea_classes": "ui_cn([ui_def(p['Class'], '')])",
"select_classes": "ui_cn(['pr-2', ui_def(p['Class'], '')])",
"checkbox_classes": "ui_cn([ui_def(p['Class'], '')])",
"radio_classes": "ui_cn([ui_def(p['Class'], '')])",
"switch_classes": "ui_cn([ui_def(p['Class'], '')])",
"image_classes": "ui_cn([ui_def(p['Class'], '')])",
"picture_classes": "ui_cn([ui_def(p['Class'], '')])",
"icon_classes": "ui_compose('ui/icon/icon.variants.json', {'size': ui_def(p['Size'], '')}, [ui_def(p['Class'], '')])",
"dialog_classes": "ui_cn([ui_def(p['Class'], '')])",
"disclosure_classes": "ui_cn([ui_def(p['Class'], '')])",
"summary_classes": "ui_cn([ui_def(p['Class'], '')])",
"meter_classes": "ui_cn([ui_def(p['Class'], '')])",
"progress_classes": "ui_cn([ui_def(p['Class'], '')])",
"separator_classes": "ui_cn([ui_def(p['Class'], '')])",
}
# Code generated by @ui8kit/codegen. DO NOT EDIT.
"""cn: class fragments joined with tailwind-merge conflict resolution (the last class of a group wins, and a class removes
the earlier classes of the groups it overrides: p-2 removes px-4, not the reverse). Port of cn_merge.go."""
from __future__ import annotations
_DISPLAY = {"block", "inline", "inline-block", "inline-flex", "flex", "grid", "contents", "hidden"}
_PREFIXES = [
("gap-x-", "gap-x"), ("gap-y-", "gap-y"), ("items-", "align-items"), ("justify-", "justify-content"),
("self-", "align-self"), ("content-", "align-content"), ("overflow-x-", "overflow-x"), ("overflow-y-", "overflow-y"),
("inset-x-", "inset-x"), ("inset-y-", "inset-y"), ("min-w-", "min-width"), ("min-h-", "min-height"),
("max-w-", "max-width"), ("max-h-", "max-height"), ("shadow-", "shadow"), ("ring-", "ring"), ("rounded-", "rounded"),
("leading-", "leading"), ("tracking-", "tracking"), ("opacity-", "opacity"), ("z-", "z"), ("top-", "top"),
("right-", "right"), ("bottom-", "bottom"), ("left-", "left"),
]
_TEXT_SIZES = {"text-xs", "text-sm", "text-base", "text-lg", "text-xl"} | {f"text-{n}xl" for n in range(2, 10)}
_WEIGHTS = {f"font-{w}" for w in ("thin", "extralight", "light", "normal", "medium", "semibold", "bold", "extrabold", "black")}
def _is_number(s: str) -> bool:
if s.startswith("["):
return True
return s != "" and all(c in "0123456789." for c in s)
def _split_variant(token: str) -> tuple[str, str]:
depth, cut = 0, -1
for i, c in enumerate(token):
if c == "[":
depth += 1
elif c == "]":
depth = max(0, depth - 1)
elif c == ":" and depth == 0:
cut = i
core = token if cut == -1 else token[cut + 1:]
core = core[1:] if core.startswith("!") else core
return ("" if cut == -1 else token[:cut + 1]), core
def _has_direction(core: str, kind: str) -> bool:
return any(core.startswith(kind + d) for d in ("x-", "y-", "t-", "r-", "b-", "l-", "s-", "e-"))
def _space_axis(core: str, kind: str, n: str) -> list[str]:
if core.startswith(kind + "x-"):
return [f"{n}-x", f"{n}-r", f"{n}-l", f"{n}-s", f"{n}-e"]
if core.startswith(kind + "y-"):
return [f"{n}-y", f"{n}-t", f"{n}-b"]
for s in "trbl":
if core.startswith(kind + s + "-"):
return [f"{n}-{s}"]
return []
def _groups(core: str) -> list[str]:
if core in _DISPLAY:
return ["display"]
if core in ("flex-row", "flex-col", "flex-row-reverse", "flex-col-reverse"):
return ["flex-direction"]
if core in ("static", "relative", "absolute", "fixed", "sticky"):
return ["position"]
if core in ("isolate", "isolation-auto"):
return ["isolation"]
if core in ("object-contain", "object-cover", "object-fill", "object-none", "object-scale-down"):
return ["object-fit"]
if core in ("object-bottom", "object-center", "object-left", "object-left-bottom", "object-left-top", "object-right", "object-right-bottom", "object-right-top", "object-top"):
return ["object-position"]
if core.startswith("aspect-"):
return ["aspect"]
# ring-offset-N (width) and ring-offset-<color> are their own groups
if core.startswith("ring-offset-"):
return ["ring-offset-width" if _is_number(core[12:]) else "ring-offset-color"]
for kind in ("inset-ring", "ring"):
if core == kind:
return [kind + "-width"]
if core.startswith(kind + "-"):
return [kind + ("-width" if _is_number(core[len(kind) + 1:]) else "-color")]
for p, g in _PREFIXES:
if core.startswith(p):
return [g]
if core.startswith("gap-"):
return ["gap", "gap-x", "gap-y"]
if core.startswith("inset-"):
return ["inset", "inset-x", "inset-y", "top", "right", "bottom", "left"]
if core.startswith("overflow-"):
return ["overflow", "overflow-x", "overflow-y"]
if core == "border" or (core.startswith("border-") and _is_number(core[7:])):
return ["border-width"] + [f"border-w-{s}" for s in "xytrblse"]
if len(core) >= 8 and core.startswith("border-") and core[7] in "xytrblse" and (len(core) == 8 or (core[8] == "-" and _is_number(core[9:]))):
side = core[7]
if side == "x":
return ["border-w-x", "border-w-r", "border-w-l", "border-w-s", "border-w-e"]
if side == "y":
return ["border-w-y", "border-w-t", "border-w-b"]
return ["border-w-" + side]
if core in ("text-left", "text-center", "text-right", "text-justify", "text-start", "text-end"):
return ["text-align"]
if core == "rounded":
return ["rounded"]
if core in ("shadow", "shadow-none"):
return ["shadow"]
if core in ("flex-1", "flex-auto", "flex-none", "flex-initial"):
return ["flex-size", "flex-grow", "flex-shrink", "flex-basis"]
if core == "grow" or core.startswith("grow-"):
return ["flex-grow"]
if core in ("shrink", "shrink-0"):
return ["flex-shrink"]
if core.startswith("size-"):
return ["size", "width", "height"]
if core.startswith("w-"):
return ["width"]
if core.startswith("h-"):
return ["height"]
for kind, n in (("p", "padding"), ("m", "margin")):
if core.startswith(kind + "-") and not _has_direction(core, kind):
return [n] + [f"{n}-{s}" for s in "xytrblse"]
axis = _space_axis(core, kind, n)
if axis:
return axis
if core.startswith("bg-"):
return ["bg"]
if core in _TEXT_SIZES or (core.startswith("text-[") and len(core) > 6 and (core[6].isdigit() or core[6] == ".")):
return ["text-size", "leading"]
if core.startswith("text-"):
return ["text-color"]
if core in _WEIGHTS:
return ["font-weight"]
return []
def merge(classes: list[str]) -> str:
kept: list[tuple[str, str]] = []
for chunk in classes:
for token in str(chunk).split():
prefix, core = _split_variant(token)
key = ""
removes: list[str] = []
if core:
g = _groups(core)
if g:
key, removes = prefix + g[0], g[1:]
else:
key = "=" + token
if key:
drop = {key} | {prefix + r for r in removes}
kept = [it for it in kept if it[1] not in drop]
kept.append((token, key))
return " ".join(t for t, _ in kept)
# Code generated by @ui8kit/codegen. DO NOT EDIT.
"""Helpers of the generated Jinja2 templates (registered as `ui_*` globals).
Ported from the xgen Jinja2 runtime (tag xgen-archive-2026-10-23,
xgen/runtimes/jinja2/assets/py/ui8kit_jinja/runtime.py), trimmed to the brick
helpers the 17 primitives use. Semantics mirror the canonical renderer
(src/domain/render.ts) and runtime/go: trimmed strings, decision tables,
recipe composition, tailwind-merge-style class merging. Every helper is
None-safe.
"""
from __future__ import annotations
import html
import re
import json
import math
import os
from typing import Any
from .cn_merge import merge
_ROOT = ""
_JSON: dict[str, Any] = {}
def set_root(root: str) -> None:
global _ROOT
_ROOT = root
def load_json(path: str) -> Any:
if path not in _JSON:
with open(os.path.join(_ROOT, path), encoding="utf-8") as f:
_JSON[path] = json.load(f)
return _JSON[path]
def _num(v: Any) -> bool:
return isinstance(v, (int, float)) and not isinstance(v, bool)
def def_(v: Any, d: Any) -> Any:
"""a prop with its default: the default when the prop is None or missing"""
return d if v is None else v
def field(item: Any, name: str, zero: Any) -> Any:
"""a field of a record item; the key is matched without regard to case (as Go json does)"""
if not isinstance(item, dict):
return zero
if name in item:
return zero if item[name] is None else item[name]
for k, v in item.items():
if str(k).lower() == name.lower():
return zero if v is None else v
return zero
def fmt_num(f: Any) -> str:
"""String(n) of JavaScript"""
if isinstance(f, int):
return str(f)
if math.isnan(f):
return "NaN"
if math.isinf(f):
return "Infinity" if f > 0 else "-Infinity"
if f == math.floor(f) and abs(f) < 1e21:
return "%d" % int(f)
return repr(f)
def s(v: Any) -> str:
if v is None:
return ""
if isinstance(v, str):
return v
if isinstance(v, bool):
return "true" if v else "false"
if _num(v):
return fmt_num(v)
return json.dumps(v, separators=(",", ":"), ensure_ascii=False)
def truthy(v: Any) -> bool:
"""canonical truthiness (render.ts): string non-blank, number > 0, bool itself"""
if v is None:
return False
if isinstance(v, bool):
return v
if isinstance(v, str):
return v.strip() != ""
if _num(v):
return v > 0
return bool(v)
def eq(a: Any, b: Any) -> bool:
"""strict equality (===)"""
if _num(a) or _num(b):
return _num(a) and _num(b) and float(a) == float(b)
if a is None:
return b is None
if isinstance(a, bool) or isinstance(b, bool):
return isinstance(a, bool) and isinstance(b, bool) and a == b
if isinstance(a, str):
return isinstance(b, str) and a == b
return False
URL_ATTRS = frozenset(["href", "src", "action", "formaction", "poster", "cite", "background", "xlink:href"])
_DATA_IMAGE = re.compile(r"^data:image/(png|jpeg|gif|webp|avif|svg\+xml)[;,]")
def safe_url(v: Any, data_image: bool = False) -> str:
"""URL attribute value: "" for javascript:, vbscript: and data: (ASCII whitespace/control chars removed, case-insensitive);
data_image (only <img src>) allows data:image/(png|jpeg|gif|webp|avif|svg+xml)."""
t = s(v)
k = "".join(c for c in t if ord(c) > 0x20).lower()
if data_image and _DATA_IMAGE.match(k):
return t
return "" if k.startswith(("javascript:", "vbscript:", "data:")) else t
def has_attr(a: Any, name: str) -> bool:
"""the caller's Attrs set name (case-insensitive): Attrs win over the named attribute"""
return isinstance(a, dict) and any(str(k).lower() == name for k in a)
def attr_html(a: Any, img: bool = False, blank: Any = ()) -> str:
"""the Attrs escape hatch as markup: ` name="value"`, a bare name for True, nothing for None and False;
an unsafe URL (data:image allowed in <img src> when img) or a blank optional attribute (blank) is omitted"""
if not isinstance(a, dict):
return ""
blank = list(blank or ())
out = ""
for k, v in a.items():
if v is None or v is False:
continue
key = str(k).lower()
if isinstance(v, str) and v.strip() == "" and key in blank:
continue
if isinstance(v, str) and v != "" and key in URL_ATTRS and safe_url(v, img and key == "src") == "":
continue
name = html.escape(str(k), quote=True)
out += f" {name}" if v is True else f' {name}="{html.escape(s(v), quote=True)}"'
return out
def is_set_str(v: Any) -> bool:
return s(v).strip() != ""
def default_if_empty(v: Any, fallback: str) -> str:
x = s(v).strip()
return x or fallback
def map_or(v: Any, mapping: dict, fallback: str, lower: bool = False) -> str:
x = s(v).strip()
if lower:
x = x.lower()
return str(mapping[x]) if x in mapping else fallback
def int_map_or(v: Any, mapping: dict, fallback: str) -> str:
try:
k = int(v)
except (TypeError, ValueError):
k = 0
return str(mapping[k]) if k in mapping else fallback
def bool_str(v: Any) -> str:
return "true" if truthy(v) else "false"
def opt_bool_str(v: Any) -> str:
"""Tri-state ARIA state: "true"/"false" when set, "" when None (attribute omitted)."""
return "" if v is None else ("true" if truthy(v) else "false")
def concat_trim(parts: list) -> str:
return "".join(s(p).strip() for p in parts)
def cn(parts: list) -> str:
return merge([s(p) for p in parts])
def _compound_hits(c: dict, pick_: Any) -> bool:
return all(pick_(k) in str(w).split("|") for k, w in c.items() if k != "class")
def compose(path: str, selection: dict, extra: list) -> str:
"""the brick class contract: recipe base, the selected variants (defaults for empty), compounds, then the tail"""
r = load_json(path)
defaults = r.get("defaults") or {}
def pick_(k: str) -> str:
c = s(selection.get(k)).strip()
return c or str(defaults.get(k, "")).strip()
parts = [str(r["base"]).strip()] if str(r.get("base", "")).strip() else []
for key in r.get("keys", []):
choices = (r.get("byKey") or {}).get(key)
if choices is None:
continue
choice = pick_(key)
if not choice:
if choices:
raise ValueError(f"[compose] missing default for key {key}")
continue
if str(choices.get(choice, "")).strip():
parts.append(str(choices[choice]))
for c in r.get("compound", []) or []:
if _compound_hits(c, pick_) and str(c.get("class", "")).strip():
parts.append(str(c["class"]))
return cn(parts + list(extra))
def resolve_tag(tag: Any, fallback: str, allowed: list) -> str:
x = s(tag).strip().lower()
return x if x and x in allowed else fallback
Props
Names and types come from the xgen specs of the source. Standard HTML attributes (id, role, tabIndex, aria-*) pass through to the root element; the class prop is className in React.
No props data for this item.
Used in
- about-company
- about-me
- action-group
- activity-feed
- add-icon
- add-qty
- announcement-bar
- app-main
- app-shell
- article-block
- article-body
- auth-card
- auth-form
- auth-layout
- avatar
- backdrop
- badge-square
- bar-chart
- before-after
- bento-grid
- bottom-nav
- bulk-bar
- cart-count
- cart-drawer
- cart-list
- cart-summary-card
- cart-table
- category-nav
- chart-panel
- checklist
- checkout-form
- checkout-step
- checkout-submit
- code-window
- combo-builder
- compare-mark
- comparison-table
- contact-form
- cookie-banner
- credit-packs
- cta-actions
- cta-band
- cta-banner
- cta-proof
- cta-proof-items
- cut-cards
- dashboard-overview
- dashboard-shell
- delivery-info
- dish-bento
- dish-card
- dish-cart-grid
- dish-compare
- dish-showcase
- dish-strip
- drawer-lines
- dropdown-item
- editor-tab
- empty-panel
- empty-state
- error-page
- faq-cards
- faq-disclosures
- faq-finder
- faq-help
- faq-list
- faq-split
- feature-accordion
- feature-cards
- feature-grid
- feature-metric-cards
- feature-pairs
- feature-rows
- feature-showcase
- feature-split
- feature-stat-rows
- feature-sticky
- feature-tabs
- field
- figure-block
- file-tree
- file-tree-item
- footer-brand
- footer-card
- footer-channels
- footer-columns
- footer-contacts
- footer-figures
- footer-group-cards
- footer-link-columns
- footer-points
- footer-signup-card
- footer-sitemap
- footer-split
- grill-builder
- grocery-list
- hero-badge
- hero-classic
- hero-head
- hero-prompt
- hero-split
- hero-split-extras
- hero-split-media
- icon-tab
- icon-tabs
- icon-wall
- job-board
- job-cards
- kanban-board
- lightbox-gallery
- lightbox-stage
- logo-cloud
- logo-ribbon
- logo-sidebar
- logo-slot
- meat-cards
- media-contacts
- media-figures
- media-frame
- media-list
- media-posts
- media-review
- media-steps
- media-topics
- mega-menu
- member-row
- menu-board
- menu-entry
- menu-row
- menu-section-nav
- meter-row
- metric-row
- milestone-timeline
- nav-actions
- nav-bar
- nav-bar-menu
- nav-block
- nav-item
- nav-item-row
- nav-links
- newsletter-form
- notice
- number-field
- offer-media
- option-chips
- order-rows
- order-summary
- order-table
- over-media
- page-aside
- page-crumbs
- page-header
- page-intro
- page-trail
- pager
- panel
- payment-options
- photo-gallery
- pill
- pizza-picker
- post-actions
- post-author
- post-card
- post-feature
- post-grid
- post-header
- post-mini-card
- post-outline
- post-overlay-card
- post-showcase
- post-split
- post-stats
- post-tags
- pricing-card
- pricing-tiers
- product-card
- product-detail
- product-gallery
- product-grid
- product-info
- product-price
- profile-form
- project-grid
- project-tiles
- prompt-composer
- proof-band
- quick-order
- quote-card
- quote-figures
- quote-logo-tiles
- quote-proof
- quote-rating-panel
- quote-slot
- quote-split
- range-field
- rating
- recipe-kits
- region
- reservation-form
- restaurant-menu
- review-list
- search-field
- search-palette
- section-box
- section-column
- section-frame
- section-head
- section-header
- shell-content
- shell-footer
- shell-sidebar
- shell-topbar
- shopping-cart
- side-checks
- sidebar-nav
- sidebar-panel
- signup-wizard
- site-footer
- site-header
- sitemap-footer
- skeleton-layout
- slot-board
- slot-grid
- stat-figure
- stat-tile
- stats-band
- stepper
- steps-list
- store-hero
- store-locations
- story-dots
- story-panel
- story-tabs
- support-channels
- sushi-sets
- switcher
- switcher-item
- table-toolbar
- team-grid
- template-grid
- testimonial-grid
- timeline
- topic-chips
- tour-callout
- usage-calculator
- usp-strip
- veggie-box
- video-grid
- video-modal
- week-menu
- weighted-title
- zone-rows
- zone-table