@kashi-ui/react 2.15.0 → 2.16.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,137 @@
1
+ "use client";
2
+ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { useRef, useState } from "react";
4
+ import { cx } from "./cx.js";
5
+ import { move, useFlip } from "./dnd.js";
6
+ import { useIsomorphicLayoutEffect } from "./utils.js";
7
+ import { useKashi } from "./KashiProvider.js";
8
+ const Grip = () => (_jsx("svg", { viewBox: "0 0 20 20", fill: "currentColor", "aria-hidden": "true", children: [6, 10, 14].flatMap((y) => [_jsx("circle", { cx: "7.5", cy: y, r: "1.3" }, `a${y}`), _jsx("circle", { cx: "12.5", cy: y, r: "1.3" }, `b${y}`)]) }));
9
+ /**
10
+ * فهرست کشیدنی: با ماوس و لمس از دستگیره بکشید، یا با کیبورد: فاصله برای برداشتن، کلیدهای جهت برای حرکت،
11
+ * فاصلهٔ دوباره برای رها کردن و Escape برای لغو. هر حرکت برای صفحه‌خوان اعلام می‌شود.
12
+ */
13
+ export function SortableList({ items, getId, getLabel, onReorder, renderItem, "aria-label": ariaLabel, disabled, className }) {
14
+ const { messages: M, n } = useKashi();
15
+ const S = M.sortable;
16
+ const root = useRef(null);
17
+ // ترتیب پیش‌نمایش هنگام کشیدن؛ null یعنی همان items
18
+ const [preview, setPreview] = useState(null);
19
+ const [active, setActive] = useState(null);
20
+ const [mode, setMode] = useState(null);
21
+ const [live, setLive] = useState("");
22
+ const drag = useRef(null);
23
+ const list = preview ?? items;
24
+ useFlip(root, list.map(getId).join("|"));
25
+ const total = n(list.length);
26
+ const say = (fn, item, pos) => setLive(fn(getLabel(item), n(pos + 1), total));
27
+ const finish = (commit) => {
28
+ const current = preview;
29
+ const it = current?.find((x) => getId(x) === active);
30
+ if (it && current) {
31
+ if (commit) {
32
+ onReorder(current);
33
+ say(S.dropped, it, current.indexOf(it));
34
+ }
35
+ else
36
+ setLive(S.cancelled(getLabel(it)));
37
+ }
38
+ const el = active ? root.current?.querySelector(`[data-flip="${CSS.escape(active)}"]`) : null;
39
+ if (el)
40
+ el.style.translate = "";
41
+ drag.current = null;
42
+ setPreview(null);
43
+ setActive(null);
44
+ setMode(null);
45
+ };
46
+ const finishRef = useRef(finish);
47
+ finishRef.current = finish;
48
+ const refocusing = useRef(false);
49
+ useIsomorphicLayoutEffect(() => {
50
+ if (mode !== "keyboard" || !active)
51
+ return;
52
+ const el = root.current?.querySelector(`[data-flip="${CSS.escape(active)}"] .k-sortable__handle`);
53
+ if (el && document.activeElement !== el)
54
+ el.focus();
55
+ refocusing.current = false;
56
+ }, [preview, mode, active]);
57
+ // اگر فوکوس از فهرست بیرون رفت، جابه‌جایی کیبوردی لغو می‌شود (جابه‌جایی DOM خودش blur موقت می‌سازد)
58
+ const onBlur = () => setTimeout(() => {
59
+ if (!refocusing.current && !root.current?.contains(document.activeElement))
60
+ finishRef.current(false);
61
+ }, 0);
62
+ // جای مورد کشیده‌شده زیر اشاره‌گر
63
+ const follow = (clientY) => {
64
+ const d = drag.current;
65
+ const el = d && root.current?.querySelector(`[data-flip="${CSS.escape(d.id)}"]`);
66
+ if (!d || !el || !preview)
67
+ return;
68
+ const base = el.getBoundingClientRect().top - (parseFloat(el.style.translate.split(" ")[1] ?? "0") || 0);
69
+ el.style.translate = `0 ${clientY - d.grabY - base}px`;
70
+ // جای تازه: مورد زیر مرکز مورد کشیده‌شده
71
+ const center = clientY - d.grabY + el.offsetHeight / 2;
72
+ const others = Array.from(root.current.querySelectorAll("[data-flip]"));
73
+ let to = 0;
74
+ for (const o of others) {
75
+ if (o === el)
76
+ continue;
77
+ const r = o.getBoundingClientRect();
78
+ const top = r.top - (parseFloat(o.style.translate.split(" ")[1] ?? "0") || 0);
79
+ if (center > top + r.height / 2)
80
+ to++;
81
+ }
82
+ const from = preview.findIndex((x) => getId(x) === d.id);
83
+ if (to !== from)
84
+ setPreview(move(preview, from, to));
85
+ };
86
+ const onPointerDown = (e, item) => {
87
+ if (disabled || e.button !== 0)
88
+ return;
89
+ const el = e.currentTarget.closest("[data-flip]");
90
+ e.currentTarget.setPointerCapture(e.pointerId);
91
+ drag.current = { id: getId(item), grabY: e.clientY - el.getBoundingClientRect().top, pointer: e.pointerId };
92
+ setPreview(items);
93
+ setActive(getId(item));
94
+ setMode("pointer");
95
+ };
96
+ const onKeyDown = (e, item) => {
97
+ if (disabled)
98
+ return;
99
+ const id = getId(item);
100
+ if (e.key === " " || e.key === "Enter") {
101
+ e.preventDefault();
102
+ if (active === id && mode === "keyboard")
103
+ finish(true);
104
+ else {
105
+ setPreview(items);
106
+ setActive(id);
107
+ setMode("keyboard");
108
+ say(S.grabbed, item, items.indexOf(item));
109
+ }
110
+ return;
111
+ }
112
+ if (active !== id || mode !== "keyboard" || !preview)
113
+ return;
114
+ if (e.key === "Escape") {
115
+ e.preventDefault();
116
+ finish(false);
117
+ return;
118
+ }
119
+ const from = preview.findIndex((x) => getId(x) === id);
120
+ const to = e.key === "ArrowUp" || e.key === "ArrowLeft" ? from - 1 : e.key === "ArrowDown" || e.key === "ArrowRight" ? from + 1 : e.key === "Home" ? 0 : e.key === "End" ? preview.length - 1 : -2;
121
+ if (to === -2)
122
+ return;
123
+ e.preventDefault();
124
+ if (to < 0 || to >= preview.length || to === from)
125
+ return;
126
+ const next = move(preview, from, to);
127
+ refocusing.current = true;
128
+ setPreview(next);
129
+ say(S.moved, item, to);
130
+ };
131
+ return (_jsxs(_Fragment, { children: [_jsx("ul", { ref: root, className: cx("k-sortable", className), "aria-label": ariaLabel, "data-dragging": active ? "" : undefined, children: list.map((item, index) => {
132
+ const id = getId(item);
133
+ const dragging = active === id;
134
+ const handle = (_jsx("button", { type: "button", className: "k-sortable__handle", "aria-label": S.handle(getLabel(item)), "aria-pressed": dragging && mode === "keyboard", title: S.instructions, disabled: disabled, onPointerDown: (e) => onPointerDown(e, item), onPointerMove: (e) => drag.current?.pointer === e.pointerId && follow(e.clientY), onPointerUp: (e) => drag.current?.pointer === e.pointerId && finish(true), onPointerCancel: () => drag.current && finish(false), onKeyDown: (e) => onKeyDown(e, item), onBlur: () => mode === "keyboard" && dragging && onBlur(), children: _jsx(Grip, {}) }));
135
+ return (_jsx("li", { className: "k-sortable__item", "data-flip": id, "data-dragging": dragging ? "" : undefined, "data-mode": dragging ? mode ?? undefined : undefined, children: renderItem ? renderItem(item, { handle, dragging, index }) : (_jsxs(_Fragment, { children: [handle, _jsx("span", { className: "k-sortable__label", children: getLabel(item) })] })) }, id));
136
+ }) }), _jsx("span", { className: "k-sr-only", "aria-live": "assertive", children: live })] }));
137
+ }
@@ -0,0 +1,24 @@
1
+ import { type ElementType } from "react";
2
+ export interface StreamingTextProps {
3
+ /** متن تا این لحظه؛ در پاسخ زندهٔ مدل زبانی با هر تکهٔ تازه بلندتر می‌شود */
4
+ text: string;
5
+ /** هنوز در حال نوشتن است: نشانگر چشمک‌زن و aria-busy @default false */
6
+ streaming?: boolean;
7
+ /**
8
+ * متن کامل را خودش کلمه‌به‌کلمه نشان می‌دهد (برای وقتی که پاسخ یک‌جا رسیده)؛
9
+ * عدد، کلمه در ثانیه است. بدون آن فقط کلمه‌های تازهٔ text نرم ظاهر می‌شوند.
10
+ */
11
+ speed?: number;
12
+ /** پس از نمایش کامل متن (در حالت speed) */
13
+ onDone?: () => void;
14
+ /** نشانگر انتهای متن @default true */
15
+ cursor?: boolean;
16
+ /** @default "p" */
17
+ as?: ElementType;
18
+ className?: string;
19
+ }
20
+ /**
21
+ * متنی که کلمه‌به‌کلمه نوشته می‌شود؛ برای پاسخ زندهٔ دستیار هوش مصنوعی.
22
+ * صفحه‌خوان هر کلمه را جدا نمی‌خواند: متن تا پایان aria-busy است و پایان پاسخ یک بار اعلام می‌شود.
23
+ */
24
+ export declare function StreamingText({ text, streaming, speed, onDone, cursor, as: Tag, className }: StreamingTextProps): import("react").JSX.Element;
@@ -0,0 +1,52 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { useEffect, useRef, useState } from "react";
4
+ import { cx } from "./cx.js";
5
+ import { useKashi } from "./KashiProvider.js";
6
+ const reduced = () => typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
7
+ /** کلمه‌ها با فاصلهٔ بعدشان؛ نیم‌فاصله داخل کلمه می‌ماند */
8
+ const words = (s) => s.match(/\S+\s*|\s+/g) ?? [];
9
+ /**
10
+ * متنی که کلمه‌به‌کلمه نوشته می‌شود؛ برای پاسخ زندهٔ دستیار هوش مصنوعی.
11
+ * صفحه‌خوان هر کلمه را جدا نمی‌خواند: متن تا پایان aria-busy است و پایان پاسخ یک بار اعلام می‌شود.
12
+ */
13
+ export function StreamingText({ text, streaming = false, speed, onDone, cursor = true, as: Tag = "p", className }) {
14
+ const { messages: M } = useKashi();
15
+ const all = words(text);
16
+ const [shown, setShown] = useState(() => (speed && !reduced() ? 0 : all.length));
17
+ // کلمه‌هایی که پیش از این دیده شده‌اند انیمیشن نمی‌گیرند
18
+ const seen = useRef(speed ? 0 : all.length);
19
+ const done = useRef(onDone);
20
+ done.current = onDone;
21
+ useEffect(() => {
22
+ if (!speed || reduced()) {
23
+ setShown(all.length);
24
+ return;
25
+ }
26
+ if (shown >= all.length) {
27
+ done.current?.();
28
+ return;
29
+ }
30
+ const t = setTimeout(() => setShown((n) => n + 1), 1000 / speed);
31
+ return () => clearTimeout(t);
32
+ }, [speed, shown, all.length]);
33
+ const animated = !!speed && !reduced();
34
+ const count = animated ? Math.min(shown, all.length) : all.length;
35
+ useEffect(() => {
36
+ seen.current = count;
37
+ });
38
+ const typing = streaming || (animated && count < all.length);
39
+ // پایان نوشتن یک بار برای صفحه‌خوان اعلام می‌شود
40
+ const was = useRef(typing);
41
+ const [announce, setAnnounce] = useState("");
42
+ useEffect(() => {
43
+ if (was.current && !typing)
44
+ setAnnounce(M.streaming.done);
45
+ if (typing)
46
+ setAnnounce("");
47
+ was.current = typing;
48
+ }, [typing, M.streaming.done]);
49
+ const visible = all.slice(0, count);
50
+ const from = seen.current;
51
+ return (_jsxs(Tag, { className: cx("k-stream", className), dir: "auto", "aria-busy": typing || undefined, "data-streaming": typing ? "" : undefined, children: [visible.map((w, i) => (i < from ? w : _jsx("span", { className: "k-stream__word", children: w }, i))), cursor && typing && _jsx("span", { className: "k-stream__cursor", "aria-hidden": "true" }), _jsx("span", { className: "k-sr-only", "aria-live": "polite", children: announce })] }));
52
+ }
@@ -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 TaxIdInputProps extends Base {
5
+ /** مقدار یکدست‌شده: ارقام لاتین و حروف بزرگ */
6
+ value?: string;
7
+ defaultValue?: string;
8
+ onValueChange?: (value: string, valid: boolean) => void;
9
+ invalidMessage?: ReactNode;
10
+ }
11
+ /**
12
+ * شمارهٔ منحصربه‌فرد مالیاتی فاکتور (سامانهٔ مودیان): ۲۲ نویسه.
13
+ * ارقام فارسی لاتین می‌شوند، حروف بزرگ و فاصله و خط تیره حذف؛ فقط شکل بررسی می‌شود.
14
+ */
15
+ export declare const TaxIdInput: import("react").ForwardRefExoticComponent<TaxIdInputProps & import("react").RefAttributes<HTMLInputElement>>;
16
+ export {};
@@ -0,0 +1,27 @@
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 { isValidTaxId, normalizeTaxId } from "@kashi-ui/persian";
5
+ import { Input } from "./Input.js";
6
+ import { useKashi } from "./KashiProvider.js";
7
+ /**
8
+ * شمارهٔ منحصربه‌فرد مالیاتی فاکتور (سامانهٔ مودیان): ۲۲ نویسه.
9
+ * ارقام فارسی لاتین می‌شوند، حروف بزرگ و فاصله و خط تیره حذف؛ فقط شکل بررسی می‌شود.
10
+ */
11
+ export const TaxIdInput = forwardRef(function TaxIdInput({ value, defaultValue = "", onValueChange, invalidMessage, error, name, onBlur, placeholder, ...rest }, ref) {
12
+ const { messages: M } = useKashi();
13
+ invalidMessage ?? (invalidMessage = M.invalid.taxId);
14
+ const [inner, setInner] = useState(() => normalizeTaxId(defaultValue).slice(0, 22));
15
+ const [touched, setTouched] = useState(false);
16
+ const raw = value !== undefined ? normalizeTaxId(value).slice(0, 22) : inner;
17
+ const showInvalid = raw.length > 0 && (touched || raw.length === 22) && !isValidTaxId(raw);
18
+ return (_jsxs(_Fragment, { children: [_jsx(Input, { ref: ref, type: "text", variant: "code", dir: "ltr", placeholder: placeholder ?? "A1B2C3…", value: raw, onChange: (e) => {
19
+ const next = normalizeTaxId(e.target.value).slice(0, 22);
20
+ if (value === undefined)
21
+ setInner(next);
22
+ onValueChange?.(next, isValidTaxId(next));
23
+ }, onBlur: (e) => {
24
+ setTouched(true);
25
+ onBlur?.(e);
26
+ }, error: error ?? (showInvalid ? invalidMessage : undefined), ...rest }), name && _jsx("input", { type: "hidden", name: name, value: raw })] }));
27
+ });
package/dist/dnd.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ import { type RefObject } from "react";
2
+ /**
3
+ * حرکت نرم موارد پس از جابه‌جایی (FLIP): جای قبلی هر [data-flip] را به خاطر می‌سپارد و
4
+ * پس از هر تغییر ترتیب، از جای قبلی به جای تازه می‌لغزاندش. موردی که دستی کشیده می‌شود ([data-dragging]) حرکت نمی‌گیرد.
5
+ */
6
+ export declare function useFlip(root: RefObject<HTMLElement | null>, key: unknown): void;
7
+ /** جهت صفحه برای کلیدهای چپ و راست */
8
+ export declare const isRtl: (el: Element | null) => boolean;
9
+ /** جابه‌جایی یک عضو آرایه */
10
+ export declare function move<T>(list: T[], from: number, to: number): T[];
package/dist/dnd.js ADDED
@@ -0,0 +1,54 @@
1
+ "use client";
2
+ import { useRef } from "react";
3
+ import { useIsomorphicLayoutEffect } from "./utils.js";
4
+ const reduced = () => typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
5
+ /**
6
+ * حرکت نرم موارد پس از جابه‌جایی (FLIP): جای قبلی هر [data-flip] را به خاطر می‌سپارد و
7
+ * پس از هر تغییر ترتیب، از جای قبلی به جای تازه می‌لغزاندش. موردی که دستی کشیده می‌شود ([data-dragging]) حرکت نمی‌گیرد.
8
+ */
9
+ export function useFlip(root, key) {
10
+ const last = useRef(new Map());
11
+ useIsomorphicLayoutEffect(() => {
12
+ const el = root.current;
13
+ if (!el)
14
+ return;
15
+ const items = Array.from(el.querySelectorAll("[data-flip]"));
16
+ const next = new Map();
17
+ for (const it of items) {
18
+ const id = it.dataset.flip;
19
+ const prev = last.current.get(id);
20
+ const style = it.style.translate;
21
+ it.style.transition = "none";
22
+ if (!it.hasAttribute("data-dragging"))
23
+ it.style.translate = "";
24
+ const rect = it.getBoundingClientRect();
25
+ next.set(id, rect);
26
+ if (!prev || it.hasAttribute("data-dragging") || reduced()) {
27
+ if (it.hasAttribute("data-dragging"))
28
+ it.style.translate = style;
29
+ it.style.transition = "";
30
+ continue;
31
+ }
32
+ const dx = prev.left - rect.left;
33
+ const dy = prev.top - rect.top;
34
+ if (Math.abs(dx) < 1 && Math.abs(dy) < 1) {
35
+ it.style.transition = "";
36
+ continue;
37
+ }
38
+ it.style.translate = `${dx}px ${dy}px`;
39
+ void it.offsetWidth;
40
+ it.style.transition = "";
41
+ it.style.translate = "";
42
+ }
43
+ last.current = next;
44
+ }, [key]);
45
+ }
46
+ /** جهت صفحه برای کلیدهای چپ و راست */
47
+ export const isRtl = (el) => !!el && getComputedStyle(el).direction === "rtl";
48
+ /** جابه‌جایی یک عضو آرایه */
49
+ export function move(list, from, to) {
50
+ const next = list.slice();
51
+ const [it] = next.splice(from, 1);
52
+ next.splice(to, 0, it);
53
+ return next;
54
+ }
package/dist/index.d.ts CHANGED
@@ -179,3 +179,36 @@ export { KashiProvider, useKashi } from "./KashiProvider.js";
179
179
  export type { KashiProviderProps } from "./KashiProvider.js";
180
180
  export { faMessages, enMessages } from "@kashi-ui/persian";
181
181
  export type { KashiMessages, KashiMessagesInput, KashiLocale } from "@kashi-ui/persian";
182
+ export { SayadInput } from "./SayadInput.js";
183
+ export type { SayadInputProps } from "./SayadInput.js";
184
+ export { EconomicCodeInput } from "./EconomicCodeInput.js";
185
+ export type { EconomicCodeInputProps } from "./EconomicCodeInput.js";
186
+ export { TaxIdInput } from "./TaxIdInput.js";
187
+ export type { TaxIdInputProps } from "./TaxIdInput.js";
188
+ export { BusinessHours, WeekdayPicker } from "./BusinessHours.js";
189
+ export type { BusinessHoursProps, WeekdayPickerProps } from "./BusinessHours.js";
190
+ export { ChatThread, ChatMessage, ChatDivider, TypingIndicator } from "./Chat.js";
191
+ export type { ChatThreadProps, ChatMessageProps, ChatRole, ChatStatus, TypingIndicatorProps } from "./Chat.js";
192
+ export { ChatComposer } from "./ChatComposer.js";
193
+ export type { ChatComposerProps, ChatComposerSend } from "./ChatComposer.js";
194
+ export { StreamingText } from "./StreamingText.js";
195
+ export type { StreamingTextProps } from "./StreamingText.js";
196
+ export { CodeBlock, highlightCode } from "./CodeBlock.js";
197
+ export type { CodeBlockProps } from "./CodeBlock.js";
198
+ export { SortableList } from "./Sortable.js";
199
+ export type { SortableListProps, SortableRenderState } from "./Sortable.js";
200
+ export { Kanban } from "./Kanban.js";
201
+ export type { KanbanProps, KanbanColumn, KanbanCardState } from "./Kanban.js";
202
+ export { Lightbox, Gallery } from "./Lightbox.js";
203
+ export type { LightboxProps, LightboxImage, GalleryProps } from "./Lightbox.js";
204
+ export { RichTextEditor, sanitizeRichText } from "./RichTextEditor.js";
205
+ export type { RichTextEditorProps, RichTextTool } from "./RichTextEditor.js";
206
+ export { NotificationCenter, NotificationList } from "./NotificationCenter.js";
207
+ export type { NotificationCenterProps, NotificationListProps, NotificationItem } from "./NotificationCenter.js";
208
+ export { QRCode } from "./QRCode.js";
209
+ export type { QRCodeProps } from "./QRCode.js";
210
+ export { encodeQr } from "./qr.js";
211
+ export type { QrLevel } from "./qr.js";
212
+ export { Scheduler } from "./Scheduler.js";
213
+ export type { SchedulerProps, SchedulerEvent } from "./Scheduler.js";
214
+ export type { EconomicCodeType, WeekHours, DayHours, TimeRange } from "@kashi-ui/persian";
package/dist/index.js CHANGED
@@ -90,3 +90,19 @@ export { PaymentReceipt } from "./PaymentReceipt.js";
90
90
  export { PersianInput, PERSIAN_INPUT_LABELS } from "./PersianInput.js";
91
91
  export { KashiProvider, useKashi } from "./KashiProvider.js";
92
92
  export { faMessages, enMessages } from "@kashi-ui/persian";
93
+ export { SayadInput } from "./SayadInput.js";
94
+ export { EconomicCodeInput } from "./EconomicCodeInput.js";
95
+ export { TaxIdInput } from "./TaxIdInput.js";
96
+ export { BusinessHours, WeekdayPicker } from "./BusinessHours.js";
97
+ export { ChatThread, ChatMessage, ChatDivider, TypingIndicator } from "./Chat.js";
98
+ export { ChatComposer } from "./ChatComposer.js";
99
+ export { StreamingText } from "./StreamingText.js";
100
+ export { CodeBlock, highlightCode } from "./CodeBlock.js";
101
+ export { SortableList } from "./Sortable.js";
102
+ export { Kanban } from "./Kanban.js";
103
+ export { Lightbox, Gallery } from "./Lightbox.js";
104
+ export { RichTextEditor, sanitizeRichText } from "./RichTextEditor.js";
105
+ export { NotificationCenter, NotificationList } from "./NotificationCenter.js";
106
+ export { QRCode } from "./QRCode.js";
107
+ export { encodeQr } from "./qr.js";
108
+ export { Scheduler } from "./Scheduler.js";
package/dist/qr.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ /**
2
+ * سازندهٔ کد QR بدون وابستگی (استاندارد ISO/IEC 18004، حالت بایت با UTF-8، نسخهٔ ۱ تا ۴۰).
3
+ * خروجی ماتریس مربعی است: true یعنی خانهٔ تیره.
4
+ */
5
+ export type QrLevel = "L" | "M" | "Q" | "H";
6
+ /** متن را به ماتریس QR تبدیل می‌کند؛ اگر متن جا نشود null برمی‌گرداند */
7
+ export declare function encodeQr(text: string, level?: QrLevel): boolean[][] | null;
package/dist/qr.js ADDED
@@ -0,0 +1,271 @@
1
+ /**
2
+ * سازندهٔ کد QR بدون وابستگی (استاندارد ISO/IEC 18004، حالت بایت با UTF-8، نسخهٔ ۱ تا ۴۰).
3
+ * خروجی ماتریس مربعی است: true یعنی خانهٔ تیره.
4
+ */
5
+ // تعداد کدواژهٔ تصحیح خطا در هر بلوک و تعداد بلوک‌ها، برای هر سطح و نسخه (اندیس ۰ استفاده نمی‌شود)
6
+ const ECC = {
7
+ L: [-1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30],
8
+ M: [-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28],
9
+ Q: [-1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30],
10
+ H: [-1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30],
11
+ };
12
+ const BLOCKS = {
13
+ L: [-1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25],
14
+ M: [-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49],
15
+ Q: [-1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68],
16
+ H: [-1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81],
17
+ };
18
+ const FORMAT = { L: 1, M: 0, Q: 3, H: 2 };
19
+ const rawModules = (v) => {
20
+ let r = (16 * v + 128) * v + 64;
21
+ if (v >= 2) {
22
+ const a = Math.floor(v / 7) + 2;
23
+ r -= (25 * a - 10) * a - 55;
24
+ if (v >= 7)
25
+ r -= 36;
26
+ }
27
+ return r;
28
+ };
29
+ const dataCodewords = (v, l) => Math.floor(rawModules(v) / 8) - ECC[l][v] * BLOCKS[l][v];
30
+ // ضرب در میدان گالوا GF(2^8) با چندجمله‌ای 0x11D
31
+ const gmul = (x, y) => {
32
+ let z = 0;
33
+ for (let i = 7; i >= 0; i--) {
34
+ z = (z << 1) ^ ((z >>> 7) * 0x11d);
35
+ z ^= ((y >>> i) & 1) * x;
36
+ }
37
+ return z & 0xff;
38
+ };
39
+ const rsDivisor = (degree) => {
40
+ const r = new Array(degree).fill(0);
41
+ r[degree - 1] = 1;
42
+ let root = 1;
43
+ for (let i = 0; i < degree; i++) {
44
+ for (let j = 0; j < r.length; j++) {
45
+ r[j] = gmul(r[j], root);
46
+ if (j + 1 < r.length)
47
+ r[j] ^= r[j + 1];
48
+ }
49
+ root = gmul(root, 0x02);
50
+ }
51
+ return r;
52
+ };
53
+ const rsRemainder = (data, div) => {
54
+ const r = new Array(div.length).fill(0);
55
+ for (const b of data) {
56
+ const f = b ^ r.shift();
57
+ r.push(0);
58
+ div.forEach((c, i) => (r[i] ^= gmul(c, f)));
59
+ }
60
+ return r;
61
+ };
62
+ const alignment = (v) => {
63
+ if (v === 1)
64
+ return [];
65
+ const n = Math.floor(v / 7) + 2;
66
+ const step = v === 32 ? 26 : Math.ceil((v * 4 + 4) / (n * 2 - 2)) * 2;
67
+ const r = [6];
68
+ for (let p = v * 4 + 10; r.length < n; p -= step)
69
+ r.splice(1, 0, p);
70
+ return r;
71
+ };
72
+ const MASKS = [
73
+ (x, y) => (x + y) % 2 === 0,
74
+ (_, y) => y % 2 === 0,
75
+ (x) => x % 3 === 0,
76
+ (x, y) => (x + y) % 3 === 0,
77
+ (x, y) => (Math.floor(x / 3) + Math.floor(y / 2)) % 2 === 0,
78
+ (x, y) => ((x * y) % 2) + ((x * y) % 3) === 0,
79
+ (x, y) => (((x * y) % 2) + ((x * y) % 3)) % 2 === 0,
80
+ (x, y) => (((x + y) % 2) + ((x * y) % 3)) % 2 === 0,
81
+ ];
82
+ /** امتیاز جریمهٔ استاندارد برای انتخاب بهترین ماسک (کمتر بهتر) */
83
+ function penalty(m) {
84
+ const n = m.length;
85
+ let score = 0;
86
+ const lines = (get) => {
87
+ for (let a = 0; a < n; a++) {
88
+ let run = 1;
89
+ for (let b = 1; b <= n; b++) {
90
+ if (b < n && get(a, b) === get(a, b - 1))
91
+ run++;
92
+ else {
93
+ if (run >= 5)
94
+ score += run - 2;
95
+ run = 1;
96
+ }
97
+ }
98
+ // الگوی شبیه نشانگر: ۱:۱:۳:۱:۱ با چهار خانهٔ روشن کنارش
99
+ for (let b = 0; b + 10 < n; b++) {
100
+ const s = Array.from({ length: 11 }, (_, k) => get(a, b + k));
101
+ const p1 = [true, false, true, true, true, false, true, false, false, false, false];
102
+ if (s.every((v, k) => v === p1[k]) || s.every((v, k) => v === p1[10 - k]))
103
+ score += 40;
104
+ }
105
+ }
106
+ };
107
+ lines((y, x) => m[y][x]);
108
+ lines((x, y) => m[y][x]);
109
+ let dark = 0;
110
+ for (let y = 0; y < n; y++)
111
+ for (let x = 0; x < n; x++) {
112
+ if (m[y][x])
113
+ dark++;
114
+ if (x < n - 1 && y < n - 1 && m[y][x] === m[y][x + 1] && m[y][x] === m[y + 1][x] && m[y][x] === m[y + 1][x + 1])
115
+ score += 3;
116
+ }
117
+ const total = n * n;
118
+ score += (Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1) * 10;
119
+ return score;
120
+ }
121
+ /** متن را به ماتریس QR تبدیل می‌کند؛ اگر متن جا نشود null برمی‌گرداند */
122
+ export function encodeQr(text, level = "M") {
123
+ const bytes = Array.from(new TextEncoder().encode(text));
124
+ let ver = 0;
125
+ for (let v = 1; v <= 40; v++) {
126
+ const cc = v <= 9 ? 8 : 16;
127
+ if (4 + cc + bytes.length * 8 <= dataCodewords(v, level) * 8) {
128
+ ver = v;
129
+ break;
130
+ }
131
+ }
132
+ if (!ver)
133
+ return null;
134
+ // رشتهٔ بیت‌ها: حالت بایت، طول، داده، پایان‌دهنده و پرکننده
135
+ const bits = [];
136
+ const put = (val, len) => {
137
+ for (let i = len - 1; i >= 0; i--)
138
+ bits.push((val >>> i) & 1);
139
+ };
140
+ put(0b0100, 4);
141
+ put(bytes.length, ver <= 9 ? 8 : 16);
142
+ for (const b of bytes)
143
+ put(b, 8);
144
+ const cap = dataCodewords(ver, level) * 8;
145
+ put(0, Math.min(4, cap - bits.length));
146
+ put(0, (8 - (bits.length % 8)) % 8);
147
+ for (let pad = 0xec; bits.length < cap; pad ^= 0xec ^ 0x11)
148
+ put(pad, 8);
149
+ const data = [];
150
+ for (let i = 0; i < bits.length; i += 8)
151
+ data.push(parseInt(bits.slice(i, i + 8).join(""), 2));
152
+ // بلوک‌ها، تصحیح خطا و درهم‌آمیختن
153
+ const nb = BLOCKS[level][ver];
154
+ const eccLen = ECC[level][ver];
155
+ const raw = Math.floor(rawModules(ver) / 8);
156
+ const short = nb - (raw % nb);
157
+ const shortLen = Math.floor(raw / nb);
158
+ const div = rsDivisor(eccLen);
159
+ const blocks = [];
160
+ for (let i = 0, k = 0; i < nb; i++) {
161
+ const len = shortLen - eccLen + (i < short ? 0 : 1);
162
+ const dat = data.slice(k, k + len);
163
+ k += len;
164
+ const ecc = rsRemainder(dat, div);
165
+ if (i < short)
166
+ dat.push(0);
167
+ blocks.push(dat.concat(ecc));
168
+ }
169
+ const all = [];
170
+ for (let i = 0; i < blocks[0].length; i++)
171
+ for (let j = 0; j < nb; j++)
172
+ if (i !== shortLen - eccLen || j >= short)
173
+ all.push(blocks[j][i]);
174
+ // الگوهای ثابت
175
+ const size = ver * 4 + 17;
176
+ const m = Array.from({ length: size }, () => new Array(size).fill(false));
177
+ const fn = Array.from({ length: size }, () => new Array(size).fill(false));
178
+ const set = (x, y, dark) => {
179
+ m[y][x] = dark;
180
+ fn[y][x] = true;
181
+ };
182
+ for (let i = 0; i < size; i++) {
183
+ set(6, i, i % 2 === 0);
184
+ set(i, 6, i % 2 === 0);
185
+ }
186
+ for (const [cx, cy] of [[3, 3], [size - 4, 3], [3, size - 4]])
187
+ for (let dy = -4; dy <= 4; dy++)
188
+ for (let dx = -4; dx <= 4; dx++) {
189
+ const x = cx + dx, y = cy + dy;
190
+ if (x >= 0 && x < size && y >= 0 && y < size) {
191
+ const d = Math.max(Math.abs(dx), Math.abs(dy));
192
+ set(x, y, d !== 2 && d !== 4);
193
+ }
194
+ }
195
+ const al = alignment(ver);
196
+ al.forEach((ax, i) => al.forEach((ay, j) => {
197
+ if ((i === 0 && j === 0) || (i === 0 && j === al.length - 1) || (i === al.length - 1 && j === 0))
198
+ return;
199
+ for (let dy = -2; dy <= 2; dy++)
200
+ for (let dx = -2; dx <= 2; dx++)
201
+ set(ax + dx, ay + dy, Math.max(Math.abs(dx), Math.abs(dy)) !== 1);
202
+ }));
203
+ const drawFormat = (mask) => {
204
+ const d = (FORMAT[level] << 3) | mask;
205
+ let r = d;
206
+ for (let i = 0; i < 10; i++)
207
+ r = (r << 1) ^ ((r >>> 9) * 0x537);
208
+ const b = ((d << 10) | r) ^ 0x5412;
209
+ const bit = (i) => ((b >>> i) & 1) === 1;
210
+ for (let i = 0; i <= 5; i++)
211
+ set(8, i, bit(i));
212
+ set(8, 7, bit(6));
213
+ set(8, 8, bit(7));
214
+ set(7, 8, bit(8));
215
+ for (let i = 9; i < 15; i++)
216
+ set(14 - i, 8, bit(i));
217
+ for (let i = 0; i < 8; i++)
218
+ set(size - 1 - i, 8, bit(i));
219
+ for (let i = 8; i < 15; i++)
220
+ set(8, size - 15 + i, bit(i));
221
+ set(8, size - 8, true);
222
+ };
223
+ drawFormat(0);
224
+ if (ver >= 7) {
225
+ let r = ver;
226
+ for (let i = 0; i < 12; i++)
227
+ r = (r << 1) ^ ((r >>> 11) * 0x1f25);
228
+ const b = (ver << 12) | r;
229
+ for (let i = 0; i < 18; i++) {
230
+ const dark = ((b >>> i) & 1) === 1;
231
+ const a = size - 11 + (i % 3), c = Math.floor(i / 3);
232
+ set(a, c, dark);
233
+ set(c, a, dark);
234
+ }
235
+ }
236
+ // چیدن کدواژه‌ها به شکل زیگزاگ
237
+ let i = 0;
238
+ for (let right = size - 1; right >= 1; right -= 2) {
239
+ if (right === 6)
240
+ right = 5;
241
+ for (let vert = 0; vert < size; vert++)
242
+ for (let j = 0; j < 2; j++) {
243
+ const x = right - j;
244
+ const up = ((right + 1) & 2) === 0;
245
+ const y = up ? size - 1 - vert : vert;
246
+ if (!fn[y][x] && i < all.length * 8) {
247
+ m[y][x] = ((all[i >>> 3] >>> (7 - (i & 7))) & 1) === 1;
248
+ i++;
249
+ }
250
+ }
251
+ }
252
+ // بهترین ماسک
253
+ const apply = (k) => {
254
+ for (let y = 0; y < size; y++)
255
+ for (let x = 0; x < size; x++)
256
+ if (!fn[y][x] && MASKS[k](x, y))
257
+ m[y][x] = !m[y][x];
258
+ };
259
+ let best = 0, bestScore = Infinity;
260
+ for (let k = 0; k < 8; k++) {
261
+ apply(k);
262
+ drawFormat(k);
263
+ const s = penalty(m);
264
+ if (s < bestScore)
265
+ [best, bestScore] = [k, s];
266
+ apply(k);
267
+ }
268
+ apply(best);
269
+ drawFormat(best);
270
+ return m;
271
+ }