From f97d66b2ba2d6fc1082ed36fc5982382e6753a01 Mon Sep 17 00:00:00 2001 From: windingwind Date: Sat, 6 May 2023 00:07:40 +0800 Subject: [PATCH] add: annotation tag action --- src/hooks.ts | 7 ++++- src/modules/annotationTagAction.ts | 42 ++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 src/modules/annotationTagAction.ts diff --git a/src/hooks.ts b/src/hooks.ts index 22d6d4e..642d03a 100644 --- a/src/hooks.ts +++ b/src/hooks.ts @@ -41,6 +41,7 @@ import { createNoteFromTemplate, createWorkspaceNote, } from "./modules/createNote"; +import { annotationTagAction } from "./modules/annotationTagAction"; async function onStartup() { await Promise.all([ @@ -56,7 +57,7 @@ async function onStartup() { registerNoteLinkProxyHandler(); - registerNotify(["tab", "item"]); + registerNotify(["tab", "item", "item-tag"]); registerEditorInstanceHook(); @@ -126,6 +127,10 @@ function onNotify( if (annotationItems.length !== 0) { checkReaderAnnotationButton(annotationItems); } + } + // Insert annotation when assigning tag starts with @ + if (event === "add" && type === "item-tag") { + annotationTagAction(ids as number[], extraData); } else { return; } diff --git a/src/modules/annotationTagAction.ts b/src/modules/annotationTagAction.ts new file mode 100644 index 0000000..f50f6b7 --- /dev/null +++ b/src/modules/annotationTagAction.ts @@ -0,0 +1,42 @@ +import { addLineToNote, getNoteTreeFlattened } from "../utils/note"; + +export { annotationTagAction }; + +async function annotationTagAction( + ids: Array, + extraData: Record +) { + const workspaceNote = Zotero.Items.get(addon.data.workspace.mainId); + if (!workspaceNote || !workspaceNote.isNote()) { + return; + } + const nodes = getNoteTreeFlattened(workspaceNote); + const headings: string[] = nodes.map((node) => node.model.name); + + for (const tagId of ids.filter((t) => + (extraData[t].tag as string).startsWith("@") + )) { + const tagName = (extraData[tagId].tag as string).slice(1).trim(); + if (headings.includes(tagName) || tagName === "@") { + let lineIndex: number; + if (tagName === "@") { + lineIndex = -1; + } else { + const targetNode = nodes.find((node) => node.model.name === tagName); + lineIndex = targetNode?.model.endIndex; + } + + const annotationItem = Zotero.Items.get((tagId as string).split("-")[0]); + if (!annotationItem.isAnnotation()) { + continue; + } + await addLineToNote( + workspaceNote, + await addon.api.convert.annotations2html([annotationItem], { + noteItem: workspaceNote, + }), + lineIndex + ); + } + } +}