Add Zotero.Item::topLevelItem and Zotero.Items.getTopLevel(items)

This commit is contained in:
Dan Stillman 2022-08-25 05:15:25 -04:00 committed by Dan Stillman
parent 6646be66d0
commit ca4ced1e9f
3 changed files with 41 additions and 1 deletions

View file

@ -153,7 +153,16 @@ Zotero.defineProperty(Zotero.Item.prototype, 'parentItemKey', {
Zotero.defineProperty(Zotero.Item.prototype, 'parentItem', {
get: function() { return Zotero.Items.get(this.parentID) || undefined; },
});
Zotero.defineProperty(Zotero.Item.prototype, 'topLevelItem', {
get: function () {
var item = this; // eslint-disable-line consistent-this
var parentItem;
while ((parentItem = item.parentItem)) {
item = parentItem;
}
return item;
}
});
Zotero.defineProperty(Zotero.Item.prototype, 'firstCreator', {
get: function() { return this._firstCreator; }

View file

@ -1735,6 +1735,17 @@ Zotero.Items = function() {
};
/**
* Get the top-level items of all passed items
*
* @param {Zotero.Item[]} items
* @return {Zotero.Item[]}
*/
this.getTopLevel = function (items) {
return [...new Set(items.map(item => item.topLevelItem))];
};
/**
* Returns an array of items with children of selected parents removed
*

View file

@ -483,6 +483,26 @@ describe("Zotero.Item", function () {
});
});
describe("#topLevelItem", function () {
it("should return self for top-level item", async function () {
var item = await createDataObject('item');
assert.equal(item, item.topLevelItem);
});
it("should return parent item for note", async function () {
var item = await createDataObject('item');
var note = await createDataObject('item', { itemType: 'note', parentItemID: item.id });
assert.equal(item, note.topLevelItem);
});
it("should return top-level item for annotation", async function () {
var item = await createDataObject('item');
var attachment = await importPDFAttachment(item);
var annotation = await createAnnotation('highlight', attachment);
assert.equal(item, annotation.topLevelItem);
});
});
describe("#getCreators()", function () {
it("should update after creators are removed", function* () {
var item = createUnsavedDataObject('item');