Merge pull request #10888 from electron/menu_refactor

refactor menu.js to bring it up to readability and es6 standards
This commit is contained in:
Shelley Vohr 2017-10-26 00:31:47 -04:00 committed by GitHub
commit bb04b22ec8
2 changed files with 286 additions and 333 deletions

View file

@ -5,139 +5,39 @@ const EventEmitter = require('events').EventEmitter
const v8Util = process.atomBinding('v8_util') const v8Util = process.atomBinding('v8_util')
const bindings = process.atomBinding('menu') const bindings = process.atomBinding('menu')
// Automatically generated radio menu item's group id. const {Menu} = bindings
var nextGroupId = 0 let applicationMenu = null
let groupIdIndex = 0
// Search between separators to find a radio menu item and return its group id,
// otherwise generate a group id.
var generateGroupId = function (items, pos) {
var i, item, j, k, ref1, ref2, ref3
if (pos > 0) {
for (i = j = ref1 = pos - 1; ref1 <= 0 ? j <= 0 : j >= 0; i = ref1 <= 0 ? ++j : --j) {
item = items[i]
if (item.type === 'radio') {
return item.groupId
}
if (item.type === 'separator') {
break
}
}
} else if (pos < items.length) {
for (i = k = ref2 = pos, ref3 = items.length - 1; ref2 <= ref3 ? k <= ref3 : k >= ref3; i = ref2 <= ref3 ? ++k : --k) {
item = items[i]
if (item.type === 'radio') {
return item.groupId
}
if (item.type === 'separator') {
break
}
}
}
return ++nextGroupId
}
// Returns the index of item according to |id|.
var indexOfItemById = function (items, id) {
var i, item, j, len
for (i = j = 0, len = items.length; j < len; i = ++j) {
item = items[i]
if (item.id === id) {
return i
}
}
return -1
}
// Returns the index of where to insert the item according to |position|.
var indexToInsertByPosition = function (items, position) {
var insertIndex
if (!position) {
return items.length
}
const [query, id] = position.split('=')
insertIndex = indexOfItemById(items, id)
if (insertIndex === -1 && query !== 'endof') {
console.warn("Item with id '" + id + "' is not found")
return items.length
}
switch (query) {
case 'after':
insertIndex++
break
case 'endof':
// If the |id| doesn't exist, then create a new group with the |id|.
if (insertIndex === -1) {
items.push({
id: id,
type: 'separator'
})
insertIndex = items.length - 1
}
// Find the end of the group.
insertIndex++
while (insertIndex < items.length && items[insertIndex].type !== 'separator') {
insertIndex++
}
}
return insertIndex
}
const Menu = bindings.Menu
Object.setPrototypeOf(Menu.prototype, EventEmitter.prototype) Object.setPrototypeOf(Menu.prototype, EventEmitter.prototype)
/* Instance Methods */
Menu.prototype._init = function () { Menu.prototype._init = function () {
this.commandsMap = {} this.commandsMap = {}
this.groupsMap = {} this.groupsMap = {}
this.items = [] this.items = []
this.delegate = { this.delegate = {
isCommandIdChecked: (commandId) => { isCommandIdChecked: id => this.commandsMap[id] ? this.commandsMap[id].checked : undefined,
var command = this.commandsMap[commandId] isCommandIdEnabled: id => this.commandsMap[id] ? this.commandsMap[id].enabled : undefined,
return command != null ? command.checked : undefined isCommandIdVisible: id => this.commandsMap[id] ? this.commandsMap[id].visible : undefined,
}, getAcceleratorForCommandId: (id, useDefaultAccelerator) => {
isCommandIdEnabled: (commandId) => { const command = this.commandsMap[id]
var command = this.commandsMap[commandId] if (!command) return
return command != null ? command.enabled : undefined if (command.accelerator) return command.accelerator
},
isCommandIdVisible: (commandId) => {
var command = this.commandsMap[commandId]
return command != null ? command.visible : undefined
},
getAcceleratorForCommandId: (commandId, useDefaultAccelerator) => {
const command = this.commandsMap[commandId]
if (command == null) return
if (command.accelerator != null) return command.accelerator
if (useDefaultAccelerator) return command.getDefaultRoleAccelerator() if (useDefaultAccelerator) return command.getDefaultRoleAccelerator()
}, },
getIconForCommandId: (commandId) => { getIconForCommandId: id => this.commandsMap[id] ? this.commandsMap[id].icon : undefined,
var command = this.commandsMap[commandId] executeCommand: (event, id) => {
return command != null ? command.icon : undefined const command = this.commandsMap[id]
}, if (!command) return
executeCommand: (event, commandId) => {
const command = this.commandsMap[commandId]
if (command == null) return
command.click(event, BrowserWindow.getFocusedWindow(), webContents.getFocusedWebContents()) command.click(event, BrowserWindow.getFocusedWindow(), webContents.getFocusedWebContents())
}, },
menuWillShow: () => { menuWillShow: () => {
// Make sure radio groups have at least one menu item seleted. // Ensure radio groups have at least one menu item seleted
var checked, group, id, j, len, radioItem, ref1 for (const id in this.groupsMap) {
ref1 = this.groupsMap const found = this.groupsMap[id].find(item => item.checked) || null
for (id in ref1) { if (!found) v8Util.setHiddenValue(this.groupsMap[id][0], 'checked', true)
group = ref1[id]
checked = false
for (j = 0, len = group.length; j < len; j++) {
radioItem = group[j]
if (!radioItem.checked) {
continue
}
checked = true
break
}
if (!checked) {
v8Util.setHiddenValue(group[0], 'checked', true)
}
} }
} }
} }
@ -145,55 +45,47 @@ Menu.prototype._init = function () {
Menu.prototype.popup = function (window, x, y, positioningItem) { Menu.prototype.popup = function (window, x, y, positioningItem) {
let asyncPopup let asyncPopup
let [newX, newY, newPosition, newWindow] = [x, y, positioningItem, window]
// menu.popup(x, y, positioningItem) // menu.popup(x, y, positioningItem)
if (window != null && (typeof window !== 'object' || window.constructor !== BrowserWindow)) { if (!window) {
// Shift. // shift over values
positioningItem = y if (typeof window !== 'object' || window.constructor !== BrowserWindow) {
y = x [newPosition, newY, newX, newWindow] = [y, x, window, null]
x = window }
window = null
} }
// menu.popup(window, {}) // menu.popup(window, {})
if (x != null && typeof x === 'object') { if (x && typeof x === 'object') {
const options = x const opts = x
x = options.x newX = opts.x
y = options.y newY = opts.y
positioningItem = options.positioningItem newPosition = opts.positioningItem
asyncPopup = options.async asyncPopup = opts.async
} }
// Default to showing in focused window. // set defaults
if (window == null) window = BrowserWindow.getFocusedWindow() if (typeof x !== 'number') newX = -1
if (typeof y !== 'number') newY = -1
// Default to showing under mouse location. if (typeof positioningItem !== 'number') newPosition = -1
if (typeof x !== 'number') x = -1 if (!window) newWindow = BrowserWindow.getFocusedWindow()
if (typeof y !== 'number') y = -1
// Default to not highlighting any item.
if (typeof positioningItem !== 'number') positioningItem = -1
// Default to synchronous for backwards compatibility.
if (typeof asyncPopup !== 'boolean') asyncPopup = false if (typeof asyncPopup !== 'boolean') asyncPopup = false
this.popupAt(window, x, y, positioningItem, asyncPopup) this.popupAt(newWindow, newX, newY, newPosition, asyncPopup)
} }
Menu.prototype.closePopup = function (window) { Menu.prototype.closePopup = function (window) {
if (window == null || window.constructor !== BrowserWindow) { if (!window || window.constructor !== BrowserWindow) {
window = BrowserWindow.getFocusedWindow() window = BrowserWindow.getFocusedWindow()
} }
if (window != null) { if (window) this.closePopupAt(window.id)
this.closePopupAt(window.id)
}
} }
Menu.prototype.getMenuItemById = function (id) { Menu.prototype.getMenuItemById = function (id) {
const items = this.items const items = this.items
let found = items.find(item => item.id === id) || null let found = items.find(item => item.id === id) || null
for (let i = 0, length = items.length; !found && i < length; i++) { for (let i = 0; !found && i < items.length; i++) {
if (items[i].submenu) { if (items[i].submenu) {
found = items[i].submenu.getMenuItemById(id) found = items[i].submenu.getMenuItemById(id)
} }
@ -206,61 +98,17 @@ Menu.prototype.append = function (item) {
} }
Menu.prototype.insert = function (pos, item) { Menu.prototype.insert = function (pos, item) {
var base, name if ((item ? item.constructor : void 0) !== MenuItem) {
if ((item != null ? item.constructor : void 0) !== MenuItem) {
throw new TypeError('Invalid item') throw new TypeError('Invalid item')
} }
switch (item.type) {
case 'normal':
this.insertItem(pos, item.commandId, item.label)
break
case 'checkbox':
this.insertCheckItem(pos, item.commandId, item.label)
break
case 'separator':
this.insertSeparator(pos)
break
case 'submenu':
this.insertSubMenu(pos, item.commandId, item.label, item.submenu)
break
case 'radio':
// Grouping radio menu items.
item.overrideReadOnlyProperty('groupId', generateGroupId(this.items, pos))
if ((base = this.groupsMap)[name = item.groupId] == null) {
base[name] = []
}
this.groupsMap[item.groupId].push(item)
// Setting a radio menu item should flip other items in the group. // insert item depending on its type
v8Util.setHiddenValue(item, 'checked', item.checked) insertItemByType.call(this, item, pos)
Object.defineProperty(item, 'checked', {
enumerable: true, // set item properties
get: function () { if (item.sublabel) this.setSublabel(pos, item.sublabel)
return v8Util.getHiddenValue(item, 'checked') if (item.icon) this.setIcon(pos, item.icon)
}, if (item.role) this.setRole(pos, item.role)
set: () => {
var j, len, otherItem, ref1
ref1 = this.groupsMap[item.groupId]
for (j = 0, len = ref1.length; j < len; j++) {
otherItem = ref1[j]
if (otherItem !== item) {
v8Util.setHiddenValue(otherItem, 'checked', false)
}
}
return v8Util.setHiddenValue(item, 'checked', true)
}
})
this.insertRadioItem(pos, item.commandId, item.label, item.groupId)
}
if (item.sublabel != null) {
this.setSublabel(pos, item.sublabel)
}
if (item.icon != null) {
this.setIcon(pos, item.icon)
}
if (item.role != null) {
this.setRole(pos, item.role)
}
// Make menu accessable to items. // Make menu accessable to items.
item.overrideReadOnlyProperty('menu', this) item.overrideReadOnlyProperty('menu', this)
@ -270,73 +118,150 @@ Menu.prototype.insert = function (pos, item) {
this.commandsMap[item.commandId] = item this.commandsMap[item.commandId] = item
} }
// Force menuWillShow to be called
Menu.prototype._callMenuWillShow = function () { Menu.prototype._callMenuWillShow = function () {
if (this.delegate != null) { if (this.delegate) this.delegate.menuWillShow()
this.delegate.menuWillShow() this.items.forEach(item => {
} if (item.submenu) item.submenu._callMenuWillShow()
this.items.forEach(function (item) {
if (item.submenu != null) {
item.submenu._callMenuWillShow()
}
}) })
} }
var applicationMenu = null /* Static Methods */
Menu.setApplicationMenu = function (menu) { Menu.getApplicationMenu = () => applicationMenu
if (!(menu === null || menu.constructor === Menu)) {
throw new TypeError('Invalid menu')
}
// Keep a reference.
applicationMenu = menu
if (process.platform === 'darwin') {
if (menu === null) {
return
}
menu._callMenuWillShow()
bindings.setApplicationMenu(menu)
} else {
BrowserWindow.getAllWindows().forEach(function (window) {
window.setMenu(menu)
})
}
}
Menu.getApplicationMenu = function () {
return applicationMenu
}
Menu.sendActionToFirstResponder = bindings.sendActionToFirstResponder Menu.sendActionToFirstResponder = bindings.sendActionToFirstResponder
// set application menu with a preexisting menu
Menu.setApplicationMenu = function (menu) {
if (!(menu || menu.constructor === Menu)) {
throw new TypeError('Invalid menu')
}
applicationMenu = menu
if (process.platform === 'darwin') {
if (!menu) return
menu._callMenuWillShow()
bindings.setApplicationMenu(menu)
} else {
const windows = BrowserWindow.getAllWindows()
return windows.map(w => w.setMenu(menu))
}
}
Menu.buildFromTemplate = function (template) { Menu.buildFromTemplate = function (template) {
var insertIndex, item, j, k, len, len1, menu, menuItem, positionedTemplate if (!(template instanceof Array)) {
if (!Array.isArray(template)) {
throw new TypeError('Invalid template for Menu') throw new TypeError('Invalid template for Menu')
} }
positionedTemplate = []
insertIndex = 0 const menu = new Menu()
for (j = 0, len = template.length; j < len; j++) { const positioned = []
item = template[j] let idx = 0
if (item.position) {
insertIndex = indexToInsertByPosition(positionedTemplate, item.position) // sort template by position
} else { template.forEach(item => {
// If no |position| is specified, insert after last item. idx = (item.position) ? indexToInsertByPosition(positioned, item.position) : idx += 1
insertIndex++ positioned.splice(idx, 0, item)
} })
positionedTemplate.splice(insertIndex, 0, item)
} // add each item from positioned menu to application menu
menu = new Menu() positioned.forEach((item) => {
for (k = 0, len1 = positionedTemplate.length; k < len1; k++) {
item = positionedTemplate[k]
if (typeof item !== 'object') { if (typeof item !== 'object') {
throw new TypeError('Invalid template for MenuItem') throw new TypeError('Invalid template for MenuItem')
} }
menuItem = new MenuItem(item) menu.append(new MenuItem(item))
menu.append(menuItem) })
}
return menu return menu
} }
/* Helper Functions */
// Search between separators to find a radio menu item and return its group id
function generateGroupId (items, pos) {
if (pos > 0) {
for (let idx = pos - 1; idx >= 0; idx--) {
if (items[idx].type === 'radio') return items[idx].groupId
if (items[idx].type === 'separator') break
}
} else if (pos < items.length) {
for (let idx = pos; idx <= items.length - 1; idx++) {
if (items[idx].type === 'radio') return items[idx].groupId
if (items[idx].type === 'separator') break
}
}
groupIdIndex += 1
return groupIdIndex
}
function indexOfItemById (items, id) {
const foundItem = items.find(item => item.id === id) || -1
return items.indexOf(foundItem)
}
function indexToInsertByPosition (items, position) {
if (!position) return items.length
const [query, id] = position.split('=') // parse query and id from position
const idx = indexOfItemById(items, id) // calculate initial index of item
// warn if query doesn't exist
if (idx === -1 && query !== 'endof') {
console.warn(`Item with id ${id} is not found`)
return items.length
}
// compute new index based on query
const queries = {
after: (index) => {
index += 1
return index
},
endof: (index) => {
if (index === -1) {
items.push({id, type: 'separator'})
index = items.length - 1
}
index += 1
while (index < items.length && items[index].type !== 'separator') index += 1
return index
}
}
// return new index if needed, or original indexOfItemById
return (query in queries) ? queries[query](idx) : idx
}
function insertItemByType (item, pos) {
const types = {
normal: () => this.insertItem(pos, item.commandId, item.label),
checkbox: () => this.insertCheckItem(pos, item.commandId, item.label),
separator: () => this.insertSeparator(pos),
submenu: () => this.insertSubMenu(pos, item.commandId, item.label, item.submenu),
radio: () => {
// Grouping radio menu items
item.overrideReadOnlyProperty('groupId', generateGroupId(this.items, pos))
if (this.groupsMap[item.groupId] == null) {
this.groupsMap[item.groupId] = []
}
this.groupsMap[item.groupId].push(item)
// Setting a radio menu item should flip other items in the group.
v8Util.setHiddenValue(item, 'checked', item.checked)
Object.defineProperty(item, 'checked', {
enumerable: true,
get: () => v8Util.getHiddenValue(item, 'checked'),
set: () => {
this.groupsMap[item.groupId].forEach(other => {
if (other !== item) v8Util.setHiddenValue(other, 'checked', false)
})
v8Util.setHiddenValue(item, 'checked', true)
}
})
this.insertRadioItem(pos, item.commandId, item.label, item.groupId)
}
}
types[item.type]()
}
module.exports = Menu module.exports = Menu

View file

@ -7,7 +7,7 @@ const {closeWindow} = require('./window-helpers')
describe('menu module', function () { describe('menu module', function () {
describe('Menu.buildFromTemplate', function () { describe('Menu.buildFromTemplate', function () {
it('should be able to attach extra fields', function () { it('should be able to attach extra fields', function () {
var menu = Menu.buildFromTemplate([ const menu = Menu.buildFromTemplate([
{ {
label: 'text', label: 'text',
extra: 'field' extra: 'field'
@ -17,7 +17,7 @@ describe('menu module', function () {
}) })
it('does not modify the specified template', function () { it('does not modify the specified template', function () {
var template = ipcRenderer.sendSync('eval', "var template = [{label: 'text', submenu: [{label: 'sub'}]}];\nrequire('electron').Menu.buildFromTemplate(template);\ntemplate;") const template = ipcRenderer.sendSync('eval', "var template = [{label: 'text', submenu: [{label: 'sub'}]}];\nrequire('electron').Menu.buildFromTemplate(template);\ntemplate;")
assert.deepStrictEqual(template, [ assert.deepStrictEqual(template, [
{ {
label: 'text', label: 'text',
@ -47,7 +47,7 @@ describe('menu module', function () {
describe('Menu.buildFromTemplate should reorder based on item position specifiers', function () { describe('Menu.buildFromTemplate should reorder based on item position specifiers', function () {
it('should position before existing item', function () { it('should position before existing item', function () {
var menu = Menu.buildFromTemplate([ const menu = Menu.buildFromTemplate([
{ {
label: '2', label: '2',
id: '2' id: '2'
@ -66,7 +66,7 @@ describe('menu module', function () {
}) })
it('should position after existing item', function () { it('should position after existing item', function () {
var menu = Menu.buildFromTemplate([ const menu = Menu.buildFromTemplate([
{ {
label: '1', label: '1',
id: '1' id: '1'
@ -85,7 +85,7 @@ describe('menu module', function () {
}) })
it('should position at endof existing separator groups', function () { it('should position at endof existing separator groups', function () {
var menu = Menu.buildFromTemplate([ const menu = Menu.buildFromTemplate([
{ {
type: 'separator', type: 'separator',
id: 'numbers' id: 'numbers'
@ -129,7 +129,7 @@ describe('menu module', function () {
}) })
it('should create separator group if endof does not reference existing separator group', function () { it('should create separator group if endof does not reference existing separator group', function () {
var menu = Menu.buildFromTemplate([ const menu = Menu.buildFromTemplate([
{ {
label: 'a', label: 'a',
id: 'a', id: 'a',
@ -167,7 +167,7 @@ describe('menu module', function () {
}) })
it('should continue inserting items at next index when no specifier is present', function () { it('should continue inserting items at next index when no specifier is present', function () {
var menu = Menu.buildFromTemplate([ const menu = Menu.buildFromTemplate([
{ {
label: '4', label: '4',
id: '4' id: '4'
@ -197,7 +197,7 @@ describe('menu module', function () {
describe('Menu.getMenuItemById', function () { describe('Menu.getMenuItemById', function () {
it('should return the item with the given id', function () { it('should return the item with the given id', function () {
var menu = Menu.buildFromTemplate([ const menu = Menu.buildFromTemplate([
{ {
label: 'View', label: 'View',
submenu: [ submenu: [
@ -220,7 +220,7 @@ describe('menu module', function () {
describe('Menu.insert', function () { describe('Menu.insert', function () {
it('should store item in @items by its index', function () { it('should store item in @items by its index', function () {
var menu = Menu.buildFromTemplate([ const menu = Menu.buildFromTemplate([
{ {
label: '1' label: '1'
}, { }, {
@ -229,9 +229,9 @@ describe('menu module', function () {
label: '3' label: '3'
} }
]) ])
var item = new MenuItem({
label: 'inserted' const item = new MenuItem({ label: 'inserted' })
})
menu.insert(1, item) menu.insert(1, item)
assert.equal(menu.items[0].label, '1') assert.equal(menu.items[0].label, '1')
assert.equal(menu.items[1].label, 'inserted') assert.equal(menu.items[1].label, 'inserted')
@ -240,33 +240,71 @@ describe('menu module', function () {
}) })
}) })
describe('Menu.append', function () {
it('should add the item to the end of the menu', function () {
const menu = Menu.buildFromTemplate([
{
label: '1'
}, {
label: '2'
}, {
label: '3'
}
])
const item = new MenuItem({ label: 'inserted' })
menu.append(item)
assert.equal(menu.items[0].label, '1')
assert.equal(menu.items[1].label, '2')
assert.equal(menu.items[2].label, '3')
assert.equal(menu.items[3].label, 'inserted')
})
})
describe('Menu.popup', function () { describe('Menu.popup', function () {
let w = null let w = null
let menu
afterEach(function () { beforeEach(() => {
w = new BrowserWindow({show: false, width: 200, height: 200})
menu = Menu.buildFromTemplate([
{
label: '1'
}, {
label: '2'
}, {
label: '3'
}
])
})
afterEach(() => {
return closeWindow(w).then(function () { w = null }) return closeWindow(w).then(function () { w = null })
}) })
describe('when called with async: true', function () { describe('when called with async: true', function () {
it('returns immediately', function () { it('returns immediately', function () {
w = new BrowserWindow({show: false, width: 200, height: 200})
const menu = Menu.buildFromTemplate([
{
label: '1'
}, {
label: '2'
}, {
label: '3'
}
])
menu.popup(w, {x: 100, y: 100, async: true}) menu.popup(w, {x: 100, y: 100, async: true})
menu.closePopup(w) menu.closePopup(w)
}) })
}) })
}) })
describe('Menu.setApplicationMenu', function () {
const menu = Menu.buildFromTemplate([
{
label: '1'
}, {
label: '2'
}
])
Menu.setApplicationMenu(menu)
assert.notEqual(Menu.getApplicationMenu(), null)
})
describe('MenuItem.click', function () { describe('MenuItem.click', function () {
it('should be called with the item object passed', function (done) { it('should be called with the item object passed', function (done) {
var menu = Menu.buildFromTemplate([ const menu = Menu.buildFromTemplate([
{ {
label: 'text', label: 'text',
click: function (item) { click: function (item) {
@ -282,7 +320,7 @@ describe('menu module', function () {
describe('MenuItem with checked property', function () { describe('MenuItem with checked property', function () {
it('clicking an checkbox item should flip the checked property', function () { it('clicking an checkbox item should flip the checked property', function () {
var menu = Menu.buildFromTemplate([ const menu = Menu.buildFromTemplate([
{ {
label: 'text', label: 'text',
type: 'checkbox' type: 'checkbox'
@ -294,7 +332,7 @@ describe('menu module', function () {
}) })
it('clicking an radio item should always make checked property true', function () { it('clicking an radio item should always make checked property true', function () {
var menu = Menu.buildFromTemplate([ const menu = Menu.buildFromTemplate([
{ {
label: 'text', label: 'text',
type: 'radio' type: 'radio'
@ -307,99 +345,91 @@ describe('menu module', function () {
}) })
it('at least have one item checked in each group', function () { it('at least have one item checked in each group', function () {
var i, j, k, menu, template const template = []
template = [] for (let i = 0; i <= 10; i++) {
for (i = j = 0; j <= 10; i = ++j) {
template.push({ template.push({
label: '' + i, label: `${i}`,
type: 'radio' type: 'radio'
}) })
} }
template.push({ template.push({type: 'separator'})
type: 'separator' for (let i = 12; i <= 20; i++) {
})
for (i = k = 12; k <= 20; i = ++k) {
template.push({ template.push({
label: '' + i, label: `${i}`,
type: 'radio' type: 'radio'
}) })
} }
menu = Menu.buildFromTemplate(template) const menu = Menu.buildFromTemplate(template)
menu.delegate.menuWillShow() menu.delegate.menuWillShow()
assert.equal(menu.items[0].checked, true) assert.equal(menu.items[0].checked, true)
assert.equal(menu.items[12].checked, true) assert.equal(menu.items[12].checked, true)
}) })
it('should assign groupId automatically', function () { it('should assign groupId automatically', function () {
var groupId, i, j, k, l, m, menu, template const template = []
template = [] for (let i = 0; i <= 10; i++) {
for (i = j = 0; j <= 10; i = ++j) {
template.push({ template.push({
label: '' + i, label: `${i}`,
type: 'radio' type: 'radio'
}) })
} }
template.push({ template.push({type: 'separator'})
type: 'separator' for (let i = 12; i <= 20; i++) {
})
for (i = k = 12; k <= 20; i = ++k) {
template.push({ template.push({
label: '' + i, label: `${i}`,
type: 'radio' type: 'radio'
}) })
} }
menu = Menu.buildFromTemplate(template) const menu = Menu.buildFromTemplate(template)
groupId = menu.items[0].groupId const groupId = menu.items[0].groupId
for (i = l = 0; l <= 10; i = ++l) { for (let i = 0; i <= 10; i++) {
assert.equal(menu.items[i].groupId, groupId) assert.equal(menu.items[i].groupId, groupId)
} }
for (i = m = 12; m <= 20; i = ++m) { for (let i = 12; i <= 20; i++) {
assert.equal(menu.items[i].groupId, groupId + 1) assert.equal(menu.items[i].groupId, groupId + 1)
} }
}) })
it("setting 'checked' should flip other items' 'checked' property", function () { it("setting 'checked' should flip other items' 'checked' property", function () {
var i, j, k, l, m, menu, n, o, p, q, template const template = []
template = [] for (let i = 0; i <= 10; i++) {
for (i = j = 0; j <= 10; i = ++j) {
template.push({ template.push({
label: '' + i, label: `${i}`,
type: 'radio' type: 'radio'
}) })
} }
template.push({ template.push({type: 'separator'})
type: 'separator' for (let i = 12; i <= 20; i++) {
})
for (i = k = 12; k <= 20; i = ++k) {
template.push({ template.push({
label: '' + i, label: `${i}`,
type: 'radio' type: 'radio'
}) })
} }
menu = Menu.buildFromTemplate(template)
for (i = l = 0; l <= 10; i = ++l) { const menu = Menu.buildFromTemplate(template)
for (let i = 0; i <= 10; i++) {
assert.equal(menu.items[i].checked, false) assert.equal(menu.items[i].checked, false)
} }
menu.items[0].checked = true menu.items[0].checked = true
assert.equal(menu.items[0].checked, true) assert.equal(menu.items[0].checked, true)
for (i = m = 1; m <= 10; i = ++m) { for (let i = 1; i <= 10; i++) {
assert.equal(menu.items[i].checked, false) assert.equal(menu.items[i].checked, false)
} }
menu.items[10].checked = true menu.items[10].checked = true
assert.equal(menu.items[10].checked, true) assert.equal(menu.items[10].checked, true)
for (i = n = 0; n <= 9; i = ++n) { for (let i = 0; i <= 9; i++) {
assert.equal(menu.items[i].checked, false) assert.equal(menu.items[i].checked, false)
} }
for (i = o = 12; o <= 20; i = ++o) { for (let i = 12; i <= 20; i++) {
assert.equal(menu.items[i].checked, false) assert.equal(menu.items[i].checked, false)
} }
menu.items[12].checked = true menu.items[12].checked = true
assert.equal(menu.items[10].checked, true) assert.equal(menu.items[10].checked, true)
for (i = p = 0; p <= 9; i = ++p) { for (let i = 0; i <= 9; i++) {
assert.equal(menu.items[i].checked, false) assert.equal(menu.items[i].checked, false)
} }
assert.equal(menu.items[12].checked, true) assert.equal(menu.items[12].checked, true)
for (i = q = 13; q <= 20; i = ++q) { for (let i = 13; i <= 20; i++) {
assert.equal(menu.items[i].checked, false) assert.equal(menu.items[i].checked, false)
} }
}) })
@ -407,20 +437,18 @@ describe('menu module', function () {
describe('MenuItem command id', function () { describe('MenuItem command id', function () {
it('cannot be overwritten', function () { it('cannot be overwritten', function () {
var item = new MenuItem({ const item = new MenuItem({label: 'item'})
label: 'item'
})
var commandId = item.commandId const commandId = item.commandId
assert(commandId != null) assert(commandId)
item.commandId = '' + commandId + '-modified' item.commandId = `${commandId}-modified`
assert.equal(item.commandId, commandId) assert.equal(item.commandId, commandId)
}) })
}) })
describe('MenuItem with invalid type', function () { describe('MenuItem with invalid type', function () {
it('throws an exception', function () { it('throws an exception', function () {
assert.throws(function () { assert.throws(() => {
Menu.buildFromTemplate([ Menu.buildFromTemplate([
{ {
label: 'text', label: 'text',
@ -433,7 +461,7 @@ describe('menu module', function () {
describe('MenuItem with submenu type and missing submenu', function () { describe('MenuItem with submenu type and missing submenu', function () {
it('throws an exception', function () { it('throws an exception', function () {
assert.throws(function () { assert.throws(() => {
Menu.buildFromTemplate([ Menu.buildFromTemplate([
{ {
label: 'text', label: 'text',
@ -446,7 +474,7 @@ describe('menu module', function () {
describe('MenuItem role', function () { describe('MenuItem role', function () {
it('includes a default label and accelerator', function () { it('includes a default label and accelerator', function () {
var item = new MenuItem({role: 'close'}) let item = new MenuItem({role: 'close'})
assert.equal(item.label, process.platform === 'darwin' ? 'Close Window' : 'Close') assert.equal(item.label, process.platform === 'darwin' ? 'Close Window' : 'Close')
assert.equal(item.accelerator, undefined) assert.equal(item.accelerator, undefined)
assert.equal(item.getDefaultRoleAccelerator(), 'CommandOrControl+W') assert.equal(item.getDefaultRoleAccelerator(), 'CommandOrControl+W')
@ -480,7 +508,7 @@ describe('menu module', function () {
describe('MenuItem editMenu', function () { describe('MenuItem editMenu', function () {
it('includes a default submenu layout when submenu is empty', function () { it('includes a default submenu layout when submenu is empty', function () {
var item = new MenuItem({role: 'editMenu'}) const item = new MenuItem({role: 'editMenu'})
assert.equal(item.label, 'Edit') assert.equal(item.label, 'Edit')
assert.equal(item.submenu.items[0].role, 'undo') assert.equal(item.submenu.items[0].role, 'undo')
assert.equal(item.submenu.items[1].role, 'redo') assert.equal(item.submenu.items[1].role, 'redo')
@ -503,7 +531,7 @@ describe('menu module', function () {
}) })
it('overrides default layout when submenu is specified', function () { it('overrides default layout when submenu is specified', function () {
var item = new MenuItem({role: 'editMenu', submenu: [{role: 'close'}]}) const item = new MenuItem({role: 'editMenu', submenu: [{role: 'close'}]})
assert.equal(item.label, 'Edit') assert.equal(item.label, 'Edit')
assert.equal(item.submenu.items[0].role, 'close') assert.equal(item.submenu.items[0].role, 'close')
}) })
@ -511,7 +539,7 @@ describe('menu module', function () {
describe('MenuItem windowMenu', function () { describe('MenuItem windowMenu', function () {
it('includes a default submenu layout when submenu is empty', function () { it('includes a default submenu layout when submenu is empty', function () {
var item = new MenuItem({role: 'windowMenu'}) const item = new MenuItem({role: 'windowMenu'})
assert.equal(item.label, 'Window') assert.equal(item.label, 'Window')
assert.equal(item.submenu.items[0].role, 'minimize') assert.equal(item.submenu.items[0].role, 'minimize')
assert.equal(item.submenu.items[1].role, 'close') assert.equal(item.submenu.items[1].role, 'close')
@ -523,7 +551,7 @@ describe('menu module', function () {
}) })
it('overrides default layout when submenu is specified', function () { it('overrides default layout when submenu is specified', function () {
var item = new MenuItem({role: 'windowMenu', submenu: [{role: 'copy'}]}) const item = new MenuItem({role: 'windowMenu', submenu: [{role: 'copy'}]})
assert.equal(item.label, 'Window') assert.equal(item.label, 'Window')
assert.equal(item.submenu.items[0].role, 'copy') assert.equal(item.submenu.items[0].role, 'copy')
}) })
@ -531,13 +559,13 @@ describe('menu module', function () {
describe('MenuItem with custom properties in constructor', function () { describe('MenuItem with custom properties in constructor', function () {
it('preserves the custom properties', function () { it('preserves the custom properties', function () {
var template = [{ const template = [{
label: 'menu 1', label: 'menu 1',
customProp: 'foo', customProp: 'foo',
submenu: [] submenu: []
}] }]
var menu = Menu.buildFromTemplate(template) const menu = Menu.buildFromTemplate(template)
menu.items[0].submenu.append(new MenuItem({ menu.items[0].submenu.append(new MenuItem({
label: 'item 1', label: 'item 1',
customProp: 'bar', customProp: 'bar',