This repository has been archived by the owner on Mar 17, 2022. It is now read-only.
/
projectManager.js
606 lines (537 loc) · 17.1 KB
/
projectManager.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
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
define([
"settings!user",
"command",
"sessions",
"storage/file",
"util/manos",
"ui/dialog",
"ui/contextMenus",
"editor",
"util/template!templates/projectDir.html,templates/projectFile.html",
"util/i18n",
"util/dom2"
], function(Settings, command, sessions, File, M, dialog, context, editor, inflate, i18n) {
/*
It's tempting to store projects in local storage, similar to the way that we
retain files for tabs, but this would be a mistake. Reading from storage is a
pain, because it wants to store a single level deep, and we'll want to alter
parts of the setup individually.
Instead, we'll retain a single file handle to the project file, which (as
JSON) will store the IDs of individual directories, the project-specific
settings, and (hopefully, one day) build systems. This also gets us around
the issues of restored directory order and constantly updating the retained
file list--we'll just update it when the project file is saved.
*/
var guidCounter = 0;
//pseudo-worker to let the UI thread breathe
var queue = [];
var working = false;
var tick = function(fn) {
if (fn) queue.push(fn);
if (fn && working) return;
working = true;
//start work on the next frame
var process = function() {
var then = Date.now();
while (queue.length) {
var now = Date.now();
if (now - then > 10) {
return setTimeout(process);
}
var next = queue.shift();
next();
}
working = false;
};
setTimeout(process);
};
var getPath = (entry, c) => chrome.fileSystem.getDisplayPath(entry, c);
//FSNodes are used to track filesystem state inside projects
//We don't use the typical File object, because we're not really reading them
//Nodes form a tree starting at the root directory
var FSNode = function(entry) {
this.children = [];
this.id = guidCounter++;
if (entry) this.setEntry(entry);
};
FSNode.prototype = {
isDirectory: false,
entry: null,
tab: null,
id: null,
label: null,
setEntry: function(entry, c) {
this.entry = entry;
this.label = entry.name;
this.isDirectory = entry.isDirectory;
},
//walk will asynchronously collect the file tree
walk: function(blacklist, done) {
var self = this;
var entries = [];
var reader = this.entry.createReader();
var inc = 1;
var check = function() {
inc--;
if (inc == 0) {
return done(self);
}
};
var collect = function(list) {
if (list.length == 0) return complete();
entries.push.apply(entries, list);
reader.readEntries(collect);
};
var complete = function() {
self.children = [];
entries.forEach(function(entry) {
//skip dot dirs, but not files
if (!Settings.get("user").showHiddenDirectories) {
if (entry.name[0] == "." && entry.isDirectory) return;
}
//skip ignored files
if (blacklist) {
if (blacklist.test(entry.name)) return;
}
var node = new FSNode(entry);
self.children.push(node);
if (node.isDirectory) {
inc++;
//give the UI thread a chance to breathe
tick(function() { node.walk(blacklist, check); });
}
});
check();
};
reader.readEntries(collect);
}
};
// min / max sidebar width
var MIN_WIDTH = 100;
var MAX_WIDTH = 500;
// The Project Manager actually handles rendering and interfacing with the rest
// of the code. Commands are bound to a singleton instance, but it's technically
// not picky about being the only one.
var ProjectManager = function(element) {
this.directories = [];
this.pathMap = {};
this.expanded = {};
this.project = null;
this.projectFile = null;
this.resizing = false;
if (element) {
this.setElement(element);
}
this.loading = false;
var self = this;
chrome.storage.local.get("retainedProject", function(data) {
if (data.retainedProject) {
var retained = data.retainedProject;
if (typeof retained == "string") {
retained = {
id: retained
};
}
self.loading = true;
self.render();
var file = new File();
var onFail = function() {
self.loading = false;
self.render();
chrome.storage.local.remove("retainedProject");
}
file.onWrite = self.watchProjectFile.bind(self);
file.restore(retained.id, function(err, f) {
if (err) {
return onFail();
}
file.read(function(err, data) {
if (err) {
return onFail();
}
self.projectFile = file;
self.loadProject(JSON.parse(data));
});
});
}
});
};
var blacklistRegExp = function(config) {
//avoid race condition when reloading
var blacklist = (config || Settings.get("user")).ignoreFiles;
if (blacklist) {
return new RegExp(blacklist);
}
return null;
}
ProjectManager.prototype = {
element: null,
addDirectory: function(c) {
var self = this;
chrome.fileSystem.chooseEntry({ type: "openDirectory" }, function(d) {
if (!d) return;
self.insertDirectory(d);
});
},
insertDirectory: function(entry) {
var root;
this.element.addClass("loading");
//ensure we aren't duplicating
chrome.fileSystem.getDisplayPath(entry, path => {
this.directories.forEach(function(directoryNode){
if (directoryNode.path == path) {
root = directoryNode;
}
});
//if this is the first, go ahead and start the slideout
if (!this.directories.length) {
this.element.addClass("show");
}
if (!root) {
root = new FSNode(entry);
root.path = path;
this.directories.push(root);
}
//if the directory was there, we still want
//to refresh it, in response to the users
//interaction
var self = this;
tick(function() {
root.walk(blacklistRegExp(), function() {
self.render()
});
});
});
},
removeDirectory: function(args) {
this.directories = this.directories.filter(function(node) {
return node.id != args.id;
});
this.render();
},
removeAllDirectories: function() {
this.directories = [];
this.render();
},
refresh: function() {
var counter = 0;
var self = this;
this.element.addClass("loading");
var check = function() {
counter++;
if (counter == self.directories.length) {
//render() should get rid of the class, but let's be sure
self.element.removeClass("loading");
self.render();
}
};
blacklist = blacklistRegExp();
this.directories.forEach(function(d) {
d.walk(blacklist, check);
});
},
render: function() {
if (!this.element) return;
//Ace doesn't know about non-window resize events
//moving the panel will screw up its dimensions
setTimeout(function() {
editor.resize();
}, 500);
var tree = this.element.find(".tree");
this.pathMap = {};
if (this.directories.length == 0 && !this.loading) {
this.element.removeClass("show");
this.element.style.width = null;
tree.innerHTML = "";
return;
}
var self = this;
this.element.addClass("show");
if (this.loading) {
this.element.addClass("loading");
}
var walker = function(node) {
var li = document.createElement("li");
if (node.isDirectory) {
var isRoot = self.directories.indexOf(node) != -1;
var nodeData = {
label: node.label,
path: node.entry.fullPath,
contextMenu: context.makeURL(isRoot ? "root/directory" : "directory", node.id)
};
var a = inflate.get("templates/projectDir.html", nodeData);
li.append(a);
if (self.expanded[node.entry.fullPath]) {
li.addClass("expanded");
}
var ul = document.createElement("ul");
node.children.sort(function(a, b) {
if (a.isDirectory != b.isDirectory) {
//sneaky casting trick
return ~~b.isDirectory - ~~a.isDirectory;
}
if (a.label < b.label) return -1;
if (a.label > b.label) return 1;
return 0;
});
for (var i = 0; i < node.children.length; i++) {
ul.append(walker(node.children[i]));
}
li.append(ul);
} else {
var nodeData = {
path: node.entry.fullPath,
contextMenu: context.makeURL("file", node.entry.fullPath.replace(/[\/\\]/g, "@")),
label: node.label
};
var a = inflate.get("templates/projectFile.html", nodeData)
li.append(a);
self.pathMap[node.entry.fullPath] = node;
}
return li;
};
//we give the load bar a chance to display before rendering
tick(function() {
var trees = self.directories.map(walker);
var list = document.createElement("ul");
trees.forEach(function(dir) {
dir.classList.add("root");
dir.classList.add("expanded");
list.appendChild(dir);
});
tree.innerHTML = "";
tree.appendChild(list);
if (!self.loading) {
self.element.removeClass("loading");
}
});
},
setElement: function(el) {
this.element = el;
this.bindEvents();
},
bindEvents: function() {
var self = this;
this.element.on("click", function(e) {
e.preventDefault();
var target = e.target;
if (target.hasClass("directory")) {
target.parentElement.toggle("expanded");
var path = target.getAttribute("data-full-path");
self.expanded[path] = !!!self.expanded[path];
}
editor.focus();
});
// make sure width is not set in element `style`
this.element.style.width = null;
var handle = this.element.find('.project-resizer');
this.startResize = this.startResize.bind(this);
this.stopResize = this.stopResize.bind(this);
this.resize = this.resize.bind(this);
handle.on('mousedown', this.startResize);
},
startResize: function (e) {
// do not resize when 'autohide' is on
if (this.element.hasClass('autohide')) return;
e.preventDefault();
e.stopPropagation();
this.element.addClass('resizing');
this.resizing = true;
document.on('mousemove', this.resize);
document.on('mouseup', this.stopResize);
},
resize: function (e) {
if (!this.resizing) return;
var mouseX = e.pageX;
if (mouseX > MIN_WIDTH && mouseX < MAX_WIDTH) {
this.element.style.width = e.pageX + 8 + 'px';
}
},
stopResize: function (e) {
if (!this.resizing) return;
e.preventDefault();
e.stopPropagation();
this.element.removeClass('resizing');
this.resizing = false;
document.off('mousemove', this.resize);
document.off('mouseup', this.stopResize);
//Ace doesn't know about non-window resize events
//moving the panel will screw up its dimensions
setTimeout(function() {
editor.resize();
}, 100);
},
openFile: function(path, c) {
var self = this;
var found = false;
var node = this.pathMap[path];
if (!node) return;
//walk through existing tabs to see if it's already open
var tabs = sessions.getAllTabs();
chrome.fileSystem.getDisplayPath(node.entry, function(path) {
//look through the tabs for matching display paths
M.map(
tabs,
function(tab, i, c) {
if (!tab.file || tab.file.virtual) {
return c(false);
}
tab.file.getPath(function(err, p) {
if (p == path) {
sessions.setCurrent(tab);
found = true;
}
//we don't actually use the result
c();
});
},
//if no match found, create a tab
function() {
if (found) {
if (c) {
c();
}
return;
}
var file = new File(node.entry);
file.read(function(err, data) {
sessions.addFile(data, file);
if (c) {
c();
}
});
}
);
});
},
generateProject: function() {
var project = this.project || {};
//everything but "folders" is left as-is
//run through all directories, retain them, and add to the structure
project.folders = this.directories.map(function(node) {
var id = chrome.fileSystem.retainEntry(node.entry);
return {
retained: id,
path: node.entry.fullPath
};
});
var json = JSON.stringify(project, null, 2);
if (this.projectFile) {
this.projectFile.write(json);
} else {
var file = new File();
var watch = this.watchProjectFile.bind(this);
var self = this;
file.open("save", function() {
file.write(json);
var id = file.retain();
chrome.storage.local.set({retainedProject: id});
file.onWrite = watch;
self.projectFile = file;
});
}
return json;
},
openProjectFile: function() {
var file = new File();
var self = this;
file.open(function() {
file.read(function(err, data) {
self.loadProject(data);
var retained = file.retain();
chrome.storage.local.set({retainedProject: retained});
self.projectFile = file;
file.onWrite = self.watchProjectFile.bind(self);
});
});
},
watchProjectFile: function() {
var self = this;
this.projectFile.read(function(err, data) {
self.loadProject(data);
});
},
loadProject: function(project) {
var self = this;
//project is the JSON from a project file
if (typeof project == "string") {
project = JSON.parse(project);
}
this.project = project;
//assign settings
if (project.settings) {
Settings.setProject(project.settings);
}
this.loading = true;
this.element.addClass("loading");
//restore directory entries that can be restored
this.directories = [];
blacklist = blacklistRegExp(project.settings);
M.map(
project.folders,
function(folder, index, c) {
chrome.fileSystem.restoreEntry(folder.retained, function(entry) {
//remember, you can only restore project directories you'd previously opened
if (!entry) return c();
chrome.fileSystem.getDisplayPath(entry, function(path) {
var node = new FSNode(entry);
node.path = path;
//if this is the first, go ahead and start the slideout
if (!self.directories.length) {
self.element.addClass("show");
}
self.directories.push(node);
node.walk(blacklist, c);
});
});
},
function() {
self.loading = false;
self.render();
}
);
},
editProjectFile: function() {
if (!this.projectFile) {
return dialog(i18n.get("projectNoCurrentProject"));
}
var self = this;
this.projectFile.read(function(err, data) {
sessions.addFile(data, self.projectFile);
});
},
clearProject: function(keepRetained) {
this.projectFile = null;
this.directories = [];
this.project = {};
Settings.clearProject();
if (!keepRetained) chrome.storage.local.remove("retainedProject");
this.render();
},
getPaths: function() {
return Object.keys(this.pathMap);
},
};
var pm = new ProjectManager(document.find(".project"));
command.on("project:add-dir", pm.addDirectory.bind(pm));
command.on("project:remove-all", pm.removeAllDirectories.bind(pm));
command.on("project:generate", pm.generateProject.bind(pm));
command.on("project:open-file", pm.openFile.bind(pm));
command.on("project:refresh-dir", pm.refresh.bind(pm));
command.on("project:open", pm.openProjectFile.bind(pm));
command.on("project:edit", pm.editProjectFile.bind(pm));
command.on("project:clear", pm.clearProject.bind(pm));
context.register("Remove from Project", "removeDirectory", "root/directory/:id", pm.removeDirectory.bind(pm));
var setAutoHide = function() {
var hide = Settings.get("user").autoHideProject;
if (hide) {
pm.element.classList.add("autohide");
pm.element.style.width = null;
} else {
pm.element.classList.remove("autohide");
}
}
command.on("init:startup", setAutoHide);
command.on("init:restart", setAutoHide);
return pm;
});