-
-
Notifications
You must be signed in to change notification settings - Fork 205
Expand file tree
/
Copy pathExtensionManagerViewModel.js
More file actions
671 lines (597 loc) · 25.3 KB
/
Copy pathExtensionManagerViewModel.js
File metadata and controls
671 lines (597 loc) · 25.3 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
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
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
/*
* GNU AGPL-3.0 License
*
* Copyright (c) 2021 - present core.ai . All rights reserved.
* Original work Copyright (c) 2013 - 2021 Adobe Systems Incorporated. All rights reserved.
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License
* for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see https://opensource.org/licenses/AGPL-3.0.
*
*/
/*unittests: ExtensionManager*/
define(function (require, exports, module) {
var _ = require("thirdparty/lodash");
const ExtensionManager = require("extensibility/ExtensionManager"),
registry_utils = require("extensibility/registry_utils"),
EventDispatcher = require("utils/EventDispatcher"),
Strings = require("strings"),
PreferencesManager = require("preferences/PreferencesManager");
/**
* @private
* @type {Array}
* A list of fields to search when trying to search for a query string in an object. Each field is
* represented as an array of keys to recurse downward through the object. We store this here to avoid
* doing it for each search call.
*/
var _searchFields = [["metadata", "name"], ["metadata", "title"], ["metadata", "description"],
["metadata", "author", "name"], ["metadata", "keywords"], ["owner"]];
/**
* The base model for the ExtensionManagerView. Keeps track of the extensions that are currently visible
* and manages sorting/filtering them. Must be disposed with dispose() when done.
* Events:
* - change - triggered when the data for a given extension changes. Second parameter is the extension id.
* - filter - triggered whenever the filtered set changes (including on initialize).
*
* @constructor
*/
function ExtensionManagerViewModel() {
this._handleStatusChange = this._handleStatusChange.bind(this);
// Listen for extension status changes.
ExtensionManager
.on("statusChange." + this.source, this._handleStatusChange)
.on("registryUpdate." + this.source, this._handleStatusChange);
}
EventDispatcher.makeEventDispatcher(ExtensionManagerViewModel.prototype);
/**
* @type {string}
* Constant indicating that this model/view should initialize from the main extension registry.
*/
ExtensionManagerViewModel.prototype.SOURCE_REGISTRY = "registry";
/**
* @type {string}
* Constant indicating that this model/view should initialize from the main extension registry with only themes.
*/
ExtensionManagerViewModel.prototype.SOURCE_THEMES = "themes";
/**
* @type {string}
* Constant indicating that this model/view should initialize from the list of locally installed extensions.
*/
ExtensionManagerViewModel.prototype.SOURCE_INSTALLED = "installed";
/**
* @type {string}
* Constant indicating that this model/view should initialize from the list of default bundled extensions.
*/
ExtensionManagerViewModel.prototype.SOURCE_DEFAULT = "default";
/**
* @type {Object}
* The current set of extensions managed by this model. Same as ExtensionManager.extensions.
*/
ExtensionManagerViewModel.prototype.extensions = null;
/**
* @type {string}
* The current source for the model; one of the SOURCE_* keys above.
*/
ExtensionManagerViewModel.prototype.source = null;
/**
* @type {Array.<Object>}
* The list of IDs of items matching the current query and sorted with the current sort.
*/
ExtensionManagerViewModel.prototype.filterSet = null;
/**
* @type {Object}
* The list of all ids from the extension list, sorted with the current sort.
*/
ExtensionManagerViewModel.prototype.sortedFullSet = null;
/**
* @private
* @type {string}
* The last query we filtered by. Used to optimize future searches.
*/
ExtensionManagerViewModel.prototype._lastQuery = null;
/**
* @type {string}
* Info message to display to the user when listing extensions
*/
ExtensionManagerViewModel.prototype.infoMessage = null;
/**
* @type {string}
* An optional message to display to the user
*/
ExtensionManagerViewModel.prototype.message = null;
/**
* @type {number}
* Number to show in tab's notification icon. No icon shown if 0.
*/
ExtensionManagerViewModel.prototype.notifyCount = 0;
/**
* @private {$.Promise}
* Internal use only to track when initialization fails, see usage in _updateMessage.
*/
ExtensionManagerViewModel.prototype._initializeFromSourcePromise = null;
/**
* Unregisters listeners when we're done.
*/
ExtensionManagerViewModel.prototype.dispose = function () {
this.trigger("dispose");
ExtensionManager.off("." + this.source);
};
/**
* @private
* Sets up the initial filtered set based on the sorted full set.
*/
ExtensionManagerViewModel.prototype._setInitialFilter = function () {
// Initial filtered list is the same as the sorted list.
this.filterSet = _.clone(this.sortedFullSet);
this.trigger("filter");
};
/**
* @private
* Re-sorts the current full set based on the source we're viewing.
* The base implementation does nothing.
*/
ExtensionManagerViewModel.prototype._sortFullSet = function () { };
/**
* Initializes the model from the source.
*/
ExtensionManagerViewModel.prototype.initialize = function () {
var self = this;
this._initializeFromSourcePromise = this._initializeFromSource().always(function () {
self._updateMessage();
});
return this._initializeFromSourcePromise;
};
/**
* @private
* Updates the initial set and filter as necessary when the status of an extension changes,
* and notifies listeners of the change.
* @param {$.Event} e The jQuery event object.
* @param {string} id The id of the extension whose status changed.
*/
ExtensionManagerViewModel.prototype._handleStatusChange = function (e, id) {
this.trigger("change", id);
};
/**
* @private
* Searches for the given query in the current extension list and updates the filter set,
* dispatching a filter event.
* @param {string} query The string to search for.
* @param {boolean} force If true, always filter starting with the full set, not the last
* query's filter.
*/
ExtensionManagerViewModel.prototype.filter = function (query, force) {
var self = this, initialList;
if (!force && this._lastQuery && query.indexOf(this._lastQuery) === 0) {
// This is the old query with some new letters added, so we know we can just
// search in the current filter set. (This is true even if query has spaces).
initialList = this.filterSet;
} else {
// This is a new query, so start with the full list.
initialList = this.sortedFullSet;
}
var keywords = query.toLowerCase().split(/\s+/);
// Takes 'extensionList' and returns a version filtered to only those that match 'keyword'
function filterForKeyword(extensionList, word) {
var filteredList = [];
extensionList.forEach(function (id) {
var entry = self._getEntry(id);
if (entry && self._entryMatchesQuery(entry, word)) {
filteredList.push(id);
}
});
return filteredList;
}
// "AND" the keywords together: successively filter down the result set by each keyword in turn
var i, currentList = initialList;
for (i = 0; i < keywords.length; i++) {
currentList = filterForKeyword(currentList, keywords[i]);
}
this._lastQuery = query;
this.filterSet = currentList;
this._updateMessage();
this.trigger("filter");
};
/**
* @private
* Updates an optional message displayed to the user along with the extension list.
*/
ExtensionManagerViewModel.prototype._updateMessage = function () {
if (this._initializeFromSourcePromise && this._initializeFromSourcePromise.state() === "rejected") {
this.message = Strings.EXTENSION_MANAGER_ERROR_LOAD;
} else if (this.filterSet && this.filterSet.length === 0) {
this.message = this.sortedFullSet && this.sortedFullSet.length ? Strings.NO_EXTENSION_MATCHES : Strings.NO_EXTENSIONS;
} else {
this.message = null;
}
};
/**
* @private
* This is to be overridden by subclasses to provide the metadata for the extension
* with the provided `id`.
*
* @param {string} id of the extension
* @return {Object?} extension metadata or null if there's no matching extension
*/
ExtensionManagerViewModel.prototype._getEntry = function (id) {
return null;
};
/**
* @private
* Tests if the given entry matches the query.
* @param {Object} entry The extension entry to test.
* @param {string} query The query to match against.
* @return {boolean} Whether the query matches.
*/
ExtensionManagerViewModel.prototype._entryMatchesQuery = function (entry, query) {
return query === "" ||
_searchFields.some(function (fieldSpec) {
var i, cur = entry;
for (i = 0; i < fieldSpec.length; i++) {
// Recurse downward through the specified fields to the leaf value.
cur = cur[fieldSpec[i]];
if (!cur) {
return false;
}
}
// If the leaf value is an array (like keywords), search each item, otherwise
// just search in the string.
if (Array.isArray(cur)) {
return cur.some(function (keyword) {
return keyword.toLowerCase().indexOf(query) !== -1;
});
} else if (fieldSpec[fieldSpec.length - 1] === "owner") {
// Special handling: ignore the authentication source when querying,
// since it's not useful to search on
var components = cur.split(":");
if (components[1].toLowerCase().indexOf(query) !== -1) {
return true;
}
} else if (cur.toLowerCase().indexOf(query) !== -1) {
return true;
}
});
};
ExtensionManagerViewModel.prototype._setSortedExtensionList = function (extensions, isTheme) {
this.filterSet = this.sortedFullSet = registry_utils.sortRegistry(extensions, "registryInfo", PreferencesManager.get("extensions.sort"))
.filter(function (entry) {
if (!isTheme) {
return entry.registryInfo && !entry.registryInfo.metadata.theme;
}
return entry.registryInfo && entry.registryInfo.metadata.theme;
})
.filter(function (entry) {
return !ExtensionManager.isExtensionTakenDown(entry.registryInfo.metadata.name);
})
.map(function (entry) {
return entry.registryInfo.metadata.name;
});
};
/**
* The model for the ExtensionManagerView that is responsible for handling registry-based extensions.
* This extends ExtensionManagerViewModel.
* Must be disposed with dispose() when done.
*
* Events:
* - change - triggered when the data for a given extension changes. Second parameter is the extension id.
* - filter - triggered whenever the filtered set changes (including on initialize).
*
* @constructor
*/
function RegistryViewModel() {
ExtensionManagerViewModel.call(this);
this.infoMessage = `<div style="display: flex; justify-content: space-between;">
<div style="margin-top: 3px; width: 80%;">${Strings.REGISTRY_SANITY_CHECK_WARNING}</div>
<div>
<button class="dialog-button btn primary btn-mini createExtesnion"
style="white-space: nowrap;">
${Strings.EXTENSION_MANAGER_CREATE_EXTENSION}</button>
</div>
</div>`;
}
RegistryViewModel.prototype = Object.create(ExtensionManagerViewModel.prototype);
RegistryViewModel.prototype.constructor = RegistryViewModel;
/**
* @type {string}
* RegistryViewModels always have a source of SOURCE_REGISTRY.
*/
RegistryViewModel.prototype.source = ExtensionManagerViewModel.prototype.SOURCE_REGISTRY;
/**
* Initializes the model from the remote extension registry.
* @return {$.Promise} a promise that's resolved with the registry JSON data
* or rejected if the server can't be reached.
*/
RegistryViewModel.prototype._initializeFromSource = function () {
var self = this;
return ExtensionManager.downloadRegistry()
.done(function () {
self.extensions = ExtensionManager.extensions;
// Sort the registry by last published date and store the sorted list of IDs.
self._setSortedExtensionList(ExtensionManager.extensions, false);
self._setInitialFilter();
})
.fail(function () {
self.extensions = [];
self.sortedFullSet = [];
self.filterSet = [];
});
};
/**
* @private
* Finds the extension metadata by id. If there is no extension matching the given id,
* this returns `null`.
* @param {string} id of the extension
* @return {Object?} extension metadata or null if there's no matching extension
*/
RegistryViewModel.prototype._getEntry = function (id) {
var entry = this.extensions[id];
if (entry) {
return entry.registryInfo;
}
return entry;
};
/**
* The model for the ExtensionManagerView that is responsible for handling previously-installed extensions.
* This extends ExtensionManagerViewModel.
* Must be disposed with dispose() when done.
*
* Events:
* - change - triggered when the data for a given extension changes. Second parameter is the extension id.
* - filter - triggered whenever the filtered set changes (including on initialize).
*
* @constructor
*/
function InstalledViewModel() {
ExtensionManagerViewModel.call(this);
// when registry is downloaded, sort extensions again - those with updates will be before others
var self = this;
ExtensionManager.on("registryDownload." + this.source, function () {
self._sortFullSet();
self._setInitialFilter();
});
this.infoMessage = `<div style="display: flex; justify-content: space-between;">
<div style="margin-top: 3px;">${Strings.EXTENSION_MANAGER_THEMES_INFO}</div>
<div>
<button id="InstalledViewThemeRevert" class="dialog-button btn btn-mini undoTheme forced-hidden">
${Strings.EXTENSION_MANAGER_THEMES_UNDO}</button>
</div>
</div>`;
}
InstalledViewModel.prototype = Object.create(ExtensionManagerViewModel.prototype);
InstalledViewModel.prototype.constructor = InstalledViewModel;
/**
* @type {string}
* InstalledViewModels always have a source of SOURCE_INSTALLED.
*/
InstalledViewModel.prototype.source = ExtensionManagerViewModel.prototype.SOURCE_INSTALLED;
/**
* Initializes the model from the set of locally installed extensions, sorted
* alphabetically by id (or name of the extension folder for legacy extensions).
* @return {$.Promise} a promise that's resolved when we're done initializing.
*/
InstalledViewModel.prototype._initializeFromSource = function () {
var self = this;
this.extensions = ExtensionManager.extensions;
this.sortedFullSet = Object.keys(this.extensions)
.filter(function (key) {
return self.extensions[key].installInfo &&
self.extensions[key].installInfo.locationType !== ExtensionManager.LOCATION_DEFAULT;
});
this._sortFullSet();
this._setInitialFilter();
this._countUpdates();
return new $.Deferred().resolve().promise();
};
/**
* @private
* Re-sorts the current full set
*/
InstalledViewModel.prototype._sortFullSet = function () {
var self = this;
this.sortedFullSet = this.sortedFullSet.sort(function (key1, key2) {
// before sorting by name, put first extensions that have updates
var ua1 = self.extensions[key1].installInfo.updateAvailable,
ua2 = self.extensions[key2].installInfo.updateAvailable;
if (ua1 && !ua2) {
return -1;
} else if (!ua1 && ua2) {
return 1;
}
var metadata1 = self.extensions[key1].installInfo.metadata,
metadata2 = self.extensions[key2].installInfo.metadata,
id1 = (metadata1.title || metadata1.name).toLocaleLowerCase(),
id2 = (metadata2.title || metadata2.name).toLocaleLowerCase();
return id1.localeCompare(id2);
});
};
/**
* @private
* Updates notifyCount based on number of extensions with an update available
*/
InstalledViewModel.prototype._countUpdates = function () {
var self = this;
this.notifyCount = 0;
this.sortedFullSet.forEach(function (key) {
if (self.extensions[key].installInfo.updateCompatible && !ExtensionManager.isMarkedForUpdate(key)) {
self.notifyCount++;
}
});
};
/**
* @private
* Updates the initial set and filter as necessary when the status of an extension changes,
* and notifies listeners of the change.
* @param {$.Event} e The jQuery event object.
* @param {string} id The id of the extension whose status changed.
*/
InstalledViewModel.prototype._handleStatusChange = function (e, id) {
var index = this.sortedFullSet.indexOf(id),
refilter = false;
if (index !== -1 && !this.extensions[id].installInfo) {
// This was in our set, but was uninstalled. Remove it.
this.sortedFullSet.splice(index, 1);
this._countUpdates(); // may also affect update count
refilter = true;
} else if (index === -1 && this.extensions[id].installInfo) {
// This was not in our set, but is now installed. Add it and resort.
this.sortedFullSet.push(id);
this._sortFullSet();
refilter = true;
}
if (refilter) {
this.filter(this._lastQuery || "", true);
}
if (this.extensions[id].installInfo) {
// If our count of available updates may have been affected, re-count
this._countUpdates();
}
ExtensionManagerViewModel.prototype._handleStatusChange.call(this, e, id);
};
/**
* @private
* Finds the extension metadata by id. If there is no extension matching the given id,
* this returns `null`.
* @param {string} id of the extension
* @return {Object?} extension metadata or null if there's no matching extension
*/
InstalledViewModel.prototype._getEntry = function (id) {
var entry = this.extensions[id];
if (entry) {
return entry.installInfo;
}
return entry;
};
/**
* Model for displaying default extensions that come bundled with Brackets
*/
function DefaultViewModel() {
ExtensionManagerViewModel.call(this);
}
// Inheritance setup
DefaultViewModel.prototype = Object.create(ExtensionManagerViewModel.prototype);
DefaultViewModel.prototype.constructor = DefaultViewModel;
/**
* Add SOURCE_DEFAULT to DefaultViewModel
*/
DefaultViewModel.prototype.source = ExtensionManagerViewModel.prototype.SOURCE_DEFAULT;
/**
* Initializes the model from the set of default extensions, sorted alphabetically by id
* @return {$.Promise} a promise that's resolved when we're done initializing.
*/
DefaultViewModel.prototype._initializeFromSource = function () {
var self = this;
this.extensions = ExtensionManager.extensions;
this.sortedFullSet = Object.keys(this.extensions)
.filter(function (key) {
return self.extensions[key].installInfo &&
self.extensions[key].installInfo.locationType === ExtensionManager.LOCATION_DEFAULT;
})
.filter(function (key) {
return !ExtensionManager.isExtensionTakenDown(key);
});
this._sortFullSet();
this._setInitialFilter();
return new $.Deferred().resolve().promise();
};
/**
* @private
* Re-sorts the current full set
*/
DefaultViewModel.prototype._sortFullSet = function () {
var self = this;
this.sortedFullSet = this.sortedFullSet.sort(function (key1, key2) {
var metadata1 = self.extensions[key1].installInfo.metadata,
metadata2 = self.extensions[key2].installInfo.metadata,
id1 = (metadata1.title || metadata1.name).toLocaleLowerCase(),
id2 = (metadata2.title || metadata2.name).toLocaleLowerCase();
return id1.localeCompare(id2);
});
};
/**
* @private
* Finds the default extension metadata by id. If there is no default extension matching the given id,
* this returns `null`.
* @param {string} id of the theme extension
* @return {Object?} extension metadata or null if there's no matching extension
*/
DefaultViewModel.prototype._getEntry = function (id) {
return this.extensions[id] ? this.extensions[id].installInfo : null;
};
/**
* The model for the ExtensionManagerView that is responsible for handling registry-based theme extensions.
* This extends ExtensionManagerViewModel.
* Must be disposed with dispose() when done.
*
* Events:
* - change - triggered when the data for a given extension changes. Second parameter is the extension id.
* - filter - triggered whenever the filtered set changes (including on initialize).
*
* @constructor
*/
function ThemesViewModel() {
ExtensionManagerViewModel.call(this);
this.infoMessage = `<div style="display: flex; justify-content: space-between;">
<div style="margin-top: 3px;">${Strings.EXTENSION_MANAGER_THEMES_INFO}</div>
<div>
<button id="ThemeViewThemeRevert" class="dialog-button btn btn-mini undoTheme forced-hidden">
${Strings.EXTENSION_MANAGER_THEMES_UNDO}</button>
<button class="dialog-button btn btn-mini createTheme primary"
style="white-space: nowrap;">
${Strings.EXTENSION_MANAGER_CREATE_THEME}</button>
</div>
</div>`;
}
// Inheritance setup
ThemesViewModel.prototype = Object.create(ExtensionManagerViewModel.prototype);
ThemesViewModel.prototype.constructor = ThemesViewModel;
/**
* @type {string}
* ThemeViewModels always have a source of SOURCE_THEMES.
*/
ThemesViewModel.prototype.source = ExtensionManagerViewModel.prototype.SOURCE_THEMES;
/**
* Initializes the model from the remote extension registry.
* @return {$.Promise} a promise that's resolved with the registry JSON data.
*/
ThemesViewModel.prototype._initializeFromSource = function () {
var self = this;
return ExtensionManager.downloadRegistry()
.done(function () {
self.extensions = ExtensionManager.extensions;
// Sort the registry by last published date and store the sorted list of IDs.
self._setSortedExtensionList(ExtensionManager.extensions, true);
self._setInitialFilter();
})
.fail(function () {
self.extensions = [];
self.sortedFullSet = [];
self.filterSet = [];
});
};
/**
* @private
* Finds the theme extension metadata by id. If there is no theme extension matching the given id,
* this returns `null`.
* @param {string} id of the theme extension
* @return {Object?} extension metadata or null if there's no matching extension
*/
ThemesViewModel.prototype._getEntry = function (id) {
var entry = this.extensions[id];
if (entry) {
return entry.registryInfo;
}
return entry;
};
exports.RegistryViewModel = RegistryViewModel;
exports.ThemesViewModel = ThemesViewModel;
exports.InstalledViewModel = InstalledViewModel;
exports.DefaultViewModel = DefaultViewModel;
});