significant cleanup; all tests still passing

This commit is contained in:
Shelley Vohr 2017-10-23 20:04:22 -04:00
parent 3fc5d51a96
commit 9038987e1d
No known key found for this signature in database
GPG key ID: F13993A75599653C

View file

@ -1,39 +1,66 @@
const {BrowserWindow, MenuItem} = require('electron') 'use strict'
const {EventEmitter} = require('events')
//const _ = require('lodash')
const {BrowserWindow, MenuItem, webContents} = require('electron')
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')
const { Menu } = bindings const {Menu} = bindings
let applicationMenu = null
let nextGroupId = 0
Menu.prototype.__proto__ = EventEmitter.prototype Object.setPrototypeOf(Menu.prototype, EventEmitter.prototype)
Menu.prototype._init = function () { Menu.prototype._init = function () {
this.commandsMap = {} this.commandsMap = {}
this.groupsMap = {} this.groupsMap = {}
this.items = [] this.items = []
return this.delegate = { this.delegate = {
isCommandIdChecked: id => (this.commandsMap[id] ? this.commandsMap[id].checked : undefined), isCommandIdChecked: (commandId) => {
isCommandIdEnabled: id => (this.commandsMap[id] ? this.commandsMap[id].enabled : undefined), var command = this.commandsMap[commandId]
isCommandIdVisible: id => (this.commandsMap[id] ? this.commandsMap[id].visible : undefined), return command != null ? command.checked : undefined
getAcceleratorForCommandId: id => (this.commandsMap[id] ? this.commandsMap[id].accelerator : undefined), },
getIconForCommandId: id => (this.commandsMap[id] ? this.commandsMap[id].icon : undefined), isCommandIdEnabled: (commandId) => {
executeCommand: (id) => { var command = this.commandsMap[commandId]
const command = this.commandsMap[id] return command != null ? command.enabled : undefined
return command ? this.commandsMap[id].click(BrowserWindow.getFocusedWindow()) : undefined },
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()
},
getIconForCommandId: (commandId) => {
var command = this.commandsMap[commandId]
return command != null ? command.icon : undefined
},
executeCommand: (event, commandId) => {
const command = this.commandsMap[commandId]
if (command == null) return
command.click(event, BrowserWindow.getFocusedWindow(), webContents.getFocusedWebContents())
}, },
menuWillShow: () => { menuWillShow: () => {
for (let id in this.groupsMap) { // Make sure radio groups have at least one menu item seleted.
const group = this.groupsMap[id] var checked, group, id, j, len, radioItem, ref1
let checked = false ref1 = this.groupsMap
for (let radioItem in group) { for (id in ref1) {
if (radioItem.checked) { group = ref1[id]
checked = false
for (j = 0, len = group.length; j < len; j++) {
radioItem = group[j]
if (!radioItem.checked) {
continue
}
checked = true checked = true
break break
} }
if (!checked) {
v8Util.setHiddenValue(group[0], 'checked', true)
} }
if (!checked) v8Util.setHiddenValue(group[0], 'checked', true)
} }
} }
} }
@ -60,79 +87,29 @@ Menu.prototype.popup = function (window, x, y, positioningItem) {
asyncPopup = options.async asyncPopup = options.async
} }
// Default to showing in focused window.
if (window == null) window = BrowserWindow.getFocusedWindow() if (window == null) window = BrowserWindow.getFocusedWindow()
// Default to showing under mouse location.
if (typeof x !== 'number') x = -1 if (typeof x !== 'number') x = -1
if (typeof y !== 'number') y = -1 if (typeof y !== 'number') y = -1
// Default to not highlighting any item.
if (typeof positioningItem !== 'number') positioningItem = -1 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(window, x, y, positioningItem, asyncPopup)
} }
Menu.prototype.append = function (item) { Menu.prototype.closePopup = function (window) {
return this.insert(this.getItemCount(), item) if (window == null || window.constructor !== BrowserWindow) {
} window = BrowserWindow.getFocusedWindow()
Menu.prototype.insert = function (pos, item) {
if ((item != null ? item.constructor : undefined) !== MenuItem) {
throw new TypeError('Invalid item')
} }
if (window != null) {
switch (item.type) { this.closePopupAt(window.id)
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 (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() { return v8Util.getHiddenValue(item, 'checked') },
set: val => {
for (let otherItem in this.groupsMap[item.groupId]) {
if (otherItem !== item) v8Util.setHiddenValue(otherItem, 'checked', false)
} }
return v8Util.setHiddenValue(item, 'checked', true)
}
})
this.insertRadioItem(pos, item.commandId, item.label, item.groupId)
break
}
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. */
item.overrideReadOnlyProperty('menu', this)
/* Remember the items. */
this.items.splice(pos, 0, item)
return this.commandsMap[item.commandId] = item
}
/* Force menuWillShow to be called */
Menu.prototype._callMenuWillShow = function () {
if (this.delegate != null) this.delegate.menuWillShow()
this.items.forEach(item => {
if (item.submenu != null) item.submenu._callMenuWillShow()
})
} }
Menu.prototype.getMenuItemById = function (id) { Menu.prototype.getMenuItemById = function (id) {
@ -147,8 +124,83 @@ Menu.prototype.getMenuItemById = function (id) {
return found return found
} }
//cleaned up
Menu.prototype.append = function (item) {
return this.insert(this.getItemCount(), item)
}
Menu.prototype.insert = function (pos, item) {
var base, name
if ((item != null ? item.constructor : void 0) !== MenuItem) {
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.
v8Util.setHiddenValue(item, 'checked', item.checked)
Object.defineProperty(item, 'checked', {
enumerable: true,
get: function () {
return v8Util.getHiddenValue(item, 'checked')
},
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.
item.overrideReadOnlyProperty('menu', this)
// Remember the items.
this.items.splice(pos, 0, item)
this.commandsMap[item.commandId] = item
}
// Force menuWillShow to be called
// cleaned up
Menu.prototype._callMenuWillShow = function () {
if (this.delegate != null) this.delegate.menuWillShow()
this.items.forEach(item => {
if (item.submenu != null) item.submenu._callMenuWillShow()
})
}
// cleaned up
Menu.setApplicationMenu = function (menu) { Menu.setApplicationMenu = function (menu) {
if (menu !== null && menu.constructor !== Menu) { if (!(menu === null || menu.constructor === Menu)) {
throw new TypeError('Invalid menu') throw new TypeError('Invalid menu')
} }
@ -156,32 +208,35 @@ Menu.setApplicationMenu = function (menu) {
if (process.platform === 'darwin') { if (process.platform === 'darwin') {
if (menu === null) return if (menu === null) return
menu._callMenuWillShow() menu._callMenuWillShow()
return bindings.setApplicationMenu(menu) bindings.setApplicationMenu(menu)
} else { } else {
const windows = BrowserWindow.getAllWindows() const windows = BrowserWindow.getAllWindows()
return windows.map((w) => w.setMenu(menu)) return windows.map(w => w.setMenu(menu))
} }
} }
// cleaned up
Menu.getApplicationMenu = () => applicationMenu Menu.getApplicationMenu = () => applicationMenu
Menu.sendActionToFirstResponder = bindings.sendActionToFirstResponder Menu.sendActionToFirstResponder = bindings.sendActionToFirstResponder
// build menu from a template // cleaned up
Menu.buildFromTemplate = function (template) { Menu.buildFromTemplate = function (template) {
if (!(template instanceof Array)) { if (!(template instanceof Array)) {
throw new TypeError('Invalid template for Menu') throw new TypeError('Invalid template for Menu')
} }
const menu = new Menu const menu = new Menu()
const positioned = [] const positioned = []
let idx = 0 let idx = 0
// sort template by position
template.forEach(item => { template.forEach(item => {
idx = (item.position) ? indexToInsertByPosition(positioned, item.position) : idx++ idx = (item.position) ? indexToInsertByPosition(positioned, item.position) : idx += 1
positioned.splice(idx, 0, item) positioned.splice(idx, 0, item)
}) })
// add each item from positioned menu to application menu
positioned.forEach((item) => { positioned.forEach((item) => {
if (typeof item !== 'object') { if (typeof item !== 'object') {
throw new TypeError('Invalid template for MenuItem') throw new TypeError('Invalid template for MenuItem')
@ -192,78 +247,76 @@ Menu.buildFromTemplate = function (template) {
return menu return menu
} }
// Automatically generated radio menu item's group id. /* Helper Methods */
let nextGroupId = 0
let applicationMenu = null
/* Search between seperators to find a radio menu item and return its group id */ // Search between separators to find a radio menu item and return its group id,
const generateGroupId = function(items, pos) { function generateGroupId (items, pos) {
let i, item var i, item, j, k, ref1, ref2, ref3
if (pos > 0) { if (pos > 0) {
let asc, start for (i = j = ref1 = pos - 1; ref1 <= 0 ? j <= 0 : j >= 0; i = ref1 <= 0 ? ++j : --j) {
for (start = pos - 1, i = start, asc = start <= 0; asc ? i <= 0 : i >= 0; asc ? i++ : i--) {
item = items[i] item = items[i]
if (item.type === 'radio') { return item.groupId } if (item.type === 'radio') {
if (item.type === 'separator') { break } return item.groupId
}
if (item.type === 'separator') {
break
}
} }
} else if (pos < items.length) { } else if (pos < items.length) {
let asc1, end for (i = k = ref2 = pos, ref3 = items.length - 1; ref2 <= ref3 ? k <= ref3 : k >= ref3; i = ref2 <= ref3 ? ++k : --k) {
for (i = pos, end = items.length - 1, asc1 = pos <= end; asc1 ? i <= end : i >= end; asc1 ? i++ : i--) {
item = items[i] item = items[i]
if (item.type === 'radio') { return item.groupId } if (item.type === 'radio') {
if (item.type === 'separator') { break } return item.groupId
}
if (item.type === 'separator') {
break
}
} }
} }
return ++nextGroupId return ++nextGroupId
} }
/* Returns the index of item according to |id|. */ // Returns the index of item according to |id|.
const indexOfItemById = function (items, id) { // cleaned up
for (let i = 0; i < items.length; i++) { function indexOfItemById (items, id) {
const item = items[i] const foundItem = items.find(item => item.id === id) || null
if (item.id === id) return i return items.indexOf(foundItem)
}
return -1
} }
/* Returns the index of where to insert the item according to |position|. */ // Returns the index of where to insert the item according to |position|
function indexToInsertByPosition (items, position) { function indexToInsertByPosition (items, position) {
if (!position) return items.length if (!position) return items.length
const [query, id] = position.split('=')
let idx = indexOfItemById(items, id)
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') { if (idx === -1 && query !== 'endof') {
console.warn(`Item with id '${id}' is not found`) console.warn("Item with id '" + id + "' is not found")
return items.length return items.length
} }
// compute new index based on query
const queries = { const queries = {
'after': () => idx++, 'after': (index) => index += 1,
'endof': () => { 'endof': (index) => {
if (idx === -1) { if (index === -1) {
items.push({id, type: 'separator'}) items.push({id, type: 'separator'})
idx = items.length - 1 index = items.length - 1
} }
idx++ index += 1
while (idx < items.length && items[idx].type !== 'separator') { while (index < items.length && items[index].type !== 'separator') index += 1
idx++ return index
}
} }
} }
queries[query]() // return new index if needed, or original indexOfItemById
return idx return (query in queries) ? queries[query](idx) : idx
} }
// WIP, need to figure out how to pass current menu group to this method function computeNewIndexOnQuery(idx, query) {
function isOuterSeparator (current, item) {
current.filter(item => { !item.visible })
const idx = current.indexof(item)
if (idx === 0 || idx === current.length) {
return true
}
return false
} }
module.exports = Menu module.exports = Menu