Browse Source

fix: guard against duplicate TouchBarItem IDs (#22272)

* feat: Add OtherItemsProxy touchbar item

* review!

* fix: guard against duplicate TouchBarItem IDs

* add spec
Erick Zhao 5 years ago
parent
commit
85ef762269
2 changed files with 15 additions and 0 deletions
  1. 7 0
      lib/browser/api/touch-bar.js
  2. 8 0
      spec-main/api-touch-bar-spec.ts

+ 7 - 0
lib/browser/api/touch-bar.js

@@ -53,6 +53,7 @@ class TouchBar extends EventEmitter {
     }
 
     let hasOtherItemsProxy = false
+    const idSet = new Set()
     items.forEach((item) => {
       if (!(item instanceof TouchBarItem)) {
         throw new Error('Each item must be an instance of TouchBarItem')
@@ -65,6 +66,12 @@ class TouchBar extends EventEmitter {
           throw new Error('Must only have one OtherItemsProxy per TouchBar')
         }
       }
+
+      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

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

@@ -39,6 +39,14 @@ describe('TouchBar module', () => {
     }).to.throw('Must only have one OtherItemsProxy per TouchBar')
   })
 
+  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