Skip to content

Instantly share code, notes, and snippets.

@Weiyuan-Lane
Created January 20, 2019 15:58
Show Gist options
  • Save Weiyuan-Lane/ebf27c6f91d58d88880e8664b59a0dd6 to your computer and use it in GitHub Desktop.
Save Weiyuan-Lane/ebf27c6f91d58d88880e8664b59a0dd6 to your computer and use it in GitHub Desktop.
MenuItem entity for context menu to make nesting menu items as modules in modules.
'use strict'
/* This is a global variable containing all the
* callbacks for various menu items
*
* In the following line, a listener is attached
* to the contextMenus onClicked API, where an id
* is inputted to identify the callback to trigger
* with the registered callbacks
*/
const contextMenuCallbacks = []
chrome.contextMenus.onClicked.addListener(function(info, tab) {
const callbackResource = contextMenuCallbacks[info.menuItemId]
if (typeof callbackResource === 'function') {
callbackResource()
}
})
/*
* MenuItem represents a simple menu item that can be in any
* part of the context-menu tree - be it the root or the leaves
*
* As part of the menu item implementation, either the callback
* from clicking or children menu items should be provided. Else,
* clicking the menu item will yield no visible change
*
* Other attributes here are key to creating a basic menu item,
* such as id and title. See
* https://developer.chrome.com/apps/contextMenus#method-create
* for more
*/
export default class MenuItem {
constructor({ id, type, title, contexts, documentUrlPatterns, callback, childMenuItems = [] }) {
if (id === '' || typeof id !== 'string') {
throw new Error('You need a id for identifying this menu item')
}
this._id = id
// Whitelisted attributes when intialising the context-menu
// See https://developer.chrome.com/apps/contextMenus#method-create
// for more
this._baseMenuConfig = {
id, type, title, contexts, documentUrlPatterns
}
if (typeof callback === 'function') {
contextMenuCallbacks[this._id] = callback
} else {
this._childMenuItems = childMenuItems
}
}
init(parentId){
let menuConfig = this._baseMenuConfig
if (typeof parentId === 'string') {
menuConfig = Object.assign(menuConfig, { parentId })
}
// See https://developer.chrome.com/apps/contextMenus#method-create
chrome.contextMenus.create(menuConfig)
// Once this menu item is established in the context-menu,
// create the children context-menu that can appear when
// clicking this item.
// These children items are also MenuItem or subclasses of MenuItem
if (this._childMenuItems) {
this._childMenuItems.forEach((childMenuItem) => {
childMenuItem.init(this._id)
})
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment