@x-cmd/draw 0.4.0 → 0.4.2

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/dist/lib.d.ts CHANGED
@@ -16,11 +16,14 @@ export { renderScatter } from './render/scatter.js';
16
16
  export { renderCombo } from './render/combo.js';
17
17
  export { renderQR } from './render/qr.js';
18
18
  export { parseAnnos, injectAnnos, annoLayer, type Anno } from './render/anno.js';
19
+ export { parseLadderSpec, ladderSpecFromParams, type LadderSpec, type LadderItem, type LadderSide } from './specs/ladder.js';
20
+ export { resolveSrcSpec } from './render/src-spec.js';
19
21
  export { footerUnit, headerMeta, tipUnit, tipHeight, type FooterItem, type TipRow } from './render/units.js';
20
22
  export { renderSankey } from './render/sankey.js';
21
23
  export { renderQuadrant } from './render/quadrant.js';
22
24
  export { renderCompass } from './render/compass.js';
23
25
  export { renderButterfly } from './render/butterfly.js';
26
+ export { renderLadder, renderButterflyLadder } from './render/ladder.js';
24
27
  export { renderCalendar } from './render/calendar.js';
25
28
  export { renderTable, tableToGrid, type TableGrid } from './render/table.js';
26
29
  export { parseTableSpec, tableSpecFromParams } from './specs/table.js';
package/dist/lib.js CHANGED
@@ -21,11 +21,14 @@ export { renderScatter } from './render/scatter.js';
21
21
  export { renderCombo } from './render/combo.js';
22
22
  export { renderQR } from './render/qr.js';
23
23
  export { parseAnnos, injectAnnos, annoLayer } from './render/anno.js';
24
+ export { parseLadderSpec, ladderSpecFromParams } from './specs/ladder.js';
25
+ export { resolveSrcSpec } from './render/src-spec.js';
24
26
  export { footerUnit, headerMeta, tipUnit, tipHeight } from './render/units.js';
25
27
  export { renderSankey } from './render/sankey.js';
26
28
  export { renderQuadrant } from './render/quadrant.js';
27
29
  export { renderCompass } from './render/compass.js';
28
30
  export { renderButterfly } from './render/butterfly.js';
31
+ export { renderLadder, renderButterflyLadder } from './render/ladder.js';
29
32
  export { renderCalendar } from './render/calendar.js';
30
33
  export { renderTable, tableToGrid } from './render/table.js';
31
34
  export { parseTableSpec, tableSpecFromParams } from './specs/table.js';
@@ -0,0 +1,8 @@
1
+ import type { DrawResult } from './query.js';
2
+ export declare const BANNER_FACE_CSS: string;
3
+ /**
4
+ * GET /draw/x-cmd/release-banner?title=<slogan[|slogan2]>&version=<x.y.z>&cmd=<cmd>[&paper=<yellow|orange|pink|purple|green|cyan|blue|gray|apple>]
5
+ * x-cmd 命名空间的发布封面(1200×630);位图加 &format=png(og:image 尺寸,scale=2 为 retina)。
6
+ * @throws ApiError(400) with a corrective example on bad input
7
+ */
8
+ export declare function renderReleaseBannerFromUrl(url: URL): DrawResult;
@@ -0,0 +1,204 @@
1
+ // /draw/banner 主题化 OG 封面:复刻 codeberg x-cmd/img 的 satori 版发布封面为
2
+ // draw 手写 SVG 路线。v2 按 render.mjs JSX 逐项对照重写 —— 标题=release 功能口号
3
+ // (Inter Bold 72 #000),左下角 tag = "X-CMD - v<version>"(Inter Medium #4f514c),
4
+ // 终端 #181818 r18 只有三色点 + "❯ bin rest" 命令(FiraCode,#28c840/#4fb9f3/#f4f4f4,
5
+ // 白色块光标),纸底 = 对角 #fff→#F0EDD8 暖黄渐变 + 点阵颗粒(滤镜会撞免费档 CPU,
6
+ // 见 git 史:feTurbulence/feDropShadow 在 3MP 光栅化实测 1102)。
7
+ import { ApiError, clip } from '../specs/index.js';
8
+ import { resolveVersion } from '../version.js';
9
+ import { esc, textW } from './svg.js';
10
+ import { FONT, TAB } from '../theme.js';
11
+ import { INTER_FACE_CSS } from '../styles/inter.js';
12
+ import { FONT_FILES_B64 } from '../styles/fonts-banner.js';
13
+ const W = 1200;
14
+ const H = 630;
15
+ // ── cli-release-v1 视觉锁(全部数值对照 render.mjs 常量) ─────────────────────
16
+ const TITLE = { size: 72, left: 64, inkTop: 83, lh: 1.1, ls: -1.4, cap: 52 }; // cap≈0.727em
17
+ const TAG = { size: 34, bottom: 75 }; // 左下 "X-CMD - vX.Y.Z"
18
+ const TERM = { x: 553, y: 328, w: 720, h: 400, r: 18, pad: 24, dot: 17, dotGap: 10, barH: 18, mb: 52 };
19
+ const CMD = { size: 34 }; // FiraCode 0.6em 等宽 advance
20
+ const CURSOR = { w: 24, h: 47 };
21
+ // 纸底色板:?paper=<name>。前 8 色为 paper-bg.mjs 的 TINTS(锁定色,勿调);
22
+ // apple = 苹果白(#fff→#F5F5F7,中性灰颗粒)。yellow 为缺省。
23
+ const PAPERS = {
24
+ yellow: { tint: '#f0edd8', grain: '#6b5d3f' },
25
+ orange: { tint: '#f6eee7', grain: '#6b5d3f' },
26
+ pink: { tint: '#f6e7ec', grain: '#6b5d3f' },
27
+ purple: { tint: '#f1e7f6', grain: '#6b5d3f' },
28
+ green: { tint: '#daefe0', grain: '#6b5d3f' },
29
+ cyan: { tint: '#e7f6f2', grain: '#6b5d3f' },
30
+ blue: { tint: '#dbecfa', grain: '#6b5d3f' },
31
+ gray: { tint: '#e2e6e6', grain: '#6b5d3f' },
32
+ apple: { tint: '#f5f5f7', grain: '#7a7a7a' },
33
+ };
34
+ const INK = '#000000';
35
+ const TAG_C = '#4f514c';
36
+ const TERM_BG = '#181818';
37
+ const C_GREEN = '#28c840';
38
+ const C_BLUE = '#4fb9f3';
39
+ const C_FG = '#f4f4f4';
40
+ // banner 字体的 @font-face(浏览器端);resvg 端走 png.ts 的 fontBuffers
41
+ // (onepage 标题同用这套品牌字重,导出共用)
42
+ export const BANNER_FACE_CSS = FONT_FILES_B64
43
+ .map((f) => `@font-face{font-family:'${f.family}';src:url(data:font/woff2;base64,${f.woff2}) format('woff2');font-weight:500 700}`)
44
+ .join('');
45
+ function seedOf(s) {
46
+ let h = 2166136261;
47
+ for (let i = 0; i < s.length; i++) {
48
+ h ^= s.charCodeAt(i);
49
+ h = Math.imul(h, 16777619);
50
+ }
51
+ return h >>> 0;
52
+ }
53
+ function rng(seed) {
54
+ let s = seed || 1;
55
+ return () => { s = (Math.imul(s, 1664525) + 1013904223) >>> 0; return s / 4294967296; };
56
+ }
57
+ // 标题:显式换行(\n 或 |)优先;单串则单行放不下再按词拆两行(最均衡断点)
58
+ function titleLines(title) {
59
+ const raw = title.trim();
60
+ if (raw === '')
61
+ throw new ApiError(400, '"title" is required, e.g. title=Validate files|against JSON Schema');
62
+ const maxW = W - TITLE.left - 24;
63
+ if (raw.includes('\n') || raw.includes('|')) {
64
+ const ls = raw.split(/\n|\|/).map((l) => l.trim()).filter(Boolean);
65
+ if (ls.length > 2)
66
+ throw new ApiError(400, 'title takes at most 2 lines');
67
+ for (const l of ls) {
68
+ if (textW(l, TITLE.size) > maxW)
69
+ throw new ApiError(400, `title line "${clip(l, 24)}" is too wide at 72px; shorten it`);
70
+ }
71
+ return ls;
72
+ }
73
+ const words = raw.split(/\s+/);
74
+ for (const w of words) {
75
+ if (textW(w, TITLE.size) > maxW)
76
+ throw new ApiError(400, `title word "${clip(w, 24)}" is too wide at 72px; shorten it`);
77
+ }
78
+ if (textW(raw, TITLE.size) <= maxW)
79
+ return [raw];
80
+ if (words.length === 1)
81
+ throw new ApiError(400, 'title is too long for one line at 72px; use fewer/shorter words');
82
+ let best;
83
+ let bestGap = Infinity;
84
+ for (let i = 1; i < words.length; i++) {
85
+ const l1 = words.slice(0, i).join(' ');
86
+ const l2 = words.slice(i).join(' ');
87
+ if (textW(l1, TITLE.size) > maxW || textW(l2, TITLE.size) > maxW)
88
+ continue;
89
+ const gap = Math.abs(textW(l1, TITLE.size) - textW(l2, TITLE.size));
90
+ if (gap < bestGap) {
91
+ bestGap = gap;
92
+ best = [l1, l2];
93
+ }
94
+ }
95
+ if (best === undefined)
96
+ throw new ApiError(400, 'title cannot be split into two lines that both fit at 72px; shorten it');
97
+ return best;
98
+ }
99
+ // 纸底:复刻 paper-bg.mjs 的渐变数学 —— t = clip(yy + lean*(xx-0.5)*yy),hold 区恒白,
100
+ // 再 γ0.82 下沉;lean ∈ ±{0,0.22,0.42} 由种子决定。SVG 侧用「倾斜线性渐变 + 按曲线
101
+ // 采样停靠点」等价表达(纯矢量零滤镜),叠加原有点阵颗粒。
102
+ function paper(seed, name) {
103
+ const p = PAPERS[name] ?? PAPERS.yellow;
104
+ const r = rng(seed);
105
+ const leans = [-0.42, -0.22, 0, 0.22, 0.42];
106
+ const lean = leans[Math.floor(r() * leans.length)];
107
+ const hold = 0.28 + Math.floor(r() * 3) * 0.02;
108
+ const T = 64;
109
+ let dots = '';
110
+ for (let i = 0; i < 12; i++) {
111
+ dots += `<circle cx="${(r() * T).toFixed(1)}" cy="${(r() * T).toFixed(1)}" r="0.7" fill="${p.grain}" fill-opacity="${(0.03 + r() * 0.07).toFixed(3)}"/>`;
112
+ }
113
+ // 停靠点:t 均匀采样 9 点,经 hold + γ0.82 映射后与所选纸色混色
114
+ const hex = (n) => n.toString(16).padStart(2, '0');
115
+ const tintRgb = [1, 3, 5].map((i) => parseInt(p.tint.slice(i, i + 2), 16));
116
+ const stops = [];
117
+ for (let i = 0; i <= 8; i++) {
118
+ const t = i / 8;
119
+ const tt = Math.pow(Math.min(1, Math.max(0, (t - hold) / (1 - hold))), 0.82);
120
+ const mix = (c) => Math.round(255 + (c - 255) * tt);
121
+ stops.push(`<stop offset="${t.toFixed(3)}" stop-color="#${tintRgb.map((c) => hex(mix(c))).join('')}"/>`);
122
+ }
123
+ return (`<linearGradient id="tint" x1="0" y1="0" x2="${lean.toFixed(2)}" y2="1">${stops.join('')}</linearGradient>` +
124
+ `<rect width="${W}" height="${H}" fill="url(#tint)"/>` +
125
+ `<pattern id="grain" width="${T}" height="${T}" patternUnits="userSpaceOnUse">${dots}</pattern>` +
126
+ `<rect width="${W}" height="${H}" fill="url(#grain)"/>`);
127
+ }
128
+ // 终端投影:参考 = BLUR56 左重 diffuse halo。矢量等价 = 椭圆径向渐变光晕
129
+ // (中心左移 90px + OFFSET_Y 8,向外透明衰减)——柔和无边线,零滤镜零位图。
130
+ function termShadow() {
131
+ const { x, y, w, h } = TERM;
132
+ const cx = Math.round(x + w / 2 - 50);
133
+ const cy = y + h / 2 + 8;
134
+ return (`<radialGradient id="halo" cx="0.5" cy="0.5" r="0.5"><stop offset="0" stop-color="#3a3325" stop-opacity="0.08"/><stop offset="0.5" stop-color="#3a3325" stop-opacity="0.045"/><stop offset="1" stop-color="#3a3325" stop-opacity="0"/></radialGradient>` +
135
+ `<ellipse cx="${cx}" cy="${cy}" rx="${Math.round(w * 0.72)}" ry="${Math.round(h * 0.68)}" fill="url(#halo)"/>`);
136
+ }
137
+ // 终端:#181818 圆角出血 + 三色点 + ❯ bin rest + 白块光标(FiraCode 真等宽 0.6em)
138
+ function terminal(cmd) {
139
+ const { x, y, w, h, r, pad, dot, dotGap, barH, mb } = TERM;
140
+ const innerX = x + pad;
141
+ const dotsY = y + pad + barH / 2;
142
+ const cmdTop = y + pad + barH + mb; // 命令行顶部
143
+ const cmdBase = Math.round(cmdTop + CURSOR.h / 2 + CMD.size * 0.36);
144
+ const parts = cmd.trim().split(/\s+/);
145
+ const bin = parts[0] ?? '';
146
+ const restStr = parts.slice(1).join(' ');
147
+ const em = 0.6 * CMD.size; // FiraCode 每字符 advance
148
+ const seq = `❯ ${bin}${restStr ? ` ${restStr}` : ''} `;
149
+ const cursorX = innerX + Math.round(seq.length * em);
150
+ return (termShadow() +
151
+ `<rect x="${x}" y="${y}" width="${w}" height="${h}" rx="${r}" fill="${TERM_BG}"/>` +
152
+ `<circle cx="${x + pad + dot / 2}" cy="${dotsY}" r="${dot / 2}" fill="#ff5f57"/>` +
153
+ `<circle cx="${x + pad + dot / 2 + dot + dotGap}" cy="${dotsY}" r="${dot / 2}" fill="#febc2e"/>` +
154
+ `<circle cx="${x + pad + dot / 2 + 2 * (dot + dotGap)}" cy="${dotsY}" r="${dot / 2}" fill="#28c840"/>` +
155
+ `<text x="${innerX}" y="${cmdBase}" font-family="DrawMono" font-size="${CMD.size}" fill="${C_FG}"><tspan fill="${C_GREEN}">❯</tspan> <tspan fill="${C_BLUE}">${esc(bin)}</tspan>${restStr ? ` <tspan>${esc(restStr)}</tspan>` : ''}</text>` +
156
+ `<rect x="${cursorX}" y="${cmdTop}" width="${CURSOR.w}" height="${CURSOR.h}" fill="${C_FG}"/>`);
157
+ }
158
+ function renderReleaseBanner(p, url) {
159
+ const v = resolveVersion(url.searchParams.get('v'));
160
+ const cmd = p.cmd.trim();
161
+ if (cmd.length === 0)
162
+ throw new ApiError(400, '"cmd" is required, e.g. cmd=x upgrade');
163
+ if (cmd.length > 28)
164
+ throw new ApiError(400, `"cmd" is ${cmd.length} chars; the terminal keeps at most 28`);
165
+ const ver = p.version.trim();
166
+ if (ver === '')
167
+ throw new ApiError(400, '"version" is required, e.g. version=0.10.13 (shown as X-CMD - vX.Y.Z)');
168
+ const version = ver.startsWith('v') ? ver : `v${ver}`;
169
+ const paperName = p.paper.trim().toLowerCase();
170
+ if (paperName !== '' && !(paperName in PAPERS)) {
171
+ throw new ApiError(400, `"paper" must be one of: ${Object.keys(PAPERS).join(', ')} (default yellow). Got: ${JSON.stringify(paperName)}`);
172
+ }
173
+ const lines = titleLines(p.title.replace(/%0A/gi, '\n'));
174
+ const seed = seedOf(`${lines.join(' ')}|${version}|${cmd}`);
175
+ const pName = paperName || 'yellow';
176
+ const parts = [paper(seed, pName), terminal(cmd)];
177
+ // 标题:Inter Bold 72 #000,ink 顶 83,行距 1.1(baseline = inkTop + cap + i*lh*size)
178
+ const base1 = TITLE.inkTop + TITLE.cap;
179
+ lines.forEach((l, i) => {
180
+ const y = Math.round(base1 + i * TITLE.lh * TITLE.size);
181
+ parts.push(`<text x="${TITLE.left}" y="${y}" font-family="DrawInterBold" font-size="${TITLE.size}" letter-spacing="${TITLE.ls}" fill="${INK}">${esc(l)}</text>`);
182
+ });
183
+ // 左下 tag: X-CMD - vX.Y.Z
184
+ const tagY = H - TAG.bottom;
185
+ parts.push(`<text x="${TITLE.left}" y="${tagY}" font-family="DrawInterMedium" font-size="${TAG.size}" letter-spacing="-0.1" fill="${TAG_C}" style="${TAB}">X-CMD - ${esc(version)}</text>`);
186
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}" font-family="${FONT}" role="img" aria-label="${esc(lines.join(' '))}">` +
187
+ `<style>${INTER_FACE_CSS}${BANNER_FACE_CSS}</style>` +
188
+ `<metadata>${esc(JSON.stringify({ generator: 'draw', template: 'release-banner', namespace: 'x-cmd', version: v.version, title: lines.join('\n'), release: version, cmd, paper: pName }))}</metadata>` +
189
+ parts.join('') + `</svg>`;
190
+ return { svg, version: v.version, cacheControl: v.cacheControl };
191
+ }
192
+ /**
193
+ * GET /draw/x-cmd/release-banner?title=<slogan[|slogan2]>&version=<x.y.z>&cmd=<cmd>[&paper=<yellow|orange|pink|purple|green|cyan|blue|gray|apple>]
194
+ * x-cmd 命名空间的发布封面(1200×630);位图加 &format=png(og:image 尺寸,scale=2 为 retina)。
195
+ * @throws ApiError(400) with a corrective example on bad input
196
+ */
197
+ export function renderReleaseBannerFromUrl(url) {
198
+ return renderReleaseBanner({
199
+ title: url.searchParams.get('title') ?? '',
200
+ version: url.searchParams.get('version') ?? '',
201
+ cmd: url.searchParams.get('cmd') ?? '',
202
+ paper: url.searchParams.get('paper') ?? '',
203
+ }, url);
204
+ }
@@ -0,0 +1,62 @@
1
+ import type { DrawResult } from './query.js';
2
+ export interface Doc {
3
+ meta: Record<string, string>;
4
+ title: string;
5
+ subtitle: string;
6
+ bullets: string[];
7
+ sections: {
8
+ name: string;
9
+ major: boolean;
10
+ minor4?: boolean;
11
+ blocks: Block[];
12
+ }[];
13
+ }
14
+ type Block = {
15
+ k: 'p';
16
+ text: string;
17
+ } | {
18
+ k: 'li';
19
+ items: string[];
20
+ } | {
21
+ k: 'code';
22
+ lines: string[];
23
+ } | {
24
+ k: 'quote';
25
+ text: string;
26
+ } | {
27
+ k: 'hr';
28
+ } | {
29
+ k: 'img';
30
+ url: string;
31
+ alt: string;
32
+ w?: number;
33
+ h?: number;
34
+ } | {
35
+ k: 'table';
36
+ head: string[];
37
+ rows: string[][];
38
+ };
39
+ /** markdown 子集 → Doc。onesvg(Satori 内核)同用此解析。 */
40
+ export declare function parseOnepageDoc(md: string): Doc;
41
+ /**
42
+ * GET /draw/x-cmd/onepage?d=<urlencoded markdown> — ≤16000 字符(CJK percent-encoding
43
+ * 放大 ~3 倍,长文走 POST 或 ?src=<github url>)。POST /draw/x-cmd/onepage:body 即
44
+ * markdown,直接渲染返回 SVG(不存储)。条状长图:1800 宽,高度随内容生长;yfm:
45
+ * title/subtitle/contact/location/website/qr/qr-note。
46
+ * @throws ApiError(400) with a corrective example on bad input
47
+ */
48
+ export declare function renderOnepageFromUrl(url: URL): Promise<DrawResult>;
49
+ /** POST 通道:body 即 markdown(长度由 readBody 上限兜底),长文/CJK 全文走这里。 */
50
+ export declare function renderOnepageFromMarkdown(md: string, url: URL): Promise<DrawResult>;
51
+ /** PNG/JPEG/GIF/WebP 头部尺寸探测(无需解码)。 */
52
+ export declare function imgDims(b: Uint8Array): {
53
+ w: number;
54
+ h: number;
55
+ } | undefined;
56
+ /** github blob/raw 页面链接 → raw.githubusercontent.com 直链;其余原样返回。 */
57
+ export declare function toRawGithub(src: string): string;
58
+ /** GET ?src=<http url>:服务端取 markdown(≤64KB,文本类)再渲染 —— 长文放 GitHub,链接进 one。 */
59
+ export declare function renderOnepageFromSrc(src: string, url: URL): Promise<DrawResult>;
60
+ /** ?src= 的取文部分(onepage 与 onesvg 共用):github blob 自动转 raw,校验类型与大小。 */
61
+ export declare function fetchSrcDoc(src: string): Promise<string>;
62
+ export {};
@@ -0,0 +1,670 @@
1
+ // /draw/x-cmd/onepage 一页纸模式(x-cmd-hub/draw#28/#30):markdown(+yfm)进,
2
+ // 一张手机分享条状长图出 —— 1800 宽、高度随内容生长。
3
+ //
4
+ // ── 排版模型 v2.1(墨迹空隙记账) ───────────────────────────────────────────
5
+ //
6
+ // 1. 韵律唯一:所有字号是 BODY(画布/25)的倍数,所有空隙以 UNIT(一行正文)
7
+ // 计量 —— 全页只有一个尺度来源。
8
+ // 2. 墨迹记账:块间空隙指「墨迹到墨迹」的视觉距离 —— 引擎自动扣掉行盒
9
+ // half-leading,STYLE 表里的数字就是设计师心智里的数字,不随字号漂移。
10
+ // 3. 接近性分组(格式塔):标题 before >> after(≈2.4:1),标题永远归属下文;
11
+ // 组内(副标题/列表项)紧,组间(节)松 —— 空隙即结构。
12
+ // 4. 对比即层次:字号阶梯 ≥1.25 才可感知(1.5/1.28/1.12/1.0),粗细与颜色
13
+ // 只作辅助,不承担层级。
14
+ // 5. 折叠不叠加:相邻块空隙取 max(CSS margin-collapse 语义),节奏可预测。
15
+ // 6. 行盒:每行占「字号 × 行高」,字形以 1em 居中,基线 = 行盒顶 + 行高/2 + 0.34em;
16
+ // 折行 atom(拉丁词/CJK 单字)+ 避头尾禁则,行宽按内容宽实测。
17
+ import { ApiError } from '../specs/index.js';
18
+ import { resolveVersion } from '../version.js';
19
+ import { esc, textW, EDIT_TAG_STRIP_SRC } from './svg.js';
20
+ import { renderQR } from './qr.js';
21
+ import { resolveSkin } from '../styles/index.js';
22
+ import { INTER_FACE_CSS } from '../styles/inter.js';
23
+ import { BANNER_FACE_CSS } from './banner.js'; // 标题品牌字重(浏览器端 @font-face;resvg 端 png.ts 已挂)
24
+ import { FONT } from '../theme.js';
25
+ // ── 画布与版心 ───────────────────────────────────────────────────────────────
26
+ const W = 1800; // 画布宽(手机 2x)
27
+ const MARGIN = W * 0.12; // 页边 = 画布 12%(216)
28
+ const CONTENT = W - MARGIN * 2; // 版心 1368
29
+ const H_MAX = 40000;
30
+ const PAD_TOP = 120; // 顶部留白(大标题需呼吸;略小于底部)
31
+ const PAD_BOTTOM = 280; // 底部留白 > 顶部(页面是容器,下缘更松)
32
+ // ── 主题(取色源自原图 RGB 实测;只定义"用什么颜色",不定义版式) ────────────────
33
+ const THEME = {
34
+ accent: '#3f78f6', // 标题/副标题/顶级节左缘装饰条
35
+ ink: '#000000', // 节头、页脚联系行
36
+ body: '#808fa5', // 正文(蓝灰)
37
+ meta: '#686868', // 页头要点
38
+ code: '#374151',
39
+ codeBg: '#f5f7fa',
40
+ note: '#9e9d9d', // 页脚小字
41
+ rule: '#f5f5f5', // 页头下分隔带
42
+ bg: '#ffffff',
43
+ };
44
+ const F_TITLE = "'DrawInterBold','DrawCJKBold',Inter,'PingFang SC','Hiragino Sans GB','Microsoft YaHei','Noto Sans CJK SC',sans-serif";
45
+ const F_REG = "'DrawInter','DrawCJK',Inter,'PingFang SC','Hiragino Sans GB','Microsoft YaHei','Noto Sans CJK SC',sans-serif";
46
+ const F_BOLD = "'DrawInterBold','DrawCJKBold',Inter,'PingFang SC','Hiragino Sans GB','Microsoft YaHei','Noto Sans CJK SC',sans-serif";
47
+ const F_MONO = "'DrawMono',ui-monospace,Menlo,Consolas,monospace";
48
+ // ── 字号阶梯与样式表 ────────────────────────────────────────────────────────
49
+ // BODY 是唯一基准:字号 = BODY × r;行高 = 字号 × lineH。
50
+ // 间距 = 视觉空隙(墨迹到墨迹,UNIT 倍数)—— 引擎扣掉 half-leading 后落位,
51
+ // 表里的数字即设计稿,不随字号/行高漂移。块间空隙 = max(prev.after, this.before)。
52
+ const BODY = W / 25; // 72px @1800
53
+ const LINE = 1.5; // 正文行高(微信文章标准节奏)
54
+ const UNIT = BODY * LINE; // 韵律单位:一行正文(108)—— 所有空隙以此计量
55
+ const S = {
56
+ // ── 页头组:title/subtitle/要点/灰带是一个视觉组(组内紧,组间松) ──
57
+ title: { size: BODY * 1.5, lineH: 1.25, weight: 700, family: F_TITLE, color: THEME.accent, after: 1.1 }, // 大字下至少留一整行
58
+ subtitle: { size: BODY * 0.95, lineH: 1.55, weight: 400, family: F_REG, color: '#7aa3f7', before: 0.4, after: 0.6 }, // 紧跟标题(结组)
59
+ meta: { size: BODY * 0.92, lineH: 1.85, weight: 400, family: F_REG, color: '#8894a8', before: 0.6 }, // 要点连排:项间 0.6 UNIT ≈ 2 倍行距节奏
60
+ // ── 节头:before >> after(≈2.4:1)—— 接近性:标题永远归属下文 ──
61
+ h2: { size: BODY * 1.28, lineH: 1.3, weight: 700, family: F_BOLD, color: THEME.ink, before: 2.2, after: 1.0, bar: true },
62
+ h3: { size: BODY * 1.12, lineH: 1.35, weight: 700, family: F_BOLD, color: THEME.ink, before: 1.6, after: 0.8 },
63
+ h4: { size: BODY, lineH: 1.35, weight: 700, family: F_BOLD, color: THEME.meta, before: 1.2, after: 0.6 },
64
+ // ── 流体块:段间 ≈ 2× 行间;列表项间略大于行间(结组) ──
65
+ body: { size: BODY, lineH: LINE, weight: 400, family: F_REG, color: THEME.body, after: 0.7 }, // 段间空隙在 after 侧(不声明 before:标题 after 才能精确绑定下文)
66
+ li: { size: BODY, lineH: 1.45, weight: 400, family: F_REG, color: THEME.body, before: 0.4 },
67
+ quote: { size: BODY * 0.95, lineH: 1.7, weight: 400, family: F_REG, color: THEME.meta, before: 0.55, after: 0.7 },
68
+ code: { size: BODY * 0.78, lineH: 1.55, weight: 400, family: F_MONO, color: THEME.code, before: 0.55, after: 0.7 },
69
+ boldHead: { size: BODY, lineH: 1.4, weight: 700, family: F_BOLD, color: THEME.ink, before: 1.1, after: 0.55 }, // 独立粗体行 = 小节头(上松 2:1 紧)
70
+ figcap: { size: BODY * 0.5, lineH: 1.5, weight: 400, family: F_REG, color: THEME.note, before: 0.3 },
71
+ // ── 页脚组 ──
72
+ footHead: { size: BODY, lineH: 1.35, weight: 700, family: F_BOLD, color: THEME.ink, before: 2.2, after: 0.7, bar: true },
73
+ contact: { size: BODY, lineH: LINE, weight: 700, family: F_BOLD, color: THEME.ink, before: 0.35 },
74
+ contactSub: { size: BODY * 0.95, lineH: LINE, weight: 400, family: F_REG, color: THEME.body, before: 0.25 },
75
+ caption: { size: BODY * 0.45, lineH: 1.5, weight: 400, family: F_REG, color: THEME.note, before: 0.35 },
76
+ };
77
+ /** markdown 子集 → Doc。onesvg(Satori 内核)同用此解析。 */
78
+ export function parseOnepageDoc(md) {
79
+ return parse(md);
80
+ }
81
+ function parse(md) {
82
+ const meta = {};
83
+ let body = md.replace(/\r\n/g, '\n');
84
+ const yfm = /^---\n([\s\S]*?)\n---\n?/.exec(body);
85
+ if (yfm) {
86
+ body = body.slice(yfm[0].length);
87
+ for (const m of yfm[1].matchAll(/^([A-Za-z_][\w-]*)\s*:\s*(.+)$/gm))
88
+ meta[m[1].toLowerCase()] = m[2].trim();
89
+ }
90
+ let title = meta.title ?? '';
91
+ let subtitle = meta.subtitle ?? '';
92
+ body = body.replace(/^#\s+.+\n?/, (h) => { if (!title)
93
+ title = h.replace(/^#\s+/, '').trim(); return ''; });
94
+ if (!title)
95
+ throw new ApiError(400, 'onepage needs a title: yfm `title:` field or a `# heading` line');
96
+ const bullets = [];
97
+ const sections = [];
98
+ let cur;
99
+ const ensureBody = () => {
100
+ if (cur === undefined) {
101
+ cur = { name: '', major: false, blocks: [] };
102
+ sections.push(cur);
103
+ }
104
+ return cur;
105
+ };
106
+ const IMG_RE = /^!\[([^\]]*)\]\((\S+?)(?:\s+=(\d+)x(\d+))?\)$/;
107
+ for (const raw of body.split(/\n{2,}/)) {
108
+ const lines = raw.split('\n').map((l) => l.trim()).filter((l) => l !== '');
109
+ if (lines.length === 0)
110
+ continue;
111
+ if (/^```/.test(lines[0])) {
112
+ const codeLines = raw.split('\n').slice(1).filter((l) => !/^```/.test(l.trim()));
113
+ ensureBody().blocks.push({ k: 'code', lines: codeLines });
114
+ continue;
115
+ }
116
+ // 水平线:整块只有 --- / *** / ___
117
+ if (lines.every((l) => /^(-{3,}|\*{3,}|_{3,})$/.test(l))) {
118
+ ensureBody().blocks.push({ k: 'hr' });
119
+ continue;
120
+ }
121
+ // 引用块:整块每行以 > 开头
122
+ if (lines.every((l) => l.startsWith('>'))) {
123
+ ensureBody().blocks.push({ k: 'quote', text: lines.map((l) => l.replace(/^>\s?/, '')).join(' ') });
124
+ continue;
125
+ }
126
+ // 表格:首行为 |a|b| 且次行为 |---|---|
127
+ if (lines.length >= 2 && /^\|.*\|$/.test(lines[0]) && /^\|[-: |]+$/.test(lines[1])) {
128
+ const cells = (l) => l.slice(1, -1).split('|').map((c) => c.trim());
129
+ ensureBody().blocks.push({ k: 'table', head: cells(lines[0]), rows: lines.slice(2).map(cells) });
130
+ continue;
131
+ }
132
+ if (/^#{1,4}\s+/.test(lines[0])) {
133
+ const lvl = lines[0].match(/^#+/)[0].length; // #/## = 顶级(带装饰条),### 次级,#### 小节
134
+ cur = { name: lines[0].replace(/^#+\s+/, '').replace(/\*\*/g, '').replace(/`([^`]*)`/g, '$1').trim(), major: lvl <= 2, minor4: lvl === 4, blocks: [] };
135
+ sections.push(cur);
136
+ lines.shift();
137
+ if (lines.length === 0)
138
+ continue;
139
+ }
140
+ // 图表:整块单行 ![alt](url[=WxH])
141
+ if (lines.length === 1) {
142
+ const im = IMG_RE.exec(lines[0]);
143
+ if (im !== null) {
144
+ ensureBody().blocks.push({ k: 'img', url: im[2], alt: im[1], ...(im[3] !== undefined ? { w: Number(im[3]), h: Number(im[4]) } : {}) });
145
+ continue;
146
+ }
147
+ }
148
+ const listItems = lines.filter((l) => /^([-*]|\d+[.、)])\s+/.test(l));
149
+ if (listItems.length === lines.length) {
150
+ const items = listItems.map((l) => l.replace(/^([-*])\s+/, '').replace(/^(\d+[.、)])\s+/, '$1 '));
151
+ if (cur === undefined)
152
+ bullets.push(...items); // 首节前的列表 = 页头要点
153
+ else
154
+ cur.blocks.push({ k: 'li', items });
155
+ }
156
+ else {
157
+ ensureBody().blocks.push({ k: 'p', text: lines.join(' ') });
158
+ }
159
+ }
160
+ if (sections.length === 0 && bullets.length === 0)
161
+ throw new ApiError(400, 'onepage needs content: sections (`## heading`), paragraphs, or lists');
162
+ return { meta, title, subtitle, bullets, sections };
163
+ }
164
+ // ── 折行器:atom(拉丁词/CJK 单字)+ 避头尾禁则 ────────────────────────────────
165
+ // 行首禁则:这些字符不可居行首;行末禁则:这些字符不可居行末。
166
+ // 触发行首禁则时,把上一行行末最后一 atom 带下,标点不孤悬。
167
+ const NO_START = new Set([...'。,、;:?!,.:;?))]】」』”’…%‰']);
168
+ const NO_END = new Set([...'([([【「『“‘$#']);
169
+ const ATOM_RE = /[A-Za-z0-9'’\-@.:/#%&+]+|\s+|[^\s]/gu;
170
+ // 盘古之白:汉字与拉丁/数字之间自动加一个空格(中文排版惯例;mdnice 等微信
171
+ // 排版器同款)。行内 code run 不动(命令必须逐字)。
172
+ const HAN = '\u4e00-\u9fff';
173
+ function hanSpace(t) {
174
+ return t
175
+ .replace(new RegExp(`([${HAN}])([A-Za-z0-9])`, 'gu'), '$1 $2')
176
+ .replace(new RegExp(`([A-Za-z0-9])([${HAN}])`, 'gu'), '$1 $2');
177
+ }
178
+ function runs(text) {
179
+ const out = [];
180
+ for (const m of text.matchAll(/\*\*([^*]+)\*\*|`([^`]+)`|([^*`]+)/g)) {
181
+ if (m[1] !== undefined)
182
+ out.push({ t: hanSpace(m[1]), b: true });
183
+ else if (m[2] !== undefined)
184
+ out.push({ t: m[2], b: false, m: true });
185
+ else if (m[3] !== undefined && m[3] !== '')
186
+ out.push({ t: hanSpace(m[3]), b: false });
187
+ }
188
+ return out;
189
+ }
190
+ /** 折行内核:atom 序列 → 行(atom 携带宽度;禁则在断点处生效)。 */
191
+ function breakAtoms(atoms, maxW) {
192
+ const lines = [];
193
+ let line = [];
194
+ let w = 0;
195
+ for (const at of atoms) {
196
+ if (w + at.w > maxW && line.some((x) => x.a.trim() !== '')) {
197
+ let take = line;
198
+ if (at.a.trim() !== '' && NO_START.has(at.a[0]) && line.length > 1) {
199
+ const last = line[line.length - 1];
200
+ take = line.slice(0, -1);
201
+ line = [last];
202
+ w = last.w;
203
+ if (NO_END.has(last.a[last.a.length - 1]) && take.length > 1) {
204
+ const prev = take[take.length - 1];
205
+ line.unshift(prev);
206
+ w += prev.w;
207
+ take = take.slice(0, -1);
208
+ }
209
+ }
210
+ else {
211
+ line = [];
212
+ w = 0;
213
+ }
214
+ lines.push(take);
215
+ }
216
+ if (at.a.trim() !== '' || line.some((x) => x.a.trim() !== '')) {
217
+ line.push(at);
218
+ w += at.w;
219
+ }
220
+ }
221
+ if (line.some((x) => x.a.trim() !== ''))
222
+ lines.push(line);
223
+ return lines;
224
+ }
225
+ const toAtoms = (text, fs) => [...text.matchAll(ATOM_RE)].map((m) => ({ a: m[0], w: textW(m[0], fs) }));
226
+ /** 纯文本折行(标题/要点等)。 */
227
+ function wrap(text, fs, maxW) {
228
+ return breakAtoms(toAtoms(text, fs), maxW).map((l) => l.map((x) => x.a).join(''));
229
+ }
230
+ /** 带粗体标记的段落折行 → 每行 Run[](行内容与禁则一致,粗体位不漂移)。 */
231
+ function wrapRuns(rs, fs, maxW) {
232
+ const atoms = [];
233
+ for (const r of rs) {
234
+ for (const m of r.t.matchAll(ATOM_RE))
235
+ atoms.push({ a: m[0], b: r.b, m: r.m, w: textW(m[0], fs) });
236
+ }
237
+ return breakAtoms(atoms, maxW).map((ls) => {
238
+ const out = [];
239
+ for (const x of ls) {
240
+ const lastR = out[out.length - 1];
241
+ if (lastR !== undefined && lastR.b === x.b && lastR.m === x.m)
242
+ lastR.t += x.a;
243
+ else
244
+ out.push({ t: x.a, b: x.b, m: x.m });
245
+ }
246
+ return out;
247
+ });
248
+ }
249
+ // 代码行折行:无禁则(逐字符硬折,续行缩进两空格)
250
+ function wrapCode(lines, fs, maxW) {
251
+ const out = [];
252
+ for (const l of lines) {
253
+ const hard = l.replace(/\s+$/, '');
254
+ if (hard === '') {
255
+ out.push('');
256
+ continue;
257
+ }
258
+ let cur = '';
259
+ let w = 0;
260
+ let cont = false;
261
+ for (const ch of hard) {
262
+ const cw = textW(ch, fs);
263
+ if (w + cw > maxW && cur !== '') {
264
+ out.push((cont ? ' ' : '') + cur);
265
+ cont = true;
266
+ cur = ch;
267
+ w = cw;
268
+ }
269
+ else {
270
+ cur += ch;
271
+ w += cw;
272
+ }
273
+ }
274
+ if (cur !== '')
275
+ out.push((cont ? ' ' : '') + cur);
276
+ }
277
+ return out;
278
+ }
279
+ // ── 布局器:墨迹记账 + 空隙折叠 ─────────────────────────────────────────────
280
+ // 游标 ink 记「上一块墨迹底」(文本以 1em 计,盒块以盒边计);块间空隙
281
+ // gap = max(prev.after, this.before) × UNIT
282
+ // 是纯视觉距离(墨迹到墨迹)—— STYLE 表的数字即设计稿,不随字号漂移。
283
+ /** 行盒顶/底到墨迹边缘的 half-leading(字形以 1em 居中于行盒)。 */
284
+ const hl = (st) => st.size * (st.lineH - 1) / 2;
285
+ /** 行盒顶 → 该行基线:字形在行盒内垂直居中,基线在 em 中心下方 0.34em。 */
286
+ const baseline = (top, st) => top + st.size * st.lineH / 2 + st.size * 0.34;
287
+ /** 居中单行(页脚联系区/图题注专用)。 */
288
+ function centerLine(text, st, y) {
289
+ return `<text x="${W / 2}" y="${baseline(y, st).toFixed(0)}" text-anchor="middle" font-family="${st.family}" font-size="${st.size.toFixed(0)}"${st.weight === 700 ? ' font-weight="700"' : ''} fill="${st.color}">${esc(text)}</text>`;
290
+ }
291
+ function layout(doc, v, imgMap = {}) {
292
+ const items = [];
293
+ const push = (s) => { items.push({ s }); };
294
+ let ink = PAD_TOP; // 上一块墨迹底
295
+ let post = 0; // 上一块留下的 after 愿望(UNIT 倍数)
296
+ // 开文本块:视觉空隙 → 首行行盒顶(扣本块 half-leading)
297
+ const openText = (st, before) => {
298
+ const g = Math.max(post, before ?? st.before ?? 0);
299
+ post = 0;
300
+ return ink + g * UNIT - hl(st);
301
+ };
302
+ const closeText = (st, boxBottom) => { ink = boxBottom - hl(st); };
303
+ // 开盒块(代码框/图/线):墨迹即盒边,无需扣 leading
304
+ const openBox = (before) => {
305
+ const g = Math.max(post, before);
306
+ post = 0;
307
+ return ink + g * UNIT;
308
+ };
309
+ const leave = (n) => { post = n; };
310
+ // 行链:逐行 <text>(基线由行盒推导);返回末行行盒底
311
+ const emitRuns = (rs, st, top, maxW = CONTENT, x = MARGIN) => {
312
+ for (const lineRuns of wrapRuns(rs, st.size, maxW)) {
313
+ const body = lineRuns
314
+ .map((r) => {
315
+ if (r.b)
316
+ return `<tspan font-family="${F_BOLD}" fill="${THEME.ink}">${esc(r.t)}</tspan>`;
317
+ if (r.m)
318
+ return `<tspan font-family="${F_MONO}">${esc(r.t)}</tspan>`;
319
+ return esc(r.t);
320
+ })
321
+ .join('');
322
+ push(`<text x="${x}" y="${baseline(top, st).toFixed(0)}" font-family="${st.family}" font-size="${st.size.toFixed(0)}" font-weight="${st.weight}" fill="${st.color}">${body}</text>`);
323
+ top += st.size * st.lineH;
324
+ }
325
+ return top;
326
+ };
327
+ // 文本块一步到位(段落/标题/要点)
328
+ const textBlock = (rs, st, maxW = CONTENT, x = MARGIN) => {
329
+ closeText(st, emitRuns(rs, st, openText(st), maxW, x));
330
+ leave(st.after ?? 0);
331
+ };
332
+ const plainBlock = (text, st, maxW = CONTENT, x = MARGIN) => textBlock(runs(text), st, maxW, x);
333
+ // 左缘装饰条:与节头首行行盒同高,左缘出血(主题元素)
334
+ const bar = (top, st) => {
335
+ push(`<rect x="0" y="${(top + st.size * st.lineH * 0.06).toFixed(0)}" width="${W * 0.045}" height="${(st.size * st.lineH * 0.88).toFixed(0)}" fill="${THEME.accent}"/>`);
336
+ };
337
+ // ── 页头组:标题 → 副标题 → 要点 → 灰带收边 ──
338
+ plainBlock(doc.title, S.title);
339
+ if (doc.subtitle !== '')
340
+ plainBlock(doc.subtitle, S.subtitle);
341
+ if (doc.bullets.length > 0) {
342
+ for (const b of doc.bullets)
343
+ plainBlock(b, S.meta);
344
+ const ry = openBox(0.5);
345
+ push(`<rect x="0" y="${ry.toFixed(0)}" width="${W}" height="${(0.5 * UNIT).toFixed(0)}" fill="${THEME.rule}"/>`);
346
+ ink = ry + 0.5 * UNIT;
347
+ leave(0.8);
348
+ }
349
+ // ── 正文节 ──
350
+ for (const sec of doc.sections) {
351
+ if (sec.name !== '') {
352
+ const st = sec.minor4 === true ? S.h4 : sec.major ? S.h2 : S.h3;
353
+ const top = openText(st);
354
+ if (st.bar === true)
355
+ bar(top, st);
356
+ closeText(st, emitRuns(runs(sec.name), st, top));
357
+ leave(st.after ?? 0);
358
+ }
359
+ for (const blk of sec.blocks) {
360
+ if (blk.k === 'li') {
361
+ const st = S.li;
362
+ for (const it of blk.items) {
363
+ const numbered = /^\d+[.、)]/.test(it);
364
+ const text = numbered ? it.slice(it.indexOf('.') + 1).trim() : it.replace(/^[-*]\s+/, '');
365
+ const markerW = 0.75 * BODY;
366
+ let top = openText(st);
367
+ const mk = `<text x="${MARGIN}" y="${baseline(top, st).toFixed(0)}" font-family="${st.family}" font-size="${st.size.toFixed(0)}" font-weight="700" fill="${THEME.accent}">${numbered ? it.slice(0, it.indexOf('.')) + '.' : '•'}</text>`;
368
+ wrapRuns(runs(text), st.size, CONTENT - markerW).forEach((lineRuns, i) => {
369
+ const body = lineRuns
370
+ .map((r) => (r.b ? `<tspan font-family="${F_BOLD}" fill="${THEME.ink}">${esc(r.t)}</tspan>` : esc(r.t)))
371
+ .join('');
372
+ push(`${i === 0 ? mk : ''}<text x="${MARGIN + markerW}" y="${baseline(top, st).toFixed(0)}" font-family="${st.family}" font-size="${st.size.toFixed(0)}" font-weight="${st.weight}" fill="${st.color}">${body}</text>`);
373
+ top += st.size * st.lineH;
374
+ });
375
+ closeText(st, top);
376
+ leave(0); // 项间空隙由下一项的 before(0.4)承担
377
+ }
378
+ leave(S.body.after ?? 0.7); // 列表块尾:与段落块同级的分离空隙
379
+ }
380
+ else if (blk.k === 'code') {
381
+ const st = S.code;
382
+ const y = openBox(st.before ?? 0);
383
+ const pad = 0.35 * UNIT;
384
+ const clines = wrapCode(blk.lines, st.size, CONTENT - pad * 2);
385
+ const boxH = pad * 2 + clines.length * st.size * st.lineH;
386
+ push(`<rect x="${MARGIN}" y="${y.toFixed(0)}" width="${CONTENT}" height="${boxH.toFixed(0)}" rx="${(0.2 * UNIT).toFixed(0)}" fill="${THEME.codeBg}"/>`);
387
+ let ty = y + pad;
388
+ for (const l of clines) {
389
+ push(`<text x="${(MARGIN + pad).toFixed(0)}" y="${baseline(ty, st).toFixed(0)}" font-family="${st.family}" font-size="${st.size.toFixed(0)}" fill="${st.color}">${esc(l)}</text>`);
390
+ ty += st.size * st.lineH;
391
+ }
392
+ ink = y + boxH;
393
+ leave(st.after ?? 0);
394
+ }
395
+ else if (blk.k === 'quote') {
396
+ const st = S.quote;
397
+ const top = openText(st);
398
+ const indent = 0.5 * UNIT;
399
+ const lineList = wrapRuns(runs(blk.text), st.size, CONTENT - indent - 0.4 * UNIT);
400
+ let ty = top;
401
+ for (const lineRuns of lineList) {
402
+ const body = lineRuns.map((r) => esc(r.t)).join('');
403
+ push(`<text x="${MARGIN + indent}" y="${baseline(ty, st).toFixed(0)}" font-family="${st.family}" font-size="${st.size.toFixed(0)}" fill="${st.color}">${body}</text>`);
404
+ ty += st.size * st.lineH;
405
+ }
406
+ // 竖线:墨迹链两端各延伸 0.1 UNIT(光学 padding,消除贴边感)
407
+ const qy = top + hl(st) - 0.1 * UNIT;
408
+ push(`<rect x="${MARGIN + indent * 0.35}" y="${qy.toFixed(0)}" width="6" height="${(ty - hl(st) + 0.2 * UNIT - qy).toFixed(0)}" fill="${THEME.accent}"/>`);
409
+ closeText(st, ty);
410
+ leave(st.after ?? 0);
411
+ }
412
+ else if (blk.k === 'hr') {
413
+ const y = openBox(0.5);
414
+ push(`<rect x="${MARGIN}" y="${y.toFixed(0)}" width="${CONTENT}" height="2" fill="#e5e7eb"/>`);
415
+ ink = y + 2;
416
+ leave(0.8);
417
+ }
418
+ else if (blk.k === 'img') {
419
+ // 图表:居中图块(图表居中规则)。imgMap 提供尺寸与 data-URI;缺省占位
420
+ const info = imgMap[blk.url];
421
+ const maxW = CONTENT;
422
+ let iw = blk.w ?? info?.w ?? maxW * 0.7;
423
+ let ih = blk.h ?? info?.h ?? iw * 0.62;
424
+ if (iw > maxW) {
425
+ ih = ih * maxW / iw;
426
+ iw = maxW;
427
+ }
428
+ const y = openBox(0.6);
429
+ const ix = MARGIN + (CONTENT - iw) / 2;
430
+ if (info !== undefined && info.data !== undefined) {
431
+ push(`<image href="${info.data}" x="${ix.toFixed(0)}" y="${y.toFixed(0)}" width="${iw.toFixed(0)}" height="${ih.toFixed(0)}"/>`);
432
+ }
433
+ else {
434
+ push(`<rect x="${ix.toFixed(0)}" y="${y.toFixed(0)}" width="${iw.toFixed(0)}" height="${ih.toFixed(0)}" rx="8" fill="${THEME.codeBg}"/>`);
435
+ push(`<text x="${(ix + iw / 2).toFixed(0)}" y="${(y + ih / 2).toFixed(0)}" text-anchor="middle" font-family="${F_REG}" font-size="${(BODY * 0.5).toFixed(0)}" fill="${THEME.note}">${esc(blk.alt || 'figure')}</text>`);
436
+ }
437
+ ink = y + ih;
438
+ if (blk.alt !== '') {
439
+ const st = S.figcap;
440
+ const top = openText(st); // figcap.before 0.3:题注与图结组
441
+ push(centerLine(blk.alt, st, top));
442
+ closeText(st, top + st.size * st.lineH);
443
+ leave(0.5);
444
+ }
445
+ else {
446
+ leave(0.6);
447
+ }
448
+ }
449
+ else if (blk.k === 'table') {
450
+ // 表格轻量呈现:表头粗 + 行内 " · " 连接;表头下划线 + 行间发丝线
451
+ const st = S.body;
452
+ let top = openText(st, 0.55);
453
+ top = emitRuns(runs(blk.head.map((h) => `**${h}**`).join(' · ')), st, top);
454
+ push(`<rect x="${MARGIN}" y="${(top + 0.06 * UNIT).toFixed(0)}" width="${CONTENT}" height="3" fill="#d8dce4"/>`);
455
+ top += 0.22 * UNIT;
456
+ for (const row of blk.rows) {
457
+ top = emitRuns(runs(row.join(' · ')), st, top);
458
+ push(`<rect x="${MARGIN}" y="${(top + 0.03 * UNIT).toFixed(0)}" width="${CONTENT}" height="1" fill="#eef0f4"/>`);
459
+ top += 0.10 * UNIT;
460
+ }
461
+ closeText(st, top);
462
+ leave(0.65);
463
+ }
464
+ else if (blk.k === 'p') {
465
+ // 独立粗体行(**小节**)按小节头排版:获得「上松下紧」的分组语义
466
+ const st = /^\*\*[^*]+\*\*$/.test(blk.text.trim()) ? S.boldHead : S.body;
467
+ textBlock(runs(blk.text), st);
468
+ }
469
+ }
470
+ }
471
+ // ── 页脚组:联系方式(带条)→ 居中联系行 → 居中 QR → 小字说明 ──
472
+ const contact = doc.meta.contact;
473
+ const subLines = [doc.meta.location, doc.meta.website].filter((s) => typeof s === 'string' && s !== '');
474
+ const qrUrl = doc.meta.qr;
475
+ if (contact !== undefined || subLines.length > 0 || qrUrl !== undefined) {
476
+ const fst = S.footHead;
477
+ const ftop = openText(fst);
478
+ bar(ftop, fst);
479
+ closeText(fst, emitRuns(runs(doc.meta['contact-title'] ?? '联系方式'), fst, ftop));
480
+ leave(fst.after ?? 0);
481
+ for (const [st, text] of [
482
+ ...(contact !== undefined ? [[S.contact, contact]] : []),
483
+ ...subLines.map((sl) => [S.contactSub, sl]),
484
+ ]) {
485
+ const cy = openText(st);
486
+ push(centerLine(text, st, cy));
487
+ closeText(st, cy + st.size * st.lineH);
488
+ leave(st.after ?? 0);
489
+ }
490
+ if (qrUrl !== undefined) {
491
+ const qy = openBox(0.5);
492
+ const q = 0.36 * W; // QR 边长 = 画布 36%(≈650,扫码距离友好)
493
+ const qx = (W - q) / 2;
494
+ const qr = renderQR(qrUrl.slice(0, 500), '#000000', '#ffffff', q, q, v, resolveSkin('qr', null, 'light'), undefined, undefined)
495
+ .replace(/^<svg[^>]*>/, '').replace(/<\/svg>$/, '')
496
+ .replace(/<style[\s\S]*?<\/style>/g, '')
497
+ .replace(/<metadata>[\s\S]*?<\/metadata>/g, '')
498
+ .replace(new RegExp(EDIT_TAG_STRIP_SRC, 'g'), '');
499
+ push(`<g transform="translate(${qx.toFixed(0)}, ${qy.toFixed(0)})">${qr}</g>`);
500
+ ink = qy + q;
501
+ const capY = openText(S.caption);
502
+ push(centerLine(doc.meta['qr-note'] ?? '扫码了解更多', S.caption, capY));
503
+ closeText(S.caption, capY + S.caption.size * S.caption.lineH);
504
+ }
505
+ }
506
+ return { items, total: ink + PAD_BOTTOM };
507
+ }
508
+ // ── 渲染入口 ───────────────────────────────────────────────────────────────
509
+ function render(md, url, imgMap = {}) {
510
+ const v = resolveVersion(url.searchParams.get('v'));
511
+ const doc = parse(md);
512
+ const lay = layout(doc, v.version, imgMap);
513
+ if (lay.total > H_MAX) {
514
+ throw new ApiError(400, `onepage is ${Math.round(lay.total)}px tall (max ${H_MAX}); split the doc`);
515
+ }
516
+ const HT = Math.ceil(lay.total);
517
+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${HT}" viewBox="0 0 ${W} ${HT}" font-family="${FONT}" role="img" aria-label="${esc(doc.title)}">` +
518
+ `<style>${INTER_FACE_CSS}${BANNER_FACE_CSS}</style>` +
519
+ `<metadata>${esc(JSON.stringify({ generator: 'draw', template: 'onepage', namespace: 'x-cmd', theme: 'md-engine-v2.1', version: v.version, title: doc.title }))}</metadata>` +
520
+ `<rect width="${W}" height="${HT}" fill="${THEME.bg}"/>` +
521
+ lay.items.map((it) => it.s).join('') +
522
+ `</svg>`;
523
+ return { svg, version: v.version, cacheControl: v.cacheControl };
524
+ }
525
+ /**
526
+ * GET /draw/x-cmd/onepage?d=<urlencoded markdown> — ≤16000 字符(CJK percent-encoding
527
+ * 放大 ~3 倍,长文走 POST 或 ?src=<github url>)。POST /draw/x-cmd/onepage:body 即
528
+ * markdown,直接渲染返回 SVG(不存储)。条状长图:1800 宽,高度随内容生长;yfm:
529
+ * title/subtitle/contact/location/website/qr/qr-note。
530
+ * @throws ApiError(400) with a corrective example on bad input
531
+ */
532
+ export async function renderOnepageFromUrl(url) {
533
+ const raw = url.searchParams.get('d');
534
+ if (raw === null || raw.trim() === '') {
535
+ throw new ApiError(400, '"d" (urlencoded markdown) or "src" (http url of the markdown) is required, e.g. d=' + encodeURIComponent('---\ntitle: Hello\n---\n## 简介\n第一段…') + ' (long docs: POST the body or src=<github blob url>)');
536
+ }
537
+ if (raw.length > 16000)
538
+ throw new ApiError(400, `"d" is ${raw.length} chars (max 16000); POST the markdown or use ?src= instead`);
539
+ return renderDoc(raw, url);
540
+ }
541
+ /** POST 通道:body 即 markdown(长度由 readBody 上限兜底),长文/CJK 全文走这里。 */
542
+ export async function renderOnepageFromMarkdown(md, url) {
543
+ return renderDoc(md, url);
544
+ }
545
+ // ── 图表资源:服务端并行取图 + 尺寸探测(居中图块需先知宽高) ────────────────────
546
+ const IMG_MAX = 2 * 1024 * 1024;
547
+ const IMG_MAX_COUNT = 8;
548
+ /** PNG/JPEG/GIF/WebP 头部尺寸探测(无需解码)。 */
549
+ export function imgDims(b) {
550
+ const v = new DataView(b.buffer, b.byteOffset, b.byteLength);
551
+ if (b.length > 24 && v.getUint32(0) === 0x89504e47)
552
+ return { w: v.getUint32(16), h: v.getUint32(20) }; // PNG IHDR
553
+ if (b.length > 10 && b[0] === 0x47 && b[1] === 0x49)
554
+ return { w: v.getUint16(6, true), h: v.getUint16(8, true) }; // GIF
555
+ if (b.length > 4 && b[0] === 0xff && b[1] === 0xd8) { // JPEG SOF
556
+ let i = 2;
557
+ while (i + 9 < b.length) {
558
+ if (b[i] !== 0xff) {
559
+ i++;
560
+ continue;
561
+ }
562
+ const m = b[i + 1];
563
+ if (m >= 0xc0 && m <= 0xcf && m !== 0xc4 && m !== 0xc8 && m !== 0xcc) {
564
+ return { h: v.getUint16(i + 5), w: v.getUint16(i + 7) };
565
+ }
566
+ i += 2 + v.getUint16(i + 2);
567
+ }
568
+ return undefined;
569
+ }
570
+ if (b.length > 30 && v.getUint32(0) === 0x52494646) { // RIFF…WebP
571
+ const tag = String.fromCharCode(b[12], b[13], b[14]);
572
+ if (tag === 'VP8 ')
573
+ return { w: v.getUint16(26, true) & 0x3fff, h: v.getUint16(28, true) & 0x3fff };
574
+ if (tag === 'VP8L') {
575
+ const bits = v.getUint32(21, true);
576
+ return { w: (bits & 0x3fff) + 1, h: ((bits >> 14) & 0x3fff) + 1 };
577
+ }
578
+ if (tag === 'VP8X')
579
+ return { w: (v.getUint32(24, true) & 0xffffff) + 1, h: (v.getUint32(27, true) & 0xffffff) + 1 };
580
+ }
581
+ return undefined;
582
+ }
583
+ async function resolveImages(md) {
584
+ const urls = [...md.matchAll(/^!\[[^\]]*\]\((\S+?)(?:\s+=\d+x\d+)?\)$/gm)].map((m) => m[1]).slice(0, IMG_MAX_COUNT);
585
+ const out = {};
586
+ await Promise.all(urls.map(async (u) => {
587
+ if (!/^https?:\/\//.test(u))
588
+ return;
589
+ try {
590
+ const r = await fetch(u, { redirect: 'follow' });
591
+ if (!r.ok)
592
+ return;
593
+ const buf = new Uint8Array(await r.arrayBuffer());
594
+ if (buf.byteLength > IMG_MAX)
595
+ return;
596
+ const dims = imgDims(buf);
597
+ if (dims === undefined)
598
+ return;
599
+ const kind = (r.headers.get('content-type') ?? 'image/png').split(';')[0];
600
+ out[u] = { ...dims, data: `data:${kind};base64,${b64(buf)}` };
601
+ }
602
+ catch { /* 取不到 → 占位框 */ }
603
+ }));
604
+ return out;
605
+ }
606
+ const b64 = (b) => {
607
+ let s = '';
608
+ const CH = 0x8000;
609
+ for (let i = 0; i < b.length; i += CH)
610
+ s += String.fromCharCode(...b.subarray(i, i + CH));
611
+ return btoa(s);
612
+ };
613
+ /** 渲染入口:先并行取图(图表居中需要尺寸),再同步走版。 */
614
+ async function renderDoc(md, url) {
615
+ return render(md, url, md.includes('](') ? await resolveImages(md) : {});
616
+ }
617
+ // ── ?src= 远程取文(参考 x-cmd/ppt 的三步逻辑) ────────────────────────────────
618
+ // ① github 地址自动转 raw;② client 端能取就自取(raw.githubusercontent 自带
619
+ // ACAO:*);③ 跨域取不到 → /draw/nocors?url= 服务端代取。onepage 的 ?src= 走
620
+ // 服务端 fetch,天然无跨域,①只负责把 blob 链接规范成 raw 直链。
621
+ const SRC_MAX = 65536; // 源文档上限(比 ?d= 的 16000 放宽一档,POST 仍最宽)
622
+ /** github blob/raw 页面链接 → raw.githubusercontent.com 直链;其余原样返回。 */
623
+ export function toRawGithub(src) {
624
+ let u;
625
+ try {
626
+ u = new URL(src);
627
+ }
628
+ catch {
629
+ throw new ApiError(400, `"src" is not a valid URL: ${JSON.stringify(src.slice(0, 120))}`);
630
+ }
631
+ if (u.protocol !== 'https:' && u.protocol !== 'http:') {
632
+ throw new ApiError(400, `"src" must be http(s), got ${u.protocol}`);
633
+ }
634
+ if (u.hostname === 'github.com' || u.hostname === 'www.github.com') {
635
+ const m = u.pathname.match(/^\/([^/]+)\/([^/]+)\/(?:blob|raw)\/(.+)$/);
636
+ if (m)
637
+ return `https://raw.githubusercontent.com/${m[1]}/${m[2]}/${m[3]}${u.search}`;
638
+ }
639
+ return u.toString();
640
+ }
641
+ /** GET ?src=<http url>:服务端取 markdown(≤64KB,文本类)再渲染 —— 长文放 GitHub,链接进 one。 */
642
+ export async function renderOnepageFromSrc(src, url) {
643
+ return render(await fetchSrcDoc(src), url);
644
+ }
645
+ /** ?src= 的取文部分(onepage 与 onesvg 共用):github blob 自动转 raw,校验类型与大小。 */
646
+ export async function fetchSrcDoc(src) {
647
+ const target = toRawGithub(src);
648
+ let res;
649
+ try {
650
+ res = await fetch(target, {
651
+ headers: { 'user-agent': 'x-cmd-draw/onepage', accept: 'text/plain, text/markdown;q=0.9, */*;q=0.1' },
652
+ redirect: 'follow',
653
+ });
654
+ }
655
+ catch (e) {
656
+ throw new ApiError(400, `src fetch failed (${e instanceof Error ? e.message : 'network error'}): ${target}`);
657
+ }
658
+ if (!res.ok) {
659
+ throw new ApiError(res.status === 404 ? 404 : 400, `src fetch got ${res.status} for ${target}`);
660
+ }
661
+ const ct = res.headers.get('content-type') ?? '';
662
+ if (/(image|audio|video|font)\//i.test(ct)) {
663
+ throw new ApiError(400, `src is ${ct}, expected markdown/text (github blob links are converted to raw automatically)`);
664
+ }
665
+ const body = await res.text();
666
+ if (body.length > SRC_MAX) {
667
+ throw new ApiError(400, `src doc is ${body.length} chars (max ${SRC_MAX}); POST the markdown instead`);
668
+ }
669
+ return body;
670
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * 把 `?src=<url>` 取来的规格折进 `d=` —— 返回一个改好的 URL ✓
3
+ * (取来的 JSON 当成 d= 用 ✓;其余参数:标题、尺寸、风格照旧 ✓)。
4
+ */
5
+ export declare function resolveSrcSpec(url: URL): Promise<URL>;
@@ -0,0 +1,55 @@
1
+ // `?src=<url>`:规格放在文件里,URL 只带一个链接。
2
+ //
3
+ // 天梯图这类会有上千行数据 —— 塞进 URL 会超长(浏览器几千字符、代理几 KB 都有上限)。
4
+ // 所以规格可以放在一个 JSON 文件里,URL 只给链接。
5
+ //
6
+ // 跟 onepage 的 `?src=` 一个规矩:github blob 链接自动转 raw ✓;
7
+ // 不许取回环和私网地址(SSRF)✓;体积上限 1MB ✓。
8
+ //
9
+ // **一份实现** ✓ —— 库自己的 HTTP 层与站里的 worker 都用这个 ✓(别各抄一份 ✓)。
10
+ import { ApiError } from '../specs/index.js';
11
+ import { toRawGithub } from './onepage.js';
12
+ /**
13
+ * 把 `?src=<url>` 取来的规格折进 `d=` —— 返回一个改好的 URL ✓
14
+ * (取来的 JSON 当成 d= 用 ✓;其余参数:标题、尺寸、风格照旧 ✓)。
15
+ */
16
+ export async function resolveSrcSpec(url) {
17
+ const src = url.searchParams.get('src');
18
+ if (src === null || src === '')
19
+ return url;
20
+ const raw = toRawGithub(src);
21
+ const host = new URL(raw).hostname;
22
+ if (/^(localhost|127\.|10\.|192\.168\.|169\.254\.|0\.0\.0\.0$|\[?::1)/.test(host)) {
23
+ throw new ApiError(400, 'refusing to fetch private/loopback addresses');
24
+ }
25
+ let up;
26
+ try {
27
+ up = await fetch(raw, { headers: { 'user-agent': 'x-cmd/draw', accept: '*/*' }, redirect: 'follow' });
28
+ }
29
+ catch (e) {
30
+ throw new ApiError(502, `upstream fetch failed: ${e instanceof Error ? e.message : 'network error'}`);
31
+ }
32
+ if (up.status >= 400) {
33
+ throw new ApiError(up.status >= 500 ? 502 : 404, `upstream ${up.status} for ${raw}`);
34
+ }
35
+ const text = await up.text();
36
+ if (text.length > 1024 * 1024) {
37
+ throw new ApiError(413, `upstream spec is ${text.length}B (max 1048576)`);
38
+ }
39
+ let spec;
40
+ try {
41
+ spec = JSON.parse(text);
42
+ }
43
+ catch {
44
+ throw new ApiError(400, `upstream spec is not valid JSON: ${raw}`);
45
+ }
46
+ const next = new URL(url);
47
+ next.searchParams.delete('src');
48
+ next.searchParams.set('d', text);
49
+ // 规格文件自己知道是什么图(JSON 里的 type ✓)—— URL 没带 type 就补上 ✓
50
+ // (只给一个文件链接就能画 ✓ —— 这就是 ?src= 的用法 ✓)
51
+ if (!next.searchParams.get('type') && spec && typeof spec === 'object' && typeof spec.type === 'string') {
52
+ next.searchParams.set('type', spec.type);
53
+ }
54
+ return next;
55
+ }
@@ -220,42 +220,49 @@ export function matchLadderRows(left, right, match = 'rank') {
220
220
  all.sort((a, b) => b.item.value - a.item.value);
221
221
  return all.map((x) => (x.side === 0 ? [x.item, undefined] : [undefined, x.item]));
222
222
  }
223
- // 匹配排序:按左边的次序,给每张卡找右边数值最接近的那张
224
- const n = Math.max(left.length, right.length);
225
- const usedRight = new Set();
226
- const rows = [];
227
- for (let i = 0; i < n; i++) {
228
- const l = left[i];
229
- if (!l) {
230
- rows.push([undefined, right[i]]);
223
+ // 匹配排序:**右边每一张卡去找左边数值最接近的那张**,待到那一行去。
224
+ //
225
+ // 「左边在后面三行,右边那张也得找最相近的」—— 哪怕中间空出几行,
226
+ // 被拉走的那张原来的位置就**空着**(缺位)。缺位不是 bug,是信号:
227
+ // 这一档真的没有能对上的卡。
228
+ //
229
+ // 为什么这么设计:左右两边都是**按强弱排好**的,所以「找最接近的那个」
230
+ // 的结果是**单调**的 —— 两张右边的卡不会抢同一行,总距离也是最小的。
231
+ // (换成「每行去抢最接近的那张」就不单调了,谁先谁抢,顺序一换结果就变。)
232
+ const taken = new Set(); // 已被占用的左边行
233
+ const placeAt = new Map(); // 左边第 i 行 → 右边第 j 张
234
+ for (let j = 0; j < right.length; j++) {
235
+ const r = right[j];
236
+ if (!r)
231
237
  continue;
232
- }
233
238
  let best = -1;
234
239
  let bestGap = Infinity;
235
- for (let j = 0; j < right.length; j++) {
236
- if (usedRight.has(j))
240
+ for (let i = 0; i < left.length; i++) {
241
+ const l = left[i];
242
+ if (!l || taken.has(i))
237
243
  continue;
238
- const gap = Math.abs(Math.log(right[j].value) - Math.log(l.value));
244
+ const gap = Math.abs(Math.log(r.value) - Math.log(l.value));
239
245
  if (gap < bestGap) {
240
246
  bestGap = gap;
241
- best = j;
247
+ best = i;
242
248
  }
243
249
  }
244
- if (best < 0) {
245
- rows.push([l, undefined]);
246
- }
247
- else {
248
- usedRight.add(best);
249
- rows.push([l, right[best]]);
250
+ if (best >= 0) {
251
+ taken.add(best);
252
+ placeAt.set(best, j);
250
253
  }
251
254
  }
252
- // 右边剩下没配上的,填进左边空着的行
253
- const spare = [...right.keys()].filter((j) => !usedRight.has(j));
254
- let k = 0;
255
- for (let i = 0; i < rows.length && k < spare.length; i++) {
256
- if (!rows[i][0]) {
257
- rows[i] = [undefined, right[spare[k++]]];
258
- }
255
+ // 没配上左边的右边卡,留在自己原来的行
256
+ const n = Math.max(left.length, right.length);
257
+ const rows = [];
258
+ for (let i = 0; i < n; i++) {
259
+ const j = placeAt.get(i);
260
+ let r;
261
+ if (j !== undefined)
262
+ r = right[j];
263
+ else if (i < right.length && !taken.has(i) && ![...placeAt.values()].includes(i))
264
+ r = right[i];
265
+ rows.push([left[i], r]);
259
266
  }
260
267
  return rows;
261
268
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@x-cmd/draw",
3
- "version": "0.4.0",
3
+ "version": "0.4.2",
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",