@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.
- package/README.md +6 -1
- package/dist/base.js +4 -0
- package/dist/buttons.d.ts +82 -0
- package/dist/buttons.js +487 -0
- package/dist/cards.d.ts +30 -0
- package/dist/cards.js +183 -0
- package/dist/cdn/{appointment-wMGBoHw9.js → appointment-DOXBUwIU.js} +1 -1
- package/dist/cdn/{base-Dg1Mb8Jk.js → base-D4tCOysh.js} +1 -1
- package/dist/cdn/{basic-B5ZxgagA.js → basic-DuY4RslZ.js} +1 -1
- package/dist/cdn/buttons-zhSdiaXr.js +1 -0
- package/dist/cdn/calendar-BulPeVAJ.js +16 -0
- package/dist/cdn/card-BKiwJF34.js +1 -0
- package/dist/cdn/cards-DKarXHsC.js +1 -0
- package/dist/cdn/charts-ETYOAJyB.js +1 -0
- package/dist/cdn/chat-D5ZIMnNp.js +4 -0
- package/dist/cdn/choice-DBvC2Puo.js +1 -0
- package/dist/cdn/{combobox-CBT7yp94.js → combobox-BGuPAAt3.js} +1 -1
- package/dist/cdn/{commerce-CsyixnVK.js → commerce-SzWdpWJG.js} +1 -1
- package/dist/cdn/content-BgfBfy8j.js +1 -0
- package/dist/cdn/controls--OMZkJYe.js +1 -0
- package/dist/cdn/display-BfYWAjNu.js +1 -0
- package/dist/cdn/{fields-Cx84-qz1.js → fields-B-jTUQiI.js} +1 -1
- package/dist/cdn/forms-DgRiYmdV.js +1 -0
- package/dist/cdn/{holidays-DO82gXhM.js → holidays-Cu6IfbTL.js} +1 -1
- package/dist/cdn/hours-CeiVqPKD.js +1 -0
- package/dist/cdn/inputs-BkJ70Xkc.js +1 -0
- package/dist/cdn/kashi-elements.js +1 -1
- package/dist/cdn/legal-id-Mt8FX0fV.js +1 -0
- package/dist/cdn/{map-DlpA916P.js → map-TfSt3CjL.js} +2 -2
- package/dist/cdn/media-BRBINvzU.js +1 -0
- package/dist/cdn/{menu-CqTvk8Ok.js → menu-DTNVFXrb.js} +1 -1
- package/dist/cdn/money-CjGI2VIQ.js +1 -0
- package/dist/cdn/{nav-BHv7H1Fy.js → nav-CT5RVOzy.js} +1 -1
- package/dist/cdn/{overlay-BIEEJ4Sh.js → overlay-DC5-I6hM.js} +1 -1
- package/dist/cdn/parts-5fVaWtRe.js +1 -0
- package/dist/cdn/pickers-BwDRsDRo.js +1 -0
- package/dist/cdn/relative-OC1fV3Xh.js +1 -0
- package/dist/cdn/rich-text-CS6xEim6.js +1 -0
- package/dist/cdn/sheets-eVMx4d-5.js +1 -0
- package/dist/cdn/{table-B5XwDDS9.js → table-tgB4iwcM.js} +1 -1
- package/dist/cdn/{text-Bml-pVjo.js → text-C6fzEBBh.js} +1 -1
- package/dist/cdn/{time-DrXgFeQy.js → time-CkqqUKJv.js} +1 -1
- package/dist/cdn/{time-BQsTSvql.js → time-CwOYrtK-.js} +1 -1
- package/dist/cdn/validate-Dr2f6i6s.js +1 -0
- package/dist/cdn/work-DoNAKgVU.js +1 -0
- package/dist/cdn.js +11 -0
- package/dist/chat.d.ts +127 -0
- package/dist/chat.js +734 -0
- package/dist/choice.d.ts +98 -0
- package/dist/choice.js +597 -0
- package/dist/content.d.ts +164 -0
- package/dist/content.js +726 -0
- package/dist/hours.d.ts +29 -0
- package/dist/hours.js +179 -0
- package/dist/index.d.ts +64 -2
- package/dist/index.js +22 -1
- package/dist/manifest.json +843 -1
- package/dist/media.d.ts +51 -0
- package/dist/media.js +363 -0
- package/dist/parts.d.ts +31 -0
- package/dist/parts.js +114 -0
- package/dist/qr.d.ts +7 -0
- package/dist/qr.js +271 -0
- package/dist/rich-text.d.ts +40 -0
- package/dist/rich-text.js +375 -0
- package/dist/sheets.d.ts +128 -0
- package/dist/sheets.js +661 -0
- package/dist/validate.d.ts +40 -0
- package/dist/validate.js +224 -0
- package/dist/work.d.ts +117 -0
- package/dist/work.js +895 -0
- package/package.json +4 -4
- package/dist/cdn/calendar-Cjp5Rqer.js +0 -16
- package/dist/cdn/charts-DvQ4OwdS.js +0 -1
- package/dist/cdn/controls-B-s4IF_4.js +0 -1
- package/dist/cdn/display-MorJMDEF.js +0 -1
- package/dist/cdn/forms-CQeP9iiW.js +0 -1
- package/dist/cdn/inputs-Bqcs9Xy7.js +0 -1
- package/dist/cdn/pickers-BT9VPT4o.js +0 -1
package/dist/chat.js
ADDED
|
@@ -0,0 +1,734 @@
|
|
|
1
|
+
// رابط گفتگو و دستیار هوش مصنوعی: ظرف گفتگو، حباب پیام، «در حال نوشتن»، کادر نوشتن، متن کلمهبهکلمه و نمایش کد.
|
|
2
|
+
import { formatRelative } from "@kashi-ui/persian";
|
|
3
|
+
import { afterParse, bool, define, digitsOf, emit, esc, HTMLBase, lang, localeDigits, msg, num, uid } from "./base.js";
|
|
4
|
+
import { copyText, icon, numAttr, reduced, takeSlot, toDate, unslotted } from "./parts.js";
|
|
5
|
+
const ARROW_DOWN = icon('<path d="M10 4v12m0 0-4.5-4.5M10 16l4.5-4.5"/>', 1.9);
|
|
6
|
+
// ---------- گفتگو ----------
|
|
7
|
+
/**
|
|
8
|
+
* ظرف پیامها: ناحیهٔ log که پیام تازه را برای صفحهخوان میخواند، با پیام تازه پایین میماند (مگر کاربر بالا رفته باشد)
|
|
9
|
+
* و دکمهٔ «رفتن به آخرین پیام» نشان میدهد. فرزندان kashi-chat-message، kashi-typing-indicator یا هر HTML دیگر.
|
|
10
|
+
*/
|
|
11
|
+
export class KashiChat extends HTMLBase {
|
|
12
|
+
constructor() {
|
|
13
|
+
super(...arguments);
|
|
14
|
+
this.scroller = null;
|
|
15
|
+
this.stick = true;
|
|
16
|
+
this.mo = null;
|
|
17
|
+
this.ro = null;
|
|
18
|
+
}
|
|
19
|
+
connectedCallback() {
|
|
20
|
+
afterParse(() => {
|
|
21
|
+
if (!this.isConnected)
|
|
22
|
+
return;
|
|
23
|
+
if (!this.scroller)
|
|
24
|
+
this.build();
|
|
25
|
+
this.update();
|
|
26
|
+
this.observe();
|
|
27
|
+
this.toEnd();
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
disconnectedCallback() {
|
|
31
|
+
this.mo?.disconnect();
|
|
32
|
+
this.ro?.disconnect();
|
|
33
|
+
this.mo = this.ro = null;
|
|
34
|
+
}
|
|
35
|
+
attributeChangedCallback() {
|
|
36
|
+
if (this.scroller)
|
|
37
|
+
this.update();
|
|
38
|
+
}
|
|
39
|
+
/** ظرف پیامها؛ پیام تازه را اینجا append کنید (یا روی خود عنصر، که خودکار منتقل میشود) */
|
|
40
|
+
get thread() {
|
|
41
|
+
return this.scroller;
|
|
42
|
+
}
|
|
43
|
+
/** رفتن به آخرین پیام */
|
|
44
|
+
scrollToEnd(smooth = true) {
|
|
45
|
+
this.stick = true;
|
|
46
|
+
this.scroller?.scrollTo({ top: this.scroller.scrollHeight, behavior: smooth ? "smooth" : "auto" });
|
|
47
|
+
}
|
|
48
|
+
build() {
|
|
49
|
+
const box = document.createElement("div");
|
|
50
|
+
box.className = "k-chat";
|
|
51
|
+
box.innerHTML = `<div class="k-chat__scroll" role="log" aria-live="polite" tabindex="0"></div><button type="button" class="k-chat__jump" tabindex="-1" aria-hidden="true">${ARROW_DOWN}</button>`;
|
|
52
|
+
this.scroller = box.querySelector(".k-chat__scroll");
|
|
53
|
+
this.jump = box.querySelector(".k-chat__jump");
|
|
54
|
+
this.scroller.append(...this.childNodes);
|
|
55
|
+
this.append(box);
|
|
56
|
+
this.scroller.addEventListener("scroll", () => {
|
|
57
|
+
const el = this.scroller;
|
|
58
|
+
const near = el.scrollHeight - el.scrollTop - el.clientHeight < 48;
|
|
59
|
+
this.stick = near;
|
|
60
|
+
this.jump.toggleAttribute("data-show", !near);
|
|
61
|
+
this.jump.tabIndex = near ? -1 : 0;
|
|
62
|
+
this.jump.setAttribute("aria-hidden", String(near));
|
|
63
|
+
});
|
|
64
|
+
this.jump.addEventListener("click", () => this.scrollToEnd());
|
|
65
|
+
}
|
|
66
|
+
observe() {
|
|
67
|
+
if (this.mo || typeof MutationObserver === "undefined")
|
|
68
|
+
return;
|
|
69
|
+
// پیامی که بعداً روی خود عنصر اضافه شود به ظرف منتقل میشود
|
|
70
|
+
this.mo = new MutationObserver(() => {
|
|
71
|
+
const stray = [...this.childNodes].filter((n) => n !== this.scroller?.parentElement);
|
|
72
|
+
if (stray.length)
|
|
73
|
+
this.scroller.append(...stray);
|
|
74
|
+
this.toEnd();
|
|
75
|
+
});
|
|
76
|
+
this.mo.observe(this, { childList: true, subtree: true, characterData: true });
|
|
77
|
+
if (typeof ResizeObserver !== "undefined") {
|
|
78
|
+
this.ro = new ResizeObserver(() => this.toEnd());
|
|
79
|
+
this.ro.observe(this.scroller);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
toEnd() {
|
|
83
|
+
if (bool(this, "auto-scroll", true) && this.stick && this.scroller)
|
|
84
|
+
this.scroller.scrollTop = this.scroller.scrollHeight;
|
|
85
|
+
}
|
|
86
|
+
update() {
|
|
87
|
+
const M = msg();
|
|
88
|
+
this.scroller.setAttribute("aria-label", this.getAttribute("label") ?? M.chat.thread);
|
|
89
|
+
this.jump.setAttribute("aria-label", M.chat.scrollDown);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
KashiChat.observedAttributes = ["label", "auto-scroll"];
|
|
93
|
+
// ---------- پیام ----------
|
|
94
|
+
const svg = (d, w = 1.7) => icon(d, w);
|
|
95
|
+
const STATUS_ICON = {
|
|
96
|
+
sending: svg('<circle cx="10" cy="10" r="6.5"/><path d="M10 6.5V10l2 1.5"/>'),
|
|
97
|
+
failed: svg('<circle cx="10" cy="10" r="7"/><path d="M10 6.5v4M10 13.5h.01"/>'),
|
|
98
|
+
sent: svg('<path d="m4.5 10.5 3 3 6-7"/>', 1.9),
|
|
99
|
+
delivered: svg('<path d="m2.5 10.5 3 3 6-7"/><path d="m9 13.2.3.3 6-7"/>', 1.9),
|
|
100
|
+
read: svg('<path d="m2.5 10.5 3 3 6-7"/><path d="m9 13.2.3.3 6-7"/>', 1.9),
|
|
101
|
+
};
|
|
102
|
+
const COPY = svg('<rect x="7" y="7" width="10" height="10" rx="2"/><path d="M13 7V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h2"/>');
|
|
103
|
+
const CHECK = svg('<path d="m5 10.5 3.2 3L15 7"/>', 2);
|
|
104
|
+
const RETRY = svg('<path d="M4 10a6 6 0 1 0 1.8-4.3"/><path d="M4 3.5V7h3.5"/>');
|
|
105
|
+
const UP = svg('<path d="M6.5 9 9.5 3.5a1.6 1.6 0 0 1 2.9 1.2L11.5 8h3.8a1.5 1.5 0 0 1 1.5 1.8l-1.2 5.5a1.5 1.5 0 0 1-1.5 1.2H6.5M6.5 9v7.5M6.5 9H4v7.5h2.5"/>');
|
|
106
|
+
const DOWN = svg('<path d="M13.5 11 10.5 16.5a1.6 1.6 0 0 1-2.9-1.2L8.5 12H4.7a1.5 1.5 0 0 1-1.5-1.8l1.2-5.5A1.5 1.5 0 0 1 5.9 3.5h7.6M13.5 11V3.5m0 7.5H16V3.5h-2.5"/>');
|
|
107
|
+
const ISO = /^\d{4}-\d{2}-\d{2}T/;
|
|
108
|
+
/**
|
|
109
|
+
* حباب پیام: from (user، assistant یا system)، name، time (ISO به شکل نسبی یا هر متن)، status و edited.
|
|
110
|
+
* copyable دکمهٔ کپی، retry دکمهٔ «تلاش دوباره» (kashi-retry)، feedback دکمههای پسند (kashi-feedback با detail.value).
|
|
111
|
+
* slot="avatar" آواتار و slot="actions" دکمههای دلخواه. جهت متن هر پیام خودکار است.
|
|
112
|
+
*/
|
|
113
|
+
export class KashiChatMessage extends HTMLBase {
|
|
114
|
+
constructor() {
|
|
115
|
+
super(...arguments);
|
|
116
|
+
this.box = null;
|
|
117
|
+
this.avatar = [];
|
|
118
|
+
this.extra = [];
|
|
119
|
+
}
|
|
120
|
+
connectedCallback() {
|
|
121
|
+
afterParse(() => {
|
|
122
|
+
if (!this.isConnected)
|
|
123
|
+
return;
|
|
124
|
+
if (!this.box)
|
|
125
|
+
this.build();
|
|
126
|
+
this.update();
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
disconnectedCallback() {
|
|
130
|
+
clearTimeout(this.timer);
|
|
131
|
+
}
|
|
132
|
+
attributeChangedCallback(_n, old, next) {
|
|
133
|
+
if (this.box && old !== next)
|
|
134
|
+
this.update();
|
|
135
|
+
}
|
|
136
|
+
build() {
|
|
137
|
+
this.avatar = takeSlot(this, "avatar");
|
|
138
|
+
this.extra = takeSlot(this, "actions");
|
|
139
|
+
this.box = document.createElement("div");
|
|
140
|
+
this.bubble = document.createElement("div");
|
|
141
|
+
this.bubble.className = "k-msg__bubble";
|
|
142
|
+
this.bubble.dir = "auto";
|
|
143
|
+
this.bubble.append(...unslotted(this));
|
|
144
|
+
this.replaceChildren(this.box);
|
|
145
|
+
this.box.addEventListener("click", (e) => this.onClick(e));
|
|
146
|
+
}
|
|
147
|
+
async onClick(e) {
|
|
148
|
+
const b = e.target.closest("[data-act]");
|
|
149
|
+
if (!b)
|
|
150
|
+
return;
|
|
151
|
+
const act = b.dataset.act;
|
|
152
|
+
if (act === "copy") {
|
|
153
|
+
if (!(await copyText(this.getAttribute("copy-text") ?? this.bubble.innerText ?? this.bubble.textContent ?? "")))
|
|
154
|
+
return;
|
|
155
|
+
const C = msg().chat;
|
|
156
|
+
b.setAttribute("data-done", "");
|
|
157
|
+
b.innerHTML = CHECK;
|
|
158
|
+
b.setAttribute("aria-label", C.copied);
|
|
159
|
+
this.box.querySelector(".k-msg__actions > .k-sr-only").textContent = C.copied;
|
|
160
|
+
clearTimeout(this.timer);
|
|
161
|
+
this.timer = setTimeout(() => this.update(), 2000);
|
|
162
|
+
emit(this, "kashi-copy", {});
|
|
163
|
+
}
|
|
164
|
+
else if (act === "retry")
|
|
165
|
+
emit(this, "kashi-retry", {});
|
|
166
|
+
else if (act === "up" || act === "down") {
|
|
167
|
+
const next = this.getAttribute("rated") === act ? null : act;
|
|
168
|
+
if (next)
|
|
169
|
+
this.setAttribute("rated", next);
|
|
170
|
+
else
|
|
171
|
+
this.removeAttribute("rated");
|
|
172
|
+
emit(this, "kashi-feedback", { value: next });
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
update() {
|
|
176
|
+
const C = msg().chat;
|
|
177
|
+
const box = this.box;
|
|
178
|
+
const from = this.getAttribute("from") ?? "assistant";
|
|
179
|
+
if (from === "system") {
|
|
180
|
+
box.className = "k-chat__system";
|
|
181
|
+
box.removeAttribute("data-from");
|
|
182
|
+
box.replaceChildren(...this.bubble.childNodes.length ? [...this.bubble.childNodes] : []);
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
if (box.className === "k-chat__system")
|
|
186
|
+
this.bubble.append(...box.childNodes);
|
|
187
|
+
box.className = "k-msg";
|
|
188
|
+
box.dataset.from = from;
|
|
189
|
+
const status = this.getAttribute("status");
|
|
190
|
+
if (status)
|
|
191
|
+
box.dataset.status = status;
|
|
192
|
+
else
|
|
193
|
+
delete box.dataset.status;
|
|
194
|
+
const name = this.getAttribute("name");
|
|
195
|
+
const who = name ?? (from === "user" ? C.you : C.assistant);
|
|
196
|
+
const timeAttr = this.getAttribute("time");
|
|
197
|
+
const d = timeAttr && ISO.test(timeAttr) ? toDate(timeAttr) : null;
|
|
198
|
+
const timeText = d ? formatRelative(d, { locale: lang(), digits: digitsOf(this) }) : timeAttr;
|
|
199
|
+
const edited = bool(this, "edited");
|
|
200
|
+
const rated = this.getAttribute("rated");
|
|
201
|
+
const copyable = bool(this, "copyable") || this.hasAttribute("copy-text");
|
|
202
|
+
const actions = copyable || bool(this, "retry") || bool(this, "feedback") || this.extra.length;
|
|
203
|
+
const main = document.createElement("div");
|
|
204
|
+
main.className = "k-msg__main";
|
|
205
|
+
main.innerHTML = `${name ? `<div class="k-msg__name">${esc(name)}</div>` : `<span class="k-sr-only">${esc(who)}: </span>`}`;
|
|
206
|
+
main.append(this.bubble);
|
|
207
|
+
if (timeText || status || edited) {
|
|
208
|
+
main.insertAdjacentHTML("beforeend", `<div class="k-msg__meta">${edited ? `<span>${esc(C.edited)}</span>` : ""}${timeText ? `<time${d ? ` datetime="${d.toISOString()}"` : ""}>${esc(timeText)}</time>` : ""}${status ? `<span class="k-msg__status" data-status="${esc(status)}" role="img" aria-label="${esc(C[status] ?? status)}">${STATUS_ICON[status] ?? ""}</span>` : ""}</div>`);
|
|
209
|
+
}
|
|
210
|
+
if (actions) {
|
|
211
|
+
const a = document.createElement("div");
|
|
212
|
+
a.className = "k-msg__actions";
|
|
213
|
+
a.setAttribute("role", "group");
|
|
214
|
+
a.setAttribute("aria-label", C.actions);
|
|
215
|
+
a.innerHTML = `${copyable ? `<button type="button" class="k-msg__action" data-act="copy" aria-label="${esc(C.copy)}">${COPY}</button>` : ""}${bool(this, "retry") ? `<button type="button" class="k-msg__action" data-act="retry" aria-label="${esc(C.retry)}">${RETRY}</button>` : ""}${bool(this, "feedback") ? `<button type="button" class="k-msg__action" data-act="up" aria-label="${esc(C.like)}" aria-pressed="${rated === "up"}">${UP}</button><button type="button" class="k-msg__action" data-act="down" aria-label="${esc(C.dislike)}" aria-pressed="${rated === "down"}">${DOWN}</button>` : ""}`;
|
|
216
|
+
a.append(...this.extra);
|
|
217
|
+
a.insertAdjacentHTML("beforeend", '<span class="k-sr-only" aria-live="polite"></span>');
|
|
218
|
+
main.append(a);
|
|
219
|
+
}
|
|
220
|
+
const focused = box.contains(document.activeElement) ? document.activeElement.dataset.act : undefined;
|
|
221
|
+
box.replaceChildren();
|
|
222
|
+
if (this.avatar.length) {
|
|
223
|
+
const av = document.createElement("div");
|
|
224
|
+
av.className = "k-msg__avatar";
|
|
225
|
+
av.append(...this.avatar);
|
|
226
|
+
box.append(av);
|
|
227
|
+
}
|
|
228
|
+
box.append(main);
|
|
229
|
+
if (focused)
|
|
230
|
+
box.querySelector(`[data-act="${focused}"]`)?.focus();
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
KashiChatMessage.observedAttributes = ["from", "name", "time", "status", "edited", "copyable", "copy-text", "retry", "feedback", "rated"];
|
|
234
|
+
/** نشانگر «در حال نوشتن…» با سه نقطهٔ موجی؛ name نام نویسنده و show-label متن کنار نقطهها */
|
|
235
|
+
export class KashiTypingIndicator extends HTMLBase {
|
|
236
|
+
connectedCallback() {
|
|
237
|
+
this.render();
|
|
238
|
+
}
|
|
239
|
+
attributeChangedCallback() {
|
|
240
|
+
if (this.isConnected)
|
|
241
|
+
this.render();
|
|
242
|
+
}
|
|
243
|
+
render() {
|
|
244
|
+
const name = this.getAttribute("name");
|
|
245
|
+
const text = name ? msg().chat.typing(name) : msg().chat.typingShort;
|
|
246
|
+
this.innerHTML = `<div class="k-typing" role="status"><span class="k-typing__dots" aria-hidden="true"><i></i><i></i><i></i></span>${bool(this, "show-label") ? `<span class="k-typing__label">${esc(text)}…</span>` : `<span class="k-sr-only">${esc(text)}</span>`}</div>`;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
KashiTypingIndicator.observedAttributes = ["name", "show-label"];
|
|
250
|
+
// ---------- کادر نوشتن ----------
|
|
251
|
+
const CLIP = icon('<path d="m15.5 9.5-5.6 5.6a3.5 3.5 0 0 1-5-5l6-6a2.3 2.3 0 0 1 3.3 3.3l-6 6a1.2 1.2 0 0 1-1.7-1.7l5.5-5.5"/>', 1.8);
|
|
252
|
+
const SEND = icon('<path d="M10 16V4m0 0L5 9m5-5 5 5"/>', 1.8);
|
|
253
|
+
const STOP = '<svg viewBox="0 0 20 20" aria-hidden="true"><rect x="6" y="6" width="8" height="8" rx="1.5" fill="currentColor"/></svg>';
|
|
254
|
+
const X = icon('<path d="M6 6l8 8M14 6l-8 8"/>', 1.8);
|
|
255
|
+
const DOC = icon('<path d="M11.5 3H6a1.5 1.5 0 0 0-1.5 1.5v11A1.5 1.5 0 0 0 6 17h8a1.5 1.5 0 0 0 1.5-1.5V7z"/><path d="M11.5 3v4h4"/>', 1.8);
|
|
256
|
+
/** حجم فایل به زبان فعلی */
|
|
257
|
+
export function formatBytes(bytes) {
|
|
258
|
+
const units = msg().fileUpload.units;
|
|
259
|
+
let v = bytes, i = 0;
|
|
260
|
+
while (v >= 1024 && i < units.length - 1) {
|
|
261
|
+
v /= 1024;
|
|
262
|
+
i++;
|
|
263
|
+
}
|
|
264
|
+
const n = i === 0 ? String(v) : v.toFixed(v < 10 ? 1 : 0).replace(/\.0$/, "");
|
|
265
|
+
return `${localeDigits() === "fa" ? n.replace(/\d/g, (d) => "۰۱۲۳۴۵۶۷۸۹"[+d]).replace(".", "٫") : n} ${units[i]}`;
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* کادر نوشتن پیام: بلند شدن خودکار تا max-rows، Enter ارسال و Shift+Enter خط تازه (هنگام تایپ با IME ارسال نمیکند)،
|
|
269
|
+
* پیوست با attach (یا accept مثل "image/*,.pdf") و چسباندن تصویر، و streaming که دکمه را «توقف» میکند.
|
|
270
|
+
* رویدادها: kashi-send با detail { text, files }، kashi-stop و kashi-change. slot="tools" دکمههای کنار پیوست.
|
|
271
|
+
*/
|
|
272
|
+
export class KashiChatComposer extends HTMLBase {
|
|
273
|
+
constructor() {
|
|
274
|
+
super(...arguments);
|
|
275
|
+
this.box = null;
|
|
276
|
+
this.files = [];
|
|
277
|
+
this.urls = [];
|
|
278
|
+
this.error = "";
|
|
279
|
+
this.key = uid("kashi-composer");
|
|
280
|
+
this.initial = null;
|
|
281
|
+
}
|
|
282
|
+
connectedCallback() {
|
|
283
|
+
afterParse(() => {
|
|
284
|
+
if (!this.isConnected)
|
|
285
|
+
return;
|
|
286
|
+
if (!this.box)
|
|
287
|
+
this.build();
|
|
288
|
+
this.update();
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
disconnectedCallback() {
|
|
292
|
+
for (const u of this.urls)
|
|
293
|
+
if (u)
|
|
294
|
+
URL.revokeObjectURL(u);
|
|
295
|
+
}
|
|
296
|
+
attributeChangedCallback(n, old, next) {
|
|
297
|
+
if (!this.box || old === next)
|
|
298
|
+
return;
|
|
299
|
+
if (n === "value")
|
|
300
|
+
this.value = next ?? "";
|
|
301
|
+
else
|
|
302
|
+
this.update();
|
|
303
|
+
}
|
|
304
|
+
get value() {
|
|
305
|
+
return this.box ? this.area.value : (this.initial ?? this.getAttribute("value") ?? "");
|
|
306
|
+
}
|
|
307
|
+
set value(v) {
|
|
308
|
+
this.initial = String(v ?? "");
|
|
309
|
+
if (!this.box)
|
|
310
|
+
return;
|
|
311
|
+
this.area.value = this.initial;
|
|
312
|
+
this.paint();
|
|
313
|
+
}
|
|
314
|
+
/** پیوستهای فعلی */
|
|
315
|
+
get attachments() {
|
|
316
|
+
return [...this.files];
|
|
317
|
+
}
|
|
318
|
+
focus(options) {
|
|
319
|
+
this.area?.focus(options);
|
|
320
|
+
}
|
|
321
|
+
build() {
|
|
322
|
+
const tools = takeSlot(this, "tools");
|
|
323
|
+
const box = document.createElement("div");
|
|
324
|
+
box.innerHTML = `<ul class="k-composer__files" hidden></ul><textarea class="k-composer__input" rows="1" dir="auto"></textarea><div class="k-composer__bar"><button type="button" class="k-composer__tool" data-act="attach">${CLIP}</button><input type="file" hidden><span class="k-composer__count" hidden></span><button type="button" class="k-composer__send" data-act="send"></button></div><p class="k-hint k-hint--error k-composer__error" id="${this.key}-err" role="alert" hidden></p><p class="k-composer__hint" id="${this.key}-hint" hidden></p>`;
|
|
325
|
+
this.area = box.querySelector("textarea");
|
|
326
|
+
this.picker = box.querySelector("input[type=file]");
|
|
327
|
+
this.area.value = this.initial ?? this.getAttribute("value") ?? "";
|
|
328
|
+
box.querySelector(".k-composer__count").before(...tools);
|
|
329
|
+
this.replaceChildren(box);
|
|
330
|
+
this.box = box;
|
|
331
|
+
this.area.addEventListener("input", () => {
|
|
332
|
+
this.paint();
|
|
333
|
+
emit(this, "kashi-change", { value: this.area.value });
|
|
334
|
+
});
|
|
335
|
+
this.area.addEventListener("keydown", (e) => {
|
|
336
|
+
if (e.key === "Enter" && !e.shiftKey && !e.isComposing && e.keyCode !== 229) {
|
|
337
|
+
e.preventDefault();
|
|
338
|
+
this.send();
|
|
339
|
+
}
|
|
340
|
+
});
|
|
341
|
+
this.area.addEventListener("paste", (e) => {
|
|
342
|
+
if (!this.hasAttribute("attach"))
|
|
343
|
+
return;
|
|
344
|
+
const pasted = [...(e.clipboardData?.files ?? [])];
|
|
345
|
+
if (pasted.length) {
|
|
346
|
+
e.preventDefault();
|
|
347
|
+
this.add(pasted);
|
|
348
|
+
}
|
|
349
|
+
});
|
|
350
|
+
this.picker.addEventListener("change", () => {
|
|
351
|
+
this.add([...(this.picker.files ?? [])]);
|
|
352
|
+
this.picker.value = "";
|
|
353
|
+
});
|
|
354
|
+
box.addEventListener("click", (e) => {
|
|
355
|
+
const b = e.target.closest("button");
|
|
356
|
+
if (!b)
|
|
357
|
+
return;
|
|
358
|
+
if (b.dataset.act === "attach")
|
|
359
|
+
this.picker.click();
|
|
360
|
+
else if (b.dataset.act === "send")
|
|
361
|
+
this.send();
|
|
362
|
+
else if (b.dataset.act === "stop")
|
|
363
|
+
emit(this, "kashi-stop", {});
|
|
364
|
+
else if (b.dataset.remove !== undefined) {
|
|
365
|
+
const i = Number(b.dataset.remove);
|
|
366
|
+
this.files.splice(i, 1);
|
|
367
|
+
this.renderFiles();
|
|
368
|
+
this.area.focus();
|
|
369
|
+
}
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
add(list) {
|
|
373
|
+
const C = msg().composer;
|
|
374
|
+
const maxSize = numAttr(this, "max-size");
|
|
375
|
+
const maxFiles = numAttr(this, "max-files", 5);
|
|
376
|
+
this.error = "";
|
|
377
|
+
const ok = [];
|
|
378
|
+
for (const f of list) {
|
|
379
|
+
if (maxSize && f.size > maxSize)
|
|
380
|
+
this.error = C.tooLarge(f.name, formatBytes(maxSize));
|
|
381
|
+
else
|
|
382
|
+
ok.push(f);
|
|
383
|
+
}
|
|
384
|
+
const next = [...this.files, ...ok];
|
|
385
|
+
if (next.length > maxFiles)
|
|
386
|
+
this.error = C.tooMany(num(this, maxFiles));
|
|
387
|
+
this.files = next.slice(0, maxFiles);
|
|
388
|
+
this.renderFiles();
|
|
389
|
+
}
|
|
390
|
+
renderFiles() {
|
|
391
|
+
const C = msg().composer;
|
|
392
|
+
for (const u of this.urls)
|
|
393
|
+
if (u)
|
|
394
|
+
URL.revokeObjectURL(u);
|
|
395
|
+
this.urls = this.files.map((f) => (f.type.startsWith("image/") && typeof URL.createObjectURL === "function" ? URL.createObjectURL(f) : ""));
|
|
396
|
+
const ul = this.box.querySelector(".k-composer__files");
|
|
397
|
+
ul.hidden = !this.files.length;
|
|
398
|
+
ul.setAttribute("aria-label", C.attachments);
|
|
399
|
+
ul.innerHTML = this.files.map((f, i) => `<li class="k-composer__file">${this.urls[i] ? `<img src="${esc(this.urls[i])}" alt="" class="k-composer__thumb">` : `<span class="k-composer__thumb">${DOC}</span>`}<span class="k-composer__file-text"><span class="k-composer__file-name" dir="auto">${esc(f.name)}</span><span class="k-composer__file-size">${esc(formatBytes(f.size))}</span></span><button type="button" class="k-composer__remove" data-remove="${i}" aria-label="${esc(C.removeAttachment(f.name))}">${X}</button></li>`).join("");
|
|
400
|
+
this.paint();
|
|
401
|
+
}
|
|
402
|
+
canSend() {
|
|
403
|
+
const text = this.area.value;
|
|
404
|
+
const max = numAttr(this, "max-length");
|
|
405
|
+
return !bool(this, "disabled") && !bool(this, "streaming") && (text.trim().length > 0 || this.files.length > 0) && (!max || text.length <= max);
|
|
406
|
+
}
|
|
407
|
+
/** ارسال پیام فعلی (مثل Enter) */
|
|
408
|
+
send() {
|
|
409
|
+
if (!this.canSend())
|
|
410
|
+
return;
|
|
411
|
+
emit(this, "kashi-send", { text: this.area.value.trim(), files: [...this.files] });
|
|
412
|
+
this.area.value = "";
|
|
413
|
+
this.files = [];
|
|
414
|
+
this.error = "";
|
|
415
|
+
this.renderFiles();
|
|
416
|
+
emit(this, "kashi-change", { value: "" });
|
|
417
|
+
this.area.focus();
|
|
418
|
+
}
|
|
419
|
+
update() {
|
|
420
|
+
const C = msg().composer;
|
|
421
|
+
const box = this.box;
|
|
422
|
+
const disabled = bool(this, "disabled");
|
|
423
|
+
box.className = "k-composer";
|
|
424
|
+
box.toggleAttribute("data-disabled", disabled);
|
|
425
|
+
this.area.disabled = disabled;
|
|
426
|
+
this.area.placeholder = this.getAttribute("placeholder") ?? C.placeholder;
|
|
427
|
+
this.area.setAttribute("aria-label", this.getAttribute("label") ?? C.label);
|
|
428
|
+
const attach = this.getAttribute("attach");
|
|
429
|
+
const attachBtn = box.querySelector("[data-act=attach]");
|
|
430
|
+
attachBtn.hidden = attach === null || attach === "false";
|
|
431
|
+
attachBtn.setAttribute("aria-label", C.attach);
|
|
432
|
+
this.picker.multiple = numAttr(this, "max-files", 5) > 1;
|
|
433
|
+
if (attach && attach !== "true" && attach !== "false")
|
|
434
|
+
this.picker.accept = attach;
|
|
435
|
+
else
|
|
436
|
+
this.picker.removeAttribute("accept");
|
|
437
|
+
const hint = box.querySelector(".k-composer__hint");
|
|
438
|
+
hint.textContent = C.hint;
|
|
439
|
+
hint.hidden = !bool(this, "show-hint");
|
|
440
|
+
this.paint();
|
|
441
|
+
}
|
|
442
|
+
/** ارتفاع، شمارنده، خطا و دکمهٔ ارسال یا توقف */
|
|
443
|
+
paint() {
|
|
444
|
+
const C = msg().composer;
|
|
445
|
+
const box = this.box;
|
|
446
|
+
const el = this.area;
|
|
447
|
+
el.style.blockSize = "auto";
|
|
448
|
+
const line = parseFloat(getComputedStyle(el).lineHeight) || 24;
|
|
449
|
+
if (el.scrollHeight)
|
|
450
|
+
el.style.blockSize = `${Math.min(el.scrollHeight, line * numAttr(this, "max-rows", 8) + 2)}px`;
|
|
451
|
+
const max = numAttr(this, "max-length");
|
|
452
|
+
const len = el.value.length;
|
|
453
|
+
const count = box.querySelector(".k-composer__count");
|
|
454
|
+
count.hidden = !(max && len > max * 0.8);
|
|
455
|
+
count.textContent = max ? `${num(this, len)}/${num(this, max)}` : "";
|
|
456
|
+
count.toggleAttribute("data-over", !!max && len > max);
|
|
457
|
+
if (max && len > max)
|
|
458
|
+
el.setAttribute("aria-invalid", "true");
|
|
459
|
+
else
|
|
460
|
+
el.removeAttribute("aria-invalid");
|
|
461
|
+
const err = box.querySelector(".k-composer__error");
|
|
462
|
+
err.textContent = this.error;
|
|
463
|
+
err.hidden = !this.error;
|
|
464
|
+
box.toggleAttribute("data-invalid", !!this.error);
|
|
465
|
+
const by = [bool(this, "show-hint") ? `${this.key}-hint` : "", this.error ? `${this.key}-err` : ""].filter(Boolean).join(" ");
|
|
466
|
+
if (by)
|
|
467
|
+
el.setAttribute("aria-describedby", by);
|
|
468
|
+
else
|
|
469
|
+
el.removeAttribute("aria-describedby");
|
|
470
|
+
box.querySelector("[data-act=attach]").disabled = bool(this, "disabled") || this.files.length >= numAttr(this, "max-files", 5);
|
|
471
|
+
const send = box.querySelector(".k-composer__send");
|
|
472
|
+
const streaming = bool(this, "streaming");
|
|
473
|
+
const hadFocus = document.activeElement === send;
|
|
474
|
+
send.dataset.act = streaming ? "stop" : "send";
|
|
475
|
+
send.toggleAttribute("data-stop", streaming);
|
|
476
|
+
send.setAttribute("aria-label", streaming ? C.stop : C.send);
|
|
477
|
+
send.innerHTML = streaming ? STOP : SEND;
|
|
478
|
+
send.disabled = !streaming && !this.canSend();
|
|
479
|
+
if (hadFocus && !send.disabled)
|
|
480
|
+
send.focus();
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
KashiChatComposer.observedAttributes = ["placeholder", "label", "streaming", "attach", "max-files", "max-size", "max-length", "max-rows", "show-hint", "disabled", "value"];
|
|
484
|
+
// ---------- متن کلمهبهکلمه ----------
|
|
485
|
+
const words = (s) => s.match(/\S+\s*|\s+/g) ?? [];
|
|
486
|
+
/**
|
|
487
|
+
* متنی که کلمهبهکلمه نوشته میشود؛ برای پاسخ زندهٔ دستیار. text متن تا این لحظه (با appendText تکهٔ تازه اضافه کنید)،
|
|
488
|
+
* streaming نشانگر چشمکزن و aria-busy، speed (کلمه در ثانیه) متن کامل را خودش آرام نشان میدهد. پایان: kashi-done.
|
|
489
|
+
*/
|
|
490
|
+
export class KashiStreamingText extends HTMLBase {
|
|
491
|
+
constructor() {
|
|
492
|
+
super(...arguments);
|
|
493
|
+
this.full = "";
|
|
494
|
+
this.shown = 0;
|
|
495
|
+
this.seen = 0;
|
|
496
|
+
this.root = null;
|
|
497
|
+
this.typing = false;
|
|
498
|
+
this.textSet = false;
|
|
499
|
+
}
|
|
500
|
+
connectedCallback() {
|
|
501
|
+
afterParse(() => {
|
|
502
|
+
if (!this.isConnected)
|
|
503
|
+
return;
|
|
504
|
+
if (!this.root) {
|
|
505
|
+
if (!this.textSet)
|
|
506
|
+
this.full = this.getAttribute("text") ?? this.textContent?.trim() ?? "";
|
|
507
|
+
this.root = document.createElement("p");
|
|
508
|
+
this.root.className = "k-stream";
|
|
509
|
+
this.root.dir = "auto";
|
|
510
|
+
this.replaceChildren(this.root);
|
|
511
|
+
const n = words(this.full).length;
|
|
512
|
+
this.shown = this.animated ? 0 : n;
|
|
513
|
+
this.seen = this.shown;
|
|
514
|
+
}
|
|
515
|
+
this.tick();
|
|
516
|
+
});
|
|
517
|
+
}
|
|
518
|
+
disconnectedCallback() {
|
|
519
|
+
clearTimeout(this.timer);
|
|
520
|
+
}
|
|
521
|
+
attributeChangedCallback(n, old, next) {
|
|
522
|
+
if (old === next)
|
|
523
|
+
return;
|
|
524
|
+
if (n === "text") {
|
|
525
|
+
this.full = next ?? "";
|
|
526
|
+
this.textSet = true;
|
|
527
|
+
}
|
|
528
|
+
if (this.root)
|
|
529
|
+
this.tick();
|
|
530
|
+
}
|
|
531
|
+
get text() {
|
|
532
|
+
return this.full;
|
|
533
|
+
}
|
|
534
|
+
set text(v) {
|
|
535
|
+
this.full = String(v ?? "");
|
|
536
|
+
this.textSet = true;
|
|
537
|
+
if (this.root)
|
|
538
|
+
this.tick();
|
|
539
|
+
}
|
|
540
|
+
/** افزودن تکهٔ تازهٔ پاسخ */
|
|
541
|
+
appendText(chunk) {
|
|
542
|
+
this.text = this.full + chunk;
|
|
543
|
+
}
|
|
544
|
+
get animated() {
|
|
545
|
+
return numAttr(this, "speed", 0) > 0 && !reduced();
|
|
546
|
+
}
|
|
547
|
+
tick() {
|
|
548
|
+
clearTimeout(this.timer);
|
|
549
|
+
const all = words(this.full);
|
|
550
|
+
if (!this.animated)
|
|
551
|
+
this.shown = all.length;
|
|
552
|
+
else if (this.shown < all.length)
|
|
553
|
+
this.timer = setTimeout(() => {
|
|
554
|
+
this.shown++;
|
|
555
|
+
this.tick();
|
|
556
|
+
}, 1000 / numAttr(this, "speed", 1));
|
|
557
|
+
this.paint(all);
|
|
558
|
+
}
|
|
559
|
+
paint(all) {
|
|
560
|
+
const root = this.root;
|
|
561
|
+
const count = Math.min(this.shown, all.length);
|
|
562
|
+
const typing = bool(this, "streaming") || (this.animated && count < all.length);
|
|
563
|
+
// فقط کلمههای تازه span با انیمیشن میگیرند؛ متن دیدهشده ساده میماند
|
|
564
|
+
const from = Math.min(this.seen, count);
|
|
565
|
+
root.textContent = all.slice(0, from).join("");
|
|
566
|
+
for (const w of all.slice(from, count)) {
|
|
567
|
+
const s = document.createElement("span");
|
|
568
|
+
s.className = "k-stream__word";
|
|
569
|
+
s.textContent = w;
|
|
570
|
+
root.append(s);
|
|
571
|
+
}
|
|
572
|
+
this.seen = count;
|
|
573
|
+
if (bool(this, "cursor", true) && typing)
|
|
574
|
+
root.insertAdjacentHTML("beforeend", '<span class="k-stream__cursor" aria-hidden="true"></span>');
|
|
575
|
+
root.insertAdjacentHTML("beforeend", '<span class="k-sr-only" aria-live="polite"></span>');
|
|
576
|
+
if (typing)
|
|
577
|
+
root.setAttribute("aria-busy", "true");
|
|
578
|
+
else
|
|
579
|
+
root.removeAttribute("aria-busy");
|
|
580
|
+
root.toggleAttribute("data-streaming", typing);
|
|
581
|
+
if (this.typing && !typing) {
|
|
582
|
+
root.querySelector(".k-sr-only").textContent = msg().streaming.done;
|
|
583
|
+
emit(this, "kashi-done", {});
|
|
584
|
+
}
|
|
585
|
+
this.typing = typing;
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
KashiStreamingText.observedAttributes = ["text", "streaming", "speed", "cursor"];
|
|
589
|
+
// ---------- نمایش کد ----------
|
|
590
|
+
const KEYWORDS = new Set(("import export from default const let var function return if else for while do switch case break continue new class extends " +
|
|
591
|
+
"async await try catch finally throw typeof instanceof in of interface type enum implements public private protected static readonly " +
|
|
592
|
+
"def lambda pass elif with as yield None True False self print fn pub use mod impl struct match mut package func go defer select " +
|
|
593
|
+
"true false null undefined void this super echo SELECT FROM WHERE INSERT INTO VALUES UPDATE SET DELETE JOIN ON AND OR NOT ORDER BY GROUP LIMIT").split(" "));
|
|
594
|
+
const TOKEN = /(\/\/[^\n]*|#(?![{\[])[^\n]*|\/\*[\s\S]*?\*\/|<!--[\s\S]*?-->)|("(?:\\.|[^"\\\n])*"|'(?:\\.|[^'\\\n])*'|`(?:\\.|[^`\\])*`)|(\b\d[\d_.]*(?:e[+-]?\d+)?\b)|([A-Za-z_$][\w$]*)/g;
|
|
595
|
+
/** رنگآمیزی سبک به شکل تکههای [کلاس، متن] */
|
|
596
|
+
function tokens(code, language = "") {
|
|
597
|
+
const out = [];
|
|
598
|
+
const hash = /^(py|python|sh|bash|shell|zsh|yaml|yml|toml|rb|ruby|r)$/i.test(language);
|
|
599
|
+
let last = 0;
|
|
600
|
+
for (const m of code.matchAll(TOKEN)) {
|
|
601
|
+
const [t, comment, str, n, word] = m;
|
|
602
|
+
const i = m.index ?? 0;
|
|
603
|
+
if (comment && comment.startsWith("#") && !hash)
|
|
604
|
+
continue;
|
|
605
|
+
if (i > last)
|
|
606
|
+
out.push(["", code.slice(last, i)]);
|
|
607
|
+
out.push([comment ? "comment" : str ? "string" : n ? "number" : word && KEYWORDS.has(word) ? "keyword" : word && code[i + t.length] === "(" ? "fn" : "", t]);
|
|
608
|
+
last = i + t.length;
|
|
609
|
+
}
|
|
610
|
+
if (last < code.length)
|
|
611
|
+
out.push(["", code.slice(last)]);
|
|
612
|
+
return out;
|
|
613
|
+
}
|
|
614
|
+
const lineSet = (v) => {
|
|
615
|
+
const s = new Set();
|
|
616
|
+
for (const part of (v ?? "").split(/[\s,]+/)) {
|
|
617
|
+
const [a, b] = part.split("-").map(Number);
|
|
618
|
+
if (!a)
|
|
619
|
+
continue;
|
|
620
|
+
for (let i = a; i <= (b || a); i++)
|
|
621
|
+
s.add(i);
|
|
622
|
+
}
|
|
623
|
+
return s;
|
|
624
|
+
};
|
|
625
|
+
const WRAP = icon('<path d="M3 5h14M3 10h11a3 3 0 0 1 0 6h-3m0 0 2-2m-2 2 2 2M3 15h4"/>');
|
|
626
|
+
/**
|
|
627
|
+
* نمایش کد، همیشه چپبهراست: کد از ویژگی code یا متن داخل عنصر (معمولاً داخل <template> یا <pre>)،
|
|
628
|
+
* language یا filename برچسب بالا، line-numbers، highlight-lines="2,4-6"، wrap، highlight="false" بدون رنگ و max-height.
|
|
629
|
+
*/
|
|
630
|
+
export class KashiCodeBlock extends HTMLBase {
|
|
631
|
+
constructor() {
|
|
632
|
+
super(...arguments);
|
|
633
|
+
this.source = null;
|
|
634
|
+
this.fig = null;
|
|
635
|
+
this.wrapped = false;
|
|
636
|
+
}
|
|
637
|
+
connectedCallback() {
|
|
638
|
+
afterParse(() => {
|
|
639
|
+
if (!this.isConnected)
|
|
640
|
+
return;
|
|
641
|
+
if (!this.fig) {
|
|
642
|
+
if (this.source === null && !this.hasAttribute("code")) {
|
|
643
|
+
const t = this.querySelector("template");
|
|
644
|
+
this.source = (t ? t.innerHTML : this.querySelector("pre, code")?.textContent ?? this.textContent ?? "").replace(/^\n/, "");
|
|
645
|
+
// تورفتگی مشترک خطها (از HTML صفحه) برداشته میشود
|
|
646
|
+
const lines = this.source.split("\n");
|
|
647
|
+
const indent = Math.min(...lines.filter((l) => l.trim()).map((l) => l.match(/^\s*/)[0].length));
|
|
648
|
+
if (indent > 0 && Number.isFinite(indent))
|
|
649
|
+
this.source = lines.map((l) => l.slice(indent)).join("\n");
|
|
650
|
+
if (t)
|
|
651
|
+
this.source = this.source.replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&");
|
|
652
|
+
}
|
|
653
|
+
this.wrapped = bool(this, "wrap");
|
|
654
|
+
this.fig = document.createElement("figure");
|
|
655
|
+
this.replaceChildren(this.fig);
|
|
656
|
+
this.fig.addEventListener("click", (e) => this.onClick(e));
|
|
657
|
+
}
|
|
658
|
+
this.render();
|
|
659
|
+
});
|
|
660
|
+
}
|
|
661
|
+
disconnectedCallback() {
|
|
662
|
+
clearTimeout(this.timer);
|
|
663
|
+
}
|
|
664
|
+
attributeChangedCallback(n, old, next) {
|
|
665
|
+
if (old === next)
|
|
666
|
+
return;
|
|
667
|
+
if (n === "wrap")
|
|
668
|
+
this.wrapped = next !== null && next !== "false";
|
|
669
|
+
if (this.fig)
|
|
670
|
+
this.render();
|
|
671
|
+
}
|
|
672
|
+
get code() {
|
|
673
|
+
return (this.getAttribute("code") ?? this.source ?? "").replace(/\n$/, "");
|
|
674
|
+
}
|
|
675
|
+
set code(v) {
|
|
676
|
+
this.source = String(v ?? "");
|
|
677
|
+
this.removeAttribute("code");
|
|
678
|
+
if (this.fig)
|
|
679
|
+
this.render();
|
|
680
|
+
}
|
|
681
|
+
async onClick(e) {
|
|
682
|
+
const b = e.target.closest("button");
|
|
683
|
+
if (!b)
|
|
684
|
+
return;
|
|
685
|
+
const B = msg().codeBlock;
|
|
686
|
+
if (b.dataset.act === "wrap") {
|
|
687
|
+
this.wrapped = !this.wrapped;
|
|
688
|
+
this.fig.toggleAttribute("data-wrap", this.wrapped);
|
|
689
|
+
b.setAttribute("aria-pressed", String(this.wrapped));
|
|
690
|
+
}
|
|
691
|
+
else if (b.dataset.act === "copy" && (await copyText(this.code))) {
|
|
692
|
+
b.setAttribute("data-done", "");
|
|
693
|
+
b.innerHTML = `${CHECK}<span>${esc(B.copied)}</span>`;
|
|
694
|
+
this.fig.querySelector(".k-code__tools > .k-sr-only").textContent = B.copied;
|
|
695
|
+
clearTimeout(this.timer);
|
|
696
|
+
this.timer = setTimeout(() => {
|
|
697
|
+
b.removeAttribute("data-done");
|
|
698
|
+
b.innerHTML = `${COPY}<span>${esc(B.copy)}</span>`;
|
|
699
|
+
this.fig.querySelector(".k-code__tools > .k-sr-only").textContent = "";
|
|
700
|
+
}, 2000);
|
|
701
|
+
emit(this, "kashi-copy", { value: this.code });
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
render() {
|
|
705
|
+
const B = msg().codeBlock;
|
|
706
|
+
const text = this.code;
|
|
707
|
+
const lang_ = this.getAttribute("language") ?? "";
|
|
708
|
+
const title = this.getAttribute("filename") ?? lang_;
|
|
709
|
+
const numbers = bool(this, "line-numbers");
|
|
710
|
+
const marked = lineSet(this.getAttribute("highlight-lines"));
|
|
711
|
+
const parts = this.getAttribute("highlight") === "false" ? [["", text]] : tokens(text, lang_);
|
|
712
|
+
const lines = [""];
|
|
713
|
+
for (const [cls, t] of parts) {
|
|
714
|
+
t.split("\n").forEach((seg, j) => {
|
|
715
|
+
if (j)
|
|
716
|
+
lines.push("");
|
|
717
|
+
if (seg)
|
|
718
|
+
lines[lines.length - 1] += cls ? `<span class="k-code__t-${cls}">${esc(seg)}</span>` : esc(seg);
|
|
719
|
+
});
|
|
720
|
+
}
|
|
721
|
+
const max = this.getAttribute("max-height");
|
|
722
|
+
const fig = this.fig;
|
|
723
|
+
fig.className = "k-code";
|
|
724
|
+
fig.toggleAttribute("data-wrap", this.wrapped);
|
|
725
|
+
fig.innerHTML = `<figcaption class="k-code__head"><span class="k-code__lang" dir="ltr">${esc(title || B.lines(num(this, lines.length)))}</span><span class="k-code__tools"><button type="button" class="k-code__btn" data-act="wrap" aria-label="${esc(B.wrap)}" aria-pressed="${this.wrapped}">${WRAP}</button><button type="button" class="k-code__btn" data-act="copy">${COPY}<span>${esc(B.copy)}</span></button><span class="k-sr-only" aria-live="polite"></span></span></figcaption><pre class="k-code__pre" dir="ltr" tabindex="0"${lang_ ? ` aria-label="${esc(B.code(lang_))}"` : ""}${max ? ` style="max-block-size: ${esc(max)}"` : ""}><code>${lines.map((l, i) => `<span class="k-code__line"${marked.has(i + 1) ? " data-marked" : ""}>${numbers ? `<span class="k-code__num" aria-hidden="true">${i + 1}</span>` : ""}<span class="k-code__text">${l || " "}</span></span>`).join("")}</code></pre>`;
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
KashiCodeBlock.observedAttributes = ["code", "language", "filename", "line-numbers", "highlight-lines", "wrap", "highlight", "max-height"];
|
|
729
|
+
define("kashi-chat", KashiChat, "block");
|
|
730
|
+
define("kashi-chat-message", KashiChatMessage, "contents");
|
|
731
|
+
define("kashi-typing-indicator", KashiTypingIndicator, "contents");
|
|
732
|
+
define("kashi-chat-composer", KashiChatComposer, "block");
|
|
733
|
+
define("kashi-streaming-text", KashiStreamingText, "block");
|
|
734
|
+
define("kashi-code-block", KashiCodeBlock, "block");
|