@songsid/agend 2.3.5-beta.3 → 2.3.5-beta.4

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.
@@ -4,7 +4,12 @@
4
4
  // - Right-click on a message opens Reply / Copy text / Copy link. Shift+right-click, a right-click with text selected,
5
5
  // or one on a link, an image or a field keeps the browser's own menu.
6
6
  // - A long press (500 ms without moving) opens the same menu; the click and the browser menu it would also cause are
7
- // swallowed.
7
+ // swallowed. M-2789 (the leader's ruling A, "text wins on text"): a long press on a message's WORDS, or one when a
8
+ // selection has already started inside the message, is the browser's — it selects text (then the 「引用」 pill,
9
+ // chat-quote.js); the menu still opens from a long press anywhere else on the message (its padding, header, an empty
10
+ // part of the bubble). Android starts its selection only after contextmenu's own default, so the press's place
11
+ // decides, not only a selection already made. Native long-press selection can't be shown headless: confirmed on a
12
+ // real phone before a beta.
8
13
  // - Swipe left on a message: it follows the finger (up to 64 px); let go past 56 px and it is a reply. A mostly
9
14
  // vertical move is scrolling, never a reply. A swipe right is the phone drawer's (app-swipe.js), on a message too: the
10
15
  // two never fight.
@@ -12,7 +17,41 @@
12
17
  // order); Escape closes the menu.
13
18
 
14
19
  const LONG_PRESS_MS = 500, MOVE_TOLERANCE = 10, SWIPE_REPLY_PX = 56, SWIPE_MAX_PX = 64;
20
+ /** How long after a touch on a message's words its contextmenu is still that press's (the browser's selection). */
21
+ const WORDS_PRESS_MS = 1500;
22
+ const clock = () => (typeof performance !== "undefined" && performance.now ? performance.now() : Date.now());
15
23
 
24
+ /**
25
+ * On a message's own words: the press at (x, y) lands on a glyph of its rendered text — not on the blank part of a
26
+ * line, its padding, its header or its action strip (a paragraph's box is wider than a short line's glyphs: #3555
27
+ * review P2-2). The browser's own hit test (caretPositionFromPoint / caretRangeFromPoint), then the glyph's box
28
+ * beside that caret; without either API, not words (the menu, as before).
29
+ */
30
+ const GLYPH_SLACK = 2;
31
+ function onWords(target, x, y, doc) {
32
+ const e = target && (target.nodeType === 1 ? target : target.parentElement);
33
+ const md = e && e.closest ? e.closest(".msg[data-key] .md") : null;
34
+ if (!md || e.closest(".meta, .msg-actions") || !Number.isFinite(x) || !Number.isFinite(y)) return false;
35
+ let node = null, offset = 0;
36
+ if (typeof doc.caretPositionFromPoint === "function") { const p = doc.caretPositionFromPoint(x, y); if (p) { node = p.offsetNode; offset = p.offset; } }
37
+ else if (typeof doc.caretRangeFromPoint === "function") { const r = doc.caretRangeFromPoint(x, y); if (r) { node = r.startContainer; offset = r.startOffset; } }
38
+ if (!node || node.nodeType !== 3 || !md.contains(node) || typeof doc.createRange !== "function") return false;
39
+ // The caret sits between two characters: the press is on words when the glyph before or after it holds the point.
40
+ for (const at of [offset - 1, offset]) {
41
+ if (at < 0 || at >= node.data.length || !node.data[at].trim()) continue;
42
+ const rg = doc.createRange(); rg.setStart(node, at); rg.setEnd(node, at + 1);
43
+ for (const b of rg.getClientRects()) {
44
+ if (x >= b.left - GLYPH_SLACK && x <= b.right + GLYPH_SLACK && y >= b.top - GLYPH_SLACK && y <= b.bottom + GLYPH_SLACK) return true;
45
+ }
46
+ }
47
+ return false;
48
+ }
49
+ /** A selection already started inside `el` (a message): the browser's, never ours. */
50
+ function selectionIn(el, doc) {
51
+ const sel = doc.getSelection ? doc.getSelection() : null;
52
+ if (!sel || sel.isCollapsed || !String(sel).trim()) return false;
53
+ return !!((sel.anchorNode && el.contains(sel.anchorNode)) || (sel.focusNode && el.contains(sel.focusNode)));
54
+ }
16
55
  /** The message element an event is on (a person's or an agent's message of this thread), or null. */
17
56
  function messageEl(list, target) {
18
57
  const el = target && target.closest ? target.closest(".msg[data-key]") : null;
@@ -34,7 +73,7 @@ function keepsNativeMenu(e, doc) {
34
73
  */
35
74
  export function installMessageActions(list, deps) {
36
75
  const doc = list.ownerDocument, win = doc.defaultView;
37
- let menu = null, press = null, swipe = null, swallowClick = false;
76
+ let menu = null, press = null, swipe = null, swallowClick = false, wordsPressAt = -Infinity;
38
77
 
39
78
  function closeMenu() {
40
79
  if (!menu) return;
@@ -88,6 +127,8 @@ export function installMessageActions(list, deps) {
88
127
  cancelPress(); // Android's long press fires this itself: one menu
89
128
  const el = messageEl(list, e.target);
90
129
  if (!el || keepsNativeMenu(e, doc)) return;
130
+ // M-2789: a long press on the words (or a selection begun in this message) is the browser's — its selection.
131
+ if (selectionIn(el, doc) || (clock() - wordsPressAt < WORDS_PRESS_MS && onWords(e.target, e.clientX, e.clientY, doc))) return;
91
132
  const row = deps.messageOf(el.dataset.key);
92
133
  if (!row) return;
93
134
  e.preventDefault();
@@ -117,9 +158,14 @@ export function installMessageActions(list, deps) {
117
158
  if (!el) return;
118
159
  const t0 = e.touches[0];
119
160
  const native = keepsNativeMenu({ target: e.target, shiftKey: false }, doc); // a link, an image, code: the browser's
120
- press = native ? null : { el, x: t0.clientX, y: t0.clientY, timer: setTimeout(() => {
161
+ // M-2789: a press on the message's words is the browser's text selection, not our menu (swipe-left Reply stays).
162
+ const words = onWords(e.target, t0.clientX, t0.clientY, doc);
163
+ wordsPressAt = words ? clock() : -Infinity;
164
+ press = native || words ? null : { el, x: t0.clientX, y: t0.clientY, timer: setTimeout(() => {
121
165
  const row = deps.messageOf(el.dataset.key);
122
- press = null; cancelSwipe();
166
+ press = null;
167
+ if (selectionIn(el, doc)) return; // a selection has started here: it stays the browser's
168
+ cancelSwipe();
123
169
  if (!row) return;
124
170
  swallowClick = true; setTimeout(() => { swallowClick = false; }, 700);
125
171
  openMenu(row, t0.clientX, t0.clientY);
@@ -0,0 +1,256 @@
1
+ // M-2789 (the user, 11-09): answer a long, multi-part message passage by passage. Select text in ONE message of the thread
2
+ // → a small 「引用」 pill → the passage goes into the composer as a Markdown quote ("> …") at the caret, on its own lines,
3
+ // the caret left on the next line for the answer. Repeatable: quote, answer, quote the next passage, answer…
4
+ //
5
+ // - Desktop: the pill is anchored to where the selection ends (a pointer at the exact spot), above that line — or below
6
+ // it when that covers less of the neighbouring lines' text (the passage itself never counts). After a quote the
7
+ // composer takes the focus.
8
+ // - Phone (a coarse pointer): the pill 「引用選取的文字」 docks above the composer's whole box inside the 16-px gutter — clear
9
+ // of the system's own copy toolbar (above a selection) and of the finger — or at the top of the thread when the
10
+ // passage sits there. The keyboard does NOT open after a quote (the user's choice): more passages can be selected;
11
+ // the composer's own scroller shows the caret and the newest quote.
12
+ // - No pill for a selection across messages, outside the thread, or on a page that can't send; no keyboard shortcut
13
+ // (the user's choice). The whole-message Reply (#2272) is unchanged, and so is the browser's menu on selected text.
14
+ // - What is sent is the composer's text as typed: the agent reads the "> " lines as written; the web renders them as
15
+ // blockquotes (chat-render.js); Discord's mirror shows them as quotes, Telegram's as the same plain lines.
16
+ //
17
+ // Its own words and drawing (a page that loaded an older chat-strings.js or ui-icons.js still draws it), CSSOM only
18
+ // (no style attribute: #1300), the shared popover look (.msg-menu) with the shared border and shadow tokens.
19
+ import { register, t } from "/assets/app-i18n.js";
20
+
21
+ register("chatQuote", {
22
+ en: { quote: "Quote", quotePhone: "Quote selection", label: "Quote the selected text in your message" },
23
+ "zh-TW": { quote: "引用", quotePhone: "引用選取的文字", label: "把選取的文字引用到你的訊息裡" },
24
+ });
25
+ const tq = (k) => t(`chatQuote.${k}`);
26
+
27
+ /**
28
+ * Where the person's caret was in the composer when it last lost the focus — what a quote goes in at. A field's own
29
+ * selectionStart can't be trusted after the page's selection moved into the thread (Chrome resets it), so it is kept
30
+ * here, with the text it belongs to (a caret for another text is no caret).
31
+ */
32
+ const remembered = new WeakMap();
33
+ export function composerCaret(field, value) {
34
+ if (!field) return value.length;
35
+ const r = remembered.get(field);
36
+ if (r && r.value === value) return r.caret;
37
+ const doc = field.ownerDocument;
38
+ if (doc && doc.activeElement === field && field.value === value) return field.selectionStart ?? value.length;
39
+ return value.length;
40
+ }
41
+
42
+ /** The passage as Markdown quote lines: each line "> line" (an empty one "> " keeps the quote one block). */
43
+ export function quoteBlock(text) {
44
+ const lines = String(text ?? "").replace(/\r\n?/g, "\n").replace(/ /g, " ").split("\n").map((l) => l.replace(/\s+$/, ""));
45
+ while (lines.length && !lines[0].trim()) lines.shift();
46
+ while (lines.length && !lines[lines.length - 1].trim()) lines.pop();
47
+ // A run of empty lines inside the passage becomes one quoted empty line.
48
+ const out = [];
49
+ for (const l of lines) { if (!l.trim() && out.length && out[out.length - 1] === ">") continue; out.push(l.trim() ? `> ${l}` : ">"); }
50
+ return out.join("\n");
51
+ }
52
+
53
+ /**
54
+ * Put the passage into `value` at `caret`, on its own lines: a blank line before it when text precedes on the line or
55
+ * just above, the caret on the line after it (for the answer), and a line break before any text that follows.
56
+ * Returns { value, caret }, or null for a passage with nothing to quote.
57
+ */
58
+ export function insertQuote(value, caret, text) {
59
+ const block = quoteBlock(text);
60
+ if (!block) return null;
61
+ const v = String(value ?? "");
62
+ const at = Math.max(0, Math.min(Number.isInteger(caret) ? caret : v.length, v.length));
63
+ const before = v.slice(0, at), after = v.slice(at);
64
+ const lead = !before ? "" : before.endsWith("\n\n") ? "" : before.endsWith("\n") ? "\n" : "\n\n";
65
+ const head = before + lead + block + "\n";
66
+ // Text after the caret starts its own line below the answer's (its leading spaces dropped with the break).
67
+ const tail = after && !after.startsWith("\n") ? "\n" + after.replace(/^[ \t]+/, "") : after;
68
+ return { value: head + tail, caret: head.length };
69
+ }
70
+
71
+ /** The selected passage when it lies inside one message's text of `list`, else null. { text, el, rects }. */
72
+ export function selectedPassage(list, sel) {
73
+ if (!sel || sel.isCollapsed || !sel.rangeCount) return null;
74
+ const text = String(sel.toString() || "");
75
+ if (!text.trim()) return null;
76
+ const msg = (n) => { const e = n && (n.nodeType === 1 ? n : n.parentElement); return e && e.closest ? e.closest(".msg[data-key]") : null; };
77
+ // The message's own words, not its header (sender, time) or its action strip.
78
+ const inBody = (n) => { const e = n && (n.nodeType === 1 ? n : n.parentElement); return !!(e && e.closest && e.closest(".body, .md") && !e.closest(".meta, .msg-actions")); };
79
+ // Every range of the selection (a browser may keep several: #3555 review P3) in the same message's words — what is
80
+ // quoted is the whole selection's text.
81
+ const range = sel.getRangeAt(0), a = msg(range.startContainer);
82
+ if (!a || !list.contains(a)) return null;
83
+ for (let i = 0; i < sel.rangeCount; i++) {
84
+ const rg = sel.getRangeAt(i);
85
+ if (msg(rg.startContainer) !== a || msg(rg.endContainer) !== a || !inBody(rg.startContainer) || !inBody(rg.endContainer)) return null;
86
+ }
87
+ return { text, el: a, range };
88
+ }
89
+
90
+ /**
91
+ * Where the composer's caret sits, in px from the top of its text (a mirror of the field's text box up to the caret).
92
+ * Used to show the caret without focusing the field (a phone: the keyboard stays down).
93
+ */
94
+ export function caretTop(field, pos) {
95
+ const doc = field.ownerDocument, win = doc.defaultView;
96
+ if (!win || !win.getComputedStyle) return 0;
97
+ const cs = win.getComputedStyle(field);
98
+ const m = doc.createElement("div");
99
+ for (const p of ["box-sizing", "width", "padding-top", "padding-right", "padding-bottom", "padding-left", "border-top-width", "border-right-width",
100
+ "border-bottom-width", "border-left-width", "font-family", "font-size", "font-weight", "font-style", "line-height", "letter-spacing", "word-spacing", "tab-size"]) {
101
+ m.style.setProperty(p, cs.getPropertyValue(p));
102
+ }
103
+ for (const [k, v] of [["position", "absolute"], ["visibility", "hidden"], ["top", "0"], ["left", "-9999px"], ["white-space", "pre-wrap"], ["overflow-wrap", "break-word"], ["height", "auto"]]) m.style.setProperty(k, v);
104
+ m.textContent = field.value.slice(0, pos);
105
+ const mark = doc.createElement("span"); mark.textContent = "​"; m.append(mark);
106
+ doc.body.append(m);
107
+ const y = mark.offsetTop, h = mark.offsetHeight;
108
+ m.remove();
109
+ return { y, h };
110
+ }
111
+
112
+ /** Scroll the field's own scroller so the caret (and the lines just above it: the newest quote) are in view. */
113
+ export function showCaret(field, pos) {
114
+ // At the end (the usual case: the newest quote is the last thing in the box): the bottom.
115
+ if (pos >= field.value.length) { field.scrollTop = field.scrollHeight; return; }
116
+ const c = caretTop(field, pos);
117
+ if (!c || typeof c !== "object") { field.scrollTop = field.scrollHeight; return; }
118
+ const view = field.clientHeight;
119
+ if (c.y + c.h > field.scrollTop + view) field.scrollTop = Math.max(0, c.y + c.h - view + 4);
120
+ else if (c.y < field.scrollTop) field.scrollTop = Math.max(0, c.y - 4);
121
+ }
122
+
123
+ // The quote mark: two marks on the shared 24-px grid, 2-px stroke, currentColor (as ui-icons.js draws).
124
+ const ICON = "M4 11h5v6H4v-6zm0 0c0-3 1.5-5 4-6M14 11h5v6h-5v-6zm0 0c0-3 1.5-5 4-6";
125
+ function iconEl(doc) {
126
+ const NS = "http://www.w3.org/2000/svg";
127
+ const svg = doc.createElementNS(NS, "svg");
128
+ for (const [k, v] of [["class", "icon"], ["width", "16"], ["height", "16"], ["viewBox", "0 0 24 24"], ["fill", "none"], ["stroke", "currentColor"], ["stroke-width", "2"],
129
+ ["stroke-linecap", "round"], ["stroke-linejoin", "round"], ["aria-hidden", "true"], ["focusable", "false"]]) svg.setAttribute(k, v);
130
+ const p = doc.createElementNS(NS, "path"); p.setAttribute("d", ICON); svg.append(p);
131
+ return svg;
132
+ }
133
+
134
+ const overlap = (a, z) => Math.max(0, Math.min(a.right, z.right) - Math.max(a.left, z.left)) * Math.max(0, Math.min(a.bottom, z.bottom) - Math.max(a.top, z.top));
135
+
136
+ /**
137
+ * Install the pill on `list` (the thread element). `deps`:
138
+ * field() → the composer's text field (marked data-touched once it has had the focus: its caret is the person's);
139
+ * canQuote() → boolean (a page that can send); insert(text) (the composer's side: see panel-chat.js);
140
+ * phone() → boolean (a coarse pointer); composerBox() → the composer's whole box (Element) or null; threadBox() → Element.
141
+ * Returns a function that removes everything.
142
+ */
143
+ export function installQuoteSelection(list, deps) {
144
+ const doc = list.ownerDocument, win = doc.defaultView;
145
+ let pop = null, timer = null, down = false, current = null, drawnFor = "";
146
+
147
+ function hide() {
148
+ current = null; drawnFor = "";
149
+ if (!pop) return;
150
+ pop.remove(); pop = null;
151
+ }
152
+ function place(passage) {
153
+ const phone = !!deps.phone?.();
154
+ if (!pop) {
155
+ pop = doc.createElement("div");
156
+ pop.className = "msg-menu quote-pop";
157
+ pop.setAttribute("role", "toolbar"); pop.setAttribute("data-trust", "menu"); pop.setAttribute("aria-label", tq("label"));
158
+ const b = doc.createElement("button");
159
+ b.type = "button"; b.className = "menu-item quote-pick";
160
+ b.append(iconEl(doc));
161
+ const span = doc.createElement("span"); b.append(span);
162
+ // A press on the pill must not collapse the selection it is about (mousedown's default does, pointerdown's
163
+ // preventDefault alone doesn't); the passage is the one the pill was drawn for, whatever the selection did since.
164
+ b.addEventListener("pointerdown", (e) => { e.preventDefault(); });
165
+ b.addEventListener("mousedown", (e) => { e.preventDefault(); });
166
+ b.addEventListener("click", (e) => { e.preventDefault(); const text = drawnFor; hide(); if (text) { deps.insert(text); doc.getSelection?.()?.removeAllRanges?.(); } });
167
+ pop.append(b);
168
+ doc.body.append(pop);
169
+ }
170
+ pop.classList.toggle("is-phone", phone);
171
+ const label = pop.querySelector(".quote-pick span"); label.textContent = tq(phone ? "quotePhone" : "quote");
172
+ pop.querySelector(".quote-tip")?.remove();
173
+ const pr = pop.getBoundingClientRect();
174
+ const vw = win?.innerWidth ?? 1024;
175
+ const rects = [...(passage.range.getClientRects?.() ?? [])].filter((x) => x.width > 0);
176
+ if (!rects.length) { hide(); return; }
177
+ const last = rects[rects.length - 1];
178
+ let left, top, tip = null;
179
+ if (!phone) {
180
+ // The other lines of the message (the passage's own never count as covered).
181
+ const lines = [];
182
+ if (typeof doc.createTreeWalker === "function" && typeof doc.createRange === "function") {
183
+ const w = doc.createTreeWalker(passage.el, 4 /* text */);
184
+ while (w.nextNode()) {
185
+ const rg = doc.createRange(); rg.selectNodeContents(w.currentNode);
186
+ for (const z of rg.getClientRects()) if (z.width > 0 && !rects.some((q) => overlap(q, z) > 0)) lines.push(z);
187
+ }
188
+ }
189
+ left = Math.max(8, Math.min(last.right - pr.width / 2, vw - pr.width - 8));
190
+ const above = { left, right: left + pr.width, top: last.top - pr.height - 10, bottom: last.top - 10 };
191
+ const below = { left, right: left + pr.width, top: last.bottom + 10, bottom: last.bottom + 10 + pr.height };
192
+ const cover = (a) => lines.reduce((n, z) => n + overlap(a, z), 0);
193
+ const under = cover(below) < cover(above) || above.top < 4;
194
+ top = under ? below.top : above.top;
195
+ tip = { side: under ? "up" : "down", x: Math.max(10, Math.min(last.right - left - 5, pr.width - 20)) };
196
+ } else {
197
+ const box = deps.composerBox?.()?.getBoundingClientRect?.();
198
+ left = Math.max(16, vw - 16 - pr.width);
199
+ top = box ? box.top - pr.height - 12 : (win?.innerHeight ?? 800) - pr.height - 120;
200
+ const at = { left, right: left + pr.width, top: top - 8, bottom: top + pr.height + 8 };
201
+ if (rects.some((q) => overlap(at, q) > 0)) {
202
+ const th = deps.threadBox?.()?.getBoundingClientRect?.();
203
+ top = Math.max(th ? th.top : 0, 0) + 12;
204
+ }
205
+ }
206
+ if (tip) {
207
+ const s = doc.createElement("span"); s.className = `quote-tip ${tip.side}`; s.setAttribute("aria-hidden", "true");
208
+ s.style.setProperty("left", `${tip.x}px`);
209
+ pop.append(s);
210
+ }
211
+ pop.style.setProperty("left", `${Math.round(left)}px`);
212
+ pop.style.setProperty("top", `${Math.round(top)}px`);
213
+ }
214
+ function check() {
215
+ timer = null;
216
+ if (down || deps.canQuote?.() === false) { hide(); return; }
217
+ const passage = selectedPassage(list, doc.getSelection?.());
218
+ if (!passage) { hide(); return; }
219
+ current = passage; drawnFor = passage.text;
220
+ place(passage);
221
+ }
222
+ function soon() { if (timer) clearTimeout(timer); timer = setTimeout(check, 120); }
223
+ const onSelection = () => soon();
224
+ const onDown = (e) => { if (pop && pop.contains(e.target)) return; down = true; hide(); };
225
+ // A gesture the browser took over (a touch scroll: pointerdown → pointercancel, no pointerup — #3555 review P2-1)
226
+ // ends the press as a pointerup does; the selection then decides.
227
+ const onUp = () => { if (!down) return; down = false; soon(); };
228
+ const onKey = (e) => { if (e.key === "Escape" && pop) { hide(); } };
229
+ const onScroll = () => { if (pop && current) place(current); };
230
+ const onFocusIn = (e) => { const f = deps.field?.(); if (f && e.target === f) f.dataset.touched = "1"; };
231
+ // The caret as the person leaves it: kept on every move inside the composer and when it loses the focus.
232
+ const keep = (e) => { const f = deps.field?.(); if (f && e.target === f) remembered.set(f, { value: f.value, caret: f.selectionStart ?? f.value.length }); };
233
+ const KEEP = ["focusout", "input", "keyup", "mouseup", "select"];
234
+ doc.addEventListener("focusin", onFocusIn);
235
+ for (const k of KEEP) doc.addEventListener(k, keep, true);
236
+ doc.addEventListener("selectionchange", onSelection);
237
+ list.addEventListener("pointerdown", onDown);
238
+ doc.addEventListener("pointerup", onUp);
239
+ doc.addEventListener("pointercancel", onUp);
240
+ doc.addEventListener("keydown", onKey);
241
+ win?.addEventListener("scroll", onScroll, true);
242
+ win?.addEventListener("resize", onScroll);
243
+ return () => {
244
+ if (timer) clearTimeout(timer);
245
+ hide();
246
+ doc.removeEventListener("focusin", onFocusIn);
247
+ for (const k of KEEP) doc.removeEventListener(k, keep, true);
248
+ doc.removeEventListener("selectionchange", onSelection);
249
+ list.removeEventListener("pointerdown", onDown);
250
+ doc.removeEventListener("pointerup", onUp);
251
+ doc.removeEventListener("pointercancel", onUp);
252
+ doc.removeEventListener("keydown", onKey);
253
+ win?.removeEventListener("scroll", onScroll, true);
254
+ win?.removeEventListener("resize", onScroll);
255
+ };
256
+ }
@@ -122,13 +122,16 @@
122
122
  var MAX_TABLE_COLUMNS = 20;
123
123
 
124
124
  /** Leading whitespace as columns: a tab counts four. */
125
+ var LIST_ITEM = /^([ \t]*)([-*+]|\d{1,9}[.)])\s+(.*)$/;
125
126
  function indentOf(ws) { var n = 0; for (var i = 0; i < ws.length; i++) n += ws[i] === "\t" ? 4 : 1; return n; }
126
127
 
127
128
  /**
128
129
  * A run of list items as nested lists. An item indented deeper than the one before opens a list inside that
129
130
  * item; a shallower one closes lists back to its level; at the same level a change of kind (- vs 1.) starts a
130
131
  * new list. Every tag is the renderer's own; item text goes through inline() like any other text.
132
+ * M-2811: a numbered list keeps its first number ("3." after a paragraph reads 3 — `start`, digits only).
131
133
  */
134
+ function openList(it) { return it.tag === "ol" && it.num > 1 ? '<ol start="' + it.num + '">' : "<" + it.tag + ">"; }
132
135
  function renderList(items, store) {
133
136
  var html = "";
134
137
  var stack = []; // { indent, tag }
@@ -137,10 +140,10 @@
137
140
  while (stack.length && it.indent < stack[stack.length - 1].indent) html += "</li></" + stack.pop().tag + ">";
138
141
  var top = stack[stack.length - 1];
139
142
  if (!top || (it.indent > top.indent && stack.length < MAX_LIST_DEPTH)) {
140
- html += "<" + it.tag + ">";
143
+ html += openList(it);
141
144
  stack.push({ indent: it.indent, tag: it.tag });
142
145
  } else if (top.tag !== it.tag) {
143
- html += "</li></" + top.tag + "><" + it.tag + ">";
146
+ html += "</li></" + top.tag + ">" + openList(it);
144
147
  top.tag = it.tag;
145
148
  } else {
146
149
  html += "</li>";
@@ -211,7 +214,16 @@
211
214
  for (var i = 0; i < lines.length; i++) {
212
215
  var line = lines[i];
213
216
  var m;
214
- if (/^\s*$/.test(line)) { flushAll(); continue; }
217
+ if (/^\s*$/.test(line)) {
218
+ // M-2811: a blank line between list items (a "loose" list: "1. a\n\n2. b") keeps one list — its numbering runs
219
+ // on instead of starting at 1 again for every item.
220
+ if (list.length) {
221
+ var k = i + 1;
222
+ while (k < lines.length && /^\s*$/.test(lines[k])) k++;
223
+ if (k < lines.length && LIST_ITEM.test(lines[k])) { i = k - 1; continue; }
224
+ }
225
+ flushAll(); continue;
226
+ }
215
227
  // A table: a header row with a pipe, then a separator row with the same number of columns.
216
228
  if (line.indexOf("|") !== -1 && i + 1 < lines.length) {
217
229
  var aligns = tableAligns(lines[i + 1]);
@@ -229,9 +241,9 @@
229
241
  if ((m = /^(#{1,6})\s+(.*)$/.exec(line))) { flushAll(); var n = Math.min(m[1].length + 2, 6); out.push("<h" + n + ">" + inline(m[2], store) + "</h" + n + ">"); continue; }
230
242
  if (/^\s*(?:-{3,}|\*{3,}|_{3,})\s*$/.test(line)) { flushAll(); out.push("<hr>"); continue; }
231
243
  if ((m = /^&gt;\s?(.*)$/.exec(line))) { flushPara(); flushList(); quote.push(m[1]); continue; }
232
- if ((m = /^([ \t]*)([-*+]|\d{1,9}[.)])\s+(.*)$/.exec(line))) {
244
+ if ((m = LIST_ITEM.exec(line))) {
233
245
  flushPara(); flushQuote();
234
- list.push({ indent: indentOf(m[1]), tag: /\d/.test(m[2]) ? "ol" : "ul", text: m[3] });
246
+ list.push({ indent: indentOf(m[1]), tag: /\d/.test(m[2]) ? "ol" : "ul", num: /\d/.test(m[2]) ? parseInt(m[2], 10) : 0, text: m[3] });
235
247
  continue;
236
248
  }
237
249
  flushList(); flushQuote();
@@ -75,6 +75,7 @@ import { confirmedWrite, selfConfirmed } from "./settings-confirm.js";
75
75
  import { createChatStore } from "./chat-store.js";
76
76
  import { createThread, msgKey } from "./chat-thread.js";
77
77
  import { installMessageActions } from "./chat-msg-actions.js";
78
+ import { composerCaret, insertQuote, installQuoteSelection, showCaret } from "./chat-quote.js";
78
79
  import { createEmojiIndex } from "./chat-emojis.js";
79
80
  import { pollPublicPreview } from "./preview-status.js";
80
81
  import { createMentionIndex } from "./chat-mentions.js";
@@ -506,6 +507,38 @@ function Thread({ name, th }) {
506
507
  copyText, notice: (text, ok = true) => toast(text, ok),
507
508
  linkOf: (x) => `${location.origin}/ui/chat/${encodeURIComponent(name)}#m=${msgKey(x)}`,
508
509
  });
510
+ // M-2789: select a passage in a message → 「引用」 → it goes into the composer as a quote at the caret, repeatable.
511
+ const offQuote = installQuoteSelection(ls, {
512
+ field: () => document.getElementById("msgIn"),
513
+ canQuote: () => !!document.getElementById("msgIn"),
514
+ phone: () => typeof matchMedia === "function" && matchMedia("(pointer: coarse)").matches,
515
+ composerBox: () => document.querySelector(".composer-box"),
516
+ threadBox: () => sc,
517
+ insert: (text) => {
518
+ const field = document.getElementById("msgIn");
519
+ const value = store.state.drafts[name] || "";
520
+ // The caret where the person left it in the composer (kept when it lost the focus); never touched: the end.
521
+ const caret = field && field.dataset.touched === "1" ? composerCaret(field, value) : value.length;
522
+ const r = insertQuote(value, caret, text);
523
+ if (!r) return;
524
+ // Through the composer's own typing path (its onInput: the draft, the palette, the box's height), as a keystroke
525
+ // would — the store alone doesn't redraw the box. No composer on screen: the draft, for when it is.
526
+ if (field) {
527
+ const set = typeof HTMLTextAreaElement === "function" ? Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, "value")?.set : null;
528
+ if (set) set.call(field, r.value); else field.value = r.value;
529
+ field.dispatchEvent(new Event("input", { bubbles: true }));
530
+ } else store.setDraft(name, r.value);
531
+ const phone = typeof matchMedia === "function" && matchMedia("(pointer: coarse)").matches;
532
+ // After the box redraws with the new text: the caret after the quote, in view. A phone keeps its keyboard down.
533
+ setTimeout(() => {
534
+ const el = document.getElementById("msgIn"); if (!el) return;
535
+ el.dataset.touched = "1";
536
+ try { el.setSelectionRange(r.caret, r.caret); } catch { /* not a text field */ }
537
+ if (!phone) el.focus();
538
+ showCaret(el, r.caret);
539
+ }, 0);
540
+ },
541
+ });
509
542
  // A copied message link (#m=<boot>-<id>): show that message, flashed.
510
543
  const linked = /^#m=([0-9a-f]{1,32}-\d{1,15})$/.exec(location.hash);
511
544
  if (linked) void thread.jumpTo(linked[1]);
@@ -519,7 +552,7 @@ function Thread({ name, th }) {
519
552
  return () => {
520
553
  window.removeEventListener("hashchange", onHash);
521
554
  unfollow();
522
- offActions();
555
+ offActions(); offQuote();
523
556
  sc.removeEventListener("scroll", onScroll);
524
557
  ls.removeEventListener("click", thread.onClick);
525
558
  e.sink = null;
@@ -6,7 +6,7 @@ import { Icon } from "./ui-icons.js";
6
6
  import { Toasts } from "./ui-toast.js";
7
7
  import { ConfirmHost, confirmDialog } from "./ui-confirm.js";
8
8
  import { ColorDialogHost } from "./identity-color.js";
9
- import { t, lang, setLang, onLang } from "./app-i18n.js";
9
+ import { t, lang, setLang, onLang, register } from "./app-i18n.js";
10
10
  import { appStore, createStore, guestBadge, guestPage, guestTrusted, useStore } from "./app-store.js";
11
11
  import { navStore } from "./app-nav.js";
12
12
  import { toast } from "./ui-toast.js";
@@ -563,6 +563,17 @@ const mmss = (ms) => { const s = Math.max(0, Math.ceil(ms / 1000)); return `${Ma
563
563
  * corner, except in Settings itself, which shows the same cards in its column, right under the operation (`inline`),
564
564
  * so they never cover it (alpha.2 sweep).
565
565
  */
566
+ // #3511: the immutable diff stays in the Fleet's locale; this known line is display-only in the page's locale.
567
+ // Own dictionary also works when app-i18n.js was cached before the Hub connection flow shipped.
568
+ register("pendingHub", {
569
+ en: { connect: "Connect this Fleet to Hub {0} using your company account. Agent sharing stays separate." },
570
+ "zh-TW": { connect: "以公司帳號將這個 Fleet 連接到 Hub {0}。分享 Agent 需另外選擇。" },
571
+ });
572
+ function pendingSummaryLine(line) {
573
+ if (typeof line !== "string") return line;
574
+ const known = /^(?:Connect this Fleet to Hub (.+) using your company account\. Agent sharing stays separate\.|以公司帳號將這個 Fleet 連接到 Hub (.+)。分享 Agent 需另外選擇。)$/.exec(line);
575
+ return known ? t("pendingHub.connect", known[1] ?? known[2]) : line;
576
+ }
566
577
  export function PendingChanges({ inline = false } = {}) {
567
578
  const { pendingChanges } = useStore(appStore);
568
579
  const list = pendingChanges || [];
@@ -587,7 +598,7 @@ export function PendingChanges({ inline = false } = {}) {
587
598
  ${p.state === "pending" ? html`<span class="pending-left">${t("app.pendingLeft", mmss(p.deadline - NOW()))}</span>` : null}
588
599
  ${p.dismiss ? html`<button type="button" class="icon-btn" aria-label=${t("app.close")} title=${t("app.close")} onClick=${p.dismiss}><${Icon} name="close" size=${14} /></button>` : null}</div>
589
600
  ${p.label ? html`<div class="pending-label">${p.label}</div>` : null}
590
- ${Array.isArray(p.summary) && p.summary.length ? html`<ul class="pending-summary">${p.summary.map((line, i) => html`<li key=${i}>${line}</li>`)}</ul>` : null}
601
+ ${Array.isArray(p.summary) && p.summary.length ? html`<ul class="pending-summary">${p.summary.map((line, i) => html`<li key=${i}>${pendingSummaryLine(line)}</li>`)}</ul>` : null}
591
602
  ${p.state === "pending" ? html`<${PendingHow} p=${p} />` : null}
592
603
  ${(p.state === "applying" || p.state === "applied") && p.confirmation && p.confirmation.kind === "web" ? html`<p class="note">${t("app.pendingWeb")}</p>` : null}
593
604
  ${p.state !== "pending" && p.state !== "applying" && p.state !== "applied" && p.outcome && p.outcome.message ? html`<p class="note">${p.outcome.message}</p>` : null}
@@ -891,6 +891,14 @@ img.amb-p { object-fit: contain; }
891
891
  .msg-quote .quote-text { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
892
892
  .msg-menu { position: fixed; z-index: 60; min-width: 180px; padding: var(--s-1); border-radius: var(--r-md); background: var(--surface);
893
893
  box-shadow: var(--shadow-2); display: flex; flex-direction: column; }
894
+ /* M-2789: the 「引用」 pill on a selected passage (chat-quote.js) — the message menu's look, one item, its pointer at the
895
+ passage's end; readable on white and dark alike (the shared border and shadow tokens). A phone's is a 44-px tap. */
896
+ .msg-menu.quote-pop { min-width: 0; padding: 2px; border: 1px solid var(--border-strong); overflow: visible; }
897
+ .quote-pop .quote-pick { display: inline-flex; align-items: center; gap: 6px; padding: 5px 10px; white-space: nowrap; }
898
+ .quote-pop.is-phone .quote-pick { min-height: var(--tap); padding: 10px 14px; }
899
+ .quote-pop .quote-tip { position: absolute; width: 10px; height: 10px; background: var(--surface); transform: rotate(45deg); pointer-events: none; }
900
+ .quote-pop .quote-tip.down { bottom: -6px; border-right: 1px solid var(--border-strong); border-bottom: 1px solid var(--border-strong); }
901
+ .quote-pop .quote-tip.up { top: -6px; border-left: 1px solid var(--border-strong); border-top: 1px solid var(--border-strong); }
894
902
  .msg[data-key] { transition: transform var(--t-fast); }
895
903
  .msg.swipe-ready { box-shadow: 3px 0 0 var(--accent); border-radius: var(--r-sm); } /* let go now: a reply */
896
904
  @media (max-width: 899px) {
@@ -1419,10 +1427,6 @@ body.side-resizing, body.side-resizing * { cursor: col-resize !important; user-s
1419
1427
  .u-stale-detail { color: var(--text-3); font-size: var(--fs-xs); }
1420
1428
  .u-sub { color: var(--text-3); font-size: var(--fs-xs); font-variant-numeric: tabular-nums; }
1421
1429
  /* #3066 §1: a weekly quota's measured 100% under its bar, and its notes (the fleet-only limit always). */
1422
- .u-cap { margin-top: 4px; font-size: var(--fs-xs); }
1423
- .u-cap-line { color: var(--text-2); font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
1424
- .u-cap-wait .u-cap-line { color: var(--text-3); }
1425
- .u-cap-note { color: var(--text-3); overflow-wrap: anywhere; }
1426
1430
  .u-err { color: var(--warn); font-size: var(--fs-sm); }
1427
1431
  .u-foot { display: flex; align-items: center; justify-content: space-between; gap: var(--s-2); }
1428
1432
  /* #1673: the usage rail beside the page on a wide screen (header-tools.js UsageRail; shown only at min-width 1200px). */
@@ -1461,6 +1465,8 @@ body.side-resizing, body.side-resizing * { cursor: col-resize !important; user-s
1461
1465
  .u-cm-tag { font-size: var(--fs-xs); color: var(--text-3); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
1462
1466
  /* #2240: an account of several pools (agy) names each pool's line: a wider label, ending in an ellipsis if it must. */
1463
1467
  .u-crow.is-pooled .u-cm { grid-template-columns: minmax(0, 7.0em) minmax(0, 1fr) 2.9em 3.7em; column-gap: 7px; }
1468
+ /* M-2815: a per-model weekly on its own bar ("Fable"): a wider tag for every bar of that login, so they line up. */
1469
+ .u-crow.has-models .u-cm { grid-template-columns: minmax(0, 3.6em) minmax(0, 1fr) 2.9em 3.7em; }
1464
1470
  .u-cm-bar { height: 6px; border-radius: var(--r-full); background: var(--surface-2); overflow: hidden; }
1465
1471
  .u-cm-fill { display: block; height: 100%; width: 0; min-width: 2px; border-radius: var(--r-full); background: var(--accent); }
1466
1472
  .u-cm-fill.warn { background: var(--warn); } .u-cm-fill.crit { background: var(--danger); }
@@ -66,20 +66,16 @@ function expiryText(iso) {
66
66
  }
67
67
  /**
68
68
  * #3066 §1: a server line ({ text, i18n }) in this page's language — or, when this tab's strings predate the key (a
69
- * stale tab), the server's own English text, never the bare key.
69
+ * stale tab), the server's own English text, never the bare key. M-2815: the card no longer draws capacity; kept
70
+ * exported so a module from another release that imports it still links (settings-stale-module-link-3321).
70
71
  */
71
72
  export function capacityLine(x) {
72
73
  if (!x || typeof x.text !== "string") return "";
73
74
  const key = x.i18n && typeof x.i18n.key === "string" ? `view.${x.i18n.key}` : null;
74
75
  return key && t(key) !== key ? usageText(x.text, x.i18n) : x.text;
75
76
  }
76
- /** #3066 §1: a weekly quota's measured 100% (or why not yet), and the limit it always carries: only this fleet counts. */
77
- function UsageCapacity({ c }) {
78
- const notes = Array.isArray(c.notes) ? c.notes : [];
79
- return html`<div class=${`u-cap${c.status === "ok" ? "" : " u-cap-wait"}`}>
80
- <div class="u-cap-line">${capacityLine(c.line)}</div>
81
- ${notes.map((n, i) => html`<div key=${i} class="u-cap-note">${capacityLine(n)}</div>`)}</div>`;
82
- }
77
+ // M-2815 (the user): the card shows no measured capacity ("100% ≈ …" and its fleet-only note) — get_usage and the usage
78
+ // report keep it (#3066 §1); a weekly metric's `capacity` is left unread here.
83
79
  export function UsageMetric({ m }) {
84
80
  const bar = useRef(null);
85
81
  const label = usageText(m.label, m.labelI18n);
@@ -94,8 +90,7 @@ export function UsageMetric({ m }) {
94
90
  const sub = [note, resetText(m.resetsAt)].filter(Boolean).join(" · ");
95
91
  return html`<div class="u-metric"><div class="u-row"><span class="u-label">${label}</span>${word ? html`<span class=${`u-status ${cls}`}>${word}</span>` : null}
96
92
  <span class=${`u-pct ${cls}`}>${pct.toFixed(0)}<span class="u-unit">%</span></span></div>
97
- <div class="u-meter"><div ref=${bar} class=${`u-fill ${cls}`}></div></div>${sub ? html`<div class="u-sub">${sub}</div>` : null}
98
- ${m.capacity ? html`<${UsageCapacity} c=${m.capacity} />` : null}</div>`;
93
+ <div class="u-meter"><div ref=${bar} class=${`u-fill ${cls}`}></div></div>${sub ? html`<div class="u-sub">${sub}</div>` : null}</div>`;
99
94
  }
100
95
  if (m.type === "dollars") {
101
96
  const val = m.limit ? `$${(m.used ?? 0).toFixed(2)} / $${m.limit.toFixed(2)}` : `$${(m.used ?? 0).toFixed(2)}`;
@@ -176,12 +171,28 @@ export function compactSlots(p) {
176
171
  const pct = ((p && p.metrics) || []).filter((m) => m && m.type === "percent" && !m.resetPassed);
177
172
  const isShort = (m) => Number(m.windowMs) > 0 && m.windowMs < TWO_DAYS;
178
173
  const short = pct.filter(isShort).sort((a, b) => a.windowMs - b.windowMs)[0] || null;
179
- const long = pct.filter((m) => !isShort(m)).map((m, i) => ({ m, i }))
174
+ // M-2815: the long column is the account's own week; a per-model one (scope "model") only when it has nothing else.
175
+ const longest = (list) => list.map((m, i) => ({ m, i }))
180
176
  .sort((a, b) => ((Number(b.m.windowMs) || -1) - (Number(a.m.windowMs) || -1)) || a.i - b.i)[0]?.m || null;
177
+ const longs = pct.filter((m) => !isShort(m));
178
+ const long = longest(longs.filter((m) => m.scope !== "model")) || longest(longs);
181
179
  return { short, long };
182
180
  }
183
- /** The windows a compact line shows, short first. */
184
- export const compactMetrics = (p) => { const { short, long } = compactSlots(p); return [short, long].filter(Boolean); };
181
+ /**
182
+ * The windows a compact line shows, short first; then (M-2815, the user) each per-model weekly ("Fable (weekly)") the
183
+ * server sends, on its own labelled bar — a per-model window under two days stays in the full card.
184
+ */
185
+ export const compactMetrics = (p) => {
186
+ const { short, long } = compactSlots(p);
187
+ const models = ((p && p.metrics) || []).filter((m) => m && m.type === "percent" && !m.resetPassed && m.scope === "model"
188
+ && m !== long && Number(m.windowMs) >= TWO_DAYS);
189
+ return [short, long, ...models].filter(Boolean);
190
+ };
191
+ /** A per-model window's tag on the compact line: the model's name ("Fable"), the window's full name in its tooltip. */
192
+ export function modelTag(m) {
193
+ const arg = m && m.labelI18n && Array.isArray(m.labelI18n.args) ? m.labelI18n.args[0] : null;
194
+ return typeof arg === "string" && arg ? arg : String((m && m.label) || "").replace(/\s*\(weekly\)$/i, "");
195
+ }
185
196
  /** A window as a few characters ("5h", "7d"); one whose length is not known says its label. */
186
197
  export function windowTag(m) {
187
198
  const ms = Number(m && m.windowMs);
@@ -275,13 +286,14 @@ export function CompactRow({ p, onExpand }) {
275
286
  const say = stale ? stale.mark : note || tn("usage.no_data");
276
287
  const detail = stale ? [stale.mark, stale.detail].filter(Boolean).join(" — ") : say;
277
288
  const name = title.profile || title.base;
278
- return html`<button type="button" class=${`u-crow${p.stale ? " is-stale" : ""}${pools ? " is-pooled" : ""}`} aria-expanded="false" title=${`${p.name} — ${tn("usageExpand")}`} onClick=${onExpand}>
289
+ const models = !pools && metrics.some((m) => m.scope === "model");
290
+ return html`<button type="button" class=${`u-crow${p.stale ? " is-stale" : ""}${pools ? " is-pooled" : ""}${models ? " has-models" : ""}`} aria-expanded="false" title=${`${p.name} — ${tn("usageExpand")}`} onClick=${onExpand}>
279
291
  <span class="u-crow-head"><span class="u-crow-name">${name}</span>
280
292
  ${p.plan ? html`<span class="pill u-plan" title=${p.plan}><span aria-hidden="true">${planBadge(p.plan)}</span><span class="sr-only">${p.plan}</span></span>` : null}
281
293
  ${stale && metrics.length ? html`<span class="u-crow-stale" title=${detail}>${p.cachedAt ? tn("usageCachedAt", { at: usageClock(p.cachedAt) }) : stale.mark}<span class="sr-only"> (${detail})</span></span>` : null}</span>
282
294
  ${pools ? pools.map((x) => html`<${CompactMeter} key=${x.pool.label} m=${x.worst} tag=${usageText(x.pool.label, x.pool.labelI18n)}
283
295
  title=${x.metrics.map((m) => { const c = resetClock(m); return `${usageText(m.label, m.labelI18n)}: ${pctOf(m).toFixed(0)}%${c ? ` (${c})` : ""}`; }).join(" · ")} />`)
284
- : metrics.length ? metrics.map((m, j) => html`<${CompactMeter} key=${j} m=${m} />`)
296
+ : metrics.length ? metrics.map((m, j) => html`<${CompactMeter} key=${j} m=${m} tag=${m.scope === "model" ? modelTag(m) : undefined} />`)
285
297
  : html`<span class=${`u-crow-note${(stale || (p.status === "error" && !p.transient)) ? " is-alert" : ""}`} title=${detail}>${say}</span>`}
286
298
  </button>`;
287
299
  }
@@ -376,7 +388,7 @@ export function UsageBody({ owner }) {
376
388
  ${compact ? compactGroups(providers).map((g) => html`<${CompactGroup} key=${g.base} group=${g}
377
389
  line=${({ p, i }) => (expanded.has(key(p)) ? card(p, i) : html`<${CompactRow} key=${key(p)} p=${p} onExpand=${() => toggleOne(key(p))} />`)} />`)
378
390
  : providers.map((p, i) => card(p, i))}
379
- <div class="u-foot"><span class="note" title=${new Date(data.fetchedAt).toLocaleString()}>${updatedAgo(data.fetchedAt)}${failed ? html` · <span class="u-refresh-failed" role="status">${tn("usageRefreshFailed")}</span>` : data.refreshing ? html` · <span class="u-refreshing">${tn("usageRefreshing")}</span>` : null}</span>
391
+ <div class="u-foot"><span class="note" title=${new Date(data.fetchedAt).toLocaleString()}>${failed ? html`${updatedAgo(data.fetchedAt)} · <span class="u-refresh-failed" role="status">${tn("usageRefreshFailed")}</span>` : data.refreshing ? html`<span class="u-refreshing">${tn("usageRefreshing")}</span>` : updatedAgo(data.fetchedAt)}</span>
380
392
  ${byAgent() ? html`<a class="btn btn-ghost btn-sm u-by-agent" href="/ui/fleet/usage" title=${tn("usageByAgentTitle")}>${tn("usageByAgent")}</a>` : null}
381
393
  <button type="button" class="btn btn-sm" onClick=${() => load(true)}>${tn("usageRefresh")}</button></div>`;
382
394
  }