diff --git a/.eslintignore b/.eslintignore
new file mode 100644
index 00000000000..45b5d291c22
--- /dev/null
+++ b/.eslintignore
@@ -0,0 +1,4 @@
+dist
+es
+lib
+node_modules
\ No newline at end of file
diff --git a/.eslintrc.js b/.eslintrc.js
new file mode 100644
index 00000000000..7670df5d186
--- /dev/null
+++ b/.eslintrc.js
@@ -0,0 +1,56 @@
+module.exports = {
+ root: true,
+ env: {
+ browser: true,
+ es2021: true,
+ node: true,
+ commonjs: true,
+ jest: true,
+ },
+ extends: ['eslint:recommended', 'plugin:@typescript-eslint/recommended', 'plugin:jsdoc/recommended-error'],
+ overrides: [
+ {
+ env: {
+ node: true,
+ },
+ files: ['.eslintrc.{js,cjs}'],
+ parserOptions: {
+ sourceType: 'script',
+ },
+ },
+ ],
+ parser: '@typescript-eslint/parser',
+ parserOptions: {
+ ecmaVersion: 'latest',
+ sourceType: 'module',
+ },
+ plugins: ['@typescript-eslint', 'jsdoc'],
+ rules: {
+ // indent: ['error', 2, { SwitchCase: 1 }],
+ 'linebreak-style': ['error', 'unix'],
+ quotes: ['error', 'single', { allowTemplateLiterals: true, avoidEscape: true }],
+ semi: ['error', 'always'],
+
+ 'jsdoc/require-param-type': 0,
+ '@typescript-eslint/no-this-alias': 'off',
+
+ // TODO: rules below will be set to 2 in the future
+ 'jsdoc/require-jsdoc': 1,
+ 'jsdoc/check-access': 1,
+ 'jsdoc/check-tag-names': 1,
+ 'jsdoc/require-description': 1,
+ 'jsdoc/require-param': 1,
+ 'jsdoc/check-param-names': 1,
+ 'jsdoc/require-param-description': 1,
+ 'jsdoc/require-returns': 1,
+ 'jsdoc/require-returns-type': 0,
+ 'jsdoc/require-returns-description': 1,
+
+ '@typescript-eslint/no-unused-vars': 1,
+
+ // TODO: rules below are not recommended, and will be removed in the future
+ '@typescript-eslint/no-explicit-any': 1,
+ '@typescript-eslint/ban-types': 1,
+ '@typescript-eslint/ban-ts-comment': 1,
+ },
+};
diff --git a/.gitignore b/.gitignore
index f5c500be45e..73a830ee496 100644
--- a/.gitignore
+++ b/.gitignore
@@ -25,13 +25,4 @@ esm
coverage
# Bundle visualizer
-stats.html
-
-# Snapshots error images
-packages/g6/tests/integration/snapshots/**/*-actual.*
-packages/g6/tests/integration/snapshots/**/*-diff.*
-
-# Website cache byb dumi
-site/.dumi/tmp
-site/.dumi/tmp-production
-
+stats.html
\ No newline at end of file
diff --git a/.prettierignore b/.prettierignore
new file mode 100644
index 00000000000..45b5d291c22
--- /dev/null
+++ b/.prettierignore
@@ -0,0 +1,4 @@
+dist
+es
+lib
+node_modules
\ No newline at end of file
diff --git a/.prettierrc b/.prettierrc
deleted file mode 100644
index 764fbde2e82..00000000000
--- a/.prettierrc
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "singleQuote": true,
- "trailingComma": "all",
- "printWidth": 120,
- "overrides": [
- {
- "files": ".prettierrc",
- "options": { "parser": "json" }
- }
- ]
-}
diff --git a/packages/react-node/.prettierrc.js b/.prettierrc.js
similarity index 87%
rename from packages/react-node/.prettierrc.js
rename to .prettierrc.js
index e6df093da70..b79bdf3eea5 100644
--- a/packages/react-node/.prettierrc.js
+++ b/.prettierrc.js
@@ -1,10 +1,9 @@
module.exports = {
- pluginSearchDirs: false,
plugins: [
require.resolve('prettier-plugin-organize-imports'),
require.resolve('prettier-plugin-packagejson'),
],
- printWidth: 80,
+ printWidth: 120,
proseWrap: 'never',
singleQuote: true,
trailingComma: 'all',
diff --git a/package.json b/package.json
index 80000480c5a..8c0ede01255 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,7 @@
{
"name": "g6",
"private": true,
+ "repository": "https://github.com/antvis/G6.git",
"scripts": {
"postinstall": "husky install",
"prepare": "husky install",
@@ -10,25 +11,46 @@
"build:react-node": "cd ./packages/react-node && npm run build",
"build:site": "cd ./packages/site && npm run build"
},
- "devDependencies": {
- "@commitlint/cli": "^17.8.1",
- "@commitlint/config-conventional": "^17.8.1",
- "husky": "^8.0.3",
- "lint-staged": "^10.5.4",
- "npm-run-all": "^4.1.5",
- "prettier": "^2.8.8"
+ "commitlint": {
+ "extends": [
+ "@commitlint/config-conventional"
+ ]
},
"lint-staged": {
"*.{ts,tsx}": [
"eslint --fix",
- "prettier --write",
- "git add"
+ "prettier --write"
]
},
- "pnpm": {
- "overrides": {
- "prettier": "^2.8.8"
- }
- },
- "repository": "https://github.com/antvis/G6.git"
+ "devDependencies": {
+ "@commitlint/cli": "^18.4.3",
+ "@commitlint/config-conventional": "^18.4.3",
+ "@rollup/plugin-commonjs": "^25.0.7",
+ "@rollup/plugin-node-resolve": "^15.2.3",
+ "@rollup/plugin-terser": "^0.4.4",
+ "@rollup/plugin-typescript": "^11.1.5",
+ "@types/jest": "^29.5.11",
+ "@types/jsdom": "^21.1.6",
+ "@types/node": "^20.10.5",
+ "@typescript-eslint/eslint-plugin": "^6.15.0",
+ "@typescript-eslint/parser": "^6.15.0",
+ "eslint": "^8.56.0",
+ "eslint-plugin-jsdoc": "^46.9.1",
+ "husky": "^8.0.3",
+ "jest": "^29.7.0",
+ "jest-environment-jsdom": "^29.7.0",
+ "jsdom": "^23.0.1",
+ "limit-size": "^0.1.4",
+ "lint-staged": "^15.2.0",
+ "npm-run-all": "^4.1.5",
+ "prettier": "^3.1.1",
+ "prettier-plugin-organize-imports": "^3.2.4",
+ "prettier-plugin-packagejson": "^2.4.7",
+ "rimraf": "^5.0.5",
+ "rollup": "^4.9.1",
+ "rollup-plugin-polyfill-node": "^0.13.0",
+ "rollup-plugin-visualizer": "^5.11.0",
+ "ts-jest": "^29.1.1",
+ "typescript": "^5.3.3"
+ }
}
diff --git a/packages/g6-plugin-map-view/.eslintignore b/packages/g6-plugin-map-view/.eslintignore
deleted file mode 100644
index 96b252f79ec..00000000000
--- a/packages/g6-plugin-map-view/.eslintignore
+++ /dev/null
@@ -1,6 +0,0 @@
-dist
-es
-lib
-node_modules
-*.ejs
-*.min.js
\ No newline at end of file
diff --git a/packages/g6-plugin-map-view/.eslintrc b/packages/g6-plugin-map-view/.eslintrc
deleted file mode 100644
index 8cd2a18cfee..00000000000
--- a/packages/g6-plugin-map-view/.eslintrc
+++ /dev/null
@@ -1,40 +0,0 @@
-{
- "root": true,
- "parser": "@typescript-eslint/parser",
- "plugins": ["@typescript-eslint"],
- "extends": [
- "eslint:recommended",
- "plugin:@typescript-eslint/recommended",
- "plugin:import/errors",
- "plugin:import/warnings",
- "plugin:import/typescript",
- "prettier"
- ],
- "rules": {
- "no-constant-condition": [
- "error",
- {
- "checkLoops": false
- }
- ],
- "@typescript-eslint/no-empty-interface": "warn",
- "@typescript-eslint/no-var-requires": "off",
- "@typescript-eslint/ban-ts-comment": "off",
- "@typescript-eslint/ban-types": "warn",
- "@typescript-eslint/explicit-module-boundary-types": "off",
- "@typescript-eslint/no-explicit-any": "off",
- "@typescript-eslint/no-empty-function": "off",
- "@typescript-eslint/no-unused-vars": "off",
- "no-fallthrough": "off",
- "import/no-unresolved": "off",
- "no-multiple-empty-lines": 1,
- "no-prototype-builtins": "warn",
- "import/order": "warn",
- "import/namespace": "warn",
- // Allow `const self = this`.
- "@typescript-eslint/no-this-alias": "off"
- },
- "env": {
- "node": true
- }
-}
diff --git a/packages/g6-plugin-map-view/.prettierrc b/packages/g6-plugin-map-view/.prettierrc
deleted file mode 100644
index 94beb148408..00000000000
--- a/packages/g6-plugin-map-view/.prettierrc
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "singleQuote": true,
- "trailingComma": "all",
- "printWidth": 80,
- "overrides": [
- {
- "files": ".prettierrc",
- "options": { "parser": "json" }
- }
- ]
-}
diff --git a/packages/g6-plugin-map-view/package.json b/packages/g6-plugin-map-view/package.json
index 6cd5acf94c9..c6fa7b61c23 100644
--- a/packages/g6-plugin-map-view/package.json
+++ b/packages/g6-plugin-map-view/package.json
@@ -26,19 +26,18 @@
"dist"
],
"scripts": {
- "start": "rimraf ./lib && tsc --module commonjs --outDir lib --watch",
- "build:umd": "rimraf ./dist && rollup -c && npm run size",
+ "build": "run-p build:*",
"build:cjs": "rimraf ./lib && tsc --module commonjs --outDir lib",
"build:esm": "rimraf ./esm && tsc --module ESNext --outDir esm",
- "build": "run-p build:*",
+ "build:umd": "rimraf ./dist && rollup -c && npm run size",
"bundle-vis": "cross-env BUNDLE_VIS=1 run-p build:umd",
- "prepublishOnly": "npm run ci",
"ci": "run-s lint build",
"clean": "rimraf es lib",
"clear:doc": "rimraf ../site/docs/_apis",
- "doc": "npm run clear:doc && typedoc",
"lint": "eslint ./src --quiet && prettier ./src --check",
- "size": "limit-size"
+ "prepublishOnly": "npm run ci",
+ "size": "limit-size",
+ "start": "rimraf ./lib && tsc --module commonjs --outDir lib --watch"
},
"dependencies": {
"@antv/dom-util": "^2.0.4",
@@ -46,35 +45,8 @@
"@antv/l7-maps": "^2.18.3",
"@antv/util": "~2.0.5"
},
- "devDependencies": {
- "@rollup/plugin-terser": "^0.4.3",
- "@types/gl": "6.0.2",
- "@types/jsdom": "^21.1.1",
- "@types/node": "13.11.1",
- "@types/pixelmatch": "^5.2.4",
- "@types/pngjs": "^6.0.1",
- "@types/xmlserializer": "^0.6.3",
- "@typescript-eslint/eslint-plugin": "^6.5.0",
- "@typescript-eslint/parser": "^6.5.0",
- "@umijs/fabric": "^2.0.0",
- "babel-loader": "^8.0.6",
- "eslint": "^8.48.0",
- "eslint-plugin-import": "^2.28.1",
- "father": "^2.29.1",
- "gl": "^6.0.2",
- "jsdom": "^19.0.0",
- "limit-size": "^0.1.4",
- "npm-run-all": "^4.1.5",
- "prettier": "^3.0.3",
- "rimraf": "^3.0.0",
- "rollup": "^2.79.1",
- "rollup-plugin-node-resolve": "^5.2.0",
- "rollup-plugin-polyfill-node": "^0.8.0",
- "rollup-plugin-typescript": "^1.0.1",
- "rollup-plugin-visualizer": "^5.6.0",
- "tslib": "^2.5.0",
- "typedoc": "^0.25.0",
- "typescript": "5.1.6"
+ "peerDependencies": {
+ "@antv/g6": "^5.0.0-beta.28"
},
"limit-size": [
{
@@ -86,8 +58,5 @@
"path": "dist/g6-plugin-map-view.min.js",
"limit": "3 Mb"
}
- ],
- "peerDependencies": {
- "@antv/g6": "^5.0.0-beta.28"
- }
+ ]
}
diff --git a/packages/g6-plugin-map-view/rollup.config.js b/packages/g6-plugin-map-view/rollup.config.mjs
similarity index 60%
rename from packages/g6-plugin-map-view/rollup.config.js
rename to packages/g6-plugin-map-view/rollup.config.mjs
index 0196fc03e15..cbb1c5f8c46 100644
--- a/packages/g6-plugin-map-view/rollup.config.js
+++ b/packages/g6-plugin-map-view/rollup.config.mjs
@@ -1,13 +1,13 @@
-import terser from '@rollup/plugin-terser';
-import resolve from 'rollup-plugin-node-resolve';
-import typescript from 'rollup-plugin-typescript';
import commonjs from '@rollup/plugin-commonjs';
+import resolve from '@rollup/plugin-node-resolve';
+import terser from '@rollup/plugin-terser';
+import typescript from '@rollup/plugin-typescript';
import nodePolyfills from 'rollup-plugin-polyfill-node';
import { visualizer } from 'rollup-plugin-visualizer';
const isBundleVis = !!process.env.BUNDLE_VIS;
-module.exports = [
+export default [
{
input: 'src/index.ts',
output: {
@@ -16,13 +16,6 @@ module.exports = [
format: 'umd',
sourcemap: false,
},
- plugins: [
- nodePolyfills(),
- resolve(),
- commonjs(),
- typescript(),
- terser(),
- ...(isBundleVis ? [visualizer()] : []),
- ],
+ plugins: [nodePolyfills(), resolve(), commonjs(), typescript(), terser(), ...(isBundleVis ? [visualizer()] : [])],
},
];
diff --git a/packages/g6-plugin-map-view/src/index.ts b/packages/g6-plugin-map-view/src/index.ts
index 2fe9820dbb3..c699a5e45d1 100644
--- a/packages/g6-plugin-map-view/src/index.ts
+++ b/packages/g6-plugin-map-view/src/index.ts
@@ -1,8 +1,9 @@
-import { Scene, LineLayer, PointLayer, RasterLayer } from '@antv/l7';
-import { Map as BaseMap } from '@antv/l7-maps';
+// @ts-nocheck
import { createDom, modifyCSS } from '@antv/dom-util';
+import { IGraph, IPluginBaseConfig, PluginBase } from '@antv/g6';
+import { LineLayer, PointLayer, RasterLayer, Scene } from '@antv/l7';
+import { Map as BaseMap } from '@antv/l7-maps';
import { debounce, isArray, isString, uniqueId } from '@antv/util';
-import { IGraph, PluginBase, IPluginBaseConfig } from '@antv/g6';
export interface MapViewConfig extends IPluginBaseConfig {
key?: string;
@@ -99,14 +100,7 @@ export class MapView extends PluginBase {
*/
public initMap() {
const { graph, options } = this;
- const {
- size,
- className,
- containerStyle,
- theme,
- initialMapZoom,
- initialMapCenter,
- } = options;
+ const { size, className, containerStyle, theme, initialMapZoom, initialMapCenter } = options;
let parentNode = options.container;
const container: HTMLDivElement = createDom(
`
`,
@@ -168,9 +162,7 @@ export class MapView extends PluginBase {
return new Promise((resolve) => {
this.scene.on('loaded', () => {
this.scene.addLayer(baseMapLayer);
- const amapCopyRightDom = document.getElementsByClassName(
- 'amap-copyright',
- )[0] as HTMLElement;
+ const amapCopyRightDom = document.getElementsByClassName('amap-copyright')[0] as HTMLElement;
amapCopyRightDom?.remove();
this.scene.setMapStatus({
dragEnable: true,
@@ -236,12 +228,7 @@ export class MapView extends PluginBase {
}
private newPointLayer(options: any = {}) {
- const {
- sizeField = 'keyShapeSize',
- sizeNeedScale = true,
- style,
- ...others
- } = options;
+ const { sizeField = 'keyShapeSize', sizeNeedScale = true, style, ...others } = options;
const layer = new PointLayer(others);
layer
.source([], {
@@ -300,13 +287,7 @@ export class MapView extends PluginBase {
private addMapListeners() {
const { graph, options } = this;
- const {
- enableHoverActivate,
- activateState,
- enableSelect,
- selectState,
- enableBrushSelect,
- } = options;
+ const { enableHoverActivate, activateState, enableSelect, selectState, enableBrushSelect } = options;
if (enableBrushSelect) {
this.scene.on('selecting', this.onBrushing.bind(this));
@@ -318,9 +299,7 @@ export class MapView extends PluginBase {
});
this.lineLayer.on('mouseout', (e) => {
const activeEdgeIds = graph.findIdByState('edge', activateState);
- const features = this.lineLayer
- .getSource()
- .data.dataArray.filter((model) => activeEdgeIds.includes(model.id));
+ const features = this.lineLayer.getSource().data.dataArray.filter((model) => activeEdgeIds.includes(model.id));
this.setItemState('edge', features, activateState, false);
});
this.pointLayer.on('mouseenter', (e) => {
@@ -328,9 +307,7 @@ export class MapView extends PluginBase {
});
this.pointLayer.on('mouseout', (e) => {
const activeNodeIds = graph.findIdByState('node', activateState);
- const features = this.pointLayer
- .getSource()
- .data.dataArray.filter((model) => activeNodeIds.includes(model.id));
+ const features = this.pointLayer.getSource().data.dataArray.filter((model) => activeNodeIds.includes(model.id));
this.setItemState('node', features, activateState, false);
});
}
@@ -340,9 +317,7 @@ export class MapView extends PluginBase {
});
this.lineLayer.on('unclick', (e) => {
const activeEdgeIds = graph.findIdByState('edge', selectState);
- const features = this.lineLayer
- .getSource()
- .data.dataArray.filter((model) => activeEdgeIds.includes(model.id));
+ const features = this.lineLayer.getSource().data.dataArray.filter((model) => activeEdgeIds.includes(model.id));
this.setItemState('edge', features, selectState, false);
this.setItemState('edge', features, activateState, false);
});
@@ -351,9 +326,7 @@ export class MapView extends PluginBase {
});
this.pointLayer.on('unclick', (e) => {
const activeNodeIds = graph.findIdByState('node', selectState);
- const features = this.pointLayer
- .getSource()
- .data.dataArray.filter((model) => activeNodeIds.includes(model.id));
+ const features = this.pointLayer.getSource().data.dataArray.filter((model) => activeNodeIds.includes(model.id));
this.setItemState('node', features, selectState, false);
this.setItemState('node', features, activateState, false);
});
@@ -378,9 +351,7 @@ export class MapView extends PluginBase {
const points = graph
.getAllNodesData()
.map((node) => {
- const itemGroup = nodesGroup.find(
- (ele) => ele.getAttribute('data-item-id') === node.id,
- );
+ const itemGroup = nodesGroup.find((ele) => ele.getAttribute('data-item-id') === node.id);
const keyShape = itemGroup.querySelector('#keyShape');
const {
fill: keyShapeFill,
@@ -389,10 +360,7 @@ export class MapView extends PluginBase {
width: keyShapeWidth = 32,
height: keyShapeHeight = 32,
} = keyShape.attributes;
- if (
- typeof node.data[lngPropertyName] !== 'number' ||
- typeof node.data[latPropertyName] !== 'number'
- )
+ if (typeof node.data[lngPropertyName] !== 'number' || typeof node.data[latPropertyName] !== 'number')
return false;
const point = {
id: node.id,
@@ -401,10 +369,7 @@ export class MapView extends PluginBase {
shape: keyShape.nodeName,
keyShapeFill,
keyShapeOpacity,
- keyShapeSize:
- keyShape.nodeName === 'circle'
- ? keyShapeR
- : [keyShapeWidth, keyShapeHeight],
+ keyShapeSize: keyShape.nodeName === 'circle' ? keyShapeR : [keyShapeWidth, keyShapeHeight],
};
pointMap.set(node.id, point);
@@ -431,9 +396,7 @@ export class MapView extends PluginBase {
if (!sourcePoint || !targetPoint) return false;
const { lng: sourceLng, lat: sourceLat } = pointMap.get(edge.source);
const { lng: targetLng, lat: targetLat } = pointMap.get(edge.target);
- const itemGroup = edgesGroup.find(
- (ele) => ele.getAttribute('data-item-id') === edge.id,
- );
+ const itemGroup = edgesGroup.find((ele) => ele.getAttribute('data-item-id') === edge.id);
const keyShape = itemGroup.querySelector('#keyShape');
const {
lineWidth: keyShapeSize = 1,
@@ -460,17 +423,13 @@ export class MapView extends PluginBase {
private updateMapState(e) {
const { ids, value, states } = e;
if (this.pointLayer) {
- const nodes = this.pointLayer
- .getSource()
- .data.dataArray.filter((nodeMapModel) => ids.includes(nodeMapModel.id));
+ const nodes = this.pointLayer.getSource().data.dataArray.filter((nodeMapModel) => ids.includes(nodeMapModel.id));
if (nodes.length) {
this.setMapItemState('node', nodes, states, value);
}
}
if (this.lineLayer) {
- const edges = this.lineLayer
- .getSource()
- .data.dataArray.filter((edgeMapModel) => ids.includes(edgeMapModel.id));
+ const edges = this.lineLayer.getSource().data.dataArray.filter((edgeMapModel) => ids.includes(edgeMapModel.id));
if (edges.length) {
this.setMapItemState('edge', edges, states, value);
}
@@ -481,18 +440,14 @@ export class MapView extends PluginBase {
const { key } = e;
if (this.options.brushKey === key.toLowerCase()) {
this.scene.enableBoxSelect(true);
- const brushDOM = document.getElementsByClassName(
- 'l7-select-box',
- )[0] as HTMLElement;
+ const brushDOM = document.getElementsByClassName('l7-select-box')[0] as HTMLElement;
modifyCSS(brushDOM, this.options.brushCSS || {});
}
}
private onKeyUp(e) {
const { key } = e;
if (this.options.brushKey === key.toLowerCase()) {
- const brushDom = document.getElementsByClassName(
- 'l7-select-box',
- )[0] as HTMLElement;
+ const brushDom = document.getElementsByClassName('l7-select-box')[0] as HTMLElement;
if (brushDom) brushDom.style.display = 'none';
this.scene.disableBoxSelect();
}
@@ -509,30 +464,18 @@ export class MapView extends PluginBase {
if (!bbox) return;
const { x: x1, y: y1 } = startEvent;
const { x: x2, y: y2 } = endEvent;
- this.pointLayer.boxSelect(
- [Math.min(x1, x2), Math.min(y1, y2), Math.max(x1, x2), Math.max(y1, y2)],
- (features) => {
- this.setItemState('node', features, state, true);
- },
- );
- this.lineLayer.boxSelect(
- [Math.min(x1, x2), Math.min(y1, y2), Math.max(x1, x2), Math.max(y1, y2)],
- (features) => {
- this.setItemState('edge', features, state, true);
- },
- );
+ this.pointLayer.boxSelect([Math.min(x1, x2), Math.min(y1, y2), Math.max(x1, x2), Math.max(y1, y2)], (features) => {
+ this.setItemState('node', features, state, true);
+ });
+ this.lineLayer.boxSelect([Math.min(x1, x2), Math.min(y1, y2), Math.max(x1, x2), Math.max(y1, y2)], (features) => {
+ this.setItemState('edge', features, state, true);
+ });
}
private setMapItemState(itemType, mapNodeModels, state, value) {
const encodedData = this.pointLayer.getEncodedData();
- const transientActiveLayer =
- itemType === 'edge'
- ? this.transientLineActiveLayer
- : this.transientPointActiveLayer;
- const transientSelectLayer =
- itemType === 'edge'
- ? this.transientLineSelectLayer
- : this.transientPointSelectLayer;
+ const transientActiveLayer = itemType === 'edge' ? this.transientLineActiveLayer : this.transientPointActiveLayer;
+ const transientSelectLayer = itemType === 'edge' ? this.transientLineSelectLayer : this.transientPointSelectLayer;
mapNodeModels.forEach((model) => {
if (state === this.options.activateState) {
if (!value) {
@@ -542,9 +485,7 @@ export class MapView extends PluginBase {
transientActiveLayer.setData(
mapNodeModels.map((model) => {
const encoded = encodedData.find((data) => data.id === model._id);
- const sizeNumber = isArray(encoded.size)
- ? encoded.size[0]
- : encoded.size;
+ const sizeNumber = isArray(encoded.size) ? encoded.size[0] : encoded.size;
return {
...model,
actualSize: sizeNumber + 4,
diff --git a/packages/g6-plugin-map-view/tsconfig.json b/packages/g6-plugin-map-view/tsconfig.json
index 7b624ad91d3..04c1ced7f0f 100644
--- a/packages/g6-plugin-map-view/tsconfig.json
+++ b/packages/g6-plugin-map-view/tsconfig.json
@@ -1,23 +1,16 @@
{
"compilerOptions": {
- "outDir": "lib",
- "module": "commonjs",
- "target": "es6",
- "jsx": "preserve",
- "moduleResolution": "node",
- "experimentalDecorators": true,
+ "baseUrl": "src",
"declaration": true,
- "sourceMap": true,
- "allowSyntheticDefaultImports": true,
- "esModuleInterop": true,
- "isolatedModules": true,
- "pretty": true,
+ "experimentalDecorators": true,
+ "jsx": "preserve",
"lib": ["dom", "esnext"],
- "skipLibCheck": true,
- "sourceRoot": "src",
- "baseUrl": "src",
- "resolveJsonModule": true
+ "outDir": "lib",
+ "pretty": true,
+ "resolveJsonModule": true,
+ "sourceMap": true,
+ "sourceRoot": "src"
},
- "include": ["src/**/*"],
- "exclude": ["node_modules"]
+ "exclude": ["node_modules"],
+ "extends": "../../tsconfig.json"
}
diff --git a/packages/g6/.eslintignore b/packages/g6/.eslintignore
deleted file mode 100644
index 96b252f79ec..00000000000
--- a/packages/g6/.eslintignore
+++ /dev/null
@@ -1,6 +0,0 @@
-dist
-es
-lib
-node_modules
-*.ejs
-*.min.js
\ No newline at end of file
diff --git a/packages/g6/.eslintrc b/packages/g6/.eslintrc
deleted file mode 100644
index afb17cd8be5..00000000000
--- a/packages/g6/.eslintrc
+++ /dev/null
@@ -1,41 +0,0 @@
-{
- "root": true,
- "parser": "@typescript-eslint/parser",
- "plugins": ["@typescript-eslint"],
- "extends": [
- "eslint:recommended",
- "plugin:@typescript-eslint/recommended",
- "plugin:import/errors",
- "plugin:import/warnings",
- "plugin:import/typescript",
- "prettier"
- ],
- "rules": {
- "no-constant-condition": [
- "error",
- {
- "checkLoops": false
- }
- ],
- "@typescript-eslint/no-empty-interface": "warn",
- "@typescript-eslint/no-var-requires": "off",
- "@typescript-eslint/ban-ts-comment": "off",
- "@typescript-eslint/ban-types": "warn",
- "@typescript-eslint/explicit-module-boundary-types": "off",
- "@typescript-eslint/no-explicit-any": "off",
- "@typescript-eslint/no-empty-function": "off",
- "@typescript-eslint/no-unused-vars": "off",
- "no-fallthrough": "off",
- "import/no-unresolved": "off",
- "no-multiple-empty-lines": 1,
- "no-prototype-builtins": "warn",
- "import/order": "warn",
- "import/namespace": "warn",
- // Allow `const self = this`.
- "@typescript-eslint/no-this-alias": "off"
- },
- "env": {
- "node": true,
- "jest": true
- }
-}
diff --git a/packages/g6/.gitignore b/packages/g6/.gitignore
new file mode 100644
index 00000000000..f00def86ab0
--- /dev/null
+++ b/packages/g6/.gitignore
@@ -0,0 +1,2 @@
+tests/integration/snapshots/**/*-actual.*
+tests/integration/snapshots/**/*-diff.*
\ No newline at end of file
diff --git a/packages/g6/.prettierrc b/packages/g6/.prettierrc
deleted file mode 100644
index 94beb148408..00000000000
--- a/packages/g6/.prettierrc
+++ /dev/null
@@ -1,11 +0,0 @@
-{
- "singleQuote": true,
- "trailingComma": "all",
- "printWidth": 80,
- "overrides": [
- {
- "files": ".prettierrc",
- "options": { "parser": "json" }
- }
- ]
-}
diff --git a/packages/g6/package.json b/packages/g6/package.json
index 9342ed00104..11a2d6cc25d 100644
--- a/packages/g6/package.json
+++ b/packages/g6/package.json
@@ -2,6 +2,22 @@
"name": "@antv/g6",
"version": "5.0.0-beta.28",
"description": "A Graph Visualization Framework in JavaScript",
+ "keywords": [
+ "antv",
+ "g6",
+ "graph",
+ "graph analysis",
+ "graph editor",
+ "graph visualization",
+ "relational data"
+ ],
+ "homepage": "https://g6.antv.antgroup.com/",
+ "bugs": {
+ "url": "https://github.com/antvis/g6/issues"
+ },
+ "repository": "git@github.com/antvis/g6.git",
+ "license": "MIT",
+ "author": "https://github.com/orgs/antvis/people",
"main": "lib/index.js",
"module": "esm/index.js",
"types": "lib/index.d.ts",
@@ -12,36 +28,26 @@
"dist"
],
"scripts": {
- "dev": "vite",
- "start": "rimraf ./lib && tsc --module commonjs --outDir lib --watch",
- "build:umd": "rimraf ./dist && rollup -c && npm run size",
+ "build": "run-p build:*",
"build:cjs": "rimraf ./lib && tsc --module commonjs --outDir lib",
"build:esm": "rimraf ./esm && tsc --module ESNext --outDir esm",
"build:esm:watch": "rimraf ./esm && tsc --module ESNext --outDir esm --watch",
- "build": "run-p build:*",
+ "build:umd": "rimraf ./dist && rollup -c && npm run size",
"bundle-vis": "cross-env BUNDLE_VIS=1 npm run build:umd",
- "size": "limit-size",
- "prepublishOnly": "npm run ci",
- "doc": "rimraf ../site/docs/_apis && typedoc",
- "lint": "eslint ./src ./tests --quiet && prettier ./src ./tests --check",
+ "ci": "run-s lint build test:integration",
+ "coverage": "jest --coverage",
+ "dev": "vite",
"fix": "eslint ./src ./tests --fix && prettier ./src ./tests --write ",
+ "lint": "eslint ./src ./tests --quiet && prettier ./src ./tests --check",
+ "prepublishOnly": "npm run ci",
+ "size": "limit-size",
+ "start": "rimraf ./lib && tsc --module commonjs --outDir lib --watch",
"test": "jest",
- "test:integration": "node --expose-gc --max-old-space-size=4096 --unhandled-rejections=strict node_modules/jest/bin/jest tests/integration/ --config jest.node.config.js --coverage --logHeapUsage --detectOpenHandles",
- "test:integration_one": "node --expose-gc --max-old-space-size=4096 --unhandled-rejections=strict node_modules/jest/bin/jest tests/integration/behavior --config jest.node.config.js --logHeapUsage --detectOpenHandles",
- "test-live": "DEBUG_MODE=1 jest --watch ./tests/unit/item-animate-spec.ts",
"test-behavior": "DEBUG_MODE=1 jest --watch ./tests/unit/item-3d-spec.ts",
- "ci": "run-s lint build test:integration",
- "coverage": "jest --coverage"
+ "test-live": "DEBUG_MODE=1 jest --watch ./tests/unit/item-animate-spec.ts",
+ "test:integration": "node --expose-gc --max-old-space-size=4096 --unhandled-rejections=strict --experimental-vm-modules ../../node_modules/jest/bin/jest tests/integration/ --config jest.node.config.js --coverage --logHeapUsage --detectOpenHandles",
+ "test:integration_one": "node --expose-gc --trace-warnings --max-old-space-size=4096 --unhandled-rejections=strict --experimental-vm-modules ../../node_modules/jest/bin/jest tests/integration/toolbar --config jest.node.config.js --logHeapUsage --detectOpenHandles"
},
- "keywords": [
- "antv",
- "g6",
- "graph",
- "graph analysis",
- "graph editor",
- "graph visualization",
- "relational data"
- ],
"dependencies": {
"@ant-design/colors": "^7.0.0",
"@antv/algorithm": "^0.1.26",
@@ -63,40 +69,14 @@
"color": "^4.2.3",
"gl-matrix": "^3.4.3",
"insert-css": "^2.0.0",
- "tslib": "^2.5.0"
+ "tslib": "^2.6.2"
},
"devDependencies": {
"@antv/g6-plugin-map-view": "workspace:*",
- "@rollup/plugin-terser": "^0.4.3",
- "@types/jest": "^29.5.1",
- "@types/jsdom": "^21.1.1",
- "@types/node": "13.11.1",
- "@types/xmlserializer": "^0.6.3",
- "@typescript-eslint/eslint-plugin": "^6.5.0",
- "@typescript-eslint/parser": "^6.5.0",
- "@umijs/fabric": "^2.0.0",
- "babel-loader": "^8.0.6",
- "cross-env": "^7.0.3",
- "eslint": "^8.48.0",
- "eslint-plugin-import": "^2.28.1",
- "jest": "^29.5.1",
- "jest-environment-jsdom": "^29.7.0",
- "jsdom": "^19.0.0",
- "limit-size": "^0.1.4",
- "npm-run-all": "^4.1.5",
- "prettier": "^3.0.3",
- "rimraf": "^3.0.0",
- "rollup": "^2.79.1",
- "rollup-plugin-node-resolve": "^5.2.0",
- "rollup-plugin-polyfill-node": "^0.8.0",
- "rollup-plugin-typescript": "^1.0.1",
- "rollup-plugin-visualizer": "^5.6.0",
+ "@types/jsdom": "^21.1.6",
+ "@types/xmlserializer": "^0.6.6",
"stats.js": "^0.17.0",
- "ts-jest": "^29.1.1",
- "typedoc": "^0.25.0",
- "typedoc-plugin-markdown": "^3.16.0",
- "typescript": "5.1.6",
- "vite": "^4.2.2",
+ "vite": "^5.0.10",
"xmlserializer": "^0.6.1"
},
"limit-size": [
@@ -109,12 +89,5 @@
"path": "dist/g6.min.js",
"limit": "2 Mb"
}
- ],
- "author": "https://github.com/orgs/antvis/people",
- "homepage": "https://g6.antv.antgroup.com/",
- "bugs": {
- "url": "https://github.com/antvis/g6/issues"
- },
- "repository": "git@github.com/antvis/g6.git",
- "license": "MIT"
+ ]
}
diff --git a/packages/g6/rollup.config.js b/packages/g6/rollup.config.mjs
similarity index 59%
rename from packages/g6/rollup.config.js
rename to packages/g6/rollup.config.mjs
index 172df8dab70..b09d88d8538 100644
--- a/packages/g6/rollup.config.js
+++ b/packages/g6/rollup.config.mjs
@@ -1,13 +1,13 @@
-import terser from '@rollup/plugin-terser';
-import resolve from 'rollup-plugin-node-resolve';
-import typescript from 'rollup-plugin-typescript';
import commonjs from '@rollup/plugin-commonjs';
+import resolve from '@rollup/plugin-node-resolve';
+import terser from '@rollup/plugin-terser';
+import typescript from '@rollup/plugin-typescript';
import nodePolyfills from 'rollup-plugin-polyfill-node';
import { visualizer } from 'rollup-plugin-visualizer';
const isBundleVis = !!process.env.BUNDLE_VIS;
-module.exports = [
+export default[
{
input: 'src/index.ts',
output: {
@@ -16,13 +16,6 @@ module.exports = [
format: 'umd',
sourcemap: false,
},
- plugins: [
- nodePolyfills(),
- resolve(),
- commonjs(),
- typescript(),
- terser(),
- ...(isBundleVis ? [visualizer()] : []),
- ],
+ plugins: [nodePolyfills(), resolve(), commonjs(), typescript(), terser(), ...(isBundleVis ? [visualizer()] : [])],
},
];
diff --git a/packages/g6/sidebars.js b/packages/g6/sidebars.js
deleted file mode 100644
index f385bdc26cd..00000000000
--- a/packages/g6/sidebars.js
+++ /dev/null
@@ -1,11 +0,0 @@
-module.exports = {
- "docs": {
- "Modules": [
- "api-ts/modules/_graph_"
- ],
- "Classes": [
- "api-ts/classes/_graph_.graph",
- "api-ts/classes/_graph_.graph"
- ]
- }
-};
\ No newline at end of file
diff --git a/packages/g6/src/api-doc/graph.ts b/packages/g6/src/api-doc/graph.ts
index 6f6c671cb3d..42636c21b22 100644
--- a/packages/g6/src/api-doc/graph.ts
+++ b/packages/g6/src/api-doc/graph.ts
@@ -1,5 +1,5 @@
import * as Util from '../util';
-export { Util };
export { Graph } from '../runtime/graph';
export type { GraphData, IGraph, Specification } from '../types';
+export { Util };
diff --git a/packages/g6/src/api-doc/item.ts b/packages/g6/src/api-doc/item.ts
index e85e913d1ae..3f7b6b1151a 100644
--- a/packages/g6/src/api-doc/item.ts
+++ b/packages/g6/src/api-doc/item.ts
@@ -1,45 +1,40 @@
import {
CircleStyleProps,
- RectStyleProps,
EllipseStyleProps,
- PolygonStyleProps,
+ ImageStyleProps,
LineStyleProps,
PathStyleProps,
+ PolygonStyleProps,
PolylineStyleProps,
+ RectStyleProps,
TextStyleProps,
- ImageStyleProps,
} from '@antv/g';
-import {
- CubeGeometryProps,
- PlaneGeometryProps,
- SphereGeometryProps,
- TorusGeometryProps,
-} from '@antv/g-plugin-3d';
-import { ShapeStyle, BadgePosition, IBadgePosition } from '../types/item';
+import { CubeGeometryProps, PlaneGeometryProps, SphereGeometryProps, TorusGeometryProps } from '@antv/g-plugin-3d';
+import { BadgePosition, IBadgePosition, ShapeStyle } from '../types/item';
import { IAnchorPositionMap } from '../types/node';
+export { BaseEdge as CustomEdge } from '../stdlib/item/edge/base';
+export * from '../stdlib/item/node';
+export { BaseNode as CustomNode } from '../stdlib/item/node/base';
+export { BaseNode3D as CustomNode3D } from '../stdlib/item/node/base3d';
+export type { GShapeStyle } from '../types/item';
+export type { NodeShapeStyles, NodeUserModelData } from '../types/node';
export type {
+ BadgePosition,
CircleStyleProps,
- RectStyleProps,
+ CubeGeometryProps,
EllipseStyleProps,
- PolygonStyleProps,
+ IAnchorPositionMap,
+ IBadgePosition,
+ ImageStyleProps,
LineStyleProps,
PathStyleProps,
- PolylineStyleProps,
- TextStyleProps,
- ImageStyleProps,
- CubeGeometryProps,
PlaneGeometryProps,
+ PolygonStyleProps,
+ PolylineStyleProps,
+ RectStyleProps,
+ ShapeStyle,
SphereGeometryProps,
+ TextStyleProps,
TorusGeometryProps,
- BadgePosition,
- IBadgePosition,
- ShapeStyle,
- IAnchorPositionMap,
};
-export type { NodeUserModelData, NodeShapeStyles } from '../types/node';
-export type { GShapeStyle } from '../types/item';
-export { BaseNode as CustomNode } from '../stdlib/item/node/base';
-export { BaseNode3D as CustomNode3D } from '../stdlib/item/node/base3d';
-export { BaseEdge as CustomEdge } from '../stdlib/item/edge/base';
-export * from '../stdlib/item/node';
diff --git a/packages/g6/src/item/combo.ts b/packages/g6/src/item/combo.ts
index b1007d02a2d..ce02ba594c1 100644
--- a/packages/g6/src/item/combo.ts
+++ b/packages/g6/src/item/combo.ts
@@ -1,15 +1,11 @@
import { Group, Tuple3Number } from '@antv/g';
import { clone, throttle } from '@antv/util';
import { ComboDisplayModel, ComboModel, IGraph } from '../types';
-import { DisplayMapper, LodLevelRanges, State } from '../types/item';
-import { ComboStyleSet } from '../types/theme';
import { ComboModelData, ComboUserModelData } from '../types/combo';
import { Point } from '../types/common';
-import {
- getCircleIntersectByPoint,
- getNearestPoint,
- getRectIntersectByPoint,
-} from '../util/point';
+import { DisplayMapper, LodLevelRanges, State } from '../types/item';
+import { ComboStyleSet } from '../types/theme';
+import { getCircleIntersectByPoint, getNearestPoint, getRectIntersectByPoint } from '../util/point';
import Node from './node';
interface IProps {
@@ -41,7 +37,7 @@ interface IProps {
getChildren?: () => (Node | Combo)[];
}
export default class Combo extends Node {
- public type: 'combo';
+ public declare type: 'combo';
private anchorPointsCache: Point[] | undefined;
private cacheCombinedBounds?:
@@ -89,9 +85,7 @@ export default class Combo extends Node {
...this.themeStyles.collapsed[shapeId],
};
if (this.themeStyles.collapsed[shapeId].contentType === 'childCount') {
- (displayModel.data[shapeId] as any).text = `${
- this.getChildren().length || 0
- }`;
+ (displayModel.data[shapeId] as any).text = `${this.getChildren().length || 0}`;
}
});
}
@@ -120,7 +114,10 @@ export default class Combo extends Node {
* Maps (mapper will be function, value, or encode format) model to displayModel and find out the shapes to be update for incremental updating.
* @param model inner model
* @param diffData changes from graphCore changed event
+ * @param innerModel
+ * @param diffData.previous
* @param isReplace whether replace the whole data or partial update
+ * @param diffData.current
* @returns
*/
public getDisplayModelAndChanges(
@@ -131,11 +128,7 @@ export default class Combo extends Node {
model: ComboDisplayModel;
typeChange?: boolean;
} {
- const superResult = super.getDisplayModelAndChanges(
- innerModel,
- diffData,
- isReplace,
- );
+ const superResult = super.getDisplayModelAndChanges(innerModel, diffData, isReplace);
const model = superResult.model as ComboDisplayModel;
return {
model: this.updateModelByBounds(model),
@@ -166,8 +159,7 @@ export default class Combo extends Node {
public getPosition(): Point {
const { x = 0, y = 0, z = 0 } = this.model.data;
- this.cacheCombinedBounds =
- this.cacheCombinedBounds || this.getCombinedBounds();
+ this.cacheCombinedBounds = this.cacheCombinedBounds || this.getCombinedBounds();
const { center } = this.cacheCombinedBounds || {};
return center
? {
@@ -182,11 +174,7 @@ export default class Combo extends Node {
};
}
- public getIntersectPoint(
- point: Point,
- innerPoint: Point,
- anchorPoints: number[][],
- ) {
+ public getIntersectPoint(point: Point, innerPoint: Point, anchorPoints: number[][]) {
const { keyShape } = this.shapeMap;
const shapeType = keyShape.nodeName;
const { collapsed, keyShape: keyShapeStyle } = this.displayModel.data;
@@ -198,9 +186,7 @@ export default class Combo extends Node {
{
x,
y,
- r:
- (collapsed ? keyShapeStyle?.r : keyShape.attributes.r) ||
- keyShape.attributes.r,
+ r: (collapsed ? keyShapeStyle?.r : keyShape.attributes.r) || keyShape.attributes.r,
},
point,
);
@@ -249,10 +235,7 @@ export default class Combo extends Node {
// If the linkPoint is failed to calculate.
linkPoint = point;
}
- linkPoint = getNearestPoint(
- anchorPointsPositions,
- linkPoint,
- ).nearestPoint;
+ linkPoint = getNearestPoint(anchorPointsPositions, linkPoint).nearestPoint;
}
if (!linkPoint) {
// If the calculations above are all failed, return the data's position
@@ -283,8 +266,7 @@ export default class Combo extends Node {
if (!this.shapeMap[shapeId] || this.shapeMap[shapeId].destroyed) return;
const clonedKeyShape = this.shapeMap[shapeId].cloneNode();
// TODO: other animating attributes?
- clonedKeyShape.style.opacity =
- this.renderExt.mergedStyles[shapeId]?.opacity || 1;
+ clonedKeyShape.style.opacity = this.renderExt.mergedStyles[shapeId]?.opacity || 1;
group.appendChild(clonedKeyShape);
});
group.setPosition(this.group.getPosition());
diff --git a/packages/g6/src/item/edge.ts b/packages/g6/src/item/edge.ts
index 33f16deeef2..084c223c669 100644
--- a/packages/g6/src/item/edge.ts
+++ b/packages/g6/src/item/edge.ts
@@ -2,15 +2,15 @@ import { Group } from '@antv/g';
import { clone, throttle } from '@antv/util';
import { EdgeDisplayModel, EdgeModel, ID, IGraph, Point } from '../types';
import { EdgeModelData } from '../types/edge';
-import { DisplayMapper, State, LodLevelRanges } from '../types/item';
-import { updateShapes } from '../util/shape';
-import { animateShapes } from '../util/animate';
+import { DisplayMapper, LodLevelRanges, State } from '../types/item';
import { EdgeStyleSet } from '../types/theme';
-import { isSamePoint, getNearestPoint } from '../util/point';
+import { animateShapes } from '../util/animate';
+import { getNearestPoint, isSamePoint } from '../util/point';
import { isPolylineWithObstacleAvoidance } from '../util/polyline';
+import { updateShapes } from '../util/shape';
+import Combo from './combo';
import Item from './item';
import Node from './node';
-import Combo from './combo';
interface IProps {
graph: IGraph;
@@ -37,9 +37,9 @@ interface IProps {
export default class Edge extends Item {
public destroyed = false;
// inner data model
- public model: EdgeModel;
+ public declare model: EdgeModel;
// display data model
- public displayModel: EdgeDisplayModel;
+ public declare displayModel: EdgeDisplayModel;
/** Set to different value in implements */
public type = 'edge' as const;
public nodeMap: Map;
@@ -80,20 +80,12 @@ export default class Edge extends Item {
this.renderExt.setTargetPoint(targetPoint);
this.renderExt.setNodeMap(this.nodeMap);
- const shapeMap = this.renderExt.draw(
- displayModel,
- sourcePoint,
- targetPoint,
- this.shapeMap,
- diffData,
- diffState,
- );
+ const shapeMap = this.renderExt.draw(displayModel, sourcePoint, targetPoint, this.shapeMap, diffData, diffState);
if (this.shapeMap.labelShape) {
this.shapeMap.labelShape.attributes.dataIsLabel = true;
}
if (this.shapeMap.labelBackgroundShape) {
- this.shapeMap.labelBackgroundShape.attributes.dataIsLabelBackground =
- true;
+ this.shapeMap.labelBackgroundShape.attributes.dataIsLabelBackground = true;
}
// add shapes to group, and update shapeMap
@@ -134,8 +126,7 @@ export default class Edge extends Item {
undefined,
[this.group, this.labelGroup],
firstRendering ? 'buildIn' : 'update',
- current.concat(previous).map((state) => state.name) ||
- this.changedStates,
+ current.concat(previous).map((state) => state.name) || this.changedStates,
this.animateFrameListener,
(canceled) => onfinish(displayModel.id, canceled),
);
@@ -162,18 +153,11 @@ export default class Edge extends Item {
public forceUpdate() {
if (this.destroyed || !this.shapeMap.keyShape) return;
const force = isPolylineWithObstacleAvoidance(this.displayModel);
- const { sourcePoint, targetPoint, changed } = this.getEndPoints(
- this.displayModel,
- );
+ const { sourcePoint, targetPoint, changed } = this.getEndPoints(this.displayModel);
if (!force && !changed) return;
this.renderExt.setSourcePoint(sourcePoint);
this.renderExt.setTargetPoint(targetPoint);
- const shapeMap = this.renderExt.draw(
- this.displayModel,
- sourcePoint,
- targetPoint,
- this.shapeMap,
- );
+ const shapeMap = this.renderExt.draw(this.displayModel, sourcePoint, targetPoint, this.shapeMap);
if (shapeMap.labelShape) {
shapeMap.labelShape.attributes.dataIsLabel = true;
}
@@ -181,12 +165,7 @@ export default class Edge extends Item {
shapeMap.labelBackgroundShape.attributes.dataIsLabelBackground = true;
}
// add shapes to group, and update shapeMap
- this.shapeMap = updateShapes(
- this.shapeMap,
- shapeMap,
- this.group,
- this.labelGroup,
- );
+ this.shapeMap = updateShapes(this.shapeMap, shapeMap, this.group, this.labelGroup);
this.labelGroup.children
.filter((element) => element.attributes.dataIsLabel)
.forEach((shape) => (shape.attributes.dataOriginPosition = ''));
@@ -238,27 +217,13 @@ export default class Edge extends Item {
if (keyShape?.controlPoints?.length) {
// @ts-ignore
const controlPointsBesideEnds = keyShape.controlPoints.filter(
- (point) =>
- !isSamePoint(point, sourcePosition) &&
- !isSamePoint(point, targetPosition),
+ (point) => !isSamePoint(point, sourcePosition) && !isSamePoint(point, targetPosition),
);
- sourcePrevious = getNearestPoint(
- controlPointsBesideEnds,
- sourcePosition,
- ).nearestPoint;
- targetPrevious = getNearestPoint(
- controlPointsBesideEnds,
- targetPosition,
- ).nearestPoint;
+ sourcePrevious = getNearestPoint(controlPointsBesideEnds, sourcePosition).nearestPoint;
+ targetPrevious = getNearestPoint(controlPointsBesideEnds, targetPosition).nearestPoint;
}
- this.cache.sourcePointCache = this.sourceItem.getAnchorPoint(
- sourcePrevious,
- sourceAnchor,
- );
- this.cache.targetPointCache = this.targetItem.getAnchorPoint(
- targetPrevious,
- targetAnchor,
- );
+ this.cache.sourcePointCache = this.sourceItem.getAnchorPoint(sourcePrevious, sourceAnchor);
+ this.cache.targetPointCache = this.targetItem.getAnchorPoint(targetPrevious, targetAnchor);
return {
sourcePoint: this.cache.sourcePointCache,
targetPoint: this.cache.targetPointCache,
@@ -274,8 +239,7 @@ export default class Edge extends Item {
* @returns
*/
private shouldUpdatePoints(sourcePosition, targetPosition, controlPoints) {
- const isComboEnd =
- this.sourceItem.type === 'combo' || this.targetItem.type === 'combo';
+ const isComboEnd = this.sourceItem.type === 'combo' || this.targetItem.type === 'combo';
const changed =
!(
isSamePoint(sourcePosition, this.cache.sourcePositionCache) &&
@@ -292,6 +256,7 @@ export default class Edge extends Item {
/**
* Update label positions on label canvas by getting viewport position from transformed canvas position.
+ * @param ignoreVisibility
*/
public updateLabelPosition(ignoreVisibility?: boolean) {
const { graph, labelGroup } = this;
@@ -301,21 +266,16 @@ export default class Edge extends Item {
const zoom = graph.getZoom();
labelGroup.children.forEach((shape) => {
if (shape.attributes.dataIsLabelBackground) {
- this.renderExt.drawLabelBackgroundShape(
- this.displayModel,
- this.shapeMap,
- );
+ this.renderExt.drawLabelBackgroundShape(this.displayModel, this.shapeMap);
return;
}
if (shape.attributes.dataIsLabel) {
const { maxWidth } = this.renderExt.mergedStyles[shape.id] || {};
if (maxWidth) {
if (!shape.attributes.dataOriginWordWrapWidth) {
- shape.attributes.dataOriginWordWrapWidth =
- shape.style.wordWrapWidth;
+ shape.attributes.dataOriginWordWrapWidth = shape.style.wordWrapWidth;
}
- shape.style.wordWrapWidth =
- shape.attributes.dataOriginWordWrapWidth * zoom;
+ shape.style.wordWrapWidth = shape.attributes.dataOriginWordWrapWidth * zoom;
}
}
if (!shape.attributes.dataOriginPosition) {
@@ -325,9 +285,7 @@ export default class Edge extends Item {
z: shape.style.z,
};
}
- const viewportPosition = graph.getViewportByCanvas(
- shape.attributes.dataOriginPosition,
- );
+ const viewportPosition = graph.getViewportByCanvas(shape.attributes.dataOriginPosition);
shape.style.x = viewportPosition.x;
shape.style.y = viewportPosition.y;
shape.style.z = viewportPosition.z;
@@ -341,8 +299,7 @@ export default class Edge extends Item {
if (!shape.attributes.dataOriginWordWrapWidth) {
shape.attributes.dataOriginWordWrapWidth = shape.style.wordWrapWidth;
}
- shape.style.wordWrapWidth =
- shape.attributes.dataOriginWordWrapWidth * zoom;
+ shape.style.wordWrapWidth = shape.attributes.dataOriginWordWrapWidth * zoom;
}
},
50,
@@ -368,8 +325,7 @@ export default class Edge extends Item {
if (!this.shapeMap[shapeId] || this.shapeMap[shapeId].destroyed) return;
const clonedKeyShape = this.shapeMap[shapeId].cloneNode();
// TODO: other animating attributes?
- clonedKeyShape.style.opacity =
- this.renderExt.mergedStyles[shapeId]?.opacity || 1;
+ clonedKeyShape.style.opacity = this.renderExt.mergedStyles[shapeId]?.opacity || 1;
group.appendChild(clonedKeyShape);
});
containerGroup.appendChild(group);
@@ -382,12 +338,7 @@ export default class Edge extends Item {
if (transientItemMap) {
this.nodeMap.forEach((node, id) => {
const transientItem = transientItemMap.get(id) as Node;
- if (
- !transientItem ||
- !transientItem.isVisible() ||
- transientItem.type !== 'node'
- )
- return;
+ if (!transientItem || !transientItem.isVisible() || transientItem.type !== 'node') return;
this.nodeMap.set(id, transientItem);
});
}
diff --git a/packages/g6/src/item/item.ts b/packages/g6/src/item/item.ts
index e64d7923008..8504c580dff 100644
--- a/packages/g6/src/item/item.ts
+++ b/packages/g6/src/item/item.ts
@@ -1,39 +1,29 @@
-import { Group, DisplayObject, AABB, IAnimation } from '@antv/g';
+import { AABB, DisplayObject, Group, IAnimation } from '@antv/g';
import { isFunction, isObject, throttle } from '@antv/util';
import { OTHER_SHAPES_FIELD_NAME, RESERVED_SHAPE_IDS } from '../constant';
+import { IGraph } from '../types';
+import { AnimateTiming, IAnimates, IStateAnimate } from '../types/animate';
import { EdgeShapeMap } from '../types/edge';
import {
DisplayMapper,
IItem,
+ ITEM_TYPE,
ItemDisplayModel,
ItemModel,
ItemModelData,
ItemShapeStyles,
- ITEM_TYPE,
- State,
LodLevelRanges,
+ State,
} from '../types/item';
import { NodeShapeMap } from '../types/node';
import { EdgeStyleSet, NodeStyleSet } from '../types/theme';
+import { GROUP_ANIMATE_STYLES, animateShapes, getShapeAnimateBeginStyles, stopAnimate } from '../util/animate';
import { isArrayOverlap } from '../util/array';
-import {
- combineBounds,
- getShapeLocalBoundsByStyle,
- mergeStyles,
- updateShapes,
-} from '../util/shape';
-import { isEncode } from '../util/type';
-import { DEFAULT_MAPPER } from '../util/mapper';
import { cloneJSON } from '../util/data';
-import {
- getShapeAnimateBeginStyles,
- animateShapes,
- GROUP_ANIMATE_STYLES,
- stopAnimate,
-} from '../util/animate';
-import { AnimateTiming, IAnimates, IStateAnimate } from '../types/animate';
+import { DEFAULT_MAPPER } from '../util/mapper';
+import { combineBounds, getShapeLocalBoundsByStyle, mergeStyles, updateShapes } from '../util/shape';
+import { isEncode } from '../util/type';
import { formatLodLevels } from '../util/zoom';
-import { IGraph } from '../types';
export default abstract class Item implements IItem {
public graph: IGraph;
@@ -106,7 +96,10 @@ export default abstract class Item implements IItem {
this.onframe = props.onframe;
}
- /** Initiate the item. */
+ /**
+ * Initiate the item.
+ * @param props
+ */
public init(props) {
const {
graph,
@@ -143,9 +136,7 @@ export default abstract class Item implements IItem {
} = this.displayModel.data;
const RenderExtension = renderExtensions.find((ext) => ext.type === type);
this.themeStyles = theme.styles;
- this.lodLevels = modelLodLevels
- ? formatLodLevels(modelLodLevels)
- : theme.lodLevels;
+ this.lodLevels = modelLodLevels ? formatLodLevels(modelLodLevels) : theme.lodLevels;
if (!RenderExtension) {
if (this.type === 'node') {
throw new Error(
@@ -156,9 +147,7 @@ export default abstract class Item implements IItem {
`TypeError: RenderExtension is not a constructor. The '${type}' in your data haven't been registered. You can use built-in edge types like 'line-edge', 'quadratic-edge','cubic-edge' or create a custom edge type as you like.`,
);
} else {
- throw new Error(
- `TypeError: RenderExtension is not a constructor. The '${type}' haven't been registered.`,
- );
+ throw new Error(`TypeError: RenderExtension is not a constructor. The '${type}' haven't been registered.`);
}
}
this.renderExt = new RenderExtension({
@@ -173,8 +162,17 @@ export default abstract class Item implements IItem {
/**
* Draws the shapes.
+ * @param displayModel
+ * @param diffData
+ * @param diffData.previous
+ * @param diffData.current
+ * @param diffState
+ * @param diffState.previous
+ * @param diffState.current
+ * @param animate
+ * @param onfinish
* @internal
- * */
+ */
public draw(
displayModel: ItemDisplayModel,
diffData?: { previous: ItemModelData; current: ItemModelData },
@@ -197,8 +195,7 @@ export default abstract class Item implements IItem {
this.afterDrawShapeMap.labelShape.attributes.dataIsLabel = true;
}
if (this.afterDrawShapeMap.labelBackgroundShape) {
- this.afterDrawShapeMap.labelBackgroundShape.attributes.dataIsLabelBackground =
- true;
+ this.afterDrawShapeMap.labelBackgroundShape.attributes.dataIsLabelBackground = true;
}
const shapeMap = updateShapes(
this.afterDrawShapeMap,
@@ -225,8 +222,19 @@ export default abstract class Item implements IItem {
/**
* Updates the shapes.
+ * @param model
+ * @param diffData
+ * @param diffData.previous
+ * @param diffData.current
+ * @param isReplace
+ * @param itemTheme
+ * @param itemTheme.styles
+ * @param itemTheme.lodLevels
+ * @param onlyMove
+ * @param animate
+ * @param onfinish
* @internal
- * */
+ */
public update(
model: ItemModel,
diffData?: { previous: ItemModelData; current: ItemModelData },
@@ -245,11 +253,7 @@ export default abstract class Item implements IItem {
this.themeStyles = itemTheme.styles;
}
// 2. map new merged model to displayModel, keep prevModel and newModel for 3.
- const { model: displayModel, typeChange } = this.getDisplayModelAndChanges(
- this.model,
- diffData,
- isReplace,
- );
+ const { model: displayModel, typeChange } = this.getDisplayModelAndChanges(this.model, diffData, isReplace);
this.displayModel = displayModel;
this.lodLevels = displayModel.data.lodLevels
@@ -264,11 +268,8 @@ export default abstract class Item implements IItem {
if (typeChange) {
Object.values(this.shapeMap).forEach((child) => child.destroy());
this.shapeMap = { keyShape: undefined };
- const { type = this.type === 'node' ? 'circle-node' : 'line-edge' } =
- displayModel.data;
- const RenderExtension = this.renderExtensions.find(
- (ext) => ext.type === type,
- );
+ const { type = this.type === 'node' ? 'circle-node' : 'line-edge' } = displayModel.data;
+ const RenderExtension = this.renderExtensions.find((ext) => ext.type === type);
this.renderExt = new RenderExtension({
themeStyles: this.themeStyles.default,
lodLevels: this.lodLevels,
@@ -295,8 +296,10 @@ export default abstract class Item implements IItem {
* Update the group's position, e.g. node, combo.
* @param displayModel
* @param diffData
+ * @param diffData.previous
+ * @param diffData.current
* @param onfinish
- * @returns
+ * @param animate
*/
public updatePosition(
displayModel: ItemDisplayModel,
@@ -309,7 +312,10 @@ export default abstract class Item implements IItem {
* Maps (mapper will be function, value, or encode format) model to displayModel and find out the shapes to be update for incremental updating.
* @param model inner model
* @param diffData changes from graphCore changed event
+ * @param innerModel
+ * @param diffData.previous
* @param isReplace whether replace the whole data or partial update
+ * @param diffData.current
* @returns
*/
public getDisplayModelAndChanges(
@@ -352,9 +358,7 @@ export default abstract class Item implements IItem {
}
// === fields' values in mapper are final value or Encode ===
- const dataChangedFields = isReplace
- ? undefined
- : Object.keys(current || {}).concat(Object.keys(otherFields)); // only fields in current data for partial updating
+ const dataChangedFields = isReplace ? undefined : Object.keys(current || {}).concat(Object.keys(otherFields)); // only fields in current data for partial updating
let typeChange = false;
const { data, ...otherProps } = innerModel;
@@ -363,12 +367,11 @@ export default abstract class Item implements IItem {
Object.keys(mapper).forEach((fieldName) => {
let subMapper = mapper[fieldName];
const isReservedShapeId = RESERVED_SHAPE_IDS.includes(fieldName);
- const isShapeId =
- isReservedShapeId || fieldName === OTHER_SHAPES_FIELD_NAME;
+ const isShapeId = isReservedShapeId || fieldName === OTHER_SHAPES_FIELD_NAME;
if ((isShapeId && isEncode(subMapper)) || !isShapeId) {
// fields not about shape
- if (!displayModelData.hasOwnProperty(fieldName)) {
+ if (!(fieldName in displayModelData)) {
const { changed, value: mappedValue } = updateChange({
innerModel,
mapper,
@@ -382,10 +385,7 @@ export default abstract class Item implements IItem {
displayModelData[fieldName] = mappedValue;
}
if (changed && fieldName === 'type') typeChange = true;
- } else if (
- fieldName === 'type' &&
- (!dataChangedFields || dataChangedFields.includes('type'))
- ) {
+ } else if (fieldName === 'type' && (!dataChangedFields || dataChangedFields.includes('type'))) {
typeChange = true;
}
}
@@ -417,9 +417,8 @@ export default abstract class Item implements IItem {
}
: {};
Object.keys(subMapper).forEach((shapeId) => {
- if (!displayModelData[fieldName]?.hasOwnProperty(shapeId)) {
- displayModelData[fieldName][shapeId] =
- displayModelData[fieldName][shapeId] || {};
+ if (!(shapeId in displayModelData[fieldName])) {
+ displayModelData[fieldName][shapeId] = displayModelData[fieldName][shapeId] || {};
const shappStyle = subMapper[shapeId];
updateShapeChange({
innerModel,
@@ -449,7 +448,11 @@ export default abstract class Item implements IItem {
return this.type;
}
- /** Show the item. */
+ /**
+ * Show the item.
+ * @param animate
+ * @param shapeIds
+ */
public show(animate = true, shapeIds = undefined) {
const shapeIdsToStop = shapeIds?.filter((id) => {
const shape = this.shapeMap[id];
@@ -463,17 +466,12 @@ export default abstract class Item implements IItem {
if (this.destroyed) return;
const { animates = {} } = this.displayModel.data;
const shapeIdsToShow =
- shapeIdsToStop ||
- Object.keys(this.shapeMap).filter(
- (shapeId) => this.cacheHiddenByItem[shapeId],
- );
+ shapeIdsToStop || Object.keys(this.shapeMap).filter((shapeId) => this.cacheHiddenByItem[shapeId]);
if (animate && animates.show?.length) {
const showAnimateFieldsMap: any = {};
Object.values(animates.show).forEach((animate) => {
const { shapeId = 'group' } = animate;
- showAnimateFieldsMap[shapeId] = (
- showAnimateFieldsMap[shapeId] || []
- ).concat(animate.fields);
+ showAnimateFieldsMap[shapeId] = (showAnimateFieldsMap[shapeId] || []).concat(animate.fields);
});
const targetStyleMap = {};
shapeIdsToShow.forEach((id) => {
@@ -483,7 +481,7 @@ export default abstract class Item implements IItem {
targetStyleMap[id] = targetStyleMap[id] || {};
const beginStyle = getShapeAnimateBeginStyles(shape);
showAnimateFieldsMap[id].forEach((field) => {
- if (beginStyle.hasOwnProperty(field)) {
+ if (field in beginStyle) {
targetStyleMap[id][field] = shape.style[field];
shape.style[field] = beginStyle[field];
}
@@ -492,25 +490,16 @@ export default abstract class Item implements IItem {
shape.show();
delete this.cacheHiddenByItem[id];
});
- if (
- showAnimateFieldsMap.group &&
- this.shapeMap.keyShape.attributes.visibility === 'hidden'
- ) {
+ if (showAnimateFieldsMap.group && this.shapeMap.keyShape.attributes.visibility === 'hidden') {
showAnimateFieldsMap.group.forEach((field) => {
const usingField = field === 'size' ? 'transform' : field;
- if (GROUP_ANIMATE_STYLES[0].hasOwnProperty(usingField)) {
- this.group.style[usingField] =
- GROUP_ANIMATE_STYLES[0][usingField];
+ if (usingField in GROUP_ANIMATE_STYLES[0]) {
+ this.group.style[usingField] = GROUP_ANIMATE_STYLES[0][usingField];
}
});
}
if (Object.keys(targetStyleMap).length) {
- this.animations = this.runWithAnimates(
- animates,
- 'show',
- targetStyleMap,
- shapeIdsToShow,
- );
+ this.animations = this.runWithAnimates(animates, 'show', targetStyleMap, shapeIdsToShow);
}
} else {
shapeIdsToShow.forEach((id) => {
@@ -529,16 +518,17 @@ export default abstract class Item implements IItem {
});
}
- /** Hides the item. */
+ /**
+ * Hides the item.
+ * @param animate
+ * @param keepKeyShape
+ * @param shapeIds
+ */
public hide(animate = true, keepKeyShape = false, shapeIds = undefined) {
const shapeIdsToHide =
shapeIds?.filter((id) => {
const shape = this.shapeMap[id];
- return (
- shape &&
- (shape.attributes.visibility !== 'hidden' ||
- this.cacheNotHiddenByItem[id])
- );
+ return shape && (shape.attributes.visibility !== 'hidden' || this.cacheNotHiddenByItem[id]);
}) || Object.keys(this.shapeMap);
if (!shapeIdsToHide.length) return;
this.cacheNotHiddenByItem = {};
@@ -559,13 +549,7 @@ export default abstract class Item implements IItem {
if (this.destroyed) return;
const { animates = {} } = this.displayModel.data;
if (animate && animates.hide?.length) {
- this.animations = this.runWithAnimates(
- animates,
- 'hide',
- undefined,
- shapeIdsToHide,
- func,
- );
+ this.animations = this.runWithAnimates(animates, 'hide', undefined, shapeIdsToHide, func);
} else {
// 2. clear group and remove group
func();
@@ -619,7 +603,7 @@ export default abstract class Item implements IItem {
}
// if the renderExt overwrote the setState, run the custom setState instead of the default
- if (this.renderExt.constructor.prototype.hasOwnProperty('setState')) {
+ if ('setState' in this.renderExt.constructor) {
this.renderExt.setState(state, value, this.shapeMap);
return;
}
@@ -653,10 +637,8 @@ export default abstract class Item implements IItem {
this.states = newStates;
this.changedStates = changedStates.map((state) => state.name);
// if the renderExt overwrote the setState, run the custom setState instead of the default
- if (this.renderExt.constructor.prototype.hasOwnProperty('setState')) {
- changedStates.forEach(({ name, value }) =>
- this.renderExt.setState(name, value, this.shapeMap),
- );
+ if ('setState' in this.renderExt.constructor) {
+ changedStates.forEach(({ name, value }) => this.renderExt.setState(name, value, this.shapeMap));
return;
}
this.drawWithStates(previousStates);
@@ -675,6 +657,7 @@ export default abstract class Item implements IItem {
* @param animates
* @param timing
* @param targetStyleMap
+ * @param shapeIdsToShow
* @param callback
* @returns
*/
@@ -688,9 +671,7 @@ export default abstract class Item implements IItem {
let targetStyle = {};
if (!targetStyleMap) {
shapeIdsToShow?.forEach((shapeId) => {
- targetStyle[shapeId] = getShapeAnimateBeginStyles(
- this.shapeMap[shapeId],
- );
+ targetStyle[shapeId] = getShapeAnimateBeginStyles(this.shapeMap[shapeId]);
});
} else {
targetStyle = targetStyleMap;
@@ -711,13 +692,10 @@ export default abstract class Item implements IItem {
/**
* Re-draw the item with merged state styles.
* @param previousStates previous states
- * @returns
+ * @param animate
+ * @param onfinish
*/
- private drawWithStates(
- previousStates: State[],
- animate = true,
- onfinish?: Function,
- ) {
+ private drawWithStates(previousStates: State[], animate = true, onfinish?: Function) {
const { default: _, ...themeStateStyles } = this.themeStyles;
const { data: displayModelData } = this.displayModel;
let styles = {}; // merged styles
@@ -726,12 +704,7 @@ export default abstract class Item implements IItem {
const mapper = this.stateMapper?.[stateName];
if (!mapper && !themeStateStyles?.[stateName]) return;
// re-mapper the state styles for states if they have dirty tags
- if (
- mapper &&
- value &&
- (!this.stateDirtyMap.hasOwnProperty(stateName) ||
- this.stateDirtyMap[stateName])
- ) {
+ if (mapper && value && (!(stateName in this.stateDirtyMap) || this.stateDirtyMap[stateName])) {
this.stateDirtyMap[stateName] = false;
Object.keys(mapper).forEach((shapeId) => {
stateStyles[shapeId] = {
@@ -750,8 +723,7 @@ export default abstract class Item implements IItem {
// other shapes
Object.keys(mapper[shapeId]).forEach((otherShapeId) => {
stateStyles[shapeId] = stateStyles[shapeId] || {};
- stateStyles[shapeId][otherShapeId] =
- stateStyles[shapeId][otherShapeId] || {};
+ stateStyles[shapeId][otherShapeId] = stateStyles[shapeId][otherShapeId] || {};
updateShapeChange({
innerModel: this.model,
mapper: mapper[shapeId][otherShapeId],
@@ -765,10 +737,7 @@ export default abstract class Item implements IItem {
}
this.cacheStateStyles[stateName] = stateStyles;
// merge the theme state styles
- const mergedStateStyles = mergeStyles([
- themeStateStyles[stateName],
- stateStyles,
- ]);
+ const mergedStateStyles = mergeStyles([themeStateStyles[stateName], stateStyles]);
// merge the states' styles into drawing style
styles = mergeStyles([styles, mergedStateStyles]);
@@ -776,9 +745,7 @@ export default abstract class Item implements IItem {
const mergedData = mergeStyles([displayModelData, styles]);
const { animates } = mergedData;
const displayUpdateAnimates = [];
- const stateNames = previousStates
- .concat(this.states)
- .map((state) => state.name);
+ const stateNames = previousStates.concat(this.states).map((state) => state.name);
animates?.update?.forEach((animateCfg) => {
const { states } = animateCfg as IStateAnimate;
if (states && isArrayOverlap(states, stateNames)) {
@@ -822,7 +789,7 @@ export default abstract class Item implements IItem {
/**
* Get the local bounding box for the keyShape.
- * */
+ */
public getLocalKeyBBox(): AABB {
const { keyShape } = this.shapeMap;
return keyShape?.getLocalBounds() || ({ center: [0, 0, 0] } as AABB);
@@ -837,8 +804,7 @@ export default abstract class Item implements IItem {
// during animations, estimate the final bounds by the styles in displayModel
const { keyShape, labelShape } = this.shapeMap;
const { x = 0, y = 0, z = 0 } = this.displayModel.data;
- const { keyShape: keyShapeStyle, labelShape: labelShapeStyle } =
- this.renderExt.mergedStyles;
+ const { keyShape: keyShapeStyle, labelShape: labelShapeStyle } = this.renderExt.mergedStyles;
const estimateBounds = labelShape
? combineBounds([
getShapeLocalBoundsByStyle(keyShape, keyShapeStyle),
@@ -863,6 +829,7 @@ export default abstract class Item implements IItem {
/**
* Stop all the animations on the item.
+ * @param shapeIds
*/
public stopAnimations(shapeIds?: string[]) {
const promises = [];
@@ -916,6 +883,7 @@ export default abstract class Item implements IItem {
/**
* Update label positions on label canvas by getting viewport position from transformed canvas position.
+ * @param ignoreVisibility
*/
public updateLabelPosition(ignoreVisibility: boolean = false) {}
@@ -932,13 +900,7 @@ export default abstract class Item implements IItem {
this.stopAnimations();
const { animates } = this.displayModel.data;
if (animates?.buildOut?.length && !this.transient) {
- this.animations = this.runWithAnimates(
- animates,
- 'buildOut',
- undefined,
- undefined,
- func,
- );
+ this.animations = this.runWithAnimates(animates, 'buildOut', undefined, undefined, func);
} else {
// 2. clear group and remove group
func();
@@ -948,13 +910,17 @@ export default abstract class Item implements IItem {
/**
* Get the mapped value of a field on innerModel.
- * @param param0: {
+ * @param param0 {
* innerModel, // find unmapped field value from innerModel
* fieldName, // name of the field to read from innerModel
* mapper, // mapper object, contains the field's mapper
* dataChangedFields, // fields' names which are changed in data
* }
- * @returns { changed: boolean, value: unknown } return whether the mapper affects the value, and the mapped result
+ * @param param0.innerModel
+ * @param param0.fieldName
+ * @param param0.mapper
+ * @param param0.dataChangedFields
+ * @returns return whether the mapper affects the value, and the mapped result
*/
const updateChange = ({
innerModel,
@@ -988,29 +954,27 @@ const updateChange = ({
/**
* Update a shape's config according to the mapper.
- * @param param0: {
+ * @param param0 {
* innerModel, // find unmapped field value from innerModel
* mapper, // mapper object, contains the field's mapper
* shapeId, // id of the shape where the fieldName belong to
* dataChangedFields, // fields' names which are changed in data
* shapeConfig, // the shape's config to be updated
* }
- * @returns { changed: boolean, value: unknown } return whether the mapper affects the value, and the mapped result
+ * @param param0.innerModel
+ * @param param0.mapper
+ * @param param0.dataChangedFields
+ * @param param0.shapeConfig
+ * @param param0.fieldPath
*/
-const updateShapeChange = ({
- innerModel,
- mapper,
- dataChangedFields,
- shapeConfig,
- fieldPath,
-}) => {
+const updateShapeChange = ({ innerModel, mapper, dataChangedFields, shapeConfig, fieldPath }) => {
if (!mapper) return;
let innerModelValue = innerModel.data;
fieldPath?.forEach((field) => {
innerModelValue = innerModelValue[field] || {};
});
Object.keys(mapper).forEach((shapeAttrName) => {
- if (innerModelValue?.hasOwnProperty(shapeAttrName)) return;
+ if (shapeAttrName in innerModelValue) return;
const { value: mappedValue, changed } = updateChange({
innerModel,
mapper,
diff --git a/packages/g6/src/item/node.ts b/packages/g6/src/item/node.ts
index 2722da26b32..56ea6d2bb21 100644
--- a/packages/g6/src/item/node.ts
+++ b/packages/g6/src/item/node.ts
@@ -1,11 +1,11 @@
-import { Group, AABB } from '@antv/g';
+import { AABB, Group } from '@antv/g';
import { clone } from '@antv/util';
-import { Point } from '../types/common';
import { ComboDisplayModel, ComboModel, ID, IGraph, NodeModel } from '../types';
-import { DisplayMapper, State, LodLevelRanges } from '../types/item';
+import { ComboModelData } from '../types/combo';
+import { Point } from '../types/common';
+import { DisplayMapper, LodLevelRanges, State } from '../types/item';
import { NodeDisplayModel, NodeModelData } from '../types/node';
import { ComboStyleSet, NodeStyleSet } from '../types/theme';
-import { updateShapes } from '../util/shape';
import { animateShapes, getAnimatesExcludePosition } from '../util/animate';
import {
getCircleIntersectByPoint,
@@ -13,7 +13,7 @@ import {
getNearestPoint,
getRectIntersectByPoint,
} from '../util/point';
-import { ComboModelData } from '../types/combo';
+import { updateShapes } from '../util/shape';
import Item from './item';
interface IProps {
@@ -38,7 +38,7 @@ interface IProps {
delayFirstDraw?: boolean;
}
export default class Node extends Item {
- public type: 'node' | 'combo';
+ public declare type: 'node' | 'combo';
private renderBoundsCache: Map = new Map();
@@ -65,29 +65,16 @@ export default class Node extends Item {
animate = true,
onfinish: Function = () => {},
) {
- const {
- group,
- labelGroup,
- renderExt,
- shapeMap: prevShapeMap,
- model,
- graph,
- } = this;
+ const { group, labelGroup, renderExt, shapeMap: prevShapeMap, model, graph } = this;
renderExt.mergeStyles(displayModel);
const firstRendering = !this.shapeMap?.keyShape;
- const shapeMap = renderExt.draw(
- displayModel,
- this.shapeMap,
- diffData,
- diffState,
- );
+ const shapeMap = renderExt.draw(displayModel, this.shapeMap, diffData, diffState);
if (this.shapeMap.labelShape) {
this.shapeMap.labelShape.attributes.dataIsLabel = true;
}
if (this.shapeMap.labelBackgroundShape) {
- this.shapeMap.labelBackgroundShape.attributes.dataIsLabelBackground =
- true;
+ this.shapeMap.labelBackgroundShape.attributes.dataIsLabelBackground = true;
}
// add shapes to group, and update shapeMap
@@ -131,8 +118,7 @@ export default class Node extends Item {
undefined,
[group, labelGroup],
firstRendering ? 'buildIn' : 'update',
- current.concat(previous).map((state) => state.name) ||
- this.changedStates,
+ current.concat(previous).map((state) => state.name) || this.changedStates,
this.animateFrameListener,
(canceled) => onfinish(model.id, canceled),
);
@@ -146,6 +132,12 @@ export default class Node extends Item {
/**
* Update the node's position,
* do not update other styles which leads to better performance than updating position by updateData.
+ * @param displayModel
+ * @param diffData
+ * @param diffData.previous
+ * @param diffData.current
+ * @param animate
+ * @param onfinish
*/
public updatePosition(
displayModel: NodeDisplayModel | ComboDisplayModel,
@@ -157,27 +149,13 @@ export default class Node extends Item {
onfinish: Function = () => {},
) {
const { group, labelGroup, graph } = this;
- const {
- fx,
- fy,
- fz,
- x,
- y,
- z = 0,
- animates,
- disableAnimate,
- } = displayModel.data;
+ const { fx, fy, fz, x, y, z = 0, animates, disableAnimate } = displayModel.data;
const position = {
x: fx === undefined ? x : (fx as number),
y: fy === undefined ? y : (fy as number),
z: fz === undefined ? z : (fz as number),
};
- if (
- isNaN(position.x as number) ||
- isNaN(position.y as number) ||
- isNaN(position.z as number)
- )
- return;
+ if (isNaN(position.x as number) || isNaN(position.y as number) || isNaN(position.z as number)) return;
const viewportPosition = graph.getViewportByCanvas(position);
labelGroup.style.x = viewportPosition.x;
labelGroup.style.y = viewportPosition.y;
@@ -185,8 +163,7 @@ export default class Node extends Item {
if (animate && !disableAnimate && animates?.update) {
const groupAnimates = animates.update.filter(
({ shapeId, fields = [] }) =>
- (!shapeId || shapeId === 'group') &&
- (fields.includes('x') || fields.includes('y')),
+ (!shapeId || shapeId === 'group') && (fields.includes('x') || fields.includes('y')),
);
if (groupAnimates.length) {
const animations = animateShapes(
@@ -212,13 +189,13 @@ export default class Node extends Item {
/**
* Update label positions on label canvas by getting viewport position from transformed canvas position.
+ * @param ignoreVisibility
*/
public updateLabelPosition(ignoreVisibility?: boolean) {
if (!ignoreVisibility && this.labelGroup.style.visibility === 'hidden') {
return;
}
- const { graph, group, labelGroup, displayModel, shapeMap, renderExt } =
- this;
+ const { graph, group, labelGroup, displayModel, shapeMap, renderExt } = this;
let [x, y, z] = group.getPosition();
if (group.getAnimations().length) {
const { x: dataX, y: dataY, z: dataZ } = displayModel.data;
@@ -231,15 +208,9 @@ export default class Node extends Item {
if (!this.renderBoundsCache.has(id)) {
this.renderBoundsCache.set(id, clone(renderBounds));
}
- const dy =
- renderBounds.halfExtents[1] -
- this.renderBoundsCache.get(id).halfExtents[1];
+ const dy = renderBounds.halfExtents[1] - this.renderBoundsCache.get(id).halfExtents[1];
const zoom = graph.getZoom();
- const {
- x: vx,
- y: vy,
- z: vz,
- } = graph.getViewportByCanvas({ x, y: y + dy, z });
+ const { x: vx, y: vy, z: vz } = graph.getViewportByCanvas({ x, y: y + dy, z });
if (labelGroup.style.x !== vx) {
labelGroup.style.x = vx;
}
@@ -282,12 +253,7 @@ export default class Node extends Item {
});
}
- public clone(
- containerGroup: Group,
- labelContainerGroup: Group,
- shapeIds?: string[],
- disableAnimate?: boolean,
- ) {
+ public clone(containerGroup: Group, labelContainerGroup: Group, shapeIds?: string[], disableAnimate?: boolean) {
// clone specific shapes but not the whole item
if (shapeIds?.length) {
const group = new Group();
@@ -295,8 +261,7 @@ export default class Node extends Item {
if (!this.shapeMap[shapeId] || this.shapeMap[shapeId].destroyed) return;
const clonedKeyShape = this.shapeMap[shapeId].cloneNode();
// TODO: other animating attributes?
- clonedKeyShape.style.opacity =
- this.renderExt.mergedStyles[shapeId]?.opacity || 1;
+ clonedKeyShape.style.opacity = this.renderExt.mergedStyles[shapeId]?.opacity || 1;
group.appendChild(clonedKeyShape);
});
group.setPosition(this.group.getPosition());
@@ -330,32 +295,19 @@ export default class Node extends Item {
}
public getAnchorPoint(point: Point, anchorIdx?: number) {
- const { anchorPoints = [] } = this.displayModel.data as
- | NodeModelData
- | ComboModelData;
+ const { anchorPoints = [] } = this.displayModel.data as NodeModelData | ComboModelData;
- return this.getIntersectPoint(
- point,
- this.getPosition(),
- anchorPoints,
- anchorIdx,
- );
+ return this.getIntersectPoint(point, this.getPosition(), anchorPoints, anchorIdx);
}
- public getIntersectPoint(
- point: Point,
- innerPoint: Point,
- anchorPoints: number[][],
- anchorIdx?: number,
- ) {
+ public getIntersectPoint(point: Point, innerPoint: Point, anchorPoints: number[][], anchorIdx?: number) {
const { keyShape } = this.shapeMap;
const shapeType = keyShape.nodeName;
const { x, y, z } = innerPoint;
const keyShapeRenderBBox = keyShape.getRenderBounds();
const keyShapeWidth = keyShapeRenderBBox.max[0] - keyShapeRenderBBox.min[0];
- const keyShapeHeight =
- keyShapeRenderBBox.max[1] - keyShapeRenderBBox.min[1];
+ const keyShapeHeight = keyShapeRenderBBox.max[1] - keyShapeRenderBBox.min[1];
const anchorPositions = anchorPoints.map((pointRatio) => {
const [xRatio, yRatio] = pointRatio;
return {
@@ -426,8 +378,7 @@ export default class Node extends Item {
}
public getPosition(): Point {
- const initiated =
- this.shapeMap.keyShape && this.group.attributes.x !== undefined;
+ const initiated = this.shapeMap.keyShape && this.group.attributes.x !== undefined;
if (initiated && this.renderExt.dimensions !== 3) {
const { center } = this.shapeMap.keyShape.getRenderBounds();
return { x: center[0], y: center[1], z: center[2] };
diff --git a/packages/g6/src/runtime/controller/data.ts b/packages/g6/src/runtime/controller/data.ts
index da0f08b2d8c..622432ef834 100644
--- a/packages/g6/src/runtime/controller/data.ts
+++ b/packages/g6/src/runtime/controller/data.ts
@@ -1,14 +1,11 @@
+import { AABB } from '@antv/g';
import { Graph as GraphLib, ID } from '@antv/graphlib';
import { clone, isArray, isEmpty, isObject } from '@antv/util';
-import { AABB } from '@antv/g';
+import Combo from '../../item/combo';
+import Edge from '../../item/edge';
+import Node from '../../item/node';
import { registry } from '../../stdlib';
-import {
- ComboModel,
- ComboUserModel,
- GraphData,
- IGraph,
- Specification,
-} from '../../types';
+import { ComboModel, ComboUserModel, GraphData, IGraph } from '../../types';
import { ComboUserModelData } from '../../types/combo';
import {
DataChangeType,
@@ -19,20 +16,10 @@ import {
InlineGraphDataConfig,
InlineTreeDataConfig,
} from '../../types/data';
-import {
- EdgeDisplayModel,
- EdgeModel,
- EdgeModelData,
- EdgeUserModel,
- EdgeUserModelData,
-} from '../../types/edge';
+import { EdgeDisplayModel, EdgeModel, EdgeModelData, EdgeUserModel, EdgeUserModelData } from '../../types/edge';
import { ITEM_TYPE } from '../../types/item';
-import {
- NodeModel,
- NodeModelData,
- NodeUserModel,
- NodeUserModelData,
-} from '../../types/node';
+import { NodeModel, NodeModelData, NodeUserModel, NodeUserModelData } from '../../types/node';
+import { hasTreeBehaviors } from '../../util/behavior';
import {
AVAILABLE_DATA_LIFECYCLE,
DEFAULT_ACTIVE_DATA_LIFECYCLE,
@@ -46,11 +33,7 @@ import {
} from '../../util/data';
import { getExtension } from '../../util/extension';
import { isTreeLayout } from '../../util/layout';
-import { hasTreeBehaviors } from '../../util/behavior';
import { EdgeCollisionChecker, QuadTree } from '../../util/polyline';
-import Node from '../../item/node';
-import Edge from '../../item/edge';
-import Combo from '../../item/combo';
/**
* Manages the data transform extensions;
@@ -79,18 +62,11 @@ export class DataController {
this.tap();
}
- public findData(
- type: ITEM_TYPE,
- condition: ID[] | Function,
- ): EdgeModel[] | NodeModel[] | ComboModel[] {
+ public findData(type: ITEM_TYPE, condition: ID[] | Function): EdgeModel[] | NodeModel[] | ComboModel[] {
const { graphCore } = this;
const conditionType = typeof condition;
const conditionIsArray = isArray(condition);
- if (
- conditionType === 'string' ||
- conditionType === 'number' ||
- conditionIsArray
- ) {
+ if (conditionType === 'string' || conditionType === 'number' || conditionIsArray) {
const ids = conditionIsArray ? condition : [condition];
switch (type) {
case 'node':
@@ -101,9 +77,7 @@ export class DataController {
return model;
});
case 'edge':
- return ids.map((id) =>
- graphCore.hasEdge(id) ? graphCore.getEdge(id) : undefined,
- );
+ return ids.map((id) => (graphCore.hasEdge(id) ? graphCore.getEdge(id) : undefined));
case 'combo':
return ids.map((id) => {
if (!graphCore.hasNode(id)) return undefined;
@@ -113,8 +87,7 @@ export class DataController {
});
}
} else if (conditionType === 'function') {
- const getData =
- type === 'node' ? graphCore.getAllNodes : graphCore.getAllEdges;
+ const getData = type === 'node' ? graphCore.getAllNodes : graphCore.getAllEdges;
if (type === 'combo') {
// TODO getData = ?
}
@@ -123,9 +96,7 @@ export class DataController {
}
}
- public findAllData(
- type: ITEM_TYPE,
- ): EdgeModel[] | NodeModel[] | ComboModel[] {
+ public findAllData(type: ITEM_TYPE): EdgeModel[] | NodeModel[] | ComboModel[] {
if (!this.graphCore) return [];
switch (type) {
case 'node':
@@ -139,10 +110,7 @@ export class DataController {
}
}
- public findRelatedEdges(
- nodeId: ID,
- direction: 'in' | 'out' | 'both' = 'both',
- ) {
+ public findRelatedEdges(nodeId: ID, direction: 'in' | 'out' | 'both' = 'both') {
return this.graphCore.getRelatedEdges(nodeId, direction);
}
@@ -159,8 +127,7 @@ export class DataController {
edges.forEach((edge) => {
// @ts-ignore
- const edgeDisplayModel = itemMap.get(edge.id)
- .displayModel as EdgeDisplayModel;
+ const edgeDisplayModel = itemMap.get(edge.id).displayModel as EdgeDisplayModel;
if (!shouldBegin(edgeDisplayModel)) return;
const {
@@ -183,26 +150,18 @@ export class DataController {
// @ts-ignore
const nodeData = transientItem.displayModel.data;
if (nodeData) {
- nodeBBox.update(
- [nodeData.x as number, nodeData.y as number, 0],
- nodeBBox.halfExtents,
- );
+ nodeBBox.update([nodeData.x as number, nodeData.y as number, 0], nodeBBox.halfExtents);
}
}
const checker = new EdgeCollisionChecker(quadTree);
const collisions = checker.getCollidingEdges(nodeBBox);
- const collidingEdges = collisions.map((collision) =>
- this.graphCore.getEdge(collision.id),
- );
+ const collidingEdges = collisions.map((collision) => this.graphCore.getEdge(collision.id));
return collidingEdges;
}
- public findNeighborNodes(
- nodeId: ID,
- direction: 'in' | 'out' | 'both' = 'both',
- ) {
+ public findNeighborNodes(nodeId: ID, direction: 'in' | 'out' | 'both' = 'both') {
if (direction === 'in') return this.graphCore.getAncestors(nodeId);
if (direction === 'out') return this.graphCore.getSuccessors(nodeId);
return this.graphCore.getNeighbors(nodeId);
@@ -219,9 +178,7 @@ export class DataController {
private tap() {
this.extensions = this.getExtensions();
this.graph.hooks.datachange.tap(this.onDataChange.bind(this));
- this.graph.hooks.treecollapseexpand.tap(
- this.onTreeCollapseExpand.bind(this),
- );
+ this.graph.hooks.treecollapseexpand.tap(this.onTreeCollapseExpand.bind(this));
// check whether use tree layout or behaviors
// if so, establish tree structure for graph
@@ -236,9 +193,7 @@ export class DataController {
*/
private getExtensions() {
const { transforms = [] } = this.graph.getSpecification();
- const requiredTransformers = [
- { type: 'validate-data', activeLifecycle: 'all' },
- ];
+ const requiredTransformers = [{ type: 'validate-data', activeLifecycle: 'all' }];
return [...transforms, ...requiredTransformers]
.map((config) => ({
config,
@@ -250,6 +205,8 @@ export class DataController {
/**
* Listener of graph's datachange hook.
* @param param contains new graph data and type of data change
+ * @param param.data
+ * @param param.type
*/
private onDataChange(param: { data: DataConfig; type: DataChangeType }) {
const { data, type: changeType } = param;
@@ -275,10 +232,7 @@ export class DataController {
}
}
- private onTreeCollapseExpand(params: {
- ids: ID[];
- action: 'collapse' | 'expand';
- }) {
+ private onTreeCollapseExpand(params: { ids: ID[]; action: 'collapse' | 'expand' }) {
const { ids, action } = params;
ids.forEach((id) => {
this.graphCore.mergeNodeData(id, {
@@ -326,9 +280,7 @@ export class DataController {
const nodes = this.graphCore.getAllNodes();
const edges = this.graphCore.getAllEdges();
// graph data to tree structure and storing
- const rootIds = nodes
- .filter((node) => node.data.isRoot)
- .map((node) => node.id);
+ const rootIds = nodes.filter((node) => node.data.isRoot).map((node) => node.id);
graphData2TreeData({}, { nodes, edges }, rootIds).forEach((tree) => {
traverse(tree, (node) => {
node.children?.forEach((child) => {
@@ -342,6 +294,7 @@ export class DataController {
/**
* Change data by replace, merge repalce, union, remove or update.
* @param data new data
+ * @param dataConfig
* @param changeType type of data change, 'replace' means discard the old data. 'mergeReplace' means merge the common part. 'union' means merge whole sets of old and new one. 'remove' means remove the common part. 'update' means update the comme part.
*/
private changeData(dataConfig: DataConfig, changeType: DataChangeType) {
@@ -350,10 +303,7 @@ export class DataController {
this.dataType = dataType;
const preprocessedData = this.preprocessData(data, changeType);
- const { dataAdded, dataRemoved, dataUpdated } = this.transformData(
- preprocessedData,
- changeType,
- );
+ const { dataAdded, dataRemoved, dataUpdated } = this.transformData(preprocessedData, changeType);
if (changeType === 'replace') {
const { nodes, edges, combos } = dataAdded;
@@ -372,14 +322,8 @@ export class DataController {
this.graphCore.attachTreeStructure('combo');
nodes.forEach((node) => {
if (node.data.parentId) {
- if (
- validateComboStructure(this.graph, node.id, node.data.parentId)
- ) {
- this.graphCore.setParent(
- node.id,
- node.data.parentId as ID,
- 'combo',
- );
+ if (validateComboStructure(this.graph, node.id, node.data.parentId)) {
+ this.graphCore.setParent(node.id, node.data.parentId as ID, 'combo');
} else {
this.graphCore.mergeNodeData(node.id, { parentId: undefined });
}
@@ -387,9 +331,7 @@ export class DataController {
});
combos.forEach((combo) => {
if (combo.data.parentId) {
- if (
- validateComboStructure(this.graph, combo.id, combo.data.parentId)
- ) {
+ if (validateComboStructure(this.graph, combo.id, combo.data.parentId)) {
this.graphCore.setParent(combo.id, combo.data.parentId, 'combo');
} else {
this.graphCore.mergeNodeData(combo.id, { parentId: undefined });
@@ -403,12 +345,7 @@ export class DataController {
this.doUpdate(dataUpdated);
}
- if (
- data.edges?.filter(
- (edge) =>
- edge.hasOwnProperty('source') || edge.hasOwnProperty('target'),
- ).length
- ) {
+ if (data.edges?.filter((edge) => 'source' in edge || 'target' in edge).length) {
// convert and store tree structure to graphCore
this.updateTreeGraph(dataType, {
nodes: this.graphCore.getAllNodes(),
@@ -454,7 +391,7 @@ export class DataController {
const mergedData = mergeOneLevelData(graphCore.getNode(id), newModel);
graphCore.mergeNodeData(id, mergedData);
}
- if (data.hasOwnProperty('parentId')) {
+ if ('parentId' in data) {
graphCore.setParent(id, data.parentId, 'combo');
}
});
@@ -465,10 +402,8 @@ export class DataController {
const oldModel = graphCore.getEdge(newModel.id);
if (!oldModel) return;
const { id, source, target, data } = newModel;
- if (source && oldModel.source !== source)
- graphCore.updateEdgeSource(id, source);
- if (target && oldModel.target !== target)
- graphCore.updateEdgeTarget(id, target);
+ if (source && oldModel.source !== source) graphCore.updateEdgeSource(id, source);
+ if (target && oldModel.target !== target) graphCore.updateEdgeTarget(id, target);
if (data) {
const mergedData = mergeOneLevelData(graphCore.getEdge(id), newModel);
graphCore.mergeEdgeData(id, mergedData);
@@ -523,7 +458,7 @@ export class DataController {
data: others,
});
graphCore.mergeNodeData(id, mergedData);
- if (others.hasOwnProperty('parentId')) {
+ if ('parentId' in others) {
graphCore.setParent(id, others.parentId, 'combo');
}
}
@@ -579,23 +514,14 @@ export class DataController {
);
const succeedEdgeIds = graphCore
.getAllEdges()
- .filter(
- ({ source, target }) =>
- succeedIds.includes(source) && succeedIds.includes(target),
- )
+ .filter(({ source, target }) => succeedIds.includes(source) && succeedIds.includes(target))
.map((edge) => edge.id);
- this.graph.showItem(
- succeedIds
- .filter((succeedId) => succeedId !== id)
- .concat(succeedEdgeIds),
- );
+ this.graph.showItem(succeedIds.filter((succeedId) => succeedId !== id).concat(succeedEdgeIds));
// for tree graph view, remove the node from the parent's children list
graphCore.setParent(id, undefined, 'tree');
// for tree graph view, make the its children to be roots
- graphCore
- .getChildren(id, 'tree')
- .forEach((child) => graphCore.setParent(child.id, undefined, 'tree'));
+ graphCore.getChildren(id, 'tree').forEach((child) => graphCore.setParent(child.id, undefined, 'tree'));
}
graphCore.removeNode(id);
}
@@ -604,10 +530,7 @@ export class DataController {
data: GraphData;
type: 'graphData' | 'treeData' | 'fetch';
} {
- const { type, value } = dataConfig as
- | InlineGraphDataConfig
- | InlineTreeDataConfig
- | FetchDataConfig;
+ const { type, value } = dataConfig as InlineGraphDataConfig | InlineTreeDataConfig | FetchDataConfig;
let data = value;
if (!type) {
data = dataConfig as GraphData;
@@ -616,9 +539,7 @@ export class DataController {
} else if (type === 'fetch') {
// TODO: fetch
} else if (!(data as GraphData).nodes) {
- console.warn(
- 'Input data type is invalid, the type shuold be "graphData", "treeData", or "fetch".',
- );
+ console.warn('Input data type is invalid, the type shuold be "graphData", "treeData", or "fetch".');
return;
}
@@ -645,10 +566,7 @@ export class DataController {
[newModel],
(succeed) => {
const { x, y, _isCombo } = succeed.data;
- if (
- !_isCombo ||
- !this.graphCore.getChildren(succeed.id, 'combo').length
- ) {
+ if (!_isCombo || !this.graphCore.getChildren(succeed.id, 'combo').length) {
succeedNodesModels.push({
id: succeed.id,
data: {
@@ -707,9 +625,7 @@ export class DataController {
// update structure
(_children as ID[]).forEach((childId) => {
if (!this.graphCore.hasNode(childId)) {
- console.warn(
- `Adding child ${childId} to combo ${id} failed. The child ${childId} does not exist`,
- );
+ console.warn(`Adding child ${childId} to combo ${id} failed. The child ${childId} does not exist`);
return;
}
graphCore.setParent(childId, id, 'combo');
@@ -722,10 +638,7 @@ export class DataController {
* @param data new graph data
* @param type type of data change
*/
- private preprocessData(
- data: DataConfig,
- type: DataChangeType,
- ): GraphDataChanges {
+ private preprocessData(data: DataConfig, type: DataChangeType): GraphDataChanges {
const { graphCore } = this;
const dataCloned: GraphData = clone(data);
const prevData = graphCore
@@ -734,8 +647,7 @@ export class DataController {
edges: graphCore.getAllEdges(),
})
: {};
- const { prevMinusNew, newMinusPrev, intersectionOfPrevAndNew } =
- diffGraphData(prevData, dataCloned);
+ const { prevMinusNew, newMinusPrev, intersectionOfPrevAndNew } = diffGraphData(prevData, dataCloned);
const dataChangeMap: Record = {
replace: { dataAdded: dataCloned, dataUpdated: {}, dataRemoved: {} },
@@ -776,25 +688,22 @@ export class DataController {
*/
private isTransformActive = (config: any, changeType: DataChangeType) => {
let activeLifecycle =
- isObject(config) && 'activeLifecycle' in config
- ? (config as any).activeLifecycle
- : DEFAULT_ACTIVE_DATA_LIFECYCLE;
+ isObject(config) && 'activeLifecycle' in config ? (config as any).activeLifecycle : DEFAULT_ACTIVE_DATA_LIFECYCLE;
activeLifecycle = Array.isArray(activeLifecycle)
? activeLifecycle
: activeLifecycle === 'all'
- ? AVAILABLE_DATA_LIFECYCLE
- : [activeLifecycle];
+ ? AVAILABLE_DATA_LIFECYCLE
+ : [activeLifecycle];
return (activeLifecycle as string[]).includes(dataLifecycleMap[changeType]);
};
/**
* run transforms on preprocessed data
+ * @param data
+ * @param changeType
* @returns transformed data and the id map list
*/
- private transformData(
- data: GraphDataChanges,
- changeType: DataChangeType,
- ): GraphDataChanges {
+ private transformData(data: GraphDataChanges, changeType: DataChangeType): GraphDataChanges {
// transform the data with transform extensions, output innerData and idMaps ===
this.extensions.forEach(({ func, config }) => {
if (this.isTransformActive(config, changeType)) {
@@ -830,18 +739,11 @@ export class DataController {
* @param index index in linkedList to start from, from the tail by defailt
* @returns source id list
*/
-const getComesFromLinkedList = (
- id,
- linkedList,
- index = linkedList.length - 1,
-) => {
+const getComesFromLinkedList = (id, linkedList, index = linkedList.length - 1) => {
let comesFrom = [];
linkedList[index][id]?.forEach((comesFromId) => {
if (index === 0) comesFrom.push(comesFromId);
- else
- comesFrom = comesFrom.concat(
- getComesFromLinkedList(comesFromId, linkedList, index - 1),
- );
+ else comesFrom = comesFrom.concat(getComesFromLinkedList(comesFromId, linkedList, index - 1));
});
return comesFrom;
};
@@ -853,11 +755,7 @@ const getComesFromLinkedList = (
* @param isNode
* @returns false for no different, ['data'] for data different
*/
-const diffAt = (
- newModel,
- oldModel,
- isNode,
-): ('data' | 'source' | 'target')[] => {
+const diffAt = (newModel, oldModel, isNode): ('data' | 'source' | 'target')[] => {
// edge's source or target is changed
const diff = [];
if (!isNode) {
@@ -878,17 +776,10 @@ const diffAt = (
const oldValueIsObject = isObject(oldValue);
if (newValueIsObject !== oldValueIsObject) return diff.concat('data');
if (newValueIsObject && oldValueIsObject) {
- if (JSON.stringify(newValue) !== JSON.stringify(oldValue))
- return diff.concat('data');
+ if (JSON.stringify(newValue) !== JSON.stringify(oldValue)) return diff.concat('data');
else continue;
}
- if (
- typeof newValue === 'number' &&
- typeof oldValue === 'number' &&
- isNaN(newValue) &&
- isNaN(oldValue)
- )
- return;
+ if (typeof newValue === 'number' && typeof oldValue === 'number' && isNaN(newValue) && isNaN(oldValue)) return;
if (newValue !== oldValue) return diff.concat('data');
}
return diff;
@@ -910,10 +801,7 @@ const mergeOneLevelData = (
Object.keys(newData).forEach((key) => {
if (isArray(prevData[key]) || isArray(newData[key])) {
mergedData[key] = newData[key];
- } else if (
- typeof prevData[key] === 'object' &&
- typeof newData[key] === 'object'
- ) {
+ } else if (typeof prevData[key] === 'object' && typeof newData[key] === 'object') {
mergedData[key] = {
...(prevData[key] as object),
...(newData[key] as object),
@@ -925,11 +813,7 @@ const mergeOneLevelData = (
return mergedData;
};
-type UserModels = (
- | Partial
- | Partial
- | Partial
-)[];
+type UserModels = (Partial | Partial | Partial)[];
/**
* Generate the difference between two model list
diff --git a/packages/g6/src/runtime/controller/index.ts b/packages/g6/src/runtime/controller/index.ts
index e7a770b92e8..f5b4a22ebf1 100644
--- a/packages/g6/src/runtime/controller/index.ts
+++ b/packages/g6/src/runtime/controller/index.ts
@@ -2,6 +2,6 @@ export * from './data';
export * from './interaction';
export * from './item';
export * from './layout';
-export * from './viewport';
-export * from './theme';
export * from './plugin';
+export * from './theme';
+export * from './viewport';
diff --git a/packages/g6/src/runtime/controller/interaction.ts b/packages/g6/src/runtime/controller/interaction.ts
index 43f40d6441a..5ebdcc28778 100644
--- a/packages/g6/src/runtime/controller/interaction.ts
+++ b/packages/g6/src/runtime/controller/interaction.ts
@@ -2,36 +2,25 @@ import { FederatedPointerEvent, IElement } from '@antv/g';
import { registry } from '../../stdlib';
import { IGraph } from '../../types';
import { Behavior } from '../../types/behavior';
-import {
- CANVAS_EVENT_TYPE,
- DOM_EVENT_TYPE,
- IG6GraphEvent,
-} from '../../types/event';
-import {
- ItemInfo,
- getContextMenuEventProps,
- getItemInfoFromElement,
-} from '../../util/event';
+import { CANVAS_EVENT_TYPE, DOM_EVENT_TYPE, IG6GraphEvent } from '../../types/event';
+import { ItemInfo, getContextMenuEventProps, getItemInfoFromElement } from '../../util/event';
import { getExtension } from '../../util/extension';
type Listener = (event: IG6GraphEvent) => void;
/**
* Wraps the listener with error logging.
+ * @param type
+ * @param eventName
+ * @param listener
* @returns a new listener with error logging.
*/
-const wrapListener = (
- type: string,
- eventName: string,
- listener: Listener,
-): Listener => {
+const wrapListener = (type: string, eventName: string, listener: Listener): Listener => {
return (event: any) => {
try {
listener(event);
} catch (error) {
- console.error(
- `G6: Error occurred in "${eventName}" phase of the behavior "${type}"!`,
- );
+ console.error(`G6: Error occurred in "${eventName}" phase of the behavior "${type}"!`);
throw error;
}
};
@@ -85,17 +74,10 @@ export class InteractionController {
return Object.keys(modes).includes(mode);
};
- private initBehavior = (
- config: string | { type: string; key: string },
- ): Behavior | null => {
- const key =
- typeof config === 'string'
- ? config
- : (config as any).key || (config as any).type;
+ private initBehavior = (config: string | { type: string; key: string }): Behavior | null => {
+ const key = typeof config === 'string' ? config : (config as any).key || (config as any).type;
if (this.behaviorMap.has(key)) {
- console.error(
- `G6: Failed to add behavior with key or type "${key}"! It was already added.`,
- );
+ console.error(`G6: Failed to add behavior with key or type "${key}"! It was already added.`);
return;
}
try {
@@ -109,10 +91,7 @@ export class InteractionController {
}
return behavior;
} catch (error) {
- console.error(
- `G6: Failed to initialize behavior with key or type "${key}"!`,
- error,
- );
+ console.error(`G6: Failed to initialize behavior with key or type "${key}"!`, error);
return null;
}
};
@@ -122,10 +101,7 @@ export class InteractionController {
this.behaviorMap.delete(key);
behavior.destroy();
} catch (error) {
- console.error(
- `G6: Failed to destroy behavior with key or type "${key}"!`,
- error,
- );
+ console.error(`G6: Failed to destroy behavior with key or type "${key}"!`, error);
}
};
@@ -134,11 +110,7 @@ export class InteractionController {
this.listenersMap[key] = {};
Object.keys(events).forEach((eventName) => {
// Wrap the listener with error logging.
- const listener = wrapListener(
- key,
- eventName,
- events[eventName].bind(behavior),
- );
+ const listener = wrapListener(key, eventName, events[eventName].bind(behavior));
this.graph.on(eventName, listener);
this.listenersMap[key][eventName] = listener;
});
@@ -154,6 +126,7 @@ export class InteractionController {
/**
* Listener of graph's init hook. Add listeners from behaviors to graph.
* @param param contains the mode to switch to
+ * @param param.mode
*/
private onModeChange = (param: { mode: string }) => {
const { mode } = param;
@@ -196,6 +169,9 @@ export class InteractionController {
/**
* Listener of graph's behaviorchange hook. Update, add, or remove behaviors from modes.
* @param param contains action, modes, and behaviors
+ * @param param.action
+ * @param param.modes
+ * @param param.behaviors
*/
private onBehaviorChange = (param: {
action: 'update' | 'add' | 'remove';
@@ -212,10 +188,7 @@ export class InteractionController {
if (action === 'add') {
behaviors.forEach((config) => {
- const key =
- typeof config === 'string'
- ? config
- : (config as any).key || (config as any).type;
+ const key = typeof config === 'string' ? config : (config as any).key || (config as any).type;
const behavior = this.initBehavior(config);
if (behavior) {
this.addListeners(key, behavior);
@@ -226,10 +199,7 @@ export class InteractionController {
if (action === 'remove') {
behaviors.forEach((config) => {
- const key =
- typeof config === 'string'
- ? config
- : (config as any).key || (config as any).type;
+ const key = typeof config === 'string' ? config : (config as any).key || (config as any).type;
const behavior = this.behaviorMap.get(key);
if (behavior) {
this.removeListeners(key);
@@ -241,10 +211,7 @@ export class InteractionController {
if (action === 'update') {
behaviors.forEach((config) => {
- const key =
- typeof config === 'string'
- ? config
- : (config as any).key || (config as any).type;
+ const key = typeof config === 'string' ? config : (config as any).key || (config as any).type;
const behavior = this.behaviorMap.get(key);
if (behavior) {
behavior.updateConfig(config);
@@ -256,10 +223,7 @@ export class InteractionController {
private initEvents = () => {
Object.values(CANVAS_EVENT_TYPE).forEach((eventName) => {
- this.graph.canvas.document.addEventListener(
- eventName,
- this.handleCanvasEvent,
- );
+ this.graph.canvas.document.addEventListener(eventName, this.handleCanvasEvent);
});
const $dom = this.graph.canvas.getContextService().getDomElement();
Object.values(DOM_EVENT_TYPE).forEach((eventName) => {
@@ -341,6 +305,7 @@ export class InteractionController {
/**
* Emit item's pointerleave/pointerenter events when pointer moves on the canvas.
+ * @param event
*/
private handlePointerMove = (event: IG6GraphEvent) => {
const prevItemInfo = this.prevItemInfo;
diff --git a/packages/g6/src/runtime/controller/item.ts b/packages/g6/src/runtime/controller/item.ts
index 8d6a65d2c27..b8133816446 100644
--- a/packages/g6/src/runtime/controller/item.ts
+++ b/packages/g6/src/runtime/controller/item.ts
@@ -1,68 +1,37 @@
import { AABB, Canvas, DisplayObject, Group } from '@antv/g';
+import { AmbientLight, DirectionalLight } from '@antv/g-plugin-3d';
import { GraphChange, ID } from '@antv/graphlib';
-import {
- debounce,
- each,
- isArray,
- isNumber,
- isObject,
- map,
- throttle,
- uniq,
- uniqueId,
-} from '@antv/util';
-import { DirectionalLight, AmbientLight } from '@antv/g-plugin-3d';
+import { debounce, isArray, isNumber, isObject, uniq, uniqueId } from '@antv/util';
+import Combo from '../../item/combo';
+import Edge from '../../item/edge';
+import Node from '../../item/node';
import registry from '../../stdlib';
+import { BaseEdge } from '../../stdlib/item/edge/base';
+import { BaseNode } from '../../stdlib/item/node/base';
import {
ComboModel,
IGraph,
- NodeModel,
NodeDisplayModel,
NodeEncode,
+ NodeModel,
NodeModelData,
NodeShapesEncode,
} from '../../types';
-import {
- ComboDisplayModel,
- ComboEncode,
- ComboShapesEncode,
-} from '../../types/combo';
+import { ComboDisplayModel, ComboEncode, ComboShapesEncode } from '../../types/combo';
import { GraphCore } from '../../types/data';
+import { EdgeDisplayModel, EdgeEncode, EdgeModel, EdgeModelData, EdgeShapesEncode } from '../../types/edge';
+import { ViewportChangeHookParams } from '../../types/hook';
+import { DisplayMapper, ITEM_TYPE, LodLevelRanges, SHAPE_TYPE, ShapeStyle } from '../../types/item';
import {
- EdgeDisplayModel,
- EdgeEncode,
- EdgeModel,
- EdgeModelData,
- EdgeShapesEncode,
-} from '../../types/edge';
-import Node from '../../item/node';
-import Edge from '../../item/edge';
-import Combo from '../../item/combo';
-import {
- getCombinedBoundsByData,
- intersectBBox,
- upsertShape,
-} from '../../util/shape';
-import { getExtension } from '../../util/extension';
-import { upsertTransientItem } from '../../util/item';
-import {
- ITEM_TYPE,
- ShapeStyle,
- SHAPE_TYPE,
- LodLevelRanges,
- DisplayMapper,
-} from '../../types/item';
-import {
- ThemeSpecification,
- NodeThemeSpecifications,
+ ComboStyleSet,
+ ComboThemeSpecifications,
+ EdgeStyleSet,
EdgeThemeSpecifications,
NodeStyleSet,
- EdgeStyleSet,
- ComboThemeSpecifications,
- ComboStyleSet,
+ NodeThemeSpecifications,
+ ThemeSpecification,
} from '../../types/theme';
-import { ViewportChangeHookParams } from '../../types/hook';
-import { formatLodLevels } from '../../util/zoom';
+import { isBBoxInBBox, isPointInBBox } from '../../util/bbox';
import {
deconstructData,
graphComboTreeDfs,
@@ -72,14 +41,12 @@ import {
traverseGraphAncestors,
} from '../../util/data';
import { getGroupedChanges } from '../../util/event';
-import { BaseNode } from '../../stdlib/item/node/base';
-import { BaseEdge } from '../../stdlib/item/edge/base';
-import { isBBoxInBBox, isPointInBBox } from '../../util/bbox';
+import { getExtension } from '../../util/extension';
+import { upsertTransientItem } from '../../util/item';
+import { isPointPreventPolylineOverlap, isPolylineWithObstacleAvoidance } from '../../util/polyline';
+import { getCombinedBoundsByData, intersectBBox, upsertShape } from '../../util/shape';
import { convertToNumber } from '../../util/type';
-import {
- isPointPreventPolylineOverlap,
- isPolylineWithObstacleAvoidance,
-} from '../../util/polyline';
+import { formatLodLevels } from '../../util/zoom';
enum WARN_TYPE {
FAIL_GET_BBOX,
@@ -93,36 +60,21 @@ enum WARN_TYPE {
}
const getWarnMsg = {
- [WARN_TYPE.FAIL_GET_BBOX]: (ids) =>
- `Fail to get items' bboxes, the items with ids ${ids.join(
- ', ',
- )} do not exist.`,
+ [WARN_TYPE.FAIL_GET_BBOX]: (ids) => `Fail to get items' bboxes, the items with ids ${ids.join(', ')} do not exist.`,
[WARN_TYPE.FAIL_GET_VISIBLE]: (ids) =>
- `Fail to get items' visible, the items with ids ${ids.join(
- ', ',
- )} do not exist.`,
- [WARN_TYPE.FAIL_SET_STATE]: (ids) =>
- `Fail to set states for items ${ids.join(', ')}, which do not exist.`,
- [WARN_TYPE.FAIL_SET_VISIBLE]: (ids) =>
- `Fail to set visibility for items ${ids.join(', ')}, which do not exist.`,
- [WARN_TYPE.FAIL_DRAW_TRANSIENT]: (ids) =>
- `Fail to draw transient items of ${ids}, which do not exist.`,
+ `Fail to get items' visible, the items with ids ${ids.join(', ')} do not exist.`,
+ [WARN_TYPE.FAIL_SET_STATE]: (ids) => `Fail to set states for items ${ids.join(', ')}, which do not exist.`,
+ [WARN_TYPE.FAIL_SET_VISIBLE]: (ids) => `Fail to set visibility for items ${ids.join(', ')}, which do not exist.`,
+ [WARN_TYPE.FAIL_DRAW_TRANSIENT]: (ids) => `Fail to draw transient items of ${ids}, which do not exist.`,
[WARN_TYPE.SOURCE_NOT_EXIST]: (params) =>
- `The source nodes ${params
- .map((p) => p.source)
- .join(', ')} do not exist in the graph for edges ${params
+ `The source nodes ${params.map((p) => p.source).join(', ')} do not exist in the graph for edges ${params
.map((p) => p.id)
.join(', ')}, please add the nodes first`,
[WARN_TYPE.TARGET_NOT_EXIST]: (params) =>
- `The target nodes ${params
- .map((p) => p.target)
- .join(', ')} do not exist in the graph for edges ${params
+ `The target nodes ${params.map((p) => p.target).join(', ')} do not exist in the graph for edges ${params
.map((p) => p.id)
.join(', ')}, please add the nodes first`,
- [WARN_TYPE.FAIL_GET_STATE]: (ids) =>
- `Fail to get items' states, the items with ids ${ids.join(
- ', ',
- )} do not exist.`,
+ [WARN_TYPE.FAIL_GET_STATE]: (ids) => `Fail to get items' states, the items with ids ${ids.join(', ')} do not exist.`,
};
/**
* Manages and stores the node / edge / combo items.
@@ -138,26 +90,14 @@ export class ItemController {
/**
* Node / edge / combo items map
*/
- private itemMap: Map = new Map<
- ID,
- Node | Edge | Combo
- >();
+ private itemMap: Map = new Map();
/**
* node / edge / combo 's mapper in graph config
*/
- private nodeMapper:
- | ((data: NodeModel) => NodeDisplayModel)
- | NodeEncode
- | undefined;
- private edgeMapper:
- | ((data: EdgeModel) => EdgeDisplayModel)
- | EdgeEncode
- | undefined;
- private comboMapper:
- | ((data: ComboModel) => ComboDisplayModel)
- | ComboEncode
- | undefined;
+ private nodeMapper: ((data: NodeModel) => NodeDisplayModel) | NodeEncode | undefined;
+ private edgeMapper: ((data: EdgeModel) => EdgeDisplayModel) | EdgeEncode | undefined;
+ private comboMapper: ((data: ComboModel) => ComboDisplayModel) | ComboEncode | undefined;
private nodeStateMapper: {
[stateName: string]: ((data: NodeModel) => NodeDisplayModel) | NodeEncode;
@@ -166,9 +106,7 @@ export class ItemController {
[stateName: string]: ((data: EdgeModel) => EdgeDisplayModel) | EdgeEncode;
};
private comboStateMapper: {
- [stateName: string]:
- | ((data: ComboModel) => ComboDisplayModel)
- | ComboEncode;
+ [stateName: string]: ((data: ComboModel) => ComboDisplayModel) | ComboEncode;
};
// if the graph has combos, nodeGroup/edgeGroup/comboGroup point to the same group, so as transient groups.
@@ -188,14 +126,8 @@ export class ItemController {
private comboDataTypeSet: Set = new Set();
// The G shapes or groups on transient map drawn by this controller
- private transientObjectMap: Map = new Map<
- ID,
- DisplayObject
- >();
- private transientItemMap: Map = new Map<
- ID,
- Node | Edge | Combo | Group
- >();
+ private transientObjectMap: Map = new Map();
+ private transientItemMap: Map = new Map();
/** Caches */
private nearEdgesCache: Map = new Map();
@@ -209,14 +141,7 @@ export class ItemController {
constructor(graph: IGraph) {
this.graph = graph;
// get mapper for node / edge / combo
- const {
- node,
- edge,
- combo,
- nodeState = {},
- edgeState = {},
- comboState = {},
- } = graph.getSpecification();
+ const { node, edge, combo, nodeState = {}, edgeState = {}, comboState = {} } = graph.getSpecification();
this.nodeMapper = node;
this.edgeMapper = edge;
this.comboMapper = combo;
@@ -239,20 +164,14 @@ export class ItemController {
this.graph.hooks.render.tap(this.onRender.bind(this));
this.graph.hooks.itemchange.tap(this.onChange.bind(this));
this.graph.hooks.itemstatechange.tap(this.onItemStateChange.bind(this));
- this.graph.hooks.itemstateconfigchange.tap(
- this.onItemStateConfigChange.bind(this),
- );
- this.graph.hooks.itemvisibilitychange.tap(
- this.onItemVisibilityChange.bind(this),
- );
+ this.graph.hooks.itemstateconfigchange.tap(this.onItemStateConfigChange.bind(this));
+ this.graph.hooks.itemvisibilitychange.tap(this.onItemVisibilityChange.bind(this));
this.graph.hooks.itemzindexchange.tap(this.onItemZIndexChange.bind(this));
this.graph.hooks.transientupdate.tap(this.onTransientUpdate.bind(this));
this.graph.hooks.viewportchange.tap(this.onViewportChange.bind(this));
this.graph.hooks.themechange.tap(this.onThemeChange.bind(this));
this.graph.hooks.mapperchange.tap(this.onMapperChange.bind(this));
- this.graph.hooks.treecollapseexpand.tap(
- this.onTreeCollapseExpand.bind(this),
- );
+ this.graph.hooks.treecollapseexpand.tap(this.onTreeCollapseExpand.bind(this));
this.graph.hooks.destroy.tap(this.onDestroy.bind(this));
}
@@ -267,21 +186,22 @@ export class ItemController {
const edgeTypes = Object.keys(registry.useLib.edges || {});
const comboTypes = Object.keys(registry.useLib.combos || {});
return {
- node: nodeTypes
- .map((config) => getExtension(config, registry.useLib, 'node'))
- .filter(Boolean),
- edge: edgeTypes
- .map((config) => getExtension(config, registry.useLib, 'edge'))
- .filter(Boolean),
- combo: comboTypes
- .map((config) => getExtension(config, registry.useLib, 'combo'))
- .filter(Boolean),
+ node: nodeTypes.map((config) => getExtension(config, registry.useLib, 'node')).filter(Boolean),
+ edge: edgeTypes.map((config) => getExtension(config, registry.useLib, 'edge')).filter(Boolean),
+ combo: comboTypes.map((config) => getExtension(config, registry.useLib, 'combo')).filter(Boolean),
};
}
/**
* Listener of runtime's render hook.
* @param param contains inner data stored in graphCore structure
+ * @param param.graphCore
+ * @param param.theme
+ * @param param.transientCanvas
+ * @param param.transientLabelCanvas
+ * @param param.tileOptimize
+ * @param param.tileOptimize.tileFirstRender
+ * @param param.tileOptimize.tileFirstRenderSize
*/
private async onRender(param: {
graphCore: GraphCore;
@@ -293,13 +213,7 @@ export class ItemController {
tileFirstRenderSize?: number;
};
}) {
- const {
- graphCore,
- theme = {},
- transientCanvas,
- transientLabelCanvas,
- tileOptimize = {},
- } = param;
+ const { graphCore, theme = {}, transientCanvas, transientLabelCanvas, tileOptimize = {} } = param;
const { graph } = this;
// 0. clear groups on canvas, and create new groups
@@ -382,22 +296,13 @@ export class ItemController {
edges: graphCore.getAllEdges(),
});
- const renderNodesPromise = this.renderNodes(
- nodes,
- theme.node,
- tileOptimize,
- );
+ const renderNodesPromise = this.renderNodes(nodes, theme.node, tileOptimize);
let nodesInView;
if (renderNodesPromise) {
nodesInView = await renderNodesPromise;
}
this.renderCombos(combos, theme.combo, graphCore);
- const renderEdgesPromise = this.renderEdges(
- edges,
- theme.edge,
- tileOptimize,
- nodesInView,
- );
+ const renderEdgesPromise = this.renderEdges(edges, theme.edge, tileOptimize, nodesInView);
if (renderEdgesPromise) {
await renderEdgesPromise;
}
@@ -433,6 +338,14 @@ export class ItemController {
/**
* Listener of runtime's itemchange lifecycle hook.
* @param param
+ * @param param.type
+ * @param param.changes
+ * @param param.graphCore
+ * @param param.theme
+ * @param param.upsertAncestors
+ * @param param.animate
+ * @param param.action
+ * @param param.callback
*/
private onChange(param: {
type: ITEM_TYPE;
@@ -442,10 +355,7 @@ export class ItemController {
upsertAncestors?: boolean;
animate?: boolean;
action?: 'updatePosition';
- callback?: (
- model: NodeModel | EdgeModel | ComboModel,
- canceled?: boolean,
- ) => void;
+ callback?: (model: NodeModel | EdgeModel | ComboModel, canceled?: boolean) => void;
}) {
const {
changes,
@@ -461,33 +371,25 @@ export class ItemController {
// change items according to the order of the keys in groupedChanges
// === 1. remove edges; 2. remove nodes ===
- [...groupedChanges.EdgeRemoved, ...groupedChanges.NodeRemoved].forEach(
- ({ value }) => {
- const { id } = value;
- const item = itemMap.get(id);
- if (item) {
- item.destroy();
- itemMap.delete(id);
- }
- },
- );
+ [...groupedChanges.EdgeRemoved, ...groupedChanges.NodeRemoved].forEach(({ value }) => {
+ const { id } = value;
+ const item = itemMap.get(id);
+ if (item) {
+ item.destroy();
+ itemMap.delete(id);
+ }
+ });
- const {
- node: nodeTheme = {},
- edge: edgeTheme = {},
- combo: comboTheme = {},
- } = theme;
+ const { node: nodeTheme = {}, edge: edgeTheme = {}, combo: comboTheme = {} } = theme;
// === 3. add nodes ===
if (groupedChanges.NodeAdded.length) {
const newNodes: NodeModel[] = [];
const newCombos: ComboModel[] = [];
- groupedChanges.NodeAdded.map((change) => change.value).forEach(
- (model) => {
- if (model.data._isCombo) newCombos.push(model as ComboModel);
- else newNodes.push(model);
- },
- );
+ groupedChanges.NodeAdded.map((change) => change.value).forEach((model) => {
+ if (model.data._isCombo) newCombos.push(model as ComboModel);
+ else newNodes.push(model);
+ });
if (newNodes.length) {
this.renderNodes(newNodes, nodeTheme);
}
@@ -572,8 +474,7 @@ export class ItemController {
this.expandCombo(graphCore, innerModel as ComboModel);
}
}
- const previousParentId =
- item.displayModel.data.parentId || previous.parentId;
+ const previousParentId = item.displayModel.data.parentId || previous.parentId;
// update the current parent combo tree
// if the node has previous parent, related previous parent combo should be updated to
if (upsertAncestors) {
@@ -586,20 +487,14 @@ export class ItemController {
begins.push(graphCore.getNode(previousParentId as ID));
}
// ancestors and suceeds combos should be updated
- traverseAncestorsAndSucceeds(
- this.graph,
- graphCore,
- begins,
- (treeItem) => {
- if (treeItem.data._isCombo && treeItem.id !== innerModel.id)
- comboIdsToUpdate.add(treeItem.id);
- const relatedEdges = graphCore.getRelatedEdges(treeItem.id);
- relatedEdges.forEach((edge) => {
- edgeIdsToUpdate.add(edge.id);
- nodeRelatedIdsToUpdate.add(edge.id);
- });
- },
- );
+ traverseAncestorsAndSucceeds(this.graph, graphCore, begins, (treeItem) => {
+ if (treeItem.data._isCombo && treeItem.id !== innerModel.id) comboIdsToUpdate.add(treeItem.id);
+ const relatedEdges = graphCore.getRelatedEdges(treeItem.id);
+ relatedEdges.forEach((edge) => {
+ edgeIdsToUpdate.add(edge.id);
+ nodeRelatedIdsToUpdate.add(edge.id);
+ });
+ });
} else if (type === 'combo') {
// only the succeed combos should be updated
graphComboTreeDfs(this.graph, [innerModel], (child) => {
@@ -608,32 +503,21 @@ export class ItemController {
edgeIdsToUpdate.add(edge.id);
nodeRelatedIdsToUpdate.add(edge.id);
});
- if (child.data._isCombo && child.id !== innerModel.id)
- comboIdsToUpdate.add(child.id);
+ if (child.data._isCombo && child.id !== innerModel.id) comboIdsToUpdate.add(child.id);
});
}
}
// update the theme if the dataType value is changed
let itemTheme;
- if (
- nodeDataTypeField &&
- previous[nodeDataTypeField] !== current[nodeDataTypeField]
- ) {
- itemTheme = getItemTheme(
- this.nodeDataTypeSet,
- nodeDataTypeField,
- current[nodeDataTypeField],
- nodeTheme,
- );
+ if (nodeDataTypeField && previous[nodeDataTypeField] !== current[nodeDataTypeField]) {
+ itemTheme = getItemTheme(this.nodeDataTypeSet, nodeDataTypeField, current[nodeDataTypeField], nodeTheme);
}
const adjacentEdgeInnerModels = graphCore.getRelatedEdges(id);
if (isPointPreventPolylineOverlap(innerModel)) {
- const newNearEdges = this.graph.getNearEdgesData(id, (edge) =>
- isPolylineWithObstacleAvoidance(edge),
- );
+ const newNearEdges = this.graph.getNearEdgesData(id, (edge) => isPolylineWithObstacleAvoidance(edge));
const prevNearEdges = this.nearEdgesCache.get(id) || [];
adjacentEdgeInnerModels.push(...newNearEdges);
adjacentEdgeInnerModels.push(...prevNearEdges);
@@ -647,10 +531,7 @@ export class ItemController {
item.onframe = () => updateRelates({ edgeIds: nodeRelatedIdsToUpdate });
let statesCache;
- if (
- innerModel.data._isCombo &&
- previous.collapsed !== current.collapsed
- ) {
+ if (innerModel.data._isCombo && previous.collapsed !== current.collapsed) {
statesCache = this.graph.getItemAllStates(id);
this.graph.clearItemState(id);
}
@@ -665,9 +546,7 @@ export class ItemController {
(_, canceled) => {
item.onframe = undefined;
if (statesCache) {
- statesCache.forEach((state) =>
- this.graph.setItemState(id, state, true),
- );
+ statesCache.forEach((state) => this.graph.setItemState(id, state, true));
}
// @ts-ignore
debounceUpdateRelates({
@@ -711,24 +590,13 @@ export class ItemController {
// update the theme if the dataType value is changed
let itemTheme;
if (previous[edgeDataTypeField] !== current[edgeDataTypeField]) {
- itemTheme = getItemTheme(
- this.edgeDataTypeSet,
- edgeDataTypeField,
- current[edgeDataTypeField],
- edgeTheme,
- );
+ itemTheme = getItemTheme(this.edgeDataTypeSet, edgeDataTypeField, current[edgeDataTypeField], edgeTheme);
}
const item = itemMap.get(id);
const innerModel = graphCore.getEdge(id);
if (!item || item.destroyed) return;
- item.update(
- innerModel,
- { current, previous },
- isReplace,
- itemTheme,
- undefined,
- animate,
- (_, canceled) => callback(innerModel, canceled),
+ item.update(innerModel, { current, previous }, isReplace, itemTheme, undefined, animate, (_, canceled) =>
+ callback(innerModel, canceled),
);
});
}
@@ -745,10 +613,8 @@ export class ItemController {
Object.values(edgeUpdate).forEach((updateObj: any) => {
const { source, target, id } = updateObj;
const item = itemMap.get(id) as Edge;
- if (source !== undefined)
- item.updateEnd('source', this.itemMap.get(source) as Node);
- if (target !== undefined)
- item.updateEnd('target', this.itemMap.get(target) as Node);
+ if (source !== undefined) item.updateEnd('source', this.itemMap.get(source) as Node);
+ if (target !== undefined) item.updateEnd('target', this.itemMap.get(target) as Node);
});
}
// === 8. combo tree structure change, resort the shapes ===
@@ -780,18 +646,16 @@ export class ItemController {
* states: state names to set
* value: state value
* }
+ * @param param.ids
+ * @param param.states
+ * @param param.value
*/
- private onItemStateChange(param: {
- ids: ID[];
- states: string[];
- value: boolean;
- }) {
+ private onItemStateChange(param: { ids: ID[]; states: string[]; value: boolean }) {
const { ids, states, value } = param;
ids.forEach((id) => {
const item = this.itemMap.get(id);
if (!item) {
- this.cacheWarnMsg[WARN_TYPE.FAIL_SET_STATE] =
- this.cacheWarnMsg[WARN_TYPE.FAIL_SET_STATE] || [];
+ this.cacheWarnMsg[WARN_TYPE.FAIL_SET_STATE] = this.cacheWarnMsg[WARN_TYPE.FAIL_SET_STATE] || [];
this.cacheWarnMsg[WARN_TYPE.FAIL_SET_STATE].push(id);
// @ts-ignore
this.debounceWarn(WARN_TYPE.FAIL_SET_STATE);
@@ -810,19 +674,13 @@ export class ItemController {
itemType: ITEM_TYPE;
stateConfig:
| {
- [stateName: string]:
- | ((data: NodeModel) => NodeDisplayModel)
- | NodeShapesEncode;
+ [stateName: string]: ((data: NodeModel) => NodeDisplayModel) | NodeShapesEncode;
}
| {
- [stateName: string]:
- | ((data: EdgeModel) => EdgeDisplayModel)
- | EdgeShapesEncode;
+ [stateName: string]: ((data: EdgeModel) => EdgeDisplayModel) | EdgeShapesEncode;
}
| {
- [stateName: string]:
- | ((data: ComboModel) => ComboDisplayModel)
- | ComboShapesEncode;
+ [stateName: string]: ((data: ComboModel) => ComboDisplayModel) | ComboShapesEncode;
};
}) {
const { itemType, stateConfig } = param;
@@ -845,20 +703,11 @@ export class ItemController {
keepKeyShape?: boolean;
keepRelated?: boolean;
}) {
- const {
- ids,
- shapeIds,
- value,
- graphCore,
- animate = true,
- keepKeyShape = false,
- keepRelated = false,
- } = param;
+ const { ids, shapeIds, value, graphCore, animate = true, keepKeyShape = false, keepRelated = false } = param;
ids.forEach((id) => {
const item = this.itemMap.get(id);
if (!item) {
- this.cacheWarnMsg[WARN_TYPE.FAIL_SET_VISIBLE] =
- this.cacheWarnMsg[WARN_TYPE.FAIL_SET_VISIBLE] || [];
+ this.cacheWarnMsg[WARN_TYPE.FAIL_SET_VISIBLE] = this.cacheWarnMsg[WARN_TYPE.FAIL_SET_VISIBLE] || [];
this.cacheWarnMsg[WARN_TYPE.FAIL_SET_VISIBLE].push(id);
// @ts-ignore
this.debounceWarn(WARN_TYPE.FAIL_SET_VISIBLE);
@@ -889,8 +738,7 @@ export class ItemController {
const relatedEdges = graphCore.getRelatedEdges(id);
item.show(animate);
relatedEdges.forEach(({ id: edgeId, source, target }) => {
- if (this.getItemVisible(source) && this.getItemVisible(target))
- this.itemMap.get(edgeId)?.show(animate);
+ if (this.getItemVisible(source) && this.getItemVisible(target)) this.itemMap.get(edgeId)?.show(animate);
});
}
} else {
@@ -905,11 +753,7 @@ export class ItemController {
});
}
- private onItemZIndexChange(params: {
- ids: ID[];
- action: 'front' | 'back';
- graphCore: GraphCore;
- }) {
+ private onItemZIndexChange(params: { ids: ID[]; action: 'front' | 'back'; graphCore: GraphCore }) {
const { ids = [], action, graphCore } = params;
ids.forEach((id) => {
const item = this.itemMap.get(id);
@@ -942,18 +786,15 @@ export class ItemController {
/**
* get the items inside viewport
+ * @param containType
+ * @param ratio
* @returns
*/
- private groupItemsByView = (
- containType: 'inside' | 'intersect' = 'inside',
- ratio: number = 1,
- ) => {
+ private groupItemsByView = (containType: 'inside' | 'intersect' = 'inside', ratio: number = 1) => {
const range = this.graph.getCanvasRange();
const items = Array.from(this.itemMap, ([key, value]) => value);
- const containFunc =
- containType === 'intersect' ? intersectBBox : isBBoxInBBox;
- let { inView: itemsInView, outView: itemsOutView } =
- this.cacheViewItems || {};
+ const containFunc = containType === 'intersect' ? intersectBBox : isBBoxInBBox;
+ let { inView: itemsInView, outView: itemsOutView } = this.cacheViewItems || {};
if (!ratio || ratio === 1 || !this.cacheViewItems) {
itemsInView = [];
itemsOutView = [];
@@ -994,19 +835,11 @@ export class ItemController {
};
private onViewportChange = debounce(
- ({
- transform,
- effectTiming,
- tileLodSize = 1000,
- }: ViewportChangeHookParams) => {
+ ({ transform, effectTiming, tileLodSize = 1000 }: ViewportChangeHookParams) => {
const { zoom } = transform;
if (zoom) {
const zoomRatio = this.graph.getZoom();
- const {
- items,
- inView: itemsInview,
- outView: itemsOutView,
- } = this.groupItemsByView();
+ const { items, inView: itemsInview, outView: itemsOutView } = this.groupItemsByView();
const sortedItems = itemsInview.concat(itemsOutView);
const sections = Math.ceil(items.length / tileLodSize);
const itemSections = Array.from({ length: sections }, (v, i) =>
@@ -1036,17 +869,11 @@ export class ItemController {
this.itemMap.forEach((item) => {
const itemTye = item.getType();
const usingTheme = itemTye === 'node' ? nodeTheme : edgeTheme;
- const usingTypeSet =
- itemTye === 'node' ? nodeDataTypeSet : edgeDataTypeSet;
+ const usingTypeSet = itemTye === 'node' ? nodeDataTypeSet : edgeDataTypeSet;
const { dataTypeField } = usingTheme;
let dataType;
if (dataTypeField) dataType = item.model.data[dataTypeField] as string;
- const itemTheme = getItemTheme(
- usingTypeSet,
- dataTypeField,
- dataType,
- usingTheme,
- );
+ const itemTheme = getItemTheme(usingTypeSet, dataTypeField, dataType, usingTheme);
item.update(
item.model,
undefined,
@@ -1149,8 +976,7 @@ export class ItemController {
if (isItemType) {
const item = this.itemMap.get(id);
if (!item) {
- this.cacheWarnMsg[WARN_TYPE.FAIL_DRAW_TRANSIENT] =
- this.cacheWarnMsg[WARN_TYPE.FAIL_DRAW_TRANSIENT] || [];
+ this.cacheWarnMsg[WARN_TYPE.FAIL_DRAW_TRANSIENT] = this.cacheWarnMsg[WARN_TYPE.FAIL_DRAW_TRANSIENT] || [];
this.cacheWarnMsg[WARN_TYPE.FAIL_DRAW_TRANSIENT].push(id);
// @ts-ignore
this.debounceWarn(WARN_TYPE.FAIL_DRAW_TRANSIENT);
@@ -1171,19 +997,14 @@ export class ItemController {
);
if (shapeIds) {
// only update node positions to cloned node container(group)
- if (
- (type === 'node' || type === 'combo') &&
- data.hasOwnProperty('x') &&
- data.hasOwnProperty('y')
- ) {
+ if ((type === 'node' || type === 'combo') && 'x' in data && 'y' in data) {
const { x, y } = data;
(transientItem as Group).setPosition([x, y]);
}
// TODO: edge onlyDrawKeyShape?
} else {
const transItem = transientItem as Node | Edge | Combo;
- const positionChanged =
- data.hasOwnProperty('x') && data.hasOwnProperty('y');
+ const positionChanged = 'x' in data && 'y' in data;
if (type === 'combo' && positionChanged) {
const { x, y } = data;
const { x: ox = x, y: oy = y } = transItem.displayModel.data;
@@ -1196,8 +1017,7 @@ export class ItemController {
(node) => {
const transChild = this.transientItemMap.get(node.id) as Node;
if (!transChild) return;
- const { x: childX = 0, y: childY = 0 } = transChild.model
- .data as NodeModelData;
+ const { x: childX = 0, y: childY = 0 } = transChild.model.data as NodeModelData;
transChild?.update({
...transChild.model,
@@ -1212,16 +1032,9 @@ export class ItemController {
);
}
- if (
- graphCore.hasTreeStructure('combo') &&
- type !== 'edge' &&
- positionChanged
- ) {
+ if (graphCore.hasTreeStructure('combo') && type !== 'edge' && positionChanged) {
// force update ancestor combos in the sametime
- let currentAncestor = graphCore.getParent(
- transItem.model.id,
- 'combo',
- );
+ let currentAncestor = graphCore.getParent(transItem.model.id, 'combo');
while (currentAncestor) {
const ancestorItem = this.transientItemMap.get(currentAncestor.id);
if (ancestorItem) (ancestorItem as Combo).forceUpdate();
@@ -1240,9 +1053,7 @@ export class ItemController {
if (type !== 'edge') {
const relatedEdges = graphCore.getRelatedEdges(transItem.model.id);
relatedEdges.forEach((relatedEdge) => {
- const transientEdge = this.transientItemMap.get(
- relatedEdge.id,
- ) as Edge;
+ const transientEdge = this.transientItemMap.get(relatedEdge.id) as Edge;
if (transientEdge) transientEdge.forceUpdate();
});
}
@@ -1270,9 +1081,7 @@ export class ItemController {
return this.itemMap;
}
- public findDisplayModel(
- id: ID,
- ): NodeDisplayModel | EdgeDisplayModel | ComboDisplayModel {
+ public findDisplayModel(id: ID): NodeDisplayModel | EdgeDisplayModel | ComboDisplayModel {
const item = this.itemMap.get(id);
if (!item) return { id, data: {} };
return {
@@ -1288,6 +1097,10 @@ export class ItemController {
/**
* Create nodes with inner data to canvas.
* @param models nodes' inner data
+ * @param nodeTheme
+ * @param tileOptimize
+ * @param tileOptimize.tileFirstRender
+ * @param tileOptimize.tileFirstRenderSize
*/
private async renderNodes(
models: NodeModel[],
@@ -1297,19 +1110,11 @@ export class ItemController {
tileFirstRenderSize?: number;
},
): Promise | undefined {
- const {
- nodeExtensions,
- nodeGroup,
- nodeLabelGroup,
- nodeDataTypeSet,
- graph,
- } = this;
+ const { nodeExtensions, nodeGroup, nodeLabelGroup, nodeDataTypeSet, graph } = this;
const { dataTypeField = '' } = nodeTheme;
const { tileFirstRender, tileFirstRenderSize = 1000 } = tileOptimize || {};
const zoom = graph.getZoom();
- const delayFirstDraw = isNumber(tileFirstRender)
- ? models.length > tileFirstRender
- : tileFirstRender;
+ const delayFirstDraw = isNumber(tileFirstRender) ? models.length > tileFirstRender : tileFirstRender;
const itemsInView = [];
const itemsOutView = [];
const viewRange = this.graph.getCanvasRange();
@@ -1317,12 +1122,7 @@ export class ItemController {
// get the base styles from theme
let dataType;
if (dataTypeField) dataType = node.data[dataTypeField] as string;
- const itemTheme = getItemTheme(
- nodeDataTypeSet,
- dataTypeField,
- dataType,
- nodeTheme,
- );
+ const itemTheme = getItemTheme(nodeDataTypeSet, dataTypeField, dataType, nodeTheme);
const nodeItem = new Node({
graph,
@@ -1347,13 +1147,7 @@ export class ItemController {
this.itemMap.set(node.id, nodeItem);
const { x, y } = nodeItem.model.data;
- if (
- delayFirstDraw &&
- isPointInBBox(
- { x: convertToNumber(x), y: convertToNumber(y) },
- viewRange,
- )
- ) {
+ if (delayFirstDraw && isPointInBBox({ x: convertToNumber(x), y: convertToNumber(y) }, viewRange)) {
itemsInView.push(nodeItem);
} else {
itemsOutView.push(nodeItem);
@@ -1363,10 +1157,7 @@ export class ItemController {
let requestId;
const sectionNum = Math.ceil(itemsOutView.length / tileFirstRenderSize);
const sections = Array.from({ length: sectionNum }, (v, i) =>
- itemsOutView.slice(
- i * tileFirstRenderSize,
- i * tileFirstRenderSize + tileFirstRenderSize,
- ),
+ itemsOutView.slice(i * tileFirstRenderSize, i * tileFirstRenderSize + tileFirstRenderSize),
);
sections.unshift(itemsInView);
const update = (resolve) => {
@@ -1392,25 +1183,15 @@ export class ItemController {
}
}
- private async renderCombos(
- models: ComboModel[],
- comboTheme: ComboThemeSpecifications = {},
- graphCore: GraphCore,
- ) {
- const { comboExtensions, comboGroup, comboDataTypeSet, graph, itemMap } =
- this;
+ private async renderCombos(models: ComboModel[], comboTheme: ComboThemeSpecifications = {}, graphCore: GraphCore) {
+ const { comboExtensions, comboGroup, comboDataTypeSet, graph, itemMap } = this;
const { dataTypeField = '' } = comboTheme;
const zoom = graph.getZoom();
models.forEach((combo) => {
// get the base styles from theme
let dataType;
if (dataTypeField) dataType = combo.data[dataTypeField] as string;
- const itemTheme = getItemTheme(
- comboDataTypeSet,
- dataTypeField,
- dataType,
- comboTheme,
- );
+ const itemTheme = getItemTheme(comboDataTypeSet, dataTypeField, dataType, comboTheme);
const getCombinedBounds = () => {
// calculate the position of the combo according to its children
@@ -1461,6 +1242,11 @@ export class ItemController {
/**
* Create edges with inner data to canvas.
* @param models edges' inner data
+ * @param edgeTheme
+ * @param tileOptimize
+ * @param tileOptimize.tileFirstRender
+ * @param tileOptimize.tileFirstRenderSize
+ * @param nodesInView
*/
private renderEdges(
models: EdgeModel[],
@@ -1471,21 +1257,12 @@ export class ItemController {
},
nodesInView?: Node[],
): Promise | undefined {
- const {
- edgeExtensions,
- edgeGroup,
- edgeLabelGroup,
- itemMap,
- edgeDataTypeSet,
- graph,
- } = this;
+ const { edgeExtensions, edgeGroup, edgeLabelGroup, itemMap, edgeDataTypeSet, graph } = this;
const { dataTypeField = '' } = edgeTheme;
const { tileFirstRender, tileFirstRenderSize = 1000 } = tileOptimize || {};
const zoom = graph.getZoom();
const nodeMap = filterItemMapByType(itemMap, 'node') as Map;
- const delayFirstDraw = isNumber(tileFirstRender)
- ? models.length > tileFirstRender
- : tileFirstRender;
+ const delayFirstDraw = isNumber(tileFirstRender) ? models.length > tileFirstRender : tileFirstRender;
const nodesInViewIds = new Set(nodesInView?.map((node) => node.getID()));
const edgesInView = [];
const edgesOutView = [];
@@ -1494,16 +1271,14 @@ export class ItemController {
const sourceItem = itemMap.get(source) as Node;
const targetItem = itemMap.get(target) as Node;
if (!sourceItem) {
- this.cacheWarnMsg[WARN_TYPE.SOURCE_NOT_EXIST] =
- this.cacheWarnMsg[WARN_TYPE.SOURCE_NOT_EXIST] || [];
+ this.cacheWarnMsg[WARN_TYPE.SOURCE_NOT_EXIST] = this.cacheWarnMsg[WARN_TYPE.SOURCE_NOT_EXIST] || [];
this.cacheWarnMsg[WARN_TYPE.SOURCE_NOT_EXIST].push({ id, source });
// @ts-ignore
this.debounceWarn(WARN_TYPE.SOURCE_NOT_EXIST);
return;
}
if (!targetItem) {
- this.cacheWarnMsg[WARN_TYPE.TARGET_NOT_EXIST] =
- this.cacheWarnMsg[WARN_TYPE.TARGET_NOT_EXIST] || [];
+ this.cacheWarnMsg[WARN_TYPE.TARGET_NOT_EXIST] = this.cacheWarnMsg[WARN_TYPE.TARGET_NOT_EXIST] || [];
this.cacheWarnMsg[WARN_TYPE.TARGET_NOT_EXIST].push({ id, source });
// @ts-ignore
this.debounceWarn(WARN_TYPE.TARGET_NOT_EXIST);
@@ -1512,12 +1287,7 @@ export class ItemController {
// get the base styles from theme
let dataType;
if (dataTypeField) dataType = edge.data[dataTypeField] as string;
- const itemTheme = getItemTheme(
- edgeDataTypeSet,
- dataTypeField,
- dataType,
- edgeTheme,
- );
+ const itemTheme = getItemTheme(edgeDataTypeSet, dataTypeField, dataType, edgeTheme);
const edgeItem = new Edge({
graph,
delayFirstDraw,
@@ -1540,8 +1310,7 @@ export class ItemController {
});
itemMap.set(id, edgeItem);
- if (nodesInViewIds.has(source) || nodesInViewIds.has(target))
- edgesInView.push(edgeItem);
+ if (nodesInViewIds.has(source) || nodesInViewIds.has(target)) edgesInView.push(edgeItem);
else edgesOutView.push(edgeItem);
return edgeItem;
});
@@ -1550,10 +1319,7 @@ export class ItemController {
let requestId;
const sectionNum = Math.ceil(edgesOutView.length / tileFirstRenderSize);
const sections = Array.from({ length: sectionNum }, (v, i) =>
- edgesOutView.slice(
- i * tileFirstRenderSize,
- i * tileFirstRenderSize + tileFirstRenderSize,
- ),
+ edgesOutView.slice(i * tileFirstRenderSize, i * tileFirstRenderSize + tileFirstRenderSize),
);
sections.unshift(edgesInView);
const update = (resolve) => {
@@ -1577,11 +1343,7 @@ export class ItemController {
* @param value state value, true by default
* @returns
*/
- public findIdByState(
- itemType: ITEM_TYPE,
- state: string,
- value: string | boolean = true,
- ): ID[] {
+ public findIdByState(itemType: ITEM_TYPE, state: string, value: string | boolean = true): ID[] {
const ids: ID[] = [];
this.itemMap.forEach((item) => {
if (item.getType() !== itemType) return;
@@ -1599,8 +1361,7 @@ export class ItemController {
public getItemState(id: ID, state: string) {
const item = this.itemMap.get(id);
if (!item) {
- this.cacheWarnMsg[WARN_TYPE.FAIL_GET_STATE] =
- this.cacheWarnMsg[WARN_TYPE.FAIL_GET_STATE] || [];
+ this.cacheWarnMsg[WARN_TYPE.FAIL_GET_STATE] = this.cacheWarnMsg[WARN_TYPE.FAIL_GET_STATE] || [];
this.cacheWarnMsg[WARN_TYPE.FAIL_GET_STATE].push(id);
// @ts-ignore
this.debounceWarn(WARN_TYPE.FAIL_GET_STATE);
@@ -1612,8 +1373,7 @@ export class ItemController {
public getItemAllStates(id: ID): string[] {
const item = this.itemMap.get(id);
if (!item) {
- this.cacheWarnMsg[WARN_TYPE.FAIL_GET_STATE] =
- this.cacheWarnMsg[WARN_TYPE.FAIL_GET_STATE] || [];
+ this.cacheWarnMsg[WARN_TYPE.FAIL_GET_STATE] = this.cacheWarnMsg[WARN_TYPE.FAIL_GET_STATE] || [];
this.cacheWarnMsg[WARN_TYPE.FAIL_GET_STATE].push(id);
// @ts-ignore
this.debounceWarn(WARN_TYPE.FAIL_GET_STATE);
@@ -1629,17 +1389,10 @@ export class ItemController {
return this.itemMap.get(id);
}
- public getItemBBox(
- id: ID,
- isKeyShape = false,
- isTransient = false,
- ): AABB | false {
- const item = isTransient
- ? this.transientItemMap.get(id)
- : this.itemMap.get(id);
+ public getItemBBox(id: ID, isKeyShape = false, isTransient = false): AABB | false {
+ const item = isTransient ? this.transientItemMap.get(id) : this.itemMap.get(id);
if (!item) {
- this.cacheWarnMsg[WARN_TYPE.FAIL_GET_BBOX] =
- this.cacheWarnMsg[WARN_TYPE.FAIL_GET_BBOX] || [];
+ this.cacheWarnMsg[WARN_TYPE.FAIL_GET_BBOX] = this.cacheWarnMsg[WARN_TYPE.FAIL_GET_BBOX] || [];
this.cacheWarnMsg[WARN_TYPE.FAIL_GET_BBOX].push(id);
// @ts-ignore
this.debounceWarn(WARN_TYPE.FAIL_GET_BBOX);
@@ -1653,8 +1406,7 @@ export class ItemController {
const item = this.itemMap.get(id);
const shapeIds = [];
Object.keys(item.shapeMap).forEach((shapeId) => {
- if (item.shapeMap[shapeId]?.attributes.visibility !== 'hidden')
- shapeIds.push(shapeId);
+ if (item.shapeMap[shapeId]?.attributes.visibility !== 'hidden') shapeIds.push(shapeId);
});
return shapeIds;
}
@@ -1672,8 +1424,7 @@ export class ItemController {
public getItemVisible(id: ID) {
const item = this.itemMap.get(id);
if (!item) {
- this.cacheWarnMsg[WARN_TYPE.FAIL_GET_VISIBLE] =
- this.cacheWarnMsg[WARN_TYPE.FAIL_GET_VISIBLE] || [];
+ this.cacheWarnMsg[WARN_TYPE.FAIL_GET_VISIBLE] = this.cacheWarnMsg[WARN_TYPE.FAIL_GET_VISIBLE] || [];
this.cacheWarnMsg[WARN_TYPE.FAIL_GET_VISIBLE].push(id);
// @ts-ignore
this.debounceWarn(WARN_TYPE.FAIL_GET_VISIBLE);
@@ -1761,10 +1512,8 @@ export class ItemController {
const { source, target } = graphCore.getEdge(eid);
const ends = { source, target };
const endsVisible = {
- source:
- this.graph.getItemVisible(source) || nodesToShow.includes(source),
- target:
- this.graph.getItemVisible(target) || nodesToShow.includes(target),
+ source: this.graph.getItemVisible(source) || nodesToShow.includes(source),
+ target: this.graph.getItemVisible(target) || nodesToShow.includes(target),
};
// actual edges to show
if (endsVisible.source && endsVisible.target) return true;
@@ -1774,28 +1523,18 @@ export class ItemController {
Object.keys(virtualEnds).forEach((end) => {
if (!endsVisible[end]) {
if (!visibleAncestorMap.get(ends[end])) {
- traverseAncestors(
- graphCore,
- [graphCore.getNode(ends[end])],
- (ancestor) => {
- if (visibleAncestorMap.has(ends[end])) return;
- if (
- this.graph.getItemVisible(ancestor.id) ||
- nodesToShow.includes(ancestor.id)
- )
- visibleAncestorMap.set(ends[end], ancestor.id);
- },
- );
+ traverseAncestors(graphCore, [graphCore.getNode(ends[end])], (ancestor) => {
+ if (visibleAncestorMap.has(ends[end])) return;
+ if (this.graph.getItemVisible(ancestor.id) || nodesToShow.includes(ancestor.id))
+ visibleAncestorMap.set(ends[end], ancestor.id);
+ });
}
virtualEnds[end] = visibleAncestorMap.get(ends[end]);
} else {
virtualEnds[end] = ends[end];
}
});
- if (
- virtualEnds.source !== undefined &&
- virtualEnds.target !== undefined
- ) {
+ if (virtualEnds.source !== undefined && virtualEnds.target !== undefined) {
virtualPairs.push(virtualEnds);
}
return false;
@@ -1814,6 +1553,10 @@ export class ItemController {
/**
* Collapse or expand a sub tree according to action
* @param params
+ * @param params.ids
+ * @param params.animate
+ * @param params.action
+ * @param params.graphCore
*/
private onTreeCollapseExpand(params: {
ids: ID[];
@@ -1839,13 +1582,8 @@ export class ItemController {
* @param rootModels The root node models of sub trees
* @param graphCore
* @param animate Whether enable animations for expanding, true by default
- * @returns
*/
- private collapseSubTree(
- rootModels: NodeModel[],
- graphCore: GraphCore,
- animate = true,
- ) {
+ private collapseSubTree(rootModels: NodeModel[], graphCore: GraphCore, animate = true) {
let positions = [];
rootModels.forEach((root) => {
let shouldCollapse = true;
@@ -1856,10 +1594,7 @@ export class ItemController {
(node) => {
if (node.id === root.id) return;
const neighbors = graphCore.getNeighbors(node.id);
- if (
- !graphCore.getChildren(node.id, 'tree')?.length &&
- neighbors.length > 1
- ) {
+ if (!graphCore.getChildren(node.id, 'tree')?.length && neighbors.length > 1) {
shouldCollapse = false;
}
nodes.push(node);
@@ -1880,16 +1615,11 @@ export class ItemController {
}
});
if (!positions.length) return;
- this.graph.updateNodePosition(
- positions,
- undefined,
- !animate,
- (model, canceled) => {
- positions.forEach((position) => {
- this.graph.hideItem(position.id, { disableAnimate: canceled });
- });
- },
- );
+ this.graph.updateNodePosition(positions, undefined, !animate, (model, canceled) => {
+ positions.forEach((position) => {
+ this.graph.hideItem(position.id, { disableAnimate: canceled });
+ });
+ });
}
/**
@@ -1899,37 +1629,22 @@ export class ItemController {
* @param animate Whether enable animations for expanding, true by default.
* @returns
*/
- private async expandSubTree(
- rootModels: NodeModel[],
- graphCore: GraphCore,
- animate = true,
- ) {
+ private async expandSubTree(rootModels: NodeModel[], graphCore: GraphCore, animate = true) {
let allNodeIds = [];
let allEdgeIds = [];
rootModels.forEach((root) => {
const nodeIds = [];
- graphCoreTreeDfs(
- graphCore,
- [root],
- (node) => nodeIds.push(node.id),
- 'TB',
- 'tree',
- {
- stopBranchFn: (node) => {
- const shouldStop =
- node.id !== root.id && (node.data.collapsed as boolean);
- if (shouldStop) nodeIds.push(node.id);
- return shouldStop;
- },
+ graphCoreTreeDfs(graphCore, [root], (node) => nodeIds.push(node.id), 'TB', 'tree', {
+ stopBranchFn: (node) => {
+ const shouldStop = node.id !== root.id && (node.data.collapsed as boolean);
+ if (shouldStop) nodeIds.push(node.id);
+ return shouldStop;
},
- );
+ });
allEdgeIds = allEdgeIds.concat(
graphCore
.getAllEdges()
- .filter(
- (edge) =>
- nodeIds.includes(edge.source) && nodeIds.includes(edge.target),
- )
+ .filter((edge) => nodeIds.includes(edge.source) && nodeIds.includes(edge.target))
.map((edge) => edge.id),
);
allNodeIds = allNodeIds.concat(nodeIds.filter((id) => id !== root.id));
@@ -1944,10 +1659,7 @@ const getItemTheme = (
dataTypeSet: Set,
dataTypeField: string,
dataType: string,
- itemTheme:
- | NodeThemeSpecifications
- | EdgeThemeSpecifications
- | ComboThemeSpecifications,
+ itemTheme: NodeThemeSpecifications | EdgeThemeSpecifications | ComboThemeSpecifications,
): {
styles: NodeStyleSet | EdgeStyleSet;
lodLevels?: LodLevelRanges;
@@ -1956,9 +1668,7 @@ const getItemTheme = (
const formattedLodLevels = formatLodLevels(lodLevels);
if (!dataTypeField) {
// dataType field is not assigned
- const styles = isArray(themeStyles)
- ? themeStyles[0]
- : Object.values(themeStyles)[0];
+ const styles = isArray(themeStyles) ? themeStyles[0] : Object.values(themeStyles)[0];
return { styles, lodLevels: formattedLodLevels };
}
dataTypeSet.add(dataType as string);
@@ -1968,9 +1678,7 @@ const getItemTheme = (
const idx = Array.from(dataTypeSet).indexOf(dataType);
themeStyle = themeStyles[idx % themeStylesLength];
} else if (isObject(themeStyles)) {
- themeStyle =
- themeStyles[dataType] ||
- (themeStyles as { [dataTypeValue: string]: NodeStyleSet }).others;
+ themeStyle = themeStyles[dataType] || (themeStyles as { [dataTypeValue: string]: NodeStyleSet }).others;
}
return {
styles: themeStyle,
diff --git a/packages/g6/src/runtime/controller/layout.ts b/packages/g6/src/runtime/controller/layout.ts
index 2d3d51f6d24..fb4b9b44a10 100644
--- a/packages/g6/src/runtime/controller/layout.ts
+++ b/packages/g6/src/runtime/controller/layout.ts
@@ -1,29 +1,17 @@
import { Animation, DisplayObject, IAnimationEffectTiming } from '@antv/g';
import { Graph as GraphLib, ID } from '@antv/graphlib';
-import {
- isLayoutWithIterations,
- Layout,
- LayoutMapping,
- OutNode,
- Supervisor,
-} from '@antv/layout';
+import { Layout, LayoutMapping, OutNode, Supervisor, isLayoutWithIterations } from '@antv/layout';
import { Extensions, registry, stdLib } from '../../stdlib';
import {
IGraph,
- isImmediatelyInvokedLayoutOptions,
- isLayoutWorkerized,
LayoutOptions,
NodeModelData,
+ isImmediatelyInvokedLayoutOptions,
+ isLayoutWorkerized,
} from '../../types';
import { GraphCore } from '../../types/data';
import { EdgeModelData } from '../../types/edge';
-import {
- getNodeSizeFn,
- isComboLayout,
- layoutOneTree,
- radialLayout,
- isTreeLayout,
-} from '../../util/layout';
+import { getNodeSizeFn, isComboLayout, isTreeLayout, layoutOneTree, radialLayout } from '../../util/layout';
/**
* Manages layout extensions and graph layout.
@@ -53,11 +41,7 @@ export class LayoutController {
this.graph.hooks.destroy.tap(this.onDestroy.bind(this));
}
- private async onLayout(params: {
- graphCore: GraphCore;
- options: LayoutOptions;
- animate?: boolean;
- }) {
+ private async onLayout(params: { graphCore: GraphCore; options: LayoutOptions; animate?: boolean }) {
/**
* The final calculated result.
*/
@@ -69,24 +53,15 @@ export class LayoutController {
const { graphCore, options, animate = true } = params;
let layoutNodes = graphCore.getAllNodes();
if (!isComboLayout(options)) {
- layoutNodes = layoutNodes.filter(
- (node) => this.graph.getItemVisible(node.id) && !node.data._isCombo,
- );
+ layoutNodes = layoutNodes.filter((node) => this.graph.getItemVisible(node.id) && !node.data._isCombo);
}
const layoutNodesIdMap = {};
layoutNodes.forEach((node) => (layoutNodesIdMap[node.id] = true));
const layoutData = {
nodes: layoutNodes,
- edges: graphCore
- .getAllEdges()
- .filter(
- (edge) =>
- layoutNodesIdMap[edge.source] && layoutNodesIdMap[edge.target],
- ),
+ edges: graphCore.getAllEdges().filter((edge) => layoutNodesIdMap[edge.source] && layoutNodesIdMap[edge.target]),
};
- const layoutGraphCore = new GraphLib(
- layoutData,
- );
+ const layoutGraphCore = new GraphLib(layoutData);
if (graphCore.hasTreeStructure('combo')) {
layoutGraphCore.attachTreeStructure('combo');
layoutNodes.forEach((node) => {
@@ -138,9 +113,7 @@ export class LayoutController {
const presetNode = { x, y, z };
const otherProps = this.previousNodes?.get(node.id) || {};
['_order', 'layer'].forEach((field) => {
- presetNode[field] = node.data.hasOwnProperty(field)
- ? node.data[field]
- : otherProps[field];
+ presetNode[field] = field in node.data ? node.data[field] : otherProps[field];
});
return {
id: node.id,
@@ -154,10 +127,7 @@ export class LayoutController {
});
if (animated) {
- await this.animateLayoutWithoutIterations(
- positions,
- animationEffectTiming,
- );
+ await this.animateLayoutWithoutIterations(positions, animationEffectTiming);
}
} else {
const { presetLayout } = options;
@@ -259,9 +229,7 @@ export class LayoutController {
const presetNode = { x, y, z };
const otherProps = this.previousNodes?.get(node.id) || {};
['_order', 'layer'].forEach((field) => {
- presetNode[field] = node.data.hasOwnProperty(field)
- ? node.data[field]
- : otherProps[field];
+ presetNode[field] = field in node.data ? node.data[field] : otherProps[field];
});
return {
id: node.id,
@@ -319,26 +287,14 @@ export class LayoutController {
positions = await layout.execute(layoutGraphCore);
if (animated) {
- await this.animateLayoutWithoutIterations(
- positions,
- animationEffectTiming,
- );
+ await this.animateLayoutWithoutIterations(positions, animationEffectTiming);
}
}
}
return positions;
};
- private presetLayout = async (
- layoutData,
- nodeSize,
- width,
- height,
- center,
- presetLayout,
- params,
- layoutGraphCore,
- ) => {
+ private presetLayout = async (layoutData, nodeSize, width, height, center, presetLayout, params, layoutGraphCore) => {
// presetLayout has higher priority than the positions in data
if (presetLayout?.type) {
const presetPositions = await this.layoutOnce(
@@ -392,14 +348,7 @@ export class LayoutController {
return nodeWithPostions;
};
- async handleTreeLayout(
- type,
- options,
- animationEffectTiming,
- graphCore,
- layoutData,
- animate,
- ) {
+ async handleTreeLayout(type, options, animationEffectTiming, graphCore, layoutData, animate) {
const { animated = false, rootIds = [], begin = [0, 0], radial } = options;
const nodePositions = [];
const nodeMap = new Map();
@@ -433,15 +382,9 @@ export class LayoutController {
}
});
if (animated) {
- await this.animateLayoutWithoutIterations(
- { nodes: nodePositions, edges: [] },
- animationEffectTiming,
- );
+ await this.animateLayoutWithoutIterations({ nodes: nodePositions, edges: [] }, animationEffectTiming);
}
- this.updateNodesPosition(
- { nodes: nodePositions, edges: [] },
- animated || animate,
- );
+ this.updateNodesPosition({ nodes: nodePositions, edges: [] }, animated || animate);
return;
}
@@ -474,11 +417,7 @@ export class LayoutController {
}
}
- private updateNodesPosition(
- positions: LayoutMapping,
- animate = true,
- cache = true,
- ) {
+ private updateNodesPosition(positions: LayoutMapping, animate = true, cache = true) {
if (!positions) return;
const { nodes, edges } = positions;
if (cache) this.previousNodes = new Map();
@@ -549,21 +488,18 @@ export class LayoutController {
// @see https://g.antv.antgroup.com/api/animation/waapi#%E5%B1%9E%E6%80%A7
this.currentAnimation.onframe = (e) => {
// @see https://g.antv.antgroup.com/api/animation/waapi#progress
- const progress = (e.target as Animation).effect.getComputedTiming()
- .progress as number;
- const interpolatedNodesPosition = (initialPositions as OutNode[]).map(
- ({ id, data }, i) => {
- const { x: fromX = 0, y: fromY = 0 } = data;
- const { x: toX, y: toY } = positions.nodes[i].data;
- return {
- id,
- data: {
- x: fromX + (toX - fromX) * progress,
- y: fromY + (toY - fromY) * progress,
- },
- };
- },
- );
+ const progress = (e.target as Animation).effect.getComputedTiming().progress as number;
+ const interpolatedNodesPosition = (initialPositions as OutNode[]).map(({ id, data }, i) => {
+ const { x: fromX = 0, y: fromY = 0 } = data;
+ const { x: toX, y: toY } = positions.nodes[i].data;
+ return {
+ id,
+ data: {
+ x: fromX + (toX - fromX) * progress,
+ y: fromY + (toY - fromY) * progress,
+ },
+ };
+ });
this.updateNodesPosition({
nodes: interpolatedNodesPosition,
diff --git a/packages/g6/src/runtime/controller/plugin.ts b/packages/g6/src/runtime/controller/plugin.ts
index 7357ebee33d..57057c59b07 100644
--- a/packages/g6/src/runtime/controller/plugin.ts
+++ b/packages/g6/src/runtime/controller/plugin.ts
@@ -1,10 +1,10 @@
import { uniqueId } from '@antv/util';
import registry from '../../stdlib';
+import { LodController } from '../../stdlib/plugin';
import { IGraph } from '../../types';
-import { getExtension } from '../../util/extension';
-import { Plugin as PluginBase } from '../../types/plugin';
import { IG6GraphEvent } from '../../types/event';
-import { LodController } from '../../stdlib/plugin';
+import { Plugin as PluginBase } from '../../types/plugin';
+import { getExtension } from '../../util/extension';
type Listener = (event: IG6GraphEvent) => void;
@@ -18,20 +18,17 @@ const REQUIRED_PLUGINS = [
/**
* Wraps the listener with error logging.
+ * @param type
+ * @param eventName
+ * @param listener
* @returns a new listener with error logging.
*/
-const wrapListener = (
- type: string,
- eventName: string,
- listener: Listener,
-): Listener => {
+const wrapListener = (type: string, eventName: string, listener: Listener): Listener => {
return (event: any) => {
try {
listener(event);
} catch (error) {
- console.error(
- `G6: Error occurred in "${eventName}" phase of the plugin "${type}"!`,
- );
+ console.error(`G6: Error occurred in "${eventName}" phase of the plugin "${type}"!`);
throw error;
}
};
@@ -49,8 +46,7 @@ export class PluginController {
* @example
* { 'minimap': Minimap, 'tooltip': Tooltip }
*/
- private pluginMap: Map =
- new Map();
+ private pluginMap: Map = new Map();
/**
* Listeners added by all current plugins.
@@ -121,14 +117,9 @@ export class PluginController {
const options = typeof config === 'string' ? {} : config;
const type = typeof config === 'string' ? config : config.type;
- const key =
- typeof config === 'string'
- ? config
- : config.key || config.options?.key || type;
+ const key = typeof config === 'string' ? config : config.key || config.options?.key || type;
if (!Plugin) {
- throw new Error(
- `Plugin ${type} not found, please make sure you have registered it first`,
- );
+ throw new Error(`Plugin ${type} not found, please make sure you have registered it first`);
}
const plugin = new Plugin({ ...options, key });
plugin.init(graph);
@@ -237,27 +228,16 @@ export class PluginController {
return plugin;
}
- private addListeners = (
- key: string,
- plugin: PluginBase,
- initWithGraph: boolean = true,
- ) => {
+ private addListeners = (key: string, plugin: PluginBase, initWithGraph: boolean = true) => {
const events = plugin.getEvents();
this.listenersMap[key] = {};
Object.keys(events).forEach((eventName) => {
// Wrap the listener with error logging.
- const listener = wrapListener(
- key,
- eventName,
- events[eventName].bind(plugin),
- );
+ const listener = wrapListener(key, eventName, events[eventName].bind(plugin));
this.graph.on(eventName, listener);
this.listenersMap[key][eventName] = listener;
// The plugin is not initiated with graph, some events are not listened, trigger them manually
- if (
- !initWithGraph &&
- ['afterrender', 'afterlayout'].includes(eventName)
- ) {
+ if (!initWithGraph && ['afterrender', 'afterlayout'].includes(eventName)) {
listener({} as IG6GraphEvent);
}
});
diff --git a/packages/g6/src/runtime/controller/theme.ts b/packages/g6/src/runtime/controller/theme.ts
index a21c00bbacc..8f8ae56569d 100644
--- a/packages/g6/src/runtime/controller/theme.ts
+++ b/packages/g6/src/runtime/controller/theme.ts
@@ -38,9 +38,7 @@ export class ThemeController {
private getExtension() {
const { theme = {} } = this.graph.getSpecification();
this.themeConfig = theme;
- return theme
- ? getExtension(theme, registry.useLib, 'themeSolver')
- : undefined;
+ return theme ? getExtension(theme, registry.useLib, 'themeSolver') : undefined;
}
private getThemes() {
@@ -49,6 +47,8 @@ export class ThemeController {
/**
* Graph init listener, create theme solver and generate theme
+ * @param root0
+ * @param root0.canvases
*/
private onInit({ canvases }) {
if (this.extension) {
diff --git a/packages/g6/src/runtime/controller/viewport.ts b/packages/g6/src/runtime/controller/viewport.ts
index 81747b3122b..a95c4332430 100644
--- a/packages/g6/src/runtime/controller/viewport.ts
+++ b/packages/g6/src/runtime/controller/viewport.ts
@@ -1,6 +1,4 @@
-import { ICamera, PointLike } from '@antv/g';
import { IGraph } from '../../types';
-import { CameraAnimationOptions } from '../../types/animate';
import { ViewportChangeHookParams } from '../../types/hook';
let landmarkCounter = 0;
@@ -20,10 +18,7 @@ export class ViewportController {
this.graph.hooks.viewportchange.tap(this.onViewportChange.bind(this));
}
- private async onViewportChange({
- transform,
- effectTiming,
- }: ViewportChangeHookParams) {
+ private async onViewportChange({ transform, effectTiming }: ViewportChangeHookParams) {
const camera = this.graph.canvas.getCamera();
const transientCamera = this.graph.transientCanvas.getCamera();
// @ts-ignore
@@ -32,21 +27,12 @@ export class ViewportController {
transientCamera.cancelLandmarkAnimation();
this.graph.emit('cancelviewportanimation');
}
- const {
- translate,
- rotate,
- zoom,
- origin = this.graph.getViewportCenter(),
- } = transform;
+ const { translate, rotate, zoom, origin = this.graph.getViewportCenter() } = transform;
const currentZoom = camera.getZoom();
if (effectTiming) {
this.graph.emit('beforeviewportanimation', transform);
- const {
- duration = 1000,
- easing = 'linear',
- easingFunction,
- } = effectTiming;
+ const { duration = 1000, easing = 'linear', easingFunction } = effectTiming;
const landmarkOptions: Partial<{
position: [number, number] | [number, number, number] | Float32Array;
focalPoint: [number, number] | [number, number, number] | Float32Array;
@@ -72,16 +58,8 @@ export class ViewportController {
animateTargetPosition[2] = pz - dz;
animateTargetFocal[2] = fz - dz;
}
- landmarkOptions.position = animateTargetPosition as [
- number,
- number,
- number,
- ];
- landmarkOptions.focalPoint = animateTargetFocal as [
- number,
- number,
- number,
- ];
+ landmarkOptions.position = animateTargetPosition as [number, number, number];
+ landmarkOptions.focalPoint = animateTargetFocal as [number, number, number];
}
if (zoom) {
@@ -94,14 +72,8 @@ export class ViewportController {
landmarkOptions.roll = camera.getRoll() + angle;
}
- const landmark = camera.createLandmark(
- `mark${landmarkCounter++}`,
- landmarkOptions,
- );
- const transientLandmark = transientCamera.createLandmark(
- `mark${landmarkCounter}`,
- landmarkOptions,
- );
+ const landmark = camera.createLandmark(`mark${landmarkCounter++}`, landmarkOptions);
+ const transientLandmark = transientCamera.createLandmark(`mark${landmarkCounter}`, landmarkOptions);
return new Promise((resolve) => {
transientCamera.gotoLandmark(transientLandmark, {
@@ -145,14 +117,8 @@ export class ViewportController {
if (zoom) {
const { ratio } = zoom;
- camera.setZoomByViewportPoint(currentZoom * ratio, [
- origin.x,
- origin.y,
- ]);
- transientCamera.setZoomByViewportPoint(currentZoom * ratio, [
- origin.x,
- origin.y,
- ]);
+ camera.setZoomByViewportPoint(currentZoom * ratio, [origin.x, origin.y]);
+ transientCamera.setZoomByViewportPoint(currentZoom * ratio, [origin.x, origin.y]);
}
}
}
diff --git a/packages/g6/src/runtime/graph.ts b/packages/g6/src/runtime/graph.ts
index 8619bf3594d..c7bd03f7d71 100644
--- a/packages/g6/src/runtime/graph.ts
+++ b/packages/g6/src/runtime/graph.ts
@@ -1,96 +1,45 @@
import EventEmitter from '@antv/event-emitter';
-import {
- AABB,
- Canvas,
- Cursor,
- DataURLType,
- DisplayObject,
- PointLike,
- Rect,
-} from '@antv/g';
+import { AABB, Canvas, Cursor, DataURLType, DisplayObject, PointLike, Rect } from '@antv/g';
import { GraphChange, ID } from '@antv/graphlib';
-import {
- clone,
- groupBy,
- isArray,
- isEmpty,
- isEqual,
- isNil,
- isNumber,
- isObject,
- isString,
- map,
-} from '@antv/util';
+import { clone, groupBy, isArray, isEmpty, isEqual, isNil, isNumber, isObject, isString, map } from '@antv/util';
+import Node from '../item/node';
import { History } from '../stdlib/plugin/history';
import { Command } from '../stdlib/plugin/history/command';
-import type {
- ComboUserModel,
- EdgeUserModel,
- GraphData,
- IGraph,
- NodeUserModel,
- Specification,
-} from '../types';
+import type { ComboUserModel, EdgeUserModel, GraphData, IGraph, NodeUserModel, Specification } from '../types';
import type { CameraAnimationOptions } from '../types/animate';
import type { BehaviorOptionsOf, BehaviorRegistry } from '../types/behavior';
-import type {
- ComboDisplayModel,
- ComboModel,
- ComboShapesEncode,
-} from '../types/combo';
+import type { ComboDisplayModel, ComboModel, ComboShapesEncode } from '../types/combo';
import type { Bounds, Padding, Point } from '../types/common';
import type { DataChangeType, DataConfig, GraphCore } from '../types/data';
-import type {
- EdgeDisplayModel,
- EdgeModel,
- EdgeModelData,
- EdgeShapesEncode,
-} from '../types/edge';
+import type { EdgeDisplayModel, EdgeModel, EdgeModelData, EdgeShapesEncode } from '../types/edge';
import type { StackType } from '../types/history';
import type { Hooks, ViewportChangeHookParams } from '../types/hook';
import type { ITEM_TYPE, SHAPE_TYPE, ShapeStyle } from '../types/item';
-import type {
- ImmediatelyInvokedLayoutOptions,
- LayoutOptions,
- StandardLayoutOptions,
-} from '../types/layout';
-import type {
- NodeDisplayModel,
- NodeModel,
- NodeModelData,
- NodeShapesEncode,
-} from '../types/node';
+import type { ImmediatelyInvokedLayoutOptions, LayoutOptions, StandardLayoutOptions } from '../types/layout';
+import type { NodeDisplayModel, NodeModel, NodeModelData, NodeShapesEncode } from '../types/node';
import { Plugin as PluginBase } from '../types/plugin';
import type { RendererName } from '../types/render';
import { ComboMapper, EdgeMapper, NodeMapper } from '../types/spec';
-import type {
- ThemeOptionsOf,
- ThemeRegistry,
- ThemeSpecification,
-} from '../types/theme';
+import type { ThemeOptionsOf, ThemeRegistry, ThemeSpecification } from '../types/theme';
import { FitViewRules, GraphTransformOptions } from '../types/view';
+import { getCombinedCanvasesBounds } from '../util/bbox';
import { changeRenderer, createCanvas } from '../util/canvas';
+import { cloneJSON, isEmptyGraph } from '../util/data';
import { createDOM } from '../util/dom';
import { getLayoutBounds } from '../util/layout';
import { formatPadding } from '../util/shape';
-import Node from '../item/node';
-import { cloneJSON, isEmptyGraph } from '../util/data';
-import { getCombinedCanvasesBounds } from '../util/bbox';
import {
DataController,
InteractionController,
ItemController,
LayoutController,
+ PluginController,
ThemeController,
ViewportController,
- PluginController,
} from './controller';
import Hook from './hooks';
-export class Graph
- extends EventEmitter
- implements IGraph
-{
+export class Graph extends EventEmitter implements IGraph {
public hooks: Hooks;
// for nodes and edges excluding their labels, which will be separate into groups
public canvas: Canvas;
@@ -131,11 +80,7 @@ export class Graph
constructor(spec: Specification) {
super();
- this.specification = Object.assign(
- {},
- this.defaultSpecification,
- this.formatSpecification(spec),
- );
+ this.specification = Object.assign({}, this.defaultSpecification, this.formatSpecification(spec));
this.initHooks();
this.initCanvas();
this.initControllers();
@@ -193,28 +138,18 @@ export class Graph
: (container as HTMLElement);
if (!containerDOM) {
- console.error(
- `Create graph failed. The container for graph ${containerDOM} is not exist.`,
- );
+ console.error(`Create graph failed. The container for graph ${containerDOM} is not exist.`);
this.destroy();
return;
}
this.container = containerDOM;
}
- [
- 'backgroundCanvas',
- 'canvas',
- 'labelCanvas',
- 'transientCanvas',
- 'transientLabelCanvas',
- ].forEach((name) => {
+ ['backgroundCanvas', 'canvas', 'labelCanvas', 'transientCanvas', 'transientLabelCanvas'].forEach((name) => {
this[name] =
this.specification[name] ||
createCanvas(
- ['labelCanvas', 'transientLabelCanvas'].includes(name)
- ? 'canvas'
- : this.rendererType,
+ ['labelCanvas', 'transientLabelCanvas'].includes(name) ? 'canvas' : this.rendererType,
this.container,
width ?? this.container.scrollWidth,
height ?? this.container.scrollHeight,
@@ -226,35 +161,25 @@ export class Graph
});
Promise.all(
- [
- this.backgroundCanvas,
- this.canvas,
- this.labelCanvas,
- this.transientCanvas,
- this.transientLabelCanvas,
- ].map((canvas) => canvas.ready),
+ [this.backgroundCanvas, this.canvas, this.labelCanvas, this.transientCanvas, this.transientLabelCanvas].map(
+ (canvas) => canvas.ready,
+ ),
).then(() => {
- [
- this.backgroundCanvas,
- this.canvas,
- this.labelCanvas,
- this.transientCanvas,
- this.transientLabelCanvas,
- ].forEach((canvas, i) => {
- const $domElement = canvas
- .getContextService()
- .getDomElement() as unknown as HTMLElement;
- if ($domElement && $domElement.style) {
- // Make all these 3 canvas doms overlap each other. The container already has `position: relative` style.
- $domElement.style.position = 'absolute';
- $domElement.style.outline = 'none';
- $domElement.tabIndex = 1; // Enable keyboard events
- // Transient canvas should let interactive events go through.
- if (i !== 1) {
- $domElement.style.pointerEvents = 'none';
+ [this.backgroundCanvas, this.canvas, this.labelCanvas, this.transientCanvas, this.transientLabelCanvas].forEach(
+ (canvas, i) => {
+ const $domElement = canvas.getContextService().getDomElement() as unknown as HTMLElement;
+ if ($domElement && $domElement.style) {
+ // Make all these 3 canvas doms overlap each other. The container already has `position: relative` style.
+ $domElement.style.position = 'absolute';
+ $domElement.style.outline = 'none';
+ $domElement.tabIndex = 1; // Enable keyboard events
+ // Transient canvas should let interactive events go through.
+ if (i !== 1) {
+ $domElement.style.pointerEvents = 'none';
+ }
}
- }
- });
+ },
+ );
this.canvasReady = true;
});
@@ -279,7 +204,6 @@ export class Graph
/**
* Change the renderer at runtime.
* @param type renderer name
- * @returns
*/
public changeRenderer(type) {
this.rendererType = type || 'canvas';
@@ -342,19 +266,13 @@ export class Graph
itemType: ITEM_TYPE;
stateConfig:
| {
- [stateName: string]:
- | ((data: NodeModel) => NodeDisplayModel)
- | NodeShapesEncode;
+ [stateName: string]: ((data: NodeModel) => NodeDisplayModel) | NodeShapesEncode;
}
| {
- [stateName: string]:
- | ((data: EdgeModel) => EdgeDisplayModel)
- | EdgeShapesEncode;
+ [stateName: string]: ((data: EdgeModel) => EdgeDisplayModel) | EdgeShapesEncode;
}
| {
- [stateName: string]:
- | ((data: ComboModel) => ComboDisplayModel)
- | ComboShapesEncode;
+ [stateName: string]: ((data: ComboModel) => ComboDisplayModel) | ComboShapesEncode;
};
}>({
name: 'itemstateconfigchange',
@@ -381,10 +299,7 @@ export class Graph
}>({ name: 'transientupdate' }),
pluginchange: new Hook<{
action: 'update' | 'add' | 'remove';
- plugins: (
- | string
- | { key: string; type: string; [cfgName: string]: unknown }
- )[];
+ plugins: (string | { key: string; type: string; [cfgName: string]: unknown })[];
}>({ name: 'pluginchange' }),
themechange: new Hook<{
theme: ThemeSpecification;
@@ -425,18 +340,10 @@ export class Graph
/**
* Update the specs(configurations).
+ * @param spec
*/
public updateSpecification(spec: Specification): Specification {
- const {
- node,
- edge,
- combo,
- theme,
- nodeState,
- edgeState,
- comboState,
- ...others
- } = spec;
+ const { node, edge, combo, theme, nodeState, edgeState, comboState, ...others } = spec;
if (node) this.updateMapper('node', node);
if (edge) this.updateMapper('edge', edge);
if (combo) this.updateMapper('combo', combo);
@@ -445,14 +352,12 @@ export class Graph
if (edgeState) this.updateStateConfig('edge', edgeState, 'replace');
if (comboState) this.updateStateConfig('combo', comboState, 'replace');
- const newSpec = Object.assign(
- this.specification,
- this.formatSpecification(others),
- );
+ const newSpec = Object.assign(this.specification, this.formatSpecification(others));
return newSpec;
}
/**
* Update the theme specs (configurations).
+ * @param theme
*/
public updateTheme(theme: ThemeOptionsOf) {
this.specification.theme = theme;
@@ -475,11 +380,8 @@ export class Graph
* Update the item display mapper for a specific item type.
* @param {ITEM_TYPE} type - The type of item (node, edge, or combo).
* @param {NodeMapper | EdgeMapper | ComboMapper} mapper - The mapper to be updated.
- * */
- public updateMapper(
- type: ITEM_TYPE,
- mapper: NodeMapper | EdgeMapper | ComboMapper,
- ) {
+ */
+ public updateMapper(type: ITEM_TYPE, mapper: NodeMapper | EdgeMapper | ComboMapper) {
switch (type) {
case 'node':
this.specification.node = mapper as NodeMapper;
@@ -502,24 +404,18 @@ export class Graph
* @param {string} itemType - The type of item (node, edge, or combo).
* @param {object} stateConfig - The state configuration to update.
* @param {string} updateType - The type of update ('mergeReplace' or 'replace'). Default is 'mergeReplace'.
- **/
+ */
public updateStateConfig(
itemType: ITEM_TYPE,
stateConfig:
| {
- [stateName: string]:
- | ((data: NodeModel) => NodeDisplayModel)
- | NodeShapesEncode;
+ [stateName: string]: ((data: NodeModel) => NodeDisplayModel) | NodeShapesEncode;
}
| {
- [stateName: string]:
- | ((data: EdgeModel) => EdgeDisplayModel)
- | EdgeShapesEncode;
+ [stateName: string]: ((data: EdgeModel) => EdgeDisplayModel) | EdgeShapesEncode;
}
| {
- [stateName: string]:
- | ((data: ComboModel) => ComboDisplayModel)
- | ComboShapesEncode;
+ [stateName: string]: ((data: ComboModel) => ComboDisplayModel) | ComboShapesEncode;
},
updateType: 'mergeReplace' | 'replace' = 'mergeReplace',
) {
@@ -550,12 +446,10 @@ export class Graph
* Input data and render the graph.
* If there is old data, diffs and changes it.
* @param data
- * @returns
* @group Data
*/
public async read(data: DataConfig) {
- const { tileFirstRender, tileFirstRenderSize } =
- this.specification.optimize || {};
+ const { tileFirstRender, tileFirstRenderSize } = this.specification.optimize || {};
this.hooks.datachange.emit({ data, type: 'replace' });
const emitRender = async () => {
await this.hooks.render.emitLinearAsync({
@@ -608,13 +502,9 @@ export class Graph
await emitRender();
} else {
await Promise.all(
- [
- this.backgroundCanvas,
- this.canvas,
- this.labelCanvas,
- this.transientCanvas,
- this.transientLabelCanvas,
- ].map((canvas) => canvas.ready),
+ [this.backgroundCanvas, this.canvas, this.labelCanvas, this.transientCanvas, this.transientLabelCanvas].map(
+ (canvas) => canvas.ready,
+ ),
);
await emitRender();
}
@@ -625,7 +515,6 @@ export class Graph
* @param data new data
* @param type the way to change data, 'replace' means discard the old data and use the new one; 'mergeReplace' means merge the common part, remove (old - new), add (new - old)
* @param relayout whether relayout the nodes after data changing
- * @returns
* @group Data
*/
public async changeData(
@@ -633,8 +522,7 @@ export class Graph
type: 'replace' | 'mergeReplace' = 'mergeReplace',
relayout: boolean = true,
) {
- const { tileFirstRender, tileFirstRenderSize } =
- this.specification.optimize || {};
+ const { tileFirstRender, tileFirstRenderSize } = this.specification.optimize || {};
this.hooks.datachange.emit({ data, type });
this.hooks.render.emit({
graphCore: this.dataController.graphCore,
@@ -655,7 +543,6 @@ export class Graph
/**
* Clear the graph, means remove all the items on the graph.
- * @returns
*/
public clear() {
this.startHistoryBatch();
@@ -678,10 +565,7 @@ export class Graph
const { width, height } = this.canvas.getConfig();
return { x: width! / 2, y: height! / 2 };
}
- public async transform(
- options: GraphTransformOptions,
- effectTiming?: CameraAnimationOptions,
- ): Promise {
+ public async transform(options: GraphTransformOptions, effectTiming?: CameraAnimationOptions): Promise {
if (isEmptyGraph(this, true)) return;
const { tileLodSize } = this.specification.optimize || {};
await this.hooks.viewportchange.emitLinearAsync({
@@ -703,6 +587,7 @@ export class Graph
* Move the graph with a relative distance under viewport coordinates.
* @param dx x of the relative distance
* @param dy y of the relative distance
+ * @param distance
* @param effectTiming animation configurations
*/
public async translate(
@@ -732,12 +617,11 @@ export class Graph
/**
* Move the graph to destination under viewport coordinates.
* @param destination destination under viewport coordinates.
+ * @param destination.x
+ * @param destination.y
* @param effectTiming animation configurations
*/
- public async translateTo(
- { x, y }: Point,
- effectTiming?: CameraAnimationOptions,
- ) {
+ public async translateTo({ x, y }: Point, effectTiming?: CameraAnimationOptions) {
const { x: cx, y: cy } = this.getViewportCenter();
const canvasPoint = this.canvas.viewport2Canvas({ x, y });
@@ -760,11 +644,7 @@ export class Graph
* @param origin origin under viewport coordinates.
* @param effectTiming animation configurations
*/
- public async zoom(
- ratio: number,
- origin?: Point,
- effectTiming?: CameraAnimationOptions,
- ) {
+ public async zoom(ratio: number, origin?: Point, effectTiming?: CameraAnimationOptions) {
await this.transform(
{
zoom: {
@@ -782,16 +662,8 @@ export class Graph
* @param origin zoom center
* @param effectTiming animation configurations
*/
- public async zoomTo(
- zoom: number,
- origin?: PointLike,
- effectTiming?: CameraAnimationOptions,
- ) {
- await this.zoom(
- zoom / this.canvas.getCamera().getZoom(),
- origin,
- effectTiming,
- );
+ public async zoomTo(zoom: number, origin?: PointLike, effectTiming?: CameraAnimationOptions) {
+ await this.zoom(zoom / this.canvas.getCamera().getZoom(), origin, effectTiming);
}
/**
@@ -808,11 +680,7 @@ export class Graph
* @param origin
* @param effectTiming
*/
- public async rotate(
- angle: number,
- origin?: PointLike,
- effectTiming?: CameraAnimationOptions,
- ) {
+ public async rotate(angle: number, origin?: PointLike, effectTiming?: CameraAnimationOptions) {
await this.transform(
{
rotate: {
@@ -830,22 +698,15 @@ export class Graph
* @param origin
* @param effectTiming
*/
- public async rotateTo(
- angle: number,
- origin?: PointLike,
- effectTiming?: CameraAnimationOptions,
- ) {
- await this.rotate(
- angle - this.canvas.getCamera().getRoll(),
- origin,
- effectTiming,
- );
+ public async rotateTo(angle: number, origin?: PointLike, effectTiming?: CameraAnimationOptions) {
+ await this.rotate(angle - this.canvas.getCamera().getRoll(), origin, effectTiming);
}
/**
* Fit the graph content to the view.
* @param options.padding padding while fitting
* @param options.rules rules for fitting
+ * @param options
* @param effectTiming animation configurations
*/
public async fitView(
@@ -856,9 +717,7 @@ export class Graph
effectTiming?: CameraAnimationOptions,
) {
const { padding, rules } = options || {};
- const [top, right, bottom, left] = padding
- ? formatPadding(padding)
- : [0, 0, 0, 0];
+ const [top, right, bottom, left] = padding ? formatPadding(padding) : [0, 0, 0, 0];
const {
direction = 'both',
ratioRule = 'min',
@@ -881,8 +740,7 @@ export class Graph
x: graphCenterX,
y: graphCenterY,
});
- const { width: viewportWidth, height: viewportHeight } =
- this.canvas.getConfig();
+ const { width: viewportWidth, height: viewportHeight } = this.canvas.getConfig();
const graphWidth = halfExtents[0] * 2;
const graphHeight = halfExtents[1] * 2;
@@ -893,10 +751,7 @@ export class Graph
});
const isOutOfView =
- min[0] < tlInCanvas.x ||
- min[1] < tlInCanvas.y ||
- max[0] > brInCanvas.x ||
- max[1] > brInCanvas.y;
+ min[0] < tlInCanvas.x || min[1] < tlInCanvas.y || max[0] > brInCanvas.x || max[1] > brInCanvas.y;
if (onlyOutOfViewport && !isOutOfView) return;
const targetViewWidth = brInCanvas.x - tlInCanvas.x;
@@ -911,10 +766,7 @@ export class Graph
} else if (direction === 'y') {
ratio = hRatio;
} else {
- ratio =
- ratioRule === 'max'
- ? Math.max(wRatio, hRatio)
- : Math.min(wRatio, hRatio);
+ ratio = ratioRule === 'max' ? Math.max(wRatio, hRatio) : Math.min(wRatio, hRatio);
}
if (onlyZoomAtLargerThanViewport && ratio > 1) ratio = 1;
@@ -936,12 +788,10 @@ export class Graph
}
/**
* Fit the graph center to the view center.
+ * @param boundsType
* @param effectTiming animation configurations
*/
- public async fitCenter(
- boundsType: 'render' | 'layout' = 'render',
- effectTiming?: CameraAnimationOptions,
- ) {
+ public async fitCenter(boundsType: 'render' | 'layout' = 'render', effectTiming?: CameraAnimationOptions) {
const {
center: [graphCenterX, graphCenterY],
} =
@@ -950,14 +800,12 @@ export class Graph
getCombinedCanvasesBounds([this.canvas, this.labelCanvas])
: // Get the bounds of the nodes positions while the graph content is not ready.
getLayoutBounds(this);
- await this.translateTo(
- this.canvas.canvas2Viewport({ x: graphCenterX, y: graphCenterY }),
- effectTiming,
- );
+ await this.translateTo(this.canvas.canvas2Viewport({ x: graphCenterX, y: graphCenterY }), effectTiming);
}
/**
* Move the graph to make the item align the view center.
* @param item node/edge/combo item or its id
+ * @param id
* @param effectTiming animation configurations
*/
public async focusItem(id: ID | ID[], effectTiming?: CameraAnimationOptions) {
@@ -978,10 +826,7 @@ export class Graph
const {
center: [itemCenterX, itemCenterY],
} = bounds;
- await this.translateTo(
- this.canvas.canvas2Viewport({ x: itemCenterX, y: itemCenterY }),
- effectTiming,
- );
+ await this.translateTo(this.canvas.canvas2Viewport({ x: itemCenterX, y: itemCenterY }), effectTiming);
}
}
@@ -1007,6 +852,7 @@ export class Graph
/**
* Set the size for the graph canvas.
* @param number[] [width, height]
+ * @param size
* @group View
*/
public setSize(size: number[]) {
@@ -1020,15 +866,11 @@ export class Graph
this.emit('beforesetsize', { oldSize, size: size });
this.specification.width = size[0];
this.specification.height = size[1];
- [
- this.canvas,
- this.labelCanvas,
- this.transientCanvas,
- this.transientLabelCanvas,
- this.backgroundCanvas,
- ].forEach((canvas) => {
- canvas.resize(size[0], size[1]);
- });
+ [this.canvas, this.labelCanvas, this.transientCanvas, this.transientLabelCanvas, this.backgroundCanvas].forEach(
+ (canvas) => {
+ canvas.resize(size[0], size[1]);
+ },
+ );
this.emit('aftersetsize', { oldSize, size: size });
}
@@ -1039,22 +881,15 @@ export class Graph
return {
min: [leftTop.x, leftTop.y, leftTop.z],
max: [rightBottom.x, rightBottom.y, rightBottom.z],
- center: [
- (leftTop.x + rightBottom.x) / 2,
- (leftTop.y + rightBottom.y) / 2,
- (leftTop.z + rightBottom.z) / 2,
- ],
- halfExtents: [
- (rightBottom.x - leftTop.x) / 2,
- (rightBottom.y - leftTop.y) / 2,
- (rightBottom.z - leftTop.z) / 2,
- ],
+ center: [(leftTop.x + rightBottom.x) / 2, (leftTop.y + rightBottom.y) / 2, (leftTop.z + rightBottom.z) / 2],
+ halfExtents: [(rightBottom.x - leftTop.x) / 2, (rightBottom.y - leftTop.y) / 2, (rightBottom.z - leftTop.z) / 2],
};
}
/**
* Get the rendering coordinate according to the canvas dom (viewport) coordinate.
* @param Point rendering coordinate
+ * @param viewportPoint
* @returns canvas dom (viewport) coordinate
* @group View
*/
@@ -1065,6 +900,7 @@ export class Graph
/**
* Get the canvas dom (viewport) coordinate according to the rendering coordinate.
* @param Point canvas dom (viewport) coordinate
+ * @param canvasPoint
* @returns rendering coordinate
* @group View
*/
@@ -1075,6 +911,7 @@ export class Graph
/**
* Get the browser coordinate according to the rendering coordinate.
* @param Point rendering coordinate
+ * @param canvasPoint
* @returns browser coordinate
* @group View
*/
@@ -1086,6 +923,7 @@ export class Graph
/**
* Get the rendering coordinate according to the browser coordinate.
* @param Point browser coordinate
+ * @param clientPoint
* @returns rendering coordinate
* @group View
*/
@@ -1102,8 +940,7 @@ export class Graph
* @group Data
*/
public getNodeData(condition: ID | Function): NodeModel | undefined {
- const conds =
- isString(condition) || isNumber(condition) ? [condition] : condition;
+ const conds = isString(condition) || isNumber(condition) ? [condition] : condition;
return this.dataController.findData('node', conds)?.[0] as NodeModel;
}
/**
@@ -1113,10 +950,7 @@ export class Graph
* @group Data
*/
public getEdgeData(condition: ID | Function): EdgeModel | undefined {
- const conds =
- isString(condition) || isNumber(condition) || isNumber(condition)
- ? [condition]
- : condition;
+ const conds = isString(condition) || isNumber(condition) || isNumber(condition) ? [condition] : condition;
return this.dataController.findData('edge', conds)?.[0] as EdgeModel;
}
/**
@@ -1126,8 +960,7 @@ export class Graph
* @group Data
*/
public getComboData(condition: ID | Function): ComboModel | undefined {
- const conds =
- isString(condition) || isNumber(condition) ? [condition] : condition;
+ const conds = isString(condition) || isNumber(condition) ? [condition] : condition;
return this.dataController.findData('combo', conds)?.[0] as ComboModel;
}
/**
@@ -1157,45 +990,32 @@ export class Graph
/**
* Get one-hop edge ids from a start node.
* @param nodeId id of the start node
+ * @param direction
* @returns one-hop edges' data array
* @group Data
*/
- public getRelatedEdgesData(
- nodeId: ID,
- direction: 'in' | 'out' | 'both' = 'both',
- ): EdgeModel[] {
+ public getRelatedEdgesData(nodeId: ID, direction: 'in' | 'out' | 'both' = 'both'): EdgeModel[] {
return this.dataController.findRelatedEdges(nodeId, direction);
}
/**
* Get nearby edges from a start node using quad-tree collision detection.
* @param nodeId id of the start node
+ * @param shouldBegin
* @returns nearby edges' data array
*/
- public getNearEdgesData(
- nodeId: ID,
- shouldBegin?: (edge: EdgeDisplayModel) => boolean,
- ): EdgeModel[] {
- const transientItem = this.itemController.getTransientItem(
- nodeId,
- ) as unknown as Node;
+ public getNearEdgesData(nodeId: ID, shouldBegin?: (edge: EdgeDisplayModel) => boolean): EdgeModel[] {
+ const transientItem = this.itemController.getTransientItem(nodeId) as unknown as Node;
const itemMap = this.itemController.getItemMap();
- return this.dataController.findNearEdges(
- nodeId,
- itemMap,
- transientItem,
- shouldBegin,
- );
+ return this.dataController.findNearEdges(nodeId, itemMap, transientItem, shouldBegin);
}
/**
* Get one-hop node ids from a start node.
* @param nodeId id of the start node
+ * @param direction
* @returns one-hop nodes' data array
* @group Data
*/
- public getNeighborNodesData(
- nodeId: ID,
- direction: 'in' | 'out' | 'both' = 'both',
- ): NodeModel[] {
+ public getNeighborNodesData(nodeId: ID, direction: 'in' | 'out' | 'both' = 'both'): NodeModel[] {
return this.dataController.findNeighborNodes(nodeId, direction);
}
/**
@@ -1224,9 +1044,7 @@ export class Graph
* @returns display model
* @group Data
*/
- protected getDisplayModel(
- id: ID,
- ): NodeDisplayModel | EdgeDisplayModel | ComboDisplayModel {
+ protected getDisplayModel(id: ID): NodeDisplayModel | EdgeDisplayModel | ComboDisplayModel {
return this.itemController.findDisplayModel(id);
}
@@ -1234,6 +1052,7 @@ export class Graph
* Find items which has the state.
* @param itemType item type
* @param state state name
+ * @param value
* @param additionalFilter additional filter function
* @returns items that is the type and has the state
* @group Item
@@ -1257,25 +1076,14 @@ export class Graph
* Add one or more node/edge/combo data to the graph.
* @param itemType item type
* @param model user data
+ * @param models
* @returns whether success
* @group Data
*/
public addData(
itemType: ITEM_TYPE,
- models:
- | NodeUserModel
- | EdgeUserModel
- | ComboUserModel
- | NodeUserModel[]
- | EdgeUserModel[]
- | ComboUserModel[],
- ):
- | NodeModel
- | EdgeModel
- | ComboModel
- | NodeModel[]
- | EdgeModel[]
- | ComboModel[] {
+ models: NodeUserModel | EdgeUserModel | ComboUserModel | NodeUserModel[] | EdgeUserModel[] | ComboUserModel[],
+ ): NodeModel | EdgeModel | ComboModel | NodeModel[] | EdgeModel[] | ComboModel[] {
// data controller and item controller subscribe additem in order
const { graphCore } = this.dataController;
@@ -1317,8 +1125,7 @@ export class Graph
* Remove one or more node/edge/combo data from the graph.
* @param itemType the type the item(s) to be removed.
* @param id the id or the ids' array of the items to be removed.
- * @returns whether success
- * @group Data
+ * @param ids
*/
public removeData(itemType: ITEM_TYPE, ids: ID | ID[]) {
const idArr = isArray(ids) ? ids : [ids];
@@ -1330,9 +1137,7 @@ export class Graph
data[`${itemType}s`] = idArr
.map((id) => {
if (!hasItem.bind(graphCore)(id)) {
- console.warn(
- `The ${itemType} data with id ${id} does not exist. It will be ignored`,
- );
+ console.warn(`The ${itemType} data with id ${id} does not exist. It will be ignored`);
return;
}
return getItem.bind(graphCore)(id);
@@ -1367,7 +1172,6 @@ export class Graph
* to make sure they both contain the union set of their original fields.
* The missing fields' values are filled using data from displayModel data.
* @param changes
- * @returns
*/
private extendChanges(changes) {
return changes
@@ -1385,24 +1189,16 @@ export class Graph
const commonFields = [...new Set([...oldFields, ...newFields])];
commonFields.forEach((field) => {
- if (!Object.prototype.hasOwnProperty.call(oldValue, field)) {
+ if (!(field in oldValue)) {
oldValue[field] = displayData[field];
}
- if (!Object.prototype.hasOwnProperty.call(newValue, field)) {
+ if (!(field in newValue)) {
newValue[field] = displayData[field];
}
});
- if (
- (oldValue.x === undefined || Number.isNaN(oldValue.x)) &&
- !oldValue._isCombo
- )
- oldValue.x = 0;
- if (
- (oldValue.y === undefined || Number.isNaN(oldValue.x)) &&
- !oldValue._isCombo
- )
- oldValue.y = 0;
+ if ((oldValue.x === undefined || Number.isNaN(oldValue.x)) && !oldValue._isCombo) oldValue.x = 0;
+ if ((oldValue.y === undefined || Number.isNaN(oldValue.x)) && !oldValue._isCombo) oldValue.y = 0;
if (Number.isNaN(newValue.x)) delete newValue.x;
if (Number.isNaN(newValue.y)) delete newValue.y;
@@ -1427,19 +1223,8 @@ export class Graph
models:
| Partial
| Partial
- | Partial<
- | ComboUserModel
- | Partial[]
- | Partial[]
- | Partial[]
- >,
- ):
- | NodeModel
- | EdgeModel
- | ComboModel
- | NodeModel[]
- | EdgeModel[]
- | ComboModel[] {
+ | Partial[] | Partial[] | Partial[]>,
+ ): NodeModel | EdgeModel | ComboModel | NodeModel[] | EdgeModel[] | ComboModel[] {
const modelArr = isArray(models) ? models : [models];
const data = { nodes: [], edges: [], combos: [] };
data[`${itemType}s`] = modelArr;
@@ -1486,25 +1271,12 @@ export class Graph
* @group Data
*/
public updateNodePosition(
- models:
- | Partial
- | Partial<
- ComboUserModel | Partial[] | Partial[]
- >,
+ models: Partial | Partial[] | Partial[]>,
upsertAncestors?: boolean,
disableAnimate = false,
- callback?: (
- model: NodeModel | EdgeModel | ComboModel,
- canceled?: boolean,
- ) => void,
+ callback?: (model: NodeModel | EdgeModel | ComboModel, canceled?: boolean) => void,
) {
- return this.updatePosition(
- 'node',
- models,
- upsertAncestors,
- disableAnimate,
- callback,
- );
+ return this.updatePosition('node', models, upsertAncestors, disableAnimate, callback);
}
/**
@@ -1518,32 +1290,19 @@ export class Graph
* @group Data
*/
public updateComboPosition(
- models:
- | Partial
- | Partial<
- ComboUserModel | Partial[] | Partial[]
- >,
+ models: Partial | Partial[] | Partial[]>,
upsertAncestors?: boolean,
disableAnimate = false,
callback?: (model: NodeModel | EdgeModel | ComboModel) => void,
) {
- return this.updatePosition(
- 'combo',
- models,
- upsertAncestors,
- disableAnimate,
- callback,
- );
+ return this.updatePosition('combo', models, upsertAncestors, disableAnimate, callback);
}
/**
* Get history plugin instance
*/
private getHistoryPlugin(): History {
- if (
- !this.specification.enableStack ||
- !this.pluginController.hasPlugin('history')
- ) {
+ if (!this.specification.enableStack || !this.pluginController.hasPlugin('history')) {
console.error('The history plugin is not loaded or initialized.');
return;
}
@@ -1552,26 +1311,17 @@ export class Graph
private updatePosition(
type: 'node' | 'combo',
- models:
- | Partial
- | Partial<
- ComboUserModel | Partial[] | Partial[]
- >,
+ models: Partial | Partial[] | Partial[]>,
upsertAncestors?: boolean,
disableAnimate = false,
- callback?: (
- model: NodeModel | EdgeModel | ComboModel,
- canceled?: boolean,
- ) => void,
+ callback?: (model: NodeModel | EdgeModel | ComboModel, canceled?: boolean) => void,
) {
const modelArr = isArray(models) ? models : [models];
const { graphCore } = this.dataController;
const { specification } = this.themeController;
graphCore?.once('changed', (event) => {
if (!event.changes.length) return;
- const changes = event.changes.filter(
- (change) => !isEqual(change.newValue, change.oldValue),
- );
+ const changes = event.changes.filter((change) => !isEqual(change.newValue, change.oldValue));
const timingParameters = {
type,
action: 'updatePosition',
@@ -1626,7 +1376,10 @@ export class Graph
/**
* Show the item(s).
* @param item the item to be shown
- * @returns
+ * @param ids
+ * @param options
+ * @param options.disableAnimate
+ * @param options.shapeIds
* @group Item
*/
public showItem(
@@ -1679,10 +1432,15 @@ export class Graph
/**
* Hide the item(s).
* @param id the id for the item to be hidden.
+ * @param ids
+ * @param options
* @param disableAnimate whether disable the hidden animations.
* @param keepKeyShape whether keep the keyShape.
* @param keepRelated whether keep the related nodes for edge.
- * @returns
+ * @param options.disableAnimate
+ * @param options.keepKeyShape
+ * @param options.keepRelated
+ * @param options.shapeIds
* @group Item
*/
public hideItem(
@@ -1694,12 +1452,7 @@ export class Graph
shapeIds?: string[];
},
) {
- const {
- disableAnimate = false,
- keepKeyShape = false,
- keepRelated = false,
- shapeIds,
- } = options || {};
+ const { disableAnimate = false, keepKeyShape = false, keepRelated = false, shapeIds } = options || {};
const idArr: ID[] = isArray(ids) ? ids : [ids];
if (isEmpty(idArr)) return;
@@ -1746,7 +1499,6 @@ export class Graph
/**
* Make the item(s) to the front.
* @param ids
- * @returns
* @group Item
*/
public frontItem(ids: ID | ID[]) {
@@ -1765,7 +1517,6 @@ export class Graph
/**
* Make the item(s) to the back.
* @param ids
- * @returns
* @group Item
*/
public backItem(ids: ID | ID[]) {
@@ -1782,11 +1533,7 @@ export class Graph
});
}
- private getItemPreviousStates(stateOption: {
- ids: ID | ID[];
- states: string | string[];
- value: boolean;
- }) {
+ private getItemPreviousStates(stateOption: { ids: ID | ID[]; states: string | string[]; value: boolean }) {
const { ids, states } = stateOption;
const idArr = Array.isArray(ids) ? ids : [ids];
const stateArr = Array.isArray(states) ? states : [states];
@@ -1803,15 +1550,12 @@ export class Graph
* Set state for the item.
* @param item the item to be set
* @param state the state name
+ * @param ids
+ * @param states
* @param value state value
- * @returns
* @group Item
*/
- public setItemState(
- ids: ID | ID[],
- states: string | string[],
- value: boolean,
- ) {
+ public setItemState(ids: ID | ID[], states: string | string[], value: boolean) {
const idArr = isArray(ids) ? ids : [ids];
if (ids === undefined || !idArr.length) return;
const stateArr = isArray(states) ? states : [states];
@@ -1839,6 +1583,7 @@ export class Graph
* Get the state value for an item.
* @param id the id for the item
* @param states the state name
+ * @param state
* @returns {boolean} the state value
* @group Item
*/
@@ -1860,7 +1605,6 @@ export class Graph
* Clear all the states for item(s).
* @param ids the id(s) for the item(s) to be clear
* @param states the states' names, all the states wil be cleared if states is not assigned
- * @returns
* @group Item
*/
public clearItemState(ids: ID | ID[], states?: string[]) {
@@ -1888,14 +1632,12 @@ export class Graph
/**
* Get the rendering bbox for a node / edge / combo, or the graph (when the id is not assigned).
* @param id the id for the node / edge / combo, undefined for the whole graph
+ * @param onlyKeyShape
+ * @param isTransient
* @returns rendering bounding box. returns false if the item is not exist
* @group Item
*/
- public getRenderBBox(
- id: ID | undefined,
- onlyKeyShape = false,
- isTransient = false,
- ): AABB | false {
+ public getRenderBBox(id: ID | undefined, onlyKeyShape = false, isTransient = false): AABB | false {
if (!id) return this.canvas.getRoot().getRenderBounds();
return this.itemController.getItemBBox(id, onlyKeyShape, isTransient);
}
@@ -1974,6 +1716,7 @@ export class Graph
/**
* Collapse a combo.
* @param comboId combo id or ids' array.
+ * @param comboIds
* @group Combo
*/
public collapseCombo(comboIds: ID | ID[]) {
@@ -1994,6 +1737,7 @@ export class Graph
/**
* Expand a combo.
* @param comboId combo id or ids' array.
+ * @param comboIds
* @group Combo
*/
public expandCombo(comboIds: ID | ID[]) {
@@ -2017,6 +1761,7 @@ export class Graph
* do not update other styles which leads to better performance than updating positions by updateData.
* In fact, it changes the succeed nodes positions to affect the combo's position, but not modify the combo's position directly.
* @param models new configurations with x and y for every combo, which has id field to indicate the specific item.
+ * @param ids
* @param dx the distance alone x-axis to move the combo.
* @param dy the distance alone y-axis to move the combo.
* @param upsertAncestors whether update the ancestors in the combo tree.
@@ -2028,10 +1773,7 @@ export class Graph
dx: number,
dy: number,
upsertAncestors?: boolean,
- callback?: (
- model: NodeModel | EdgeModel | ComboModel,
- canceled?: boolean,
- ) => void,
+ callback?: (model: NodeModel | EdgeModel | ComboModel, canceled?: boolean) => void,
): ComboModel[] {
const idArr = isArray(ids) ? ids : [ids];
const { graphCore } = this.dataController;
@@ -2076,11 +1818,10 @@ export class Graph
// ===== layout =====
/**
* Layout the graph (with current configurations if cfg is not assigned).
+ * @param options
+ * @param disableAnimate
*/
- public async layout(
- options?: Partial,
- disableAnimate = false,
- ) {
+ public async layout(options?: Partial, disableAnimate = false) {
this.emit('beforelayout');
const { graphCore } = this.dataController;
const formattedOptions = {
@@ -2090,9 +1831,7 @@ export class Graph
this.updateSpecification({ layout: formattedOptions });
- const layoutUnset =
- (!options && !this.getSpecification().layout) ||
- !Object.keys(formattedOptions).length;
+ const layoutUnset = (!options && !this.getSpecification().layout) || !Object.keys(formattedOptions).length;
if (layoutUnset) {
const nodes = graphCore.getAllNodes();
if (nodes.every((node) => isNil(node.data.x) && isNil(node.data.y))) {
@@ -2100,9 +1839,7 @@ export class Graph
(formattedOptions as StandardLayoutOptions).type = 'grid';
} else {
// Use user-defined position(x/y default to 0).
- (formattedOptions as ImmediatelyInvokedLayoutOptions).execute = async (
- graph,
- ) => {
+ (formattedOptions as ImmediatelyInvokedLayoutOptions).execute = async (graph) => {
const nodes = graph.getAllNodes();
return {
nodes: nodes.map((node) => ({
@@ -2136,7 +1873,6 @@ export class Graph
/**
*
- * @returns
*/
public getLayoutCurrentAnimation() {
return this.layoutController.getCurrentAnimation();
@@ -2145,7 +1881,6 @@ export class Graph
/**
* Switch mode.
* @param mode mode name
- * @returns
* @group Interaction
*/
public setMode(mode: string) {
@@ -2176,13 +1911,9 @@ export class Graph
* Add behavior(s) to mode(s).
* @param behaviors behavior names or configs
* @param modes mode names
- * @returns
* @group Interaction
*/
- public addBehaviors(
- behaviors: BehaviorOptionsOf | BehaviorOptionsOf[],
- modes: string | string[],
- ) {
+ public addBehaviors(behaviors: BehaviorOptionsOf | BehaviorOptionsOf[], modes: string | string[]) {
const modesArr = isArray(modes) ? modes : [modes];
const behaviorsArr = isArray(behaviors) ? behaviors : [behaviors];
this.hooks.behaviorchange.emit({
@@ -2194,16 +1925,14 @@ export class Graph
});
// update the graph specification
modesArr.forEach((mode) => {
- this.specification.modes[mode] = (
- this.specification.modes[mode] || []
- ).concat(behaviorsArr);
+ this.specification.modes[mode] = (this.specification.modes[mode] || []).concat(behaviorsArr);
});
}
/**
* Remove behavior(s) from mode(s).
* @param behaviors behavior configs with unique key
+ * @param behaviorKeys
* @param modes mode names
- * @returns
* @group Interaction
*/
public removeBehaviors(behaviorKeys: string[], modes: string | string[]) {
@@ -2222,8 +1951,7 @@ export class Graph
const oldBehavior = this.specification.modes[mode].find(
(behavior) => isObject(behavior) && behavior.key === key,
);
- const indexOfOldBehavior =
- this.specification.modes[mode].indexOf(oldBehavior);
+ const indexOfOldBehavior = this.specification.modes[mode].indexOf(oldBehavior);
this.specification.modes[mode].splice(indexOfOldBehavior, 1);
});
});
@@ -2233,7 +1961,6 @@ export class Graph
* Update a behavior on a mode.
* @param behavior behavior configs, whose name indicates the behavior to be updated
* @param mode mode name
- * @returns
* @group Interaction
*/
public updateBehavior(behavior: BehaviorOptionsOf, mode?: string) {
@@ -2255,7 +1982,6 @@ export class Graph
/**
* Add plugin(s) to graph.
* @param pluginCfgs
- * @returns
* @group Plugin
*/
public addPlugins(
@@ -2283,8 +2009,7 @@ export class Graph
)[] = [];
pluginsArr.forEach((config) => {
const oldPlugin = oldPlugins.find((oldPlugin) => {
- if (typeof oldPlugin === 'string' || typeof config === 'string')
- return false;
+ if (typeof oldPlugin === 'string' || typeof config === 'string') return false;
return oldPlugin.key === config.key;
});
if (oldPlugin) {
@@ -2308,7 +2033,6 @@ export class Graph
/**
* Remove plugin(s) from graph.
* @param pluginKeys
- * @returns
* @group Plugin
*/
public removePlugins(pluginKeys: (PluginBase | string)[]) {
@@ -2320,11 +2044,7 @@ export class Graph
// update the graph specification
const { plugins } = this.specification;
this.specification.plugins = plugins?.filter((plugin) => {
- if (isObject(plugin))
- return !(
- pluginArr.includes(plugin.key) ||
- pluginArr.includes(plugin as PluginBase)
- );
+ if (isObject(plugin)) return !(pluginArr.includes(plugin.key) || pluginArr.includes(plugin as PluginBase));
return !pluginArr.includes(plugin);
});
}
@@ -2332,7 +2052,6 @@ export class Graph
/**
* Update a plugin of the graph.
* @param plugin plugin configs, whose key indicates the behavior to be updated
- * @returns
* @group Interaction
*/
public updatePlugin(
@@ -2351,14 +2070,10 @@ export class Graph
[cfg: string]: unknown;
};
if (!key) {
- console.warn(
- `The key for the plugin is not found. G6 will update the first plugin with type ${type}`,
- );
+ console.warn(`The key for the plugin is not found. G6 will update the first plugin with type ${type}`);
}
if (!plugins) {
- console.warn(
- 'Update plugin failed, the plugin to be updated does not exist.',
- );
+ console.warn('Update plugin failed, the plugin to be updated does not exist.');
return;
}
const oldPlugin = plugins?.find((p) => {
@@ -2375,9 +2090,7 @@ export class Graph
);
});
if (!oldPlugin) {
- console.warn(
- `Update plugin failed, the plugin with key ${key} or type ${type} is not found.`,
- );
+ console.warn(`Update plugin failed, the plugin with key ${key} or type ${type} is not found.`);
return;
}
const idx = plugins.indexOf(oldPlugin);
@@ -2398,6 +2111,16 @@ export class Graph
* Draw or update a G shape or group to the transient canvas.
* @param type shape type or item type
* @param id new shape id or updated shape id for a interaction shape, node/edge/combo id for item interaction group drawing
+ * @param config
+ * @param config.action
+ * @param config.data
+ * @param config.style
+ * @param config.drawSource
+ * @param config.drawTarget
+ * @param config.shapeIds
+ * @param config.visible
+ * @param config.upsertAncestors
+ * @param canvas
* @returns upserted shape or group
* @group Interaction
*/
@@ -2437,33 +2160,19 @@ export class Graph
* Asynchronously generates a Data URL representation of the canvas content, including
* background, main content, and transient canvas.
* @param The type of the Data URL (e.g., 'image/png', 'image/jpeg').
+ * @param type
* @returns A Promise that resolves to the Data URL string.
*/
public async toDataURL(type?: DataURLType): Promise {
- const {
- backgroundCanvas,
- canvas,
- transientCanvas,
- labelCanvas,
- rendererType,
- } = this;
-
- const pixelRatio =
- typeof window !== 'undefined' ? window.devicePixelRatio : 1;
+ const { backgroundCanvas, canvas, transientCanvas, labelCanvas, rendererType } = this;
+
+ const pixelRatio = typeof window !== 'undefined' ? window.devicePixelRatio : 1;
const [width, height] = this.getSize();
- const vContainerDOM: HTMLElement = createDOM(
- '',
- );
+ const vContainerDOM: HTMLElement = createDOM('');
const camera = canvas.getCamera();
- const vCanvas = createCanvas(
- rendererType,
- vContainerDOM,
- width,
- height,
- pixelRatio,
- );
+ const vCanvas = createCanvas(rendererType, vContainerDOM, width, height, pixelRatio);
await vCanvas.ready;
const backgroundClonedGroup = backgroundCanvas.getRoot().cloneNode(true);
@@ -2481,11 +2190,7 @@ export class Graph
// TODO: after cloning, label background with rotation take a wrong place, remove it to temporary solve.
labelClonedGroup.children[0].children.forEach((childGroup) => {
childGroup.children.forEach((shape) => {
- if (
- shape.getAttribute('data-is-label-background') &&
- shape.style.transform
- )
- shape.remove();
+ if (shape.getAttribute('data-is-label-background') && shape.style.transform) shape.remove();
});
});
@@ -2510,9 +2215,7 @@ export class Graph
width: vCanvasContextService.getDomElement().width,
height: vCanvasContextService.getDomElement().height,
//@ts-ignore
- fill: backgroundCanvas.getContextService().getDomElement().style[
- 'background-color'
- ],
+ fill: backgroundCanvas.getContextService().getDomElement().style['background-color'],
zIndex: -10,
},
});
@@ -2536,19 +2239,11 @@ export class Graph
* including background, main content, and transient canvas, with optional padding.
* @param type The type of the Data URL (e.g., 'image/png', 'image/jpeg').
* @param imageConfig Configuration options for the image (optional).
+ * @param imageConfig.padding
* @returns A Promise that resolves to the Data URL string.
*/
- public async toFullDataURL(
- type?: DataURLType,
- imageConfig?: { padding?: number | number[] },
- ) {
- const {
- backgroundCanvas,
- canvas,
- transientCanvas,
- labelCanvas,
- rendererType,
- } = this;
+ public async toFullDataURL(type?: DataURLType, imageConfig?: { padding?: number | number[] }) {
+ const { backgroundCanvas, canvas, transientCanvas, labelCanvas, rendererType } = this;
const backgroundRoot = backgroundCanvas.getRoot();
const root = canvas.getRoot();
const transientRoot = transientCanvas.getRoot();
@@ -2600,20 +2295,11 @@ export class Graph
const halfX = (right - left) / 2;
const halfY = (bottom - top) / 2;
- const pixelRatio =
- typeof window !== 'undefined' ? window.devicePixelRatio : 1;
+ const pixelRatio = typeof window !== 'undefined' ? window.devicePixelRatio : 1;
const vWidth = halfX * 2;
const vHeight = halfY * 2;
- const vContainerDOM: HTMLElement = createDOM(
- '',
- );
- const vCanvas = createCanvas(
- rendererType,
- vContainerDOM,
- vWidth,
- vHeight,
- pixelRatio,
- );
+ const vContainerDOM: HTMLElement = createDOM('');
+ const vCanvas = createCanvas(rendererType, vContainerDOM, vWidth, vHeight, pixelRatio);
await vCanvas.ready;
const vCanvasContextService = vCanvas.getContextService();
if (rendererType !== 'svg') {
@@ -2625,9 +2311,7 @@ export class Graph
width: vCanvasContextService.getDomElement().width,
height: vCanvasContextService.getDomElement().height,
//@ts-ignore
- fill: backgroundCanvas.getContextService().getDomElement().style[
- 'background-color'
- ],
+ fill: backgroundCanvas.getContextService().getDomElement().style['background-color'],
},
});
vCanvas.appendChild(bgRect);
@@ -2636,10 +2320,7 @@ export class Graph
const clonedGroup = root.cloneNode(true);
const transientClonedGroup = transientRoot.cloneNode(true);
const labelClonedGroup = labelRoot.cloneNode(true);
- const transPosition: [number, number] = [
- -graphCenterX + halfX,
- -graphCenterY + halfY,
- ];
+ const transPosition: [number, number] = [-graphCenterX + halfX, -graphCenterY + halfY];
backgroundClonedGroup.setPosition(transPosition);
clonedGroup.setPosition(transPosition);
transientClonedGroup.setPosition(transPosition);
@@ -2654,11 +2335,7 @@ export class Graph
// TODO: after cloning, label background with rotation take a wrong place, remove it to temporary solve.
labelClonedGroup.children[0].children.forEach((childGroup) => {
childGroup.children.forEach((shape) => {
- if (
- shape.getAttribute('data-is-label-background') &&
- shape.style.transform
- )
- shape.remove();
+ if (shape.getAttribute('data-is-label-background') && shape.style.transform) shape.remove();
});
});
@@ -2743,9 +2420,7 @@ export class Graph
const rendererType = this.rendererType;
if (!type) type = 'image/png';
- const fileName: string =
- (name || 'graph') +
- (rendererType === 'svg' ? '.svg' : type.split('/')[1]);
+ const fileName: string = (name || 'graph') + (rendererType === 'svg' ? '.svg' : type.split('/')[1]);
const link: HTMLAnchorElement = document.createElement('a');
@@ -2762,19 +2437,14 @@ export class Graph
* @param name The desired name for the downloaded image file (optional).
* @param type The type of the image to download (optional, defaults to 'image/png').
* @param imageConfig Configuration options for the image (optional).
+ * @param imageConfig.padding
*/
- public downloadFullImage(
- name?: string,
- type?: DataURLType,
- imageConfig?: { padding?: number | number[] },
- ): void {
+ public downloadFullImage(name?: string, type?: DataURLType, imageConfig?: { padding?: number | number[] }): void {
const self = this;
const rendererType = this.rendererType;
if (!type) type = 'image/png';
- const fileName: string =
- (name || 'graph') +
- (rendererType === 'svg' ? '.svg' : type.split('/')[1]);
+ const fileName: string = (name || 'graph') + (rendererType === 'svg' ? '.svg' : type.split('/')[1]);
const link: HTMLAnchorElement = document.createElement('a');
self.asyncToFullDataUrl(type, imageConfig, (dataURL) => {
@@ -2807,6 +2477,7 @@ export class Graph
* with optional padding, and invokes the provided callback.
* @param type The type of the Data URL (optional, defaults to 'image/png').
* @param imageConfig Configuration options for the image (optional).
+ * @param imageConfig.padding
* @param callback A callback function to handle the Data URL (optional).
*/
protected asyncToFullDataUrl(
@@ -2894,7 +2565,6 @@ export class Graph
/**
* Retrieve the complete history stack
- * @returns
*/
public getStack() {
const history = this.getHistoryPlugin();
@@ -2904,7 +2574,6 @@ export class Graph
/**
* Restore n operations that were last n reverted on the graph.
* @param steps The number of operations to undo. Default to 1.
- * @returns
*/
public undo() {
const history = this.getHistoryPlugin();
@@ -2914,7 +2583,6 @@ export class Graph
/**
* Revert recent n operation(s) performed on the graph.
* @param steps The number of operations to redo. Default to 1.
- * @returns
*/
public redo() {
const history = this.getHistoryPlugin();
@@ -2975,9 +2643,7 @@ export class Graph
public cleanHistory(stackType?: StackType) {
const history = this.getHistoryPlugin();
if (!stackType) return history?.clear();
- return stackType === 'undo'
- ? history?.clearUndoStack()
- : history?.clearRedoStack();
+ return stackType === 'undo' ? history?.clearUndoStack() : history?.clearRedoStack();
}
/**
@@ -2985,7 +2651,6 @@ export class Graph
* @param ids Root id(s) of the sub trees.
* @param disableAnimate Whether disable the animations for this operation.
* @param stack Whether push this operation to stack.
- * @returns
* @group Tree
*/
public collapse(ids: ID | ID[], disableAnimate = false) {
@@ -3001,7 +2666,6 @@ export class Graph
* @param ids Root id(s) of the sub trees.
* @param disableAnimate Whether disable the animations for this operation.
* @param stack Whether push this operation to stack.
- * @returns
* @group Tree
*/
public expand(ids: ID | ID[], disableAnimate = false) {
@@ -3015,7 +2679,7 @@ export class Graph
/**
* Destroy the graph instance and remove the related canvases.
- * @returns
+ * @param callback
* @group Graph Instance
*/
public destroy(callback?: Function) {
diff --git a/packages/g6/src/stdlib/behavior/activate-relations.ts b/packages/g6/src/stdlib/behavior/activate-relations.ts
index a6985135cc5..170395f98c1 100644
--- a/packages/g6/src/stdlib/behavior/activate-relations.ts
+++ b/packages/g6/src/stdlib/behavior/activate-relations.ts
@@ -59,7 +59,7 @@ const DEFAULT_OPTIONS: ActivateRelationsOptions = {
export class ActivateRelations extends Behavior {
timer: number;
- inactiveItems: {};
+ inactiveItems: object;
prevNodeIds: ID[];
prevEdgeIds: ID[];
@@ -67,9 +67,7 @@ export class ActivateRelations extends Behavior {
super(Object.assign({}, DEFAULT_OPTIONS, options));
// Validate options
if (options.trigger && !MOUSE_TRIGGERS.includes(options.trigger)) {
- console.warn(
- `G6: Invalid trigger option "${options.trigger}" for activate-relations behavior!`,
- );
+ console.warn(`G6: Invalid trigger option "${options.trigger}" for activate-relations behavior!`);
this.options.trigger = DEFAULT_OPTIONS.trigger;
}
this.prevEdgeIds = [];
@@ -101,22 +99,12 @@ export class ActivateRelations extends Behavior {
if (!graph || graph.destroyed) return;
if (!this.options.shouldBegin(e)) return;
- const ids = graph
- .getNeighborNodesData(itemId, 'both')
- .map((item) => item.id);
- const edgeIds = graph
- .getRelatedEdgesData(itemId, 'both')
- .map((item) => item.id);
+ const ids = graph.getNeighborNodesData(itemId, 'both').map((item) => item.id);
+ const edgeIds = graph.getRelatedEdgesData(itemId, 'both').map((item) => item.id);
const nodeIds = [itemId, ...ids];
/** 数据对比,处理得到最小改动的高亮和非高亮的数据 */
- const { active: activeNodeIds, inactive: inactiveNodeIds } = compare(
- this.prevNodeIds,
- nodeIds,
- );
- const { active: activeEdgeIds, inactive: inactiveEdgeIds } = compare(
- this.prevEdgeIds,
- edgeIds,
- );
+ const { active: activeNodeIds, inactive: inactiveNodeIds } = compare(this.prevNodeIds, nodeIds);
+ const { active: activeEdgeIds, inactive: inactiveEdgeIds } = compare(this.prevEdgeIds, edgeIds);
graph.historyBatch(() => {
/** 节点 */
diff --git a/packages/g6/src/stdlib/behavior/brush-select.ts b/packages/g6/src/stdlib/behavior/brush-select.ts
index aa329f2e2ae..b65b70bb20d 100644
--- a/packages/g6/src/stdlib/behavior/brush-select.ts
+++ b/packages/g6/src/stdlib/behavior/brush-select.ts
@@ -1,12 +1,12 @@
import { DisplayObject } from '@antv/g';
import { ID } from '@antv/graphlib';
-import rectSelector from '../selector/rect';
import { Behavior } from '../../types/behavior';
import { Point } from '../../types/common';
import { IG6GraphEvent } from '../../types/event';
import { ITEM_TYPE } from '../../types/item';
import { diffSet, intersectSet, unionSet } from '../../util/array';
import { getEdgesBetween } from '../../util/item';
+import rectSelector from '../selector/rect';
const ALLOWED_TRIGGERS = ['drag', 'shift', 'ctrl', 'alt', 'meta'] as const;
const BRUSH_SHAPE_ID = 'g6-brush-select-brush-shape';
@@ -61,12 +61,7 @@ export interface BrushSelectOptions {
* If it returns false, you may probably listen to `eventName` and
* manage states or data manually
*/
- shouldUpdate: (
- itemType: ITEM_TYPE,
- id: ID,
- action: 'select' | 'deselect',
- self: BrushSelect,
- ) => boolean;
+ shouldUpdate: (itemType: ITEM_TYPE, id: ID, action: 'select' | 'deselect', self: BrushSelect) => boolean;
/**
* A callback be called after selecting.
*/
@@ -113,9 +108,7 @@ export class BrushSelect extends Behavior {
super(Object.assign({}, DEFAULT_OPTIONS, options));
// Validate options
if (options.trigger && !ALLOWED_TRIGGERS.includes(options.trigger)) {
- console.warn(
- `G6: Invalid trigger option "${options.trigger}" for brush-select behavior!`,
- );
+ console.warn(`G6: Invalid trigger option "${options.trigger}" for brush-select behavior!`);
this.options.trigger = DEFAULT_OPTIONS.trigger;
}
}
@@ -190,10 +183,7 @@ export class BrushSelect extends Behavior {
this.mousedown = false;
}
- public clearStates(
- clearIds: IDSet | undefined = undefined,
- restIds = undefined,
- ) {
+ public clearStates(clearIds: IDSet | undefined = undefined, restIds = undefined) {
const { graph } = this;
const { selectedState, eventName, onDeselect } = this.options;
@@ -240,23 +230,14 @@ export class BrushSelect extends Behavior {
public selectItems(event: IG6GraphEvent) {
const { graph, options } = this;
- const {
- selectedState,
- itemTypes,
- eventName,
- selectSetMode,
- shouldUpdate,
- onSelect,
- } = options;
+ const { selectedState, itemTypes, eventName, selectSetMode, shouldUpdate, onSelect } = options;
const selector = this.getSelector();
const points = this.getPoints(event).filter(Boolean);
if (points.length < 2) return;
let selectedIds = selector(graph, points, itemTypes.concat('node'));
let operateSetFunc = (a, b) => b;
const currentNotEmpty =
- this.selectedIds?.nodes.length ||
- this.selectedIds?.edges.length ||
- this.selectedIds?.combos.length;
+ this.selectedIds?.nodes.length || this.selectedIds?.edges.length || this.selectedIds?.combos.length;
switch (selectSetMode) {
case 'diff':
@@ -277,21 +258,19 @@ export class BrushSelect extends Behavior {
break;
}
selectedIds = {
- nodes: operateSetFunc(this.selectedIds?.nodes, selectedIds.nodes).filter(
- (id) => shouldUpdate('node', id, 'select', this),
+ nodes: operateSetFunc(this.selectedIds?.nodes, selectedIds.nodes).filter((id) =>
+ shouldUpdate('node', id, 'select', this),
),
edges: [],
- combos: operateSetFunc(
- this.selectedIds?.combos,
- selectedIds.combos,
- ).filter((id) => shouldUpdate('combo', id, 'select', this)),
+ combos: operateSetFunc(this.selectedIds?.combos, selectedIds.combos).filter((id) =>
+ shouldUpdate('combo', id, 'select', this),
+ ),
};
const edgeSelectable = itemTypes.includes('edge');
if (edgeSelectable) {
- selectedIds.edges = getEdgesBetween(
- graph,
- selectedIds.nodes.concat(selectedIds.combos),
- ).filter((id) => shouldUpdate('edge', id, 'select', this));
+ selectedIds.edges = getEdgesBetween(graph, selectedIds.nodes.concat(selectedIds.combos)).filter((id) =>
+ shouldUpdate('edge', id, 'select', this),
+ );
}
const nodeSelectable = itemTypes.includes('node');
if (!nodeSelectable) selectedIds.nodes = [];
@@ -300,20 +279,11 @@ export class BrushSelect extends Behavior {
if (selectedState) {
const diffToClear = {
- nodes: nodeSelectable
- ? diffSet(this.selectedIds?.nodes, selectedIds.nodes)
- : [],
- edges: edgeSelectable
- ? diffSet(this.selectedIds?.edges, selectedIds.edges)
- : [],
- combos: comboSelectable
- ? diffSet(this.selectedIds?.combos, selectedIds.combos)
- : [],
+ nodes: nodeSelectable ? diffSet(this.selectedIds?.nodes, selectedIds.nodes) : [],
+ edges: edgeSelectable ? diffSet(this.selectedIds?.edges, selectedIds.edges) : [],
+ combos: comboSelectable ? diffSet(this.selectedIds?.combos, selectedIds.combos) : [],
};
- const clearNotEmpty =
- diffToClear.nodes.length ||
- diffToClear.edges.length ||
- diffToClear.combos.length;
+ const clearNotEmpty = diffToClear.nodes.length || diffToClear.edges.length || diffToClear.combos.length;
if (clearNotEmpty) {
this.clearStates(diffToClear, selectedIds as any);
}
@@ -324,10 +294,7 @@ export class BrushSelect extends Behavior {
.forEach((id) => graph.setItemState(id, selectedState, true));
}
this.selectedIds = selectedIds;
- const selectNotEmpty =
- selectedIds.nodes.length ||
- selectedIds.edges.length ||
- selectedIds.combos.length;
+ const selectNotEmpty = selectedIds.nodes.length || selectedIds.edges.length || selectedIds.combos.length;
if (selectNotEmpty) onSelect?.(this.selectedIds);
// Emit an event.
diff --git a/packages/g6/src/stdlib/behavior/click-select.ts b/packages/g6/src/stdlib/behavior/click-select.ts
index bbba1e36891..fcf7bc9332b 100644
--- a/packages/g6/src/stdlib/behavior/click-select.ts
+++ b/packages/g6/src/stdlib/behavior/click-select.ts
@@ -73,9 +73,7 @@ export class ClickSelect extends Behavior {
super(Object.assign({}, DEFAULT_OPTIONS, options));
// Validate options
if (options.trigger && !ALLOWED_TRIGGERS.includes(options.trigger)) {
- console.warn(
- `G6: Invalid trigger option "${options.trigger}" for click-select behavior!`,
- );
+ console.warn(`G6: Invalid trigger option "${options.trigger}" for click-select behavior!`);
this.options.trigger = DEFAULT_OPTIONS.trigger;
}
}
@@ -127,12 +125,8 @@ export class ClickSelect extends Behavior {
const state = this.options.selectedState;
const multiple = this.isMultipleSelect(event as any);
// FIXME: should use graph.getItemState() instead
- const isSelectAction = !this.graph
- .findIdByState(itemType, state)
- .includes(itemId);
- const action: 'select' | 'unselect' = isSelectAction
- ? 'select'
- : 'unselect';
+ const isSelectAction = !this.graph.findIdByState(itemType, state).includes(itemId);
+ const action: 'select' | 'unselect' = isSelectAction ? 'select' : 'unselect';
// Select/Unselect item.
if (this.options.shouldUpdate(event)) {
@@ -190,8 +184,7 @@ export class ClickSelect extends Behavior {
}
public onCanvasPointerUp(event: IG6GraphEvent) {
- if (this.canvasPointerDown && !this.canvasPointerMove)
- this.onCanvasClick(event);
+ if (this.canvasPointerDown && !this.canvasPointerMove) this.onCanvasClick(event);
this.canvasPointerDown = undefined;
this.canvasPointerMove = false;
}
diff --git a/packages/g6/src/stdlib/behavior/collapse-expand-combo.ts b/packages/g6/src/stdlib/behavior/collapse-expand-combo.ts
index 47d73a595e1..53aaa720d2d 100644
--- a/packages/g6/src/stdlib/behavior/collapse-expand-combo.ts
+++ b/packages/g6/src/stdlib/behavior/collapse-expand-combo.ts
@@ -1,10 +1,5 @@
-import { ID } from '@antv/graphlib';
-import { throttle, uniq } from '@antv/util';
-import { ComboModel, EdgeModel, NodeModel } from '../../types';
import { Behavior } from '../../types/behavior';
import { IG6GraphEvent } from '../../types/event';
-import { Point } from '../../types/common';
-import { graphComboTreeDfs } from '../../util/data';
const ALLOWED_TRIGGERS = ['dblclick', 'click'] as const;
type Trigger = (typeof ALLOWED_TRIGGERS)[number];
diff --git a/packages/g6/src/stdlib/behavior/collapse-expand-tree.ts b/packages/g6/src/stdlib/behavior/collapse-expand-tree.ts
index 9648239c801..528917b8655 100644
--- a/packages/g6/src/stdlib/behavior/collapse-expand-tree.ts
+++ b/packages/g6/src/stdlib/behavior/collapse-expand-tree.ts
@@ -46,9 +46,7 @@ export class CollapseExpandTree extends Behavior {
super(Object.assign({}, DEFAULT_OPTIONS, options));
// Validate options
if (options.trigger && !ALLOWED_TRIGGERS.includes(options.trigger)) {
- console.warn(
- `G6: Invalid trigger option "${options.trigger}" for collapse-expand-tree behavior!`,
- );
+ console.warn(`G6: Invalid trigger option "${options.trigger}" for collapse-expand-tree behavior!`);
this.options.trigger = DEFAULT_OPTIONS.trigger;
}
}
diff --git a/packages/g6/src/stdlib/behavior/create-edge.ts b/packages/g6/src/stdlib/behavior/create-edge.ts
index 84f0ba5cf6e..abfeb105211 100644
--- a/packages/g6/src/stdlib/behavior/create-edge.ts
+++ b/packages/g6/src/stdlib/behavior/create-edge.ts
@@ -1,8 +1,8 @@
import type { IG6GraphEvent } from '../../types';
-import { warn } from '../../util/warn';
-import { generateEdgeID } from '../../util/item';
import { Behavior } from '../../types/behavior';
import { EdgeDisplayModelData } from '../../types/edge';
+import { generateEdgeID } from '../../util/item';
+import { warn } from '../../util/warn';
const KEYBOARD_TRIGGERS = ['shift', 'ctrl', 'control', 'alt', 'meta'] as const;
const EVENT_TRIGGERS = ['click', 'drag'] as const;
@@ -80,10 +80,7 @@ export class CreateEdge extends Behavior {
this.options.trigger = DEFAULT_OPTIONS.trigger;
}
- if (
- options.secondaryKey &&
- !KEYBOARD_TRIGGERS.includes(options.secondaryKey)
- ) {
+ if (options.secondaryKey && !KEYBOARD_TRIGGERS.includes(options.secondaryKey)) {
warn({
optionName: `create-edge.secondaryKey`,
shouldBe: KEYBOARD_TRIGGERS,
@@ -121,10 +118,7 @@ export class CreateEdge extends Behavior {
}
: {};
- return { ...triggerEvents, ...keyboardEvents } as Record<
- string,
- (e: IG6GraphEvent) => void
- >;
+ return { ...triggerEvents, ...keyboardEvents } as Record void>;
};
handleCreateEdge = (e: IG6GraphEvent) => {
@@ -135,8 +129,7 @@ export class CreateEdge extends Behavior {
const { graph, options, addingEdge } = this;
const currentNodeId = e.itemId;
- const { edgeConfig, createVirtualEventName, createActualEventName } =
- options;
+ const { edgeConfig, createVirtualEventName, createActualEventName } = options;
if (addingEdge) {
if (!this.options.shouldEnd(e)) {
@@ -150,8 +143,7 @@ export class CreateEdge extends Behavior {
target: currentNodeId,
data: {
...edgeConfig,
- type:
- currentNodeId === addingEdge.source ? 'loop-edge' : edgeConfig.type,
+ type: currentNodeId === addingEdge.source ? 'loop-edge' : edgeConfig.type,
},
});
if (createActualEventName) {
@@ -206,17 +198,12 @@ export class CreateEdge extends Behavior {
return;
}
- const elements = await this.graph.canvas.document.elementsFromPoint(
- e.canvas.x,
- e.canvas.y,
- );
+ const elements = await this.graph.canvas.document.elementsFromPoint(e.canvas.x, e.canvas.y);
const currentIds = elements
- // @ts-ignore TODO: G type
+ // @ts-expect-error TODO: G type
.map((ele) => ele.parentNode.getAttribute?.('data-item-id'))
.filter((id) => id !== undefined && !DUMMY_NODE_ID !== id);
- const dropId = currentIds.find(
- (id) => this.graph.getComboData(id) || this.graph.getNodeData(id),
- );
+ const dropId = currentIds.find((id) => this.graph.getComboData(id) || this.graph.getNodeData(id));
if (!dropId) {
this.cancelCreating();
diff --git a/packages/g6/src/stdlib/behavior/drag-canvas.ts b/packages/g6/src/stdlib/behavior/drag-canvas.ts
index 22c88e0abc4..e6f10b7c7de 100644
--- a/packages/g6/src/stdlib/behavior/drag-canvas.ts
+++ b/packages/g6/src/stdlib/behavior/drag-canvas.ts
@@ -1,7 +1,7 @@
import { isNumber } from '@antv/util';
+import { ID, IG6GraphEvent } from '../../types';
import { Behavior } from '../../types/behavior';
import { Point } from '../../types/common';
-import { ID, IG6GraphEvent } from '../../types';
const VALID_TRIGGERS = ['drag', 'directionKeys'];
const DRAG_DURATION = 250;
@@ -81,9 +81,7 @@ export class DragCanvas extends Behavior {
constructor(options: Partial) {
const finalOptions = Object.assign({}, DEFAULT_OPTIONS, options);
if (!VALID_TRIGGERS.includes(finalOptions.trigger)) {
- console.warn(
- `The trigger ${finalOptions.trigger} is not valid, 'drag' will take effect.`,
- );
+ console.warn(`The trigger ${finalOptions.trigger} is not valid, 'drag' will take effect.`);
finalOptions.trigger = 'drag';
}
super(finalOptions);
@@ -110,8 +108,7 @@ export class DragCanvas extends Behavior {
}
public onPointerDown(event) {
- const { secondaryKey, secondaryKeyToDisable, dragOnItems, shouldBegin } =
- this.options;
+ const { secondaryKey, secondaryKeyToDisable, dragOnItems, shouldBegin } = this.options;
// disabled key is pressing
if (secondaryKeyToDisable && this.disableKeydown) return;
// assistant key is not pressing
@@ -137,15 +134,9 @@ export class DragCanvas extends Behavior {
private hideShapes() {
const { graph } = this;
- const { tileBehavior: graphBehaviorOptimize, tileBehaviorSize = 1000 } =
- graph.getSpecification().optimize || {};
- const optimize =
- this.options.enableOptimize !== undefined
- ? this.options.enableOptimize
- : graphBehaviorOptimize;
- const shouldOptimize = isNumber(optimize)
- ? graph.getAllNodesData().length > optimize
- : optimize;
+ const { tileBehavior: graphBehaviorOptimize, tileBehaviorSize = 1000 } = graph.getSpecification().optimize || {};
+ const optimize = this.options.enableOptimize !== undefined ? this.options.enableOptimize : graphBehaviorOptimize;
+ const shouldOptimize = isNumber(optimize) ? graph.getAllNodesData().length > optimize : optimize;
if (shouldOptimize) {
this.hiddenEdgeIds = graph
@@ -159,10 +150,7 @@ export class DragCanvas extends Behavior {
const hiddenIds = [...this.hiddenNodeIds];
const sectionNum = Math.ceil(hiddenIds.length / tileBehaviorSize);
const sections = Array.from({ length: sectionNum }, (v, i) =>
- hiddenIds.slice(
- i * tileBehaviorSize,
- i * tileBehaviorSize + tileBehaviorSize,
- ),
+ hiddenIds.slice(i * tileBehaviorSize, i * tileBehaviorSize + tileBehaviorSize),
);
const update = () => {
if (!sections.length && this.tileRequestId) {
@@ -249,8 +237,7 @@ export class DragCanvas extends Behavior {
this.graph.canvas.getConfig().disableHitTesting = true;
}
- const { tileBehavior: graphBehaviorOptimize } =
- this.graph.getSpecification().optimize || {};
+ const { tileBehavior: graphBehaviorOptimize } = this.graph.getSpecification().optimize || {};
const shouldDebounce =
typeof graphBehaviorOptimize === 'boolean'
@@ -258,11 +245,7 @@ export class DragCanvas extends Behavior {
: this.graph.getAllNodesData().length > graphBehaviorOptimize;
const now = Date.now();
- if (
- shouldDebounce &&
- this.lastDragTriggerTime &&
- now - this.lastDragTriggerTime < DRAG_DURATION / 5
- ) {
+ if (shouldDebounce && this.lastDragTriggerTime && now - this.lastDragTriggerTime < DRAG_DURATION / 5) {
return;
}
@@ -292,15 +275,9 @@ export class DragCanvas extends Behavior {
this.graph.canvas.getConfig().disableHitTesting = false;
const { graph, hiddenNodeIds, hiddenEdgeIds = [] } = this;
- const { tileBehavior: graphBehaviorOptimize, tileBehaviorSize = 1000 } =
- graph.getSpecification().optimize || {};
- const optimize =
- this.options.enableOptimize !== undefined
- ? this.options.enableOptimize
- : graphBehaviorOptimize;
- const shouldOptimize = isNumber(optimize)
- ? graph.getAllNodesData().length > optimize
- : optimize;
+ const { tileBehavior: graphBehaviorOptimize, tileBehaviorSize = 1000 } = graph.getSpecification().optimize || {};
+ const optimize = this.options.enableOptimize !== undefined ? this.options.enableOptimize : graphBehaviorOptimize;
+ const shouldOptimize = isNumber(optimize) ? graph.getAllNodesData().length > optimize : optimize;
if (shouldOptimize) {
if (this.tileRequestId) {
@@ -311,10 +288,7 @@ export class DragCanvas extends Behavior {
const hiddenIds = [...hiddenNodeIds, ...hiddenEdgeIds];
const sectionNum = Math.ceil(hiddenIds.length / tileBehaviorSize);
const sections = Array.from({ length: sectionNum }, (v, i) =>
- hiddenIds.slice(
- i * tileBehaviorSize,
- i * tileBehaviorSize + tileBehaviorSize,
- ),
+ hiddenIds.slice(i * tileBehaviorSize, i * tileBehaviorSize + tileBehaviorSize),
);
const update = () => {
if (!sections.length && this.tileRequestId) {
@@ -334,14 +308,7 @@ export class DragCanvas extends Behavior {
public onKeydown(event) {
const { key } = event;
- const {
- secondaryKey,
- secondaryKeyToDisable,
- trigger,
- speedUpKey,
- eventName,
- shouldBegin,
- } = this.options;
+ const { secondaryKey, secondaryKeyToDisable, trigger, speedUpKey, eventName, shouldBegin } = this.options;
if (secondaryKey && secondaryKey === key.toLowerCase()) {
this.keydown = true;
}
@@ -374,10 +341,7 @@ export class DragCanvas extends Behavior {
break;
}
if (dx || dy) {
- const { dx: formattedDx, dy: formattedDy } = this.formatDisplacement(
- dx,
- dy,
- );
+ const { dx: formattedDx, dy: formattedDy } = this.formatDisplacement(dx, dy);
graph.translate({ dx: formattedDx, dy: formattedDy });
if (eventName) {
this.graph.emit(eventName, {
diff --git a/packages/g6/src/stdlib/behavior/drag-combo.ts b/packages/g6/src/stdlib/behavior/drag-combo.ts
index d8c3b246d39..956dda29b73 100644
--- a/packages/g6/src/stdlib/behavior/drag-combo.ts
+++ b/packages/g6/src/stdlib/behavior/drag-combo.ts
@@ -2,8 +2,8 @@ import { ID } from '@antv/graphlib';
import { debounce, throttle, uniq } from '@antv/util';
import { ComboModel, EdgeModel, NodeModel } from '../../types';
import { Behavior } from '../../types/behavior';
-import { IG6GraphEvent } from '../../types/event';
import { Point } from '../../types/common';
+import { IG6GraphEvent } from '../../types/event';
import { graphComboTreeDfs } from '../../util/data';
const DELEGATE_SHAPE_ID = 'g6-drag-combo-delegate-shape';
@@ -139,14 +139,13 @@ export class DragCombo extends Behavior {
}
};
- /** Given selected node ids, get their related visible edges. */
- private getRelatedEdges(
- selectedComboIds: ID[],
- comboTreeRoots: (ComboModel | NodeModel)[],
- ) {
- let edges = selectedComboIds.flatMap((comboId) =>
- this.graph.getRelatedEdgesData(comboId),
- );
+ /**
+ * Given selected node ids, get their related visible edges.
+ * @param selectedComboIds
+ * @param comboTreeRoots
+ */
+ private getRelatedEdges(selectedComboIds: ID[], comboTreeRoots: (ComboModel | NodeModel)[]) {
+ let edges = selectedComboIds.flatMap((comboId) => this.graph.getRelatedEdgesData(comboId));
graphComboTreeDfs(this.graph, comboTreeRoots, (child) => {
edges = edges.concat(this.graph.getRelatedEdgesData(child.id));
});
@@ -177,11 +176,7 @@ export class DragCombo extends Behavior {
const items = begins;
graphComboTreeDfs(this.graph, begins, (child) => items.push(child), 'TB');
- return uniq(items).filter(
- (item) =>
- !selectedComboIds.includes(item.id) &&
- this.graph.getItemVisible(item.id),
- );
+ return uniq(items).filter((item) => !selectedComboIds.includes(item.id) && this.graph.getItemVisible(item.id));
}
public onPointerDown(event: IG6GraphEvent) {
@@ -197,8 +192,7 @@ export class DragCombo extends Behavior {
const beginDeltaY = Math.abs(this.pointerDown.y - event.canvas.y);
if (beginDeltaX < 1 && beginDeltaY < 1) return;
- const enableTransient =
- this.options.enableTransient && this.graph.rendererType !== 'webgl-3d';
+ const enableTransient = this.options.enableTransient && this.graph.rendererType !== 'webgl-3d';
if (this.dragging) {
this.originPositions = this.selectedComboIds
@@ -226,19 +220,11 @@ export class DragCombo extends Behavior {
this.dragging = true;
const currentComboId = event.itemId;
- let selectedComboIds = this.graph.findIdByState(
- 'combo',
- this.options.selectedState,
- true,
- );
+ let selectedComboIds = this.graph.findIdByState('combo', this.options.selectedState, true);
// If current node is selected, drag all the selected nodes together.
// Otherwise drag current node.
- if (
- currentComboId &&
- event.itemType === 'combo' &&
- !selectedComboIds.includes(currentComboId)
- ) {
+ if (currentComboId && event.itemType === 'combo' && !selectedComboIds.includes(currentComboId)) {
selectedComboIds = [currentComboId];
}
this.selectedComboIds = selectedComboIds;
@@ -246,10 +232,7 @@ export class DragCombo extends Behavior {
// Hide related edge.
if (this.options.hideRelatedEdges && !enableTransient) {
this.hiddenComboTreeRoots = this.getComboTreeItems(selectedComboIds);
- this.hiddenEdges = this.getRelatedEdges(
- selectedComboIds,
- this.hiddenComboTreeRoots,
- );
+ this.hiddenEdges = this.getRelatedEdges(selectedComboIds, this.hiddenComboTreeRoots);
this.graph.executeWithNoStack(() => {
this.graph.hideItem(
this.hiddenEdges.map((edge) => edge.id),
@@ -266,10 +249,7 @@ export class DragCombo extends Behavior {
if (enableTransient) {
// Draw transient edges and nodes.
this.hiddenComboTreeRoots = this.getComboTreeItems(selectedComboIds);
- this.hiddenEdges = this.getRelatedEdges(
- selectedComboIds,
- this.hiddenComboTreeRoots,
- );
+ this.hiddenEdges = this.getRelatedEdges(selectedComboIds, this.hiddenComboTreeRoots);
selectedComboIds.forEach((comboId) => {
this.graph.drawTransient('combo', comboId, {
upsertAncestors: !this.options.updateComboStructure,
@@ -297,11 +277,7 @@ export class DragCombo extends Behavior {
// Throttle moving.
if (this.options.throttle > 0) {
- this.throttledMoveCombos = throttle(
- this.moveCombos,
- this.options.throttle,
- { leading: true, trailing: true },
- );
+ this.throttledMoveCombos = throttle(this.moveCombos, this.options.throttle, { leading: true, trailing: true });
} else {
this.throttledMoveCombos = this.moveCombos;
}
@@ -316,24 +292,18 @@ export class DragCombo extends Behavior {
return;
}
- // @ts-ignore FIXME: type
+ // @ts-expect-error FIXME: type
const pointerEvent = event as PointerEvent;
- // @ts-ignore FIXME: Type
+ // @ts-expect-error FIXME: Type
const deltaX = pointerEvent.canvas.x - this.previousX;
- // @ts-ignore FIXME: Type
+ // @ts-expect-error FIXME: Type
const deltaY = pointerEvent.canvas.y - this.previousY;
if (this.options.enableDelegate) {
this.moveDelegate(deltaX, deltaY);
} else {
- const enableTransient =
- this.options.enableTransient && this.graph.rendererType !== 'webgl-3d';
- this.throttledMoveCombos(
- deltaX,
- deltaY,
- enableTransient,
- !this.options.updateComboStructure,
- );
+ const enableTransient = this.options.enableTransient && this.graph.rendererType !== 'webgl-3d';
+ this.throttledMoveCombos(deltaX, deltaY, enableTransient, !this.options.updateComboStructure);
}
}
@@ -384,18 +354,10 @@ export class DragCombo extends Behavior {
};
public moveDelegate(deltaX: number, deltaY: number) {
- const x1 = Math.min(
- ...this.originPositions.map((position) => position.minX),
- );
- const y1 = Math.min(
- ...this.originPositions.map((position) => position.minY),
- );
- const x2 = Math.max(
- ...this.originPositions.map((position) => position.maxX),
- );
- const y2 = Math.max(
- ...this.originPositions.map((position) => position.maxY),
- );
+ const x1 = Math.min(...this.originPositions.map((position) => position.minX));
+ const y1 = Math.min(...this.originPositions.map((position) => position.minY));
+ const x2 = Math.max(...this.originPositions.map((position) => position.maxX));
+ const y2 = Math.max(...this.originPositions.map((position) => position.maxY));
this.graph.drawTransient('rect', DELEGATE_SHAPE_ID, {
style: {
x: x1 + deltaX,
@@ -444,8 +406,7 @@ export class DragCombo extends Behavior {
);
this.hiddenComboTreeRoots = [];
}
- const enableTransient =
- this.options.enableTransient && this.graph.rendererType !== 'webgl-3d';
+ const enableTransient = this.options.enableTransient && this.graph.rendererType !== 'webgl-3d';
if (enableTransient) {
this.graph.showItem(
this.originPositions.concat(positions).map((position) => position.id),
@@ -458,17 +419,16 @@ export class DragCombo extends Behavior {
public onPointerUp(event: IG6GraphEvent) {
this.pointerDown = undefined;
this.dragging = false;
- const enableTransient =
- this.options.enableTransient && this.graph.rendererType !== 'webgl-3d';
+ const enableTransient = this.options.enableTransient && this.graph.rendererType !== 'webgl-3d';
// If transient or delegate was enabled, move the real nodes.
// if (enableTransient || this.options.enableDelegate) {
- // @ts-ignore FIXME: type
+ // @ts-expect-error FIXME: type
const pointerEvent = event as PointerEvent;
const baseX = enableTransient ? this.originX : this.previousX;
const baseY = enableTransient ? this.originY : this.previousY;
- // @ts-ignore FIXME: Type
+ // @ts-expect-error FIXME: Type
const deltaX = pointerEvent.canvas.x - baseX + 0.01;
- // @ts-ignore FIXME: Type
+ // @ts-expect-error FIXME: Type
const deltaY = pointerEvent.canvas.y - baseY + 0.01;
this.moveCombos(
deltaX,
@@ -513,8 +473,7 @@ export class DragCombo extends Behavior {
this.clearTransientItems();
this.restoreHiddenItems();
- const enableTransient =
- this.options.enableTransient && this.graph.rendererType !== 'webgl-3d';
+ const enableTransient = this.options.enableTransient && this.graph.rendererType !== 'webgl-3d';
// Restore node positions.
if (!enableTransient && !this.options.enableDelegate) {
const positionChanges = this.originPositions.map(({ id, x, y }) => {
@@ -527,23 +486,16 @@ export class DragCombo extends Behavior {
}
public async onDropNode(event: IG6GraphEvent) {
- const elements = await this.graph.canvas.document.elementsFromPoint(
- event.canvas.x,
- event.canvas.y,
- );
+ const elements = await this.graph.canvas.document.elementsFromPoint(event.canvas.x, event.canvas.y);
const draggingIds = this.originPositions.map(({ id }) => id);
const currentIds = elements
- // @ts-ignore TODO: G type
+ // @ts-expect-error TODO: G type
.map((ele) => ele.parentNode.getAttribute?.('data-item-id'))
.filter((id) => id !== undefined && !draggingIds.includes(id));
// the top item which is not in draggingIds
- const dropId = currentIds.find(
- (id) => this.graph.getComboData(id) || this.graph.getNodeData(id),
- );
+ const dropId = currentIds.find((id) => this.graph.getComboData(id) || this.graph.getNodeData(id));
// drop on a node A, move the dragged node to the same parent of A
- const newParentId = this.graph.getNodeData(dropId)
- ? this.graph.getNodeData(dropId).data.parentId
- : dropId;
+ const newParentId = this.graph.getNodeData(dropId) ? this.graph.getNodeData(dropId).data.parentId : dropId;
this.originPositions.forEach(({ id }) => {
const model = this.graph.getComboData(id);
diff --git a/packages/g6/src/stdlib/behavior/drag-node.ts b/packages/g6/src/stdlib/behavior/drag-node.ts
index 555b4a334d2..06779a66805 100644
--- a/packages/g6/src/stdlib/behavior/drag-node.ts
+++ b/packages/g6/src/stdlib/behavior/drag-node.ts
@@ -2,13 +2,10 @@ import { ID } from '@antv/graphlib';
import { debounce, throttle, uniq } from '@antv/util';
import { ComboModel, EdgeModel, NodeModel } from '../../types';
import { Behavior } from '../../types/behavior';
-import { IG6GraphEvent } from '../../types/event';
import { Point } from '../../types/common';
+import { IG6GraphEvent } from '../../types/event';
import { graphComboTreeDfs } from '../../util/data';
-import {
- isPointPreventPolylineOverlap,
- isPolylineWithObstacleAvoidance,
-} from '../../util/polyline';
+import { isPointPreventPolylineOverlap, isPolylineWithObstacleAvoidance } from '../../util/polyline';
const DELEGATE_SHAPE_ID = 'g6-drag-node-delegate-shape';
@@ -151,20 +148,17 @@ export class DragNode extends Behavior {
}
};
- /** Given selected node ids, get their related visible edges. */
- private getRelatedEdges(
- selectedNodeIds: ID[],
- relatedCombo: (ComboModel | NodeModel)[],
- ) {
+ /**
+ * Given selected node ids, get their related visible edges.
+ * @param selectedNodeIds
+ * @param relatedCombo
+ */
+ private getRelatedEdges(selectedNodeIds: ID[], relatedCombo: (ComboModel | NodeModel)[]) {
const relatedNodeComboIds = [];
- graphComboTreeDfs(this.graph, relatedCombo, (item) =>
- relatedNodeComboIds.push(item.id),
- );
+ graphComboTreeDfs(this.graph, relatedCombo, (item) => relatedNodeComboIds.push(item.id));
return uniq(
- selectedNodeIds
- .concat(relatedNodeComboIds)
- .flatMap((nodeId) => this.graph.getRelatedEdgesData(nodeId)),
+ selectedNodeIds.concat(relatedNodeComboIds).flatMap((nodeId) => this.graph.getRelatedEdgesData(nodeId)),
);
}
@@ -179,16 +173,13 @@ export class DragNode extends Behavior {
return relatedNodes;
}
- /** Retrieve the nearby edges for a given node using quad-tree collision detection. */
- private getNearEdgesForNodes(
- nodeIds: ID[],
- shouldBegin?: (edge: EdgeModel) => boolean,
- ) {
- return uniq(
- nodeIds.flatMap((nodeId) =>
- this.graph.getNearEdgesData(nodeId, shouldBegin),
- ),
- );
+ /**
+ * Retrieve the nearby edges for a given node using quad-tree collision detection.
+ * @param nodeIds
+ * @param shouldBegin
+ */
+ private getNearEdgesForNodes(nodeIds: ID[], shouldBegin?: (edge: EdgeModel) => boolean) {
+ return uniq(nodeIds.flatMap((nodeId) => this.graph.getNearEdgesData(nodeId, shouldBegin)));
}
private getComboTreeItems(selectedNodeIds: ID[]) {
@@ -231,18 +222,13 @@ export class DragNode extends Behavior {
const beginDeltaY = Math.abs(this.pointerDown.y - event.canvas.y);
if (beginDeltaX < 1 && beginDeltaY < 1) return;
- const enableTransient =
- this.options.enableTransient && this.graph.rendererType !== 'webgl-3d';
+ const enableTransient = this.options.enableTransient && this.graph.rendererType !== 'webgl-3d';
// pointerDown + first move = dragging
if (!this.dragging) {
this.dragging = true;
const currentNodeId = event.itemId;
- this.selectedNodeIds = this.graph.findIdByState(
- 'node',
- this.options.selectedState,
- true,
- );
+ this.selectedNodeIds = this.graph.findIdByState('node', this.options.selectedState, true);
// If current node is selected, drag all the selected nodes together.
// Otherwise drag current node.
@@ -275,46 +261,28 @@ export class DragNode extends Behavior {
// Hide related edge.
if (this.options.hideRelatedEdges && !enableTransient) {
- this.hiddenComboTreeItems = this.getComboTreeItems(
- this.selectedNodeIds,
- );
- this.hiddenEdges = this.getRelatedEdges(
- this.selectedNodeIds,
- this.hiddenComboTreeItems,
- );
+ this.hiddenComboTreeItems = this.getComboTreeItems(this.selectedNodeIds);
+ this.hiddenEdges = this.getRelatedEdges(this.selectedNodeIds, this.hiddenComboTreeItems);
this.hiddenRelatedNodes = this.getRelatedNodes(this.selectedNodeIds);
this.graph.executeWithNoStack(() => {
const hiddenEdgeIds = this.hiddenEdges.map((edge) => edge.id);
hiddenEdgeIds.forEach((edgeId) => {
- this.hiddenShapeCache.set(
- edgeId,
- this.graph.getItemVisibleShapeIds(edgeId),
- );
+ this.hiddenShapeCache.set(edgeId, this.graph.getItemVisibleShapeIds(edgeId));
});
this.graph.hideItem(hiddenEdgeIds, {
disableAnimate: true,
});
- const hiddenRelatedNodeIds = this.hiddenRelatedNodes.map(
- (node) => node.id,
- );
+ const hiddenRelatedNodeIds = this.hiddenRelatedNodes.map((node) => node.id);
hiddenRelatedNodeIds.forEach((nodeId) => {
- this.hiddenShapeCache.set(
- nodeId,
- this.graph.getItemVisibleShapeIds(nodeId),
- );
+ this.hiddenShapeCache.set(nodeId, this.graph.getItemVisibleShapeIds(nodeId));
});
this.graph.hideItem(hiddenRelatedNodeIds, {
disableAnimate: true,
keepRelated: true,
});
- const hiddenComboTreeItemIds = this.hiddenComboTreeItems.map(
- (child) => child.id,
- );
+ const hiddenComboTreeItemIds = this.hiddenComboTreeItems.map((child) => child.id);
hiddenComboTreeItemIds.forEach((itemId) => {
- this.hiddenShapeCache.set(
- itemId,
- this.graph.getItemVisibleShapeIds(itemId),
- );
+ this.hiddenShapeCache.set(itemId, this.graph.getItemVisibleShapeIds(itemId));
});
this.graph.hideItem(
this.hiddenComboTreeItems.map((child) => child.id),
@@ -328,14 +296,9 @@ export class DragNode extends Behavior {
// Draw transient nodes and edges.
if (enableTransient) {
// Draw transient edges and nodes.
- this.hiddenComboTreeItems = this.getComboTreeItems(
- this.selectedNodeIds,
- );
-
- this.hiddenEdges = this.getRelatedEdges(
- this.selectedNodeIds,
- this.hiddenComboTreeItems,
- );
+ this.hiddenComboTreeItems = this.getComboTreeItems(this.selectedNodeIds);
+
+ this.hiddenEdges = this.getRelatedEdges(this.selectedNodeIds, this.hiddenComboTreeItems);
this.hiddenRelatedNodes = this.getRelatedNodes(this.selectedNodeIds);
this.selectedNodeIds.forEach((nodeId) => {
// draw the nodes' transients and their ancestor combos' transisents
@@ -350,42 +313,26 @@ export class DragNode extends Behavior {
// Hide original edges and nodes. They will be restored when pointerup.
this.graph.executeWithNoStack(() => {
this.selectedNodeIds.forEach((itemId) => {
- this.hiddenShapeCache.set(
- itemId,
- this.graph.getItemVisibleShapeIds(itemId),
- );
+ this.hiddenShapeCache.set(itemId, this.graph.getItemVisibleShapeIds(itemId));
});
this.graph.hideItem(this.selectedNodeIds, { disableAnimate: true });
const hiddenEdgeIds = this.hiddenEdges.map((edge) => edge.id);
hiddenEdgeIds.forEach((itemId) => {
- this.hiddenShapeCache.set(
- itemId,
- this.graph.getItemVisibleShapeIds(itemId),
- );
+ this.hiddenShapeCache.set(itemId, this.graph.getItemVisibleShapeIds(itemId));
});
this.graph.hideItem(hiddenEdgeIds, { disableAnimate: true });
- const hiddenRelatedNodeIds = this.hiddenRelatedNodes.map(
- (node) => node.id,
- );
+ const hiddenRelatedNodeIds = this.hiddenRelatedNodes.map((node) => node.id);
hiddenRelatedNodeIds.forEach((itemId) => {
- this.hiddenShapeCache.set(
- itemId,
- this.graph.getItemVisibleShapeIds(itemId),
- );
+ this.hiddenShapeCache.set(itemId, this.graph.getItemVisibleShapeIds(itemId));
});
this.graph.hideItem(hiddenRelatedNodeIds, {
disableAnimate: true,
keepRelated: true,
});
- const hiddenComboTreeItemIds = this.hiddenComboTreeItems.map(
- (combo) => combo.id,
- );
+ const hiddenComboTreeItemIds = this.hiddenComboTreeItems.map((combo) => combo.id);
hiddenComboTreeItemIds.forEach((itemId) => {
- this.hiddenShapeCache.set(
- itemId,
- this.graph.getItemVisibleShapeIds(itemId),
- );
+ this.hiddenShapeCache.set(itemId, this.graph.getItemVisibleShapeIds(itemId));
});
this.graph.hideItem(
this.hiddenComboTreeItems.map((combo) => combo.id),
@@ -398,11 +345,7 @@ export class DragNode extends Behavior {
// Throttle moving.
if (this.options.throttle > 0) {
- this.throttledMoveNodes = throttle(
- this.moveNodes,
- this.options.throttle,
- { leading: true, trailing: true },
- );
+ this.throttledMoveNodes = throttle(this.moveNodes, this.options.throttle, { leading: true, trailing: true });
} else {
this.throttledMoveNodes = this.moveNodes;
}
@@ -415,20 +358,17 @@ export class DragNode extends Behavior {
* When dragging nodes, if nodes are set to `preventPolylineEdgeOverlap`, identity nearby edges and dynamically update them
*/
if (this.dragging && enableTransient) {
- const preventPolylineOverlapNodeIds = this.selectedNodeIds.filter(
- (nodeId) => {
- const innerModel = this.graph.getNodeData(nodeId);
- return isPointPreventPolylineOverlap(innerModel);
- },
- );
+ const preventPolylineOverlapNodeIds = this.selectedNodeIds.filter((nodeId) => {
+ const innerModel = this.graph.getNodeData(nodeId);
+ return isPointPreventPolylineOverlap(innerModel);
+ });
if (preventPolylineOverlapNodeIds.length) {
const hiddenEdgesIds = this.hiddenEdges.map((edge) => edge.id);
this.hiddenNearEdgesCache = this.hiddenNearEdges;
- this.hiddenNearEdges = this.getNearEdgesForNodes(
- preventPolylineOverlapNodeIds,
- (edge) => isPolylineWithObstacleAvoidance(edge),
+ this.hiddenNearEdges = this.getNearEdgesForNodes(preventPolylineOverlapNodeIds, (edge) =>
+ isPolylineWithObstacleAvoidance(edge),
).filter((edge) => !hiddenEdgesIds.includes(edge.id));
const hiddenNearEdgesIds = this.hiddenNearEdges.map((edge) => edge.id);
@@ -448,10 +388,7 @@ export class DragNode extends Behavior {
const hiddenNearEdgeIds = this.hiddenNearEdges.map((edge) => edge.id);
hiddenNearEdgeIds.forEach((itemId) => {
- this.hiddenShapeCache.set(
- itemId,
- this.graph.getItemVisibleShapeIds(itemId),
- );
+ this.hiddenShapeCache.set(itemId, this.graph.getItemVisibleShapeIds(itemId));
});
this.graph.hideItem(hiddenNearEdgeIds, { disableAnimate: true });
}
@@ -462,24 +399,18 @@ export class DragNode extends Behavior {
return;
}
- // @ts-ignore FIXME: type
+ // @ts-expect-error FIXME: type
const pointerEvent = event as PointerEvent;
- // @ts-ignore FIXME: Type
+ // @ts-expect-error FIXME: Type
const deltaX = pointerEvent.canvas.x - this.originX;
- // @ts-ignore FIXME: Type
+ // @ts-expect-error FIXME: Type
const deltaY = pointerEvent.canvas.y - this.originY;
if (this.options.enableDelegate) {
this.moveDelegate(deltaX, deltaY);
} else {
- const enableTransient =
- this.options.enableTransient && this.graph.rendererType !== 'webgl-3d';
- this.throttledMoveNodes(
- deltaX,
- deltaY,
- enableTransient,
- !this.options.updateComboStructure,
- );
+ const enableTransient = this.options.enableTransient && this.graph.rendererType !== 'webgl-3d';
+ this.throttledMoveNodes(deltaX, deltaY, enableTransient, !this.options.updateComboStructure);
}
}
@@ -516,12 +447,7 @@ export class DragNode extends Behavior {
};
});
const positions = [...this.originPositions];
- this.graph.updateNodePosition(
- positionChanges,
- upsertAncestors,
- true,
- () => callback?.(positions),
- );
+ this.graph.updateNodePosition(positionChanges, upsertAncestors, true, () => callback?.(positions));
}
}
@@ -535,18 +461,10 @@ export class DragNode extends Behavior {
};
public moveDelegate(deltaX: number, deltaY: number) {
- const x1 = Math.min(
- ...this.originPositions.map((position) => position.minX),
- );
- const y1 = Math.min(
- ...this.originPositions.map((position) => position.minY),
- );
- const x2 = Math.max(
- ...this.originPositions.map((position) => position.maxX),
- );
- const y2 = Math.max(
- ...this.originPositions.map((position) => position.maxY),
- );
+ const x1 = Math.min(...this.originPositions.map((position) => position.minX));
+ const y1 = Math.min(...this.originPositions.map((position) => position.minY));
+ const x2 = Math.max(...this.originPositions.map((position) => position.maxX));
+ const y2 = Math.max(...this.originPositions.map((position) => position.maxY));
this.graph.drawTransient('rect', DELEGATE_SHAPE_ID, {
style: {
x: x1 + deltaX,
@@ -621,8 +539,7 @@ export class DragNode extends Behavior {
});
this.hiddenComboTreeItems = [];
}
- const enableTransient =
- this.options.enableTransient && this.graph.rendererType !== 'webgl-3d';
+ const enableTransient = this.options.enableTransient && this.graph.rendererType !== 'webgl-3d';
if (enableTransient) {
this.originPositions.concat(positions).forEach((pos) => {
this.graph.showItem(pos.id, {
@@ -649,15 +566,14 @@ export class DragNode extends Behavior {
this.pointerDown = undefined;
this.dragging = false;
this.selectedNodeIds = [];
- const enableTransient =
- this.options.enableTransient && this.graph.rendererType !== 'webgl-3d';
+ const enableTransient = this.options.enableTransient && this.graph.rendererType !== 'webgl-3d';
// If transient or delegate was enabled, move the real nodes.
// if (enableTransient || this.options.enableDelegate) {
- // @ts-ignore FIXME: type
+ // @ts-expect-error FIXME: type
const pointerEvent = event as PointerEvent;
- // @ts-ignore FIXME: Type
+ // @ts-expect-error FIXME: Type
const deltaX = pointerEvent.canvas.x - this.originX + 0.01;
- // @ts-ignore FIXME: Type
+ // @ts-expect-error FIXME: Type
const deltaY = pointerEvent.canvas.y - this.originY + 0.01;
this.moveNodes(
deltaX,
@@ -700,8 +616,7 @@ export class DragNode extends Behavior {
this.clearTransientItems(this.originPositions);
this.restoreHiddenItems();
- const enableTransient =
- this.options.enableTransient && this.graph.rendererType !== 'webgl-3d';
+ const enableTransient = this.options.enableTransient && this.graph.rendererType !== 'webgl-3d';
// Restore node positions.
if (!enableTransient && !this.options.enableDelegate) {
const positionChanges = this.originPositions.map(({ id, x, y }) => {
@@ -714,23 +629,16 @@ export class DragNode extends Behavior {
}
public async onDropNode(event: IG6GraphEvent) {
- const elements = await this.graph.canvas.document.elementsFromPoint(
- event.canvas.x,
- event.canvas.y,
- );
+ const elements = await this.graph.canvas.document.elementsFromPoint(event.canvas.x, event.canvas.y);
const draggingIds = this.originPositions.map(({ id }) => id);
const currentIds = elements
- // @ts-ignore TODO: G type
+ // @ts-expect-error TODO: G type
.map((ele) => ele.parentNode.getAttribute?.('data-item-id'))
.filter((id) => id !== undefined && !draggingIds.includes(id));
// the top item which is not in draggingIds
- const dropId = currentIds.find(
- (id) => this.graph.getComboData(id) || this.graph.getNodeData(id),
- );
+ const dropId = currentIds.find((id) => this.graph.getComboData(id) || this.graph.getNodeData(id));
// drop on a node A, move the dragged node to the same parent of A
- const newParentId = this.graph.getNodeData(dropId)
- ? this.graph.getNodeData(dropId).data.parentId
- : dropId;
+ const newParentId = this.graph.getNodeData(dropId) ? this.graph.getNodeData(dropId).data.parentId : dropId;
this.graph.startHistoryBatch();
this.originPositions.forEach(({ id }) => {
@@ -765,22 +673,15 @@ export class DragNode extends Behavior {
}
public async onDropCanvas(event: IG6GraphEvent) {
- const elements = await this.graph.canvas.document.elementsFromPoint(
- event.canvas.x,
- event.canvas.y,
- );
+ const elements = await this.graph.canvas.document.elementsFromPoint(event.canvas.x, event.canvas.y);
const draggingIds = this.originPositions.map(({ id }) => id);
const currentIds = elements
- // @ts-ignore TODO: G type
+ // @ts-expect-error TODO: G type
.map((ele) => ele.parentNode.getAttribute?.('data-item-id'))
.filter((id) => id !== undefined && !draggingIds.includes(id));
// the top item which is not in draggingIds
- const dropId = currentIds.find(
- (id) => this.graph.getComboData(id) || this.graph.getNodeData(id),
- );
- const parentId = this.graph.getNodeData(dropId)
- ? this.graph.getNodeData(dropId).data.parentId
- : dropId;
+ const dropId = currentIds.find((id) => this.graph.getComboData(id) || this.graph.getNodeData(id));
+ const parentId = this.graph.getNodeData(dropId) ? this.graph.getNodeData(dropId).data.parentId : dropId;
this.graph.startHistoryBatch();
this.onPointerUp(event);
const nodeToUpdate = [];
diff --git a/packages/g6/src/stdlib/behavior/hover-activate.ts b/packages/g6/src/stdlib/behavior/hover-activate.ts
index 08dc4f9fed5..dd94b3693f8 100644
--- a/packages/g6/src/stdlib/behavior/hover-activate.ts
+++ b/packages/g6/src/stdlib/behavior/hover-activate.ts
@@ -1,7 +1,7 @@
import { ID } from '@antv/graphlib';
-import { ITEM_TYPE } from '../../types/item';
import { Behavior } from '../../types/behavior';
import { IG6GraphEvent } from '../../types/event';
+import { ITEM_TYPE } from '../../types/item';
export interface HoverActivateOptions {
/**
diff --git a/packages/g6/src/stdlib/behavior/index.ts b/packages/g6/src/stdlib/behavior/index.ts
index 900b9f59eee..762c0615bea 100644
--- a/packages/g6/src/stdlib/behavior/index.ts
+++ b/packages/g6/src/stdlib/behavior/index.ts
@@ -1,18 +1,18 @@
export * from './activate-relations';
export * from './brush-select';
export * from './click-select';
-export * from './collapse-expand-tree';
export * from './collapse-expand-combo';
+export * from './collapse-expand-tree';
+export * from './create-edge';
export * from './drag-canvas';
-export * from './drag-node';
export * from './drag-combo';
-export * from './zoom-canvas';
+export * from './drag-node';
export * from './hover-activate';
export * from './lasso-select';
export * from './orbit-canvas-3d';
export * from './rotate-canvas-3d';
+export * from './scroll-canvas';
+export * from './shortcuts-call';
export * from './track-canvas-3d';
+export * from './zoom-canvas';
export * from './zoom-canvas-3d';
-export * from './create-edge';
-export * from './shortcuts-call';
-export * from './scroll-canvas';
diff --git a/packages/g6/src/stdlib/behavior/lasso-select.ts b/packages/g6/src/stdlib/behavior/lasso-select.ts
index 6c9c455a786..052d5baf6c6 100644
--- a/packages/g6/src/stdlib/behavior/lasso-select.ts
+++ b/packages/g6/src/stdlib/behavior/lasso-select.ts
@@ -1,9 +1,9 @@
import { DisplayObject } from '@antv/g';
import { ID } from '@antv/graphlib';
+import { IGraph } from '../../types';
+import { Point } from '../../types/common';
import { IG6GraphEvent } from '../../types/event';
import lassoSelector from '../selector/lasso';
-import { Point } from '../../types/common';
-import { IGraph } from '../../types';
import { BrushSelect } from './brush-select';
const ALLOWED_TRIGGERS = ['drag', 'shift', 'ctrl', 'alt', 'meta'] as const;
@@ -11,7 +11,7 @@ const LASSO_SHAPE_ID = 'g6-lasso-select-brush-shape';
type Trigger = (typeof ALLOWED_TRIGGERS)[number];
export class LassoSelect extends BrushSelect {
- brush: DisplayObject;
+ declare brush: DisplayObject;
selectedIds: {
nodes: ID[];
edges: ID[];
@@ -22,9 +22,9 @@ export class LassoSelect extends BrushSelect {
combos: [],
};
points: Point[] = [];
- beginPoint: Point;
- mousedown: boolean;
- graph: IGraph;
+ declare beginPoint: Point;
+ declare mousedown: boolean;
+ declare graph: IGraph;
public onMouseDown = (event: IG6GraphEvent) => {
this.points = [];
diff --git a/packages/g6/src/stdlib/behavior/rotate-canvas-3d.ts b/packages/g6/src/stdlib/behavior/rotate-canvas-3d.ts
index 8c0ed0b2e3a..a59a6a25221 100644
--- a/packages/g6/src/stdlib/behavior/rotate-canvas-3d.ts
+++ b/packages/g6/src/stdlib/behavior/rotate-canvas-3d.ts
@@ -1,7 +1,7 @@
import { ICamera } from '@antv/g';
import { Behavior } from '../../types/behavior';
-import { IG6GraphEvent } from '../../types/event';
import { Point } from '../../types/common';
+import { IG6GraphEvent } from '../../types/event';
const VALID_TRIGGERS = ['drag', 'directionKeys'];
diff --git a/packages/g6/src/stdlib/behavior/scroll-canvas.ts b/packages/g6/src/stdlib/behavior/scroll-canvas.ts
index ab866d500c2..4be2fb0415a 100644
--- a/packages/g6/src/stdlib/behavior/scroll-canvas.ts
+++ b/packages/g6/src/stdlib/behavior/scroll-canvas.ts
@@ -1,6 +1,6 @@
import { isBoolean, isNumber, isObject } from '@antv/util';
-import { Behavior } from '../../types/behavior';
import { ID, IG6GraphEvent } from '../../types';
+import { Behavior } from '../../types/behavior';
interface ScrollCanvasOptions {
/**
@@ -21,7 +21,8 @@ interface ScrollCanvasOptions {
* Use ```'ctrl'``` by default;
*/
zoomKey?: string | string[];
- /** Switch to zooming while pressing the key and wheeling. This option allows you to control the zoom ratio for each event.
+ /**
+ * Switch to zooming while pressing the key and wheeling. This option allows you to control the zoom ratio for each event.
* Use ```'0.05'``` by default;
*/
zoomRatio?: number;
@@ -84,9 +85,7 @@ export class ScrollCanvas extends Behavior {
if (zoomKeys.includes('control')) zoomKeys.push('ctrl');
const keyDown = zoomKeys.some((ele) => ev[`${ele}Key`]);
- const nativeEvent = ev.nativeEvent as
- | (WheelEvent & { wheelDelta: number })
- | undefined;
+ const nativeEvent = ev.nativeEvent as (WheelEvent & { wheelDelta: number }) | undefined;
if (keyDown) {
const canvas = graph.canvas;
@@ -205,8 +204,7 @@ export class ScrollCanvas extends Behavior {
const { itemType } = evt;
const { allowDragOnItem } = this.options;
const targetIsCanvas = itemType === 'canvas';
- if (isBoolean(allowDragOnItem) && !allowDragOnItem && !targetIsCanvas)
- return false;
+ if (isBoolean(allowDragOnItem) && !allowDragOnItem && !targetIsCanvas) return false;
if (isObject(allowDragOnItem)) {
const { node, edge, combo } = allowDragOnItem;
if (!node && itemType === 'node') return false;
@@ -218,13 +216,10 @@ export class ScrollCanvas extends Behavior {
private hideShapes() {
const { graph, options } = this;
- const { tileBehavior: graphBehaviorOptimize, tileBehaviorSize = 1000 } =
- graph.getSpecification().optimize || {};
+ const { tileBehavior: graphBehaviorOptimize, tileBehaviorSize = 1000 } = graph.getSpecification().optimize || {};
const { optimizeZoom } = options;
const optimize = this.options.enableOptimize || graphBehaviorOptimize;
- const shouldOptimize = isNumber(optimize)
- ? graph.getAllNodesData().length > optimize
- : optimize;
+ const shouldOptimize = isNumber(optimize) ? graph.getAllNodesData().length > optimize : optimize;
if (shouldOptimize) {
const currentZoom = graph.getZoom();
const newHiddenEdgeIds = graph
@@ -247,10 +242,7 @@ export class ScrollCanvas extends Behavior {
let requestId;
const sectionNum = Math.ceil(newHiddenNodeIds.length / tileBehaviorSize);
const sections = Array.from({ length: sectionNum }, (v, i) =>
- newHiddenNodeIds.slice(
- i * tileBehaviorSize,
- i * tileBehaviorSize + tileBehaviorSize,
- ),
+ newHiddenNodeIds.slice(i * tileBehaviorSize, i * tileBehaviorSize + tileBehaviorSize),
);
const update = () => {
if (!sections.length) {
@@ -283,12 +275,9 @@ export class ScrollCanvas extends Behavior {
return;
}
- const { tileBehavior: graphBehaviorOptimize, tileBehaviorSize = 1000 } =
- graph.getSpecification().optimize || {};
+ const { tileBehavior: graphBehaviorOptimize, tileBehaviorSize = 1000 } = graph.getSpecification().optimize || {};
const optimize = this.options.enableOptimize || graphBehaviorOptimize;
- const shouldOptimize = isNumber(optimize)
- ? graph.getAllNodesData().length > optimize
- : optimize;
+ const shouldOptimize = isNumber(optimize) ? graph.getAllNodesData().length > optimize : optimize;
if (!shouldOptimize) {
this.hiddenEdgeIds = this.hiddenNodeIds = [];
return;
@@ -298,10 +287,7 @@ export class ScrollCanvas extends Behavior {
const hiddenIds = [...hiddenNodeIds, ...hiddenEdgeIds];
const sectionNum = Math.ceil(hiddenIds.length / tileBehaviorSize);
const sections = Array.from({ length: sectionNum }, (v, i) =>
- hiddenIds.slice(
- i * tileBehaviorSize,
- i * tileBehaviorSize + tileBehaviorSize,
- ),
+ hiddenIds.slice(i * tileBehaviorSize, i * tileBehaviorSize + tileBehaviorSize),
);
const update = () => {
if (!sections.length) {
@@ -321,21 +307,17 @@ export class ScrollCanvas extends Behavior {
const ALLOW_EVENTS = ['shift', 'ctrl', 'alt', 'control', 'meta'];
+/**
+ *
+ * @param zoomKey
+ */
function initZoomKey(zoomKey?: string | string[]) {
- const zoomKeys = zoomKey
- ? Array.isArray(zoomKey)
- ? zoomKey
- : [zoomKey]
- : [];
+ const zoomKeys = zoomKey ? (Array.isArray(zoomKey) ? zoomKey : [zoomKey]) : [];
const validZoomKeys = zoomKeys.filter((zoomKey) => {
const keyIsValid = ALLOW_EVENTS.includes(zoomKey);
if (!keyIsValid)
- console.warn(
- `Invalid zoomKey: ${zoomKey}, please use a valid zoomKey: ${JSON.stringify(
- ALLOW_EVENTS,
- )}`,
- );
+ console.warn(`Invalid zoomKey: ${zoomKey}, please use a valid zoomKey: ${JSON.stringify(ALLOW_EVENTS)}`);
return keyIsValid;
});
diff --git a/packages/g6/src/stdlib/behavior/shortcuts-call.ts b/packages/g6/src/stdlib/behavior/shortcuts-call.ts
index ea0abd433c1..4f8ed61f296 100644
--- a/packages/g6/src/stdlib/behavior/shortcuts-call.ts
+++ b/packages/g6/src/stdlib/behavior/shortcuts-call.ts
@@ -44,9 +44,7 @@ export class ShortcutsCall extends Behavior {
super(Object.assign({}, DEFAULT_OPTIONS, options));
// Validate options
if (options.trigger && !ALLOW_TRIGGERS.includes(options.trigger)) {
- console.warn(
- `G6: Invalid trigger option "${options.trigger}" for shortcuts-call behavior!`,
- );
+ console.warn(`G6: Invalid trigger option "${options.trigger}" for shortcuts-call behavior!`);
this.options.trigger = DEFAULT_OPTIONS.trigger;
}
if (options.combinedKey === this.options.trigger) {
@@ -82,9 +80,7 @@ export class ShortcutsCall extends Behavior {
}
if (!graph[functionName]) {
- console.warn(
- `G6: Invalid functionName option: "${functionName}" for shortcuts-call behavior!`,
- );
+ console.warn(`G6: Invalid functionName option: "${functionName}" for shortcuts-call behavior!`);
return {};
}
if (!this.triggerKeydown) return;
diff --git a/packages/g6/src/stdlib/behavior/zoom-canvas-3d.ts b/packages/g6/src/stdlib/behavior/zoom-canvas-3d.ts
index 19773f51761..d74f0df77d2 100644
--- a/packages/g6/src/stdlib/behavior/zoom-canvas-3d.ts
+++ b/packages/g6/src/stdlib/behavior/zoom-canvas-3d.ts
@@ -1,9 +1,5 @@
-import { ID } from '@antv/graphlib';
-import { debounce, uniq } from '@antv/util';
-import { EdgeModel } from '../../types';
import { Behavior } from '../../types/behavior';
import { IG6GraphEvent } from '../../types/event';
-import { Point } from '../../types/common';
const VALID_TRIGGERS = ['wheel', 'upDownKeys'];
@@ -104,24 +100,14 @@ export class ZoomCanvas3D extends Behavior {
public onWheel(event) {
const { graph, options } = this;
- const {
- secondaryKey,
- triggerOnItems,
- eventName,
- minZoom,
- maxZoom,
- sensitivity = 1,
- shouldBegin,
- } = options;
+ const { secondaryKey, triggerOnItems, eventName, minZoom, maxZoom, sensitivity = 1, shouldBegin } = options;
if (event.itemId && !triggerOnItems) return;
if (!shouldBegin(event)) return;
if (secondaryKey && !this.keydown) return;
const camera = graph.canvas.getCamera();
const sign = event.deltaY > 0 ? 1 : -1;
const currentDistance = camera.getDistance();
- const dolly =
- ((100 * sign * sensitivity) / currentDistance) *
- Math.sqrt(currentDistance);
+ const dolly = ((100 * sign * sensitivity) / currentDistance) * Math.sqrt(currentDistance);
const toDistance = currentDistance + dolly;
const azimuth = camera.getAzimuth();
const isFlipped = azimuth < 90 && azimuth > -90 ? 1 : -1;
@@ -129,11 +115,7 @@ export class ZoomCanvas3D extends Behavior {
const cameraFrontOfFocalPoint = isFlipped * distancePositive > 0;
// zoom out constraint
- if (
- dolly > 0 &&
- cameraFrontOfFocalPoint &&
- toDistance > (1 / minZoom) * 200
- ) {
+ if (dolly > 0 && cameraFrontOfFocalPoint && toDistance > (1 / minZoom) * 200) {
return;
}
// zoom in constraint
diff --git a/packages/g6/src/stdlib/behavior/zoom-canvas.ts b/packages/g6/src/stdlib/behavior/zoom-canvas.ts
index 59b83f561d5..9a4b75b6731 100644
--- a/packages/g6/src/stdlib/behavior/zoom-canvas.ts
+++ b/packages/g6/src/stdlib/behavior/zoom-canvas.ts
@@ -1,4 +1,4 @@
-import { isNumber, isBoolean } from '@antv/util';
+import { isBoolean, isNumber } from '@antv/util';
import { ID, IG6GraphEvent } from '../../types';
import { Behavior } from '../../types/behavior';
@@ -48,10 +48,10 @@ export interface ZoomCanvasOptions {
shouldBegin?: (event: IG6GraphEvent) => boolean;
/**
* Whether to fix the stroke thickness, text size, overall size, etc. of selected elements. false by default.
- * @property {boolean} fixAll: fix the overall size of the element, higher priority than fixSelectedItems.fixLineWidth and fixSelectedItems.fixLabel;
- * @property {boolean} fixLineWidth: fix the stroke thickness of keyShape;
- * @property {boolean} fixLabel: fix the text size of labelShape, labelBackgroundShape;
- * @property {string} fixState: the state of the element to be fixed. Default is `selected` ;
+ * - fixAll: fix the overall size of the element, higher priority than fixSelectedItems.fixLineWidth and fixSelectedItems.fixLabel;
+ * - fixLineWidth: fix the stroke thickness of keyShape;
+ * - fixLabel: fix the text size of labelShape, labelBackgroundShape;
+ * - fixState: the state of the element to be fixed. Default is `selected` ;
*/
fixSelectedItems:
| boolean
@@ -102,9 +102,7 @@ export class ZoomCanvas extends Behavior {
constructor(options: Partial) {
const finalOptions = Object.assign({}, DEFAULT_OPTIONS, options);
if (!VALID_TRIGGERS.includes(finalOptions.trigger)) {
- console.warn(
- `The trigger ${finalOptions.trigger} is not valid, 'wheel' will take effect.`,
- );
+ console.warn(`The trigger ${finalOptions.trigger} is not valid, 'wheel' will take effect.`);
finalOptions.trigger = 'wheel';
}
const { fixSelectedItems } = finalOptions;
@@ -115,9 +113,7 @@ export class ZoomCanvas extends Behavior {
};
}
if (!isBoolean(fixSelectedItems)) {
- if (!fixSelectedItems.fixState)
- // @ts-ignore
- finalOptions.fixSelectedItems.fixState = 'selected';
+ if (!fixSelectedItems.fixState) fixSelectedItems.fixState = 'selected';
}
super(finalOptions);
}
@@ -149,15 +145,9 @@ export class ZoomCanvas extends Behavior {
private hideShapes() {
const { graph } = this;
- const { tileBehavior: graphBehaviorOptimize, tileBehaviorSize = 1000 } =
- graph.getSpecification().optimize || {};
- const optimize =
- this.options.enableOptimize !== undefined
- ? this.options.enableOptimize
- : graphBehaviorOptimize;
- const shouldOptimize = isNumber(optimize)
- ? graph.getAllNodesData().length > optimize
- : optimize;
+ const { tileBehavior: graphBehaviorOptimize, tileBehaviorSize = 1000 } = graph.getSpecification().optimize || {};
+ const optimize = this.options.enableOptimize !== undefined ? this.options.enableOptimize : graphBehaviorOptimize;
+ const shouldOptimize = isNumber(optimize) ? graph.getAllNodesData().length > optimize : optimize;
if (shouldOptimize) {
this.hiddenEdgeIds = graph
.getAllEdgesData()
@@ -171,10 +161,7 @@ export class ZoomCanvas extends Behavior {
const hiddenIds = [...this.hiddenNodeIds];
const sectionNum = Math.ceil(hiddenIds.length / tileBehaviorSize);
const sections = Array.from({ length: sectionNum }, (v, i) =>
- hiddenIds.slice(
- i * tileBehaviorSize,
- i * tileBehaviorSize + tileBehaviorSize,
- ),
+ hiddenIds.slice(i * tileBehaviorSize, i * tileBehaviorSize + tileBehaviorSize),
);
const update = () => {
if (!sections.length && this.tileRequestId) {
@@ -194,15 +181,9 @@ export class ZoomCanvas extends Behavior {
private endZoom() {
const { graph, hiddenEdgeIds = [], hiddenNodeIds } = this;
- const { tileBehavior: graphBehaviorOptimize, tileBehaviorSize = 1000 } =
- graph.getSpecification().optimize || {};
- const optimize =
- this.options.enableOptimize !== undefined
- ? this.options.enableOptimize
- : graphBehaviorOptimize;
- const shouldOptimize = isNumber(optimize)
- ? graph.getAllNodesData().length > optimize
- : optimize;
+ const { tileBehavior: graphBehaviorOptimize, tileBehaviorSize = 1000 } = graph.getSpecification().optimize || {};
+ const optimize = this.options.enableOptimize !== undefined ? this.options.enableOptimize : graphBehaviorOptimize;
+ const shouldOptimize = isNumber(optimize) ? graph.getAllNodesData().length > optimize : optimize;
this.zooming = false;
if (shouldOptimize) {
if (this.tileRequestId) {
@@ -213,10 +194,7 @@ export class ZoomCanvas extends Behavior {
const hiddenIds = [...hiddenNodeIds, ...hiddenEdgeIds];
const sectionNum = Math.ceil(hiddenIds.length / tileBehaviorSize);
const sections = Array.from({ length: sectionNum }, (v, i) =>
- hiddenIds.slice(
- i * tileBehaviorSize,
- i * tileBehaviorSize + tileBehaviorSize,
- ),
+ hiddenIds.slice(i * tileBehaviorSize, i * tileBehaviorSize + tileBehaviorSize),
);
const update = () => {
if (!sections.length && this.tileRequestId) {
@@ -239,23 +217,11 @@ export class ZoomCanvas extends Behavior {
public onWheel(event) {
const { graph, keydown } = this;
const { deltaY, client, itemId } = event;
- const {
- eventName,
- sensitivity,
- secondaryKey,
- triggerOnItems,
- minZoom,
- maxZoom,
- shouldBegin,
- } = this.options;
+ const { eventName, sensitivity, secondaryKey, triggerOnItems, minZoom, maxZoom, shouldBegin } = this.options;
// TODO: CANVAS
const isOnItem = itemId && itemId !== 'CANVAS';
- if (
- (secondaryKey && !keydown) ||
- (isOnItem && !triggerOnItems) ||
- !shouldBegin(event)
- ) {
+ if ((secondaryKey && !keydown) || (isOnItem && !triggerOnItems) || !shouldBegin(event)) {
this.endZoom();
return;
}
@@ -268,8 +234,7 @@ export class ZoomCanvas extends Behavior {
this.zooming = true;
}
- const { tileBehavior: graphBehaviorOptimize } =
- graph.getSpecification().optimize || {};
+ const { tileBehavior: graphBehaviorOptimize } = graph.getSpecification().optimize || {};
const shouldDebounce =
typeof graphBehaviorOptimize === 'boolean'
@@ -277,11 +242,7 @@ export class ZoomCanvas extends Behavior {
: graph.getAllNodesData().length > graphBehaviorOptimize;
const now = Date.now();
- if (
- shouldDebounce &&
- this.lastWheelTriggerTime &&
- now - this.lastWheelTriggerTime < WHEEL_DURATION / 5
- ) {
+ if (shouldDebounce && this.lastWheelTriggerTime && now - this.lastWheelTriggerTime < WHEEL_DURATION / 5) {
return;
}
@@ -375,8 +336,7 @@ export class ZoomCanvas extends Behavior {
const { group } = item;
const transform = group.style.transform;
if (!this.zoomCache.balanceRatio.has(id)) {
- const oriBalanceRatio =
- Number(transform?.match(/scale\(([\d.]+),/)?.[1]) || 1;
+ const oriBalanceRatio = Number(transform?.match(/scale\(([\d.]+),/)?.[1]) || 1;
this.zoomCache.balanceRatio.set(id, oriBalanceRatio);
}
const balanceRatioCache = this.zoomCache.balanceRatio.get(id);
@@ -399,14 +359,7 @@ export class ZoomCanvas extends Behavior {
public onKeydown(event) {
const { key } = event;
- const {
- secondaryKey,
- trigger,
- speedUpKey,
- eventName,
- sensitivity,
- shouldBegin,
- } = this.options;
+ const { secondaryKey, trigger, speedUpKey, eventName, sensitivity, shouldBegin } = this.options;
if (secondaryKey && secondaryKey === key.toLowerCase()) {
this.keydown = true;
}
diff --git a/packages/g6/src/stdlib/data/index.ts b/packages/g6/src/stdlib/data/index.ts
index c9164b2f24a..0cfaa0710a3 100644
--- a/packages/g6/src/stdlib/data/index.ts
+++ b/packages/g6/src/stdlib/data/index.ts
@@ -1,4 +1,4 @@
export * from './mapNodeSize';
+export * from './processParallelEdges';
export * from './transformV4Data';
export * from './validateData';
-export * from './processParallelEdges';
diff --git a/packages/g6/src/stdlib/data/mapNodeSize.ts b/packages/g6/src/stdlib/data/mapNodeSize.ts
index d199bac77bb..bbbff688f20 100644
--- a/packages/g6/src/stdlib/data/mapNodeSize.ts
+++ b/packages/g6/src/stdlib/data/mapNodeSize.ts
@@ -1,10 +1,5 @@
+import { GraphData } from '../../types';
import { GraphCore, GraphDataChanges } from '../../types/data';
-import {
- GraphData,
- ComboUserModel,
- EdgeUserModel,
- NodeUserModel,
-} from '../../types';
/**
* Validate and format the graph data.
@@ -49,10 +44,8 @@ const handler = (
minValue = Infinity;
nodes.forEach((n) => {
nodeMap.set(n.id, n);
- if (maxValue < (n.data[field] as number))
- maxValue = n.data[field] as number;
- if (minValue > (n.data[field] as number))
- minValue = n.data[field] as number;
+ if (maxValue < (n.data[field] as number)) maxValue = n.data[field] as number;
+ if (minValue > (n.data[field] as number)) minValue = n.data[field] as number;
});
const valueRange = [minValue, maxValue];
const sizeMap = scaleNodeProp(nodes, field, valueRange, range);
@@ -76,11 +69,7 @@ const scaleNodeProp = (nodes, field, valueRange, mappedRange) => {
const dataLength = valueRange[1] - valueRange[0];
const map = new Map();
nodes.forEach((n) => {
- map.set(
- n.id,
- ((n.data[field] - valueRange[0]) * outLength) / dataLength +
- mappedRange[0],
- );
+ map.set(n.id, ((n.data[field] - valueRange[0]) * outLength) / dataLength + mappedRange[0]);
});
return map;
};
diff --git a/packages/g6/src/stdlib/data/processParallelEdges.ts b/packages/g6/src/stdlib/data/processParallelEdges.ts
index 00c834eb2d3..2fe5daf3997 100644
--- a/packages/g6/src/stdlib/data/processParallelEdges.ts
+++ b/packages/g6/src/stdlib/data/processParallelEdges.ts
@@ -1,9 +1,9 @@
import { Edge } from '@antv/graphlib';
-import { loopPosition } from '../../util/loop';
-import { EdgeUserModel, ID, GraphCore } from '../../types';
-import { uniqBy } from '../../util/array';
-import { EdgeUserModelData } from '../../types/edge';
+import { EdgeUserModel, GraphCore, ID } from '../../types';
import { GraphDataChanges } from '../../types/data';
+import { EdgeUserModelData } from '../../types/edge';
+import { uniqBy } from '../../util/array';
+import { loopPosition } from '../../util/loop';
/**
* Process edges which might overlap. For edges that share the same target and source nodes.
@@ -49,14 +49,8 @@ export const ProcessParallelEdges = (
const oldModel = graphCore?.getEdge(newModel.id);
if (!oldModel) return;
const { id, source, target } = newModel;
- if (
- (source && oldModel.source !== source) ||
- (target && oldModel.target !== target)
- ) {
- const prevParallelEdges = getParallelEdges(
- graphCore.getEdge(id),
- cacheEdges,
- );
+ if ((source && oldModel.source !== source) || (target && oldModel.target !== target)) {
+ const prevParallelEdges = getParallelEdges(graphCore.getEdge(id), cacheEdges);
edges = [...prevParallelEdges, ...edges];
}
});
@@ -98,10 +92,7 @@ export const ProcessParallelEdges = (
* @param edgeModel the data model of the edge currently under consideration
* @param allEdges the set of all edges in graph
*/
-const getParallelEdges = (
- edgeModel: EdgeUserModel,
- allEdges: Edge[],
-) => {
+const getParallelEdges = (edgeModel: EdgeUserModel, allEdges: Edge[]) => {
const { id, source, target } = edgeModel;
return allEdges.filter((edge) => {
return (
@@ -117,10 +108,7 @@ const getParallelEdges = (
* @param edges parallel edges affected by the modification
* @param options processing configuration
*/
-const calculateOffset = (
- edges: EdgeUserModel[],
- options: ParallelEdgesOptions,
-) => {
+const calculateOffset = (edges: EdgeUserModel[], options: ParallelEdgesOptions) => {
const {
offsetDiff = 15,
multiEdgeType = 'quadratic-edge',
@@ -154,15 +142,11 @@ const calculateOffset = (
const src = sedge.source;
const dst = sedge.target;
- if (
- (source === dst && target === src) ||
- (source === src && target === dst)
- ) {
+ if ((source === dst && target === src) || (source === src && target === dst)) {
edgeMap.get(sourceTarget)!.push(sedge);
processedEdgesSet.add(j);
if (source === dst && target === src) {
- reverses[`${src}|${dst}|${edgeMap.get(sourceTarget)?.length - 1}`] =
- true;
+ reverses[`${src}|${dst}|${edgeMap.get(sourceTarget)?.length - 1}`] = true;
}
}
}
@@ -186,15 +170,11 @@ const calculateOffset = (
if (singleEdgeType) current.data.type = singleEdgeType;
} else {
current.data.type = multiEdgeType;
- const sign =
- (k % 2 === 0 ? 1 : -1) *
- (reverses[`${current.source}|${current.target}|${k}`] ? -1 : 1);
+ const sign = (k % 2 === 0 ? 1 : -1) * (reverses[`${current.source}|${current.target}|${k}`] ? -1 : 1);
current.data.keyShape ||= {};
// @ts-ignore
current.data.keyShape.curveOffset =
- length % 2 === 1
- ? sign * Math.ceil(k / 2) * cod
- : sign * (Math.floor(k / 2) * cod + offsetDiff);
+ length % 2 === 1 ? sign * Math.ceil(k / 2) * cod : sign * (Math.floor(k / 2) * cod + offsetDiff);
}
}
});
diff --git a/packages/g6/src/stdlib/data/transformV4Data.ts b/packages/g6/src/stdlib/data/transformV4Data.ts
index 88f81550e1f..750ee41093d 100644
--- a/packages/g6/src/stdlib/data/transformV4Data.ts
+++ b/packages/g6/src/stdlib/data/transformV4Data.ts
@@ -1,23 +1,15 @@
import { isArray, isNumber, uniqueId } from '@antv/util';
+import { GraphData } from '../../types';
import { GraphCore, GraphDataChanges } from '../../types/data';
-import {
- GraphData,
- ComboUserModel,
- EdgeUserModel,
- NodeUserModel,
-} from '../../types';
/**
* Validate and format the graph data.
* @param data input user data.
+ * @param options validate options.
* @param graphCore the graph core stores the previous data.
* @returns formatted data.
*/
-export const TransformV4Data = (
- data: GraphDataChanges,
- options = {},
- graphCore?: GraphCore,
-): GraphDataChanges => {
+export const TransformV4Data = (data: GraphDataChanges, options = {}, graphCore?: GraphCore): GraphDataChanges => {
const { dataAdded, dataUpdated, dataRemoved } = data;
return {
dataAdded: handler(dataAdded, options, graphCore),
@@ -26,11 +18,7 @@ export const TransformV4Data = (
};
};
-const handler = (
- data: GraphData,
- options = {},
- graphCore?: GraphCore,
-): GraphData => {
+const handler = (data: GraphData, options = {}, graphCore?: GraphCore): GraphData => {
const { nodes = [], edges = [], combos = [] } = data;
const formattedNodes = nodes.map((node: any) => {
const prevNode = graphCore?.getNode(node.id);
@@ -38,23 +26,10 @@ const handler = (
...prevNode,
...node,
};
- const {
- id,
- type,
- style,
- size,
- color,
- label,
- labelCfg = {},
- icon,
- linkPoints,
- data = {},
- ...others
- } = mergedNode;
+ const { id, type, style, size, color, label, labelCfg = {}, icon, linkPoints, data = {}, ...others } = mergedNode;
const anchorShapes = [];
if (linkPoints) {
- const { top, bottom, left, right, ...otherAnchorShapeStyles } =
- linkPoints;
+ const { top, bottom, left, right, ...otherAnchorShapeStyles } = linkPoints;
Object.keys({ top, bottom, left, right }).forEach((key) => {
if (!linkPoints[key]) return;
anchorShapes.push({ position: key, ...otherAnchorShapeStyles });
@@ -173,19 +148,7 @@ const handler = (
...prevCombo,
...combo,
};
- const {
- id,
- type,
- style,
- size,
- color,
- label,
- labelCfg = {},
- icon,
- linkPoints,
- data = {},
- ...others
- } = mergedCombo;
+ const { id, type, style, size, color, label, labelCfg = {}, icon, linkPoints, data = {}, ...others } = mergedCombo;
const { style: labelStyle = {}, ...otherLabelStyle } = labelCfg;
const { background } = labelStyle;
const newCombo = {
diff --git a/packages/g6/src/stdlib/data/validateData.ts b/packages/g6/src/stdlib/data/validateData.ts
index dae4bc5da2f..673e5f38801 100644
--- a/packages/g6/src/stdlib/data/validateData.ts
+++ b/packages/g6/src/stdlib/data/validateData.ts
@@ -1,24 +1,15 @@
import { uniqueId } from '@antv/util';
+import { ComboUserModel, EdgeUserModel, GraphData, NodeUserModel } from '../../types';
import { GraphCore, GraphDataChanges } from '../../types/data';
-import {
- GraphData,
- ComboUserModel,
- EdgeUserModel,
- NodeUserModel,
-} from '../../types';
-import { deconstructData } from '../../util/data';
/**
* Validate and format the graph data which will be added.
* @param data input user data.
+ * @param options validate options.
* @param graphCore the graph core stores the previous data.
* @returns formatted data.
*/
-export const ValidateData = (
- data: GraphDataChanges,
- options = {},
- graphCore?: GraphCore,
-): GraphDataChanges => {
+export const ValidateData = (data: GraphDataChanges, options = {}, graphCore?: GraphCore): GraphDataChanges => {
const { dataAdded, dataRemoved, dataUpdated } = data;
return {
dataAdded: handler(dataAdded, options, graphCore),
@@ -27,11 +18,7 @@ export const ValidateData = (
};
};
-const handler = (
- data: GraphData,
- options = {},
- graphCore?: GraphCore,
-): GraphData => {
+const handler = (data: GraphData, options = {}, graphCore?: GraphCore): GraphData => {
const { nodes, edges, combos } = data;
const idMap = new Map();
const nodeIdMap = new Map();
@@ -52,9 +39,9 @@ const handler = (
}
if (idMap.has(item.id)) {
console.error(
- `Unique global id is neccessary for graph nodes/edges/combos. The ${type} ${JSON.stringify(
- item,
- )} with id ${item.id} is duplicated.`,
+ `Unique global id is neccessary for graph nodes/edges/combos. The ${type} ${JSON.stringify(item)} with id ${
+ item.id
+ } is duplicated.`,
);
return false;
}
@@ -75,14 +62,8 @@ const handler = (
formattedCombos?.forEach((combo) => {
const { parentId } = combo.data;
- if (
- parentId !== undefined &&
- !comboIdMap.has(parentId) &&
- (!graphCore || !graphCore.hasNode(parentId))
- ) {
- console.error(
- `The parentId of combo with id ${combo.id} will be removed since it is not exist in combos.`,
- );
+ if (parentId !== undefined && !comboIdMap.has(parentId) && (!graphCore || !graphCore.hasNode(parentId))) {
+ console.error(`The parentId of combo with id ${combo.id} will be removed since it is not exist in combos.`);
delete combo.data.parentId;
}
});
@@ -91,15 +72,9 @@ const handler = (
?.map((node) => {
if (!idAndDataCheck(node, 'node')) return false;
const { parentId } = node.data;
- if (
- parentId !== undefined &&
- !comboIdMap.has(parentId) &&
- (!graphCore || !graphCore.hasNode(parentId))
- ) {
+ if (parentId !== undefined && !comboIdMap.has(parentId) && (!graphCore || !graphCore.hasNode(parentId))) {
// TODO: parentId is a node in graphCore
- console.error(
- `The parentId of node with id ${node.id} will be removed since it is not exist in combos.`,
- );
+ console.error(`The parentId of node with id ${node.id} will be removed since it is not exist in combos.`);
delete node.data.parentId;
}
idMap.set(node.id, true);
@@ -121,32 +96,20 @@ const handler = (
}
if (source === undefined) {
- console.error(
- `The edge with id ${id} will be ignored since its source is undefined.`,
- );
+ console.error(`The edge with id ${id} will be ignored since its source is undefined.`);
return false;
}
if (target === undefined) {
- console.error(
- `The edge with id ${id} will be ignored since its target is undefined.`,
- );
+ console.error(`The edge with id ${id} will be ignored since its target is undefined.`);
return false;
}
- if (
- !nodeIdMap.has(source) &&
- !comboIdMap.has(source) &&
- (!graphCore || !graphCore.hasNode(source))
- ) {
+ if (!nodeIdMap.has(source) && !comboIdMap.has(source) && (!graphCore || !graphCore.hasNode(source))) {
console.error(
`The edge with id ${id} will be ignored since its source ${source} is not existed in nodes and combos.`,
);
return false;
}
- if (
- !nodeIdMap.has(target) &&
- !comboIdMap.has(target) &&
- (!graphCore || !graphCore.hasNode(target))
- ) {
+ if (!nodeIdMap.has(target) && !comboIdMap.has(target) && (!graphCore || !graphCore.hasNode(target))) {
console.error(
`The edge with id ${id} will be ignored since its target ${target} is not existed in nodes and combos.`,
);
diff --git a/packages/g6/src/stdlib/index.ts b/packages/g6/src/stdlib/index.ts
index 6e3e7b531d1..deca118d67d 100644
--- a/packages/g6/src/stdlib/index.ts
+++ b/packages/g6/src/stdlib/index.ts
@@ -1,5 +1,5 @@
-import * as Layouts from '@antv/layout';
import Hierarchy from '@antv/hierarchy';
+import * as Layouts from '@antv/layout';
import { Lib } from '../types/stdlib';
import { Behavior as BaseBehavior } from '../types/behavior';
@@ -7,14 +7,13 @@ import { Plugin as BasePlugin } from '../types/plugin';
import * as Behaviors from './behavior';
import * as Transforms from './data';
import * as Combos from './item/combo';
-import * as Nodes from './item/node';
import * as Edges from './item/edge';
+import * as Nodes from './item/node';
+import * as Plugins from './plugin';
import * as Themes from './theme';
import * as ThemeSolvers from './themeSolver';
-import * as Plugins from './plugin';
-const { ValidateData, TransformV4Data, MapNodeSize, ProcessParallelEdges } =
- Transforms;
+const { ValidateData, TransformV4Data, MapNodeSize, ProcessParallelEdges } = Transforms;
const { compactBox, dendrogram, indented, mindmap } = Hierarchy;
@@ -39,15 +38,7 @@ const {
BaseNode3D,
} = Nodes;
-const {
- LineEdge,
- CubicEdge,
- CubicHorizontalEdge,
- CubicVerticalEdge,
- LoopEdge,
- PolylineEdge,
- QuadraticEdge,
-} = Edges;
+const { LineEdge, CubicEdge, CubicHorizontalEdge, CubicVerticalEdge, LoopEdge, PolylineEdge, QuadraticEdge } = Edges;
const { CircleCombo, RectCombo } = Combos;
const {
ActivateRelations,
@@ -101,10 +92,10 @@ const {
ComboCombinedLayout,
} = Layouts;
-import lassoSelector from './selector/lasso';
-import rectSelector from './selector/rect';
import Hull from './plugin/hull';
import { WaterMarker } from './plugin/watermarker';
+import lassoSelector from './selector/lasso';
+import rectSelector from './selector/rect';
const stdLib = {
transforms: {
@@ -177,22 +168,12 @@ const stdLib = {
upTriangle: (x, y, r) => {
const l1 = r * Math.cos(Math.PI / 6);
const l2 = r * Math.sin(Math.PI / 6);
- return [
- ['M', x - l1, y + l2],
- ['L', x + l1, y + l2],
- ['L', x, y - r],
- ['Z'],
- ];
+ return [['M', x - l1, y + l2], ['L', x + l1, y + l2], ['L', x, y - r], ['Z']];
},
downTriangle: (x, y, r) => {
const l1 = r * Math.cos(Math.PI / 6);
const l2 = r * Math.sin(Math.PI / 6);
- return [
- ['M', x - l1, y - l2],
- ['L', x + l1, y - l2],
- ['L', x, y + r],
- ['Z'],
- ];
+ return [['M', x - l1, y - l2], ['L', x + l1, y - l2], ['L', x, y + r], ['Z']];
},
},
};
diff --git a/packages/g6/src/stdlib/item/combo/circle.ts b/packages/g6/src/stdlib/item/combo/circle.ts
index 59e5cec00b2..383d200ca35 100644
--- a/packages/g6/src/stdlib/item/combo/circle.ts
+++ b/packages/g6/src/stdlib/item/combo/circle.ts
@@ -1,11 +1,6 @@
import { DisplayObject } from '@antv/g';
+import { ComboDisplayModel, ComboModelData, ComboShapeMap, ComboShapeStyles } from '../../../types/combo';
import { State } from '../../../types/item';
-import {
- ComboDisplayModel,
- ComboModelData,
- ComboShapeMap,
- ComboShapeStyles,
-} from '../../../types/combo';
import { BaseNode } from '../node/base';
export class CircleCombo extends BaseNode {
@@ -16,7 +11,7 @@ export class CircleCombo extends BaseNode {
y: 0,
},
};
- mergedStyles: ComboShapeStyles;
+ declare mergedStyles: ComboShapeStyles;
constructor(props) {
super(props);
// suggest to merge default styles like this to avoid style value missing
@@ -36,42 +31,22 @@ export class CircleCombo extends BaseNode {
// haloShape
if (data.haloShape && this.drawHaloShape) {
- shapes.haloShape = this.drawHaloShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.haloShape = this.drawHaloShape(model, shapeMap, diffData, diffState);
}
// labelShape
if (data.labelShape) {
- shapes.labelShape = this.drawLabelShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.labelShape = this.drawLabelShape(model, shapeMap, diffData, diffState);
}
// labelBackgroundShape
if (data.labelBackgroundShape) {
- shapes.labelBackgroundShape = this.drawLabelBackgroundShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.labelBackgroundShape = this.drawLabelBackgroundShape(model, shapeMap, diffData, diffState);
}
// anchor shapes
if (data.anchorShapes) {
- const anchorShapes = this.drawAnchorShapes(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ const anchorShapes = this.drawAnchorShapes(model, shapeMap, diffData, diffState);
shapes = {
...shapes,
...anchorShapes,
@@ -80,22 +55,12 @@ export class CircleCombo extends BaseNode {
// iconShape
if (data.iconShape) {
- shapes.iconShape = this.drawIconShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.iconShape = this.drawIconShape(model, shapeMap, diffData, diffState);
}
// badgeShape
if (data.badgeShapes) {
- const badgeShapes = this.drawBadgeShapes(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ const badgeShapes = this.drawBadgeShapes(model, shapeMap, diffData, diffState);
shapes = {
...shapes,
...badgeShapes,
diff --git a/packages/g6/src/stdlib/item/combo/rect.ts b/packages/g6/src/stdlib/item/combo/rect.ts
index fe7463bb629..74075fa5790 100644
--- a/packages/g6/src/stdlib/item/combo/rect.ts
+++ b/packages/g6/src/stdlib/item/combo/rect.ts
@@ -1,11 +1,6 @@
import { DisplayObject } from '@antv/g';
+import { ComboDisplayModel, ComboModelData, ComboShapeMap, ComboShapeStyles } from '../../../types/combo';
import { State } from '../../../types/item';
-import {
- ComboDisplayModel,
- ComboModelData,
- ComboShapeMap,
- ComboShapeStyles,
-} from '../../../types/combo';
import { BaseNode } from '../node/base';
export class RectCombo extends BaseNode {
@@ -17,7 +12,7 @@ export class RectCombo extends BaseNode {
height: 32,
},
};
- mergedStyles: ComboShapeStyles;
+ declare mergedStyles: ComboShapeStyles;
constructor(props) {
super(props);
// suggest to merge default styles like this to avoid style value missing
@@ -37,42 +32,22 @@ export class RectCombo extends BaseNode {
// haloShape
if (data.haloShape && this.drawHaloShape) {
- shapes.haloShape = this.drawHaloShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.haloShape = this.drawHaloShape(model, shapeMap, diffData, diffState);
}
// labelShape
if (data.labelShape) {
- shapes.labelShape = this.drawLabelShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.labelShape = this.drawLabelShape(model, shapeMap, diffData, diffState);
}
// labelBackgroundShape
if (data.labelBackgroundShape) {
- shapes.labelBackgroundShape = this.drawLabelBackgroundShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.labelBackgroundShape = this.drawLabelBackgroundShape(model, shapeMap, diffData, diffState);
}
// anchor shapes
if (data.anchorShapes) {
- const anchorShapes = this.drawAnchorShapes(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ const anchorShapes = this.drawAnchorShapes(model, shapeMap, diffData, diffState);
shapes = {
...shapes,
...anchorShapes,
@@ -81,22 +56,12 @@ export class RectCombo extends BaseNode {
// iconShape
if (data.iconShape) {
- shapes.iconShape = this.drawIconShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.iconShape = this.drawIconShape(model, shapeMap, diffData, diffState);
}
// badgeShape
if (data.badgeShapes) {
- const badgeShapes = this.drawBadgeShapes(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ const badgeShapes = this.drawBadgeShapes(model, shapeMap, diffData, diffState);
shapes = {
...shapes,
...badgeShapes,
@@ -129,10 +94,8 @@ export class RectCombo extends BaseNode {
public getMergedStyles(model: ComboDisplayModel) {
const merged = super.getMergedStyles(model);
- merged.keyShape.x =
- (merged.keyShape.x as number) - merged.keyShape.width / 2;
- merged.keyShape.y =
- (merged.keyShape.y as number) - merged.keyShape.height / 2;
+ merged.keyShape.x = (merged.keyShape.x as number) - merged.keyShape.width / 2;
+ merged.keyShape.y = (merged.keyShape.y as number) - merged.keyShape.height / 2;
return merged;
}
}
diff --git a/packages/g6/src/stdlib/item/edge/base.ts b/packages/g6/src/stdlib/item/edge/base.ts
index e4fb8567d98..3ff7c9efccd 100644
--- a/packages/g6/src/stdlib/item/edge/base.ts
+++ b/packages/g6/src/stdlib/item/edge/base.ts
@@ -1,33 +1,14 @@
-import { AABB, DisplayObject, Line, Polyline } from '@antv/g';
-import { isNumber, isBoolean } from '@antv/util';
+import { DisplayObject, Line, Polyline } from '@antv/g';
+import { isBoolean } from '@antv/util';
import { ID } from 'types';
-import {
- DEFAULT_LABEL_BG_PADDING,
- OTHER_SHAPES_FIELD_NAME,
- RESERVED_SHAPE_IDS,
-} from '../../../constant';
+import { DEFAULT_LABEL_BG_PADDING, OTHER_SHAPES_FIELD_NAME, RESERVED_SHAPE_IDS } from '../../../constant';
+import Node from '../../../item/node';
import { Point } from '../../../types/common';
-import {
- ArrowStyle,
- EdgeDisplayModel,
- EdgeModelData,
- EdgeShapeMap,
- EdgeShapeStyles,
-} from '../../../types/edge';
-import {
- GShapeStyle,
- SHAPE_TYPE,
- ShapeStyle,
- State,
- LodLevelRanges,
- ItemModelData,
-} from '../../../types/item';
+import { ArrowStyle, EdgeDisplayModel, EdgeModelData, EdgeShapeMap, EdgeShapeStyles } from '../../../types/edge';
+import { GShapeStyle, LodLevelRanges, SHAPE_TYPE, ShapeStyle, State } from '../../../types/item';
+import { DEFAULT_ARROW_CONFIG, getArrowPath } from '../../../util/arrow';
import { formatPadding, mergeStyles, upsertShape } from '../../../util/shape';
-import { DEFAULT_ANIMATE_CFG, fadeIn, fadeOut } from '../../../util/animate';
import { getWordWrapWidthByEnds } from '../../../util/text';
-import { AnimateCfg } from '../../../types/animate';
-import { DEFAULT_ARROW_CONFIG, getArrowPath } from '../../../util/arrow';
-import Node from '../../../item/node';
export abstract class BaseEdge {
type: string;
@@ -87,23 +68,15 @@ export abstract class BaseEdge {
dataStyles[fieldName] = data[fieldName] as ShapeStyle;
} else if (fieldName === OTHER_SHAPES_FIELD_NAME) {
Object.keys(data[fieldName]).forEach(
- (otherShapeId) =>
- (dataStyles[otherShapeId] = data[fieldName][otherShapeId]),
+ (otherShapeId) => (dataStyles[otherShapeId] = data[fieldName][otherShapeId]),
);
}
});
- const merged = mergeStyles([
- this.themeStyles,
- this.defaultStyles,
- dataStyles,
- ]) as EdgeShapeStyles;
+ const merged = mergeStyles([this.themeStyles, this.defaultStyles, dataStyles]) as EdgeShapeStyles;
const padding = merged.labelBackgroundShape?.padding;
if (padding) {
- merged.labelBackgroundShape.padding = formatPadding(
- padding,
- DEFAULT_LABEL_BG_PADDING,
- );
+ merged.labelBackgroundShape.padding = formatPadding(padding, DEFAULT_LABEL_BG_PADDING);
}
return merged;
}
@@ -123,11 +96,7 @@ export abstract class BaseEdge {
const { zoom } = this.#zoomCache;
const { maxWidth = '60%' } = this.mergedStyles.labelShape || {};
- this.#zoomCache.wordWrapWidth = getWordWrapWidthByEnds(
- [this.sourcePoint, this.targetPoint],
- maxWidth,
- 1,
- );
+ this.#zoomCache.wordWrapWidth = getWordWrapWidthByEnds([this.sourcePoint, this.targetPoint], maxWidth, 1);
this.#zoomCache.zoom = 1;
if (zoom !== 1) this.onZoom(shapeMap, zoom);
@@ -161,6 +130,12 @@ export abstract class BaseEdge {
* @param model The displayed model of this edge, only for drawing and not received by users.
* @param shapeMap The shape map that contains all of the elements to show on the edge.
* @param shapesChanged An array of shape IDs that have changed and need to be updated.
+ * @param diffData
+ * @param diffData.previous
+ * @param diffData.current
+ * @param diffState
+ * @param diffState.previous
+ * @param diffState.current
* @returns An object that contains some new shapes to be added to the edge.
*/
public afterDraw(
@@ -180,11 +155,7 @@ export abstract class BaseEdge {
* @param value state value
* @param shapeMap The shape map that contains all of the elements to show on the edge.
*/
- public setState: (
- name: string,
- value: boolean,
- shapeMap: { [shapeId: string]: DisplayObject },
- ) => void;
+ public setState: (name: string, value: boolean, shapeMap: { [shapeId: string]: DisplayObject }) => void;
/**
* Draw the label shape of the edge
@@ -192,6 +163,10 @@ export abstract class BaseEdge {
* @param shapeMap The shape map that contains all of the elements to show on the edge.
* @param diffData An object that contains previous and current data.
* @param diffState An object that contains previous and current edge's state.
+ * @param diffData.previous
+ * @param diffData.current
+ * @param diffState.previous
+ * @param diffState.current
* @returns The display object representing the label shape of the edge.
*/
public drawLabelShape(
@@ -238,18 +213,12 @@ export abstract class BaseEdge {
break;
}
- const point = (keyShape as Line | Polyline).getPoint(
- positionPreset.pointRatio[0],
- );
+ const point = (keyShape as Line | Polyline).getPoint(positionPreset.pointRatio[0]);
let positionStyle: any = { x: point.x, y: point.y };
let isRevert = false;
if (autoRotate) {
- const pointOffset = (keyShape as Line | Polyline).getPoint(
- positionPreset.pointRatio[1],
- );
- let angle = Math.atan(
- (point.y - pointOffset.y) / (point.x - pointOffset.x),
- );
+ const pointOffset = (keyShape as Line | Polyline).getPoint(positionPreset.pointRatio[1]);
+ let angle = Math.atan((point.y - pointOffset.y) / (point.x - pointOffset.x));
if (isNaN(angle)) angle = 0;
// revert
@@ -263,12 +232,8 @@ export abstract class BaseEdge {
positionPreset.offsetX = 4;
}
}
- const offsetX = (
- propsOffsetX === undefined ? positionPreset.offsetX : propsOffsetX
- ) as number;
- const offsetY = (
- propsOffsetY === undefined ? positionPreset.offsetY : propsOffsetY
- ) as number;
+ const offsetX = (propsOffsetX === undefined ? positionPreset.offsetX : propsOffsetX) as number;
+ const offsetY = (propsOffsetY === undefined ? positionPreset.offsetY : propsOffsetY) as number;
// the projection is |offsetX| away from point, along the tangent line of the keyShape's path at point
const projection = {
x: point.x + offsetX * Math.cos(angle),
@@ -285,11 +250,7 @@ export abstract class BaseEdge {
...positionStyle,
isRevert,
};
- const wordWrapWidth = getWordWrapWidthByEnds(
- [this.sourcePoint, this.targetPoint],
- maxWidth,
- this.#zoomCache.zoom,
- );
+ const wordWrapWidth = getWordWrapWidthByEnds([this.sourcePoint, this.targetPoint], maxWidth, this.#zoomCache.zoom);
this.#zoomCache.wordWrapWidth = wordWrapWidth;
const style = {
...this.defaultStyles.labelShape,
@@ -314,6 +275,10 @@ export abstract class BaseEdge {
* @param shapeMap The shape map that contains all of the elements to show on the edge.
* @param diffData An object that contains previous and current data.
* @param diffState An object that contains previous and current edge's state.
+ * @param diffData.previous
+ * @param diffData.current
+ * @param diffState.previous
+ * @param diffState.current
* @returns The display object representing the label background shape of the edge.
*/
public drawLabelBackgroundShape(
@@ -325,8 +290,7 @@ export abstract class BaseEdge {
const { labelShape } = shapeMap;
if (!labelShape || !labelShape.style.text || !model.data.labelShape) return;
- const { labelBackgroundShape, labelShape: labelShapeStyle } =
- this.mergedStyles;
+ const { labelBackgroundShape, labelShape: labelShapeStyle } = this.mergedStyles;
const textGeoBBox = labelShape.getGeometryBounds();
const { x, y, transform, isRevert } = this.labelPosition;
@@ -344,9 +308,7 @@ export abstract class BaseEdge {
if (transform) bgStyle.transform = transform;
if (labelShapeStyle.position === 'start') {
if (isRevert) {
- bgStyle.transformOrigin = `${bgStyle.width - padding[1]} ${
- bgStyle.height / 2
- }`;
+ bgStyle.transformOrigin = `${bgStyle.width - padding[1]} ${bgStyle.height / 2}`;
} else {
bgStyle.transformOrigin = `${padding[3]} ${bgStyle.height / 2}`;
}
@@ -354,14 +316,10 @@ export abstract class BaseEdge {
if (isRevert) {
bgStyle.transformOrigin = `${padding[3]} ${bgStyle.height / 2}`;
} else {
- bgStyle.transformOrigin = `${bgStyle.width - padding[1]} ${
- bgStyle.height / 2
- }`;
+ bgStyle.transformOrigin = `${bgStyle.width - padding[1]} ${bgStyle.height / 2}`;
}
} else {
- bgStyle.transformOrigin = `${textWidth / 2 + padding[3]} ${
- textHeight / 2 + padding[0]
- }`;
+ bgStyle.transformOrigin = `${textWidth / 2 + padding[3]} ${textHeight / 2 + padding[0]}`;
}
return this.upsertShape('rect', 'labelBackgroundShape', bgStyle, {
@@ -378,6 +336,10 @@ export abstract class BaseEdge {
* @param shapeMap The shape map that contains all of the elements to show on the edge.
* @param diffData An object that contains previous and current data.
* @param diffState An object that contains previous and current edge's state.
+ * @param diffData.previous
+ * @param diffData.current
+ * @param diffState.previous
+ * @param diffState.current
* @returns The display object representing the icon shape of the edge.
*/
public drawIconShape(
@@ -387,17 +349,9 @@ export abstract class BaseEdge {
diffState?: { previous: State[]; current: State[] },
): DisplayObject {
const { labelShape, labelBackgroundShape, keyShape } = shapeMap;
- const { iconShape: shapeStyle, labelShape: labelShapeProps } =
- this.mergedStyles;
+ const { iconShape: shapeStyle, labelShape: labelShapeProps } = this.mergedStyles;
- const {
- width,
- height,
- fontSize,
- text,
- offsetX = 0,
- offsetY = 0,
- } = shapeStyle;
+ const { width, height, fontSize, text, offsetX = 0, offsetY = 0 } = shapeStyle;
const w = (width || fontSize) as number;
const h = (height || fontSize) as number;
@@ -414,34 +368,24 @@ export abstract class BaseEdge {
if (labelShapeProps) {
const referShape = labelBackgroundShape || labelShape;
const referBounds = referShape.getGeometryBounds();
- const {
- min: referMin,
- max: referMax,
- halfExtents: referHalExtents,
- } = referBounds;
+ const { min: referMin, max: referMax, halfExtents: referHalExtents } = referBounds;
const referHeight = referMax[1] - referMin[1];
const referWidth = referMax[0] - referMin[0];
- const {
- x: referX,
- y: referY,
- transform: referTransform,
- } = referShape.attributes;
+ const { x: referX, y: referY, transform: referTransform } = referShape.attributes;
const { textAlign: labelAlign } = labelShape.attributes;
shapeStyle.x = referMin[0] - w + 4 + referX + offsetX;
shapeStyle.y = referMin[1] + (referHeight - h) / 2 + referY + offsetY;
if (referTransform) {
shapeStyle.transform = referTransform;
if (labelAlign === 'right') {
- shapeStyle.transformOrigin = `${
- referWidth / 2 - w / 2 + 4 + referHalExtents[0] - offsetX
- } ${h / 2 - offsetY}`;
+ shapeStyle.transformOrigin = `${referWidth / 2 - w / 2 + 4 + referHalExtents[0] - offsetX} ${
+ h / 2 - offsetY
+ }`;
} else if (labelAlign === 'left') {
shapeStyle.transformOrigin = `${w + 4 - offsetX} ${h / 2 - offsetY}`;
} else {
// labelShape align 'center'
- shapeStyle.transformOrigin = `${(w + referWidth) / 2 - offsetX} ${
- h / 2 - offsetY
- }`;
+ shapeStyle.transformOrigin = `${(w + referWidth) / 2 - offsetX} ${h / 2 - offsetY}`;
}
}
} else {
@@ -451,17 +395,12 @@ export abstract class BaseEdge {
// TODO: rotate
}
- return this.upsertShape(
- iconShapeType,
- 'iconShape',
- shapeStyle as GShapeStyle,
- {
- model,
- shapeMap,
- diffData,
- diffState,
- },
- );
+ return this.upsertShape(iconShapeType, 'iconShape', shapeStyle as GShapeStyle, {
+ model,
+ shapeMap,
+ diffData,
+ diffState,
+ });
}
/**
@@ -470,6 +409,10 @@ export abstract class BaseEdge {
* @param shapeMap The shape map that contains all of the elements to show on the edge.
* @param diffData An object that contains previous and current data.
* @param diffState An object that contains previous and current edge's state.
+ * @param diffData.previous
+ * @param diffData.current
+ * @param diffState.previous
+ * @param diffState.current
* @returns The display object representing the halo shape of the edge.
*/
public drawHaloShape(
@@ -512,12 +455,9 @@ export abstract class BaseEdge {
* The listener for graph zooming.
* @param shapeMap The shape map that contains all of the elements to show on the edge.
* @param zoom The zoom level of the graph.
+ * @param cacheHiddenShape
*/
- public onZoom = (
- shapeMap: EdgeShapeMap,
- zoom: number,
- cacheHiddenShape = {},
- ) => {};
+ public onZoom = (shapeMap: EdgeShapeMap, zoom: number, cacheHiddenShape = {}) => {};
/**
* Update the source point { x, y } for the edge. Called in item's draw func.
@@ -564,17 +504,8 @@ export abstract class BaseEdge {
resultStyle[`${markerField}Offset`] = 0;
return;
}
- const arrowStyle = isBoolean(arrowConfig)
- ? ({ ...DEFAULT_ARROW_CONFIG } as ArrowStyle)
- : arrowConfig;
- const {
- type = 'triangle',
- width = 10,
- height = 10,
- path: propPath,
- offset = 0,
- ...others
- } = arrowStyle;
+ const arrowStyle = isBoolean(arrowConfig) ? ({ ...DEFAULT_ARROW_CONFIG } as ArrowStyle) : arrowConfig;
+ const { type = 'triangle', width = 10, height = 10, path: propPath, offset = 0, ...others } = arrowStyle;
resultStyle[markerField] = this.upsertShape(
'path',
`${markerField}Shape`,
@@ -599,8 +530,17 @@ export abstract class BaseEdge {
* @param type shape's type
* @param id unique string to indicates the shape
* @param style style to be updated
+ * @param config
* @param shapeMap the shape map of a edge
* @param model data model of the edge
+ * @param config.model
+ * @param config.shapeMap
+ * @param config.diffData
+ * @param config.diffData.previous
+ * @param config.diffData.current
+ * @param config.diffState
+ * @param config.diffState.previous
+ * @param config.diffState.current
* @returns The display object representing the shape.
*/
public upsertShape(
diff --git a/packages/g6/src/stdlib/item/edge/cubic-horizontal.ts b/packages/g6/src/stdlib/item/edge/cubic-horizontal.ts
index 792356081c7..27825e8ecb0 100644
--- a/packages/g6/src/stdlib/item/edge/cubic-horizontal.ts
+++ b/packages/g6/src/stdlib/item/edge/cubic-horizontal.ts
@@ -24,7 +24,7 @@ export class CubicHorizontalEdge extends CubicEdge {
/**
* calculate the control points by curvePosition|controlPoints|curveOffset
- * @param startPoint: source point position of edge
+ * @param startPoint source point position of edge
* @param endPoint target point position of edge
* @param percent the proportion of control points' in the segment, Range 0 to 1
* @param controlPoints the control point position
@@ -37,42 +37,28 @@ export class CubicHorizontalEdge extends CubicEdge {
percent: number,
controlPoints: Point[],
offset: number,
- ) => Point[] = (
- startPoint: Point,
- endPoint: Point,
- percent = 0.5,
- controlPoints,
- offset,
- ) => {
+ ) => Point[] = (startPoint: Point, endPoint: Point, percent = 0.5, controlPoints, offset) => {
if (controlPoints?.length > 1) return controlPoints;
const distanceToPoint = (startPoint.x - endPoint.x) * percent;
- const controlPoint1: Point = this.getControlPoint(
- startPoint,
- endPoint,
- distanceToPoint,
- );
- const controlPoint2: Point = this.getControlPoint(
- endPoint,
- startPoint,
- -distanceToPoint,
- );
+ const controlPoint1: Point = this.getControlPoint(startPoint, endPoint, distanceToPoint);
+ const controlPoint2: Point = this.getControlPoint(endPoint, startPoint, -distanceToPoint);
return [controlPoint1, controlPoint2];
};
/**
* control point calculated according to startPoint, endPoint, percent, and offset
- * @param {Point} startPoint source point position of edge (x, y)
- * @param {Point} endPoint target point position of edge (x, y)
- * @param {Number} percent the proportion of control points' in the segment, Range 0 to 1
- * @param {Number} offset the curveOffset
- * @return {Point} control point (x,y)
+ * @param startPoint source point position of edge (x, y)
+ * @param endPoint target point position of edge (x, y)
+ * @param percent the proportion of control points' in the segment, Range 0 to 1
+ * @param offset the curveOffset
+ * @returns control point (x,y)
*/
- protected getControlPoint: (
+ protected getControlPoint: (startPoint: Point, endPoint: Point, offset: number) => Point = (
startPoint: Point,
endPoint: Point,
- offset: number,
- ) => Point = (startPoint: Point, endPoint: Point, offset = 0) => {
+ offset = 0,
+ ) => {
if (endPoint.y === startPoint.y || endPoint.x === startPoint.x) {
return { x: (startPoint.x + endPoint.x) / 2, y: startPoint.y };
}
diff --git a/packages/g6/src/stdlib/item/edge/cubic-vertical.ts b/packages/g6/src/stdlib/item/edge/cubic-vertical.ts
index f9a1716f7d5..5229ac2305c 100644
--- a/packages/g6/src/stdlib/item/edge/cubic-vertical.ts
+++ b/packages/g6/src/stdlib/item/edge/cubic-vertical.ts
@@ -23,11 +23,11 @@ export class CubicVerticalEdge extends CubicEdge {
/**
* control point calculated according to startPoint, endPoint, percent, and offset
- * @param {Point} startPoint source point position of edge (x, y)
- * @param {Point} endPoint target point position of edge (x, y)
- * @param {Number} percent the proportion of control points' in the segment, Range 0 to 1
- * @param {Number} offset the curveOffset
+ * @param startPoint source point position of edge (x, y)
+ * @param endPoint target point position of edge (x, y)
+ * @param percent the proportion of control points' in the segment, Range 0 to 1
* @param controlPoints the control point position
+ * @param offset the curveOffset
* @returns control points
*/
protected getControlPoints: (
@@ -36,42 +36,28 @@ export class CubicVerticalEdge extends CubicEdge {
percent: number,
controlPoints: Point[],
offset: number,
- ) => Point[] = (
- startPoint: Point,
- endPoint: Point,
- percent = 0.5,
- controlPoints,
- offset,
- ) => {
+ ) => Point[] = (startPoint: Point, endPoint: Point, percent = 0.5, controlPoints, offset) => {
if (controlPoints?.length > 1) return controlPoints;
const distanceToPoint = (startPoint.y - endPoint.y) * percent;
- const controlPoint1: Point = this.getControlPoint(
- startPoint,
- endPoint,
- distanceToPoint,
- );
- const controlPoint2: Point = this.getControlPoint(
- endPoint,
- startPoint,
- -distanceToPoint,
- );
+ const controlPoint1: Point = this.getControlPoint(startPoint, endPoint, distanceToPoint);
+ const controlPoint2: Point = this.getControlPoint(endPoint, startPoint, -distanceToPoint);
return [controlPoint1, controlPoint2];
};
/**
* control point calculated according to startPoint, endPoint, percent, and offset
- * @param {Point} startPoint source point position of edge (x, y)
- * @param {Point} endPoint target point position of edge (x, y)
- * @param {Number} percent the proportion of control points' in the segment, Range 0 to 1
- * @param {Number} offset the curveOffset
- * @return {Point} control point (x,y)
+ * @param startPoint source point position of edge (x, y)
+ * @param endPoint target point position of edge (x, y)
+ * @param percent the proportion of control points' in the segment, Range 0 to 1
+ * @param offset the curveOffset
+ * @returns control point (x,y)
*/
- protected getControlPoint: (
+ protected getControlPoint: (startPoint: Point, endPoint: Point, offset: number) => Point = (
startPoint: Point,
endPoint: Point,
- offset: number,
- ) => Point = (startPoint: Point, endPoint: Point, offset = 0) => {
+ offset = 0,
+ ) => {
if (endPoint.y === startPoint.y || endPoint.x === startPoint.x) {
return { x: startPoint.x, y: (startPoint.y + endPoint.y) / 2 };
}
diff --git a/packages/g6/src/stdlib/item/edge/cubic.ts b/packages/g6/src/stdlib/item/edge/cubic.ts
index 3a6b3e3d67d..5b178bc9783 100644
--- a/packages/g6/src/stdlib/item/edge/cubic.ts
+++ b/packages/g6/src/stdlib/item/edge/cubic.ts
@@ -5,7 +5,6 @@ import { EdgeModelData, EdgeShapeMap } from '../../../types/edge';
import { State } from '../../../types/item';
import { EdgeDisplayModel } from '../../../types';
-// eslint-disable-next-line import/namespace
import { BaseEdge } from './base';
export class CubicEdge extends BaseEdge {
@@ -45,50 +44,23 @@ export class CubicEdge extends BaseEdge {
const shapes: EdgeShapeMap = { keyShape: undefined };
- shapes.keyShape = this.drawKeyShape(
- model,
- sourcePoint,
- targetPoint,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.keyShape = this.drawKeyShape(model, sourcePoint, targetPoint, shapeMap, diffData, diffState);
if (data.haloShape) {
- shapes.haloShape = this.drawHaloShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.haloShape = this.drawHaloShape(model, shapeMap, diffData, diffState);
}
if (data.labelShape) {
- shapes.labelShape = this.drawLabelShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.labelShape = this.drawLabelShape(model, shapeMap, diffData, diffState);
}
// labelBackgroundShape
if (data.labelBackgroundShape) {
- shapes.labelBackgroundShape = this.drawLabelBackgroundShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.labelBackgroundShape = this.drawLabelBackgroundShape(model, shapeMap, diffData, diffState);
}
if (data.iconShape) {
- shapes.iconShape = this.drawIconShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.iconShape = this.drawIconShape(model, shapeMap, diffData, diffState);
}
// TODO: other shapes
@@ -142,7 +114,7 @@ export class CubicEdge extends BaseEdge {
/**
* calculate the control points by curvePosition|controlPoints|curveOffset
- * @param startPoint: source point position of edge
+ * @param startPoint source point position of edge
* @param endPoint target point position of edge
* @param percent the proportion of control points' in the segment, Range 0 to 1
* @param controlPoints the control point position
@@ -155,44 +127,23 @@ export class CubicEdge extends BaseEdge {
percent: number,
controlPoints: Point[],
offset: number,
- ) => Point[] = (
- startPoint: Point,
- endPoint: Point,
- percent = 0.5,
- controlPoints,
- offset = 20,
- ) => {
+ ) => Point[] = (startPoint: Point, endPoint: Point, percent = 0.5, controlPoints, offset = 20) => {
if (controlPoints?.length > 1) return controlPoints;
- const controlPoint1: Point = this.getControlPoint(
- startPoint,
- endPoint,
- percent,
- offset,
- );
- const controlPoint2: Point = this.getControlPoint(
- startPoint,
- endPoint,
- percent,
- -offset,
- );
+ const controlPoint1: Point = this.getControlPoint(startPoint, endPoint, percent, offset);
+ const controlPoint2: Point = this.getControlPoint(startPoint, endPoint, percent, -offset);
return [controlPoint1, controlPoint2];
};
/**
* control point calculated according to startPoint, endPoint, percent, and offset
- * @param {Point} startPoint source point position of edge (x, y)
- * @param {Point} endPoint target point position of edge (x, y)
- * @param {Number} percent the proportion of control points' in the segment, Range 0 to 1
- * @param {Number} offset the curveOffset
- * @return {Point} control point (x,y)
+ * @param startPoint source point position of edge (x, y)
+ * @param endPoint target point position of edge (x, y)
+ * @param percent the proportion of control points' in the segment, Range 0 to 1
+ * @param offset the curveOffset
+ * @returns control point (x,y)
*/
- protected getControlPoint: (
- startPoint: Point,
- endPoint: Point,
- percent: number,
- offset: number,
- ) => Point = (
+ protected getControlPoint: (startPoint: Point, endPoint: Point, percent: number, offset: number) => Point = (
startPoint: Point,
endPoint: Point,
percent = 0,
@@ -204,10 +155,7 @@ export class CubicEdge extends BaseEdge {
};
let tangent: vec2 = [0, 0];
- vec2.normalize(tangent, [
- endPoint.x - startPoint.x,
- endPoint.y - startPoint.y,
- ]);
+ vec2.normalize(tangent, [endPoint.x - startPoint.x, endPoint.y - startPoint.y]);
if (!tangent || (!tangent[0] && !tangent[1])) {
tangent = [0, 0];
diff --git a/packages/g6/src/stdlib/item/edge/index.ts b/packages/g6/src/stdlib/item/edge/index.ts
index 3c84f9e44f3..79c5fc5227e 100644
--- a/packages/g6/src/stdlib/item/edge/index.ts
+++ b/packages/g6/src/stdlib/item/edge/index.ts
@@ -1,7 +1,7 @@
-export * from './line';
-export * from './quadratic';
-export * from './polyline';
-export * from './loop';
+export * from './cubic';
export * from './cubic-horizontal';
export * from './cubic-vertical';
-export * from './cubic';
+export * from './line';
+export * from './loop';
+export * from './polyline';
+export * from './quadratic';
diff --git a/packages/g6/src/stdlib/item/edge/line.ts b/packages/g6/src/stdlib/item/edge/line.ts
index 935cd130be6..67f11dd3eef 100644
--- a/packages/g6/src/stdlib/item/edge/line.ts
+++ b/packages/g6/src/stdlib/item/edge/line.ts
@@ -1,9 +1,5 @@
import { Point } from '../../../types/common';
-import {
- EdgeDisplayModel,
- EdgeModelData,
- EdgeShapeMap,
-} from '../../../types/edge';
+import { EdgeDisplayModel, EdgeModelData, EdgeShapeMap } from '../../../types/edge';
import { State } from '../../../types/item';
import { BaseEdge } from './base';
@@ -37,50 +33,23 @@ export class LineEdge extends BaseEdge {
let shapes: EdgeShapeMap = { keyShape: undefined };
- shapes.keyShape = this.drawKeyShape(
- model,
- sourcePoint,
- targetPoint,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.keyShape = this.drawKeyShape(model, sourcePoint, targetPoint, shapeMap, diffData, diffState);
if (data.haloShape) {
- shapes.haloShape = this.drawHaloShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.haloShape = this.drawHaloShape(model, shapeMap, diffData, diffState);
}
if (data.labelShape) {
- shapes.labelShape = this.drawLabelShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.labelShape = this.drawLabelShape(model, shapeMap, diffData, diffState);
}
// labelBackgroundShape
if (data.labelBackgroundShape) {
- shapes.labelBackgroundShape = this.drawLabelBackgroundShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.labelBackgroundShape = this.drawLabelBackgroundShape(model, shapeMap, diffData, diffState);
}
if (data.iconShape) {
- shapes.iconShape = this.drawIconShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.iconShape = this.drawIconShape(model, shapeMap, diffData, diffState);
}
// otherShapes
diff --git a/packages/g6/src/stdlib/item/edge/loop.ts b/packages/g6/src/stdlib/item/edge/loop.ts
index 64fd51bcb56..e09288cc8e8 100644
--- a/packages/g6/src/stdlib/item/edge/loop.ts
+++ b/packages/g6/src/stdlib/item/edge/loop.ts
@@ -1,18 +1,11 @@
import { vec2 } from 'gl-matrix';
-import { getBBoxHeight, getBBoxWidth } from '../../../util/bbox';
-import { distanceVec } from '../../../util/point';
-import {
- calculatePointForEllipse,
- calculatePointForOtherShapes,
-} from '../../../util/loop';
import { Point } from '../../../types/common';
-import {
- EdgeDisplayModel,
- EdgeModelData,
- EdgeShapeMap,
-} from '../../../types/edge';
+import { EdgeDisplayModel, EdgeModelData, EdgeShapeMap } from '../../../types/edge';
import { State } from '../../../types/item';
import { LOOP_POSITION, LoopCfg, LoopPosition } from '../../../types/loop';
+import { getBBoxHeight, getBBoxWidth } from '../../../util/bbox';
+import { calculatePointForEllipse, calculatePointForOtherShapes } from '../../../util/loop';
+import { distanceVec } from '../../../util/point';
import { CubicEdge } from './cubic';
export class LoopEdge extends CubicEdge {
@@ -61,15 +54,7 @@ export class LoopEdge extends CubicEdge {
...keyShapeStyle,
path: [
['M', startPoint.x, startPoint.y],
- [
- 'C',
- controlPoints[0].x,
- controlPoints[0].y,
- controlPoints[1].x,
- controlPoints[1].y,
- endPoint.x,
- endPoint.y,
- ],
+ ['C', controlPoints[0].x, controlPoints[0].y, controlPoints[1].x, controlPoints[1].y, endPoint.x, endPoint.y],
],
};
@@ -116,12 +101,7 @@ export class LoopEdge extends CubicEdge {
if (startPoint[0] === endPoint[0] && startPoint[1] === endPoint[1]) {
if (shapeType === 'circle' || shapeType === 'ellipse') {
- [startPoint, endPoint] = calculatePointForEllipse(
- position,
- center,
- halfOfWidth,
- halfOfHeight,
- );
+ [startPoint, endPoint] = calculatePointForEllipse(position, center, halfOfWidth, halfOfHeight);
} else {
[startPoint, endPoint] = calculatePointForOtherShapes(
position,
@@ -142,10 +122,7 @@ export class LoopEdge extends CubicEdge {
// The distance from the edge of the keyShape
const dist: number = loopCfg.dist || Math.max(width, height) * 2;
- const startVec: vec2 = [
- startPoint[0] - center[0],
- startPoint[1] - center[1],
- ];
+ const startVec: vec2 = [startPoint[0] - center[0], startPoint[1] - center[1]];
const endVec: vec2 = [endPoint[0] - center[0], endPoint[1] - center[1]];
const rstart = distanceVec([0, 0], startVec);
const rend = distanceVec([0, 0], endVec);
diff --git a/packages/g6/src/stdlib/item/edge/polyline.ts b/packages/g6/src/stdlib/item/edge/polyline.ts
index 3ce3efa73a3..1a4e6a5e9c5 100644
--- a/packages/g6/src/stdlib/item/edge/polyline.ts
+++ b/packages/g6/src/stdlib/item/edge/polyline.ts
@@ -1,15 +1,11 @@
-import { isEmpty, mix } from '@antv/util';
import { ID } from '@antv/graphlib';
+import { isEmpty, mix } from '@antv/util';
+import Node from '../../../item/node';
import { Point } from '../../../types/common';
-import {
- EdgeDisplayModel,
- EdgeModelData,
- EdgeShapeMap,
-} from '../../../types/edge';
+import { EdgeDisplayModel, EdgeModelData, EdgeShapeMap } from '../../../types/edge';
import { State } from '../../../types/item';
import { getPolylinePath } from '../../../util/polyline';
import { RouterCfg, pathFinder } from '../../../util/router';
-import Node from '../../../item/node';
import { LineEdge } from './line';
export class PolylineEdge extends LineEdge {
public type = 'polyline-edge';
@@ -41,61 +37,30 @@ export class PolylineEdge extends LineEdge {
const shapes: EdgeShapeMap = { keyShape: undefined };
- shapes.keyShape = this.drawKeyShape(
- model,
- sourcePoint,
- targetPoint,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.keyShape = this.drawKeyShape(model, sourcePoint, targetPoint, shapeMap, diffData, diffState);
if (data.haloShape) {
- shapes.haloShape = this.drawHaloShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.haloShape = this.drawHaloShape(model, shapeMap, diffData, diffState);
}
if (data.labelShape) {
- shapes.labelShape = this.drawLabelShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.labelShape = this.drawLabelShape(model, shapeMap, diffData, diffState);
}
// labelBackgroundShape
if (data.labelBackgroundShape) {
- shapes.labelBackgroundShape = this.drawLabelBackgroundShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.labelBackgroundShape = this.drawLabelBackgroundShape(model, shapeMap, diffData, diffState);
}
if (data.iconShape) {
- shapes.iconShape = this.drawIconShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.iconShape = this.drawIconShape(model, shapeMap, diffData, diffState);
}
// TODO: other shapes
return shapes;
}
- public getControlPoints(
- model: EdgeDisplayModel,
- sourcePoint: Point,
- targetPoint: Point,
- ): Point[] {
+ public getControlPoints(model: EdgeDisplayModel, sourcePoint: Point, targetPoint: Point): Point[] {
const { keyShape: keyShapeStyle } = this.mergedStyles as any;
return keyShapeStyle.controlPoints;
}
@@ -118,8 +83,7 @@ export class PolylineEdge extends LineEdge {
const { id: edgeId, source: sourceNodeId, target: targetNodeId } = model;
// Draw a polyline with control points
- if (!auto && routeCfg.name !== 'er')
- return getPolylinePath(edgeId, points, radius);
+ if (!auto && routeCfg.name !== 'er') return getPolylinePath(edgeId, points, radius);
// Find the shortest path computed by A* routing algorithm
const polylinePoints = pathFinder(
@@ -142,30 +106,16 @@ export class PolylineEdge extends LineEdge {
diffState?: { previous: State[]; current: State[] },
) {
const { keyShape: keyShapeStyle } = this.mergedStyles as any;
- const controlPoints = this.getControlPoints(
- model,
- sourcePoint,
- targetPoint,
- );
+ const controlPoints = this.getControlPoints(model, sourcePoint, targetPoint);
let points = [sourcePoint, targetPoint];
if (controlPoints) {
points = [sourcePoint, ...controlPoints, targetPoint];
}
- const routeCfg = mix(
- {},
- { offset: keyShapeStyle.offset, name: 'orth' },
- keyShapeStyle.routeCfg,
- );
+ const routeCfg = mix({}, { offset: keyShapeStyle.offset, name: 'orth' }, keyShapeStyle.routeCfg);
- const path = this.getPath(
- model,
- points,
- keyShapeStyle.radius,
- routeCfg,
- isEmpty(controlPoints),
- );
+ const path = this.getPath(model, points, keyShapeStyle.radius, routeCfg, isEmpty(controlPoints));
const { startArrow, endArrow, ...others } = keyShapeStyle;
const lineStyle = {
diff --git a/packages/g6/src/stdlib/item/edge/quadratic.ts b/packages/g6/src/stdlib/item/edge/quadratic.ts
index f74c3640316..fceb11eb8dd 100644
--- a/packages/g6/src/stdlib/item/edge/quadratic.ts
+++ b/packages/g6/src/stdlib/item/edge/quadratic.ts
@@ -1,11 +1,7 @@
-import { getControlPoint } from '../../../util/path';
import { Point } from '../../../types/common';
-import {
- EdgeDisplayModel,
- EdgeModelData,
- EdgeShapeMap,
-} from '../../../types/edge';
+import { EdgeDisplayModel, EdgeModelData, EdgeShapeMap } from '../../../types/edge';
import { State } from '../../../types/item';
+import { getControlPoint } from '../../../util/path';
import { BaseEdge } from './base';
export class QuadraticEdge extends BaseEdge {
@@ -35,50 +31,23 @@ export class QuadraticEdge extends BaseEdge {
const shapes: EdgeShapeMap = { keyShape: undefined };
- shapes.keyShape = this.drawKeyShape(
- model,
- sourcePoint,
- targetPoint,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.keyShape = this.drawKeyShape(model, sourcePoint, targetPoint, shapeMap, diffData, diffState);
if (data.haloShape) {
- shapes.haloShape = this.drawHaloShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.haloShape = this.drawHaloShape(model, shapeMap, diffData, diffState);
}
if (data.labelShape) {
- shapes.labelShape = this.drawLabelShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.labelShape = this.drawLabelShape(model, shapeMap, diffData, diffState);
}
// labelBackgroundShape
if (data.labelBackgroundShape) {
- shapes.labelBackgroundShape = this.drawLabelBackgroundShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.labelBackgroundShape = this.drawLabelBackgroundShape(model, shapeMap, diffData, diffState);
}
if (data.iconShape) {
- shapes.iconShape = this.drawIconShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.iconShape = this.drawIconShape(model, shapeMap, diffData, diffState);
}
// TODO: other shapes
@@ -122,7 +91,7 @@ export class QuadraticEdge extends BaseEdge {
/**
* calculate the control point by curvePosition|controlPoints|curveOffset
- * @param startPoint: source point position of edge
+ * @param startPoint source point position of edge
* @param endPoint target point position of edge
* @param percent the proportion of control points' in the segment, Range 0 to 1
* @param controlPoints the control point position
@@ -135,21 +104,8 @@ export class QuadraticEdge extends BaseEdge {
percent: number,
controlPoints: Point[],
offset: number,
- ) => Point[] = (
- startPoint: Point,
- endPoint: Point,
- percent = 0,
- controlPoints,
- offset,
- ) => {
+ ) => Point[] = (startPoint: Point, endPoint: Point, percent = 0, controlPoints, offset) => {
if (controlPoints?.length) return controlPoints;
- return [
- getControlPoint(
- startPoint as Point,
- endPoint as Point,
- percent as number,
- offset as number,
- ),
- ];
+ return [getControlPoint(startPoint as Point, endPoint as Point, percent as number, offset as number)];
};
}
diff --git a/packages/g6/src/stdlib/item/node/base.ts b/packages/g6/src/stdlib/item/node/base.ts
index 2d68eb8f55c..e90a4064d86 100644
--- a/packages/g6/src/stdlib/item/node/base.ts
+++ b/packages/g6/src/stdlib/item/node/base.ts
@@ -1,34 +1,11 @@
import { AABB, DisplayObject } from '@antv/g';
import { OTHER_SHAPES_FIELD_NAME, RESERVED_SHAPE_IDS } from '../../../constant';
import { NodeDisplayModel } from '../../../types';
-import {
- GShapeStyle,
- SHAPE_TYPE,
- SHAPE_TYPE_3D,
- ShapeStyle,
- State,
- LodLevelRanges,
- ItemModelData,
-} from '../../../types/item';
-import {
- NodeModelData,
- NodeShapeMap,
- NodeShapeStyles,
- IAnchorPositionMap,
-} from '../../../types/node';
-import {
- ComboDisplayModel,
- ComboModelData,
- ComboShapeStyles,
- ComboShapeMap,
-} from '../../../types/combo';
-import {
- formatPadding,
- getShapeLocalBoundsByStyle,
- mergeStyles,
- upsertShape,
-} from '../../../util/shape';
+import { ComboDisplayModel, ComboModelData, ComboShapeMap, ComboShapeStyles } from '../../../types/combo';
import type { IGraph } from '../../../types/graph';
+import { GShapeStyle, LodLevelRanges, SHAPE_TYPE, SHAPE_TYPE_3D, ShapeStyle, State } from '../../../types/item';
+import { IAnchorPositionMap, NodeModelData, NodeShapeMap, NodeShapeStyles } from '../../../types/node';
+import { formatPadding, getShapeLocalBoundsByStyle, mergeStyles, upsertShape } from '../../../util/shape';
import { getWordWrapWidthByBox } from '../../../util/text';
import { convertToNumber } from '../../../util/type';
@@ -109,16 +86,11 @@ export abstract class BaseNode {
}
} else if (fieldName === OTHER_SHAPES_FIELD_NAME) {
Object.keys(data[fieldName]).forEach(
- (otherShapeId) =>
- (dataStyles[otherShapeId] = data[fieldName][otherShapeId]),
+ (otherShapeId) => (dataStyles[otherShapeId] = data[fieldName][otherShapeId]),
);
}
});
- const merged = mergeStyles([
- this.themeStyles,
- this.defaultStyles,
- dataStyles,
- ]) as NodeShapeStyles;
+ const merged = mergeStyles([this.themeStyles, this.defaultStyles, dataStyles]) as NodeShapeStyles;
const padding = merged.labelBackgroundShape?.padding;
if (padding) {
merged.labelBackgroundShape.padding = formatPadding(padding);
@@ -132,11 +104,7 @@ export abstract class BaseNode {
public updateCache(shapeMap) {
if (shapeMap.labelShape) {
const { maxWidth = '200%' } = this.mergedStyles.labelShape || {};
- this.#zoomCache.wordWrapWidth = getWordWrapWidthByBox(
- shapeMap.keyShape.getLocalBounds(),
- maxWidth,
- 1,
- );
+ this.#zoomCache.wordWrapWidth = getWordWrapWidthByBox(shapeMap.keyShape.getLocalBounds(), maxWidth, 1);
}
}
/**
@@ -168,6 +136,12 @@ export abstract class BaseNode {
* @param model The displayed model of this node, only for drawing and not received by users.
* @param shapeMap The shape map that contains all of the elements to show on the node.
* @param shapesChanged An array of shape IDs that have changed and need to be updated.
+ * @param diffData
+ * @param diffData.previous
+ * @param diffData.current
+ * @param diffState
+ * @param diffState.previous
+ * @param diffState.current
* @returns An object that contains some new shapes to be added to the node.
*/
public afterDraw(
@@ -190,11 +164,7 @@ export abstract class BaseNode {
* @param value state value
* @param shapeMap The shape map that contains all of the elements to show on the node.
*/
- public setState: (
- name: string,
- value: boolean,
- shapeMap: { [shapeId: string]: DisplayObject },
- ) => void;
+ public setState: (name: string, value: boolean, shapeMap: { [shapeId: string]: DisplayObject }) => void;
/**
* The key function of drawing shape.
@@ -221,6 +191,10 @@ export abstract class BaseNode {
* @param shapeMap The shape map that contains all of the elements to show on the node.
* @param diffData An object that contains previous and current data.
* @param diffState An object that contains previous and current node's state.
+ * @param diffData.previous
+ * @param diffData.current
+ * @param diffState.previous
+ * @param diffState.current
* @returns The display object representing the label shape of the node.
*/
public drawLabelShape(
@@ -235,11 +209,7 @@ export abstract class BaseNode {
const { labelShape: shapeStyle } = this.mergedStyles;
if (!shapeStyle || !shapeStyle.text || !model.data.labelShape) return;
const { keyShape } = shapeMap;
- const keyShapeBox = getShapeLocalBoundsByStyle(
- keyShape,
- this.mergedStyles.keyShape,
- keyShape.getLocalBounds(),
- );
+ const keyShapeBox = getShapeLocalBoundsByStyle(keyShape, this.mergedStyles.keyShape, keyShape.getLocalBounds());
const {
position,
offsetX: propsOffsetX,
@@ -298,15 +268,9 @@ export abstract class BaseNode {
positionPreset.offsetY = 2;
break;
}
- const offsetX = (
- propsOffsetX === undefined ? positionPreset.offsetX : propsOffsetX
- ) as number;
- const offsetY = (
- propsOffsetY === undefined ? positionPreset.offsetY : propsOffsetY
- ) as number;
- const offsetZ = (
- propsOffsetZ === undefined ? positionPreset.offsetZ : propsOffsetZ
- ) as number;
+ const offsetX = (propsOffsetX === undefined ? positionPreset.offsetX : propsOffsetX) as number;
+ const offsetY = (propsOffsetY === undefined ? positionPreset.offsetY : propsOffsetY) as number;
+ const offsetZ = (propsOffsetZ === undefined ? positionPreset.offsetZ : propsOffsetZ) as number;
positionPreset.x += offsetX;
positionPreset.y += offsetY;
positionPreset.z += offsetZ;
@@ -334,6 +298,10 @@ export abstract class BaseNode {
* @param shapeMap The shape map that contains all of the elements to show on the node.
* @param diffData An object that contains previous and current data.
* @param diffState An object that contains previous and current node's state.
+ * @param diffData.previous
+ * @param diffData.current
+ * @param diffState.previous
+ * @param diffState.current
* @returns The display object representing the label background shape of the node.
*/
public drawLabelBackgroundShape(
@@ -350,13 +318,9 @@ export abstract class BaseNode {
// label's local bounds, will take scale into account
const textBBoxGeo = labelShape.getGeometryBounds();
const height = textBBoxGeo.max[1] - textBBoxGeo.min[1];
- const width = Math.min(
- textBBoxGeo.max[0] - textBBoxGeo.min[0] + 2,
- labelShape.attributes.wordWrapWidth,
- );
+ const width = Math.min(textBBoxGeo.max[0] - textBBoxGeo.min[0] + 2, labelShape.attributes.wordWrapWidth);
- const { padding, ...backgroundStyle } =
- this.mergedStyles.labelBackgroundShape;
+ const { padding, ...backgroundStyle } = this.mergedStyles.labelBackgroundShape;
const bgStyle: any = {
fill: '#fff',
@@ -382,6 +346,10 @@ export abstract class BaseNode {
* @param shapeMap The shape map that contains all of the elements to show on the node.
* @param diffData An object that contains previous and current data.
* @param diffState An object that contains previous and current node's state.
+ * @param diffData.previous
+ * @param diffData.current
+ * @param diffState.previous
+ * @param diffState.current
* @returns The display object representing the icon shape of the node.
*/
public drawIconShape(
@@ -394,14 +362,7 @@ export abstract class BaseNode {
diffState?: { previous: State[]; current: State[] },
): DisplayObject {
const { iconShape: shapeStyle } = this.mergedStyles;
- const {
- width,
- height,
- fontSize,
- text,
- offsetX = 0,
- offsetY = 0,
- } = shapeStyle;
+ const { width, height, fontSize, text, offsetX = 0, offsetY = 0 } = shapeStyle;
const w = (width || fontSize) as number;
const h = (height || fontSize) as number;
const iconShapeType = text ? 'text' : 'image';
@@ -418,17 +379,12 @@ export abstract class BaseNode {
shapeStyle.fontSize = w;
}
- return this.upsertShape(
- iconShapeType,
- 'iconShape',
- shapeStyle as GShapeStyle,
- {
- shapeMap,
- model,
- diffData,
- diffState,
- },
- );
+ return this.upsertShape(iconShapeType, 'iconShape', shapeStyle as GShapeStyle, {
+ shapeMap,
+ model,
+ diffData,
+ diffState,
+ });
}
/**
@@ -437,6 +393,10 @@ export abstract class BaseNode {
* @param shapeMap The shape map that contains all of the elements to show on the node.
* @param diffData An object that contains previous and current data.
* @param diffState An object that contains previous and current node's state.
+ * @param diffData.previous
+ * @param diffData.current
+ * @param diffState.previous
+ * @param diffState.current
* @returns The display object representing the halo shape of the node.
*/
public drawHaloShape(
@@ -449,8 +409,7 @@ export abstract class BaseNode {
diffState?: { previous: State[]; current: State[] },
): DisplayObject {
const { keyShape } = shapeMap;
- const { haloShape: haloShapeStyle, keyShape: keyShapeStyle } =
- this.mergedStyles;
+ const { haloShape: haloShapeStyle, keyShape: keyShapeStyle } = this.mergedStyles;
if (haloShapeStyle.visible === false) return;
const { nodeName, attributes } = keyShape;
const { x, y, fill } = attributes;
@@ -479,6 +438,10 @@ export abstract class BaseNode {
* @param shapeMap The shape map that contains all of the elements to show on the node.
* @param diffData An object that contains previous and current data.
* @param diffState An object that contains previous and current node's state.
+ * @param diffData.previous
+ * @param diffData.current
+ * @param diffState.previous
+ * @param diffState.current
* @returns The display object representing the anchors shape of the node.
*/
public drawAnchorShapes(
@@ -492,22 +455,15 @@ export abstract class BaseNode {
): {
[shapeId: string]: DisplayObject;
} {
- const { anchorShapes: commonStyle, keyShape: keyShapeStyle } =
- this.mergedStyles;
+ const { anchorShapes: commonStyle, keyShape: keyShapeStyle } = this.mergedStyles;
- const individualConfigs = Object.values(this.mergedStyles).filter(
- (style) => style.tag === 'anchorShape',
- );
+ const individualConfigs = Object.values(this.mergedStyles).filter((style) => style.tag === 'anchorShape');
if (!individualConfigs.length) return;
const shapes = {};
const anchorPositionMap = this.calculateAnchorPosition(keyShapeStyle);
individualConfigs.forEach((config, i) => {
const { position, fill = keyShapeStyle.fill, ...style } = config;
- const [cx, cy] = this.#getAnchorPosition(
- position,
- anchorPositionMap,
- shapeMap,
- );
+ const [cx, cy] = this.#getAnchorPosition(position, anchorPositionMap, shapeMap);
const id = `anchorShape${i}`;
shapes[id] = this.upsertShape(
'circle',
@@ -543,18 +499,11 @@ export abstract class BaseNode {
keyShapeBBox.min[1] - keyShapeBBox.center[1],
]; //topRight
if (position instanceof Array) {
- return [
- keyShapeWidth * (position[0] - 0.5),
- keyShapeHeight * (position[1] - 0.5),
- ];
+ return [keyShapeWidth * (position[0] - 0.5), keyShapeHeight * (position[1] - 0.5)];
} else if (typeof position === 'string') {
position = position.toLowerCase();
//receive a unknown string, remind the user.
- return (
- anchorPositionMap[position] ||
- anchorPositionMap['default'] ||
- defaultPosition
- );
+ return anchorPositionMap[position] || anchorPositionMap['default'] || defaultPosition;
}
//receive a position in unknown type (such as a number or undefined).
return anchorPositionMap['default'] || defaultPosition;
@@ -584,6 +533,10 @@ export abstract class BaseNode {
* @param shapeMap The shape map that contains all of the elements to show on the node.
* @param diffData An object that contains previous and current data.
* @param diffState An object that contains previous and current node's state.
+ * @param diffData.previous
+ * @param diffData.current
+ * @param diffState.previous
+ * @param diffState.current
* @returns The display object representing the badges shape of the node.
*/
public drawBadgeShapes(
@@ -597,21 +550,15 @@ export abstract class BaseNode {
): {
[shapeId: string]: DisplayObject;
} {
- const { badgeShapes: commonStyle, keyShape: keyShapeStyle } =
- this.mergedStyles;
- const individualConfigs = Object.values(this.mergedStyles).filter(
- (style) => style.tag === 'badgeShape',
- );
+ const { badgeShapes: commonStyle, keyShape: keyShapeStyle } = this.mergedStyles;
+ const individualConfigs = Object.values(this.mergedStyles).filter((style) => style.tag === 'badgeShape');
if (!individualConfigs.length) return {};
const keyShapeBBox = getShapeLocalBoundsByStyle(
shapeMap.keyShape,
keyShapeStyle,
shapeMap.keyShape.getLocalBounds(),
);
- const keyShapeSize = Math.min(
- keyShapeBBox.max[0] - keyShapeBBox.min[0],
- keyShapeBBox.max[1] - keyShapeBBox.min[1],
- );
+ const keyShapeSize = Math.min(keyShapeBBox.max[0] - keyShapeBBox.min[0], keyShapeBBox.max[1] - keyShapeBBox.min[1]);
const shapes = {};
individualConfigs.forEach((config, i) => {
const { position, ...individualStyle } = config;
@@ -620,9 +567,7 @@ export abstract class BaseNode {
...commonStyle,
...individualStyle,
};
- const colorFromPalette = commonStyle.palette
- ? commonStyle.palette[i % commonStyle.palette.length]
- : '#7E92B5';
+ const colorFromPalette = commonStyle.palette ? commonStyle.palette[i % commonStyle.palette.length] : '#7E92B5';
const {
text = '',
type,
@@ -714,10 +659,7 @@ export abstract class BaseNode {
const bbox = shapes[id].getLocalBounds();
const bgShapeId = `${position}BadgeBackgroundShape`;
- const bgWidth =
- (text as string).length <= 1
- ? bgHeight
- : Math.max(bgHeight, bbox.max[0] - bbox.min[0]) + 8;
+ const bgWidth = (text as string).length <= 1 ? bgHeight : Math.max(bgHeight, bbox.max[0] - bbox.min[0]) + 8;
shapes[bgShapeId] = this.upsertShape(
'rect',
bgShapeId,
@@ -750,6 +692,10 @@ export abstract class BaseNode {
* @param shapeMap The shape map that contains all of the elements to show on the node.
* @param diffData An object that contains previous and current data.
* @param diffState An object that contains previous and current node's state.
+ * @param diffData.previous
+ * @param diffData.current
+ * @param diffState.previous
+ * @param diffState.current
* @returns The display object representing the other shapes of the node.
*/
public drawOtherShapes(
@@ -770,20 +716,26 @@ export abstract class BaseNode {
* 2. change the shapes' sizes to make them have same visual size while zooming, e.g. labelShape, labelBackgroundShape.
* @param shapeMap The shape map that contains all of the elements to show on the node.
* @param zoom The zoom level of the graph.
+ * @param cacheHiddenShape
*/
- public onZoom = (
- shapeMap: NodeShapeMap | ComboShapeMap,
- zoom: number,
- cacheHiddenShape = {},
- ) => {};
+ public onZoom = (shapeMap: NodeShapeMap | ComboShapeMap, zoom: number, cacheHiddenShape = {}) => {};
/**
* Create (if does not exit in shapeMap) or update the shape according to the configurations.
* @param type shape's type
* @param id unique string to indicates the shape
* @param style style to be updated
+ * @param config
* @param shapeMap the shape map of a node / combo
* @param model data model of the node / combo
+ * @param config.model
+ * @param config.shapeMap
+ * @param config.diffData
+ * @param config.diffData.previous
+ * @param config.diffData.current
+ * @param config.diffState
+ * @param config.diffState.previous
+ * @param config.diffState.current
* @returns The display object representing the shape.
*/
public upsertShape(
diff --git a/packages/g6/src/stdlib/item/node/base3d.ts b/packages/g6/src/stdlib/item/node/base3d.ts
index 94cc3b11ac1..6c6bf767dc6 100644
--- a/packages/g6/src/stdlib/item/node/base3d.ts
+++ b/packages/g6/src/stdlib/item/node/base3d.ts
@@ -1,25 +1,15 @@
import { DisplayObject } from '@antv/g';
import { NodeDisplayModel } from '../../../types';
-import {
- GShapeStyle,
- SHAPE_TYPE,
- SHAPE_TYPE_3D,
- ShapeStyle,
- State,
-} from '../../../types/item';
-import {
- NodeModelData,
- NodeShapeMap,
- NodeShapeStyles,
-} from '../../../types/node';
+import { GShapeStyle, SHAPE_TYPE, SHAPE_TYPE_3D, ShapeStyle, State } from '../../../types/item';
+import { NodeModelData, NodeShapeMap, NodeShapeStyles } from '../../../types/node';
import { upsertShape3D } from '../../../util/shape3d';
import { BaseNode } from './base';
export abstract class BaseNode3D extends BaseNode {
- type: string;
- defaultStyles: NodeShapeStyles;
- themeStyles: NodeShapeStyles;
- mergedStyles: NodeShapeStyles;
+ declare type: string;
+ declare defaultStyles: NodeShapeStyles;
+ declare themeStyles: NodeShapeStyles;
+ declare mergedStyles: NodeShapeStyles;
device: any; // for 3d renderer
dimensions: number = 3;
constructor(props) {
@@ -33,6 +23,10 @@ export abstract class BaseNode3D extends BaseNode {
* @param shapeMap The shape map that contains all of the elements to show on the 3D node.
* @param diffData An object that contains previous and current data.
* @param diffState An object that contains previous and current 3D node's state.
+ * @param diffData.previous
+ * @param diffData.current
+ * @param diffState.previous
+ * @param diffState.current
* @returns The display object representing the label shape of the 3D node.
*/
public drawLabelShape(
@@ -49,13 +43,7 @@ export abstract class BaseNode3D extends BaseNode {
max: [x + r || width / 2, y + r || height / 2, z + r || depth / 2],
};
const { labelShape: shapeStyle } = this.mergedStyles;
- const {
- position,
- offsetX: propsOffsetX,
- offsetY: propsOffsetY,
- maxWidth,
- ...otherStyle
- } = shapeStyle;
+ const { position, offsetX: propsOffsetX, offsetY: propsOffsetY, maxWidth, ...otherStyle } = shapeStyle;
const positionPreset = {
x: keyShapeBox.center[0],
@@ -91,12 +79,8 @@ export abstract class BaseNode3D extends BaseNode {
positionPreset.offsetY = 4;
break;
}
- const offsetX = (
- propsOffsetX === undefined ? positionPreset.offsetX : propsOffsetX
- ) as number;
- const offsetY = (
- propsOffsetY === undefined ? positionPreset.offsetY : propsOffsetY
- ) as number;
+ const offsetX = (propsOffsetX === undefined ? positionPreset.offsetX : propsOffsetX) as number;
+ const offsetY = (propsOffsetY === undefined ? positionPreset.offsetY : propsOffsetY) as number;
positionPreset.x += offsetX;
positionPreset.y += offsetY;
@@ -121,6 +105,10 @@ export abstract class BaseNode3D extends BaseNode {
* @param shapeMap The shape map that contains all of the elements to show on the 3D node.
* @param diffData An object that contains previous and current data.
* @param diffState An object that contains previous and current 3D node's state.
+ * @param diffData.previous
+ * @param diffData.current
+ * @param diffState.previous
+ * @param diffState.current
* @returns The display object representing the icon shape of the 3D node.
*/
public drawIconShape(
@@ -166,6 +154,10 @@ export abstract class BaseNode3D extends BaseNode {
* @param shapeMap
* @param diffData
* @param diffState
+ * @param diffData.previous
+ * @param diffData.current
+ * @param diffState.previous
+ * @param diffState.current
* @returns
*/
public drawAnchorShapes(
diff --git a/packages/g6/src/stdlib/item/node/circle.ts b/packages/g6/src/stdlib/item/node/circle.ts
index c4595dc55fa..d4efbdda88c 100644
--- a/packages/g6/src/stdlib/item/node/circle.ts
+++ b/packages/g6/src/stdlib/item/node/circle.ts
@@ -1,11 +1,7 @@
import { DisplayObject } from '@antv/g';
import { NodeDisplayModel } from '../../../types';
import { State } from '../../../types/item';
-import {
- NodeModelData,
- NodeShapeMap,
- NodeShapeStyles,
-} from '../../../types/node';
+import { NodeModelData, NodeShapeMap, NodeShapeStyles } from '../../../types/node';
import { BaseNode } from './base';
export class CircleNode extends BaseNode {
@@ -16,7 +12,7 @@ export class CircleNode extends BaseNode {
y: 0,
},
};
- mergedStyles: NodeShapeStyles;
+ declare mergedStyles: NodeShapeStyles;
constructor(props) {
super(props);
// suggest to merge default styles like this to avoid style value missing
@@ -36,42 +32,22 @@ export class CircleNode extends BaseNode {
// haloShape
if (data.haloShape && this.drawHaloShape) {
- shapes.haloShape = this.drawHaloShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.haloShape = this.drawHaloShape(model, shapeMap, diffData, diffState);
}
// labelShape
if (data.labelShape && this.drawLabelShape) {
- shapes.labelShape = this.drawLabelShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.labelShape = this.drawLabelShape(model, shapeMap, diffData, diffState);
}
// labelBackgroundShape
if (data.labelBackgroundShape && this.drawLabelBackgroundShape) {
- shapes.labelBackgroundShape = this.drawLabelBackgroundShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.labelBackgroundShape = this.drawLabelBackgroundShape(model, shapeMap, diffData, diffState);
}
// anchor shapes
if (data.anchorShapes && this.drawAnchorShapes) {
- const anchorShapes = this.drawAnchorShapes(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ const anchorShapes = this.drawAnchorShapes(model, shapeMap, diffData, diffState);
shapes = {
...shapes,
...anchorShapes,
@@ -80,22 +56,12 @@ export class CircleNode extends BaseNode {
// iconShape
if (data.iconShape && this.drawIconShape) {
- shapes.iconShape = this.drawIconShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.iconShape = this.drawIconShape(model, shapeMap, diffData, diffState);
}
// badgeShape
if (data.badgeShapes && this.drawBadgeShapes) {
- const badgeShapes = this.drawBadgeShapes(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ const badgeShapes = this.drawBadgeShapes(model, shapeMap, diffData, diffState);
shapes = {
...shapes,
...badgeShapes,
@@ -118,17 +84,12 @@ export class CircleNode extends BaseNode {
diffData?: { previous: NodeModelData; current: NodeModelData },
diffState?: { previous: State[]; current: State[] },
): DisplayObject {
- const shape = this.upsertShape(
- 'circle',
- 'keyShape',
- this.mergedStyles.keyShape,
- {
- model,
- shapeMap,
- diffData,
- diffState,
- },
- );
+ const shape = this.upsertShape('circle', 'keyShape', this.mergedStyles.keyShape, {
+ model,
+ shapeMap,
+ diffData,
+ diffState,
+ });
return shape;
}
}
diff --git a/packages/g6/src/stdlib/item/node/cube.ts b/packages/g6/src/stdlib/item/node/cube.ts
index b20fba4bc3c..c0762d0c3cc 100644
--- a/packages/g6/src/stdlib/item/node/cube.ts
+++ b/packages/g6/src/stdlib/item/node/cube.ts
@@ -1,11 +1,7 @@
import { DisplayObject } from '@antv/g';
import { NodeDisplayModel } from '../../../types';
import { State } from '../../../types/item';
-import {
- NodeModelData,
- NodeShapeMap,
- NodeShapeStyles,
-} from '../../../types/node';
+import { NodeModelData, NodeShapeMap, NodeShapeStyles } from '../../../types/node';
import { BaseNode3D } from './base3d';
export class CubeNode extends BaseNode3D {
@@ -19,7 +15,7 @@ export class CubeNode extends BaseNode3D {
z: 0,
},
};
- mergedStyles: NodeShapeStyles;
+ declare mergedStyles: NodeShapeStyles;
constructor(props) {
super(props);
}
@@ -38,52 +34,27 @@ export class CubeNode extends BaseNode3D {
// haloShape
if (data.haloShape && this.drawHaloShape) {
- shapes.haloShape = this.drawHaloShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.haloShape = this.drawHaloShape(model, shapeMap, diffData, diffState);
}
// labelShape
if (data.labelShape) {
- shapes.labelShape = this.drawLabelShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.labelShape = this.drawLabelShape(model, shapeMap, diffData, diffState);
}
// labelBackgroundShape
if (data.labelBackgroundShape) {
- shapes.labelBackgroundShape = this.drawLabelBackgroundShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.labelBackgroundShape = this.drawLabelBackgroundShape(model, shapeMap, diffData, diffState);
}
// iconShape
if (data.iconShape) {
- shapes.iconShape = this.drawIconShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.iconShape = this.drawIconShape(model, shapeMap, diffData, diffState);
}
// badgeShape
if (data.badgeShapes) {
- const badgeShapes = this.drawBadgeShapes(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ const badgeShapes = this.drawBadgeShapes(model, shapeMap, diffData, diffState);
shapes = {
...shapes,
...badgeShapes,
diff --git a/packages/g6/src/stdlib/item/node/diamond.ts b/packages/g6/src/stdlib/item/node/diamond.ts
index da771f8a873..9f606acd881 100644
--- a/packages/g6/src/stdlib/item/node/diamond.ts
+++ b/packages/g6/src/stdlib/item/node/diamond.ts
@@ -1,12 +1,7 @@
import { DisplayObject } from '@antv/g';
import { NodeDisplayModel } from '../../../types';
import { State } from '../../../types/item';
-import {
- IAnchorPositionMap,
- NodeModelData,
- NodeShapeMap,
- NodeShapeStyles,
-} from '../../../types/node';
+import { IAnchorPositionMap, NodeModelData, NodeShapeMap, NodeShapeStyles } from '../../../types/node';
import { BaseNode } from './base';
type PathArray = any; //TODO: cannot import type PathArray
export class DiamondNode extends BaseNode {
@@ -17,7 +12,7 @@ export class DiamondNode extends BaseNode {
y: 0,
},
};
- mergedStyles: NodeShapeStyles;
+ declare mergedStyles: NodeShapeStyles;
constructor(props) {
super(props);
// suggest to merge default styles like this to avoid style value missing
@@ -37,42 +32,22 @@ export class DiamondNode extends BaseNode {
// haloShape
if (data.haloShape && this.drawHaloShape) {
- shapes.haloShape = this.drawHaloShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.haloShape = this.drawHaloShape(model, shapeMap, diffData, diffState);
}
// labelShape
if (data.labelShape) {
- shapes.labelShape = this.drawLabelShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.labelShape = this.drawLabelShape(model, shapeMap, diffData, diffState);
}
// labelBackgroundShape
if (data.labelBackgroundShape) {
- shapes.labelBackgroundShape = this.drawLabelBackgroundShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.labelBackgroundShape = this.drawLabelBackgroundShape(model, shapeMap, diffData, diffState);
}
// anchor shapes
if (data.anchorShapes) {
- const anchorShapes = this.drawAnchorShapes(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ const anchorShapes = this.drawAnchorShapes(model, shapeMap, diffData, diffState);
shapes = {
...shapes,
...anchorShapes,
@@ -81,22 +56,12 @@ export class DiamondNode extends BaseNode {
// iconShape
if (data.iconShape) {
- shapes.iconShape = this.drawIconShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.iconShape = this.drawIconShape(model, shapeMap, diffData, diffState);
}
// badgeShape
if (data.badgeShapes) {
- const badgeShapes = this.drawBadgeShapes(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ const badgeShapes = this.drawBadgeShapes(model, shapeMap, diffData, diffState);
shapes = {
...shapes,
...badgeShapes,
@@ -151,9 +116,7 @@ export class DiamondNode extends BaseNode {
return path;
}
- public override calculateAnchorPosition(
- keyShapeStyle: any,
- ): IAnchorPositionMap {
+ public override calculateAnchorPosition(keyShapeStyle: any): IAnchorPositionMap {
const anchorPositionMap = {};
const { size } = keyShapeStyle;
const sizeArr = Array.isArray(size) ? size : [size, size];
diff --git a/packages/g6/src/stdlib/item/node/donut.ts b/packages/g6/src/stdlib/item/node/donut.ts
index cc8707bfc66..15a3032cc25 100644
--- a/packages/g6/src/stdlib/item/node/donut.ts
+++ b/packages/g6/src/stdlib/item/node/donut.ts
@@ -2,11 +2,7 @@ import { DisplayObject } from '@antv/g';
import { each } from '@antv/util';
import { NodeDisplayModel } from '../../../types';
import { ShapeStyle, State } from '../../../types/item';
-import {
- NodeModelData,
- NodeShapeMap,
- NodeShapeStyles,
-} from '../../../types/node';
+import { NodeModelData, NodeShapeMap, NodeShapeStyles } from '../../../types/node';
import { BaseNode } from './base';
const defaultDonutPalette = [
@@ -68,7 +64,7 @@ export class DonutNode extends BaseNode {
zIndex: 1,
},
};
- mergedStyles: NodeShapeStyles;
+ declare mergedStyles: NodeShapeStyles;
constructor(props) {
super(props);
// suggest to merge default styles like this to avoid style value missing
@@ -88,42 +84,22 @@ export class DonutNode extends BaseNode {
// haloShape
if (data.haloShape && this.drawHaloShape) {
- shapes.haloShape = this.drawHaloShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.haloShape = this.drawHaloShape(model, shapeMap, diffData, diffState);
}
// labelShape
if (data.labelShape) {
- shapes.labelShape = this.drawLabelShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.labelShape = this.drawLabelShape(model, shapeMap, diffData, diffState);
}
// labelBackgroundShape
if (data.labelBackgroundShape) {
- shapes.labelBackgroundShape = this.drawLabelBackgroundShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.labelBackgroundShape = this.drawLabelBackgroundShape(model, shapeMap, diffData, diffState);
}
// anchor shapes
if (data.anchorShapes) {
- const anchorShapes = this.drawAnchorShapes(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ const anchorShapes = this.drawAnchorShapes(model, shapeMap, diffData, diffState);
shapes = {
...shapes,
...anchorShapes,
@@ -132,22 +108,12 @@ export class DonutNode extends BaseNode {
// iconShape
if (data.iconShape) {
- shapes.iconShape = this.drawIconShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.iconShape = this.drawIconShape(model, shapeMap, diffData, diffState);
}
// badgeShape
if (data.badgeShapes) {
- const badgeShapes = this.drawBadgeShapes(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ const badgeShapes = this.drawBadgeShapes(model, shapeMap, diffData, diffState);
shapes = {
...shapes,
...badgeShapes,
@@ -156,12 +122,7 @@ export class DonutNode extends BaseNode {
// donutShapes
if (data.donutShapes) {
- const donutShapes = this.drawDonutShapes(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ const donutShapes = this.drawDonutShapes(model, shapeMap, diffData, diffState);
shapes = {
...shapes,
...donutShapes,
@@ -184,6 +145,10 @@ export class DonutNode extends BaseNode {
* @param shapeMap
* @param diffData
* @param diffState
+ * @param diffData.previous
+ * @param diffData.current
+ * @param diffState.previous
+ * @param diffState.current
* @returns
*/
private drawDonutShapes(
@@ -242,6 +207,10 @@ export class DonutNode extends BaseNode {
* @param shapeMap
* @param diffData
* @param diffState
+ * @param diffData.previous
+ * @param diffData.current
+ * @param diffState.previous
+ * @param diffState.current
* @returns
*/
private drawDonutSegment = (
@@ -255,16 +224,7 @@ export class DonutNode extends BaseNode {
beginAngle: number; // next begin angle
shouldEnd: boolean; // finish fans drawing
} => {
- const {
- arcR,
- beginAngle,
- config,
- index,
- lineWidth,
- zIndex,
- totalValue,
- drawWhole = false,
- } = cfg;
+ const { arcR, beginAngle, config, index, lineWidth, zIndex, totalValue, drawWhole = false } = cfg;
const id = `donutShape${index}`;
const percent = config.value / totalValue;
if (percent < 0.001) {
@@ -291,8 +251,7 @@ export class DonutNode extends BaseNode {
['M', arcBegin[0], arcBegin[1]],
['A', arcR, arcR, 0, isLargeArc, 0, arcEnd[0], arcEnd[1]],
],
- stroke:
- config.color || defaultDonutPalette[index % defaultDonutPalette.length],
+ stroke: config.color || defaultDonutPalette[index % defaultDonutPalette.length],
lineWidth,
zIndex,
} as ShapeStyle;
@@ -365,6 +324,7 @@ const getDonutConfig = (
/**
* calculate the lineWidth and radius for fan shapes according to the keyShape's radius
* @param keyShape
+ * @param innerSize
* @returns
*/
const getDonutSize = (
diff --git a/packages/g6/src/stdlib/item/node/ellipse.ts b/packages/g6/src/stdlib/item/node/ellipse.ts
index 5c0573dc8d8..e128f3155a2 100644
--- a/packages/g6/src/stdlib/item/node/ellipse.ts
+++ b/packages/g6/src/stdlib/item/node/ellipse.ts
@@ -1,11 +1,7 @@
import { DisplayObject } from '@antv/g';
import { NodeDisplayModel } from '../../../types';
import { State } from '../../../types/item';
-import {
- NodeModelData,
- NodeShapeMap,
- NodeShapeStyles,
-} from '../../../types/node';
+import { NodeModelData, NodeShapeMap, NodeShapeStyles } from '../../../types/node';
import { convertToNumber } from '../../../util/type';
import { BaseNode } from './base';
export class EllipseNode extends BaseNode {
@@ -17,7 +13,7 @@ export class EllipseNode extends BaseNode {
y: 0,
},
};
- mergedStyles: NodeShapeStyles;
+ declare mergedStyles: NodeShapeStyles;
constructor(props) {
super(props);
// suggest to merge default styles like this to avoid style value missing
@@ -37,41 +33,22 @@ export class EllipseNode extends BaseNode {
// haloShape
if (data.haloShape && this.drawHaloShape) {
- shapes.haloShape = this.drawHaloShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.haloShape = this.drawHaloShape(model, shapeMap, diffData, diffState);
}
// labelShape
if (data.labelShape) {
- shapes.labelShape = this.drawLabelShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.labelShape = this.drawLabelShape(model, shapeMap, diffData, diffState);
}
// labelBackgroundShape
if (data.labelBackgroundShape) {
- shapes.labelBackgroundShape = this.drawLabelBackgroundShape(
- model,
- shapeMap,
- diffData,
- );
+ shapes.labelBackgroundShape = this.drawLabelBackgroundShape(model, shapeMap, diffData);
}
// anchor shapes
if (data.anchorShapes) {
- const anchorShapes = this.drawAnchorShapes(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ const anchorShapes = this.drawAnchorShapes(model, shapeMap, diffData, diffState);
shapes = {
...shapes,
...anchorShapes,
@@ -80,22 +57,12 @@ export class EllipseNode extends BaseNode {
// iconShape
if (data.iconShape) {
- shapes.iconShape = this.drawIconShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.iconShape = this.drawIconShape(model, shapeMap, diffData, diffState);
}
// badgeShape
if (data.badgeShapes) {
- const badgeShapes = this.drawBadgeShapes(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ const badgeShapes = this.drawBadgeShapes(model, shapeMap, diffData, diffState);
shapes = {
...shapes,
...badgeShapes,
@@ -132,10 +99,7 @@ export class EllipseNode extends BaseNode {
const anchorPositionMap = {};
anchorPositionMap['top'] = [x, y - keyShapeStyle.ry];
anchorPositionMap['left'] = [x - keyShapeStyle.rx, y];
- anchorPositionMap['right'] = anchorPositionMap['default'] = [
- x + keyShapeStyle.rx,
- y,
- ];
+ anchorPositionMap['right'] = anchorPositionMap['default'] = [x + keyShapeStyle.rx, y];
anchorPositionMap['bottom'] = [x, y + keyShapeStyle.ry];
return anchorPositionMap;
}
diff --git a/packages/g6/src/stdlib/item/node/hexagon.ts b/packages/g6/src/stdlib/item/node/hexagon.ts
index d23ab40afd7..8bc1e29f4ad 100644
--- a/packages/g6/src/stdlib/item/node/hexagon.ts
+++ b/packages/g6/src/stdlib/item/node/hexagon.ts
@@ -1,12 +1,7 @@
import { DisplayObject } from '@antv/g';
import { NodeDisplayModel } from '../../../types';
import { State } from '../../../types/item';
-import {
- IAnchorPositionMap,
- NodeModelData,
- NodeShapeMap,
- NodeShapeStyles,
-} from '../../../types/node';
+import { IAnchorPositionMap, NodeModelData, NodeShapeMap, NodeShapeStyles } from '../../../types/node';
import { BaseNode } from './base';
const offsetAngleMap = {
@@ -23,7 +18,7 @@ export class HexagonNode extends BaseNode {
direction: 'vertical',
},
};
- mergedStyles: NodeShapeStyles;
+ declare mergedStyles: NodeShapeStyles;
constructor(props) {
super(props);
// suggest to merge default styles like this to avoid style value missing
@@ -43,42 +38,22 @@ export class HexagonNode extends BaseNode {
// haloShape
if (data.haloShape && this.drawHaloShape) {
- shapes.haloShape = this.drawHaloShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.haloShape = this.drawHaloShape(model, shapeMap, diffData, diffState);
}
// labelShape
if (data.labelShape) {
- shapes.labelShape = this.drawLabelShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.labelShape = this.drawLabelShape(model, shapeMap, diffData, diffState);
}
// labelBackgroundShape
if (data.labelBackgroundShape) {
- shapes.labelBackgroundShape = this.drawLabelBackgroundShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.labelBackgroundShape = this.drawLabelBackgroundShape(model, shapeMap, diffData, diffState);
}
// anchor shapes
if (data.anchorShapes) {
- const anchorShapes = this.drawAnchorShapes(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ const anchorShapes = this.drawAnchorShapes(model, shapeMap, diffData, diffState);
shapes = {
...shapes,
...anchorShapes,
@@ -87,22 +62,12 @@ export class HexagonNode extends BaseNode {
// iconShape
if (data.iconShape) {
- shapes.iconShape = this.drawIconShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.iconShape = this.drawIconShape(model, shapeMap, diffData, diffState);
}
// badgeShape
if (data.badgeShapes) {
- const badgeShapes = this.drawBadgeShapes(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ const badgeShapes = this.drawBadgeShapes(model, shapeMap, diffData, diffState);
shapes = {
...shapes,
...badgeShapes,
@@ -154,29 +119,11 @@ export class HexagonNode extends BaseNode {
return v;
}
- public override calculateAnchorPosition(
- keyShapeStyle: any,
- ): IAnchorPositionMap {
- const anchorPositionHorizontal = [
- 'right',
- 'rightbottom',
- 'leftbottom',
- 'left',
- 'lefttop',
- 'righttop',
- ];
- const anchorPositionVertical = [
- 'bottom',
- 'leftbottom',
- 'lefttop',
- 'top',
- 'righttop',
- 'rightbottom',
- ];
+ public override calculateAnchorPosition(keyShapeStyle: any): IAnchorPositionMap {
+ const anchorPositionHorizontal = ['right', 'rightbottom', 'leftbottom', 'left', 'lefttop', 'righttop'];
+ const anchorPositionVertical = ['bottom', 'leftbottom', 'lefttop', 'top', 'righttop', 'rightbottom'];
const anchorPositionDirection =
- keyShapeStyle.direction === 'horizontal'
- ? anchorPositionHorizontal
- : anchorPositionVertical;
+ keyShapeStyle.direction === 'horizontal' ? anchorPositionHorizontal : anchorPositionVertical;
const angleIncrement = Math.PI / 3; //The angle increment between vertex.
const offsetAngle = offsetAngleMap[keyShapeStyle.direction];
const r = keyShapeStyle.r;
@@ -187,9 +134,8 @@ export class HexagonNode extends BaseNode {
const vy = r * Math.sin(angle);
anchorPositionMap[anchorPositionDirection[i]] = [vx, vy];
}
- if (!anchorPositionMap.hasOwnProperty('default')) {
- anchorPositionMap['default'] =
- anchorPositionMap[anchorPositionDirection[0]];
+ if (!('default' in anchorPositionMap)) {
+ anchorPositionMap['default'] = anchorPositionMap[anchorPositionDirection[0]];
}
return anchorPositionMap;
}
diff --git a/packages/g6/src/stdlib/item/node/image.ts b/packages/g6/src/stdlib/item/node/image.ts
index 37753075dcf..4fef5be24a0 100644
--- a/packages/g6/src/stdlib/item/node/image.ts
+++ b/packages/g6/src/stdlib/item/node/image.ts
@@ -1,14 +1,10 @@
import { DisplayObject } from '@antv/g';
import { ComboDisplayModel, NodeDisplayModel } from '../../../types';
-import { State } from '../../../types/item';
-import {
- NodeModelData,
- NodeShapeMap,
- NodeShapeStyles,
-} from '../../../types/node';
-import { convertToNumber } from '../../../util/type';
import { ComboModelData, ComboShapeMap } from '../../../types/combo';
+import { State } from '../../../types/item';
+import { NodeModelData, NodeShapeMap, NodeShapeStyles } from '../../../types/node';
import { ShapeTagMap } from '../../../util/shape';
+import { convertToNumber } from '../../../util/type';
import { BaseNode } from './base';
export class ImageNode extends BaseNode {
@@ -20,7 +16,7 @@ export class ImageNode extends BaseNode {
height: 32,
},
};
- mergedStyles: NodeShapeStyles;
+ declare mergedStyles: NodeShapeStyles;
constructor(props) {
super(props);
// suggest to merge default styles like this to avoid style value missing
@@ -74,10 +70,7 @@ export class ImageNode extends BaseNode {
const anchorPositionMap = {};
anchorPositionMap['top'] = [x, y - height / 2];
anchorPositionMap['left'] = [x - width / 2, y];
- anchorPositionMap['right'] = anchorPositionMap['default'] = [
- x + width / 2,
- y,
- ];
+ anchorPositionMap['right'] = anchorPositionMap['default'] = [x + width / 2, y];
anchorPositionMap['bottom'] = [x, y + height / 2];
return anchorPositionMap;
}
@@ -106,21 +99,12 @@ export class ImageNode extends BaseNode {
// labelBackgroundShape
if (data.labelBackgroundShape) {
- shapes.labelBackgroundShape = this.drawLabelBackgroundShape(
- model,
- shapeMap,
- diffData,
- );
+ shapes.labelBackgroundShape = this.drawLabelBackgroundShape(model, shapeMap, diffData);
}
// anchor shapes
if (data.anchorShapes) {
- const anchorShapes = this.drawAnchorShapes(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ const anchorShapes = this.drawAnchorShapes(model, shapeMap, diffData, diffState);
shapes = {
...shapes,
...anchorShapes,
@@ -134,12 +118,7 @@ export class ImageNode extends BaseNode {
// badgeShape
if (data.badgeShapes) {
- const badgeShapes = this.drawBadgeShapes(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ const badgeShapes = this.drawBadgeShapes(model, shapeMap, diffData, diffState);
shapes = {
...shapes,
...badgeShapes,
@@ -166,8 +145,7 @@ export class ImageNode extends BaseNode {
diffState?: { previous: State[]; current: State[] },
): DisplayObject {
const { keyShape } = shapeMap;
- const { haloShape: haloShapeStyle, keyShape: keyShapeStyle } =
- this.mergedStyles;
+ const { haloShape: haloShapeStyle, keyShape: keyShapeStyle } = this.mergedStyles;
if (haloShapeStyle?.visible === false) return;
const clipShape = haloShapeStyle?.clipCfg?.type || 'rect';
diff --git a/packages/g6/src/stdlib/item/node/index.ts b/packages/g6/src/stdlib/item/node/index.ts
index 67b2951a9f5..bcf1dccb1b8 100644
--- a/packages/g6/src/stdlib/item/node/index.ts
+++ b/packages/g6/src/stdlib/item/node/index.ts
@@ -1,15 +1,15 @@
+export * from './base';
+export * from './base3d';
export * from './circle';
-export * from './sphere';
-export * from './rect';
-export * from './star';
-export * from './hexagon';
-export * from './triangle';
-export * from './ellipse';
-export * from './donut';
+export * from './cube';
export * from './diamond';
-export * from './modelRect';
+export * from './donut';
+export * from './ellipse';
+export * from './hexagon';
export * from './image';
-export * from './cube';
+export * from './modelRect';
export * from './plane';
-export * from './base';
-export * from './base3d';
+export * from './rect';
+export * from './sphere';
+export * from './star';
+export * from './triangle';
diff --git a/packages/g6/src/stdlib/item/node/modelRect.ts b/packages/g6/src/stdlib/item/node/modelRect.ts
index 707e44e9271..db7b33af823 100644
--- a/packages/g6/src/stdlib/item/node/modelRect.ts
+++ b/packages/g6/src/stdlib/item/node/modelRect.ts
@@ -1,18 +1,8 @@
-import { DisplayObject, AABB } from '@antv/g';
+import { DisplayObject } from '@antv/g';
import { NodeDisplayModel } from '../../../types';
+import { ComboDisplayModel, ComboModelData, ComboShapeMap } from '../../../types/combo';
import { State } from '../../../types/item';
-import {
- IAnchorPositionMap,
- NodeModelData,
- NodeShapeMap,
- NodeShapeStyles,
- NodeUserModelData,
-} from '../../../types/node';
-import {
- ComboDisplayModel,
- ComboModelData,
- ComboShapeMap,
-} from '../../../types/combo';
+import { IAnchorPositionMap, NodeModelData, NodeShapeMap, NodeShapeStyles } from '../../../types/node';
import { convertToNumber } from '../../../util/type';
import { BaseNode } from './base';
@@ -61,7 +51,7 @@ export class ModelRectNode extends BaseNode {
offsetY: 0,
},
};
- mergedStyles: NodeShapeStyles;
+ declare mergedStyles: NodeShapeStyles;
logoX: number; //The x-coordinate of logoIcon
logoY: number; //The y-coordinate of logoIcon
logoWidth: number; //The width of logoIcon
@@ -85,21 +75,11 @@ export class ModelRectNode extends BaseNode {
// haloShape
if (data.haloShape && this.drawHaloShape) {
- shapes.haloShape = this.drawHaloShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.haloShape = this.drawHaloShape(model, shapeMap, diffData, diffState);
}
// anchor shapes
if (data.anchorShapes) {
- const anchorShapes = this.drawAnchorShapes(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ const anchorShapes = this.drawAnchorShapes(model, shapeMap, diffData, diffState);
shapes = {
...shapes,
...anchorShapes,
@@ -108,12 +88,7 @@ export class ModelRectNode extends BaseNode {
//logoIconShape
if (data.iconShape) {
- shapes.iconShape = this.drawIconShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.iconShape = this.drawIconShape(model, shapeMap, diffData, diffState);
}
// otherShapes
@@ -126,12 +101,7 @@ export class ModelRectNode extends BaseNode {
// labelShape (after drawOtherShapes)
if (data.labelShape) {
- shapes.labelShape = this.drawLabelShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.labelShape = this.drawLabelShape(model, shapeMap, diffData, diffState);
}
return shapes;
}
@@ -160,19 +130,14 @@ export class ModelRectNode extends BaseNode {
);
}
- public override calculateAnchorPosition(
- keyShapeStyle: any,
- ): IAnchorPositionMap {
+ public override calculateAnchorPosition(keyShapeStyle: any): IAnchorPositionMap {
const x = convertToNumber(keyShapeStyle.x);
const y = convertToNumber(keyShapeStyle.y);
const { height, width } = keyShapeStyle;
const anchorPositionMap = {};
anchorPositionMap['top'] = [x, y - height / 2];
anchorPositionMap['left'] = [x - width / 2, y];
- anchorPositionMap['right'] = anchorPositionMap['default'] = [
- x + width / 2,
- y,
- ];
+ anchorPositionMap['right'] = anchorPositionMap['default'] = [x + width / 2, y];
anchorPositionMap['bottom'] = [x, y + height / 2];
return anchorPositionMap;
}
@@ -195,24 +160,16 @@ export class ModelRectNode extends BaseNode {
if (!labelShapeStyle) return;
const { width, height, x, y } = keyShapeStyle;
- const { offsetX: labelOffsetX = 0, offsetY: labelOffsetY = 0 } =
- labelShapeStyle;
+ const { offsetX: labelOffsetX = 0, offsetY: labelOffsetY = 0 } = labelShapeStyle;
const mixDisplay = descriptionStyle.show;
- const defaultLabelFontSize = mixDisplay
- ? Math.min(height, width) / 4
- : Math.min(height, width) / 6; //match with keyShape
+ const defaultLabelFontSize = mixDisplay ? Math.min(height, width) / 4 : Math.min(height, width) / 6; //match with keyShape
const logoIconBBox = shapeMap['logoIcon']?.getBBox();
- const defaultLabelX = mixDisplay
- ? -width / 2 + logoIconBBox?.width + width / 10
- : 0;
+ const defaultLabelX = mixDisplay ? -width / 2 + logoIconBBox?.width + width / 10 : 0;
const defaultLabelY = mixDisplay ? 0 - height / 7 : 0;
const defaultWordWrapWidth =
- width / 2 -
- (logoIconBBox.left + logoIconBBox.width + width / 20) -
- defaultLabelFontSize * 2 -
- labelOffsetX;
+ width / 2 - (logoIconBBox.left + logoIconBBox.width + width / 20) - defaultLabelFontSize * 2 - labelOffsetX;
labelShapeStyle.maxWidth = defaultWordWrapWidth;
return this.upsertShape(
@@ -257,38 +214,10 @@ export class ModelRectNode extends BaseNode {
} = this.mergedStyles as any;
const shapes = {
- preRect: this.drawPreRectShape(
- preRectStyle,
- keyShapeStyle,
- model,
- shapeMap,
- diffData,
- diffState,
- ),
- logoIcon: this.drawLogoIconShape(
- logoIconStyle,
- keyShapeStyle,
- model,
- shapeMap,
- diffData,
- diffState,
- ),
- description: this.drawDescriptionShape(
- descriptionStyle,
- keyShapeStyle,
- model,
- shapeMap,
- diffData,
- diffState,
- ),
- stateIcon: this.drawStateIcon(
- stateIconStyle,
- keyShapeStyle,
- model,
- shapeMap,
- diffData,
- diffState,
- ),
+ preRect: this.drawPreRectShape(preRectStyle, keyShapeStyle, model, shapeMap, diffData, diffState),
+ logoIcon: this.drawLogoIconShape(logoIconStyle, keyShapeStyle, model, shapeMap, diffData, diffState),
+ description: this.drawDescriptionShape(descriptionStyle, keyShapeStyle, model, shapeMap, diffData, diffState),
+ stateIcon: this.drawStateIcon(stateIconStyle, keyShapeStyle, model, shapeMap, diffData, diffState),
};
return shapes;
@@ -353,18 +282,11 @@ export class ModelRectNode extends BaseNode {
const logoIconShapeType = logoIconText ? 'text' : 'image';
// calculate logo position
- const logoX =
- convertToNumber(x) -
- convertToNumber(width) / 2 +
- logoIconOffsetX +
- width / 10 -
- logoIconWidth / 2;
+ const logoX = convertToNumber(x) - convertToNumber(width) / 2 + logoIconOffsetX + width / 10 - logoIconWidth / 2;
const logoY = logoIconText
? logoIconOffsetY
- : convertToNumber(y) -
- convertToNumber(logoIconHeight) / 2 +
- logoIconOffsetY;
+ : convertToNumber(y) - convertToNumber(logoIconHeight) / 2 + logoIconOffsetY;
if (logoIconText) {
logoIconStyle.textAlign = 'center';
@@ -403,17 +325,12 @@ export class ModelRectNode extends BaseNode {
) {
if (!descriptionStyle || !descriptionStyle.show) return;
const { width, height } = keyShapeStyle;
- const {
- fontSize: descFontSize,
- offsetX: descOffsetX,
- offsetY: descOffsetY,
- } = descriptionStyle;
+ const { fontSize: descFontSize, offsetX: descOffsetX, offsetY: descOffsetY } = descriptionStyle;
const logoIconBBox = shapeMap['logoIcon']?.getBBox();
const defaultLabelFontSize = Math.min(height, width) / 5;
const defaultDescriptionX = -width / 2 + logoIconBBox?.width + width / 10;
- const defaultWordWrapWidth =
- width / 2 - defaultDescriptionX - defaultLabelFontSize * 2;
+ const defaultWordWrapWidth = width / 2 - defaultDescriptionX - defaultLabelFontSize * 2;
const defaultDescriptionFontSize = defaultLabelFontSize / 2;
return this.upsertShape(
@@ -462,16 +379,10 @@ export class ModelRectNode extends BaseNode {
const stateIconShapeType = stateIconText ? 'text' : 'image';
// Calculate state position
- const stateX =
- convertToNumber(x) +
- convertToNumber(width) / 2 -
- stateIconWidth +
- stateIconOffsetX;
+ const stateX = convertToNumber(x) + convertToNumber(width) / 2 - stateIconWidth + stateIconOffsetX;
const stateY = stateIconText
? stateIconOffsetY
- : convertToNumber(y) -
- convertToNumber(stateIconHeight || stateIconFontSize) / 2 +
- stateIconOffsetY;
+ : convertToNumber(y) - convertToNumber(stateIconHeight || stateIconFontSize) / 2 + stateIconOffsetY;
if (stateIconText) {
stateIconStyle.textAlign = 'center';
diff --git a/packages/g6/src/stdlib/item/node/plane.ts b/packages/g6/src/stdlib/item/node/plane.ts
index ca49a960a13..ea6d3b85c53 100644
--- a/packages/g6/src/stdlib/item/node/plane.ts
+++ b/packages/g6/src/stdlib/item/node/plane.ts
@@ -1,11 +1,7 @@
import { DisplayObject } from '@antv/g';
import { NodeDisplayModel } from '../../../types';
import { State } from '../../../types/item';
-import {
- NodeModelData,
- NodeShapeMap,
- NodeShapeStyles,
-} from '../../../types/node';
+import { NodeModelData, NodeShapeMap, NodeShapeStyles } from '../../../types/node';
import { BaseNode3D } from './base3d';
export class PlaneNode extends BaseNode3D {
@@ -24,7 +20,7 @@ export class PlaneNode extends BaseNode3D {
z: 0,
},
};
- mergedStyles: NodeShapeStyles;
+ declare mergedStyles: NodeShapeStyles;
constructor(props) {
super(props);
}
@@ -43,52 +39,27 @@ export class PlaneNode extends BaseNode3D {
// haloShape
if (data.haloShape && this.drawHaloShape) {
- shapes.haloShape = this.drawHaloShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.haloShape = this.drawHaloShape(model, shapeMap, diffData, diffState);
}
// labelShape
if (data.labelShape) {
- shapes.labelShape = this.drawLabelShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.labelShape = this.drawLabelShape(model, shapeMap, diffData, diffState);
}
// labelBackgroundShape
if (data.labelBackgroundShape) {
- shapes.labelBackgroundShape = this.drawLabelBackgroundShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.labelBackgroundShape = this.drawLabelBackgroundShape(model, shapeMap, diffData, diffState);
}
// iconShape
if (data.iconShape) {
- shapes.iconShape = this.drawIconShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.iconShape = this.drawIconShape(model, shapeMap, diffData, diffState);
}
// badgeShape
if (data.badgeShapes) {
- const badgeShapes = this.drawBadgeShapes(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ const badgeShapes = this.drawBadgeShapes(model, shapeMap, diffData, diffState);
shapes = {
...shapes,
...badgeShapes,
diff --git a/packages/g6/src/stdlib/item/node/rect.ts b/packages/g6/src/stdlib/item/node/rect.ts
index 7aa9cc17adb..78c1be8e805 100644
--- a/packages/g6/src/stdlib/item/node/rect.ts
+++ b/packages/g6/src/stdlib/item/node/rect.ts
@@ -2,11 +2,7 @@ import { DisplayObject } from '@antv/g';
import { NodeDisplayModel } from '../../../types';
import { State } from '../../../types/item';
-import {
- NodeModelData,
- NodeShapeMap,
- NodeShapeStyles,
-} from '../../../types/node';
+import { NodeModelData, NodeShapeMap, NodeShapeStyles } from '../../../types/node';
import { convertToNumber } from '../../../util/type';
import { BaseNode } from './base';
@@ -19,7 +15,7 @@ export class RectNode extends BaseNode {
height: 32,
},
};
- mergedStyles: NodeShapeStyles;
+ declare mergedStyles: NodeShapeStyles;
constructor(props) {
super(props);
// suggest to merge default styles like this to avoid style value missing
@@ -37,12 +33,8 @@ export class RectNode extends BaseNode {
'keyShape',
{
...this.mergedStyles.keyShape,
- x:
- (this.mergedStyles.keyShape.x as number) -
- this.mergedStyles.keyShape.width / 2,
- y:
- (this.mergedStyles.keyShape.y as number) -
- this.mergedStyles.keyShape.height / 2,
+ x: (this.mergedStyles.keyShape.x as number) - this.mergedStyles.keyShape.width / 2,
+ y: (this.mergedStyles.keyShape.y as number) - this.mergedStyles.keyShape.height / 2,
},
{
model,
@@ -61,10 +53,7 @@ export class RectNode extends BaseNode {
const anchorPositionMap = {};
anchorPositionMap['top'] = [x, y - height / 2];
anchorPositionMap['left'] = [x - width / 2, y];
- anchorPositionMap['right'] = anchorPositionMap['default'] = [
- x + width / 2,
- y,
- ];
+ anchorPositionMap['right'] = anchorPositionMap['default'] = [x + width / 2, y];
anchorPositionMap['bottom'] = [x, y + height / 2];
return anchorPositionMap;
}
@@ -83,42 +72,22 @@ export class RectNode extends BaseNode {
// labelShape
if (data.labelShape) {
- shapes.labelShape = this.drawLabelShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.labelShape = this.drawLabelShape(model, shapeMap, diffData, diffState);
}
// haloShape
if (data.haloShape && this.drawHaloShape) {
- shapes.haloShape = this.drawHaloShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.haloShape = this.drawHaloShape(model, shapeMap, diffData, diffState);
}
// labelBackgroundShape
if (data.labelBackgroundShape) {
- shapes.labelBackgroundShape = this.drawLabelBackgroundShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.labelBackgroundShape = this.drawLabelBackgroundShape(model, shapeMap, diffData, diffState);
}
// anchor shapes
if (data.anchorShapes) {
- const anchorShapes = this.drawAnchorShapes(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ const anchorShapes = this.drawAnchorShapes(model, shapeMap, diffData, diffState);
shapes = {
...shapes,
...anchorShapes,
@@ -127,22 +96,12 @@ export class RectNode extends BaseNode {
// iconShape
if (data.iconShape) {
- shapes.iconShape = this.drawIconShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.iconShape = this.drawIconShape(model, shapeMap, diffData, diffState);
}
// badgeShape
if (data.badgeShapes) {
- const badgeShapes = this.drawBadgeShapes(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ const badgeShapes = this.drawBadgeShapes(model, shapeMap, diffData, diffState);
shapes = {
...shapes,
...badgeShapes,
diff --git a/packages/g6/src/stdlib/item/node/sphere.ts b/packages/g6/src/stdlib/item/node/sphere.ts
index 08ce834549f..95e83ac2ece 100644
--- a/packages/g6/src/stdlib/item/node/sphere.ts
+++ b/packages/g6/src/stdlib/item/node/sphere.ts
@@ -1,11 +1,7 @@
import { DisplayObject } from '@antv/g';
import { NodeDisplayModel } from '../../../types';
import { State } from '../../../types/item';
-import {
- NodeModelData,
- NodeShapeMap,
- NodeShapeStyles,
-} from '../../../types/node';
+import { NodeModelData, NodeShapeMap, NodeShapeStyles } from '../../../types/node';
import { BaseNode3D } from './base3d';
export class SphereNode extends BaseNode3D {
@@ -19,7 +15,7 @@ export class SphereNode extends BaseNode3D {
z: 0,
},
};
- mergedStyles: NodeShapeStyles;
+ declare mergedStyles: NodeShapeStyles;
constructor(props) {
super(props);
}
@@ -37,52 +33,27 @@ export class SphereNode extends BaseNode3D {
// haloShape
if (data.haloShape && this.drawHaloShape) {
- shapes.haloShape = this.drawHaloShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.haloShape = this.drawHaloShape(model, shapeMap, diffData, diffState);
}
// labelShape
if (data.labelShape) {
- shapes.labelShape = this.drawLabelShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.labelShape = this.drawLabelShape(model, shapeMap, diffData, diffState);
}
// labelBackgroundShape
if (data.labelBackgroundShape) {
- shapes.labelBackgroundShape = this.drawLabelBackgroundShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.labelBackgroundShape = this.drawLabelBackgroundShape(model, shapeMap, diffData, diffState);
}
// iconShape
if (data.iconShape) {
- shapes.iconShape = this.drawIconShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.iconShape = this.drawIconShape(model, shapeMap, diffData, diffState);
}
// badgeShape
if (data.badgeShapes) {
- const badgeShapes = this.drawBadgeShapes(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ const badgeShapes = this.drawBadgeShapes(model, shapeMap, diffData, diffState);
shapes = {
...shapes,
...badgeShapes,
diff --git a/packages/g6/src/stdlib/item/node/star.ts b/packages/g6/src/stdlib/item/node/star.ts
index 66ca0995371..2f271199548 100644
--- a/packages/g6/src/stdlib/item/node/star.ts
+++ b/packages/g6/src/stdlib/item/node/star.ts
@@ -1,12 +1,7 @@
import { DisplayObject } from '@antv/g';
import { NodeDisplayModel } from '../../../types';
import { State } from '../../../types/item';
-import {
- IAnchorPositionMap,
- NodeModelData,
- NodeShapeMap,
- NodeShapeStyles,
-} from '../../../types/node';
+import { IAnchorPositionMap, NodeModelData, NodeShapeMap, NodeShapeStyles } from '../../../types/node';
import { BaseNode } from './base';
export class StarNode extends BaseNode {
@@ -17,7 +12,7 @@ export class StarNode extends BaseNode {
y: 0,
},
};
- mergedStyles: NodeShapeStyles;
+ declare mergedStyles: NodeShapeStyles;
constructor(props) {
super(props);
// suggest to merge default styles like this to avoid style value missing
@@ -37,42 +32,22 @@ export class StarNode extends BaseNode {
// haloShape
if (data.haloShape && this.drawHaloShape) {
- shapes.haloShape = this.drawHaloShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.haloShape = this.drawHaloShape(model, shapeMap, diffData, diffState);
}
// labelShape
if (data.labelShape) {
- shapes.labelShape = this.drawLabelShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.labelShape = this.drawLabelShape(model, shapeMap, diffData, diffState);
}
// labelBackgroundShape
if (data.labelBackgroundShape) {
- shapes.labelBackgroundShape = this.drawLabelBackgroundShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.labelBackgroundShape = this.drawLabelBackgroundShape(model, shapeMap, diffData, diffState);
}
// anchor shapes
if (data.anchorShapes) {
- const anchorShapes = this.drawAnchorShapes(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ const anchorShapes = this.drawAnchorShapes(model, shapeMap, diffData, diffState);
shapes = {
...shapes,
...anchorShapes,
@@ -81,22 +56,12 @@ export class StarNode extends BaseNode {
// iconShape
if (data.iconShape) {
- shapes.iconShape = this.drawIconShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.iconShape = this.drawIconShape(model, shapeMap, diffData, diffState);
}
// badgeShape
if (data.badgeShapes) {
- const badgeShapes = this.drawBadgeShapes(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ const badgeShapes = this.drawBadgeShapes(model, shapeMap, diffData, diffState);
shapes = {
...shapes,
...badgeShapes,
@@ -144,55 +109,28 @@ export class StarNode extends BaseNode {
}
return [
['M', 0, -outerR],
- [
- 'L',
- innerR * Math.cos((3 * Math.PI) / 10),
- -innerR * Math.sin((3 * Math.PI) / 10),
- ],
+ ['L', innerR * Math.cos((3 * Math.PI) / 10), -innerR * Math.sin((3 * Math.PI) / 10)],
['L', outerR * Math.cos(Math.PI / 10), -outerR * Math.sin(Math.PI / 10)],
['L', innerR * Math.cos(Math.PI / 10), innerR * Math.sin(Math.PI / 10)],
- [
- 'L',
- outerR * Math.cos((3 * Math.PI) / 10),
- outerR * Math.sin((3 * Math.PI) / 10),
- ],
+ ['L', outerR * Math.cos((3 * Math.PI) / 10), outerR * Math.sin((3 * Math.PI) / 10)],
['L', 0, innerR],
- [
- 'L',
- -outerR * Math.cos((3 * Math.PI) / 10),
- outerR * Math.sin((3 * Math.PI) / 10),
- ],
+ ['L', -outerR * Math.cos((3 * Math.PI) / 10), outerR * Math.sin((3 * Math.PI) / 10)],
['L', -innerR * Math.cos(Math.PI / 10), innerR * Math.sin(Math.PI / 10)],
['L', -outerR * Math.cos(Math.PI / 10), -outerR * Math.sin(Math.PI / 10)],
- [
- 'L',
- -innerR * Math.cos((3 * Math.PI) / 10),
- -innerR * Math.sin((3 * Math.PI) / 10),
- ],
+ ['L', -innerR * Math.cos((3 * Math.PI) / 10), -innerR * Math.sin((3 * Math.PI) / 10)],
'Z',
];
}
- public override calculateAnchorPosition(
- keyShapeStyle: any,
- ): IAnchorPositionMap {
+ public override calculateAnchorPosition(keyShapeStyle: any): IAnchorPositionMap {
const anchorPositionMap = {};
const outerR = keyShapeStyle.outerR;
const innerR = keyShapeStyle.innerR;
anchorPositionMap['top'] = [0, -outerR];
- anchorPositionMap['left'] = [
- -outerR * Math.cos(Math.PI / 10),
- -outerR * Math.sin(Math.PI / 10),
- ];
- anchorPositionMap['leftbottom'] = [
- -outerR * Math.cos((3 * Math.PI) / 10),
- outerR * Math.sin((3 * Math.PI) / 10),
- ];
+ anchorPositionMap['left'] = [-outerR * Math.cos(Math.PI / 10), -outerR * Math.sin(Math.PI / 10)];
+ anchorPositionMap['leftbottom'] = [-outerR * Math.cos((3 * Math.PI) / 10), outerR * Math.sin((3 * Math.PI) / 10)];
anchorPositionMap['bottom'] = [0, innerR];
- anchorPositionMap['rightbottom'] = [
- outerR * Math.cos((3 * Math.PI) / 10),
- outerR * Math.sin((3 * Math.PI) / 10),
- ];
+ anchorPositionMap['rightbottom'] = [outerR * Math.cos((3 * Math.PI) / 10), outerR * Math.sin((3 * Math.PI) / 10)];
anchorPositionMap['right'] = anchorPositionMap['default'] = [
outerR * Math.cos(Math.PI / 10),
-outerR * Math.sin(Math.PI / 10),
diff --git a/packages/g6/src/stdlib/item/node/triangle.ts b/packages/g6/src/stdlib/item/node/triangle.ts
index eea04d3b02d..25c20c29cf8 100644
--- a/packages/g6/src/stdlib/item/node/triangle.ts
+++ b/packages/g6/src/stdlib/item/node/triangle.ts
@@ -1,16 +1,8 @@
import { DisplayObject } from '@antv/g';
import { NodeDisplayModel } from '../../../types';
-import {
- ComboDisplayModel,
- ComboModelData,
- ComboShapeMap,
-} from '../../../types/combo';
+import { ComboDisplayModel, ComboModelData, ComboShapeMap } from '../../../types/combo';
import { GShapeStyle, State } from '../../../types/item';
-import {
- NodeModelData,
- NodeShapeMap,
- NodeShapeStyles,
-} from '../../../types/node';
+import { NodeModelData, NodeShapeMap, NodeShapeStyles } from '../../../types/node';
import { BaseNode } from './base';
type PathArray = any;
@@ -24,7 +16,7 @@ export class TriangleNode extends BaseNode {
direction: 'up', //'up'|'left'|'right'|'down'
},
};
- mergedStyles: NodeShapeStyles;
+ declare mergedStyles: NodeShapeStyles;
constructor(props) {
super(props);
// suggest to merge default styles like this to avoid style value missing
@@ -44,41 +36,22 @@ export class TriangleNode extends BaseNode {
// haloShape
if (data.haloShape && this.drawHaloShape) {
- shapes.haloShape = this.drawHaloShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.haloShape = this.drawHaloShape(model, shapeMap, diffData, diffState);
}
// labelShape
if (data.labelShape) {
- shapes.labelShape = this.drawLabelShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.labelShape = this.drawLabelShape(model, shapeMap, diffData, diffState);
}
// labelBackgroundShape
if (data.labelBackgroundShape) {
- shapes.labelBackgroundShape = this.drawLabelBackgroundShape(
- model,
- shapeMap,
- diffData,
- );
+ shapes.labelBackgroundShape = this.drawLabelBackgroundShape(model, shapeMap, diffData);
}
// anchor shapes
if (data.anchorShapes) {
- const anchorShapes = this.drawAnchorShapes(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ const anchorShapes = this.drawAnchorShapes(model, shapeMap, diffData, diffState);
shapes = {
...shapes,
...anchorShapes,
@@ -87,22 +60,12 @@ export class TriangleNode extends BaseNode {
// iconShape
if (data.iconShape) {
- shapes.iconShape = this.drawIconShape(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ shapes.iconShape = this.drawIconShape(model, shapeMap, diffData, diffState);
}
// badgeShape
if (data.badgeShapes) {
- const badgeShapes = this.drawBadgeShapes(
- model,
- shapeMap,
- diffData,
- diffState,
- );
+ const badgeShapes = this.drawBadgeShapes(model, shapeMap, diffData, diffState);
shapes = {
...shapes,
...badgeShapes,
@@ -141,48 +104,33 @@ export class TriangleNode extends BaseNode {
},
);
}
- private getTrianglePath(
- r: number,
- direction: 'up' | 'down' | 'left' | 'right',
- ): PathArray {
+ private getTrianglePath(r: number, direction: 'up' | 'down' | 'left' | 'right'): PathArray {
const halfHeight = (3 * r) / 2;
const halfLength = (3 * r) / Math.sin((1 / 3) * Math.PI) / 2;
let path: PathArray;
if (direction === 'down') {
- path = [
- ['M', 0, halfHeight],
- ['L', halfLength, -halfHeight],
- ['L', -halfLength, -halfHeight],
- ['Z'],
- ];
+ path = [['M', 0, halfHeight], ['L', halfLength, -halfHeight], ['L', -halfLength, -halfHeight], ['Z']];
} else if (direction === 'left') {
- path = [
- ['M', -halfHeight, 0],
- ['L', halfHeight, halfLength],
- ['L', halfHeight, -halfLength],
- ['Z'],
- ];
+ path = [['M', -halfHeight, 0], ['L', halfHeight, halfLength], ['L', halfHeight, -halfLength], ['Z']];
} else if (direction === 'right') {
- path = [
- ['M', halfHeight, 0],
- ['L', -halfHeight, halfLength],
- ['L', -halfHeight, -halfLength],
- ['Z'],
- ];
+ path = [['M', halfHeight, 0], ['L', -halfHeight, halfLength], ['L', -halfHeight, -halfLength], ['Z']];
} else {
//up
- path = [
- ['M', 0, -halfHeight],
- ['L', halfLength, halfHeight],
- ['L', -halfLength, halfHeight],
- ['Z'],
- ];
+ path = [['M', 0, -halfHeight], ['L', halfLength, halfHeight], ['L', -halfLength, halfHeight], ['Z']];
}
return path;
}
/**
+ * @param model
+ * @param shapeMap
+ * @param diffData
+ * @param diffData.previous
+ * @param diffData.current
+ * @param diffState
+ * @param diffState.previous
+ * @param diffState.current
* @description: add 'defaultOffsetX' and 'defaultOffsetY' making the icon align to the triangle center
*/
public override drawIconShape(
@@ -209,14 +157,7 @@ export class TriangleNode extends BaseNode {
defaultOffsetX = 0;
defaultOffsetY = -keyShapeStyle.r / 4;
}
- const {
- width,
- height,
- fontSize,
- text,
- offsetX = 0,
- offsetY = 0,
- } = shapeStyle;
+ const { width, height, fontSize, text, offsetX = 0, offsetY = 0 } = shapeStyle;
const w = (width || fontSize) as number;
const h = (height || fontSize) as number;
const iconShapeType = text ? 'text' : 'image';
@@ -233,17 +174,12 @@ export class TriangleNode extends BaseNode {
shapeStyle.fontSize = w;
}
- return this.upsertShape(
- iconShapeType,
- 'iconShape',
- shapeStyle as GShapeStyle,
- {
- model,
- shapeMap,
- diffData,
- diffState,
- },
- );
+ return this.upsertShape(iconShapeType, 'iconShape', shapeStyle as GShapeStyle, {
+ model,
+ shapeMap,
+ diffData,
+ diffState,
+ });
}
public override calculateAnchorPosition(keyShapeStyle) {
@@ -255,32 +191,20 @@ export class TriangleNode extends BaseNode {
const anchorPositionMap = {};
if (direction === 'down') {
anchorPositionMap['bottom'] = [0, halfHeight];
- anchorPositionMap['right'] = anchorPositionMap['default'] = [
- halfLength,
- -halfHeight,
- ];
+ anchorPositionMap['right'] = anchorPositionMap['default'] = [halfLength, -halfHeight];
anchorPositionMap['left'] = [-halfLength, -halfHeight];
} else if (direction === 'left') {
anchorPositionMap['top'] = [halfHeight, -halfLength];
anchorPositionMap['bottom'] = [halfHeight, halfLength];
- anchorPositionMap['left'] = anchorPositionMap['default'] = [
- -halfHeight,
- 0,
- ];
+ anchorPositionMap['left'] = anchorPositionMap['default'] = [-halfHeight, 0];
} else if (direction === 'right') {
anchorPositionMap['top'] = [-halfHeight, -halfLength];
anchorPositionMap['bottom'] = [-halfHeight, halfLength];
- anchorPositionMap['right'] = anchorPositionMap['default'] = [
- halfHeight,
- 0,
- ];
+ anchorPositionMap['right'] = anchorPositionMap['default'] = [halfHeight, 0];
} else {
//up
anchorPositionMap['left'] = [-halfLength, halfHeight];
- anchorPositionMap['top'] = anchorPositionMap['default'] = [
- 0,
- -halfHeight,
- ];
+ anchorPositionMap['top'] = anchorPositionMap['default'] = [0, -halfHeight];
anchorPositionMap['right'] = [halfLength, halfHeight];
}
return anchorPositionMap;
diff --git a/packages/g6/src/stdlib/plugin/edgeBundling/index.ts b/packages/g6/src/stdlib/plugin/edgeBundling/index.ts
index 825fabbb9e8..c48a36e8609 100644
--- a/packages/g6/src/stdlib/plugin/edgeBundling/index.ts
+++ b/packages/g6/src/stdlib/plugin/edgeBundling/index.ts
@@ -1,4 +1,4 @@
-import { IGraph, GraphData, NodeModel } from 'types';
+import { GraphData, IGraph, NodeModel } from 'types';
import { EdgeModel, IEdge } from 'types/edge';
import { Point } from '../../../types/common';
@@ -51,6 +51,12 @@ interface VectorPosition {
length: number;
}
+/**
+ *
+ * @param pointA
+ * @param pointB
+ * @param eps
+ */
function getEucliDis(pointA: Point, pointB: Point, eps?: number): number {
const vx = pointA.x - pointB.x;
const vy = pointA.y - pointB.y;
@@ -60,15 +66,23 @@ function getEucliDis(pointA: Point, pointB: Point, eps?: number): number {
return eps;
}
+/**
+ *
+ * @param ei
+ * @param ej
+ */
function getDotProduct(ei: Point, ej: Point): number {
return ei.x * ej.x + ei.y * ej.y;
}
+/**
+ *
+ * @param p
+ * @param e
+ */
function projectPointToEdge(p: Point, e: VectorPosition): Point {
- const k =
- (e.source.data.y - e.target.data.y) / (e.source.data.x - e.target.data.x);
- const x =
- (k * k * e.source.data.x + k * (p.y - e.source.data.y) + p.x) / (k * k + 1);
+ const k = (e.source.data.y - e.target.data.y) / (e.source.data.x - e.target.data.x);
+ const x = (k * k * e.source.data.x + k * (p.y - e.source.data.y) + p.x) / (k * k + 1);
const y = k * (x - e.source.data.x) + e.source.data.y;
return { x, y };
}
@@ -131,10 +145,7 @@ export class EdgeBundling extends Base {
nodeIdMap[node.id] = node;
});
- if (error)
- throw new Error(
- 'please layout the graph or assign x and y for nodes first',
- );
+ if (error) throw new Error('please layout the graph or assign x and y for nodes first');
self.nodeIdMap = nodeIdMap;
// subdivide each edges
@@ -161,12 +172,7 @@ export class EdgeBundling extends Base {
const source = nodeIdMap[e.source as string];
const target = nodeIdMap[e.target as string];
- forces[k] = self.getEdgeForces(
- { source, target },
- k,
- divisions,
- lambda,
- );
+ forces[k] = self.getEdgeForces({ source, target }, k, divisions, lambda);
for (let p = 0; p < divisions + 1; p++) {
edgePoints[k][p].x += forces[k][p].x;
@@ -189,9 +195,7 @@ export class EdgeBundling extends Base {
e.data.type = 'polyline-edge';
if (typeof e.data.keyShape === 'object') {
- (e.data.keyShape as Record).controlPoints = edgePoints[
- i
- ].slice(1, edgePoints[i].length - 1);
+ (e.data.keyShape as Record).controlPoints = edgePoints[i].slice(1, edgePoints[i].length - 1);
} else {
e.data.keyShape = {
controlPoints: edgePoints[i].slice(1, edgePoints[i].length - 1),
@@ -252,10 +256,7 @@ export class EdgeBundling extends Base {
if (!edgePoints[i]?.length) {
// it is a straight line
- edgeLength = getEucliDis(
- { x: source.data.x!, y: source.data.y! },
- { x: target.data.x!, y: target.data.y! },
- );
+ edgeLength = getEucliDis({ x: source.data.x!, y: source.data.y! }, { x: target.data.x!, y: target.data.y! });
} else {
edgeLength = self.getEdgeLength(edgePoints[i]);
}
@@ -334,10 +335,7 @@ export class EdgeBundling extends Base {
const jSource = nodeIdMap[ej.source as string];
const jTarget = nodeIdMap[ej.target as string];
- const score = self.getBundleScore(
- { source: iSource, target: iTarget },
- { source: jSource, target: jTarget },
- );
+ const score = self.getBundleScore({ source: iSource, target: iTarget }, { source: jSource, target: jTarget });
if (score >= bundleThreshold) {
edgeBundles[i].push(j);
@@ -393,19 +391,13 @@ export class EdgeBundling extends Base {
}
protected getAngleScore(ei: VectorPosition, ej: VectorPosition): number {
- const dotProduct = getDotProduct(
- { x: ei.vx, y: ei.vy },
- { x: ej.vx, y: ej.vy },
- );
+ const dotProduct = getDotProduct({ x: ei.vx, y: ei.vy }, { x: ej.vx, y: ej.vy });
return dotProduct / (ei.length * ej.length);
}
protected getScaleScore(ei: VectorPosition, ej: VectorPosition): number {
const aLength = (ei.length + ej.length) / 2;
- const score =
- 2 /
- (aLength / Math.min(ei.length, ej.length) +
- Math.max(ei.length, ej.length) / aLength);
+ const score = 2 / (aLength / Math.min(ei.length, ej.length) + Math.max(ei.length, ej.length) / aLength);
return score;
}
@@ -448,18 +440,12 @@ export class EdgeBundling extends Base {
return Math.max(0, 1 - (2 * getEucliDis(pMid, iMid)) / getEucliDis(ps, pt));
}
- protected getEdgeForces(
- e: any,
- eidx: number,
- divisions: number,
- lambda: number,
- ): Point[] {
+ protected getEdgeForces(e: any, eidx: number, divisions: number, lambda: number): Point[] {
const self = this;
const edgePoints = self.getOptionByKey('edgePoints');
const K = self.getOptionByKey('K');
- const kp =
- K / (getEucliDis(e.source.data, e.target.data) * (divisions + 1));
+ const kp = K / (getEucliDis(e.source.data, e.target.data) * (divisions + 1));
const edgePointForces = [{ x: 0, y: 0 }];
for (let i = 1; i < divisions; i++) {
@@ -509,10 +495,7 @@ export class EdgeBundling extends Base {
};
if (Math.abs(force.x) > eps || Math.abs(force.y) > eps) {
- const length = getEucliDis(
- edgePoints[eb][pidx],
- edgePoints[eidx][pidx],
- );
+ const length = getEucliDis(edgePoints[eb][pidx], edgePoints[eidx][pidx]);
const diff = 1 / length;
resForce.x += force.x * diff;
diff --git a/packages/g6/src/stdlib/plugin/edgeFilterLens/index.ts b/packages/g6/src/stdlib/plugin/edgeFilterLens/index.ts
index ced16d9eb37..aec424abeae 100644
--- a/packages/g6/src/stdlib/plugin/edgeFilterLens/index.ts
+++ b/packages/g6/src/stdlib/plugin/edgeFilterLens/index.ts
@@ -1,10 +1,10 @@
import { DisplayObject } from '@antv/g';
-import { Plugin as Base, IPluginBaseConfig } from '../../../types/plugin';
import { IGraph } from '../../../types';
import { IG6GraphEvent } from '../../../types/event';
import { ShapeStyle } from '../../../types/item';
-import { distance } from '../../../util/point';
+import { Plugin as Base, IPluginBaseConfig } from '../../../types/plugin';
import { cloneJSON } from '../../../util/data';
+import { distance } from '../../../util/point';
const DELTA = 0.01;
interface EdgeFilterLensConfig extends IPluginBaseConfig {
@@ -138,9 +138,7 @@ export class EdgeFilterLens extends Base {
}
protected moveDelegate(e) {
- if (
- this.isInLensDelegate(this.delegate, { x: e.canvas.x, y: e.canvas.y })
- ) {
+ if (this.isInLensDelegate(this.delegate, { x: e.canvas.x, y: e.canvas.y })) {
const center = {
x: e.canvas.x - this.delegateCenterDiff.x,
y: e.canvas.y - this.delegateCenterDiff.y,
@@ -171,12 +169,8 @@ export class EdgeFilterLens extends Base {
const { graph, options } = this;
const graphCanvasEl = graph.canvas.context.config.canvas;
const graphHeight = graphCanvasEl?.height || 500;
- const maxR = options.maxR
- ? Math.min(options.maxR, graphHeight)
- : graphHeight;
- const minR = options.minR
- ? Math.max(options.minR, graphHeight * DELTA)
- : graphHeight * DELTA;
+ const maxR = options.maxR ? Math.min(options.maxR, graphHeight) : graphHeight;
+ const minR = options.minR ? Math.max(options.minR, graphHeight * DELTA) : graphHeight * DELTA;
const scale = 1 + (e.originalEvent as any).deltaY * -1 * DELTA;
let r = options.r * scale;
@@ -190,16 +184,10 @@ export class EdgeFilterLens extends Base {
/**
* Response function for mousemove, click, or drag to filter out the edges
* @param e mouse event
+ * @param mousePos
*/
protected filter(e: IG6GraphEvent, mousePos?) {
- const {
- graph,
- options,
- showNodeLabel,
- showEdgeLabel,
- cachedTransientNodes,
- cachedTransientEdges,
- } = this;
+ const { graph, options, showNodeLabel, showEdgeLabel, cachedTransientNodes, cachedTransientEdges } = this;
const r = options.r;
const showType = options.showType;
const shouldShow = options.shouldShow;
@@ -222,16 +210,10 @@ export class EdgeFilterLens extends Base {
const targetId = edge.target;
if (shouldShow(edge)) {
if (showType === 'only-source' || showType === 'one') {
- if (hitNodesMap.get(sourceId) && !hitNodesMap.get(targetId))
- hitEdges.push(edge);
+ if (hitNodesMap.get(sourceId) && !hitNodesMap.get(targetId)) hitEdges.push(edge);
} else if (showType === 'only-target' || showType === 'one') {
- if (hitNodesMap.get(targetId) && !hitNodesMap.get(sourceId))
- hitEdges.push(edge);
- } else if (
- showType === 'both' &&
- hitNodesMap.get(sourceId) &&
- hitNodesMap.get(targetId)
- ) {
+ if (hitNodesMap.get(targetId) && !hitNodesMap.get(sourceId)) hitEdges.push(edge);
+ } else if (showType === 'both' && hitNodesMap.get(sourceId) && hitNodesMap.get(targetId)) {
hitEdges.push(edge);
}
}
@@ -247,9 +229,7 @@ export class EdgeFilterLens extends Base {
cachedTransientNodes.delete(node.id);
} else {
graph.drawTransient('node', node.id, {
- shapeIds: showNodeLabel
- ? ['labelShape', 'labelBackgroundShape', 'keyShape']
- : ['keyShape'],
+ shapeIds: showNodeLabel ? ['labelShape', 'labelBackgroundShape', 'keyShape'] : ['keyShape'],
});
}
});
@@ -319,8 +299,8 @@ export class EdgeFilterLens extends Base {
/**
* Update the delegate shape of the lens
- * @param {Point} mCenter the center of the shape
- * @param {number} r the radius of the shape
+ * @param mCenter the center of the shape
+ * @param r the radius of the shape
*/
private updateDelegate(mCenter, r) {
const { graph, options, delegate } = this;
@@ -357,12 +337,7 @@ export class EdgeFilterLens extends Base {
* Clear the filtering
*/
public clear() {
- const {
- graph,
- delegate: lensDelegate,
- cachedTransientNodes,
- cachedTransientEdges,
- } = this;
+ const { graph, delegate: lensDelegate, cachedTransientNodes, cachedTransientEdges } = this;
if (lensDelegate && !lensDelegate.destroyed) {
graph.drawTransient('circle', 'lens-shape', { action: 'remove' });
diff --git a/packages/g6/src/stdlib/plugin/fisheye/index.ts b/packages/g6/src/stdlib/plugin/fisheye/index.ts
index de984845640..16910705d04 100644
--- a/packages/g6/src/stdlib/plugin/fisheye/index.ts
+++ b/packages/g6/src/stdlib/plugin/fisheye/index.ts
@@ -245,10 +245,7 @@ export class Fisheye extends Base {
ratio = 1 / (1 - DELTA);
}
const graphHeight = graph.canvas.context.config.canvas.height;
- if (
- (r > (maxR || graphHeight) && ratio > 1) ||
- (r < (minR || graphHeight * 0.05) && ratio < 1)
- ) {
+ if ((r > (maxR || graphHeight) && ratio > 1) || (r < (minR || graphHeight * 0.05) && ratio < 1)) {
ratio = 1;
}
r *= ratio;
@@ -263,11 +260,10 @@ export class Fisheye extends Base {
* Scale the range by dragging
* @param e mouse event
*/
- protected scaleRByDrag = throttle(
- this.scaleRByDragMethod.bind(this),
- this.options.throttle,
- { leading: true, trailing: true },
- );
+ protected scaleRByDrag = throttle(this.scaleRByDragMethod.bind(this), this.options.throttle, {
+ leading: true,
+ trailing: true,
+ });
protected scaleRByDragMethod(e: IG6GraphEvent) {
if (!e) return;
const { dragPrePos, graph, options } = this;
@@ -280,14 +276,8 @@ export class Fisheye extends Base {
ratio = 1 / (1 - DELTA);
}
const graphCanvasEl = graph.canvas.context.config.canvas;
- const [
- graphWidth = graphCanvasEl?.width || 500,
- graphHeight = graphCanvasEl?.height || 500,
- ] = graph.getSize();
- if (
- (r > (maxR || graphHeight) && ratio > 1) ||
- (r < (minR || graphHeight * 0.05) && ratio < 1)
- ) {
+ const [graphWidth = graphCanvasEl?.width || 500, graphHeight = graphCanvasEl?.height || 500] = graph.getSize();
+ if ((r > (maxR || graphHeight) && ratio > 1) || (r < (minR || graphHeight * 0.05) && ratio < 1)) {
ratio = 1;
}
r *= ratio;
@@ -300,7 +290,7 @@ export class Fisheye extends Base {
/**
* Scale the magnifying factor by wheel
- * @param e mouse wheel event
+ * @param evt mouse wheel event
*/
protected scaleDByWheel(evt: IG6GraphEvent) {
if (!evt && !evt.originalEvent) return;
@@ -332,11 +322,10 @@ export class Fisheye extends Base {
* Scale the magnifying factor by dragging
* @param e mouse event
*/
- protected scaleDByDrag = throttle(
- this.scaleDByDragMethod.bind(this),
- this.options.throttle,
- { leading: true, trailing: true },
- );
+ protected scaleDByDrag = throttle(this.scaleDByDragMethod.bind(this), this.options.throttle, {
+ leading: true,
+ trailing: true,
+ });
protected scaleDByDragMethod(e: IG6GraphEvent) {
const { d, maxD, minD, r } = this.options;
const delta = e.canvas.x - this.dragPrePos.x > 0 ? 0.1 : -0.1;
@@ -352,18 +341,12 @@ export class Fisheye extends Base {
/**
* Response function for mousemove, click, or drag to magnify
* @param e mouse event
+ * @param mousePos
*/
protected magnify(e: IG6GraphEvent, mousePos?) {
this.restoreCache();
- const {
- r2,
- graph,
- cachedOriginPositions,
- cachedTransientTexts,
- molecularParam,
- delegateCenterDiff,
- options,
- } = this;
+ const { r2, graph, cachedOriginPositions, cachedTransientTexts, molecularParam, delegateCenterDiff, options } =
+ this;
const positions = Object.keys(cachedOriginPositions).map((id) => ({
id,
data: {
@@ -375,9 +358,7 @@ export class Fisheye extends Base {
const nodes = graph.getAllNodesData();
const nodeLength = nodes.length;
const point = graph.getCanvasByClient(e.client);
- let mCenter = mousePos
- ? { x: mousePos.x, y: mousePos.y }
- : { x: point.x, y: point.y };
+ let mCenter = mousePos ? { x: mousePos.x, y: mousePos.y } : { x: point.x, y: point.y };
if (this.dragging && (trigger === 'mousemove' || trigger === 'click')) {
mCenter = this.cacheCenter;
}
@@ -391,8 +372,7 @@ export class Fisheye extends Base {
const { x, y } = cachedOriginPositions[model.id]; // calculate based on the origin positions
if (isNaN(x) || isNaN(y)) continue;
// the square of the distance between the node and the magnified center
- const dist2 =
- (x - mCenter.x) * (x - mCenter.x) + (y - mCenter.y) * (y - mCenter.y);
+ const dist2 = (x - mCenter.x) * (x - mCenter.x) + (y - mCenter.y) * (y - mCenter.y);
if (!isNaN(dist2) && dist2 < r2 && dist2 !== 0) {
const dist = Math.sqrt(dist2);
// // (r * (d + 1) * (dist / r)) / (d * (dist / r) + 1);
@@ -405,8 +385,7 @@ export class Fisheye extends Base {
id: model.id,
data: { x: magnifiedX, y: magnifiedY },
};
- const textContent =
- model.data.label || (model.data.labelShape as any)?.text;
+ const textContent = model.data.label || (model.data.labelShape as any)?.text;
if (showLabel && 2 * dist < r) {
const transientTextID = `node-text-${model.id}`;
const cachedTransientText = cachedTransientTexts[transientTextID];
@@ -506,6 +485,7 @@ export class Fisheye extends Base {
* Update the delegate shape of the lens
* @param {Point} mCenter the center of the shape
* @param {number} r the radius of the shape
+ * @param e
*/
private updateDelegate(mCenter, r, e) {
const { graph, dPercentText } = this;
@@ -575,12 +555,7 @@ export class Fisheye extends Base {
* Clear the fisheye lens
*/
public clear() {
- const {
- graph,
- delegate: lensDelegate,
- cachedOriginPositions,
- dPercentText,
- } = this;
+ const { graph, delegate: lensDelegate, cachedOriginPositions, dPercentText } = this;
this.restoreCache();
graph.updateNodePosition(
Object.keys(cachedOriginPositions).map((id) => ({
diff --git a/packages/g6/src/stdlib/plugin/grid/index.ts b/packages/g6/src/stdlib/plugin/grid/index.ts
index e057255adf2..68ea8d394b7 100644
--- a/packages/g6/src/stdlib/plugin/grid/index.ts
+++ b/packages/g6/src/stdlib/plugin/grid/index.ts
@@ -1,19 +1,17 @@
// TODO: update type define.
import { Canvas } from '@antv/g';
import { uniqueId } from '@antv/util';
-import { createDOM, modifyCSS } from '../../../util/dom';
import { IGraph } from '../../../types';
import { Plugin as Base, IPluginBaseConfig } from '../../../types/plugin';
+import { createDOM, modifyCSS } from '../../../util/dom';
const GRID_PNG =
'url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAiIGhlaWdodD0iNDAiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PGRlZnM+PHBhdHRlcm4gaWQ9ImdyaWQiIHdpZHRoPSI0MCIgaGVpZ2h0PSI0MCIgcGF0dGVyblVuaXRzPSJ1c2VyU3BhY2VPblVzZSI+PHBhdGggZD0iTSAwIDEwIEwgNDAgMTAgTSAxMCAwIEwgMTAgNDAgTSAwIDIwIEwgNDAgMjAgTSAyMCAwIEwgMjAgNDAgTSAwIDMwIEwgNDAgMzAgTSAzMCAwIEwgMzAgNDAiIGZpbGw9Im5vbmUiIHN0cm9rZT0iI2UwZTBlMCIgb3BhY2l0eT0iMC4yIiBzdHJva2Utd2lkdGg9IjEiLz48cGF0aCBkPSJNIDQwIDAgTCAwIDAgMCA0MCIgZmlsbD0ibm9uZSIgc3Ryb2tlPSIjZTBlMGUwIiBzdHJva2Utd2lkdGg9IjEiLz48L3BhdHRlcm4+PC9kZWZzPjxyZWN0IHdpZHRoPSIxMDAlIiBoZWlnaHQ9IjEwMCUiIGZpbGw9InVybCgjZ3JpZCkiLz48L3N2Zz4=)';
/**
* This is an interface named `GridConfig`, which extends the `IPluginBaseConfig` interface. It contains the following properties:
-
-- `img`: A string representing the background image of the grid.
-- `follow`: A boolean indicating whether the grid follows the view movement.
-
+ * - `img`: A string representing the background image of the grid.
+ * - `follow`: A boolean indicating whether the grid follows the view movement.
*/
export interface GridConfig extends IPluginBaseConfig {
img?: string;
@@ -101,9 +99,9 @@ export class Grid extends Base {
if (!matrix) matrix = [1, 0, 0, 0, 1, 0, 0, 0, 1];
const isFollow = this.options.follow;
- const transform = `matrix(${matrix[0]}, ${matrix[1]}, ${matrix[3]}, ${
- matrix[4]
- }, ${isFollow ? matrix[6] : '0'}, ${isFollow ? matrix[7] : '0'})`;
+ const transform = `matrix(${matrix[0]}, ${matrix[1]}, ${matrix[3]}, ${matrix[4]}, ${isFollow ? matrix[6] : '0'}, ${
+ isFollow ? matrix[7] : '0'
+ })`;
modifyCSS(gridContainer, {
transform,
diff --git a/packages/g6/src/stdlib/plugin/history/combo-command.ts b/packages/g6/src/stdlib/plugin/history/combo-command.ts
index 5cca7a82c59..33b49e9dde4 100644
--- a/packages/g6/src/stdlib/plugin/history/combo-command.ts
+++ b/packages/g6/src/stdlib/plugin/history/combo-command.ts
@@ -12,17 +12,13 @@ export class ComboCommand implements Command {
undo(graph: IGraph) {
graph.executeWithNoStack(() => {
- this.action === 'expandCombo'
- ? graph.collapseCombo(this.ids)
- : graph.expandCombo(this.ids);
+ this.action === 'expandCombo' ? graph.collapseCombo(this.ids) : graph.expandCombo(this.ids);
});
}
redo(graph: IGraph) {
graph.executeWithNoStack(() => {
- this.action === 'collapseCombo'
- ? graph.collapseCombo(this.ids)
- : graph.expandCombo(this.ids);
+ this.action === 'collapseCombo' ? graph.collapseCombo(this.ids) : graph.expandCombo(this.ids);
});
}
}
diff --git a/packages/g6/src/stdlib/plugin/history/command.ts b/packages/g6/src/stdlib/plugin/history/command.ts
index c0ea7b8b03f..2fbe6bd54f4 100644
--- a/packages/g6/src/stdlib/plugin/history/command.ts
+++ b/packages/g6/src/stdlib/plugin/history/command.ts
@@ -1,11 +1,11 @@
import { groupBy } from '@antv/util';
import { ID, IGraph } from '../../../types';
import type { ITEM_TYPE } from '../../../types/item';
+import { ComboCommand } from './combo-command';
+import { ItemDataCommand } from './item-data-command';
import { LayerUpdatedCommand } from './layer-updated-command';
import { StateUpdatedCommand } from './state-updated-command';
import { VisibilityUpdatedCommand } from './visibility-updated-command';
-import { ItemDataCommand } from './item-data-command';
-import { ComboCommand } from './combo-command';
export interface Command {
redo: (graph: IGraph) => void;
@@ -15,25 +15,13 @@ interface CreateProps {
type: ITEM_TYPE;
ids: ID[];
changes: any;
- action?:
- | 'updatePosition'
- | 'updateState'
- | 'updateVisibility'
- | 'front'
- | 'back'
- | 'expandCombo'
- | 'collapseCombo';
+ action?: 'updatePosition' | 'updateState' | 'updateVisibility' | 'front' | 'back' | 'expandCombo' | 'collapseCombo';
upsertAncestors?: boolean;
disableAnimate?: boolean;
}
export default class CommandFactory {
- static create({
- type: itemType,
- action,
- changes,
- ...rest
- }: CreateProps): Command[] {
+ static create({ type: itemType, action, changes, ...rest }: CreateProps): Command[] {
const commands = [];
const groupedByType = groupBy(changes, 'type');
@@ -62,10 +50,7 @@ export default class CommandFactory {
const actionCommandMap = {
updateState: new StateUpdatedCommand(changes),
- updateVisibility: new VisibilityUpdatedCommand(
- changes,
- rest.disableAnimate,
- ),
+ updateVisibility: new VisibilityUpdatedCommand(changes, rest.disableAnimate),
front: new LayerUpdatedCommand('front', rest.ids),
back: new LayerUpdatedCommand('back', rest.ids),
expandCombo: new ComboCommand('expandCombo', rest.ids),
diff --git a/packages/g6/src/stdlib/plugin/history/index.ts b/packages/g6/src/stdlib/plugin/history/index.ts
index f45b578fbad..21825dd6666 100644
--- a/packages/g6/src/stdlib/plugin/history/index.ts
+++ b/packages/g6/src/stdlib/plugin/history/index.ts
@@ -6,23 +6,23 @@ import CommandFactory, { Command } from './command';
/**
* The `HistoryConfig` interface contains the following properties:
-
-- `enableStack`: An optional boolean value that indicates whether to enable the stack.
-- `stackCfg`: A required object of type `StackCfg` representing the stack configuration.
-
-The `StackCfg` type is defined as an object with the following properties:
-
-- `stackSize`: An optional number representing the size of the stack.
-- `stackActive`: An optional boolean value indicating whether the stack is active. If active, operations can be pushed onto the stack; otherwise, they cannot.
-- `excludes`: An optional array of strings representing APIs that should be excluded from being put on the stack, even if their operation type is not ignored.
-- `includes`: An optional array of strings representing APIs that should be included in being put on the stack.
-- `ignoreAdd`: An optional boolean value indicating whether to ignore add operations.
-- `ignoreRemove`: An optional boolean value indicating whether to ignore remove operations.
-- `ignoreUpdate`: An optional boolean value indicating whether to ignore update operations.
-- `ignoreStateChange`: An optional boolean value indicating whether to ignore state change operations.
-- `ignoreLayerChange`: An optional boolean value indicating whether to ignore layer change operations.
-- `ignoreDisplayChange`: An optional boolean value indicating whether to ignore display change operations.
-
+ *
+ * - `enableStack`: An optional boolean value that indicates whether to enable the stack.
+ * - `stackCfg`: A required object of type `StackCfg` representing the stack configuration.
+ *
+ * The `StackCfg` type is defined as an object with the following properties:
+ *
+ * - `stackSize`: An optional number representing the size of the stack.
+ * - `stackActive`: An optional boolean value indicating whether the stack is active. If active, operations can be pushed onto the stack; otherwise, they cannot.
+ * - `excludes`: An optional array of strings representing APIs that should be excluded from being put on the stack, even if their operation type is not ignored.
+ * - `includes`: An optional array of strings representing APIs that should be included in being put on the stack.
+ * - `ignoreAdd`: An optional boolean value indicating whether to ignore add operations.
+ * - `ignoreRemove`: An optional boolean value indicating whether to ignore remove operations.
+ * - `ignoreUpdate`: An optional boolean value indicating whether to ignore update operations.
+ * - `ignoreStateChange`: An optional boolean value indicating whether to ignore state change operations.
+ * - `ignoreLayerChange`: An optional boolean value indicating whether to ignore layer change operations.
+ * - `ignoreDisplayChange`: An optional boolean value indicating whether to ignore display change operations.
+ *
*/
export interface HistoryConfig extends IPluginBaseConfig {
enableStack?: boolean;
@@ -172,11 +172,7 @@ export class History extends Base {
return this.enableStack;
}
- public push(
- cmd: Command[],
- stackType: StackType = STACK_TYPE.undo,
- isNew = true,
- ) {
+ public push(cmd: Command[], stackType: StackType = STACK_TYPE.undo, isNew = true) {
if (this.stackActive) {
if (stackType === STACK_TYPE.undo) {
if (isNew) {
@@ -191,9 +187,7 @@ export class History extends Base {
}
this.graph.emit('history:change', cmd, stackType, isNew);
} else {
- console.error(
- 'Stacking operations are currently paused. Unable to push to the stack.',
- );
+ console.error('Stacking operations are currently paused. Unable to push to the stack.');
}
}
@@ -266,9 +260,7 @@ export class History extends Base {
*/
public startHistoryBatch() {
if (this.isBatching) {
- throw new Error(
- 'Ensure that historyBatch processing is stopped before starting.',
- );
+ throw new Error('Ensure that historyBatch processing is stopped before starting.');
}
this.initBatchCommands();
this.isBatching = true;
@@ -281,9 +273,7 @@ export class History extends Base {
*/
public stopHistoryBatch() {
if (!this.isBatching) {
- throw new Error(
- 'Ensure that historyBatch processing is started before stopping.',
- );
+ throw new Error('Ensure that historyBatch processing is started before stopping.');
}
this.push(this.batchCommands);
this.isBatching = false;
@@ -314,10 +304,7 @@ export class History extends Base {
const { apiName, changes } = props;
if (changes && changes.length === 0) return;
if (this.shouldPushToStack(apiName)) {
- this.batchCommands = [
- ...this.batchCommands,
- ...CommandFactory.create(props),
- ];
+ this.batchCommands = [...this.batchCommands, ...CommandFactory.create(props)];
if (this.isBatching) {
return;
}
@@ -327,8 +314,7 @@ export class History extends Base {
/**
* Determine if a given operation should be pushed onto the history stack based on various configurations.
- * @param {string} apiName name of the API operation.
- * @param {boolean} stack Optional. whether push this operation into graph's stack.
+ * @param apiName name of the API operation.
*/
private shouldPushToStack(apiName: string): boolean {
const { includes = [], excludes = [] } = this.cfg;
diff --git a/packages/g6/src/stdlib/plugin/history/item-data-command.ts b/packages/g6/src/stdlib/plugin/history/item-data-command.ts
index c5e01de7faf..bd2c7ff011c 100644
--- a/packages/g6/src/stdlib/plugin/history/item-data-command.ts
+++ b/packages/g6/src/stdlib/plugin/history/item-data-command.ts
@@ -1,7 +1,7 @@
-import type { ITEM_TYPE } from '../../../types/item';
import type { IGraph } from '../../../types';
-import type { GroupedChanges } from '../../../util/event';
import { STACK_TYPE, type StackType } from '../../../types/history';
+import type { ITEM_TYPE } from '../../../types/item';
+import type { GroupedChanges } from '../../../util/event';
import { Command } from './command';
export class ItemDataCommand implements Command {
@@ -38,11 +38,7 @@ export class ItemDataCommand implements Command {
});
}
- private updateChangedData(
- graph: IGraph,
- operationType: StackType,
- onlyMove = false,
- ) {
+ private updateChangedData(graph: IGraph, operationType: StackType, onlyMove = false) {
const modelMap = new Map();
if (this.type === 'combo' && !onlyMove) {
this.changes.forEach((data) => {
@@ -57,8 +53,7 @@ export class ItemDataCommand implements Command {
});
} else {
this.changes.forEach((data) => {
- const value =
- operationType === STACK_TYPE.undo ? data.oldValue : data.newValue;
+ const value = operationType === STACK_TYPE.undo ? data.oldValue : data.newValue;
if (
(typeof value === 'number' && isNaN(value)) ||
(['x', 'y'].includes(data.propertyName) && value === undefined)
@@ -93,11 +88,7 @@ export class ItemDataCommand implements Command {
this.action === 'remove' && this.addChangedData(graph);
this.action === 'update' && this.updateChangedData(graph, STACK_TYPE.undo);
this.action === 'updatePosition' &&
- this.updateChangedData(
- graph,
- STACK_TYPE.undo,
- this.action === 'updatePosition',
- );
+ this.updateChangedData(graph, STACK_TYPE.undo, this.action === 'updatePosition');
}
redo(graph: IGraph) {
@@ -105,10 +96,6 @@ export class ItemDataCommand implements Command {
this.action === 'add' && this.addChangedData(graph);
this.action === 'update' && this.updateChangedData(graph, STACK_TYPE.redo);
this.action === 'updatePosition' &&
- this.updateChangedData(
- graph,
- STACK_TYPE.redo,
- this.action === 'updatePosition',
- );
+ this.updateChangedData(graph, STACK_TYPE.redo, this.action === 'updatePosition');
}
}
diff --git a/packages/g6/src/stdlib/plugin/history/layer-updated-command.ts b/packages/g6/src/stdlib/plugin/history/layer-updated-command.ts
index 1a0c4e8fbaf..9e1cec93a50 100644
--- a/packages/g6/src/stdlib/plugin/history/layer-updated-command.ts
+++ b/packages/g6/src/stdlib/plugin/history/layer-updated-command.ts
@@ -12,17 +12,13 @@ export class LayerUpdatedCommand implements Command {
undo(graph: IGraph) {
graph.executeWithNoStack(() => {
- this.action === 'front'
- ? graph.backItem(this.ids)
- : graph.frontItem(this.ids);
+ this.action === 'front' ? graph.backItem(this.ids) : graph.frontItem(this.ids);
});
}
redo(graph: IGraph) {
graph.executeWithNoStack(() => {
- this.action === 'front'
- ? graph.frontItem(this.ids)
- : graph.backItem(this.ids);
+ this.action === 'front' ? graph.frontItem(this.ids) : graph.backItem(this.ids);
});
}
}
diff --git a/packages/g6/src/stdlib/plugin/hull/bubbleset.ts b/packages/g6/src/stdlib/plugin/hull/bubbleset.ts
index 87c619c682b..52e6898918d 100644
--- a/packages/g6/src/stdlib/plugin/hull/bubbleset.ts
+++ b/packages/g6/src/stdlib/plugin/hull/bubbleset.ts
@@ -2,17 +2,17 @@ import { AABB } from '@antv/g';
import { ComboModel, IGraph, NodeModel } from '../../../types';
import { Bounds, Point } from '../../../types/common';
import { isPointInPolygon } from '../../../util/shape';
+import { BubblesetCfg } from './types';
import {
LineStructure,
- pointLineSquareDist,
- squareDist,
fractionToLine,
- isPointsOverlap,
getPointsCenter,
+ isPointsOverlap,
itemIntersectByLine,
+ pointLineSquareDist,
pointRectSquareDist,
+ squareDist,
} from './util';
-import { BubblesetCfg } from './types';
const defaultOps = {
/** number of times to run the algorithm to refine the path finding in difficult areas */
@@ -41,6 +41,7 @@ const defaultOps = {
/**
* Marching square algorithm for tracking the contour of a pixel group
* https://www.emanueleferonato.com/2013/03/01/using-marching-squares-algorithm-to-trace-the-contour-of-an-image/
+ * @param contour
* @param potentialArea
* @param threshold
*/
@@ -152,18 +153,14 @@ function MarchingSquares(contour, potentialArea, threshold) {
/**
* Space partition & assign value to each cell
- * @param points
+ * @param width
+ * @param height
+ * @param pixelGroupSize
*/
-const initGridCells = (
- width: number,
- height: number,
- pixelGroupSize: number,
-) => {
+const initGridCells = (width: number, height: number, pixelGroupSize: number) => {
const scaleWidth = Math.ceil(width / pixelGroupSize);
const scaleHeight = Math.ceil(height / pixelGroupSize);
- const gridCells = new Float32Array(
- Math.max(0, scaleWidth * scaleHeight),
- ).fill(0);
+ const gridCells = new Float32Array(Math.max(0, scaleWidth * scaleHeight)).fill(0);
return {
cells: gridCells,
width: scaleWidth,
@@ -174,8 +171,10 @@ const initGridCells = (
/**
* Find the optimal already visited member to item;
Optimal: minimize cost(j) = distance(i,j) ∗ countObstacles(i,j)
- * @param item
+ * @param graph
+ * @param model
* @param visited
+ * @param nonMembers
*/
const pickBestNeighbor = (
graph: IGraph,
@@ -193,12 +192,7 @@ const pickBestNeighbor = (
y: neighborModel.data.y,
} as Point;
const dist = squareDist(itemP, neighborItemP);
- const directLine = new LineStructure(
- itemP.x,
- itemP.y,
- neighborItemP.x,
- neighborItemP.y,
- );
+ const directLine = new LineStructure(itemP.x, itemP.y, neighborItemP.x, neighborItemP.y);
const numberObstacles = nonMembers.reduce((count, _item) => {
if (fractionToLine(graph, _item.id, directLine) > 0) {
return count + 1;
@@ -215,6 +209,7 @@ const pickBestNeighbor = (
/**
* 返回和线相交的item中,离边的起点最近的item
+ * @param graph
* @param items
* @param line
*/
@@ -239,6 +234,11 @@ const getIntersectItem = (
/**
* Modify the directLine and Route virtual edges around obstacles
+ * @param graph
+ * @param directLine
+ * @param nonMembers
+ * @param maxRoutingIterations
+ * @param morphBuffer
*/
const computeRoute = (
graph: IGraph,
@@ -258,20 +258,13 @@ const computeRoute = (
let flag = false;
lines.forEach((line) => {
if (flag) return;
- if (
- isPointsOverlap(point, { x: line.x1, y: line.y1 }) ||
- isPointsOverlap(point, { x: line.x2, y: line.y2 })
- ) {
+ if (isPointsOverlap(point, { x: line.x1, y: line.y1 }) || isPointsOverlap(point, { x: line.x2, y: line.y2 })) {
flag = true;
}
});
return flag;
};
- const isPointInNonMembers = (
- graph: IGraph,
- point: Point,
- _nonMembers: (NodeModel | ComboModel)[],
- ) => {
+ const isPointInNonMembers = (graph: IGraph, point: Point, _nonMembers: (NodeModel | ComboModel)[]) => {
for (const model of _nonMembers) {
const bbox = graph.getRenderBBox(model.id);
if (!bbox) continue;
@@ -297,65 +290,29 @@ const computeRoute = (
const line = linesToCheck.pop();
const closestItem = getIntersectItem(graph, nonMembers, line);
if (closestItem) {
- const [intersections, countIntersections] = itemIntersectByLine(
- graph,
- closestItem.id,
- line,
- );
+ const [intersections, countIntersections] = itemIntersectByLine(graph, closestItem.id, line);
// if line passes through item
if (countIntersections === 2) {
const testReroute = (isFirst: boolean) => {
let tempMorphBuffer = morphBuffer;
- let virtualNode = rerouteLine(
- closestItem,
- tempMorphBuffer,
- intersections,
- isFirst,
- );
+ let virtualNode = rerouteLine(closestItem, tempMorphBuffer, intersections, isFirst);
// test the virtualNode already exists
- let exist =
- pointExists(virtualNode, linesToCheck) ||
- pointExists(virtualNode, checkedLines);
- let pointInside = isPointInNonMembers(
- graph,
- virtualNode,
- nonMembers,
- );
+ let exist = pointExists(virtualNode, linesToCheck) || pointExists(virtualNode, checkedLines);
+ let pointInside = isPointInNonMembers(graph, virtualNode, nonMembers);
while (!exist && pointInside && tempMorphBuffer >= 1) {
// try a smaller buffer
tempMorphBuffer /= 1.5;
- virtualNode = rerouteLine(
- closestItem,
- tempMorphBuffer,
- intersections,
- isFirst,
- );
- exist =
- pointExists(virtualNode, linesToCheck) ||
- pointExists(virtualNode, checkedLines);
+ virtualNode = rerouteLine(closestItem, tempMorphBuffer, intersections, isFirst);
+ exist = pointExists(virtualNode, linesToCheck) || pointExists(virtualNode, checkedLines);
pointInside = isPointInNonMembers(graph, virtualNode, nonMembers);
}
// 第二次route时不要求pointInside
if (virtualNode && !exist && (!isFirst || !pointInside)) {
// add 2 rerouted lines to check
- linesToCheck.push(
- new LineStructure(
- line.x1,
- line.y1,
- virtualNode.x,
- virtualNode.y,
- ),
- );
- linesToCheck.push(
- new LineStructure(
- virtualNode.x,
- virtualNode.y,
- line.x2,
- line.y2,
- ),
- );
+ linesToCheck.push(new LineStructure(line.x1, line.y1, virtualNode.x, virtualNode.y));
+ linesToCheck.push(new LineStructure(virtualNode.x, virtualNode.y, line.x2, line.y2));
hasIntersection = true;
}
};
@@ -385,6 +342,12 @@ const computeRoute = (
/**
* Connect item with visited members using direct line or virtual edges
+ * @param graph
+ * @param currentModel
+ * @param nonMembers
+ * @param visited
+ * @param maxRoutingIterations
+ * @param morphBuffer
*/
function getRoute(
graph: IGraph,
@@ -394,12 +357,7 @@ function getRoute(
maxRoutingIterations: number,
morphBuffer: number,
) {
- const optimalNeighbor = pickBestNeighbor(
- graph,
- currentModel,
- visited,
- nonMembers,
- );
+ const optimalNeighbor = pickBestNeighbor(graph, currentModel, visited, nonMembers);
if (optimalNeighbor === null) {
return [];
}
@@ -414,12 +372,7 @@ function getRoute(
break;
}
const line2 = checkedLines.pop()!;
- const mergeLine = new LineStructure(
- line1.x1,
- line1.y1,
- line2.x2,
- line2.y2,
- );
+ const mergeLine = new LineStructure(line1.x1, line1.y1, line2.x2, line2.y2);
const closestItem = getIntersectItem(graph, nonMembers, mergeLine);
// merge most recent line and previous line
if (!closestItem) {
@@ -437,22 +390,17 @@ function getRoute(
optimalNeighbor.data.x as number,
optimalNeighbor.data.y as number,
);
- const checkedLines = computeRoute(
- graph,
- directLine,
- nonMembers,
- maxRoutingIterations,
- morphBuffer,
- );
+ const checkedLines = computeRoute(graph, directLine, nonMembers, maxRoutingIterations, morphBuffer);
const finalRoute = mergeLines(checkedLines);
return finalRoute;
}
/**
* Calculate the counter that includes the selected items and excludes the non-selected items
+ * @param graph
* @param members
* @param nonMembers
- * @param options
+ * @param ops
*/
export const genBubbleSet = (
graph: IGraph,
@@ -462,9 +410,7 @@ export const genBubbleSet = (
) => {
// eslint-disable-next-line no-redeclare
const options = Object.assign(defaultOps, ops);
- const centroid = getPointsCenter(
- members.map((model) => ({ x: model.data.x, y: model.data.y } as Point)),
- );
+ const centroid = getPointsCenter(members.map((model) => ({ x: model.data.x, y: model.data.y }) as Point));
// 按照到中心距离远近排序
members = members.sort(
(a, b) =>
@@ -474,14 +420,7 @@ export const genBubbleSet = (
const visited: (NodeModel | ComboModel)[] = [];
const virtualEdges: LineStructure[] = [];
members.forEach((model) => {
- const lines = getRoute(
- graph,
- model,
- nonMembers,
- visited,
- options.maxRoutingIterations,
- options.morphBuffer,
- );
+ const lines = getRoute(graph, model, nonMembers, visited, options.maxRoutingIterations, options.morphBuffer);
lines.forEach((l) => {
virtualEdges.push(l);
});
@@ -492,12 +431,7 @@ export const genBubbleSet = (
// virtualEdges.push(new LineStructure(e.getSource().getModel().x, e.getSource().getModel().y, e.getTarget().getModel().x, e.getTarget().getModel().y));
// });
- const activeRegion = getActiveRegion(
- graph,
- members,
- virtualEdges,
- options.nodeR0,
- );
+ const activeRegion = getActiveRegion(graph, members, virtualEdges, options.nodeR0);
const potentialArea = initGridCells(
activeRegion.max[0] - activeRegion.min[0],
activeRegion.max[1] - activeRegion.min[1],
@@ -507,24 +441,11 @@ export const genBubbleSet = (
// Use march squares to generate contour
let contour = [];
let hull = [];
- for (
- let iterations = 0;
- iterations < options.maxMarchingIterations;
- iterations++
- ) {
- fillPotentialArea(
- graph,
- members,
- nonMembers,
- virtualEdges,
- activeRegion,
- potentialArea,
- options,
- );
+ for (let iterations = 0; iterations < options.maxMarchingIterations; iterations++) {
+ fillPotentialArea(graph, members, nonMembers, virtualEdges, activeRegion, potentialArea, options);
contour = [];
hull = [];
- if (!new MarchingSquares(contour, potentialArea, options.threshold).march())
- continue;
+ if (!new MarchingSquares(contour, potentialArea, options.threshold).march()) continue;
const marchedPath = contour.map((point) => ({
x: Math.round(point.x * options.pixelGroupSize + activeRegion.min[0]),
y: Math.round(point.y * options.pixelGroupSize + activeRegion.min[1]),
@@ -551,10 +472,7 @@ export const genBubbleSet = (
const hullPoints = hull.map((point) => [point.x, point.y]);
const nodeBBox = graph.getRenderBBox(model.id);
if (!nodeBBox) continue;
- if (
- !isPointInPolygon(hullPoints, nodeBBox.center[0], nodeBBox.center[1])
- )
- return false;
+ if (!isPointInPolygon(hullPoints, nodeBBox.center[0], nodeBBox.center[1])) return false;
}
// 不强制要求所有nonMembers都没有包含在内
// for (const item of nonMembers) {
@@ -572,10 +490,7 @@ export const genBubbleSet = (
if (iterations <= options.maxMarchingIterations * 0.5) {
options.memberInfluenceFactor *= 1.2;
options.edgeInfluenceFactor *= 1.2;
- } else if (
- options.nonMemberInfluenceFactor !== 0 &&
- nonMembers.length > 0
- ) {
+ } else if (options.nonMemberInfluenceFactor !== 0 && nonMembers.length > 0) {
// after half the iterations, start increasing positive energy and lowering the threshold
options.nonMemberInfluenceFactor *= 0.8;
} else {
@@ -587,8 +502,10 @@ export const genBubbleSet = (
/**
* union bounding box
+ * @param graph
* @param members
* @param edges
+ * @param offset
*/
function getActiveRegion(
graph: IGraph,
@@ -611,18 +528,10 @@ function getActiveRegion(
});
for (const bbox of bboxes) {
- activeRegion.min[0] =
- (bbox.min[0] < activeRegion.min[0] ? bbox.min[0] : activeRegion.min[0]) -
- offset;
- activeRegion.min[1] =
- (bbox.min[1] < activeRegion.min[1] ? bbox.min[1] : activeRegion.min[1]) -
- offset;
- activeRegion.max[0] =
- (bbox.max[0] > activeRegion.max[0] ? bbox.max[0] : activeRegion.max[0]) +
- offset;
- activeRegion.max[1] =
- (bbox.max[1] > activeRegion.max[1] ? bbox.max[1] : activeRegion.max[1]) +
- offset;
+ activeRegion.min[0] = (bbox.min[0] < activeRegion.min[0] ? bbox.min[0] : activeRegion.min[0]) - offset;
+ activeRegion.min[1] = (bbox.min[1] < activeRegion.min[1] ? bbox.min[1] : activeRegion.min[1]) - offset;
+ activeRegion.max[0] = (bbox.max[0] > activeRegion.max[0] ? bbox.max[0] : activeRegion.max[0]) + offset;
+ activeRegion.max[1] = (bbox.max[1] > activeRegion.max[1] ? bbox.max[1] : activeRegion.max[1]) + offset;
}
activeRegion.halfExtents = [
(activeRegion.max[0] - activeRegion.min[0]) / 2,
@@ -632,6 +541,16 @@ function getActiveRegion(
return activeRegion;
}
+/**
+ *
+ * @param graph
+ * @param members
+ * @param nonMembers
+ * @param edges
+ * @param activeRegion
+ * @param potentialArea
+ * @param options
+ */
function fillPotentialArea(
graph: IGraph,
members: (NodeModel | ComboModel)[],
@@ -641,58 +560,44 @@ function fillPotentialArea(
potentialArea,
options: BubblesetCfg,
) {
+ /**
+ *
+ * @param x
+ * @param offset
+ */
function pos2GridIx(x, offset) {
const gridIx = Math.floor((x - offset) / options.pixelGroupSize);
return gridIx < 0 ? 0 : gridIx;
}
+ /**
+ *
+ * @param x
+ * @param offset
+ */
function gridIx2Pos(x, offset) {
return x * options.pixelGroupSize + offset;
}
// using inverse a for numerical stability
- const nodeInfA =
- (options.nodeR0 - options.nodeR1) * (options.nodeR0 - options.nodeR1);
- const edgeInfA =
- (options.edgeR0 - options.edgeR1) * (options.edgeR0 - options.edgeR1);
+ const nodeInfA = (options.nodeR0 - options.nodeR1) * (options.nodeR0 - options.nodeR1);
+ const edgeInfA = (options.edgeR0 - options.edgeR1) * (options.edgeR0 - options.edgeR1);
const getAffectedRegion = (bbox: Bounds, thresholdR) => {
- const startX = Math.min(
- pos2GridIx(bbox.min[0], thresholdR + activeRegion.min[0]),
- potentialArea.width,
- );
- const startY = Math.min(
- pos2GridIx(bbox.min[1], thresholdR + activeRegion.min[1]),
- potentialArea.height,
- );
- const endX = Math.min(
- pos2GridIx(bbox.max[0], -thresholdR + activeRegion.min[0]),
- potentialArea.width,
- );
- const endY = Math.min(
- pos2GridIx(bbox.max[1], -thresholdR + activeRegion.min[1]),
- potentialArea.height,
- );
+ const startX = Math.min(pos2GridIx(bbox.min[0], thresholdR + activeRegion.min[0]), potentialArea.width);
+ const startY = Math.min(pos2GridIx(bbox.min[1], thresholdR + activeRegion.min[1]), potentialArea.height);
+ const endX = Math.min(pos2GridIx(bbox.max[0], -thresholdR + activeRegion.min[0]), potentialArea.width);
+ const endY = Math.min(pos2GridIx(bbox.max[1], -thresholdR + activeRegion.min[1]), potentialArea.height);
return [startX, startY, endX, endY];
};
- const addItemInfluence = (
- graph: IGraph,
- model: NodeModel | ComboModel,
- influenceFactor: number,
- ) => {
+ const addItemInfluence = (graph: IGraph, model: NodeModel | ComboModel, influenceFactor: number) => {
const bbox = graph.getRenderBBox(model.id);
if (!bbox) return;
- const [startX, startY, endX, endY] = getAffectedRegion(
- bbox,
- options.nodeR1,
- );
+ const [startX, startY, endX, endY] = getAffectedRegion(bbox, options.nodeR1);
// calculate item influence for each cell
for (let y = startY; y < endY; y += 1) {
for (let x = startX; x < endX; x += 1) {
- if (
- influenceFactor < 0 &&
- potentialArea[x + y * potentialArea.width] <= 0
- ) {
+ if (influenceFactor < 0 && potentialArea[x + y * potentialArea.width] <= 0) {
continue;
}
const tempX = gridIx2Pos(x, activeRegion.min[0]);
@@ -708,8 +613,7 @@ function fillPotentialArea(
);
if (distanceSq < options.nodeR1 ** 2) {
const dr = Math.sqrt(distanceSq) - options.nodeR1;
- potentialArea.cells[x + y * potentialArea.width] +=
- influenceFactor * dr * dr;
+ potentialArea.cells[x + y * potentialArea.width] += influenceFactor * dr * dr;
}
}
}
@@ -717,17 +621,11 @@ function fillPotentialArea(
const addEdgeInfluence = (line: LineStructure, influenceFactor: number) => {
const bbox = line.getBBox();
- const [startX, startY, endX, endY] = getAffectedRegion(
- bbox,
- options.edgeR1,
- );
+ const [startX, startY, endX, endY] = getAffectedRegion(bbox, options.edgeR1);
// for every point in active part of potentialArea, calculate distance to nearest point on line and add influence
for (let y = startY; y < endY; y += 1) {
for (let x = startX; x < endX; x += 1) {
- if (
- influenceFactor < 0 &&
- potentialArea.cells[x + y * potentialArea.width] <= 0
- ) {
+ if (influenceFactor < 0 && potentialArea.cells[x + y * potentialArea.width] <= 0) {
continue;
}
const tempX = gridIx2Pos(x, activeRegion.min[0]);
@@ -736,8 +634,7 @@ function fillPotentialArea(
// only influence if less than r1
if (minDistanceSq < options.edgeR1 ** 2) {
const mdr = Math.sqrt(minDistanceSq) - options.edgeR1;
- potentialArea.cells[x + y * potentialArea.width] +=
- influenceFactor * mdr * mdr;
+ potentialArea.cells[x + y * potentialArea.width] += influenceFactor * mdr * mdr;
}
}
}
@@ -756,24 +653,21 @@ function fillPotentialArea(
}
if (options.negativeNodeInfluenceFactor) {
nonMembers.forEach((item) => {
- addItemInfluence(
- graph,
- item,
- options.negativeNodeInfluenceFactor / nodeInfA,
- );
+ addItemInfluence(graph, item, options.negativeNodeInfluenceFactor / nodeInfA);
});
}
}
-function rerouteLine(
- item,
- buffer: number,
- intersections: Point[],
- wrapNormal: boolean,
-): Point {
+/**
+ *
+ * @param item
+ * @param buffer
+ * @param intersections
+ * @param wrapNormal
+ */
+function rerouteLine(item, buffer: number, intersections: Point[], wrapNormal: boolean): Point {
const bbox = item.getBBox();
- const [topIntersect, leftIntersect, bottomIntersect, rightIntersect] =
- intersections;
+ const [topIntersect, leftIntersect, bottomIntersect, rightIntersect] = intersections;
const cornerPos = {
topLeft: { x: bbox.minX - buffer, y: bbox.minY - buffer },
topRight: { x: bbox.maxX + buffer, y: bbox.minY - buffer },
@@ -782,47 +676,41 @@ function rerouteLine(
};
const totalArea = bbox.height * bbox.width;
+ /**
+ *
+ * @param intersect1
+ * @param intersect2
+ */
function calcHalfArea(intersect1, intersect2) {
- return (
- bbox.width *
- ((intersect1.y - bbox.minY + (intersect2.y - bbox.minY)) * 0.5)
- );
+ return bbox.width * ((intersect1.y - bbox.minY + (intersect2.y - bbox.minY)) * 0.5);
}
// Find the position of the control point according to the intersect of line and bounding box
if (leftIntersect) {
// If there is a triangle in the intersect area
- if (topIntersect)
- return wrapNormal ? cornerPos.topLeft : cornerPos.bottomRight;
- if (bottomIntersect)
- return wrapNormal ? cornerPos.bottomLeft : cornerPos.topRight;
+ if (topIntersect) return wrapNormal ? cornerPos.topLeft : cornerPos.bottomRight;
+ if (bottomIntersect) return wrapNormal ? cornerPos.bottomLeft : cornerPos.topRight;
// Divide the intersect area into two trapezoids upper and down, compare the area
const topArea = calcHalfArea(leftIntersect, rightIntersect);
if (topArea < totalArea * 0.5) {
- if (leftIntersect.y > rightIntersect.y)
- return wrapNormal ? cornerPos.topLeft : cornerPos.bottomRight;
+ if (leftIntersect.y > rightIntersect.y) return wrapNormal ? cornerPos.topLeft : cornerPos.bottomRight;
return wrapNormal ? cornerPos.topRight : cornerPos.bottomLeft;
}
- if (leftIntersect.y < rightIntersect.y)
- return wrapNormal ? cornerPos.bottomLeft : cornerPos.topRight;
+ if (leftIntersect.y < rightIntersect.y) return wrapNormal ? cornerPos.bottomLeft : cornerPos.topRight;
return wrapNormal ? cornerPos.bottomRight : cornerPos.topLeft;
}
if (rightIntersect) {
- if (topIntersect)
- return wrapNormal ? cornerPos.topRight : cornerPos.bottomLeft;
- if (bottomIntersect)
- return wrapNormal ? cornerPos.bottomRight : cornerPos.topLeft;
+ if (topIntersect) return wrapNormal ? cornerPos.topRight : cornerPos.bottomLeft;
+ if (bottomIntersect) return wrapNormal ? cornerPos.bottomRight : cornerPos.topLeft;
}
// Divide the intersect area into two trapezoids left and right
const leftArea = calcHalfArea(topIntersect, bottomIntersect);
if (leftArea < totalArea * 0.5) {
- if (topIntersect.x > bottomIntersect.x)
- return wrapNormal ? cornerPos.topLeft : cornerPos.bottomRight;
+ if (topIntersect.x > bottomIntersect.x) return wrapNormal ? cornerPos.topLeft : cornerPos.bottomRight;
return wrapNormal ? cornerPos.bottomLeft : cornerPos.topRight;
}
- if (topIntersect.x < bottomIntersect.x)
- return wrapNormal ? cornerPos.topRight : cornerPos.bottomLeft;
+ if (topIntersect.x < bottomIntersect.x) return wrapNormal ? cornerPos.topRight : cornerPos.bottomLeft;
return wrapNormal ? cornerPos.bottomRight : cornerPos.topLeft;
}
diff --git a/packages/g6/src/stdlib/plugin/hull/convexHull.ts b/packages/g6/src/stdlib/plugin/hull/convexHull.ts
index b43c9aaa0d8..d50cd475d19 100644
--- a/packages/g6/src/stdlib/plugin/hull/convexHull.ts
+++ b/packages/g6/src/stdlib/plugin/hull/convexHull.ts
@@ -5,6 +5,9 @@ import { Point } from '../../../types/common';
* Use cross product to judge the direction of the turn.
* Returns a positive value, if OAB makes a clockwise turn,
* negative for counter-clockwise turn, and zero if the points are collinear.
+ * @param a
+ * @param b
+ * @param o
*/
export const cross = (a: Point, b: Point, o: Point) => {
return (a.y - o.y) * (b.x - o.x) - (a.x - o.x) * (b.y - o.y);
@@ -12,8 +15,8 @@ export const cross = (a: Point, b: Point, o: Point) => {
/**
* Generate a convex hull of given points. Andrew's monotone chain algorithm.
- * @param points An array of [x, y] representing the coordinates of points.
- * @return a list of vertices of the convex hull in counter-clockwise order,
+ * @param models An array of [x, y] representing the coordinates of points.
+ * @returns a list of vertices of the convex hull in counter-clockwise order,
*/
export const genConvexHull = (models: (NodeModel | ComboModel)[]) => {
const points: Point[] = models.map(
@@ -21,7 +24,7 @@ export const genConvexHull = (models: (NodeModel | ComboModel)[]) => {
({
x: model.data.x,
y: model.data.y,
- } as Point),
+ }) as Point,
);
points.sort((a, b) => {
return a.x === b.x ? a.y - b.y : a.x - b.x;
@@ -41,10 +44,7 @@ export const genConvexHull = (models: (NodeModel | ComboModel)[]) => {
// build the lower hull
const lower = [];
for (let i = 0; i < points.length; i++) {
- while (
- lower.length >= 2 &&
- cross(lower[lower.length - 2], lower[lower.length - 1], points[i]) <= 0
- ) {
+ while (lower.length >= 2 && cross(lower[lower.length - 2], lower[lower.length - 1], points[i]) <= 0) {
lower.pop();
}
lower.push(points[i]);
@@ -53,10 +53,7 @@ export const genConvexHull = (models: (NodeModel | ComboModel)[]) => {
// build the upper hull
const upper = [];
for (let i = points.length - 1; i >= 0; i--) {
- while (
- upper.length >= 2 &&
- cross(upper[upper.length - 2], upper[upper.length - 1], points[i]) <= 0
- ) {
+ while (upper.length >= 2 && cross(upper[upper.length - 2], upper[upper.length - 1], points[i]) <= 0) {
upper.pop();
}
upper.push(points[i]);
diff --git a/packages/g6/src/stdlib/plugin/hull/hullComponent.ts b/packages/g6/src/stdlib/plugin/hull/hullComponent.ts
index 61f7a7c5a56..103504e50b6 100644
--- a/packages/g6/src/stdlib/plugin/hull/hullComponent.ts
+++ b/packages/g6/src/stdlib/plugin/hull/hullComponent.ts
@@ -2,19 +2,19 @@ import { DisplayObject } from '@antv/g';
import { isArray } from '@antv/util';
import { ComboModel, ID, IGraph, NodeModel } from '../../../types';
import { ShapeStyle } from '../../../types/item';
-import { isPolygonsIntersect } from '../../../util/shape';
import { pathToPoints } from '../../../util/path';
+import { isPolygonsIntersect } from '../../../util/shape';
+import { genBubbleSet } from './bubbleset';
+import { genConvexHull } from './convexHull';
+import { BubblesetCfg } from './types';
import {
getClosedSpline,
- roundedHull,
- paddedHull,
- getPolygonIntersectByLine,
getExtendPoint,
getInvertBaseline,
+ getPolygonIntersectByLine,
+ paddedHull,
+ roundedHull,
} from './util';
-import { genConvexHull } from './convexHull';
-import { genBubbleSet } from './bubbleset';
-import { BubblesetCfg } from './types';
type LabelPlacement = 'top' | 'bottom' | 'right' | 'left';
@@ -71,12 +71,8 @@ export default class Hull {
const { members: memberIds = [], nonMembers: nonMemberIds = [] } = options;
this.options = options;
this.graph = graph;
- this.members = memberIds.map(
- (id) => graph.getNodeData(id) || graph.getComboData(id),
- );
- this.nonMembers = nonMemberIds.map(
- (id) => graph.getNodeData(id) || graph.getComboData(id),
- );
+ this.members = memberIds.map((id) => graph.getNodeData(id) || graph.getComboData(id));
+ this.nonMembers = nonMemberIds.map((id) => graph.getNodeData(id) || graph.getComboData(id));
this.setPadding();
this.setType();
@@ -99,10 +95,7 @@ export default class Hull {
const firstBBox = this.graph.getRenderBBox(this.members[0].id);
if (firstBBox) nodeSize = firstBBox.halfExtents[0];
}
- this.padding =
- this.options.padding > 0
- ? this.options.padding + nodeSize
- : 10 + nodeSize;
+ this.padding = this.options.padding > 0 ? this.options.padding + nodeSize : 10 + nodeSize;
this.bubbleCfg = {
...this.options.bubbleCfg,
nodeR0: this.padding - nodeSize,
@@ -116,11 +109,7 @@ export default class Hull {
if (this.members.length < 3) {
this.type = 'round-convex';
}
- if (
- this.type !== 'round-convex' &&
- this.type !== 'smooth-convex' &&
- this.type !== 'bubble'
- ) {
+ if (this.type !== 'round-convex' && this.type !== 'smooth-convex' && this.type !== 'bubble') {
console.warn(
'The hull type should be either round-convex, smooth-convex or bubble, round-convex is used by default.',
);
@@ -128,10 +117,7 @@ export default class Hull {
}
}
- getPath(
- members: (NodeModel | ComboModel)[],
- nonMembers: (NodeModel | ComboModel)[],
- ) {
+ getPath(members: (NodeModel | ComboModel)[], nonMembers: (NodeModel | ComboModel)[]) {
let contour, path, hull;
switch (this.type) {
case 'round-convex':
@@ -194,12 +180,7 @@ export default class Hull {
}
private getLabelStyle(propsStyle, keyShapeBounds) {
- const {
- position,
- offsetX = 0,
- offsetY = 0,
- autoRotate = true,
- } = propsStyle;
+ const { position, offsetX = 0, offsetY = 0, autoRotate = true } = propsStyle;
const { min, max, center } = keyShapeBounds;
const style: ShapeStyle = {
x: 0,
@@ -258,18 +239,13 @@ export default class Hull {
startPoint = { x: center[0], y: center[1] };
}
const extendedPoint = getExtendPoint(point, startPoint, 100);
- const intersect = getPolygonIntersectByLine(points, [
- startPoint,
- extendedPoint,
- ]);
+ const intersect = getPolygonIntersectByLine(points, [startPoint, extendedPoint]);
if (intersect) {
const { point: intersectPoint, line } = intersect;
style.x = intersectPoint.x + offsetX;
style.y = intersectPoint.y + offsetY;
if (autoRotate) {
- const angle = Math.atan(
- (line[0].y - line[1].y) / (line[0].x - line[1].x),
- );
+ const angle = Math.atan((line[0].y - line[1].y) / (line[0].x - line[1].x));
style.transform = `rotate(${(angle / Math.PI) * 180}deg)`;
style.textAlign = 'center';
if (position === 'right' || position === 'left') {
@@ -294,7 +270,7 @@ export default class Hull {
/**
* Add a member of hull, and if the member was originally in nonMembers, remove it from nonMembers.
* @param itemIds id(s) of member nodes/combos
- * @return boolean Whether successfully added.
+ * @returns boolean Whether successfully added.
*/
public addMember(itemIds: ID | ID[]): boolean {
if (!itemIds) return;
@@ -325,7 +301,7 @@ export default class Hull {
/**
* Add the nodes that the hull needs to exclude, and if the member was originally in the members, remove it from the members.
* @param itemIds id(s) of member nodes/combos
- * @return boolean Whether successfully added.
+ * @returns boolean Whether successfully added.
*/
public addNonMember(itemIds: ID | ID[]): boolean {
if (!itemIds) return;
@@ -357,7 +333,7 @@ export default class Hull {
/**
* Remove members from the hull.
* @param itemIds id(s) of member nodes/combos
- * @return boolean Returns true if the removal is successful, otherwise returns false.
+ * @returns boolean Returns true if the removal is successful, otherwise returns false.
*/
public removeMember(itemIds: ID | ID[]): boolean {
if (!itemIds) return;
@@ -383,7 +359,7 @@ export default class Hull {
/**
* Remove non members from the hull.
* @param itemIds id(s) of member nodes/combos
- * @return boolean Returns true if the removal is successful, otherwise returns false.
+ * @returns boolean Returns true if the removal is successful, otherwise returns false.
*/
public removeNonMember(itemIds: ID | ID[]): boolean {
if (!itemIds) return;
@@ -410,15 +386,11 @@ export default class Hull {
public updateMembers(memberIds?: ID[], nonMemberIds?: ID[]) {
if (memberIds) {
this.options.members = memberIds;
- this.members = memberIds.map(
- (id) => this.graph.getNodeData(id) || this.graph.getComboData(id),
- );
+ this.members = memberIds.map((id) => this.graph.getNodeData(id) || this.graph.getComboData(id));
}
if (nonMemberIds) {
this.options.nonMembers = nonMemberIds;
- this.nonMembers = nonMemberIds.map(
- (id) => this.graph.getNodeData(id) || this.graph.getComboData(id),
- );
+ this.nonMembers = nonMemberIds.map((id) => this.graph.getNodeData(id) || this.graph.getComboData(id));
}
this.path = this.getPath(this.members, this.nonMembers);
this.render();
@@ -452,14 +424,10 @@ export default class Hull {
},
};
if (memberIds) {
- this.members = memberIds.map(
- (id) => this.graph.getNodeData(id) || this.graph.getComboData(id),
- );
+ this.members = memberIds.map((id) => this.graph.getNodeData(id) || this.graph.getComboData(id));
}
if (nonMemberIds) {
- this.nonMembers = nonMemberIds.map(
- (id) => this.graph.getNodeData(id) || this.graph.getComboData(id),
- );
+ this.nonMembers = nonMemberIds.map((id) => this.graph.getNodeData(id) || this.graph.getComboData(id));
}
this.setPadding();
this.setType();
diff --git a/packages/g6/src/stdlib/plugin/hull/index.ts b/packages/g6/src/stdlib/plugin/hull/index.ts
index 71d872e510f..290bccf47d4 100644
--- a/packages/g6/src/stdlib/plugin/hull/index.ts
+++ b/packages/g6/src/stdlib/plugin/hull/index.ts
@@ -1,12 +1,12 @@
import { isArray, throttle, uniqueId } from '@antv/util';
-import { ITEM_TYPE, ShapeStyle } from '../../../types/item';
+import { DEFAULT_TEXT_STYLE } from '../../../constant';
import { ComboModel, EdgeModel, ID, IGraph, NodeModel } from '../../../types';
+import { ComboLabelPosition } from '../../../types/combo';
+import { ITEM_TYPE, ShapeStyle } from '../../../types/item';
import { Plugin as Base, IPluginBaseConfig } from '../../../types/plugin';
import { isArrayOverlap } from '../../../util/array';
-import { ComboLabelPosition } from '../../../types/combo';
-import { DEFAULT_TEXT_STYLE } from '../../../constant';
-import { BubblesetCfg } from './types';
import HullComponent, { HullComponentOptions } from './hullComponent';
+import { BubblesetCfg } from './types';
interface HullConfig extends IPluginBaseConfig {
/** Common style for the hulls in this plugin. You can also configure individually for each hulls. */
@@ -71,6 +71,10 @@ export default class Hull extends Base {
/**
* viewport change
* @param param
+ * @param param.itemType
+ * @param param.action
+ * @param param.models
+ * @param param.ids
*/
protected handleNodesChange(param: {
itemType: ITEM_TYPE;
@@ -93,14 +97,11 @@ export default class Hull extends Base {
Object.keys(this.hullMap).forEach((id) => {
const hullComponent = this.hullMap[id];
if (this.cacheChanges.remove.length) {
- isArrayOverlap(
- hullComponent.options.members,
- this.cacheChanges.remove,
- ) && hullComponent.removeMember(this.cacheChanges.remove);
+ isArrayOverlap(hullComponent.options.members, this.cacheChanges.remove) &&
+ hullComponent.removeMember(this.cacheChanges.remove);
} else if (this.cacheChanges.update.length) {
const modelIds = this.cacheChanges.update.map((model) => model.id);
- isArrayOverlap(hullComponent.options.members, modelIds) &&
- hullComponent.updateMembers();
+ isArrayOverlap(hullComponent.options.members, modelIds) && hullComponent.updateMembers();
}
});
this.cacheChanges = { update: [], remove: [] };
@@ -120,16 +121,9 @@ export default class Hull extends Base {
const { padding, style, bubbleCfg, labelShape } = this.options;
const configs = isArray(options) ? options : [options];
configs.forEach((config) => {
- const {
- id,
- style: singleStyle,
- labelShape: singleLabelShape,
- members,
- ...others
- } = config;
+ const { id, style: singleStyle, labelShape: singleLabelShape, members, ...others } = config;
const validMembers = members?.filter(
- (memberId) =>
- this.graph.getNodeData(memberId) || this.graph.getComboData(memberId),
+ (memberId) => this.graph.getNodeData(memberId) || this.graph.getComboData(memberId),
);
if (!validMembers?.length) {
console.warn(`Create hull failed. There are no valid members.`);
@@ -170,9 +164,7 @@ export default class Hull extends Base {
configs.forEach((config) => {
const { id, ...others } = config;
if (!this.hullMap[id]) {
- console.warn(
- `Update hull component failed. The bubble with id ${id} is not existed.`,
- );
+ console.warn(`Update hull component failed. The bubble with id ${id} is not existed.`);
return;
}
this.hullMap[id].updateOptions(others);
@@ -191,9 +183,7 @@ export default class Hull extends Base {
public addHullMember(id: ID, members: ID | ID[]) {
const hullComponent = this.hullMap[id];
if (!hullComponent) {
- console.warn(
- `Add member to hull failed. The hull with id ${id} is not exist`,
- );
+ console.warn(`Add member to hull failed. The hull with id ${id} is not exist`);
return;
}
hullComponent.addMember(members);
@@ -202,9 +192,7 @@ export default class Hull extends Base {
public removeHullMember(id: ID, members: ID | ID[]) {
const hullComponent = this.hullMap[id];
if (!hullComponent) {
- console.warn(
- `Remove member from hull failed. The hull with id ${id} is not exist`,
- );
+ console.warn(`Remove member from hull failed. The hull with id ${id} is not exist`);
return;
}
hullComponent.removeMember(members);
@@ -213,9 +201,7 @@ export default class Hull extends Base {
public addHullNonMember(id: ID, members: ID | ID[]) {
const hullComponent = this.hullMap[id];
if (!hullComponent) {
- console.warn(
- `Add non member to hull failed. The hull with id ${id} is not exist`,
- );
+ console.warn(`Add non member to hull failed. The hull with id ${id} is not exist`);
return;
}
hullComponent.addNonMember(members);
@@ -224,9 +210,7 @@ export default class Hull extends Base {
public removeHullNonMember(id: ID, members: ID | ID[]) {
const hullComponent = this.hullMap[id];
if (!hullComponent) {
- console.warn(
- `Remove non member from hull failed. The hull with id ${id} is not exist`,
- );
+ console.warn(`Remove non member from hull failed. The hull with id ${id} is not exist`);
return;
}
hullComponent.removeNonMember(members);
diff --git a/packages/g6/src/stdlib/plugin/hull/util.ts b/packages/g6/src/stdlib/plugin/hull/util.ts
index 7c31f7943f7..587c38dd5c6 100644
--- a/packages/g6/src/stdlib/plugin/hull/util.ts
+++ b/packages/g6/src/stdlib/plugin/hull/util.ts
@@ -1,6 +1,6 @@
+import { AABB } from '@antv/g';
import { vec2 } from 'gl-matrix';
import { ID, IGraph } from 'types';
-import { AABB } from '@antv/g';
import { Bounds, Point } from '../../../types/common';
import { getLineIntersect } from '../../../util/shape';
@@ -10,9 +10,7 @@ import { getLineIntersect } from '../../../util/shape';
*/
export const getClosedSpline = (points: Point[]) => {
if (points.length < 2) {
- throw new Error(
- `point length must larges than 2, now it's ${points.length}`,
- );
+ throw new Error(`point length must larges than 2, now it's ${points.length}`);
}
const first = points[0];
const second = points[1];
@@ -65,11 +63,7 @@ export function roundedHull(polyPoints: vec2[], padding: number) {
// The rounded hull path around two points
const roundedHull2 = (points: vec2[]) => {
- const offsetVector = vec2.scale(
- [0, 0],
- unitNormal(points[0], points[1]),
- padding,
- );
+ const offsetVector = vec2.scale([0, 0], unitNormal(points[0], points[1]), padding);
const invOffsetVector = vec2.scale([0, 0], offsetVector, -1);
const p0 = vec2.add([0, 0], points[0], offsetVector);
@@ -77,9 +71,12 @@ export function roundedHull(polyPoints: vec2[], padding: number) {
const p2 = vec2.add([0, 0], points[1], invOffsetVector);
const p3 = vec2.add([0, 0], points[0], invOffsetVector);
- return `M ${p0} L ${p1} A ${[padding, padding, '0,0,0', p2].join(
- ',',
- )} L ${p3} A ${[padding, padding, '0,0,0', p0].join(',')}`;
+ return `M ${p0} L ${p1} A ${[padding, padding, '0,0,0', p2].join(',')} L ${p3} A ${[
+ padding,
+ padding,
+ '0,0,0',
+ p0,
+ ].join(',')}`;
};
// Special case handling: the number of nodes is less than or equal to 2
@@ -91,19 +88,13 @@ export function roundedHull(polyPoints: vec2[], padding: number) {
// Calculate each offset (outwards) segment of the convex hull.
for (let segmentIndex = 0; segmentIndex < segments.length; ++segmentIndex) {
- const p0 =
- segmentIndex === 0
- ? polyPoints[polyPoints.length - 1]
- : polyPoints[segmentIndex - 1];
+ const p0 = segmentIndex === 0 ? polyPoints[polyPoints.length - 1] : polyPoints[segmentIndex - 1];
const p1 = polyPoints[segmentIndex];
// Compute the offset vector for the line segment, with length = padding.
const offset = vec2.scale([0, 0], unitNormal(p0, p1), padding);
- segments[segmentIndex] = [
- vec2.add([0, 0], p0, offset),
- vec2.add([0, 0], p1, offset),
- ];
+ segments[segmentIndex] = [vec2.add([0, 0], p0, offset), vec2.add([0, 0], p1, offset)];
}
const arcData = `A ${[padding, padding, '0,0,0,'].join(',')}`;
@@ -134,12 +125,7 @@ export function paddedHull(polyPoints: vec2[], padding: number) {
const p1 = [points[0][0], points[0][1] - padding];
const p2 = [points[0][0], points[0][1] + padding];
- return `M ${p1} A ${[padding, padding, '0,0,0', p2].join(',')} A ${[
- padding,
- padding,
- '0,0,0',
- p1,
- ].join(',')}`;
+ return `M ${p1} A ${[padding, padding, '0,0,0', p2].join(',')} A ${[padding, padding, '0,0,0', p1].join(',')}`;
};
// Returns the path for a rounded hull around two points.
@@ -147,27 +133,18 @@ export function paddedHull(polyPoints: vec2[], padding: number) {
const v = vecFrom(points[0], points[1]);
const extensionVec = vecScaleTo(v, padding);
- const extension0 = vec2.add(
- [0, 0],
- points[0],
- vec2.scale([0, 0], extensionVec, -1),
- );
+ const extension0 = vec2.add([0, 0], points[0], vec2.scale([0, 0], extensionVec, -1));
const extension1 = vec2.add([0, 0], points[1], extensionVec);
const tangentHalfLength = 1.2 * padding;
- const controlDelta = vecScaleTo(
- vec2.normalize([0, 0], v),
- tangentHalfLength,
- );
+ const controlDelta = vecScaleTo(vec2.normalize([0, 0], v), tangentHalfLength);
const invControlDelta = vec2.scale([0, 0], controlDelta, -1);
const control0 = vec2.add([0, 0], extension0, invControlDelta);
const control1 = vec2.add([0, 0], extension1, invControlDelta);
const control3 = vec2.add([0, 0], extension0, controlDelta);
- return `M ${extension0} C ${[control0, control1, extension1].join(
- ',',
- )} S ${[control3, extension0].join(',')} Z`;
+ return `M ${extension0} C ${[control0, control1, extension1].join(',')} S ${[control3, extension0].join(',')} Z`;
};
// Handle special cases
@@ -188,17 +165,9 @@ export function paddedHull(polyPoints: vec2[], padding: number) {
const priorIndex = i > 0 ? i - 1 : pointCount - 1;
const extensionVec = vec2.normalize(
[0, 0],
- vec2.add(
- [0, 0],
- hullPoints[priorIndex].v,
- vec2.scale([0, 0], hullPoints[i].v, -1),
- ),
- );
- hullPoints[i].p = vec2.add(
- [0, 0],
- hullPoints[i].p as vec2,
- vec2.scale([0, 0], extensionVec, padding),
+ vec2.add([0, 0], hullPoints[priorIndex].v, vec2.scale([0, 0], hullPoints[i].v, -1)),
);
+ hullPoints[i].p = vec2.add([0, 0], hullPoints[i].p as vec2, vec2.scale([0, 0], extensionVec, padding));
}
return hullPoints.map((obj) => {
@@ -304,11 +273,7 @@ export const squareDist = (a: Point, b: Point): number => {
return (a.x - b.x) ** 2 + (a.y - b.y) ** 2;
};
-export const fractionToLine = (
- graph: IGraph,
- itemId: ID,
- line: LineStructure,
-) => {
+export const fractionToLine = (graph: IGraph, itemId: ID, line: LineStructure) => {
const directions = ['top', 'left', 'bottom', 'right'];
const bbox = graph.getRenderBBox(itemId);
if (!bbox) return Infinity;
@@ -316,10 +281,7 @@ export const fractionToLine = (
let countIntersections = 0;
for (let i = 0; i < 4; i++) {
const [x1, y1, x2, y2] = getBBoxBoundLine(bbox, directions[i]);
- let testDistance = fractionAlongLineA(
- line,
- new LineStructure(x1, y1, x2, y2),
- );
+ let testDistance = fractionAlongLineA(line, new LineStructure(x1, y1, x2, y2));
testDistance = Math.abs(testDistance - 0.5);
if (testDistance >= 0 && testDistance <= 1) {
countIntersections += 1;
@@ -343,14 +305,13 @@ export const getBBoxBoundLine = (bbox: AABB, direction: string) => {
/**
* When calculating the intersection of two line segments, the division ratio of the intersection point to the first line segment.
+ * @param la
+ * @param lb
*/
const fractionAlongLineA = (la: LineStructure, lb: LineStructure) => {
- const uaT =
- (lb.x2 - lb.x1) * (la.y1 - lb.y1) - (lb.y2 - lb.y1) * (la.x1 - lb.x1);
- const ubT =
- (la.x2 - la.x1) * (la.y1 - lb.y1) - (la.y2 - la.y1) * (la.x1 - lb.x1);
- const uB =
- (lb.y2 - lb.y1) * (la.x2 - la.x1) - (lb.x2 - lb.x1) * (la.y2 - la.y1);
+ const uaT = (lb.x2 - lb.x1) * (la.y1 - lb.y1) - (lb.y2 - lb.y1) * (la.x1 - lb.x1);
+ const ubT = (la.x2 - la.x1) * (la.y1 - lb.y1) - (la.y2 - la.y1) * (la.x1 - lb.x1);
+ const uB = (lb.y2 - lb.y1) * (la.x2 - la.x1) - (lb.x2 - lb.x1) * (la.y2 - la.y1);
if (uB) {
const ua = uaT / uB;
const ub = ubT / uB;
@@ -365,11 +326,7 @@ export const isPointsOverlap = (p1, p2, e = 1e-3) => {
return (p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2 < e ** 2;
};
-export const itemIntersectByLine = (
- graph: IGraph,
- itemId: ID,
- line: LineStructure,
-): [Point[], number] => {
+export const itemIntersectByLine = (graph: IGraph, itemId: ID, line: LineStructure): [Point[], number] => {
const directions = ['top', 'left', 'bottom', 'right'];
const bbox = graph.getRenderBBox(itemId);
if (!bbox) return;
@@ -395,11 +352,12 @@ export const itemIntersectByLine = (
* The square of the distance from the point to the rectangle: the distance from the point inside the rectangle is 0, if the projection of the point outside falls on the side of the rectangle, it is the nearest vertical distance from the point to the side of the rectangle, otherwise it is the distance from the point to the vertex of the rectangle.
* @param point Point
* @param rect Rect
+ * @param rect.width
+ * @param rect.height
+ * @param rect.x
+ * @param rect.y
*/
-export const pointRectSquareDist = (
- point: Point,
- rect: { width: number; height: number; x: number; y: number },
-) => {
+export const pointRectSquareDist = (point: Point, rect: { width: number; height: number; x: number; y: number }) => {
const isLeft = point.x < rect.x;
const isRight = point.x > rect.x + rect.width;
const isTop = point.y > rect.y + rect.height;
@@ -421,14 +379,8 @@ export const pointRectSquareDist = (
if (isRight && !isTop && !isBottom) {
return (rect.x + rect.width - point.x) ** 2;
}
- const dx = Math.min(
- Math.abs(rect.x - point.x),
- Math.abs(rect.x + rect.width - point.x),
- );
- const dy = Math.min(
- Math.abs(rect.y - point.y),
- Math.abs(rect.y + rect.height - point.y),
- );
+ const dx = Math.min(Math.abs(rect.x - point.x), Math.abs(rect.x + rect.width - point.x));
+ const dy = Math.min(Math.abs(rect.y - point.y), Math.abs(rect.y + rect.height - point.y));
return dx * dx + dy * dy;
};
diff --git a/packages/g6/src/stdlib/plugin/index.ts b/packages/g6/src/stdlib/plugin/index.ts
index bfed9e591da..e5c7abc2318 100644
--- a/packages/g6/src/stdlib/plugin/index.ts
+++ b/packages/g6/src/stdlib/plugin/index.ts
@@ -1,13 +1,13 @@
export * from './edgeBundling';
+export * from './edgeFilterLens';
export * from './fisheye';
export * from './grid';
export * from './history';
export * from './legend';
+export * from './lodController';
export * from './menu';
export * from './minimap';
+export * from './snapline';
+export * from './timebar';
export * from './toolbar';
export * from './tooltip';
-export * from './timebar';
-export * from './snapline';
-export * from './edgeFilterLens';
-export * from './lodController';
diff --git a/packages/g6/src/stdlib/plugin/legend/index.ts b/packages/g6/src/stdlib/plugin/legend/index.ts
index 8780d6b166f..a3d9e996e97 100644
--- a/packages/g6/src/stdlib/plugin/legend/index.ts
+++ b/packages/g6/src/stdlib/plugin/legend/index.ts
@@ -1,13 +1,13 @@
-import { Category } from '@antv/gui';
-import { Canvas, DisplayObject, Circle, Line } from '@antv/g';
-import { isFunction, isString, upperFirst, uniqueId } from '@antv/util';
+import { Canvas, Circle, DisplayObject, Line } from '@antv/g';
import { ID } from '@antv/graphlib';
+import { Category } from '@antv/gui';
+import { isFunction, isString, uniqueId, upperFirst } from '@antv/util';
import { IGraph } from '../../../types';
-import { RendererName } from '../../../types/render';
import { Plugin as Base, IPluginBaseConfig } from '../../../types/plugin';
+import { RendererName } from '../../../types/render';
import { createCanvas } from '../../../util/canvas';
-import { ShapeTagMap, formatPadding } from '../../../util/shape';
import { createDOM } from '../../../util/dom';
+import { ShapeTagMap, formatPadding } from '../../../util/shape';
const LEGEND_CATEGORY_ITEM_MARKER = '.legend-category-item-marker';
@@ -212,16 +212,9 @@ export class Legend extends Base {
// If canvas does not exist, create it
if (!this.canvas) {
- const canvasSize = [
- size[0] === 'fit-content' ? 0 : size[0],
- size[1] === 'fit-content' ? 0 : size[1],
- ];
+ const canvasSize = [size[0] === 'fit-content' ? 0 : size[0], size[1] === 'fit-content' ? 0 : size[1]];
- const {
- canvas,
- background,
- renderer = 'canvas',
- } = this.options as LegendConfig;
+ const { canvas, background, renderer = 'canvas' } = this.options as LegendConfig;
if (canvas) {
this.canvas = canvas;
} else {
@@ -230,14 +223,7 @@ export class Legend extends Base {
this.wrapper = this.createWrapper();
}
- this.canvas = createCanvas(
- renderer,
- this.wrapper,
- canvasSize[0],
- canvasSize[1],
- undefined,
- { background },
- );
+ this.canvas = createCanvas(renderer, this.wrapper, canvasSize[0], canvasSize[1], undefined, { background });
}
// Add click event listener to canvas
@@ -248,10 +234,8 @@ export class Legend extends Base {
// Clear relevant states on the graph
const { graph, options } = this;
const { activeState, selectedState } = options;
- if (this.activeIds.node.size)
- graph.clearItemState(Array.from(this.activeIds.node), activeState);
- if (this.activeIds.edge.size)
- graph.clearItemState(Array.from(this.activeIds.edge), activeState);
+ if (this.activeIds.node.size) graph.clearItemState(Array.from(this.activeIds.node), activeState);
+ if (this.activeIds.edge.size) graph.clearItemState(Array.from(this.activeIds.edge), activeState);
this.activeIds = {
node: new Set(),
edge: new Set(),
@@ -268,17 +252,13 @@ export class Legend extends Base {
// Clear legend states
this.selectedTypes.node.forEach((nodeType) => {
- const marker = this.canvas
- .getRoot()
- .querySelector(`#marker-node-${nodeType}`);
+ const marker = this.canvas.getRoot().querySelector(`#marker-node-${nodeType}`);
if (!marker) return;
const lineWidth = this.styleCache.node[nodeType].lineWidth;
marker.style.lineWidth = lineWidth;
});
this.selectedTypes.edge.forEach((edgeType) => {
- const marker = this.canvas
- .getRoot()
- .querySelector(`#marker-edge-${edgeType}`);
+ const marker = this.canvas.getRoot().querySelector(`#marker-edge-${edgeType}`);
if (!marker) return;
const lineWidth = this.styleCache.edge[edgeType].lineWidth;
marker.style.lineWidth = lineWidth;
@@ -320,10 +300,7 @@ export class Legend extends Base {
$container = graph.container;
}
- const wrapperSize = [
- size[0] === 'fit-content' ? 0 : size[0],
- size[1] === 'fit-content' ? 0 : size[1],
- ];
+ const wrapperSize = [size[0] === 'fit-content' ? 0 : size[0], size[1] === 'fit-content' ? 0 : size[1]];
const wrapper = createDOM(
``,
);
@@ -333,8 +310,8 @@ export class Legend extends Base {
/**
* Creates a legend for the graph based on the given item type (node or edge).
- * @param {string} itemType - The type of item for which the legend is being created (node or edge).
- * @returns {Category} - The created legend.
+ * @param itemType - The type of item for which the legend is being created (node or edge).
+ * @returns The created legend.
*/
private upsertLegend(itemType: 'node' | 'edge' = 'node') {
const { graph, options, canvas } = this;
@@ -374,8 +351,7 @@ export class Legend extends Base {
const { size: legendSize, grid } = this.getLegendSize(rows, cols, padding);
// Gets all the data for the given item type and extracts the unique types based on the typeField.
- const data =
- itemType === 'node' ? graph.getAllNodesData() : graph.getAllEdgesData();
+ const data = itemType === 'node' ? graph.getAllNodesData() : graph.getAllEdgesData();
const typeSet = new Set();
const typeModelMap = {};
data.map((model) => {
@@ -393,16 +369,7 @@ export class Legend extends Base {
label: labelFormatter ? labelFormatter(type) : type,
}));
- const markerStyleKeys = [
- 'fill',
- 'stroke',
- 'fillOpacity',
- 'opacity',
- 'lineWidth',
- 'shadow',
- 'shadowBlur',
- 'size',
- ];
+ const markerStyleKeys = ['fill', 'stroke', 'fillOpacity', 'opacity', 'lineWidth', 'shadow', 'shadowBlur', 'size'];
// Creates the marker style for the legend based on the propsMarkerStyle or the style of the corresponding element on the graph.
const markerRelatedStyle: any = {};
@@ -410,8 +377,7 @@ export class Legend extends Base {
if (!propsMarkerStyle) {
// 使用图上对应元素的样式
const graphGroup = graph.canvas.getRoot();
- const itemTypeGroup =
- graphGroup.getElementById(`${itemType}-group`) || graphGroup;
+ const itemTypeGroup = graphGroup.getElementById(`${itemType}-group`) || graphGroup;
const typeStyleMap = {};
const formatStyles = {
x1: -10,
@@ -420,9 +386,7 @@ export class Legend extends Base {
y2: 0,
};
types.forEach((type) => {
- const itemGroup = itemTypeGroup.find(
- (ele) => ele.getAttribute('data-item-id') === typeModelMap[type].id,
- );
+ const itemGroup = itemTypeGroup.find((ele) => ele.getAttribute('data-item-id') === typeModelMap[type].id);
const keyShape = itemGroup.querySelector('#keyShape');
typeStyleMap[type] = {
shape: keyShape.nodeName,
@@ -441,9 +405,7 @@ export class Legend extends Base {
if (typeStyleMap[typeValue].style.r) markerStyleKey = 'r';
markerStyleKey = 'width';
}
- return (
- typeStyleMap[typeValue].style[markerStyleKey] || defaultStyle[key]
- );
+ return typeStyleMap[typeValue].style[markerStyleKey] || defaultStyle[key];
};
});
getShape = (item) => {
@@ -456,31 +418,21 @@ export class Legend extends Base {
};
} else {
// 使用 markerStyle 中的样式映射
- const { shape: markerShape, ...markerStyle } = Object.assign(
- {},
- defaultStyle,
- propsMarkerStyle || {},
- );
+ const { shape: markerShape, ...markerStyle } = Object.assign({}, defaultStyle, propsMarkerStyle || {});
getShape = this.getShapeConfig(itemType, markerShape);
Object.keys(markerStyle).forEach((key) => {
const styleValue = markerStyle[key];
let value = styleValue;
if (typeof styleValue === 'object') {
value = (item) => {
- return (
- styleValue[item.typeValue] ||
- styleValue[item.typeValue].size ||
- 10
- );
+ return styleValue[item.typeValue] || styleValue[item.typeValue].size || 10;
};
} else if (isFunction(styleValue)) {
value = (item) => styleValue(item.typeValue);
}
if (key === 'color') {
- markerRelatedStyle['itemMarkerFill'] =
- markerRelatedStyle['itemMarkerFill'] || value;
- markerRelatedStyle['itemMarkerStroke'] =
- markerRelatedStyle['itemMarkerStroke'] || value;
+ markerRelatedStyle['itemMarkerFill'] = markerRelatedStyle['itemMarkerFill'] || value;
+ markerRelatedStyle['itemMarkerStroke'] = markerRelatedStyle['itemMarkerStroke'] || value;
} else {
markerRelatedStyle[`itemMarker${upperFirstLetter(key)}`] = value;
}
@@ -510,13 +462,10 @@ export class Legend extends Base {
const { Shape, style } = getShape(item as any);
const { typeValue } = item;
this.styleCache[itemType][typeValue] = style;
- return () =>
- new Shape({ style, id: `marker-${itemType}-${typeValue}` });
+ return () => new Shape({ style, id: `marker-${itemType}-${typeValue}` });
},
- mouseenter: (ele) =>
- this.handleMouseEnter(ele, types, typeField, itemType, data),
- mouseleave: (ele) =>
- this.handleMouseLeave(ele, types, typeField, itemType),
+ mouseenter: (ele) => this.handleMouseEnter(ele, types, typeField, itemType, data),
+ mouseleave: (ele) => this.handleMouseLeave(ele, types, typeField, itemType),
click: (ele) => this.handleClick(ele, types, typeField, itemType, data),
},
});
@@ -566,29 +515,20 @@ export class Legend extends Base {
// Positions the legends based on their orientation and padding values.
if (orientation === 'horizontal') {
- firstItem.legend.translateLocal([
- 0,
- -bbox.min[1] + firstItem.padding[0],
- ]);
+ firstItem.legend.translateLocal([0, -bbox.min[1] + firstItem.padding[0]]);
const firstItemBounds = (
- firstItem.legend.childNodes[1].childNodes[0]
- .childNodes[0] as DisplayObject
+ firstItem.legend.childNodes[1].childNodes[0].childNodes[0] as DisplayObject
).getRenderBounds();
if (firstItemBounds) {
const firstBottom = firstItemBounds.max[1] + firstItem.padding[2];
secondItem.legend.translateLocal([0, firstBottom]);
}
} else {
- firstItem.legend.translateLocal([
- -bbox.min[0] + firstItem.padding[3],
- 0,
- ]);
+ firstItem.legend.translateLocal([-bbox.min[0] + firstItem.padding[3], 0]);
const firstRight =
- (
- firstItem.legend.childNodes[1].childNodes[0].childNodes[0]
- .childNodes[1] as DisplayObject
- ).getRenderBounds().max[0] + firstItem.padding[1];
+ (firstItem.legend.childNodes[1].childNodes[0].childNodes[0].childNodes[1] as DisplayObject).getRenderBounds()
+ .max[0] + firstItem.padding[1];
secondItem.legend.translateLocal([firstRight, 0]);
}
}
@@ -598,12 +538,8 @@ export class Legend extends Base {
const totalBBox = this.canvas.getRoot().getRenderBounds();
const canvasSize = [
- size[0] === 'fit-content'
- ? totalBBox.max[0] - totalBBox.min[0]
- : size[0],
- size[1] === 'fit-content'
- ? totalBBox.max[1] - totalBBox.min[1]
- : size[1],
+ size[0] === 'fit-content' ? totalBBox.max[0] - totalBBox.min[0] : size[0],
+ size[1] === 'fit-content' ? totalBBox.max[1] - totalBBox.min[1] : size[1],
];
this.canvas.resize(canvasSize[0], canvasSize[1]);
// During server-side rendering, wrapper is not available.
@@ -624,8 +560,7 @@ export class Legend extends Base {
itemType: 'node' | 'edge',
markerShape,
): (item: { typeValue: string }) => { Shape: DisplayObject; style: any } {
- const DefaultShape: typeof Circle | typeof Line =
- itemType === 'node' ? Circle : Line;
+ const DefaultShape: typeof Circle | typeof Line = itemType === 'node' ? Circle : Line;
const defaultStyle =
itemType === 'node'
? { r: 10, width: 20, height: 20, lineWidth: 1 }
@@ -698,11 +633,11 @@ export class Legend extends Base {
/**
* Handles the mouse enter event for a given element.
- * @param {Object} ele - The element (legend item marker) that triggered the event.
- * @param {Array} types - An array of all the types on the legend.
- * @param {string} typeField - The field that contains the type information.
- * @param {string} itemType - The type of item, node or edge.
- * @param {Array} data - An array of data models.
+ * @param ele - The element (legend item marker) that triggered the event.
+ * @param types - An array of all the types on the legend.
+ * @param typeField - The field that contains the type information.
+ * @param itemType - The type of item, node or edge.
+ * @param data - An array of data models.
*/
private handleMouseEnter(ele, types, typeField, itemType, data) {
const { graph, options } = this;
@@ -711,15 +646,12 @@ export class Legend extends Base {
const { index } = ele.__data__;
const type = types[index];
this.activeType[typeField] = type;
- const activeIds = data
- .filter((model) => model.data[typeField] === type)
- .map((model) => model.id);
+ const activeIds = data.filter((model) => model.data[typeField] === type).map((model) => model.id);
graph.setItemState(activeIds, activeState, true);
activeIds.forEach((id) => this.activeIds[itemType].add(id));
// Update legend style.
- ele.querySelector(LEGEND_CATEGORY_ITEM_MARKER).style.lineWidth =
- this.styleCache[itemType][type].lineWidth + 2 || 4;
+ ele.querySelector(LEGEND_CATEGORY_ITEM_MARKER).style.lineWidth = this.styleCache[itemType][type].lineWidth + 2 || 4;
}
/**
@@ -741,8 +673,7 @@ export class Legend extends Base {
ele.querySelector(LEGEND_CATEGORY_ITEM_MARKER).style.lineWidth =
this.styleCache[itemType][type].lineWidth + 4 || 6;
} else {
- ele.querySelector(LEGEND_CATEGORY_ITEM_MARKER).style.lineWidth =
- this.styleCache[itemType][type].lineWidth || 1;
+ ele.querySelector(LEGEND_CATEGORY_ITEM_MARKER).style.lineWidth = this.styleCache[itemType][type].lineWidth || 1;
}
graph.setItemState(currentActiveIds, activeState, false);
currentActiveIds.forEach((id) => this.activeIds[itemType].delete(id));
@@ -762,9 +693,7 @@ export class Legend extends Base {
if (!selectedState) return;
const { index } = ele.__data__;
const type = types[index];
- const ids = data
- .filter((model) => model.data[typeField] === type)
- .map((model) => model.id);
+ const ids = data.filter((model) => model.data[typeField] === type).map((model) => model.id);
if (this.selectedTypes[itemType].has(type)) {
this.selectedTypes[itemType].delete(type);
ids.forEach((id) => this.selectedIds[itemType].delete(id));
diff --git a/packages/g6/src/stdlib/plugin/lodController/index.ts b/packages/g6/src/stdlib/plugin/lodController/index.ts
index d008fba7067..cd6663a68fc 100644
--- a/packages/g6/src/stdlib/plugin/lodController/index.ts
+++ b/packages/g6/src/stdlib/plugin/lodController/index.ts
@@ -1,5 +1,5 @@
-import { debounce, uniqueId, throttle, isArray } from '@antv/util';
import { AABB } from '@antv/g';
+import { debounce, isArray, throttle, uniqueId } from '@antv/util';
import {
ComboDisplayModel,
ComboModel,
@@ -11,9 +11,9 @@ import {
NodeModel,
} from '../../../types';
import { Plugin as Base, IPluginBaseConfig } from '../../../types/plugin';
+import { GraphTransformOptions } from '../../../types/view';
import { intersectBBox } from '../../../util/shape';
import { getZoomLevel } from '../../../util/zoom';
-import { GraphTransformOptions } from '../../../types/view';
/**
* This is an interface named `LodControllerConfig`, which extends the `IPluginBaseConfig` interface. It contains the following properties:
@@ -36,10 +36,7 @@ export class LodController extends Base {
newlyOutView: (NodeModel | EdgeModel | ComboModel)[];
newlyInView: (NodeModel | EdgeModel | ComboModel)[];
};
- private displayModelCache: Map<
- ID,
- NodeDisplayModel | EdgeDisplayModel | ComboDisplayModel
- > = new Map();
+ private displayModelCache: Map = new Map();
private renderBoundsCache: Map = new Map();
private canvasCellDirty: boolean = true;
private canvasCellSize = 100;
@@ -92,9 +89,7 @@ export class LodController extends Base {
const nodes = graph.getAllNodesData();
this.debounce = Math.min(Math.floor(nodes.length / 100), 80);
}
- this.debounceUpdateVisible = this.getDebounceFn(
- this.updateVisible.bind(this),
- );
+ this.debounceUpdateVisible = this.getDebounceFn(this.updateVisible.bind(this));
};
protected onAfterLayout = () => {
@@ -104,7 +99,7 @@ export class LodController extends Base {
};
/**
* Update grid.
- * @param param
+ * @param params
*/
protected updateCells = (params?: GraphTransformOptions) => {
if (!this.graph.canvasReady) return;
@@ -122,8 +117,7 @@ export class LodController extends Base {
private updateVisible = (zoomRatio = 1) => {
const { graph, cacheViewModels, options } = this;
- const { cellSize, numberPerCell, disableAnimate, disableLod } =
- options || {};
+ const { cellSize, numberPerCell, disableAnimate, disableLod } = options || {};
const graphZoom = graph.getZoom();
const { inView } = cacheViewModels || this.groupItemsByView(1);
@@ -142,21 +136,14 @@ export class LodController extends Base {
const displayModel = this.getDisplayModel(model.id);
const { lodLevels, x, y, z, ...others } = displayModel.data;
const lodLevelsEmpty = isEmptyObj(lodLevels);
- const currentZoomLevel = lodLevelsEmpty
- ? 0
- : getZoomLevel(lodLevels as any, graphZoom);
+ const currentZoomLevel = lodLevelsEmpty ? 0 : getZoomLevel(lodLevels as any, graphZoom);
const autoVisibleShapeIds = [];
const lodVisibleShapeIds = [];
const invisibleShapeIds = [];
Object.keys(others).forEach((shapeId) => {
if (shapeId === 'keyShape') return;
const val = others[shapeId] as any;
- if (
- !val ||
- typeof val !== 'object' ||
- !Object.keys(val).length ||
- isArray(val)
- ) {
+ if (!val || typeof val !== 'object' || !Object.keys(val).length || isArray(val)) {
return;
}
const { lod, visible } = val;
@@ -204,10 +191,8 @@ export class LodController extends Base {
cells.forEach((cell) => {
// priority: lod Visible > shown last time > rest auto
cell.sort((a, b) => {
- const { lodVisibleShapeIds: aLodVisibleShapeIds } =
- candidateShapeMap.get(a);
- const { lodVisibleShapeIds: bLodVisibleShapeIds } =
- candidateShapeMap.get(b);
+ const { lodVisibleShapeIds: aLodVisibleShapeIds } = candidateShapeMap.get(a);
+ const { lodVisibleShapeIds: bLodVisibleShapeIds } = candidateShapeMap.get(b);
if (lodVisibleIds.includes(b) && bLodVisibleShapeIds.length) return 1;
if (lodVisibleIds.includes(a) && aLodVisibleShapeIds.length) return -1;
const bShownLastTime = this.shownIds.has(b) && !lodInvisibleIds.has(b);
@@ -218,8 +203,7 @@ export class LodController extends Base {
});
let rest = numberPerCell;
cell.forEach((id) => {
- const { lodVisibleShapeIds, autoVisibleShapeIds, invisibleShapeIds } =
- candidateShapeMap.get(id);
+ const { lodVisibleShapeIds, autoVisibleShapeIds, invisibleShapeIds } = candidateShapeMap.get(id);
if (!disableLod && invisibleShapeIds.length) {
graph.hideItem(id, { shapeIds: invisibleShapeIds, disableAnimate });
@@ -227,8 +211,7 @@ export class LodController extends Base {
const item = graph.itemController.itemMap.get(id);
if (
disableLod ||
- (item.labelGroup.children.length &&
- (rest > 0 || (zoomRatio >= 1 && this.shownIds.has(id))))
+ (item.labelGroup.children.length && (rest > 0 || (zoomRatio >= 1 && this.shownIds.has(id))))
) {
const shapeIdsToShow = lodVisibleShapeIds.concat(autoVisibleShapeIds);
if (shapeIdsToShow.length) {
@@ -244,10 +227,7 @@ export class LodController extends Base {
shownIds.set(id, 1);
rest--;
} else {
- if (
- lodVisibleShapeIds.includes('labelShape') &&
- this.labelPositionDirty.has(id)
- ) {
+ if (lodVisibleShapeIds.includes('labelShape') && this.labelPositionDirty.has(id)) {
item.updateLabelPosition(disableLod);
this.labelPositionDirty.delete(id);
}
@@ -273,15 +253,12 @@ export class LodController extends Base {
this.shownIds = shownIds;
};
- private debounceUpdateVisible = this.getDebounceFn(
- this.updateVisible.bind(this),
- );
+ private debounceUpdateVisible = this.getDebounceFn(this.updateVisible.bind(this));
private updateLabelPositions = throttle(
(zoomRatio) => {
const { graph, options } = this;
- const { inView, newlyOutView, newlyInView } =
- this.groupItemsByView(zoomRatio);
+ const { inView, newlyOutView, newlyInView } = this.groupItemsByView(zoomRatio);
const graphZoom = graph.getZoom();
const levelCache = {};
this.labelPositionDirty.clear();
@@ -298,8 +275,7 @@ export class LodController extends Base {
!item.labelGroup.children.length ||
!item.shapeMap.labelShape ||
(!options?.disableLod &&
- (item.labelGroup.style.visibility === 'hidden' ||
- item.shapeMap.labelShape.style.visibility === 'hidden'))
+ (item.labelGroup.style.visibility === 'hidden' || item.shapeMap.labelShape.style.visibility === 'hidden'))
) {
return;
}
@@ -333,9 +309,7 @@ export class LodController extends Base {
}
const levelsKey = JSON.stringify(lodLevels);
const currentZoomLevel =
- levelCache[levelsKey] || lodLevelsEmpty
- ? 0
- : getZoomLevel(lodLevels as any, graphZoom);
+ levelCache[levelsKey] || lodLevelsEmpty ? 0 : getZoomLevel(lodLevels as any, graphZoom);
levelCache[levelsKey] = currentZoomLevel;
if (lod <= currentZoomLevel) {
// lod visible
@@ -366,6 +340,7 @@ export class LodController extends Base {
/**
* get the items inside viewport
+ * @param ratio
* @returns
*/
private groupItemsByView = (ratio: number = 1) => {
@@ -386,15 +361,13 @@ export class LodController extends Base {
if (
rowIdx > canvasCellRowRange[0] &&
rowIdx < canvasCellRowRange[1] &&
- (Math.abs(colIdx - canvasCellColRange[0]) < 2 ||
- Math.abs(colIdx - canvasCellColRange[1]) < 2)
+ (Math.abs(colIdx - canvasCellColRange[0]) < 2 || Math.abs(colIdx - canvasCellColRange[1]) < 2)
) {
return true;
} else if (
colIdx > canvasCellColRange[0] &&
colIdx < canvasCellColRange[1] &&
- (Math.abs(rowIdx - canvasCellRowRange[0]) < 2 ||
- Math.abs(rowIdx - canvasCellRowRange[1]) < 2)
+ (Math.abs(rowIdx - canvasCellRowRange[0]) < 2 || Math.abs(rowIdx - canvasCellRowRange[1]) < 2)
) {
return true;
}
@@ -410,8 +383,7 @@ export class LodController extends Base {
};
const newlyOutView = [];
const newlyInView = [];
- const cacheIsEmpty =
- !this.cacheViewModels || (!inView.length && !outView.length);
+ const cacheIsEmpty = !this.cacheViewModels || (!inView.length && !outView.length);
if (!ratio || ratio === 1 || cacheIsEmpty) {
const previousOutView = new Map();
const previousInView = new Map();
@@ -551,7 +523,7 @@ export class LodController extends Base {
protected beforeViewportAnimation = () => {
if (this.animationUpdateTimer) return;
- this.animationUpdateTimer = setInterval(() => {
+ this.animationUpdateTimer = window.setInterval(() => {
this.updateLabelPositions();
}, 16);
};
diff --git a/packages/g6/src/stdlib/plugin/menu/index.ts b/packages/g6/src/stdlib/plugin/menu/index.ts
index 7c46b938127..a1456373987 100644
--- a/packages/g6/src/stdlib/plugin/menu/index.ts
+++ b/packages/g6/src/stdlib/plugin/menu/index.ts
@@ -1,10 +1,10 @@
import { isString, uniqueId } from '@antv/util';
import insertCss from 'insert-css';
import Item from '../../../item/item';
-import { createDOM, modifyCSS } from '../../../util/dom';
import { IGraph } from '../../../types';
import { IG6GraphEvent } from '../../../types/event';
import { Plugin as Base, IPluginBaseConfig } from '../../../types/plugin';
+import { createDOM, modifyCSS } from '../../../util/dom';
typeof document !== 'undefined' &&
insertCss(`
@@ -37,24 +37,21 @@ typeof document !== 'undefined' &&
`);
/**
* The `MenuConfig` interface contains the following properties:
-
-- `handleMenuClick`: An optional function for handling menu click events. It takes two arguments: `target` (of type HTMLElement) and `item` (of type Item), and has no return value.
-- `getContent`: An optional function for getting the content of the menu. It takes an optional argument of type `IG6GraphEvent`, and returns a value of type HTMLElement, string, or Promise (resolving to HTMLElement or string).
-- `offsetX`: An optional number representing the offset of the menu in the X direction.
-- `offsetY`: An optional number representing the offset of the menu in the Y direction.
-- `shouldBegin`: An optional function for determining whether the menu should be displayed. It takes an optional argument of type `IG6GraphEvent`, and returns a boolean value.
-- `itemTypes`: An optional array of strings representing the types of items for which the menu is allowed to be displayed.
-- `trigger`: An optional string, either 'click' or 'contextmenu', representing the event type that triggers the display of the menu.
-- `onHide`: An optional function to be executed when the menu is hidden. It takes no arguments and returns a boolean value.
-- `loadingContent`: An optional HTMLElement or string representing the loading DOM.
-- `liHoverStyle`: An optional object representing the style of li elements when hovered over. It can contain any number of key-value pairs, where the key is a style name and the value is a string.
+ * - `handleMenuClick`: An optional function for handling menu click events. It takes two arguments: `target` (of type HTMLElement) and `item` (of type Item), and has no return value.
+ * - `getContent`: An optional function for getting the content of the menu. It takes an optional argument of type `IG6GraphEvent`, and returns a value of type HTMLElement, string, or Promise (resolving to HTMLElement or string).
+ * - `offsetX`: An optional number representing the offset of the menu in the X direction.
+ * - `offsetY`: An optional number representing the offset of the menu in the Y direction.
+ * - `shouldBegin`: An optional function for determining whether the menu should be displayed. It takes an optional argument of type `IG6GraphEvent`, and returns a boolean value.
+ * - `itemTypes`: An optional array of strings representing the types of items for which the menu is allowed to be displayed.
+ * - `trigger`: An optional string, either 'click' or 'contextmenu', representing the event type that triggers the display of the menu.
+ * - `onHide`: An optional function to be executed when the menu is hidden. It takes no arguments and returns a boolean value.
+ * - `loadingContent`: An optional HTMLElement or string representing the loading DOM.
+ * - `liHoverStyle`: An optional object representing the style of li elements when hovered over. It can contain any number of key-value pairs, where the key is a style name and the value is a string.
*/
export interface MenuConfig extends IPluginBaseConfig {
handleMenuClick?: (target: HTMLElement, item: Item) => void;
// return the content of menu, support the `Promise` type return value.
- getContent?: (
- evt?: IG6GraphEvent,
- ) => HTMLElement | string | Promise;
+ getContent?: (evt?: IG6GraphEvent) => HTMLElement | string | Promise;
offsetX?: number;
offsetY?: number;
shouldBegin?: (evt?: IG6GraphEvent) => boolean;
@@ -126,9 +123,7 @@ export class Menu extends Base {
.join('')}
}
`);
- const menu = createDOM(
- ``,
- );
+ const menu = createDOM(``);
modifyCSS(menu, { top: '0px', position: 'absolute', visibility: 'hidden' });
let container: HTMLElement | null | string = this.options.container;
if (!container) {
@@ -144,16 +139,16 @@ export class Menu extends Base {
protected async onMenuShow(e: IG6GraphEvent) {
const self = this;
e.preventDefault?.();
- self.onMenuHide();
+ this.onMenuHide();
const itemTypes = this.options.itemTypes;
if (!e.itemId) {
if (itemTypes.indexOf('canvas') === -1) {
- self.onMenuHide();
+ this.onMenuHide();
return;
}
} else {
if (e.itemId && e.itemType && itemTypes.indexOf(e.itemType) === -1) {
- self.onMenuHide();
+ this.onMenuHide();
return;
}
}
diff --git a/packages/g6/src/stdlib/plugin/minimap/index.ts b/packages/g6/src/stdlib/plugin/minimap/index.ts
index 0f7f1ebf36c..6b808c379b6 100644
--- a/packages/g6/src/stdlib/plugin/minimap/index.ts
+++ b/packages/g6/src/stdlib/plugin/minimap/index.ts
@@ -149,8 +149,7 @@ export class Minimap extends Base {
if ((e as any).dataTransfer) {
const img = new Image();
- img.src =
- "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' %3E%3Cpath /%3E%3C/svg%3E";
+ img.src = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' %3E%3Cpath /%3E%3C/svg%3E";
(e as any).dataTransfer.setDragImage?.(img, 0, 0);
try {
(e as any).dataTransfer.setData('text/html', 'view-port-minimap');
@@ -248,11 +247,7 @@ export class Minimap extends Base {
containerDOM.addEventListener('mouseup', dragendListener.bind(this));
if (isSafari || isFireFox) {
- containerDOM.addEventListener(
- 'mousemove',
- dragListener.bind(this),
- false,
- );
+ containerDOM.addEventListener('mousemove', dragListener.bind(this), false);
}
this.viewport = viewport;
@@ -271,10 +266,8 @@ export class Minimap extends Base {
const { size } = options;
const graphCanvasEl = graph.canvas.context.config.canvas;
- const [
- graphWidth = graphCanvasEl?.scrollWidth || 500,
- graphHeight = graphCanvasEl?.scrollHeight || 500,
- ] = graph.getSize();
+ const [graphWidth = graphCanvasEl?.scrollWidth || 500, graphHeight = graphCanvasEl?.scrollHeight || 500] =
+ graph.getSize();
const graphZoom = graph.getZoom();
const graphBBox = graph.canvas.getRoot().getRenderBounds();
@@ -396,9 +389,7 @@ export class Minimap extends Base {
*/
private updateOneNodeKeyShape(nodeModel, group) {
const { itemMap = new Map(), graph } = this;
- const graphNodeGroup = graph.canvas
- .getRoot()
- .find((ele) => ele.id === 'node-group');
+ const graphNodeGroup = graph.canvas.getRoot().find((ele) => ele.id === 'node-group');
if (!graphNodeGroup) return;
let { minimapItem, graphItem } = itemMap.get(nodeModel.id) || {};
@@ -494,9 +485,7 @@ export class Minimap extends Base {
*/
private updateOneEdgeKeyShape(edgeModel, group) {
const { itemMap = new Map(), graph } = this;
- const graphEdgeGroup = graph.canvas
- .getRoot()
- .find((ele) => ele.id === 'edge-group');
+ const graphEdgeGroup = graph.canvas.getRoot().find((ele) => ele.id === 'edge-group');
if (!graphEdgeGroup) return;
let { minimapItem, graphItem } = itemMap.get(edgeModel.id) || {};
if (minimapItem && !minimapItem.destroyed) {
@@ -529,9 +518,7 @@ export class Minimap extends Base {
const { itemMap = new Map(), options, graph } = this;
const { delegateStyle } = options;
- const graphNodeGroup = graph.canvas
- .getRoot()
- .find((ele) => ele.id === 'node-group');
+ const graphNodeGroup = graph.canvas.getRoot().find((ele) => ele.id === 'node-group');
if (!graphNodeGroup) return;
// 差量更新 minimap 上的一个节点,对应主图的 item
@@ -561,9 +548,7 @@ export class Minimap extends Base {
});
group.appendChild(minimapItem);
} else {
- Object.keys(attrs).forEach(
- (key) => (minimapItem.style[key] = attrs[key]),
- );
+ Object.keys(attrs).forEach((key) => (minimapItem.style[key] = attrs[key]));
}
minimapItem.toFront();
@@ -577,7 +562,7 @@ export class Minimap extends Base {
* Listener for main graph updating, update the viewport DOM.
*/
private handleUpdateCanvas = debounce(
- (event) => {
+ () => {
const self = this;
if (self.destroyed) return;
self.updateCanvas();
@@ -598,18 +583,16 @@ export class Minimap extends Base {
() => {
const nodeGroup = this.canvas.getRoot().getElementById('node-group');
const edgeGroup = this.canvas.getRoot().getElementById('edge-group');
- (nodeGroup?.childNodes || [])
- .concat(edgeGroup?.childNodes || [])
- .forEach((child) => {
- const id = child.getAttribute?.('data-item-id');
- if (this.visibleCache.hasOwnProperty(id)) {
- if (this.visibleCache[id]) {
- child.childNodes.forEach((shape) => shape.show());
- } else if (this.visibleCache[id] === false) {
- child.childNodes.forEach((shape) => shape.hide());
- }
+ (nodeGroup?.childNodes || []).concat(edgeGroup?.childNodes || []).forEach((child) => {
+ const id = child.getAttribute?.('data-item-id');
+ if (id in this.visibleCache) {
+ if (this.visibleCache[id]) {
+ child.childNodes.forEach((shape) => shape.show());
+ } else if (this.visibleCache[id] === false) {
+ child.childNodes.forEach((shape) => shape.hide());
}
- });
+ }
+ });
this.visibleCache = {};
},
50,
@@ -651,9 +634,7 @@ export class Minimap extends Base {
}
this.container = container;
- const containerDOM = createDOM(
- '',
- );
+ const containerDOM = createDOM('');
container.appendChild(containerDOM);
containerDOM.addEventListener('dragenter', (e) => {
e.preventDefault();
@@ -664,13 +645,7 @@ export class Minimap extends Base {
// TODO: graph.rendererType
const graphCanvas = graph.canvas;
- this.canvas = createCanvas(
- 'canvas',
- containerDOM,
- size[0],
- size[1],
- graphCanvas.devicePixelRatio,
- );
+ this.canvas = createCanvas('canvas', containerDOM, size[0], size[1], graphCanvas.devicePixelRatio);
return this.canvas.ready;
}
@@ -705,20 +680,13 @@ export class Minimap extends Base {
const height = graphBBox.max[1] - graphBBox.min[1];
// Scale the graph to fit the size - padding of the minimap container
- const zoomRatio = Math.min(
- (size[0] - 2 * padding) / width,
- (size[1] - 2 * padding) / height,
- );
+ const zoomRatio = Math.min((size[0] - 2 * padding) / width, (size[1] - 2 * padding) / height);
const zoomCenter = canvas.viewport2Canvas({ x: 0, y: 0 });
canvas.getCamera().setFocalPoint(zoomCenter.x, zoomCenter.y);
canvas.getCamera().setPosition(zoomCenter.x, zoomCenter.y);
canvas.getCamera().setZoom(zoomRatio);
- canvas
- .getCamera()
- .setPosition(minimapBBox.center[0], minimapBBox.center[1]);
- canvas
- .getCamera()
- .setFocalPoint(minimapBBox.center[0], minimapBBox.center[1]);
+ canvas.getCamera().setPosition(minimapBBox.center[0], minimapBBox.center[1]);
+ canvas.getCamera().setFocalPoint(minimapBBox.center[0], minimapBBox.center[1]);
const { x: dx, y: dy } = canvas.canvas2Viewport({
x: minimapBBox.min[0],
@@ -734,7 +702,7 @@ export class Minimap extends Base {
/**
* Get the canvas of the minimap.
- * @return {Canvas} G Canvas
+ * @returns {Canvas} G Canvas
*/
public getCanvas(): Canvas {
return this.canvas;
@@ -742,7 +710,7 @@ export class Minimap extends Base {
/**
* Get the viewport DOM of the minimap.
- * @return {HTMLElement} viewport DOM
+ * @returns {HTMLElement} viewport DOM
*/
public getViewport(): HTMLElement {
return this.viewport;
@@ -750,7 +718,7 @@ export class Minimap extends Base {
/**
* Get the container DOM of the minimap.
- * @return {HTMLElement} container DOM
+ * @returns {HTMLElement} container DOM
*/
public getContainer(): HTMLElement {
return this.container;
@@ -769,20 +737,11 @@ const getMoveAtBorder = (dom, evt) => {
const { clientX, clientY } = evt;
if (Math.abs(clientX - bounds.x) < 4 && Math.abs(clientY - bounds.y) < 4) {
return 'left-top';
- } else if (
- Math.abs(clientX - bounds.x) < 4 &&
- Math.abs(clientY - bounds.y - bounds.height) < 4
- ) {
+ } else if (Math.abs(clientX - bounds.x) < 4 && Math.abs(clientY - bounds.y - bounds.height) < 4) {
return 'left-bottom';
- } else if (
- Math.abs(clientX - bounds.x - bounds.width) < 4 &&
- Math.abs(clientY - bounds.y) < 4
- ) {
+ } else if (Math.abs(clientX - bounds.x - bounds.width) < 4 && Math.abs(clientY - bounds.y) < 4) {
return 'right-top';
- } else if (
- Math.abs(clientX - bounds.x - bounds.width) < 4 &&
- Math.abs(clientY - bounds.y - bounds.height) < 4
- ) {
+ } else if (Math.abs(clientX - bounds.x - bounds.width) < 4 && Math.abs(clientY - bounds.y - bounds.height) < 4) {
return 'right-bottom';
} else if (Math.abs(clientX - bounds.x) < 4) {
return 'left';
diff --git a/packages/g6/src/stdlib/plugin/snapline/index.ts b/packages/g6/src/stdlib/plugin/snapline/index.ts
index 1ff75ea9de6..d6875ea80ca 100644
--- a/packages/g6/src/stdlib/plugin/snapline/index.ts
+++ b/packages/g6/src/stdlib/plugin/snapline/index.ts
@@ -1,10 +1,10 @@
-import { ID } from '@antv/graphlib';
import { AABB, DisplayObject } from '@antv/g';
+import { ID } from '@antv/graphlib';
import { throttle } from '@antv/util';
-import { ITEM_TYPE, ShapeStyle } from '../../../types/item';
import { IG6GraphEvent, IGraph, NodeModel } from '../../../types';
-import { Plugin as Base, IPluginBaseConfig } from '../../../types/plugin';
import { Point } from '../../../types/common';
+import { ITEM_TYPE, ShapeStyle } from '../../../types/item';
+import { Plugin as Base, IPluginBaseConfig } from '../../../types/plugin';
export interface SnapLineConfig extends IPluginBaseConfig {
// snapline type
@@ -33,18 +33,12 @@ type DrawLineForChoose = { dl: DrawLine; offset: Point };
export class Snapline extends Base {
//#region state: historyPoints
- private historyPoints: [Point | undefined, Point | undefined] = [
- undefined,
- undefined,
- ];
+ private historyPoints: [Point | undefined, Point | undefined] = [undefined, undefined];
/**
* when start drag, offset of cursor and node center (event.canvas - draggingnode.BBox)
*/
- private initialOffset: [
- offsetX: number | undefined,
- offsetY: number | undefined,
- ] = [undefined, undefined];
+ private initialOffset: [offsetX: number | undefined, offsetY: number | undefined] = [undefined, undefined];
/**
* Cache the nodes' positions to be throttle updated.
@@ -53,14 +47,10 @@ export class Snapline extends Base {
/**
* Gets the current cursor node and center offset and then with initialOffset difference
+ * @param e
*/
- private getCurOffsetCompareToInitialOffset = (
- e: IG6GraphEvent,
- ): [number | undefined, number | undefined] => {
- if (
- this.initialOffset[0] === undefined ||
- this.initialOffset[1] === undefined
- ) {
+ private getCurOffsetCompareToInitialOffset = (e: IG6GraphEvent): [number | undefined, number | undefined] => {
+ if (this.initialOffset[0] === undefined || this.initialOffset[1] === undefined) {
return [undefined, undefined];
}
@@ -69,20 +59,14 @@ export class Snapline extends Base {
e.canvas.y - this.draggingBBox.center[1],
];
- return [
- curOffset[0] - this.initialOffset[0],
- curOffset[1] - this.initialOffset[1],
- ];
+ return [curOffset[0] - this.initialOffset[0], curOffset[1] - this.initialOffset[1]];
};
private dragging = false;
private draggingBBox: AABB = undefined;
// Gets the offset between the cursor and draggingItem
- private getPointerOffsetWithItem = (pointer: {
- x: number;
- y: number;
- }): { x: number; y: number } => {
+ private getPointerOffsetWithItem = (pointer: { x: number; y: number }): { x: number; y: number } => {
return {
x: Math.abs(pointer.x - this.draggingBBox.center[0]),
y: Math.abs(pointer.x - this.draggingBBox.center[1]),
@@ -122,9 +106,10 @@ export class Snapline extends Base {
return `${dl.line[0].x}-${dl.line[0].y}-${dl.line[1].x}-${dl.line[1].y}`;
}
/**
- *
* @param cp based on constractBBox's point
* @param dp based on draggingBBox point
+ * @param cp."0"
+ * @param cp."1"
* @returns
*/
getDrawLineIdByPoints([cp, dp]: [Point, Point]): ID {
@@ -135,18 +120,18 @@ export class Snapline extends Base {
* all AlignLines satisfy conditions: in the tolerance range
*/
addAlignLinesForChoose() {
- function isInToleranceRange(
- xOrY: number,
- contrast: number,
- tolerance: number,
- ): boolean {
+ /**
+ *
+ * @param xOrY
+ * @param contrast
+ * @param tolerance
+ */
+ function isInToleranceRange(xOrY: number, contrast: number, tolerance: number): boolean {
return xOrY >= contrast - tolerance && xOrY <= contrast + tolerance;
}
this.vContrastPoints.forEach((vpoint) => {
- if (
- isInToleranceRange(this.draggingBBox.min[0], vpoint.x, this.tolerance)
- )
+ if (isInToleranceRange(this.draggingBBox.min[0], vpoint.x, this.tolerance))
this.alignLinesForChoose.v.push({
dl: {
line: [vpoint, { x: vpoint.x, y: this.draggingBBox.center[1] }],
@@ -154,13 +139,7 @@ export class Snapline extends Base {
},
offset: { x: vpoint.x - this.draggingBBox.min[0], y: 0 },
});
- if (
- isInToleranceRange(
- this.draggingBBox.center[0],
- vpoint.x,
- this.tolerance,
- )
- )
+ if (isInToleranceRange(this.draggingBBox.center[0], vpoint.x, this.tolerance))
this.alignLinesForChoose.v.push({
dl: {
line: [vpoint, { x: vpoint.x, y: this.draggingBBox.center[1] }],
@@ -168,9 +147,7 @@ export class Snapline extends Base {
},
offset: { x: vpoint.x - this.draggingBBox.center[0], y: 0 },
});
- if (
- isInToleranceRange(this.draggingBBox.max[0], vpoint.x, this.tolerance)
- )
+ if (isInToleranceRange(this.draggingBBox.max[0], vpoint.x, this.tolerance))
this.alignLinesForChoose.v.push({
dl: {
line: [vpoint, { x: vpoint.x, y: this.draggingBBox.center[1] }],
@@ -181,9 +158,7 @@ export class Snapline extends Base {
});
this.hContrastPoints.forEach((hpoint) => {
- if (
- isInToleranceRange(this.draggingBBox.min[1], hpoint.y, this.tolerance)
- )
+ if (isInToleranceRange(this.draggingBBox.min[1], hpoint.y, this.tolerance))
this.alignLinesForChoose.v.push({
dl: {
line: [hpoint, { x: this.draggingBBox.min[0], y: hpoint.y }],
@@ -191,13 +166,7 @@ export class Snapline extends Base {
},
offset: { x: 0, y: hpoint.y - this.draggingBBox.min[1] },
});
- if (
- isInToleranceRange(
- this.draggingBBox.center[1],
- hpoint.y,
- this.tolerance,
- )
- )
+ if (isInToleranceRange(this.draggingBBox.center[1], hpoint.y, this.tolerance))
this.alignLinesForChoose.v.push({
dl: {
line: [hpoint, { x: this.draggingBBox.center[0], y: hpoint.y }],
@@ -205,9 +174,7 @@ export class Snapline extends Base {
},
offset: { x: 0, y: hpoint.y - this.draggingBBox.center[1] },
});
- if (
- isInToleranceRange(this.draggingBBox.max[1], hpoint.y, this.tolerance)
- )
+ if (isInToleranceRange(this.draggingBBox.max[1], hpoint.y, this.tolerance))
this.alignLinesForChoose.v.push({
dl: {
line: [hpoint, { x: this.draggingBBox.max[0], y: hpoint.y }],
@@ -299,9 +266,7 @@ export class Snapline extends Base {
},
});
}
- if (
- Math.abs(this.draggingBBox.center[0] - cb.center[0]) <= this.tolerance
- ) {
+ if (Math.abs(this.draggingBBox.center[0] - cb.center[0]) <= this.tolerance) {
this.alignLinesForChoose.v.push({
dl: {
line: [
@@ -442,9 +407,7 @@ export class Snapline extends Base {
},
});
}
- if (
- Math.abs(this.draggingBBox.center[1] - cb.center[1]) <= this.tolerance
- ) {
+ if (Math.abs(this.draggingBBox.center[1] - cb.center[1]) <= this.tolerance) {
this.alignLinesForChoose.h.push({
dl: {
line: [
@@ -534,10 +497,7 @@ export class Snapline extends Base {
// v direction line selection rule: draggingBBox's left/vcenter/right compares to vContrastPoints
// h direction line selection rule: draggingBBox's top/hcenter/bottom compares to hContrastPoints
- if (
- this.alignLinesForChoose.v.length + this.alignLinesForChoose.h.length ===
- 0
- ) {
+ if (this.alignLinesForChoose.v.length + this.alignLinesForChoose.h.length === 0) {
return { v: undefined, h: undefined };
}
@@ -545,25 +505,15 @@ export class Snapline extends Base {
let hTmpLines: DrawLineForChoose[] = [];
// 1.v,h direction: select the line with minimum offset
- const vMinOffset = Math.min(
- ...this.alignLinesForChoose.v.map((dlFc) => dlFc.offset.x),
- );
- const hMinOffset = Math.min(
- ...this.alignLinesForChoose.h.map((dlFc) => dlFc.offset.y),
- );
+ const vMinOffset = Math.min(...this.alignLinesForChoose.v.map((dlFc) => dlFc.offset.x));
+ const hMinOffset = Math.min(...this.alignLinesForChoose.h.map((dlFc) => dlFc.offset.y));
- vTmpLines = this.alignLinesForChoose.v.filter(
- (dlFc) => dlFc.offset.x === vMinOffset,
- );
- hTmpLines = this.alignLinesForChoose.h.filter(
- (dlFc) => dlFc.offset.y === hMinOffset,
- );
+ vTmpLines = this.alignLinesForChoose.v.filter((dlFc) => dlFc.offset.x === vMinOffset);
+ hTmpLines = this.alignLinesForChoose.h.filter((dlFc) => dlFc.offset.y === hMinOffset);
// 2.same tolerance,hcenter > top > bottom; vcenter > left > right. (The principle of selecting only one direction)
{
- const vcenter_hasdata = vTmpLines.some(
- (dlFc) => dlFc.dl.lp === 'vcenter',
- );
+ const vcenter_hasdata = vTmpLines.some((dlFc) => dlFc.dl.lp === 'vcenter');
const left_hasdata = vTmpLines.some((dlFc) => dlFc.dl.lp === 'left');
vTmpLines = vTmpLines.filter((dlFc) => {
@@ -588,9 +538,7 @@ export class Snapline extends Base {
return false;
});
- const hcenter_hasdata = hTmpLines.some(
- (dlFc) => dlFc.dl.lp === 'hcenter',
- );
+ const hcenter_hasdata = hTmpLines.some((dlFc) => dlFc.dl.lp === 'hcenter');
const top_hasdata = hTmpLines.some((dlFc) => dlFc.dl.lp === 'top');
hTmpLines = hTmpLines.filter((dlFc) => {
@@ -620,10 +568,7 @@ export class Snapline extends Base {
const uniVTmpLines = Array.from(
vTmpLines
.reduce((map, item) => {
- if (
- !map.has(item.dl.lp) ||
- Math.abs(item.offset.x) < Math.abs(map.get(item.dl.lp)?.offset.x)
- ) {
+ if (!map.has(item.dl.lp) || Math.abs(item.offset.x) < Math.abs(map.get(item.dl.lp)?.offset.x)) {
map.set(item.dl.lp, item);
}
return map;
@@ -634,10 +579,7 @@ export class Snapline extends Base {
const uniHTmpLines = Array.from(
hTmpLines
.reduce((map, item) => {
- if (
- !map.has(item.dl.lp) ||
- Math.abs(item.offset.y) < Math.abs(map.get(item.dl.lp)?.offset.y)
- ) {
+ if (!map.has(item.dl.lp) || Math.abs(item.offset.y) < Math.abs(map.get(item.dl.lp)?.offset.y)) {
map.set(item.dl.lp, item);
}
return map;
@@ -647,27 +589,23 @@ export class Snapline extends Base {
// 4.choose a maximum offset one of DrawLineForChoose
const vMaxDL = uniVTmpLines.length
- ? uniVTmpLines.reduce(
- (maxItem: DrawLineForChoose, curItem: DrawLineForChoose) => {
- if (curItem.offset.x > maxItem.offset.x) {
- return curItem;
- } else {
- return maxItem;
- }
- },
- )
+ ? uniVTmpLines.reduce((maxItem: DrawLineForChoose, curItem: DrawLineForChoose) => {
+ if (curItem.offset.x > maxItem.offset.x) {
+ return curItem;
+ } else {
+ return maxItem;
+ }
+ })
: undefined;
const hMaxDL = uniHTmpLines.length
- ? uniHTmpLines.reduce(
- (maxItem: DrawLineForChoose, curItem: DrawLineForChoose) => {
- if (curItem.offset.y > maxItem.offset.y) {
- return curItem;
- } else {
- return maxItem;
- }
- },
- )
+ ? uniHTmpLines.reduce((maxItem: DrawLineForChoose, curItem: DrawLineForChoose) => {
+ if (curItem.offset.y > maxItem.offset.y) {
+ return curItem;
+ } else {
+ return maxItem;
+ }
+ })
: undefined;
return {
@@ -694,10 +632,10 @@ export class Snapline extends Base {
*
* When the cursor moves out of this region && non-adsorbed state => set to undefined
*/
- private historyAbsorbArea: [
- [x0: number, x1: number] | undefined,
- [y0: number, y1: number] | undefined,
- ] = [undefined, undefined];
+ private historyAbsorbArea: [[x0: number, x1: number] | undefined, [y0: number, y1: number] | undefined] = [
+ undefined,
+ undefined,
+ ];
/**
* Unable to adsorb: countdown
@@ -774,10 +712,7 @@ export class Snapline extends Base {
//#region event handler
onDragStart(event: IG6GraphEvent) {
this.draggingBBox = this.graph.getRenderBBox(event.itemId, true) as AABB;
- this.initialOffset = [
- event.canvas.x - this.draggingBBox.center[0],
- event.canvas.y - this.draggingBBox.center[1],
- ];
+ this.initialOffset = [event.canvas.x - this.draggingBBox.center[0], event.canvas.y - this.draggingBBox.center[1]];
}
onDrag = throttle(
@@ -801,8 +736,7 @@ export class Snapline extends Base {
const checkVShouldHoldAbsorb = (vlp, vline) => {
// v direction: continue to adsorb
const vShouldAbsorb =
- Math.abs(this.getCurOffsetCompareToInitialOffset(event)[0]) <=
- this.tolerance * this.toleranceFactor;
+ Math.abs(this.getCurOffsetCompareToInitialOffset(event)[0]) <= this.tolerance * this.toleranceFactor;
if (vShouldAbsorb) {
if (vlp === 'left') {
@@ -837,8 +771,7 @@ export class Snapline extends Base {
const checkHShouldHoldAbsorb = (hlp, hline) => {
// h direction: continue to adsorb
const hShouldAbsorb =
- Math.abs(this.getCurOffsetCompareToInitialOffset(event)[1]) <=
- this.tolerance * this.toleranceFactor;
+ Math.abs(this.getCurOffsetCompareToInitialOffset(event)[1]) <= this.tolerance * this.toleranceFactor;
if (hShouldAbsorb) {
if (hlp === 'top') {
@@ -870,8 +803,7 @@ export class Snapline extends Base {
};
// v direction: whether adsorbed
const checkVShouldAbsorb = () => {
- const ret: { vdl: DrawLine; hdl: DrawLine } | false =
- this.canDrawLine();
+ const ret: { vdl: DrawLine; hdl: DrawLine } | false = this.canDrawLine();
// If in recent from adsorption area, can't immediately draw lines (must be removed from the area to reline this area)
if (ret) {
@@ -883,8 +815,7 @@ export class Snapline extends Base {
};
// h direction: whether adsorbed
const checkHShouldAbsorb = () => {
- const ret: { vdl: DrawLine; hdl: DrawLine } | false =
- this.canDrawLine();
+ const ret: { vdl: DrawLine; hdl: DrawLine } | false = this.canDrawLine();
// If in recent from adsorption area, can't immediately draw lines (must be removed from the area to reline this area)
if (ret) {
@@ -920,8 +851,7 @@ export class Snapline extends Base {
checkVShouldAbsorb();
} else if (!this.isAdsorbed[0] && !this.isAdsorbed[1]) {
// 4、currently, v and h directions are not adsorbed
- const ret: { vdl: DrawLine; hdl: DrawLine } | false =
- this.canDrawLine();
+ const ret: { vdl: DrawLine; hdl: DrawLine } | false = this.canDrawLine();
// If you have recently detached from the attachment area, you cannot draw the line immediately (you need to remove the detached area to redraw the area)
if (ret) {
@@ -955,13 +885,7 @@ export class Snapline extends Base {
{ do: DisplayObject | undefined; dl: DrawLine | undefined } | undefined,
] = [undefined, undefined];
- drawAlignLines({
- vdl,
- hdl,
- }: {
- vdl: DrawLine | undefined;
- hdl: DrawLine | undefined;
- }) {
+ drawAlignLines({ vdl, hdl }: { vdl: DrawLine | undefined; hdl: DrawLine | undefined }) {
// 1.draw align line
const vLineID: ID = vdl ? this.getDrawLineIdByDrawLine(vdl) : undefined;
const hLineID: ID = hdl ? this.getDrawLineIdByDrawLine(hdl) : undefined;
@@ -1001,13 +925,12 @@ export class Snapline extends Base {
/**
* remove align line
- * @param rvdl: remove vertical drawed line
- * @param rhdl: remove horizon drawed line
+ * @param rvdl - remove vertical drawed line
+ * @param rhdl - remove horizon drawed line
+ * @param rvdl."0"
+ * @param rvdl."1"
*/
- removeAlignLine([rvdl, rhdl]: [
- rvdl: boolean | undefined,
- rhdl: boolean | undefined,
- ]) {
+ removeAlignLine([rvdl, rhdl]: [rvdl: boolean | undefined, rhdl: boolean | undefined]) {
if (rvdl) {
const vlid = this.getDrawLineIdByDrawLine(this.drawedLines[0].dl);
this.graph.drawTransient('line', vlid, { action: 'remove' });
@@ -1060,6 +983,7 @@ export class Snapline extends Base {
/**
* get draggingBBox Point based on LinePosition
+ * @param lp
*/
getDraggingBBoxPointByLinePosition(lp: LinePosition): Point | undefined {
if (!this.draggingBBox) {
@@ -1087,12 +1011,14 @@ export class Snapline extends Base {
/**
* update align line under condition of absorbed
+ * @param root0
+ * @param root0."0"
+ * @param root0."1"
*/
updateAlignLineWhenAbsorb([v, h]: [boolean, boolean]) {
if (v) {
if (this.drawedLines[0] && this.drawedLines[0].do) {
- const draggingBBoxDrawEndPoint: Point =
- this.getDraggingBBoxPointByLinePosition(this.drawedLines[0].dl.lp);
+ const draggingBBoxDrawEndPoint: Point = this.getDraggingBBoxPointByLinePosition(this.drawedLines[0].dl.lp);
const vdl: DrawLine = {
line: [
this.drawedLines[0].dl.line[0],
@@ -1111,8 +1037,7 @@ export class Snapline extends Base {
if (h) {
if (this.drawedLines[1] && this.drawedLines[1].do) {
- const draggingBBoxDrawEndPoint: Point =
- this.getDraggingBBoxPointByLinePosition(this.drawedLines[1].dl.lp);
+ const draggingBBoxDrawEndPoint: Point = this.getDraggingBBoxPointByLinePosition(this.drawedLines[1].dl.lp);
const hdl: DrawLine = {
line: [
this.drawedLines[1].dl.line[0],
@@ -1134,8 +1059,7 @@ export class Snapline extends Base {
* check whether can draw lines
*/
canDrawLine(): { vdl: DrawLine; hdl: DrawLine } | false {
- const { v, h }: { v: DrawLine | undefined; h: DrawLine | undefined } =
- this.chooseAlignLine();
+ const { v, h }: { v: DrawLine | undefined; h: DrawLine | undefined } = this.chooseAlignLine();
if (!v && !h) {
return false;
}
@@ -1146,14 +1070,11 @@ export class Snapline extends Base {
/**
* detect whether adsorption can be cancelled
* two directions:v h
- * @return first: v direction ; second:h direction; undefine means no-adsorb
+ * @returns first: v direction ; second:h direction; undefine means no-adsorb
*/
canCancelAbsorb(): [boolean | undefined, boolean | undefined] {
// eslint-disable-next-line prefer-const
- let ret: [boolean | undefined, boolean | undefined] = [
- undefined,
- undefined,
- ];
+ let ret: [boolean | undefined, boolean | undefined] = [undefined, undefined];
const vdl = this.drawedLines[0].dl;
const hdl = this.drawedLines[1].dl;
@@ -1181,6 +1102,9 @@ export class Snapline extends Base {
/**
* absorb the dragging box
+ * @param dls
+ * @param dls.vdl
+ * @param dls.hdl
*/
absorb(dls: { vdl: DrawLine; hdl: DrawLine }) {
if (dls.vdl) {
@@ -1205,11 +1129,11 @@ export class Snapline extends Base {
* If there is dl(draw line), then absorb to dl;
* don't pass dl, means cancel absorb
* @param dl drawline [point, point]
+ * @param shouldChange
+ * @param shouldChange.x
+ * @param shouldChange.y
*/
- updateDraggingItemPosition(
- dl?: DrawLine,
- shouldChange?: { x?: number; y?: number },
- ) {
+ updateDraggingItemPosition(dl?: DrawLine, shouldChange?: { x?: number; y?: number }) {
// Determine if historyPoints do not exist do not continue
if (!this.historyPoints[0] && !this.historyPoints[1]) {
return;
@@ -1281,11 +1205,7 @@ export class Snapline extends Base {
throttleUpdate = throttle(
() => {
- this.graph.updateNodePosition(
- Array.from(this.updateCache.values()),
- false,
- true,
- );
+ this.graph.updateNodePosition(Array.from(this.updateCache.values()), false, true);
this.updateCache.clear();
},
16,
diff --git a/packages/g6/src/stdlib/plugin/timebar/index.ts b/packages/g6/src/stdlib/plugin/timebar/index.ts
index 3cff9ea1c9a..a197c805990 100644
--- a/packages/g6/src/stdlib/plugin/timebar/index.ts
+++ b/packages/g6/src/stdlib/plugin/timebar/index.ts
@@ -8,14 +8,12 @@ import type { Padding } from '../../../types/common';
import type { ITEM_TYPE } from '../../../types/item';
import { Plugin as Base, IPluginBaseConfig } from '../../../types/plugin';
import { createCanvas } from '../../../util/canvas';
-import { formatPadding } from '../../../util/shape';
import { createDOM } from '../../../util/dom';
+import { formatPadding } from '../../../util/shape';
// -- start -- Adapt to GUI -- start --
type SubStyleProps = {
- [K in keyof T as K extends `${Prefix}${infer Rest}`
- ? Uncapitalize
- : never]: T[K];
+ [K in keyof T as K extends `${Prefix}${infer Rest}` ? Uncapitalize : never]: T[K];
};
const prefixStyleProps = (style: Record, prefix: string) => {
@@ -97,10 +95,7 @@ export interface TimebarConfig
* manage graph manually when timebar range/value change
* @description if it is not specified, the graph will be filtered by default
*/
- filter?: (
- graph: IGraph,
- values: Parameters,
- ) => void;
+ filter?: (graph: IGraph, values: Parameters) => void;
axisStyle?: SubStyleProps;
chartStyle?: SubStyleProps;
controllerStyle?: SubStyleProps;
@@ -109,11 +104,7 @@ export interface TimebarConfig
const prospectiveTimeKeys = ['timestamp', 'time', 'date', 'datetime'];
const prospectiveValueKeys = ['value', 'date'];
-const tryToGet = (
- datum: Datum,
- optionsKeys: string[],
- defaultValue?: T,
-) => {
+const tryToGet = (datum: Datum, optionsKeys: string[], defaultValue?: T) => {
for (let i = 0; i < optionsKeys.length; i++) {
const key = optionsKeys[i];
const val = datum?.[key] as T;
@@ -165,10 +156,8 @@ export class Timebar extends Base {
data: [],
filterItemTypes: ['node'],
filterType: 'modify',
- getTimeFromItem: (model) =>
- tryToGet(model.data, prospectiveTimeKeys, undefined),
- getTimeFromData: (datum) =>
- tryToGet(datum, prospectiveTimeKeys, undefined),
+ getTimeFromItem: (model) => tryToGet(model.data, prospectiveTimeKeys, undefined),
+ getTimeFromData: (datum) => tryToGet(datum, prospectiveTimeKeys, undefined),
getValueFromItem: (datum) => tryToGet(datum, prospectiveValueKeys, 0),
height: 60,
padding: 10,
@@ -235,23 +224,14 @@ export class Timebar extends Base {
const { className } = options;
const { width, height } = this.containerShape;
- const wrapper = createDOM(
- ``,
- );
+ const wrapper = createDOM(``);
this.container.appendChild(wrapper);
return wrapper;
}
private createCanvas() {
const { width, height } = this.containerShape;
- const canvas = createCanvas(
- 'canvas',
- this.wrapper,
- width,
- height,
- undefined,
- { background: '#fff' },
- );
+ const canvas = createCanvas('canvas', this.wrapper, width, height, undefined, { background: '#fff' });
return canvas;
}
@@ -328,8 +308,7 @@ export class Timebar extends Base {
...userDefinedOptions,
};
- if (!this.timebar)
- this.timebar = this.canvas.appendChild(new GUITimebar({ style }));
+ if (!this.timebar) this.timebar = this.canvas.appendChild(new GUITimebar({ style }));
else this.timebar.update(style);
this.updatePosition();
}
@@ -340,15 +319,11 @@ export class Timebar extends Base {
this.processValuesChange();
}
- private handleValuesChange(
- values: Parameters[0],
- ) {
+ private handleValuesChange(values: Parameters[0]) {
this.processValuesChange(values);
}
- private processValuesChange(
- values: Parameters[0] = this.timebar.values,
- ) {
+ private processValuesChange(values: Parameters[0] = this.timebar.values) {
const { filter } = this.options;
if (filter) filter(values);
else this.filter(values);
@@ -356,16 +331,11 @@ export class Timebar extends Base {
private filter(values: Parameters[0]) {
// cache data
- if (
- !this.graphDataCache ||
- (this.graphDataCache.nodes.length === 0 &&
- this.graphDataCache.edges.length === 0)
- ) {
+ if (!this.graphDataCache || (this.graphDataCache.nodes.length === 0 && this.graphDataCache.edges.length === 0)) {
this.graphDataCache = deepMix({}, this.data);
}
- const { filterType, filterItemTypes, shouldIgnore, getTimeFromItem } =
- this.options;
+ const { filterType, filterItemTypes, shouldIgnore, getTimeFromItem } = this.options;
const isTimeInValues = (time: number | Date) => {
if (Array.isArray(values)) {
@@ -390,10 +360,7 @@ export class Timebar extends Base {
const items = this.graphDataCache[key];
items.forEach((item) => {
- const queryItem =
- type === 'node'
- ? this.graph.getNodeData(item.id)
- : this.graph.getEdgeData(item.id);
+ const queryItem = type === 'node' ? this.graph.getNodeData(item.id) : this.graph.getEdgeData(item.id);
const time = getTimeFromItem(item, type);
const isItemExists = queryItem !== undefined;
const isItemVisible = queryItem && this.graph.getItemVisible(item.id);
diff --git a/packages/g6/src/stdlib/plugin/toolbar/index.ts b/packages/g6/src/stdlib/plugin/toolbar/index.ts
index 17ac3fef84d..c1a0307467e 100644
--- a/packages/g6/src/stdlib/plugin/toolbar/index.ts
+++ b/packages/g6/src/stdlib/plugin/toolbar/index.ts
@@ -5,13 +5,11 @@ import { createDOM, modifyCSS } from '../../../util/dom';
/**
* The `ToolbarConfig` interface contains the following properties:
-
-- `handleClick`: An optional function for handling clicks on the toolbar. It takes two arguments: `code` (of type string) and `graph` (of type IGraph), and has no return value.
-- `getContent`: A required function for getting the content of the toolbar. It takes an optional argument of type `IGraph`, and returns a value of type HTMLElement or string.
-- `zoomSensitivity`: An optional number representing the zoom sensitivity of the toolbar. The default value is 10.
-- `minZoom`: An optional number representing the minimum zoom ratio of the toolbar. The default value is 0.00001.
-- `maxZoom`: An optional number representing the maximum zoom ratio of the toolbar. The default value is 1000.
-
+ * - `handleClick`: An optional function for handling clicks on the toolbar. It takes two arguments: `code` (of type string) and `graph` (of type IGraph), and has no return value.
+ * - `getContent`: A required function for getting the content of the toolbar. It takes an optional argument of type `IGraph`, and returns a value of type HTMLElement or string.
+ * - `zoomSensitivity`: An optional number representing the zoom sensitivity of the toolbar. The default value is 10.
+ * - `minZoom`: An optional number representing the minimum zoom ratio of the toolbar. The default value is 0.00001.
+ * - `maxZoom`: An optional number representing the maximum zoom ratio of the toolbar. The default value is 1000.
*/
export interface ToolbarConfig extends IPluginBaseConfig {
/** Function for handling clicks on toolbar */
@@ -117,9 +115,7 @@ export class Toolbar extends Base {
this.containerDOM.appendChild(this.toolbarDOM);
this.toolbarDOM.addEventListener('click', (evt) => {
- const current = (getEventPath(evt) as HTMLElement[]).filter(
- (p) => p.nodeName === 'LI',
- );
+ const current = (getEventPath(evt) as HTMLElement[]).filter((p) => p.nodeName === 'LI');
if (current.length === 0) {
return;
}
@@ -220,7 +216,6 @@ export class Toolbar extends Base {
/**
* Handles different types of operations on the Toolbar
* @param code operation code
- * @param graph graph instance
*/
public handleDefaultOperator(code: string) {
switch (code) {
diff --git a/packages/g6/src/stdlib/plugin/tooltip/index.ts b/packages/g6/src/stdlib/plugin/tooltip/index.ts
index 2f79f6bd536..646250c068f 100644
--- a/packages/g6/src/stdlib/plugin/tooltip/index.ts
+++ b/packages/g6/src/stdlib/plugin/tooltip/index.ts
@@ -55,22 +55,18 @@ type Placement =
/**
* The `TooltipConfig` interface contains the following properties:
-
-- `getContent`: An optional function for getting the content of the tooltip. It takes an optional argument of type `IG6GraphEvent`, and returns a value of type HTMLElement, string, or Promise (resolving to HTMLElement or string).
-- `offsetX`: An optional number representing the offset of the tooltip in the X direction.
-- `offsetY`: An optional number representing the offset of the tooltip in the Y direction.
-- `shouldBegin`: An optional function for determining whether the tooltip should be displayed. It takes an optional argument of type `IG6GraphEvent`, and returns a boolean value.
-- `itemTypes`: An optional array of strings representing the types of items for which the tooltip is allowed to be displayed. The possible values are 'node', 'edge', 'combo', and 'canvas'.
-- `trigger`: An optional string, either 'pointerenter' or 'click', representing the event type that triggers the display of the tooltip.
-- `fixToNode`: An optional array of two numbers, a string representing a placement, or undefined, representing how to fix the tooltip to a node.
-- `loadingContent`: An optional HTMLElement or string representing the loading DOM.
-
+ * - `getContent`: An optional function for getting the content of the tooltip. It takes an optional argument of type `IG6GraphEvent`, and returns a value of type HTMLElement, string, or Promise (resolving to HTMLElement or string).
+ * - `offsetX`: An optional number representing the offset of the tooltip in the X direction.
+ * - `offsetY`: An optional number representing the offset of the tooltip in the Y direction.
+ * - `shouldBegin`: An optional function for determining whether the tooltip should be displayed. It takes an optional argument of type `IG6GraphEvent`, and returns a boolean value.
+ * - `itemTypes`: An optional array of strings representing the types of items for which the tooltip is allowed to be displayed. The possible values are 'node', 'edge', 'combo', and 'canvas'.
+ * - `trigger`: An optional string, either 'pointerenter' or 'click', representing the event type that triggers the display of the tooltip.
+ * - `fixToNode`: An optional array of two numbers, a string representing a placement, or undefined, representing how to fix the tooltip to a node.
+ * - `loadingContent`: An optional HTMLElement or string representing the loading DOM.
*/
export interface TooltipConfig extends IPluginBaseConfig {
/** Function for getting tooltip content */
- getContent?: (
- evt?: IG6GraphEvent,
- ) => HTMLElement | string | Promise;
+ getContent?: (evt?: IG6GraphEvent) => HTMLElement | string | Promise;
/** Offset of tooltip in X direction */
offsetX?: number;
/** Offset of tooltip in Y direction */
@@ -153,9 +149,7 @@ export class Tooltip extends Base {
public init(graph: IGraph) {
super.init(graph);
const className = this.options.className;
- const tooltip = createDOM(
- ``,
- );
+ const tooltip = createDOM(``);
modifyCSS(tooltip, {
position: 'absolute',
visibility: 'hidden',
@@ -186,12 +180,7 @@ export class Tooltip extends Base {
}
public onClick(e: IG6GraphEvent) {
- if (
- e.itemId &&
- e.itemType &&
- this.options.itemTypes.indexOf(e.itemType) === -1
- )
- return;
+ if (e.itemId && e.itemType && this.options.itemTypes.indexOf(e.itemType) === -1) return;
const { itemId } = e;
// click the same item twice, tooltip will be hidden
if (this.currentTarget === itemId) {
@@ -206,12 +195,7 @@ export class Tooltip extends Base {
}
public onPointerEnter(e: IG6GraphEvent) {
- if (
- e.itemId &&
- e.itemType &&
- this.options.itemTypes.indexOf(e.itemType) === -1
- )
- return;
+ if (e.itemId && e.itemType && this.options.itemTypes.indexOf(e.itemType) === -1) return;
const { itemId } = e;
this.currentTarget = itemId;
this.showTooltip(e);
@@ -219,12 +203,7 @@ export class Tooltip extends Base {
}
public onPointerMove(e: IG6GraphEvent) {
- if (
- e.itemId &&
- e.itemType &&
- this.options.itemTypes.indexOf(e.itemType) === -1
- )
- return;
+ if (e.itemId && e.itemType && this.options.itemTypes.indexOf(e.itemType) === -1) return;
if (!this.currentTarget || e.itemId === this.currentTarget) {
return;
}
diff --git a/packages/g6/src/stdlib/plugin/types.ts b/packages/g6/src/stdlib/plugin/types.ts
index cd52a18ceac..63e259363ce 100644
--- a/packages/g6/src/stdlib/plugin/types.ts
+++ b/packages/g6/src/stdlib/plugin/types.ts
@@ -1,11 +1,11 @@
+export type { EdgeFilterLens } from './edgeFilterLens';
export type { FisheyeConfig } from './fisheye';
export type { GridConfig } from './grid';
export type { HistoryConfig } from './history';
export type { LegendConfig } from './legend';
export type { MenuConfig } from './menu';
export type { MiniMapConfig } from './minimap';
+export type { SnapLineConfig } from './snapline';
+export type { TimebarConfig } from './timebar';
export type { ToolbarConfig } from './toolbar';
export type { TooltipConfig } from './tooltip';
-export type { TimebarConfig } from './timebar';
-export type { SnapLineConfig } from './snapline';
-export type { EdgeFilterLens } from './edgeFilterLens';
diff --git a/packages/g6/src/stdlib/plugin/watermarker/index.ts b/packages/g6/src/stdlib/plugin/watermarker/index.ts
index 565a624705f..76257af2be1 100644
--- a/packages/g6/src/stdlib/plugin/watermarker/index.ts
+++ b/packages/g6/src/stdlib/plugin/watermarker/index.ts
@@ -1,8 +1,8 @@
-import { uniqueId, isString } from '@antv/util';
import { Canvas, Group, Image, Text, TextStyleProps } from '@antv/g';
+import { isString, uniqueId } from '@antv/util';
+import { IGraph } from '../../../types';
import { Plugin as Base, IPluginBaseConfig } from '../../../types/plugin';
import { createCanvas } from '../../../util/canvas';
-import { IGraph } from '../../../types';
/** Define configuration types for image and text watermarks */
type ImageWaterMarkerConfig = {
@@ -66,8 +66,7 @@ export class WaterMarker extends Base {
begin: [0, 0],
separation: [100, 100],
image: {
- imgURL:
- 'https://gw.alipayobjects.com/os/s/prod/antv/assets/image/logo-with-text-73b8a.svg',
+ imgURL: 'https://gw.alipayobjects.com/os/s/prod/antv/assets/image/logo-with-text-73b8a.svg',
width: 94,
height: 28,
rotate: 0,
@@ -85,6 +84,7 @@ export class WaterMarker extends Base {
/**
* Initialize the WaterMarker plugin.
+ * @param graph
*/
public init(graph: IGraph) {
super.init(graph);
@@ -130,21 +130,11 @@ export class WaterMarker extends Base {
container.style.position = 'relative';
}
- this.canvasSize = [
- width === undefined ? graphSize[0] : width,
- height === undefined ? graphSize[1] : height,
- ];
+ this.canvasSize = [width === undefined ? graphSize[0] : width, height === undefined ? graphSize[1] : height];
this.followGraphSize = width === undefined || height === undefined;
- this.canvas = createCanvas(
- 'canvas',
- container,
- this.canvasSize[0],
- this.canvasSize[1],
- );
- const $domElement = this.canvas
- .getContextService()
- .getDomElement() as unknown as HTMLElement;
+ this.canvas = createCanvas('canvas', container, this.canvasSize[0], this.canvasSize[1]);
+ const $domElement = this.canvas.getContextService().getDomElement() as unknown as HTMLElement;
$domElement.style.position = 'fixed';
$domElement.style.outline = 'none';
$domElement.style.pointerEvents = 'none';
@@ -153,12 +143,8 @@ export class WaterMarker extends Base {
const canvasEl = this.canvas.getContextService().getDomElement() as any;
this.container.removeChild(canvasEl);
- const graphCanvasDOM = graph.canvas
- .getContextService()
- .getDomElement() as any;
- const graphTransientCanvasDOM = graph.transientCanvas
- .getContextService()
- .getDomElement() as any;
+ const graphCanvasDOM = graph.canvas.getContextService().getDomElement() as any;
+ const graphTransientCanvasDOM = graph.transientCanvas.getContextService().getDomElement() as any;
switch (position) {
case 'top':
this.container.appendChild(canvasEl);
diff --git a/packages/g6/src/stdlib/selector/lasso.ts b/packages/g6/src/stdlib/selector/lasso.ts
index 48c84e98c99..d36666d86c1 100644
--- a/packages/g6/src/stdlib/selector/lasso.ts
+++ b/packages/g6/src/stdlib/selector/lasso.ts
@@ -10,6 +10,9 @@ import { isPolygonsIntersect } from '../../util/shape';
* A node is selected if the center of its bbox is inside the rect;
* An edge is selected if both end nodes are inside the rect;
* A combo is selected if the center of its bbox is inside the rect.
+ * @param graph
+ * @param points
+ * @param itemTypes
*/
export default (graph: IGraph, points: Point[], itemTypes: ITEM_TYPE[]) => {
const lassoContour = points.map((point) => [point.x, point.y]);
@@ -40,10 +43,7 @@ export default (graph: IGraph, points: Point[], itemTypes: ITEM_TYPE[]) => {
if (itemTypes.includes('edge')) {
// an edge is selected only if both the source and target nodes are selected
- selectedEdgeIds = getEdgesBetween(
- graph,
- selectedNodeIds.concat(selectedComboIds),
- );
+ selectedEdgeIds = getEdgesBetween(graph, selectedNodeIds.concat(selectedComboIds));
}
return {
@@ -52,11 +52,7 @@ export default (graph: IGraph, points: Point[], itemTypes: ITEM_TYPE[]) => {
combos: selectedComboIds,
};
};
-const isItemIntersectPolygon = (
- graph: IGraph,
- id: ID,
- polyPoints: number[][],
-) => {
+const isItemIntersectPolygon = (graph: IGraph, id: ID, polyPoints: number[][]) => {
// TODO
// const shape = item.getKeyShape();
// if (item.get('type') === 'path') {
diff --git a/packages/g6/src/stdlib/selector/rect.ts b/packages/g6/src/stdlib/selector/rect.ts
index 2b598d8a969..850961f0cd5 100644
--- a/packages/g6/src/stdlib/selector/rect.ts
+++ b/packages/g6/src/stdlib/selector/rect.ts
@@ -9,6 +9,9 @@ import { getEdgesBetween } from '../../util/item';
* A node is selected if the center of its bbox is inside the rect;
* An edge is selected if both end nodes are inside the rect;
* A combo is selected if the center of its bbox is inside the rect.
+ * @param graph
+ * @param points
+ * @param itemTypes
*/
export default (graph: IGraph, points: Point[], itemTypes: ITEM_TYPE[]) => {
const [p1, p2] = points;
@@ -46,10 +49,7 @@ export default (graph: IGraph, points: Point[], itemTypes: ITEM_TYPE[]) => {
if (itemTypes.includes('edge')) {
// The edge is selected while both the source and target node are selected.
- selectedEdgeIds = getEdgesBetween(
- graph,
- selectedNodeIds.concat(selectedComboIds),
- );
+ selectedEdgeIds = getEdgesBetween(graph, selectedNodeIds.concat(selectedComboIds));
}
return {
@@ -59,20 +59,8 @@ export default (graph: IGraph, points: Point[], itemTypes: ITEM_TYPE[]) => {
};
};
-const isBBoxCenterInRect = (
- graph: IGraph,
- id: ID,
- left: number,
- right: number,
- top: number,
- bottom: number,
-) => {
+const isBBoxCenterInRect = (graph: IGraph, id: ID, left: number, right: number, top: number, bottom: number) => {
const bbox = graph.getRenderBBox(id);
if (!bbox) return false;
- return (
- bbox.center[0] >= left &&
- bbox.center[0] <= right &&
- bbox.center[1] >= top &&
- bbox.center[1] <= bottom
- );
+ return bbox.center[0] >= left && bbox.center[0] <= right && bbox.center[1] >= top && bbox.center[1] <= bottom;
};
diff --git a/packages/g6/src/stdlib/theme/index.ts b/packages/g6/src/stdlib/theme/index.ts
index ba7f11f8ec0..4100599d4e5 100644
--- a/packages/g6/src/stdlib/theme/index.ts
+++ b/packages/g6/src/stdlib/theme/index.ts
@@ -1,2 +1,2 @@
-export * from './light';
export * from './dark';
+export * from './light';
diff --git a/packages/g6/src/stdlib/themeSolver/base.ts b/packages/g6/src/stdlib/themeSolver/base.ts
index 82e36ec249c..50a28129201 100644
--- a/packages/g6/src/stdlib/themeSolver/base.ts
+++ b/packages/g6/src/stdlib/themeSolver/base.ts
@@ -11,10 +11,7 @@ export abstract class BaseThemeSolver {
this.specification = this.solver(options, themes);
this.options = options;
}
- abstract solver(
- options: ThemeSolverOptions,
- themes: ThemeSpecificationMap,
- ): ThemeSpecification;
+ abstract solver(options: ThemeSolverOptions, themes: ThemeSpecificationMap): ThemeSpecification;
public getSpecification: () => ThemeSpecification = () => {
return this.specification;
};
diff --git a/packages/g6/src/stdlib/themeSolver/index.ts b/packages/g6/src/stdlib/themeSolver/index.ts
index 69f80abde86..d0ff1c0974c 100644
--- a/packages/g6/src/stdlib/themeSolver/index.ts
+++ b/packages/g6/src/stdlib/themeSolver/index.ts
@@ -1,3 +1,3 @@
-export * from './spec';
export * from './base';
+export * from './spec';
export * from './subject';
diff --git a/packages/g6/src/stdlib/themeSolver/spec.ts b/packages/g6/src/stdlib/themeSolver/spec.ts
index db53ae7b9bd..f601f8880b2 100644
--- a/packages/g6/src/stdlib/themeSolver/spec.ts
+++ b/packages/g6/src/stdlib/themeSolver/spec.ts
@@ -1,9 +1,5 @@
import { isArray, isObject } from '@antv/util';
-import {
- NodeStyleSets,
- EdgeStyleSets,
- ThemeSpecification,
-} from '../../types/theme';
+import { EdgeStyleSets, NodeStyleSets, ThemeSpecification } from '../../types/theme';
import { mergeStyles } from '../../util/shape';
import { BaseThemeSolver, ThemeSpecificationMap } from './base';
@@ -31,10 +27,7 @@ interface SpecThemeSolverOptions {
};
}
export class SpecThemeSolver extends BaseThemeSolver {
- public solver(
- options: SpecThemeSolverOptions,
- themes: ThemeSpecificationMap,
- ): ThemeSpecification {
+ public solver(options: SpecThemeSolverOptions, themes: ThemeSpecificationMap): ThemeSpecification {
const { base = 'light', specification } = options;
const baseSpec = themes[base];
const mergedSpec = { ...baseSpec };
@@ -53,8 +46,7 @@ export class SpecThemeSolver extends BaseThemeSolver {
if (isArray(paletteProps)) {
return paletteProps.map((color) => ({
default: {
- keyShape:
- itemType === 'edge' ? { stroke: color } : { fill: color },
+ keyShape: itemType === 'edge' ? { stroke: color } : { fill: color },
},
}));
}
@@ -64,9 +56,7 @@ export class SpecThemeSolver extends BaseThemeSolver {
res[dataType] = {
default: {
keyShape:
- itemType === 'edge'
- ? { stroke: paletteProps[dataType] }
- : { fill: paletteProps[dataType] },
+ itemType === 'edge' ? { stroke: paletteProps[dataType] } : { fill: paletteProps[dataType] },
},
};
});
@@ -85,10 +75,7 @@ export class SpecThemeSolver extends BaseThemeSolver {
mergedStyles = incomingStyles.map((incomingStyle) => {
const mergedStatesStyles = { ...baseStyles };
Object.keys(incomingStyle).forEach((stateName) => {
- mergedStatesStyles[stateName] = mergeStyles([
- baseStyles[stateName],
- incomingStyle[stateName],
- ]);
+ mergedStatesStyles[stateName] = mergeStyles([baseStyles[stateName], incomingStyle[stateName]]);
});
return mergedStatesStyles;
});
@@ -98,10 +85,7 @@ export class SpecThemeSolver extends BaseThemeSolver {
const mergedStatesStyles = { ...baseStyles };
const incomingStyle = incomingStyles[dataType];
Object.keys(incomingStyle).forEach((stateName) => {
- mergedStatesStyles[stateName] = mergeStyles([
- baseStyles[stateName],
- incomingStyle[stateName],
- ]);
+ mergedStatesStyles[stateName] = mergeStyles([baseStyles[stateName], incomingStyle[stateName]]);
});
mergedStyles[dataType] = mergedStatesStyles;
});
diff --git a/packages/g6/src/stdlib/themeSolver/subject.ts b/packages/g6/src/stdlib/themeSolver/subject.ts
index 1d8bad338dd..e41298a7429 100644
--- a/packages/g6/src/stdlib/themeSolver/subject.ts
+++ b/packages/g6/src/stdlib/themeSolver/subject.ts
@@ -1,6 +1,6 @@
+import { generate } from '@ant-design/colors';
import { isArray } from '@antv/util';
import color from 'color';
-import { generate } from '@ant-design/colors';
import { ThemeSpecification } from '../../types/theme';
import { mergeStyles } from '../../util/shape';
import { BaseThemeSolver, ThemeSpecificationMap } from './base';
@@ -28,10 +28,7 @@ interface SubjectThemeSolverOptions {
}
export class SubjectThemeSolver extends BaseThemeSolver {
- public solver(
- options: SubjectThemeSolverOptions,
- themes: ThemeSpecificationMap,
- ): ThemeSpecification {
+ public solver(options: SubjectThemeSolverOptions, themes: ThemeSpecificationMap): ThemeSpecification {
const { base = 'light', baseColor = '#fff', specification } = options;
const baseSpec = themes[base];
const mergedSpec = { ...baseSpec };
@@ -47,31 +44,15 @@ export class SubjectThemeSolver extends BaseThemeSolver {
let mergedStyles;
if (isArray(palette)) {
mergedStyles = palette.map((subjectColor) => {
- const colorSet = getColorsWithSubjectColor(
- subjectColor,
- baseColor,
- base,
- );
- return this.getMergeStylesFromColorSet(
- itemType,
- colorSet,
- baseStyles,
- );
+ const colorSet = getColorsWithSubjectColor(subjectColor, baseColor, base);
+ return this.getMergeStylesFromColorSet(itemType, colorSet, baseStyles);
});
} else {
mergedStyles = { others: baseStyles };
Object.keys(palette).forEach((dataType) => {
const subjectColor = palette[dataType];
- const colorSet = getColorsWithSubjectColor(
- subjectColor,
- baseColor,
- base,
- );
- mergedStyles[dataType] = this.getMergeStylesFromColorSet(
- itemType,
- colorSet,
- baseStyles,
- );
+ const colorSet = getColorsWithSubjectColor(subjectColor, baseColor, base);
+ mergedStyles[dataType] = this.getMergeStylesFromColorSet(itemType, colorSet, baseStyles);
});
}
mergedSpec[itemType] = {
@@ -280,39 +261,17 @@ export const mixColor = (backColor, frontColor, frontAlpha) => {
]).rgb();
};
-const getColorsWithDefaultTheme = (
- subjectColor,
- backColor = '#fff',
- disableColor = 'rgb(150, 150, 150)',
-) => {
- const subjectColor005 = mixColor(backColor, subjectColor, 0.05)
- .rgb()
- .toString();
- const subjectColor01 = mixColor(backColor, subjectColor, 0.1)
- .rgb()
- .toString();
- const subjectColor02 = mixColor(backColor, subjectColor, 0.2)
- .rgb()
- .toString();
- const subjectColor04 = mixColor(backColor, subjectColor, 0.4)
- .rgb()
- .toString();
-
- const disableColor002 = mixColor(backColor, disableColor, 0.02)
- .rgb()
- .toString();
- const disableColor005 = mixColor(backColor, disableColor, 0.05)
- .rgb()
- .toString();
- const disableColor01 = mixColor(backColor, disableColor, 0.1)
- .rgb()
- .toString();
- const disableColor02 = mixColor(backColor, disableColor, 0.2)
- .rgb()
- .toString();
- const disableColor03 = mixColor(backColor, disableColor, 0.3)
- .rgb()
- .toString();
+const getColorsWithDefaultTheme = (subjectColor, backColor = '#fff', disableColor = 'rgb(150, 150, 150)') => {
+ const subjectColor005 = mixColor(backColor, subjectColor, 0.05).rgb().toString();
+ const subjectColor01 = mixColor(backColor, subjectColor, 0.1).rgb().toString();
+ const subjectColor02 = mixColor(backColor, subjectColor, 0.2).rgb().toString();
+ const subjectColor04 = mixColor(backColor, subjectColor, 0.4).rgb().toString();
+
+ const disableColor002 = mixColor(backColor, disableColor, 0.02).rgb().toString();
+ const disableColor005 = mixColor(backColor, disableColor, 0.05).rgb().toString();
+ const disableColor01 = mixColor(backColor, disableColor, 0.1).rgb().toString();
+ const disableColor02 = mixColor(backColor, disableColor, 0.2).rgb().toString();
+ const disableColor03 = mixColor(backColor, disableColor, 0.3).rgb().toString();
const paletteFromSubject = generate(subjectColor, {
theme: 'default',
@@ -373,39 +332,17 @@ const getColorsWithDefaultTheme = (
};
};
-const getColorsWithDarkTheme = (
- subjectColor,
- backColor = '#fff',
- disableColor = '#777',
-) => {
- const subjectColor02 = mixColor(backColor, subjectColor, 0.2)
- .rgb()
- .toString();
- const subjectColor03 = mixColor(backColor, subjectColor, 0.3)
- .rgb()
- .toString();
- const subjectColor06 = mixColor(backColor, subjectColor, 0.6)
- .rgb()
- .toString();
- const subjectColor08 = mixColor(backColor, subjectColor, 0.8)
- .rgb()
- .toString();
-
- const disableColor02 = mixColor(backColor, disableColor, 0.2)
- .rgb()
- .toString();
- const disableColor025 = mixColor(backColor, disableColor, 0.25)
- .rgb()
- .toString();
- const disableColor03 = mixColor(backColor, disableColor, 0.3)
- .rgb()
- .toString();
- const disableColor04 = mixColor(backColor, disableColor, 0.4)
- .rgb()
- .toString();
- const disableColor05 = mixColor(backColor, disableColor, 0.5)
- .rgb()
- .toString();
+const getColorsWithDarkTheme = (subjectColor, backColor = '#fff', disableColor = '#777') => {
+ const subjectColor02 = mixColor(backColor, subjectColor, 0.2).rgb().toString();
+ const subjectColor03 = mixColor(backColor, subjectColor, 0.3).rgb().toString();
+ const subjectColor06 = mixColor(backColor, subjectColor, 0.6).rgb().toString();
+ const subjectColor08 = mixColor(backColor, subjectColor, 0.8).rgb().toString();
+
+ const disableColor02 = mixColor(backColor, disableColor, 0.2).rgb().toString();
+ const disableColor025 = mixColor(backColor, disableColor, 0.25).rgb().toString();
+ const disableColor03 = mixColor(backColor, disableColor, 0.3).rgb().toString();
+ const disableColor04 = mixColor(backColor, disableColor, 0.4).rgb().toString();
+ const disableColor05 = mixColor(backColor, disableColor, 0.5).rgb().toString();
const paletteFromSubject = generate(subjectColor, {
theme: 'dark',
@@ -470,27 +407,14 @@ const getColorsWithDarkTheme = (
* get the set of colors according to the subject color and background color
* @param subjectColor the subject color
* @param backColor background color
- * @param disableColor the color for disable state
+ * @param theme the theme of the color set
*/
-const getColorsWithSubjectColor = (
- subjectColor,
- backColor = '#fff',
- theme: 'light' | 'dark' = 'light',
-) => {
- if (theme !== 'light')
- return getColorsWithDarkTheme(subjectColor, backColor, '#777');
- return getColorsWithDefaultTheme(
- subjectColor,
- backColor,
- 'rgb(150, 150, 150)',
- );
+const getColorsWithSubjectColor = (subjectColor, backColor = '#fff', theme: 'light' | 'dark' = 'light') => {
+ if (theme !== 'light') return getColorsWithDarkTheme(subjectColor, backColor, '#777');
+ return getColorsWithDefaultTheme(subjectColor, backColor, 'rgb(150, 150, 150)');
};
-const getColorSetsBySubjectColors = (
- subjectColors,
- backColor = '#fff',
- theme: 'light' | 'dark' = 'light',
-) => {
+const getColorSetsBySubjectColors = (subjectColors, backColor = '#fff', theme: 'light' | 'dark' = 'light') => {
const sets = [];
subjectColors.forEach((sColor) => {
sets.push(getColorsWithSubjectColor(sColor, backColor, theme));
diff --git a/packages/g6/src/types/animate.ts b/packages/g6/src/types/animate.ts
index 1d70fa9ba30..b0943b09a02 100644
--- a/packages/g6/src/types/animate.ts
+++ b/packages/g6/src/types/animate.ts
@@ -3,7 +3,6 @@ import { IAnimationEffectTiming } from '@antv/g';
export interface AnimateCfg {
/**
* Duration of one animation.
- * @type {number}
*/
duration?: number;
/**
@@ -13,27 +12,22 @@ export interface AnimateCfg {
easing?: string;
/**
* Delay of the animation.
- * @type {function}
*/
delay?: number;
/**
* Iteration number for the animation, Infinity means repeat.
- * @type {number | typeof Infinity}
*/
iterations?: number | typeof Infinity;
/**
* Called after the animation is finished.
- * @type {function}
*/
callback?: () => void;
/**
* Called after the animation is paused.
- * @type {function}}
*/
pauseCallback?: () => void;
/**
* Called after the animation is resumed.
- * @type {function}
*/
resumeCallback?: () => void;
}
@@ -66,6 +60,4 @@ export interface IAnimates {
update?: (IAnimate | IStateAnimate)[];
}
-export type CameraAnimationOptions = Partial<
- Pick
->;
+export type CameraAnimationOptions = Partial>;
diff --git a/packages/g6/src/types/behavior.ts b/packages/g6/src/types/behavior.ts
index 9f76cc9062d..9c4b1c41a9c 100644
--- a/packages/g6/src/types/behavior.ts
+++ b/packages/g6/src/types/behavior.ts
@@ -23,8 +23,10 @@ export abstract class Behavior {
destroy() {}
}
-/** Behavior registry table.
- * @example { 'drag-node': DragNodeBehavior, 'my-drag-node': MyDragNodeBehavior }
+/**
+ * Behavior registry table.
+ * @example
+ * { 'drag-node': DragNodeBehavior, 'my-drag-node': MyDragNodeBehavior }
*/
export interface BehaviorRegistry {
[type: string]: typeof Behavior;
diff --git a/packages/g6/src/types/combo.ts b/packages/g6/src/types/combo.ts
index 9792dc5d80e..95eb635e00f 100644
--- a/packages/g6/src/types/combo.ts
+++ b/packages/g6/src/types/combo.ts
@@ -8,12 +8,12 @@ import {
IItem,
ItemShapeStyles,
LabelBackground,
+ LodLevel,
ShapeAttrEncode,
- ShapesEncode,
ShapeStyle,
- LodLevel,
+ ShapesEncode,
} from './item';
-import { NodeShapeMap, NodeUserModelData } from './node';
+import { NodeShapeMap } from './node';
export type ComboLabelPosition =
| 'bottom'
diff --git a/packages/g6/src/types/data.ts b/packages/g6/src/types/data.ts
index cf8c68f3374..5ebc9692b4c 100644
--- a/packages/g6/src/types/data.ts
+++ b/packages/g6/src/types/data.ts
@@ -1,13 +1,8 @@
import { Graph as GraphLib, TreeData as ITreeData } from '@antv/graphlib';
import { AVAILABLE_DATA_LIFECYCLE } from '../util/data';
import { ComboUserModel } from './combo';
-import {
- NodeDisplayModelData,
- NodeModelData,
- NodeUserModel,
- NodeUserModelData,
-} from './node';
import { EdgeDisplayModelData, EdgeModelData, EdgeUserModel } from './edge';
+import { NodeDisplayModelData, NodeModelData, NodeUserModel, NodeUserModelData } from './node';
export interface GraphData {
nodes?: NodeUserModel[];
@@ -21,9 +16,7 @@ export interface GraphDataChanges {
dataRemoved: GraphData;
}
-export type TreeData =
- | ITreeData
- | ITreeData[];
+export type TreeData = ITreeData | ITreeData[];
export interface InlineGraphDataConfig {
type: 'graphData';
@@ -39,17 +32,10 @@ export interface FetchDataConfig {
value: string;
}
-export type DataConfig =
- | GraphData
- | InlineGraphDataConfig
- | InlineTreeDataConfig
- | FetchDataConfig;
+export type DataConfig = GraphData | InlineGraphDataConfig | InlineTreeDataConfig | FetchDataConfig;
export type GraphCore = GraphLib;
-export type DisplayGraphCore = GraphLib<
- NodeDisplayModelData,
- EdgeDisplayModelData
->;
+export type DisplayGraphCore = GraphLib;
export type TransformerFn = (data: GraphData) => GraphData;
diff --git a/packages/g6/src/types/edge.ts b/packages/g6/src/types/edge.ts
index 1c5fa250cf1..fcf184beac5 100644
--- a/packages/g6/src/types/edge.ts
+++ b/packages/g6/src/types/edge.ts
@@ -80,8 +80,7 @@ export interface EdgeShapeStyles extends ItemShapeStyles {
};
}
-export type EdgeDisplayModelData = EdgeModelData &
- EdgeShapeStyles & { lodLevels?: LodLevel[] };
+export type EdgeDisplayModelData = EdgeModelData & EdgeShapeStyles & { lodLevels?: LodLevel[] };
/** User input data. */
export type EdgeUserModel = GEdge;
@@ -122,14 +121,7 @@ export interface EdgeShapeMap {
// TODO
export type IEdge = IItem;
-export type ArrowType =
- | 'triangle'
- | 'circle'
- | 'diamond'
- | 'rect'
- | 'vee'
- | 'triangle-rect'
- | 'simple';
+export type ArrowType = 'triangle' | 'circle' | 'diamond' | 'rect' | 'vee' | 'triangle-rect' | 'simple';
export type ArrowStyle = PathStyleProps & {
type: ArrowType;
diff --git a/packages/g6/src/types/event.ts b/packages/g6/src/types/event.ts
index 98a22ddba8b..b792e47a0f7 100644
--- a/packages/g6/src/types/event.ts
+++ b/packages/g6/src/types/event.ts
@@ -37,8 +37,7 @@ export enum DOM_EVENT_TYPE {
/** Event type union */
export type ICanvasEventType = `${CANVAS_EVENT_TYPE}`;
-export interface IG6GraphEvent
- extends Omit {
+export interface IG6GraphEvent extends Omit {
currentTarget: IGraph;
itemType: 'node' | 'edge' | 'combo' | 'canvas';
itemId: ID;
diff --git a/packages/g6/src/types/graph.ts b/packages/g6/src/types/graph.ts
index 9f70b1f3e0b..0f37b9df017 100644
--- a/packages/g6/src/types/graph.ts
+++ b/packages/g6/src/types/graph.ts
@@ -5,38 +5,21 @@ import { Command } from '../stdlib/plugin/history/command';
import { Hooks } from '../types/hook';
import { CameraAnimationOptions } from './animate';
import { BehaviorOptionsOf, BehaviorRegistry } from './behavior';
-import {
- ComboDisplayModel,
- ComboModel,
- ComboShapesEncode,
- ComboUserModel,
-} from './combo';
+import { ComboDisplayModel, ComboModel, ComboShapesEncode, ComboUserModel } from './combo';
import { Padding, Point } from './common';
import { GraphData } from './data';
-import {
- EdgeDisplayModel,
- EdgeModel,
- EdgeShapesEncode,
- EdgeUserModel,
-} from './edge';
+import { EdgeDisplayModel, EdgeModel, EdgeShapesEncode, EdgeUserModel } from './edge';
import type { StackType } from './history';
import { ITEM_TYPE, SHAPE_TYPE, ShapeStyle } from './item';
import { LayoutOptions } from './layout';
-import {
- NodeDisplayModel,
- NodeModel,
- NodeShapesEncode,
- NodeUserModel,
-} from './node';
+import { NodeDisplayModel, NodeModel, NodeShapesEncode, NodeUserModel } from './node';
import { RendererName } from './render';
import { ComboMapper, EdgeMapper, NodeMapper, Specification } from './spec';
import { ThemeOptionsOf, ThemeRegistry } from './theme';
import { FitViewRules, GraphTransformOptions } from './view';
-export interface IGraph<
- B extends BehaviorRegistry = BehaviorRegistry,
- T extends ThemeRegistry = ThemeRegistry,
-> extends EventEmitter {
+export interface IGraph
+ extends EventEmitter {
[x: string]: any;
hooks: Hooks;
canvas: Canvas;
@@ -63,36 +46,27 @@ export interface IGraph<
updateTheme: (theme: ThemeOptionsOf) => void;
/**
* Update the item display mapper for a specific item type.
- * @param {ITEM_TYPE} type - The type of item (node, edge, or combo).
- * @param {NodeMapper | EdgeMapper | ComboMapper} mapper - The mapper to be updated.
- * */
- updateMapper: (
- type: ITEM_TYPE,
- mapper: NodeMapper | EdgeMapper | ComboMapper,
- ) => void;
+ * @param type - The type of item (node, edge, or combo).
+ * @param mapper - The mapper to be updated.
+ */
+ updateMapper: (type: ITEM_TYPE, mapper: NodeMapper | EdgeMapper | ComboMapper) => void;
/**
* Updates the state configuration for the specified item type, corresponds to the nodeState, edgeState, or comboState on the graph spec.
- * @param {string} itemType - The type of item (node, edge, or combo).
- * @param {object} stateConfig - The state configuration to update.
- * @param {string} updateType - The type of update ('mergeReplace' or 'replace'). Default is 'mergeReplace'.
- **/
+ * @param itemType - The type of item (node, edge, or combo).
+ * @param stateConfig - The state configuration to update.
+ * @param updateType - The type of update ('mergeReplace' or 'replace'). Default is 'mergeReplace'.
+ */
updateStateConfig: (
itemType: ITEM_TYPE,
stateConfig:
| {
- [stateName: string]:
- | ((data: NodeModel) => NodeDisplayModel)
- | NodeShapesEncode;
+ [stateName: string]: ((data: NodeModel) => NodeDisplayModel) | NodeShapesEncode;
}
| {
- [stateName: string]:
- | ((data: EdgeModel) => EdgeDisplayModel)
- | EdgeShapesEncode;
+ [stateName: string]: ((data: EdgeModel) => EdgeDisplayModel) | EdgeShapesEncode;
}
| {
- [stateName: string]:
- | ((data: ComboModel) => ComboDisplayModel)
- | ComboShapesEncode;
+ [stateName: string]: ((data: ComboModel) => ComboDisplayModel) | ComboShapesEncode;
},
updateType?: 'mergeReplace' | 'replace',
) => void;
@@ -154,30 +128,21 @@ export interface IGraph<
* @returns one-hop edge ids
* @group Data
*/
- getRelatedEdgesData: (
- nodeId: ID,
- direction?: 'in' | 'out' | 'both',
- ) => EdgeModel[];
+ getRelatedEdgesData: (nodeId: ID, direction?: 'in' | 'out' | 'both') => EdgeModel[];
/**
* Get nearby edges from a start node using quad-tree collision detection.
* @param nodeId id of the start node
* @returns nearby edges' data array
* @group Data
*/
- getNearEdgesData: (
- nodeId: ID,
- shouldBegin?: (edge: EdgeDisplayModel) => boolean,
- ) => EdgeModel[];
+ getNearEdgesData: (nodeId: ID, shouldBegin?: (edge: EdgeDisplayModel) => boolean) => EdgeModel[];
/**
* Get one-hop node ids from a start node.
* @param nodeId id of the start node
* @returns one-hop node ids
* @group Data
*/
- getNeighborNodesData: (
- nodeId: ID,
- direction?: 'in' | 'out' | 'both',
- ) => NodeModel[];
+ getNeighborNodesData: (nodeId: ID, direction?: 'in' | 'out' | 'both') => NodeModel[];
/*
* Get the children's data of a combo.
* @param comboId combo id
@@ -207,11 +172,7 @@ export interface IGraph<
* @returns
* @group Data
*/
- changeData: (
- data: GraphData,
- type?: 'replace' | 'mergeReplace',
- relayout?: boolean,
- ) => void;
+ changeData: (data: GraphData, type?: 'replace' | 'mergeReplace', relayout?: boolean) => void;
/**
* Clear the graph, means remove all the items on the graph.
* @returns
@@ -242,20 +203,8 @@ export interface IGraph<
*/
addData: (
itemType: ITEM_TYPE,
- model:
- | NodeUserModel
- | EdgeUserModel
- | ComboUserModel
- | NodeUserModel[]
- | EdgeUserModel[]
- | ComboUserModel[],
- ) =>
- | NodeModel
- | EdgeModel
- | ComboModel
- | NodeModel[]
- | EdgeModel[]
- | ComboModel[];
+ model: NodeUserModel | EdgeUserModel | ComboUserModel | NodeUserModel[] | EdgeUserModel[] | ComboUserModel[],
+ ) => NodeModel | EdgeModel | ComboModel | NodeModel[] | EdgeModel[] | ComboModel[];
/**
* Remove one or more node/edge/combo data from the graph.
* @param itemType the type the item(s) to be removed.
@@ -275,19 +224,8 @@ export interface IGraph<
model:
| Partial
| Partial
- | Partial<
- | ComboUserModel
- | Partial[]
- | Partial[]
- | Partial[]
- >,
- ) =>
- | NodeModel
- | EdgeModel
- | ComboModel
- | NodeModel[]
- | EdgeModel[]
- | ComboModel[];
+ | Partial[] | Partial[] | Partial[]>,
+ ) => NodeModel | EdgeModel | ComboModel | NodeModel[] | EdgeModel[] | ComboModel[];
/**
* Update one or more nodes' positions,
@@ -299,17 +237,10 @@ export interface IGraph<
* @group Data
*/
updateNodePosition: (
- models:
- | Partial
- | Partial<
- ComboUserModel | Partial[] | Partial[]
- >,
+ models: Partial | Partial[] | Partial[]>,
upsertAncestors?: boolean,
disableAnimate?: boolean,
- callback?: (
- model: NodeModel | EdgeModel | ComboModel,
- canceled?: boolean,
- ) => void,
+ callback?: (model: NodeModel | EdgeModel | ComboModel, canceled?: boolean) => void,
) => NodeModel | ComboModel | NodeModel[] | ComboModel[];
/**
@@ -322,11 +253,7 @@ export interface IGraph<
* @group Data
*/
updateComboPosition: (
- models:
- | Partial
- | Partial<
- ComboUserModel | Partial[] | Partial[]
- >,
+ models: Partial | Partial[] | Partial[]>,
upsertAncestors?: boolean,
disableAnimate?: boolean,
callback?: (model: NodeModel | EdgeModel | ComboModel) => void,
@@ -348,10 +275,7 @@ export interface IGraph<
dx: number,
dy: number,
upsertAncestors?: boolean,
- callback?: (
- model: NodeModel | EdgeModel | ComboModel,
- canceled?: boolean,
- ) => void,
+ callback?: (model: NodeModel | EdgeModel | ComboModel, canceled?: boolean) => void,
) => ComboModel[];
// ===== view operations =====
@@ -377,10 +301,7 @@ export interface IGraph<
* @param effectTiming animation configurations
* @group View
*/
- translateTo: (
- point: PointLike,
- effectTiming?: CameraAnimationOptions,
- ) => Promise;
+ translateTo: (point: PointLike, effectTiming?: CameraAnimationOptions) => Promise;
/**
* Return the current zoom level of camera.
* @returns current zoom
@@ -394,11 +315,7 @@ export interface IGraph<
* @param effectTiming animation configurations
* @group View
*/
- zoom: (
- ratio: number,
- center?: Point,
- effectTiming?: CameraAnimationOptions,
- ) => Promise;
+ zoom: (ratio: number, center?: Point, effectTiming?: CameraAnimationOptions) => Promise;
/**
* Zoom the graph to a specified ratio.
* @param toRatio specified ratio
@@ -406,11 +323,7 @@ export interface IGraph<
* @param effectTiming animation configurations
* @group View
*/
- zoomTo: (
- toRatio: number,
- center?: Point,
- effectTiming?: CameraAnimationOptions,
- ) => Promise;
+ zoomTo: (toRatio: number, center?: Point, effectTiming?: CameraAnimationOptions) => Promise;
/**
* Rotate the graph with a relative angle in clockwise.
* @param angle
@@ -418,11 +331,7 @@ export interface IGraph<
* @param effectTiming
* @group View
*/
- rotate: (
- angle: number,
- center?: Point,
- effectTiming?: CameraAnimationOptions,
- ) => Promise;
+ rotate: (angle: number, center?: Point, effectTiming?: CameraAnimationOptions) => Promise;
/**
* Rotate the graph to an absolute angle in clockwise.
* @param toAngle
@@ -430,11 +339,7 @@ export interface IGraph<
* @param effectTiming
* @group View
*/
- rotateTo: (
- toAngle: number,
- center?: Point,
- effectTiming?: CameraAnimationOptions,
- ) => Promise;
+ rotateTo: (toAngle: number, center?: Point, effectTiming?: CameraAnimationOptions) => Promise;
/**
* Transform the graph with a CSS-Transform-like syntax.
@@ -442,10 +347,7 @@ export interface IGraph<
* @param effectTiming
* @group View
*/
- transform: (
- options: GraphTransformOptions,
- effectTiming?: CameraAnimationOptions,
- ) => Promise;
+ transform: (options: GraphTransformOptions, effectTiming?: CameraAnimationOptions) => Promise;
/**
* Stop the current transition of transform immediately.
* @group View
@@ -477,20 +379,14 @@ export interface IGraph<
* @returns
* @group View
*/
- fitCenter: (
- boundsType?: 'render' | 'layout',
- effectTiming?: CameraAnimationOptions,
- ) => Promise;
+ fitCenter: (boundsType?: 'render' | 'layout', effectTiming?: CameraAnimationOptions) => Promise