ain-ui 0.2.1 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/NOTICE +37 -0
  2. package/README.md +179 -76
  3. package/dist/agent.d.ts +131 -0
  4. package/dist/agent.js +802 -0
  5. package/dist/ainui.d.ts +15 -1
  6. package/dist/ainui.js +59 -16
  7. package/dist/basic.d.ts +5 -47
  8. package/dist/basic.js +11 -25
  9. package/dist/catalog/standard.gen.d.ts +5 -0
  10. package/dist/catalog/standard.gen.js +6 -0
  11. package/dist/catalog-v1.json +2560 -0
  12. package/dist/catalog.json +19924 -2047
  13. package/dist/chat.js +6 -7
  14. package/dist/expression.d.ts +23 -0
  15. package/dist/expression.js +222 -0
  16. package/dist/index.d.ts +2 -0
  17. package/dist/index.js +2 -0
  18. package/dist/macros.d.ts +12 -0
  19. package/dist/macros.js +57 -0
  20. package/dist/payment.js +6 -7
  21. package/dist/pickers.d.ts +158 -0
  22. package/dist/pickers.js +110 -0
  23. package/dist/protocol.d.ts +100 -0
  24. package/dist/protocol.js +232 -0
  25. package/dist/react/ain.d.ts +1 -0
  26. package/dist/react/ain.js +225 -0
  27. package/dist/react/catalog.d.ts +9 -0
  28. package/dist/react/catalog.js +23 -0
  29. package/dist/react/core.d.ts +84 -0
  30. package/dist/react/core.js +158 -0
  31. package/dist/react/functions.d.ts +2 -0
  32. package/dist/react/functions.js +29 -0
  33. package/dist/react/standard/composites.d.ts +1 -0
  34. package/dist/react/standard/composites.js +110 -0
  35. package/dist/react/standard/data.d.ts +1 -0
  36. package/dist/react/standard/data.js +481 -0
  37. package/dist/react/standard/feedback.d.ts +11 -0
  38. package/dist/react/standard/feedback.js +111 -0
  39. package/dist/react/standard/inputs.d.ts +5 -0
  40. package/dist/react/standard/inputs.js +467 -0
  41. package/dist/react/standard/layout.d.ts +5 -0
  42. package/dist/react/standard/layout.js +104 -0
  43. package/dist/react/standard/media.d.ts +33 -0
  44. package/dist/react/standard/media.js +208 -0
  45. package/dist/react/standard/rich.d.ts +1 -0
  46. package/dist/react/standard/rich.js +146 -0
  47. package/dist/react/standard/text.d.ts +9 -0
  48. package/dist/react/standard/text.js +209 -0
  49. package/dist/react/surface.d.ts +44 -0
  50. package/dist/react/surface.js +134 -0
  51. package/dist/react.d.ts +3 -36
  52. package/dist/react.js +3 -240
  53. package/dist/renderer.d.ts +1 -1
  54. package/dist/renderer.js +307 -4
  55. package/dist/styles.css +850 -0
  56. package/package.json +28 -11
@@ -0,0 +1,208 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
+ /** Standard catalog — media: images, icons, vector drawings, video, audio, sandboxed HTML. */
4
+ import React, { useEffect, useState } from "react";
5
+ import { color, cx, mediaUrl, px, radius, safeUrl, standard, surfaceColor, useHost } from "../core.js";
6
+ const str = (v) => (typeof v === "string" ? v : typeof v === "number" && Number.isFinite(v) ? String(v) : "");
7
+ const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : undefined);
8
+ const list = (v) => (Array.isArray(v) ? v : []);
9
+ const obj = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : {});
10
+ const A2UI_ICONS = {
11
+ arrowBack: "arrow-left", arrowForward: "arrow-right", check: "check", close: "x", delete: "trash-2", edit: "pencil", search: "search", add: "plus",
12
+ menu: "menu", home: "home", settings: "settings", info: "info", warning: "triangle-alert", error: "circle-alert", favorite: "heart",
13
+ favoriteOff: "heart-off", star: "star", starHalf: "star-half", starOff: "star-off", share: "share-2", download: "download", upload: "upload", send: "send", person: "user",
14
+ calendarToday: "calendar", event: "calendar", locationOn: "map-pin", phone: "phone", call: "phone", mail: "mail", lock: "lock", lockOpen: "lock-open",
15
+ visibility: "eye", visibilityOff: "eye-off", moreVert: "ellipsis-vertical", moreHoriz: "ellipsis", refresh: "refresh-cw", attachFile: "paperclip",
16
+ folder: "folder", payment: "credit-card", shoppingCart: "shopping-cart", help: "circle-help", notifications: "bell", notificationsOff: "bell-off",
17
+ camera: "camera", photo: "image", image: "image", accountCircle: "circle-user", print: "printer", play: "play", pause: "pause", stop: "square",
18
+ };
19
+ const SHAPES = new Set(["path", "circle", "rect", "line", "polyline", "polygon", "ellipse"]);
20
+ let lucide;
21
+ let loaded;
22
+ const loadIcons = () => (lucide ??= import("lucide").then((m) => (loaded = (m.icons ?? {})), () => (loaded = {})));
23
+ const pascal = (name) => name.split(/[-_\s]+/).filter(Boolean).map((p) => p[0].toUpperCase() + p.slice(1)).join("");
24
+ function findIcon(icons, name) {
25
+ const mapped = A2UI_ICONS[name] ?? name;
26
+ const found = icons[pascal(mapped)] ?? icons[pascal(mapped.replace(/([a-z])([A-Z0-9])/g, "$1-$2"))];
27
+ return Array.isArray(found) ? found : undefined;
28
+ }
29
+ const ICON_SIZE = { sm: 14, md: 18, lg: 24, xl: 32 };
30
+ const STROKE = { normal: 2, medium: 2.25, semibold: 2.5, bold: 3 };
31
+ /** A Lucide icon (kebab-case or A2UI name) or `{svgPath}`; an empty svg of the same size until the icon data loads. */
32
+ export function IconGlyph({ name, size = 18, label, strokeWidth = 2, className, style }) {
33
+ const [icons, setIcons] = useState(loaded);
34
+ const wanted = typeof name === "string" ? name.trim() : "";
35
+ useEffect(() => {
36
+ if (!wanted || icons)
37
+ return;
38
+ let alive = true;
39
+ void loadIcons().then((set) => { if (alive)
40
+ setIcons(set); });
41
+ return () => { alive = false; };
42
+ }, [wanted, icons]);
43
+ const path = typeof obj(name).svgPath === "string" ? obj(name).svgPath : "";
44
+ const node = !path && wanted && icons ? findIcon(icons, wanted) : undefined;
45
+ return _jsx("svg", { className: cx("ainui-icon", className), width: size, height: size, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: strokeWidth, strokeLinecap: "round", strokeLinejoin: "round", style: style, ...(label ? { role: "img", "aria-label": label } : { "aria-hidden": true }), children: path ? _jsx("path", { d: path }) : node?.map(([tag, attrs], i) => (SHAPES.has(tag) ? React.createElement(tag, { key: i, ...attrs }) : null)) });
46
+ }
47
+ const Icon = standard("Icon", ({ props }) => _jsx(IconGlyph, { name: props.name, label: str(props.label) || undefined, size: num(props.size) ?? ICON_SIZE[props.size] ?? ICON_SIZE.md, strokeWidth: STROKE[props.strokeWeight] ?? 2, className: cx(props.inline && "ainui-icon-inline"), style: { color: props.color === "default" || props.color === "prose" ? undefined : color(props.color), flex: "none" } }));
48
+ /** A full-screen view of one image of a set. A click or Escape closes it; arrows move within the set. */
49
+ export function Lightbox({ images, index, onIndex, onClose }) {
50
+ const count = images.length;
51
+ const at = Math.max(0, Math.min(count - 1, index));
52
+ const move = (by) => { if (count > 1)
53
+ onIndex?.((at + by + count) % count); };
54
+ useEffect(() => {
55
+ const onKey = (e) => {
56
+ if (e.key === "Escape")
57
+ onClose();
58
+ else if (e.key === "ArrowRight")
59
+ move(1);
60
+ else if (e.key === "ArrowLeft")
61
+ move(-1);
62
+ };
63
+ document.addEventListener("keydown", onKey);
64
+ return () => document.removeEventListener("keydown", onKey);
65
+ });
66
+ const image = images[at];
67
+ if (!image)
68
+ return null;
69
+ const nav = (by, label, glyph) => _jsx("button", { type: "button", className: cx("ainui-lightbox-close", "ainui-lightbox-nav", by < 0 ? "ainui-lightbox-prev" : "ainui-lightbox-next"), "aria-label": label, onClick: (e) => { e.stopPropagation(); move(by); }, children: glyph });
70
+ return _jsxs("span", { className: "ainui-lightbox", role: "dialog", "aria-modal": "true", "aria-label": image.alt || image.caption || "Image", onClick: onClose, children: [_jsx("img", { src: image.src, alt: image.alt ?? "" }), image.caption && _jsx("span", { className: "ainui-lightbox-caption", children: image.caption }), count > 1 && onIndex && nav(-1, "Previous image", "‹"), count > 1 && onIndex && nav(1, "Next image", "›"), _jsx("button", { type: "button", className: "ainui-lightbox-close", "aria-label": "Close", autoFocus: true, onClick: onClose, children: "\u00D7" })] });
71
+ }
72
+ /* ---------- Image ---------- */
73
+ const FIT = { cover: "cover", contain: "contain", fill: "fill", none: "none", scaleDown: "scale-down" };
74
+ const VARIANTS = ["icon", "avatar", "smallFeature", "mediumFeature", "largeFeature", "header"];
75
+ const Image = standard("Image", ({ props }) => {
76
+ const host = useHost();
77
+ const src = mediaUrl(props.url, host);
78
+ const [failed, setFailed] = useState("");
79
+ const [zoom, setZoom] = useState(false);
80
+ const alt = str(props.description);
81
+ const variant = VARIANTS.includes(props.variant) ? props.variant : "mediumFeature";
82
+ const small = variant === "icon" || variant === "avatar";
83
+ const frame = {
84
+ width: px(props.width), height: px(props.height), maxWidth: px(props.maxWidth), maxHeight: px(props.maxHeight), minWidth: px(props.minWidth), minHeight: px(props.minHeight),
85
+ aspectRatio: str(props.aspectRatio) || undefined, borderRadius: radius(props.radius), background: surfaceColor(props.background),
86
+ };
87
+ const className = cx("ainui-image", `ainui-image-${variant.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)}`, props.frame && "ainui-image-frame", props.hoverZoom && "ainui-image-hover-zoom");
88
+ if (!src || failed === src) {
89
+ if (props.hideOnFailure)
90
+ return null;
91
+ const text = str(props.fallback) || alt;
92
+ return _jsx("span", { className: cx(className, "ainui-image-failed"), style: frame, role: text ? "img" : undefined, "aria-label": text || undefined, "aria-hidden": text ? undefined : true, children: text });
93
+ }
94
+ const img = _jsx("img", { src: src, alt: alt, loading: "lazy", onError: () => setFailed(src), style: { objectFit: FIT[props.fit] ?? "cover", objectPosition: str(props.position) || undefined } });
95
+ // The catalog's default opens every image; an icon or avatar only does when asked to.
96
+ const lightbox = props.lightbox === true || (props.lightbox !== false && !small);
97
+ const overlay = obj(props.actionOverlay);
98
+ const overlayLabel = str(overlay.label);
99
+ const overlayHref = safeUrl(overlay.href);
100
+ const overlayBody = _jsxs(_Fragment, { children: [overlay.icon ? _jsx(IconGlyph, { name: overlay.icon, size: 14 }) : null, overlayLabel] });
101
+ return _jsxs("span", { className: className, style: frame, children: [lightbox
102
+ ? _jsx("button", { type: "button", className: "ainui-image-open", "aria-label": alt ? `Open image: ${alt}` : "Open image", onClick: () => setZoom(true), children: img })
103
+ : img, overlayLabel && (overlayHref
104
+ ? _jsx("a", { className: "ainui-image-overlay", href: overlayHref, target: "_blank", rel: "noopener noreferrer", onClick: host.openUrl ? (e) => { e.preventDefault(); host.openUrl?.(overlayHref); } : undefined, children: overlayBody })
105
+ : _jsx("button", { type: "button", className: "ainui-image-overlay", onClick: () => void props.onOverlayClick?.(), children: overlayBody })), zoom && _jsx(Lightbox, { images: [{ src, alt }], index: 0, onClose: () => setZoom(false) })] });
106
+ });
107
+ /* ---------- Favicon ---------- */
108
+ export function siteHost(url) {
109
+ const raw = str(url).trim();
110
+ if (!raw)
111
+ return "";
112
+ try {
113
+ const u = new URL(/^[a-z][a-z0-9+.-]*:/i.test(raw) ? raw : `https://${raw}`);
114
+ return /^https?:$/.test(u.protocol) && /^[a-z0-9.-]+$/i.test(u.hostname) ? u.hostname.replace(/^www\./, "") : "";
115
+ }
116
+ catch {
117
+ return "";
118
+ }
119
+ }
120
+ /** The icon of the site at `url`; nothing when the site has none or the URL is not a web address. */
121
+ export function SiteIcon({ url, size = 16, alt = "", frame, inline }) {
122
+ const domain = siteHost(url);
123
+ const [failed, setFailed] = useState("");
124
+ if (!domain || failed === domain)
125
+ return null;
126
+ return _jsx("img", { className: cx("ainui-favicon", frame && "ainui-favicon-frame", inline && "ainui-favicon-inline"), width: size, height: size, alt: alt, loading: "lazy", src: `https://www.google.com/s2/favicons?domain=${encodeURIComponent(domain)}&sz=${Math.round(size * 2)}`, onError: () => setFailed(domain), style: { width: size, height: size } });
127
+ }
128
+ const Favicon = standard("Favicon", ({ props }) => {
129
+ const size = num(props.size);
130
+ return _jsx(SiteIcon, { url: props.url, alt: str(props.alt), frame: !!props.frame, inline: !!props.inline, size: size && size > 0 ? Math.min(size, 256) : 16 });
131
+ });
132
+ /* ---------- Svg ---------- */
133
+ const paint = (v) => typeof v !== "string" || !v ? undefined : v === "none" || v === "transparent" ? v : v === "prose" || v === "default" || v === "currentColor" ? "currentColor"
134
+ : v === "secondary" ? "var(--ainui-muted)" : /^[#a-z0-9(),.%\s/-]+$/i.test(v) && !/url\s*\(/i.test(v) ? color(v) : undefined;
135
+ const shapeStyle = (s) => {
136
+ const fill = paint(s.fill), stroke = paint(s.stroke);
137
+ return fill || stroke ? { ...(fill ? { fill } : {}), ...(stroke ? { stroke } : {}) } : undefined;
138
+ };
139
+ const LINECAP = ["butt", "round", "square"], LINEJOIN = ["miter", "round", "bevel"], ANCHOR = ["start", "middle", "end"];
140
+ const VIEWBOX = /^\s*-?\d+(\.\d+)?([\s,]+-?\d+(\.\d+)?){3}\s*$/;
141
+ const ASPECT = /^(none|x(Min|Mid|Max)Y(Min|Mid|Max))(\s+(meet|slice))?$/;
142
+ const Svg = standard("Svg", ({ props }) => {
143
+ const label = str(props.label);
144
+ const width = px(props.width ?? props.size), height = px(props.height ?? props.size);
145
+ const strokeWidth = num(props.strokeWidth);
146
+ return _jsxs("svg", { className: "ainui-svg", viewBox: typeof props.viewBox === "string" && VIEWBOX.test(props.viewBox) ? props.viewBox.trim() : "0 0 24 24", preserveAspectRatio: typeof props.preserveAspectRatio === "string" && ASPECT.test(props.preserveAspectRatio.trim()) ? props.preserveAspectRatio.trim() : undefined, strokeWidth: strokeWidth, strokeLinecap: LINECAP.includes(props.strokeLinecap) ? props.strokeLinecap : undefined, strokeLinejoin: LINEJOIN.includes(props.strokeLinejoin) ? props.strokeLinejoin : undefined, style: { width: width ?? (height ? undefined : "24px"), height: height ?? (width ? undefined : "24px"), color: paint(props.color), fill: paint(props.fill) ?? "currentColor", stroke: paint(props.stroke) }, ...(label ? { role: "img", "aria-label": label } : { "aria-hidden": true }), children: [list(props.paths).map((p, i) => (typeof obj(p).d === "string" ? _jsx("path", { d: p.d, strokeWidth: num(p.strokeWidth), style: shapeStyle(p) }, `p${i}`) : null)), list(props.rects).map((r, i) => (num(obj(r).width) !== undefined && num(obj(r).height) !== undefined
147
+ ? _jsx("rect", { x: num(r.x) ?? 0, y: num(r.y) ?? 0, width: Math.max(0, r.width), height: Math.max(0, r.height), rx: num(r.rx), style: shapeStyle(r) }, `r${i}`) : null)), list(props.circles).map((c, i) => (num(obj(c).r) !== undefined ? _jsx("circle", { cx: num(c.cx) ?? 0, cy: num(c.cy) ?? 0, r: Math.max(0, c.r), style: shapeStyle(c) }, `c${i}`) : null)), list(props.lines).map((l, i) => (obj(l) === l
148
+ ? _jsx("line", { x1: num(l.x1) ?? 0, y1: num(l.y1) ?? 0, x2: num(l.x2) ?? 0, y2: num(l.y2) ?? 0, style: { stroke: paint(l.stroke) ?? paint(props.stroke) ?? "currentColor" } }, `l${i}`) : null)), list(props.texts).map((t, i) => (str(obj(t).text)
149
+ ? _jsx("text", { x: num(t.x) ?? 0, y: num(t.y) ?? 0, fontSize: num(t.size), textAnchor: ANCHOR.includes(t.anchor) ? t.anchor : undefined, stroke: "none", style: shapeStyle({ fill: t.fill }), children: str(t.text) }, `t${i}`) : null))] });
150
+ });
151
+ /* ---------- Video ---------- */
152
+ function youtubeId(url) {
153
+ try {
154
+ const u = new URL(url);
155
+ const host = u.hostname.replace(/^(www|m|music)\./, "");
156
+ const id = host === "youtu.be" ? u.pathname.slice(1).split("/")[0]
157
+ : host === "youtube.com" || host === "youtube-nocookie.com" ? (u.pathname === "/watch" ? u.searchParams.get("v") ?? "" : /^\/(shorts|embed|live|v)\/([^/?#]+)/.exec(u.pathname)?.[2] ?? "")
158
+ : "";
159
+ return /^[\w-]{6,20}$/.test(id) ? id : "";
160
+ }
161
+ catch {
162
+ return "";
163
+ }
164
+ }
165
+ const VIDEO_SITES = /(^|\.)(vimeo\.com|dailymotion\.com|twitch\.tv|tiktok\.com|facebook\.com|instagram\.com|twitter\.com|x\.com|bilibili\.com|tv\.naver\.com|tv\.kakao\.com|youtube\.com|youtu\.be)$/i;
166
+ const FILE_EXT = /\.(mp4|m4v|webm|ogv|ogg|mov|m3u8)$/i;
167
+ const TRACK_KIND = ["subtitles", "captions", "descriptions"];
168
+ const Video = standard("Video", ({ props }) => {
169
+ const host = useHost();
170
+ const [playing, setPlaying] = useState(false);
171
+ const src = mediaUrl(props.url, host);
172
+ const poster = mediaUrl(props.posterUrl, host);
173
+ const title = str(props.title);
174
+ const style = { aspectRatio: str(props.aspectRatio) || "16 / 9", width: px(props.width) ?? "100%", maxWidth: px(props.maxWidth) ?? "100%" };
175
+ if (!src)
176
+ return null;
177
+ const yt = youtubeId(src);
178
+ if (yt) {
179
+ // Nothing is requested from the video site's player until the viewer asks for it.
180
+ return _jsx("div", { className: "ainui-video ainui-video-youtube", style: style, children: playing
181
+ ? _jsx("iframe", { src: `https://www.youtube-nocookie.com/embed/${yt}?autoplay=1&rel=0`, title: title || "YouTube video", allow: "autoplay; encrypted-media; picture-in-picture; fullscreen", allowFullScreen: true, referrerPolicy: "strict-origin-when-cross-origin" })
182
+ : _jsxs("button", { type: "button", className: "ainui-video-poster", "aria-label": title ? `Play video: ${title}` : "Play video", onClick: () => setPlaying(true), children: [_jsx("img", { src: poster || `https://i.ytimg.com/vi/${yt}/hqdefault.jpg`, alt: "", loading: "lazy" }), _jsx("span", { className: "ainui-video-play", "aria-hidden": "true", children: _jsx("svg", { viewBox: "0 0 24 24", width: "28", height: "28", fill: "currentColor", children: _jsx("path", { d: "M8 5v14l11-7z" }) }) })] }) });
183
+ }
184
+ let site = "";
185
+ try {
186
+ const u = new URL(src, "https://local.invalid");
187
+ if (VIDEO_SITES.test(u.hostname) && !FILE_EXT.test(u.pathname))
188
+ site = u.hostname.replace(/^www\./, "");
189
+ }
190
+ catch { /* a relative URL is a file */ }
191
+ if (site) {
192
+ return _jsxs("a", { className: "ainui-video-link", href: src, target: "_blank", rel: "noopener noreferrer", onClick: host.openUrl ? (e) => { e.preventDefault(); host.openUrl?.(src); } : undefined, children: [_jsx("span", { className: "ainui-video-play", "aria-hidden": "true", children: _jsx("svg", { viewBox: "0 0 24 24", width: "16", height: "16", fill: "currentColor", children: _jsx("path", { d: "M8 5v14l11-7z" }) }) }), _jsx("span", { children: title || "Watch video" }), _jsx("span", { className: "ainui-video-site", children: site })] });
193
+ }
194
+ return _jsx("video", { className: "ainui-video", controls: true, preload: "metadata", playsInline: true, src: src, poster: poster || undefined, title: title || undefined, "aria-label": title || undefined, style: style, children: list(props.captions).map((c, i) => {
195
+ const track = mediaUrl(obj(c).url, host);
196
+ return track ? _jsx("track", { src: track, kind: TRACK_KIND.includes(c.kind) ? c.kind : "subtitles", srcLang: str(c.language) || undefined, label: str(c.label) || str(c.language) || undefined, default: i === 0 }, i) : null;
197
+ }) });
198
+ });
199
+ const AudioPlayer = standard("AudioPlayer", ({ props }) => {
200
+ const host = useHost();
201
+ const src = mediaUrl(props.url, host);
202
+ const description = str(props.description);
203
+ if (!src)
204
+ return null;
205
+ return _jsxs("figure", { className: "ainui-audio-player", children: [description && _jsx("figcaption", { className: "ainui-audio-player-description", children: description }), _jsx("audio", { controls: true, preload: "metadata", src: src, "aria-label": description || "Audio" })] });
206
+ });
207
+ const HtmlView = standard("HtmlView", ({ props }) => _jsx("iframe", { className: "ainui-html-view", sandbox: "", srcDoc: str(props.html), title: str(props.title) || "Embedded content", loading: "lazy", referrerPolicy: "no-referrer", style: { width: px(props.width) ?? "100%", height: px(props.height) ?? "360px" } }));
208
+ export const media = [Image, Icon, Favicon, Svg, Video, AudioPlayer, HtmlView];
@@ -0,0 +1 @@
1
+ export declare const rich: import("@a2ui/react").ReactComponentImplementation<import("zod").ZodTypeAny>[];
@@ -0,0 +1,146 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ /** Standard catalog — rich: dashboard building blocks (headings, KPIs, trends, progress, notes, people, timelines). */
4
+ import { useId, useState } from "react";
5
+ import { Kids, cx, mediaUrl, standard, useHost } from "../core.js";
6
+ import { IconGlyph } from "./media.js";
7
+ const str = (v) => (typeof v === "string" ? v : typeof v === "number" && Number.isFinite(v) ? String(v) : "");
8
+ const num = (v) => typeof v === "number" && Number.isFinite(v) ? v : typeof v === "string" && v.trim() !== "" && Number.isFinite(Number(v)) ? Number(v) : undefined;
9
+ const list = (v) => (Array.isArray(v) ? v : []);
10
+ const obj = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : {});
11
+ const display = (v) => (typeof v === "number" && Number.isFinite(v) ? v.toLocaleString("en-US") : str(v));
12
+ const MOODS = new Set(["positive", "negative", "warning", "info", "accent"]);
13
+ const toneMood = (tone) => (typeof tone === "string" && MOODS.has(tone) ? tone : undefined);
14
+ /** The trend as given, or read from the delta's sign ("+4%" is up, "-2" is down). */
15
+ function trendOf(trend, delta) {
16
+ if (trend === "up" || trend === "down" || trend === "flat")
17
+ return trend;
18
+ const d = str(delta).trim();
19
+ return /^\+/.test(d) ? "up" : /^[-−–]/.test(d) ? "down" : undefined;
20
+ }
21
+ /** An explicit tone wins (a falling churn can be positive); otherwise up is good and down is bad. */
22
+ const moodOf = (tone, trend) => toneMood(tone) ?? (trend === "up" ? "positive" : trend === "down" ? "negative" : "neutral");
23
+ function Delta({ delta, trend, mood }) {
24
+ if (!delta)
25
+ return null;
26
+ const glyph = trend === "up" ? "arrow-up-right" : trend === "down" ? "arrow-down-right" : trend === "flat" ? "arrow-right" : "";
27
+ return _jsxs("span", { className: cx("ainui-delta", `ainui-delta-${mood}`, `ainui-rich-${mood}`), children: [glyph && _jsx(IconGlyph, { name: glyph, size: 14, strokeWidth: 2.25 }), _jsx("span", { children: delta })] });
28
+ }
29
+ /** A Lucide icon name, or an emoji / short text shown as written. */
30
+ function Glyph({ icon, size = 18 }) {
31
+ return /^[a-z][a-z0-9-]*$/i.test(icon) ? _jsx(IconGlyph, { name: icon, size: size }) : _jsx("span", { className: "ainui-emoji", "aria-hidden": "true", children: icon });
32
+ }
33
+ /* ---------- Heading, Section ---------- */
34
+ const Heading = standard("Heading", ({ props }) => {
35
+ const level = ["1", "2", "3"].includes(String(props.level)) ? String(props.level) : "1";
36
+ const H = `h${level}`;
37
+ const eyebrow = str(props.eyebrow), subtitle = str(props.subtitle);
38
+ return _jsxs("header", { className: cx("ainui-heading", `ainui-heading-${level}`), children: [eyebrow && _jsx("p", { className: "ainui-eyebrow", children: eyebrow }), _jsx(H, { className: "ainui-heading-title", children: str(props.text) }), subtitle && _jsx("p", { className: "ainui-heading-subtitle", children: subtitle })] });
39
+ });
40
+ const Section = standard("Section", ({ props, buildChild }) => {
41
+ const id = useId();
42
+ const eyebrow = str(props.eyebrow), title = str(props.title), description = str(props.description);
43
+ return _jsxs("section", { className: "ainui-section", "aria-labelledby": title ? id : undefined, children: [(eyebrow || title || description) && _jsxs("div", { className: "ainui-section-head", children: [(title || eyebrow) && _jsxs("div", { className: "ainui-section-titles", children: [title && _jsx("h3", { id: id, className: "ainui-section-title", children: title }), eyebrow && _jsx("span", { className: "ainui-eyebrow", children: eyebrow })] }), description && _jsx("p", { className: "ainui-section-description", children: description })] }), _jsx("div", { className: "ainui-section-body", children: _jsx(Kids, { of: props.children, buildChild: buildChild }) })] });
44
+ });
45
+ /* ---------- Stat, StatGroup, Sparkline ---------- */
46
+ const Stat = standard("Stat", ({ props }) => {
47
+ const trend = trendOf(props.trend, props.delta);
48
+ const mood = moodOf(props.tone, trend);
49
+ const icon = str(props.icon), caption = str(props.caption);
50
+ return _jsxs("div", { className: cx("ainui-stat", `ainui-stat-${mood}`, `ainui-rich-${mood}`), children: [_jsxs("div", { className: "ainui-stat-label", children: [icon && _jsx(Glyph, { icon: icon, size: 15 }), _jsx("span", { children: str(props.label) })] }), _jsxs("div", { className: "ainui-stat-line", children: [_jsx("span", { className: "ainui-stat-value", children: display(props.value) || "—" }), _jsx(Delta, { delta: str(props.delta), trend: trend, mood: mood })] }), caption && _jsx("div", { className: "ainui-stat-caption", children: caption })] });
51
+ });
52
+ const StatGroup = standard("StatGroup", ({ props }) => {
53
+ const items = list(props.items).map(obj).filter((i) => str(i.label) || display(i.value));
54
+ return _jsx("div", { className: "ainui-stat-group", role: "group", children: items.map((item, i) => {
55
+ const trend = trendOf(item.trend, item.delta);
56
+ const mood = moodOf(undefined, trend);
57
+ return _jsxs("div", { className: cx("ainui-stat-group-item", `ainui-stat-${mood}`, `ainui-rich-${mood}`), children: [_jsx("div", { className: "ainui-stat-label", children: str(item.label) }), _jsxs("div", { className: "ainui-stat-line", children: [_jsx("span", { className: "ainui-stat-value", children: display(item.value) || "—" }), _jsx(Delta, { delta: str(item.delta), trend: trend, mood: mood })] })] }, i);
58
+ }) });
59
+ });
60
+ const W = 120, H = 36;
61
+ const Sparkline = standard("Sparkline", ({ props }) => {
62
+ const gradient = `ainui-spark-${useId().replace(/[^A-Za-z0-9_-]/g, "")}`;
63
+ const values = list(props.values).map(num).filter((v) => v !== undefined);
64
+ const delta = str(props.delta);
65
+ const trend = trendOf(undefined, delta) ?? (values.length > 1 ? (values[values.length - 1] > values[0] ? "up" : values[values.length - 1] < values[0] ? "down" : "flat") : undefined);
66
+ const tone = props.tone === "positive" || props.tone === "negative" ? props.tone : undefined;
67
+ const lineMood = tone ?? "accent";
68
+ const deltaMood = moodOf(tone, trend);
69
+ const value = str(props.value) || (values.length ? values[values.length - 1].toLocaleString("en-US") : "");
70
+ const min = Math.min(...values), max = Math.max(...values), span = max - min || 1;
71
+ const points = values.map((v, i) => [values.length > 1 ? (i / (values.length - 1)) * W : W / 2, 3 + (1 - (v - min) / span) * (H - 6)]);
72
+ const line = points.map(([x, y], i) => `${i ? "L" : "M"}${x.toFixed(2)} ${y.toFixed(2)}`).join(" ");
73
+ const label = str(props.label);
74
+ return _jsxs("div", { className: cx("ainui-sparkline", `ainui-sparkline-${lineMood}`, `ainui-rich-${lineMood}`), children: [_jsxs("div", { className: "ainui-sparkline-text", children: [label && _jsx("div", { className: "ainui-stat-label", children: label }), _jsxs("div", { className: "ainui-stat-line", children: [value && _jsx("span", { className: "ainui-sparkline-value", children: value }), _jsx(Delta, { delta: delta, trend: trend, mood: deltaMood })] })] }), points.length > 1 && _jsxs("svg", { className: "ainui-sparkline-chart", viewBox: `0 0 ${W} ${H}`, preserveAspectRatio: "none", role: "img", "aria-label": `${label ? `${label}: ` : ""}${values.length} values from ${values[0]} to ${values[values.length - 1]}`, children: [_jsx("defs", { children: _jsxs("linearGradient", { id: gradient, x1: "0", y1: "0", x2: "0", y2: "1", children: [_jsx("stop", { offset: "0%", stopColor: "currentColor", stopOpacity: 0.28 }), _jsx("stop", { offset: "100%", stopColor: "currentColor", stopOpacity: 0 })] }) }), _jsx("path", { d: `${line} L${W} ${H} L0 ${H} Z`, fill: `url(#${gradient})`, stroke: "none" }), _jsx("path", { d: line, fill: "none", stroke: "currentColor", strokeWidth: 1.75, strokeLinejoin: "round", strokeLinecap: "round", vectorEffect: "non-scaling-stroke" })] })] });
75
+ });
76
+ /* ---------- Progress ---------- */
77
+ const Progress = standard("Progress", ({ props }) => {
78
+ const value = Math.max(0, Math.min(100, num(props.value) ?? 0));
79
+ const mood = toneMood(props.tone) ?? "accent";
80
+ const label = str(props.label), caption = str(props.caption);
81
+ const shown = Number.isInteger(value) ? value : Number(value.toFixed(1));
82
+ return _jsxs("div", { className: cx("ainui-progress", `ainui-progress-${mood}`, `ainui-rich-${mood}`), children: [_jsxs("div", { className: "ainui-progress-head", children: [_jsx("span", { className: "ainui-progress-label", children: label }), _jsxs("span", { className: "ainui-progress-percent", children: [shown, "%"] })] }), _jsx("div", { className: "ainui-progress-track", role: "progressbar", "aria-valuemin": 0, "aria-valuemax": 100, "aria-valuenow": shown, "aria-label": label || "Progress", children: _jsx("div", { className: "ainui-progress-fill", style: { width: `${value}%` } }) }), caption && _jsx("div", { className: "ainui-progress-caption", children: caption })] });
83
+ });
84
+ /* ---------- Callout, Alert ---------- */
85
+ function ActionButton({ label, onAction, className }) {
86
+ if (!label)
87
+ return null;
88
+ return _jsx("button", { type: "button", className: cx("ainui-rich-button", className), disabled: typeof onAction !== "function", onClick: () => { if (typeof onAction === "function")
89
+ void onAction(); }, children: label });
90
+ }
91
+ const Callout = standard("Callout", ({ props }) => {
92
+ const icon = str(props.icon) || "lightbulb", title = str(props.title);
93
+ return _jsxs("aside", { className: "ainui-callout", children: [_jsx("span", { className: "ainui-callout-icon", children: _jsx(Glyph, { icon: icon, size: 18 }) }), _jsxs("div", { className: "ainui-callout-body", children: [title && _jsx("div", { className: "ainui-callout-title", children: title }), _jsx("div", { className: "ainui-callout-text", children: str(props.text) }), _jsx(ActionButton, { label: str(props.actionLabel), onAction: props.onAction, className: "ainui-callout-action" })] })] });
94
+ });
95
+ const ALERT_ICON = { info: "info", success: "circle-check", warning: "triangle-alert", error: "circle-alert" };
96
+ const Alert = standard("Alert", ({ props }) => {
97
+ const tone = props.tone in ALERT_ICON ? props.tone : "info";
98
+ const message = str(props.message);
99
+ return _jsxs("div", { className: cx("ainui-alert", `ainui-alert-${tone}`), role: tone === "error" || tone === "warning" ? "alert" : "status", children: [_jsx("span", { className: "ainui-alert-icon", children: _jsx(IconGlyph, { name: ALERT_ICON[tone], size: 18 }) }), _jsxs("div", { className: "ainui-alert-body", children: [_jsx("div", { className: "ainui-alert-title", children: str(props.title) }), message && _jsx("div", { className: "ainui-alert-message", children: message })] })] });
100
+ });
101
+ /* ---------- Avatar ---------- */
102
+ const HUES = ["info", "success", "warning", "discovery", "danger", "caution", "secondary"];
103
+ const initials = (name) => {
104
+ const parts = name.trim().split(/\s+/).filter(Boolean);
105
+ const chars = parts.length > 1 ? [parts[0], parts[parts.length - 1]].map((p) => Array.from(p)[0]) : Array.from(parts[0] ?? "").slice(0, 2);
106
+ return chars.join("").toUpperCase() || "?";
107
+ };
108
+ const hueOf = (name) => { let h = 0; for (const c of name)
109
+ h = (h * 31 + c.codePointAt(0)) >>> 0; return HUES[h % HUES.length]; };
110
+ const Avatar = standard("Avatar", ({ props }) => {
111
+ const host = useHost();
112
+ const [broken, setBroken] = useState(false);
113
+ const name = str(props.name), subtitle = str(props.subtitle);
114
+ const size = ["sm", "md", "lg"].includes(props.size) ? props.size : "md";
115
+ const status = ["online", "away", "offline"].includes(props.status) ? props.status : "";
116
+ const src = broken ? "" : mediaUrl(props.image, host);
117
+ const hue = hueOf(name);
118
+ return _jsxs("div", { className: cx("ainui-avatar", `ainui-avatar-${size}`), children: [_jsxs("span", { className: "ainui-avatar-circle", style: src ? undefined : { background: `var(--ainui-${hue}-soft)`, color: `var(--ainui-${hue})` }, children: [src ? _jsx("img", { src: src, alt: "", onError: () => setBroken(true) }) : _jsx("span", { "aria-hidden": "true", children: initials(name) }), status && _jsx("span", { className: cx("ainui-avatar-status", `ainui-avatar-status-${status}`), role: "img", "aria-label": status })] }), (name || subtitle) && _jsxs("span", { className: "ainui-avatar-text", children: [name && _jsx("span", { className: "ainui-avatar-name", children: name }), subtitle && _jsx("span", { className: "ainui-avatar-subtitle", children: subtitle })] })] });
119
+ });
120
+ /* ---------- KeyValueList, Timeline, TagList ---------- */
121
+ const KeyValueList = standard("KeyValueList", ({ props }) => {
122
+ const items = list(props.items).map(obj).filter((i) => str(i.label) || display(i.value));
123
+ const columns = Math.max(1, Math.min(3, Math.round(num(props.columns) ?? 1)));
124
+ const title = str(props.title);
125
+ return _jsxs("div", { className: "ainui-kv", children: [title && _jsx("div", { className: "ainui-kv-title", children: title }), _jsx("dl", { className: cx("ainui-kv-grid", `ainui-kv-columns-${columns}`), children: items.map((item, i) => _jsxs("div", { className: "ainui-kv-row", children: [_jsxs("dt", { className: "ainui-kv-label", children: [str(item.label), str(item.hint) && _jsx("span", { className: "ainui-kv-hint", children: str(item.hint) })] }), _jsx("dd", { className: "ainui-kv-value", children: display(item.value) })] }, i)) })] });
126
+ });
127
+ const Timeline = standard("Timeline", ({ props }) => {
128
+ const items = list(props.items).map(obj).filter((i) => str(i.title));
129
+ return _jsx("ol", { className: "ainui-timeline", children: items.map((item, i) => {
130
+ const status = ["done", "current", "upcoming"].includes(item.status) ? item.status : "upcoming";
131
+ const icon = str(item.icon) || (status === "done" ? "check" : "");
132
+ const time = str(item.time), description = str(item.description);
133
+ return _jsxs("li", { className: cx("ainui-timeline-item", `ainui-timeline-${status}`), "aria-current": status === "current" ? "step" : undefined, children: [_jsx("span", { className: "ainui-timeline-marker", children: icon && (status === "done" && !str(item.icon) ? _jsx(IconGlyph, { name: "check", size: 14, strokeWidth: 3 }) : _jsx(Glyph, { icon: icon, size: 13 })) }), _jsxs("div", { className: "ainui-timeline-content", children: [_jsxs("div", { className: "ainui-timeline-head", children: [_jsx("span", { className: "ainui-timeline-title", children: str(item.title) }), time && _jsx("span", { className: "ainui-timeline-time", children: time })] }), description && _jsx("div", { className: "ainui-timeline-description", children: description })] })] }, i);
134
+ }) });
135
+ });
136
+ const TagList = standard("TagList", ({ props }) => {
137
+ const tags = list(props.tags).map(str).filter(Boolean);
138
+ const mood = toneMood(props.tone) ?? "neutral";
139
+ return _jsx("ul", { className: cx("ainui-tag-list", `ainui-tag-list-${mood}`, `ainui-rich-${mood}`), children: tags.map((t, i) => _jsx("li", { className: "ainui-tag", children: t }, `${t}:${i}`)) });
140
+ });
141
+ /* ---------- EmptyState ---------- */
142
+ const EmptyState = standard("EmptyState", ({ props }) => {
143
+ const description = str(props.description);
144
+ return _jsxs("div", { className: "ainui-empty-state", children: [_jsx("span", { className: "ainui-empty-state-icon", children: _jsx(Glyph, { icon: str(props.icon) || "inbox", size: 24 }) }), _jsx("div", { className: "ainui-empty-state-title", children: str(props.title) }), description && _jsx("p", { className: "ainui-empty-state-description", children: description }), _jsx(ActionButton, { label: str(props.actionLabel), onAction: props.onAction, className: "ainui-empty-state-action" })] });
145
+ });
146
+ export const rich = [Heading, Section, Stat, StatGroup, Sparkline, Progress, Callout, Alert, Avatar, KeyValueList, Timeline, TagList, EmptyState];
@@ -0,0 +1,9 @@
1
+ /** Standard catalog — text: headings, body text, inline marks, badges, code, markdown, math, links, tooltips. */
2
+ import React from "react";
3
+ /** True inside an element that only takes phrasing content (a paragraph, a button): block text renders a `span`. */
4
+ export declare const InlineContext: React.Context<boolean>;
5
+ /** http(s), site-relative and mailto. Anything else gives "". */
6
+ export declare function linkUrl(v: unknown): string;
7
+ /** Inline markdown as React elements (never HTML): bold, italic, strike, underline, code, links. */
8
+ export declare function inlineMarkdown(source: string, depth?: number): React.ReactNode[];
9
+ export declare const text: import("@a2ui/react").ReactComponentImplementation<import("zod").ZodTypeAny>[];
@@ -0,0 +1,209 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ /** Standard catalog — text: headings, body text, inline marks, badges, code, markdown, math, links, tooltips. */
4
+ import { createContext, useContext, useEffect, useId, useLayoutEffect, useRef, useState } from "react";
5
+ import { renderMarkdown } from "@a2ui/markdown-it";
6
+ import { Kids, color, cx, kid, px, safeUrl, space, standard, useHost } from "../core.js";
7
+ /** True inside an element that only takes phrasing content (a paragraph, a button): block text renders a `span`. */
8
+ export const InlineContext = createContext(false);
9
+ const WEIGHT = { normal: 400, medium: 500, semibold: 600, bold: 700 };
10
+ const ALIGN = ["start", "center", "end"];
11
+ const num = (v) => (typeof v === "number" && Number.isFinite(v) ? v : undefined);
12
+ /** Text colour tokens name roles (`secondary` is quieter text), unlike the tone colours of `color()`. */
13
+ function textColor(v) {
14
+ if (typeof v !== "string" || !v)
15
+ return undefined;
16
+ if (v === "default" || v === "prose" || v === "emphasis")
17
+ return "var(--ainui-fg)";
18
+ if (v === "secondary" || v === "tertiary")
19
+ return "var(--ainui-muted)";
20
+ return color(v);
21
+ }
22
+ /** http(s), site-relative and mailto. Anything else gives "". */
23
+ export function linkUrl(v) {
24
+ return safeUrl(v) || (typeof v === "string" && /^mailto:[^\s<>"]+$/i.test(v.trim()) ? v.trim() : "");
25
+ }
26
+ function Anchor({ href, title, className, children }) {
27
+ const host = useHost();
28
+ const url = linkUrl(href);
29
+ const viaHost = host.openUrl && safeUrl(url) ? host.openUrl : undefined;
30
+ return _jsx("a", { className: cx("ainui-link", className), href: url || undefined, title: typeof title === "string" && title ? title : undefined, target: url ? "_blank" : undefined, rel: url ? "noopener noreferrer" : undefined, onClick: viaHost ? (e) => { e.preventDefault(); viaHost(url); } : undefined, children: children });
31
+ }
32
+ const INLINE = /\\([\\`*_~+[\]()])|(`+)(.+?)\2|\*\*(?=\S)(.+?)(?<=\S)\*\*|\*(?=\S)(.+?)(?<=\S)\*|~~(.+?)~~|\+\+(.+?)\+\+|\[([^\]\n]+)\]\(([^)\s]+)(?:\s+"([^"]*)")?\)/gs;
33
+ /** Inline markdown as React elements (never HTML): bold, italic, strike, underline, code, links. */
34
+ export function inlineMarkdown(source, depth = 0) {
35
+ if (depth > 6 || !/[\\`*~+[]/.test(source))
36
+ return [source];
37
+ const out = [];
38
+ let last = 0;
39
+ for (const m of source.matchAll(INLINE)) {
40
+ const at = m.index ?? 0;
41
+ if (at > last)
42
+ out.push(source.slice(last, at));
43
+ last = at + m[0].length;
44
+ const key = `${depth}:${at}`;
45
+ const inner = (s) => inlineMarkdown(s, depth + 1);
46
+ if (m[1] !== undefined)
47
+ out.push(m[1]);
48
+ else if (m[3] !== undefined)
49
+ out.push(_jsx("code", { className: "ainui-code", children: m[3] }, key));
50
+ else if (m[4] !== undefined)
51
+ out.push(_jsx("strong", { children: inner(m[4]) }, key));
52
+ else if (m[5] !== undefined)
53
+ out.push(_jsx("em", { children: inner(m[5]) }, key));
54
+ else if (m[6] !== undefined)
55
+ out.push(_jsx("s", { children: inner(m[6]) }, key));
56
+ else if (m[7] !== undefined)
57
+ out.push(_jsx("u", { children: inner(m[7]) }, key));
58
+ else if (linkUrl(m[9]))
59
+ out.push(_jsx(Anchor, { href: m[9], title: m[10], children: inner(m[8]) }, key));
60
+ else
61
+ out.push(m[0]);
62
+ }
63
+ if (last < source.length)
64
+ out.push(source.slice(last));
65
+ return out;
66
+ }
67
+ const plain = (v) => (typeof v === "string" ? v : typeof v === "number" || typeof v === "boolean" ? String(v) : "");
68
+ const rich = (v) => (typeof v === "string" ? inlineMarkdown(v) : plain(v) || null);
69
+ /** The typography props Title, Text, Caption, Label and ShimmerText share. */
70
+ function typography(p, base, size, weight) {
71
+ const lines = num(p.maxLines), min = num(p.minLines);
72
+ const decoration = [p.underline && "underline", p.lineThrough && "line-through"].filter(Boolean).join(" ");
73
+ const style = {
74
+ color: textColor(p.color), fontWeight: WEIGHT[p.fontWeight] ?? weight, textAlign: ALIGN.includes(p.textAlign) ? p.textAlign : undefined,
75
+ fontStyle: p.italic ? "italic" : undefined, fontVariantNumeric: p.tabularNums ? "tabular-nums" : undefined,
76
+ width: px(p.width), fontSize: px(p.fontSize), lineHeight: num(p.lineHeight) ?? (typeof p.lineHeight === "string" && p.lineHeight ? p.lineHeight : undefined),
77
+ minHeight: min && min > 0 ? `calc(${min} * 1lh)` : undefined, textDecoration: decoration || undefined,
78
+ whiteSpace: p.preserveWhitespace ? "pre-wrap" : undefined,
79
+ ...(lines && lines > 0 ? { WebkitLineClamp: Math.round(lines) } : {}),
80
+ ...(typeof p.weight === "number" ? { flex: `${p.weight} 1 0%`, minWidth: 0 } : {}),
81
+ };
82
+ const className = cx(base, `${base}-${typeof p.size === "string" && /^[a-z0-9]+$/.test(p.size) ? p.size : size}`, p.truncate && "ainui-truncate", !!lines && lines > 0 && "ainui-clamp");
83
+ return { className, style };
84
+ }
85
+ const HEADING = { sm: "h4", md: "h3", lg: "h3" };
86
+ const Title = standard("Title", ({ props }) => {
87
+ const Tag = HEADING[props.size ?? "md"] ?? (typeof props.size === "string" ? "h2" : "h3");
88
+ return _jsx(Tag, { ...typography(props, "ainui-title", "md", props.strong === false ? 400 : 700), children: plain(props.text) });
89
+ });
90
+ const HIGHLIGHT = { green: "success", orange: "warning", pink: "danger" };
91
+ const Text = standard("Text", ({ props, buildChild }) => {
92
+ const nested = useContext(InlineContext);
93
+ const Tag = nested || props.inline ? "span" : "p";
94
+ const t = typography(props, "ainui-text", "md", props.strong ? 600 : undefined);
95
+ const body = rich(props.text);
96
+ return _jsxs(Tag, { className: cx(t.className, props.inline && "ainui-text-inline"), style: t.style, children: [props.highlight ? _jsx("mark", { className: "ainui-highlight", style: { background: `var(--ainui-${HIGHLIGHT[props.highlight] ?? "warning"}-soft)` }, children: body }) : body, _jsx(InlineContext.Provider, { value: true, children: _jsx(Kids, { of: props.children, buildChild: buildChild }) })] });
97
+ });
98
+ const Caption = standard("Caption", ({ props }) => {
99
+ const Tag = useContext(InlineContext) ? "span" : "div";
100
+ return _jsx(Tag, { ...typography(props, "ainui-caption", "lg"), children: rich(props.text) });
101
+ });
102
+ const Label = standard("Label", ({ props }) => _jsx("label", { htmlFor: typeof props.htmlFor === "string" && props.htmlFor ? props.htmlFor : undefined, ...typography(props, "ainui-label", "sm", 500), children: plain(props.text) }));
103
+ const Bold = standard("Bold", ({ props }) => _jsx("strong", { className: "ainui-bold", style: { fontWeight: WEIGHT[props.fontWeight] }, children: plain(props.text) }));
104
+ const Italic = standard("Italic", ({ props }) => _jsx("em", { className: "ainui-italic", children: plain(props.text) }));
105
+ const Underline = standard("Underline", ({ props }) => _jsx("u", { className: "ainui-underline", children: plain(props.text) }));
106
+ const Strikethrough = standard("Strikethrough", ({ props }) => _jsx("s", { className: "ainui-strikethrough", children: plain(props.text) }));
107
+ const BADGE_COLORS = ["secondary", "success", "danger", "warning", "info", "discovery"];
108
+ const Badge = standard("Badge", ({ props }) => {
109
+ const pick = (v, of, fallback) => (typeof v === "string" && of.includes(v) ? v : fallback);
110
+ return _jsx("span", { className: cx("ainui-badge", `ainui-badge-${pick(props.variant, ["soft", "solid", "outline"], "soft")}`, `ainui-badge-${pick(props.color, BADGE_COLORS, "secondary")}`, `ainui-badge-${pick(props.size, ["sm", "md", "lg"], "md")}`, props.pill !== false && "ainui-badge-pill"), style: { fontWeight: WEIGHT[props.fontWeight], maxWidth: px(props.maxWidth), padding: space(props.padding) }, children: plain(props.label) });
111
+ });
112
+ const Blockquote = standard("Blockquote", ({ props }) => _jsx("blockquote", { className: "ainui-blockquote", children: rich(props.text) }));
113
+ const Code = standard("Code", ({ props }) => {
114
+ const [copied, setCopied] = useState(false);
115
+ const timer = useRef(undefined);
116
+ useEffect(() => () => clearTimeout(timer.current), []);
117
+ const source = plain(props.text);
118
+ const language = typeof props.language === "string" ? props.language.trim().replace(/[^\w+#.-]/g, "") : "";
119
+ if (!language)
120
+ return _jsx("code", { className: "ainui-code", children: source });
121
+ const copy = async () => {
122
+ try {
123
+ await globalThis.navigator?.clipboard?.writeText(source);
124
+ }
125
+ catch { /* clipboard denied: the button still confirms nothing was thrown */ }
126
+ setCopied(true);
127
+ clearTimeout(timer.current);
128
+ timer.current = setTimeout(() => setCopied(false), 1500);
129
+ };
130
+ return _jsxs("div", { className: "ainui-code-block", children: [_jsxs("div", { className: "ainui-code-bar", children: [_jsx("span", { className: "ainui-code-language", children: language }), _jsx("button", { type: "button", className: "ainui-code-copy", onClick: copy, "aria-live": "polite", children: copied ? "Copied" : "Copy" })] }), _jsx("pre", { tabIndex: 0, children: _jsx("code", { className: `language-${language}`, children: source }) })] });
131
+ });
132
+ const Markdown = standard("Markdown", ({ props }) => {
133
+ const source = plain(props.text);
134
+ const [html, setHtml] = useState(null);
135
+ const ref = useRef(null);
136
+ const asked = useRef(0), shown = useRef(0);
137
+ useEffect(() => {
138
+ const turn = ++asked.current;
139
+ // A slow render never replaces a newer one, and the previous HTML stays until this one is ready.
140
+ const show = (out) => { if (turn > shown.current && typeof out === "string") {
141
+ shown.current = turn;
142
+ setHtml(out);
143
+ } };
144
+ try {
145
+ const out = renderMarkdown(source);
146
+ if (out && typeof out.then === "function")
147
+ out.then(show, () => undefined);
148
+ else
149
+ show(out);
150
+ }
151
+ catch { /* the plain source stays visible */ }
152
+ }, [source]);
153
+ useLayoutEffect(() => {
154
+ ref.current?.querySelectorAll?.("a[href]").forEach((a) => { a.setAttribute("target", "_blank"); a.setAttribute("rel", "noopener noreferrer"); });
155
+ }, [html]);
156
+ const className = cx("ainui-markdown", props.streaming && "ainui-markdown-streaming");
157
+ const busy = props.streaming ? true : undefined;
158
+ return html === null
159
+ ? _jsx("div", { className: cx(className, "ainui-markdown-plain"), "aria-busy": busy, children: source })
160
+ : _jsx("div", { ref: ref, className: className, "aria-busy": busy, dangerouslySetInnerHTML: { __html: html } });
161
+ });
162
+ let katexLoad;
163
+ const loadKatex = () => (katexLoad ??= (async () => {
164
+ try {
165
+ const mod = await import("katex");
166
+ const k = mod?.default?.renderToString ? mod.default : mod;
167
+ return typeof k?.renderToString === "function" ? k : null;
168
+ }
169
+ catch {
170
+ return null;
171
+ }
172
+ })());
173
+ const Math_ = standard("Math", ({ props }) => {
174
+ const tex = plain(props.value), block = !!props.block;
175
+ const [html, setHtml] = useState(null);
176
+ useEffect(() => {
177
+ let live = true;
178
+ void loadKatex().then((k) => {
179
+ if (!live)
180
+ return;
181
+ try {
182
+ setHtml(k ? k.renderToString(tex, { throwOnError: false, displayMode: block }) : null);
183
+ }
184
+ catch {
185
+ setHtml(null);
186
+ }
187
+ });
188
+ return () => { live = false; };
189
+ }, [tex, block]);
190
+ const Tag = block ? "div" : "span";
191
+ const className = cx("ainui-math", block && "ainui-math-block");
192
+ return html === null
193
+ ? _jsx(Tag, { className: className, children: _jsx("code", { className: "ainui-math-source", children: tex }) })
194
+ : _jsx(Tag, { className: className, dangerouslySetInnerHTML: { __html: html } });
195
+ });
196
+ const ShimmerText = standard("ShimmerText", ({ props }) => {
197
+ const t = typography(props, "ainui-shimmer-text", "md");
198
+ const { color: base, ...style } = t.style;
199
+ return _jsx("span", { className: t.className, "aria-busy": "true", style: { ...style, ...(base ? { "--ainui-shimmer-base": base } : {}), ...(style.width || style.textAlign ? { display: "block" } : {}) }, children: plain(props.text) });
200
+ });
201
+ const Link = standard("Link", ({ props }) => _jsx(Anchor, { href: props.href, title: props.title, children: plain(props.text) }));
202
+ const Tooltip = standard("Tooltip", ({ props, buildChild }) => {
203
+ const [open, setOpen] = useState(false);
204
+ const id = useId();
205
+ const has = props.content != null && props.content !== "";
206
+ return _jsxs("span", { className: "ainui-tooltip", onMouseEnter: () => setOpen(true), onMouseLeave: () => setOpen(false), onFocus: () => setOpen(true), onBlur: () => setOpen(false), onKeyDown: (e) => { if (e.key === "Escape")
207
+ setOpen(false); }, children: [_jsx("span", { className: "ainui-tooltip-trigger", tabIndex: 0, "aria-describedby": has ? id : undefined, children: _jsx(InlineContext.Provider, { value: true, children: kid(buildChild, props.trigger) }) }), has && _jsx("span", { id: id, role: "tooltip", className: "ainui-tooltip-content", hidden: !open, children: _jsx(InlineContext.Provider, { value: true, children: kid(buildChild, props.content) }) })] });
208
+ });
209
+ export const text = [Title, Text, Caption, Label, Bold, Italic, Underline, Strikethrough, Badge, Blockquote, Code, Markdown, Math_, ShimmerText, Link, Tooltip];