-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathinspect.js
526 lines (463 loc) · 19.3 KB
/
inspect.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
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
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
/*
* 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, indent: 4, maxerr: 50, */
/*global brackets, require, define, Mustache, $, setInterval, window */
define(function (require, exports, module) {
"use strict";
// Brackets modules
var DocumentManager = brackets.getModule("document/DocumentManager"),
LanguageManager = brackets.getModule("language/LanguageManager"),
ExtensionUtils = brackets.getModule("utils/ExtensionUtils"),
NodeConnection = brackets.getModule("utils/NodeConnection"),
ProjectManager = brackets.getModule("project/ProjectManager"),
PreferencesManager = brackets.getModule("preferences/PreferencesManager");
var inspectHtml = require("text!htmlContent/inspect.html"),
SkyLabController = require("lib/inspect/skylab").SkyLabController,
SkyLabPopup = require("lib/inspect/skylabpopup"),
SkyLabView = require("lib/inspect/skylabview"),
Strings = require("strings");
var Dialogs = brackets.getModule("widgets/Dialogs"),
inspectHowtoDialogHtml = require("text!htmlContent/inspect-howto-dialog.html");
var $body = $("body"),
$inspect,
$toolbarIcon,
inspectEnabled = false,
inspectShown = false,
deviceManagerInitialized = false,
projectRoot,
serverAddress,
currentURL = null,
nodeConnection = new NodeConnection(),
inspectPromise;
var GETTING_STARTED_KEY = "hasShownGettingStarted";
var prefs = PreferencesManager.getExtensionPrefs("edge-code-inspect");
PreferencesManager.convertPreferences(module, { "hasShownGettingStarted": "user edge-code-inspect.hasShownGettingStarted" });
var firstRun = prefs.get(GETTING_STARTED_KEY);
var Paths = {
ROOT : require.toUrl('./')
};
// Rendered templates
var inspectHowtoDialogTemplate = Mustache.render(inspectHowtoDialogHtml, {Strings : Strings, Paths : Paths});
// work around a URL jQuery URL escaping issue
var howtoDiagramURL = Mustache.render("{{{Paths.ROOT}}}{{{Strings.HOWTO_DIAGRAM_IMAGE}}}",
{Strings : Strings, Paths : Paths}),
howtoDiagramHiDPIURL = Mustache.render("{{{Paths.ROOT}}}{{{Strings.HOWTO_DIAGRAM_IMAGE_HIDPI}}}",
{Strings : Strings, Paths : Paths});
/**
* For a given event name, build a new event name from within the Inspect
* namespace. The parameter is optional and, if provided, can either be a
* single String or an array of Strings. If no parameter is provided, the
* namespace is returned. If a single name is provide, a single scoped name
* is returned. If an array of names are passed, an array of scoped names
* is returned.
*/
function inspectEvent(event) {
var EVENT_NAMESPACE = ".edge-code-inspect";
if (event === undefined) {
return EVENT_NAMESPACE;
} else if (arguments.length > 1) {
return Array.prototype.slice
.call(arguments)
.map(function (elem) {
return inspectEvent(elem);
})
.join(" ");
} else if (typeof event === "string") {
return event + EVENT_NAMESPACE;
}
}
/**
* Initialize the connection to the Inspect device manager.
*/
function initDeviceManager() {
SkyLabView.initialize();
SkyLabPopup.initInspect($inspect, Strings);
SkyLabPopup.startListening();
deviceManagerInitialized = true;
}
/**
* Request that the device manager direct clients to the current URL. This
* has the effect of refreshing and synchronizing clients. (Note though that
* this does not direct the clients to clear their cache.)
*/
function refreshCurrentURL() {
if (currentURL) {
SkyLabController.followUrl(currentURL, "false");
}
}
/**
* Calculate and record a URL for the current document. If the document is
* an HTML file, the URL will point to that file. Otherwise, it will not
* change the URL.
*
* @return boolean - true if the URL has changed; false otherwise.
*/
function updateCurrentURL() {
var document = DocumentManager.getCurrentDocument();
if (document && document.file) {
var fullPath = document.file.fullPath,
rootIndex = fullPath.indexOf(projectRoot),
relativePath;
if (rootIndex === 0) {
var language = LanguageManager.getLanguageForPath(fullPath);
if (language.getId() === "html") {
relativePath = fullPath.substring(projectRoot.length - 1,
fullPath.length);
relativePath = encodeURIComponent(relativePath);
relativePath = relativePath.replace(/%2F/g, "/");
currentURL = "http://" + serverAddress.address + ":" +
serverAddress.port + relativePath;
return true;
}
} else {
throw new Error("Document root does not match project root",
projectRoot,
fullPath);
}
}
return false;
}
/**
* Initialize the connection to the Node process.
*
* @return jQuery.Promise - Resolves when the connection is open.
*/
function connectToNode() {
if (nodeConnection.connected()) {
return $.Deferred().resolve().promise();
} else {
return nodeConnection.connect(true);
}
}
/**
* Load the Inspect HTTP server domain into the Node process. The Node
* connection should be opened before attempting to load the Inspect HTTP
* server domain.
*
* @return jQuery.Promise - Resolves once the domains are successfully loaded.
*/
function loadDomain() {
if (nodeConnection.connected()) {
var modulePath = ExtensionUtils.getModulePath(module, "node/InspectHTTPDomain");
return nodeConnection.loadDomains([modulePath], true);
} else {
return $.Deferred().reject().promise();
}
}
/**
* Open a connection to the Inspect HTTP server from the Node process. The
* Inspect HTTP domain should be loaded before attempting to open a
* connection to the HTTP server.
*
* @param String root - The filesystem root from which the HTTP server
* should serve files.
* @return jQuery.Promise - Resolves with a reference to the HTTP server.
*/
function openHTTPServer(root) {
if (nodeConnection.connected()) {
return nodeConnection.domains.inspectHttpServer.getServer(root);
} else {
return $.Deferred().reject().promise();
}
}
/**
* Close a connection to the HTTP server from the Node process. The
* Inspect HTTP domain should be loaded before attempting to close a
* connection to the HTTP server.
*
* Note that it can take a very long time for this promise to resolve.
* This is because the close event is not emitted by the Node HTTP server
* until all clients have disconnected. And because of HTTP Keep-Alive,
* this can take a long time.
*
* @param String root - The filesystem root from which the HTTP server
* serves the files.
* @return jQuery.Promise - Resolves when the HTTP server is closed.
*/
function closeHTTPServer(root) {
if (nodeConnection.connected()) {
return nodeConnection.domains.inspectHttpServer.closeServer(root);
} else {
return $.Deferred().reject().promise();
}
}
/**
* Stop an HTTP server at a given filesystem root. This helper function
* performs the following steps in order:
* 1. Connects to the Node process
* 2. Ensures that the Inspect HTTP domain has been loaded
* 3. Closes the HTTP server at the given filesystem root.
* Note that it can take a very long time for this promise to resolve. See
* the comment at closeHTTPServer above.
*
* @param String root - The filesystem root from which the HTTP server
* serves the files.
* @return jQuery.Promise - Resolves when the HTTP server is closed.
*/
function stopServer(root) {
var deferred = $.Deferred();
connectToNode().done(function () {
loadDomain().done(function () {
closeHTTPServer(root).done(function (path) {
serverAddress = null;
deferred.resolve();
}).fail(function (path) {
deferred.reject();
});
}).fail(function () {
deferred.reject();
});
}).fail(function () {
deferred.reject();
});
return deferred.promise();
}
/**
* Start an HTTP server at a given filesystem root. This helper function
* performs the following steps in order:
* 1. Connects to the Node process
* 2. Loads the Inspect HTTP domain into the Node process
* 3. Starts an HTTP server at the given filesystem root.
*
* @param String root - The filesystem root from which the HTTP server
* serves the files.
* @return jQuery.Promise - Resolves when the HTTP server is open.
*/
function startServer(root) {
var deferred = $.Deferred();
connectToNode().done(function () {
loadDomain().done(function () {
openHTTPServer(root).done(function (address) {
serverAddress = address;
deferred.resolve();
}).fail(function () {
deferred.reject();
});
}).fail(function () {
deferred.reject();
});
}).fail(function () {
deferred.reject();
});
return deferred.promise();
}
/**
* Disable Inspect at the given filesystem root. Note that it can take a
* very long time for this promise to resolve. See the comment at
* closeHTTPServer above.
*
* @param String root - The filesystem root at which Inspect is enabled.
* @return jQuery.Promise - Resolves when Inspect is disabled.
*/
function stopInspect(root) {
var deferred = $.Deferred();
inspectEnabled = false;
currentURL = null;
$(nodeConnection).off(inspectEvent());
inspectPromise.done(function () {
stopServer(root).done(function () {
deferred.resolve();
}).fail(function () {
deferred.reject();
});
}).fail(function () {
inspectEnabled = true;
deferred.reject();
});
return deferred.promise();
}
/**
* Enable Inspect at the given filesystem root.
*
* @param String root - The filesystem root at which Inspect will be enabled.
* @return jQuery.Promise - Resolves when Inspect is enabled.
*/
function startInspect(root) {
inspectEnabled = true;
return startServer(projectRoot).done(function () {
if (updateCurrentURL()) {
refreshCurrentURL();
}
// This event is fired if new domains are added to the node connection,
// which happens, e.g., if node is restarted. To be on the safe side,
// we restart everything when this happens.
$(nodeConnection).on(inspectEvent("base.newDomains"), function () {
if (inspectEnabled) {
stopInspect(projectRoot);
inspectPromise = startInspect(projectRoot);
}
});
}).fail(function () {
inspectEnabled = false;
});
}
/**
* Handle the Inspect follow toggle event by either enabling or disabling
* Inspect for the current project root.
*/
function onFollowToggle() {
var $toolbarIcon = $("#inspect-toolbar");
if (SkyLabPopup.getFollowState() === "on") {
if (!inspectEnabled) {
projectRoot = ProjectManager.getProjectRoot().fullPath;
inspectPromise = startInspect(projectRoot);
inspectPromise.done(function () {
$(ProjectManager)
.on(inspectEvent("beforeProjectClose", "beforeAppClose"), function () {
if (inspectEnabled) {
stopInspect(projectRoot);
projectRoot = null;
}
})
.on(inspectEvent("projectOpen"), function (event, newProjectRoot) {
if (!inspectEnabled) {
projectRoot = newProjectRoot.fullPath;
inspectPromise = startInspect(projectRoot);
}
});
$(DocumentManager)
.on(inspectEvent("documentSaved"), refreshCurrentURL)
.on(inspectEvent("currentDocumentChange"), function () {
inspectPromise.done(function () {
if (updateCurrentURL()) {
refreshCurrentURL();
}
});
});
$(window)
.on(inspectEvent("focus"), refreshCurrentURL);
$toolbarIcon.addClass("active");
}).fail(function () {
inspectEnabled = false;
});
}
} else {
if (inspectEnabled) {
stopInspect(projectRoot);
// Note that we don't wait for for this to finish because
// stopping the underlying HTTP server can take a very long time
$(ProjectManager).off(inspectEvent());
$(DocumentManager).off(inspectEvent());
$(window).off(inspectEvent());
$toolbarIcon.removeClass("active");
}
}
}
/**
* Hide the Inspect popover.
*/
function hideControls() {
$("#inspect, .inspectPopoverArrow").fadeOut(50, function () {
$inspect.css("display", "");
$inspect.removeClass("visible");
$(SkyLabController).trigger("close.popup");
});
$body.off(inspectEvent());
inspectShown = false;
}
/**
* Handle input when the popover is displayed. Specifically, close the popover if the user clicks outside of the window.
*/
function handleInput(event) {
function inTree($jqObj) {
return $jqObj[0] === event.target ||
$jqObj.find(event.target).length > 0;
}
if ($body.find(".modal-backdrop").length > 0) {
return;
}
if (!inTree($inspect) && !inTree($toolbarIcon)) {
hideControls();
}
}
/**
* Show the Inspect popover.
*/
function showControls() {
$toolbarIcon = $("#inspect-toolbar");
var iconOffset = $toolbarIcon.offset().top,
inspectTop = iconOffset - 20;
if (!deviceManagerInitialized) {
initDeviceManager();
}
$inspect.css("top", inspectTop);
$inspect.addClass("visible");
$body.on(inspectEvent("keyup", "mousedown"), handleInput);
inspectShown = true;
}
/**
* show how-to dialog with" Getting Started" instructions
*/
function showHowToDialog() {
var $howToDialog = Dialogs.showModalDialogUsingTemplate(inspectHowtoDialogTemplate);
$howToDialog.getElement().find(".close").on("click", $howToDialog.close.bind($howToDialog));
$(".inspect-howto-diagram").css("background-image", "-webkit-image-set(url('" + howtoDiagramURL + "') 1x, url('" + howtoDiagramHiDPIURL + "') 2x)");
}
/**
* Show or hide the Inspect popover depending on its current state.
*/
function handleInspectControls() {
if (inspectShown) {
hideControls();
} else {
showControls();
}
// if this is the first time that the Inspect extension has been launched,
// then show the Getting Started dialog.
if (!firstRun) {
showHowToDialog();
firstRun = true;
prefs.set(GETTING_STARTED_KEY, true);
prefs.save();
}
}
/**
* Initialize this Inspect administrator. Adds the Inspect popover to the
* DOM and connects to the Node process.
*
* @return jQuery.Promise - Resolves once the connection to the Node
* process is open.
*/
function initAdmin() {
var $mainContent = Mustache.render(inspectHtml, Strings);
$body.append($mainContent);
$inspect = $("#inspect");
$inspect.on("Inspect:followtoggle", onFollowToggle);
$inspect.on("Inspect:refreshCurrentUrl", function () {
if (inspectEnabled) {
refreshCurrentURL();
}
});
return nodeConnection.connect(true);
}
exports.initAdmin = initAdmin;
exports.initDeviceManager = initDeviceManager;
exports.handleInspectControls = handleInspectControls;
exports.showHowToDialog = showHowToDialog;
// for unit testing
exports.nodeConnection = nodeConnection;
exports.connectToNode = connectToNode;
exports.loadDomain = loadDomain;
exports.openHTTPServer = openHTTPServer;
exports.closeHTTPServer = closeHTTPServer;
});