This repository has been archived by the owner on Oct 13, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
index.js
268 lines (250 loc) · 7.8 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const ContextMenu = require('context-menu').default;
const os = require('os');
const fs = require('fs');
const ReactDOM = require('react-dom');
function arraySplit(
array,
shouldSplitPredicate,
) {
const result = [];
let current = [];
for (const value of array) {
if (shouldSplitPredicate(value)) {
result.push(current);
current = [];
} else {
current.push(value);
}
}
if (current.length > 0) {
result.push(current);
}
return result;
}
function getTextForAccelerator(accelerator) {
if (accelerator == null) {
return undefined;
}
return accelerator
.replace(/Command\+/g, '\u2318')
.replace(/Shift\+/g, '\u21e7')
.replace(/Alt\+/g, '\u2325')
.replace(/Ctrl\+/g, '\u2303')
.replace('BACKSPACE', '\u232B')
.replace('SPACE', '\u2423')
.replace('TAB', '\u21E5')
.replace('DELETE', '\u232B')
.replace('UP', '\u2191')
.replace('DOWN', '\u2193')
.replace('LEFT', '\u2190')
.replace('RIGHT', '\u2192');
}
function convertElectronMenu(
event,
template,
) {
return arraySplit(
template.filter(item => item.visible !== false),
item => item.type === 'separator',
).map(
(subarray) =>
subarray.map(
(item) => {
if (item.submenu != null) {
return {
label: item.label,
submenu: convertElectronMenu(event, item.submenu),
disabled: false,
};
}
return {
label: item.label,
sublabel: getTextForAccelerator(item.accelerator),
onClick: () => {
if (item.command != null) {
if (item.command.indexOf('tree-view:') === 0) {
const pkg = atom.packages.getActivePackage('tree-view');
if (pkg && pkg.mainModule && pkg.mainModule.getTreeViewInstance) {
const treeView = pkg.mainModule.getTreeViewInstance();
if (treeView.focus) {
treeView.focus();
}
}
}
atom.commands.dispatch(event.target, item.command);
}
},
disabled: item.enabled === false,
};
},
),
);
}
/**
* After opening the context menu, the context-menu library
* sets up a window click handler to detect when you've clicked
* on an item or clicked outside to close the menu, or right clicked
* again to open a new menu. The problem is that atom (or some other mysterious force)
* does a `stopPropagation` _somewhere_, causing the `onClick` of a menu item to not
* trigger hiding the menu correctly. This means that subsequent context menu item clicks
* would have their click event stolen by this handler, causing the menu to do nothing.
* Even destorying the entire contet-menu library doesn't fix this, because their click handler
* is not correctly disposed. Instead, we can force emit a click just before showing the menu
* to make sure the click handler registers the click. This should be harmless, but it is
* a little sketchy to dispatch this event to window.
*/
function dispatchFakeWindowMouseDown() {
const event = document.createEvent('MouseEvents');
event.initMouseEvent(
'mousedown',
true, // bubbles
true, // cancelable
document.defaultView,
0, // button
0, // pointerX
0, // pointerY
0, // pointerX
0, // pointerY
false, // ctrlKey
false, // altKey
false, // shiftKey
false, // metaKey
0, // button
window,
);
window.dispatchEvent(event);
}
/**
* Monkey patch ContextMenu's display logic to clip the x/y to be larger than 0,
* and scroll when the size is too small otherwise. Implementation mostly taken
* from the context-menu package itself.
*/
ContextMenu.prototype.adjustContextMenuClippingAndShow = function () {
const rootMenu = this.rootContextMenu;
rootMenu.style.visibility = 'hidden';
rootMenu.style.display = 'block';
const rootMenuBox = rootMenu.getBoundingClientRect();
let { x, y } = this.pos;
if (y + rootMenuBox.height > window.innerHeight) {
y -= rootMenuBox.height;
}
if (x + rootMenuBox.width > window.innerWidth) {
x -= rootMenuBox.width;
}
y = Math.max(0, y);
x = Math.max(0, x);
rootMenu.style.top = `${y}px`;
rootMenu.style.left = `${x}px`;
rootMenu.style.maxHeight = `100vh`;
rootMenu.style.overflow = `scroll`;
rootMenu.style.visibility = '';
}
/**
* atom on macOS Catalina can crash when showing a context menu.
* To prevent this, we can just stop atom from using `electron.remote.Menu` and instead
* make our own HTML-based context menus.
*/
async function monkeyPatchContextMenus() {
// Catalina is darwin version 19.0.0; also take 20, 21, etc for future-proofing
// https://en.wikipedia.org/wiki/Darwin_%28operating_system%29#Release_history
const isCatalinaOrLater = process.platform === 'darwin' && /^19\.|^2\d\./.test(os.release());
if (!isCatalinaOrLater) {
return;
}
// Import default styles from the context-menu package, since we're not using css-in-js
const stylesPath = require.resolve('context-menu/lib/styles.css');
const contextMenuDefaultStyles = await new Promise(
(res, rej) => fs.readFile(stylesPath, 'utf-8', (err, data) => err ? rej(err) : res(data))
);
const styles = document.createElement('style');
// Style the menu to be similar to macOS context menu styling
styles.innerHTML = `
${contextMenuDefaultStyles}
.context-menu {
background-color: rgb(160,160,160);
border-radius: 6px;
box-shadow: rgba(0,0,0,0.5) 2px 2px 10px;
font-family: -apple-system, BlinkMacSystemFont, sans-serif;
color: black;
padding: 4px 0;
z-index: 12;
}
.context-menu ul:not(:first-child) {
border-top: 2px solid rgb(145,148,153);
}
.context-menu ul {
padding: 2px 0;
}
.context-menu li {
padding-left: 18px;
}
.context-menu button {
white-space: nowrap;
}
.context-menu li:hover {
background-color: rgb(39, 94, 194);
color: white;
}
.context-menu button i.submenu-expand {
padding-right: 8px;
}
.context-menu button i.submenu-expand:after {
content: '\\25ba';
}
.context-menu button span.label.sublabel {
font-size: 100%;
}
`;
document.head.appendChild(styles);
const installContextMenus = () => {
const contextMenuRoot = document.createElement('div');
ContextMenu.init(contextMenuRoot, {theme: 'custom'});
document.body.appendChild(contextMenuRoot);
return () => {
const children = Array.from(contextMenuRoot.children);
children.forEach(child => {
ReactDOM.unmountComponentAtNode(child);
});
contextMenuRoot.remove();
};
}
const disposeContextMenu = installContextMenus();
const savedShowForEvent = atom.contextMenu.showForEvent;
atom.contextMenu.showForEvent = function(event) {
// Based on atom's default implementation:
// https://raw.githubusercontent.com/atom/atom/master/src/context-menu-manager.coffee
this.activeElement = event.target;
const menuTemplate = this.templateForEvent(event);
if (menuTemplate == null || menuTemplate.length === 0) {
return;
}
const groups = convertElectronMenu(event, menuTemplate);
dispatchFakeWindowMouseDown();
ContextMenu.showMenu(groups);
};
return () => {
// cleanup
atom.contextMenu.showForEvent = savedShowForEvent;
disposeContextMenu();
styles.remove();
};
}
let dispose;
module.exports = {
activate() {
setImmediate(() => {
dispose = monkeyPatchContextMenus();
});
},
deactivate() {
if (dispose != null) {
dispose();
}
},
};