Rework libraryTreeView event handling

Changes `libraryTreeView::addEventListener('load')` and similar to
`libraryTreeView::onLoad.addListener(listener, once)`, etc. `once` is an
optional boolean that, when true, causes the listener to fire once and
then be removed. This is implicit for 'load'.

'load' maintains its special behavior of running immediately if the
treeview has already been loaded.

Also adds `waitForLoad()` and `waitForSelect()` functions that return
promises on event completion, since most uses of those events were just
resolving deferreds.
This commit is contained in:
Dan Stillman 2017-03-24 05:18:55 -04:00
parent 1a4b7121d3
commit 820755e152
10 changed files with 105 additions and 99 deletions

View file

@ -661,11 +661,9 @@ var Zotero_Citation_Dialog = new function () {
_multipleSourceButton.disabled = false; _multipleSourceButton.disabled = false;
} }
} else { } else {
collectionsView.addEventListener('load', Zotero.Promise.coroutine(function* () { collectionsView.onLoad.addListener(Zotero.Promise.coroutine(function* () {
if (itemsView) { if (itemsView) {
var deferred = Zotero.Promise.defer(); yield itemsView.waitForLoad();
itemsView.addEventListener('load', () => deferred.resolve());
yield deferred.promise;
_acceptButton.disabled = !itemsView.getSelectedItems().length; _acceptButton.disabled = !itemsView.getSelectedItems().length;
} }
})); }));

View file

@ -49,9 +49,7 @@ var doLoad = Zotero.Promise.coroutine(function* () {
collectionsView.hideSources = ['duplicates', 'trash', 'feeds']; collectionsView.hideSources = ['duplicates', 'trash', 'feeds'];
document.getElementById('zotero-collections-tree').view = collectionsView; document.getElementById('zotero-collections-tree').view = collectionsView;
var deferred = Zotero.Promise.defer(); yield collectionsView.waitForLoad();
collectionsView.addEventListener('load', () => deferred.resolve());
yield deferred.promise;
connectionSelectedDeferred = Zotero.Promise.defer(); connectionSelectedDeferred = Zotero.Promise.defer();
yield connectionSelectedDeferred.promise; yield connectionSelectedDeferred.promise;
@ -93,9 +91,7 @@ var onCollectionSelected = Zotero.Promise.coroutine(function* ()
// Create items list and wait for it to load // Create items list and wait for it to load
itemsView = new Zotero.ItemTreeView(collectionTreeRow, (window.arguments[1] ? true : false)); itemsView = new Zotero.ItemTreeView(collectionTreeRow, (window.arguments[1] ? true : false));
document.getElementById('zotero-items-tree').view = itemsView; document.getElementById('zotero-items-tree').view = itemsView;
var deferred = Zotero.Promise.defer(); yield itemsView.waitForLoad();
itemsView.addEventListener('load', () => deferred.resolve());
yield deferred.promise;
clearItemsPaneMessage(); clearItemsPaneMessage();

View file

@ -120,7 +120,7 @@ Zotero.CollectionTreeView.prototype.setTree = Zotero.Promise.coroutine(function*
} }
this.selection.selectEventsSuppressed = false; this.selection.selectEventsSuppressed = false;
yield this._runListeners('load'); yield this.runListeners('load');
this._initialized = true; this._initialized = true;
} }
catch (e) { catch (e) {
@ -301,10 +301,9 @@ Zotero.CollectionTreeView.prototype.selectWait = Zotero.Promise.method(function
if (this.selection.currentIndex == row) { if (this.selection.currentIndex == row) {
return; return;
}; };
var deferred = Zotero.Promise.defer(); var promise = this.waitForSelect();
this.addEventListener('select', () => deferred.resolve());
this.selection.select(row); this.selection.select(row);
return deferred.promise; return promise;
}); });
@ -516,10 +515,9 @@ Zotero.CollectionTreeView.prototype.notify = Zotero.Promise.coroutine(function*
this._rememberScrollPosition(scrollPosition); this._rememberScrollPosition(scrollPosition);
var deferred = Zotero.Promise.defer(); var promise = this.waitForSelect();
this.addEventListener('select', () => deferred.resolve());
this.selection.selectEventsSuppressed = false; this.selection.selectEventsSuppressed = false;
return deferred.promise; return promise;
}); });
/** /**
@ -1180,9 +1178,7 @@ Zotero.CollectionTreeView.prototype.selectItem = Zotero.Promise.coroutine(functi
return false; return false;
} }
var deferred = Zotero.Promise.defer(); yield this.waitForLoad();
this.addEventListener('load', () => deferred.resolve());
yield deferred.promise;
var currentLibraryID = this.getSelectedLibraryID(); var currentLibraryID = this.getSelectedLibraryID();
// If in a different library // If in a different library
@ -1198,9 +1194,7 @@ Zotero.CollectionTreeView.prototype.selectItem = Zotero.Promise.coroutine(functi
var itemsView = this.selectedTreeRow.itemTreeView; var itemsView = this.selectedTreeRow.itemTreeView;
deferred = Zotero.Promise.defer(); yield itemsView.waitForLoad();
itemsView.addEventListener('load', () => deferred.resolve());
yield deferred.promise;
var selected = yield itemsView.selectItem(itemID, expand); var selected = yield itemsView.selectItem(itemID, expand);
if (selected) { if (selected) {
@ -1217,9 +1211,7 @@ Zotero.CollectionTreeView.prototype.selectItem = Zotero.Promise.coroutine(functi
} }
itemsView = this.selectedTreeRow.itemTreeView; itemsView = this.selectedTreeRow.itemTreeView;
deferred = Zotero.Promise.defer(); yield itemsView.waitForLoad();
itemsView.addEventListener('load', () => deferred.resolve());
yield deferred.promise;
return itemsView.selectItem(itemID, expand); return itemsView.selectItem(itemID, expand);
}); });

View file

@ -276,7 +276,7 @@ Zotero.ItemTreeView.prototype.setTree = Zotero.Promise.coroutine(function* (tree
Zotero.debug("Set tree for items view " + this.id + " in " + (Date.now() - start) + " ms"); Zotero.debug("Set tree for items view " + this.id + " in " + (Date.now() - start) + " ms");
this._initialized = true; this._initialized = true;
yield this._runListeners('load'); yield this.runListeners('load');
} }
catch (e) { catch (e) {
Zotero.debug(e, 1); Zotero.debug(e, 1);
@ -953,14 +953,14 @@ Zotero.ItemTreeView.prototype.notify = Zotero.Promise.coroutine(function* (actio
}*/ }*/
//this._treebox.endUpdateBatch(); //this._treebox.endUpdateBatch();
let selectPromise;
if (madeChanges) { if (madeChanges) {
var deferred = Zotero.Promise.defer(); selectPromise = this.waitForSelect();
this.addEventListener('select', () => deferred.resolve());
} }
this.selection.selectEventsSuppressed = false; this.selection.selectEventsSuppressed = false;
if (madeChanges) { if (madeChanges) {
Zotero.debug("Yielding for select promise"); // TEMP Zotero.debug("Yielding for select promise"); // TEMP
return deferred.promise; return selectPromise;
} }
}); });
@ -1735,12 +1735,12 @@ Zotero.ItemTreeView.prototype.selectItem = Zotero.Promise.coroutine(function* (i
// here, which means that 'yield selectItem(itemID)' continues before the itembox has been // here, which means that 'yield selectItem(itemID)' continues before the itembox has been
// refreshed. To get around this, we wait for a select event that's triggered by // refreshed. To get around this, we wait for a select event that's triggered by
// itemSelected() when it's done. // itemSelected() when it's done.
let promise;
if (this.selection.selectEventsSuppressed) { if (this.selection.selectEventsSuppressed) {
this.selection.select(row); this.selection.select(row);
} }
else { else {
var deferred = Zotero.Promise.defer(); promise = this.waitForSelect();
this.addEventListener('select', () => deferred.resolve());
this.selection.select(row); this.selection.select(row);
} }
@ -1750,8 +1750,8 @@ Zotero.ItemTreeView.prototype.selectItem = Zotero.Promise.coroutine(function* (i
} }
this.selection.select(row); this.selection.select(row);
if (deferred) { if (promise) {
yield deferred.promise; yield promise;
} }
this.betterEnsureRowIsVisible(row, parentRow); this.betterEnsureRowIsVisible(row, parentRow);

View file

@ -25,15 +25,28 @@
Zotero.LibraryTreeView = function () { Zotero.LibraryTreeView = function () {
this._initialized = false; this._initialized = false;
this._listeners = { this._listeners = {};
load: [],
select: []
};
this._rows = []; this._rows = [];
this._rowMap = {}; this._rowMap = {};
this.id = Zotero.Utilities.randomString(); this.id = Zotero.Utilities.randomString();
Zotero.debug("Creating " + this.type + "s view with id " + this.id); Zotero.debug("Creating " + this.type + "s view with id " + this.id);
//
// Create .on(Load|Select).addListener() methods
//
var _createEventBinding = function (event, alwaysOnce) {
return alwaysOnce
? {
addListener: listener => this._addListener(event, listener, true)
}
: {
addListener: (listener, once) => this._addListener(event, listener, once)
};
}.bind(this);
this.onLoad = _createEventBinding('load', true);
this.onSelect = _createEventBinding('select');
}; };
Zotero.LibraryTreeView.prototype = { Zotero.LibraryTreeView.prototype = {
@ -41,31 +54,56 @@ Zotero.LibraryTreeView.prototype = {
return this._initialized; return this._initialized;
}, },
addEventListener: function(event, listener) {
if (event == 'load') { addEventListener: function (event, listener) {
Zotero.logError("Zotero.LibraryTreeView::addEventListener() is deprecated");
this.addListener(event, listener);
},
waitForLoad: function () {
return this._waitForEvent('load');
},
waitForSelect: function () {
return this._waitForEvent('select');
},
runListeners: Zotero.Promise.coroutine(function* (event) {
//Zotero.debug(`Calling ${event} listeners on ${this.type} tree ${this.id}`);
if (!this._listeners[event]) return;
for (let [listener, once] of this._listeners[event].entries()) {
yield Zotero.Promise.resolve(listener.call(this));
if (once) {
this._listeners[event].delete(listener);
}
}
}),
_addListener: function(event, listener, once) {
// If already initialized run now // If already initialized run now
if (this._initialized) { if (event == 'load' && this._initialized) {
listener.call(this); listener.call(this);
} }
else {
this._listeners[event].push(listener);
}
}
else { else {
if (!this._listeners[event]) { if (!this._listeners[event]) {
this._listeners[event] = []; this._listeners[event] = new Map();
} }
this._listeners[event].push(listener); this._listeners[event].set(listener, once);
} }
}, },
_runListeners: Zotero.Promise.coroutine(function* (event) { _waitForEvent: Zotero.Promise.coroutine(function* (event) {
if (!this._listeners[event]) return; if (event == 'load' && this._initialized) {
var listener; return;
while (listener = this._listeners[event].shift()) {
yield Zotero.Promise.resolve(listener.call(this));
} }
return new Zotero.Promise((resolve, reject) => {
this._addListener(event, () => resolve(), true);
});
}), }),
@ -141,7 +179,7 @@ Zotero.LibraryTreeView.prototype = {
}, },
onSelect: function () { runSelectListeners: function () {
return this._runListeners('select'); return this._runListeners('select');
}, },

View file

@ -402,11 +402,11 @@ var ZoteroPane = new function()
// TODO: Remove now that no tab mode? // TODO: Remove now that no tab mode?
var containerWindow = window; var containerWindow = window;
if(containerWindow.zoteroSavedCollectionSelection) { if(containerWindow.zoteroSavedCollectionSelection) {
this.collectionsView.addEventListener('load', Zotero.Promise.coroutine(function* () { this.collectionsView.onLoad.addListener(Zotero.Promise.coroutine(function* () {
yield this.collectionsView.selectByID(containerWindow.zoteroSavedCollectionSelection); yield this.collectionsView.selectByID(containerWindow.zoteroSavedCollectionSelection);
if (containerWindow.zoteroSavedItemSelection) { if (containerWindow.zoteroSavedItemSelection) {
this.itemsView.addEventListener('load', function () { this.itemsView.onLoad.addListener(function () {
this.itemsView.rememberSelection(containerWindow.zoteroSavedItemSelection); this.itemsView.rememberSelection(containerWindow.zoteroSavedItemSelection);
delete containerWindow.zoteroSavedItemSelection; delete containerWindow.zoteroSavedItemSelection;
}.bind(this)); }.bind(this));
@ -987,8 +987,7 @@ var ZoteroPane = new function()
var cv = this.collectionsView; var cv = this.collectionsView;
var deferred = Zotero.Promise.defer(); var promise = cv.waitForSelect();
cv.addEventListener('select', () => deferred.resolve());
var selectedRow = cv.selection.currentIndex; var selectedRow = cv.selection.currentIndex;
yield cv.refresh(); yield cv.refresh();
@ -1004,7 +1003,7 @@ var ZoteroPane = new function()
this.collectionsView.selection.selectEventsSuppressed = false; this.collectionsView.selection.selectEventsSuppressed = false;
return deferred.promise; return promise;
}); });
@ -1199,11 +1198,10 @@ var ZoteroPane = new function()
// Wait for existing items view to finish loading before unloading it // Wait for existing items view to finish loading before unloading it
// //
// TODO: Cancel loading // TODO: Cancel loading
let deferred = Zotero.Promise.defer(); let promise = this.itemsView.waitForLoad();
this.itemsView.addEventListener('load', () => deferred.resolve()); if (promise.isPending()) {
if (deferred.promise.isPending()) {
Zotero.debug("Waiting for items view " + this.itemsView.id + " to finish loading"); Zotero.debug("Waiting for items view " + this.itemsView.id + " to finish loading");
yield deferred.promise; yield promise;
} }
this.itemsView.unregister(); this.itemsView.unregister();
@ -1240,7 +1238,7 @@ var ZoteroPane = new function()
Zotero.Prefs.clear('lastViewedFolder'); Zotero.Prefs.clear('lastViewedFolder');
ZoteroPane_Local.displayErrorMessage(); ZoteroPane_Local.displayErrorMessage();
}; };
this.itemsView.addEventListener('load', () => this.setTagScope()); this.itemsView.onLoad.addListener(() => this.setTagScope());
if (this.tagSelectorShown()) { if (this.tagSelectorShown()) {
let tagSelector = document.getElementById('zotero-tag-selector') let tagSelector = document.getElementById('zotero-tag-selector')
let handler = function () { let handler = function () {
@ -1250,7 +1248,7 @@ var ZoteroPane = new function()
tagSelector.addEventListener('refresh', handler); tagSelector.addEventListener('refresh', handler);
} }
else { else {
this.itemsView.addEventListener('load', () => Zotero.uiIsReady()); this.itemsView.onLoad.addListener(() => Zotero.uiIsReady());
} }
// If item data not yet loaded for library, load it now. // If item data not yet loaded for library, load it now.
@ -1320,7 +1318,7 @@ var ZoteroPane = new function()
Zotero.Prefs.set('lastViewedFolder', collectionTreeRow.id); Zotero.Prefs.set('lastViewedFolder', collectionTreeRow.id);
}, this) }, this)
.finally(function () { .finally(function () {
return this.collectionsView.onSelect(); return this.collectionsView.runListeners('select');
}.bind(this)); }.bind(this));
}; };
@ -1387,12 +1385,9 @@ var ZoteroPane = new function()
// Don't select item until items list has loaded // Don't select item until items list has loaded
// //
// This avoids an error if New Item is used while the pane is first loading. // This avoids an error if New Item is used while the pane is first loading.
var deferred = Zotero.Promise.defer(); var promise = this.itemsView.waitForLoad();
this.itemsView.addEventListener('load', function () { if (promise.isPending()) {
deferred.resolve(); yield promise;
});
if (deferred.promise.isPending()) {
yield deferred.promise;
} }
if (!this.itemsView || !this.itemsView.selection) { if (!this.itemsView || !this.itemsView.selection) {
@ -1598,7 +1593,7 @@ var ZoteroPane = new function()
return true; return true;
}.bind(this))() }.bind(this))()
.finally(function () { .finally(function () {
return this.itemsView.onSelect(); return this.itemsView.runListeners('select');
}.bind(this)); }.bind(this));
} }
@ -2462,9 +2457,7 @@ var ZoteroPane = new function()
// some menu items (e.g., export/createBib/loadReport) to appear gray in the menu at first and // some menu items (e.g., export/createBib/loadReport) to appear gray in the menu at first and
// then turn black once there are items. Pass a flag to prevent an accidental infinite loop. // then turn black once there are items. Pass a flag to prevent an accidental infinite loop.
if (!collectionTreeRow.isHeader() && !this.itemsView.initialized && !noRepeat) { if (!collectionTreeRow.isHeader() && !this.itemsView.initialized && !noRepeat) {
this.itemsView.addEventListener('load', function () { this.itemsView.onLoad.addListener(() => this.buildCollectionContextMenu(true));
this.buildCollectionContextMenu(true);
}.bind(this));
} }
// Set attributes on the menu from the configuration object // Set attributes on the menu from the configuration object

View file

@ -190,15 +190,11 @@ var waitForItemsLoad = Zotero.Promise.coroutine(function* (win, collectionRowToS
var zp = win.ZoteroPane; var zp = win.ZoteroPane;
var cv = zp.collectionsView; var cv = zp.collectionsView;
var deferred = Zotero.Promise.defer(); yield cv.waitForLoad();
cv.addEventListener('load', () => deferred.resolve());
yield deferred.promise;
if (collectionRowToSelect !== undefined) { if (collectionRowToSelect !== undefined) {
yield cv.selectWait(collectionRowToSelect); yield cv.selectWait(collectionRowToSelect);
} }
deferred = Zotero.Promise.defer(); yield zp.itemsView.waitForLoad();
zp.itemsView.addEventListener('load', () => deferred.resolve());
return deferred.promise;
}); });
var waitForTagSelector = function (win) { var waitForTagSelector = function (win) {

View file

@ -35,8 +35,7 @@ describe("Advanced Search", function () {
var deferred = Zotero.Promise.defer(); var deferred = Zotero.Promise.defer();
o.search(); o.search();
var iv = o.itemsView; var iv = o.itemsView;
iv.addEventListener('load', () => deferred.resolve()); yield iv.waitForLoad();
yield deferred.promise;
// Check results // Check results
assert.equal(iv.rowCount, 1); assert.equal(iv.rowCount, 1);

View file

@ -566,8 +566,7 @@ describe("Zotero.ItemTreeView", function() {
let view = zp.itemsView; let view = zp.itemsView;
yield view.selectItem(item3.id, true); yield view.selectItem(item3.id, true);
var deferred = Zotero.Promise.defer(); var promise = view.waitForSelect();
view.addEventListener('select', () => deferred.resolve());
view.drop(view.getRowIndexByID(item2.id), 0, { view.drop(view.getRowIndexByID(item2.id), 0, {
dropEffect: 'copy', dropEffect: 'copy',
@ -585,7 +584,7 @@ describe("Zotero.ItemTreeView", function() {
mozItemCount: 1 mozItemCount: 1
}) })
yield deferred.promise; yield promise;
// Old parent should be empty // Old parent should be empty
assert.isFalse(view.isContainerOpen(view.getRowIndexByID(item1.id))); assert.isFalse(view.isContainerOpen(view.getRowIndexByID(item1.id)));
@ -606,8 +605,7 @@ describe("Zotero.ItemTreeView", function() {
let view = zp.itemsView; let view = zp.itemsView;
yield view.selectItem(item3.id, true); yield view.selectItem(item3.id, true);
var deferred = Zotero.Promise.defer(); var promise = view.waitForSelect();
view.addEventListener('select', () => deferred.resolve());
view.drop(view.getRowIndexByID(item1.id), 0, { view.drop(view.getRowIndexByID(item1.id), 0, {
dropEffect: 'copy', dropEffect: 'copy',
@ -625,7 +623,7 @@ describe("Zotero.ItemTreeView", function() {
mozItemCount: 1 mozItemCount: 1
}) })
yield deferred.promise; yield promise;
// Old parent should be empty // Old parent should be empty
assert.isFalse(view.isContainerOpen(view.getRowIndexByID(item2.id))); assert.isFalse(view.isContainerOpen(view.getRowIndexByID(item2.id)));
@ -640,8 +638,7 @@ describe("Zotero.ItemTreeView", function() {
var file = getTestDataDirectory(); var file = getTestDataDirectory();
file.append('test.png'); file.append('test.png');
var deferred = Zotero.Promise.defer(); var promise = itemsView.waitForSelect();
itemsView.addEventListener('select', () => deferred.resolve());
itemsView.drop(0, -1, { itemsView.drop(0, -1, {
dropEffect: 'copy', dropEffect: 'copy',
@ -659,7 +656,7 @@ describe("Zotero.ItemTreeView", function() {
} }
}) })
yield deferred.promise; yield promise;
var items = itemsView.getSelectedItems(); var items = itemsView.getSelectedItems();
var path = yield items[0].getFilePathAsync(); var path = yield items[0].getFilePathAsync();
assert.equal( assert.equal(
@ -669,8 +666,7 @@ describe("Zotero.ItemTreeView", function() {
}); });
it("should create a top-level attachment when a URL is dragged", function* () { it("should create a top-level attachment when a URL is dragged", function* () {
var deferred = Zotero.Promise.defer(); var promise = itemsView.waitForSelect();
itemsView.addEventListener('select', () => deferred.resolve());
itemsView.drop(0, -1, { itemsView.drop(0, -1, {
dropEffect: 'copy', dropEffect: 'copy',
@ -688,7 +684,7 @@ describe("Zotero.ItemTreeView", function() {
mozItemCount: 1, mozItemCount: 1,
}) })
yield deferred.promise; yield promise;
var item = itemsView.getSelectedItems()[0]; var item = itemsView.getSelectedItems()[0];
assert.equal(item.getField('url'), pdfURL); assert.equal(item.getField('url'), pdfURL);
assert.equal( assert.equal(

View file

@ -35,9 +35,7 @@ describe("Related Box", function () {
yield Zotero.Promise.delay(50); yield Zotero.Promise.delay(50);
} }
while (!view); while (!view);
var deferred = Zotero.Promise.defer(); yield view.waitForLoad();
view.addEventListener('load', () => deferred.resolve());
yield deferred.promise;
// Select the other item // Select the other item
for (let i = 0; i < view.rowCount; i++) { for (let i = 0; i < view.rowCount; i++) {