@kashi-ui/react 0.10.0 → 0.12.0

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.
package/README.md CHANGED
@@ -20,8 +20,8 @@ export function SignUp() {
20
20
  }
21
21
  ```
22
22
 
23
- کامپوننت‌ها: Button · Input · Textarea · Select · Checkbox · RadioGroup · Switch · Badge · Card · Alert · Avatar · AvatarGroup · Tabs · Dialog · Toast · Tooltip · DropdownMenu · DataTable · Pagination · Breadcrumb · Accordion · Stepper · Progress · Spinner · Skeleton · EmptyState · Divider · Kbd · RelativeTime · Combobox · CommandPalette · TagInput · FileUpload · Slider · NumberInput · Popover · StatCard · Timeline · SideNav · SegmentedControl · CopyButton · Banner · Rating
23
+ کامپوننت‌ها: Button · Input · Textarea · Select · Checkbox · RadioGroup · Switch · Badge · Card · Alert · Avatar · AvatarGroup · Tabs · Dialog · Toast · Tooltip · DropdownMenu · DataTable · Pagination · Breadcrumb · Accordion · Stepper · Progress · Spinner · Skeleton · EmptyState · Divider · Kbd · RelativeTime · Combobox · CommandPalette · TagInput · FileUpload · Slider · NumberInput · Popover · StatCard · Timeline · SideNav · SegmentedControl · CopyButton · Banner · Rating · TreeView · ButtonGroup · ChipGroup · PasswordStrength · BarChart · LineChart · ContextMenu · InlineEdit
24
24
 
25
- فارسی: DatePicker و Calendar شمسی · DateRangePicker · TimeInput · PostalCodeInput · PlateInput · NationalIdInput · CardNumberInput · IbanInput · MobileInput · PriceInput · OtpInput
25
+ فارسی: DatePicker و Calendar شمسی · DateRangePicker · TimeInput · PostalCodeInput · PlateInput · LandlineInput · MonthPicker · Countdown · ActivityHeatmap · ProvinceSelect · NationalIdInput · CardNumberInput · IbanInput · MobileInput · PriceInput · OtpInput
26
26
 
27
27
  نیازمند React ۱۸ یا بالاتر. مستندات کامل: [kashi.sepantapouya.com](https://kashi.sepantapouya.com) · کد: [GitHub](https://github.com/Sepantapouya/Kashi) · لایسنس MIT
@@ -0,0 +1,13 @@
1
+ export interface ActivityHeatmapProps {
2
+ /** تعداد فعالیت در هر روز؛ کلید تاریخ میلادی YYYY-MM-DD */
3
+ data: Record<string, number>;
4
+ /** سال شمسی @default سال جاری */
5
+ year?: number;
6
+ /** نام دسترس‌پذیر، مثل «فعالیت تیم در سال ۱۴۰۵» */
7
+ label?: string;
8
+ /** واحد در راهنما @default «فعالیت» */
9
+ unit?: string;
10
+ className?: string;
11
+ }
12
+ /** نقشهٔ فعالیت سالانه با ماه‌های شمسی؛ هفته از شنبه شروع می‌شود */
13
+ export declare function ActivityHeatmap({ data, year, label, unit, className }: ActivityHeatmapProps): import("react").JSX.Element;
@@ -0,0 +1,34 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { JALALI_MONTHS, formatJalali, formatNumber, jalaliMonthLength, toGregorian, toISODate, toJalali } from "@kashi-ui/persian";
3
+ import { useRef, useState } from "react";
4
+ import { cx } from "./cx.js";
5
+ import { ChartTip } from "./Chart.js";
6
+ const WEEK = ["ش", "", "د", "", "چ", "", "ج"];
7
+ /** نقشهٔ فعالیت سالانه با ماه‌های شمسی؛ هفته از شنبه شروع می‌شود */
8
+ export function ActivityHeatmap({ data, year = toJalali(new Date()).jy, label, unit = "فعالیت", className }) {
9
+ const days = [];
10
+ for (let m = 1; m <= 12; m++)
11
+ for (let d = 1; d <= jalaliMonthLength(year, m); d++) {
12
+ const date = toGregorian(year, m, d);
13
+ days.push({ date, value: data[toISODate(date)] ?? 0 });
14
+ }
15
+ const max = Math.max(0, ...days.map((d) => d.value));
16
+ const level = (v) => (v <= 0 || max === 0 ? 0 : Math.max(1, Math.ceil((v / max) * 4)));
17
+ // شنبه سطر اول
18
+ const row = (d) => (d.getDay() + 1) % 7;
19
+ const offset = row(days[0].date);
20
+ const col = (i) => Math.floor((i + offset) / 7);
21
+ const monthStarts = JALALI_MONTHS.map((name, m) => ({ name, col: col(days.findIndex((d) => toJalali(d.date).jm === m + 1)) }));
22
+ const total = days.reduce((s, d) => s + d.value, 0);
23
+ const monthly = JALALI_MONTHS.map((name, m) => ({ name, sum: days.filter((d) => toJalali(d.date).jm === m + 1).reduce((s, d) => s + d.value, 0) }));
24
+ const box = useRef(null);
25
+ const [tip, setTip] = useState(null);
26
+ const name = label ?? `${unit} در سال ${formatNumber(year, { digits: "fa" }).replace(/٬/g, "")}`;
27
+ return (_jsxs("figure", { ref: box, className: cx("k-heatmap", className), style: { margin: 0 }, onPointerLeave: () => setTip(null), children: [_jsx("div", { className: "k-heatmap__scroll", children: _jsxs("div", { role: "img", "aria-label": `${name}: ${formatNumber(total)} ${unit}`, children: [_jsx("div", { className: "k-heatmap__months", "aria-hidden": "true", children: monthStarts.map((m) => _jsx("span", { style: { gridColumn: m.col + 1 }, children: m.name }, m.name)) }), _jsxs("div", { className: "k-heatmap__body", "aria-hidden": "true", children: [_jsx("div", { className: "k-heatmap__days", children: WEEK.map((w, i) => _jsx("span", { children: w }, i)) }), _jsxs("div", { className: "k-heatmap__grid", onPointerOver: (e) => {
28
+ const cell = e.target.closest("[data-i]");
29
+ if (!cell || !box.current)
30
+ return setTip(null);
31
+ const b = box.current.getBoundingClientRect(), r = cell.getBoundingClientRect();
32
+ setTip({ x: r.left + r.width / 2 - b.left, y: r.top - b.top - 2, i: Number(cell.dataset.i) });
33
+ }, children: [Array.from({ length: offset }, (_, i) => _jsx("span", { className: "k-heatmap__cell", "data-empty": "" }, `e${i}`)), days.map((d, i) => (_jsx("span", { className: "k-heatmap__cell", "data-l": level(d.value), "data-i": i, "data-active": tip?.i === i ? "" : undefined }, d.date.getTime())))] })] })] }) }), tip && _jsx(ChartTip, { x: tip.x, y: tip.y, width: box.current?.clientWidth, title: formatJalali(days[tip.i].date, { style: "full" }), rows: [{ value: `${formatNumber(days[tip.i].value)} ${unit}` }] }), _jsxs("figcaption", { className: "k-heatmap__foot", children: [_jsxs("span", { children: [formatNumber(total), " ", unit, " \u062F\u0631 ", formatNumber(year).replace(/٬/g, "")] }), _jsxs("span", { className: "k-heatmap__scale", "aria-hidden": "true", children: ["\u06A9\u0645\u062A\u0631 ", [0, 1, 2, 3, 4].map((l) => _jsx("span", { className: "k-heatmap__cell", "data-l": l }, l)), " \u0628\u06CC\u0634\u062A\u0631"] })] }), _jsxs("table", { className: "k-sr-only", children: [_jsxs("caption", { children: [name, "\u060C \u0628\u0647 \u062A\u0641\u06A9\u06CC\u06A9 \u0645\u0627\u0647"] }), _jsx("tbody", { children: monthly.map((m) => _jsxs("tr", { children: [_jsx("th", { scope: "row", children: m.name }), _jsx("td", { children: formatNumber(m.sum) })] }, m.name)) })] })] }));
34
+ }
@@ -0,0 +1,7 @@
1
+ import type { HTMLAttributes } from "react";
2
+ export interface ButtonGroupProps extends HTMLAttributes<HTMLDivElement> {
3
+ /** نام گروه برای صفحه‌خوان */
4
+ "aria-label"?: string;
5
+ }
6
+ /** دکمه‌های چسبیده به هم، مثل «قبلی / امروز / بعدی» یا ابزار قالب‌بندی */
7
+ export declare function ButtonGroup({ className, ...rest }: ButtonGroupProps): import("react").JSX.Element;
@@ -0,0 +1,6 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { cx } from "./cx.js";
3
+ /** دکمه‌های چسبیده به هم، مثل «قبلی / امروز / بعدی» یا ابزار قالب‌بندی */
4
+ export function ButtonGroup({ className, ...rest }) {
5
+ return _jsx("div", { role: "group", className: cx("k-btn-group", className), ...rest });
6
+ }
@@ -0,0 +1,115 @@
1
+ import { type ReactNode } from "react";
2
+ export interface TipRow {
3
+ name?: string;
4
+ value: string;
5
+ color?: string;
6
+ }
7
+ /** راهنمای شناور مشترک نمودارها؛ x و y نسبت به ظرف نمودار */
8
+ export declare function ChartTip({ x, y, title, rows, width }: {
9
+ x: number;
10
+ y: number;
11
+ title?: ReactNode;
12
+ rows: TipRow[];
13
+ width?: number;
14
+ }): import("react").JSX.Element;
15
+ export interface BarChartProps {
16
+ /** عنوان نمودار؛ نام دسترس‌پذیر هم هست */
17
+ title: string;
18
+ /** یک سری */
19
+ data?: {
20
+ label: string;
21
+ value: number;
22
+ }[];
23
+ /** یا چند سری روی هم (ستون انباشته)، حداکثر چهار؛ با labels */
24
+ series?: LineSeries[];
25
+ labels?: string[];
26
+ /** قالب مقدار در راهنما و برچسب @default ارقام فارسی با جداکننده */
27
+ format?: (n: number) => string;
28
+ /** برچسب مقدار روی بلندترین ستون @default true */
29
+ labelMax?: boolean;
30
+ height?: string;
31
+ className?: string;
32
+ }
33
+ /** نمودار ستونی؛ تک‌سری یا انباشته تا چهار سری. با موس یا Tab روی هر ستون مقدار دقیق نمایش داده می‌شود */
34
+ export declare function BarChart({ title, data, series, labels, format, labelMax, height, className }: BarChartProps): import("react").JSX.Element;
35
+ export interface BarListProps {
36
+ title: string;
37
+ /** به ترتیب داده‌شده؛ معمولاً از بیشترین به کمترین */
38
+ data: {
39
+ label: string;
40
+ value: number;
41
+ href?: string;
42
+ }[];
43
+ format?: (n: number) => string;
44
+ className?: string;
45
+ }
46
+ /** میله‌های افقی برای رتبه‌بندی با نام‌های بلند، مثل پربازدیدترین صفحه‌ها */
47
+ export declare function BarList({ title, data, format, className }: BarListProps): import("react").JSX.Element;
48
+ export interface ProportionBarProps {
49
+ title: string;
50
+ /** حداکثر چهار بخش؛ بیشتر را در «سایر» جمع کنید */
51
+ data: {
52
+ label: string;
53
+ value: number;
54
+ }[];
55
+ /** نمایش درصد کنار هر بخش در راهنما @default true */
56
+ percent?: boolean;
57
+ format?: (n: number) => string;
58
+ className?: string;
59
+ }
60
+ /** سهم هر بخش از کل در یک میلهٔ افقی، مثل منبع ورود کاربران؛ جایگزین خواناتر نمودار دایره‌ای */
61
+ export declare function ProportionBar({ title, data, percent, format, className }: ProportionBarProps): import("react").JSX.Element;
62
+ export interface PieChartProps {
63
+ title: string;
64
+ /** بیش از پنج بخش در «سایر» جمع می‌شود */
65
+ data: {
66
+ label: string;
67
+ value: number;
68
+ }[];
69
+ /** «donut» با جمع کل در وسط @default "donut" */
70
+ variant?: "donut" | "pie";
71
+ format?: (n: number) => string;
72
+ /** برچسب وسط دونات @default «جمع» */
73
+ totalLabel?: string;
74
+ /** اندازهٔ نمودار به پیکسل @default 176 */
75
+ size?: number;
76
+ className?: string;
77
+ }
78
+ /**
79
+ * نمودار دایره‌ای یا دونات تا پنج بخش، با فاصلهٔ کوچک بین بخش‌ها، راهنمای درصد و جدول هم‌ارز.
80
+ * برای مقایسهٔ دقیق بخش‌ها ProportionBar خواناتر است.
81
+ */
82
+ export declare function PieChart({ title, data, variant, format, totalLabel, size, className }: PieChartProps): import("react").JSX.Element;
83
+ export interface SparklineProps {
84
+ values: number[];
85
+ /** نام دسترس‌پذیر، مثل «روند فروش هفت روز اخیر: افزایشی» */
86
+ "aria-label"?: string;
87
+ /** رنگ خط @default برند */
88
+ tone?: "brand" | "success" | "error" | "neutral";
89
+ /** سطح کم‌رنگ زیر خط @default true */
90
+ area?: boolean;
91
+ className?: string;
92
+ }
93
+ /** خط روند کوچک برای کارت آمار و جدول؛ بدون محور، فقط شکل روند */
94
+ export declare function Sparkline({ values, "aria-label": ariaLabel, tone, area, className }: SparklineProps): import("react").JSX.Element;
95
+ export interface LineSeries {
96
+ name: string;
97
+ values: number[];
98
+ }
99
+ export interface LineChartProps {
100
+ title: string;
101
+ /** برچسب محور افقی، مثل ماه‌ها */
102
+ labels: string[];
103
+ /** حداکثر چهار سری؛ رنگ‌ها به ترتیب ثابت */
104
+ series: LineSeries[];
105
+ format?: (n: number) => string;
106
+ /** سطح کم‌رنگ زیر خط (فقط برای یک سری) */
107
+ area?: boolean;
108
+ height?: string;
109
+ className?: string;
110
+ }
111
+ /**
112
+ * نمودار خطی تا چهار سری: خط ۲ پیکسلی، برچسب نام در انتهای هر خط،
113
+ * راهنمای عمودی با موس و ←→ روی کیبورد، و جدول هم‌ارز برای صفحه‌خوان.
114
+ */
115
+ export declare function LineChart({ title, labels, series, format, area, height, className }: LineChartProps): import("react").JSX.Element;
package/dist/Chart.js ADDED
@@ -0,0 +1,197 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useId, useLayoutEffect, useRef, useState } from "react";
3
+ import { formatNumber } from "@kashi-ui/persian";
4
+ import { cx } from "./cx.js";
5
+ const fmtDefault = (n) => formatNumber(Math.round(n));
6
+ /** عدد کوتاه برای محور: ۱٬۲۰۰٬۰۰۰ ← ۱٫۲ م */
7
+ const compact = (n) => {
8
+ const a = Math.abs(n);
9
+ const fa = (x, u) => `${formatNumber(Math.round(x * 10) / 10).replace(".", "٫")}${u}`;
10
+ if (a >= 1e9)
11
+ return fa(n / 1e9, " میلیارد");
12
+ if (a >= 1e6)
13
+ return fa(n / 1e6, " م");
14
+ if (a >= 1e3)
15
+ return fa(n / 1e3, " هزار");
16
+ return formatNumber(n);
17
+ };
18
+ /** گام‌های گرد محور: ۰، ۲۵، ۵۰… */
19
+ function niceTicks(max, count = 4) {
20
+ if (max <= 0)
21
+ return [0];
22
+ const raw = max / count;
23
+ const mag = 10 ** Math.floor(Math.log10(raw));
24
+ const step = [1, 2, 2.5, 5, 10].map((m) => m * mag).find((s) => s >= raw);
25
+ return Array.from({ length: Math.ceil(max / step) + 1 }, (_, i) => i * step);
26
+ }
27
+ /** راهنمای شناور مشترک نمودارها؛ x و y نسبت به ظرف نمودار */
28
+ export function ChartTip({ x, y, title, rows, width }) {
29
+ // داخل ظرف بماند
30
+ const cx = width ? Math.min(Math.max(x, 80), width - 80) : x;
31
+ return (_jsxs("div", { className: "k-chart__tip", style: { left: cx, top: y }, "aria-hidden": "true", children: [title && _jsx("span", { className: "k-chart__tip-title", children: title }), rows.map((r, i) => (_jsxs("span", { className: "k-chart__tip-row", style: r.color ? { "--_c": r.color } : undefined, children: [r.name !== undefined && _jsxs("span", { children: [r.color && _jsx("i", {}), r.name] }), _jsx("strong", { children: r.value })] }, i)))] }));
32
+ }
33
+ /** موقعیت راهنما بالای یک عنصر، نسبت به ظرف */
34
+ const tipAt = (el, box, i, anchor) => {
35
+ if (!box)
36
+ return null;
37
+ const b = box.getBoundingClientRect();
38
+ const r = (anchor ?? el).getBoundingClientRect();
39
+ return { x: r.left + r.width / 2 - b.left, y: r.top - b.top, i };
40
+ };
41
+ /** جدول هم‌ارز برای صفحه‌خوان و چاپ */
42
+ function DataTable({ caption, labels, series, format }) {
43
+ return (_jsxs("table", { className: "k-sr-only", children: [_jsx("caption", { children: caption }), _jsx("thead", { children: _jsxs("tr", { children: [_jsx("th", { scope: "col", children: "\u062F\u0648\u0631\u0647" }), series.map((s) => _jsx("th", { scope: "col", children: s.name }, s.name))] }) }), _jsx("tbody", { children: labels.map((l, i) => _jsxs("tr", { children: [_jsx("th", { scope: "row", children: l }), series.map((s) => _jsx("td", { children: format(s.values[i]) }, s.name))] }, l)) })] }));
44
+ }
45
+ /** نمودار ستونی؛ تک‌سری یا انباشته تا چهار سری. با موس یا Tab روی هر ستون مقدار دقیق نمایش داده می‌شود */
46
+ export function BarChart({ title, data, series, labels, format = fmtDefault, labelMax = true, height, className }) {
47
+ const id = useId();
48
+ const stacked = series?.slice(0, 4);
49
+ const cats = stacked ? labels ?? [] : (data ?? []).map((d) => d.label);
50
+ const totals = cats.map((_, i) => (stacked ? stacked.reduce((n, s) => n + (s.values[i] ?? 0), 0) : data[i].value));
51
+ const max = Math.max(0, ...totals);
52
+ const ticks = niceTicks(max);
53
+ const top = ticks[ticks.length - 1] || 1;
54
+ const maxIndex = totals.indexOf(max);
55
+ const color = (i) => ({ "--_c": `var(--k-chart-${i + 1})` });
56
+ const describe = (i) => stacked ? `${cats[i]}: ${stacked.map((s) => `${s.name} ${format(s.values[i] ?? 0)}`).join("، ")}، جمع ${format(totals[i])}` : `${cats[i]}: ${format(totals[i])}`;
57
+ const box = useRef(null);
58
+ const [tip, setTip] = useState(null);
59
+ const show = (e, i) => setTip(tipAt(e.currentTarget, box.current, i, e.currentTarget.querySelector(".k-bars__bar, .k-bars__stack")));
60
+ return (_jsxs("figure", { className: cx("k-chart k-chart--bar", className), "aria-labelledby": `${id}-t`, style: { margin: 0, ...(height ? { "--k-chart-height": height } : {}) }, children: [_jsxs("figcaption", { className: "k-chart__head", children: [_jsx("p", { className: "k-chart__title", id: `${id}-t`, children: title }), stacked && stacked.length > 1 && (_jsx("ul", { className: "k-chart__legend", "aria-hidden": "true", children: stacked.map((s, i) => _jsxs("li", { style: color(i), children: [_jsx("span", { className: "k-chart__key k-chart__key--box" }), s.name] }, s.name)) }))] }), _jsxs("div", { className: "k-chart__plot", ref: box, children: [_jsx("div", { className: "k-bars__grid", "aria-hidden": "true", children: ticks.map((t) => _jsx("span", { "data-v": compact(t) }, t)) }), _jsx("div", { className: "k-bars", role: "list", "aria-label": title, children: cats.map((label, i) => (_jsxs("div", { className: "k-bars__col", role: "listitem", tabIndex: 0, "aria-label": describe(i), "data-active": tip?.i === i ? "" : undefined, style: { "--_d": `${i * 40}ms` }, onPointerEnter: (e) => show(e, i), onPointerLeave: () => setTip(null), onFocus: (e) => show(e, i), onBlur: () => setTip(null), children: [labelMax && i === maxIndex && _jsx("span", { className: "k-bars__value", "aria-hidden": "true", children: format(totals[i]) }), stacked ? (_jsx("span", { className: "k-bars__stack", style: { blockSize: `${(totals[i] / top) * 100}%` }, "aria-hidden": "true", children: stacked.map((s, si) => (_jsx("span", { className: "k-bars__seg", style: { ...color(si), flexGrow: s.values[i] ?? 0 } }, s.name))) })) : (_jsx("span", { className: "k-bars__bar", style: { blockSize: `${(totals[i] / top) * 100}%` }, "aria-hidden": "true" })), _jsx("span", { className: "k-bars__label", "aria-hidden": "true", children: label })] }, label))) }), tip && (_jsx(ChartTip, { x: tip.x, y: tip.y, width: box.current?.clientWidth, title: cats[tip.i], rows: stacked
61
+ ? [...stacked.map((s, si) => ({ name: s.name, value: format(s.values[tip.i] ?? 0), color: `var(--k-chart-${si + 1})` })), { name: "جمع", value: format(totals[tip.i]) }]
62
+ : [{ value: format(totals[tip.i]) }] }))] })] }));
63
+ }
64
+ /** میله‌های افقی برای رتبه‌بندی با نام‌های بلند، مثل پربازدیدترین صفحه‌ها */
65
+ export function BarList({ title, data, format = fmtDefault, className }) {
66
+ const id = useId();
67
+ const max = Math.max(1, ...data.map((d) => d.value));
68
+ const total = data.reduce((n, d) => n + d.value, 0) || 1;
69
+ const share = (v) => `${formatNumber(Math.round((v / total) * 1000) / 10).replace(".", "٫")}٪`;
70
+ const box = useRef(null);
71
+ const [tip, setTip] = useState(null);
72
+ return (_jsxs("figure", { className: cx("k-chart", className), "aria-labelledby": `${id}-t`, style: { margin: 0 }, children: [_jsx("figcaption", { className: "k-chart__head", children: _jsx("p", { className: "k-chart__title", id: `${id}-t`, children: title }) }), _jsxs("ol", { className: "k-barlist", ref: box, style: { position: "relative" }, children: [data.map((d, i) => (_jsxs("li", { className: "k-barlist__row", "data-active": tip?.i === i ? "" : undefined, style: { "--_d": `${i * 60}ms` }, onPointerEnter: (e) => setTip(tipAt(e.currentTarget, box.current, i, e.currentTarget.querySelector(".k-barlist__fill"))), onPointerLeave: () => setTip(null), children: [_jsxs("span", { className: "k-barlist__track", children: [_jsx("span", { className: "k-barlist__fill", style: { inlineSize: `${(d.value / max) * 100}%` }, "aria-hidden": "true" }), d.href ? _jsx("a", { className: "k-barlist__label", href: d.href, children: d.label }) : _jsx("span", { className: "k-barlist__label", children: d.label })] }), _jsxs("span", { className: "k-barlist__value", children: [format(d.value), " ", _jsx("span", { className: "k-barlist__share", children: share(d.value) })] })] }, d.label))), tip && _jsx(ChartTip, { x: tip.x, y: tip.y, width: box.current?.clientWidth, title: data[tip.i].label, rows: [{ name: "مقدار", value: format(data[tip.i].value) }, { name: "سهم از کل", value: share(data[tip.i].value) }] })] })] }));
73
+ }
74
+ /** سهم هر بخش از کل در یک میلهٔ افقی، مثل منبع ورود کاربران؛ جایگزین خواناتر نمودار دایره‌ای */
75
+ export function ProportionBar({ title, data, percent = true, format = fmtDefault, className }) {
76
+ const id = useId();
77
+ const parts = data.slice(0, 4);
78
+ const total = parts.reduce((n, d) => n + d.value, 0) || 1;
79
+ const pct = (v) => `${formatNumber(Math.round((v / total) * 1000) / 10).replace(".", "٫")}٪`;
80
+ const color = (i) => ({ "--_c": `var(--k-chart-${i + 1})` });
81
+ const box = useRef(null);
82
+ const [tip, setTip] = useState(null);
83
+ return (_jsxs("figure", { className: cx("k-chart", className), "aria-labelledby": `${id}-t`, style: { margin: 0 }, children: [_jsx("figcaption", { className: "k-chart__head", children: _jsx("p", { className: "k-chart__title", id: `${id}-t`, children: title }) }), _jsxs("div", { className: "k-proportion__wrap", ref: box, children: [_jsx("div", { className: "k-proportion", "aria-hidden": "true", children: parts.map((d, i) => (_jsx("span", { className: "k-proportion__seg", "data-active": tip?.i === i ? "" : undefined, style: { ...color(i), flexGrow: d.value }, onPointerEnter: (e) => setTip(tipAt(e.currentTarget, box.current, i)), onPointerLeave: () => setTip(null) }, d.label))) }), tip && _jsx(ChartTip, { x: tip.x, y: tip.y, width: box.current?.clientWidth, rows: [{ name: parts[tip.i].label, value: pct(parts[tip.i].value), color: `var(--k-chart-${tip.i + 1})` }, { name: "تعداد", value: format(parts[tip.i].value) }] })] }), _jsx("ul", { className: "k-proportion__legend", children: parts.map((d, i) => (_jsxs("li", { style: color(i), "data-active": tip?.i === i ? "" : undefined, children: [_jsx("span", { className: "k-chart__key k-chart__key--box", "aria-hidden": "true" }), _jsx("span", { children: d.label }), _jsx("strong", { children: percent ? pct(d.value) : format(d.value) }), percent && _jsx("span", { className: "k-proportion__abs", children: format(d.value) })] }, d.label))) })] }));
84
+ }
85
+ /**
86
+ * نمودار دایره‌ای یا دونات تا پنج بخش، با فاصلهٔ کوچک بین بخش‌ها، راهنمای درصد و جدول هم‌ارز.
87
+ * برای مقایسهٔ دقیق بخش‌ها ProportionBar خواناتر است.
88
+ */
89
+ export function PieChart({ title, data, variant = "donut", format = fmtDefault, totalLabel = "جمع", size = 176, className }) {
90
+ const id = useId();
91
+ const sorted = [...data].sort((a, b) => b.value - a.value);
92
+ const parts = sorted.length > 5 ? [...sorted.slice(0, 4), { label: "سایر", value: sorted.slice(4).reduce((n, d) => n + d.value, 0) }] : sorted;
93
+ const total = parts.reduce((n, d) => n + d.value, 0) || 1;
94
+ const pct = (v) => `${formatNumber(Math.round((v / total) * 1000) / 10).replace(".", "٫")}٪`;
95
+ const slot = (i) => (i < 4 ? `var(--k-chart-${i + 1})` : "var(--k-text-quaternary)");
96
+ const donut = variant === "donut";
97
+ // دایره با stroke-dasharray: هر بخش یک کمان؛ برای pie، شعاع نصف و ضخامت برابر قطر
98
+ const R = 50, r = donut ? 40 : 25, w = donut ? 16 : 50;
99
+ const C = 2 * Math.PI * r;
100
+ const gap = parts.length > 1 ? (donut ? 1.6 : 0.8) : 0;
101
+ const [active, setActive] = useState(null);
102
+ const box = useRef(null);
103
+ let acc = 0;
104
+ const arcs = parts.map((d) => {
105
+ const len = (d.value / total) * C;
106
+ const a = { start: acc, len };
107
+ acc += len;
108
+ return a;
109
+ });
110
+ const mid = (i) => {
111
+ const ang = ((arcs[i].start + arcs[i].len / 2) / C) * 2 * Math.PI - Math.PI / 2;
112
+ const rr = donut ? r : r * 1.3;
113
+ return { x: (R + rr * Math.cos(ang)) / (2 * R), y: (R + rr * Math.sin(ang)) / (2 * R) };
114
+ };
115
+ return (_jsxs("figure", { className: cx("k-chart k-pie", className), "aria-labelledby": `${id}-t`, style: { margin: 0 }, children: [_jsx("figcaption", { className: "k-chart__head", children: _jsx("p", { className: "k-chart__title", id: `${id}-t`, children: title }) }), _jsxs("div", { className: "k-pie__body", children: [_jsxs("div", { className: "k-pie__plot", ref: box, style: { inlineSize: size, blockSize: size }, onPointerLeave: () => setActive(null), children: [_jsxs("svg", { viewBox: "0 0 100 100", className: "k-pie__svg", "aria-hidden": "true", children: [donut && _jsx("circle", { cx: R, cy: R, r: r, fill: "none", stroke: "var(--k-bg-tertiary)", strokeWidth: w }), parts.map((d, i) => (_jsx("circle", { className: "k-pie__slice", "data-active": active === i ? "" : undefined, cx: R, cy: R, r: r, fill: "none", stroke: slot(i), strokeWidth: w, strokeDasharray: `${Math.max(0, arcs[i].len - gap)} ${C}`, strokeDashoffset: -arcs[i].start, transform: `rotate(-90 ${R} ${R})`, style: { "--_d": `${i * 80}ms` }, onPointerEnter: () => setActive(i) }, d.label)))] }), donut && (_jsxs("div", { className: "k-pie__center", "aria-hidden": "true", children: [_jsx("strong", { children: active === null ? format(total) : pct(parts[active].value) }), _jsx("span", { children: active === null ? totalLabel : parts[active].label })] })), active !== null && !donut && (_jsx(ChartTip, { x: mid(active).x * size, y: mid(active).y * size - 8, rows: [{ name: parts[active].label, value: pct(parts[active].value), color: slot(active) }, { name: "تعداد", value: format(parts[active].value) }] }))] }), _jsx("ul", { className: "k-pie__legend", children: parts.map((d, i) => (_jsxs("li", { style: { "--_c": slot(i) }, "data-active": active === i ? "" : undefined, onPointerEnter: () => setActive(i), onPointerLeave: () => setActive(null), children: [_jsx("span", { className: "k-chart__key k-chart__key--box", "aria-hidden": "true" }), _jsx("span", { className: "k-pie__name", children: d.label }), _jsx("strong", { children: pct(d.value) }), _jsx("span", { className: "k-pie__abs", children: format(d.value) })] }, d.label))) })] })] }));
116
+ }
117
+ /** خط روند کوچک برای کارت آمار و جدول؛ بدون محور، فقط شکل روند */
118
+ export function Sparkline({ values, "aria-label": ariaLabel, tone = "brand", area = true, className }) {
119
+ const hi = Math.max(...values), lo = Math.min(...values);
120
+ // حداقل دامنه ۲۵٪ مقدار تا تغییر کوچک، زیگزاگ بزرگ دیده نشود
121
+ const span = Math.max(hi - lo, Math.abs(hi) * 0.25) || 1;
122
+ const min = (hi + lo) / 2 - span / 2;
123
+ const pts = values.map((v, i) => [(i / Math.max(1, values.length - 1)) * 100, 28 - ((v - min) / span) * 24]);
124
+ const d = pts.map(([x, y], i) => `${i ? "L" : "M"}${x},${y}`).join(" ");
125
+ const c = tone === "neutral" ? "var(--k-text-tertiary)" : tone === "brand" ? "var(--k-text-brand)" : `var(--k-text-${tone})`;
126
+ return (_jsxs("svg", { className: cx("k-sparkline", className), viewBox: "0 0 100 30", preserveAspectRatio: "none", role: ariaLabel ? "img" : undefined, "aria-label": ariaLabel, "aria-hidden": ariaLabel ? undefined : true, style: { color: c }, children: [area && _jsx("path", { d: `${d} L100,30 L0,30 Z`, fill: "currentColor", opacity: 0.1 }), _jsx("path", { d: d, fill: "none", stroke: "currentColor", strokeWidth: 2, vectorEffect: "non-scaling-stroke", strokeLinejoin: "round", strokeLinecap: "round" })] }));
127
+ }
128
+ /**
129
+ * نمودار خطی تا چهار سری: خط ۲ پیکسلی، برچسب نام در انتهای هر خط،
130
+ * راهنمای عمودی با موس و ←→ روی کیبورد، و جدول هم‌ارز برای صفحه‌خوان.
131
+ */
132
+ export function LineChart({ title, labels, series, format = fmtDefault, area, height, className }) {
133
+ const id = useId();
134
+ const plot = useRef(null);
135
+ const [size, setSize] = useState({ w: 600, h: 220, rtl: true });
136
+ const [active, setActive] = useState(null);
137
+ const shown = series.slice(0, 4);
138
+ useLayoutEffect(() => {
139
+ const el = plot.current;
140
+ if (!el)
141
+ return;
142
+ const measure = () => setSize({ w: el.clientWidth, h: el.clientHeight, rtl: getComputedStyle(el).direction === "rtl" });
143
+ measure();
144
+ const ro = new ResizeObserver(measure);
145
+ ro.observe(el);
146
+ return () => ro.disconnect();
147
+ }, []);
148
+ const pad = { top: 12, bottom: 24, start: 52, end: shown.length > 1 ? 64 : 16 };
149
+ const max = Math.max(0, ...shown.flatMap((s) => s.values));
150
+ const ticks = niceTicks(max);
151
+ const top = ticks[ticks.length - 1] || 1;
152
+ const innerW = Math.max(1, size.w - pad.start - pad.end);
153
+ const innerH = Math.max(1, size.h - pad.top - pad.bottom);
154
+ // محور زمان در جهت خواندن صفحه: در RTL اولین نقطه سمت راست
155
+ const x = (i) => {
156
+ const t = labels.length > 1 ? i / (labels.length - 1) : 0.5;
157
+ return size.rtl ? size.w - pad.start - t * innerW : pad.start + t * innerW;
158
+ };
159
+ const y = (v) => pad.top + innerH - (v / top) * innerH;
160
+ // SVG با جهت ltr رسم می‌شود تا text-anchor فیزیکی باشد؛ اعداد محور بیرون از ناحیهٔ نمودار
161
+ const tickX = size.rtl ? size.w - pad.start + 8 : pad.start - 8;
162
+ const anchor = size.rtl ? "start" : "end";
163
+ // برچسب انتهای خط‌ها روی هم نیفتند: دست‌کم ۱۴ پیکسل فاصلهٔ عمودی
164
+ const last = labels.length - 1;
165
+ const endY = (() => {
166
+ const order = shown.map((s, i) => ({ i, y: y(s.values[last]) })).sort((a, b) => a.y - b.y);
167
+ for (let k = 1; k < order.length; k++)
168
+ if (order[k].y - order[k - 1].y < 14)
169
+ order[k].y = order[k - 1].y + 14;
170
+ return Object.fromEntries(order.map((o) => [o.i, o.y]));
171
+ })();
172
+ const endX = (i) => x(i) + (size.rtl ? -8 : 8);
173
+ const color = (i) => ({ "--_c": `var(--k-chart-${i + 1})` });
174
+ const pick = (clientX) => {
175
+ const r = plot.current.getBoundingClientRect();
176
+ const px = clientX - r.left;
177
+ let best = 0;
178
+ labels.forEach((_, i) => { if (Math.abs(x(i) - px) < Math.abs(x(best) - px))
179
+ best = i; });
180
+ setActive(best);
181
+ };
182
+ const onKey = (e) => {
183
+ const next = { ArrowLeft: size.rtl ? 1 : -1, ArrowRight: size.rtl ? -1 : 1 }[e.key];
184
+ if (next) {
185
+ e.preventDefault();
186
+ setActive((a) => Math.min(labels.length - 1, Math.max(0, (a ?? (next > 0 ? -1 : labels.length)) + next)));
187
+ }
188
+ else if (e.key === "Home")
189
+ setActive(0);
190
+ else if (e.key === "End")
191
+ setActive(labels.length - 1);
192
+ else if (e.key === "Escape")
193
+ setActive(null);
194
+ };
195
+ const step = Math.max(1, Math.ceil(labels.length / Math.max(2, Math.floor(innerW / 64))));
196
+ return (_jsxs("figure", { className: cx("k-chart", className), "aria-labelledby": `${id}-t`, style: { margin: 0, ...(height ? { "--k-chart-height": height } : {}) }, children: [_jsxs("figcaption", { className: "k-chart__head", children: [_jsx("p", { className: "k-chart__title", id: `${id}-t`, children: title }), shown.length > 1 && (_jsx("ul", { className: "k-chart__legend", "aria-hidden": "true", children: shown.map((s, i) => _jsxs("li", { style: color(i), children: [_jsx("span", { className: "k-chart__key" }), s.name] }, s.name)) }))] }), _jsxs("div", { ref: plot, className: "k-chart__plot", tabIndex: 0, role: "img", "aria-label": `${title}. با کلیدهای جهت بین نقطه‌ها حرکت کنید.`, "aria-describedby": `${id}-live`, onPointerMove: (e) => pick(e.clientX), onPointerLeave: () => setActive(null), onKeyDown: onKey, onBlur: () => setActive(null), children: [_jsxs("svg", { className: "k-chart__svg", "aria-hidden": "true", direction: "ltr", children: [_jsx("g", { className: "k-chart__grid", children: ticks.map((t) => _jsx("line", { x1: pad.start - (size.rtl ? 0 : 0), x2: size.w - pad.end, y1: y(t), y2: y(t), transform: size.rtl ? `translate(${pad.end - pad.start} 0)` : undefined }, t)) }), ticks.map((t) => _jsx("text", { className: "k-chart__tick", x: tickX, y: y(t) + 4, textAnchor: anchor, children: compact(t) }, t)), labels.map((l, i) => (i % step === 0 || i === labels.length - 1) && _jsx("text", { className: "k-chart__tick", x: x(i), y: size.h - 6, textAnchor: "middle", children: l }, l)), _jsx("defs", { children: _jsxs("linearGradient", { id: `${id}-fade`, x1: "0", y1: "0", x2: "0", y2: "1", children: [_jsx("stop", { offset: "0", style: { stopColor: "var(--k-chart-1)", stopOpacity: 0.28 } }), _jsx("stop", { offset: "1", style: { stopColor: "var(--k-chart-1)", stopOpacity: 0 } })] }) }), (area ?? shown.length === 1) && shown.length === 1 && (_jsx("path", { className: "k-chart__area", fill: `url(#${id}-fade)`, d: `M${x(0)},${y(0)} ${shown[0].values.map((v, i) => `L${x(i)},${y(v)}`).join(" ")} L${x(labels.length - 1)},${y(0)} Z` })), active !== null && _jsx("line", { className: "k-chart__cross", x1: x(active), x2: x(active), y1: pad.top, y2: pad.top + innerH }), shown.map((s, si) => (_jsxs("g", { style: color(si), children: [_jsx("path", { className: "k-chart__line", pathLength: 1, d: s.values.map((v, i) => `${i ? "L" : "M"}${x(i)},${y(v)}`).join(" ") }), _jsx("circle", { className: "k-chart__dot", cx: x(s.values.length - 1), cy: y(s.values[s.values.length - 1]), r: 4 }), shown.length > 1 && _jsx("text", { className: "k-chart__end", x: endX(last), y: endY[si] + 4, textAnchor: size.rtl ? "end" : "start", children: s.name }), active !== null && _jsx("circle", { className: "k-chart__dot", cx: x(active), cy: y(s.values[active]), r: 4.5 })] }, s.name)))] }), active !== null && (_jsx(ChartTip, { x: x(active), y: Math.min(...shown.map((s) => y(s.values[active]))) - 6, width: size.w, title: labels[active], rows: shown.map((s, si) => ({ name: s.name, value: format(s.values[active]), color: `var(--k-chart-${si + 1})` })) }))] }), _jsx("span", { className: "k-sr-only", "aria-live": "polite", id: `${id}-live`, children: active !== null ? `${labels[active]}: ${shown.map((s) => `${s.name} ${format(s.values[active])}`).join("، ")}` : "" }), _jsx(DataTable, { caption: title, labels: labels, series: shown, format: format })] }));
197
+ }
@@ -0,0 +1,22 @@
1
+ import { type ReactNode } from "react";
2
+ export interface ChipOption {
3
+ value: string;
4
+ label: ReactNode;
5
+ icon?: ReactNode;
6
+ /** تعداد نتیجه‌ها کنار برچسب */
7
+ count?: number;
8
+ disabled?: boolean;
9
+ }
10
+ export interface ChipGroupProps {
11
+ options: ChipOption[];
12
+ /** مقدارهای انتخاب‌شده */
13
+ value?: string[];
14
+ defaultValue?: string[];
15
+ onChange?: (value: string[]) => void;
16
+ /** فقط یک انتخاب؛ کلیک دوباره انتخاب را برمی‌دارد */
17
+ single?: boolean;
18
+ "aria-label"?: string;
19
+ className?: string;
20
+ }
21
+ /** تراشه‌های فیلتر روشن و خاموش‌شونده، مثل دسته‌بندی‌ها یا وضعیت سفارش */
22
+ export declare function ChipGroup({ options, value, defaultValue, onChange, single, "aria-label": ariaLabel, className }: ChipGroupProps): import("react").JSX.Element;
@@ -0,0 +1,18 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useState } from "react";
3
+ import { toFaDigits } from "@kashi-ui/persian";
4
+ import { cx } from "./cx.js";
5
+ const Check = () => (_jsx("svg", { className: "k-chip__check", viewBox: "0 0 20 20", fill: "none", stroke: "currentColor", strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: _jsx("path", { d: "m5 10.5 3.2 3L15 7" }) }));
6
+ /** تراشه‌های فیلتر روشن و خاموش‌شونده، مثل دسته‌بندی‌ها یا وضعیت سفارش */
7
+ export function ChipGroup({ options, value, defaultValue = [], onChange, single, "aria-label": ariaLabel, className }) {
8
+ const [inner, setInner] = useState(defaultValue);
9
+ const current = value ?? inner;
10
+ const toggle = (v) => {
11
+ const on = current.includes(v);
12
+ const next = single ? (on ? [] : [v]) : on ? current.filter((x) => x !== v) : [...current, v];
13
+ if (value === undefined)
14
+ setInner(next);
15
+ onChange?.(next);
16
+ };
17
+ return (_jsx("div", { role: "group", "aria-label": ariaLabel, className: cx("k-chips", className), children: options.map((o) => (_jsxs("button", { type: "button", className: "k-chip", "aria-pressed": current.includes(o.value), disabled: o.disabled, onClick: () => toggle(o.value), children: [_jsx(Check, {}), o.icon, o.label, o.count !== undefined && _jsx("span", { className: "k-chip__count", children: toFaDigits(o.count) })] }, o.value))) }));
18
+ }
@@ -0,0 +1,15 @@
1
+ import { type ReactNode } from "react";
2
+ export interface ContextMenuProps {
3
+ /** ناحیه‌ای که راست‌کلیک روی آن منو را باز می‌کند */
4
+ children: ReactNode;
5
+ /** گزینه‌ها: MenuItem، MenuSeparator و MenuLabel */
6
+ menu: ReactNode;
7
+ /** نام منو برای صفحه‌خوان @default «گزینه‌ها» */
8
+ label?: string;
9
+ className?: string;
10
+ }
11
+ /**
12
+ * منوی راست‌کلیک؛ با کیبورد هم: کلید ContextMenu یا Shift+F10 روی ناحیهٔ فوکوس‌شده.
13
+ * همان گزینه‌ها و پیمایش منوی کشویی را دارد.
14
+ */
15
+ export declare function ContextMenu({ children, menu, label, className }: ContextMenuProps): import("react").JSX.Element;
@@ -0,0 +1,71 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useEffect, useId, useRef, useState } from "react";
3
+ import { MenuCtx, items, menuKeyDown } from "./DropdownMenu.js";
4
+ import { cx } from "./cx.js";
5
+ /**
6
+ * منوی راست‌کلیک؛ با کیبورد هم: کلید ContextMenu یا Shift+F10 روی ناحیهٔ فوکوس‌شده.
7
+ * همان گزینه‌ها و پیمایش منوی کشویی را دارد.
8
+ */
9
+ export function ContextMenu({ children, menu, label = "گزینه‌ها", className }) {
10
+ const id = useId();
11
+ const [pos, setPos] = useState(null);
12
+ const area = useRef(null);
13
+ const list = useRef(null);
14
+ const returnTo = useRef(null);
15
+ const placed = useRef(false);
16
+ const close = (focusBack = true) => {
17
+ placed.current = false;
18
+ setPos(null);
19
+ if (focusBack)
20
+ returnTo.current?.focus();
21
+ };
22
+ const openAt = (x, y) => {
23
+ returnTo.current = document.activeElement ?? area.current;
24
+ setPos({ x, y });
25
+ };
26
+ useEffect(() => {
27
+ const el = list.current;
28
+ const pop = el;
29
+ if (!pos) {
30
+ if (el.matches?.(":popover-open"))
31
+ pop.hidePopover?.();
32
+ return;
33
+ }
34
+ if (pop.showPopover && !el.matches(":popover-open"))
35
+ pop.showPopover();
36
+ // یک بار جای‌گذاری: در RTL منو سمت چپ نشانگر باز می‌شود (مثل منوی بومی) و از صفحه بیرون نمی‌رود
37
+ if (!placed.current) {
38
+ placed.current = true;
39
+ const r = el.getBoundingClientRect();
40
+ const rtl = getComputedStyle(area.current).direction === "rtl";
41
+ let nx = rtl ? pos.x - r.width : pos.x;
42
+ if (nx < 8)
43
+ nx = rtl ? pos.x : 8;
44
+ nx = Math.max(8, Math.min(nx, innerWidth - r.width - 8));
45
+ const ny = Math.max(8, pos.y + r.height > innerHeight - 8 ? pos.y - r.height : pos.y);
46
+ if (nx !== pos.x || ny !== pos.y)
47
+ return setPos({ x: nx, y: Math.min(ny, innerHeight - r.height - 8) });
48
+ }
49
+ items(el)[0]?.focus({ preventScroll: true });
50
+ const onDown = (e) => !el.contains(e.target) && close(false);
51
+ const onScroll = () => close(false);
52
+ document.addEventListener("pointerdown", onDown);
53
+ // اسکرولی که همین حالا در جریان است منو را نبندد
54
+ const t = setTimeout(() => addEventListener("scroll", onScroll, { passive: true, once: true }), 150);
55
+ return () => {
56
+ clearTimeout(t);
57
+ document.removeEventListener("pointerdown", onDown);
58
+ removeEventListener("scroll", onScroll);
59
+ };
60
+ }, [pos?.x, pos?.y]);
61
+ return (_jsxs("div", { ref: area, className: cx("k-context-area", className), "aria-haspopup": "menu", "aria-describedby": `${id}-hint`, onContextMenu: (e) => {
62
+ e.preventDefault();
63
+ openAt(e.clientX, e.clientY);
64
+ }, onKeyDown: (e) => {
65
+ if (e.key === "ContextMenu" || (e.shiftKey && e.key === "F10")) {
66
+ e.preventDefault();
67
+ const r = document.activeElement.getBoundingClientRect();
68
+ openAt(r.left + r.width / 2, r.top + r.height / 2);
69
+ }
70
+ }, children: [children, _jsx("span", { id: `${id}-hint`, className: "k-sr-only", children: "\u0628\u0631\u0627\u06CC \u06AF\u0632\u06CC\u0646\u0647\u200C\u0647\u0627 \u0631\u0627\u0633\u062A\u200C\u06A9\u0644\u06CC\u06A9 \u06A9\u0646\u06CC\u062F \u06CC\u0627 Shift+F10 \u0631\u0627 \u0628\u0632\u0646\u06CC\u062F." }), _jsx(MenuCtx.Provider, { value: { close }, children: _jsx("ul", { ref: list, ...{ popover: "manual" }, role: "menu", "aria-label": label, className: "k-menu k-menu--context", hidden: !pos, style: pos ? { "--_x": `${pos.x}px`, "--_y": `${pos.y}px` } : undefined, onKeyDown: (e) => menuKeyDown(e, list.current, () => close(), () => close(false)), children: menu }) })] }));
71
+ }
@@ -0,0 +1,22 @@
1
+ export interface CountdownProps {
2
+ /** زمان پایان */
3
+ to?: Date;
4
+ /** یا مدت به ثانیه از لحظهٔ نمایش (مثلاً ۱۲۰ برای ارسال دوبارهٔ کد) */
5
+ seconds?: number;
6
+ onComplete?: () => void;
7
+ /** «clock» مثل ۰۲:۳۴، «blocks» کادرهای روز/ساعت/دقیقه/ثانیه @default "clock" */
8
+ variant?: "clock" | "blocks";
9
+ /** @default "fa" */
10
+ digits?: "fa" | "latin";
11
+ /** نام برای صفحه‌خوان، مثل «زمان باقی‌مانده تا ارسال دوباره» */
12
+ "aria-label"?: string;
13
+ className?: string;
14
+ labels?: {
15
+ days?: string;
16
+ hours?: string;
17
+ minutes?: string;
18
+ seconds?: string;
19
+ };
20
+ }
21
+ /** شمارش معکوس با ارقام فارسی؛ هر ثانیه به‌روز می‌شود و در پایان onComplete را صدا می‌زند */
22
+ export declare function Countdown({ to, seconds, onComplete, variant, digits, "aria-label": ariaLabel, className, labels }: CountdownProps): import("react").JSX.Element;
@@ -0,0 +1,37 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useEffect, useRef, useState } from "react";
3
+ import { toFaDigits } from "@kashi-ui/persian";
4
+ import { cx } from "./cx.js";
5
+ const pad = (n) => String(n).padStart(2, "0");
6
+ /** شمارش معکوس با ارقام فارسی؛ هر ثانیه به‌روز می‌شود و در پایان onComplete را صدا می‌زند */
7
+ export function Countdown({ to, seconds, onComplete, variant = "clock", digits = "fa", "aria-label": ariaLabel, className, labels = {} }) {
8
+ const { days = "روز", hours = "ساعت", minutes = "دقیقه", seconds: secLabel = "ثانیه" } = labels;
9
+ const end = useRef(to?.getTime() ?? Date.now() + (seconds ?? 0) * 1000);
10
+ const [left, setLeft] = useState(() => Math.max(0, Math.ceil((end.current - Date.now()) / 1000)));
11
+ const done = useRef(false);
12
+ useEffect(() => {
13
+ end.current = to?.getTime() ?? Date.now() + (seconds ?? 0) * 1000;
14
+ done.current = false;
15
+ const tick = () => {
16
+ const s = Math.max(0, Math.ceil((end.current - Date.now()) / 1000));
17
+ setLeft(s);
18
+ if (s === 0 && !done.current) {
19
+ done.current = true;
20
+ onComplete?.();
21
+ }
22
+ };
23
+ tick();
24
+ const t = setInterval(tick, 1000);
25
+ return () => clearInterval(t);
26
+ }, [to?.getTime(), seconds]);
27
+ const d = Math.floor(left / 86400), h = Math.floor((left % 86400) / 3600), m = Math.floor((left % 3600) / 60), s = left % 60;
28
+ const f = (x) => (digits === "fa" ? toFaDigits(String(x)) : String(x));
29
+ // متن کامل برای صفحه‌خوان؛ role="timer" به‌طور پیش‌فرض هر ثانیه خوانده نمی‌شود
30
+ const spoken = [d && `${f(d)} ${days}`, h && `${f(h)} ${hours}`, m && `${f(m)} ${minutes}`, `${f(s)} ${secLabel}`].filter(Boolean).join(" و ");
31
+ if (variant === "blocks") {
32
+ const units = [...(d ? [[d, days]] : []), [h, hours], [m, minutes], [s, secLabel]];
33
+ return (_jsx("div", { role: "timer", "aria-label": ariaLabel ? `${ariaLabel}: ${spoken}` : spoken, className: cx("k-countdown k-countdown--blocks", className), "data-done": left === 0 ? "" : undefined, children: units.map(([v, name]) => (_jsxs("span", { className: "k-countdown__unit", "aria-hidden": "true", children: [_jsx("span", { className: "k-countdown__num", children: f(pad(v)) }), _jsx("span", { className: "k-countdown__name", children: name })] }, name))) }));
34
+ }
35
+ const clock = (d ? `${d}:` : "") + (h || d ? `${pad(h)}:` : "") + `${pad(m)}:${pad(s)}`;
36
+ return (_jsx("span", { role: "timer", "aria-label": ariaLabel ? `${ariaLabel}: ${spoken}` : spoken, className: cx("k-countdown", className), "data-done": left === 0 ? "" : undefined, dir: "ltr", children: _jsx("span", { "aria-hidden": "true", children: f(clock) }) }));
37
+ }
@@ -1,4 +1,7 @@
1
- import { type ReactElement, type ReactNode } from "react";
1
+ import { type KeyboardEvent, type ReactElement, type ReactNode } from "react";
2
+ export declare const MenuCtx: import("react").Context<{
3
+ close: (focusTrigger?: boolean) => void;
4
+ } | null>;
2
5
  export interface DropdownMenuProps {
3
6
  /** دکمه‌ای که منو را باز می‌کند */
4
7
  trigger: ReactElement;
@@ -8,12 +11,15 @@ export interface DropdownMenuProps {
8
11
  align?: "start" | "end";
9
12
  children: ReactNode;
10
13
  }
14
+ export declare const items: (menu: HTMLElement | null) => HTMLElement[];
11
15
  /**
12
16
  * منوی کشویی با الگوی Menu Button در WAI-ARIA:
13
17
  * Enter، Space یا ↓ باز می‌کند و اولین گزینه را فوکوس می‌کند، ↑ آخرین را؛
14
18
  * ↑↓ و Home/End حرکت، حرف اول برای پرش، Esc بستن و برگشت به دکمه، Tab بستن.
15
19
  */
16
20
  export declare function DropdownMenu({ trigger, label, align, children }: DropdownMenuProps): import("react").JSX.Element;
21
+ /** پیمایش کیبورد مشترک منوها: ↑↓، Home/End، حرف اول، Esc و Tab */
22
+ export declare function menuKeyDown(e: KeyboardEvent<HTMLElement>, menu: HTMLElement | null, close: () => void, dismiss: () => void): void;
17
23
  export interface MenuItemProps {
18
24
  onSelect?: () => void;
19
25
  icon?: ReactNode;
@@ -1,8 +1,8 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
2
  import { Children, cloneElement, createContext, isValidElement, useContext, useEffect, useId, useRef, useState, } from "react";
3
3
  import { cx } from "./cx.js";
4
- const MenuCtx = createContext(null);
5
- const items = (menu) => [...(menu?.querySelectorAll('[role^="menuitem"]:not([aria-disabled="true"])') ?? [])];
4
+ export const MenuCtx = createContext(null);
5
+ export const items = (menu) => [...(menu?.querySelectorAll('[role^="menuitem"]:not([aria-disabled="true"])') ?? [])];
6
6
  /**
7
7
  * منوی کشویی با الگوی Menu Button در WAI-ARIA:
8
8
  * Enter، Space یا ↓ باز می‌کند و اولین گزینه را فوکوس می‌کند، ↑ آخرین را؛
@@ -36,33 +36,7 @@ export function DropdownMenu({ trigger, label, align = "start", children }) {
36
36
  focusOnOpen.current = where;
37
37
  setOpen(true);
38
38
  };
39
- const onMenuKey = (e) => {
40
- const list = items(menuRef.current);
41
- const i = list.indexOf(document.activeElement);
42
- const go = (j) => list[(j + list.length) % list.length]?.focus();
43
- if (e.key === "ArrowDown")
44
- go(i + 1);
45
- else if (e.key === "ArrowUp")
46
- go(i - 1);
47
- else if (e.key === "Home")
48
- go(0);
49
- else if (e.key === "End")
50
- go(list.length - 1);
51
- else if (e.key === "Escape")
52
- close();
53
- else if (e.key === "Tab")
54
- return setOpen(false);
55
- else if (e.key.length === 1 && /\S/.test(e.key)) {
56
- // پرش با حرف اول
57
- const k = e.key.toLowerCase();
58
- const start = i + 1;
59
- const hit = [...list.slice(start), ...list.slice(0, start)].find((el) => el.textContent?.trim().toLowerCase().startsWith(k));
60
- hit?.focus();
61
- }
62
- else
63
- return;
64
- e.preventDefault();
65
- };
39
+ const onMenuKey = (e) => menuKeyDown(e, menuRef.current, close, () => setOpen(false));
66
40
  const t = isValidElement(trigger)
67
41
  ? cloneElement(trigger, {
68
42
  ref: triggerRef,
@@ -81,6 +55,34 @@ export function DropdownMenu({ trigger, label, align = "start", children }) {
81
55
  : trigger;
82
56
  return (_jsxs("span", { className: "k-menu-anchor", ref: anchorRef, children: [t, _jsx(MenuCtx.Provider, { value: { close }, children: _jsx("ul", { ref: menuRef, id: `${id}-menu`, role: "menu", "aria-label": label, "aria-labelledby": label ? undefined : `${id}-trigger`, className: cx("k-menu", align === "end" && "k-menu--end"), hidden: !open, onKeyDown: onMenuKey, children: Children.map(children, (c) => c) }) })] }));
83
57
  }
58
+ /** پیمایش کیبورد مشترک منوها: ↑↓، Home/End، حرف اول، Esc و Tab */
59
+ export function menuKeyDown(e, menu, close, dismiss) {
60
+ const list = items(menu);
61
+ const i = list.indexOf(document.activeElement);
62
+ const go = (j) => list[(j + list.length) % list.length]?.focus();
63
+ if (e.key === "ArrowDown")
64
+ go(i + 1);
65
+ else if (e.key === "ArrowUp")
66
+ go(i - 1);
67
+ else if (e.key === "Home")
68
+ go(0);
69
+ else if (e.key === "End")
70
+ go(list.length - 1);
71
+ else if (e.key === "Escape")
72
+ close();
73
+ else if (e.key === "Tab")
74
+ return dismiss();
75
+ else if (e.key.length === 1 && /\S/.test(e.key)) {
76
+ // پرش با حرف اول
77
+ const k = e.key.toLowerCase();
78
+ const start = i + 1;
79
+ const hit = [...list.slice(start), ...list.slice(0, start)].find((el) => el.textContent?.trim().toLowerCase().startsWith(k));
80
+ hit?.focus();
81
+ }
82
+ else
83
+ return;
84
+ e.preventDefault();
85
+ }
84
86
  export function MenuItem({ onSelect, icon, shortcut, tone = "default", disabled, href, checked, children }) {
85
87
  const checkable = checked !== undefined;
86
88
  const ctx = useContext(MenuCtx);
@@ -0,0 +1,23 @@
1
+ import { type ReactNode } from "react";
2
+ export interface InlineEditProps {
3
+ value?: string;
4
+ defaultValue?: string;
5
+ /** پس از ثبت؛ اگر Promise برگرداند تا پایانش منتظر می‌ماند و در خطا متن قبلی برمی‌گردد */
6
+ onSave?: (value: string) => void | Promise<void>;
7
+ /** نام فیلد برای صفحه‌خوان، مثل «نام پروژه» (الزامی) */
8
+ label: string;
9
+ placeholder?: string;
10
+ /** اعتبارسنجی؛ پیام خطا یا undefined */
11
+ validate?: (value: string) => string | undefined;
12
+ /** نمایش متن، مثلاً به‌شکل عنوان */
13
+ renderView?: (value: string) => ReactNode;
14
+ className?: string;
15
+ labels?: {
16
+ edit?: string;
17
+ save?: string;
18
+ cancel?: string;
19
+ empty?: string;
20
+ };
21
+ }
22
+ /** ویرایش درجا: کلیک یا Enter برای ویرایش، Enter ثبت، Esc انصراف */
23
+ export declare function InlineEdit({ value, defaultValue, onSave, label, placeholder, validate, renderView, className, labels }: InlineEditProps): import("react").JSX.Element;
@@ -0,0 +1,77 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useEffect, useRef, useState } from "react";
3
+ import { cx } from "./cx.js";
4
+ const Pencil = () => _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: "m13.5 3.5 3 3L7 16H4v-3Z" }) });
5
+ const Check = () => _jsx("svg", { viewBox: "0 0 20 20", fill: "none", stroke: "currentColor", strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: _jsx("path", { d: "m5 10.5 3.2 3L15 7" }) });
6
+ const X = () => _jsx("svg", { viewBox: "0 0 20 20", fill: "none", stroke: "currentColor", strokeWidth: 1.8, strokeLinecap: "round", "aria-hidden": "true", children: _jsx("path", { d: "m6 6 8 8M14 6l-8 8" }) });
7
+ /** ویرایش درجا: کلیک یا Enter برای ویرایش، Enter ثبت، Esc انصراف */
8
+ export function InlineEdit({ value, defaultValue = "", onSave, label, placeholder, validate, renderView, className, labels = {} }) {
9
+ const { edit = "ویرایش", save = "ثبت", cancel = "انصراف", empty = "خالی" } = labels;
10
+ const [inner, setInner] = useState(defaultValue);
11
+ const current = value ?? inner;
12
+ const [editing, setEditing] = useState(false);
13
+ const [draft, setDraft] = useState(current);
14
+ const [error, setError] = useState();
15
+ const [busy, setBusy] = useState(false);
16
+ const input = useRef(null);
17
+ const view = useRef(null);
18
+ const back = useRef(false);
19
+ useEffect(() => {
20
+ if (editing)
21
+ input.current?.select();
22
+ else if (back.current) {
23
+ back.current = false;
24
+ view.current?.focus();
25
+ }
26
+ }, [editing]);
27
+ const start = () => {
28
+ setDraft(current);
29
+ setError(undefined);
30
+ setEditing(true);
31
+ };
32
+ const stop = () => {
33
+ back.current = true;
34
+ setEditing(false);
35
+ };
36
+ const commit = async () => {
37
+ const v = draft.trim();
38
+ const err = validate?.(v);
39
+ if (err)
40
+ return setError(err);
41
+ if (v === current)
42
+ return stop();
43
+ const prev = current;
44
+ if (value === undefined)
45
+ setInner(v);
46
+ setBusy(true);
47
+ try {
48
+ await onSave?.(v);
49
+ stop();
50
+ }
51
+ catch {
52
+ if (value === undefined)
53
+ setInner(prev);
54
+ setError("ذخیره نشد؛ دوباره امتحان کنید.");
55
+ }
56
+ finally {
57
+ setBusy(false);
58
+ }
59
+ };
60
+ if (!editing) {
61
+ return (_jsx("span", { className: cx("k-inline-edit", className), children: _jsxs("button", { ref: view, type: "button", className: "k-inline-edit__view", onClick: start, "aria-label": `${label}: ${current || empty}، ${edit}`, children: [current ? (renderView ? renderView(current) : current) : _jsx("span", { className: "k-inline-edit__placeholder", children: placeholder ?? empty }), _jsx(Pencil, {})] }) }));
62
+ }
63
+ const errId = `${label}-err`.replace(/\s/g, "-");
64
+ return (_jsxs("span", { className: cx("k-inline-edit", className), children: [_jsxs("span", { className: "k-field", style: { gap: 4 }, children: [_jsx("span", { className: "k-input", "data-state": error ? "invalid" : undefined, children: _jsx("input", { ref: input, className: "k-input__control", "aria-label": label, value: draft, placeholder: placeholder, "aria-invalid": error ? true : undefined, "aria-describedby": error ? errId : undefined, disabled: busy, onChange: (e) => {
65
+ setDraft(e.target.value);
66
+ setError(undefined);
67
+ }, onKeyDown: (e) => {
68
+ if (e.key === "Enter") {
69
+ e.preventDefault();
70
+ commit();
71
+ }
72
+ else if (e.key === "Escape") {
73
+ e.preventDefault();
74
+ stop();
75
+ }
76
+ } }) }), error && _jsx("span", { className: "k-hint k-hint--error", id: errId, children: error })] }), _jsxs("span", { className: "k-inline-edit__actions", children: [_jsx("button", { type: "button", className: "k-btn k-btn--primary k-btn--icon k-btn--sm", "aria-label": save, "aria-busy": busy || undefined, onClick: commit, children: _jsx(Check, {}) }), _jsx("button", { type: "button", className: "k-btn k-btn--secondary k-btn--icon k-btn--sm", "aria-label": cancel, onClick: stop, children: _jsx(X, {}) })] })] }));
77
+ }
@@ -0,0 +1,19 @@
1
+ import { type ReactNode } from "react";
2
+ import { type InputProps } from "./Input.js";
3
+ type Base = Omit<InputProps, "value" | "defaultValue" | "onChange" | "type" | "inputMode" | "addonEnd">;
4
+ export interface LandlineInputProps extends Base {
5
+ /** مثل "02188776655" یا "+982188776655" */
6
+ value?: string;
7
+ defaultValue?: string;
8
+ /** شماره به شکل ۰۲۱xxxxxxxx، معتبر بودن و نام استان */
9
+ onValueChange?: (value: string, valid: boolean, province: string | null) => void;
10
+ /** @default "fa" */
11
+ digits?: "fa" | "latin";
12
+ /** نمایش نام استان از روی پیش‌شماره @default true */
13
+ showProvince?: boolean;
14
+ /** @default "شمارهٔ تلفن ثابت معتبر نیست." */
15
+ invalidMessage?: ReactNode;
16
+ }
17
+ /** تلفن ثابت با پیش‌شماره: +98 را به ۰ تبدیل می‌کند، گروه‌بندی و نام استان را نشان می‌دهد */
18
+ export declare const LandlineInput: import("react").ForwardRefExoticComponent<LandlineInputProps & import("react").RefAttributes<HTMLInputElement>>;
19
+ export {};
@@ -0,0 +1,23 @@
1
+ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { forwardRef, useId, useState } from "react";
3
+ import { formatLandline, getLandlineProvince, isValidLandline, normalizeLandline } from "@kashi-ui/persian";
4
+ import { Input } from "./Input.js";
5
+ import { useDigitsInput } from "./useDigitsInput.js";
6
+ import { mergeRefs } from "./utils.js";
7
+ /** تلفن ثابت با پیش‌شماره: +98 را به ۰ تبدیل می‌کند، گروه‌بندی و نام استان را نشان می‌دهد */
8
+ export const LandlineInput = forwardRef(function LandlineInput({ value, defaultValue, onValueChange, digits = "fa", showProvince = true, invalidMessage = "شمارهٔ تلفن ثابت معتبر نیست.", error, name, id, onBlur, placeholder, ...rest }, ref) {
9
+ const autoId = useId();
10
+ const inputId = id ?? autoId;
11
+ const [touched, setTouched] = useState(false);
12
+ const { raw, shown, inputRef, handleChange } = useDigitsInput({ value, defaultValue, maxDigits: 11, normalize: normalizeLandline, format: formatLandline, digits });
13
+ const province = showProvince ? getLandlineProvince(raw) : null;
14
+ const showInvalid = raw.length > 0 && (touched || raw.length === 11) && !isValidLandline(raw);
15
+ const provId = `${inputId}-province`;
16
+ return (_jsxs(_Fragment, { children: [_jsx(Input, { ref: mergeRefs(ref, inputRef), id: inputId, type: "tel", inputMode: "tel", autoComplete: "tel-national", dir: "ltr", placeholder: placeholder ?? (digits === "fa" ? "۰۲۱ ۸۸۷۷ ۶۶۵۵" : "021 8877 6655"), value: shown, onChange: (e) => {
17
+ const next = handleChange(e);
18
+ onValueChange?.(next, isValidLandline(next), getLandlineProvince(next));
19
+ }, onBlur: (e) => {
20
+ setTouched(true);
21
+ onBlur?.(e);
22
+ }, addonEnd: province ? _jsx("span", { className: "k-input__meta", id: provId, children: province }) : undefined, "aria-describedby": province ? provId : undefined, error: error ?? (showInvalid ? invalidMessage : undefined), ...rest }), name && _jsx("input", { type: "hidden", name: name, value: raw })] }));
23
+ });
@@ -0,0 +1,23 @@
1
+ export interface JalaliMonth {
2
+ year: number;
3
+ /** ۱ تا ۱۲ */
4
+ month: number;
5
+ }
6
+ export interface MonthPickerProps {
7
+ value?: JalaliMonth | null;
8
+ defaultValue?: JalaliMonth | null;
9
+ onChange?: (value: JalaliMonth) => void;
10
+ min?: JalaliMonth;
11
+ max?: JalaliMonth;
12
+ /** @default "fa" */
13
+ digits?: "fa" | "latin";
14
+ /** @default "انتخاب ماه" */
15
+ "aria-label"?: string;
16
+ className?: string;
17
+ labels?: {
18
+ prevYear?: string;
19
+ nextYear?: string;
20
+ };
21
+ }
22
+ /** انتخاب ماه و سال شمسی، برای گزارش ماهانه یا تاریخ انقضای کارت؛ ↑↓←→ بین ماه‌ها و PageUp/PageDown بین سال‌ها */
23
+ export declare function MonthPicker({ value, defaultValue, onChange, min, max, digits, "aria-label": ariaLabel, className, labels }: MonthPickerProps): import("react").JSX.Element;
@@ -0,0 +1,62 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useEffect, useRef, useState } from "react";
3
+ import { JALALI_MONTHS, toFaDigits, toJalali } from "@kashi-ui/persian";
4
+ import { cx } from "./cx.js";
5
+ const key = (m) => m.year * 12 + m.month;
6
+ const Arrow = ({ next }) => (_jsx("svg", { viewBox: "0 0 20 20", fill: "none", stroke: "currentColor", strokeWidth: 1.7, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", "data-k-mirror": "", children: _jsx("path", { d: next ? "m8 5 5 5-5 5" : "m12 5-5 5 5 5" }) }));
7
+ /** انتخاب ماه و سال شمسی، برای گزارش ماهانه یا تاریخ انقضای کارت؛ ↑↓←→ بین ماه‌ها و PageUp/PageDown بین سال‌ها */
8
+ export function MonthPicker({ value, defaultValue = null, onChange, min, max, digits = "fa", "aria-label": ariaLabel = "انتخاب ماه", className, labels = {} }) {
9
+ const { prevYear = "سال قبل", nextYear = "سال بعد" } = labels;
10
+ const today = toJalali(new Date());
11
+ const [inner, setInner] = useState(defaultValue);
12
+ const selected = value !== undefined ? value : inner;
13
+ const [year, setYear] = useState(selected?.year ?? today.jy);
14
+ const [focus, setFocus] = useState(selected?.year === year ? selected.month : today.jy === year ? today.jm : 1);
15
+ const grid = useRef(null);
16
+ // پس از رندر سال یا ماه تازه، فوکوس به همان ماه برود (با کیبورد)
17
+ const pendingFocus = useRef(false);
18
+ useEffect(() => {
19
+ if (!pendingFocus.current)
20
+ return;
21
+ pendingFocus.current = false;
22
+ grid.current?.querySelector(`[data-month="${focus}"]`)?.focus();
23
+ }, [year, focus]);
24
+ const f = (n) => (digits === "fa" ? toFaDigits(String(n)) : String(n));
25
+ const out = (m) => (min && key(m) < key(min)) || (max && key(m) > key(max));
26
+ const pick = (m) => {
27
+ if (out(m))
28
+ return;
29
+ if (value === undefined)
30
+ setInner(m);
31
+ onChange?.(m);
32
+ };
33
+ const moveTo = (y, m) => {
34
+ pendingFocus.current = true;
35
+ setYear(y);
36
+ setFocus(m);
37
+ };
38
+ const onKeyDown = (e) => {
39
+ const rtl = getComputedStyle(e.currentTarget).direction === "rtl";
40
+ const delta = { ArrowRight: rtl ? -1 : 1, ArrowLeft: rtl ? 1 : -1, ArrowDown: 3, ArrowUp: -3 };
41
+ let idx = year * 12 + focus - 1;
42
+ if (e.key in delta)
43
+ idx += delta[e.key];
44
+ else if (e.key === "PageUp")
45
+ idx -= 12;
46
+ else if (e.key === "PageDown")
47
+ idx += 12;
48
+ else if (e.key === "Home")
49
+ idx = year * 12;
50
+ else if (e.key === "End")
51
+ idx = year * 12 + 11;
52
+ else
53
+ return;
54
+ e.preventDefault();
55
+ moveTo(Math.floor(idx / 12), (idx % 12) + 1);
56
+ };
57
+ return (_jsxs("div", { className: cx("k-monthpicker", className), role: "group", "aria-label": ariaLabel, children: [_jsxs("div", { className: "k-monthpicker__header", children: [_jsx("button", { type: "button", className: "k-btn k-btn--tertiary k-btn--icon k-btn--sm", "aria-label": prevYear, onClick: () => setYear(year - 1), disabled: !!min && year <= min.year, children: _jsx(Arrow, {}) }), _jsx("span", { className: "k-monthpicker__year", "aria-live": "polite", children: f(year) }), _jsx("button", { type: "button", className: "k-btn k-btn--tertiary k-btn--icon k-btn--sm", "aria-label": nextYear, onClick: () => setYear(year + 1), disabled: !!max && year >= max.year, children: _jsx(Arrow, { next: true }) })] }), _jsx("div", { className: "k-monthpicker__grid", ref: grid, onKeyDown: onKeyDown, children: JALALI_MONTHS.map((name, i) => {
58
+ const m = { year, month: i + 1 };
59
+ const isSel = selected?.year === year && selected.month === i + 1;
60
+ return (_jsx("button", { type: "button", "data-month": i + 1, className: "k-monthpicker__month", tabIndex: focus === i + 1 ? 0 : -1, "aria-pressed": isSel, "aria-label": `${name} ${f(year)}`, "aria-current": today.jy === year && today.jm === i + 1 ? "date" : undefined, disabled: !!out(m), onFocus: () => setFocus(i + 1), onClick: () => pick(m), children: name }, name));
61
+ }) })] }));
62
+ }
@@ -0,0 +1,23 @@
1
+ export interface PasswordRule {
2
+ label: string;
3
+ test: (password: string) => boolean;
4
+ }
5
+ export declare const defaultPasswordRules: PasswordRule[];
6
+ export interface PasswordStrengthProps {
7
+ password: string;
8
+ rules?: PasswordRule[];
9
+ /** نمایش فهرست شرط‌ها @default true */
10
+ showRules?: boolean;
11
+ /** هشدار وقتی رمز حروف فارسی دارد (صفحه‌کلید فارسی مانده) @default true */
12
+ warnPersian?: boolean;
13
+ /** شناسهٔ این بخش، برای aria-describedby فیلد رمز */
14
+ id?: string;
15
+ className?: string;
16
+ labels?: {
17
+ title?: string;
18
+ levels?: [string, string, string, string];
19
+ persian?: string;
20
+ };
21
+ }
22
+ /** قدرت رمز عبور با نوار چهارقسمتی و فهرست شرط‌ها؛ زیر فیلد رمز بگذارید و با id به آن وصل کنید */
23
+ export declare function PasswordStrength({ password, rules, showRules, warnPersian, id, className, labels }: PasswordStrengthProps): import("react").JSX.Element;
@@ -0,0 +1,21 @@
1
+ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { toFaDigits } from "@kashi-ui/persian";
3
+ import { cx } from "./cx.js";
4
+ export const defaultPasswordRules = [
5
+ { label: `حداقل ${toFaDigits(8)} نویسه`, test: (p) => p.length >= 8 },
6
+ { label: "حروف بزرگ و کوچک انگلیسی", test: (p) => /[a-z]/.test(p) && /[A-Z]/.test(p) },
7
+ { label: "دست‌کم یک عدد", test: (p) => /\d/.test(p) },
8
+ { label: "دست‌کم یک نماد، مثل ! یا @", test: (p) => /[^A-Za-z0-9\s؀-ۿ]/.test(p) },
9
+ ];
10
+ const Check = () => _jsx("svg", { viewBox: "0 0 20 20", fill: "none", stroke: "currentColor", strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: _jsx("path", { d: "m5 10.5 3.2 3L15 7" }) });
11
+ const Dot = () => _jsx("svg", { viewBox: "0 0 20 20", "aria-hidden": "true", children: _jsx("circle", { cx: "10", cy: "10", r: "2.5", fill: "currentColor" }) });
12
+ /** قدرت رمز عبور با نوار چهارقسمتی و فهرست شرط‌ها؛ زیر فیلد رمز بگذارید و با id به آن وصل کنید */
13
+ export function PasswordStrength({ password, rules = defaultPasswordRules, showRules = true, warnPersian = true, id, className, labels = {} }) {
14
+ const { title = "قدرت رمز", levels = ["ضعیف", "متوسط", "خوب", "قوی"], persian = "رمز حروف فارسی دارد؛ شاید صفحه‌کلید روی فارسی مانده است." } = labels;
15
+ const met = rules.map((r) => r.test(password));
16
+ const n = met.filter(Boolean).length;
17
+ // امتیاز ۰ تا ۴ به نسبت شرط‌های برآورده‌شده
18
+ const score = password ? Math.max(1, Math.round((n / rules.length) * 4)) : 0;
19
+ const persianTyped = warnPersian && /[؀-ۿ]/.test(password);
20
+ return (_jsxs("div", { id: id, className: cx("k-strength", className), "data-score": score, children: [_jsx("div", { className: "k-strength__bars", "aria-hidden": "true", children: [0, 1, 2, 3].map((i) => _jsx("span", { className: "k-strength__bar" }, i)) }), _jsx("p", { className: "k-strength__label", "aria-live": "polite", style: { margin: 0 }, children: score > 0 && _jsxs(_Fragment, { children: [title, ": ", _jsx("strong", { children: levels[score - 1] })] }) }), persianTyped && _jsx("p", { className: "k-hint k-hint--error", role: "alert", children: persian }), showRules && (_jsx("ul", { className: "k-strength__rules", children: rules.map((r, i) => (_jsxs("li", { className: "k-strength__rule", "data-met": met[i] ? "" : undefined, children: [met[i] ? _jsx(Check, {}) : _jsx(Dot, {}), _jsxs("span", { children: [r.label, _jsx("span", { className: "k-sr-only", children: met[i] ? "، رعایت شده" : "، رعایت نشده" })] })] }, r.label))) }))] }));
21
+ }
@@ -0,0 +1,7 @@
1
+ import { type ComboboxProps } from "./Combobox.js";
2
+ export interface ProvinceSelectProps extends Omit<ComboboxProps, "options"> {
3
+ /** نمایش مرکز استان زیر نام @default true */
4
+ showCapital?: boolean;
5
+ }
6
+ /** انتخاب یکی از ۳۱ استان با جستجو؛ با نام مرکز استان هم پیدا می‌شود (مثلاً «مشهد») */
7
+ export declare const ProvinceSelect: import("react").ForwardRefExoticComponent<ProvinceSelectProps & import("react").RefAttributes<HTMLInputElement>>;
@@ -0,0 +1,9 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { forwardRef } from "react";
3
+ import { PROVINCES } from "@kashi-ui/persian";
4
+ import { Combobox } from "./Combobox.js";
5
+ const options = (capital) => PROVINCES.map((p) => ({ value: p.name, label: p.name, description: capital ? `مرکز: ${p.capital}` : undefined, keywords: [p.capital] }));
6
+ /** انتخاب یکی از ۳۱ استان با جستجو؛ با نام مرکز استان هم پیدا می‌شود (مثلاً «مشهد») */
7
+ export const ProvinceSelect = forwardRef(function ProvinceSelect({ showCapital = true, label = "استان", placeholder = "جستجوی استان یا شهر", ...rest }, ref) {
8
+ return _jsx(Combobox, { ref: ref, label: label, placeholder: placeholder, options: options(showCapital), ...rest });
9
+ });
@@ -0,0 +1,26 @@
1
+ import { type ReactNode } from "react";
2
+ export interface TreeNode {
3
+ id: string;
4
+ label: string;
5
+ icon?: ReactNode;
6
+ /** متن کوچک انتهای ردیف، مثل تعداد یا حجم */
7
+ meta?: ReactNode;
8
+ disabled?: boolean;
9
+ children?: TreeNode[];
10
+ }
11
+ export interface TreeViewProps {
12
+ items: TreeNode[];
13
+ selected?: string | null;
14
+ defaultSelected?: string | null;
15
+ onSelect?: (id: string, node: TreeNode) => void;
16
+ expanded?: string[];
17
+ defaultExpanded?: string[];
18
+ onExpandedChange?: (ids: string[]) => void;
19
+ "aria-label"?: string;
20
+ className?: string;
21
+ }
22
+ /**
23
+ * درخت پوشه‌ها یا دسته‌بندی‌ها با الگوی Tree در WAI-ARIA:
24
+ * ↑↓ حرکت، → و ← (در RTL برعکس) باز و بسته کردن، Home/End، Enter یا Space انتخاب.
25
+ */
26
+ export declare function TreeView({ items, selected, defaultSelected, onSelect, expanded, defaultExpanded, onExpandedChange, "aria-label": ariaLabel, className }: TreeViewProps): import("react").JSX.Element;
@@ -0,0 +1,96 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useRef, useState } from "react";
3
+ import { cx } from "./cx.js";
4
+ const Chevron = () => _jsx("svg", { viewBox: "0 0 20 20", fill: "none", stroke: "currentColor", strokeWidth: 1.8, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: _jsx("path", { d: "m8 5 5 5-5 5" }) });
5
+ /**
6
+ * درخت پوشه‌ها یا دسته‌بندی‌ها با الگوی Tree در WAI-ARIA:
7
+ * ↑↓ حرکت، → و ← (در RTL برعکس) باز و بسته کردن، Home/End، Enter یا Space انتخاب.
8
+ */
9
+ export function TreeView({ items, selected, defaultSelected = null, onSelect, expanded, defaultExpanded = [], onExpandedChange, "aria-label": ariaLabel, className }) {
10
+ const [innerSel, setInnerSel] = useState(defaultSelected);
11
+ const [innerExp, setInnerExp] = useState(defaultExpanded);
12
+ const sel = selected !== undefined ? selected : innerSel;
13
+ const exp = expanded ?? innerExp;
14
+ const [focusId, setFocusId] = useState(null);
15
+ const root = useRef(null);
16
+ // ردیف‌های قابل‌مشاهده به ترتیب، برای پیمایش با کیبورد
17
+ const visible = [];
18
+ const walk = (nodes, level, parent) => {
19
+ for (const n of nodes) {
20
+ visible.push({ node: n, level, parent });
21
+ if (n.children?.length && exp.includes(n.id))
22
+ walk(n.children, level + 1, n.id);
23
+ }
24
+ };
25
+ walk(items, 1, null);
26
+ const current = focusId && visible.some((v) => v.node.id === focusId) ? focusId : sel && visible.some((v) => v.node.id === sel) ? sel : visible[0]?.node.id;
27
+ const setExp = (ids) => {
28
+ if (expanded === undefined)
29
+ setInnerExp(ids);
30
+ onExpandedChange?.(ids);
31
+ };
32
+ const toggle = (id, open = !exp.includes(id)) => setExp(open ? [...new Set([...exp, id])] : exp.filter((x) => x !== id));
33
+ const choose = (n) => {
34
+ if (n.disabled)
35
+ return;
36
+ if (selected === undefined)
37
+ setInnerSel(n.id);
38
+ onSelect?.(n.id, n);
39
+ };
40
+ const focus = (id) => {
41
+ setFocusId(id);
42
+ root.current?.querySelector(`[data-id="${CSS.escape(id)}"]`)?.focus();
43
+ };
44
+ const onKeyDown = (e) => {
45
+ const i = visible.findIndex((v) => v.node.id === current);
46
+ const v = visible[i];
47
+ if (!v)
48
+ return;
49
+ const rtl = getComputedStyle(e.currentTarget).direction === "rtl";
50
+ const inKey = rtl ? "ArrowLeft" : "ArrowRight";
51
+ const outKey = rtl ? "ArrowRight" : "ArrowLeft";
52
+ const hasKids = !!v.node.children?.length;
53
+ const open = exp.includes(v.node.id);
54
+ let handled = true;
55
+ if (e.key === "ArrowDown")
56
+ visible[i + 1] && focus(visible[i + 1].node.id);
57
+ else if (e.key === "ArrowUp")
58
+ visible[i - 1] && focus(visible[i - 1].node.id);
59
+ else if (e.key === "Home")
60
+ focus(visible[0].node.id);
61
+ else if (e.key === "End")
62
+ focus(visible[visible.length - 1].node.id);
63
+ else if (e.key === inKey) {
64
+ if (hasKids && !open)
65
+ toggle(v.node.id, true);
66
+ else if (hasKids)
67
+ focus(v.node.children[0].id);
68
+ }
69
+ else if (e.key === outKey) {
70
+ if (hasKids && open)
71
+ toggle(v.node.id, false);
72
+ else if (v.parent)
73
+ focus(v.parent);
74
+ }
75
+ else if (e.key === "Enter" || e.key === " ")
76
+ choose(v.node);
77
+ else
78
+ handled = false;
79
+ if (handled)
80
+ e.preventDefault();
81
+ };
82
+ const render = (nodes, level) => nodes.map((n) => {
83
+ const hasKids = !!n.children?.length;
84
+ const open = exp.includes(n.id);
85
+ return (_jsxs("li", { role: "treeitem", "data-id": n.id, className: "k-tree__item", "aria-level": level, "aria-expanded": hasKids ? open : undefined, "aria-selected": sel === n.id, "aria-disabled": n.disabled || undefined, tabIndex: current === n.id ? 0 : -1, onFocus: (e) => {
86
+ if (e.target === e.currentTarget)
87
+ setFocusId(n.id);
88
+ }, children: [_jsxs("div", { className: "k-tree__row", onClick: () => {
89
+ if (hasKids)
90
+ toggle(n.id);
91
+ choose(n);
92
+ focus(n.id);
93
+ }, children: [hasKids ? _jsx("span", { className: "k-tree__toggle", "aria-hidden": "true", children: _jsx(Chevron, {}) }) : _jsx("span", { className: "k-tree__spacer" }), n.icon && _jsx("span", { className: "k-tree__icon", "aria-hidden": "true", children: n.icon }), _jsx("span", { className: "k-tree__label", children: n.label }), n.meta && _jsx("span", { className: "k-tree__meta", children: n.meta })] }), hasKids && open && _jsx("ul", { role: "group", children: render(n.children, level + 1) })] }, n.id));
94
+ });
95
+ return (_jsx("ul", { ref: root, role: "tree", "aria-label": ariaLabel, className: cx("k-tree", className), onKeyDown: onKeyDown, children: render(items, 1) }));
96
+ }
package/dist/index.d.ts CHANGED
@@ -98,3 +98,27 @@ export { PostalCodeInput } from "./PostalCodeInput.js";
98
98
  export type { PostalCodeInputProps } from "./PostalCodeInput.js";
99
99
  export { PlateInput } from "./PlateInput.js";
100
100
  export type { PlateInputProps } from "./PlateInput.js";
101
+ export { TreeView } from "./TreeView.js";
102
+ export type { TreeNode, TreeViewProps } from "./TreeView.js";
103
+ export { ButtonGroup } from "./ButtonGroup.js";
104
+ export type { ButtonGroupProps } from "./ButtonGroup.js";
105
+ export { ChipGroup } from "./ChipGroup.js";
106
+ export type { ChipOption, ChipGroupProps } from "./ChipGroup.js";
107
+ export { PasswordStrength, defaultPasswordRules } from "./PasswordStrength.js";
108
+ export type { PasswordRule, PasswordStrengthProps } from "./PasswordStrength.js";
109
+ export { Countdown } from "./Countdown.js";
110
+ export type { CountdownProps } from "./Countdown.js";
111
+ export { MonthPicker } from "./MonthPicker.js";
112
+ export type { JalaliMonth, MonthPickerProps } from "./MonthPicker.js";
113
+ export { LandlineInput } from "./LandlineInput.js";
114
+ export type { LandlineInputProps } from "./LandlineInput.js";
115
+ export { BarChart, BarList, LineChart, PieChart, ProportionBar, Sparkline } from "./Chart.js";
116
+ export type { BarChartProps, BarListProps, LineChartProps, LineSeries, PieChartProps, ProportionBarProps, SparklineProps } from "./Chart.js";
117
+ export { ActivityHeatmap } from "./ActivityHeatmap.js";
118
+ export type { ActivityHeatmapProps } from "./ActivityHeatmap.js";
119
+ export { ContextMenu } from "./ContextMenu.js";
120
+ export type { ContextMenuProps } from "./ContextMenu.js";
121
+ export { InlineEdit } from "./InlineEdit.js";
122
+ export type { InlineEditProps } from "./InlineEdit.js";
123
+ export { ProvinceSelect } from "./ProvinceSelect.js";
124
+ export type { ProvinceSelectProps } from "./ProvinceSelect.js";
package/dist/index.js CHANGED
@@ -49,3 +49,15 @@ export { Rating } from "./Rating.js";
49
49
  export { TimeInput } from "./TimeInput.js";
50
50
  export { PostalCodeInput } from "./PostalCodeInput.js";
51
51
  export { PlateInput } from "./PlateInput.js";
52
+ export { TreeView } from "./TreeView.js";
53
+ export { ButtonGroup } from "./ButtonGroup.js";
54
+ export { ChipGroup } from "./ChipGroup.js";
55
+ export { PasswordStrength, defaultPasswordRules } from "./PasswordStrength.js";
56
+ export { Countdown } from "./Countdown.js";
57
+ export { MonthPicker } from "./MonthPicker.js";
58
+ export { LandlineInput } from "./LandlineInput.js";
59
+ export { BarChart, BarList, LineChart, PieChart, ProportionBar, Sparkline } from "./Chart.js";
60
+ export { ActivityHeatmap } from "./ActivityHeatmap.js";
61
+ export { ContextMenu } from "./ContextMenu.js";
62
+ export { InlineEdit } from "./InlineEdit.js";
63
+ export { ProvinceSelect } from "./ProvinceSelect.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kashi-ui/react",
3
- "version": "0.10.0",
3
+ "version": "0.12.0",
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": "^0.10.0",
25
+ "@kashi-ui/css": "^0.12.0",
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": "^0.10.0",
63
- "@kashi-ui/persian": "^0.10.0"
62
+ "@kashi-ui/bank-logos": "^0.12.0",
63
+ "@kashi-ui/persian": "^0.12.0"
64
64
  }
65
65
  }