@kashi-ui/elements 2.22.0 → 2.23.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.
Files changed (79) hide show
  1. package/README.md +6 -1
  2. package/dist/base.js +4 -0
  3. package/dist/buttons.d.ts +82 -0
  4. package/dist/buttons.js +487 -0
  5. package/dist/cards.d.ts +30 -0
  6. package/dist/cards.js +183 -0
  7. package/dist/cdn/{appointment-wMGBoHw9.js → appointment-DOXBUwIU.js} +1 -1
  8. package/dist/cdn/{base-Dg1Mb8Jk.js → base-D4tCOysh.js} +1 -1
  9. package/dist/cdn/{basic-B5ZxgagA.js → basic-DuY4RslZ.js} +1 -1
  10. package/dist/cdn/buttons-zhSdiaXr.js +1 -0
  11. package/dist/cdn/calendar-BulPeVAJ.js +16 -0
  12. package/dist/cdn/card-BKiwJF34.js +1 -0
  13. package/dist/cdn/cards-DKarXHsC.js +1 -0
  14. package/dist/cdn/charts-ETYOAJyB.js +1 -0
  15. package/dist/cdn/chat-D5ZIMnNp.js +4 -0
  16. package/dist/cdn/choice-DBvC2Puo.js +1 -0
  17. package/dist/cdn/{combobox-CBT7yp94.js → combobox-BGuPAAt3.js} +1 -1
  18. package/dist/cdn/{commerce-CsyixnVK.js → commerce-SzWdpWJG.js} +1 -1
  19. package/dist/cdn/content-BgfBfy8j.js +1 -0
  20. package/dist/cdn/controls--OMZkJYe.js +1 -0
  21. package/dist/cdn/display-BfYWAjNu.js +1 -0
  22. package/dist/cdn/{fields-Cx84-qz1.js → fields-B-jTUQiI.js} +1 -1
  23. package/dist/cdn/forms-DgRiYmdV.js +1 -0
  24. package/dist/cdn/{holidays-DO82gXhM.js → holidays-Cu6IfbTL.js} +1 -1
  25. package/dist/cdn/hours-CeiVqPKD.js +1 -0
  26. package/dist/cdn/inputs-BkJ70Xkc.js +1 -0
  27. package/dist/cdn/kashi-elements.js +1 -1
  28. package/dist/cdn/legal-id-Mt8FX0fV.js +1 -0
  29. package/dist/cdn/{map-DlpA916P.js → map-TfSt3CjL.js} +2 -2
  30. package/dist/cdn/media-BRBINvzU.js +1 -0
  31. package/dist/cdn/{menu-CqTvk8Ok.js → menu-DTNVFXrb.js} +1 -1
  32. package/dist/cdn/money-CjGI2VIQ.js +1 -0
  33. package/dist/cdn/{nav-BHv7H1Fy.js → nav-CT5RVOzy.js} +1 -1
  34. package/dist/cdn/{overlay-BIEEJ4Sh.js → overlay-DC5-I6hM.js} +1 -1
  35. package/dist/cdn/parts-5fVaWtRe.js +1 -0
  36. package/dist/cdn/pickers-BwDRsDRo.js +1 -0
  37. package/dist/cdn/relative-OC1fV3Xh.js +1 -0
  38. package/dist/cdn/rich-text-CS6xEim6.js +1 -0
  39. package/dist/cdn/sheets-eVMx4d-5.js +1 -0
  40. package/dist/cdn/{table-B5XwDDS9.js → table-tgB4iwcM.js} +1 -1
  41. package/dist/cdn/{text-Bml-pVjo.js → text-C6fzEBBh.js} +1 -1
  42. package/dist/cdn/{time-DrXgFeQy.js → time-CkqqUKJv.js} +1 -1
  43. package/dist/cdn/{time-BQsTSvql.js → time-CwOYrtK-.js} +1 -1
  44. package/dist/cdn/validate-Dr2f6i6s.js +1 -0
  45. package/dist/cdn/work-DoNAKgVU.js +1 -0
  46. package/dist/cdn.js +11 -0
  47. package/dist/chat.d.ts +127 -0
  48. package/dist/chat.js +734 -0
  49. package/dist/choice.d.ts +98 -0
  50. package/dist/choice.js +597 -0
  51. package/dist/content.d.ts +164 -0
  52. package/dist/content.js +726 -0
  53. package/dist/hours.d.ts +29 -0
  54. package/dist/hours.js +179 -0
  55. package/dist/index.d.ts +64 -2
  56. package/dist/index.js +22 -1
  57. package/dist/manifest.json +843 -1
  58. package/dist/media.d.ts +51 -0
  59. package/dist/media.js +363 -0
  60. package/dist/parts.d.ts +31 -0
  61. package/dist/parts.js +114 -0
  62. package/dist/qr.d.ts +7 -0
  63. package/dist/qr.js +271 -0
  64. package/dist/rich-text.d.ts +40 -0
  65. package/dist/rich-text.js +375 -0
  66. package/dist/sheets.d.ts +128 -0
  67. package/dist/sheets.js +661 -0
  68. package/dist/validate.d.ts +40 -0
  69. package/dist/validate.js +224 -0
  70. package/dist/work.d.ts +117 -0
  71. package/dist/work.js +895 -0
  72. package/package.json +4 -4
  73. package/dist/cdn/calendar-Cjp5Rqer.js +0 -16
  74. package/dist/cdn/charts-DvQ4OwdS.js +0 -1
  75. package/dist/cdn/controls-B-s4IF_4.js +0 -1
  76. package/dist/cdn/display-MorJMDEF.js +0 -1
  77. package/dist/cdn/forms-CQeP9iiW.js +0 -1
  78. package/dist/cdn/inputs-Bqcs9Xy7.js +0 -1
  79. package/dist/cdn/pickers-BT9VPT4o.js +0 -1
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
+ }
@@ -0,0 +1,40 @@
1
+ import { HTMLBase } from "./base.js";
2
+ export type RichTextTool = "bold" | "italic" | "underline" | "strike" | "heading" | "quote" | "bullet" | "ordered" | "link" | "direction" | "undo" | "clear" | "|";
3
+ /** پاک‌سازی HTML: فقط برچسب‌های متنی مجاز، پیوندهای http، https و mailto، و ویژگی dir */
4
+ export declare function sanitizeRichText(html: string): string;
5
+ /**
6
+ * ویرایشگر متن غنی فارسی: جهت هر بند جدا، نیم‌فاصله با Shift+Space، چسباندن پاک‌شده و نوار ابزار با کلیدهای جهت.
7
+ * value (HTML، پاک‌سازی می‌شود) یا HTML داخل عنصر، label، placeholder، tools="bold italic | link"، min-height، show-count، name، hint، error و disabled.
8
+ * kashi-change با detail { value: HTML، text }.
9
+ */
10
+ export declare class KashiRichText extends HTMLBase {
11
+ static observedAttributes: string[];
12
+ private root;
13
+ private area;
14
+ private bar;
15
+ private html;
16
+ private saved;
17
+ private state;
18
+ private focusTool;
19
+ private key;
20
+ connectedCallback(): void;
21
+ disconnectedCallback(): void;
22
+ attributeChangedCallback(n: string, old: string | null, next: string | null): void;
23
+ /** HTML پاک‌شده */
24
+ get value(): string;
25
+ set value(v: string);
26
+ /** متن ساده */
27
+ get text(): string;
28
+ focus(options?: FocusOptions): void;
29
+ private get tools();
30
+ private build;
31
+ private renderBar;
32
+ private syncTabStops;
33
+ private paintTools;
34
+ private onSelection;
35
+ private exec;
36
+ private run;
37
+ private emitChange;
38
+ private paintFoot;
39
+ private update;
40
+ }
@@ -0,0 +1,375 @@
1
+ // ویرایشگر متن غنی سبک و فارسی.
2
+ import { afterParse, define, emit, esc, HTMLBase, msg, num, syncHidden, uid } from "./base.js";
3
+ import { icon, isRtl } from "./parts.js";
4
+ const DEFAULT_TOOLS = ["bold", "italic", "underline", "strike", "|", "heading", "quote", "bullet", "ordered", "|", "link", "direction", "|", "undo", "clear"];
5
+ const ALLOWED = new Set(["P", "BR", "B", "STRONG", "I", "EM", "U", "S", "STRIKE", "DEL", "A", "UL", "OL", "LI", "H2", "H3", "BLOCKQUOTE", "DIV", "SPAN", "CODE"]);
6
+ const BLOCKS = "p, li, h2, h3, blockquote, div";
7
+ /** پاک‌سازی HTML: فقط برچسب‌های متنی مجاز، پیوندهای http، https و mailto، و ویژگی dir */
8
+ export function sanitizeRichText(html) {
9
+ const tpl = document.createElement("template");
10
+ tpl.innerHTML = html;
11
+ const walk = (node) => {
12
+ for (const child of [...node.childNodes]) {
13
+ if (child.nodeType === 8) {
14
+ child.remove();
15
+ continue;
16
+ }
17
+ if (child.nodeType !== 1)
18
+ continue;
19
+ const el = child;
20
+ if (!ALLOWED.has(el.tagName)) {
21
+ if (/^(SCRIPT|STYLE|IFRAME|OBJECT|EMBED|TEMPLATE|SVG|MATH|HEAD|TITLE|META|LINK)$/i.test(el.tagName))
22
+ el.remove();
23
+ else {
24
+ walk(el);
25
+ el.replaceWith(...el.childNodes);
26
+ }
27
+ continue;
28
+ }
29
+ for (const attr of [...el.attributes]) {
30
+ const keep = (attr.name === "dir" && /^(rtl|ltr|auto)$/.test(attr.value)) || (el.tagName === "A" && attr.name === "href" && /^(https?:|mailto:)/i.test(attr.value.trim()));
31
+ if (!keep)
32
+ el.removeAttribute(attr.name);
33
+ }
34
+ if (el.tagName === "A") {
35
+ if (!el.hasAttribute("href")) {
36
+ el.replaceWith(...el.childNodes);
37
+ continue;
38
+ }
39
+ el.setAttribute("rel", "noopener noreferrer nofollow");
40
+ }
41
+ walk(el);
42
+ }
43
+ };
44
+ walk(tpl.content);
45
+ return tpl.innerHTML;
46
+ }
47
+ const I = (d) => icon(d, 1.8);
48
+ const ICONS = {
49
+ bold: I('<path d="M6 4h5a3 3 0 0 1 0 6H6zm0 6h6a3 3 0 0 1 0 6H6z"/>'),
50
+ italic: I('<path d="M12 4H8.5M11.5 16H8M11 4 9 16"/>'),
51
+ underline: I('<path d="M6 4v5a4 4 0 0 0 8 0V4M5 17h10"/>'),
52
+ strike: I('<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"/>'),
53
+ heading: I('<path d="M5 4v12M13 4v12M5 10h8M15.5 16v-5l-1.5 1"/>'),
54
+ quote: I('<path d="M8 8H5v3h2.5c0 2-1 3-2.5 3.5M15 8h-3v3h2.5c0 2-1 3-2.5 3.5"/>'),
55
+ bullet: I('<path d="M8 5.5h8M8 10h8M8 14.5h8M4.5 5.5h.01M4.5 10h.01M4.5 14.5h.01"/>'),
56
+ ordered: I('<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"/>'),
57
+ link: I('<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"/>'),
58
+ undo: I('<path d="M7 5 4 8l3 3M4 8h8a4 4 0 0 1 0 8H9"/>'),
59
+ clear: I('<path d="M5 4h10M10 4l-2.5 12M4 16l12-12"/>'),
60
+ direction: I('<path d="M9 4h6M13 4v12M9 4v8a3 3 0 0 1-3-3 3 3 0 0 1 3-3M4 14l2 2 2-2"/>'),
61
+ };
62
+ const q = (c) => {
63
+ try {
64
+ return document.queryCommandState(c);
65
+ }
66
+ catch {
67
+ return false;
68
+ }
69
+ };
70
+ /**
71
+ * ویرایشگر متن غنی فارسی: جهت هر بند جدا، نیم‌فاصله با Shift+Space، چسباندن پاک‌شده و نوار ابزار با کلیدهای جهت.
72
+ * value (HTML، پاک‌سازی می‌شود) یا HTML داخل عنصر، label، placeholder، tools="bold italic | link"، min-height، show-count، name، hint، error و disabled.
73
+ * kashi-change با detail { value: HTML، text }.
74
+ */
75
+ export class KashiRichText extends HTMLBase {
76
+ constructor() {
77
+ super(...arguments);
78
+ this.root = null;
79
+ this.html = "";
80
+ this.saved = null;
81
+ this.state = {};
82
+ this.focusTool = 0;
83
+ this.key = uid("kashi-rte");
84
+ this.onSelection = () => {
85
+ const sel = document.getSelection();
86
+ if (!sel || !this.area?.contains(sel.anchorNode))
87
+ return;
88
+ const node = sel.anchorNode instanceof Element ? sel.anchorNode : sel.anchorNode?.parentElement;
89
+ const block = node?.closest(BLOCKS);
90
+ this.state = {
91
+ bold: q("bold"), italic: q("italic"), underline: q("underline"), strike: q("strikeThrough"),
92
+ bullet: q("insertUnorderedList"), ordered: q("insertOrderedList"),
93
+ heading: !!block?.closest("h2, h3"), quote: !!block?.closest("blockquote"),
94
+ link: !!node?.closest("a"), ltr: block?.dir === "ltr",
95
+ };
96
+ this.paintTools();
97
+ };
98
+ }
99
+ connectedCallback() {
100
+ afterParse(() => {
101
+ if (!this.isConnected)
102
+ return;
103
+ if (!this.root) {
104
+ if (!this.html)
105
+ this.html = sanitizeRichText(this.getAttribute("value") ?? this.innerHTML.trim());
106
+ this.build();
107
+ }
108
+ this.update();
109
+ document.addEventListener("selectionchange", this.onSelection);
110
+ });
111
+ }
112
+ disconnectedCallback() {
113
+ document.removeEventListener("selectionchange", this.onSelection);
114
+ }
115
+ attributeChangedCallback(n, old, next) {
116
+ if (!this.root || old === next)
117
+ return;
118
+ if (n === "value")
119
+ this.value = next ?? "";
120
+ else if (n === "tools")
121
+ this.renderBar();
122
+ else
123
+ this.update();
124
+ }
125
+ /** HTML پاک‌شده */
126
+ get value() {
127
+ return this.html;
128
+ }
129
+ set value(v) {
130
+ this.html = sanitizeRichText(String(v ?? ""));
131
+ if (!this.root)
132
+ return;
133
+ if (this.area.innerHTML !== this.html)
134
+ this.area.innerHTML = this.html;
135
+ this.update();
136
+ }
137
+ /** متن ساده */
138
+ get text() {
139
+ return (this.area?.innerText ?? this.area?.textContent ?? "").trim();
140
+ }
141
+ focus(options) {
142
+ this.area?.focus(options);
143
+ }
144
+ get tools() {
145
+ const t = this.getAttribute("tools");
146
+ return t ? t.split(/[\s,]+/).filter(Boolean) : DEFAULT_TOOLS;
147
+ }
148
+ build() {
149
+ const id = this.key;
150
+ const root = document.createElement("div");
151
+ root.innerHTML = `<label class="k-label k-rte__label" id="${id}-label"></label><div class="k-rte__box"><div class="k-rte__bar" role="toolbar" aria-controls="${id}"></div><form class="k-rte__link" hidden><input class="k-rte__link-input" type="url" dir="ltr" value="https://"><button type="submit" class="k-btn k-btn--primary k-btn--xs"></button></form><div id="${id}" class="k-rte__area" role="textbox" aria-multiline="true" aria-describedby="${id}-help" dir="rtl"></div><div class="k-rte__foot"></div></div><div id="${id}-help" class="k-rte__help"></div>`;
152
+ this.replaceChildren(root);
153
+ this.root = root;
154
+ this.area = root.querySelector(".k-rte__area");
155
+ this.bar = root.querySelector(".k-rte__bar");
156
+ this.area.innerHTML = this.html;
157
+ try {
158
+ document.execCommand("defaultParagraphSeparator", false, "p");
159
+ }
160
+ catch { /* */ }
161
+ root.querySelector("label").addEventListener("click", () => this.area.focus());
162
+ this.area.addEventListener("input", () => this.emitChange());
163
+ this.area.addEventListener("blur", () => this.emitChange(false));
164
+ this.area.addEventListener("keydown", (e) => {
165
+ if (e.key === " " && e.shiftKey) {
166
+ e.preventDefault();
167
+ document.execCommand("insertText", false, "‌");
168
+ }
169
+ if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "k") {
170
+ e.preventDefault();
171
+ this.run("link");
172
+ }
173
+ });
174
+ this.area.addEventListener("paste", (e) => {
175
+ e.preventDefault();
176
+ const rich = e.clipboardData?.getData("text/html");
177
+ if (rich)
178
+ document.execCommand("insertHTML", false, sanitizeRichText(rich));
179
+ else
180
+ document.execCommand("insertText", false, e.clipboardData?.getData("text/plain") ?? "");
181
+ this.emitChange();
182
+ });
183
+ this.bar.addEventListener("mousedown", (e) => e.preventDefault());
184
+ this.bar.addEventListener("click", (e) => {
185
+ const b = e.target.closest(".k-rte__tool");
186
+ if (!b)
187
+ return;
188
+ this.focusTool = Number(b.dataset.index);
189
+ this.syncTabStops();
190
+ this.run(b.dataset.tool);
191
+ });
192
+ this.bar.addEventListener("keydown", (e) => {
193
+ if (!["ArrowRight", "ArrowLeft", "Home", "End"].includes(e.key))
194
+ return;
195
+ e.preventDefault();
196
+ const count = this.bar.querySelectorAll(".k-rte__tool").length;
197
+ const rtl = isRtl(this.bar);
198
+ const step = (e.key === "ArrowLeft") === rtl ? 1 : -1;
199
+ this.focusTool = e.key === "Home" ? 0 : e.key === "End" ? count - 1 : Math.max(0, Math.min(count - 1, this.focusTool + step));
200
+ this.syncTabStops();
201
+ this.bar.querySelectorAll(".k-rte__tool")[this.focusTool]?.focus();
202
+ });
203
+ const form = root.querySelector(".k-rte__link");
204
+ const input = form.querySelector("input");
205
+ form.addEventListener("submit", (e) => {
206
+ e.preventDefault();
207
+ e.stopPropagation();
208
+ form.hidden = true;
209
+ const url = input.value.trim();
210
+ if (/^(https?:\/\/|mailto:)\S+$/i.test(url))
211
+ this.exec("createLink", url);
212
+ else
213
+ this.area.focus();
214
+ });
215
+ input.addEventListener("keydown", (e) => {
216
+ if (e.key === "Escape") {
217
+ e.preventDefault();
218
+ e.stopPropagation();
219
+ form.hidden = true;
220
+ this.area.focus();
221
+ }
222
+ else if (e.key === "Enter") {
223
+ // فرم داخلی نباید فرم والد صفحه را ارسال کند
224
+ e.preventDefault();
225
+ form.requestSubmit?.() ?? form.dispatchEvent(new Event("submit", { cancelable: true }));
226
+ }
227
+ });
228
+ this.renderBar();
229
+ }
230
+ renderBar() {
231
+ const tools = this.tools;
232
+ let b = -1;
233
+ this.bar.innerHTML = tools.map((t) => {
234
+ if (t === "|")
235
+ return '<span class="k-rte__sep" aria-hidden="true"></span>';
236
+ if (!ICONS[t])
237
+ return "";
238
+ b++;
239
+ return `<button type="button" class="k-rte__tool" data-tool="${t}" data-index="${b}" tabindex="${b === this.focusTool ? 0 : -1}">${ICONS[t]}</button>`;
240
+ }).join("");
241
+ this.paintTools();
242
+ }
243
+ syncTabStops() {
244
+ this.bar.querySelectorAll(".k-rte__tool").forEach((b, i) => (b.tabIndex = i === this.focusTool ? 0 : -1));
245
+ }
246
+ paintTools() {
247
+ const R = msg().richText;
248
+ const disabled = this.hasAttribute("disabled");
249
+ for (const b of this.bar.querySelectorAll(".k-rte__tool")) {
250
+ const t = b.dataset.tool;
251
+ const label = t === "direction" ? (this.state.ltr ? R.rtl : R.ltr) : t === "link" && this.state.link ? R.unlink : R[t];
252
+ b.setAttribute("aria-label", label);
253
+ b.title = label;
254
+ b.disabled = disabled;
255
+ if (t === "direction")
256
+ b.setAttribute("aria-pressed", String(!!this.state.ltr));
257
+ else if (t !== "link" && t !== "undo" && t !== "clear")
258
+ b.setAttribute("aria-pressed", String(!!this.state[t]));
259
+ }
260
+ }
261
+ exec(cmd, arg) {
262
+ this.area.focus();
263
+ if (this.saved) {
264
+ const sel = document.getSelection();
265
+ sel?.removeAllRanges();
266
+ sel?.addRange(this.saved);
267
+ this.saved = null;
268
+ }
269
+ document.execCommand(cmd, false, arg);
270
+ this.emitChange();
271
+ }
272
+ run(tool) {
273
+ const s = this.state;
274
+ switch (tool) {
275
+ case "bold": return this.exec("bold");
276
+ case "italic": return this.exec("italic");
277
+ case "underline": return this.exec("underline");
278
+ case "strike": return this.exec("strikeThrough");
279
+ case "heading": return this.exec("formatBlock", s.heading ? "<p>" : "<h2>");
280
+ case "quote": return this.exec("formatBlock", s.quote ? "<p>" : "<blockquote>");
281
+ case "bullet": return this.exec("insertUnorderedList");
282
+ case "ordered": return this.exec("insertOrderedList");
283
+ case "undo": return this.exec("undo");
284
+ case "clear": return this.exec("removeFormat");
285
+ case "direction": {
286
+ const sel = document.getSelection();
287
+ const node = sel?.anchorNode;
288
+ const b = (node instanceof Element ? node : node?.parentElement)?.closest(BLOCKS);
289
+ if (b && this.area.contains(b) && b !== this.area) {
290
+ b.dir = b.dir === "ltr" ? "rtl" : "ltr";
291
+ this.state.ltr = b.dir === "ltr";
292
+ this.paintTools();
293
+ this.emitChange();
294
+ }
295
+ return;
296
+ }
297
+ case "link": {
298
+ if (s.link)
299
+ return this.exec("unlink");
300
+ const sel = document.getSelection();
301
+ if (sel && sel.rangeCount && this.area.contains(sel.anchorNode))
302
+ this.saved = sel.getRangeAt(0).cloneRange();
303
+ const form = this.root.querySelector(".k-rte__link");
304
+ form.hidden = false;
305
+ const input = form.querySelector("input");
306
+ input.value = "https://";
307
+ input.focus();
308
+ input.select();
309
+ return;
310
+ }
311
+ }
312
+ }
313
+ emitChange(fire = true) {
314
+ const raw = this.area.innerHTML;
315
+ const out = sanitizeRichText(raw === "<p><br></p>" || raw === "<br>" ? "" : raw);
316
+ const changed = out !== this.html;
317
+ this.html = out;
318
+ this.paintFoot();
319
+ if (fire && changed)
320
+ emit(this, "kashi-change", { value: out, text: this.text });
321
+ }
322
+ paintFoot() {
323
+ const R = msg().richText;
324
+ const text = this.area.innerText ?? this.area.textContent ?? "";
325
+ const words = text.trim() ? text.trim().split(/\s+/).length : 0;
326
+ const foot = this.root.querySelector(".k-rte__foot");
327
+ foot.hidden = this.getAttribute("show-count") === "false";
328
+ foot.innerHTML = `<span>${esc(R.words(num(this, words)))}</span><span aria-hidden="true">·</span><span>${esc(R.chars(num(this, text.replace(/\n/g, "").length)))}</span><span class="k-rte__tip">${esc(R.zwnj)}</span>`;
329
+ const empty = !text.trim() && !/<(img|li|blockquote)/.test(this.html);
330
+ this.area.toggleAttribute("data-empty", empty);
331
+ syncHidden(this, this.getAttribute("name"), this.html);
332
+ }
333
+ update() {
334
+ const R = msg().richText;
335
+ const root = this.root;
336
+ const error = this.getAttribute("error"), hint = this.getAttribute("hint");
337
+ const disabled = this.hasAttribute("disabled");
338
+ const label = this.getAttribute("label");
339
+ root.className = "k-rte";
340
+ root.toggleAttribute("data-disabled", disabled);
341
+ root.toggleAttribute("data-invalid", !!error);
342
+ const l = root.querySelector(".k-rte__label");
343
+ l.textContent = label ?? "";
344
+ l.hidden = !label;
345
+ this.bar.setAttribute("aria-label", R.toolbar);
346
+ const a = this.area;
347
+ if (label) {
348
+ a.setAttribute("aria-labelledby", `${this.key}-label`);
349
+ a.removeAttribute("aria-label");
350
+ }
351
+ else {
352
+ a.removeAttribute("aria-labelledby");
353
+ a.setAttribute("aria-label", this.getAttribute("aria-label") ?? R.label);
354
+ }
355
+ if (error)
356
+ a.setAttribute("aria-invalid", "true");
357
+ else
358
+ a.removeAttribute("aria-invalid");
359
+ if (disabled)
360
+ a.setAttribute("aria-disabled", "true");
361
+ else
362
+ a.removeAttribute("aria-disabled");
363
+ a.contentEditable = disabled ? "false" : "true";
364
+ a.dataset.placeholder = this.getAttribute("placeholder") ?? R.placeholder;
365
+ a.style.minBlockSize = this.getAttribute("min-height") ?? "8rem";
366
+ const form = root.querySelector(".k-rte__link");
367
+ form.querySelector("input").setAttribute("aria-label", R.linkUrl);
368
+ form.querySelector("button").textContent = R.apply;
369
+ root.querySelector(".k-rte__help").innerHTML = error ? `<p class="k-hint k-hint--error">${esc(error)}</p>` : hint ? `<p class="k-hint">${esc(hint)}</p>` : `<span class="k-sr-only">${esc(R.zwnj)}</span>`;
370
+ this.paintTools();
371
+ this.paintFoot();
372
+ }
373
+ }
374
+ KashiRichText.observedAttributes = ["label", "aria-label", "placeholder", "tools", "min-height", "show-count", "name", "hint", "error", "disabled", "value"];
375
+ define("kashi-rich-text", KashiRichText, "block");