@x-cmd/draw 0.5.3 → 0.5.5

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.
@@ -1,3 +1,10 @@
1
+ /** 一个矩形(标注避让用) */
2
+ export interface Box {
3
+ x: number;
4
+ y: number;
5
+ w: number;
6
+ h: number;
7
+ }
1
8
  export interface Anno {
2
9
  kind: 'oval' | 'text' | 'hl' | 'note' | 'arrow' | 'path';
3
10
  /** 椭圆:中心;文字:标签中心;高亮:左上角;评论:引线的落点;箭头:起点;折线:第一点(都是百分比) */
@@ -71,6 +78,7 @@ export declare function annoLayer(annos: Anno[], frame: {
71
78
  h: number;
72
79
  }, k?: number, opts?: {
73
80
  uniform?: boolean;
81
+ avoid?: Box[];
74
82
  }): string;
75
83
  /**
76
84
  * 图里的**绘图区**(数据区)✓ —— 标注的百分比要按它换算,不是按整个画布 ✓
@@ -93,4 +101,14 @@ export declare function plotAreaOf(svg: string): {
93
101
  * 把标注层塞进一张已经画好的 SVG(盖在最后面 = 最上面)。
94
102
  * 坐标按**绘图区**换算 —— 画布尺寸变了,百分比的位置不变 ✓。
95
103
  */
104
+ /**
105
+ * 图里已有的**文字块** —— 标注要躲开它们。
106
+ *
107
+ * 为什么:标注(评论气泡)是自己挑位置的 ⇒ 可能正好落在某个标签上
108
+ * (架构图那个「auth」副标题、导图那个「Agents」)⇒ 读者两样都读不到。
109
+ *
110
+ * 做法:把图里的 `<text>` 扫一遍,按字号与锚点推出每段字的盒子。
111
+ * 组上的 translate 也要算进去(有些渲染器把东西放在平移过的组里)。
112
+ */
113
+ export declare function textBoxesOf(svg: string): Box[];
96
114
  export declare function injectAnnos(svg: string, annos: Anno[] | undefined): string;
@@ -610,13 +610,40 @@ export function annoLayer(annos, frame, k = 1, opts) {
610
610
  by = frame.y + (a.ty / 100) * frame.h;
611
611
  }
612
612
  else {
613
- // 缺省:框放在引线的哪一侧 —— 先试右边,再试左边;上面放不下就放下面
614
- bx = ax + gap;
615
- if (bx + bw > frame.x + frame.w)
616
- bx = ax - gap - bw;
617
- by = ay - gap - bh;
618
- if (by < frame.y)
619
- by = ay + gap;
613
+ // 缺省:框自己挑位置 —— **躲开图里的字**(标注压住字 = 读者读不到)。
614
+ // 候选位置:引线四周的一圈(右/左/上/下 × 几档远近)⇒ 挑压字最少、离锚点最近的那个。
615
+ const xs = [ax + gap, ax + gap * 2.5, ax + gap * 4, ax - bw / 2, ax - gap - bw, ax - gap * 2.5 - bw, ax - gap * 4 - bw];
616
+ const ys = [ay - gap - bh, ay - bh / 2, ay + gap, ay + gap + bh / 2];
617
+ const hits = (x, y) => {
618
+ let n = 0;
619
+ for (const b of opts?.avoid ?? []) {
620
+ if (x < b.x + b.w && x + bw > b.x && y < b.y + b.h && y + bh > b.y)
621
+ n++;
622
+ }
623
+ // 框不能盖住**锚点** —— 锚点就是「指着哪儿」的那个记号,盖住了等于没说
624
+ if (x < ax + 8 && x + bw > ax - 8 && y < ay + 8 && y + bh > ay - 8)
625
+ n += 3;
626
+ return n;
627
+ };
628
+ let best = [xs[0], ys[0]];
629
+ let bestScore = Infinity;
630
+ let bestDist = Infinity;
631
+ for (const cy0 of ys) {
632
+ for (const cx0 of xs) {
633
+ const x0 = Math.min(Math.max(cx0, frame.x), Math.max(frame.x, frame.x + frame.w - bw));
634
+ const y0 = Math.min(Math.max(cy0, frame.y), Math.max(frame.y, frame.y + frame.h - bh));
635
+ const score = hits(x0, y0);
636
+ const dist = Math.hypot(x0 + bw / 2 - ax, y0 + bh / 2 - ay);
637
+ // 压字少的优先;一样多 ⇒ 离锚点近的优先(引线短 ⇒ 好读)
638
+ if (score < bestScore || (score === bestScore && dist < bestDist)) {
639
+ bestScore = score;
640
+ bestDist = dist;
641
+ best = [x0, y0];
642
+ }
643
+ }
644
+ }
645
+ bx = best[0];
646
+ by = best[1];
620
647
  }
621
648
  // 夹回画布(太小放不下时宁可压边,也不能跑出去)
622
649
  bx = Math.min(Math.max(bx, frame.x), Math.max(frame.x, frame.x + frame.w - bw));
@@ -696,6 +723,50 @@ export function plotAreaOf(svg) {
696
723
  * 把标注层塞进一张已经画好的 SVG(盖在最后面 = 最上面)。
697
724
  * 坐标按**绘图区**换算 —— 画布尺寸变了,百分比的位置不变 ✓。
698
725
  */
726
+ /**
727
+ * 图里已有的**文字块** —— 标注要躲开它们。
728
+ *
729
+ * 为什么:标注(评论气泡)是自己挑位置的 ⇒ 可能正好落在某个标签上
730
+ * (架构图那个「auth」副标题、导图那个「Agents」)⇒ 读者两样都读不到。
731
+ *
732
+ * 做法:把图里的 `<text>` 扫一遍,按字号与锚点推出每段字的盒子。
733
+ * 组上的 translate 也要算进去(有些渲染器把东西放在平移过的组里)。
734
+ */
735
+ export function textBoxesOf(svg) {
736
+ const out = [];
737
+ const stack = [[0, 0]];
738
+ const tagRe = /<g\b([^>]*?)\/>|<g\b([^>]*?)>|<\/g>|<text\b([^>]*?)>([\s\S]*?)<\/text>/g;
739
+ for (let m = tagRe.exec(svg); m; m = tagRe.exec(svg)) {
740
+ if (m[1] !== undefined)
741
+ continue; // 自闭合的 <g/>
742
+ if (m[2] !== undefined) {
743
+ const tr = /translate\((-?[\d.]+)[ ,]+(-?[\d.]+)\)/.exec(m[2]);
744
+ const [ox, oy] = stack[stack.length - 1];
745
+ stack.push(tr ? [ox + Number(tr[1]), oy + Number(tr[2])] : [ox, oy]);
746
+ continue;
747
+ }
748
+ if (m[0].startsWith('</g')) {
749
+ if (stack.length > 1)
750
+ stack.pop();
751
+ continue;
752
+ }
753
+ const attrs = m[3] ?? '';
754
+ const content = (m[4] ?? '').replace(/<[^>]*>/g, '').trim();
755
+ if (!content)
756
+ continue;
757
+ const x = Number(/\bx="(-?[\d.]+)"/.exec(attrs)?.[1] ?? NaN);
758
+ const y = Number(/\by="(-?[\d.]+)"/.exec(attrs)?.[1] ?? NaN);
759
+ if (!Number.isFinite(x) || !Number.isFinite(y))
760
+ continue;
761
+ const fs = Number(/font-size="([\d.]+)"/.exec(attrs)?.[1] ?? 13);
762
+ const anchor = /text-anchor="(\w+)"/.exec(attrs)?.[1] ?? 'start';
763
+ const tw = textWidth(content, fs);
764
+ const [ox, oy] = stack[stack.length - 1];
765
+ const x0 = anchor === 'end' ? x - tw : anchor === 'middle' ? x - tw / 2 : x;
766
+ out.push({ x: x0 + ox, y: y + oy - fs * 0.8, w: tw, h: fs * 1.05 });
767
+ }
768
+ return out;
769
+ }
699
770
  export function injectAnnos(svg, annos) {
700
771
  if (!annos?.length)
701
772
  return svg;
@@ -735,7 +806,7 @@ export function injectAnnos(svg, annos) {
735
806
  const plot = plotAreaOf(svg);
736
807
  // 图有值映射 ⇒ 标注的 y 是**数据值** ⇒ 先换算成绘图区的百分比 ✓
737
808
  const d = dscaleOf(svg);
738
- const layer = annoLayer(d ? annoValuesToPct(annos, d) : annos, plot ?? { x: x0, y: y0, w: vw, h: vh }, k, { uniform: !d });
809
+ const layer = annoLayer(d ? annoValuesToPct(annos, d) : annos, plot ?? { x: x0, y: y0, w: vw, h: vh }, k, { uniform: !d, avoid: textBoxesOf(svg) });
739
810
  const at = svg.lastIndexOf('</svg>');
740
811
  if (at < 0)
741
812
  return svg;
@@ -1,6 +1,6 @@
1
1
  import { dayIso, daysInMonth, firstWeekday, isoDay, isoParts, isoWeekday } from '../specs/calendar.js';
2
2
  import { TAB, card } from '../theme.js';
3
- import { esc, r2, svgDoc, textW, titleBlock, topLegend, trunc } from './svg.js';
3
+ import { esc, r2, svgDoc, TAG_RESERVE, textW, titleBlock, topLegend, trunc } from './svg.js';
4
4
  import { footerUnit, headerMeta, tipHeight, tipUnit } from './units.js';
5
5
  const PAD = 24;
6
6
  const HEAD_FS = 12;
@@ -48,12 +48,17 @@ function fitText(s, maxW, fs) {
48
48
  t = t.slice(0, -1);
49
49
  return `<title>${esc(s)}</title>${esc(t)}…`;
50
50
  }
51
- /** 按像素宽度折行(最多 maxLines 行)—— 挤的格子里文字不能串到隔壁格,也不能截掉一半 */
51
+ /**
52
+ * 按像素宽度折行(最多 maxLines 行)—— 挤的格子里文字不能串到隔壁格,也不能截掉一半。
53
+ *
54
+ * 返回的是**可以直接塞进 SVG 的片段**(已转义;放不下的那一行带 `<title>`)——
55
+ * 调用方不要再转义一次,不然 `<title>` 会变成字面量。
56
+ */
52
57
  function wrapLines(s, maxW, fs, maxLines = 2) {
53
58
  if (!s)
54
59
  return [''];
55
60
  if (textW(s, fs) <= maxW)
56
- return [s];
61
+ return [esc(s)];
57
62
  const words = s.split(/\s+/).filter(Boolean);
58
63
  const lines = [];
59
64
  let line = '';
@@ -71,7 +76,7 @@ function wrapLines(s, maxW, fs, maxLines = 2) {
71
76
  if (line && lines.length < maxLines)
72
77
  lines.push(line);
73
78
  // 还是太长 ⇒ 最后一行再截(但带上 title,悬停能看全)
74
- return lines.map((l) => (textW(l, fs) > maxW ? fitText(l, maxW, fs) : l));
79
+ return lines.map((l) => (textW(l, fs) > maxW ? fitText(l, maxW, fs) : esc(l)));
75
80
  }
76
81
  /** 某一天是休息日吗(默认:周末) */
77
82
  function isRest(ctx, date) {
@@ -155,9 +160,10 @@ function monthGrid(ctx, y, m, x, y0, w, h, dense = false, headY) {
155
160
  }
156
161
  const fill = today ? '#ffffff' : holiday ? 'var(--d-mark)' : rest ? 'var(--d-muted)' : 'var(--d-ink)';
157
162
  parts.push(`<text x="${r2(nx)}" y="${r2(ny)}" text-anchor="end" font-size="${NUM_FS}" font-weight="${today || holiday ? 600 : 400}" fill="${fill}" style="${TAB}">${dayNum}</text>`);
158
- // 假日的名字
163
+ // 假日的名字(密集的格子放不下 ⇒ 不写:半截名字比没有更糟,
164
+ // 假日在**日期号**上已经是红的,名字在下面的备注里)
159
165
  const dl = ctx.dayOf(iso)?.label;
160
- if (dl) {
166
+ if (dl && !dense) {
161
167
  const dfill = holiday ? 'var(--d-mark)' : 'var(--d-text)';
162
168
  parts.push(`<text x="${r2(cx + 6)}" y="${r2(cy + 16)}" font-size="${EV_FS}" fill="${dfill}">${fitText(dl, cw - 30, EV_FS)}</text>`);
163
169
  }
@@ -182,7 +188,7 @@ function monthGrid(ctx, y, m, x, y0, w, h, dense = false, headY) {
182
188
  parts.push(`<circle cx="${r2(cx + 9)}" cy="${r2(ey - 4)}" r="3" fill="${ctx.colorOf(it.kind)}"/>`);
183
189
  // 月历不写时间(苹果的月视图也不写)—— 格子窄,时间会把名字挤没
184
190
  lines.forEach((ln, li) => {
185
- parts.push(`<text x="${r2(cx + 16)}" y="${r2(ey + li * 13)}" font-size="${EV_FS}" fill="var(--d-text)">${esc(ln)}</text>`);
191
+ parts.push(`<text x="${r2(cx + 16)}" y="${r2(ey + li * 13)}" font-size="${EV_FS}" fill="var(--d-text)">${ln}</text>`);
186
192
  });
187
193
  ey += lines.length * 13 + 2;
188
194
  }
@@ -262,7 +268,13 @@ function timeGrid(ctx, days, periods, x, y0, w, h, dense = false) {
262
268
  const by = y0 + r * ch + 3;
263
269
  const bw = cw - 6;
264
270
  const bh = Math.max(16, ch - 6);
265
- parts.push(`<rect x="${r2(bx)}" y="${r2(by)}" width="${r2(bw)}" height="${r2(bh)}" rx="6" fill="${ctx.colorOf(it.kind)}" fill-opacity="0.14"/>`, `<rect x="${r2(bx)}" y="${r2(by)}" width="3" height="${r2(bh)}" rx="1.5" fill="${ctx.colorOf(it.kind)}"/>`, `<text x="${r2(bx + 8)}" y="${r2(by + 14)}" font-size="11" fill="var(--d-ink)">${esc(trunc(it.label, 14))}</text>`);
271
+ parts.push(`<rect x="${r2(bx)}" y="${r2(by)}" width="${r2(bw)}" height="${r2(bh)}" rx="6" fill="${ctx.colorOf(it.kind)}" fill-opacity="0.14"/>`, `<rect x="${r2(bx)}" y="${r2(by)}" width="3" height="${r2(bh)}" rx="1.5" fill="${ctx.colorOf(it.kind)}"/>`);
272
+ // 名字**折行**而不是截断(截一半等于给错信息):格子放得下几行就折几行
273
+ const room = bw - 14;
274
+ const maxLines = Math.max(1, Math.min(2, Math.floor((bh - 8) / 13)));
275
+ wrapLines(it.label, room, EV_FS, maxLines).forEach((ln, li) => {
276
+ parts.push(`<text x="${r2(bx + 8)}" y="${r2(by + 14 + li * 13)}" font-size="${EV_FS}" fill="var(--d-ink)">${ln}</text>`);
277
+ });
266
278
  }
267
279
  }
268
280
  return parts.join('');
@@ -288,7 +300,12 @@ function planBoard(ctx, start, days, x, y0, w, rowH) {
288
300
  rows.forEach((it, r) => {
289
301
  const ry = y0 + r * rowH;
290
302
  parts.push(`<line x1="${r2(x)}" y1="${r2(ry)}" x2="${r2(x + w)}" y2="${r2(ry)}" stroke="var(--d-grid)" stroke-width="1"/>`);
291
- parts.push(`<text x="${r2(x + 4)}" y="${r2(ry + rowH / 2 + 4)}" font-size="13" fill="var(--d-ink)">${esc(trunc(it.label, 20))}</text>`);
303
+ // 名字折行(行高够就折两行;截一半等于给错信息)
304
+ const lines = wrapLines(it.label, labelW - 10, 13, Math.max(1, Math.min(2, Math.floor(rowH / 16))));
305
+ const ty = ry + rowH / 2 - (lines.length - 1) * 7 + 4;
306
+ lines.forEach((ln, li) => {
307
+ parts.push(`<text x="${r2(x + 4)}" y="${r2(ty + li * 15)}" font-size="13" fill="var(--d-ink)">${ln}</text>`);
308
+ });
292
309
  const s = isoDay(it.date);
293
310
  const e = isoDay(it.until ?? it.date);
294
311
  const bx = x + labelW + (s - d0) * per;
@@ -430,8 +447,8 @@ export function renderCalendar(spec, o) {
430
447
  const nDays = spec.days.length;
431
448
  const nNotes = spec.notes.length;
432
449
  const meta = [nItems ? `${nItems} 个日程` : '', nNotes ? `${nNotes} 条备注` : ''].filter(Boolean).join(' · ');
433
- // 右边让开 Edit @X-CMD 角标(它占右上角那一块,最多 ~100px)
434
- const badgeRoom = Math.min(108, bodyW * 0.32);
450
+ // 右边让开 Edit @X-CMD 角标(它占右上角那一块 —— 标题 18px 时角标有 139px 宽)
451
+ const badgeRoom = Math.min(TAG_RESERVE, bodyW * 0.45);
435
452
  const titleSvg = titleBlock(title) + headerMeta(meta, PAD, 38, bodyW - badgeRoom);
436
453
  // 图例:出现过的类别(坐底部一行 —— 类别多的时候放标题那行会压住标题)
437
454
  const legendSvg = legendItems.length
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@x-cmd/draw",
3
- "version": "0.5.3",
3
+ "version": "0.5.5",
4
4
  "description": "SVG chart rendering as a service, a library, and a CLI — pie/bar/hbar/line/area/radar/gauge/scatter/combo/sankey/qr, same params everywhere",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",