Initial commit of Zotero PDF Copier & Renamer

This commit is contained in:
MD. PARVEJ HOSSAIN 2026-06-10 23:10:05 +06:00
commit a1f83836e7
57 changed files with 9342 additions and 0 deletions

30
.env.example Normal file
View File

@ -0,0 +1,30 @@
# Usage:
# Copy this file as `.env` and fill in the variables below as instructed.
# If you are developing more than one plugin, you can store the bin path and
# profile path in the system environment variables, which can be omitted here.
# The path of the Zotero binary file.
# The path delimiter should be escaped as `\\` for win32.
# The path is `*/Zotero.app/Contents/MacOS/zotero` for MacOS.
ZOTERO_PLUGIN_ZOTERO_BIN_PATH = /path/to/zotero.exe
# The path of the profile used for development.
# Start the profile manager by `/path/to/zotero.exe -p` to create a profile for development.
# @see https://www.zotero.org/support/kb/profile_directory
ZOTERO_PLUGIN_PROFILE_PATH = /path/to/profile
# The directory where the database is located.
# If this field is kept empty, Zotero will start with the default data.
# @see https://www.zotero.org/support/zotero_data
ZOTERO_PLUGIN_DATA_DIR =
# Custom commands to kill Zotero processes.
# Commands for different platforms are already built into zotero-plugin,
# if the built-in commands are not suitable for your needs, please modify this variable.
# ZOTERO_PLUGIN_KILL_COMMAND =
# GitHub Token
# For scaffold auto create release and upload assets.
# Fill in this variable if you are publishing locally instead of CI.
# GITHUB_TOKEN =

1
.gitattributes vendored Normal file
View File

@ -0,0 +1 @@
* text=auto eol=lf

16
.github/dependabot.yml vendored Normal file
View File

@ -0,0 +1,16 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
version: 2
updates:
- package-ecosystem: "npm" # See documentation for possible values
directory: "/" # Location of package manifests
schedule:
interval: "weekly"
groups:
all-non-major:
update-types:
- "minor"
- "patch"

4
.github/renovate.json vendored Normal file
View File

@ -0,0 +1,4 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"extends": ["github>zotero-plugin-dev/renovate-config"]
}

44
.github/workflows/ci.yml vendored Normal file
View File

@ -0,0 +1,44 @@
name: CI
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
lint:
runs-on: ubuntu-latest
env:
GITHUB_TOKEN: ${{ secrets.GitHub_TOKEN }}
steps:
- name: Setup JS
uses: zotero-plugin-dev/workflows/setup-js@main
- name: Run Lint
run: npm run lint:check
build:
runs-on: ubuntu-latest
env:
GITHUB_TOKEN: ${{ secrets.GitHub_TOKEN }}
steps:
- name: Setup JS
uses: zotero-plugin-dev/workflows/setup-js@main
- name: Run Build
run: npm run build
- name: Upload build result
uses: actions/upload-artifact@v4
with:
name: build-result
path: .scaffold/build
test:
runs-on: ubuntu-latest
needs:
- build
steps:
- name: Setup JS
uses: zotero-plugin-dev/workflows/setup-js@main
- run: npm run test

20
.github/workflows/issue-bot.yml vendored Normal file
View File

@ -0,0 +1,20 @@
name: Issue Bot
on:
issues:
types:
- labeled
issue_comment:
types:
- created
schedule:
- cron: "30 1 * * *"
workflow_dispatch:
permissions:
issues: write
pull-requests: write
jobs:
issue-bot:
uses: zotero-plugin-dev/workflows/.github/workflows/issue-bot.yml@main

21
.github/workflows/release.yml vendored Normal file
View File

@ -0,0 +1,21 @@
name: Release
on:
push:
tags:
- v**
permissions:
contents: write
issues: write
pull-requests: write
jobs:
create-release:
uses: zotero-plugin-dev/workflows/.github/workflows/release-plugin.yml@main
# You can customize any of the inputs here.
# If you omit an input, its default value will be used.
with:
build: "npm run build"
release: "npm run release"
secrets: inherit

16
.gitignore vendored Normal file
View File

@ -0,0 +1,16 @@
# dot files
.DS_Store
# Node.js
node_modules
pnpm-lock.yaml
yarn.lock
# TSC
tsconfig.tsbuildinfo
# Scaffold
.env
.scaffold
build
logs

7
.prettierignore Normal file
View File

@ -0,0 +1,7 @@
.vscode
build
logs
node_modules
package-lock.json
yarn.lock
pnpm-lock.yaml

7
.vscode/extensions.json vendored Normal file
View File

@ -0,0 +1,7 @@
{
"recommendations": [
"dbaeumer.vscode-eslint",
"esbenp.prettier-vscode",
"macabeus.vscode-fluent"
]
}

22
.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,22 @@
{
// 使用 IntelliSense 了解相关属性。
// 悬停以查看现有属性的描述。
// 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Start",
"runtimeExecutable": "npm",
"runtimeArgs": ["run", "start"]
},
{
"type": "node",
"request": "launch",
"name": "Build",
"runtimeExecutable": "npm",
"runtimeArgs": ["run", "build"]
}
]
}

8
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,8 @@
{
"editor.formatOnType": false,
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit"
},
"typescript.tsdk": "node_modules/typescript/lib"
}

45
.vscode/toolkit.code-snippets vendored Normal file
View File

@ -0,0 +1,45 @@
{
"appendElement - full": {
"scope": "javascript,typescript",
"prefix": "appendElement",
"body": [
"appendElement({",
"\ttag: '${1:div}',",
"\tid: '${2:id}',",
"\tnamespace: '${3:html}',",
"\tclassList: ['${4:class}'],",
"\tstyles: {${5:style}: '$6'},",
"\tproperties: {},",
"\tattributes: {},",
"\t[{ '${7:onload}', (e: Event) => $8, ${9:false} }],",
"\tcheckExistanceParent: ${10:HTMLElement},",
"\tignoreIfExists: ${11:true},",
"\tskipIfExists: ${12:true},",
"\tremoveIfExists: ${13:true},",
"\tcustomCheck: (doc: Document, options: ElementOptions) => ${14:true},",
"\tchildren: [$15]",
"}, ${16:container});"
]
},
"appendElement - minimum": {
"scope": "javascript,typescript",
"prefix": "appendElement",
"body": "appendElement({ tag: '$1' }, $2);"
},
"register Notifier": {
"scope": "javascript,typescript",
"prefix": "registerObserver",
"body": [
"registerObserver({",
"\t notify: (",
"\t\tevent: _ZoteroTypes.Notifier.Event,",
"\t\ttype: _ZoteroTypes.Notifier.Type,",
"\t\tids: string[],",
"\t\textraData: _ZoteroTypes.anyObj",
"\t) => {",
"\t\t$0",
"\t}",
"});"
]
}
}

661
LICENSE Normal file
View File

@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<http://www.gnu.org/licenses/>.

78
README.md Normal file
View File

@ -0,0 +1,78 @@
# Zotero PDF Copier & Renamer
A powerful, lightweight, and restartless add-on for **Zotero 7, 8, and 9** that lets you copy attached PDF documents from selected bibliography references into any folder on your computer. Copied PDFs are automatically renamed based on the paper's title (sanitized for safe OS filenames) and index-deduplicated.
Developed and designed with custom branding and a native graphical interface.
---
## Developer Details
- **Author**: Md. Parvej Hossain
- **Email**: [contact@parvej.me](mailto:contact@parvej.me)
- **Plugin ID**: `zotero-pdf-copier-renamer@parvej.me`
- **Icon Artwork**: `copy_9376689.png`
---
## Key Features
- **Direct Context Menu Access**: Right-click on any selected items in the main library grid pane to start copying instantly.
- **Visual Icon Registration**: Custom branded icon next to the context menu command and inside the Zotero Extensions listing for quick visual recognition.
- **Smart PDF Copying**: Filters all selected items to only copy actual PDF files (skips notes, web links, or citations that do not have attachments).
- **Auto-Renaming by Title**: Uses the parent paper's metadata title (e.g. `Prediction of Track of Super Cyclone Amphan using WRF-ARW Model.pdf`) instead of cryptic random hashes.
- **Full Filename Sanitization**: Automatically strips characters that are illegal or reserved in operating system path strings (such as `:`, `?`, `/`, `\`, `*`, `|`, `"`, `<`, `>`).
- **Smart Index Deduplication**:
- If a paper reference contains multiple PDF attachments, the copier appends numbered suffixes (e.g. `Paper Title_(1).pdf`, `Paper Title_(2).pdf`).
- If a file with the same name already exists in the target destination folder, the copier automatically adds a sequence suffix to prevent overwriting existing work.
- **Native OS Folder Picker**: Directly launches the native operating system folder selection dialog (handling modern `window.browsingContext` requirements on Zotero 9/Gecko 128+).
- **Graphical Progress Interface**: Features Zotero's native `ItemProgress` layout showing an animated progress bar, real-time completion percentage, and the current file being copied.
- **Auto-Close Timers**: Automatically closes the notification card 5 seconds after copying is complete. Includes clickable dismiss control (click anywhere on the notification card to close immediately).
---
## File Architecture
- **`manifest.json`**: Describes metadata and specifies Zotero 7 through Zotero 9 compatibility limits.
- **`package.json`**: Configures compilation parameters, dependencies, and packaging configurations.
- **`zotero-plugin.config.ts`**: Builds and bundles the typescript source code utilizing target `firefox115`.
- **`build.cjs`**: A clean, CommonJS Node.js script that compiles typescript assets using `zotero-plugin build` and packages them into the final `zotero-pdf-copier-renamer.xpi` installer archive.
- **`addon/`**: Folder containing the extension's static assets, resources, preferences, and chrome loaders.
- **`src/`**: Folder containing the TypeScript source code. Core operations are implemented in `src/hooks.ts`.
---
## Compilation & Building
To package the extension from source:
1. **Install Prerequisites**: Ensure you have Node.js and `npm` installed on your machine.
2. **Install Dependencies**: Open a terminal in this directory and run:
```bash
npm install
```
3. **Compile and Package**: Run the CommonJS builder script:
```bash
node build.cjs
```
This compiles the source code and generates the installer file **`zotero-pdf-copier-renamer.xpi`** in the project root.
---
## Installation Guide
1. Open **Zotero** on your computer.
2. Go to the top menu: **Tools -> Add-ons** (or **Extensions**).
3. Click the gear icon (`⚙️`) in the top-right corner of the Add-ons manager page.
4. Select **Install Add-on From File...**.
5. Select the generated **`zotero-pdf-copier-renamer.xpi`** file.
6. Click **Install** and restart Zotero when prompted.
---
## How to Operate
1. Select one or more papers (regular references) in your Zotero library grid.
2. Right-click, and click **Copy Attachments to Folder...** (identified by the custom logo icon).
3. Select the destination folder on your laptop.
4. Watch the progress window in the bottom-right corner complete, and check your folder for the copied files!

58
addon/bootstrap.js vendored Normal file
View File

@ -0,0 +1,58 @@
/**
* Most of this code is from Zotero team's official Make It Red example[1]
* or the Zotero 7 documentation[2].
* [1] https://github.com/zotero/make-it-red
* [2] https://www.zotero.org/support/dev/zotero_7_for_developers
*/
var chromeHandle;
function install(data, reason) {}
async function startup({ id, version, resourceURI, rootURI }, reason) {
var aomStartup = Components.classes[
"@mozilla.org/addons/addon-manager-startup;1"
].getService(Components.interfaces.amIAddonManagerStartup);
var manifestURI = Services.io.newURI(rootURI + "manifest.json");
chromeHandle = aomStartup.registerChrome(manifestURI, [
["content", "__addonRef__", rootURI + "content/"],
]);
/**
* Global variables for plugin code.
* The `_globalThis` is the global root variable of the plugin sandbox environment
* and all child variables assigned to it is globally accessible.
* See `src/index.ts` for details.
*/
const ctx = { rootURI };
ctx._globalThis = ctx;
Services.scriptloader.loadSubScript(
`${rootURI}/content/scripts/__addonRef__.js`,
ctx,
);
await Zotero.__addonInstance__.hooks.onStartup();
}
async function onMainWindowLoad({ window }, reason) {
await Zotero.__addonInstance__?.hooks.onMainWindowLoad(window);
}
async function onMainWindowUnload({ window }, reason) {
await Zotero.__addonInstance__?.hooks.onMainWindowUnload(window);
}
async function shutdown({ id, version, resourceURI, rootURI }, reason) {
if (reason === APP_SHUTDOWN) {
return;
}
await Zotero.__addonInstance__?.hooks.onShutdown();
if (chromeHandle) {
chromeHandle.destruct();
chromeHandle = null;
}
}
async function uninstall(data, reason) {}

403
addon/content/dialog.js Normal file
View File

@ -0,0 +1,403 @@
let Zotero, addon, items, api;
let selectedFolderId = null;
let selectedParentId = null;
function createHtmlElement(tagName) {
return document.createElementNS("http://www.w3.org/1999/xhtml", tagName);
}
function init() {
const args = window.arguments[0];
Zotero = args.Zotero;
addon = args.addon;
items = args.items;
api = args.api;
loadFolders();
}
async function loadFolders() {
const container = document.getElementById("folders-container");
try {
const folders = await api.sendEncryptedGetRequest("/api/extension/folders");
if (!folders || folders.length === 0) {
container.innerHTML = `<div style="display: flex; align-items: center; justify-content: center; height: 100%; color: var(--text-secondary); font-size: 13px;">No folders found in Research OS. Please create one on the website first.</div>`;
return;
}
container.innerHTML = "";
const treeRootUl = createHtmlElement("ul");
treeRootUl.className = "folder-tree";
container.appendChild(treeRootUl);
folders.forEach(rootFolder => {
// 1. Create root folder node
const rootNodeLi = createHtmlElement("li");
rootNodeLi.className = "folder-node";
const rootDiv = createHtmlElement("div");
rootDiv.className = "folder-item";
rootDiv.innerHTML = `<span class="folder-icon">📁</span><span>${rootFolder.name}</span>`;
rootDiv.onclick = () => selectFolder(rootFolder.id, null, rootDiv);
rootNodeLi.appendChild(rootDiv);
treeRootUl.appendChild(rootNodeLi);
const subfolders = rootFolder.children || [];
// Helper to render child folders recursively
function renderSubfolders(parentId, parentElement) {
const children = subfolders.filter(sub => {
if (parentId === null) {
return sub.parent_id === null || sub.parent_id === undefined;
}
return sub.parent_id === parentId;
});
if (children.length > 0) {
const branchUl = createHtmlElement("ul");
branchUl.className = "folder-branch";
parentElement.appendChild(branchUl);
children.forEach(sub => {
const childLi = createHtmlElement("li");
childLi.className = "folder-node";
const childDiv = createHtmlElement("div");
childDiv.className = "folder-item";
childDiv.innerHTML = `<span class="folder-icon">📂</span><span>${sub.name}</span>`;
childDiv.onclick = () => selectFolder(rootFolder.id, sub.id, childDiv);
childLi.appendChild(childDiv);
branchUl.appendChild(childLi);
// Recurse for nested folders
renderSubfolders(sub.id, childLi);
});
}
}
// Start recursion
renderSubfolders(null, rootNodeLi);
});
} catch (err) {
Zotero.debug(err);
container.innerHTML = `<div style="display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100%; color: var(--error); font-size: 13px; padding: 16px; text-align: center; gap: 8px;">
<span>Failed to fetch Research OS folders.</span>
<span style="font-size: 11px; color: var(--text-secondary);">${err.message}</span>
</div>`;
}
}
function cleanDoi(input) {
if (!input) return "";
let cleaned = input.trim().toLowerCase();
cleaned = cleaned.replace(/^(https?:\/\/)?(www\.)?(dx\.)?doi\.org\//i, "");
cleaned = cleaned.replace(/^doi\s*:\s*/i, "");
const doiRegex = /(10\.\d{4,9}\/[-._;()/:a-zA-Z0-9]+)/i;
const match = cleaned.match(doiRegex);
return match ? match[1] : cleaned;
}
function selectFolder(folderId, parentId, element) {
selectedFolderId = folderId;
selectedParentId = parentId;
// Clear selection styles
const items = document.querySelectorAll(".folder-item");
items.forEach(item => item.classList.remove("selected"));
// Highlight selected element
element.classList.add("selected");
// Enable Sync button
document.getElementById("btn-sync").disabled = false;
}
async function startSync() {
// Switch screens
document.getElementById("folder-screen").classList.remove("active");
document.getElementById("progress-screen").classList.add("active");
const itemsContainer = document.getElementById("items-container");
itemsContainer.innerHTML = "";
// Create progress rows for each item
items.forEach((item, index) => {
const row = createHtmlElement("div");
row.className = "sync-item-row";
row.id = `sync-row-${index}`;
// Determine if it has a PDF attachment
let hasPdf = false;
if (item.isRegularItem()) {
const attachments = item.getAttachments();
for (let attId of attachments) {
const att = Zotero.Items.get(attId);
if (att.attachmentContentType === "application/pdf" || att.getField("title").toLowerCase().endsWith(".pdf")) {
hasPdf = true;
break;
}
}
}
row.innerHTML = `
<div class="sync-item-info">
<div class="sync-item-title">${escapeHtml(item.getField("title") || "Untitled")}</div>
<div class="sync-item-detail" id="sync-detail-${index}">
${hasPdf ? "📎 PDF Attachment found" : "📄 No PDF Attachment"}
</div>
</div>
<div class="sync-item-status status-pending" id="sync-status-${index}">Pending</div>
`;
itemsContainer.appendChild(row);
});
updateProgress(0, "Fetching existing papers in target location...");
let existingPapers = [];
try {
const parentParam = selectedParentId ? `?parent_id=${selectedParentId}` : "";
existingPapers = await api.sendEncryptedGetRequest(`/api/extension/folders/${selectedFolderId}/papers${parentParam}`) || [];
} catch (err) {
Zotero.debug(`Failed to fetch existing papers: ${err.message}`);
}
updateProgress(0, `Starting synchronization of ${items.length} items...`);
let successCount = 0;
for (let i = 0; i < items.length; i++) {
const item = items[i];
const statusLabel = document.getElementById(`sync-status-${i}`);
const detailLabel = document.getElementById(`sync-detail-${i}`);
statusLabel.className = "sync-item-status status-syncing";
statusLabel.textContent = "Syncing";
updateProgress(Math.round((i / items.length) * 100), `Syncing: ${item.getField("title")}`);
try {
// Step 1: Gather metadata
const paperTitle = item.getField("title") || "Untitled";
let paperAbstract = item.getField("abstractNote") || "";
let paperAuthors = "";
try {
paperAuthors = item.getCreators().map(c => `${c.firstName} ${c.lastName}`.trim()).join(", ");
} catch (e) {}
let paperJournal = item.getField("publicationTitle") || item.getField("journalAbbreviation") || "";
let paperYear = "";
try {
const date = item.getField("date");
if (date) {
const match = date.match(/\d{4}/);
if (match) paperYear = match[0];
}
} catch (e) {}
let paperPublisher = "";
try {
paperPublisher = item.getField("publisher") || "";
} catch (e) {}
let paperSjr = "";
let paperQuartile = "";
// Step 2: Try to get DOI and check duplicate
let doi = "";
try {
doi = item.getField("DOI");
} catch (e) {}
if (!doi) {
try {
const extra = item.getField("extra") || "";
const match = extra.match(/DOI:\s*(\S+)/i);
if (match) doi = match[1];
} catch (e) {}
}
// Duplicate matching logic
const cleanZoteroDoi = cleanDoi(doi);
const normalizedZoteroTitle = paperTitle.toLowerCase().replace(/[^a-z0-9]/g, "");
const duplicatePaper = existingPapers.find(existing => {
// 1. Try DOI matching
let existingDoi = "";
if (existing.metadata) {
try {
const meta = typeof existing.metadata === 'string' ? JSON.parse(existing.metadata) : existing.metadata;
existingDoi = meta.doi || "";
} catch (e) {}
}
if (cleanZoteroDoi && existingDoi) {
if (cleanZoteroDoi === cleanDoi(existingDoi)) {
return true;
}
}
// 2. Try Title matching
const normalizedExistingTitle = (existing.name || "").toLowerCase().replace(/[^a-z0-9]/g, "");
if (normalizedZoteroTitle && normalizedExistingTitle && normalizedZoteroTitle === normalizedExistingTitle) {
return true;
}
return false;
});
const isDuplicate = !!duplicatePaper;
if (isDuplicate) {
detailLabel.textContent = `Duplicate found. Merging attachment into existing paper (ID: ${duplicatePaper.id})...`;
}
let enriched = null;
// If NOT duplicate, fetch metadata
if (!isDuplicate) {
if (doi) {
detailLabel.textContent = "Extracting DOI and enriching metadata...";
try {
const enrichUrl = `/api/extension/paper?doi=${encodeURIComponent(doi)}`;
enriched = await api.sendEncryptedGetRequest(enrichUrl);
} catch (enrichErr) {
Zotero.debug(`Failed to enrich via DOI: ${enrichErr.message}`);
}
} else {
detailLabel.textContent = "No DOI found, searching by title...";
try {
const enrichUrl = `/api/extension/paper?title=${encodeURIComponent(paperTitle)}`;
enriched = await api.sendEncryptedGetRequest(enrichUrl);
} catch (enrichErr) {
Zotero.debug(`Failed to enrich via title: ${enrichErr.message}`);
}
}
if (enriched && enriched.metadata) {
if (enriched.metadata.abstract) paperAbstract = enriched.metadata.abstract;
if (enriched.metadata.journal && enriched.metadata.journal !== 'N/A') paperJournal = enriched.metadata.journal;
if (enriched.metadata.year && enriched.metadata.year !== 'N/A') paperYear = enriched.metadata.year;
if (enriched.metadata.authors && enriched.metadata.authors.length > 0) {
paperAuthors = Array.isArray(enriched.metadata.authors) ? enriched.metadata.authors.join(', ') : enriched.metadata.authors;
}
if (enriched.metadata.publisher && enriched.metadata.publisher !== 'N/A') {
paperPublisher = enriched.metadata.publisher;
} else if (enriched.ranking && enriched.ranking.publisher) {
paperPublisher = enriched.ranking.publisher;
}
if (enriched.ranking) {
paperSjr = enriched.ranking.sjr || "";
paperQuartile = enriched.ranking.quartile || "";
}
}
}
// Step 3: Handle PDF attachments
const pdfs = [];
const attachments = item.getAttachments();
let pdfAttachment = null;
for (let attId of attachments) {
const att = Zotero.Items.get(attId);
if (att.attachmentContentType === "application/pdf" || att.getField("title").toLowerCase().endsWith(".pdf")) {
pdfAttachment = att;
break;
}
}
if (pdfAttachment) {
detailLabel.textContent = isDuplicate
? "Uploading duplicate PDF attachment..."
: "Reading local PDF copy...";
const filePath = await pdfAttachment.getFilePathAsync();
if (filePath) {
// Read local file bytes
const bytes = await IOUtils.read(filePath);
const blob = new Blob([bytes], { type: "application/pdf" });
detailLabel.textContent = "Uploading PDF to Research OS (Cloudflare R2)...";
const uploadRes = await api.uploadPdf(blob, `${paperTitle.replace(/[^a-zA-Z0-9]/g, "_")}.pdf`);
if (uploadRes && uploadRes.url) {
pdfs.push({
id: Date.now().toString() + "_" + Math.random().toString(36).substr(2, 9),
name: isDuplicate ? `Attached PDF (${new Date().toLocaleDateString()})` : "Main Paper",
url: uploadRes.url,
type: "file",
createdAt: new Date().toISOString()
});
detailLabel.textContent = "PDF successfully uploaded.";
}
} else {
Zotero.debug("PDF attachment file path was empty. PDF will not be uploaded.");
}
}
// Step 4: Insert/Update paper in database
detailLabel.textContent = isDuplicate
? "Updating existing paper record..."
: "Saving paper metadata to Research OS...";
const paperPayload = {
title: paperTitle,
doi: doi,
abstract: paperAbstract,
authors: paperAuthors,
journal: paperJournal,
year: paperYear,
publisher: paperPublisher,
sjr: paperSjr,
quartile: paperQuartile,
pdfs: pdfs
};
const payload = {
folderId: selectedFolderId,
parent_id: selectedParentId,
paper: paperPayload
};
if (isDuplicate) {
payload.paperId = duplicatePaper.id;
}
await api.sendEncryptedRequest("/api/extension/insert", payload);
statusLabel.className = "sync-item-status status-success";
statusLabel.textContent = "Success";
detailLabel.textContent = isDuplicate
? (pdfs.length > 0 ? "Merged new PDF successfully" : "Already matched (no new PDF)")
: (pdfs.length > 0 ? "Synced successfully with PDF" : "Synced successfully (no PDF)");
successCount++;
} catch (err) {
Zotero.debug(err);
statusLabel.className = "sync-item-status status-error";
statusLabel.textContent = "Error";
detailLabel.textContent = `Error: ${err.message}`;
appendErrorLog(item.getField("title") || "Untitled", err);
}
}
updateProgress(100, `Completed! Successfully synced ${successCount} of ${items.length} items.`);
document.getElementById("btn-close").disabled = false;
}
function appendErrorLog(title, err) {
const container = document.getElementById("error-log-container");
const logBox = document.getElementById("error-log-box");
if (container && logBox) {
container.style.display = "flex";
const timestamp = new Date().toLocaleTimeString();
const stackInfo = err.stack ? `\nStack trace:\n${err.stack}` : "";
logBox.value += `[${timestamp}] Error syncing "${title}":\n${err.message}${stackInfo}\n\n`;
}
}
function updateProgress(percent, text) {
document.getElementById("progress-bar").style.width = `${percent}%`;
document.getElementById("progress-percent").textContent = `${percent}%`;
document.getElementById("progress-text").textContent = text;
}
function escapeHtml(text) {
const map = {
"&": "&amp;",
"<": "&lt;",
">": "&gt;",
'"': "&quot;",
"'": "&#039;"
};
return text.replace(/[&<>"']/g, m => map[m]);
}

341
addon/content/dialog.xhtml Normal file
View File

@ -0,0 +1,341 @@
<?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
<window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
xmlns:html="http://www.w3.org/1999/xhtml"
title="Sync to Research OS"
width="550"
height="500"
onload="init()">
<html:style>
:root {
--bg-primary: #ffffff;
--bg-secondary: #f8fafc;
--bg-tertiary: #f1f5f9;
--text-primary: #000000;
--text-secondary: #475569;
--accent: #4f46e5;
--accent-hover: #4338ca;
--success: #16a34a;
--error: #dc2626;
--border-color: #cbd5e1;
}
:root, window {
background-color: var(--bg-primary) !important;
color: var(--text-primary) !important;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
margin: 0;
padding: 20px;
height: 100vh;
display: flex;
flex-direction: column;
box-sizing: border-box;
}
.container {
display: flex;
flex-direction: column;
height: 100%;
gap: 16px;
}
h2 {
margin: 0 0 4px 0;
font-size: 18px;
font-weight: 600;
color: var(--text-primary);
}
.subtitle {
margin: 0 0 16px 0;
font-size: 13px;
color: var(--text-secondary);
}
/* Screen layout */
.screen {
display: none;
flex-direction: column;
flex: 1;
overflow: hidden;
}
.screen.active {
display: flex;
}
/* Folder selection styles */
.folder-list {
flex: 1;
border: 1px solid var(--border-color);
border-radius: 8px;
background-color: var(--bg-secondary);
overflow-y: auto;
padding: 8px;
}
.folder-item {
display: flex;
align-items: center;
padding: 8px 12px;
border-radius: 6px;
cursor: pointer;
margin-bottom: 4px;
transition: all 0.2s;
font-size: 13px;
}
.folder-item:hover {
background-color: var(--bg-tertiary);
}
.folder-item.selected {
background-color: var(--accent);
color: #ffffff !important;
}
.folder-tree,
.folder-branch {
list-style: none;
padding: 0;
margin: 0;
}
.folder-branch {
margin-left: 12px;
padding-left: 12px;
border-left: 1px solid var(--border-color);
}
.folder-node {
position: relative;
}
.folder-branch > .folder-node::before {
content: "";
position: absolute;
left: -12px;
top: 17px;
width: 12px;
height: 1px;
background-color: var(--border-color);
}
.folder-icon {
margin-right: 8px;
font-size: 16px;
}
/* Progress tracker styles */
.progress-card {
border: 1px solid var(--border-color);
border-radius: 8px;
background-color: var(--bg-secondary);
padding: 16px;
display: flex;
flex-direction: column;
gap: 12px;
}
.progress-bar-container {
background-color: var(--bg-tertiary);
height: 8px;
border-radius: 4px;
overflow: hidden;
width: 100%;
}
.progress-bar {
background: linear-gradient(90deg, #4f46e5 0%, #818cf8 100%);
height: 100%;
width: 0%;
border-radius: 4px;
transition: width 0.3s ease;
}
.progress-status {
display: flex;
justify-content: space-between;
font-size: 13px;
font-weight: 500;
}
.item-list {
flex: 1;
border: 1px solid var(--border-color);
border-radius: 8px;
background-color: var(--bg-secondary);
overflow-y: auto;
padding: 8px;
display: flex;
flex-direction: column;
gap: 6px;
}
.sync-item-row {
display: flex;
align-items: center;
justify-content: space-between;
padding: 10px 12px;
border-radius: 6px;
background-color: rgba(0, 0, 0, 0.02);
border: 1px solid rgba(0, 0, 0, 0.05);
font-size: 13px;
}
.sync-item-info {
display: flex;
flex-direction: column;
gap: 2px;
flex: 1;
overflow: hidden;
padding-right: 12px;
}
.sync-item-title {
font-weight: 500;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
color: var(--text-primary);
}
.sync-item-detail {
font-size: 11px;
color: var(--text-secondary);
}
.sync-item-status {
font-weight: 600;
font-size: 12px;
padding: 4px 8px;
border-radius: 4px;
text-transform: uppercase;
}
.status-pending {
background-color: rgba(0, 0, 0, 0.04);
color: var(--text-secondary);
}
.status-syncing {
background-color: rgba(79, 70, 229, 0.08);
color: #4f46e5;
}
.status-success {
background-color: rgba(16, 185, 129, 0.15);
color: var(--success);
}
.status-error {
background-color: rgba(239, 68, 68, 0.15);
color: var(--error);
}
/* Buttons block */
.button-group {
display: flex;
justify-content: flex-end;
gap: 12px;
margin-top: 8px;
}
.btn {
padding: 10px 20px;
border-radius: 6px;
font-weight: 600;
font-size: 13px;
cursor: pointer;
border: none;
transition: all 0.2s;
}
.btn-primary {
background-color: var(--accent);
color: #ffffff;
}
.btn-primary:hover {
background-color: var(--accent-hover);
}
.btn-secondary {
background-color: var(--bg-tertiary);
color: var(--text-primary);
}
.btn-secondary:hover {
background-color: var(--border-color);
}
.btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
/* Scrollbars */
::-webkit-scrollbar {
width: 6px;
}
::-webkit-scrollbar-track {
background: transparent;
}
::-webkit-scrollbar-thumb {
background: var(--border-color);
border-radius: 3px;
}
</html:style>
<html:div class="container">
<!-- View 1: Folder Selection -->
<html:div id="folder-screen" class="screen active">
<html:h2>Sync to Research OS</html:h2>
<html:div class="subtitle">Select the destination folder in Research OS for the selected items.</html:div>
<html:div id="folders-container" class="folder-list">
<html:div style="display: flex; align-items: center; justify-content: center; height: 100%; color: var(--text-secondary); font-size: 13px;">
Loading folders from Research OS...
</html:div>
</html:div>
<html:div class="button-group">
<html:button id="btn-cancel" class="btn btn-secondary" onclick="window.close()">Cancel</html:button>
<html:button id="btn-sync" class="btn btn-primary" onclick="startSync()" disabled="true">Sync Now</html:button>
</html:div>
</html:div>
<!-- View 2: Progress Screen -->
<html:div id="progress-screen" class="screen">
<html:h2>Syncing Papers</html:h2>
<html:div class="subtitle">Please wait while items are being securely uploaded to Research OS.</html:div>
<html:div class="progress-card">
<html:div class="progress-status">
<html:span id="progress-text">Initializing...</html:span>
<html:span id="progress-percent">0%</html:span>
</html:div>
<html:div class="progress-bar-container">
<html:div id="progress-bar" class="progress-bar"></html:div>
</html:div>
</html:div>
<html:h2 style="margin-top: 16px; font-size: 14px;">Sync Status List</html:h2>
<html:div id="items-container" class="item-list">
<!-- Progress rows injected here -->
</html:div>
<html:div id="error-log-container" style="display: none; flex-direction: column; gap: 6px; margin-top: 16px; min-height: 120px; height: 120px;">
<html:h2 style="font-size: 13px; color: var(--error); margin: 0 0 2px 0;">Detailed Error Logs</html:h2>
<html:textarea id="error-log-box" readonly="true" style="flex: 1; width: 100%; font-family: monospace; font-size: 11px; padding: 8px; border: 1px solid var(--border-color); border-radius: 6px; background-color: var(--bg-secondary); color: var(--text-primary); resize: none; box-sizing: border-box; outline: none;"></html:textarea>
</html:div>
<html:div class="button-group">
<html:button id="btn-close" class="btn btn-secondary" onclick="window.close()" disabled="true">Close</html:button>
</html:div>
</html:div>
</html:div>
<script src="chrome://researchossync/content/dialog.js" type="application/javascript"/>
</window>

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.8 KiB

View File

@ -0,0 +1,44 @@
<vbox
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
xmlns:html="http://www.w3.org/1999/xhtml"
onload="Zotero.ResearchOsSync.hooks.onPrefsEvent('load', { window })"
style="padding: 16px; min-width: 480px; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;"
>
<groupbox style="border: 1px solid #e2e8f0; border-radius: 8px; padding: 16px; background-color: #ffffff; box-shadow: 0 1px 3px rgba(0,0,0,0.05);">
<label><html:h3 style="margin: 0 0 16px 0; color: #0f172a; font-size: 16px; font-weight: 600; border-bottom: 1px solid #f1f5f9; padding-bottom: 8px;">Research OS Integration Settings</html:h3></label>
<html:div style="display: flex; flex-direction: column; gap: 12px; width: 100%;">
<html:div style="display: flex; flex-direction: column; gap: 4px;">
<html:label for="zotero-prefpane-researchossync-serverUrl" style="font-size: 13px; font-weight: 500; color: #475569;">Server Endpoint URL</html:label>
<html:input
type="text"
id="zotero-prefpane-researchossync-serverUrl"
preference="extensions.zotero.researchossync.serverUrl"
placeholder="e.g. http://localhost:3000"
style="padding: 8px 12px; border: 1px solid #cbd5e1; border-radius: 6px; font-size: 13px; outline: none; background: #f8fafc; transition: all 0.2s;"
/>
</html:div>
<html:div style="display: flex; flex-direction: column; gap: 4px;">
<html:label for="zotero-prefpane-researchossync-apiToken" style="font-size: 13px; font-weight: 500; color: #475569;">Extension API Token</html:label>
<html:input
type="password"
id="zotero-prefpane-researchossync-apiToken"
preference="extensions.zotero.researchossync.apiToken"
placeholder="ext_..."
style="padding: 8px 12px; border: 1px solid #cbd5e1; border-radius: 6px; font-size: 13px; outline: none; background: #f8fafc; transition: all 0.2s;"
/>
</html:div>
<html:div style="display: flex; justify-content: flex-end; margin-top: 10px;">
<html:button
id="zotero-prefpane-researchossync-test"
onclick="Zotero.ResearchOsSync.hooks.onPrefsEvent('test', { window })"
style="padding: 8px 16px; background-color: #cbd5e1; color: #0f172a; font-weight: 600; font-size: 13px; border-radius: 6px; border: 1px solid #94a3b8; cursor: pointer;"
>
Test Connection
</html:button>
</html:div>
</html:div>
</groupbox>
</vbox>

View File

@ -0,0 +1,3 @@
.makeItRed {
background-color: tomato;
}

View File

@ -0,0 +1,11 @@
startup-begin = Addon is loading
startup-finish = Addon is ready
menuitem-label = Addon Template: Helper Examples
menupopup-label = Addon Template: Menupopup
menuitem-submenulabel = Addon Template
menuitem-filemenulabel = Addon Template: File Menuitem
prefs-title = Template
prefs-table-title = Title
prefs-table-detail = Detail
tabpanel-lib-tab-label = Lib Tab
tabpanel-reader-tab-label = Reader Tab

View File

@ -0,0 +1,11 @@
item-section-example1-head-text =
.label = Plugin Template: Item Info
item-section-example1-sidenav-tooltip =
.tooltiptext = This is Plugin Template section (item info)
item-section-example2-head-text =
.label = Plugin Template: Reader [{$status}]
item-section-example2-sidenav-tooltip =
.tooltiptext = This is Plugin Template section (reader)
item-section-example2-button-tooltip =
.tooltiptext = Unregister this section
item-info-row-example-label = Example Row

View File

@ -0,0 +1,5 @@
pref-title = Addon Template Example
pref-enable =
.label = Enable
pref-input = Input
pref-help = { $name } Build { $version } { $time }

View File

@ -0,0 +1,11 @@
startup-begin = 插件加载中
startup-finish = 插件已就绪
menuitem-label = 插件模板: 帮助工具样例
menupopup-label = 插件模板: 弹出菜单
menuitem-submenulabel = 插件模板:子菜单
menuitem-filemenulabel = 插件模板: 文件菜单
prefs-title = 插件模板
prefs-table-title = 标题
prefs-table-detail = 详情
tabpanel-lib-tab-label = 库标签
tabpanel-reader-tab-label = 阅读器标签

View File

@ -0,0 +1,11 @@
item-section-example1-head-text =
.label = 插件模板: 条目信息
item-section-example1-sidenav-tooltip =
.tooltiptext = 这是插件模板面板(条目信息)
item-section-example2-head-text =
.label = 插件模板: 阅读器[{$status}]
item-section-example2-sidenav-tooltip =
.tooltiptext = 这是插件模板面板(阅读器)
item-section-example2-button-tooltip =
.tooltiptext = 移除此面板
item-info-row-example-label = 示例行

View File

@ -0,0 +1,5 @@
pref-title = 插件模板设置示例
pref-enable =
.label = 开启
pref-input = 输入
pref-help = { $name } Build { $version } { $time }

20
addon/manifest.json Normal file
View File

@ -0,0 +1,20 @@
{
"manifest_version": 2,
"name": "__addonName__",
"version": "__buildVersion__",
"description": "__description__",
"homepage_url": "__homepage__",
"author": "__author__",
"icons": {
"48": "content/icons/favicon@0.5x.png",
"96": "content/icons/favicon.png"
},
"applications": {
"zotero": {
"id": "__addonID__",
"update_url": "__updateURL__",
"strict_min_version": "6.999",
"strict_max_version": "10.*"
}
}
}

2
addon/prefs.js Normal file
View File

@ -0,0 +1,2 @@
pref("serverUrl", "http://localhost:3000");
pref("apiToken", "");

52
build.cjs Normal file
View File

@ -0,0 +1,52 @@
const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');
const xpiName = 'zotero-pdf-copier-renamer.xpi';
const zipName = 'zotero-pdf-copier-renamer.zip';
console.log('Building and packaging Zotero Attachment Copy extension...');
try {
// 1. Run the template's build command
console.log('Running zotero-plugin build...');
execSync('npx zotero-plugin build', { stdio: 'inherit' });
// 2. Check if build directory exists
const buildDir = path.join('.scaffold', 'build', 'addon');
if (!fs.existsSync(buildDir)) {
throw new Error('Build output directory not found!');
}
// 3. Delete existing zip/xpi files if they exist
if (fs.existsSync(xpiName)) {
fs.unlinkSync(xpiName);
}
if (fs.existsSync(zipName)) {
fs.unlinkSync(zipName);
}
// 4. Package build output using bestzip
// We want to run bestzip inside the buildDir and output the zip to the project root
const absXpiPath = path.resolve(zipName);
console.log(`Zipping contents of ${buildDir} to ${absXpiPath}...`);
// Read files dynamically and pass them to bestzip to keep them at the root of the zip
const files = fs.readdirSync(buildDir);
const filesList = files.map(f => `"${f}"`).join(' ');
const zipCommand = `npx -y bestzip "${absXpiPath}" ${filesList}`;
console.log(`Running: ${zipCommand} in ${buildDir}`);
execSync(zipCommand, { cwd: buildDir, stdio: 'inherit' });
// 5. Rename zip to xpi
if (fs.existsSync(zipName)) {
fs.renameSync(zipName, xpiName);
}
console.log(`\nSuccessfully built and packaged: ${xpiName}`);
console.log('You can now install this file in Zotero via Tools -> Add-ons -> Install Add-on From File...');
} catch (error) {
console.error('Build failed:', error.message);
process.exit(1);
}

BIN
copy_9376689.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.8 KiB

415
doc/README-frFR.md Normal file
View File

@ -0,0 +1,415 @@
# Modèle d'extension Zotero
[![zotero target version](https://img.shields.io/badge/Zotero-7-green?style=flat-square&logo=zotero&logoColor=CC2936)](https://www.zotero.org)
[![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)
Ceci est un modèle pour développer une extension pour [Zotero](https://www.zotero.org/).
[English](../README.md) | [简体中文](./README-zhCN.md) | [Français](./README-frFR.md)
- Documentation
- [📖 Plugin Development Documentation](https://zotero-chinese.com/plugin-dev-guide/) (Chinese, not yet complete)
- [📖 Plugin Development Documentation for Zotero 7](https://www.zotero.org/support/dev/zotero_7_for_developers)
- Outils pour le développement de pluqgins
- [🛠️ Zotero Plugin Toolkit](https://github.com/windingwind/zotero-plugin-toolkit) | [API Documentation](https://github.com/windingwind/zotero-plugin-toolkit/blob/master/docs/zotero-plugin-toolkit.md)
- [🛠️ Zotero Plugin Scaffold](https://github.com/northword/zotero-plugin-scaffold)
- [ℹ️ Zotero Type Definitions](https://github.com/windingwind/zotero-types)
- [📜 Zotero Source Code](https://github.com/zotero/zotero)
- [📌 Zotero Plugin Template](https://github.com/windingwind/zotero-plugin-template) (Ce dépot)
> [!TIP]
> 👁 Surveillez ce dépôt afin d'être informé des corrections et des mises à jour.
## Exetensions développées sur la base de ce modèle
[![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)
[![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)
[![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)
[![GitHub Repo stars](https://img.shields.io/github/stars/windingwind/zotero-tag?label=zotero-tag&style=flat-square)](https://github.com/windingwind/zotero-tag)
[![GitHub Repo stars](https://img.shields.io/github/stars/iShareStuff/ZoteroTheme?label=zotero-theme&style=flat-square)](https://github.com/iShareStuff/ZoteroTheme)
[![GitHub Repo stars](https://img.shields.io/github/stars/MuiseDestiny/zotero-reference?label=zotero-reference&style=flat-square)](https://github.com/MuiseDestiny/zotero-reference)
[![GitHub Repo stars](https://img.shields.io/github/stars/MuiseDestiny/zotero-citation?label=zotero-citation&style=flat-square)](https://github.com/MuiseDestiny/zotero-citation)
[![GitHub Repo stars](https://img.shields.io/github/stars/MuiseDestiny/ZoteroStyle?label=zotero-style&style=flat-square)](https://github.com/MuiseDestiny/ZoteroStyle)
[![GitHub Repo stars](https://img.shields.io/github/stars/volatile-static/Chartero?label=Chartero&style=flat-square)](https://github.com/volatile-static/Chartero)
[![GitHub Repo stars](https://img.shields.io/github/stars/l0o0/tara?label=tara&style=flat-square)](https://github.com/l0o0/tara)
[![GitHub Repo stars](https://img.shields.io/github/stars/redleafnew/delitemwithatt?label=delitemwithatt&style=flat-square)](https://github.com/redleafnew/delitemwithatt)
[![GitHub Repo stars](https://img.shields.io/github/stars/redleafnew/zotero-updateifsE?label=zotero-updateifsE&style=flat-square)](https://github.com/redleafnew/zotero-updateifsE)
[![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)
[![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)
[![GitHub Repo stars](https://img.shields.io/github/stars/MuiseDestiny/zotero-gpt?label=zotero-gpt&style=flat-square)](https://github.com/MuiseDestiny/zotero-gpt)
[![GitHub Repo stars](https://img.shields.io/github/stars/zoushucai/zotero-journalabbr?label=zotero-journalabbr&style=flat-square)](https://github.com/zoushucai/zotero-journalabbr)
[![GitHub Repo stars](https://img.shields.io/github/stars/MuiseDestiny/zotero-figure?label=zotero-figure&style=flat-square)](https://github.com/MuiseDestiny/zotero-figure)
[![GitHub Repo stars](https://img.shields.io/github/stars/l0o0/jasminum?label=jasminum&style=flat-square)](https://github.com/l0o0/jasminum)
[![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)
[![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)
Si vous utilisez ce dépôt, je vous recommande de mettre le badge suivant dans votre README :
[![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)
```md
[![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)
```
## Fonctionalités
- Architecture orientée événements, basée sur la programmation fonctionnelle utilisant des squeletteq étendus ;
- Simple et convivial, il est prêt à l'emploi.
- ⭐ [Nuveauté !] Rechargement automatique à chaud ! Chaque fois que le code source est modifié, il est automatiquement compilé et rechargé. [Voir ici→]((#auto-hot-reload)
- Nombreux exemples dans `src/modules/examples.ts` ; ils couvrent la plupart des usages des APIs habituellement utilisées dans les extensions (en utilisant [zotero-plugin-toolkit](https://github.com/windingwind/zotero-plugin-toolkit));
- Support de TypeScript :
- Prise en charge complète de la définition des types pour l'ensemble du projet Zotero, qui est écrit en JavaScript (avec les [zotero-types](https://github.com/windingwind/zotero-types));
- Variables globales et configuration de l'environnement ;
- Gestion des workflows pour le développement, la finalisation et la publication des extensions :
- - Génére / met à jour automatiquement l'id/version de l'extension, met à jour les configurations, et définit les variables d'environnement (`development` / `production`);
- Construit et recharge automatiquement le code dans Zotero ;
- Publie automatiquement les nouvelles versions sur GitHub.
- Intégration avec Prettier et ES Lint (analyseur et formatteur de code).
## Exemples
Ce dépot fournit des exemples pour les API [zotero-plugin-toolkit](https://github.com/windingwind/zotero-plugin-toolkit).
Recherchez `@example` dans `src/examples.ts`. Les exemples sont appelés dans `src/hooks.ts`.
### Exemples basiques
- registerNotifier
- registerPrefs, unregisterPrefs
### Exemples utilisant les raccourcis clavier
- registerShortcuts
- exampleShortcutLargerCallback
- exampleShortcutSmallerCallback
- exampleShortcutConflictionCallback
### Exemples d'interface utilisateur (UI)
![image](https://user-images.githubusercontent.com/33902321/211739774-cc5c2df8-5fd9-42f0-9cdf-0f2e5946d427.png)
- registerStyleSheet (utilisé par l'extension officielle make-it-red qui sert d'exemple)
- registerRightClickMenuItem
- registerRightClickMenuPopup
- registerWindowMenuWithSeprator
- registerExtraColumn
- registerExtraColumnWithCustomCell
- registerCustomItemBoxRow
- registerLibraryTabPanel
- registerReaderTabPanel
### Exemples avec des panneaux de préférences
![image](https://user-images.githubusercontent.com/33902321/211737987-cd7c5c87-9177-4159-b975-dc67690d0490.png)
- Liaisons avec les préférences
- Événements de l'interface utilisateur
- Table
- Locale
Voir [`src/modules/preferenceScript.ts`](../src/modules/preferenceScript.ts)
### Exemples de fenêtre d'aide
![image](https://user-images.githubusercontent.com/33902321/215119473-e7d0d0ef-6d96-437e-b989-4805ffcde6cf.png)
- dialogExample
- clipboardExample
- filePickerExample
- progressWindowExample
- vtableExample (voir Exemples avec des panneaux de préférences)
### Exemples de prompts
Un module d'invite (entrée de commande contextuelle) de style Obsidian. Il accepte les commandes textuelles pour exécuter le callback, avec un affichage optionnel dans la fenêtre popup.
S'active avec `Shift+P`.
![image](https://user-images.githubusercontent.com/33902321/215120009-e7c7ed27-33a0-44fe-b021-06c272481a92.png)
- registerAlertPromptExample
## Guide de démarrage rapide
### 0. Pré-requis
1. Installez une version beta de Zotero: <https://www.zotero.org/support/beta_builds>
2. Installez [Node.js latest LTS version](https://nodejs.org/en/) and [Git](https://git-scm.com/)
> [!NOTE]
> Ce guide suppose que vous avez une compréhension initiale de la structure de base et du fonctionnement des extensiosn Zotero. Si ce n'est pas le cas, veuillez vous référer à la [documentation](https://www.zotero.org/support/dev/zotero_7_for_developers)et aux exemples officiels de l'extension [Make It Red](https://github.com/zotero/make-it-red) en premier lieu.
### 1. Créez votre dépôt
1. Cliquez sur `Use this template`
2. Clonez votre dépôt avec git.
<details >
<summary>💡 Démarrer votre projet avec GitHub Codespace</summary>
_GitHub CodeSpace_ vous permet de démarrer votre projet sans avoir à télécharger le code/IDE/dépendances localement.
Effectuez les étapes ci-dessus et créez votre première extension en 30 secondes!
- Allez en haut de la [page d'accueil](https://github.com/windingwind/zotero-plugin-template), cliquez sur le bouton vert `Use this template`, cliquez sur `Open in codespace`. ous devrez peut-être vous connecter à votre compte GitHub.
- Attendez que _GitHub CodeSpace_ se charge.
</details>
3. Entrez dans le dossier du dépôt
### 2. Configurez les paramètres du Modèle et l'environnement de développement
1. Modifier les paramètres dans `./package.json`, y compris :
```jsonc
{
"version": "0.0.0",
"description": "",
"config": {
"addonName": "", // name to be displayed in the plugin manager
"addonID": "", // ID to avoid conflict. IMPORTANT!
"addonRef": "", // e.g. Element ID prefix
"addonInstance": "", // the plugin's root instance: Zotero.${addonInstance}
"prefsPrefix": "extensions.zotero.${addonRef}", // the prefix of prefs
},
"repository": {
"type": "git",
"url": "git+https://github.com/your-github-name/repo-name.git",
},
"author": "Your Name",
"bugs": {
"url": "https://github.com/your-github-name/repo-name/issues",
},
"homepage": "https://github.com/your-github-name/repo-name#readme",
}
```
> ![WARNING]
> Veillez à bien définir addonID et addonRef pour éviter tout conflit.
Si vous avez besoin d'héberger vos paquets XPI en dehors de GitHub, modifiez `updateURL` et ajoutez `xpiDownloadLink` dans `zotero-plugin.config.ts`.
2. Copiez le fichier de la variable d'environnement. Modifiez la commandes quilance la version beta de Zotero.
> Créez un profil de développement (Optionnel)
> Démarrez la version beta de Zotero avec `/path/to/zotero -p`. Créez un nouveau profil et utilisez-le comme profil de développement. Ne le faites qu'une seule fois !
```sh
cp .env.example .env
vim .env
```
Si vous développez plus d'une extension, vous pouvez stocker le chemin bin et le chemin profile dans les variables d'environnement du système, qui peuvent être omises ici.
3. Installez les dépendances avec `npm install`
> Si vous utilisez `pnpm` comme gestionnaire de paquets pour votre projet, vous devez ajouter `public-hoist-pattern[]=*@types/bluebird*` à `.npmrc`, voir <https://github.com/windingwind/zotero-types?tab=readme-ov-file#usage>.
Si vous obtenez `npm ERR ! ERESOLVE unable to resolve dependency tree` avec `npm install`, qui est un bogue de dépendance en amont de typescript-eslint, utilisez la commande `npm i -f` pour l'installer.
### 3. Codez
Démarrez le serveur de développement avec `npm start`:
- Il fera La pré-construction de l'extension en mode développement
- Il démarrera Zotero avec l'extension chargée depuis `build/`
- Il surveillera `src/**` et `addon/**`.
- Si `src/**` a changé, lancez esbuild et rechargez.
- Si `addon/**` a changé, reconstruisez l'extension (en mode développement) et recharger là.
#### Rechargement automatique à chaud
Fatigué des redémarrages incessants ? Oubliez-les !
1. Lancez `npm start`.
2. Coder. (Oui, c'est tout)
Lorsque des changements de fichiers sont détectés dans `src` ou `addon`, l'extension 'sera automatiquement compilé et rechargé.
<details style="text-indent: 2em">
<summary>💡 Étapes pour ajouter cette fonctionnalité à une extension existante :</summary>
Voir [zotero-plugin-scaffold](https://github.com/northword/zotero-plugin-scaffold).
</details>
#### Déboguer dans Zotero
Vous pouvez également :
- Tester les extraits de code dans Outils -> Développeur -> Run Javascript ;
- Déboguer la sortie avec`Zotero.debug()`. Trouver les sorties dans Aide->Journal de débogage->Voir le journal;
- Déboguer l'interface utilisateur. Zotero est construit sur le cadre XUL de Firefox. Déboguez l'interface utilisateur XUL avec un logiciel comme [XUL Explorer](https://udn.realityripple.com/docs/Archive/Mozilla/XUL_Explorer).
> Documentation de XUL : <http://www.devdoc.net/web/developer.mozilla.org/en-US/docs/XUL.html>
### 4. Construction (Build)
Exécutez `npm run build` construire l'extension en mode production : t le xpi pour l'installation et le code construit se trouve dans le dossier `build`.
Étapes de la construction :
- Créez/videz `build/`.
- Copiez `addon/**` dans `build/addon/**`.
- Remplacez les espaces réservés : utilisez `replace-in-file` pour remplacer les mots-clés et les configurations définis dans `package.json` dans les fichiers non-construits (`xhtml`, `json`, et al.).
- Préparez les fichiers de locale pour [éviter les conflits](https://www.zotero.org/support/dev/zotero_7_for_developers#avoiding_localization_conflicts)
- Renommer `**/*.flt` en `**/${addonRef}-*.flt`
- Préfixez chaque message fluent[TODO] avec `addonRef-`
- Utilisez ESBuild pour construire le code source `.ts` vers `.js`, construisez `src/index.ts` vers `./build/addon/content/scripts`.
- (Mode production uniquement) Zipper le fichier `./build/addon` vers `./build/*.xpi`.
- (Mode production uniquement) Préparez `update.json` ou `update-beta.json`
> [!NOTE]
>
> **Quelle est la différence entre mode développement et production ?**
>
> - Cette variable d'environnement est stockée dans `Zotero.${addonInstance}.data.env`. La sortie vers la console est désactivée en mode production.
> - Vous pouvez décider ce que les utilisateurs ne peuvent pas voir/utiliser en fonction de cette variable.
> - En mode production, le script de construction va empaqueter l'extension et mettre à jour le fichier `update.json`.
### 5. Produire une Release
pour construire et produire une Release, utilisez :
```shell
# version increase, git add, commit and push
# then on ci, npm run build, and release to GitHub
npm run release
```
> [!NOTE]
> Cela utilisera [Bumpp](https://github.com/antfu-collective/bumpp) pour saisir le nouveau numéro de version, modifier localement la version, exécuter tous les scripts (pré/post) version définis dans `package.json`, commit, build (optionnel), marquer le commit avec le numéro de version et pousser les commits et les tags git. Bumpp peut être configuré dans `zotero-plugin-config.ts` ; par exemple, ajoutez `release : { bumpp : { execute : « npm run build » } }` pour construire également avant de commiter.
> Par la suite, GitHub Action reconstruira l'extensions et utilisera le script `release` de `zotero-plugin-scaffold` pour publier l'XPI sur GitHub Release. De plus, une version séparée (tag : `release`) sera créée ou mise à jour qui inclura les manifestes de mise à jour `update.json` et `update-beta.json` en tant qu'actifs. Ceux-ci seront disponibles à `https://github.com/{{owner}}/{{repo}}/releases/download/release/update*.json`.
#### À propos des pré-releases
Le modèle définit `prerelease` comme la version beta de l'extension, lorsque vous sélectionnez une version `prerelease` dans Bumpp (avec `-` dans le numéro de version). Le script de construction créera un nouveau `update-beta.json` pour l'utilisation de la prerelease, ce qui assure que les utilisateurs de la version normale ne seront pas en mesure de mettre à jour vers la version beta. Seuls les utilisateurs qui ont téléchargé et installé manuellement la version bêta seront en mesure de mettre à jour automatiquement vers la prochaine version bêta.
Lorsque la prochaine version normale sera mise à jour, `update.json` et `update-beta.json` seront tous deux mis à jour (sur la version spéciale `release`, voir ci-dessus) afin que les utilisateurs de la version normale et de la version bêta puissent se mettre à jour vers la nouvelle version normale.
> [!WARNING]
> La distinction entre les versions des extensions compatibles avec Zotero 6 et Zotero 7 devrait être strictement faite en configurant `applications.zotero.strict_min_version` dans `addons.__addonID__.updates[]` de `update.json` respectivement, afin que Zotero le reconnaisse correctement, voir <https://www.zotero.org/support/dev/zotero_7_for_developers#updaterdf_updatesjson>.
## Détails
### À propos des hooks
> Voir également [`src/hooks.ts`](https://github.com/windingwind/zotero-plugin-template/blob/main/src/hooks.ts)
1. Lorsque l'installation/activation/démarrage est déclenché par Zotero, `bootstrap.js` > `startup` est appelé
- Attendez que Zotero soit prêt ;
- Chargez de `index.js` (l'entrée principale du code de lextension, construit à partir de `index.ts`) ;
- Enregistrez les ressources si Zotero 7+
2. Dans l'entrée principale `index.js`, l'objet extension est injecté sous `Zotero` et `hooks.ts` > `onStartup` est appelé.
- Initialisez tout ce que vous voulez, y compris les auditeurs de notifications (hooks), les panneaux de préférences et les éléments de l'interface utilisateur.
3. Lorsque la désinstallation/désactivation est déclenchée depuis Zotero, `bootstrap.js` > `shutdown` est appelé.
- `events.ts` > `onShutdown` est appelé. Cela supprime les éléments de l'interface utilisateur, les panneaux de préférences, ou tout ce qui a été créé par l'extension'.
- Supprimez les scripts et libérez les ressources.
### À propos des variables globales
> Voir aussi [`src/index.ts`](https://github.com/windingwind/zotero-plugin-template/blob/main/src/index.ts)
L'extension 'bootstrappé' fonctionne dans un bac à sable, qui n'a pas de variables globales par défaut comme `Zotero` ou `window`, que nous avions l'habitude d'avoir en superposition dans la fenêtre d'environnement des extensions.
Ce modèle enregistre les variables suivantes avec une portée globale :
```plain
Zotero, ZoteroPane, Zotero_Tabs, window, document, rootURI, ztoolkit, addon;
```
### Création d'une API pour les éléments de l'extension
Le modèle d'extension fournit de nouvelles API pour les extensions 'bootstrappées'. Nous avons deux raisons d'utiliser ces APIs, au lieu de `createElement/createElementNS` :
- En mode bootstrap, les extensions doivent nettoyer tous les éléments de l'interface utilisateur à la sortie (désactivation ou désinstallation), ce qui est très ennuyeux. En utilisant `createElement`, le modèle de l'eextensions va maintenir ces éléments. Il suffit de lancer `unregisterAll` à la sortie.
- Zotero 7 requiert createElement()/createElementNS() → createXULElement() pour les éléments XUL restants, alors que Zotero 6 ne supporte pas `createXULElement`. L'API React.createElement-like `createElement` détecte l'espace de noms (xul/html/svg) et crée des éléments automatiquement, avec l'élément de retour dans le type d'élément TS correspondant.
```ts
createElement(document, "div"); // returns HTMLDivElement
createElement(document, "hbox"); // returns XUL.Box
createElement(document, "button", { namespace: "xul" }); // manually set namespace. returns XUL.Button
```
### À propos de l'API Zotero
La documentation de Zotero est obsolète et incomplète. Clonez <https://github.com/zotero/zotero> et recherchez le mot-clé globalement.
> ⭐Le [zotero-types](https://github.com/windingwind/zotero-types) fournit les API de Zotero les plus fréquemment utilisées. Il est inclus dans ce modèle par défaut. Votre IDE devrait fournir des indices pour la plupart des API.
Une astuce pour trouver l'API que vous voulez :
Recherchez le label de l'interface utilisateur dans les fichiers `.xhtml`/`.flt`, trouvez la clé correspondante dans le fichier locale. Ensuite, recherchez cette clé dans les fichiers `.js`/`.jsx`.
### Structure des répertoires
Cette section montre la structure des répertoires d'un modèle.
- Tous les fichiers de code `.js/.ts` sont dans `./src` ;
- Les fichiers de configuration des addons : `./addon/manifest.json` ;
- Fichiers d'interface utilisateur : `./addon/content/*.xhtml`.
- Les fichiers des Locales : `./addon/locale/**/*.flt` ;
- Fichier de préférences : `./addon/prefs.js` ;
```shell
.
|-- .github/ # github conf
|-- .vscode/ # vscode conf
|-- addon # static files
| |-- bootstrap.js
| |-- content
| | |-- icons
| | | |-- favicon.png
| | | `-- favicon@0.5x.png
| | |-- preferences.xhtml
| | `-- zoteroPane.css
| |-- locale
| | |-- en-US
| | | |-- addon.ftl
| | | |-- mainWindow.ftl
| | | `-- preferences.ftl
| | `-- zh-CN
| | |-- addon.ftl
| | |-- mainWindow.ftl
| | `-- preferences.ftl
| |-- manifest.json
| `-- prefs.js
|-- build # build dir
|-- node_modules
|-- src # source code of scripts
| |-- addon.ts # base class
| |-- hooks.ts # lifecycle hooks
| |-- index.ts # main entry
| |-- modules # sub modules
| | |-- examples.ts
| | `-- preferenceScript.ts
| `-- utils # utilities
| |-- locale.ts
| |-- prefs.ts
| |-- wait.ts
| |-- window.ts
| `-- ztoolkit.ts
|-- typings # ts typings
| `-- global.d.ts
|-- .env # enviroment config (do not check into repo)
|-- .env.example # template of enviroment config, https://github.com/northword/zotero-plugin-scaffold
|-- .gitignore # git conf
|-- .gitattributes # git conf
|-- .prettierrc # prettier conf, https://prettier.io/
|-- eslint.config.mjs # eslint conf, https://eslint.org/
|-- LICENSE
|-- package-lock.json
|-- package.json
|-- tsconfig.json # typescript conf, https://code.visualstudio.com/docs/languages/jsconfig
|-- README.md
`-- zotero-plugin.config.ts # scaffold conf, https://github.com/northword/zotero-plugin-scaffold
```
## Clause de non-responsabilité
Utilisez ce code sous AGPL. Aucune garantie n'est fournie. Gardez à l'esprit les lois de votre pays !
Si vous souhaitez modifier la licence, veuillez me contacter à l'adresse suivante : <wyzlshx@foxmail.com>

410
doc/README-zhCN.md Normal file
View File

@ -0,0 +1,410 @@
# Zotero Plugin Template
[![zotero target version](https://img.shields.io/badge/Zotero-7-green?style=flat-square&logo=zotero&logoColor=CC2936)](https://www.zotero.org)
[![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)
这是 [Zotero](https://www.zotero.org/) 的插件模板。
[English](../README.md) | [简体中文](./README-zhCN.md) | [Français](./README-frFR.md)
- 开发指南
- [📖 插件开发文档](https://zotero-chinese.com/plugin-dev-guide/) (中文版,尚不完善)
- [📖 Zotero 7 插件开发文档](https://www.zotero.org/support/dev/zotero_7_for_developers)
- 开发工具参考
- [🛠️ Zotero 插件工具包](https://github.com/windingwind/zotero-plugin-toolkit) | [API 文档](https://github.com/windingwind/zotero-plugin-toolkit/blob/master/docs/zotero-plugin-toolkit.md)
- [🛠️ Zotero 插件开发脚手架](https://github.com/northword/zotero-plugin-scaffold)
- [📜 Zotero 源代码](https://github.com/zotero/zotero)
- [ℹ️ Zotero 类型定义](https://github.com/windingwind/zotero-types)
- [📌 Zotero 插件模板](https://github.com/windingwind/zotero-plugin-template) (即本仓库)
> [!tip]
> 👁 Watch 本仓库,以及时收到修复或更新的通知。
## 使用此模板构建的插件
[![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)
[![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)
[![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)
[![GitHub Repo stars](https://img.shields.io/github/stars/windingwind/zotero-tag?label=zotero-tag&style=flat-square)](https://github.com/windingwind/zotero-tag)
[![GitHub Repo stars](https://img.shields.io/github/stars/iShareStuff/ZoteroTheme?label=zotero-theme&style=flat-square)](https://github.com/iShareStuff/ZoteroTheme)
[![GitHub Repo stars](https://img.shields.io/github/stars/MuiseDestiny/zotero-reference?label=zotero-reference&style=flat-square)](https://github.com/MuiseDestiny/zotero-reference)
[![GitHub Repo stars](https://img.shields.io/github/stars/MuiseDestiny/zotero-citation?label=zotero-citation&style=flat-square)](https://github.com/MuiseDestiny/zotero-citation)
[![GitHub Repo stars](https://img.shields.io/github/stars/MuiseDestiny/ZoteroStyle?label=zotero-style&style=flat-square)](https://github.com/MuiseDestiny/ZoteroStyle)
[![GitHub Repo stars](https://img.shields.io/github/stars/volatile-static/Chartero?label=Chartero&style=flat-square)](https://github.com/volatile-static/Chartero)
[![GitHub Repo stars](https://img.shields.io/github/stars/l0o0/tara?label=tara&style=flat-square)](https://github.com/l0o0/tara)
[![GitHub Repo stars](https://img.shields.io/github/stars/redleafnew/delitemwithatt?label=delitemwithatt&style=flat-square)](https://github.com/redleafnew/delitemwithatt)
[![GitHub Repo stars](https://img.shields.io/github/stars/redleafnew/zotero-updateifsE?label=zotero-updateifsE&style=flat-square)](https://github.com/redleafnew/zotero-updateifsE)
[![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)
[![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)
[![GitHub Repo stars](https://img.shields.io/github/stars/MuiseDestiny/zotero-gpt?label=zotero-gpt&style=flat-square)](https://github.com/MuiseDestiny/zotero-gpt)
[![GitHub Repo stars](https://img.shields.io/github/stars/zoushucai/zotero-journalabbr?label=zotero-journalabbr&style=flat-square)](https://github.com/zoushucai/zotero-journalabbr)
[![GitHub Repo stars](https://img.shields.io/github/stars/MuiseDestiny/zotero-figure?label=zotero-figure&style=flat-square)](https://github.com/MuiseDestiny/zotero-figure)
[![GitHub Repo stars](https://img.shields.io/github/stars/l0o0/jasminum?label=jasminum&style=flat-square)](https://github.com/l0o0/jasminum)
[![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)
[![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)
如果你正在使用此库,我建议你将这个标志 ([![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 文件中:
```md
[![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)
```
## Features 特性
- 事件驱动、函数式编程的可扩展框架;
- 简单易用,开箱即用;
- `src/modules/examples.ts` 中有丰富的示例,涵盖了插件中常用的大部分 API (使用 [zotero-plugin-toolkit](https://github.com/windingwind/zotero-plugin-toolkit);
- TypeScript 支持:
- 为使用 JavaScript 编写的 Zotero 源码提供全面的类型定义支持 (使用 [zotero-types](https://github.com/windingwind/zotero-types));
- 全局变量和环境设置;
- 插件开发/构建/发布工作流:
- ⭐自动热重载!每当修改源码时,都会自动编译并重新加载插件;
- 自动生成/更新插件版本、更新配置和设置环境变量 (`development`/`production`);
- 自动发布到 GitHub ;
- 集成 Prettier 和 ES Lint;
## Examples 示例
此库提供了 [zotero-plugin-toolkit](https://github.com/windingwind/zotero-plugin-toolkit) 中 API 的示例。
在 `src/examples.ts` 中搜索`@example` 查看示例。这些示例在 `src/hooks.ts` 中调用演示。
### 基本示例 (Basic Examples)
- registerNotifier
- registerPrefs, unregisterPrefs
### 快捷键示例 (Shortcut Keys Examples)
- registerShortcuts
- exampleShortcutLargerCallback
- exampleShortcutSmallerCallback
- exampleShortcutConflictionCallback
### UI 示例 (UI Examples)
![image](https://user-images.githubusercontent.com/33902321/211739774-cc5c2df8-5fd9-42f0-9cdf-0f2e5946d427.png)
- registerStyleSheet(the official make-it-red example)
- registerRightClickMenuItem
- registerRightClickMenuPopup
- registerWindowMenuWithSeprator
- registerExtraColumn
- registerExtraColumnWithCustomCell
- registerCustomItemBoxRow
- registerLibraryTabPanel
- registerReaderTabPanel
### 首选项面板示例 (Preference Pane Examples)
![image](https://user-images.githubusercontent.com/33902321/211737987-cd7c5c87-9177-4159-b975-dc67690d0490.png)
- Preferences bindings
- UI Events
- Table
- Locale
详情参见 [`src/modules/preferenceScript.ts`](./src/modules/preferenceScript.ts)
### 帮助示例 (HelperExamples)
![image](https://user-images.githubusercontent.com/33902321/215119473-e7d0d0ef-6d96-437e-b989-4805ffcde6cf.png)
- dialogExample
- clipboardExample
- filePickerExample
- progressWindowExample
- vtableExample(See Preference Pane Examples)
### 指令行示例 (PromptExamples)
Obsidian 风格的指令输入模块,它通过接受文本来运行插件,并在弹出窗口中显示可选项。
使用 `Shift+P` 激活。
![image](https://user-images.githubusercontent.com/33902321/215120009-e7c7ed27-33a0-44fe-b021-06c272481a92.png)
- registerAlertPromptExample
## 快速上手
### 0 环境要求
1. 安装 [beta 版 Zotero](https://www.zotero.org/support/beta_builds)
2. 安装 [Node.js 最新 LTS 版本](https://nodejs.org/zh-cn/download) 和 [Git](https://git-scm.com/)
> [!note]
> 本指南假定你已经对 Zotero 插件的基本结构和工作原理有初步的了解。如果你还不了解,请先参考[官方文档](https://www.zotero.org/support/dev/zotero_7_for_developers) 和[官方插件样例 Make It Red](https://github.com/zotero/make-it-red)。
### 1 创建你的仓库 (Create Your Repo)
1. 点击 `Use this template`;
2. 使用 `git clone` 克隆上一步生成的仓库;
<details >
<summary>💡 从 GitHub Codespace 开始</summary>
_GitHub CodeSpace_ 使你可以直接开始开发而无需在本地下载代码/IDE/依赖。
重复下列步骤,仅需三十秒即可开始构建你的第一个插件!
- 点击首页 `Use this template` 按钮,随后点击 `Open in codespace`,你需要登录你的 GitHub 账号。
- 等待 codespace 加载。
</details>
3. 进入项目文件夹;
### 2 配置模板和开发环境 (Config Template Settings and Enviroment)
1. 修改 `./package.json` 中的设置,包括:
```jsonc
{
"version": "", // 修改为 0.0.0
"description": "",
"config": {
"addonName": "", // 插件名称
"addonID": "", // 插件 ID【重要:防止冲突】
"addonRef": "", // 插件命名空间:元素前缀等
"addonInstance": "", // 注册在 Zotero 根下的实例名
"prefsPrefix": "extensions.zotero.${addonRef}", // 首选项的前缀
},
"repository": {
"type": "git",
"url": "git+https://github.com/your-github-name/repo-name.git",
},
"author": "Your Name",
"bugs": {
"url": "https://github.com/your-github-name/repo-name/issues",
},
"homepage": "https://github.com/your-github-name/repo-name#readme",
}
```
> [!warning]
> 注意设置 addonID 和 addonRef 以避免冲突。
如果你需要在 GitHub 以外的地方托管你的 XPI 包,请修改 `zotero-plugin.config.ts` 中的 `updateURL` 和 `xpiDownloadLink`。
2. 复制 Zotero 启动配置,填入 Zotero 可执行文件路径和 profile 路径。
> (可选项) 创建开发用 profile 目录:
>
> 此操作仅需执行一次:使用 `/path/to/zotero -p` 启动 Zotero,创建一个新的配置文件并用作开发配置文件。
```sh
cp .env.example .env
vim .env
```
如果你维护了多个插件,可以将这些内容存入系统环境变量,以避免在每个插件中都需要重复设置。
3. 运行 `npm install` 以安装相关依赖
> 如果你使用 `pnpm` 作为包管理器,你需要添加 `public-hoist-pattern[]=*@types/bluebird*` 到`.npmrc`, 详情请查看 [zotero-types](https://github.com/windingwind/zotero-types?tab=readme-ov-file#usage) 的文档。
如果你使用 `npm install` 的过程中遇到了 `npm ERR! ERESOLVE unable to resolve dependency tree` ,这是由于上游依赖 typescript-eslint 导致的错误,请使用 `npm i -f` 命令进行安装。
### 3 开发插件
使用 `npm start` 启动开发服务器,它将:
- 在开发模式下预构建插件
- 启动 Zotero,并让其从 `build/` 中加载插件
- 打开开发者工具(devtool)
- 监听 `src/**` 和 `addon/**`,当文件发生修改时,重新构建插件并且重新加载
#### 自动热重载
厌倦了无休止的重启吗?忘掉它,拥抱热加载!
1. 运行 `npm start`.
2. 编码。(是的,就这么简单)
当检测到 `src` 或 `addon` 中的文件修改时,插件将自动编译并重新加载。
<details style="text-indent: 2em">
<summary>💡 将此功能添加到现有插件的步骤</summary>
请参阅:[zotero-plugin-scaffold](https://github.com/northword/zotero-plugin-scaffold)。
</details>
#### 调试代码
你还可以:
- 在 Tools->Developer->Run Javascript 中测试代码片段;
- 使用 `Zotero.debug()` 调试输出。在 Help->Debug Output Logging->View Output 查看输出;
- 调试 UI. Zotero 建立在 Firefox XUL 框架之上。使用 [XUL Explorer](https://udn.realityripple.com/docs/Archive/Mozilla/XUL_Explorer) 等软件调试 XUL UI.
> XUL 文档:<http://www.devdoc.net/web/developer.mozilla.org/en-US/docs/XUL.html>
### 4 构建插件
运行 `npm run build` 在生产模式下构建插件,构建的结果位于 `.scaffold/build/` 目录中。
构建步骤文档可参阅 [zotero-plugin-scaffold](https://northword.github.io/zotero-plugin-scaffold/build.html)简单来说,可以分为以下几步:
- 创建/清空 `build/`
- 复制 `addon/**` 到 `.scaffold/build/addon/**`
- 替换占位符:替换在 `package.json` 中定义的关键字和配置
- 准备本地化文件以避免冲突,查看 [zotero_7_for_developers](https://www.zotero.org/support/dev/zotero_7_for_developers#avoiding_localization_conflicts) 了解更多
- 重命名`**/*.flt` 为 `**/${addonRef}-*.flt`
- 在每个消息前加上 `addonRef-`
- 为 FTL 消息生成类型声明文件
- 准备首选项文件,在首选项键前添加前缀 `package.json#prefsPrefix`,并为首选项生成类型声明文件
- 使用 ESBuild 来将 `.ts` 源码构建为 `.js`,从 `src/index.ts` 构建到`.scaffold/build/addon/content/scripts`
- (仅在生产模式下工作) 压缩 `.scaffold/build/addon` 目录为 `.scaffold/build/*.xpi`
- (仅在生产模式下工作) 准备 `update.json` 或 `update-beta.json`
> [!note]
>
> **Dev & prod 两者有什么区别?**
>
> - 此环境变量存储在 `Zotero.${addonInstance}.data.env` 中,控制台输出在生产模式下被禁用。
> - 你可以根据此变量决定用户无法查看/使用的内容。
> - 在生产模式下,构建脚本将自动打包插件并更新 `update.json`.
### 5 发布
如果要构建和发布插件,运行如下指令:
```shell
# version increase, git add, commit and push
# then on ci, npm run build, and release to GitHub
npm run release
```
> [!note]
> 在此模板中,发布流程被配置为在本地更新版本号、提交并推送标签,随后 GitHub Action 将重新构建插件并将 XPI 发布到 GitHub Release。
#### 关于预发布
该模板将 `prerelease` 定义为插件的测试版,当你在版本选择中选择 `prerelease` 版本 (版本号中带有 `-` ),构建脚本将创建一个 `update-beta.json` 给预发布版本使用,这将确保常规版本的用户不会自动更新到测试版,只有手动下载并安装了测试版的用户才能自动更新到下一个测试版。当下一个正式版本更新时,脚本将同步更新 `update.json` 和 `update-beta.json`,这将使正式版和测试版用户都可以更新到最新的正式版。
> [!warning]
> 严格来说,区分 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)。
## Details 更多细节
### 关于 Hooks(About Hooks)
> 可以在 [`src/hooks.ts`](https://github.com/windingwind/zotero-plugin-template/blob/main/src/hooks.ts) 中查看更多。
1. 当在 Zotero 中触发安装/启用/启动时,`bootstrap.js` > `startup` 被调用
- 等待 Zotero 就绪
- 加载 `index.js` (插件代码的主入口,从 `index.ts` 中构建)
- 如果是 Zotero 7 以上的版本则注册资源
2. 主入口 `index.js` 中,插件对象被注入到 `Zotero` ,并且 `hooks.ts` > `onStartup` 被调用。
- 初始化插件需要的资源,包括通知监听器、首选项面板和 UI 元素。
3. 当在 Zotero 中触发卸载/禁用时,`bootstrap.js` > `shutdown` 被调用。
- `events.ts` > `onShutdown` 被调用。移除 UI 元素、首选项面板或插件创建的任何内容。
- 移除脚本并释放资源。
### 关于全局变量 (About Global Variables)
> 可以在 [`src/index.ts`](https://github.com/windingwind/zotero-plugin-template/blob/main/src/index.ts)中查看更多
bootstrap 插件在沙盒中运行,但沙盒中没有默认的全局变量,例如 `Zotero` 或 `window` 等我们曾在 overlay 插件环境中使用的变量。
此模板将以下变量注册到全局范围:
```plain
Zotero, ZoteroPane, Zotero_Tabs, window, document, rootURI, ztoolkit, addon;
```
### 创建元素 API(Create Elements API)
插件模板为 bootstrap 插件提供了一些新的 API. 我们有两个原因使用这些 API,而不是使用 `createElement/createElementNS`:
- 在 bootstrap 模式下,插件必须在推出(禁用或卸载)时清理所有 UI 元素,这非常麻烦。使用 `createElement`,插件模板将维护这些元素。仅仅在退出时 `unregisterAll` .
- Zotero 7 需要 createElement()/createElementNS() → createXULElement() 来表示其他的 XUL 元素,而 Zotero 6 并不支持 `createXULElement`. 类似于 React.createElement 的 API `createElement` 检测 namespace(xul/html/svg) 并且自动创建元素,返回元素为对应的 TypeScript 元素类型。
```ts
createElement(document, "div"); // returns HTMLDivElement
createElement(document, "hbox"); // returns XUL.Box
createElement(document, "button", { namespace: "xul" }); // manually set namespace. returns XUL.Button
```
### 关于 Zotero API(About Zotero API)
Zotero 文档已过时且不完整,克隆 <https://github.com/zotero/zotero> 并全局搜索关键字。
> ⭐[zotero-types](https://github.com/windingwind/zotero-types) 提供了最常用的 Zotero API,在默认情况下它被包含在此模板中。你的 IDE 将为大多数的 API 提供提醒。
猜你需要:查找所需 API 的技巧
在 `.xhtml`/`.flt` 文件中搜索 UI 标签,然后在 locale 文件中找到对应的键。,然后在 `.js`/`.jsx` 文件中搜索此键。
### 目录结构 (Directory Structure)
本部分展示了模板的目录结构。
- 所有的 `.js/.ts` 代码都在 `./src`;
- 插件配置文件:`./addon/manifest.json`;
- UI 文件:`./addon/content/*.xhtml`.
- 区域设置文件:`./addon/locale/**/*.flt`;
- 首选项文件:`./addon/prefs.js`;
```shell
.
|-- .github/ # github conf
|-- .vscode/ # vscode conf
|-- addon # static files
| |-- bootstrap.js
| |-- content
| | |-- icons
| | | |-- favicon.png
| | | `-- favicon@0.5x.png
| | |-- preferences.xhtml
| | `-- zoteroPane.css
| |-- locale
| | |-- en-US
| | | |-- addon.ftl
| | | |-- mainWindow.ftl
| | | `-- preferences.ftl
| | `-- zh-CN
| | |-- addon.ftl
| | |-- mainWindow.ftl
| | `-- preferences.ftl
| |-- manifest.json
| `-- prefs.js
|-- build # build dir
|-- node_modules
|-- src # source code of scripts
| |-- addon.ts # base class
| |-- hooks.ts # lifecycle hooks
| |-- index.ts # main entry
| |-- modules # sub modules
| | |-- examples.ts
| | `-- preferenceScript.ts
| `-- utils # utilities
| |-- locale.ts
| |-- prefs.ts
| |-- wait.ts
| |-- window.ts
| `-- ztoolkit.ts
|-- typings # ts typings
| `-- global.d.ts
|-- .env # enviroment config (do not check into repo)
|-- .env.example # template of enviroment config, https://github.com/northword/zotero-plugin-scaffold
|-- .gitignore # git conf
|-- .gitattributes # git conf
|-- .prettierrc # prettier conf, https://prettier.io/
|-- eslint.config.mjs # eslint conf, https://eslint.org/
|-- LICENSE
|-- package-lock.json
|-- package.json
|-- tsconfig.json # typescript conf, https://code.visualstudio.com/docs/languages/jsconfig
|-- README.md
`-- zotero-plugin.config.ts # scaffold conf, https://github.com/northword/zotero-plugin-scaffold
```
## Disclaimer 免责声明
在 AGPL 下使用此代码。不提供任何保证。遵守你所在地区的法律!
如果你想更改许可,请通过 <wyzlshx@foxmail.com> 与我联系。

16
eslint.config.mjs Normal file
View File

@ -0,0 +1,16 @@
// @ts-check Let TS check this config file
import zotero from "@zotero-plugin/eslint-config";
export default zotero({
overrides: [
{
files: ["**/*.ts"],
rules: {
// We disable this rule here because the template
// contains some unused examples and variables
"@typescript-eslint/no-unused-vars": "off",
},
},
],
});

4667
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

63
package.json Normal file
View File

@ -0,0 +1,63 @@
{
"name": "zotero-pdf-copier-renamer",
"type": "module",
"version": "1.0.0",
"description": "Copy and rename PDF attachments of selected references",
"config": {
"addonName": "Zotero PDF Copier & Renamer",
"addonID": "zotero-pdf-copier-renamer@parvej.me",
"addonRef": "zoteroattachmentcopier",
"addonInstance": "ZoteroAttachmentCopier",
"prefsPrefix": "extensions.zotero.zoteroattachmentcopier"
},
"repository": {
"type": "git",
"url": "git+https://github.com/windingwind/zotero-plugin-template.git"
},
"author": "Md. Parvej Hossain <contact@parvej.me>",
"bugs": {
"url": "https://github.com/windingwind/zotero-plugin-template/issues"
},
"homepage": "https://github.com/windingwind/zotero-plugin-template#readme",
"license": "AGPL-3.0-or-later",
"scripts": {
"start": "zotero-plugin serve",
"build": "zotero-plugin build && tsc --noEmit",
"lint:check": "prettier --check . && eslint .",
"lint:fix": "prettier --write . && eslint . --fix",
"release": "zotero-plugin release",
"test": "zotero-plugin test",
"update-deps": "npm update --save"
},
"dependencies": {
"zotero-plugin-toolkit": "^5.1.0-beta.13"
},
"devDependencies": {
"@types/chai": "^5.2.3",
"@types/mocha": "^10.0.10",
"@types/node": "^24.10.0",
"@zotero-plugin/eslint-config": "^0.6.7",
"chai": "^6.2.1",
"eslint": "^9.39.2",
"mocha": "^11.7.5",
"prettier": "^3.7.4",
"typescript": "^5.9.3",
"zotero-plugin-scaffold": "^0.8.2",
"zotero-types": "^4.1.0-beta.4"
},
"prettier": {
"printWidth": 80,
"tabWidth": 2,
"endOfLine": "lf",
"overrides": [
{
"files": [
"*.xhtml"
],
"options": {
"htmlWhitespaceSensitivity": "css"
}
}
]
}
}

42
src/addon.ts Normal file
View File

@ -0,0 +1,42 @@
import { config } from "../package.json";
import { ColumnOptions, DialogHelper } from "zotero-plugin-toolkit";
import hooks from "./hooks";
import { createZToolkit } from "./utils/ztoolkit";
class Addon {
public data: {
alive: boolean;
config: typeof config;
// Env type, see build.js
env: "development" | "production";
initialized?: boolean;
ztoolkit: ZToolkit;
locale?: {
current: any;
};
prefs?: {
window: Window;
columns: Array<ColumnOptions>;
rows: Array<{ [dataKey: string]: string }>;
};
dialog?: DialogHelper;
};
// Lifecycle hooks
public hooks: typeof hooks;
// APIs
public api: object;
constructor() {
this.data = {
alive: true,
config,
env: __env__,
initialized: false,
ztoolkit: createZToolkit(),
};
this.hooks = hooks;
this.api = {};
}
}
export default Addon;

268
src/hooks.ts Normal file
View File

@ -0,0 +1,268 @@
declare const addon: any;
declare const ztoolkit: any;
declare const rootURI: string;
declare const Services: any;
declare const Components: any;
declare const PathUtils: any;
declare const IOUtils: any;
declare const ChromeUtils: any;
async function onStartup() {
await Promise.all([
Zotero.initializationPromise,
Zotero.unlockPromise,
Zotero.uiReadyPromise,
]);
await Promise.all(
Zotero.getMainWindows().map((win) => onMainWindowLoad(win)),
);
addon.data.initialized = true;
Zotero.debug("Zotero Attachment Copy: Startup completed");
}
async function onMainWindowLoad(win: _ZoteroTypes.MainWindow): Promise<void> {
// Register menu item on the individual library items context menu
ztoolkit.Menu.register("item", {
tag: "menuitem",
id: "zotero-itemmenu-attachmentcopy",
label: "Copy Attachments to Folder...",
commandListener: (ev: any) => {
handleCopyAttachments().catch((err) => {
Zotero.logError(err);
win.alert("Zotero Attachment Copy Error: " + err.message);
});
},
icon: `chrome://${addon.data.config.addonRef}/content/icons/favicon@0.5x.png`,
});
Zotero.debug("Zotero Attachment Copy: Menu item registered");
}
async function onMainWindowUnload(win: Window): Promise<void> {
ztoolkit.unregisterAll();
}
function onShutdown(): void {
ztoolkit.unregisterAll();
addon.data.alive = false;
// @ts-expect-error - Plugin instance is not typed
delete Zotero[addon.data.config.addonInstance];
}
async function handleCopyAttachments() {
let importedServices: any;
let importedPathUtils: any;
let importedIOUtils: any;
try {
importedServices = ChromeUtils.importESModule("resource://gre/modules/Services.sys.mjs").Services;
importedPathUtils = ChromeUtils.importESModule("resource://gre/modules/PathUtils.sys.mjs").PathUtils;
importedIOUtils = ChromeUtils.importESModule("resource://gre/modules/IOUtils.sys.mjs").IOUtils;
} catch (err: any) {
Zotero.logError(err);
importedServices = typeof Services !== 'undefined' ? Services : null;
importedPathUtils = typeof PathUtils !== 'undefined' ? PathUtils : null;
importedIOUtils = typeof IOUtils !== 'undefined' ? IOUtils : null;
}
// 1. Get Zotero pane and main window
const pane = Zotero.getActiveZoteroPane();
if (!pane) {
Zotero.logError(new Error("Zotero Attachment Copy: ZoteroPane is not active."));
return;
}
const window = pane.window || Zotero.getMainWindow() || (importedServices ? importedServices.wm.getMostRecentWindow("navigator:browser") : null);
if (!window) {
Zotero.logError(new Error("Zotero Attachment Copy: Main window not found."));
return;
}
const items = pane.getSelectedItems();
if (!items || items.length === 0) {
window.alert("Please select at least one paper reference.");
return;
}
const regularItems = items.filter(item => item.isRegularItem());
if (regularItems.length === 0) {
window.alert("Please select reference items (attachments or notes cannot be copied directly).");
return;
}
try {
// 2. Open Folder Picker
const fp = Components.classes["@mozilla.org/filepicker;1"]
.createInstance(Components.interfaces.nsIFilePicker);
try {
// @ts-expect-error - browsingContext is present on Gecko 125+ / Zotero 9+
fp.init(window.browsingContext, "Select Destination Folder", Components.interfaces.nsIFilePicker.modeGetFolder);
} catch (e) {
fp.init(window, "Select Destination Folder", Components.interfaces.nsIFilePicker.modeGetFolder);
}
fp.open(async (result: number) => {
try {
if (result !== Components.interfaces.nsIFilePicker.returnOK) {
return;
}
const folder = fp.file;
const destPath = folder.path;
Zotero.debug("Zotero Attachment Copy: Chosen destination path: " + destPath);
// 3. Initialize Progress Window
const pw = new Zotero.ProgressWindow({ closeOnClick: true });
pw.closeOnClick = true;
pw.changeHeadline("Copying PDF Attachments...");
// Add a clean graphical progress bar
const itemProgress = new pw.ItemProgress(
"chrome://zotero/skin/zotero_z_32px.png",
"Preparing selected items..."
);
pw.show();
let totalCopied = 0;
let totalFailed = 0;
const totalPapers = regularItems.length;
// Iterate through selected papers
for (let i = 0; i < totalPapers; i++) {
const item = regularItems[i];
const title = item.getField('title') || 'Untitled';
const sanitizedTitle = sanitizeFileName(title);
// Update live progress bar and description text dynamically
const pct = Math.round((i / totalPapers) * 100);
itemProgress.setProgress(pct);
itemProgress.setText(`Copying ${i + 1} of ${totalPapers}: ${title}`);
try {
const attachmentIDs = item.getAttachments();
if (!attachmentIDs || attachmentIDs.length === 0) {
continue;
}
const attachments = Zotero.Items.get(attachmentIDs).filter((x: any): x is any => !!x);
const pdfAttachments = attachments.filter(att => att.isPDFAttachment());
if (pdfAttachments.length === 0) {
continue;
}
for (let j = 0; j < pdfAttachments.length; j++) {
const att = pdfAttachments[j];
const srcPath = await att.getFilePathAsync();
if (!srcPath || !(await importedIOUtils.exists(srcPath))) {
pw.addDescription(`Failed: ${title} (PDF file not found)`);
totalFailed++;
continue;
}
// Determine destination file name
let destFileName = sanitizedTitle + ".pdf";
if (pdfAttachments.length > 1) {
destFileName = `${sanitizedTitle}_(${j + 1}).pdf`;
}
let finalDestPath = importedPathUtils.join(destPath, destFileName);
// Avoid overwriting by checking if file already exists
let overwriteCount = 0;
while (await importedIOUtils.exists(finalDestPath)) {
overwriteCount++;
if (pdfAttachments.length > 1) {
destFileName = `${sanitizedTitle}_(${j + 1}_${overwriteCount}).pdf`;
} else {
destFileName = `${sanitizedTitle}_(${overwriteCount}).pdf`;
}
finalDestPath = importedPathUtils.join(destPath, destFileName);
}
// Copy file using modern IOUtils.copy
Zotero.debug(`Zotero Attachment Copy: Copying from "${srcPath}" to "${finalDestPath}"`);
await importedIOUtils.copy(srcPath, finalDestPath);
totalCopied++;
}
} catch (err: any) {
Zotero.logError(err);
pw.addDescription(`Failed: ${title} - ${err.message}`);
totalFailed++;
}
}
// Complete progress display
pw.changeHeadline("Copy Completed!");
itemProgress.setProgress(100);
itemProgress.setText(`Successfully copied ${totalCopied} PDF(s).`);
if (totalFailed > 0) {
pw.addDescription(`Failed or missing: ${totalFailed} PDF(s).`);
}
// Auto-close after 5 seconds (5000 ms) using both Zotero and JS timers
pw.startCloseTimer(5000);
setTimeout(() => {
try {
pw.close();
} catch (e) {
// Ignore if already closed
}
}, 5000);
} catch (innerErr: any) {
Zotero.logError(innerErr);
window.alert("Zotero Attachment Copy: Copying failed - " + innerErr.message);
}
});
} catch (e: any) {
Zotero.logError(e);
window.alert("Zotero Attachment Copy: Folder picker failed - " + e.message);
}
}
function sanitizeFileName(title: string): string {
if (!title) return 'Untitled';
// Replace invalid characters on Windows/macOS/Linux: \ / : * ? " < > |
let sanitized = title.replace(/[\/\\:*?"<>|]/g, "_").trim();
// Trim length to avoid OS limits (keep filename under 120 characters)
if (sanitized.length > 120) {
sanitized = sanitized.substring(0, 120).trim();
}
return sanitized || 'Untitled';
}
async function onNotify(
event: string,
type: string,
ids: Array<string | number>,
extraData: { [key: string]: any },
) {
// Global notify handler
}
async function onPrefsEvent(type: string, data: { [key: string]: any }) {
// Preferences pane events handler
}
function onShortcuts(type: string) {
// Keyboard shortcut dispatcher
}
function onDialogEvents(type: string) {
// Dialog events dispatcher
}
export default {
onStartup,
onShutdown,
onMainWindowLoad,
onMainWindowUnload,
onNotify,
onPrefsEvent,
onShortcuts,
onDialogEvents,
};

25
src/index.ts Normal file
View File

@ -0,0 +1,25 @@
import { BasicTool } from "zotero-plugin-toolkit";
import Addon from "./addon";
import { config } from "../package.json";
const basicTool = new BasicTool();
// @ts-expect-error - Plugin instance is not typed
if (!basicTool.getGlobal("Zotero")[config.addonInstance]) {
_globalThis.addon = new Addon();
defineGlobal("ztoolkit", () => {
return _globalThis.addon.data.ztoolkit;
});
// @ts-expect-error - Plugin instance is not typed
Zotero[config.addonInstance] = addon;
}
function defineGlobal(name: Parameters<BasicTool["getGlobal"]>[0]): void;
function defineGlobal(name: string, getter: () => any): void;
function defineGlobal(name: string, getter?: () => any) {
Object.defineProperty(_globalThis, name, {
get() {
return getter ? getter() : basicTool.getGlobal(name);
},
});
}

866
src/modules/examples.ts Normal file
View File

@ -0,0 +1,866 @@
import { getLocaleID, getString } from "../utils/locale";
function example(
target: any,
propertyKey: string | symbol,
descriptor: PropertyDescriptor,
) {
const original = descriptor.value;
descriptor.value = function (...args: any) {
try {
ztoolkit.log(`Calling example ${target.name}.${String(propertyKey)}`);
return original.apply(this, args);
} catch (e) {
ztoolkit.log(`Error in example ${target.name}.${String(propertyKey)}`, e);
throw e;
}
};
return descriptor;
}
export class BasicExampleFactory {
@example
static registerNotifier() {
const callback = {
notify: async (
event: string,
type: string,
ids: number[] | string[],
extraData: { [key: string]: any },
) => {
if (!addon?.data.alive) {
this.unregisterNotifier(notifierID);
return;
}
addon.hooks.onNotify(event, type, ids, extraData);
},
};
// Register the callback in Zotero as an item observer
const notifierID = Zotero.Notifier.registerObserver(callback, [
"tab",
"item",
"file",
]);
Zotero.Plugins.addObserver({
shutdown: ({ id }) => {
if (id === addon.data.config.addonID)
this.unregisterNotifier(notifierID);
},
});
}
@example
static exampleNotifierCallback() {
new ztoolkit.ProgressWindow(addon.data.config.addonName)
.createLine({
text: "Open Tab Detected!",
type: "success",
progress: 100,
})
.show();
}
@example
private static unregisterNotifier(notifierID: string) {
Zotero.Notifier.unregisterObserver(notifierID);
}
@example
static registerPrefs() {
Zotero.PreferencePanes.register({
pluginID: addon.data.config.addonID,
src: rootURI + "content/preferences.xhtml",
label: getString("prefs-title"),
image: `chrome://${addon.data.config.addonRef}/content/icons/favicon.png`,
});
}
}
export class KeyExampleFactory {
@example
static registerShortcuts() {
// Register an event key for Alt+L
ztoolkit.Keyboard.register((ev, keyOptions) => {
ztoolkit.log(ev, keyOptions.keyboard);
if (keyOptions.keyboard?.equals("shift,l")) {
addon.hooks.onShortcuts("larger");
}
if (ev.shiftKey && ev.key === "S") {
addon.hooks.onShortcuts("smaller");
}
});
new ztoolkit.ProgressWindow(addon.data.config.addonName)
.createLine({
text: "Example Shortcuts: Alt+L/S/C",
type: "success",
})
.show();
}
@example
static exampleShortcutLargerCallback() {
new ztoolkit.ProgressWindow(addon.data.config.addonName)
.createLine({
text: "Larger!",
type: "default",
})
.show();
}
@example
static exampleShortcutSmallerCallback() {
new ztoolkit.ProgressWindow(addon.data.config.addonName)
.createLine({
text: "Smaller!",
type: "default",
})
.show();
}
}
export class UIExampleFactory {
@example
static registerStyleSheet(win: _ZoteroTypes.MainWindow) {
const doc = win.document;
const styles = ztoolkit.UI.createElement(doc, "link", {
properties: {
type: "text/css",
rel: "stylesheet",
href: `chrome://${addon.data.config.addonRef}/content/zoteroPane.css`,
},
});
doc.documentElement?.appendChild(styles);
doc.getElementById("zotero-item-pane-content")?.classList.add("makeItRed");
}
@example
static registerRightClickMenuItem() {
const menuIcon = `chrome://${addon.data.config.addonRef}/content/icons/favicon@0.5x.png`;
// item menuitem with icon
ztoolkit.Menu.register("item", {
tag: "menuitem",
id: "zotero-itemmenu-addontemplate-test",
label: getString("menuitem-label"),
commandListener: (ev) => addon.hooks.onDialogEvents("dialogExample"),
icon: menuIcon,
});
}
@example
static registerRightClickMenuPopup(win: Window) {
ztoolkit.Menu.register(
"item",
{
tag: "menu",
label: getString("menupopup-label"),
children: [
{
tag: "menuitem",
label: getString("menuitem-submenulabel"),
oncommand: "alert('Hello World! Sub Menuitem.')",
},
],
},
"before",
win.document?.querySelector(
"#zotero-itemmenu-addontemplate-test",
) as XUL.MenuItem,
);
}
@example
static registerWindowMenuWithSeparator() {
ztoolkit.Menu.register("menuFile", {
tag: "menuseparator",
});
// menu->File menuitem
ztoolkit.Menu.register("menuFile", {
tag: "menuitem",
label: getString("menuitem-filemenulabel"),
oncommand: "alert('Hello World! File Menuitem.')",
});
}
@example
static async registerExtraColumn() {
const field = "test1";
await Zotero.ItemTreeManager.registerColumns({
pluginID: addon.data.config.addonID,
dataKey: field,
label: "text column",
dataProvider: (item: Zotero.Item, dataKey: string) => {
return field + String(item.id);
},
iconPath: "chrome://zotero/skin/cross.png",
});
}
@example
static async registerExtraColumnWithCustomCell() {
const field = "test2";
await Zotero.ItemTreeManager.registerColumns({
pluginID: addon.data.config.addonID,
dataKey: field,
label: "custom column",
dataProvider: (item: Zotero.Item, dataKey: string) => {
return field + String(item.id);
},
renderCell(index, data, column, isFirstColumn, doc) {
ztoolkit.log("Custom column cell is rendered!");
const span = doc.createElement("span");
span.className = `cell ${column.className}`;
span.style.background = "#0dd068";
span.innerText = "⭐" + data;
return span;
},
});
}
@example
static registerItemPaneCustomInfoRow() {
Zotero.ItemPaneManager.registerInfoRow({
rowID: "example",
pluginID: addon.data.config.addonID,
editable: true,
label: {
l10nID: getLocaleID("item-info-row-example-label"),
},
position: "afterCreators",
onGetData: ({ item }) => {
return item.getField("title");
},
onSetData: ({ item, value }) => {
item.setField("title", value);
},
});
}
@example
static registerItemPaneSection() {
Zotero.ItemPaneManager.registerSection({
paneID: "example",
pluginID: addon.data.config.addonID,
header: {
l10nID: getLocaleID("item-section-example1-head-text"),
icon: "chrome://zotero/skin/16/universal/book.svg",
},
sidenav: {
l10nID: getLocaleID("item-section-example1-sidenav-tooltip"),
icon: "chrome://zotero/skin/20/universal/save.svg",
},
onRender: ({ body, item, editable, tabType }) => {
body.textContent = JSON.stringify({
id: item?.id,
editable,
tabType,
});
},
});
}
@example
static async registerReaderItemPaneSection() {
Zotero.ItemPaneManager.registerSection({
paneID: "reader-example",
pluginID: addon.data.config.addonID,
header: {
l10nID: getLocaleID("item-section-example2-head-text"),
// Optional
l10nArgs: `{"status": "Initialized"}`,
// Can also have a optional dark icon
icon: "chrome://zotero/skin/16/universal/book.svg",
},
sidenav: {
l10nID: getLocaleID("item-section-example2-sidenav-tooltip"),
icon: "chrome://zotero/skin/20/universal/save.svg",
},
// Optional
bodyXHTML:
'<html:h1 id="test">THIS IS TEST</html:h1><browser disableglobalhistory="true" remote="true" maychangeremoteness="true" type="content" flex="1" id="browser" style="width: 180%; height: 280px"/>',
// Optional, Called when the section is first created, must be synchronous
onInit: ({ item }) => {
ztoolkit.log("Section init!", item?.id);
},
// Optional, Called when the section is destroyed, must be synchronous
onDestroy: (props) => {
ztoolkit.log("Section destroy!");
},
// Optional, Called when the section data changes (setting item/mode/tabType/inTrash), must be synchronous. return false to cancel the change
onItemChange: ({ item, setEnabled, tabType }) => {
ztoolkit.log(`Section item data changed to ${item?.id}`);
setEnabled(tabType === "reader");
return true;
},
// Called when the section is asked to render, must be synchronous.
onRender: ({
body,
item,
setL10nArgs,
setSectionSummary,
setSectionButtonStatus,
}) => {
ztoolkit.log("Section rendered!", item?.id);
const title = body.querySelector("#test") as HTMLElement;
title.style.color = "red";
title.textContent = "LOADING";
setL10nArgs(`{ "status": "Loading" }`);
setSectionSummary("loading!");
setSectionButtonStatus("test", { hidden: true });
},
// Optional, can be asynchronous.
onAsyncRender: async ({
body,
item,
setL10nArgs,
setSectionSummary,
setSectionButtonStatus,
}) => {
ztoolkit.log("Section secondary render start!", item?.id);
await Zotero.Promise.delay(1000);
ztoolkit.log("Section secondary render finish!", item?.id);
const title = body.querySelector("#test") as HTMLElement;
title.style.color = "green";
title.textContent = item.getField("title");
setL10nArgs(`{ "status": "Loaded" }`);
setSectionSummary("rendered!");
setSectionButtonStatus("test", { hidden: false });
},
// Optional, Called when the section is toggled. Can happen anytime even if the section is not visible or not rendered
onToggle: ({ item }) => {
ztoolkit.log("Section toggled!", item?.id);
},
// Optional, Buttons to be shown in the section header
sectionButtons: [
{
type: "test",
icon: "chrome://zotero/skin/16/universal/empty-trash.svg",
l10nID: getLocaleID("item-section-example2-button-tooltip"),
onClick: ({ item, paneID }) => {
ztoolkit.log("Section clicked!", item?.id);
Zotero.ItemPaneManager.unregisterSection(paneID);
},
},
],
});
}
}
export class PromptExampleFactory {
@example
static registerNormalCommandExample() {
ztoolkit.Prompt.register([
{
name: "Normal Command Test",
label: "Plugin Template",
callback(prompt) {
ztoolkit.getGlobal("alert")("Command triggered!");
},
},
]);
}
@example
static registerAnonymousCommandExample(window: Window) {
ztoolkit.Prompt.register([
{
id: "search",
callback: async (prompt) => {
// https://github.com/zotero/zotero/blob/7262465109c21919b56a7ab214f7c7a8e1e63909/chrome/content/zotero/integration/quickFormat.js#L589
function getItemDescription(item: Zotero.Item) {
const nodes = [];
let str = "";
let author,
authorDate = "";
if (item.firstCreator) {
author = authorDate = item.firstCreator;
}
let date = item.getField("date", true, true) as string;
if (date && (date = date.substr(0, 4)) !== "0000") {
authorDate += " (" + parseInt(date) + ")";
}
authorDate = authorDate.trim();
if (authorDate) nodes.push(authorDate);
const publicationTitle = item.getField(
"publicationTitle",
false,
true,
);
if (publicationTitle) {
nodes.push(`<i>${publicationTitle}</i>`);
}
let volumeIssue = item.getField("volume");
const issue = item.getField("issue");
if (issue) volumeIssue += "(" + issue + ")";
if (volumeIssue) nodes.push(volumeIssue);
const publisherPlace = [];
let field;
if ((field = item.getField("publisher")))
publisherPlace.push(field);
if ((field = item.getField("place"))) publisherPlace.push(field);
if (publisherPlace.length) nodes.push(publisherPlace.join(": "));
const pages = item.getField("pages");
if (pages) nodes.push(pages);
if (!nodes.length) {
const url = item.getField("url");
if (url) nodes.push(url);
}
// compile everything together
for (let i = 0, n = nodes.length; i < n; i++) {
const node = nodes[i];
if (i != 0) str += ", ";
if (typeof node === "object") {
const label =
Zotero.getMainWindow().document.createElement("label");
label.setAttribute("value", str);
label.setAttribute("crop", "end");
str = "";
} else {
str += node;
}
}
if (str.length) str += ".";
return str;
}
function filter(ids: number[]) {
ids = ids.filter(async (id) => {
const item = (await Zotero.Items.getAsync(id)) as Zotero.Item;
return item.isRegularItem() && !(item as any).isFeedItem;
});
return ids;
}
const text = prompt.inputNode.value;
prompt.showTip("Searching...");
const s = new Zotero.Search();
s.addCondition("quicksearch-titleCreatorYear", "contains", text);
s.addCondition("itemType", "isNot", "attachment");
let ids = await s.search();
// prompt.exit will remove current container element.
// @ts-expect-error ignore
prompt.exit();
const container = prompt.createCommandsContainer();
container.classList.add("suggestions");
ids = filter(ids);
console.log(ids.length);
if (ids.length == 0) {
const s = new Zotero.Search();
const operators = [
"is",
"isNot",
"true",
"false",
"isInTheLast",
"isBefore",
"isAfter",
"contains",
"doesNotContain",
"beginsWith",
];
let hasValidCondition = false;
let joinMode = "all";
if (/\s*\|\|\s*/.test(text)) {
joinMode = "any";
}
text.split(/\s*(&&|\|\|)\s*/g).forEach((conditinString: string) => {
const conditions = conditinString.split(/\s+/g);
if (
conditions.length == 3 &&
operators.indexOf(conditions[1]) != -1
) {
hasValidCondition = true;
s.addCondition(
"joinMode",
joinMode as _ZoteroTypes.Search.Operator,
"",
);
s.addCondition(
conditions[0] as string,
conditions[1] as _ZoteroTypes.Search.Operator,
conditions[2] as string,
);
}
});
if (hasValidCondition) {
ids = await s.search();
}
}
ids = filter(ids);
console.log(ids.length);
if (ids.length > 0) {
ids.forEach((id: number) => {
const item = Zotero.Items.get(id);
const title = item.getField("title");
const ele = ztoolkit.UI.createElement(window.document!, "div", {
namespace: "html",
classList: ["command"],
listeners: [
{
type: "mousemove",
listener: function () {
// @ts-expect-error ignore
prompt.selectItem(this);
},
},
{
type: "click",
listener: () => {
prompt.promptNode.style.display = "none";
ztoolkit.getGlobal("Zotero_Tabs").select("zotero-pane");
ztoolkit.getGlobal("ZoteroPane").selectItem(item.id);
},
},
],
styles: {
display: "flex",
flexDirection: "column",
justifyContent: "start",
},
children: [
{
tag: "span",
styles: {
fontWeight: "bold",
overflow: "hidden",
textOverflow: "ellipsis",
whiteSpace: "nowrap",
},
properties: {
innerText: title,
},
},
{
tag: "span",
styles: {
overflow: "hidden",
textOverflow: "ellipsis",
whiteSpace: "nowrap",
},
properties: {
innerHTML: getItemDescription(item),
},
},
],
});
container.appendChild(ele);
});
} else {
// @ts-expect-error ignore
prompt.exit();
prompt.showTip("Not Found.");
}
},
},
]);
}
@example
static registerConditionalCommandExample() {
ztoolkit.Prompt.register([
{
name: "Conditional Command Test",
label: "Plugin Template",
// The when function is executed when Prompt UI is woken up by `Shift + P`, and this command does not display when false is returned.
when: () => {
const items = ztoolkit.getGlobal("ZoteroPane").getSelectedItems();
return items.length > 0;
},
callback(prompt) {
prompt.inputNode.placeholder = "Hello World!";
const items = ztoolkit.getGlobal("ZoteroPane").getSelectedItems();
ztoolkit.getGlobal("alert")(
`You select ${items.length} items!\n\n${items
.map(
(item, index) =>
String(index + 1) + ". " + item.getDisplayTitle(),
)
.join("\n")}`,
);
},
},
]);
}
}
export class HelperExampleFactory {
@example
static async dialogExample() {
const dialogData: { [key: string | number]: any } = {
inputValue: "test",
checkboxValue: true,
loadCallback: () => {
ztoolkit.log(dialogData, "Dialog Opened!");
},
unloadCallback: () => {
ztoolkit.log(dialogData, "Dialog closed!");
},
};
const dialogHelper = new ztoolkit.Dialog(10, 2)
.addCell(0, 0, {
tag: "h1",
properties: { innerHTML: "Helper Examples" },
})
.addCell(1, 0, {
tag: "h2",
properties: { innerHTML: "Dialog Data Binding" },
})
.addCell(2, 0, {
tag: "p",
properties: {
innerHTML:
"Elements with attribute 'data-bind' are binded to the prop under 'dialogData' with the same name.",
},
styles: {
width: "200px",
},
})
.addCell(3, 0, {
tag: "label",
namespace: "html",
attributes: {
for: "dialog-checkbox",
},
properties: { innerHTML: "bind:checkbox" },
})
.addCell(
3,
1,
{
tag: "input",
namespace: "html",
id: "dialog-checkbox",
attributes: {
"data-bind": "checkboxValue",
"data-prop": "checked",
type: "checkbox",
},
properties: { label: "Cell 1,0" },
},
false,
)
.addCell(4, 0, {
tag: "label",
namespace: "html",
attributes: {
for: "dialog-input",
},
properties: { innerHTML: "bind:input" },
})
.addCell(
4,
1,
{
tag: "input",
namespace: "html",
id: "dialog-input",
attributes: {
"data-bind": "inputValue",
"data-prop": "value",
type: "text",
},
},
false,
)
.addCell(5, 0, {
tag: "h2",
properties: { innerHTML: "Toolkit Helper Examples" },
})
.addCell(
6,
0,
{
tag: "button",
namespace: "html",
attributes: {
type: "button",
},
listeners: [
{
type: "click",
listener: (e: Event) => {
addon.hooks.onDialogEvents("clipboardExample");
},
},
],
children: [
{
tag: "div",
styles: {
padding: "2.5px 15px",
},
properties: {
innerHTML: "example:clipboard",
},
},
],
},
false,
)
.addCell(
7,
0,
{
tag: "button",
namespace: "html",
attributes: {
type: "button",
},
listeners: [
{
type: "click",
listener: (e: Event) => {
addon.hooks.onDialogEvents("filePickerExample");
},
},
],
children: [
{
tag: "div",
styles: {
padding: "2.5px 15px",
},
properties: {
innerHTML: "example:filepicker",
},
},
],
},
false,
)
.addCell(
8,
0,
{
tag: "button",
namespace: "html",
attributes: {
type: "button",
},
listeners: [
{
type: "click",
listener: (e: Event) => {
addon.hooks.onDialogEvents("progressWindowExample");
},
},
],
children: [
{
tag: "div",
styles: {
padding: "2.5px 15px",
},
properties: {
innerHTML: "example:progressWindow",
},
},
],
},
false,
)
.addCell(
9,
0,
{
tag: "button",
namespace: "html",
attributes: {
type: "button",
},
listeners: [
{
type: "click",
listener: (e: Event) => {
addon.hooks.onDialogEvents("vtableExample");
},
},
],
children: [
{
tag: "div",
styles: {
padding: "2.5px 15px",
},
properties: {
innerHTML: "example:virtualized-table",
},
},
],
},
false,
)
.addButton("Confirm", "confirm")
.addButton("Cancel", "cancel")
.addButton("Help", "help", {
noClose: true,
callback: (e) => {
dialogHelper.window?.alert(
"Help Clicked! Dialog will not be closed.",
);
},
})
.setDialogData(dialogData)
.open("Dialog Example");
addon.data.dialog = dialogHelper;
await dialogData.unloadLock.promise;
addon.data.dialog = undefined;
if (addon.data.alive)
ztoolkit.getGlobal("alert")(
`Close dialog with ${dialogData._lastButtonId}.\nCheckbox: ${dialogData.checkboxValue}\nInput: ${dialogData.inputValue}.`,
);
ztoolkit.log(dialogData);
}
@example
static clipboardExample() {
new ztoolkit.Clipboard()
.addText(
"![Plugin Template](https://github.com/windingwind/zotero-plugin-template)",
"text/unicode",
)
.addText(
'<a href="https://github.com/windingwind/zotero-plugin-template">Plugin Template</a>',
"text/html",
)
.copy();
ztoolkit.getGlobal("alert")("Copied!");
}
@example
static async filePickerExample() {
const path = await new ztoolkit.FilePicker(
"Import File",
"open",
[
["PNG File(*.png)", "*.png"],
["Any", "*.*"],
],
"image.png",
).open();
ztoolkit.getGlobal("alert")(`Selected ${path}`);
}
@example
static progressWindowExample() {
new ztoolkit.ProgressWindow(addon.data.config.addonName)
.createLine({
text: "ProgressWindow Example!",
type: "success",
progress: 100,
})
.show();
}
@example
static vtableExample() {
ztoolkit.getGlobal("alert")("See src/modules/preferenceScript.ts");
}
}

View File

@ -0,0 +1,32 @@
export async function registerPrefsScripts(prefWindow: Window) {
const doc = prefWindow.document;
// Get input elements from XHTML
const serverInput = doc.getElementById("zotero-prefpane-researchossync-serverUrl") as HTMLInputElement;
const tokenInput = doc.getElementById("zotero-prefpane-researchossync-apiToken") as HTMLInputElement;
if (serverInput && tokenInput) {
// Read currently saved preferences
const serverUrl = Zotero.Prefs.get("extensions.zotero.researchossync.serverUrl") as string || "http://localhost:3000";
const apiToken = Zotero.Prefs.get("extensions.zotero.researchossync.apiToken") as string || "";
// Populate the inputs
serverInput.value = serverUrl;
tokenInput.value = apiToken;
// Save settings immediately to preference branch as the user types or changes value
serverInput.addEventListener("input", () => {
Zotero.Prefs.set("extensions.zotero.researchossync.serverUrl", serverInput.value.trim());
});
serverInput.addEventListener("change", () => {
Zotero.Prefs.set("extensions.zotero.researchossync.serverUrl", serverInput.value.trim());
});
tokenInput.addEventListener("input", () => {
Zotero.Prefs.set("extensions.zotero.researchossync.apiToken", tokenInput.value.trim());
});
tokenInput.addEventListener("change", () => {
Zotero.Prefs.set("extensions.zotero.researchossync.apiToken", tokenInput.value.trim());
});
}
}

76
src/modules/syncDialog.ts Normal file
View File

@ -0,0 +1,76 @@
import * as api from "../utils/api";
export function getItemsToSync(selectedItems: any[], selectedCollection: any): any[] {
const flatItems: any[] = [];
function collectFromCollection(collection: any) {
const childItems = collection.getChildItems();
for (const item of childItems) {
if (item.isRegularItem()) {
flatItems.push(item);
}
}
const subCols = collection.getChildCollections();
for (const subCol of subCols) {
collectFromCollection(subCol);
}
}
if (selectedItems && selectedItems.length > 0) {
for (const item of selectedItems) {
if (item.isRegularItem()) {
flatItems.push(item);
}
}
} else if (selectedCollection) {
collectFromCollection(selectedCollection);
}
return flatItems;
}
export function openSyncDialog() {
const zoteroPane = Zotero.getActiveZoteroPane();
if (!zoteroPane) {
Zotero.getMainWindow().alert("No active Zotero pane found.");
return;
}
const selectedItems = zoteroPane.getSelectedItems();
const selectedCollection = zoteroPane.getSelectedCollection();
const flatItems = getItemsToSync(selectedItems, selectedCollection);
if (flatItems.length === 0) {
Zotero.getMainWindow().alert("No papers selected or found in the selected collection to sync.");
return;
}
// Verify configuration
const { serverUrl, apiToken } = api.getPreferences();
if (!serverUrl || !apiToken) {
const confirmed = Zotero.getMainWindow().confirm(
"Research OS Sync has not been configured yet.\n\nWould you like to open Settings now to add your credentials?"
);
if (confirmed) {
(Zotero.PreferencePanes as any).open(addon.data.config.addonID);
}
return;
}
// Open dialog
const mainWin = Zotero.getMainWindow();
const dialogUrl = `chrome://${addon.data.config.addonRef}/content/dialog.xhtml`;
mainWin.openDialog(
dialogUrl,
"researchossync-sync-dialog",
"chrome,centerscreen,resizable=yes,width=550,height=500",
{
Zotero,
addon,
items: flatItems,
api
}
);
}

114
src/utils/api.ts Normal file
View File

@ -0,0 +1,114 @@
import { encryptPayload, decryptPayload } from "./crypto";
export function getPreferences() {
const serverUrl = Zotero.Prefs.get("extensions.zotero.researchossync.serverUrl") as string || "http://localhost:3000";
const apiToken = Zotero.Prefs.get("extensions.zotero.researchossync.apiToken") as string || "";
return { serverUrl, apiToken };
}
async function handleResponseError(response: Response, apiToken: string): Promise<never> {
const text = await response.text();
try {
const parsed = JSON.parse(text);
if (parsed.payload && parsed.iv) {
const decryptedStr = await decryptPayload(parsed.payload, parsed.iv, apiToken);
let errorMsg = decryptedStr;
try {
const decryptedObj = JSON.parse(decryptedStr);
errorMsg = decryptedObj.error || errorMsg;
} catch (e) {}
throw new Error(`Server returned ${response.status}: ${errorMsg}`);
}
} catch (e: any) {
if (e.message && e.message.startsWith("Server returned")) {
throw e;
}
}
throw new Error(`Server returned ${response.status}: ${text}`);
}
export async function sendEncryptedRequest(path: string, body: any): Promise<any> {
const { serverUrl, apiToken } = getPreferences();
if (!apiToken) throw new Error("API Token is missing. Configure settings first.");
// 1. Encrypt body
const encrypted = await encryptPayload(JSON.stringify(body), apiToken);
// 2. Fetch
const url = `${serverUrl.replace(/\/$/, "")}${path}`;
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${apiToken}`
},
body: JSON.stringify(encrypted)
});
if (!response.ok) {
await handleResponseError(response, apiToken);
}
// 3. Decrypt response
const responseJson: any = await response.json();
if (!responseJson.payload || !responseJson.iv) {
return responseJson; // In case server returned unencrypted (e.g. error)
}
const decryptedStr = await decryptPayload(responseJson.payload, responseJson.iv, apiToken);
return JSON.parse(decryptedStr);
}
export async function sendEncryptedGetRequest(path: string): Promise<any> {
const { serverUrl, apiToken } = getPreferences();
if (!apiToken) throw new Error("API Token is missing. Configure settings first.");
const url = `${serverUrl.replace(/\/$/, "")}${path}`;
const response = await fetch(url, {
method: "GET",
headers: {
"Authorization": `Bearer ${apiToken}`
}
});
if (!response.ok) {
await handleResponseError(response, apiToken);
}
const responseJson: any = await response.json();
if (!responseJson.payload || !responseJson.iv) {
return responseJson;
}
const decryptedStr = await decryptPayload(responseJson.payload, responseJson.iv, apiToken);
return JSON.parse(decryptedStr);
}
export async function uploadPdf(fileBlob: Blob, filename: string): Promise<{ url: string; filename: string }> {
const { serverUrl, apiToken } = getPreferences();
if (!apiToken) throw new Error("API Token is missing. Configure settings first.");
const formData = new (Zotero.getMainWindow() as any).FormData();
formData.append("pdf", fileBlob, filename);
const url = `${serverUrl.replace(/\/$/, "")}/api/extension/upload-pdf`;
const response = await fetch(url, {
method: "POST",
headers: {
"Authorization": `Bearer ${apiToken}`
},
body: formData
});
if (!response.ok) {
await handleResponseError(response, apiToken);
}
const responseJson: any = await response.json();
if (!responseJson.payload || !responseJson.iv) {
return responseJson;
}
const decryptedStr = await decryptPayload(responseJson.payload, responseJson.iv, apiToken);
return JSON.parse(decryptedStr);
}

79
src/utils/crypto.ts Normal file
View File

@ -0,0 +1,79 @@
export async function deriveKey(token: string): Promise<any> {
const encoder = new TextEncoder();
const data = encoder.encode(token);
// Hash the token with SHA-256 to get 32 bytes key
const hash = await crypto.subtle.digest('SHA-256', data);
return await crypto.subtle.importKey(
'raw',
hash,
{ name: 'AES-GCM' },
false,
['encrypt', 'decrypt']
);
}
export async function encryptPayload(plainText: string, token: string): Promise<{ payload: string; iv: string }> {
const key = await deriveKey(token);
// Generate random 12-byte IV
const iv = crypto.getRandomValues(new Uint8Array(12));
const encoder = new TextEncoder();
const encodedData = encoder.encode(plainText);
// Encrypt data
const ciphertextBuffer = await crypto.subtle.encrypt(
{
name: 'AES-GCM',
iv: iv as any
},
key as any,
encodedData
);
// Convert ArrayBuffers to base64
const payloadBase64 = arrayBufferToBase64(ciphertextBuffer);
const ivBase64 = arrayBufferToBase64(iv.buffer);
return {
payload: payloadBase64,
iv: ivBase64
};
}
export async function decryptPayload(payloadBase64: string, ivBase64: string, token: string): Promise<string> {
const key = await deriveKey(token);
const iv = base64ToArrayBuffer(ivBase64);
const ciphertextBuffer = base64ToArrayBuffer(payloadBase64);
// Decrypt data
const decryptedBuffer = await crypto.subtle.decrypt(
{
name: 'AES-GCM',
iv: iv as any
},
key as any,
ciphertextBuffer
);
const decoder = new TextDecoder();
return decoder.decode(decryptedBuffer);
}
function arrayBufferToBase64(buffer: ArrayBuffer): string {
const bytes = new Uint8Array(buffer);
let binary = '';
for (let i = 0; i < bytes.byteLength; i++) {
binary += String.fromCharCode(bytes[i]);
}
return globalThis.btoa(binary);
}
function base64ToArrayBuffer(base64: string): ArrayBuffer {
const binaryString = globalThis.atob(base64);
const len = binaryString.length;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes.buffer;
}

96
src/utils/locale.ts Normal file
View File

@ -0,0 +1,96 @@
import { config } from "../../package.json";
import { FluentMessageId } from "../../typings/i10n";
export { initLocale, getString, getLocaleID };
/**
* Initialize locale data
*/
function initLocale() {
const l10n = new (
typeof Localization === "undefined"
? ztoolkit.getGlobal("Localization")
: Localization
)([`${config.addonRef}-addon.ftl`], true);
addon.data.locale = {
current: l10n,
};
}
/**
* Get locale string, see https://firefox-source-docs.mozilla.org/l10n/fluent/tutorial.html#fluent-translation-list-ftl
* @param localString ftl key
* @param options.branch branch name
* @param options.args args
* @example
* ```ftl
* # addon.ftl
* addon-static-example = This is default branch!
* .branch-example = This is a branch under addon-static-example!
* addon-dynamic-example =
{ $count ->
[one] I have { $count } apple
*[other] I have { $count } apples
}
* ```
* ```js
* getString("addon-static-example"); // This is default branch!
* getString("addon-static-example", { branch: "branch-example" }); // This is a branch under addon-static-example!
* getString("addon-dynamic-example", { args: { count: 1 } }); // I have 1 apple
* getString("addon-dynamic-example", { args: { count: 2 } }); // I have 2 apples
* ```
*/
function getString(localString: FluentMessageId): string;
function getString(localString: FluentMessageId, branch: string): string;
function getString(
localeString: FluentMessageId,
options: { branch?: string | undefined; args?: Record<string, unknown> },
): string;
function getString(...inputs: any[]) {
if (inputs.length === 1) {
return _getString(inputs[0]);
} else if (inputs.length === 2) {
if (typeof inputs[1] === "string") {
return _getString(inputs[0], { branch: inputs[1] });
} else {
return _getString(inputs[0], inputs[1]);
}
} else {
throw new Error("Invalid arguments");
}
}
interface Pattern {
value: string | null;
attributes: Array<{
name: string;
value: string;
}> | null;
}
function _getString(
localeString: FluentMessageId,
options: { branch?: string | undefined; args?: Record<string, unknown> } = {},
): string {
const localStringWithPrefix = `${config.addonRef}-${localeString}`;
const { branch, args } = options;
const pattern = addon.data.locale?.current.formatMessagesSync([
{ id: localStringWithPrefix, args },
])[0] as Pattern;
if (!pattern) {
return localStringWithPrefix;
}
if (branch && pattern.attributes) {
return (
pattern.attributes.find((attr) => attr.name === branch)?.value ||
localStringWithPrefix
);
} else {
return pattern.value || localStringWithPrefix;
}
}
function getLocaleID(id: FluentMessageId) {
return `${config.addonRef}-${id}`;
}

36
src/utils/prefs.ts Normal file
View File

@ -0,0 +1,36 @@
import { config } from "../../package.json";
type PluginPrefsMap = _ZoteroTypes.Prefs["PluginPrefsMap"];
const PREFS_PREFIX = config.prefsPrefix;
/**
* Get preference value.
* Wrapper of `Zotero.Prefs.get`.
* @param key
*/
export function getPref<K extends keyof PluginPrefsMap>(key: K) {
return Zotero.Prefs.get(`${PREFS_PREFIX}.${key}`, true) as PluginPrefsMap[K];
}
/**
* Set preference value.
* Wrapper of `Zotero.Prefs.set`.
* @param key
* @param value
*/
export function setPref<K extends keyof PluginPrefsMap>(
key: K,
value: PluginPrefsMap[K],
) {
return Zotero.Prefs.set(`${PREFS_PREFIX}.${key}`, value, true);
}
/**
* Clear preference value.
* Wrapper of `Zotero.Prefs.clear`.
* @param key
*/
export function clearPref(key: string) {
return Zotero.Prefs.clear(`${PREFS_PREFIX}.${key}`, true);
}

10
src/utils/window.ts Normal file
View File

@ -0,0 +1,10 @@
export { isWindowAlive };
/**
* Check if the window is alive.
* Useful to prevent opening duplicate windows.
* @param win
*/
function isWindowAlive(win?: Window) {
return win && !Components.utils.isDeadWrapper(win) && !win.closed;
}

48
src/utils/ztoolkit.ts Normal file
View File

@ -0,0 +1,48 @@
import { ZoteroToolkit } from "zotero-plugin-toolkit";
import { config } from "../../package.json";
export { createZToolkit };
function createZToolkit() {
const _ztoolkit = new ZoteroToolkit();
/**
* Alternatively, import toolkit modules you use to minify the plugin size.
* You can add the modules under the `MyToolkit` class below and uncomment the following line.
*/
// const _ztoolkit = new MyToolkit();
initZToolkit(_ztoolkit);
return _ztoolkit;
}
function initZToolkit(_ztoolkit: ReturnType<typeof createZToolkit>) {
const env = __env__;
_ztoolkit.basicOptions.log.prefix = `[${config.addonName}]`;
_ztoolkit.basicOptions.log.disableConsole = env === "production";
_ztoolkit.UI.basicOptions.ui.enableElementJSONLog = __env__ === "development";
_ztoolkit.UI.basicOptions.ui.enableElementDOMLog = __env__ === "development";
// Getting basicOptions.debug will load global modules like the debug bridge.
// since we want to deprecate it, should avoid using it unless necessary.
// _ztoolkit.basicOptions.debug.disableDebugBridgePassword =
// __env__ === "development";
_ztoolkit.basicOptions.api.pluginID = config.addonID;
_ztoolkit.ProgressWindow.setIconURI(
"default",
`chrome://${config.addonRef}/content/icons/favicon.png`,
);
}
import { BasicTool, unregister } from "zotero-plugin-toolkit";
import { UITool } from "zotero-plugin-toolkit";
class MyToolkit extends BasicTool {
UI: UITool;
constructor() {
super();
this.UI = new UITool(this);
}
unregisterAll() {
unregister(this);
}
}

8
test/startup.test.ts Normal file
View File

@ -0,0 +1,8 @@
import { assert } from "chai";
import { config } from "../package.json";
describe("startup", function () {
it("should have plugin instance defined", function () {
assert.isNotEmpty(Zotero[config.addonInstance]);
});
});

3
test/tsconfig.json Normal file
View File

@ -0,0 +1,3 @@
{
"extends": "../tsconfig.json"
}

5
tsconfig.json Normal file
View File

@ -0,0 +1,5 @@
{
"extends": "zotero-types/entries/sandbox/",
"include": ["src", "typings"],
"exclude": ["build", "addon"]
}

18
typings/global.d.ts vendored Normal file
View File

@ -0,0 +1,18 @@
declare const _globalThis: {
[key: string]: any;
Zotero: _ZoteroTypes.Zotero;
ztoolkit: ZToolkit;
addon: typeof addon;
};
declare type ZToolkit = ReturnType<
typeof import("../src/utils/ztoolkit").createZToolkit
>;
declare const ztoolkit: ZToolkit;
declare const rootURI: string;
declare const addon: import("../src/addon").default;
declare const __env__: "production" | "development";

26
typings/i10n.d.ts vendored Normal file
View File

@ -0,0 +1,26 @@
// Generated by zotero-plugin-scaffold
/* prettier-ignore */
/* eslint-disable */
// @ts-nocheck
export type FluentMessageId =
| 'item-info-row-example-label'
| 'item-section-example1-head-text'
| 'item-section-example1-sidenav-tooltip'
| 'item-section-example2-button-tooltip'
| 'item-section-example2-head-text'
| 'item-section-example2-sidenav-tooltip'
| 'menuitem-filemenulabel'
| 'menuitem-label'
| 'menuitem-submenulabel'
| 'menupopup-label'
| 'pref-enable'
| 'pref-help'
| 'pref-input'
| 'pref-title'
| 'prefs-table-detail'
| 'prefs-table-title'
| 'prefs-title'
| 'startup-begin'
| 'startup-finish'
| 'tabpanel-lib-tab-label'
| 'tabpanel-reader-tab-label';

14
typings/prefs.d.ts vendored Normal file
View File

@ -0,0 +1,14 @@
// Generated by zotero-plugin-scaffold
/* prettier-ignore */
/* eslint-disable */
// @ts-nocheck
// prettier-ignore
declare namespace _ZoteroTypes {
interface Prefs {
PluginPrefsMap: {
"serverUrl": string;
"apiToken": string;
};
}
}

Binary file not shown.

48
zotero-plugin.config.ts Normal file
View File

@ -0,0 +1,48 @@
import { defineConfig } from "zotero-plugin-scaffold";
import pkg from "./package.json";
export default defineConfig({
source: ["src", "addon"],
dist: ".scaffold/build",
name: pkg.config.addonName,
id: pkg.config.addonID,
namespace: pkg.config.addonRef,
updateURL: `https://github.com/{{owner}}/{{repo}}/releases/download/release/${
pkg.version.includes("-") ? "update-beta.json" : "update.json"
}`,
xpiDownloadLink:
"https://github.com/{{owner}}/{{repo}}/releases/download/v{{version}}/{{xpiName}}.xpi",
build: {
assets: ["addon/**/*.*"],
define: {
...pkg.config,
author: pkg.author,
description: pkg.description,
homepage: pkg.homepage,
buildVersion: pkg.version,
buildTime: "{{buildTime}}",
},
prefs: {
prefix: pkg.config.prefsPrefix,
},
esbuildOptions: [
{
entryPoints: ["src/index.ts"],
define: {
__env__: `"${process.env.NODE_ENV}"`,
},
bundle: true,
target: "firefox115",
outfile: `.scaffold/build/addon/content/scripts/${pkg.config.addonRef}.js`,
},
],
},
test: {
waitForPlugin: `() => Zotero.${pkg.config.addonInstance}.data.initialized`,
},
// If you need to see a more detailed log, uncomment the following line:
// logLevel: "trace",
});