From 5156aed9618e948cf453a29aa1c5453016914441 Mon Sep 17 00:00:00 2001 From: Lingfan Gao Date: Wed, 28 Feb 2024 19:41:14 +0100 Subject: [PATCH] feat: Keyborg ids should be unique for multiple bundles Currently if a keyborg instance is created from different bundles they will have the same id since the counter is on the file scope. This PR updates the id generation so that it is unique for a global core instance --- src/Keyborg.ts | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/src/Keyborg.ts b/src/Keyborg.ts index cc60b89f6..e986d34ae 100644 --- a/src/Keyborg.ts +++ b/src/Keyborg.ts @@ -279,8 +279,8 @@ export class Keyborg { } private constructor(win: WindowWithKeyborg, props?: KeyborgProps) { - this._id = "k" + ++_lastId; this._win = win; + this._id = this.createId(win); const current = win.__keyborg; @@ -296,6 +296,25 @@ export class Keyborg { } } + /** + * creates an id that will be truly global core instance + * @returns global id for the keyborg instance + */ + private createId(win: WindowWithKeyborg) { + const current = win.__keyborg; + let id = "k" + ++_lastId; + if (!current) { + return id; + } + + // other bundles might have created keyborg instances before this one + while (current.refs[id]) { + id = "k" + ++_lastId; + } + + return id; + } + private dispose(): void { const current = this._win?.__keyborg;