From 5b81bb3d60619125b72f60b0035dd85df7cda4e7 Mon Sep 17 00:00:00 2001 From: Bogdan Abaev Date: Thu, 3 Sep 2026 16:12:27 -0700 Subject: [PATCH] citation dlg: turn annotation bubble into citation When switching the dialog type from "Add Annotation" to "Add/Edit Citation", keep the selected annotations instead of discarding them. Each annotation becomes a bubble for its top-level item, with the annotation's page as a page locator. This lets one use annotations as landmarks for what page to cite without opening the item in the reader. Annotations are groupped by top level item + page pairs. Two annotations from the same page become a single citation bubble with that page. Two annotations from different pages become two different bubbles for each locator. Also, fix: - highlight in itemTree sometimes not getting cleared on model type switch - last used collection not persisting in "Add Annotations" mode --- chrome/content/zotero/elements/bubbleInput.js | 18 +++-- .../zotero/integration/citationDialog.js | 54 +++++++++++-- test/tests/citationDialogTest.js | 78 +++++++++++++++++++ 3 files changed, 138 insertions(+), 12 deletions(-) diff --git a/chrome/content/zotero/elements/bubbleInput.js b/chrome/content/zotero/elements/bubbleInput.js index 5cac125669..cf3b5b2227 100644 --- a/chrome/content/zotero/elements/bubbleInput.js +++ b/chrome/content/zotero/elements/bubbleInput.js @@ -142,12 +142,17 @@ * Return the focus to an input. Try to focus on the previously active input first. * Otherwise, focus the last non-empty input in the editor. * If all inputs are empty, focus the last one. + * @param {Boolean} [options.focusLast=false] - Forget the previously active input + * and focus the last input, e.g. after all bubbles were replaced */ - refocusInput() { - let input = this.getCurrentInput(); + refocusInput({ focusLast = false } = {}) { + let input; let allInputs = [...this._body.querySelectorAll('.input')]; - if (!input) { - input = allInputs.find(inp => inp.value.length); + if (focusLast) { + this._lastFocusedInput = null; + } + else { + input = this.getCurrentInput() || allInputs.find(inp => inp.value.length); } if (!input) { input = allInputs[allInputs.length - 1]; @@ -713,7 +718,10 @@ remainingInput.value = combinedValue; inputToDelete.remove(); // Ensure the width of the combined input is correct - remainingInput.style.width = Utils.getContentWidth(node) + 'px'; + remainingInput.style.width = Utils.getContentWidth(remainingInput) + 'px'; + // Check the combined input again, in case more inputs follow it + node = remainingInput; + continue; } node = node.nextElementSibling; } diff --git a/chrome/content/zotero/integration/citationDialog.js b/chrome/content/zotero/integration/citationDialog.js index 9972e3b36a..f2705a1cf8 100644 --- a/chrome/content/zotero/integration/citationDialog.js +++ b/chrome/content/zotero/integration/citationDialog.js @@ -214,9 +214,9 @@ function cleanupBeforeDialogClosing() { // Only library mode in annotations dialog if (!DIALOG_STATE.isAddingAnnotations()) { Zotero.Prefs.set("integration.citationDialogLastUsedMode", currentLayout.type); - if (currentLayout.type == "library") { - Zotero.Prefs.set("integration.citationDialogCollectionLastSelected", libraryLayout.collectionsView.selectedTreeRow.id); - } + } + if (currentLayout.type == "library") { + Zotero.Prefs.set("integration.citationDialogCollectionLastSelected", libraryLayout.collectionsView.selectedTreeRow.id); } libraryLayout.collectionsView.unregister(); libraryLayout.itemsView.unregister(); @@ -238,6 +238,7 @@ async function setDialogType(type) { if (DIALOG_STATE.loaded && io.disableDialogTypeSwitch) return; // If there is a running search, do nothing to avoid window resizing conflicts if (SearchHandler.searching) return; + let previousType = DIALOG_STATE.type; DIALOG_STATE.type = type; document.documentElement.setAttribute("dialog-type", DIALOG_STATE.type); @@ -293,6 +294,8 @@ async function setDialogType(type) { } if (DIALOG_STATE.loaded) { + // Prevent focus handler from interfering - input is explicitly refocused below + IOManager._noRefocusing = true; // Completely reset itemTree to have right dragAndDrop, regularOnly, multiselect behavior libraryLayout.itemsView.unregister(); _id("zotero-items-tree").replaceChildren(); @@ -300,11 +303,24 @@ async function setDialogType(type) { await libraryLayout._initItemTree(); libraryLayout._onCollectionSelection(); - // Rerun the search and update bubble-input + // When switching from annotations to citation dialog type, the annotations are carried over + // as their top-level items with page locators, so they can be rearranged + // or previewed like any other citation. + let bubbleItems = []; + if (previousType == "annotations" && DIALOG_STATE.isCitingItems()) { + bubbleItems = CitationDataManager.buildParentCitationBubbleItems(); + } + CitationDataManager.clearAll(); + await CitationDataManager.addItems({ bubbleItems }); + IOManager.updateBubbleInput(); + IOManager._noRefocusing = false; + _id("bubble-input").refocusInput({ focusLast: true }); + // The new itemTree highlighted rows of the previous citation when it was initialized + libraryLayout.refreshItemsView(); + + // Rerun the search SearchHandler.clearNonLibraryItemsCache(); currentLayout.search(SearchHandler.searchValue); - CitationDataManager.clearAll(); - IOManager.updateBubbleInput(); } } @@ -1020,11 +1036,11 @@ class LibraryLayout extends Layout { // Highlight/de-highlight selected rows async _refreshItemsViewHighlightedRows() { - let selectedIDs = CitationDataManager.getCitedLibraryItemIDs(); // Wait for the tree to fully load to avoid a logged error that the tree is undefined while (!this.itemsView.tree) { await Zotero.Promise.delay(10); } + let selectedIDs = CitationDataManager.getCitedLibraryItemIDs(); this.itemsView.setHighlightedRows([...selectedIDs]); } @@ -2289,6 +2305,30 @@ const CitationDataManager = { } }, + // Build bubble items for the top-level parent items of the annotations in the citation, + // cited at the annotation's page. Annotations whose attachment has no parent item are dropped, + // and annotations of the same item on the same page are merged into one bubble item. + buildParentCitationBubbleItems() { + let bubbleItems = []; + let addedKeys = new Set(); + for (let { item } of this.items) { + // For an annotation of a standalone attachment, the top-level item is the attachment itself + let topLevelItem = item.topLevelItem; + if (!topLevelItem.isRegularItem()) continue; + let locator = (item.annotationPageLabel || "").trim(); + let key = `${topLevelItem.id}|${locator}`; + if (addedKeys.has(key)) continue; + addedKeys.add(key); + let bubbleItem = BubbleItem.fromItem(topLevelItem); + if (locator) { + bubbleItem.locator = locator; + bubbleItem.label = "page"; + } + bubbleItems.push(bubbleItem); + } + return bubbleItems; + }, + // Resorts the items in the citation async sort() { if (DIALOG_STATE.isAddingAnnotations()) { diff --git a/test/tests/citationDialogTest.js b/test/tests/citationDialogTest.js index e7ae2f6f94..6a07b3a977 100644 --- a/test/tests/citationDialogTest.js +++ b/test/tests/citationDialogTest.js @@ -953,11 +953,13 @@ describe("Citation Dialog", function () { highlightAnnotation = await createAnnotation('highlight', attachment); highlightAnnotation.annotationText = 'highlighted text'; highlightAnnotation.annotationComment = 'highlight comment'; + highlightAnnotation.annotationPageLabel = '5'; await highlightAnnotation.saveTx(); underlineAnnotation = await createAnnotation('underline', attachment); underlineAnnotation.annotationText = 'underlined text'; underlineAnnotation.annotationComment = 'underline'; + underlineAnnotation.annotationPageLabel = '7'; await underlineAnnotation.saveTx(); }); @@ -995,6 +997,82 @@ describe("Citation Dialog", function () { assert.equal(bubbles[0].textContent, `Last_One “highlighted text”`); }); + it("should carry annotations over as cited parent items when switching to citation mode", async function () { + // Second annotation on the same page as the highlight, to be merged with it + let samePageAnnotation = await createAnnotation('highlight', attachment); + samePageAnnotation.annotationPageLabel = '5'; + await samePageAnnotation.saveTx(); + // Annotation of a standalone attachment has no item to cite + let standaloneAttachment = await importFileAttachment('test.pdf'); + let standaloneAnnotation = await createAnnotation('highlight', standaloneAttachment); + await standaloneAnnotation.saveTx(); + + let waitForSearch = async () => { + while (SearchHandler.searching) { + await Zotero.Promise.delay(10); + } + }; + try { + await IOManager.addItemsToCitation([highlightAnnotation, underlineAnnotation, samePageAnnotation, standaloneAnnotation]); + assert.equal(CitationDataManager.items.length, 4); + await dialog.setDialogType("citation"); + await waitForSearch(); + + // Annotations become their parent item with page locators + let citationItems = CitationDataManager.items + .map(bubbleItem => bubbleItem.getCitationItem()) + .sort((a, b) => a.locator - b.locator); + assert.deepEqual(citationItems, [ + { id: parentItem.id, locator: '5', label: 'page' }, + { id: parentItem.id, locator: '7', label: 'page' } + ]); + let bubbles = dialog.document.querySelector("bubble-input").getAllBubbles(); + assert.equal(bubbles.length, 2); + assert.isFalse(dialog.document.getElementById("accept-button").disabled); + // Focus is placed into the last input + let inputs = [...dialog.document.querySelectorAll("bubble-input .input")]; + assert.equal(dialog.document.activeElement, inputs[inputs.length - 1]); + // The parent item's row is highlighted in the rebuilt itemTree + while (dialog.currentLayout.itemsView.getRowIndexByID(parentItem.id) === false) { + await Zotero.Promise.delay(10); + } + assert.isTrue(dialog.currentLayout.itemsView._highlightedRows.has(parentItem.id)); + } + finally { + await samePageAnnotation.eraseTx(); + await standaloneAttachment.eraseTx(); + // Go back to the annotations dialog type and wait for the rebuilt itemTree to load + await dialog.setDialogType("annotations"); + await waitForSearch(); + while (dialog.currentLayout.itemsView.getRowIndexByID(parentItem.id) === false) { + await Zotero.Promise.delay(10); + } + } + }); + + it("should merge all neighboring inputs when bubbles are replaced", async function () { + await IOManager.addItemsToCitation([highlightAnnotation, underlineAnnotation]); + let bubbleInput = dialog.document.getElementById("bubble-input"); + let inputs = [...bubbleInput.querySelectorAll(".input")]; + assert.equal(inputs.length, 3); + inputs[0].value = "one"; + inputs[1].value = "two"; + inputs[2].value = "three"; + + // Replace all bubbles, which leaves the three inputs next to each other + CitationDataManager.items = CitationDataManager.buildParentCitationBubbleItems(); + IOManager.updateBubbleInput(); + + // There must be exactly one input between bubbles, with all values combined + let nodes = [...bubbleInput.querySelector(".body").children]; + assert.equal(nodes.filter(node => node.classList.contains("bubble")).length, 2); + assert.equal(nodes.filter(node => node.classList.contains("input")).length, 3); + for (let i = 1; i < nodes.length; i++) { + assert.notEqual(nodes[i].classList.contains("input"), nodes[i - 1].classList.contains("input")); + } + assert.equal(nodes[0].value, "one two three"); + }); + it("should select itemTree row on click of selected non-annotation item", async function () { // Pretend that highlight annotation is selected SearchHandler.results.selectedItems = [parentItem];