Skip to content

Commit

Permalink
fix(chart): chart.options should remove node (#5103)
Browse files Browse the repository at this point in the history
  • Loading branch information
pearmini committed May 26, 2023
1 parent ffc88bb commit 6949459
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 3 deletions.
19 changes: 19 additions & 0 deletions __tests__/unit/api/options.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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' }],
});
});
});
7 changes: 6 additions & 1 deletion src/api/node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,15 @@ export class Node<
): Node<ChildValue, Value> {
const node = new Ctor({});
node.children = [];
this.push(node);
return node;
}

push(node: Node<ChildValue, Value>): this {
node.parentNode = this;
node.index = this.children.length;
this.children.push(node);
return node;
return this;
}

/**
Expand Down
7 changes: 5 additions & 2 deletions src/api/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -174,14 +174,17 @@ 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;
const { children: oldChildren } = oldNode;
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]);
Expand Down

0 comments on commit 6949459

Please sign in to comment.