@kashi-ui/react 2.7.0 → 2.8.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,34 @@
1
+ import { type ReactNode } from "react";
2
+ export interface BottomSheetProps {
3
+ open: boolean;
4
+ onOpenChange: (open: boolean) => void;
5
+ title: ReactNode;
6
+ description?: ReactNode;
7
+ /** پنهان کردن عنوان از دید (صفحه‌خوان همچنان می‌خواند) */
8
+ hideTitle?: boolean;
9
+ /**
10
+ * ارتفاع‌های ایست به نسبت ارتفاع صفحه، از کوچک به بزرگ (مثل [0.5, 0.9]).
11
+ * بدون آن، برگه به اندازهٔ محتواست (حداکثر ۹۰٪) و کشیدن فقط برای بستن است.
12
+ */
13
+ snapPoints?: number[];
14
+ /** ایست اولیه (اندیس snapPoints) @default 0 */
15
+ defaultSnap?: number;
16
+ /** ایست فعلی (کنترل‌شده) */
17
+ snap?: number;
18
+ onSnapChange?: (index: number) => void;
19
+ /** دکمه‌های پایین برگه */
20
+ footer?: ReactNode;
21
+ /** بستن با کلیک روی پس‌زمینه و کشیدن به پایین @default true */
22
+ dismissible?: boolean;
23
+ /** دکمهٔ بستن در سربرگ @default false (دستگیره و Esc کافی‌اند) */
24
+ showClose?: boolean;
25
+ closeLabel?: string;
26
+ className?: string;
27
+ children?: ReactNode;
28
+ }
29
+ /**
30
+ * برگهٔ پایین برای گوشی روی <dialog> بومی: با دستگیره بالا و پایین کشیده می‌شود،
31
+ * روی ارتفاع‌های تعیین‌شده می‌ایستد و با کشیدن به پایین یا Esc بسته می‌شود.
32
+ * دستگیره با کیبورد هم کار می‌کند: Enter ایست بعدی، جهت‌های بالا و پایین تغییر ارتفاع.
33
+ */
34
+ export declare function BottomSheet({ open, onOpenChange, title, description, hideTitle, snapPoints, defaultSnap, snap, onSnapChange, footer, dismissible, showClose, closeLabel, className, children, }: BottomSheetProps): import("react").JSX.Element;
@@ -0,0 +1,115 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { useEffect, useId, useRef, useState } from "react";
4
+ import { cx } from "./cx.js";
5
+ import { CloseIcon } from "./icons.js";
6
+ import { useKashi } from "./KashiProvider.js";
7
+ import { useModalDialog } from "./modal.js";
8
+ /** فاصله‌ای که بعد از آن، کشیدن به پایین برگه را می‌بندد (نسبت به ارتفاع برگه) */
9
+ const CLOSE_RATIO = 0.3;
10
+ /** سرعت پرتاب (پیکسل بر میلی‌ثانیه) که بدون توجه به فاصله می‌بندد یا ایست را عوض می‌کند */
11
+ const FLING = 0.6;
12
+ /**
13
+ * برگهٔ پایین برای گوشی روی <dialog> بومی: با دستگیره بالا و پایین کشیده می‌شود،
14
+ * روی ارتفاع‌های تعیین‌شده می‌ایستد و با کشیدن به پایین یا Esc بسته می‌شود.
15
+ * دستگیره با کیبورد هم کار می‌کند: Enter ایست بعدی، جهت‌های بالا و پایین تغییر ارتفاع.
16
+ */
17
+ export function BottomSheet({ open, onOpenChange, title, description, hideTitle, snapPoints, defaultSnap = 0, snap, onSnapChange, footer, dismissible = true, showClose = false, closeLabel, className, children, }) {
18
+ const { messages: M } = useKashi();
19
+ closeLabel ?? (closeLabel = M.common.close);
20
+ const ref = useRef(null);
21
+ const id = useId();
22
+ const { restoreFocus } = useModalDialog(ref, open);
23
+ const points = snapPoints?.length ? snapPoints : null;
24
+ const [innerSnap, setInnerSnap] = useState(defaultSnap);
25
+ const current = Math.min(snap ?? innerSnap, (points?.length ?? 1) - 1);
26
+ const drag = useRef(null);
27
+ const setSnap = (i) => {
28
+ if (snap === undefined)
29
+ setInnerSnap(i);
30
+ onSnapChange?.(i);
31
+ };
32
+ // هر بار باز شدن از ایست اولیه شروع شود
33
+ useEffect(() => {
34
+ if (open && snap === undefined)
35
+ setInnerSnap(defaultSnap);
36
+ }, [open, snap, defaultSnap]);
37
+ const style = points ? { "--k-sheet-height": `${points[current] * 100}dvh` } : undefined;
38
+ const onPointerDown = (e) => {
39
+ if (e.button !== 0 || e.target.closest(".k-dialog__close"))
40
+ return;
41
+ const d = ref.current;
42
+ if (!d)
43
+ return;
44
+ drag.current = { y: e.clientY, t: e.timeStamp, h: d.getBoundingClientRect().height, dy: 0, v: 0 };
45
+ e.currentTarget.setPointerCapture(e.pointerId);
46
+ d.setAttribute("data-dragging", "");
47
+ };
48
+ const onPointerMove = (e) => {
49
+ const s = drag.current;
50
+ const d = ref.current;
51
+ if (!s || !d)
52
+ return;
53
+ const dy = e.clientY - s.y;
54
+ const dt = Math.max(1, e.timeStamp - s.t);
55
+ s.v = (dy - s.dy) / dt;
56
+ s.dy = dy;
57
+ s.t = e.timeStamp;
58
+ // بالا کشیدن فقط تا بزرگ‌ترین ایست؛ بیشتر از آن با مقاومت
59
+ const maxUp = points ? (points[points.length - 1] * innerHeight) - s.h : 0;
60
+ const y = dy < 0 ? -Math.min(-dy, Math.max(0, maxUp)) - Math.max(0, -dy - Math.max(0, maxUp)) * 0.15 : dy;
61
+ d.style.translate = `0 ${y}px`;
62
+ };
63
+ const onPointerUp = () => {
64
+ const s = drag.current;
65
+ const d = ref.current;
66
+ drag.current = null;
67
+ if (!s || !d)
68
+ return;
69
+ d.removeAttribute("data-dragging");
70
+ d.style.translate = "";
71
+ const target = s.h - s.dy; // ارتفاع مطلوب کاربر
72
+ if (dismissible && (s.dy > s.h * CLOSE_RATIO || (s.v > FLING && s.dy > 24))) {
73
+ if (!points || current === 0 || s.v > FLING * 1.5 || target < points[0] * innerHeight * 0.6) {
74
+ d.style.translate = `0 ${Math.max(0, s.dy)}px`;
75
+ onOpenChange(false);
76
+ return;
77
+ }
78
+ }
79
+ if (!points)
80
+ return;
81
+ let next = current;
82
+ if (Math.abs(s.v) > FLING)
83
+ next = Math.max(0, Math.min(points.length - 1, current + (s.v < 0 ? 1 : -1)));
84
+ else
85
+ next = points.reduce((best, p, i) => (Math.abs(p * innerHeight - target) < Math.abs(points[best] * innerHeight - target) ? i : best), 0);
86
+ if (next !== current)
87
+ setSnap(next);
88
+ };
89
+ const onHandleKey = (e) => {
90
+ if (!points)
91
+ return;
92
+ if (e.key === "ArrowUp" && current < points.length - 1) {
93
+ e.preventDefault();
94
+ setSnap(current + 1);
95
+ }
96
+ if (e.key === "ArrowDown" && current > 0) {
97
+ e.preventDefault();
98
+ setSnap(current - 1);
99
+ }
100
+ };
101
+ const expanded = points ? current === points.length - 1 : undefined;
102
+ return (_jsxs("dialog", { ref: ref, "data-placement": "bottom", className: cx("k-dialog k-dialog--bottom k-sheet", points && "k-sheet--snap", className), style: style, "aria-labelledby": `${id}-title`, "aria-describedby": description ? `${id}-desc` : undefined, onClose: () => {
103
+ if (ref.current)
104
+ ref.current.style.translate = "";
105
+ if (open)
106
+ onOpenChange(false);
107
+ restoreFocus();
108
+ }, onCancel: (e) => {
109
+ e.preventDefault();
110
+ onOpenChange(false);
111
+ }, onClick: (e) => {
112
+ if (dismissible && e.target === ref.current)
113
+ onOpenChange(false);
114
+ }, children: [_jsxs("div", { className: "k-sheet__grab", onPointerDown: onPointerDown, onPointerMove: onPointerMove, onPointerUp: onPointerUp, onPointerCancel: onPointerUp, children: [points ? (_jsx("button", { type: "button", className: "k-sheet__handle", "aria-label": expanded ? M.sheet.collapse : M.sheet.expand, "aria-expanded": expanded, onClick: () => setSnap(expanded ? 0 : current + 1), onKeyDown: onHandleKey })) : (_jsx("span", { className: "k-sheet__handle", "aria-hidden": "true" })), _jsxs("div", { className: cx("k-dialog__header k-sheet__header", hideTitle && !showClose && "k-sheet__header--hidden"), children: [_jsxs("div", { className: cx("k-dialog__heading", hideTitle && "k-sr-only"), children: [_jsx("h2", { className: "k-dialog__title", id: `${id}-title`, children: title }), description && _jsx("p", { className: "k-dialog__description", id: `${id}-desc`, children: description })] }), showClose && (_jsx("button", { type: "button", className: "k-btn k-btn--tertiary k-btn--icon k-btn--sm k-dialog__close", "aria-label": closeLabel, onClick: () => onOpenChange(false), children: _jsx(CloseIcon, {}) }))] })] }), _jsx("div", { className: "k-dialog__body k-sheet__body", children: children }), footer && _jsx("div", { className: "k-dialog__footer k-sheet__footer", children: footer })] }));
115
+ }
@@ -51,6 +51,14 @@ export interface DataTableProps<T> {
51
51
  onRowClick?: (row: T) => void;
52
52
  /** محتوای پایین جدول، مثل صفحه‌بندی */
53
53
  footer?: ReactNode;
54
+ /**
55
+ * اسکرول مجازی برای هزاران ردیف: فقط ردیف‌های دیده‌شده ساخته می‌شوند.
56
+ * ارتفاع از maxHeight (پیش‌فرض 28rem)؛ ردیف‌ها باید هم‌قد باشند. rowHeight تخمین اولیه است و بعد اندازه‌گیری می‌شود.
57
+ */
58
+ virtual?: boolean | {
59
+ rowHeight?: number;
60
+ overscan?: number;
61
+ };
54
62
  labels?: {
55
63
  selectAll?: string;
56
64
  selectRow?: (row: T) => string;
@@ -67,4 +75,4 @@ export interface DataTableProps<T> {
67
75
  className?: string;
68
76
  }
69
77
  /** جدول داده با مرتب‌سازی (aria-sort)، انتخاب ردیف‌ها و حالت خالی */
70
- export declare function DataTable<T extends Record<string, unknown>>({ columns, rows, getRowId, caption, description, hideCaption, selectable, selected, onSelectedChange, sort, defaultSort, onSortChange, empty, compact, striped, stickyHeader, maxHeight, loading, onRowClick, footer, labels, classNames, className, }: DataTableProps<T>): import("react").JSX.Element;
78
+ export declare function DataTable<T extends Record<string, unknown>>({ columns, rows, getRowId, caption, description, hideCaption, selectable, selected, onSelectedChange, sort, defaultSort, onSortChange, empty, compact, striped, stickyHeader, maxHeight, loading, onRowClick, footer, virtual, labels, classNames, className, }: DataTableProps<T>): import("react").JSX.Element;
package/dist/DataTable.js CHANGED
@@ -1,10 +1,10 @@
1
1
  "use client";
2
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
- import { useEffect, useId, useMemo, useRef, useState } from "react";
2
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
+ import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
4
4
  import { cx } from "./cx.js";
5
5
  import { useKashi } from "./KashiProvider.js";
6
6
  /** جدول داده با مرتب‌سازی (aria-sort)، انتخاب ردیف‌ها و حالت خالی */
7
- export function DataTable({ columns, rows, getRowId, caption, description, hideCaption, selectable, selected, onSelectedChange, sort, defaultSort = null, onSortChange, empty, compact, striped, stickyHeader, maxHeight, loading, onRowClick, footer, labels = {}, classNames = {}, className, }) {
7
+ export function DataTable({ columns, rows, getRowId, caption, description, hideCaption, selectable, selected, onSelectedChange, sort, defaultSort = null, onSortChange, empty, compact, striped, stickyHeader, maxHeight, loading, onRowClick, footer, virtual, labels = {}, classNames = {}, className, }) {
8
8
  const id = useId();
9
9
  const [innerSort, setInnerSort] = useState(defaultSort);
10
10
  const [innerSel, setInnerSel] = useState([]);
@@ -46,17 +46,60 @@ export function DataTable({ columns, rows, getRowId, caption, description, hideC
46
46
  const loadingRows = loading === true ? 5 : typeof loading === "number" ? loading : 0;
47
47
  const cellCls = (c) => cx(c.numeric && "k-table__num", c.align && !c.numeric && `k-table__align-${c.align}`, c.hideBelow && `k-table__hide-${c.hideBelow}`, c.className, classNames.cell) || undefined;
48
48
  const colCount = columns.length + (selectable ? 1 : 0);
49
- return (_jsxs("div", { className: cx("k-table-wrap", stickyHeader && "k-table-wrap--sticky", className, classNames.root), role: "region", "aria-labelledby": `${id}-caption`, "aria-busy": loadingRows > 0 || undefined, tabIndex: 0, style: maxHeight ? { maxBlockSize: maxHeight } : undefined, children: [_jsxs("table", { className: cx("k-table", compact && "k-table--compact", striped && "k-table--striped", onRowClick && "k-table--clickable", classNames.table), children: [_jsxs("caption", { id: `${id}-caption`, className: hideCaption ? "k-sr-only" : undefined, children: [_jsx("span", { className: "k-table__caption-title", children: caption }), description && _jsx("span", { className: "k-table__caption-desc", children: description })] }), _jsx("thead", { children: _jsxs("tr", { children: [selectable && (_jsx("th", { scope: "col", className: "k-table__check", children: _jsx("input", { ref: allRef, type: "checkbox", className: "k-checkbox", "aria-label": selectAll, checked: all, onChange: () => setSel(all ? [] : ids) }) })), columns.map((c) => {
49
+ // ---- اسکرول مجازی
50
+ const vOpts = virtual ? (typeof virtual === "object" ? virtual : {}) : null;
51
+ const wrap = useRef(null);
52
+ const [rowH, setRowH] = useState(vOpts?.rowHeight ?? (compact ? 41 : 53));
53
+ const [view, setView] = useState({ top: 0, height: 0, head: 0 });
54
+ const overscan = vOpts?.overscan ?? 6;
55
+ useEffect(() => {
56
+ const w = wrap.current;
57
+ if (!vOpts || !w)
58
+ return;
59
+ let frame = 0;
60
+ const read = () => {
61
+ frame = 0;
62
+ setView({ top: w.scrollTop, height: w.clientHeight, head: w.querySelector("thead")?.offsetHeight ?? 0 });
63
+ };
64
+ const on = () => { if (!frame)
65
+ frame = requestAnimationFrame(read); };
66
+ read();
67
+ w.addEventListener("scroll", on, { passive: true });
68
+ const ro = typeof ResizeObserver !== "undefined" ? new ResizeObserver(on) : null;
69
+ ro?.observe(w);
70
+ return () => { w.removeEventListener("scroll", on); ro?.disconnect(); cancelAnimationFrame(frame); };
71
+ }, [!!vOpts]);
72
+ const useIso = typeof window === "undefined" ? useEffect : useLayoutEffect;
73
+ useIso(() => {
74
+ // ارتفاع واقعی ردیف را از اولین ردیف ساخته‌شده بخوان
75
+ if (!vOpts || vOpts.rowHeight)
76
+ return;
77
+ const tr = wrap.current?.querySelector("tbody tr[data-row]");
78
+ if (tr && Math.abs(tr.offsetHeight - rowH) > 0.5)
79
+ setRowH(tr.offsetHeight);
80
+ });
81
+ const win = vOpts && sorted.length > 0
82
+ ? (() => {
83
+ const first = Math.max(0, Math.floor((view.top - view.head) / rowH) - overscan);
84
+ const count = Math.ceil((view.height || 600) / rowH) + overscan * 2;
85
+ const last = Math.min(sorted.length, first + count);
86
+ return { first, last, before: first * rowH, after: (sorted.length - last) * rowH };
87
+ })()
88
+ : null;
89
+ const visible = win ? sorted.slice(win.first, win.last) : sorted;
90
+ const spacer = (h, key) => h > 0 && _jsx("tr", { className: "k-table__spacer", "aria-hidden": "true", children: _jsx("td", { colSpan: colCount, style: { blockSize: h, padding: 0, border: 0 } }) }, key);
91
+ return (_jsxs("div", { ref: wrap, className: cx("k-table-wrap", (stickyHeader || vOpts) && "k-table-wrap--sticky", vOpts && "k-table-wrap--virtual", className, classNames.root), role: "region", "aria-labelledby": `${id}-caption`, "aria-busy": loadingRows > 0 || undefined, tabIndex: 0, style: maxHeight || vOpts ? { maxBlockSize: maxHeight ?? "28rem" } : undefined, children: [_jsxs("table", { className: cx("k-table", compact && "k-table--compact", striped && "k-table--striped", onRowClick && "k-table--clickable", classNames.table), "aria-rowcount": vOpts ? sorted.length + 1 : undefined, children: [_jsxs("caption", { id: `${id}-caption`, className: hideCaption ? "k-sr-only" : undefined, children: [_jsx("span", { className: "k-table__caption-title", children: caption }), description && _jsx("span", { className: "k-table__caption-desc", children: description })] }), _jsx("thead", { children: _jsxs("tr", { "aria-rowindex": vOpts ? 1 : undefined, children: [selectable && (_jsx("th", { scope: "col", className: "k-table__check", children: _jsx("input", { ref: allRef, type: "checkbox", className: "k-checkbox", "aria-label": selectAll, checked: all, onChange: () => setSel(all ? [] : ids) }) })), columns.map((c) => {
50
92
  const s = activeSort?.key === c.key ? activeSort.direction : undefined;
51
93
  return (_jsx("th", { scope: "col", "aria-sort": c.sortable ? (s ?? "none") : undefined, className: cx(cellCls(c), classNames.header) || undefined, style: c.width ? { inlineSize: c.width } : undefined, children: c.sortable ? _jsx("button", { type: "button", className: "k-table__sort", onClick: () => setSort(c.key), children: c.header }) : c.header }, c.key));
52
- })] }) }), _jsx("tbody", { children: loadingRows > 0 ? (Array.from({ length: loadingRows }, (_, i) => (_jsxs("tr", { "aria-hidden": "true", children: [selectable && _jsx("td", { className: "k-table__check", children: _jsx("span", { className: "k-skeleton", style: { inlineSize: "1.125rem", blockSize: "1.125rem" } }) }), columns.map((c) => (_jsx("td", { className: cellCls(c), children: _jsx("span", { className: "k-skeleton", style: { inlineSize: `${50 + ((i * 17 + c.key.length * 11) % 40)}%` } }) }, c.key)))] }, `sk-${i}`)))) : sorted.length === 0 ? (_jsx("tr", { className: "k-table__empty", children: _jsx("td", { colSpan: colCount, children: empty ?? _jsx("p", { style: { padding: "2rem", margin: 0, textAlign: "center" }, children: M.table.empty }) }) })) : (sorted.map((r) => {
53
- const rid = getRowId(r);
54
- const on = sel.includes(rid);
55
- return (_jsxs("tr", { "aria-selected": selectable ? on : undefined, className: classNames.row, onClick: onRowClick ? (e) => {
56
- // کلیک روی چک‌باکس، دکمه یا لینک داخل ردیف را ردیف نگیرد
57
- if (e.target.closest("a, button, input, label, select, textarea"))
58
- return;
59
- onRowClick(r);
60
- } : undefined, children: [selectable && (_jsx("td", { className: "k-table__check", children: _jsx("input", { type: "checkbox", className: "k-checkbox", "aria-label": selectRow(r), checked: on, onChange: () => setSel(on ? sel.filter((x) => x !== rid) : [...sel, rid]) }) })), columns.map((c) => (_jsx("td", { className: cellCls(c), children: c.render ? c.render(r) : r[c.key] }, c.key)))] }, rid));
61
- })) })] }), loadingRows > 0 && _jsx("span", { className: "k-sr-only", role: "status", children: loadingLabel }), footer && _jsx("div", { className: cx("k-table__footer", classNames.footer), children: footer })] }));
94
+ })] }) }), _jsx("tbody", { children: loadingRows > 0 ? (Array.from({ length: loadingRows }, (_, i) => (_jsxs("tr", { "aria-hidden": "true", children: [selectable && _jsx("td", { className: "k-table__check", children: _jsx("span", { className: "k-skeleton", style: { inlineSize: "1.125rem", blockSize: "1.125rem" } }) }), columns.map((c) => (_jsx("td", { className: cellCls(c), children: _jsx("span", { className: "k-skeleton", style: { inlineSize: `${50 + ((i * 17 + c.key.length * 11) % 40)}%` } }) }, c.key)))] }, `sk-${i}`)))) : sorted.length === 0 ? (_jsx("tr", { className: "k-table__empty", children: _jsx("td", { colSpan: colCount, children: empty ?? _jsx("p", { style: { padding: "2rem", margin: 0, textAlign: "center" }, children: M.table.empty }) }) })) : (_jsxs(_Fragment, { children: [win && spacer(win.before, "sp-top"), visible.map((r, vi) => {
95
+ const rid = getRowId(r);
96
+ const on = sel.includes(rid);
97
+ const index = (win?.first ?? 0) + vi;
98
+ return (_jsxs("tr", { "data-row": vOpts ? "" : undefined, "aria-rowindex": vOpts ? index + 2 : undefined, className: cx(striped && vOpts && index % 2 === 1 && "k-table__row--odd", classNames.row) || undefined, "aria-selected": selectable ? on : undefined, onClick: onRowClick ? (e) => {
99
+ // کلیک روی چک‌باکس، دکمه یا لینک داخل ردیف را ردیف نگیرد
100
+ if (e.target.closest("a, button, input, label, select, textarea"))
101
+ return;
102
+ onRowClick(r);
103
+ } : undefined, children: [selectable && (_jsx("td", { className: "k-table__check", children: _jsx("input", { type: "checkbox", className: "k-checkbox", "aria-label": selectRow(r), checked: on, onChange: () => setSel(on ? sel.filter((x) => x !== rid) : [...sel, rid]) }) })), columns.map((c) => (_jsx("td", { className: cellCls(c), children: c.render ? c.render(r) : r[c.key] }, c.key)))] }, rid));
104
+ }), win && spacer(win.after, "sp-bottom")] })) })] }), loadingRows > 0 && _jsx("span", { className: "k-sr-only", role: "status", children: loadingLabel }), footer && _jsx("div", { className: cx("k-table__footer", classNames.footer), children: footer })] }));
62
105
  }
package/dist/Dialog.js CHANGED
@@ -1,9 +1,10 @@
1
1
  "use client";
2
2
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
- import { useEffect, useId, useRef } from "react";
3
+ import { useId, useRef } from "react";
4
4
  import { cx } from "./cx.js";
5
5
  import { CloseIcon } from "./icons.js";
6
6
  import { useKashi } from "./KashiProvider.js";
7
+ import { useModalDialog } from "./modal.js";
7
8
  /**
8
9
  * پنجرهٔ گفتگو روی <dialog> بومی با showModal:
9
10
  * فوکوس داخل پنجره می‌ماند، Esc می‌بندد، بقیهٔ صفحه از دسترس صفحه‌خوان خارج می‌شود
@@ -13,23 +14,13 @@ export function Dialog({ open, onOpenChange, title, description, icon, tone = "d
13
14
  const { messages: M } = useKashi();
14
15
  closeLabel ?? (closeLabel = M.common.close);
15
16
  const ref = useRef(null);
16
- const opener = useRef(null);
17
17
  const id = useId();
18
- useEffect(() => {
19
- const d = ref.current;
20
- if (!d)
21
- return;
22
- if (open && !d.open) {
23
- opener.current = document.activeElement;
24
- d.showModal();
25
- }
26
- else if (!open && d.open) {
27
- d.close();
28
- }
29
- }, [open]);
18
+ // باز و بسته با انیمیشن خروج و برگشت فوکوس
19
+ const { restoreFocus } = useModalDialog(ref, open);
30
20
  return (_jsxs("dialog", { ref: ref, "data-placement": placement, className: cx("k-dialog", size !== "md" && `k-dialog--${size}`, placement !== "center" && `k-dialog--${placement}`, tone === "danger" && "k-dialog--danger", className), "aria-labelledby": `${id}-title`, "aria-describedby": description ? `${id}-desc` : undefined, onClose: () => {
31
- onOpenChange(false);
32
- opener.current?.focus?.();
21
+ if (open)
22
+ onOpenChange(false);
23
+ restoreFocus();
33
24
  }, onCancel: (e) => {
34
25
  // Esc: بستن از طریق state تا والد همگام بماند
35
26
  e.preventDefault();
@@ -0,0 +1,24 @@
1
+ import { type ReactNode } from "react";
2
+ export interface DrawerProps {
3
+ open: boolean;
4
+ onOpenChange: (open: boolean) => void;
5
+ title: ReactNode;
6
+ description?: ReactNode;
7
+ /** سمت باز شدن؛ در RTL «start» سمت راست است @default "end" */
8
+ side?: "start" | "end";
9
+ /** پهنا: sm ۲۰، md ۲۶، lg ۳۶ رم؛ full تمام صفحه @default "md" */
10
+ size?: "sm" | "md" | "lg" | "full";
11
+ /** دکمه‌های پایین کشو؛ همیشه دیده می‌شوند و محتوا زیرشان اسکرول می‌خورد */
12
+ footer?: ReactNode;
13
+ /** بستن با کلیک روی پس‌زمینه @default true */
14
+ dismissible?: boolean;
15
+ /** @default "بستن" */
16
+ closeLabel?: string;
17
+ className?: string;
18
+ children?: ReactNode;
19
+ }
20
+ /**
21
+ * کشوی کناری روی <dialog> بومی: فیلترها، جزئیات یک ردیف، تنظیمات یا منوی گوشی.
22
+ * فوکوس داخل کشو می‌ماند، Esc می‌بندد و با انیمیشن خروج بسته می‌شود.
23
+ */
24
+ export declare function Drawer({ open, onOpenChange, title, description, side, size, footer, dismissible, closeLabel, className, children, }: DrawerProps): import("react").JSX.Element;
package/dist/Drawer.js ADDED
@@ -0,0 +1,29 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { useId, useRef } from "react";
4
+ import { cx } from "./cx.js";
5
+ import { CloseIcon } from "./icons.js";
6
+ import { useKashi } from "./KashiProvider.js";
7
+ import { useModalDialog } from "./modal.js";
8
+ /**
9
+ * کشوی کناری روی <dialog> بومی: فیلترها، جزئیات یک ردیف، تنظیمات یا منوی گوشی.
10
+ * فوکوس داخل کشو می‌ماند، Esc می‌بندد و با انیمیشن خروج بسته می‌شود.
11
+ */
12
+ export function Drawer({ open, onOpenChange, title, description, side = "end", size = "md", footer, dismissible = true, closeLabel, className, children, }) {
13
+ const { messages: M } = useKashi();
14
+ closeLabel ?? (closeLabel = M.common.close);
15
+ const ref = useRef(null);
16
+ const id = useId();
17
+ const { restoreFocus } = useModalDialog(ref, open);
18
+ return (_jsxs("dialog", { ref: ref, "data-placement": side, className: cx("k-dialog k-drawer", `k-dialog--${side}`, size !== "md" && `k-drawer--${size}`, className), "aria-labelledby": `${id}-title`, "aria-describedby": description ? `${id}-desc` : undefined, onClose: () => {
19
+ if (open)
20
+ onOpenChange(false);
21
+ restoreFocus();
22
+ }, onCancel: (e) => {
23
+ e.preventDefault();
24
+ onOpenChange(false);
25
+ }, onClick: (e) => {
26
+ if (dismissible && e.target === ref.current)
27
+ onOpenChange(false);
28
+ }, children: [_jsxs("div", { className: "k-dialog__header k-drawer__header", children: [_jsxs("div", { className: "k-dialog__heading", children: [_jsx("h2", { className: "k-dialog__title", id: `${id}-title`, children: title }), description && _jsx("p", { className: "k-dialog__description", id: `${id}-desc`, children: description })] }), _jsx("button", { type: "button", className: "k-btn k-btn--tertiary k-btn--icon k-btn--sm k-dialog__close", "aria-label": closeLabel, onClick: () => onOpenChange(false), children: _jsx(CloseIcon, {}) })] }), _jsx("div", { className: "k-dialog__body k-drawer__body", children: children }), footer && _jsx("div", { className: "k-dialog__footer k-drawer__footer", children: footer })] }));
29
+ }
@@ -0,0 +1,21 @@
1
+ import type { HTMLAttributes, ReactNode } from "react";
2
+ export type EmptyStatePreset = "noData" | "noResults" | "error" | "offline" | "noAccess" | "done";
3
+ export interface EmptyStateProps extends Omit<HTMLAttributes<HTMLDivElement>, "title"> {
4
+ /** عنوان؛ با preset اختیاری است */
5
+ title?: ReactNode;
6
+ description?: ReactNode;
7
+ icon?: ReactNode;
8
+ /** دکمه‌ها */
9
+ actions?: ReactNode;
10
+ /**
11
+ * حالت آماده با آیکون، عنوان و توضیح پیش‌فرض (فارسی و انگلیسی)؛ هر کدام را با title، description یا icon عوض کنید.
12
+ * noData خالی · noResults جستجو بی‌نتیجه · error خطای بارگذاری · offline بدون اینترنت · noAccess بدون دسترسی · done کار تمام شد
13
+ */
14
+ preset?: EmptyStatePreset;
15
+ /** sm داخل جدول و منو، md پیش‌فرض، lg صفحهٔ کامل @default "md" */
16
+ size?: "sm" | "md" | "lg";
17
+ /** قاب خط‌چین؛ مناسب جای خالی داخل صفحه یا محل رها کردن فایل */
18
+ bordered?: boolean;
19
+ }
20
+ /** حالت خالی: وقتی داده‌ای برای نمایش نیست؛ بگویید چرا و قدم بعدی را پیشنهاد کنید */
21
+ export declare function EmptyState({ title, description, icon, actions, preset, size, bordered, className, ...rest }: EmptyStateProps): import("react").JSX.Element;
@@ -0,0 +1,23 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { cx } from "./cx.js";
4
+ import { useKashi } from "./KashiProvider.js";
5
+ const P = { viewBox: "0 0 20 20", fill: "none", stroke: "currentColor", strokeWidth: 1.5, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": true };
6
+ // آیکون‌ها از @kashi-ui/icons، کپی‌شده تا پکیج React به آن وابسته نشود
7
+ const ICONS = {
8
+ noData: _jsxs("svg", { ...P, children: [_jsx("path", { d: "M7.25 2.75h5.5c3.6 0 4.5.9 4.5 4.5v5.5c0 3.6-.9 4.5-4.5 4.5h-5.5c-3.6 0-4.5-.9-4.5-4.5v-5.5c0-3.6.9-4.5 4.5-4.5Z" }), _jsx("path", { d: "M2.75 10.75h3.1c.55 0 1 .3 1.25.75l.5.95c.25.45.7.75 1.25.75h2.3c.55 0 1-.3 1.25-.75l.5-.95c.25-.45.7-.75 1.25-.75h3.1" })] }),
9
+ noResults: _jsxs("svg", { ...P, children: [_jsx("circle", { cx: "9.1", cy: "9.1", r: "6.2" }), _jsx("path", { d: "m14.9 14.9 2.3 2.3M7.2 7.2l3.8 3.8M11 7.2l-3.8 3.8" })] }),
10
+ error: _jsxs("svg", { ...P, children: [_jsx("path", { d: "M8.33 3.9c.74-1.3 2.6-1.3 3.34 0l5.6 9.75c.74 1.3-.2 2.85-1.67 2.85H4.4c-1.48 0-2.41-1.56-1.67-2.85Z" }), _jsx("path", { d: "M10 7.9v3.1M10 13.6v.01" })] }),
11
+ offline: _jsxs("svg", { ...P, children: [_jsx("path", { d: "M2.75 7.6a10.5 10.5 0 0 1 14.5 0M5.2 10.3a7 7 0 0 1 9.6 0M7.7 12.95a3.5 3.5 0 0 1 4.6 0M10 15.75v.01" }), _jsx("path", { d: "m3 3 14 14" })] }),
12
+ noAccess: _jsxs("svg", { ...P, children: [_jsx("path", { d: "M7.25 8.25h5.5c2.6 0 3.25.65 3.25 3.25v2.75c0 2.6-.65 3.25-3.25 3.25h-5.5C4.65 17.5 4 16.85 4 14.25V11.5c0-2.6.65-3.25 3.25-3.25Z" }), _jsx("path", { d: "M6.9 8.3V6.4a3.1 3.1 0 0 1 6.2 0v1.9M10 11.6v2.2" })] }),
13
+ done: _jsxs("svg", { ...P, children: [_jsx("circle", { cx: "10", cy: "10", r: "7.25" }), _jsx("path", { d: "m6.75 10.1 2.2 2.2 4.3-4.5" })] }),
14
+ };
15
+ /** حالت خالی: وقتی داده‌ای برای نمایش نیست؛ بگویید چرا و قدم بعدی را پیشنهاد کنید */
16
+ export function EmptyState({ title, description, icon, actions, preset, size = "md", bordered, className, ...rest }) {
17
+ const { messages: M } = useKashi();
18
+ const text = preset ? M.empty[preset] : undefined;
19
+ title ?? (title = text?.[0]);
20
+ description ?? (description = text?.[1]);
21
+ icon ?? (icon = preset ? ICONS[preset] : undefined);
22
+ return (_jsxs("div", { className: cx("k-empty", size !== "md" && `k-empty--${size}`, bordered && "k-empty--bordered", className), "data-preset": preset, role: preset === "error" || preset === "offline" ? "status" : undefined, ...rest, children: [icon && _jsx("span", { className: "k-empty__icon", "aria-hidden": "true", children: icon }), title && _jsx("p", { className: "k-empty__title", children: title }), description && _jsx("p", { className: "k-empty__description", children: description }), actions && _jsx("div", { className: "k-empty__actions", children: actions })] }));
23
+ }
package/dist/Misc.d.ts CHANGED
@@ -11,12 +11,3 @@ export interface KbdProps extends HTMLAttributes<HTMLElement> {
11
11
  }
12
12
  /** کلید صفحه‌کلید */
13
13
  export declare function Kbd({ keys, children, className, ...rest }: KbdProps): import("react").JSX.Element;
14
- export interface EmptyStateProps extends Omit<HTMLAttributes<HTMLDivElement>, "title"> {
15
- title: ReactNode;
16
- description?: ReactNode;
17
- icon?: ReactNode;
18
- /** دکمه‌ها */
19
- actions?: ReactNode;
20
- }
21
- /** حالت خالی: وقتی داده‌ای برای نمایش نیست */
22
- export declare function EmptyState({ title, description, icon, actions, className, ...rest }: EmptyStateProps): import("react").JSX.Element;
package/dist/Misc.js CHANGED
@@ -1,5 +1,5 @@
1
1
  "use client";
2
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { jsx as _jsx } from "react/jsx-runtime";
3
3
  import { cx } from "./cx.js";
4
4
  export function Divider({ label, vertical, className, ...rest }) {
5
5
  return (_jsx("div", { role: "separator", "aria-orientation": vertical ? "vertical" : undefined, className: cx("k-divider", vertical && "k-divider--vertical", className), ...rest, children: label && _jsx("span", { children: label }) }));
@@ -11,7 +11,3 @@ export function Kbd({ keys, children, className, ...rest }) {
11
11
  }
12
12
  return _jsx("kbd", { className: cx("k-kbd", className), ...rest, children: children });
13
13
  }
14
- /** حالت خالی: وقتی داده‌ای برای نمایش نیست */
15
- export function EmptyState({ title, description, icon, actions, className, ...rest }) {
16
- return (_jsxs("div", { className: cx("k-empty", className), ...rest, children: [icon && _jsx("span", { className: "k-empty__icon", "aria-hidden": "true", children: icon }), _jsx("p", { className: "k-empty__title", children: title }), description && _jsx("p", { className: "k-empty__description", children: description }), actions && _jsx("div", { className: "k-empty__actions", children: actions })] }));
17
- }
@@ -0,0 +1,43 @@
1
+ import { type ElementType, type ReactNode } from "react";
2
+ export interface NavbarLink {
3
+ href: string;
4
+ label: ReactNode;
5
+ /** صفحهٔ فعلی؛ aria-current="page" می‌گیرد */
6
+ current?: boolean;
7
+ icon?: ReactNode;
8
+ /** بج کنار عنوان، مثل «جدید» یا تعداد */
9
+ badge?: ReactNode;
10
+ }
11
+ export interface NavbarProps {
12
+ /** لوگو و نام */
13
+ brand: ReactNode;
14
+ /** @default "/" */
15
+ brandHref?: string;
16
+ links?: NavbarLink[];
17
+ /** دکمه‌ها و آیکون‌های سمت چپ (در RTL)، مثل ورود یا جستجو */
18
+ actions?: ReactNode;
19
+ /** چسبیدن به بالای صفحه؛ با اسکرول سایه و پس‌زمینهٔ مات می‌گیرد @default true */
20
+ sticky?: boolean;
21
+ /** نشان صفحهٔ فعلی: «line» خط زیر پیوند، «pill» قرص رنگی @default "line" */
22
+ variant?: "line" | "pill";
23
+ /** پیوندها وسط نوار، لوگو و دکمه‌ها در دو طرف */
24
+ centered?: boolean;
25
+ /** نوار شناور: جدا از لبه‌ها با گوشهٔ گرد و سایه */
26
+ floating?: boolean;
27
+ /** بی‌رنگ روی تصویر یا هیرو؛ با sticky، پس از اسکرول پس‌زمینه می‌گیرد */
28
+ transparent?: boolean;
29
+ /** زیر این عرض پیوندها به منوی کشو می‌روند: sm ۶۴۰، md ۷۶۸، lg ۱۰۲۴ پیکسل @default "md" */
30
+ collapseBelow?: "sm" | "md" | "lg";
31
+ /** محتوای اضافهٔ پایین منوی گوشی، مثل دکمهٔ ورود */
32
+ menuFooter?: ReactNode;
33
+ /** کامپوننت پیوند، مثل Link در Next.js @default "a" */
34
+ linkAs?: ElementType;
35
+ /** @default "ناوبری اصلی" */
36
+ "aria-label"?: string;
37
+ className?: string;
38
+ }
39
+ /**
40
+ * نوار ناوبری بالای سایت: لوگو، پیوندها با نشانگر لغزان، دکمه‌ها
41
+ * و در گوشی منوی کشو با همان پیوندها. با اسکرول سایه می‌گیرد.
42
+ */
43
+ export declare function Navbar({ brand, brandHref, links, actions, sticky, variant, centered, floating, transparent, collapseBelow, menuFooter, linkAs, "aria-label": ariaLabel, className, }: NavbarProps): import("react").JSX.Element;
package/dist/Navbar.js ADDED
@@ -0,0 +1,53 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { useEffect, useLayoutEffect, useRef, useState } from "react";
4
+ import { cx } from "./cx.js";
5
+ import { Drawer } from "./Drawer.js";
6
+ import { useKashi } from "./KashiProvider.js";
7
+ const useIsoLayout = typeof window === "undefined" ? useEffect : useLayoutEffect;
8
+ /**
9
+ * نوار ناوبری بالای سایت: لوگو، پیوندها با نشانگر لغزان، دکمه‌ها
10
+ * و در گوشی منوی کشو با همان پیوندها. با اسکرول سایه می‌گیرد.
11
+ */
12
+ export function Navbar({ brand, brandHref = "/", links = [], actions, sticky = true, variant = "line", centered, floating, transparent, collapseBelow = "md", menuFooter, linkAs, "aria-label": ariaLabel, className, }) {
13
+ const { messages: M } = useKashi();
14
+ const label = ariaLabel ?? M.navbar.label;
15
+ const A = linkAs ?? "a";
16
+ const [open, setOpen] = useState(false);
17
+ const [scrolled, setScrolled] = useState(false);
18
+ const nav = useRef(null);
19
+ // نشانگر لغزان: روی پیوند زیر نشانگر یا پیوند فعلی
20
+ const place = (el) => {
21
+ const n = nav.current;
22
+ if (!n)
23
+ return;
24
+ if (!el) {
25
+ n.style.setProperty("--_pill-o", "0");
26
+ return;
27
+ }
28
+ n.style.setProperty("--_pill-x", `${el.offsetLeft}px`);
29
+ n.style.setProperty("--_pill-w", `${el.offsetWidth}px`);
30
+ n.style.setProperty("--_pill-o", "1");
31
+ };
32
+ const toCurrent = () => place(nav.current?.querySelector('[aria-current="page"]') ?? null);
33
+ useIsoLayout(() => {
34
+ toCurrent();
35
+ const n = nav.current;
36
+ if (!n || typeof ResizeObserver === "undefined")
37
+ return;
38
+ const ro = new ResizeObserver(toCurrent);
39
+ ro.observe(n);
40
+ return () => ro.disconnect();
41
+ }, [links]);
42
+ useEffect(() => {
43
+ // فقط نوار چسبیده با اسکرول صفحه تغییر می‌کند؛ نوار غیرچسبیده همراه محتوا بالا می‌رود
44
+ if (!sticky)
45
+ return;
46
+ const on = () => setScrolled(window.scrollY > 4);
47
+ on();
48
+ window.addEventListener("scroll", on, { passive: true });
49
+ return () => window.removeEventListener("scroll", on);
50
+ }, [sticky]);
51
+ const item = (l, i, cls, onClick) => (_jsxs(A, { href: l.href, className: cls, "aria-current": l.current ? "page" : undefined, onClick: onClick, children: [l.icon && _jsx("span", { className: "k-navbar__icon", "aria-hidden": "true", children: l.icon }), _jsx("span", { children: l.label }), l.badge && _jsx("span", { className: "k-navbar__badge", children: l.badge })] }, i));
52
+ return (_jsxs("header", { className: cx("k-navbar", sticky && "k-navbar--sticky", variant === "pill" && "k-navbar--pill", centered && "k-navbar--centered", floating && "k-navbar--floating", transparent && "k-navbar--transparent", `k-navbar--collapse-${collapseBelow}`, className), "data-scrolled": scrolled || undefined, children: [_jsxs("div", { className: "k-navbar__inner", children: [_jsx(A, { href: brandHref, className: "k-navbar__brand", children: brand }), links.length > 0 && (_jsxs("nav", { ref: nav, className: "k-navbar__nav", "aria-label": label, onPointerLeave: toCurrent, children: [_jsx("span", { className: "k-navbar__pill", "aria-hidden": "true" }), links.map((l, i) => (_jsxs(A, { href: l.href, className: "k-navbar__link", "aria-current": l.current ? "page" : undefined, onPointerEnter: (e) => place(e.currentTarget), onFocus: (e) => place(e.currentTarget), onBlur: toCurrent, children: [l.icon && _jsx("span", { className: "k-navbar__icon", "aria-hidden": "true", children: l.icon }), _jsx("span", { children: l.label }), l.badge && _jsx("span", { className: "k-navbar__badge", children: l.badge })] }, i)))] })), _jsxs("div", { className: "k-navbar__actions", children: [actions, links.length > 0 && (_jsx("button", { type: "button", className: "k-btn k-btn--tertiary k-btn--icon k-btn--sm k-navbar__menu", "aria-label": M.navbar.menu, "aria-haspopup": "dialog", "aria-expanded": open, onClick: () => setOpen(true), children: _jsx("svg", { viewBox: "0 0 20 20", fill: "none", stroke: "currentColor", strokeWidth: 1.5, strokeLinecap: "round", "aria-hidden": "true", children: _jsx("path", { d: "M3.75 5.5h12.5M3.75 10h12.5M3.75 14.5h12.5" }) }) }))] })] }), links.length > 0 && (_jsx(Drawer, { open: open, onOpenChange: setOpen, side: "start", size: "sm", title: M.navbar.menuTitle, footer: menuFooter, className: "k-navbar__drawer", children: _jsx("nav", { className: "k-navbar__mobile", "aria-label": label, children: links.map((l, i) => item(l, i, "k-navbar__mobile-link", () => setOpen(false))) }) }))] }));
53
+ }
package/dist/index.d.ts CHANGED
@@ -50,8 +50,18 @@ export { Progress, Spinner } from "./Progress.js";
50
50
  export type { ProgressProps, SpinnerProps } from "./Progress.js";
51
51
  export { Skeleton } from "./Skeleton.js";
52
52
  export type { SkeletonProps } from "./Skeleton.js";
53
- export { Divider, Kbd, EmptyState } from "./Misc.js";
54
- export type { DividerProps, KbdProps, EmptyStateProps } from "./Misc.js";
53
+ export { Divider, Kbd } from "./Misc.js";
54
+ export type { DividerProps, KbdProps } from "./Misc.js";
55
+ export { EmptyState } from "./EmptyState.js";
56
+ export type { EmptyStateProps, EmptyStatePreset } from "./EmptyState.js";
57
+ export { Drawer } from "./Drawer.js";
58
+ export type { DrawerProps } from "./Drawer.js";
59
+ export { BottomSheet } from "./BottomSheet.js";
60
+ export type { BottomSheetProps } from "./BottomSheet.js";
61
+ export { Navbar } from "./Navbar.js";
62
+ export type { NavbarProps, NavbarLink } from "./Navbar.js";
63
+ export { useForm, rules } from "./useForm.js";
64
+ export type { UseFormOptions, UseFormReturn, FormRule, FieldBinding } from "./useForm.js";
55
65
  export { DropdownMenu, MenuItem, MenuSeparator, MenuLabel } from "./DropdownMenu.js";
56
66
  export type { DropdownMenuProps, MenuItemProps } from "./DropdownMenu.js";
57
67
  export { DataTable } from "./DataTable.js";
package/dist/index.js CHANGED
@@ -25,7 +25,12 @@ export { Breadcrumb } from "./Breadcrumb.js";
25
25
  export { Pagination, pageRange } from "./Pagination.js";
26
26
  export { Progress, Spinner } from "./Progress.js";
27
27
  export { Skeleton } from "./Skeleton.js";
28
- export { Divider, Kbd, EmptyState } from "./Misc.js";
28
+ export { Divider, Kbd } from "./Misc.js";
29
+ export { EmptyState } from "./EmptyState.js";
30
+ export { Drawer } from "./Drawer.js";
31
+ export { BottomSheet } from "./BottomSheet.js";
32
+ export { Navbar } from "./Navbar.js";
33
+ export { useForm, rules } from "./useForm.js";
29
34
  export { DropdownMenu, MenuItem, MenuSeparator, MenuLabel } from "./DropdownMenu.js";
30
35
  export { DataTable } from "./DataTable.js";
31
36
  export { OtpInput } from "./OtpInput.js";
@@ -0,0 +1,9 @@
1
+ import { type RefObject } from "react";
2
+ /**
3
+ * باز و بسته کردن <dialog> بومی با showModal و انیمیشن خروج:
4
+ * هنگام بستن data-closing می‌گیرد، پایان انیمیشن را صبر می‌کند و بعد close() می‌شود؛
5
+ * فوکوس به عنصری که پنجره را باز کرده برمی‌گردد. با «کاهش حرکت» فوراً بسته می‌شود.
6
+ */
7
+ export declare function useModalDialog(ref: RefObject<HTMLDialogElement | null>, open: boolean): {
8
+ restoreFocus: () => void | undefined;
9
+ };
package/dist/modal.js ADDED
@@ -0,0 +1,54 @@
1
+ "use client";
2
+ import { useEffect, useRef } from "react";
3
+ const reduced = () => typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
4
+ /**
5
+ * باز و بسته کردن <dialog> بومی با showModal و انیمیشن خروج:
6
+ * هنگام بستن data-closing می‌گیرد، پایان انیمیشن را صبر می‌کند و بعد close() می‌شود؛
7
+ * فوکوس به عنصری که پنجره را باز کرده برمی‌گردد. با «کاهش حرکت» فوراً بسته می‌شود.
8
+ */
9
+ export function useModalDialog(ref, open) {
10
+ const opener = useRef(null);
11
+ useEffect(() => {
12
+ const d = ref.current;
13
+ if (!d)
14
+ return;
15
+ if (open) {
16
+ if (d.open && !d.hasAttribute("data-closing"))
17
+ return;
18
+ d.removeAttribute("data-closing");
19
+ if (!d.open) {
20
+ opener.current = document.activeElement;
21
+ d.showModal();
22
+ }
23
+ return;
24
+ }
25
+ if (!d.open)
26
+ return;
27
+ // اول بسته شود، بعد نشانهٔ بستن برداشته شود؛ برعکسش یک فریم انیمیشن ورود را دوباره اجرا می‌کرد (پرش هنگام بستن)
28
+ const finish = () => {
29
+ if (d.open)
30
+ d.close();
31
+ d.removeAttribute("data-closing");
32
+ };
33
+ if (reduced())
34
+ return finish();
35
+ d.setAttribute("data-closing", "");
36
+ // پشتیبان: اگر انیمیشنی اجرا نشد (مثلاً در مرورگر قدیمی) باز هم بسته شود
37
+ const t = setTimeout(finish, 320);
38
+ const end = (e) => {
39
+ // رویداد ::backdrop (کوتاه‌تر) و انیمیشن فرزندها را نادیده بگیر؛ فقط پایان حرکت خود پنجره
40
+ if (e.target !== d || e.pseudoElement)
41
+ return;
42
+ clearTimeout(t);
43
+ finish();
44
+ };
45
+ d.addEventListener("animationend", end, { once: true });
46
+ return () => {
47
+ clearTimeout(t);
48
+ d.removeEventListener("animationend", end);
49
+ };
50
+ }, [open, ref]);
51
+ /** پس از بسته شدن واقعی فراخوانده شود */
52
+ const restoreFocus = () => opener.current?.focus?.();
53
+ return { restoreFocus };
54
+ }
@@ -0,0 +1,90 @@
1
+ import { type FormEvent } from "react";
2
+ import type { KashiMessages } from "@kashi-ui/persian";
3
+ type Values = Record<string, unknown>;
4
+ /** پیام خطا: متن آماده یا کلیدی که با زبان KashiProvider ترجمه می‌شود */
5
+ type Message = string | ((M: KashiMessages, n: (v: number | string) => string) => string);
6
+ /** هر قاعده مقدار را می‌گیرد و اگر درست نبود پیام خطا برمی‌گرداند */
7
+ export type FormRule<V extends Values = Values> = (value: unknown, values: V) => Message | null | undefined | false;
8
+ /**
9
+ * قاعده‌های آماده با پیام فارسی و انگلیسی. پیام دلخواه را به‌عنوان آخرین آرگومان بدهید.
10
+ * همهٔ قاعده‌ها جز required مقدار خالی را رد نمی‌کنند و ارقام فارسی را می‌پذیرند.
11
+ */
12
+ export declare const rules: {
13
+ required: (message?: string) => FormRule;
14
+ minLength: (n: number, message?: string) => FormRule<Values>;
15
+ maxLength: (n: number, message?: string) => FormRule<Values>;
16
+ min: (n: number, message?: string) => FormRule<Values>;
17
+ max: (n: number, message?: string) => FormRule<Values>;
18
+ pattern: (re: RegExp, message?: string) => FormRule<Values>;
19
+ email: (message?: string) => FormRule<Values>;
20
+ nationalId: (message?: string) => FormRule<Values>;
21
+ legalId: (message?: string) => FormRule<Values>;
22
+ mobile: (message?: string) => FormRule<Values>;
23
+ landline: (message?: string) => FormRule<Values>;
24
+ card: (message?: string) => FormRule<Values>;
25
+ iban: (message?: string) => FormRule<Values>;
26
+ postalCode: (message?: string) => FormRule<Values>;
27
+ /** برابر بودن با فیلد دیگر، مثل تکرار رمز */
28
+ match: (field: string, message?: string) => FormRule<Values>;
29
+ /** قاعدهٔ دلخواه: true یعنی درست */
30
+ custom: <V extends Values = Values>(ok: (value: unknown, values: V) => boolean, message: string) => FormRule<V>;
31
+ };
32
+ export interface UseFormOptions<V extends Values> {
33
+ defaultValues: V;
34
+ /** قاعده‌های هر فیلد به ترتیب؛ اولین خطا نمایش داده می‌شود */
35
+ rules?: {
36
+ [K in keyof V]?: FormRule<V>[];
37
+ };
38
+ /**
39
+ * زمان بررسی: «blur» پس از خروج از فیلد (پیش‌فرض)، «change» با هر تغییر، «submit» فقط هنگام ارسال.
40
+ * پس از اولین ارسال، فیلدهای دارای خطا با هر تغییر دوباره بررسی می‌شوند تا خطا همان لحظه برود.
41
+ */
42
+ validateOn?: "blur" | "change" | "submit";
43
+ }
44
+ /** آنچه روی هر فیلد پخش می‌شود: <Input {...form.field("name")} /> */
45
+ export interface FieldBinding {
46
+ id: string;
47
+ name: string;
48
+ error?: string;
49
+ "aria-invalid"?: true;
50
+ required?: boolean;
51
+ ref: (el: HTMLElement | null) => void;
52
+ onBlur: () => void;
53
+ value?: string;
54
+ checked?: boolean;
55
+ /** چک‌باکس و سوییچ: حالت خطا؛ متن خطا در description نمایش داده می‌شود */
56
+ invalid?: boolean;
57
+ description?: string;
58
+ onChange?: (eventOrValue: unknown) => void;
59
+ onValueChange?: (value: unknown) => void;
60
+ }
61
+ export interface UseFormReturn<V extends Values> {
62
+ values: V;
63
+ errors: Partial<Record<keyof V, string>>;
64
+ touched: Partial<Record<keyof V, boolean>>;
65
+ /**
66
+ * اتصال یک فیلد. type: «value» برای فیلدهای فارسی و هر کامپوننتی که onValueChange دارد (کد ملی، موبایل، شبا…)،
67
+ * «checkbox» برای چک‌باکس و سوییچ، پیش‌فرض برای Input، Textarea و input بومی.
68
+ */
69
+ field: (name: keyof V & string, options?: {
70
+ type?: "text" | "value" | "checkbox";
71
+ }) => FieldBinding;
72
+ setValue: <K extends keyof V>(name: K, value: V[K]) => void;
73
+ setError: (name: keyof V, message: string | undefined) => void;
74
+ /** همهٔ فیلدها را بررسی می‌کند؛ true یعنی بدون خطا */
75
+ validate: () => boolean;
76
+ /** onSubmit فرم: بررسی، تمرکز روی اولین فیلد نادرست و در صورت درستی اجرای fn */
77
+ handleSubmit: (fn: (values: V) => void | Promise<void>) => (e?: FormEvent) => Promise<void>;
78
+ reset: (values?: V) => void;
79
+ isSubmitting: boolean;
80
+ isDirty: boolean;
81
+ submitCount: number;
82
+ /** پیام خلاصه برای بالای فرم، مثل «۲ مورد را اصلاح کنید.»؛ بدون خطا undefined */
83
+ summary?: string;
84
+ }
85
+ /**
86
+ * مدیریت مقدار و اعتبارسنجی فرم با پیام‌های فارسی (و انگلیسی با KashiProvider).
87
+ * بدون وابستگی؛ خطاها مستقیم به ویژگی error کامپوننت‌های کاشی می‌رسند.
88
+ */
89
+ export declare function useForm<V extends Values>({ defaultValues, rules: fieldRules, validateOn }: UseFormOptions<V>): UseFormReturn<V>;
90
+ export {};
@@ -0,0 +1,150 @@
1
+ "use client";
2
+ import { useCallback, useId, useMemo, useRef, useState } from "react";
3
+ import { isValidCardNumber, isValidIban, isValidLandline, isValidLegalId, isValidMobile, isValidNationalId, isValidPostalCode, toEnDigits, } from "@kashi-ui/persian";
4
+ import { useKashi } from "./KashiProvider.js";
5
+ const isEmpty = (v) => v === undefined || v === null || v === "" || v === false || (Array.isArray(v) && v.length === 0);
6
+ const str = (v) => toEnDigits(String(v ?? "")).trim();
7
+ /** قاعده‌ای که مقدار خالی را رد نمی‌کند؛ خالی بودن کار required است */
8
+ const check = (ok, msg) => (v, values) => (isEmpty(v) || ok(v, values) ? null : msg);
9
+ const len = (v) => [...String(v ?? "")].length;
10
+ /**
11
+ * قاعده‌های آماده با پیام فارسی و انگلیسی. پیام دلخواه را به‌عنوان آخرین آرگومان بدهید.
12
+ * همهٔ قاعده‌ها جز required مقدار خالی را رد نمی‌کنند و ارقام فارسی را می‌پذیرند.
13
+ */
14
+ export const rules = {
15
+ required: (message) => Object.assign((v) => (isEmpty(typeof v === "string" ? v.trim() : v) ? message ?? ((M) => M.form.required) : null), { isRequired: true }),
16
+ minLength: (n, message) => check((v) => len(v) >= n, message ?? ((M, f) => M.form.minLength(f(n)))),
17
+ maxLength: (n, message) => check((v) => len(v) <= n, message ?? ((M, f) => M.form.maxLength(f(n)))),
18
+ min: (n, message) => check((v) => Number(str(v)) >= n, message ?? ((M, f) => M.form.min(f(n)))),
19
+ max: (n, message) => check((v) => Number(str(v)) <= n, message ?? ((M, f) => M.form.max(f(n)))),
20
+ pattern: (re, message) => check((v) => re.test(String(v)), message ?? ((M) => M.form.pattern)),
21
+ email: (message) => check((v) => /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(str(v)), message ?? ((M) => M.form.email)),
22
+ nationalId: (message) => check((v) => isValidNationalId(str(v)), message ?? ((M) => M.invalid.nationalId)),
23
+ legalId: (message) => check((v) => isValidLegalId(str(v)), message ?? ((M) => M.invalid.legalId)),
24
+ mobile: (message) => check((v) => isValidMobile(str(v)), message ?? ((M) => M.invalid.mobile)),
25
+ landline: (message) => check((v) => isValidLandline(str(v)), message ?? ((M) => M.invalid.landline)),
26
+ card: (message) => check((v) => isValidCardNumber(str(v)), message ?? ((M) => M.invalid.card)),
27
+ iban: (message) => check((v) => isValidIban(str(v)), message ?? ((M) => M.invalid.iban)),
28
+ postalCode: (message) => check((v) => isValidPostalCode(str(v)), message ?? ((M) => M.invalid.postal)),
29
+ /** برابر بودن با فیلد دیگر، مثل تکرار رمز */
30
+ match: (field, message) => check((v, values) => v === values[field], message ?? ((M) => M.form.match)),
31
+ /** قاعدهٔ دلخواه: true یعنی درست */
32
+ custom: (ok, message) => check(ok, message),
33
+ };
34
+ /**
35
+ * مدیریت مقدار و اعتبارسنجی فرم با پیام‌های فارسی (و انگلیسی با KashiProvider).
36
+ * بدون وابستگی؛ خطاها مستقیم به ویژگی error کامپوننت‌های کاشی می‌رسند.
37
+ */
38
+ export function useForm({ defaultValues, rules: fieldRules = {}, validateOn = "blur" }) {
39
+ const { messages: M, n } = useKashi();
40
+ const uid = useId();
41
+ const [values, setValues] = useState(defaultValues);
42
+ const [errors, setErrors] = useState({});
43
+ const [touched, setTouched] = useState({});
44
+ const [isSubmitting, setSubmitting] = useState(false);
45
+ const [submitCount, setSubmitCount] = useState(0);
46
+ const initial = useRef(defaultValues);
47
+ const els = useRef({});
48
+ const latest = useRef(values);
49
+ latest.current = values;
50
+ const fmt = useCallback((v) => (typeof v === "number" ? n(v) : v), [n]);
51
+ const run = useCallback((name, all) => {
52
+ for (const rule of (fieldRules[name] ?? [])) {
53
+ const m = rule(all[name], all);
54
+ if (m)
55
+ return typeof m === "function" ? m(M, fmt) : m;
56
+ }
57
+ return undefined;
58
+ }, [fieldRules, M, fmt]);
59
+ const validateOne = (name, all) => {
60
+ const e = run(name, all);
61
+ setErrors((prev) => (prev[name] === e ? prev : { ...prev, [name]: e }));
62
+ return e;
63
+ };
64
+ const setValue = (name, value) => {
65
+ const next = { ...latest.current, [name]: value };
66
+ latest.current = next;
67
+ setValues(next);
68
+ if (validateOn === "change" || errors[name] !== undefined || (submitCount > 0 && validateOn !== "submit"))
69
+ validateOne(name, next);
70
+ };
71
+ const validate = () => {
72
+ const all = latest.current;
73
+ const next = {};
74
+ for (const k of Object.keys(fieldRules)) {
75
+ const e = run(k, all);
76
+ if (e)
77
+ next[k] = e;
78
+ }
79
+ setErrors(next);
80
+ return Object.keys(next).length === 0;
81
+ };
82
+ const handleSubmit = (fn) => async (e) => {
83
+ e?.preventDefault();
84
+ setSubmitCount((c) => c + 1);
85
+ setTouched(Object.fromEntries(Object.keys(fieldRules).map((k) => [k, true])));
86
+ const all = latest.current;
87
+ const bad = Object.keys(fieldRules).find((k) => run(k, all));
88
+ if (!validate()) {
89
+ if (bad)
90
+ els.current[bad]?.focus?.();
91
+ return;
92
+ }
93
+ setSubmitting(true);
94
+ try {
95
+ await fn(all);
96
+ }
97
+ finally {
98
+ setSubmitting(false);
99
+ }
100
+ };
101
+ const field = (name, { type = "text" } = {}) => {
102
+ const error = errors[name];
103
+ const required = (fieldRules[name] ?? []).some((r) => r.isRequired);
104
+ const read = (x) => {
105
+ if (x && typeof x === "object" && "target" in x) {
106
+ const t = x.target;
107
+ return type === "checkbox" ? t.checked : t.value;
108
+ }
109
+ return x;
110
+ };
111
+ const base = {
112
+ id: `${uid}-${name}`,
113
+ name,
114
+ error,
115
+ "aria-invalid": error ? true : undefined,
116
+ required: required || undefined,
117
+ ref: (el) => { els.current[name] = el; },
118
+ onBlur: () => {
119
+ setTouched((t) => (t[name] ? t : { ...t, [name]: true }));
120
+ if (validateOn !== "submit")
121
+ validateOne(name, latest.current);
122
+ },
123
+ };
124
+ if (type === "checkbox") {
125
+ // Checkbox و Switch ویژگی error ندارند: invalid و متن خطا در description
126
+ const { error: err, ...rest } = base;
127
+ return { ...rest, checked: !!values[name], onChange: (x) => setValue(name, read(x)), ...(err ? { invalid: true, description: err } : {}) };
128
+ }
129
+ if (type === "value")
130
+ return { ...base, value: (values[name] ?? ""), onValueChange: (x) => setValue(name, x) };
131
+ return { ...base, value: (values[name] ?? ""), onChange: (x) => setValue(name, read(x)) };
132
+ };
133
+ const errorCount = Object.values(errors).filter(Boolean).length;
134
+ const isDirty = useMemo(() => Object.keys(values).some((k) => values[k] !== initial.current[k]), [values]);
135
+ return {
136
+ values, errors, touched, field, setValue,
137
+ setError: (name, message) => setErrors((prev) => ({ ...prev, [name]: message })),
138
+ validate, handleSubmit,
139
+ reset: (v = initial.current) => {
140
+ initial.current = v;
141
+ latest.current = v;
142
+ setValues(v);
143
+ setErrors({});
144
+ setTouched({});
145
+ setSubmitCount(0);
146
+ },
147
+ isSubmitting, isDirty, submitCount,
148
+ summary: errorCount > 0 && submitCount > 0 ? M.form.summary(n(errorCount)) : undefined,
149
+ };
150
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kashi-ui/react",
3
- "version": "2.7.0",
3
+ "version": "2.8.1",
4
4
  "description": "کامپوننت‌های React دیزاین‌سیستم کاشی",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -22,7 +22,7 @@
22
22
  "test": "node --test test/*.test.mjs"
23
23
  },
24
24
  "peerDependencies": {
25
- "@kashi-ui/css": "^2.7.0",
25
+ "@kashi-ui/css": "^2.8.1",
26
26
  "react": ">=18"
27
27
  },
28
28
  "devDependencies": {
@@ -59,7 +59,7 @@
59
59
  }
60
60
  },
61
61
  "dependencies": {
62
- "@kashi-ui/bank-logos": "^2.7.0",
63
- "@kashi-ui/persian": "^2.7.0"
62
+ "@kashi-ui/bank-logos": "^2.8.1",
63
+ "@kashi-ui/persian": "^2.8.1"
64
64
  }
65
65
  }