@kashi-ui/react 0.8.0 → 0.9.1

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.
@@ -0,0 +1,90 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useId, useRef, useState } from "react";
3
+ import { toFaDigits } from "@kashi-ui/persian";
4
+ import { cx } from "./cx.js";
5
+ import { Progress } from "./Progress.js";
6
+ /** حجم فایل به فارسی: ۱٫۲ مگابایت */
7
+ export function formatBytes(bytes) {
8
+ const units = ["بایت", "کیلوبایت", "مگابایت", "گیگابایت"];
9
+ let v = bytes;
10
+ let i = 0;
11
+ while (v >= 1024 && i < units.length - 1) {
12
+ v /= 1024;
13
+ i++;
14
+ }
15
+ const n = i === 0 ? String(v) : v.toFixed(v < 10 ? 1 : 0).replace(/\.0$/, "");
16
+ return `${toFaDigits(n).replace(".", "٫")} ${units[i]}`;
17
+ }
18
+ const ext = (name) => (name.split(".").pop() ?? "").slice(0, 4).toUpperCase();
19
+ function accepts(file, accept) {
20
+ if (!accept)
21
+ return true;
22
+ return accept.split(",").map((a) => a.trim().toLowerCase()).some((a) => a.startsWith(".") ? file.name.toLowerCase().endsWith(a) : a.endsWith("/*") ? file.type.startsWith(a.slice(0, -1)) : file.type === a);
23
+ }
24
+ const UploadIcon = () => (_jsx("svg", { viewBox: "0 0 20 20", fill: "none", stroke: "currentColor", strokeWidth: 1.7, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: _jsx("path", { d: "M10 13V3.5m-4 4 4-4 4 4M4 13v2.5A1.5 1.5 0 0 0 5.5 17h9a1.5 1.5 0 0 0 1.5-1.5V13" }) }));
25
+ const TrashIcon = () => (_jsx("svg", { viewBox: "0 0 20 20", fill: "none", stroke: "currentColor", strokeWidth: 1.7, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: _jsx("path", { d: "M3.5 5.5h13M8 5.5V4h4v1.5M5 5.5l.8 10.2a1.5 1.5 0 0 0 1.5 1.3h5.4a1.5 1.5 0 0 0 1.5-1.3L15 5.5" }) }));
26
+ /** بارگذاری فایل با کشیدن و رها کردن یا دکمهٔ انتخاب؛ هر فایل وضعیت و پیشرفت خودش را دارد */
27
+ export function FileUpload({ accept, multiple = true, maxSize, maxFiles, uploader, onFilesChange, hint, disabled, name, className, labels = {} }) {
28
+ const id = useId();
29
+ const inputRef = useRef(null);
30
+ const [items, setItems] = useState([]);
31
+ const [dragging, setDragging] = useState(false);
32
+ const [announce, setAnnounce] = useState("");
33
+ const { browse = "انتخاب فایل", drop = "یا فایل را اینجا رها کنید", remove = (n) => `حذف ${n}`, tooBig = (m) => `حجم فایل بیشتر از ${m} است.`, wrongType = "این نوع فایل پذیرفته نیست.", tooMany = (n) => `حداکثر ${toFaDigits(n)} فایل.`, done = "بارگذاری شد", uploading = "در حال بارگذاری", } = labels;
34
+ const update = (fn) => setItems((prev) => {
35
+ const next = fn(prev);
36
+ onFilesChange?.(next);
37
+ return next;
38
+ });
39
+ const add = (files) => {
40
+ const list = Array.from(files).slice(0, multiple ? undefined : 1);
41
+ const added = list.map((file, i) => {
42
+ const fid = `${Date.now()}-${i}-${file.name}`;
43
+ let err;
44
+ if (!accepts(file, accept))
45
+ err = wrongType;
46
+ else if (maxSize && file.size > maxSize)
47
+ err = tooBig(formatBytes(maxSize));
48
+ else if (maxFiles && items.length + i >= maxFiles)
49
+ err = tooMany(maxFiles);
50
+ return { id: fid, file, status: err ? "error" : uploader ? "uploading" : "done", progress: err ? 0 : uploader ? 0 : 100, error: err };
51
+ });
52
+ update((prev) => (multiple ? [...prev, ...added] : added));
53
+ setAnnounce(added.map((a) => `${a.file.name}: ${a.error ?? (uploader ? uploading : done)}`).join("، "));
54
+ for (const it of added) {
55
+ if (it.status !== "uploading" || !uploader)
56
+ continue;
57
+ uploader(it.file, (p) => update((l) => l.map((x) => (x.id === it.id ? { ...x, progress: p } : x))))
58
+ .then(() => {
59
+ update((l) => l.map((x) => (x.id === it.id ? { ...x, status: "done", progress: 100 } : x)));
60
+ setAnnounce(`${it.file.name}: ${done}`);
61
+ })
62
+ .catch((e) => {
63
+ const msg = e instanceof Error ? e.message : "خطا در بارگذاری";
64
+ update((l) => l.map((x) => (x.id === it.id ? { ...x, status: "error", error: msg } : x)));
65
+ setAnnounce(`${it.file.name}: ${msg}`);
66
+ });
67
+ }
68
+ };
69
+ const onDrop = (e) => {
70
+ e.preventDefault();
71
+ setDragging(false);
72
+ if (!disabled && e.dataTransfer.files.length)
73
+ add(e.dataTransfer.files);
74
+ };
75
+ return (_jsxs("div", { className: className, children: [_jsxs("div", { className: "k-dropzone", "data-dragging": dragging ? "" : undefined, "data-disabled": disabled ? "" : undefined, onDragOver: (e) => {
76
+ e.preventDefault();
77
+ if (!disabled)
78
+ setDragging(true);
79
+ }, onDragLeave: (e) => {
80
+ if (!e.currentTarget.contains(e.relatedTarget))
81
+ setDragging(false);
82
+ }, onDrop: onDrop, children: [_jsx("span", { className: "k-dropzone__icon", "aria-hidden": "true", children: _jsx(UploadIcon, {}) }), _jsxs("p", { className: "k-dropzone__title", style: { margin: 0 }, children: [_jsx("button", { type: "button", className: "k-dropzone__browse", disabled: disabled, "aria-describedby": hint ? `${id}-hint` : undefined, onClick: () => inputRef.current?.click(), children: browse }), " ", _jsx("span", { children: drop })] }), hint && _jsx("p", { className: "k-dropzone__hint", id: `${id}-hint`, style: { margin: 0 }, children: hint }), _jsx("input", { ref: inputRef, type: "file", accept: accept, multiple: multiple, name: name, tabIndex: -1, "aria-hidden": "true", onChange: (e) => {
83
+ if (e.target.files?.length)
84
+ add(e.target.files);
85
+ e.target.value = "";
86
+ } })] }), items.length > 0 && (_jsx("ul", { className: "k-file-list", role: "list", children: items.map((it) => (_jsxs("li", { className: "k-file", "data-status": it.status, children: [_jsx("span", { className: "k-file__icon", "aria-hidden": "true", children: ext(it.file.name) }), _jsx("span", { className: "k-file__name", title: it.file.name, children: it.file.name }), _jsx("button", { type: "button", className: cx("k-btn k-btn--tertiary k-btn--icon k-btn--sm k-file__remove"), "aria-label": remove(it.file.name), onClick: () => {
87
+ update((l) => l.filter((x) => x.id !== it.id));
88
+ setAnnounce(`${it.file.name} حذف شد`);
89
+ }, children: _jsx(TrashIcon, {}) }), _jsx("span", { className: "k-file__meta", children: it.error ?? `${formatBytes(it.file.size)}${it.status === "uploading" ? ` · ${toFaDigits(Math.round(it.progress))}٪` : it.status === "done" ? ` · ${done}` : ""}` }), it.status === "uploading" && _jsx(Progress, { value: it.progress, size: "sm", "aria-label": `${uploading} ${it.file.name}` })] }, it.id))) })), _jsx("span", { className: "k-sr-only", "aria-live": "polite", children: announce })] }));
90
+ }
@@ -0,0 +1,29 @@
1
+ import { type ReactNode } from "react";
2
+ export interface NumberInputProps {
3
+ label?: ReactNode;
4
+ hint?: ReactNode;
5
+ error?: ReactNode;
6
+ value?: number | null;
7
+ defaultValue?: number | null;
8
+ onChange?: (value: number | null) => void;
9
+ min?: number;
10
+ max?: number;
11
+ /** @default 1 */
12
+ step?: number;
13
+ /** جداکنندهٔ هزارگان */
14
+ thousands?: boolean;
15
+ /** @default "fa" */
16
+ digits?: "fa" | "latin";
17
+ /** واحد کنار عدد، مثل «نفر» */
18
+ unit?: ReactNode;
19
+ disabled?: boolean;
20
+ name?: string;
21
+ id?: string;
22
+ className?: string;
23
+ labels?: {
24
+ increment?: string;
25
+ decrement?: string;
26
+ };
27
+ }
28
+ /** ورودی عدد با دکمه‌های + و −؛ ↑↓ یک گام، PageUp/PageDown ده گام، Home/End کمینه و بیشینه */
29
+ export declare const NumberInput: import("react").ForwardRefExoticComponent<NumberInputProps & import("react").RefAttributes<HTMLInputElement>>;
@@ -0,0 +1,56 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { forwardRef, useId, useState } from "react";
3
+ import { formatNumber, onlyDigits, toFaDigits } from "@kashi-ui/persian";
4
+ import { cx } from "./cx.js";
5
+ import { Field, describedBy } from "./Field.js";
6
+ const Minus = () => _jsx("svg", { viewBox: "0 0 20 20", fill: "none", stroke: "currentColor", strokeWidth: 1.8, strokeLinecap: "round", "aria-hidden": "true", children: _jsx("path", { d: "M5 10h10" }) });
7
+ const Plus = () => _jsx("svg", { viewBox: "0 0 20 20", fill: "none", stroke: "currentColor", strokeWidth: 1.8, strokeLinecap: "round", "aria-hidden": "true", children: _jsx("path", { d: "M10 5v10M5 10h10" }) });
8
+ /** ورودی عدد با دکمه‌های + و −؛ ↑↓ یک گام، PageUp/PageDown ده گام، Home/End کمینه و بیشینه */
9
+ export const NumberInput = forwardRef(function NumberInput({ label, hint, error, value, defaultValue = null, onChange, min, max, step = 1, thousands, digits = "fa", unit, disabled, name, id, className, labels = {} }, ref) {
10
+ const autoId = useId();
11
+ const inputId = id ?? autoId;
12
+ const [inner, setInner] = useState(defaultValue);
13
+ const current = value !== undefined ? value : inner;
14
+ const [draft, setDraft] = useState(null);
15
+ const { increment = "افزایش", decrement = "کاهش" } = labels;
16
+ const clamp = (n) => Math.min(max ?? Infinity, Math.max(min ?? -Infinity, n));
17
+ const show = (n) => {
18
+ if (n === null)
19
+ return "";
20
+ const s = thousands ? formatNumber(n, { digits: "latin" }) : String(n);
21
+ return digits === "fa" ? toFaDigits(s).replace(/,/g, "٬") : s;
22
+ };
23
+ const set = (n) => {
24
+ // هنگام تایپ محدود نمی‌شود تا عدد نیمه‌کاره پاک نشود؛ محدودسازی در blur و دکمه‌ها
25
+ if (value === undefined)
26
+ setInner(n);
27
+ onChange?.(n);
28
+ };
29
+ const bump = (k) => set(clamp((current ?? min ?? 0) + k * step));
30
+ const onKeyDown = (e) => {
31
+ const keys = {
32
+ ArrowUp: () => bump(1),
33
+ ArrowDown: () => bump(-1),
34
+ PageUp: () => bump(10),
35
+ PageDown: () => bump(-10),
36
+ Home: () => min !== undefined && set(min),
37
+ End: () => max !== undefined && set(max),
38
+ };
39
+ if (!keys[e.key])
40
+ return;
41
+ e.preventDefault();
42
+ keys[e.key]();
43
+ setDraft(null);
44
+ };
45
+ return (_jsxs(Field, { id: inputId, label: label, hint: hint, error: error, className: className, children: [_jsx("div", { className: cx("k-number"), children: _jsxs("div", { className: "k-input", "data-state": error ? "invalid" : disabled ? "disabled" : undefined, children: [_jsx("button", { type: "button", className: "k-number__step", tabIndex: -1, "aria-label": decrement, disabled: disabled || (min !== undefined && (current ?? 0) <= min), onClick: () => bump(-1), children: _jsx(Minus, {}) }), _jsx("input", { ref: ref, id: inputId, className: "k-input__control", type: "text", inputMode: "decimal", role: "spinbutton", "aria-valuenow": current ?? undefined, "aria-valuemin": min, "aria-valuemax": max, "aria-valuetext": current === null ? undefined : show(current), "aria-invalid": error ? true : undefined, "aria-describedby": describedBy(inputId, hint, error), disabled: disabled, dir: "ltr", value: draft ?? show(current), onChange: (e) => {
46
+ const raw = e.target.value;
47
+ const neg = /^\s*[-−]/.test(raw);
48
+ const d = onlyDigits(raw);
49
+ setDraft(raw);
50
+ set(d ? (neg ? -1 : 1) * Number(d) : null);
51
+ }, onBlur: () => {
52
+ setDraft(null);
53
+ if (current !== null && current !== clamp(current))
54
+ set(clamp(current));
55
+ }, onKeyDown: onKeyDown }), unit && _jsx("span", { className: "k-input__addon", children: unit }), _jsx("button", { type: "button", className: "k-number__step", tabIndex: -1, "aria-label": increment, disabled: disabled || (max !== undefined && (current ?? 0) >= max), onClick: () => bump(1), children: _jsx(Plus, {}) })] }) }), name && _jsx("input", { type: "hidden", name: name, value: current ?? "" })] }));
56
+ });
@@ -0,0 +1,19 @@
1
+ import { type ReactElement, type ReactNode } from "react";
2
+ export interface PopoverProps {
3
+ /** دکمه‌ای که پنجره را باز می‌کند */
4
+ trigger: ReactElement;
5
+ title?: ReactNode;
6
+ children: ReactNode;
7
+ open?: boolean;
8
+ onOpenChange?: (open: boolean) => void;
9
+ /** @default "bottom-start" */
10
+ placement?: "bottom-start" | "bottom-end" | "top-start" | "top-end";
11
+ /** نام پنجره اگر title ندارد */
12
+ "aria-label"?: string;
13
+ className?: string;
14
+ }
15
+ /**
16
+ * پنجرهٔ شناور غیرمودال کنار یک دکمه؛ برای فرم کوتاه، فیلتر یا توضیح.
17
+ * فوکوس به داخل می‌رود، Esc و کلیک بیرون می‌بندد و فوکوس به دکمه برمی‌گردد.
18
+ */
19
+ export declare function Popover({ trigger, title, children, open, onOpenChange, placement, "aria-label": ariaLabel, className }: PopoverProps): import("react").JSX.Element;
@@ -0,0 +1,58 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { cloneElement, isValidElement, useEffect, useId, useRef, useState } from "react";
3
+ import { cx } from "./cx.js";
4
+ const FOCUSABLE = 'a[href], button:not([disabled]), input:not([disabled]), select, textarea, [tabindex]:not([tabindex="-1"])';
5
+ /**
6
+ * پنجرهٔ شناور غیرمودال کنار یک دکمه؛ برای فرم کوتاه، فیلتر یا توضیح.
7
+ * فوکوس به داخل می‌رود، Esc و کلیک بیرون می‌بندد و فوکوس به دکمه برمی‌گردد.
8
+ */
9
+ export function Popover({ trigger, title, children, open, onOpenChange, placement = "bottom-start", "aria-label": ariaLabel, className }) {
10
+ const id = useId();
11
+ const [inner, setInner] = useState(false);
12
+ const isOpen = open ?? inner;
13
+ const anchor = useRef(null);
14
+ const panel = useRef(null);
15
+ const triggerRef = useRef(null);
16
+ const set = (v, focusTrigger = false) => {
17
+ if (open === undefined)
18
+ setInner(v);
19
+ onOpenChange?.(v);
20
+ if (!v && focusTrigger)
21
+ triggerRef.current?.focus();
22
+ };
23
+ useEffect(() => {
24
+ if (!isOpen)
25
+ return;
26
+ const p = panel.current;
27
+ (p?.querySelector(FOCUSABLE) ?? p)?.focus();
28
+ const onDown = (e) => {
29
+ if (!anchor.current?.contains(e.target))
30
+ set(false);
31
+ };
32
+ document.addEventListener("pointerdown", onDown);
33
+ return () => document.removeEventListener("pointerdown", onDown);
34
+ }, [isOpen]);
35
+ const t = isValidElement(trigger)
36
+ ? cloneElement(trigger, {
37
+ ref: triggerRef,
38
+ "aria-haspopup": "dialog",
39
+ "aria-expanded": isOpen,
40
+ "aria-controls": isOpen ? `${id}-panel` : undefined,
41
+ onClick: (e) => {
42
+ trigger.props.onClick?.(e);
43
+ set(!isOpen);
44
+ },
45
+ })
46
+ : trigger;
47
+ const [side, align] = placement.split("-");
48
+ return (_jsxs("span", { className: "k-popover-anchor", ref: anchor, children: [t, _jsxs("div", { ref: panel, id: `${id}-panel`, role: "dialog", "aria-labelledby": title ? `${id}-title` : undefined, "aria-label": title ? undefined : ariaLabel, tabIndex: -1, hidden: !isOpen, className: cx("k-popover", side === "top" && "k-popover--top", align === "end" && "k-popover--end", className), onKeyDown: (e) => {
49
+ if (e.key === "Escape") {
50
+ e.stopPropagation();
51
+ set(false, true);
52
+ }
53
+ }, onBlur: (e) => {
54
+ const next = e.relatedTarget;
55
+ if (next && !anchor.current?.contains(next))
56
+ set(false);
57
+ }, children: [title && _jsx("p", { className: "k-popover__title", id: `${id}-title`, children: title }), _jsx("div", { className: "k-popover__body", children: children })] })] }));
58
+ }
@@ -0,0 +1,28 @@
1
+ import { type ReactNode } from "react";
2
+ export interface SideNavItem {
3
+ label: string;
4
+ href?: string;
5
+ icon?: ReactNode;
6
+ /** نشان کنار مورد، مثل تعداد */
7
+ badge?: ReactNode;
8
+ current?: boolean;
9
+ onClick?: () => void;
10
+ /** زیرمنو؛ مورد والد به دکمهٔ باز و بسته تبدیل می‌شود */
11
+ items?: SideNavItem[];
12
+ }
13
+ export interface SideNavSection {
14
+ label?: string;
15
+ items: SideNavItem[];
16
+ }
17
+ export interface SideNavProps {
18
+ sections: SideNavSection[];
19
+ header?: ReactNode;
20
+ footer?: ReactNode;
21
+ /** فقط آیکون‌ها؛ نام هر مورد با aria-label و title حفظ می‌شود */
22
+ collapsed?: boolean;
23
+ /** @default "اصلی" */
24
+ "aria-label"?: string;
25
+ className?: string;
26
+ }
27
+ /** ناوبری کناری پنل مدیریت با گروه، زیرمنو، نشان و حالت جمع‌شده */
28
+ export declare function SideNav({ sections, header, footer, collapsed, "aria-label": ariaLabel, className }: SideNavProps): import("react").JSX.Element;
@@ -0,0 +1,22 @@
1
+ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useId, useState } from "react";
3
+ import { cx } from "./cx.js";
4
+ const Chevron = () => (_jsx("svg", { className: "k-sidenav__chevron", viewBox: "0 0 20 20", fill: "none", stroke: "currentColor", strokeWidth: 1.7, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: _jsx("path", { d: "m6 8 4 4 4-4" }) }));
5
+ const hasCurrent = (it) => Boolean(it.current || it.items?.some(hasCurrent));
6
+ function Item({ item, collapsed }) {
7
+ const id = useId();
8
+ // زیرمنویی که صفحهٔ فعلی در آن است از اول باز است
9
+ const [open, setOpen] = useState(() => Boolean(item.items?.some(hasCurrent)));
10
+ const a11y = collapsed ? { "aria-label": item.label, title: item.label } : {};
11
+ const inner = (_jsxs(_Fragment, { children: [item.icon, _jsx("span", { className: "k-sidenav__text", children: item.label }), item.badge] }));
12
+ if (item.items?.length) {
13
+ return (_jsxs("li", { children: [_jsxs("button", { type: "button", className: "k-sidenav__item", "aria-expanded": open, "aria-controls": `${id}-sub`, onClick: () => setOpen((o) => !o), ...a11y, children: [inner, _jsx(Chevron, {})] }), _jsx("ul", { className: "k-sidenav__sub", id: `${id}-sub`, role: "list", hidden: !open, children: item.items.map((s) => _jsx(Item, { item: s, collapsed: collapsed }, s.label)) })] }));
14
+ }
15
+ const props = { className: "k-sidenav__item", "aria-current": item.current ? "page" : undefined, onClick: item.onClick, ...a11y };
16
+ return _jsx("li", { children: item.href ? _jsx("a", { href: item.href, ...props, children: inner }) : _jsx("button", { type: "button", ...props, children: inner }) });
17
+ }
18
+ /** ناوبری کناری پنل مدیریت با گروه، زیرمنو، نشان و حالت جمع‌شده */
19
+ export function SideNav({ sections, header, footer, collapsed, "aria-label": ariaLabel = "اصلی", className }) {
20
+ const id = useId();
21
+ return (_jsxs("nav", { className: cx("k-sidenav", collapsed && "k-sidenav--collapsed", className), "aria-label": ariaLabel, children: [header && _jsx("div", { className: "k-sidenav__header", children: header }), sections.map((sec, i) => (_jsxs("div", { children: [sec.label && _jsx("p", { className: "k-sidenav__label", id: `${id}-s${i}`, children: sec.label }), _jsx("ul", { className: "k-sidenav__group", role: "list", "aria-labelledby": sec.label ? `${id}-s${i}` : undefined, children: sec.items.map((it) => _jsx(Item, { item: it, collapsed: collapsed }, it.label)) })] }, sec.label ?? i))), footer && _jsx("div", { className: "k-sidenav__footer", children: footer })] }));
22
+ }
@@ -0,0 +1,32 @@
1
+ import { type ReactNode } from "react";
2
+ type Val = number | [number, number];
3
+ export interface SliderProps<V extends Val = Val> {
4
+ label?: ReactNode;
5
+ /** یک عدد، یا [از، تا] برای بازه */
6
+ value?: V;
7
+ defaultValue?: V;
8
+ onChange?: (value: V) => void;
9
+ /** @default 0 */
10
+ min?: number;
11
+ /** @default 100 */
12
+ max?: number;
13
+ /** @default 1 */
14
+ step?: number;
15
+ /** نمایش مقدار کنار برچسب @default true */
16
+ showValue?: boolean;
17
+ /** قالب نمایش؛ پیش‌فرض ارقام فارسی با جداکنندهٔ هزارگان */
18
+ format?: (n: number) => string;
19
+ /** برچسب‌های زیر نوار، مثل [0, 50, 100] */
20
+ marks?: number[];
21
+ disabled?: boolean;
22
+ name?: string;
23
+ className?: string;
24
+ labels?: {
25
+ from?: string;
26
+ to?: string;
27
+ separator?: string;
28
+ };
29
+ }
30
+ /** لغزنده روی <input type="range"> بومی؛ با آرایهٔ دوتایی، بازه با دو دستگیره */
31
+ export declare function Slider<V extends Val>({ label, value, defaultValue, onChange, min, max, step, showValue, format, marks, disabled, name, className, labels, }: SliderProps<V>): import("react").JSX.Element;
32
+ export {};
package/dist/Slider.js ADDED
@@ -0,0 +1,33 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useId, useState } from "react";
3
+ import { formatNumber } from "@kashi-ui/persian";
4
+ import { cx } from "./cx.js";
5
+ /** لغزنده روی <input type="range"> بومی؛ با آرایهٔ دوتایی، بازه با دو دستگیره */
6
+ export function Slider({ label, value, defaultValue, onChange, min = 0, max = 100, step = 1, showValue = true, format = (n) => formatNumber(n), marks, disabled, name, className, labels = {}, }) {
7
+ const id = useId();
8
+ const isRange = Array.isArray(value ?? defaultValue);
9
+ const [inner, setInner] = useState(defaultValue ?? (isRange ? [min, max] : min));
10
+ const current = (value ?? inner);
11
+ const [lo, hi] = Array.isArray(current) ? current : [min, current];
12
+ const pct = (n) => `${((n - min) / (max - min)) * 100}%`;
13
+ const { from = "حداقل", to = "حداکثر", separator = " تا " } = labels;
14
+ const set = (next) => {
15
+ if (value === undefined)
16
+ setInner(next);
17
+ onChange?.(next);
18
+ };
19
+ const fill = { "--_from": isRange ? pct(lo) : "0%", "--_to": pct(hi) };
20
+ const labelId = `${id}-label`;
21
+ const input = (which) => {
22
+ const v = which === "lo" ? lo : hi;
23
+ return (_jsx("input", { type: "range", className: "k-slider__input", min: min, max: max, step: step, value: v, disabled: disabled, name: name ? (isRange ? `${name}_${which === "lo" ? "min" : "max"}` : name) : undefined, "aria-labelledby": isRange ? undefined : label ? labelId : undefined, "aria-label": isRange ? `${which === "lo" ? from : to}${typeof label === "string" ? ` ${label}` : ""}` : undefined, "aria-valuetext": format(v), onChange: (e) => {
24
+ const n = Number(e.target.value);
25
+ // دستگیره‌ها از روی هم رد نمی‌شوند
26
+ if (!isRange)
27
+ set(n);
28
+ else
29
+ set(which === "lo" ? [Math.min(n, hi), hi] : [lo, Math.max(n, lo)]);
30
+ } }));
31
+ };
32
+ return (_jsxs("div", { className: cx("k-slider", className), "data-range": isRange ? "" : undefined, children: [(label || showValue) && (_jsxs("div", { className: "k-slider__head", children: [label && _jsx("span", { className: "k-label", id: labelId, children: label }), showValue && _jsx("span", { className: "k-slider__value", "aria-hidden": "true", children: isRange ? `${format(lo)}${separator}${format(hi)}` : format(hi) })] })), _jsxs("div", { className: "k-slider__track", style: fill, children: [_jsx("span", { className: "k-slider__fill", "aria-hidden": "true" }), isRange && input("lo"), input("hi")] }), marks && (_jsx("div", { className: "k-slider__marks", "aria-hidden": "true", children: marks.map((m) => _jsx("span", { children: format(m) }, m)) }))] }));
33
+ }
package/dist/Stat.d.ts ADDED
@@ -0,0 +1,24 @@
1
+ import { type HTMLAttributes, type ReactNode } from "react";
2
+ export interface StatCardProps extends Omit<HTMLAttributes<HTMLDivElement>, "title"> {
3
+ label: ReactNode;
4
+ value: ReactNode;
5
+ /** واحد کوچک کنار عدد، مثل «تومان» یا «نفر» */
6
+ unit?: ReactNode;
7
+ icon?: ReactNode;
8
+ /** درصد تغییر؛ مثبت افزایش، منفی کاهش */
9
+ change?: number;
10
+ /** برای شاخص‌هایی که کاهش در آن‌ها خوب است، مثل نرخ خطا */
11
+ invertTrend?: boolean;
12
+ /** متن کنار روند، مثل «نسبت به ماه قبل» */
13
+ caption?: ReactNode;
14
+ /** نمودار کوچک یا هر محتوای دیگر در پایین کارت */
15
+ children?: ReactNode;
16
+ labels?: {
17
+ up?: string;
18
+ down?: string;
19
+ flat?: string;
20
+ };
21
+ }
22
+ /** کارت شاخص کلیدی (KPI) با روند؛ صفحه‌خوان روند را به شکل «۱۲٪ افزایش» می‌خواند */
23
+ export declare const StatCard: import("react").ForwardRefExoticComponent<StatCardProps & import("react").RefAttributes<HTMLDivElement>>;
24
+ export declare function StatGrid({ className, ...rest }: HTMLAttributes<HTMLDivElement>): import("react").JSX.Element;
package/dist/Stat.js ADDED
@@ -0,0 +1,17 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { forwardRef } from "react";
3
+ import { toFaDigits } from "@kashi-ui/persian";
4
+ import { cx } from "./cx.js";
5
+ const Arrow = ({ dir }) => (_jsx("svg", { viewBox: "0 0 20 20", fill: "none", stroke: "currentColor", strokeWidth: 1.8, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: dir === "up" ? _jsx("path", { d: "M10 15V5m0 0-4 4m4-4 4 4" }) : _jsx("path", { d: "M10 5v10m0 0-4-4m4 4 4-4" }) }));
6
+ /** کارت شاخص کلیدی (KPI) با روند؛ صفحه‌خوان روند را به شکل «۱۲٪ افزایش» می‌خواند */
7
+ export const StatCard = forwardRef(function StatCard({ label, value, unit, icon, change, invertTrend, caption, children, labels = {}, className, ...rest }, ref) {
8
+ const { up = "افزایش", down = "کاهش", flat = "بدون تغییر" } = labels;
9
+ const dir = change === undefined ? null : change > 0 ? "up" : change < 0 ? "down" : "flat";
10
+ // رنگ بر اساس خوب یا بد بودن، نه جهت
11
+ const good = dir === "flat" ? "flat" : (dir === "up") !== Boolean(invertTrend) ? "up" : "down";
12
+ const pct = change === undefined ? "" : `${toFaDigits(Math.abs(Math.round(change * 10) / 10)).replace(".", "٫")}٪`;
13
+ return (_jsxs("div", { ref: ref, className: cx("k-stat", className), ...rest, children: [_jsxs("div", { className: "k-stat__head", children: [icon && _jsx("span", { className: "k-stat__icon", "aria-hidden": "true", children: icon }), _jsx("p", { className: "k-stat__label", children: label })] }), _jsxs("p", { className: "k-stat__value", children: [_jsx("span", { children: value }), unit && _jsx("span", { className: "k-stat__unit", children: unit })] }), (dir || caption) && (_jsxs("div", { className: "k-stat__foot", children: [dir && (_jsxs("span", { className: `k-trend k-trend--${good}`, children: [dir !== "flat" && _jsx(Arrow, { dir: dir }), _jsx("span", { "aria-hidden": "true", children: dir === "flat" ? flat : pct }), _jsx("span", { className: "k-sr-only", children: dir === "flat" ? flat : `${pct} ${dir === "up" ? up : down}` })] })), caption && _jsx("span", { children: caption })] })), children && _jsx("div", { className: "k-stat__chart", children: children })] }));
14
+ });
15
+ export function StatGrid({ className, ...rest }) {
16
+ return _jsx("div", { className: cx("k-stat-grid", className), ...rest });
17
+ }
@@ -0,0 +1,33 @@
1
+ import { type ReactNode } from "react";
2
+ import { type BadgeTone } from "./Badge.js";
3
+ export interface TagInputProps {
4
+ label?: ReactNode;
5
+ hint?: ReactNode;
6
+ error?: ReactNode;
7
+ value?: string[];
8
+ defaultValue?: string[];
9
+ onChange?: (tags: string[]) => void;
10
+ placeholder?: string;
11
+ /** کلیدهایی که برچسب را ثبت می‌کنند @default ["Enter", ",", "،"] */
12
+ separators?: string[];
13
+ /** بررسی هر برچسب؛ متن خطا برمی‌گرداند یا undefined */
14
+ validate?: (tag: string) => string | undefined;
15
+ /** بیشترین تعداد */
16
+ max?: number;
17
+ /** @default false */
18
+ allowDuplicates?: boolean;
19
+ tone?: BadgeTone;
20
+ disabled?: boolean;
21
+ name?: string;
22
+ id?: string;
23
+ className?: string;
24
+ labels?: {
25
+ added?: (t: string) => string;
26
+ removed?: (t: string) => string;
27
+ remove?: (t: string) => string;
28
+ max?: (n: number) => string;
29
+ duplicate?: string;
30
+ };
31
+ }
32
+ /** ورود چند مقدار، مثل مهارت‌ها یا ایمیل‌ها؛ Enter یا ویرگول (, یا ،) ثبت می‌کند و Backspace آخری را حذف می‌کند */
33
+ export declare const TagInput: import("react").ForwardRefExoticComponent<TagInputProps & import("react").RefAttributes<HTMLInputElement>>;
@@ -0,0 +1,88 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { forwardRef, useId, useRef, useState } from "react";
3
+ import { normalizePersian, toFaDigits } from "@kashi-ui/persian";
4
+ import { Badge } from "./Badge.js";
5
+ import { Field, describedBy } from "./Field.js";
6
+ import { mergeRefs } from "./utils.js";
7
+ /** ورود چند مقدار، مثل مهارت‌ها یا ایمیل‌ها؛ Enter یا ویرگول (, یا ،) ثبت می‌کند و Backspace آخری را حذف می‌کند */
8
+ export const TagInput = forwardRef(function TagInput({ label, hint, error, value, defaultValue = [], onChange, placeholder, separators = ["Enter", ",", "،"], validate, max, allowDuplicates = false, tone = "brand", disabled, name, id, className, labels = {}, }, ref) {
9
+ const autoId = useId();
10
+ const inputId = id ?? autoId;
11
+ const [inner, setInner] = useState(defaultValue);
12
+ const tags = value !== undefined ? value : inner;
13
+ const [text, setText] = useState("");
14
+ const [localError, setLocalError] = useState();
15
+ const [announce, setAnnounce] = useState("");
16
+ const inputRef = useRef(null);
17
+ const { added = (t) => `${t} اضافه شد`, removed = (t) => `${t} حذف شد`, remove = (t) => `حذف ${t}`, max: maxMsg = (n) => `حداکثر ${toFaDigits(n)} مورد`, duplicate = "این مورد قبلاً اضافه شده است.", } = labels;
18
+ const set = (next) => {
19
+ if (value === undefined)
20
+ setInner(next);
21
+ onChange?.(next);
22
+ };
23
+ /** چند برچسب را یکجا اضافه می‌کند؛ اگر یکی نامعتبر بود، متنش در فیلد می‌ماند */
24
+ const addMany = (raw) => {
25
+ let next = [...tags];
26
+ for (const r of raw) {
27
+ const t = normalizePersian(r).trim();
28
+ if (!t)
29
+ continue;
30
+ if (max !== undefined && next.length >= max)
31
+ return fail(maxMsg(max), t);
32
+ if (!allowDuplicates && next.includes(t))
33
+ return fail(duplicate, t);
34
+ const err = validate?.(t);
35
+ if (err)
36
+ return fail(err, t);
37
+ next = [...next, t];
38
+ setAnnounce(added(t));
39
+ }
40
+ set(next);
41
+ setText("");
42
+ setLocalError(undefined);
43
+ function fail(msg, t) {
44
+ set(next);
45
+ setText(t);
46
+ setLocalError(msg);
47
+ }
48
+ };
49
+ const removeAt = (i) => {
50
+ const t = tags[i];
51
+ set(tags.filter((_, j) => j !== i));
52
+ setAnnounce(removed(t));
53
+ inputRef.current?.focus();
54
+ };
55
+ const singleSeps = separators.filter((s) => s.length === 1).map((s) => `\\${s}`).join("");
56
+ const onKeyDown = (e) => {
57
+ if (separators.includes(e.key) && text.trim()) {
58
+ e.preventDefault();
59
+ addMany([text]);
60
+ }
61
+ else if (e.key === "Backspace" && !text && tags.length) {
62
+ removeAt(tags.length - 1);
63
+ }
64
+ };
65
+ const onPaste = (e) => {
66
+ const data = e.clipboardData.getData("text");
67
+ const parts = data.split(new RegExp(`[${singleSeps}\\n\\t]`));
68
+ if (parts.length > 1) {
69
+ e.preventDefault();
70
+ addMany(parts);
71
+ }
72
+ };
73
+ const shownError = error ?? localError;
74
+ return (_jsxs(Field, { id: inputId, label: label, hint: hint, error: shownError, className: className, children: [_jsxs("div", { className: "k-tag-input", "data-invalid": shownError ? "" : undefined, onClick: () => inputRef.current?.focus(), children: [tags.map((t, i) => (_jsx(Badge, { tone: tone, onRemove: disabled ? undefined : () => removeAt(i), removeLabel: remove(t), children: t }, `${t}-${i}`))), _jsx("input", { ref: mergeRefs(ref, inputRef), id: inputId, className: "k-tag-input__control", value: text, placeholder: tags.length ? undefined : placeholder, disabled: disabled, "aria-invalid": shownError ? true : undefined, "aria-describedby": describedBy(inputId, hint, shownError), onChange: (e) => {
75
+ const v = e.target.value;
76
+ setLocalError(undefined);
77
+ // صفحه‌کلید موبایل و IME رویداد کلید نمی‌فرستند؛ جداکننده را در متن هم پیدا کن
78
+ const parts = v.split(new RegExp(`[${singleSeps}]`));
79
+ if (singleSeps && parts.length > 1) {
80
+ const rest = parts.pop() ?? "";
81
+ addMany(parts);
82
+ if (rest)
83
+ setText(rest);
84
+ }
85
+ else
86
+ setText(v);
87
+ }, onKeyDown: onKeyDown, onPaste: onPaste, onBlur: () => text.trim() && addMany([text]) })] }), _jsx("span", { className: "k-sr-only", "aria-live": "polite", children: announce }), name && tags.map((t, i) => _jsx("input", { type: "hidden", name: name, value: t }, i))] }));
88
+ });
@@ -0,0 +1,19 @@
1
+ import type { HTMLAttributes, ReactNode } from "react";
2
+ export interface TimelineItem {
3
+ id?: string | number;
4
+ title: ReactNode;
5
+ /** Date به شکل نسبی («۵ دقیقه پیش») نمایش داده می‌شود */
6
+ time?: Date | ReactNode;
7
+ /** آیکون یا آواتار داخل نشانگر */
8
+ icon?: ReactNode;
9
+ tone?: "neutral" | "brand" | "success" | "error";
10
+ /** متن یا محتوای اضافه در کادر زیر عنوان، مثل متن کامنت */
11
+ content?: ReactNode;
12
+ }
13
+ export interface TimelineProps extends HTMLAttributes<HTMLOListElement> {
14
+ items: TimelineItem[];
15
+ /** @default "fa" */
16
+ digits?: "fa" | "latin";
17
+ }
18
+ /** خط زمانی رویدادها و فعالیت‌ها، به ترتیب داده‌شده */
19
+ export declare function Timeline({ items, digits, className, ...rest }: TimelineProps): import("react").JSX.Element;
@@ -0,0 +1,8 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { cx } from "./cx.js";
3
+ import { RelativeTime } from "./RelativeTime.js";
4
+ const Dot = () => _jsx("svg", { viewBox: "0 0 20 20", "aria-hidden": "true", children: _jsx("circle", { cx: "10", cy: "10", r: "3", fill: "currentColor" }) });
5
+ /** خط زمانی رویدادها و فعالیت‌ها، به ترتیب داده‌شده */
6
+ export function Timeline({ items, digits = "fa", className, ...rest }) {
7
+ return (_jsx("ol", { className: cx("k-timeline", className), ...rest, children: items.map((it, i) => (_jsxs("li", { className: "k-timeline__item", "data-tone": it.tone && it.tone !== "neutral" ? it.tone : undefined, children: [_jsx("span", { className: "k-timeline__marker", "aria-hidden": "true", children: it.icon ?? _jsx(Dot, {}) }), _jsxs("div", { className: "k-timeline__body", children: [_jsx("p", { className: "k-timeline__title", children: it.title }), it.time !== undefined && (_jsx("span", { className: "k-timeline__time", children: it.time instanceof Date ? _jsx(RelativeTime, { date: it.time, digits: digits }) : it.time })), it.content && _jsx("div", { className: "k-timeline__content", children: it.content })] })] }, it.id ?? i))) }));
8
+ }
package/dist/index.d.ts CHANGED
@@ -62,3 +62,25 @@ export { Accordion, AccordionItem } from "./Accordion.js";
62
62
  export type { AccordionProps, AccordionItemProps } from "./Accordion.js";
63
63
  export { Stepper } from "./Stepper.js";
64
64
  export type { StepperProps, Step } from "./Stepper.js";
65
+ export { Combobox, defaultFilter, highlight, searchText } from "./Combobox.js";
66
+ export type { ComboboxOption, ComboboxProps } from "./Combobox.js";
67
+ export { CommandPalette } from "./CommandPalette.js";
68
+ export type { CommandPaletteProps, CommandItem } from "./CommandPalette.js";
69
+ export { TagInput } from "./TagInput.js";
70
+ export type { TagInputProps } from "./TagInput.js";
71
+ export { FileUpload, formatBytes } from "./FileUpload.js";
72
+ export type { FileUploadProps, FileItem, FileStatus } from "./FileUpload.js";
73
+ export { Slider } from "./Slider.js";
74
+ export type { SliderProps } from "./Slider.js";
75
+ export { NumberInput } from "./NumberInput.js";
76
+ export type { NumberInputProps } from "./NumberInput.js";
77
+ export { Popover } from "./Popover.js";
78
+ export type { PopoverProps } from "./Popover.js";
79
+ export { DateRangePicker, defaultRangePresets } from "./DateRangePicker.js";
80
+ export type { DateRange, DateRangePreset, DateRangePickerProps } from "./DateRangePicker.js";
81
+ export { StatCard, StatGrid } from "./Stat.js";
82
+ export type { StatCardProps } from "./Stat.js";
83
+ export { Timeline } from "./Timeline.js";
84
+ export type { TimelineItem, TimelineProps } from "./Timeline.js";
85
+ export { SideNav } from "./SideNav.js";
86
+ export type { SideNavItem, SideNavSection, SideNavProps } from "./SideNav.js";
package/dist/index.js CHANGED
@@ -31,3 +31,14 @@ export { DataTable } from "./DataTable.js";
31
31
  export { OtpInput } from "./OtpInput.js";
32
32
  export { Accordion, AccordionItem } from "./Accordion.js";
33
33
  export { Stepper } from "./Stepper.js";
34
+ export { Combobox, defaultFilter, highlight, searchText } from "./Combobox.js";
35
+ export { CommandPalette } from "./CommandPalette.js";
36
+ export { TagInput } from "./TagInput.js";
37
+ export { FileUpload, formatBytes } from "./FileUpload.js";
38
+ export { Slider } from "./Slider.js";
39
+ export { NumberInput } from "./NumberInput.js";
40
+ export { Popover } from "./Popover.js";
41
+ export { DateRangePicker, defaultRangePresets } from "./DateRangePicker.js";
42
+ export { StatCard, StatGrid } from "./Stat.js";
43
+ export { Timeline } from "./Timeline.js";
44
+ export { SideNav } from "./SideNav.js";