From e0e1fc4217146aba85a26164346ccab4a3e0edf8 Mon Sep 17 00:00:00 2001 From: MiniPear Date: Fri, 26 May 2023 16:00:39 +0800 Subject: [PATCH] fix(chart): chart.options should remove node --- __tests__/unit/api/options.spec.ts | 19 +++++++++++++++++++ src/api/node.ts | 7 ++++++- src/api/utils.ts | 7 +++++-- 3 files changed, 30 insertions(+), 3 deletions(-) diff --git a/__tests__/unit/api/options.spec.ts b/__tests__/unit/api/options.spec.ts index 005c11a6f6..dce703c99d 100644 --- a/__tests__/unit/api/options.spec.ts +++ b/__tests__/unit/api/options.spec.ts @@ -241,4 +241,23 @@ describe('chart api and options', () => { expect(interval.data()).toEqual([2, 3, 4]); }); + + it('chart.options({...}) should remove node.', () => { + const chart = new Chart({}); + + chart.options({ + type: 'view', + children: [{ type: 'line' }, { type: 'point' }], + }); + + chart.options({ + type: 'view', + children: [{ type: 'line' }], + }); + + expect(chart.options()).toEqual({ + type: 'view', + children: [{ type: 'line' }], + }); + }); }); diff --git a/src/api/node.ts b/src/api/node.ts index fdfd9f0999..db81a8738f 100644 --- a/src/api/node.ts +++ b/src/api/node.ts @@ -74,10 +74,15 @@ export class Node< ): Node { const node = new Ctor({}); node.children = []; + this.push(node); + return node; + } + + push(node: Node): this { node.parentNode = this; node.index = this.children.length; this.children.push(node); - return node; + return this; } /** diff --git a/src/api/utils.ts b/src/api/utils.ts index 93046f4717..6f165627fb 100644 --- a/src/api/utils.ts +++ b/src/api/utils.ts @@ -151,7 +151,7 @@ function appendNode(parent: Node, newOptions: G2ViewTree) { while (discovered.length) { const [parent, nodeOptions] = discovered.shift(); const node = createNode(nodeOptions); - if (Array.isArray(parent.children)) parent.children.push(node); + if (Array.isArray(parent.children)) parent.push(node); const { children } = nodeOptions; if (Array.isArray(children)) { for (const child of children) { @@ -174,6 +174,8 @@ export function updateRoot( // If there is no oldNode, create a node tree directly. if (!oldNode) { appendNode(parent, newNode); + } else if (!newNode) { + oldNode.remove(); } else { updateNode(oldNode, newNode); const { children: newChildren } = newNode; @@ -181,7 +183,8 @@ export function updateRoot( if (Array.isArray(newChildren) && Array.isArray(oldChildren)) { // Only update node specified in newChildren, // the extra oldChildren will remain still. - for (let i = 0; i < newChildren.length; i++) { + const n = Math.max(newChildren.length, oldChildren.length); + for (let i = 0; i < n; i++) { const newChild = newChildren[i]; const oldChild = oldChildren[i]; discovered.push([oldNode, oldChild, newChild]);