Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions packages/vrender-core/__tests__/unit/common/generator.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
/**
* @jest-environment node
*/

import { Generator } from '../../../src/common/generator';

declare const require: any;

describe('Generator', () => {
test('GenAutoIncrementId returns a finite number', () => {
const id = Generator.GenAutoIncrementId();
Expand All @@ -20,4 +26,30 @@ describe('Generator', () => {
expect(ids[i + 1]).toBe(ids[i] + 1);
}
});

test('GenAutoIncrementId shares one sequence across isolated module instances', () => {
jest.resetModules();
const { Generator: FirstGenerator } = require('../../../src/common/generator');
const firstId = FirstGenerator.GenAutoIncrementId();

jest.resetModules();
const { Generator: SecondGenerator } = require('../../../src/common/generator');
const secondId = SecondGenerator.GenAutoIncrementId();

expect(secondId).toBe(firstId + 1);
});

test('keeps node ids unique across isolated module instances', () => {
jest.resetModules();
const { Node: ParentNode } = require('../../../src/graphic/node-tree');
const parent = new ParentNode();

jest.resetModules();
const { Node: ChildNode } = require('../../../src/graphic/node-tree');
const child = new ChildNode();

expect(child._uid).not.toBe(parent._uid);
expect(parent.appendChild(child)).toBe(child);
expect(parent.firstChild).toBe(child);
});
});
21 changes: 18 additions & 3 deletions packages/vrender-core/src/common/generator.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,22 @@
export class Generator {
private static auto_increment_id: number = 0;
interface IGeneratorState {
autoIncrementId: number;
}

const GENERATOR_STATE_SYMBOL = Symbol.for('@visactor/vrender-core/generator-state');

function getGeneratorState(): IGeneratorState {
const scope = globalThis as typeof globalThis & {
[GENERATOR_STATE_SYMBOL]?: IGeneratorState;
};
return scope[GENERATOR_STATE_SYMBOL] || (scope[GENERATOR_STATE_SYMBOL] = { autoIncrementId: 0 });
}

// Application and legacy runtime state are shared across bundles. Keep node ids in the same
// global scope so a shared Stage cannot receive a Layer with a colliding id from another bundle.
const generatorState = getGeneratorState();

export class Generator {
static GenAutoIncrementId(): number {
return Generator.auto_increment_id++;
return generatorState.autoIncrementId++;
}
}
Loading