dsh-composer-live 0.3.1 → 0.4.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/CHANGELOG.md CHANGED
@@ -2,6 +2,33 @@
2
2
 
3
3
  > 更新日志以中文记录。Changelog entries are written in Chinese.
4
4
 
5
+ ## 0.4.0(2026-11-20)
6
+
7
+ **行级差量渲染——长文档打字从「每键全文档重建」到「只重写光标行」。视觉零变化,纯性能版。**
8
+
9
+ ### ⚡ 渲染层改「行容器定位 + 行级差量替换」
10
+
11
+ 以前每敲一个键,整个渲染层(背景 + 全部文字段)推倒重建:200 行文档打 60 个字实测 33 次超 50ms 的长任务(最大 170ms、22% 的帧超 32ms)——长文档打字的顿挫感全部来源于此。现在:
12
+
13
+ - **渲染层结构改为「背景层 + 每行容器」**:行容器承担绝对定位(锚在行首字符坐标),行内文字段坐标改为相对行首——行内容与行位置彻底解耦
14
+ - **打字只重写变化的 1-2 行**:行文本与形态(焦点态/引用装饰/等宽位)未变的行,正则解析、token 化、DOM 重建全部跳过,行 HTML 直接复用;实测 60 键去重后**只重写 1 个行容器**(差量命中率 99%+)
15
+ - **光标跨行只重写新旧两行**(旧行回阅读态 + 新行进源码态),不再全文档重建——拖选/跳行的顿挫同步消失
16
+ - **上游折行变化不再引发下游重测**:测量缓存验证拆为 x/y 两半——x 过而 y 偏 = 整行平移,缓存坐标就地重定基(1 次测量 + 加法,替代整行数千次重测)
17
+ - **firstDiff 短路**:首个文本变化行之上的行整体跳过验证与定位——打字稳态成本与文档长度解耦,200 行和 20 行一样轻
18
+
19
+ **实测(200 行文档,与 v0.3.x 同一把尺子)**:打字 60 键长任务 33 次 → **0 次**(max 170ms → 0);超 32ms 帧占比 22% → **0**;扩选长任务 109ms → **0**;空闲零渲染保持不回归。
20
+
21
+ ### ⚡ 每键热路径瘦身
22
+
23
+ - **卡底色查询移出每键路径**(0.3.1 引入的祖先链 `getComputedStyle` 每键 3-6 次 → 只随主题/换肤变化时重查,2 秒兜底)
24
+ - **度量读取拆轻重两段**:签名命中路径(空闲/同行光标移动)只读 color+padding 两属性;全量度量复制只在真渲染时跑
25
+ - **keydown 白名单早退**:普通打字键不再经过锚表构建(每键省 O(文档) 遍历)
26
+ - 顺手修一个存量 O(N²):等宽位判定从行循环内提出(200 行文档每帧 4 万次 → 1 次)
27
+
28
+ ### 🧪 性能门槛固化(`e2e/run-perf.mjs`)
29
+
30
+ 136 个 E2E 场景只管「画得对不对」,本版起「跑得快不快」也有自动化门槛:空闲零渲染 / 打字帧中位 <20ms / 长任务 ≤8 次 / 扩选 ≤60ms,双环境各跑一次,宽松阈值防退化不误报。`diag-perf.mjs` 同步新增「重写行数」直接指标。
31
+
5
32
  ## 0.3.1(2026-11-15)
6
33
 
7
34
  ### 🩹 代码块配色改「从输入卡底色派生」——修复部分皮肤深色下代码块与输入框同色隐形
package/README.md CHANGED
@@ -9,7 +9,7 @@
9
9
  <p align="center">
10
10
  <img src="https://img.shields.io/badge/License-MIT-blue.svg" alt="License: MIT">
11
11
  <img src="https://img.shields.io/badge/DSH-%3E%3D%200.1.5--rc.2-4c6ef5" alt="DSH >= 0.1.5-rc.2">
12
- <img src="https://img.shields.io/badge/tests-246%20unit%20%C2%B7%20136%20E2E-2ea44f" alt="tests">
12
+ <img src="https://img.shields.io/badge/tests-246%20unit%20%C2%B7%20141%20E2E-2ea44f" alt="tests">
13
13
  </p>
14
14
 
15
15
  ![Live typing demo: inline styles, lists, task items, then a ```js code block auto-completes and highlights as you type](https://github.com/zeusxx/dsh-composer-live/raw/main/docs/screenshots/demo.gif)
@@ -124,7 +124,7 @@ The official composer already provides — and this plugin deliberately does not
124
124
  - A **Chromium-based browser** (Chrome, Edge, …): the transparency technique relies on `-webkit-text-fill-color`.
125
125
  - OS-independent — it is pure DOM/CSS with no native dependencies.
126
126
 
127
- **Verified DSH versions** — every release runs the full 136-scenario E2E suite on two live instances covering both supported generations:
127
+ **Verified DSH versions** — every release runs the full 141-scenario E2E suite on two live instances covering both supported generations:
128
128
 
129
129
  | DSH version | Status |
130
130
  | --- | --- |
@@ -167,6 +167,8 @@ The official composer is a Lexical contenteditable editor. This plugin makes its
167
167
 
168
168
  Because the overlay never does its own layout, alignment bugs (drift, jitter, misplacement) cannot exist by construction: measured deviation is ≤ 0.02px across scenarios, 0.00 per keystroke frame.
169
169
 
170
+ **Row-level differential rendering (v0.4.0)** — the overlay is split into a background layer plus one positioned container per line, with segment coordinates relative to the line head. Typing re-renders only the 1–2 changed lines (a 60-keystroke burst on a 200-line document rewrites exactly **one** line container — 0 long tasks, versus 33 tasks peaking at 170 ms before), and cursor moves across lines rewrite only the old and new line. Re-flowing an upstream line shifts downstream lines with a single `style.top` write each — no re-measuring, no re-parsing. Steady-state typing cost is decoupled from document length.
171
+
170
172
  The plugin injects no official services. It reads the editor DOM directly and derives a "projection text" (chips → U+FFFC, `<br>`/paragraph boundaries → newlines), which keeps it immune to client API churn; DOM anchoring uses stable `data-` attributes instead of hashed CSS-module class names. Draft edits (list continuation, fence completion, indenting…) go through Lexical-native channels — synthetic `beforeinput` events that preserve the undo stack — never direct DOM mutation.
171
173
 
172
174
  See [docs/architecture.md](./docs/architecture.md) for the full deep dive.
@@ -195,8 +197,9 @@ This plugin focuses purely on the **editing experience**. Other composer plugins
195
197
  ## Development
196
198
 
197
199
  ```bash
198
- node test-live.cjs # 220 unit tests (pure functions, no browser needed)
199
- node e2e/run-e2e.mjs # 136-scenario × 10-invariant E2E suite against a live instance
200
+ node test-live.cjs # 246 unit tests (pure functions, no browser needed)
201
+ node e2e/run-e2e.mjs # 141-scenario × 10-invariant E2E suite against a live instance
202
+ node e2e/run-perf.mjs # performance gate: idle 0 renders, typing frame median <20ms, long tasks ≤8 (loose anti-regression thresholds)
200
203
  ```
201
204
 
202
205
  The E2E runner expects a DSH web instance with this source deployed and derives everything from environment variables: `DSH_CL_PORT` (default 8124) and `DSH_CL_DSH_HOME` (defaults to `DSH_HOME`, then `~/.dsh`) locate the deployed copy for a version check; the auth cookie is fetched automatically. See [e2e/README.md](./e2e/README.md) for the full variable list.
package/README.zh-CN.md CHANGED
@@ -9,7 +9,7 @@
9
9
  <p align="center">
10
10
  <img src="https://img.shields.io/badge/License-MIT-blue.svg" alt="License: MIT">
11
11
  <img src="https://img.shields.io/badge/DSH-%3E%3D%200.1.5--rc.2-4c6ef5" alt="DSH >= 0.1.5-rc.2">
12
- <img src="https://img.shields.io/badge/tests-246%20unit%20%C2%B7%20136%20E2E-2ea44f" alt="tests">
12
+ <img src="https://img.shields.io/badge/tests-246%20unit%20%C2%B7%20141%20E2E-2ea44f" alt="tests">
13
13
  </p>
14
14
 
15
15
  ![实时打字演示:行内格式、列表、任务项,```js 代码块自动补全并语法高亮](https://github.com/zeusxx/dsh-composer-live/raw/main/docs/screenshots/demo.gif)
@@ -120,7 +120,7 @@ Obsidian「实时预览」式:**光标/选区所在行显示源码标记**(
120
120
 
121
121
  ## 实测版本
122
122
 
123
- 每个版本发布前都在两个真实实例上跑完整 136 场景 E2E(覆盖两代支持的架构):
123
+ 每个版本发布前都在两个真实实例上跑完整 141 场景 E2E(覆盖两代支持的架构):
124
124
 
125
125
  | DSH 版本 | 状态 |
126
126
  | --- | --- |
@@ -169,6 +169,8 @@ DSH_HOME=/path/to/your/.dsh dsh plugin --profile web add dsh-composer-live
169
169
 
170
170
  渲染层从不自己排版,所以对齐类问题(漂移、抖动、错位)在架构上不存在:实测各场景偏差 ≤ 0.02px,连续打字逐帧偏差 0.00。
171
171
 
172
+ **行级差量渲染(v0.4.0)**——渲染层拆成「背景层 + 每行容器」,段坐标相对行首。打字只重画变化的 1-2 行(200 行文档连打 60 键实测只重写 **1 个**行容器、0 次长任务——优化前 33 次、最大 170ms);光标跨行只重写新旧两行;上游折行变化对下游只是每行一次 `style.top` 写入(零重测零重解析)——打字稳态成本与文档长度解耦,长文档与短文档一样轻。
173
+
172
174
  插件不注入任何官方服务。它直接读编辑器 DOM 推导「投影文本」(胶囊 → U+FFFC,`<br>`/段落边界 → 换行),对官方 client API 变化免疫;DOM 锚定用稳定的 `data-` 属性而非哈希过的 CSS Modules 类名。改动草稿的操作(列表续项、围栏补全、缩进……)走 Lexical 原生通道——保撤销栈的合成 `beforeinput` 事件——绝不直接改 DOM。
173
175
 
174
176
  完整深读见 [docs/architecture.md](./docs/architecture.md)。
@@ -186,8 +188,9 @@ DSH_HOME=/path/to/your/.dsh dsh plugin --profile web add dsh-composer-live
186
188
  ## 开发
187
189
 
188
190
  ```bash
189
- node test-live.cjs # 220 项单测(纯函数,无需浏览器)
190
- node e2e/run-e2e.mjs # 136 场景 × 10 不变量的 E2E 套件(对着运行中的实例测)
191
+ node test-live.cjs # 246 项单测(纯函数,无需浏览器)
192
+ node e2e/run-e2e.mjs # 141 场景 × 10 不变量的 E2E 套件(对着运行中的实例测)
193
+ node e2e/run-perf.mjs # 性能门槛:空闲零渲染、打字帧中位 <20ms、长任务 ≤8(宽松防退化阈值)
191
194
  ```
192
195
 
193
196
  E2E runner 要求被测实例已部署当前源码,路径全部由环境变量推导:`DSH_CL_PORT`(默认 8124)与 `DSH_CL_DSH_HOME`(默认取 `DSH_HOME`,再默认 `~/.dsh`)定位部署副本做版本对照,鉴权 cookie 自动获取。完整变量表见 [e2e/README.md](./e2e/README.md)。
package/client.js CHANGED
@@ -72,6 +72,8 @@ window.__ModuleLoader__.load({
72
72
  const CHIP_HOST_SEL = "[data-composer-chip]";
73
73
  /** 文本引用装饰(热词高亮):内容参与投影(非原子 chip),但透明化下需要恢复显示。 */
74
74
  const TEXT_REF_SEL = "[data-composer-text-ref]";
75
+ /** keydown 关心的键(v0.4.0 早退白名单):decideKeyAction 只对这三键返回动作。 */
76
+ const KEY_ACTS = ["Enter", "Tab", "ArrowDown"];
75
77
  /** chip 在「投影文本」里的字符(与官方 detectText 同构)。 */
76
78
  const CHIP_CHAR = "";
77
79
  /** 行内代码/图片占位控制字符(不与正文数字混淆)。 */
@@ -460,9 +462,9 @@ window.__ModuleLoader__.load({
460
462
  * 3000 次测量降到 ~300 次)。同文本多行(空行/重复行)共享 key 互相顶替 →
461
463
  * 各自全测,无害。
462
464
  */
463
- function measureAnchorChars(anchors, lineCount, cache, layoutGen) {
465
+ function measureAnchorChars(anchors, lineCount, cache, layoutGen, firstDiff) {
464
466
  const useCache = !!(cache && layoutGen);
465
- if (useCache && cache.gen !== layoutGen) { cache.gen = layoutGen; cache.lines.clear(); }
467
+ if (useCache && cache.gen !== layoutGen) { cache.gen = layoutGen; cache.entries.length = 0; cache.prevLines = []; }
466
468
  const range = document.createRange();
467
469
  // 第一遍(零测量):把锚流切成分段的「行」(seg = 文本节点内的字符区间),
468
470
  // 同时拼出行文本(缓存 key)。行边界 = br/para 锚 + 文本节点内字面 \n。
@@ -493,22 +495,43 @@ window.__ModuleLoader__.load({
493
495
  }
494
496
  off += len;
495
497
  }
496
- // 第二遍:逐行缓存判定 → 命中直接用;miss 全行测量并回填。
498
+ // 第二遍(v0.4.0 按行号条目 + x/y 拆分验证 + dy 重定基 + firstDiff 短路):
499
+ // - firstDiff 之上的行:文本未变且其上布局未变 → 直接用缓存(零测量)
500
+ // - 文本同的行:只验证行首 x(左对齐下 x 恒定);x 过而 y 偏 = 整行平移
501
+ // (上游折行数变化),缓存数组就地 +dy 重定基(精确,无逐字符重测)
502
+ // - x 也偏 = 重折行/字体变 → 全行重测回填
503
+ // 旧「全文本 Map + x/y 双验证」对 y 平移必失败(打字改折行时下游全量重测,
504
+ // 正是 longTask 主力),且同文本多行互相顶替(重复行每帧全测)——按行号
505
+ // 索引一并消除。条目长度 = 行数,自然收缩,无需旧的上限防泄漏。
506
+ const entries = useCache ? cache.entries : null;
497
507
  const lineChars = [];
498
508
  for (let li = 0; li < lineCount; li++) {
499
509
  const row = li < rows.length ? rows[li] : null;
500
510
  const text = li < texts.length ? texts[li] : null;
511
+ const e = entries ? entries[li] : null;
501
512
  let chars = null;
502
- if (useCache && row && row.length) {
503
- const m = cache.lines.get(text);
504
- if (m && m.length) {
505
- const s0 = row[0];
506
- try {
507
- range.setStart(s0.node, s0.from);
508
- range.setEnd(s0.node, s0.from + 1);
509
- const pr = range.getBoundingClientRect();
510
- if (pr && Math.abs(pr.top - m[0].y) < 0.5 && Math.abs(pr.left - m[0].x) < 0.5) chars = m;
511
- } catch (err) { /* 验证失败 → 全行重测 */ }
513
+ if (e && e.text === text) {
514
+ if (!e.chars.length || li < firstDiff) {
515
+ chars = e.chars; // 空行无可测;firstDiff 之上布局必未变,零验证
516
+ } else {
517
+ const s0 = row && row[0];
518
+ if (s0) {
519
+ try {
520
+ range.setStart(s0.node, s0.from);
521
+ range.setEnd(s0.node, s0.from + 1);
522
+ const pr = range.getBoundingClientRect();
523
+ if (pr && Math.abs(pr.left - e.chars[0].x) < 0.5) {
524
+ const dy = pr.top - e.chars[0].y;
525
+ if (Math.abs(dy) < 0.5) {
526
+ chars = e.chars;
527
+ } else if (Math.abs(dy) < 64) {
528
+ for (const c of e.chars) c.y += dy; // 整行平移:y 重定基
529
+ chars = e.chars;
530
+ }
531
+ // dy 超界(异常跳变,如切会话残留)→ 视为 miss 全行重测
532
+ }
533
+ } catch (err) { /* 验证失败 → 全行重测 */ }
534
+ }
512
535
  }
513
536
  }
514
537
  if (!chars) {
@@ -527,34 +550,60 @@ window.__ModuleLoader__.load({
527
550
  } catch (err) { /* 跳过该段 */ }
528
551
  }
529
552
  }
530
- if (useCache && chars.length) cache.lines.set(text, chars);
553
+ if (entries) entries[li] = { text, chars };
531
554
  }
532
555
  lineChars.push(chars);
533
556
  }
534
- if (useCache && cache.lines.size > 800) cache.lines.clear(); // 上限防泄漏(长会话删行残留)
557
+ if (entries && entries.length > lineCount) entries.length = lineCount;
558
+ if (cache) cache.prevLines = texts.slice(0, lineCount);
535
559
  return lineChars;
536
560
  }
537
561
 
538
- /** 字符锚定渲染主入口:清空 overlay,按测量坐标输出「整块背景 + 定位字符段」。 */
562
+ /** 字符锚定渲染主入口(v0.4.0 行级差量):overlay = 背景层 + 每行容器。
563
+ * 行容器承担定位(left/top = 行首字符的 ov 相对坐标),段坐标改为相对行首
564
+ * ——行 HTML 与绝对位置解耦:上游折行变化引起的 y 平移退化为每行一次
565
+ * style.top 写(零重建零重测);行文本与形态未变则行 HTML 直接复用(正则
566
+ * 链、tokenizeViaDom、innerHTML 解析全跳过)。打字稳态只重写光标行 1-2 行,
567
+ * 光标跨行只重写新旧两行,成本与文档长度解耦(firstDiff 之上整体短路)。 */
539
568
  function renderCharOverlay(ov, input, anchors, lines, states, refs, cache, layoutGen, editSet) {
540
569
  const ovRect = ov.getBoundingClientRect();
541
570
  const ox = ovRect.left, oy = ovRect.top;
542
571
  const segLineHeight = getComputedStyle(ov).lineHeight; // 段定位的 half-leading 修正用
543
- const lineChars = measureAnchorChars(anchors, lines.length, cache, layoutGen);
572
+ // firstDiff:首个文本变化行——之上的行布局未变(测量零验证、位置零写入)
573
+ let firstDiff = lines.length;
574
+ for (let i = 0; i < lines.length; i++) {
575
+ if (cache.prevLines[i] !== lines[i]) { firstDiff = i; break; }
576
+ }
577
+ const lineChars = measureAnchorChars(anchors, lines.length, cache, layoutGen, firstDiff);
544
578
  // 容器内容区(块背景的水平范围——统一宽度消灭按行宽的锯齿)
545
579
  const inpRect = input.getBoundingClientRect();
546
580
  const ics = getComputedStyle(input);
547
581
  const pl = parseFloat(ics.paddingLeft) || 0, pr = parseFloat(ics.paddingRight) || 0;
548
582
  const contentLeft = inpRect.left + pl - 12;
549
583
  const contentW = inpRect.width - pl - pr + 24;
550
- let out = "";
551
584
  // 每行在投影文本中的起始 offset(refs 区间按绝对 offset 匹配字符)
552
585
  const lineStarts = [];
553
586
  let lineAcc = 0;
554
587
  for (const l of lines) { lineStarts.push(lineAcc); lineAcc += l.length + 1; }
588
+ // ===== 骨架守卫:ov 被清空过(fallbackToOfficial / !editable 分支 / 官方
589
+ // 重挂)时 bglayer 不在 → 重建骨架并整体失效行缓存(rowEls 已随 ov 清空
590
+ // 失联,entries 的 HTML/坐标签名一并作废)。
591
+ let bgWrap = ov.querySelector(":scope > .dsh-cl-bglayer");
592
+ if (!bgWrap) {
593
+ ov.textContent = "";
594
+ bgWrap = document.createElement("div");
595
+ bgWrap.className = "dsh-cl-bglayer";
596
+ ov.appendChild(bgWrap);
597
+ cache.entries.length = 0;
598
+ cache.prevLines = [];
599
+ cache.rowEls = [];
600
+ firstDiff = 0;
601
+ }
555
602
  // ===== 块级背景(代码块整块一个矩形:垂直无缝;引用段同理) =====
556
603
  // 逐行画背景会按行内容宽度锯齿 + 行间露缝——聚合到块级:从块首行首字符顶
557
604
  // 到块末行末字符底 ±2.5px,水平取容器内容宽。块内空行天然被矩形覆盖。
605
+ // v0.4.0:bgOut 串拼进 bglayer,串本身即签名——变了才写 innerHTML。
606
+ let bgOut = "";
558
607
  const blockBgDone = new Set();
559
608
  const verticalPad = 2.5;
560
609
  for (let li = 0; li < lines.length; li++) {
@@ -572,8 +621,8 @@ window.__ModuleLoader__.load({
572
621
  continue;
573
622
  }
574
623
  const cls = "dsh-cl-bg" + (st.fenceOpen ? " dsh-cl-bg-open" : "") + (states[end].fenceClose ? " dsh-cl-bg-close" : "");
575
- out += '<div class="' + cls + '" style="left:' + (contentLeft - ox) + "px;top:" + (top - oy - verticalPad) + "px;width:" + contentW + "px;height:" + (bottom - top + verticalPad * 2) + 'px"></div>';
576
- if (st.fenceOpen && st.lang) out += '<span class="dsh-cl-lang" style="top:' + (top - oy + 2) + 'px">' + escapeHtml(st.lang) + "</span>";
624
+ bgOut += '<div class="' + cls + '" style="left:' + (contentLeft - ox) + "px;top:" + (top - oy - verticalPad) + "px;width:" + contentW + "px;height:" + (bottom - top + verticalPad * 2) + 'px"></div>';
625
+ if (st.fenceOpen && st.lang) bgOut += '<span class="dsh-cl-lang" style="top:' + (top - oy + 2) + 'px">' + escapeHtml(st.lang) + "</span>";
577
626
  for (let k = li; k <= end; k++) blockBgDone.add(k);
578
627
  }
579
628
  // 引用段(连续 quote 行聚合一个背景)
@@ -587,84 +636,135 @@ window.__ModuleLoader__.load({
587
636
  for (let k = li; k <= end; k++) {
588
637
  for (const c of lineChars[k]) { if (c.y < top) top = c.y; if (c.y + c.h > bottom) bottom = c.y + c.h; }
589
638
  }
590
- if (top !== Infinity) out += '<div class="dsh-cl-qbg" style="left:' + (contentLeft - ox) + "px;top:" + (top - oy - verticalPad) + "px;width:" + contentW + "px;height:" + (bottom - top + verticalPad * 2) + 'px"></div>';
639
+ if (top !== Infinity) bgOut += '<div class="dsh-cl-qbg" style="left:' + (contentLeft - ox) + "px;top:" + (top - oy - verticalPad) + "px;width:" + contentW + "px;height:" + (bottom - top + verticalPad * 2) + 'px"></div>';
591
640
  for (let k = li; k <= end; k++) quoteBgDone.add(k);
592
641
  }
593
- // ===== 字符段渲染 =====
642
+ if (bgWrap.__dshClSig !== bgOut) { bgWrap.innerHTML = bgOut; bgWrap.__dshClSig = bgOut; }
643
+ // ===== 行容器差量 =====
644
+ // 等宽整框位提出行循环(旧版在行内 states.some 是 O(N²),200 行 4 万次/帧)。
645
+ const anyCode = states.some((st) => st.inCode);
646
+ const rows = cache.rowEls || (cache.rowEls = []);
594
647
  for (let li = 0; li < lines.length; li++) {
595
648
  const line = lines[li];
596
649
  const st = states[li];
597
- if (paraHasChip(line)) continue; // chip 行:官方原样(KEEP)
598
650
  const chars = lineChars[li];
599
- if (!chars.length) continue; // 空行:背景已由块级矩形覆盖
600
- // 行字符的样式 token(HTML 复用既有正则链 → DOM 解析)
601
- let html;
602
- if (st.inCode) html = codeLineContent(line, st.fenceOpen ? "dsh-cl-fence-open" : (st.fenceClose ? "dsh-cl-fence-close" : ""), st.lang, st.fenceOpen, -2);
603
- else html = inlineLineContent(line, null);
604
- const tokens = tokenizeViaDom(html);
605
- // token → 每字符样式类(token 文本流 = 源文字符流,mk 占位保证逐字符对应)
606
- const charCls = new Array(chars.length).fill("");
607
- let ci = 0;
608
- for (const tk of tokens) {
609
- const tl = tk.text.length;
610
- for (let k = 0; k < tl && ci < chars.length; k++, ci++) charCls[ci] = tk.cls;
611
- }
612
- // 焦点行(v0.3.0):非编辑行 → 阅读形态(标记隐身/符号化)。表格行与
613
- // 代码围栏行恒源码(竖线/围栏是编辑结构,不随光标离开而阅读化)。
651
+ // 行形态签名(内容层,无坐标):state + 有效源码位 + refs 裁剪 + 等宽位。
652
+ // 有效源码位必须含 alwaysSrc(表格/围栏行恒源码)——光标扫过它们不重建。
614
653
  const alwaysSrc = (st.kind && st.kind.type === "table") || st.fenceOpen || st.fenceClose;
615
- if (!alwaysSrc && !(editSet && editSet.has(li))) {
616
- for (let k = 0; k < charCls.length; k++) charCls[k] = toReadingForm(charCls[k]);
617
- }
618
- // 官方文本引用装饰(/ 命令、技能名)→ 引用色。编辑器文字透明,官方给
619
- // 装饰 span 的 color 看不见;按投影区间在渲染层补上同一主题色。
654
+ const srcBit = alwaysSrc || (editSet && editSet.has(li)) ? "s" : "r";
655
+ let refMask = "";
620
656
  if (refs.length) {
621
- const base = lineStarts[li] || 0;
622
- for (let k = 0; k < chars.length; k++) {
623
- const abs = base + chars[k].off;
624
- for (const r of refs) {
625
- if (abs >= r.start && abs < r.end) {
626
- charCls[k] = (charCls[k] ? charCls[k] + " " : "") + "dsh-cl-ref";
627
- break;
628
- }
629
- }
657
+ const ls = lineStarts[li] || 0, le = ls + line.length, parts = [];
658
+ for (const r of refs) if (r.end > ls && r.start < le) parts.push((Math.max(r.start, ls) - ls) + ":" + (Math.min(r.end, le) - ls));
659
+ refMask = parts.join(",");
660
+ }
661
+ const sig = stateKey(st) + "\u0001" + srcBit + "\u0001" + refMask + "\u0001" + (anyCode ? "M" : "");
662
+ const e = cache.entries[li];
663
+ if (!e || e.text !== line || e.sig !== sig) {
664
+ // 空行/chip 行 → 空容器(chip 行官方原样 KEEP;空行背景由块级矩形覆盖)
665
+ cache.entries[li] = { text: line, chars, sig, html: buildRowHtml(line, st, chars, srcBit === "s", refs, lineStarts[li] || 0, anyCode, segLineHeight) };
666
+ }
667
+ const entry = cache.entries[li];
668
+ // DOM 槽位(按行号对齐;增长尾部 append 保文档序)
669
+ let rowEl = rows[li];
670
+ if (!rowEl || !rowEl.isConnected || rowEl.parentElement !== ov) {
671
+ rowEl = document.createElement("div");
672
+ rowEl.className = "dsh-cl-row";
673
+ rowEl.dataset.li = String(li);
674
+ ov.appendChild(rowEl);
675
+ rows[li] = rowEl;
676
+ }
677
+ if (rowEl.__dshClHtml !== entry.html) { rowEl.innerHTML = entry.html; rowEl.__dshClHtml = entry.html; }
678
+ // 位置(行首字符 ov 相对坐标;firstDiff 之上布局未变跳过)
679
+ if (li >= firstDiff && chars.length) {
680
+ const c0 = chars[0];
681
+ const pos = (c0.x - ox) + "," + (c0.y - oy);
682
+ if (rowEl.__dshClPos !== pos) {
683
+ rowEl.style.left = (c0.x - ox) + "px";
684
+ rowEl.style.top = (c0.y - oy) + "px";
685
+ rowEl.__dshClPos = pos;
630
686
  }
631
687
  }
632
- // 合并「同样式 + 同视觉行 + 横向连续」的字符成段(段内浏览器排版同字体零差)。
633
- // 等宽整框语义:文档含代码块时全部段用等宽合成栈(与编辑器 MONO_ALL 同源变量)。
634
- const anyCode = states.some((st) => st.inCode);
635
- const codeCls = anyCode ? " dsh-cl-codefont" : "";
636
- // 段定位必须用「行盒顶」而非「字形盒顶」:段内字符随段自身行盒排版,
637
- // 字形顶 = 段top + half-leading((行高-字形高)/2)。直接拿测量出的字形顶
638
- // 定位会让渲染文字整体下移 half-leading(实测恒 +3px:行高27/字形21)。
639
- // 段内其余字符的相对排布与编辑器同构(同字体同行高同基线规则),首字符
640
- // 对齐即全段对齐;代码行等宽段用该段首字符的字形高计算。
641
- const segLineH = parseFloat(segLineHeight) || 0;
642
- let segStart = 0;
643
- const flush = (endExclusive) => {
644
- const s = chars[segStart];
645
- let text = "";
646
- // 段 text 剔除 \r:CRLF 粘贴的行尾 \r 在段内(white-space:pre)会被当
647
- // 真换行——段盒凭空多撑一行(代码块背景多一块)。编辑器把 \r 当
648
- // 换行语义的一部分(0 宽不可见),渲染侧同样零宽处理=直接不画。
649
- for (let k = segStart; k < endExclusive; k++) {
650
- const ch = line.charAt(chars[k].off);
651
- if (ch !== "\r") text += ch;
688
+ }
689
+ while (rows.length > lines.length) rows.pop().remove();
690
+ // DOM 序校正:确保 bglayer 之后按行序排列——querySelectorAll 返回文档序
691
+ // (INV-4 断言依赖),中途行重建 + 首尾行残留的稀疏场景会乱序,逐位拉回。
692
+ const kids = ov.children;
693
+ for (let i = 1; i <= rows.length; i++) {
694
+ if (kids[i] !== rows[i - 1]) ov.insertBefore(rows[i - 1], kids[i] || null);
695
+ }
696
+ cache.prevLines = lines.slice();
697
+ }
698
+
699
+ /** 单行 → 段 HTML(v0.4.0 从 renderCharOverlay 抽取)。段坐标相对行首字符 c0
700
+ * (行容器承担绝对定位)——同行文本在同字体同宽下段相对布局恒定,行 HTML
701
+ * 可跨「y 平移」复用。合段/半行距/refs 染色/阅读态逻辑与旧版逐字一致。 */
702
+ function buildRowHtml(line, st, chars, isSrc, refs, lineStart, anyCode, segLineHeight) {
703
+ if (!chars.length || paraHasChip(line)) return "";
704
+ // 行字符的样式 token(HTML 复用既有正则链 → DOM 解析)
705
+ let html;
706
+ if (st.inCode) html = codeLineContent(line, st.fenceOpen ? "dsh-cl-fence-open" : (st.fenceClose ? "dsh-cl-fence-close" : ""), st.lang, st.fenceOpen, -2);
707
+ else html = inlineLineContent(line, null);
708
+ const tokens = tokenizeViaDom(html);
709
+ // token → 每字符样式类(token 文本流 = 源文字符流,mk 占位保证逐字符对应)
710
+ const charCls = new Array(chars.length).fill("");
711
+ let ci = 0;
712
+ for (const tk of tokens) {
713
+ const tl = tk.text.length;
714
+ for (let k = 0; k < tl && ci < chars.length; k++, ci++) charCls[ci] = tk.cls;
715
+ }
716
+ // 焦点行(v0.3.0):非编辑行 → 阅读形态(标记隐身/符号化)。isSrc 已含
717
+ // 「表格行与代码围栏行恒源码」(竖线/围栏是编辑结构,不随光标离开而阅读化)。
718
+ if (!isSrc) {
719
+ for (let k = 0; k < charCls.length; k++) charCls[k] = toReadingForm(charCls[k]);
720
+ }
721
+ // 官方文本引用装饰(/ 命令、技能名)→ 引用色。编辑器文字透明,官方给
722
+ // 装饰 span 的 color 看不见;按投影区间在渲染层补上同一主题色。
723
+ if (refs.length) {
724
+ for (let k = 0; k < chars.length; k++) {
725
+ const abs = lineStart + chars[k].off;
726
+ for (const r of refs) {
727
+ if (abs >= r.start && abs < r.end) {
728
+ charCls[k] = (charCls[k] ? charCls[k] + " " : "") + "dsh-cl-ref";
729
+ break;
730
+ }
652
731
  }
653
- if (!text) { segStart = endExclusive; return; } // 整段全 \r:无可视字符,不输出空段
654
- const cls = charCls[segStart] + codeCls;
655
- const half = segLineH > s.h ? (segLineH - s.h) / 2 : 0;
656
- out += '<span class="dsh-cl-c' + (cls ? " " + cls : "") + '" style="left:' + (s.x - ox) + "px;top:" + (s.y - oy - half) + 'px">' + escapeHtml(text) + "</span>";
657
- segStart = endExclusive;
658
- };
659
- for (let i = 1; i <= chars.length; i++) {
660
- const cont = i < chars.length
661
- && charCls[i] === charCls[segStart]
662
- && Math.abs(chars[i].y - chars[segStart].y) < 2
663
- && (chars[i].x - (chars[i - 1].x + chars[i - 1].w)) < 1.5;
664
- if (!cont) flush(i);
665
732
  }
666
733
  }
667
- ov.innerHTML = out;
734
+ // 合并「同样式 + 同视觉行 + 横向连续」的字符成段(段内浏览器排版同字体零差)。
735
+ // 等宽整框语义:文档含代码块时全部段用等宽合成栈(与编辑器 MONO_ALL 同源变量)。
736
+ const codeCls = anyCode ? " dsh-cl-codefont" : "";
737
+ // 段定位必须用「行盒顶」而非「字形盒顶」:段内字符随段自身行盒排版,
738
+ // 字形顶 = 段top + half-leading((行高-字形高)/2)。段内其余字符的相对排布
739
+ // 与编辑器同构(同字体同行高同基线规则),首字符对齐即全段对齐。
740
+ const segLineH = parseFloat(segLineHeight) || 0;
741
+ const c0 = chars[0];
742
+ let out = "";
743
+ let segStart = 0;
744
+ const flush = (endExclusive) => {
745
+ const s = chars[segStart];
746
+ let text = "";
747
+ // 段 text 剔除 \r:CRLF 粘贴的行尾 \r 在段内(white-space:pre)会被当
748
+ // 真换行——段盒凭空多撑一行。编辑器把 \r 当换行语义的一部分(0 宽
749
+ // 不可见),渲染侧同样零宽处理=直接不画。
750
+ for (let k = segStart; k < endExclusive; k++) {
751
+ const ch = line.charAt(chars[k].off);
752
+ if (ch !== "\r") text += ch;
753
+ }
754
+ if (!text) { segStart = endExclusive; return; } // 整段全 \r:无可视字符,不输出空段
755
+ const cls = charCls[segStart] + codeCls;
756
+ const half = segLineH > s.h ? (segLineH - s.h) / 2 : 0;
757
+ out += '<span class="dsh-cl-c' + (cls ? " " + cls : "") + '" style="left:' + (s.x - c0.x) + "px;top:" + (s.y - c0.y - half) + 'px">' + escapeHtml(text) + "</span>";
758
+ segStart = endExclusive;
759
+ };
760
+ for (let i = 1; i <= chars.length; i++) {
761
+ const cont = i < chars.length
762
+ && charCls[i] === charCls[segStart]
763
+ && Math.abs(chars[i].y - chars[segStart].y) < 2
764
+ && (chars[i].x - (chars[i - 1].x + chars[i - 1].w)) < 1.5;
765
+ if (!cont) flush(i);
766
+ }
767
+ return out;
668
768
  }
669
769
  //#endregion
670
770
 
@@ -1084,7 +1184,9 @@ window.__ModuleLoader__.load({
1084
1184
  // ===== 字符锚定渲染(v0.2):定位字符段 + 背景块 =====
1085
1185
  // 字符段:绝对定位画在编辑器字符 rect 上;字体继承 overlay(syncMetrics
1086
1186
  // 复制官方度量);样式类只改 paint(伪粗/染色/胶囊背景外扩),零 advance 变化。
1087
- ".dsh-cl-c{position:absolute;white-space:pre;pointer-events:none;color:inherit;font-family:inherit;}" +
1187
+ ".dsh-cl-row{position:absolute;margin:0;}" +
1188
+ ".dsh-cl-bglayer{margin:0;}" +
1189
+ ".dsh-cl-c{position:absolute;white-space:pre;pointer-events:none;color:inherit;font-family:inherit;}" +
1088
1190
  // 官方文本引用装饰(/ 命令、技能名):渲染层用同一主题引用色。
1089
1191
  // 编辑器层文字已透明,官方给装饰 span 的 color 看不见(此前显示为
1090
1192
  // 普通正文色);hover 背景同样在编辑器层(z-index:1,画在 overlay
@@ -1361,7 +1463,18 @@ window.__ModuleLoader__.load({
1361
1463
  const METRIC_KEYS = ["fontFamily", "fontSize", "fontWeight", "lineHeight", "letterSpacing",
1362
1464
  "tabSize", "whiteSpace", "wordBreak", "overflowWrap", "wordWrap",
1363
1465
  "boxSizing", "textAlign", "textIndent"];
1364
- function syncMetrics(input, ov) {
1466
+ /** 轻段主题度量(v0.4.0):input 文字色(transparent 沿父链取一档)+ padding。
1467
+ * 每键必读(两者都进渲染签名),单次 getComputedStyle 两个属性。 */
1468
+ function readThemeMetrics(input) {
1469
+ const cs = getComputedStyle(input);
1470
+ let color = cs.color;
1471
+ if (!color || color === "transparent" || color === "rgba(0, 0, 0, 0)") {
1472
+ color = getComputedStyle(input.parentElement).color;
1473
+ }
1474
+ return { color, padding: cs.padding };
1475
+ }
1476
+
1477
+ function syncMetrics(input, ov) {
1365
1478
  const cs = getComputedStyle(input);
1366
1479
  const fp = input.querySelector(":scope > p");
1367
1480
  const fc = fp ? getComputedStyle(fp) : cs;
@@ -1397,7 +1510,7 @@ window.__ModuleLoader__.load({
1397
1510
  if (!editable) {
1398
1511
  ov.innerHTML = "";
1399
1512
  card.__dshClRenderSig = "";
1400
- card.__dshClLineCache = null;
1513
+ card.__dshClRowCache = null;
1401
1514
  return;
1402
1515
  }
1403
1516
  const anchors = buildAnchors(input);
@@ -1412,9 +1525,29 @@ window.__ModuleLoader__.load({
1412
1525
  const states = computeBlockStates(lines);
1413
1526
  const editSet = computeEditLines(lines, caret, caretF, document.activeElement === input);
1414
1527
 
1415
- // 合成字体栈(拉丁=代码等宽,中文=界面栈)写入 card 变量
1528
+ // 度量与主题(v0.2.17 上移到短路点之前:主题色是签名的组成部分)。
1529
+ // v0.4.0 拆轻重段:轻段每键只读 color+padding(进签名),重段(度量全量
1530
+ // 复制到 ov 的 syncMetrics)挪到签名 miss 之后——签名命中路径(空闲轮询/
1531
+ // 同行光标移动/selectionchange 噪音)从 2-3 次 getComputedStyle×6 属性降
1532
+ // 为 1 次×2 属性。padding 必须进签名:input 内距变化要能击穿签名让重段
1533
+ // 跑(原实现靠每键跑 syncMetrics 的守卫捕捉,拆开后由签名承担)。
1534
+ const scrollEl0 = card.querySelector(SCROLL_SEL);
1535
+ const themeMetrics = readThemeMetrics(input);
1536
+ const color0 = themeMetrics.color;
1537
+ if (scrollEl0) {
1538
+ scrollEl0.classList.toggle("dsh-cl-light", isLightColor(color0));
1539
+ document.body.classList.toggle("dsh-cl-light", isLightColor(color0));
1540
+ }
1541
+
1542
+ // v0.4.0 慢通道:字体栈合成 + 卡底实测只随「主题/字体设置/换肤」变(分钟
1543
+ // 级频率),共用 slowKey(color0 变化即时失效 + 2s 时间桶兜底不改文字色的
1544
+ // 换肤场景)——key 未变直接用上轮结果,把每键 3-6 次祖先链/哨兵
1545
+ // getComputedStyle 从打字路径移除。--dsh-cl-card-bg 写在 body 级:工具栏
1546
+ // 在卡外(v0.2.14),沿 DOM 继承全可达。
1547
+ const slowKey = color0 + "|" + Math.floor(Date.now() / 2000);
1416
1548
  const sentinel = card.__dshClSentinel;
1417
- if (sentinel && sentinel.isConnected) {
1549
+ if (sentinel && sentinel.isConnected && card.__dshClFontKey !== slowKey) {
1550
+ card.__dshClFontKey = slowKey;
1418
1551
  const sc = getComputedStyle(sentinel);
1419
1552
  const merged = buildCodeFont(sc.getPropertyValue("--ds-font-family-code"), sc.fontFamily);
1420
1553
  if (card.__dshClFontSig !== merged) {
@@ -1422,22 +1555,13 @@ window.__ModuleLoader__.load({
1422
1555
  card.style.setProperty("--dsh-cl-code-font", merged);
1423
1556
  }
1424
1557
  }
1425
-
1426
- // 度量与主题(v0.2.17 上移到短路点之前:主题色是签名的组成部分)
1427
- const scrollEl0 = card.querySelector(SCROLL_SEL);
1428
- const color0 = syncMetrics(input, ov);
1429
- if (scrollEl0) {
1430
- scrollEl0.classList.toggle("dsh-cl-light", isLightColor(color0));
1431
- document.body.classList.toggle("dsh-cl-light", isLightColor(color0));
1432
- }
1433
-
1434
- // v0.3.1 卡底实测 → --dsh-cl-card-bg(代码块/语言标签/胶囊底 color-mix
1435
- // 派生的基准)。卡底只随主题/换肤变,签名守卫避免每键重写 body style;
1436
- // 写在 body 级:工具栏在卡外(v0.2.14),沿 DOM 继承全可达。
1437
- const cardBg = effectiveCardBg(card);
1438
- if (document.body.__dshClCardBg !== cardBg) {
1439
- document.body.__dshClCardBg = cardBg;
1440
- document.body.style.setProperty("--dsh-cl-card-bg", cardBg);
1558
+ if (card.__dshClBgKey !== slowKey) {
1559
+ card.__dshClBgKey = slowKey;
1560
+ const cardBg = effectiveCardBg(card);
1561
+ if (document.body.__dshClCardBg !== cardBg) {
1562
+ document.body.__dshClCardBg = cardBg;
1563
+ document.body.style.setProperty("--dsh-cl-card-bg", cardBg);
1564
+ }
1441
1565
  }
1442
1566
 
1443
1567
  // ===== 渲染签名短路(v0.2.17 性能优化的核心) =====
@@ -1452,16 +1576,20 @@ window.__ModuleLoader__.load({
1452
1576
  // editSig:选区行集合的指纹(焦点行切换/拖选跨行/焦点进出都要重渲染——
1453
1577
  // cursorLine 只覆盖「光标所在行变化」,选区另一端变化与焦点态变化由它捕捉)
1454
1578
  const editSig = editSet ? "e" + Array.from(editSet).join(",") : "r";
1455
- const renderSig = [src, cursorLine, editSig, Math.round(irx.left - orx.left), Math.round(irx.top - orx.top), Math.round(irx.width), card.__dshClFontSig || "", color0].join("\u0000");
1579
+ const renderSig = [src, cursorLine, editSig, Math.round(irx.left - orx.left), Math.round(irx.top - orx.top), Math.round(irx.width), card.__dshClFontSig || "", color0, themeMetrics.padding].join("\u0000");
1456
1580
  if (card.__dshClRenderSig === renderSig) {
1457
1581
  updateToolbarMarks(card, src, caret);
1458
1582
  card.__dshClCaret = caret;
1459
1583
  return;
1460
1584
  }
1461
1585
  card.__dshClRenderSig = renderSig;
1462
- if (!card.__dshClLineCache) card.__dshClLineCache = { gen: "", lines: new Map() };
1463
- // 行测量缓存的布局代:字体/容器几何/主题任一变化 → 行缓存整体作废
1464
- const layoutGen = [card.__dshClFontSig || "", Math.round(irx.width), Math.round(irx.left - orx.left), color0].join("|");
1586
+ syncMetrics(input, ov); // v0.4.0 重段:度量全量复制到 ov(签名 miss 时才需要;内部自有守卫)
1587
+ if (!card.__dshClRowCache) card.__dshClRowCache = { gen: "", prevLines: [], entries: [], rowEls: [] };
1588
+ // 行缓存的布局代:字体/容器几何/主题/等宽整框任一变化 → 行缓存整体作废。
1589
+ // hasCode(MONO_ALL 整框等宽)必须进代:等宽切换改全部行字体但 fontSig
1590
+ // (哨兵合成栈)不感知——漏了会让 firstDiff 短路用旧测量画错坐标。
1591
+ const hasCode = states.some((st) => st.inCode);
1592
+ const layoutGen = [card.__dshClFontSig || "", Math.round(irx.width), Math.round(irx.left - orx.left), color0, hasCode ? "M" : ""].join("|");
1465
1593
 
1466
1594
  // 编辑器 class(打点在测量前——等宽打点影响布局,先定型再测量):
1467
1595
  // - KEEP(chip 段恢复)段落级
@@ -1475,8 +1603,7 @@ window.__ModuleLoader__.load({
1475
1603
  for (const p of ps) {
1476
1604
  p.classList.toggle(KEEP, hasChip);
1477
1605
  }
1478
- const hasCode = states.some((st) => st.inCode);
1479
- input.classList.toggle(MONO_ALL, hasCode);
1606
+ input.classList.toggle(MONO_ALL, hasCode); // hasCode 已在 layoutGen 处算过
1480
1607
 
1481
1608
  // 度量与主题段已于签名短路点之前执行(color 是签名组成部分)
1482
1609
 
@@ -1501,7 +1628,7 @@ window.__ModuleLoader__.load({
1501
1628
  fallbackToOfficial();
1502
1629
  } else {
1503
1630
  try {
1504
- renderCharOverlay(ov, input, anchors, lines, states, anchors.refs || [], card.__dshClLineCache, layoutGen, editSet);
1631
+ renderCharOverlay(ov, input, anchors, lines, states, anchors.refs || [], card.__dshClRowCache, layoutGen, editSet);
1505
1632
  if (hasContent && ov.querySelectorAll(".dsh-cl-c").length === 0) fallbackToOfficial();
1506
1633
  } catch (err) {
1507
1634
  fallbackToOfficial();
@@ -1912,6 +2039,10 @@ window.__ModuleLoader__.load({
1912
2039
  const phase = input2.getAttribute("data-phase");
1913
2040
  if (phase && phase !== "plain") return;
1914
2041
  if (menuOpen(card)) return; // 候选菜单开着 → 全归官方
2042
+ // v0.4.0 白名单早退:decideKeyAction 只关心 Enter/Tab/ArrowDown(Ctrl/Cmd
2043
+ // 组合的 B/I/E 分支在后面单独判),其余键——普通打字占绝对多数——不需要
2044
+ // buildAnchors+anchorsText+domOffsetOf 的 O(文档) 前置,直接放行官方。
2045
+ if (!e.ctrlKey && !e.metaKey && !e.altKey && KEY_ACTS.indexOf(e.key) === -1) return;
1915
2046
  const anchors = buildAnchors(input2);
1916
2047
  const src = anchorsText(anchors);
1917
2048
  const caret = domOffsetOf(input2, anchors, true);
@@ -2088,7 +2219,9 @@ window.__ModuleLoader__.load({
2088
2219
  anchorKinds: anchors.reduce((m, a) => { m[a.kind] = (m[a.kind] || 0) + 1; return m; }, {}),
2089
2220
  segs,
2090
2221
  host: input.classList.contains(HOST),
2091
- editable: input.getAttribute("contenteditable") === "true"
2222
+ editable: input.getAttribute("contenteditable") === "true",
2223
+ rows: card.__dshClRowCache ? card.__dshClRowCache.rowEls.length : 0, // 行容器数(应与 lineCount 一致)
2224
+ rowEntries: card.__dshClRowCache ? card.__dshClRowCache.entries.length : 0
2092
2225
  };
2093
2226
  };
2094
2227
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-composer-live",
3
- "version": "0.3.1",
3
+ "version": "0.4.0",
4
4
  "description": "Type Markdown, see it rendered live — Open-WebUI-style composer for DeepSeek Harness (DSH) web. Syntax-highlighted code blocks, task lists, format toolbars, smart paste. Pure browser-side, zero dependencies.",
5
5
  "icon": "./assets/icon-180.png",
6
6
  "type": "module",