@kashi-ui/react 2.15.1 → 2.17.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.
@@ -0,0 +1,263 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { useEffect, useId, useRef, useState } from "react";
4
+ import { cx } from "./cx.js";
5
+ import { useKashi } from "./KashiProvider.js";
6
+ const DEFAULT_TOOLS = ["bold", "italic", "underline", "strike", "|", "heading", "quote", "bullet", "ordered", "|", "link", "direction", "|", "undo", "clear"];
7
+ const ALLOWED = new Set(["P", "BR", "B", "STRONG", "I", "EM", "U", "S", "STRIKE", "DEL", "A", "UL", "OL", "LI", "H2", "H3", "BLOCKQUOTE", "DIV", "SPAN", "CODE"]);
8
+ const BLOCKS = "p, li, h2, h3, blockquote, div";
9
+ /** پاک‌سازی HTML: فقط برچسب‌های متنی مجاز، پیوندهای http، https و mailto، و ویژگی dir؛ بقیه حذف می‌شود */
10
+ export function sanitizeRichText(html) {
11
+ if (typeof document === "undefined") {
12
+ // رندر سرور: همان قاعده‌ها با عبارت باقاعده؛ مرورگر دوباره با DOM پاک می‌کند
13
+ return html
14
+ .replace(/<(script|style|iframe|object|embed|template|svg|math|head|title)\b[\s\S]*?<\/\1\s*>/gi, "")
15
+ .replace(/<!--[\s\S]*?-->/g, "")
16
+ .replace(/<\/?([a-z][a-z0-9]*)\b([^>]*)>/gi, (tag, name, attrs) => {
17
+ const t = name.toUpperCase();
18
+ if (!ALLOWED.has(t))
19
+ return "";
20
+ if (tag.startsWith("</"))
21
+ return `</${name.toLowerCase()}>`;
22
+ const keep = [];
23
+ const dir = attrs.match(/\sdir\s*=\s*["']?(rtl|ltr|auto)\b/i);
24
+ if (dir)
25
+ keep.push(`dir="${dir[1].toLowerCase()}"`);
26
+ if (t === "A") {
27
+ const href = attrs.match(/\shref\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i);
28
+ const url = (href?.[1] ?? href?.[2] ?? href?.[3] ?? "").trim();
29
+ if (/^(https?:|mailto:)/i.test(url))
30
+ keep.push(`href="${url.replace(/"/g, "&quot;")}"`, 'rel="noopener noreferrer nofollow"');
31
+ }
32
+ return `<${name.toLowerCase()}${keep.length ? " " + keep.join(" ") : ""}>`;
33
+ });
34
+ }
35
+ const tpl = document.createElement("template");
36
+ tpl.innerHTML = html;
37
+ const walk = (node) => {
38
+ for (const child of Array.from(node.childNodes)) {
39
+ if (child.nodeType === 8) {
40
+ child.remove();
41
+ continue;
42
+ }
43
+ if (child.nodeType !== 1)
44
+ continue;
45
+ const el = child;
46
+ if (!ALLOWED.has(el.tagName)) {
47
+ if (/^(SCRIPT|STYLE|IFRAME|OBJECT|EMBED|TEMPLATE|SVG|MATH|HEAD|TITLE|META|LINK)$/.test(el.tagName))
48
+ el.remove();
49
+ else {
50
+ walk(el);
51
+ el.replaceWith(...Array.from(el.childNodes));
52
+ }
53
+ continue;
54
+ }
55
+ for (const attr of Array.from(el.attributes)) {
56
+ const keep = (attr.name === "dir" && /^(rtl|ltr|auto)$/.test(attr.value)) || (el.tagName === "A" && attr.name === "href" && /^(https?:|mailto:)/i.test(attr.value.trim()));
57
+ if (!keep)
58
+ el.removeAttribute(attr.name);
59
+ }
60
+ if (el.tagName === "A") {
61
+ if (!el.hasAttribute("href")) {
62
+ el.replaceWith(...Array.from(el.childNodes));
63
+ continue;
64
+ }
65
+ el.setAttribute("rel", "noopener noreferrer nofollow");
66
+ }
67
+ walk(el);
68
+ }
69
+ };
70
+ walk(tpl.content);
71
+ return tpl.innerHTML;
72
+ }
73
+ const I = (d) => _jsx("svg", { viewBox: "0 0 20 20", fill: "none", stroke: "currentColor", strokeWidth: 1.8, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: d });
74
+ const ICONS = {
75
+ bold: I(_jsx("path", { d: "M6 4h5a3 3 0 0 1 0 6H6zm0 6h6a3 3 0 0 1 0 6H6z" })),
76
+ italic: I(_jsx("path", { d: "M12 4H8.5M11.5 16H8M11 4 9 16" })),
77
+ underline: I(_jsx("path", { d: "M6 4v5a4 4 0 0 0 8 0V4M5 17h10" })),
78
+ strike: I(_jsx("path", { d: "M4 10h12M13.5 6.5c-.5-1.5-2-2.5-3.7-2.5C7.9 4 6.5 5.1 6.5 6.6c0 3.4 7 2 7 6.3 0 1.7-1.6 3.1-3.6 3.1-1.9 0-3.4-1-3.9-2.6" })),
79
+ heading: I(_jsx("path", { d: "M5 4v12M13 4v12M5 10h8M15.5 16v-5l-1.5 1" })),
80
+ quote: I(_jsx("path", { d: "M8 8H5v3h2.5c0 2-1 3-2.5 3.5M15 8h-3v3h2.5c0 2-1 3-2.5 3.5" })),
81
+ bullet: I(_jsx("path", { d: "M8 5.5h8M8 10h8M8 14.5h8M4.5 5.5h.01M4.5 10h.01M4.5 14.5h.01" })),
82
+ ordered: I(_jsx("path", { d: "M8 5.5h8M8 10h8M8 14.5h8M4 4.5l1-.5v3M4 12.5c0-.6.5-1 1-1s1 .4 1 1c0 .7-2 1.5-2 2.5h2" })),
83
+ link: I(_jsx("path", { d: "M8.5 11.5a3 3 0 0 0 4.2 0l2.6-2.6a3 3 0 0 0-4.2-4.2L10 5.8M11.5 8.5a3 3 0 0 0-4.2 0l-2.6 2.6a3 3 0 0 0 4.2 4.2l1.1-1.1" })),
84
+ undo: I(_jsx("path", { d: "M7 5 4 8l3 3M4 8h8a4 4 0 0 1 0 8H9" })),
85
+ clear: I(_jsx("path", { d: "M5 4h10M10 4l-2.5 12M4 16l12-12" })),
86
+ };
87
+ const DIR_ICON = I(_jsx("path", { d: "M9 4h6M13 4v12M9 4v8a3 3 0 0 1-3-3 3 3 0 0 1 3-3M4 14l2 2 2-2" }));
88
+ /** ویرایشگر متن غنی سبک و فارسی: جهت هر بند جدا، نیم‌فاصله با Shift+Space، چسباندن پاک‌شده و نوار ابزار با کیبورد */
89
+ export function RichTextEditor({ value, defaultValue = "", onChange, label, "aria-label": ariaLabel, placeholder, tools = DEFAULT_TOOLS, minHeight = "8rem", showCount = true, name, hint, error, disabled, className, }) {
90
+ const { messages: M, n } = useKashi();
91
+ const R = M.richText;
92
+ const area = useRef(null);
93
+ const bar = useRef(null);
94
+ const saved = useRef(null);
95
+ const [html, setHtml] = useState(() => sanitizeRichText(value ?? defaultValue));
96
+ // محتوای اولیه یک بار (و در رندر سرور) نوشته می‌شود؛ بعد از آن DOM دست خود کاربر است
97
+ const initial = useRef(html);
98
+ const [text, setText] = useState("");
99
+ const [state, setState] = useState({});
100
+ const [linkOpen, setLinkOpen] = useState(false);
101
+ const [url, setUrl] = useState("https://");
102
+ const [focusTool, setFocusTool] = useState(0);
103
+ const id = useId();
104
+ // مقدار اولیه یا کنترل‌شده در DOM؛ اگر همان چیزی است که کاربر نوشته، دست نمی‌خورد تا مکان‌نما نپرد
105
+ useEffect(() => {
106
+ const el = area.current;
107
+ if (!el)
108
+ return;
109
+ const next = sanitizeRichText(value ?? html);
110
+ if (el.innerHTML !== next)
111
+ el.innerHTML = next;
112
+ setText(el.innerText ?? el.textContent ?? "");
113
+ // eslint-disable-next-line react-hooks/exhaustive-deps
114
+ }, [value]);
115
+ useEffect(() => {
116
+ if (!area.current)
117
+ return;
118
+ try {
119
+ document.execCommand("defaultParagraphSeparator", false, "p");
120
+ }
121
+ catch {
122
+ /* مرورگر پشتیبانی نمی‌کند */
123
+ }
124
+ const update = () => {
125
+ const sel = document.getSelection();
126
+ if (!sel || !area.current?.contains(sel.anchorNode))
127
+ return;
128
+ const block = (sel.anchorNode instanceof Element ? sel.anchorNode : sel.anchorNode?.parentElement)?.closest(BLOCKS);
129
+ const q = (c) => {
130
+ try {
131
+ return document.queryCommandState(c);
132
+ }
133
+ catch {
134
+ return false;
135
+ }
136
+ };
137
+ setState({
138
+ bold: q("bold"), italic: q("italic"), underline: q("underline"), strike: q("strikeThrough"),
139
+ bullet: q("insertUnorderedList"), ordered: q("insertOrderedList"),
140
+ heading: !!block?.closest("h2, h3"), quote: !!block?.closest("blockquote"),
141
+ link: !!(sel.anchorNode instanceof Element ? sel.anchorNode : sel.anchorNode?.parentElement)?.closest("a"),
142
+ ltr: block?.dir === "ltr",
143
+ });
144
+ };
145
+ document.addEventListener("selectionchange", update);
146
+ return () => document.removeEventListener("selectionchange", update);
147
+ }, []);
148
+ const emit = () => {
149
+ const el = area.current;
150
+ if (!el)
151
+ return;
152
+ const out = sanitizeRichText(el.innerHTML === "<p><br></p>" || el.innerHTML === "<br>" ? "" : el.innerHTML);
153
+ const plain = el.innerText ?? el.textContent ?? "";
154
+ setHtml(out);
155
+ setText(plain);
156
+ onChange?.(out, plain.trim());
157
+ };
158
+ const exec = (cmd, arg) => {
159
+ area.current?.focus();
160
+ if (saved.current) {
161
+ const sel = document.getSelection();
162
+ sel?.removeAllRanges();
163
+ sel?.addRange(saved.current);
164
+ saved.current = null;
165
+ }
166
+ document.execCommand(cmd, false, arg);
167
+ emit();
168
+ };
169
+ const currentBlock = () => {
170
+ const sel = document.getSelection();
171
+ const node = sel?.anchorNode;
172
+ return (node instanceof Element ? node : node?.parentElement)?.closest(BLOCKS) ?? null;
173
+ };
174
+ const run = (tool) => {
175
+ switch (tool) {
176
+ case "bold": return exec("bold");
177
+ case "italic": return exec("italic");
178
+ case "underline": return exec("underline");
179
+ case "strike": return exec("strikeThrough");
180
+ case "heading": return exec("formatBlock", state.heading ? "<p>" : "<h2>");
181
+ case "quote": return exec("formatBlock", state.quote ? "<p>" : "<blockquote>");
182
+ case "bullet": return exec("insertUnorderedList");
183
+ case "ordered": return exec("insertOrderedList");
184
+ case "undo": return exec("undo");
185
+ case "clear": return exec("removeFormat");
186
+ case "direction": {
187
+ const b = currentBlock();
188
+ if (b && area.current?.contains(b) && b !== area.current) {
189
+ b.dir = b.dir === "ltr" ? "rtl" : "ltr";
190
+ setState((s) => ({ ...s, ltr: b.dir === "ltr" }));
191
+ emit();
192
+ }
193
+ return;
194
+ }
195
+ case "link": {
196
+ if (state.link)
197
+ return exec("unlink");
198
+ const sel = document.getSelection();
199
+ if (sel && sel.rangeCount && area.current?.contains(sel.anchorNode))
200
+ saved.current = sel.getRangeAt(0).cloneRange();
201
+ setLinkOpen(true);
202
+ return;
203
+ }
204
+ }
205
+ };
206
+ const buttons = tools.filter((t) => t !== "|");
207
+ const onBarKey = (e) => {
208
+ const keys = ["ArrowRight", "ArrowLeft", "Home", "End"];
209
+ if (!keys.includes(e.key))
210
+ return;
211
+ e.preventDefault();
212
+ const rtl = getComputedStyle(e.currentTarget).direction === "rtl";
213
+ const step = e.key === "Home" ? -Infinity : e.key === "End" ? Infinity : (e.key === "ArrowLeft") === rtl ? 1 : -1;
214
+ const next = Math.max(0, Math.min(buttons.length - 1, step === Infinity ? buttons.length - 1 : step === -Infinity ? 0 : focusTool + step));
215
+ setFocusTool(next);
216
+ bar.current?.querySelectorAll(".k-rte__tool")[next]?.focus();
217
+ };
218
+ const label_ = (t) => (t === "direction" ? (state.ltr ? R.rtl : R.ltr) : t === "link" && state.link ? R.unlink : R[t]);
219
+ const words = text.trim() ? text.trim().split(/\s+/).length : 0;
220
+ const empty = !text.trim() && !/<(img|li|blockquote)/.test(html);
221
+ const helpId = `${id}-help`;
222
+ let b = -1;
223
+ return (_jsxs("div", { className: cx("k-rte", className), "data-disabled": disabled ? "" : undefined, "data-invalid": error ? "" : undefined, children: [label && _jsx("label", { className: "k-label k-rte__label", id: `${id}-label`, onClick: () => area.current?.focus(), children: label }), _jsxs("div", { className: "k-rte__box", children: [_jsx("div", { ref: bar, className: "k-rte__bar", role: "toolbar", "aria-label": R.toolbar, "aria-controls": id, onKeyDown: onBarKey, children: tools.map((t, k) => {
224
+ if (t === "|")
225
+ return _jsx("span", { className: "k-rte__sep", "aria-hidden": "true" }, k);
226
+ b++;
227
+ const pressed = t === "direction" ? state.ltr : t === "link" || t === "undo" || t === "clear" ? undefined : !!state[t];
228
+ const idx = b;
229
+ return (_jsx("button", { type: "button", className: "k-rte__tool", tabIndex: idx === focusTool ? 0 : -1, "aria-label": label_(t), title: label_(t), "aria-pressed": pressed, disabled: disabled, onMouseDown: (e) => e.preventDefault(), onClick: () => {
230
+ setFocusTool(idx);
231
+ run(t);
232
+ }, children: t === "direction" ? DIR_ICON : ICONS[t] }, k));
233
+ }) }), linkOpen && (_jsxs("form", { className: "k-rte__link", onSubmit: (e) => {
234
+ e.preventDefault();
235
+ setLinkOpen(false);
236
+ if (/^(https?:\/\/|mailto:)\S+$/i.test(url.trim()))
237
+ exec("createLink", url.trim());
238
+ }, children: [_jsx("input", { className: "k-rte__link-input", type: "url", dir: "ltr", "aria-label": R.linkUrl, value: url, autoFocus: true, onChange: (e) => setUrl(e.target.value), onKeyDown: (e) => {
239
+ if (e.key === "Escape") {
240
+ e.preventDefault();
241
+ setLinkOpen(false);
242
+ area.current?.focus();
243
+ }
244
+ } }), _jsx("button", { type: "submit", className: "k-btn k-btn--primary k-btn--xs", children: R.apply })] })), _jsx("div", { ref: area, id: id, className: "k-rte__area", role: "textbox", "aria-multiline": "true", "aria-label": label ? undefined : ariaLabel ?? R.label, "aria-labelledby": label ? `${id}-label` : undefined, "aria-describedby": helpId, "aria-invalid": error ? true : undefined, "aria-disabled": disabled || undefined, contentEditable: !disabled, suppressContentEditableWarning: true, dangerouslySetInnerHTML: { __html: initial.current }, dir: "rtl", "data-empty": empty ? "" : undefined, "data-placeholder": placeholder ?? R.placeholder, style: { minBlockSize: minHeight }, onInput: emit, onBlur: emit, onKeyDown: (e) => {
245
+ // نیم‌فاصله
246
+ if (e.key === " " && e.shiftKey) {
247
+ e.preventDefault();
248
+ document.execCommand("insertText", false, "‌");
249
+ }
250
+ if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "k") {
251
+ e.preventDefault();
252
+ run("link");
253
+ }
254
+ }, onPaste: (e) => {
255
+ e.preventDefault();
256
+ const rich = e.clipboardData.getData("text/html");
257
+ if (rich)
258
+ document.execCommand("insertHTML", false, sanitizeRichText(rich));
259
+ else
260
+ document.execCommand("insertText", false, e.clipboardData.getData("text/plain"));
261
+ emit();
262
+ } }), showCount && (_jsxs("div", { className: "k-rte__foot", children: [_jsx("span", { children: R.words(n(words)) }), _jsx("span", { "aria-hidden": "true", children: "\u00B7" }), _jsx("span", { children: R.chars(n(text.replace(/\n/g, "").length)) }), _jsx("span", { className: "k-rte__tip", children: R.zwnj })] }))] }), _jsx("div", { id: helpId, className: "k-rte__help", children: error ? _jsx("p", { className: "k-hint k-hint--error", children: error }) : hint ? _jsx("p", { className: "k-hint", children: hint }) : _jsx("span", { className: "k-sr-only", children: R.zwnj }) }), name && _jsx("input", { type: "hidden", name: name, value: html })] }));
263
+ }
@@ -0,0 +1,16 @@
1
+ import { type ReactNode } from "react";
2
+ import { type InputProps } from "./Input.js";
3
+ type Base = Omit<InputProps, "value" | "defaultValue" | "onChange" | "type" | "inputMode">;
4
+ export interface SayadInputProps extends Base {
5
+ /** ارقام لاتین، مثل "1234567890123456" */
6
+ value?: string;
7
+ defaultValue?: string;
8
+ onValueChange?: (value: string, valid: boolean) => void;
9
+ /** @default "fa" */
10
+ digits?: "fa" | "latin";
11
+ /** @default "شناسهٔ صیادی باید ۱۶ رقم باشد." */
12
+ invalidMessage?: ReactNode;
13
+ }
14
+ /** شناسهٔ صیادی چک: ۱۶ رقم در گروه‌های چهارتایی؛ فقط طول بررسی می‌شود چون رقم کنترل آن عمومی نیست */
15
+ export declare const SayadInput: import("react").ForwardRefExoticComponent<SayadInputProps & import("react").RefAttributes<HTMLInputElement>>;
16
+ export {};
@@ -0,0 +1,24 @@
1
+ "use client";
2
+ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { forwardRef, useState } from "react";
4
+ import { formatSayad, isValidSayad } from "@kashi-ui/persian";
5
+ import { Input } from "./Input.js";
6
+ import { useDigitsInput } from "./useDigitsInput.js";
7
+ import { mergeRefs } from "./utils.js";
8
+ import { useKashi } from "./KashiProvider.js";
9
+ /** شناسهٔ صیادی چک: ۱۶ رقم در گروه‌های چهارتایی؛ فقط طول بررسی می‌شود چون رقم کنترل آن عمومی نیست */
10
+ export const SayadInput = forwardRef(function SayadInput({ value, defaultValue, onValueChange, digits, invalidMessage, error, name, onBlur, placeholder, ...rest }, ref) {
11
+ const { messages: M, digits: D } = useKashi();
12
+ digits ?? (digits = D);
13
+ invalidMessage ?? (invalidMessage = M.invalid.sayad);
14
+ const { raw, shown, inputRef, handleChange } = useDigitsInput({ value, defaultValue, maxDigits: 16, format: formatSayad, digits });
15
+ const [touched, setTouched] = useState(false);
16
+ const showInvalid = raw.length > 0 && touched && !isValidSayad(raw);
17
+ return (_jsxs(_Fragment, { children: [_jsx(Input, { ref: mergeRefs(ref, inputRef), type: "text", inputMode: "numeric", autoComplete: "off", dir: "ltr", placeholder: placeholder ?? (digits === "fa" ? "۰۰۰۰ ۰۰۰۰ ۰۰۰۰ ۰۰۰۰" : "0000 0000 0000 0000"), value: shown, onChange: (e) => {
18
+ const next = handleChange(e);
19
+ onValueChange?.(next, isValidSayad(next));
20
+ }, onBlur: (e) => {
21
+ setTouched(true);
22
+ onBlur?.(e);
23
+ }, error: error ?? (showInvalid ? invalidMessage : undefined), ...rest }), name && _jsx("input", { type: "hidden", name: name, value: raw })] }));
24
+ });
@@ -0,0 +1,42 @@
1
+ export interface SchedulerEvent {
2
+ id: string;
3
+ title: string;
4
+ start: Date;
5
+ end: Date;
6
+ /** رنگ رویداد؛ یکی از رنگ‌های نمودار مثل "var(--k-chart-2)" یا هر رنگ CSS @default برند */
7
+ color?: string;
8
+ /** متن کوتاه زیر عنوان، مثل محل یا نام مشتری */
9
+ description?: string;
10
+ }
11
+ export interface SchedulerProps {
12
+ events: SchedulerEvent[];
13
+ /** روزی که نما دور آن است @default امروز */
14
+ date?: Date;
15
+ defaultDate?: Date;
16
+ onDateChange?: (date: Date) => void;
17
+ view?: "week" | "day";
18
+ /** @default "week" */
19
+ defaultView?: "week" | "day";
20
+ onViewChange?: (view: "week" | "day") => void;
21
+ /** ساعت شروع جدول @default 8 */
22
+ startHour?: number;
23
+ /** ساعت پایان جدول @default 20 */
24
+ endHour?: number;
25
+ /** طول هر خانه به دقیقه @default 30 */
26
+ step?: number;
27
+ /** کلیک یا Enter روی خانهٔ خالی؛ برای ساختن رویداد */
28
+ onSlotClick?: (start: Date) => void;
29
+ onEventClick?: (event: SchedulerEvent) => void;
30
+ /** جمعه‌ها و تعطیلات رسمی ثابت رنگ تعطیل می‌گیرند @default true */
31
+ holidays?: boolean;
32
+ /** لحظهٔ «اکنون» برای خط قرمز و امروز @default اکنون */
33
+ now?: Date;
34
+ /** ارتفاع هر ساعت @default "3.5rem" */
35
+ hourHeight?: string;
36
+ className?: string;
37
+ }
38
+ /**
39
+ * برنامهٔ هفتگی و روزانه با تقویم شمسی و شروع هفته از شنبه: رویدادها بر اساس ساعت، رویدادهای هم‌پوشان کنار هم،
40
+ * خط «اکنون»، تعطیلات، و خانه‌های خالی که با کلیک یا کیبورد (کلیدهای جهت و Enter) رویداد تازه می‌سازند.
41
+ */
42
+ export declare function Scheduler({ events, date, defaultDate, onDateChange, view, defaultView, onViewChange, startHour, endHour, step, onSlotClick, onEventClick, holidays, now: nowProp, hourHeight, className, }: SchedulerProps): import("react").JSX.Element;
@@ -0,0 +1,144 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { useEffect, useRef, useState } from "react";
4
+ import { formatJalali, formatTime, getIranHoliday, jalaliWeekday, toJalali } from "@kashi-ui/persian";
5
+ import { cx } from "./cx.js";
6
+ import { useKashi } from "./KashiProvider.js";
7
+ import { SegmentedControl } from "./SegmentedControl.js";
8
+ const day0 = (d) => new Date(d.getFullYear(), d.getMonth(), d.getDate());
9
+ const addDays = (d, n) => new Date(d.getFullYear(), d.getMonth(), d.getDate() + n);
10
+ const same = (a, b) => day0(a).getTime() === day0(b).getTime();
11
+ const mins = (d) => d.getHours() * 60 + d.getMinutes();
12
+ const svg = (d) => _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: d }) });
13
+ /** ستون‌بندی رویدادهای هم‌پوشان یک روز تا کنار هم بنشینند */
14
+ function layout(list) {
15
+ const sorted = [...list].sort((a, b) => a.start.getTime() - b.start.getTime() || b.end.getTime() - a.end.getTime());
16
+ const out = new Map();
17
+ let group = [];
18
+ let cols = [];
19
+ let groupEnd = 0;
20
+ const flush = () => {
21
+ const n = Math.max(1, cols.length);
22
+ for (const e of group)
23
+ out.get(e.id).cols = n;
24
+ group = [];
25
+ cols = [];
26
+ };
27
+ for (const e of sorted) {
28
+ if (group.length && e.start.getTime() >= groupEnd)
29
+ flush();
30
+ let c = cols.findIndex((end) => end <= e.start.getTime());
31
+ if (c < 0) {
32
+ c = cols.length;
33
+ cols.push(0);
34
+ }
35
+ cols[c] = e.end.getTime();
36
+ out.set(e.id, { col: c, cols: 1 });
37
+ group.push(e);
38
+ groupEnd = Math.max(groupEnd, e.end.getTime());
39
+ }
40
+ flush();
41
+ return out;
42
+ }
43
+ /**
44
+ * برنامهٔ هفتگی و روزانه با تقویم شمسی و شروع هفته از شنبه: رویدادها بر اساس ساعت، رویدادهای هم‌پوشان کنار هم،
45
+ * خط «اکنون»، تعطیلات، و خانه‌های خالی که با کلیک یا کیبورد (کلیدهای جهت و Enter) رویداد تازه می‌سازند.
46
+ */
47
+ export function Scheduler({ events, date, defaultDate, onDateChange, view, defaultView = "week", onViewChange, startHour = 8, endHour = 20, step = 30, onSlotClick, onEventClick, holidays = true, now: nowProp, hourHeight = "3.5rem", className, }) {
48
+ const { messages: M, locale, digits, weekdays, weekdaysShort, months, n } = useKashi();
49
+ const S = M.scheduler;
50
+ const [innerDate, setInnerDate] = useState(() => day0(defaultDate ?? new Date()));
51
+ const [innerView, setInnerView] = useState(defaultView);
52
+ const anchor = day0(date ?? innerDate);
53
+ const mode = view ?? innerView;
54
+ const [now, setNow] = useState(() => nowProp ?? new Date());
55
+ useEffect(() => {
56
+ if (nowProp)
57
+ return setNow(nowProp);
58
+ const t = setInterval(() => setNow(new Date()), 60000);
59
+ return () => clearInterval(t);
60
+ }, [nowProp]);
61
+ const start = mode === "week" ? addDays(anchor, -jalaliWeekday(anchor)) : anchor;
62
+ const days = Array.from({ length: mode === "week" ? 7 : 1 }, (_, i) => addDays(start, i));
63
+ const slots = Math.max(1, Math.round(((endHour - startHour) * 60) / step));
64
+ const total = (endHour - startHour) * 60;
65
+ const [focus, setFocus] = useState([0, 0]);
66
+ const grid = useRef(null);
67
+ const setDate = (d) => {
68
+ if (date === undefined)
69
+ setInnerDate(day0(d));
70
+ onDateChange?.(day0(d));
71
+ };
72
+ const setMode = (v) => {
73
+ if (view === undefined)
74
+ setInnerView(v);
75
+ onViewChange?.(v);
76
+ };
77
+ const shift = (dir) => setDate(addDays(anchor, dir * (mode === "week" ? 7 : 1)));
78
+ const t = (m) => {
79
+ const s = formatTime({ hours: Math.floor(m / 60), minutes: m % 60 });
80
+ return digits === "fa" ? n(s) : s;
81
+ };
82
+ const a = toJalali(days[0]);
83
+ const b = toJalali(days[days.length - 1]);
84
+ const title = mode === "day"
85
+ ? formatJalali(anchor, { style: "full", locale, digits })
86
+ : a.jm === b.jm
87
+ ? `${months[a.jm - 1]} ${n(a.jy)}`
88
+ : a.jy === b.jy
89
+ ? `${months[a.jm - 1]}${locale === "en" ? "–" : " و "}${months[b.jm - 1]} ${n(a.jy)}`
90
+ : `${months[a.jm - 1]} ${n(a.jy)}${locale === "en" ? "–" : " و "}${months[b.jm - 1]} ${n(b.jy)}`;
91
+ const slotDate = (d, s) => {
92
+ const x = days[d];
93
+ const m = startHour * 60 + s * step;
94
+ return new Date(x.getFullYear(), x.getMonth(), x.getDate(), Math.floor(m / 60), m % 60);
95
+ };
96
+ const onGridKey = (e) => {
97
+ const target = e.target;
98
+ if (!target.classList.contains("k-sched__slot"))
99
+ return;
100
+ const rtl = getComputedStyle(e.currentTarget).direction === "rtl";
101
+ let [d, s] = focus;
102
+ if (e.key === "ArrowUp")
103
+ s--;
104
+ else if (e.key === "ArrowDown")
105
+ s++;
106
+ else if (e.key === "ArrowRight")
107
+ d += rtl ? -1 : 1;
108
+ else if (e.key === "ArrowLeft")
109
+ d += rtl ? 1 : -1;
110
+ else if (e.key === "Home")
111
+ s = 0;
112
+ else if (e.key === "End")
113
+ s = slots - 1;
114
+ else
115
+ return;
116
+ e.preventDefault();
117
+ d = Math.max(0, Math.min(days.length - 1, d));
118
+ s = Math.max(0, Math.min(slots - 1, s));
119
+ setFocus([d, s]);
120
+ grid.current?.querySelector(`[data-slot="${d}-${s}"]`)?.focus();
121
+ };
122
+ return (_jsxs("div", { className: cx("k-sched", className), "data-view": mode, style: { "--k-sched-hour": hourHeight }, children: [_jsxs("div", { className: "k-sched__bar", children: [_jsxs("div", { className: "k-sched__nav", children: [_jsx("button", { type: "button", className: "k-sched__icon", "aria-label": mode === "week" ? S.prevWeek : S.prevDay, onClick: () => shift(-1), children: svg("m8 5 5 5-5 5") }), _jsx("button", { type: "button", className: "k-btn k-btn--secondary k-btn--sm", onClick: () => setDate(new Date()), "aria-pressed": days.some((d) => same(d, now)), children: M.common.today }), _jsx("button", { type: "button", className: "k-sched__icon", "aria-label": mode === "week" ? S.nextWeek : S.nextDay, onClick: () => shift(1), children: svg("m12 5-5 5 5 5") })] }), _jsx("h2", { className: "k-sched__title", "aria-live": "polite", children: title }), _jsx(SegmentedControl, { className: "k-sched__views", size: "sm", "aria-label": S.view, value: mode, onChange: (v) => setMode(v), options: [{ value: "week", label: S.week }, { value: "day", label: S.day }] })] }), _jsx("div", { className: "k-sched__scroll", tabIndex: -1, children: _jsxs("div", { className: "k-sched__grid", style: { "--k-sched-days": days.length, "--k-sched-slots": slots, "--k-sched-hours": endHour - startHour }, children: [_jsx("div", { className: "k-sched__corner", "aria-hidden": "true" }), days.map((d, i) => {
123
+ const holiday = holidays ? getIranHoliday(d, { locale }) : null;
124
+ return (_jsxs("div", { className: "k-sched__dayhead", "data-today": same(d, now) ? "" : undefined, "data-holiday": holiday ? "" : undefined, title: holiday ?? undefined, children: [_jsx("span", { className: "k-sched__weekday", children: mode === "week" ? weekdaysShort[jalaliWeekday(d)] : weekdays[jalaliWeekday(d)] }), _jsx("button", { type: "button", className: "k-sched__daynum", "aria-label": formatJalali(d, { style: "full", locale, digits }), onClick: () => { setDate(d); setMode("day"); }, children: n(toJalali(d).jd) })] }, i));
125
+ }), _jsx("div", { className: "k-sched__times", "aria-hidden": "true", children: Array.from({ length: endHour - startHour }, (_, h) => _jsx("span", { className: "k-sched__time", children: t((startHour + h) * 60) }, h)) }), _jsx("div", { ref: grid, className: "k-sched__body", role: "group", "aria-label": S.label, onKeyDown: onGridKey, children: days.map((d, di) => {
126
+ const list = events.filter((e) => same(e.start, d) && mins(e.end) > startHour * 60 && mins(e.start) < endHour * 60);
127
+ const pos = layout(list);
128
+ const isToday = same(d, now);
129
+ const nowMin = mins(now) - startHour * 60;
130
+ return (_jsxs("div", { className: "k-sched__col", role: "group", "aria-label": formatJalali(d, { style: "full", locale, digits }), "data-today": isToday ? "" : undefined, "data-holiday": holidays && getIranHoliday(d) ? "" : undefined, children: [Array.from({ length: slots }, (_, s) => (_jsx("button", { type: "button", className: "k-sched__slot", "data-slot": `${di}-${s}`, "data-hour": (s * step) % 60 === 0 ? "" : undefined, tabIndex: focus[0] === di && focus[1] === s ? 0 : -1, "aria-label": S.slot(weekdays[jalaliWeekday(d)], t(startHour * 60 + s * step)), onFocus: () => setFocus([di, s]), onClick: () => onSlotClick?.(slotDate(di, s)) }, s))), list.map((e) => {
131
+ const p = pos.get(e.id);
132
+ const top = Math.max(0, mins(e.start) - startHour * 60);
133
+ const end = Math.min(total, mins(e.end) - startHour * 60);
134
+ const range = `${t(mins(e.start))} – ${t(mins(e.end))}`;
135
+ return (_jsxs("button", { type: "button", className: "k-sched__event", style: {
136
+ "--k-sched-top": top / total,
137
+ "--k-sched-len": Math.max(15, end - top) / total,
138
+ "--k-sched-col": p.col,
139
+ "--k-sched-cols": p.cols,
140
+ "--k-sched-color": e.color ?? "var(--k-bg-brand)",
141
+ }, "data-short": end - top < 45 ? "" : undefined, onClick: () => onEventClick?.(e), children: [_jsx("span", { className: "k-sched__event-title", dir: "auto", children: e.title }), _jsxs("span", { className: "k-sched__event-time", children: [_jsx("span", { className: "k-sr-only", children: M.common.list }), range] }), e.description && _jsx("span", { className: "k-sched__event-desc", dir: "auto", children: e.description })] }, e.id));
142
+ }), isToday && nowMin >= 0 && nowMin <= total && (_jsx("span", { className: "k-sched__now", style: { "--k-sched-top": nowMin / total }, role: "img", "aria-label": `${S.now} ${t(mins(now))}` }))] }, di));
143
+ }) })] }) })] }));
144
+ }
@@ -0,0 +1,27 @@
1
+ import { type ReactNode } from "react";
2
+ export interface SortableRenderState {
3
+ /** دستگیرهٔ کشیدن؛ هر جای مورد که بخواهید بگذاریدش */
4
+ handle: ReactNode;
5
+ /** این مورد در حال کشیدن است */
6
+ dragging: boolean;
7
+ index: number;
8
+ }
9
+ export interface SortableListProps<T> {
10
+ items: T[];
11
+ getId: (item: T) => string;
12
+ /** نام مورد برای صفحه‌خوان، مثل «کار ۳» */
13
+ getLabel: (item: T) => string;
14
+ /** با رها کردن؛ آرایهٔ مرتب تازه */
15
+ onReorder: (items: T[]) => void;
16
+ /** محتوای هر مورد؛ بدون آن متن getLabel با دستگیره نشان داده می‌شود */
17
+ renderItem?: (item: T, state: SortableRenderState) => ReactNode;
18
+ /** نام فهرست برای صفحه‌خوان */
19
+ "aria-label"?: string;
20
+ disabled?: boolean;
21
+ className?: string;
22
+ }
23
+ /**
24
+ * فهرست کشیدنی: با ماوس و لمس از دستگیره بکشید، یا با کیبورد: فاصله برای برداشتن، کلیدهای جهت برای حرکت،
25
+ * فاصلهٔ دوباره برای رها کردن و Escape برای لغو. هر حرکت برای صفحه‌خوان اعلام می‌شود.
26
+ */
27
+ export declare function SortableList<T>({ items, getId, getLabel, onReorder, renderItem, "aria-label": ariaLabel, disabled, className }: SortableListProps<T>): import("react").JSX.Element;