| Layout | Preview | When to use it |
@@ -583,10 +586,11 @@ Branches extend horizontally from a central topic. This example uses ID prefixes
```ts
import type { GraphNode, LayoutConfig } from '@antv/g6-lite';
+import { MindmapLayout } from '@antv/layout';
const leftBranches = new Set(['A', 'C']);
const layout: LayoutConfig = {
- type: 'mindmap',
+ type: MindmapLayout,
direction: 'H',
levelGap: 100,
nodeGap: 24,
@@ -611,7 +615,9 @@ const layout: LayoutConfig = {
Each node occupies a row. Children appear below their parents and indent farther at each level. Use `indent` for horizontal spacing and `rowHeight` for vertical spacing.
```ts
-const layout: LayoutConfig = { type: 'indented', indent: 72, rowHeight: 30 };
+import { IndentedLayout } from '@antv/layout';
+
+const layout: LayoutConfig = { type: IndentedLayout, indent: 72, rowHeight: 30 };
const edge: EdgeConfig = { type: 'polyline', style: { router: 'indented', endArrow: false } };
```
@@ -629,7 +635,9 @@ const edge: EdgeConfig = { type: 'polyline', style: { router: 'indented', endArr
Use three levels for a problem, categories of causes, and individual causes. `categoryGap` spaces the categories along the spine and `categoryDistance` moves them away from it.
```ts
-const layout: LayoutConfig = { type: 'fishbone', categoryGap: 156, categoryDistance: 130, itemHStep: 54 };
+import { FishboneLayout } from '@antv/layout';
+
+const layout: LayoutConfig = { type: FishboneLayout, categoryGap: 156, categoryDistance: 130, itemHStep: 54 };
const edge: EdgeConfig = { type: 'polyline', style: { router: 'fishbone', endArrow: false } };
```
@@ -645,7 +653,7 @@ const edge: EdgeConfig = { type: 'polyline', style: { router: 'fishbone', endArr
### Layout options [#config-library-layout-fields]
-Set the layout `type` and its options in `layout`. For example, `layout: { type: 'dagre', rankdir: 'LR' }` arranges a flow from left to right.
+Set the layout `type` and its options in `layout`. For example, `layout: { type: DagreLayout, rankdir: 'LR' }` arranges a flow from left to right.
| Layout type | Example options | Effect |
| --- | --- | --- |
diff --git a/site/content/docs/en/compatibility/g6-v5-migration.mdx b/site/content/docs/en/compatibility/g6-v5-migration.mdx
index 481972c93..f99df7731 100644
--- a/site/content/docs/en/compatibility/g6-v5-migration.mdx
+++ b/site/content/docs/en/compatibility/g6-v5-migration.mdx
@@ -25,6 +25,7 @@ G6 v5 commonly uses a container ID, labelText, and drag-element; see the [offici
```ts
import { Graph } from '@antv/g6-lite';
+import { CircularLayout } from '@antv/layout';
export async function mountGraph(container: HTMLElement) {
const graph = new Graph({
@@ -34,7 +35,7 @@ export async function mountGraph(container: HTMLElement) {
edges: [{ id: 'a-b', source: 'a', target: 'b' }],
},
node: { style: { label: (node) => node.id } },
- layout: { type: 'circular', radius: 100 },
+ layout: { type: CircularLayout, radius: 100 },
behaviors: ['zoom-canvas', 'drag-canvas', 'drag-node', 'click-select'],
});
try {
diff --git a/site/content/docs/en/getting-started/quick-start.mdx b/site/content/docs/en/getting-started/quick-start.mdx
index 280035db1..8c52e97af 100644
--- a/site/content/docs/en/getting-started/quick-start.mdx
+++ b/site/content/docs/en/getting-started/quick-start.mdx
@@ -188,11 +188,11 @@ Save the HTML below as `index.html` and open it in your browser.
### Use the UMD script [#cdn-umd]
-The UMD script includes runtime dependencies and built-in layouts. Once loaded, create a graph with `G6Lite.Graph`. This minimal example draws two nodes and one edge:
+The UMD script includes runtime dependencies and built-in force-directed layouts (`force`, `force-atlas2`, `d3-force`, `fruchterman`). Once loaded, create a graph with `G6Lite.Graph`. This minimal example draws two nodes and one edge:
```html
-
+
-
-
+const layout = { type: RadialLayout, focusNode: '0', unitRadius: 68 };
```
-Registered layouts run on the main thread.
+These layout classes also run on the main thread.
## Configuration and example
@@ -61,6 +69,7 @@ Set the algorithm with `layout.type`. This example uses Dagre to arrange three s
```ts
import { Graph } from '@antv/g6-lite';
+import { DagreLayout } from '@antv/layout';
const graph = new Graph({
container: '#container',
@@ -71,7 +80,7 @@ const graph = new Graph({
{ source: 'Review', target: 'Publish' },
],
},
- layout: { type: 'dagre', rankdir: 'LR', ranksep: 80 },
+ layout: { type: DagreLayout, rankdir: 'LR', ranksep: 80 },
node: { style: { label: (node) => node.id } },
});
diff --git a/site/content/docs/en/guides/layout-radial.mdx b/site/content/docs/en/guides/layout-radial.mdx
index f45f8c34e..fa4e22922 100644
--- a/site/content/docs/en/guides/layout-radial.mdx
+++ b/site/content/docs/en/guides/layout-radial.mdx
@@ -15,18 +15,16 @@ Use it to see the direct and indirect relationships of an account, service, or d
## Basic usage
-This layout is optional. Import and register it before setting `layout.type`. For CDN usage, see [Optional layouts](/en/docs/guides/layout-overview#optional-layouts).
+This is an external layout. Import its class from `@antv/layout` and pass it as `layout.type`; no registration is required. See [Built-in and external layouts](/en/docs/guides/layout-overview#builtin-and-external-layouts).
```ts
-import { Graph, register } from '@antv/g6-lite';
-import radial from '@antv/g6-lite/layouts/radial';
-
-register('layout', 'radial', radial);
+import { Graph } from '@antv/g6-lite';
+import { RadialLayout } from '@antv/layout';
const graph = new Graph({
container,
data,
- layout: { type: 'radial' },
+ layout: { type: RadialLayout },
});
```
diff --git a/site/content/docs/en/guides/layout-random.mdx b/site/content/docs/en/guides/layout-random.mdx
index 081cb1f8e..b085d2235 100644
--- a/site/content/docs/en/guides/layout-random.mdx
+++ b/site/content/docs/en/guides/layout-random.mdx
@@ -15,18 +15,16 @@ Use it for a quick preview of graph data. Each run samples new positions.
## Basic usage
-This layout is optional. Import and register it before setting `layout.type`. For CDN usage, see [Optional layouts](/en/docs/guides/layout-overview#optional-layouts).
+This is an external layout. Import its class from `@antv/layout` and pass it as `layout.type`; no registration is required. See [Built-in and external layouts](/en/docs/guides/layout-overview#builtin-and-external-layouts).
```ts
-import { Graph, register } from '@antv/g6-lite';
-import random from '@antv/g6-lite/layouts/random';
-
-register('layout', 'random', random);
+import { Graph } from '@antv/g6-lite';
+import { RandomLayout } from '@antv/layout';
const graph = new Graph({
container,
data,
- layout: { type: 'random' },
+ layout: { type: RandomLayout },
});
```
diff --git a/site/content/docs/en/guides/layout-trees.mdx b/site/content/docs/en/guides/layout-trees.mdx
index dc5039b1d..5d2cf5adf 100644
--- a/site/content/docs/en/guides/layout-trees.mdx
+++ b/site/content/docs/en/guides/layout-trees.mdx
@@ -19,7 +19,7 @@ Express parent-child relationships as edges with the parent as `source` and the
Use **Tree layout** to compare the three arrangements. The example also changes the edge routing. Indented trees use elbow connectors, while the fishbone layout uses angled branches.
-Register each tree layout before using it. [Optional layouts](/en/docs/guides/layout-overview#optional-layouts)
+Import each tree layout class from `@antv/layout` and pass it as `layout.type`; no registration is required. See [Built-in and external layouts](/en/docs/guides/layout-overview#builtin-and-external-layouts).
diff --git a/site/content/docs/en/guides/layout-worker.mdx b/site/content/docs/en/guides/layout-worker.mdx
index 412b407e4..971c52cbb 100644
--- a/site/content/docs/en/guides/layout-worker.mdx
+++ b/site/content/docs/en/guides/layout-worker.mdx
@@ -16,7 +16,7 @@ layout: { type: 'force-atlas2', worker: true, maxIteration: 100 },
| layout.worker | Graph behavior |
| --- | --- |
| Omitted | Attempts a Worker at ≥ 1000 nodes; main thread below that threshold |
-| true | Attempts a Worker for built-in library layouts; registered extensions, including all six optional layouts, execute on the main thread |
+| true | Attempts a Worker for string-named built-in layouts; layout classes imported from `@antv/layout` and registered extensions execute on the main thread |
| false | Explicitly disables Workers, including for large graphs |
Standalone runLayout has no node-count-based automatic switch. Worker failures fall back to the same main-thread algorithm. See the [layout reference](/en/docs/guides/layout#worker) for execution order and iteration defaults.
diff --git a/site/content/docs/en/guides/layout.mdx b/site/content/docs/en/guides/layout.mdx
index 4fa1fb608..734d56b4c 100644
--- a/site/content/docs/en/guides/layout.mdx
+++ b/site/content/docs/en/guides/layout.mdx
@@ -11,7 +11,7 @@ Configure the layout in `new Graph()` through `layout`. See the [Layout overview
| Field | Purpose |
| --- | --- |
-| `type` | Algorithm name, such as `dagre` |
+| `type` | Algorithm name for built-in layouts (such as `force`) or a layout class imported from `@antv/layout` (such as `DagreLayout`) |
| `width`, `height` | Computation bounds, defaulting to canvas dimensions |
| `center` | Layout center for algorithms that use it |
| `worker` | Whether to try computing in a Worker |
@@ -24,23 +24,23 @@ Direction and spacing depend on the algorithm. See the [layout reference](/en/do
The thumbnails show 11 layouts on the same data. Try them in the [layout gallery](/en/docs/examples/layout-gallery) or see the [AntV Layout documentation](https://layout.antv.vision/) for more options.
-Layouts marked **Optional** must be imported and registered. See [Optional layouts](/en/docs/guides/layout-overview#optional-layouts).
+Layouts marked **External** must be imported from `@antv/layout` and passed as classes through `layout.type`; no registration is required. See [Built-in and external layouts](/en/docs/guides/layout-overview#builtin-and-external-layouts).
| type | Preview | Purpose | Common algorithm options |
| --- | --- | --- | --- |
-| [`circular`](/en/docs/guides/layout-circular) |  | Circle or spiral | radius, startRadius, endRadius, startAngle, endAngle, clockwise |
-| [`concentric`](/en/docs/guides/layout-concentric) |  | Rings by importance | sortBy, maxLevelDiff, nodeSize, nodeSpacing, preventOverlap |
-| [`grid`](/en/docs/guides/layout-grid) |  | Rows and columns | rows, cols, begin, sortBy, nodeSize, nodeSpacing, preventOverlap |
-| [`random`](/en/docs/guides/layout-random) |  | **Optional.** Random positions | width, height, center |
-| [`dagre`](/en/docs/guides/layout-dagre) |  | Directed layers | rankdir: TB/BT/LR/RL, nodesep, ranksep, edgesep, nodeSize, ranker |
+| [`circular`](/en/docs/guides/layout-circular) |  | **External.** Circle or spiral | radius, startRadius, endRadius, startAngle, endAngle, clockwise |
+| [`concentric`](/en/docs/guides/layout-concentric) |  | **External.** Rings by importance | sortBy, maxLevelDiff, nodeSize, nodeSpacing, preventOverlap |
+| [`grid`](/en/docs/guides/layout-grid) |  | **External.** Rows and columns | rows, cols, begin, sortBy, nodeSize, nodeSpacing, preventOverlap |
+| [`random`](/en/docs/guides/layout-random) |  | **External.** Random positions | width, height, center |
+| [`dagre`](/en/docs/guides/layout-dagre) |  | **External.** Directed layers | rankdir: TB/BT/LR/RL, nodesep, ranksep, edgesep, nodeSize, ranker |
| [`force`](/en/docs/guides/layout-force) |  | Force-directed network | linkDistance, nodeStrength, edgeStrength, maxIteration, minMovement |
| [`d3-force`](/en/docs/guides/layout-d3-force) |  | D3 simulation | linkDistance, nodeStrength, alphaDecay, alphaMin; use nodeStrength, not charge |
| [`force-atlas2`](/en/docs/guides/layout-force-atlas2) |  | ForceAtlas2 network | kr, kg, barnesHut, prune, maxIteration |
| [`fruchterman`](/en/docs/guides/layout-fruchterman) |  | Fruchterman network | gravity, speed, maxIteration, minMovement |
-| [`radial`](/en/docs/guides/layout-radial) |  | **Optional.** Rings around a focus | focusNode, unitRadius, linkDistance, preventOverlap |
-| [`mds`](/en/docs/guides/layout-mds) |  | **Optional.** Positions from graph distances | linkDistance, center |
+| [`radial`](/en/docs/guides/layout-radial) |  | **External.** Rings around a focus | focusNode, unitRadius, linkDistance, preventOverlap |
+| [`mds`](/en/docs/guides/layout-mds) |  | **External.** Positions from graph distances | linkDistance, center |
@@ -48,7 +48,7 @@ Rendered node sizes are not automatically passed to algorithms. For overlap avoi
### Computation defaults [#computation-defaults]
-G6Lite injects or rewrites the following options; explicit values win. These rules apply to library layouts, not the three functional tree layouts.
+G6Lite injects or rewrites the following options; explicit values win. These rules apply to the library layouts above, including tree layout classes imported from `@antv/layout`.
| Algorithm / option | Default or rule |
| --- | --- |
@@ -74,7 +74,7 @@ Use **Layout** to compare Grid, Circular, and Dagre on the same data. The code s
Set parent-child relationships in `edges`, with the parent as `source` and the child as `target`. Compare mind map, indented, and fishbone layouts in the [tree layout example](/en/docs/guides/layout-trees#configuration-and-example).
-### Functional tree layouts [#functional-tree-layouts]
+### Tree layouts [#functional-tree-layouts]
Use a connected tree with one root and no cycles.
@@ -82,9 +82,9 @@ Use a connected tree with one root and no cycles.
| type | Preview | Purpose |
| --- | --- | --- |
-| [`mindmap`](/en/docs/guides/layout-mindmap) |  | **Optional.** Organize a hierarchy into branches |
-| [`indented`](/en/docs/guides/layout-indented) |  | **Optional.** Show a tree as a list |
-| [`fishbone`](/en/docs/guides/layout-fishbone) |  | **Optional.** Group categories and items along a spine |
+| [`mindmap`](/en/docs/guides/layout-mindmap) |  | **External.** Organize a hierarchy into branches |
+| [`indented`](/en/docs/guides/layout-indented) |  | **External.** Show a tree as a list |
+| [`fishbone`](/en/docs/guides/layout-fishbone) |  | **External.** Group categories and items along a spine |
@@ -136,7 +136,9 @@ For root → category → item structures. Deeper nodes do not receive a complet
For a graph that has completed render: setLayout replaces the entire configuration. Fit the graph after layout only when needed:
```ts
-graph.setLayout({ type: 'dagre', rankdir: 'LR', nodesep: 32, ranksep: 64 });
+import { DagreLayout } from '@antv/layout';
+
+graph.setLayout({ type: DagreLayout, rankdir: 'LR', nodesep: 32, ranksep: 64 });
await graph.layout();
graph.fitView({ padding: 48, maxZoom: 1 });
```
@@ -149,7 +151,7 @@ Layout may change existing x/y. Graph's fx/fy override the corresponding final a
## Worker
-Graph supplies worker: true when node count ≥ 1000 and worker is omitted, without filtering by algorithm name. Standalone runLayout has no automatic switch. Execution order is registered extension → built-in tree → Worker → main-thread library. Worker creation, cloning, or execution failures fall back to the same main-thread algorithm, which may block again.
+Graph supplies worker: true when node count ≥ 1000 and worker is omitted for string-named built-in layouts. Layout classes imported from `@antv/layout` and custom layout classes cannot be transferred to a Worker and always run on the main thread. Standalone runLayout has no automatic switch. Execution order is registered extension → Worker → main-thread library. Worker creation, cloning, or execution failures fall back to the same main-thread algorithm, which may block again.
Prefer explicit worker: false for function-valued options. See [layout methods](/en/docs/api/graph#layout) for cancellation. Successful configuration does not prove a Worker actually ran.
diff --git a/site/content/docs/en/metrics/performance.mdx b/site/content/docs/en/metrics/performance.mdx
index dc0ae95bb..41dd54588 100644
--- a/site/content/docs/en/metrics/performance.mdx
+++ b/site/content/docs/en/metrics/performance.mdx
@@ -38,27 +38,15 @@ The table shows the median time in milliseconds from graph creation through two
These results apply only to the environment above and do not certify minimum supported browser versions. See [Minimum browser versions](/en/docs/compatibility/browser#minimum-browser-versions) for capability version references and the remaining acceptance scope.
-## Browser bundle size [#bundle-size]
+## G6Lite CDN file sizes [#umd-size]
-esbuild 0.21.5 bundles each npm entry and its dependencies into a single minified browser script. The G6Lite measurement uses the default entry, with optional layouts imported separately as needed. ECharts imports GraphChart and CanvasRenderer only. Sigma.js includes Graphology. Sizes are in KiB and exclude source maps.
+The published UMD file `g6-lite.min.js` includes rendering, interactions, and built-in force-directed layouts. One kB is 1,000 bytes.
-| npm package | Minified (KiB) | gzip -9 (KiB) |
-| --- | ---: | ---: |
-| `@antv/g6-lite` development build (`0.1.0`) | 511.3 | 159.5 |
-| `@antv/g6@5.1.1` | 1,435.3 | 413.4 |
-| `sigma@4.0.4` + `graphology@0.26.0` | 438.4 | 110.7 |
-| `echarts@6.1.0` | 386.3 | 130.2 |
-
-### G6Lite CDN file sizes [#umd-size]
-
-These files come from the published npm package `@antv/g6-lite@0.1.0`, downloaded again and measured with `gzip -9` on 2026-11-24. One kB is 1,000 bytes. The homepage uses the default script's measurement from the same run. These are the distributed UMD files, measured separately from the esbuild bundles above.
-
-| Published file | Contents | gzip -9 (kB) |
-| --- | --- | ---: |
-| `g6-lite.min.js` | Default script with rendering, interactions, and built-in layouts | 150.3 |
-| `g6-lite-layouts.min.js` | Six optional layouts, loaded when needed | 29.1 |
+| Published file | Contents | Minified (kB) | gzip -9 (kB) |
+| --- | --- | ---: | ---: |
+| `g6-lite.min.js` | Default script with rendering, interactions, and built-in force-directed layouts | 408.1 | 118.2 |
-Load the optional script before registering the layout you want to use. [Optional layouts](/en/docs/guides/layout-overview#optional-layouts)
+Other layouts are imported as classes from `@antv/layout` and run on the main thread. [Built-in and external layouts](/en/docs/guides/layout-overview#builtin-and-external-layouts)
## Measuring your own graph [#performance-tuning]
diff --git a/site/content/docs/zh/api/graph.mdx b/site/content/docs/zh/api/graph.mdx
index b65e524c6..0d7a8594f 100644
--- a/site/content/docs/zh/api/graph.mdx
+++ b/site/content/docs/zh/api/graph.mdx
@@ -764,7 +764,7 @@ console.log(client, point);
`graph.setLayout(config: LayoutConfig): void`
-替换布局配置。要让已有的图按新配置重排,再调用 [layout()](#graph-layout-layout)。
+替换布局配置。从 `@antv/layout` 导入的外部布局类可直接作为 `config.type` 传入,无需注册。要让已有的图按新配置重排,再调用 [layout()](#graph-layout-layout)。
### layout() [#graph-layout-layout]
@@ -775,7 +775,9 @@ console.log(client, point);
-执行顺序同布局配置参考:已注册同名扩展、内置函数式树布局、Worker、库算法。传 viewport 时,扩展 execute 上下文的 width/height 优先使用 viewport;显式 config.width/height 仍在 context.options 中。无 viewport 时,上下文尺寸回退到 config 或 800×600。
+字符串布局按已注册同名扩展、Worker、主线程库算法的顺序解析;从 `@antv/layout` 导入的布局类直接在主线程执行。传 viewport 时,扩展 execute 上下文的 width/height 优先使用 viewport;显式 config.width/height 仍在 context.options 中。无 viewport 时,上下文尺寸回退到 config 或 800×600。
独立 runLayout 不执行 Graph 的最终 fx/fy 覆盖,不运行 Graph transforms,也不发送 Graph 布局事件。返回后将坐标用于自己的渲染器;需要 Graph 的数据写回、状态和事件链时,使用实例 layout。
diff --git a/site/content/docs/zh/api/options.mdx b/site/content/docs/zh/api/options.mdx
index 494857659..5ab4562ea 100644
--- a/site/content/docs/zh/api/options.mdx
+++ b/site/content/docs/zh/api/options.mdx
@@ -101,6 +101,7 @@ import { NodeDocExample } from '@/components/node-doc-example';
```ts
import { Graph, type GraphNode } from '@antv/g6-lite';
+import { CircularLayout } from '@antv/layout';
// 省略 layout 时,节点按 x、y 定位。
const nodes: GraphNode[] = [
@@ -115,7 +116,7 @@ const graph = new Graph({
await graph.render();
// 启用圆形布局,通过 setData() 传入 fx 固定 A 的横坐标。
-graph.setLayout({ type: 'circular' });
+graph.setLayout({ type: CircularLayout });
await graph.setData({
nodes: [{ id: 'A', fx: 100 }, { id: 'B' }],
edges: [],
@@ -550,8 +551,8 @@ graph.updateNodeData('A', { score: 80 });
| 属性 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
-| `type` | 必填。内置布局名称或已注册的布局名,例如 `'dagre'`、`'grid'`。未知名称采用随机坐标。可选布局需先注册。 | `string` | — |
-| `worker` | 设为 `false` 可关闭。执行顺序与回退见[布局指南](/docs/guides/layout#worker)。 | `boolean` | Graph 中节点数 ≥ 1000 时默认尝试启用 |
+| `type` | 必填。内置布局名称(`'force'`、`'force-atlas2'`、`'d3-force'`、`'fruchterman'`)、已注册的布局名,或直接从 `@antv/layout` 导入的布局类(如 `DagreLayout`)。未知名称采用随机坐标。 | `string \| LayoutConstructor` | — |
+| `worker` | 设为 `false` 可关闭。仅字符串形式的内置布局支持 Worker;从 `@antv/layout` 导入的布局类和自定义布局类在主线程执行。执行顺序与回退见[布局指南](/docs/guides/layout#worker)。 | `boolean` | Graph 中节点数 ≥ 1000 且为字符串内置布局时默认尝试启用 |
| `width` | 布局计算使用的宽度。 | `number` | 当前画布宽度 |
| `height` | 布局计算使用的高度。 | `number` | 当前画布高度 |
| `center` | 布局中心,是否使用由算法决定。 | `[number, number]` | `[width / 2, height / 2]` |
@@ -563,6 +564,8 @@ graph.updateNodeData('A', { score: 80 });
同一棵树可以排成思维导图、目录列表或鱼骨图。数据用 `nodes` 声明节点,用 `edges` 的 `source → target` 表示父子关系。输入一棵有且只有一个根节点的连通树。
+这三种布局均为外部布局,从 `@antv/layout` 导入 `MindmapLayout`、`IndentedLayout` 或 `FishboneLayout` 后作为 `layout.type` 传入,无需注册。
+
| 布局 | 排列效果 | 适用场景 |
@@ -583,10 +586,11 @@ graph.updateNodeData('A', { score: 80 });
```ts
import type { GraphNode, LayoutConfig } from '@antv/g6-lite';
+import { MindmapLayout } from '@antv/layout';
const leftBranches = new Set(['A', 'C']);
const layout: LayoutConfig = {
- type: 'mindmap',
+ type: MindmapLayout,
direction: 'H',
levelGap: 100,
nodeGap: 24,
@@ -611,7 +615,9 @@ const layout: LayoutConfig = {
每个节点占一行,子节点排在父节点下方,层级越深缩进越多。调整 `indent` 控制缩进,调整 `rowHeight` 控制行距。
```ts
-const layout: LayoutConfig = { type: 'indented', indent: 72, rowHeight: 30 };
+import { IndentedLayout } from '@antv/layout';
+
+const layout: LayoutConfig = { type: IndentedLayout, indent: 72, rowHeight: 30 };
const edge: EdgeConfig = { type: 'polyline', style: { router: 'indented', endArrow: false } };
```
@@ -629,7 +635,9 @@ const edge: EdgeConfig = { type: 'polyline', style: { router: 'indented', endArr
用三层节点表示「问题 → 原因分类 → 具体原因」。`categoryGap` 拉开主干上的分类,`categoryDistance` 调整分类离主干的距离。
```ts
-const layout: LayoutConfig = { type: 'fishbone', categoryGap: 156, categoryDistance: 130, itemHStep: 54 };
+import { FishboneLayout } from '@antv/layout';
+
+const layout: LayoutConfig = { type: FishboneLayout, categoryGap: 156, categoryDistance: 130, itemHStep: 54 };
const edge: EdgeConfig = { type: 'polyline', style: { router: 'fishbone', endArrow: false } };
```
@@ -645,7 +653,7 @@ const edge: EdgeConfig = { type: 'polyline', style: { router: 'fishbone', endArr
### 布局参数 [#config-library-layout-fields]
-在 `layout` 中设置布局类型 `type`,再加上表里的参数。例如,`layout: { type: 'dagre', rankdir: 'LR' }` 会让流程从左向右排列。
+在 `layout` 中设置布局类型 `type`,再加上表里的参数。例如,`layout: { type: DagreLayout, rankdir: 'LR' }` 会让流程从左向右排列。
| 布局类型 | 参数示例 | 效果 |
| --- | --- | --- |
diff --git a/site/content/docs/zh/compatibility/g6-v5-migration.mdx b/site/content/docs/zh/compatibility/g6-v5-migration.mdx
index d13d8d91c..9e64a3c51 100644
--- a/site/content/docs/zh/compatibility/g6-v5-migration.mdx
+++ b/site/content/docs/zh/compatibility/g6-v5-migration.mdx
@@ -23,6 +23,7 @@ G6 v5 通常使用容器 ID、labelText 与 drag-element;见[官方示例](htt
```ts
import { Graph } from '@antv/g6-lite';
+import { CircularLayout } from '@antv/layout';
export async function mountGraph(container: HTMLElement) {
const graph = new Graph({
@@ -32,7 +33,7 @@ export async function mountGraph(container: HTMLElement) {
edges: [{ id: 'a-b', source: 'a', target: 'b' }],
},
node: { style: { label: (node) => node.id } },
- layout: { type: 'circular', radius: 100 },
+ layout: { type: CircularLayout, radius: 100 },
behaviors: ['zoom-canvas', 'drag-canvas', 'drag-node', 'click-select'],
});
try {
diff --git a/site/content/docs/zh/getting-started/quick-start.mdx b/site/content/docs/zh/getting-started/quick-start.mdx
index f5ede7c7b..4b6d36651 100644
--- a/site/content/docs/zh/getting-started/quick-start.mdx
+++ b/site/content/docs/zh/getting-started/quick-start.mdx
@@ -188,11 +188,11 @@ import { Graph } from 'https://esm.sh/@antv/g6-lite@0.1.0?bundle';
### 使用 UMD 脚本 [#cdn-umd]
-UMD 主脚本包含运行依赖和内置布局,加载后通过 `G6Lite.Graph` 创建图。下面的最小示例绘制两个节点和一条边:
+UMD 主脚本包含运行依赖和内置力导向布局(`force`、`force-atlas2`、`d3-force`、`fruchterman`),加载后通过 `G6Lite.Graph` 创建图。下面的最小示例绘制两个节点和一条边:
```html
-
+
-
-
+const layout = { type: RadialLayout, focusNode: '0', unitRadius: 68 };
```
-注册的布局在主线程运行。
+这些布局类也在主线程运行。
## 配置与示例
@@ -61,6 +69,7 @@ const layout = { type: 'radial', focusNode: '0', unitRadius: 68 };
```ts
import { Graph } from '@antv/g6-lite';
+import { DagreLayout } from '@antv/layout';
const graph = new Graph({
container: '#container',
@@ -71,7 +80,7 @@ const graph = new Graph({
{ source: '审核', target: '发布' },
],
},
- layout: { type: 'dagre', rankdir: 'LR', ranksep: 80 },
+ layout: { type: DagreLayout, rankdir: 'LR', ranksep: 80 },
node: { style: { label: (node) => node.id } },
});
diff --git a/site/content/docs/zh/guides/layout-radial.mdx b/site/content/docs/zh/guides/layout-radial.mdx
index 9477dbd22..775c77fbc 100644
--- a/site/content/docs/zh/guides/layout-radial.mdx
+++ b/site/content/docs/zh/guides/layout-radial.mdx
@@ -15,18 +15,16 @@ import { NodeDocExample } from '@/components/node-doc-example';
## 基本用法
-这是可选布局。先导入并注册,再设置 `layout.type`。CDN 接入见[可选布局](/docs/guides/layout-overview#optional-layouts)。
+这是外部布局。从 `@antv/layout` 导入布局类并作为 `layout.type` 传入,无需注册。详见[内置与外部布局](/docs/guides/layout-overview#builtin-and-external-layouts)。
```ts
-import { Graph, register } from '@antv/g6-lite';
-import radial from '@antv/g6-lite/layouts/radial';
-
-register('layout', 'radial', radial);
+import { Graph } from '@antv/g6-lite';
+import { RadialLayout } from '@antv/layout';
const graph = new Graph({
container,
data,
- layout: { type: 'radial' },
+ layout: { type: RadialLayout },
});
```
diff --git a/site/content/docs/zh/guides/layout-random.mdx b/site/content/docs/zh/guides/layout-random.mdx
index c44a69f6a..22a8ec2ab 100644
--- a/site/content/docs/zh/guides/layout-random.mdx
+++ b/site/content/docs/zh/guides/layout-random.mdx
@@ -15,18 +15,16 @@ import { NodeDocExample } from '@/components/node-doc-example';
## 基本用法
-这是可选布局。先导入并注册,再设置 `layout.type`。CDN 接入见[可选布局](/docs/guides/layout-overview#optional-layouts)。
+这是外部布局。从 `@antv/layout` 导入布局类并作为 `layout.type` 传入,无需注册。详见[内置与外部布局](/docs/guides/layout-overview#builtin-and-external-layouts)。
```ts
-import { Graph, register } from '@antv/g6-lite';
-import random from '@antv/g6-lite/layouts/random';
-
-register('layout', 'random', random);
+import { Graph } from '@antv/g6-lite';
+import { RandomLayout } from '@antv/layout';
const graph = new Graph({
container,
data,
- layout: { type: 'random' },
+ layout: { type: RandomLayout },
});
```
diff --git a/site/content/docs/zh/guides/layout-trees.mdx b/site/content/docs/zh/guides/layout-trees.mdx
index 99a61d3f4..a43428592 100644
--- a/site/content/docs/zh/guides/layout-trees.mdx
+++ b/site/content/docs/zh/guides/layout-trees.mdx
@@ -19,7 +19,7 @@ import { NodeDocExample } from '@/components/node-doc-example';
用 **Tree layout** 切换三种布局。示例同时调整边的画法,缩进树用折线连接,鱼骨图用斜线展示条目。
-这三种树布局都需要先注册。 [可选布局](/docs/guides/layout-overview#optional-layouts)
+这三种树布局均从 `@antv/layout` 导入对应布局类并作为 `layout.type` 传入,无需注册。见[内置与外部布局](/docs/guides/layout-overview#builtin-and-external-layouts)。
diff --git a/site/content/docs/zh/guides/layout-worker.mdx b/site/content/docs/zh/guides/layout-worker.mdx
index 3e393b15b..9a328368a 100644
--- a/site/content/docs/zh/guides/layout-worker.mdx
+++ b/site/content/docs/zh/guides/layout-worker.mdx
@@ -18,7 +18,7 @@ layout: { type: 'force-atlas2', worker: true, maxIteration: 100 },
| layout.worker | Graph 中的行为 |
| --- | --- |
| 省略 | 节点数 ≥ 1000 时尝试启用;低于 1000 时走主线程 |
-| true | 对内置库布局尝试 Worker;注册扩展(包括六种可选布局)在主线程执行 |
+| true | 对字符串形式的内置布局尝试 Worker;从 `@antv/layout` 导入的布局类和注册扩展均在主线程执行 |
| false | 显式关闭,包括大图 |
独立 runLayout 没有按节点数自动启用的行为。Worker 失败会回退到同一算法的主线程实现;具体执行顺序和默认迭代值见[布局参考](/docs/guides/layout#worker)。
diff --git a/site/content/docs/zh/guides/layout.mdx b/site/content/docs/zh/guides/layout.mdx
index 14637c6b2..d739a5d44 100644
--- a/site/content/docs/zh/guides/layout.mdx
+++ b/site/content/docs/zh/guides/layout.mdx
@@ -13,7 +13,7 @@ import { NodeDocExample as LayoutDocExample } from '@/components/node-doc-exampl
| 字段 | 用途 |
| --- | --- |
-| `type` | 指定布局算法,例如 `dagre` |
+| `type` | 指定布局算法:内置布局名称(如 `force`)或从 `@antv/layout` 导入的布局类(如 `DagreLayout`) |
| `width`、`height` | 设置计算范围,默认取画布宽高 |
| `center` | 设置布局中心,默认取计算范围的中心,由算法决定是否使用 |
| `worker` | 设置是否尝试在 Worker 中计算 |
@@ -24,23 +24,23 @@ import { NodeDocExample as LayoutDocExample } from '@/components/node-doc-exampl
下表的 11 种布局用同一份数据生成缩略图。想试用其中一种,可以打开[布局示例合集](/docs/examples/layout-gallery)。完整算法参数见 [AntV Layout 文档](https://layout.antv.vision/)。
-标为「可选」的布局需先导入并注册,见[可选布局](/docs/guides/layout-overview#optional-layouts)。
+标为「外部」的布局都需从 `@antv/layout` 导入布局类并作为 `layout.type` 传入,无需注册,见[内置与外部布局](/docs/guides/layout-overview#builtin-and-external-layouts)。
| type | 效果 | 用途 | 常用算法参数 |
| --- | --- | --- | --- |
-| [`circular`](/docs/guides/layout-circular) |  | 圆周或螺旋排列 | radius、startRadius、endRadius、startAngle、endAngle、clockwise |
-| [`concentric`](/docs/guides/layout-concentric) |  | 按重要程度分圈 | sortBy、maxLevelDiff、nodeSize、nodeSpacing、preventOverlap |
-| [`grid`](/docs/guides/layout-grid) |  | 规则行列 | rows、cols、begin、sortBy、nodeSize、nodeSpacing、preventOverlap |
-| [`random`](/docs/guides/layout-random) |  | **可选。** 随机位置 | width、height、center |
-| [`dagre`](/docs/guides/layout-dagre) |  | 有向分层 | rankdir: TB/BT/LR/RL,nodesep、ranksep、edgesep、nodeSize、ranker |
+| [`circular`](/docs/guides/layout-circular) |  | **外部。** 圆周或螺旋排列 | radius、startRadius、endRadius、startAngle、endAngle、clockwise |
+| [`concentric`](/docs/guides/layout-concentric) |  | **外部。** 按重要程度分圈 | sortBy、maxLevelDiff、nodeSize、nodeSpacing、preventOverlap |
+| [`grid`](/docs/guides/layout-grid) |  | **外部。** 规则行列 | rows、cols、begin、sortBy、nodeSize、nodeSpacing、preventOverlap |
+| [`random`](/docs/guides/layout-random) |  | **外部。** 随机位置 | width、height、center |
+| [`dagre`](/docs/guides/layout-dagre) |  | **外部。** 有向分层 | rankdir: TB/BT/LR/RL,nodesep、ranksep、edgesep、nodeSize、ranker |
| [`force`](/docs/guides/layout-force) |  | 力导向网络 | linkDistance、nodeStrength、edgeStrength、maxIteration、minMovement |
| [`d3-force`](/docs/guides/layout-d3-force) |  | D3 力模拟 | linkDistance、nodeStrength、alphaDecay、alphaMin;使用 nodeStrength,不是 charge |
| [`force-atlas2`](/docs/guides/layout-force-atlas2) |  | ForceAtlas2 网络 | kr、kg、barnesHut、prune、maxIteration |
| [`fruchterman`](/docs/guides/layout-fruchterman) |  | Fruchterman 网络 | gravity、speed、maxIteration、minMovement |
-| [`radial`](/docs/guides/layout-radial) |  | **可选。** 围绕焦点的同心层 | focusNode、unitRadius、linkDistance、preventOverlap |
-| [`mds`](/docs/guides/layout-mds) |  | **可选。** 按图距离求二维位置 | linkDistance、center |
+| [`radial`](/docs/guides/layout-radial) |  | **外部。** 围绕焦点的同心层 | focusNode、unitRadius、linkDistance、preventOverlap |
+| [`mds`](/docs/guides/layout-mds) |  | **外部。** 按图距离求二维位置 | linkDistance、center |
@@ -48,7 +48,7 @@ import { NodeDocExample as LayoutDocExample } from '@/components/node-doc-exampl
### 计算默认值 [#计算默认值]
-以下由 G6Lite 注入或改写,用户显式值优先;仅适用于上面的库布局,不用于三个函数式树布局。
+以下由 G6Lite 注入或改写,用户显式值优先;适用于上面的库布局,包括从 `@antv/layout` 导入的树布局类。
| 算法 / 选项 | 默认或规则 |
| --- | --- |
@@ -82,9 +82,9 @@ import { NodeDocExample as LayoutDocExample } from '@/components/node-doc-exampl
| type | 效果 | 用途 |
| --- | --- | --- |
-| [`mindmap`](/docs/guides/layout-mindmap) |  | **可选。** 按左右分支组织层级 |
-| [`indented`](/docs/guides/layout-indented) |  | **可选。** 逐行展示树形列表 |
-| [`fishbone`](/docs/guides/layout-fishbone) |  | **可选。** 沿主干展示分类和条目 |
+| [`mindmap`](/docs/guides/layout-mindmap) |  | **外部。** 按左右分支组织层级 |
+| [`indented`](/docs/guides/layout-indented) |  | **外部。** 逐行展示树形列表 |
+| [`fishbone`](/docs/guides/layout-fishbone) |  | **外部。** 沿主干展示分类和条目 |
@@ -136,7 +136,9 @@ import { NodeDocExample as LayoutDocExample } from '@/components/node-doc-exampl
首次渲染后,布局配置通过 `setLayout()` 替换,节点位置在 `layout()` 完成后更新。需要让整张图重新进入视野时,再调用 `fitView()`。
```ts
-graph.setLayout({ type: 'dagre', rankdir: 'LR', nodesep: 32, ranksep: 64 });
+import { DagreLayout } from '@antv/layout';
+
+graph.setLayout({ type: DagreLayout, rankdir: 'LR', nodesep: 32, ranksep: 64 });
await graph.layout();
graph.fitView({ padding: 48, maxZoom: 1 });
```
@@ -147,7 +149,7 @@ graph.fitView({ padding: 48, maxZoom: 1 });
## Worker
-库布局可通过 `worker: true` 尝试在后台线程计算。图达到 1000 个节点时默认尝试启用。算法参数包含函数时,可设置 `worker: false` 在主线程计算。启用、回退和取消示例见 [Worker 布局指南](/docs/guides/layout-worker)。
+字符串形式的内置布局可通过 `worker: true` 尝试在后台线程计算,图达到 1000 个节点时默认尝试启用。从 `@antv/layout` 导入的布局类及自定义布局类无法传入 Worker,始终在主线程执行。算法参数包含函数时,可设置 `worker: false` 在主线程计算。启用、回退和取消示例见 [Worker 布局指南](/docs/guides/layout-worker)。
## 常见问题
diff --git a/site/content/docs/zh/metrics/performance.mdx b/site/content/docs/zh/metrics/performance.mdx
index 7eafb3753..cc1e6e7d7 100644
--- a/site/content/docs/zh/metrics/performance.mdx
+++ b/site/content/docs/zh/metrics/performance.mdx
@@ -34,27 +34,15 @@ description: 同一图数据下 G6Lite、G6、Sigma.js 与 ECharts 的首绘耗
本轮结果只适用于上述测试环境,不代表最低浏览器版本认证。各浏览器的能力版本参考与尚未覆盖的验收范围见[最低浏览器版本](/docs/compatibility/browser#最低浏览器版本)。
-## 浏览器包体积 [#bundle-size]
+## G6Lite CDN 文件体积 [#umd-size]
-使用 esbuild 0.21.5 将各库的 npm 入口和依赖打包为单个浏览器脚本,并进行代码压缩。G6Lite 测量默认入口,可选布局按需引入。ECharts 只引入 GraphChart 和 CanvasRenderer,Sigma.js 包含 Graphology。体积以 KiB 计,不含 source map。
+发布的 UMD 文件 `g6-lite.min.js` 包含渲染、交互和内置力导向布局,1 kB = 1,000 字节。
-| npm 包 | 代码压缩后(KiB) | gzip -9(KiB) |
-| --- | ---: | ---: |
-| `@antv/g6-lite` 开发构建(`0.1.0`) | 511.3 | 159.5 |
-| `@antv/g6@5.1.1` | 1,435.3 | 413.4 |
-| `sigma@4.0.4` + `graphology@0.26.0` | 438.4 | 110.7 |
-| `echarts@6.1.0` | 386.3 | 130.2 |
-
-### G6Lite CDN 文件体积 [#umd-size]
-
-以下文件来自 npm 正式发布的 `@antv/g6-lite@0.1.0`,于 2026-11-24 重新下载并使用 `gzip -9` 分别测量,1 kB = 1,000 字节。首页展示默认脚本的同次测量值。这些文件是现成的 UMD 产物,与上方 esbuild 重新打包的体积采用不同口径。
-
-| 发布文件 | 内容 | gzip -9(kB) |
-| --- | --- | ---: |
-| `g6-lite.min.js` | 默认脚本,包含渲染、交互和内置布局 | 150.3 |
-| `g6-lite-layouts.min.js` | 六种可选布局,使用时额外加载 | 29.1 |
+| 发布文件 | 内容 | 压缩前(kB) | gzip 后(kB) |
+| --- | --- | ---: | ---: |
+| `g6-lite.min.js` | 默认脚本,包含渲染、交互和内置力导向布局 | 408.1 | 118.2 |
-需要使用可选布局时,加载附加脚本后注册对应的布局。 [可选布局用法](/docs/guides/layout-overview#optional-layouts)
+其他布局从 `@antv/layout` 导入布局类后传入,在主线程执行。 [内置与外部布局](/docs/guides/layout-overview#builtin-and-external-layouts)
## 业务图怎么测 [#performance-tuning]
diff --git a/site/demos/basic.ts b/site/demos/basic.ts
index 4b2546981..b6c5246b2 100644
--- a/site/demos/basic.ts
+++ b/site/demos/basic.ts
@@ -2,6 +2,7 @@
* Demo: 最简示例 — 少量节点边 + 环形布局
*/
import { Graph } from '@antv/g6-lite';
+import { CircularLayout } from '@antv/layout';
export async function run(container: string | HTMLElement) {
const graph = new Graph({
@@ -23,7 +24,7 @@ export async function run(container: string | HTMLElement) {
{ source: '3', target: '4' },
],
},
- layout: { type: 'circular', radius: 150 },
+ layout: { type: CircularLayout, radius: 150 },
behaviors: ['zoom-canvas', 'drag-canvas'],
theme: 'light',
});
diff --git a/site/demos/behaviors.ts b/site/demos/behaviors.ts
index 61f3dda97..134594177 100644
--- a/site/demos/behaviors.ts
+++ b/site/demos/behaviors.ts
@@ -4,6 +4,7 @@
* 操作:滚轮缩放、拖拽平移、悬停高亮;按住 Shift 拖拽框选节点(brush-select)。
*/
import { Graph } from '@antv/g6-lite';
+import { CircularLayout } from '@antv/layout';
export async function run(container: string | HTMLElement) {
const graph = new Graph({
@@ -33,7 +34,7 @@ export async function run(container: string | HTMLElement) {
},
},
edge: { type: 'line', style: { lineWidth: 2 } },
- layout: { type: 'circular', radius: 150 },
+ layout: { type: CircularLayout, radius: 150 },
behaviors: [
'zoom-canvas',
'drag-canvas',
diff --git a/site/demos/custom-behavior.ts b/site/demos/custom-behavior.ts
index 0ec99edae..11699175f 100644
--- a/site/demos/custom-behavior.ts
+++ b/site/demos/custom-behavior.ts
@@ -8,6 +8,7 @@ import {
type BehaviorOptions,
type ExtensionContext,
} from '@antv/g6-lite';
+import { DagreLayout } from '@antv/layout';
const PIN_BEHAVIOR = 'pin-node' as const;
@@ -73,7 +74,7 @@ export async function run(container: string | HTMLElement) {
},
},
edge: { style: { endArrow: true } },
- layout: { type: 'dagre', rankdir: 'LR', nodesep: 24, ranksep: 70, nodeSize: [88, 36] },
+ layout: { type: DagreLayout, rankdir: 'LR', nodesep: 24, ranksep: 70, nodeSize: [88, 36] },
behaviors: ['zoom-canvas', 'drag-canvas', { type: PIN_BEHAVIOR } satisfies PinBehaviorOptions],
});
await graph.render();
diff --git a/site/demos/custom-label-renderer.ts b/site/demos/custom-label-renderer.ts
index 0a1d04b60..f62613138 100644
--- a/site/demos/custom-label-renderer.ts
+++ b/site/demos/custom-label-renderer.ts
@@ -3,6 +3,7 @@
* The multiline behavior lives entirely in this demo, not in G6Lite core.
*/
import { Graph, register, type LabelRenderer } from '@antv/g6-lite';
+import { DagreLayout } from '@antv/layout';
interface MultilineLayoutData {
lines: string[];
@@ -62,7 +63,7 @@ export async function run(container: string | HTMLElement) {
{ source: 'gateway', target: 'target', data: { label: 'RPC\nresponse' } },
],
},
- layout: { type: 'dagre', rankdir: 'LR', nodeSize: 32, ranksep: 180 },
+ layout: { type: DagreLayout, rankdir: 'LR', nodeSize: 32, ranksep: 180 },
behaviors: ['zoom-canvas', 'drag-canvas', 'drag-node'],
// #region node-label
node: {
diff --git a/site/demos/decoration-badges.ts b/site/demos/decoration-badges.ts
index 21666b8e6..4e5813fa0 100644
--- a/site/demos/decoration-badges.ts
+++ b/site/demos/decoration-badges.ts
@@ -2,6 +2,7 @@
* Demo: stack built-in badges on a node boundary.
*/
import { Graph, type NodeBadgeItem } from '@antv/g6-lite';
+import { DagreLayout } from '@antv/layout';
export async function run(container: string | HTMLElement) {
const graph = new Graph({
@@ -59,7 +60,7 @@ export async function run(container: string | HTMLElement) {
],
},
edge: { style: { endArrow: true, stroke: '#99ADD1' } },
- layout: { type: 'dagre', rankdir: 'LR', nodesep: 40, ranksep: 120, nodeSize: 56 },
+ layout: { type: DagreLayout, rankdir: 'LR', nodesep: 40, ranksep: 120, nodeSize: 56 },
behaviors: ['zoom-canvas', 'drag-canvas'],
});
await graph.render();
diff --git a/site/demos/dependency-graph.ts b/site/demos/dependency-graph.ts
index dcce3496b..eb46aa092 100644
--- a/site/demos/dependency-graph.ts
+++ b/site/demos/dependency-graph.ts
@@ -2,6 +2,7 @@
* Demo: a left-to-right service call chain.
*/
import { Graph } from '@antv/g6-lite';
+import { DagreLayout } from '@antv/layout';
const CALLS: Array<[string, string, string]> = [
['gateway', '网关', 'auth'],
@@ -41,7 +42,7 @@ export async function run(container: string | HTMLElement) {
},
},
edge: { style: { endArrow: true, stroke: '#99ADD1', lineWidth: 1.5 } },
- layout: { type: 'dagre', rankdir: 'LR', nodesep: 24, ranksep: 64, nodeSize: [84, 34] },
+ layout: { type: DagreLayout, rankdir: 'LR', nodesep: 24, ranksep: 64, nodeSize: [84, 34] },
behaviors: ['zoom-canvas', 'drag-canvas', 'highlight-node'],
});
await graph.render();
diff --git a/site/demos/docs-built-in-layout.ts b/site/demos/docs-built-in-layout.ts
index 25f5d8c38..0830480cf 100644
--- a/site/demos/docs-built-in-layout.ts
+++ b/site/demos/docs-built-in-layout.ts
@@ -1,22 +1,26 @@
-import { Graph, register, type GraphNode, type GraphOptions, type LayoutConfig } from '@antv/g6-lite';
-import mds from '@antv/g6-lite/layouts/mds';
-import radial from '@antv/g6-lite/layouts/radial';
-import indented from '@antv/g6-lite/layouts/indented';
-import mindmap from '@antv/g6-lite/layouts/mindmap';
-import fishboneLayout from '@antv/g6-lite/layouts/fishbone';
-import random from '@antv/g6-lite/layouts/random';
-
-const optionalLayouts = new Map(Object.entries({ mds, radial, indented, mindmap, fishbone: fishboneLayout, random }));
+import { Graph, type GraphNode, type GraphOptions, type LayoutConfig } from '@antv/g6-lite';
+import {
+ CircularLayout,
+ ConcentricLayout,
+ DagreLayout,
+ FishboneLayout,
+ GridLayout,
+ IndentedLayout,
+ MDSLayout,
+ MindmapLayout,
+ RadialLayout,
+ RandomLayout,
+} from '@antv/layout';
const layouts = {
// #region layout-grid-config
- 'grid': { type: 'grid', rows: 2, cols: 3, width: 360, height: 160 },
+ 'grid': { type: GridLayout, rows: 2, cols: 3, width: 360, height: 160 },
// #endregion layout-grid-config
// #region layout-circular-config
- 'circular': { type: 'circular', radius: 100 },
+ 'circular': { type: CircularLayout, radius: 100 },
// #endregion layout-circular-config
// #region layout-dagre-config
- 'dagre': { type: 'dagre', rankdir: 'LR', nodesep: 32, ranksep: 80, nodeSize: [80, 32] },
+ 'dagre': { type: DagreLayout, rankdir: 'LR', nodesep: 32, ranksep: 80, nodeSize: [80, 32] },
// #endregion layout-dagre-config
// #region layout-force-config
'force': { type: 'force', linkDistance: 100 },
@@ -47,11 +51,11 @@ const layouts = {
},
// #endregion layout-fruchterman-config
// #region layout-radial-config
- 'radial': { type: 'radial', focusNode: '0', unitRadius: 68 },
+ 'radial': { type: RadialLayout, focusNode: '0', unitRadius: 68 },
// #endregion layout-radial-config
// #region layout-concentric-config
'concentric': {
- type: 'concentric',
+ type: ConcentricLayout,
sortBy: 'degree',
maxLevelDiff: 1,
preventOverlap: true,
@@ -60,14 +64,14 @@ const layouts = {
},
// #endregion layout-concentric-config
// #region layout-mds-config
- 'mds': { type: 'mds', linkDistance: 80 },
+ 'mds': { type: MDSLayout, linkDistance: 80 },
// #endregion layout-mds-config
// #region layout-indented-config
- 'indented': { type: 'indented', direction: 'LR', indent: 72, rowHeight: 30 },
+ 'indented': { type: IndentedLayout, direction: 'LR', indent: 72, rowHeight: 30 },
// #endregion layout-indented-config
// #region layout-mindmap-config
'mindmap': {
- type: 'mindmap',
+ type: MindmapLayout,
direction: 'H',
levelGap: 100,
nodeGap: 24,
@@ -78,7 +82,7 @@ const layouts = {
// #endregion layout-mindmap-config
// #region layout-fishbone-config
'fishbone': {
- type: 'fishbone',
+ type: FishboneLayout,
direction: 'LR',
categoryGap: 200,
categoryDistance: 138,
@@ -87,7 +91,7 @@ const layouts = {
},
// #endregion layout-fishbone-config
// #region layout-random-config
- 'random': { type: 'random', width: 400, height: 240, center: [200, 120] },
+ 'random': { type: RandomLayout, width: 400, height: 240, center: [200, 120] },
// #endregion layout-random-config
} satisfies Record;
@@ -266,8 +270,6 @@ function tree(type: string): ExampleOptions {
// #endregion tree
export function run(container: HTMLElement, type: BuiltInLayoutExample) {
- const extension = optionalLayouts.get(type);
- if (extension) register('layout', type, extension);
const layout = layouts[type];
if (type === 'concentric') return render(container, layout, concentric());
if (type === 'fishbone') return render(container, layout, fishbone());
diff --git a/site/demos/docs-edge-indented.ts b/site/demos/docs-edge-indented.ts
index cf37840f0..c0d2b7496 100644
--- a/site/demos/docs-edge-indented.ts
+++ b/site/demos/docs-edge-indented.ts
@@ -1,8 +1,7 @@
-import { Graph, register } from '@antv/g6-lite';
-import indented from '@antv/g6-lite/layouts/indented';
+import { Graph } from '@antv/g6-lite';
+import { IndentedLayout } from '@antv/layout';
export async function run(container: HTMLElement) {
- register('layout', 'indented', indented);
const graph = new Graph({
container,
data: {
@@ -18,7 +17,7 @@ export async function run(container: HTMLElement) {
style: { width: 80, height: 28, borderRadius: 5, label: (node) => node.id, labelPlacement: 'center', labelColor: '#fff' },
},
// #region routing
- layout: { type: 'indented', direction: 'LR', indent: 160, rowHeight: 70 },
+ layout: { type: IndentedLayout, direction: 'LR', indent: 160, rowHeight: 70 },
edge: {
type: 'polyline',
style: { router: 'indented', indentTarget: 'left', radius: 10, lineWidth: 2, hitAreaWidth: 12 },
diff --git a/site/demos/docs-events-lifecycle.ts b/site/demos/docs-events-lifecycle.ts
index 957514b54..97108c6c7 100644
--- a/site/demos/docs-events-lifecycle.ts
+++ b/site/demos/docs-events-lifecycle.ts
@@ -1,5 +1,6 @@
import { Graph, type FitViewOptions, type GraphData, type GraphEventMap } from '@antv/g6-lite';
import { createDemoPanel } from './demo-panel.ts';
+import { GridLayout } from '@antv/layout';
export async function run(container: HTMLElement) {
const initialData = (): GraphData => ({
@@ -13,7 +14,7 @@ export async function run(container: HTMLElement) {
const graph = new Graph({
container,
data: initialData(),
- layout: { type: 'grid', rows: 1, width: 320, height: 80 },
+ layout: { type: GridLayout, rows: 1, width: 320, height: 80 },
node: { style: { size: 30, label: (node) => `${node.id}: ${node.data?.edits ?? 0}`, labelOffsetY: 8 } },
behaviors: [],
autoFit: fit,
diff --git a/site/demos/docs-extension-layout.ts b/site/demos/docs-extension-layout.ts
index 12224b923..3a1e40a49 100644
--- a/site/demos/docs-extension-layout.ts
+++ b/site/demos/docs-extension-layout.ts
@@ -1,5 +1,6 @@
import { Graph, register, type ExtensionContext, type LayoutExtension } from '@antv/g6-lite';
import { createDemoPanel } from './demo-panel.ts';
+import { GridLayout } from '@antv/layout';
interface ColumnOptions extends Record { gap?: number; delay?: number }
function pause(signal: AbortSignal | undefined, delay: number) {
@@ -49,7 +50,7 @@ export async function run(container: HTMLElement) {
const request = ++revision;
status.textContent = mode === 'slow' ? 'Running slow layout…' : 'Running…';
if (mode === 'grid') graph.cancelLayout();
- graph.setLayout(mode === 'grid' ? { type: 'grid' } : { type: 'docs-column', gap: 100, delay: mode === 'slow' ? 180 : 0 });
+ graph.setLayout(mode === 'grid' ? { type: GridLayout } : { type: 'docs-column', gap: 100, delay: mode === 'slow' ? 180 : 0 });
await graph.layout();
if (graph.destroyed || request !== revision) return;
graph.fitView({ padding: 56 });
diff --git a/site/demos/docs-graph-options.ts b/site/demos/docs-graph-options.ts
index 1429e193b..2dfa26d53 100644
--- a/site/demos/docs-graph-options.ts
+++ b/site/demos/docs-graph-options.ts
@@ -1,4 +1,5 @@
import { Graph } from '@antv/g6-lite';
+import { DagreLayout } from '@antv/layout';
export async function run(container: HTMLElement) {
const graph = new Graph({
@@ -55,7 +56,7 @@ export async function run(container: HTMLElement) {
},
},
// #endregion element-options
- layout: { type: 'dagre', rankdir: 'LR', ranksep: 84, nodesep: 16, nodeSize: 96 },
+ layout: { type: DagreLayout, rankdir: 'LR', ranksep: 84, nodesep: 16, nodeSize: 96 },
label: { hideOnLowZoom: false, scaleWithZoom: false },
behaviors: ['click-select', 'drag-canvas', 'zoom-canvas'],
autoFit: { padding: 36 },
diff --git a/site/demos/docs-layout-networks.ts b/site/demos/docs-layout-networks.ts
index 513f91d6f..6f032bd68 100644
--- a/site/demos/docs-layout-networks.ts
+++ b/site/demos/docs-layout-networks.ts
@@ -1,15 +1,12 @@
-import { Graph, register, type LayoutConfig } from '@antv/g6-lite';
-import mds from '@antv/g6-lite/layouts/mds';
-import radial from '@antv/g6-lite/layouts/radial';
+import { Graph, type LayoutConfig } from '@antv/g6-lite';
+import { ConcentricLayout, MDSLayout, RadialLayout } from '@antv/layout';
import { createDemoPanel } from './demo-panel.ts';
export async function run(container: HTMLElement) {
- register('layout', 'mds', mds);
- register('layout', 'radial', radial);
// #region network-options
const layouts: Record = {
- radial: { type: 'radial', focusNode: '0', unitRadius: 68 },
- concentric: { type: 'concentric', sortBy: 'degree', nodeSize: 24 },
+ radial: { type: RadialLayout, focusNode: '0', unitRadius: 68 },
+ concentric: { type: ConcentricLayout, sortBy: 'degree', nodeSize: 24 },
force: { type: 'force', linkDistance: 100 },
'd3-force': { type: 'd3-force', linkDistance: 100 },
'force-atlas2': { type: 'force-atlas2', kr: 12, kg: 0.5, preventOverlap: true, nodeSize: 24, maxIteration: 200 },
@@ -22,7 +19,7 @@ export async function run(container: HTMLElement) {
maxIteration: 250,
minMovement: 0.05,
},
- mds: { type: 'mds', linkDistance: 80 },
+ mds: { type: MDSLayout, linkDistance: 80 },
};
// #endregion network-options
const connections = [
diff --git a/site/demos/docs-layout-result.ts b/site/demos/docs-layout-result.ts
index c4f849f3b..cfac3c09e 100644
--- a/site/demos/docs-layout-result.ts
+++ b/site/demos/docs-layout-result.ts
@@ -1,4 +1,5 @@
import { Graph, runLayout } from '@antv/g6-lite';
+import { DagreLayout } from '@antv/layout';
export async function run(container: HTMLElement) {
const data = {
@@ -9,7 +10,7 @@ export async function run(container: HTMLElement) {
{ source: 'Validate', target: 'Output' },
],
};
- const result = await runLayout(data, { type: 'dagre', rankdir: 'LR', ranksep: 72 }, { width: 600, height: 300 });
+ const result = await runLayout(data, { type: DagreLayout, rankdir: 'LR', ranksep: 72 }, { width: 600, height: 300 });
// No layout option on Graph: display the coordinates already computed above.
const graph = new Graph({
container,
diff --git a/site/demos/docs-layout-switch.ts b/site/demos/docs-layout-switch.ts
index 3a843fe9e..f6994735a 100644
--- a/site/demos/docs-layout-switch.ts
+++ b/site/demos/docs-layout-switch.ts
@@ -1,5 +1,8 @@
import { Graph, type FitViewOptions, type LayoutConfig } from '@antv/g6-lite';
import { createDemoPanel } from './demo-panel.ts';
+import { GridLayout } from '@antv/layout';
+import { CircularLayout } from '@antv/layout';
+import { DagreLayout } from '@antv/layout';
export function getFitOptions(): FitViewOptions {
return { padding: [56, 48, 76, 48] };
@@ -8,9 +11,9 @@ export function getFitOptions(): FitViewOptions {
export async function run(container: HTMLElement) {
// #region layout-options
const layouts: Record = {
- grid: { type: 'grid', rows: 2, cols: 3, width: 360, height: 160 },
- circular: { type: 'circular', radius: 100 },
- dagre: { type: 'dagre', rankdir: 'LR', nodesep: 64, ranksep: 96, nodeSize: 28 },
+ grid: { type: GridLayout, rows: 2, cols: 3, width: 360, height: 160 },
+ circular: { type: CircularLayout, radius: 100 },
+ dagre: { type: DagreLayout, rankdir: 'LR', nodesep: 64, ranksep: 96, nodeSize: 28 },
};
// #endregion layout-options
const graph = new Graph({
diff --git a/site/demos/docs-layout-tree.ts b/site/demos/docs-layout-tree.ts
index bfbd95072..c23cd7911 100644
--- a/site/demos/docs-layout-tree.ts
+++ b/site/demos/docs-layout-tree.ts
@@ -1,20 +1,15 @@
-import { Graph, register, type EdgeConfig, type GraphNode, type LayoutConfig } from '@antv/g6-lite';
-import indented from '@antv/g6-lite/layouts/indented';
-import mindmap from '@antv/g6-lite/layouts/mindmap';
-import fishbone from '@antv/g6-lite/layouts/fishbone';
+import { Graph, type EdgeConfig, type GraphNode, type LayoutConfig } from '@antv/g6-lite';
+import { FishboneLayout, IndentedLayout, MindmapLayout } from '@antv/layout';
import { createDemoPanel } from './demo-panel.ts';
export async function run(container: HTMLElement) {
- register('layout', 'indented', indented);
- register('layout', 'mindmap', mindmap);
- register('layout', 'fishbone', fishbone);
const nodeSize = 16;
const leftBranches = new Set(['A', 'C']);
// #region tree-layouts
const layouts = {
mindmap: {
layout: {
- type: 'mindmap',
+ type: MindmapLayout,
direction: 'H',
levelGap: 100,
nodeGap: 24,
@@ -25,12 +20,12 @@ export async function run(container: HTMLElement) {
edge: { type: 'line', style: { endArrow: false } },
},
indented: {
- layout: { type: 'indented', direction: 'LR', indent: 72, rowHeight: 30 },
+ layout: { type: IndentedLayout, direction: 'LR', indent: 72, rowHeight: 30 },
edge: { type: 'polyline', style: { router: 'indented', endArrow: false } },
},
fishbone: {
layout: {
- type: 'fishbone',
+ type: FishboneLayout,
direction: 'LR',
categoryGap: 156,
categoryDistance: 130,
diff --git a/site/demos/docs-layout-worker.ts b/site/demos/docs-layout-worker.ts
index 99deb473b..a63b1fe51 100644
--- a/site/demos/docs-layout-worker.ts
+++ b/site/demos/docs-layout-worker.ts
@@ -1,8 +1,9 @@
import { Graph, type LayoutConfig } from '@antv/g6-lite';
import { createDemoPanel } from './demo-panel.ts';
+import { GridLayout } from '@antv/layout';
export async function run(container: HTMLElement) {
- const grid: LayoutConfig = { type: 'grid', rows: 10, cols: 16, width: 400, height: 200, worker: false };
+ const grid: LayoutConfig = { type: GridLayout, rows: 10, cols: 16, width: 400, height: 200, worker: false };
const graph = new Graph({
container,
data: {
diff --git a/site/demos/docs-polyline-orth.ts b/site/demos/docs-polyline-orth.ts
index f3fab120c..c267fbe7e 100644
--- a/site/demos/docs-polyline-orth.ts
+++ b/site/demos/docs-polyline-orth.ts
@@ -1,10 +1,11 @@
import { Graph, type EdgeConfig, type LayoutConfig } from '@antv/g6-lite';
import { createDemoPanel } from './demo-panel.ts';
+import { DagreLayout } from '@antv/layout';
export async function run(container: HTMLElement) {
// #region routing
const layout = {
- type: 'dagre', rankdir: 'LR',
+ type: DagreLayout, rankdir: 'LR',
nodesep: 40, ranksep: 96, nodeSize: [84, 32],
} satisfies LayoutConfig;
const edge: EdgeConfig = {
diff --git a/site/demos/fishbone.ts b/site/demos/fishbone.ts
index c3bae47c1..a4c141a0d 100644
--- a/site/demos/fishbone.ts
+++ b/site/demos/fishbone.ts
@@ -1,8 +1,8 @@
/**
* Demo: 鱼骨图 (Fishbone/Ishikawa Diagram) — 盈利未达预期分析
*/
-import { Graph, register, type GraphEdge, type GraphNode } from '@antv/g6-lite';
-import fishbone from '@antv/g6-lite/layouts/fishbone';
+import { Graph, type GraphEdge, type GraphNode } from '@antv/g6-lite';
+import { FishboneLayout } from '@antv/layout';
import { attachLabelsCanvas, type GraphInstanceWithTools } from './tooling.ts';
const CATEGORY_COLORS = ['#E8684A', '#5B8FF9', '#5AD8A6', '#F6BD16', '#6F5EF9', '#5D7092'];
@@ -106,7 +106,6 @@ function getEdgeColor(_source: GraphNode, _target: GraphNode, edge: GraphEdge) {
}
export async function run(container: string | HTMLElement) {
- register('layout', 'fishbone', fishbone);
const wrapper = typeof container === 'string' ? document.querySelector(container)! as HTMLElement : container;
wrapper.style.position = 'relative';
@@ -116,7 +115,7 @@ export async function run(container: string | HTMLElement) {
data,
node: { type: 'rect', style: (n) => getNodeStyle(n) },
edge: { type: 'polyline', style: { stroke: getEdgeColor, lineWidth: 1.5, router: 'fishbone', endArrow: false, startArrow: false } },
- layout: { type: 'fishbone', direction: 'LR', categoryGap: 180, itemGap: 44, itemHStep: 50, categoryDistance: 200 },
+ layout: { type: FishboneLayout, direction: 'LR', categoryGap: 180, itemGap: 44, itemHStep: 50, categoryDistance: 200 },
behaviors: ['zoom-canvas', 'drag-canvas'],
theme: 'light',
});
diff --git a/site/demos/flowchart.ts b/site/demos/flowchart.ts
index 3f524b050..4d0e6e8bb 100644
--- a/site/demos/flowchart.ts
+++ b/site/demos/flowchart.ts
@@ -3,6 +3,7 @@
*/
import { Graph } from '@antv/g6-lite';
import { attachLabelsCanvas, attachEdgeLabelsCanvas, type GraphInstanceWithTools } from './tooling.ts';
+import { DagreLayout } from '@antv/layout';
const COLORS: Record = {
start: '#5B8FF9',
@@ -81,7 +82,7 @@ export async function run(container: string | HTMLElement) {
radius: 16,
},
},
- layout: { type: 'dagre', rankdir: 'TB', nodesep: 40, ranksep: 60, nodeSize: [180, 32] },
+ layout: { type: DagreLayout, rankdir: 'TB', nodesep: 40, ranksep: 60, nodeSize: [180, 32] },
behaviors: ['zoom-canvas', 'drag-canvas'],
theme: 'light',
});
diff --git a/site/demos/g6-v5-compat.ts b/site/demos/g6-v5-compat.ts
index f0ff20e1a..3d206535d 100644
--- a/site/demos/g6-v5-compat.ts
+++ b/site/demos/g6-v5-compat.ts
@@ -5,6 +5,7 @@
import { Graph, register, type NodeExtension } from '@antv/g6-lite';
import { createDemoPanel } from './demo-panel.ts';
+import { DagreLayout } from '@antv/layout';
const statusBadgeNode: NodeExtension = {
base: 'rect',
@@ -89,7 +90,7 @@ export async function run(container: string | HTMLElement) {
labelFontSize: 13,
},
},
- layout: { type: 'dagre', rankdir: 'LR', nodesep: 45, ranksep: 90, nodeSize: [96, 34] },
+ layout: { type: DagreLayout, rankdir: 'LR', nodesep: 45, ranksep: 90, nodeSize: [96, 34] },
behaviors: ['zoom-canvas', 'drag-canvas', 'drag-node', 'click-select', 'hover-highlight'],
});
diff --git a/site/demos/indented-tree.ts b/site/demos/indented-tree.ts
index d3bba892c..5db90d782 100644
--- a/site/demos/indented-tree.ts
+++ b/site/demos/indented-tree.ts
@@ -7,8 +7,8 @@
*
* 通过右上角菜单切换两种模式。
*/
-import { Graph, register } from '@antv/g6-lite';
-import indented from '@antv/g6-lite/layouts/indented';
+import { Graph } from '@antv/g6-lite';
+import { IndentedLayout } from '@antv/layout';
import { createDemoPanel } from './demo-panel.ts';
import { attachLabelsCanvas, type GraphInstanceWithTools } from './tooling.ts';
@@ -64,7 +64,7 @@ function measureTextWidth(text: string): number {
}
const layoutBase = {
- type: 'indented' as const,
+ type: IndentedLayout,
indent: 80,
rowHeight: 52,
direction: 'LR' as const,
@@ -146,7 +146,6 @@ function configMinimal() {
}
export async function run(container: string | HTMLElement) {
- register('layout', 'indented', indented);
const wrapper =
typeof container === 'string'
? (document.querySelector(container)! as HTMLElement)
diff --git a/site/demos/labels.ts b/site/demos/labels.ts
index 5777c8947..f814cf76f 100644
--- a/site/demos/labels.ts
+++ b/site/demos/labels.ts
@@ -3,6 +3,7 @@
*/
import { Graph, type GraphEdge, type GraphNode, type LabelPlacement } from '@antv/g6-lite';
import { createDemoPanel } from './demo-panel.ts';
+import { CircularLayout } from '@antv/layout';
const DATA = {
nodes: [
@@ -40,7 +41,7 @@ export async function run(container: string | HTMLElement) {
autoFit: true,
container: el,
data: DATA,
- layout: { type: 'circular', radius: 180 },
+ layout: { type: CircularLayout, radius: 180 },
behaviors: ['zoom-canvas', 'drag-canvas', 'drag-node'],
node: {
style: {
@@ -93,7 +94,7 @@ export async function run(container: string | HTMLElement) {
graph.updateOptions({ node: { style: { icon: iconsVisible ? iconForNode : false } } });
});
ui.addChoice('布局', ['circular', 'force'], 'circular', async (value) => {
- graph.setLayout(value === 'circular' ? { type: 'circular', radius: 180 } : { type: 'd3-force' });
+ graph.setLayout(value === 'circular' ? { type: CircularLayout, radius: 180 } : { type: 'd3-force' });
await graph.layout();
graph.fitView();
});
diff --git a/site/demos/layout-gallery.ts b/site/demos/layout-gallery.ts
index eee635c83..a58dbba0f 100644
--- a/site/demos/layout-gallery.ts
+++ b/site/demos/layout-gallery.ts
@@ -1,25 +1,20 @@
-import { Graph, register, type LayoutConfig } from '@antv/g6-lite';
-import mds from '@antv/g6-lite/layouts/mds';
-import radial from '@antv/g6-lite/layouts/radial';
-import random from '@antv/g6-lite/layouts/random';
+import { Graph, type LayoutConfig } from '@antv/g6-lite';
+import { ConcentricLayout, MDSLayout, RadialLayout, RandomLayout } from '@antv/layout';
import { createDemoPanel } from './demo-panel.ts';
const NODES = Array.from({ length: 18 }, (_, index) => ({ id: String(index), data: { label: String(index) } }));
const EDGES = Array.from({ length: 17 }, (_, index) => ({ id: `e-${index}`, source: String(Math.floor(index / 2)), target: String(index + 1) }));
const LAYOUTS: Array<{ label: string; config: LayoutConfig }> = [
- { label: 'Radial', config: { type: 'radial', unitRadius: 68, linkDistance: 60 } },
- { label: 'Concentric', config: { type: 'concentric', nodeSize: 28, minNodeSpacing: 18 } },
+ { label: 'Radial', config: { type: RadialLayout, unitRadius: 68, linkDistance: 60 } },
+ { label: 'Concentric', config: { type: ConcentricLayout, nodeSize: 28, minNodeSpacing: 18 } },
{ label: 'ForceAtlas2', config: { type: 'force-atlas2', maxIteration: 60, barnesHut: true, prune: false } },
{ label: 'Fruchterman', config: { type: 'fruchterman', maxIteration: 80, gravity: 8, speed: 5 } },
- { label: 'MDS', config: { type: 'mds', linkDistance: 70 } },
- { label: 'Random', config: { type: 'random' } },
+ { label: 'MDS', config: { type: MDSLayout, linkDistance: 70 } },
+ { label: 'Random', config: { type: RandomLayout } },
];
export async function run(container: string | HTMLElement) {
- register('layout', 'mds', mds);
- register('layout', 'radial', radial);
- register('layout', 'random', random);
const graph = new Graph({
autoFit: true,
container,
diff --git a/site/demos/layout-worker-cancel.ts b/site/demos/layout-worker-cancel.ts
index c6f2fb781..ffb7a17b1 100644
--- a/site/demos/layout-worker-cancel.ts
+++ b/site/demos/layout-worker-cancel.ts
@@ -1,5 +1,6 @@
import { Graph, type GraphData } from '@antv/g6-lite';
import { createDemoPanel } from './demo-panel.ts';
+import { GridLayout } from '@antv/layout';
function createData(): GraphData {
const nodes = Array.from({ length: 240 }, (_, index) => ({ id: String(index) }));
@@ -16,7 +17,7 @@ export async function run(container: string | HTMLElement) {
autoFit: true,
container,
data: createData(),
- layout: { type: 'grid', rows: 15, cols: 16 },
+ layout: { type: GridLayout, rows: 15, cols: 16 },
node: { style: { size: 7 } },
edge: { style: { stroke: '#cbd5e1', opacity: 0.45 } },
behaviors: ['zoom-canvas', 'drag-canvas'],
@@ -47,13 +48,13 @@ export async function run(container: string | HTMLElement) {
void runLayout({ type: 'force-atlas2', worker: true, maxIteration: 200, barnesHut: true, prune: false }, 'cancel test');
cancelTimer = window.setTimeout(() => {
graph.cancelLayout();
- void runLayout({ type: 'grid', rows: 15, cols: 16 }, 'cancelled → grid');
+ void runLayout({ type: GridLayout, rows: 15, cols: 16 }, 'cancelled → grid');
}, 20);
});
ui.addAction('恢复 Grid', () => {
clearTimeout(cancelTimer);
graph.cancelLayout();
- void runLayout({ type: 'grid', rows: 15, cols: 16 }, 'grid');
+ void runLayout({ type: GridLayout, rows: 15, cols: 16 }, 'grid');
});
ui.setStatus('grid ready');
diff --git a/site/demos/layouts.ts b/site/demos/layouts.ts
index bb976eeb9..8b197bce6 100644
--- a/site/demos/layouts.ts
+++ b/site/demos/layouts.ts
@@ -3,6 +3,9 @@
*/
import { Graph } from '@antv/g6-lite';
import { createDemoPanel } from './demo-panel.ts';
+import { CircularLayout } from '@antv/layout';
+import { GridLayout } from '@antv/layout';
+import { DagreLayout } from '@antv/layout';
const data = {
nodes: [
@@ -18,10 +21,10 @@ const data = {
};
const LAYOUTS = [
- { type: 'circular', radius: 180 },
+ { type: CircularLayout, radius: 180 },
{ type: 'force', linkDistance: 80 },
- { type: 'grid', rows: 2, cols: 5 },
- { type: 'dagre', rankdir: 'TB', nodesep: 30, ranksep: 40 },
+ { type: GridLayout, rows: 2, cols: 5 },
+ { type: DagreLayout, rankdir: 'TB', nodesep: 30, ranksep: 40 },
] as const;
export async function run(container: string | HTMLElement) {
diff --git a/site/demos/mindmap.ts b/site/demos/mindmap.ts
index 440a1203e..a852f1efb 100644
--- a/site/demos/mindmap.ts
+++ b/site/demos/mindmap.ts
@@ -1,8 +1,8 @@
/**
* Demo: 思维导图 (Mind Map) — 台风形成因素
*/
-import { Graph, register, type GraphEdge, type GraphNode } from '@antv/g6-lite';
-import mindmap from '@antv/g6-lite/layouts/mindmap';
+import { Graph, type GraphEdge, type GraphNode } from '@antv/g6-lite';
+import { MindmapLayout } from '@antv/layout';
import { attachLabelsCanvas, type GraphInstanceWithTools } from './tooling.ts';
const BRANCH_COLORS = ['#E8684A', '#5B8FF9', '#5AD8A6', '#F6BD16'];
@@ -118,7 +118,6 @@ function getEdgeColor(_source: GraphNode, _target: GraphNode, edge: GraphEdge) {
}
export async function run(container: string | HTMLElement) {
- register('layout', 'mindmap', mindmap);
const wrapper = typeof container === 'string' ? document.querySelector(container)! as HTMLElement : container;
wrapper.style.position = 'relative';
@@ -139,7 +138,7 @@ export async function run(container: string | HTMLElement) {
},
},
layout: {
- type: 'mindmap',
+ type: MindmapLayout,
direction: 'H',
levelGap: 120, // 缩短左右间距
nodeGap: 12,
diff --git a/site/demos/neighbor-highlight.ts b/site/demos/neighbor-highlight.ts
index 6bb40564d..43ceddf78 100644
--- a/site/demos/neighbor-highlight.ts
+++ b/site/demos/neighbor-highlight.ts
@@ -1,11 +1,10 @@
/**
* Demo: hover a node to highlight its neighbors, or an edge to highlight its endpoints.
*/
-import { Graph, register } from '@antv/g6-lite';
-import radial from '@antv/g6-lite/layouts/radial';
+import { Graph } from '@antv/g6-lite';
+import { RadialLayout } from '@antv/layout';
export async function run(container: string | HTMLElement) {
- register('layout', 'radial', radial);
const graph = new Graph({
autoFit: true,
container,
@@ -30,7 +29,7 @@ export async function run(container: string | HTMLElement) {
},
},
edge: { style: { stroke: '#C5CEDB', lineWidth: 2 } },
- layout: { type: 'radial', unitRadius: 120, linkDistance: 100 },
+ layout: { type: RadialLayout, unitRadius: 120, linkDistance: 100 },
behaviors: ['zoom-canvas', 'drag-canvas', 'highlight-node', 'highlight-edge'],
});
await graph.render();
diff --git a/site/demos/org-chart.ts b/site/demos/org-chart.ts
index f14ffe268..f02cc2b5e 100644
--- a/site/demos/org-chart.ts
+++ b/site/demos/org-chart.ts
@@ -3,6 +3,7 @@
*/
import { Graph } from '@antv/g6-lite';
import { attachLabelsCanvas, type GraphInstanceWithTools } from './tooling.ts';
+import { DagreLayout } from '@antv/layout';
const LEVEL_COLORS: Record = {
ceo: '#4A7DC0',
@@ -60,7 +61,7 @@ export async function run(container: string | HTMLElement) {
startArrow: false,
},
},
- layout: { type: 'dagre', rankdir: 'TB', nodesep: 50, ranksep: 80, nodeSize: [NODE_W, NODE_H] },
+ layout: { type: DagreLayout, rankdir: 'TB', nodesep: 50, ranksep: 80, nodeSize: [NODE_W, NODE_H] },
behaviors: ['zoom-canvas', 'drag-canvas'],
theme: 'light',
});
diff --git a/site/demos/polyline-routing.ts b/site/demos/polyline-routing.ts
index 083f0bcc5..df64d2cdd 100644
--- a/site/demos/polyline-routing.ts
+++ b/site/demos/polyline-routing.ts
@@ -2,6 +2,7 @@
* Demo: orthogonal polyline edges with rounded corners.
*/
import { Graph } from '@antv/g6-lite';
+import { DagreLayout } from '@antv/layout';
export async function run(container: string | HTMLElement) {
const graph = new Graph({
@@ -45,7 +46,7 @@ export async function run(container: string | HTMLElement) {
router: 'orth',
},
},
- layout: { type: 'dagre', rankdir: 'LR', nodesep: 28, ranksep: 72, nodeSize: [88, 36] },
+ layout: { type: DagreLayout, rankdir: 'LR', nodesep: 28, ranksep: 72, nodeSize: [88, 36] },
behaviors: ['zoom-canvas', 'drag-canvas'],
});
await graph.render();
diff --git a/site/demos/radial-tree.ts b/site/demos/radial-tree.ts
index ea17275a1..c0c362de6 100644
--- a/site/demos/radial-tree.ts
+++ b/site/demos/radial-tree.ts
@@ -1,8 +1,8 @@
/**
* Demo: a topic tree laid out with the radial algorithm.
*/
-import { Graph, register } from '@antv/g6-lite';
-import radial from '@antv/g6-lite/layouts/radial';
+import { Graph } from '@antv/g6-lite';
+import { RadialLayout } from '@antv/layout';
const TREE: Array<[string, string, string?]> = [
['root', '产品'],
@@ -18,7 +18,6 @@ const TREE: Array<[string, string, string?]> = [
];
export async function run(container: string | HTMLElement) {
- register('layout', 'radial', radial);
const graph = new Graph({
autoFit: { padding: 32 },
container,
@@ -35,7 +34,7 @@ export async function run(container: string | HTMLElement) {
},
},
edge: { style: { stroke: '#C5CEDB', lineWidth: 1.5 } },
- layout: { type: 'radial', unitRadius: 110, linkDistance: 90, nodeSize: 28 },
+ layout: { type: RadialLayout, unitRadius: 110, linkDistance: 90, nodeSize: 28 },
behaviors: ['zoom-canvas', 'drag-canvas'],
});
await graph.render();
diff --git a/site/demos/search-focus.ts b/site/demos/search-focus.ts
index cb43ebd23..003670495 100644
--- a/site/demos/search-focus.ts
+++ b/site/demos/search-focus.ts
@@ -3,6 +3,7 @@
*/
import { Graph } from '@antv/g6-lite';
import { createDemoPanel } from './demo-panel.ts';
+import { CircularLayout } from '@antv/layout';
const PEOPLE = [
'Alice',
@@ -44,7 +45,7 @@ export async function run(container: string | HTMLElement) {
labelPlacement: 'bottom',
},
},
- layout: { type: 'circular', radius: 180 },
+ layout: { type: CircularLayout, radius: 180 },
behaviors: ['zoom-canvas', 'drag-canvas'],
});
await graph.render();
diff --git a/site/demos/set-data.ts b/site/demos/set-data.ts
index 55f48a38c..03901885b 100644
--- a/site/demos/set-data.ts
+++ b/site/demos/set-data.ts
@@ -4,6 +4,8 @@
*/
import { Graph, type FitViewOptions } from '@antv/g6-lite';
import { createDemoPanel } from './demo-panel.ts';
+import { CircularLayout } from '@antv/layout';
+import { GridLayout } from '@antv/layout';
const DATA_A = {
nodes: [
@@ -57,7 +59,7 @@ export async function run(container: string | HTMLElement) {
autoFit: fit,
container: el,
data: DATA_A,
- layout: { type: 'circular', radius: 120 },
+ layout: { type: CircularLayout, radius: 120 },
behaviors: [
'zoom-canvas',
'drag-canvas',
@@ -87,9 +89,9 @@ export async function run(container: string | HTMLElement) {
ui.addChoice('布局', ['circular', 'grid', 'force'], 'circular', async (value) => {
log(`setLayout(${value}) + layout()`);
- if (value === 'grid') graph.setLayout({ type: 'grid' });
+ if (value === 'grid') graph.setLayout({ type: GridLayout });
else if (value === 'force') graph.setLayout({ type: 'd3-force' });
- else graph.setLayout({ type: 'circular', radius: 150 });
+ else graph.setLayout({ type: CircularLayout, radius: 150 });
await graph.layout();
graph.fitView(fit);
log(`${value} done`);
diff --git a/site/demos/shapes.ts b/site/demos/shapes.ts
index 2bee7b215..16497b1a4 100644
--- a/site/demos/shapes.ts
+++ b/site/demos/shapes.ts
@@ -2,6 +2,7 @@
* Demo: 混合图形 — 矩形节点 + 弧线边 + 粗线边
*/
import { Graph } from '@antv/g6-lite';
+import { CircularLayout } from '@antv/layout';
export async function run(container: string | HTMLElement) {
// --- Rect nodes with arc edges ---
@@ -50,7 +51,7 @@ export async function run(container: string | HTMLElement) {
curvature: 0.25,
},
},
- layout: { type: 'circular', radius: 48 },
+ layout: { type: CircularLayout, radius: 48 },
behaviors: ['zoom-canvas', 'drag-canvas', 'highlight-node', 'highlight-edge'],
theme: 'light',
});
@@ -92,7 +93,7 @@ export async function run(container: string | HTMLElement) {
lineWidth: 3,
},
},
- layout: { type: 'circular', radius: 48 },
+ layout: { type: CircularLayout, radius: 48 },
behaviors: ['zoom-canvas', 'drag-canvas', 'highlight-node', 'highlight-edge'],
theme: 'light',
});
diff --git a/site/demos/theme.ts b/site/demos/theme.ts
index 04b1e4a98..3b5d21fb1 100644
--- a/site/demos/theme.ts
+++ b/site/demos/theme.ts
@@ -3,6 +3,7 @@
*/
import { Graph } from '@antv/g6-lite';
import { createDemoPanel } from './demo-panel.ts';
+import { CircularLayout } from '@antv/layout';
const data = {
nodes: [{ id: '0' }, { id: '1' }, { id: '2' }, { id: '3' }, { id: '4' }],
@@ -35,7 +36,7 @@ export async function run(container: string | HTMLElement) {
data,
node: { type: 'circle', style: { size: 14 } },
edge: { type: 'line' },
- layout: { type: 'circular', radius: 120 },
+ layout: { type: CircularLayout, radius: 120 },
behaviors: ['zoom-canvas', 'drag-canvas'],
theme: themeOption,
});
diff --git a/site/next.config.mjs b/site/next.config.mjs
index 2ed5335dd..f50acada8 100644
--- a/site/next.config.mjs
+++ b/site/next.config.mjs
@@ -24,12 +24,6 @@ const config = {
'./layoutWorker.js': '../src/layout/layoutWorker.ts',
// Examples live in site/demos and import the library by package name, so
// point that name at the TypeScript source instead of the built dist.
- '@antv/g6-lite/layouts/mds': '../src/layout/optional/mds.ts',
- '@antv/g6-lite/layouts/radial': '../src/layout/optional/radial.ts',
- '@antv/g6-lite/layouts/indented': '../src/layout/optional/indented.ts',
- '@antv/g6-lite/layouts/mindmap': '../src/layout/optional/mindmap.ts',
- '@antv/g6-lite/layouts/fishbone': '../src/layout/optional/fishbone.ts',
- '@antv/g6-lite/layouts/random': '../src/layout/optional/random.ts',
'@antv/g6-lite': '../src/index.ts',
},
},
diff --git a/site/src/components/homepage/bundle-measurement.json b/site/src/components/homepage/bundle-measurement.json
index 25c410e02..ac412e19d 100644
--- a/site/src/components/homepage/bundle-measurement.json
+++ b/site/src/components/homepage/bundle-measurement.json
@@ -1,12 +1,9 @@
{
"version": "0.1.0",
- "measuredAt": "2026-11-24",
- "gzipBytes": 150304,
+ "measuredAt": "2026-11-27",
+ "gzipBytes": 118214,
"unitBytes": 1000,
"entry": "dist/g6-lite.min.js",
"compression": "Gzip -9",
- "source": "https://registry.npmjs.org/@antv/g6-lite/-/g6-lite-0.1.0.tgz",
- "integrity": "sha512-o3NWidrTaTEAA4RiNd56NDQOgTizoPtHwCQl6aoxipkJYk2pwnPI7d34E8LcC4UX0u6DgeyIYG8OclVBlWWI4Q==",
- "gitHead": "448fc17d278693cb6bbe1886d78d43b2f4bab407",
- "command": "gzip -9 -c package/dist/g6-lite.min.js | wc -c"
+ "command": "gzip -9 -c dist/g6-lite.min.js | wc -c"
}
diff --git a/site/src/components/homepage/example-showcase.tsx b/site/src/components/homepage/example-showcase.tsx
index f5c8a0051..ebac5dd13 100644
--- a/site/src/components/homepage/example-showcase.tsx
+++ b/site/src/components/homepage/example-showcase.tsx
@@ -10,19 +10,9 @@ import { CopyPrompt } from '@/components/ai-skill/copy-prompt';
import { localizedPath, type Locale } from '@/lib/i18n';
import type { HomepageShowcaseCopy } from './content';
import styles from './homepage.module.css';
-import {
- getShowcaseOptionalLayout,
- showcaseIds,
- type ShowcaseCode,
- type ShowcaseId,
-} from './showcase-catalog';
+import { showcaseIds, type ShowcaseCode, type ShowcaseId } from './showcase-catalog';
import { loadShowcaseCode } from './showcase-code-loader';
-const layoutLoaders = {
- mindmap: () => import('@antv/g6-lite/layouts/mindmap'),
- fishbone: () => import('@antv/g6-lite/layouts/fishbone'),
-};
-
const subscribeNoop = () => () => {};
export function ExampleShowcase({
@@ -80,14 +70,11 @@ export function ExampleShowcase({
const start = async () => {
setStatus('loading');
try {
- const layout = getShowcaseOptionalLayout(active);
- const [{ Graph, register }, runtime, layoutModule] = await Promise.all([
+ const [{ Graph }, runtime] = await Promise.all([
import('../../../../src/index.ts'),
import('./showcase-examples'),
- layout && layoutLoaders[layout](),
]);
if (disposed) return;
- if (layout && layoutModule) register('layout', layout, layoutModule.default);
graph = new Graph({ container: mount, ...runtime.showcaseOptions(active, locale, dark) });
graphRef.current = graph;
await graph.render();
diff --git a/site/src/components/homepage/showcase-code.server.ts b/site/src/components/homepage/showcase-code.server.ts
index ddaa74df9..8dd25b494 100644
--- a/site/src/components/homepage/showcase-code.server.ts
+++ b/site/src/components/homepage/showcase-code.server.ts
@@ -4,7 +4,6 @@ import { codeToHtml } from 'shiki';
import type { Locale } from '@/lib/i18n';
import type { ShowcaseCode, ShowcaseId, ShowcaseTheme } from './showcase-catalog';
import { showcaseOptions } from './showcase-examples';
-import { getShowcaseOptionalLayout } from './showcase-catalog';
/** Highlight at build time; the browser receives one selected source and markup. */
export async function createShowcaseCode(
@@ -23,6 +22,9 @@ export function showcaseSource(id: ShowcaseId, locale: Locale, dark = false): st
const config = JSON.stringify(
options,
(key, value) => {
+ if (key === 'type' && typeof value === 'function' && value.name) {
+ return `__layout_class_${value.name}__`;
+ }
if (typeof value !== 'function') return value;
const token = `__showcase_callback_${callbacks.length}__`;
let source = value.toString();
@@ -40,15 +42,15 @@ export function showcaseSource(id: ShowcaseId, locale: Locale, dark = false): st
2,
)
.replace(/"__showcase_callback_(\d+)__"/g, (_match, index) => callbacks[Number(index)])
+ .replace(/"__layout_class_(\w+)__"/g, '$1')
.slice(2, -2);
const nodes = data.nodes.map((node) => ` ${JSON.stringify(node)}`).join(',\n');
const edges = data.edges.map((edge) => ` ${JSON.stringify(edge)}`).join(',\n');
- const layout = getShowcaseOptionalLayout(id);
- const imports = layout
- ? `import { Graph, register } from '@antv/g6-lite';
-import ${layout} from '@antv/g6-lite/layouts/${layout}';
-
-register('layout', '${layout}', ${layout});`
+ const layoutType = typeof options.layout === 'object' ? options.layout?.type : undefined;
+ const layoutClass = typeof layoutType === 'function' ? layoutType.name : undefined;
+ const imports = layoutClass
+ ? `import { Graph } from '@antv/g6-lite';
+import { ${layoutClass} } from '@antv/layout';`
: "import { Graph } from '@antv/g6-lite';";
return `${imports}
diff --git a/site/src/components/homepage/showcase-examples.ts b/site/src/components/homepage/showcase-examples.ts
index 2d6142a2a..3b5ef7a78 100644
--- a/site/src/components/homepage/showcase-examples.ts
+++ b/site/src/components/homepage/showcase-examples.ts
@@ -1,3 +1,4 @@
+import { DagreLayout, FishboneLayout, MindmapLayout } from '@antv/layout';
import type { Graph, GraphNode, GraphOptions } from '../../../../src/index.ts';
import type { Locale } from '@/lib/i18n';
@@ -183,7 +184,7 @@ export function showcaseOptions(id: ShowcaseId, locale: Locale, dark = false): O
[2, 6],
];
options.layout = {
- type: 'dagre',
+ type: DagreLayout,
rankdir: 'TB',
nodesep: 32,
ranksep: 70,
@@ -214,7 +215,7 @@ export function showcaseOptions(id: ShowcaseId, locale: Locale, dark = false): O
[4, 8],
];
options.layout = {
- type: 'mindmap',
+ type: MindmapLayout,
direction: 'H',
levelGap: 40,
nodeGap: 120,
@@ -239,7 +240,7 @@ export function showcaseOptions(id: ShowcaseId, locale: Locale, dark = false): O
[4, 8],
];
options.layout = {
- type: 'fishbone',
+ type: FishboneLayout,
direction: 'LR',
categoryGap: 110,
categoryDistance: 100,
diff --git a/site/src/lib/node-doc-example-source.ts b/site/src/lib/node-doc-example-source.ts
index 4689ce6a6..230d74334 100644
--- a/site/src/lib/node-doc-example-source.ts
+++ b/site/src/lib/node-doc-example-source.ts
@@ -2,6 +2,19 @@ import { readFileSync } from 'node:fs';
import path from 'node:path';
import type { BuiltInLayoutExample } from '../../demos/docs-built-in-layout.ts';
+const LAYOUT_CLASSES: Record = {
+ grid: 'GridLayout',
+ circular: 'CircularLayout',
+ dagre: 'DagreLayout',
+ concentric: 'ConcentricLayout',
+ radial: 'RadialLayout',
+ mds: 'MDSLayout',
+ indented: 'IndentedLayout',
+ mindmap: 'MindmapLayout',
+ fishbone: 'FishboneLayout',
+ random: 'RandomLayout',
+};
+
type RegisteredNodeDocExampleId = Exclude;
export type NodeDocExampleId = 'demo-drag-canvas' | 'demo-click-select' | 'demo-brush-select' | 'demo-lasso-select' | 'demo-highlight-node' | 'demo-highlight-edge' | 'behavior-drag-node' | 'behavior-drag-edge' | 'behavior-zoom-pan' | 'built-in-layout' | 'graph-options' | 'parallel-workflow' | 'self-loops' | 'extension-plugin' | 'extension-transform' | 'extension-layout' | 'extension-decoration' | 'extension-label' | 'extension-edge' | 'extension-node' | 'polyline-orth' | 'body' | 'style' | 'labels' | 'node-icons' | 'label-options' | 'badges' | 'edge-style' | 'edge-hit-area' | 'edge-parallel' | 'edge-curves' | 'edge-cubic' | 'edge-orth' | 'edge-indented' | 'edge-labels' | 'combo-data' | 'combo-style' | 'combo-collapsed' | 'combo-states' | 'combo-membership' | 'label-policy' | 'theme-switch' | 'theme-precedence' | 'layout-switch' | 'layout-networks' | 'layout-tree' | 'layout-worker' | 'layout-result' | 'behavior-switch' | 'behavior-selection' | 'behavior-highlight' | 'behavior-custom' | 'behavior-tooltip' | 'behavior-tooltip-hover' | 'events-listen' | 'events-lifecycle' | 'state-concept' | 'state-preserve' | 'viewport-concept' | 'viewport-preserve' | 'state-visibility' | 'viewport-resize' | 'viewport-zoom-to' | 'viewport-zoom-by' | 'graph-lifecycle' | 'data-workflow' | 'combo-operations' | 'dependency-graph' | 'node-halo' | 'node-updates' | 'breathing-node' | 'edge-state-styles' | 'edge-updates' | 'edge-arrows' | 'edge-dashes';
@@ -122,9 +135,8 @@ export function readBuiltInLayoutExample(type: BuiltInLayoutExample) {
? 'arrangement'
: 'network';
const [mainImport] = source.split('\n');
- const layoutImport = source.split('\n').find((line) => line.endsWith(`'@antv/g6-lite/layouts/${type}';`));
- const layoutName = layoutImport?.split(' ')[1];
- const registration = layoutName ? ` register('layout', '${type}', ${layoutName});\n` : '';
+ const layoutClass = LAYOUT_CLASSES[type];
+ const layoutImport = layoutClass ? `import { ${layoutClass} } from '@antv/layout';` : undefined;
const code = [
type === 'mindmap' ? mainImport : mainImport.replace(', type GraphNode', ''),
...(layoutImport ? [layoutImport] : []),
@@ -132,12 +144,11 @@ export function readBuiltInLayoutExample(type: BuiltInLayoutExample) {
getNodeDocExampleSnippet(source, dataRegion),
getNodeDocExampleSnippet(source, 'render'),
`export function run(container: HTMLElement) {
-${registration} const layout: LayoutConfig = ${config.replaceAll('\n', '\n ')};
- return render(container, layout, ${dataRegion}(${dedicatedExample ? '' : 'layout.type'}));
+ const layout: LayoutConfig = ${config.replaceAll('\n', '\n ')};
+ return render(container, layout, ${dataRegion}(${dedicatedExample ? '' : `'${type}'`}));
}`,
].join('\n\n');
- const registrationImport = layoutImport ? "import { register } from '@antv/g6-lite';" : undefined;
- const excerpt = [registrationImport, layoutImport, registration.trim(), `const layout = ${config};`].filter(Boolean).join('\n\n');
+ const excerpt = [layoutImport, `const layout = ${config};`].filter(Boolean).join('\n\n');
return { code, excerpt: type === 'fishbone' ? `${excerpt}\n\n${getNodeDocExampleSnippet(source, 'edge-router')}` : excerpt };
}
diff --git a/site/src/lib/playground-runtime.ts b/site/src/lib/playground-runtime.ts
index e6fa12715..c0976f47d 100644
--- a/site/src/lib/playground-runtime.ts
+++ b/site/src/lib/playground-runtime.ts
@@ -11,30 +11,17 @@ interface SiteExampleModule {
run(container: string | HTMLElement): Promise;
}
-const layoutModules = {
- '@antv/g6-lite/layouts/mds': () => import('@antv/g6-lite/layouts/mds'),
- '@antv/g6-lite/layouts/radial': () => import('@antv/g6-lite/layouts/radial'),
- '@antv/g6-lite/layouts/indented': () => import('@antv/g6-lite/layouts/indented'),
- '@antv/g6-lite/layouts/mindmap': () => import('@antv/g6-lite/layouts/mindmap'),
- '@antv/g6-lite/layouts/fishbone': () => import('@antv/g6-lite/layouts/fishbone'),
- '@antv/g6-lite/layouts/random': () => import('@antv/g6-lite/layouts/random'),
-};
-
async function loadExternals(code: string): Promise> {
- const [g6, demoPanel, tooling, lilGui] = await Promise.all([
+ const [g6, layout, demoPanel, tooling, lilGui] = await Promise.all([
import('@antv/g6-lite'),
+ import('@antv/layout'),
import('../../demos/demo-panel.ts'),
import('../../demos/tooling.ts'),
import('lil-gui'),
]);
- const layouts = await Promise.all(
- Object.entries(layoutModules)
- .filter(([name]) => code.includes(`'${name}'`) || code.includes(`"${name}"`))
- .map(async ([name, load]) => [name, await load()] as const),
- );
return {
- ...Object.fromEntries(layouts),
'@antv/g6-lite': g6,
+ '@antv/layout': layout,
'lil-gui': lilGui,
'./demo-panel.ts': demoPanel,
'./demo-panel': demoPanel,
diff --git a/site/src/lib/quick-start.ts b/site/src/lib/quick-start.ts
index f3758356e..2ba2c36fe 100644
--- a/site/src/lib/quick-start.ts
+++ b/site/src/lib/quick-start.ts
@@ -1,3 +1,4 @@
+import { CircularLayout } from '@antv/layout';
import type { GraphData, GraphOptions } from '../../../src/index.ts';
/** Immutable data replacements for the framework update example. */
@@ -76,7 +77,7 @@ export function quickStartOptions(): Omit {
},
},
edge: { style: { endArrow: true } },
- layout: { type: 'circular', radius: 120 },
+ layout: { type: CircularLayout, radius: 120 },
autoFit: { padding: 32 },
behaviors: ['zoom-canvas', 'drag-canvas', 'drag-node', 'hover-highlight'],
};
diff --git a/site/tsconfig.json b/site/tsconfig.json
index 4f80b9aaf..3da7c401b 100644
--- a/site/tsconfig.json
+++ b/site/tsconfig.json
@@ -26,24 +26,6 @@
"@antv/g6-lite": [
"../src/index.ts"
],
- "@antv/g6-lite/layouts/mds": [
- "../src/layout/optional/mds.ts"
- ],
- "@antv/g6-lite/layouts/radial": [
- "../src/layout/optional/radial.ts"
- ],
- "@antv/g6-lite/layouts/indented": [
- "../src/layout/optional/indented.ts"
- ],
- "@antv/g6-lite/layouts/mindmap": [
- "../src/layout/optional/mindmap.ts"
- ],
- "@antv/g6-lite/layouts/fishbone": [
- "../src/layout/optional/fishbone.ts"
- ],
- "@antv/g6-lite/layouts/random": [
- "../src/layout/optional/random.ts"
- ],
"collections/*": [
"./.source/*"
]
diff --git a/skills/antv-g6lite-graph/SKILL.md b/skills/antv-g6lite-graph/SKILL.md
index 1076bdc76..ccac9437b 100644
--- a/skills/antv-g6lite-graph/SKILL.md
+++ b/skills/antv-g6lite-graph/SKILL.md
@@ -48,6 +48,7 @@ In bundled applications, use ESM:
```ts
import { Graph } from '@antv/g6-lite';
+import { DagreLayout } from '@antv/layout';
const graph = new Graph({
container: '#container',
@@ -56,7 +57,7 @@ const graph = new Graph({
edges: [{ id: 'a-b', source: 'a', target: 'b' }],
},
node: { style: { label: (node) => node.name ?? node.id } },
- layout: { type: 'dagre', rankdir: 'LR', ranksep: 80 },
+ layout: { type: DagreLayout, rankdir: 'LR', ranksep: 80 },
behaviors: ['zoom-canvas', 'drag-canvas', 'drag-node', 'hover-highlight'],
});
await graph.render();
@@ -67,7 +68,7 @@ The container must already exist, have nonzero width/height, and use `position:
## Contract details that prevent common failures
-- Import runtime APIs from the package root or documented exports such as `@antv/g6-lite/layouts/mindmap`. Do not deep-import source or distribution internals in application code; CDN browser distribution URLs are separate.
+- Import runtime APIs from the package root. Import layout classes such as `MindmapLayout` from `@antv/layout`. Do not deep-import source or distribution internals in application code; CDN browser distribution URLs are separate.
- Nodes need unique string IDs and edges must reference existing node IDs. Give edges stable explicit IDs when selection or updates must survive data replacement.
- Node borders use `node.style.strokeWidth`; labels use `node.style.label`, `labelColor`, `labelFontSize`, and `labelPlacement`. Do not use nested `node.label` objects.
- Arrows use `edge.style.endArrow: true` and `arrowSize: 6`; `startArrow` is also boolean. Arrow objects such as `{ fill, size }` are unsupported and can cause rendering errors during dragging in 0.1.0.
diff --git a/skills/antv-g6lite-graph/references/layouts.md b/skills/antv-g6lite-graph/references/layouts.md
index d80b03307..b0853f35d 100644
--- a/skills/antv-g6lite-graph/references/layouts.md
+++ b/skills/antv-g6lite-graph/references/layouts.md
@@ -6,27 +6,26 @@ Choose by the question the graph should answer, then tune against actual node si
| Need | Layout | Useful starting options | Loading |
| --- | --- | --- | --- |
-| Stable overview, compare groups | `circular`, `grid` | `radius: 140`; `cols: 4` | Built in |
-| Dependency/flow direction | `dagre` | `rankdir: 'LR', ranksep: 100, nodesep: 48` | Built in |
| General relationship network | `force`, `d3-force` | `linkDistance: 100` | Built in |
| Network clusters | `force-atlas2`, `fruchterman` | Tune forces and iteration budget using the algorithm docs | Built in |
-| Rank nodes in rings | `concentric` | `sortBy: 'degree'` | Built in |
-| Focus-node distance rings | `radial` | `focusNode: 'root', unitRadius: 80` | Optional, register first |
-| Distance-based overview | `mds` | `linkDistance: 80` | Optional, register first |
-| Mind map | `mindmap` | `direction: 'H', levelGap: 140, nodeGap: 32` | Optional, register first |
-| Directory tree | `indented` | `indent: 100, rowHeight: 44` | Optional, register first |
-| Cause/category tree | `fishbone` | `categoryGap: 180` | Optional, register first |
-| Random initial positions | `random` | `width: 800, height: 600` | Optional, register first |
+| Stable overview, compare groups | `CircularLayout`, `GridLayout` | `radius: 140`; `cols: 4` | Import from `@antv/layout` |
+| Dependency/flow direction | `DagreLayout` | `rankdir: 'LR', ranksep: 100, nodesep: 48` | Import from `@antv/layout` |
+| Rank nodes in rings | `ConcentricLayout` | `sortBy: 'degree'` | Import from `@antv/layout` |
+| Focus-node distance rings | `RadialLayout` | `focusNode: 'root', unitRadius: 80` | Import from `@antv/layout` |
+| Distance-based overview | `MDSLayout` | `linkDistance: 80` | Import from `@antv/layout` |
+| Mind map | `MindmapLayout` | `direction: 'H', levelGap: 140, nodeGap: 32` | Import from `@antv/layout` |
+| Directory tree | `IndentedLayout` | `indent: 100, rowHeight: 44` | Import from `@antv/layout` |
+| Cause/category tree | `FishboneLayout` | `categoryGap: 180` | Import from `@antv/layout` |
+| Random initial positions | `RandomLayout` | `width: 800, height: 600` | Import from `@antv/layout` |
These are starting points, not universal spacing rules. Force-layout options differ by algorithm; do not copy option names between them unchecked. Tree layouts expect a meaningful root-to-child edge structure. Validate multiple parents, cycles, and disconnected roots before presenting arbitrary network data as a tree.
-## npm: import and register an optional layout
+## npm: import a layout class from @antv/layout
```ts
-import { Graph, register } from '@antv/g6-lite';
-import mindmap from '@antv/g6-lite/layouts/mindmap';
+import { Graph } from '@antv/g6-lite';
+import { MindmapLayout } from '@antv/layout';
-register('layout', 'mindmap', mindmap);
const graph = new Graph({
container: '#container',
data: {
@@ -40,7 +39,7 @@ const graph = new Graph({
{ id: 'root-verify', source: 'root', target: 'verify' },
],
},
- layout: { type: 'mindmap', direction: 'H', levelGap: 140, nodeGap: 32 },
+ layout: { type: MindmapLayout, direction: 'H', levelGap: 140, nodeGap: 32 },
node: {
type: 'rect',
style: { width: 100, height: 36, label: (node) => node.name ?? node.id },
@@ -51,31 +50,34 @@ const graph = new Graph({
await graph.render();
```
-The same pattern applies to documented subpaths `layouts/mds`, `layouts/radial`, `layouts/indented`, `layouts/fishbone`, and `layouts/random`.
+The same pattern applies to `CircularLayout`, `GridLayout`, `DagreLayout`, `ConcentricLayout`, `RadialLayout`, `MDSLayout`, `IndentedLayout`, `FishboneLayout`, and `RandomLayout`. Built-in layouts (`force`, `force-atlas2`, `d3-force`, `fruchterman`) use string names without an import.
-## CDN: load the companion bundle from the same release
+## CDN: use built-in layouts or load @antv/layout separately
-The default main entry is `https://unpkg.com/@antv/g6-lite`. Optional layouts additionally need `dist/g6-lite-layouts.min.js`, exposing `window.G6LiteLayouts`. Then call `G6Lite.register('layout', 'mindmap', G6LiteLayouts.mindmap)` before rendering.
+The UMD main entry `https://unpkg.com/@antv/g6-lite` includes the four built-in force-directed layouts. For other layouts, load `@antv/layout` from a CDN and pass the layout class:
-For a generated example using optional layouts, resolve `latest` once during authoring, then use the resulting version for both scripts. This fetch can run in the authoring terminal or JavaScript tool; it is not needed on every page visit:
-
-```js
-const response = await fetch('https://unpkg.com/@antv/g6-lite/package.json');
-if (!response.ok) throw new Error(`Package lookup failed: ${response.status}`);
-const { version } = await response.json();
-const base = `https://unpkg.com/@antv/g6-lite@${version}/dist`;
-console.log(``);
-console.log(``);
+```html
+
+
+
```
-Insert those two actual script tags, in order, before the graph's initialization script. Reuse the mindmap data/configuration above through `window.G6Lite` and register with `window.G6LiteLayouts`. Do not leave template version markers in the delivered HTML. When offline, use the user's known release or installed version and disclose that remote availability was not checked.
+Resolve one version for all scripts rather than independently resolving `latest` during a release.
## Relayout and fitting
After initialization:
```ts
-graph.setLayout({ type: 'dagre', rankdir: 'LR', ranksep: 100 });
+import { DagreLayout } from '@antv/layout';
+
+graph.setLayout({ type: DagreLayout, rankdir: 'LR', ranksep: 100 });
await graph.layout();
if (!graph.destroyed) graph.fitView({ padding: 48 });
```
@@ -85,7 +87,7 @@ if (!graph.destroyed) graph.fitView({ padding: 48 });
## Workers and scale
- Built-in library layouts may attempt a Worker at 1,000 nodes when `worker` is omitted. `worker: true` requests a Worker; `worker: false` disables the attempt.
-- Registered layouts, including the six optional layouts, execute on the main thread. `worker: true` does not move registered extension code.
+- Custom layout classes, including tree layouts imported from `@antv/layout`, execute on the main thread. `worker: true` does not move custom layout code.
- Worker configuration and transferred data must be structured-cloneable. Use `worker: false` when algorithm callbacks are required. Node/edge rendering style callbacks are separate from layout configuration.
- Creation, loading, transfer, or computation failures can fall back to the main thread. Confirm Worker requests and execution threads; neither `worker: true` nor successful layout proves off-thread computation.
- Keep emitted ESM Worker assets and relative paths. UMD does not guarantee standalone Worker assets; prefer bundled ESM when off-thread execution is required.
diff --git a/skills/antv-g6lite-graph/references/templates/react-graph.tsx b/skills/antv-g6lite-graph/references/templates/react-graph.tsx
index 07a6552fd..9c3c7dc24 100644
--- a/skills/antv-g6lite-graph/references/templates/react-graph.tsx
+++ b/skills/antv-g6lite-graph/references/templates/react-graph.tsx
@@ -2,6 +2,7 @@
import { useEffect, useRef, useState } from 'react';
import { Graph, type GraphData, type NodeGraphEvent } from '@antv/g6-lite';
+import { DagreLayout } from '@antv/layout';
type Props = {
data: GraphData;
@@ -48,7 +49,7 @@ export function RelationshipGraph({ data, onNodeClick }: Props) {
style: { stroke: '#94a3b8', endArrow: true, arrowSize: 6 },
stateStyles: { inactive: { opacity: 0.15 } },
},
- layout: { type: 'dagre', rankdir: 'LR', ranksep: 100 },
+ layout: { type: DagreLayout, rankdir: 'LR', ranksep: 100 },
behaviors: [
'zoom-canvas',
'drag-canvas',
diff --git a/skills/antv-g6lite-graph/references/templates/standalone.html b/skills/antv-g6lite-graph/references/templates/standalone.html
index 24d366453..8d2951920 100644
--- a/skills/antv-g6lite-graph/references/templates/standalone.html
+++ b/skills/antv-g6lite-graph/references/templates/standalone.html
@@ -138,7 +138,7 @@ Service dependencies
inactive: { opacity: 0.15 },
},
},
- layout: { type: 'dagre', rankdir: 'LR', ranksep: 120, nodesep: 64 },
+ layout: { type: 'force', linkDistance: 120 },
behaviors: [
'zoom-canvas',
'drag-canvas',
diff --git a/src/graph.ts b/src/graph.ts
index 2a7d14e27..a19ed6e6f 100644
--- a/src/graph.ts
+++ b/src/graph.ts
@@ -42,6 +42,7 @@ import type {
GraphOptions,
InternalCombo,
LayoutConfig,
+ LayoutConstructor,
LayoutNode,
NodeDataUpdate,
NodeModel,
@@ -919,7 +920,7 @@ export class Graph {
/**
* Set the layout configuration. Does not execute layout — call layout() after.
*/
- setLayout(config: LayoutConfig): void {
+ setLayout(config: LayoutConfig | LayoutConstructor): void {
if (this._destroyed) return;
this.options.layout = config;
}
@@ -1408,9 +1409,12 @@ export class Graph {
private resolveEffectiveLayout(nodeCount: number): LayoutConfig | undefined {
const layout = this.options.layout;
if (!layout) return undefined;
- return layout.worker === undefined && nodeCount >= 1000
- ? { ...layout, worker: true }
- : { ...layout };
+ const config: LayoutConfig = typeof layout === 'function' ? { type: layout } : layout;
+ // Custom layout classes cannot run in a Worker; only string-named built-ins
+ // get the automatic Worker default for large graphs.
+ return config.worker === undefined && nodeCount >= 1000 && typeof config.type === 'string'
+ ? { ...config, worker: true }
+ : { ...config };
}
private getCurrentLayoutNodes(): LayoutNode[] {
@@ -1457,14 +1461,16 @@ export class Graph {
private createDataModel(theme: ReturnType): DataModel {
const { node, edge, layout } = this.options;
+ const layoutConfig = typeof layout === 'function' ? undefined : layout;
const layoutDirection =
- ((layout?.rankdir ?? layout?.direction) as ('TB' | 'LR' | 'BT' | 'RL') | undefined) ?? 'TB';
+ ((layoutConfig?.rankdir ?? layoutConfig?.direction) as
+ ('TB' | 'LR' | 'BT' | 'RL') | undefined) ?? 'TB';
return new DataModel({
nodeConfig: node,
edgeConfig: edge,
theme,
layoutDirection,
- layoutType: layout?.type,
+ layoutType: typeof layoutConfig?.type === 'string' ? layoutConfig.type : undefined,
polylineRouter: edge?.style?.router ?? 'orth',
});
}
diff --git a/src/index.ts b/src/index.ts
index f6a8ab96f..536d4f2f5 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -81,6 +81,8 @@ export type {
LabelRenderer,
LabelType,
LayoutConfig,
+ LayoutConstructor,
+ LayoutInstance,
NodeBadgeItem,
NodeBadgeKind,
NodeConfig,
diff --git a/src/layout/builtinLayouts.ts b/src/layout/builtinLayouts.ts
new file mode 100644
index 000000000..72743354b
--- /dev/null
+++ b/src/layout/builtinLayouts.ts
@@ -0,0 +1,13 @@
+import { D3ForceLayout, ForceAtlas2Layout, ForceLayout, FruchtermanLayout } from '@antv/layout';
+import type { LayoutConstructor } from '../types';
+
+/**
+ * Built-in layouts bundled with G6Lite, focused on large-scale graph analysis.
+ * Other @antv/layout algorithms can be passed directly as `layout.type`.
+ */
+export const BUILTIN_LAYOUTS: Record = {
+ force: ForceLayout,
+ 'force-atlas2': ForceAtlas2Layout,
+ 'd3-force': D3ForceLayout,
+ fruchterman: FruchtermanLayout,
+};
diff --git a/src/layout/fishboneLayout.ts b/src/layout/fishboneLayout.ts
deleted file mode 100644
index 7e55f346c..000000000
--- a/src/layout/fishboneLayout.ts
+++ /dev/null
@@ -1,154 +0,0 @@
-/**
- * Fishbone Layout (Ishikawa Diagram)
- * Two-level tree: head -> categories -> items
- *
- * Spine geometry (LR direction):
- * - Spine anchor[i] sits at (spineX[i], centerY)
- * - Category node is offset LEFT by categoryDistance:
- * cat.x = spineX[i] - categoryDistance
- * cat.y = centerY +/- categoryDistance (45 degree diagonal bone)
- * - Items staircase away from the category in the same direction
- */
-
-import type { GraphData, GraphNode } from '../types';
-
-export interface FishboneLayoutOptions {
- direction?: 'LR' | 'RL';
- categoryGap?: number;
- itemGap?: number;
- itemHStep?: number;
- categoryDistance?: number;
- getWidth?: (node: GraphNode) => number;
- getHeight?: (node: GraphNode) => number;
-}
-
-interface TreeNode {
- id: string;
- children: TreeNode[];
- x: number;
- y: number;
- width: number;
- height: number;
-}
-
-type LayoutResult = { nodes: Array };
-
-/** Execute the fishbone layout without retaining state or mutating the input data. */
-export function executeFishboneLayout(
- data: GraphData,
- options: FishboneLayoutOptions = {},
-): LayoutResult {
- const direction = options.direction ?? 'LR';
- const categoryGap = options.categoryGap ?? 180;
- const itemHStep = options.itemHStep ?? 20;
- const categoryDistance = options.categoryDistance ?? 200;
- const getWidth = options.getWidth ?? (() => 80);
- const getHeight = options.getHeight ?? (() => 30);
-
- const nodeMap = new Map();
- const childrenMap = new Map();
- const hasParent = new Set();
-
- for (const node of data.nodes) {
- nodeMap.set(node.id, {
- id: node.id,
- children: [],
- x: 0,
- y: 0,
- width: getWidth(node),
- height: getHeight(node),
- });
- }
-
- for (const edge of data.edges) {
- if (!nodeMap.has(edge.source) || !nodeMap.has(edge.target)) continue;
- let childIds = childrenMap.get(edge.source);
- if (!childIds) {
- childIds = [];
- childrenMap.set(edge.source, childIds);
- }
- childIds.push(edge.target);
- hasParent.add(edge.target);
- }
-
- const rootId = data.nodes.find((node) => !hasParent.has(node.id))?.id;
- const root = rootId ? nodeMap.get(rootId) : undefined;
- if (!root) return { nodes: data.nodes.map((node) => ({ ...node, x: 0, y: 0 })) };
-
- const visited = new Set([root.id]);
- const stack: Array<{ node: TreeNode; childIndex: number }> = [{ node: root, childIndex: 0 }];
-
- while (stack.length > 0) {
- const frame = stack[stack.length - 1];
- const childIds = childrenMap.get(frame.node.id) ?? [];
- if (frame.childIndex >= childIds.length) {
- stack.pop();
- continue;
- }
-
- const childId = childIds[frame.childIndex];
- frame.childIndex += 1;
- const child = nodeMap.get(childId);
- if (!child || visited.has(childId)) continue;
-
- visited.add(childId);
- frame.node.children.push(child);
- stack.push({ node: child, childIndex: 0 });
- }
-
- const categories = root.children;
- const categoryCount = categories.length;
-
- if (categoryCount === 0) {
- root.x = 450;
- root.y = 300;
- } else {
- const centerY = categoryDistance + 80;
- const leftMargin = categoryDistance + 20;
- const spineLength = categoryCount * categoryGap;
-
- root.x = leftMargin + spineLength + root.width / 2;
- root.y = centerY;
-
- for (let index = 0; index < categoryCount; index += 1) {
- const category = categories[index];
- const verticalDirection = index % 2 === 0 ? -1 : 1;
- const spineX = leftMargin + (index + 0.5) * categoryGap;
-
- category.x = spineX - categoryDistance;
- category.y = centerY + verticalDirection * categoryDistance;
-
- const itemCount = category.children.length;
- for (let itemIndex = 0; itemIndex < itemCount; itemIndex += 1) {
- const item = category.children[itemIndex];
- const ratio = (itemIndex + 1) / (itemCount + 1);
- const yOffset = ratio * categoryDistance;
- const meetX = category.x + yOffset;
- item.x = meetX - itemHStep - item.width / 2;
- item.y = category.y - verticalDirection * yOffset;
- }
- }
-
- if (direction === 'RL') {
- const totalWidth = leftMargin + spineLength + root.width;
- const pending = [root];
- while (pending.length > 0) {
- const node = pending.pop();
- if (!node) break;
- node.x = totalWidth - node.x;
- pending.push(...node.children);
- }
- }
- }
-
- return {
- nodes: data.nodes.map((node) => {
- const layoutNode = visited.has(node.id) ? nodeMap.get(node.id) : undefined;
- return {
- ...node,
- x: layoutNode?.x ?? 0,
- y: layoutNode?.y ?? 0,
- };
- }),
- };
-}
diff --git a/src/layout/indentedLayout.ts b/src/layout/indentedLayout.ts
deleted file mode 100644
index 8c9e2f15e..000000000
--- a/src/layout/indentedLayout.ts
+++ /dev/null
@@ -1,100 +0,0 @@
-/**
- * Indented Tree Layout — 缩进树布局
- *
- * 将树形数据按缩进方式排列:x 由深度决定,y 由 DFS 遍历顺序决定。
- * 适用于文件目录、分类层级等场景。
- *
- * 支持内置色板:通过 nodeColors / edgeColors 按深度自动分配颜色,
- * 结果写入返回节点的 data._nodeColor / data._edgeColor,供样式函数读取。
- */
-
-import { ANTV_CATEGORY_10 } from '../palette';
-import type { GraphData, GraphNode } from '../types';
-
-/** Default palette when nodeColors / edgeColors are enabled but not specified. */
-const DEFAULT_PALETTE = ANTV_CATEGORY_10;
-
-export interface IndentedLayoutOptions {
- indent?: number;
- rowHeight?: number;
- direction?: 'LR' | 'RL';
- rootId?: string;
- nodeColors?: string[];
- edgeColors?: string[];
-}
-
-type LayoutResult = { nodes: Array };
-
-/** Execute the indented tree layout without retaining state or mutating the input data. */
-export function executeIndentedLayout(
- data: GraphData,
- options: IndentedLayoutOptions = {},
-): LayoutResult {
- const indent = options.indent ?? 80;
- const rowHeight = options.rowHeight ?? 40;
- const direction = options.direction ?? 'LR';
- const { rootId, nodeColors, edgeColors } = options;
- const { nodes, edges } = data;
-
- if (nodes.length === 0) return { nodes: [] };
-
- const children = new Map();
- const hasParent = new Set();
- const nodeIds = new Set(nodes.map((node) => node.id));
- for (const edge of edges) {
- if (!nodeIds.has(edge.source) || !nodeIds.has(edge.target)) continue;
- let childIds = children.get(edge.source);
- if (!childIds) {
- childIds = [];
- children.set(edge.source, childIds);
- }
- childIds.push(edge.target);
- hasParent.add(edge.target);
- }
-
- const root = rootId ?? nodes.find((node) => !hasParent.has(node.id))?.id ?? nodes[0].id;
- const nPalette = nodeColors ?? (nodeColors === undefined ? undefined : DEFAULT_PALETTE);
- const ePalette = edgeColors ?? (edgeColors === undefined ? undefined : DEFAULT_PALETTE);
- const positions = new Map();
- const visited = new Set();
- const stack: Array<{ id: string; depth: number }> = [{ id: root, depth: 0 }];
- let rowIndex = 0;
-
- while (stack.length > 0) {
- const current = stack.pop();
- if (!current) break;
- if (!nodeIds.has(current.id) || visited.has(current.id)) continue;
- visited.add(current.id);
-
- const x = direction === 'LR' ? current.depth * indent : -(current.depth * indent);
- const y = rowIndex * rowHeight;
- rowIndex += 1;
- positions.set(current.id, {
- x,
- y,
- depth: current.depth,
- });
-
- const childIds = children.get(current.id) ?? [];
- for (let index = childIds.length - 1; index >= 0; index -= 1) {
- stack.push({ id: childIds[index], depth: current.depth + 1 });
- }
- }
-
- return {
- nodes: nodes.map((node) => {
- const position = positions.get(node.id);
- if (!position) return { ...node, x: 0, y: 0 };
-
- const nextData: Record = {
- ...node.data,
- depth: position.depth,
- _isRoot: position.depth === 0,
- };
- if (nPalette) nextData._nodeColor = nPalette[position.depth % nPalette.length];
- if (ePalette) nextData._edgeColor = ePalette[position.depth % ePalette.length];
-
- return { ...node, data: nextData, x: position.x, y: position.y };
- }),
- };
-}
diff --git a/src/layout/layoutLoader.ts b/src/layout/layoutLoader.ts
index 007cf53ad..eb5a08a29 100644
--- a/src/layout/layoutLoader.ts
+++ b/src/layout/layoutLoader.ts
@@ -1,52 +1,10 @@
-import type { GraphData, GraphNode } from '../types';
+import type { LayoutConstructor } from '../types';
+import { BUILTIN_LAYOUTS } from './builtinLayouts';
-export type LayoutInstance = {
- execute: (data: GraphData) => Promise;
- forEachNode: (fn: (node: GraphNode & { x: number; y: number }) => void) => void;
-};
-
-export type LayoutConstructor = new (options?: Record) => LayoutInstance;
-
-type LayoutLoader = () => Promise;
-
-const LAYOUT_LOADERS: Record = {
- circular: () =>
- import('@antv/layout/lib/algorithm/circular/index.js').then(
- ({ CircularLayout }) => CircularLayout as unknown as LayoutConstructor,
- ),
- concentric: () =>
- import('@antv/layout/lib/algorithm/concentric/index.js').then(
- ({ ConcentricLayout }) => ConcentricLayout as unknown as LayoutConstructor,
- ),
- dagre: () =>
- import('@antv/layout/lib/algorithm/dagre/index.js').then(
- ({ DagreLayout }) => DagreLayout as unknown as LayoutConstructor,
- ),
- 'd3-force': () =>
- import('@antv/layout/lib/algorithm/d3-force/index.js').then(
- ({ D3ForceLayout }) => D3ForceLayout as unknown as LayoutConstructor,
- ),
- force: () =>
- import('@antv/layout/lib/algorithm/force/index.js').then(
- ({ ForceLayout }) => ForceLayout as unknown as LayoutConstructor,
- ),
- 'force-atlas2': () =>
- import('@antv/layout/lib/algorithm/force-atlas2/index.js').then(
- ({ ForceAtlas2Layout }) => ForceAtlas2Layout as unknown as LayoutConstructor,
- ),
- fruchterman: () =>
- import('@antv/layout/lib/algorithm/fruchterman/index.js').then(
- ({ FruchtermanLayout }) => FruchtermanLayout as unknown as LayoutConstructor,
- ),
- grid: () =>
- import('@antv/layout/lib/algorithm/grid/index.js').then(
- ({ GridLayout }) => GridLayout as unknown as LayoutConstructor,
- ),
-};
+export type LayoutLoader = () => Promise;
/** Resolve a built-in algorithm without starting the import. */
export function getLayoutLoader(type: string): LayoutLoader | undefined {
- return Object.prototype.hasOwnProperty.call(LAYOUT_LOADERS, type)
- ? LAYOUT_LOADERS[type]
- : undefined;
+ const LayoutClass = BUILTIN_LAYOUTS[type];
+ return LayoutClass ? async () => LayoutClass : undefined;
}
diff --git a/src/layout/layoutOptions.ts b/src/layout/layoutOptions.ts
index 1aa7aa14d..23705c24f 100644
--- a/src/layout/layoutOptions.ts
+++ b/src/layout/layoutOptions.ts
@@ -1,9 +1,12 @@
+import type { LayoutConstructor } from '../types';
+
/**
* Normalize options shared by main-thread and Worker-backed @antv/layout execution.
* Keep this module side-effect free so both runtimes use identical thresholds.
+ * Custom layout classes skip the built-in per-algorithm defaults.
*/
export function normalizeLibraryLayoutOptions(
- type: string,
+ type: string | LayoutConstructor,
config: Record,
nodeCount: number,
): Record {
diff --git a/src/layout/layoutWorker.ts b/src/layout/layoutWorker.ts
index 9dfb831e5..baab7069a 100644
--- a/src/layout/layoutWorker.ts
+++ b/src/layout/layoutWorker.ts
@@ -4,7 +4,7 @@
*/
import type { GraphData, GraphEdge, GraphNode } from '../types';
-import { getLayoutLoader } from './layoutLoader';
+import { BUILTIN_LAYOUTS } from './builtinLayouts';
import { normalizeLibraryLayoutOptions } from './layoutOptions';
interface WorkerMessage {
@@ -38,15 +38,14 @@ self.onmessage = async (e: MessageEvent) => {
const layoutData: GraphData = { nodes: layoutNodes, edges: layoutEdges };
try {
- const loadLayout = getLayoutLoader(type);
- if (!loadLayout) throw new Error(`Unknown built-in layout "${type}"`);
- const LayoutClass = await loadLayout();
+ const LayoutClass = BUILTIN_LAYOUTS[type];
+ if (!LayoutClass) throw new Error(`Unknown built-in layout "${type}"`);
const layout = new LayoutClass(opts);
await layout.execute(layoutData);
const positions: Array<{ id: string; x: number; y: number }> = [];
- layout.forEachNode((node: { id: string; x: number; y: number }) => {
- positions.push({ id: node.id, x: node.x, y: node.y });
+ layout.forEachNode((node) => {
+ positions.push({ id: String(node.id), x: node.x, y: node.y });
});
const response: WorkerResponse = { id, positions };
diff --git a/src/layout/libraryLayout.ts b/src/layout/libraryLayout.ts
index aaa3e8c0e..463d5eba3 100644
--- a/src/layout/libraryLayout.ts
+++ b/src/layout/libraryLayout.ts
@@ -1,5 +1,10 @@
-import type { GraphData, GraphNode, LayoutConfig } from '../types';
-import type { LayoutConstructor, LayoutInstance } from './layoutLoader';
+import type {
+ GraphData,
+ GraphNode,
+ LayoutConfig,
+ LayoutConstructor,
+ LayoutInstance,
+} from '../types';
import { normalizeLibraryLayoutOptions } from './layoutOptions';
import type { LayoutResult } from './runLayout';
@@ -32,7 +37,7 @@ function createLibraryLayoutData(data: GraphData): GraphData {
async function executeLibraryLayout(
layout: LayoutInstance,
- type: string,
+ type: string | LayoutConstructor,
layoutData: GraphData,
options: Record,
): Promise {
@@ -56,7 +61,7 @@ function mergeLibraryLayoutResult(
layoutData: GraphData,
layout: LayoutInstance,
): LayoutResult {
- const positions = new Map();
+ const positions = new Map();
layout.forEachNode((node) => positions.set(node.id, [node.x, node.y]));
const layoutNodes = new Map(layoutData.nodes.map((node) => [node.id, node]));
return {
diff --git a/src/layout/mindmapLayout.ts b/src/layout/mindmapLayout.ts
deleted file mode 100644
index ea9799d79..000000000
--- a/src/layout/mindmapLayout.ts
+++ /dev/null
@@ -1,228 +0,0 @@
-/**
- * Mind Map Layout: horizontal tree with root at center, children expand to left/right.
- * Reference: G6 mindmap layout
- */
-
-import { ANTV_CATEGORY_10 } from '../palette';
-import type { GraphData, GraphNode } from '../types';
-
-export interface MindmapLayoutOptions {
- direction?: 'H' | 'LR' | 'RL';
- levelGap?: number;
- nodeGap?: number;
- branchColors?: string[];
- getWidth?: (node: GraphNode) => number;
- getHeight?: (node: GraphNode) => number;
- getSide?: (node: GraphNode, index: number, parentSide?: 'left' | 'right') => 'left' | 'right';
-}
-
-interface TreeNode {
- id: string;
- data: GraphNode['data'];
- children: TreeNode[];
- x: number;
- y: number;
- width: number;
- height: number;
- side?: 'left' | 'right';
- depth: number;
-}
-
-type ResolvedMindmapLayoutOptions = Required;
-
-const DEFAULT_LEVEL_GAP = 120;
-const DEFAULT_NODE_GAP = 30;
-const DEFAULT_NODE_WIDTH = 100;
-const DEFAULT_NODE_HEIGHT = 40;
-const DEFAULT_BRANCH_COLORS = ANTV_CATEGORY_10;
-
-export function executeMindmapLayout(
- data: GraphData,
- options: MindmapLayoutOptions = {},
-): { nodes: Array } {
- const inputNodes = Array.isArray(data?.nodes) ? data.nodes : [];
- if (inputNodes.length === 0) return { nodes: [] };
-
- const resolvedOptions: ResolvedMindmapLayoutOptions = {
- direction: options.direction ?? 'H',
- levelGap: options.levelGap ?? DEFAULT_LEVEL_GAP,
- nodeGap: options.nodeGap ?? DEFAULT_NODE_GAP,
- branchColors: [...(options.branchColors ?? DEFAULT_BRANCH_COLORS)],
- getWidth: options.getWidth ?? (() => DEFAULT_NODE_WIDTH),
- getHeight: options.getHeight ?? (() => DEFAULT_NODE_HEIGHT),
- getSide: options.getSide ?? (() => 'right'),
- };
-
- const nodeMap = new Map();
- const childrenMap = new Map();
- const hasParent = new Set();
-
- for (const node of inputNodes) {
- if (nodeMap.has(node.id)) continue;
- nodeMap.set(node.id, {
- id: node.id,
- data: node.data ? { ...node.data } : undefined,
- children: [],
- x: 0,
- y: 0,
- width: 0,
- height: 0,
- depth: 0,
- });
- }
-
- for (const edge of Array.isArray(data.edges) ? data.edges : []) {
- const { source, target } = edge;
- if (source === target || !nodeMap.has(source) || !nodeMap.has(target)) continue;
- // A mind map is a tree. Keep the first valid parent so malformed multi-parent
- // input cannot add the same TreeNode to multiple branches.
- if (hasParent.has(target)) continue;
- const children = childrenMap.get(source) ?? [];
- if (children.includes(target)) continue;
- children.push(target);
- childrenMap.set(source, children);
- hasParent.add(target);
- }
-
- const rootId = inputNodes.find((node) => nodeMap.has(node.id) && !hasParent.has(node.id))?.id;
- // A graph made entirely of cycles has no natural root. Falling back to the
- // first node keeps the result deterministic; the DFS guard below cuts cycles.
- const rootNode = nodeMap.get(rootId ?? inputNodes[0].id);
- if (!rootNode) {
- return {
- nodes: inputNodes.map((node) => ({
- ...node,
- data: node.data ? { ...node.data } : undefined,
- x: 0,
- y: 0,
- })),
- };
- }
-
- const visited = new Set();
- const visiting = new Set();
-
- const buildChildren = (node: TreeNode, depth: number): void => {
- if (visiting.has(node.id) || visited.has(node.id)) return;
- visiting.add(node.id);
- visited.add(node.id);
- node.depth = depth;
-
- for (const childId of childrenMap.get(node.id) ?? []) {
- if (visiting.has(childId) || visited.has(childId)) continue;
- const child = nodeMap.get(childId);
- if (!child) continue;
- node.children.push(child);
- buildChildren(child, depth + 1);
- }
-
- visiting.delete(node.id);
- };
-
- buildChildren(rootNode, 0);
-
- const toCallbackNode = (node: TreeNode): GraphNode => ({
- id: node.id,
- data: node.data ? { ...node.data } : undefined,
- });
-
- const calculateSizes = (node: TreeNode): void => {
- const graphNode = toCallbackNode(node);
- node.width = resolvedOptions.getWidth(graphNode);
- node.height = resolvedOptions.getHeight(graphNode);
- node.children.forEach(calculateSizes);
- };
-
- const assignSides = (node: TreeNode, parentSide?: 'left' | 'right'): void => {
- if (node.children.length === 0) return;
-
- if (node.depth === 0) {
- if (resolvedOptions.direction === 'H') {
- node.children.forEach((child, index) => {
- child.side = resolvedOptions.getSide(toCallbackNode(child), index, undefined);
- });
- } else {
- const side = resolvedOptions.direction === 'LR' ? 'right' : 'left';
- node.children.forEach((child) => {
- child.side = side;
- });
- }
- } else {
- node.children.forEach((child, index) => {
- child.side = resolvedOptions.getSide(toCallbackNode(child), index, parentSide);
- });
- }
-
- // Preserve the previous layout's parent-side propagation semantics.
- node.children.forEach((child) => assignSides(child, node.side));
- };
-
- const assignBranchColor = (node: TreeNode, colorIndex: number): void => {
- const { branchColors } = resolvedOptions;
- if (branchColors.length > 0) {
- const color = branchColors[colorIndex % branchColors.length];
- node.data = { ...(node.data ?? {}), _branchColor: color };
- }
- node.children.forEach((child) => assignBranchColor(child, colorIndex));
- };
-
- const getChildrenHeight = (children: TreeNode[]): number => {
- if (children.length === 0) return 0;
- return children.reduce(
- (total, child, index) =>
- total + child.height + (index < children.length - 1 ? resolvedOptions.nodeGap : 0),
- 0,
- );
- };
-
- const calculatePositions = (node: TreeNode): void => {
- if (node.children.length === 0) return;
-
- const leftChildren: TreeNode[] = [];
- const rightChildren: TreeNode[] = [];
- for (const child of node.children) {
- (child.side === 'left' ? leftChildren : rightChildren).push(child);
- }
-
- if (rightChildren.length > 0) {
- let yOffset = node.y - getChildrenHeight(rightChildren) / 2;
- for (const child of rightChildren) {
- child.x = node.x + node.width / 2 + resolvedOptions.levelGap + child.width / 2;
- child.y = yOffset + child.height / 2;
- yOffset += child.height + resolvedOptions.nodeGap;
- assignBranchColor(child, 1);
- calculatePositions(child);
- }
- }
-
- if (leftChildren.length > 0) {
- let yOffset = node.y - getChildrenHeight(leftChildren) / 2;
- for (const child of leftChildren) {
- child.x = node.x - node.width / 2 - resolvedOptions.levelGap - child.width / 2;
- child.y = yOffset + child.height / 2;
- yOffset += child.height + resolvedOptions.nodeGap;
- assignBranchColor(child, 0);
- calculatePositions(child);
- }
- }
- };
-
- rootNode.x = 0;
- rootNode.y = 0;
- calculateSizes(rootNode);
- assignSides(rootNode);
- calculatePositions(rootNode);
-
- return {
- nodes: inputNodes.map((node) => {
- const layoutNode = nodeMap.get(node.id);
- const positioned = layoutNode && visited.has(layoutNode.id);
- return {
- ...node,
- data: layoutNode?.data ? { ...layoutNode.data } : undefined,
- x: positioned ? layoutNode.x : 0,
- y: positioned ? layoutNode.y : 0,
- };
- }),
- };
-}
diff --git a/src/layout/optional/fishbone.ts b/src/layout/optional/fishbone.ts
deleted file mode 100644
index aa6eb7651..000000000
--- a/src/layout/optional/fishbone.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import type { LayoutExtension } from '../../extensions/contracts';
-import { executeFishboneLayout, type FishboneLayoutOptions } from '../fishboneLayout';
-
-const fishbone: LayoutExtension = {
- execute(data, { options }) {
- return executeFishboneLayout(data, options as FishboneLayoutOptions);
- },
-};
-
-export default fishbone;
diff --git a/src/layout/optional/indented.ts b/src/layout/optional/indented.ts
deleted file mode 100644
index de1588e9b..000000000
--- a/src/layout/optional/indented.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import type { LayoutExtension } from '../../extensions/contracts';
-import { executeIndentedLayout, type IndentedLayoutOptions } from '../indentedLayout';
-
-const indented: LayoutExtension = {
- execute(data, { options }) {
- return executeIndentedLayout(data, options as IndentedLayoutOptions);
- },
-};
-
-export default indented;
diff --git a/src/layout/optional/index.ts b/src/layout/optional/index.ts
deleted file mode 100644
index aba30300e..000000000
--- a/src/layout/optional/index.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-export { default as mds } from './mds';
-export { default as radial } from './radial';
-export { default as indented } from './indented';
-export { default as mindmap } from './mindmap';
-export { default as fishbone } from './fishbone';
-export { default as random } from './random';
diff --git a/src/layout/optional/mds.ts b/src/layout/optional/mds.ts
deleted file mode 100644
index 89e422a5b..000000000
--- a/src/layout/optional/mds.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { MDSLayout } from '@antv/layout/lib/algorithm/mds/index.js';
-import type { LayoutExtension } from '../../extensions/contracts';
-import type { LayoutConstructor } from '../layoutLoader';
-import { runLibraryLayout } from '../libraryLayout';
-
-const mds: LayoutExtension = {
- execute(data, { options, signal }) {
- return runLibraryLayout(
- MDSLayout as unknown as LayoutConstructor,
- data,
- { ...options, type: 'mds' },
- signal,
- );
- },
-};
-
-export default mds;
diff --git a/src/layout/optional/mindmap.ts b/src/layout/optional/mindmap.ts
deleted file mode 100644
index ad1caa6ab..000000000
--- a/src/layout/optional/mindmap.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import type { LayoutExtension } from '../../extensions/contracts';
-import { executeMindmapLayout, type MindmapLayoutOptions } from '../mindmapLayout';
-
-const mindmap: LayoutExtension = {
- execute(data, { options }) {
- return executeMindmapLayout(data, options as MindmapLayoutOptions);
- },
-};
-
-export default mindmap;
diff --git a/src/layout/optional/radial.ts b/src/layout/optional/radial.ts
deleted file mode 100644
index 698ee203f..000000000
--- a/src/layout/optional/radial.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { RadialLayout } from '@antv/layout/lib/algorithm/radial/index.js';
-import type { LayoutExtension } from '../../extensions/contracts';
-import type { LayoutConstructor } from '../layoutLoader';
-import { runLibraryLayout } from '../libraryLayout';
-
-const radial: LayoutExtension = {
- execute(data, { options, signal }) {
- return runLibraryLayout(
- RadialLayout as unknown as LayoutConstructor,
- data,
- { ...options, type: 'radial' },
- signal,
- );
- },
-};
-
-export default radial;
diff --git a/src/layout/optional/random.ts b/src/layout/optional/random.ts
deleted file mode 100644
index 79fa20941..000000000
--- a/src/layout/optional/random.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { RandomLayout } from '@antv/layout/lib/algorithm/random/index.js';
-import type { LayoutExtension } from '../../extensions/contracts';
-import type { LayoutConstructor } from '../layoutLoader';
-import { runLibraryLayout } from '../libraryLayout';
-
-const random: LayoutExtension = {
- execute(data, { options, signal }) {
- return runLibraryLayout(
- RandomLayout as unknown as LayoutConstructor,
- data,
- { ...options, type: 'random' },
- signal,
- );
- },
-};
-
-export default random;
diff --git a/src/layout/runLayout.ts b/src/layout/runLayout.ts
index d087dfee1..890b6b945 100644
--- a/src/layout/runLayout.ts
+++ b/src/layout/runLayout.ts
@@ -13,8 +13,6 @@ import { runLayoutInWorker } from './workerLayout';
export type LayoutResult = { nodes: Array };
-const OPTIONAL_LAYOUTS = new Set(['mds', 'radial', 'indented', 'mindmap', 'fishbone', 'random']);
-
interface LayoutRuntime {
signal?: AbortSignal;
extensionContext?: ExtensionContext;
@@ -40,6 +38,7 @@ async function runExtensionLayout(
viewport: { width: number; height: number } | undefined,
runtime: LayoutRuntime,
): Promise {
+ if (typeof config.type !== 'string') return undefined;
const extension = createExtension('layout', config.type);
if (!extension) return undefined;
const options = Object.freeze({ ...config });
@@ -112,10 +111,12 @@ export async function runLayout(
if (runtime.signal?.aborted) return createFallbackResult(data);
const { type } = resolvedConfig;
- if (OPTIONAL_LAYOUTS.has(type)) {
- throw new Error(
- `[G6Lite] Register layout "${type}" from @antv/g6-lite/layouts/${type} before use.`,
- );
+
+ // Custom layout classes are executed on the main thread because functions
+ // cannot be transferred to a Worker via postMessage.
+ if (typeof type === 'function') {
+ if (runtime.signal?.aborted) return createFallbackResult(data);
+ return runLibraryLayout(type, data, resolvedConfig, runtime.signal);
}
const loadLayout = getLayoutLoader(type);
diff --git a/src/types.ts b/src/types.ts
index 1ada8e334..331e18924 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -589,10 +589,25 @@ export interface EdgeConfig {
stateStyles?: Partial>;
}
+/** Runtime layout instance contract used by G6Lite. */
+export interface LayoutInstance {
+ execute: (data: GraphData) => Promise;
+ forEachNode: (
+ fn: (
+ node: { id: string | number; x: number; y: number; data?: Record },
+ index?: number,
+ ) => void,
+ ) => void;
+}
+
+/** Layout class constructor, typically imported from @antv/layout. */
+export type LayoutConstructor = new (options?: Record) => LayoutInstance;
+
/** Layout config: type + algorithm-specific options (aligned with @antv/layout). */
export interface LayoutConfig {
- type: string;
- /** Run layout in a Web Worker to avoid blocking the main thread. */
+ /** Built-in layout name or a layout class imported from @antv/layout. */
+ type: string | LayoutConstructor;
+ /** Run layout in a Web Worker to avoid blocking the main thread. Only string-named built-in layouts support Worker. */
worker?: boolean;
/** Layout viewport width; defaults to the canvas width (injected by Graph). */
width?: number;
@@ -754,7 +769,7 @@ export interface GraphOptions {
node?: NodeConfig;
edge?: EdgeConfig;
combo?: ComboConfig;
- layout?: LayoutConfig;
+ layout?: LayoutConfig | LayoutConstructor;
behaviors?: BehaviorOption[];
transforms?: TransformOption[];
plugins?: PluginOption[];
diff --git a/tests/bugfix/layout/layoutViewport.test.ts b/tests/bugfix/layout/layoutViewport.test.ts
index 0fa11cb9e..116882267 100644
--- a/tests/bugfix/layout/layoutViewport.test.ts
+++ b/tests/bugfix/layout/layoutViewport.test.ts
@@ -28,7 +28,6 @@ class FakeLayout {
}
vi.mock('@antv/layout/lib/algorithm/force/index.js', () => ({ ForceLayout: FakeLayout }));
-vi.mock('@antv/layout/lib/algorithm/circular/index.js', () => ({ CircularLayout: FakeLayout }));
// Import AFTER the mock is registered.
const { runLayout } = await import('@src/layout/runLayout.js');
@@ -73,7 +72,7 @@ describe('runLayout viewport injection', () => {
});
it('leaves opts viewport untouched when no viewport is passed (back-compat)', async () => {
- await runLayout(data as never, { type: 'circular' });
+ await runLayout(data as never, { type: 'force' });
expect(captured.opts!.width).toBeUndefined();
expect(captured.opts!.height).toBeUndefined();
expect(captured.opts!.center).toBeUndefined();
diff --git a/tests/unit/graph.test.ts b/tests/unit/graph.test.ts
index 0cca9dd8b..0b98866e8 100644
--- a/tests/unit/graph.test.ts
+++ b/tests/unit/graph.test.ts
@@ -374,7 +374,7 @@ describe('P1: repeated render resource lifecycle', () => {
transformInstances: new Map(),
options: {
data: { nodes: [{ id: 'node' }], edges: [] },
- layout: { type: 'grid' },
+ layout: { type: 'force' },
},
containerEl: { clientWidth: 400, clientHeight: 300 },
renderer: { resize: vi.fn(), clearWithTheme: vi.fn() },
@@ -394,7 +394,7 @@ describe('P1: repeated render resource lifecycle', () => {
});
it('derives automatic worker layout without mutating the configured options', async () => {
- const layout = { type: 'grid' };
+ const layout = { type: 'force' };
const executeLayout = vi.fn(async (data: { nodes: Array<{ id: string }> }, config) => ({
nodes: data.nodes.map((node, index) => ({ ...node, x: index, y: index })),
config,
@@ -418,10 +418,10 @@ describe('P1: repeated render resource lifecycle', () => {
}
).runConfiguredLayout({ nodes, edges: [] }, 1);
- expect(layout).toEqual({ type: 'grid' });
+ expect(layout).toEqual({ type: 'force' });
expect(executeLayout).toHaveBeenCalledWith(
expect.anything(),
- expect.objectContaining({ type: 'grid', worker: true }),
+ expect.objectContaining({ type: 'force', worker: true }),
);
expect(executeLayout.mock.calls[0][1]).not.toBe(layout);
});
diff --git a/tests/unit/layout/functionalLayouts.test.ts b/tests/unit/layout/functionalLayouts.test.ts
deleted file mode 100644
index 4a8149b33..000000000
--- a/tests/unit/layout/functionalLayouts.test.ts
+++ /dev/null
@@ -1,145 +0,0 @@
-import { describe, expect, it } from 'vitest';
-import { register } from '@src/index.js';
-import { executeFishboneLayout } from '@src/layout/fishboneLayout.js';
-import { executeIndentedLayout } from '@src/layout/indentedLayout.js';
-import { executeMindmapLayout } from '@src/layout/mindmapLayout.js';
-import fishbone from '@src/layout/optional/fishbone.js';
-import indented from '@src/layout/optional/indented.js';
-import mindmap from '@src/layout/optional/mindmap.js';
-import { runLayout } from '@src/layout/runLayout.js';
-import { ANTV_CATEGORY_10 } from '@src/palette.js';
-import type { GraphData } from '@src/types.js';
-
-describe('optional tree layouts', () => {
- it('executes the indented layout without mutating input data', () => {
- const data: GraphData = {
- nodes: [{ id: 'root', data: { label: 'Root' } }, { id: 'child' }, { id: 'leaf' }],
- edges: [
- { source: 'root', target: 'child' },
- { source: 'child', target: 'leaf' },
- ],
- };
- const original = structuredClone(data);
-
- const result = executeIndentedLayout(data, {
- indent: 60,
- rowHeight: 30,
- nodeColors: ['#root', '#child', '#leaf'],
- edgeColors: ['#edge-0', '#edge-1'],
- });
-
- expect(result.nodes).toMatchObject([
- {
- id: 'root',
- x: 0,
- y: 0,
- data: { label: 'Root', depth: 0, _isRoot: true, _nodeColor: '#root' },
- },
- { id: 'child', x: 60, y: 30, data: { depth: 1, _isRoot: false } },
- { id: 'leaf', x: 120, y: 60, data: { depth: 2, _isRoot: false } },
- ]);
- expect(data).toEqual(original);
- });
-
- it('executes the mindmap layout with deterministic branch sides and colors', () => {
- const data: GraphData = {
- nodes: [{ id: 'root' }, { id: 'left' }, { id: 'right' }, { id: 'left-child' }],
- edges: [
- { source: 'root', target: 'left' },
- { source: 'root', target: 'right' },
- { source: 'left', target: 'left-child' },
- ],
- };
- const original = structuredClone(data);
-
- const result = executeMindmapLayout(data, {
- branchColors: ['#left', '#right'],
- getSide: (_node, index, parentSide) => parentSide ?? (index === 0 ? 'left' : 'right'),
- });
- const byId = new Map(result.nodes.map((node) => [node.id, node]));
-
- expect(byId.get('root')).toMatchObject({ x: 0, y: 0 });
- expect(byId.get('left')).toMatchObject({ x: -220, y: 0, data: { _branchColor: '#left' } });
- expect(byId.get('right')).toMatchObject({ x: 220, y: 0, data: { _branchColor: '#right' } });
- expect(byId.get('left-child')).toMatchObject({
- x: -440,
- y: 0,
- data: { _branchColor: '#left' },
- });
- expect(data).toEqual(original);
- });
-
- it('uses the current AntV category palette for default mindmap branch colors', () => {
- const result = executeMindmapLayout(
- {
- nodes: [{ id: 'root' }, { id: 'first' }, { id: 'second' }],
- edges: [
- { source: 'root', target: 'first' },
- { source: 'root', target: 'second' },
- ],
- },
- {
- getSide: (_node, index) => (index === 0 ? 'left' : 'right'),
- },
- );
- const byId = new Map(result.nodes.map((node) => [node.id, node]));
-
- expect(byId.get('first')?.data?._branchColor).toBe(ANTV_CATEGORY_10[0]);
- expect(byId.get('second')?.data?._branchColor).toBe(ANTV_CATEGORY_10[1]);
- });
-
- it('executes the fishbone layout as a stateless function', () => {
- const data: GraphData = {
- nodes: [{ id: 'head' }, { id: 'category' }, { id: 'item' }],
- edges: [
- { source: 'head', target: 'category' },
- { source: 'category', target: 'item' },
- ],
- };
- const original = structuredClone(data);
-
- const result = executeFishboneLayout(data);
- const byId = new Map(result.nodes.map((node) => [node.id, node]));
-
- expect(byId.get('head')).toMatchObject({ x: 440, y: 280 });
- expect(byId.get('category')).toMatchObject({ x: 110, y: 80 });
- expect(byId.get('item')).toMatchObject({ x: 150, y: 180 });
- expect(data).toEqual(original);
- });
-
- it('runs registered indented layout when worker is requested', async () => {
- register('layout', 'indented', indented);
- const result = await runLayout(
- {
- nodes: [{ id: 'root' }, { id: 'child' }],
- edges: [{ source: 'root', target: 'child' }],
- },
- { type: 'indented', worker: true, indent: 50, rowHeight: 25 },
- );
-
- expect(result.nodes).toMatchObject([
- { id: 'root', x: 0, y: 0 },
- { id: 'child', x: 50, y: 25 },
- ]);
- });
-
- it.each(Object.entries({ mindmap, fishbone }))(
- 'routes %s through the unified runLayout entry',
- async (type, extension) => {
- register('layout', type, extension);
- const result = await runLayout(
- {
- nodes: [{ id: 'root' }, { id: 'child' }],
- edges: [{ source: 'root', target: 'child' }],
- },
- { type, worker: true },
- );
-
- expect(result.nodes.map((node) => node.id)).toEqual(['root', 'child']);
- result.nodes.forEach((node) => {
- expect(Number.isFinite(node.x)).toBe(true);
- expect(Number.isFinite(node.y)).toBe(true);
- });
- },
- );
-});
diff --git a/tests/unit/layout/layoutLoader.test.ts b/tests/unit/layout/layoutLoader.test.ts
index c64aff4f8..6500f1c90 100644
--- a/tests/unit/layout/layoutLoader.test.ts
+++ b/tests/unit/layout/layoutLoader.test.ts
@@ -1,10 +1,6 @@
import { describe, expect, it, vi } from 'vitest';
-import { register } from '@src/index.js';
import { getLayoutLoader } from '@src/layout/layoutLoader.js';
import { runLayout } from '@src/layout/runLayout.js';
-import mds from '@src/layout/optional/mds.js';
-import radial from '@src/layout/optional/radial.js';
-import random from '@src/layout/optional/random.js';
const FakeLayout = vi.hoisted(
() =>
@@ -16,31 +12,25 @@ const FakeLayout = vi.hoisted(
},
);
-vi.mock('@antv/layout/lib/algorithm/dagre/index.js', () => ({ DagreLayout: FakeLayout }));
-vi.mock('@antv/layout/lib/algorithm/mds/index.js', () => ({ MDSLayout: FakeLayout }));
-vi.mock('@antv/layout/lib/algorithm/radial/index.js', () => ({ RadialLayout: FakeLayout }));
-vi.mock('@antv/layout/lib/algorithm/random/index.js', () => ({ RandomLayout: FakeLayout }));
+vi.mock('@antv/layout/lib/algorithm/force/index.js', () => ({ ForceLayout: FakeLayout }));
describe('layoutLoader', () => {
const data = { nodes: [{ id: 'a' }], edges: [] };
- it('loads dagre without explicit registration', async () => {
- await expect(getLayoutLoader('dagre')?.()).resolves.toBe(FakeLayout);
+ it('loads built-in force without explicit registration', async () => {
+ await expect(getLayoutLoader('force')?.()).resolves.toBe(FakeLayout);
});
- it.each(Object.entries({ mds, radial, random }))(
- 'uses %s after registration',
- async (type, extension) => {
- expect(getLayoutLoader(type)).toBeUndefined();
- await expect(runLayout(data, { type, worker: true })).rejects.toThrow(
- `@antv/g6-lite/layouts/${type}`,
- );
- register('layout', type, extension);
- await expect(runLayout(data, { type, worker: true })).resolves.toEqual({
- nodes: [{ id: 'a', x: 20, y: 30, data: undefined }],
- });
- },
- );
+ it('does not bundle non-built-in layout names', () => {
+ expect(getLayoutLoader('dagre')).toBeUndefined();
+ expect(getLayoutLoader('circular')).toBeUndefined();
+ });
+
+ it('runs a custom layout class on the main thread even when worker is requested', async () => {
+ await expect(runLayout(data, { type: FakeLayout, worker: true })).resolves.toEqual({
+ nodes: [{ id: 'a', x: 20, y: 30 }],
+ });
+ });
it('preserves random placement for unknown names independently of the registered layout', async () => {
const rng = vi.spyOn(Math, 'random').mockReturnValue(0.75);
diff --git a/tests/unit/layout/workerLayout.test.ts b/tests/unit/layout/workerLayout.test.ts
index ea80f7c24..384639ee1 100644
--- a/tests/unit/layout/workerLayout.test.ts
+++ b/tests/unit/layout/workerLayout.test.ts
@@ -34,7 +34,7 @@ class FakeWorker {
}
const data = { nodes: [{ id: 'node' }], edges: [] };
-const config = { type: 'grid', worker: true } as const;
+const config = { type: 'force', worker: true } as const;
afterEach(() => {
terminateLayoutWorker();
diff --git a/tests/unit/site/quick-start.test.ts b/tests/unit/site/quick-start.test.ts
index 124eea813..879d0a4d1 100644
--- a/tests/unit/site/quick-start.test.ts
+++ b/tests/unit/site/quick-start.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
-import { D3ForceLayout } from '@antv/layout/lib/algorithm/d3-force/index.js';
+import { D3ForceLayout } from '@antv/layout';
import { quickStartNetworkOptions } from '../../../site/src/lib/quick-start';
describe('quick-start network', () => {
From 34170c5e86f54d4ebbaa52f3960d0e20bcbf20e3 Mon Sep 17 00:00:00 2001
From: hustcc
Date: Fri, 27 Nov 2026 23:42:07 +0800
Subject: [PATCH 2/6] docs: remove minzip badge from README
---
README.md | 1 -
README.zh-CN.md | 1 -
2 files changed, 2 deletions(-)
diff --git a/README.md b/README.md
index b4521d727..a404e96b3 100644
--- a/README.md
+++ b/README.md
@@ -13,7 +13,6 @@ English | [简体中文](./README.zh-CN.md)
-
diff --git a/README.zh-CN.md b/README.zh-CN.md
index ed518fb50..9a1fc28cf 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -13,7 +13,6 @@
-
From 067c51ae74b4fbea4db773fdae166393a76e3c9d Mon Sep 17 00:00:00 2001
From: hustcc
Date: Fri, 27 Nov 2026 23:55:33 +0800
Subject: [PATCH 3/6] docs: add UMD size comparison with G6, ECharts, and
Sigma.js
---
site/content/docs/en/metrics/performance.mdx | 9 ++++++---
site/content/docs/zh/metrics/performance.mdx | 9 ++++++---
2 files changed, 12 insertions(+), 6 deletions(-)
diff --git a/site/content/docs/en/metrics/performance.mdx b/site/content/docs/en/metrics/performance.mdx
index 41dd54588..12ba8edf8 100644
--- a/site/content/docs/en/metrics/performance.mdx
+++ b/site/content/docs/en/metrics/performance.mdx
@@ -40,11 +40,14 @@ These results apply only to the environment above and do not certify minimum sup
## G6Lite CDN file sizes [#umd-size]
-The published UMD file `g6-lite.min.js` includes rendering, interactions, and built-in force-directed layouts. One kB is 1,000 bytes.
+The published UMD file `g6-lite.min.js` includes rendering, interactions, and built-in force-directed layouts. Other libraries are measured from their published UMD bundles on unpkg.
-| Published file | Contents | Minified (kB) | gzip -9 (kB) |
+| Library | UMD bundle | Minified (kB) | gzip -9 (kB) |
| --- | --- | ---: | ---: |
-| `g6-lite.min.js` | Default script with rendering, interactions, and built-in force-directed layouts | 408.1 | 118.2 |
+| `@antv/g6-lite` | `g6-lite.min.js` | 408.1 | 118.2 |
+| `@antv/g6@5.1.1` | `g6.min.js` | 1,383.3 | 390.6 |
+| `echarts@6.1.0` | `echarts.min.js` | 1,121.9 | 368.2 |
+| `sigma@4.0.4` + `graphology@0.26.0` | `sigma.min.js` + `graphology.umd.min.js` | 466.7 | 117.6 |
Other layouts are imported as classes from `@antv/layout` and run on the main thread. [Built-in and external layouts](/en/docs/guides/layout-overview#builtin-and-external-layouts)
diff --git a/site/content/docs/zh/metrics/performance.mdx b/site/content/docs/zh/metrics/performance.mdx
index cc1e6e7d7..27870a84c 100644
--- a/site/content/docs/zh/metrics/performance.mdx
+++ b/site/content/docs/zh/metrics/performance.mdx
@@ -36,11 +36,14 @@ description: 同一图数据下 G6Lite、G6、Sigma.js 与 ECharts 的首绘耗
## G6Lite CDN 文件体积 [#umd-size]
-发布的 UMD 文件 `g6-lite.min.js` 包含渲染、交互和内置力导向布局,1 kB = 1,000 字节。
+发布的 UMD 文件 `g6-lite.min.js` 包含渲染、交互和内置力导向布局。其他库测量自 unpkg 上发布的 UMD 产物。
-| 发布文件 | 内容 | 压缩前(kB) | gzip 后(kB) |
+| 库 | UMD 产物 | 压缩前(kB) | gzip 后(kB) |
| --- | --- | ---: | ---: |
-| `g6-lite.min.js` | 默认脚本,包含渲染、交互和内置力导向布局 | 408.1 | 118.2 |
+| `@antv/g6-lite` | `g6-lite.min.js` | 408.1 | 118.2 |
+| `@antv/g6@5.1.1` | `g6.min.js` | 1,383.3 | 390.6 |
+| `echarts@6.1.0` | `echarts.min.js` | 1,121.9 | 368.2 |
+| `sigma@4.0.4` + `graphology@0.26.0` | `sigma.min.js` + `graphology.umd.min.js` | 466.7 | 117.6 |
其他布局从 `@antv/layout` 导入布局类后传入,在主线程执行。 [内置与外部布局](/docs/guides/layout-overview#builtin-and-external-layouts)
From c84700db31bc6aea96764e1d1522d8e193454eaa Mon Sep 17 00:00:00 2001
From: hustcc
Date: Mon, 30 Nov 2026 15:41:24 +0800
Subject: [PATCH 4/6] chore: update antv layout version with 2.1.0
---
package.json | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/package.json b/package.json
index 817c544db..4cd12d2b2 100644
--- a/package.json
+++ b/package.json
@@ -73,7 +73,7 @@
},
"dependencies": {
"@antv/event-emitter": "^0.1.3",
- "@antv/layout": "^2.1.0-beta.1",
+ "@antv/layout": "^2.1.0",
"regl": "^2.1.1"
},
"engines": {
From 34bf8b6d8bdac3ee97f339e2f06314c279d7c865 Mon Sep 17 00:00:00 2001
From: "gengsheng.wp"
Date: Mon, 30 Nov 2026 18:58:54 +0800
Subject: [PATCH 5/6] fix(site): align layout examples with the layout refactor
---
README.md | 4 +-
README.zh-CN.md | 4 +-
site/content/docs/en/api/options.mdx | 2 +-
.../docs/en/compatibility/g6-v5-migration.mdx | 3 +-
.../docs/en/getting-started/quick-start.mdx | 6 +--
.../content/docs/en/getting-started/react.mdx | 3 +-
site/content/docs/en/getting-started/vue.mdx | 3 +-
.../docs/en/guides/layout-networks.mdx | 2 +-
.../docs/en/guides/layout-overview.mdx | 8 +++-
site/content/docs/en/guides/layout.mdx | 2 +-
site/content/docs/en/metrics/performance.mdx | 8 ++--
site/content/docs/zh/api/options.mdx | 2 +-
.../docs/zh/compatibility/g6-v5-migration.mdx | 3 +-
.../docs/zh/getting-started/quick-start.mdx | 6 +--
.../content/docs/zh/getting-started/react.mdx | 3 +-
site/content/docs/zh/getting-started/vue.mdx | 3 +-
.../docs/zh/guides/layout-networks.mdx | 2 +-
.../docs/zh/guides/layout-overview.mdx | 8 +++-
site/content/docs/zh/guides/layout.mdx | 2 +-
site/content/docs/zh/metrics/performance.mdx | 8 ++--
site/demos/fishbone.ts | 2 +-
site/scripts/check-example-documentation.mjs | 21 +++++++++-
.../homepage/bundle-measurement.json | 7 ++--
site/src/components/homepage/homepage.tsx | 2 +-
.../homepage/showcase-code.server.ts | 38 +++++++++++++------
.../components/homepage/showcase-examples.ts | 9 +----
site/src/lib/playground-runtime.ts | 2 +-
site/src/lib/quick-start.ts | 3 +-
skills/antv-g6lite-graph/SKILL.md | 9 ++---
.../antv-g6lite-graph/references/layouts.md | 19 ++++++----
.../antv-g6lite-graph/references/migration.md | 2 +-
.../references/troubleshooting.md | 4 +-
32 files changed, 121 insertions(+), 79 deletions(-)
diff --git a/README.md b/README.md
index a404e96b3..0ca35aefd 100644
--- a/README.md
+++ b/README.md
@@ -85,11 +85,11 @@ Only package-root exports from `@antv/g6-lite` and `package.json#exports` are pu
## CDN / UMD
-Use the UMD build directly in a browser without a bundler. It exposes `window.G6Lite` and includes the runtime dependencies and built-in force-directed layouts (`force`, `force-atlas2`, `d3-force`, `fruchterman`). Other `@antv/layout` algorithms can be passed as layout classes; see [Built-in and external layouts](https://g6lite.antv.vision/en/docs/guides/layout-overview#builtin-and-external-layouts). See [Optional layouts](https://g6lite.antv.vision/en/docs/guides/layout-overview#optional-layouts) for additional registered layouts.
+Use the UMD build in a browser to access `window.G6Lite`. This example uses the built-in `force` layout in `0.1.0`. See the [layout overview](https://g6lite.antv.vision/en/docs/guides/layout-overview) for layout options by version.
```html
-
+
+
+
```
-ESM integrations support on-demand layout loading through a bundler; the UMD script bundles built-in layouts. Both integrations require [importing and registering optional layouts](/en/docs/guides/layout-overview#optional-layouts) before use. See the [Worker guide](/en/docs/guides/layout-worker) for Worker deployment requirements.
+ESM integrations support on-demand layout loading through a bundler. The UMD script bundles built-in layouts. See the [layout overview](/en/docs/guides/layout-overview#builtin-and-external-layouts) for the layout options available in each version and the [Worker guide](/en/docs/guides/layout-worker) for Worker deployment requirements.
The standalone HTML examples above destroy their instances on `pagehide`. Recreate them if the browser restores the page from its back/forward cache.
diff --git a/site/content/docs/en/getting-started/react.mdx b/site/content/docs/en/getting-started/react.mdx
index f9fcdfb04..9285e1667 100644
--- a/site/content/docs/en/getting-started/react.mdx
+++ b/site/content/docs/en/getting-started/react.mdx
@@ -30,7 +30,6 @@ Save the following as `GraphView.tsx`. The component creates a graph on mount, c
import { useEffect, useRef, useState } from 'react';
import { Graph, type GraphData } from '@antv/g6-lite';
-import { CircularLayout } from '@antv/layout';
const basicData: GraphData = {
nodes: [{ id: 'Alice' }, { id: 'Bob' }, { id: 'Carol' }],
@@ -58,7 +57,7 @@ export default function GraphView() {
const graph = new Graph({
container: containerRef.current,
data: basicData,
- layout: { type: CircularLayout, radius: 120 },
+ layout: { type: 'force', linkDistance: 120 },
node: { style: { size: 24, label: (node) => node.id, labelPlacement: 'bottom' } },
edge: { style: { endArrow: true } },
autoFit: fitView,
diff --git a/site/content/docs/en/getting-started/vue.mdx b/site/content/docs/en/getting-started/vue.mdx
index 47095ddb6..d4022feb0 100644
--- a/site/content/docs/en/getting-started/vue.mdx
+++ b/site/content/docs/en/getting-started/vue.mdx
@@ -31,7 +31,6 @@ Save the following as `GraphView.vue`. The component creates a graph on mount, c
+
```
-ESM 接入支持通过构建工具按需加载布局;UMD 主脚本已内联内置布局。两种接入方式使用可选布局时都需要[先导入并注册](/docs/guides/layout-overview#optional-layouts)。布局的 Worker 部署要求见 [Worker 指南](/docs/guides/layout-worker)。
+ESM 接入支持通过构建工具按需加载布局,UMD 主脚本已内联内置布局。其他算法的接入方式随 G6Lite 版本变化,请查阅[布局总览](/docs/guides/layout-overview#builtin-and-external-layouts)。Worker 的部署要求见 [Worker 指南](/docs/guides/layout-worker)。
上面的独立 HTML 示例在 `pagehide` 时销毁图实例。浏览器从往返缓存恢复页面时,需要重新创建实例。
diff --git a/site/content/docs/zh/getting-started/react.mdx b/site/content/docs/zh/getting-started/react.mdx
index a552b1470..034ec4ad4 100644
--- a/site/content/docs/zh/getting-started/react.mdx
+++ b/site/content/docs/zh/getting-started/react.mdx
@@ -30,7 +30,6 @@ export default function App() {
import { useEffect, useRef, useState } from 'react';
import { Graph, type GraphData } from '@antv/g6-lite';
-import { CircularLayout } from '@antv/layout';
const basicData: GraphData = {
nodes: [{ id: 'Alice' }, { id: 'Bob' }, { id: 'Carol' }],
@@ -58,7 +57,7 @@ export default function GraphView() {
const graph = new Graph({
container: containerRef.current,
data: basicData,
- layout: { type: CircularLayout, radius: 120 },
+ layout: { type: 'force', linkDistance: 120 },
node: { style: { size: 24, label: (node) => node.id, labelPlacement: 'bottom' } },
edge: { style: { endArrow: true } },
autoFit: fitView,
diff --git a/site/content/docs/zh/getting-started/vue.mdx b/site/content/docs/zh/getting-started/vue.mdx
index fbdc6089e..0583a4e53 100644
--- a/site/content/docs/zh/getting-started/vue.mdx
+++ b/site/content/docs/zh/getting-started/vue.mdx
@@ -31,7 +31,6 @@ import GraphView from './GraphView.vue';
-
+
+
+
```
-Resolve one version for all scripts rather than independently resolving `latest` during a release.
-
## Relayout and fitting
After initialization:
diff --git a/skills/antv-g6lite-graph/references/migration.md b/skills/antv-g6lite-graph/references/migration.md
index 85d0af297..3d72e405c 100644
--- a/skills/antv-g6lite-graph/references/migration.md
+++ b/skills/antv-g6lite-graph/references/migration.md
@@ -17,7 +17,7 @@ Requirements such as React/HTML node trees, multiple renderers, SSR, 3D, full an
| Nodes/edges | Built-in circle/rect and supported edge paths, or a supported extension | Actual appearance, labels, hit areas |
| Styles | G6Lite `node.style`, `edge.style`, state styles | Field names and callback signatures |
| Arrows | Boolean `endArrow`/`startArrow` and numeric `arrowSize` | Render and drag after conversion |
-| Layout | A supported built-in or registered optional layout | Parameters, hierarchy, cancellation, Worker behavior |
+| Layout | A built-in layout, or an imported class on builds that support layout classes | Parameters, hierarchy, cancellation, Worker behavior |
| Behaviors | G6Lite names and configuration shapes | Required defaults included in a replacement list |
| Events | Typed node/edge/Combo/canvas payloads | IDs, coordinates, selection and drag payloads |
| Data updates | `setData`, incremental mutation/state/position APIs | Camera and state retention policies |
diff --git a/skills/antv-g6lite-graph/references/troubleshooting.md b/skills/antv-g6lite-graph/references/troubleshooting.md
index a27b621a1..bfe15252a 100644
--- a/skills/antv-g6lite-graph/references/troubleshooting.md
+++ b/skills/antv-g6lite-graph/references/troubleshooting.md
@@ -8,7 +8,7 @@ Start with the observed failure and a small reproduction. Retain the application
| --- | --- | --- |
| `G6Lite` is undefined | Script response, status, CSP, load order | Load the UMD entry before initialization; show an actionable load error |
| Blank canvas | Actual container bounds, selector, WebGL, console errors | Use an existing sized client-side DOM element; reduce to two nodes |
-| All nodes overlap | Coordinates, layout type, optional registration | Supply coordinates or load/register the selected layout |
+| All nodes overlap | Coordinates, layout type, and installed version | Supply coordinates or use the selected layout's API for that version |
| Missing labels/borders | `node.style` fields and callback return values | Use `label`, `labelColor`, `strokeWidth`; remove G6 v5 option shapes |
| State styles do not apply | State names, configuration location, whole-object node style function | Use per-field node style callbacks and node/edge `stateStyles` |
| Dragging fails after arrows were added | Arrow value types | Use boolean `endArrow`/`startArrow`, numeric `arrowSize` |
@@ -25,7 +25,7 @@ Start with the observed failure and a small reproduction. Retain the application
1. Record package version, input size, browser/device, container dimensions, error text, and relevant failing requests.
2. Reduce to valid node IDs, existing edge endpoints, a sized container, and a built-in layout or supplied coordinates.
-3. Add labels/styles, interactions, Combo, optional layouts, and extensions back according to the failing feature. Confirm the first addition that reproduces it.
+3. Add labels/styles, interactions, Combo, external layouts, and extensions back according to the failing feature. Confirm the first addition that reproduces it.
4. Compare that configuration to installed declarations and an official example. If it is a library defect, retain the minimal reproduction and expected/observed behavior.
For React/SSR, Graph construction belongs in a client effect. Static imports of the ESM package are not evidence that Graph can render server-side. For async refresh, check whether `setData()` ran before `render()` completed; no initialized runtime exists at that point.
From 1a9c5081009c890110170c849f93a90839c7f43b Mon Sep 17 00:00:00 2001
From: Pearl Wang
Date: Mon, 30 Nov 2026 19:30:07 +0800
Subject: [PATCH 6/6] docs(site): finish layout refactor documentation (#76)
---
README.md | 2 +-
README.zh-CN.md | 2 +-
site/content/docs/en/api/graph.mdx | 6 +++---
site/content/docs/en/api/options.mdx | 4 ++--
site/content/docs/en/graph/overview.mdx | 2 +-
.../docs/en/guides/layout-overview.mdx | 4 +---
site/content/docs/en/guides/layout-worker.mdx | 10 ++++-----
site/content/docs/en/guides/layout.mdx | 2 +-
site/content/docs/en/metrics/bundle-size.mdx | 8 +++----
site/content/docs/en/metrics/performance.mdx | 21 ++++++++++++++-----
site/content/docs/zh/api/graph.mdx | 6 +++---
site/content/docs/zh/api/options.mdx | 4 ++--
site/content/docs/zh/graph/overview.mdx | 2 +-
.../docs/zh/guides/layout-overview.mdx | 4 +---
site/content/docs/zh/guides/layout-worker.mdx | 12 +++++------
site/content/docs/zh/guides/layout.mdx | 2 +-
site/content/docs/zh/metrics/bundle-size.mdx | 8 +++----
site/content/docs/zh/metrics/performance.mdx | 21 ++++++++++++++-----
.../homepage/bundle-measurement.json | 9 ++++----
site/src/components/homepage/content.ts | 6 ++++--
site/src/components/homepage/homepage.tsx | 3 ++-
skills/antv-g6lite-graph/SKILL.md | 4 ++--
.../antv-g6lite-graph/references/layouts.md | 4 ++--
.../references/templates/react-graph.tsx | 3 ++-
.../references/visual-design.md | 2 +-
25 files changed, 86 insertions(+), 65 deletions(-)
diff --git a/README.md b/README.md
index 0ca35aefd..9f959abcc 100644
--- a/README.md
+++ b/README.md
@@ -110,7 +110,7 @@ Use the UMD build in a browser to access `window.G6Lite`. This example uses the
- [jsDelivr](https://cdn.jsdelivr.net/npm/@antv/g6-lite/dist/g6-lite.min.js)
- [UNPKG](https://unpkg.com/@antv/g6-lite/dist/g6-lite.min.js)
-The minzip badge records Bundlephobia's measurement of the npm entry. The UMD badge measures the complete CDN download via UNPKG.
+The UMD gzip badge measures the complete UMD file served by UNPKG.
## Learn More
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 8584c3cf6..4598e630d 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -110,7 +110,7 @@ await graph.render();
- [jsDelivr](https://cdn.jsdelivr.net/npm/@antv/g6-lite/dist/g6-lite.min.js)
- [UNPKG](https://unpkg.com/@antv/g6-lite/dist/g6-lite.min.js)
-minzip 徽章记录 Bundlephobia 对 npm 入口的测量值;UMD 徽章通过 UNPKG 测量完整 CDN 文件的下载体积。
+UMD gzip 徽章测量 UNPKG 提供的完整 UMD 文件体积。
## 继续阅读
diff --git a/site/content/docs/en/api/graph.mdx b/site/content/docs/en/api/graph.mdx
index cb243281a..72fb5adbc 100644
--- a/site/content/docs/en/api/graph.mdx
+++ b/site/content/docs/en/api/graph.mdx
@@ -762,9 +762,9 @@ console.log(client, point);
### setLayout() [#setlayout]
-`graph.setLayout(config: LayoutConfig): void`
+`graph.setLayout(config: LayoutConfig | LayoutConstructor): void`
-Replaces the layout configuration. External layout classes imported from `@antv/layout` can be passed directly as `config.type` without registration. To rearrange an existing graph with the new configuration, call [layout()](#graph-layout-layout).
+Replaces the layout configuration. Pass a layout class directly, as in `graph.setLayout(CircularLayout)`, or set it as `config.type` alongside algorithm options. See [Built-in and external layouts](/en/docs/guides/layout-overview#builtin-and-external-layouts) for imports and version requirements. Call [layout()](#graph-layout-layout) to rearrange the graph.
### layout() [#graph-layout-layout]
@@ -834,7 +834,7 @@ console.log(nodes);
-String-named layouts resolve through a registered extension, Worker, then the main-thread library algorithm. Layout classes imported from `@antv/layout` execute directly on the main thread. With viewport, extension execute context width/height prefer viewport values; explicit config.width/height remain in context.options. Without viewport, context dimensions fall back to config or 800×600.
+For a string name, G6Lite checks for a registered extension first. Built-in algorithms can use a G6Lite Worker and fall back to the main-thread algorithm. A layout class manages its own execution. With viewport, extension execute context width/height prefer viewport values; explicit config.width/height remain in context.options. Without viewport, context dimensions fall back to config or 800×600.
Standalone runLayout does not perform Graph's final fx/fy override, execute Graph transforms, or emit Graph layout events. Use results in your own renderer; use instance layout for Graph's writeback, state, and event sequence.
diff --git a/site/content/docs/en/api/options.mdx b/site/content/docs/en/api/options.mdx
index a49909695..08e21b969 100644
--- a/site/content/docs/en/api/options.mdx
+++ b/site/content/docs/en/api/options.mdx
@@ -20,7 +20,7 @@ import { NodeDocExample } from '@/components/node-doc-example';
| `node` | Sets node shapes, appearance, state styles, labels, and decorations. | [`NodeConfig`](#options-node) | `circle` with theme and built-in styles |
| `edge` | Sets edge shapes, line styles, arrowheads, labels, and state styles. | [`EdgeConfig`](#options-edge) | `line` with theme and built-in styles |
| `combo` | Sets the appearance, labels, and collapsed shapes of all Combos. Define membership through `data.combos` and each node's `comboId`. | [`ComboConfig`](#options-combo) | Default Combo styles |
-| `layout` | Sets the algorithm and parameters used to position nodes. | [`LayoutConfig`](#options-layout) | Existing `x` and `y`, with missing axes set to `0` |
+| `layout` | Sets the algorithm and its parameters. Pass a layout class directly to use its defaults. | [`LayoutConfig`](#options-layout) or `LayoutConstructor` | Existing `x` and `y`, with missing axes set to `0` |
| `behaviors` | Configures interactions such as zoom, drag, and selection. An explicit array replaces the defaults. Pass `[]` to disable all behaviors. | [`BehaviorOption[]`](#options-behaviors) | `['zoom-canvas', 'drag-canvas']` |
| `transforms` | Enables custom transforms or parallel edge separation. | [`TransformOption[]`](#transforms) | — |
| `plugins` | Configures registered plugins to mount in the graph container. | [`PluginOption[]`](#plugins) | No plugins |
@@ -552,7 +552,7 @@ See the [Labels and icons guide](/en/docs/guides/label#global-label-policies) fo
| Property | Description | Type | Default |
| --- | --- | --- | --- |
| `type` | Required. A built-in layout name (`'force'`, `'force-atlas2'`, `'d3-force'`, `'fruchterman'`), a registered layout name, or a layout class imported from `@antv/layout` (such as `DagreLayout`). Unknown names use random placement. | `string \| LayoutConstructor` | — |
-| `worker` | Set to `false` to disable. Only string-named built-in layouts support Workers; layout classes imported from `@antv/layout` and custom layout classes run on the main thread. See the [layout guide](/en/docs/guides/layout#worker) for execution order and fallback behavior. | `boolean` | Graph attempts to use a Worker by default at 1,000 nodes or more for string-named built-in layouts |
+| `worker` | Controls whether a string-named built-in layout attempts to use a G6Lite Worker. See the [layout guide](/en/docs/guides/layout#worker) for execution order and fallback. | `boolean` | Graph attempts a Worker at 1,000 nodes or more for string-named built-in layouts |
| `width` | Width used for layout computation. | `number` | Current canvas width |
| `height` | Height used for layout computation. | `number` | Current canvas height |
| `center` | Layout center. Each algorithm decides whether to use it. | `[number, number]` | `[width / 2, height / 2]` |
diff --git a/site/content/docs/en/graph/overview.mdx b/site/content/docs/en/graph/overview.mdx
index 654be5882..2a798a6ff 100644
--- a/site/content/docs/en/graph/overview.mdx
+++ b/site/content/docs/en/graph/overview.mdx
@@ -60,7 +60,7 @@ After the first render, you can focus a node or update the data. For method timi
| `edge` | `EdgeConfig` | Straight edges | Sets edge shapes, arrowheads, and states. |
| `combo` | `ComboConfig` | Built-in styles | Sets group appearance, labels, and collapsed shapes. |
| `label` | `LabelOptions` | Built-in policy | Controls label scaling and visibility. |
-| `layout` | `LayoutConfig` | Input coordinates | Chooses the algorithm and options for positioning nodes. |
+| `layout` | `LayoutConfig` or `LayoutConstructor` | Input coordinates | Configures an algorithm and its options, or accepts a layout class directly. |
| `behaviors` | `BehaviorOption[]` | Canvas zoom and drag | Configures interactions such as zooming, dragging, and selection. |
| `theme` | `ThemeOption` | `'light'` | Sets default styles for the canvas and elements. |
| `transforms` | `TransformOption[]` | None | Processes input data in order before layout. |
diff --git a/site/content/docs/en/guides/layout-overview.mdx b/site/content/docs/en/guides/layout-overview.mdx
index 38fb2a3ed..8f428a657 100644
--- a/site/content/docs/en/guides/layout-overview.mdx
+++ b/site/content/docs/en/guides/layout-overview.mdx
@@ -55,7 +55,7 @@ const graph = new Graph({
You can also pass the class directly without an options object: `layout: DagreLayout`.
-External layout classes run on the main thread and do not support Workers.
+External layout classes manage their own execution. `layout.worker` controls the G6Lite Worker for string-named built-in layouts.
## Other layouts [#optional-layouts]
@@ -67,8 +67,6 @@ import { RadialLayout } from '@antv/layout';
const layout = { type: RadialLayout, focusNode: '0', unitRadius: 68 };
```
-These layout classes also run on the main thread.
-
## Configuration and example
Set the algorithm with `layout.type`. This example uses Dagre to arrange three steps from left to right.
diff --git a/site/content/docs/en/guides/layout-worker.mdx b/site/content/docs/en/guides/layout-worker.mdx
index 971c52cbb..27afa7d32 100644
--- a/site/content/docs/en/guides/layout-worker.mdx
+++ b/site/content/docs/en/guides/layout-worker.mdx
@@ -15,11 +15,11 @@ layout: { type: 'force-atlas2', worker: true, maxIteration: 100 },
| layout.worker | Graph behavior |
| --- | --- |
-| Omitted | Attempts a Worker at ≥ 1000 nodes; main thread below that threshold |
-| true | Attempts a Worker for string-named built-in layouts; layout classes imported from `@antv/layout` and registered extensions execute on the main thread |
-| false | Explicitly disables Workers, including for large graphs |
+| Omitted | Attempts a G6Lite Worker at 1,000 nodes or more for string-named built-in layouts |
+| true | Attempts a G6Lite Worker for string-named built-in layouts |
+| false | Disables the G6Lite Worker at any graph size |
-Standalone runLayout has no node-count-based automatic switch. Worker failures fall back to the same main-thread algorithm. See the [layout reference](/en/docs/guides/layout#worker) for execution order and iteration defaults.
+A registered extension with a matching name takes precedence. Registered extensions and imported layout classes manage their own execution. Standalone `runLayout` uses a G6Lite Worker when explicitly requested. Worker failures fall back to the same main-thread algorithm. See the [layout reference](/en/docs/guides/layout#worker) for execution order and iteration defaults.
## Code and rendered result
@@ -39,7 +39,7 @@ Creation, asset loading, postMessage cloning, or computation failures can trigge
## Cancellation and cleanup
-After rendering, graph.cancelLayout() can terminate that instance's active Worker and discard results. It neither rolls back completed layouts nor affects another Graph's Worker. To continue, setLayout again and await layout.
+After rendering, `graph.cancelLayout()` can terminate the instance's G6Lite Worker and discard the pending layout result. Custom layouts manage their own background tasks and resources. To continue, call `setLayout()` and await `layout()`.
The example's generation check also protects application-side completion messages and fitView from stale calls. Call graph.destroy() on unmount, and clean up your own controls, timers, and subscriptions.
diff --git a/site/content/docs/en/guides/layout.mdx b/site/content/docs/en/guides/layout.mdx
index 55dedc33a..a33a821a3 100644
--- a/site/content/docs/en/guides/layout.mdx
+++ b/site/content/docs/en/guides/layout.mdx
@@ -151,7 +151,7 @@ Layout may change existing x/y. Graph's fx/fy override the corresponding final a
## Worker
-Graph supplies worker: true when node count ≥ 1000 and worker is omitted for string-named built-in layouts. Layout classes imported from `@antv/layout` and custom layout classes cannot be transferred to a Worker and always run on the main thread. Standalone runLayout has no automatic switch. Execution order is registered extension → Worker → main-thread library. Worker creation, cloning, or execution failures fall back to the same main-thread algorithm, which may block again.
+Graph attempts a G6Lite Worker for string-named built-in layouts when `worker` is omitted and the graph has 1,000 nodes or more. Registered extensions take precedence, and they manage their own execution, as do imported layout classes. Standalone `runLayout` requires an explicit Worker request. Worker creation, cloning, or execution failures fall back to the same main-thread algorithm.
Prefer explicit worker: false for function-valued options. See [layout methods](/en/docs/api/graph#layout) for cancellation. Successful configuration does not prove a Worker actually ran.
diff --git a/site/content/docs/en/metrics/bundle-size.mdx b/site/content/docs/en/metrics/bundle-size.mdx
index 25b95bf35..b7f01b9a5 100644
--- a/site/content/docs/en/metrics/bundle-size.mdx
+++ b/site/content/docs/en/metrics/bundle-size.mdx
@@ -5,7 +5,7 @@ description: See the consolidated performance results
This content has moved to [Performance comparison](/en/docs/metrics/performance#bundle-size).
-- [build measurement](/en/docs/metrics/performance#bundle-size)
-- [esm and layout chunks](/en/docs/metrics/performance#bundle-size)
-- [umd cdn](/en/docs/metrics/performance#bundle-size)
-- [reproduce](/en/docs/metrics/performance#benchmark-method)
+- [UMD build measurements](/en/docs/metrics/performance#umd-size)
+- [Loading layouts with ESM](/en/docs/guides/layout-overview#builtin-and-external-layouts)
+- [UMD and CDN file sizes](/en/docs/metrics/performance#umd-size)
+- [Reproduce UMD size measurements](/en/docs/metrics/performance#umd-measurement)
diff --git a/site/content/docs/en/metrics/performance.mdx b/site/content/docs/en/metrics/performance.mdx
index 315dfcefe..dce63e33e 100644
--- a/site/content/docs/en/metrics/performance.mdx
+++ b/site/content/docs/en/metrics/performance.mdx
@@ -3,9 +3,9 @@ title: Performance comparison
description: First-draw timing and browser bundle sizes for G6Lite, G6, Sigma.js, and ECharts on the same graph data
---
-This comparison covers G6Lite, G6, Sigma.js, and the ECharts Graph series. All renderers receive the same precomputed positions, and all bundles use the same build settings. The 2026-11-13 comparison used a local G6Lite development build whose version field was `0.1.0`, rather than the package later published to npm.
+This page records first-draw timings and UMD file sizes for G6Lite, G6, Sigma.js, and the ECharts Graph series. Each renderer receives the same precomputed positions in the first-draw test. The G6Lite timing from November 13, 2026 uses a local development build whose version field was `0.1.0`.
-The original record did not retain a source commit or package integrity identifier for that development build, so these results apply only to that build. First-draw performance of the published package needs a separate measurement. The [CDN file sizes](#umd-size) below have been measured again using the published npm package.
+The original record did not retain a source commit or package integrity identifier for that development build, so these results apply only to that build. First-draw performance of the published package needs a separate measurement. See [UMD file sizes](#umd-size) for measurements of the layout-refactor build and published CDN files.
@@ -40,9 +40,11 @@ These results apply only to the environment above and do not certify minimum sup
-## G6Lite CDN file sizes [#umd-size]
+## UMD file sizes [#umd-size]
-The G6Lite release measurement uses the published `@antv/g6-lite@0.1.0` npm package and matches the homepage. Other libraries are measured from their published UMD bundles on unpkg. One kB is 1,000 bytes.
+The homepage shows the [source build for the layout refactor in PR #75](https://github.com/antvis/G6Lite/commit/34bf8b6d8bdac3ee97f339e2f06314c279d7c865). On November 30, 2026, `npm run size` measured `dist/g6-lite.min.js` at **118,503 bytes (118.5 kB)** with the default Node.js gzip settings. The minified file before compression was 408.1 kB. This build includes four built-in force-directed layouts and the runtime dependencies. Import other layouts as needed from `@antv/layout`. [Built-in and external layouts](/en/docs/guides/layout-overview#builtin-and-external-layouts)
+
+The table below measures published CDN files with `gzip -9`. The G6Lite measurement uses the `@antv/g6-lite@0.1.0` npm package. The other libraries use their UMD files from unpkg. One kB is 1,000 bytes.
| Library | UMD bundle | Minified (kB) | gzip -9 (kB) |
| --- | --- | ---: | ---: |
@@ -51,7 +53,16 @@ The G6Lite release measurement uses the published `@antv/g6-lite@0.1.0` npm pack
| `echarts@6.1.0` | `echarts.min.js` | 1,121.9 | 368.2 |
| `sigma@4.0.4` + `graphology@0.26.0` | `sigma.min.js` + `graphology.umd.min.js` | 466.7 | 117.6 |
-The local layout-refactor build recorded 408.1 kB before compression and 118.2 kB after gzip. That build bundles four force-directed layouts. Its other layouts are imported from `@antv/layout` and run on the main thread. [Built-in and external layouts](/en/docs/guides/layout-overview#builtin-and-external-layouts)
+### Reproduce UMD size measurements [#umd-measurement]
+
+Build G6Lite from the source commit you want to measure, then run the size check.
+
+```bash
+npm run build
+npm run size
+```
+
+For published artifacts, download the UMD file for the version in the table and run `gzip -9 -c | wc -c` to count bytes.
## Measuring your own graph [#performance-tuning]
diff --git a/site/content/docs/zh/api/graph.mdx b/site/content/docs/zh/api/graph.mdx
index 0d7a8594f..df16c218d 100644
--- a/site/content/docs/zh/api/graph.mdx
+++ b/site/content/docs/zh/api/graph.mdx
@@ -762,9 +762,9 @@ console.log(client, point);
### setLayout() [#setlayout]
-`graph.setLayout(config: LayoutConfig): void`
+`graph.setLayout(config: LayoutConfig | LayoutConstructor): void`
-替换布局配置。从 `@antv/layout` 导入的外部布局类可直接作为 `config.type` 传入,无需注册。要让已有的图按新配置重排,再调用 [layout()](#graph-layout-layout)。
+替换布局配置。可直接传入布局类,例如 `graph.setLayout(CircularLayout)`,也可通过 `config.type` 指定布局类并设置参数。导入和版本要求见[内置与外部布局](/docs/guides/layout-overview#builtin-and-external-layouts)。要按新配置重排,再调用 [layout()](#graph-layout-layout)。
### layout() [#graph-layout-layout]
@@ -834,7 +834,7 @@ console.log(nodes);
-字符串布局按已注册同名扩展、Worker、主线程库算法的顺序解析;从 `@antv/layout` 导入的布局类直接在主线程执行。传 viewport 时,扩展 execute 上下文的 width/height 优先使用 viewport;显式 config.width/height 仍在 context.options 中。无 viewport 时,上下文尺寸回退到 config 或 800×600。
+字符串布局先查找已注册的同名扩展,再对内置算法尝试 G6Lite Worker,最后执行主线程算法。直接传入的布局类由自身实现负责计算。传 viewport 时,扩展 execute 上下文的 width/height 优先使用 viewport;显式 config.width/height 仍在 context.options 中。无 viewport 时,上下文尺寸回退到 config 或 800×600。
独立 runLayout 不执行 Graph 的最终 fx/fy 覆盖,不运行 Graph transforms,也不发送 Graph 布局事件。返回后将坐标用于自己的渲染器;需要 Graph 的数据写回、状态和事件链时,使用实例 layout。
diff --git a/site/content/docs/zh/api/options.mdx b/site/content/docs/zh/api/options.mdx
index 6eb502417..d0c01491e 100644
--- a/site/content/docs/zh/api/options.mdx
+++ b/site/content/docs/zh/api/options.mdx
@@ -20,7 +20,7 @@ import { NodeDocExample } from '@/components/node-doc-example';
| `node` | 设置节点形状、外观、状态样式、标签和装饰。 | [`NodeConfig`](#options-node) | `circle`,使用主题和内置样式 |
| `edge` | 设置边的形状、线条、箭头、标签和状态样式。 | [`EdgeConfig`](#options-edge) | `line`,使用主题和内置样式 |
| `combo` | 设置所有 Combo 的外观、标签和折叠形态。分组关系由 `data.combos` 和节点的 `comboId` 声明。 | [`ComboConfig`](#options-combo) | 使用默认分组样式 |
-| `layout` | 指定布局算法及其参数,用于计算节点位置。 | [`LayoutConfig`](#options-layout) | 使用已有 `x`、`y`,缺省轴为 `0` |
+| `layout` | 指定布局算法及其参数。可直接传入布局类以使用其默认参数。 | [`LayoutConfig`](#options-layout) 或 `LayoutConstructor` | 使用已有 `x`、`y`,缺省轴为 `0` |
| `behaviors` | 配置缩放、拖拽、选择等交互。显式数组替换默认行为,`[]` 禁用全部行为。 | [`BehaviorOption[]`](#options-behaviors) | `['zoom-canvas', 'drag-canvas']` |
| `transforms` | 启用自定义数据处理或平行边分离。 | [`TransformOption[]`](#transforms) | — |
| `plugins` | 配置要在图容器中挂载的已注册插件。 | [`PluginOption[]`](#plugins) | 无插件 |
@@ -552,7 +552,7 @@ graph.updateNodeData('A', { score: 80 });
| 属性 | 描述 | 类型 | 默认值 |
| --- | --- | --- | --- |
| `type` | 必填。内置布局名称(`'force'`、`'force-atlas2'`、`'d3-force'`、`'fruchterman'`)、已注册的布局名,或直接从 `@antv/layout` 导入的布局类(如 `DagreLayout`)。未知名称采用随机坐标。 | `string \| LayoutConstructor` | — |
-| `worker` | 设为 `false` 可关闭。仅字符串形式的内置布局支持 Worker;从 `@antv/layout` 导入的布局类和自定义布局类在主线程执行。执行顺序与回退见[布局指南](/docs/guides/layout#worker)。 | `boolean` | Graph 中节点数 ≥ 1000 且为字符串内置布局时默认尝试启用 |
+| `worker` | 控制字符串形式的内置布局是否尝试使用 G6Lite Worker。执行顺序与回退见[布局指南](/docs/guides/layout#worker)。 | `boolean` | Graph 中节点数 ≥ 1000 且为字符串内置布局时默认尝试启用 |
| `width` | 布局计算使用的宽度。 | `number` | 当前画布宽度 |
| `height` | 布局计算使用的高度。 | `number` | 当前画布高度 |
| `center` | 布局中心,是否使用由算法决定。 | `[number, number]` | `[width / 2, height / 2]` |
diff --git a/site/content/docs/zh/graph/overview.mdx b/site/content/docs/zh/graph/overview.mdx
index b7e75fcc5..11ff03349 100644
--- a/site/content/docs/zh/graph/overview.mdx
+++ b/site/content/docs/zh/graph/overview.mdx
@@ -60,7 +60,7 @@ await graph.render();
| `edge` | `EdgeConfig` | 直线边 | 配置线型、箭头和状态。 |
| `combo` | `ComboConfig` | 内置样式 | 配置分组外观、标签和折叠形态。 |
| `label` | `LabelOptions` | 内置策略 | 控制标签的缩放和可见性。 |
-| `layout` | `LayoutConfig` | 使用数据坐标 | 指定布局算法及参数,由布局计算节点位置。 |
+| `layout` | `LayoutConfig` 或 `LayoutConstructor` | 使用数据坐标 | 配置布局算法及参数,也可直接传入布局类。 |
| `behaviors` | `BehaviorOption[]` | 缩放、拖动画布 | 配置缩放、拖拽、选择等交互。 |
| `theme` | `ThemeOption` | `'light'` | 设置画布和元素的默认样式。 |
| `transforms` | `TransformOption[]` | 无 | 按顺序处理布局前的输入数据。 |
diff --git a/site/content/docs/zh/guides/layout-overview.mdx b/site/content/docs/zh/guides/layout-overview.mdx
index d3c6063f5..d1625dccd 100644
--- a/site/content/docs/zh/guides/layout-overview.mdx
+++ b/site/content/docs/zh/guides/layout-overview.mdx
@@ -55,7 +55,7 @@ const graph = new Graph({
也可以省略配置对象,直接传布局类:`layout: DagreLayout`。
-外部布局类在主线程执行,不支持 Worker。
+外部布局类由各自的实现负责计算。`layout.worker` 调度的是 G6Lite 的字符串内置布局。
## 其他布局 [#optional-layouts]
@@ -67,8 +67,6 @@ import { RadialLayout } from '@antv/layout';
const layout = { type: RadialLayout, focusNode: '0', unitRadius: 68 };
```
-这些布局类也在主线程运行。
-
## 配置与示例
布局类型通过 `layout.type` 指定。下面用 Dagre 把三个步骤从左到右排列。
diff --git a/site/content/docs/zh/guides/layout-worker.mdx b/site/content/docs/zh/guides/layout-worker.mdx
index 9a328368a..7bab809b6 100644
--- a/site/content/docs/zh/guides/layout-worker.mdx
+++ b/site/content/docs/zh/guides/layout-worker.mdx
@@ -9,7 +9,7 @@ Worker 可以把布局计算放到后台线程,让画布在计算期间保持
## 启用方式
-布局是否尝试在后台计算,由 `layout.worker` 设置。
+`layout.worker` 控制内置布局是否尝试使用 G6Lite Worker。
```ts
layout: { type: 'force-atlas2', worker: true, maxIteration: 100 },
@@ -17,11 +17,11 @@ layout: { type: 'force-atlas2', worker: true, maxIteration: 100 },
| layout.worker | Graph 中的行为 |
| --- | --- |
-| 省略 | 节点数 ≥ 1000 时尝试启用;低于 1000 时走主线程 |
-| true | 对字符串形式的内置布局尝试 Worker;从 `@antv/layout` 导入的布局类和注册扩展均在主线程执行 |
-| false | 显式关闭,包括大图 |
+| 省略 | 字符串形式的内置布局在节点数 ≥ 1000 时尝试启用 |
+| true | 对字符串形式的内置布局尝试使用 G6Lite Worker |
+| false | 关闭 G6Lite Worker,包括大图 |
-独立 runLayout 没有按节点数自动启用的行为。Worker 失败会回退到同一算法的主线程实现;具体执行顺序和默认迭代值见[布局参考](/docs/guides/layout#worker)。
+已注册的同名扩展优先。注册扩展和导入的布局类自行管理计算。独立调用 `runLayout` 时按显式的 `worker` 值启用 G6Lite Worker。Worker 失败会回退到同一算法的主线程实现,见[布局参考](/docs/guides/layout#worker)。
## 代码与对应效果
@@ -41,7 +41,7 @@ Worker 仅收到节点 id/x/y/data 和边 source/target/data。Graph 在结果
## 取消与清理
-在渲染完成的实例上调用 graph.cancelLayout(),可终止该实例正在使用的 Worker 并放弃结果;不会回滚已完成布局,也不会影响其他 Graph 的 Worker。继续切换时,重新 setLayout 后 await layout。
+在渲染完成的实例上调用 `graph.cancelLayout()`,可以终止该实例的 G6Lite Worker 并放弃本次布局结果。自定义布局自己管理后台任务与资源。继续切换时,调用 `setLayout()` 后等待 `layout()`。
示例的 generation 检查还保护应用自己的完成提示和 fitView,避免过期调用结束后继续执行这些副作用。卸载时调用 graph.destroy();自行创建的按钮、计时器和订阅也要清理。
diff --git a/site/content/docs/zh/guides/layout.mdx b/site/content/docs/zh/guides/layout.mdx
index b24887065..6e43cdfa5 100644
--- a/site/content/docs/zh/guides/layout.mdx
+++ b/site/content/docs/zh/guides/layout.mdx
@@ -149,7 +149,7 @@ graph.fitView({ padding: 48, maxZoom: 1 });
## Worker
-字符串形式的内置布局可通过 `worker: true` 尝试在后台线程计算,图达到 1000 个节点时默认尝试启用。从 `@antv/layout` 导入的布局类及自定义布局类无法传入 Worker,始终在主线程执行。算法参数包含函数时,可设置 `worker: false` 在主线程计算。启用、回退和取消示例见 [Worker 布局指南](/docs/guides/layout-worker)。
+字符串形式的内置布局可通过 `worker: true` 尝试使用 G6Lite Worker。省略该选项时,达到 1000 个节点的内置布局会默认尝试启用。注册扩展和导入的布局类自行管理计算。内置算法参数包含函数时,可设置 `worker: false` 在主线程计算。启用、回退和取消示例见 [Worker 布局指南](/docs/guides/layout-worker)。
## 常见问题
diff --git a/site/content/docs/zh/metrics/bundle-size.mdx b/site/content/docs/zh/metrics/bundle-size.mdx
index f5aa36cbe..c59eaff1d 100644
--- a/site/content/docs/zh/metrics/bundle-size.mdx
+++ b/site/content/docs/zh/metrics/bundle-size.mdx
@@ -5,7 +5,7 @@ description: 查看合并后的性能数据
内容已并入[性能对比](/docs/metrics/performance#bundle-size)。
-- [构建测量](/docs/metrics/performance#bundle-size)
-- [esm 与布局分块](/docs/metrics/performance#bundle-size)
-- [umd cdn](/docs/metrics/performance#bundle-size)
-- [如何复测](/docs/metrics/performance#benchmark-method)
+- [UMD 构建测量](/docs/metrics/performance#umd-size)
+- [ESM 布局接入](/docs/guides/layout-overview#builtin-and-external-layouts)
+- [UMD 与 CDN 体积](/docs/metrics/performance#umd-size)
+- [复测 UMD 体积](/docs/metrics/performance#umd-measurement)
diff --git a/site/content/docs/zh/metrics/performance.mdx b/site/content/docs/zh/metrics/performance.mdx
index 6c51d3b25..2f59750f4 100644
--- a/site/content/docs/zh/metrics/performance.mdx
+++ b/site/content/docs/zh/metrics/performance.mdx
@@ -3,9 +3,9 @@ title: 性能对比
description: 同一图数据下 G6Lite、G6、Sigma.js 与 ECharts 的首绘耗时和浏览器包体积
---
-本页比较 G6Lite、G6、Sigma.js 和 ECharts 的 Graph 系列。首绘使用同一份预置坐标数据,包体积使用同一种构建方式。2026-11-13 的对比测试使用 G6Lite 本地开发构建,当时的版本字段为 `0.1.0`;它不是后来发布到 npm 的正式包。
+本页记录 G6Lite、G6、Sigma.js 和 ECharts Graph 系列的首绘耗时与 UMD 文件体积。首绘使用同一份预置坐标数据。2026-11-13 的 G6Lite 首绘测试使用版本字段为 `0.1.0` 的本地开发构建。
-原始记录未保存该开发构建的源码提交号或包完整性标识,因此这些结果仅对应当时的构建。正式包的首绘性能需要单独复测;下方 [CDN 文件体积](#umd-size)已按 npm 正式发布包重新测量。
+原始记录未保存该开发构建的源码提交号或包完整性标识,因此这些结果仅对应当时的构建。正式包的首绘性能需要单独复测。下方 [UMD 文件体积](#umd-size)列出布局重构构建和已发布 CDN 产物的测量值。
@@ -36,9 +36,11 @@ description: 同一图数据下 G6Lite、G6、Sigma.js 与 ECharts 的首绘耗
-## G6Lite CDN 文件体积 [#umd-size]
+## UMD 文件体积 [#umd-size]
-G6Lite 的发布数据来自 npm 上的 `@antv/g6-lite@0.1.0`,与首页使用同一口径。其他库测量自 unpkg 上发布的 UMD 产物。1 kB = 1,000 字节。
+首页展示 [PR #75 的布局重构源码构建](https://github.com/antvis/G6Lite/commit/34bf8b6d8bdac3ee97f339e2f06314c279d7c865)。2026-11-30 构建后运行 `npm run size`,用 Node.js 的默认 gzip 设置测得 `dist/g6-lite.min.js` 为 **118,503 字节(118.5 kB)**,压缩前为 408.1 kB。该构建包含四种内置力导向布局和运行时依赖。其他布局可从 `@antv/layout` 按需导入。 [内置与外部布局](/docs/guides/layout-overview#builtin-and-external-layouts)
+
+下表使用 `gzip -9` 测量已发布的 CDN 产物。G6Lite 使用 npm 上的 `@antv/g6-lite@0.1.0`,其他库使用 unpkg 上的 UMD 文件。1 kB = 1,000 字节。
| 库 | UMD 产物 | 压缩前(kB) | gzip 后(kB) |
| --- | --- | ---: | ---: |
@@ -47,7 +49,16 @@ G6Lite 的发布数据来自 npm 上的 `@antv/g6-lite@0.1.0`,与首页使用
| `echarts@6.1.0` | `echarts.min.js` | 1,121.9 | 368.2 |
| `sigma@4.0.4` + `graphology@0.26.0` | `sigma.min.js` + `graphology.umd.min.js` | 466.7 | 117.6 |
-布局重构的本地开发构建记录为 408.1 kB,gzip 后为 118.2 kB。该构建只内置四种力导向布局,其他布局从 `@antv/layout` 导入后在主线程执行。 [内置与外部布局](/docs/guides/layout-overview#builtin-and-external-layouts)
+### 复测 UMD 体积 [#umd-measurement]
+
+从要测量的源码提交构建 G6Lite,再运行体积检查。
+
+```bash
+npm run build
+npm run size
+```
+
+测量已发布产物时,下载表中对应版本的 UMD 文件,再用 `gzip -9 -c <文件路径> | wc -c` 获取字节数。
## 业务图怎么测 [#performance-tuning]
diff --git a/site/src/components/homepage/bundle-measurement.json b/site/src/components/homepage/bundle-measurement.json
index 2b03be8ef..7b75ba39e 100644
--- a/site/src/components/homepage/bundle-measurement.json
+++ b/site/src/components/homepage/bundle-measurement.json
@@ -1,10 +1,9 @@
{
- "version": "0.1.0",
+ "sourceCommit": "34bf8b6d8bdac3ee97f339e2f06314c279d7c865",
"measuredAt": "2026-11-30",
- "gzipBytes": 150304,
+ "gzipBytes": 118503,
"unitBytes": 1000,
"entry": "dist/g6-lite.min.js",
- "compression": "Gzip -9",
- "source": "https://registry.npmjs.org/@antv/g6-lite/-/g6-lite-0.1.0.tgz",
- "command": "gzip -9 -c package/dist/g6-lite.min.js | wc -c"
+ "compression": "Gzip",
+ "command": "npm run size"
}
diff --git a/site/src/components/homepage/content.ts b/site/src/components/homepage/content.ts
index 4d86b13fe..437a2bf6c 100644
--- a/site/src/components/homepage/content.ts
+++ b/site/src/components/homepage/content.ts
@@ -28,7 +28,8 @@ const zh = {
loadTitle: '轻量加载',
loadDescription: '核心入口与布局算法分离,按需加载所选布局,降低初始化阶段的加载开销。',
measured: 'UMD 包体积',
- umdScope: '含内置布局和依赖',
+ umdScope: '含 4 种内置力导向布局和依赖',
+ measurementSource: '源码构建',
sizeLink: '查看体积测量口径',
interactionTitle: '高性能渲染',
interactionDescription:
@@ -182,7 +183,8 @@ const en: typeof zh = {
loadTitle: 'Lightweight loading',
loadDescription: 'Layout algorithms load on demand, keeping the initial core bundle small.',
measured: 'UMD bundle size',
- umdScope: 'Includes built-in layouts and dependencies',
+ umdScope: 'Includes four built-in force layouts and dependencies',
+ measurementSource: 'Source build',
sizeLink: 'How we measure bundle size',
interactionTitle: 'High-performance rendering',
interactionDescription:
diff --git a/site/src/components/homepage/homepage.tsx b/site/src/components/homepage/homepage.tsx
index cae4813eb..b806b1a2a 100644
--- a/site/src/components/homepage/homepage.tsx
+++ b/site/src/components/homepage/homepage.tsx
@@ -101,7 +101,8 @@ export async function Homepage({ locale = 'zh' }: { locale?: Locale }) {
{bundleMeasurement.entry}
- v{bundleMeasurement.version} · {bundleMeasurement.measuredAt}
+ {copy.performance.measurementSource} · {bundleMeasurement.sourceCommit.slice(0, 7)} ·{' '}
+ {bundleMeasurement.measuredAt}
.
-// The host application needs React and @antv/g6-lite; no repository demo helpers are used.
+// This template requires React, a G6Lite build with layout class support, and @antv/layout@^2.1.0.
+// For the published G6Lite 0.1.0, remove the DagreLayout import and use type: 'dagre' below.
export function RelationshipGraph({ data, onNodeClick }: Props) {
const containerRef = useRef(null);
const runtimeRef = useRef(null);
diff --git a/skills/antv-g6lite-graph/references/visual-design.md b/skills/antv-g6lite-graph/references/visual-design.md
index e29fcaa66..5af70457d 100644
--- a/skills/antv-g6lite-graph/references/visual-design.md
+++ b/skills/antv-g6lite-graph/references/visual-design.md
@@ -15,7 +15,7 @@ Keep the existing application's design language. For a standalone graph, choose
| --- | --- |
| Small flow/dependency graph | Dagre left-to-right; labels on each node; directional edges; generous rank spacing |
| Relationship network | Force layout; short external labels; hover emphasis and click details |
-| Mind map/tree | Register the tree layout; use hierarchy and branch colors; keep full labels readable inside rectangles |
+| Mind map/tree | Choose a [tree layout for your G6Lite version](layouts.md). Use hierarchy and branch colors and keep labels readable inside rectangles. |
| Dense or large network | Reduce default labels; reveal relevant labels/details through supported configuration or application UI; provide search and focus |
Start around 12–14 CSS pixels for ordinary labels and validate at the target viewport. Long names need sufficient node width, spacing, or supported `labelMaxWidth` settings; do not shrink every label until it becomes unreadable. Use `node.style.label` / `edge.style.label` instead of copying repository-only demo canvas helpers.