From cb7a763446cf5e0e0d064f6a70cb7e96b86819b7 Mon Sep 17 00:00:00 2001 From: Aaron Date: Thu, 28 Dec 2023 11:05:09 +0800 Subject: [PATCH] chore: optimize project configs (#5299) * chore: optimize project configs --- .eslintignore | 4 + .eslintrc.js | 56 ++ .gitignore | 11 +- .prettierignore | 4 + .prettierrc | 11 - .../.prettierrc.js => .prettierrc.js | 3 +- package.json | 52 +- packages/g6-plugin-map-view/.eslintignore | 6 - packages/g6-plugin-map-view/.eslintrc | 40 - packages/g6-plugin-map-view/.prettierrc | 11 - packages/g6-plugin-map-view/package.json | 47 +- .../{rollup.config.js => rollup.config.mjs} | 17 +- packages/g6-plugin-map-view/src/index.ts | 117 +-- packages/g6-plugin-map-view/tsconfig.json | 27 +- packages/g6/.eslintignore | 6 - packages/g6/.eslintrc | 41 - packages/g6/.gitignore | 2 + packages/g6/.prettierrc | 11 - packages/g6/package.json | 93 +- .../{rollup.config.js => rollup.config.mjs} | 17 +- packages/g6/sidebars.js | 11 - packages/g6/src/api-doc/graph.ts | 2 +- packages/g6/src/api-doc/item.ts | 47 +- packages/g6/src/item/combo.ts | 46 +- packages/g6/src/item/edge.ts | 103 +- packages/g6/src/item/item.ts | 244 ++--- packages/g6/src/item/node.ts | 109 +-- packages/g6/src/runtime/controller/data.ts | 228 ++--- packages/g6/src/runtime/controller/index.ts | 4 +- .../g6/src/runtime/controller/interaction.ts | 79 +- packages/g6/src/runtime/controller/item.ts | 668 ++++--------- packages/g6/src/runtime/controller/layout.ts | 122 +-- packages/g6/src/runtime/controller/plugin.ts | 48 +- packages/g6/src/runtime/controller/theme.ts | 6 +- .../g6/src/runtime/controller/viewport.ts | 52 +- packages/g6/src/runtime/graph.ts | 716 ++++---------- .../src/stdlib/behavior/activate-relations.ts | 24 +- .../g6/src/stdlib/behavior/brush-select.ts | 71 +- .../g6/src/stdlib/behavior/click-select.ts | 15 +- .../stdlib/behavior/collapse-expand-combo.ts | 5 - .../stdlib/behavior/collapse-expand-tree.ts | 4 +- .../g6/src/stdlib/behavior/create-edge.ts | 31 +- .../g6/src/stdlib/behavior/drag-canvas.ts | 66 +- packages/g6/src/stdlib/behavior/drag-combo.ts | 116 +-- packages/g6/src/stdlib/behavior/drag-node.ts | 233 ++--- .../g6/src/stdlib/behavior/hover-activate.ts | 2 +- packages/g6/src/stdlib/behavior/index.ts | 12 +- .../g6/src/stdlib/behavior/lasso-select.ts | 12 +- .../src/stdlib/behavior/rotate-canvas-3d.ts | 2 +- .../g6/src/stdlib/behavior/scroll-canvas.ts | 52 +- .../g6/src/stdlib/behavior/shortcuts-call.ts | 8 +- .../g6/src/stdlib/behavior/zoom-canvas-3d.ts | 24 +- .../g6/src/stdlib/behavior/zoom-canvas.ts | 89 +- packages/g6/src/stdlib/data/index.ts | 2 +- packages/g6/src/stdlib/data/mapNodeSize.ts | 19 +- .../src/stdlib/data/processParallelEdges.ts | 44 +- .../g6/src/stdlib/data/transformV4Data.ts | 51 +- packages/g6/src/stdlib/data/validateData.ts | 67 +- packages/g6/src/stdlib/index.ts | 37 +- packages/g6/src/stdlib/item/combo/circle.ts | 51 +- packages/g6/src/stdlib/item/combo/rect.ts | 57 +- packages/g6/src/stdlib/item/edge/base.ts | 202 ++-- .../src/stdlib/item/edge/cubic-horizontal.ts | 38 +- .../g6/src/stdlib/item/edge/cubic-vertical.ts | 44 +- packages/g6/src/stdlib/item/edge/cubic.ts | 84 +- packages/g6/src/stdlib/item/edge/index.ts | 10 +- packages/g6/src/stdlib/item/edge/line.ts | 43 +- packages/g6/src/stdlib/item/edge/loop.ts | 37 +- packages/g6/src/stdlib/item/edge/polyline.ts | 76 +- packages/g6/src/stdlib/item/edge/quadratic.ts | 64 +- packages/g6/src/stdlib/item/node/base.ts | 202 ++-- packages/g6/src/stdlib/item/node/base3d.ts | 50 +- packages/g6/src/stdlib/item/node/circle.ts | 67 +- packages/g6/src/stdlib/item/node/cube.ts | 43 +- packages/g6/src/stdlib/item/node/diamond.ts | 55 +- packages/g6/src/stdlib/item/node/donut.ts | 80 +- packages/g6/src/stdlib/item/node/ellipse.ts | 54 +- packages/g6/src/stdlib/item/node/hexagon.ts | 82 +- packages/g6/src/stdlib/item/node/image.ts | 40 +- packages/g6/src/stdlib/item/node/index.ts | 22 +- packages/g6/src/stdlib/item/node/modelRect.ts | 137 +-- packages/g6/src/stdlib/item/node/plane.ts | 43 +- packages/g6/src/stdlib/item/node/rect.ts | 63 +- packages/g6/src/stdlib/item/node/sphere.ts | 43 +- packages/g6/src/stdlib/item/node/star.ts | 94 +- packages/g6/src/stdlib/item/node/triangle.ts | 142 +-- .../src/stdlib/plugin/edgeBundling/index.ts | 75 +- .../src/stdlib/plugin/edgeFilterLens/index.ts | 53 +- .../g6/src/stdlib/plugin/fisheye/index.ts | 65 +- packages/g6/src/stdlib/plugin/grid/index.ts | 14 +- .../stdlib/plugin/history/combo-command.ts | 8 +- .../g6/src/stdlib/plugin/history/command.ts | 25 +- .../g6/src/stdlib/plugin/history/index.ts | 60 +- .../plugin/history/item-data-command.ts | 25 +- .../plugin/history/layer-updated-command.ts | 8 +- .../g6/src/stdlib/plugin/hull/bubbleset.ts | 336 +++---- .../g6/src/stdlib/plugin/hull/convexHull.ts | 19 +- .../src/stdlib/plugin/hull/hullComponent.ts | 78 +- packages/g6/src/stdlib/plugin/hull/index.ts | 52 +- packages/g6/src/stdlib/plugin/hull/util.ts | 112 +-- packages/g6/src/stdlib/plugin/index.ts | 8 +- packages/g6/src/stdlib/plugin/legend/index.ts | 159 +--- .../src/stdlib/plugin/lodController/index.ts | 72 +- packages/g6/src/stdlib/plugin/menu/index.ts | 37 +- .../g6/src/stdlib/plugin/minimap/index.ts | 99 +- .../g6/src/stdlib/plugin/snapline/index.ts | 246 ++--- .../g6/src/stdlib/plugin/timebar/index.ts | 61 +- .../g6/src/stdlib/plugin/toolbar/index.ts | 17 +- .../g6/src/stdlib/plugin/tooltip/index.ts | 47 +- packages/g6/src/stdlib/plugin/types.ts | 6 +- .../g6/src/stdlib/plugin/watermarker/index.ts | 32 +- packages/g6/src/stdlib/selector/lasso.ts | 14 +- packages/g6/src/stdlib/selector/rect.ts | 24 +- packages/g6/src/stdlib/theme/index.ts | 2 +- packages/g6/src/stdlib/themeSolver/base.ts | 5 +- packages/g6/src/stdlib/themeSolver/index.ts | 2 +- packages/g6/src/stdlib/themeSolver/spec.ts | 28 +- packages/g6/src/stdlib/themeSolver/subject.ts | 142 +-- packages/g6/src/types/animate.ts | 10 +- packages/g6/src/types/behavior.ts | 6 +- packages/g6/src/types/combo.ts | 6 +- packages/g6/src/types/data.ts | 22 +- packages/g6/src/types/edge.ts | 12 +- packages/g6/src/types/event.ts | 3 +- packages/g6/src/types/graph.ts | 198 +--- packages/g6/src/types/history.ts | 3 +- packages/g6/src/types/hook.ts | 40 +- packages/g6/src/types/index.ts | 41 +- packages/g6/src/types/item.ts | 49 +- packages/g6/src/types/layout.ts | 16 +- packages/g6/src/types/node.ts | 3 +- packages/g6/src/types/spec.ts | 48 +- packages/g6/src/types/theme.ts | 38 +- packages/g6/src/types/view.ts | 8 +- packages/g6/src/util/animate.ts | 117 +-- packages/g6/src/util/arrow.ts | 6 +- packages/g6/src/util/bbox.ts | 76 +- packages/g6/src/util/behavior.ts | 12 +- packages/g6/src/util/canvas.ts | 7 +- packages/g6/src/util/data.ts | 82 +- packages/g6/src/util/dom.ts | 5 +- packages/g6/src/util/event.ts | 32 +- packages/g6/src/util/extend.ts | 25 +- packages/g6/src/util/extension.ts | 6 +- packages/g6/src/util/index.ts | 16 +- packages/g6/src/util/item.ts | 17 +- packages/g6/src/util/layout.ts | 17 +- packages/g6/src/util/loop.ts | 33 +- packages/g6/src/util/math.ts | 17 +- packages/g6/src/util/matrix.ts | 36 +- packages/g6/src/util/mock.ts | 4 +- packages/g6/src/util/path.ts | 26 +- packages/g6/src/util/point.ts | 42 +- packages/g6/src/util/polyline.ts | 155 ++- packages/g6/src/util/router.ts | 143 +-- packages/g6/src/util/shape.ts | 144 +-- packages/g6/src/util/shape3d.ts | 63 +- packages/g6/src/util/text.ts | 12 +- packages/g6/src/util/warn.ts | 14 +- packages/g6/src/util/zoom.ts | 4 +- packages/g6/tests/bak/items-node-cube.spec.ts | 37 - packages/g6/tests/bak/plugins-legend.spec.ts | 175 ---- .../demo/behaviors/activate-relations.ts | 2 +- .../g6/tests/demo/behaviors/brush-select.ts | 2 +- .../demo/behaviors/collapse-expand-tree.ts | 5 +- .../g6/tests/demo/behaviors/create-edge.ts | 2 +- .../g6/tests/demo/behaviors/shortcuts-call.ts | 2 +- packages/g6/tests/demo/combo/combo-basic.ts | 2 +- packages/g6/tests/demo/combo/combo-rect.ts | 7 +- packages/g6/tests/demo/data/data-from-v4.ts | 26 +- packages/g6/tests/demo/data/graphCore.ts | 11 +- .../tests/demo/data/process-parallel-edges.ts | 10 +- packages/g6/tests/demo/demo/data3d.ts | 15 +- packages/g6/tests/demo/demo/demo.ts | 21 +- packages/g6/tests/demo/demo/demoFor4.ts | 7 +- .../g6/tests/demo/demo/demoForPolyline.ts | 2 +- packages/g6/tests/demo/demo/diamond.ts | 2 +- packages/g6/tests/demo/demo/ellipse.ts | 2 +- packages/g6/tests/demo/demo/hexagon.ts | 2 +- packages/g6/tests/demo/demo/menu.ts | 12 +- packages/g6/tests/demo/demo/modelRect.ts | 2 +- packages/g6/tests/demo/demo/quadratic.ts | 2 +- packages/g6/tests/demo/demo/star.ts | 2 +- packages/g6/tests/demo/demo/tooltip.ts | 12 +- packages/g6/tests/demo/demo/triangle.ts | 2 +- packages/g6/tests/demo/index.ts | 87 +- packages/g6/tests/demo/item/edge/arrow.ts | 12 +- .../g6/tests/demo/item/edge/cubic-edge.ts | 2 +- .../demo/item/edge/cubic-horizontal-edge.ts | 2 +- .../demo/item/edge/cubic-vertical-edge.ts | 2 +- packages/g6/tests/demo/item/edge/loop-edge.ts | 18 +- .../g6/tests/demo/item/edge/polyline-edge.ts | 1 - packages/g6/tests/demo/item/node/cube.ts | 3 +- .../g6/tests/demo/item/node/donut-node.ts | 2 +- .../g6/tests/demo/item/node/image-clip.ts | 5 +- packages/g6/tests/demo/item/node/image.ts | 5 +- .../g6/tests/demo/layouts/combo-combined.ts | 2 +- packages/g6/tests/demo/layouts/d3force.ts | 2 +- packages/g6/tests/demo/layouts/dagre-combo.ts | 10 +- .../g6/tests/demo/layouts/dagre-update.ts | 5 +- packages/g6/tests/demo/layouts/dagre.ts | 2 +- packages/g6/tests/demo/layouts/force-3d.ts | 2 +- .../g6/tests/demo/layouts/force-wasm-3d.ts | 4 +- packages/g6/tests/demo/layouts/force-wasm.ts | 4 +- .../g6/tests/demo/layouts/forceatlas2-wasm.ts | 6 +- .../g6/tests/demo/layouts/fruchterman-wasm.ts | 6 +- packages/g6/tests/demo/performance/fps.ts | 2 +- .../g6/tests/demo/performance/layout-3d.ts | 12 +- packages/g6/tests/demo/performance/layout.ts | 10 +- .../g6/tests/demo/performance/performance.ts | 37 +- .../g6/tests/demo/plugins/edgeBundling.ts | 5 +- .../g6/tests/demo/plugins/edgeFilterLens.ts | 10 +- packages/g6/tests/demo/plugins/fisheye.ts | 18 +- .../g6/tests/demo/plugins/history-combo.ts | 2 +- packages/g6/tests/demo/plugins/hull.ts | 9 +- packages/g6/tests/demo/plugins/legend.ts | 2 +- packages/g6/tests/demo/plugins/map.ts | 2 +- packages/g6/tests/demo/plugins/minimap.ts | 2 +- packages/g6/tests/demo/plugins/snapline.ts | 8 +- .../g6/tests/demo/plugins/timebar-chart.ts | 14 +- .../g6/tests/demo/plugins/timebar-time.ts | 2 +- packages/g6/tests/demo/plugins/toolbar.ts | 4 +- packages/g6/tests/demo/plugins/watermarker.ts | 14 +- packages/g6/tests/demo/tree/treeGraph.ts | 19 +- packages/g6/tests/demo/visual/visual.ts | 9 +- packages/g6/tests/index.html | 2 +- packages/g6/tests/integration/anchor.spec.ts | 41 +- .../animations-node-build-in.spec.ts | 31 +- .../integration/api-update-mapper.spec.ts | 48 +- .../behaviors-activate-relations.spec.ts | 27 +- .../behaviors-collapse-expand-tree.spec.ts | 39 +- .../integration/behaviors-create-edge.spec.ts | 54 +- .../behaviors-scroll-canvas.spec.ts | 22 +- .../behaviors-shortcuts-call.spec.ts | 39 +- .../g6/tests/integration/combo-render.spec.ts | 26 +- .../data-process-parallel-edges.spec.ts | 44 +- .../tests/integration/data-validate.spec.ts | 140 +-- .../integration/items-edge-arrow.spec.ts | 53 +- .../tests/integration/items-edge-line.spec.ts | 39 +- .../tests/integration/items-edge-loop.spec.ts | 30 +- .../integration/items-edge-polyline.spec.ts | 54 +- .../integration/items-node-donut.spec.ts | 46 +- .../integration/items-node-image.spec.ts | 14 +- .../integration/layouts-circular.spec.ts | 12 +- .../tests/integration/layouts-d3force.spec.ts | 12 +- .../tests/integration/layouts-dagre.spec.ts | 12 +- .../tests/integration/layouts-force.spec.ts | 12 +- .../tests/integration/layouts-force3d.spec.ts | 5 +- .../g6/tests/integration/layouts-grid.spec.ts | 12 +- .../g6/tests/integration/node-diamond.spec.ts | 14 +- .../g6/tests/integration/node-ellipse.spec.ts | 14 +- .../g6/tests/integration/node-hexagon.spec.ts | 14 +- .../tests/integration/node-modelRect.spec.ts | 14 +- .../g6/tests/integration/node-star.spec.ts | 14 +- .../tests/integration/node-triangle.spec.ts | 14 +- .../plugins-edgeFilterLens.spec.ts | 17 +- .../integration/plugins-history-combo.spec.ts | 33 +- .../tests/integration/plugins-history.spec.ts | 161 +--- .../g6/tests/integration/plugins-hull.spec.ts | 116 +-- .../integration/plugins-watermarker.spec.ts | 17 +- .../tests/integration/timebar-chart.spec.ts | 12 +- .../integration/timebar-timeline.spec.ts | 12 +- .../tests/integration/toolbar-default.spec.ts | 12 +- .../integration/treegraph-render.spec.ts | 113 +-- .../integration/utils/createNodeGCanvas.ts | 20 +- packages/g6/tests/integration/utils/event.ts | 14 +- .../utils/offscreenCanvasContext.ts | 8 +- .../integration/utils/toMatchSVGSnapshot.ts | 29 +- .../integration/utils/useSnapshotMatchers.ts | 11 +- packages/g6/tests/main.ts | 16 +- packages/g6/tests/unit/behavior-spec.ts | 6 +- .../tests/unit/behaviors/brush-select-spec.ts | 12 +- .../tests/unit/behaviors/drag-canvas-spec.ts | 24 +- .../tests/unit/behaviors/lasso-select-spec.ts | 12 +- .../tests/unit/behaviors/zoom-canvas-spec.ts | 12 +- packages/g6/tests/unit/click-select-spec.ts | 2 - packages/g6/tests/unit/data-spec.ts | 39 +- packages/g6/tests/unit/drag-node-spec.ts | 14 +- packages/g6/tests/unit/edge-spec.ts | 886 ++++-------------- packages/g6/tests/unit/ellipse-spec.ts | 105 +-- packages/g6/tests/unit/hexagon-spec.ts | 88 +- packages/g6/tests/unit/item-animate-spec.ts | 57 +- packages/g6/tests/unit/layout-spec.ts | 16 +- packages/g6/tests/unit/node-spec.ts | 241 +---- .../tests/unit/plugins/edgebundling-spec.ts | 31 +- packages/g6/tests/unit/plugins/grid-spec.ts | 1 - packages/g6/tests/unit/plugins/legend-spec.ts | 1 - packages/g6/tests/unit/plugins/menu-spec.ts | 32 +- .../g6/tests/unit/plugins/minimap-spec.ts | 63 +- .../g6/tests/unit/plugins/tooltip-spec.ts | 26 +- packages/g6/tests/unit/quadratic-spec.ts | 495 ++-------- packages/g6/tests/unit/rect-spec.ts | 4 +- packages/g6/tests/unit/show-animate-spec.ts | 29 +- packages/g6/tests/unit/star-spec.ts | 88 +- packages/g6/tests/unit/theme-spec.ts | 192 ++-- packages/g6/tests/unit/theme-subject-spec.ts | 33 +- packages/g6/tests/unit/triangle-spec.ts | 105 +-- packages/g6/tsconfig.json | 27 +- packages/g6/typedoc.config.js | 40 - packages/react-node/.editorconfig | 13 - packages/react-node/.eslintrc.js | 3 - packages/react-node/.gitignore | 1 - packages/react-node/.prettierignore | 2 - packages/react-node/package.json | 1 - packages/react-node/tsconfig.json | 6 +- packages/site/.dumirc.ts | 29 +- packages/site/.eslintignore | 22 - packages/site/.eslintrc.js | 47 - packages/site/.gitignore | 8 - packages/site/.prettierrc | 11 - packages/site/.translate-info.txt | 61 -- packages/site/api-extractor.json | 15 - packages/site/docs/apis/.nojekyll | 5 - packages/site/package.json | 19 +- packages/site/scripts/find-unused-demos.js | 47 - packages/site/translate-api-doc.mjs | 110 --- packages/site/tsconfig.json | 4 +- tsconfig.json | 17 + 318 files changed, 3973 insertions(+), 10860 deletions(-) create mode 100644 .eslintignore create mode 100644 .eslintrc.js create mode 100644 .prettierignore delete mode 100644 .prettierrc rename packages/react-node/.prettierrc.js => .prettierrc.js (87%) delete mode 100644 packages/g6-plugin-map-view/.eslintignore delete mode 100644 packages/g6-plugin-map-view/.eslintrc delete mode 100644 packages/g6-plugin-map-view/.prettierrc rename packages/g6-plugin-map-view/{rollup.config.js => rollup.config.mjs} (60%) delete mode 100644 packages/g6/.eslintignore delete mode 100644 packages/g6/.eslintrc create mode 100644 packages/g6/.gitignore delete mode 100644 packages/g6/.prettierrc rename packages/g6/{rollup.config.js => rollup.config.mjs} (59%) delete mode 100644 packages/g6/sidebars.js delete mode 100644 packages/g6/tests/bak/items-node-cube.spec.ts delete mode 100644 packages/g6/tests/bak/plugins-legend.spec.ts delete mode 100644 packages/g6/typedoc.config.js delete mode 100644 packages/react-node/.editorconfig delete mode 100644 packages/react-node/.eslintrc.js delete mode 100644 packages/react-node/.prettierignore delete mode 100644 packages/site/.eslintignore delete mode 100644 packages/site/.eslintrc.js delete mode 100644 packages/site/.prettierrc delete mode 100644 packages/site/.translate-info.txt delete mode 100644 packages/site/api-extractor.json delete mode 100644 packages/site/docs/apis/.nojekyll delete mode 100644 packages/site/scripts/find-unused-demos.js delete mode 100644 packages/site/translate-api-doc.mjs create mode 100644 tsconfig.json 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; /** * Move the graph to make the item align the view center. * @param item node/edge/combo item or its id * @param effectTiming animation configurations * @group View */ - focusItem: ( - id: ID | ID[], - effectTiming?: CameraAnimationOptions, - ) => Promise; + focusItem: (id: ID | ID[], effectTiming?: CameraAnimationOptions) => Promise; /** * Get the size of the graph canvas. * @returns [width, height] @@ -543,10 +439,7 @@ export interface IGraph< * @returns * @group Data */ - showItem: ( - ids: ID | ID[], - options?: { disableAnimate?: boolean; shapeIds?: string[] }, - ) => void; + showItem: (ids: ID | ID[], options?: { disableAnimate?: boolean; shapeIds?: string[] }) => void; /** * Hide the item(s). * @param ids the item id(s) to be hidden @@ -614,11 +507,7 @@ export interface IGraph< * @param id the id for the node / edge / combo, undefined for the whole graph * @returns rendering bounding box. returns false if the item is not exist */ - getRenderBBox: ( - id: ID | undefined, - onlyKeyShape?: boolean, - isTransient?: boolean, - ) => AABB | false; + getRenderBBox: (id: ID | undefined, onlyKeyShape?: boolean, isTransient?: boolean) => AABB | false; /** * Get the visibility for a node / edge / combo. @@ -693,10 +582,7 @@ export interface IGraph< * @returns * @group Interaction */ - addBehaviors: ( - behaviors: BehaviorOptionsOf | BehaviorOptionsOf[], - modes: string | string[], - ) => void; + addBehaviors: (behaviors: BehaviorOptionsOf | BehaviorOptionsOf[], modes: string | string[]) => void; /** * Remove behavior(s) from mode(s). * @param behaviors behavior names or configs @@ -771,11 +657,7 @@ export interface IGraph< * @returns * @group Plugin */ - updatePlugin: (pluginCfg: { - key: string; - type: string; - [cfgName: string]: unknown; - }) => void; + updatePlugin: (pluginCfg: { key: string; type: string; [cfgName: string]: unknown }) => void; // ===== history operations ===== diff --git a/packages/g6/src/types/history.ts b/packages/g6/src/types/history.ts index dbbacac2c5d..62c8d353e25 100644 --- a/packages/g6/src/types/history.ts +++ b/packages/g6/src/types/history.ts @@ -3,7 +3,8 @@ export type StackCfg = { stackSize?: number; /** Indicate whether the stack is active. If active, operations can be pushed onto the stack; otherwise, cannot. */ stackActive?: boolean; - /** Allows finer-grained control over the ignore option. + /** + * Allows finer-grained control over the ignore option. * If an API is in excludes, even if its operation type is not ignored, it will not be put on the stack */ excludes?: string[]; diff --git a/packages/g6/src/types/hook.ts b/packages/g6/src/types/hook.ts index e240bc7e7e8..d93913964b1 100644 --- a/packages/g6/src/types/hook.ts +++ b/packages/g6/src/types/hook.ts @@ -2,26 +2,16 @@ import { Canvas } from '@antv/g'; import { GraphChange, ID } from '@antv/graphlib'; import { CameraAnimationOptions } from './animate'; import { BehaviorOptionsOf } from './behavior'; +import { ComboDisplayModel, ComboModel, ComboShapesEncode } from './combo'; import { DataChangeType, DataConfig, GraphCore } from './data'; -import { - EdgeDisplayModel, - EdgeModel, - EdgeModelData, - EdgeShapesEncode, -} from './edge'; -import { ITEM_TYPE, ShapeStyle, SHAPE_TYPE } from './item'; +import { EdgeDisplayModel, EdgeModel, EdgeModelData, EdgeShapesEncode } from './edge'; +import { ITEM_TYPE, SHAPE_TYPE, ShapeStyle } from './item'; import { LayoutOptions } from './layout'; -import { - NodeDisplayModel, - NodeModel, - NodeModelData, - NodeShapesEncode, -} from './node'; -import { ThemeSpecification } from './theme'; -import { GraphTransformOptions } from './view'; -import { ComboDisplayModel, ComboModel, ComboShapesEncode } from './combo'; +import { NodeDisplayModel, NodeModel, NodeModelData, NodeShapesEncode } from './node'; import { Plugin as PluginBase } from './plugin'; import { ComboMapper, EdgeMapper, NodeMapper } from './spec'; +import { ThemeSpecification } from './theme'; +import { GraphTransformOptions } from './view'; export interface IHook { name: string; @@ -97,19 +87,13 @@ export interface Hooks { 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; }; }>; itemvisibilitychange: IHook<{ @@ -154,11 +138,7 @@ export interface Hooks { viewportchange: IHook; pluginchange: IHook<{ action: 'update' | 'add' | 'remove'; - plugins: ( - | string - | { key: string; type: string; [cfgName: string]: unknown } - | PluginBase - )[]; + plugins: (string | { key: string; type: string; [cfgName: string]: unknown } | PluginBase)[]; }>; themechange: IHook<{ theme?: ThemeSpecification; diff --git a/packages/g6/src/types/index.ts b/packages/g6/src/types/index.ts index 8fdee545594..429ad135b67 100644 --- a/packages/g6/src/types/index.ts +++ b/packages/g6/src/types/index.ts @@ -1,17 +1,7 @@ export type { ID } from '@antv/graphlib'; -export type { IAnimate, IAnimates, AnimateTiming, AnimateCfg } from './animate'; +export type { AnimateCfg, AnimateTiming, IAnimate, IAnimates } from './animate'; export { Behavior } from './behavior'; export type { BehaviorOptionsOf, BehaviorRegistry } from './behavior'; -export type { - NodeDisplayModel, - NodeModel, - NodeUserModel, - NodeEncode, - NodeShapeStyles, - NodeLabelPosition, - NodeShapesEncode, - NodeModelData, -} from './node'; export type { ComboDisplayModel, ComboLabelPosition, @@ -22,13 +12,7 @@ export type { ComboUserModel, } from './combo'; export type { Point } from './common'; -export type { - DataConfig, - DisplayGraphCore, - GraphCore, - GraphData, - TreeData, -} from './data'; +export type { DataConfig, DisplayGraphCore, GraphCore, GraphData, TreeData } from './data'; export type { EdgeDisplayModel, EdgeLabelPosition, @@ -41,16 +25,19 @@ export type { export type { ICanvasEventType, IG6GraphEvent } from './event'; export type { IGraph } from './graph'; export type { StackCfg } from './history'; -export { - isImmediatelyInvokedLayoutOptions, - isLayoutWorkerized, -} from './layout'; // function 不应该放在 types 文件下面 +export { isImmediatelyInvokedLayoutOptions, isLayoutWorkerized } from './layout'; // function 不应该放在 types 文件下面 +export type { ImmediatelyInvokedLayoutOptions, LayoutOptions, StandardLayoutOptions } from './layout'; export type { - ImmediatelyInvokedLayoutOptions, - LayoutOptions, - StandardLayoutOptions, -} from './layout'; -export type { IPluginBaseConfig } from './plugin'; + NodeDisplayModel, + NodeEncode, + NodeLabelPosition, + NodeModel, + NodeModelData, + NodeShapeStyles, + NodeShapesEncode, + NodeUserModel, +} from './node'; export { Plugin as PluginBase } from './plugin'; +export type { IPluginBaseConfig } from './plugin'; export type { Specification } from './spec'; export type { ThemeSpecification } from './theme'; diff --git a/packages/g6/src/types/item.ts b/packages/g6/src/types/item.ts index 72ed6f49c05..343fdae4685 100644 --- a/packages/g6/src/types/item.ts +++ b/packages/g6/src/types/item.ts @@ -14,36 +14,12 @@ import { RectStyleProps, TextStyleProps, } from '@antv/g'; -import { - CubeGeometryProps, - PlaneGeometryProps, - SphereGeometryProps, -} from '@antv/g-plugin-3d'; +import { CubeGeometryProps, PlaneGeometryProps, SphereGeometryProps } from '@antv/g-plugin-3d'; import { ID } from '@antv/graphlib'; -import { AnimateCfg, IAnimates } from './animate'; -import { - ComboDisplayModel, - ComboEncode, - ComboModel, - ComboModelData, - ComboUserModel, -} from './combo'; -import { - EdgeDisplayModel, - EdgeEncode, - EdgeModel, - EdgeModelData, - EdgeShapeMap, - EdgeUserModel, -} from './edge'; -import { - NodeDisplayModel, - NodeEncode, - NodeModel, - NodeModelData, - NodeShapeMap, - NodeUserModel, -} from './node'; +import { IAnimates } from './animate'; +import { ComboDisplayModel, ComboEncode, ComboModel, ComboModelData, ComboUserModel } from './combo'; +import { EdgeDisplayModel, EdgeEncode, EdgeModel, EdgeModelData, EdgeShapeMap, EdgeUserModel } from './edge'; +import { NodeDisplayModel, NodeEncode, NodeModel, NodeModelData, NodeShapeMap, NodeUserModel } from './node'; import { ComboStyleSet, EdgeStyleSet, NodeStyleSet } from './theme'; export type GShapeStyle = CircleStyleProps & @@ -125,16 +101,9 @@ export type ItemModelData = NodeModelData | EdgeModelData | ComboModelData; export type ItemModel = NodeModel | EdgeModel | ComboModel; -export type ItemDisplayModel = - | NodeDisplayModel - | EdgeDisplayModel - | ComboDisplayModel; +export type ItemDisplayModel = NodeDisplayModel | EdgeDisplayModel | ComboDisplayModel; -export type DisplayMapper = - | ((model: ItemModel) => ItemDisplayModel) - | NodeEncode - | EdgeEncode - | ComboEncode; +export type DisplayMapper = ((model: ItemModel) => ItemDisplayModel) | NodeEncode | EdgeEncode | ComboEncode; export type State = { name: string; @@ -250,7 +219,7 @@ export interface IItem { /** * Draws the shapes. * @internal - * */ + */ draw: ( displayModel: ItemDisplayModel, diffData?: { previous: ItemModelData; current: ItemModelData }, @@ -261,7 +230,7 @@ export interface IItem { /** * Updates the shapes. * @internal - * */ + */ update: ( model: ItemModel, diffData: { previous: ItemModelData; current: ItemModelData }, diff --git a/packages/g6/src/types/layout.ts b/packages/g6/src/types/layout.ts index ba2721cb7a2..144b45b2857 100644 --- a/packages/g6/src/types/layout.ts +++ b/packages/g6/src/types/layout.ts @@ -73,16 +73,20 @@ export type StandardLayoutOptions = PureLayoutOptions & presetLayout?: Partial; }; -export type LayoutOptions = - | StandardLayoutOptions - | ImmediatelyInvokedLayoutOptions; +export type LayoutOptions = StandardLayoutOptions | ImmediatelyInvokedLayoutOptions; -export function isImmediatelyInvokedLayoutOptions( - options: any, -): options is ImmediatelyInvokedLayoutOptions { +/** + * + * @param options + */ +export function isImmediatelyInvokedLayoutOptions(options: any): options is ImmediatelyInvokedLayoutOptions { return !!options.execute; } +/** + * + * @param options + */ export function isLayoutWorkerized(options: StandardLayoutOptions) { return ( [ diff --git a/packages/g6/src/types/node.ts b/packages/g6/src/types/node.ts index 44716e7c3f3..82c929308d1 100644 --- a/packages/g6/src/types/node.ts +++ b/packages/g6/src/types/node.ts @@ -162,8 +162,7 @@ export interface NodeShapeStyles extends ItemShapeStyles { } /** Data in display model. */ -export type NodeDisplayModelData = NodeModelData & - NodeShapeStyles & { lodLevels?: LodLevel[] }; +export type NodeDisplayModelData = NodeModelData & NodeShapeStyles & { lodLevels?: LodLevel[] }; /** User input model. */ export type NodeUserModel = GNode; diff --git a/packages/g6/src/types/spec.ts b/packages/g6/src/types/spec.ts index d253b3cdf84..5baecb8bb3a 100644 --- a/packages/g6/src/types/spec.ts +++ b/packages/g6/src/types/spec.ts @@ -1,44 +1,24 @@ import { Canvas } from '@antv/g'; import { AnimateCfg, CameraAnimationOptions } from './animate'; +import { BehaviorOptionsOf, BehaviorRegistry } from './behavior'; +import { ComboDisplayModel, ComboEncode, ComboModel, ComboShapesEncode } from './combo'; import { Padding, Point } from './common'; import { DataConfig, DataLifecycleType, TransformerFn } from './data'; -import { - EdgeDisplayModel, - EdgeEncode, - EdgeModel, - EdgeShapesEncode, -} from './edge'; -import { - NodeDisplayModel, - NodeEncode, - NodeModel, - NodeShapesEncode, -} from './node'; -import { FitViewRules, GraphAlignment } from './view'; -import { - ComboDisplayModel, - ComboEncode, - ComboModel, - ComboShapesEncode, -} from './combo'; -import { BehaviorOptionsOf, BehaviorRegistry } from './behavior'; +import { EdgeDisplayModel, EdgeEncode, EdgeModel, EdgeShapesEncode } from './edge'; import { LayoutOptions } from './layout'; +import { NodeDisplayModel, NodeEncode, NodeModel, NodeShapesEncode } from './node'; import { ThemeOptionsOf, ThemeRegistry } from './theme'; +import { FitViewRules, GraphAlignment } from './view'; -import { RendererName } from './render'; import { StackCfg } from './history'; import { Plugin } from './plugin'; +import { RendererName } from './render'; export type NodeMapper = ((data: NodeModel) => NodeDisplayModel) | NodeEncode; export type EdgeMapper = ((data: EdgeModel) => EdgeDisplayModel) | EdgeEncode; -export type ComboMapper = - | ((data: ComboModel) => ComboDisplayModel) - | ComboEncode; +export type ComboMapper = ((data: ComboModel) => ComboDisplayModel) | ComboEncode; -export interface Specification< - B extends BehaviorRegistry, - T extends ThemeRegistry, -> { +export interface Specification { container?: string | HTMLElement; backgroundCanvas?: Canvas; canvas?: Canvas; @@ -106,19 +86,13 @@ export interface Specification< /** item state styles */ nodeState?: { - [stateName: string]: - | ((data: NodeModel) => NodeDisplayModel) - | NodeShapesEncode; + [stateName: string]: ((data: NodeModel) => NodeDisplayModel) | NodeShapesEncode; }; edgeState?: { - [stateName: string]: - | ((data: EdgeModel) => EdgeDisplayModel) - | EdgeShapesEncode; + [stateName: string]: ((data: EdgeModel) => EdgeDisplayModel) | EdgeShapesEncode; }; comboState?: { - [stateName: string]: - | ((data: ComboModel) => ComboDisplayModel) - | ComboShapesEncode; + [stateName: string]: ((data: ComboModel) => ComboDisplayModel) | ComboShapesEncode; }; /** layout */ diff --git a/packages/g6/src/types/theme.ts b/packages/g6/src/types/theme.ts index 97e85eece70..865041e137e 100644 --- a/packages/g6/src/types/theme.ts +++ b/packages/g6/src/types/theme.ts @@ -19,7 +19,8 @@ export abstract class Theme { destroy() {} } -/** Theme registry table. +/** + * Theme registry table. * @example { 'drag-node': DragNodeBehavior, 'my-drag-node': MyDragNodeBehavior } */ export interface ThemeRegistry { @@ -33,15 +34,11 @@ export interface ThemeRegistry { export type ThemeOptionsOf = | Extract | { - [K in keyof T]: T[K] extends { new (options: infer O): any } - ? O & { type: K } - : { type: K }; + [K in keyof T]: T[K] extends { new (options: infer O): any } ? O & { type: K } : { type: K }; }[Extract]; export type ThemeObjectOptionsOf = { - [K in keyof T]: T[K] extends { new (options: infer O): any } - ? O & { type: K; key: string } - : never; + [K in keyof T]: T[K] extends { new (options: infer O): any } ? O & { type: K; key: string } : never; }[Extract]; /** Default and state styles for a node. */ @@ -66,7 +63,8 @@ export type ComboStyleSet = { [stateName: string]: ComboShapeStyles; }; -/** Array of node style sets to map the palette in order. +/** + * Array of node style sets to map the palette in order. * e.g. * [ * { default: { keyShape: { fill: 'red', stroke: 'black' } }, selected: { keyShape: { fill: 'yellow' }} }, @@ -78,12 +76,11 @@ export type ComboStyleSet = { * 'cluster1': { default: { keyShape: { fill: 'red', stroke: 'black' } }, selected: { keyShape: { fill: 'yellow' }} }, * 'cluster2': { default: { keyShape: { fill: 'blue', stroke: 'black' } }, selected: { keyShape: { fill: 'green' }} }, * } - **/ -export type NodeStyleSets = - | NodeStyleSet[] - | { [dataTypeValue: string]: NodeStyleSet }; + */ +export type NodeStyleSets = NodeStyleSet[] | { [dataTypeValue: string]: NodeStyleSet }; -/** Array of edge style sets to map the palette in order. +/** + * Array of edge style sets to map the palette in order. * e.g. * [ * { default: { keyShape: { fill: 'red', stroke: 'black' } }, selected: { keyShape: { fill: 'yellow' }} }, @@ -95,12 +92,11 @@ export type NodeStyleSets = * 'cluster1': { default: { keyShape: { fill: 'red', stroke: 'black' } }, selected: { keyShape: { fill: 'yellow' }} }, * 'cluster2': { default: { keyShape: { fill: 'blue', stroke: 'black' } }, selected: { keyShape: { fill: 'green' }} }, * } - **/ -export type EdgeStyleSets = - | EdgeStyleSet[] - | { [dataTypeValue: string]: EdgeStyleSet }; + */ +export type EdgeStyleSets = EdgeStyleSet[] | { [dataTypeValue: string]: EdgeStyleSet }; -/** Array of combo style sets to map the palette in order. +/** + * Array of combo style sets to map the palette in order. * e.g. * [ * { default: { keyShape: { fill: 'red', stroke: 'black' } }, selected: { keyShape: { fill: 'yellow' }} }, @@ -112,10 +108,8 @@ export type EdgeStyleSets = * 'cluster1': { default: { keyShape: { fill: 'red', stroke: 'black' } }, selected: { keyShape: { fill: 'yellow' }} }, * 'cluster2': { default: { keyShape: { fill: 'blue', stroke: 'black' } }, selected: { keyShape: { fill: 'green' }} }, * } - **/ -export type ComboStyleSets = - | ComboStyleSet[] - | { [dataTypeValue: string]: ComboStyleSet }; + */ +export type ComboStyleSets = ComboStyleSet[] | { [dataTypeValue: string]: ComboStyleSet }; /** * Theme specification for node. diff --git a/packages/g6/src/types/view.ts b/packages/g6/src/types/view.ts index 7974e69a9cd..94a3e2489a9 100644 --- a/packages/g6/src/types/view.ts +++ b/packages/g6/src/types/view.ts @@ -11,13 +11,7 @@ export interface FitViewRules { boundsType?: 'render' | 'layout'; } -export type GraphAlignment = - | 'left-top' - | 'right-top' - | 'left-bottom' - | 'right-bottom' - | 'center' - | [number, number]; +export type GraphAlignment = 'left-top' | 'right-top' | 'left-bottom' | 'right-bottom' | 'center' | [number, number]; export type GraphTransformOptions = { translate?: Partial<{ diff --git a/packages/g6/src/util/animate.ts b/packages/g6/src/util/animate.ts index e10e5615e35..2b28d919c7c 100644 --- a/packages/g6/src/util/animate.ts +++ b/packages/g6/src/util/animate.ts @@ -1,11 +1,4 @@ -import { - DisplayObject, - Group, - IAnimation, - Line, - Path, - Polyline, -} from '@antv/g'; +import { DisplayObject, Group, IAnimation, Line, Path, Polyline } from '@antv/g'; import { isString, uniq } from '@antv/util'; import { AnimateTiming, IAnimate, IAnimates } from '../types/animate'; import { ItemShapeStyles, ShapeStyle } from '../types/item'; @@ -14,6 +7,7 @@ import { cloneJSON } from './data'; /** * Initial(timing = show) shape animation start from init shape styles, and end to the shape's style config. + * @param shape */ export const getShapeAnimateBeginStyles = (shape) => { if (!shape) return {}; @@ -120,7 +114,8 @@ const getStyleDiff = (style1: ShapeStyle, style2: ShapeStyle) => { /** * Grouping the animates at a timing by order. * @param animates - * @param timing + * @param segmentedTiming + * @param changedStates * @returns */ const groupTimingAnimates = ( @@ -144,11 +139,14 @@ const groupTimingAnimates = ( /** * Execute animations in order at a timing. * @param shapeMap - * @param group + * @param shapeIds + * @param groups * @param timingAnimates * @param targetStylesMap * @param timing * @param onfinish + * @param cancelAnimations + * @param canceled */ const runAnimateGroupOnShapes = ( shapeMap: { [shapeId: string]: DisplayObject }, @@ -188,8 +186,7 @@ const runAnimateGroupOnShapes = ( else if (field !== 'opacity') usingFields.push(field); else hasOpacity = true; }); - const targetStyle = - targetStylesMap.group || GROUP_ANIMATE_STYLES[isOut ? 0 : 1]; + const targetStyle = targetStylesMap.group || GROUP_ANIMATE_STYLES[isOut ? 0 : 1]; if (hasCanceled) { Object.keys(targetStyle).forEach((key) => { groups.forEach((group) => (group.style[key] = targetStyle[key])); @@ -200,9 +197,7 @@ const runAnimateGroupOnShapes = ( shapeIdsToAnimate.forEach((sid) => { if (!shapeMap[sid]) return; const { opacity: targetOpacity = isOut ? 0 : 1 } = - targetStylesMap[sid] || - targetStylesMap.otherShapes?.[sid] || - {}; + targetStylesMap[sid] || targetStylesMap.otherShapes?.[sid] || {}; animates.push( runAnimateOnShape( shapeMap[sid], @@ -217,41 +212,22 @@ const runAnimateGroupOnShapes = ( if (usingFields.length) { animates = animates.concat( groups.map((group) => - runAnimateOnShape( - group, - usingFields, - targetStyle, - GROUP_ANIMATE_STYLES[isOut ? 1 : 0], - animateConfig, - ), + runAnimateOnShape(group, usingFields, targetStyle, GROUP_ANIMATE_STYLES[isOut ? 1 : 0], animateConfig), ), ); } } } else { const shape = shapeMap[shapeId]; - if ( - shape && - shape.style.display !== 'none' && - shape.style.visibility !== 'hidden' - ) { - const targetStyle = - targetStylesMap[shapeId] || - targetStylesMap.otherShapes?.[shapeId] || - {}; + if (shape && shape.style.display !== 'none' && shape.style.visibility !== 'hidden') { + const targetStyle = targetStylesMap[shapeId] || targetStylesMap.otherShapes?.[shapeId] || {}; if (hasCanceled) { Object.keys(targetStyle).forEach((key) => { shape.style[key] = targetStyle[key]; }); } else { animates.push( - runAnimateOnShape( - shape, - fields, - targetStyle, - getShapeAnimateBeginStyles(shape), - animateConfig, - ), + runAnimateOnShape(shape, fields, targetStyle, getShapeAnimateBeginStyles(shape), animateConfig), ); } } @@ -306,41 +282,20 @@ const runAnimateOnShape = ( } else { animateArr = [{}, {}]; fields.forEach((key) => { - animateArr[0][key] = - shape.style[key] === undefined - ? cloneJSON(beginStyle[key]) - : cloneJSON(shape.style[key]); + animateArr[0][key] = shape.style[key] === undefined ? cloneJSON(beginStyle[key]) : cloneJSON(shape.style[key]); if (targetStyle[key] === undefined) return; animateArr[1][key] = cloneJSON(targetStyle[key]); if (key === 'lineDash') { - const beginPercents = uniq( - animateArr[0][key].filter( - (val) => isString(val) && val.includes('%'), - ), - ); - const targetPercents = uniq( - animateArr[1][key].filter( - (val) => isString(val) && val.includes('%'), - ), - ); + const beginPercents = uniq(animateArr[0][key].filter((val) => isString(val) && val.includes('%'))); + const targetPercents = uniq(animateArr[1][key].filter((val) => isString(val) && val.includes('%'))); if (beginPercents.length || targetPercents.length) { percentLineDash = cloneJSON(animateArr[0].lineDash); - const totalLength = ( - shape as Line | Polyline | Path - ).getTotalLength(); + const totalLength = (shape as Line | Polyline | Path).getTotalLength(); beginPercents.forEach((percent, i) => { - replaceElements( - animateArr[0][key], - percent, - (Number(percent.replace('%', '')) / 100) * totalLength, - ); + replaceElements(animateArr[0][key], percent, (Number(percent.replace('%', '')) / 100) * totalLength); }); targetPercents.forEach((percent, i) => { - replaceElements( - animateArr[1][key], - percent, - (Number(percent.replace('%', '')) / 100) * totalLength, - ); + replaceElements(animateArr[1][key], percent, (Number(percent.replace('%', '')) / 100) * totalLength); }); } } else if (key === 'offsetDistance') { @@ -351,13 +306,10 @@ const runAnimateOnShape = ( if (!checkFrames(animateArr, shape)) return; if (!shape.isVisible()) { // Invisible, do not apply animate. Directly assign the target style instead. - Object.keys(animateArr[1]).forEach( - (field) => (shape.style[field] = animateArr[1][field]), - ); + Object.keys(animateArr[1]).forEach((field) => (shape.style[field] = animateArr[1][field])); return; } - if (animateConfig.iterations === -1 || animateConfig.iterations === null) - animateConfig.iterations = Infinity; + if (animateConfig.iterations === -1 || animateConfig.iterations === null) animateConfig.iterations = Infinity; const animation = shape.animate(animateArr, animateConfig); if (percentLineDash) { animation.onfinish = () => { @@ -376,13 +328,11 @@ const runAnimateOnShape = ( const checkFrames = (frames, shape) => { if (JSON.stringify(frames[0]) === JSON.stringify(frames[1])) return false; ['x', 'y'].forEach((dim) => { - if (!frames[0].hasOwnProperty(dim)) return; + if (!(dim in frames[0])) return; let val; const formatted = [...frames]; - if (frames[0][dim] === undefined && frames[0][dim] !== frames[1][dim]) - val = frames[1][dim]; - if (frames[1][dim] === undefined && frames[0][dim] !== frames[1][dim]) - val = frames[1][dim]; + if (frames[0][dim] === undefined && frames[0][dim] !== frames[1][dim]) val = frames[1][dim]; + if (frames[1][dim] === undefined && frames[0][dim] !== frames[1][dim]) val = frames[1][dim]; if (val !== undefined) { shape.style[dim] = val; delete formatted[0][dim]; @@ -400,8 +350,12 @@ const checkFrames = (frames, shape) => { * @param animates * @param mergedStyles * @param shapeMap - * @param group - * @param timing timing to match 'when' in the animate config in style + * @param shapeIds + * @param groups + * @param timing + * @param changedStates + * @param onAnimatesFrame + * @param onAnimatesEnd * @returns */ export const animateShapes = ( @@ -419,13 +373,8 @@ export const animateShapes = ( onAnimatesEnd(false); return; } - const segmentedTiming = - timing === 'update' && changedStates?.length ? 'stateUpdate' : timing; - const timingAnimateGroups = groupTimingAnimates( - animates, - segmentedTiming, - changedStates, - ); + const segmentedTiming = timing === 'update' && changedStates?.length ? 'stateUpdate' : timing; + const timingAnimateGroups = groupTimingAnimates(animates, segmentedTiming, changedStates); let i = 0; const groupKeys = Object.keys(timingAnimateGroups); if (!groupKeys.length) return; diff --git a/packages/g6/src/util/arrow.ts b/packages/g6/src/util/arrow.ts index f6b970e3fe2..609a9c639fa 100644 --- a/packages/g6/src/util/arrow.ts +++ b/packages/g6/src/util/arrow.ts @@ -7,11 +7,7 @@ import { ArrowType } from '../types/edge'; * @param height The height of the arrow. * @returns */ -export const getArrowPath = ( - type: ArrowType, - width: number, - height: number, -) => { +export const getArrowPath = (type: ArrowType, width: number, height: number) => { switch (type) { case 'triangle': return `M 0,0 L ${width},-${height / 2} L ${width},${height / 2} Z`; diff --git a/packages/g6/src/util/bbox.ts b/packages/g6/src/util/bbox.ts index 32eaa2f0236..653b61d6c25 100644 --- a/packages/g6/src/util/bbox.ts +++ b/packages/g6/src/util/bbox.ts @@ -61,10 +61,7 @@ export const getExpandedBBox = (bbox: AABB, offset: number): AABB => { } = bbox; const expandBBox = new AABB(); if (getBBoxWidth(bbox) || getBBoxHeight(bbox)) { - expandBBox.setMinMax( - [minX - offset, minY - offset, 0], - [maxX + offset, maxY + offset, 0], - ); + expandBBox.setMinMax([minX - offset, minY - offset, 0], [maxX + offset, maxY + offset, 0]); } return expandBBox; }; @@ -119,9 +116,7 @@ export const getBBoxPoints = (bbox: AABB): PolyPoint[] => { */ export const isPointOutsideBBox = (point: PolyPoint, bbox: AABB): boolean => { const { x, y } = point; - return ( - x < bbox.min[0] || x > bbox.max[0] || y < bbox.min[1] || y > bbox.max[1] - ); + return x < bbox.min[0] || x > bbox.max[0] || y < bbox.min[1] || y > bbox.max[1]; }; /** @@ -174,10 +169,7 @@ export const getBBoxYCrossPoints = (bbox: AABB, y: number): PolyPoint[] => { * @param point a 2d point * @returns intersection points */ -export const getBBoxCrossPointsByPoint = ( - bbox: AABB, - point: PolyPoint, -): PolyPoint[] => +export const getBBoxCrossPointsByPoint = (bbox: AABB, point: PolyPoint): PolyPoint[] => getBBoxXCrossPoints(bbox, point.x).concat(getBBoxYCrossPoints(bbox, point.y)); /** @@ -186,10 +178,7 @@ export const getBBoxCrossPointsByPoint = ( * @param bbox a bounding box * @returns 0 if the point is in the center; True if the point is closer to the horizontal axis; False otherwise. */ -export const isHorizontalPoint = ( - point: PolyPoint, - bbox: AABB, -): boolean | number => { +export const isHorizontalPoint = (point: PolyPoint, bbox: AABB): boolean | number => { const dx = Math.abs(point.x - bbox.center[0]); const dy = Math.abs(point.y - bbox.center[1]); if (dx === 0 && dy === 0) return 0; @@ -203,11 +192,7 @@ export const isHorizontalPoint = ( * @param anotherPoint anotherPoint * @returns the anchor point of bbox */ -export const getExpandedBBoxPoint = ( - bbox: AABB, - point: PolyPoint, - anotherPoint: PolyPoint, -): PolyPoint => { +export const getExpandedBBoxPoint = (bbox: AABB, point: PolyPoint, anotherPoint: PolyPoint): PolyPoint => { const isHorizontal = isHorizontalPoint(point, bbox); if (isHorizontal === 0) { // Explain that the anchor point is the node center (linkCenter: true) @@ -249,12 +234,7 @@ export const getExpandedBBoxPoint = ( * @param p3 Endpoint of the second line segment * @returns True if the line segments intersect, False otherwise */ -export const isSegmentsIntersected = ( - p0: PolyPoint, - p1: PolyPoint, - p2: PolyPoint, - p3: PolyPoint, -): boolean => { +export const isSegmentsIntersected = (p0: PolyPoint, p1: PolyPoint, p2: PolyPoint, p3: PolyPoint): boolean => { const v1x = p2.x - p0.x; const v1y = p2.y - p0.y; const v2x = p3.x - p0.x; @@ -279,11 +259,7 @@ export const isSegmentsIntersected = ( * @param bbox a bounding box * @returns True if the line segment intersects with bbox, False otherwise */ -export const isSegmentCrossingBBox = ( - p1: PolyPoint, - p2: PolyPoint, - bbox: AABB, -): boolean => { +export const isSegmentCrossingBBox = (p1: PolyPoint, p2: PolyPoint, bbox: AABB): boolean => { if (getBBoxWidth(bbox) || getBBoxHeight(bbox)) { const [pa, pb, pc, pd] = getBBoxPoints(bbox); return ( @@ -297,25 +273,23 @@ export const isSegmentCrossingBBox = ( }; /** - Determines whether a given point is inside a given bounding box. - @param {Point} point - The point to be checked. - @param {AABB} bbox - The bounding box. - @returns {boolean} - Returns true if the point is inside the bounding box, false otherwise. -*/ + * Determines whether a given point is inside a given bounding box. + * @param {Point} point - The point to be checked. + * @param {AABB} bbox - The bounding box. + * @returns {boolean} - Returns true if the point is inside the bounding box, false otherwise. + */ export const isPointInBBox = (point: Point, bbox: AABB) => { const { x, y } = point; - return ( - x > bbox.min[0] && x < bbox.max[0] && y > bbox.min[1] && y < bbox.max[1] - ); + return x > bbox.min[0] && x < bbox.max[0] && y > bbox.min[1] && y < bbox.max[1]; }; /** - Determines whether a given sub-bounding box is fully contained within a given bounding box. - @param {AABB} subBBox - The sub-bounding box to be checked. - @param {AABB} bbox - The bounding box. - @param {number} [scale] - Optional scaling factor to adjust the size of the bounding box. - @returns {boolean} - Returns true if the sub-bounding box is fully contained within the bounding box, false otherwise. -*/ + * Determines whether a given sub-bounding box is fully contained within a given bounding box. + * @param {AABB} subBBox - The sub-bounding box to be checked. + * @param {AABB} bbox - The bounding box. + * @param {number} [scale] - Optional scaling factor to adjust the size of the bounding box. + * @returns {boolean} - Returns true if the sub-bounding box is fully contained within the bounding box, false otherwise. + */ export const isBBoxInBBox = (subBBox: AABB, bbox: AABB, scale?: number) => { if (scale) { return ( @@ -342,16 +316,10 @@ export const getCombinedCanvasesBounds = (canvases: Canvas[]) => { }; canvases.forEach((canvas) => { const bounds = canvas.document.documentElement.getBounds(); - combinedBounds.min = combinedBounds.min.map((val, i) => - Math.min(val || Infinity, bounds.min[i]), - ); - combinedBounds.max = combinedBounds.max.map((val, i) => - Math.max(val || -Infinity, bounds.max[i]), - ); + combinedBounds.min = combinedBounds.min.map((val, i) => Math.min(val || Infinity, bounds.min[i])); + combinedBounds.max = combinedBounds.max.map((val, i) => Math.max(val || -Infinity, bounds.max[i])); }); - combinedBounds.center = combinedBounds.center.map( - (_, i) => (combinedBounds.max[i] + combinedBounds.min[i]) / 2, - ); + combinedBounds.center = combinedBounds.center.map((_, i) => (combinedBounds.max[i] + combinedBounds.min[i]) / 2); combinedBounds.halfExtents = combinedBounds.halfExtents.map( (_, i) => (combinedBounds.max[i] - combinedBounds.min[i]) / 2, ); diff --git a/packages/g6/src/util/behavior.ts b/packages/g6/src/util/behavior.ts index eb075112a25..f7b9df54b12 100644 --- a/packages/g6/src/util/behavior.ts +++ b/packages/g6/src/util/behavior.ts @@ -3,12 +3,12 @@ import { BehaviorOptionsOf, BehaviorRegistry } from '../types/behavior'; import { isArrayOverlap } from './array'; const TREE_BEHAVIORS = ['collapse-expand-tree']; -export function hasTreeBehaviors( - behaviors: BehaviorOptionsOf[], -) { +/** + * + * @param behaviors + */ +export function hasTreeBehaviors(behaviors: BehaviorOptionsOf[]) { if (!behaviors?.length) return false; - const behaviorTypes = behaviors - .map((behavior) => (isString(behavior) ? behavior : behavior.type)) - .filter(Boolean); + const behaviorTypes = behaviors.map((behavior) => (isString(behavior) ? behavior : behavior.type)).filter(Boolean); return isArrayOverlap(TREE_BEHAVIORS, behaviorTypes); } diff --git a/packages/g6/src/util/canvas.ts b/packages/g6/src/util/canvas.ts index bc4790f1c4a..36c0c7b685b 100644 --- a/packages/g6/src/util/canvas.ts +++ b/packages/g6/src/util/canvas.ts @@ -13,6 +13,8 @@ import { RendererName } from '../types/render'; * @param {number} width * @param {number} height * @param {number} pixelRatio optional + * @param canvasConfig + * @param unregisterPlugins * @returns */ export const createCanvas = ( @@ -71,10 +73,7 @@ export const createCanvas = ( * @param canvas Canvas instance * @returns */ -export const changeRenderer = ( - rendererType: RendererName, - canvas: Canvas, -): Canvas => { +export const changeRenderer = (rendererType: RendererName, canvas: Canvas): Canvas => { let renderer: any; switch (rendererType.toLowerCase()) { case 'svg': diff --git a/packages/g6/src/util/data.ts b/packages/g6/src/util/data.ts index 02c9338ed8e..b111c4dfe52 100644 --- a/packages/g6/src/util/data.ts +++ b/packages/g6/src/util/data.ts @@ -1,15 +1,9 @@ +import { connectedComponent, depthFirstSearch } from '@antv/algorithm'; import { ID, TreeData } from '@antv/graphlib'; import { isArray } from '@antv/util'; -import { depthFirstSearch, connectedComponent } from '@antv/algorithm'; -import { - DataChangeType, - DataLifecycleType, - GraphCore, - GraphData, - GraphDataChanges, -} from '../types/data'; -import { IGraph } from '../types/graph'; import { NodeModel, NodeUserModel } from '../types'; +import { DataLifecycleType, GraphCore, GraphData } from '../types/data'; +import { IGraph } from '../types/graph'; import { NodeUserModelData } from '../types/node'; /** @@ -38,7 +32,10 @@ export const deconstructData = (data) => { * @param nodes begin nodes * @param fn will be called while visiting each node * @param mode 'TB' - visit from top to bottom; 'BT' - visit from bottom to top; - * @returns + * @param treeKey + * @param stopFns + * @param stopFns.stopBranchFn + * @param stopFns.stopAllFn */ export const graphCoreTreeDfs = ( graphCore: GraphCore, @@ -59,14 +56,7 @@ export const graphCoreTreeDfs = ( if (stopBranchFn?.(node)) continue; // Stop this branch if (stopAllFn?.(node)) return; // Stop all if (mode === 'TB') fn(node); // Traverse from top to bottom - graphCoreTreeDfs( - graphCore, - graphCore.getChildren(node.id, treeKey), - fn, - mode, - treeKey, - stopFns, - ); + graphCoreTreeDfs(graphCore, graphCore.getChildren(node.id, treeKey), fn, mode, treeKey, stopFns); if (mode !== 'TB') fn(node); // Traverse from bottom to top } }; @@ -77,14 +67,8 @@ export const graphCoreTreeDfs = ( * @param nodes begin nodes * @param fn will be called while visiting each node * @param mode 'TB' - visit from top to bottom; 'BT' - visit from bottom to top; - * @returns */ -export const graphComboTreeDfs = ( - graph: IGraph, - nodes: NodeUserModel[], - fn, - mode: 'TB' | 'BT' = 'TB', -) => { +export const graphComboTreeDfs = (graph: IGraph, nodes: NodeUserModel[], fn, mode: 'TB' | 'BT' = 'TB') => { if (!nodes?.length) return; nodes.forEach((node) => { if (mode === 'TB') fn(node); // Traverse from top to bottom @@ -100,7 +84,6 @@ export const graphComboTreeDfs = ( * @param nodes begin nodes * @param fn will be called while visiting each node * @param mode 'TB' - visit from top to bottom; 'BT' - visit from bottom to top; - * @returns */ export const traverseAncestorsAndSucceeds = ( graph: IGraph, @@ -115,11 +98,7 @@ export const traverseAncestorsAndSucceeds = ( return; }; -export const traverseGraphAncestors = ( - graph: IGraph, - nodes: NodeUserModel[], - fn, -) => { +export const traverseGraphAncestors = (graph: IGraph, nodes: NodeUserModel[], fn) => { if (!nodes?.length) return; nodes.forEach((node) => { if (!node.data.parentId) return; @@ -153,6 +132,7 @@ export const traverseAncestors = (graphCore, nodes, fn) => { * @param graph G6 graph instance * @param testParent id of the node to be the parent * @param parentId id of the node to be the succeed + * @param testSucceed * @returns */ export const isSucceed = (graph, testParent, testSucceed): boolean => { @@ -172,15 +152,9 @@ export const isSucceed = (graph, testParent, testSucceed): boolean => { * @param toBeAncestorId id of the new parent to check if it is valid to be a parent of the node with id toBeSucceedId * @returns */ -export const validateComboStructure = ( - graph, - toBeSucceedId, - toBeAncestorId, -): boolean => { +export const validateComboStructure = (graph, toBeSucceedId, toBeAncestorId): boolean => { if (toBeAncestorId && !graph.getComboData(toBeAncestorId)) { - console.warn( - `Setting parent combo failed. The parent combo with id ${toBeAncestorId} does not exist`, - ); + console.warn(`Setting parent combo failed. The parent combo with id ${toBeAncestorId} does not exist`); return false; } if (toBeSucceedId === toBeAncestorId) { @@ -203,9 +177,7 @@ export const validateComboStructure = ( * @param treeData Tree structured data or an array of it. * @returns Graph formatted data object with nodes, edges and combos. */ -export const treeData2GraphData = ( - treeData: TreeData | TreeData[], -) => { +export const treeData2GraphData = (treeData: TreeData | TreeData[]) => { const graphData = { nodes: [], edges: [], @@ -243,20 +215,13 @@ export const treeData2GraphData = ( * @param propRootIds Ids of root nodes. There should be at least one node for each connected component, or the first node in a connected component will be added to the roots array. * @returns */ -export const graphData2TreeData = ( - nodeMap: { [id: string]: any }, - graphData: GraphData, - propRootIds: ID[] = [], -) => { +export const graphData2TreeData = (nodeMap: { [id: string]: any }, graphData: GraphData, propRootIds: ID[] = []) => { const trees = []; const graphDataWithoutCombos = { nodes: graphData.nodes?.filter((node) => !node.data._isCombo), edges: graphData.edges, }; - const connectedComponents = connectedComponent( - graphDataWithoutCombos as any, - false, - ) as NodeModel[][]; + const connectedComponents = connectedComponent(graphDataWithoutCombos as any, false) as NodeModel[][]; const rootIds = []; const componentsNodeIds: ID[][] = []; connectedComponents.forEach((com, i) => { @@ -277,12 +242,7 @@ export const graphData2TreeData = ( id, { enter: ({ previous, current }) => { - if ( - !previous || - current === id || - !componentsNodeIds[i].includes(current) - ) - return; + if (!previous || current === id || !componentsNodeIds[i].includes(current)) return; nodeMap[previous] = nodeMap[previous] || { id: previous, children: [], @@ -313,13 +273,7 @@ export const traverse = (treeData, callback) => { export const DEFAULT_ACTIVE_DATA_LIFECYCLE = 'all'; -export const AVAILABLE_DATA_LIFECYCLE = [ - 'read', - 'changeData', - 'updateData', - 'addData', - 'removeData', -]; +export const AVAILABLE_DATA_LIFECYCLE = ['read', 'changeData', 'updateData', 'addData', 'removeData']; export const dataLifecycleMap: Record = { replace: 'read', diff --git a/packages/g6/src/util/dom.ts b/packages/g6/src/util/dom.ts index 696194ebd47..86c07b9134b 100644 --- a/packages/g6/src/util/dom.ts +++ b/packages/g6/src/util/dom.ts @@ -20,10 +20,7 @@ export function createDOM(str: string): HTMLElement { * @param css * @returns */ -export function modifyCSS( - dom: HTMLElement, - css: { [key: string]: any }, -): HTMLElement { +export function modifyCSS(dom: HTMLElement, css: { [key: string]: any }): HTMLElement { if (!dom) return; Object.keys(css).forEach((key) => { diff --git a/packages/g6/src/util/event.ts b/packages/g6/src/util/event.ts index 8ed286c4548..4855fbcab58 100644 --- a/packages/g6/src/util/event.ts +++ b/packages/g6/src/util/event.ts @@ -8,8 +8,8 @@ import { NodeAdded, NodeDataUpdated, NodeRemoved, - TreeStructureChanged, TreeStructureAttached, + TreeStructureChanged, TreeStructureDetached, } from '@antv/graphlib'; import { IG6GraphEvent, IGraph, NodeModelData } from '../types'; @@ -25,6 +25,7 @@ export type ItemInfo = { /** * Given an element, which might be a child shape of a node/edge, * get its belonging item. + * @param element */ export const getItemInfoFromElement = (element: IElement): ItemInfo | null => { if (element.nodeName === 'document') { @@ -54,10 +55,7 @@ export const getItemInfoFromElement = (element: IElement): ItemInfo | null => { * @param graph Graph instance. * @returns Contextmenu event props. */ -export const getContextMenuEventProps = ( - event: IG6GraphEvent, - graph: IGraph, -): IG6GraphEvent => { +export const getContextMenuEventProps = (event: IG6GraphEvent, graph: IGraph): IG6GraphEvent => { return { ...event, type: 'contextmenu', @@ -96,10 +94,7 @@ export type GroupedChanges = { * @param changes * @returns */ -export const getGroupedChanges = ( - graphCore: GraphCore, - changes, -): GroupedChanges => { +export const getGroupedChanges = (graphCore: GraphCore, changes): GroupedChanges => { const groupedChanges: GroupedChanges = { NodeRemoved: [], EdgeRemoved: [], @@ -115,9 +110,7 @@ export const getGroupedChanges = ( }; changes.forEach((change) => { const { type: changeType } = change; - if ( - ['NodeDataUpdated', 'EdgeUpdated', 'EdgeDataUpdated'].includes(changeType) - ) { + if (['NodeDataUpdated', 'EdgeUpdated', 'EdgeDataUpdated'].includes(changeType)) { const { id: oid } = change; if (!graphCore.hasNode(oid) && !graphCore.hasEdge(oid)) { const nid = Number(oid); @@ -127,19 +120,10 @@ export const getGroupedChanges = ( return; } } else if (changeType === 'TreeStructureChanged') { - if (change.treeKey === 'combo') - groupedChanges.ComboStructureChanged.push(change); - else if (change.treeKey === 'tree') - groupedChanges.TreeStructureChanged.push(change); + if (change.treeKey === 'combo') groupedChanges.ComboStructureChanged.push(change); + else if (change.treeKey === 'tree') groupedChanges.TreeStructureChanged.push(change); return; - } else if ( - [ - 'NodeRemoved', - 'EdgeRemoved', - 'TreeStructureAttached', - 'TreeStructureDetached', - ].includes(changeType) - ) { + } else if (['NodeRemoved', 'EdgeRemoved', 'TreeStructureAttached', 'TreeStructureDetached'].includes(changeType)) { groupedChanges[changeType].push(change); } else { const { id: oid } = change.value; diff --git a/packages/g6/src/util/extend.ts b/packages/g6/src/util/extend.ts index a6cfbcea7ab..01f917ec341 100644 --- a/packages/g6/src/util/extend.ts +++ b/packages/g6/src/util/extend.ts @@ -1,19 +1,24 @@ +import { Graph } from '../runtime/graph'; +import { registry } from '../stdlib'; import { BehaviorRegistry } from '../types/behavior'; -import { ThemeRegistry } from '../types/theme'; -import { NodeRegistry } from '../types/node'; import { EdgeRegistry } from '../types/edge'; import { LayoutRegistry } from '../types/layout'; +import { NodeRegistry } from '../types/node'; import { PluginRegistry } from '../types/plugin'; -import { Graph } from '../runtime/graph'; -import { registry } from '../stdlib'; +import { ThemeRegistry } from '../types/theme'; /** * Extend graph class with custom libs (extendLibrary), and extendLibrary will be merged into useLib. * B1 is the Behavior lib from user, B2 is the Behavior lib of the graph to be extended(built-in graph) * TODO: more templates, and might be merged to be two templates for the whole extendLibrary - * @param GraphClass graph class to be extended - * @param extendLibrary custom libs to extend - * @returns extended graph class + * @param GraphClass + * @param extendLibrary + * @param extendLibrary.behaviors + * @param extendLibrary.themeSolvers + * @param extendLibrary.nodes + * @param extendLibrary.edges + * @param extendLibrary.layouts + * @param extendLibrary.plugins */ export const extend = < B1 extends BehaviorRegistry, @@ -33,11 +38,7 @@ export const extend = < ): typeof Graph => { // merged the extendLibrary to useLib for global usage Object.keys(extendLibrary).forEach((cat) => { - registry.useLib[cat] = Object.assign( - {}, - registry.useLib[cat], - extendLibrary[cat] || {}, - ); + registry.useLib[cat] = Object.assign({}, registry.useLib[cat], extendLibrary[cat] || {}); Object.keys(registry.useLib[cat]).forEach((type) => { const extension = registry.useLib[cat][type]; extension.type = type; diff --git a/packages/g6/src/util/extension.ts b/packages/g6/src/util/extension.ts index 892d31b0491..c8dc569cc31 100644 --- a/packages/g6/src/util/extension.ts +++ b/packages/g6/src/util/extension.ts @@ -8,11 +8,7 @@ import { StdLibCategory } from '../types/stdlib'; * @param {StdLibCategory} cat category of the extension * @returns */ -export const getExtension = ( - config: string | Function | object, - lib, - cat: StdLibCategory, -) => { +export const getExtension = (config: string | Function | object, lib, cat: StdLibCategory) => { const catKey = `${cat}s`; // TODO: whether keep function type config? if (isFunction(config)) { diff --git a/packages/g6/src/util/index.ts b/packages/g6/src/util/index.ts index 678a48197dc..ec1e8514ef3 100644 --- a/packages/g6/src/util/index.ts +++ b/packages/g6/src/util/index.ts @@ -1,17 +1,17 @@ -export { extend } from './extend'; -export { mock } from './mock'; -export { isEncode } from './type'; export { getArrowPath } from './arrow'; export { - graphCoreTreeDfs, graphComboTreeDfs, + graphCoreTreeDfs, + graphData2TreeData, + isSucceed, + traverse, + traverseAncestors, traverseAncestorsAndSucceeds, traverseGraphAncestors, - traverseAncestors, - isSucceed, treeData2GraphData, - graphData2TreeData, - traverse, } from './data'; +export { extend } from './extend'; export { getEdgesBetween } from './item'; export { transform } from './matrix'; +export { mock } from './mock'; +export { isEncode } from './type'; diff --git a/packages/g6/src/util/item.ts b/packages/g6/src/util/item.ts index a62a0eaffa3..0df5a4dacd3 100644 --- a/packages/g6/src/util/item.ts +++ b/packages/g6/src/util/item.ts @@ -1,10 +1,10 @@ -import { ID } from '@antv/graphlib'; import { Group } from '@antv/g'; +import { ID } from '@antv/graphlib'; import { uniqueId } from '@antv/util'; -import { IGraph } from '../types'; import Combo from '../item/combo'; import Edge from '../item/edge'; import Node from '../item/node'; +import { IGraph } from '../types'; import { GraphCore } from '../types/data'; import { getCombinedBoundsByItem } from './shape'; @@ -51,12 +51,7 @@ export const upsertTransientItem = ( if (transientItem) { return transientItem; } - const { - shapeIds, - drawSource = true, - drawTarget = true, - visible = true, - } = drawOptions; + const { shapeIds, drawSource = true, drawTarget = true, visible = true } = drawOptions; if (item.type === 'node') { transientItem = item.clone(nodeGroup, nodeLabelGroup, shapeIds, true); } else if (item.type === 'edge') { @@ -140,11 +135,7 @@ export const upsertTransientItem = ( // @ts-ignore transientItem.transient = true; - if ( - item.type !== 'edge' && - upsertAncestors && - graphCore.hasTreeStructure('combo') - ) { + if (item.type !== 'edge' && upsertAncestors && graphCore.hasTreeStructure('combo')) { // find the ancestors to upsert transients let currentAncestor = graphCore.getParent(item.model.id, 'combo'); while (currentAncestor) { diff --git a/packages/g6/src/util/layout.ts b/packages/g6/src/util/layout.ts index 0e7afc5e9bc..281abd32b98 100644 --- a/packages/g6/src/util/layout.ts +++ b/packages/g6/src/util/layout.ts @@ -111,13 +111,11 @@ export const getNodeSizeFn = (options, defaultSize = 32) => { /** * * @param data Tree graph data + * @param tree + * @param nodeMap * @param layout */ -export const radialLayout = ( - tree: TreeGraphData, - nodeMap: Map, - layout?: string, -): GraphData => { +export const radialLayout = (tree: TreeGraphData, nodeMap: Map, layout?: string): GraphData => { // 布局方式有 H / V / LR / RL / TB / BT const VERTICAL_LAYOUTS: string[] = ['V', 'TB', 'BT']; const min: Point = { @@ -153,10 +151,7 @@ export const radialLayout = ( const root = nodeMap.get(tree.id); traverse(tree, (child) => { const node = nodeMap.get(child.id); - const radial = - ((node.data[radScale] - min[radScale]) / radDiff) * - (Math.PI * 2 - avgRad) + - avgRad; + const radial = ((node.data[radScale] - min[radScale]) / radDiff) * (Math.PI * 2 - avgRad) + avgRad; const r = Math.abs(node.data[rScale] - root.data[rScale]); node.data.x = r * Math.cos(radial); node.data.y = r * Math.sin(radial); @@ -167,8 +162,8 @@ export const radialLayout = ( /** * Get the layout (nodes' positions) bounds of a graph. - * @param {Graph} graph - The graph object. - * @returns {Object} - The layout bounds object containing the minimum, maximum, center, and halfExtents values. + * @param graph - The graph object. + * @returns - The layout bounds object containing the minimum, maximum, center, and halfExtents values. */ export const getLayoutBounds = (graph) => { const min = [Infinity, Infinity]; diff --git a/packages/g6/src/util/loop.ts b/packages/g6/src/util/loop.ts index f8a9981dcc1..8d8aa56e89c 100644 --- a/packages/g6/src/util/loop.ts +++ b/packages/g6/src/util/loop.ts @@ -2,16 +2,7 @@ import { Tuple3Number } from '@antv/g'; import { vec2 } from 'gl-matrix'; import { LOOP_POSITION, LoopPosition } from '../types/loop'; -export const loopPosition = [ - 'top', - 'top-right', - 'right', - 'bottom-right', - 'bottom', - 'bottom-left', - 'left', - 'top-left', -]; +export const loopPosition = ['top', 'top-right', 'right', 'bottom-right', 'bottom', 'bottom-left', 'left', 'top-left']; const PI_OVER_8 = Math.PI / 8; @@ -71,9 +62,7 @@ export const calculatePointForOtherShapes = ( const defaultPointPadding = Math.min(halfOfHeight / 2, halfOfWidth / 2); const maxPointPadding = Math.min(halfOfHeight, halfOfWidth); - const pointPadding = customPointPadding - ? Math.min(maxPointPadding, customPointPadding) - : defaultPointPadding; + const pointPadding = customPointPadding ? Math.min(maxPointPadding, customPointPadding) : defaultPointPadding; const pointsPositionMap: Record = { [LOOP_POSITION.top]: [ @@ -123,11 +112,7 @@ export const calculatePointForOtherShapes = ( * @param {number} angleInRadians - The angle in radians. * @returns {vec2} - The point on the ellipse at the given angle. */ -export const getPointOnEllipseAtAngle = ( - halfOfWidth: number, - halfOfHeight: number, - angleInRadians: number, -): vec2 => { +export const getPointOnEllipseAtAngle = (halfOfWidth: number, halfOfHeight: number, angleInRadians: number): vec2 => { const x = halfOfWidth * Math.cos(angleInRadians); const y = halfOfHeight * Math.sin(angleInRadians); return [x, y]; @@ -146,15 +131,7 @@ export const getPointsOnEllipseAtAngles = ( startAngle: number, endAngle: number, ) => { - const [rstartX, rstartY] = getPointOnEllipseAtAngle( - halfOfWidth, - halfOfHeight, - startAngle, - ); - const [rendX, rendY] = getPointOnEllipseAtAngle( - halfOfWidth, - halfOfHeight, - endAngle, - ); + const [rstartX, rstartY] = getPointOnEllipseAtAngle(halfOfWidth, halfOfHeight, startAngle); + const [rendX, rendY] = getPointOnEllipseAtAngle(halfOfWidth, halfOfHeight, endAngle); return [rstartX, rstartY, rendX, rendY]; }; diff --git a/packages/g6/src/util/math.ts b/packages/g6/src/util/math.ts index 3ea5ae2b6dc..930d8a1de05 100644 --- a/packages/g6/src/util/math.ts +++ b/packages/g6/src/util/math.ts @@ -5,10 +5,9 @@ import { Point, PolyPoint } from '../types/common'; * @param {number} value the value to be judged * @param {number} min the min of the range * @param {number} max the max of the range - * @return {boolean} bool the result boolean + * @returns {boolean} bool the result boolean */ -export const isBetween = (value: number, min: number, max: number) => - value >= min && value <= max; +export const isBetween = (value: number, min: number, max: number) => value >= min && value <= max; /** * Calculate the manhattan distance between two points @@ -16,10 +15,8 @@ export const isBetween = (value: number, min: number, max: number) => * @param p2 the second 2d point * @returns Sum of the absolute coordinate differences of two points */ -export const manhattanDist = ( - p1: Point | PolyPoint, - p2: Point | PolyPoint, -): number => Math.abs(p1.x - p2.x) + Math.abs(p1.y - p2.y); +export const manhattanDist = (p1: Point | PolyPoint, p2: Point | PolyPoint): number => + Math.abs(p1.x - p2.x) + Math.abs(p1.y - p2.y); /** * @@ -27,7 +24,5 @@ export const manhattanDist = ( * @param p2 * @returns */ -export const eulerDist = ( - p1: Point | PolyPoint, - p2: Point | PolyPoint, -): number => Math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2); +export const eulerDist = (p1: Point | PolyPoint, p2: Point | PolyPoint): number => + Math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2); diff --git a/packages/g6/src/util/matrix.ts b/packages/g6/src/util/matrix.ts index bed31789c01..867d4ab7be8 100644 --- a/packages/g6/src/util/matrix.ts +++ b/packages/g6/src/util/matrix.ts @@ -1,35 +1,49 @@ import { mat3 } from 'gl-matrix'; -type mat3Type = [ - number, - number, - number, - number, - number, - number, - number, - number, - number, -]; +type mat3Type = [number, number, number, number, number, number, number, number, number]; +/** + * + * @param out + * @param a + * @param v + */ function leftTranslate(out, a, v) { const transMat: mat3Type = [0, 0, 0, 0, 0, 0, 0, 0, 0]; mat3.fromTranslation(transMat, v); return mat3.multiply(out, transMat, a); } +/** + * + * @param out + * @param a + * @param rad + */ function leftRotate(out, a, rad) { const rotateMat: mat3Type = [0, 0, 0, 0, 0, 0, 0, 0, 0]; mat3.fromRotation(rotateMat, rad); return mat3.multiply(out, rotateMat, a); } +/** + * + * @param out + * @param a + * @param v + */ function leftScale(out, a, v) { const scaleMat: mat3Type = [0, 0, 0, 0, 0, 0, 0, 0, 0]; mat3.fromScaling(scaleMat, v); return mat3.multiply(out, scaleMat, a); } +/** + * + * @param out + * @param a + * @param a1 + */ function leftMultiply(out, a, a1) { return mat3.multiply(out, a1, a); } diff --git a/packages/g6/src/util/mock.ts b/packages/g6/src/util/mock.ts index 6cbf56f4548..2b86704d832 100644 --- a/packages/g6/src/util/mock.ts +++ b/packages/g6/src/util/mock.ts @@ -53,9 +53,7 @@ export const mock = (nodeCount: number) => { random: (ratio = 0.5) => { const length: number = parseInt(String(nodeCount * ratio)); - const randomArray: string[] = nodeIds - .sort(() => Math.random() - 0.5) - .slice(0, length); + const randomArray: string[] = nodeIds.sort(() => Math.random() - 0.5).slice(0, length); const edges = fullEdges .filter((edge) => { diff --git a/packages/g6/src/util/path.ts b/packages/g6/src/util/path.ts index 66ed0e577b5..b7347c87922 100644 --- a/packages/g6/src/util/path.ts +++ b/packages/g6/src/util/path.ts @@ -3,28 +3,20 @@ import { Point } from '../types/common'; /** * Calculate the position of control point according to the start, end, and offset. - * @param {IPoint} startPoint Start point with x and y. - * @param {IPoint} endPoint End point with x and y. - * @param {Number} percent Control point's position percentage between source and end point, ranges from 0 to 1. - * @param {Number} offset Offset from the control point to the line start at startPoint and end at endPoint. - * @return {IPoint} The control point with x and y. + * @param startPoint Start point with x and y. + * @param endPoint End point with x and y. + * @param percent Control point's position percentage between source and end point, ranges from 0 to 1. + * @param offset Offset from the control point to the line start at startPoint and end at endPoint. + * @returns The control point with x and y. */ -export const getControlPoint = ( - startPoint: Point, - endPoint: Point, - percent = 0, - offset = 0, -): Point => { +export const getControlPoint = (startPoint: Point, endPoint: Point, percent = 0, offset = 0): Point => { const point: Point = { x: (1 - percent) * startPoint.x + percent * endPoint.x, y: (1 - percent) * startPoint.y + percent * endPoint.y, }; 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]; @@ -61,7 +53,7 @@ const PATH_COMMANDS = { * Converts a path string to an array of path segments. * @param {string} path - The path string to convert. * @returns {Array} - An array of path segments. - **/ + */ const fromPathToArray = (path: string) => { const items = path .replace(/[\n\r]/g, '') @@ -74,7 +66,7 @@ const fromPathToArray = (path: string) => { let currentElement = {}; while (items.length > 0) { let it = items.shift(); - if (PATH_COMMANDS.hasOwnProperty(it)) { + if (it in PATH_COMMANDS) { currentCommand = it; } else { items.unshift(it); diff --git a/packages/g6/src/util/point.ts b/packages/g6/src/util/point.ts index 372afee368c..6eddc310760 100644 --- a/packages/g6/src/util/point.ts +++ b/packages/g6/src/util/point.ts @@ -53,9 +53,7 @@ export const distance = (p1: Point, p2: Point): number => { const vx = p1.x - p2.x; const vy = p1.y - p2.y; const vz = p1.z - p2.z; - return isNaN(vz) - ? Math.sqrt(vx * vx + vy * vy) - : Math.sqrt(vx * vx + vy * vy + vz * vz); + return isNaN(vz) ? Math.sqrt(vx * vx + vy * vy) : Math.sqrt(vx * vx + vy * vy + vz * vz); }; /** @@ -71,9 +69,12 @@ export const isSamePoint = (p1: Point, p2: Point): boolean => { /** * Get point and circle intersect point. - * @param {ICircle} circle Circle's center x,y and radius r - * @param {Point} point Point x,y - * @return {Point} calculated intersect point + * @param circleProps - Circle's center x,y and radius r + * @param circleProps.x + * @param point - Point x,y + * @param circleProps.y + * @param circleProps.r + * @returns calculated intersect point */ export const getCircleIntersectByPoint = ( circleProps: { x: number; y: number; r: number }, @@ -96,9 +97,13 @@ export const getCircleIntersectByPoint = ( /** * Get point and ellipse inIntersect. - * @param {Object} ellipse ellipse center x,y and radius rx,ry - * @param {Object} point Point x,y - * @return {object} calculated intersect point + * @param ellipseProps - ellipse center x,y and radius rx,ry + * @param ellipseProps.rx + * @param point - Point x,y + * @param ellipseProps.ry + * @param ellipseProps.x + * @param ellipseProps.y + * @returns calculated intersect point */ export const getEllipseIntersectByPoint = ( ellipseProps: { @@ -129,9 +134,13 @@ export const getEllipseIntersectByPoint = ( /** * Point and rectangular intersection point. - * @param {IRect} rect rect - * @param {Point} point point - * @return {PointPoint} rst; + * @param rectProps - rect + * @param rectProps.x + * @param point - point + * @param rectProps.y + * @param rectProps.width + * @param rectProps.height + * @returns rst; */ export const getRectIntersectByPoint = ( rectProps: { x: number; y: number; width: number; height: number }, @@ -181,14 +190,9 @@ export const getRectIntersectByPoint = ( * @param {Point} p1 The end point of the first line. * @param {Point} p2 The start point of the second line. * @param {Point} p3 The end point of the second line. - * @return {Point} Calculated intersect point. + * @returns {Point} Calculated intersect point. */ -export const getLineIntersect = ( - p0: Point, - p1: Point, - p2: Point, - p3: Point, -): Point | null => { +export const getLineIntersect = (p0: Point, p1: Point, p2: Point, p3: Point): Point | null => { const tolerance = 0.0001; const E: Point = { diff --git a/packages/g6/src/util/polyline.ts b/packages/g6/src/util/polyline.ts index 307fec31c6d..6c3cbbdfab9 100644 --- a/packages/g6/src/util/polyline.ts +++ b/packages/g6/src/util/polyline.ts @@ -1,25 +1,24 @@ import { AABB } from '@antv/g'; -import { each } from '@antv/util'; import { ID } from '@antv/graphlib'; -import { EdgeDisplayModel } from '../types/edge'; -import { NodeDisplayModel } from '../types'; +import { each } from '@antv/util'; import Node from '../item/node'; -import Item from '../item/item'; +import { NodeDisplayModel } from '../types'; import { Point, PolyPoint } from '../types/common'; +import { EdgeDisplayModel } from '../types/edge'; import { + getBBoxCrossPointsByPoint, getBBoxFromPoint, getBBoxFromPoints, - getExpandedBBox, getBBoxPoints, + getExpandedBBox, getExpandedBBoxPoint, - mergeBBox, - getBBoxCrossPointsByPoint, isPointOutsideBBox, isSegmentCrossingBBox, + mergeBBox, } from './bbox'; import { manhattanDist } from './math'; -import { RouterCfg } from './router'; import { isBending } from './point'; +import { RouterCfg } from './router'; /** * Simplify points of polyline by removing duplicated points @@ -42,22 +41,21 @@ export const simplifyPolylinePoints = (points: PolyPoint[]): PolyPoint[] => { /** * Use the A* path-finding algorithm to obtain the shortest path. * Considering that there is no need to implement automatic obstacle avoidance, use waypoints to plan the path. + * @param start + * @param end + * @param startNode + * @param endNode + * @param cfg */ -export const simplePathFinder = ( - start: PolyPoint, - end: PolyPoint, - startNode: Node, - endNode: Node, - cfg: RouterCfg, -) => { - return simplifyPolylinePoints( - getPolylinePoints(start, end, cfg.offset, startNode, endNode), - ); +export const simplePathFinder = (start: PolyPoint, end: PolyPoint, startNode: Node, endNode: Node, cfg: RouterCfg) => { + return simplifyPolylinePoints(getPolylinePoints(start, end, cfg.offset, startNode, endNode)); }; /** * 如果 points 中的一个节点 x 与 p 相等,则消耗 -2。y 同 * 即优先选择和 points 在同一水平线 / 垂直线上的点 + * @param p + * @param points */ // eslint-disable-next-line @typescript-eslint/naming-convention export const _costByPoints = (p: PolyPoint, points: PolyPoint[]): number => { @@ -78,6 +76,11 @@ export const _costByPoints = (p: PolyPoint, points: PolyPoint[]): number => { /** * ps 经过 p 到 pt 的距离,减去其他路过节点造成的消耗 + * @param p + * @param ps + * @param pt + * @param source + * @param target */ export const heuristicCostEstimate = ( p: PolyPoint, @@ -85,10 +88,7 @@ export const heuristicCostEstimate = ( pt: PolyPoint, source?: PolyPoint, target?: PolyPoint, -): number => - manhattanDist(p, ps) + - manhattanDist(p, pt) + - _costByPoints(p, [ps, pt, source!, target!]); +): number => manhattanDist(p, ps) + manhattanDist(p, pt) + _costByPoints(p, [ps, pt, source!, target!]); export const reconstructPath = ( pathPoints: PolyPoint[], @@ -98,23 +98,15 @@ export const reconstructPath = ( iterator = 0, ) => { pathPoints.unshift(pointById[currentId]); - if ( - cameFrom[currentId] && - cameFrom[currentId] !== currentId && - iterator <= 100 - ) { - reconstructPath( - pathPoints, - pointById, - cameFrom, - cameFrom[currentId], - iterator + 1, - ); + if (cameFrom[currentId] && cameFrom[currentId] !== currentId && iterator <= 100) { + reconstructPath(pathPoints, pointById, cameFrom, cameFrom[currentId], iterator + 1); } }; /** * 从 arr 中删去 item + * @param arr + * @param item */ export const removeFrom = (arr: PolyPoint[], item: PolyPoint) => { const index = arr.indexOf(item); @@ -125,21 +117,17 @@ export const removeFrom = (arr: PolyPoint[], item: PolyPoint) => { /** * 在 points 中找到满足 x 或 y 和 point 的 x 或 y 相等,且与 point 连线不经过 bbox1 与 bbox2 的点 + * @param points + * @param point + * @param bbox1 + * @param bbox2 */ -export const getNeighborPoints = ( - points: PolyPoint[], - point: PolyPoint, - bbox1: AABB, - bbox2: AABB, -): PolyPoint[] => { +export const getNeighborPoints = (points: PolyPoint[], point: PolyPoint, bbox1: AABB, bbox2: AABB): PolyPoint[] => { const neighbors: Point[] = []; points.forEach((p) => { if (p === point) return; if (p.x === point.x || p.y === point.y) { - if ( - isSegmentCrossingBBox(p, point, bbox1) || - isSegmentCrossingBBox(p, point, bbox2) - ) { + if (isSegmentCrossingBBox(p, point, bbox1) || isSegmentCrossingBBox(p, point, bbox2)) { return; } neighbors.push(p); @@ -148,7 +136,16 @@ export const getNeighborPoints = ( return simplifyPolylinePoints(neighbors); }; -/** A-Star Algorithm using waypoints */ +/** + * A-Star Algorithm using waypoints + * @param points + * @param start + * @param goal + * @param sBBox + * @param tBBox + * @param os + * @param ot + */ export const pathFinderUsingWaypoints = ( points: PolyPoint[], start: PolyPoint, @@ -224,8 +221,7 @@ export const pathFinderUsingWaypoints = ( openSet[neighborId] = neighbor; } - const tentativeGScore = - fScore[current.id] + manhattanDist(current, neighbor); // + manhattanDist(neighbor, goal); + const tentativeGScore = fScore[current.id] + manhattanDist(current, neighbor); // + manhattanDist(neighbor, goal); if (gScore[neighborId] && tentativeGScore >= gScore[neighborId]) { sortedOpenSet.add({ id: neighborId, @@ -236,9 +232,7 @@ export const pathFinderUsingWaypoints = ( cameFrom[neighborId] = current.id; gScore[neighborId] = tentativeGScore; - fScore[neighborId] = - gScore[neighborId] + - heuristicCostEstimate(neighbor, goal, start, os, ot); + fScore[neighborId] = gScore[neighborId] + heuristicCostEstimate(neighbor, goal, start, os, ot); sortedOpenSet.add({ id: neighborId, value: fScore[neighborId], @@ -253,13 +247,12 @@ export const pathFinderUsingWaypoints = ( /** * Calculate the two points necessary to draw a rounded corner between three points, given a radius. + * @param p0 + * @param p1 + * @param p2 + * @param r */ -export const getBorderRadiusPoints = ( - p0: Point, - p1: Point, - p2: Point, - r: number, -): Point[] => { +export const getBorderRadiusPoints = (p0: Point, p1: Point, p2: Point, r: number): Point[] => { const d0 = manhattanDist(p0, p1); const d1 = manhattanDist(p2, p1); const maxR = Math.min(d0, d1) / 2; // calculate the minimum possible radius @@ -275,12 +268,13 @@ export const getBorderRadiusPoints = ( return [ps, pt]; }; -/** Draw a polyline path */ -export const pointsToPolyline = ( - points: Point[], - borderRadius?: number, - z?: boolean, -): string => { +/** + * Draw a polyline path + * @param points + * @param borderRadius + * @param z + */ +export const pointsToPolyline = (points: Point[], borderRadius?: number, z?: boolean): string => { const pathSegments: string[] = []; const startPoint = points[0]; pathSegments.push(`M ${startPoint.x} ${startPoint.y}`); @@ -314,12 +308,7 @@ export const pointsToPolyline = ( * @param z whether is closed from the last point to the first point * @returns */ -export const getPolylinePath = ( - id: ID, - points: Point[], - radius?: number, - z?: boolean, -): string => { +export const getPolylinePath = (id: ID, points: Point[], radius?: number, z?: boolean): string => { if (!points || points.length < 2) { return 'M 0 0 L 0 0'; // Cannot draw a single point } @@ -409,15 +398,7 @@ export const getPolylinePoints = ( connectPoints.unshift(sPoint); connectPoints.push(tPoint); connectPoints = simplifyPolylinePoints(connectPoints); - const pathPoints = pathFinderUsingWaypoints( - connectPoints, - sPoint, - tPoint, - sBBox, - tBBox, - start, - end, - ); + const pathPoints = pathFinderUsingWaypoints(connectPoints, sPoint, tPoint, sBBox, tBBox, start, end); return simplifyPolylinePoints(pathPoints); }; @@ -562,7 +543,10 @@ export class QuadTree { private southwest?: QuadTree; private southeast?: QuadTree; - constructor(public boundary: AABB, capacity: number) { + constructor( + public boundary: AABB, + capacity: number, + ) { this.capacity = capacity; } @@ -645,7 +629,10 @@ export class EdgeCollisionChecker { this.quadTree = quadTree; } - /** Check if node and edge intersect */ + /** + * Check if node and edge intersect + * @param nodeBBox + */ getCollidingEdges(nodeBBox: AABB): ComputedEdge[] { // Get edge's bounding box intersects moving node's bounding box const potentialCollisions = this.quadTree.queryRange(nodeBBox); @@ -658,6 +645,8 @@ export class EdgeCollisionChecker { /** * Check if the edge is a polyline and obstacle avoidance is enabled + * @param displayModel + * @param polylineEdgeType */ export const isPolylineWithObstacleAvoidance = ( displayModel: EdgeDisplayModel, @@ -667,17 +656,15 @@ export const isPolylineWithObstacleAvoidance = ( const isPolyline = polylineEdgeType.includes(type); if (!isPolyline) return false; // @ts-ignore - const isObstacleAvoidanceEnabled = (keyShape?.routeCfg as RouterCfg) - ?.enableObstacleAvoidance; + const isObstacleAvoidanceEnabled = (keyShape?.routeCfg as RouterCfg)?.enableObstacleAvoidance; return isObstacleAvoidanceEnabled; }; /** * Check if the node prevents polyline edges from overlapping + * @param displayModel */ -export const isPointPreventPolylineOverlap = ( - displayModel: NodeDisplayModel, -) => { +export const isPointPreventPolylineOverlap = (displayModel: NodeDisplayModel) => { if (!displayModel) return false; const { preventPolylineEdgeOverlap } = displayModel.data; return preventPolylineEdgeOverlap || false; diff --git a/packages/g6/src/util/router.ts b/packages/g6/src/util/router.ts index df43a17eab5..cd8ec0a4f7f 100644 --- a/packages/g6/src/util/router.ts +++ b/packages/g6/src/util/router.ts @@ -1,18 +1,12 @@ import { deepMix, map } from '@antv/util'; +import Node from '../item/node'; import { ID } from '../types'; import { Point, PolyPoint } from '../types/common'; -import Node from '../item/node'; -import { simplePathFinder, SortedArray } from './polyline'; -import { - getBBoxWidth, - getBBoxHeight, - getExpandedBBox, - getExpandedBBoxPoint, - isSegmentCrossingBBox, -} from './bbox'; -import { getLineIntersect } from './shape'; +import { getBBoxHeight, getBBoxWidth, getExpandedBBox, getExpandedBBoxPoint, isSegmentCrossingBBox } from './bbox'; import { eulerDist, manhattanDist } from './math'; import { getNearestPoint } from './point'; +import { SortedArray, simplePathFinder } from './polyline'; +import { getLineIntersect } from './shape'; export interface RouterCfg { name: 'orth' | 'er'; @@ -31,13 +25,7 @@ export interface RouterCfg { /** Function to calculate the distance between two points */ distFunc?: (p1: PolyPoint, p2: PolyPoint) => number; /** Simplified function to find path */ - fallbackRoute?: ( - p1: PolyPoint, - p2: PolyPoint, - startNode?: Node, - endNode?: Node, - cfg?: RouterCfg, - ) => PolyPoint[]; + fallbackRoute?: (p1: PolyPoint, p2: PolyPoint, startNode?: Node, endNode?: Node, cfg?: RouterCfg) => PolyPoint[]; /** Maximum loops */ maximumLoops?: number; /** @@ -104,25 +92,13 @@ const pos2GridIx = (pos: number, gridSize: number) => { return gridIx < 0 ? 0 : sign * gridIx; }; -const getObstacleMap = ( - items: Map, - gridSize: number, - offset: number, -) => { +const getObstacleMap = (items: Map, gridSize: number, offset: number) => { const obstacleMap = {}; items.forEach((item: Node) => { if (!item || !item.isVisible()) return; const bbox = getExpandedBBox(item.getBBox(), offset); - for ( - let x = pos2GridIx(bbox.min[0], gridSize); - x <= pos2GridIx(bbox.max[0], gridSize); - x += 1 - ) { - for ( - let y = pos2GridIx(bbox.min[1], gridSize); - y <= pos2GridIx(bbox.max[1], gridSize); - y += 1 - ) { + for (let x = pos2GridIx(bbox.min[0], gridSize); x <= pos2GridIx(bbox.max[0], gridSize); x += 1) { + for (let y = pos2GridIx(bbox.min[1], gridSize); y <= pos2GridIx(bbox.max[1], gridSize); y += 1) { obstacleMap[`${x}|||${y}`] = true; } } @@ -133,6 +109,8 @@ const getObstacleMap = ( /** * Calculate angle between the ray from p1 to p2 (clockwise) + * @param p1 + * @param p2 */ const getDirectionAngle = (p1: PolyPoint, p2: PolyPoint) => { const deltaX = p2.x - p1.x; @@ -145,16 +123,19 @@ const getDirectionAngle = (p1: PolyPoint, p2: PolyPoint) => { /** * Get changed direction angle and make sure less than 180 degrees + * @param angle1 + * @param angle2 */ const getAngleDiff = (angle1: number, angle2: number) => { const directionChange = Math.abs(angle1 - angle2); - return directionChange > Math.PI - ? 2 * Math.PI - directionChange - : directionChange; + return directionChange > Math.PI ? 2 * Math.PI - directionChange : directionChange; }; /** * estimated cost from the starting point to the end point after passing through the current point + * @param from + * @param endPoints + * @param distFunc */ const estimateCost = (from: PolyPoint, endPoints: PolyPoint[], distFunc) => { let min = Infinity; @@ -192,17 +173,12 @@ const getBoxPoints = ( const { directions, offset } = cfg; const bbox = node.getBBox(); const isInside = - oriPoint.x > bbox.min[0] && - oriPoint.x < bbox.max[0] && - oriPoint.y > bbox.min[1] && - oriPoint.y < bbox.max[1]; + oriPoint.x > bbox.min[0] && oriPoint.x < bbox.max[0] && oriPoint.y > bbox.min[1] && oriPoint.y < bbox.max[1]; const expandBBox = getExpandedBBox(bbox, offset); for (const i in expandBBox) { - expandBBox[i] = map(expandBBox[i], (item: number) => - pos2GridIx(item, cfg.gridSize), - ); + expandBBox[i] = map(expandBBox[i], (item: number) => pos2GridIx(item, cfg.gridSize)); } if (isInside) { @@ -303,15 +279,7 @@ const getDirectionChange = ( return getAngleDiff(prevDirectionAngle, directionAngle); }; -const getControlPoints = ( - current, - cameFrom, - scaleStartPoint, - endPoint, - startPoints, - scaleEndPoint, - gridSize, -) => { +const getControlPoints = (current, cameFrom, scaleStartPoint, endPoint, startPoints, scaleEndPoint, gridSize) => { const controlPoints = []; let pointZero = endPoint; let currentId = current.id; @@ -341,12 +309,7 @@ const getControlPoints = ( y: currentCameFrom.y, id: currentCameFrom.id, }; - const directionChange = getDirectionChange( - prePoint, - point, - cameFrom, - scaleStartPoint, - ); + const directionChange = getDirectionChange(prePoint, point, cameFrom, scaleStartPoint); if (directionChange) { pointZero = { x: prePoint.x === point.x ? pointZero.x : prePoint.x * gridSize, @@ -371,7 +334,14 @@ const getControlPoints = ( return controlPoints; }; -/** Find the shortest path computed by A* routing algorithm */ +/** + * Find the shortest path computed by A* routing algorithm + * @param points + * @param sourceNodeId + * @param targetNodeId + * @param nodeMap + * @param routerCfg + */ export const pathFinder = ( points: Point[], sourceNodeId: ID, @@ -383,13 +353,11 @@ export const pathFinder = ( const endNode = nodeMap.get(targetNodeId); const startPoint: PolyPoint = startNode?.getPosition() || points[0]; - const endPoint: PolyPoint = - endNode?.getPosition() || points[points.length - 1]; + const endPoint: PolyPoint = endNode?.getPosition() || points[points.length - 1]; if (isNaN(startPoint.x) || isNaN(endPoint.x)) return []; - const defaultCfgs = - routerCfg.name === 'orth' ? defaultCfg : deepMix(defaultCfg, octolinearCfg); + const defaultCfgs = routerCfg.name === 'orth' ? defaultCfg : deepMix(defaultCfg, octolinearCfg); const cfg: RouterCfg = deepMix(defaultCfgs, routerCfg); @@ -412,20 +380,8 @@ export const pathFinder = ( startPoint.id = `${scaleStartPoint.x}|||${scaleStartPoint.y}`; endPoint.id = `${scaleEndPoint.x}|||${scaleEndPoint.y}`; - const startPoints = getBoxPoints( - scaleStartPoint, - startPoint, - startNode, - scaleEndPoint, - cfg, - ); - const endPoints = getBoxPoints( - scaleEndPoint, - endPoint, - endNode, - scaleStartPoint, - cfg, - ); + const startPoints = getBoxPoints(scaleStartPoint, startPoint, startNode, scaleEndPoint, cfg); + const endPoints = getBoxPoints(scaleEndPoint, endPoint, endNode, scaleStartPoint, cfg); startPoints.forEach((point) => { delete obstacleMap[point.id]; }); @@ -466,12 +422,7 @@ export const pathFinder = ( }); } let remainLoops = cfg.maximumLoops; - let current, - direction, - neighbor, - neighborCost, - costFromStart, - directionChange; + let current, direction, neighbor, neighborCost, costFromStart, directionChange; let curCost = Infinity; const endPointMap = {}; endPoints.forEach((point) => { @@ -494,15 +445,7 @@ export const pathFinder = ( // If the point with the smallest fScore is the endpoint if (endPointMap[`${current.x}|||${current.y}`]) { - return getControlPoints( - current, - cameFrom, - scaleStartPoint, - endPoint, - startPoints, - scaleEndPoint, - gridSize, - ); + return getControlPoints(current, cameFrom, scaleStartPoint, endPoint, startPoints, scaleEndPoint, gridSize); } delete openSet[current.id]; @@ -513,9 +456,7 @@ export const pathFinder = ( // Take a step in the direction of the candidate point for (let i = 0; i < cfg.directions.length; i++) { direction = cfg.directions[i]; - const neighborId = `${Math.round(current.x) + direction.stepX}|||${ - Math.round(current.y) + direction.stepY - }`; + const neighborId = `${Math.round(current.x) + direction.stepX}|||${Math.round(current.y) + direction.stepY}`; neighbor = { x: current.x + direction.stepX, y: current.y + direction.stepY, @@ -523,12 +464,7 @@ export const pathFinder = ( }; if (closedSet[neighborId]) continue; - directionChange = getDirectionChange( - current, - neighbor, - cameFrom, - scaleStartPoint, - ); + directionChange = getDirectionChange(current, neighbor, cameFrom, scaleStartPoint); if (directionChange > cfg.maxAllowedDirectionChange) continue; if (obstacleMap[neighborId]) continue; // skip if intersects @@ -538,9 +474,7 @@ export const pathFinder = ( } const directionPenalties = penalties[directionChange]; - neighborCost = - cfg.distFunc(current, neighbor) + - (isNaN(directionPenalties) ? gridSize : directionPenalties); + neighborCost = cfg.distFunc(current, neighbor) + (isNaN(directionPenalties) ? gridSize : directionPenalties); costFromStart = gScore[current.id] + neighborCost; const neighborGScore = gScore[neighborId]; if (neighborGScore && costFromStart >= neighborGScore) { @@ -549,8 +483,7 @@ export const pathFinder = ( cameFrom[neighborId] = current; gScore[neighborId] = costFromStart; - fScore[neighborId] = - costFromStart + estimateCost(neighbor, endPoints, cfg.distFunc); + fScore[neighborId] = costFromStart + estimateCost(neighbor, endPoints, cfg.distFunc); sortedOpenSet.add({ id: neighborId, diff --git a/packages/g6/src/util/shape.ts b/packages/g6/src/util/shape.ts index 027e56656d0..9a424e4f498 100644 --- a/packages/g6/src/util/shape.ts +++ b/packages/g6/src/util/shape.ts @@ -20,23 +20,10 @@ import { DEFAULT_LABEL_BG_PADDING } from '../constant'; import Combo from '../item/combo'; import Edge from '../item/edge'; import Node from '../item/node'; -import { - AnimateTiming, - ComboDisplayModel, - ComboModelData, - IAnimates, - IGraph, -} from '../types'; +import { AnimateTiming, ComboDisplayModel, ComboModelData, IAnimates, IGraph } from '../types'; import { Padding, Point, StandardPadding } from '../types/common'; import { EdgeDisplayModel, EdgeModelData, EdgeShapeMap } from '../types/edge'; -import { - GShapeStyle, - ItemShapeStyles, - SHAPE_TYPE, - SHAPE_TYPE_3D, - ShapeStyle, - State, -} from '../types/item'; +import { GShapeStyle, ItemShapeStyles, SHAPE_TYPE, SHAPE_TYPE_3D, ShapeStyle, State } from '../types/item'; import { NodeDisplayModel, NodeModelData, NodeShapeMap } from '../types/node'; import { getShapeAnimateBeginStyles } from './animate'; import { isArrayOverlap } from './array'; @@ -59,20 +46,13 @@ export const ShapeTagMap = { const LINE_TYPES = ['line', 'polyline', 'path']; -export const createShape = ( - type: SHAPE_TYPE, - style: GShapeStyle, - id: string, -) => { +export const createShape = (type: SHAPE_TYPE, style: GShapeStyle, id: string) => { const ShapeClass = ShapeTagMap[type]; const shape = new ShapeClass({ id, style }); if (style.draggable === undefined) shape.style.draggable = true; if (style.droppable === undefined) shape.style.droppable = true; if (LINE_TYPES.includes(type)) { - shape.style.increasedLineWidthForHitTesting = Math.max( - shape.style.lineWidth as number, - 6, - ); + shape.style.increasedLineWidthForHitTesting = Math.max(shape.style.lineWidth as number, 6); } return shape; }; @@ -82,6 +62,9 @@ export const createShape = ( * @param animates animate configs * @param timing * @param shapeId + * @param diffState + * @param diffState.previous + * @param diffState.current * @returns */ const findAnimateFields = ( @@ -92,8 +75,7 @@ const findAnimateFields = ( ) => { if (!animates?.[timing]?.length) return []; let animateFields = []; - const { previous: previousState = [], current: currentState = [] } = - diffState || {}; + const { previous: previousState = [], current: currentState = [] } = diffState || {}; const states = previousState.concat(currentState); animates[timing].forEach( // @ts-ignore @@ -107,10 +89,7 @@ const findAnimateFields = ( ) { if (animateShapeId === shapeId) { animateFields = animateFields.concat(fields); - } else if ( - (!animateShapeId || animateShapeId === 'group') && - fields.includes('opacity') - ) { + } else if ((!animateShapeId || animateShapeId === 'group') && fields.includes('opacity')) { // group opacity, all shapes animates with opacity animateFields.push('opacity'); } @@ -129,8 +108,17 @@ const findAnimateFields = ( * @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 / edge / combo * @param model data model of the node / edge / 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 */ export const upsertShape = ( @@ -155,12 +143,7 @@ export const upsertShape = ( if (!shape) { // find the animate styles, set them to be INIT_SHAPE_STYLES if (!disableAnimate && animates) { - const animateFields = findAnimateFields( - animates, - firstRendering ? 'buildIn' : 'update', - id, - diffState, - ); + const animateFields = findAnimateFields(animates, firstRendering ? 'buildIn' : 'update', id, diffState); shape = createShape(type, style, id); const initShapeStyles = getShapeAnimateBeginStyles(shape); animateFields.forEach((key) => { @@ -205,10 +188,7 @@ export const upsertShape = ( return shape; }; -export const getGroupSucceedMap = ( - group: IElement, - map?: { [id: string]: IElement }, -) => { +export const getGroupSucceedMap = (group: IElement, map?: { [id: string]: IElement }) => { const useMap = map || {}; group.children.forEach((child) => { if (child.tagName === 'group') getGroupSucceedMap(child, useMap); @@ -224,6 +204,9 @@ export const getGroupSucceedMap = ( * @param prevShapeMap previous shape map * @param newShapeMap new shape map * @param group container group + * @param labelGroup + * @param removeDiff + * @param shouldUpdate * @returns merged shape map */ export const updateShapes = ( @@ -253,10 +236,7 @@ export const updateShapes = ( } finalShapeMap[id] = newShape; const parentGroup = - newShape.attributes.dataIsLabel || - newShape.attributes.dataIsLabelBackground - ? labelGroup - : group; + newShape.attributes.dataIsLabel || newShape.attributes.dataIsLabelBackground ? labelGroup : group; if ( // NewShape is already in the group, no need to re-append. // Note: If the given child is a reference to an existing node in the document, @@ -332,10 +312,7 @@ export const mergeStyles = (styleMaps: ItemShapeStyles[]) => { * @param styleMap2 shapes' styles map as incoming map * @returns */ -const merge2Styles = ( - styleMap1: ItemShapeStyles, - styleMap2: ItemShapeStyles, -) => { +const merge2Styles = (styleMap1: ItemShapeStyles, styleMap2: ItemShapeStyles) => { if (!styleMap1) return { ...styleMap2 }; else if (!styleMap2) return { ...styleMap1 }; const mergedStyle = styleMap1; @@ -355,10 +332,7 @@ const merge2Styles = ( * @param points1 vertex array of polygon1 * @param points2 vertex array of polygon2 */ -export const isPolygonsIntersect = ( - points1: number[][], - points2: number[][], -): boolean => { +export const isPolygonsIntersect = (points1: number[][], points2: number[][]): boolean => { const getBBox = (points): Partial => { const xArr = points.map((p) => p[0]); const yArr = points.map((p) => p[1]); @@ -450,10 +424,7 @@ export const isPolygonsIntersect = ( export const intersectBBox = (box1: Partial, box2: Partial) => { if (!box2?.min || !box1?.min) return false; return ( - box2.min[0] <= box1.max[0] && - box2.max[0] >= box1.min[0] && - box2.min[1] <= box1.max[1] && - box2.max[1] >= box1.min[1] + box2.min[0] <= box1.max[0] && box2.max[0] >= box1.min[0] && box2.min[1] <= box1.max[1] && box2.max[1] >= box1.min[1] ); }; @@ -468,6 +439,10 @@ export const isPointInPolygon = (points: number[][], x: number, y: number) => { const n = points.length; // 判断两个double在eps精度下的大小关系 const tolerance = 1e-6; + /** + * + * @param xValue + */ function dcmp(xValue) { if (Math.abs(xValue) < tolerance) { return 0; @@ -534,14 +509,9 @@ const lineIntersectPolygon = (lines, line) => { * @param {Point} p1 end of the first line * @param {Point} p2 start of the second line * @param {Point} p3 end of the second line - * @return {Point} the intersect point + * @returns {Point} the intersect point */ -export const getLineIntersect = ( - p0: Point, - p1: Point, - p2: Point, - p3: Point, -): Point | null => { +export const getLineIntersect = (p0: Point, p1: Point, p2: Point, p3: Point): Point | null => { const tolerance = 0.0001; const E: Point = { @@ -593,10 +563,7 @@ const FIELDS_AFFECT_BBOX = { * @param style style object * @returns */ -export const isStyleAffectBBox = ( - type: SHAPE_TYPE | SHAPE_TYPE_3D, - style: ShapeStyle, -) => { +export const isStyleAffectBBox = (type: SHAPE_TYPE | SHAPE_TYPE_3D, style: ShapeStyle) => { return isArrayOverlap(Object.keys(style), FIELDS_AFFECT_BBOX[type]); }; @@ -605,6 +572,7 @@ export const isStyleAffectBBox = ( * @param shape target shape * @param style computed merged style * @param bounds shape's local bounds + * @param bbox * @returns */ export const getShapeLocalBoundsByStyle = ( @@ -617,20 +585,7 @@ export const getShapeLocalBoundsByStyle = ( center: number[]; halfExtents: number[]; } => { - const { - r, - rx, - ry, - width, - height, - depth = 0, - x1, - x2, - y1, - y2, - z1 = 0, - z2 = 0, - } = style; + const { r, rx, ry, width, height, depth = 0, x1, x2, y1, y2, z1 = 0, z2 = 0 } = style; const radius = Number(r); const radiusX = Number(rx); const radiusY = Number(ry); @@ -715,9 +670,7 @@ export const combineBounds = ( }); }); res.center = res.center.map((val, i) => (res.max[i] + res.min[i]) / 2); - res.halfExtents = res.halfExtents.map( - (val, i) => (res.max[i] - res.min[i]) / 2, - ); + res.halfExtents = res.halfExtents.map((val, i) => (res.max[i] - res.min[i]) / 2); return res; }; @@ -751,13 +704,10 @@ export const getCombinedBoundsByData = ( if (bounds) { if (item.model.data._isCombo) { // child is combo, move to the correct center - const { center: childComboCenter } = - (item as Combo).getCombinedBounds() || {}; + const { center: childComboCenter } = (item as Combo).getCombinedBounds() || {}; if (childComboCenter) { ['min', 'max', 'center'].forEach((field) => { - bounds[field] = bounds[field].map( - (val, i) => val - bounds.center[i] + childComboCenter[i], - ); + bounds[field] = bounds[field].map((val, i) => val - bounds.center[i] + childComboCenter[i]); }); } } @@ -773,12 +723,8 @@ export const getCombinedBoundsByData = ( } }); if (!validCounts) return false; - resBounds.size = resBounds.size.map( - (val, i) => resBounds.max[i] - resBounds.min[i], - ); - resBounds.center = resBounds.center.map( - (val, i) => (resBounds.max[i] + resBounds.min[i]) / 2, - ); + resBounds.size = resBounds.size.map((val, i) => resBounds.max[i] - resBounds.min[i]); + resBounds.center = resBounds.center.map((val, i) => (resBounds.max[i] + resBounds.min[i]) / 2); return resBounds as { center: Tuple3Number; min: Tuple3Number; @@ -810,12 +756,8 @@ export const getCombinedBoundsByItem = (items: (Node | Combo | Edge)[]) => { } }); if (!validCounts) return false; - resBounds.size = resBounds.size.map( - (val, i) => resBounds.max[i] - resBounds.min[i], - ); - resBounds.center = resBounds.center.map( - (val, i) => (resBounds.max[i] + resBounds.min[i]) / 2, - ); + resBounds.size = resBounds.size.map((val, i) => resBounds.max[i] - resBounds.min[i]); + resBounds.center = resBounds.center.map((val, i) => (resBounds.max[i] + resBounds.min[i]) / 2); return resBounds as { center: Tuple3Number; min: Tuple3Number; diff --git a/packages/g6/src/util/shape3d.ts b/packages/g6/src/util/shape3d.ts index 1adaad29f8d..372efdc519b 100644 --- a/packages/g6/src/util/shape3d.ts +++ b/packages/g6/src/util/shape3d.ts @@ -1,16 +1,16 @@ import { DisplayObject, Group } from '@antv/g'; import { - SphereGeometry, CubeGeometry, Mesh, MeshBasicMaterial, MeshLambertMaterial, MeshPhongMaterial, PlaneGeometry, + SphereGeometry, } from '@antv/g-plugin-3d'; import { EdgeShapeMap } from '../types/edge'; -import { NodeShapeMap } from '../types/node'; import { GShapeStyle, SHAPE_TYPE, SHAPE_TYPE_3D } from '../types/item'; +import { NodeShapeMap } from '../types/node'; import { createShape } from './shape'; const GeometryTagMap = { @@ -21,23 +21,14 @@ const GeometryTagMap = { const GEOMETRY_SIZE = 10; -export const createShape3D = ( - type: SHAPE_TYPE_3D | SHAPE_TYPE, - style: GShapeStyle, - id: string, - device: any, -) => { +export const createShape3D = (type: SHAPE_TYPE_3D | SHAPE_TYPE, style: GShapeStyle, id: string, device: any) => { // It is not a 3d Shape but 2d. if (!GeometryTagMap[type]) { return createShape(type as SHAPE_TYPE, style, id); } // materialType: 'lambert' | 'phong' | 'basic', TODO: type - const { - materialType = 'lambert', - materialProps = {}, - ...otherStyles - } = style as any; + const { materialType = 'lambert', materialProps = {}, ...otherStyles } = style as any; if (!device.GeometryCache) { device.GeometryCache = {}; } @@ -45,14 +36,11 @@ export const createShape3D = ( // Share the same geometry & material between meshes. let cachedGeometry = device.GeometryCache[type]; if (!cachedGeometry) { - cachedGeometry = device.GeometryCache[type] = new GeometryTagMap[type]( - device, - { - radius: GEOMETRY_SIZE, - latitudeBands: 32, - longitudeBands: 32, - }, - ); + cachedGeometry = device.GeometryCache[type] = new GeometryTagMap[type](device, { + radius: GEOMETRY_SIZE, + latitudeBands: 32, + longitudeBands: 32, + }); } if (!device.MaterialCache) { @@ -61,26 +49,18 @@ export const createShape3D = ( if (!device.MaterialCache[materialType as string]) { switch (materialType) { case 'basic': - device.MaterialCache[materialType as string] = new MeshBasicMaterial( - device, - materialProps, - ); + device.MaterialCache[materialType as string] = new MeshBasicMaterial(device, materialProps); break; case 'phong': { - device.MaterialCache[materialType as string] = new MeshPhongMaterial( - device, - { - shininess: 30, - ...materialProps, - }, - ); + device.MaterialCache[materialType as string] = new MeshPhongMaterial(device, { + shininess: 30, + ...materialProps, + }); + break; } case 'lambert': default: { - device.MaterialCache[materialType as string] = new MeshLambertMaterial( - device, - materialProps, - ); + device.MaterialCache[materialType as string] = new MeshLambertMaterial(device, materialProps); break; } } @@ -103,19 +83,14 @@ export const createShape3D = ( // Scale the shape to the correct size. switch (type) { case 'cube': - shape.scale([ - style.width / GEOMETRY_SIZE, - style.height / GEOMETRY_SIZE, - style.depth / GEOMETRY_SIZE, - ]); + shape.scale([style.width / GEOMETRY_SIZE, style.height / GEOMETRY_SIZE, style.depth / GEOMETRY_SIZE]); break; case 'plane': shape.scale(style.width / GEOMETRY_SIZE, 1, style.depth / GEOMETRY_SIZE); break; case 'sphere': default: { - const scaling = - (((style as any).r || style.radius) as number) / GEOMETRY_SIZE; + const scaling = (((style as any).r || style.radius) as number) / GEOMETRY_SIZE; shape.scale(scaling); } } @@ -159,6 +134,8 @@ export const upsertShape3D = ( * @param prevShapeMap previous shape map * @param newShapeMap new shape map * @param group container group + * @param removeDiff + * @param shouldUpdate * @returns merged shape map */ export const updateShapes3D = ( diff --git a/packages/g6/src/util/text.ts b/packages/g6/src/util/text.ts index 32691f28150..e760fd8a307 100644 --- a/packages/g6/src/util/text.ts +++ b/packages/g6/src/util/text.ts @@ -7,6 +7,7 @@ import { Point } from '../types/common'; * @param keyShapeBox * @param maxWidth * @param zoom + * @param enableBalanceShape * @returns */ export const getWordWrapWidthByBox = ( @@ -27,19 +28,12 @@ export const getWordWrapWidthByBox = ( * @param zoom * @returns */ -export const getWordWrapWidthByEnds = ( - points: Point[], - maxWidth: string | number, - zoom = 1, -) => { +export const getWordWrapWidthByEnds = (points: Point[], maxWidth: string | number, zoom = 1) => { const dist = getEuclideanDistance(points[0], points[1]) * zoom; return getWordWrapWidthWithBase(dist, maxWidth); }; -const getWordWrapWidthWithBase = ( - length: number, - maxWidth: string | number, -) => { +const getWordWrapWidthWithBase = (length: number, maxWidth: string | number) => { let wordWrapWidth = 2 * length; if (typeof maxWidth === 'string') { wordWrapWidth = (length * Number(maxWidth.replace('%', ''))) / 100; diff --git a/packages/g6/src/util/warn.ts b/packages/g6/src/util/warn.ts index 7d6e12f275d..20a86cd545f 100644 --- a/packages/g6/src/util/warn.ts +++ b/packages/g6/src/util/warn.ts @@ -11,10 +11,14 @@ type WarnOption = { scope: string; }; +/** + * + * @param root0 + * @param root0.optionName + * @param root0.shouldBe + * @param root0.now + * @param root0.scope + */ export function warn({ optionName, shouldBe, now, scope }: WarnOption) { - console.warn( - `G6 [${scope}]: Invalid option, ${optionName} must be one of ${shouldBe.join( - ', ', - )}, but got ${now}`, - ); + console.warn(`G6 [${scope}]: Invalid option, ${optionName} must be one of ${shouldBe.join(', ')}, but got ${now}`); } diff --git a/packages/g6/src/util/zoom.ts b/packages/g6/src/util/zoom.ts index cd00ccc4d45..bdd82fedcda 100644 --- a/packages/g6/src/util/zoom.ts +++ b/packages/g6/src/util/zoom.ts @@ -5,9 +5,7 @@ import { LodLevel, LodLevelRanges } from '../types/item'; * @param lodLevels * @returns */ -export const formatLodLevels = ( - lodLevels?: LodLevel[], -): LodLevelRanges | undefined => { +export const formatLodLevels = (lodLevels?: LodLevel[]): LodLevelRanges | undefined => { if (!lodLevels?.length) return; const primaryLevel = lodLevels.find((level) => level.primary); if (!primaryLevel) return; diff --git a/packages/g6/tests/bak/items-node-cube.spec.ts b/packages/g6/tests/bak/items-node-cube.spec.ts deleted file mode 100644 index abf2461a27f..00000000000 --- a/packages/g6/tests/bak/items-node-cube.spec.ts +++ /dev/null @@ -1,37 +0,0 @@ -import { resetEntityCounter } from '@antv/g'; -import cube from '../demo/item/node/cube'; -import './utils/useSnapshotMatchers'; -import { createContext, sleep } from './utils'; - -describe('Items node cube', () => { - beforeEach(() => { - /** - * SVG Snapshot testing will generate a unique id for each element. - * Reset to 0 to keep snapshot consistent. - */ - resetEntityCounter(); - }); - - it('should be rendered correctly with WebGL', (done) => { - const dir = `${__dirname}/snapshots/webgl/items/node`; - const { backgroundCanvas, canvas, transientCanvas, container } = - createContext('webgl', 500, 500); - - const graph = cube({ - container, - backgroundCanvas, - canvas, - transientCanvas, - width: 500, - height: 500, - renderer: 'webgl-3d', - }); - - graph.on('afterlayout', async () => { - await sleep(300); - await expect(canvas).toMatchWebGLSnapshot(dir, 'items-node-cube'); - graph.destroy(); - done(); - }); - }); -}); diff --git a/packages/g6/tests/bak/plugins-legend.spec.ts b/packages/g6/tests/bak/plugins-legend.spec.ts deleted file mode 100644 index e78de40b416..00000000000 --- a/packages/g6/tests/bak/plugins-legend.spec.ts +++ /dev/null @@ -1,175 +0,0 @@ -import { resetEntityCounter } from '@antv/g'; -import legend from '../demo/plugins/legend'; -import './utils/useSnapshotMatchers'; -import { createContext, triggerEvent } from './utils'; -import { createNodeGCanvas } from './utils/createNodeGCanvas'; - -describe('Plugin legend', () => { - beforeEach(() => { - /** - * SVG Snapshot testing will generate a unique id for each element. - * Reset to 0 to keep snapshot consistent. - */ - resetEntityCounter(); - }); - - it('should be rendered correctly with Canvas2D', (done) => { - const dir = `${__dirname}/snapshots/canvas/plugins/legend`; - const { backgroundCanvas, canvas, transientCanvas, container } = - createContext('canvas', 500, 500); - const legendCanvas = createNodeGCanvas('canvas', 200, 200); - - const graph = legend({ - container, - backgroundCanvas, - canvas, - transientCanvas, - width: 500, - height: 500, - legendCanvas, - }); - - const plugin = - graph['pluginController']['pluginMap'].get('legend1')!.plugin; - - graph.on('afterlayout', async () => { - await expect(legendCanvas).toMatchSVGSnapshot(dir, 'plugins-legend'); - - /** - * Select nodeb mark by click. - */ - triggerEvent(plugin, 'mousedown', 72, 56); - triggerEvent(plugin, 'mouseup', 72, 56); - await expect(legendCanvas).toMatchSVGSnapshot( - dir, - 'plugins-legend-select-marker-node', - ); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'plugins-legend-select-node', - ); - - /** - * Click document to clear filter state. - */ - triggerEvent(plugin, 'mousedown', 0, 0); - triggerEvent(plugin, 'mouseup', 0, 0); - await expect(legendCanvas).toMatchSVGSnapshot( - dir, - 'plugins-legend-deselect-marker-node', - ); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'plugins-legend-deselect-node', - ); - - /** - * Activate nodeb mark by mouseenter. - */ - triggerEvent(plugin, 'mousemove', 72, 80); - triggerEvent(plugin, 'mousemove', 72, 56); - await expect(legendCanvas).toMatchSVGSnapshot( - dir, - 'plugins-legend-activate-marker-node', - ); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'plugins-legend-activate-node', - ); - - /** - * Deactivate nodeb mark by mouseleave. - */ - triggerEvent(plugin, 'mousemove', 72, 80); - await expect(legendCanvas).toMatchSVGSnapshot( - dir, - 'plugins-legend-deactivate-marker-node', - ); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'plugins-legend-deactivate-node', - ); - - /** - * Select e1 mark by click. - */ - triggerEvent(plugin, 'mousedown', 72, 128); - triggerEvent(plugin, 'mouseup', 72, 128); - await expect(legendCanvas).toMatchSVGSnapshot( - dir, - 'plugins-legend-select-marker-edge', - ); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'plugins-legend-select-edge', - ); - - /** - * Click document to clear filter state. - */ - triggerEvent(plugin, 'mousedown', 0, 0); - triggerEvent(plugin, 'mouseup', 0, 0); - await expect(legendCanvas).toMatchSVGSnapshot( - dir, - 'plugins-legend-deselect-marker-node', - ); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'plugins-legend-deselect-node', - ); - - /** - * Activate e1 mark by mouseenter. - */ - triggerEvent(plugin, 'mousemove', 72, 200); - triggerEvent(plugin, 'mousemove', 72, 128); - await expect(legendCanvas).toMatchSVGSnapshot( - dir, - 'plugins-legend-activate-marker-edge', - ); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'plugins-legend-activate-edge', - ); - - /** - * Deactivate e1 mark by mouseleave. - */ - triggerEvent(plugin, 'mousemove', 72, 200); - await expect(legendCanvas).toMatchSVGSnapshot( - dir, - 'plugins-legend-deactivate-marker-edge', - ); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'plugins-legend-deactivate-edge', - ); - - graph.destroy(); - done(); - }); - }); - - it('should be rendered correctly with SVG', (done) => { - const dir = `${__dirname}/snapshots/svg/plugins/legend`; - const { backgroundCanvas, canvas, transientCanvas, container } = - createContext('svg', 500, 500); - const legendCanvas = createNodeGCanvas('svg', 200, 200); - - const graph = legend({ - container, - backgroundCanvas, - canvas, - transientCanvas, - width: 500, - height: 500, - legendCanvas, - }); - - graph.on('afterlayout', async () => { - await expect(legendCanvas).toMatchSVGSnapshot(dir, 'plugins-legend'); - graph.destroy(); - done(); - }); - }); -}); diff --git a/packages/g6/tests/demo/behaviors/activate-relations.ts b/packages/g6/tests/demo/behaviors/activate-relations.ts index 017aba8299b..8c79d42025b 100644 --- a/packages/g6/tests/demo/behaviors/activate-relations.ts +++ b/packages/g6/tests/demo/behaviors/activate-relations.ts @@ -1,5 +1,5 @@ +import { Extensions, Graph, extend } from '../../../src/index'; import { TestCaseContext } from '../interface'; -import { Graph, Extensions, extend } from '../../../src/index'; export default (context: TestCaseContext) => { const ExtGraph = extend(Graph, { diff --git a/packages/g6/tests/demo/behaviors/brush-select.ts b/packages/g6/tests/demo/behaviors/brush-select.ts index bf853b38a44..d710162f04d 100644 --- a/packages/g6/tests/demo/behaviors/brush-select.ts +++ b/packages/g6/tests/demo/behaviors/brush-select.ts @@ -1,4 +1,4 @@ -import { Graph, Extensions, extend } from '../../../src/index'; +import { Extensions, Graph, extend } from '../../../src/index'; import { TestCaseContext } from '../interface'; export default (context: TestCaseContext) => { const ExtGraph = extend(Graph, { diff --git a/packages/g6/tests/demo/behaviors/collapse-expand-tree.ts b/packages/g6/tests/demo/behaviors/collapse-expand-tree.ts index 500705c367c..02115e3f4f6 100644 --- a/packages/g6/tests/demo/behaviors/collapse-expand-tree.ts +++ b/packages/g6/tests/demo/behaviors/collapse-expand-tree.ts @@ -2,10 +2,7 @@ import G6 from '../../../src/index'; import { treeDataCfg } from '../../datasets/dataCfg'; import { TestCaseContext } from '../interface'; -export default ( - context: TestCaseContext, - options: { trigger?: string } = {}, -) => { +export default (context: TestCaseContext, options: { trigger?: string } = {}) => { // no animations for testing const { trigger = 'click' } = options; const graph = new G6.Graph({ diff --git a/packages/g6/tests/demo/behaviors/create-edge.ts b/packages/g6/tests/demo/behaviors/create-edge.ts index 7dc67160fcf..53fdcf03ed1 100644 --- a/packages/g6/tests/demo/behaviors/create-edge.ts +++ b/packages/g6/tests/demo/behaviors/create-edge.ts @@ -1,4 +1,4 @@ -import { extend, Graph, Extensions } from '../../../src/index'; +import { Extensions, Graph, extend } from '../../../src/index'; import { TestCaseContext } from '../interface'; export default (context: TestCaseContext, options) => { diff --git a/packages/g6/tests/demo/behaviors/shortcuts-call.ts b/packages/g6/tests/demo/behaviors/shortcuts-call.ts index 9de96ab16e9..0b6266b11f4 100644 --- a/packages/g6/tests/demo/behaviors/shortcuts-call.ts +++ b/packages/g6/tests/demo/behaviors/shortcuts-call.ts @@ -1,4 +1,4 @@ -import { Graph, extend, Extensions } from '../../../src/index'; +import { Extensions, Graph, extend } from '../../../src/index'; import { TestCaseContext } from '../interface'; export default (context: TestCaseContext, options = {}) => { diff --git a/packages/g6/tests/demo/combo/combo-basic.ts b/packages/g6/tests/demo/combo/combo-basic.ts index 829a9822551..b5a58ede5ea 100644 --- a/packages/g6/tests/demo/combo/combo-basic.ts +++ b/packages/g6/tests/demo/combo/combo-basic.ts @@ -1,4 +1,4 @@ -import { Graph, Extensions, extend } from '../../../src/index'; +import { Extensions, Graph, extend } from '../../../src/index'; export default ( context, diff --git a/packages/g6/tests/demo/combo/combo-rect.ts b/packages/g6/tests/demo/combo/combo-rect.ts index 6fe0355f80e..315f2b08b39 100644 --- a/packages/g6/tests/demo/combo/combo-rect.ts +++ b/packages/g6/tests/demo/combo/combo-rect.ts @@ -1,10 +1,7 @@ -import { Graph, Extensions, stdLib, extend } from '../../../src/index'; +import { Extensions, Graph, extend, stdLib } from '../../../src/index'; +import { data as comboData } from '../../datasets/combo-data'; import { container, height, width } from '../../datasets/const'; -import { - data as comboData, - smallData as smallComboData, -} from '../../datasets/combo-data'; export default () => { const ExtGraph = extend(Graph, { diff --git a/packages/g6/tests/demo/data/data-from-v4.ts b/packages/g6/tests/demo/data/data-from-v4.ts index 97450aafe97..b52a3fed59a 100644 --- a/packages/g6/tests/demo/data/data-from-v4.ts +++ b/packages/g6/tests/demo/data/data-from-v4.ts @@ -1,19 +1,9 @@ import { Layout, LayoutMapping } from '@antv/layout'; -import { - Graph, - extend, - stdLib, - Extensions, - GraphCore, -} from '../../../src/index'; -import { TestCaseContext } from '../interface'; +import { Extensions, Graph, GraphCore, extend } from '../../../src/index'; import { GraphDataChanges } from '../../../src/types/data'; +import { TestCaseContext } from '../interface'; -const edgeClusterTransform = ( - data: GraphDataChanges, - options = {}, - graphCore?: GraphCore, -): GraphDataChanges => { +const edgeClusterTransform = (data: GraphDataChanges, options = {}, graphCore?: GraphCore): GraphDataChanges => { const { dataAdded, dataRemoved, dataUpdated } = data; const handler = (data, options = {}, userGraphCore) => { const { nodes, edges } = data; @@ -39,22 +29,22 @@ class LineLayout implements Layout<{}> { } /** * Return the positions of nodes and edges(if needed). + * @param graph + * @param options */ async execute(graph, options = {}) { return this.genericLineLayout(false, graph, options); } /** * To directly assign the positions to the nodes. + * @param graph + * @param options */ async assign(graph, options = {}) { this.genericLineLayout(true, graph, options); } - private async genericLineLayout( - assign: boolean, - graph, - options = {}, - ): Promise { + private async genericLineLayout(assign: boolean, graph, options = {}): Promise { const { height = 500 } = { ...this.options, ...options }; const nodes = graph.getAllNodes(); diff --git a/packages/g6/tests/demo/data/graphCore.ts b/packages/g6/tests/demo/data/graphCore.ts index 9a7de83c707..bac2c3ca0d8 100644 --- a/packages/g6/tests/demo/data/graphCore.ts +++ b/packages/g6/tests/demo/data/graphCore.ts @@ -1,5 +1,4 @@ -import { Layout, LayoutMapping } from '@antv/layout'; -import { Graph, extend, stdLib } from '../../../src/index'; +import { Graph } from '../../../src/index'; import { TestCaseContext } from '../interface'; const data = { @@ -1383,13 +1382,7 @@ export default (context: TestCaseContext, options?: {}) => { }, }, modes: { - default: [ - 'drag-node', - 'click-select', - 'zoom-canvas', - 'drag-canvas', - 'drag-combo', - ], + default: ['drag-node', 'click-select', 'zoom-canvas', 'drag-canvas', 'drag-combo'], }, data, }); diff --git a/packages/g6/tests/demo/data/process-parallel-edges.ts b/packages/g6/tests/demo/data/process-parallel-edges.ts index 89f95eb4a03..4b0ab91139a 100644 --- a/packages/g6/tests/demo/data/process-parallel-edges.ts +++ b/packages/g6/tests/demo/data/process-parallel-edges.ts @@ -1,5 +1,5 @@ -import { TestCaseContext } from '../interface'; import { Extensions, Graph, extend } from '../../../src/index'; +import { TestCaseContext } from '../interface'; const data = { nodes: [ @@ -100,13 +100,7 @@ export default (context: TestCaseContext) => { transforms: [ { type: 'process-parallel-edges', - activeLifecycle: [ - 'read', - 'changeData', - 'updateData', - 'addData', - 'removeData', - ], // default: 'read' + activeLifecycle: ['read', 'changeData', 'updateData', 'addData', 'removeData'], // default: 'read' multiEdgeType: 'quadratic-edge', loopEdgeType: 'loop-edge', }, diff --git a/packages/g6/tests/demo/demo/data3d.ts b/packages/g6/tests/demo/demo/data3d.ts index 7aef6a46a06..367cbc9208d 100644 --- a/packages/g6/tests/demo/demo/data3d.ts +++ b/packages/g6/tests/demo/demo/data3d.ts @@ -15946,8 +15946,7 @@ export default { { id: '2335', data: { - label: - 'Countryside/Hodgkins/Indian Head Park/Willow Springs Suburban LIFE Citizen (Illinois)', + label: 'Countryside/Hodgkins/Indian Head Park/Willow Springs Suburban LIFE Citizen (Illinois)', x: 6665.528665655571, y: 641.9570084920047, z: -238.00546373774057, @@ -21530,8 +21529,7 @@ export default { { id: '3017', data: { - label: - 'National Rugby League Championship Company (Australia - Asia)', + label: 'National Rugby League Championship Company (Australia - Asia)', x: 1418.9285794433872, y: 2043.2893506199605, z: -899.8344252545023, @@ -21663,8 +21661,7 @@ export default { { id: '3030', data: { - label: - 'PDN Xinren Information Technology Co. Ltd. (Australia - Asia)', + label: 'PDN Xinren Information Technology Co. Ltd. (Australia - Asia)', x: 1530.797803881288, y: 2353.679998459286, z: -250.29084276656107, @@ -61287,8 +61284,7 @@ export default { { id: '6907', data: { - label: - 'Outsource Automated Services and Integrated Systems Reservations Services', + label: 'Outsource Automated Services and Integrated Systems Reservations Services', x: 7077.1391361480455, y: -965.7207905014666, z: 2140.2753201072715, @@ -65766,8 +65762,7 @@ export default { { id: '6142', data: { - label: - 'Automotive Information Center And Its Autosite Web-Based Products', + label: 'Automotive Information Center And Its Autosite Web-Based Products', x: 5962.936678704428, y: 4775.8809934958945, z: -398.1871015058835, diff --git a/packages/g6/tests/demo/demo/demo.ts b/packages/g6/tests/demo/demo/demo.ts index 667015f75e7..63a3b1d5a0b 100644 --- a/packages/g6/tests/demo/demo/demo.ts +++ b/packages/g6/tests/demo/demo/demo.ts @@ -1,11 +1,9 @@ -import { initThreads, supportsThreads, ForceLayout } from '@antv/layout-wasm'; -import { labelPropagation } from '@antv/algorithm'; +import { initThreads, supportsThreads } from '@antv/layout-wasm'; import Stats from 'stats.js'; -import G6, { Graph, Extensions, extend, GraphData } from '../../../src/index'; +import { Extensions, Graph, GraphData, extend } from '../../../src/index'; -import { container, height, width } from '../../datasets/const'; import { RendererName } from '../../../src/types/render'; -import { Point } from '../../../src/types/common'; +import { container, width } from '../../datasets/const'; import data from './data.json'; import data3d from './data3d'; @@ -14,7 +12,7 @@ let dataFor2D: GraphData = { nodes: [], edges: [] }; let dataFor3D: GraphData = { nodes: [], edges: [] }; let colorSelects = []; const { nodes, edges } = data; -export { nodes, edges }; +export { edges, nodes }; const dataFormat = (dataAUR, options = {}, graphCore) => { const { dataAdded, dataUpdated, dataRemoved } = dataAUR; @@ -443,8 +441,7 @@ const create3DGraph = async () => { let i = 0; const tick = () => { camera.setPosition([oripos[0], oripos[1], oripos[2] + k]); - const rdx = - i < 100 ? Math.min(i * 0.5, 20) : Math.min((200 - i) * 0.2, 20); + const rdx = i < 100 ? Math.min(i * 0.5, 20) : Math.min((200 - i) * 0.2, 20); rotate(camera, rdx, rdx, newGraph); timer = requestAnimationFrame(tick); if (i > 200) cancelAnimationFrame(timer); @@ -582,9 +579,7 @@ const addButtons = () => { addColorBtn.style.color = 'rgb(34, 126, 255)'; paletteContainer.appendChild(addColorBtn); addColorBtn.addEventListener('click', (e) => { - colorSelects.push( - generateColorSelect(`${colorSelects.length}`, colorsContainer), - ); + colorSelects.push(generateColorSelect(`${colorSelects.length}`, colorsContainer)); }); const colorsContainer = document.createElement('div'); @@ -683,7 +678,6 @@ const handleSwitchRenderer = (rendererName, oldgraph) => { // oldgraph.changeRenderer('webgl'); break; case 'svg': - // comming soon default: break; } @@ -825,8 +819,7 @@ export default async () => { dataFor3D = getDataFor3D(data3d); graph = create2DGraph(); - const { rendererSelect, themeSelect, customThemeSelect, zoomIn, zoomOut } = - addButtons(); + const { rendererSelect, themeSelect, customThemeSelect, zoomIn, zoomOut } = addButtons(); rendererSelect.addEventListener('change', (e: any) => { const type = e.target.value; diff --git a/packages/g6/tests/demo/demo/demoFor4.ts b/packages/g6/tests/demo/demo/demoFor4.ts index a4be119b95a..19271ffb9a2 100644 --- a/packages/g6/tests/demo/demo/demoFor4.ts +++ b/packages/g6/tests/demo/demo/demoFor4.ts @@ -59,12 +59,7 @@ const subjectColors = [ '#008685', '#F08BB4', ]; -const colorSets = G6.Util.getColorSetsBySubjectColors( - subjectColors, - '#fff', - 'default', - '#777', -); +const colorSets = G6.Util.getColorSetsBySubjectColors(subjectColors, '#fff', 'default', '#777'); clusteredData.clusters.forEach((cluster, i) => { const colorSet = colorSets[i % colorSets.length]; diff --git a/packages/g6/tests/demo/demo/demoForPolyline.ts b/packages/g6/tests/demo/demo/demoForPolyline.ts index 2f3cac6f9ba..42dc15e79c2 100644 --- a/packages/g6/tests/demo/demo/demoForPolyline.ts +++ b/packages/g6/tests/demo/demo/demoForPolyline.ts @@ -1,5 +1,5 @@ import Stats from 'stats.js'; -import { Graph, Extensions, extend } from '../../../src/index'; +import { Extensions, Graph, extend } from '../../../src/index'; import { container, height, width } from '../../datasets/const'; diff --git a/packages/g6/tests/demo/demo/diamond.ts b/packages/g6/tests/demo/demo/diamond.ts index ed454650867..84c8e2ec0bf 100644 --- a/packages/g6/tests/demo/demo/diamond.ts +++ b/packages/g6/tests/demo/demo/diamond.ts @@ -1,5 +1,5 @@ +import { Extensions, Graph, extend } from '../../../src/index'; import { TestCaseContext } from '../interface'; -import { Graph, Extensions, extend } from '../../../src/index'; let graph: any; diff --git a/packages/g6/tests/demo/demo/ellipse.ts b/packages/g6/tests/demo/demo/ellipse.ts index 1592fd8f9bc..0c6cf38838a 100644 --- a/packages/g6/tests/demo/demo/ellipse.ts +++ b/packages/g6/tests/demo/demo/ellipse.ts @@ -1,5 +1,5 @@ +import { Extensions, Graph, extend } from '../../../src/index'; import { TestCaseContext } from '../interface'; -import { Graph, Extensions, extend } from '../../../src/index'; let graph: any; diff --git a/packages/g6/tests/demo/demo/hexagon.ts b/packages/g6/tests/demo/demo/hexagon.ts index efe0f3a3c14..475fd349e31 100644 --- a/packages/g6/tests/demo/demo/hexagon.ts +++ b/packages/g6/tests/demo/demo/hexagon.ts @@ -1,5 +1,5 @@ +import { Extensions, Graph, extend } from '../../../src/index'; import { TestCaseContext } from '../interface'; -import { Graph, Extensions, extend } from '../../../src/index'; let graph: any; diff --git a/packages/g6/tests/demo/demo/menu.ts b/packages/g6/tests/demo/demo/menu.ts index eca307e5a9a..67e29804aae 100644 --- a/packages/g6/tests/demo/demo/menu.ts +++ b/packages/g6/tests/demo/demo/menu.ts @@ -1,4 +1,4 @@ -import { Graph, Extensions, extend } from '../../../src/index'; +import { Extensions, Graph, extend } from '../../../src/index'; import { container, height, width } from '../../datasets/const'; @@ -61,7 +61,10 @@ export default () => { handleMenuClick: (e, id) => { console.log(id); }, - /** async string menu */ + /** + * async string menu + * @param e + */ getContent: (e) => { return new Promise((resolve) => { const data = ` @@ -77,7 +80,10 @@ export default () => { }, }, ], - /** default menu */ + /** + * default menu + * @param nodeInnerModel + */ // plugins: ['menu'], node: (nodeInnerModel: any) => { const { id, data } = nodeInnerModel; diff --git a/packages/g6/tests/demo/demo/modelRect.ts b/packages/g6/tests/demo/demo/modelRect.ts index 6076d6e5980..7b14e364059 100644 --- a/packages/g6/tests/demo/demo/modelRect.ts +++ b/packages/g6/tests/demo/demo/modelRect.ts @@ -1,5 +1,5 @@ +import { Extensions, Graph, extend } from '../../../src/index'; import { TestCaseContext } from '../interface'; -import { Graph, Extensions, extend } from '../../../src/index'; let graph: any; diff --git a/packages/g6/tests/demo/demo/quadratic.ts b/packages/g6/tests/demo/demo/quadratic.ts index 4f675e170c7..05c690b77ae 100644 --- a/packages/g6/tests/demo/demo/quadratic.ts +++ b/packages/g6/tests/demo/demo/quadratic.ts @@ -1,4 +1,4 @@ -import { Graph, Extensions, extend } from '../../../src/index'; +import { Extensions, Graph, extend } from '../../../src/index'; import { container, height, width } from '../../datasets/const'; export default () => { diff --git a/packages/g6/tests/demo/demo/star.ts b/packages/g6/tests/demo/demo/star.ts index c280940d88d..73cbd8efdc4 100644 --- a/packages/g6/tests/demo/demo/star.ts +++ b/packages/g6/tests/demo/demo/star.ts @@ -1,6 +1,6 @@ // 这是从外部引入的功能 +import { Extensions, Graph, extend } from '../../../src/index'; import { TestCaseContext } from '../interface'; -import { Graph, Extensions, extend } from '../../../src/index'; let graph: any; diff --git a/packages/g6/tests/demo/demo/tooltip.ts b/packages/g6/tests/demo/demo/tooltip.ts index 6abc664f33c..7ab3f39c215 100644 --- a/packages/g6/tests/demo/demo/tooltip.ts +++ b/packages/g6/tests/demo/demo/tooltip.ts @@ -1,4 +1,4 @@ -import { Graph, Extensions, extend } from '../../../src/index'; +import { Extensions, Graph, extend } from '../../../src/index'; import { container, height, width } from '../../datasets/const'; export default () => { @@ -58,7 +58,10 @@ export default () => { type: 'tooltip', trigger: 'pointerenter', fixToNode: 'leftBottom', - /** async string tooltip*/ + /** + * async string tooltip + * @param e + */ getContent: (e) => { return new Promise((resolve) => { const data = ` @@ -74,7 +77,10 @@ export default () => { }, }, ], - /** default tooltip */ + /** + * default tooltip + * @param nodeInnerModel + */ // plugins: ['tooltip'], node: (nodeInnerModel: any) => { const { id, data } = nodeInnerModel; diff --git a/packages/g6/tests/demo/demo/triangle.ts b/packages/g6/tests/demo/demo/triangle.ts index 93be3b0d383..35a0d72f4db 100644 --- a/packages/g6/tests/demo/demo/triangle.ts +++ b/packages/g6/tests/demo/demo/triangle.ts @@ -1,5 +1,5 @@ +import { Extensions, Graph, extend } from '../../../src/index'; import { TestCaseContext } from '../interface'; -import { Graph, Extensions, extend } from '../../../src/index'; let graph: any; diff --git a/packages/g6/tests/demo/index.ts b/packages/g6/tests/demo/index.ts index 308679db77a..32062a70e66 100644 --- a/packages/g6/tests/demo/index.ts +++ b/packages/g6/tests/demo/index.ts @@ -1,7 +1,5 @@ // import demoFor4 from './demo/demoFor4'; -import anchor from './item/anchor'; import animations_node_build_in from './animations/node-build-in'; -import arrow from './item/edge/arrow'; import behaviors_activateRelations from './behaviors/activate-relations'; import behaviors_brush_select from './behaviors/brush-select'; import behaviors_click_select from './behaviors/click-select'; @@ -11,37 +9,45 @@ import behaviors_dragCanvas from './behaviors/drag-canvas'; import behaviors_scrollCanvas from './behaviors/scroll-canvas'; import behaviors_shortcuts_call from './behaviors/shortcuts-call'; import behaviors_zoomCanvas from './behaviors/zoom-canvas'; -import circularUpdate from './layouts/circular-update'; import comboBasic from './combo/combo-basic'; -import comboDagre from './layouts/dagre-combo'; import comboRect from './combo/combo-rect'; -import cube from './item/node/cube'; -import cubic_edge from './item/edge/cubic-edge'; -import cubic_horizon_edge from './item/edge/cubic-horizontal-edge'; -import cubic_vertical_edge from './item/edge/cubic-vertical-edge'; -import dagreUpdate from './layouts/dagre-update'; import dataV4 from './data/data-from-v4'; import dataValidate from './data/data-validate'; +import graphCore from './data/graphCore'; +import processParallelEdges from './data/process-parallel-edges'; import demo from './demo/demo'; import demoForPolyline from './demo/demoForPolyline'; import diamond from './demo/diamond'; -import donut_node from './item/node/donut-node'; -import edgeFilterLens from './plugins/edgeFilterLens'; import ellipse from './demo/ellipse'; -import fisheye from './plugins/fisheye'; -import fps_test from './performance/fps'; -import graphCore from './data/graphCore'; import hexagon from './demo/hexagon'; -import history from './plugins/history'; -import history_combo from './plugins/history-combo'; -import hull from './plugins/hull'; -import image_clip_node from './item/node/image-clip'; +import menu from './demo/menu'; +import modelRect from './demo/modelRect'; +import quadratic from './demo/quadratic'; +import rect from './demo/rect'; +import star from './demo/star'; +import tooltip from './demo/tooltip'; +import triangle from './demo/triangle'; +import anchor from './item/anchor'; +import arrow from './item/edge/arrow'; +import cubic_edge from './item/edge/cubic-edge'; +import cubic_horizon_edge from './item/edge/cubic-horizontal-edge'; +import cubic_vertical_edge from './item/edge/cubic-vertical-edge'; +import line_edge from './item/edge/line-edge'; +import loop_edge from './item/edge/loop-edge'; +import polyline from './item/edge/polyline-edge'; +import label from './item/label'; +import cube from './item/node/cube'; +import donut_node from './item/node/donut-node'; import image_node from './item/node/image'; +import image_clip_node from './item/node/image-clip'; import layouts_circular from './layouts/circular'; +import circularUpdate from './layouts/circular-update'; import layouts_combocombined from './layouts/combo-combined'; import layouts_custom from './layouts/custom'; import layouts_d3force from './layouts/d3force'; import layouts_dagre from './layouts/dagre'; +import comboDagre from './layouts/dagre-combo'; +import dagreUpdate from './layouts/dagre-update'; import layouts_force from './layouts/force'; import layouts_force_3d from './layouts/force-3d'; import layouts_force_wasm from './layouts/force-wasm'; @@ -50,38 +56,30 @@ import layouts_forceatlas2_wasm from './layouts/forceatlas2-wasm'; import layouts_fruchterman_gpu from './layouts/fruchterman-gpu'; import layouts_fruchterman_wasm from './layouts/fruchterman-wasm'; import layouts_grid from './layouts/grid'; -import legend from './plugins/legend'; -import line_edge from './item/edge/line-edge'; -import loop_edge from './item/edge/loop-edge'; -import map from './plugins/map'; -import mapper from './visual/mapper'; -import menu from './demo/menu'; -import minimap from './plugins/minimap'; -import modelRect from './demo/modelRect'; -import performance from './performance/performance'; +import fps_test from './performance/fps'; import performance_layout from './performance/layout'; import performance_layout_3d from './performance/layout-3d'; -import polyline from './item/edge/polyline-edge'; -import processParallelEdges from './data/process-parallel-edges'; -import quadratic from './demo/quadratic'; -import rect from './demo/rect'; +import performance from './performance/performance'; +import edgeBundling from './plugins/edgeBundling'; +import edgeFilterLens from './plugins/edgeFilterLens'; +import fisheye from './plugins/fisheye'; +import history from './plugins/history'; +import history_combo from './plugins/history-combo'; +import hull from './plugins/hull'; +import legend from './plugins/legend'; +import minimap from './plugins/minimap'; import snapline from './plugins/snapline'; -import star from './demo/star'; import toolbar from './plugins/toolbar'; -import tooltip from './demo/tooltip'; +import watermarker from './plugins/watermarker'; import treeGraph from './tree/treeGraph'; -import triangle from './demo/triangle'; import user_defined_canvas from './user-defined-canvas/circular'; +import mapper from './visual/mapper'; import visual from './visual/visual'; -import watermarker from './plugins/watermarker'; -import edgeBundling from './plugins/edgeBundling'; -import label from './item/label'; -export { default as timebar_time } from './plugins/timebar-time'; export { default as timebar_chart } from './plugins/timebar-chart'; +export { default as timebar_time } from './plugins/timebar-time'; export { - label, anchor, animations_node_build_in, arrow, @@ -116,20 +114,21 @@ export { fps_test, graphCore, hexagon, - history_combo, history, + history_combo, hull, image_clip_node, image_node, + label, layouts_circular, layouts_combocombined, layouts_custom, layouts_d3force, layouts_dagre, + layouts_force, layouts_force_3d, - layouts_force_wasm_3d, layouts_force_wasm, - layouts_force, + layouts_force_wasm_3d, layouts_forceatlas2_wasm, layouts_fruchterman_gpu, layouts_fruchterman_wasm, @@ -142,9 +141,9 @@ export { menu, minimap, modelRect, - performance_layout_3d, - performance_layout, performance, + performance_layout, + performance_layout_3d, polyline, processParallelEdges, quadratic, diff --git a/packages/g6/tests/demo/item/edge/arrow.ts b/packages/g6/tests/demo/item/edge/arrow.ts index 67ad00c9f7c..64b491d0654 100644 --- a/packages/g6/tests/demo/item/edge/arrow.ts +++ b/packages/g6/tests/demo/item/edge/arrow.ts @@ -1,6 +1,6 @@ import { ArrowConfig } from '@antv/g6'; +import { Extensions, Graph, extend } from '../../../../src/index'; import { TestCaseContext } from '../../interface'; -import { Graph, Extensions, extend } from '../../../../src/index'; const defaultData = { nodes: [ @@ -92,15 +92,7 @@ export default ( }); document.body.appendChild(removeBtn); - const arrowTypes = [ - 'triangle', - 'circle', - 'rect', - 'diamond', - 'vee', - 'triangle-rect', - 'simple', - ]; + const arrowTypes = ['triangle', 'circle', 'rect', 'diamond', 'vee', 'triangle-rect', 'simple']; let typeIdx = 0; const updateBtn = document.createElement('button'); updateBtn.textContent = '更新箭头类型'; diff --git a/packages/g6/tests/demo/item/edge/cubic-edge.ts b/packages/g6/tests/demo/item/edge/cubic-edge.ts index 61283c62ecb..f7388cdb04e 100644 --- a/packages/g6/tests/demo/item/edge/cubic-edge.ts +++ b/packages/g6/tests/demo/item/edge/cubic-edge.ts @@ -1,4 +1,4 @@ -import { Graph, Extensions, extend } from '../../../../src/index'; +import { Extensions, Graph, extend } from '../../../../src/index'; // @ts-nocheck diff --git a/packages/g6/tests/demo/item/edge/cubic-horizontal-edge.ts b/packages/g6/tests/demo/item/edge/cubic-horizontal-edge.ts index e5e006df283..5346329855d 100644 --- a/packages/g6/tests/demo/item/edge/cubic-horizontal-edge.ts +++ b/packages/g6/tests/demo/item/edge/cubic-horizontal-edge.ts @@ -1,4 +1,4 @@ -import { Graph, Extensions, extend } from '../../../../src/index'; +import { Extensions, Graph, extend } from '../../../../src/index'; // @ts-nocheck diff --git a/packages/g6/tests/demo/item/edge/cubic-vertical-edge.ts b/packages/g6/tests/demo/item/edge/cubic-vertical-edge.ts index e7cd2e6de5e..94804af6710 100644 --- a/packages/g6/tests/demo/item/edge/cubic-vertical-edge.ts +++ b/packages/g6/tests/demo/item/edge/cubic-vertical-edge.ts @@ -1,4 +1,4 @@ -import { Graph, Extensions, extend } from '../../../../src/index'; +import { Extensions, Graph, extend } from '../../../../src/index'; // @ts-nocheck let graph: IGraph; diff --git a/packages/g6/tests/demo/item/edge/loop-edge.ts b/packages/g6/tests/demo/item/edge/loop-edge.ts index a697026fa3b..8848a38836b 100644 --- a/packages/g6/tests/demo/item/edge/loop-edge.ts +++ b/packages/g6/tests/demo/item/edge/loop-edge.ts @@ -1,10 +1,5 @@ import { deepMix } from '@antv/util'; -import { - Graph, - EdgeUserModel, - Extensions, - extend, -} from '../../../../src/index'; +import { EdgeUserModel, Extensions, Graph, extend } from '../../../../src/index'; import { TestCaseContext } from '../../interface'; // @ts-nocheck @@ -12,16 +7,7 @@ import { TestCaseContext } from '../../interface'; let graph: IGraph; let container: HTMLElement; -const loopPosition = [ - 'top', - 'top-right', - 'right', - 'bottom-right', - 'bottom', - 'bottom-left', - 'left', - 'top-left', -]; +const loopPosition = ['top', 'top-right', 'right', 'bottom-right', 'bottom', 'bottom-left', 'left', 'top-left']; const defaultData = { nodes: [ diff --git a/packages/g6/tests/demo/item/edge/polyline-edge.ts b/packages/g6/tests/demo/item/edge/polyline-edge.ts index 1dde37bd1b3..43912026c4f 100644 --- a/packages/g6/tests/demo/item/edge/polyline-edge.ts +++ b/packages/g6/tests/demo/item/edge/polyline-edge.ts @@ -1,7 +1,6 @@ // @ts-nocheck import { Extensions, Graph, IGraph, extend } from '../../../../src/index'; import { TestCaseContext } from '../../interface'; -import { Graph, Extensions, extend } from '../../../../src/index'; let graph: IGraph; let container: HTMLElement; diff --git a/packages/g6/tests/demo/item/node/cube.ts b/packages/g6/tests/demo/item/node/cube.ts index b2f8fb4399d..865c23016b8 100644 --- a/packages/g6/tests/demo/item/node/cube.ts +++ b/packages/g6/tests/demo/item/node/cube.ts @@ -1,5 +1,4 @@ -import { Graph, Extensions, extend } from '../../../../src/index'; -import { data } from '../../../datasets/dataset1'; +import { Extensions, Graph, extend } from '../../../../src/index'; import { TestCaseContext } from '../../interface'; export default (context: TestCaseContext) => { diff --git a/packages/g6/tests/demo/item/node/donut-node.ts b/packages/g6/tests/demo/item/node/donut-node.ts index 136b720b59c..9069a28eb2f 100644 --- a/packages/g6/tests/demo/item/node/donut-node.ts +++ b/packages/g6/tests/demo/item/node/donut-node.ts @@ -1,4 +1,4 @@ -import { Graph, Extensions, extend } from '../../../../src/index'; +import { Extensions, Graph, extend } from '../../../../src/index'; let outerTop = 0; let graph: IGraph; diff --git a/packages/g6/tests/demo/item/node/image-clip.ts b/packages/g6/tests/demo/item/node/image-clip.ts index 0ae21d0e3b7..0336b1ca1e2 100644 --- a/packages/g6/tests/demo/item/node/image-clip.ts +++ b/packages/g6/tests/demo/item/node/image-clip.ts @@ -1,7 +1,7 @@ // import { Circle } from '@antv/g'; import { Graph } from '../../../../src/index'; -import { TestCaseContext } from '../../interface'; import { data } from '../../../datasets/dataset1'; +import { TestCaseContext } from '../../interface'; export default (context: TestCaseContext) => { const { width, height, extendedParams } = context; @@ -29,8 +29,7 @@ export default (context: TestCaseContext) => { ...innerModel.data, keyShape: { src: - extendedParams ?? - 'https://gw.alipayobjects.com/mdn/rms_6ae20b/afts/img/A*N4ZMS7gHsUIAAAAAAAAAAABkARQnAQ', + extendedParams ?? 'https://gw.alipayobjects.com/mdn/rms_6ae20b/afts/img/A*N4ZMS7gHsUIAAAAAAAAAAABkARQnAQ', clipCfg: { type: 'circle', r: 10, diff --git a/packages/g6/tests/demo/item/node/image.ts b/packages/g6/tests/demo/item/node/image.ts index 0fd00e3a79d..533bde68b39 100644 --- a/packages/g6/tests/demo/item/node/image.ts +++ b/packages/g6/tests/demo/item/node/image.ts @@ -1,7 +1,7 @@ // import { Circle } from '@antv/g'; import { Graph } from '../../../../src/index'; -import { TestCaseContext } from '../../interface'; import { data } from '../../../datasets/dataset1'; +import { TestCaseContext } from '../../interface'; export default (context: TestCaseContext) => { const { width, height, extendedParams } = context; @@ -29,8 +29,7 @@ export default (context: TestCaseContext) => { ...innerModel.data, keyShape: { src: - extendedParams ?? - 'https://gw.alipayobjects.com/mdn/rms_6ae20b/afts/img/A*N4ZMS7gHsUIAAAAAAAAAAABkARQnAQ', + extendedParams ?? 'https://gw.alipayobjects.com/mdn/rms_6ae20b/afts/img/A*N4ZMS7gHsUIAAAAAAAAAAABkARQnAQ', }, labelShape: { text: innerModel.id, diff --git a/packages/g6/tests/demo/layouts/combo-combined.ts b/packages/g6/tests/demo/layouts/combo-combined.ts index 2bf765ba9f0..652cd5ee160 100644 --- a/packages/g6/tests/demo/layouts/combo-combined.ts +++ b/packages/g6/tests/demo/layouts/combo-combined.ts @@ -1,5 +1,5 @@ +import { Extensions, Graph, extend } from '../../../src/index'; import { TestCaseContext } from '../interface'; -import { Graph, Extensions, extend } from '../../../src/index'; const data = { nodes: [ diff --git a/packages/g6/tests/demo/layouts/d3force.ts b/packages/g6/tests/demo/layouts/d3force.ts index 266f5aa2818..4c6ee07c258 100644 --- a/packages/g6/tests/demo/layouts/d3force.ts +++ b/packages/g6/tests/demo/layouts/d3force.ts @@ -1,4 +1,4 @@ -import { Graph, Extensions, extend } from '../../../src/index'; +import { Extensions, Graph, extend } from '../../../src/index'; import { data } from '../../datasets/dataset1'; import { TestCaseContext } from '../interface'; diff --git a/packages/g6/tests/demo/layouts/dagre-combo.ts b/packages/g6/tests/demo/layouts/dagre-combo.ts index a237fe8081e..c1cfaf99222 100644 --- a/packages/g6/tests/demo/layouts/dagre-combo.ts +++ b/packages/g6/tests/demo/layouts/dagre-combo.ts @@ -1,4 +1,4 @@ -import { Graph, Extensions, extend } from '../../../src/index'; +import { Extensions, Graph, extend } from '../../../src/index'; import { TestCaseContext } from '../interface'; @@ -179,13 +179,7 @@ export default (context: TestCaseContext) => { ...context, autoFit: 'view', modes: { - default: [ - 'drag-combo', - 'drag-node', - 'drag-canvas', - 'zoom-canvas', - 'collapse-expand-combo', - ], + default: ['drag-combo', 'drag-node', 'drag-canvas', 'zoom-canvas', 'collapse-expand-combo'], }, layout: { type: 'dagre', diff --git a/packages/g6/tests/demo/layouts/dagre-update.ts b/packages/g6/tests/demo/layouts/dagre-update.ts index 5da22e1edb5..717406b73e6 100644 --- a/packages/g6/tests/demo/layouts/dagre-update.ts +++ b/packages/g6/tests/demo/layouts/dagre-update.ts @@ -1,4 +1,4 @@ -import { extend, Graph, Extensions } from '../../../src/index'; +import { Extensions, Graph, extend } from '../../../src/index'; import { TestCaseContext } from '../interface'; export default (context: TestCaseContext) => { @@ -122,8 +122,7 @@ export default (context: TestCaseContext) => { if (typeof window !== 'undefined') window.onresize = () => { if (!graph || graph.destroyed) return; - if (!container || !container.scrollWidth || !container.scrollHeight) - return; + if (!container || !container.scrollWidth || !container.scrollHeight) return; graph.setSize([container.scrollWidth, container.scrollHeight]); }; diff --git a/packages/g6/tests/demo/layouts/dagre.ts b/packages/g6/tests/demo/layouts/dagre.ts index 8c0f5aa5fc2..4646dee109f 100644 --- a/packages/g6/tests/demo/layouts/dagre.ts +++ b/packages/g6/tests/demo/layouts/dagre.ts @@ -1,4 +1,4 @@ -import { Graph, Extensions, extend } from '../../../src/index'; +import { Extensions, Graph, extend } from '../../../src/index'; import { TestCaseContext } from '../interface'; diff --git a/packages/g6/tests/demo/layouts/force-3d.ts b/packages/g6/tests/demo/layouts/force-3d.ts index 1288139e18d..a1c85b1dbfc 100644 --- a/packages/g6/tests/demo/layouts/force-3d.ts +++ b/packages/g6/tests/demo/layouts/force-3d.ts @@ -1,4 +1,4 @@ -import { Graph, Extensions, extend } from '../../../src/index'; +import { Extensions, Graph, extend } from '../../../src/index'; import { data } from '../../datasets/dataset1'; import { TestCaseContext } from '../interface'; diff --git a/packages/g6/tests/demo/layouts/force-wasm-3d.ts b/packages/g6/tests/demo/layouts/force-wasm-3d.ts index 86400d8d909..69b9b17957c 100644 --- a/packages/g6/tests/demo/layouts/force-wasm-3d.ts +++ b/packages/g6/tests/demo/layouts/force-wasm-3d.ts @@ -1,5 +1,5 @@ -import { supportsThreads, initThreads, ForceLayout } from '@antv/layout-wasm'; -import { Graph, Extensions, extend } from '../../../src/index'; +import { ForceLayout, initThreads, supportsThreads } from '@antv/layout-wasm'; +import { Extensions, Graph, extend } from '../../../src/index'; import { loadDataset } from '../../datasets/legacy-format'; import { TestCaseContext } from '../interface'; diff --git a/packages/g6/tests/demo/layouts/force-wasm.ts b/packages/g6/tests/demo/layouts/force-wasm.ts index 5ebf19f5c3e..eeab54d85ff 100644 --- a/packages/g6/tests/demo/layouts/force-wasm.ts +++ b/packages/g6/tests/demo/layouts/force-wasm.ts @@ -1,5 +1,5 @@ -import { supportsThreads, initThreads, ForceLayout } from '@antv/layout-wasm'; -import { Graph, Extensions, extend } from '../../../src/index'; +import { ForceLayout, initThreads, supportsThreads } from '@antv/layout-wasm'; +import { Graph, extend } from '../../../src/index'; import { data } from '../../datasets/dataset1'; import { TestCaseContext } from '../interface'; diff --git a/packages/g6/tests/demo/layouts/forceatlas2-wasm.ts b/packages/g6/tests/demo/layouts/forceatlas2-wasm.ts index f629548baf5..288d30b3d8c 100644 --- a/packages/g6/tests/demo/layouts/forceatlas2-wasm.ts +++ b/packages/g6/tests/demo/layouts/forceatlas2-wasm.ts @@ -1,8 +1,4 @@ -import { - supportsThreads, - initThreads, - ForceAtlas2Layout, -} from '@antv/layout-wasm'; +import { ForceAtlas2Layout, initThreads, supportsThreads } from '@antv/layout-wasm'; import { Graph, extend } from '../../../src/index'; import { data } from '../../datasets/dataset1'; import { TestCaseContext } from '../interface'; diff --git a/packages/g6/tests/demo/layouts/fruchterman-wasm.ts b/packages/g6/tests/demo/layouts/fruchterman-wasm.ts index 65018331904..7dd7c53f697 100644 --- a/packages/g6/tests/demo/layouts/fruchterman-wasm.ts +++ b/packages/g6/tests/demo/layouts/fruchterman-wasm.ts @@ -1,8 +1,4 @@ -import { - supportsThreads, - initThreads, - FruchtermanLayout, -} from '@antv/layout-wasm'; +import { FruchtermanLayout, initThreads, supportsThreads } from '@antv/layout-wasm'; import { Graph, extend } from '../../../src/index'; import { data } from '../../datasets/dataset1'; import { TestCaseContext } from '../interface'; diff --git a/packages/g6/tests/demo/performance/fps.ts b/packages/g6/tests/demo/performance/fps.ts index 9195487158d..cf5b1eb0f1f 100644 --- a/packages/g6/tests/demo/performance/fps.ts +++ b/packages/g6/tests/demo/performance/fps.ts @@ -1,5 +1,5 @@ import Stats from 'stats.js'; -import { Graph, Extensions, extend } from '../../../src/index'; +import { Extensions, Graph, extend } from '../../../src/index'; import { container, width } from '../../datasets/const'; import data from '../../datasets/eva-3d-data.json'; diff --git a/packages/g6/tests/demo/performance/layout-3d.ts b/packages/g6/tests/demo/performance/layout-3d.ts index d13fb5e1af9..4db4031e36f 100644 --- a/packages/g6/tests/demo/performance/layout-3d.ts +++ b/packages/g6/tests/demo/performance/layout-3d.ts @@ -1,5 +1,5 @@ -import { supportsThreads, initThreads, ForceLayout } from '@antv/layout-wasm'; -import { Graph, Extensions, extend } from '../../../src/index'; +import { initThreads, supportsThreads } from '@antv/layout-wasm'; +import { Extensions, Graph, extend } from '../../../src/index'; import { loadDataset } from '../../datasets/legacy-format'; const ExtGraph = extend(Graph, { layouts: { @@ -124,9 +124,7 @@ export default async () => { graph.on('beforelayout', () => { const startTime = performance.now(); timer = setInterval(() => { - $timer1.innerHTML = `@antv/layout-wasm: ${( - performance.now() - startTime - ).toFixed(2)}ms`; + $timer1.innerHTML = `@antv/layout-wasm: ${(performance.now() - startTime).toFixed(2)}ms`; }, 1); }); @@ -190,9 +188,7 @@ export default async () => { graph.on('beforelayout', () => { const startTime = performance.now(); timer = setInterval(() => { - $timer2.innerHTML = `@antv/layout: ${( - performance.now() - startTime - ).toFixed(2)}ms`; + $timer2.innerHTML = `@antv/layout: ${(performance.now() - startTime).toFixed(2)}ms`; }, 1); }); diff --git a/packages/g6/tests/demo/performance/layout.ts b/packages/g6/tests/demo/performance/layout.ts index 7057fb383fc..9c4a93144b4 100644 --- a/packages/g6/tests/demo/performance/layout.ts +++ b/packages/g6/tests/demo/performance/layout.ts @@ -1,5 +1,5 @@ -import { supportsThreads, initThreads, ForceLayout } from '@antv/layout-wasm'; import { labelPropagation } from '@antv/algorithm'; +import { ForceLayout, initThreads, supportsThreads } from '@antv/layout-wasm'; import G6 from '../../../src/index'; import { loadDataset } from '../../datasets/legacy-format'; @@ -150,9 +150,7 @@ export default async () => { graph.on('beforelayout', () => { const startTime = performance.now(); timer = setInterval(() => { - $timer1.innerHTML = `Time: ${(performance.now() - startTime).toFixed( - 2, - )}ms`; + $timer1.innerHTML = `Time: ${(performance.now() - startTime).toFixed(2)}ms`; }, 1); }); @@ -185,9 +183,7 @@ export default async () => { graph.on('beforelayout', () => { const startTime = performance.now(); timer = setInterval(() => { - $timer2.innerHTML = `Time: ${(performance.now() - startTime).toFixed( - 2, - )}ms`; + $timer2.innerHTML = `Time: ${(performance.now() - startTime).toFixed(2)}ms`; }, 1); }); diff --git a/packages/g6/tests/demo/performance/performance.ts b/packages/g6/tests/demo/performance/performance.ts index 85127e790c4..cf4c657828c 100644 --- a/packages/g6/tests/demo/performance/performance.ts +++ b/packages/g6/tests/demo/performance/performance.ts @@ -1,10 +1,5 @@ -import { - ForceLayout, - FruchtermanLayout, - initThreads, - supportsThreads, -} from '@antv/layout-wasm'; -import { Graph, Extensions, extend } from '../../../src/index'; +import { initThreads, supportsThreads } from '@antv/layout-wasm'; +import { Extensions, Graph, extend } from '../../../src/index'; import { IBadgePosition } from '../../../src/types/item'; import { container, width } from '../../datasets/const'; const data = { @@ -1697,23 +1692,8 @@ const clusters = [ 'Mme.Magloire', 'Mlle.Baptistine', ], - [ - 'Tholomyes', - 'Listolier', - 'Fameuil', - 'Blacheville', - 'Favourite', - 'Dahlia', - 'Zephine', - ], - [ - 'Bamatabois', - 'Judge', - 'Champmathieu', - 'Brevet', - 'Chenildieu', - 'Cochepaille', - ], + ['Tholomyes', 'Listolier', 'Fameuil', 'Blacheville', 'Favourite', 'Dahlia', 'Zephine'], + ['Bamatabois', 'Judge', 'Champmathieu', 'Brevet', 'Chenildieu', 'Cochepaille'], [ 'Mabeuf', 'Enjolras', @@ -1968,14 +1948,7 @@ const createGraph = async () => { interval: 0.02, }, modes: { - default: [ - 'zoom-canvas', - 'drag-canvas', - 'drag-node', - 'brush-select', - 'click-select', - 'hover-activate', - ], + default: ['zoom-canvas', 'drag-canvas', 'drag-node', 'brush-select', 'click-select', 'hover-activate'], }, theme: { type: 'spec', diff --git a/packages/g6/tests/demo/plugins/edgeBundling.ts b/packages/g6/tests/demo/plugins/edgeBundling.ts index 623492989e7..9b6cd5e7ac5 100644 --- a/packages/g6/tests/demo/plugins/edgeBundling.ts +++ b/packages/g6/tests/demo/plugins/edgeBundling.ts @@ -1,4 +1,4 @@ -import { Graph, Extensions, extend } from '../../../src/index'; +import { Extensions, Graph, extend } from '../../../src/index'; import { TestCaseContext } from '../interface'; export default (context: TestCaseContext, options = {}) => { @@ -505,8 +505,7 @@ export default (context: TestCaseContext, options = {}) => { }, }); - const { plugin: edgeBundling } = - graph.pluginController.pluginMap.get('edgeBundling'); + const { plugin: edgeBundling } = graph.pluginController.pluginMap.get('edgeBundling'); setTimeout(() => { const nodes = graph.getAllNodesData(); diff --git a/packages/g6/tests/demo/plugins/edgeFilterLens.ts b/packages/g6/tests/demo/plugins/edgeFilterLens.ts index d862cd20218..bb97efb34d7 100644 --- a/packages/g6/tests/demo/plugins/edgeFilterLens.ts +++ b/packages/g6/tests/demo/plugins/edgeFilterLens.ts @@ -1,7 +1,7 @@ import { clone } from '@antv/util'; -import { Graph, Extensions, extend } from '../../../src/index'; -import { TestCaseContext } from '../interface'; +import { Extensions, Graph, extend } from '../../../src/index'; import data from '../../datasets/force-data.json'; +import { TestCaseContext } from '../interface'; export default (context: TestCaseContext, options = {}) => { const trigger = 'mousemove'; @@ -25,16 +25,14 @@ export default (context: TestCaseContext, options = {}) => { // tip const tip = document.createElement('span'); - tip.innerHTML = - '点击画布任意位置开始探索。过滤镜中显示两端节点均在过滤镜中的边。'; + tip.innerHTML = '点击画布任意位置开始探索。过滤镜中显示两端节点均在过滤镜中的边。'; buttonContainer.appendChild(tip); buttonContainer.appendChild(document.createElement('br')); // tip english const tipEn = document.createElement('span'); - tipEn.innerHTML = - 'Click the canvas to begin. Show the edge whose both end nodes are inside the lens.'; + tipEn.innerHTML = 'Click the canvas to begin. Show the edge whose both end nodes are inside the lens.'; buttonContainer.appendChild(tipEn); buttonContainer.appendChild(document.createElement('br')); diff --git a/packages/g6/tests/demo/plugins/fisheye.ts b/packages/g6/tests/demo/plugins/fisheye.ts index 6594d3ecca4..e1e4ce0733a 100644 --- a/packages/g6/tests/demo/plugins/fisheye.ts +++ b/packages/g6/tests/demo/plugins/fisheye.ts @@ -1,4 +1,4 @@ -import { Graph, Extensions, extend } from '../../../src/index'; +import { Extensions, Graph, extend } from '../../../src/index'; export default async () => { let fisheye = { @@ -10,17 +10,7 @@ export default async () => { showLabel: true, trigger: 'mousemove', }; - const colors = [ - '#8FE9FF', - '#87EAEF', - '#FFC9E3', - '#A7C2FF', - '#FFA1E3', - '#FFE269', - '#BFCFEE', - '#FFA0C5', - '#D5FF86', - ]; + const colors = ['#8FE9FF', '#87EAEF', '#FFC9E3', '#A7C2FF', '#FFA1E3', '#FFE269', '#BFCFEE', '#FFA0C5', '#D5FF86']; // ================= The DOMs for configurations =============== // const graphDiv = document.getElementById('container'); @@ -195,9 +185,7 @@ export default async () => { }); }; - fetch( - 'https://gw.alipayobjects.com/os/bmw-prod/afe8b2a6-f691-4070-aa73-46fc07fd1171.json', - ) + fetch('https://gw.alipayobjects.com/os/bmw-prod/afe8b2a6-f691-4070-aa73-46fc07fd1171.json') .then((res) => res.json()) .then((data) => { data.nodes.forEach((node) => { diff --git a/packages/g6/tests/demo/plugins/history-combo.ts b/packages/g6/tests/demo/plugins/history-combo.ts index d089b1fa632..eef0d45a690 100644 --- a/packages/g6/tests/demo/plugins/history-combo.ts +++ b/packages/g6/tests/demo/plugins/history-combo.ts @@ -1,4 +1,4 @@ -import { Graph, Extensions, extend } from '../../../src/index'; +import { Extensions, Graph, extend } from '../../../src/index'; const createOperationContainer = (container: HTMLElement) => { const operationContainer = document.createElement('div'); diff --git a/packages/g6/tests/demo/plugins/hull.ts b/packages/g6/tests/demo/plugins/hull.ts index af3e89d994e..1668d8dac93 100644 --- a/packages/g6/tests/demo/plugins/hull.ts +++ b/packages/g6/tests/demo/plugins/hull.ts @@ -1,4 +1,4 @@ -import G6, { ID, Extensions } from '../../../src/index'; +import G6, { Extensions, ID } from '../../../src/index'; import { ShapeStyle } from '../../../src/types/item'; export default ( context, @@ -9,12 +9,7 @@ export default ( nonMembers?: ID[]; } = {}, ) => { - const { - hullType = 'smooth-convex', - labelPosition = 'left', - style, - nonMembers = [], - } = options; + const { hullType = 'smooth-convex', labelPosition = 'left', style, nonMembers = [] } = options; const hullPlugin = new Extensions.Hull({ key: 'hull-plugin1', style, diff --git a/packages/g6/tests/demo/plugins/legend.ts b/packages/g6/tests/demo/plugins/legend.ts index 87ce0b34908..7ede73a580a 100644 --- a/packages/g6/tests/demo/plugins/legend.ts +++ b/packages/g6/tests/demo/plugins/legend.ts @@ -1,4 +1,4 @@ -import { Graph, Extensions, extend } from '../../../src/index'; +import { Extensions, Graph, extend } from '../../../src/index'; import { TestCaseContext } from '../interface'; export default (context: TestCaseContext) => { diff --git a/packages/g6/tests/demo/plugins/map.ts b/packages/g6/tests/demo/plugins/map.ts index 1f319192b92..deac3021ac6 100644 --- a/packages/g6/tests/demo/plugins/map.ts +++ b/packages/g6/tests/demo/plugins/map.ts @@ -1,5 +1,5 @@ import { MapView } from '@antv/g6-plugin-map-view'; -import { Graph, Extensions, extend } from '../../../src/index'; +import { Extensions, Graph, extend } from '../../../src/index'; import { TestCaseContext } from '../interface'; export default (context: TestCaseContext) => { diff --git a/packages/g6/tests/demo/plugins/minimap.ts b/packages/g6/tests/demo/plugins/minimap.ts index 48a6b9134b3..b06925f4d76 100644 --- a/packages/g6/tests/demo/plugins/minimap.ts +++ b/packages/g6/tests/demo/plugins/minimap.ts @@ -1,4 +1,4 @@ -import { Graph, Extensions, extend } from '../../../src/index'; +import { Extensions, Graph, extend } from '../../../src/index'; import { TestCaseContext } from '../interface'; export default (context: TestCaseContext) => { diff --git a/packages/g6/tests/demo/plugins/snapline.ts b/packages/g6/tests/demo/plugins/snapline.ts index d9a0588f6ff..579b4e52e59 100644 --- a/packages/g6/tests/demo/plugins/snapline.ts +++ b/packages/g6/tests/demo/plugins/snapline.ts @@ -1,11 +1,5 @@ import { AABB } from '@antv/g'; -import { - Graph as BaseGraph, - IGraph, - GraphData, - Extensions, - extend, -} from '../../../src/index'; +import { Graph as BaseGraph, Extensions, GraphData, IGraph, extend } from '../../../src/index'; let graph: IGraph; diff --git a/packages/g6/tests/demo/plugins/timebar-chart.ts b/packages/g6/tests/demo/plugins/timebar-chart.ts index cfd81e5ea8e..92ef15d98e0 100644 --- a/packages/g6/tests/demo/plugins/timebar-chart.ts +++ b/packages/g6/tests/demo/plugins/timebar-chart.ts @@ -1,4 +1,4 @@ -import { Graph, extend, Extensions } from '../../../src/index'; +import { Extensions, Graph, extend } from '../../../src/index'; import type { TestCaseContext } from '../interface'; const ExtGraph = extend(Graph, { @@ -10,13 +10,11 @@ const ExtGraph = extend(Graph, { export default (context: TestCaseContext) => { const startTime = new Date('2023-08-01').getTime(); const diff = 3600 * 24 * 1000; - const timebarData = [10, 12, 3, 4, 15, 10, 5, 0, 3, 1].map( - (value, index) => ({ - time: new Date(startTime + index * diff), - value, - label: new Date(startTime + index * diff).toLocaleString(), - }), - ); + const timebarData = [10, 12, 3, 4, 15, 10, 5, 0, 3, 1].map((value, index) => ({ + time: new Date(startTime + index * diff), + value, + label: new Date(startTime + index * diff).toLocaleString(), + })); const graphData = { nodes: new Array(49).fill(0).map((_, index) => ({ id: `node-${index}`, diff --git a/packages/g6/tests/demo/plugins/timebar-time.ts b/packages/g6/tests/demo/plugins/timebar-time.ts index 3c80a440a7e..cc567211c73 100644 --- a/packages/g6/tests/demo/plugins/timebar-time.ts +++ b/packages/g6/tests/demo/plugins/timebar-time.ts @@ -1,4 +1,4 @@ -import { Graph, extend, Extensions } from '../../../src/index'; +import { Extensions, Graph, extend } from '../../../src/index'; import type { TestCaseContext } from '../interface'; const ExtGraph = extend(Graph, { diff --git a/packages/g6/tests/demo/plugins/toolbar.ts b/packages/g6/tests/demo/plugins/toolbar.ts index 9aec9ba9250..8f03d7bc93a 100644 --- a/packages/g6/tests/demo/plugins/toolbar.ts +++ b/packages/g6/tests/demo/plugins/toolbar.ts @@ -1,4 +1,4 @@ -import { Graph, Extensions, extend } from '../../../src/index'; +import { Extensions, Graph, extend } from '../../../src/index'; import { TestCaseContext } from '../interface'; export default (context: TestCaseContext) => { @@ -42,7 +42,7 @@ export default (context: TestCaseContext) => { toolbar: Extensions.Toolbar, }, }); - const graph = new Graph({ + const graph = new ExtGraph({ ...context, type: 'graph', layout: { diff --git a/packages/g6/tests/demo/plugins/watermarker.ts b/packages/g6/tests/demo/plugins/watermarker.ts index b7a2e1a190e..d8053e95f23 100644 --- a/packages/g6/tests/demo/plugins/watermarker.ts +++ b/packages/g6/tests/demo/plugins/watermarker.ts @@ -1,6 +1,5 @@ -import { Graph, Extensions, extend } from '../../../src/index'; +import { Extensions, Graph, extend } from '../../../src/index'; import { TestCaseContext } from '../interface'; -import { createNodeGCanvas } from '../../integration/utils/createNodeGCanvas'; export default (context: TestCaseContext, options = {}) => { const { watermarkerCanvas, ...pluginConfigs } = options; @@ -70,19 +69,12 @@ export default (context: TestCaseContext, options = {}) => { begin: [10, 10], separation: [10, 10], text: { - texts: [ - 'hello', - 'antv', - 'dasdfasdfaasdfasdfas', - 'kjadkja', - 'iy32iuhehfka', - ], + texts: ['hello', 'antv', 'dasdfasdfaasdfasdfas', 'kjadkja', 'iy32iuhehfka'], fill: '#f00', rotate: 30, }, 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: 40, diff --git a/packages/g6/tests/demo/tree/treeGraph.ts b/packages/g6/tests/demo/tree/treeGraph.ts index 56f3853c168..62540cc2155 100644 --- a/packages/g6/tests/demo/tree/treeGraph.ts +++ b/packages/g6/tests/demo/tree/treeGraph.ts @@ -1,6 +1,6 @@ import G6 from '../../../src/index'; +import { graphDataCfg, treeDataCfg } from '../../datasets/dataCfg'; import { TestCaseContext } from '../interface'; -import { treeDataCfg, graphDataCfg } from '../../datasets/dataCfg'; export default ( context: TestCaseContext, @@ -10,11 +10,7 @@ export default ( defaultCollapse?: boolean; } = {}, ) => { - const { - dataType = 'graph', - layoutType = 'compactBox', - defaultCollapse = false, - } = options; + const { dataType = 'graph', layoutType = 'compactBox', defaultCollapse = false } = options; const datasets = { tree: JSON.parse(JSON.stringify(treeDataCfg)), @@ -149,12 +145,7 @@ export default ( layoutBtn.id = 'treegraph-changelayout'; layoutBtn.textContent = '切换树/图布局'; layoutBtn.addEventListener('click', (e) => { - if ( - ['compactBox', 'indented', 'mindmap', 'dendrogram'].includes( - currentLayout, - ) - ) - currentLayout = 'grid'; + if (['compactBox', 'indented', 'mindmap', 'dendrogram'].includes(currentLayout)) currentLayout = 'grid'; else currentLayout = 'compactBox'; graph.layout({ type: currentLayout }); }); @@ -170,9 +161,7 @@ export default ( graph.removeData('node', ['dynamicNode']); } else { graph.addData('node', [{ id: 'dynamicNode', data: { x: 10, y: 10 } }]); - graph.addData('edge', [ - { id: 'newedge', source: 'node1', target: 'dynamicNode', data: {} }, - ]); + graph.addData('edge', [{ id: 'newedge', source: 'node1', target: 'dynamicNode', data: {} }]); } graph.layout(); }); diff --git a/packages/g6/tests/demo/visual/visual.ts b/packages/g6/tests/demo/visual/visual.ts index 68b26d9e47c..6f5b37eea1a 100644 --- a/packages/g6/tests/demo/visual/visual.ts +++ b/packages/g6/tests/demo/visual/visual.ts @@ -34,14 +34,7 @@ const createGraph = () => { type: 'grid', }, modes: { - default: [ - 'zoom-canvas', - 'drag-canvas', - 'drag-node', - 'brush-select', - 'click-select', - 'hover-activate', - ], + default: ['zoom-canvas', 'drag-canvas', 'drag-node', 'brush-select', 'click-select', 'hover-activate'], }, theme: { type: 'spec', diff --git a/packages/g6/tests/index.html b/packages/g6/tests/index.html index 83887d70d3b..b2dfc10f111 100644 --- a/packages/g6/tests/index.html +++ b/packages/g6/tests/index.html @@ -1,4 +1,4 @@ - + diff --git a/packages/g6/tests/integration/anchor.spec.ts b/packages/g6/tests/integration/anchor.spec.ts index afe4625dccd..069a1ab86dc 100644 --- a/packages/g6/tests/integration/anchor.spec.ts +++ b/packages/g6/tests/integration/anchor.spec.ts @@ -6,14 +6,10 @@ const dir = `${__dirname}/snapshots/anchor`; describe('Anchor points and shapes', () => { it('edges link to node center with empty anchorPoints', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = anchor( { @@ -41,14 +37,10 @@ describe('Anchor points and shapes', () => { }); it('node with 4 anchorPoints and edge find the nearest one', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = anchor( { @@ -84,10 +76,7 @@ describe('Anchor points and shapes', () => { }, }); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'anchor-4-points-update-position', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'anchor-4-points-update-position'); graph.destroy(); done(); @@ -95,14 +84,10 @@ describe('Anchor points and shapes', () => { }); it('node with 4 anchorPoints and anchorShapes and edge find the nearest one', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = anchor( { diff --git a/packages/g6/tests/integration/animations-node-build-in.spec.ts b/packages/g6/tests/integration/animations-node-build-in.spec.ts index cf5fc92367a..aa41991ba8a 100644 --- a/packages/g6/tests/integration/animations-node-build-in.spec.ts +++ b/packages/g6/tests/integration/animations-node-build-in.spec.ts @@ -6,14 +6,10 @@ const dir = `${__dirname}/snapshots/animations`; describe('Animation node buildIn', () => { it('should be rendered correctly', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = nodeBuildIn({ backgroundCanvas, @@ -39,10 +35,7 @@ describe('Animation node buildIn', () => { animation.pause(); }); }); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'animations-node-build-in-ready', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'animations-node-build-in-ready'); /** * Time: 200 @@ -54,10 +47,7 @@ describe('Animation node buildIn', () => { animation.pause(); }); }); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'animations-node-build-in-running', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'animations-node-build-in-running'); /** * Resume all animations. @@ -75,15 +65,10 @@ describe('Animation node buildIn', () => { await Promise.all( nodes.map(async ({ id }) => { const node = graph['getItemById'](id)!; - await Promise.all( - node.animations.map((animation) => animation.finished), - ); + await Promise.all(node.animations.map((animation) => animation.finished)); }), ); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'animations-node-build-in-finished', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'animations-node-build-in-finished'); graph.destroy(); done(); diff --git a/packages/g6/tests/integration/api-update-mapper.spec.ts b/packages/g6/tests/integration/api-update-mapper.spec.ts index b2ef9db5b36..1b1c2acf5de 100644 --- a/packages/g6/tests/integration/api-update-mapper.spec.ts +++ b/packages/g6/tests/integration/api-update-mapper.spec.ts @@ -6,14 +6,10 @@ const dir = `${__dirname}/snapshots/api`; describe('updateMapper API', () => { it('node and edge mapper update', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = mapper({ backgroundCanvas, @@ -29,41 +25,21 @@ describe('updateMapper API', () => { graph.on('afterlayout', async () => { await expect(canvas).toMatchSVGSnapshot(dir, 'api-update-mapper-init'); - const $updateNodeJson = document.getElementById( - 'change-node-json-mapper', - ); + const $updateNodeJson = document.getElementById('change-node-json-mapper'); $updateNodeJson?.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'api-update-mapper-node-json', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'api-update-mapper-node-json'); - const $updateNodeFunc = document.getElementById( - 'change-node-func-mapper', - ); + const $updateNodeFunc = document.getElementById('change-node-func-mapper'); $updateNodeFunc?.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'api-update-mapper-node-func', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'api-update-mapper-node-func'); - const $updateEdgeJson = document.getElementById( - 'change-edge-json-mapper', - ); + const $updateEdgeJson = document.getElementById('change-edge-json-mapper'); $updateEdgeJson?.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'api-update-mapper-edge-json', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'api-update-mapper-edge-json'); - const $updateEdgeFunc = document.getElementById( - 'change-edge-func-mapper', - ); + const $updateEdgeFunc = document.getElementById('change-edge-func-mapper'); $updateEdgeFunc?.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'api-update-mapper-edge-func', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'api-update-mapper-edge-func'); graph.destroy(); done(); diff --git a/packages/g6/tests/integration/behaviors-activate-relations.spec.ts b/packages/g6/tests/integration/behaviors-activate-relations.spec.ts index 1b369137026..fa95347b8d4 100644 --- a/packages/g6/tests/integration/behaviors-activate-relations.spec.ts +++ b/packages/g6/tests/integration/behaviors-activate-relations.spec.ts @@ -6,14 +6,10 @@ const dir = `${__dirname}/snapshots/behaviors`; describe('Activate relations behavior', () => { it('should be rendered correctly', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = activateRelations({ backgroundCanvas, @@ -27,27 +23,18 @@ describe('Activate relations behavior', () => { }); graph.on('afterlayout', async () => { - await expect([canvas, labelCanvas]).toMatchSVGSnapshot( - dir, - 'behaviors-activate-relations', - ); + await expect([canvas, labelCanvas]).toMatchSVGSnapshot(dir, 'behaviors-activate-relations'); // @ts-ignore // mouseEvent.target = canvas.getContextService().getDomElement(); graph.emit('node:click', { itemId: 'node1', itemType: 'node' }); - await expect([canvas, labelCanvas]).toMatchSVGSnapshot( - dir, - 'behaviors-activate-relations-activate-node1', - ); + await expect([canvas, labelCanvas]).toMatchSVGSnapshot(dir, 'behaviors-activate-relations-activate-node1'); /** * Click document to clear active state. */ graph.emit('canvas:click', {}); - await expect([canvas, labelCanvas]).toMatchSVGSnapshot( - dir, - 'behaviors-activate-relations-deactivate-node1', - ); + await expect([canvas, labelCanvas]).toMatchSVGSnapshot(dir, 'behaviors-activate-relations-deactivate-node1'); graph.destroy(); done(); diff --git a/packages/g6/tests/integration/behaviors-collapse-expand-tree.spec.ts b/packages/g6/tests/integration/behaviors-collapse-expand-tree.spec.ts index 3565d8b7e11..7f2501d8cc1 100644 --- a/packages/g6/tests/integration/behaviors-collapse-expand-tree.spec.ts +++ b/packages/g6/tests/integration/behaviors-collapse-expand-tree.spec.ts @@ -1,19 +1,15 @@ -import './utils/useSnapshotMatchers'; import collapseExpandTree from '../demo/behaviors/collapse-expand-tree'; import { createContext } from './utils'; +import './utils/useSnapshotMatchers'; const dir = `${__dirname}/snapshots/behaviors`; describe('Collapse or expand a branch', () => { it('should be rendered correctly', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = collapseExpandTree({ backgroundCanvas, @@ -27,37 +23,22 @@ describe('Collapse or expand a branch', () => { }); graph.on('afterrender', async (e) => { - await expect([canvas, labelCanvas]).toMatchSVGSnapshot( - dir, - 'behaviors-collapse-expand', - ); + await expect([canvas, labelCanvas]).toMatchSVGSnapshot(dir, 'behaviors-collapse-expand'); // collapse child branch graph.emit('node:click', { itemId: 'cnode1', itemType: 'node' }); - await expect([canvas, labelCanvas]).toMatchSVGSnapshot( - dir, - 'behaviors-collapse-expand-collapse-cnode1', - ); + await expect([canvas, labelCanvas]).toMatchSVGSnapshot(dir, 'behaviors-collapse-expand-collapse-cnode1'); // collapse parent branch graph.emit('node:click', { itemId: 'node1', itemType: 'node' }); - await expect([canvas, labelCanvas]).toMatchSVGSnapshot( - dir, - 'behaviors-collapse-expand-collapse-node1', - ); + await expect([canvas, labelCanvas]).toMatchSVGSnapshot(dir, 'behaviors-collapse-expand-collapse-node1'); // expand parent branch graph.emit('node:click', { itemId: 'node1', itemType: 'node' }); - await expect([canvas, labelCanvas]).toMatchSVGSnapshot( - dir, - 'behaviors-collapse-expand-expand-node1', - ); + await expect([canvas, labelCanvas]).toMatchSVGSnapshot(dir, 'behaviors-collapse-expand-expand-node1'); // expand child branch graph.emit('node:click', { itemId: 'cnode1', itemType: 'node' }); - await expect([canvas, labelCanvas]).toMatchSVGSnapshot( - dir, - 'behaviors-collapse-expand-expand-cnode1', - ); + await expect([canvas, labelCanvas]).toMatchSVGSnapshot(dir, 'behaviors-collapse-expand-expand-cnode1'); graph.destroy(); done(); }); diff --git a/packages/g6/tests/integration/behaviors-create-edge.spec.ts b/packages/g6/tests/integration/behaviors-create-edge.spec.ts index 65ce02651bd..7d14f184961 100644 --- a/packages/g6/tests/integration/behaviors-create-edge.spec.ts +++ b/packages/g6/tests/integration/behaviors-create-edge.spec.ts @@ -6,14 +6,10 @@ const dir = `${__dirname}/snapshots/behaviors`; describe('Create edge behavior', () => { it('trigger click should be rendered correctly', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = createEdge( { @@ -41,20 +37,14 @@ describe('Create edge behavior', () => { canvas: { x: 100, y: 100 }, }); graph.emit('pointermove', { canvas: { x: 100, y: 100 } }); - await expect([canvas, labelCanvas]).toMatchSVGSnapshot( - dir, - 'behaviors-create-edge-click-begin', - ); + await expect([canvas, labelCanvas]).toMatchSVGSnapshot(dir, 'behaviors-create-edge-click-begin'); graph.emit('node:click', { itemId: 'node2', itemType: 'node', canvas: { x: 100, y: 100 }, }); - await expect([canvas, labelCanvas]).toMatchSVGSnapshot( - dir, - 'behaviors-create-edge-click-finish', - ); + await expect([canvas, labelCanvas]).toMatchSVGSnapshot(dir, 'behaviors-create-edge-click-finish'); graph.emit('node:click', { itemId: 'node5', @@ -66,10 +56,7 @@ describe('Create edge behavior', () => { itemType: 'node', canvas: { x: 100, y: 100 }, }); - await expect([canvas, labelCanvas]).toMatchSVGSnapshot( - dir, - 'behaviors-create-edge-click-loop', - ); + await expect([canvas, labelCanvas]).toMatchSVGSnapshot(dir, 'behaviors-create-edge-click-loop'); graph.destroy(); done(); @@ -77,14 +64,10 @@ describe('Create edge behavior', () => { }); it('trigger drag should be rendered correctly', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = createEdge( { @@ -110,10 +93,7 @@ describe('Create edge behavior', () => { canvas: { x: 100, y: 100 }, }); graph.emit('drag', { canvas: { x: 100, y: 100 } }); - await expect([canvas, labelCanvas]).toMatchSVGSnapshot( - dir, - 'behaviors-create-edge-drag-begin', - ); + await expect([canvas, labelCanvas]).toMatchSVGSnapshot(dir, 'behaviors-create-edge-drag-begin'); const nodeModel = graph.getNodeData('node2'); graph.emit('drop', { @@ -121,10 +101,7 @@ describe('Create edge behavior', () => { itemType: 'node', canvas: { x: nodeModel?.data.x, y: nodeModel?.data.y }, }); - await expect([canvas, labelCanvas]).toMatchSVGSnapshot( - dir, - 'behaviors-create-edge-drag-finish', - ); + await expect([canvas, labelCanvas]).toMatchSVGSnapshot(dir, 'behaviors-create-edge-drag-finish'); graph.emit('node:dragstart', { itemId: 'node5', @@ -138,10 +115,7 @@ describe('Create edge behavior', () => { itemType: 'node', canvas: { x: node5Model?.data.x, y: node5Model?.data.y }, }); - await expect([canvas, labelCanvas]).toMatchSVGSnapshot( - dir, - 'behaviors-create-edge-drag-loop', - ); + await expect([canvas, labelCanvas]).toMatchSVGSnapshot(dir, 'behaviors-create-edge-drag-loop'); graph.destroy(); done(); diff --git a/packages/g6/tests/integration/behaviors-scroll-canvas.spec.ts b/packages/g6/tests/integration/behaviors-scroll-canvas.spec.ts index 6e873f98b21..fe2be64bc9f 100644 --- a/packages/g6/tests/integration/behaviors-scroll-canvas.spec.ts +++ b/packages/g6/tests/integration/behaviors-scroll-canvas.spec.ts @@ -6,14 +6,10 @@ const dir = `${__dirname}/snapshots/behaviors`; describe('Scroll canvas behavior', () => { it('should be rendered correctly', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = scrollCanvas({ backgroundCanvas, @@ -34,20 +30,14 @@ describe('Scroll canvas behavior', () => { deltaY: 50, }); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'behaviors-scroll-canvas-wheel', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'behaviors-scroll-canvas-wheel'); graph.emit('wheel', { client: { x: 50, y: 50 }, ctrlKey: true, }); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'behaviors-scroll-canvas-zoom', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'behaviors-scroll-canvas-zoom'); graph.destroy(); done(); diff --git a/packages/g6/tests/integration/behaviors-shortcuts-call.spec.ts b/packages/g6/tests/integration/behaviors-shortcuts-call.spec.ts index 456a35ca566..3e0a2b99eb9 100644 --- a/packages/g6/tests/integration/behaviors-shortcuts-call.spec.ts +++ b/packages/g6/tests/integration/behaviors-shortcuts-call.spec.ts @@ -6,14 +6,10 @@ const dir = `${__dirname}/snapshots/behaviors`; describe('Shortcuts-call behavior', () => { it('should be rendered correctly with default options', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = ShortcutsCall({ backgroundCanvas, @@ -25,10 +21,7 @@ describe('Shortcuts-call behavior', () => { }); graph.on('afterlayout', async () => { - await expect([canvas, labelCanvas]).toMatchSVGSnapshot( - dir, - 'behaviors-shortcuts-call', - ); + await expect([canvas, labelCanvas]).toMatchSVGSnapshot(dir, 'behaviors-shortcuts-call'); // default behavior ctrl + 1 to fitView graph.emit('keydown', { @@ -37,24 +30,17 @@ describe('Shortcuts-call behavior', () => { graph.emit('keydown', { key: '1', }); - await expect([canvas, labelCanvas]).toMatchSVGSnapshot( - dir, - 'behaviors-shortcuts-call-with-fitView', - ); + await expect([canvas, labelCanvas]).toMatchSVGSnapshot(dir, 'behaviors-shortcuts-call-with-fitView'); graph.destroy(); done(); }); }); it('should be rendered correctly with custom options', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = ShortcutsCall( { @@ -81,10 +67,7 @@ describe('Shortcuts-call behavior', () => { graph.emit('keydown', { key: 'm', }); - await expect([canvas, labelCanvas]).toMatchSVGSnapshot( - dir, - 'behaviors-shortcuts-call-with-zoom', - ); + await expect([canvas, labelCanvas]).toMatchSVGSnapshot(dir, 'behaviors-shortcuts-call-with-zoom'); graph.destroy(); done(); }); diff --git a/packages/g6/tests/integration/combo-render.spec.ts b/packages/g6/tests/integration/combo-render.spec.ts index 29105f87989..995120afa08 100644 --- a/packages/g6/tests/integration/combo-render.spec.ts +++ b/packages/g6/tests/integration/combo-render.spec.ts @@ -1,19 +1,15 @@ import comboBasic from '../demo/combo/combo-basic'; -import './utils/useSnapshotMatchers'; import { createContext } from './utils'; +import './utils/useSnapshotMatchers'; const dir = `${__dirname}/snapshots/items/combo`; describe('combo circle', () => { it('circle combo should be rendered correctly', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = comboBasic( { @@ -50,14 +46,10 @@ describe('combo circle', () => { }); it('rect combo should be rendered correctly with Canvas2D', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = comboBasic( { diff --git a/packages/g6/tests/integration/data-process-parallel-edges.spec.ts b/packages/g6/tests/integration/data-process-parallel-edges.spec.ts index bcd6f7a444a..1274e66f42a 100644 --- a/packages/g6/tests/integration/data-process-parallel-edges.spec.ts +++ b/packages/g6/tests/integration/data-process-parallel-edges.spec.ts @@ -1,5 +1,5 @@ -import processParallelEdges from '../demo/data/process-parallel-edges'; import { EdgeUserModel } from '../../src'; +import processParallelEdges from '../demo/data/process-parallel-edges'; import { createContext } from './utils'; import './utils/useSnapshotMatchers'; @@ -7,14 +7,10 @@ const dir = `${__dirname}/snapshots/data-parallel`; describe('Process parallel edges', () => { it('should be rendered correctly with Canvas2D', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = processParallelEdges({ backgroundCanvas, @@ -28,10 +24,7 @@ describe('Process parallel edges', () => { }); graph.on('afterlayout', async () => { - await expect(canvas).toMatchSVGSnapshot( - dir, - 'data-parallel-edges-quadratic', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'data-parallel-edges-quadratic'); const loopEdges: EdgeUserModel[] = []; for (let i = 0; i < 10; i++) { @@ -50,36 +43,21 @@ describe('Process parallel edges', () => { // ====== add/remove edge ====== const $changeData = document.getElementById('parallelEdges-removeEdge')!; $changeData.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'data-parallel-edges-add-edge', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'data-parallel-edges-add-edge'); $changeData.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'data-parallel-edges-remove-edge', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'data-parallel-edges-remove-edge'); // ====== update edge's source ====== const $updateData = document.getElementById('parallelEdges-updateData')!; $updateData.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'data-parallel-edges-update-edge-1', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'data-parallel-edges-update-edge-1'); $updateData.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'data-parallel-edges-update-edge-2', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'data-parallel-edges-update-edge-2'); $updateData.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'data-parallel-edges-update-edge-3', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'data-parallel-edges-update-edge-3'); graph.destroy(); done(); diff --git a/packages/g6/tests/integration/data-validate.spec.ts b/packages/g6/tests/integration/data-validate.spec.ts index 8ad8d07f863..cdc4a673246 100644 --- a/packages/g6/tests/integration/data-validate.spec.ts +++ b/packages/g6/tests/integration/data-validate.spec.ts @@ -1,19 +1,15 @@ +import dataValidate from '../demo/data/data-validate'; import { createContext } from './utils'; import './utils/useSnapshotMatchers'; -import dataValidate from '../demo/data/data-validate'; const dir = `${__dirname}/snapshots/data`; describe('TreeGraph', () => { it('data with error DUPLICATE_NODE_ID', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = dataValidate( { @@ -32,10 +28,7 @@ describe('TreeGraph', () => { ); graph.on('afterlayout', async () => { - await expect(canvas).toMatchSVGSnapshot( - dir, - 'data-validate-duplicate-node-id', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'data-validate-duplicate-node-id'); graph.destroy(); done(); @@ -43,14 +36,10 @@ describe('TreeGraph', () => { }); it('data with error DUPLICATE_NODE_EDGE_ID', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = dataValidate( { @@ -69,10 +58,7 @@ describe('TreeGraph', () => { ); graph.on('afterlayout', async () => { - await expect(canvas).toMatchSVGSnapshot( - dir, - 'data-validate-duplicate-node-edge-id', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'data-validate-duplicate-node-edge-id'); graph.destroy(); done(); @@ -80,14 +66,10 @@ describe('TreeGraph', () => { }); it('data with error NODE_NO_DATA', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = dataValidate( { @@ -106,10 +88,7 @@ describe('TreeGraph', () => { ); graph.on('afterlayout', async () => { - await expect(canvas).toMatchSVGSnapshot( - dir, - 'data-validate-node-no-data', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'data-validate-node-no-data'); graph.destroy(); done(); @@ -117,14 +96,10 @@ describe('TreeGraph', () => { }); it('data with error NODE_NO_ID', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = dataValidate( { @@ -151,14 +126,10 @@ describe('TreeGraph', () => { }); it('data with error EDGE_NO_ID', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = dataValidate( { @@ -184,14 +155,10 @@ describe('TreeGraph', () => { }); }); it('data with error NODE_PARENT_NOT_EXIST', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = dataValidate( { @@ -210,10 +177,7 @@ describe('TreeGraph', () => { ); graph.on('afterlayout', async () => { - await expect(canvas).toMatchSVGSnapshot( - dir, - 'data-validate-node-parent-not-exist', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'data-validate-node-parent-not-exist'); graph.destroy(); done(); @@ -221,14 +185,10 @@ describe('TreeGraph', () => { }); it('data with error EDGE_SOURCE_NOT_EXIST', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = dataValidate( { @@ -247,10 +207,7 @@ describe('TreeGraph', () => { ); graph.on('afterlayout', async () => { - await expect(canvas).toMatchSVGSnapshot( - dir, - 'data-validate-edge-source-not-exist', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'data-validate-edge-source-not-exist'); graph.destroy(); done(); @@ -258,14 +215,10 @@ describe('TreeGraph', () => { }); it('data with error EDGE_NO_SOURCE', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = dataValidate( { @@ -284,10 +237,7 @@ describe('TreeGraph', () => { ); graph.on('afterlayout', async () => { - await expect(canvas).toMatchSVGSnapshot( - dir, - 'data-validate-edge-no-source', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'data-validate-edge-no-source'); graph.destroy(); done(); @@ -295,14 +245,10 @@ describe('TreeGraph', () => { }); it('data with error COMBO_NO_ID', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = dataValidate( { diff --git a/packages/g6/tests/integration/items-edge-arrow.spec.ts b/packages/g6/tests/integration/items-edge-arrow.spec.ts index 27a8d3402cb..1cab3af1311 100644 --- a/packages/g6/tests/integration/items-edge-arrow.spec.ts +++ b/packages/g6/tests/integration/items-edge-arrow.spec.ts @@ -1,19 +1,15 @@ -import { createContext } from './utils'; import arrow from '../demo/item/edge/arrow'; +import { createContext } from './utils'; import './utils/useSnapshotMatchers'; const dir = `${__dirname}/snapshots/items/edge/arrow`; describe('Edge start arrow', () => { it('Edge with endArrow', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = arrow( { @@ -35,39 +31,24 @@ describe('Edge start arrow', () => { graph.on('afterlayout', async () => { await expect(canvas).toMatchSVGSnapshot(dir, 'arrow-end'); - const $typeBtn = document.getElementById( - 'arrow-change-type', - ) as HTMLInputElement; + const $typeBtn = document.getElementById('arrow-change-type') as HTMLInputElement; $typeBtn.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'arrow-end-change-type-circle', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'arrow-end-change-type-circle'); $typeBtn.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'arrow-end-change-type-rect', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'arrow-end-change-type-rect'); $typeBtn.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'arrow-end-change-type-diamond', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'arrow-end-change-type-diamond'); $typeBtn.click(); await expect(canvas).toMatchSVGSnapshot(dir, 'arrow-end-change-type-vee'); - const $colorBtn = document.getElementById( - 'arrow-change-color', - ) as HTMLInputElement; + const $colorBtn = document.getElementById('arrow-change-color') as HTMLInputElement; $colorBtn.click(); await expect(canvas).toMatchSVGSnapshot(dir, 'arrow-end-change-color'); - const $removeBtn = document.getElementById( - 'arrow-remove', - ) as HTMLInputElement; + const $removeBtn = document.getElementById('arrow-remove') as HTMLInputElement; $removeBtn.click(); await expect(canvas).toMatchSVGSnapshot(dir, 'arrow-end-remove'); @@ -80,14 +61,10 @@ describe('Edge start arrow', () => { }); it('Edge with startArrow', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = arrow( { diff --git a/packages/g6/tests/integration/items-edge-line.spec.ts b/packages/g6/tests/integration/items-edge-line.spec.ts index 9027abb2d40..e70da56d4d0 100644 --- a/packages/g6/tests/integration/items-edge-line.spec.ts +++ b/packages/g6/tests/integration/items-edge-line.spec.ts @@ -6,14 +6,10 @@ const dir = `${__dirname}/snapshots/items/edge/line`; describe('Items edge line', () => { it('should be rendered correctly', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = lineEdge({ backgroundCanvas, @@ -32,40 +28,25 @@ describe('Items edge line', () => { /** * Click the checkbox to show label. */ - const $showLabel = document.querySelectorAll( - 'input', - )[0] as HTMLInputElement; + const $showLabel = document.querySelectorAll('input')[0] as HTMLInputElement; $showLabel.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'items-edge-line-show-label', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'items-edge-line-show-label'); $showLabel.click(); /** * Click the checkbox to display selected style. */ - const $selected = document.querySelectorAll( - 'input', - )[2] as HTMLInputElement; + const $selected = document.querySelectorAll('input')[2] as HTMLInputElement; $selected.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'items-edge-line-selected-style', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'items-edge-line-selected-style'); $selected.click(); /** * Click the checkbox to highlight. */ - const $highlight = document.querySelectorAll( - 'input', - )[3] as HTMLInputElement; + const $highlight = document.querySelectorAll('input')[3] as HTMLInputElement; $highlight.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'items-edge-line-highlight-style', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'items-edge-line-highlight-style'); $highlight.click(); graph.destroy(); diff --git a/packages/g6/tests/integration/items-edge-loop.spec.ts b/packages/g6/tests/integration/items-edge-loop.spec.ts index 219fd99398b..8f8e5f6fce4 100644 --- a/packages/g6/tests/integration/items-edge-loop.spec.ts +++ b/packages/g6/tests/integration/items-edge-loop.spec.ts @@ -6,14 +6,10 @@ const dir = `${__dirname}/snapshots/items/edge/loop`; describe('Items edge line', () => { it('should be rendered correctly', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = loopEdge({ backgroundCanvas, @@ -32,9 +28,7 @@ describe('Items edge line', () => { /** * Click the checkbox to switch clockwise. */ - const $switchClockwise = document.querySelectorAll( - 'input', - )[0] as HTMLInputElement; + const $switchClockwise = document.querySelectorAll('input')[0] as HTMLInputElement; $switchClockwise.click(); await expect(canvas).toMatchSVGSnapshot(dir, 'items-edge-loop-clockwise'); $switchClockwise.click(); @@ -50,25 +44,17 @@ describe('Items edge line', () => { /** * Click the button to change loop position. */ - const $loopPositionBtn = document.querySelectorAll( - 'button', - )[0] as HTMLButtonElement; + const $loopPositionBtn = document.querySelectorAll('button')[0] as HTMLButtonElement; $loopPositionBtn.click(); await expect(canvas).toMatchSVGSnapshot(dir, 'items-edge-loop-top-right'); $loopPositionBtn.click(); await expect(canvas).toMatchSVGSnapshot(dir, 'items-edge-loop-right'); $loopPositionBtn.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'items-edge-loop-bottom-right', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'items-edge-loop-bottom-right'); $loopPositionBtn.click(); await expect(canvas).toMatchSVGSnapshot(dir, 'items-edge-loop-bottom'); $loopPositionBtn.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'items-edge-loop-bottom-left', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'items-edge-loop-bottom-left'); $loopPositionBtn.click(); await expect(canvas).toMatchSVGSnapshot(dir, 'items-edge-loop-left'); $loopPositionBtn.click(); diff --git a/packages/g6/tests/integration/items-edge-polyline.spec.ts b/packages/g6/tests/integration/items-edge-polyline.spec.ts index 344b3c1f173..16fbb516f88 100644 --- a/packages/g6/tests/integration/items-edge-polyline.spec.ts +++ b/packages/g6/tests/integration/items-edge-polyline.spec.ts @@ -1,19 +1,15 @@ import polylineEdge from '../demo/item/edge/polyline-edge'; -import './utils/useSnapshotMatchers'; import { createContext } from './utils'; +import './utils/useSnapshotMatchers'; const dir = `${__dirname}/snapshots/items/edge/polyline`; describe('Items edge polyline', () => { it('should be rendered correctly', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = polylineEdge({ backgroundCanvas, @@ -32,40 +28,25 @@ describe('Items edge polyline', () => { /** * Click the checkbox to show label. */ - const $showLabel = document.querySelectorAll( - 'input', - )[0] as HTMLInputElement; + const $showLabel = document.querySelectorAll('input')[0] as HTMLInputElement; $showLabel.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'items-edge-polyline-show-label', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'items-edge-polyline-show-label'); $showLabel.click(); /** * Click the checkbox to display selected style. */ - const $selected = document.querySelectorAll( - 'input', - )[2] as HTMLInputElement; + const $selected = document.querySelectorAll('input')[2] as HTMLInputElement; $selected.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'items-edge-polyline-selected-style', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'items-edge-polyline-selected-style'); $selected.click(); /** * Click the checkbox to highlight. */ - const $highlight = document.querySelectorAll( - 'input', - )[3] as HTMLInputElement; + const $highlight = document.querySelectorAll('input')[3] as HTMLInputElement; $highlight.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'items-edge-polyline-highlight-style', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'items-edge-polyline-highlight-style'); $highlight.click(); /** @@ -73,21 +54,14 @@ describe('Items edge polyline', () => { */ const $radius = document.querySelectorAll('input')[4] as HTMLInputElement; $radius.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'items-edge-polyline-radius', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'items-edge-polyline-radius'); $radius.click(); /** * Click the checkbox to enable automatic obstacle avoidances. */ - const $obstacle = document.querySelectorAll( - 'input', - )[5] as HTMLInputElement; - const $enableObstacleAvoidance = document.querySelectorAll( - 'input', - )[6] as HTMLInputElement; + const $obstacle = document.querySelectorAll('input')[5] as HTMLInputElement; + const $enableObstacleAvoidance = document.querySelectorAll('input')[6] as HTMLInputElement; /** * Click the checkbox to prevent obstacle to overlap edges. diff --git a/packages/g6/tests/integration/items-node-donut.spec.ts b/packages/g6/tests/integration/items-node-donut.spec.ts index 0096d7cfdf6..75892d0a759 100644 --- a/packages/g6/tests/integration/items-node-donut.spec.ts +++ b/packages/g6/tests/integration/items-node-donut.spec.ts @@ -1,19 +1,15 @@ import donutNode from '../demo/item/node/donut-node'; -import './utils/useSnapshotMatchers'; import { createContext } from './utils'; +import './utils/useSnapshotMatchers'; const dir = `${__dirname}/snapshots/items/node/donut`; describe('Items node donut', () => { it('should be rendered correctly', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = donutNode({ backgroundCanvas, @@ -32,28 +28,18 @@ describe('Items node donut', () => { /** * Click the checkbox to set custom colors. */ - const $customColors = document.querySelectorAll( - 'input', - )[0] as HTMLInputElement; + const $customColors = document.querySelectorAll('input')[0] as HTMLInputElement; $customColors.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'items-node-donut-custom-colors', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'items-node-donut-custom-colors'); $customColors.click(); /** * Click the checkbox to set custom inner size. */ - const $innerSize = document.querySelectorAll( - 'input', - )[1] as HTMLInputElement; + const $innerSize = document.querySelectorAll('input')[1] as HTMLInputElement; $innerSize.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'items-node-donut-custom-innersize', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'items-node-donut-custom-innersize'); $innerSize.click(); /** @@ -61,23 +47,15 @@ describe('Items node donut', () => { */ const $attrs = document.querySelectorAll('input')[2] as HTMLInputElement; $attrs.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'items-node-donut-custom-attrs', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'items-node-donut-custom-attrs'); $attrs.click(); /** * Click the checkbox to set selected style. */ - const $selected = document.querySelectorAll( - 'input', - )[3] as HTMLInputElement; + const $selected = document.querySelectorAll('input')[3] as HTMLInputElement; $selected.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'items-node-donut-selected-style', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'items-node-donut-selected-style'); $selected.click(); graph.destroy(); diff --git a/packages/g6/tests/integration/items-node-image.spec.ts b/packages/g6/tests/integration/items-node-image.spec.ts index 2e43b144d30..15e42c74e4d 100644 --- a/packages/g6/tests/integration/items-node-image.spec.ts +++ b/packages/g6/tests/integration/items-node-image.spec.ts @@ -1,19 +1,15 @@ import imageNode from '../demo/item/node/image'; -import './utils/useSnapshotMatchers'; import { createContext } from './utils'; +import './utils/useSnapshotMatchers'; const dir = `${__dirname}/snapshots/items/node/image`; describe('Items node image', () => { it('should be rendered correctly', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = imageNode({ backgroundCanvas, diff --git a/packages/g6/tests/integration/layouts-circular.spec.ts b/packages/g6/tests/integration/layouts-circular.spec.ts index a437752d946..be26d969a1f 100644 --- a/packages/g6/tests/integration/layouts-circular.spec.ts +++ b/packages/g6/tests/integration/layouts-circular.spec.ts @@ -6,14 +6,10 @@ const dir = `${__dirname}/snapshots/layouts`; describe('Circular layout', () => { it('should be rendered correctly', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = circular({ backgroundCanvas, diff --git a/packages/g6/tests/integration/layouts-d3force.spec.ts b/packages/g6/tests/integration/layouts-d3force.spec.ts index fd8f2ab3be8..38cb75281ad 100644 --- a/packages/g6/tests/integration/layouts-d3force.spec.ts +++ b/packages/g6/tests/integration/layouts-d3force.spec.ts @@ -9,14 +9,10 @@ describe('D3Force layout', () => { * D3 force has some random result, which is hard to test with screenshots. */ it.skip('should be rendered correctly', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = d3force({ backgroundCanvas, diff --git a/packages/g6/tests/integration/layouts-dagre.spec.ts b/packages/g6/tests/integration/layouts-dagre.spec.ts index a407c5cc3a9..1237cded85e 100644 --- a/packages/g6/tests/integration/layouts-dagre.spec.ts +++ b/packages/g6/tests/integration/layouts-dagre.spec.ts @@ -6,14 +6,10 @@ const dir = `${__dirname}/snapshots/layouts`; describe('Dagre layout', () => { it('should be rendered correctly', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = dagre({ backgroundCanvas, diff --git a/packages/g6/tests/integration/layouts-force.spec.ts b/packages/g6/tests/integration/layouts-force.spec.ts index 2deb6ef1f25..4114aaea880 100644 --- a/packages/g6/tests/integration/layouts-force.spec.ts +++ b/packages/g6/tests/integration/layouts-force.spec.ts @@ -6,14 +6,10 @@ const dir = `${__dirname}/snapshots/layouts`; describe.skip('Force layout', () => { it('should be rendered correctly', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = force({ backgroundCanvas, diff --git a/packages/g6/tests/integration/layouts-force3d.spec.ts b/packages/g6/tests/integration/layouts-force3d.spec.ts index 663cf340a85..86105f7a381 100644 --- a/packages/g6/tests/integration/layouts-force3d.spec.ts +++ b/packages/g6/tests/integration/layouts-force3d.spec.ts @@ -1,13 +1,12 @@ import force3D from '../demo/layouts/force-3d'; -import './utils/useSnapshotMatchers'; import { createContext } from './utils'; +import './utils/useSnapshotMatchers'; const dir = `${__dirname}/snapshots/layouts`; describe('Force3D layout', () => { it.skip('should be rendered correctly with WebGL', (done) => { - const { backgroundCanvas, canvas, transientCanvas, container } = - createContext(500, 500); + const { backgroundCanvas, canvas, transientCanvas, container } = createContext(500, 500); const graph = force3D({ container, diff --git a/packages/g6/tests/integration/layouts-grid.spec.ts b/packages/g6/tests/integration/layouts-grid.spec.ts index 7ec5fa7c5bf..3598b805796 100644 --- a/packages/g6/tests/integration/layouts-grid.spec.ts +++ b/packages/g6/tests/integration/layouts-grid.spec.ts @@ -6,14 +6,10 @@ const dir = `${__dirname}/snapshots/layouts`; describe('Grid layout', () => { it('should be rendered correctly', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = grid({ backgroundCanvas, diff --git a/packages/g6/tests/integration/node-diamond.spec.ts b/packages/g6/tests/integration/node-diamond.spec.ts index 75fda0bd506..6a4fd6db439 100644 --- a/packages/g6/tests/integration/node-diamond.spec.ts +++ b/packages/g6/tests/integration/node-diamond.spec.ts @@ -1,20 +1,16 @@ import diamond from '../demo/demo/diamond'; -import './utils/useSnapshotMatchers'; import { createContext } from './utils'; import { triggerEvent } from './utils/event'; +import './utils/useSnapshotMatchers'; const dir = `${__dirname}/snapshots/items/node/diamond`; describe('node diamond', () => { it('should be rendered correctly', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = diamond({ backgroundCanvas, diff --git a/packages/g6/tests/integration/node-ellipse.spec.ts b/packages/g6/tests/integration/node-ellipse.spec.ts index 850269fa176..a0ecc187f03 100644 --- a/packages/g6/tests/integration/node-ellipse.spec.ts +++ b/packages/g6/tests/integration/node-ellipse.spec.ts @@ -1,20 +1,16 @@ import ellipse from '../demo/demo/ellipse'; -import './utils/useSnapshotMatchers'; import { createContext } from './utils'; import { triggerEvent } from './utils/event'; +import './utils/useSnapshotMatchers'; const dir = `${__dirname}/snapshots/items/node/ellipse`; describe('node ellipse', () => { it('should be rendered correctly', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = ellipse({ backgroundCanvas, diff --git a/packages/g6/tests/integration/node-hexagon.spec.ts b/packages/g6/tests/integration/node-hexagon.spec.ts index c9978018df8..2109cec2271 100644 --- a/packages/g6/tests/integration/node-hexagon.spec.ts +++ b/packages/g6/tests/integration/node-hexagon.spec.ts @@ -1,20 +1,16 @@ import hexagon from '../demo/demo/hexagon'; -import './utils/useSnapshotMatchers'; import { createContext } from './utils'; import { triggerEvent } from './utils/event'; +import './utils/useSnapshotMatchers'; const dir = `${__dirname}/snapshots/items/node/hexagon`; describe('node hexagon', () => { it('should be rendered correctly', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = hexagon({ backgroundCanvas, diff --git a/packages/g6/tests/integration/node-modelRect.spec.ts b/packages/g6/tests/integration/node-modelRect.spec.ts index f3fdd66b72b..16d378ab51d 100644 --- a/packages/g6/tests/integration/node-modelRect.spec.ts +++ b/packages/g6/tests/integration/node-modelRect.spec.ts @@ -1,20 +1,16 @@ import modelRect from '../demo/demo/modelRect'; -import './utils/useSnapshotMatchers'; import { createContext } from './utils'; import { triggerEvent } from './utils/event'; +import './utils/useSnapshotMatchers'; const dir = `${__dirname}/snapshots/items/node/modelRect`; describe('node modelRect', () => { it('should be rendered correctly', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = modelRect({ backgroundCanvas, diff --git a/packages/g6/tests/integration/node-star.spec.ts b/packages/g6/tests/integration/node-star.spec.ts index 49ff2fe26c1..f7abe7e53c2 100644 --- a/packages/g6/tests/integration/node-star.spec.ts +++ b/packages/g6/tests/integration/node-star.spec.ts @@ -1,20 +1,16 @@ import star from '../demo/demo/star'; -import './utils/useSnapshotMatchers'; import { createContext } from './utils'; import { triggerEvent } from './utils/event'; +import './utils/useSnapshotMatchers'; const dir = `${__dirname}/snapshots/items/node/star`; describe('node star', () => { it('should be rendered correctly', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = star({ backgroundCanvas, diff --git a/packages/g6/tests/integration/node-triangle.spec.ts b/packages/g6/tests/integration/node-triangle.spec.ts index 1c6749026d8..dfbd909dadd 100644 --- a/packages/g6/tests/integration/node-triangle.spec.ts +++ b/packages/g6/tests/integration/node-triangle.spec.ts @@ -1,20 +1,16 @@ import triangle from '../demo/demo/triangle'; -import './utils/useSnapshotMatchers'; import { createContext } from './utils'; import { triggerEvent } from './utils/event'; +import './utils/useSnapshotMatchers'; const dir = `${__dirname}/snapshots/items/node/triangle`; describe('node triangle', () => { it('should be rendered correctly', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = triangle({ backgroundCanvas, diff --git a/packages/g6/tests/integration/plugins-edgeFilterLens.spec.ts b/packages/g6/tests/integration/plugins-edgeFilterLens.spec.ts index cf6676ba470..4fdc851973a 100644 --- a/packages/g6/tests/integration/plugins-edgeFilterLens.spec.ts +++ b/packages/g6/tests/integration/plugins-edgeFilterLens.spec.ts @@ -7,14 +7,10 @@ const dir = `${__dirname}/snapshots/plugins/edgeFilterLens`; describe('Default EdgeFilterLens', () => { it('should be rendered correctly with fitler lens with mousemove', async () => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = EdgeFilterLens({ backgroundCanvas, canvas, @@ -35,10 +31,7 @@ describe('Default EdgeFilterLens', () => { await process; triggerEvent(graph, 'mousedown', 200, 200); - await expect(transientCanvas).toMatchSVGSnapshot( - dir, - 'plugins-edge-filter-lens-transients', - ); + await expect(transientCanvas).toMatchSVGSnapshot(dir, 'plugins-edge-filter-lens-transients'); graph.destroy(); }); }); diff --git a/packages/g6/tests/integration/plugins-history-combo.spec.ts b/packages/g6/tests/integration/plugins-history-combo.spec.ts index 64daa9787e5..aa541d938c5 100644 --- a/packages/g6/tests/integration/plugins-history-combo.spec.ts +++ b/packages/g6/tests/integration/plugins-history-combo.spec.ts @@ -1,19 +1,15 @@ import historyCombo from '../demo/plugins/history-combo'; -import './utils/useSnapshotMatchers'; import { createContext } from './utils'; +import './utils/useSnapshotMatchers'; const dir = `${__dirname}/snapshots/plugins/history`; describe('Plugins history combo', () => { it('should be rendered correctly', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = historyCombo({ backgroundCanvas, @@ -27,10 +23,7 @@ describe('Plugins history combo', () => { }); graph.on('afterlayout', async () => { - await expect(canvas).toMatchSVGSnapshot( - dir, - 'plugins-history-combo-init', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'plugins-history-combo-init'); const $undo = document.querySelectorAll('button')[0]; const $redo = document.querySelectorAll('button')[1]; @@ -39,21 +32,13 @@ describe('Plugins history combo', () => { * Click button to add combo 2. * Verify that the API `addCombo` supports history. */ - const $addCombo = document.querySelectorAll( - 'button', - )[2] as HTMLInputElement; + const $addCombo = document.querySelectorAll('button')[2] as HTMLInputElement; $addCombo.click(); await expect(canvas).toMatchSVGSnapshot(dir, 'plugins-history-add-combo'); $undo.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'plugins-history-add-combo-undo', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'plugins-history-add-combo-undo'); $redo.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'plugins-history-add-combo-redo', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'plugins-history-add-combo-redo'); $undo.click(); /** diff --git a/packages/g6/tests/integration/plugins-history.spec.ts b/packages/g6/tests/integration/plugins-history.spec.ts index 1770bf6eeb1..e61602db641 100644 --- a/packages/g6/tests/integration/plugins-history.spec.ts +++ b/packages/g6/tests/integration/plugins-history.spec.ts @@ -1,19 +1,15 @@ import history from '../demo/plugins/history'; -import './utils/useSnapshotMatchers'; import { createContext } from './utils'; +import './utils/useSnapshotMatchers'; const dir = `${__dirname}/snapshots/plugins/history`; describe('Plugins history', () => { it('should be rendered correctly', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = history({ backgroundCanvas, @@ -36,136 +32,76 @@ describe('Plugins history', () => { * Click button to set node 1 state selected. * Verify that the API `setItemSate` supports history. */ - const $setState = document.querySelectorAll( - 'button', - )[2] as HTMLInputElement; + const $setState = document.querySelectorAll('button')[2] as HTMLInputElement; $setState.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'plugins-history-set-item-state', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'plugins-history-set-item-state'); $undo.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'plugins-history-set-item-state-undo', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'plugins-history-set-item-state-undo'); $redo.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'plugins-history-set-item-state-redo', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'plugins-history-set-item-state-redo'); /** * Click button to clear node 1 selected. * Verify that the API `clearItemState` supports history. */ - const $clearState = document.querySelectorAll( - 'button', - )[3] as HTMLInputElement; + const $clearState = document.querySelectorAll('button')[3] as HTMLInputElement; $clearState.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'plugins-history-clear-item-state', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'plugins-history-clear-item-state'); $undo.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'plugins-history-clear-item-state-undo', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'plugins-history-clear-item-state-undo'); $redo.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'plugins-history-clear-item-state-redo', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'plugins-history-clear-item-state-redo'); $undo.click(); /** * Click button to add node 3 and edge 2. * Verify that the API `addData` supports history. */ - const $addData = document.querySelectorAll( - 'button', - )[4] as HTMLInputElement; + const $addData = document.querySelectorAll('button')[4] as HTMLInputElement; $addData.click(); await expect(canvas).toMatchSVGSnapshot(dir, 'plugins-history-add-data'); $undo.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'plugins-history-add-data-undo', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'plugins-history-add-data-undo'); $redo.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'plugins-history-add-data-redo', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'plugins-history-add-data-redo'); /** * Click button to delete node 3 and edge 2. * Verify that the API `deleteData` supports history. */ - const $deleteData = document.querySelectorAll( - 'button', - )[5] as HTMLInputElement; + const $deleteData = document.querySelectorAll('button')[5] as HTMLInputElement; $deleteData.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'plugins-history-delete-data', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'plugins-history-delete-data'); $undo.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'plugins-history-delete-data-undo', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'plugins-history-delete-data-undo'); $redo.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'plugins-history-delete-data-redo', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'plugins-history-delete-data-redo'); $undo.click(); /** * Click button to update node 1. * Verify that the API `updateData` supports history. */ - const $updateData = document.querySelectorAll( - 'button', - )[6] as HTMLInputElement; + const $updateData = document.querySelectorAll('button')[6] as HTMLInputElement; $updateData.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'plugins-history-update-data', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'plugins-history-update-data'); $undo.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'plugins-history-update-data-undo', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'plugins-history-update-data-undo'); $redo.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'plugins-history-update-data-redo', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'plugins-history-update-data-redo'); $undo.click(); /** * Click button to hide node 3. * Verify that the API `hideItem` supports history. */ - const $showHideItem = document.querySelectorAll( - 'button', - )[7] as HTMLInputElement; + const $showHideItem = document.querySelectorAll('button')[7] as HTMLInputElement; $showHideItem.click(); await expect(canvas).toMatchSVGSnapshot(dir, 'plugins-history-hide-item'); $undo.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'plugins-history-hide-item-undo', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'plugins-history-hide-item-undo'); $redo.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'plugins-history-hide-item-redo', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'plugins-history-hide-item-redo'); /** * Click button to show node 3. @@ -174,59 +110,34 @@ describe('Plugins history', () => { $showHideItem.click(); await expect(canvas).toMatchSVGSnapshot(dir, 'plugins-history-show-item'); $undo.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'plugins-history-show-item-undo', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'plugins-history-show-item-undo'); $redo.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'plugins-history-show-item-redo', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'plugins-history-show-item-redo'); /** * Click button to back node 3. * Verify that the API `backItem` supports history. */ - const $backItem = document.querySelectorAll( - 'button', - )[9] as HTMLInputElement; + const $backItem = document.querySelectorAll('button')[9] as HTMLInputElement; $updateData.click(); $backItem.click(); await expect(canvas).toMatchSVGSnapshot(dir, 'plugins-history-back-item'); $undo.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'plugins-history-back-item-undo', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'plugins-history-back-item-undo'); $redo.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'plugins-history-back-item-redo', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'plugins-history-back-item-redo'); /** * Click button to front node 3. * Verify that the API `frontItem` supports history. */ - const $frontItem = document.querySelectorAll( - 'button', - )[8] as HTMLInputElement; + const $frontItem = document.querySelectorAll('button')[8] as HTMLInputElement; $frontItem.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'plugins-history-front-item', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'plugins-history-front-item'); $undo.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'plugins-history-front-item-undo', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'plugins-history-front-item-undo'); $redo.click(); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'plugins-history-front-item-redo', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'plugins-history-front-item-redo'); graph.destroy(); done(); diff --git a/packages/g6/tests/integration/plugins-hull.spec.ts b/packages/g6/tests/integration/plugins-hull.spec.ts index 0d85e847c21..6605d7d8d1c 100644 --- a/packages/g6/tests/integration/plugins-hull.spec.ts +++ b/packages/g6/tests/integration/plugins-hull.spec.ts @@ -6,14 +6,10 @@ const dir = `${__dirname}/snapshots/plugins/hull`; describe('Hull plugin', () => { it('should be rendered correctly with round-convex type', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = hull( { @@ -34,89 +30,49 @@ describe('Hull plugin', () => { ); graph.on('afterlayout', async () => { - await expect(transientCanvas).toMatchSVGSnapshot( - dir, - 'plugins-hull-render', - ); + await expect(transientCanvas).toMatchSVGSnapshot(dir, 'plugins-hull-render'); // ========= remove hull ========= - const $removeHull = document.getElementById( - 'hull-removehull', - ) as HTMLInputElement; + const $removeHull = document.getElementById('hull-removehull') as HTMLInputElement; console.log('$removeHull', $removeHull); $removeHull.click(); - await expect(transientCanvas).toMatchSVGSnapshot( - dir, - 'plugins-hull-add-hull', - ); + await expect(transientCanvas).toMatchSVGSnapshot(dir, 'plugins-hull-add-hull'); // ========= add hull ========= $removeHull.click(); - await expect(transientCanvas).toMatchSVGSnapshot( - dir, - 'plugins-hull-remove-hull', - ); + await expect(transientCanvas).toMatchSVGSnapshot(dir, 'plugins-hull-remove-hull'); // ========= remove node ========= - const $removeNode = document.getElementById( - 'hull-removenode', - ) as HTMLInputElement; + const $removeNode = document.getElementById('hull-removenode') as HTMLInputElement; $removeNode.click(); - await expect(transientCanvas).toMatchSVGSnapshot( - dir, - 'plugins-hull-remove-node', - ); + await expect(transientCanvas).toMatchSVGSnapshot(dir, 'plugins-hull-remove-node'); // ========= add node ========= $removeNode.click(); - await expect(transientCanvas).toMatchSVGSnapshot( - dir, - 'plugins-hull-add-node', - ); + await expect(transientCanvas).toMatchSVGSnapshot(dir, 'plugins-hull-add-node'); // ========= remove member ========= - const $removeMember = document.getElementById( - 'hull-removemember', - ) as HTMLInputElement; + const $removeMember = document.getElementById('hull-removemember') as HTMLInputElement; $removeMember.click(); - await expect(transientCanvas).toMatchSVGSnapshot( - dir, - 'plugins-hull-remove-member', - ); + await expect(transientCanvas).toMatchSVGSnapshot(dir, 'plugins-hull-remove-member'); // ========= add member ========= $removeMember.click(); - await expect(transientCanvas).toMatchSVGSnapshot( - dir, - 'plugins-hull-add-member', - ); + await expect(transientCanvas).toMatchSVGSnapshot(dir, 'plugins-hull-add-member'); // ========= add non-member ========= - const $removeNonMember = document.getElementById( - 'hull-removenonmember', - ) as HTMLInputElement; + const $removeNonMember = document.getElementById('hull-removenonmember') as HTMLInputElement; $removeNonMember.click(); - await expect(transientCanvas).toMatchSVGSnapshot( - dir, - 'plugins-hull-add-nonmember', - ); + await expect(transientCanvas).toMatchSVGSnapshot(dir, 'plugins-hull-add-nonmember'); // ========= remove non-member ========= $removeNonMember.click(); - await expect(transientCanvas).toMatchSVGSnapshot( - dir, - 'plugins-hull-remove-nonmember', - ); + await expect(transientCanvas).toMatchSVGSnapshot(dir, 'plugins-hull-remove-nonmember'); // ========= update config ========= - const $updateConfig = document.getElementById( - 'hull-updateconfig', - ) as HTMLInputElement; + const $updateConfig = document.getElementById('hull-updateconfig') as HTMLInputElement; $updateConfig.click(); - await expect(transientCanvas).toMatchSVGSnapshot( - dir, - 'plugins-hull-update-config', - ); + await expect(transientCanvas).toMatchSVGSnapshot(dir, 'plugins-hull-update-config'); graph.destroy(); done(); @@ -124,14 +80,10 @@ describe('Hull plugin', () => { }); it('should be rendered correctly with bubble type', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = hull( { @@ -152,10 +104,7 @@ describe('Hull plugin', () => { ); graph.on('afterlayout', async () => { - await expect(transientCanvas).toMatchSVGSnapshot( - dir, - 'plugins-hull-render-bubble', - ); + await expect(transientCanvas).toMatchSVGSnapshot(dir, 'plugins-hull-render-bubble'); graph.destroy(); done(); @@ -163,14 +112,10 @@ describe('Hull plugin', () => { }); it('should be rendered correctly with smooth-convex type', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = hull( { @@ -190,10 +135,7 @@ describe('Hull plugin', () => { ); graph.on('afterlayout', async () => { - await expect(transientCanvas).toMatchSVGSnapshot( - dir, - 'plugins-hull-render-smooth-convex', - ); + await expect(transientCanvas).toMatchSVGSnapshot(dir, 'plugins-hull-render-smooth-convex'); graph.destroy(); done(); diff --git a/packages/g6/tests/integration/plugins-watermarker.spec.ts b/packages/g6/tests/integration/plugins-watermarker.spec.ts index 5e48796a971..c32b6196af1 100644 --- a/packages/g6/tests/integration/plugins-watermarker.spec.ts +++ b/packages/g6/tests/integration/plugins-watermarker.spec.ts @@ -7,14 +7,10 @@ const dir = `${__dirname}/snapshots/plugins/watermarker`; describe('plugin', () => { it('watermarker with text config', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const watermarkerContainer = document.createElement('div'); document.body.appendChild(container); @@ -37,10 +33,7 @@ describe('plugin', () => { }, ); graph.on('afterlayout', async () => { - await expect(watermarkerCanvas).toMatchSVGSnapshot( - dir, - 'plugins-watermarker-text', - ); + await expect(watermarkerCanvas).toMatchSVGSnapshot(dir, 'plugins-watermarker-text'); watermarkerCanvas.destroy(); graph.destroy(); done(); diff --git a/packages/g6/tests/integration/timebar-chart.spec.ts b/packages/g6/tests/integration/timebar-chart.spec.ts index 81799df7e79..d1e9b699d8c 100644 --- a/packages/g6/tests/integration/timebar-chart.spec.ts +++ b/packages/g6/tests/integration/timebar-chart.spec.ts @@ -6,14 +6,10 @@ const dir = `${__dirname}/snapshots/plugins/timebar`; describe.skip('Timebar Chart', () => { it('should be rendered correctly', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = TimebarTime({ backgroundCanvas, canvas, diff --git a/packages/g6/tests/integration/timebar-timeline.spec.ts b/packages/g6/tests/integration/timebar-timeline.spec.ts index 3be82b38f6d..307b527fa10 100644 --- a/packages/g6/tests/integration/timebar-timeline.spec.ts +++ b/packages/g6/tests/integration/timebar-timeline.spec.ts @@ -6,14 +6,10 @@ const dir = `${__dirname}/snapshots/plugins/timebar`; describe.skip('Default Timebar', () => { it('should be rendered correctly', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = TimebarTime({ backgroundCanvas, canvas, diff --git a/packages/g6/tests/integration/toolbar-default.spec.ts b/packages/g6/tests/integration/toolbar-default.spec.ts index 776ffb07f96..cfc48a3bab9 100644 --- a/packages/g6/tests/integration/toolbar-default.spec.ts +++ b/packages/g6/tests/integration/toolbar-default.spec.ts @@ -6,14 +6,10 @@ const dir = `${__dirname}/snapshots/plugins/toolbar`; describe('Toolbar', () => { it('should be rendered correctly', (done) => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = toolbar({ backgroundCanvas, canvas, diff --git a/packages/g6/tests/integration/treegraph-render.spec.ts b/packages/g6/tests/integration/treegraph-render.spec.ts index 0b0f3b7058e..5e5096a3302 100644 --- a/packages/g6/tests/integration/treegraph-render.spec.ts +++ b/packages/g6/tests/integration/treegraph-render.spec.ts @@ -6,14 +6,10 @@ const dir = `${__dirname}/snapshots/treegraph`; describe.skip('TreeGraph', () => { it('graph data with tree layout, remove/add/update node, and change layout', async () => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = treeGraph( { @@ -32,70 +28,45 @@ describe.skip('TreeGraph', () => { }, ); - await expect([canvas, labelCanvas]).toMatchSVGSnapshot( - dir, - 'treegraph-graphdata', - ); + await expect([canvas, labelCanvas]).toMatchSVGSnapshot(dir, 'treegraph-graphdata'); // ====== change to tree data ====== const $changeData = document.getElementById('treegraph-changedata')!; $changeData.click(); - await expect([canvas, labelCanvas]).toMatchSVGSnapshot( - dir, - 'treegraph-graphdata-changedata', - ); + await expect([canvas, labelCanvas]).toMatchSVGSnapshot(dir, 'treegraph-graphdata-changedata'); $changeData.click(); - await expect([canvas, labelCanvas]).toMatchSVGSnapshot( - dir, - 'treegraph-graphdata-changedata2', - ); + await expect([canvas, labelCanvas]).toMatchSVGSnapshot(dir, 'treegraph-graphdata-changedata2'); // ====== remove a node ====== const $removeNode = document.getElementById('treegraph-removenode')!; $removeNode.click(); // remove graph.layout(); - await expect([canvas, labelCanvas]).toMatchSVGSnapshot( - dir, - 'treegraph-graphdata-removenode', - ); + await expect([canvas, labelCanvas]).toMatchSVGSnapshot(dir, 'treegraph-graphdata-removenode'); // ====== add a node ====== $removeNode.click(); // add graph.layout(); - await expect([canvas, labelCanvas]).toMatchSVGSnapshot( - dir, - 'treegraph-graphdata-addnode', - ); + await expect([canvas, labelCanvas]).toMatchSVGSnapshot(dir, 'treegraph-graphdata-addnode'); // ====== update a node ====== const $updateNode = document.getElementById('treegraph-updatenode')!; $updateNode.click(); // update label - await expect([canvas, labelCanvas]).toMatchSVGSnapshot( - dir, - 'treegraph-graphdata-updatenode', - ); + await expect([canvas, labelCanvas]).toMatchSVGSnapshot(dir, 'treegraph-graphdata-updatenode'); // ====== change to graph layout ====== const $changeLayout = document.getElementById('treegraph-changelayout')!; $changeLayout.click(); - await expect([canvas, labelCanvas]).toMatchSVGSnapshot( - dir, - 'treegraph-graphdata-changelayout', - ); + await expect([canvas, labelCanvas]).toMatchSVGSnapshot(dir, 'treegraph-graphdata-changelayout'); graph.destroy(); }); it('should be rendered correctly with tree data', async () => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = treeGraph( { @@ -114,49 +85,33 @@ describe.skip('TreeGraph', () => { }, ); - await expect([canvas, labelCanvas]).toMatchSVGSnapshot( - dir, - 'treegraph-treedata', - ); + await expect([canvas, labelCanvas]).toMatchSVGSnapshot(dir, 'treegraph-treedata'); // ======= collapse ======= const $collapse = document.getElementById('treegraph-collapse')!; $collapse.click(); // collapse - await expect([canvas, labelCanvas]).toMatchSVGSnapshot( - dir, - 'treegraph-treedata-collapse', - ); + await expect([canvas, labelCanvas]).toMatchSVGSnapshot(dir, 'treegraph-treedata-collapse'); // ======= expand ======= $collapse.click(); // expand - await expect([canvas, labelCanvas]).toMatchSVGSnapshot( - dir, - 'treegraph-treedata-expand', - )!; + await expect([canvas, labelCanvas]).toMatchSVGSnapshot(dir, 'treegraph-treedata-expand')!; // ======= change layout ======= const $changeLayout = document.getElementById('treegraph-changelayout')!; $changeLayout.click(); - await expect([canvas, labelCanvas]).toMatchSVGSnapshot( - dir, - 'treegraph-treedata-changelayout', - ); + await expect([canvas, labelCanvas]).toMatchSVGSnapshot(dir, 'treegraph-treedata-changelayout'); graph.destroy(); }); it('graph data with initiated collapsed', async () => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = treeGraph( { @@ -176,22 +131,15 @@ describe.skip('TreeGraph', () => { }, ); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'treegraph-graphdata-initial-collapse', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'treegraph-graphdata-initial-collapse'); graph.destroy(); }); it('tree data with initiated collapsed', async () => { - const { - backgroundCanvas, - canvas, - container, - labelCanvas, - transientCanvas, - transientLabelCanvas, - } = createContext(500, 500); + const { backgroundCanvas, canvas, container, labelCanvas, transientCanvas, transientLabelCanvas } = createContext( + 500, + 500, + ); const graph = treeGraph( { @@ -211,10 +159,7 @@ describe.skip('TreeGraph', () => { }, ); - await expect(canvas).toMatchSVGSnapshot( - dir, - 'treegraph-treedata-initial-collapse', - ); + await expect(canvas).toMatchSVGSnapshot(dir, 'treegraph-treedata-initial-collapse'); graph.destroy(); }); }); diff --git a/packages/g6/tests/integration/utils/createNodeGCanvas.ts b/packages/g6/tests/integration/utils/createNodeGCanvas.ts index e6443c6ad39..9da791abf8d 100644 --- a/packages/g6/tests/integration/utils/createNodeGCanvas.ts +++ b/packages/g6/tests/integration/utils/createNodeGCanvas.ts @@ -1,13 +1,15 @@ import { Canvas, resetEntityCounter } from '@antv/g'; -import { Renderer as SVGRenderer } from '@antv/g-svg'; import { Plugin as DragAndDropPlugin } from '@antv/g-plugin-dragndrop'; -import { OffscreenCanvasContext, measureText } from './offscreenCanvasContext'; +import { Renderer as SVGRenderer } from '@antv/g-svg'; +import { OffscreenCanvasContext } from './offscreenCanvasContext'; -export function createNodeGCanvas( - dom: HTMLDivElement, - width: number, - height: number, -): Canvas { +/** + * + * @param dom + * @param width + * @param height + */ +export function createNodeGCanvas(dom: HTMLDivElement, width: number, height: number): Canvas { resetEntityCounter(); // setMockMeasureTextWidth(measureText); const offscreenNodeCanvas = { @@ -16,9 +18,7 @@ export function createNodeGCanvas( const context = new OffscreenCanvasContext(offscreenNodeCanvas); const renderer = new SVGRenderer(); - renderer.registerPlugin( - new DragAndDropPlugin({ dragstartDistanceThreshold: 10 }), - ); + renderer.registerPlugin(new DragAndDropPlugin({ dragstartDistanceThreshold: 10 })); return new Canvas({ container: dom, width, diff --git a/packages/g6/tests/integration/utils/event.ts b/packages/g6/tests/integration/utils/event.ts index b88ea33f2c1..ca3d50a4a4c 100644 --- a/packages/g6/tests/integration/utils/event.ts +++ b/packages/g6/tests/integration/utils/event.ts @@ -1,11 +1,13 @@ import { Graph } from '../../../src/runtime/graph'; -export function triggerEvent( - graph: Graph, - type: string, - clientX: number, - clientY: number, -) { +/** + * + * @param graph + * @param type + * @param clientX + * @param clientY + */ +export function triggerEvent(graph: Graph, type: string, clientX: number, clientY: number) { // TODO: TouchEvent // const isMouseEvent = type.startsWith('mouse'); // const isTouchEvent = type.startsWith('touch'); diff --git a/packages/g6/tests/integration/utils/offscreenCanvasContext.ts b/packages/g6/tests/integration/utils/offscreenCanvasContext.ts index 5b71e52d41b..afbf9678783 100644 --- a/packages/g6/tests/integration/utils/offscreenCanvasContext.ts +++ b/packages/g6/tests/integration/utils/offscreenCanvasContext.ts @@ -85,6 +85,11 @@ const defaultWidthMap = { '…': 82, }; +/** + * + * @param text + * @param fontSize + */ export function measureText(text: string, fontSize: number) { let sum = 0; for (let i = 0; i < text.length; i++) { @@ -100,8 +105,7 @@ export class OffscreenCanvasContext { set font(font: string) { // `${fontStyle} ${fontVariant} ${fontWeight} ${fontSizeString} - const [fontStyle, fontVariant, fontWeight, fontSizeString] = - font.split(' '); + const [fontStyle, fontVariant, fontWeight, fontSizeString] = font.split(' '); const fontSize = parseFloat(fontSizeString.replace('px', '')); this.fontSize = fontSize; } diff --git a/packages/g6/tests/integration/utils/toMatchSVGSnapshot.ts b/packages/g6/tests/integration/utils/toMatchSVGSnapshot.ts index 853bdcfceb0..22a2f5bde65 100644 --- a/packages/g6/tests/integration/utils/toMatchSVGSnapshot.ts +++ b/packages/g6/tests/integration/utils/toMatchSVGSnapshot.ts @@ -1,8 +1,8 @@ -import * as path from 'path'; -import * as fs from 'fs'; import { Canvas } from '@antv/g'; -import xmlserializer from 'xmlserializer'; +import * as fs from 'fs'; +import * as path from 'path'; import { format } from 'prettier'; +import xmlserializer from 'xmlserializer'; import { sleep } from './sleep'; export type ToMatchSVGSnapshotOptions = { @@ -10,15 +10,18 @@ export type ToMatchSVGSnapshotOptions = { keepSVGElementId?: boolean; }; const formatSVG = (svg: string, keepSVGElementId: boolean) => { - return ( - keepSVGElementId - ? svg - : svg.replace(/id="[^"]*"/g, '').replace(/clip-path="[^"]*"/g, '') - ).replace('\r\n', '\n'); + return (keepSVGElementId ? svg : svg.replace(/id="[^"]*"/g, '').replace(/clip-path="[^"]*"/g, '')).replace( + '\r\n', + '\n', + ); }; /** * Merge multiple svg into one. + * @param gCanvas + * @param dir + * @param name + * @param options */ // @see https://jestjs.io/docs/26.x/expect#expectextendmatchers export async function toMatchSVGSnapshot( @@ -38,22 +41,18 @@ export async function toMatchSVGSnapshot( let actual: string = ''; // Clone - const svg = ( - gCanvases[0].getContextService().getDomElement() as unknown as SVGElement - ).cloneNode(true) as SVGElement; + const svg = (gCanvases[0].getContextService().getDomElement() as unknown as SVGElement).cloneNode(true) as SVGElement; const gRoot = svg.querySelector('#g-root'); gCanvases.slice(1).forEach((gCanvas) => { - const dom = ( - gCanvas.getContextService().getDomElement() as unknown as SVGElement - ).cloneNode(true) as SVGElement; + const dom = (gCanvas.getContextService().getDomElement() as unknown as SVGElement).cloneNode(true) as SVGElement; gRoot?.append(...(dom.querySelector('#g-root')?.childNodes || [])); }); actual += svg ? formatSVG( - format(xmlserializer.serializeToString(svg as any), { + await format(xmlserializer.serializeToString(svg as any), { parser: 'babel', }), keepSVGElementId, diff --git a/packages/g6/tests/integration/utils/useSnapshotMatchers.ts b/packages/g6/tests/integration/utils/useSnapshotMatchers.ts index fcca404798a..8325db8f246 100644 --- a/packages/g6/tests/integration/utils/useSnapshotMatchers.ts +++ b/packages/g6/tests/integration/utils/useSnapshotMatchers.ts @@ -1,17 +1,10 @@ -import { - toMatchSVGSnapshot, - ToMatchSVGSnapshotOptions, -} from './toMatchSVGSnapshot'; +import { toMatchSVGSnapshot, ToMatchSVGSnapshotOptions } from './toMatchSVGSnapshot'; declare global { // eslint-disable-next-line @typescript-eslint/no-namespace namespace jest { interface Matchers { - toMatchSVGSnapshot( - dir: string, - name: string, - options?: ToMatchSVGSnapshotOptions, - ): Promise; + toMatchSVGSnapshot(dir: string, name: string, options?: ToMatchSVGSnapshotOptions): Promise; } } } diff --git a/packages/g6/tests/main.ts b/packages/g6/tests/main.ts index b9876cde511..45fc002f279 100644 --- a/packages/g6/tests/main.ts +++ b/packages/g6/tests/main.ts @@ -5,21 +5,13 @@ let graph: any; let imageType: DataURLType = 'image/png'; // Select for renderers. -const $rendererSelect = document.getElementById( - 'renderer-select', -) as HTMLSelectElement; +const $rendererSelect = document.getElementById('renderer-select') as HTMLSelectElement; $rendererSelect.onchange = async () => { graph = await render(); }; -const $imageSelect = document.getElementById( - 'image-select', -) as HTMLSelectElement; -const $imageSelectDownloadButton = document.getElementById( - 'image-download-button', -) as HTMLSelectElement; -const $fullImageSelectDownloadButton = document.getElementById( - 'full-image-download-button', -) as HTMLSelectElement; +const $imageSelect = document.getElementById('image-select') as HTMLSelectElement; +const $imageSelectDownloadButton = document.getElementById('image-download-button') as HTMLSelectElement; +const $fullImageSelectDownloadButton = document.getElementById('full-image-download-button') as HTMLSelectElement; $rendererSelect.onchange = async () => { graph = await render(); }; diff --git a/packages/g6/tests/unit/behavior-spec.ts b/packages/g6/tests/unit/behavior-spec.ts index ac1ec549434..d12b06e60db 100644 --- a/packages/g6/tests/unit/behavior-spec.ts +++ b/packages/g6/tests/unit/behavior-spec.ts @@ -95,11 +95,7 @@ describe('behavior', () => { }); it('register behavior and extend G6', () => { class CustomBehavior extends Behavior { - constructor(options: { - key: string; - config: boolean; - itemType?: 'node' | 'edge' | 'combo'; - }) { + constructor(options: { key: string; config: boolean; itemType?: 'node' | 'edge' | 'combo' }) { super(options); } public getSpec: undefined; // select getEvents way to implement diff --git a/packages/g6/tests/unit/behaviors/brush-select-spec.ts b/packages/g6/tests/unit/behaviors/brush-select-spec.ts index 5959f6d2745..4bd38ad4a93 100644 --- a/packages/g6/tests/unit/behaviors/brush-select-spec.ts +++ b/packages/g6/tests/unit/behaviors/brush-select-spec.ts @@ -1249,15 +1249,9 @@ describe('brush-select behavior with brushStyle', () => { }); // node group + edge group + brush expect(graph.transientCanvas.getRoot().childNodes.length).toBe(3); - expect(graph.transientCanvas.getRoot().childNodes[2].config.id).toBe( - 'g6-brush-select-brush-shape', - ); - expect(graph.transientCanvas.getRoot().childNodes[2].style.fill).toBe( - '#f00', - ); - expect( - graph.transientCanvas.getRoot().childNodes[2].style.fillOpacity, - ).toBe(0.5); + expect(graph.transientCanvas.getRoot().childNodes[2].config.id).toBe('g6-brush-select-brush-shape'); + expect(graph.transientCanvas.getRoot().childNodes[2].style.fill).toBe('#f00'); + expect(graph.transientCanvas.getRoot().childNodes[2].style.fillOpacity).toBe(0.5); graph.emit('canvas:pointerup', { canvas: { x: 200, y: 150 }, shiftKey: true, diff --git a/packages/g6/tests/unit/behaviors/drag-canvas-spec.ts b/packages/g6/tests/unit/behaviors/drag-canvas-spec.ts index dd8461931bc..30fd2c17fb1 100644 --- a/packages/g6/tests/unit/behaviors/drag-canvas-spec.ts +++ b/packages/g6/tests/unit/behaviors/drag-canvas-spec.ts @@ -59,16 +59,12 @@ describe('drag-canvas behavior', () => { client: { x: 200, y: 50 }, }); expect(graph.getItemVisible('edge1')).toBe(false); - expect( - graph.transientCanvas.getRoot().childNodes[1].childNodes.length, - ).toBe(2); + expect(graph.transientCanvas.getRoot().childNodes[1].childNodes.length).toBe(2); graph.emit('pointerup', { client: { x: 200, y: 50 }, }); expect(graph.getItemVisible('edge1')).toBe(true); - expect( - graph.transientCanvas.getRoot().childNodes[1].childNodes.length, - ).toBe(0); + expect(graph.transientCanvas.getRoot().childNodes[1].childNodes.length).toBe(0); graph.emit('pointerdown', { client: { x: 100, y: 50 }, @@ -80,9 +76,7 @@ describe('drag-canvas behavior', () => { shiftKey: true, }); expect(graph.getItemVisible('edge1')).toBe(false); - expect( - graph.transientCanvas.getRoot().childNodes[1].childNodes.length, - ).toBe(2); + expect(graph.transientCanvas.getRoot().childNodes[1].childNodes.length).toBe(2); // times === 3, out of view failed graph.emit('pointermove', { client: { x: 100, y: 550 }, @@ -91,9 +85,7 @@ describe('drag-canvas behavior', () => { client: { x: 200, y: 50 }, }); expect(graph.getItemVisible('edge1')).toBe(true); - expect( - graph.transientCanvas.getRoot().childNodes[1].childNodes.length, - ).toBe(0); + expect(graph.transientCanvas.getRoot().childNodes[1].childNodes.length).toBe(0); graph.destroy(); done(); @@ -214,9 +206,7 @@ describe('drag-canvas behavior', () => { client: { x: 200, y: 150 }, }); expect(graph.getItemVisible('edge1')).toBe(false); - expect( - graph.transientCanvas.getRoot().childNodes[1].childNodes.length, - ).toBe(2); + expect(graph.transientCanvas.getRoot().childNodes[1].childNodes.length).toBe(2); graph.emit('pointerup', { client: { x: 200, y: 50 }, }); @@ -263,9 +253,7 @@ describe('drag-canvas behavior', () => { client: { x: 200, y: 150 }, }); expect(graph.getItemVisible('edge1')).toBe(true); - expect( - graph.transientCanvas.getRoot().childNodes[1].childNodes.length, - ).toBe(0); + expect(graph.transientCanvas.getRoot().childNodes[1].childNodes.length).toBe(0); graph.emit('pointerup', { client: { x: 200, y: 50 }, }); diff --git a/packages/g6/tests/unit/behaviors/lasso-select-spec.ts b/packages/g6/tests/unit/behaviors/lasso-select-spec.ts index 263be6ff9b3..b306012daa5 100644 --- a/packages/g6/tests/unit/behaviors/lasso-select-spec.ts +++ b/packages/g6/tests/unit/behaviors/lasso-select-spec.ts @@ -1346,15 +1346,9 @@ describe('lasso-select behavior with brushStyle', () => { }); // edge group + node group + brush expect(graph.transientCanvas.getRoot().childNodes.length).toBe(3); - expect(graph.transientCanvas.getRoot().childNodes[2].config.id).toBe( - 'g6-lasso-select-brush-shape', - ); - expect(graph.transientCanvas.getRoot().childNodes[2].style.fill).toBe( - '#f00', - ); - expect( - graph.transientCanvas.getRoot().childNodes[2].style.fillOpacity, - ).toBe(0.5); + expect(graph.transientCanvas.getRoot().childNodes[2].config.id).toBe('g6-lasso-select-brush-shape'); + expect(graph.transientCanvas.getRoot().childNodes[2].style.fill).toBe('#f00'); + expect(graph.transientCanvas.getRoot().childNodes[2].style.fillOpacity).toBe(0.5); graph.emit('canvas:pointerup', { canvas: { x: 200, y: 150 }, shiftKey: true, diff --git a/packages/g6/tests/unit/behaviors/zoom-canvas-spec.ts b/packages/g6/tests/unit/behaviors/zoom-canvas-spec.ts index bcf45303f58..000ddaf05d8 100644 --- a/packages/g6/tests/unit/behaviors/zoom-canvas-spec.ts +++ b/packages/g6/tests/unit/behaviors/zoom-canvas-spec.ts @@ -37,9 +37,7 @@ describe('zoom-canvas behavior', () => { }); graph.on('afterlayout', (e) => { - expect( - graph.transientCanvas.getRoot().childNodes[1].childNodes.length, - ).toBe(0); + expect(graph.transientCanvas.getRoot().childNodes[1].childNodes.length).toBe(0); // times === 0; graph.emit('wheel', { canvas: { x: 100, y: 50 }, @@ -49,9 +47,7 @@ describe('zoom-canvas behavior', () => { expect(graph.getItemVisible('edge1')).toBe(false); expect(graph.getItemVisible('node1')).toBe(false); expect(graph.getItemVisible('node2')).toBe(false); - expect( - graph.transientCanvas.getRoot().childNodes[1].childNodes.length, - ).toBe(2); + expect(graph.transientCanvas.getRoot().childNodes[1].childNodes.length).toBe(2); // times === 1; graph.emit('wheel', { @@ -64,9 +60,7 @@ describe('zoom-canvas behavior', () => { expect(graph.getItemVisible('edge1')).toBe(true); expect(graph.getItemVisible('node1')).toBe(true); expect(graph.getItemVisible('node2')).toBe(true); - expect( - graph.transientCanvas.getRoot().childNodes[1].childNodes.length, - ).toBe(0); + expect(graph.transientCanvas.getRoot().childNodes[1].childNodes.length).toBe(0); // hide item first and wheel graph.hideItem('edge1'); diff --git a/packages/g6/tests/unit/click-select-spec.ts b/packages/g6/tests/unit/click-select-spec.ts index 30aea7e92ce..261c780fe86 100644 --- a/packages/g6/tests/unit/click-select-spec.ts +++ b/packages/g6/tests/unit/click-select-spec.ts @@ -1,6 +1,4 @@ import G6 from '../../src/index'; -import { Behavior } from '../../src/types/behavior'; -import { extend } from '../../src/util/extend'; const container = document.createElement('div'); document.querySelector('body').appendChild(container); diff --git a/packages/g6/tests/unit/data-spec.ts b/packages/g6/tests/unit/data-spec.ts index 68bc31b843d..e1ea311152a 100644 --- a/packages/g6/tests/unit/data-spec.ts +++ b/packages/g6/tests/unit/data-spec.ts @@ -54,9 +54,7 @@ describe('data', () => { }, }; const node1InnerData = graph.getNodeData('node1'); - expect(JSON.stringify(newNode1UserData)).toBe( - JSON.stringify(node1InnerData), - ); + expect(JSON.stringify(newNode1UserData)).toBe(JSON.stringify(node1InnerData)); // === update edge data === const edge2UpdateUserData = { @@ -77,13 +75,10 @@ describe('data', () => { }, }; const edge2InnerData = graph.getEdgeData('edge2'); - expect(JSON.stringify(newEdge2UserData)).toBe( - JSON.stringify(edge2InnerData), + expect(JSON.stringify(newEdge2UserData)).toBe(JSON.stringify(edge2InnerData)); + expect(graph.itemController.itemMap.get('edge2').shapeMap['keyShape'].attributes.lineWidth).toBe( + edge2UpdateUserData.data.keyShape.lineWidth, ); - expect( - graph.itemController.itemMap.get('edge2').shapeMap['keyShape'].attributes - .lineWidth, - ).toBe(edge2UpdateUserData.data.keyShape.lineWidth); // === update edge source === const edge1UpdateUserData = { @@ -92,17 +87,9 @@ describe('data', () => { }; graph.updateData('edge', edge1UpdateUserData); const newSourceData = graph.getNodeData('node3'); - expect( - graph.itemController.itemMap.get('edge1').shapeMap['keyShape'].attributes - .x1, - ).toBe(newSourceData.data.x); - expect( - graph.itemController.itemMap.get('edge1').shapeMap['keyShape'].attributes - .y1, - ).toBe(newSourceData.data.y); - expect(graph.itemController.itemMap.get('edge1').sourceItem).toBe( - graph.itemController.itemMap.get('node3'), - ); + expect(graph.itemController.itemMap.get('edge1').shapeMap['keyShape'].attributes.x1).toBe(newSourceData.data.x); + expect(graph.itemController.itemMap.get('edge1').shapeMap['keyShape'].attributes.y1).toBe(newSourceData.data.y); + expect(graph.itemController.itemMap.get('edge1').sourceItem).toBe(graph.itemController.itemMap.get('node3')); // === update edge source, target, and data in the same time === const edge1UpdateUserData2 = { @@ -123,9 +110,7 @@ describe('data', () => { expect(edgeItem.shapeMap['keyShape'].attributes.y1).toBe(sourceData.data.y); expect(edgeItem.shapeMap['keyShape'].attributes.x2).toBe(targetData.data.x); expect(edgeItem.shapeMap['keyShape'].attributes.y2).toBe(targetData.data.y); - expect(edgeItem.shapeMap['keyShape'].attributes.stroke).toBe( - edge1UpdateUserData2.data.keyShape.stroke, - ); + expect(edgeItem.shapeMap['keyShape'].attributes.stroke).toBe(edge1UpdateUserData2.data.keyShape.stroke); // === update nodes === graph.updateData('node', [ @@ -176,12 +161,8 @@ describe('data', () => { const edge1Item = graph.itemController.itemMap.get('edge1'); const edge2Item = graph.itemController.itemMap.get('edge2'); expect(edge1Item.shapeMap['keyShape'].attributes.stroke).toBe('#0f0'); - expect(edge1Item.sourceItem).toBe( - graph.itemController.itemMap.get('node2'), - ); - expect( - JSON.stringify(edge2Item.shapeMap['keyShape'].attributes.lineDash), - ).toBe('[5,5]'); + expect(edge1Item.sourceItem).toBe(graph.itemController.itemMap.get('node2')); + expect(JSON.stringify(edge2Item.shapeMap['keyShape'].attributes.lineDash)).toBe('[5,5]'); }); it('addData', () => { graph.addData('node', { diff --git a/packages/g6/tests/unit/drag-node-spec.ts b/packages/g6/tests/unit/drag-node-spec.ts index f898080a753..a46ff0bb5ce 100644 --- a/packages/g6/tests/unit/drag-node-spec.ts +++ b/packages/g6/tests/unit/drag-node-spec.ts @@ -1,8 +1,6 @@ import G6 from '../../src/index'; import { DragNodeOptions } from '../../src/stdlib/behavior/drag-node'; import { IGraph } from '../../src/types'; -import { Behavior } from '../../src/types/behavior'; -import { extend } from '../../src/util/extend'; const container = document.createElement('div'); document.querySelector('body').appendChild(container); @@ -110,13 +108,9 @@ describe('drag-node', () => { expect(graph.getItemVisible('edge1')).toBe(false); expect(graph.getItemVisible('edge2')).toBe(false); // @ts-ignore - expect( - graph.itemController.transientItemMap.get('node1').model.data.x, - ).toEqual(250); + expect(graph.itemController.transientItemMap.get('node1').model.data.x).toEqual(250); // @ts-ignore - expect( - graph.itemController.transientItemMap.get('node1').model.data.y, - ).toEqual(350); + expect(graph.itemController.transientItemMap.get('node1').model.data.y).toEqual(350); // Should update position when drag ends. graph.emit('pointerup', { client: { x: 250, y: 350 } }); @@ -177,9 +171,7 @@ describe('drag-node', () => { expect(graph.getItemVisible('node1')).toBe(true); expect(graph.getItemVisible('edge1')).toBe(true); // @ts-ignore - expect(graph.itemController.transientObjectMap).toHaveProperty( - 'g6-drag-node-delegate-shape', - ); + expect(graph.itemController.transientObjectMap).toHaveProperty('g6-drag-node-delegate-shape'); // Should update position when drag ends. graph.emit('pointerup', { client: { x: 250, y: 350 } }); diff --git a/packages/g6/tests/unit/edge-spec.ts b/packages/g6/tests/unit/edge-spec.ts index 721c751e8b1..97860630fb6 100644 --- a/packages/g6/tests/unit/edge-spec.ts +++ b/packages/g6/tests/unit/edge-spec.ts @@ -2,12 +2,7 @@ import { DisplayObject } from '@antv/g'; import { clone } from '@antv/util'; -import G6, { - EdgeDisplayModel, - Graph, - IGraph, - NodeDisplayModel, -} from '../../src/index'; +import G6, { EdgeDisplayModel, Graph, IGraph, NodeDisplayModel } from '../../src/index'; import { LineEdge } from '../../src/stdlib/item/edge'; import { CircleNode } from '../../src/stdlib/item/node'; import { NodeModelData, NodeShapeMap } from '../../src/types/node'; @@ -84,12 +79,8 @@ describe('edge item', () => { expect(edgeItem.shapeMap.labelShape.attributes.text).toBe('edge-label'); const fill = edgeItem.shapeMap.labelShape.attributes.fill; expect(fill).toBe('rgba(0,0,0,0.85)'); - expect(edgeItem.shapeMap.labelShape.attributes.transform).toBe( - 'rotate(45)', - ); - expect(edgeItem.shapeMap.labelBackgroundShape.attributes.transform).toBe( - 'rotate(45)', - ); + expect(edgeItem.shapeMap.labelShape.attributes.transform).toBe('rotate(45)'); + expect(edgeItem.shapeMap.labelBackgroundShape.attributes.transform).toBe('rotate(45)'); let labelBounds = edgeItem.shapeMap.labelShape.getGeometryBounds(); expect(edgeItem.shapeMap.labelBackgroundShape.attributes.width).toBe( labelBounds.max[0] - labelBounds.min[0] + padding[1] + padding[3], @@ -108,15 +99,13 @@ describe('edge item', () => { }, }); expect(edgeItem.shapeMap.labelShape.attributes.fill).toBe('#00f'); - expect( - edgeItem.shapeMap.labelShape.attributes.x - - edgeItem.shapeMap.labelBackgroundShape.attributes.x, - ).toBe(padding[3]); + expect(edgeItem.shapeMap.labelShape.attributes.x - edgeItem.shapeMap.labelBackgroundShape.attributes.x).toBe( + padding[3], + ); labelBounds = edgeItem.shapeMap.labelShape.getGeometryBounds(); const labelWidth = labelBounds.max[0] - labelBounds.min[0]; const labelHeight = labelBounds.max[1] - labelBounds.min[1]; - const labelBgBounds = - edgeItem.shapeMap.labelBackgroundShape.getGeometryBounds(); + const labelBgBounds = edgeItem.shapeMap.labelBackgroundShape.getGeometryBounds(); const labelBgWidth = labelBgBounds.max[0] - labelBgBounds.min[0]; const labelBgHeight = labelBgBounds.max[1] - labelBgBounds.min[1]; expect(labelBgWidth - labelWidth).toBe(padding[1] + padding[3]); @@ -154,19 +143,11 @@ describe('edge item', () => { const edgeItem = graph.itemController.itemMap.get('edge1'); let { labelShape, iconShape, labelBackgroundShape } = edgeItem.shapeMap; expect(iconShape.attributes.x + iconShape.attributes.width + 6).toBe( - labelBackgroundShape.getGeometryBounds().min[0] + - labelBackgroundShape.attributes.x, - ); - expect(iconShape.attributes.transform).toBe( - labelBackgroundShape.attributes.transform, + labelBackgroundShape.getGeometryBounds().min[0] + labelBackgroundShape.attributes.x, ); - expect( - Math.floor(iconShape.attributes.y + iconShape.attributes.height / 2), - ).toBeCloseTo( - Math.floor( - labelBackgroundShape.getGeometryBounds().center[1] + - labelBackgroundShape.attributes.y, - ), + expect(iconShape.attributes.transform).toBe(labelBackgroundShape.attributes.transform); + expect(Math.floor(iconShape.attributes.y + iconShape.attributes.height / 2)).toBeCloseTo( + Math.floor(labelBackgroundShape.getGeometryBounds().center[1] + labelBackgroundShape.attributes.y), 0.01, ); @@ -185,19 +166,11 @@ describe('edge item', () => { iconShape = edgeItem.shapeMap['iconShape']; labelBackgroundShape = edgeItem.shapeMap['labelBackgroundShape']; expect(iconShape.attributes.x + iconShape.attributes.fontSize + 6).toBe( - labelBackgroundShape.getGeometryBounds().min[0] + - labelBackgroundShape.attributes.x, + labelBackgroundShape.getGeometryBounds().min[0] + labelBackgroundShape.attributes.x, ); - expect(iconShape.attributes.transform).toBe( - labelBackgroundShape.attributes.transform, - ); - expect( - Math.floor(iconShape.attributes.y + iconShape.attributes.fontSize / 2), - ).toBeCloseTo( - Math.floor( - labelBackgroundShape.getGeometryBounds().center[1] + - labelBackgroundShape.attributes.y, - ), + expect(iconShape.attributes.transform).toBe(labelBackgroundShape.attributes.transform); + expect(Math.floor(iconShape.attributes.y + iconShape.attributes.fontSize / 2)).toBeCloseTo( + Math.floor(labelBackgroundShape.getGeometryBounds().center[1] + labelBackgroundShape.attributes.y), 0.01, ); @@ -214,15 +187,11 @@ describe('edge item', () => { iconShape = edgeItem.shapeMap['iconShape']; labelBackgroundShape = edgeItem.shapeMap['labelBackgroundShape']; expect(iconShape.attributes.x + iconShape.attributes.fontSize + 6).toBe( - labelBackgroundShape.getGeometryBounds().min[0] + - labelBackgroundShape.attributes.x, - ); - expect(iconShape.attributes.transform).toBe( - labelShape.attributes.transform, + labelBackgroundShape.getGeometryBounds().min[0] + labelBackgroundShape.attributes.x, ); + expect(iconShape.attributes.transform).toBe(labelShape.attributes.transform); expect(iconShape.attributes.y + iconShape.attributes.fontSize / 2).toBe( - labelBackgroundShape.getGeometryBounds().center[1] + - labelBackgroundShape.attributes.y, + labelBackgroundShape.getGeometryBounds().center[1] + labelBackgroundShape.attributes.y, ); graph.destroy(); done(); @@ -310,23 +279,18 @@ describe('edge mapper', () => { keyShape: { stroke: { fields: ['buStatus'], - formatter: (innerModel) => - innerModel.data.buStatus ? '#0f0' : '#f00', + formatter: (innerModel) => (innerModel.data.buStatus ? '#0f0' : '#f00'), }, lineWidth: 5, lineDash: { fields: ['buStatus', 'buType'], - formatter: (innerModel) => - innerModel.data.buStatus || innerModel.data.buType - ? undefined - : [5, 5], + formatter: (innerModel) => (innerModel.data.buStatus || innerModel.data.buType ? undefined : [5, 5]), }, }, labelShape: { text: { fields: ['buName', 'buType'], - formatter: (innerModel) => - `${innerModel.data.buName}-${innerModel.data.buType}`, + formatter: (innerModel) => `${innerModel.data.buName}-${innerModel.data.buType}`, }, }, }, @@ -341,9 +305,7 @@ describe('edge mapper', () => { let edge2 = graph.itemController.itemMap.get('edge2'); expect(edge2.shapeMap.keyShape.attributes.stroke).toBe('#f00'); expect(edge2.shapeMap.keyShape.attributes.lineWidth).toBe(5); - expect(JSON.stringify(edge2.shapeMap.keyShape.attributes.lineDash)).toBe( - '[5,5]', - ); + expect(JSON.stringify(edge2.shapeMap.keyShape.attributes.lineDash)).toBe('[5,5]'); expect(edge2.shapeMap.labelShape.attributes.text).toBe('edge-2-0'); // update user data @@ -421,96 +383,45 @@ describe('state', () => { graph.setItemState('edge1', 'selected', true); expect(graph.findIdByState('edge', 'selected').length).toBe(1); expect(graph.findIdByState('edge', 'selected')[0]).toBe('edge1'); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.stroke).toBe('#0f0'); graph.setItemState('edge1', 'selected', false); expect(graph.findIdByState('edge', 'selected').length).toBe(0); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(1); // set multiple edges state graph.setItemState(['edge1', 'edge2'], 'selected', true); expect(graph.findIdByState('edge', 'selected').length).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.stroke).toBe('#0f0'); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.stroke).toBe('#0f0'); graph.setItemState('edge1', 'selected', false); expect(graph.findIdByState('edge', 'selected').length).toBe(1); expect(graph.findIdByState('edge', 'selected')[0]).toBe('edge2'); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(1); graph.setItemState(['edge1', 'edge2'], 'selected', false); expect(graph.findIdByState('edge', 'selected').length).toBe(0); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.lineWidth).toBe(1); // // set multiple states graph.setItemState(['edge2', 'edge1'], ['selected', 'highlight'], true); expect(graph.findIdByState('edge', 'selected').length).toBe(2); expect(graph.findIdByState('edge', 'highlight').length).toBe(2); // should be merged styles from selected and highlight - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .stroke, - ).toBe('#00f'); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .opacity, - ).toBe(0.5); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .stroke, - ).toBe('#00f'); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .opacity, - ).toBe(0.5); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.stroke).toBe('#00f'); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.opacity).toBe(0.5); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.stroke).toBe('#00f'); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.opacity).toBe(0.5); // clear states graph.clearItemState(['edge1', 'edge2']); expect(graph.findIdByState('edge', 'selected').length).toBe(0); expect(graph.findIdByState('edge', 'highlight').length).toBe(0); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .opacity, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.opacity).toBe(1); graph.destroy(); done(); @@ -581,132 +492,52 @@ describe('state', () => { graph.setItemState('edge1', 'selected', true); expect(graph.findIdByState('edge', 'selected').length).toBe(1); expect(graph.findIdByState('edge', 'selected')[0]).toBe('edge1'); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); - expect( - JSON.stringify( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineDash, - ), - ).toBe('[2,2]'); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.stroke).toBe('#0f0'); + expect(JSON.stringify(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineDash)).toBe('[2,2]'); graph.setItemState('edge1', 'selected', false); expect(graph.findIdByState('edge', 'selected').length).toBe(0); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .stroke, - ).toBe('#f00'); - expect( - JSON.stringify( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineDash, - ), - ).toBe('[2,2]'); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.stroke).toBe('#f00'); + expect(JSON.stringify(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineDash)).toBe('[2,2]'); // set multiple edges state graph.setItemState(['edge1', 'edge2'], 'selected', true); expect(graph.findIdByState('edge', 'selected').length).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); - expect( - JSON.stringify( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineDash, - ), - ).toBe('[2,2]'); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); - expect( - JSON.stringify( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineDash, - ), - ).toBe('[2,2]'); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.stroke).toBe('#0f0'); + expect(JSON.stringify(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineDash)).toBe('[2,2]'); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.stroke).toBe('#0f0'); + expect(JSON.stringify(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineDash)).toBe('[2,2]'); graph.setItemState('edge1', 'selected', false); expect(graph.findIdByState('edge', 'selected').length).toBe(1); expect(graph.findIdByState('edge', 'selected')[0]).toBe('edge2'); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .stroke, - ).toBe('#f00'); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.stroke).toBe('#f00'); graph.setItemState(['edge1', 'edge2'], 'selected', false); expect(graph.findIdByState('edge', 'selected').length).toBe(0); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .stroke, - ).toBe('#f00'); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.lineWidth).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.stroke).toBe('#f00'); // set multiple states graph.setItemState(['edge2', 'edge1'], ['selected', 'highlight'], true); expect(graph.findIdByState('edge', 'selected').length).toBe(2); expect(graph.findIdByState('edge', 'highlight').length).toBe(2); // should be merged styles from selected and highlight - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .stroke, - ).toBe('#00f'); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .opacity, - ).toBe(0.5); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .stroke, - ).toBe('#00f'); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .opacity, - ).toBe(0.5); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.stroke).toBe('#00f'); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.opacity).toBe(0.5); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.stroke).toBe('#00f'); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.opacity).toBe(0.5); // clear states graph.clearItemState(['edge1', 'edge2']); expect(graph.findIdByState('edge', 'selected').length).toBe(0); expect(graph.findIdByState('edge', 'highlight').length).toBe(0); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .opacity, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.opacity).toBe(1); graph.destroy(); done(); @@ -729,11 +560,7 @@ describe('state', () => { diffData?: { oldData: NodeModelData; newData: NodeModelData }, ) { const { labelShape: propsLabelStyle } = model.data; - const labelStyle = Object.assign( - {}, - this.defaultStyles.labelShape, - propsLabelStyle, - ); + const labelStyle = Object.assign({}, this.defaultStyles.labelShape, propsLabelStyle); return this.upsertShape( 'text', 'labelShape', @@ -989,15 +816,13 @@ describe('cubic-edge unit test', () => { edgeItem = graph.itemController.itemMap.get('edge1'); expect(edgeItem.shapeMap.labelShape.attributes.fill).toBe('#00f'); - expect( - edgeItem.shapeMap.labelShape.attributes.x - - edgeItem.shapeMap.labelBackgroundShape.attributes.x, - ).toBe(padding[3]); + expect(edgeItem.shapeMap.labelShape.attributes.x - edgeItem.shapeMap.labelBackgroundShape.attributes.x).toBe( + padding[3], + ); labelBounds = edgeItem.shapeMap.labelShape.getGeometryBounds(); const labelWidth = labelBounds.max[0] - labelBounds.min[0]; const labelHeight = labelBounds.max[1] - labelBounds.min[1]; - const labelBgBounds = - edgeItem.shapeMap.labelBackgroundShape.getGeometryBounds(); + const labelBgBounds = edgeItem.shapeMap.labelBackgroundShape.getGeometryBounds(); const labelBgWidth = labelBgBounds.max[0] - labelBgBounds.min[0]; const labelBgHeight = labelBgBounds.max[1] - labelBgBounds.min[1]; expect(labelBgWidth - labelWidth).toBe(padding[1] + padding[3]); @@ -1040,21 +865,15 @@ describe('cubic-edge unit test', () => { const edgeItem = graph.itemController.itemMap.get('edge1'); let { labelShape, iconShape, labelBackgroundShape } = edgeItem.shapeMap; expect(iconShape.attributes.x + iconShape.attributes.width + 6).toBe( - labelBackgroundShape.getGeometryBounds().min[0] + - labelBackgroundShape.attributes.x, + labelBackgroundShape.getGeometryBounds().min[0] + labelBackgroundShape.attributes.x, ); // TODO: test transform // expect(iconShape.attributes.transform).toBe( // labelBackgroundShape.attributes.transform, // ); - expect( - Math.floor(iconShape.attributes.y + iconShape.attributes.height / 2), - ).toBeCloseTo( - Math.floor( - labelBackgroundShape.getGeometryBounds().center[1] + - labelBackgroundShape.attributes.y, - ), + expect(Math.floor(iconShape.attributes.y + iconShape.attributes.height / 2)).toBeCloseTo( + Math.floor(labelBackgroundShape.getGeometryBounds().center[1] + labelBackgroundShape.attributes.y), 0.01, ); @@ -1073,20 +892,14 @@ describe('cubic-edge unit test', () => { iconShape = edgeItem.shapeMap['iconShape']; labelBackgroundShape = edgeItem.shapeMap['labelBackgroundShape']; expect(iconShape.attributes.x + iconShape.attributes.fontSize + 6).toBe( - labelBackgroundShape.getGeometryBounds().min[0] + - labelBackgroundShape.attributes.x, + labelBackgroundShape.getGeometryBounds().min[0] + labelBackgroundShape.attributes.x, ); // TODO: test transform // expect(iconShape.attributes.transform).toBe( // labelBackgroundShape.attributes.transform, // ); - expect( - Math.floor(iconShape.attributes.y + iconShape.attributes.fontSize / 2), - ).toBeCloseTo( - Math.floor( - labelBackgroundShape.getGeometryBounds().center[1] + - labelBackgroundShape.attributes.y, - ), + expect(Math.floor(iconShape.attributes.y + iconShape.attributes.fontSize / 2)).toBeCloseTo( + Math.floor(labelBackgroundShape.getGeometryBounds().center[1] + labelBackgroundShape.attributes.y), 0.01, ); @@ -1103,8 +916,7 @@ describe('cubic-edge unit test', () => { iconShape = edgeItem.shapeMap['iconShape']; labelBackgroundShape = edgeItem.shapeMap['labelBackgroundShape']; expect(iconShape.attributes.x + iconShape.attributes.fontSize + 6).toBe( - labelBackgroundShape.getGeometryBounds().min[0] + - labelBackgroundShape.attributes.x, + labelBackgroundShape.getGeometryBounds().min[0] + labelBackgroundShape.attributes.x, ); // TODO: test transform @@ -1112,8 +924,7 @@ describe('cubic-edge unit test', () => { // labelShape.attributes.transform, // ); expect(iconShape.attributes.y + iconShape.attributes.fontSize / 2).toBe( - labelBackgroundShape.getGeometryBounds().center[1] + - labelBackgroundShape.attributes.y, + labelBackgroundShape.getGeometryBounds().center[1] + labelBackgroundShape.attributes.y, ); graph.destroy(); done(); @@ -1180,96 +991,45 @@ describe('cubic-edge unit test', () => { graph.setItemState('edge1', 'selected', true); expect(graph.findIdByState('edge', 'selected').length).toBe(1); expect(graph.findIdByState('edge', 'selected')[0]).toBe('edge1'); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.stroke).toBe('#0f0'); graph.setItemState('edge1', 'selected', false); expect(graph.findIdByState('edge', 'selected').length).toBe(0); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(1); // set multiple edges state graph.setItemState(['edge1', 'edge2'], 'selected', true); expect(graph.findIdByState('edge', 'selected').length).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.stroke).toBe('#0f0'); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.stroke).toBe('#0f0'); graph.setItemState('edge1', 'selected', false); expect(graph.findIdByState('edge', 'selected').length).toBe(1); expect(graph.findIdByState('edge', 'selected')[0]).toBe('edge2'); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(1); graph.setItemState(['edge1', 'edge2'], 'selected', false); expect(graph.findIdByState('edge', 'selected').length).toBe(0); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.lineWidth).toBe(1); // // set multiple states graph.setItemState(['edge2', 'edge1'], ['selected', 'highlight'], true); expect(graph.findIdByState('edge', 'selected').length).toBe(2); expect(graph.findIdByState('edge', 'highlight').length).toBe(2); // should be merged styles from selected and highlight - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .stroke, - ).toBe('#00f'); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .opacity, - ).toBe(0.5); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .stroke, - ).toBe('#00f'); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .opacity, - ).toBe(0.5); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.stroke).toBe('#00f'); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.opacity).toBe(0.5); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.stroke).toBe('#00f'); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.opacity).toBe(0.5); // clear states graph.clearItemState(['edge1', 'edge2']); expect(graph.findIdByState('edge', 'selected').length).toBe(0); expect(graph.findIdByState('edge', 'highlight').length).toBe(0); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .opacity, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.opacity).toBe(1); }); graph.destroy(); @@ -1339,96 +1099,45 @@ describe('cubic-horizontal-edge unit test', () => { graph.setItemState('edge1', 'selected', true); expect(graph.findIdByState('edge', 'selected').length).toBe(1); expect(graph.findIdByState('edge', 'selected')[0]).toBe('edge1'); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.stroke).toBe('#0f0'); graph.setItemState('edge1', 'selected', false); expect(graph.findIdByState('edge', 'selected').length).toBe(0); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(1); // set multiple edges state graph.setItemState(['edge1', 'edge2'], 'selected', true); expect(graph.findIdByState('edge', 'selected').length).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.stroke).toBe('#0f0'); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.stroke).toBe('#0f0'); graph.setItemState('edge1', 'selected', false); expect(graph.findIdByState('edge', 'selected').length).toBe(1); expect(graph.findIdByState('edge', 'selected')[0]).toBe('edge2'); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(1); graph.setItemState(['edge1', 'edge2'], 'selected', false); expect(graph.findIdByState('edge', 'selected').length).toBe(0); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.lineWidth).toBe(1); // // set multiple states graph.setItemState(['edge2', 'edge1'], ['selected', 'highlight'], true); expect(graph.findIdByState('edge', 'selected').length).toBe(2); expect(graph.findIdByState('edge', 'highlight').length).toBe(2); // should be merged styles from selected and highlight - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .stroke, - ).toBe('#00f'); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .opacity, - ).toBe(0.5); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .stroke, - ).toBe('#00f'); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .opacity, - ).toBe(0.5); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.stroke).toBe('#00f'); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.opacity).toBe(0.5); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.stroke).toBe('#00f'); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.opacity).toBe(0.5); // clear states graph.clearItemState(['edge1', 'edge2']); expect(graph.findIdByState('edge', 'selected').length).toBe(0); expect(graph.findIdByState('edge', 'highlight').length).toBe(0); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .opacity, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.opacity).toBe(1); }); graph.destroy(); @@ -1538,15 +1247,13 @@ describe('cubic-horizontal-edge unit test', () => { edgeItem = graph.itemController.itemMap.get('edge1'); expect(edgeItem.shapeMap.labelShape.attributes.fill).toBe('#00f'); - expect( - edgeItem.shapeMap.labelShape.attributes.x - - edgeItem.shapeMap.labelBackgroundShape.attributes.x, - ).toBe(padding[3]); + expect(edgeItem.shapeMap.labelShape.attributes.x - edgeItem.shapeMap.labelBackgroundShape.attributes.x).toBe( + padding[3], + ); labelBounds = edgeItem.shapeMap.labelShape.getGeometryBounds(); const labelWidth = labelBounds.max[0] - labelBounds.min[0]; const labelHeight = labelBounds.max[1] - labelBounds.min[1]; - const labelBgBounds = - edgeItem.shapeMap.labelBackgroundShape.getGeometryBounds(); + const labelBgBounds = edgeItem.shapeMap.labelBackgroundShape.getGeometryBounds(); const labelBgWidth = labelBgBounds.max[0] - labelBgBounds.min[0]; const labelBgHeight = labelBgBounds.max[1] - labelBgBounds.min[1]; expect(labelBgWidth - labelWidth).toBe(padding[1] + padding[3]); @@ -1589,21 +1296,15 @@ describe('cubic-horizontal-edge unit test', () => { const edgeItem = graph.itemController.itemMap.get('edge1'); let { labelShape, iconShape, labelBackgroundShape } = edgeItem.shapeMap; expect(iconShape.attributes.x + iconShape.attributes.width + 6).toBe( - labelBackgroundShape.getGeometryBounds().min[0] + - labelBackgroundShape.attributes.x, + labelBackgroundShape.getGeometryBounds().min[0] + labelBackgroundShape.attributes.x, ); // TODO: test transform // expect(iconShape.attributes.transform).toBe( // labelBackgroundShape.attributes.transform, // ); - expect( - Math.floor(iconShape.attributes.y + iconShape.attributes.height / 2), - ).toBeCloseTo( - Math.floor( - labelBackgroundShape.getGeometryBounds().center[1] + - labelBackgroundShape.attributes.y, - ), + expect(Math.floor(iconShape.attributes.y + iconShape.attributes.height / 2)).toBeCloseTo( + Math.floor(labelBackgroundShape.getGeometryBounds().center[1] + labelBackgroundShape.attributes.y), 0.01, ); @@ -1622,20 +1323,14 @@ describe('cubic-horizontal-edge unit test', () => { iconShape = edgeItem.shapeMap['iconShape']; labelBackgroundShape = edgeItem.shapeMap['labelBackgroundShape']; expect(iconShape.attributes.x + iconShape.attributes.fontSize + 6).toBe( - labelBackgroundShape.getGeometryBounds().min[0] + - labelBackgroundShape.attributes.x, + labelBackgroundShape.getGeometryBounds().min[0] + labelBackgroundShape.attributes.x, ); // TODO: test transform // expect(iconShape.attributes.transform).toBe( // labelBackgroundShape.attributes.transform, // ); - expect( - Math.floor(iconShape.attributes.y + iconShape.attributes.fontSize / 2), - ).toBeCloseTo( - Math.floor( - labelBackgroundShape.getGeometryBounds().center[1] + - labelBackgroundShape.attributes.y, - ), + expect(Math.floor(iconShape.attributes.y + iconShape.attributes.fontSize / 2)).toBeCloseTo( + Math.floor(labelBackgroundShape.getGeometryBounds().center[1] + labelBackgroundShape.attributes.y), 0.01, ); @@ -1652,16 +1347,14 @@ describe('cubic-horizontal-edge unit test', () => { iconShape = edgeItem.shapeMap['iconShape']; labelBackgroundShape = edgeItem.shapeMap['labelBackgroundShape']; expect(iconShape.attributes.x + iconShape.attributes.fontSize + 6).toBe( - labelBackgroundShape.getGeometryBounds().min[0] + - labelBackgroundShape.attributes.x, + labelBackgroundShape.getGeometryBounds().min[0] + labelBackgroundShape.attributes.x, ); // TODO: test transform // expect(iconShape.attributes.transform).toBe( // labelShape.attributes.transform, // ); expect(iconShape.attributes.y + iconShape.attributes.fontSize / 2).toBe( - labelBackgroundShape.getGeometryBounds().center[1] + - labelBackgroundShape.attributes.y, + labelBackgroundShape.getGeometryBounds().center[1] + labelBackgroundShape.attributes.y, ); graph.destroy(); done(); @@ -1727,96 +1420,45 @@ describe('cubic-horizontal-edge unit test', () => { graph.setItemState('edge1', 'selected', true); expect(graph.findIdByState('edge', 'selected').length).toBe(1); expect(graph.findIdByState('edge', 'selected')[0]).toBe('edge1'); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.stroke).toBe('#0f0'); graph.setItemState('edge1', 'selected', false); expect(graph.findIdByState('edge', 'selected').length).toBe(0); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(1); // set multiple edges state graph.setItemState(['edge1', 'edge2'], 'selected', true); expect(graph.findIdByState('edge', 'selected').length).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.stroke).toBe('#0f0'); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.stroke).toBe('#0f0'); graph.setItemState('edge1', 'selected', false); expect(graph.findIdByState('edge', 'selected').length).toBe(1); expect(graph.findIdByState('edge', 'selected')[0]).toBe('edge2'); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(1); graph.setItemState(['edge1', 'edge2'], 'selected', false); expect(graph.findIdByState('edge', 'selected').length).toBe(0); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.lineWidth).toBe(1); // // set multiple states graph.setItemState(['edge2', 'edge1'], ['selected', 'highlight'], true); expect(graph.findIdByState('edge', 'selected').length).toBe(2); expect(graph.findIdByState('edge', 'highlight').length).toBe(2); // should be merged styles from selected and highlight - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .stroke, - ).toBe('#00f'); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .opacity, - ).toBe(0.5); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .stroke, - ).toBe('#00f'); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .opacity, - ).toBe(0.5); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.stroke).toBe('#00f'); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.opacity).toBe(0.5); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.stroke).toBe('#00f'); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.opacity).toBe(0.5); // clear states graph.clearItemState(['edge1', 'edge2']); expect(graph.findIdByState('edge', 'selected').length).toBe(0); expect(graph.findIdByState('edge', 'highlight').length).toBe(0); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .opacity, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.opacity).toBe(1); }); graph.destroy(); @@ -1926,15 +1568,13 @@ describe('cubic-vertical-edge unit test', () => { edgeItem = graph.itemController.itemMap.get('edge1'); expect(edgeItem.shapeMap.labelShape.attributes.fill).toBe('#00f'); - expect( - edgeItem.shapeMap.labelShape.attributes.x - - edgeItem.shapeMap.labelBackgroundShape.attributes.x, - ).toBe(padding[3]); + expect(edgeItem.shapeMap.labelShape.attributes.x - edgeItem.shapeMap.labelBackgroundShape.attributes.x).toBe( + padding[3], + ); labelBounds = edgeItem.shapeMap.labelShape.getGeometryBounds(); const labelWidth = labelBounds.max[0] - labelBounds.min[0]; const labelHeight = labelBounds.max[1] - labelBounds.min[1]; - const labelBgBounds = - edgeItem.shapeMap.labelBackgroundShape.getGeometryBounds(); + const labelBgBounds = edgeItem.shapeMap.labelBackgroundShape.getGeometryBounds(); const labelBgWidth = labelBgBounds.max[0] - labelBgBounds.min[0]; const labelBgHeight = labelBgBounds.max[1] - labelBgBounds.min[1]; expect(labelBgWidth - labelWidth).toBe(padding[1] + padding[3]); @@ -1977,21 +1617,15 @@ describe('cubic-vertical-edge unit test', () => { const edgeItem = graph.itemController.itemMap.get('edge1'); let { labelShape, iconShape, labelBackgroundShape } = edgeItem.shapeMap; expect(iconShape.attributes.x + iconShape.attributes.width + 6).toBe( - labelBackgroundShape.getGeometryBounds().min[0] + - labelBackgroundShape.attributes.x, + labelBackgroundShape.getGeometryBounds().min[0] + labelBackgroundShape.attributes.x, ); // TODO: test transform // expect(iconShape.attributes.transform).toBe( // labelBackgroundShape.attributes.transform, // ); - expect( - Math.floor(iconShape.attributes.y + iconShape.attributes.height / 2), - ).toBeCloseTo( - Math.floor( - labelBackgroundShape.getGeometryBounds().center[1] + - labelBackgroundShape.attributes.y, - ), + expect(Math.floor(iconShape.attributes.y + iconShape.attributes.height / 2)).toBeCloseTo( + Math.floor(labelBackgroundShape.getGeometryBounds().center[1] + labelBackgroundShape.attributes.y), 0.01, ); @@ -2010,20 +1644,14 @@ describe('cubic-vertical-edge unit test', () => { iconShape = edgeItem.shapeMap['iconShape']; labelBackgroundShape = edgeItem.shapeMap['labelBackgroundShape']; expect(iconShape.attributes.x + iconShape.attributes.fontSize + 6).toBe( - labelBackgroundShape.getGeometryBounds().min[0] + - labelBackgroundShape.attributes.x, + labelBackgroundShape.getGeometryBounds().min[0] + labelBackgroundShape.attributes.x, ); // TODO: test transform // expect(iconShape.attributes.transform).toBe( // labelBackgroundShape.attributes.transform, // ); - expect( - Math.floor(iconShape.attributes.y + iconShape.attributes.fontSize / 2), - ).toBeCloseTo( - Math.floor( - labelBackgroundShape.getGeometryBounds().center[1] + - labelBackgroundShape.attributes.y, - ), + expect(Math.floor(iconShape.attributes.y + iconShape.attributes.fontSize / 2)).toBeCloseTo( + Math.floor(labelBackgroundShape.getGeometryBounds().center[1] + labelBackgroundShape.attributes.y), 0.01, ); @@ -2040,16 +1668,14 @@ describe('cubic-vertical-edge unit test', () => { iconShape = edgeItem.shapeMap['iconShape']; labelBackgroundShape = edgeItem.shapeMap['labelBackgroundShape']; expect(iconShape.attributes.x + iconShape.attributes.fontSize + 6).toBe( - labelBackgroundShape.getGeometryBounds().min[0] + - labelBackgroundShape.attributes.x, + labelBackgroundShape.getGeometryBounds().min[0] + labelBackgroundShape.attributes.x, ); // TODO: test transform // expect(iconShape.attributes.transform).toBe( // labelShape.attributes.transform, // ); expect(iconShape.attributes.y + iconShape.attributes.fontSize / 2).toBe( - labelBackgroundShape.getGeometryBounds().center[1] + - labelBackgroundShape.attributes.y, + labelBackgroundShape.getGeometryBounds().center[1] + labelBackgroundShape.attributes.y, ); graph.destroy(); done(); @@ -2115,96 +1741,45 @@ describe('cubic-vertical-edge unit test', () => { graph.setItemState('edge1', 'selected', true); expect(graph.findIdByState('edge', 'selected').length).toBe(1); expect(graph.findIdByState('edge', 'selected')[0]).toBe('edge1'); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.stroke).toBe('#0f0'); graph.setItemState('edge1', 'selected', false); expect(graph.findIdByState('edge', 'selected').length).toBe(0); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(1); // set multiple edges state graph.setItemState(['edge1', 'edge2'], 'selected', true); expect(graph.findIdByState('edge', 'selected').length).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.stroke).toBe('#0f0'); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.stroke).toBe('#0f0'); graph.setItemState('edge1', 'selected', false); expect(graph.findIdByState('edge', 'selected').length).toBe(1); expect(graph.findIdByState('edge', 'selected')[0]).toBe('edge2'); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(1); graph.setItemState(['edge1', 'edge2'], 'selected', false); expect(graph.findIdByState('edge', 'selected').length).toBe(0); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.lineWidth).toBe(1); // // set multiple states graph.setItemState(['edge2', 'edge1'], ['selected', 'highlight'], true); expect(graph.findIdByState('edge', 'selected').length).toBe(2); expect(graph.findIdByState('edge', 'highlight').length).toBe(2); // should be merged styles from selected and highlight - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .stroke, - ).toBe('#00f'); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .opacity, - ).toBe(0.5); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .stroke, - ).toBe('#00f'); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .opacity, - ).toBe(0.5); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.stroke).toBe('#00f'); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.opacity).toBe(0.5); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.stroke).toBe('#00f'); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.opacity).toBe(0.5); // clear states graph.clearItemState(['edge1', 'edge2']); expect(graph.findIdByState('edge', 'selected').length).toBe(0); expect(graph.findIdByState('edge', 'highlight').length).toBe(0); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .opacity, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.opacity).toBe(1); }); graph.destroy(); @@ -2314,15 +1889,13 @@ describe('cubic-vertical-edge unit test', () => { edgeItem = graph.itemController.itemMap.get('edge1'); expect(edgeItem.shapeMap.labelShape.attributes.fill).toBe('#00f'); - expect( - edgeItem.shapeMap.labelShape.attributes.x - - edgeItem.shapeMap.labelBackgroundShape.attributes.x, - ).toBe(padding[3]); + expect(edgeItem.shapeMap.labelShape.attributes.x - edgeItem.shapeMap.labelBackgroundShape.attributes.x).toBe( + padding[3], + ); labelBounds = edgeItem.shapeMap.labelShape.getGeometryBounds(); const labelWidth = labelBounds.max[0] - labelBounds.min[0]; const labelHeight = labelBounds.max[1] - labelBounds.min[1]; - const labelBgBounds = - edgeItem.shapeMap.labelBackgroundShape.getGeometryBounds(); + const labelBgBounds = edgeItem.shapeMap.labelBackgroundShape.getGeometryBounds(); const labelBgWidth = labelBgBounds.max[0] - labelBgBounds.min[0]; const labelBgHeight = labelBgBounds.max[1] - labelBgBounds.min[1]; expect(labelBgWidth - labelWidth).toBe(padding[1] + padding[3]); @@ -2365,21 +1938,15 @@ describe('cubic-vertical-edge unit test', () => { const edgeItem = graph.itemController.itemMap.get('edge1'); let { labelShape, iconShape, labelBackgroundShape } = edgeItem.shapeMap; expect(iconShape.attributes.x + iconShape.attributes.width + 6).toBe( - labelBackgroundShape.getGeometryBounds().min[0] + - labelBackgroundShape.attributes.x, + labelBackgroundShape.getGeometryBounds().min[0] + labelBackgroundShape.attributes.x, ); // TODO: test transform // expect(iconShape.attributes.transform).toBe( // labelBackgroundShape.attributes.transform, // ); - expect( - Math.floor(iconShape.attributes.y + iconShape.attributes.height / 2), - ).toBeCloseTo( - Math.floor( - labelBackgroundShape.getGeometryBounds().center[1] + - labelBackgroundShape.attributes.y, - ), + expect(Math.floor(iconShape.attributes.y + iconShape.attributes.height / 2)).toBeCloseTo( + Math.floor(labelBackgroundShape.getGeometryBounds().center[1] + labelBackgroundShape.attributes.y), 0.01, ); @@ -2398,20 +1965,14 @@ describe('cubic-vertical-edge unit test', () => { iconShape = edgeItem.shapeMap['iconShape']; labelBackgroundShape = edgeItem.shapeMap['labelBackgroundShape']; expect(iconShape.attributes.x + iconShape.attributes.fontSize + 6).toBe( - labelBackgroundShape.getGeometryBounds().min[0] + - labelBackgroundShape.attributes.x, + labelBackgroundShape.getGeometryBounds().min[0] + labelBackgroundShape.attributes.x, ); // TODO: test transform // expect(iconShape.attributes.transform).toBe( // labelBackgroundShape.attributes.transform, // ); - expect( - Math.floor(iconShape.attributes.y + iconShape.attributes.fontSize / 2), - ).toBeCloseTo( - Math.floor( - labelBackgroundShape.getGeometryBounds().center[1] + - labelBackgroundShape.attributes.y, - ), + expect(Math.floor(iconShape.attributes.y + iconShape.attributes.fontSize / 2)).toBeCloseTo( + Math.floor(labelBackgroundShape.getGeometryBounds().center[1] + labelBackgroundShape.attributes.y), 0.01, ); @@ -2428,16 +1989,14 @@ describe('cubic-vertical-edge unit test', () => { iconShape = edgeItem.shapeMap['iconShape']; labelBackgroundShape = edgeItem.shapeMap['labelBackgroundShape']; expect(iconShape.attributes.x + iconShape.attributes.fontSize + 6).toBe( - labelBackgroundShape.getGeometryBounds().min[0] + - labelBackgroundShape.attributes.x, + labelBackgroundShape.getGeometryBounds().min[0] + labelBackgroundShape.attributes.x, ); // TODO: test transform // expect(iconShape.attributes.transform).toBe( // labelShape.attributes.transform, // ); expect(iconShape.attributes.y + iconShape.attributes.fontSize / 2).toBe( - labelBackgroundShape.getGeometryBounds().center[1] + - labelBackgroundShape.attributes.y, + labelBackgroundShape.getGeometryBounds().center[1] + labelBackgroundShape.attributes.y, ); graph.destroy(); done(); @@ -2503,96 +2062,45 @@ describe('cubic-vertical-edge unit test', () => { graph.setItemState('edge1', 'selected', true); expect(graph.findIdByState('edge', 'selected').length).toBe(1); expect(graph.findIdByState('edge', 'selected')[0]).toBe('edge1'); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.stroke).toBe('#0f0'); graph.setItemState('edge1', 'selected', false); expect(graph.findIdByState('edge', 'selected').length).toBe(0); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(1); // set multiple edges state graph.setItemState(['edge1', 'edge2'], 'selected', true); expect(graph.findIdByState('edge', 'selected').length).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.stroke).toBe('#0f0'); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.stroke).toBe('#0f0'); graph.setItemState('edge1', 'selected', false); expect(graph.findIdByState('edge', 'selected').length).toBe(1); expect(graph.findIdByState('edge', 'selected')[0]).toBe('edge2'); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(1); graph.setItemState(['edge1', 'edge2'], 'selected', false); expect(graph.findIdByState('edge', 'selected').length).toBe(0); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.lineWidth).toBe(1); // // set multiple states graph.setItemState(['edge2', 'edge1'], ['selected', 'highlight'], true); expect(graph.findIdByState('edge', 'selected').length).toBe(2); expect(graph.findIdByState('edge', 'highlight').length).toBe(2); // should be merged styles from selected and highlight - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .stroke, - ).toBe('#00f'); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .opacity, - ).toBe(0.5); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .stroke, - ).toBe('#00f'); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .opacity, - ).toBe(0.5); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.stroke).toBe('#00f'); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.opacity).toBe(0.5); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.stroke).toBe('#00f'); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.opacity).toBe(0.5); // clear states graph.clearItemState(['edge1', 'edge2']); expect(graph.findIdByState('edge', 'selected').length).toBe(0); expect(graph.findIdByState('edge', 'highlight').length).toBe(0); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .opacity, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.opacity).toBe(1); }); graph.destroy(); diff --git a/packages/g6/tests/unit/ellipse-spec.ts b/packages/g6/tests/unit/ellipse-spec.ts index 64a70b38fea..59e6306861e 100644 --- a/packages/g6/tests/unit/ellipse-spec.ts +++ b/packages/g6/tests/unit/ellipse-spec.ts @@ -174,16 +174,12 @@ describe('node mapper', () => { keyShape: { fill: { fields: ['buStatus'], - formatter: (innerModel) => - innerModel.data.buStatus ? '#0f0' : '#f00', + formatter: (innerModel) => (innerModel.data.buStatus ? '#0f0' : '#f00'), }, lineWidth: 5, stroke: { fields: ['buStatus', 'buType'], - formatter: (innerModel) => - innerModel.data.buStatus || innerModel.data.buType - ? '#fff' - : '#000', + formatter: (innerModel) => (innerModel.data.buStatus || innerModel.data.buType ? '#fff' : '#000'), }, }, labelShape: {}, @@ -276,105 +272,48 @@ describe('state', () => { graph.setItemState('node1', 'selected', true); expect(graph.findIdByState('node', 'selected').length).toBe(1); expect(graph.findIdByState('node', 'selected')[0]).toBe('node1'); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.stroke).toBe('#0f0'); graph.setItemState('node1', 'selected', false); expect(graph.findIdByState('node', 'selected').length).toBe(0); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .lineWidth, - ).toBe(0); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.lineWidth).toBe(0); // set multiple nodes state graph.setItemState(['node1', 'node2'], 'selected', true); expect(graph.findIdByState('node', 'selected').length).toBe(2); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); - expect( - graph.itemController.itemMap.get('node2').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('node2').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.stroke).toBe('#0f0'); + expect(graph.itemController.itemMap.get('node2').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('node2').shapeMap.keyShape.style.stroke).toBe('#0f0'); graph.setItemState('node1', 'selected', false); expect(graph.findIdByState('node', 'selected').length).toBe(1); expect(graph.findIdByState('node', 'selected')[0]).toBe('node2'); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .lineWidth, - ).toBe(0); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.lineWidth).toBe(0); graph.setItemState(['node1', 'node2'], 'selected', false); expect(graph.findIdByState('node', 'selected').length).toBe(0); - expect( - graph.itemController.itemMap.get('node2').shapeMap.keyShape.style - .lineWidth, - ).toBe(0); + expect(graph.itemController.itemMap.get('node2').shapeMap.keyShape.style.lineWidth).toBe(0); // set multiple states graph.setItemState(['node1', 'node2'], ['selected', 'highlight'], true); expect(graph.findIdByState('node', 'selected').length).toBe(2); expect(graph.findIdByState('node', 'highlight').length).toBe(2); // should be merged styles from selected and highlight - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .lineWidth, - ).toBe(3); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .stroke, - ).toBe('#00f'); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.r, - ).toBe(30); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .opacity, - ).toBe(0.5); - expect( - graph.itemController.itemMap.get('node2').shapeMap.keyShape.style - .lineWidth, - ).toBe(3); - expect( - graph.itemController.itemMap.get('node2').shapeMap.keyShape.style - .stroke, - ).toBe('#00f'); - expect( - graph.itemController.itemMap.get('node2').shapeMap.keyShape.style.r, - ).toBe(30); - expect( - graph.itemController.itemMap.get('node2').shapeMap.keyShape.style - .opacity, - ).toBe(0.5); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.lineWidth).toBe(3); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.stroke).toBe('#00f'); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.r).toBe(30); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.opacity).toBe(0.5); + expect(graph.itemController.itemMap.get('node2').shapeMap.keyShape.style.lineWidth).toBe(3); + expect(graph.itemController.itemMap.get('node2').shapeMap.keyShape.style.stroke).toBe('#00f'); + expect(graph.itemController.itemMap.get('node2').shapeMap.keyShape.style.r).toBe(30); + expect(graph.itemController.itemMap.get('node2').shapeMap.keyShape.style.opacity).toBe(0.5); // clear states graph.clearItemState(['node1', 'node2']); expect(graph.findIdByState('node', 'selected').length).toBe(0); expect(graph.findIdByState('node', 'highlight').length).toBe(0); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.r, - ).toBe(16); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .lineWidth, - ).toBe(0); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .opacity, - ).toBe(1); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.r).toBe(16); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.lineWidth).toBe(0); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.opacity).toBe(1); graph.destroy(); done(); diff --git a/packages/g6/tests/unit/hexagon-spec.ts b/packages/g6/tests/unit/hexagon-spec.ts index 4ca60e1cc32..4ee42718912 100644 --- a/packages/g6/tests/unit/hexagon-spec.ts +++ b/packages/g6/tests/unit/hexagon-spec.ts @@ -171,16 +171,12 @@ describe('node mapper', () => { keyShape: { fill: { fields: ['buStatus'], - formatter: (innerModel) => - innerModel.data.buStatus ? '#0f0' : '#f00', + formatter: (innerModel) => (innerModel.data.buStatus ? '#0f0' : '#f00'), }, lineWidth: 5, stroke: { fields: ['buStatus', 'buType'], - formatter: (innerModel) => - innerModel.data.buStatus || innerModel.data.buType - ? '#fff' - : '#000', + formatter: (innerModel) => (innerModel.data.buStatus || innerModel.data.buType ? '#fff' : '#000'), }, }, labelShape: {}, @@ -272,88 +268,48 @@ describe('state', () => { graph.setItemState('node1', 'selected', true); expect(graph.findIdByState('node', 'selected').length).toBe(1); expect(graph.findIdByState('node', 'selected')[0]).toBe('node1'); - expect( - graph.itemController.itemMap['node1'].shapeMap.keyShape.style.lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap['node1'].shapeMap.keyShape.style.stroke, - ).toBe('#0f0'); + expect(graph.itemController.itemMap['node1'].shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap['node1'].shapeMap.keyShape.style.stroke).toBe('#0f0'); graph.setItemState('node1', 'selected', false); expect(graph.findIdByState('node', 'selected').length).toBe(0); - expect( - graph.itemController.itemMap['node1'].shapeMap.keyShape.style.lineWidth, - ).toBe(0); + expect(graph.itemController.itemMap['node1'].shapeMap.keyShape.style.lineWidth).toBe(0); // set multiple nodes state graph.setItemState(['node1', 'node2'], 'selected', true); expect(graph.findIdByState('node', 'selected').length).toBe(2); - expect( - graph.itemController.itemMap['node1'].shapeMap.keyShape.style.lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap['node1'].shapeMap.keyShape.style.stroke, - ).toBe('#0f0'); - expect( - graph.itemController.itemMap['node2'].shapeMap.keyShape.style.lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap['node2'].shapeMap.keyShape.style.stroke, - ).toBe('#0f0'); + expect(graph.itemController.itemMap['node1'].shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap['node1'].shapeMap.keyShape.style.stroke).toBe('#0f0'); + expect(graph.itemController.itemMap['node2'].shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap['node2'].shapeMap.keyShape.style.stroke).toBe('#0f0'); graph.setItemState('node1', 'selected', false); expect(graph.findIdByState('node', 'selected').length).toBe(1); expect(graph.findIdByState('node', 'selected')[0]).toBe('node2'); - expect( - graph.itemController.itemMap['node1'].shapeMap.keyShape.style.lineWidth, - ).toBe(0); + expect(graph.itemController.itemMap['node1'].shapeMap.keyShape.style.lineWidth).toBe(0); graph.setItemState(['node1', 'node2'], 'selected', false); expect(graph.findIdByState('node', 'selected').length).toBe(0); - expect( - graph.itemController.itemMap['node2'].shapeMap.keyShape.style.lineWidth, - ).toBe(0); + expect(graph.itemController.itemMap['node2'].shapeMap.keyShape.style.lineWidth).toBe(0); // set multiple states graph.setItemState(['node1', 'node2'], ['selected', 'highlight'], true); expect(graph.findIdByState('node', 'selected').length).toBe(2); expect(graph.findIdByState('node', 'highlight').length).toBe(2); // should be merged styles from selected and highlight - expect( - graph.itemController.itemMap['node1'].shapeMap.keyShape.style.lineWidth, - ).toBe(3); - expect( - graph.itemController.itemMap['node1'].shapeMap.keyShape.style.stroke, - ).toBe('#00f'); - expect( - graph.itemController.itemMap['node1'].shapeMap.keyShape.style.r, - ).toBe(30); - expect( - graph.itemController.itemMap['node1'].shapeMap.keyShape.style.opacity, - ).toBe(0.5); - expect( - graph.itemController.itemMap['node2'].shapeMap.keyShape.style.lineWidth, - ).toBe(3); - expect( - graph.itemController.itemMap['node2'].shapeMap.keyShape.style.stroke, - ).toBe('#00f'); - expect( - graph.itemController.itemMap['node2'].shapeMap.keyShape.style.r, - ).toBe(30); - expect( - graph.itemController.itemMap['node2'].shapeMap.keyShape.style.opacity, - ).toBe(0.5); + expect(graph.itemController.itemMap['node1'].shapeMap.keyShape.style.lineWidth).toBe(3); + expect(graph.itemController.itemMap['node1'].shapeMap.keyShape.style.stroke).toBe('#00f'); + expect(graph.itemController.itemMap['node1'].shapeMap.keyShape.style.r).toBe(30); + expect(graph.itemController.itemMap['node1'].shapeMap.keyShape.style.opacity).toBe(0.5); + expect(graph.itemController.itemMap['node2'].shapeMap.keyShape.style.lineWidth).toBe(3); + expect(graph.itemController.itemMap['node2'].shapeMap.keyShape.style.stroke).toBe('#00f'); + expect(graph.itemController.itemMap['node2'].shapeMap.keyShape.style.r).toBe(30); + expect(graph.itemController.itemMap['node2'].shapeMap.keyShape.style.opacity).toBe(0.5); // clear states graph.clearItemState(['node1', 'node2']); expect(graph.findIdByState('node', 'selected').length).toBe(0); expect(graph.findIdByState('node', 'highlight').length).toBe(0); - expect( - graph.itemController.itemMap['node1'].shapeMap.keyShape.style.r, - ).toBe(20); - expect( - graph.itemController.itemMap['node1'].shapeMap.keyShape.style.lineWidth, - ).toBe(0); - expect( - graph.itemController.itemMap['node1'].shapeMap.keyShape.style.opacity, - ).toBe(1); + expect(graph.itemController.itemMap['node1'].shapeMap.keyShape.style.r).toBe(20); + expect(graph.itemController.itemMap['node1'].shapeMap.keyShape.style.lineWidth).toBe(0); + expect(graph.itemController.itemMap['node1'].shapeMap.keyShape.style.opacity).toBe(1); graph.destroy(); done(); diff --git a/packages/g6/tests/unit/item-animate-spec.ts b/packages/g6/tests/unit/item-animate-spec.ts index cbaa94eaf39..cdc538f7e0f 100644 --- a/packages/g6/tests/unit/item-animate-spec.ts +++ b/packages/g6/tests/unit/item-animate-spec.ts @@ -64,11 +64,7 @@ class CustomNode extends CircleNode { model, ); const { labelShape: propsLabelStyle } = model.data; - const labelStyle = Object.assign( - {}, - this.defaultStyles.labelShape, - propsLabelStyle, - ); + const labelStyle = Object.assign({}, this.defaultStyles.labelShape, propsLabelStyle); const labelShape = upsertShape( 'text', 'labelShape', @@ -534,14 +530,10 @@ describe('node update animations', () => { setTimeout(() => { graph.setItemState('node1', 'selected', true); const node1 = graph.itemController.itemMap.get('node1'); - expect(node1.shapeMap.keyShape.attributes.fill).toBe( - 'rgb(239, 244, 255)', - ); + expect(node1.shapeMap.keyShape.attributes.fill).toBe('rgb(239, 244, 255)'); expect(node1.shapeMap.keyShape.attributes.lineWidth).toBe(1); setTimeout(() => { - expect(node1.shapeMap.keyShape.attributes.fill).not.toBe( - 'rgb(239, 244, 255)', - ); + expect(node1.shapeMap.keyShape.attributes.fill).not.toBe('rgb(239, 244, 255)'); expect(node1.shapeMap.keyShape.attributes.lineWidth > 1).toBe(true); graph.destroy(); done(); @@ -597,19 +589,13 @@ describe('node update animations', () => { graph.setItemState('node1', 'selected', true); const node1 = graph.itemController.itemMap.get('node1'); expect(node1.shapeMap.keyShape.attributes.lineWidth).toBe(1); - expect(node1.shapeMap.keyShape.attributes.fill).toBe( - 'rgb(239, 244, 255)', - ); + expect(node1.shapeMap.keyShape.attributes.fill).toBe('rgb(239, 244, 255)'); setTimeout(() => { expect(node1.shapeMap.keyShape.attributes.lineWidth > 1).toBe(true); - expect(node1.shapeMap.keyShape.attributes.fill).toBe( - 'rgb(239, 244, 255)', - ); + expect(node1.shapeMap.keyShape.attributes.fill).toBe('rgb(239, 244, 255)'); setTimeout(() => { expect(node1.shapeMap.keyShape.attributes.lineWidth > 1).toBe(true); - expect(node1.shapeMap.keyShape.attributes.fill).toBe( - 'rgba(255,0,0,1)', - ); + expect(node1.shapeMap.keyShape.attributes.fill).toBe('rgba(255,0,0,1)'); graph.destroy(); done(); }, 1000); @@ -722,12 +708,8 @@ describe('edge update animations', () => { setTimeout(() => { expect(edge1.shapeMap.keyShape.attributes.stroke).not.toBe('#000'); setTimeout(() => { - expect(edge1.shapeMap.keyShape.attributes.stroke).not.toBe( - '#000', - ); - expect(edge1.shapeMap.keyShape.attributes.lineWidth > 1).toBe( - true, - ); + expect(edge1.shapeMap.keyShape.attributes.stroke).not.toBe('#000'); + expect(edge1.shapeMap.keyShape.attributes.lineWidth > 1).toBe(true); graph.destroy(); done(); }, 1000); @@ -890,9 +872,7 @@ describe('node show up animations', () => { graph.on('afterrender', () => { const node1 = graph.itemController.itemMap.get('node1'); expect(node1.shapeMap.keyShape.attributes.opacity).toBe(0); - expect(node1.shapeMap.keyShape.attributes.fill).toBe( - 'rgb(239, 244, 255)', - ); + expect(node1.shapeMap.keyShape.attributes.fill).toBe('rgb(239, 244, 255)'); setTimeout(() => { graph.updateData('node', { id: 'node1', @@ -906,9 +886,7 @@ describe('node show up animations', () => { expect(node1.shapeMap.keyShape.attributes.opacity).toBe(1); setTimeout(() => { expect(node1.shapeMap.keyShape.attributes.opacity).toBe(1); - expect(node1.shapeMap.keyShape.attributes.fill).not.toBe( - 'rgb(239, 244, 255)', - ); + expect(node1.shapeMap.keyShape.attributes.fill).not.toBe('rgb(239, 244, 255)'); graph.destroy(); done(); }, 1000); @@ -945,9 +923,7 @@ describe('node show up animations', () => { graph.on('afterrender', () => { const node1 = graph.itemController.itemMap.get('node1'); - expect(node1.shapeMap.keyShape.attributes.fill).toBe( - 'rgb(239, 244, 255)', - ); + expect(node1.shapeMap.keyShape.attributes.fill).toBe('rgb(239, 244, 255)'); graph.updateData('node', { id: 'node1', data: { @@ -956,9 +932,7 @@ describe('node show up animations', () => { }, }, }); - expect(node1.shapeMap.keyShape.attributes.fill).toBe( - 'rgb(239, 244, 255)', - ); + expect(node1.shapeMap.keyShape.attributes.fill).toBe('rgb(239, 244, 255)'); setTimeout(() => { graph.updateData('node', { id: 'node1', @@ -1177,13 +1151,10 @@ describe('custom node animations', () => { const edge1 = graph.itemController.itemMap.get('edge1'); expect(edge1.shapeMap.runningCircle.attributes.offsetDistance).toBe(0); setTimeout(() => { - const currentOffsetDistance = - edge1.shapeMap.runningCircle.attributes.offsetDistance; + const currentOffsetDistance = edge1.shapeMap.runningCircle.attributes.offsetDistance; expect(currentOffsetDistance).not.toBe(0); setTimeout(() => { - expect( - edge1.shapeMap.runningCircle.attributes.offsetDistance, - ).not.toBe(currentOffsetDistance); + expect(edge1.shapeMap.runningCircle.attributes.offsetDistance).not.toBe(currentOffsetDistance); graph.destroy(); done(); }, 200); diff --git a/packages/g6/tests/unit/layout-spec.ts b/packages/g6/tests/unit/layout-spec.ts index f20a101ddfa..06d425b6913 100644 --- a/packages/g6/tests/unit/layout-spec.ts +++ b/packages/g6/tests/unit/layout-spec.ts @@ -268,9 +268,7 @@ describe('layout', () => { graph.once('afterlayout', () => { const nodesData = graph.getAllNodesData(); - expect( - nodesData.every((node) => node.data.x > 0 && node.data.y > 0), - ).toBeTruthy(); + expect(nodesData.every((node) => node.data.x > 0 && node.data.y > 0)).toBeTruthy(); graph.destroy(); done(); }); @@ -393,9 +391,7 @@ describe('layout', () => { graph.stopLayout(); const nodesData = graph.getAllNodesData(); - expect( - nodesData.every((node) => node.data.x > 0 && node.data.y > 0), - ).toBeTruthy(); + expect(nodesData.every((node) => node.data.x > 0 && node.data.y > 0)).toBeTruthy(); graph.destroy(); done(); @@ -420,9 +416,7 @@ describe('layout', () => { graph.once('afterlayout', () => { const nodesData = graph.getAllNodesData(); - expect( - nodesData.every((node) => node.data.x > 0 && node.data.y > 0), - ).toBeTruthy(); + expect(nodesData.every((node) => node.data.x > 0 && node.data.y > 0)).toBeTruthy(); graph.destroy(); done(); @@ -467,9 +461,7 @@ describe('layout', () => { graph.once('afterlayout', () => { const nodesData = graph.getAllNodesData(); - expect( - nodesData.every((node) => node.data.x === 0 && node.data.y === 0), - ).toBeTruthy(); + expect(nodesData.every((node) => node.data.x === 0 && node.data.y === 0)).toBeTruthy(); graph.destroy(); done(); diff --git a/packages/g6/tests/unit/node-spec.ts b/packages/g6/tests/unit/node-spec.ts index 64b093a1457..dfe1df2f8cb 100644 --- a/packages/g6/tests/unit/node-spec.ts +++ b/packages/g6/tests/unit/node-spec.ts @@ -2,17 +2,12 @@ import { DisplayObject } from '@antv/g'; import { clone } from '@antv/util'; -import G6, { - EdgeDisplayModel, - Graph, - IGraph, - NodeDisplayModel, -} from '../../src/index'; +import G6, { EdgeDisplayModel, Graph, IGraph, NodeDisplayModel } from '../../src/index'; import { LineEdge } from '../../src/stdlib/item/edge'; import { CircleNode } from '../../src/stdlib/item/node'; +import { State } from '../../src/types/item'; import { NodeModelData, NodeShapeMap } from '../../src/types/node'; import { extend } from '../../src/util/extend'; -import { State } from '../../src/types/item'; const container = document.createElement('div'); document.querySelector('body').appendChild(container); @@ -183,16 +178,12 @@ describe('node mapper', () => { keyShape: { fill: { fields: ['buStatus'], - formatter: (innerModel) => - innerModel.data.buStatus ? '#0f0' : '#f00', + formatter: (innerModel) => (innerModel.data.buStatus ? '#0f0' : '#f00'), }, lineWidth: 5, stroke: { fields: ['buStatus', 'buType'], - formatter: (innerModel) => - innerModel.data.buStatus || innerModel.data.buType - ? '#fff' - : '#000', + formatter: (innerModel) => (innerModel.data.buStatus || innerModel.data.buType ? '#fff' : '#000'), }, }, labelShape: {}, @@ -245,11 +236,7 @@ describe('register node', () => { diffData?: { oldData: NodeModelData; newData: NodeModelData }, ) { const { labelShape: propsLabelStyle } = model.data; - const labelStyle = Object.assign( - {}, - this.defaultStyles.labelShape, - propsLabelStyle, - ); + const labelStyle = Object.assign({}, this.defaultStyles.labelShape, propsLabelStyle); return this.upsertShape( 'text', 'labelShape', @@ -416,18 +403,8 @@ describe('register node', () => { shapeMap: NodeShapeMap, diffData?: { oldData: NodeModelData; newData: NodeModelData }, ) { - const keyShapeStyle = Object.assign( - {}, - this.defaultStyles.keyShape, - model.data.labelShape, - ); - return this.upsertShape( - 'rect', - 'keyShape', - keyShapeStyle, - shapeMap, - model, - ); + const keyShapeStyle = Object.assign({}, this.defaultStyles.keyShape, model.data.labelShape); + return this.upsertShape('rect', 'keyShape', keyShapeStyle, shapeMap, model); } public drawOtherShapes( model: NodeDisplayModel, @@ -580,105 +557,48 @@ describe('state', () => { graph.setItemState('node1', 'selected', true); expect(graph.findIdByState('node', 'selected').length).toBe(1); expect(graph.findIdByState('node', 'selected')[0]).toBe('node1'); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.stroke).toBe('#0f0'); graph.setItemState('node1', 'selected', false); expect(graph.findIdByState('node', 'selected').length).toBe(0); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .lineWidth, - ).toBe(0); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.lineWidth).toBe(0); // set multiple nodes state graph.setItemState(['node1', 'node2'], 'selected', true); expect(graph.findIdByState('node', 'selected').length).toBe(2); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); - expect( - graph.itemController.itemMap.get('node2').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('node2').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.stroke).toBe('#0f0'); + expect(graph.itemController.itemMap.get('node2').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('node2').shapeMap.keyShape.style.stroke).toBe('#0f0'); graph.setItemState('node1', 'selected', false); expect(graph.findIdByState('node', 'selected').length).toBe(1); expect(graph.findIdByState('node', 'selected')[0]).toBe('node2'); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .lineWidth, - ).toBe(0); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.lineWidth).toBe(0); graph.setItemState(['node1', 'node2'], 'selected', false); expect(graph.findIdByState('node', 'selected').length).toBe(0); - expect( - graph.itemController.itemMap.get('node2').shapeMap.keyShape.style - .lineWidth, - ).toBe(0); + expect(graph.itemController.itemMap.get('node2').shapeMap.keyShape.style.lineWidth).toBe(0); // set multiple states graph.setItemState(['node1', 'node2'], ['selected', 'highlight'], true); expect(graph.findIdByState('node', 'selected').length).toBe(2); expect(graph.findIdByState('node', 'highlight').length).toBe(2); // should be merged styles from selected and highlight - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .lineWidth, - ).toBe(3); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .stroke, - ).toBe('#00f'); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.r, - ).toBe(30); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .opacity, - ).toBe(0.5); - expect( - graph.itemController.itemMap.get('node2').shapeMap.keyShape.style - .lineWidth, - ).toBe(3); - expect( - graph.itemController.itemMap.get('node2').shapeMap.keyShape.style - .stroke, - ).toBe('#00f'); - expect( - graph.itemController.itemMap.get('node2').shapeMap.keyShape.style.r, - ).toBe(30); - expect( - graph.itemController.itemMap.get('node2').shapeMap.keyShape.style - .opacity, - ).toBe(0.5); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.lineWidth).toBe(3); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.stroke).toBe('#00f'); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.r).toBe(30); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.opacity).toBe(0.5); + expect(graph.itemController.itemMap.get('node2').shapeMap.keyShape.style.lineWidth).toBe(3); + expect(graph.itemController.itemMap.get('node2').shapeMap.keyShape.style.stroke).toBe('#00f'); + expect(graph.itemController.itemMap.get('node2').shapeMap.keyShape.style.r).toBe(30); + expect(graph.itemController.itemMap.get('node2').shapeMap.keyShape.style.opacity).toBe(0.5); // clear states graph.clearItemState(['node1', 'node2']); expect(graph.findIdByState('node', 'selected').length).toBe(0); expect(graph.findIdByState('node', 'highlight').length).toBe(0); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.r, - ).toBe(16); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .lineWidth, - ).toBe(0); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .opacity, - ).toBe(1); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.r).toBe(16); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.lineWidth).toBe(0); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.opacity).toBe(1); graph.destroy(); done(); @@ -748,105 +668,48 @@ describe('state', () => { graph.setItemState('node1', 'selected', true); expect(graph.findIdByState('node', 'selected').length).toBe(1); expect(graph.findIdByState('node', 'selected')[0]).toBe('node1'); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.stroke).toBe('#0f0'); graph.setItemState('node1', 'selected', false); expect(graph.findIdByState('node', 'selected').length).toBe(0); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .lineWidth, - ).toBe(0); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.lineWidth).toBe(0); // set multiple nodes state graph.setItemState(['node1', 'node2'], 'selected', true); expect(graph.findIdByState('node', 'selected').length).toBe(2); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); - expect( - graph.itemController.itemMap.get('node2').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('node2').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.stroke).toBe('#0f0'); + expect(graph.itemController.itemMap.get('node2').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('node2').shapeMap.keyShape.style.stroke).toBe('#0f0'); graph.setItemState('node1', 'selected', false); expect(graph.findIdByState('node', 'selected').length).toBe(1); expect(graph.findIdByState('node', 'selected')[0]).toBe('node2'); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .lineWidth, - ).toBe(0); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.lineWidth).toBe(0); graph.setItemState(['node1', 'node2'], 'selected', false); expect(graph.findIdByState('node', 'selected').length).toBe(0); - expect( - graph.itemController.itemMap.get('node2').shapeMap.keyShape.style - .lineWidth, - ).toBe(0); + expect(graph.itemController.itemMap.get('node2').shapeMap.keyShape.style.lineWidth).toBe(0); // set multiple states graph.setItemState(['node1', 'node2'], ['selected', 'highlight'], true); expect(graph.findIdByState('node', 'selected').length).toBe(2); expect(graph.findIdByState('node', 'highlight').length).toBe(2); // should be merged styles from selected and highlight - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .lineWidth, - ).toBe(3); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .stroke, - ).toBe('#00f'); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.r, - ).toBe(30); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .opacity, - ).toBe(0.5); - expect( - graph.itemController.itemMap.get('node2').shapeMap.keyShape.style - .lineWidth, - ).toBe(3); - expect( - graph.itemController.itemMap.get('node2').shapeMap.keyShape.style - .stroke, - ).toBe('#00f'); - expect( - graph.itemController.itemMap.get('node2').shapeMap.keyShape.style.r, - ).toBe(30); - expect( - graph.itemController.itemMap.get('node2').shapeMap.keyShape.style - .opacity, - ).toBe(0.5); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.lineWidth).toBe(3); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.stroke).toBe('#00f'); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.r).toBe(30); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.opacity).toBe(0.5); + expect(graph.itemController.itemMap.get('node2').shapeMap.keyShape.style.lineWidth).toBe(3); + expect(graph.itemController.itemMap.get('node2').shapeMap.keyShape.style.stroke).toBe('#00f'); + expect(graph.itemController.itemMap.get('node2').shapeMap.keyShape.style.r).toBe(30); + expect(graph.itemController.itemMap.get('node2').shapeMap.keyShape.style.opacity).toBe(0.5); // clear states graph.clearItemState(['node1', 'node2']); expect(graph.findIdByState('node', 'selected').length).toBe(0); expect(graph.findIdByState('node', 'highlight').length).toBe(0); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.r, - ).toBe(16); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .lineWidth, - ).toBe(0); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .opacity, - ).toBe(1); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.r).toBe(16); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.lineWidth).toBe(0); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.opacity).toBe(1); graph.destroy(); done(); @@ -869,11 +732,7 @@ describe('state', () => { diffData?: { oldData: NodeModelData; newData: NodeModelData }, ) { const { labelShape: propsLabelStyle } = model.data; - const labelStyle = Object.assign( - {}, - this.defaultStyles.labelShape, - propsLabelStyle, - ); + const labelStyle = Object.assign({}, this.defaultStyles.labelShape, propsLabelStyle); return this.upsertShape( 'text', 'labelShape', @@ -888,9 +747,7 @@ describe('state', () => { public drawOtherShapes( model: NodeDisplayModel, shapeMap: NodeShapeMap, - diffData?: - | { previous: NodeModelData; current: NodeModelData } - | undefined, + diffData?: { previous: NodeModelData; current: NodeModelData } | undefined, diffState?: { previous: State[]; current: State[] } | undefined, ): { [id: string]: DisplayObject } { const extraShape = this.upsertShape( diff --git a/packages/g6/tests/unit/plugins/edgebundling-spec.ts b/packages/g6/tests/unit/plugins/edgebundling-spec.ts index 5d38b084fc6..0632304eab2 100644 --- a/packages/g6/tests/unit/plugins/edgebundling-spec.ts +++ b/packages/g6/tests/unit/plugins/edgebundling-spec.ts @@ -41,8 +41,7 @@ describe('edge bundling', () => { }); it('edge bundling on circular layout with default configs', () => { - const { plugin: edgeBundling } = - graph.pluginController.pluginMap.get('edgeBundling'); + const { plugin: edgeBundling } = graph.pluginController.pluginMap.get('edgeBundling'); const graphData = { nodes: graph.getAllNodesData(), @@ -51,16 +50,13 @@ describe('edge bundling', () => { edgeBundling.bundling(graphData); expect(graphData.edges[0].data.type).toEqual('polyline-edge'); - expect(graphData.edges[0].data.keyShape?.controlPoints.length > 2).toEqual( - true, - ); + expect(graphData.edges[0].data.keyShape?.controlPoints.length > 2).toEqual(true); edgeBundling.destroy(); }); it('bundling on circular with fixed bundleThreshold and iterations', () => { - const { plugin: edgeBundling } = - graph.pluginController.pluginMap.get('edgeBundling'); + const { plugin: edgeBundling } = graph.pluginController.pluginMap.get('edgeBundling'); const graphData = { nodes: graph.getAllNodesData(), @@ -74,9 +70,7 @@ describe('edge bundling', () => { }); expect(graphData.edges[0].data.type).toEqual('polyline-edge'); - expect(graphData.edges[0].data.keyShape?.controlPoints.length > 2).toEqual( - true, - ); + expect(graphData.edges[0].data.keyShape?.controlPoints.length > 2).toEqual(true); edgeBundling.destroy(); }); @@ -91,8 +85,7 @@ describe('edge bundling', () => { }; graph.changeData(data2); graph.on('afterlayout', () => { - const { plugin: edgeBundling } = - graph.pluginController.pluginMap.get('edgeBundling'); + const { plugin: edgeBundling } = graph.pluginController.pluginMap.get('edgeBundling'); data2.nodes = [ { @@ -131,30 +124,28 @@ describe('edge bundling', () => { }); expect(data2.edges[0].data.type).toEqual('polyline-edge'); - expect(data2.edges[0].data.keyShape?.controlPoints.length > 2).toEqual( - true, - ); + expect(data2.edges[0].data.keyShape?.controlPoints.length > 2).toEqual(true); edgeBundling.destroy(); }); }); it('bundling no position info, throw error', () => { - const { plugin: edgeBundling } = - graph.pluginController.pluginMap.get('edgeBundling'); + const { plugin: edgeBundling } = graph.pluginController.pluginMap.get('edgeBundling'); const data2 = { nodes: [{ id: 'n0' }, { id: 'n1' }], edges: [{ source: 'n0', target: 'n1' }], }; + /** + * + */ function fn() { edgeBundling.updateBundling({ data: data2, }); } - expect(fn).toThrowError( - 'please layout the graph or assign x and y for nodes first', - ); + expect(fn).toThrowError('please layout the graph or assign x and y for nodes first'); edgeBundling.destroy(); graph.destroy(); }); diff --git a/packages/g6/tests/unit/plugins/grid-spec.ts b/packages/g6/tests/unit/plugins/grid-spec.ts index b48bdf2f9fa..b8cc152b22a 100644 --- a/packages/g6/tests/unit/plugins/grid-spec.ts +++ b/packages/g6/tests/unit/plugins/grid-spec.ts @@ -1,5 +1,4 @@ import { Graph } from '../../../src/index'; -import { pxCompare } from '../util'; const container = document.createElement('div'); container.id = 'container'; diff --git a/packages/g6/tests/unit/plugins/legend-spec.ts b/packages/g6/tests/unit/plugins/legend-spec.ts index 845fbf51688..0b1ccc7e74c 100644 --- a/packages/g6/tests/unit/plugins/legend-spec.ts +++ b/packages/g6/tests/unit/plugins/legend-spec.ts @@ -1,5 +1,4 @@ import { Graph } from '../../../src/index'; -import { pxCompare } from '../util'; const container = document.createElement('div'); container.id = 'container'; diff --git a/packages/g6/tests/unit/plugins/menu-spec.ts b/packages/g6/tests/unit/plugins/menu-spec.ts index a8f0ac1335d..267a99977ed 100644 --- a/packages/g6/tests/unit/plugins/menu-spec.ts +++ b/packages/g6/tests/unit/plugins/menu-spec.ts @@ -1,5 +1,4 @@ import { Graph } from '../../../src/index'; -import { pxCompare } from '../util'; const container = document.createElement('div'); document.querySelector('body').appendChild(container); @@ -37,9 +36,7 @@ describe('plugin', () => { it('menu with default config', (done) => { const graph = createGraph(['menu']); graph.on('afterlayout', (e) => { - const contextmenuDiv = document.getElementsByClassName( - 'g6-component-contextmenu', - )?.[0]; + const contextmenuDiv = document.getElementsByClassName('g6-component-contextmenu')?.[0]; expect(contextmenuDiv).not.toBe(undefined); }); }); @@ -50,7 +47,10 @@ describe('plugin', () => { key: 'menu1', type: 'menu', trigger: 'contextmenu', - /** async string menu */ + /** + * async string menu + * @param e + */ getContent: (e) => { return `
    @@ -62,9 +62,7 @@ describe('plugin', () => { }, ]); graph.on('afterlayout', (e) => { - const contextmenuDiv = document.getElementsByClassName( - 'g6-component-contextmenu', - )?.[0]; + const contextmenuDiv = document.getElementsByClassName('g6-component-contextmenu')?.[0]; expect(contextmenuDiv).not.toBe(undefined); }); }); @@ -75,7 +73,10 @@ describe('plugin', () => { key: 'menu1', type: 'menu', trigger: 'contextmenu', - /** async string menu */ + /** + * async string menu + * @param e + */ getContent: (e) => { const outDiv = document.createElement('div'); outDiv.style.width = '180px'; @@ -91,9 +92,7 @@ describe('plugin', () => { }, ]); graph.on('afterlayout', (e) => { - const contextmenuDiv = document.getElementsByClassName( - 'g6-component-contextmenu', - )?.[0]; + const contextmenuDiv = document.getElementsByClassName('g6-component-contextmenu')?.[0]; expect(contextmenuDiv).not.toBe(undefined); }); }); @@ -104,7 +103,10 @@ describe('plugin', () => { key: 'menu1', type: 'menu', trigger: 'contextmenu', - /** async string menu */ + /** + * async string menu + * @param e + */ getContent: (e) => { return new Promise((resolve) => { const data = ` @@ -122,9 +124,7 @@ describe('plugin', () => { ]); graph.on('afterlayout', (e) => { - const contextmenuDiv = document.getElementsByClassName( - 'g6-component-contextmenu', - )?.[0]; + const contextmenuDiv = document.getElementsByClassName('g6-component-contextmenu')?.[0]; expect(contextmenuDiv).not.toBe(undefined); }); }); diff --git a/packages/g6/tests/unit/plugins/minimap-spec.ts b/packages/g6/tests/unit/plugins/minimap-spec.ts index 0e4b0ad08ad..6fb5c053e55 100644 --- a/packages/g6/tests/unit/plugins/minimap-spec.ts +++ b/packages/g6/tests/unit/plugins/minimap-spec.ts @@ -37,9 +37,7 @@ describe('plugin', () => { test('minimap with string config', (done) => { const graph = createGraph(['minimap']); graph.on('afterlayout', (e) => { - const viewport = document.getElementsByClassName( - 'g6-minimap-viewport', - )?.[0]; + const viewport = document.getElementsByClassName('g6-minimap-viewport')?.[0]; expect(viewport).not.toBe(undefined); // setTimeout for: minimap viewport debounce update setTimeout(() => { @@ -63,9 +61,7 @@ describe('plugin', () => { expect(pxCompare(viewport.style.width, 82)).toBe(true); expect(pxCompare(viewport.style.height, 88)).toBe(true); - graph.updateData('node', [ - { id: 'node3', data: { x: 150, y: 50 } }, - ]); + graph.updateData('node', [{ id: 'node3', data: { x: 150, y: 50 } }]); setTimeout(() => { expect(pxCompare(viewport.style.left, 100)).toBe(true); @@ -81,9 +77,7 @@ describe('plugin', () => { expect(pxCompare(viewport.style.height, 76)).toBe(true); graph.destroy(); - const viewport2 = document.getElementsByClassName( - 'g6-minimap-viewport', - )?.[0]; + const viewport2 = document.getElementsByClassName('g6-minimap-viewport')?.[0]; expect(viewport2).toBe(undefined); done(); }, 100); @@ -108,28 +102,21 @@ describe('plugin', () => { ]); graph.on('afterlayout', (e) => { - const viewport = document.getElementsByClassName( - 'g6-minimap-viewport', - )?.[0]; + const viewport = document.getElementsByClassName('g6-minimap-viewport')?.[0]; setTimeout(() => { expect(pxCompare(viewport.style.width, 300)).toBe(true); expect(pxCompare(viewport.style.height, 300)).toBe(true); expect(viewport.style.width).toBe('300px'); expect(viewport.style.height).toBe('300px'); - const { plugin: minimap } = - graph.pluginController.pluginMap.get('minimap1'); + const { plugin: minimap } = graph.pluginController.pluginMap.get('minimap1'); expect(minimap).not.toBe(undefined); const minimapCanvas = minimap.canvas; const minimapRootGroup = minimapCanvas.getRoot(); expect(minimapRootGroup.children.length).toBe(3); - const node1Delegate = minimapRootGroup.find( - (ele) => ele.id === 'minimap-delegate-node1', - ); + const node1Delegate = minimapRootGroup.find((ele) => ele.id === 'minimap-delegate-node1'); expect(node1Delegate.nodeName).toBe('rect'); expect(node1Delegate.style.fill).toBe('#f00'); - const node2Delegate = minimapRootGroup.find( - (ele) => ele.id === 'minimap-delegate-node2', - ); + const node2Delegate = minimapRootGroup.find((ele) => ele.id === 'minimap-delegate-node2'); expect(node2Delegate.nodeName).toBe('rect'); expect(node2Delegate.style.fill).toBe('#f00'); graph.destroy(); @@ -149,34 +136,25 @@ describe('plugin', () => { ]); graph.on('afterlayout', (e) => { - const viewport = document.getElementsByClassName( - 'g6-minimap-viewport', - )?.[0]; + const viewport = document.getElementsByClassName('g6-minimap-viewport')?.[0]; setTimeout(() => { expect(pxCompare(viewport.style.width, 200)).toBe(true); expect(pxCompare(viewport.style.height, 300)).toBe(true); expect(viewport.style.width).toBe('200px'); expect(viewport.style.height).toBe('300px'); - const { plugin: minimap } = - graph.pluginController.pluginMap.get('minimap1'); + const { plugin: minimap } = graph.pluginController.pluginMap.get('minimap1'); expect(minimap).not.toBe(undefined); const minimapCanvas = minimap.canvas; const minimapRootGroup = minimapCanvas.getRoot(); expect(minimapRootGroup.children.length).toBe(3); - const node1Delegate = minimapRootGroup.find( - (ele) => ele.id === 'minimap-keyShape-node1', - ); + const node1Delegate = minimapRootGroup.find((ele) => ele.id === 'minimap-keyShape-node1'); expect(node1Delegate.nodeName).toBe('circle'); - const node1KeyShape = - graph.itemController.itemMap.get('node1').shapeMap['keyShape']; + const node1KeyShape = graph.itemController.itemMap.get('node1').shapeMap['keyShape']; expect(node1Delegate.style.fill).toBe(node1KeyShape.style.fill); - const node2Delegate = minimapRootGroup.find( - (ele) => ele.id === 'minimap-keyShape-node2', - ); + const node2Delegate = minimapRootGroup.find((ele) => ele.id === 'minimap-keyShape-node2'); expect(node2Delegate.nodeName).toBe('circle'); - const node2KeyShape = - graph.itemController.itemMap.get('node2').shapeMap['keyShape']; + const node2KeyShape = graph.itemController.itemMap.get('node2').shapeMap['keyShape']; expect(node2Delegate.style.fill).toBe(node2KeyShape.style.fill); graph.destroy(); @@ -191,9 +169,7 @@ describe('graph plugin related APIs', () => { test('add plugins to graph', (done) => { graph = createGraph(undefined); graph.on('afterlayout', () => { - let viewport = document.getElementsByClassName( - 'g6-minimap-viewport', - )?.[0]; + let viewport = document.getElementsByClassName('g6-minimap-viewport')?.[0]; expect(viewport).toBe(undefined); graph.addPlugins('minimap'); @@ -217,9 +193,7 @@ describe('graph plugin related APIs', () => { // setTimeout for minimap canvas ready setTimeout(() => { - const viewports = document.getElementsByClassName( - 'g6-minimap-viewport', - ); + const viewports = document.getElementsByClassName('g6-minimap-viewport'); expect(viewports.length).toBe(3); done(); }, 100); @@ -241,14 +215,11 @@ describe('graph plugin related APIs', () => { const viewports = document.getElementsByClassName('g6-minimap-viewport'); expect(viewports.length).toBe(3); - const { plugin: minimap } = - graph.pluginController.pluginMap.get('minimap2'); + const { plugin: minimap } = graph.pluginController.pluginMap.get('minimap2'); expect(minimap).not.toBe(undefined); const minimapCanvas = minimap.canvas; const minimapRootGroup = minimapCanvas.getRoot(); - const node1Delegate = minimapRootGroup.find( - (ele) => ele.id === 'minimap-delegate-node1', - ); + const node1Delegate = minimapRootGroup.find((ele) => ele.id === 'minimap-delegate-node1'); expect(node1Delegate.nodeName).toBe('rect'); expect(node1Delegate.style.fill).toBe('#f00'); diff --git a/packages/g6/tests/unit/plugins/tooltip-spec.ts b/packages/g6/tests/unit/plugins/tooltip-spec.ts index 388a9517fab..da8c45fd572 100644 --- a/packages/g6/tests/unit/plugins/tooltip-spec.ts +++ b/packages/g6/tests/unit/plugins/tooltip-spec.ts @@ -1,5 +1,4 @@ import { Graph } from '../../../src/index'; -import { pxCompare } from '../util'; const container = document.createElement('div'); document.querySelector('body').appendChild(container); @@ -37,9 +36,7 @@ describe('tooltip-plugin', () => { it('tooltip with default config', (done) => { const graph = createGraph(['tooltip']); graph.on('afterlayout', (e) => { - const toolTipDiv = document.getElementsByClassName( - 'g6-component-tooltip', - )?.[0]; + const toolTipDiv = document.getElementsByClassName('g6-component-tooltip')?.[0]; expect(toolTipDiv).not.toBe(undefined); }); }); @@ -61,9 +58,7 @@ describe('tooltip-plugin', () => { }, ]); graph.on('afterlayout', (e) => { - const toolTipDiv = document.getElementsByClassName( - 'g6-component-tooltip', - )?.[0]; + const toolTipDiv = document.getElementsByClassName('g6-component-tooltip')?.[0]; expect(toolTipDiv).not.toBe(undefined); }); }); @@ -78,9 +73,7 @@ describe('tooltip-plugin', () => { ]); graph.on('afterlayout', (e) => { - const toolTipDiv = document.getElementsByClassName( - 'g6-component-tooltip', - )?.[0]; + const toolTipDiv = document.getElementsByClassName('g6-component-tooltip')?.[0]; expect(toolTipDiv).not.toBe(undefined); }); }); @@ -100,9 +93,7 @@ describe('tooltip-plugin', () => { }, ]); graph.on('afterlayout', (e) => { - const toolTipDiv = document.getElementsByClassName( - 'g6-component-tooltip', - )?.[0]; + const toolTipDiv = document.getElementsByClassName('g6-component-tooltip')?.[0]; expect(toolTipDiv).not.toBe(undefined); }); }); @@ -114,7 +105,10 @@ describe('tooltip-plugin', () => { type: 'tooltip', trigger: 'click', // fixToNode: [1, 0.5], - /** async string tooltip */ + /** + * async string tooltip + * @param e + */ getContent: (e) => { return new Promise((resolve) => { const data = ` @@ -131,9 +125,7 @@ describe('tooltip-plugin', () => { }, ]); graph.on('afterlayout', (e) => { - const toolTipDiv = document.getElementsByClassName( - 'g6-component-tooltip', - )?.[0]; + const toolTipDiv = document.getElementsByClassName('g6-component-tooltip')?.[0]; expect(toolTipDiv).not.toBe(undefined); }); }); diff --git a/packages/g6/tests/unit/quadratic-spec.ts b/packages/g6/tests/unit/quadratic-spec.ts index f081b80a4cb..7d113650a6f 100644 --- a/packages/g6/tests/unit/quadratic-spec.ts +++ b/packages/g6/tests/unit/quadratic-spec.ts @@ -1,18 +1,6 @@ // @ts-nocheck -import { DisplayObject } from '@antv/g'; -import { clone } from '@antv/util'; -import G6, { - EdgeDisplayModel, - Graph, - IGraph, - NodeDisplayModel, -} from '../../src/index'; -import { LineEdge } from '../../src/stdlib/item/edge'; -import { CircleNode } from '../../src/stdlib/item/node'; -import { NodeModelData, NodeShapeMap } from '../../src/types/node'; -import { extend } from '../../src/util/extend'; -import { upsertShape } from '../../src/util/shape'; +import G6, { Graph, IGraph } from '../../src/index'; const container = document.createElement('div'); const width = document.getElementById('container')?.clientWidth; @@ -105,9 +93,7 @@ describe('edge item', () => { expect(edgeItem).not.toBe(undefined); expect(edgeItem.shapeMap.labelShape.attributes.text).toBe('label'); expect(edgeItem.shapeMap.labelShape.attributes.fill).toBe('blue'); - expect(edgeItem.shapeMap.labelBackgroundShape.attributes.fill).toBe( - 'white', - ); + expect(edgeItem.shapeMap.labelBackgroundShape.attributes.fill).toBe('white'); done(); }); }); @@ -154,15 +140,13 @@ describe('edge item', () => { }, }); expect(edgeItem.shapeMap.labelShape.attributes.fill).toBe('#00f'); - expect( - edgeItem.shapeMap.labelShape.attributes.x - - edgeItem.shapeMap.labelBackgroundShape.attributes.x, - ).toBe(padding[3]); + expect(edgeItem.shapeMap.labelShape.attributes.x - edgeItem.shapeMap.labelBackgroundShape.attributes.x).toBe( + padding[3], + ); labelBounds = edgeItem.shapeMap.labelShape.getGeometryBounds(); const labelWidth = labelBounds.max[0] - labelBounds.min[0]; const labelHeight = labelBounds.max[1] - labelBounds.min[1]; - const labelBgBounds = - edgeItem.shapeMap.labelBackgroundShape.getGeometryBounds(); + const labelBgBounds = edgeItem.shapeMap.labelBackgroundShape.getGeometryBounds(); const labelBgWidth = labelBgBounds.max[0] - labelBgBounds.min[0]; const labelBgHeight = labelBgBounds.max[1] - labelBgBounds.min[1]; expect(labelBgWidth - labelWidth).toBe(padding[1] + padding[3]); @@ -200,19 +184,11 @@ describe('edge item', () => { const edgeItem = graph.itemController.itemMap.get('edge1'); let { labelShape, iconShape, labelBackgroundShape } = edgeItem.shapeMap; expect(iconShape.attributes.x + iconShape.attributes.width + 6).toBe( - labelBackgroundShape.getGeometryBounds().min[0] + - labelBackgroundShape.attributes.x, - ); - expect(iconShape.attributes.transform).toBe( - labelBackgroundShape.attributes.transform, + labelBackgroundShape.getGeometryBounds().min[0] + labelBackgroundShape.attributes.x, ); - expect( - Math.floor(iconShape.attributes.y + iconShape.attributes.height / 2), - ).toBeCloseTo( - Math.floor( - labelBackgroundShape.getGeometryBounds().center[1] + - labelBackgroundShape.attributes.y, - ), + expect(iconShape.attributes.transform).toBe(labelBackgroundShape.attributes.transform); + expect(Math.floor(iconShape.attributes.y + iconShape.attributes.height / 2)).toBeCloseTo( + Math.floor(labelBackgroundShape.getGeometryBounds().center[1] + labelBackgroundShape.attributes.y), 0.01, ); @@ -231,19 +207,11 @@ describe('edge item', () => { iconShape = edgeItem.shapeMap['iconShape']; labelBackgroundShape = edgeItem.shapeMap['labelBackgroundShape']; expect(iconShape.attributes.x + iconShape.attributes.fontSize + 6).toBe( - labelBackgroundShape.getGeometryBounds().min[0] + - labelBackgroundShape.attributes.x, + labelBackgroundShape.getGeometryBounds().min[0] + labelBackgroundShape.attributes.x, ); - expect(iconShape.attributes.transform).toBe( - labelBackgroundShape.attributes.transform, - ); - expect( - Math.floor(iconShape.attributes.y + iconShape.attributes.fontSize / 2), - ).toBeCloseTo( - Math.floor( - labelBackgroundShape.getGeometryBounds().center[1] + - labelBackgroundShape.attributes.y, - ), + expect(iconShape.attributes.transform).toBe(labelBackgroundShape.attributes.transform); + expect(Math.floor(iconShape.attributes.y + iconShape.attributes.fontSize / 2)).toBeCloseTo( + Math.floor(labelBackgroundShape.getGeometryBounds().center[1] + labelBackgroundShape.attributes.y), 0.01, ); @@ -260,15 +228,11 @@ describe('edge item', () => { iconShape = edgeItem.shapeMap['iconShape']; labelBackgroundShape = edgeItem.shapeMap['labelBackgroundShape']; expect(iconShape.attributes.x + iconShape.attributes.fontSize + 6).toBe( - labelBackgroundShape.getGeometryBounds().min[0] + - labelBackgroundShape.attributes.x, - ); - expect(iconShape.attributes.transform).toBe( - labelShape.attributes.transform, + labelBackgroundShape.getGeometryBounds().min[0] + labelBackgroundShape.attributes.x, ); + expect(iconShape.attributes.transform).toBe(labelShape.attributes.transform); expect(iconShape.attributes.y + iconShape.attributes.fontSize / 2).toBe( - labelBackgroundShape.getGeometryBounds().center[1] + - labelBackgroundShape.attributes.y, + labelBackgroundShape.getGeometryBounds().center[1] + labelBackgroundShape.attributes.y, ); graph.destroy(); done(); @@ -331,95 +295,44 @@ describe('state', () => { graph.setItemState('edge1', 'selected', true); expect(graph.findIdByState('edge', 'selected').length).toBe(1); expect(graph.findIdByState('edge', 'selected')[0]).toBe('edge1'); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.stroke).toBe('#0f0'); graph.setItemState('edge1', 'selected', false); expect(graph.findIdByState('edge', 'selected').length).toBe(0); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(1); // set multiple edges state graph.setItemState(['edge1', 'edge2'], 'selected', true); expect(graph.findIdByState('edge', 'selected').length).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.stroke).toBe('#0f0'); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.stroke).toBe('#0f0'); graph.setItemState('edge1', 'selected', false); expect(graph.findIdByState('edge', 'selected').length).toBe(1); expect(graph.findIdByState('edge', 'selected')[0]).toBe('edge2'); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(1); graph.setItemState(['edge1', 'edge2'], 'selected', false); expect(graph.findIdByState('edge', 'selected').length).toBe(0); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.lineWidth).toBe(1); graph.setItemState(['edge2', 'edge1'], ['selected', 'highlight'], true); expect(graph.findIdByState('edge', 'selected').length).toBe(2); expect(graph.findIdByState('edge', 'highlight').length).toBe(2); // should be merged styles from selected and highlight - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .stroke, - ).toBe('#00f'); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .opacity, - ).toBe(0.5); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .stroke, - ).toBe('#00f'); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .opacity, - ).toBe(0.5); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.stroke).toBe('#00f'); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.opacity).toBe(0.5); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.stroke).toBe('#00f'); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.opacity).toBe(0.5); // clear states graph.clearItemState(['edge1', 'edge2']); expect(graph.findIdByState('edge', 'selected').length).toBe(0); expect(graph.findIdByState('edge', 'highlight').length).toBe(0); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .opacity, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.opacity).toBe(1); graph.destroy(); done(); @@ -481,95 +394,44 @@ describe('state', () => { graph.setItemState('edge1', 'active', true); expect(graph.findIdByState('edge', 'active').length).toBe(1); expect(graph.findIdByState('edge', 'active')[0]).toBe('edge1'); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.stroke).toBe('#0f0'); graph.setItemState('edge1', 'active', false); expect(graph.findIdByState('edge', 'active').length).toBe(0); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(1); // set multiple edges state graph.setItemState(['edge1', 'edge2'], 'active', true); expect(graph.findIdByState('edge', 'active').length).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.stroke).toBe('#0f0'); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.stroke).toBe('#0f0'); graph.setItemState('edge1', 'active', false); expect(graph.findIdByState('edge', 'active').length).toBe(1); expect(graph.findIdByState('edge', 'active')[0]).toBe('edge2'); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(1); graph.setItemState(['edge1', 'edge2'], 'active', false); expect(graph.findIdByState('edge', 'active').length).toBe(0); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.lineWidth).toBe(1); graph.setItemState(['edge2', 'edge1'], ['active', 'highlight'], true); expect(graph.findIdByState('edge', 'active').length).toBe(2); expect(graph.findIdByState('edge', 'highlight').length).toBe(2); // should be merged styles from active and highlight - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .stroke, - ).toBe('#00f'); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .opacity, - ).toBe(0.5); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .stroke, - ).toBe('#00f'); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .opacity, - ).toBe(0.5); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.stroke).toBe('#00f'); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.opacity).toBe(0.5); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.stroke).toBe('#00f'); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.opacity).toBe(0.5); // clear states graph.clearItemState(['edge1', 'edge2']); expect(graph.findIdByState('edge', 'active').length).toBe(0); expect(graph.findIdByState('edge', 'highlight').length).toBe(0); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .opacity, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.opacity).toBe(1); graph.destroy(); done(); @@ -631,95 +493,44 @@ describe('state', () => { graph.setItemState('edge1', 'highlight', true); expect(graph.findIdByState('edge', 'highlight').length).toBe(1); expect(graph.findIdByState('edge', 'highlight')[0]).toBe('edge1'); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .stroke, - ).toBe('#00f'); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.stroke).toBe('#00f'); graph.setItemState('edge1', 'highlight', false); expect(graph.findIdByState('edge', 'highlight').length).toBe(0); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(1); // set multiple edges state graph.setItemState(['edge1', 'edge2'], 'highlight', true); expect(graph.findIdByState('edge', 'highlight').length).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .stroke, - ).toBe('#00f'); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .stroke, - ).toBe('#00f'); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.stroke).toBe('#00f'); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.stroke).toBe('#00f'); graph.setItemState('edge1', 'highlight', false); expect(graph.findIdByState('edge', 'highlight').length).toBe(1); expect(graph.findIdByState('edge', 'highlight')[0]).toBe('edge2'); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(1); graph.setItemState(['edge1', 'edge2'], 'highlight', false); expect(graph.findIdByState('edge', 'highlight').length).toBe(0); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.lineWidth).toBe(1); graph.setItemState(['edge2', 'edge1'], ['highlight', 'highlight'], true); expect(graph.findIdByState('edge', 'highlight').length).toBe(2); expect(graph.findIdByState('edge', 'highlight').length).toBe(2); // should be merged styles from highlight and highlight - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .stroke, - ).toBe('#00f'); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .opacity, - ).toBe(0.5); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .stroke, - ).toBe('#00f'); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .opacity, - ).toBe(0.5); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.stroke).toBe('#00f'); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.opacity).toBe(0.5); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.stroke).toBe('#00f'); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.opacity).toBe(0.5); // clear states graph.clearItemState(['edge1', 'edge2']); expect(graph.findIdByState('edge', 'highlight').length).toBe(0); expect(graph.findIdByState('edge', 'highlight').length).toBe(0); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .opacity, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.opacity).toBe(1); graph.destroy(); done(); @@ -781,95 +592,44 @@ describe('state', () => { graph.setItemState('edge1', 'inactive', true); expect(graph.findIdByState('edge', 'inactive').length).toBe(1); expect(graph.findIdByState('edge', 'inactive')[0]).toBe('edge1'); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.stroke).toBe('#0f0'); graph.setItemState('edge1', 'inactive', false); expect(graph.findIdByState('edge', 'inactive').length).toBe(0); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(1); // set multiple edges state graph.setItemState(['edge1', 'edge2'], 'inactive', true); expect(graph.findIdByState('edge', 'inactive').length).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.stroke).toBe('#0f0'); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.stroke).toBe('#0f0'); graph.setItemState('edge1', 'inactive', false); expect(graph.findIdByState('edge', 'inactive').length).toBe(1); expect(graph.findIdByState('edge', 'inactive')[0]).toBe('edge2'); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(1); graph.setItemState(['edge1', 'edge2'], 'inactive', false); expect(graph.findIdByState('edge', 'inactive').length).toBe(0); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.lineWidth).toBe(1); graph.setItemState(['edge2', 'edge1'], ['inactive', 'highlight'], true); expect(graph.findIdByState('edge', 'inactive').length).toBe(2); expect(graph.findIdByState('edge', 'highlight').length).toBe(2); // should be merged styles from inactive and highlight - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .stroke, - ).toBe('#00f'); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .opacity, - ).toBe(0.5); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .stroke, - ).toBe('#00f'); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .opacity, - ).toBe(0.5); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.stroke).toBe('#00f'); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.opacity).toBe(0.5); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.stroke).toBe('#00f'); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.opacity).toBe(0.5); // clear states graph.clearItemState(['edge1', 'edge2']); expect(graph.findIdByState('edge', 'inactive').length).toBe(0); expect(graph.findIdByState('edge', 'highlight').length).toBe(0); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .opacity, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.opacity).toBe(1); graph.destroy(); done(); @@ -931,95 +691,44 @@ describe('state', () => { graph.setItemState('edge1', 'disable', true); expect(graph.findIdByState('edge', 'disable').length).toBe(1); expect(graph.findIdByState('edge', 'disable')[0]).toBe('edge1'); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.stroke).toBe('#0f0'); graph.setItemState('edge1', 'disable', false); expect(graph.findIdByState('edge', 'disable').length).toBe(0); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(1); // set multiple edges state graph.setItemState(['edge1', 'edge2'], 'disable', true); expect(graph.findIdByState('edge', 'disable').length).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.stroke).toBe('#0f0'); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.stroke).toBe('#0f0'); graph.setItemState('edge1', 'disable', false); expect(graph.findIdByState('edge', 'disable').length).toBe(1); expect(graph.findIdByState('edge', 'disable')[0]).toBe('edge2'); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(1); graph.setItemState(['edge1', 'edge2'], 'disable', false); expect(graph.findIdByState('edge', 'disable').length).toBe(0); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.lineWidth).toBe(1); graph.setItemState(['edge2', 'edge1'], ['disable', 'highlight'], true); expect(graph.findIdByState('edge', 'disable').length).toBe(2); expect(graph.findIdByState('edge', 'highlight').length).toBe(2); // should be merged styles from disable and highlight - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .stroke, - ).toBe('#00f'); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .opacity, - ).toBe(0.5); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .stroke, - ).toBe('#00f'); - expect( - graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style - .opacity, - ).toBe(0.5); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.stroke).toBe('#00f'); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.opacity).toBe(0.5); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.stroke).toBe('#00f'); + expect(graph.itemController.itemMap.get('edge2').shapeMap.keyShape.style.opacity).toBe(0.5); // clear states graph.clearItemState(['edge1', 'edge2']); expect(graph.findIdByState('edge', 'disable').length).toBe(0); expect(graph.findIdByState('edge', 'highlight').length).toBe(0); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .lineWidth, - ).toBe(1); - expect( - graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style - .opacity, - ).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.lineWidth).toBe(1); + expect(graph.itemController.itemMap.get('edge1').shapeMap.keyShape.style.opacity).toBe(1); graph.destroy(); done(); diff --git a/packages/g6/tests/unit/rect-spec.ts b/packages/g6/tests/unit/rect-spec.ts index 55c922da207..2a34d047279 100644 --- a/packages/g6/tests/unit/rect-spec.ts +++ b/packages/g6/tests/unit/rect-spec.ts @@ -1,6 +1,4 @@ import G6 from '../../src/index'; -import { Behavior } from '../../src/types/behavior'; -import { extend } from '../../src/util/extend'; const container = document.createElement('div'); document.querySelector('body')?.appendChild(container); @@ -14,7 +12,7 @@ describe('behavior', () => { }, }); let graphSpec = graph.getSpecification(); - // @ts-ignore + // @ts-expect-error expect(graphSpec.modes.default[0]).toBe('drag-canvas'); // @ts-ignore expect(graphSpec.modes.default[1]).toBe('click-select'); diff --git a/packages/g6/tests/unit/show-animate-spec.ts b/packages/g6/tests/unit/show-animate-spec.ts index 2ad2f97c823..4a76e570f7c 100644 --- a/packages/g6/tests/unit/show-animate-spec.ts +++ b/packages/g6/tests/unit/show-animate-spec.ts @@ -1741,11 +1741,7 @@ class CustomNode extends CircleNode { model, ); const { labelShape: propsLabelStyle } = model.data; - const labelStyle = Object.assign( - {}, - this.defaultStyles.labelShape, - propsLabelStyle, - ); + const labelStyle = Object.assign({}, this.defaultStyles.labelShape, propsLabelStyle); const labelShape = upsertShape( 'text', 'labelShape', @@ -1808,23 +1804,8 @@ const clusters = [ 'Mme.Magloire', 'Mlle.Baptistine', ], - [ - 'Tholomyes', - 'Listolier', - 'Fameuil', - 'Blacheville', - 'Favourite', - 'Dahlia', - 'Zephine', - ], - [ - 'Bamatabois', - 'Judge', - 'Champmathieu', - 'Brevet', - 'Chenildieu', - 'Cochepaille', - ], + ['Tholomyes', 'Listolier', 'Fameuil', 'Blacheville', 'Favourite', 'Dahlia', 'Zephine'], + ['Bamatabois', 'Judge', 'Champmathieu', 'Brevet', 'Chenildieu', 'Cochepaille'], [ 'Mabeuf', 'Enjolras', @@ -1933,9 +1914,7 @@ describe('graph show up animations', () => { // ], labelShape: { position: 'end', - text: - innerModel.data.labelShape?.text || - '123asdfaskdfjaksjhdfjakshdfjkashdfkjahsfjkhaskjflhalkjs', + text: innerModel.data.labelShape?.text || '123asdfaskdfjaksjhdfjakshdfjkashdfkjahsfjkhaskjflhalkjs', }, labelBackgroundShape: { fill: '#f00', diff --git a/packages/g6/tests/unit/star-spec.ts b/packages/g6/tests/unit/star-spec.ts index c6f35f4b9fd..051319d152b 100644 --- a/packages/g6/tests/unit/star-spec.ts +++ b/packages/g6/tests/unit/star-spec.ts @@ -173,16 +173,12 @@ describe('node mapper', () => { keyShape: { fill: { fields: ['buStatus'], - formatter: (innerModel) => - innerModel.data.buStatus ? '#0f0' : '#f00', + formatter: (innerModel) => (innerModel.data.buStatus ? '#0f0' : '#f00'), }, lineWidth: 5, stroke: { fields: ['buStatus', 'buType'], - formatter: (innerModel) => - innerModel.data.buStatus || innerModel.data.buType - ? '#fff' - : '#000', + formatter: (innerModel) => (innerModel.data.buStatus || innerModel.data.buType ? '#fff' : '#000'), }, }, labelShape: {}, @@ -275,88 +271,48 @@ describe('state', () => { graph.setItemState('node1', 'selected', true); expect(graph.findIdByState('node', 'selected').length).toBe(1); expect(graph.findIdByState('node', 'selected')[0]).toBe('node1'); - expect( - graph.itemController.itemMap['node1'].shapeMap.keyShape.style.lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap['node1'].shapeMap.keyShape.style.stroke, - ).toBe('#0f0'); + expect(graph.itemController.itemMap['node1'].shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap['node1'].shapeMap.keyShape.style.stroke).toBe('#0f0'); graph.setItemState('node1', 'selected', false); expect(graph.findIdByState('node', 'selected').length).toBe(0); - expect( - graph.itemController.itemMap['node1'].shapeMap.keyShape.style.lineWidth, - ).toBe(0); + expect(graph.itemController.itemMap['node1'].shapeMap.keyShape.style.lineWidth).toBe(0); // set multiple nodes state graph.setItemState(['node1', 'node2'], 'selected', true); expect(graph.findIdByState('node', 'selected').length).toBe(2); - expect( - graph.itemController.itemMap['node1'].shapeMap.keyShape.style.lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap['node1'].shapeMap.keyShape.style.stroke, - ).toBe('#0f0'); - expect( - graph.itemController.itemMap['node2'].shapeMap.keyShape.style.lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap['node2'].shapeMap.keyShape.style.stroke, - ).toBe('#0f0'); + expect(graph.itemController.itemMap['node1'].shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap['node1'].shapeMap.keyShape.style.stroke).toBe('#0f0'); + expect(graph.itemController.itemMap['node2'].shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap['node2'].shapeMap.keyShape.style.stroke).toBe('#0f0'); graph.setItemState('node1', 'selected', false); expect(graph.findIdByState('node', 'selected').length).toBe(1); expect(graph.findIdByState('node', 'selected')[0]).toBe('node2'); - expect( - graph.itemController.itemMap['node1'].shapeMap.keyShape.style.lineWidth, - ).toBe(0); + expect(graph.itemController.itemMap['node1'].shapeMap.keyShape.style.lineWidth).toBe(0); graph.setItemState(['node1', 'node2'], 'selected', false); expect(graph.findIdByState('node', 'selected').length).toBe(0); - expect( - graph.itemController.itemMap['node2'].shapeMap.keyShape.style.lineWidth, - ).toBe(0); + expect(graph.itemController.itemMap['node2'].shapeMap.keyShape.style.lineWidth).toBe(0); // set multiple states graph.setItemState(['node1', 'node2'], ['selected', 'highlight'], true); expect(graph.findIdByState('node', 'selected').length).toBe(2); expect(graph.findIdByState('node', 'highlight').length).toBe(2); // should be merged styles from selected and highlight - expect( - graph.itemController.itemMap['node1'].shapeMap.keyShape.style.lineWidth, - ).toBe(3); - expect( - graph.itemController.itemMap['node1'].shapeMap.keyShape.style.stroke, - ).toBe('#00f'); - expect( - graph.itemController.itemMap['node1'].shapeMap.keyShape.style.r, - ).toBe(30); - expect( - graph.itemController.itemMap['node1'].shapeMap.keyShape.style.opacity, - ).toBe(0.5); - expect( - graph.itemController.itemMap['node2'].shapeMap.keyShape.style.lineWidth, - ).toBe(3); - expect( - graph.itemController.itemMap['node2'].shapeMap.keyShape.style.stroke, - ).toBe('#00f'); - expect( - graph.itemController.itemMap['node2'].shapeMap.keyShape.style.r, - ).toBe(30); - expect( - graph.itemController.itemMap['node2'].shapeMap.keyShape.style.opacity, - ).toBe(0.5); + expect(graph.itemController.itemMap['node1'].shapeMap.keyShape.style.lineWidth).toBe(3); + expect(graph.itemController.itemMap['node1'].shapeMap.keyShape.style.stroke).toBe('#00f'); + expect(graph.itemController.itemMap['node1'].shapeMap.keyShape.style.r).toBe(30); + expect(graph.itemController.itemMap['node1'].shapeMap.keyShape.style.opacity).toBe(0.5); + expect(graph.itemController.itemMap['node2'].shapeMap.keyShape.style.lineWidth).toBe(3); + expect(graph.itemController.itemMap['node2'].shapeMap.keyShape.style.stroke).toBe('#00f'); + expect(graph.itemController.itemMap['node2'].shapeMap.keyShape.style.r).toBe(30); + expect(graph.itemController.itemMap['node2'].shapeMap.keyShape.style.opacity).toBe(0.5); // clear states graph.clearItemState(['node1', 'node2']); expect(graph.findIdByState('node', 'selected').length).toBe(0); expect(graph.findIdByState('node', 'highlight').length).toBe(0); - expect( - graph.itemController.itemMap['node1'].shapeMap.keyShape.style.r, - ).toBe(16); - expect( - graph.itemController.itemMap['node1'].shapeMap.keyShape.style.lineWidth, - ).toBe(0); - expect( - graph.itemController.itemMap['node1'].shapeMap.keyShape.style.opacity, - ).toBe(1); + expect(graph.itemController.itemMap['node1'].shapeMap.keyShape.style.r).toBe(16); + expect(graph.itemController.itemMap['node1'].shapeMap.keyShape.style.lineWidth).toBe(0); + expect(graph.itemController.itemMap['node1'].shapeMap.keyShape.style.opacity).toBe(1); graph.destroy(); done(); diff --git a/packages/g6/tests/unit/theme-spec.ts b/packages/g6/tests/unit/theme-spec.ts index e62de23b93f..d476704baa9 100644 --- a/packages/g6/tests/unit/theme-spec.ts +++ b/packages/g6/tests/unit/theme-spec.ts @@ -2,8 +2,8 @@ import { clone } from '@antv/util'; import G6, { GraphData, IGraph } from '../../src/index'; -import { CircleNode } from '../../src/stdlib/item/node'; import { LineEdge } from '../../src/stdlib/item/edge'; +import { CircleNode } from '../../src/stdlib/item/node'; import { LightTheme } from '../../src/stdlib/theme/light'; import { extend } from '../../src/util/extend'; @@ -125,60 +125,36 @@ describe('theme', () => { }); graph.on('afterlayout', () => { const node = graph.itemController.itemMap.get('node1'); - const { keyShape: nodeKeyShape, labelShape: nodeLabelShape } = - node.shapeMap; + const { keyShape: nodeKeyShape, labelShape: nodeLabelShape } = node.shapeMap; expect(node.shapeMap.haloShape).toBe(undefined); - expect(nodeKeyShape.style.fill).toBe( - LightTheme.node.styles[0].default.keyShape.fill, - ); - expect(nodeLabelShape.style.fontWeight).toBe( - LightTheme.node.styles[0].default.labelShape.fontWeight, - ); + expect(nodeKeyShape.style.fill).toBe(LightTheme.node.styles[0].default.keyShape.fill); + expect(nodeLabelShape.style.fontWeight).toBe(LightTheme.node.styles[0].default.labelShape.fontWeight); const edge = graph.itemController.itemMap.get('edge1'); - const { keyShape: edgeKeyShape, labelShape: edgeLabelShape } = - edge.shapeMap; + const { keyShape: edgeKeyShape, labelShape: edgeLabelShape } = edge.shapeMap; expect(edge.shapeMap.haloShape).toBe(undefined); - expect(edgeKeyShape.style.stroke).toBe( - LightTheme.edge.styles[0].default.keyShape.stroke, - ); - expect(edgeLabelShape.style.fontWeight).toBe( - LightTheme.edge.styles[0].default.labelShape.fontWeight, - ); + expect(edgeKeyShape.style.stroke).toBe(LightTheme.edge.styles[0].default.keyShape.stroke); + expect(edgeLabelShape.style.fontWeight).toBe(LightTheme.edge.styles[0].default.labelShape.fontWeight); // set state, should response with default theme state style graph.setItemState('node1', 'selected', true); expect(node.shapeMap.haloShape).not.toBe(undefined); - expect(node.shapeMap.haloShape.style.lineWidth).not.toBe( - LightTheme.node.styles[0].selected.haloShape.lineWith, - ); + expect(node.shapeMap.haloShape.style.lineWidth).not.toBe(LightTheme.node.styles[0].selected.haloShape.lineWith); expect(nodeKeyShape.style.fill).toBe( LightTheme.node.styles[0].default.keyShape.fill, // no change ); - expect(nodeLabelShape.style.fontWeight).toBe( - LightTheme.node.styles[0].selected.labelShape.fontWeight, - ); + expect(nodeLabelShape.style.fontWeight).toBe(LightTheme.node.styles[0].selected.labelShape.fontWeight); graph.clearItemState('node1'); - expect(nodeKeyShape.style.fill).toBe( - LightTheme.node.styles[0].default.keyShape.fill, - ); - expect(nodeLabelShape.style.fontWeight).toBe( - LightTheme.node.styles[0].default.labelShape.fontWeight, - ); + expect(nodeKeyShape.style.fill).toBe(LightTheme.node.styles[0].default.keyShape.fill); + expect(nodeLabelShape.style.fontWeight).toBe(LightTheme.node.styles[0].default.labelShape.fontWeight); graph.setItemState('edge1', 'selected', true); expect(edge.shapeMap.haloShape).not.toBe(undefined); - expect(edge.shapeMap.haloShape.style.lineWidth).not.toBe( - LightTheme.edge.styles[0].selected.haloShape.lineWith, - ); + expect(edge.shapeMap.haloShape.style.lineWidth).not.toBe(LightTheme.edge.styles[0].selected.haloShape.lineWith); expect(edgeKeyShape.style.stroke).toBe( LightTheme.edge.styles[0].default.keyShape.stroke, // no change ); - expect(edgeKeyShape.style.lineWidth).toBe( - LightTheme.edge.styles[0].selected.keyShape.lineWidth, - ); - expect(edgeLabelShape.style.fill).toBe( - LightTheme.edge.styles[0].default.labelShape.fill, - ); + expect(edgeKeyShape.style.lineWidth).toBe(LightTheme.edge.styles[0].selected.keyShape.lineWidth); + expect(edgeLabelShape.style.fill).toBe(LightTheme.edge.styles[0].default.labelShape.fill); const node4 = graph.itemController.itemMap.get('node4'); expect(node4.shapeMap.anchorShape0).not.toBe(undefined); @@ -281,58 +257,42 @@ describe('theme', () => { }); graph.on('afterlayout', () => { // canvas style - expect( - graph.backgroundCanvas.getContextService().getDomElement().style - .backgroundColor, - ).toBe('rgb(255, 255, 255)'); // = rgb format of LightTheme.canvas.backgroundColor + expect(graph.backgroundCanvas.getContextService().getDomElement().style.backgroundColor).toBe( + 'rgb(255, 255, 255)', + ); // = rgb format of LightTheme.canvas.backgroundColor const node1 = graph.itemController.itemMap.get('node1'); - const { keyShape: nodeKeyShape1, labelShape: nodeLabelShape1 } = - node1.shapeMap; + const { keyShape: nodeKeyShape1, labelShape: nodeLabelShape1 } = node1.shapeMap; expect(nodeKeyShape1.style.fill).toBe('#f00'); expect(nodeLabelShape1.style.fill).toBe('#f00'); const node2 = graph.itemController.itemMap.get('node2'); - const { keyShape: nodeKeyShape2, labelShape: nodeLabelShape2 } = - node2.shapeMap; + const { keyShape: nodeKeyShape2, labelShape: nodeLabelShape2 } = node2.shapeMap; expect(nodeKeyShape2.style.fill).toBe('#0f0'); expect(nodeLabelShape2.style.fill).toBe('#0f0'); const node3 = graph.itemController.itemMap.get('node3'); - const { keyShape: nodeKeyShape3, labelShape: nodeLabelShape3 } = - node3.shapeMap; + const { keyShape: nodeKeyShape3, labelShape: nodeLabelShape3 } = node3.shapeMap; expect(nodeKeyShape3.style.fill).toBe('#00f'); expect(nodeLabelShape3.style.fill).toBe('#00f'); // node4 has no mapped palette, buitin theme take effects const node4 = graph.itemController.itemMap.get('node4'); - const { keyShape: nodeKeyShape4, labelShape: nodeLabelShape4 } = - node4.shapeMap; - expect(nodeKeyShape4.style.fill).toBe( - LightTheme.node.styles[0].default.keyShape.fill, - ); - expect(nodeLabelShape4.style.fontWeight).toBe( - LightTheme.node.styles[0].default.labelShape.fontWeight, - ); + const { keyShape: nodeKeyShape4, labelShape: nodeLabelShape4 } = node4.shapeMap; + expect(nodeKeyShape4.style.fill).toBe(LightTheme.node.styles[0].default.keyShape.fill); + expect(nodeLabelShape4.style.fontWeight).toBe(LightTheme.node.styles[0].default.labelShape.fontWeight); // edges const edge1 = graph.itemController.itemMap.get('edge1'); - const { keyShape: edgeKeyShape1, labelShape: edgeLabelShape1 } = - edge1.shapeMap; + const { keyShape: edgeKeyShape1, labelShape: edgeLabelShape1 } = edge1.shapeMap; expect(edgeKeyShape1.style.stroke).toBe('#f00'); expect(edgeLabelShape1.style.fill).toBe('#f00'); const edge2 = graph.itemController.itemMap.get('edge2'); - const { keyShape: edgeKeyShape2, labelShape: edgeLabelShape2 } = - edge2.shapeMap; + const { keyShape: edgeKeyShape2, labelShape: edgeLabelShape2 } = edge2.shapeMap; expect(edgeKeyShape2.style.stroke).toBe('#0f0'); expect(edgeLabelShape2.style.fill).toBe('#0f0'); // edge3 has no mapped palette, buitin theme take effects const edge3 = graph.itemController.itemMap.get('edge3'); - const { keyShape: edgeKeyShape4, labelShape: edgeLabelShape4 } = - edge3.shapeMap; - expect(edgeKeyShape4.style.stroke).toBe( - LightTheme.edge.styles[0].default.keyShape.stroke, - ); - expect(edgeLabelShape4.style.fontWeight).toBe( - LightTheme.edge.styles[0].default.labelShape.fontWeight, - ); + const { keyShape: edgeKeyShape4, labelShape: edgeLabelShape4 } = edge3.shapeMap; + expect(edgeKeyShape4.style.stroke).toBe(LightTheme.edge.styles[0].default.keyShape.stroke); + expect(edgeLabelShape4.style.fontWeight).toBe(LightTheme.edge.styles[0].default.labelShape.fontWeight); // update node dataType graph.updateData('node', { @@ -356,22 +316,16 @@ describe('theme', () => { // node setState with state in builtin theme graph.setItemState('node1', 'selected', true); - expect(nodeLabelShape1.style.fontWeight).toBe( - LightTheme.node.styles[0].selected.labelShape.fontWeight, - ); + expect(nodeLabelShape1.style.fontWeight).toBe(LightTheme.node.styles[0].selected.labelShape.fontWeight); // edge setState with state in builtin theme graph.setItemState('edge1', 'selected', true); expect(edgeLabelShape1.style.fill).toBe('#0f0'); // not assigned in selected theme - expect(edgeLabelShape1.style.fontWeight).toBe( - LightTheme.edge.styles[0].selected.labelShape.fontWeight, - ); + expect(edgeLabelShape1.style.fontWeight).toBe(LightTheme.edge.styles[0].selected.labelShape.fontWeight); // node setState with state in configured spec graph.setItemState('node1', 'state1', true); expect(nodeKeyShape1.style.fill).toBe('#000'); - expect(nodeLabelShape1.style.fontWeight).toBe( - LightTheme.node.styles[0].selected.labelShape.fontWeight, - ); + expect(nodeLabelShape1.style.fontWeight).toBe(LightTheme.node.styles[0].selected.labelShape.fontWeight); graph.setItemState('node1', 'state2', true); expect(nodeKeyShape1.style.fill).toBe('#000'); expect(nodeKeyShape1.style.stroke).toBe('#f00'); @@ -383,20 +337,14 @@ describe('theme', () => { graph.setItemState('edge1', 'state1', true); expect(edgeKeyShape1.style.stroke).toBe('#000'); expect(edgeKeyShape1.style.lineWidth).toBe(2); - expect(edgeLabelShape1.style.fontWeight).toBe( - LightTheme.edge.styles[0].selected.labelShape.fontWeight, - ); + expect(edgeLabelShape1.style.fontWeight).toBe(LightTheme.edge.styles[0].selected.labelShape.fontWeight); graph.setItemState('edge1', 'state2', true); - expect(JSON.stringify(edgeKeyShape1.style.lineDash)).toBe( - JSON.stringify([5, 5]), - ); + expect(JSON.stringify(edgeKeyShape1.style.lineDash)).toBe(JSON.stringify([5, 5])); expect(edgeKeyShape1.style.stroke).toBe('#000'); expect(edgeKeyShape1.style.lineWidth).toBe(2); graph.setItemState('edge1', 'state3', true); expect(edgeKeyShape1.style.stroke).toBe('#ff0'); - expect(JSON.stringify(edgeKeyShape1.style.lineDash)).toBe( - JSON.stringify([5, 5]), - ); + expect(JSON.stringify(edgeKeyShape1.style.lineDash)).toBe(JSON.stringify([5, 5])); expect(edgeKeyShape1.style.lineWidth).toBe(2); // clear node's one state @@ -405,9 +353,7 @@ describe('theme', () => { // clear edge's one state, state1 + state3 is kept graph.clearItemState('edge1', ['state2']); expect(edgeKeyShape1.style.stroke).toBe('#ff0'); - expect(JSON.stringify(edgeKeyShape1.style.lineDash)).toBe( - JSON.stringify([5, 5]), - ); + expect(JSON.stringify(edgeKeyShape1.style.lineDash)).toBe(JSON.stringify([5, 5])); expect(edgeKeyShape1.style.lineWidth).toBe(2); // clear all states @@ -498,37 +444,31 @@ describe('theme', () => { }); graph.on('afterlayout', () => { const node1 = graph.itemController.itemMap.get('node1'); - const { keyShape: nodeKeyShape1, labelShape: nodeLabelShape1 } = - node1.shapeMap; + const { keyShape: nodeKeyShape1, labelShape: nodeLabelShape1 } = node1.shapeMap; expect(nodeKeyShape1.style.fill).toBe('#f00'); expect(nodeLabelShape1.style.fill).toBe('#f00'); const node2 = graph.itemController.itemMap.get('node2'); - const { keyShape: nodeKeyShape2, labelShape: nodeLabelShape2 } = - node2.shapeMap; + const { keyShape: nodeKeyShape2, labelShape: nodeLabelShape2 } = node2.shapeMap; expect(nodeKeyShape2.style.fill).toBe('#0f0'); expect(nodeLabelShape2.style.fill).toBe('#0f0'); const node3 = graph.itemController.itemMap.get('node3'); - const { keyShape: nodeKeyShape3, labelShape: nodeLabelShape3 } = - node3.shapeMap; + const { keyShape: nodeKeyShape3, labelShape: nodeLabelShape3 } = node3.shapeMap; expect(nodeKeyShape3.style.fill).toBe('#00f'); expect(nodeLabelShape3.style.fill).toBe('#00f'); // node4 has no mapped palette, buitin theme take effects const node4 = graph.itemController.itemMap.get('node4'); - const { keyShape: nodeKeyShape4, labelShape: nodeLabelShape4 } = - node4.shapeMap; + const { keyShape: nodeKeyShape4, labelShape: nodeLabelShape4 } = node4.shapeMap; // different from map, undefined data type value will be regarded as a value to find corresponding color in palette. That is because g6 doesn't know if the value undefined is the real value or not expect(nodeKeyShape4.style.fill).toBe('#f00'); expect(nodeLabelShape4.style.fill).toBe('#f00'); // edges const edge1 = graph.itemController.itemMap.get('edge1'); - const { keyShape: edgeKeyShape1, labelShape: edgeLabelShape1 } = - edge1.shapeMap; + const { keyShape: edgeKeyShape1, labelShape: edgeLabelShape1 } = edge1.shapeMap; expect(edgeKeyShape1.style.stroke).toBe('#f00'); expect(edgeLabelShape1.style.fill).toBe('#f00'); const edge2 = graph.itemController.itemMap.get('edge2'); - const { keyShape: edgeKeyShape2, labelShape: edgeLabelShape2 } = - edge2.shapeMap; + const { keyShape: edgeKeyShape2, labelShape: edgeLabelShape2 } = edge2.shapeMap; expect(edgeKeyShape2.style.stroke).toBe('#0f0'); expect(edgeLabelShape2.style.fill).toBe('#0f0'); // edge3 has no mapped palette, buitin theme take effects @@ -558,22 +498,16 @@ describe('theme', () => { // node setState with state in builtin theme graph.setItemState('node1', 'selected', true); - expect(nodeLabelShape1.style.fontWeight).toBe( - LightTheme.node.styles[0].selected.labelShape.fontWeight, - ); + expect(nodeLabelShape1.style.fontWeight).toBe(LightTheme.node.styles[0].selected.labelShape.fontWeight); // edge setState with state in builtin theme graph.setItemState('edge1', 'selected', true); expect(edgeLabelShape1.style.fill).toBe('#0f0'); // not assigned in selected theme - expect(edgeLabelShape1.style.fontWeight).toBe( - LightTheme.edge.styles[0].selected.labelShape.fontWeight, - ); + expect(edgeLabelShape1.style.fontWeight).toBe(LightTheme.edge.styles[0].selected.labelShape.fontWeight); // node setState with state in configured spec graph.setItemState('node1', 'state1', true); expect(nodeKeyShape1.style.fill).toBe('#000'); - expect(nodeLabelShape1.style.fontWeight).toBe( - LightTheme.node.styles[0].selected.labelShape.fontWeight, - ); + expect(nodeLabelShape1.style.fontWeight).toBe(LightTheme.node.styles[0].selected.labelShape.fontWeight); graph.setItemState('node1', 'state2', true); expect(nodeKeyShape1.style.fill).toBe('#000'); expect(nodeKeyShape1.style.stroke).toBe('#f00'); @@ -585,20 +519,14 @@ describe('theme', () => { graph.setItemState('edge1', 'state1', true); expect(edgeKeyShape1.style.stroke).toBe('#000'); expect(edgeKeyShape1.style.lineWidth).toBe(2); - expect(edgeLabelShape1.style.fontWeight).toBe( - LightTheme.edge.styles[0].selected.labelShape.fontWeight, - ); + expect(edgeLabelShape1.style.fontWeight).toBe(LightTheme.edge.styles[0].selected.labelShape.fontWeight); graph.setItemState('edge1', 'state2', true); - expect(JSON.stringify(edgeKeyShape1.style.lineDash)).toBe( - JSON.stringify([5, 5]), - ); + expect(JSON.stringify(edgeKeyShape1.style.lineDash)).toBe(JSON.stringify([5, 5])); expect(edgeKeyShape1.style.stroke).toBe('#000'); expect(edgeKeyShape1.style.lineWidth).toBe(2); graph.setItemState('edge1', 'state3', true); expect(edgeKeyShape1.style.stroke).toBe('#ff0'); - expect(JSON.stringify(edgeKeyShape1.style.lineDash)).toBe( - JSON.stringify([5, 5]), - ); + expect(JSON.stringify(edgeKeyShape1.style.lineDash)).toBe(JSON.stringify([5, 5])); expect(edgeKeyShape1.style.lineWidth).toBe(2); // clear node's one state @@ -608,9 +536,7 @@ describe('theme', () => { // clear edge's one state, state1 + state3 is kept graph.clearItemState('edge1', ['state2']); expect(edgeKeyShape1.style.stroke).toBe('#ff0'); - expect(JSON.stringify(edgeKeyShape1.style.lineDash)).toBe( - JSON.stringify([5, 5]), - ); + expect(JSON.stringify(edgeKeyShape1.style.lineDash)).toBe(JSON.stringify([5, 5])); expect(edgeKeyShape1.style.lineWidth).toBe(2); // clear all states @@ -735,23 +661,13 @@ describe('theme', () => { graph.on('afterlayout', () => { // custom node's and edge's keyShape follow the light theme const node = graph.itemController.itemMap.get('node1'); - const { keyShape: nodeKeyShape, labelShape: nodeLabelShape } = - node.shapeMap; - expect(nodeKeyShape.style.fill).toBe( - LightTheme.node.styles[0].default.keyShape.fill, - ); - expect(nodeLabelShape.style.fontWeight).toBe( - LightTheme.node.styles[0].default.labelShape.fontWeight, - ); + const { keyShape: nodeKeyShape, labelShape: nodeLabelShape } = node.shapeMap; + expect(nodeKeyShape.style.fill).toBe(LightTheme.node.styles[0].default.keyShape.fill); + expect(nodeLabelShape.style.fontWeight).toBe(LightTheme.node.styles[0].default.labelShape.fontWeight); const edge = graph.itemController.itemMap.get('edge1'); - const { keyShape: edgeKeyShape, labelShape: edgeLabelShape } = - edge.shapeMap; - expect(edgeKeyShape.style.stroke).toBe( - LightTheme.edge.styles[0].default.keyShape.stroke, - ); - expect(edgeLabelShape.style.fontWeight).toBe( - LightTheme.edge.styles[0].default.labelShape.fontWeight, - ); + const { keyShape: edgeKeyShape, labelShape: edgeLabelShape } = edge.shapeMap; + expect(edgeKeyShape.style.stroke).toBe(LightTheme.edge.styles[0].default.keyShape.stroke); + expect(edgeLabelShape.style.fontWeight).toBe(LightTheme.edge.styles[0].default.labelShape.fontWeight); graph.destroy(); done(); }); diff --git a/packages/g6/tests/unit/theme-subject-spec.ts b/packages/g6/tests/unit/theme-subject-spec.ts index 1a6d107f5d4..3f85c5a5912 100644 --- a/packages/g6/tests/unit/theme-subject-spec.ts +++ b/packages/g6/tests/unit/theme-subject-spec.ts @@ -88,8 +88,7 @@ describe('theme', () => { nodeKeyShape = node.shapeMap.keyShape; keyShapeFill = nodeKeyShape.style.fill; keyShapeStroke = nodeKeyShape.style.stroke; - const { lineWidth: keyShapeLineWidth, shadowColor: keyShapeShadowColor } = - nodeKeyShape.style; + const { lineWidth: keyShapeLineWidth, shadowColor: keyShapeShadowColor } = nodeKeyShape.style; expect(keyShapeFill).toBe('rgb(230, 230, 255)'); expect(keyShapeStroke).toBe('#00f'); expect(keyShapeLineWidth).toBe(4); @@ -193,8 +192,7 @@ describe('theme', () => { nodeKeyShape = node.shapeMap.keyShape; keyShapeFill = nodeKeyShape.style.fill; keyShapeStroke = nodeKeyShape.style.stroke; - const { lineWidth: keyShapeLineWidth, shadowColor: keyShapeShadowColor } = - nodeKeyShape.style; + const { lineWidth: keyShapeLineWidth, shadowColor: keyShapeShadowColor } = nodeKeyShape.style; expect(keyShapeFill).toBe('rgb(230, 230, 255)'); expect(keyShapeStroke).toBe('#00f'); expect(keyShapeLineWidth).toBe(4); @@ -204,18 +202,12 @@ describe('theme', () => { node = graph.itemController.itemMap.get('node4'); const { keyShape } = node.shapeMap; keyShapeStroke = keyShape.style.stroke; - expect(keyShapeStroke).toBe( - LightTheme.node.styles[0].default.keyShape.stroke, - ); + expect(keyShapeStroke).toBe(LightTheme.node.styles[0].default.keyShape.stroke); graph.setItemState('node4', 'selected', true); keyShapeStroke = keyShape.style.stroke; - expect(keyShapeStroke).toBe( - LightTheme.node.styles[0].selected.keyShape.stroke, - ); - expect(keyShape.style.lineWidth).toBe( - LightTheme.node.styles[0].selected.keyShape.lineWidth, - ); + expect(keyShapeStroke).toBe(LightTheme.node.styles[0].selected.keyShape.stroke); + expect(keyShape.style.lineWidth).toBe(LightTheme.node.styles[0].selected.keyShape.lineWidth); let edge = graph.itemController.itemMap.get('edge1'); let { keyShape: edgeKeyShape } = edge.shapeMap; @@ -231,18 +223,12 @@ describe('theme', () => { edge = graph.itemController.itemMap.get('edge3'); edgeKeyShape = edge.shapeMap.keyShape; edgeKeyShapeStroke = edgeKeyShape.style.stroke; - expect(edgeKeyShapeStroke).toBe( - LightTheme.edge.styles[0].default.keyShape.stroke, - ); + expect(edgeKeyShapeStroke).toBe(LightTheme.edge.styles[0].default.keyShape.stroke); graph.setItemState('edge3', 'selected', true); edgeKeyShapeStroke = edgeKeyShape.style.stroke; - expect(edgeKeyShapeStroke).toBe( - LightTheme.edge.styles[0].selected.keyShape.stroke, - ); - expect(edgeKeyShape.style.lineWidth).toBe( - LightTheme.edge.styles[0].selected.keyShape.lineWidth, - ); + expect(edgeKeyShapeStroke).toBe(LightTheme.edge.styles[0].selected.keyShape.stroke); + expect(edgeKeyShape.style.lineWidth).toBe(LightTheme.edge.styles[0].selected.keyShape.lineWidth); graph.destroy(); done(); @@ -314,8 +300,7 @@ describe('theme', () => { nodeKeyShape = node.shapeMap.keyShape; keyShapeFill = nodeKeyShape.style.fill; keyShapeStroke = nodeKeyShape.style.stroke; - const { lineWidth: keyShapeLineWidth, shadowColor: keyShapeShadowColor } = - nodeKeyShape.style; + const { lineWidth: keyShapeLineWidth, shadowColor: keyShapeShadowColor } = nodeKeyShape.style; expect(keyShapeFill).toBe('rgb(95, 95, 146)'); expect(keyShapeStroke).toBe('#00f'); expect(keyShapeLineWidth).toBe(4); diff --git a/packages/g6/tests/unit/triangle-spec.ts b/packages/g6/tests/unit/triangle-spec.ts index 27f6f68308b..04c6a99ec7f 100644 --- a/packages/g6/tests/unit/triangle-spec.ts +++ b/packages/g6/tests/unit/triangle-spec.ts @@ -171,16 +171,12 @@ describe('node mapper', () => { keyShape: { fill: { fields: ['buStatus'], - formatter: (innerModel) => - innerModel.data.buStatus ? '#0f0' : '#f00', + formatter: (innerModel) => (innerModel.data.buStatus ? '#0f0' : '#f00'), }, lineWidth: 5, stroke: { fields: ['buStatus', 'buType'], - formatter: (innerModel) => - innerModel.data.buStatus || innerModel.data.buType - ? '#fff' - : '#000', + formatter: (innerModel) => (innerModel.data.buStatus || innerModel.data.buType ? '#fff' : '#000'), }, }, labelShape: {}, @@ -272,105 +268,48 @@ describe('state', () => { graph.setItemState('node1', 'selected', true); expect(graph.findIdByState('node', 'selected').length).toBe(1); expect(graph.findIdByState('node', 'selected')[0]).toBe('node1'); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.stroke).toBe('#0f0'); graph.setItemState('node1', 'selected', false); expect(graph.findIdByState('node', 'selected').length).toBe(0); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .lineWidth, - ).toBe(0); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.lineWidth).toBe(0); // set multiple nodes state graph.setItemState(['node1', 'node2'], 'selected', true); expect(graph.findIdByState('node', 'selected').length).toBe(2); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); - expect( - graph.itemController.itemMap.get('node2').shapeMap.keyShape.style - .lineWidth, - ).toBe(2); - expect( - graph.itemController.itemMap.get('node2').shapeMap.keyShape.style - .stroke, - ).toBe('#0f0'); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.stroke).toBe('#0f0'); + expect(graph.itemController.itemMap.get('node2').shapeMap.keyShape.style.lineWidth).toBe(2); + expect(graph.itemController.itemMap.get('node2').shapeMap.keyShape.style.stroke).toBe('#0f0'); graph.setItemState('node1', 'selected', false); expect(graph.findIdByState('node', 'selected').length).toBe(1); expect(graph.findIdByState('node', 'selected')[0]).toBe('node2'); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .lineWidth, - ).toBe(0); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.lineWidth).toBe(0); graph.setItemState(['node1', 'node2'], 'selected', false); expect(graph.findIdByState('node', 'selected').length).toBe(0); - expect( - graph.itemController.itemMap.get('node2').shapeMap.keyShape.style - .lineWidth, - ).toBe(0); + expect(graph.itemController.itemMap.get('node2').shapeMap.keyShape.style.lineWidth).toBe(0); // set multiple states graph.setItemState(['node1', 'node2'], ['selected', 'highlight'], true); expect(graph.findIdByState('node', 'selected').length).toBe(2); expect(graph.findIdByState('node', 'highlight').length).toBe(2); // should be merged styles from selected and highlight - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .lineWidth, - ).toBe(3); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .stroke, - ).toBe('#00f'); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.r, - ).toBe(30); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .opacity, - ).toBe(0.5); - expect( - graph.itemController.itemMap.get('node2').shapeMap.keyShape.style - .lineWidth, - ).toBe(3); - expect( - graph.itemController.itemMap.get('node2').shapeMap.keyShape.style - .stroke, - ).toBe('#00f'); - expect( - graph.itemController.itemMap.get('node2').shapeMap.keyShape.style.r, - ).toBe(30); - expect( - graph.itemController.itemMap.get('node2').shapeMap.keyShape.style - .opacity, - ).toBe(0.5); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.lineWidth).toBe(3); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.stroke).toBe('#00f'); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.r).toBe(30); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.opacity).toBe(0.5); + expect(graph.itemController.itemMap.get('node2').shapeMap.keyShape.style.lineWidth).toBe(3); + expect(graph.itemController.itemMap.get('node2').shapeMap.keyShape.style.stroke).toBe('#00f'); + expect(graph.itemController.itemMap.get('node2').shapeMap.keyShape.style.r).toBe(30); + expect(graph.itemController.itemMap.get('node2').shapeMap.keyShape.style.opacity).toBe(0.5); // clear states graph.clearItemState(['node1', 'node2']); expect(graph.findIdByState('node', 'selected').length).toBe(0); expect(graph.findIdByState('node', 'highlight').length).toBe(0); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.r, - ).toBe(16); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .lineWidth, - ).toBe(0); - expect( - graph.itemController.itemMap.get('node1').shapeMap.keyShape.style - .opacity, - ).toBe(1); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.r).toBe(16); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.lineWidth).toBe(0); + expect(graph.itemController.itemMap.get('node1').shapeMap.keyShape.style.opacity).toBe(1); graph.destroy(); done(); diff --git a/packages/g6/tsconfig.json b/packages/g6/tsconfig.json index ef3e0141089..8d965967ee6 100644 --- a/packages/g6/tsconfig.json +++ b/packages/g6/tsconfig.json @@ -1,24 +1,17 @@ { "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, + "experimentalDecorators": true, + "lib": ["DOM", "ESNext"], + "outDir": "lib", "pretty": true, - "lib": ["dom", "esnext"], - "types": ["@types/jest"], - "skipLibCheck": true, + "resolveJsonModule": true, + "sourceMap": true, "sourceRoot": "src", - "baseUrl": "src", - "resolveJsonModule": true + "strict": false // should be true later }, - "include": ["src/**/*"], - "exclude": ["node_modules"] + "exclude": ["node_modules", "dist", "lib", "esm"], + "extends": "../../tsconfig.json", + "include": ["src/**/*"] } diff --git a/packages/g6/typedoc.config.js b/packages/g6/typedoc.config.js deleted file mode 100644 index 2e19b043bfa..00000000000 --- a/packages/g6/typedoc.config.js +++ /dev/null @@ -1,40 +0,0 @@ -const path = require('path'); -const outputDir = path.resolve(__dirname, '../site/docs/_apis'); -console.log('outputDir', outputDir); - -module.exports = { - includes: ['./src', './node_modules/@antv/layout'], - entryPoints: [ - /** graph */ - 'src/api-doc/graph.ts', - /** plugins */ - 'src/api-doc/plugins.ts', - /** behaviors */ - 'src/api-doc/behaviors.ts', - /** types */ - 'src/api-doc/types.ts', - /** util */ - 'src/api-doc/util.ts', - /** layout */ - 'src/api-doc/layout.ts', - /** item */ - 'src/api-doc/item.ts', - ], - out: outputDir, - hideGenerator: true, - includeVersion: true, - excludePrivate: true, - excludeProtected: true, - // excludeExternals: true, - plugin: 'typedoc-plugin-markdown', - hideInPageTOC: true, - // hideBreadcrumbs: true, - hidePageTitle: true, - theme: 'markdown', - categoryOrder: ['Plugins', 'Behaviors', '*'], - groupOrder: ['Variables', 'Functions', 'Interfaces', '*'], - name: 'Overview', - readme: 'none', - // https://github.com/tgreyuk/typedoc-plugin-markdown/blob/master/packages/typedoc-plugin-markdown/src/theme.ts#L31 - filenameSeparator: '/', -}; diff --git a/packages/react-node/.editorconfig b/packages/react-node/.editorconfig deleted file mode 100644 index e717f5eb638..00000000000 --- a/packages/react-node/.editorconfig +++ /dev/null @@ -1,13 +0,0 @@ -# http://editorconfig.org -root = true - -[*] -indent_style = space -indent_size = 2 -end_of_line = lf -charset = utf-8 -trim_trailing_whitespace = true -insert_final_newline = true - -[*.md] -trim_trailing_whitespace = false diff --git a/packages/react-node/.eslintrc.js b/packages/react-node/.eslintrc.js deleted file mode 100644 index 28983409455..00000000000 --- a/packages/react-node/.eslintrc.js +++ /dev/null @@ -1,3 +0,0 @@ -module.exports = { - extends: require.resolve('@umijs/lint/dist/config/eslint'), -}; diff --git a/packages/react-node/.gitignore b/packages/react-node/.gitignore index cf89318df8a..fb4ea89661d 100644 --- a/packages/react-node/.gitignore +++ b/packages/react-node/.gitignore @@ -1,4 +1,3 @@ -node_modules /dist .dumi/tmp .dumi/tmp-test diff --git a/packages/react-node/.prettierignore b/packages/react-node/.prettierignore deleted file mode 100644 index 6a50e206c7f..00000000000 --- a/packages/react-node/.prettierignore +++ /dev/null @@ -1,2 +0,0 @@ -/dist -*.yaml diff --git a/packages/react-node/package.json b/packages/react-node/package.json index f181a00cfee..79f32b10bcb 100644 --- a/packages/react-node/package.json +++ b/packages/react-node/package.json @@ -24,7 +24,6 @@ "@antv/util": "^3.3.5" }, "devDependencies": { - "@ant-design/icons": "^5.2.6", "@antv/g-canvas": "^1.11.22", "@antv/g-svg": "^1.10.21", "@antv/g-webgl": "^1.9.29", diff --git a/packages/react-node/tsconfig.json b/packages/react-node/tsconfig.json index 951256c3b2a..328eeecfe09 100644 --- a/packages/react-node/tsconfig.json +++ b/packages/react-node/tsconfig.json @@ -1,16 +1,14 @@ { "compilerOptions": { - "strict": true, + "baseUrl": "./", "declaration": true, - "skipLibCheck": true, - "esModuleInterop": true, "jsx": "react", - "baseUrl": "./", "paths": { "@@/*": [".dumi/tmp/*"], "@antv/g6-react-node": ["src"], "@antv/g6-react-node/*": ["src/*", "*"] } }, + "extends": "../../tsconfig.json", "include": [".dumirc.ts", "src/**/*"] } diff --git a/packages/site/.dumirc.ts b/packages/site/.dumirc.ts index 2152df362a4..ac3794c3bf0 100644 --- a/packages/site/.dumirc.ts +++ b/packages/site/.dumirc.ts @@ -1,31 +1,6 @@ -import { Extractor, ExtractorConfig } from '@microsoft/api-extractor'; import { defineConfig } from 'dumi'; -import fs from 'fs'; -import path from 'path'; import { homepage, repository, version } from './package.json'; -const getExtraLib = () => { - try { - const extractorConfig = ExtractorConfig.loadFileAndPrepare(path.resolve('./api-extractor.json')); - const extractorResult = Extractor.invoke(extractorConfig, { - localBuild: true, - showVerboseMessages: true, - }); - if (extractorResult.succeeded) { - const typeFilePath = extractorResult.extractorConfig.untrimmedFilePath; - if (typeFilePath) { - return `declare module '${name}'{ - ${fs.readFileSync(typeFilePath, `utf8`)} - }`; - } - } - } catch (e) { - // eslint-disable-next-line no-console - console.warn(`api-extractor warn: ${e.message}`); - } - return ''; -}; - export default defineConfig({ locales: [ { id: 'zh', name: '中文' }, @@ -299,9 +274,7 @@ export default defineConfig({ // 第一个分块的大小 splitPaneMainSize: '62%', }, - playground: { - extraLib: getExtraLib(), - }, + playground: {}, announcement: { zh: '', en: '', diff --git a/packages/site/.eslintignore b/packages/site/.eslintignore deleted file mode 100644 index b1fc0c82cdd..00000000000 --- a/packages/site/.eslintignore +++ /dev/null @@ -1,22 +0,0 @@ -build/ -coverage/ -lib/ -dist/ -mocks/ -node_modules/ -demos/ -.cache -public -bin -esm/ -es/ -examples/ -tests/ -stories/ -gatsby-browser.js -site/ -webpack.*.js -gatsby-*.js -global.d.ts -jest.config.js -.eslintrc.* diff --git a/packages/site/.eslintrc.js b/packages/site/.eslintrc.js deleted file mode 100644 index b9c5c5d6d2f..00000000000 --- a/packages/site/.eslintrc.js +++ /dev/null @@ -1,47 +0,0 @@ -module.exports = { - extends: [require.resolve('@umijs/fabric/dist/eslint')], - globals: { - $: true, - _: true, - }, - rules: { - 'no-bitwise': 0, - 'import/order': 0, - 'no-plusplus': 0, - 'no-console': ['error', { allow: ['warn', 'error'] }], - 'operator-assignment': 0, - 'consistent-return': 0, - 'lines-between-class-members': 0, - 'class-methods-use-this': 0, - 'lines-between-class-members': 0, - 'no-multi-assign': 0, - 'no-continue': 0, - 'no-underscore-dangle': 0, - 'no-useless-constructor': 0, - 'prefer-destructuring': 0, - 'guard-for-in': 0, - 'no-restricted-globals': 0, - 'max-classes-per-file': 0, - '@typescript-eslint/no-invalid-this': 0, - '@typescript-eslint/no-this-alias': 0, - '@typescript-eslint/array-type': 0, - 'import/export': 0, - // 后面需要去掉 - 'no-restricted-syntax': 0, - 'prefer-spread': 0, - '@typescript-eslint/camelcase': 0, - 'no-loop-func': 0, - '@typescript-eslint/no-loop-func': 0, - '@typescript-eslint/no-redeclare': 0, - '@typescript-eslint/no-shadow': 0, - '@typescript-eslint/no-unused-vars': 0, - 'no-param-reassign': 0, - 'import/no-extraneous-dependencies': 0, - 'no-unused-expressions': 0, - 'dot-notation': 0, - 'array-callback-return': 0, - 'one-var': 0, - 'no-lonely-if': 0, - 'no-sequences': 0 - }, -}; diff --git a/packages/site/.gitignore b/packages/site/.gitignore index b5564dd557e..8f9dec8ccfe 100644 --- a/packages/site/.gitignore +++ b/packages/site/.gitignore @@ -1,14 +1,6 @@ -/node_modules /dist -/example/node_modules -/example/dist -/example/.dumi/theme -/example/.dumi/tmp -/example/.dumi/tmp-production .dumi/tmp .dumi/tmp-production -.DS_Store ## api doc -docs/_apis .translate-info.txt \ No newline at end of file diff --git a/packages/site/.prettierrc b/packages/site/.prettierrc deleted file mode 100644 index 764fbde2e82..00000000000 --- a/packages/site/.prettierrc +++ /dev/null @@ -1,11 +0,0 @@ -{ - "singleQuote": true, - "trailingComma": "all", - "printWidth": 120, - "overrides": [ - { - "files": ".prettierrc", - "options": { "parser": "json" } - } - ] -} diff --git a/packages/site/.translate-info.txt b/packages/site/.translate-info.txt deleted file mode 100644 index 3d34a41cf32..00000000000 --- a/packages/site/.translate-info.txt +++ /dev/null @@ -1,61 +0,0 @@ - -file: docs/apis/.nojekyll has been translated -file: docs/apis/README.en.md has been translated -Error: ENOENT: no such file or directory, lstat 'docs/apis/classes/graph/Graph.en.md' -TRANSLATE ERROR: docs/apis/README.zh.md:docs/apis/classes/graph/Graph.zh.md - -Error: ENOENT: no such file or directory, lstat 'docs/apis/interfaces/behaviors/ActivateRelationsOptions.en.md' -Error: ENOENT: no such file or directory, lstat 'docs/apis/interfaces/behaviors/BrushSelectOptions.en.md' -TRANSLATE ERROR: docs/apis/classes/graph-Graph.zh.md:docs/apis/interfaces/behaviors/BrushSelectOptions.zh.md - -Error: ENOENT: no such file or directory, lstat 'docs/apis/interfaces/behaviors/CollapseExpandComboOptions.en.md' -Error: ENOENT: no such file or directory, lstat 'docs/apis/interfaces/behaviors/DragCanvasOptions.en.md' -Error: ENOENT: no such file or directory, lstat 'docs/apis/interfaces/behaviors/DragComboOptions.en.md' -Error: ENOENT: no such file or directory, lstat 'docs/apis/interfaces/behaviors/DragNodeOptions.en.md' -Error: ENOENT: no such file or directory, lstat 'docs/apis/interfaces/behaviors/HoverActivateOptions.en.md' -Error: ENOENT: no such file or directory, lstat 'docs/apis/interfaces/behaviors/IG6GraphEvent.en.md' -TRANSLATE ERROR: docs/apis/interfaces/plugins-LegendConfig.zh.md:docs/apis/interfaces/behaviors/IG6GraphEvent.zh.md - -Error: ENOENT: no such file or directory, lstat 'docs/apis/interfaces/behaviors/Options.en.md' -Error: ENOENT: no such file or directory, lstat 'docs/apis/interfaces/behaviors/OrbitCanvas3DOptions.en.md' -Error: ENOENT: no such file or directory, lstat 'docs/apis/interfaces/behaviors/RotateCanvas3DOptions.en.md' -Error: ENOENT: no such file or directory, lstat 'docs/apis/interfaces/behaviors/TrackCanvas3DOptions.en.md' -Error: ENOENT: no such file or directory, lstat 'docs/apis/interfaces/behaviors/ZoomCanvas3DOptions.en.md' -Error: ENOENT: no such file or directory, lstat 'docs/apis/interfaces/behaviors/ZoomCanvasOptions.en.md' -Error: ENOENT: no such file or directory, lstat 'docs/apis/interfaces/graph/GraphData.en.md' -Error: ENOENT: no such file or directory, lstat 'docs/apis/interfaces/graph/IGraph.en.md' -TRANSLATE ERROR: docs/apis/interfaces/types-GraphData.zh.md:docs/apis/interfaces/graph/IGraph.zh.md - -Error: ENOENT: no such file or directory, lstat 'docs/apis/interfaces/graph/Specification.en.md' -TRANSLATE ERROR: docs/apis/interfaces/types-IG6GraphEvent.en.md:docs/apis/interfaces/graph/Specification.zh.md - -Error: ENOENT: no such file or directory, lstat 'docs/apis/interfaces/item/NodeUserModelData.en.md' -Error: ENOENT: no such file or directory, lstat 'docs/apis/interfaces/layout/CircularLayoutOptions.en.md' -Error: ENOENT: no such file or directory, lstat 'docs/apis/interfaces/layout/ComboCombinedLayoutOptions.en.md' -Error: ENOENT: no such file or directory, lstat 'docs/apis/interfaces/layout/ConcentricLayoutOptions.en.md' -Error: ENOENT: no such file or directory, lstat 'docs/apis/interfaces/layout/D3ForceLayoutOptions.en.md' -Error: ENOENT: no such file or directory, lstat 'docs/apis/interfaces/layout/DagreLayoutOptions.en.md' -Error: ENOENT: no such file or directory, lstat 'docs/apis/interfaces/layout/ForceAtlas2LayoutOptions.en.md' -Error: ENOENT: no such file or directory, lstat 'docs/apis/interfaces/layout/ForceLayoutOptions.en.md' -TRANSLATE ERROR: docs/apis/modules/behaviors.en.md:docs/apis/interfaces/layout/ForceLayoutOptions.zh.md - -Error: ENOENT: no such file or directory, lstat 'docs/apis/interfaces/layout/FruchtermanLayoutOptions.en.md' -Error: ENOENT: no such file or directory, lstat 'docs/apis/interfaces/layout/GridLayoutOptions.en.md' -Error: ENOENT: no such file or directory, lstat 'docs/apis/interfaces/layout/MDSLayoutOptions.en.md' -Error: ENOENT: no such file or directory, lstat 'docs/apis/interfaces/layout/RadialLayoutOptions.en.md' -Error: ENOENT: no such file or directory, lstat 'docs/apis/interfaces/plugins/FisheyeConfig.en.md' -Error: ENOENT: no such file or directory, lstat 'docs/apis/interfaces/plugins/GridConfig.en.md' -Error: ENOENT: no such file or directory, lstat 'docs/apis/interfaces/plugins/HistoryConfig.en.md' -Error: ENOENT: no such file or directory, lstat 'docs/apis/interfaces/plugins/LegendConfig.en.md' -Error: ENOENT: no such file or directory, lstat 'docs/apis/interfaces/plugins/MenuConfig.en.md' -Error: ENOENT: no such file or directory, lstat 'docs/apis/interfaces/plugins/MiniMapConfig.en.md' -Error: ENOENT: no such file or directory, lstat 'docs/apis/interfaces/plugins/ToolbarConfig.en.md' -Error: ENOENT: no such file or directory, lstat 'docs/apis/interfaces/plugins/TooltipConfig.en.md' -file: undefined has been translated -file: undefined has been translated -Error: ENOENT: no such file or directory, lstat 'docs/apis/modules/item.en.md' -Error: ENOENT: no such file or directory, lstat 'docs/apis/modules/layout.en.md' -file: undefined has been translated -file: undefined has been translated -file: undefined has been translated -file: undefined has been translated \ No newline at end of file diff --git a/packages/site/api-extractor.json b/packages/site/api-extractor.json deleted file mode 100644 index aa8cd9927fa..00000000000 --- a/packages/site/api-extractor.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "mainEntryPointFilePath": "/lib/index.d.ts", - "apiReport": { - "enabled": false - }, - "docModel": { - "enabled": false - }, - "dtsRollup": { - "enabled": true - }, - "tsdocMetadata": { - "enabled": false - } -} diff --git a/packages/site/docs/apis/.nojekyll b/packages/site/docs/apis/.nojekyll deleted file mode 100644 index 7912a321ae6..00000000000 --- a/packages/site/docs/apis/.nojekyll +++ /dev/null @@ -1,5 +0,0 @@ ---- -title: ---- - -TypeDoc added this file to prevent GitHub Pages from using Jekyll. You can turn off this behavior by setting the `githubPages` option to false. \ No newline at end of file diff --git a/packages/site/package.json b/packages/site/package.json index 6e83ec486ef..1c96f834fb8 100644 --- a/packages/site/package.json +++ b/packages/site/package.json @@ -27,13 +27,12 @@ "build": "dumi build", "deploy": "npm run build && gh-pages -d dist", "develop": "dumi dev", + "find-unused-demos": "node ./scripts/find-unused-demos.js", "preview": "dumi preview", "start": "npm run develop", - "translate": "node translate-api-doc.mjs", - "find-unused-demos": "node ./scripts/find-unused-demos.js" + "translate": "node translate-api-doc.mjs" }, "dependencies": { - "@ant-design/icons": "^5.2.6", "@antv/algorithm": "^0.1.26", "@antv/chart-node-g6": "^0.0.3", "@antv/dumi-theme-antv": "^0.4.4", @@ -45,22 +44,10 @@ "@antv/layout-gpu": "^1.1.5", "@antv/layout-wasm": "^1.3.4", "@antv/util": "^2.0.9", - "@antv/vis-predict-engine": "^0.1.1", - "@faker-js/faker": "^8.0.2", - "@microsoft/api-extractor": "^7.33.6", "antd": "^5.10.2", "dumi": "^2.2.14", "fs-extra": "latest", - "google-translate-api-x": "^10.6.7", "insert-css": "^2.0.0", - "stats.js": "^0.17.0", - "typedoc": "^0.24.8", - "typedoc-plugin-markdown": "^3.14.0", - "typescript": "5.1.6" - }, - "devDependencies": { - "@types/node": "13.11.1", - "cross-env": "^7.0.3", - "prettier": "^2.8.8" + "stats.js": "^0.17.0" } } diff --git a/packages/site/scripts/find-unused-demos.js b/packages/site/scripts/find-unused-demos.js deleted file mode 100644 index dc930cf698a..00000000000 --- a/packages/site/scripts/find-unused-demos.js +++ /dev/null @@ -1,47 +0,0 @@ -const fs = require('fs'); -const path = require('path'); - -async function traverseDirectory(dir) { - const files = fs.readdirSync(dir); - - for (const file of files) { - const fullPath = path.join(dir, file); - const stat = fs.statSync(fullPath); - - if (stat.isDirectory()) { - if (file === 'demo') { - readMetaAndFiles(fullPath); - } - await traverseDirectory(fullPath); - } - } -} - -// 定义一个函数来读取 meta.json 文件和目录中的所有文件名 -function readMetaAndFiles(dir) { - try { - const metaPath = path.join(dir, 'meta.json'); - const metaExists = fs.existsSync(metaPath); - - const files = fs.readdirSync(dir).filter((file) => file !== 'meta.json'); - - if (metaExists) { - // 读取并打印 meta.json 内容 - const metaData = JSON.parse(fs.readFileSync(metaPath, 'utf8')); - - const filenameInMeta = metaData.demos.map((demo) => demo.filename); - - // 找出 meta.json 中没有的文件 - - const unusedFiles = files.filter((file) => !filenameInMeta.includes(file)); - - unusedFiles.forEach((name) => { - console.log(path.join(dir, name)); - }); - } - } catch (error) {} -} - -// 开始遍历给定的目录 -const startDirectory = 'examples'; // 替换为你的目录路径 -traverseDirectory(startDirectory).then(() => console.log('Traversal complete.')); diff --git a/packages/site/translate-api-doc.mjs b/packages/site/translate-api-doc.mjs deleted file mode 100644 index 358026de51a..00000000000 --- a/packages/site/translate-api-doc.mjs +++ /dev/null @@ -1,110 +0,0 @@ -import fs from 'fs'; -import fsExtra from 'fs-extra'; -// import translate from 'google-translate-api-x'; -import { readFile, writeFile } from 'node:fs/promises'; - -/** - * A workaround - * because of `readdir` doesn't work with { recursive: true } - * see : https://github.com/nodejs/node/issues/48858 - */ -var walk = (dir) => { - try { - var results = []; - var list = fs.readdirSync(dir); - list.forEach((file) => { - file = dir + '/' + file; - var stat = fs.statSync(file); - if (stat && stat.isDirectory()) { - /* Recurse into a subdirectory */ - results = results.concat(walk(file)); - } else { - /* Is a file */ - results.push(file); - } - }); - return results; - } catch (error) { - return []; - } -}; - -const TEMP_DOC_FILE_PATH = 'docs/_apis'; -const DOC_FILE_PATH = 'docs/apis'; - -let errorMessage = ``; - -const main = async () => { - // if node.js version not equal 18 ,throw error - - const RawFiles = walk(TEMP_DOC_FILE_PATH); //Readdir(TEMP_DOC_FILE_PATH, { recursive: true }); - // const files = await readdir(dirPath, { recursive: true }); // it is a bug: https://github.com/nodejs/node/issues/48858 - const AllFiles = walk(DOC_FILE_PATH, { recursive: true }); - - for (let i = 0; i < RawFiles.length; i++) { - let file = AllFiles[i]; - let rawFile = RawFiles[i]; - - const en_path = rawFile.replace('.md', '.en.md').replace(TEMP_DOC_FILE_PATH, DOC_FILE_PATH); - const zh_path = rawFile.replace('.md', '.zh.md').replace(TEMP_DOC_FILE_PATH, DOC_FILE_PATH); - let has_en_file = false; - let has_zh_file = false; - - try { - has_en_file = fs.lstatSync(en_path).isFile(); - has_zh_file = fs.lstatSync(zh_path).isFile(); - } catch (error) { - errorMessage = errorMessage + '\n' + error; - } - - if (has_en_file && has_zh_file) { - errorMessage = errorMessage + '\n' + `file: ${file} has been translated`; - console.log(`file: ${file} has been translated`); - continue; - } - - const content = await readFile(rawFile); - - const zh_file_name = zh_path.split('/').pop().split('.')[0]; - const en_file_name = en_path.split('/').pop().split('.')[0]; - - const zh_header = `--- -title: ${zh_file_name} ---- - -> 📋 中文文档还在翻译中... 欢迎PR - -`; - const en_header = `--- -title: ${en_file_name} ---- - -`; - const en_content = content.toString().replaceAll('.md', '.en.md'); - const zh_content = content.toString().replaceAll('.md', '.zh.md'); - - /** create en_US file */ - - await fsExtra.ensureFile(en_path); - await writeFile(en_path, en_header + en_content); - - let hasTranslated = false; - try { - hasTranslated = fs.lstatSync(zh_path).isFile(); - } catch (error) {} - - if (!hasTranslated) { - // const res = await translate(zh_content, { from: 'en', to: 'zh-CN' }).catch((error) => { - // errorMessage = errorMessage + '\n' + `TRANSLATE ERROR: ${file}:${zh_path} \n `; - // return { text: '' }; - // }); - // writeFile(zh_path, zh_header + res.text); - writeFile(zh_path, zh_header + zh_content); - } - } - fs.writeFileSync('.translate-info.txt', errorMessage); - // rm('docs/apis/modules.en.md'); - // rm('docs/apis/modules.zh.md'); -}; - -main(); diff --git a/packages/site/tsconfig.json b/packages/site/tsconfig.json index 4158ac937cc..775098c1823 100644 --- a/packages/site/tsconfig.json +++ b/packages/site/tsconfig.json @@ -1,15 +1,13 @@ { + "extends": "../../tsconfig.json", "compilerOptions": { "baseUrl": ".", - "target": "ESNext", "jsx": "react", "lib": ["dom"], - "types": ["node"], "paths": { "@antv/g6": ["../g6/lib/index"] }, "typeRoots": ["global.d.ts"] }, "include": ["example/**/*"], - "exclude": ["node_modules"] } diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 00000000000..74a5c6362e7 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "allowSyntheticDefaultImports": true, + "esModuleInterop": true, + "forceConsistentCasingInFileNames": true, + "isolatedModules": true, + "module": "esnext", + "moduleResolution": "Node", + "resolveJsonModule": true, + "skipLibCheck": true, + "sourceMap": true, + "strict": true, + "target": "esnext", + "types": ["node", "@types/jest"] + }, + "exclude": ["node_modules"] +}