@fengwk/kchart 0.1.1 → 0.2.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.
Files changed (101) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.md +31 -2
  3. package/README.zh-CN.md +31 -2
  4. package/dist/esm/_virtual/_kchart-families.js +2 -1
  5. package/dist/esm/chart/composition.js +7 -5
  6. package/dist/esm/chart/maps.js +9 -7
  7. package/dist/esm/chart/mindmap.js +19 -5
  8. package/dist/esm/chart/multivariate.js +49 -14
  9. package/dist/esm/chart/relations.js +15 -7
  10. package/dist/esm/chart/spec.js +5 -2
  11. package/dist/esm/core/context.js +29 -10
  12. package/dist/esm/core/scene.js +238 -21
  13. package/dist/esm/core/text.js +1 -1
  14. package/dist/esm/diagram/block.js +287 -295
  15. package/dist/esm/diagram/blocks.js +541 -605
  16. package/dist/esm/diagram/board-paint.js +594 -0
  17. package/dist/esm/diagram/board-route.js +60 -0
  18. package/dist/esm/diagram/c4.js +75 -35
  19. package/dist/esm/diagram/class.js +3 -2
  20. package/dist/esm/diagram/cynefin.js +55 -9
  21. package/dist/esm/diagram/eventmodeling.js +4 -2
  22. package/dist/esm/diagram/gantt.js +37 -15
  23. package/dist/esm/diagram/gitgraph.js +26 -5
  24. package/dist/esm/diagram/graph-layout.js +39 -2
  25. package/dist/esm/diagram/graph-route.js +296 -38
  26. package/dist/esm/diagram/info.js +32 -0
  27. package/dist/esm/diagram/journey.js +5 -5
  28. package/dist/esm/diagram/kanban.js +3 -3
  29. package/dist/esm/diagram/layers.js +9 -7
  30. package/dist/esm/diagram/mindmap.js +5 -1
  31. package/dist/esm/diagram/numeric-composition.js +24 -4
  32. package/dist/esm/diagram/numeric-model.js +1 -1
  33. package/dist/esm/diagram/numeric-radar.js +25 -7
  34. package/dist/esm/diagram/numeric-sankey.js +4 -3
  35. package/dist/esm/diagram/numeric-xy.js +12 -2
  36. package/dist/esm/diagram/packet.js +4 -4
  37. package/dist/esm/diagram/quadrant.js +12 -5
  38. package/dist/esm/diagram/railroad-parse.js +20 -10
  39. package/dist/esm/diagram/railroad.js +1 -1
  40. package/dist/esm/diagram/registry.js +46 -8
  41. package/dist/esm/diagram/sequence.js +43 -6
  42. package/dist/esm/diagram/swimlane.js +2 -2
  43. package/dist/esm/diagram/time.js +3 -3
  44. package/dist/esm/diagram/timeline.js +5 -5
  45. package/dist/esm/diagram/treeview.js +5 -3
  46. package/dist/esm/diagram/venn.js +35 -15
  47. package/dist/esm/diagram/wardley.js +61 -26
  48. package/dist/esm/diagram/zenuml.js +338 -0
  49. package/dist/esm/index.d.ts +3 -1
  50. package/dist/esm/mermaid.d.ts +1 -1
  51. package/dist/esm/mermaid.js +2 -1
  52. package/dist/esm/node.js +8 -2
  53. package/dist/esm/src/families.js +6 -1
  54. package/dist/units/chart/composition.js +1 -1
  55. package/dist/units/chart/maps.js +1 -1
  56. package/dist/units/chart/mindmap.js +1 -1
  57. package/dist/units/chart/multivariate.js +1 -1
  58. package/dist/units/chart/relations.js +1 -1
  59. package/dist/units/chart/spec.js +1 -1
  60. package/dist/units/core/context.js +1 -1
  61. package/dist/units/core/scene.js +1 -1
  62. package/dist/units/core/text.js +1 -1
  63. package/dist/units/diagram/block.js +2 -2
  64. package/dist/units/diagram/blocks.js +2 -2
  65. package/dist/units/diagram/board-paint.js +1 -0
  66. package/dist/units/diagram/board-route.js +1 -0
  67. package/dist/units/diagram/c4.js +1 -1
  68. package/dist/units/diagram/class.js +2 -2
  69. package/dist/units/diagram/cynefin.js +2 -2
  70. package/dist/units/diagram/eventmodeling.js +1 -1
  71. package/dist/units/diagram/gantt.js +3 -3
  72. package/dist/units/diagram/gitgraph.js +2 -1
  73. package/dist/units/diagram/graph-layout.js +1 -1
  74. package/dist/units/diagram/graph-route.js +1 -1
  75. package/dist/units/diagram/info.js +2 -0
  76. package/dist/units/diagram/journey.js +3 -3
  77. package/dist/units/diagram/kanban.js +1 -1
  78. package/dist/units/diagram/layers.js +1 -1
  79. package/dist/units/diagram/mindmap.js +1 -1
  80. package/dist/units/diagram/numeric-composition.js +1 -1
  81. package/dist/units/diagram/numeric-model.js +1 -1
  82. package/dist/units/diagram/numeric-radar.js +2 -2
  83. package/dist/units/diagram/numeric-sankey.js +1 -1
  84. package/dist/units/diagram/numeric-xy.js +1 -1
  85. package/dist/units/diagram/packet.js +1 -1
  86. package/dist/units/diagram/quadrant.js +1 -1
  87. package/dist/units/diagram/railroad-parse.js +2 -2
  88. package/dist/units/diagram/railroad.js +1 -1
  89. package/dist/units/diagram/registry.js +2 -2
  90. package/dist/units/diagram/sequence.js +1 -1
  91. package/dist/units/diagram/swimlane.js +2 -2
  92. package/dist/units/diagram/time.js +1 -1
  93. package/dist/units/diagram/timeline.js +1 -1
  94. package/dist/units/diagram/treeview.js +1 -1
  95. package/dist/units/diagram/venn.js +1 -1
  96. package/dist/units/diagram/wardley.js +4 -4
  97. package/dist/units/diagram/zenuml.js +2 -0
  98. package/dist/units.json +79 -51
  99. package/package.json +1 -1
  100. package/dist/esm/diagram/relations.js +0 -966
  101. package/dist/units/diagram/relations.js +0 -3
package/CHANGELOG.md CHANGED
@@ -1,5 +1,40 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.0
4
+
5
+ This release adds an opt-in compact embedding mode, one-page overview boards, native ZenUML rendering and clearer diagnostics. Apart from boards, frameless titles and the layout fixes listed below, diagrams render as in 0.1.1.
6
+
7
+ ### Compact embedding
8
+
9
+ - `diagram()` and the Mermaid facade accept opt-in `compact: true` for diagrams placed inline with text. The layout is capped at 720px, the SVG is cropped to the drawing and left-aligned instead of centered, and text uses 12–14px, so output is the same for every host width of 720px or more.
10
+ - Structure diagrams keep their natural size instead of spreading to fill the host width. Mermaid charts (pie, XY, quadrant, radar, Sankey, treemap, Venn, Gantt, Wardley, Cynefin) are sized from their data; a single-leaf treemap is a small tile.
11
+ - Without an outer frame (`frame: false`), a compact diagram shows its title once, as a left-aligned heading above the drawing.
12
+ - Without a frame and without `compact`, the host shows the title. Every diagram returns it as `scene.heading` and leaves it out of the drawing; before, titled Gantt, timeline, journey, packet, Git, quadrant, pie, XY and radar diagrams also drew it, so pages that captioned the figure showed it twice. Axis names on Mermaid XY charts stay in the drawing.
13
+
14
+ ### Boards
15
+
16
+ - Native `blocks` draws one-page overview boards. New `card` (a title plus description lines), `note`, `legend` and `grid N` lines join `row`, `col` and `box`. Braces at the end of a `box` or `card` line take a style word (`accent`, `new`, `info`, `ok`, `warn`, `danger`, `ext`), `db`, a `#01` badge, an `@id` reference or a `"tag"`. Relations `->`, `=>` (main flow) and `~>` (dashed) connect groups and cards by `@id` or exact title.
17
+ - Limits rise to 8 nesting levels, 400 groups and cards, 1,000 capability items and 200 relations. Larger boards still render, scroll inside the figure and warn once with `LARGE_DIAGRAM`.
18
+ - Breaking for `blocks` sources: an indented item line that starts with `card `, `note ` or `grid N`, or is exactly `legend`, is now a structure line. Groups are neutral dashed frames instead of cycling the series colors; plain cards and capability items are borderless tiles; styled cards are outlined in the style's theme color.
19
+ - Mermaid `block` and native `blocks` share one router. Relations run orthogonally around cards, group borders and titles, and leave each side through ports ordered by destination. Gaps widen to fit relations and labels, but rows, columns and spans stay as written. Mermaid `block` groups are dashed frames with the title at the top left.
20
+ - Styles used together on one board stay distinguishable in every built-in theme. `accent` follows the chart accent (`tones[1]`); if the board also uses a status color too close to it, `accent` is drawn in ink.
21
+
22
+ ### Mermaid compatibility
23
+
24
+ - Render the ZenUML examples from Mermaid 12.3.0 as native KChart sequence diagrams, including participant annotations, aliases, nested calls and activations, replies, creation, comments, and fragments. No runtime plugin is required.
25
+ - Mermaid `radar-beta` supports 1–24 axes with measured label spacing and hints for degenerate or scrolling charts. Native radar remains limited to 3–6 dimensions. Mermaid `info` displays the current KChart package version.
26
+ - Header near misses suggest the supported keyword (for example `eventmodeling` for `eventmodeling-beta`), and Gantt reports tasks accidentally combined on one line.
27
+ - Block, railroad, Wardley, and ZenUML diagnostics give localized, specific fixes, including examples of valid syntax.
28
+
29
+ ### Layout fixes
30
+
31
+ - Flowcharts with subgraphs stack their stages on a shared axis. Edges leave and enter nodes without hooking around the endpoint, with fewer jogs and crossings.
32
+ - Class member text keeps clear of compartment dividers. C4 relationship captions stay off boundary borders, and a caption moved aside never has a leader line crossing a card or title.
33
+ - Git commit captions prefer breaking at spaces and punctuation. Bilateral mindmaps move branches between sides only when that strictly improves the balance.
34
+ - Sankey labels lose their halo, and CJK quadrant y-axis labels stand upright. The fallback text measurer counts fullwidth forms as fullwidth glyphs.
35
+ - A map given by name alone (`"map": "world"`) is rejected with the accepted shapes in the message: `{"asset": "world"}`, `{"asset": "us-states"}` or an external GeoJSON with `idProperty`.
36
+ - A geo-scatter map without a value field lists its places by name directly below the map, instead of leaving room for a size legend and marking every place "no value".
37
+
3
38
  ## 0.1.1
4
39
 
5
40
  - Center the title and payload together both horizontally and vertically inside Event Modeling frames. Keep the payload rows left-aligned within that block.
package/README.md CHANGED
@@ -6,7 +6,7 @@ KChart renders declarative charts and diagrams to deterministic SVG without a DO
6
6
 
7
7
  ## Mermaid compatibility
8
8
 
9
- All 525 core examples accepted by Mermaid 12.3.0 in the [conformance corpus](https://github.com/fengwk/html-view-skill/tree/main/packages/kchart/tests/conformance) render at both 800 px and 360 px without error diagnostics and pass the geometry checks. KChart uses its own layout and theme: supported style colors map by hue to theme status colors; unsupported presentation is not reproduced. Safe links are kept, but callbacks are not executed. ZenUML is an external Mermaid plugin and is not supported; the legacy `zenuml` reader only handles simple call diagrams.
9
+ All 525 core examples accepted by Mermaid 12.3.0 in the [conformance corpus](https://github.com/fengwk/html-view-skill/tree/main/packages/kchart/tests/conformance) render at both 800 px and 360 px without error diagnostics and pass the geometry checks. KChart uses its own layout and theme: supported style colors map by hue to theme status colors; unsupported presentation is not reproduced. Safe links are kept, but callbacks are not executed. ZenUML needs an external plugin in Mermaid; KChart parses it natively and draws it as a sequence diagram, covering all 16 ZenUML examples in the Mermaid 12.3.0 documentation.
10
10
 
11
11
  ## Browser and async Node API
12
12
 
@@ -23,12 +23,41 @@ const bars = await render({
23
23
 
24
24
  `render(spec, options?)` and `diagram(source, options?)` resolve to `{ svg, scene, diagnostics }`. For invalid input or a layout that cannot be rendered, `svg` and `scene` are `null`; unexpected failures reject. Each diagram diagnostic has `severity`: an `error` blocks rendering, while a `warning` (for example, a skipped callback or a suggestion to split a large diagram) accompanies a rendered SVG. `check(source, { syntax, lang }?)` resolves to the parse/validation diagnostics, warnings included, without laying out the diagram. The diagram syntax defaults to `mermaid`; use `layers`, `blocks`, or `swimlane` for native diagrams. `catalog` and `diagramTypes` expose the supported types and diagram aliases synchronously.
25
25
 
26
- Render options include `width`, `lang`, `theme`, `media`, `frame`, `prefix`, and `measure(text, size, weight, fontFamily)`. Set `frame: false` if your host already supplies a figure frame. Give each inline SVG a unique `prefix`; allow horizontal scrolling if a diagram needs more room than the requested width.
26
+ Render options include `width`, `lang`, `theme`, `media`, `frame`, `prefix`, and `measure(text, size, weight, fontFamily)`. Set `frame: false` if your host already supplies a figure frame. The host then shows the title: a chart's comes from its spec (`title`, `subtitle`), and a diagram returns its title as `scene.heading` without drawing it (compact embedding, below, draws it once instead). Give each inline SVG a unique `prefix`; allow horizontal scrolling if a diagram needs more room than the requested width.
27
+
28
+ For embedding, set `compact: true` in `diagram()` (async or sync) or in the Mermaid facade’s `render()` options. It caps layout width at 720px, crops the scene to its visible content instead of centering it, and uses 12–14px text. With `frame: false`, KChart omits the outer frame and shows any diagram title once above the drawing, left-aligned and wrapped to the layout width. The default is `compact: false`.
27
29
 
28
30
  If `lang` is omitted, diagrams infer English or Chinese from the source: English when there are at least twice as many English words as CJK characters and at least one English word; otherwise Chinese. Set `lang` explicitly to override this.
29
31
 
30
32
  A production Vite build splits chart and diagram families at dynamic imports. Make the Markdown component itself a dynamic import (for example with `React.lazy`) to defer the facade as well. Shared dependencies can be reused between families. For a map chart, only the requested built-in map (`world` or `us-states`) is loaded; `options.assets` can supply your own map data instead. The renderer needs no network service at runtime; serve the JavaScript chunks and map assets locally for offline use. In a hosted browser build on-demand imports may still load chunks from your own host.
31
33
 
34
+ ## Boards
35
+
36
+ Native `blocks` draws a one-page overview board: dashed groups (`box`) holding cards, notes and a legend, laid out with `row`, `col` and `grid N`. Each line indented under a `card` is one description line. Braces at the end of a `box` or `card` line add a style word (`accent`, `new`, `info`, `ok`, `warn`, `danger`, `ext`), a `#01` badge, an `@id` reference or a `"tag"`. Relations `->`, `=>` (main flow) and `~>` (dashed) connect groups and cards by `@id` or exact title.
37
+
38
+ ```js
39
+ const board = await diagram(`row
40
+ box Inputs
41
+ card Sessions
42
+ Every repository
43
+ box Weekly review {accent}
44
+ card Collect {accent #01}
45
+ Run the metrics
46
+ card Diagnose {accent #02}
47
+ Pick a fix
48
+ col
49
+ card Checks {ok}
50
+ legend
51
+ accent: Review step
52
+ ok: Lasting fix
53
+ =>: Main flow
54
+ Sessions => Collect
55
+ Collect => Diagnose
56
+ Diagnose -> Checks: ships`, { syntax: 'blocks', width: 720 });
57
+ ```
58
+
59
+ Relations run orthogonally around cards, group borders and titles; gaps widen to fit them, but rows, columns and spans stay as written. Mermaid `block` diagrams use the same router and dashed group frames. Colors come from the theme: plain cards are borderless tiles, styled cards are outlined in the style color, and the styles used together on one board stay distinguishable in every built-in theme. See the [blocks reference (Chinese)](https://github.com/fengwk/html-view-skill/blob/main/skills/html-view/references/diagrams/architecture.md#blocks) for every option and limit.
60
+
32
61
  ## Synchronous Node API
33
62
 
34
63
  ```js
package/README.zh-CN.md CHANGED
@@ -6,7 +6,7 @@ KChart 将声明式图表和结构图渲染为确定性的 SVG,不依赖 DOM
6
6
 
7
7
  ## Mermaid 兼容性
8
8
 
9
- [兼容性语料](https://github.com/fengwk/html-view-skill/tree/main/packages/kchart/tests/conformance)中 Mermaid 12.3.0 接受的 525 个核心示例,均能在 800 px 和 360 px 下无错误诊断地渲染,并通过图形几何检查。KChart 使用自己的布局与主题:可识别的样式颜色按色相映射为主题状态色,不复刻不支持的外观。安全链接会保留,回调不会执行。ZenUML 是 Mermaid 外部插件,KChart 不支持该插件;仅保留 `zenuml` 简单调用图的旧版读法。
9
+ [兼容性语料](https://github.com/fengwk/html-view-skill/tree/main/packages/kchart/tests/conformance)中 Mermaid 12.3.0 接受的 525 个核心示例,均能在 800 px 和 360 px 下无错误诊断地渲染,并通过图形几何检查。KChart 使用自己的布局与主题:可识别的样式颜色按色相映射为主题状态色,不复刻不支持的外观。安全链接会保留,回调不会执行。ZenUML 在 Mermaid 中需要外部插件;KChart 自己解析并把它画成时序图,Mermaid 12.3.0 文档中的 16 个 ZenUML 示例全部可以渲染。
10
10
 
11
11
  ## 浏览器和 Node 异步 API
12
12
 
@@ -23,12 +23,41 @@ const bars = await render({
23
23
 
24
24
  `render(spec, options?)` 和 `diagram(source, options?)` 返回 Promise,结果为 `{ svg, scene, diagnostics }`。输入无效或无法布局时,`svg` 和 `scene` 均为 `null`;意外错误会拒绝 Promise。每条结构图诊断带 `severity`:`error` 阻止渲染;`warning` 会随 SVG 一起返回,例如跳过回调或建议拆分大图。`check(source, { syntax, lang }?)` 仅解析和校验,不执行布局,异步返回含警告在内的诊断数组。结构图默认使用 `mermaid` 语法,原生结构图使用 `layers`、`blocks` 或 `swimlane`。`catalog` 和 `diagramTypes` 可同步查询支持的图型及结构图别名。
25
25
 
26
- 渲染选项包括 `width`、`lang`、`theme`、`media`、`frame`、`prefix` 和 `measure(text, size, weight, fontFamily)`。宿主已有图框时可设置 `frame: false`。每个内联 SVG 应使用不同的 `prefix`;结构图可能宽于请求值,建议让容器可以横向滚动。
26
+ 渲染选项包括 `width`、`lang`、`theme`、`media`、`frame`、`prefix` 和 `measure(text, size, weight, fontFamily)`。宿主已有图框时可设置 `frame: false`,此时题名由宿主显示:数据图取规格中的 `title`、`subtitle`;结构图把题名放在 `scene.heading` 返回,图内不再绘制(下文的 compact 嵌入模式除外,会在图形上方画一次)。每个内联 SVG 应使用不同的 `prefix`;结构图可能宽于请求值,建议让容器可以横向滚动。
27
+
28
+ 嵌入页面时,可在异步或同步 `diagram()`、或 Mermaid 适配器的 `render()` 中传入 `compact: true`。布局宽度上限为 720px,画布贴合可见内容、不再居中,文字使用 12–14px。同时设置 `frame: false` 时,不绘制外层图框;有标题的图只在图形上方显示一次标题,左对齐并按布局宽度换行。`compact` 默认关闭。
27
29
 
28
30
  不传 `lang` 时,结构图会根据源码推断语言:英文词至少有一个,且数量不少于中日韩字符的两倍时用英文,否则用中文。显式指定 `lang` 可覆盖推断结果。
29
31
 
30
32
  在 Vite 生产构建中,数据图和结构图的各个族通过动态导入拆分。如果也要延迟加载适配器,请动态导入 Markdown 组件(例如使用 `React.lazy`)。不同族可复用公共依赖。地图只在地图图表需要时加载相应的内置数据(`world` 或 `us-states`),也可通过 `options.assets` 注入自有地图。渲染不依赖在线服务;将 JavaScript 分块和地图资源放在本地即可离线使用。浏览器部署时,动态导入仍可能从宿主加载分块。
31
33
 
34
+ ## 总览图
35
+
36
+ 原生 `blocks` 用于画一页总览图:虚线分组(`box`)里放卡片、说明文字和图例,用 `row`、`col`、`grid N` 排布。`card` 下每个缩进行是一行说明。`box` 或 `card` 行尾的花括号可加样式词(`accent`、`new`、`info`、`ok`、`warn`、`danger`、`ext`)、`#01` 徽章、`@id` 引用名或 `"标签"`。关系 `->`、`=>`(主流程)和 `~>`(虚线)按 `@id` 或完整标题连接分组与卡片。
37
+
38
+ ```js
39
+ const board = await diagram(`row
40
+ box 输入
41
+ card 会话记录
42
+ 所有仓库
43
+ box 每周复盘 {accent}
44
+ card 收集数据 {accent #01}
45
+ 跑指标
46
+ card 诊断 {accent #02}
47
+ 选补丁
48
+ col
49
+ card 前置检查 {ok}
50
+ legend
51
+ accent: 复盘步骤
52
+ ok: 沉淀资产
53
+ =>: 主流程
54
+ 会话记录 => 收集数据
55
+ 收集数据 => 诊断
56
+ 诊断 -> 前置检查: 上线`, { syntax: 'blocks', width: 720 });
57
+ ```
58
+
59
+ 关系走横平竖直的路径,绕开卡片、分组边框和标题;间隙会自动加宽,但行、列和跨列保持原样。Mermaid `block` 使用同一套走线和虚线分组框。颜色由主题决定:普通卡片是无边框底块,带样式的卡片用样式色描边,同一张图里一起使用的样式在每套内置主题下都能区分。全部写法和上限见 [blocks 参考](https://github.com/fengwk/html-view-skill/blob/main/skills/html-view/references/diagrams/architecture.md#blocks)。
60
+
32
61
  ## Node 同步 API
33
62
 
34
63
  ```js
@@ -14,6 +14,7 @@ var loadFamily = {
14
14
  "diagram/er": () => import("../diagram/er.js"),
15
15
  "diagram/agentflow": () => import("../diagram/agentflow.js"),
16
16
  "diagram/wardley": () => import("../diagram/wardley.js"),
17
+ "diagram/info": () => import("../diagram/info.js"),
17
18
  "diagram/eventmodeling": () => import("../diagram/eventmodeling.js"),
18
19
  "diagram/layers": () => import("../diagram/layers.js"),
19
20
  "diagram/blocks": () => import("../diagram/blocks.js"),
@@ -32,7 +33,7 @@ var loadFamily = {
32
33
  "diagram/quadrant": () => import("../diagram/quadrant.js"),
33
34
  "diagram/class": () => import("../diagram/class.js"),
34
35
  "diagram/requirement": () => import("../diagram/requirement.js"),
35
- "diagram/relations": () => import("../diagram/relations.js"),
36
+ "diagram/zenuml": () => import("../diagram/zenuml.js"),
36
37
  "diagram/architecture": () => import("../diagram/architecture.js"),
37
38
  "diagram/block": () => import("../diagram/block.js"),
38
39
  "diagram/numeric-composition": () => import("../diagram/numeric-composition.js"),
@@ -96,13 +96,14 @@ function pieLayout(spec, ctx, isDonut = false) {
96
96
  color: ctx.color(`tone${i % 6 + 1}`),
97
97
  meta: pointMeta(row, String(row[table.categoryField]), values[i], spec.chart)
98
98
  }));
99
- const sideLegend = width > 560;
100
- const legendWidth = sideLegend ? Math.min(320, Math.max(180, width * .34)) : Math.min(width - 32, 270);
99
+ const compact = spec[compositionPresentation]?.compact === true;
100
+ const sideLegend = width > 560 || compact && rows.length >= 4;
101
+ const legendWidth = sideLegend ? compact ? Math.max(154, width * .42) : Math.min(320, Math.max(180, width * .34)) : Math.min(width - 32, 270);
101
102
  const chartSpan = sideLegend ? Math.min(width - legendWidth - 36, 460) : width;
102
103
  const groupWidth = sideLegend ? chartSpan + 28 + legendWidth : width;
103
104
  const groupX = sideLegend ? (width - groupWidth) / 2 : 0;
104
105
  const cx = sideLegend ? groupX + chartSpan / 2 : width / 2;
105
- const r = width <= 360 ? Math.min(112, width * .275) : Math.min(sideLegend ? 168 : 112, Math.max(60, chartSpan * .32));
106
+ const r = compact ? Math.min(92, Math.max(60, chartSpan * (sideLegend ? .44 : .26))) : width <= 360 ? Math.min(112, width * .275) : Math.min(sideLegend ? 168 : 112, Math.max(60, chartSpan * .32));
106
107
  const cy = r + 36, inner = isDonut ? r * .58 : 0;
107
108
  const labelRadius = r * (spec[compositionPresentation]?.labelRadius ?? .72);
108
109
  const children = [], sectors = [], sliceLabels = [], ticksVariant = isDonut && spec.variant === "ticks";
@@ -532,7 +533,7 @@ function fallbackLegend(children, entries, x, y, width, ctx, kind, format = (val
532
533
  function treemap(spec, ctx) {
533
534
  const root = spec.data, tree = treeNodes(root), leaves = tree.filter((x) => !x.children.length);
534
535
  const diagram = spec[compositionPresentation];
535
- let width = Math.min(ctx.width - 48, 752), mapHeight = 242, needWidth = false, needHeight = false;
536
+ let width = Math.min(ctx.width - 48, 752), mapHeight = diagram?.compact ? leaves.length === 1 ? 120 : Math.min(280, 190 + leaves.length * 8) : 242, needWidth = false, needHeight = false;
536
537
  const tones = new Map(leaves.map((leaf, i) => [leaf, `tone${i % 6 + 1}`])), children = [], fallback = [];
537
538
  const statusOf = (entry) => ctx.design[entry.node[compositionPresentation]?.status];
538
539
  const colorOf = (leaf) => statusOf(leaf) || ctx.color(tones.get(leaf));
@@ -699,7 +700,8 @@ function treemap(spec, ctx) {
699
700
  leading: 18,
700
701
  fill: ctx.color("fg")
701
702
  }));
702
- place(tree[0], 24, top, width, mapHeight, 0);
703
+ const inset = diagram?.compact && leaves.length === 1 ? .02 : 0;
704
+ place(tree[0], 24 + width * inset, top + mapHeight * inset, width * (1 - inset * 2), mapHeight * (1 - inset * 2), 0);
703
705
  if (!needWidth && !needHeight) break;
704
706
  if (attempt === 6) ctx.fit("矩形树图的最小分块无法容纳编号", "拆分图表或缩小权重差距");
705
707
  if (needWidth) width *= 1.5;
@@ -128,9 +128,10 @@ function coordinateBounds(features, rows, enc, inset, projection) {
128
128
  };
129
129
  }
130
130
  var INDEX_TOP = 98;
131
+ var INDEX_TOP_BARE = 28;
131
132
  var INDEX_ROW = 16;
132
133
  var INDEX_CAP = 24;
133
- function makePlot(spec, ctx, features, rows = []) {
134
+ function makePlot(spec, ctx, features, rows = [], indexTop = INDEX_TOP) {
134
135
  const width = ctx.width;
135
136
  const inset = spec.data.map.asset === "us-states";
136
137
  const projection = ctx.assets?.projection || "equirectangular";
@@ -138,7 +139,7 @@ function makePlot(spec, ctx, features, rows = []) {
138
139
  const ll = project(bounds.west, bounds.south, projection), ur = project(bounds.east, bounds.north, projection);
139
140
  const margin = width <= 360 ? 12 : 32;
140
141
  const indexRows = Math.min(rows.length, INDEX_CAP);
141
- const bottom = indexRows ? 126 + Math.ceil(indexRows / (width < 420 ? 1 : 2)) * INDEX_ROW : 112;
142
+ const bottom = indexRows ? indexTop + 28 + Math.ceil(indexRows / (width < 420 ? 1 : 2)) * INDEX_ROW : 112;
142
143
  const availableW = width - margin * 2;
143
144
  const budgetH = Math.max(180, Math.round(width * .64) - (indexRows ? 120 : 80));
144
145
  const scale = Math.min(availableW / Math.max(1e-9, ur[0] - ll[0]), budgetH / Math.max(1e-9, ur[1] - ll[1]));
@@ -418,7 +419,8 @@ function choropleth(spec, ctx) {
418
419
  }
419
420
  function scatter(spec, ctx) {
420
421
  const { features } = featuresFor(spec, ctx), rows = spec.data.rows, enc = spec.encode;
421
- const layout = makePlot(spec, ctx, features, rows), c = palette(ctx), { children, projectPoint } = layout;
422
+ const indexTop = enc.value ? INDEX_TOP : INDEX_TOP_BARE;
423
+ const layout = makePlot(spec, ctx, features, rows, indexTop), c = palette(ctx), { children, projectPoint } = layout;
422
424
  for (const feature of features) {
423
425
  const id = feature.properties.id || null;
424
426
  const point = layout.inset && ["US-AK", "US-HI"].includes(id) ? (lon, lat) => insetPoint(layout, id, lon, lat) : projectPoint;
@@ -483,7 +485,7 @@ function scatter(spec, ctx) {
483
485
  });
484
486
  });
485
487
  if (valueField) bottomLegend(children, ctx, layout, min, max, valueField, true);
486
- const indexY = layout.height - layout.bottom + INDEX_TOP, localized = ctx.lang.startsWith("en");
488
+ const indexY = layout.height - layout.bottom + indexTop, localized = ctx.lang.startsWith("en");
487
489
  children.push(ctx.text(24, indexY, localized ? "Locations" : "地点索引", {
488
490
  size: 12,
489
491
  weight: 600,
@@ -500,8 +502,8 @@ function scatter(spec, ctx) {
500
502
  const x = 24 + column * ((layout.width - 48) / columns);
501
503
  const y = columnHeights[column];
502
504
  const name = item.label || item.id || `#${item.index + 1}`;
503
- const readout = item.zero ? localized ? `${formattedValue(ctx, 0, valueField)} (no marker)` : `${formattedValue(ctx, 0, valueField)}(无点)` : item.value == null ? localized ? "no value" : "无数值" : formattedValue(ctx, item.value, valueField);
504
- const lines = ctx.wrap(`${name} · ${readout}`, columnWidth, 12, 400);
505
+ const readout = !valueField ? "" : item.zero ? localized ? `${formattedValue(ctx, 0, valueField)} (no marker)` : `${formattedValue(ctx, 0, valueField)}(无点)` : item.value == null ? localized ? "no value" : "无数值" : formattedValue(ctx, item.value, valueField);
506
+ const lines = ctx.wrap(readout ? `${name} · ${readout}` : name, columnWidth, 12, 400);
505
507
  lines.forEach((line, lineIndex) => children.push(ctx.text(x, y + lineIndex * INDEX_ROW, line, {
506
508
  size: 12,
507
509
  fill: c.ink,
@@ -527,7 +529,7 @@ function scatter(spec, ctx) {
527
529
  }));
528
530
  indexBottom += 20;
529
531
  }
530
- const reservedIndex = layout.bottom - INDEX_TOP;
532
+ const reservedIndex = layout.bottom - indexTop;
531
533
  const usedIndex = indexBottom - indexY + 16;
532
534
  if (usedIndex > reservedIndex) layout.height += usedIndex - reservedIndex;
533
535
  if (outside.length) {
@@ -229,11 +229,25 @@ function arrange(spec, ctx, mode, { cap, gap }) {
229
229
  for (let d = 0; d < maxDepth; d++) col[d + 1] = col[d] + levelW[d] + gap;
230
230
  stack(root, 0, (n) => mode === "left" ? -col[n.depth] - n.w : col[n.depth]);
231
231
  } else if (mode === "bilateral") {
232
- const sides = [[], []], mass = [0, 0];
233
- for (const child of root.children) {
234
- const side = mass[0] <= mass[1] ? 0 : 1;
235
- sides[side].push(child);
236
- mass[side] += leaves(child);
232
+ const partition = (branches) => {
233
+ const sides = [[], []], mass = [0, 0];
234
+ for (const child of branches) {
235
+ const side = mass[0] <= mass[1] ? 0 : 1;
236
+ sides[side].push(child);
237
+ mass[side] += leaves(child);
238
+ }
239
+ return {
240
+ sides,
241
+ mass
242
+ };
243
+ };
244
+ const original = partition(root.children);
245
+ const ranked = partition([...root.children].sort((a, b) => leaves(b) - leaves(a)));
246
+ const imbalance = ({ mass }) => Math.abs(mass[0] - mass[1]);
247
+ const { sides, mass } = imbalance(ranked) < imbalance(original) ? ranked : original;
248
+ for (let i = 0; i < sides.length; i++) {
249
+ const members = new Set(sides[i]);
250
+ sides[i] = root.children.filter((child) => members.has(child));
237
251
  }
238
252
  const subtree = (n) => [n, ...n.children.flatMap(subtree)];
239
253
  place(root, 0, -root.h / 2);
@@ -4,10 +4,12 @@ import { columnHeaders } from "../core/geometry.js";
4
4
  import { contrast, pushContrast } from "../core/color.js";
5
5
  // src/chart/multivariate.js
6
6
  var multivariate_exports = /* @__PURE__ */ __exportAll({
7
+ compactNumeric: () => compactNumeric,
7
8
  diagramCombo: () => diagramCombo,
8
9
  install: () => install
9
10
  });
10
11
  var diagramCombo = Symbol("diagram combo");
12
+ var compactNumeric = Symbol("compact numeric geometry");
11
13
  var finite = Number.isFinite;
12
14
  var number = (ctx, field, values, zero = false) => {
13
15
  const result = ctx.ticks(values.filter(finite), field, { zero });
@@ -269,7 +271,7 @@ var chart = (spec, ctx) => {
269
271
  const leftGutter = Math.max(36, ...(axisTicks.left?.labels || ["0"]).map((label) => ctx.measure(label, 12))) + 16;
270
272
  const rightGutter = Math.max(28, ...(axisTicks.right?.labels || [""]).map((label) => ctx.measure(label, 12))) + 16;
271
273
  const annotationRows = (spec.annotations || []).filter((annotation) => annotation.label || annotation.text).length;
272
- const p = plot(36 + annotationRows * 16, 302, leftGutter, width - rightGutter);
274
+ const p = plot(36 + annotationRows * 16, spec[compactNumeric] ? 252 : 302, leftGutter, width - rightGutter);
273
275
  reserveEdgeCategories(cats, p);
274
276
  const yFor = (field, v) => p.y + p.h - (v - scales[field].min) / (scales[field].max - scales[field].min || 1) * p.h;
275
277
  const y0 = (field) => yFor(field, Math.max(scales[field].min, Math.min(scales[field].max, 0)));
@@ -896,14 +898,46 @@ var chart = (spec, ctx) => {
896
898
  range: rangeText(field, domains[i])
897
899
  }));
898
900
  const chord = 2 * Math.sin(Math.PI / dimensions.length);
899
- const labelRoom = dimensions.length >= 6 ? Math.max(48, Math.min(96, Math.ceil(width * chord * .42))) : Math.max(84, Math.min(140, Math.ceil(Math.max(72, width * .2) * chord)));
901
+ const dense = dimensions.length > 6;
902
+ const labelRoom = dense ? 96 : dimensions.length === 6 ? Math.max(48, Math.min(96, Math.ceil(width * chord * .42))) : Math.max(84, Math.min(140, Math.ceil(Math.max(72, width * .2) * chord)));
900
903
  const wrapped = axisLabels.map((item) => ({
901
904
  name: ctx.wrap(item.name, labelRoom, 12, 600),
902
905
  range: ctx.wrap(item.range, labelRoom, 12, 400)
903
906
  }));
904
907
  const textWidth = Math.max(0, ...wrapped.flatMap((item) => [...item.name.map((line) => ctx.measure(line, 12, 600)), ...item.range.map((line) => ctx.measure(line, 12, 400))]));
905
908
  const labelDepth = Math.max(...wrapped.map((item) => (item.name.length + item.range.length) * 16));
906
- const radius = Math.min(180, Math.max(72, (width - textWidth * 2 - 24) / 2));
909
+ const positionLabel = (angle, i, radius) => {
910
+ const cos = Math.cos(angle), sin = Math.sin(angle);
911
+ const horizontal = Math.abs(cos) >= Math.abs(sin);
912
+ const anchor = horizontal ? cos < 0 ? "end" : "start" : "middle";
913
+ const tx = horizontal ? cos * (radius + 10) : cos * radius;
914
+ const ty = horizontal ? sin * radius : sin * (radius + 10);
915
+ const block = wrapped[i].name.length + wrapped[i].range.length;
916
+ return {
917
+ anchor,
918
+ tx,
919
+ firstY: horizontal ? ty - (block - 1) * 8 : sin < 0 ? ty - block * 16 - 4 : ty + 16,
920
+ block
921
+ };
922
+ };
923
+ let radius = Math.min(spec[compactNumeric] ? 132 : 180, Math.max(72, (width - textWidth * 2 - 24) / 2));
924
+ if (dense) {
925
+ const widths = wrapped.map((item) => Math.max(...item.name.map((line) => ctx.measure(line, 12, 600)), ...item.range.map((line) => ctx.measure(line, 12, 400))));
926
+ const labelsOverlap = () => {
927
+ const boxes = angles.map((angle, i) => {
928
+ const { anchor, tx, firstY, block } = positionLabel(angle, i, radius);
929
+ const x = tx - widths[i] * (anchor === "end" ? 1 : anchor === "middle" ? .5 : 0);
930
+ return {
931
+ l: x - 3,
932
+ r: x + widths[i] + 3,
933
+ t: firstY - 15,
934
+ b: firstY + (block - 1) * 16 + 6
935
+ };
936
+ });
937
+ return boxes.some((a, i) => boxes.slice(i + 1).some((b) => a.l < b.r && b.l < a.r && a.t < b.b && b.t < a.b));
938
+ };
939
+ while (labelsOverlap()) radius += Math.max(8, radius * .05);
940
+ }
907
941
  const cx = Math.max(width / 2, textWidth + radius + 12);
908
942
  const cy = radius + labelDepth + 24;
909
943
  const chartWidth = Math.max(width, cx + radius + textWidth + 12);
@@ -921,7 +955,9 @@ var chart = (spec, ctx) => {
921
955
  continue;
922
956
  }
923
957
  const points = angles.map((angle) => [cx + Math.cos(angle) * radius * ring / rings, cy + Math.sin(angle) * radius * ring / rings]);
924
- children.push(ctx.el("polygon", {
958
+ if (points.length === 1) children.push(ctx.circle(...points[0], 1, { fill: ctx.color("grid") }));
959
+ else if (points.length === 2) children.push(ctx.line(...points[0], ...points[1], { stroke: ctx.color("grid") }));
960
+ else children.push(ctx.el("polygon", {
925
961
  points: points.map((point) => point.join(",")).join(" "),
926
962
  fill: "none",
927
963
  stroke: ctx.color("grid")
@@ -930,19 +966,14 @@ var chart = (spec, ctx) => {
930
966
  angles.forEach((angle, i) => {
931
967
  const cos = Math.cos(angle), sin = Math.sin(angle);
932
968
  children.push(ctx.line(cx, cy, cx + cos * radius, cy + sin * radius, { stroke: ctx.color("axis") }));
933
- const horizontal = Math.abs(cos) >= Math.abs(sin);
934
- const anchor = horizontal ? cos < 0 ? "end" : "start" : "middle";
935
- const tx = horizontal ? cx + cos * (radius + 10) : cx + cos * radius;
936
- const ty = horizontal ? cy + sin * radius : cy + sin * (radius + 10);
937
- const block = wrapped[i].name.length + wrapped[i].range.length;
938
- const firstY = horizontal ? ty - (block - 1) * 8 : sin < 0 ? ty - block * 16 - 4 : ty + 16;
939
- children.push(ctx.textLines(tx, firstY, wrapped[i].name, {
969
+ const { anchor, tx, firstY } = positionLabel(angle, i, radius);
970
+ children.push(ctx.textLines(cx + tx, cy + firstY, wrapped[i].name, {
940
971
  anchor,
941
972
  size: 12,
942
973
  weight: 600,
943
974
  fill: ctx.color("fg")
944
975
  }));
945
- children.push(ctx.textLines(tx, firstY + wrapped[i].name.length * 16, wrapped[i].range, {
976
+ children.push(ctx.textLines(cx + tx, cy + firstY + wrapped[i].name.length * 16, wrapped[i].range, {
946
977
  anchor,
947
978
  size: 12,
948
979
  weight: 400,
@@ -952,7 +983,11 @@ var chart = (spec, ctx) => {
952
983
  data.forEach((row, rowIndex) => {
953
984
  const points = dimensions.map((field, i) => [cx + Math.cos(angles[i]) * radiusAt(i, row[field]), cy + Math.sin(angles[i]) * radiusAt(i, row[field])]);
954
985
  const color = ctx.color(`tone${rowIndex % 6 + 1}`);
955
- children.push(ctx.el("polygon", {
986
+ if (points.length === 2) children.push(ctx.line(...points[0], ...points[1], {
987
+ stroke: color,
988
+ "stroke-width": 2
989
+ }));
990
+ else if (points.length >= 3) children.push(ctx.el("polygon", {
956
991
  points: points.map((point) => point.join(",")).join(" "),
957
992
  fill: color,
958
993
  "fill-opacity": .14,
@@ -1226,4 +1261,4 @@ function install({ register }) {
1226
1261
  ], chart);
1227
1262
  }
1228
1263
  install({ register });
1229
- export { diagramCombo, install, multivariate_exports };
1264
+ export { compactNumeric, diagramCombo, install, multivariate_exports };
@@ -4,6 +4,7 @@ import { sizeBudget } from "./spec.js";
4
4
  // src/chart/relations.js
5
5
  var relations_exports = /* @__PURE__ */ __exportAll({
6
6
  install: () => install,
7
+ sankeyCompact: () => sankeyCompact,
7
8
  sankeyPresentation: () => sankeyPresentation
8
9
  });
9
10
  var clamp = (n, lo, hi) => Math.max(lo, Math.min(hi, n));
@@ -407,6 +408,7 @@ function orderSankeyStages(stages, grouped, edges, stageMap) {
407
408
  return best;
408
409
  }
409
410
  var sankeyPresentation = Symbol("sankey presentation");
411
+ var sankeyCompact = Symbol("diagram sankey compact");
410
412
  function sankey(spec, ctx) {
411
413
  const { nodes, edges } = spec.data;
412
414
  const budget = spec[sizeBudget] ?? {}, maxNodes = budget.nodes ?? 60, maxEdges = budget.edges ?? 120;
@@ -414,6 +416,7 @@ function sankey(spec, ctx) {
414
416
  const stageMap = nodes.every((n) => Number.isInteger(n.stage)) ? new Map(nodes.map((n) => [n.id, n.stage])) : networkStages(spec.data);
415
417
  const stages = [...new Set(nodes.map((n) => stageMap.get(n.id)))].sort((a, b) => a - b);
416
418
  const vertical = spec.layout === "down";
419
+ const compact = spec[sankeyCompact] === true;
417
420
  const nodeSize = 18;
418
421
  const labelSize = 12;
419
422
  const labelCap = vertical ? 160 : 120;
@@ -441,10 +444,13 @@ function sankey(spec, ctx) {
441
444
  const row = nodes.filter((node) => stageMap.get(node.id) === stage);
442
445
  return row.reduce((sum, node) => sum + nodeSize + wrapped.get(node.id).width + 16, 0) + Math.max(0, row.length - 1) * 6 + margin * 2;
443
446
  })) : 0;
444
- const W = vertical ? Math.max(ctx.width, verticalMinimum) : Math.max(ctx.width, horizontalMinimum);
447
+ const compactWidth = Math.min(720, Math.max(360, margin * 2 + widestLabel + stages.length * (nodeSize + lane)));
448
+ const W = vertical ? Math.max(compact ? compactWidth : ctx.width, verticalMinimum) : Math.max(compact ? compactWidth : ctx.width, horizontalMinimum);
445
449
  Math.max(1, ...stages.map((stage) => nodes.filter((node) => stageMap.get(node.id) === stage).length));
446
450
  const labelStackHeight = Math.max(0, ...stages.map((stage) => nodes.filter((node) => stageMap.get(node.id) === stage).reduce((sum, node) => sum + wrapped.get(node.id).height + 4, 0)));
447
- const H = vertical ? Math.max(460, margin * 2 + stages.length * nodeSize + Math.max(0, stages.length - 1) * (maxLabelLines * 14 + 36) + 40) : Math.max(360, margin * 2 + labelStackHeight + 40);
451
+ const compactFlowTotal = Math.max(1, ...stages.map((stage) => edges.filter((edge) => stageMap.get(edge.source) === stage).reduce((total, edge) => total + edge.value, 0)));
452
+ const compactHeight = Math.max(160, margin * 2 + labelStackHeight + 40, Math.min(300, 160 + Math.sqrt(compactFlowTotal) * 5));
453
+ const H = vertical ? Math.max(compact ? 160 : 460, margin * 2 + stages.length * nodeSize + Math.max(0, stages.length - 1) * (maxLabelLines * 14 + 36) + 40) : compact ? compactHeight : Math.max(360, margin * 2 + labelStackHeight + 40);
448
454
  const axisStart = !vertical && stages.length === 1 ? Math.max(margin, lane + 8) : margin;
449
455
  const axisEnd = vertical ? H - margin - nodeSize : W - margin - nodeSize;
450
456
  const slot = stages.length > 1 ? Math.max(minSlot, (axisEnd - axisStart) / (stages.length - 1)) : 0;
@@ -752,10 +758,12 @@ function sankey(spec, ctx) {
752
758
  anchor,
753
759
  size: labelSize,
754
760
  fill: ctx.color(i === box.totalIndex ? "muted" : "fg"),
755
- stroke: ctx.color("bg"),
756
- "stroke-width": 4,
757
- "stroke-linejoin": "round",
758
- "paint-order": "stroke",
761
+ ...spec[sankeyPresentation] ? {} : {
762
+ stroke: ctx.color("bg"),
763
+ "stroke-width": 4,
764
+ "stroke-linejoin": "round",
765
+ "paint-order": "stroke"
766
+ },
759
767
  meta: {
760
768
  kind: i === box.totalIndex ? "node-total" : "label",
761
769
  node: String(n.id)
@@ -946,4 +954,4 @@ function install({ register }) {
946
954
  register("threads", threads);
947
955
  }
948
956
  install({ register });
949
- export { install, relations_exports, sankeyPresentation };
957
+ export { install, relations_exports, sankeyCompact, sankeyPresentation };
@@ -276,7 +276,7 @@ function validate(spec) {
276
276
  const m = spec.data.map;
277
277
  const builtin = obj(m) && Object.keys(m).length === 1 && ["world", "us-states"].includes(m.asset);
278
278
  const external = obj(m) && obj(m.geojson) && m.geojson.type === "FeatureCollection" && Array.isArray(m.geojson.features) && typeof m.idProperty === "string" && Object.keys(m).every((k) => ["geojson", "idProperty"].includes(k));
279
- if (!builtin && !external) err(errors, "/data/map", "map须是world、us-states或GeoJSON FeatureCollection");
279
+ if (!builtin && !external) err(errors, "/data/map", "map须是对象:{asset:'world'}、{asset:'us-states'}或{geojson:FeatureCollection,idProperty:'地区键字段'}", "内置地图写成 \"map\": {\"asset\": \"world\"},不要只写地图名。");
280
280
  if (external) {
281
281
  const ids = /* @__PURE__ */ new Set();
282
282
  for (const [i, f] of m.geojson.features.entries()) {
@@ -552,7 +552,10 @@ function checkTable(s, c, e) {
552
552
  if (c.encodeForms.length && !c.encodeForms.some((form) => form.length === Object.keys(enc).filter((k) => k === "value" || k === "panel").length && form.every((k) => Object.hasOwn(enc, k)))) err(e, "/encode", "small-multiples须使用value[]宽表或value+panel长表");
553
553
  if (s.chart === "small-multiples" && (enc.panel ? Array.isArray(enc.value) : !Array.isArray(enc.value))) err(e, "/encode", "宽表value须为字段数组;长表value须为单个字段并配panel");
554
554
  if (Array.isArray(enc.value) && enc.value.length > 6) err(e, "/encode/value", "最多支持6个度量系列");
555
- if (["radar", "parallel"].includes(s.chart) && (enc.dimensions?.length < 3 || enc.dimensions?.length > 6)) err(e, "/encode/dimensions", "radar至少3维,parallel为3至6维");
555
+ if (["radar", "parallel"].includes(s.chart)) {
556
+ const { minDimensions = 3, maxDimensions = 6 } = s.chart === "radar" ? s[sizeBudget] ?? {} : {};
557
+ if (enc.dimensions?.length < minDimensions || enc.dimensions?.length > maxDimensions) err(e, "/encode/dimensions", `${s.chart}需要${minDimensions}至${maxDimensions}维`);
558
+ }
556
559
  if (s.chart === "radar") {
557
560
  for (const name of enc.dimensions || []) if (!fields[name]?.domain) err(e, `/fields/${name}/domain`, `${s.chart}的每个维度都必须显式声明domain`);
558
561
  }
@@ -34,7 +34,24 @@ function createContext(options = {}) {
34
34
  const palette = paletteOf(resolved);
35
35
  const fontFamily = resolved.fontFamily || "system-ui, -apple-system, BlinkMacSystemFont, \"Segoe UI\", \"Noto Sans SC\", \"Microsoft YaHei\", sans-serif";
36
36
  if (typeof fontFamily !== "string" || !fontFamily.trim()) throw new TypeError("Invalid theme font family");
37
- const measure = options.measure || fallbackMeasure;
37
+ const compact = options.compact === true;
38
+ const font = (size, weight) => !compact ? {
39
+ size,
40
+ weight
41
+ } : size === 16 && weight === 650 ? {
42
+ size: 14,
43
+ weight: 600
44
+ } : {
45
+ size: size === 14 ? 13 : Math.max(12, Math.min(14, size ?? 12)),
46
+ weight
47
+ };
48
+ const measureText = options.measure || fallbackMeasure;
49
+ const measureRendered = (value, size, weight) => measureText(value, size, weight, fontFamily);
50
+ const measureInk = options.measure ? measureRendered : (value, size, weight) => measureRendered(value, size, weight) + (String(value).match(/[mMwW@]/g)?.length || 0) * size * .38;
51
+ const measure = (value, size, weight) => {
52
+ const mapped = font(size, weight);
53
+ return measureRendered(value, mapped.size, mapped.weight);
54
+ };
38
55
  const color = (role) => {
39
56
  if (!roles.includes(role)) throw new TypeError(`Unknown color role: ${role}`);
40
57
  const value = palette[role];
@@ -42,10 +59,7 @@ function createContext(options = {}) {
42
59
  return value;
43
60
  };
44
61
  const frameTone = (value, prominent = false) => resolved.frameInk ? prominent ? resolved.fg1 : resolved.frameInk : value;
45
- const wrap = (value, maxWidth, size = 12, weight = 400, options) => wrapText(String(value ?? ""), maxWidth, {
46
- size,
47
- weight
48
- }, (text, font) => measure(text, font.size, font.weight, fontFamily), options);
62
+ const wrap = (value, maxWidth, size = 12, weight = 400, options) => wrapText(String(value ?? ""), maxWidth, font(size, weight), (text, spec) => measureRendered(text, spec.size, spec.weight), options);
49
63
  const text = (x, y, value, opts = {}) => {
50
64
  const { anchor = "start", size = 12, weight = 400, fill = color("muted"), meta, ...attrs } = opts;
51
65
  if (![
@@ -53,14 +67,15 @@ function createContext(options = {}) {
53
67
  "middle",
54
68
  "end"
55
69
  ].includes(anchor)) throw new TypeError("Invalid text anchor");
70
+ const mapped = font(size, weight);
56
71
  return {
57
72
  ...primitive("text", {
58
73
  x,
59
74
  y,
60
75
  ...attrs,
61
76
  "text-anchor": anchor,
62
- "font-size": size,
63
- "font-weight": weight,
77
+ "font-size": mapped.size,
78
+ "font-weight": mapped.weight,
64
79
  fill
65
80
  }, meta),
66
81
  text: String(value ?? "")
@@ -73,9 +88,9 @@ function createContext(options = {}) {
73
88
  const flow = (items, maxWidth, size = 12, weight = 400) => {
74
89
  const rows = [];
75
90
  let row = [], rowWidth = 0;
76
- const gap = measure(" · ", size, weight, fontFamily);
91
+ const gap = measure(" · ", size, weight);
77
92
  for (const item of items || []) {
78
- const value = String(item), itemWidth = measure(value, size, weight, fontFamily);
93
+ const value = String(item), itemWidth = measure(value, size, weight);
79
94
  if (itemWidth > maxWidth) {
80
95
  if (row.length) rows.push(row);
81
96
  row = [];
@@ -153,7 +168,11 @@ function createContext(options = {}) {
153
168
  scheme: resolved.scheme,
154
169
  design: resolved,
155
170
  assets: options.assets || null,
156
- measure: (value, size, weight) => measure(value, size, weight, fontFamily),
171
+ compact,
172
+ font,
173
+ measure,
174
+ measureRendered,
175
+ measureInk,
157
176
  el,
158
177
  shape: primitive,
159
178
  text,