├── .gitattributes ├── default.jpg ├── .prettierignore ├── .gitignore ├── addon ├── chrome │ └── content │ │ ├── icons │ │ ├── favicon.png │ │ └── favicon@0.5x.png │ │ ├── preferences.xhtml │ │ └── zoteroPane.css ├── prefs.js ├── locale │ ├── zh-CN │ │ ├── preferences.ftl │ │ ├── addon.ftl │ │ └── mainWindow.ftl │ └── en-US │ │ ├── preferences.ftl │ │ ├── addon.ftl │ │ └── mainWindow.ftl ├── manifest.json └── bootstrap.js ├── .vscode ├── extensions.json ├── settings.json ├── launch.json └── toolkit.code-snippets ├── src ├── utils │ ├── window.ts │ ├── prefs.ts │ ├── wait.ts │ ├── ztoolkit.ts │ └── locale.ts ├── index.ts ├── addon.ts ├── modules │ ├── preferenceScript.ts │ └── main.ts └── hooks.ts ├── tsconfig.json ├── typings └── global.d.ts ├── .github ├── dependabot.yml ├── renovate.json └── workflows │ └── release.yml ├── zotero-plugin.config.ts ├── .env.example ├── eslint.config.mjs ├── package.json ├── README.md ├── doc └── README-zhCN.md └── LICENSE /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto eol=lf -------------------------------------------------------------------------------- /default.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kazgu/zotero-chatgpt/HEAD/default.jpg -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | .vscode 2 | build 3 | logs 4 | node_modules 5 | package-lock.json 6 | yarn.lock 7 | pnpm-lock.yaml 8 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | build 2 | logs 3 | node_modules 4 | pnpm-lock.yaml 5 | yarn.lock 6 | .DS_Store 7 | .env 8 | .vscode 9 | .github -------------------------------------------------------------------------------- /addon/chrome/content/icons/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kazgu/zotero-chatgpt/HEAD/addon/chrome/content/icons/favicon.png -------------------------------------------------------------------------------- /addon/chrome/content/icons/favicon@0.5x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kazgu/zotero-chatgpt/HEAD/addon/chrome/content/icons/favicon@0.5x.png -------------------------------------------------------------------------------- /addon/prefs.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable no-undef */ 2 | // pref("__prefsPrefix__.enable", true); 3 | pref("__prefsPrefix__.base", "https://api.openai.com/v1"); 4 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": [ 3 | "dbaeumer.vscode-eslint", 4 | "esbenp.prettier-vscode", 5 | "macabeus.vscode-fluent" 6 | ] 7 | } 8 | -------------------------------------------------------------------------------- /addon/locale/zh-CN/preferences.ftl: -------------------------------------------------------------------------------- 1 | pref-title = 设置 2 | pref-input = API_Key 3 | pref-base = BaseUrl 4 | pref-model = Model 5 | pref-help = { $name } Build { $version } { $time } -------------------------------------------------------------------------------- /addon/locale/en-US/preferences.ftl: -------------------------------------------------------------------------------- 1 | pref-title = Settings 2 | pref-input = API_Key 3 | pref-base = BaseUrl 4 | pref-model = Model 5 | pref-help = { $name } Build { $version } { $time } -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.formatOnType": false, 3 | "editor.formatOnSave": true, 4 | "editor.codeActionsOnSave": { 5 | "source.fixAll.eslint": "explicit" 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /src/utils/window.ts: -------------------------------------------------------------------------------- 1 | export { isWindowAlive }; 2 | 3 | /** 4 | * Check if the window is alive. 5 | * Useful to prevent opening duplicate windows. 6 | * @param win 7 | */ 8 | function isWindowAlive(win?: Window) { 9 | return win && !Components.utils.isDeadWrapper(win) && !win.closed; 10 | } 11 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "experimentalDecorators": true, 4 | "module": "commonjs", 5 | "target": "ES2016", 6 | "resolveJsonModule": true, 7 | "skipLibCheck": true, 8 | "strict": true 9 | }, 10 | "include": ["src", "typings", "node_modules/zotero-types"], 11 | "exclude": ["build", "addon"] 12 | } 13 | -------------------------------------------------------------------------------- /addon/locale/zh-CN/addon.ftl: -------------------------------------------------------------------------------- 1 | startup-begin = 插件加载中 2 | startup-finish = 插件已就绪 3 | menuitem-label = 插件模板: 帮助工具样例 4 | menupopup-label = 插件模板: 弹出菜单 5 | menuitem-submenulabel = 插件模板:子菜单 6 | menuitem-filemenulabel = 插件模板: 文件菜单 7 | prefs-title = ChatGPT 8 | prefs-table-title = 标题 9 | prefs-table-detail = 详情 10 | tabpanel-lib-tab-label = 库标签 11 | tabpanel-reader-tab-label = 阅读器标签 -------------------------------------------------------------------------------- /addon/locale/en-US/addon.ftl: -------------------------------------------------------------------------------- 1 | startup-begin = Addon is loading 2 | startup-finish = Addon is ready 3 | menuitem-label = Papers 4 | menupopup-label = Addon Template: Menupopup 5 | menuitem-submenulabel = Addon Template 6 | menuitem-filemenulabel = Addon Template: File Menuitem 7 | prefs-title = ChatGPT 8 | prefs-table-title = Title 9 | prefs-table-detail = Detail 10 | tabpanel-lib-tab-label = Lib Tab 11 | tabpanel-reader-tab-label = Reader Tab -------------------------------------------------------------------------------- /typings/global.d.ts: -------------------------------------------------------------------------------- 1 | declare const _globalThis: { 2 | [key: string]: any; 3 | Zotero: _ZoteroTypes.Zotero; 4 | ztoolkit: ZToolkit; 5 | addon: typeof addon; 6 | }; 7 | 8 | declare type ZToolkit = ReturnType< 9 | typeof import("../src/utils/ztoolkit").createZToolkit 10 | >; 11 | 12 | declare const ztoolkit: ZToolkit; 13 | 14 | declare const rootURI: string; 15 | 16 | declare const addon: import("../src/addon").default; 17 | 18 | declare const __env__: "production" | "development"; 19 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # To get started with Dependabot version updates, you'll need to specify which 2 | # package ecosystems to update and where the package manifests are located. 3 | # Please see the documentation for all configuration options: 4 | # https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates 5 | 6 | version: 2 7 | updates: 8 | - package-ecosystem: "npm" # See documentation for possible values 9 | directory: "/" # Location of package manifests 10 | schedule: 11 | interval: "weekly" 12 | -------------------------------------------------------------------------------- /addon/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "manifest_version": 2, 3 | "name": "__addonName__", 4 | "version": "__buildVersion__", 5 | "description": "__description__", 6 | "homepage_url": "__homepage__", 7 | "author": "__author__", 8 | "icons": { 9 | "48": "chrome/content/icons/favicon@0.5x.png", 10 | "96": "chrome/content/icons/favicon.png" 11 | }, 12 | "applications": { 13 | "zotero": { 14 | "id": "__addonID__", 15 | "update_url": "__updateURL__", 16 | "strict_min_version": "6.999", 17 | "strict_max_version": "7.0.*" 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // 使用 IntelliSense 了解相关属性。 3 | // 悬停以查看现有属性的描述。 4 | // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "type": "node", 9 | "request": "launch", 10 | "name": "Start", 11 | "runtimeExecutable": "npm", 12 | "runtimeArgs": ["run", "start"] 13 | }, 14 | { 15 | "type": "node", 16 | "request": "launch", 17 | "name": "Build", 18 | "runtimeExecutable": "npm", 19 | "runtimeArgs": ["run", "build"] 20 | } 21 | ] 22 | } 23 | -------------------------------------------------------------------------------- /.github/renovate.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://docs.renovatebot.com/renovate-schema.json", 3 | "extends": [ 4 | "config:recommended", 5 | ":semanticPrefixChore", 6 | ":prHourlyLimitNone", 7 | ":prConcurrentLimitNone", 8 | ":enableVulnerabilityAlerts", 9 | ":dependencyDashboard", 10 | "group:allNonMajor", 11 | "schedule:weekly" 12 | ], 13 | "labels": ["dependencies"], 14 | "packageRules": [ 15 | { 16 | "matchPackageNames": [ 17 | "zotero-plugin-toolkit", 18 | "zotero-types", 19 | "zotero-plugin-scaffold" 20 | ], 21 | "schedule": ["at any time"], 22 | "automerge": true 23 | } 24 | ], 25 | "git-submodules": { 26 | "enabled": true 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { BasicTool } from "zotero-plugin-toolkit"; 2 | import Addon from "./addon"; 3 | import { config } from "../package.json"; 4 | 5 | const basicTool = new BasicTool(); 6 | 7 | if (!basicTool.getGlobal("Zotero")[config.addonInstance]) { 8 | _globalThis.addon = new Addon(); 9 | defineGlobal("ztoolkit", () => { 10 | return _globalThis.addon.data.ztoolkit; 11 | }); 12 | Zotero[config.addonInstance] = addon; 13 | } 14 | 15 | function defineGlobal(name: Parameters[0]): void; 16 | function defineGlobal(name: string, getter: () => any): void; 17 | function defineGlobal(name: string, getter?: () => any) { 18 | Object.defineProperty(_globalThis, name, { 19 | get() { 20 | return getter ? getter() : basicTool.getGlobal(name); 21 | }, 22 | }); 23 | } 24 | -------------------------------------------------------------------------------- /src/utils/prefs.ts: -------------------------------------------------------------------------------- 1 | import { config } from "../../package.json"; 2 | 3 | /** 4 | * Get preference value. 5 | * Wrapper of `Zotero.Prefs.get`. 6 | * @param key 7 | */ 8 | export function getPref(key: string) { 9 | return Zotero.Prefs.get(`${config.prefsPrefix}.${key}`, true); 10 | } 11 | 12 | /** 13 | * Set preference value. 14 | * Wrapper of `Zotero.Prefs.set`. 15 | * @param key 16 | * @param value 17 | */ 18 | export function setPref(key: string, value: string | number | boolean) { 19 | return Zotero.Prefs.set(`${config.prefsPrefix}.${key}`, value, true); 20 | } 21 | 22 | /** 23 | * Clear preference value. 24 | * Wrapper of `Zotero.Prefs.clear`. 25 | * @param key 26 | */ 27 | export function clearPref(key: string) { 28 | return Zotero.Prefs.clear(`${config.prefsPrefix}.${key}`, true); 29 | } 30 | -------------------------------------------------------------------------------- /addon/locale/zh-CN/mainWindow.ftl: -------------------------------------------------------------------------------- 1 | item-section-example1-head-text = 2 | .label = ChatGPT 3 | item-section-example1-sidenav-tooltip = 4 | .tooltiptext = ChatGPT 5 | item-section-example2-head-text = 6 | .label = ChatGPT 对话助手 7 | item-section-example2-sidenav-tooltip = 8 | .tooltiptext = ChatGPT 对话助手 9 | item-section-example2-button-tooltip = 10 | .tooltiptext = ChatGPT 对话助手 11 | 12 | chat-attach-pdf-label = 附加 PDF 内容 13 | chat-attach-pdf-attached = 已附加 14 | chat-attach-pdf-no-pdf = 当前项目无 PDF 15 | chat-input-placeholder = 输入您的消息... 16 | chat-send-button = 发送 17 | chat-send-button-tooltip = 发送消息 (Enter) 18 | chat-error-no-api-key = API key 或 base URL 未设置,请在设置中配置 19 | chat-error-no-pdf = 未找到 PDF 附件 20 | chat-error-network = 网络错误,请检查连接 21 | chat-error-api = API 调用失败 22 | chat-typing = 正在输入... 23 | chat-empty-state = 开始与 ChatGPT 对话 24 | -------------------------------------------------------------------------------- /addon/locale/en-US/mainWindow.ftl: -------------------------------------------------------------------------------- 1 | item-section-example1-head-text = 2 | .label = ChatGPT 3 | item-section-example1-sidenav-tooltip = 4 | .tooltiptext = ChatGPT 5 | item-section-example2-head-text = 6 | .label = ChatGPT Assistant 7 | item-section-example2-sidenav-tooltip = 8 | .tooltiptext = ChatGPT Assistant 9 | item-section-example2-button-tooltip = 10 | .tooltiptext = ChatGPT Assistant 11 | 12 | chat-attach-pdf-label = Attach PDF Content 13 | chat-attach-pdf-attached = Attached 14 | chat-attach-pdf-no-pdf = No PDF in current item 15 | chat-input-placeholder = ... 16 | chat-send-button = Send 17 | chat-send-button-tooltip = Send(Enter) 18 | chat-error-no-api-key = API key or base URL not set, please configure in settings 19 | chat-error-no-pdf = No PDF attachment found 20 | chat-error-network = Network error, please check your connection 21 | chat-error-api = API call failed 22 | chat-typing = Typing... 23 | chat-empty-state = Start a conversation with ChatGPT 24 | -------------------------------------------------------------------------------- /src/addon.ts: -------------------------------------------------------------------------------- 1 | import { ColumnOptions } from "zotero-plugin-toolkit/dist/helpers/virtualizedTable"; 2 | import { DialogHelper } from "zotero-plugin-toolkit/dist/helpers/dialog"; 3 | import hooks from "./hooks"; 4 | import { createZToolkit } from "./utils/ztoolkit"; 5 | 6 | class Addon { 7 | public data: { 8 | alive: boolean; 9 | // Env type, see build.js 10 | env: "development" | "production"; 11 | ztoolkit: ZToolkit; 12 | locale?: { 13 | current: any; 14 | }; 15 | prefs?: { 16 | window: Window; 17 | columns: Array; 18 | rows: Array<{ [dataKey: string]: string }>; 19 | }; 20 | dialog?: DialogHelper; 21 | }; 22 | // Lifecycle hooks 23 | public hooks: typeof hooks; 24 | // APIs 25 | public api: object; 26 | 27 | constructor() { 28 | this.data = { 29 | alive: true, 30 | env: __env__, 31 | ztoolkit: createZToolkit(), 32 | }; 33 | this.hooks = hooks; 34 | this.api = {}; 35 | } 36 | } 37 | 38 | export default Addon; 39 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: 4 | push: 5 | tags: 6 | - v** 7 | 8 | permissions: 9 | contents: write 10 | issues: write 11 | pull-requests: write 12 | 13 | jobs: 14 | release: 15 | runs-on: ubuntu-latest 16 | env: 17 | GITHUB_TOKEN: ${{ secrets.GitHub_TOKEN }} 18 | steps: 19 | - name: Checkout 20 | uses: actions/checkout@v4 21 | with: 22 | fetch-depth: 0 23 | 24 | - name: Setup Node.js 25 | uses: actions/setup-node@v4 26 | with: 27 | node-version: 20 28 | 29 | - name: Install deps 30 | run: npm install -f 31 | 32 | - name: Build 33 | run: | 34 | npm run build 35 | 36 | - name: Release to GitHub 37 | run: | 38 | npm run release 39 | sleep 1s 40 | 41 | - name: Notify release 42 | uses: apexskier/github-release-commenter@v1 43 | continue-on-error: true 44 | with: 45 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 46 | comment-template: | 47 | :rocket: _This ticket has been resolved in {release_tag}. See {release_link} for release notes._ 48 | -------------------------------------------------------------------------------- /addon/chrome/content/preferences.xhtml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 24 | 25 | -------------------------------------------------------------------------------- /zotero-plugin.config.ts: -------------------------------------------------------------------------------- 1 | import { defineConfig } from "zotero-plugin-scaffold"; 2 | import pkg from "./package.json"; 3 | 4 | export default defineConfig({ 5 | source: ["src", "addon"], 6 | dist: "build", 7 | name: pkg.config.addonName, 8 | id: pkg.config.addonID, 9 | namespace: pkg.config.addonRef, 10 | updateURL: `https://github.com/{{owner}}/{{repo}}/releases/download/release/${ 11 | pkg.version.includes("-") ? "update-beta.json" : "update.json" 12 | }`, 13 | xpiDownloadLink: 14 | "https://github.com/{{owner}}/{{repo}}/releases/download/v{{version}}/{{xpiName}}.xpi", 15 | 16 | build: { 17 | assets: ["addon/**/*.*"], 18 | define: { 19 | ...pkg.config, 20 | author: pkg.author, 21 | description: pkg.description, 22 | homepage: pkg.homepage, 23 | buildVersion: pkg.version, 24 | buildTime: "{{buildTime}}", 25 | }, 26 | esbuildOptions: [ 27 | { 28 | entryPoints: ["src/index.ts"], 29 | define: { 30 | __env__: `"${process.env.NODE_ENV}"`, 31 | }, 32 | bundle: true, 33 | target: "firefox115", 34 | outfile: `build/addon/chrome/content/scripts/${pkg.config.addonRef}.js`, 35 | }, 36 | ], 37 | }, 38 | 39 | // If you need to see a more detailed log, uncomment the following line: 40 | // logLevel: "trace", 41 | }); 42 | -------------------------------------------------------------------------------- /.env.example: -------------------------------------------------------------------------------- 1 | # Usage: 2 | # Copy this file as `.env` and fill in the variables below as instructed. 3 | 4 | # If you are developing more than one plugin, you can store the bin path and 5 | # profile path in the system environment variables, which can be omitted here. 6 | 7 | # The path of the Zotero binary file. 8 | # The path delimiter should be escaped as `\\` for win32. 9 | # The path is `*/Zotero.app/Contents/MacOS/zotero` for MacOS. 10 | ZOTERO_PLUGIN_ZOTERO_BIN_PATH = /path/to/zotero.exe 11 | 12 | # The path of the profile used for development. 13 | # Start the profile manager by `/path/to/zotero.exe -p` to create a profile for development. 14 | # @see https://www.zotero.org/support/kb/profile_directory 15 | ZOTERO_PLUGIN_PROFILE_PATH = /path/to/profile 16 | 17 | # The directory where the database is located. 18 | # If this field is kept empty, Zotero will start with the default data. 19 | # @see https://www.zotero.org/support/zotero_data 20 | ZOTERO_PLUGIN_DATA_DIR = 21 | 22 | # Custom commands to kill Zotero processes. 23 | # Commands for different platforms are already built into zotero-plugin, 24 | # if the built-in commands are not suitable for your needs, please modify this variable. 25 | # ZOTERO_PLUGIN_KILL_COMMAND = 26 | 27 | # GitHub Token 28 | # For scaffold auto create release and upload assets. 29 | # Fill in this variable if you are publishing locally instead of CI. 30 | # GITHUB_TOKEN = -------------------------------------------------------------------------------- /eslint.config.mjs: -------------------------------------------------------------------------------- 1 | // @ts-check Let TS check this config file 2 | 3 | import eslint from "@eslint/js"; 4 | import tseslint from "typescript-eslint"; 5 | 6 | export default tseslint.config( 7 | { 8 | ignores: ["build/**", "dist/**", "node_modules/**", "scripts/"], 9 | }, 10 | { 11 | extends: [eslint.configs.recommended, ...tseslint.configs.recommended], 12 | rules: { 13 | "no-restricted-globals": [ 14 | "error", 15 | { message: "Use `Zotero.getMainWindow()` instead.", name: "window" }, 16 | { 17 | message: "Use `Zotero.getMainWindow().document` instead.", 18 | name: "document", 19 | }, 20 | { 21 | message: "Use `Zotero.getActiveZoteroPane()` instead.", 22 | name: "ZoteroPane", 23 | }, 24 | "Zotero_Tabs", 25 | ], 26 | 27 | "@typescript-eslint/ban-ts-comment": [ 28 | "warn", 29 | { 30 | "ts-expect-error": "allow-with-description", 31 | "ts-ignore": "allow-with-description", 32 | "ts-nocheck": "allow-with-description", 33 | "ts-check": "allow-with-description", 34 | }, 35 | ], 36 | "@typescript-eslint/no-unused-vars": "off", 37 | "@typescript-eslint/no-explicit-any": [ 38 | "off", 39 | { 40 | ignoreRestArgs: true, 41 | }, 42 | ], 43 | "@typescript-eslint/no-non-null-assertion": "off", 44 | }, 45 | }, 46 | ); 47 | -------------------------------------------------------------------------------- /src/utils/wait.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Wait until the condition is `true` or timeout. 3 | * The callback is triggered if condition returns `true`. 4 | * @param condition 5 | * @param callback 6 | * @param interval 7 | * @param timeout 8 | */ 9 | export function waitUntil( 10 | condition: () => boolean, 11 | callback: () => void, 12 | interval = 100, 13 | timeout = 10000, 14 | ) { 15 | const start = Date.now(); 16 | const intervalId = ztoolkit.getGlobal("setInterval")(() => { 17 | if (condition()) { 18 | ztoolkit.getGlobal("clearInterval")(intervalId); 19 | callback(); 20 | } else if (Date.now() - start > timeout) { 21 | ztoolkit.getGlobal("clearInterval")(intervalId); 22 | } 23 | }, interval); 24 | } 25 | 26 | /** 27 | * Wait async until the condition is `true` or timeout. 28 | * @param condition 29 | * @param interval 30 | * @param timeout 31 | */ 32 | export function waitUtilAsync( 33 | condition: () => boolean, 34 | interval = 100, 35 | timeout = 10000, 36 | ) { 37 | return new Promise((resolve, reject) => { 38 | const start = Date.now(); 39 | const intervalId = ztoolkit.getGlobal("setInterval")(() => { 40 | if (condition()) { 41 | ztoolkit.getGlobal("clearInterval")(intervalId); 42 | resolve(); 43 | } else if (Date.now() - start > timeout) { 44 | ztoolkit.getGlobal("clearInterval")(intervalId); 45 | reject(); 46 | } 47 | }, interval); 48 | }); 49 | } 50 | -------------------------------------------------------------------------------- /.vscode/toolkit.code-snippets: -------------------------------------------------------------------------------- 1 | { 2 | "appendElement - full": { 3 | "scope": "javascript,typescript", 4 | "prefix": "appendElement", 5 | "body": [ 6 | "appendElement({", 7 | "\ttag: '${1:div}',", 8 | "\tid: '${2:id}',", 9 | "\tnamespace: '${3:html}',", 10 | "\tclassList: ['${4:class}'],", 11 | "\tstyles: {${5:style}: '$6'},", 12 | "\tproperties: {},", 13 | "\tattributes: {},", 14 | "\t[{ '${7:onload}', (e: Event) => $8, ${9:false} }],", 15 | "\tcheckExistanceParent: ${10:HTMLElement},", 16 | "\tignoreIfExists: ${11:true},", 17 | "\tskipIfExists: ${12:true},", 18 | "\tremoveIfExists: ${13:true},", 19 | "\tcustomCheck: (doc: Document, options: ElementOptions) => ${14:true},", 20 | "\tchildren: [$15]", 21 | "}, ${16:container});" 22 | ] 23 | }, 24 | "appendElement - minimum": { 25 | "scope": "javascript,typescript", 26 | "prefix": "appendElement", 27 | "body": "appendElement({ tag: '$1' }, $2);" 28 | }, 29 | "register Notifier": { 30 | "scope": "javascript,typescript", 31 | "prefix": "registerObserver", 32 | "body": [ 33 | "registerObserver({", 34 | "\t notify: (", 35 | "\t\tevent: _ZoteroTypes.Notifier.Event,", 36 | "\t\ttype: _ZoteroTypes.Notifier.Type,", 37 | "\t\tids: string[],", 38 | "\t\textraData: _ZoteroTypes.anyObj", 39 | "\t) => {", 40 | "\t\t$0", 41 | "\t}", 42 | "});" 43 | ] 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/utils/ztoolkit.ts: -------------------------------------------------------------------------------- 1 | import { ZoteroToolkit } from "zotero-plugin-toolkit"; 2 | import { config } from "../../package.json"; 3 | 4 | export { createZToolkit }; 5 | 6 | function createZToolkit() { 7 | const _ztoolkit = new ZoteroToolkit(); 8 | /** 9 | * Alternatively, import toolkit modules you use to minify the plugin size. 10 | * You can add the modules under the `MyToolkit` class below and uncomment the following line. 11 | */ 12 | // const _ztoolkit = new MyToolkit(); 13 | initZToolkit(_ztoolkit); 14 | return _ztoolkit; 15 | } 16 | 17 | function initZToolkit(_ztoolkit: ReturnType) { 18 | const env = __env__; 19 | _ztoolkit.basicOptions.log.prefix = `[${config.addonName}]`; 20 | _ztoolkit.basicOptions.log.disableConsole = env === "production"; 21 | _ztoolkit.UI.basicOptions.ui.enableElementJSONLog = __env__ === "development"; 22 | _ztoolkit.UI.basicOptions.ui.enableElementDOMLog = __env__ === "development"; 23 | _ztoolkit.basicOptions.debug.disableDebugBridgePassword = 24 | __env__ === "development"; 25 | _ztoolkit.basicOptions.api.pluginID = config.addonID; 26 | _ztoolkit.ProgressWindow.setIconURI( 27 | "default", 28 | `chrome://${config.addonRef}/content/icons/favicon.png`, 29 | ); 30 | } 31 | 32 | import { BasicTool, unregister } from "zotero-plugin-toolkit"; 33 | import { UITool } from "zotero-plugin-toolkit"; 34 | 35 | class MyToolkit extends BasicTool { 36 | UI: UITool; 37 | 38 | constructor() { 39 | super(); 40 | this.UI = new UITool(this); 41 | } 42 | 43 | unregisterAll() { 44 | unregister(this); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "zotero-chatgpt", 3 | "version": "1.5", 4 | "description": "ChatGPT in Zotero", 5 | "config": { 6 | "addonName": "Zotero ChatGPT", 7 | "addonID": "zoterochatbot@foxmail.com", 8 | "addonRef": "zoterochatbot", 9 | "addonInstance": "AddonTemplate", 10 | "prefsPrefix": "extensions.zotero.addontemplate" 11 | }, 12 | "repository": { 13 | "type": "git", 14 | "url": "git+https://github.com/kazgu/zotero-chatgpt.git" 15 | }, 16 | "author": "kazgu", 17 | "bugs": { 18 | "url": "https://github.com/kazgu/zotero-chatgpt/issues" 19 | }, 20 | "homepage": "https://github.com/kazgu/zotero-chatgpt#readme", 21 | "license": "AGPL-3.0-or-later", 22 | "scripts": { 23 | "start": "zotero-plugin serve", 24 | "build": "tsc --noEmit && zotero-plugin build", 25 | "lint": "prettier --write . && eslint . --fix", 26 | "release": "zotero-plugin release", 27 | "test": "echo \"Error: no test specified\" && exit 1", 28 | "update-deps": "npm update --save" 29 | }, 30 | "dependencies": { 31 | "@types/aws-lambda": "^8.10.145", 32 | "@types/bluebird": "^3.5.42", 33 | "@types/estree": "^1.0.6", 34 | "@types/json-schema": "^7.0.15", 35 | "@types/localforage": "^0.0.34", 36 | "@types/minimatch": "^5.1.2", 37 | "@types/mute-stream": "^0.0.4", 38 | "@types/normalize-package-data": "^2.4.4", 39 | "@types/prop-types": "^15.7.13", 40 | "@types/react": "^18.3.12", 41 | "@types/semver": "^7.5.8", 42 | "@types/wrap-ansi": "^8.1.0", 43 | "@types/yauzl": "^2.10.3", 44 | "aws-lambda": "^1.0.7", 45 | "wrap-ansi": "^9.0.0", 46 | "zotero-plugin-toolkit": "^4.0.9" 47 | }, 48 | "devDependencies": { 49 | "@eslint/js": "^9.14.0", 50 | "@types/node": "^22.9.0", 51 | "eslint": "^9.12.0", 52 | "prettier": "^3.3.3", 53 | "typescript": "^5.6.3", 54 | "typescript-eslint": "^8.14.0", 55 | "zotero-plugin-scaffold": "^0.1.6", 56 | "zotero-types": "^2.2.0" 57 | }, 58 | "prettier": { 59 | "printWidth": 80, 60 | "tabWidth": 2, 61 | "endOfLine": "lf", 62 | "overrides": [ 63 | { 64 | "files": [ 65 | "*.xhtml" 66 | ], 67 | "options": { 68 | "htmlWhitespaceSensitivity": "css" 69 | } 70 | } 71 | ] 72 | } 73 | } -------------------------------------------------------------------------------- /addon/bootstrap.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable no-undef */ 2 | 3 | /** 4 | * Most of this code is from Zotero team's official Make It Red example[1] 5 | * or the Zotero 7 documentation[2]. 6 | * [1] https://github.com/zotero/make-it-red 7 | * [2] https://www.zotero.org/support/dev/zotero_7_for_developers 8 | */ 9 | 10 | var chromeHandle; 11 | 12 | function install(data, reason) {} 13 | 14 | async function startup({ id, version, resourceURI, rootURI }, reason) { 15 | await Zotero.initializationPromise; 16 | 17 | // String 'rootURI' introduced in Zotero 7 18 | if (!rootURI) { 19 | rootURI = resourceURI.spec; 20 | } 21 | 22 | var aomStartup = Components.classes[ 23 | "@mozilla.org/addons/addon-manager-startup;1" 24 | ].getService(Components.interfaces.amIAddonManagerStartup); 25 | var manifestURI = Services.io.newURI(rootURI + "manifest.json"); 26 | chromeHandle = aomStartup.registerChrome(manifestURI, [ 27 | ["content", "__addonRef__", rootURI + "chrome/content/"], 28 | ]); 29 | 30 | /** 31 | * Global variables for plugin code. 32 | * The `_globalThis` is the global root variable of the plugin sandbox environment 33 | * and all child variables assigned to it is globally accessible. 34 | * See `src/index.ts` for details. 35 | */ 36 | const ctx = { 37 | rootURI, 38 | }; 39 | ctx._globalThis = ctx; 40 | 41 | Services.scriptloader.loadSubScript( 42 | `${rootURI}/chrome/content/scripts/__addonRef__.js`, 43 | ctx, 44 | ); 45 | Zotero.__addonInstance__.hooks.onStartup(); 46 | } 47 | 48 | async function onMainWindowLoad({ window }, reason) { 49 | Zotero.__addonInstance__?.hooks.onMainWindowLoad(window); 50 | } 51 | 52 | async function onMainWindowUnload({ window }, reason) { 53 | Zotero.__addonInstance__?.hooks.onMainWindowUnload(window); 54 | } 55 | 56 | function shutdown({ id, version, resourceURI, rootURI }, reason) { 57 | if (reason === APP_SHUTDOWN) { 58 | return; 59 | } 60 | 61 | if (typeof Zotero === "undefined") { 62 | Zotero = Components.classes["@zotero.org/Zotero;1"].getService( 63 | Components.interfaces.nsISupports, 64 | ).wrappedJSObject; 65 | } 66 | Zotero.__addonInstance__?.hooks.onShutdown(); 67 | 68 | Cc["@mozilla.org/intl/stringbundle;1"] 69 | .getService(Components.interfaces.nsIStringBundleService) 70 | .flushBundles(); 71 | 72 | Cu.unload(`${rootURI}/chrome/content/scripts/__addonRef__.js`); 73 | 74 | if (chromeHandle) { 75 | chromeHandle.destruct(); 76 | chromeHandle = null; 77 | } 78 | } 79 | 80 | function uninstall(data, reason) {} 81 | -------------------------------------------------------------------------------- /src/utils/locale.ts: -------------------------------------------------------------------------------- 1 | import { config } from "../../package.json"; 2 | 3 | export { initLocale, getString, getLocaleID }; 4 | 5 | /** 6 | * Initialize locale data 7 | */ 8 | function initLocale() { 9 | const l10n = new ( 10 | typeof Localization === "undefined" 11 | ? ztoolkit.getGlobal("Localization") 12 | : Localization 13 | )([`${config.addonRef}-addon.ftl`], true); 14 | addon.data.locale = { 15 | current: l10n, 16 | }; 17 | } 18 | 19 | /** 20 | * Get locale string, see https://firefox-source-docs.mozilla.org/l10n/fluent/tutorial.html#fluent-translation-list-ftl 21 | * @param localString ftl key 22 | * @param options.branch branch name 23 | * @param options.args args 24 | * @example 25 | * ```ftl 26 | * # addon.ftl 27 | * addon-static-example = This is default branch! 28 | * .branch-example = This is a branch under addon-static-example! 29 | * addon-dynamic-example = 30 | { $count -> 31 | [one] I have { $count } apple 32 | *[other] I have { $count } apples 33 | } 34 | * ``` 35 | * ```js 36 | * getString("addon-static-example"); // This is default branch! 37 | * getString("addon-static-example", { branch: "branch-example" }); // This is a branch under addon-static-example! 38 | * getString("addon-dynamic-example", { args: { count: 1 } }); // I have 1 apple 39 | * getString("addon-dynamic-example", { args: { count: 2 } }); // I have 2 apples 40 | * ``` 41 | */ 42 | function getString(localString: string): string; 43 | function getString(localString: string, branch: string): string; 44 | function getString( 45 | localeString: string, 46 | options: { branch?: string | undefined; args?: Record }, 47 | ): string; 48 | function getString(...inputs: any[]) { 49 | if (inputs.length === 1) { 50 | return _getString(inputs[0]); 51 | } else if (inputs.length === 2) { 52 | if (typeof inputs[1] === "string") { 53 | return _getString(inputs[0], { branch: inputs[1] }); 54 | } else { 55 | return _getString(inputs[0], inputs[1]); 56 | } 57 | } else { 58 | throw new Error("Invalid arguments"); 59 | } 60 | } 61 | 62 | function _getString( 63 | localeString: string, 64 | options: { branch?: string | undefined; args?: Record } = {}, 65 | ): string { 66 | const localStringWithPrefix = `${config.addonRef}-${localeString}`; 67 | const { branch, args } = options; 68 | const pattern = addon.data.locale?.current.formatMessagesSync([ 69 | { id: localStringWithPrefix, args }, 70 | ])[0]; 71 | if (!pattern) { 72 | return localStringWithPrefix; 73 | } 74 | if (branch && pattern.attributes) { 75 | for (const attr of pattern.attributes) { 76 | if (attr.name === branch) { 77 | return attr.value; 78 | } 79 | } 80 | return pattern.attributes[branch] || localStringWithPrefix; 81 | } else { 82 | return pattern.value || localStringWithPrefix; 83 | } 84 | } 85 | 86 | function getLocaleID(id: string) { 87 | return `${config.addonRef}-${id}`; 88 | } 89 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Zotero ChatGPT Plugin 2 | 3 | [![Zotero target version](https://img.shields.io/badge/Zotero-7-green?style=flat-square&logo=zotero&logoColor=CC2936)](https://www.zotero.org) 4 | [![License: AGPL-3.0-or-later](https://img.shields.io/badge/License-AGPL--3.0--or--later-blue.svg)](https://www.gnu.org/licenses/agpl-3.0) 5 | 6 | A Zotero plugin that integrates ChatGPT functionality directly into your reference management workflow. 7 | 8 | ![show](default.jpg "show") 9 | 10 | ## Features 11 | 12 | - **ChatGPT Query Interface**: 13 | - Directly query ChatGPT with research questions 14 | - Stream responses in real-time 15 | - Supports system prompts for customized behavior 16 | 17 | - **Research Paper Tools**: 18 | - **PDF Summarization**: Automatically summarize attached PDFs of research papers 19 | - **BibTeX Generation**: Fetch BibTeX entries from DBLP for references 20 | - **Context Integration**: Auto-include paper titles/abstracts in queries 21 | 22 | - **Translation**: 23 | - Translate text to Chinese with one click 24 | - Customizable translation prompts 25 | 26 | - **UI Integration**: 27 | - Right-click context menu for quick access 28 | - Dedicated reader pane interface 29 | - Customizable style sheets 30 | - Keyboard shortcuts for common functions 31 | 32 | - **Configuration**: 33 | - Set OpenAI API key and model preferences 34 | - Customize base API URL 35 | - Configure default behaviors 36 | 37 | ## Installation 38 | 39 | 1. Download the latest `.xpi` file from the [Releases page](https://github.com/kazgu/zotero-chatgpt/releases) 40 | 2. In Zotero, go to Tools → Add-ons 41 | 3. Click the gear icon and select "Install Add-on From File" 42 | 4. Select the downloaded `.xpi` file 43 | 5. Restart Zotero 44 | 45 | ## Development 46 | 47 | ### Prerequisites 48 | 49 | - [Zotero 7](https://www.zotero.org/support/beta_builds) 50 | - [Node.js](https://nodejs.org/en/) 51 | - [Git](https://git-scm.com/) 52 | 53 | ### Setup 54 | 55 | 1. Clone the repository: 56 | ```bash 57 | git clone https://github.com/kazgu/zotero-chatgpt.git 58 | cd zotero-chatgpt 59 | ``` 60 | 2. Install dependencies: 61 | ```bash 62 | npm install 63 | ``` 64 | 3. Configure environment variables by copying `.env.example` to `.env` and updating the paths: 65 | ```bash 66 | cp .env.example .env 67 | ``` 68 | 69 | ### Running in Development Mode 70 | 71 | ```bash 72 | npm start 73 | ``` 74 | 75 | This will: 76 | - Start the development server 77 | - Launch Zotero with the plugin loaded from the `build/` directory 78 | - Open developer tools 79 | - Watch for changes in `src/` and `addon/` directories and automatically reload 80 | 81 | ### Building for Production 82 | 83 | ```bash 84 | npm run build 85 | ``` 86 | 87 | The production build will be created in the `build/` directory. 88 | 89 | ## License 90 | 91 | This project is licensed under the AGPL-3.0-or-later License - see the [LICENSE](LICENSE) file for details. 92 | 93 | ## Acknowledgments 94 | 95 | - Built using the [Zotero Plugin Template](https://github.com/windingwind/zotero-plugin-template) 96 | - Uses [zotero-plugin-toolkit](https://github.com/windingwind/zotero-plugin-toolkit) for plugin utilities 97 | -------------------------------------------------------------------------------- /src/modules/preferenceScript.ts: -------------------------------------------------------------------------------- 1 | import { config } from "../../package.json"; 2 | import { getString } from "../utils/locale"; 3 | 4 | export async function registerPrefsScripts(_window: Window) { 5 | // This function is called when the prefs window is opened 6 | // See addon/chrome/content/preferences.xul onpaneload 7 | if (!addon.data.prefs) { 8 | addon.data.prefs = { 9 | window: _window, 10 | columns: [ 11 | { 12 | dataKey: "title", 13 | label: getString("prefs-table-title"), 14 | fixedWidth: true, 15 | width: 100, 16 | }, 17 | { 18 | dataKey: "detail", 19 | label: getString("prefs-table-detail"), 20 | }, 21 | ], 22 | rows: [ 23 | { 24 | title: "Orange", 25 | detail: "It's juicy", 26 | }, 27 | { 28 | title: "Banana", 29 | detail: "It's sweet", 30 | }, 31 | { 32 | title: "Apple", 33 | detail: "I mean the fruit APPLE", 34 | }, 35 | ], 36 | }; 37 | } else { 38 | addon.data.prefs.window = _window; 39 | } 40 | updatePrefsUI(); 41 | bindPrefEvents(); 42 | } 43 | 44 | async function updatePrefsUI() { 45 | // You can initialize some UI elements on prefs window 46 | // with addon.data.prefs.window.document 47 | // Or bind some events to the elements 48 | const renderLock = ztoolkit.getGlobal("Zotero").Promise.defer(); 49 | if (addon.data.prefs?.window == undefined) return; 50 | const tableHelper = new ztoolkit.VirtualizedTable(addon.data.prefs?.window) 51 | .setContainerId(`${config.addonRef}-table-container`) 52 | .setProp({ 53 | id: `${config.addonRef}-prefs-table`, 54 | // Do not use setLocale, as it modifies the Zotero.Intl.strings 55 | // Set locales directly to columns 56 | columns: addon.data.prefs?.columns, 57 | showHeader: true, 58 | multiSelect: true, 59 | staticColumns: true, 60 | disableFontSizeScaling: true, 61 | }) 62 | .setProp("getRowCount", () => addon.data.prefs?.rows.length || 0) 63 | .setProp( 64 | "getRowData", 65 | (index) => 66 | addon.data.prefs?.rows[index] || { 67 | title: "no data", 68 | detail: "no data", 69 | }, 70 | ) 71 | // Show a progress window when selection changes 72 | .setProp("onSelectionChange", (selection) => { 73 | new ztoolkit.ProgressWindow(config.addonName) 74 | .createLine({ 75 | text: `Selected line: ${addon.data.prefs?.rows 76 | .filter((v, i) => selection.isSelected(i)) 77 | .map((row) => row.title) 78 | .join(",")}`, 79 | progress: 100, 80 | }) 81 | .show(); 82 | }) 83 | // When pressing delete, delete selected line and refresh table. 84 | // Returning false to prevent default event. 85 | .setProp("onKeyDown", (event: KeyboardEvent) => { 86 | if (event.key == "Delete" || (Zotero.isMac && event.key == "Backspace")) { 87 | addon.data.prefs!.rows = 88 | addon.data.prefs?.rows.filter( 89 | (v, i) => !tableHelper.treeInstance.selection.isSelected(i), 90 | ) || []; 91 | tableHelper.render(); 92 | return false; 93 | } 94 | return true; 95 | }) 96 | // For find-as-you-type 97 | .setProp( 98 | "getRowString", 99 | (index) => addon.data.prefs?.rows[index].title || "", 100 | ) 101 | // Render the table. 102 | .render(-1, () => { 103 | renderLock.resolve(); 104 | }); 105 | await renderLock.promise; 106 | ztoolkit.log("Preference table rendered!"); 107 | } 108 | 109 | function bindPrefEvents() { 110 | 111 | 112 | addon.data 113 | .prefs!.window.document.querySelector( 114 | `#zotero-prefpane-${config.addonRef}-input`, 115 | ) 116 | ?.addEventListener("change", (e) => { 117 | ztoolkit.log(e); 118 | addon.data.prefs!.window.alert( 119 | `Successfully changed to ${(e.target as HTMLInputElement).value}!`, 120 | ); 121 | }); 122 | 123 | addon.data 124 | .prefs!.window.document.querySelector( 125 | `#zotero-prefpane-${config.addonRef}-base`, 126 | ) 127 | ?.addEventListener("change", (e) => { 128 | ztoolkit.log(e); 129 | addon.data.prefs!.window.alert( 130 | `Successfully changed to ${(e.target as HTMLInputElement).value}!`, 131 | ); 132 | }); 133 | } 134 | -------------------------------------------------------------------------------- /src/hooks.ts: -------------------------------------------------------------------------------- 1 | import { 2 | BasicExampleFactory, 3 | HelperExampleFactory, 4 | KeyExampleFactory, 5 | UIExampleFactory, 6 | } from "./modules/main"; 7 | import { config } from "../package.json"; 8 | import { getString, initLocale } from "./utils/locale"; 9 | import { registerPrefsScripts } from "./modules/preferenceScript"; 10 | import { createZToolkit } from "./utils/ztoolkit"; 11 | 12 | async function onStartup() { 13 | await Promise.all([ 14 | Zotero.initializationPromise, 15 | Zotero.unlockPromise, 16 | Zotero.uiReadyPromise, 17 | ]); 18 | 19 | initLocale(); 20 | 21 | BasicExampleFactory.registerPrefs(); 22 | 23 | // BasicExampleFactory.registerNotifier(); 24 | 25 | // KeyExampleFactory.registerShortcuts(); 26 | 27 | // await UIExampleFactory.registerExtraColumn(); 28 | 29 | // await UIExampleFactory.registerExtraColumnWithCustomCell(); 30 | 31 | // UIExampleFactory.registerItemPaneSection(); 32 | 33 | 34 | 35 | await Promise.all( 36 | Zotero.getMainWindows().map((win) => onMainWindowLoad(win)), 37 | ); 38 | } 39 | 40 | async function onMainWindowLoad(win: Window): Promise { 41 | // Create ztoolkit for every window 42 | addon.data.ztoolkit = createZToolkit(); 43 | 44 | // @ts-ignore This is a moz feature 45 | win.MozXULElement.insertFTLIfNeeded(`${config.addonRef}-mainWindow.ftl`); 46 | 47 | // const popupWin = new ztoolkit.ProgressWindow(config.addonName, { 48 | // closeOnClick: true, 49 | // closeTime: -1, 50 | // }) 51 | // .createLine({ 52 | // text: getString("startup-begin"), 53 | // type: "default", 54 | // progress: 0, 55 | // }) 56 | // .show(); 57 | 58 | await Zotero.Promise.delay(1000); 59 | // popupWin.changeLine({ 60 | // progress: 30, 61 | // text: `[30%] ${getString("startup-begin")}`, 62 | // }); 63 | 64 | UIExampleFactory.registerReaderItemPaneSection(win); 65 | UIExampleFactory.registerStyleSheet(win); 66 | 67 | UIExampleFactory.registerRightClickMenuItem(); 68 | 69 | // UIExampleFactory.registerRightClickMenuPopup(win); 70 | 71 | UIExampleFactory.registerWindowMenuWithSeparator(); 72 | 73 | // PromptExampleFactory.registerNormalCommandExample(); 74 | 75 | // PromptExampleFactory.registerAnonymousCommandExample(win); 76 | 77 | // PromptExampleFactory.registerConditionalCommandExample(); 78 | 79 | await Zotero.Promise.delay(1000); 80 | 81 | // popupWin.changeLine({ 82 | // progress: 100, 83 | // text: `[100%] ${getString("startup-finish")}`, 84 | // }); 85 | // popupWin.startCloseTimer(5000); 86 | 87 | // addon.hooks.onDialogEvents("dialogExample"); 88 | } 89 | 90 | async function onMainWindowUnload(win: Window): Promise { 91 | ztoolkit.unregisterAll(); 92 | addon.data.dialog?.window?.close(); 93 | } 94 | 95 | function onShutdown(): void { 96 | ztoolkit.unregisterAll(); 97 | addon.data.dialog?.window?.close(); 98 | // Remove addon object 99 | addon.data.alive = false; 100 | delete Zotero[config.addonInstance]; 101 | } 102 | 103 | /** 104 | * This function is just an example of dispatcher for Notify events. 105 | * Any operations should be placed in a function to keep this funcion clear. 106 | */ 107 | async function onNotify( 108 | event: string, 109 | type: string, 110 | ids: Array, 111 | extraData: { [key: string]: any }, 112 | ) { 113 | // You can add your code to the corresponding notify type 114 | ztoolkit.log("notify", event, type, ids, extraData); 115 | if ( 116 | event == "select" && 117 | type == "tab" && 118 | extraData[ids[0]].type == "reader" 119 | ) { 120 | BasicExampleFactory.exampleNotifierCallback(); 121 | } else { 122 | return; 123 | } 124 | } 125 | 126 | /** 127 | * This function is just an example of dispatcher for Preference UI events. 128 | * Any operations should be placed in a function to keep this funcion clear. 129 | * @param type event type 130 | * @param data event data 131 | */ 132 | async function onPrefsEvent(type: string, data: { [key: string]: any }) { 133 | switch (type) { 134 | case "load": 135 | registerPrefsScripts(data.window); 136 | break; 137 | default: 138 | return; 139 | } 140 | } 141 | 142 | function onShortcuts(type: string) { 143 | switch (type) { 144 | case "larger": 145 | KeyExampleFactory.exampleShortcutLargerCallback(); 146 | break; 147 | case "smaller": 148 | KeyExampleFactory.exampleShortcutSmallerCallback(); 149 | break; 150 | default: 151 | break; 152 | } 153 | } 154 | 155 | function onDialogEvents(type: string) { 156 | switch (type) { 157 | case "dialogExample": 158 | HelperExampleFactory.dialogExample(); 159 | break; 160 | case "clipboardExample": 161 | HelperExampleFactory.clipboardExample(); 162 | break; 163 | case "filePickerExample": 164 | HelperExampleFactory.filePickerExample(); 165 | break; 166 | case "progressWindowExample": 167 | HelperExampleFactory.progressWindowExample(); 168 | break; 169 | case "vtableExample": 170 | HelperExampleFactory.vtableExample(); 171 | break; 172 | default: 173 | break; 174 | } 175 | } 176 | 177 | // Add your hooks here. For element click, etc. 178 | // Keep in mind hooks only do dispatch. Don't add code that does real jobs in hooks. 179 | // Otherwise the code would be hard to read and maintain. 180 | 181 | export default { 182 | onStartup, 183 | onShutdown, 184 | onMainWindowLoad, 185 | onMainWindowUnload, 186 | onNotify, 187 | onPrefsEvent, 188 | onShortcuts, 189 | onDialogEvents, 190 | }; 191 | -------------------------------------------------------------------------------- /addon/chrome/content/zoteroPane.css: -------------------------------------------------------------------------------- 1 | .makeItRed { 2 | background-color: tomato; 3 | } 4 | 5 | /* ChatGPT Chat Interface Styles */ 6 | 7 | /* Main container */ 8 | .chat-container { 9 | display: flex; 10 | flex-direction: column; 11 | height: 100%; 12 | background: #f7f7f8; 13 | font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; 14 | } 15 | 16 | /* Chat history area */ 17 | .chat-history { 18 | flex: 1; 19 | overflow-y: auto; 20 | overflow-x: hidden; 21 | padding: 16px; 22 | display: flex; 23 | flex-direction: column; 24 | gap: 12px; 25 | scroll-behavior: smooth; 26 | } 27 | 28 | /* Scrollbar styling */ 29 | .chat-history::-webkit-scrollbar { 30 | width: 6px; 31 | } 32 | 33 | .chat-history::-webkit-scrollbar-track { 34 | background: transparent; 35 | } 36 | 37 | .chat-history::-webkit-scrollbar-thumb { 38 | background: #ccc; 39 | border-radius: 3px; 40 | } 41 | 42 | .chat-history::-webkit-scrollbar-thumb:hover { 43 | background: #999; 44 | } 45 | 46 | /* Message wrapper */ 47 | .message-wrapper { 48 | display: flex; 49 | width: 100%; 50 | animation: slideIn 0.2s ease-out; 51 | } 52 | 53 | .message-wrapper.user { 54 | justify-content: flex-end; 55 | } 56 | 57 | .message-wrapper.assistant { 58 | justify-content: flex-start; 59 | } 60 | 61 | .message-wrapper.system { 62 | justify-content: center; 63 | } 64 | 65 | /* Message bubbles */ 66 | .message-bubble { 67 | border-radius: 18px; 68 | padding: 10px 16px; 69 | max-width: 70%; 70 | word-wrap: break-word; 71 | word-break: break-word; 72 | white-space: pre-wrap; 73 | line-height: 1.5; 74 | } 75 | 76 | .message-bubble.user-message { 77 | background: #0084ff; 78 | color: white; 79 | border-bottom-right-radius: 4px; 80 | } 81 | 82 | .message-bubble.assistant-message { 83 | background: #e4e6eb; 84 | color: #050505; 85 | border-bottom-left-radius: 4px; 86 | } 87 | 88 | .message-bubble.system-message { 89 | background: #fff3cd; 90 | color: #856404; 91 | border-radius: 8px; 92 | font-size: 13px; 93 | max-width: 80%; 94 | text-align: center; 95 | } 96 | 97 | .message-bubble.error-message { 98 | background: #ff4444; 99 | color: white; 100 | border-radius: 8px; 101 | font-size: 13px; 102 | max-width: 80%; 103 | } 104 | 105 | /* Message content */ 106 | .message-content { 107 | font-size: 14px; 108 | } 109 | 110 | /* Typing indicator */ 111 | .typing-indicator { 112 | display: inline-flex; 113 | gap: 4px; 114 | padding: 8px 0; 115 | } 116 | 117 | .typing-dot { 118 | width: 8px; 119 | height: 8px; 120 | border-radius: 50%; 121 | background: #8a8a8a; 122 | animation: typing 1.4s infinite; 123 | } 124 | 125 | .typing-dot:nth-child(2) { 126 | animation-delay: 0.2s; 127 | } 128 | 129 | .typing-dot:nth-child(3) { 130 | animation-delay: 0.4s; 131 | } 132 | 133 | /* PDF control section */ 134 | .pdf-control { 135 | padding: 8px 16px; 136 | background: white; 137 | border-top: 1px solid #e5e5e5; 138 | display: flex; 139 | align-items: center; 140 | gap: 8px; 141 | } 142 | 143 | .pdf-control label { 144 | display: flex; 145 | align-items: center; 146 | gap: 6px; 147 | font-size: 13px; 148 | color: #444; 149 | cursor: pointer; 150 | user-select: none; 151 | } 152 | 153 | .pdf-control input[type="checkbox"] { 154 | cursor: pointer; 155 | } 156 | 157 | .pdf-control input[type="checkbox"]:disabled { 158 | cursor: not-allowed; 159 | opacity: 0.5; 160 | } 161 | 162 | .pdf-status { 163 | font-size: 12px; 164 | color: #666; 165 | margin-left: 4px; 166 | } 167 | 168 | .pdf-status.attached { 169 | color: #28a745; 170 | font-weight: 500; 171 | } 172 | 173 | /* Input section */ 174 | .input-section { 175 | border-top: 1px solid #e5e5e5; 176 | background: white; 177 | padding: 12px; 178 | } 179 | 180 | .input-area { 181 | display: flex; 182 | gap: 8px; 183 | align-items: flex-end; 184 | } 185 | 186 | .input-box { 187 | flex: 1; 188 | border: 1px solid #ccc; 189 | border-radius: 20px; 190 | padding: 10px 16px; 191 | font-size: 14px; 192 | font-family: inherit; 193 | resize: none; 194 | max-height: 120px; 195 | overflow-y: auto; 196 | transition: border-color 0.2s; 197 | line-height: 1.4; 198 | } 199 | 200 | .input-box:focus { 201 | outline: none; 202 | border-color: #0084ff; 203 | } 204 | 205 | .input-box::placeholder { 206 | color: #999; 207 | } 208 | 209 | .input-box::-webkit-scrollbar { 210 | width: 4px; 211 | } 212 | 213 | .input-box::-webkit-scrollbar-thumb { 214 | background: #ccc; 215 | border-radius: 2px; 216 | } 217 | 218 | /* Send button */ 219 | .send-button { 220 | background: #0084ff; 221 | color: white; 222 | border: none; 223 | border-radius: 50%; 224 | width: 36px; 225 | height: 36px; 226 | min-width: 36px; 227 | min-height: 36px; 228 | cursor: pointer; 229 | display: flex; 230 | align-items: center; 231 | justify-content: center; 232 | font-size: 18px; 233 | font-weight: bold; 234 | transition: background 0.2s, transform 0.1s; 235 | flex-shrink: 0; 236 | } 237 | 238 | .send-button:hover:not(:disabled) { 239 | background: #0073e6; 240 | } 241 | 242 | .send-button:active:not(:disabled) { 243 | transform: scale(0.95); 244 | } 245 | 246 | .send-button:disabled { 247 | background: #ccc; 248 | cursor: not-allowed; 249 | opacity: 0.6; 250 | } 251 | 252 | .send-button svg, 253 | .send-button span { 254 | pointer-events: none; 255 | } 256 | 257 | /* Animations */ 258 | @keyframes slideIn { 259 | from { 260 | opacity: 0; 261 | transform: translateY(10px); 262 | } 263 | 264 | to { 265 | opacity: 1; 266 | transform: translateY(0); 267 | } 268 | } 269 | 270 | @keyframes typing { 271 | 272 | 0%, 273 | 60%, 274 | 100% { 275 | transform: translateY(0); 276 | } 277 | 278 | 30% { 279 | transform: translateY(-10px); 280 | } 281 | } 282 | 283 | @keyframes fadeIn { 284 | from { 285 | opacity: 0; 286 | } 287 | 288 | to { 289 | opacity: 1; 290 | } 291 | } 292 | 293 | /* Empty state */ 294 | .chat-empty-state { 295 | display: flex; 296 | flex-direction: column; 297 | align-items: center; 298 | justify-content: center; 299 | height: 100%; 300 | color: #666; 301 | font-size: 14px; 302 | text-align: center; 303 | padding: 20px; 304 | gap: 8px; 305 | } 306 | 307 | .chat-empty-state-icon { 308 | font-size: 48px; 309 | opacity: 0.3; 310 | } 311 | 312 | /* Responsive adjustments */ 313 | @media (max-width: 400px) { 314 | .message-bubble { 315 | max-width: 85%; 316 | padding: 8px 12px; 317 | font-size: 13px; 318 | } 319 | 320 | .chat-history { 321 | padding: 12px; 322 | gap: 8px; 323 | } 324 | 325 | .input-section { 326 | padding: 8px; 327 | } 328 | } 329 | 330 | /* Dark mode support (optional) */ 331 | @media (prefers-color-scheme: dark) { 332 | .chat-container { 333 | background: #1e1e1e; 334 | } 335 | 336 | .message-bubble.assistant-message { 337 | background: #2d2d2d; 338 | color: #e4e4e4; 339 | } 340 | 341 | .pdf-control, 342 | .input-section { 343 | background: #2d2d2d; 344 | border-color: #3d3d3d; 345 | } 346 | 347 | .pdf-control label { 348 | color: #ccc; 349 | } 350 | 351 | .input-box { 352 | background: #1e1e1e; 353 | border-color: #3d3d3d; 354 | color: #e4e4e4; 355 | } 356 | 357 | .input-box::placeholder { 358 | color: #666; 359 | } 360 | } -------------------------------------------------------------------------------- /doc/README-zhCN.md: -------------------------------------------------------------------------------- 1 | # Zotero Plugin Template 2 | 3 | [![zotero target version](https://img.shields.io/badge/Zotero-7-green?style=flat-square&logo=zotero&logoColor=CC2936)](https://www.zotero.org) 4 | [![Using Zotero Plugin Template](https://img.shields.io/badge/Using-Zotero%20Plugin%20Template-blue?style=flat-square&logo=github)](https://github.com/windingwind/zotero-plugin-template) 5 | 6 | 这是 [Zotero](https://www.zotero.org/) 的插件模板. 7 | 8 | [English](../README.md) | [简体中文](./README-zhCN.md) 9 | 10 | - 开发指南 11 | - [📖 插件开发文档](https://zotero-chinese.com/plugin-dev-guide/) (中文版,尚不完善) 12 | - [📖 Zotero 7 插件开发文档](https://www.zotero.org/support/dev/zotero_7_for_developers) 13 | - 开发工具参考 14 | - [🛠️ Zotero 插件工具包](https://github.com/windingwind/zotero-plugin-toolkit) | [API 文档](https://github.com/windingwind/zotero-plugin-toolkit/blob/master/docs/zotero-plugin-toolkit.md) 15 | - [🛠️ Zotero 插件开发脚手架](https://github.com/northword/zotero-plugin-scaffold) 16 | - [📜 Zotero 源代码](https://github.com/zotero/zotero) 17 | - [ℹ️ Zotero 类型定义](https://github.com/windingwind/zotero-types) 18 | - [📌 Zotero 插件模板](https://github.com/windingwind/zotero-plugin-template) (即本仓库) 19 | 20 | > [!tip] 21 | > 👁 Watch 本仓库,以及时收到修复或更新的通知. 22 | 23 | ## 使用此模板构建的插件 24 | 25 | [![GitHub Repo stars](https://img.shields.io/github/stars/windingwind/zotero-better-notes?label=zotero-better-notes&style=flat-square)](https://github.com/windingwind/zotero-better-notes) 26 | [![GitHub Repo stars](https://img.shields.io/github/stars/windingwind/zotero-pdf-preview?label=zotero-pdf-preview&style=flat-square)](https://github.com/windingwind/zotero-pdf-preview) 27 | [![GitHub Repo stars](https://img.shields.io/github/stars/windingwind/zotero-pdf-translate?label=zotero-pdf-translate&style=flat-square)](https://github.com/windingwind/zotero-pdf-translate) 28 | [![GitHub Repo stars](https://img.shields.io/github/stars/windingwind/zotero-tag?label=zotero-tag&style=flat-square)](https://github.com/windingwind/zotero-tag) 29 | [![GitHub Repo stars](https://img.shields.io/github/stars/iShareStuff/ZoteroTheme?label=zotero-theme&style=flat-square)](https://github.com/iShareStuff/ZoteroTheme) 30 | [![GitHub Repo stars](https://img.shields.io/github/stars/MuiseDestiny/zotero-reference?label=zotero-reference&style=flat-square)](https://github.com/MuiseDestiny/zotero-reference) 31 | [![GitHub Repo stars](https://img.shields.io/github/stars/MuiseDestiny/zotero-citation?label=zotero-citation&style=flat-square)](https://github.com/MuiseDestiny/zotero-citation) 32 | [![GitHub Repo stars](https://img.shields.io/github/stars/MuiseDestiny/ZoteroStyle?label=zotero-style&style=flat-square)](https://github.com/MuiseDestiny/ZoteroStyle) 33 | [![GitHub Repo stars](https://img.shields.io/github/stars/volatile-static/Chartero?label=Chartero&style=flat-square)](https://github.com/volatile-static/Chartero) 34 | [![GitHub Repo stars](https://img.shields.io/github/stars/l0o0/tara?label=tara&style=flat-square)](https://github.com/l0o0/tara) 35 | [![GitHub Repo stars](https://img.shields.io/github/stars/redleafnew/delitemwithatt?label=delitemwithatt&style=flat-square)](https://github.com/redleafnew/delitemwithatt) 36 | [![GitHub Repo stars](https://img.shields.io/github/stars/redleafnew/zotero-updateifsE?label=zotero-updateifsE&style=flat-square)](https://github.com/redleafnew/zotero-updateifsE) 37 | [![GitHub Repo stars](https://img.shields.io/github/stars/northword/zotero-format-metadata?label=zotero-format-metadata&style=flat-square)](https://github.com/northword/zotero-format-metadata) 38 | [![GitHub Repo stars](https://img.shields.io/github/stars/inciteful-xyz/inciteful-zotero-plugin?label=inciteful-zotero-plugin&style=flat-square)](https://github.com/inciteful-xyz/inciteful-zotero-plugin) 39 | [![GitHub Repo stars](https://img.shields.io/github/stars/MuiseDestiny/zotero-gpt?label=zotero-gpt&style=flat-square)](https://github.com/MuiseDestiny/zotero-gpt) 40 | [![GitHub Repo stars](https://img.shields.io/github/stars/zoushucai/zotero-journalabbr?label=zotero-journalabbr&style=flat-square)](https://github.com/zoushucai/zotero-journalabbr) 41 | [![GitHub Repo stars](https://img.shields.io/github/stars/MuiseDestiny/zotero-figure?label=zotero-figure&style=flat-square)](https://github.com/MuiseDestiny/zotero-figure) 42 | [![GitHub Repo stars](https://img.shields.io/github/stars/l0o0/jasminum?label=jasminum&style=flat-square)](https://github.com/l0o0/jasminum) 43 | [![GitHub Repo stars](https://img.shields.io/github/stars/lifan0127/ai-research-assistant?label=ai-research-assistant&style=flat-square)](https://github.com/lifan0127/ai-research-assistant) 44 | 45 | [![GitHub Repo stars](https://img.shields.io/github/stars/daeh/zotero-markdb-connect?label=zotero-markdb-connect&style=flat-square)](https://github.com/daeh/zotero-markdb-connect) 46 | 47 | 如果你正在使用此库,我建议你将这个标志 ([![Using Zotero Plugin Template](https://img.shields.io/badge/Using-Zotero%20Plugin%20Template-blue?style=flat-square&logo=github)](https://github.com/windingwind/zotero-plugin-template)) 放在 README 文件中: 48 | 49 | ```md 50 | [![Using Zotero Plugin Template](https://img.shields.io/badge/Using-Zotero%20Plugin%20Template-blue?style=flat-square&logo=github)](https://github.com/windingwind/zotero-plugin-template) 51 | ``` 52 | 53 | ## Features 特性 54 | 55 | - 事件驱动、函数式编程的可扩展框架; 56 | - 简单易用,开箱即用; 57 | - ⭐[新特性!]自动热重载!每当修改源码时,都会自动编译并重新加载插件;[详情请跳转→](#自动热重载) 58 | - `src/modules/examples.ts` 中有丰富的示例,涵盖了插件中常用的大部分API (使用 [zotero-plugin-toolkit](https://github.com/windingwind/zotero-plugin-toolkit); 59 | - TypeScript 支持: 60 | - 为使用 JavaScript 编写的 Zotero 源码提供全面的类型定义支持 (使用 [zotero-types](https://github.com/windingwind/zotero-types)); 61 | - 全局变量和环境设置; 62 | - 插件开发/构建/发布工作流: 63 | - 自动生成/更新插件版本、更新配置和设置环境变量 (`development`/`production`); 64 | - 自动在 Zotero 中构建和重新加载代码; 65 | - 自动发布到 GitHub ; 66 | - 集成 Prettier 和 ES Lint; 67 | 68 | ## Examples 示例 69 | 70 | 此库提供了 [zotero-plugin-toolkit](https://github.com/windingwind/zotero-plugin-toolkit) 中API的示例. 71 | 72 | 在 `src/examples.ts` 中搜索`@example` 查看示例. 这些示例在 `src/hooks.ts` 中调用演示. 73 | 74 | ### 基本示例(Basic Examples) 75 | 76 | - registerNotifier 77 | - registerPrefs, unregisterPrefs 78 | 79 | ### 快捷键示例(Shortcut Keys Examples) 80 | 81 | - registerShortcuts 82 | - exampleShortcutLargerCallback 83 | - exampleShortcutSmallerCallback 84 | - exampleShortcutConflictionCallback 85 | 86 | ### UI示例(UI Examples) 87 | 88 | ![image](https://user-images.githubusercontent.com/33902321/211739774-cc5c2df8-5fd9-42f0-9cdf-0f2e5946d427.png) 89 | 90 | - registerStyleSheet(the official make-it-red example) 91 | - registerRightClickMenuItem 92 | - registerRightClickMenuPopup 93 | - registerWindowMenuWithSeprator 94 | - registerExtraColumn 95 | - registerExtraColumnWithCustomCell 96 | - registerCustomItemBoxRow 97 | - registerLibraryTabPanel 98 | - registerReaderTabPanel 99 | 100 | ### 首选项面板示例(Preference Pane Examples) 101 | 102 | ![image](https://user-images.githubusercontent.com/33902321/211737987-cd7c5c87-9177-4159-b975-dc67690d0490.png) 103 | 104 | - Preferences bindings 105 | - UI Events 106 | - Table 107 | - Locale 108 | 109 | 详情参见 [`src/modules/preferenceScript.ts`](./src/modules/preferenceScript.ts) 110 | 111 | ### 帮助示例(HelperExamples) 112 | 113 | ![image](https://user-images.githubusercontent.com/33902321/215119473-e7d0d0ef-6d96-437e-b989-4805ffcde6cf.png) 114 | 115 | - dialogExample 116 | - clipboardExample 117 | - filePickerExample 118 | - progressWindowExample 119 | - vtableExample(See Preference Pane Examples) 120 | 121 | ### 指令行示例(PromptExamples) 122 | 123 | Obsidian风格的指令输入模块,它通过接受文本来运行插件,并在弹出窗口中显示可选项. 124 | 125 | 使用 `Shift+P` 激活. 126 | 127 | ![image](https://user-images.githubusercontent.com/33902321/215120009-e7c7ed27-33a0-44fe-b021-06c272481a92.png) 128 | 129 | - registerAlertPromptExample 130 | 131 | ## 快速上手 132 | 133 | ### 0 环境要求 134 | 135 | 1. 安装 [beta 版 Zotero](https://www.zotero.org/support/beta_builds) 136 | 2. 安装 [Node.js](https://nodejs.org/en/) 和 [Git](https://git-scm.com/) 137 | 138 | > [!note] 139 | > 本指南假定你已经对 Zotero 插件的基本结构和工作原理有初步的了解. 如果你还不了解,请先参考[官方文档](https://www.zotero.org/support/dev/zotero_7_for_developers) 和[官方插件样例 Make It Red](https://github.com/zotero/make-it-red)。 140 | 141 | ### 1 创建你的仓库(Create Your Repo) 142 | 143 | 1. 点击 `Use this template`; 144 | 2. 使用 `git clone` 克隆上一步生成的仓库; 145 |
146 | 💡 从 GitHub Codespace 开始 147 | 148 | _GitHub CodeSpace_ 使你可以直接开始开发而无需在本地下载代码/IDE/依赖. 149 | 150 | 重复下列步骤,仅需三十秒即可开始构建你的第一个插件! 151 | 152 | - 点击首页 `Use this template` 按钮,随后点击 `Open in codespace`, 你需要登录你的 GitHub 账号. 153 | - 等待 codespace 加载. 154 | 155 |
156 | 157 | 3. 进入项目文件夹; 158 | 159 | ### 2 配置模板和开发环境(Config Template Settings and Enviroment) 160 | 161 | 1. 修改 `./package.json` 中的设置,包括: 162 | 163 | ```json5 164 | { 165 | version: "", // 修改为 0.0.0 166 | author: "", 167 | description: "", 168 | homepage: "", 169 | config: { 170 | addonName: "", // 插件名称 171 | addonID: "", // 插件 ID 【重要:防止冲突】 172 | addonRef: "", // 插件命名空间:元素前缀等 173 | addonInstance: "", // 注册在 Zotero 根下的实例名 174 | prefsPrefix: "extensions.zotero.${addonRef}", // 首选项的前缀 175 | }, 176 | } 177 | ``` 178 | 179 | > [!warning] 180 | > 注意设置 addonID 和 addonRef 以避免冲突. 181 | 182 | 如果你需要在 GitHub 以外的地方托管你的 XPI 包,请修改 `zotero-plugin.config.ts` 中的 `updateURL` 和 `xpiDownloadLink`。 183 | 184 | 2. 复制 Zotero 启动配置,填入 Zotero 可执行文件路径和 profile 路径. 185 | 186 | > (可选项) 创建开发用 profile 目录: 187 | > 188 | > 此操作仅需执行一次: 使用 `/path/to/zotero -p` 启动 Zotero,创建一个新的配置文件并用作开发配置文件。 189 | 190 | ```sh 191 | cp .env.example .env 192 | vim .env 193 | ``` 194 | 195 | 如果你维护了多个插件,可以将这些内容存入系统环境变量,以避免在每个插件中都需要重复设置。 196 | 197 | 3. 运行 `npm install` 以安装相关依赖 198 | 199 | > 如果你使用 `pnpm` 作为包管理器,你需要添加 `public-hoist-pattern[]=*@types/bluebird*` 到`.npmrc`, 详情请查看 [zotero-types](https://github.com/windingwind/zotero-types?tab=readme-ov-file#usage) 的文档. 200 | 201 | 如果你使用 `npm install` 的过程中遇到了 `npm ERR! ERESOLVE unable to resolve dependency tree` ,这是由于上游依赖 typescript-eslint 导致的错误,请使用 `npm i -f` 命令进行安装。 202 | 203 | ### 3 开发插件 204 | 205 | 使用 `npm start` 启动开发服务器,它将: 206 | 207 | - 在开发模式下预构建插件 208 | - 启动 Zotero ,并让其从 `build/` 中加载插件 209 | - 打开开发者工具(devtool) 210 | - 监听 `src/**` 和 `addon/**`. 211 | - 如果 `src/**` 修改了,运行 esbuild 并且重新加载 212 | - 如果 `addon/**` 修改了,(在开发模式下)重新构建插件并且重新加载 213 | 214 | #### 自动热重载 215 | 216 | 厌倦了无休止的重启吗?忘掉它,拥抱热加载! 217 | 218 | 1. 运行 `npm start`. 219 | 2. 编码. (是的,就这么简单) 220 | 221 | 当检测到 `src` 或 `addon` 中的文件修改时,插件将自动编译并重新加载. 222 | 223 |
224 | 💡 将此功能添加到现有插件的步骤 225 | 226 | 请参阅:[zotero-plugin-scaffold](https://github.com/northword/zotero-plugin-scaffold)。 227 | 228 |
229 | 230 | #### 调试代码 231 | 232 | 你还可以: 233 | 234 | - 在 Tools->Developer->Run Javascript 中测试代码片段; 235 | 236 | - 使用 `Zotero.debug()` 调试输出. 在 Help->Debug Output Logging->View Output 查看输出; 237 | 238 | - 调试 UI. Zotero 建立在 Firefox XUL 框架之上. 使用 [XUL Explorer](https://udn.realityripple.com/docs/Archive/Mozilla/XUL_Explorer) 等软件调试 XUL UI. 239 | 240 | > XUL 文档: 241 | 242 | ### 4 构建插件 243 | 244 | 运行 `npm run build` 在生产模式下构建插件,构建的结果位于 `build/` 目录中. 245 | 246 | 构建步骤: 247 | 248 | - 创建/清空 `build/` 249 | - 复制 `addon/**` 到 `build/addon/**` 250 | - 替换占位符:使用 `replace-in-file` 去替换在 `package.json` 中定义的关键字和配置 (`xhtml`、`.flt` 等) 251 | - 准备本地化文件以避免冲突,查看官方文档了解更多( 252 | - 重命名`**/*.flt` 为 `**/${addonRef}-*.flt` 253 | - 在每个消息前加上 `addonRef-` 254 | - 使用 Esbuild 来将 `.ts` 源码构建为 `.js`,从 `src/index.ts` 构建到`./build/addon/chrome/content/scripts` 255 | - (仅在生产模式下工作) 压缩 `./build/addon` 目录为 `./build/*.xpi` 256 | - (仅在生产模式下工作) 准备 `update.json` 或 `update-beta.json` 257 | 258 | > [!note] 259 | > 260 | > **Dev & prod 两者有什么区别?** 261 | > 262 | > - 此环境变量存储在 `Zotero.${addonInstance}.data.env` 中,控制台输出在生产模式下被禁用. 263 | > - 你可以根据此变量决定用户无法查看/使用的内容. 264 | > - 在生产模式下,构建脚本将自动打包插件并更新 `update.json`. 265 | 266 | ### 5 发布 267 | 268 | 如果要构建和发布插件,运行如下指令: 269 | 270 | ```shell 271 | # version increase, git add, commit and push 272 | # then on ci, npm run build, and release to GitHub 273 | npm run release 274 | ``` 275 | 276 | > [!note] 277 | > 在此模板中,release-it 被配置为在本地更新版本号、提交并推送标签,随后 GitHub Action 将重新构建插件并将 XPI 发布到 GitHub Release. 278 | 279 | #### 关于预发布 280 | 281 | 该模板将 `prerelease` 定义为插件的测试版,当你在 release-it 中选择 `prerelease` 版本 (版本号中带有 `-` ),构建脚本将创建一个 `update-beta.json` 给预发布版本使用,这将确保常规版本的用户不会自动更新到测试版,只有手动下载并安装了测试版的用户才能自动更新到下一个测试版. 当下一个正式版本更新时,脚本将同步更新 `update.json` 和 `update-beta.json`,这将使正式版和测试版用户都可以更新到最新的正式版. 282 | 283 | > [!warning] 284 | > 严格来说,区分 Zotero 6 和 Zotero 7 兼容的插件版本应该通过 `update.json` 的 `addons.__addonID__.updates[]` 中分别配置 `applications.zotero.strict_min_version`,这样 Zotero 才能正确识别,详情在 Zotero 7 开发文档(. 285 | 286 | ## Details 更多细节 287 | 288 | ### 关于Hooks(About Hooks) 289 | 290 | > 可以在 [`src/hooks.ts`](https://github.com/windingwind/zotero-plugin-template/blob/main/src/hooks.ts) 中查看更多 291 | 292 | 1. 当在 Zotero 中触发安装/启用/启动时,`bootstrap.js` > `startup` 被调用 293 | - 等待 Zotero 就绪 294 | - 加载 `index.js` (插件代码的主入口,从 `index.ts` 中构建) 295 | - 如果是 Zotero 7 以上的版本则注册资源 296 | 2. 主入口 `index.js` 中,插件对象被注入到 `Zotero` ,并且 `hooks.ts` > `onStartup` 被调用. 297 | - 初始化插件需要的资源,包括通知监听器、首选项面板和UI元素. 298 | 3. 当在 Zotero 中触发卸载/禁用时,`bootstrap.js` > `shutdown` 被调用. 299 | - `events.ts` > `onShutdown` 被调用. 移除 UI 元素、首选项面板或插件创建的任何内容. 300 | - 移除脚本并释放资源. 301 | 302 | ### 关于全局变量(About Global Variables) 303 | 304 | > 可以在 [`src/index.ts`](https://github.com/windingwind/zotero-plugin-template/blob/main/src/index.ts)中查看更多 305 | 306 | bootstrap插件在沙盒中运行,但沙盒中没有默认的全局变量,例如 `Zotero` 或 `window` 等我们曾在overlay插件环境中使用的变量. 307 | 308 | 此模板将以下变量注册到全局范围: 309 | 310 | ```ts 311 | Zotero, ZoteroPane, Zotero_Tabs, window, document, rootURI, ztoolkit, addon; 312 | ``` 313 | 314 | ### 创建元素 API(Create Elements API) 315 | 316 | 插件模板为 bootstrap 插件提供了一些新的API. 我们有两个原因使用这些 API,而不是使用 `createElement/createElementNS`: 317 | 318 | - 在 bootstrap 模式下,插件必须在推出(禁用或卸载)时清理所有 UI 元素,这非常麻烦. 使用 `createElement`,插件模板将维护这些元素. 仅仅在退出时 `unregisterAll` . 319 | - Zotero 7 需要 createElement()/createElementNS() → createXULElement() 来表示其他的 XUL 元素,而 Zotero 6 并不支持 `createXULElement`. 类似于 React.createElement 的API `createElement` 检测 namespace(xul/html/svg) 并且自动创建元素,返回元素为对应的 TypeScript 元素类型. 320 | 321 | ```ts 322 | createElement(document, "div"); // returns HTMLDivElement 323 | createElement(document, "hbox"); // returns XUL.Box 324 | createElement(document, "button", { namespace: "xul" }); // manually set namespace. returns XUL.Button 325 | ``` 326 | 327 | ### 关于 Zotero API(About Zotero API) 328 | 329 | Zotero 文档已过时且不完整,克隆 并全局搜索关键字. 330 | 331 | > ⭐[zotero-types](https://github.com/windingwind/zotero-types) 提供了最常用的 Zotero API,在默认情况下它被包含在此模板中. 你的 IDE 将为大多数的 API 提供提醒. 332 | 333 | 猜你需要:查找所需 API的技巧 334 | 335 | 在 `.xhtml`/`.flt` 文件中搜索 UI 标签,然后在 locale 文件中找到对应的键. ,然后在 `.js`/`.jsx` 文件中搜索此键. 336 | 337 | ### 目录结构(Directory Structure) 338 | 339 | 本部分展示了模板的目录结构. 340 | 341 | - 所有的 `.js/.ts` 代码都在 `./src`; 342 | - 插件配置文件:`./addon/manifest.json`; 343 | - UI 文件: `./addon/chrome/content/*.xhtml`. 344 | - 区域设置文件: `./addon/locale/**/*.flt`; 345 | - 首选项文件: `./addon/prefs.js`; 346 | > 不要在 `prefs.js` 中换行 347 | 348 | ```shell 349 | . 350 | |-- .eslintrc.json # eslint conf 351 | |-- .gitattributes # git conf 352 | |-- .github/ # github conf 353 | |-- .gitignore # git conf 354 | |-- .prettierrc # prettier conf 355 | |-- .release-it.json # release-it conf 356 | |-- .vscode # vs code conf 357 | | |-- extensions.json 358 | | |-- launch.json 359 | | |-- setting.json 360 | | `-- toolkit.code-snippets 361 | |-- package-lock.json # npm conf 362 | |-- package.json # npm conf 363 | |-- LICENSE 364 | |-- README.md 365 | |-- addon 366 | | |-- bootstrap.js # addon load/unload script, like a main.c 367 | | |-- chrome 368 | | | `-- content 369 | | | |-- icons/ 370 | | | |-- preferences.xhtml # preference panel 371 | | | `-- zoteroPane.css 372 | | |-- locale # locale 373 | | | |-- en-US 374 | | | | |-- addon.ftl 375 | | | | `-- preferences.ftl 376 | | | `-- zh-CN 377 | | | |-- addon.ftl 378 | | | `-- preferences.ftl 379 | | |-- manifest.json # addon config 380 | | `-- prefs.js 381 | |-- build/ # build dir 382 | |-- scripts # scripts for dev 383 | | |-- build.mjs # script to build plugin 384 | | |-- scripts.mjs # scripts send to Zotero, such as reload, openDevTool, etc 385 | | |-- server.mjs # script to start a development server 386 | | |-- start.mjs # script to start Zotero process 387 | | |-- stop.mjs # script to kill Zotero process 388 | | |-- utils.mjs # utils functions for dev scripts 389 | | |-- update-template.json # template of `update.json` 390 | | `-- zotero-cmd-template.json # template of local env 391 | |-- src # source code 392 | | |-- addon.ts # base class 393 | | |-- hooks.ts # lifecycle hooks 394 | | |-- index.ts # main entry 395 | | |-- modules # sub modules 396 | | | |-- examples.ts 397 | | | `-- preferenceScript.ts 398 | | `-- utils # utilities 399 | | |-- locale.ts 400 | | |-- prefs.ts 401 | | |-- wait.ts 402 | | `-- window.ts 403 | |-- tsconfig.json # https://code.visualstudio.com/docs/languages/jsconfig 404 | |-- typings # ts typings 405 | | `-- global.d.ts 406 | `-- update.json 407 | ``` 408 | 409 | ## Disclaimer 免责声明 410 | 411 | 在 AGPL 下使用此代码. 不提供任何保证. 遵守你所在地区的法律! 412 | 413 | 如果你想更改许可,请通过 与我联系. 414 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /src/modules/main.ts: -------------------------------------------------------------------------------- 1 | import { config } from "../../package.json"; 2 | import { getLocaleID, getString } from "../utils/locale"; 3 | import { getPref } from "../utils/prefs"; 4 | 5 | // Chat session types 6 | interface ChatMessage { 7 | role: 'user' | 'assistant' | 'system'; 8 | content: string; 9 | timestamp?: number; 10 | } 11 | 12 | interface ChatSession { 13 | messages: ChatMessage[]; 14 | pdfAttached: boolean; 15 | pdfContent?: string; 16 | } 17 | 18 | // Global chat sessions manager using WeakMap 19 | const chatSessions = new WeakMap(); 20 | 21 | // Helper function to get or create chat session 22 | function getChatSession(item: Zotero.Item): ChatSession { 23 | if (!chatSessions.has(item)) { 24 | chatSessions.set(item, { 25 | messages: [], 26 | pdfAttached: false, 27 | pdfContent: undefined 28 | }); 29 | } 30 | return chatSessions.get(item)!; 31 | } 32 | 33 | function example( 34 | target: any, 35 | propertyKey: string | symbol, 36 | descriptor: PropertyDescriptor, 37 | ) { 38 | const original = descriptor.value; 39 | descriptor.value = function (...args: any) { 40 | try { 41 | ztoolkit.log(`Calling example ${target.name}.${String(propertyKey)}`); 42 | return original.apply(this, args); 43 | } catch (e) { 44 | ztoolkit.log(`Error in example ${target.name}.${String(propertyKey)}`, e); 45 | throw e; 46 | } 47 | }; 48 | return descriptor; 49 | } 50 | 51 | export class BasicExampleFactory { 52 | @example 53 | static registerNotifier() { 54 | const callback = { 55 | notify: async ( 56 | event: string, 57 | type: string, 58 | ids: number[] | string[], 59 | extraData: { [key: string]: any }, 60 | ) => { 61 | if (!addon?.data.alive) { 62 | this.unregisterNotifier(notifierID); 63 | return; 64 | } 65 | addon.hooks.onNotify(event, type, ids, extraData); 66 | }, 67 | }; 68 | 69 | // Register the callback in Zotero as an item observer 70 | const notifierID = Zotero.Notifier.registerObserver(callback, [ 71 | "tab", 72 | "item", 73 | "file", 74 | ]); 75 | 76 | Zotero.Plugins.addObserver({ 77 | shutdown: ({ id: pluginID }) => { 78 | this.unregisterNotifier(notifierID); 79 | }, 80 | }); 81 | } 82 | 83 | @example 84 | static exampleNotifierCallback() { 85 | new ztoolkit.ProgressWindow(config.addonName) 86 | .createLine({ 87 | text: "Open Tab Detected!", 88 | type: "success", 89 | progress: 100, 90 | }) 91 | .show(); 92 | } 93 | 94 | @example 95 | private static unregisterNotifier(notifierID: string) { 96 | Zotero.Notifier.unregisterObserver(notifierID); 97 | } 98 | 99 | @example 100 | static registerPrefs() { 101 | Zotero.PreferencePanes.register({ 102 | pluginID: config.addonID, 103 | src: rootURI + "chrome/content/preferences.xhtml", 104 | label: getString("prefs-title"), 105 | image: `chrome://${config.addonRef}/content/icons/favicon.png`, 106 | }); 107 | } 108 | } 109 | 110 | export class KeyExampleFactory { 111 | @example 112 | static registerShortcuts() { 113 | // Register an event key for Alt+L 114 | ztoolkit.Keyboard.register((ev, keyOptions) => { 115 | ztoolkit.log(ev, keyOptions.keyboard); 116 | if (keyOptions.keyboard?.equals("shift,l")) { 117 | addon.hooks.onShortcuts("larger"); 118 | } 119 | if (ev.shiftKey && ev.key === "S") { 120 | addon.hooks.onShortcuts("smaller"); 121 | } 122 | }); 123 | 124 | new ztoolkit.ProgressWindow(config.addonName) 125 | .createLine({ 126 | text: "Example Shortcuts: Alt+L/S/C", 127 | type: "success", 128 | }) 129 | .show(); 130 | } 131 | 132 | @example 133 | static exampleShortcutLargerCallback() { 134 | new ztoolkit.ProgressWindow(config.addonName) 135 | .createLine({ 136 | text: "Larger!", 137 | type: "default", 138 | }) 139 | .show(); 140 | } 141 | 142 | @example 143 | static exampleShortcutSmallerCallback() { 144 | new ztoolkit.ProgressWindow(config.addonName) 145 | .createLine({ 146 | text: "Smaller!", 147 | type: "default", 148 | }) 149 | .show(); 150 | } 151 | } 152 | 153 | export class UIExampleFactory { 154 | @example 155 | static registerStyleSheet(win: Window) { 156 | const doc = win.document; 157 | const styles = ztoolkit.UI.createElement(doc, "link", { 158 | properties: { 159 | type: "text/css", 160 | rel: "stylesheet", 161 | href: `chrome://${config.addonRef}/content/zoteroPane.css`, 162 | }, 163 | }); 164 | doc.documentElement.appendChild(styles); 165 | // doc.getElementById("zotero-item-pane-content")?.classList.add("makeItRed"); 166 | } 167 | 168 | @example 169 | static registerRightClickMenuItem() { 170 | const menuIcon = `chrome://${config.addonRef}/content/icons/favicon@0.5x.png`; 171 | 172 | // item menuitem with icon 173 | ztoolkit.Menu.register("item", { 174 | tag: "menuitem", 175 | id: "zotero-itemmenu-addontemplate-test", 176 | label: getString("menuitem-label"), 177 | commandListener: (ev) => addon.hooks.onDialogEvents("dialogExample"), 178 | icon: menuIcon, 179 | }); 180 | } 181 | 182 | 183 | 184 | @example 185 | static registerWindowMenuWithSeparator() { 186 | ztoolkit.Menu.register("menuFile", { 187 | tag: "menuseparator", 188 | }); 189 | // menu->File menuitem 190 | ztoolkit.Menu.register("menuFile", { 191 | tag: "menuitem", 192 | label: getString("menuitem-filemenulabel"), 193 | oncommand: "alert('Hello World! File Menuitem.')", 194 | }); 195 | } 196 | 197 | @example 198 | static async registerExtraColumn() { 199 | const field = "test1"; 200 | await Zotero.ItemTreeManager.registerColumns({ 201 | pluginID: config.addonID, 202 | dataKey: field, 203 | label: "text column", 204 | dataProvider: (item: Zotero.Item, dataKey: string) => { 205 | return field + String(item.id); 206 | }, 207 | iconPath: "chrome://zotero/skin/cross.png", 208 | }); 209 | } 210 | 211 | @example 212 | static async registerExtraColumnWithCustomCell() { 213 | const field = "test2"; 214 | await Zotero.ItemTreeManager.registerColumns({ 215 | pluginID: config.addonID, 216 | dataKey: field, 217 | label: "custom column", 218 | dataProvider: (item: Zotero.Item, dataKey: string) => { 219 | return field + String(item.id); 220 | }, 221 | renderCell(index, data, column) { 222 | ztoolkit.log("Custom column cell is rendered!"); 223 | const span = Zotero.getMainWindow().document.createElementNS( 224 | "http://www.w3.org/1999/xhtml", 225 | "span", 226 | ); 227 | span.className = `cell ${column.className}`; 228 | span.style.background = "#0dd068"; 229 | span.innerText = "⭐" + data; 230 | return span; 231 | }, 232 | }); 233 | } 234 | 235 | @example 236 | static registerItemPaneSection() { 237 | Zotero.ItemPaneManager.registerSection({ 238 | paneID: "example", 239 | pluginID: config.addonID, 240 | header: { 241 | l10nID: getLocaleID("item-section-example1-head-text"), 242 | icon: `chrome://${config.addonRef}/content/icons/favicon@0.5x.png`, 243 | }, 244 | bodyXHTML: 'Clear+Title+AbsgetBib Asktranslate ', 245 | sidenav: { 246 | l10nID: getLocaleID("item-section-example1-sidenav-tooltip"), 247 | icon: `chrome://${config.addonRef}/content/icons/favicon@0.5x.png`, 248 | }, 249 | onRender: ({ body, item, editable, tabType }) => { 250 | 251 | 252 | 253 | 254 | 255 | }, 256 | }); 257 | } 258 | 259 | @example 260 | static async registerReaderItemPaneSection(win: Window) { 261 | const doc = win.document; 262 | Zotero.ItemPaneManager.registerSection({ 263 | paneID: "reader-example", 264 | pluginID: config.addonID, 265 | header: { 266 | l10nID: getLocaleID("item-section-example2-head-text"), 267 | icon: `chrome://${config.addonRef}/content/icons/favicon@0.5x.png`, 268 | }, 269 | sidenav: { 270 | l10nID: getLocaleID("item-section-example2-sidenav-tooltip"), 271 | icon: `chrome://${config.addonRef}/content/icons/favicon@0.5x.png`, 272 | }, 273 | bodyXHTML: ` 274 | 275 | 276 | 277 | 💬 278 | Start a conversation with ChatGPT 279 | 280 | 281 | 282 | 283 | 284 | 附加 PDF 内容 285 | 286 | 287 | 288 | 289 | 290 | 296 | Send 302 | 303 | 304 | 305 | `, 306 | // Optional, Called when the section is first created, must be synchronous 307 | onInit: ({ item }) => { 308 | ztoolkit.log("Section init!", item?.id); 309 | }, 310 | // Optional, Called when the section is destroyed, must be synchronous 311 | onDestroy: (props) => { 312 | ztoolkit.log("Section destroy!"); 313 | }, 314 | // Optional, Called when the section data changes (setting item/mode/tabType/inTrash), must be synchronous. return false to cancel the change 315 | onItemChange: ({ item, setEnabled, tabType }) => { 316 | ztoolkit.log(`Section item data changed to ${item?.id}`); 317 | setEnabled(tabType === "reader"); 318 | return true; 319 | }, 320 | 321 | onRender: ({ 322 | body, 323 | item, 324 | setL10nArgs, 325 | setSectionSummary, 326 | setSectionButtonStatus, 327 | }) => { 328 | 329 | }, 330 | 331 | onAsyncRender: async ({ 332 | body, 333 | item, 334 | setL10nArgs, 335 | setSectionSummary, 336 | setSectionButtonStatus, 337 | }) => { 338 | // Get DOM elements 339 | const chatHistory = body.querySelector("#chat-history") as HTMLElement; 340 | const messageInput = body.querySelector("#message-input") as HTMLTextAreaElement; 341 | const sendButton = body.querySelector("#send-button") as HTMLButtonElement; 342 | const attachPdfCheckbox = body.querySelector("#attach-pdf") as HTMLInputElement; 343 | const pdfStatus = body.querySelector("#pdf-status") as HTMLElement; 344 | 345 | // Get API credentials 346 | const OPENAI_API_KEY = getPref('input') as string; 347 | const apiUrl = getPref('base') as string; 348 | const model = getPref('model') as string; 349 | 350 | // Get or create chat session for this item 351 | const session = getChatSession(item); 352 | 353 | // Check if PDF is available 354 | const hasPdf = await checkPdfAvailability(item); 355 | if (!hasPdf) { 356 | attachPdfCheckbox.disabled = true; 357 | pdfStatus.textContent = getString("chat-attach-pdf-no-pdf"); 358 | pdfStatus.className = "pdf-status"; 359 | } else if (session.pdfAttached) { 360 | pdfStatus.textContent = `✓ ${getString("chat-attach-pdf-attached")}`; 361 | pdfStatus.className = "pdf-status attached"; 362 | } 363 | 364 | // Helper: Check PDF availability 365 | async function checkPdfAvailability(item: Zotero.Item): Promise { 366 | try { 367 | const attachments = await item.getAttachments(); 368 | for (const attachmentID of attachments) { 369 | const attachment = await Zotero.Items.getAsync(attachmentID); 370 | if (attachment.attachmentContentType === 'application/pdf') { 371 | return true; 372 | } 373 | } 374 | return false; 375 | } catch (error) { 376 | return false; 377 | } 378 | } 379 | 380 | // Helper: Get PDF content 381 | async function getPdfContent(item: Zotero.Item): Promise { 382 | try { 383 | const attachments = await item.getAttachments(); 384 | for (const attachmentID of attachments) { 385 | const attachment = await Zotero.Items.getAsync(attachmentID); 386 | if (attachment.attachmentContentType === 'application/pdf') { 387 | return await attachment.attachmentText; 388 | } 389 | } 390 | return null; 391 | } catch (error) { 392 | ztoolkit.log("Error getting PDF content:", error); 393 | return null; 394 | } 395 | } 396 | 397 | // Helper: Render user message 398 | function renderUserMessage(content: string) { 399 | // Remove empty state if exists 400 | const emptyState = chatHistory.querySelector('#empty-state'); 401 | if (emptyState) { 402 | emptyState.remove(); 403 | } 404 | 405 | const wrapper = body.ownerDocument.createElement('div'); 406 | wrapper.setAttribute('style', 'display:block;margin:8px 0;text-align:right;'); 407 | 408 | const bubble = body.ownerDocument.createElement('div'); 409 | bubble.setAttribute('style', 'display:inline-block;max-width:70%;overflow-y:auto;overflow-x:auto;background:#0084ff;color:#fff;padding:10px 14px;border-radius:12px;text-align:left;word-wrap:break-word;white-space:pre-wrap;'); 410 | 411 | bubble.textContent = content; 412 | wrapper.appendChild(bubble); 413 | chatHistory.appendChild(wrapper); 414 | 415 | scrollToBottom(); 416 | } 417 | 418 | // Helper: Create AI message element 419 | function createAssistantMessageElement(): { content: HTMLElement, copyBtn: HTMLElement } { 420 | const wrapper = body.ownerDocument.createElement('div'); 421 | wrapper.setAttribute('style', 'display:block;margin:8px 0;text-align:left;'); 422 | 423 | const bubble = body.ownerDocument.createElement('div'); 424 | bubble.setAttribute('style', 'position:relative;display:inline-block;max-width:70%;overflow-y:auto;overflow-x:auto;background:#e4e6eb;color:#333;padding:10px 14px 10px 14px;border-radius:12px;word-wrap:break-word;white-space:pre-wrap;'); 425 | 426 | const content = body.ownerDocument.createElement('div'); 427 | content.setAttribute('style', 'padding-right:30px;'); 428 | 429 | const copyBtn = body.ownerDocument.createElement('button'); 430 | copyBtn.textContent = '📋'; 431 | copyBtn.setAttribute('title', 'Copy'); 432 | copyBtn.setAttribute('style', 'display:none;position:absolute;right:4px;bottom:4px;background:rgba(255,255,255,0.8);border:1px solid #ccc;border-radius:4px;padding:2px 6px;cursor:pointer;font-size:14px;opacity:0.6;transition:opacity 0.2s;'); 433 | 434 | copyBtn.addEventListener('mouseenter', () => { 435 | copyBtn.style.opacity = '1'; 436 | }); 437 | 438 | copyBtn.addEventListener('mouseleave', () => { 439 | copyBtn.style.opacity = '0.6'; 440 | }); 441 | 442 | copyBtn.addEventListener('click', () => { 443 | const textContent = content.textContent || ''; 444 | try { 445 | // Use Zotero toolkit clipboard 446 | new ztoolkit.Clipboard() 447 | .addText(textContent, "text/unicode") 448 | .copy(); 449 | copyBtn.textContent = '✓'; 450 | setTimeout(() => { 451 | copyBtn.textContent = '📋'; 452 | }, 2000); 453 | } catch (error) { 454 | ztoolkit.log("Copy failed:", error); 455 | copyBtn.textContent = '✗'; 456 | setTimeout(() => { 457 | copyBtn.textContent = '📋'; 458 | }, 2000); 459 | } 460 | }); 461 | 462 | bubble.appendChild(content); 463 | bubble.appendChild(copyBtn); 464 | wrapper.appendChild(bubble); 465 | chatHistory.appendChild(wrapper); 466 | 467 | scrollToBottom(); 468 | return { content, copyBtn }; 469 | } 470 | 471 | // Helper: Simple markdown to HTML converter 472 | function markdownToHtml(markdown: string): string { 473 | let html = markdown; 474 | 475 | // Code blocks (```language\ncode\n```) 476 | html = html.replace(/```(\w+)?\n([\s\S]*?)```/g, (match, lang, code) => { 477 | return `
${escapeHtml(code.trim())}
`; 478 | }); 479 | 480 | // Inline code (`code`) 481 | html = html.replace(/`([^`]+)`/g, '$1'); 482 | 483 | // Bold (**text** or __text__) 484 | html = html.replace(/\*\*(.+?)\*\*/g, '$1'); 485 | html = html.replace(/__(.+?)__/g, '$1'); 486 | 487 | // Italic (*text* or _text_) 488 | html = html.replace(/\*(.+?)\*/g, '$1'); 489 | html = html.replace(/_(.+?)_/g, '$1'); 490 | 491 | // Headers 492 | html = html.replace(/^### (.+)$/gm, '

$1

'); 493 | html = html.replace(/^## (.+)$/gm, '

$1

'); 494 | html = html.replace(/^# (.+)$/gm, '

$1

'); 495 | 496 | // Lists (- item) 497 | html = html.replace(/^- (.+)$/gm, '
  • $1
  • '); 498 | html = html.replace(/(\n?)+/g, '
      $&
    '); 499 | 500 | // Numbered lists (1. item) 501 | html = html.replace(/^\d+\.\s(.+)$/gm, '
  • $1
  • '); 502 | 503 | // Links [text](url) 504 | html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '$1'); 505 | 506 | // Line breaks 507 | html = html.replace(/\n/g, '
    '); 508 | 509 | return html; 510 | } 511 | 512 | // Helper: Escape HTML 513 | function escapeHtml(text: string): string { 514 | const div = body.ownerDocument.createElement('div'); 515 | div.textContent = text; 516 | return div.innerHTML; 517 | } 518 | 519 | // Helper: Update message content with markdown rendering 520 | function updateMessageContent(messageObj: { content: HTMLElement, copyBtn: HTMLElement }, content: string) { 521 | messageObj.content.innerHTML = markdownToHtml(content); 522 | scrollToBottom(); 523 | } 524 | 525 | // Helper: Show copy button 526 | function showCopyButton(copyBtn: HTMLElement) { 527 | copyBtn.style.display = 'block'; 528 | } 529 | 530 | // Helper: Scroll to bottom 531 | function scrollToBottom() { 532 | chatHistory.scrollTop = chatHistory.scrollHeight; 533 | } 534 | 535 | // Helper: Show error message 536 | function showError(message: string) { 537 | const wrapper = body.ownerDocument.createElement('div'); 538 | wrapper.setAttribute('style', 'display:block;margin:8px 0;text-align:center;'); 539 | 540 | const bubble = body.ownerDocument.createElement('div'); 541 | bubble.setAttribute('style', 'display:inline-block;background:#ff4444;color:#fff;padding:8px 12px;border-radius:6px;font-size:13px;'); 542 | bubble.textContent = `⚠️ ${message}`; 543 | 544 | wrapper.appendChild(bubble); 545 | chatHistory.appendChild(wrapper); 546 | 547 | scrollToBottom(); 548 | } 549 | 550 | // Main: Send message function 551 | async function sendMessage() { 552 | const userMessage = messageInput.value.trim(); 553 | if (!userMessage) return; 554 | 555 | // Validate API settings 556 | if (!OPENAI_API_KEY || !apiUrl) { 557 | showError(getString("chat-error-no-api-key")); 558 | return; 559 | } 560 | 561 | // Disable inputs 562 | sendButton.disabled = true; 563 | messageInput.disabled = true; 564 | const originalButtonText = sendButton.innerHTML; 565 | sendButton.innerHTML = '...'; 566 | 567 | try { 568 | // Render user message 569 | renderUserMessage(userMessage); 570 | 571 | // Prepare message content 572 | let finalContent = userMessage; 573 | 574 | // Handle PDF attachment 575 | if (attachPdfCheckbox.checked && !session.pdfAttached) { 576 | if (!session.pdfContent) { 577 | const pdfContent = await getPdfContent(item); 578 | session.pdfContent = pdfContent || undefined; 579 | } 580 | if (session.pdfContent) { 581 | finalContent += "\n\nPDF Content:\n" + session.pdfContent; 582 | session.pdfAttached = true; 583 | pdfStatus.textContent = `✓ ${getString("chat-attach-pdf-attached")}`; 584 | pdfStatus.className = "pdf-status attached"; 585 | } else { 586 | showError(getString("chat-error-no-pdf")); 587 | } 588 | } 589 | 590 | // Add user message to history 591 | session.messages.push({ 592 | role: 'user', 593 | content: finalContent, 594 | timestamp: Date.now() 595 | }); 596 | 597 | // Build API messages 598 | const systemPrompt = 'You are a research assistant.'; 599 | const apiMessages = [ 600 | { role: 'system', content: systemPrompt }, 601 | ...session.messages.map(msg => ({ 602 | role: msg.role, 603 | content: msg.content 604 | })) 605 | ]; 606 | 607 | // Create AI message element 608 | const aiMessageObj = createAssistantMessageElement(); 609 | let assistantContent = ''; 610 | 611 | // Call API with streaming 612 | const response = await fetch(`${apiUrl}/chat/completions`, { 613 | method: 'POST', 614 | headers: { 615 | 'Authorization': `Bearer ${OPENAI_API_KEY}`, 616 | 'Content-Type': 'application/json', 617 | }, 618 | body: JSON.stringify({ 619 | model: model, 620 | messages: apiMessages, 621 | stream: true, 622 | }), 623 | }); 624 | 625 | if (!response.ok) { 626 | throw new Error(`${response.status} ${response.statusText}`); 627 | } 628 | 629 | // Process streaming response 630 | const reader = response.body?.getReader(); 631 | const decoder = new TextDecoder(); 632 | 633 | while (true) { 634 | const { done, value } = await reader!.read(); 635 | if (done) break; 636 | 637 | const chunk = decoder.decode(value, { stream: true }); 638 | const lines = chunk.split('\n').filter(line => line.trim() !== ''); 639 | 640 | for (let line of lines) { 641 | try { 642 | line = line.replace(/^data:\s*/, ''); 643 | if (line === '[DONE]') continue; 644 | 645 | const data = JSON.parse(line); 646 | const content = data.choices?.[0]?.delta?.content || ''; 647 | 648 | if (content) { 649 | assistantContent += content; 650 | updateMessageContent(aiMessageObj, assistantContent); 651 | } 652 | } catch (error) { 653 | // Ignore JSON parse errors for incomplete chunks 654 | } 655 | } 656 | } 657 | 658 | // Add assistant message to history 659 | if (assistantContent) { 660 | session.messages.push({ 661 | role: 'assistant', 662 | content: assistantContent, 663 | timestamp: Date.now() 664 | }); 665 | // Show copy button after completion 666 | showCopyButton(aiMessageObj.copyBtn); 667 | } 668 | 669 | // Clear input 670 | messageInput.value = ''; 671 | messageInput.style.height = 'auto'; 672 | 673 | } catch (error) { 674 | ztoolkit.log("Error sending message:", error); 675 | showError(getString("chat-error-api") + `: ${error}`); 676 | } finally { 677 | // Re-enable inputs 678 | sendButton.disabled = false; 679 | messageInput.disabled = false; 680 | sendButton.innerHTML = originalButtonText; 681 | messageInput.focus(); 682 | } 683 | } 684 | 685 | // Auto-resize textarea 686 | messageInput.addEventListener('input', () => { 687 | messageInput.style.height = 'auto'; 688 | messageInput.style.height = Math.min(messageInput.scrollHeight, 120) + 'px'; 689 | }); 690 | 691 | // Send on Enter, new line on Shift+Enter 692 | messageInput.addEventListener('keydown', (e) => { 693 | if (e.key === 'Enter' && !e.shiftKey) { 694 | e.preventDefault(); 695 | sendButton.click(); 696 | } 697 | }); 698 | 699 | // Send button click 700 | sendButton.addEventListener('click', sendMessage); 701 | 702 | // Restore chat history if exists 703 | if (session.messages.length > 0) { 704 | // Remove empty state 705 | const emptyState = chatHistory.querySelector('.chat-empty-state'); 706 | if (emptyState) { 707 | emptyState.remove(); 708 | } 709 | 710 | // Render existing messages (without PDF content in display) 711 | for (const msg of session.messages) { 712 | if (msg.role === 'user') { 713 | // Display user message without PDF content 714 | const displayContent = msg.content.split('\n\nPDF Content:\n')[0]; 715 | renderUserMessage(displayContent); 716 | } else if (msg.role === 'assistant') { 717 | const aiMessageObj = createAssistantMessageElement(); 718 | updateMessageContent(aiMessageObj, msg.content); 719 | showCopyButton(aiMessageObj.copyBtn); 720 | } 721 | } 722 | } 723 | }, 724 | // Optional, Called when the section is toggled. Can happen anytime even if the section is not visible or not rendered 725 | onToggle: ({ item }) => { 726 | ztoolkit.log("Section toggled!", item?.id); 727 | }, 728 | 729 | }); 730 | } 731 | } 732 | 733 | 734 | 735 | export class HelperExampleFactory { 736 | @example 737 | static async dialogExample() { 738 | const items = ztoolkit.getGlobal("ZoteroPane").getSelectedItems(); 739 | var pTitle = ''; 740 | var pTitleH = ''; 741 | var Review_text = ''; 742 | var topic = ''; 743 | 744 | for (var i in items) { 745 | if (items[i].getField("abstractNote") as string == 'Topic') { 746 | topic = items[i].getField("title") as string; 747 | continue; 748 | } 749 | 750 | 751 | var title = 'title: ' + items[i].getField("title") as string; 752 | var abstract = 'abstract: ' + items[i].getField("abstractNote") as string; 753 | var authors = items[i].getCreators(); 754 | var authorss = []; 755 | for (var j in authors) { 756 | authorss.push(authors[j].firstName + ' ' + authors[j].lastName); 757 | } 758 | 759 | 760 | pTitleH += items[i].getField("title") as string + '\n'; 761 | pTitle += 'Paper' + i + ':\n' + title + '\n' + 'authors:' + authorss.join() + '\n' + 'year:' + items[i].getField("date") as string + '\n' + abstract + '\n\n'; 762 | 763 | // var url = 'https://dblp.uni-trier.de/search/publ/api?q=' + items[i].getField("title") + '&format=bib' 764 | // const response = await fetch(url); 765 | // if (!response.ok) { 766 | // throw new Error('Network response was not ok'); 767 | // } else { 768 | 769 | // var data = await response.text(); 770 | // // pTitle += '' + items[i].getField("title") + '\n\n'; 771 | // pTitleH += '' + items[i].getField("title") + '
    '; 772 | // pTitle+='' + data + '\n'+'\n'+abstract+'\n'; 773 | 774 | // } 775 | 776 | 777 | 778 | // const attachments = await items[i].getAttachments(); 779 | 780 | // let pdfAttachment = null; 781 | // let pdfPath_content = null; 782 | 783 | // for (const attachmentID of attachments) { 784 | // const attachment = await Zotero.Items.getAsync(attachmentID); 785 | // if (attachment.attachmentContentType === 'application/pdf') { 786 | // pdfAttachment = attachment; 787 | // pdfPath_content = await attachment.attachmentText; 788 | // pTitleH=pdfPath_content.substring(0,100); 789 | // break; 790 | // } 791 | // } 792 | 793 | } 794 | 795 | const OPENAI_API_KEY = getPref('input') as string; 796 | const apiUrl = getPref('base') as string; 797 | const model = getPref('model') as string; 798 | 799 | 800 | 801 | if (!OPENAI_API_KEY || !apiUrl || !topic) { 802 | Review_text = 'API key or base URL is null,topic is empty, please set them in settings.'; 803 | } 804 | 805 | 806 | 807 | // var user_qtxt = uquery.value; 808 | 809 | // if (ask_pdf.checked == true) { 810 | // const attachments = await item.getAttachments(); 811 | 812 | // let pdfAttachment = null; 813 | // let pdfPath_content = null; 814 | 815 | // for (const attachmentID of attachments) { 816 | // const attachment = await Zotero.Items.getAsync(attachmentID); 817 | // if (attachment.attachmentContentType === 'application/pdf') { 818 | // pdfAttachment = attachment; 819 | // pdfPath_content = await attachment.attachmentText; 820 | // break; 821 | // } 822 | // } 823 | 824 | // if (!pdfPath_content) { 825 | // result_p.textContent = 'No PDF attachment found for this item.'; 826 | // return; 827 | // } 828 | // user_qtxt += "\n\n paper pdf text:\n\n" + `${pdfPath_content}`; 829 | // } 830 | var system_prompt = `You are a computer science researcher. Based on the provided literature, write a comprehensive related work section about ${topic}. Instead of simply listing papers, identify and discuss the common ground and key differences between studies. 831 | 832 | Writing Requirements: 833 | 834 | 1.Maintain a balanced style: 60% formal academic tone, 40% conversational clarity. 835 | 2.Use clear subjects in each sentence and prefer short, crisp sentence structures over long, complex ones. 836 | 3.Synthesize the literature into a natural, compact paragraph format. 837 | 4.Include proper LaTeX citations (e.g., \cite{author2023}) at appropriate locations within the text. 838 | 839 | Focus on creating a cohesive narrative that demonstrates how the field has evolved and where current gaps or disagreements exist.`; 840 | 841 | 842 | var requestData = { 843 | model: `${model}`, 844 | messages: [{ role: 'system', content: `${system_prompt}` }, { role: 'user', content: 'literatures:\n' + `${pTitle}` }], 845 | stream: true, 846 | // max_tokens: 2000, 847 | // temperature: 0.7, 848 | }; 849 | 850 | 851 | 852 | try { 853 | var response = await fetch(`${apiUrl}/chat/completions`, { 854 | method: 'POST', 855 | headers: { 856 | 'Authorization': `Bearer ${OPENAI_API_KEY}`, 857 | 'Content-Type': 'application/json', 858 | }, 859 | body: JSON.stringify(requestData), 860 | }); 861 | 862 | if (!response.ok) { 863 | throw new Error(`Error: ${response.status} ${response.statusText}`); 864 | } else { 865 | 866 | const reader = response.body?.getReader(); 867 | 868 | const decoder = new TextDecoder(); 869 | let done = false; 870 | 871 | while (!done) { 872 | const { done: streamDone, value } = await reader!.read(); 873 | done = streamDone; 874 | if (value) { 875 | // 解析数据块 876 | 877 | const chunk = decoder.decode(value, { stream: true }); 878 | // 处理每个数据块 879 | 880 | const lines = chunk.split('\n').filter(line => line.trim() !== ''); 881 | for (var line of lines) { 882 | try { 883 | line = line.replace('data:', '') 884 | // result_p.textContent+=line; 885 | const data = JSON.parse(line); 886 | if (data.choices && data.choices[0]) { 887 | const text = data.choices[0].delta?.content || ''; 888 | // process.stdout.write(text); // 直接输出文本到控制台 889 | Review_text += text; 890 | } 891 | } catch (error) { 892 | ztoolkit.log("Could not parse JSON:", line); 893 | // result_p.textContent+=error as string; 894 | } 895 | } 896 | } 897 | } 898 | } 899 | 900 | 901 | } catch (error) { 902 | ztoolkit.log("Error", error); 903 | throw error; 904 | } 905 | 906 | 907 | 908 | 909 | const dialogData: { [key: string | number]: any } = { 910 | inputValue: "test", 911 | checkboxValue: true, 912 | loadCallback: () => { 913 | ztoolkit.log(dialogData, "Dialog Opened!"); 914 | }, 915 | unloadCallback: () => { 916 | ztoolkit.log(dialogData, "Dialog closed!"); 917 | }, 918 | }; 919 | const dialogHelper = new ztoolkit.Dialog(2, 2) 920 | .addCell(0, 0, { 921 | tag: "p", 922 | properties: { 923 | innerHTML: 924 | `${pTitleH}`, 925 | }, 926 | styles: { 927 | width: "440px", 928 | fontSize: "12", 929 | }, 930 | }) 931 | .addCell( 932 | 1, 933 | 0, 934 | { 935 | tag: "button", 936 | namespace: "html", 937 | attributes: { 938 | type: "button", 939 | }, 940 | listeners: [ 941 | { 942 | type: "click", 943 | listener: (e: Event) => { 944 | new ztoolkit.Clipboard() 945 | .addText( 946 | `${pTitle}`, 947 | "text/unicode", 948 | ) 949 | .copy(); 950 | ztoolkit.getGlobal("alert")("Copied!"); 951 | }, 952 | }, 953 | ], 954 | children: [ 955 | { 956 | tag: "div", 957 | styles: { 958 | padding: "2.5px 15px", 959 | }, 960 | properties: { 961 | innerHTML: "Copy", 962 | }, 963 | }, 964 | ], 965 | }, 966 | false, 967 | ) 968 | .addCell( 969 | 1, 970 | 1, 971 | { 972 | tag: "button", 973 | namespace: "html", 974 | attributes: { 975 | type: "button", 976 | }, 977 | listeners: [ 978 | { 979 | type: "click", 980 | listener: (e: Event) => { 981 | new ztoolkit.Clipboard() 982 | .addText( 983 | `${Review_text}`, 984 | "text/unicode", 985 | ) 986 | .copy(); 987 | ztoolkit.getGlobal("alert")("Copied!"); 988 | }, 989 | }, 990 | ], 991 | children: [ 992 | { 993 | tag: "div", 994 | styles: { 995 | padding: "2.5px 15px", 996 | }, 997 | properties: { 998 | innerHTML: "Copy Review", 999 | }, 1000 | }, 1001 | ], 1002 | }, 1003 | false, 1004 | ) 1005 | .addButton("Cancel", "cancel") 1006 | .setDialogData(dialogData) 1007 | .open("Papers"); 1008 | 1009 | addon.data.dialog = dialogHelper; 1010 | await dialogData.unloadLock.promise; 1011 | addon.data.dialog = undefined; 1012 | 1013 | ztoolkit.log(dialogData); 1014 | } 1015 | 1016 | @example 1017 | static clipboardExample() { 1018 | new ztoolkit.Clipboard() 1019 | .addText( 1020 | "![Plugin Template](https://github.com/windingwind/zotero-plugin-template)", 1021 | "text/unicode", 1022 | ) 1023 | .addText( 1024 | 'Plugin Template', 1025 | "text/html", 1026 | ) 1027 | .copy(); 1028 | ztoolkit.getGlobal("alert")("Copied!"); 1029 | } 1030 | 1031 | @example 1032 | static async filePickerExample() { 1033 | const path = await new ztoolkit.FilePicker( 1034 | "Import File", 1035 | "open", 1036 | [ 1037 | ["PNG File(*.png)", "*.png"], 1038 | ["Any", "*.*"], 1039 | ], 1040 | "image.png", 1041 | ).open(); 1042 | ztoolkit.getGlobal("alert")(`Selected ${path}`); 1043 | } 1044 | 1045 | @example 1046 | static progressWindowExample() { 1047 | new ztoolkit.ProgressWindow(config.addonName) 1048 | .createLine({ 1049 | text: "ProgressWindow Example!", 1050 | type: "success", 1051 | progress: 100, 1052 | }) 1053 | .show(); 1054 | } 1055 | 1056 | @example 1057 | static vtableExample() { 1058 | ztoolkit.getGlobal("alert")("See src/modules/preferenceScript.ts"); 1059 | } 1060 | } 1061 | --------------------------------------------------------------------------------