refactor: utils and it's tests (#5356)

* refactor: use same console function

* test: add test case for math

* chore: fix lint

* test: fix ci
This commit is contained in:
hustcc 2024-01-19 09:58:10 +08:00 committed by GitHub
parent 98a213ab70
commit 3c96d53d1e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
37 changed files with 206 additions and 117 deletions

View File

@ -20,6 +20,7 @@ import { EdgeStyleSet, NodeStyleSet } from '../types/theme';
import { GROUP_ANIMATE_STYLES, animateShapes, getShapeAnimateBeginStyles, stopAnimate } from '../utils/animate';
import { isArrayOverlap } from '../utils/array';
import { cloneJSON } from '../utils/data';
import { warn } from '../utils/invariant';
import { DEFAULT_MAPPER } from '../utils/mapper';
import { combineBounds, getShapeLocalBoundsByStyle, mergeStyles, updateShapes } from '../utils/shape';
import { isEncode } from '../utils/type';
@ -205,7 +206,7 @@ export default abstract class Item implements IItem {
false,
(id) => {
if (RESERVED_SHAPE_IDS.includes(id)) {
console.warn(
warn(
`Shape with id ${id} is reserved and should be returned in draw function, if the shape with ${id} returned by afterDraw is a new one, it will not be added to the group.`,
);
return false;

View File

@ -1,5 +1,6 @@
import type { ID, IG6GraphEvent } from '../../types';
import { Behavior } from '../../types/behavior';
import { warn } from '../../utils/invariant';
const KEYBOARD_TRIGGERS = ['shift', 'ctrl', 'alt', 'meta'] as const;
const MOUSE_TRIGGERS = ['pointerenter', 'click'] as const;
@ -67,7 +68,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!`);
warn(`Invalid trigger option "${options.trigger}" for activate-relations behavior!`);
this.options.trigger = DEFAULT_OPTIONS.trigger;
}
this.prevEdgeIds = [];

View File

@ -5,6 +5,7 @@ import { Point } from '../../types/common';
import { IG6GraphEvent } from '../../types/event';
import { ITEM_TYPE } from '../../types/item';
import { diffSet, intersectSet, unionSet } from '../../utils/array';
import { warn } from '../../utils/invariant';
import { getEdgesBetween } from '../../utils/item';
import rectSelector from '../selector/rect';
@ -108,7 +109,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!`);
warn(`Invalid trigger option "${options.trigger}" for brush-select behavior!`);
this.options.trigger = DEFAULT_OPTIONS.trigger;
}
}

View File

@ -2,6 +2,7 @@ import { ID } from '@antv/graphlib';
import { Behavior } from '../../types/behavior';
import { Point } from '../../types/common';
import { IG6GraphEvent } from '../../types/event';
import { warn } from '../../utils/invariant';
const ALLOWED_TRIGGERS = ['shift', 'ctrl', 'alt', 'meta'] as const;
type Trigger = (typeof ALLOWED_TRIGGERS)[number];
@ -73,7 +74,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!`);
warn(`Invalid trigger option "${options.trigger}" for click-select behavior!`);
this.options.trigger = DEFAULT_OPTIONS.trigger;
}
}

View File

@ -1,5 +1,6 @@
import { Behavior } from '../../types/behavior';
import { IG6GraphEvent } from '../../types/event';
import { warn } from '../../utils/invariant';
const ALLOWED_TRIGGERS = ['click', 'dblclick'] as const;
type Trigger = (typeof ALLOWED_TRIGGERS)[number];
@ -46,7 +47,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!`);
warn(`Invalid trigger option "${options.trigger}" for collapse-expand-tree behavior!`);
this.options.trigger = DEFAULT_OPTIONS.trigger;
}
}
@ -80,7 +81,7 @@ export class CollapseExpandTree extends Behavior {
const model = this.graph.getNodeData(itemId);
if (!model) {
console.warn(`Node with id ${itemId} is not exist`);
warn(`Node with id ${itemId} is not exist`);
return;
}
this.graph.frontItem(itemId);

View File

@ -1,8 +1,8 @@
import type { IG6GraphEvent } from '../../types';
import { Behavior } from '../../types/behavior';
import { EdgeDisplayModelData } from '../../types/edge';
import { warn } from '../../utils/invariant';
import { generateEdgeID } from '../../utils/item';
import { warn } from '../../utils/warn';
const KEYBOARD_TRIGGERS = ['shift', 'ctrl', 'control', 'alt', 'meta'] as const;
const EVENT_TRIGGERS = ['click', 'drag'] as const;
@ -70,23 +70,21 @@ export class CreateEdge extends Behavior {
validateOptions(options: Partial<CreateEdgeOptions>) {
if (options.trigger && !EVENT_TRIGGERS.includes(options.trigger)) {
warn({
optionName: `create-edge.trigger`,
shouldBe: EVENT_TRIGGERS,
now: options.trigger,
scope: 'behavior',
});
const optionName = `create-edge.trigger`;
const shouldBe = EVENT_TRIGGERS;
const now = options.trigger;
warn(`Invalid option, ${optionName} must be one of ${shouldBe.join(', ')}, but got ${now}.`);
this.options.trigger = DEFAULT_OPTIONS.trigger;
}
if (options.secondaryKey && !KEYBOARD_TRIGGERS.includes(options.secondaryKey)) {
warn({
optionName: `create-edge.secondaryKey`,
shouldBe: KEYBOARD_TRIGGERS,
now: options.secondaryKey,
scope: 'behavior',
});
const optionName = `create-edge.secondaryKey`;
const shouldBe = KEYBOARD_TRIGGERS;
const now = options.secondaryKey;
warn(`Invalid option, ${optionName} must be one of ${shouldBe.join(', ')}, but got ${now}.`);
this.options.secondaryKey = DEFAULT_OPTIONS.secondaryKey;
}
}

View File

@ -2,6 +2,7 @@ import { isNumber } from '@antv/util';
import { ID, IG6GraphEvent } from '../../types';
import { Behavior } from '../../types/behavior';
import { Point } from '../../types/common';
import { warn } from '../../utils/invariant';
const VALID_TRIGGERS = ['drag', 'directionKeys'];
const DRAG_DURATION = 250;
@ -81,7 +82,7 @@ export class DragCanvas extends Behavior {
constructor(options: Partial<DragCanvasOptions>) {
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.`);
warn(`The trigger ${finalOptions.trigger} is not valid, 'drag' will take effect.`);
finalOptions.trigger = 'drag';
}
super(finalOptions);

View File

@ -5,6 +5,7 @@ import { Behavior } from '../../types/behavior';
import { Point } from '../../types/common';
import { IG6GraphEvent } from '../../types/event';
import { graphComboTreeDfs } from '../../utils/data';
import { warn } from '../../utils/invariant';
const DELEGATE_SHAPE_ID = 'g6-drag-combo-delegate-shape';
@ -198,7 +199,7 @@ export class DragCombo extends Behavior {
this.originPositions = this.selectedComboIds
.map((id) => {
if (!this.graph.getComboData(id)) {
console.warn('combo does not exist', id);
warn(`combo with id="${id}" does not exist.`);
return;
}
const bounds = this.graph.getRenderBBox(id, true, enableTransient);

View File

@ -5,6 +5,7 @@ import { Behavior } from '../../types/behavior';
import { Point } from '../../types/common';
import { IG6GraphEvent } from '../../types/event';
import { graphComboTreeDfs } from '../../utils/data';
import { warn } from '../../utils/invariant';
import { isPointPreventPolylineOverlap, isPolylineWithObstacleAvoidance } from '../../utils/polyline';
const DELEGATE_SHAPE_ID = 'g6-drag-node-delegate-shape';
@ -239,7 +240,7 @@ export class DragNode extends Behavior {
this.originPositions = this.selectedNodeIds
.map((id) => {
if (!this.graph.getNodeData(id)) {
console.warn('node does not exist', id);
warn('node with id = "${id}" does not exist');
return;
}
const { x, y } = this.graph.getNodeData(id).data as {

View File

@ -1,5 +1,6 @@
import { CameraType } from '@antv/g';
import { IG6GraphEvent } from '../../types/event';
import { warn } from '../../utils/invariant';
import { RotateCanvas3D } from './rotate-canvas-3d';
// TODO: truck canvas
@ -44,7 +45,7 @@ export class OrbitCanvas3D extends RotateCanvas3D {
constructor(options: Partial<OrbitCanvas3DOptions>) {
const finalOptions = Object.assign({}, DEFAULT_OPTIONS, options);
if (!VALID_TRIGGERS.includes(finalOptions.trigger)) {
console.warn(
warn(
`The trigger ${
finalOptions.trigger
} is not valid for track-canvas-3d behavior, "drag" will take effect instead. Only "${VALID_TRIGGERS.join(

View File

@ -2,6 +2,7 @@ import { ICamera } from '@antv/g';
import { Behavior } from '../../types/behavior';
import { Point } from '../../types/common';
import { IG6GraphEvent } from '../../types/event';
import { warn } from '../../utils/invariant';
const VALID_TRIGGERS = ['drag', 'directionKeys'];
@ -57,7 +58,7 @@ export class RotateCanvas3D extends Behavior {
constructor(options: Partial<RotateCanvas3DOptions>) {
const finalOptions = Object.assign({}, DEFAULT_OPTIONS, options);
if (!VALID_TRIGGERS.includes(finalOptions.trigger)) {
console.warn(
warn(
`The trigger ${
finalOptions.trigger
} is not valid for rotate-canvas-3d behavior, "drag" will take effect instead. Only "${VALID_TRIGGERS.join(

View File

@ -1,6 +1,7 @@
import { isBoolean, isNumber, isObject } from '@antv/util';
import { ID, IG6GraphEvent } from '../../types';
import { Behavior } from '../../types/behavior';
import { warn } from '../../utils/invariant';
interface ScrollCanvasOptions {
/**
@ -312,8 +313,7 @@ function initZoomKey(zoomKey?: string | string[]) {
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)}`);
if (!keyIsValid) warn(`Invalid zoomKey: ${zoomKey}, please use a valid zoomKey: ${JSON.stringify(ALLOW_EVENTS)}`);
return keyIsValid;
});

View File

@ -1,5 +1,6 @@
import type { IG6GraphEvent } from '../../types';
import { Behavior } from '../../types/behavior';
import { warn } from '../../utils/invariant';
const DEFAULT_TRIGGER = 'ctrl';
const ALLOW_TRIGGERS = ['shift', 'ctrl', 'alt', 'control'] as const;
@ -44,7 +45,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!`);
warn(`Invalid trigger option "${options.trigger}" for shortcuts-call behavior!`);
this.options.trigger = DEFAULT_OPTIONS.trigger;
}
if (options.combinedKey === this.options.trigger) {
@ -80,7 +81,7 @@ export class ShortcutsCall extends Behavior {
}
if (!graph[functionName]) {
console.warn(`G6: Invalid functionName option: "${functionName}" for shortcuts-call behavior!`);
warn(`Invalid functionName option: "${functionName}" for shortcuts-call behavior!`);
return {};
}
if (!this.triggerKeydown) return;

View File

@ -1,5 +1,6 @@
import { CameraType } from '@antv/g';
import { IG6GraphEvent } from '../../types/event';
import { warn } from '../../utils/invariant';
import { RotateCanvas3D } from './rotate-canvas-3d';
// TODO: truck canvas
@ -44,7 +45,7 @@ export class TrackCanvas3D extends RotateCanvas3D {
constructor(options: Partial<TrackCanvas3DOptions>) {
const finalOptions = Object.assign({}, DEFAULT_OPTIONS, options);
if (!VALID_TRIGGERS.includes(finalOptions.trigger)) {
console.warn(
warn(
`The trigger ${
finalOptions.trigger
} is not valid for track-canvas-3d behavior, "drag" will take effect instead. Only "${VALID_TRIGGERS.join(

View File

@ -1,5 +1,6 @@
import { Behavior } from '../../types/behavior';
import { IG6GraphEvent } from '../../types/event';
import { warn } from '../../utils/invariant';
const VALID_TRIGGERS = ['wheel', 'upDownKeys'];
@ -61,7 +62,7 @@ export class ZoomCanvas3D extends Behavior {
constructor(options: Partial<ZoomCanvas3DOptions>) {
const finalOptions = Object.assign({}, DEFAULT_OPTIONS, options);
if (!VALID_TRIGGERS.includes(finalOptions.trigger)) {
console.warn(
warn(
`The trigger ${
finalOptions.trigger
} is not valid for zoom-canvas-3d behavior, "wheel" will take effect instead. Only "${VALID_TRIGGERS.join(

View File

@ -1,6 +1,7 @@
import { isBoolean, isNumber } from '@antv/util';
import { ID, IG6GraphEvent } from '../../types';
import { Behavior } from '../../types/behavior';
import { warn } from '../../utils/invariant';
const VALID_TRIGGERS = ['wheel', 'upDownKeys'];
const WHEEL_DURATION = 250;
@ -102,7 +103,7 @@ export class ZoomCanvas extends Behavior {
constructor(options: Partial<ZoomCanvasOptions>) {
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.`);
warn(`The trigger ${finalOptions.trigger} is not valid, 'wheel' will take effect.`);
finalOptions.trigger = 'wheel';
}
const { fixSelectedItems } = finalOptions;

View File

@ -1,6 +1,7 @@
import { uniqueId } from '@antv/util';
import { ComboUserModel, EdgeUserModel, GraphData, NodeUserModel } from '../../types';
import { GraphCore, GraphDataChanges } from '../../types/data';
import { error } from '../../utils/invariant';
/**
* Validate and format the graph data which will be added.
@ -29,7 +30,7 @@ const handler = (data: GraphData, options = {}, graphCore?: GraphCore): GraphDat
if (generateId) {
item.id = `${type}-${uniqueId()}`;
} else {
console.error(
error(
`Unique global id is neccessary for graph items. The ${type} ${JSON.stringify(
item,
)} without id will be ignored.`,
@ -38,7 +39,7 @@ const handler = (data: GraphData, options = {}, graphCore?: GraphCore): GraphDat
}
}
if (idMap.has(item.id)) {
console.error(
error(
`Unique global id is neccessary for graph nodes/edges/combos. The ${type} ${JSON.stringify(item)} with id ${
item.id
} is duplicated.`,
@ -63,7 +64,7 @@ const handler = (data: GraphData, options = {}, graphCore?: GraphCore): GraphDat
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.`);
error(`The parentId of combo with id ${combo.id} will be removed since it is not exist in combos.`);
delete combo.data.parentId;
}
});
@ -74,7 +75,7 @@ const handler = (data: GraphData, options = {}, graphCore?: GraphCore): GraphDat
const { parentId } = node.data;
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.`);
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);
@ -96,23 +97,19 @@ const handler = (data: GraphData, options = {}, graphCore?: GraphCore): GraphDat
}
if (source === undefined) {
console.error(`The edge with id ${id} will be ignored since its source is undefined.`);
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.`);
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))) {
console.error(
`The edge with id ${id} will be ignored since its source ${source} is not existed in nodes and combos.`,
);
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))) {
console.error(
`The edge with id ${id} will be ignored since its target ${target} is not existed in nodes and combos.`,
);
error(`The edge with id ${id} will be ignored since its target ${target} is not existed in nodes and combos.`);
return false;
}
idMap.set(id, true);

View File

@ -7,6 +7,7 @@ import type { LayoutRegistry } from '../types/layout';
import type { NodeRegistry } from '../types/node';
import type { PluginRegistry as WidgetRegistry } from '../types/plugin';
import type { ThemeRegistry, ThemeSolverRegistry } from '../types/theme';
import { warn } from '../utils/invariant';
/**
* <zh/>
@ -59,8 +60,8 @@ function register<T extends PluginCategory>(category: T, type: string, pluginCla
pluginRegistry[category] ||= new Map();
if (pluginRegistry[category].get(type)) {
console.warn(
`[G6] The plugin of type '${type}' has been previously registered and has been automatically overwritten by the latest registration.`,
warn(
`The plugin of type '${type}' has been previously registered and has been automatically overwritten by the latest registration.`,
);
}

View File

@ -1,6 +1,7 @@
import { AABB } from '@antv/g';
import { ComboModel, Graph, NodeModel } from '../../../types';
import { Bounds, Point } from '../../../types/common';
import { warn } from '../../../utils/invariant';
import { isPointInPolygon } from '../../../utils/shape';
import { BubblesetCfg } from './types';
import {
@ -91,7 +92,7 @@ function MarchingSquares(contour, potentialArea, threshold) {
// assign the move direction according to state of the square
switch (state) {
case -1:
console.warn('Marched out of bounds');
warn('Marched out of bounds');
return true;
case 0:
case 3:
@ -133,7 +134,7 @@ function MarchingSquares(contour, potentialArea, threshold) {
y++; // go down
break;
default:
console.warn(`Marching squares invalid state: ${state}`);
warn(`Marching squares invalid state: ${state}`);
return true;
}
}

View File

@ -2,6 +2,7 @@ import { DisplayObject } from '@antv/g';
import { isArray } from '@antv/util';
import { ComboModel, Graph, ID, NodeModel } from '../../../types';
import { ShapeStyle } from '../../../types/item';
import { warn } from '../../../utils/invariant';
import { pathToPoints } from '../../../utils/path';
import { isPolygonsIntersect } from '../../../utils/shape';
import { genBubbleSet } from './bubbleset';
@ -110,9 +111,7 @@ export default class Hull {
this.type = 'round-convex';
}
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.',
);
warn('The hull type should be either round-convex, smooth-convex or bubble, round-convex is used by default.');
this.type = 'round-convex';
}
}
@ -448,7 +447,7 @@ export default class Hull {
// } else {
const shapeBBox = this.graph.getRenderBBox(itemId);
if (!shapeBBox) {
console.warn(`The item with ${itemId} is not existed in the graph.`);
warn(`The item with ${itemId} is not existed in the graph.`);
return;
}
shapePoints = [

View File

@ -5,6 +5,7 @@ import { ComboLabelPosition } from '../../../types/combo';
import { ITEM_TYPE, ShapeStyle } from '../../../types/item';
import { Plugin as Base, IPluginBaseConfig } from '../../../types/plugin';
import { isArrayOverlap } from '../../../utils/array';
import { warn } from '../../../utils/invariant';
import HullComponent, { HullComponentOptions } from './hullComponent';
import { BubblesetCfg } from './types';
@ -126,13 +127,11 @@ export default class Hull extends Base {
(memberId) => this.graph.getNodeData(memberId) || this.graph.getComboData(memberId),
);
if (!validMembers?.length) {
console.warn(`Create hull failed. There are no valid members.`);
warn(`Create hull failed. There are no valid members.`);
return;
}
if (validMembers.length !== members.length) {
console.warn(
`Some member of hull ${id} is not exist in the graph. Hull ${id} is added without those invalid members.`,
);
warn(`Some member of hull ${id} is not exist in the graph. Hull ${id} is added without those invalid members.`);
}
const fullOptions = {
id: `${this.key}-${id}`,
@ -164,7 +163,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.`);
warn(`Update hull component failed. The bubble with id ${id} is not existed.`);
return;
}
this.hullMap[id].updateOptions(others);
@ -183,7 +182,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`);
warn(`Add member to hull failed. The hull with id ${id} is not exist`);
return;
}
hullComponent.addMember(members);
@ -192,7 +191,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`);
warn(`Remove member from hull failed. The hull with id ${id} is not exist`);
return;
}
hullComponent.removeMember(members);
@ -201,7 +200,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`);
warn(`Add non member to hull failed. The hull with id ${id} is not exist`);
return;
}
hullComponent.addNonMember(members);
@ -210,7 +209,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`);
warn(`Remove non member from hull failed. The hull with id ${id} is not exist`);
return;
}
hullComponent.removeNonMember(members);

View File

@ -6,6 +6,7 @@ import { Graph } from '../../../types';
import { IG6GraphEvent } from '../../../types/event';
import { Plugin as Base, IPluginBaseConfig } from '../../../types/plugin';
import { createDOM, modifyCSS } from '../../../utils/dom';
import { warn } from '../../../utils/invariant';
typeof document !== 'undefined' &&
insertCss(`
@ -384,7 +385,7 @@ export class Tooltip extends Base {
x: itemBBox.min[0] + itemWidth * 1,
y: itemBBox.min[1] - itemHeight * 0.5,
};
console.warn(
warn(
`The '${this.options.fixToNode}' fixToNode position configuration is not supported, please use 'top'|'left'| 'right'| 'bottom'| 'topLeft'| 'leftTop'| 'topRight'| 'rightTop'| 'bottomLeft'| 'leftBottom'| 'bottomRight'| 'rightBottom', or use array to config, like: [0,5,1]`,
);
break;

View File

@ -31,6 +31,7 @@ import {
treeData2GraphData,
validateComboStructure,
} from '../../utils/data';
import { warn } from '../../utils/invariant';
import { isTreeLayout } from '../../utils/layout';
import { EdgeCollisionChecker, QuadTree } from '../../utils/polyline';
@ -541,7 +542,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".');
warn('Input data type is invalid, the type shuold be "graphData", "treeData", or "fetch".');
return;
}
@ -627,7 +628,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`);
warn(`Adding child ${childId} to combo ${id} failed. The child ${childId} does not exist`);
return;
}
graphCore.setParent(childId, id, 'combo');

View File

@ -4,6 +4,7 @@ import { Graph } from '../../types';
import { Behavior } from '../../types/behavior';
import { CANVAS_EVENT_TYPE, DOM_EVENT_TYPE, IG6GraphEvent } from '../../types/event';
import { ItemInfo, getContextMenuEventProps, getItemInfoFromElement } from '../../utils/event';
import { error, warn } from '../../utils/invariant';
type Listener = (event: IG6GraphEvent) => void;
@ -18,9 +19,9 @@ const wrapListener = (type: string, eventName: string, listener: Listener): List
return (event: any) => {
try {
listener(event);
} catch (error) {
console.error(`G6: Error occurred in "${eventName}" phase of the behavior "${type}"!`);
throw error;
} catch (e) {
error(`Error occurred in "${eventName}" phase of the behavior "${type}"!`);
throw e;
}
};
};
@ -76,7 +77,7 @@ export class InteractionController {
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.`);
error(`Failed to add behavior with key or type "${key}"! It was already added.`);
return;
}
try {
@ -91,8 +92,8 @@ export class InteractionController {
this.behaviorMap.set(key, behavior);
}
return behavior;
} catch (error) {
console.error(`G6: Failed to initialize behavior with key or type "${key}"!`, error);
} catch (e) {
error(`Failed to initialize behavior with key or type "${key}"!`);
return null;
}
};
@ -101,8 +102,8 @@ export class InteractionController {
try {
this.behaviorMap.delete(key);
behavior.destroy();
} catch (error) {
console.error(`G6: Failed to destroy behavior with key or type "${key}"!`, error);
} catch (e) {
error(`Failed to destroy behavior with key or type "${key}"!`);
}
};
@ -138,7 +139,7 @@ export class InteractionController {
}
if (!this.validateMode(mode)) {
console.warn(`G6: Mode "${mode}" was not specified in current graph.`);
warn(`Mode "${mode}" was not specified in current graph.`);
}
this.mode = mode;

View File

@ -47,6 +47,7 @@ import {
traverseGraphAncestors,
} from '../../utils/data';
import { getGroupedChanges } from '../../utils/event';
import { warn } from '../../utils/invariant';
import { upsertTransientItem } from '../../utils/item';
import { isPointPreventPolylineOverlap, isPolylineWithObstacleAvoidance } from '../../utils/polyline';
import { getCombinedBoundsByData, intersectBBox, upsertShape } from '../../utils/shape';
@ -1403,7 +1404,7 @@ export class ItemController {
private debounceWarn = debounce(
(type) => {
const msg = getWarnMsg[type](this.cacheWarnMsg[type]);
console.warn(msg);
warn(msg);
this.cacheWarnMsg[type] = [];
},
16,

View File

@ -251,7 +251,6 @@ export class LayoutController {
// CustomLayout is not workerized.
if (!isLayoutWorkerized(options)) {
workerEnabled = false;
// TODO: console.warn();
}
if (workerEnabled) {

View File

@ -27,7 +27,7 @@ const wrapListener = (type: string, eventName: string, listener: Listener): List
try {
listener(event);
} catch (error) {
console.error(`G6: Error occurred in "${eventName}" phase of the plugin "${type}"!`);
error(`Error occurred in "${eventName}" phase of the plugin "${type}"!`);
throw error;
}
};

View File

@ -24,6 +24,7 @@ import { getCombinedCanvasesBounds } from '../utils/bbox';
import { changeRenderer, createCanvas } from '../utils/canvas';
import { cloneJSON, isEmptyGraph } from '../utils/data';
import { createDOM } from '../utils/dom';
import { error, warn } from '../utils/invariant';
import { getLayoutBounds } from '../utils/layout';
import { formatPadding } from '../utils/shape';
import {
@ -36,6 +37,7 @@ import {
ViewportController,
} from './controller';
import Hook from './hooks';
export class Graph<B extends BehaviorRegistry = any, T extends ThemeSolverRegistry = any> extends EventEmitter {
public hooks: Hooks;
// for nodes and edges excluding their labels, which will be separate into groups
@ -133,7 +135,7 @@ export class Graph<B extends BehaviorRegistry = any, T extends ThemeSolverRegist
: (container as HTMLElement);
if (!containerDOM) {
console.error(`Create graph failed. The container for graph ${containerDOM} is not exist.`);
error(`Create graph failed. The container for graph ${containerDOM} is not exist.`);
this.destroy();
return;
}
@ -834,9 +836,7 @@ export class Graph<B extends BehaviorRegistry = any, T extends ThemeSolverRegist
*/
public setSize(size: number[]) {
if (!isArray(size) || size.length < 2) {
console.warn(
`Failed to setSize. The parameter size: ${size} is invalid. It must be an array with 2 number elements.`,
);
warn(`Failed to setSize. The parameter size: ${size} is invalid. It must be an array with 2 number elements.`);
return;
}
const oldSize = [this.specification.width, this.specification.height];
@ -1114,7 +1114,7 @@ export class Graph<B extends BehaviorRegistry = any, T extends ThemeSolverRegist
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`);
warn(`The ${itemType} data with id ${id} does not exist. It will be ignored`);
return;
}
return getItem.bind(graphCore)(id);
@ -1975,7 +1975,7 @@ export class Graph<B extends BehaviorRegistry = any, T extends ThemeSolverRegist
return oldPlugin.key === config.key;
});
if (oldPlugin) {
console.warn(
warn(
`Add plugin with key ${
(config as any).key
} failed, the key is duplicated to the existing plugins on the graph.`,
@ -2032,10 +2032,10 @@ export class Graph<B extends BehaviorRegistry = any, T extends ThemeSolverRegist
[cfg: string]: unknown;
};
if (!key) {
console.warn(`The key for the plugin is not found. G6 will update the first plugin with type ${type}`);
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.');
warn('Update plugin failed, the plugin to be updated does not exist.');
return;
}
const oldPlugin = plugins?.find((p) => {
@ -2052,7 +2052,7 @@ export class Graph<B extends BehaviorRegistry = any, T extends ThemeSolverRegist
);
});
if (!oldPlugin) {
console.warn(`Update plugin failed, the plugin with key ${key} or type ${type} is not found.`);
warn(`Update plugin failed, the plugin with key ${key} or type ${type} is not found.`);
return;
}
const idx = plugins.indexOf(oldPlugin);
@ -2327,9 +2327,7 @@ export class Graph<B extends BehaviorRegistry = any, T extends ThemeSolverRegist
*/
private dataURLToImage(dataURL: string, renderer: string, link, fileName) {
if (!dataURL || dataURL === 'data:') {
console.error(
'Download image failed. The graph is too large or there is invalid attribute values in graph items',
);
error('Download image failed. The graph is too large or there is invalid attribute values in graph items');
return;
}

View File

@ -5,6 +5,7 @@ import { NodeModel, NodeUserModel } from '../types';
import { DataLifecycleType, GraphCore, GraphData } from '../types/data';
import { Graph } from '../types/graph';
import { NodeUserModelData } from '../types/node';
import { warn } from './invariant';
/**
* Deconstruct data and distinguish nodes and combos from graphcore data.
@ -154,17 +155,15 @@ export const isSucceed = (graph, testParent, testSucceed): 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`);
warn(`Setting parent combo failed. The parent combo with id ${toBeAncestorId} does not exist`);
return false;
}
if (toBeSucceedId === toBeAncestorId) {
console.warn(
`Setting parent combo failed. Cannot set combo/node with id ${toBeSucceedId} to be the child of itself.`,
);
warn(`Setting parent combo failed. Cannot set combo/node with id ${toBeSucceedId} to be the child of itself.`);
return false;
}
if (toBeAncestorId && isSucceed(graph, toBeSucceedId, toBeAncestorId)) {
console.warn(
warn(
`Setting parent combo failed, since the parent combo with id ${toBeAncestorId} is a succeed of the combo with id ${toBeSucceedId}.`,
);
return false;

View File

@ -0,0 +1,47 @@
/**
* Simplified from https://github.com/zertosh/invariant.
*/
const BRAND = 'G6';
/**
*
* @param message
*/
function getMessage(message: string) {
return `${BRAND}: ${message}`;
}
/**
* invariant error.
* @param message
*/
export function invariant(message: string): void {
const error = new Error(getMessage(message));
error.name = BRAND;
// error.framesToPop = 1; // we don't care about invariant's own frame
throw error;
}
/**
* info message in console.
* @param message
*/
export function info(message: string): void {
console.warn(getMessage(message));
}
/**
* warn message in console.
* @param message
*/
export function warn(message: string) {
console.warn(getMessage(message));
}
/**
* error message in console.
* @param message
*/
export function error(message: string) {
console.error(getMessage(message));
}

View File

@ -1,24 +0,0 @@
/**
* optionName: 选项名
* shouldBe: 合法的输入参数
* now: 当前用户输入值
* scope: 选项所属的模块
*/
type WarnOption = {
optionName: string;
shouldBe: any;
now: string | number;
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}`);
}

View File

@ -1,3 +1,7 @@
/**
*
* @param url
*/
export async function loadDataset(url: string) {
const result = await fetch(url);
const legacyG6GraphFormat = await result.json();

View File

@ -1,5 +1,10 @@
import { createNodeGCanvas } from './createNodeGCanvas';
/**
*
* @param width
* @param height
*/
export function createContext(width: number, height: number) {
const container = document.createElement('div');
document.body.appendChild(container);

View File

@ -1,3 +1,7 @@
/**
*
* @param n
*/
export function sleep(n: number) {
return new Promise((resolve) => {
setTimeout(resolve, n);

View File

@ -0,0 +1,25 @@
import { error, info, invariant, warn } from '../../../src/utils/invariant';
describe('invariant', () => {
it('invariant', () => {
expect(() => {
invariant('throw hello world!');
}).toThrow('throw hello world!');
});
it('log', () => {
const fn = jest.fn();
window.console.error = fn;
window.console.warn = fn;
window.console.log = fn;
error('error hello world!');
expect(fn).toHaveBeenCalledWith('G6: error hello world!');
warn('warn hello world!');
expect(fn).toHaveBeenCalledWith('G6: warn hello world!');
info('info hello world!');
expect(fn).toHaveBeenCalledWith('G6: info hello world!');
});
});

View File

@ -0,0 +1,19 @@
import { eulerDist, isBetween, manhattanDist } from '../../../src/utils/math';
describe('math', () => {
it('isBetween', () => {
expect(isBetween(1, 0, 1)).toBe(true);
expect(isBetween(1, 1, 2)).toBe(true);
expect(isBetween(1, -1, 1)).toBe(true);
expect(isBetween(1, 1, -1)).toBe(false);
expect(isBetween(1, -1, -2)).toBe(false);
});
it('manhattanDist', () => {
expect(manhattanDist({ x: 1, y: 1 }, { x: 3, y: 3 })).toBe(4);
});
it('eulerDist', () => {
expect(eulerDist({ x: 1, y: 1 }, { x: 3, y: 3 })).toBe(Math.sqrt(8));
});
});

View File

@ -39,7 +39,7 @@
"@antv/algorithm": "^0.1.26",
"@antv/chart-node-g6": "^0.0.3",
"@antv/dumi-theme-antv": "^0.4.4",
"@antv/g2": "^5.1.5",
"@antv/g2": "^5.1.15",
"@antv/g6": "workspace:*",
"@antv/g6-plugin-map-view": "workspace:*",
"@antv/g6-react-node": "workspace:*",