Showing preview only (209K chars total). Download the full file or copy to clipboard to get everything.
Repository: MuiseDestiny/zotero-gpt
Branch: bootstrap
Commit: 8045362afdd9
Files: 56
Total size: 195.6 KB
Directory structure:
gitextract_w6wx77lm/
├── .github/
│ ├── ISSUE_TEMPLATE/
│ │ ├── config.yml
│ │ ├── report_bug_cn.yml
│ │ └── report_bug_en.yml
│ ├── dependabot.yml
│ └── workflows/
│ ├── manual.yml
│ ├── publish_wiki_tags.yml
│ └── wiki.yml
├── .gitignore
├── .release-it.json
├── .vscode/
│ ├── launch.json
│ └── toolkit.code-snippets
├── LICENSE
├── addon/
│ ├── bootstrap.js
│ ├── chrome/
│ │ ├── content/
│ │ │ └── md.css
│ │ └── locale/
│ │ ├── en-US/
│ │ │ ├── addon.properties
│ │ │ └── overlay.dtd
│ │ └── zh-CN/
│ │ ├── addon.properties
│ │ └── overlay.dtd
│ ├── chrome.manifest
│ ├── install.rdf
│ ├── manifest.json
│ └── prefs.js
├── package.json
├── scripts/
│ ├── build.js
│ ├── start.js
│ ├── stop.js
│ └── zotero-cmd-default.json
├── src/
│ ├── addon.ts
│ ├── hooks.ts
│ ├── index.ts
│ └── modules/
│ ├── Meet/
│ │ ├── BetterNotes.ts
│ │ ├── OpenAI.ts
│ │ ├── Zotero.ts
│ │ └── api.ts
│ ├── base.ts
│ ├── localStorage.ts
│ ├── locale.ts
│ ├── utils.ts
│ └── views.ts
├── tags/
│ ├── Abstract2Introduction.txt
│ ├── Add-Controlled-Tagger
│ ├── AddTags.txt
│ ├── AskAbstract.txt
│ ├── AskClipboard.txt
│ ├── AskExperimentDetails.txt
│ ├── AskJournal.txt
│ ├── AskPDF.txt
│ ├── Readme.md
│ ├── SearchItems.txt
│ └── Translate.txt
├── tsconfig.json
├── typing/
│ └── global.d.ts
├── update-template.json
├── update-template.rdf
├── update.json
└── update.rdf
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/ISSUE_TEMPLATE/config.yml
================================================
blank_issues_enabled: true
contact_links:
- name: 命令标签分享
url: https://github.com/MuiseDestiny/zotero-gpt/discussions/3
about: 如果你制作了一个命令标签,欢迎在这里分享给大家
================================================
FILE: .github/ISSUE_TEMPLATE/report_bug_cn.yml
================================================
name: 插件问题反馈
description: "报告本插件存在的问题,且您确信这是插件问题而不是您的问题"
#title: ""
#labels: ["bug"]
body:
- type: markdown
attributes:
value: |
感谢提交反馈!请尽可能完整填写以下信息,帮助我们更好地定位问题和快速解决问题
**在一切开始之前,请确保您已经阅读过 [wiki](https://github.com/MuiseDestiny/zotero-gpt/wiki) 页面**
即使**重启**您的`Zotero`之后,该问题依然存在
------
- type: checkboxes
attributes:
label: 这个问题是否已有issue
description: 请搜索全部 issue 和 [wiki](https://github.com/MuiseDestiny/zotero-gpt/wiki) 以查看您想反馈的问题是否已存在或已解决
options:
- label: 我确认没有已有issue,且已阅读**常见问题**
required: true
- type: textarea
attributes:
label: 运行环境
description: |
请详细填写您的运行环境,以下是一个例子:
- **OS**: Windows11 22H2
- **Zotero version**: 6.0.23
- **Plugin version**: 0.2.3
value: |
- **OS**:
- **Zotero version**:
- **Plugin version**:
validations:
required: true
- type: textarea
attributes:
label: 当前配置信息
description: 如果能打开插件,请执行 `/report` 命令,将输出的信息**左键双击**复制粘贴到这里
placeholder: |
`api` https://api.openai.com
`secretKey` sk-...D6vr
`model` gpt-3.5-turbo
`temperature` 1.0
validations:
required: false
- type: textarea
id: what-happened
attributes:
label: 问题详情
description: 请详细描述您遇到的问题。提示:如果可以,也请提供错误的截图
placeholder: |
描述您遇到的问题
说明您的预期结果和实际结果之间的差异
validations:
required: true
- type: textarea
attributes:
label: 补充说明
description: 链接?参考资料?任何更多背景信息!
placeholder: |
该问题是偶然发生的还是可以稳定复现?
是否与不同的Paper或PDF文件有关?
================================================
FILE: .github/ISSUE_TEMPLATE/report_bug_en.yml
================================================
name: Plugin Issue Report
description: "Report issues with this plugin, and you believe that it is a plugin issue rather than your own issue"
body:
- type: markdown
attributes:
value: |
Thank you for submitting feedback! Please fill in the information below as completely as possible to help us better locate the issue and resolve it quickly.
**Before everything starts, make sure you have read the [wiki](https://github.com/MuiseDestiny/zotero-gpt/wiki) page**
Even after **restarting** your `Zotero`, the issue still persists
------
- type: checkboxes
attributes:
label: Has this issue been reported before?
description: Please search all issues and the [wiki](https://github.com/MuiseDestiny/zotero-gpt/wiki) to see if the issue you want to report already exists or has been resolved
options:
- label: I confirm that there is no existing issue, and I have read the **FAQ**
required: true
- type: textarea
attributes:
label: Operating Environment
description: |
Please provide detailed information about your environment, here is an example:
- **OS**: Windows11 22H2
- **Zotero version**: 6.0.23
- **Plugin version**: 0.2.3
value: |
- **OS**:
- **Zotero version**:
- **Plugin version**:
validations:
required: true
- type: textarea
attributes:
label: Current Configuration Information
description: If you can open the plugin, please run the `/report` command, and **double-click** to copy and paste the output here
placeholder: |
`api` https://api.openai.com
`secretKey` sk-...D6vr
`model` gpt-3.5-turbo
`temperature` 1.0
validations:
required: false
- type: textarea
id: what-happened
attributes:
label: Issue Details
description: Please provide a detailed description of the issue you encountered. If possible, please also provide a screenshot of the error
placeholder: |
Describe the issue you encountered
Explain the difference between your expected results and the actual results
validations:
required: true
- type: textarea
attributes:
label: Additional Information
description: Links? References? Any more background information!
placeholder: |
Is the issue occurring randomly or can it be reproduced?
Is it related to different Papers or PDF files?
================================================
FILE: .github/dependabot.yml
================================================
# 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"
================================================
FILE: .github/workflows/manual.yml
================================================
name: Manual Trigger
permissions: write-all
on:
# 手动触发
workflow_dispatch:
# inputs:
# logLevel:
# description: 'Log level'
# required: true
# default: 'warning'
# type: choice
# options:
# - info
# - warning
# - debug
jobs:
release:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
with:
repository: ${{github.repository}}.wiki
path: wiki
- name: Update wiki
run: |
cd wiki
mkdir -p versions
export releases=$(curl -L \
-H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" \
-H "Accept: application/vnd.github+json" \
-H "X-GitHub-Api-Version: 2022-11-28" \
"https://api.github.com/repos/${GITHUB_REPOSITORY}/releases?per_page=100" \
)
result=$(echo "${releases}" \
| awk -vRS='"' '!(NR%2){gsub(/\n/, "\\\\n"); gsub(/\r/, "\\\\r")} {printf("%s%s", $0, RT)}' \
)
echo "$result" | jq -c '.[]' | while read -r release; do
draft=$(echo "$release" | jq -r '.draft')
prerelease=$(echo "$release" | jq -r '.prerelease')
if [ "$draft" == 'false' ] && [ "$prerelease" == 'false' ]; then
tag_name=$(echo "$release" | jq -r '.tag_name')
MAJOR_VERSION=$(echo ${tag_name} | cut -d. -f1)
MINOR_VERSION=$(echo ${tag_name} | cut -d. -f2)
dir_name=versions/${MAJOR_VERSION}.${MINOR_VERSION}
mkdir -p ${dir_name}
name=${dir_name}/${tag_name}.bk
if [ ! -f "${name}" ]; then
title=$(echo "$release" | jq -r '.name')
body=$(echo "$release" | jq -r '.body')
echo -e "## ${title} \n${body}" > ${name}
echo "file created: ${name}"
else
echo "file exists: ${name}"
fi
else
echo "draft: $draft, prerelease: $prerelease"
fi
done
# generate CHANGELOG.md
# get all files start with v recrusive, and sort by version
echo -e "" > CHANGELOG.md
export files=$(find versions -name "*" -type f | sort -r)
for file in ${files}; do
t=$(basename ${file})
echo -e "# ${t%.*} \n" >> CHANGELOG.md
cat ${file} >> CHANGELOG.md
echo -e "\n\n\n " >> CHANGELOG.md
done
cat CHANGELOG.md
ls -alhR -I .git
# commit and push
# check if there is any change
if [ -z "$(git status --porcelain)" ]; then
echo "No changes to commit"
exit 0
fi
git config user.name github-actions
git config user.email github-actions@github.com
git add .
git commit -m "Update wiki for ${tag_name}"
git push
================================================
FILE: .github/workflows/publish_wiki_tags.yml
================================================
name: Publish wiki tags
permissions: write-all
on:
push:
branches:
- bootstrap
paths:
- 'tags/*.txt'
jobs:
release:
runs-on: ubuntu-latest
steps:
- name: Checkout repo
uses: actions/checkout@v3
with:
repository: ${{github.repository}}
path: repo
- name: Checkout wiki
uses: actions/checkout@v3
with:
repository: ${{github.repository}}.wiki
path: wiki
- name: Update wiki
run: |
rm -rf wiki/labels
mkdir -p wiki/labels
cp -r repo/tags/*.txt wiki/labels/
cd wiki/labels
export files=$(find . -name "*.txt" -type f | sort -r)
for file in ${files}; do
t=$(basename ${file})
# echo "<pre>" > ${t%.*}.md
cat ${file} > ${t%.*}.md
# echo "</pre>" >> ${t%.*}.md
done
rm -rf *.txt
cd ../
ls -alhR -I .git
if [ -z "$(git status --porcelain)" ]; then
echo "No changes to commit"
exit 0
fi
git config user.name github-actions
git config user.email github-actions@github.com
git add .
git commit -m "Update wiki from ${{github.repository}}"
git push
================================================
FILE: .github/workflows/wiki.yml
================================================
name: Release Trigger
# https://docs.github.com/en/actions/using-jobs/assigning-permissions-to-jobs#overview
permissions: write-all
on:
# 通过Event API触发
release:
types: [released, edited]
jobs:
release:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
with:
repository: ${{github.repository}}.wiki
path: wiki
- name: Dump GitHub context
env:
GITHUB_CONTEXT: ${{ toJson(github) }}
run: |
echo "$GITHUB_CONTEXT"
- name: Check release
id: check_release
run: |
if [ ${{ github.event.release.draft }} == 'false' ] && [ ${{ github.event.release.prerelease }} == 'false' ]; then
echo "next=true" >> $GITHUB_ENV
else
echo "next=false" >> $GITHUB_ENV
fi
- name: Update wiki
if: ${{ env.next }}
run: |
cd wiki
mkdir -p versions
export tag_name=${{ github.event.release.tag_name }}
export body="${{ github.event.release.body }}"
export title="${{ github.event.release.name }}"
export MAJOR_VERSION=$(echo ${tag_name} | cut -d. -f1)
export MINOR_VERSION=$(echo ${tag_name} | cut -d. -f2)
export dir_name=versions/${MAJOR_VERSION}.${MINOR_VERSION}
# generate certain version wiki
mkdir -p ${dir_name}
export name=${dir_name}/${tag_name}.bk
echo -e "## ${title} \n${body}" > ${name}
# generate CHANGELOG.md
# get all files start with v recrusive, and sort by version
echo -e "" > CHANGELOG.md
export files=$(find versions -name "*" -type f | sort -r)
for file in ${files}; do
t=$(basename ${file})
echo -e "# ${t%.*} \n" >> CHANGELOG.md
cat ${file} >> CHANGELOG.md
echo -e "\n\n\n " >> CHANGELOG.md
done
ls -alhR -I .git
# commit and push
# check if there is any change
if [ -z "$(git status --porcelain)" ]; then
echo "No changes to commit"
exit 0
fi
git config user.name github-actions
git config user.email github-actions@github.com
git add .
git commit -m "Update wiki for ${tag_name}"
git push
================================================
FILE: .gitignore
================================================
**/builds
node_modules
package-lock.json
zotero-cmd.json
README.md
.env
**/test
================================================
FILE: .release-it.json
================================================
{
"npm": {
"publish": false
},
"github": {
"release": true,
"assets": ["builds/*.xpi"]
},
"hooks": {
"after:bump": "npm run build",
"after:release": "echo Successfully released ${name} v${version} to ${repo.repository}."
}
}
================================================
FILE: .vscode/launch.json
================================================
{
// 使用 IntelliSense 了解相关属性。
// 悬停以查看现有属性的描述。
// 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Restart",
"runtimeExecutable": "npm",
"runtimeArgs": [
"run",
"restart"
],
},
{
"type": "node",
"request": "launch",
"name": "Restart in Prod Mode",
"runtimeExecutable": "npm",
"runtimeArgs": [
"run",
"restart-prod"
],
}
]
}
================================================
FILE: .vscode/toolkit.code-snippets
================================================
{
"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}",
"});"
]
}
}
================================================
FILE: LICENSE
================================================
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/>.
================================================
FILE: addon/bootstrap.js
================================================
/**
* 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
*/
if (typeof Zotero == "undefined") {
var Zotero;
}
var chromeHandle;
// In Zotero 6, bootstrap methods are called before Zotero is initialized, and using include.js
// to get the Zotero XPCOM service would risk breaking Zotero startup. Instead, wait for the main
// Zotero window to open and get the Zotero object from there.
//
// In Zotero 7, bootstrap methods are not called until Zotero is initialized, and the 'Zotero' is
// automatically made available.
async function waitForZotero() {
if (typeof Zotero != "undefined") {
await Zotero.initializationPromise;
}
var { Services } = ChromeUtils.import("resource://gre/modules/Services.jsm");
var windows = Services.wm.getEnumerator("navigator:browser");
var found = false;
while (windows.hasMoreElements()) {
let win = windows.getNext();
if (win.Zotero) {
Zotero = win.Zotero;
found = true;
break;
}
}
if (!found) {
await new Promise((resolve) => {
var listener = {
onOpenWindow: function (aWindow) {
// Wait for the window to finish loading
let domWindow = aWindow
.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindowInternal || Ci.nsIDOMWindow);
domWindow.addEventListener(
"load",
function () {
domWindow.removeEventListener("load", arguments.callee, false);
if (domWindow.Zotero) {
Services.wm.removeListener(listener);
Zotero = domWindow.Zotero;
resolve();
}
},
false
);
},
};
Services.wm.addListener(listener);
});
}
await Zotero.initializationPromise;
}
function install(data, reason) {}
async function startup({ id, version, resourceURI, rootURI }, reason) {
await waitForZotero();
// String 'rootURI' introduced in Zotero 7
if (!rootURI) {
rootURI = resourceURI.spec;
}
if (Zotero.platformMajorVersion >= 102) {
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 + "chrome/content/"],
["locale", "__addonRef__", "en-US", rootURI + "chrome/locale/en-US/"],
["locale", "__addonRef__", "zh-CN", rootURI + "chrome/locale/zh-CN/"],
]);
} else {
setDefaultPrefs(rootURI);
}
/**
* 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}/chrome/content/scripts/index.js`,
ctx
);
}
function shutdown({ id, version, resourceURI, rootURI }, reason) {
if (reason === APP_SHUTDOWN) {
return;
}
if (typeof Zotero === "undefined") {
Zotero = Components.classes["@zotero.org/Zotero;1"].getService(
Components.interfaces.nsISupports
).wrappedJSObject;
}
Zotero.__addonInstance__.hooks.onShutdown();
Cc["@mozilla.org/intl/stringbundle;1"]
.getService(Components.interfaces.nsIStringBundleService)
.flushBundles();
Cu.unload(`${rootURI}/chrome/content/scripts/index.js`);
if (chromeHandle) {
chromeHandle.destruct();
chromeHandle = null;
}
}
function uninstall(data, reason) {}
// Loads default preferences from defaults/preferences/prefs.js in Zotero 6
function setDefaultPrefs(rootURI) {
var branch = Services.prefs.getDefaultBranch("");
var obj = {
pref(pref, value) {
switch (typeof value) {
case "boolean":
branch.setBoolPref(pref, value);
break;
case "string":
branch.setStringPref(pref, value);
break;
case "number":
branch.setIntPref(pref, value);
break;
default:
Zotero.logError(`Invalid type '${typeof value}' for pref '${pref}'`);
}
},
};
Zotero.getMainWindow().console.log(rootURI + "prefs.js");
Services.scriptloader.loadSubScript(rootURI + "prefs.js", obj);
}
================================================
FILE: addon/chrome/content/md.css
================================================
.markdown-body {
--color-prettylights-syntax-comment: #6e7781;
--color-prettylights-syntax-constant: #0550ae;
--color-prettylights-syntax-entity: #8250df;
--color-prettylights-syntax-storage-modifier-import: #24292f;
--color-prettylights-syntax-entity-tag: #116329;
--color-prettylights-syntax-keyword: #cf222e;
--color-prettylights-syntax-string: #0a3069;
--color-prettylights-syntax-variable: #953800;
--color-prettylights-syntax-brackethighlighter-unmatched: #82071e;
--color-prettylights-syntax-invalid-illegal-text: #f6f8fa;
--color-prettylights-syntax-invalid-illegal-bg: #82071e;
--color-prettylights-syntax-carriage-return-text: #f6f8fa;
--color-prettylights-syntax-carriage-return-bg: #cf222e;
--color-prettylights-syntax-string-regexp: #116329;
--color-prettylights-syntax-markup-list: #3b2300;
--color-prettylights-syntax-markup-heading: #0550ae;
--color-prettylights-syntax-markup-italic: #24292f;
--color-prettylights-syntax-markup-bold: #24292f;
--color-prettylights-syntax-markup-deleted-text: #82071e;
--color-prettylights-syntax-markup-deleted-bg: #ffebe9;
--color-prettylights-syntax-markup-inserted-text: #116329;
--color-prettylights-syntax-markup-inserted-bg: #dafbe1;
--color-prettylights-syntax-markup-changed-text: #953800;
--color-prettylights-syntax-markup-changed-bg: #ffd8b5;
--color-prettylights-syntax-markup-ignored-text: #eaeef2;
--color-prettylights-syntax-markup-ignored-bg: #0550ae;
--color-prettylights-syntax-meta-diff-range: #8250df;
--color-prettylights-syntax-brackethighlighter-angle: #57606a;
--color-prettylights-syntax-sublimelinter-gutter-mark: #8c959f;
--color-prettylights-syntax-constant-other-reference-link: #0a3069;
--color-fg-default: #24292f;
--color-fg-muted: #57606a;
--color-fg-subtle: #6e7781;
--color-canvas-default: transparent;
--color-canvas-subtle: rgba(89, 192, 188, .1);
--color-border-default: #d0d7de;
--color-border-muted: rgba(89, 192, 188, .2);
--color-neutral-muted: rgba(89, 192, 188, .2);
--color-accent-fg: #0969da;
--color-accent-emphasis: #0969da;
--color-attention-subtle: #fff8c5;
--color-danger-fg: #cf222e
}
.markdown-body {
-ms-text-size-adjust: 100%;
-webkit-text-size-adjust: 100%;
margin: 0;
color: var(--color-fg-default);
background-color: var(--color-canvas-default);
font-family: -apple-system, BlinkMacSystemFont, segoe ui, noto sans, Helvetica, Arial, sans-serif, apple color emoji, segoe ui emoji;
font-size: 16px;
line-height: 1.5;
word-wrap: break-word
}
.markdown-body .octicon {
display: inline-block;
fill: currentColor;
vertical-align: text-bottom
}
.markdown-body h1:hover .anchor .octicon-link:before,
.markdown-body h2:hover .anchor .octicon-link:before,
.markdown-body h3:hover .anchor .octicon-link:before,
.markdown-body h4:hover .anchor .octicon-link:before,
.markdown-body h5:hover .anchor .octicon-link:before,
.markdown-body h6:hover .anchor .octicon-link:before {
width: 16px;
height: 16px;
content: ' ';
display: inline-block;
background-color: currentColor;
-webkit-mask-image: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCAxNiAxNicgdmVyc2lvbj0nMS4xJyBhcmlhLWhpZGRlbj0ndHJ1ZSc+PHBhdGggZmlsbC1ydWxlPSdldmVub2RkJyBkPSdNNy43NzUgMy4yNzVhLjc1Ljc1IDAgMDAxLjA2IDEuMDZsMS4yNS0xLjI1YTIgMiAwIDExMi44MyAyLjgzbC0yLjUgMi41YTIgMiAwIDAxLTIuODMgMCAuNzUuNzUgMCAwMC0xLjA2IDEuMDYgMy41IDMuNSAwIDAwNC45NSAwbDIuNS0yLjVhMy41IDMuNSAwIDAwLTQuOTUtNC45NWwtMS4yNSAxLjI1em0tNC42OSA5LjY0YTIgMiAwIDAxMC0yLjgzbDIuNS0yLjVhMiAyIDAgMDEyLjgzIDAgLjc1Ljc1IDAgMDAxLjA2LTEuMDYgMy41IDMuNSAwIDAwLTQuOTUgMGwtMi41IDIuNWEzLjUgMy41IDAgMDA0Ljk1IDQuOTVsMS4yNS0xLjI1YS43NS43NSAwIDAwLTEuMDYtMS4wNmwtMS4yNSAxLjI1YTIgMiAwIDAxLTIuODMgMHonPjwvcGF0aD48L3N2Zz4=);
mask-image: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0naHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmcnIHZpZXdCb3g9JzAgMCAxNiAxNicgdmVyc2lvbj0nMS4xJyBhcmlhLWhpZGRlbj0ndHJ1ZSc+PHBhdGggZmlsbC1ydWxlPSdldmVub2RkJyBkPSdNNy43NzUgMy4yNzVhLjc1Ljc1IDAgMDAxLjA2IDEuMDZsMS4yNS0xLjI1YTIgMiAwIDExMi44MyAyLjgzbC0yLjUgMi41YTIgMiAwIDAxLTIuODMgMCAuNzUuNzUgMCAwMC0xLjA2IDEuMDYgMy41IDMuNSAwIDAwNC45NSAwbDIuNS0yLjVhMy41IDMuNSAwIDAwLTQuOTUtNC45NWwtMS4yNSAxLjI1em0tNC42OSA5LjY0YTIgMiAwIDAxMC0yLjgzbDIuNS0yLjVhMiAyIDAgMDEyLjgzIDAgLjc1Ljc1IDAgMDAxLjA2LTEuMDYgMy41IDMuNSAwIDAwLTQuOTUgMGwtMi41IDIuNWEzLjUgMy41IDAgMDA0Ljk1IDQuOTVsMS4yNS0xLjI1YS43NS43NSAwIDAwLTEuMDYtMS4wNmwtMS4yNSAxLjI1YTIgMiAwIDAxLTIuODMgMHonPjwvcGF0aD48L3N2Zz4=)
}
.markdown-body details,
.markdown-body figcaption,
.markdown-body figure {
display: block
}
.markdown-body summary {
display: list-item
}
.markdown-body [hidden] {
display: none !important
}
.markdown-body a {
background-color: transparent;
color: var(--color-accent-fg);
text-decoration: none
}
.markdown-body abbr[title] {
border-bottom: none;
text-decoration: underline dotted
}
.markdown-body b,
.markdown-body strong {
font-weight: var(--base-text-weight-semibold, 600)
}
.markdown-body dfn {
font-style: italic
}
.markdown-body h1 {
margin: .67em 0;
font-weight: var(--base-text-weight-semibold, 600);
padding-bottom: .3em;
font-size: 2em;
border-bottom: 1px solid var(--color-border-muted)
}
.markdown-body mark {
background-color: var(--color-attention-subtle);
color: var(--color-fg-default)
}
.markdown-body small {
font-size: 90%
}
.markdown-body sub,
.markdown-body sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline
}
.markdown-body sub {
bottom: -.25em
}
.markdown-body sup {
top: -.5em
}
.markdown-body img {
border-style: none;
max-width: 100%;
box-sizing: content-box;
background-color: var(--color-canvas-default)
}
.markdown-body code,
.markdown-body kbd,
.markdown-body pre,
.markdown-body samp {
font-family: monospace;
font-size: 1em
}
.markdown-body figure {
margin: 1em 40px
}
.markdown-body hr {
box-sizing: content-box;
overflow: hidden;
background: 0 0;
border-bottom: 1px solid var(--color-border-muted);
height: .25em;
padding: 0;
margin: 24px 0;
background-color: var(--color-border-default);
border: 0
}
.markdown-body input {
font: inherit;
margin: 0;
overflow: visible;
font-family: inherit;
font-size: inherit;
line-height: inherit
}
.markdown-body [type=button],
.markdown-body [type=reset],
.markdown-body [type=submit] {
-webkit-appearance: button
}
.markdown-body [type=checkbox],
.markdown-body [type=radio] {
box-sizing: border-box;
padding: 0
}
.markdown-body [type=number]::-webkit-inner-spin-button,
.markdown-body [type=number]::-webkit-outer-spin-button {
height: auto
}
.markdown-body [type=search]::-webkit-search-cancel-button,
.markdown-body [type=search]::-webkit-search-decoration {
-webkit-appearance: none
}
.markdown-body ::-webkit-input-placeholder {
color: inherit;
opacity: .54
}
.markdown-body ::-webkit-file-upload-button {
-webkit-appearance: button;
font: inherit
}
.markdown-body a:hover {
text-decoration: underline
}
.markdown-body ::placeholder {
color: var(--color-fg-subtle);
opacity: 1
}
.markdown-body hr::before {
display: table;
content: ""
}
.markdown-body hr::after {
display: table;
clear: both;
content: ""
}
.markdown-body table {
border-spacing: 0;
border-collapse: collapse;
display: block;
width: max-content;
max-width: 100%;
overflow: auto;
}
.markdown-body td,
.markdown-body th {
padding: 0
}
.markdown-body details summary {
cursor: pointer
}
.markdown-body details:not([open])>*:not(summary) {
display: none !important
}
.markdown-body a:focus,
.markdown-body [role=button]:focus,
.markdown-body input[type=radio]:focus,
.markdown-body input[type=checkbox]:focus {
outline: 2px solid var(--color-accent-fg);
outline-offset: -2px;
box-shadow: none
}
.markdown-body a:focus:not(:focus-visible),
.markdown-body [role=button]:focus:not(:focus-visible),
.markdown-body input[type=radio]:focus:not(:focus-visible),
.markdown-body input[type=checkbox]:focus:not(:focus-visible) {
outline: solid 1px transparent
}
.markdown-body a:focus-visible,
.markdown-body [role=button]:focus-visible,
.markdown-body input[type=radio]:focus-visible,
.markdown-body input[type=checkbox]:focus-visible {
outline: 2px solid var(--color-accent-fg);
outline-offset: -2px;
box-shadow: none
}
.markdown-body a:not([class]):focus,
.markdown-body a:not([class]):focus-visible,
.markdown-body input[type=radio]:focus,
.markdown-body input[type=radio]:focus-visible,
.markdown-body input[type=checkbox]:focus,
.markdown-body input[type=checkbox]:focus-visible {
outline-offset: 0
}
.markdown-body kbd {
display: inline-block;
padding: 3px 5px;
font: 11px ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas, Liberation Mono, monospace;
line-height: 10px;
color: var(--color-fg-default);
vertical-align: middle;
background-color: var(--color-canvas-subtle);
border: solid 1px var(--color-neutral-muted);
border-bottom-color: var(--color-neutral-muted);
border-radius: 6px;
box-shadow: inset 0 -1px 0 var(--color-neutral-muted)
}
.markdown-body h1,
.markdown-body h2,
.markdown-body h3,
.markdown-body h4,
.markdown-body h5,
.markdown-body h6 {
margin-top: 24px;
margin-bottom: 16px;
font-weight: var(--base-text-weight-semibold, 600);
line-height: 1.25
}
.markdown-body h2 {
font-weight: var(--base-text-weight-semibold, 600);
padding-bottom: .3em;
font-size: 1.5em;
border-bottom: 1px solid var(--color-border-muted)
}
.markdown-body h3 {
font-weight: var(--base-text-weight-semibold, 600);
font-size: 1.25em
}
.markdown-body h4 {
font-weight: var(--base-text-weight-semibold, 600);
font-size: 1em
}
.markdown-body h5 {
font-weight: var(--base-text-weight-semibold, 600);
font-size: .875em
}
.markdown-body h6 {
font-weight: var(--base-text-weight-semibold, 600);
font-size: .85em;
color: var(--color-fg-muted)
}
.markdown-body p {
margin-top: 0;
margin-bottom: 10px
}
.markdown-body blockquote {
margin: 0;
padding: 0 1em;
color: var(--color-fg-muted);
border-left: .25em solid var(--color-border-default)
}
.markdown-body ul,
.markdown-body ol {
margin-top: 0;
margin-bottom: 0;
padding-left: 2em
}
.markdown-body ol ol,
.markdown-body ul ol {
list-style-type: lower-roman
}
.markdown-body ul ul ol,
.markdown-body ul ol ol,
.markdown-body ol ul ol,
.markdown-body ol ol ol {
list-style-type: lower-alpha
}
.markdown-body dd {
margin-left: 0
}
.markdown-body tt,
.markdown-body code,
.markdown-body samp {
font-family: ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas, Liberation Mono, monospace;
font-size: 12px
}
.markdown-body pre {
margin-top: 0;
margin-bottom: 0;
font-family: ui-monospace, SFMono-Regular, SF Mono, Menlo, Consolas, Liberation Mono, monospace;
font-size: 12px;
word-wrap: normal
}
.markdown-body .octicon {
display: inline-block;
overflow: visible !important;
vertical-align: text-bottom;
fill: currentColor
}
.markdown-body input::-webkit-outer-spin-button,
.markdown-body input::-webkit-inner-spin-button {
margin: 0;
-webkit-appearance: none;
appearance: none
}
.markdown-body::before {
display: table;
content: ""
}
.markdown-body::after {
display: table;
clear: both;
content: ""
}
.markdown-body>*:first-child {
margin-top: 0.25em !important
}
.markdown-body>*:last-child {
margin-bottom: 0.25em !important
}
.markdown-body a:not([href]) {
color: inherit;
text-decoration: none
}
.markdown-body .absent {
color: var(--color-danger-fg)
}
.markdown-body .anchor {
float: left;
padding-right: 4px;
margin-left: -20px;
line-height: 1
}
.markdown-body .anchor:focus {
outline: none
}
.markdown-body p,
.markdown-body blockquote,
.markdown-body ul,
.markdown-body ol,
.markdown-body dl,
.markdown-body table,
.markdown-body pre,
.markdown-body details {
margin-top: 0;
margin-bottom: 16px
}
.markdown-body blockquote>:first-child {
margin-top: 0
}
.markdown-body blockquote>:last-child {
margin-bottom: 0
}
.markdown-body h1 .octicon-link,
.markdown-body h2 .octicon-link,
.markdown-body h3 .octicon-link,
.markdown-body h4 .octicon-link,
.markdown-body h5 .octicon-link,
.markdown-body h6 .octicon-link {
color: var(--color-fg-default);
vertical-align: middle;
visibility: hidden
}
.markdown-body h1:hover .anchor,
.markdown-body h2:hover .anchor,
.markdown-body h3:hover .anchor,
.markdown-body h4:hover .anchor,
.markdown-body h5:hover .anchor,
.markdown-body h6:hover .anchor {
text-decoration: none
}
.markdown-body h1:hover .anchor .octicon-link,
.markdown-body h2:hover .anchor .octicon-link,
.markdown-body h3:hover .anchor .octicon-link,
.markdown-body h4:hover .anchor .octicon-link,
.markdown-body h5:hover .anchor .octicon-link,
.markdown-body h6:hover .anchor .octicon-link {
visibility: visible
}
.markdown-body h1 tt,
.markdown-body h1 code,
.markdown-body h2 tt,
.markdown-body h2 code,
.markdown-body h3 tt,
.markdown-body h3 code,
.markdown-body h4 tt,
.markdown-body h4 code,
.markdown-body h5 tt,
.markdown-body h5 code,
.markdown-body h6 tt,
.markdown-body h6 code {
padding: 0 .2em;
font-size: inherit
}
.markdown-body summary h1,
.markdown-body summary h2,
.markdown-body summary h3,
.markdown-body summary h4,
.markdown-body summary h5,
.markdown-body summary h6 {
display: inline-block
}
.markdown-body summary h1 .anchor,
.markdown-body summary h2 .anchor,
.markdown-body summary h3 .anchor,
.markdown-body summary h4 .anchor,
.markdown-body summary h5 .anchor,
.markdown-body summary h6 .anchor {
margin-left: -40px
}
.markdown-body summary h1,
.markdown-body summary h2 {
padding-bottom: 0;
border-bottom: 0
}
.markdown-body ul.no-list,
.markdown-body ol.no-list {
padding: 0;
list-style-type: none
}
.markdown-body ol[type=a] {
list-style-type: lower-alpha
}
.markdown-body ol[type=A] {
list-style-type: upper-alpha
}
.markdown-body ol[type=i] {
list-style-type: lower-roman
}
.markdown-body ol[type=I] {
list-style-type: upper-roman
}
.markdown-body ol[type="1"] {
list-style-type: decimal
}
.markdown-body div>ol:not([type]) {
list-style-type: decimal
}
.markdown-body ul ul,
.markdown-body ul ol,
.markdown-body ol ol,
.markdown-body ol ul {
margin-top: 0;
margin-bottom: 0
}
.markdown-body li>p {
margin-top: 16px
}
.markdown-body li+li {
margin-top: .25em
}
.markdown-body dl {
padding: 0
}
.markdown-body dl dt {
padding: 0;
margin-top: 16px;
font-size: 1em;
font-style: italic;
font-weight: var(--base-text-weight-semibold, 600)
}
.markdown-body dl dd {
padding: 0 16px;
margin-bottom: 16px
}
.markdown-body table th {
font-weight: var(--base-text-weight-semibold, 600)
}
.markdown-body table th,
.markdown-body table td {
padding: 6px 13px;
border: 1px solid var(--color-border-default)
}
.markdown-body table tr {
background-color: var(--color-canvas-default);
border-top: 1px solid var(--color-border-muted)
}
.markdown-body table tr:nth-child(2n) {
background-color: var(--color-canvas-subtle)
}
.markdown-body table img {
background-color: transparent
}
.markdown-body img[align=right] {
padding-left: 20px
}
.markdown-body img[align=left] {
padding-right: 20px
}
.markdown-body .emoji {
max-width: none;
vertical-align: text-top;
background-color: transparent
}
.markdown-body span.frame {
display: block;
overflow: hidden
}
.markdown-body span.frame>span {
display: block;
float: left;
width: auto;
padding: 7px;
margin: 13px 0 0;
overflow: hidden;
border: 1px solid var(--color-border-default)
}
.markdown-body span.frame span img {
display: block;
float: left
}
.markdown-body span.frame span span {
display: block;
padding: 5px 0 0;
clear: both;
color: var(--color-fg-default)
}
.markdown-body span.align-center {
display: block;
overflow: hidden;
clear: both
}
.markdown-body span.align-center>span {
display: block;
margin: 13px auto 0;
overflow: hidden;
text-align: center
}
.markdown-body span.align-center span img {
margin: 0 auto;
text-align: center
}
.markdown-body span.align-right {
display: block;
overflow: hidden;
clear: both
}
.markdown-body span.align-right>span {
display: block;
margin: 13px 0 0;
overflow: hidden;
text-align: right
}
.markdown-body span.align-right span img {
margin: 0;
text-align: right
}
.markdown-body span.float-left {
display: block;
float: left;
margin-right: 13px;
overflow: hidden
}
.markdown-body span.float-left span {
margin: 13px 0 0
}
.markdown-body span.float-right {
display: block;
float: right;
margin-left: 13px;
overflow: hidden
}
.markdown-body span.float-right>span {
display: block;
margin: 13px auto 0;
overflow: hidden;
text-align: right
}
.markdown-body code,
.markdown-body tt {
padding: .2em .4em;
margin: 0;
font-size: 85%;
white-space: break-spaces;
background-color: var(--color-neutral-muted);
border-radius: 6px
}
.markdown-body code br,
.markdown-body tt br {
display: none
}
.markdown-body del code {
text-decoration: inherit
}
.markdown-body samp {
font-size: 85%
}
.markdown-body pre code {
font-size: 100%
}
.markdown-body pre>code {
padding: 0;
margin: 0;
word-break: normal;
white-space: pre;
background: 0 0;
border: 0
}
.markdown-body .highlight {
margin-bottom: 16px
}
.markdown-body .highlight pre {
margin-bottom: 0;
word-break: normal
}
.markdown-body .highlight pre,
.markdown-body pre {
padding: 16px;
overflow: auto;
font-size: 85%;
line-height: 1.45;
background-color: var(--color-canvas-subtle);
border-radius: 6px
}
.markdown-body pre code,
.markdown-body pre tt {
display: inline;
max-width: auto;
padding: 0;
margin: 0;
overflow: visible;
line-height: inherit;
word-wrap: normal;
background-color: transparent;
border: 0
}
.markdown-body .csv-data td,
.markdown-body .csv-data th {
padding: 5px;
overflow: hidden;
font-size: 12px;
line-height: 1;
text-align: left;
white-space: nowrap
}
.markdown-body .csv-data .blob-num {
padding: 10px 8px 9px;
text-align: right;
background: var(--color-canvas-default);
border: 0
}
.markdown-body .csv-data tr {
border-top: 0
}
.markdown-body .csv-data th {
font-weight: var(--base-text-weight-semibold, 600);
background: var(--color-canvas-subtle);
border-top: 0
}
.markdown-body [data-footnote-ref]::before {
content: "["
}
@-webkit-keyframes blink {
to {
visibility: hidden;
}
}
@keyframes blink {
to {
visibility: hidden;
}
}
.markdown-body math {
display: none;
}
.markdown-body svg {
margin-left: 0.25em;
margin-right: 0.25em;
}
.streaming>span:after,
.streaming>ul:last-child li:last-child:after,
.streaming>pre:last-child code:after,
.streaming>ol:last-child li:last-child:after,
.streaming>:not(ol):not(ul):not(pre):last-child:after {
-webkit-animation: blink 1s steps(5, start) infinite !important;
animation: blink 1s steps(5, start) infinite !important;
content: "▋";
margin-left: .25rem;
vertical-align: baseline
}
.markdown-body [data-footnote-ref]::after {
content: "]"
}
.markdown-body .footnotes {
font-size: 12px;
color: var(--color-fg-muted);
border-top: 1px solid var(--color-border-default)
}
.markdown-body .footnotes ol {
padding-left: 16px
}
.markdown-body .footnotes ol ul {
display: inline-block;
padding-left: 16px;
margin-top: 16px
}
.markdown-body .footnotes li {
position: relative
}
.markdown-body .footnotes li:target::before {
position: absolute;
top: -8px;
right: -8px;
bottom: -8px;
left: -24px;
pointer-events: none;
content: "";
border: 2px solid var(--color-accent-emphasis);
border-radius: 6px
}
.markdown-body .footnotes li:target {
color: var(--color-fg-default)
}
.markdown-body .footnotes .data-footnote-backref g-emoji {
font-family: monospace
}
.markdown-body .pl-c {
color: var(--color-prettylights-syntax-comment)
}
.markdown-body .pl-c1,
.markdown-body .pl-s .pl-v {
color: var(--color-prettylights-syntax-constant)
}
.markdown-body .pl-e,
.markdown-body .pl-en {
color: var(--color-prettylights-syntax-entity)
}
.markdown-body .pl-smi,
.markdown-body .pl-s .pl-s1 {
color: var(--color-prettylights-syntax-storage-modifier-import)
}
.markdown-body .pl-ent {
color: var(--color-prettylights-syntax-entity-tag)
}
.markdown-body .pl-k {
color: var(--color-prettylights-syntax-keyword)
}
.markdown-body .pl-s,
.markdown-body .pl-pds,
.markdown-body .pl-s .pl-pse .pl-s1,
.markdown-body .pl-sr,
.markdown-body .pl-sr .pl-cce,
.markdown-body .pl-sr .pl-sre,
.markdown-body .pl-sr .pl-sra {
color: var(--color-prettylights-syntax-string)
}
.markdown-body .pl-v,
.markdown-body .pl-smw {
color: var(--color-prettylights-syntax-variable)
}
.markdown-body .pl-bu {
color: var(--color-prettylights-syntax-brackethighlighter-unmatched)
}
.markdown-body .pl-ii {
color: var(--color-prettylights-syntax-invalid-illegal-text);
background-color: var(--color-prettylights-syntax-invalid-illegal-bg)
}
.markdown-body .pl-c2 {
color: var(--color-prettylights-syntax-carriage-return-text);
background-color: var(--color-prettylights-syntax-carriage-return-bg)
}
.markdown-body .pl-sr .pl-cce {
font-weight: 700;
color: var(--color-prettylights-syntax-string-regexp)
}
.markdown-body .pl-ml {
color: var(--color-prettylights-syntax-markup-list)
}
.markdown-body .pl-mh,
.markdown-body .pl-mh .pl-en,
.markdown-body .pl-ms {
font-weight: 700;
color: var(--color-prettylights-syntax-markup-heading)
}
.markdown-body .pl-mi {
font-style: italic;
color: var(--color-prettylights-syntax-markup-italic)
}
.markdown-body .pl-mb {
font-weight: 700;
color: var(--color-prettylights-syntax-markup-bold)
}
.markdown-body .pl-md {
color: var(--color-prettylights-syntax-markup-deleted-text);
background-color: var(--color-prettylights-syntax-markup-deleted-bg)
}
.markdown-body .pl-mi1 {
color: var(--color-prettylights-syntax-markup-inserted-text);
background-color: var(--color-prettylights-syntax-markup-inserted-bg)
}
.markdown-body .pl-mc {
color: var(--color-prettylights-syntax-markup-changed-text);
background-color: var(--color-prettylights-syntax-markup-changed-bg)
}
.markdown-body .pl-mi2 {
color: var(--color-prettylights-syntax-markup-ignored-text);
background-color: var(--color-prettylights-syntax-markup-ignored-bg)
}
.markdown-body .pl-mdr {
font-weight: 700;
color: var(--color-prettylights-syntax-meta-diff-range)
}
.markdown-body .pl-ba {
color: var(--color-prettylights-syntax-brackethighlighter-angle)
}
.markdown-body .pl-sg {
color: var(--color-prettylights-syntax-sublimelinter-gutter-mark)
}
.markdown-body .pl-corl {
text-decoration: underline;
color: var(--color-prettylights-syntax-constant-other-reference-link)
}
.markdown-body g-emoji {
display: inline-block;
min-width: 1ch;
font-family: apple color emoji, segoe ui emoji, segoe ui symbol;
font-size: 1em;
font-style: normal !important;
font-weight: var(--base-text-weight-normal, 400);
line-height: 1;
vertical-align: -.075em
}
.markdown-body g-emoji img {
width: 1em;
height: 1em
}
.markdown-body .task-list-item {
list-style-type: none
}
.markdown-body .task-list-item label {
font-weight: var(--base-text-weight-normal, 400)
}
.markdown-body .task-list-item.enabled label {
cursor: pointer
}
.markdown-body .task-list-item+.task-list-item {
margin-top: 4px
}
.markdown-body .task-list-item .handle {
display: none
}
.markdown-body .task-list-item-checkbox {
margin: 0 .2em .25em -1.4em;
vertical-align: middle
}
.markdown-body .contains-task-list:dir(rtl) .task-list-item-checkbox {
margin: 0 -1.6em .25em .2em
}
.markdown-body .contains-task-list {
position: relative
}
.markdown-body .contains-task-list:hover .task-list-item-convert-container,
.markdown-body .contains-task-list:focus-within .task-list-item-convert-container {
display: block;
width: auto;
height: 24px;
overflow: visible;
clip: auto
}
.markdown-body ::-webkit-calendar-picker-indicator {
filter: invert(50%)
}
================================================
FILE: addon/chrome/locale/en-US/addon.properties
================================================
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
================================================
FILE: addon/chrome/locale/en-US/overlay.dtd
================================================
<!ENTITY zotero.__addonRef__.pref.title "Addon Template Example">
<!ENTITY zotero.__addonRef__.itemmenu.test.label "addon template">
<!ENTITY zotero.__addonRef__.pref.enable.label "Enable">
<!ENTITY zotero.__addonRef__.pref.input.label "Input">
<!ENTITY zotero.__addonRef__.help.version.label "__addonName__ VERSION __buildVersion__">
<!ENTITY zotero.__addonRef__.help.releasetime.label "Build __buildTime__">
================================================
FILE: addon/chrome/locale/zh-CN/addon.properties
================================================
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=阅读器标签
================================================
FILE: addon/chrome/locale/zh-CN/overlay.dtd
================================================
<!ENTITY zotero.__addonRef__.pref.title "插件模板设置示例">
<!ENTITY zotero.__addonRef__.itemmenu.test.label "插件模板">
<!ENTITY zotero.__addonRef__.pref.enable.label "开启">
<!ENTITY zotero.__addonRef__.pref.input.label "输入">
<!ENTITY zotero.__addonRef__.help.version.label "__addonName__ 版本 __buildVersion__">
<!ENTITY zotero.__addonRef__.help.releasetime.label "Build __buildTime__">
================================================
FILE: addon/chrome.manifest
================================================
content __addonRef__ chrome/content/
locale __addonRef__ en-US chrome/locale/en-US/
locale __addonRef__ zh-CN chrome/locale/zh-CN/
================================================
FILE: addon/install.rdf
================================================
<?xml version="1.0"?>
<RDF:RDF
xmlns:em="http://www.mozilla.org/2004/em-rdf#"
xmlns:NC="http://home.netscape.com/NC-rdf#"
xmlns:RDF="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
<RDF:Description
RDF:about="urn:mozilla:install-manifest"
em:id="__addonID__"
em:name="__addonName__"
em:version="__buildVersion__"
em:type="2"
em:creator="__author__"
em:description="__description__"
em:homepageURL="__homepage__"
em:iconURL="chrome://__addonRef__/content/icons/favicon.png"
em:optionsURL="chrome://__addonRef__/content/preferences.xul"
em:updateURL="__updaterdf__"
em:multiprocessCompatible="true"
em:bootstrap="true">
<em:targetApplication>
<Description>
<em:id>zotero@chnm.gmu.edu</em:id>
<em:minVersion>5.0</em:minVersion>
<em:maxVersion>*</em:maxVersion>
</Description>
</em:targetApplication>
<em:targetApplication>
<Description>
<em:id>juris-m@juris-m.github.io</em:id>
<em:minVersion>5.0</em:minVersion>
<em:maxVersion>*</em:maxVersion>
</Description>
</em:targetApplication>
</RDF:Description>
</RDF:RDF>
================================================
FILE: addon/manifest.json
================================================
{
"manifest_version": 2,
"name": "__addonName__",
"version": "__buildVersion__",
"description": "__description__",
"author": "__author__",
"icons": {
"48": "chrome/content/icons/favicon@0.5x.png",
"96": "chrome/content/icons/favicon.png"
},
"applications": {
"zotero": {
"id": "__addonID__",
"update_url": "__updaterdf__",
"strict_min_version": "6.999",
"strict_max_version": "7.0.*"
}
}
}
================================================
FILE: addon/prefs.js
================================================
pref("extensions.zotero.__addonRef__.enable", true);
pref("extensions.zotero.__addonRef__.tags", "[]");
pref("extensions.zotero.__addonRef__.secretKey", "");
pref("extensions.zotero.__addonRef__.model", "gpt-3.5-turbo");
pref("extensions.zotero.__addonRef__.api", "https://api.openai.com");
pref("extensions.zotero.__addonRef__.temperature", "1.0");
pref("extensions.zotero.__addonRef__.deltaTime", 100);
pref("extensions.zotero.__addonRef__.width", "32%");
pref("extensions.zotero.__addonRef__.tagsMore", "expand");
pref("extensions.zotero.__addonRef__.chatNumber", 3);
pref("extensions.zotero.__addonRef__.relatedNumber", 5);
pref("extensions.zotero.__addonRef__.embeddingBatchNum", 10);
================================================
FILE: package.json
================================================
{
"name": "zotero-gpt",
"version": "0.2.8",
"description": "GPT Meet Zotero",
"config": {
"addonName": "Zotero GPT",
"addonID": "zoterogpt@polygon.org",
"addonRef": "zoterogpt",
"addonInstance": "ZoteroGPT",
"releasepage": "",
"updaterdf": ""
},
"main": "src/index.ts",
"scripts": {
"build-dev": "cross-env NODE_ENV=development node scripts/build.js",
"build-prod": "cross-env NODE_ENV=production node scripts/build.js",
"build": "concurrently -c auto npm:build-prod npm:tsc",
"tsc": "tsc --noEmit",
"start-z6": "node scripts/start.js --z 6",
"start-z7": "node scripts/start.js --z 7",
"start": "node scripts/start.js",
"stop": "node scripts/stop.js",
"restart-dev": "npm run build-dev && npm run stop && npm run start",
"restart-prod": "npm run build-prod && npm run stop && npm run start",
"restart": "npm run restart-dev",
"release": "release-it",
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/MuiseDestiny/zotero-gpt.git"
},
"author": "Polygon",
"license": "AGPL-3.0-or-later",
"bugs": {
"url": "https://github.com/MuiseDestiny/zotero-gpt/issues"
},
"homepage": "",
"dependencies": {
"@dqbd/tiktoken": "^1.0.6",
"@iktakahiro/markdown-it-katex": "^4.0.1",
"@pinecone-database/pinecone": "^0.0.14",
"blueimp-md5": "^2.19.0",
"chromadb": "^1.3.1",
"compute-cosine-similarity": "^1.0.0",
"crypto": "^1.0.1",
"crypto-js": "^4.1.1",
"dotenv": "^16.0.3",
"gpt-3-encoder": "^1.1.4",
"highlight": "^0.2.4",
"highlight.js": "^11.7.0",
"htmldiff-js": "^1.0.5",
"langchain": "^0.0.66",
"lighten-darken-color": "^1.0.0",
"markdown-it": "^13.0.1",
"markdown-it-mathjax3": "^4.3.2",
"node-fetch": "^3.3.1",
"pdf-parse": "^1.1.1",
"pdfreader": "^3.0.0",
"proxy-agent": "^5.0.0",
"react-markdown": "^8.0.6",
"showdown": "^2.1.0",
"terser": "^5.17.1",
"zotero-adv-installer": "file:..",
"zotero-plugin-toolkit": "^2.0.1"
},
"devDependencies": {
"@types/crypto-js": "^4.1.1",
"@types/markdown-it": "^12.2.3",
"@types/node": "^18.11.17",
"compressing": "^1.6.3",
"concurrently": "^8.0.1",
"cross-env": "^7.0.3",
"esbuild": "^0.17.4",
"esbuild-plugin-wasm": "^1.0.0",
"minimist": "^1.2.7",
"punycode": "^2.3.0",
"release-it": "^15.6.0",
"replace-in-file": "^6.3.5",
"typescript": "^5.0.4",
"uglify-js": "^3.17.4",
"zotero-types": "^1.0.12"
}
}
================================================
FILE: scripts/build.js
================================================
const esbuild = require("esbuild");
const compressing = require("compressing");
const path = require("path");
const fs = require("fs");
const process = require("process");
const replace = require("replace-in-file");
const UglifyJS = require("terser");
const {
name,
author,
description,
homepage,
version,
config,
} = require("../package.json");
function copyFileSync(source, target) {
var targetFile = target;
// If target is a directory, a new file with the same name will be created
if (fs.existsSync(target)) {
if (fs.lstatSync(target).isDirectory()) {
targetFile = path.join(target, path.basename(source));
}
}
fs.writeFileSync(targetFile, fs.readFileSync(source));
}
function copyFolderRecursiveSync(source, target) {
var files = [];
// Check if folder needs to be created or integrated
var targetFolder = path.join(target, path.basename(source));
if (!fs.existsSync(targetFolder)) {
fs.mkdirSync(targetFolder);
}
// Copy
if (fs.lstatSync(source).isDirectory()) {
files = fs.readdirSync(source);
files.forEach(function (file) {
var curSource = path.join(source, file);
if (fs.lstatSync(curSource).isDirectory()) {
copyFolderRecursiveSync(curSource, targetFolder);
} else {
copyFileSync(curSource, targetFolder);
}
});
}
}
function clearFolder(target) {
if (fs.existsSync(target)) {
fs.rmSync(target, { recursive: true, force: true });
}
fs.mkdirSync(target, { recursive: true });
}
function dateFormat(fmt, date) {
let ret;
const opt = {
"Y+": date.getFullYear().toString(),
"m+": (date.getMonth() + 1).toString(),
"d+": date.getDate().toString(),
"H+": date.getHours().toString(),
"M+": date.getMinutes().toString(),
"S+": date.getSeconds().toString(),
};
for (let k in opt) {
ret = new RegExp("(" + k + ")").exec(fmt);
if (ret) {
fmt = fmt.replace(
ret[1],
ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, "0")
);
}
}
return fmt;
}
async function main() {
const t = new Date();
const buildTime = dateFormat("YYYY-mm-dd HH:MM:SS", t);
const buildDir = "builds";
console.log(
`[Build] BUILD_DIR=${buildDir}, VERSION=${version}, BUILD_TIME=${buildTime}, ENV=${[
process.env.NODE_ENV,
]}`
);
clearFolder(buildDir);
copyFolderRecursiveSync("addon", buildDir);
copyFileSync("update-template.json", "update.json");
copyFileSync("update-template.rdf", "update.rdf");
const outfile = path.join(buildDir, "addon/chrome/content/scripts/index.js");
await esbuild
.build({
entryPoints: ["src/index.ts"],
define: {
__env__: `"${process.env.NODE_ENV}"`,
},
bundle: true,
outfile,
// Don't turn minify on
// minify: true,
target: "firefox60",
})
.catch(() => process.exit(1));
console.log("[Build] Run esbuild OK");
const indexJsContent = fs.readFileSync(outfile, "utf-8");
const result = await UglifyJS.minify(indexJsContent, {
output: { ascii_only: true },
});
if (result.error) {
console.log("UglifyJS error", result.error);
process.exit(1);
}
fs.writeFileSync(outfile, result.code, "utf-8");
const replaceFrom = [
/__author__/g,
/__description__/g,
/__homepage__/g,
/__buildVersion__/g,
/__buildTime__/g,
];
const replaceTo = [author, description, homepage, version, buildTime];
replaceFrom.push(
...Object.keys(config).map((k) => new RegExp(`__${k}__`, "g"))
);
replaceTo.push(...Object.values(config));
const optionsAddon = {
files: [
path.join(buildDir, "**/*.rdf"),
path.join(buildDir, "**/*.dtd"),
path.join(buildDir, "**/*.xul"),
path.join(buildDir, "**/*.xhtml"),
path.join(buildDir, "**/*.json"),
path.join(buildDir, "addon/prefs.js"),
path.join(buildDir, "addon/chrome.manifest"),
path.join(buildDir, "addon/manifest.json"),
path.join(buildDir, "addon/bootstrap.js"),
"update.json",
"update.rdf",
],
from: replaceFrom,
to: replaceTo,
countMatches: true,
};
_ = replace.sync(optionsAddon);
console.log(
"[Build] Run replace in ",
_.filter((f) => f.hasChanged).map(
(f) => `${f.file} : ${f.numReplacements} / ${f.numMatches}`
)
);
console.log("[Build] Replace OK");
console.log("[Build] Addon prepare OK");
await compressing.zip.compressDir(
path.join(buildDir, "addon"),
path.join(buildDir, `${name}.xpi`),
{
ignoreBase: true,
}
);
console.log("[Build] Addon pack OK");
console.log(
`[Build] Finished in ${(new Date().getTime() - t.getTime()) / 1000} s.`
);
}
main().catch((err) => {
console.log(err);
process.exit(1);
});
================================================
FILE: scripts/start.js
================================================
const { execSync } = require("child_process");
const { exit } = require("process");
const { exec } = require("./zotero-cmd.json");
// Run node start.js -h for help
const args = require("minimist")(process.argv.slice(2));
if (args.help || args.h) {
console.log("Start Zotero Args:");
console.log(
"--zotero(-z): Zotero exec key in zotero-cmd.json. Default the first one."
);
console.log("--profile(-p): Zotero profile name.");
exit(0);
}
const zoteroPath = exec[args.zotero || args.z || Object.keys(exec)[0]];
const profile = args.profile || args.p;
const startZotero = `${zoteroPath} --debugger --purgecaches ${
profile ? `-p ${profile}` : ""
}`;
execSync(startZotero);
exit(0);
================================================
FILE: scripts/stop.js
================================================
const { execSync } = require("child_process");
const { killZoteroWindows, killZoteroUnix } = require("./zotero-cmd.json");
try {
if (process.platform === "win32") {
execSync(killZoteroWindows);
} else {
execSync(killZoteroUnix);
}
} catch (e) {}
================================================
FILE: scripts/zotero-cmd-default.json
================================================
{
"usage": "Copy and rename this file to zotero-cmd.json. Edit the cmd.",
"killZoteroWindows": "taskkill /f /im zotero.exe",
"killZoteroUnix": "kill -9 $(ps -x | grep zotero)",
"exec": {
"6": "/path/to/zotero6.exe",
"7": "/path/to/zotero7.exe"
}
}
================================================
FILE: src/addon.ts
================================================
import ZoteroToolkit from "zotero-plugin-toolkit/dist/index";
import { ColumnOptions } from "zotero-plugin-toolkit/dist/helpers/virtualizedTable";
import hooks from "./hooks";
class Addon {
public data: {
alive: boolean;
// Env type, see build.js
env: "development" | "production";
// ztoolkit: MyToolkit;
ztoolkit: ZoteroToolkit;
locale?: {
stringBundle: any;
};
prefs?: {
window: Window;
columns: Array<ColumnOptions>;
rows: Array<{ [dataKey: string]: string }>;
};
};
// Lifecycle hooks
public hooks: typeof hooks;
// APIs
public api: {};
constructor() {
this.data = {
alive: true,
env: __env__,
// ztoolkit: new MyToolkit(),
ztoolkit: new ZoteroToolkit(),
};
this.hooks = hooks;
this.api = {};
}
}
export default Addon;
================================================
FILE: src/hooks.ts
================================================
import { config } from "../package.json";
import { getString, initLocale } from "./modules/locale";
import Views from "./modules/views";
import Utils from "./modules/utils";
import { initValidation } from "../../validation/core";
async function onStartup() {
initValidation(config.addonRef);
await Promise.all([
Zotero.initializationPromise,
Zotero.unlockPromise,
Zotero.uiReadyPromise,
]);
initLocale();
ztoolkit.ProgressWindow.setIconURI(
"default",
`chrome://${config.addonRef}/content/icons/favicon.png`
);
Zotero[config.addonInstance].views = new Views();
Zotero[config.addonInstance].utils = new Utils();
}
function onShutdown(): void {
ztoolkit.unregisterAll();
// Remove addon object
addon.data.alive = false;
delete Zotero[config.addonInstance];
}
export default {
onStartup,
onShutdown,
};
================================================
FILE: src/index.ts
================================================
import { BasicTool } from "zotero-plugin-toolkit/dist/basic";
import Addon from "./addon";
import { config } from "../package.json";
const basicTool = new BasicTool();
if (!basicTool.getGlobal("Zotero")[config.addonInstance]) {
// Set global variables
let window: Window
_globalThis.Zotero = basicTool.getGlobal("Zotero");
_globalThis.ZoteroPane = basicTool.getGlobal("ZoteroPane");
_globalThis.Zotero_Tabs = basicTool.getGlobal("Zotero_Tabs");
_globalThis.window = window = basicTool.getGlobal("window");
_globalThis.URL = basicTool.getGlobal("window").URL;
_globalThis.setTimeout = basicTool.getGlobal("window").setTimeout;
_globalThis.URLSearchParams = basicTool.getGlobal("window").URLSearchParams;
_globalThis.Headers = basicTool.getGlobal("window").Headers;
_globalThis.AbortSignal = basicTool.getGlobal("window").AbortSignal;
_globalThis.Request = basicTool.getGlobal("window").Request;
_globalThis.AbortSignal.timeout = (ms: number) => {
// @ts-ignore
const controller = new window.AbortController();
const timer = window.setTimeout(() => controller.abort(), ms);
controller.signal.addEventListener("abort", () => {
window.clearTimeout(timer);
});
return controller.signal;
}
_globalThis.document = basicTool.getGlobal("document");
_globalThis.addon = new Addon();
_globalThis.ztoolkit = addon.data.ztoolkit;
ztoolkit.basicOptions.log.prefix = `[${config.addonName}]`;
ztoolkit.basicOptions.log.disableConsole = addon.data.env === "production";
ztoolkit.UI.basicOptions.ui.enableElementJSONLog = false
ztoolkit.UI.basicOptions.ui.enableElementDOMLog = false
ztoolkit.basicOptions.debug.disableDebugBridgePassword =
addon.data.env === "development";
Zotero[config.addonInstance] = addon;
// Trigger addon hook for initialization
addon.hooks.onStartup();
}
================================================
FILE: src/modules/Meet/BetterNotes.ts
================================================
import Views from "../views";
import Meet from "./api";
/**
* 优先返回选中文本,再返回所在span前所有文字MD
* @param span 光标所在行,HTMLSpanElement
* @returns
*/
export async function getEditorText(span: HTMLSpanElement) {
const BNEditorApi = Zotero.BetterNotes.api.editor
const editor = BNEditorApi.getEditorInstance(Zotero.BetterNotes.data.workspace.mainId);
let lines = [...editor._iframeWindow.document.querySelector(".primary-editor").childNodes]
lines = lines.slice(0, lines.indexOf(span))
const context = await Zotero.BetterNotes.api.convert.html2md(lines.map(e => e.outerHTML).join("\n"))
let range = Zotero.BetterNotes.api.editor.getRangeAtCursor(editor)
let selection = Zotero.BetterNotes.api.editor.getTextBetween(editor, range.from, range.to)
ztoolkit.log(selection, range)
if (selection.trim().length > 0) {
ztoolkit.log("selection", selection)
return selection
} else {
ztoolkit.log("context", context)
return context
}
}
export function reFocus(editor?: any) {
if (!editor) {
const BNEditorApi = Zotero.BetterNotes.api.editor
editor = BNEditorApi.getEditorInstance(Zotero.BetterNotes.data.workspace.mainId);
}
editor && editor._iframeWindow.focus()
}
export function replaceEditorText(htmlString: string) {
const BNEditorApi = Zotero.BetterNotes.api.editor
const editor = BNEditorApi.getEditorInstance(Zotero.BetterNotes.data.workspace.mainId);
const range = BNEditorApi.getRangeAtCursor(editor)
// 删除原来
window.setTimeout(async () => {
await Meet.Global.lock
Meet.Global.lock = Zotero.Promise.defer() as _ZoteroTypes.PromiseObject
BNEditorApi.del(editor, range.from, range.to)
insertEditorText(htmlString)
Meet.Global.lock.resolve()
})
}
/**
* 在编辑器光标处插入文本
* @param htmlString
*/
export function insertEditorText(htmlString: string, editor?: any) {
const BNEditorApi = Zotero.BetterNotes.api.editor
if (!editor) {
editor = BNEditorApi.getEditorInstance(Zotero.BetterNotes.data.workspace.mainId);
}
const to = BNEditorApi.getRangeAtCursor(editor).to
reFocus(editor)
BNEditorApi.insert(
editor,
htmlString,
to,
true
)
reFocus(editor)
}
/**
* 让GPT UI跟随此行
*/
export function follow() {
const views = Zotero.ZoteroGPT.views as Views
const BNEditorApi = Zotero.BetterNotes.api.editor
const editor = BNEditorApi.getEditorInstance(Zotero.BetterNotes.data.workspace.mainId);
let getLine: any = (index: number) => {
return editor._iframeWindow.document.querySelector(`.primary-editor>*:nth-child(${index})`)
}
let place = (reBuild: boolean = false) => {
const lineIndex = BNEditorApi.getLineAtCursor(editor) + 1
let line = getLine(lineIndex)
// 光标有文字就下一行
if (line.innerText.replace("\n", "").trim().length != 0) {
line = getLine(lineIndex+1)
}
let { x, y } = line.getBoundingClientRect();
const leftPanel = document.querySelector("#betternotes-workspace-outline-container")!
x = leftPanel.getAttribute("collapsed") ?
0
:
leftPanel.getBoundingClientRect().width
views.show(x + 30, y + 38, reBuild)
}
// 第一次重建UI
place(true)
let id = window.setInterval(async () => {
// await Meet.Global.lock;
// Meet.Global.lock = Zotero.Promise.defer() as _ZoteroTypes.PromiseObject
place()
// Meet.Global.lock.resolve()
}, 10)
views._ids.push({
type: "follow",
id: id
})
}
================================================
FILE: src/modules/Meet/OpenAI.ts
================================================
import { config } from "../../../package.json";
import { MD5 } from "crypto-js"
import { Document } from "langchain/document";
import LocalStorage from "../localStorage";
import Views from "../views";
import Meet from "./api";
const similarity = require('compute-cosine-similarity');
declare type RequestArg = { headers: any, api: string, body: Function, remove?: string | RegExp, process?: Function }
let chatID: string
const requestArgs: RequestArg[] = [
{
api: "https://aigpt.one/api/chat-stream",
headers: {
"path": "v1/chat/completions"
},
body: (requestText: string, messages: any) => {
return {
"model": "gpt-3.5-turbo",
messages: messages,
stream: true,
"max_tokens": 2000,
"presence_penalty": 0
}
}
},
{
api: "https://chatbot.theb.ai/api/chat-process",
headers: {
},
body: (requestText: string, messages: any) => {
return { "prompt": requestText, "options": { "parentMessageId": chatID }}
},
process: (text: string) => {
const res = JSON.parse(text.split("\n").slice(-1)[0])
chatID = res.id
return res.text
}
}
]
/**
* 给定文本和文档,返回文档列表,返回最相似的几个
* @param queryText
* @param docs
* @param obj
* @returns
*/
export async function similaritySearch(queryText: string, docs: Document[], obj: { key: string }) {
const storage = Meet.Global.storage = Meet.Global.storage || new LocalStorage(config.addonRef)
await storage.lock.promise;
const embeddings = new OpenAIEmbeddings() as any
// 查找本地,为节省空间,只储存向量
// 因为随着插件更新,解析出的PDF可能会有优化,因此再此进行提取MD5值作为验证
// 但可以预测,本地JSON文件可能会越来越大
const id = MD5(docs.map((i: any) => i.pageContent).join("\n\n")).toString()
await storage.lock
const _vv = storage.get(obj, id)
ztoolkit.log(_vv)
let vv: any
if (_vv) {
Meet.Global.popupWin.createLine({ text: "Reading embeddings...", type: "default" })
vv = _vv
} else {
Meet.Global.popupWin.createLine({ text: "Generating embeddings...", type: "default" })
vv = await embeddings.embedDocuments(docs.map((i: any) => i.pageContent))
window.setTimeout(async () => {
await storage.set(obj, id, vv)
})
}
const v0 = await embeddings.embedQuery(queryText)
// 从20个里面找出文本最长的几个,防止出现较短但相似度高的段落影响回答准确度
const relatedNumber = Zotero.Prefs.get(`${config.addonRef}.relatedNumber`) as number
Meet.Global.popupWin.createLine({ text: `Searching ${relatedNumber} related content...`, type: "default" })
const k = relatedNumber * 5
const pp = vv.map((v: any) => similarity(v0, v));
docs = [...pp].sort((a, b) => b - a).slice(0, k).map((p: number) => {
return docs[pp.indexOf(p)]
})
// return docs.slice(0, relatedNumber)
return docs.sort((a, b) => b.pageContent.length - a.pageContent.length).slice(0, relatedNumber)
}
class OpenAIEmbeddings {
constructor() {
}
private async request(input: string[]) {
const views = Zotero.ZoteroGPT.views as Views
let api = Zotero.Prefs.get(`${config.addonRef}.api`) as string
api = api.replace(/\/(?:v1)?\/?$/, "")
const secretKey = Zotero.Prefs.get(`${config.addonRef}.secretKey`)
const split_len = Zotero.Prefs.get(`${config.addonRef}.embeddingBatchNum`)
let res
const url = `${api}/v1/embeddings`
if (!secretKey) {
new ztoolkit.ProgressWindow(url, { closeOtherProgressWindows: true })
.createLine({ text: "Your secretKey is not configured.", type: "default" })
.show()
return
}
var final_embeddings=[]
for (let i = 0; i < input.length; i += split_len) {
const chunk = input.slice(i, i + split_len)
ztoolkit.log("input", chunk)
try {
res = await Zotero.HTTP.request(
"POST",
url,
{
responseType: "json",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${secretKey}`,
},
body: JSON.stringify({
model: "text-embedding-ada-002",
input: chunk
}),
}
)
} catch (error: any) {
try {
error = error.xmlhttp.response?.error
views.setText(`# ${error.code}\n> ${url}\n\n**${error.type}**\n${error.message}`, true)
new ztoolkit.ProgressWindow(error.code, { closeOtherProgressWindows: true })
.createLine({ text: error.message, type: "default" })
.show()
} catch {
new ztoolkit.ProgressWindow("Error", { closeOtherProgressWindows: true })
.createLine({ text: error.message, type: "default" })
.show()
}
}
if (res?.response?.data) {
final_embeddings = final_embeddings.concat(res.response.data.map((i: any) => i.embedding))
}
}
return final_embeddings
}
public async embedDocuments(texts: string[]) {
return await this.request(texts)
}
public async embedQuery(text: string) {
return (await this.request([text]))?.[0]
}
}
export async function getGPTResponse(requestText: string) {
const secretKey = Zotero.Prefs.get(`${config.addonRef}.secretKey`)
// 这里可以补充很多免费API,然后用户设置用哪个
if (!secretKey) { return await getGPTResponseBy(requestArgs[1], requestText) }
else { return await getGPTResponseByOpenAI(requestText) }
}
/**
* 所有getGPTResponseTextByXXX参照此函数实现
* gpt-3.5-turbo / gpt-4
* @param requestText
* @returns
*/
export async function getGPTResponseByOpenAI(requestText: string) {
const views = Zotero.ZoteroGPT.views as Views
const secretKey = Zotero.Prefs.get(`${config.addonRef}.secretKey`)
const temperature = Zotero.Prefs.get(`${config.addonRef}.temperature`)
let api = Zotero.Prefs.get(`${config.addonRef}.api`) as string
api = api.replace(/\/(?:v1)?\/?$/, "")
const model = Zotero.Prefs.get(`${config.addonRef}.model`)
views.messages.push({
role: "user",
content: requestText
})
// outputSpan.innerText = responseText;
const deltaTime = Zotero.Prefs.get(`${config.addonRef}.deltaTime`) as number
// 储存上一次的结果
let _textArr: string[] = []
// 随着请求返回实时变化
let textArr: string[] = []
// 激活输出
views.stopAlloutput()
views.setText("")
let responseText: string | undefined
const id: number = window.setInterval(async () => {
if (!responseText && _textArr.length == textArr.length) { return}
_textArr = textArr.slice(0, _textArr.length + 1)
let text = _textArr.join("")
text.length > 0 && views.setText(text)
if (responseText && responseText == text) {
views.setText(text, true)
window.clearInterval(id)
}
}, deltaTime)
views._ids.push({
type: "output",
id: id
})
const chatNumber = Zotero.Prefs.get(`${config.addonRef}.chatNumber`) as number
const url = `${api}/v1/chat/completions`
try {
await Zotero.HTTP.request(
"POST",
url,
{
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${secretKey}`,
},
body: JSON.stringify({
model: model,
messages: views.messages.slice(-chatNumber),
stream: true,
temperature: Number(temperature)
}),
responseType: "text",
requestObserver: (xmlhttp: XMLHttpRequest) => {
xmlhttp.onprogress = (e: any) => {
try {
textArr = e.target.response.match(/data: (.+)/g).filter((s: string) => s.indexOf("content") >= 0).map((s: string) => {
try {
return JSON.parse(s.replace("data: ", "")).choices[0].delta.content.replace(/\n+/g, "\n")
} catch {
return false
}
}).filter(Boolean)
} catch {
// 出错一般是token超出限制
ztoolkit.log(e.target.response)
}
if (e.target.timeout) {
e.target.timeout = 0;
}
};
},
}
);
} catch (error: any) {
try {
error = JSON.parse(error?.xmlhttp?.response).error
textArr = [`# ${error.code}\n> ${url}\n\n**${error.type}**\n${error.message}`]
new ztoolkit.ProgressWindow(error.code, { closeOtherProgressWindows: true })
.createLine({ text: error.message, type: "default" })
.show()
} catch {
new ztoolkit.ProgressWindow("Error", { closeOtherProgressWindows: true })
.createLine({ text: error.message, type: "default" })
.show()
}
}
responseText = textArr.join("")
ztoolkit.log("responseText", responseText)
// if (views._ids.map(i=>i.id).indexOf(id) >= 0 ) {
// views.setText(responseText, true)
// }
// window.clearInterval(id)
views.messages.push({
role: "assistant",
content: responseText
})
return responseText
}
/**
* 返回值要是纯文本
* @param requestArg
* @param requestText
* @param views
* @returns
*/
export async function getGPTResponseBy(
requestArg: RequestArg,
requestText: string,
) {
const views = Zotero.ZoteroGPT.views as Views
const deltaTime = Zotero.Prefs.get(`${config.addonRef}.deltaTime`) as number
let responseText: string | undefined
let _responseText = ""
views.messages.push({
role: "user",
content: requestText
})
// 储存上一次的结果
// 激活输出
views.stopAlloutput()
views.setText("")
const id = window.setInterval(() => {
_responseText.trim().length > 0 && views.setText(_responseText)
if (responseText && responseText == _responseText) {
views.setText(_responseText, true)
window.clearInterval(id)
}
}, deltaTime)
views._ids.push({ type: "output", id: id })
const chatNumber = Zotero.Prefs.get(`${config.addonRef}.chatNumber`) as number
const body = JSON.stringify(requestArg.body(requestText, views.messages.slice(-chatNumber)))
await Zotero.HTTP.request(
"POST",
requestArg.api,
{
headers: {
"Content-Type": "application/json",
...requestArg.headers
},
body,
responseType: "text",
requestObserver: (xmlhttp: XMLHttpRequest) => {
xmlhttp.onprogress = (e: any) => {
_responseText = e.target.response.replace(requestArg.remove, "")
if (requestArg.process) {
_responseText = requestArg.process(_responseText)
}
if (e.target.timeout) {
e.target.timeout = 0;
}
};
},
}
);
// if (views._ids.map(i => i.id).indexOf(id) >= 0) {
// views.setText(responseText, true)
// }
// window.clearInterval(id)
// if (views.isInNote) {
// window.setTimeout(async () => {
// Meet.BetterNotes.replaceEditorText(
// // await Zotero.BetterNotes.api.convert.md2html(responseText)
// views.container.querySelector(".markdown-body")!.innerHTML
// )
// })
// }
responseText = _responseText
views.messages.push({
role: "assistant",
content: responseText
})
return responseText
}
================================================
FILE: src/modules/Meet/Zotero.ts
================================================
import { config } from "../../../package.json";
import { MD5 } from "crypto-js"
import { Document } from "langchain/document";
import { similaritySearch } from "./OpenAI";
import Meet from "./api";
import ZoteroToolkit from "zotero-plugin-toolkit";
/**
* 读取剪贴板
* @returns string
*/
export function getClipboardText(): string {
// @ts-ignore
const clipboardService = window.Cc['@mozilla.org/widget/clipboard;1'].getService(Ci.nsIClipboard);
// @ts-ignore
const transferable = window.Cc['@mozilla.org/widget/transferable;1'].createInstance(Ci.nsITransferable);
if (!transferable) {
window.alert('剪贴板服务错误:无法创建可传输的实例');
}
transferable.addDataFlavor('text/unicode');
clipboardService.getData(transferable, clipboardService.kGlobalClipboard);
let clipboardData = {};
let clipboardLength = {};
try {
transferable.getTransferData('text/unicode', clipboardData, clipboardLength);
} catch (err: any) {
window.console.error('剪贴板服务获取失败:', err.message);
}
// @ts-ignore
clipboardData = clipboardData.value.QueryInterface(Ci.nsISupportsString);
// @ts-ignore
return clipboardData.data
}
/**
* 将选中条目处理成全文
* 注意:这里目前是不储存得到向量的,因为条目一直在更新
* @param key
* @returns
*/
async function selectedItems2documents(key: string) {
const docs = ZoteroPane.getSelectedItems().map((item: Zotero.Item) => {
const text = JSON.stringify(item.toJSON());
return new Document({
pageContent: text.slice(0, 500),
metadata: {
type: "id",
id: item.id,
key
}
})
})
return docs
}
/**
* https://github.com/MuiseDestiny/zotero-reference/blob/743bef7ac59d644675d8ab33a0b6c138d47fdb2f/src/modules/pdf.ts#L75
* @param items
* @returns
*/
function mergeSameLine(items: PDFItem[]) {
let toLine = (item: PDFItem) => {
let line: PDFLine = {
x: parseFloat(item.transform[4].toFixed(1)),
y: parseFloat(item.transform[5].toFixed(1)),
text: item.str || "",
height: item.height,
width: item.width,
url: item?.url,
_height: [item.height]
}
if (line.width < 0) {
line.x += line.width
line.width = -line.width
}
return line
}
let j = 0
let lines: PDFLine[] = [toLine(items[j])]
for (j = 1; j < items.length; j++) {
let line = toLine(items[j])
let lastLine = lines.slice(-1)[0]
// 考虑上标下标
if (
line.y == lastLine.y ||
(line.y >= lastLine.y && line.y < lastLine.y + lastLine.height) ||
(line.y + line.height > lastLine.y && line.y + line.height <= lastLine.y + lastLine.height)
) {
lastLine.text += (" " + line.text)
lastLine.width += line.width
lastLine.url = lastLine.url || line.url
// 记录所有高度
lastLine._height.push(line.height)
} else {
// 处理已完成的行,用众数赋值高度
let hh = lastLine._height
// lastLine.height = hh.sort((a, b) => a - b)[parseInt(String(hh.length / 2))]
// 用最大值
// lastLine.height = hh.sort((a, b) => b-a)[0]
// 众数
const num: any = {}
for (let i = 0; i < hh.length; i++) {
num[String(hh[i])] ??= 0
num[String(hh[i])] += 1
}
lastLine.height = Number(
Object.keys(num).sort((h1: string, h2: string) => {
return num[h2] - num[h1]
})[0]
)
// 新的一行
lines.push(line)
}
}
return lines
}
declare type Box = {
left: number;
right: number;
top: number;
bottom: number;
}
/**
* 判断A和B两个矩形是否几何相交
* @param A
* @param B
* @returns
*/
function isIntersect(A: Box, B: Box): boolean {
if (
B.right < A.left ||
B.left > A.right ||
B.bottom > A.top ||
B.top < A.bottom
) {
return false
} else {
return true
}
}
/**
* 判断两行是否是跨页同位置行
* @param lineA
* @param lineB
* @param maxWidth
* @param maxHeight
* @returns
*/
function isIntersectLines(lineA: any, lineB: any, maxWidth: number, maxHeight: number) {
let rectA = {
left: lineA.x / maxWidth,
right: (lineA.x + lineA.width) / maxWidth,
bottom: lineA.y / maxHeight,
top: (lineA.y + lineA.height) / maxHeight
}
let rectB = {
left: lineB.x / maxWidth,
right: (lineB.x + lineB.width) / maxWidth,
bottom: lineB.y / maxHeight,
top: (lineB.y + lineB.height) / maxHeight
}
return isIntersect(rectA, rectB)
}
/**
* 读取PDF全文,因为读取速度一般较快,所以不储存
* 当然排除学位论文,书籍等
* 此函数遇到reference关键词会停止读取,因为参考文献太影响最后计算相似度了
*/
async function pdf2documents(itemkey: string) {
const reader = await ztoolkit.Reader.getReader() as _ZoteroTypes.ReaderInstance
const PDFViewerApplication = (reader._iframeWindow as any).wrappedJSObject.PDFViewerApplication;
await PDFViewerApplication.pdfLoadingTask.promise;
await PDFViewerApplication.pdfViewer.pagesPromise;
let pages = PDFViewerApplication.pdfViewer._pages;
let totalPageNum = pages.length
// const popupWin = new ztoolkit.ProgressWindow("[Pending] PDF", { closeTime: -1 })
// .createLine({ text: `[1/${totalPageNum}] Reading`, progress: 1, type: "success" })
// .show()
const popupWin = Meet.Global.popupWin.createLine({ text: `[1/${totalPageNum}] Reading PDF`, progress: 1, type: "success" })
.show()
// 读取所有页面lines
const pageLines: any = {}
let docs: Document[] = []
for (let pageNum = 0; pageNum < totalPageNum; pageNum++) {
let pdfPage = pages[pageNum].pdfPage
let textContent = await pdfPage.getTextContent()
let items: PDFItem[] = textContent.items.filter((item: PDFItem) => item.str.trim().length)
let lines = mergeSameLine(items)
let index = lines.findIndex(line => /(r?eferences?|acknowledgements)$/i.test(line.text.trim()))
if (index != -1) {
lines = lines.slice(0, index)
}
pageLines[pageNum] = lines
popupWin.changeLine({ idx: popupWin.lines.length - 1, text: `[${pageNum + 1}/${totalPageNum}] Reading PDF`, progress: (pageNum + 1) / totalPageNum * 100})
// 防止误杀
if (index != -1 && pageNum / totalPageNum >= .9) {
break
}
}
popupWin.changeLine({ idx: popupWin.lines.length - 1, text: "Reading PDF", progress: 100 })
popupWin.changeLine({ progress: 100 });
totalPageNum = Object.keys(pageLines).length
for (let pageNum = 0; pageNum < totalPageNum; pageNum++) {
let pdfPage = pages[pageNum].pdfPage
const maxWidth = pdfPage._pageInfo.view[2];
const maxHeight = pdfPage._pageInfo.view[3];
let lines = [...pageLines[pageNum]]
// 去除页眉页脚信息
let removeLines = new Set()
let removeNumber = (text: string) => {
// 英文页码
if (/^[A-Z]{1,3}$/.test(text)) {
text = ""
}
// 正常页码1,2,3
text = text.replace(/\x20+/g, "").replace(/\d+/g, "")
return text
}
// 是否为重复
let isRepeat = (line: PDFLine, _line: PDFLine) => {
let text = removeNumber(line.text)
let _text = removeNumber(_line.text)
return text == _text && isIntersectLines(line, _line, maxWidth, maxHeight)
}
// 存在于数据起始结尾的无效行
for (let i of Object.keys(pageLines)) {
if (Number(i) == pageNum) { continue }
// 两个不同页,开始对比
let _lines = pageLines[i]
let directions = {
forward: {
factor: 1,
done: false
},
backward: {
factor: -1,
done: false
}
}
for (let offset = 0; offset < lines.length && offset < _lines.length; offset++) {
["forward", "backward"].forEach((direction: string) => {
if (directions[direction as keyof typeof directions].done) { return }
let factor = directions[direction as keyof typeof directions].factor
let index = factor * offset + (factor > 0 ? 0 : -1)
let line = lines.slice(index)[0]
let _line = _lines.slice(index)[0]
if (isRepeat(line, _line)) {
// 认为是相同的
line[direction] = true
removeLines.add(line)
} else {
directions[direction as keyof typeof directions].done = true
}
})
}
// 内部的
// 设定一个百分百正文区域防止误杀
const content = { x: 0.2 * maxWidth, width: .6 * maxWidth, y: .2 * maxHeight, height: .6 * maxHeight }
for (let j = 0; j < lines.length; j++) {
let line = lines[j]
if (isIntersectLines(content, line, maxWidth, maxHeight)) { continue }
for (let k = 0; k < _lines.length; k++) {
let _line = _lines[k]
if (isRepeat(line, _line)) {
line.repeat = line.repeat == undefined ? 1 : (line.repeat + 1)
line.repateWith = _line
removeLines.add(line)
}
}
}
}
lines = lines.filter((e: any) => !(e.forward || e.backward || (e.repeat && e.repeat > 3)));
// 段落聚类
// 原则:字体从大到小,合并;从小变大,断开
let abs = (x: number) => x > 0 ? x : -x
const paragraphs = [[lines[0]]]
for (let i = 1; i < lines.length; i++) {
let lastLine = paragraphs.slice(-1)[0].slice(-1)[0]
let currentLine = lines[i]
let nextLine = lines[i + 1]
const isNewParagraph =
// 达到一定行数阈值
paragraphs.slice(-1)[0].length >= 5 &&
(
// 当前行存在一个非常大的字体的文字
currentLine._height.some((h2: number) => lastLine._height.every((h1: number) => h2 > h1)) ||
// 是摘要自动为一段
/abstract/i.test(currentLine.text) ||
// 与上一行间距过大
abs(lastLine.y - currentLine.y) > currentLine.height * 2 ||
// 首行缩进分段
(currentLine.x > lastLine.x && nextLine && nextLine.x < currentLine.x)
)
// 开新段落
if (isNewParagraph) {
paragraphs.push([currentLine])
}
// 否则纳入当前段落
else {
paragraphs.slice(-1)[0].push(currentLine)
}
}
ztoolkit.log(paragraphs)
// 段落合并
for (let i = 0; i < paragraphs.length; i++) {
let box: { page: number, left: number; top: number; right: number; bottom: number }
/**
* 所有line是属于一个段落的
* 合并同时计算它的边界
*/
let _pageText = ""
let line, nextLine
for (let j = 0; j < paragraphs[i].length; j++) {
line = paragraphs[i][j]
if (!line) { continue }
nextLine = paragraphs[i]?.[j + 1]
// 更新边界
box ??= { page: pageNum, left: line.x, right: line.x + line.width, top: line.y + line.height, bottom: line.y }
if (line.x < box.left) {
box.left = line.x
}
if (line.x + line.width > box.right) {
box.right = line.x + line.width
}
if (line.y < box.bottom) {
line.y = box.bottom
}
if (line.y + line.height > box.top) {
box.top = line.y + line.height
}
_pageText += line.text
if (
nextLine &&
line.height > nextLine.height
) {
_pageText = "\n"
} else if (j < paragraphs[i].length - 1) {
if (!line.text.endsWith("-")) {
_pageText += " "
}
}
}
_pageText = _pageText.replace(/\x20+/g, " ").replace(/^\x20*\n+/g, "").replace(/\x20*\n+/g, "");
if (_pageText.length > 0) {
docs.push(
new Document({
pageContent: _pageText,
metadata: { type: "box", box: box!, key: itemkey },
})
)
}
}
}
// popupWin.changeHeadline("[Done] PDF")
// popupWin.startCloseTimer(1000)
console.log("pdf2documents", docs)
return docs
}
/**
* 如果当前在主面板,根据选中条目生成文本,查找相关 - 用于搜索条目
* 如果在PDF阅读界面,阅读PDF原文,查找返回相应段落 - 用于总结问题
* @param queryText
* @returns
*/
export async function getRelatedText(queryText: string) {
// @ts-ignore
const cache = (window._GPTGlobal ??= {cache: []}).cache
let docs: Document[], key: string
switch (Zotero_Tabs.selectedIndex) {
case 0:
// 只有再次选中相同条目,且条目没有更新变化,才会复用,不然会一直重复建立索引
// TODO - 优化
key = MD5(ZoteroPane.getSelectedItems().map(i => i.key).join("")).toString()
docs = cache[key] || await selectedItems2documents(key)
break;
default:
let pdfItem = Zotero.Items.get(
Zotero.Reader.getByTabID(Zotero_Tabs.selectedID)!.itemID as number
)
key = pdfItem.key
docs = cache[key] || await pdf2documents(key)
break
}
cache[key] = docs
docs = await similaritySearch(queryText, docs, { key }) as Document[]
ztoolkit.log("docs", docs)
Zotero[config.addonInstance].views.insertAuxiliary(docs)
return docs.map((doc: Document, index: number) => `[${index + 1}]${doc.pageContent}`).join("\n\n")
}
/**
* 获取选中条目某个字段
* @param fieldName
* @returns
*/
export function getItemField(fieldName: any) {
return ZoteroPane.getSelectedItems()[0].getField(fieldName)
}
/**
* 获取PDF页面文字
* @returns
*/
export function getPDFSelection() {
try {
return ztoolkit.Reader.getSelectedText(
Zotero.Reader.getByTabID(Zotero_Tabs.selectedID)
);
} catch {
return ""
}
}
export async function getPDFAnnotations(select: boolean = false) {
let keys: string[]
if (select) {
// try {
const reader = await ztoolkit.Reader.getReader() as _ZoteroTypes.ReaderInstance
const nodes = reader._iframeWindow?.document.querySelectorAll("[id^=annotation-].selected") as any
ztoolkit.log(nodes)
keys = [...nodes].map(i => i.id.split("-")[1])
ztoolkit.log(keys)
// } catch {}
}
const pdfItem = Zotero.Items.get(
Zotero.Reader.getByTabID(Zotero_Tabs.selectedID)!.itemID as number
)
const docs: Document[] = []
pdfItem.getAnnotations().forEach((anno: any) => {
if (select && keys.indexOf(anno.key) == -1) { return }
const pos = JSON.parse(anno.annotationPosition)
const rect = pos.rects[0]
docs.push(
new Document({
pageContent: anno.annotationText,
metadata: {
type: "box",
box: { page: pos.pageIndex, left: rect[0], right: rect[2], top: rect[3], bottom: rect[1] },
key: pdfItem.key
}
})
)
})
Zotero[config.addonInstance].views.insertAuxiliary(docs)
return docs.map((doc: Document, index: number) => `[${index + 1}]${doc.pageContent}`).join("\n\n")
}
================================================
FILE: src/modules/Meet/api.ts
================================================
import {
getClipboardText,
getItemField,
getPDFSelection,
getRelatedText,
getPDFAnnotations
} from "./Zotero"
import {
getEditorText,
insertEditorText,
replaceEditorText,
follow,
reFocus
} from "./BetterNotes"
import {
getGPTResponse
} from "./OpenAI"
import Views from "../views";
const Meet: {
[key: string]: any;
Global: {
[key: string]: any;
views: Views | undefined
}
} = {
/**
* 开放给用户
* 示例:Meet.Zotero.xxx()
*/
Zotero: {
/**
* 返回系统剪贴板复制的内容
*/
getClipboardText,
/**
* 返回选中条目的某个字段值,多个选中返回第一个选中的某个字段值
* @fieldName 接收字段的名称
* 比如摘要,Meet.Zotero.getItemField("abstractNote")
*/
getItemField,
/**
* 返回阅读PDF时选中的文字
*/
getPDFSelection,
/**
* 返回相关段落,如你选中多条条目,则返回与问题最相关的5个条目
* 如果你在PDF中则会读取整个PDF,返回与问题最相关的5个段落
* @queryText 接收一个查询字符串
* Meet.Zotero.getItemField("本文提到的XXX是什么意思?")
*/
getRelatedText,
/**
* 获取PDF注释内容
* @select 接收一个boolean,是否返回选中的标注
* getPDFAnnotations(true) 会返回选中的标注
* getPDFAnnotations() 默认返回所有标注
*/
getPDFAnnotations,
},
/**
* 部分开放
* 下列函数只针对主笔记
*/
BetterNotes: {
getEditorText,
insertEditorText,
replaceEditorText,
follow,
reFocus
},
OpenAI: {
getGPTResponse
},
Global: {
lock: undefined,
input: undefined,
views: undefined,
popupWin: undefined,
storage: undefined
}
}
export default Meet
================================================
FILE: src/modules/base.ts
================================================
import { config } from "../../package.json";
const help = `
### Quick Commands
\`/help\` Show all commands.
\`/clear\` Clear history conversation.
\`/report\` Run this and copy the output content to give feedback to the developer.
\`/secretKey sk-xxx\` Set GPT secret key. Generate it in https://platform.openai.com/account/api-keys.
\`/api https://api.openai.com\` Set API.
\`/model gpt-4/gpt-3.5-turbo\` Set GPT model. For example, \`/model gpt-3.5-turbo\`.
\`/temperature 1.0\` Set GPT temperature. Controls the randomness and diversity of generated text, specified within a range of 0 to 1.
\`/chatNumber 3\` Set the number of saved historical conversations.
\`/relatedNumber 5\` Set the number of most relevant text. For example, the number of paragraphs referenced while using askPDF.
\`/deltaTime 100\` Control GPT smoothness (ms).
\`/width 32%\` Control GPT UI width (pct).
\`/tagsMore expand/scroll\` Set mode to display more tags.
\`/key default\` Restore the variable values above to their default values (if have).
### About UI
You can hold down \`Ctrl\` and scroll the mouse wheel to zoom the entire UI.
And when your mouse is in the output box, the size of any content in the output box will be adjusted.
### About Tag
You can \`long click\` on the tag below to see its internal pseudo-code.
You can type \`#xxx\` and press \`Enter\` to create a tag. And save it with \`Ctrl + S\`, during which you can execute it with \`Ctrl + R\`.
You can \`right-long-click\` a tag to delete it.
### About Output Text
You can \`double click\` on this text to copy GPT's answer.
You can \`long press\` me without releasing, then move me to a suitable position before releasing.
### About Input Text
You can exit me by pressing \`Esc\` above my head and wake me up by pressing \`Shift + /\` or \`Shift + ?\` in the Zotero main window.
You can type the question in my header, then press \`Enter\` to ask me.
You can press \`Ctrl + Enter\` to execute last executed command tag again.
You can press \`Shift + Enter\` to enter long text editing mode and press \`Ctrl + R\` to execute long text.
`
// 这是 OpenAI ChatGPT 的字体
const fontFamily = `Söhne,ui-sans-serif,system-ui,-apple-system,Segoe UI,Roboto,Ubuntu,Cantarell,Noto Sans,sans-serif,Helvetica Neue,Arial,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji`
function parseTag(text: string) {
text = text.replace(/^\n/, "").replace(/\n$/, "")
let tagString = text.match(/^#(.+)\n/) as any
function randomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
let tag: Tag = {
tag: config.addonName,
color: randomColor(),
position: 9,
text: text,
trigger: "",
}
if (tagString) {
tagString = tagString[0]
tag.tag = tagString.match(/^#([^\[\n]+)/)[1]
// 解析颜色
let color = tagString.match(/\[c(?:olor)?="?(#.+?)"?\]/)
tag.color = color?.[1] || tag.color
// 解析位置
let position = tagString.match(/\[pos(?:ition)?="?(\d+?)"?\]/)
tag.position = Number(position?.[1] || tag.position)
// 解析关键词
let trigger = tagString.match(/\[tr(?:igger)?="?(.+)"?\]/)
tag.trigger = trigger?.[1] || tag.trigger
tag.text = `#${tag.tag}[position=${tag.position}][color=${tag.color}][trigger=${tag.trigger}]` + "\n" + text.replace(/^#.+\n/, "")
}
return tag
}
/**
* 这里默认标签无法删除,但可以更改里面的内容,比如颜色位置,内部prompt
*/
let defaultTags: any = [
`
#🪐AskPDF[color=#0EA293][position=10][trigger=/^(本文|这篇文章|论文)/]
You are a helpful assistant. Context information is below.
$\{
Meet.Global.views.messages = [];
Meet.Zotero.getRelatedText(Meet.Global.input)
\}
Using the provided context information, write a comprehensive reply to the given query. Make sure to cite results using [number] notation after the reference. If the provided context information refer to multiple subjects with the same name, write separate answers for each subject. Use prior knowledge only if the given context didn't provide enough information.
Answer the question: $\{Meet.Global.input\}
Reply in ${Zotero.locale}
`,
`
#🌟Translate[c=#D14D72][pos=11][trigger=/^翻译/]
Translate these content to 简体中文:
$\{
Meet.Global.input.replace("翻译", "") ||
Meet.Zotero.getPDFSelection() ||
Meet.Global.views.messages[0].content
\}
`,
`
#✨Improve writing[color=#8e44ad][pos=12][trigger=/^润色/]
Below is a paragraph from an academic paper. Polish the writing to meet the academic style, improve the spelling, grammar, clarity, concision and overall readability. When necessary, rewrite the whole sentence. Furthermore, list all modification and explain the reasons to do so in markdown table. Paragraph: "$\{
Meet.Global.input.replace("润色", "") ||
Meet.Global.views.messages[0].content
\}"
`,
`
#Clipboard[c=#576CBC][pos=13][trigger=/(剪贴板|复制内容)/]
This is the content in my clipboard:
$\{Meet.Zotero.getClipboardText()\}
---
$\{Meet.Global.input\}
`,
`
#Annotations[c=#F49D1A][pos=14][trigger=/(选中|选择的|选择|所选)?(注释|高亮|标注)/]
These are PDF Annotation contents:
$\{
Meet.Zotero.getPDFAnnotations(Meet.Global.input.match(/(选中|选择的|选择|所选)/))
\}
Please answer me in the language of my question. Make sure to cite results using [number] notation after the reference.
My question is: $\{Meet.Global.input\}
`,
`
#Selection[c=#D14D72][pos=15][trigger=/^(这段|选中)(文本|话|文字|描述)/]
Read these content:
$\{
Meet.Zotero.getPDFSelection() ||
Meet.Global.views.messages[0].content
\}
---
Answer me in the language of my question. This is my question: $\{Meet.Global.input\}
`,
`
#Item[c=#159895][pos=16][trigger=/这篇(文献|论文|文章)/]
This is a Zotero item presented in JSON format:
$\{
JSON.stringify(ZoteroPane.getSelectedItems()[0].toJSON())
\}
Base on this JSON: $\{Meet.Global.input\}
`,
`
#Items[c=#159895][pos=17][trigger=/这些(文献|论文)/]
These are Zotero items presented in JSON format:
$\{
Meet.Zotero.getRelatedText(Meet.Global.input)
\}
Please answer me using the lanaguage as same as my question. Make sure to cite results using [number] notation after the reference.
My question is: $\{Meet.Global.input\}
`,
]
defaultTags = defaultTags.map(parseTag)
export { help, fontFamily, defaultTags, parseTag }
================================================
FILE: src/modules/localStorage.ts
================================================
import { config } from "../../package.json";
class LocalStorage {
public filename!: string;
public cache: any;
public lock: any;
constructor(filename: string) {
this.lock = Zotero.Promise.defer()
this.init(filename)
}
async init(filename: string) {
const window = Zotero.getMainWindow();
// @ts-ignore
const OS = window.OS;
if (!(await OS.File.exists(filename))) {
const temp = Zotero.getTempDirectory();
this.filename = OS.Path.join(temp.path.replace(temp.leafName, ""), `${filename}.json`);
} else {
this.filename = filename
}
try {
const rawString = await Zotero.File.getContentsAsync(this.filename) as string
this.cache = JSON.parse(rawString)
} catch {
this.cache = {}
}
this.lock.resolve()
}
get(item: Zotero.Item | { key: string }, key: string) {
if (this.cache == undefined) { return }
return (this.cache[item.key] ??= {})[key]
}
async set(item: Zotero.Item | { key: string }, key: string, value: any) {
await this.lock.promise;
(this.cache[item.key] ??= {})[key] = value
window.setTimeout(async () => {
await Zotero.File.putContentsAsync(this.filename, JSON.stringify(this.cache));
})
}
}
export default LocalStorage
================================================
FILE: src/modules/locale.ts
================================================
import { config } from "../../package.json";
export function initLocale() {
addon.data.locale = {
stringBundle: Components.classes["@mozilla.org/intl/stringbundle;1"]
.getService(Components.interfaces.nsIStringBundleService)
.createBundle(`chrome://${config.addonRef}/locale/addon.properties`),
};
}
export function getString(
localString: string,
noReload: boolean = false
): string {
try {
return addon.data.locale?.stringBundle.GetStringFromName(localString);
} catch (e) {
if (!noReload) {
initLocale();
return getString(localString, true);
}
return localString;
}
}
================================================
FILE: src/modules/utils.ts
================================================
import Meet from "./Meet/api";
export default class Utils {
constructor() {
}
public getRGB(color: string) {
var sColor = color.toLowerCase();
// 十六进制颜色值的正则表达式
var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
// 如果是16进制颜色
if (sColor && reg.test(sColor)) {
if (sColor.length === 4) {
var sColorNew = "#";
for (var i = 1; i < 4; i += 1) {
sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
}
sColor = sColorNew;
}
//处理六位的颜色值
var sColorChange = [];
for (var i = 1; i < 7; i += 2) {
sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2)));
}
return sColorChange;
}
return sColor;
}
/**
* 兼容旧版
* @deprecated
* @param queryText
* @returns
*/
public async getRelatedText(queryText: string) {
return await Meet.Zotero.getRelatedText(queryText)
}
}
================================================
FILE: src/modules/views.ts
================================================
import { config } from "../../package.json";
import Meet from "./Meet/api"
import Utils from "./utils";
import { Document } from "langchain/document";
import { help, fontFamily, defaultTags, parseTag } from "./base"
const markdown = require("markdown-it")({
breaks: true, // 将行结束符\n转换为 <br> 标签
xhtmlOut: true, // 使用 /> 关闭标签,而不是 >
typographer: true,
html: true,
});
const mathjax3 = require('markdown-it-mathjax3');
markdown.use(mathjax3);
export default class Views {
private id = "zotero-GPT-container";
/**
* OpenAI接口历史消息记录,需要暴露给GPT响应函数
*/
public messages: { role: "user" | "assistant"; content: string }[] = [];
/**
* 用于储存历史执行的输入,配合方向上下键来快速回退
*/
private _history: { input: string; output: string }[] = []
/**
* 用于储存上一个执行的标签,配合 Ctrl + Enter 快速再次执行
*/
private _tag: Tag | undefined;
/**
* 记录当前GPT输出流setInterval的id,防止终止后仍有输出,需要暴露给GPT响应函数
*/
public _ids: {type: "follow"| "output", id: number}[] = []
/**
* 是否在笔记环境下
*/
public isInNote: boolean = true
public container!: HTMLDivElement;
private inputContainer!: HTMLDivElement;
private outputContainer!: HTMLDivElement;
private dotsContainer!: HTMLDivElement;
private tagsContainer!: HTMLDivElement;
private utils: Utils;
constructor() {
this.utils = new Utils()
this.registerKey()
this.addStyle()
// @ts-ignore
window.Meet = Meet
Meet.Global.views = this
}
private addStyle() {
ztoolkit.UI.appendElement({
tag: "style",
id: `${config.addonRef}-style`,
namespace: "html",
properties: {
innerHTML: `
@keyframes loading {
0%, 100%
{
opacity: 0.25;
}
50%
{
opacity: 0.8;
}
}
#${this.id} .three-dots:hover {
opacity: 0.8 !important;
}
#${this.id} .three-dots.loading .dot:nth-child(1) {
animation-delay: 0s;
}
#${this.id} .three-dots.loading .dot:nth-child(2) {
animation-delay: 0.5s;
}
#${this.id} .three-dots.loading .dot:nth-child(3) {
animation-delay: 1s;
}
#${this.id} .three-dots.loading .dot {
animation: loading 1.5s ease-in-out infinite;
}
#${this.id} ::-moz-selection {
background: rgba(89, 192, 188, .8);
color: #fff;
}
#output-container * {
font-family: ${fontFamily} !important;
}
#output-container div p, #output-container div span {
marigin: 0;
padding: 0;
text-align: justify;
}
.gpt-menu-box .menu-item:hover, .gpt-menu-box .menu-item.selected{
background-color: rgba(89, 192, 188, .23) !important;
}
#${this.id} .tag {
position: relative;
overflow: hidden;
}
#${this.id} .ripple {
left: 0;
top: 50%;
position: absolute;
background: #fff;
transform: translate(-50%, -50%);
pointer-events: none;
border-radius: 50%;
animation: ripple 1.5s linear;
}
@keyframes ripple {
from {
width: 0px;
height: 0px;
opacity: 0.5;
}
to {
width: 500px;
height: 500px;
opacity: 0;
}
}
`
},
// #output-container div.streaming span:after,
}, document.documentElement);
ztoolkit.UI.appendElement({
tag: "link",
id: `${config.addonRef}-link`,
properties: {
type: "text/css",
rel: "stylesheet",
href: `chrome://${config.addonRef}/content/md.css`
}
}, document.documentElement)
}
/**
* 设置GPT回答区域文字
* @param text
* @param isDone
*/
public setText(text: string, isDone: boolean = false, scrollToNewLine: boolean = true, isRecord: boolean = true,) {
this.outputContainer.style.display = ""
const outputDiv = this.outputContainer.querySelector(".markdown-body")! as HTMLDivElement
outputDiv.setAttribute("pureText", text);
outputDiv.classList.add("streaming");
let ready = () => {
if (outputDiv.innerHTML.trim() == "") {
outputDiv.innerHTML = `<p></p>`
}
}
ready()
/**
* 根据差异渲染,只为保全光标闪烁
*/
let md2html = () => {
let result = markdown.render(text)
// .replace(/<mjx-assistive-mml[^>]*>.*?<\/mjx-assistive-mml>/g, "")
/**
* 监测差异,替换节点或文字
* @param oldNode
* @param newNode
* @returns
*/
let diffRender = (oldNode: any, newNode: any) => {
if (newNode.nodeName == "svg") {
oldNode.parentNode.replaceChild(newNode, oldNode)
return
}
if (oldNode.nodeName == "#text" && newNode.nodeName == "#text") {
oldNode.data = newNode.data
return
} else {
if (
oldNode.outerHTML == newNode.outerHTML &&
oldNode.innerHTML == newNode.innerHTML
) {
return
}
}
// 老的比新的多要去除
[...oldNode.childNodes].slice(newNode.childNodes.length).forEach((e: any)=>e.remove())
for (let i = 0; i < newNode.childNodes.length; i++) {
if (i < oldNode.childNodes.length) {
if (oldNode.childNodes[i].tagName != newNode.childNodes[i].tagName) {
if (oldNode.childNodes[i].tagName == "#text") {
oldNode.childNodes[i].remove()
oldNode.appendChild(newNode.childNodes[i])
} else {
oldNode.replaceChild(newNode.childNodes[i], oldNode.childNodes[i])
}
continue
} else {
diffRender(oldNode.childNodes[i], newNode.childNodes[i])
}
} else {
oldNode.appendChild(newNode.childNodes[i])
}
}
}
// 纯文本本身不需要MD渲染,防止样式不一致出现变形
let _outputDiv = outputDiv.cloneNode(true) as HTMLDivElement
try {
_outputDiv.innerHTML = result
if (outputDiv.childNodes.length == 0) {
outputDiv.innerHTML = result
} else {
diffRender(outputDiv, _outputDiv)
}
} catch {
outputDiv.innerText = result
}
}
md2html()
ready()
// @ts-ignore
scrollToNewLine && this.outputContainer.scrollBy(0, this.outputContainer.scrollTopMax)
if (isDone) {
// 任何实时预览的错误到最后,应该因为下面这句消失
outputDiv.innerHTML = markdown.render(text)
if (isRecord) {
this._history.push({ input: Meet.Global.input, output: text })
}
outputDiv.classList.remove("streaming")
if (this.isInNote) {
this.hide()
// 下面是完成回答后写入 Better Notes 主笔记的两种方案
Meet.BetterNotes.insertEditorText(outputDiv.innerHTML)
// window.setTimeout(async () => {
// Meet.BetterNotes.insertEditorText(await Zotero.BetterNotes.api.convert.md2html(text))
// })
}
}
}
/**
* GPT写的
* @param node
*/
private addDragEvent(node: HTMLDivElement) {
let posX: number, posY: number
let currentX: number, currentY: number
let isDragging: boolean = false
function handleMouseDown(event: MouseEvent) {
// 如果是input或textarea元素,跳过拖拽逻辑
if (
event.target instanceof window.HTMLInputElement ||
event.target instanceof window.HTMLTextAreaElement ||
(event.target as HTMLDivElement).classList.contains("tag")
) {
return
}
posX = node.offsetLeft - event.clientX
posY = node.offsetTop - event.clientY
isDragging = true
}
function handleMouseUp(event: MouseEvent) {
isDragging = false
}
function handleMouseMove(event: MouseEvent) {
if (isDragging) {
currentX = event.clientX + posX
currentY = event.clientY + posY
node.style.left = currentX + "px"
node.style.top = currentY + "px"
}
}
// Add event listeners
node.addEventListener("mousedown", handleMouseDown)
node.addEventListener("mouseup", handleMouseUp)
node.addEventListener("mousemove", handleMouseMove)
}
/**
* GPT写的
* @param inputNode
*/
private bindUpDownKeys(inputNode: HTMLInputElement) {
// let currentIdx = this._history.length;
inputNode.addEventListener("keydown", (e) => {
this._history = this._history.filter(i=>i.input)
let currentIdx = this._history.map(i=>i.input).indexOf(this.inputContainer!.querySelector("input")!.value)
currentIdx = currentIdx == -1 ? this._history.length : currentIdx
if (e.key === "ArrowUp") {
currentIdx--;
if (currentIdx < 0) {
currentIdx = 0;
}
inputNode.value = this._history[currentIdx].input || "";
this.setText(this._history[currentIdx].output, true, false, false)
} else if (e.key === "ArrowDown") {
currentIdx++;
if (currentIdx >= this._history.length) {
currentIdx = this._history.length;
inputNode.value = "";
this.outputContainer.style.display = "none"
} else {
inputNode.value = this._history[currentIdx].input || "";
this.setText(this._history[currentIdx].output, true, false, false)
}
}
if (["ArrowDown", "ArrowUp"].indexOf(e.key) >= 0) {
e.stopPropagation();
e.preventDefault();
inputNode.setSelectionRange(inputNode.value.length, inputNode.value.length);
}
});
}
/**
* 绑定ctrl+滚轮放大缩小
* @param div
*/
private bindCtrlScrollZoom(div: HTMLDivElement) {
// 为指定的div绑定wheel事件
div.addEventListener('DOMMouseScroll', (event: any) => {
// 检查是否按下了ctrl键
if (event.ctrlKey || event.metaKey) {
let _scale = div.style.transform.match(/scale\((.+)\)/)
let scale = _scale ? parseFloat(_scale[1]) : 1
let minScale = 0.5, maxScale = 2, step = 0.05
if (div.style.bottom == "0px") {
div.style.transformOrigin = "center bottom"
} else {
div.style.transformOrigin = "center center"
}
if (event.detail > 0) {
// 缩小
scale = scale - step
div.style.transform = `scale(${scale < minScale ? minScale : scale})`;
} else {
// 放大
scale = scale + step
div.style.transform = `scale(${scale > maxScale ? maxScale : scale})`;
}
}
})
}
/**
* 绑定ctrl+滚轮放大缩小控件内的所有元素
* @param div
*/
private bindCtrlScrollZoomOutput(div: HTMLDivElement) {
const styleAttributes = {
fontSize: 'font-size',
lineHeight: 'line-height',
marginBottom: 'margin-bottom',
marginTop: 'margin-top',
paddingBottom: 'padding-bottom',
paddingTop: 'padding-top',
} as const;
type StyleAttributeKeys = keyof typeof styleAttributes;
type StyleAttributes = {
[K in StyleAttributeKeys]: string;
};
// 获取子元素的初始样式
const getChildStyles = (child: Element): StyleAttributes => {
const style = window.getComputedStyle(child);
const result: Partial<StyleAttributes> = {};
for (const key in styleAttributes) {
const typedKey = key as StyleAttributeKeys;
result[typedKey] = style.getPropertyValue(styleAttributes[typedKey]);
}
return result as StyleAttributes;
};
// 更新并应用子元素的样式
const applyNewStyles = (child: HTMLElement, style: StyleAttributes, scale: number) => {
const newStyle = (value: string) => parseFloat(value) * scale + 'px';
for (const key in styleAttributes) {
child.style && (child.style[key as StyleAttributeKeys] = newStyle(style[key as StyleAttributeKeys]))
}
};
// 为指定的div绑定wheel事件
div.addEventListener('DOMMouseScroll', (event: any) => {
const children = div.children[0].children;
if (event.ctrlKey || event.metaKey) {
const step = 0.05;
event.preventDefault();
// 阻止事件冒泡
event.stopPropagation();
const scale = event.detail > 0 ? 1 - step : 1 + step;
Array.from(children).forEach((child) => {
const childElement = child as HTMLElement;
const currentStyle = getChildStyles(child);
applyNewStyles(childElement, currentStyle, scale);
});
}
});
}
private buildContainer() {
// 顶层容器
const container = ztoolkit.UI.createElement(document, "div", {
id: this.id,
styles: {
display: "none",
flexDirection: "column",
justifyContent: "flex-start",
alignItems: "center",
position: "fixed",
width: Zotero.Prefs.get(`${config.addonRef}.width`) as string,
// height: "4em",
fontSize: "18px",
borderRadius: "10px",
backgroundColor: "#fff",
boxShadow: `0px 1.8px 7.3px rgba(0, 0, 0, 0.071),
0px 6.3px 24.7px rgba(0, 0, 0, 0.112),
0px 30px 90px rgba(0, 0, 0, 0.2)`,
fontFamily: fontFamily,
}
})
this.addDragEvent(container)
this.bindCtrlScrollZoom(container)
// 输入
const inputContainer = this.inputContainer = ztoolkit.UI.appendElement({
tag: "div",
id: "input-container",
styles: {
borderBottom: "1px solid #f6f6f6",
width: "100%",
display: "flex",
justifyContent: "center",
flexDirection: "column",
alignItems: "center",
},
children: [
{
tag: "input",
styles: {
width: "calc(100% - 1.5em)",
height: "2.5em",
borderRadius: "10px",
border: "none",
outline: "none",
fontFamily: "Consolas",
fontSize: ".8em",
}
},
{
tag: "textarea",
styles: {
display: "none",
width: "calc(100% - 1.5em)",
maxHeight: "20em",
minHeight: "2em",
borderRadius: "10px",
border: "none",
outline: "none",
resize: "vertical",
marginTop: "0.55em",
fontFamily: "Consolas",
fontSize: ".8em"
}
}
]
}, container) as HTMLDivElement
const inputNode = inputContainer.querySelector("input")!
this.bindUpDownKeys(inputNode)
const textareaNode = inputContainer.querySelector("textarea")!
const that = this;
let lastInputText = ""
let inputListener = function (event: KeyboardEvent) {
// @ts-ignore
if(this.style.display == "none") { return }
// @ts-ignore
let text = Meet.Global.input = this.value
if ((event.ctrlKey || event.metaKey) && ["s", "r"].indexOf(event.key) >= 0 && textareaNode.style.display != "none") {
// 必定保存,但未必运行
const tag = parseTag(text)
if (tag) {
// @ts-ignore
this.value = tag.text
let tags = that.getTags()
// 如果tags存在,可能是更新,先从tags里将其移除
tags = tags.filter((_tag: Tag) => {
return _tag.tag != tag.tag
})
tags.push(tag)
that.setTags(tags)
that.renderTags();
if (event.key == "s") {
new ztoolkit.ProgressWindow("Save Tag")
.createLine({ text: tag.tag, type: "success" })
.show()
return
}
// 运行代码,并保存标签
if (event.key == "r") {
return that.execTag(tag)
}
}
// 普通文本
else {
// 运行文本呢
if (event.key == "r") {
// 长文本当作未保存的命令标签执行,长文本里可以写js
return that.execTag({tag: "Untitled", position: -1, color: "", trigger: "", text})
}
}
}
if (event.key == "Enter") {
ztoolkit.log(event)
outputContainer.querySelector(".auxiliary")?.remove()
// 同时按Ctrl,会点击第一个标签
if (event.ctrlKey || event.metaKey) {
// 查找第一个点击
ztoolkit.log("Ctrl + Enter")
let tag = that._tag || that.getTags()[0]
return that.execTag(tag)
}
// 按住Shift,进入长文本编辑模式,此时应该通过Ctrl+R来运行
if (event.shiftKey) {
if (inputNode.style.display != "none") {
inputNode.style.display = "none"
textareaNode.style.display = ""
textareaNode.focus()
textareaNode.value = text + "\n"
}
return
}
// 优先级最高,防止中文输入法回车转化成英文
if (text.length != lastInputText.length) {
lastInputText = text
return
}
if (text.startsWith("#")) {
if (inputNode.style.display != "none") {
inputNode.style.display = "none"
textareaNode.style.display = ""
textareaNode.focus()
// 判断本地是否存在这个标签
const tags = that.getTags();
const tag = tags.find((tag: any) => tag.text.startsWith(text.split("\n")[0]))
if (tag) {
textareaNode.value = tag.text
} else {
textareaNode.value = text + "\n"
}
}
} else if (text.startsWith("/")) {
that._history.push(text)
// 尝试结束其它stream的生命
// that._id = undefined
that.stopAlloutput()
text = text.slice(1)
let [key, value] = text.split(" ")
if (key == "clear") {
that.messages = []
// @ts-ignore
this.value = ""
that.setText("success", true, false)
} else if (key == "help"){
that.setText(help, true, false)
} else if (key == "report") {
const secretKey = Zotero.Prefs.get(`${config.addonRef}.secretKey`) as string
// window.setTimeout(() => {
// Zotero.launchURL("https://platform.openai.com/account/usage")
// }, 1000)
return that.setText(`\`api\` ${Zotero.Prefs.get(`${config.addonRef}.api`)}\n\`secretKey\` ${secretKey.slice(0, 3) + "..." + secretKey.slice(-4)}\n\`model\` ${Zotero.Prefs.get(`${config.addonRef}.model`)}\n\`temperature\` ${Zotero.Prefs.get(`${config.addonRef}.temperature`)}`, true, false)
} else if (["secretKey", "model", "api", "temperature", "deltaTime", "width", "tagsMore", "chatNumber", "relatedNumber"].indexOf(key) >= 0) {
if (value?.length > 0) {
if (value == "default") {
Zotero.Prefs.clear(`${config.addonRef}.${key}`)
value = Zotero.Prefs.get(`${config.addonRef}.${key}`)
that.setText(`${key} = ${value}`, true, false)
return
}
switch (key) {
case "deltaTime":
case "relatedNumber":
case "chatNumber":
Zotero.Prefs.set(`${config.addonRef}.${key}`, Number(value))
break;
case "width":
ztoolkit.log("width", value.match(/^[\d\.]+%$/))
if (value.match(/^[\d\.]+%$/)) {
that.container.style.width = value
Zotero.Prefs.set(`${config.addonRef}.${key}`, value)
break;
} else {
ztoolkit.log("width Error")
return that.setText(`Invalid value, ${value}, please enter a percentage, for example \`32 %\`.`, true, false)
}
case "tagsMore":
if (["scroll", "expand"].indexOf(value) >= 0) {
Zotero.Prefs.set(`${config.addonRef}.${key}`, value)
break;
} else {
ztoolkit.log("tagsMore Error")
return that.setText(`Invalid value, ${value}, please enter \`expand\` or \`scroll\`.`, true, false)
}
default:
Zotero.Prefs.set(`${config.addonRef}.${key}`, value)
break
}
} else {
value = Zotero.Prefs.get(`${config.addonRef}.${key}`)
}
that.setText(`${key} = ${value}`, true, false)
// @ts-ignore
this.value = ""
} else {
that.setText(help, true, false)
const mdbody = that.outputContainer.querySelector(".markdown-body") as HTMLDivElement
mdbody.innerHTML = `<center><span style="color: #D14D72;font-weight:bold;font-size:20px;">Invalid Command, Please Read this.</span></center>` + mdbody.innerHTML
}
} else {
that.execText(text)
that._history.push(text)
}
} else if (event.key == "Escape") {
outputContainer.style.display = "none"
// 退出长文编辑模式
if (textareaNode.style.display != "none") {
textareaNode.style.display = "none"
inputNode.value = ""
inputNode.style.display = ""
inputNode.focus()
return
}
if (inputNode.value.length) {
inputNode.value = ""
return
}
// 退出container
that.hide()
that.container!.remove()
that.isInNote && Meet.BetterNotes.reFocus()
} else if (event.key == "/" && text == "/" && that.container.querySelector("input")?.style.display != "none") {
const rect = that.container.querySelector("input")!.getBoundingClientRect()
const commands = ["clear", "help", "report", "secretKey", "model", "api", "temperature", "chatNumber", "relatedNumber" , "deltaTime", "tagsMore", "width"]
that.createMenuNode(
{ x: rect.left, y: rect.top + rect.height, width: 200, height: 350 / 12 * commands.length },
commands.map(name => {
return {
name,
listener: () => {
// @ts-ignore
this.value = `/${name}`
}
}
}), [2, 6, 8]
)
}
lastInputText = text
}
inputNode.addEventListener("keyup", inputListener)
textareaNode.addEventListener("keyup", inputListener)
// 输出
const outputContainer = this.outputContainer = ztoolkit.UI.appendElement({
tag: "div",
id: "output-container",
styles: {
width: "calc(100% - 1em)",
backgroundColor: "rgba(89, 192, 188, .08)",
color: "#374151",
maxHeight: document.documentElement.getBoundingClientRect().height * .5 + "px",
overflowY: "auto",
overflowX: "hidden",
padding: "0.25em 0.5em",
display: "none",
// resize: "vertical"
},
children: [
{
tag: "div", // Change this to 'div'
classList: ["markdown-body"],
styles: {
fontSize: "0.8em",
lineHeight: "2em",
// margin: ".5em 0"
},
properties: {
// 用于复制
pureText: ""
}
}
],
listeners: [
{
/**
* 双击是插件的输出,可能是插入笔记
*/
type: "dblclick",
listener: () => {
// 无论后面发生什么错误,都确保先复制下来
// 目前可能用户的Better Notes版本低,不支持API
const text = outputContainer.querySelector("[pureText]")!.getAttribute("pureText") || ""
new ztoolkit.Clipboard()
.addText(text, "text/unicode")
.copy()
const div = outputContainer.cloneNode(true) as HTMLDivElement
div.querySelector(".auxiliary")?.remove()
const htmlString = div.innerHTML
if (Zotero_Tabs.selectedIndex == 1 && Zotero.BetterNotes) {
Meet.BetterNotes.insertEditorText(htmlString)
this.hide()
new ztoolkit.ProgressWindow(config.addonName)
.createLine({ text: "Insert To Main Note", type: "success" })
.show()
return
}
if (Zotero_Tabs.selectedIndex > 0) {
const parentID = Zotero.Items.get(
Zotero.Reader.getByTabID(Zotero_Tabs.selectedID)!.itemID as number
).parentID
const editor = Zotero.Notes._editorInstances.find(
(e) =>
e._item.parentID === parentID && !Components.utils.isDeadWrapper(e._iframeWindow)
);
ztoolkit.log(editor)
// 笔记被打开,且打开笔记视图,才触发向当前条目笔记插入
if (editor && document.querySelector("#zotero-tb-toggle-notes-pane.toggled")) {
Meet.BetterNotes.insertEditorText(htmlString, editor)
new ztoolkit.ProgressWindow(config.addonName)
.createLine({ text: "Insert To Note", type: "success" })
.show()
return
}
}
new ztoolkit.ProgressWindow(config.addonName)
.createLine({ text: "Copy Plain Text", type: "success" })
.show()
}
}
]
}, container) as HTMLDivElement
this.bindCtrlScrollZoomOutput(outputContainer)
// 命令标签
const tagsMore = Zotero.Prefs.get(`${config.addonRef}.tagsMore`) as string
const tagsContainer = this.tagsContainer = ztoolkit.UI.appendElement({
tag: "div",
classList: ["tags-container"],
styles: {
width: "calc(100% - .5em)",
display: "flex",
flexDirection: "row",
justifyContent: "flex-start",
alignItems: "center",
margin: ".25em 0",
flexWrap: tagsMore == "expand" ? "wrap" : "nowrap",
overflow: "hidden",
height: "1.7em"
},
listeners: [
{
type: "DOMMouseScroll",
listener: (event: any) => {
if (tagsMore == "expand") { return }
const scrollSpeed = 80
// @ts-ignore
if (event.detail > 0) {
tagsContainer.scrollLeft += scrollSpeed
} else {
tagsContainer.scrollLeft -= scrollSpeed
}
event.preventDefault()
event.stopPropagation()
}
}
]
}, container) as HTMLDivElement
this.dotsContainer = ztoolkit.UI.appendElement({
tag: "div",
classList: ["three-dots"],
styles: {
// width: "100%",
display: "flex",
height: "1em",
justifyContent: "center",
alignItems: "center",
marginBottom: "0.25em",
cursor: "pointer",
opacity: ".5",
transition: "opacity .25s linear"
},
children: (() => {
let arr = []
for (let i = 0; i < 3; i++) {
arr.push({
tag: "div",
classList: ["dot"],
styles: {
width: "6px",
height: "6px",
margin: "0 .25em",
backgroundColor: "#ff7675",
borderRadius: "6px",
},
})
}
return arr
})() as any,
listeners: [
{
type: "click",
listener: () => {
if (tagsMore == "scroll") { return }
tagsContainer.style.height = tagsContainer.style.height == "auto" ? "1.7em" : "auto"
}
}
]
}, container) as HTMLDivElement
document.documentElement.append(container)
this.renderTags()
// 聚焦
window.setTimeout(() => {
container.focus()
inputContainer.focus()
inputNode.focus()
})
return container
}
/**
* 渲染标签,要根据position排序
*/
private renderTags() {
this.tagsContainer!?.querySelectorAll("div").forEach(e=>e.remove())
let tags = this.getTags() as Tag[]
tags.forEach((tag: Tag, index: number) => {
this.addTag(tag, index)
})
}
/**
* 添加一个标签
*/
private addTag(tag: Tag, index: number) {
let [red, green, blue] = this.utils.getRGB(tag.color)
let timer: undefined | number;
ztoolkit.UI.appendElement({
tag: "div",
id: `tag-${index}`,
classList: ["tag"],
styles: {
display: "inline-block",
flexShrink: "0",
fontSize: "0.8em",
height: "1.5em",
color: `rgba(${red}, ${green}, ${blue}, 1)`,
backgroundColor: `rgba(${red}, ${green}, ${blue}, 0.15)`,
borderRadius: "1em",
border: "1px solid #fff",
margin: ".25em",
padding: "0 .8em",
cursor: "pointer",
whiteSpace: "nowrap"
},
properties: {
innerHTML: tag.tag
},
listeners: [
{
type: "mousedown",
listener: (event: any) => {
timer = window.setTimeout(() => {
timer = undefined
if (event.buttons == 1) {
// 进入编辑模式
const textareaNode = this.inputContainer?.querySelector("textarea")!
const inputNode = this.inputContainer?.querySelector("input")!
inputNode.style.display = "none";
textareaNode.style.display = ""
textareaNode.value = tag.text
this.outputContainer.style!.display = "none"
} else if (event.buttons == 2) {
let tags = this.getTags()
tags = tags.filter((_tag: Tag) => _tag.tag != tag.tag)
this.setTags(tags)
this.renderTags();
}
}, 1000)
}
},
{
type: "mouseup",
listener: async () => {
if (timer) {
window.clearTimeout(timer)
timer = undefined
this.outputContainer.querySelector(".auxiliary")?.remove()
await this.execTag(tag)
}
}
}
]
}, this.tagsContainer!) as HTMLDivElement
}
private rippleEffect(div: HTMLDivElement, color: string) {
let [red, green, blue] = this.utils.getRGB(color)
ztoolkit.UI.appendElement({
tag: "div",
styles: {
backgroundColor: `rgba(${red}, ${green}, ${blue}, 0.5)`
},
classList: ["ripple"]
}, div)
}
/**
* 执行标签
*/
private async execTag(tag: Tag) {
Meet.Global.input = this.inputContainer.querySelector("input")?.value as string
this._tag = tag
const popunWin = new ztoolkit.ProgressWindow(tag.tag, { closeTime: -1, closeOtherProgressWindows: true })
.show()
Meet.Global.popupWin = popunWin
popunWin
.createLine({ text: "Generating input content...", type: "default" })
this.dotsContainer?.classList.add("loading")
this.outputContainer.style.display = "none"
ztoolkit.log(tag, this.getTags())
const tagIndex = this.getTags().map(JSON.stringify).indexOf(JSON.stringify(tag)) as number
this.rippleEffect(
this.container.querySelector(`#tag-${tagIndex}`)!,
tag.color
)
const outputDiv = this.outputContainer.querySelector("div")!
outputDiv.innerHTML = ""
outputDiv.setAttribute("pureText", "");
let text = tag.text.replace(/^#.+\n/, "")
// 旧版语法不宜传播,MD语法会被转义
for (let rawString of text.match(/```j(?:ava)?s(?:cript)?\n([\s\S]+?)\n```/g)! || []) {
let codeString = rawString.match(/```j(?:ava)?s(?:cript)?\n([\s\S]+?)\n```/)![1]
try {
text = text.replace(rawString, await window.eval(`${codeString}`))
} catch { }
}
// 新版语法容易分享传播
for (let rawString of text.match(/\$\{[\s\S]+?\}/g)! || []) {
let codeString = rawString.match(/\$\{([\s\S]+?)\}/)![1]
try {
text = text.replace(rawString, await window.eval(`${codeString}`))
} catch { }
}
popunWin.createLine({ text: `Characters ${text.length}`, type: "success" })
popunWin.createLine({ text: "Answering...", type: "default" })
// 运行替换其中js代码
text = await Meet.OpenAI.getGPTResponse(text) as string
this.dotsContainer?.classList.remove("loading")
if (text.trim().length) {
try {
window.eval(`
setTimeout(async () => {
${text}
})
`)
popunWin.createLine({ text: "Code is executed", type: "success" })
} catch { }
popunWin.createLine({ text: "Done", type: "success" })
} else {
popunWin.createLine({ text: "Done", type: "fail" })
}
popunWin.startCloseTimer(3000)
}
/**
* 执行输入框文本
* @param text
* @returns
*/
private async execText(text: string) {
// 如果文本中存在某一标签预设的关键词|正则表达式,则转为执行该标签
const tag = this.getTags()
.filter((tag: Tag) => tag.trigger?.length > 0)
.find((tag: Tag) => {
const trigger = tag.trigger
if (trigger.startsWith("/") && trigger.endsWith("/")) {
return (window.eval(trigger) as RegExp).test(text)
} else {
return text.indexOf(trigger as string) >= 0
}
})
if (tag) { return this.execTag(tag) }
// 没有匹配执行文本
this.outputContainer.style.display = "none"
const outputDiv = this.outputContainer.querySelector("div")!
outputDiv.innerHTML = ""
outputDiv.setAttribute("pureText", "");
if (text.trim().length == 0) { return }
this.dotsContainer?.classList.add("loading")
await Meet.OpenAI.getGPTResponse(text)
this.dotsContainer?.classList.remove("loading")
}
/**
* 从Zotero.Prefs获取所有已保存标签
* 按照position顺序排序后返回
*/
private getTags() {
// 进行一个简单的处理,应该是中文/表情写入prefs.js导致的bug
let tagsJson
try {
tagsJson = Zotero.Prefs.get(`${config.addonRef}.tags`) as string
} catch {}
if (!tagsJson) {
tagsJson = "[]"
Zotero.Prefs.set(`${config.addonRef}.tags`, tagsJson)
}
let tags = JSON.parse(tagsJson)
for (let defaultTag of defaultTags) {
if (!tags.find((tag: Tag) => tag.tag == defaultTag.tag)) {
tags.push(defaultTag)
}
}
return (tags.length > 0 ? tags : defaultTags).sort((a: Tag, b: Tag) => a.position - b.position)
}
private setTags(tags: any[]) {
Zotero.Prefs.set(`${config.addonRef}.tags`, JSON.stringify(tags))
}
/**
* 下面代码是GPT写的
* @param x
* @param y
*/
public show(x: number = -1, y: number = -1, reBuild: boolean = true) {
reBuild = reBuild || !this.container
if (reBuild) {
document.querySelectorAll(`#${this.id}`).forEach(e=>e.remove())
this.container = this.buildContainer()
this.container.style.display = "flex"
}
this.container.setAttribute("follow", "")
if (x + y < 0) {
const rect = document.documentElement.getBoundingClientRect()
x = rect.width / 2 - this.container.offsetWidth / 2;
y = rect.height / 2 - this.container.offsetHeight / 2;
}
// ensure container doesn't go off the right side of the screen
if (x + this.container.offsetWidth > window.innerWidth) {
x = window.innerWidth - this.container.offsetWidth
}
// ensure container doesn't go off the bottom of the screen
if (y + this.container.offsetHeight > window.innerHeight) {
y = window.innerHeight - this.container.offsetHeight
}
// ensure container doesn't go off the left side of the screen
if (x < 0) {
x = 0
}
// ensure container doesn't go off the top of the screen
if (y < 0) {
y = 0
}
// this.container.style.display = "flex"
this.container.style.left = `${x}px`
this.container.style.top = `${y}px`
// reBuild && (this.container.style.display = "flex")
}
/**
* 关闭界面清除所有setInterval
*/
public hide() {
this.container.style.display = "none"
ztoolkit.log(this._ids)
this._ids.map(id=>id.id).forEach(window.clearInterval)
}
public stopAlloutput() {
this._ids.filter(id => id.type == "output").map(i => i.id).forEach(window.clearInterval)
}
/**
* 在输出界面插入辅助按钮
* 这是一个极具扩展性的函数
* 帮助定位,比如定位条目,PDF段落,PDF注释
*/
public insertAuxiliary(docs: Document[]) {
this.outputContainer.querySelector(".auxiliary")?.remove()
const auxDiv = ztoolkit.UI.appendElement({
namespace: "html",
classList: ["auxiliary"],
tag: "div",
styles: {
display: "flex",
alignItems: "center",
justifyContent: "center",
}
}, this.outputContainer)
docs.forEach((doc: Document, index: number) => {
ztoolkit.UI.appendElement({
namespace: "html",
tag: "a",
styles: {
margin: ".3em",
fontSize: "0.8em",
cursor: "pointer",
borderRadius: "3px",
backgroundColor: "rgba(89, 192, 188, .43)",
width: "1.5em",
height: "1.5em",
textAlign: "center",
color: "white",
fontWeight: "bold"
},
properties: {
innerText: index + 1
},
listeners: [
{
type: "click",
listener: async () => {
if (doc.metadata.type == "box") {
const reader = await ztoolkit.Reader.getReader();
(reader!._iframeWindow as any).wrappedJSObject.eval(`
PDFViewerApplication.pdfViewer.scrollPageIntoView({
pageNumber: ${doc.metadata.box.page + 1},
destArray: ${JSON.stringify([null, { name: "XYZ" }, doc.metadata.box.left, doc.metadata.box.top, 3.5])},
allowNegativeOffset: false,
ignoreDestinationZoom: false
})
`)
} else if (doc.metadata.type == "id") {
await ZoteroPane.selectItem(doc.metadata.id as number)
}
}
}
]
}, auxDiv)
})
}
/**
* 创建选项
*/
public createMenuNode(
rect: { x: number, y: number, width: number, height: number },
items: { name: string, listener: Function }[],
separators: number[]
) {
document.querySelector(".gpt-menu-box")?.remove()
const removeNode = () => {
document.removeEventListener("mousedown", removeNode)
document.removeEventListener("keydown", keyDownHandler)
window.setTimeout(() => {
menuNode.remove()
}, 0)
this.inputContainer.querySelector("input")?.focus()
}
document.addEventListener("mousedown", removeNode)
let menuNode = ztoolkit.UI.appendElement({
tag: "div",
classList: ["gpt-menu-box"],
styles: {
position: "fixed",
left: `${rect.x}px`,
top: `${rect.y}px`,
width: `${rect.width}px`,
display: "flex",
height: `${rect.height}px`,
justifyContent: "space-around",
flexDirection: "column",
padding: "6px",
border: "1px solid #d4d4d4",
backgroundColor: "#ffffff",
borderRadius: "8px",
boxShadow: `0px 1px 2px rgba(0, 0, 0, 0.028),
0px 3.4px 6.7px rgba(0, 0, 0, .042),
0px 15px 30px rgba(0, 0, 0, .07)`,
overflow: "hidden",
userSelect: "none",
},
children: (() => {
let arr = [];
for (let i = 0; i < items.length; i++) {
arr.push({
tag: "div",
classList: ["menu-item"],
styles: {
display: "flex",
alignItems: "center",
gap: "8px",
padding: "4px 8px",
cursor: "default",
fontSize: "13px",
borderRadius: "4px",
whiteSpace: "nowrap",
},
listeners: [
{
type: "mousedown",
listener: async (event: any) => {
await items[i].listener()
}
},
{
type: "mouseenter",
listener: function () {
nodes.forEach(e => e.classList.remove("selected"))
// @ts-ignore
this.classList.add("selected")
currentIndex = i
}
},
],
children: [
{
tag: "div",
classList: ["menu-item-name"],
styles: {
paddingLeft: "0.5em",
},
properties: {
innerText: items[i].name
}
}
]
})
if (separators.indexOf(i) != -1) {
arr.push({
tag: "div",
styles: {
height: "0",
margin: "6px -6px",
borderTop: ".5px solid #e0e0e0",
borderBottom: ".5px solid #e0e0e0",
}
})
}
}
return arr
})() as any
}, document.documentElement)
const winRect = document.documentElement.getBoundingClientRect()
const nodeRect = menuNode.getBoundingClientRect()
// 避免溢出
if (nodeRect.bottom > winRect.bottom) {
menuNode.style.top = ""
menuNode.style.bottom = "0px"
}
// menuNode.querySelector(".menu-item:first-child")?.classList.add("selected")
const nodes = menuNode.querySelectorAll(".menu-item")
nodes[0].classList.add("selected")
let currentIndex = 0
this.inputContainer.querySelector("input")?.blur()
let keyDownHandler = (event: any) => {
ztoolkit.log(event)
if (event.code == "ArrowDown") {
currentIndex += 1
if (currentIndex >= nodes.length) {
currentIndex = 0
}
} else if (event.code == "ArrowUp") {
currentIndex -= 1
if (currentIndex < 0) {
currentIndex = nodes.length - 1
}
} else if (event.code == "Enter") {
items[currentIndex].listener()
removeNode()
} else if (event.code == "Escape") {
removeNode()
}
nodes.forEach(e => e.classList.remove("selected"))
nodes[currentIndex].classList.add("selected")
}
document.addEventListener("keydown", keyDownHandler)
return menuNode
}
/**
* 绑定快捷键
*/
private registerKey() {
const callback = async () => {
this.isInNote = false
if (Zotero_Tabs.selectedIndex == 0) {
const div = document.querySelector("#item-tree-main-default .row.selected")!
if (div) {
const rect = div.getBoundingClientRect()
this.show(rect.x, rect.y + rect.height)
} else {
this.show()
}
} else {
const reader = await ztoolkit.Reader.getReader()
// const div = reader?._iframeWindow?.document.querySelector("#selection-menu")!
const div = reader?._iframeWindow?.document.querySelector(".selection-popup")!
if (div) {
window.setTimeout(() => {
this.messages = this.messages.concat(
[
{
role: "user",
content: `I am reading a PDF, and the following text is a part of the PDF. Please read it first, and I will ask you some question later: \n${Meet.Zotero.getPDFSelection()}`
},
{
role: "assistant",
content: "OK."
}
]
)
const rect = div?.getBoundingClientRect()
const windRect = document.documentElement.getBoundingClientRect()
const ww = windRect.width *
0.01 * Number((Zotero.Prefs.get(`${config.addonRef}.width`) as string).slice(0, -1))
ww
this.show(rect.left + rect.width * .5 - ww * .5, rect.bottom)
}, 233)
} else {
this.show()
}
}
}
if (Zotero.isMac) {
ztoolkit.Shortcut.register("event", {
id: config.addonRef,
modifiers: "meta",
key: "/",
callback: callback
})
} else {
ztoolkit.Shortcut.register("event", {
id: config.addonRef,
modifiers: "control",
key: "/",
callback: callback
})
}
document.addEventListener(
"keydown",
async (event: any) => {
// 笔记内按空格
if (
Zotero_Tabs.selectedIndex == 1 &&
event.explicitOriginalTarget.baseURI.indexOf("note-editor") >= 0 &&
event.code == "Space" &&
Zotero.BetterNotes.api.editor
) {
this.isInNote = true
const doc = event.explicitOriginalTarget.ownerDocument
let selection = doc.getSelection()
let range = selection.getRangeAt(0);
const span = range.endContainer
let text = await Meet.BetterNotes.getEditorText(span)
ztoolkit.log(text)
this.messages = [{
role: "user",
content: text
}]
if (/[\n ]+/.test(span.innerText)) {
Meet.BetterNotes.follow(span)
event.preventDefault();
}
return
}
if (
(event.shiftKey && event.key.toLowerCase() == "?") ||
(event.key == "/" && Zotero.isMac)) {
if (
event.originalTarget.isContentEditable ||
"value" in event.originalTarget
) {
return;
}
}
},
true
);
}
}
================================================
FILE: tags/Abstract2Introduction.txt
================================================
#摘要转综述[pos=1]
下面是一篇论文的摘要:
```js
const ztoolkit = Zotero.ZoteroGPT.data.ztoolkit
let getSelection = () => {
return ztoolkit.Reader.getSelectedText(
Zotero.Reader.getByTabID(Zotero_Tabs.selectedID)
);
}
getSelection()
```
现在我想引用它写一篇文献综述,请你帮我写几句话总结这篇论文的工作,作者没有告诉你,你可以用XX代替。我要中文的。要求50字左右。
---
使用场景: 选中PDF的摘要的时候
================================================
FILE: tags/Add-Controlled-Tagger
================================================
@Zotero GPT Tag
#Tags[color=#0EA253][trigger=/^生成标签/]
${
(async () => {
// =========================
// 0) 受控词表 + 与 zotero-gpt 对接的小工具
// =========================
const CONTROLLED = new Set([
"#Field/BuildingEnergyConsumption",
"#Field/IndoorThermalComfort",
"#Field/IndoorAirQuality",
"#Object/RuralResidence",
"#Method/MachineLearning",
"#Method/CFD",
"#Method/Experiment",
"#Type/Review"
]);
// ========== 新增:ProgressWindow 通知封装(最小侵入) ==========
const PW = (() => {
let pw = null;
let lines = [];
const iconMap = {
info: "chrome://zotero/skin/information.png",
success: "chrome://zotero/skin/tick.png",
warning: "chrome://zotero/skin/warning.png",
error: "chrome://zotero/skin/cross.png",
};
function ensure() {
try {
if (!Zotero?.ProgressWindow) return null;
if (!pw) {
pw = new Zotero.ProgressWindow();
pw.changeHeadline("智能标签生成");
pw.setProgress(100);
}
return pw;
} catch { return null; }
}
function showLine(msg, type = "info") {
const _pw = ensure();
if (_pw) {
_pw.addDescription(String(msg), iconMap[type] || iconMap.info);
_pw.show();
} else {
console.log(`[Tags][${type}] ${msg}`);
}
}
function startStep(msg) {
lines.push(String(msg));
const _pw = ensure();
if (_pw) {
_pw.addDescription(String(msg));
_pw.show();
} else {
console.log(`[Tags][STEP] ${msg}`);
}
}
function update(msgOrArray) {
const _pw = ensure();
if (!_pw) {
if (Array.isArray(msgOrArray)) msgOrArray.forEach(m => console.log(`[Tags] ${m}`));
else console.log(`[Tags] ${msgOrArray}`);
return;
}
// 简单策略:每次追加一行(避免复杂 diff)
const arr = Array.isArray(msgOrArray) ? msgOrArray : [msgOrArray];
arr.forEach(m => _pw.addDescription(String(m)));
_pw.show();
}
function close(afterMs = 1200) {
const _pw = ensure();
if (_pw) _pw.startCloseTimer(afterMs);
}
return { showLine, startStep, update, close };
})();
// ---------- 新增:格式规则 ----------
const TAXON_PREFIXES = ["#Field/","#Object/","#Method/","#Type/"];
const isFormattedTag = (s) => {
if (!s) return false;
const t = String(s).replace(/\u00A0/g," ").trim();
return /^#(Field|Object|Method|Type)\/[A-Za-z0-9_\-\/.]+$/.test(t);
};
const normalizeTag = (s) => String(s ?? "")
.replace(/\u00A0/g," ")
.replace(/[“”]/g,'"')
.trim();
// ---------- 更稳健:从任意文本中抽 JSON 数组 ----------
const extractJsonArray = (txt) => {
if (!txt) return null;
let s = String(txt)
.replace(/^[\s\S]*?(\[)/, "$1")
.replace(/(\])[\s\S]*$/, "$1")
.replace(/[“”]/g, '"');
const m = s.match(/\[[\s\S]*\]/);
if (!m) return null;
try {
const arr = JSON.parse(m[0]);
if (!Array.isArray(arr)) return null;
return arr.map(x => normalizeTag(x)).filter(Boolean);
} catch(_) { return null; }
};
// ---------- 新增:获取 Zotero 库里“已存在的格式化标签” ----------
const getAllFormattedTagsInLibrary = async () => {
const out = new Set();
const lower2canon = new Map();
try {
if (Zotero?.Tags?.getAll) {
const all = await Zotero.Tags.getAll();
for (const t of (all || [])) {
const name = normalizeTag(typeof t === "string" ? t : (t?.name || t?.tag || ""));
if (isFormattedTag(name)) {
out.add(name);
lower2canon.set(name.toLowerCase(), name);
}
}
}
} catch (_) {}
try {
const ts = ZoteroPane?.tagSelector;
const list = (ts?.getTags && ts.getTags()) || ts?._tags || [];
for (const t of list) {
const name = normalizeTag(typeof t === "string" ? t : (t?.name || t?.tag || ""));
if (isFormattedTag(name)) {
out.add(name);
lower2canon.set(name.toLowerCase(), name);
}
}
} catch (_) {}
return { formattedSet: out, lower2canon };
};
// ---------- LLM 提示词 ----------
const askLLMForTags = async (controlledListString, paperText) => {
const prompt = `
Read the abstract/fulltext below and output 3–5 tags ONLY as a JSON array.
Rules:
- Each tag MUST strictly follow these namespaces and format:
"#Field/<Name>" or "#Object/<Name>" or "#Method/<Name>" or "#Type/<Name>"
- Use "/" to separate the top-level namespace and the name (e.g., "#Field/IndoorThermalComfort").
- Prefer concepts in the controlled list when applicable; otherwise generate appropriate custom tags that still follow the format above.
- Output ONLY the JSON array (no prose, no code fence, no comments).
Controlled list (for reference):
${controlledListString}
Abstract / Text:
${paperText}
Example of the ONLY acceptable output format:
["#Field/IndoorThermalComfort","#Method/CFD","#Object/Furniture"]
`.trim();
PW.startStep("调用 LLM 生成标签…");
const res = await Meet?.Global?.views?.ask?.(prompt);
const parsed = extractJsonArray(res);
if (!parsed) PW.showLine("LLM 未返回有效 JSON 数组,尝试兜底策略", "warning");
return parsed;
};
// =========================
// 1) 必要的保留函数
// =========================
const safe = (v, f="") => {
if (v===undefined || v===null) return f;
return String(v).replace(/\u00A0/g," ").trim();
};
const getTagsSafe = (top) => {
try {
if (typeof top?.getTags === "function") {
const tags = top.getTags() || [];
return tags.map(t => safe(t?.tag || t?.name, "")).filter(Boolean);
}
} catch(e) {}
return [];
};
// ---------- 新增:对 LLM 输出做“库中已存在标签优先匹配”的映射 ----------
const mapToExistingOrAcceptCustom = (llmTags, existingSet, lower2canon) => {
const chosen = [];
const seen = new Set();
for (const raw of (llmTags || [])) {
const t = normalizeTag(raw);
if (!isFormattedTag(t)) continue;
const lower = t.toLowerCase();
const canon = lower2canon.get(lower);
const finalTag = canon || t;
if (!seen.has(finalTag)) {
chosen.push(finalTag);
seen.add(finalTag);
}
}
return chosen.slice(0, 5);
};
// ---------- 修改:applyTags 增加进度提示 ----------
const applyTagsToZotero = async (topItem, tagList) => {
if (!topItem || !Array.isArray(tagList) || !tagList.length) return;
try {
const existingTags = getTagsSafe(topItem);
const existingTagNames = new Set(existingTags.map(normalizeTag));
const wanted = Array.from(new Set(
tagList
.map(normalizeTag)
.filter(t => isFormattedTag(t) && !existingTagNames.has(t))
));
if (!wanted.length) {
PW.showLine("推荐标签已存在,无需添加", "info");
return;
}
PW.startStep(`添加 ${wanted.length} 个标签…`);
for (const tagName of wanted) {
if (typeof topItem.addTag === "function") topItem.addTag(tagName);
}
if (typeof topItem.saveTx === "function") await topItem.saveTx();
else if (typeof topItem.save === "function") await topItem.save();
else if (typeof topItem.saveChanges === "function") await topItem.saveChanges();
PW.showLine(`成功添加:${wanted.join(", ")}`, "success");
} catch (e) {
PW.showLine(`添加标签失败:${e.message}`, "error");
console.error("[Tags] Failed to add tags to Zotero:", e);
}
};
const stripReferences = (raw) => {
if (!raw) return raw;
const lines = raw.split(/\r?\n/);
const lower = lines.map(l => l.trim().toLowerCase());
const refHeadings = ["references","参考文献","bibliography","works cited","literature cited"];
const tailHeadings = ["declaration of competing interest","conflict of interest","credit authorship contribution statement","acknowledgements","acknowledgments","作者贡献","致谢","资金支持","funding","appendix","附录"];
let cutIdx = -1;
for (let i = lines.length - 1; i >= 0; i--) {
const s = lower[i];
if (!s) continue;
if (refHeadings.some(h => s === h || s.startsWith(h))) { cutIdx = i; break; }
}
if (cutIdx < 0) {
const startTail = Math.floor(lines.length * 0.6);
for (let i = startTail; i < lines.length; i++) {
const s = lower[i];
if (tailHeadings.some(h => s === h || s.startsWith(h))) { cutIdx = i; break; }
}
}
const isRefLine = (s) => /^\s*(\[\d+\]|\d+\.)\s+/.test(s) || (/^[A-Z][A-Za-z\-']+(,\s*[A-Z]\.){1,3}.*\(\d{4}\)/.test(s));
if (cutIdx < 0) {
const start = Math.floor(lines.length * 0.6);
let consec = 0, startIdx = -1;
for (let i = start; i < lines.length; i++) {
if (isRefLine(lines[i])) { if (startIdx < 0) startIdx = i; consec++; }
else if (consec > 0) { if (consec >= 5) { cutIdx = startIdx; break; } consec = 0; startIdx = -1; }
}
if (cutIdx < 0 && consec >= 5) cutIdx = startIdx;
}
return (cutIdx >= 0) ? lines.slice(0, cutIdx).join("\n").trim() : raw;
};
// ========== 若无法提取文本,则上传 PDF 给 LLM ==========
const uploadPdfIfNoText = async (pdfItem, extractedTxt) => {
try {
if (!pdfItem) return false;
const empty = !extractedTxt || String(extractedTxt).trim() === "";
if (!empty) return false;
const up = window?.Meet?.OpenAI?.uploadFile;
if (typeof up !== "function") return false;
PW.startStep("未提取到文本,上传 PDF 给 LLM…");
await up([pdfItem]);
PW.showLine("PDF 已上传至 LLM", "success");
return true;
} catch (e) {
PW.showLine(`PDF 上传失败:${e.message}`, "error");
return false;
}
};
// =========================
// 2) 选取单一 PDF 目标
// =========================
PW.showLine("开始生成智能标签…", "info");
const isLibEnv = (typeof Zotero_Tabs !== "undefined");
const isLibrary = isLibEnv && (Zotero_Tabs.selectedType === "library");
const isReader = isLibEnv && (Zotero_Tabs.selectedType === "reader");
let pdfItem = null;
if (isReader && typeof Zotero?.Reader?.getByTabID === "function") {
const reader = Zotero.Reader.getByTabID(Zotero_Tabs.selectedID);
pdfItem = reader?._item || reader?.item || null;
} else if (isLibrary && typeof ZoteroPane !== "undefined" && typeof ZoteroPane.getSelectedItems === "function") {
const items = ZoteroPane.getSelectedItems() || [];
if (items.length) {
const first = items[0];
const isPdf = (() => {
try { return first?.isPDFAttachment && first.isPDFAttachment(); } catch (_) { return false; }
})();
if (isPdf) {
pdfItem = first;
} else {
try {
if (typeof first?.getBestAttachmentState === "function" && typeof first?.getBestAttachment === "function") {
const st = await first.getBestAttachmentState();
if (st?.exists) {
const best = await first.getBestAttachment();
if (best?.isPDFAttachment && best.isPDFAttachment()) {
pdfItem = best;
}
}
}
} catch (_) {}
if (!pdfItem && typeof first?.getAttachments === "function") {
try {
const childIds = first.getAttachments() || [];
for (const cid of childIds) {
const ch = Zotero.Items.get(cid);
if (ch?.isPDFAttachment && ch.isPDFAttachment()) { pdfItem = ch; break; }
}
} catch (_) {}
}
}
}
}
if (!pdfItem) {
PW.showLine("未找到 PDF 附件,请选择包含 PDF 的文献项", "error");
PW.close(3000);
return "";
}
const targets = [{ item: pdfItem, number: 1 }];
const CONTROLLED_LIST_STRING = Array.from(CONTROLLED).join("\n");
// 预抓库中格式化标签
PW.startStep("读取库内已存在的格式化标签…");
const { formattedSet: LIB_FORMATTED_SET, lower2canon: LIB_LC2CANON } = await getAllFormattedTagsInLibrary();
for (const { item: pdfItem, number } of targets) {
try {
const top = pdfItem?.topLevelItem || pdfItem;
// 提取文本
PW.startStep("提取 PDF 文本…");
let textRaw = "";
try {
if (typeof Zotero?.PDFWorker?.getFullText === "function") {
const ft = await Zotero.PDFWorker.getFullText(pdfItem.id, null);
textRaw = safe(ft?.text, "");
}
} catch (_) { textRaw = ""; }
await uploadPdfIfNoText(pdfItem, textRaw);
const text = stripReferences(textRaw);
const payload = text || "(no fulltext extracted)";
// 调 LLM
const arr = await askLLMForTags(CONTROLLED_LIST_STRING, payload);
// 匹配/接受
let candidateTags = mapToExistingOrAcceptCustom(arr, LIB_FORMATTED_SET, LIB_LC2CANON);
if (!candidateTags.length) {
candidateTags = ["#Field/BuildingEnergyConsumption","#Method/MachineLearning","#Object/Furniture"]
.filter(t => CONTROLLED.has(t))
.slice(0, 3);
PW.showLine("LLM 未返回有效标签,使用兜底标签", "warning");
} else {
PW.showLine(`LLM 返回标签:${candidateTags.join(", ")}`, "info");
}
// 写入
if (candidateTags.length) {
await applyTagsToZotero(top, candidateTags);
}
} catch (e) {
PW.showLine(`处理失败:${e.message}`, "error");
console.error("(处理失败)", e);
}
}
PW.showLine("标签生成流程完成", "success");
PW.close(1800);
return "";
})(); // IIFE 结束
}$
================================================
FILE: tags/AddTags.txt
================================================
#🔭AddTags[position=9][color=#B7A7DB]
下面是我在Zotero里创建的一些嵌套标签,它们以#开头,中间用/连接:
```js
Zotero.ZoteroGPT.views.messages = [];
JSON.stringify(Zotero.ZoteroStyle.data.views.tagsUI.plainTags.slice(0, 20))
```
---
这是一篇文献的摘要:
```js
ZoteroPane.getSelectedItems()[0].getField("abstractNote")
```
---
请你帮我根据我已有的嵌套标签,分析出我该给这篇文献添加什么嵌套标签,请你推荐三个,并给我一段代码,这段代码将在Zotero里执行,下面是示例代码:
```js
const tags = ["#tag1/tag2/tag3", "#tag1/tag2/tag3", "#tag1/tag2/tag3"]
item = ZoteroPane.getSelectedItems()[0]
tags.forEach(tag=>{
item.addTag(tag)
})
await item.saveTx()
```
---
你只需要回答我代码,除了代码你不需要进行任何文字描述,你给出代码是:
================================================
FILE: tags/AskAbstract.txt
================================================
#摘要提问[pos=0]
下面是一篇论文的摘要:
```js
const ztoolkit = Zotero.ZoteroGPT.data.ztoolkit
let getSelection = () => {
return ztoolkit.Reader.getSelectedText(
Zotero.Reader.getByTabID(Zotero_Tabs.selectedID)
);
}
getSelection()
```
================================================
FILE: tags/AskClipboard.txt
================================================
#📄AskClipboard[position=9][color=#dc4334]
Read this:
```js
Zotero.ZoteroGPT.utils.getClipboardText()
```
---
please answer this question based on above content (use 简体中文):
```js
Zotero.ZoteroGPT.views.inputContainer.querySelector("input").value
```
================================================
FILE: tags/AskExperimentDetails.txt
================================================
#总结实验方法[pos=9]
请用子弹列表的形式提取该段落的信息,包括,被试数量,实验设计(如, 2(Gender: male vs female) X 2(Matching Condition: matching or mismatching)),实验流程(如,被试首先观看刺激,然后进行反应,最后呈现反馈给被试)。务必使用中文回答。
下面是论文的方法部分:
```js
const ztoolkit = Zotero.ZoteroGPT.data.ztoolkit
let getSelection = () => {
return ztoolkit.Reader.getSelectedText(
Zotero.Reader.getByTabID(Zotero_Tabs.selectedID)
);
}
ztoolkit.log(getSelection())
getSelection()
```
---
选中PDF文字时候
================================================
FILE: tags/AskJournal.txt
================================================
#期刊介绍[pos=9]
介绍一下下面这个期刊:
```js
ZoteroPane.getSelectedItems()[0].getField("publicationTitle")
```
---
应用场景: 选中主界面条目时候
================================================
FILE: tags/AskPDF.txt
================================================
#🪐AskPDF[pos=0][color=#009FBD]
You are a helpful assistant. Context information is below.
---
```js
window.gptInputString = Zotero.ZoteroGPT.views.inputContainer.querySelector("input").value
Zotero.ZoteroGPT.views.messages = [];
Zotero.ZoteroGPT.utils.getRelatedText(
window.gptInputString
)
```
---
Current date:
```js
String(new Date())
```
Using the provided context information, write a comprehensive reply to the given
gitextract_w6wx77lm/ ├── .github/ │ ├── ISSUE_TEMPLATE/ │ │ ├── config.yml │ │ ├── report_bug_cn.yml │ │ └── report_bug_en.yml │ ├── dependabot.yml │ └── workflows/ │ ├── manual.yml │ ├── publish_wiki_tags.yml │ └── wiki.yml ├── .gitignore ├── .release-it.json ├── .vscode/ │ ├── launch.json │ └── toolkit.code-snippets ├── LICENSE ├── addon/ │ ├── bootstrap.js │ ├── chrome/ │ │ ├── content/ │ │ │ └── md.css │ │ └── locale/ │ │ ├── en-US/ │ │ │ ├── addon.properties │ │ │ └── overlay.dtd │ │ └── zh-CN/ │ │ ├── addon.properties │ │ └── overlay.dtd │ ├── chrome.manifest │ ├── install.rdf │ ├── manifest.json │ └── prefs.js ├── package.json ├── scripts/ │ ├── build.js │ ├── start.js │ ├── stop.js │ └── zotero-cmd-default.json ├── src/ │ ├── addon.ts │ ├── hooks.ts │ ├── index.ts │ └── modules/ │ ├── Meet/ │ │ ├── BetterNotes.ts │ │ ├── OpenAI.ts │ │ ├── Zotero.ts │ │ └── api.ts │ ├── base.ts │ ├── localStorage.ts │ ├── locale.ts │ ├── utils.ts │ └── views.ts ├── tags/ │ ├── Abstract2Introduction.txt │ ├── Add-Controlled-Tagger │ ├── AddTags.txt │ ├── AskAbstract.txt │ ├── AskClipboard.txt │ ├── AskExperimentDetails.txt │ ├── AskJournal.txt │ ├── AskPDF.txt │ ├── Readme.md │ ├── SearchItems.txt │ └── Translate.txt ├── tsconfig.json ├── typing/ │ └── global.d.ts ├── update-template.json ├── update-template.rdf ├── update.json └── update.rdf
SYMBOL INDEX (80 symbols across 13 files)
FILE: addon/bootstrap.js
function waitForZotero (line 20) | async function waitForZotero() {
function install (line 64) | function install(data, reason) {}
function startup (line 66) | async function startup({ id, version, resourceURI, rootURI }, reason) {
function shutdown (line 105) | function shutdown({ id, version, resourceURI, rootURI }, reason) {
function uninstall (line 128) | function uninstall(data, reason) {}
function setDefaultPrefs (line 131) | function setDefaultPrefs(rootURI) {
FILE: scripts/build.js
function copyFileSync (line 17) | function copyFileSync(source, target) {
function copyFolderRecursiveSync (line 30) | function copyFolderRecursiveSync(source, target) {
function clearFolder (line 53) | function clearFolder(target) {
function dateFormat (line 61) | function dateFormat(fmt, date) {
function main (line 83) | async function main() {
FILE: src/addon.ts
class Addon (line 5) | class Addon {
method constructor (line 26) | constructor() {
FILE: src/hooks.ts
function onStartup (line 7) | async function onStartup() {
function onShutdown (line 25) | function onShutdown(): void {
FILE: src/modules/Meet/BetterNotes.ts
function getEditorText (line 9) | async function getEditorText(span: HTMLSpanElement) {
function reFocus (line 27) | function reFocus(editor?: any) {
function replaceEditorText (line 37) | function replaceEditorText(htmlString: string) {
function insertEditorText (line 55) | function insertEditorText(htmlString: string, editor?: any) {
function follow (line 74) | function follow() {
FILE: src/modules/Meet/OpenAI.ts
type RequestArg (line 8) | type RequestArg = { headers: any, api: string, body: Function, remove?: ...
function similaritySearch (line 48) | async function similaritySearch(queryText: string, docs: Document[], obj...
class OpenAIEmbeddings (line 85) | class OpenAIEmbeddings {
method constructor (line 86) | constructor() {
method request (line 88) | private async request(input: string[]) {
method embedDocuments (line 143) | public async embedDocuments(texts: string[]) {
method embedQuery (line 147) | public async embedQuery(text: string) {
function getGPTResponse (line 153) | async function getGPTResponse(requestText: string) {
function getGPTResponseByOpenAI (line 166) | async function getGPTResponseByOpenAI(requestText: string) {
function getGPTResponseBy (line 273) | async function getGPTResponseBy(
FILE: src/modules/Meet/Zotero.ts
function getClipboardText (line 12) | function getClipboardText(): string {
function selectedItems2documents (line 41) | async function selectedItems2documents(key: string) {
function mergeSameLine (line 61) | function mergeSameLine(items: PDFItem[]) {
type Box (line 119) | type Box = {
function isIntersect (line 132) | function isIntersect(A: Box, B: Box): boolean {
function isIntersectLines (line 153) | function isIntersectLines(lineA: any, lineB: any, maxWidth: number, maxH...
function pdf2documents (line 174) | async function pdf2documents(itemkey: string) {
function getRelatedText (line 371) | async function getRelatedText(queryText: string) {
function getItemField (line 402) | function getItemField(fieldName: any) {
function getPDFSelection (line 410) | function getPDFSelection() {
function getPDFAnnotations (line 420) | async function getPDFAnnotations(select: boolean = false) {
FILE: src/modules/base.ts
function parseTag (line 47) | function parseTag(text: string) {
FILE: src/modules/localStorage.ts
class LocalStorage (line 3) | class LocalStorage {
method constructor (line 7) | constructor(filename: string) {
method init (line 12) | async init(filename: string) {
method get (line 31) | get(item: Zotero.Item | { key: string }, key: string) {
method set (line 36) | async set(item: Zotero.Item | { key: string }, key: string, value: any) {
FILE: src/modules/locale.ts
function initLocale (line 3) | function initLocale() {
function getString (line 11) | function getString(
FILE: src/modules/utils.ts
class Utils (line 3) | class Utils {
method constructor (line 4) | constructor() {
method getRGB (line 6) | public getRGB(color: string) {
method getRelatedText (line 35) | public async getRelatedText(queryText: string) {
FILE: src/modules/views.ts
class Views (line 15) | class Views {
method constructor (line 43) | constructor() {
method addStyle (line 52) | private addStyle() {
method setText (line 146) | public setText(text: string, isDone: boolean = false, scrollToNewLine:...
method addDragEvent (line 244) | private addDragEvent(node: HTMLDivElement) {
method bindUpDownKeys (line 287) | private bindUpDownKeys(inputNode: HTMLInputElement) {
method bindCtrlScrollZoom (line 323) | private bindCtrlScrollZoom(div: HTMLDivElement) {
method bindCtrlScrollZoomOutput (line 353) | private bindCtrlScrollZoomOutput(div: HTMLDivElement) {
method buildContainer (line 403) | private buildContainer() {
method renderTags (line 835) | private renderTags() {
method addTag (line 846) | private addTag(tag: Tag, index: number) {
method rippleEffect (line 908) | private rippleEffect(div: HTMLDivElement, color: string) {
method execTag (line 921) | private async execTag(tag: Tag) {
method execText (line 981) | private async execText(text: string) {
method getTags (line 1010) | private getTags() {
method setTags (line 1029) | private setTags(tags: any[]) {
method show (line 1038) | public show(x: number = -1, y: number = -1, reBuild: boolean = true) {
method hide (line 1080) | public hide() {
method stopAlloutput (line 1086) | public stopAlloutput() {
method insertAuxiliary (line 1095) | public insertAuxiliary(docs: Document[]) {
method createMenuNode (line 1153) | public createMenuNode(
method registerKey (line 1294) | private registerKey() {
FILE: typing/global.d.ts
type PDFLine (line 21) | type PDFLine = {
type PDFItem (line 32) | type PDFItem = {
type PDFAnnotation (line 50) | type PDFAnnotation = {
type Rect (line 56) | interface Rect {
type Tag (line 66) | interface Tag { tag: string; color: string; position: number, trigger: s...
Condensed preview — 56 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (212K chars).
[
{
"path": ".github/ISSUE_TEMPLATE/config.yml",
"chars": 159,
"preview": "blank_issues_enabled: true\ncontact_links:\n - name: 命令标签分享\n url: https://github.com/MuiseDestiny/zotero-gpt/discussio"
},
{
"path": ".github/ISSUE_TEMPLATE/report_bug_cn.yml",
"chars": 1622,
"preview": "name: 插件问题反馈\ndescription: \"报告本插件存在的问题,且您确信这是插件问题而不是您的问题\"\n#title: \"\"\n#labels: [\"bug\"]\nbody:\n - type: markdown\n attrib"
},
{
"path": ".github/ISSUE_TEMPLATE/report_bug_en.yml",
"chars": 2493,
"preview": "name: Plugin Issue Report\ndescription: \"Report issues with this plugin, and you believe that it is a plugin issue rather"
},
{
"path": ".github/dependabot.yml",
"chars": 502,
"preview": "# To get started with Dependabot version updates, you'll need to specify which\n# package ecosystems to update and where "
},
{
"path": ".github/workflows/manual.yml",
"chars": 2974,
"preview": "name: Manual Trigger\n\npermissions: write-all\n\non:\n # 手动触发\n workflow_dispatch:\n # inputs:\n # logLevel:\n # "
},
{
"path": ".github/workflows/publish_wiki_tags.yml",
"chars": 1311,
"preview": "name: Publish wiki tags\n\npermissions: write-all\n\non:\n push:\n branches:\n - bootstrap\n paths:\n - 'tags/*."
},
{
"path": ".github/workflows/wiki.yml",
"chars": 2366,
"preview": "name: Release Trigger\n\n# https://docs.github.com/en/actions/using-jobs/assigning-permissions-to-jobs#overview\npermission"
},
{
"path": ".gitignore",
"chars": 79,
"preview": "**/builds\nnode_modules\npackage-lock.json\nzotero-cmd.json\nREADME.md\n.env\n**/test"
},
{
"path": ".release-it.json",
"chars": 257,
"preview": "{\n \"npm\": {\n \"publish\": false\n },\n \"github\": {\n \"release\": true,\n \"assets\": [\"builds/*.xpi\"]\n },\n \"hooks\":"
},
{
"path": ".vscode/launch.json",
"chars": 686,
"preview": "{\n // 使用 IntelliSense 了解相关属性。 \n // 悬停以查看现有属性的描述。\n // 欲了解更多信息,请访问: https://go.microsoft.com/fwlink/?linkid=83038"
},
{
"path": ".vscode/toolkit.code-snippets",
"chars": 1499,
"preview": "{\n \"appendElement - full\": {\n \"scope\": \"javascript,typescript\",\n \"prefix\": \"appendElement\",\n \"bo"
},
{
"path": "LICENSE",
"chars": 34520,
"preview": " GNU AFFERO GENERAL PUBLIC LICENSE\n Version 3, 19 November 2007\n\n Copyright (C)"
},
{
"path": "addon/bootstrap.js",
"chars": 4580,
"preview": "/**\n * Most of this code is from Zotero team's official Make It Red example[1]\n * or the Zotero 7 documentation[2].\n * ["
},
{
"path": "addon/chrome/content/md.css",
"chars": 25110,
"preview": ".markdown-body {\n --color-prettylights-syntax-comment: #6e7781;\n --color-prettylights-syntax-constant: #0550ae;\n "
},
{
"path": "addon/chrome/locale/en-US/addon.properties",
"chars": 378,
"preview": "startup.begin=Addon is loading\nstartup.finish=Addon is ready\nmenuitem.label=Addon Template: Helper Examples\nmenupopup.la"
},
{
"path": "addon/chrome/locale/en-US/overlay.dtd",
"chars": 410,
"preview": "<!ENTITY zotero.__addonRef__.pref.title \"Addon Template Example\">\n<!ENTITY zotero.__addonRef__.itemmenu.test.label \"addo"
},
{
"path": "addon/chrome/locale/zh-CN/addon.properties",
"chars": 279,
"preview": "startup.begin=插件加载中\nstartup.finish=插件已就绪\nmenuitem.label=插件模板: 帮助工具样例\nmenupopup.label=插件模板: 弹出菜单\nmenuitem.submenulabel=插件"
},
{
"path": "addon/chrome/locale/zh-CN/overlay.dtd",
"chars": 374,
"preview": "<!ENTITY zotero.__addonRef__.pref.title \"插件模板设置示例\">\n<!ENTITY zotero.__addonRef__.itemmenu.test.label \"插件模板\">\n<!ENTITY zo"
},
{
"path": "addon/chrome.manifest",
"chars": 131,
"preview": "content __addonRef__ chrome/content/\nlocale __addonRef__ en-US chrome/locale/en-US/\nlocale __addonRef__ zh-CN chrome/loc"
},
{
"path": "addon/install.rdf",
"chars": 1308,
"preview": "<?xml version=\"1.0\"?>\n<RDF:RDF\n xmlns:em=\"http://www.mozilla.org/2004/em-rdf#\"\n xmlns:NC=\"http://home.netscape.com"
},
{
"path": "addon/manifest.json",
"chars": 448,
"preview": "{\n \"manifest_version\": 2,\n \"name\": \"__addonName__\",\n \"version\": \"__buildVersion__\",\n \"description\": \"__description__"
},
{
"path": "addon/prefs.js",
"chars": 698,
"preview": "pref(\"extensions.zotero.__addonRef__.enable\", true);\npref(\"extensions.zotero.__addonRef__.tags\", \"[]\");\npref(\"extensions"
},
{
"path": "package.json",
"chars": 2590,
"preview": "{\n \"name\": \"zotero-gpt\",\n \"version\": \"0.2.8\",\n \"description\": \"GPT Meet Zotero\",\n \"config\": {\n \"addonName\": \"Zote"
},
{
"path": "scripts/build.js",
"chars": 4784,
"preview": "const esbuild = require(\"esbuild\");\nconst compressing = require(\"compressing\");\nconst path = require(\"path\");\nconst fs ="
},
{
"path": "scripts/start.js",
"chars": 700,
"preview": "const { execSync } = require(\"child_process\");\nconst { exit } = require(\"process\");\nconst { exec } = require(\"./zotero-c"
},
{
"path": "scripts/stop.js",
"chars": 261,
"preview": "const { execSync } = require(\"child_process\");\nconst { killZoteroWindows, killZoteroUnix } = require(\"./zotero-cmd.json\""
},
{
"path": "scripts/zotero-cmd-default.json",
"chars": 265,
"preview": "{\n \"usage\": \"Copy and rename this file to zotero-cmd.json. Edit the cmd.\",\n \"killZoteroWindows\": \"taskkill /f /im zote"
},
{
"path": "src/addon.ts",
"chars": 843,
"preview": "import ZoteroToolkit from \"zotero-plugin-toolkit/dist/index\";\nimport { ColumnOptions } from \"zotero-plugin-toolkit/dist/"
},
{
"path": "src/hooks.ts",
"chars": 854,
"preview": "import { config } from \"../package.json\";\nimport { getString, initLocale } from \"./modules/locale\";\nimport Views from \"."
},
{
"path": "src/index.ts",
"chars": 1850,
"preview": "import { BasicTool } from \"zotero-plugin-toolkit/dist/basic\";\nimport Addon from \"./addon\";\nimport { config } from \"../pa"
},
{
"path": "src/modules/Meet/BetterNotes.ts",
"chars": 3388,
"preview": "import Views from \"../views\";\nimport Meet from \"./api\";\n\n/**\n * 优先返回选中文本,再返回所在span前所有文字MD\n * @param span 光标所在行,HTMLSpanE"
},
{
"path": "src/modules/Meet/OpenAI.ts",
"chars": 10900,
"preview": "import { config } from \"../../../package.json\";\nimport { MD5 } from \"crypto-js\"\nimport { Document } from \"langchain/docu"
},
{
"path": "src/modules/Meet/Zotero.ts",
"chars": 13969,
"preview": "import { config } from \"../../../package.json\";\nimport { MD5 } from \"crypto-js\"\nimport { Document } from \"langchain/docu"
},
{
"path": "src/modules/Meet/api.ts",
"chars": 1447,
"preview": "import {\n getClipboardText,\n getItemField,\n getPDFSelection,\n getRelatedText,\n getPDFAnnotations\n} from \"./Zotero\"\n"
},
{
"path": "src/modules/base.ts",
"chars": 6199,
"preview": "import { config } from \"../../package.json\";\n\n\nconst help = `\n### Quick Commands\n\n\\`/help\\` Show all commands.\n\\`/clear\\"
},
{
"path": "src/modules/localStorage.ts",
"chars": 1268,
"preview": "import { config } from \"../../package.json\";\n\nclass LocalStorage {\n public filename!: string;\n public cache: any;\n pu"
},
{
"path": "src/modules/locale.ts",
"chars": 631,
"preview": "import { config } from \"../../package.json\";\n\nexport function initLocale() {\n addon.data.locale = {\n stringBundle: C"
},
{
"path": "src/modules/utils.ts",
"chars": 916,
"preview": "import Meet from \"./Meet/api\";\n\nexport default class Utils {\n constructor() {\n }\n public getRGB(color: string) {\n "
},
{
"path": "src/modules/views.ts",
"chars": 45225,
"preview": "import { config } from \"../../package.json\";\nimport Meet from \"./Meet/api\"\nimport Utils from \"./utils\";\nimport { Documen"
},
{
"path": "tags/Abstract2Introduction.txt",
"chars": 321,
"preview": "#摘要转综述[pos=1]\n\n下面是一篇论文的摘要:\n\n```js\nconst ztoolkit = Zotero.ZoteroGPT.data.ztoolkit\nlet getSelection = () => {\n return "
},
{
"path": "tags/Add-Controlled-Tagger",
"chars": 13223,
"preview": "@Zotero GPT Tag\n#Tags[color=#0EA253][trigger=/^生成标签/]\n${\n(async () => {\n // =========================\n // 0) 受控词表 + 与 "
},
{
"path": "tags/AddTags.txt",
"chars": 584,
"preview": "#🔭AddTags[position=9][color=#B7A7DB]\n\n下面是我在Zotero里创建的一些嵌套标签,它们以#开头,中间用/连接:\n```js\nZotero.ZoteroGPT.views.messages = [];\nJ"
},
{
"path": "tags/AskAbstract.txt",
"chars": 229,
"preview": "#摘要提问[pos=0]\n\n下面是一篇论文的摘要:\n\n```js\nconst ztoolkit = Zotero.ZoteroGPT.data.ztoolkit\nlet getSelection = () => {\n return z"
},
{
"path": "tags/AskClipboard.txt",
"chars": 256,
"preview": "#📄AskClipboard[position=9][color=#dc4334]\n\nRead this:\n\n```js\n\nZotero.ZoteroGPT.utils.getClipboardText()\n\n```\n\n---\n\npleas"
},
{
"path": "tags/AskExperimentDetails.txt",
"chars": 433,
"preview": "#总结实验方法[pos=9]\n\n请用子弹列表的形式提取该段落的信息,包括,被试数量,实验设计(如, 2(Gender: male vs female) X 2(Matching Condition: matching or mismatch"
},
{
"path": "tags/AskJournal.txt",
"chars": 122,
"preview": "#期刊介绍[pos=9]\n\n介绍一下下面这个期刊: \n```js\nZoteroPane.getSelectedItems()[0].getField(\"publicationTitle\")\n```\n\n---\n\n应用场景: 选中主界面条目时"
},
{
"path": "tags/AskPDF.txt",
"chars": 787,
"preview": "#🪐AskPDF[pos=0][color=#009FBD]\n\nYou are a helpful assistant. Context information is below.\n\n---\n```js\nwindow.gptInputStr"
},
{
"path": "tags/Readme.md",
"chars": 623,
"preview": "## About Tag\n\nYou can long click on the tag below to see its internal pseudo-code.\nYou can type #xxx and enter to create"
},
{
"path": "tags/SearchItems.txt",
"chars": 422,
"preview": "#🔍SearchItems[position=9][color=#ED5629]\n\n现在你是一个数据库系统,下面是一些JSON信息,每个JSON对应Zotero一篇文献:\n\n---\n\n```js\nwindow.gptInputString "
},
{
"path": "tags/Translate.txt",
"chars": 119,
"preview": "#🎈Translate[pos=1][c=#21a2f1]\n\ntranslate these from english to 简体中文:\n```js\nZotero.ZoteroGPT.utils.getPDFSelection()\n```"
},
{
"path": "tsconfig.json",
"chars": 288,
"preview": "{\n \"compilerOptions\": {\n \"experimentalDecorators\": true,\n \"module\": \"commonjs\",\n \"target\": \"ES2016\",\n \"reso"
},
{
"path": "typing/global.d.ts",
"chars": 1244,
"preview": "declare const _globalThis: {\n [key: string]: any;\n Zotero: _ZoteroTypes.Zotero;\n ZoteroPane: _ZoteroTypes.ZoteroPane;"
},
{
"path": "update-template.json",
"chars": 529,
"preview": "{\n \"addons\": {\n \"__addonID__\": {\n \"updates\": [\n {\n \"version\": \"__buildVersion__\",\n \"up"
},
{
"path": "update-template.rdf",
"chars": 1173,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" xmlns:em=\"http:/"
},
{
"path": "update.json",
"chars": 487,
"preview": "{\n \"addons\": {\n \"zoterogpt@polygon.org\": {\n \"updates\": [\n {\n \"version\": \"0.2.9\",\n \"upd"
},
{
"path": "update.rdf",
"chars": 1143,
"preview": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" xmlns:em=\"http:/"
}
]
About this extraction
This page contains the full source code of the MuiseDestiny/zotero-gpt GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 56 files (195.6 KB), approximately 54.4k tokens, and a symbol index with 80 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.