├── .gitattributes ├── .github ├── dependabot.yml ├── renovate.json └── workflows │ └── release.yml ├── .gitignore ├── .prettierignore ├── .vscode ├── extensions.json ├── launch.json ├── settings.json └── toolkit.code-snippets ├── LICENSE ├── README.md ├── addon ├── bootstrap.js ├── chrome │ └── content │ │ ├── icons │ │ ├── favicon.png │ │ ├── favicon@16.png │ │ └── favicon@20.png │ │ └── preferences.xhtml ├── locale │ ├── en-US │ │ ├── addon.ftl │ │ ├── mainWindow.ftl │ │ └── preferences.ftl │ └── zh-CN │ │ ├── addon.ftl │ │ ├── mainWindow.ftl │ │ └── preferences.ftl ├── manifest.json └── prefs.js ├── doc └── README-zhCN.md ├── package.json ├── scripts ├── build.mjs ├── scripts.mjs ├── server.mjs ├── start.mjs ├── stop.mjs ├── update-template.json ├── utils.mjs └── zotero-cmd-template.json ├── src ├── addon.ts ├── hooks.ts ├── index.ts ├── modules │ ├── Common.ts │ ├── dataStorage.ts │ ├── preferenceScript.ts │ └── tldrFetcher.ts └── utils │ ├── locale.ts │ ├── prefs.ts │ ├── wait.ts │ ├── window.ts │ └── ztoolkit.ts ├── tsconfig.json ├── typings └── global.d.ts └── update.json /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto eol=lf -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /.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 | "schedule:weekends" 11 | ], 12 | "packageRules": [ 13 | { 14 | "matchPackageNames": ["zotero-plugin-toolkit", "zotero-types"], 15 | "automerge": true 16 | } 17 | ], 18 | "git-submodules": { 19 | "enabled": true 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /.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 31 | 32 | - name: Release to GitHub 33 | run: | 34 | npm run release -- --no-increment --no-git --github.release --ci --VV 35 | sleep 1s 36 | 37 | - name: Notify release 38 | uses: apexskier/github-release-commenter@v1 39 | continue-on-error: true 40 | with: 41 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 42 | comment-template: | 43 | :rocket: _This ticket has been resolved in {release_tag}. See {release_link} for release notes._ 44 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | build 2 | logs 3 | node_modules 4 | package-lock.json 5 | pnpm-lock.yaml 6 | yarn.lock 7 | zotero-cmd.json 8 | .DS_Store -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | build 2 | logs 3 | node_modules 4 | package-lock.json 5 | yarn.lock 6 | pnpm-lock.yaml 7 | # zotero-cmd.json 8 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": [ 3 | "dbaeumer.vscode-eslint", 4 | "esbenp.prettier-vscode", 5 | "macabeus.vscode-fluent" 6 | ] 7 | } 8 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.formatOnType": false, 3 | "editor.formatOnSave": true, 4 | "editor.codeActionsOnSave": { 5 | "source.fixAll.eslint": "explicit" 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Zotero TL;DR 2 | 3 | [![zotero target version](https://img.shields.io/badge/Zotero-7-red?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 | This is an add-on for [Zotero 7+](https://www.zotero.org) that automatically fetch TL;DR (Too Long; Didn't Read) from [Sematic scholar](https://www.semanticscholar.org) for items. 7 | 8 | ## Install 9 | 10 | 1. Download the [latest release](https://github.com/syt2/zotero-tldr/releases/latest/download/zotero-tldr.xpi) xpi file. 11 | 2. Install in Zotero (Tools -> Add-ons) 12 | 13 | ## Usage 14 | 15 | There are no configuration steps required. 16 | The add-on will automatically fetch the TL;DR information for all items. 17 | You can view the TLDR information in details on the right side. 18 | -------------------------------------------------------------------------------- /addon/bootstrap.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Most of this code is from Zotero team's official Make It Red example[1] 3 | * or the Zotero 7 documentation[2]. 4 | * [1] https://github.com/zotero/make-it-red 5 | * [2] https://www.zotero.org/support/dev/zotero_7_for_developers 6 | */ 7 | 8 | var chromeHandle; 9 | 10 | function install(data, reason) {} 11 | 12 | async function startup({ id, version, resourceURI, rootURI }, reason) { 13 | await Zotero.initializationPromise; 14 | 15 | // String 'rootURI' introduced in Zotero 7 16 | if (!rootURI) { 17 | rootURI = resourceURI.spec; 18 | } 19 | 20 | var aomStartup = Components.classes[ 21 | "@mozilla.org/addons/addon-manager-startup;1" 22 | ].getService(Components.interfaces.amIAddonManagerStartup); 23 | var manifestURI = Services.io.newURI(rootURI + "manifest.json"); 24 | chromeHandle = aomStartup.registerChrome(manifestURI, [ 25 | ["content", "__addonRef__", rootURI + "chrome/content/"], 26 | ]); 27 | 28 | /** 29 | * Global variables for plugin code. 30 | * The `_globalThis` is the global root variable of the plugin sandbox environment 31 | * and all child variables assigned to it is globally accessible. 32 | * See `src/index.ts` for details. 33 | */ 34 | const ctx = { 35 | rootURI, 36 | }; 37 | ctx._globalThis = ctx; 38 | 39 | Services.scriptloader.loadSubScript( 40 | `${rootURI}/chrome/content/scripts/__addonRef__.js`, 41 | ctx, 42 | ); 43 | Zotero.__addonInstance__.hooks.onStartup(); 44 | } 45 | 46 | async function onMainWindowLoad({ window }, reason) { 47 | Zotero.__addonInstance__?.hooks.onMainWindowLoad(window); 48 | } 49 | 50 | async function onMainWindowUnload({ window }, reason) { 51 | Zotero.__addonInstance__?.hooks.onMainWindowUnload(window); 52 | } 53 | 54 | function shutdown({ id, version, resourceURI, rootURI }, reason) { 55 | if (reason === APP_SHUTDOWN) { 56 | return; 57 | } 58 | 59 | if (typeof Zotero === "undefined") { 60 | Zotero = Components.classes["@zotero.org/Zotero;1"].getService( 61 | Components.interfaces.nsISupports, 62 | ).wrappedJSObject; 63 | } 64 | Zotero.__addonInstance__?.hooks.onShutdown(); 65 | 66 | Cc["@mozilla.org/intl/stringbundle;1"] 67 | .getService(Components.interfaces.nsIStringBundleService) 68 | .flushBundles(); 69 | 70 | Cu.unload(`${rootURI}/chrome/content/scripts/__addonRef__.js`); 71 | 72 | if (chromeHandle) { 73 | chromeHandle.destruct(); 74 | chromeHandle = null; 75 | } 76 | } 77 | 78 | function uninstall(data, reason) {} 79 | -------------------------------------------------------------------------------- /addon/chrome/content/icons/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/syt2/Zotero-TLDR/ed129f2a4581f484416c645bfee0c687b12ddfb0/addon/chrome/content/icons/favicon.png -------------------------------------------------------------------------------- /addon/chrome/content/icons/favicon@16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/syt2/Zotero-TLDR/ed129f2a4581f484416c645bfee0c687b12ddfb0/addon/chrome/content/icons/favicon@16.png -------------------------------------------------------------------------------- /addon/chrome/content/icons/favicon@20.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/syt2/Zotero-TLDR/ed129f2a4581f484416c645bfee0c687b12ddfb0/addon/chrome/content/icons/favicon@20.png -------------------------------------------------------------------------------- /addon/chrome/content/preferences.xhtml: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/syt2/Zotero-TLDR/ed129f2a4581f484416c645bfee0c687b12ddfb0/addon/chrome/content/preferences.xhtml -------------------------------------------------------------------------------- /addon/locale/en-US/addon.ftl: -------------------------------------------------------------------------------- 1 | menuitem-updatetldrlabel = update TLDR 2 | menucollection-updatetldrlabel = update TLDR 3 | itembox-tldrlabel = TLDR 4 | tldr-unrelated = TLDR Unrelated in Semantic scholar 5 | tldr-itemnotfound = Item Not Found in Semantic scholar 6 | popWindow-succeed = Succeed 7 | popWindow-failed = Failed 8 | popWindow-waiting = Waiting -------------------------------------------------------------------------------- /addon/locale/en-US/mainWindow.ftl: -------------------------------------------------------------------------------- 1 | itemPaneSection-header = 2 | .label = TLDR 3 | itemPaneSection-sidenav = 4 | .tooltiptext = TLDR -------------------------------------------------------------------------------- /addon/locale/en-US/preferences.ftl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/syt2/Zotero-TLDR/ed129f2a4581f484416c645bfee0c687b12ddfb0/addon/locale/en-US/preferences.ftl -------------------------------------------------------------------------------- /addon/locale/zh-CN/addon.ftl: -------------------------------------------------------------------------------- 1 | menuitem-updatetldrlabel = 更新TLDR 2 | menucollection-updatetldrlabel = 批量更新TLDR 3 | itembox-tldrlabel = TLDR 4 | tldr-unrelated = 未关联TLDR 5 | tldr-itemnotfound = 未搜索到此条目 6 | popWindow-succeed = 成功 7 | popWindow-failed = 失败 8 | popWindow-waiting = 等待 -------------------------------------------------------------------------------- /addon/locale/zh-CN/mainWindow.ftl: -------------------------------------------------------------------------------- 1 | itemPaneSection-header = 2 | .label = TLDR 3 | itemPaneSection-sidenav = 4 | .tooltiptext = TLDR -------------------------------------------------------------------------------- /addon/locale/zh-CN/preferences.ftl: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/syt2/Zotero-TLDR/ed129f2a4581f484416c645bfee0c687b12ddfb0/addon/locale/zh-CN/preferences.ftl -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /addon/prefs.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable no-undef */ 2 | -------------------------------------------------------------------------------- /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 | 📖 [插件开发文档](https://zotero.yuque.com/books/share/8d230829-6004-4934-b4c6-685a7001bfa0/vec88d) (中文版,已过时) 11 | 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 | 16 | ℹ️ [Zotero 类型定义](https://github.com/windingwind/zotero-types) 17 | 18 | 📜 [Zotero 源代码](https://github.com/zotero/zotero) 19 | 20 | 📌 [Zotero 插件模板](https://github.com/windingwind/zotero-plugin-template) (即本仓库) 21 | 22 | > [!tip] 23 | > 👁 Watch 本仓库,以及时收到修复或更新的通知. 24 | 25 | ## 使用此模板构建的插件 26 | 27 | [![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) 28 | [![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) 29 | [![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) 30 | [![GitHub Repo stars](https://img.shields.io/github/stars/windingwind/zotero-tag?label=zotero-tag&style=flat-square)](https://github.com/windingwind/zotero-tag) 31 | [![GitHub Repo stars](https://img.shields.io/github/stars/iShareStuff/ZoteroTheme?label=zotero-theme&style=flat-square)](https://github.com/iShareStuff/ZoteroTheme) 32 | [![GitHub Repo stars](https://img.shields.io/github/stars/MuiseDestiny/zotero-reference?label=zotero-reference&style=flat-square)](https://github.com/MuiseDestiny/zotero-reference) 33 | [![GitHub Repo stars](https://img.shields.io/github/stars/MuiseDestiny/zotero-citation?label=zotero-citation&style=flat-square)](https://github.com/MuiseDestiny/zotero-citation) 34 | [![GitHub Repo stars](https://img.shields.io/github/stars/MuiseDestiny/ZoteroStyle?label=zotero-style&style=flat-square)](https://github.com/MuiseDestiny/ZoteroStyle) 35 | [![GitHub Repo stars](https://img.shields.io/github/stars/volatile-static/Chartero?label=Chartero&style=flat-square)](https://github.com/volatile-static/Chartero) 36 | [![GitHub Repo stars](https://img.shields.io/github/stars/l0o0/tara?label=tara&style=flat-square)](https://github.com/l0o0/tara) 37 | [![GitHub Repo stars](https://img.shields.io/github/stars/redleafnew/delitemwithatt?label=delitemwithatt&style=flat-square)](https://github.com/redleafnew/delitemwithatt) 38 | [![GitHub Repo stars](https://img.shields.io/github/stars/redleafnew/zotero-updateifsE?label=zotero-updateifsE&style=flat-square)](https://github.com/redleafnew/zotero-updateifsE) 39 | [![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) 40 | [![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) 41 | [![GitHub Repo stars](https://img.shields.io/github/stars/MuiseDestiny/zotero-gpt?label=zotero-gpt&style=flat-square)](https://github.com/MuiseDestiny/zotero-gpt) 42 | [![GitHub Repo stars](https://img.shields.io/github/stars/zoushucai/zotero-journalabbr?label=zotero-journalabbr&style=flat-square)](https://github.com/zoushucai/zotero-journalabbr) 43 | [![GitHub Repo stars](https://img.shields.io/github/stars/MuiseDestiny/zotero-figure?label=zotero-figure&style=flat-square)](https://github.com/MuiseDestiny/zotero-figure) 44 | [![GitHub Repo stars](https://img.shields.io/github/stars/l0o0/jasminum?label=jasminum&style=flat-square)](https://github.com/l0o0/jasminum) 45 | [![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) 46 | 47 | [![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) 48 | 49 | 如果你正在使用此库,我建议你将这个标志 ([![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 文件中: 50 | 51 | ```md 52 | [![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) 53 | ``` 54 | 55 | ## Features 特性 56 | 57 | - 事件驱动、函数式编程的可扩展框架; 58 | - 简单易用,开箱即用; 59 | - ⭐[新特性!]自动热重载!每当修改源码时,都会自动编译并重新加载插件;[详情请跳转→](#自动热重载) 60 | - `src/modules/examples.ts` 中有丰富的示例,涵盖了插件中常用的大部分API (使用的插件工具包 zotero-plugin-toolkit,仓库地址 https://github.com/windingwind/zotero-plugin-toolkit); 61 | - TypeScript 支持: 62 | - 为使用 JavaScript 编写的Zotero源码提供全面的类型定义支持 (使用类型定义包 zotero-types,仓库地址 https://github.com/windingwind/zotero-types); 63 | - 全局变量和环境设置; 64 | - 插件开发/构建/发布工作流: 65 | - 自动生成/更新插件id和版本、更新配置和设置环境变量 (`development`/`production`); 66 | - 自动在 Zotero 中构建和重新加载代码; 67 | - 自动发布到GitHub (使用[release-it](https://github.com/release-it/release-it)); 68 | - 集成Prettier和ES Lint; 69 | 70 | > [!warning] 71 | > Zotero本地化已升级(`dtd` 已弃用,我们将不再使用 `.properties`). 主分支将只支持 Zotero 7.0.0-beta.12 或更高版本. 如果需要支持 Zotero 6,你可能需要同时使用`dtd`、`properties` 和`ftl`. 请参考此库的 `zotero6-bootstrap` 分支. 72 | 73 | ## Examples 示例 74 | 75 | 此库提供了 [zotero-plugin-toolkit](https://github.com/windingwind/zotero-plugin-toolkit) 中API的示例. 76 | 77 | 在 `src/examples.ts` 中搜索`@example` 查看示例. 这些示例在 `src/hooks.ts` 中调用演示. 78 | 79 | ### 基本示例(Basic Examples) 80 | 81 | - registerNotifier 82 | - registerPrefs, unregisterPrefs 83 | 84 | ### 快捷键示例(Shortcut Keys Examples) 85 | 86 | - registerShortcuts 87 | - exampleShortcutLargerCallback 88 | - exampleShortcutSmallerCallback 89 | - exampleShortcutConflictionCallback 90 | 91 | ### UI示例(UI Examples) 92 | 93 | ![image](https://user-images.githubusercontent.com/33902321/211739774-cc5c2df8-5fd9-42f0-9cdf-0f2e5946d427.png) 94 | 95 | - registerStyleSheet(the official make-it-red example) 96 | - registerRightClickMenuItem 97 | - registerRightClickMenuPopup 98 | - registerWindowMenuWithSeprator 99 | - registerExtraColumn 100 | - registerExtraColumnWithCustomCell 101 | - registerCustomItemBoxRow 102 | - registerLibraryTabPanel 103 | - registerReaderTabPanel 104 | 105 | ### 首选项面板示例(Preference Pane Examples) 106 | 107 | ![image](https://user-images.githubusercontent.com/33902321/211737987-cd7c5c87-9177-4159-b975-dc67690d0490.png) 108 | 109 | - Preferences bindings 110 | - UI Events 111 | - Table 112 | - Locale 113 | 114 | 详情参见 [`src/modules/preferenceScript.ts`](./src/modules/preferenceScript.ts) 115 | 116 | ### 帮助示例(HelperExamples) 117 | 118 | ![image](https://user-images.githubusercontent.com/33902321/215119473-e7d0d0ef-6d96-437e-b989-4805ffcde6cf.png) 119 | 120 | - dialogExample 121 | - clipboardExample 122 | - filePickerExample 123 | - progressWindowExample 124 | - vtableExample(See Preference Pane Examples) 125 | 126 | ### 指令行示例(PromptExamples) 127 | 128 | Obsidian风格的指令输入模块,它通过接受文本来运行插件,并在弹出窗口中显示可选项. 129 | 130 | 使用 `Shift+P` 激活. 131 | 132 | ![image](https://user-images.githubusercontent.com/33902321/215120009-e7c7ed27-33a0-44fe-b021-06c272481a92.png) 133 | 134 | - registerAlertPromptExample 135 | 136 | ## Quick Start Guide 快速入门指南 137 | 138 | ### 0 前置要求(Requirement) 139 | 140 | 1. 安装测试版 Zotero:https://www.zotero.org/support/beta_builds 141 | 2. 安装 Node.js(https://nodejs.org/en/)和 Git(https://git-scm.com/) 142 | 143 | > [!note] 144 | > 本指南假定你已经对 Zotero 插件的基本结构和工作原理有初步的了解. 如果你还不了解,请先参考官方文档(https://www.zotero.org/support/dev/zotero_7_for_developers)和官方插件样例 Make It Red(仓库地址 https://github.com/zotero/make-it-red). 145 | 146 | ### 1 创建你的仓库(Create Your Repo) 147 | 148 | 1. 点击 `Use this template`; 149 | 2. 使用 `git clone` 克隆上一步生成的仓库; 150 |
151 | 💡 从 GitHub Codespace 开始 152 | 153 | _GitHub CodeSpace_ 使你可以直接开始开发而无需在本地下载代码/IDE/依赖. 154 | 155 | 重复下列步骤,仅需三十秒即可开始构建你的第一个插件! 156 | 157 | - 去 [homepage](https://github.com/windingwind/zotero-plugin-template)顶部,点击绿色按钮`Use this template`,点击 `Open in codespace`, 你需要登录你的GitHub账号. 158 | - 等待 codespace 加载. 159 | 160 |
161 | 162 | 3. 进入项目文件夹; 163 | 164 | ### 2 配置模板和开发环境(Config Template Settings and Enviroment) 165 | 166 | 1. 修改 `./package.json` 中的设置,包括: 167 | 168 | ```json5 169 | { 170 | version: "", // to 0.0.0 171 | author: "", 172 | description: "", 173 | homepage: "", 174 | config: { 175 | addonName: "", // name to be displayed in the plugin manager 176 | addonID: "", // ID to avoid conflict. IMPORTANT! 177 | addonRef: "", // e.g. Element ID prefix 178 | addonInstance: "", // the plugin's root instance: Zotero.${addonInstance} 179 | prefsPrefix: "extensions.zotero.${addonRef}", // the prefix of prefs 180 | releasePage: "", // URL to releases 181 | updateJSON: "", // URL to update.json 182 | }, 183 | } 184 | ``` 185 | 186 | > [!warning] 187 | > 注意设置 addonID 和 addonRef 以避免冲突. 188 | 189 | 如果你需要在GitHub以外的地方托管你的 XPI 包,请删除 `releasePage` 并添加 `updateLink`,并将值设置为你的 XPI 下载地址. 190 | 191 | 2. 复制 Zotero 启动配置,填入 Zotero 可执行文件路径和 profile 路径. 192 | 193 | > (可选项) 此操作仅需执行一次: 使用 `/path/to/zotero -p` 启动 Zotero,创建一个新的配置文件并用作开发配置文件. 194 | > 将配置文件的路径 `profilePath` 放入 `zotero-cmd.json` 中,以指定要使用的配置文件. 195 | 196 | ```sh 197 | cp ./scripts/zotero-cmd-template.json ./scripts/zotero-cmd.json 198 | vim ./scripts/zotero-cmd.json 199 | ``` 200 | 201 | 3. 运行 `npm install` 以安装相关依赖 202 | 203 | > 如果你使用 `pnpm` 作为包管理器,你需要添加 `public-hoist-pattern[]=*@types/bluebird*` 到`.npmrc`, 详情请查看 zotero-types(https://github.com/windingwind/zotero-types?tab=readme-ov-file#usage)的文档. 204 | 205 | ### 3 开始开发(Coding) 206 | 207 | 使用 `npm start` 启动开发服务器,它将: 208 | 209 | - 在开发模式下预构建插件 210 | - 启动 Zotero ,并让其从 `build/` 中加载插件 211 | - 打开开发者工具(devtool) 212 | - 监听 `src/**` 和 `addon/**`. 213 | - 如果 `src/**` 修改了,运行 esbuild 并且重新加载 214 | - 如果 `addon/**` 修改了,(在开发模式下)重新构建插件并且重新加载 215 | 216 | #### 自动热重载 217 | 218 | 厌倦了无休止的重启吗?忘掉它,拥抱热加载! 219 | 220 | 1. 运行 `npm start`. 221 | 2. 编码. (是的,就这么简单) 222 | 223 | 当检测到 `src` 或 `addon` 中的文件修改时,插件将自动编译并重新加载. 224 | 225 |
226 | 💡 将此功能添加到现有插件的步骤 227 | 228 | 1. 复制 `scripts/**.mjs` 229 | 2. 复制 `server` 、`build` 和 `stop` 命令到 `package.json` 230 | 3. 运行 `npm install --save-dev chokidar` 231 | 4. 结束. 232 | 233 |
234 | 235 | #### 在 Zotero 中 Debug 236 | 237 | 你还可以: 238 | 239 | - 在 Tools->Developer->Run Javascript 中测试代码片段; 240 | 241 | - 使用 `Zotero.debug()` 调试输出. 在 Help->Debug Output Logging->View Output 查看输出; 242 | 243 | - 调试 UI. Zotero 建立在 Firefox XUL 框架之上. 使用 [XUL Explorer](https://udn.realityripple.com/docs/Archive/Mozilla/XUL_Explorer) 等软件调试 XUL UI. 244 | 245 | > XUL 文档: 246 | 247 | ### 4 构建(Build) 248 | 249 | 运行 `npm run build` 在生产模式下构建插件,构建的结果位于 `build/` 目录中. 250 | 251 | `scripts/build.mjs` 的运行步骤: 252 | 253 | - 创建/清空 `build/` 254 | - 复制 `addon/**` 到 `build/addon/**` 255 | - 替换占位符:使用 `replace-in-file` 去替换在 `package.json` 中定义的关键字和配置 (`xhtml`、`.flt` 等) 256 | - 准备本地化文件以避免冲突,查看官方文档了解更多(https://www.zotero.org/support/dev/zotero_7_for_developers#avoiding_localization_conflicts) 257 | - 重命名`**/*.flt` 为 `**/${addonRef}-*.flt` 258 | - 在每个消息前加上 `addonRef-` 259 | - 使用 Esbuild 来将 `.ts` 源码构建为 `.js`,从 `src/index.ts` 构建到`./build/addon/chrome/content/scripts` 260 | - (仅在生产模式下工作) 压缩 `./build/addon` 目录为 `./build/*.xpi` 261 | - (仅在生产模式下工作) 准备 `update.json` 或 `update-beta.json` 262 | 263 | > [!note] 264 | > 265 | > **Dev & prod 两者有什么区别?** 266 | > 267 | > - 此环境变量存储在 `Zotero.${addonInstance}.data.env` 中,控制台输出在生产模式下被禁用. 268 | > - 你可以根据此变量决定用户无法查看/使用的内容. 269 | > - 在生产模式下,构建脚本将自动打包插件并更新 `update.json`. 270 | 271 | ### 5 发布(Release) 272 | 273 | 如果要构建和发布插件,运行如下指令: 274 | 275 | ```shell 276 | # A release-it command: version increase, npm run build, git push, and GitHub release 277 | # release-it: https://github.com/release-it/release-it 278 | npm run release 279 | ``` 280 | 281 | > [!note] 282 | > 在此模板中,release-it 被配置为在本地升级版本、构建、推送提交和 git 标签,随后GitHub Action 将重新构建插件并将 XPI 发布到 GitHub Release. 283 | > 284 | > 如果你需要发布一个本地构建的 XPI,将 `package.json` 中的 `release-it.github.release` 设置为 `true`,然后移除 `.github/workflows/release.yml`. 此外,你还需要设置环境变量 `GITHUB_TOKEN`,获取 GitHub Token(https://github.com/settings/tokens). 285 | 286 | #### 关于预发布 287 | 288 | 该模板将 `prerelease` 定义为插件的测试版,当你在 release-it 中选择 `prerelease` 版本 (版本号中带有 `-` ),构建脚本将创建一个 `update-beta.json` 给预发布版本使用,这将确保常规版本的用户不会自动更新到测试版,只有手动下载并安装了测试版的用户才能自动更新到下一个测试版. 当下一个正式版本更新时,脚本将同步更新 `update.json` 和 `update-beta.json`,这将使正式版和测试版用户都可以更新到最新的正式版. 289 | 290 | > [!warning] 291 | > 严格来说,区分 Zotero 6 和 Zotero 7 兼容的插件版本应该通过 `update.json` 的 `addons.__addonID__.updates[]` 中分别配置 `applications.zotero.strict_min_version`,这样 Zotero 才能正确识别,详情在 Zotero 7 开发文档(https://www.zotero.org/support/dev/zotero_7_for_developers#updaterdf_updatesjson)获取. 292 | 293 | ## Details 更多细节 294 | 295 | ### 关于Hooks(About Hooks) 296 | 297 | > 可以在 [`src/hooks.ts`](https://github.com/windingwind/zotero-plugin-template/blob/main/src/hooks.ts) 中查看更多 298 | 299 | 1. 当在 Zotero 中触发安装/启用/启动时,`bootstrap.js` > `startup` 被调用 300 | - 等待 Zotero 就绪 301 | - 加载 `index.js` (插件代码的主入口,从 `index.ts` 中构建) 302 | - 如果是 Zotero 7 以上的版本则注册资源 303 | 2. 主入口 `index.js` 中,插件对象被注入到 `Zotero` ,并且 `hooks.ts` > `onStartup` 被调用. 304 | - 初始化插件需要的资源,包括通知监听器、首选项面板和UI元素. 305 | 3. 当在 Zotero 中触发卸载/禁用时,`bootstrap.js` > `shutdown` 被调用. 306 | - `events.ts` > `onShutdown` 被调用. 移除 UI 元素、首选项面板或插件创建的任何内容. 307 | - 移除脚本并释放资源. 308 | 309 | ### 关于全局变量(About Global Variables) 310 | 311 | > 可以在 [`src/index.ts`](https://github.com/windingwind/zotero-plugin-template/blob/main/src/index.ts)中查看更多 312 | 313 | bootstrap插件在沙盒中运行,但沙盒中没有默认的全局变量,例如 `Zotero` 或 `window` 等我们曾在overlay插件环境中使用的变量. 314 | 315 | 此模板将以下变量注册到全局范围: 316 | 317 | ```ts 318 | Zotero, ZoteroPane, Zotero_Tabs, window, document, rootURI, ztoolkit, addon; 319 | ``` 320 | 321 | ### 创建元素 API(Create Elements API) 322 | 323 | 插件模板为 bootstrap 插件提供了一些新的API. 我们有两个原因使用这些 API,而不是使用 `createElement/createElementNS`: 324 | 325 | - 在 bootstrap 模式下,插件必须在推出(禁用或卸载)时清理所有 UI 元素,这非常麻烦. 使用 `createElement`,插件模板将维护这些元素. 仅仅在退出时 `unregisterAll` . 326 | - Zotero 7 需要 createElement()/createElementNS() → createXULElement() 来表示其他的 XUL 元素,而 Zotero 6 并不支持 `createXULElement`. 类似于 React.createElement 的API `createElement` 检测 namespace(xul/html/svg) 并且自动创建元素,返回元素为对应的 TypeScript 元素类型. 327 | 328 | ```ts 329 | createElement(document, "div"); // returns HTMLDivElement 330 | createElement(document, "hbox"); // returns XUL.Box 331 | createElement(document, "button", { namespace: "xul" }); // manually set namespace. returns XUL.Button 332 | ``` 333 | 334 | ### 关于 Zotero API(About Zotero API) 335 | 336 | Zotero 文档已过时且不完整,克隆 https://github.com/zotero/zotero 并全局搜索关键字. 337 | 338 | > ⭐[zotero-types](https://github.com/windingwind/zotero-types) 提供了最常用的 Zotero API,在默认情况下它被包含在此模板中. 你的 IDE 将为大多数的 API 提供提醒. 339 | 340 | 猜你需要:查找所需 API的技巧 341 | 342 | 在 `.xhtml`/`.flt` 文件中搜索 UI 标签,然后在 locale 文件中找到对应的键. ,然后在 `.js`/`.jsx` 文件中搜索此键. 343 | 344 | ### 目录结构(Directory Structure) 345 | 346 | 本部分展示了模板的目录结构. 347 | 348 | - 所有的 `.js/.ts` 代码都在 `./src`; 349 | - 插件配置文件:`./addon/manifest.json`; 350 | - UI 文件: `./addon/chrome/content/*.xhtml`. 351 | - 区域设置文件: `./addon/locale/**/*.flt`; 352 | - 首选项文件: `./addon/prefs.js`; 353 | > 不要在 `prefs.js` 中换行 354 | 355 | ```shell 356 | . 357 | |-- .eslintrc.json # eslint conf 358 | |-- .gitattributes # git conf 359 | |-- .github/ # github conf 360 | |-- .gitignore # git conf 361 | |-- .prettierrc # prettier conf 362 | |-- .release-it.json # release-it conf 363 | |-- .vscode # vs code conf 364 | | |-- extensions.json 365 | | |-- launch.json 366 | | |-- setting.json 367 | | `-- toolkit.code-snippets 368 | |-- package-lock.json # npm conf 369 | |-- package.json # npm conf 370 | |-- LICENSE 371 | |-- README.md 372 | |-- addon 373 | | |-- bootstrap.js # addon load/unload script, like a main.c 374 | | |-- chrome 375 | | | `-- content 376 | | | |-- icons/ 377 | | | |-- preferences.xhtml # preference panel 378 | | | `-- zoteroPane.css 379 | | |-- locale # locale 380 | | | |-- en-US 381 | | | | |-- addon.ftl 382 | | | | `-- preferences.ftl 383 | | | `-- zh-CN 384 | | | |-- addon.ftl 385 | | | `-- preferences.ftl 386 | | |-- manifest.json # addon config 387 | | `-- prefs.js 388 | |-- build/ # build dir 389 | |-- scripts # scripts for dev 390 | | |-- build.mjs # script to build plugin 391 | | |-- scripts.mjs # scripts send to Zotero, such as reload, openDevTool, etc 392 | | |-- server.mjs # script to start a development server 393 | | |-- start.mjs # script to start Zotero process 394 | | |-- stop.mjs # script to kill Zotero process 395 | | |-- utils.mjs # utils functions for dev scripts 396 | | |-- update-template.json # template of `update.json` 397 | | `-- zotero-cmd-template.json # template of local env 398 | |-- src # source code 399 | | |-- addon.ts # base class 400 | | |-- hooks.ts # lifecycle hooks 401 | | |-- index.ts # main entry 402 | | |-- modules # sub modules 403 | | | |-- examples.ts 404 | | | `-- preferenceScript.ts 405 | | `-- utils # utilities 406 | | |-- locale.ts 407 | | |-- prefs.ts 408 | | |-- wait.ts 409 | | `-- window.ts 410 | |-- tsconfig.json # https://code.visualstudio.com/docs/languages/jsconfig 411 | |-- typings # ts typings 412 | | `-- global.d.ts 413 | `-- update.json 414 | ``` 415 | 416 | ## Disclaimer 免责声明 417 | 418 | 在 AGPL 下使用此代码. 不提供任何保证. 遵守你所在地区的法律! 419 | 420 | 如果你想更改许可,请通过 与我联系. 421 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "zotero-tldr", 3 | "version": "1.0.7", 4 | "description": "TLDR(too long; didn't read) from sematic scholar", 5 | "config": { 6 | "addonName": "Zotero TLDR", 7 | "addonID": "zoterotldr@syt.com", 8 | "addonRef": "zoterotldr", 9 | "addonInstance": "ZoteroTLDR", 10 | "prefsPrefix": "extensions.zotero.zoterotldr", 11 | "releasepage": "https://github.com/syt2/zotero-tldr/releases", 12 | "updateJSON": "https://raw.githubusercontent.com/syt2/zotero-tldr/main/update.json" 13 | }, 14 | "main": "src/index.ts", 15 | "scripts": { 16 | "start": "node scripts/server.mjs", 17 | "build": "tsc --noEmit && node scripts/build.mjs production", 18 | "stop": "node scripts/stop.mjs", 19 | "lint": "prettier --write . && eslint . --ext .ts --fix", 20 | "test": "echo \"Error: no test specified\" && exit 1", 21 | "release": "release-it --only-version --preReleaseId=beta", 22 | "update-deps": "npm update --save" 23 | }, 24 | "repository": { 25 | "type": "git", 26 | "url": "git+https://github.com/syt2/zotero-tldr.git" 27 | }, 28 | "author": "syt2", 29 | "license": "AGPL-3.0-or-later", 30 | "bugs": { 31 | "url": "https://github.com/syt2/zotero-tldr/issues" 32 | }, 33 | "homepage": "https://github.com/syt2/zotero-tldr#readme", 34 | "dependencies": { 35 | "zotero-plugin-toolkit": "^2.3.29" 36 | }, 37 | "devDependencies": { 38 | "@types/node": "^20.10.4", 39 | "@typescript-eslint/eslint-plugin": "^7.3.1", 40 | "@typescript-eslint/parser": "^7.1.1", 41 | "chokidar": "^3.5.3", 42 | "compressing": "^1.10.0", 43 | "esbuild": "^0.20.1", 44 | "eslint": "^8.55.0", 45 | "eslint-config-prettier": "^9.1.0", 46 | "prettier": "^3.1.1", 47 | "release-it": "^17.0.1", 48 | "replace-in-file": "^7.0.2", 49 | "typescript": "^5.3.3", 50 | "zotero-types": "^1.3.10" 51 | }, 52 | "eslintConfig": { 53 | "env": { 54 | "browser": true, 55 | "es2021": true 56 | }, 57 | "root": true, 58 | "extends": [ 59 | "eslint:recommended", 60 | "plugin:@typescript-eslint/recommended", 61 | "prettier" 62 | ], 63 | "overrides": [], 64 | "parser": "@typescript-eslint/parser", 65 | "parserOptions": { 66 | "ecmaVersion": "latest", 67 | "sourceType": "module" 68 | }, 69 | "plugins": [ 70 | "@typescript-eslint" 71 | ], 72 | "rules": { 73 | "@typescript-eslint/ban-ts-comment": [ 74 | "warn", 75 | { 76 | "ts-expect-error": "allow-with-description", 77 | "ts-ignore": "allow-with-description", 78 | "ts-nocheck": "allow-with-description", 79 | "ts-check": "allow-with-description" 80 | } 81 | ], 82 | "@typescript-eslint/no-unused-vars": "off", 83 | "@typescript-eslint/no-explicit-any": [ 84 | "off", 85 | { 86 | "ignoreRestArgs": true 87 | } 88 | ], 89 | "@typescript-eslint/no-non-null-assertion": "off" 90 | }, 91 | "ignorePatterns": [ 92 | "**/build/**", 93 | "**/logs/**", 94 | "**/dist/**", 95 | "**/node_modules/**", 96 | "**/scripts/**", 97 | "**/*.js", 98 | "**/*.bak" 99 | ] 100 | }, 101 | "prettier": { 102 | "printWidth": 80, 103 | "tabWidth": 2, 104 | "endOfLine": "lf", 105 | "overrides": [ 106 | { 107 | "files": [ 108 | "*.xhtml" 109 | ], 110 | "options": { 111 | "htmlWhitespaceSensitivity": "css" 112 | } 113 | } 114 | ] 115 | }, 116 | "release-it": { 117 | "git": { 118 | "tagName": "V${version}" 119 | }, 120 | "npm": { 121 | "publish": false 122 | }, 123 | "github": { 124 | "release": false, 125 | "assets": [ 126 | "build/*.xpi" 127 | ] 128 | }, 129 | "hooks": { 130 | "before:init": "npm run lint", 131 | "after:bump": "npm run build" 132 | } 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /scripts/build.mjs: -------------------------------------------------------------------------------- 1 | import details from "../package.json" assert { type: "json" }; 2 | import { 3 | Logger, 4 | clearFolder, 5 | copyFileSync, 6 | copyFolderRecursiveSync, 7 | dateFormat, 8 | } from "./utils.mjs"; 9 | import { zip } from "compressing"; 10 | import { build } from "esbuild"; 11 | import { existsSync, readdirSync, renameSync } from "fs"; 12 | import path from "path"; 13 | import { env, exit } from "process"; 14 | import replaceInFile from "replace-in-file"; 15 | 16 | const { replaceInFileSync } = replaceInFile; 17 | 18 | process.env.NODE_ENV = 19 | process.argv[2] === "production" ? "production" : "development"; 20 | 21 | const buildDir = "build"; 22 | 23 | const { name, author, description, homepage, version, config } = details; 24 | const isPreRelease = version.includes("-"); 25 | 26 | function replaceString(buildTime) { 27 | const replaceFrom = [ 28 | /__author__/g, 29 | /__description__/g, 30 | /__homepage__/g, 31 | /__buildVersion__/g, 32 | /__buildTime__/g, 33 | ]; 34 | const replaceTo = [author, description, homepage, version, buildTime]; 35 | 36 | config.updateURL = isPreRelease 37 | ? config.updateJSON.replace("update.json", "update-beta.json") 38 | : config.updateJSON; 39 | 40 | replaceFrom.push( 41 | ...Object.keys(config).map((k) => new RegExp(`__${k}__`, "g")), 42 | ); 43 | replaceTo.push(...Object.values(config)); 44 | 45 | const replaceResult = replaceInFileSync({ 46 | files: [ 47 | `${buildDir}/addon/**/*.xhtml`, 48 | `${buildDir}/addon/**/*.html`, 49 | `${buildDir}/addon/**/*.css`, 50 | `${buildDir}/addon/**/*.json`, 51 | `${buildDir}/addon/prefs.js`, 52 | `${buildDir}/addon/manifest.json`, 53 | `${buildDir}/addon/bootstrap.js`, 54 | ], 55 | from: replaceFrom, 56 | to: replaceTo, 57 | countMatches: true, 58 | }); 59 | 60 | // Logger.debug( 61 | // "[Build] Run replace in ", 62 | // replaceResult.filter((f) => f.hasChanged).map((f) => `${f.file} : ${f.numReplacements} / ${f.numMatches}`), 63 | // ); 64 | } 65 | 66 | function prepareLocaleFiles() { 67 | // Prefix Fluent messages in xhtml 68 | const MessagesInHTML = new Set(); 69 | replaceInFileSync({ 70 | files: [`${buildDir}/addon/**/*.xhtml`, `${buildDir}/addon/**/*.html`], 71 | processor: (input) => { 72 | const matchs = [...input.matchAll(/(data-l10n-id)="(\S*)"/g)]; 73 | matchs.map((match) => { 74 | input = input.replace( 75 | match[0], 76 | `${match[1]}="${config.addonRef}-${match[2]}"`, 77 | ); 78 | MessagesInHTML.add(match[2]); 79 | }); 80 | return input; 81 | }, 82 | }); 83 | 84 | // Walk the sub folders of `build/addon/locale` 85 | const localesPath = path.join(buildDir, "addon/locale"), 86 | localeNames = readdirSync(localesPath, { withFileTypes: true }) 87 | .filter((dirent) => dirent.isDirectory()) 88 | .map((dirent) => dirent.name); 89 | 90 | for (const localeName of localeNames) { 91 | const localePath = path.join(localesPath, localeName); 92 | const ftlFiles = readdirSync(localePath, { 93 | withFileTypes: true, 94 | }) 95 | .filter((dirent) => dirent.isFile()) 96 | .map((dirent) => dirent.name); 97 | 98 | // rename *.ftl to addonRef-*.ftl 99 | for (const ftlFile of ftlFiles) { 100 | if (ftlFile.endsWith(".ftl")) { 101 | renameSync( 102 | path.join(localePath, ftlFile), 103 | path.join(localePath, `${config.addonRef}-${ftlFile}`), 104 | ); 105 | } 106 | } 107 | 108 | // Prefix Fluent messages in each ftl 109 | const MessageInThisLang = new Set(); 110 | replaceInFileSync({ 111 | files: [`${buildDir}/addon/locale/${localeName}/*.ftl`], 112 | processor: (fltContent) => { 113 | const lines = fltContent.split("\n"); 114 | const prefixedLines = lines.map((line) => { 115 | // https://regex101.com/r/lQ9x5p/1 116 | const match = line.match( 117 | /^(?[a-zA-Z]\S*)([ ]*=[ ]*)(?.*)$/m, 118 | ); 119 | if (match) { 120 | MessageInThisLang.add(match.groups.message); 121 | return `${config.addonRef}-${line}`; 122 | } else { 123 | return line; 124 | } 125 | }); 126 | return prefixedLines.join("\n"); 127 | }, 128 | }); 129 | 130 | // If a message in xhtml but not in ftl of current language, log it 131 | MessagesInHTML.forEach((message) => { 132 | if (!MessageInThisLang.has(message)) { 133 | Logger.error(`[Build] ${message} don't exist in ${localeName}`); 134 | } 135 | }); 136 | } 137 | } 138 | 139 | function prepareUpdateJson() { 140 | // If it is a pre-release, use update-beta.json 141 | if (!isPreRelease) { 142 | copyFileSync("scripts/update-template.json", "update.json"); 143 | } 144 | if (existsSync("update-beta.json") || isPreRelease) { 145 | copyFileSync("scripts/update-template.json", "update-beta.json"); 146 | } 147 | 148 | const updateLink = 149 | config.updateLink ?? isPreRelease 150 | ? `${config.releasePage}/download/v${version}/${name}.xpi` 151 | : `${config.releasePage}/latest/download/${name}.xpi`; 152 | 153 | const replaceResult = replaceInFileSync({ 154 | files: [ 155 | "update-beta.json", 156 | isPreRelease ? "pass" : "update.json", 157 | `${buildDir}/addon/manifest.json`, 158 | ], 159 | from: [ 160 | /__addonID__/g, 161 | /__buildVersion__/g, 162 | /__updateLink__/g, 163 | /__updateURL__/g, 164 | ], 165 | to: [config.addonID, version, updateLink, config.updateURL], 166 | countMatches: true, 167 | }); 168 | 169 | Logger.debug( 170 | `[Build] Prepare Update.json for ${ 171 | isPreRelease 172 | ? "\u001b[31m Prerelease \u001b[0m" 173 | : "\u001b[32m Release \u001b[0m" 174 | }`, 175 | replaceResult 176 | .filter((f) => f.hasChanged) 177 | .map((f) => `${f.file} : ${f.numReplacements} / ${f.numMatches}`), 178 | ); 179 | } 180 | 181 | export const esbuildOptions = { 182 | entryPoints: ["src/index.ts"], 183 | define: { 184 | __env__: `"${env.NODE_ENV}"`, 185 | }, 186 | bundle: true, 187 | target: "firefox102", 188 | outfile: path.join( 189 | buildDir, 190 | `addon/chrome/content/scripts/${config.addonRef}.js`, 191 | ), 192 | // Don't turn minify on 193 | minify: env.NODE_ENV === "production", 194 | }; 195 | 196 | export async function main() { 197 | const t = new Date(); 198 | const buildTime = dateFormat("YYYY-mm-dd HH:MM:SS", new Date()); 199 | 200 | Logger.info( 201 | `[Build] BUILD_DIR=${buildDir}, VERSION=${version}, BUILD_TIME=${buildTime}, ENV=${[ 202 | env.NODE_ENV, 203 | ]}`, 204 | ); 205 | 206 | clearFolder(buildDir); 207 | copyFolderRecursiveSync("addon", buildDir); 208 | 209 | Logger.debug("[Build] Replacing"); 210 | replaceString(buildTime); 211 | 212 | Logger.debug("[Build] Preparing locale files"); 213 | prepareLocaleFiles(); 214 | 215 | Logger.debug("[Build] Running esbuild"); 216 | await build(esbuildOptions); 217 | 218 | Logger.debug("[Build] Addon prepare OK"); 219 | 220 | if (process.env.NODE_ENV === "production") { 221 | Logger.debug("[Build] Packing Addon"); 222 | await zip.compressDir( 223 | path.join(buildDir, "addon"), 224 | path.join(buildDir, `${name}.xpi`), 225 | { 226 | ignoreBase: true, 227 | }, 228 | ); 229 | 230 | prepareUpdateJson(); 231 | 232 | Logger.debug( 233 | `[Build] Finished in ${(new Date().getTime() - t.getTime()) / 1000} s.`, 234 | ); 235 | } 236 | } 237 | 238 | if (process.env.NODE_ENV === "production") { 239 | main().catch((err) => { 240 | Logger.error(err); 241 | exit(1); 242 | }); 243 | } 244 | -------------------------------------------------------------------------------- /scripts/scripts.mjs: -------------------------------------------------------------------------------- 1 | import details from "../package.json" assert { type: "json" }; 2 | 3 | const { addonID, addonName } = details.config; 4 | const { version } = details; 5 | 6 | export const reloadScript = ` 7 | (async () => { 8 | Services.obs.notifyObservers(null, "startupcache-invalidate", null); 9 | const { AddonManager } = ChromeUtils.import("resource://gre/modules/AddonManager.jsm"); 10 | const addon = await AddonManager.getAddonByID("${addonID}"); 11 | await addon.reload(); 12 | const progressWindow = new Zotero.ProgressWindow({ closeOnClick: true }); 13 | progressWindow.changeHeadline("${addonName} Hot Reload"); 14 | progressWindow.progress = new progressWindow.ItemProgress( 15 | "chrome://zotero/skin/tick.png", 16 | "VERSION=${version}, BUILD=${new Date().toLocaleString()}. By zotero-plugin-toolkit" 17 | ); 18 | progressWindow.progress.setProgress(100); 19 | progressWindow.show(); 20 | progressWindow.startCloseTimer(5000); 21 | })()`; 22 | 23 | export const openDevToolScript = ` 24 | (async () => { 25 | 26 | // const { BrowserToolboxLauncher } = ChromeUtils.import( 27 | // "resource://devtools/client/framework/browser-toolbox/Launcher.jsm", 28 | // ); 29 | // BrowserToolboxLauncher.init(); 30 | // TODO: Use the above code to open the devtool after https://github.com/zotero/zotero/pull/3387 31 | 32 | Zotero.Prefs.set("devtools.debugger.remote-enabled", true, true); 33 | Zotero.Prefs.set("devtools.debugger.remote-port", 6100, true); 34 | Zotero.Prefs.set("devtools.debugger.prompt-connection", false, true); 35 | Zotero.Prefs.set("devtools.debugger.chrome-debugging-websocket", false, true); 36 | 37 | env = 38 | Services.env || 39 | Cc["@mozilla.org/process/environment;1"].getService(Ci.nsIEnvironment); 40 | 41 | env.set("MOZ_BROWSER_TOOLBOX_PORT", 6100); 42 | Zotero.openInViewer( 43 | "chrome://devtools/content/framework/browser-toolbox/window.html", 44 | { 45 | onLoad: (doc) => { 46 | doc.querySelector("#status-message-container").style.visibility = 47 | "collapse"; 48 | let toolboxBody; 49 | waitUntil( 50 | () => { 51 | toolboxBody = doc 52 | .querySelector(".devtools-toolbox-browsertoolbox-iframe") 53 | ?.contentDocument?.querySelector(".theme-body"); 54 | return toolboxBody; 55 | }, 56 | () => { 57 | toolboxBody.style = "pointer-events: all !important"; 58 | } 59 | ); 60 | }, 61 | } 62 | ); 63 | 64 | function waitUntil(condition, callback, interval = 100, timeout = 10000) { 65 | const start = Date.now(); 66 | const intervalId = setInterval(() => { 67 | if (condition()) { 68 | clearInterval(intervalId); 69 | callback(); 70 | } else if (Date.now() - start > timeout) { 71 | clearInterval(intervalId); 72 | } 73 | }, interval); 74 | } 75 | })()`; 76 | -------------------------------------------------------------------------------- /scripts/server.mjs: -------------------------------------------------------------------------------- 1 | import { main as build, esbuildOptions } from "./build.mjs"; 2 | import { openDevToolScript, reloadScript } from "./scripts.mjs"; 3 | import { main as startZotero } from "./start.mjs"; 4 | import { Logger } from "./utils.mjs"; 5 | import cmd from "./zotero-cmd.json" assert { type: "json" }; 6 | import { execSync } from "child_process"; 7 | import chokidar from "chokidar"; 8 | import { context } from "esbuild"; 9 | import { exit } from "process"; 10 | 11 | process.env.NODE_ENV = "development"; 12 | 13 | const { zoteroBinPath, profilePath } = cmd.exec; 14 | 15 | const startZoteroCmd = `"${zoteroBinPath}" --debugger --purgecaches -profile "${profilePath}"`; 16 | 17 | async function watch() { 18 | const watcher = chokidar.watch(["src/**", "addon/**"], { 19 | ignored: /(^|[\/\\])\../, // ignore dotfiles 20 | persistent: true, 21 | }); 22 | 23 | let esbuildCTX = await context(esbuildOptions); 24 | 25 | watcher 26 | .on("ready", () => { 27 | Logger.info("Server Ready! \n"); 28 | }) 29 | .on("change", async (path) => { 30 | Logger.info(`${path} changed.`); 31 | if (path.startsWith("src")) { 32 | await esbuildCTX.rebuild(); 33 | } else if (path.startsWith("addon")) { 34 | await build() 35 | // Do not abort the watcher when errors occur in builds triggered by the watcher. 36 | .catch((err) => { 37 | Logger.error(err); 38 | }); 39 | } 40 | // reload 41 | reload(); 42 | }) 43 | .on("error", (err) => { 44 | Logger.error("Server start failed!", err); 45 | }); 46 | } 47 | 48 | function reload() { 49 | Logger.debug("Reloading..."); 50 | const url = `zotero://ztoolkit-debug/?run=${encodeURIComponent( 51 | reloadScript, 52 | )}`; 53 | const command = `${startZoteroCmd} -url "${url}"`; 54 | execSync(command); 55 | } 56 | 57 | function openDevTool() { 58 | Logger.debug("Open dev tools..."); 59 | const url = `zotero://ztoolkit-debug/?run=${encodeURIComponent( 60 | openDevToolScript, 61 | )}`; 62 | const command = `${startZoteroCmd} -url "${url}"`; 63 | execSync(command); 64 | } 65 | 66 | async function main() { 67 | // build 68 | await build(); 69 | 70 | // start Zotero 71 | startZotero(openDevTool); 72 | 73 | // watch 74 | await watch(); 75 | } 76 | 77 | main().catch((err) => { 78 | Logger.error(err); 79 | // execSync("node scripts/stop.mjs"); 80 | exit(1); 81 | }); 82 | 83 | process.on("SIGINT", (code) => { 84 | execSync("node scripts/stop.mjs"); 85 | Logger.info(`Server terminated with signal ${code}.`); 86 | exit(0); 87 | }); 88 | -------------------------------------------------------------------------------- /scripts/start.mjs: -------------------------------------------------------------------------------- 1 | import details from "../package.json" assert { type: "json" }; 2 | import { Logger } from "./utils.mjs"; 3 | import cmd from "./zotero-cmd.json" assert { type: "json" }; 4 | import { spawn } from "child_process"; 5 | import { existsSync, readFileSync, writeFileSync, rmSync } from "fs"; 6 | import { clearFolder } from "./utils.mjs"; 7 | import path from "path"; 8 | import { exit } from "process"; 9 | 10 | const { addonID } = details.config; 11 | const { zoteroBinPath, profilePath, dataDir } = cmd.exec; 12 | 13 | // Keep in sync with the addon's onStartup 14 | const loadDevToolWhen = `Plugin ${addonID} startup`; 15 | 16 | const logPath = "logs"; 17 | const logFilePath = path.join(logPath, "zotero.log"); 18 | 19 | if (!existsSync(zoteroBinPath)) { 20 | throw new Error("Zotero binary does not exist."); 21 | } 22 | 23 | if (!existsSync(profilePath)) { 24 | throw new Error("The given Zotero profile does not exist."); 25 | } 26 | 27 | function prepareDevEnv() { 28 | const addonProxyFilePath = path.join(profilePath, `extensions/${addonID}`); 29 | const buildPath = path.resolve("build/addon"); 30 | 31 | function writeAddonProxyFile() { 32 | writeFileSync(addonProxyFilePath, buildPath); 33 | Logger.debug( 34 | `Addon proxy file has been updated. 35 | File path: ${addonProxyFilePath} 36 | Addon path: ${buildPath} `, 37 | ); 38 | } 39 | 40 | if (existsSync(addonProxyFilePath)) { 41 | if (readFileSync(addonProxyFilePath, "utf-8") !== buildPath) { 42 | writeAddonProxyFile(); 43 | } 44 | } else { 45 | writeAddonProxyFile(); 46 | } 47 | 48 | const addonXpiFilePath = path.join(profilePath, `extensions/${addonID}.xpi`); 49 | if (existsSync(addonXpiFilePath)) { 50 | rmSync(addonXpiFilePath); 51 | } 52 | 53 | const prefsPath = path.join(profilePath, "prefs.js"); 54 | if (existsSync(prefsPath)) { 55 | const PrefsLines = readFileSync(prefsPath, "utf-8").split("\n"); 56 | const filteredLines = PrefsLines.map((line) => { 57 | if ( 58 | line.includes("extensions.lastAppBuildId") || 59 | line.includes("extensions.lastAppVersion") 60 | ) { 61 | return; 62 | } 63 | if (line.includes("extensions.zotero.dataDir") && dataDir !== "") { 64 | return `user_pref("extensions.zotero.dataDir", "${dataDir.replace(/\\\\?/g, "\\\\")}");`; 65 | } 66 | return line; 67 | }); 68 | const updatedPrefs = filteredLines.join("\n"); 69 | writeFileSync(prefsPath, updatedPrefs, "utf-8"); 70 | Logger.debug("The /prefs.js has been modified."); 71 | } 72 | } 73 | 74 | function prepareLog() { 75 | clearFolder(logPath); 76 | writeFileSync(logFilePath, ""); 77 | } 78 | 79 | export function main(callback) { 80 | let isZoteroReady = false; 81 | 82 | prepareDevEnv(); 83 | 84 | prepareLog(); 85 | 86 | const zoteroProcess = spawn(zoteroBinPath, [ 87 | "--debugger", 88 | "--purgecaches", 89 | "-profile", 90 | profilePath, 91 | ]); 92 | 93 | zoteroProcess.stdout.on("data", (data) => { 94 | if (!isZoteroReady && data.toString().includes(loadDevToolWhen)) { 95 | isZoteroReady = true; 96 | callback(); 97 | } 98 | writeFileSync(logFilePath, data, { 99 | flag: "a", 100 | }); 101 | }); 102 | 103 | zoteroProcess.stderr.on("data", (data) => { 104 | writeFileSync(logFilePath, data, { 105 | flag: "a", 106 | }); 107 | }); 108 | 109 | zoteroProcess.on("close", (code) => { 110 | Logger.info(`Zotero terminated with code ${code}.`); 111 | exit(0); 112 | }); 113 | 114 | process.on("SIGINT", () => { 115 | // Handle interrupt signal (Ctrl+C) to gracefully terminate Zotero process 116 | zoteroProcess.kill(); 117 | exit(); 118 | }); 119 | } 120 | -------------------------------------------------------------------------------- /scripts/stop.mjs: -------------------------------------------------------------------------------- 1 | import { Logger, isRunning } from "./utils.mjs"; 2 | import cmd from "./zotero-cmd.json" assert { type: "json" }; 3 | import { execSync } from "child_process"; 4 | import process from "process"; 5 | 6 | const { killZoteroWindows, killZoteroUnix } = cmd; 7 | 8 | isRunning("zotero", (status) => { 9 | if (status) { 10 | killZotero(); 11 | } else { 12 | Logger.warn("No Zotero running."); 13 | } 14 | }); 15 | 16 | function killZotero() { 17 | try { 18 | if (process.platform === "win32") { 19 | execSync(killZoteroWindows); 20 | } else { 21 | execSync(killZoteroUnix); 22 | } 23 | } catch (e) { 24 | Logger.error(e); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /scripts/update-template.json: -------------------------------------------------------------------------------- 1 | { 2 | "addons": { 3 | "__addonID__": { 4 | "updates": [ 5 | { 6 | "version": "__buildVersion__", 7 | "update_link": "__updateLink__", 8 | "applications": { 9 | "zotero": { 10 | "strict_min_version": "6.999" 11 | } 12 | } 13 | } 14 | ] 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /scripts/utils.mjs: -------------------------------------------------------------------------------- 1 | import { exec } from "child_process"; 2 | import { 3 | existsSync, 4 | lstatSync, 5 | mkdirSync, 6 | readFileSync, 7 | readdirSync, 8 | rmSync, 9 | writeFileSync, 10 | } from "fs"; 11 | import path from "path"; 12 | 13 | export function copyFileSync(source, target) { 14 | var targetFile = target; 15 | 16 | // If target is a directory, a new file with the same name will be created 17 | if (existsSync(target)) { 18 | if (lstatSync(target).isDirectory()) { 19 | targetFile = path.join(target, path.basename(source)); 20 | } 21 | } 22 | 23 | writeFileSync(targetFile, readFileSync(source)); 24 | } 25 | 26 | export function copyFolderRecursiveSync(source, target) { 27 | var files = []; 28 | 29 | // Check if folder needs to be created or integrated 30 | var targetFolder = path.join(target, path.basename(source)); 31 | if (!existsSync(targetFolder)) { 32 | mkdirSync(targetFolder); 33 | } 34 | 35 | // Copy 36 | if (lstatSync(source).isDirectory()) { 37 | files = readdirSync(source); 38 | files.forEach(function (file) { 39 | var curSource = path.join(source, file); 40 | if (lstatSync(curSource).isDirectory()) { 41 | copyFolderRecursiveSync(curSource, targetFolder); 42 | } else { 43 | copyFileSync(curSource, targetFolder); 44 | } 45 | }); 46 | } 47 | } 48 | 49 | export function clearFolder(target) { 50 | if (existsSync(target)) { 51 | rmSync(target, { recursive: true, force: true }); 52 | } 53 | 54 | mkdirSync(target, { recursive: true }); 55 | } 56 | 57 | export function dateFormat(fmt, date) { 58 | let ret; 59 | const opt = { 60 | "Y+": date.getFullYear().toString(), 61 | "m+": (date.getMonth() + 1).toString(), 62 | "d+": date.getDate().toString(), 63 | "H+": date.getHours().toString(), 64 | "M+": date.getMinutes().toString(), 65 | "S+": date.getSeconds().toString(), 66 | }; 67 | for (let k in opt) { 68 | ret = new RegExp("(" + k + ")").exec(fmt); 69 | if (ret) { 70 | fmt = fmt.replace( 71 | ret[1], 72 | ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, "0"), 73 | ); 74 | } 75 | } 76 | return fmt; 77 | } 78 | 79 | export class Logger { 80 | static log(...args) { 81 | console.log(...args); 82 | } 83 | 84 | // red 85 | static error(...args) { 86 | console.error("\u001b[31m [ERROR]", ...args, "\u001b[0m"); 87 | } 88 | 89 | // yellow 90 | static warn(...args) { 91 | console.warn("\u001b[33m [WARN]", ...args, "\u001b[0m"); 92 | } 93 | 94 | // blue 95 | static debug(...args) { 96 | console.log("\u001b[34m [DEBUG]\u001b[0m", ...args); 97 | } 98 | 99 | // green 100 | static info(...args) { 101 | console.log("\u001b[32m [INFO]", ...args, "\u001b[0m"); 102 | } 103 | 104 | // cyan 105 | static trace(...args) { 106 | console.log("\u001b[36m [TRACE]\u001b[0m", ...args); 107 | } 108 | } 109 | 110 | export function isRunning(query, cb) { 111 | let platform = process.platform; 112 | let cmd = ""; 113 | switch (platform) { 114 | case "win32": 115 | cmd = `tasklist`; 116 | break; 117 | case "darwin": 118 | cmd = `ps -ax | grep ${query}`; 119 | break; 120 | case "linux": 121 | cmd = `ps -A`; 122 | break; 123 | default: 124 | break; 125 | } 126 | exec(cmd, (err, stdout, stderr) => { 127 | cb(stdout.toLowerCase().indexOf(query.toLowerCase()) > -1); 128 | }); 129 | } 130 | -------------------------------------------------------------------------------- /scripts/zotero-cmd-template.json: -------------------------------------------------------------------------------- 1 | { 2 | "usage": "Copy and rename this file to zotero-cmd.json. Edit the cmd.", 3 | "killZoteroWindows": "taskkill /f /im zotero.exe", 4 | "killZoteroUnix": "kill -9 $(ps -x | grep '[z]otero' | awk '{print $1}')", 5 | "exec": { 6 | "@comment-zoteroBinPath": "Please input the path of the Zotero binary file in `zoteroBinPath`.", 7 | "@comment-zoteroBinPath-tip": "The path delimiter should be escaped as `\\` for win32. The path is `*/Zotero.app/Contents/MacOS/zotero` for MacOS.", 8 | "zoteroBinPath": "/path/to/zotero.exe", 9 | 10 | "@comment-profilePath": "Please input the path of the profile used for development in `profilePath`.", 11 | "@comment-profilePath-tip": "Start the profile manager by `/path/to/zotero.exe -p` to create a profile for development", 12 | "@comment-profilePath-see": "https://www.zotero.org/support/kb/profile_directory", 13 | "profilePath": "/path/to/profile", 14 | 15 | "@comment-dataDir": "Please input the directory where the database is located in dataDir", 16 | "@comment-dataDir-tip": "If this field is kept empty, Zotero will start with the default data.", 17 | "@comment-dataDir-see": "https://www.zotero.org/support/zotero_data", 18 | "dataDir": "" 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/addon.ts: -------------------------------------------------------------------------------- 1 | import { DialogHelper } from "zotero-plugin-toolkit/dist/helpers/dialog"; 2 | import hooks from "./hooks"; 3 | import { createZToolkit } from "./utils/ztoolkit"; 4 | 5 | class Addon { 6 | public data: { 7 | alive: boolean; 8 | // Env type, see build.js 9 | env: "development" | "production"; 10 | ztoolkit: ZToolkit; 11 | locale?: { 12 | current: any; 13 | }; 14 | prefs?: { 15 | window: Window; 16 | }; 17 | dialog?: DialogHelper; 18 | }; 19 | // Lifecycle hooks 20 | public hooks: typeof hooks; 21 | // APIs 22 | public api: object; 23 | 24 | constructor() { 25 | this.data = { 26 | alive: true, 27 | env: __env__, 28 | ztoolkit: createZToolkit(), 29 | }; 30 | this.hooks = hooks; 31 | this.api = {}; 32 | } 33 | } 34 | 35 | export default Addon; 36 | -------------------------------------------------------------------------------- /src/hooks.ts: -------------------------------------------------------------------------------- 1 | import { RegisterFactory, UIFactory } from "./modules/Common"; 2 | import { config } from "../package.json"; 3 | import { getString, initLocale } from "./utils/locale"; 4 | import { registerPrefsScripts } from "./modules/preferenceScript"; 5 | import { createZToolkit } from "./utils/ztoolkit"; 6 | import { tldrs } from "./modules/dataStorage"; 7 | import { TLDRFetcher } from "./modules/tldrFetcher"; 8 | 9 | async function onStartup() { 10 | await Promise.all([ 11 | Zotero.initializationPromise, 12 | Zotero.unlockPromise, 13 | Zotero.uiReadyPromise, 14 | ]); 15 | 16 | // TODO: Remove this after zotero#3387 is merged 17 | if (__env__ === "development") { 18 | // Keep in sync with the scripts/startup.mjs 19 | const loadDevToolWhen = `Plugin ${config.addonID} startup`; 20 | ztoolkit.log(loadDevToolWhen); 21 | } 22 | 23 | initLocale(); 24 | 25 | await tldrs.getAsync(); 26 | 27 | RegisterFactory.registerNotifier(); 28 | 29 | await onMainWindowLoad(window); 30 | } 31 | 32 | async function onMainWindowLoad(win: Window): Promise { 33 | // Create ztoolkit for every window 34 | addon.data.ztoolkit = createZToolkit(); 35 | 36 | (win as any).MozXULElement.insertFTLIfNeeded( 37 | `${config.addonRef}-mainWindow.ftl`, 38 | ); 39 | 40 | UIFactory.registerRightClickMenuItem(); 41 | 42 | UIFactory.registerRightClickCollectionMenuItem(); 43 | 44 | UIFactory.registerTLDRItemBoxRow(); 45 | 46 | onLoad(); 47 | } 48 | 49 | async function onMainWindowUnload(win: Window): Promise { 50 | ztoolkit.unregisterAll(); 51 | addon.data.dialog?.window?.close(); 52 | } 53 | 54 | function onShutdown(): void { 55 | ztoolkit.unregisterAll(); 56 | addon.data.dialog?.window?.close(); 57 | // Remove addon object 58 | addon.data.alive = false; 59 | delete Zotero[config.addonInstance]; 60 | } 61 | 62 | /** 63 | * This function is just an example of dispatcher for Notify events. 64 | * Any operations should be placed in a function to keep this funcion clear. 65 | */ 66 | async function onNotify( 67 | event: string, 68 | type: string, 69 | ids: Array, 70 | extraData: { [key: string]: any }, 71 | ) { 72 | Zotero.log(`${event} ${type} ${ids}, ${extraData}`); 73 | if (event == "add" && type == "item" && ids.length > 0) { 74 | onNotifyAddItems(ids); 75 | } else if (event == "delete" && type == "item" && ids.length > 0) { 76 | noNotifyDeleteItem(ids); 77 | } 78 | } 79 | 80 | /** 81 | * This function is just an example of dispatcher for Preference UI events. 82 | * Any operations should be placed in a function to keep this funcion clear. 83 | * @param type event type 84 | * @param data event data 85 | */ 86 | async function onPrefsEvent(type: string, data: { [key: string]: any }) { 87 | switch (type) { 88 | case "load": 89 | registerPrefsScripts(data.window); 90 | break; 91 | default: 92 | return; 93 | } 94 | } 95 | 96 | function onLoad() { 97 | (async () => { 98 | let needFetchItems: Zotero.Item[] = []; 99 | for (const lib of Zotero.Libraries.getAll()) { 100 | needFetchItems = needFetchItems.concat( 101 | (await Zotero.Items.getAll(lib.id)).filter((item: Zotero.Item) => { 102 | return item.isRegularItem(); 103 | }), 104 | ); 105 | } 106 | onUpdateItems(needFetchItems, false); 107 | })(); 108 | } 109 | 110 | function noNotifyDeleteItem(ids: (string | number)[]) { 111 | tldrs.modify((data) => { 112 | ids.forEach((id) => { 113 | delete data[id]; 114 | }); 115 | return data; 116 | }); 117 | } 118 | 119 | function onNotifyAddItems(ids: (string | number)[]) { 120 | const addedRegularItems: Zotero.Item[] = []; 121 | for (const id of ids) { 122 | const item = Zotero.Items.get(id); 123 | if (item.isRegularItem()) { 124 | addedRegularItems.push(item); 125 | } 126 | } 127 | (async function () { 128 | await Zotero.Promise.delay(3000); 129 | onUpdateItems(addedRegularItems, false); 130 | })(); 131 | } 132 | 133 | function onUpdateItems(items: Zotero.Item[], forceFetch: boolean = false) { 134 | items = items.filter((item: Zotero.Item) => { 135 | if (!item.getField("title")) { 136 | return false; 137 | } 138 | if (!forceFetch && item.key in tldrs.get()) { 139 | return false; 140 | } 141 | return true; 142 | }); 143 | if (items.length <= 0) { 144 | return; 145 | } 146 | const newPopWin = (closeOnClick = true) => { 147 | return new ztoolkit.ProgressWindow(config.addonName, { 148 | closeOnClick: closeOnClick, 149 | }).createLine({ 150 | text: `${getString("popWindow-waiting")}: ${items.length}; ${getString( 151 | "popWindow-succeed", 152 | )}: 0; ${getString("popWindow-failed")}: 0`, 153 | type: "default", 154 | progress: 0, 155 | }); 156 | }; 157 | const popupWin = newPopWin().show(-1); 158 | (async function () { 159 | const count = items.length; 160 | const failedItems: Zotero.Item[] = []; 161 | const succeedItems: Zotero.Item[] = []; 162 | await (async function () { 163 | for (const [index, item] of items.entries()) { 164 | (await new TLDRFetcher(item).fetchTLDR()) 165 | ? succeedItems.push(item) 166 | : failedItems.push(item); 167 | await Zotero.Promise.delay(50); 168 | popupWin.changeLine({ 169 | progress: (index * 100) / count, 170 | text: `${getString("popWindow-waiting")}: ${ 171 | count - index - 1 172 | }; ${getString("popWindow-succeed")}: ${ 173 | succeedItems.length 174 | }; ${getString("popWindow-failed")}: ${failedItems.length}`, 175 | }); 176 | } 177 | })(); 178 | 179 | await (async function () { 180 | popupWin.changeLine({ 181 | type: "success", 182 | progress: 100, 183 | text: `${getString("popWindow-succeed")}: ${ 184 | succeedItems.length 185 | }; ${getString("popWindow-failed")}: ${failedItems.length}`, 186 | }); 187 | popupWin.startCloseTimer(3000); 188 | })(); 189 | })(); 190 | } 191 | 192 | // Add your hooks here. For element click, etc. 193 | // Keep in mind hooks only do dispatch. Don't add code that does real jobs in hooks. 194 | // Otherwise the code would be hard to read and maintain. 195 | 196 | export default { 197 | onStartup, 198 | onShutdown, 199 | onMainWindowLoad, 200 | onMainWindowUnload, 201 | onNotify, 202 | onPrefsEvent, 203 | onUpdateItems, 204 | }; 205 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { BasicTool } from "zotero-plugin-toolkit/dist/basic"; 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 | defineGlobal("window"); 9 | defineGlobal("document"); 10 | defineGlobal("ZoteroPane"); 11 | defineGlobal("Zotero_Tabs"); 12 | _globalThis.addon = new Addon(); 13 | defineGlobal("ztoolkit", () => { 14 | return _globalThis.addon.data.ztoolkit; 15 | }); 16 | Zotero[config.addonInstance] = addon; 17 | } 18 | 19 | function defineGlobal(name: Parameters[0]): void; 20 | function defineGlobal(name: string, getter: () => any): void; 21 | function defineGlobal(name: string, getter?: () => any) { 22 | Object.defineProperty(_globalThis, name, { 23 | get() { 24 | return getter ? getter() : basicTool.getGlobal(name); 25 | }, 26 | }); 27 | } 28 | -------------------------------------------------------------------------------- /src/modules/Common.ts: -------------------------------------------------------------------------------- 1 | import { config } from "../../package.json"; 2 | import { getString } from "../utils/locale"; 3 | import { tldrs } from "./dataStorage"; 4 | 5 | export class RegisterFactory { 6 | // 注册zotero的通知 7 | static registerNotifier() { 8 | const callback = { 9 | notify: async ( 10 | event: string, 11 | type: string, 12 | ids: number[] | string[], 13 | extraData: { [key: string]: any }, 14 | ) => { 15 | if (!addon?.data.alive) { 16 | this.unregisterNotifier(notifierID); 17 | return; 18 | } 19 | addon.hooks.onNotify(event, type, ids, extraData); 20 | }, 21 | }; 22 | 23 | // Register the callback in Zotero as an item observer 24 | const notifierID = Zotero.Notifier.registerObserver(callback, ["item"]); 25 | 26 | // Unregister callback when the window closes (important to avoid a memory leak) 27 | window.addEventListener( 28 | "unload", 29 | (e: Event) => { 30 | this.unregisterNotifier(notifierID); 31 | }, 32 | false, 33 | ); 34 | } 35 | 36 | private static unregisterNotifier(notifierID: string) { 37 | Zotero.Notifier.unregisterObserver(notifierID); 38 | } 39 | } 40 | 41 | export class UIFactory { 42 | // item右键菜单 43 | static registerRightClickMenuItem() { 44 | const menuIcon = `chrome://${config.addonRef}/content/icons/favicon.png`; 45 | // item menuitem with icon 46 | ztoolkit.Menu.register("item", { 47 | tag: "menuitem", 48 | id: "zotero-itemmenu-tldr", 49 | label: getString("menuitem-updatetldrlabel"), 50 | commandListener: (ev) => { 51 | const selectedItems = ZoteroPane.getSelectedItems() ?? []; 52 | addon.hooks.onUpdateItems(selectedItems, selectedItems.length <= 1); 53 | }, 54 | icon: menuIcon, 55 | }); 56 | } 57 | 58 | // collection右键菜单 59 | static registerRightClickCollectionMenuItem() { 60 | const menuIcon = `chrome://${config.addonRef}/content/icons/favicon.png`; 61 | ztoolkit.Menu.register("collection", { 62 | tag: "menuitem", 63 | id: "zotero-collectionmenu-tldr", 64 | label: getString("menucollection-updatetldrlabel"), 65 | commandListener: (ev) => 66 | addon.hooks.onUpdateItems( 67 | ZoteroPane.getSelectedCollection()?.getChildItems() ?? [], 68 | false, 69 | ), 70 | icon: menuIcon, 71 | }); 72 | } 73 | 74 | // tldr行 75 | static async registerTLDRItemBoxRow() { 76 | const itemTLDR = (item: Zotero.Item) => { 77 | const noteKey = tldrs.get()[item.key]; 78 | if (noteKey) { 79 | const obj = Zotero.Items.getByLibraryAndKey(item.libraryID, noteKey); 80 | if ( 81 | obj && 82 | obj instanceof Zotero.Item && 83 | item.getNotes().includes(obj.id) 84 | ) { 85 | let str = obj.getNote(); 86 | if (str.startsWith("

TL;DR

\n

")) { 87 | str = str.slice("

TL;DR

\n

".length); 88 | } 89 | if (str.endsWith("

")) { 90 | str = str.slice(0, -4); 91 | } 92 | return str; 93 | } 94 | } 95 | return ""; 96 | }; 97 | Zotero.ItemPaneManager.registerSection({ 98 | paneID: config.addonRef, 99 | pluginID: config.addonID, 100 | header: { 101 | l10nID: `${config.addonRef}-itemPaneSection-header`, 102 | icon: `chrome://${config.addonRef}/content/icons/favicon@16.png`, 103 | }, 104 | sidenav: { 105 | l10nID: `${config.addonRef}-itemPaneSection-sidenav`, 106 | icon: `chrome://${config.addonRef}/content/icons/favicon@20.png`, 107 | }, 108 | onRender: ({ body, item }: any) => { 109 | let tldr = itemTLDR(item); 110 | if (tldr.length <= 0 && item.parentItem) { 111 | tldr = itemTLDR(item.parentItem); 112 | } 113 | body.textContent = tldr; 114 | }, 115 | }); 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /src/modules/dataStorage.ts: -------------------------------------------------------------------------------- 1 | import { config } from "../../package.json"; 2 | 3 | export class Data { 4 | [x: string]: any; 5 | private dataType: string; 6 | private filePath?: string; 7 | private _data: Record; 8 | 9 | constructor(dataType: string) { 10 | this.dataType = dataType; 11 | this._data = {} as Record; 12 | } 13 | 14 | async getAsync() { 15 | await this.initDataIfNeed(); 16 | return this.data; 17 | } 18 | 19 | get() { 20 | return this.data; 21 | } 22 | 23 | async modify( 24 | action: (data: Record) => Record | Promise>, 25 | ) { 26 | await this.initDataIfNeed(); 27 | const data = this.data; 28 | const newData = await action(data); 29 | if (this.filePath) { 30 | try { 31 | await IOUtils.writeJSON(this.filePath, newData, { 32 | mode: "overwrite", 33 | compress: false, 34 | }); 35 | this.data = newData; 36 | return newData; 37 | } catch (error) { 38 | return data; 39 | } 40 | } else { 41 | this.data = newData; 42 | return newData; 43 | } 44 | } 45 | 46 | async delete() { 47 | if (this.filePath) { 48 | try { 49 | await IOUtils.remove(this.filePath); 50 | this.data = {} as Record; 51 | return true; 52 | } catch (error) { 53 | return false; 54 | } 55 | } else { 56 | this.data = {} as Record; 57 | return true; 58 | } 59 | } 60 | 61 | private get data() { 62 | return this._data; 63 | } 64 | 65 | private set data(value: Record) { 66 | this._data = value; 67 | } 68 | 69 | private async initDataIfNeed() { 70 | if (this.inited) { 71 | return; 72 | } 73 | this.inited = true; 74 | 75 | const prefsFile = PathUtils.join(PathUtils.profileDir, "prefs.js"); 76 | const prefs = await Zotero.Profile.readPrefsFromFile(prefsFile); 77 | let dir = prefs["extensions.zotero.dataDir"]; 78 | if (dir) { 79 | dir = PathUtils.join(dir, config.addonName); 80 | } else { 81 | dir = PathUtils.join( 82 | PathUtils.profileDir, 83 | "extensions", 84 | config.addonName, 85 | ); 86 | } 87 | IOUtils.makeDirectory(dir, { 88 | createAncestors: true, 89 | ignoreExisting: true, 90 | }); 91 | this.filePath = PathUtils.join(dir, this.dataType); 92 | try { 93 | this.data = await IOUtils.readJSON(this.filePath, { decompress: false }); 94 | } catch (error) { 95 | this.data = {} as Record; 96 | } 97 | } 98 | } 99 | 100 | export class DataStorage { 101 | private dataMap: { [key: string]: Data } = {}; 102 | 103 | private static shared = new DataStorage(); 104 | 105 | static instance( 106 | dataType: string, 107 | ): Data { 108 | if (this.shared.dataMap[dataType] === undefined) { 109 | const data = new Data(dataType); 110 | this.shared.dataMap[dataType] = data; 111 | return data; 112 | } else { 113 | return this.shared.dataMap[dataType]; 114 | } 115 | } 116 | 117 | private constructor() { 118 | // empty 119 | } 120 | } 121 | 122 | export const tldrs = DataStorage.instance( 123 | "fetchedItems.json", 124 | ); 125 | -------------------------------------------------------------------------------- /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 | }; 11 | } else { 12 | addon.data.prefs.window = _window; 13 | } 14 | bindPrefEvents(); 15 | } 16 | 17 | function bindPrefEvents() {} 18 | -------------------------------------------------------------------------------- /src/modules/tldrFetcher.ts: -------------------------------------------------------------------------------- 1 | import { tldrs } from "./dataStorage"; 2 | 3 | type SemanticScholarItemInfo = { 4 | title?: string; 5 | abstract?: string; 6 | tldr?: string; 7 | }; 8 | 9 | export class TLDRFetcher { 10 | private readonly zoteroItem: Zotero.Item; 11 | private readonly title?: string; 12 | private readonly abstract?: string; 13 | 14 | constructor(item: Zotero.Item) { 15 | this.zoteroItem = item; 16 | if (item.isRegularItem()) { 17 | this.title = item.getField("title") as string; 18 | this.abstract = item.getField("abstractNote") as string; 19 | } 20 | } 21 | 22 | async fetchTLDR() { 23 | if (!this.title || this.title.length <= 0) { 24 | return false; 25 | } 26 | const noteKey = (await tldrs.getAsync())[this.zoteroItem.key]; 27 | try { 28 | const infos = await this.fetchRelevanceItemInfos(this.title); 29 | for (const info of infos) { 30 | let match = false; 31 | if (info.title && this.title && this.checkLCS(info.title, this.title)) { 32 | match = true; 33 | } else if ( 34 | info.abstract && 35 | this.abstract && 36 | this.checkLCS(info.abstract, this.abstract) 37 | ) { 38 | match = true; 39 | } 40 | if (match && info.tldr) { 41 | let note = new Zotero.Item("note"); 42 | if (noteKey) { 43 | const obj = Zotero.Items.getByLibraryAndKey( 44 | this.zoteroItem.libraryID, 45 | noteKey, 46 | ); 47 | if ( 48 | obj && 49 | obj instanceof Zotero.Item && 50 | this.zoteroItem.getNotes().includes(obj.id) 51 | ) { 52 | note = obj; 53 | } 54 | } 55 | note.setNote(`

TL;DR

\n

${info.tldr}

`); 56 | note.parentID = this.zoteroItem.id; 57 | await note.saveTx(); 58 | await tldrs.modify((data: any) => { 59 | data[this.zoteroItem.key] = note.key; 60 | return data; 61 | }); 62 | return true; 63 | } 64 | } 65 | await tldrs.modify((data: any) => { 66 | data[this.zoteroItem.key] = false; 67 | return data; 68 | }); 69 | } catch (error) { 70 | Zotero.log(`post semantic scholar request error: ${error}`); 71 | } 72 | } 73 | 74 | private async fetchRelevanceItemInfos( 75 | title: string, 76 | ): Promise { 77 | const semanticScholarURL = "https://www.semanticscholar.org/api/1/search"; 78 | const params = { 79 | queryString: title, 80 | page: 1, 81 | pageSize: 10, 82 | sort: "relevance", 83 | authors: [], 84 | coAuthors: [], 85 | venues: [], 86 | performTitleMatch: true, 87 | requireViewablePdf: false, 88 | includeTldrs: true, 89 | }; 90 | const resp = await Zotero.HTTP.request("POST", semanticScholarURL, { 91 | headers: { "Content-Type": "application/json" }, 92 | body: JSON.stringify(params), 93 | }); 94 | if (resp.status === 200) { 95 | const results = JSON.parse(resp.response).results; 96 | return results.map((item: any) => { 97 | const result = { 98 | title: item.title.text, 99 | abstract: item.paperAbstract.text, 100 | tldr: undefined, 101 | }; 102 | if (item.tldr) { 103 | result.tldr = item.tldr.text; 104 | } 105 | return result; 106 | }); 107 | } 108 | return []; 109 | } 110 | 111 | private checkLCS(pattern: string, content: string): boolean { 112 | const LCS = StringMatchUtils.longestCommonSubsequence(pattern, content); 113 | return LCS.length >= Math.max(pattern.length, content.length) * 0.9; 114 | } 115 | } 116 | 117 | class StringMatchUtils { 118 | static longestCommonSubsequence(text1: string, text2: string): string { 119 | const m = text1.length; 120 | const n = text2.length; 121 | 122 | const dp: number[][] = new Array(m + 1); 123 | for (let i = 0; i <= m; i++) { 124 | dp[i] = new Array(n + 1).fill(0); 125 | } 126 | 127 | for (let i = 1; i <= m; i++) { 128 | for (let j = 1; j <= n; j++) { 129 | if (text1[i - 1] === text2[j - 1]) { 130 | dp[i][j] = dp[i - 1][j - 1] + 1; 131 | } else { 132 | dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]); 133 | } 134 | } 135 | } 136 | 137 | let i = m, 138 | j = n; 139 | const lcs: string[] = []; 140 | while (i > 0 && j > 0) { 141 | if (text1[i - 1] === text2[j - 1]) { 142 | lcs.unshift(text1[i - 1]); 143 | i--; 144 | j--; 145 | } else if (dp[i - 1][j] > dp[i][j - 1]) { 146 | i--; 147 | } else { 148 | j--; 149 | } 150 | } 151 | 152 | return lcs.join(""); 153 | } 154 | 155 | // static minWindow(s: string, t: string): [number, number] | null { 156 | // const m = s.length, n = t.length 157 | // let start = -1, minLen = Number.MAX_SAFE_INTEGER, i = 0, j = 0, end; 158 | // while (i < m) { 159 | // if (s[i] == t[j]) { 160 | // if (++j == n) { 161 | // end = i + 1; 162 | // while (--j >= 0) { 163 | // while (s[i--] != t[j]); 164 | // } 165 | // ++i; ++j; 166 | // if (end - i < minLen) { 167 | // minLen = end - i; 168 | // start = i; 169 | // } 170 | // } 171 | // } 172 | // ++i; 173 | // } 174 | // return start == -1 ? null : [start, minLen]; 175 | // } 176 | } 177 | -------------------------------------------------------------------------------- /src/utils/locale.ts: -------------------------------------------------------------------------------- 1 | import { config } from "../../package.json"; 2 | 3 | export { initLocale, getString }; 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 | return pattern.attributes[branch] || localStringWithPrefix; 76 | } else { 77 | return pattern.value || localStringWithPrefix; 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /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/dist/basic"; 33 | import { UITool } from "zotero-plugin-toolkit/dist/tools/ui"; 34 | import { PreferencePaneManager } from "zotero-plugin-toolkit/dist/managers/preferencePane"; 35 | 36 | class MyToolkit extends BasicTool { 37 | UI: UITool; 38 | PreferencePane: PreferencePaneManager; 39 | 40 | constructor() { 41 | super(); 42 | this.UI = new UITool(this); 43 | this.PreferencePane = new PreferencePaneManager(this); 44 | } 45 | 46 | unregisterAll() { 47 | unregister(this); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /typings/global.d.ts: -------------------------------------------------------------------------------- 1 | declare const _globalThis: { 2 | [key: string]: any; 3 | Zotero: _ZoteroTypes.Zotero; 4 | ZoteroPane: _ZoteroTypes.ZoteroPane; 5 | Zotero_Tabs: typeof Zotero_Tabs; 6 | window: Window; 7 | document: Document; 8 | ztoolkit: ZToolkit; 9 | addon: typeof addon; 10 | }; 11 | 12 | declare type ZToolkit = ReturnType< 13 | typeof import("../src/utils/ztoolkit").createZToolkit 14 | >; 15 | 16 | declare const ztoolkit: ZToolkit; 17 | 18 | declare const rootURI: string; 19 | 20 | declare const addon: import("../src/addon").default; 21 | 22 | declare const __env__: "production" | "development"; 23 | 24 | declare class Localization {} 25 | -------------------------------------------------------------------------------- /update.json: -------------------------------------------------------------------------------- 1 | { 2 | "addons": { 3 | "zoterotldr@syt.com": { 4 | "updates": [ 5 | { 6 | "version": "1.0.7", 7 | "update_link": "undefined/latest/download/zotero-tldr.xpi", 8 | "applications": { 9 | "zotero": { 10 | "strict_min_version": "6.999" 11 | } 12 | } 13 | } 14 | ] 15 | } 16 | } 17 | } 18 | --------------------------------------------------------------------------------