Skip to content

Commit

Permalink
fix: adjust timing for auto-updating paper info
Browse files Browse the repository at this point in the history
  • Loading branch information
TimeTrapzz committed Nov 10, 2024
1 parent 7e64626 commit c2c0004
Show file tree
Hide file tree
Showing 2 changed files with 96 additions and 38 deletions.
37 changes: 33 additions & 4 deletions src/hooks.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { UIExampleFactory } from "./modules/examples";
import { ExampleFactory } from "./modules/examples";
import { config } from "../package.json";
import { getString, initLocale } from "./utils/locale";
import { createZToolkit } from "./utils/ztoolkit";
Expand All @@ -15,9 +15,9 @@ async function onStartup() {
await onMainWindowLoad(window);

// Register all UI components and listeners
UIExampleFactory.registerRightClickMenuItem();
UIExampleFactory.registerExtraColumn();
UIExampleFactory.registerNotifier();
ExampleFactory.registerRightClickMenuItem();
ExampleFactory.registerExtraColumn();
ExampleFactory.registerNotifier();
}

async function onMainWindowLoad(win: Window): Promise<void> {
Expand All @@ -30,6 +30,34 @@ async function onMainWindowUnload(win: Window): Promise<void> {
addon.data.dialog?.window?.close();
}

async function onNotify(
event: string,
type: string,
ids: Array<string | number>,
extraData: { [key: string]: any },
) {
ztoolkit.log("notify", event, type, ids, extraData);

if (event == "add" && type == "item") {
// Get items and filter out attachments and other non-regular items
const items = Zotero.Items.get(ids as number[]);
const regularItems = items.filter(
(item) =>
item.isRegularItem() &&
!item.isAttachment() &&
// @ts-ignore item has no isFeedItem
!item.isFeedItem &&
// @ts-ignore libraryID is got from item, so get() will never return false
Zotero.Libraries.get(item.libraryID)._libraryType == "user",
);

if (regularItems.length !== 0) {
ExampleFactory.exampleNotifierCallback(regularItems);
return;
}
}
}

function onShutdown(): void {
ztoolkit.unregisterAll();
addon.data.dialog?.window?.close();
Expand All @@ -45,6 +73,7 @@ function onShutdown(): void {
export default {
onStartup,
onShutdown,
onNotify,
onMainWindowLoad,
onMainWindowUnload,
};
97 changes: 63 additions & 34 deletions src/modules/examples.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@ import { getLocaleID, getString } from "../utils/locale";
import { PaperInfo } from "./getPaperInfo";



export class UIExampleFactory {
export class ExampleFactory {
static async registerExtraColumn() {
await Zotero.ItemTreeManager.registerColumns([
{
Expand Down Expand Up @@ -38,17 +37,26 @@ export class UIExampleFactory {

public static async handleGetCCFInfo(items: Zotero.Item[]) {
if (!items || items.length === 0) return;

ztoolkit.log("handleGetCCFInfo", items);
if (items.length === 1) {
await UIExampleFactory.handleSingleItem(items[0]);
await ExampleFactory.handleSingleItem(items[0]);
} else {
await UIExampleFactory.handleMultipleItems(items);
await ExampleFactory.handleMultipleItems(items);
}
}

private static async handleSingleItem(entry: Zotero.Item) {
// Clear existing tags
UIExampleFactory.clearCCFTags(entry);
ExampleFactory.clearCCFTags(entry);
const progressWindow = new ztoolkit.ProgressWindow(getString("paper-info-update"), {
closeOtherProgressWindows: true
});
const progressLine = new progressWindow.ItemProgress(
"default",
getString("requesting-citation-single")
);
progressWindow.show();
progressWindow.startCloseTimer(2000);

// Get new CCF rank and citation number
PaperInfo.getPaperCCFRank(
Expand All @@ -57,14 +65,24 @@ export class UIExampleFactory {
(item, data) => {
entry.addTag(`ccfInfo: ${data.ccfInfo}`);
entry.saveTx();
UIExampleFactory.updateCitationNumber(entry, 1);
ExampleFactory.updateCitationNumber(entry, 1);
},
);
}

private static async handleMultipleItems(items: Zotero.Item[]) {
// Clear existing tags for all items
items.forEach(entry => UIExampleFactory.clearCCFTags(entry));
items.forEach(entry => ExampleFactory.clearCCFTags(entry));

const progressWindow = new ztoolkit.ProgressWindow(getString("paper-info-update"), {
closeOtherProgressWindows: true
});
const progressLine = new progressWindow.ItemProgress(
"default",
getString("requesting-citations-multiple", { args: { count: items.length } })
);
progressWindow.show();
progressWindow.startCloseTimer(2000);

const titles = items.map(item => item.getField("title"));
PaperInfo.batchGetPaperCCFRank(
Expand All @@ -75,13 +93,13 @@ export class UIExampleFactory {
items.forEach((entry: Zotero.Item, index: number) => {
entry.addTag(`ccfInfo: ${data[index].ccfInfo}`);
entry.saveTx();
UIExampleFactory.updateCitationNumber(entry, index, items.length);
ExampleFactory.updateCitationNumber(entry, index, items.length);
});
} else {
items.forEach((entry: Zotero.Item, index: number) => {
entry.addTag(`ccfInfo: ${data.ccfInfo}`);
entry.saveTx();
UIExampleFactory.updateCitationNumber(entry, items.length, index);
ExampleFactory.updateCitationNumber(entry, items.length, index);
});
}
},
Expand All @@ -98,25 +116,12 @@ export class UIExampleFactory {
}

private static async updateCitationNumber(entry: Zotero.Item, index?: number, total?: number) {
// Create progress window for every request
const progressWindow = new ztoolkit.ProgressWindow(getString("paper-info-update"), {
closeOtherProgressWindows: true
});
const progressLine = new progressWindow.ItemProgress(
"default",
total ?
getString("requesting-citations-multiple", { args: { count: total } }) :
getString("requesting-citation-single")
);
progressWindow.show();

PaperInfo.getPaperCitationNumber(
entry,
entry.getField("title"),
(item, data) => {
entry.addTag(`citationNumber: ${data.citationNumber}`);
entry.saveTx();
progressWindow.startCloseTimer(2000);
},
);
}
Expand All @@ -129,23 +134,47 @@ export class UIExampleFactory {
label: getString("get-ccf-info"),
commandListener: (ev) => {
const items = ZoteroPane.getSelectedItems();
UIExampleFactory.handleGetCCFInfo(items);
ExampleFactory.handleGetCCFInfo(items);
},
icon: menuIcon,
});
}

static registerNotifier() {
Zotero.Notifier.registerObserver({
notify: async (event: string, type: string, ids: (string | number)[], extraData: object) => {
if (event === 'add' && type === 'item') {
const items = ids.map(id => Zotero.Items.get(Number(id)))
.filter(item => item.isRegularItem());
if (items.length > 0) {
await UIExampleFactory.handleGetCCFInfo(items);
}
const callback = {
notify: async (
event: string,
type: string,
ids: Array<string | number>,
extraData: { [key: string]: any },
) => {
if (!addon?.data.alive) {
this.unregisterNotifier(notifierID);
return;
}
}
}, ['item']);
addon.hooks.onNotify(event, type, ids, extraData);
},
};

const notifierID = Zotero.Notifier.registerObserver(callback, ["item"]);

// Unregister callback when the window closes (important to avoid a memory leak)
window.addEventListener(
"unload",
(e: Event) => {
this.unregisterNotifier(notifierID);
},
false,
);
}

static async exampleNotifierCallback(regularItems: any) {
// 等待 10s 以防止 Zotero 未完成条目添加
await new Promise(resolve => setTimeout(resolve, 10000));
await ExampleFactory.handleGetCCFInfo(regularItems);
}

private static unregisterNotifier(notifierID: string) {
Zotero.Notifier.unregisterObserver(notifierID);
}
}

0 comments on commit c2c0004

Please sign in to comment.