atom/atom — pull request #3658 by nathansobo (2014-09-29 23:00:04+00:00)
Title: Clean up context menu API

## Consistent API

I initially set out to return `Disposable` instances from `atom.contextMenu.add`, but then I noticed that the format for expressing items didn't match up with `atom.menu.add`. This PR corrects that. You can now add context menus with the same format as adding application menus, with selectors mapping to arrays containing menu items as follows:

```coffee
atom.contextMenu.add '.editor': [
{label: 'Undo', command: 'core:undo'}
{label: 'Redo', command: 'core:redo'}
{label: 'Other', submenu: [
{label: 'Transpose', command: 'editor:transpose'}
]
}
]
```

## Created and Should Display Hooks

There's also a new `shouldDisplay` hook to address a use case I saw in color-picker, which is currently digging into `ContextMenuManager` internals to conditionally display a menu item. This is a sketch of how the API could be used, but not real code from the actual color-picker.

```coffee
atom.contextMenu.add '.editor': [{
label: 'Pick Color',
command: 'color-picker:',
shouldDisplay: (event) -> # use the right click event to decide...
}]
```

The `executeAtBuild` hook has been replaced with `created`. I couldn't find anyone using this other than us because it wasn't exposed in our API, so I went ahead and just renamed it without shimming. Here's the `created` hook being used to add the `x` and `y` of the click event to the command.

```coffee
atom.contextMenu.add '.workspace': [{
label: 'Inspect Element'
command: 'application:inspect'
devMode: true
created: (event) ->
{pageX, pageY} = event
@commandOptions = {x: pageX, y: pageY}
}]
```

## Dev Mode

Dev-mode-only items were formerly expressed with a trailing options hash on the entire call to `::add`. Now each individual item can contain a `devMode` field indicating whether it should only display in dev mode. You can see this in the `Inspect Element` example above.

## Disposables

Finally, `::add` now returns a disposable on which `::dispose` can be called to remove the added item descriptors.

## Outreach

We should probably talk to the author of color-picker and any other packages that dig into context menu internals to get them to switch to the new API. We may even want to send them a PR before merging this if the number is manageable.

/cc @atom/core