This repository was archived by the owner on Sep 6, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7.5k
Expand file tree
/
Copy pathmain.js
More file actions
473 lines (407 loc) · 17 KB
/
main.js
File metadata and controls
473 lines (407 loc) · 17 KB
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
/*
* Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, regexp: true, indent: 4, maxerr: 50 */
/*global define, brackets, window, $, Mustache */
define(function (require, exports, module) {
"use strict";
// Brackets modules
var ProjectManager = brackets.getModule("project/ProjectManager"),
SidebarView = brackets.getModule("project/SidebarView"),
PreferencesManager = brackets.getModule("preferences/PreferencesManager"),
Commands = brackets.getModule("command/Commands"),
CommandManager = brackets.getModule("command/CommandManager"),
KeyBindingManager = brackets.getModule("command/KeyBindingManager"),
Menus = brackets.getModule("command/Menus"),
EditorManager = brackets.getModule("editor/EditorManager"),
ExtensionUtils = brackets.getModule("utils/ExtensionUtils"),
FileSystem = brackets.getModule("filesystem/FileSystem"),
AppInit = brackets.getModule("utils/AppInit"),
KeyEvent = brackets.getModule("utils/KeyEvent"),
FileUtils = brackets.getModule("file/FileUtils"),
PopUpManager = brackets.getModule("widgets/PopUpManager"),
Strings = brackets.getModule("strings"),
ProjectsMenuTemplate = require("text!htmlContent/projects-menu.html");
var KeyboardPrefs = JSON.parse(require("text!keyboard.json"));
/** @const {string} Recent Projects commands ID */
var TOGGLE_DROPDOWN = "recentProjects.toggle";
/** @const {number} Maximum number of displayed recent projects */
var MAX_PROJECTS = 20;
/** @type {$.Element} jQuery elements used for the dropdown menu */
var $dropdownItem,
$dropdown,
$links;
/**
* Get the stored list of recent projects, fixing up paths as appropriate.
* Warning: unlike most paths in Brackets, these lack a trailing "/"
*/
function getRecentProjects() {
var recentProjects = PreferencesManager.getViewState("recentProjects") || [],
i;
for (i = 0; i < recentProjects.length; i++) {
// We have to canonicalize & then de-canonicalize the path here, since our pref format uses no trailing "/"
recentProjects[i] = FileUtils.stripTrailingSlash(ProjectManager.updateWelcomeProjectPath(recentProjects[i] + "/"));
}
return recentProjects;
}
/**
* Add a project to the stored list of recent projects, up to MAX_PROJECTS.
*/
function add() {
var root = FileUtils.stripTrailingSlash(ProjectManager.getProjectRoot().fullPath),
recentProjects = getRecentProjects(),
index = recentProjects.indexOf(root);
if (index !== -1) {
recentProjects.splice(index, 1);
}
recentProjects.unshift(root);
if (recentProjects.length > MAX_PROJECTS) {
recentProjects = recentProjects.slice(0, MAX_PROJECTS);
}
PreferencesManager.setViewState("recentProjects", recentProjects);
}
/**
* Check the list of items to see if any of them are hovered, and if so trigger a mouseenter.
* Normally the mouseenter event handles this, but when a previous item is deleted and the next
* item moves up to be underneath the mouse, we don't get a mouseenter event for that item.
*/
function checkHovers(pageX, pageY) {
$dropdown.children().each(function () {
var offset = $(this).offset(),
width = $(this).outerWidth(),
height = $(this).outerHeight();
if (pageX >= offset.left && pageX <= offset.left + width &&
pageY >= offset.top && pageY <= offset.top + height) {
$(".recent-folder-link", this).triggerHandler("mouseenter");
}
});
}
/**
* Create the "delete" button that shows up when you hover over a project.
*/
function renderDelete() {
return $("<div id='recent-folder-delete' class='trash-icon'>×</div>")
.mouseup(function (e) {
// Don't let the click bubble upward.
e.stopPropagation();
// Remove the project from the preferences.
var recentProjects = getRecentProjects(),
index = recentProjects.indexOf($(this).parent().data("path")),
newProjects = [],
i;
for (i = 0; i < recentProjects.length; i++) {
if (i !== index) {
newProjects.push(recentProjects[i]);
}
}
PreferencesManager.setViewState("recentProjects", newProjects);
$(this).closest("li").remove();
checkHovers(e.pageX, e.pageY);
if (newProjects.length === 1) {
$dropdown.find(".divider").remove();
}
});
}
/**
* Hide the delete button.
*/
function removeDeleteButton() {
$("#recent-folder-delete").remove();
}
/**
* Show the delete button over a given target.
*/
function addDeleteButton($target) {
removeDeleteButton();
renderDelete()
.css("top", $target.position().top + 6)
.appendTo($target);
}
/**
* Selects the next or previous item in the list
* @param {number} direction +1 for next, -1 for prev
*/
function selectNextItem(direction) {
var $links = $dropdown.find("a"),
index = $dropdownItem ? $links.index($dropdownItem) : (direction > 0 ? -1 : 0),
$newItem = $links.eq((index + direction) % $links.length);
if ($dropdownItem) {
$dropdownItem.removeClass("selected");
}
$newItem.addClass("selected");
$dropdownItem = $newItem;
removeDeleteButton();
}
/**
* Deletes the selected item and
* move the focus to next item in list.
*
* @return {boolean} TRUE if project is removed
*/
function removeSelectedItem(e) {
var recentProjects = getRecentProjects(),
$cacheItem = $dropdownItem,
index = recentProjects.indexOf($cacheItem.data("path"));
// When focus is not on project item
if (index === -1) {
return false;
}
// remove project
recentProjects.splice(index, 1);
PreferencesManager.setViewState("recentProjects", recentProjects);
checkHovers(e.pageX, e.pageY);
if (recentProjects.length === 1) {
$dropdown.find(".divider").remove();
}
selectNextItem(+1);
$cacheItem.closest("li").remove();
return true;
}
/**
* Handles the Key Down events
* @param {KeyboardEvent} event
* @return {boolean} True if the key was handled
*/
function keydownHook(event) {
var keyHandled = false;
switch (event.keyCode) {
case KeyEvent.DOM_VK_UP:
selectNextItem(-1);
keyHandled = true;
break;
case KeyEvent.DOM_VK_DOWN:
selectNextItem(+1);
keyHandled = true;
break;
case KeyEvent.DOM_VK_ENTER:
case KeyEvent.DOM_VK_RETURN:
if ($dropdownItem) {
$dropdownItem.trigger("click");
}
keyHandled = true;
break;
case KeyEvent.DOM_VK_BACK_SPACE:
case KeyEvent.DOM_VK_DELETE:
if ($dropdownItem) {
removeSelectedItem(event);
keyHandled = true;
}
break;
}
if (keyHandled) {
event.stopImmediatePropagation();
event.preventDefault();
}
return keyHandled;
}
/**
* Close the dropdown.
*/
function closeDropdown() {
// Since we passed "true" for autoRemove to addPopUp(), this will
// automatically remove the dropdown from the DOM. Also, PopUpManager
// will call cleanupDropdown().
if ($dropdown) {
PopUpManager.removePopUp($dropdown);
}
}
/**
* Remove the various event handlers that close the dropdown. This is called by the
* PopUpManager when the dropdown is closed.
*/
function cleanupDropdown() {
$("html").off("click", closeDropdown);
$("#project-files-container").off("scroll", closeDropdown);
$(SidebarView).off("hide", closeDropdown);
$("#titlebar .nav").off("click", closeDropdown);
$dropdown = null;
EditorManager.focusEditor();
$(window).off("keydown", keydownHook);
}
/**
* Adds the click and mouse enter/leave events to the dropdown
*/
function _handleListEvents() {
$dropdown
.on("click", "a", function () {
var $link = $(this),
id = $link.attr("id"),
path = $link.data("path");
if (path) {
ProjectManager.openProject(path)
.fail(function () {
// Remove the project from the list only if it does not exist on disk
var recentProjects = getRecentProjects(),
index = recentProjects.indexOf(path);
if (index !== -1) {
FileSystem.resolve(path, function (err, item) {
if (err) {
recentProjects.splice(index, 1);
}
});
}
});
closeDropdown();
} else if (id === "open-folder-link") {
CommandManager.execute(Commands.FILE_OPEN_FOLDER);
}
})
.on("mouseenter", "a", function () {
if ($dropdownItem) {
$dropdownItem.removeClass("selected");
}
$dropdownItem = $(this).addClass("selected");
if ($dropdownItem.hasClass("recent-folder-link")) {
// Note: we can't depend on the event here because this can be triggered
// manually from checkHovers().
addDeleteButton($(this));
}
})
.on("mouseleave", "a", function () {
var $link = $(this).removeClass("selected");
if ($link.get(0) === $dropdownItem.get(0)) {
$dropdownItem = null;
}
if ($link.hasClass("recent-folder-link")) {
removeDeleteButton();
}
});
}
/**
* Parses the path and returns an object with the full path, the folder name and the path without the folder.
* @param {string} path The full path to the folder.
* @return {{path: string, folder: string, rest: string}}
*/
function parsePath(path) {
var lastSlash = path.lastIndexOf("/"), folder, rest;
if (lastSlash === path.length - 1) {
lastSlash = path.slice(0, path.length - 1).lastIndexOf("/");
}
if (lastSlash >= 0) {
rest = " - " + (lastSlash ? path.slice(0, lastSlash) : "/");
folder = path.slice(lastSlash + 1);
} else {
rest = "/";
folder = path;
}
return {path: path, folder: folder, rest: rest};
}
/**
* Create the list of projects in the dropdown menu.
* @return {string} The html content
*/
function renderList() {
var recentProjects = getRecentProjects(),
currentProject = FileUtils.stripTrailingSlash(ProjectManager.getProjectRoot().fullPath),
templateVars = {
projectList : [],
Strings : Strings
};
recentProjects.forEach(function (root) {
if (root !== currentProject) {
templateVars.projectList.push(parsePath(root));
}
});
return Mustache.render(ProjectsMenuTemplate, templateVars);
}
/**
* Show or hide the recent projects dropdown.
*
* @param {{pageX:number, pageY:number}} position - the absolute position where to open the dropdown
*/
function showDropdown(position) {
// If the dropdown is already visible, just return (so the root click handler on html
// will close it).
if ($dropdown) {
return;
}
Menus.closeAll();
$dropdown = $(renderList())
.css({
left: position.pageX,
top: position.pageY
})
.appendTo($("body"));
PopUpManager.addPopUp($dropdown, cleanupDropdown, true);
// TODO: should use capture, otherwise clicking on the menus doesn't close it. More fallout
// from the fact that we can't use the Boostrap (1.4) dropdowns.
$("html").on("click", closeDropdown);
// Hide the menu if the user scrolls in the project tree. Otherwise the Lion scrollbar
// overlaps it.
// TODO: This duplicates logic that's already in ProjectManager (which calls Menus.close()).
// We should fix this when the popup handling is centralized in PopupManager, as well
// as making Esc close the dropdown. See issue #1381.
$("#project-files-container").on("scroll", closeDropdown);
// Hide the menu if the sidebar is hidden.
// TODO: Is there some more general way we could handle this for dropdowns?
$(SidebarView).on("hide", closeDropdown);
// Hacky: if we detect a click in the menubar, close ourselves.
// TODO: again, we should have centralized popup management.
$("#titlebar .nav").on("click", closeDropdown);
_handleListEvents();
$(window).on("keydown", keydownHook);
}
/**
* Show or hide the recent projects dropdown from the toogle command.
*/
function handleKeyEvent() {
if (!$dropdown) {
if (!SidebarView.isVisible()) {
SidebarView.show();
}
$("#project-dropdown-toggle").trigger("click");
$dropdown.focus();
$links = $dropdown.find("a");
// By default, select the most recent project (which is at the top of the list underneath Open Folder),
// but if there are none, select Open Folder instead.
$dropdownItem = $links.eq($links.length > 1 ? 1 : 0);
$dropdownItem.addClass("selected");
// If focusing the dropdown caused a modal bar to close, we need to refocus the dropdown
window.setTimeout(function () {
$dropdown.focus();
}, 0);
}
}
PreferencesManager.convertPreferences(module, {"recentProjects": "user"}, true);
// Register command handlers
CommandManager.register(Strings.CMD_TOGGLE_RECENT_PROJECTS, TOGGLE_DROPDOWN, handleKeyEvent);
KeyBindingManager.addBinding(TOGGLE_DROPDOWN, KeyboardPrefs.recentProjects);
// Initialize extension
AppInit.appReady(function () {
ExtensionUtils.loadStyleSheet(module, "styles/styles.css");
$(ProjectManager).on("projectOpen", add);
$(ProjectManager).on("beforeProjectClose", add);
});
AppInit.htmlReady(function () {
$("#project-title")
.wrap("<div id='project-dropdown-toggle' class='btn-alt-quiet'></div>")
.after("<span class='dropdown-arrow'></span>");
var cmenuAdapter = {
open: showDropdown,
close: closeDropdown,
isOpen: function () {
return !!$dropdown;
}
};
Menus.ContextMenu.assignContextMenuToSelector("#project-dropdown-toggle", cmenuAdapter);
});
});