@kashi-ui/react 1.7.0 → 2.0.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/dist/Button.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { type ButtonHTMLAttributes, type ElementType, type ReactNode } from "react";
2
- export type ButtonVariant = "primary" | "secondary" | "tertiary" | "link" | "danger" | "danger-secondary";
2
+ export type ButtonVariant = "primary" | "secondary" | "outline" | "tertiary" | "link" | "danger" | "danger-secondary";
3
3
  export type ButtonSize = "xs" | "sm" | "md" | "lg" | "xl";
4
4
  export interface ButtonProps extends Omit<ButtonHTMLAttributes<HTMLButtonElement>, "type"> {
5
5
  /** @default "secondary" */
@@ -0,0 +1,28 @@
1
+ import { type ReactNode } from "react";
2
+ export interface PriceRangeProps {
3
+ /** کمترین و بیشترین قیمت ممکن */
4
+ min: number;
5
+ max: number;
6
+ /** [از، تا] */
7
+ value?: [number, number];
8
+ defaultValue?: [number, number];
9
+ onChange?: (value: [number, number]) => void;
10
+ /** گام اسلایدر و گرد کردن عددهای تایپ‌شده @default 1000 */
11
+ step?: number;
12
+ /** عنوان بالای فیلتر، مثل «قیمت» */
13
+ label?: ReactNode;
14
+ /** واحد کنار فیلدها @default "تومان" (در انگلیسی «Toman») */
15
+ unit?: ReactNode;
16
+ /** با name، دو فیلد name_min و name_max در فرم ارسال می‌شوند */
17
+ name?: string;
18
+ disabled?: boolean;
19
+ className?: string;
20
+ labels?: {
21
+ from?: string;
22
+ to?: string;
23
+ min?: string;
24
+ max?: string;
25
+ };
26
+ }
27
+ /** فیلتر بازهٔ قیمت: دو فیلد «از» و «تا» با جداکنندهٔ هزارگان و یک اسلایدر دودستگیره که با هم هماهنگ‌اند */
28
+ export declare function PriceRange({ min, max, value, defaultValue, onChange, step, label, unit, name, disabled, className, labels, }: PriceRangeProps): import("react").JSX.Element;
@@ -0,0 +1,43 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { useEffect, useId, useState } from "react";
4
+ import { formatNumber, toEnDigits } from "@kashi-ui/persian";
5
+ import { cx } from "./cx.js";
6
+ import { useKashi } from "./KashiProvider.js";
7
+ import { Slider } from "./Slider.js";
8
+ /** فیلتر بازهٔ قیمت: دو فیلد «از» و «تا» با جداکنندهٔ هزارگان و یک اسلایدر دودستگیره که با هم هماهنگ‌اند */
9
+ export function PriceRange({ min, max, value, defaultValue, onChange, step = 1000, label, unit, name, disabled, className, labels = {}, }) {
10
+ const { messages: M, digits: D, locale } = useKashi();
11
+ const id = useId();
12
+ const [inner, setInner] = useState(defaultValue ?? [min, max]);
13
+ const [lo, hi] = value ?? inner;
14
+ const fmt = (n) => formatNumber(n, { digits: D });
15
+ const u = unit ?? (locale === "en" ? "Toman" : "تومان");
16
+ const { from = M.priceRange.from, to = M.priceRange.to, min: minLabel = M.priceRange.min, max: maxLabel = M.priceRange.max } = labels;
17
+ const set = (next) => {
18
+ if (value === undefined)
19
+ setInner(next);
20
+ onChange?.(next);
21
+ };
22
+ // متن فیلدها جدا از عدد نگه داشته می‌شود تا هنگام تایپ پرش نکند؛ با خروج از فیلد یا Enter اعمال می‌شود
23
+ const [text, setText] = useState([fmt(lo), fmt(hi)]);
24
+ useEffect(() => setText([fmt(lo), fmt(hi)]), [lo, hi, D]);
25
+ const parse = (s) => Number(toEnDigits(s).replace(/\D/g, "") || "0");
26
+ const commit = (which) => {
27
+ let n = Math.round(parse(text[which]) / step) * step;
28
+ n = Math.min(max, Math.max(min, n));
29
+ const next = which === 0 ? [Math.min(n, hi), hi] : [lo, Math.max(n, lo)];
30
+ set(next);
31
+ setText([fmt(next[0]), fmt(next[1])]);
32
+ };
33
+ const live = (which, raw) => {
34
+ const digits = toEnDigits(raw).replace(/\D/g, "");
35
+ const shown = digits ? fmt(Number(digits)) : "";
36
+ setText((t) => (which === 0 ? [shown, t[1]] : [t[0], shown]));
37
+ };
38
+ const field = (which) => (_jsxs("label", { className: "k-price-range__field", children: [_jsx("span", { className: "k-price-range__edge", children: which === 0 ? from : to }), _jsx("input", { className: "k-price-range__input", inputMode: "numeric", dir: "ltr", autoComplete: "off", value: text[which], disabled: disabled, "aria-label": `${which === 0 ? from : to}${typeof label === "string" ? ` ${label}` : ""}`, onChange: (e) => live(which, e.target.value), onBlur: () => commit(which), onKeyDown: (e) => { if (e.key === "Enter") {
39
+ e.preventDefault();
40
+ commit(which);
41
+ } } }), _jsx("span", { className: "k-price-range__unit", children: u })] }));
42
+ return (_jsxs("div", { className: cx("k-price-range", className), role: "group", "aria-labelledby": label ? `${id}-l` : undefined, "aria-label": label ? undefined : M.priceRange.range, children: [label && _jsx("span", { className: "k-label k-price-range__label", id: `${id}-l`, children: label }), _jsxs("div", { className: "k-price-range__fields", children: [field(0), field(1)] }), _jsx(Slider, { value: [lo, hi], onChange: (v) => set(v), min: min, max: max, step: step, showValue: false, disabled: disabled, name: name, format: (n) => `${fmt(n)} ${typeof u === "string" ? u : ""}`.trim(), labels: { from, to }, className: "k-price-range__slider" }), _jsxs("div", { className: "k-price-range__ends", "aria-hidden": "true", children: [_jsx("span", { children: minLabel }), _jsx("span", { children: maxLabel })] })] }));
43
+ }
@@ -0,0 +1,29 @@
1
+ import { type ReactNode } from "react";
2
+ export interface SearchSuggestProps {
3
+ value?: string;
4
+ defaultValue?: string;
5
+ onChange?: (query: string) => void;
6
+ /** با Enter، انتخاب پیشنهاد یا زدن یک جستجوی اخیر/پرطرفدار */
7
+ onSearch?: (query: string) => void;
8
+ /** جستجوهای اخیر (کنترل‌شده)؛ یا به‌جایش storageKey بدهید تا خودکار در مرورگر ذخیره شوند */
9
+ recent?: string[];
10
+ onClearRecent?: () => void;
11
+ /** کلید localStorage برای ذخیرهٔ خودکار جستجوهای اخیر (حداکثر ۸ مورد) */
12
+ storageKey?: string;
13
+ /** جستجوهای پرطرفدار، با آیکون روند */
14
+ popular?: string[];
15
+ /** پیشنهادها هنگام تایپ؛ آرایه (خودکار فیلتر می‌شود) یا تابعی که برای هر عبارت فهرست می‌دهد */
16
+ suggestions?: string[] | ((query: string) => string[]);
17
+ placeholder?: string;
18
+ /** برچسب برای صفحه‌خوان @default «جستجو» */
19
+ label?: string;
20
+ name?: string;
21
+ className?: string;
22
+ labels?: {
23
+ recent?: ReactNode;
24
+ popular?: ReactNode;
25
+ clear?: ReactNode;
26
+ };
27
+ }
28
+ /** جعبهٔ جستجو با جستجوهای اخیر و پرطرفدار و پیشنهاد هنگام تایپ (الگوی فروشگاه‌های اینترنتی) */
29
+ export declare function SearchSuggest({ value, defaultValue, onChange, onSearch, recent, onClearRecent, storageKey, popular, suggestions, placeholder, label, name, className, labels, }: SearchSuggestProps): import("react").JSX.Element;
@@ -0,0 +1,144 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
+ import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
4
+ import { cx } from "./cx.js";
5
+ import { useKashi } from "./KashiProvider.js";
6
+ import { useIsomorphicLayoutEffect } from "./utils.js";
7
+ const norm = (s) => s.replace(/[يى]/g, "ی").replace(/ك/g, "ک").replace(/[‌\s]+/g, " ").trim().toLowerCase();
8
+ const SearchIcon = () => _jsxs("svg", { viewBox: "0 0 20 20", width: "20", height: "20", fill: "none", stroke: "currentColor", strokeWidth: "1.6", strokeLinecap: "round", "aria-hidden": "true", children: [_jsx("circle", { cx: "9.1", cy: "9.1", r: "6.2" }), _jsx("path", { d: "m14 14 3.3 3.3" })] });
9
+ const TrendIcon = () => _jsx("svg", { viewBox: "0 0 20 20", width: "16", height: "16", fill: "none", stroke: "currentColor", strokeWidth: "1.6", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: _jsx("path", { d: "m2.75 13.5 4.6-4.6 3.2 3.2 6.2-6.2M12.75 5.9h4v4" }) });
10
+ const HistoryIcon = () => _jsx("svg", { viewBox: "0 0 20 20", width: "16", height: "16", fill: "none", stroke: "currentColor", strokeWidth: "1.6", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: _jsx("path", { d: "M3.3 10a6.7 6.7 0 1 0 1.9-4.7M3.2 2.9v2.6h2.6M10 6.6V10l2.3 1.5" }) });
11
+ /** جعبهٔ جستجو با جستجوهای اخیر و پرطرفدار و پیشنهاد هنگام تایپ (الگوی فروشگاه‌های اینترنتی) */
12
+ export function SearchSuggest({ value, defaultValue, onChange, onSearch, recent, onClearRecent, storageKey, popular = [], suggestions, placeholder, label, name, className, labels = {}, }) {
13
+ const { messages: M } = useKashi();
14
+ const id = useId();
15
+ const listId = `${id}-panel`;
16
+ const [inner, setInner] = useState(defaultValue ?? "");
17
+ const q = value ?? inner;
18
+ const setQ = (s) => { if (value === undefined)
19
+ setInner(s); onChange?.(s); };
20
+ // جستجوهای اخیر: کنترل‌شده با recent، یا ذخیرهٔ خودکار با storageKey
21
+ const [stored, setStored] = useState([]);
22
+ useEffect(() => {
23
+ if (!storageKey)
24
+ return;
25
+ try {
26
+ setStored(JSON.parse(localStorage.getItem(storageKey) ?? "[]"));
27
+ }
28
+ catch { /* حالت خصوصی */ }
29
+ }, [storageKey]);
30
+ const history = recent ?? stored;
31
+ const remember = (s) => {
32
+ if (!storageKey || recent)
33
+ return;
34
+ const next = [s, ...stored.filter((x) => norm(x) !== norm(s))].slice(0, 8);
35
+ setStored(next);
36
+ try {
37
+ localStorage.setItem(storageKey, JSON.stringify(next));
38
+ }
39
+ catch { /* حالت خصوصی */ }
40
+ };
41
+ const clearHistory = () => {
42
+ if (storageKey && !recent) {
43
+ setStored([]);
44
+ try {
45
+ localStorage.removeItem(storageKey);
46
+ }
47
+ catch { /* */ }
48
+ }
49
+ onClearRecent?.();
50
+ };
51
+ const list = useMemo(() => {
52
+ if (!q.trim() || !suggestions)
53
+ return [];
54
+ if (typeof suggestions === "function")
55
+ return suggestions(q).slice(0, 8);
56
+ const n = norm(q);
57
+ return suggestions.filter((s) => norm(s).includes(n)).slice(0, 8);
58
+ }, [q, suggestions]);
59
+ const [open, setOpen] = useState(false);
60
+ const [active, setActive] = useState(-1);
61
+ const inputRef = useRef(null);
62
+ const panelRef = useRef(null);
63
+ const boxRef = useRef(null);
64
+ const showList = list.length > 0;
65
+ const showIdle = !q.trim() && (history.length > 0 || popular.length > 0);
66
+ const visible = open && (showList || showIdle);
67
+ const submit = (s) => {
68
+ const t = s.trim();
69
+ if (!t)
70
+ return;
71
+ setQ(t);
72
+ remember(t);
73
+ onSearch?.(t);
74
+ setOpen(false);
75
+ setActive(-1);
76
+ };
77
+ // پنل با Popover API در لایهٔ بالا باز می‌شود تا ظرف‌های overflow: hidden آن را نبُرند
78
+ const [pos, setPos] = useState(null);
79
+ const place = useCallback(() => {
80
+ const r = boxRef.current?.getBoundingClientRect();
81
+ if (r)
82
+ setPos({ top: r.bottom + 8, left: r.left, width: r.width });
83
+ }, []);
84
+ useIsomorphicLayoutEffect(() => {
85
+ const el = panelRef.current;
86
+ if (!visible) {
87
+ if (el?.matches?.(":popover-open"))
88
+ el.hidePopover?.();
89
+ return;
90
+ }
91
+ if (el?.showPopover && !el.matches(":popover-open"))
92
+ el.showPopover();
93
+ place();
94
+ addEventListener("resize", place);
95
+ addEventListener("scroll", place, true);
96
+ return () => { removeEventListener("resize", place); removeEventListener("scroll", place, true); };
97
+ }, [visible, place]);
98
+ useEffect(() => {
99
+ if (!open)
100
+ return;
101
+ const onDown = (e) => {
102
+ const t = e.target;
103
+ if (!panelRef.current?.contains(t) && !boxRef.current?.contains(t))
104
+ setOpen(false);
105
+ };
106
+ document.addEventListener("pointerdown", onDown);
107
+ return () => document.removeEventListener("pointerdown", onDown);
108
+ }, [open]);
109
+ useEffect(() => setActive(-1), [q]);
110
+ const onKeyDown = (e) => {
111
+ if (e.key === "Escape") {
112
+ if (open) {
113
+ e.preventDefault();
114
+ setOpen(false);
115
+ }
116
+ else if (q)
117
+ setQ("");
118
+ return;
119
+ }
120
+ if (!showList)
121
+ return;
122
+ if (e.key === "ArrowDown") {
123
+ e.preventDefault();
124
+ setOpen(true);
125
+ setActive((a) => (a + 1) % list.length);
126
+ }
127
+ else if (e.key === "ArrowUp") {
128
+ e.preventDefault();
129
+ setActive((a) => (a <= 0 ? list.length - 1 : a - 1));
130
+ }
131
+ };
132
+ const onSubmit = (e) => { e.preventDefault(); submit(active >= 0 && list[active] ? list[active] : q); };
133
+ const chip = (s, kind) => (_jsx("li", { children: _jsxs("button", { type: "button", className: "k-search-suggest__chip", onMouseDown: (e) => e.preventDefault(), onClick: () => submit(s), children: [kind === "popular" ? _jsx(TrendIcon, {}) : _jsx(HistoryIcon, {}), s] }) }, `${kind}-${s}`));
134
+ const highlight = (s) => {
135
+ const i = norm(s).indexOf(norm(q));
136
+ if (i < 0 || s.length !== norm(s).length)
137
+ return s;
138
+ return _jsxs(_Fragment, { children: [s.slice(0, i), _jsx("mark", { children: s.slice(i, i + q.trim().length) }), s.slice(i + q.trim().length)] });
139
+ };
140
+ return (_jsxs("form", { role: "search", className: cx("k-search-suggest", className), onSubmit: onSubmit, "data-open": visible || undefined, children: [_jsxs("div", { className: "k-search-suggest__box", ref: boxRef, children: [_jsx(SearchIcon, {}), _jsx("input", { ref: inputRef, type: "search", name: name, className: "k-search-suggest__input", value: q, placeholder: placeholder, "aria-label": label ?? M.searchSuggest.label, role: "combobox", "aria-autocomplete": "list", "aria-expanded": visible, "aria-controls": listId, "aria-activedescendant": visible && showList && active >= 0 ? `${listId}-${active}` : undefined, autoComplete: "off", enterKeyHint: "search", onFocus: () => setOpen(true), onChange: (e) => { setQ(e.target.value); setOpen(true); }, onKeyDown: onKeyDown })] }), _jsx("div", { id: listId, ref: panelRef, className: "k-search-suggest__panel", hidden: !visible, ...{ popover: "manual" }, style: pos ? { position: "fixed", inset: "auto", margin: 0, top: pos.top, left: pos.left, width: pos.width } : undefined, onKeyDown: (e) => { if (e.key === "Escape") {
141
+ setOpen(false);
142
+ inputRef.current?.focus();
143
+ } }, children: showList ? (_jsx("ul", { role: "listbox", "aria-label": M.searchSuggest.suggestions, className: "k-search-suggest__list", children: list.map((s, i) => (_jsxs("li", { id: `${listId}-${i}`, role: "option", "aria-selected": i === active, className: "k-option", "data-active": i === active || undefined, onMouseDown: (e) => e.preventDefault(), onPointerMove: () => setActive(i), onClick: () => submit(s), children: [_jsx(SearchIcon, {}), _jsx("span", { className: "k-option__label", children: highlight(s) })] }, s))) })) : (_jsxs(_Fragment, { children: [history.length > 0 && (_jsxs("section", { className: "k-search-suggest__section", children: [_jsxs("div", { className: "k-search-suggest__head", children: [_jsx("b", { children: labels.recent ?? M.searchSuggest.recent }), _jsx("button", { type: "button", className: "k-btn k-btn--link k-btn--sm", onMouseDown: (e) => e.preventDefault(), onClick: clearHistory, children: labels.clear ?? M.searchSuggest.clear })] }), _jsx("ul", { className: "k-search-suggest__chips", children: history.map((s) => chip(s, "recent")) })] })), popular.length > 0 && (_jsxs("section", { className: "k-search-suggest__section", children: [_jsx("div", { className: "k-search-suggest__head", children: _jsx("b", { children: labels.popular ?? M.searchSuggest.popular }) }), _jsx("ul", { className: "k-search-suggest__chips", children: popular.map((s) => chip(s, "popular")) })] }))] })) })] }));
144
+ }
@@ -1,15 +1,32 @@
1
1
  "use client";
2
2
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
- import { useId, useState } from "react";
3
+ import { useId, useRef, useState } from "react";
4
4
  import { cx } from "./cx.js";
5
+ import { useIsomorphicLayoutEffect } from "./utils.js";
5
6
  /** انتخاب یکی از چند گزینهٔ کوتاه، مثل «فهرست / جدول / کارت»؛ روی رادیوی بومی با پیمایش ↑↓←→ */
6
7
  export function SegmentedControl({ options, value, defaultValue, onChange, name, size = "md", block, disabled, className, "aria-label": ariaLabel, "aria-labelledby": labelledBy, }) {
7
8
  const autoName = useId();
8
9
  const [inner, setInner] = useState(defaultValue ?? options.find((o) => !o.disabled)?.value);
9
10
  const current = value ?? inner;
10
- return (_jsx("div", { role: "radiogroup", "aria-label": ariaLabel, "aria-labelledby": labelledBy, className: cx("k-segmented", size === "sm" && "k-segmented--sm", block && "k-segmented--block", className), children: options.map((o) => (_jsxs("label", { className: "k-segmented__item", children: [_jsx("input", { type: "radio", className: "k-sr-only", name: name ?? autoName, value: o.value, checked: current === o.value, disabled: disabled || o.disabled, "aria-label": o["aria-label"], onChange: () => {
11
- if (value === undefined)
12
- setInner(o.value);
13
- onChange?.(o.value);
14
- } }), o.icon, o.label] }, o.value))) }));
11
+ // ریزتعامل: دستگیرهٔ انتخاب با تغییر گزینه می‌لغزد؛ تا اندازه‌گیری نشده، سبک ایستای CSS نمایش داده می‌شود
12
+ const ref = useRef(null);
13
+ const [box, setBox] = useState(null);
14
+ useIsomorphicLayoutEffect(() => {
15
+ const el = ref.current;
16
+ if (!el)
17
+ return;
18
+ const measure = () => {
19
+ const item = el.querySelector(".k-segmented__item:has(:checked)");
20
+ setBox(item ? { x: item.offsetLeft, w: item.offsetWidth } : null);
21
+ };
22
+ measure();
23
+ const ro = new ResizeObserver(measure);
24
+ ro.observe(el);
25
+ return () => ro.disconnect();
26
+ }, [current]);
27
+ return (_jsxs("div", { ref: ref, role: "radiogroup", "aria-label": ariaLabel, "aria-labelledby": labelledBy, className: cx("k-segmented", size === "sm" && "k-segmented--sm", block && "k-segmented--block", className), "data-indicator": box ? "" : undefined, style: box ? { "--_ix": `${box.x}px`, "--_iw": `${box.w}px` } : undefined, children: [box && _jsx("span", { className: "k-segmented__indicator", "aria-hidden": "true" }), options.map((o) => (_jsxs("label", { className: "k-segmented__item", children: [_jsx("input", { type: "radio", className: "k-sr-only", name: name ?? autoName, value: o.value, checked: current === o.value, disabled: disabled || o.disabled, "aria-label": o["aria-label"], onChange: () => {
28
+ if (value === undefined)
29
+ setInner(o.value);
30
+ onChange?.(o.value);
31
+ } }), o.icon, o.label] }, o.value)))] }));
15
32
  }
package/dist/Select.d.ts CHANGED
@@ -10,11 +10,17 @@ export interface SelectProps extends Omit<SelectHTMLAttributes<HTMLSelectElement
10
10
  error?: ReactNode;
11
11
  /** گزینهٔ خالی اول، مثل «انتخاب کنید» */
12
12
  placeholder?: string;
13
- /** گزینه‌ها؛ یا به‌جای آن <option> را به‌عنوان children بدهید */
13
+ /** گزینه‌ها؛ یا به‌جای آن <option> و <optgroup> را به‌عنوان children بدهید */
14
14
  options?: SelectOption[];
15
15
  /** @default "md" */
16
16
  size?: "sm" | "md" | "lg";
17
17
  fieldClassName?: string;
18
+ /** فهرست بومی مرورگر به‌جای فهرست کاشی؛ برای فهرست‌های خیلی بلند یا وقتی انتخاب‌گر سیستم گوشی را می‌خواهید @default false */
19
+ native?: boolean;
18
20
  }
19
- /** فهرست انتخابی روی <select> بومی: در گوشی انتخاب‌گر سیستم باز می‌شود و صفحه‌خوان کامل پشتیبانی می‌کند */
21
+ /**
22
+ * انتخاب از فهرست. نسخهٔ ۲: فهرست با ظاهر کاشی، صفحه‌کلید کامل (فلش‌ها، Home/End، Enter، Escape و تایپ حرف اول)
23
+ * و یک <select> بومیِ پنهان زیرش، تا فرم، name، required، onChange و ref مثل قبل کار کنند.
24
+ * برای انتخاب‌گر سیستم، native بدهید.
25
+ */
20
26
  export declare const Select: import("react").ForwardRefExoticComponent<SelectProps & import("react").RefAttributes<HTMLSelectElement>>;
package/dist/Select.js CHANGED
@@ -1,12 +1,216 @@
1
1
  "use client";
2
2
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
- import { forwardRef, useId } from "react";
3
+ import { Children, forwardRef, isValidElement, useCallback, useEffect, useId, useImperativeHandle, useMemo, useRef, useState, } from "react";
4
4
  import { cx } from "./cx.js";
5
5
  import { Field, describedBy } from "./Field.js";
6
- /** فهرست انتخابی روی <select> بومی: در گوشی انتخاب‌گر سیستم باز می‌شود و صفحه‌خوان کامل پشتیبانی می‌کند */
7
- export const Select = forwardRef(function Select({ label, hint, error, placeholder, options, size = "md", id, required, className, fieldClassName, children, "aria-describedby": extra, ...rest }, ref) {
6
+ import { useIsomorphicLayoutEffect } from "./utils.js";
7
+ const textOf = (node) => typeof node === "string" || typeof node === "number" ? String(node)
8
+ : Array.isArray(node) ? node.map(textOf).join("")
9
+ : isValidElement(node) ? textOf(node.props.children) : "";
10
+ const norm = (s) => s.replace(/[يى]/g, "ی").replace(/ك/g, "ک").replace(/‌/g, " ").toLowerCase();
11
+ /** گزینه‌ها از options یا از <option>/<optgroup> فرزند */
12
+ function collect(options, children) {
13
+ const out = (options ?? []).map((o) => ({ kind: "option", value: o.value, label: o.label, text: textOf(o.label), disabled: o.disabled }));
14
+ const walk = (nodes) => Children.forEach(nodes, (child) => {
15
+ if (!isValidElement(child))
16
+ return;
17
+ const el = child;
18
+ if (el.type === "option")
19
+ out.push({ kind: "option", value: String(el.props.value ?? textOf(el.props.children)), label: el.props.children, text: textOf(el.props.children), disabled: el.props.disabled });
20
+ else if (el.type === "optgroup") {
21
+ out.push({ kind: "group", label: el.props.label });
22
+ walk(el.props.children);
23
+ }
24
+ else
25
+ walk(el.props.children);
26
+ });
27
+ walk(children);
28
+ return out;
29
+ }
30
+ const Chevron = () => (_jsx("svg", { className: "k-select__chevron", viewBox: "0 0 20 20", width: "18", height: "18", fill: "none", stroke: "currentColor", strokeWidth: "1.7", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: _jsx("path", { d: "m6 8 4 4 4-4" }) }));
31
+ const Check = () => (_jsx("svg", { className: "k-option__check", viewBox: "0 0 20 20", width: "18", height: "18", fill: "none", stroke: "currentColor", strokeWidth: "1.8", strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: _jsx("path", { d: "m4.5 10.5 3.5 3.5 7.5-8" }) }));
32
+ /**
33
+ * انتخاب از فهرست. نسخهٔ ۲: فهرست با ظاهر کاشی، صفحه‌کلید کامل (فلش‌ها، Home/End، Enter، Escape و تایپ حرف اول)
34
+ * و یک <select> بومیِ پنهان زیرش، تا فرم، name، required، onChange و ref مثل قبل کار کنند.
35
+ * برای انتخاب‌گر سیستم، native بدهید.
36
+ */
37
+ export const Select = forwardRef(function Select({ label, hint, error, placeholder, options, size = "md", id, required, className, fieldClassName, children, native = false, "aria-describedby": extra, ...rest }, ref) {
8
38
  const autoId = useId();
9
39
  const selectId = id ?? autoId;
10
40
  const placeholderSelected = placeholder !== undefined && rest.value === undefined && rest.defaultValue === undefined;
11
- return (_jsx(Field, { id: selectId, label: label, hint: hint, error: error, required: required, className: fieldClassName, children: _jsx("div", { className: cx("k-select", size !== "md" && `k-select--${size}`, className), children: _jsxs("select", { ref: ref, id: selectId, className: "k-select__control", required: required, "aria-invalid": error ? true : undefined, "aria-describedby": describedBy(selectId, hint, error, extra), defaultValue: placeholderSelected ? "" : undefined, ...rest, children: [placeholder !== undefined && _jsx("option", { value: "", disabled: true, children: placeholder }), options?.map((o) => (_jsx("option", { value: o.value, disabled: o.disabled, children: o.label }, o.value))), children] }) }) }));
41
+ if (native) {
42
+ return (_jsx(Field, { id: selectId, label: label, hint: hint, error: error, required: required, className: fieldClassName, children: _jsx("div", { className: cx("k-select", size !== "md" && `k-select--${size}`, className), children: _jsxs("select", { ref: ref, id: selectId, className: "k-select__control", required: required, "aria-invalid": error ? true : undefined, "aria-describedby": describedBy(selectId, hint, error, extra), defaultValue: placeholderSelected ? "" : undefined, ...rest, children: [placeholder !== undefined && _jsx("option", { value: "", disabled: true, children: placeholder }), options?.map((o) => _jsx("option", { value: o.value, disabled: o.disabled, children: o.label }, o.value)), children] }) }) }));
43
+ }
44
+ return _jsx(CustomSelect, { selectId, label, hint, error, placeholder, options, size, required, className, fieldClassName, children, extra, placeholderSelected, rest, forwardedRef: ref });
12
45
  });
46
+ function CustomSelect({ selectId, label, hint, error, placeholder, options, size, required, className, fieldClassName, children, extra, placeholderSelected, rest, forwardedRef, }) {
47
+ const { value, defaultValue, onChange, disabled, name, form, autoComplete, onBlur, onFocus, ...other } = rest;
48
+ const items = useMemo(() => collect(options, children), [options, children]);
49
+ const opts = items.filter((i) => i.kind === "option");
50
+ const nativeRef = useRef(null);
51
+ useImperativeHandle(forwardedRef, () => nativeRef.current);
52
+ const triggerRef = useRef(null);
53
+ const listRef = useRef(null);
54
+ const listId = `${selectId}-list`;
55
+ const controlled = value !== undefined;
56
+ const [inner, setInner] = useState(() => String(defaultValue ?? (placeholderSelected ? "" : opts.find((o) => !o.disabled)?.value ?? "")));
57
+ const current = controlled ? String(value ?? "") : inner;
58
+ const selected = opts.find((o) => o.value === current);
59
+ const [open, setOpen] = useState(false);
60
+ const [active, setActive] = useState(-1);
61
+ const [up, setUp] = useState(false);
62
+ const typed = useRef({ text: "", at: 0 });
63
+ // انتخاب: مقدار select پنهان عوض و رویداد change واقعی فرستاده می‌شود؛ onChange همان رویداد بومی را می‌گیرد
64
+ const choose = useCallback((v) => {
65
+ const el = nativeRef.current;
66
+ if (!controlled)
67
+ setInner(v);
68
+ if (el && el.value !== v) {
69
+ Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, "value").set.call(el, v);
70
+ el.dispatchEvent(new Event("change", { bubbles: true }));
71
+ }
72
+ }, [controlled]);
73
+ const openList = (to) => {
74
+ if (disabled)
75
+ return;
76
+ const idx = to ?? Math.max(0, opts.findIndex((o) => o.value === current));
77
+ setActive(idx);
78
+ setOpen(true);
79
+ };
80
+ const close = (focus = true) => { setOpen(false); if (focus)
81
+ triggerRef.current?.focus(); };
82
+ // فهرست با Popover API در لایهٔ بالای صفحه باز می‌شود، پس داخل ظرف‌های overflow: hidden یا transform‌دار
83
+ // (کارت، دیالوگ، جدول) بریده نمی‌شود و تم و جهت همان بخش را دارد. جایش نسبت به فیلد حساب می‌شود؛
84
+ // اگر پایین جا نیست، بالای فیلد باز می‌شود
85
+ const [pos, setPos] = useState(null);
86
+ const place = useCallback(() => {
87
+ const t = triggerRef.current;
88
+ if (!t)
89
+ return;
90
+ const r = t.getBoundingClientRect();
91
+ const need = Math.min(288, (listRef.current?.scrollHeight ?? 0) + 8);
92
+ const below = innerHeight - r.bottom;
93
+ const flip = below < need && r.top > below;
94
+ setUp(flip);
95
+ setPos(flip ? { bottom: innerHeight - r.top + 6, left: r.left, width: r.width } : { top: r.bottom + 6, left: r.left, width: r.width });
96
+ }, []);
97
+ useIsomorphicLayoutEffect(() => {
98
+ const el = listRef.current;
99
+ if (!open) {
100
+ if (el?.matches?.(":popover-open"))
101
+ el.hidePopover?.();
102
+ return;
103
+ }
104
+ if (el?.showPopover && !el.matches(":popover-open"))
105
+ el.showPopover();
106
+ place();
107
+ addEventListener("resize", place);
108
+ addEventListener("scroll", place, true);
109
+ return () => { removeEventListener("resize", place); removeEventListener("scroll", place, true); };
110
+ }, [open, place]);
111
+ useEffect(() => {
112
+ if (!open)
113
+ return;
114
+ const onDown = (e) => {
115
+ const t = e.target;
116
+ if (!listRef.current?.contains(t) && !triggerRef.current?.contains(t))
117
+ setOpen(false);
118
+ };
119
+ document.addEventListener("pointerdown", onDown);
120
+ return () => document.removeEventListener("pointerdown", onDown);
121
+ }, [open]);
122
+ useEffect(() => {
123
+ if (!open || active < 0)
124
+ return;
125
+ listRef.current?.querySelector(`[data-index="${active}"]`)?.scrollIntoView({ block: "nearest" });
126
+ }, [open, active]);
127
+ const step = (from, dir) => {
128
+ for (let i = from + dir; i >= 0 && i < opts.length; i += dir)
129
+ if (!opts[i].disabled)
130
+ return i;
131
+ return from;
132
+ };
133
+ const first = () => step(-1, 1), last = () => step(opts.length, -1);
134
+ const typeahead = (key) => {
135
+ const now = Date.now();
136
+ typed.current.text = now - typed.current.at > 700 ? key : typed.current.text + key;
137
+ typed.current.at = now;
138
+ const q = norm(typed.current.text);
139
+ const start = open ? active : opts.findIndex((o) => o.value === current);
140
+ const order = [...opts.keys()].map((k) => (k + start + 1) % opts.length);
141
+ const hit = order.find((i) => !opts[i].disabled && norm(opts[i].text).startsWith(q));
142
+ if (hit === undefined)
143
+ return;
144
+ if (open)
145
+ setActive(hit);
146
+ else
147
+ choose(opts[hit].value);
148
+ };
149
+ const onKeyDown = (e) => {
150
+ if (disabled)
151
+ return;
152
+ const k = e.key;
153
+ if (!open) {
154
+ if (k === "ArrowDown" || k === "ArrowUp" || k === "Enter" || k === " ") {
155
+ e.preventDefault();
156
+ openList(k === "ArrowUp" ? undefined : undefined);
157
+ return;
158
+ }
159
+ if (k === "Home") {
160
+ e.preventDefault();
161
+ openList(first());
162
+ return;
163
+ }
164
+ if (k === "End") {
165
+ e.preventDefault();
166
+ openList(last());
167
+ return;
168
+ }
169
+ if (k.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey)
170
+ typeahead(k);
171
+ return;
172
+ }
173
+ if (k === "ArrowDown") {
174
+ e.preventDefault();
175
+ setActive((a) => step(a, 1));
176
+ }
177
+ else if (k === "ArrowUp") {
178
+ e.preventDefault();
179
+ setActive((a) => step(a, -1));
180
+ }
181
+ else if (k === "Home" || k === "PageUp") {
182
+ e.preventDefault();
183
+ setActive(first());
184
+ }
185
+ else if (k === "End" || k === "PageDown") {
186
+ e.preventDefault();
187
+ setActive(last());
188
+ }
189
+ else if (k === "Enter" || k === " ") {
190
+ e.preventDefault();
191
+ if (opts[active] && !opts[active].disabled)
192
+ choose(opts[active].value);
193
+ close();
194
+ }
195
+ else if (k === "Escape") {
196
+ e.preventDefault();
197
+ close();
198
+ }
199
+ else if (k === "Tab")
200
+ setOpen(false);
201
+ else if (k.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey)
202
+ typeahead(k);
203
+ };
204
+ let index = -1;
205
+ return (_jsx(Field, { id: selectId, label: label, hint: hint, error: error, required: required, className: fieldClassName, children: _jsxs("div", { className: cx("k-select", "k-select--custom", size !== "md" && `k-select--${size}`, className), "data-open": open || undefined, children: [_jsxs("button", { ref: triggerRef, id: selectId, type: "button", role: "combobox", className: "k-select__control", "aria-haspopup": "listbox", "aria-expanded": open, "aria-controls": listId, "aria-activedescendant": open && active >= 0 ? `${listId}-${active}` : undefined, "aria-invalid": error ? true : undefined, "aria-required": required || undefined, "aria-describedby": describedBy(selectId, hint, error, extra), disabled: disabled, onClick: () => (open ? close(false) : openList()), onKeyDown: onKeyDown, onBlur: (e) => { if (!listRef.current?.contains(e.relatedTarget))
206
+ setOpen(false); }, ...other, children: [_jsx("span", { className: cx("k-select__value", !selected && "k-select__value--placeholder"), children: selected ? selected.label : placeholder ?? " " }), _jsx(Chevron, {})] }), _jsx("ul", { id: listId, ref: listRef, role: "listbox", "aria-labelledby": selectId, className: cx("k-listbox", "k-select__list", up && "k-select__list--up"), hidden: !open, tabIndex: -1, ...{ popover: "manual" }, style: pos ? { position: "fixed", insetBlock: "auto", top: pos.top, bottom: pos.bottom, left: pos.left, width: pos.width, right: "auto" } : undefined, children: items.map((it, i) => {
207
+ if (it.kind === "group")
208
+ return _jsx("li", { role: "presentation", className: "k-listbox__group", children: it.label }, `g${i}`);
209
+ index += 1;
210
+ const n = index;
211
+ const isSel = it.value === current;
212
+ return (_jsxs("li", { id: `${listId}-${n}`, "data-index": n, role: "option", className: "k-option", "aria-selected": isSel, "aria-disabled": it.disabled || undefined, "data-active": n === active || undefined, onPointerMove: () => !it.disabled && setActive(n), onMouseDown: (e) => e.preventDefault(), onClick: () => { if (it.disabled)
213
+ return; choose(it.value); close(); }, children: [_jsx("span", { className: "k-option__label", children: it.label }), isSel && _jsx(Check, {})] }, it.value));
214
+ }) }), _jsxs("select", { ref: nativeRef, className: "k-select__native", tabIndex: -1, "aria-hidden": "true", name: name, form: form, autoComplete: autoComplete, required: required, disabled: disabled, value: current, onChange: (e) => { if (!controlled)
215
+ setInner(e.target.value); onChange?.(e); }, onFocus: (e) => { triggerRef.current?.focus(); onFocus?.(e); }, onBlur: onBlur, onInvalid: () => triggerRef.current?.focus(), children: [_jsx("option", { value: "" }), opts.map((o) => _jsx("option", { value: o.value, disabled: o.disabled, children: o.text }, o.value))] })] }) }));
216
+ }
@@ -0,0 +1,26 @@
1
+ import { type ReactNode } from "react";
2
+ export interface SwatchOption {
3
+ value: string;
4
+ label: ReactNode;
5
+ /** رنگ نمونه؛ هر مقدار CSS برای background: رنگ، گرادیان یا تصویر */
6
+ color: string;
7
+ disabled?: boolean;
8
+ }
9
+ export interface SwatchGroupProps {
10
+ options: SwatchOption[];
11
+ /** مقدارهای انتخاب‌شده */
12
+ value?: string[];
13
+ defaultValue?: string[];
14
+ onChange?: (value: string[]) => void;
15
+ /** فقط یک انتخاب (مثل رنگ کالا در صفحهٔ خرید)؛ پیش‌فرض چندانتخابی برای فیلتر */
16
+ single?: boolean;
17
+ /** عنوان گروه، مثل «رنگ» */
18
+ label?: ReactNode;
19
+ /** اندازهٔ نمونه‌ها @default "md" */
20
+ size?: "sm" | "md" | "lg";
21
+ /** با name، مقدارهای انتخاب‌شده در فرم ارسال می‌شوند */
22
+ name?: string;
23
+ className?: string;
24
+ }
25
+ /** انتخاب رنگ از میان نمونه‌ها (فیلتر رنگ کالا)؛ روی چک‌باکس یا رادیوی بومی، پس صفحه‌کلید و فرم خودکار کار می‌کنند */
26
+ export declare function SwatchGroup({ options, value, defaultValue, onChange, single, label, size, name, className }: SwatchGroupProps): import("react").JSX.Element;
@@ -0,0 +1,25 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { useId, useState } from "react";
4
+ import { cx } from "./cx.js";
5
+ import { useKashi } from "./KashiProvider.js";
6
+ /** انتخاب رنگ از میان نمونه‌ها (فیلتر رنگ کالا)؛ روی چک‌باکس یا رادیوی بومی، پس صفحه‌کلید و فرم خودکار کار می‌کنند */
7
+ export function SwatchGroup({ options, value, defaultValue, onChange, single = false, label, size = "md", name, className }) {
8
+ const { messages: M } = useKashi();
9
+ const id = useId();
10
+ const [inner, setInner] = useState(defaultValue ?? []);
11
+ const selected = value ?? inner;
12
+ const toggle = (v) => {
13
+ const next = single ? (selected[0] === v ? [] : [v]) : selected.includes(v) ? selected.filter((x) => x !== v) : [...selected, v];
14
+ if (value === undefined)
15
+ setInner(next);
16
+ onChange?.(next);
17
+ };
18
+ return (_jsxs("fieldset", { className: cx("k-swatches", size !== "md" && `k-swatches--${size}`, className), children: [label && _jsx("legend", { className: "k-label k-swatches__legend", children: label }), _jsx("div", { className: "k-swatches__grid", role: single ? "radiogroup" : undefined, children: options.map((o) => {
19
+ const on = selected.includes(o.value);
20
+ return (_jsxs("label", { className: "k-swatch", "data-disabled": o.disabled || undefined, children: [_jsx("input", { type: single ? "radio" : "checkbox", className: "k-sr-only", name: name ?? (single ? id : undefined), value: o.value, checked: on, disabled: o.disabled, onChange: () => toggle(o.value), onClick: (e) => { if (single && on) {
21
+ e.preventDefault();
22
+ toggle(o.value);
23
+ } } }), _jsx("span", { className: "k-swatch__color", style: { "--_c": o.color }, "aria-hidden": "true", children: _jsx("svg", { className: "k-swatch__check", viewBox: "0 0 20 20", fill: "none", stroke: "currentColor", strokeWidth: "2.2", strokeLinecap: "round", strokeLinejoin: "round", children: _jsx("path", { d: "m5 10.5 3.2 3L15 7" }) }) }), _jsxs("span", { className: "k-swatch__label", children: [o.label, on && _jsxs("span", { className: "k-sr-only", children: ["\u060C ", M.swatch.selected] })] })] }, o.value));
24
+ }) })] }));
25
+ }
package/dist/index.d.ts CHANGED
@@ -104,6 +104,12 @@ export { ButtonGroup } from "./ButtonGroup.js";
104
104
  export type { ButtonGroupProps } from "./ButtonGroup.js";
105
105
  export { ChipGroup } from "./ChipGroup.js";
106
106
  export type { ChipOption, ChipGroupProps } from "./ChipGroup.js";
107
+ export { SearchSuggest } from "./SearchSuggest.js";
108
+ export type { SearchSuggestProps } from "./SearchSuggest.js";
109
+ export { PriceRange } from "./PriceRange.js";
110
+ export type { PriceRangeProps } from "./PriceRange.js";
111
+ export { SwatchGroup } from "./SwatchGroup.js";
112
+ export type { SwatchGroupProps, SwatchOption } from "./SwatchGroup.js";
107
113
  export { PasswordStrength, defaultPasswordRules } from "./PasswordStrength.js";
108
114
  export type { PasswordRule, PasswordStrengthProps } from "./PasswordStrength.js";
109
115
  export { Countdown } from "./Countdown.js";
package/dist/index.js CHANGED
@@ -52,6 +52,9 @@ export { PlateInput } from "./PlateInput.js";
52
52
  export { TreeView } from "./TreeView.js";
53
53
  export { ButtonGroup } from "./ButtonGroup.js";
54
54
  export { ChipGroup } from "./ChipGroup.js";
55
+ export { SearchSuggest } from "./SearchSuggest.js";
56
+ export { PriceRange } from "./PriceRange.js";
57
+ export { SwatchGroup } from "./SwatchGroup.js";
55
58
  export { PasswordStrength, defaultPasswordRules } from "./PasswordStrength.js";
56
59
  export { Countdown } from "./Countdown.js";
57
60
  export { MonthPicker } from "./MonthPicker.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kashi-ui/react",
3
- "version": "1.7.0",
3
+ "version": "2.0.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": "^1.7.0",
25
+ "@kashi-ui/css": "^2.0.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": "^1.7.0",
63
- "@kashi-ui/persian": "^1.7.0"
62
+ "@kashi-ui/bank-logos": "^2.0.0",
63
+ "@kashi-ui/persian": "^2.0.0"
64
64
  }
65
65
  }