Spaces:
Running
Running
File size: 13,979 Bytes
4bb817b |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
* Tree data structure
*/
import * as zrUtil from 'zrender/src/core/util';
import Model from '../model/Model';
import linkSeriesData from './helper/linkSeriesData';
import SeriesData from './SeriesData';
import prepareSeriesDataSchema from './helper/createDimensions';
import {
DimensionLoose, ParsedValue, OptionDataValue,
OptionDataItemObject
} from '../util/types';
import { Dictionary } from 'zrender/src/core/types';
import { convertOptionIdName } from '../util/model';
type TreeTraverseOrder = 'preorder' | 'postorder';
type TreeTraverseCallback<Ctx> = (this: Ctx, node: TreeNode) => boolean | void;
type TreeTraverseOption = {
order?: TreeTraverseOrder
attr?: 'children' | 'viewChildren'
};
interface TreeNodeOption extends Pick<OptionDataItemObject<OptionDataValue>, 'name' | 'value'> {
children?: TreeNodeOption[];
}
export class TreeNode {
name: string;
depth: number = 0;
height: number = 0;
parentNode: TreeNode;
/**
* Reference to list item.
* Do not persistent dataIndex outside,
* besause it may be changed by list.
* If dataIndex -1,
* this node is logical deleted (filtered) in list.
*/
dataIndex: number = -1;
children: TreeNode[] = [];
viewChildren: TreeNode[] = [];
isExpand: boolean = false;
readonly hostTree: Tree<Model>;
constructor(name: string, hostTree: Tree<Model>) {
this.name = name || '';
this.hostTree = hostTree;
}
/**
* The node is removed.
*/
isRemoved(): boolean {
return this.dataIndex < 0;
}
/**
* Travel this subtree (include this node).
* Usage:
* node.eachNode(function () { ... }); // preorder
* node.eachNode('preorder', function () { ... }); // preorder
* node.eachNode('postorder', function () { ... }); // postorder
* node.eachNode(
* {order: 'postorder', attr: 'viewChildren'},
* function () { ... }
* ); // postorder
*
* @param options If string, means order.
* @param options.order 'preorder' or 'postorder'
* @param options.attr 'children' or 'viewChildren'
* @param cb If in preorder and return false,
* its subtree will not be visited.
*/
eachNode<Ctx>(options: TreeTraverseOrder, cb: TreeTraverseCallback<Ctx>, context?: Ctx): void;
eachNode<Ctx>(options: TreeTraverseOption, cb: TreeTraverseCallback<Ctx>, context?: Ctx): void;
eachNode<Ctx>(cb: TreeTraverseCallback<Ctx>, context?: Ctx): void;
eachNode<Ctx>(
options: TreeTraverseOrder | TreeTraverseOption | TreeTraverseCallback<Ctx>,
cb?: TreeTraverseCallback<Ctx> | Ctx,
context?: Ctx
) {
if (zrUtil.isFunction(options)) {
context = cb as Ctx;
cb = options;
options = null;
}
options = options || {};
if (zrUtil.isString(options)) {
options = {order: options};
}
const order = (options as TreeTraverseOption).order || 'preorder';
const children = this[(options as TreeTraverseOption).attr || 'children'];
let suppressVisitSub;
order === 'preorder' && (suppressVisitSub = (cb as TreeTraverseCallback<Ctx>).call(context as Ctx, this));
for (let i = 0; !suppressVisitSub && i < children.length; i++) {
children[i].eachNode(
options as TreeTraverseOption,
cb as TreeTraverseCallback<Ctx>,
context
);
}
order === 'postorder' && (cb as TreeTraverseCallback<Ctx>).call(context, this);
}
/**
* Update depth and height of this subtree.
*/
updateDepthAndHeight(depth: number) {
let height = 0;
this.depth = depth;
for (let i = 0; i < this.children.length; i++) {
const child = this.children[i];
child.updateDepthAndHeight(depth + 1);
if (child.height > height) {
height = child.height;
}
}
this.height = height + 1;
}
getNodeById(id: string): TreeNode {
if (this.getId() === id) {
return this;
}
for (let i = 0, children = this.children, len = children.length; i < len; i++) {
const res = children[i].getNodeById(id);
if (res) {
return res;
}
}
}
contains(node: TreeNode): boolean {
if (node === this) {
return true;
}
for (let i = 0, children = this.children, len = children.length; i < len; i++) {
const res = children[i].contains(node);
if (res) {
return res;
}
}
}
/**
* @param includeSelf Default false.
* @return order: [root, child, grandchild, ...]
*/
getAncestors(includeSelf?: boolean): TreeNode[] {
const ancestors = [];
let node = includeSelf ? this : this.parentNode;
while (node) {
ancestors.push(node);
node = node.parentNode;
}
ancestors.reverse();
return ancestors;
}
getAncestorsIndices(): number[] {
const indices: number[] = [];
let currNode = this as TreeNode;
while (currNode) {
indices.push(currNode.dataIndex);
currNode = currNode.parentNode;
}
indices.reverse();
return indices;
}
getDescendantIndices(): number[] {
const indices: number[] = [];
this.eachNode(childNode => {
indices.push(childNode.dataIndex);
});
return indices;
}
getValue(dimension?: DimensionLoose): ParsedValue {
const data = this.hostTree.data;
return data.getStore().get(data.getDimensionIndex(dimension || 'value'), this.dataIndex);
}
setLayout(layout: any, merge?: boolean) {
this.dataIndex >= 0
&& this.hostTree.data.setItemLayout(this.dataIndex, layout, merge);
}
/**
* @return {Object} layout
*/
getLayout(): any {
return this.hostTree.data.getItemLayout(this.dataIndex);
}
getModel<T = unknown>(): Model<T>;
// @depcrecated
// getModel<T = unknown, S extends keyof T = keyof T>(path: S): Model<T[S]>
// eslint-disable-next-line @typescript-eslint/no-unused-vars
getModel<T = unknown>(path?: string): Model {
if (this.dataIndex < 0) {
return;
}
const hostTree = this.hostTree;
const itemModel = hostTree.data.getItemModel(this.dataIndex);
return itemModel.getModel(path as any);
}
// TODO: TYPE More specific model
getLevelModel(): Model {
return (this.hostTree.levelModels || [])[this.depth];
}
/**
* @example
* setItemVisual('color', color);
* setItemVisual({
* 'color': color
* });
*/
// TODO: TYPE
setVisual(key: string, value: any): void;
setVisual(obj: Dictionary<any>): void;
setVisual(key: string | Dictionary<any>, value?: any) {
this.dataIndex >= 0
&& this.hostTree.data.setItemVisual(this.dataIndex, key as any, value);
}
/**
* Get item visual
* FIXME: make return type better
*/
getVisual(key: string): unknown {
return this.hostTree.data.getItemVisual(this.dataIndex, key as any);
}
getRawIndex(): number {
return this.hostTree.data.getRawIndex(this.dataIndex);
}
getId(): string {
return this.hostTree.data.getId(this.dataIndex);
}
/**
* index in parent's children
*/
getChildIndex(): number {
if (this.parentNode) {
const children = this.parentNode.children;
for (let i = 0; i < children.length; ++i) {
if (children[i] === this) {
return i;
}
}
return -1;
}
return -1;
}
/**
* if this is an ancestor of another node
*
* @param node another node
* @return if is ancestor
*/
isAncestorOf(node: TreeNode): boolean {
let parent = node.parentNode;
while (parent) {
if (parent === this) {
return true;
}
parent = parent.parentNode;
}
return false;
}
/**
* if this is an descendant of another node
*
* @param node another node
* @return if is descendant
*/
isDescendantOf(node: TreeNode): boolean {
return node !== this && node.isAncestorOf(this);
}
};
class Tree<HostModel extends Model = Model, LevelOption = any> {
type: 'tree' = 'tree';
root: TreeNode;
data: SeriesData;
hostModel: HostModel;
levelModels: Model<LevelOption>[];
private _nodes: TreeNode[] = [];
constructor(hostModel: HostModel) {
this.hostModel = hostModel;
}
/**
* Travel this subtree (include this node).
* Usage:
* node.eachNode(function () { ... }); // preorder
* node.eachNode('preorder', function () { ... }); // preorder
* node.eachNode('postorder', function () { ... }); // postorder
* node.eachNode(
* {order: 'postorder', attr: 'viewChildren'},
* function () { ... }
* ); // postorder
*
* @param options If string, means order.
* @param options.order 'preorder' or 'postorder'
* @param options.attr 'children' or 'viewChildren'
* @param cb
* @param context
*/
eachNode<Ctx>(options: TreeTraverseOrder, cb: TreeTraverseCallback<Ctx>, context?: Ctx): void;
eachNode<Ctx>(options: TreeTraverseOption, cb: TreeTraverseCallback<Ctx>, context?: Ctx): void;
eachNode<Ctx>(cb: TreeTraverseCallback<Ctx>, context?: Ctx): void;
eachNode<Ctx>(
options: TreeTraverseOrder | TreeTraverseOption | TreeTraverseCallback<Ctx>,
cb?: TreeTraverseCallback<Ctx> | Ctx,
context?: Ctx
) {
this.root.eachNode(options as TreeTraverseOption, cb as TreeTraverseCallback<Ctx>, context);
}
getNodeByDataIndex(dataIndex: number): TreeNode {
const rawIndex = this.data.getRawIndex(dataIndex);
return this._nodes[rawIndex];
}
getNodeById(name: string): TreeNode {
return this.root.getNodeById(name);
}
/**
* Update item available by list,
* when list has been performed options like 'filterSelf' or 'map'.
*/
update() {
const data = this.data;
const nodes = this._nodes;
for (let i = 0, len = nodes.length; i < len; i++) {
nodes[i].dataIndex = -1;
}
for (let i = 0, len = data.count(); i < len; i++) {
nodes[data.getRawIndex(i)].dataIndex = i;
}
}
/**
* Clear all layouts
*/
clearLayouts() {
this.data.clearItemLayouts();
}
/**
* data node format:
* {
* name: ...
* value: ...
* children: [
* {
* name: ...
* value: ...
* children: ...
* },
* ...
* ]
* }
*/
static createTree<T extends TreeNodeOption, HostModel extends Model>(
dataRoot: T,
hostModel: HostModel,
beforeLink?: (data: SeriesData) => void
) {
const tree = new Tree(hostModel);
const listData: TreeNodeOption[] = [];
let dimMax = 1;
buildHierarchy(dataRoot);
function buildHierarchy(dataNode: TreeNodeOption, parentNode?: TreeNode) {
const value = dataNode.value;
dimMax = Math.max(dimMax, zrUtil.isArray(value) ? value.length : 1);
listData.push(dataNode);
const node = new TreeNode(convertOptionIdName(dataNode.name, ''), tree);
parentNode
? addChild(node, parentNode)
: (tree.root = node);
tree._nodes.push(node);
const children = dataNode.children;
if (children) {
for (let i = 0; i < children.length; i++) {
buildHierarchy(children[i], node);
}
}
}
tree.root.updateDepthAndHeight(0);
const { dimensions } = prepareSeriesDataSchema(listData, {
coordDimensions: ['value'],
dimensionsCount: dimMax
});
const list = new SeriesData(dimensions, hostModel);
list.initData(listData);
beforeLink && beforeLink(list);
linkSeriesData({
mainData: list,
struct: tree,
structAttr: 'tree'
});
tree.update();
return tree;
}
}
/**
* It is needed to consider the mess of 'list', 'hostModel' when creating a TreeNote,
* so this function is not ready and not necessary to be public.
*/
function addChild(child: TreeNode, node: TreeNode) {
const children = node.children;
if (child.parentNode === node) {
return;
}
children.push(child);
child.parentNode = node;
}
export default Tree; |