Browse Source

fix: guard against duplicate TouchBarItem IDs (#22645)

Erick Zhao 5 years ago
parent
commit
526d748b7e
2 changed files with 21 additions and 1 deletions
  1. 13 1
      lib/browser/api/touch-bar.js
  2. 8 0
      spec-main/api-touch-bar-spec.ts

+ 13 - 1
lib/browser/api/touch-bar.js

@@ -51,13 +51,25 @@ class TouchBar extends EventEmitter {
         item.child.ordereredItems.forEach(registerItem)
       }
     }
+
+    const idSet = new Set()
     items.forEach((item) => {
       if (!(item instanceof TouchBarItem)) {
         throw new Error('Each item must be an instance of TouchBarItem')
       }
+
+      if (!idSet.has(item.id)) {
+        idSet.add(item.id)
+      } else {
+        throw new Error('Cannot add a single instance of TouchBarItem multiple times in a TouchBar')
+      }
+    })
+
+    // register in separate loop after all items are validated
+    for (const item of items) {
       this.ordereredItems.push(item)
       registerItem(item)
-    })
+    }
   }
 
   set escapeItem (item) {

+ 8 - 0
spec-main/api-touch-bar-spec.ts

@@ -32,6 +32,14 @@ describe('TouchBar module', () => {
     }).to.throw('Escape item must be an instance of TouchBarItem')
   })
 
+  it('throws an error if the same TouchBarItem is added multiple times', () => {
+    expect(() => {
+      const item = new TouchBarLabel({ label: 'Label' })
+      const touchBar = new TouchBar({ items: [item, item] })
+      touchBar.toString()
+    }).to.throw('Cannot add a single instance of TouchBarItem multiple times in a TouchBar')
+  })
+
   describe('BrowserWindow behavior', () => {
     let window: BrowserWindow