Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7d79beaf7c | ||
|
|
d4d1729b0f | ||
|
|
3e793c55db | ||
|
|
8cb439c1b9 | ||
|
|
231ff2bbbf | ||
|
|
1b8b809122 | ||
|
|
4222adae59 | ||
|
|
2858a770df | ||
|
|
f567841ab2 | ||
|
|
9b7a74e1a4 | ||
|
|
b2783d7945 | ||
|
|
7451a4723a | ||
|
|
617279573b | ||
|
|
4bcc16b4f7 | ||
|
|
4514f0a25f | ||
|
|
8fa9a869a0 | ||
|
|
f3776c8fb5 | ||
|
|
ada8fa6d91 | ||
|
|
957ddfe70e | ||
|
|
77cc5ff890 | ||
|
|
5d8d05a291 | ||
|
|
93b1ab7b12 | ||
|
|
751793b313 | ||
|
|
67d24fe4a4 | ||
|
|
7f42a79d68 | ||
|
|
bc5a0540e8 | ||
|
|
43080cbf4c | ||
|
|
b70666decb | ||
|
|
1d52311bd7 | ||
|
|
672cda65ae | ||
|
|
8a4dc9d926 | ||
|
|
b88f6f3cd6 | ||
|
|
11efba69c8 | ||
|
|
e96371b7c6 | ||
|
|
04639e0e9b | ||
|
|
2fbad53fad | ||
|
|
4c5d48a51b | ||
|
|
9783c5e434 | ||
|
|
7efff73127 | ||
|
|
c0c1797ff4 | ||
|
|
49eb8907fd | ||
|
|
5f0c8a0be6 | ||
|
|
4b092a6688 | ||
|
|
87156fefcb | ||
|
|
017e2e10d6 | ||
|
|
20d03053e7 | ||
|
|
c2890e7a43 | ||
|
|
304d691e1c | ||
|
|
2de21a64d9 | ||
|
|
f44adad3ec | ||
|
|
25552f7994 | ||
|
|
a1de9c2138 | ||
|
|
182f631936 | ||
|
|
c2698b4edb | ||
|
|
0e9498009b | ||
|
|
a37992c381 | ||
|
|
088d97784f | ||
|
|
e2de49ad79 | ||
|
|
0c66798762 | ||
|
|
f0ea373b47 | ||
|
|
6f1f48c18f | ||
|
|
91a0406d44 | ||
|
|
e58ae853cf | ||
|
|
7d679359d3 | ||
|
|
0b645e66e5 | ||
|
|
07c5e8fd03 | ||
|
|
a5341c61df | ||
|
|
77f492475f | ||
|
|
667fc66397 | ||
|
|
e270dbc951 | ||
|
|
ddef66bba2 | ||
|
|
7c4b40d626 | ||
|
|
35df0c14ae | ||
|
|
a9e0b1288a | ||
|
|
848d7d4894 | ||
|
|
0d96759e97 | ||
|
|
53d83b5aac | ||
|
|
8cbbd1153c | ||
|
|
f41aecd0eb | ||
|
|
f21e987ab0 | ||
|
|
a05c31b4de | ||
|
|
f3a0d7c069 | ||
|
|
7bfe22fe10 | ||
|
|
59ebfd3d6c | ||
|
|
0787595f98 | ||
|
|
bd621067b5 | ||
|
|
01ae389264 | ||
|
|
84700cfc2f | ||
|
|
b68f609a44 | ||
|
|
703e198780 | ||
|
|
4f75ef8709 | ||
|
|
f87b2248b2 | ||
|
|
bf65d419b6 | ||
|
|
267df53691 | ||
|
|
6c38a9048d | ||
|
|
7ec7098849 | ||
|
|
040ea45b88 | ||
|
|
583750fc35 | ||
|
|
bb6f7c4913 | ||
|
|
c9c6ab4d58 | ||
|
|
7f726f48eb | ||
|
|
7c9b52d4a6 | ||
|
|
7577374e4b | ||
|
|
c07a56dee3 | ||
|
|
f61be573e6 | ||
|
|
e44d367ee7 | ||
|
|
6dd9ac452c | ||
|
|
349584eb16 | ||
|
|
ae8fb326a9 | ||
|
|
599579ff59 | ||
|
|
022684b8dd | ||
|
|
3410480b67 | ||
|
|
3087f133a5 | ||
|
|
01a115c3d0 | ||
|
|
af5da7fe44 | ||
|
|
9022e16d0a | ||
|
|
52b9c5f408 | ||
|
|
c9c32a2d96 | ||
|
|
d720ce3dc4 | ||
|
|
adddf74c48 | ||
|
|
955a4dccb7 | ||
|
|
174f6f42b9 | ||
|
|
95935fc7c1 | ||
|
|
ed66b5e603 | ||
|
|
4805c8abbf | ||
|
|
77d6b7463b | ||
|
|
82dd6c7e79 | ||
|
|
05362e98a7 | ||
|
|
d6f5dd9540 | ||
|
|
b094f8e3c9 | ||
|
|
e06cbc719c | ||
|
|
fc0c7ac4df | ||
|
|
999c95694b | ||
|
|
c856a65b13 | ||
|
|
dc6d5bad8c | ||
|
|
3da53cc323 | ||
|
|
e4eaaeb2be | ||
|
|
76e4a05ce0 | ||
|
|
e01c6d4c69 | ||
|
|
98e1f58819 | ||
|
|
eb3b7c6fe9 | ||
|
|
874252dbe6 | ||
|
|
05e79f0e90 | ||
|
|
d119336f9c | ||
|
|
04b873aa37 | ||
|
|
3e0596535f | ||
|
|
fcaf430775 | ||
|
|
33449562cb | ||
|
|
7fb5f713dd |
No files matched your search
@@ -0,0 +1,31 @@
|
||||
version: 2.1
|
||||
orbs:
|
||||
node: circleci/node@5.0.2
|
||||
jobs:
|
||||
build:
|
||||
docker:
|
||||
- image: 'cimg/node:16.15.0'
|
||||
steps:
|
||||
- node/install
|
||||
- checkout
|
||||
- run:
|
||||
name: Print the node version
|
||||
command: node -v
|
||||
- run:
|
||||
name: Install pnpm
|
||||
command: npm i -g pnpm@7.1.2
|
||||
- run:
|
||||
name: Install Dependencies
|
||||
command: pnpm install --frozen-lockfile
|
||||
- run:
|
||||
name: Build Artalk
|
||||
command: pnpm build:all
|
||||
|
||||
workflows:
|
||||
tests:
|
||||
jobs:
|
||||
- build:
|
||||
filters:
|
||||
branches:
|
||||
ignore:
|
||||
- gh-pages
|
||||
@@ -1,6 +1,7 @@
|
||||
module.exports = {
|
||||
root: true,
|
||||
parser: "@typescript-eslint/parser",
|
||||
env: { "browser": true} ,
|
||||
parserOptions: {
|
||||
project: ['./packages/*/tsconfig.json'],
|
||||
tsconfigRootDir: __dirname,
|
||||
@@ -11,9 +12,11 @@ module.exports = {
|
||||
'prettier',
|
||||
'plugin:import/recommended',
|
||||
'plugin:import/typescript',
|
||||
"plugin:compat/recommended",
|
||||
],
|
||||
plugins: ['@typescript-eslint', 'import'],
|
||||
rules: {
|
||||
'no-alert': 'off',
|
||||
'no-unused-vars': 'off',
|
||||
'no-plusplus': 0,
|
||||
'no-param-reassign': 0,
|
||||
@@ -34,5 +37,8 @@ module.exports = {
|
||||
"project": [__dirname + "/packages/*/tsconfig.json"]
|
||||
},
|
||||
},
|
||||
'polyfills': [
|
||||
'AbortController'
|
||||
]
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"extends": ["config:base", "schedule:weekly"],
|
||||
"branchPrefix": "chore/",
|
||||
"labels": ["dependencies"],
|
||||
"rangeStrategy": "bump",
|
||||
"reviewers": [
|
||||
"qwqcode",
|
||||
"kecrily"
|
||||
]
|
||||
}
|
||||
@@ -15,20 +15,26 @@ jobs:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Set node version to 12.x
|
||||
uses: actions/setup-node@v2
|
||||
- name: Use pnpm
|
||||
uses: pnpm/action-setup@v2.2.1
|
||||
with:
|
||||
node-version: '12.x'
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
version: 7.1.2
|
||||
|
||||
- name: Set node version to 16.x
|
||||
uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: 16.x
|
||||
registry-url: https://registry.npmjs.org/
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Install dependencies
|
||||
run: yarn install
|
||||
run: pnpm install
|
||||
|
||||
- name: Build
|
||||
run: yarn build
|
||||
run: pnpm build
|
||||
|
||||
- name: Publish
|
||||
run: cd packages/artalk && yarn publish
|
||||
run: cd packages/artalk && pnpm publish --no-git-checks
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
|
||||
@@ -52,7 +58,7 @@ jobs:
|
||||
run: echo ::set-output name=VERSION::${GITHUB_REF/refs\/tags\/v/}
|
||||
|
||||
- name: Checkout ArtalkDocs
|
||||
uses: actions/checkout@v2
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
repository: ArtalkJS/Docs
|
||||
token: ${{ secrets.PAT }}
|
||||
@@ -60,6 +66,7 @@ jobs:
|
||||
- name: Update CDN links
|
||||
run: |
|
||||
sed -i 's#artalk@.[^/]*#artalk@${{ steps.get_version.outputs.VERSION }}#g' docs/code/ArtalkCDN.json
|
||||
perl -pi -e 's#"Artalk"(\W+)?:(\W+)?".*?"#"Artalk": "${{ steps.get_version.outputs.VERSION }}"#g' docs/code/ArtalkVersion.json
|
||||
sed -i 's#artalk@.[^/]*#artalk@${{ steps.get_version.outputs.VERSION }}#g' docs/code/quick-start/cdn.html
|
||||
|
||||
- uses: stefanzweifel/git-auto-commit-action@v4
|
||||
|
||||
@@ -11,18 +11,25 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v2
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Setup
|
||||
uses: actions/setup-node@v1
|
||||
- name: Use pnpm
|
||||
uses: pnpm/action-setup@v2.2.1
|
||||
with:
|
||||
node-version: '12.x'
|
||||
version: 7.1.2
|
||||
|
||||
- name: Install
|
||||
run: yarn install
|
||||
- name: Set node version to 16.x
|
||||
uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: 16.x
|
||||
registry-url: https://registry.npmjs.org/
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install
|
||||
|
||||
- name: Build
|
||||
run: cd packages/artalk && yarn predeploy
|
||||
run: cd packages/artalk && pnpm predeploy
|
||||
|
||||
- name: Deploy
|
||||
uses: peaceiris/actions-gh-pages@v3
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
.DS_Store
|
||||
node_modules/
|
||||
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
.pnpm-debug.log*
|
||||
|
||||
# Editor directories and files
|
||||
.idea
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
.DS_Store
|
||||
node_modules/
|
||||
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
.pnpm-debug.log*
|
||||
|
||||
.idea
|
||||
.vscode
|
||||
|
||||
+9
-4
@@ -4,10 +4,15 @@ node_js:
|
||||
- lts/*
|
||||
|
||||
script:
|
||||
- yarn run lint
|
||||
- yarn run build
|
||||
- pnpm run lint
|
||||
- pnpm run build
|
||||
|
||||
cache:
|
||||
yarn: true
|
||||
npm: false
|
||||
directories:
|
||||
- node_modules
|
||||
- "~/.pnpm-store"
|
||||
before_install:
|
||||
- curl -f https://get.pnpm.io/v6.16.js | node - add --global pnpm@7.1.2
|
||||
- pnpm config set store-dir ~/.pnpm-store
|
||||
install:
|
||||
- pnpm install
|
||||
@@ -1,674 +1,165 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is 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. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
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.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
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 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. Use with the GNU Affero General Public License.
|
||||
|
||||
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 Affero 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 special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU 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 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 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 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 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 General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
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 GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
|
||||
This version of the GNU Lesser General Public License incorporates
|
||||
the terms and conditions of version 3 of the GNU General Public
|
||||
License, supplemented by the additional permissions listed below.
|
||||
|
||||
0. Additional Definitions.
|
||||
|
||||
As used herein, "this License" refers to version 3 of the GNU Lesser
|
||||
General Public License, and the "GNU GPL" refers to version 3 of the GNU
|
||||
General Public License.
|
||||
|
||||
"The Library" refers to a covered work governed by this License,
|
||||
other than an Application or a Combined Work as defined below.
|
||||
|
||||
An "Application" is any work that makes use of an interface provided
|
||||
by the Library, but which is not otherwise based on the Library.
|
||||
Defining a subclass of a class defined by the Library is deemed a mode
|
||||
of using an interface provided by the Library.
|
||||
|
||||
A "Combined Work" is a work produced by combining or linking an
|
||||
Application with the Library. The particular version of the Library
|
||||
with which the Combined Work was made is also called the "Linked
|
||||
Version".
|
||||
|
||||
The "Minimal Corresponding Source" for a Combined Work means the
|
||||
Corresponding Source for the Combined Work, excluding any source code
|
||||
for portions of the Combined Work that, considered in isolation, are
|
||||
based on the Application, and not on the Linked Version.
|
||||
|
||||
The "Corresponding Application Code" for a Combined Work means the
|
||||
object code and/or source code for the Application, including any data
|
||||
and utility programs needed for reproducing the Combined Work from the
|
||||
Application, but excluding the System Libraries of the Combined Work.
|
||||
|
||||
1. Exception to Section 3 of the GNU GPL.
|
||||
|
||||
You may convey a covered work under sections 3 and 4 of this License
|
||||
without being bound by section 3 of the GNU GPL.
|
||||
|
||||
2. Conveying Modified Versions.
|
||||
|
||||
If you modify a copy of the Library, and, in your modifications, a
|
||||
facility refers to a function or data to be supplied by an Application
|
||||
that uses the facility (other than as an argument passed when the
|
||||
facility is invoked), then you may convey a copy of the modified
|
||||
version:
|
||||
|
||||
a) under this License, provided that you make a good faith effort to
|
||||
ensure that, in the event an Application does not supply the
|
||||
function or data, the facility still operates, and performs
|
||||
whatever part of its purpose remains meaningful, or
|
||||
|
||||
b) under the GNU GPL, with none of the additional permissions of
|
||||
this License applicable to that copy.
|
||||
|
||||
3. Object Code Incorporating Material from Library Header Files.
|
||||
|
||||
The object code form of an Application may incorporate material from
|
||||
a header file that is part of the Library. You may convey such object
|
||||
code under terms of your choice, provided that, if the incorporated
|
||||
material is not limited to numerical parameters, data structure
|
||||
layouts and accessors, or small macros, inline functions and templates
|
||||
(ten or fewer lines in length), you do both of the following:
|
||||
|
||||
a) Give prominent notice with each copy of the object code that the
|
||||
Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
|
||||
b) Accompany the object code with a copy of the GNU GPL and this license
|
||||
document.
|
||||
|
||||
4. Combined Works.
|
||||
|
||||
You may convey a Combined Work under terms of your choice that,
|
||||
taken together, effectively do not restrict modification of the
|
||||
portions of the Library contained in the Combined Work and reverse
|
||||
engineering for debugging such modifications, if you also do each of
|
||||
the following:
|
||||
|
||||
a) Give prominent notice with each copy of the Combined Work that
|
||||
the Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
|
||||
b) Accompany the Combined Work with a copy of the GNU GPL and this license
|
||||
document.
|
||||
|
||||
c) For a Combined Work that displays copyright notices during
|
||||
execution, include the copyright notice for the Library among
|
||||
these notices, as well as a reference directing the user to the
|
||||
copies of the GNU GPL and this license document.
|
||||
|
||||
d) Do one of the following:
|
||||
|
||||
0) Convey the Minimal Corresponding Source under the terms of this
|
||||
License, and the Corresponding Application Code in a form
|
||||
suitable for, and under terms that permit, the user to
|
||||
recombine or relink the Application with a modified version of
|
||||
the Linked Version to produce a modified Combined Work, in the
|
||||
manner specified by section 6 of the GNU GPL for conveying
|
||||
Corresponding Source.
|
||||
|
||||
1) Use a suitable shared library mechanism for linking with the
|
||||
Library. A suitable mechanism is one that (a) uses at run time
|
||||
a copy of the Library already present on the user's computer
|
||||
system, and (b) will operate properly with a modified version
|
||||
of the Library that is interface-compatible with the Linked
|
||||
Version.
|
||||
|
||||
e) Provide Installation Information, but only if you would otherwise
|
||||
be required to provide such information under section 6 of the
|
||||
GNU GPL, and only to the extent that such information is
|
||||
necessary to install and execute a modified version of the
|
||||
Combined Work produced by recombining or relinking the
|
||||
Application with a modified version of the Linked Version. (If
|
||||
you use option 4d0, the Installation Information must accompany
|
||||
the Minimal Corresponding Source and Corresponding Application
|
||||
Code. If you use option 4d1, you must provide the Installation
|
||||
Information in the manner specified by section 6 of the GNU GPL
|
||||
for conveying Corresponding Source.)
|
||||
|
||||
5. Combined Libraries.
|
||||
|
||||
You may place library facilities that are a work based on the
|
||||
Library side by side in a single library together with other library
|
||||
facilities that are not Applications and are not covered by this
|
||||
License, and convey such a combined library under terms of your
|
||||
choice, if you do both of the following:
|
||||
|
||||
a) Accompany the combined library with a copy of the same work based
|
||||
on the Library, uncombined with any other library facilities,
|
||||
conveyed under the terms of this License.
|
||||
|
||||
b) Give prominent notice with the combined library that part of it
|
||||
is a work based on the Library, and explaining where to find the
|
||||
accompanying uncombined form of the same work.
|
||||
|
||||
6. Revised Versions of the GNU Lesser General Public License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions
|
||||
of the GNU Lesser 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
|
||||
Library as you received it specifies that a certain numbered version
|
||||
of the GNU Lesser General Public License "or any later version"
|
||||
applies to it, you have the option of following the terms and
|
||||
conditions either of that published version or of any later version
|
||||
published by the Free Software Foundation. If the Library as you
|
||||
received it does not specify a version number of the GNU Lesser
|
||||
General Public License, you may choose any version of the GNU Lesser
|
||||
General Public License ever published by the Free Software Foundation.
|
||||
|
||||
If the Library as you received it specifies that a proxy can decide
|
||||
whether future versions of the GNU Lesser General Public License shall
|
||||
apply, that proxy's public statement of acceptance of any version is
|
||||
permanent authorization for you to choose that version for the
|
||||
Library.
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
<p align="center">
|
||||
<img src="https://user-images.githubusercontent.com/22412567/137740516-d9e97af0-fb3b-4dab-b331-671a9a2a3a63.png" alt="Artalk" width="100%">
|
||||
</p>
|
||||
|
||||
# Artalk
|
||||
|
||||
[](https://www.npmjs.com/package/artalk)
|
||||
[](https://www.npmjs.com/package/artalk)
|
||||
[](https://bundlephobia.com/package/artalk)
|
||||
[](https://circleci.com/gh/ArtalkJS/Artalk/tree/master)
|
||||
|
||||
> 🌌 A Self-hosted comment system
|
||||
|
||||
[简体中文](./README.md) / [Documentation](https://artalk.js.org) / [Releases](https://github.com/ArtalkJS/ArtalkGo/releases) / [ArtalkGo](https://github.com/ArtalkJS/ArtalkGo)
|
||||
|
||||
---
|
||||
|
||||
- 🍃 Lightweight (~30kB)
|
||||
- 👨👧👦 Secure (Self-hosted)
|
||||
- 🐳 Easy to use (Very Easy)
|
||||
- 🍱 Golang backend (Fast and Cross Platform)
|
||||
- 🌊 TypeScript × Vanilla × Vite (No Dependencies)
|
||||
|
||||
## Features
|
||||
|
||||
- Sidebar: Multi-site centralized management
|
||||
- Notification Center: Red badge alert / Mark as read
|
||||
- Verification: User Verification Badge / Password access
|
||||
- Moderation: Anti-spam detection / Captcha frequency limit
|
||||
- Emoticons: Insert emoji / Quickly import presets
|
||||
- Email Notify: Template customization / Send to multi-admin
|
||||
- Site Isolation: Multi-site management / Admin assignment
|
||||
- Page Management: Provide page title / Easy to look up
|
||||
- Image Upload: Upload to localhost / various remote image host
|
||||
- Private Space Mode: Only visible to yourself / Message board
|
||||
- Multiple Msg Pushers: Support Telegram / Slack / LINE
|
||||
- Nested Comments: Switchable to Flat Mode
|
||||
- Comment Vote: For or against comments
|
||||
- Comment Sort: Sort by popularity or time
|
||||
- Comment PIN: Pin important comments
|
||||
- Track only author: Show only author's comments
|
||||
- Asynchronous: Send comments without waiting
|
||||
- Infinite Scrolling: Provide various comment content pagination custom
|
||||
- AutoSave: A anti-lost editor
|
||||
- AutoFill: Autofill user profile
|
||||
- Preview: Real-time preview of markdown
|
||||
- Dark Mode: Prevents eye disease damage
|
||||
- Collapse Comment: I do not want you to see this comment
|
||||
- Data Backup: Prevent comment data loss
|
||||
- Data Migration: Switch back and forth between different commenting systems
|
||||
- Multiple comments on one page: Multiple comment areas on one page (seems useless
|
||||
- Markdown: Markdown syntax was supported by default
|
||||
- LaTex support: Import KaTex plugin to integrate LaTex parser for artalk
|
||||
- Using [Vite](https://github.com/vitejs/vite): The ultimate developer experience
|
||||
|
||||
## Getting Started
|
||||
|
||||
Reference to:[**Documentation**](https://artalk.js.org/guide/deploy.html)
|
||||
|
||||
```sh
|
||||
$ pnpm add artalk
|
||||
```
|
||||
|
||||
```ts
|
||||
import Artalk from 'artalk'
|
||||
|
||||
new Artalk({
|
||||
el: '#Comments',
|
||||
pageKey: 'http://your_domain/post/1', // Page Link
|
||||
pageTitle: 'The title of your page', // Page Title
|
||||
server: 'http://localhost:8080/api', // Server URL
|
||||
site: 'Site Name',
|
||||
i18n: 'en-US'
|
||||
})
|
||||
```
|
||||
|
||||
### Docker
|
||||
|
||||
```sh
|
||||
# Create a directory for Artalk
|
||||
mkdir Artalk
|
||||
cd Artalk
|
||||
|
||||
# Download config template
|
||||
curl -L https://raw.githubusercontent.com/ArtalkJS/ArtalkGo/master/artalk-go.example.yml > conf.yml
|
||||
|
||||
docker run -d \
|
||||
--name artalk \
|
||||
-p 0.0.0.0:8080:23366 \
|
||||
-v $(pwd)/conf.yml:/conf.yml \
|
||||
-v $(pwd)/data:/data \
|
||||
artalk/artalk-go
|
||||
```
|
||||
|
||||
### Docker Compose
|
||||
|
||||
```sh
|
||||
mkdir Artalk
|
||||
cd Artalk
|
||||
|
||||
vim docker-compose.yaml
|
||||
```
|
||||
|
||||
```yaml
|
||||
version: "3.5"
|
||||
services:
|
||||
artalk:
|
||||
container_name: artalk
|
||||
image: artalk/artalk-go
|
||||
ports:
|
||||
- 8080:23366
|
||||
volumes:
|
||||
- ./conf.yml:/conf.yml
|
||||
- ./data:/data
|
||||
```
|
||||
|
||||
```sh
|
||||
docker-compose up -d
|
||||
```
|
||||
|
||||
## Contributors
|
||||
|
||||
[](https://github.com/ArtalkJS/Artalk/graphs/contributors)
|
||||
|
||||
## Supporters
|
||||
|
||||
[](https://github.com/ArtalkJS/Artalk/stargazers)
|
||||
|
||||
## Feedback
|
||||
|
||||
Thanks for the help and feedback provided by the community, if you have good suggestions or comments, please go to [issues](https://github.com/ArtalkJS/Artalk/issues) to let us know at any time.
|
||||
|
||||
## Stargazers over time
|
||||
|
||||
[](https://starchart.cc/ArtalkJS/Artalk)
|
||||
|
||||
## License
|
||||
|
||||
[LGPL-3.0](./LICENSE)
|
||||
|
||||
[](https://app.fossa.com/projects/git%2Bgithub.com%2FArtalkJS%2FArtalk?ref=badge_shield)
|
||||
|
||||
[](https://app.fossa.com/projects/git%2Bgithub.com%2FArtalkJS%2FArtalk?ref=badge_large)
|
||||
@@ -6,54 +6,59 @@
|
||||
|
||||
[](https://www.npmjs.com/package/artalk)
|
||||
[](https://www.npmjs.com/package/artalk)
|
||||
[](https://github.com/ArtalkJS/Artalk/commits/master)
|
||||
[](https://github.com/ArtalkJS/Artalk/issues)
|
||||
[](https://github.com/ArtalkJS/Artalk/pulls)
|
||||
[](https://travis-ci.com/ArtalkJS/Artalk)
|
||||
[](./LICENSE)
|
||||
[](https://bundlephobia.com/package/artalk)
|
||||
[](https://circleci.com/gh/ArtalkJS/Artalk/tree/master)
|
||||
|
||||
> 🌌 一款简洁的自托管评论系统 | A Selfhosted Comment System.
|
||||
> 🌌 Golang 自托管评论系统
|
||||
|
||||
前往:[“**官方文档**”](https://artalk.js.org)
|
||||
[English](./README.en.md) / [官方文档](https://artalk.js.org) / [最新后端](https://github.com/ArtalkJS/ArtalkGo/releases) / [ArtalkGo](https://github.com/ArtalkJS/ArtalkGo)
|
||||
|
||||
---
|
||||
|
||||
- 轻量 (~30kB gzipped)
|
||||
- 自托管 (隐私安全)
|
||||
- 简单易上手 (防秃顶)
|
||||
- Markdown 语法 (通用性)
|
||||
- Golang 后端 (易部署 / 跨平台)
|
||||
- 🍃 轻量 (~30kB)
|
||||
- 👨👧👦 安全 (自托管)
|
||||
- 🐳 易上手 (防秃顶)
|
||||
- 🍱 Golang 后端 (快速 / 跨平台)
|
||||
- 🌊 TypeScript × Vanilla × Vite (纯天然 / 无依赖)
|
||||
|
||||
## 特性
|
||||
|
||||
- 表 情 包 :统一管理 / 链接替换
|
||||
- 通知中心:红点标记 / 已读记录
|
||||
- 侧 边 栏 :多站点集中化管理
|
||||
- 通知中心:红点的标记 / 已读记录
|
||||
- 身份验证:徽标自定义 / 密码验证
|
||||
- 站点隔离:多站点管理 / 站点管理员用户分配
|
||||
- 评论审核:反垃圾检测 / 验证码 / 提交频率限制
|
||||
- 评论审核:反垃圾检测 / 验证码频率限制
|
||||
- 表情符号:插入表情包 / 快速导入表情包
|
||||
- 邮件提醒:模版自定义 / 多管理员通知
|
||||
- 树洞模式:仅自己可见 / 说说功能
|
||||
- 站点隔离:多站点管理 / 管理员分配
|
||||
- 页面管理:标题可显示 / 快速跳转
|
||||
- 无限层级:可切换为 “平铺模式”
|
||||
- 图片上传:上传到本地 / 多种图床
|
||||
- 树洞模式:仅自己可见 / 说说功能
|
||||
- 多元推送:支持钉钉飞书 TG
|
||||
- 无限层级:可切换为平铺模式
|
||||
- 评论投票:赞同还是反对评论
|
||||
- 异步处理:邮件发送无需等待
|
||||
- 评论排序:按热度或时间排序
|
||||
- 评论置顶:重要消息置顶显示
|
||||
- 只看作者:仅显示作者的评论
|
||||
- 异步处理:发送评论无需等待
|
||||
- 滚动加载:评论内容分页处置
|
||||
- 自动保存:用户输入防丢功能
|
||||
- 自动填充:用户链接自动填充
|
||||
- 实时预览:评论内容实时预览
|
||||
- 暗黑模式:防止眼部疾病伤害
|
||||
- 评论折叠:这个不打算给你康
|
||||
- 数据备份:防止评论数据丢失
|
||||
- 数据迁移:在不同评论系统之间来回切换
|
||||
- 一页多评:一页多个评论区(似乎没啥用
|
||||
- TypeScript & Vanilla:纯天然无添加 / 无需依赖
|
||||
- [Vite](https://github.com/vitejs/vite):开发者的极致体验
|
||||
- Markdown:语法默认支持
|
||||
- 支持 Latex:引入 Artalk 的 Katex 插件
|
||||
- 使用 [Vite](https://github.com/vitejs/vite):开发者的极致体验
|
||||
|
||||
## 食用方针
|
||||
|
||||
前往:[“**文档 · 部署**”](https://artalk.js.org/guide/deploy.html)
|
||||
|
||||
```sh
|
||||
$ yarn add artalk
|
||||
$ pnpm add artalk
|
||||
```
|
||||
|
||||
```ts
|
||||
@@ -61,13 +66,157 @@ import Artalk from 'artalk'
|
||||
|
||||
new Artalk({
|
||||
el: '#Comments',
|
||||
pageKey: '<页面链接>',
|
||||
pageTitle: '<页面标题>',
|
||||
server: '<后端地址>',
|
||||
site: '<站点名称>',
|
||||
pageKey: 'http://your_domain/post/1', // 页面链接
|
||||
pageTitle: '关于如何引入 Artalk 这档子事', // 页面标题
|
||||
server: 'http://localhost:8080/api', // 后端地址
|
||||
site: 'Artalk 的博客 (你的站点名)',
|
||||
})
|
||||
```
|
||||
|
||||
### Docker
|
||||
|
||||
```sh
|
||||
# 为 Artalk 创建一个目录
|
||||
mkdir Artalk
|
||||
cd Artalk
|
||||
|
||||
# 下载配置文件模版
|
||||
curl -L https://raw.githubusercontent.com/ArtalkJS/ArtalkGo/master/artalk-go.example.yml > conf.yml
|
||||
|
||||
docker run -d \
|
||||
--name artalk \
|
||||
-p 0.0.0.0:8080:23366 \
|
||||
-v $(pwd)/conf.yml:/conf.yml \
|
||||
-v $(pwd)/data:/data \
|
||||
artalk/artalk-go
|
||||
```
|
||||
|
||||
### Docker Compose
|
||||
|
||||
```sh
|
||||
mkdir Artalk
|
||||
cd Artalk
|
||||
|
||||
vim docker-compose.yaml
|
||||
```
|
||||
|
||||
```yaml
|
||||
version: "3.5"
|
||||
services:
|
||||
artalk:
|
||||
container_name: artalk
|
||||
image: artalk/artalk-go
|
||||
ports:
|
||||
- 8080:23366
|
||||
volumes:
|
||||
- ./conf.yml:/conf.yml
|
||||
- ./data:/data
|
||||
```
|
||||
|
||||
```sh
|
||||
docker-compose up -d
|
||||
```
|
||||
|
||||
## Contributors
|
||||
|
||||
[](https://github.com/ArtalkJS/Artalk/graphs/contributors)
|
||||
|
||||
## Supporters
|
||||
|
||||
[](https://github.com/ArtalkJS/Artalk/stargazers)
|
||||
|
||||
## TODOs
|
||||
|
||||
- [x] [Golang 后端](https://github.com/ArtalkJS/ArtalkGo)
|
||||
- [x] 多数据库支持
|
||||
- [x] SQLite
|
||||
- [x] MySQL
|
||||
- [x] Postgres
|
||||
- [x] SQLServer
|
||||
- [x] 多缓存支持
|
||||
- [x] In-memory (内建缓存)
|
||||
- [x] Redis
|
||||
- [x] Memcache
|
||||
- [x] 多站点支持
|
||||
- [x] 评论获取分页
|
||||
- [x] 评论点赞投票
|
||||
- [x] 浏览量统计
|
||||
- [x] 评论分页加载
|
||||
- [x] 评论置顶 / 精华
|
||||
- [x] 评论排序 (热度 / 时间)
|
||||
- [x] 通知中心
|
||||
- [x] 提及
|
||||
- [x] 全部
|
||||
- [x] 我的
|
||||
- [x] 待审
|
||||
- [x] 管理员控制台
|
||||
- [x] 评论 (增/删/改)
|
||||
- [x] 页面 (增/删/改)
|
||||
- [x] 站点 (增/删/改)
|
||||
- [x] 数据分页
|
||||
- [ ] 配置 (GUI)
|
||||
- [x] 数据导入 ([Artransfer](https://artalk.js.org/guide/transfer.html))
|
||||
- [x] Artrans
|
||||
- [x] WordPress
|
||||
- [x] Typecho ([插件](https://github.com/ArtalkJS/Artrans-Typecho) / [Artransfer-CLI](https://github.com/ArtalkJS/Artransfer-CLI))
|
||||
- [x] Valine
|
||||
- [x] Disqus
|
||||
- [x] Commento
|
||||
- [x] Waline ([Artransfer-CLI](https://github.com/ArtalkJS/Artransfer-CLI))
|
||||
- [x] Twikoo
|
||||
- [x] Artalk v1 (PHP)
|
||||
- [x] 数据导出
|
||||
- [ ] 数据备份同步
|
||||
- [x] 邮件异步队列发送
|
||||
- [ ] 邮件队列持久化
|
||||
- [x] 邮件多种发送方式
|
||||
- [x] SMTP
|
||||
- [x] 阿里云邮件
|
||||
- [x] 系统调用 sendmail
|
||||
- [x] 邮件多模板自定义
|
||||
- [x] 用户已读标记
|
||||
- [x] 验证码
|
||||
- [x] 图片验证码
|
||||
- [x] [极验](https://www.geetest.com/)滑动验证码
|
||||
- [x] 反垃圾
|
||||
- [x] [Akismet](https://akismet.com/)
|
||||
- [x] [阿里云内容安全](https://help.aliyun.com/document_detail/28417.html)
|
||||
- [x] [腾讯云内容安全](https://cloud.tencent.com/document/product/1124/64508)
|
||||
- [x] 关键字过滤
|
||||
- [x] 评论通知管理员 ([notify](https://github.com/nikoksr/notify))
|
||||
- [x] Telegram Bot
|
||||
- [x] 飞书 WebHook Bot
|
||||
- [x] 钉钉
|
||||
- [x] Bark
|
||||
- [x] Slack
|
||||
- [x] LINE
|
||||
- [ ] 自定义 HTTP 回调
|
||||
- [ ] 命令行管理
|
||||
- [ ] 博客邮件订阅
|
||||
- [x] 用户鉴权机制
|
||||
- [x] 跨域非法请求阻止
|
||||
- [x] 全局验证码操作次数限制
|
||||
- [x] JWT 登陆状态验证
|
||||
- [x] 时区自定义
|
||||
- [x] 只看作者功能
|
||||
- [ ] AT 提及 (@)
|
||||
- [ ] 评论提及 (#)
|
||||
- [ ] 表情包统一管理
|
||||
- [ ] 导入表情包
|
||||
- [ ] 表情包图片地址控制
|
||||
- [x] 图片上传
|
||||
- [x] 图片上传到图床 ([upgit](https://github.com/pluveto/upgit))
|
||||
- [ ] 图片管理
|
||||
- [ ] 附件上传 / 管理
|
||||
- [ ] 评论标签分类系统
|
||||
- [ ] 主题样式更换
|
||||
- [ ] 规范化 API
|
||||
- [ ] 扩展中心
|
||||
- [ ] 开放用户注册
|
||||
- [ ] 接入第三方登录
|
||||
- [ ] 国际化 (i18n)
|
||||
- [x] 一键升级
|
||||
|
||||
## 特别致谢
|
||||
|
||||
感谢社区提供的帮助与反馈,若有好的建议与意见欢迎前往 [ISSUES](https://github.com/ArtalkJS/Artalk/issues) 随时告知。
|
||||
@@ -77,7 +226,8 @@ new Artalk({
|
||||
[](https://starchart.cc/ArtalkJS/Artalk)
|
||||
|
||||
## License
|
||||
[GPL-3.0](./LICENSE)
|
||||
|
||||
[LGPL-3.0](./LICENSE)
|
||||
|
||||
[](https://app.fossa.com/projects/git%2Bgithub.com%2FArtalkJS%2FArtalk?ref=badge_shield)
|
||||
|
||||
|
||||
+26
-23
@@ -1,33 +1,36 @@
|
||||
{
|
||||
"name": "artalk-monorepo",
|
||||
"private": true,
|
||||
"workspaces": [
|
||||
"packages/*"
|
||||
],
|
||||
"homepage": "https://artalk.js.org",
|
||||
"scripts": {
|
||||
"build": "yarn --cwd packages/artalk run build",
|
||||
"dev": "yarn --cwd packages/artalk run dev",
|
||||
"build:sidebar": "yarn run build && yarn --cwd packages/artalk-sidebar run build",
|
||||
"build:all": "yarn --cwd packages/artalk run build && yarn --cwd packages/artalk-sidebar run build"
|
||||
"dev": "pnpm -F artalk dev",
|
||||
"dev:sidebar": "pnpm -F @artalkjs/artalk-sidebar dev",
|
||||
"build": "pnpm -F artalk build",
|
||||
"build:sidebar": "pnpm -F @artalkjs/artalk-sidebar build",
|
||||
"build:all": "pnpm build && pnpm build:sidebar"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@rollup/plugin-dynamic-import-vars": "^1.4.1",
|
||||
"@types/node": "^16.11.7",
|
||||
"@typescript-eslint/eslint-plugin": "^5.4.0",
|
||||
"@typescript-eslint/parser": "^5.4.0",
|
||||
"autoprefixer": "^10.4.0",
|
||||
"eslint": "^8.2.0",
|
||||
"@rollup/plugin-dynamic-import-vars": "1.4.3",
|
||||
"@types/node": "16.11.36",
|
||||
"@typescript-eslint/eslint-plugin": "5.25.0",
|
||||
"@typescript-eslint/parser": "5.25.0",
|
||||
"autoprefixer": "10.4.7",
|
||||
"eslint": "8.16.0",
|
||||
"eslint-config-airbnb-base": "15.0.0",
|
||||
"eslint-config-airbnb-typescript": "^16.0.0",
|
||||
"eslint-config-prettier": "^8.3.0",
|
||||
"eslint-import-resolver-typescript": "^2.5.0",
|
||||
"eslint-plugin-import": "^2.25.2",
|
||||
"less": "^4.1.2",
|
||||
"prettier": "^2.4.1",
|
||||
"typescript": "^4.5.2",
|
||||
"vite": "^2.6.14",
|
||||
"vite-tsconfig-paths": "^3.3.17"
|
||||
"eslint-config-airbnb-typescript": "17.0.0",
|
||||
"eslint-config-prettier": "8.5.0",
|
||||
"eslint-import-resolver-typescript": "2.7.1",
|
||||
"eslint-plugin-compat": "4.0.2",
|
||||
"eslint-plugin-import": "2.26.0",
|
||||
"less": "4.1.2",
|
||||
"postcss": "8.4.14",
|
||||
"prettier": "2.6.2",
|
||||
"rollup": "2.74.1",
|
||||
"typescript": "4.6.4",
|
||||
"vite": "2.9.9",
|
||||
"vite-tsconfig-paths": "3.4.1"
|
||||
},
|
||||
"dependencies": {}
|
||||
"browserslist": [
|
||||
"supports es6 and supports es6-class and supports es6-generators and supports es6-module-dynamic-import and supports es6-module and supports es6-number and supports es6-string-includes"
|
||||
]
|
||||
}
|
||||
@@ -9,6 +9,23 @@
|
||||
<body>
|
||||
<div id="ArtalkSidebar"></div>
|
||||
|
||||
<script type="module" src="./src/index.ts"></script>
|
||||
<script type="module">
|
||||
import InitSidebar from './src/main'
|
||||
|
||||
const p = new URLSearchParams(document.location.search)
|
||||
const pageKey = p.get('pageKey') || ''
|
||||
const site = p.get('site') || ''
|
||||
const user = JSON.parse(p.get('user') || '{}')
|
||||
const view = p.get('view') || ''
|
||||
const darkMode = p.get('darkMode') === '1'
|
||||
|
||||
InitSidebar({
|
||||
el: '#ArtalkSidebar',
|
||||
server: (import.meta.env.DEV) ? 'http://localhost:23366' : '../',
|
||||
pageKey,
|
||||
site,
|
||||
darkMode,
|
||||
}, user, view)
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@artalkjs/artalk-sidebar",
|
||||
"version": "0.1.0",
|
||||
"license": "GPL-2.0",
|
||||
"version": "0.2.0",
|
||||
"license": "LGPL-3.0",
|
||||
"description": "The sidebar of artalk",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@@ -10,26 +10,13 @@
|
||||
},
|
||||
"homepage": "https://artalk.js.org",
|
||||
"bugs": "https://github.com/ArtalkJS/Artalk/issue",
|
||||
"main": "./dist/ArtalkSidebar.js",
|
||||
"unpkg": "./dist/ArtalkSidebar.iife.js",
|
||||
"jsdelivr": "./dist/ArtalkSidebar.iife.js",
|
||||
"module": "./dist/ArtalkSidebar.es.js",
|
||||
"types": "./types/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"import": "./dist/ArtalkSidebar.es.js",
|
||||
"require": "./dist/ArtalkSidebar.js"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "vite --port 23367",
|
||||
"build": "yarn lint && vite build",
|
||||
"build": "pnpm lint && vite build",
|
||||
"serve": "vite preview",
|
||||
"lint": "eslint --ext .js,.ts src"
|
||||
},
|
||||
"devDependencies": {
|
||||
},
|
||||
"dependencies": {
|
||||
"artalk": "*"
|
||||
"artalk": "workspace: *"
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
import Artalk from 'artalk'
|
||||
import ArtalkConfig, { LocalUser } from 'artalk/types/artalk-config'
|
||||
import 'artalk/dist/Artalk.css'
|
||||
import Sidebar from './sidebar'
|
||||
|
||||
class ArtalkSidebar extends Artalk {
|
||||
constructor(customConf: ArtalkConfig, user: LocalUser) {
|
||||
super(customConf)
|
||||
|
||||
this.$root.style.display = 'none'
|
||||
|
||||
user = user || {}
|
||||
this.ctx.user.data = {
|
||||
...this.ctx.user.data,
|
||||
...user
|
||||
}
|
||||
this.ctx.user.save()
|
||||
|
||||
const sidebar = new Sidebar(this.ctx)
|
||||
document.body.appendChild(sidebar.$el)
|
||||
|
||||
if (customConf.darkMode) {
|
||||
sidebar.$el.classList.add('atk-dark-mode')
|
||||
}
|
||||
|
||||
sidebar.show()
|
||||
console.log('hello artalk-sidebar')
|
||||
}
|
||||
}
|
||||
|
||||
export default ArtalkSidebar
|
||||
+93
-16
@@ -1,30 +1,104 @@
|
||||
import '../style/page-list.less'
|
||||
|
||||
import Context from 'artalk/src/context'
|
||||
import Component from 'artalk/src/lib/component'
|
||||
import Context from 'artalk/types/context'
|
||||
import * as Utils from 'artalk/src/lib/utils'
|
||||
import * as Ui from 'artalk/src/lib/ui'
|
||||
import { PageData } from 'artalk/types/artalk-data'
|
||||
import Api from 'artalk/src/api'
|
||||
import ActionBtn from 'artalk/src/components/action-btn'
|
||||
import ItemTextEditor from '../item-text-editor'
|
||||
import Component from '../sidebar-component'
|
||||
import { SidebarCtx } from '../main'
|
||||
import ItemTextEditor from '../lib/item-text-editor'
|
||||
|
||||
export default class PageList extends Component {
|
||||
$pageList!: HTMLElement
|
||||
$editor?: HTMLElement
|
||||
$inputer?: HTMLElement
|
||||
|
||||
pages: PageData[] = []
|
||||
|
||||
constructor(ctx: Context) {
|
||||
super(ctx)
|
||||
constructor(ctx: Context, sidebar: SidebarCtx) {
|
||||
super(ctx, sidebar)
|
||||
|
||||
this.$el = Utils.createElement(`<div class="atk-page-list"></div>`)
|
||||
this.$el = Utils.createElement(`<div class="atk-page-list-wrap"></div>`)
|
||||
}
|
||||
|
||||
/** 清空所有 Pages */
|
||||
clearAll() {
|
||||
/** 初始化 PageList (清空列表) */
|
||||
initPageList() {
|
||||
this.pages = []
|
||||
this.$el.innerHTML = ''
|
||||
|
||||
this.$el.innerHTML = `<div class="atk-header-action-bar">
|
||||
<span class="atk-update-all-title-btn"><i class="atk-icon atk-icon-sync"></i> <span class="atk-text">更新标题</span></span>
|
||||
<span class="atk-cache-flush-all-btn"><span class="atk-text">缓存清除</span></span>
|
||||
<span class="atk-cache-warm-up-btn"><span class="atk-text">缓存预热</span></span>
|
||||
</div>
|
||||
<div class="atk-page-list"></div>
|
||||
`
|
||||
|
||||
this.$pageList = this.$el.querySelector('.atk-page-list')!
|
||||
|
||||
// 缓存操作按钮
|
||||
const $cacheFlushBtn = this.$el.querySelector<HTMLElement>('.atk-cache-flush-all-btn')!
|
||||
$cacheFlushBtn.onclick = () => { this.ctx.getApi().cacheFlushAll().then((d: any) => alert(d.msg)).catch(() => alert('操作失败')) }
|
||||
const $cacheWarmBtn = this.$el.querySelector<HTMLElement>('.atk-cache-warm-up-btn')!
|
||||
$cacheWarmBtn.onclick = () => { this.ctx.getApi().cacheWarmUp().then((d: any) => alert(d.msg)).catch(() => alert('操作失败')) }
|
||||
|
||||
// 更新全部页面标题按钮
|
||||
;(async () => {
|
||||
const $updateAllTitleBtn = this.$el.querySelector<HTMLElement>('.atk-update-all-title-btn')!
|
||||
const $updateAllTitleIcon = $updateAllTitleBtn.querySelector<HTMLElement>('i')!
|
||||
const $updateAllTitleText = $updateAllTitleBtn.querySelector<HTMLElement>('.atk-text')!
|
||||
const btnTextOrg = $updateAllTitleText.innerText
|
||||
|
||||
const done = () => {
|
||||
$updateAllTitleText.innerText = '更新完毕'
|
||||
$updateAllTitleIcon.classList.remove('atk-rotate')
|
||||
window.setTimeout(() => {
|
||||
$updateAllTitleText.innerText = btnTextOrg
|
||||
}, 1500)
|
||||
}
|
||||
const checkStatus = async () => {
|
||||
const status = await this.ctx.getApi().pageFetch(undefined, undefined, true)
|
||||
return status
|
||||
}
|
||||
const startWatchdog = () => {
|
||||
$updateAllTitleIcon.classList.add('atk-rotate')
|
||||
|
||||
// 不完美的轮询更新状态
|
||||
const timerID = window.setInterval(async () => {
|
||||
const d = await this.ctx.getApi().pageFetch(undefined, undefined, true)
|
||||
|
||||
if (d.is_progress === false) {
|
||||
clearInterval(timerID)
|
||||
done()
|
||||
return
|
||||
}
|
||||
|
||||
$updateAllTitleText.innerText = d.msg
|
||||
}, 1000)
|
||||
}
|
||||
|
||||
// 图标恢复
|
||||
const status = await checkStatus()
|
||||
if (status.is_progress === true) {
|
||||
startWatchdog()
|
||||
$updateAllTitleText.innerText = status.msg
|
||||
}
|
||||
|
||||
// 点击发起任务
|
||||
$updateAllTitleBtn.onclick = async () => {
|
||||
if ($updateAllTitleIcon.classList.contains('atk-rotate')) return
|
||||
startWatchdog()
|
||||
$updateAllTitleText.innerText = '开始更新...'
|
||||
|
||||
// 发起任务
|
||||
try {
|
||||
await this.ctx.getApi().pageFetch(undefined, this.sidebar.curtSite)
|
||||
} catch (err: any) {
|
||||
alert(err.msg)
|
||||
done()
|
||||
}
|
||||
}
|
||||
})()
|
||||
}
|
||||
|
||||
/** 导入 Page 数据 */
|
||||
@@ -33,7 +107,7 @@ export default class PageList extends Component {
|
||||
|
||||
pages.forEach((page) => {
|
||||
const $page = this.renderPage(page)
|
||||
this.$el.append($page)
|
||||
this.$pageList.append($page)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -61,6 +135,9 @@ export default class PageList extends Component {
|
||||
$sub.innerText = page.url || page.key
|
||||
$editBtn.onclick = () => this.showEditor(page, $page)
|
||||
|
||||
$title.onclick = () => { if (page.url) window.open(page.url) }
|
||||
$sub.onclick = () => { if (page.url) window.open(page.url) }
|
||||
|
||||
return $page
|
||||
}
|
||||
|
||||
@@ -110,7 +187,7 @@ export default class PageList extends Component {
|
||||
Ui.showLoading(textEditor.$el)
|
||||
let p: PageData
|
||||
try {
|
||||
p = await new Api(this.ctx).pageEdit({ ...page, [key]: val })
|
||||
p = await this.ctx.getApi().pageEdit({ ...page, [key]: val })
|
||||
} catch (err: any) {
|
||||
showError(`修改失败:${err.msg || '未知错误'}`)
|
||||
console.error(err)
|
||||
@@ -130,7 +207,7 @@ export default class PageList extends Component {
|
||||
$keyEditBtn.onclick = () => openTextEditor('key')
|
||||
|
||||
// 仅管理员可评
|
||||
const adminOnlyActionBtn = new ActionBtn({
|
||||
const adminOnlyActionBtn = new ActionBtn(this.ctx, {
|
||||
text: () => {
|
||||
$adminOnlyBtn.classList.remove('atk-green', 'atk-yellow')
|
||||
$adminOnlyBtn.classList.add(!page.admin_only ? 'atk-green' : 'atk-yellow')
|
||||
@@ -142,7 +219,7 @@ export default class PageList extends Component {
|
||||
showLoading()
|
||||
let p: PageData
|
||||
try {
|
||||
p = await new Api(this.ctx).pageEdit({ ...page, admin_only: !page.admin_only })
|
||||
p = await this.ctx.getApi().pageEdit({ ...page, admin_only: !page.admin_only })
|
||||
} catch (err: any) {
|
||||
showError(`修改失败:${err.msg || '未知错误'}`)
|
||||
console.log(err)
|
||||
@@ -157,7 +234,7 @@ export default class PageList extends Component {
|
||||
showLoading()
|
||||
let p: PageData
|
||||
try {
|
||||
p = await new Api(this.ctx).pageFetch(page.id)
|
||||
p = (await this.ctx.getApi().pageFetch(page.id)).page
|
||||
} catch (err: any) {
|
||||
showError(`同步失败:${err.msg || '未知错误'}`)
|
||||
console.log(err)
|
||||
@@ -171,7 +248,7 @@ export default class PageList extends Component {
|
||||
const del = async () => {
|
||||
showLoading()
|
||||
try {
|
||||
await new Api(this.ctx).pageDel(page.key, page.site_name)
|
||||
await this.ctx.getApi().pageDel(page.key, page.site_name)
|
||||
} catch (err: any) {
|
||||
console.log(err)
|
||||
showError(`删除失败 ${String(err)}`)
|
||||
+3
-4
@@ -1,10 +1,9 @@
|
||||
import '../style/site-list.less'
|
||||
|
||||
import Context from 'artalk/src/context'
|
||||
import Context from 'artalk/types/context'
|
||||
import * as Utils from 'artalk/src/lib/utils'
|
||||
import * as Ui from 'artalk/src/lib/ui'
|
||||
import { SiteData } from 'artalk/types/artalk-data'
|
||||
import Api from 'artalk/src/api'
|
||||
|
||||
interface SiteListFloaterConf {
|
||||
onSwitchSite: (siteName: string) => boolean|void
|
||||
@@ -50,9 +49,9 @@ export default class SiteListFloater {
|
||||
|
||||
renderSiteItem('所有站点', '_', '__ATK_SITE_ALL')
|
||||
|
||||
const sites = await new Api(this.ctx).siteGet()
|
||||
const sites = await this.ctx.getApi().siteGet()
|
||||
sites.forEach((site) => {
|
||||
renderSiteItem(site.name, site.name.substr(0, 1))
|
||||
renderSiteItem(site.name, site.name.substring(0, 1))
|
||||
})
|
||||
|
||||
renderSiteItem('站点管理', '+', '', () => { this.conf.onClickSitesViewBtn();this.hide() })
|
||||
+19
-11
@@ -1,12 +1,12 @@
|
||||
import '../style/site-list.less'
|
||||
|
||||
import Context from 'artalk/src/context'
|
||||
import Component from 'artalk/src/lib/component'
|
||||
import Context from 'artalk/types/context'
|
||||
import * as Utils from 'artalk/src/lib/utils'
|
||||
import * as Ui from 'artalk/src/lib/ui'
|
||||
import { SiteData } from 'artalk/types/artalk-data'
|
||||
import Api from 'artalk/src/api'
|
||||
import ItemTextEditor from '../item-text-editor'
|
||||
import Component from '../sidebar-component'
|
||||
import { SidebarCtx } from '../main'
|
||||
import ItemTextEditor from '../lib/item-text-editor'
|
||||
|
||||
export default class SiteList extends Component {
|
||||
sites: SiteData[] = []
|
||||
@@ -21,8 +21,8 @@ export default class SiteList extends Component {
|
||||
|
||||
$add?: HTMLElement
|
||||
|
||||
constructor(ctx: Context) {
|
||||
super(ctx)
|
||||
constructor(ctx: Context, sidebar: SidebarCtx) {
|
||||
super(ctx, sidebar)
|
||||
|
||||
this.$el = Utils.createElement(
|
||||
`<div class="atk-site-list">
|
||||
@@ -49,6 +49,11 @@ export default class SiteList extends Component {
|
||||
this.closeEditor()
|
||||
this.showAdd()
|
||||
}
|
||||
|
||||
// TODO 这个太 magic 了
|
||||
this.ctx.on('sidebar-sites-create-form', (p: any) => {
|
||||
this.showAdd(p.create_name, p.create_urls)
|
||||
})
|
||||
}
|
||||
|
||||
public loadSites(sites: SiteData[]) {
|
||||
@@ -86,7 +91,7 @@ export default class SiteList extends Component {
|
||||
const $siteName = $site.querySelector<HTMLElement>('.atk-site-name')!
|
||||
const setActive = () => { $site.classList.add('atk-active') }
|
||||
|
||||
$siteLogo.innerText = site.name.substr(0, 1)
|
||||
$siteLogo.innerText = site.name.substring(0, 1)
|
||||
$siteName.innerText = site.name
|
||||
|
||||
// click
|
||||
@@ -175,7 +180,7 @@ export default class SiteList extends Component {
|
||||
Ui.showLoading(textEditor.$el)
|
||||
let s: SiteData
|
||||
try {
|
||||
s = await new Api(this.ctx).siteEdit({ ...site, [key]: val })
|
||||
s = await this.ctx.getApi().siteEdit({ ...site, [key]: val })
|
||||
} catch (err: any) {
|
||||
showError(`修改失败:${err.msg || '未知错误'}`)
|
||||
console.error(err)
|
||||
@@ -206,7 +211,7 @@ export default class SiteList extends Component {
|
||||
const del = async () => {
|
||||
showLoading()
|
||||
try {
|
||||
await new Api(this.ctx).siteDel(site.id, true)
|
||||
await this.ctx.getApi().siteDel(site.id, true)
|
||||
} catch (err: any) {
|
||||
console.log(err)
|
||||
showError(`删除失败 ${String(err)}`)
|
||||
@@ -230,7 +235,7 @@ export default class SiteList extends Component {
|
||||
this.activeSite = ''
|
||||
}
|
||||
|
||||
public showAdd() {
|
||||
public showAdd(defaultName?: string, defaultUrls?: string) {
|
||||
this.closeAdd()
|
||||
|
||||
this.$add = Utils.createElement(`
|
||||
@@ -256,6 +261,9 @@ export default class SiteList extends Component {
|
||||
const $siteUrls = this.$add.querySelector<HTMLInputElement>('[name="AtkSiteUrls"]')!
|
||||
const $submitBtn = this.$add.querySelector<HTMLButtonElement>('[name="AtkSubmit"]')!
|
||||
|
||||
if (defaultName) $siteName.value = defaultName
|
||||
if (defaultUrls) $siteUrls.value = defaultUrls
|
||||
|
||||
$submitBtn.onclick = async () => {
|
||||
const siteName = $siteName.value.trim()
|
||||
const siteUrls = $siteUrls.value.trim()
|
||||
@@ -265,7 +273,7 @@ export default class SiteList extends Component {
|
||||
Ui.showLoading(this.$add!)
|
||||
let s: SiteData
|
||||
try {
|
||||
s = await new Api(this.ctx).siteAdd(siteName, siteUrls)
|
||||
s = await this.ctx.getApi().siteAdd(siteName, siteUrls)
|
||||
} catch (err: any) {
|
||||
window.alert(`创建失败:${err.msg || ''}`)
|
||||
console.error(err)
|
||||
@@ -1,15 +0,0 @@
|
||||
import ArtalkSidebar from './artalk-sidebar'
|
||||
|
||||
const searchParams = new URLSearchParams(document.location.search)
|
||||
const pageKey = searchParams.get('pageKey') || ''
|
||||
const site = searchParams.get('site') || ''
|
||||
const user = JSON.parse(searchParams.get('user') || '{}')
|
||||
const darkMode = searchParams.get('darkMode') === '1'
|
||||
|
||||
const artalkSidebar = new ArtalkSidebar({
|
||||
el: '#ArtalkSidebar',
|
||||
server: (import.meta.env.MODE === 'development') ? 'http://localhost:23366/api' : '../api',
|
||||
pageKey,
|
||||
site,
|
||||
darkMode,
|
||||
}, user)
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import './style/item-text-editor.less'
|
||||
import '../style/item-text-editor.less'
|
||||
|
||||
import * as Utils from 'artalk/src/lib/utils'
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import Artalk from 'artalk'
|
||||
import ArtalkConfig, { LocalUser } from 'artalk/types/artalk-config'
|
||||
import 'artalk/dist/Artalk.css'
|
||||
import SidebarRoot from './sidebar-root'
|
||||
|
||||
export default async function InitSidebar(conf: ArtalkConfig, user: LocalUser, view?: string) {
|
||||
// 初始化 Artalk 主程序
|
||||
conf.useBackendConf = true
|
||||
const artalk = await (new Artalk(conf))
|
||||
artalk.$root.style.display = 'none'
|
||||
|
||||
// 初始化用户数据
|
||||
user = user || {}
|
||||
artalk.ctx.user.update({
|
||||
...user
|
||||
})
|
||||
|
||||
// 初始化 Sidebar
|
||||
const sidebarCtx = new SidebarCtx()
|
||||
sidebarCtx.curtSite = conf.site!
|
||||
|
||||
const sidebar = new SidebarRoot(artalk.ctx, sidebarCtx)
|
||||
|
||||
// 装载元素
|
||||
document.body.appendChild(sidebar.$el)
|
||||
|
||||
// 暗黑模式
|
||||
if (conf.darkMode) sidebar.$el.classList.add('atk-dark-mode')
|
||||
|
||||
// 初始化侧边栏
|
||||
await sidebar.init()
|
||||
|
||||
// 打开 View
|
||||
let viewName = SidebarRoot.DEFAULT_VIEW
|
||||
let viewParams = {}
|
||||
if (view) {
|
||||
const splitted = view.split('|')
|
||||
if (splitted[0]) viewName = splitted[0]
|
||||
if (splitted[1]) viewParams = JSON.parse(splitted[1])
|
||||
}
|
||||
|
||||
sidebar.switchView(viewName)
|
||||
|
||||
if (viewName === 'sites') {
|
||||
// TODO 炮打翻山...
|
||||
artalk.ctx.trigger('sidebar-sites-create-form', viewParams)
|
||||
}
|
||||
|
||||
console.log('hello artalk-sidebar')
|
||||
}
|
||||
|
||||
export class SidebarCtx {
|
||||
reload!: () => void
|
||||
curtSite!: string
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import ArtalkComponent from 'artalk/src/lib/component'
|
||||
import Context from 'artalk/types/context'
|
||||
import { SidebarCtx } from './main'
|
||||
|
||||
export default class Component extends ArtalkComponent {
|
||||
declare public ctx: Context
|
||||
sidebar: SidebarCtx
|
||||
|
||||
constructor(ctx: Context, sidebar: SidebarCtx) {
|
||||
super(ctx)
|
||||
|
||||
this.sidebar = sidebar
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
import './style/sidebar.less'
|
||||
|
||||
import Context from 'artalk/types/context'
|
||||
import * as Utils from 'artalk/src/lib/utils'
|
||||
import * as Ui from 'artalk/src/lib/ui'
|
||||
|
||||
import Component from './sidebar-component'
|
||||
import { SidebarCtx } from './main'
|
||||
import SidebarHTML from './sidebar.html?raw'
|
||||
|
||||
import SidebarView from './sidebar-views/sidebar-view'
|
||||
import CommentsView from './sidebar-views/comments-view'
|
||||
import PagesView from './sidebar-views/pages-view'
|
||||
import SitesView from './sidebar-views/sites-view'
|
||||
import TransferView from './sidebar-views/transfer-view'
|
||||
import SiteListFloater from './components/site-list-floater'
|
||||
import SettingView from './sidebar-views/setting-view'
|
||||
|
||||
import MD5 from './lib/md5'
|
||||
|
||||
const REGISTER_VIEWS = [
|
||||
CommentsView, PagesView, SitesView, TransferView, // SettingView
|
||||
]
|
||||
|
||||
export default class SidebarRoot extends Component {
|
||||
public static readonly DEFAULT_VIEW = 'comments'
|
||||
|
||||
public $header: HTMLElement
|
||||
public $headerMenu: HTMLElement
|
||||
public $title: HTMLElement
|
||||
public $avatar: HTMLElement
|
||||
public $siteLogo?: HTMLElement
|
||||
public $nav: HTMLElement
|
||||
public $curtViewBtn: HTMLElement
|
||||
public $curtViewBtnIcon: HTMLElement
|
||||
public $curtViewBtnText: HTMLElement
|
||||
public $navTabs: HTMLElement
|
||||
public $navViews: HTMLElement
|
||||
public $viewWrap: HTMLElement
|
||||
public siteSwitcher?: SiteListFloater
|
||||
|
||||
private get isAdmin() { return this.ctx.user.data.isAdmin }
|
||||
public curtView?: string
|
||||
public get curtViewInstance() {
|
||||
return this.curtView ? this.viewInstances[this.curtView] : undefined
|
||||
}
|
||||
public curtTab?: string
|
||||
|
||||
public viewInstances: {[name: string]: SidebarView} = {}
|
||||
|
||||
private viewSwitcherShow = false
|
||||
|
||||
constructor(ctx: Context, sidebar: SidebarCtx) {
|
||||
super(ctx, sidebar)
|
||||
|
||||
// initial elements
|
||||
this.$el = Utils.createElement(SidebarHTML)
|
||||
this.$header = this.$el.querySelector('.atk-sidebar-header')!
|
||||
this.$headerMenu = this.$header.querySelector('.atk-menu')!
|
||||
this.$title = this.$header.querySelector('.atk-sidebar-title')!
|
||||
this.$avatar = this.$header.querySelector('.atk-avatar')!
|
||||
|
||||
this.$nav = this.$el.querySelector('.atk-sidebar-nav')!
|
||||
this.$curtViewBtn = this.$nav.querySelector('.akt-curt-view-btn')!
|
||||
this.$curtViewBtnIcon = this.$curtViewBtn.querySelector('.atk-icon')!
|
||||
this.$curtViewBtnText = this.$curtViewBtn.querySelector('.atk-text')!
|
||||
this.$navTabs = this.$nav.querySelector('.atk-tabs')!
|
||||
this.$navViews = this.$nav.querySelector('.atk-views')!
|
||||
|
||||
this.$viewWrap = this.$el.querySelector('.atk-sidebar-view-wrap')!
|
||||
|
||||
// init UI
|
||||
this.initViewInstances()
|
||||
this.initViewSwitcher()
|
||||
|
||||
// 重载操作
|
||||
this.sidebar.reload = () => {
|
||||
this.init()
|
||||
}
|
||||
}
|
||||
|
||||
/** 初始化 views 实例对象 */
|
||||
private initViewInstances() {
|
||||
REGISTER_VIEWS.forEach((View) => {
|
||||
const viewInstance = new View(this.ctx, this.sidebar, this.$viewWrap)
|
||||
this.viewInstances[viewInstance.getName()] = viewInstance
|
||||
})
|
||||
}
|
||||
|
||||
/** 初始化 view 切换器 */
|
||||
private initViewSwitcher() {
|
||||
this.$curtViewBtn.onclick = () => {
|
||||
this.toggleViewSwitcher()
|
||||
}
|
||||
|
||||
this.$navViews.innerHTML = ''
|
||||
Object.entries(this.viewInstances).forEach(([viewName, view]) => {
|
||||
const $item = Utils.createElement(`<div class="atk-tab-item"></div>`)
|
||||
this.$navViews.append($item)
|
||||
$item.setAttribute('data-name', viewName)
|
||||
$item.innerText = view.viewTitle()
|
||||
if (viewName === this.curtView) {
|
||||
$item.classList.add('atk-active')
|
||||
this.$curtViewBtnText.innerText = view.viewTitle()
|
||||
}
|
||||
$item.onclick = () => {
|
||||
// 切换 view
|
||||
this.switchView(viewName)
|
||||
|
||||
this.toggleViewSwitcher()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/** 显示/隐藏 view 切换器 */
|
||||
private toggleViewSwitcher() {
|
||||
if (!this.viewSwitcherShow) {
|
||||
// 显示
|
||||
this.$navViews.style.display = ''
|
||||
this.$navTabs.style.display = 'none'
|
||||
this.$curtViewBtnIcon.classList.add('atk-arrow')
|
||||
// this.$curtViewBtnText.style.display = 'none'
|
||||
} else {
|
||||
// 隐藏
|
||||
this.$navViews.style.display = 'none'
|
||||
this.$navTabs.style.display = ''
|
||||
this.$curtViewBtnIcon.classList.remove('atk-arrow')
|
||||
// this.$curtViewBtnText.style.display = ''
|
||||
}
|
||||
|
||||
this.viewSwitcherShow = !this.viewSwitcherShow
|
||||
}
|
||||
|
||||
/** 初始化 */
|
||||
public async init() {
|
||||
// 用户权限检测
|
||||
if (this.isAdmin) {
|
||||
// 是管理员
|
||||
this.$title.innerText = '控制中心'
|
||||
this.$curtViewBtn.style.display = ''
|
||||
|
||||
if (!this.siteSwitcher) {
|
||||
// 初始化站点切换器
|
||||
this.siteSwitcher = new SiteListFloater(this.ctx, {
|
||||
onSwitchSite: (siteName) => {
|
||||
this.switchSite(siteName)
|
||||
},
|
||||
onClickSitesViewBtn: () => {
|
||||
this.switchView('sites')
|
||||
},
|
||||
})
|
||||
this.$viewWrap.before(this.siteSwitcher.$el)
|
||||
this.$avatar.onclick = (evt) => {
|
||||
if (!this.isAdmin) return
|
||||
this.siteSwitcher?.show(evt.target as any)
|
||||
}
|
||||
}
|
||||
|
||||
Ui.showLoading(this.$el)
|
||||
try {
|
||||
await this.siteSwitcher!.load(this.sidebar.curtSite)
|
||||
} catch (err: any) {
|
||||
const $err = Utils.createElement(
|
||||
`<span>加载失败:${err.msg || '网络错误'}<br/></span>`
|
||||
)
|
||||
const $retryBtn = Utils.createElement(
|
||||
'<span style="cursor:pointer;">点击重新获取</span>'
|
||||
)
|
||||
$err.appendChild($retryBtn)
|
||||
$retryBtn.onclick = () => {
|
||||
Ui.setError(this.$el, null)
|
||||
this.init()
|
||||
}
|
||||
Ui.setError(this.$el, $err)
|
||||
return
|
||||
} finally {
|
||||
Ui.hideLoading(this.$el)
|
||||
}
|
||||
|
||||
// 站点图像
|
||||
this.$avatar.innerHTML = ''
|
||||
this.$siteLogo = Utils.createElement('<div class="atk-site-logo"></div>')
|
||||
this.$siteLogo.innerText = (this.sidebar.curtSite || '').substring(0, 1)
|
||||
this.$avatar.append(this.$siteLogo)
|
||||
} else {
|
||||
// 不是管理员
|
||||
this.$title.innerText = '通知中心'
|
||||
this.$curtViewBtn.style.display = 'none' // 隐藏 view 切换器
|
||||
this.sidebar.curtSite = this.conf.site // 第一次 show 使用当前站点数据
|
||||
|
||||
// 头像
|
||||
const $avatarImg = document.createElement('img') as HTMLImageElement
|
||||
$avatarImg.src = Utils.getGravatarURL(
|
||||
this.ctx,
|
||||
MD5(this.ctx.user.data.email.toLowerCase())
|
||||
)
|
||||
this.$avatar.innerHTML = ''
|
||||
this.$avatar.append($avatarImg)
|
||||
}
|
||||
}
|
||||
|
||||
/** 切换 View */
|
||||
public switchView(viewName: string) {
|
||||
const view = this.viewInstances[viewName]
|
||||
if (!view)
|
||||
throw new Error(`Sidebar View "${viewName}" not found`)
|
||||
|
||||
// init view
|
||||
view.mount()
|
||||
|
||||
this.curtView = viewName
|
||||
this.curtTab = view.getActiveTab()
|
||||
|
||||
// update view indicator
|
||||
this.$curtViewBtnText.innerText = view.viewTitle()
|
||||
this.$navViews.querySelectorAll('.atk-tab-item').forEach((e) => {
|
||||
if (e.getAttribute('data-name') === viewName) {
|
||||
e.classList.add('atk-active')
|
||||
} else {
|
||||
e.classList.remove('atk-active')
|
||||
}
|
||||
})
|
||||
|
||||
// update tabs
|
||||
this.loadViewTabs(view)
|
||||
|
||||
// load element
|
||||
this.$viewWrap.innerHTML = ''
|
||||
this.$viewWrap.append(view.$el)
|
||||
this.$viewWrap.classList.forEach((c) => {
|
||||
if (c.startsWith('atk-view-name-'))
|
||||
this.$viewWrap.classList.remove(c)
|
||||
})
|
||||
this.$viewWrap.classList.add(`atk-view-name-${view.getName()}`)
|
||||
}
|
||||
|
||||
private loadViewTabs(view: SidebarView) {
|
||||
this.$navTabs.innerHTML = ''
|
||||
Object.entries<string>(view.getTabs()).forEach(([tabName, label]) => {
|
||||
const $tab = Utils.createElement(`<div class="atk-tab-item"></div>`)
|
||||
this.$navTabs.append($tab)
|
||||
$tab.innerText = label
|
||||
if (view.getActiveTab() === tabName) $tab.classList.add('atk-active')
|
||||
|
||||
// 切换 tab
|
||||
$tab.onclick = () => {
|
||||
if (view.switchTab(tabName) === false) { return }
|
||||
this.$navTabs.querySelectorAll('.atk-active').forEach(e => e.classList.remove('atk-active'))
|
||||
$tab.classList.add('atk-active')
|
||||
this.curtTab = tabName
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/** 切换站点 */
|
||||
private switchSite(siteName: string) {
|
||||
this.sidebar.curtSite = siteName
|
||||
const curtView = this.curtViewInstance
|
||||
curtView?.switchTab(this.curtTab!)
|
||||
if (this.$siteLogo) this.$siteLogo.innerText = this.sidebar.curtSite.substring(0, 1)
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
import Context from 'artalk/src/context'
|
||||
import Component from 'artalk/src/lib/component'
|
||||
import * as Utils from 'artalk/src/lib/utils'
|
||||
import Comment from 'artalk/src/components/comment'
|
||||
|
||||
export default class SidebarView extends Component {
|
||||
static viewName = ''
|
||||
static viewTitle = ''
|
||||
static viewAdminOnly = false
|
||||
|
||||
viewTabs = {}
|
||||
viewActiveTab = ''
|
||||
|
||||
protected $parent: HTMLElement
|
||||
|
||||
constructor(ctx: Context, $parent: HTMLElement) {
|
||||
super(ctx)
|
||||
|
||||
this.$parent = $parent
|
||||
this.$el = Utils.createElement(`<div class="atk-sidebar-view"></div>`)
|
||||
}
|
||||
|
||||
mount(siteName: string) {}
|
||||
|
||||
switchTab(tab: string, siteName: string): boolean|void {}
|
||||
}
|
||||
@@ -1,70 +1,67 @@
|
||||
import Context from 'artalk/src/context'
|
||||
import * as Utils from 'artalk/src/lib/utils'
|
||||
import ListLite from 'artalk/src/components/list-lite'
|
||||
|
||||
import SidebarView from '../sidebar-view'
|
||||
import ListLite from 'artalk/src/list/list-lite'
|
||||
import SidebarView from './sidebar-view'
|
||||
|
||||
export default class MessageView extends SidebarView {
|
||||
static viewName = 'comments'
|
||||
static viewTitle = '评论'
|
||||
protected readonly viewName = 'comments'
|
||||
viewTitle() { return '评论' }
|
||||
|
||||
viewTabs: any = {}
|
||||
viewActiveTab = ''
|
||||
protected tabs = {}
|
||||
protected activeTab = ''
|
||||
|
||||
list!: ListLite
|
||||
private list!: ListLite
|
||||
|
||||
mount(siteName: string) {
|
||||
mount() {
|
||||
// tabs
|
||||
if (this.ctx.user.data.isAdmin) {
|
||||
this.viewTabs = {
|
||||
this.tabs = {
|
||||
admin_all: '全部',
|
||||
admin_pending: '待审',
|
||||
all: '个人',
|
||||
}
|
||||
this.viewActiveTab = 'admin_all'
|
||||
this.activeTab = 'admin_all'
|
||||
} else {
|
||||
this.viewTabs = {
|
||||
this.tabs = {
|
||||
mentions: '提及',
|
||||
all: '全部',
|
||||
mine: '我的',
|
||||
pending: '待审',
|
||||
}
|
||||
this.viewActiveTab = 'mentions'
|
||||
this.activeTab = 'mentions'
|
||||
}
|
||||
|
||||
this.list = new ListLite(this.ctx)
|
||||
this.ctx.setList(this.list)
|
||||
this.list.flatMode = true
|
||||
this.list.unreadHighlight = true
|
||||
this.list.scrollListenerAt = this.$parent
|
||||
this.list.pageMode = 'pagination'
|
||||
this.list.noCommentText = '<div class="atk-sidebar-no-content">无内容</div>'
|
||||
this.list.renderComment = (comment) => {
|
||||
comment.setOpenURL(`${comment.data.page_key}#atk-comment-${comment.data.id}`)
|
||||
comment.onReplyBtnClick = () => {
|
||||
if (this.ctx.conf.editorTravel === true) {
|
||||
this.ctx.trigger('editor-reply', {data: comment.data, $el: comment.$el, scroll: false})
|
||||
} else {
|
||||
this.ctx.trigger('sidebar-hide')
|
||||
this.ctx.trigger('editor-reply', {data: comment.data, $el: comment.$el, scroll: true})
|
||||
}
|
||||
const pageURL = comment.getData().page_url
|
||||
comment.getRender().setOpenURL(`${pageURL}#atk-comment-${comment.getID()}`)
|
||||
comment.getConf().onReplyBtnClick = () => {
|
||||
this.ctx.replyComment(comment.getData(), comment.getEl(), true)
|
||||
}
|
||||
}
|
||||
this.list.paramsEditor = (params) => {
|
||||
params.site_name = siteName
|
||||
params.site_name = this.sidebar.curtSite
|
||||
}
|
||||
this.ctx.on('list-inserted', (data) => {
|
||||
;(this.$el.parentNode as any)?.scrollTo(0, 0)
|
||||
})
|
||||
|
||||
this.$el.innerHTML = ''
|
||||
this.$el.append(this.list.$el)
|
||||
|
||||
this.switchTab(this.viewActiveTab, siteName)
|
||||
this.switchTab(this.activeTab)
|
||||
}
|
||||
|
||||
switchTab(tab: string, siteName: string): boolean|void {
|
||||
switchTab(tab: string): boolean|void {
|
||||
//console.log(tab, siteName)
|
||||
this.viewActiveTab = tab
|
||||
this.activeTab = tab
|
||||
this.list.paramsEditor = (params) => {
|
||||
params.type = tab as any
|
||||
params.site_name = siteName
|
||||
params.site_name = this.sidebar.curtSite
|
||||
}
|
||||
this.list.fetchComments(0)
|
||||
|
||||
|
||||
@@ -1,62 +1,61 @@
|
||||
import Api from 'artalk/src/api'
|
||||
import Context from 'artalk/src/context'
|
||||
import Component from 'artalk/src/lib/component'
|
||||
import * as Utils from 'artalk/src/lib/utils'
|
||||
import * as Ui from 'artalk/src/lib/ui'
|
||||
import Comment from 'artalk/src/components/comment'
|
||||
import Pagination, { PaginationConf } from 'artalk/src/components/pagination'
|
||||
|
||||
import PageList from '../admin/page-list'
|
||||
import SidebarView from '../sidebar-view'
|
||||
import Pagination from 'artalk/src/components/pagination'
|
||||
import SidebarView from './sidebar-view'
|
||||
import PageList from '../components/page-list'
|
||||
|
||||
const PAGE_SIZE = 20
|
||||
|
||||
export default class PagesView extends SidebarView {
|
||||
static viewName = 'pages'
|
||||
static viewTitle = '页面'
|
||||
static viewAdminOnly = true
|
||||
protected readonly viewName = 'pages'
|
||||
public readonly viewAdminOnly = true
|
||||
viewTitle() { return '页面' }
|
||||
|
||||
viewTabs = {}
|
||||
viewActiveTab = ''
|
||||
protected tabs = {}
|
||||
protected activeTab = ''
|
||||
|
||||
isFirstLoad = true
|
||||
pageList!: PageList
|
||||
pagination!: Pagination
|
||||
|
||||
mount(siteName: string) {
|
||||
mount() {
|
||||
if (!this.pageList) {
|
||||
this.pageList = new PageList(this.ctx)
|
||||
this.pageList = new PageList(this.ctx, this.sidebar)
|
||||
this.$el.append(this.pageList.$el)
|
||||
}
|
||||
|
||||
this.switchTab(this.viewActiveTab, siteName)
|
||||
this.switchTab(this.activeTab)
|
||||
}
|
||||
|
||||
switchTab(tab: string, siteName: string): boolean|void {
|
||||
this.reqPages(siteName, 0)
|
||||
switchTab(tab: string): boolean|void {
|
||||
this.reqPages(0)
|
||||
}
|
||||
|
||||
async reqPages(siteName: string, offset: number) {
|
||||
this.pageList.clearAll()
|
||||
async reqPages(offset: number) {
|
||||
if (this.isFirstLoad) this.pageList.initPageList()
|
||||
;(this.$el.parentNode as any)?.scrollTo(0, 0)
|
||||
|
||||
Ui.showLoading(this.$el)
|
||||
if (this.isFirstLoad) Ui.showLoading(this.$el)
|
||||
else this.pagination.setLoading(true)
|
||||
|
||||
const data = await new Api(this.ctx).pageGet(siteName, offset, PAGE_SIZE)
|
||||
const data = await this.ctx.getApi().pageGet(this.sidebar.curtSite, offset, PAGE_SIZE)
|
||||
this.pageList.$pageList!.innerHTML = ''
|
||||
this.pageList.importPages(data.pages || [])
|
||||
|
||||
Ui.hideLoading(this.$el)
|
||||
if (this.isFirstLoad) Ui.hideLoading(this.$el)
|
||||
else this.pagination.setLoading(false)
|
||||
|
||||
if (!this.pagination) {
|
||||
if (this.isFirstLoad) {
|
||||
this.pagination = new Pagination(data.total, {
|
||||
pageSize: PAGE_SIZE,
|
||||
onChange: (o: number) => {
|
||||
this.reqPages(siteName, o)
|
||||
this.reqPages(o)
|
||||
}
|
||||
})
|
||||
|
||||
this.$el.append(this.pagination.$el)
|
||||
this.isFirstLoad = false
|
||||
} else {
|
||||
if (offset === 0) this.pagination.update(offset, data.total)
|
||||
}
|
||||
if (this.pagination && offset === 0)
|
||||
this.pagination.update(offset, data.total)
|
||||
}
|
||||
}
|
||||
@@ -1,22 +1,15 @@
|
||||
import Api from 'artalk/src/api'
|
||||
import Context from 'artalk/src/context'
|
||||
import Component from 'artalk/src/lib/component'
|
||||
import * as Utils from 'artalk/src/lib/utils'
|
||||
import Comment from 'artalk/src/components/comment'
|
||||
|
||||
import SiteList from '../admin/site-list'
|
||||
import SidebarView from '../sidebar-view'
|
||||
import SidebarView from './sidebar-view'
|
||||
|
||||
export default class SettingView extends SidebarView {
|
||||
static viewName = 'setting'
|
||||
static viewTitle = '配置'
|
||||
static viewAdminOnly = true
|
||||
protected readonly viewName = 'setting'
|
||||
public readonly viewAdminOnly = true
|
||||
viewTitle() { return '配置' }
|
||||
|
||||
viewTabs = {}
|
||||
viewActiveTab = ''
|
||||
protected tabs: { [key: string]: string } = {}
|
||||
protected activeTab = ''
|
||||
|
||||
mount(siteName: string) {
|
||||
mount() {
|
||||
}
|
||||
|
||||
switchTab(tab: string, siteName: string) {}
|
||||
switchTab(tab: string) {}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import Context from 'artalk/types/context'
|
||||
import * as Utils from 'artalk/src/lib/utils'
|
||||
import Component from '../sidebar-component'
|
||||
import { SidebarCtx } from '../main'
|
||||
|
||||
interface SidebarView {
|
||||
ctx: Context
|
||||
viewAdminOnly?: boolean
|
||||
}
|
||||
|
||||
abstract class SidebarView extends Component {
|
||||
protected $parent: HTMLElement
|
||||
|
||||
public constructor(ctx: Context, sidebar: SidebarCtx, $parent: HTMLElement) {
|
||||
super(ctx, sidebar)
|
||||
|
||||
this.$parent = $parent
|
||||
this.$el = Utils.createElement(`<div class="atk-sidebar-view"></div>`)
|
||||
}
|
||||
|
||||
protected abstract tabs: {[key: string]: string}
|
||||
protected abstract activeTab: string
|
||||
protected abstract readonly viewName: string
|
||||
public abstract viewTitle(): string
|
||||
|
||||
public abstract mount(): void
|
||||
public abstract switchTab(tab: string): boolean|void
|
||||
|
||||
public getName() {
|
||||
return this.viewName
|
||||
}
|
||||
|
||||
public getTabs() {
|
||||
return this.tabs
|
||||
}
|
||||
|
||||
public getActiveTab() {
|
||||
return this.activeTab
|
||||
}
|
||||
}
|
||||
|
||||
export default SidebarView
|
||||
@@ -1,37 +1,31 @@
|
||||
import Api from 'artalk/src/api'
|
||||
import Context from 'artalk/src/context'
|
||||
import Component from 'artalk/src/lib/component'
|
||||
import * as Utils from 'artalk/src/lib/utils'
|
||||
import Comment from 'artalk/src/components/comment'
|
||||
|
||||
import SiteList from '../admin/site-list'
|
||||
import SidebarView from '../sidebar-view'
|
||||
import SiteList from '../components/site-list'
|
||||
import SidebarView from './sidebar-view'
|
||||
|
||||
export default class SitesView extends SidebarView {
|
||||
static viewName = 'sites'
|
||||
static viewTitle = '站点'
|
||||
static viewAdminOnly = true
|
||||
protected readonly viewName = 'sites'
|
||||
public readonly viewAdminOnly = true
|
||||
viewTitle() { return '站点' }
|
||||
|
||||
viewTabs = {}
|
||||
viewActiveTab = ''
|
||||
protected tabs = {}
|
||||
protected activeTab = ''
|
||||
|
||||
siteList!: SiteList
|
||||
|
||||
mount(siteName: string) {
|
||||
mount() {
|
||||
if (!this.siteList) {
|
||||
this.siteList = new SiteList(this.ctx)
|
||||
this.siteList = new SiteList(this.ctx, this.sidebar)
|
||||
this.$el.append(this.siteList.$el)
|
||||
}
|
||||
|
||||
this.reqSites()
|
||||
}
|
||||
|
||||
switchTab(tab: string, siteName: string) {
|
||||
switchTab(tab: string) {
|
||||
this.reqSites()
|
||||
}
|
||||
|
||||
async reqSites() {
|
||||
const sites = await new Api(this.ctx).siteGet()
|
||||
const sites = await this.ctx.getApi().siteGet()
|
||||
this.siteList.loadSites(sites)
|
||||
}
|
||||
}
|
||||
@@ -1,29 +1,23 @@
|
||||
import Api from 'artalk/src/api'
|
||||
import Context from 'artalk/src/context'
|
||||
import Component from 'artalk/src/lib/component'
|
||||
import * as Utils from 'artalk/src/lib/utils'
|
||||
import * as Ui from 'artalk/src/lib/ui'
|
||||
import Comment from 'artalk/src/components/comment'
|
||||
import SidebarView from './sidebar-view'
|
||||
|
||||
import SiteList from '../admin/site-list'
|
||||
import SidebarView from '../sidebar-view'
|
||||
export default class TransferView extends SidebarView {
|
||||
protected readonly viewName = 'transfer'
|
||||
public readonly viewAdminOnly = true
|
||||
viewTitle() { return '迁移' }
|
||||
|
||||
export default class TransferView extends SidebarView {ß
|
||||
static viewName = 'transfer'
|
||||
static viewTitle = '迁移'
|
||||
static viewAdminOnly = true
|
||||
|
||||
viewTabs = {
|
||||
protected tabs = {
|
||||
'import': '导入',
|
||||
'export': '导出',
|
||||
}
|
||||
viewActiveTab = 'import'
|
||||
protected activeTab = 'import'
|
||||
|
||||
mount(siteName: string) {
|
||||
this.switchTab('import', siteName)
|
||||
mount() {
|
||||
this.switchTab('import')
|
||||
}
|
||||
|
||||
switchTab(tab: string, siteName: string) {
|
||||
switchTab(tab: string) {
|
||||
if (tab === 'import') {
|
||||
this.initImport()
|
||||
} else if (tab === 'export') {
|
||||
@@ -42,8 +36,18 @@ export default class TransferView extends SidebarView {ß
|
||||
</div>
|
||||
<div class="atk-form">
|
||||
<div class="atk-label atk-data-file-label">Artrans 数据文件</div>
|
||||
<input type="file" name="AtkDataFile" accept="text/plain,.json,.artrans">
|
||||
<span class="atk-desc">使用「<a href="https://artalk.js.org/guide/transfer.html" target="_blank">转换工具</a>」将评论数据转为 Artrans 格式</span>
|
||||
<div class="atk-file-upload-group">
|
||||
<div class="atk-file-input-wrap atk-fade-in">
|
||||
<input type="file" name="AtkDataFile" accept=".artrans">
|
||||
<span class="atk-desc">使用「<a href="https://artalk.js.org/guide/transfer.html" target="_blank">转换工具</a>」将评论数据转为 Artrans 格式</span>
|
||||
</div>
|
||||
<div class="atk-uploading-wrap atk-fade-in">
|
||||
<div class="atk-progress">
|
||||
<div class="atk-bar"></div>
|
||||
</div>
|
||||
<div class="atk-status">上传中 <span class="atk-curt">0%</span>... <span class="atk-abort">取消</span></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="atk-label">目标站点名</div>
|
||||
<input type="text" name="AtkSiteName" placeholder="输入内容..." autocomplete="off">
|
||||
<div class="atk-label">目标站点 URL</div>
|
||||
@@ -55,16 +59,139 @@ export default class TransferView extends SidebarView {ß
|
||||
</div>`
|
||||
|
||||
const $form = this.$el.querySelector<HTMLSelectElement>('.atk-form')!
|
||||
const $dataFile = $form.querySelector<HTMLInputElement>('[name="AtkDataFile"]')!
|
||||
const $dataFileLabel = $form.querySelector<HTMLInputElement>('.atk-data-file-label')!
|
||||
|
||||
const $fileWrap = $form.querySelector<HTMLElement>('.atk-file-input-wrap')!
|
||||
const $file = $fileWrap.querySelector<HTMLInputElement>('[name="AtkDataFile"]')!
|
||||
const $fileDesc = $fileWrap.querySelector<HTMLElement>('.atk-desc')!
|
||||
const fileDescOrgHTML = $fileDesc.innerHTML
|
||||
const restoreFileInput = () => {
|
||||
$fileDesc.innerHTML = fileDescOrgHTML
|
||||
$file.value = ''
|
||||
}
|
||||
|
||||
// 文件上传
|
||||
const $uploadingWrap = $form.querySelector<HTMLElement>('.atk-uploading-wrap')!
|
||||
const $uploadProgress = $uploadingWrap.querySelector<HTMLElement>('.atk-progress')!
|
||||
const $uploadProgressBar = $uploadProgress.querySelector<HTMLElement>('.atk-bar')!
|
||||
const $uploadStatus = $uploadingWrap.querySelector<HTMLElement>('.atk-status')!
|
||||
const $uploadStatusCurt = $uploadStatus.querySelector<HTMLElement>('.atk-curt')!
|
||||
const $uploadAbortBtn = $uploadStatus.querySelector<HTMLElement>('.atk-abort')!
|
||||
|
||||
const $siteName = $form.querySelector<HTMLInputElement>('[name="AtkSiteName"]')!
|
||||
const $siteURL = $form.querySelector<HTMLInputElement>('[name="AtkSiteURL"]')!
|
||||
const $payload = $form.querySelector<HTMLTextAreaElement>('[name="AtkPayload"]')!
|
||||
const $submitBtn = $form.querySelector<HTMLButtonElement>('[name="AtkSubmit"]')!
|
||||
const setError = (msg: string) => window.alert(msg)
|
||||
|
||||
const showUploading = () => {
|
||||
$fileWrap.style.display = 'none'
|
||||
$uploadingWrap.style.display = ''
|
||||
setUploading(0)
|
||||
}
|
||||
|
||||
const hideUploading = () => {
|
||||
$fileWrap.style.display = ''
|
||||
$uploadingWrap.style.display = 'none'
|
||||
}
|
||||
|
||||
const setUploading = (progress: number) => {
|
||||
$uploadProgressBar.style.width = `${progress}%`
|
||||
$uploadStatusCurt.innerText = `${progress}%`
|
||||
}
|
||||
|
||||
let UploadedFilename: string = ''
|
||||
|
||||
hideUploading()
|
||||
|
||||
const startUploadFile = async () => {
|
||||
UploadedFilename = ''
|
||||
|
||||
const xhr = new XMLHttpRequest()
|
||||
|
||||
// 进度条
|
||||
xhr.upload.addEventListener('progress', (evt) => {
|
||||
if (evt.loaded === evt.total) {
|
||||
// 上传完毕
|
||||
setUploading(100)
|
||||
return
|
||||
}
|
||||
|
||||
const fileSize = $file.files![0].size
|
||||
if (evt.loaded <= fileSize) {
|
||||
// 正在上传
|
||||
const percent = Math.round(evt.loaded / fileSize * 100)
|
||||
setUploading(percent)
|
||||
}
|
||||
})
|
||||
|
||||
// 创建上传参数
|
||||
const formData = new FormData()
|
||||
formData.append('file', $file.files![0])
|
||||
formData.append('token', this.ctx.user.data.token)
|
||||
|
||||
// 开始上传
|
||||
xhr.open('post', `${this.ctx.conf.server}/api/admin/import-upload`)
|
||||
xhr.timeout = 2*60*1000 // 2min
|
||||
xhr.send(formData)
|
||||
|
||||
// 上传成功事件
|
||||
xhr.onload = () => {
|
||||
const setErr = (msg: string): void => {
|
||||
restoreFileInput()
|
||||
hideUploading()
|
||||
alert(`文件上传失败,${msg}`)
|
||||
}
|
||||
|
||||
if (xhr.status !== 200) {
|
||||
setErr(`响应状态码:${xhr.status}`)
|
||||
return
|
||||
}
|
||||
|
||||
let json: any
|
||||
try {
|
||||
json = JSON.parse(xhr.response)
|
||||
} catch (err) {
|
||||
console.error(err)
|
||||
setErr(`JSON 解析失败:${err}`)
|
||||
return
|
||||
}
|
||||
|
||||
if (!json.success || !json.data.filename) {
|
||||
setErr(`响应:${xhr.response}`)
|
||||
return
|
||||
}
|
||||
|
||||
$fileDesc.innerHTML = '文件已成功上传,可以开始导入'
|
||||
UploadedFilename = json.data.filename
|
||||
hideUploading()
|
||||
}
|
||||
|
||||
// 中止上传
|
||||
$uploadAbortBtn.onclick = () => {
|
||||
xhr.abort()
|
||||
restoreFileInput()
|
||||
hideUploading()
|
||||
}
|
||||
}
|
||||
|
||||
// 文件上传操作
|
||||
$file.onchange = () => {
|
||||
if (!$file.files || $file.files.length === 0) return
|
||||
|
||||
showUploading()
|
||||
setTimeout(async () => {
|
||||
await startUploadFile()
|
||||
hideUploading()
|
||||
}, 80)
|
||||
}
|
||||
|
||||
// 开始导入按钮
|
||||
$submitBtn.onclick = () => {
|
||||
const dataType = 'artrans'
|
||||
if (!UploadedFilename) {
|
||||
setError(`请先上传 Artrans 数据文件`)
|
||||
return
|
||||
}
|
||||
|
||||
const siteName = $siteName.value.trim()
|
||||
const siteURL = $siteURL.value.trim()
|
||||
const payload = $payload.value.trim()
|
||||
@@ -80,7 +207,7 @@ export default class TransferView extends SidebarView {ß
|
||||
return
|
||||
}
|
||||
|
||||
if (rData !instanceof Object) {
|
||||
if (typeof rData !== 'object' || Array.isArray(rData)) {
|
||||
setError(`Payload 需为 JSON 对象`)
|
||||
return
|
||||
}
|
||||
@@ -89,7 +216,7 @@ export default class TransferView extends SidebarView {ß
|
||||
if (siteURL) rData.t_url = siteURL
|
||||
|
||||
// 创建导入会话
|
||||
const createSession = (dataStr?: string) => {
|
||||
const createSession = (filename?: string) => {
|
||||
const $logWrap = this.$el.querySelector<HTMLElement>('.atk-log-wrap')!
|
||||
const $log = $logWrap.querySelector<HTMLElement>('.atk-log')!
|
||||
const $backBtn = this.$el.querySelector<HTMLElement>('.atk-log-back-btn')!
|
||||
@@ -100,9 +227,12 @@ export default class TransferView extends SidebarView {ß
|
||||
$backBtn.onclick = () => {
|
||||
$logWrap.style.display = 'none'
|
||||
$form.style.display = ''
|
||||
restoreFileInput()
|
||||
UploadedFilename = ''
|
||||
this.sidebar.reload()
|
||||
}
|
||||
|
||||
if (dataStr) rData.json_data = dataStr
|
||||
if (filename) rData.json_file = filename
|
||||
|
||||
// 创建 iframe
|
||||
const frameName = `f_${+new Date()}`
|
||||
@@ -113,7 +243,6 @@ export default class TransferView extends SidebarView {ß
|
||||
$log.append($frame)
|
||||
|
||||
const formParams: {[k: string]: string} = {
|
||||
type: dataType,
|
||||
payload: JSON.stringify(rData),
|
||||
token: this.ctx.user.data.token || '',
|
||||
}
|
||||
@@ -122,7 +251,7 @@ export default class TransferView extends SidebarView {ß
|
||||
const $formTmp = document.createElement('form')
|
||||
$formTmp.style.display = 'none'
|
||||
$formTmp.setAttribute('method', 'post')
|
||||
$formTmp.setAttribute('action', `${this.ctx.conf.server}/admin/import`)
|
||||
$formTmp.setAttribute('action', `${this.ctx.conf.server}/api/admin/import`)
|
||||
$formTmp.setAttribute("target", frameName)
|
||||
|
||||
Object.entries(formParams).forEach(([key, val]) => {
|
||||
@@ -138,20 +267,8 @@ export default class TransferView extends SidebarView {ß
|
||||
$formTmp.remove()
|
||||
}
|
||||
|
||||
const reader = new FileReader()
|
||||
reader.onload = () => {
|
||||
const data = String(reader.result)
|
||||
createSession(data)
|
||||
}
|
||||
|
||||
// 是否已选择文件
|
||||
if ($dataFile.files?.length) {
|
||||
// 先读取文件
|
||||
reader.readAsText($dataFile.files[0])
|
||||
} else {
|
||||
// 直接开始会话
|
||||
createSession()
|
||||
}
|
||||
// 直接开始会话
|
||||
createSession(UploadedFilename)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -159,8 +276,8 @@ export default class TransferView extends SidebarView {ß
|
||||
Ui.showLoading(this.$el)
|
||||
|
||||
try {
|
||||
const d = await new Api(this.ctx).export()
|
||||
this.download(`artrans-${this.getYmdHisFilename()}.json`, d)
|
||||
const d = await this.ctx.getApi().export()
|
||||
this.download(`backup-${this.getYmdHisFilename()}.artrans`, d)
|
||||
} catch (err: any) {
|
||||
console.log(err)
|
||||
window.alert(`${String(err)}`)
|
||||
|
||||
@@ -1,268 +0,0 @@
|
||||
import './style/sidebar.less'
|
||||
|
||||
import Context from 'artalk/src/context'
|
||||
import Component from 'artalk/src/lib/component'
|
||||
import * as Utils from 'artalk/src/lib/utils'
|
||||
import * as Ui from 'artalk/src/lib/ui'
|
||||
import Comment from 'artalk/src/components/comment'
|
||||
import { SiteData } from 'artalk/types/artalk-data'
|
||||
import Api from 'artalk/src/api'
|
||||
|
||||
import SidebarHTML from './sidebar.html?raw'
|
||||
|
||||
import SidebarView from './sidebar-view'
|
||||
import CommentsView from './sidebar-views/comments-view'
|
||||
import PagesView from './sidebar-views/pages-view'
|
||||
import SitesView from './sidebar-views/sites-view'
|
||||
import TransferView from './sidebar-views/transfer-view'
|
||||
import SiteListFloater from './admin/site-list-floater'
|
||||
import SettingView from './sidebar-views/setting-view'
|
||||
|
||||
import MD5 from './lib/md5'
|
||||
|
||||
const DEFAULT_VIEW = 'comments'
|
||||
const REGISTER_VIEWS: (typeof SidebarView)[] = [
|
||||
CommentsView, PagesView, SitesView, TransferView, // SettingView
|
||||
]
|
||||
|
||||
export default class Sidebar extends Component {
|
||||
public $header: HTMLElement
|
||||
public $headerMenu: HTMLElement
|
||||
public $title: HTMLElement
|
||||
public $avatar: HTMLElement
|
||||
public $siteLogo?: HTMLElement
|
||||
public $closeBtn: HTMLElement
|
||||
public $nav: HTMLElement
|
||||
public $curtViewBtn: HTMLElement
|
||||
public $curtViewBtnIcon: HTMLElement
|
||||
public $curtViewBtnText: HTMLElement
|
||||
public $navTabs: HTMLElement
|
||||
public $navViews: HTMLElement
|
||||
public $viewWrap: HTMLElement
|
||||
public siteSwitcher?: SiteListFloater
|
||||
|
||||
private get isAdmin() { return this.ctx.user.data.isAdmin }
|
||||
public curtSite?: string
|
||||
public curtView: string = DEFAULT_VIEW
|
||||
public get curtViewInstance() {
|
||||
return this.curtView ? this.viewInstances[this.curtView] : undefined
|
||||
}
|
||||
public curtTab?: string
|
||||
|
||||
public viewInstances: {[name: string]: SidebarView} = {}
|
||||
|
||||
private viewSwitcherShow = false
|
||||
|
||||
constructor(ctx: Context) {
|
||||
super(ctx)
|
||||
|
||||
// initial elements
|
||||
this.$el = Utils.createElement(SidebarHTML)
|
||||
this.$header = this.$el.querySelector('.atk-sidebar-header')!
|
||||
this.$headerMenu = this.$header.querySelector('.atk-menu')!
|
||||
this.$title = this.$header.querySelector('.atk-sidebar-title')!
|
||||
this.$avatar = this.$header.querySelector('.atk-avatar')!
|
||||
this.$closeBtn = this.$header.querySelector('.atk-sidebar-close')!
|
||||
|
||||
this.$nav = this.$el.querySelector('.atk-sidebar-nav')!
|
||||
this.$curtViewBtn = this.$nav.querySelector('.akt-curt-view-btn')!
|
||||
this.$curtViewBtnIcon = this.$curtViewBtn.querySelector('.atk-icon')!
|
||||
this.$curtViewBtnText = this.$curtViewBtn.querySelector('.atk-text')!
|
||||
this.$navTabs = this.$nav.querySelector('.atk-tabs')!
|
||||
this.$navViews = this.$nav.querySelector('.atk-views')!
|
||||
|
||||
this.$viewWrap = this.$el.querySelector('.atk-sidebar-view-wrap')!
|
||||
|
||||
// init UI
|
||||
this.initViewSwitcher()
|
||||
|
||||
this.$closeBtn.onclick = () => {
|
||||
this.hide()
|
||||
}
|
||||
|
||||
// event
|
||||
this.ctx.on('sidebar-show', () => (this.show()))
|
||||
this.ctx.on('sidebar-hide', () => (this.hide()))
|
||||
this.ctx.on('user-changed', () => { this.firstShow = true })
|
||||
}
|
||||
|
||||
/** 初始化 view 切换器 */
|
||||
private initViewSwitcher() {
|
||||
this.$curtViewBtn.onclick = () => {
|
||||
this.toggleViewSwitcher()
|
||||
}
|
||||
|
||||
this.$navViews.innerHTML = ''
|
||||
REGISTER_VIEWS.forEach(view => {
|
||||
const $item = Utils.createElement(`<div class="atk-tab-item"></div>`)
|
||||
this.$navViews.append($item)
|
||||
$item.setAttribute('data-name', view.viewName)
|
||||
$item.innerText = view.viewTitle
|
||||
if (view.viewName === this.curtView) {
|
||||
$item.classList.add('atk-active')
|
||||
this.$curtViewBtnText.innerText = view.viewTitle
|
||||
}
|
||||
$item.onclick = () => {
|
||||
// 切换 view
|
||||
this.switchView(view.viewName)
|
||||
|
||||
this.toggleViewSwitcher()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/** 显示/隐藏 view 切换器 */
|
||||
private toggleViewSwitcher() {
|
||||
if (!this.viewSwitcherShow) {
|
||||
// 显示
|
||||
this.$navViews.style.display = ''
|
||||
this.$navTabs.style.display = 'none'
|
||||
this.$curtViewBtnIcon.classList.add('atk-arrow')
|
||||
// this.$curtViewBtnText.style.display = 'none'
|
||||
} else {
|
||||
// 隐藏
|
||||
this.$navViews.style.display = 'none'
|
||||
this.$navTabs.style.display = ''
|
||||
this.$curtViewBtnIcon.classList.remove('atk-arrow')
|
||||
// this.$curtViewBtnText.style.display = ''
|
||||
}
|
||||
|
||||
this.viewSwitcherShow = !this.viewSwitcherShow
|
||||
}
|
||||
|
||||
private firstShow = true
|
||||
|
||||
/** 显示 */
|
||||
public async show() {
|
||||
// 第一次加载
|
||||
if (this.firstShow) {
|
||||
///////////////////
|
||||
//// IMPORTANT ////
|
||||
///////////////////
|
||||
|
||||
// 用户权限检测
|
||||
if (this.isAdmin) {
|
||||
// 是管理员
|
||||
this.$title.innerText = '控制中心'
|
||||
this.$curtViewBtn.style.display = ''
|
||||
|
||||
if (!this.siteSwitcher) {
|
||||
// 初始化站点切换器
|
||||
this.siteSwitcher = new SiteListFloater(this.ctx, {
|
||||
onSwitchSite: (siteName) => { this.switchSite(siteName) },
|
||||
onClickSitesViewBtn: () => { this.switchView('sites') }
|
||||
})
|
||||
this.$viewWrap.before(this.siteSwitcher.$el)
|
||||
this.$avatar.onclick = (evt) => {
|
||||
if (!this.isAdmin) return
|
||||
this.siteSwitcher?.show(evt.target as any)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
this.curtSite = this.conf.site
|
||||
|
||||
Ui.showLoading(this.$el)
|
||||
try {
|
||||
await this.siteSwitcher!.load(this.curtSite)
|
||||
} catch (err: any) {
|
||||
const $err = Utils.createElement(`<span>加载失败:${err.msg || '网络错误'}<br/></span>`)
|
||||
const $retryBtn = Utils.createElement('<span style="cursor:pointer;">点击重新获取</span>')
|
||||
$err.appendChild($retryBtn)
|
||||
$retryBtn.onclick = () => { Ui.setError(this.$el, null); this.show() }
|
||||
Ui.setError(this.$el, $err)
|
||||
return
|
||||
} finally { Ui.hideLoading(this.$el) }
|
||||
|
||||
// 站点图像
|
||||
this.$avatar.innerHTML = ''
|
||||
this.$siteLogo = Utils.createElement('<div class="atk-site-logo"></div>')
|
||||
this.$siteLogo.innerText = (this.curtSite || '').substr(0, 1)
|
||||
this.$avatar.append(this.$siteLogo)
|
||||
} else {
|
||||
// 不是管理员
|
||||
this.$title.innerText = '通知中心'
|
||||
this.$curtViewBtn.style.display = 'none' // 隐藏 view 切换器
|
||||
this.curtSite = this.conf.site // 第一次 show 使用当前站点数据
|
||||
|
||||
// 头像
|
||||
const $avatarImg = document.createElement('img') as HTMLImageElement
|
||||
$avatarImg.src = Utils.getGravatarURL(this.ctx, MD5(this.ctx.user.data.email.toLowerCase()))
|
||||
this.$avatar.innerHTML = ''
|
||||
this.$avatar.append($avatarImg)
|
||||
}
|
||||
|
||||
this.switchView(DEFAULT_VIEW) // 打开默认 view
|
||||
this.firstShow = false
|
||||
}
|
||||
}
|
||||
|
||||
public async hide() {
|
||||
console.log("hide")
|
||||
}
|
||||
|
||||
/** 切换 View */
|
||||
public switchView(viewName: string) {
|
||||
let view = this.viewInstances[viewName]
|
||||
if (!view) {
|
||||
// 初始化 View
|
||||
const View = REGISTER_VIEWS.find(o => o.viewName === viewName)!
|
||||
view = new View(this.ctx, this.$viewWrap)
|
||||
this.viewInstances[viewName] = view
|
||||
}
|
||||
|
||||
// init view
|
||||
view.mount(this.curtSite!)
|
||||
|
||||
this.curtView = viewName
|
||||
this.curtTab = view.viewActiveTab
|
||||
|
||||
// update view indicator
|
||||
this.$curtViewBtnText.innerText = (view.constructor as typeof SidebarView).viewTitle
|
||||
this.$navViews.querySelectorAll('.atk-tab-item').forEach((e) => {
|
||||
if (e.getAttribute('data-name') === viewName) {
|
||||
e.classList.add('atk-active')
|
||||
} else {
|
||||
e.classList.remove('atk-active')
|
||||
}
|
||||
})
|
||||
|
||||
// update tabs
|
||||
this.loadViewTabs(view)
|
||||
|
||||
// load element
|
||||
this.$viewWrap.innerHTML = ''
|
||||
this.$viewWrap.append(view.$el)
|
||||
this.$viewWrap.classList.forEach((c) => {
|
||||
if (c.startsWith('atk-view-name-'))
|
||||
this.$viewWrap.classList.remove(c)
|
||||
})
|
||||
this.$viewWrap.classList.add(`atk-view-name-${(view.constructor as typeof SidebarView).viewName}`)
|
||||
}
|
||||
|
||||
private loadViewTabs(view: SidebarView) {
|
||||
this.$navTabs.innerHTML = ''
|
||||
Object.entries<string>(view.viewTabs).forEach(([tabName, label]) => {
|
||||
const $tab = Utils.createElement(`<div class="atk-tab-item"></div>`)
|
||||
this.$navTabs.append($tab)
|
||||
$tab.innerText = label
|
||||
if (view.viewActiveTab === tabName) $tab.classList.add('atk-active')
|
||||
|
||||
// 切换 tab
|
||||
$tab.onclick = () => {
|
||||
if (view.switchTab(tabName, this.curtSite!) === false) { return }
|
||||
this.$navTabs.querySelectorAll('.atk-active').forEach(e => e.classList.remove('atk-active'))
|
||||
$tab.classList.add('atk-active')
|
||||
this.curtTab = tabName
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/** 切换站点 */
|
||||
private switchSite(siteName: string) {
|
||||
this.curtSite = siteName
|
||||
const curtView = this.curtViewInstance
|
||||
curtView?.switchTab(this.curtTab!, siteName)
|
||||
if (this.$siteLogo) this.$siteLogo.innerText = this.curtSite.substr(0, 1)
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
@font-family: "Helvetica Neue", "PingFangSC-Light", "Hiragino Sans GB", "Microsoft YaHei", "WenQuanYi Micro Hei", sans-serif;
|
||||
@font-size: 14px;
|
||||
@line-height: 1.6em;
|
||||
@block-radius: 4px;
|
||||
@block-radius: 6px;
|
||||
@@ -1,3 +1,31 @@
|
||||
.atk-page-list-wrap {
|
||||
.atk-header-action-bar {
|
||||
display: block;
|
||||
overflow: hidden;
|
||||
padding: 10px 15px 0 15px;
|
||||
|
||||
& > span {
|
||||
display: inline-block;
|
||||
padding: 2px 10px;
|
||||
cursor: pointer;
|
||||
font-size: 13px;
|
||||
|
||||
i {
|
||||
display: inline-block;
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
vertical-align: middle;
|
||||
background-color: var(--at-color-meta);
|
||||
margin-right: 4px;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
background: var(--at-color-bg-grey);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.atk-page-list {
|
||||
.atk-page-item {
|
||||
display: flex;
|
||||
@@ -21,11 +49,13 @@
|
||||
color: var(--at-color-font);
|
||||
font-size: 21px;
|
||||
margin-bottom: 10px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.atk-sub {
|
||||
color: var(--at-color-sub);
|
||||
font-size: 14px;
|
||||
cursor: pointer;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
@header-height: 60px;
|
||||
@nav-height: 40px;
|
||||
|
||||
.artalk, .atk-layer-wrap {
|
||||
font-family: @font-family;
|
||||
}
|
||||
|
||||
.atk-sidebar {
|
||||
@width: 430px;
|
||||
position: fixed;
|
||||
@@ -317,13 +321,14 @@
|
||||
}
|
||||
|
||||
&[type="file"] {
|
||||
border-radius: 2px;
|
||||
background: transparent;
|
||||
border: 2px solid var(--at-color-border);
|
||||
cursor: pointer;
|
||||
position: relative;
|
||||
padding: 0 15px;
|
||||
margin-bottom: 20px;
|
||||
padding: 6px 15px;
|
||||
line-height: 0;
|
||||
margin-bottom: 17px;
|
||||
border-radius: 50px;
|
||||
|
||||
&:hover {
|
||||
background: var(--at-color-bg-light);
|
||||
@@ -333,14 +338,19 @@
|
||||
|
||||
&[type="file"]::-webkit-file-upload-button {
|
||||
background: transparent;
|
||||
color: #000;
|
||||
color: var(--at-color-font);
|
||||
border: 0;
|
||||
border-right: 2px solid #eee;
|
||||
padding: 0 20px 0 5px;
|
||||
border-left: 0;
|
||||
border-top: 0;
|
||||
border-bottom: 0;
|
||||
padding: 0 20px 0 10px;
|
||||
line-height: 25px;
|
||||
margin-right: 15px;
|
||||
cursor: pointer;
|
||||
transition: .2s ease;
|
||||
-webkit-appearance: none;
|
||||
border-radius: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -380,14 +390,59 @@
|
||||
cursor: pointer;
|
||||
outline: none;
|
||||
padding: 0 20px;
|
||||
border-radius: 4px;
|
||||
border-radius: 50px;
|
||||
margin: 0 5px;
|
||||
width: 100%;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
input, select, button {
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
.atk-file-upload-group {
|
||||
height: 100px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.atk-uploading-wrap {
|
||||
.atk-progress {
|
||||
width: 100%;
|
||||
height: 12px;
|
||||
display: block;
|
||||
overflow: hidden;
|
||||
background: #eee;
|
||||
border-radius: 100px;
|
||||
margin-bottom: 7px;
|
||||
margin-top: 20px;
|
||||
|
||||
.atk-bar {
|
||||
transition: 0.5s cubic-bezier(0.075, 0.82, 0.165, 1);
|
||||
background: var(--at-color-main);
|
||||
height: 100%;
|
||||
width: 0%;
|
||||
opacity: 0.7;
|
||||
}
|
||||
}
|
||||
|
||||
.atk-status {
|
||||
color: var(--at-color-meta);
|
||||
font-size: 14px;
|
||||
|
||||
.atk-curt {
|
||||
color: var(--at-color-main)
|
||||
}
|
||||
|
||||
.atk-abort {
|
||||
cursor: pointer;
|
||||
float: right;
|
||||
|
||||
&:hover {
|
||||
color: var(--at-color-main);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.atk-log-wrap {
|
||||
@@ -418,6 +473,10 @@
|
||||
.atk-view-name-pages, .atk-view-name-comments {
|
||||
padding-bottom: 55px;
|
||||
|
||||
.atk-comment-wrap {
|
||||
border-bottom: 1px solid var(--at-color-border);
|
||||
}
|
||||
|
||||
.atk-pagination-wrap {
|
||||
z-index: 200;
|
||||
position: fixed;
|
||||
|
||||
@@ -111,6 +111,7 @@
|
||||
display: inline-block;
|
||||
font-size: 23px;
|
||||
position: relative;
|
||||
line-height: 1.6em;
|
||||
|
||||
&:after {
|
||||
content: ' ';
|
||||
@@ -130,6 +131,7 @@
|
||||
margin-top: 6px;
|
||||
flex-wrap: wrap;
|
||||
min-height: 23px;
|
||||
margin-bottom: 15px;
|
||||
|
||||
.atk-url-item {
|
||||
background: var(--at-color-bg-grey);
|
||||
@@ -165,7 +167,7 @@
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
padding: 20px 30px 6px 35px;
|
||||
padding: 0 30px 6px 35px;
|
||||
padding-bottom: 10px;
|
||||
|
||||
.atk-site-text-actions {
|
||||
|
||||
@@ -1,23 +1,8 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"baseUrl": ".",
|
||||
"outDir": "dist",
|
||||
"target": "esnext",
|
||||
"useDefineForClassFields": true,
|
||||
"module": "esnext",
|
||||
"lib": ["esnext", "dom"],
|
||||
"moduleResolution": "node",
|
||||
"strict": true,
|
||||
"sourceMap": true,
|
||||
"experimentalDecorators": true,
|
||||
"resolveJsonModule": true,
|
||||
"esModuleInterop": true,
|
||||
"noEmit": true,
|
||||
"noImplicitAny": false,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noImplicitReturns": true,
|
||||
"paths": {
|
||||
"~/*": ["./*"],
|
||||
"@/*": ["./src/*"]
|
||||
|
||||
+1
-1
@@ -1,3 +1,3 @@
|
||||
import ArtalkSidebar from '../src/artalk-sidebar'
|
||||
import ArtalkSidebar from '../src/main'
|
||||
|
||||
export default ArtalkSidebar
|
||||
-1
@@ -1 +0,0 @@
|
||||
/// <reference types="vite/client" />
|
||||
@@ -13,29 +13,7 @@ export default defineConfig({
|
||||
build: {
|
||||
target: 'es2015',
|
||||
outDir: resolve(__dirname, "dist"),
|
||||
minify: 'terser',
|
||||
// lib: {
|
||||
// entry: resolve(__dirname, 'src/main.ts'),
|
||||
// name: 'ArtalkSidebar',
|
||||
// fileName: (format) => ((format == "umd") ? 'ArtalkSidebar.js' : `ArtalkSidebar.${format}.js`),
|
||||
// formats: ["es", "umd", "iife"]
|
||||
// },
|
||||
rollupOptions: {
|
||||
// 确保外部化处理那些你不想打包进库的依赖
|
||||
// external: ['artalk'],
|
||||
output: {
|
||||
assetFileNames: assetInfo => {
|
||||
if (/\.css$/.test(assetInfo.name)) {
|
||||
return 'ArtalkSidebar.css'
|
||||
}
|
||||
return "[name].[ext]"
|
||||
},
|
||||
// 在 UMD 构建模式下为这些外部化的依赖提供一个全局变量
|
||||
globals: {
|
||||
artalk: 'Artalk'
|
||||
}
|
||||
}
|
||||
}
|
||||
minify: 'terser'
|
||||
},
|
||||
plugins: [tsconfigPaths()],
|
||||
css: {
|
||||
|
||||
+24
-10
@@ -1,5 +1,5 @@
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Artalk DEMO</title>
|
||||
@@ -16,7 +16,8 @@
|
||||
.title > a:hover { margin-left:0 }
|
||||
.title > a > span { opacity:0 }
|
||||
.title > a:hover>span { opacity:1 }
|
||||
.desc { font-size:12px;color:#757e91 }
|
||||
.desc { font-size:12px;color:#697182 }
|
||||
body.dark-mode .desc { color:#848da3 }
|
||||
.social { margin-top:20px }
|
||||
.social > a:not(:last-child) { margin-right:2px }
|
||||
@media only screen and (max-width: 768px) {
|
||||
@@ -26,20 +27,32 @@
|
||||
}
|
||||
.float-btn { user-select: none;bottom: 25px;display: block;cursor: pointer;text-align: center;width: 60px;height: 37px;line-height: 37px;font-size: 13px;color: #757e91;background: #fff;opacity: 0.8;border-radius: 4px;border: 1px solid #eceff2;position: fixed; }
|
||||
.to-night { z-index: 99999;left: 25px;background: #1e2223;color: #fff; }
|
||||
body.dark-mode .to-night { background: #fff;border: 1px solid #2d3235;color: #0083ff; }
|
||||
body.dark-mode .to-night { background: #006fd9;border: 1px solid #2d3235;color: #fff; }
|
||||
.to-top { right: 25px; }
|
||||
</style>
|
||||
<!--<link rel="stylesheet"
|
||||
href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.5.1/styles/arta.min.css">
|
||||
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.5.1/highlight.min.js"></script>-->
|
||||
|
||||
<!-- For mobile testing -->
|
||||
<script src="https://unpkg.com/vconsole@latest/dist/vconsole.min.js"></script>
|
||||
<script>
|
||||
// VConsole will be exported to `window.VConsole` by default.
|
||||
if (navigator.userAgentData.mobile) {
|
||||
var vConsole = new window.VConsole();
|
||||
}
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="card billboard atk-fade-in">
|
||||
<div class="title"><a href="https://github.com/ArtalkJS/Artalk" target="_blank"><span>『 </span>Artalk<span> 』</span></a></div>
|
||||
<div class="desc">一款简洁的自托管评论系统 <span id="ArtalkPV"></span></div>
|
||||
<div class="social">
|
||||
<a href="https://www.npmjs.com/package/artalk" target="_blank"><img src="https://img.shields.io/npm/v/artalk.svg?style=flat-square"></a>
|
||||
<a href="https://www.npmjs.com/package/artalk" target="_blank"><img src="https://img.shields.io/npm/dt/artalk.svg?style=flat-square"></a>
|
||||
<a href="https://github.com/ArtalkJS/Artalk/commits/master" target="_blank"><img src="https://img.shields.io/github/last-commit/ArtalkJS/Artalk?style=flat-square"></a>
|
||||
<a href="https://github.com/ArtalkJS/Artalk/blob/master/LICENSE" target="_blank"><img src="https://img.shields.io/github/license/ArtalkJS/Artalk.svg?style=flat-square"></a>
|
||||
<a href="https://github.com/ArtalkJS/Artalk" target="_blank"><img src="https://img.shields.io/github/stars/ArtalkJS/Artalk?style=flat-square"></a>
|
||||
<a href="https://www.npmjs.com/package/artalk" aria-label="npm package version" target="_blank"><img src="https://img.shields.io/npm/v/artalk.svg?style=flat-square"></a>
|
||||
<a href="https://www.npmjs.com/package/artalk" aria-label="npm package download number" target="_blank"><img src="https://img.shields.io/npm/dt/artalk.svg?style=flat-square"></a>
|
||||
<a href="https://github.com/ArtalkJS/Artalk/commits/master" aria-label="last commit" target="_blank"><img src="https://img.shields.io/github/last-commit/ArtalkJS/Artalk?style=flat-square"></a>
|
||||
<a href="https://github.com/ArtalkJS/Artalk/blob/master/LICENSE" aria-label="open source license" target="_blank"><img src="https://img.shields.io/github/license/ArtalkJS/Artalk.svg?style=flat-square"></a>
|
||||
<a href="https://github.com/ArtalkJS/Artalk" aria-label="GitHub star number" target="_blank"><img src="https://img.shields.io/github/stars/ArtalkJS/Artalk?style=flat-square"></a>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card atk-fade-in">
|
||||
@@ -54,8 +67,9 @@
|
||||
el: '#comments',
|
||||
pageKey: 'https://artalk.js.org/',
|
||||
pageTitle: 'Artalk Home',
|
||||
server: (import.meta.env.MODE === 'development') ? 'http://localhost:23366/api' : 'https://artalk.qwqaq.com/api',
|
||||
site: 'ArtalkDemo',
|
||||
server: (import.meta.env.DEV) ? 'http://localhost:23366' : 'https://artalk.qwqaq.com',
|
||||
site: 'ArtalkDocs',
|
||||
//useBackendConf: true,
|
||||
});
|
||||
|
||||
window.artalk = artalk;
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
{
|
||||
"name": "artalk",
|
||||
"version": "2.1.7",
|
||||
"license": "GPL-3.0",
|
||||
"version": "2.3.1",
|
||||
"backendMinVersion": "2.1.7",
|
||||
"license": "LGPL-3.0",
|
||||
"description": "A Selfhosted Comment System",
|
||||
"keywords": [
|
||||
"comment-system",
|
||||
@@ -24,20 +25,22 @@
|
||||
"types": "./types/index.d.ts",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "yarn lint && vite build",
|
||||
"build": "pnpm lint && vite build && pnpm build:lite",
|
||||
"build:lite": "vite build --config vite-lite.config.ts",
|
||||
"build:demo": "vite build --config vite-demo.config.ts",
|
||||
"serve": "vite preview",
|
||||
"deploy": "gh-pages -d deploy",
|
||||
"predeploy": "yarn run build && yarn run build:demo && yarn run copy:deploy",
|
||||
"predeploy": "pnpm build && pnpm build:demo && pnpm copy:deploy",
|
||||
"copy:deploy": "cp -r dist deploy && cp CNAME deploy",
|
||||
"lint": "eslint --ext .js,.ts src"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/marked": "^4.0.3"
|
||||
"@types/marked": "4.0.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"hanabi": "^0.4.0",
|
||||
"insane": "^2.6.2",
|
||||
"marked": "^4.0.14"
|
||||
"marked": "^4.0.16",
|
||||
"abortcontroller-polyfill": "^1.7.3"
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
import Context from '../context'
|
||||
import { CommentData, ListData, UserData, PageData, SiteData, NotifyData } from '~/types/artalk-data'
|
||||
import ArtalkConfig from '~/types/artalk-config'
|
||||
import Context from '~/types/context'
|
||||
import { Fetch, ToFormData, POST, GET } from './request'
|
||||
import * as Utils from '../lib/utils'
|
||||
import 'abortcontroller-polyfill/dist/polyfill-patch-fetch'
|
||||
|
||||
export default class Api {
|
||||
private ctx: Context
|
||||
@@ -9,7 +11,7 @@ export default class Api {
|
||||
|
||||
constructor (ctx: Context) {
|
||||
this.ctx = ctx
|
||||
this.baseURL = ctx.conf.server
|
||||
this.baseURL = `${ctx.conf.server}/api`
|
||||
}
|
||||
|
||||
// ============================
|
||||
@@ -45,7 +47,7 @@ export default class Api {
|
||||
content: comment.content,
|
||||
rid: comment.rid,
|
||||
page_key: comment.page_key,
|
||||
ua: await Utils.getCorrectUserAgent(), // 需要后端支持,获取修正后的 UA (针对 Win11)
|
||||
ua: await Utils.getCorrectUserAgent(), // 需要后端支持,获取修正后的 UA
|
||||
}
|
||||
|
||||
if (comment.page_title) params.page_title = comment.page_title
|
||||
@@ -94,8 +96,6 @@ export default class Api {
|
||||
/** 用户 · 获取 */
|
||||
public userGet(name: string, email: string) {
|
||||
const ctrl = new AbortController()
|
||||
const { signal } = ctrl
|
||||
|
||||
const params: any = {
|
||||
name, email, site_name: (this.ctx.conf.site || '')
|
||||
}
|
||||
@@ -103,7 +103,7 @@ export default class Api {
|
||||
const req = Fetch(this.ctx, `${this.baseURL}/user-get`, {
|
||||
method: 'POST',
|
||||
body: ToFormData(params),
|
||||
signal,
|
||||
signal: ctrl.signal,
|
||||
}).then((json) => ({
|
||||
user: json.data.user as UserData|null,
|
||||
is_login: json.data.is_login as boolean,
|
||||
@@ -117,6 +117,15 @@ export default class Api {
|
||||
}
|
||||
}
|
||||
|
||||
/** 用户 · 登录状态 */
|
||||
public async loginStatus() {
|
||||
const data = await POST<any>(this.ctx, `${this.baseURL}/login-status`, {
|
||||
name: this.ctx.user.data.nick,
|
||||
email: this.ctx.user.data.email
|
||||
})
|
||||
return (data || { is_login: false, is_admin: false }) as { is_login: boolean, is_admin: boolean }
|
||||
}
|
||||
|
||||
// ============================
|
||||
// 页面 Page
|
||||
// ============================
|
||||
@@ -158,13 +167,14 @@ export default class Api {
|
||||
}
|
||||
|
||||
/** 页面 · 数据更新 */
|
||||
public async pageFetch(id: number) {
|
||||
const params: any = {
|
||||
id,
|
||||
}
|
||||
public async pageFetch(id?: number, siteName?: string, getStatus?: boolean) {
|
||||
const params: any = {}
|
||||
if (id) params.id = id
|
||||
if (siteName) params.site_name = siteName
|
||||
if (getStatus) params.get_status = getStatus
|
||||
|
||||
const d = await POST<any>(this.ctx, `${this.baseURL}/admin/page-fetch`, params)
|
||||
return (d.page as PageData)
|
||||
return (d as any)
|
||||
}
|
||||
|
||||
// ============================
|
||||
@@ -264,19 +274,100 @@ export default class Api {
|
||||
return p.pv as number
|
||||
}
|
||||
|
||||
/** 统计 */
|
||||
public async stat(
|
||||
type: 'latest_comments'|'latest_pages'|'pv_most_pages'|'comment_most_pages'|
|
||||
'page_pv'|'site_pv'|'page_comment'|'site_comment',
|
||||
pageKeys?: string|string[],
|
||||
limit?: number
|
||||
) {
|
||||
const params: any = {
|
||||
type,
|
||||
site_name: this.ctx.conf.site || '',
|
||||
}
|
||||
|
||||
if (pageKeys) params.page_keys = Array.isArray(pageKeys) ? pageKeys.join(',') : pageKeys
|
||||
if (limit) params.limit = limit
|
||||
|
||||
const data = await POST<PageData[]|CommentData[]|object|number>(this.ctx, `${this.baseURL}/stat`, params)
|
||||
return data
|
||||
}
|
||||
|
||||
/** 图片上传 */
|
||||
public async imgUpload(file: File) {
|
||||
const params: any = {
|
||||
name: this.ctx.user.data.nick,
|
||||
email: this.ctx.user.data.email,
|
||||
page_key: this.ctx.conf.pageKey,
|
||||
}
|
||||
|
||||
if (this.ctx.conf.site) params.site_name = this.ctx.conf.site
|
||||
|
||||
const form = ToFormData(params)
|
||||
form.set('file', file)
|
||||
|
||||
const init: RequestInit = {
|
||||
method: 'POST',
|
||||
body: form
|
||||
}
|
||||
|
||||
const json = await Fetch(this.ctx, `${this.baseURL}/img-upload`, init)
|
||||
return ((json.data || {}) as any) as { img_file: string, img_url: string }
|
||||
}
|
||||
|
||||
/** 获取配置 */
|
||||
public async conf() {
|
||||
const data = await POST<any>(this.ctx, `${this.baseURL}/conf`)
|
||||
const conf = (data.frontend_conf || {}) as ArtalkConfig
|
||||
|
||||
// Patch: `emoticons` config string to json
|
||||
if (conf.emoticons && typeof conf.emoticons === "string") {
|
||||
conf.emoticons = conf.emoticons.trim()
|
||||
if (conf.emoticons.startsWith("[") || conf.emoticons.startsWith("{")) {
|
||||
conf.emoticons = JSON.parse(conf.emoticons) // pase json
|
||||
} else if (conf.emoticons === "false") {
|
||||
conf.emoticons = false
|
||||
}
|
||||
}
|
||||
|
||||
return conf
|
||||
}
|
||||
|
||||
// ============================
|
||||
// 验证码
|
||||
// ============================
|
||||
|
||||
/** 验证码 · 获取 */
|
||||
public async captchaGet() {
|
||||
const data = await GET<any>(this.ctx, `${this.baseURL}/captcha/refresh`)
|
||||
const data = await POST<any>(this.ctx, `${this.baseURL}/captcha/refresh`)
|
||||
return (data.img_data || '') as string
|
||||
}
|
||||
|
||||
/** 验证码 · 检验 */
|
||||
public async captchaCheck(value: string) {
|
||||
const data = await GET<any>(this.ctx, `${this.baseURL}/captcha/check`, { value })
|
||||
const data = await POST<any>(this.ctx, `${this.baseURL}/captcha/check`, { value })
|
||||
return (data.img_data || '') as string
|
||||
}
|
||||
|
||||
/** 验证码 · 状态 */
|
||||
public async captchaStatus() {
|
||||
const data = await POST<any>(this.ctx, `${this.baseURL}/captcha/status`)
|
||||
return (data || { is_pass: false }) as { is_pass: boolean }
|
||||
}
|
||||
|
||||
// ============================
|
||||
// 管理员缓存操作
|
||||
// ============================
|
||||
|
||||
/** 缓存清除 */
|
||||
public cacheFlushAll() {
|
||||
const params: any = { flush_all: true }
|
||||
return POST(this.ctx, `${this.baseURL}/admin/cache-flush`, params)
|
||||
}
|
||||
|
||||
/** 缓存预热 */
|
||||
public cacheWarmUp() {
|
||||
const params: any = {}
|
||||
return POST(this.ctx, `${this.baseURL}/admin/cache-warm`, params)
|
||||
}
|
||||
}
|
||||
@@ -1,83 +1,58 @@
|
||||
import Context from '../context'
|
||||
import Context from '~/types/context'
|
||||
|
||||
/** 公共请求函数 */
|
||||
export async function Fetch(ctx: Context, input: RequestInfo, init: RequestInit, timeout?: number): Promise<any> {
|
||||
// JWT
|
||||
if (ctx.user.data.token) {
|
||||
const requestHeaders: HeadersInit = new Headers()
|
||||
requestHeaders.set('Authorization', `Bearer ${ctx.user.data.token}`)
|
||||
|
||||
init.headers = requestHeaders
|
||||
const headers = new Headers(init.headers) // 保留原有 headers
|
||||
headers.set('Authorization', `Bearer ${ctx.user.data.token}`)
|
||||
init.headers = headers
|
||||
}
|
||||
|
||||
// 请求操作
|
||||
try {
|
||||
const resp = await timeoutFetch(ctx, input, timeout || ctx.conf.reqTimeout || 15000, init)
|
||||
|
||||
let resp: Response
|
||||
if ((typeof timeout !== 'number' && ctx.conf.reqTimeout === 0) || timeout === 0) {
|
||||
resp = await fetch(input, init)
|
||||
} else {
|
||||
// 请求超时检测
|
||||
resp = await timeoutPromise(timeout || ctx.conf.reqTimeout || 15000, fetch(input, init))
|
||||
}
|
||||
const respHttpCode = resp.status
|
||||
const noAccessCodes = [401, 400]
|
||||
const isNoAccess = noAccessCodes.includes(respHttpCode)
|
||||
|
||||
const noAccessCodes = [401, 400]
|
||||
if (!resp.ok && !isNoAccess)
|
||||
throw new Error(`${ctx.$t('reqGot')} ${respHttpCode}`)
|
||||
|
||||
if (!resp.ok && !noAccessCodes.includes(resp.status)) throw new Error(`请求响应 ${resp.status}`)
|
||||
// 解析获取响应的 json
|
||||
let json: any = await resp.json()
|
||||
|
||||
// 解析获取响应的 json
|
||||
let json: any = await resp.json()
|
||||
|
||||
// 重新发起请求
|
||||
const recall = (resolve, reject) => {
|
||||
Fetch(ctx, input, init).then(d => {
|
||||
resolve(d)
|
||||
}).catch(err => {
|
||||
reject(err)
|
||||
})
|
||||
}
|
||||
|
||||
// 请求弹出层验证
|
||||
if (json.data && json.data.need_captcha) {
|
||||
// 请求需要验证码
|
||||
json = await (new Promise<any>((resolve, reject) => {
|
||||
ctx.trigger('checker-captcha', {
|
||||
imgData: json.data.img_data,
|
||||
onSuccess: () => {
|
||||
recall(resolve, reject)
|
||||
},
|
||||
onCancel: () => {
|
||||
reject(json)
|
||||
}
|
||||
})
|
||||
}))
|
||||
} else if ((json.data && json.data.need_login) || noAccessCodes.includes(resp.status)) {
|
||||
// 请求需要管理员权限
|
||||
json = await (new Promise<any>((resolve, reject) => {
|
||||
ctx.trigger('checker-admin', {
|
||||
onSuccess: () => {
|
||||
recall(resolve, reject)
|
||||
},
|
||||
onCancel: () => {
|
||||
reject(json)
|
||||
}
|
||||
})
|
||||
}))
|
||||
}
|
||||
|
||||
if (!json.success) throw json // throw 相当于 reject(json)
|
||||
|
||||
return json
|
||||
|
||||
} catch (err) {
|
||||
// 错误处理
|
||||
console.error(err)
|
||||
|
||||
if (err instanceof TypeError)
|
||||
throw new Error(`网络错误`)
|
||||
|
||||
throw err
|
||||
// 重新发起请求
|
||||
const recall = (resolve, reject) => {
|
||||
Fetch(ctx, input, init)
|
||||
.then(d => { resolve(d) })
|
||||
.catch(e => { reject(e) })
|
||||
}
|
||||
|
||||
// 请求弹出层验证
|
||||
if (json.data?.need_captcha) {
|
||||
// 请求需要验证码
|
||||
json = await (new Promise<any>((resolve, reject) => {
|
||||
ctx.checkCaptcha({
|
||||
imgData: json.data.img_data,
|
||||
iframe: json.data.iframe,
|
||||
onSuccess: () => { recall(resolve, reject) },
|
||||
onCancel: () => { reject(json) }
|
||||
})
|
||||
}))
|
||||
} else if (json.data?.need_login || isNoAccess) {
|
||||
// 请求需要管理员权限
|
||||
json = await (new Promise<any>((resolve, reject) => {
|
||||
ctx.checkAdmin({
|
||||
onSuccess: () => { recall(resolve, reject) },
|
||||
onCancel: () => { reject(json) }
|
||||
})
|
||||
}))
|
||||
}
|
||||
|
||||
if (!json.success) throw json // throw 相当于 reject(json)
|
||||
|
||||
return json
|
||||
}
|
||||
|
||||
/** 公共 POST 请求 */
|
||||
@@ -107,21 +82,16 @@ export function ToFormData(object: {[key: string]: any}): FormData {
|
||||
}
|
||||
|
||||
/** 我靠,fetch 一个 timeout,都要丑陋的实现 */
|
||||
function timeoutPromise<T>(ms: number, promise: Promise<T>): Promise<T> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const timeoutId = setTimeout(() => {
|
||||
reject(new Error("请求超时"))
|
||||
}, ms)
|
||||
|
||||
promise.then(
|
||||
(res) => {
|
||||
clearTimeout(timeoutId)
|
||||
resolve(res)
|
||||
},
|
||||
(err) => {
|
||||
clearTimeout(timeoutId)
|
||||
reject(err)
|
||||
}
|
||||
)
|
||||
function timeoutFetch(ctx: Context, url: RequestInfo, ms: number, opts: RequestInit) {
|
||||
const controller = new AbortController()
|
||||
opts.signal?.addEventListener('abort', () => controller.abort()) // 保留原有 signal 功能
|
||||
let promise = fetch(url, { ...opts, signal: controller.signal })
|
||||
if (ms > 0) {
|
||||
const timer = setTimeout(() => controller.abort(), ms)
|
||||
promise.finally(() => { clearTimeout(timer) })
|
||||
}
|
||||
promise = promise.catch((err) => {
|
||||
throw ((err || {}).name === 'AbortError') ? new Error(ctx.$t('reqAborted')) : err
|
||||
})
|
||||
return promise
|
||||
}
|
||||
+165
-91
@@ -1,75 +1,83 @@
|
||||
import './style/main.less'
|
||||
|
||||
import Context from './context'
|
||||
import ArtalkConfig from '~/types/artalk-config'
|
||||
import { EventPayloadMap, Handler } from '~/types/event'
|
||||
import ArtalkPlug from '~/types/plug'
|
||||
import Context from '~/types/context'
|
||||
import ConcreteContext from './context'
|
||||
import defaults from './defaults'
|
||||
import { internal as internalLocales } from './i18n'
|
||||
|
||||
import CheckerLauncher from './lib/checker'
|
||||
import Editor from './components/editor'
|
||||
import List from './components/list'
|
||||
import SidebarLayer from './components/sidebar-layer'
|
||||
import Editor from './editor'
|
||||
import List from './list'
|
||||
import SidebarLayer from './layer/sidebar-layer'
|
||||
|
||||
import { GetLayerWrap } from './components/layer'
|
||||
import { EventPayloadMap, Handler } from '~/types/event'
|
||||
import Api from './api'
|
||||
import Layer, { GetLayerWrap } from './layer'
|
||||
import * as Utils from './lib/utils'
|
||||
import * as Ui from './lib/ui'
|
||||
import * as Stat from './lib/stat'
|
||||
|
||||
/**
|
||||
* Artalk
|
||||
* @link https://artalk.js.org
|
||||
*
|
||||
* @website https://artalk.js.org
|
||||
*/
|
||||
export default class Artalk {
|
||||
public static readonly defaults: ArtalkConfig = defaults
|
||||
|
||||
public ctx: Context
|
||||
public conf: ArtalkConfig
|
||||
public $root: HTMLElement
|
||||
public conf!: ArtalkConfig
|
||||
public ctx!: Context
|
||||
public $root!: HTMLElement
|
||||
|
||||
public checkerLauncher: CheckerLauncher
|
||||
public editor: Editor
|
||||
public list: List
|
||||
public sidebarLayer: SidebarLayer
|
||||
public checkerLauncher!: CheckerLauncher
|
||||
public editor!: Editor
|
||||
public list!: List
|
||||
public sidebarLayer!: SidebarLayer
|
||||
|
||||
constructor (customConf: ArtalkConfig) {
|
||||
// 配置
|
||||
this.conf = { ...Artalk.defaults, ...customConf }
|
||||
this.conf.server = this.conf.server.replace(/\/$/, '')
|
||||
protected static Plugins: ArtalkPlug[] = [
|
||||
Stat.PvCountWidget
|
||||
]
|
||||
|
||||
// 默认 pageKey
|
||||
if (!this.conf.pageKey) {
|
||||
this.conf.pageKey = `${window.location.protocol}//${window.location.host}${window.location.pathname}`
|
||||
}
|
||||
constructor(customConf: Partial<ArtalkConfig>) {
|
||||
/* 初始化基本配置 */
|
||||
this.conf = Artalk.HandelBaseConf(customConf)
|
||||
if (this.conf.el instanceof HTMLElement) this.$root = this.conf.el
|
||||
|
||||
// 装载元素
|
||||
try {
|
||||
const $root = document.querySelector<HTMLElement>(this.conf.el)
|
||||
if (!$root) throw Error(`Sorry, target element "${this.conf.el}" was not found.`)
|
||||
this.$root = $root
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
throw new Error('Please check your Artalk `el` config.')
|
||||
}
|
||||
/* 初始化 Context */
|
||||
this.ctx = new ConcreteContext(this.conf, this.$root)
|
||||
|
||||
// Context 初始化
|
||||
this.ctx = new Context(this.$root, this.conf)
|
||||
// @ts-ignore 远程加载引用后端的配置
|
||||
if (this.conf.useBackendConf) return this.loadConfRemoteAndInitComponents()
|
||||
|
||||
// 界面初始化
|
||||
this.$root.classList.add('artalk')
|
||||
this.$root.innerHTML = ''
|
||||
/* 初始化组件 */
|
||||
this.initComponents()
|
||||
}
|
||||
|
||||
/** 组件初始化 */
|
||||
private initComponents() {
|
||||
this.initLocale()
|
||||
this.initLayer()
|
||||
this.initDarkMode()
|
||||
Utils.initMarked(this.ctx)
|
||||
|
||||
// 组件初始化
|
||||
// CheckerLauncher
|
||||
this.checkerLauncher = new CheckerLauncher(this.ctx)
|
||||
this.ctx.setCheckerLauncher(this.checkerLauncher)
|
||||
|
||||
// 编辑器
|
||||
this.editor = new Editor(this.ctx)
|
||||
this.ctx.setEditor(this.editor)
|
||||
this.$root.appendChild(this.editor.$el)
|
||||
|
||||
// 评论列表
|
||||
this.list = new List(this.ctx)
|
||||
this.ctx.setList(this.list)
|
||||
this.$root.appendChild(this.list.$el)
|
||||
|
||||
// 侧边栏
|
||||
this.sidebarLayer = new SidebarLayer(this.ctx)
|
||||
this.ctx.setSidebarLayer(this.sidebarLayer)
|
||||
this.$root.appendChild(this.sidebarLayer.$el)
|
||||
|
||||
// 评论获取
|
||||
@@ -78,56 +86,125 @@ export default class Artalk {
|
||||
// 事件绑定初始化
|
||||
this.initEventBind()
|
||||
|
||||
// 其他
|
||||
this.initPV()
|
||||
// 插件初始化
|
||||
Artalk.Plugins.forEach(plugin => {
|
||||
if (typeof plugin === 'function')
|
||||
plugin(this.ctx)
|
||||
})
|
||||
}
|
||||
|
||||
/** 事件绑定 · 初始化 */
|
||||
/** 基本配置初始化 */
|
||||
private static HandelBaseConf(customConf: Partial<ArtalkConfig>): ArtalkConfig {
|
||||
// 合并默认配置
|
||||
const conf: ArtalkConfig = Utils.mergeDeep(Artalk.defaults, customConf)
|
||||
|
||||
// 绑定元素
|
||||
if (typeof conf.el === 'string' && !!conf.el) {
|
||||
try {
|
||||
const findEl = document.querySelector<HTMLElement>(conf.el)
|
||||
if (!findEl) throw Error(`Target element "${conf.el}" was not found.`)
|
||||
conf.el = findEl
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
throw new Error('Please check your Artalk `el` config.')
|
||||
}
|
||||
}
|
||||
|
||||
// 服务器配置
|
||||
conf.server = conf.server.replace(/\/$/, '').replace(/\/api\/?$/, '')
|
||||
|
||||
// 默认 pageKey
|
||||
if (!conf.pageKey) {
|
||||
// @link http://bl.ocks.org/abernier/3070589
|
||||
conf.pageKey = `${window.location.pathname}`
|
||||
}
|
||||
|
||||
// 默认 pageTitle
|
||||
if (!conf.pageTitle) {
|
||||
conf.pageTitle = `${document.title}`
|
||||
}
|
||||
|
||||
return conf
|
||||
}
|
||||
|
||||
/** 初始化组件根据远程加载的配置 */
|
||||
private async loadConfRemoteAndInitComponents() {
|
||||
await this.loadConfRemote()
|
||||
this.initComponents()
|
||||
return this
|
||||
}
|
||||
|
||||
/** 远程加载配置 */
|
||||
private async loadConfRemote() {
|
||||
Ui.showLoading(this.$root)
|
||||
let backendConf = {}
|
||||
try {
|
||||
backendConf = await this.ctx.getApi().conf()
|
||||
} catch (err) { console.error("Load config from remote err", err) }
|
||||
this.ctx.conf = Utils.mergeDeep(this.ctx.conf, backendConf)
|
||||
Ui.hideLoading(this.$root)
|
||||
}
|
||||
|
||||
/** 事件绑定初始化 */
|
||||
private initEventBind() {
|
||||
// 锚点快速跳转评论
|
||||
window.addEventListener('hashchange', () => {
|
||||
this.list.goToCommentDelay = false
|
||||
this.list.checkGoToCommentByUrlHash()
|
||||
})
|
||||
|
||||
// 仅管理员显示控制
|
||||
this.ctx.on('check-admin-show-el', () => {
|
||||
const items: HTMLElement[] = []
|
||||
|
||||
this.$root.querySelectorAll<HTMLElement>(`[atk-only-admin-show]`).forEach(item => items.push(item))
|
||||
|
||||
// for layer
|
||||
const { $wrap: $layerWrap } = GetLayerWrap(this.ctx)
|
||||
if ($layerWrap) $layerWrap.querySelectorAll<HTMLElement>(`[atk-only-admin-show]`).forEach(item => items.push(item))
|
||||
|
||||
// for sidebar
|
||||
// TODO: 这个其实应该写在 packages/artalk-sidebar 里面的
|
||||
const $sidebarEl = document.querySelector<HTMLElement>('.atk-sidebar')
|
||||
if ($sidebarEl) $sidebarEl.querySelectorAll<HTMLElement>(`[atk-only-admin-show]`).forEach(item => items.push(item))
|
||||
|
||||
items.forEach(($item: HTMLElement) => {
|
||||
if (this.ctx.user.data.isAdmin)
|
||||
$item.classList.remove('atk-hide')
|
||||
else
|
||||
$item.classList.add('atk-hide')
|
||||
})
|
||||
})
|
||||
|
||||
// 本地用户数据变更
|
||||
this.ctx.on('user-changed', () => {
|
||||
this.ctx.trigger('check-admin-show-el')
|
||||
this.ctx.trigger('list-refresh-ui')
|
||||
this.ctx.checkAdminShowEl()
|
||||
this.ctx.listRefreshUI()
|
||||
})
|
||||
}
|
||||
|
||||
/** 重新加载 */
|
||||
public reload() {
|
||||
this.list.fetchComments(0)
|
||||
/** 语言初始化 */
|
||||
private initLocale() {
|
||||
if (typeof this.conf.locale === 'string') {
|
||||
if (this.conf.locale === 'auto') { // 自动切换
|
||||
this.conf.locale = ((navigator.languages) ? navigator.languages[0] : navigator.language)
|
||||
}
|
||||
|
||||
this.conf.locale = this.conf.locale.replace(
|
||||
/^([a-zA-Z]+)(-[a-zA-Z]+)?$/,
|
||||
(_, p1: string, p2: string) => (p1.toLowerCase() + (p2 || '').toUpperCase())
|
||||
)
|
||||
|
||||
if (!internalLocales[this.conf.locale]) { // 语言不存在时,使用 en
|
||||
console.log(`Locale "${this.conf.locale}" not found.`)
|
||||
this.conf.locale = 'en'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 暗黑模式 · 初始化 */
|
||||
public initDarkMode() {
|
||||
/** Layer 初始化 */
|
||||
private initLayer() {
|
||||
// 记录页面原始 Styles
|
||||
Layer.BodyOrgOverflow = document.body.style.overflow
|
||||
Layer.BodyOrgPaddingRight = document.body.style.paddingRight
|
||||
}
|
||||
|
||||
/** 暗黑模式初始化 */
|
||||
private initDarkMode() {
|
||||
if (this.conf.darkMode === 'auto') {
|
||||
// 自动切换暗黑模式,事件监听
|
||||
const darkModeMedia = window.matchMedia('(prefers-color-scheme: dark)')
|
||||
darkModeMedia.addEventListener('change', (e) => { this.setDarkMode(e.matches) })
|
||||
this.setDarkMode(darkModeMedia.matches)
|
||||
} else {
|
||||
this.setDarkMode(this.conf.darkMode || false)
|
||||
}
|
||||
}
|
||||
|
||||
/** 设置暗黑模式 */
|
||||
public setDarkMode(darkMode: boolean) {
|
||||
const darkModeClassName = 'atk-dark-mode'
|
||||
|
||||
this.ctx.conf.darkMode = darkMode
|
||||
this.ctx.trigger('conf-updated')
|
||||
|
||||
if (this.conf.darkMode) {
|
||||
this.$root.classList.add(darkModeClassName)
|
||||
} else {
|
||||
@@ -145,26 +222,6 @@ export default class Artalk {
|
||||
}
|
||||
}
|
||||
|
||||
/** 暗黑模式 · 设定 */
|
||||
public setDarkMode(darkMode: boolean) {
|
||||
this.ctx.conf.darkMode = darkMode
|
||||
this.initDarkMode()
|
||||
}
|
||||
|
||||
/** PV */
|
||||
public async initPV() {
|
||||
if (!this.conf.pvEl || !document.querySelector(this.conf.pvEl))
|
||||
return
|
||||
|
||||
const $pv = document.querySelector<HTMLElement>(this.conf.pvEl)!
|
||||
// $pv.innerText = '-' // 默认占位符
|
||||
const pvNum = await new Api(this.ctx).pv()
|
||||
if (Number.isNaN(Number(pvNum)))
|
||||
return
|
||||
|
||||
$pv.innerText = String(pvNum)
|
||||
}
|
||||
|
||||
/** 监听事件 */
|
||||
public on<K extends keyof EventPayloadMap>(name: K, handler: Handler<EventPayloadMap[K]>) {
|
||||
this.ctx.on(name, handler, 'external')
|
||||
@@ -179,4 +236,21 @@ export default class Artalk {
|
||||
public trigger<K extends keyof EventPayloadMap>(name: K, payload?: EventPayloadMap[K]) {
|
||||
this.ctx.trigger(name, payload, 'external')
|
||||
}
|
||||
|
||||
/** 重新加载 */
|
||||
public reload() {
|
||||
this.ctx.listReload()
|
||||
}
|
||||
|
||||
/** Use Plugin */
|
||||
public static Use(plugin: ArtalkPlug) {
|
||||
this.Plugins.push(plugin)
|
||||
}
|
||||
|
||||
/** 装载数量统计元素 */
|
||||
public static LoadCountWidget(customConf: Partial<ArtalkConfig>) {
|
||||
const conf = this.HandelBaseConf(customConf)
|
||||
const ctx = new ConcreteContext(conf)
|
||||
Stat.initCountWidget({ ctx, pvAdd: false })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import Comment from './comment'
|
||||
import ActionBtn from '../components/action-btn'
|
||||
|
||||
export default class CommentActions {
|
||||
private comment: Comment
|
||||
|
||||
private get ctx() { return this.comment.ctx }
|
||||
private get data() { return this.comment.getData() }
|
||||
private get cConf() { return this.comment.getConf() }
|
||||
|
||||
public constructor(comment: Comment) {
|
||||
this.comment = comment
|
||||
}
|
||||
|
||||
/** 投票操作 */
|
||||
public vote(type: 'up'|'down') {
|
||||
const actionBtn = (type === 'up') ? this.comment.getRender().voteBtnUp : this.comment.getRender().voteBtnDown
|
||||
|
||||
this.ctx.getApi().vote(this.data.id, `comment_${type}`)
|
||||
.then((v) => {
|
||||
this.data.vote_up = v.up
|
||||
this.data.vote_down = v.down
|
||||
this.comment.getRender().voteBtnUp?.updateText()
|
||||
this.comment.getRender().voteBtnDown?.updateText()
|
||||
})
|
||||
.catch((err) => {
|
||||
actionBtn?.setError(this.ctx.$t('voteFail'))
|
||||
console.log(err)
|
||||
})
|
||||
}
|
||||
|
||||
/** 管理员 - 评论状态修改 */
|
||||
public adminEdit(type: 'collapsed'|'pending'|'pinned', btnElem: ActionBtn) {
|
||||
if (btnElem.isLoading) return // 若正在修改中
|
||||
|
||||
btnElem.setLoading(true, `${this.ctx.$t('editing')}...`)
|
||||
|
||||
// 克隆并修改当前数据
|
||||
const modify = { ...this.data }
|
||||
if (type === 'collapsed') {
|
||||
modify.is_collapsed = !modify.is_collapsed
|
||||
} else if (type === 'pending') {
|
||||
modify.is_pending = !modify.is_pending
|
||||
} else if (type === 'pinned') {
|
||||
modify.is_pinned = !modify.is_pinned
|
||||
}
|
||||
|
||||
this.ctx.getApi().commentEdit(modify).then((data) => {
|
||||
btnElem.setLoading(false)
|
||||
|
||||
// 刷新当前 Comment UI
|
||||
this.comment.setData(data)
|
||||
|
||||
// 刷新 List UI
|
||||
this.ctx.listRefreshUI()
|
||||
}).catch((err) => {
|
||||
console.error(err)
|
||||
btnElem.setError(this.ctx.$t('editFail'))
|
||||
})
|
||||
}
|
||||
|
||||
/** 管理员 - 评论删除 */
|
||||
public adminDelete(btnElem: ActionBtn) {
|
||||
if (btnElem.isLoading) return // 若正在删除中
|
||||
|
||||
btnElem.setLoading(true, `${this.ctx.$t('deleting')}...`)
|
||||
this.ctx.getApi().commentDel(this.data.id, this.data.site_name)
|
||||
.then(() => {
|
||||
btnElem.setLoading(false)
|
||||
if (this.cConf.onDelete) this.cConf.onDelete(this.comment)
|
||||
})
|
||||
.catch((e) => {
|
||||
console.error(e)
|
||||
btnElem.setError(this.ctx.$t('deleteFail'))
|
||||
})
|
||||
}
|
||||
|
||||
/** 快速跳转到该评论 */
|
||||
public goToReplyComment() {
|
||||
const origHash = window.location.hash
|
||||
const modifyHash = `#atk-comment-${this.data.rid}`
|
||||
|
||||
window.location.hash = modifyHash
|
||||
if (modifyHash === origHash) window.dispatchEvent(new Event('hashchange')) // 强制触发事件
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -4,7 +4,7 @@
|
||||
<div class="atk-main">
|
||||
<div class="atk-header">
|
||||
<span class="atk-item atk-nick"></span>
|
||||
<span class="atk-item atk-badge"></span>
|
||||
<span class="atk-badge-wrap"></span>
|
||||
<span class="atk-item atk-date"></span>
|
||||
</div>
|
||||
<div class="atk-body">
|
||||
@@ -0,0 +1,191 @@
|
||||
import { CommentData } from '~/types/artalk-data'
|
||||
import Context from '~/types/context'
|
||||
import Component from '../lib/component'
|
||||
import * as Utils from '../lib/utils'
|
||||
import UADetect from '../lib/detect'
|
||||
import CommentRender from './render'
|
||||
import CommentActions from './actions'
|
||||
|
||||
export interface CommentConf {
|
||||
isUnread?: boolean
|
||||
openURL?: string
|
||||
isFlatMode: boolean
|
||||
replyTo?: CommentData
|
||||
afterRender?: () => void
|
||||
openEvt?: () => void
|
||||
onReplyBtnClick?: Function
|
||||
onDelete?: Function
|
||||
}
|
||||
|
||||
export default class Comment extends Component {
|
||||
private renderInstance: CommentRender
|
||||
private actionInstance: CommentActions
|
||||
|
||||
private data: CommentData
|
||||
private cConf: CommentConf
|
||||
|
||||
private parent: Comment|null
|
||||
private children: Comment[] = []
|
||||
|
||||
private nestCurt: number // 当前嵌套层数
|
||||
private nestMax: number // 最大嵌套层数
|
||||
|
||||
constructor(ctx: Context, data: CommentData, conf: CommentConf) {
|
||||
super(ctx)
|
||||
|
||||
// 最大嵌套数
|
||||
this.nestMax = ctx.conf.nestMax || 3
|
||||
|
||||
this.cConf = conf
|
||||
this.data = { ...data }
|
||||
this.data.date = this.data.date.replace(/-/g, '/') // 解决 Safari 日期解析 NaN 问题
|
||||
|
||||
this.parent = null
|
||||
this.nestCurt = 1 // 现在已嵌套 n 层
|
||||
|
||||
this.actionInstance = new CommentActions(this)
|
||||
this.renderInstance = new CommentRender(this)
|
||||
}
|
||||
|
||||
/** 渲染 UI */
|
||||
public render() {
|
||||
const newEl = this.renderInstance.render()
|
||||
|
||||
if (this.$el) this.$el.replaceWith(newEl)
|
||||
this.$el = newEl
|
||||
|
||||
if (this.cConf.afterRender) this.cConf.afterRender()
|
||||
}
|
||||
|
||||
/** 获取评论操作实例对象 */
|
||||
public getActions() {
|
||||
return this.actionInstance
|
||||
}
|
||||
|
||||
/** 获取评论渲染器实例对象 */
|
||||
public getRender() {
|
||||
return this.renderInstance
|
||||
}
|
||||
|
||||
/** 获取评论数据 */
|
||||
public getData() {
|
||||
return this.data
|
||||
}
|
||||
|
||||
/** 设置数据 */
|
||||
public setData(data: CommentData) {
|
||||
this.data = data
|
||||
|
||||
this.render()
|
||||
this.getRender().playFadeAnimForBody()
|
||||
}
|
||||
|
||||
/** 获取父评论 */
|
||||
public getParent() {
|
||||
return this.parent
|
||||
}
|
||||
|
||||
/** 获取所有子评论 */
|
||||
public getChildren() {
|
||||
return this.children
|
||||
}
|
||||
|
||||
/** 获取当前嵌套层数 */
|
||||
public getNestCurt() {
|
||||
return this.nestCurt
|
||||
}
|
||||
|
||||
/** 判断是否为根评论 */
|
||||
public getIsRoot() {
|
||||
return this.data.rid === 0
|
||||
}
|
||||
|
||||
/** 获取评论 ID */
|
||||
public getID() {
|
||||
return this.data.id
|
||||
}
|
||||
|
||||
/** 置入子评论 */
|
||||
public putChild(childC: Comment, insertMode: 'append'|'prepend' = 'append') {
|
||||
childC.parent = this
|
||||
childC.nestCurt = this.nestCurt + 1 // 嵌套层数 +1
|
||||
|
||||
this.children.push(childC)
|
||||
|
||||
const $children = this.getChildrenEl()
|
||||
if (insertMode === 'append') $children.append(childC.getEl())
|
||||
else if (insertMode === 'prepend') $children.prepend(childC.getEl())
|
||||
|
||||
childC.getRender().playFadeAnim()
|
||||
|
||||
// 内容限高
|
||||
childC.getRender().checkHeightLimitArea('content')
|
||||
}
|
||||
|
||||
/** 获取存放子评论的元素对象 */
|
||||
public getChildrenEl(): HTMLElement {
|
||||
let $children = this.getRender().getChildrenWrap()
|
||||
|
||||
if (!$children) {
|
||||
// console.log(this.nestCurt)
|
||||
if (this.nestCurt < this.nestMax) {
|
||||
$children = this.getRender().renderChildrenWrap()
|
||||
} else {
|
||||
$children = this.parent!.getChildrenEl()
|
||||
}
|
||||
}
|
||||
|
||||
return $children
|
||||
}
|
||||
|
||||
/** 获取所有父评论 */
|
||||
public getParents() {
|
||||
const parents: Comment[] = []
|
||||
const once = (c: Comment) => {
|
||||
if (c.parent) {
|
||||
parents.push(c.parent)
|
||||
once(c.parent)
|
||||
}
|
||||
}
|
||||
|
||||
once(this)
|
||||
return parents
|
||||
}
|
||||
|
||||
/** 获取评论元素对象 */
|
||||
public getEl() {
|
||||
return this.$el
|
||||
}
|
||||
|
||||
/** 获取 Gravatar 头像 URL */
|
||||
public getGravatarURL() {
|
||||
return Utils.getGravatarURL(this.ctx, this.data.email_encrypted)
|
||||
}
|
||||
|
||||
/** 获取评论 markdown 解析后的内容 */
|
||||
public getContentMarked() {
|
||||
return Utils.marked(this.ctx, this.data.content)
|
||||
}
|
||||
|
||||
/** 获取格式化后的日期 */
|
||||
public getDateFormatted() {
|
||||
return Utils.timeAgo(new Date(this.data.date), this.ctx)
|
||||
}
|
||||
|
||||
/** 获取用户 UserAgent 浏览器 */
|
||||
public getUserUaBrowser() {
|
||||
const info = UADetect(this.data.ua)
|
||||
return `${info.browser} ${info.version}`
|
||||
}
|
||||
|
||||
/** 获取用户 UserAgent 系统 */
|
||||
public getUserUaOS() {
|
||||
const info = UADetect(this.data.ua)
|
||||
return `${info.os} ${info.osVersion}`
|
||||
}
|
||||
|
||||
/** 获取配置 */
|
||||
public getConf() {
|
||||
return this.cConf
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
import Comment from './comment'
|
||||
|
||||
export default Comment
|
||||
@@ -0,0 +1,425 @@
|
||||
import '../style/comment.less'
|
||||
|
||||
import * as Utils from '../lib/utils'
|
||||
import * as Ui from '../lib/ui'
|
||||
import ActionBtn from '../components/action-btn'
|
||||
import CommentHTML from './comment.html?raw'
|
||||
import Comment from './comment'
|
||||
|
||||
export default class CommentRender {
|
||||
private comment: Comment
|
||||
|
||||
private get ctx() { return this.comment.ctx }
|
||||
private get data() { return this.comment.getData() }
|
||||
private get cConf() { return this.comment.getConf() }
|
||||
|
||||
public $el!: HTMLElement
|
||||
public $main!: HTMLElement
|
||||
public $header!: HTMLElement
|
||||
public $headerNick!: HTMLElement
|
||||
public $headerBadgeWrap!: HTMLElement
|
||||
public $body!: HTMLElement
|
||||
public $content!: HTMLElement
|
||||
private $childrenWrap!: HTMLElement|null
|
||||
public $actions!: HTMLElement
|
||||
public voteBtnUp?: ActionBtn
|
||||
public voteBtnDown?: ActionBtn
|
||||
|
||||
public $replyTo?: HTMLElement // 回复评论内容 (平铺下显示)
|
||||
public $replyAt?: HTMLElement // 回复 AT(层级嵌套下显示)
|
||||
|
||||
public constructor(comment: Comment) {
|
||||
this.comment = comment
|
||||
}
|
||||
|
||||
public render() {
|
||||
this.$el = Utils.createElement(CommentHTML)
|
||||
|
||||
this.$main = this.$el.querySelector('.atk-main')!
|
||||
this.$header = this.$el.querySelector('.atk-header')!
|
||||
this.$body = this.$el.querySelector('.atk-body')!
|
||||
this.$content = this.$body.querySelector('.atk-content')!
|
||||
this.$actions = this.$el.querySelector('.atk-actions')!
|
||||
|
||||
this.$el.setAttribute('data-comment-id', `${this.data.id}`)
|
||||
|
||||
this.renderAvatar()
|
||||
this.renderHeader()
|
||||
this.renderContent()
|
||||
this.renderReplyAt()
|
||||
this.renderReplyTo()
|
||||
this.renderPending()
|
||||
this.renderActionBtn()
|
||||
|
||||
this.recoveryChildrenWrap()
|
||||
|
||||
return this.$el
|
||||
}
|
||||
|
||||
/** 初始化 - 评论头像 */
|
||||
private renderAvatar() {
|
||||
const $avatar = this.$el.querySelector<HTMLElement>('.atk-avatar')!
|
||||
const $avatarImg = Utils.createElement<HTMLImageElement>('<img />')
|
||||
$avatarImg.src = this.comment.getGravatarURL()
|
||||
if (this.data.link) {
|
||||
const $avatarA = Utils.createElement<HTMLLinkElement>('<a target="_blank" rel="noreferrer noopener nofollow"></a>')
|
||||
$avatarA.href = this.data.link
|
||||
$avatarA.append($avatarImg)
|
||||
$avatar.append($avatarA)
|
||||
} else {
|
||||
$avatar.append($avatarImg)
|
||||
}
|
||||
}
|
||||
|
||||
/** 初始化 - 评论信息 */
|
||||
private renderHeader() {
|
||||
this.$headerNick = this.$el.querySelector<HTMLElement>('.atk-nick')!
|
||||
|
||||
if (this.data.link) {
|
||||
const $nickA = Utils.createElement<HTMLLinkElement>('<a target="_blank" rel="noreferrer noopener nofollow"></a>')
|
||||
$nickA.innerText = this.data.nick
|
||||
$nickA.href = this.data.link
|
||||
this.$headerNick.append($nickA)
|
||||
} else {
|
||||
this.$headerNick.innerText = this.data.nick
|
||||
}
|
||||
|
||||
this.$headerBadgeWrap = this.$el.querySelector<HTMLElement>('.atk-badge-wrap')!
|
||||
this.$headerBadgeWrap.innerHTML = ''
|
||||
|
||||
const badgeText = this.data.badge_name
|
||||
const badgeColor = this.data.badge_color
|
||||
if (badgeText) {
|
||||
const $badge = Utils.createElement(`<span class="atk-badge"></span>`)
|
||||
$badge.innerText = badgeText.replace('管理员', this.ctx.$t('admin')) // i18n patch
|
||||
$badge.style.backgroundColor = badgeColor || ''
|
||||
this.$headerBadgeWrap.append($badge)
|
||||
}
|
||||
|
||||
if (this.data.is_pinned) {
|
||||
const $pinnedBadge = Utils.createElement(`<span class="atk-pinned-badge">${this.ctx.$t('pin')}</span>`) // 置顶徽章
|
||||
this.$headerBadgeWrap.append($pinnedBadge)
|
||||
}
|
||||
|
||||
const $date = this.$el.querySelector<HTMLElement>('.atk-date')!
|
||||
$date.innerText = this.comment.getDateFormatted()
|
||||
$date.setAttribute('data-atk-comment-date', String(+new Date(this.data.date)))
|
||||
|
||||
if (this.ctx.conf.uaBadge) {
|
||||
let $uaWrap = this.$header.querySelector('atk-ua-wrap')
|
||||
if (!$uaWrap) {
|
||||
$uaWrap = Utils.createElement(`<span class="atk-ua-wrap"></span>`)
|
||||
this.$header.append($uaWrap)
|
||||
}
|
||||
|
||||
$uaWrap.innerHTML = ''
|
||||
const $uaBrowser = Utils.createElement(`<span class="atk-ua ua-browser"></span>`)
|
||||
const $usOS = Utils.createElement(`<span class="atk-ua ua-os"></span>`)
|
||||
$uaBrowser.innerText = this.comment.getUserUaBrowser()
|
||||
$usOS.innerText = this.comment.getUserUaOS()
|
||||
$uaWrap.append($uaBrowser)
|
||||
$uaWrap.append($usOS)
|
||||
}
|
||||
}
|
||||
|
||||
/** 初始化 - 评论内容 */
|
||||
private renderContent() {
|
||||
if (!this.data.is_collapsed) {
|
||||
this.$content.innerHTML = this.comment.getContentMarked()
|
||||
this.$content.classList.remove('atk-hide', 'atk-collapsed')
|
||||
return
|
||||
}
|
||||
|
||||
// 内容 & 折叠
|
||||
this.$content.classList.add('atk-hide', 'atk-type-collapsed')
|
||||
const collapsedInfoEl = Utils.createElement(`
|
||||
<div class="atk-collapsed">
|
||||
<span class="atk-text">${this.ctx.$t('collapsedMsg')}</span>
|
||||
<span class="atk-show-btn">${this.ctx.$t('expand')}</span>
|
||||
</div>`)
|
||||
this.$body.insertAdjacentElement('beforeend', collapsedInfoEl)
|
||||
|
||||
const contentShowBtn = collapsedInfoEl.querySelector('.atk-show-btn')!
|
||||
contentShowBtn.addEventListener('click', (e) => {
|
||||
e.stopPropagation() // 防止穿透
|
||||
|
||||
if (this.$content.classList.contains('atk-hide')) {
|
||||
this.$content.innerHTML = this.comment.getContentMarked()
|
||||
this.$content.classList.remove('atk-hide')
|
||||
Ui.playFadeInAnim(this.$content)
|
||||
contentShowBtn.innerHTML = this.ctx.$t('collapse')
|
||||
} else {
|
||||
this.$content.innerHTML = ''
|
||||
this.$content.classList.add('atk-hide')
|
||||
contentShowBtn.innerHTML = this.ctx.$t('expand')
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/** 初始化 - 层级嵌套模式显示 At */
|
||||
private renderReplyAt() {
|
||||
if (this.cConf.isFlatMode || this.data.rid === 0) return // not 平铺模式 或 根评论
|
||||
if (!this.cConf.replyTo) return
|
||||
|
||||
this.$replyAt = Utils.createElement(`<span class="atk-item atk-reply-at"><span class="atk-arrow"></span><span class="atk-nick"></span></span>`)
|
||||
this.$replyAt.querySelector<HTMLElement>('.atk-nick')!.innerText = `${this.cConf.replyTo.nick}`
|
||||
this.$replyAt.onclick = () => { this.comment.getActions().goToReplyComment() }
|
||||
|
||||
this.$headerBadgeWrap.insertAdjacentElement('afterend', this.$replyAt)
|
||||
}
|
||||
|
||||
/** 初始化 - 回复的对象 */
|
||||
private renderReplyTo() {
|
||||
if (!this.cConf.isFlatMode) return // 仅平铺模式显示
|
||||
if (!this.cConf.replyTo) return
|
||||
|
||||
this.$replyTo = Utils.createElement(`
|
||||
<div class="atk-reply-to">
|
||||
<div class="atk-meta">${this.ctx.$t('reply')} <span class="atk-nick"></span>:</div>
|
||||
<div class="atk-content"></div>
|
||||
</div>`)
|
||||
const $nick = this.$replyTo.querySelector<HTMLElement>('.atk-nick')!
|
||||
$nick.innerText = `@${this.cConf.replyTo.nick}`
|
||||
$nick.onclick = () => { this.comment.getActions().goToReplyComment() }
|
||||
let replyContent = Utils.marked(this.ctx, this.cConf.replyTo.content)
|
||||
if (this.cConf.replyTo.is_collapsed) replyContent = `[${this.ctx.$t('collapsed')}]`
|
||||
this.$replyTo.querySelector<HTMLElement>('.atk-content')!.innerHTML = replyContent
|
||||
this.$body.prepend(this.$replyTo)
|
||||
}
|
||||
|
||||
/** 初始化 - 待审核状态 */
|
||||
private renderPending() {
|
||||
if (!this.data.is_pending) return
|
||||
|
||||
const pendingEl = Utils.createElement(`<div class="atk-pending">${this.ctx.$t('pendingMsg')}</div>`)
|
||||
this.$body.prepend(pendingEl)
|
||||
}
|
||||
|
||||
/** 初始化 - 评论操作按钮 */
|
||||
private renderActionBtn() {
|
||||
// 投票功能
|
||||
if (this.ctx.conf.vote) {
|
||||
// 赞同按钮
|
||||
this.voteBtnUp = new ActionBtn(this.ctx, () => `${this.ctx.$t('voteUp')} (${this.data.vote_up || 0})`).appendTo(this.$actions)
|
||||
this.voteBtnUp.setClick(() => {
|
||||
this.comment.getActions().vote('up')
|
||||
})
|
||||
|
||||
// 反对按钮
|
||||
if (this.ctx.conf.voteDown) {
|
||||
this.voteBtnDown = new ActionBtn(this.ctx, () => `${this.ctx.$t('voteDown')} (${this.data.vote_down || 0})`).appendTo(this.$actions)
|
||||
this.voteBtnDown.setClick(() => {
|
||||
this.comment.getActions().vote('down')
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 绑定回复按钮事件
|
||||
if (this.data.is_allow_reply) {
|
||||
const replyBtn = Utils.createElement(`<span>${this.ctx.$t('reply')}</span>`)
|
||||
this.$actions.append(replyBtn)
|
||||
replyBtn.addEventListener('click', (e) => {
|
||||
e.stopPropagation() // 防止穿透
|
||||
if (!this.cConf.onReplyBtnClick) {
|
||||
this.ctx.replyComment(this.data, this.$el)
|
||||
} else {
|
||||
this.cConf.onReplyBtnClick()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// 绑定折叠按钮事件
|
||||
const collapseBtn = new ActionBtn(this.ctx, {
|
||||
text: () => (this.data.is_collapsed ? this.ctx.$t('expand') : this.ctx.$t('collapse')),
|
||||
adminOnly: true
|
||||
})
|
||||
collapseBtn.appendTo(this.$actions)
|
||||
collapseBtn.setClick(() => {
|
||||
this.comment.getActions().adminEdit('collapsed', collapseBtn)
|
||||
})
|
||||
|
||||
// 绑定待审核按钮事件
|
||||
const pendingBtn = new ActionBtn(this.ctx, {
|
||||
text: () => (this.data.is_pending ? this.ctx.$t('pending') : this.ctx.$t('approved')),
|
||||
adminOnly: true
|
||||
})
|
||||
pendingBtn.appendTo(this.$actions)
|
||||
pendingBtn.setClick(() => {
|
||||
this.comment.getActions().adminEdit('pending', pendingBtn)
|
||||
})
|
||||
|
||||
// 绑定删除按钮事件
|
||||
const delBtn = new ActionBtn(this.ctx, {
|
||||
text: this.ctx.$t('delete'),
|
||||
confirm: true,
|
||||
confirmText: this.ctx.$t('deleteConfirm'),
|
||||
adminOnly: true,
|
||||
})
|
||||
delBtn.appendTo(this.$actions)
|
||||
delBtn.setClick(() => {
|
||||
this.comment.getActions().adminDelete(delBtn)
|
||||
})
|
||||
|
||||
// 绑定置顶按钮事件
|
||||
const pinnedBtn = new ActionBtn(this.ctx, {
|
||||
text: () => (this.data.is_pinned ? this.ctx.$t('unpin') : this.ctx.$t('pin')),
|
||||
adminOnly: true
|
||||
})
|
||||
pinnedBtn.appendTo(this.$actions)
|
||||
pinnedBtn.setClick(() => {
|
||||
this.comment.getActions().adminEdit('pinned', pendingBtn)
|
||||
})
|
||||
}
|
||||
|
||||
/** 内容限高检测 */
|
||||
public checkHeightLimit() {
|
||||
this.checkHeightLimitArea('content') // 评论内容限高
|
||||
this.checkHeightLimitArea('children') // 子评论部分限高(嵌套模式)
|
||||
}
|
||||
|
||||
/** 目标内容限高检测 */
|
||||
public checkHeightLimitArea(area: 'children'|'content') {
|
||||
// 参数准备
|
||||
const childrenMaxH = this.ctx.conf.heightLimit.children
|
||||
const contentMaxH = this.ctx.conf.heightLimit.content
|
||||
|
||||
if (area === 'children' && !childrenMaxH) return
|
||||
if (area === 'content' && !contentMaxH) return
|
||||
|
||||
// 限高
|
||||
let maxHeight: number
|
||||
if (area === 'children') maxHeight = childrenMaxH!
|
||||
if (area === 'content') maxHeight = contentMaxH!
|
||||
|
||||
// 检测指定元素
|
||||
const checkEl = ($el?: HTMLElement|null) => {
|
||||
if (!$el) return
|
||||
|
||||
// 是否超过高度
|
||||
if (Utils.getHeight($el) > maxHeight) {
|
||||
this.heightLimitAdd($el, maxHeight)
|
||||
}
|
||||
}
|
||||
|
||||
// 执行限高检测
|
||||
if (area === 'children') {
|
||||
checkEl(this.$childrenWrap)
|
||||
} else if (area === 'content') {
|
||||
checkEl(this.$content)
|
||||
checkEl(this.$replyTo)
|
||||
|
||||
// 若有图片 · 图片加载完后再检测一次
|
||||
Utils.onImagesLoaded(this.$content, () => {
|
||||
checkEl(this.$content)
|
||||
})
|
||||
if (this.$replyTo) {
|
||||
Utils.onImagesLoaded(this.$replyTo, () => {
|
||||
checkEl(this.$replyTo)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 移除限高 */
|
||||
private heightLimitRemove($el: HTMLElement) {
|
||||
if (!$el) return
|
||||
if (!$el.classList.contains('atk-height-limit')) return
|
||||
|
||||
$el.classList.remove('atk-height-limit')
|
||||
Array.from($el.children).forEach((e) => {
|
||||
if (e.classList.contains('atk-height-limit-btn')) e.remove()
|
||||
})
|
||||
$el.style.height = ''
|
||||
$el.style.overflow = ''
|
||||
}
|
||||
|
||||
/** 子评论区域移除限高 */
|
||||
public heightLimitRemoveForChildren() {
|
||||
if (!this.$childrenWrap) return
|
||||
this.heightLimitRemove(this.$childrenWrap)
|
||||
}
|
||||
|
||||
/** 内容限高区域新增 */
|
||||
private heightLimitAdd($el: HTMLElement, maxHeight: number) {
|
||||
if (!$el) return
|
||||
if ($el.classList.contains('atk-height-limit')) return
|
||||
|
||||
$el.classList.add('atk-height-limit')
|
||||
$el.style.height = `${maxHeight}px`
|
||||
$el.style.overflow = 'hidden'
|
||||
const $hideMoreOpenBtn = Utils.createElement(`<div class="atk-height-limit-btn">${this.ctx.$t('readMore')}</span>`)
|
||||
$hideMoreOpenBtn.onclick = (e) => {
|
||||
e.stopPropagation()
|
||||
this.heightLimitRemove($el)
|
||||
|
||||
// 子评论数等于 1,直接取消限高
|
||||
const children = this.comment.getChildren()
|
||||
if (children.length === 1) children[0].getRender().heightLimitRemove(children[0].getRender().$content)
|
||||
}
|
||||
$el.append($hideMoreOpenBtn)
|
||||
}
|
||||
|
||||
/** 渐出动画 */
|
||||
playFadeAnim() {
|
||||
Ui.playFadeInAnim(this.comment.getRender().$el)
|
||||
}
|
||||
|
||||
/** 渐出动画 · 评论内容区域 */
|
||||
playFadeAnimForBody() {
|
||||
Ui.playFadeInAnim(this.comment.getRender().$body)
|
||||
}
|
||||
|
||||
/** 获取子评论 Wrap */
|
||||
public getChildrenWrap() {
|
||||
return this.$childrenWrap
|
||||
}
|
||||
|
||||
/** 初始化子评论区域 Wrap */
|
||||
public renderChildrenWrap() {
|
||||
if (!this.$childrenWrap) {
|
||||
this.$childrenWrap = Utils.createElement('<div class="atk-comment-children"></div>')
|
||||
this.$main.append(this.$childrenWrap)
|
||||
}
|
||||
|
||||
return this.$childrenWrap
|
||||
}
|
||||
|
||||
/** 恢复原有的子评论区域 Wrap */
|
||||
public recoveryChildrenWrap() {
|
||||
if (this.$childrenWrap) {
|
||||
this.$main.append(this.$childrenWrap)
|
||||
}
|
||||
}
|
||||
|
||||
/** 设置已读 */
|
||||
public setUnread(val: boolean) {
|
||||
if (val) this.$el.classList.add('atk-unread')
|
||||
else this.$el.classList.remove('atk-unread')
|
||||
}
|
||||
|
||||
/** 设置为可点击的评论 */
|
||||
public setOpenable(val: boolean) {
|
||||
if (val) this.$el.classList.add('atk-openable')
|
||||
else this.$el.classList.remove('atk-openable')
|
||||
}
|
||||
|
||||
/** 设置点击评论打开置顶 URL */
|
||||
public setOpenURL(url: string) {
|
||||
this.setOpenable(true)
|
||||
this.$el.onclick = (evt) => {
|
||||
evt.preventDefault()
|
||||
window.open(url)
|
||||
|
||||
if (this.cConf.openEvt) this.cConf.openEvt()
|
||||
}
|
||||
}
|
||||
|
||||
/** 设置点击评论时的操作 */
|
||||
public setOpenAction(action: () => void) {
|
||||
this.setOpenable(true)
|
||||
this.$el.onclick = (evt) => {
|
||||
evt.preventDefault()
|
||||
action()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
import Context from '@/context'
|
||||
import Component from '@/lib/component'
|
||||
import * as Utils from '@/lib/utils'
|
||||
import * as Ui from '@/lib/ui'
|
||||
|
||||
export default class Example extends Component {
|
||||
constructor(ctx: Context) {
|
||||
super(ctx)
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import Context from '~/types/context'
|
||||
import * as Utils from '../lib/utils'
|
||||
|
||||
interface ActionBtnConf {
|
||||
@@ -18,6 +19,7 @@ interface ActionBtnConf {
|
||||
* 通用操作按钮
|
||||
*/
|
||||
export default class ActionBtn {
|
||||
private ctx: Context
|
||||
private conf: ActionBtnConf
|
||||
public $el: HTMLElement
|
||||
|
||||
@@ -31,7 +33,8 @@ export default class ActionBtn {
|
||||
public confirmRecTimer?: number // 确认消息复原定时器
|
||||
|
||||
/** 构造函数 */
|
||||
constructor(conf: ActionBtnConf|string|(() => string)) {
|
||||
constructor(ctx: Context, conf: ActionBtnConf|string|(() => string)) {
|
||||
this.ctx = ctx
|
||||
this.$el = Utils.createElement(`<span class="atk-common-action-btn"></span>`)
|
||||
|
||||
this.conf = (typeof conf !== 'object') ? ({ text: conf }) : conf
|
||||
@@ -73,7 +76,7 @@ export default class ActionBtn {
|
||||
if (!this.isConfirming) {
|
||||
this.isConfirming = true
|
||||
this.$el.classList.add('atk-btn-confirm')
|
||||
this.$el.innerText = this.conf.confirmText || '确认操作'
|
||||
this.$el.innerText = this.conf.confirmText || this.ctx.$t('actionConfirm')
|
||||
this.confirmRecTimer = window.setTimeout(() => confirmRestore(), 5000)
|
||||
return
|
||||
}
|
||||
@@ -107,7 +110,7 @@ export default class ActionBtn {
|
||||
this.isLoading = value
|
||||
if (value) {
|
||||
this.$el.classList.add('atk-btn-loading')
|
||||
this.$el.innerText = loadingText || '加载中...'
|
||||
this.$el.innerText = loadingText || `${this.ctx.$t('loading')}...`
|
||||
} else {
|
||||
this.$el.classList.remove('atk-btn-loading')
|
||||
this.$el.innerText = this.getText()
|
||||
|
||||
@@ -1,570 +0,0 @@
|
||||
import '../style/comment.less'
|
||||
|
||||
import Context from '../context'
|
||||
import Component from '../lib/component'
|
||||
import * as Utils from '../lib/utils'
|
||||
import * as Ui from '../lib/ui'
|
||||
import UADetect from '../lib/detect'
|
||||
import { CommentData } from '~/types/artalk-data'
|
||||
import CommentHTML from './html/comment.html?raw'
|
||||
import Api from '../api'
|
||||
import ActionBtn from './action-btn'
|
||||
|
||||
export default class Comment extends Component {
|
||||
public data: CommentData
|
||||
|
||||
public $main!: HTMLElement
|
||||
public $header!: HTMLElement
|
||||
public $body!: HTMLElement
|
||||
public $content!: HTMLElement
|
||||
public $children!: HTMLElement|null
|
||||
public $actions!: HTMLElement
|
||||
public voteBtnUp?: ActionBtn
|
||||
public voteBtnDown?: ActionBtn
|
||||
|
||||
public parent: Comment|null
|
||||
public nestedNum: number
|
||||
private maxNestingNum: number // 最多嵌套层数
|
||||
public children: Comment[] = []
|
||||
|
||||
public replyTo?: CommentData // 回复对象(flatMode 用)
|
||||
public $replyTo?: HTMLElement
|
||||
|
||||
public afterRender?: () => void
|
||||
|
||||
private unread = false
|
||||
private openable = false
|
||||
private openURL?: string
|
||||
public openEvt?: () => void
|
||||
|
||||
public onReplyBtnClick?: Function
|
||||
|
||||
constructor(ctx: Context, data: CommentData) {
|
||||
super(ctx)
|
||||
|
||||
// 最大嵌套数
|
||||
this.maxNestingNum = ctx.conf.maxNesting || 3
|
||||
|
||||
this.data = { ...data }
|
||||
this.data.date = this.data.date.replace(/-/g, '/') // 解决 Safari 日期解析 NaN 问题
|
||||
|
||||
this.parent = null
|
||||
this.nestedNum = 1 // 现在已嵌套 n 层
|
||||
}
|
||||
|
||||
/** 渲染 UI */
|
||||
public render() {
|
||||
this.$el = Utils.createElement(CommentHTML)
|
||||
this.$main = this.$el.querySelector('.atk-main')!
|
||||
this.$header = this.$el.querySelector('.atk-header')!
|
||||
this.$body = this.$el.querySelector('.atk-body')!
|
||||
this.$content = this.$body.querySelector('.atk-content')!
|
||||
this.$actions = this.$el.querySelector('.atk-actions')!
|
||||
this.$children = null
|
||||
|
||||
this.$el.setAttribute('data-comment-id', `${this.data.id}`)
|
||||
|
||||
this.renderCheckUnread()
|
||||
this.renderCheckClickable()
|
||||
|
||||
this.renderAvatar()
|
||||
this.renderHeader()
|
||||
this.renderContent()
|
||||
this.renderReplyTo()
|
||||
this.renderPending()
|
||||
this.renderActionBtn()
|
||||
|
||||
if (this.afterRender) this.afterRender()
|
||||
|
||||
return this.$el
|
||||
}
|
||||
|
||||
//#region Renders
|
||||
private renderCheckUnread() {
|
||||
if (this.unread) this.$el.classList.add('atk-unread')
|
||||
else this.$el.classList.remove('atk-unread')
|
||||
}
|
||||
|
||||
private renderCheckClickable() {
|
||||
if (this.openable) {
|
||||
this.$el.classList.add('atk-openable')
|
||||
} else {
|
||||
this.$el.classList.remove('atk-openable')
|
||||
}
|
||||
|
||||
this.$el.addEventListener('click', (evt) => {
|
||||
if (this.openable && this.openURL) {
|
||||
evt.preventDefault()
|
||||
window.open(this.openURL)
|
||||
}
|
||||
if (this.openEvt)
|
||||
this.openEvt()
|
||||
})
|
||||
}
|
||||
|
||||
private renderAvatar() {
|
||||
const $avatar = this.$el.querySelector<HTMLElement>('.atk-avatar')!
|
||||
const $avatarImg = Utils.createElement<HTMLImageElement>('<img />')
|
||||
$avatarImg.src = this.getGravatarUrl()
|
||||
if (this.data.link) {
|
||||
const $avatarA = Utils.createElement<HTMLLinkElement>('<a target="_blank" rel="noreferrer noopener nofollow"></a>')
|
||||
$avatarA.href = this.data.link
|
||||
$avatarA.append($avatarImg)
|
||||
$avatar.append($avatarA)
|
||||
} else {
|
||||
$avatar.append($avatarImg)
|
||||
}
|
||||
}
|
||||
|
||||
private renderHeader() {
|
||||
const $nick = this.$el.querySelector<HTMLElement>('.atk-nick')!
|
||||
if (this.data.link) {
|
||||
const $nickA = Utils.createElement<HTMLLinkElement>('<a target="_blank" rel="noreferrer noopener nofollow"></a>')
|
||||
$nickA.innerText = this.data.nick
|
||||
$nickA.href = this.data.link
|
||||
$nick.append($nickA)
|
||||
} else {
|
||||
$nick.innerText = this.data.nick
|
||||
}
|
||||
|
||||
const $badge = this.$el.querySelector<HTMLElement>('.atk-badge')!
|
||||
if (this.data.badge_name) {
|
||||
$badge.innerText = this.data.badge_name
|
||||
if (this.data.badge_color)
|
||||
$badge.style.backgroundColor = this.data.badge_color
|
||||
} else {
|
||||
$badge.remove()
|
||||
}
|
||||
|
||||
if (this.data.is_pinned) {
|
||||
const $pinnedBadge = Utils.createElement(`<span class="atk-item atk-pinned-badge">置顶</span>`) // 置顶徽章
|
||||
$nick.insertAdjacentElement('afterend', $pinnedBadge)
|
||||
}
|
||||
|
||||
const $date = this.$el.querySelector<HTMLElement>('.atk-date')!
|
||||
$date.innerText = this.getDateFormatted()
|
||||
$date.setAttribute('data-atk-comment-date', String(+new Date(this.data.date)))
|
||||
|
||||
if (this.conf.uaBadge) {
|
||||
const $uaWrap = Utils.createElement(`<span class="atk-ua-wrap"></span>`)
|
||||
const $uaBrowser = Utils.createElement(`<span class="atk-ua ua-browser"></span>`)
|
||||
const $usOS = Utils.createElement(`<span class="atk-ua ua-os"></span>`)
|
||||
$uaBrowser.innerText = this.getUserUaBrowser()
|
||||
$usOS.innerText = this.getUserUaOS()
|
||||
$uaWrap.append($uaBrowser)
|
||||
$uaWrap.append($usOS)
|
||||
this.$header.append($uaWrap)
|
||||
}
|
||||
}
|
||||
|
||||
private renderContent() {
|
||||
// 内容 & 折叠
|
||||
if (!this.data.is_collapsed) {
|
||||
this.$content.innerHTML = this.getContentMarked()
|
||||
return
|
||||
}
|
||||
|
||||
this.$content.classList.add('atk-hide', 'atk-type-collapsed')
|
||||
const collapsedInfoEl = Utils.createElement(`
|
||||
<div class="atk-collapsed">
|
||||
<span class="atk-text">该评论已被系统或管理员折叠</span>
|
||||
<span class="atk-show-btn">查看内容</span>
|
||||
</div>`)
|
||||
this.$body.insertAdjacentElement('beforeend', collapsedInfoEl)
|
||||
|
||||
const contentShowBtn = collapsedInfoEl.querySelector('.atk-show-btn')!
|
||||
contentShowBtn.addEventListener('click', (e) => {
|
||||
e.stopPropagation() // 防止穿透
|
||||
|
||||
if (this.$content.classList.contains('atk-hide')) {
|
||||
this.$content.innerHTML = this.getContentMarked()
|
||||
this.$content.classList.remove('atk-hide')
|
||||
Ui.playFadeInAnim(this.$content)
|
||||
contentShowBtn.innerHTML = '收起内容'
|
||||
} else {
|
||||
this.$content.innerHTML = ''
|
||||
this.$content.classList.add('atk-hide')
|
||||
contentShowBtn.innerHTML = '查看内容'
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// 回复的对象
|
||||
private renderReplyTo() {
|
||||
if (!this.replyTo) return
|
||||
|
||||
this.$replyTo = Utils.createElement(`
|
||||
<div class="atk-reply-to">
|
||||
<div class="atk-meta">回复 <span class="atk-nick"></span>:</div>
|
||||
<div class="atk-content"></div>
|
||||
</div>`)
|
||||
this.$replyTo.querySelector<HTMLElement>('.atk-nick')!.innerText = `@${this.replyTo.nick}`
|
||||
let replyContent = Utils.marked(this.ctx, this.replyTo.content)
|
||||
if (this.replyTo.is_collapsed) replyContent = '[已折叠]'
|
||||
this.$replyTo.querySelector<HTMLElement>('.atk-content')!.innerHTML = replyContent
|
||||
this.$body.prepend(this.$replyTo)
|
||||
}
|
||||
|
||||
// 待审核状态
|
||||
private renderPending() {
|
||||
if (!this.data.is_pending) return
|
||||
|
||||
const pendingEl = Utils.createElement(`<div class="atk-pending">审核中,仅本人可见。</div>`)
|
||||
this.$body.prepend(pendingEl)
|
||||
}
|
||||
|
||||
/** 初始化评论操作按钮 */
|
||||
private renderActionBtn() {
|
||||
// 投票功能
|
||||
if (this.ctx.conf.vote) {
|
||||
// 赞同按钮
|
||||
this.voteBtnUp = new ActionBtn(() => `赞同 (${this.data.vote_up || 0})`).appendTo(this.$actions)
|
||||
this.voteBtnUp.setClick(() => {
|
||||
this.vote('up')
|
||||
})
|
||||
|
||||
// 反对按钮
|
||||
if (this.ctx.conf.voteDown) {
|
||||
this.voteBtnDown = new ActionBtn(() => `反对 (${this.data.vote_down || 0})`).appendTo(this.$actions)
|
||||
this.voteBtnDown.setClick(() => {
|
||||
this.vote('down')
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 绑定回复按钮事件
|
||||
if (this.data.is_allow_reply) {
|
||||
const replyBtn = Utils.createElement(`<span>回复</span>`)
|
||||
this.$actions.append(replyBtn)
|
||||
replyBtn.addEventListener('click', (e) => {
|
||||
e.stopPropagation() // 防止穿透
|
||||
if (!this.onReplyBtnClick) {
|
||||
this.ctx.trigger('editor-reply', {data: this.data, $el: this.$el})
|
||||
} else {
|
||||
this.onReplyBtnClick()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// 绑定折叠按钮事件
|
||||
const collapseBtn = new ActionBtn({
|
||||
text: () => (this.data.is_collapsed ? '取消折叠' : '折叠'),
|
||||
adminOnly: true
|
||||
})
|
||||
collapseBtn.appendTo(this.$actions)
|
||||
collapseBtn.setClick(() => {
|
||||
this.adminEdit('collapsed', collapseBtn)
|
||||
})
|
||||
|
||||
// 绑定待审核按钮事件
|
||||
const pendingBtn = new ActionBtn({
|
||||
text: () => (this.data.is_pending ? '待审' : '已审'),
|
||||
adminOnly: true
|
||||
})
|
||||
pendingBtn.appendTo(this.$actions)
|
||||
pendingBtn.setClick(() => {
|
||||
this.adminEdit('pending', pendingBtn)
|
||||
})
|
||||
|
||||
// 绑定删除按钮事件
|
||||
const delBtn = new ActionBtn({
|
||||
text: '删除',
|
||||
confirm: true,
|
||||
confirmText: '确认删除',
|
||||
adminOnly: true,
|
||||
})
|
||||
delBtn.appendTo(this.$actions)
|
||||
delBtn.setClick(() => {
|
||||
this.adminDelete(delBtn)
|
||||
})
|
||||
|
||||
// 绑定置顶按钮事件
|
||||
const pinnedBtn = new ActionBtn({
|
||||
text: () => (this.data.is_pinned ? '取消置顶' : '置顶'),
|
||||
adminOnly: true
|
||||
})
|
||||
pinnedBtn.appendTo(this.$actions)
|
||||
pinnedBtn.setClick(() => {
|
||||
this.adminEdit('pinned', pendingBtn)
|
||||
})
|
||||
}
|
||||
//#endregion
|
||||
|
||||
/** 刷新评论 UI */
|
||||
public refreshUI() {
|
||||
const originalEl = this.$el
|
||||
const newEl = this.render()
|
||||
originalEl.replaceWith(newEl) // 替换 document 中的的 elem
|
||||
this.playFadeInAnim()
|
||||
|
||||
// 重建子评论元素
|
||||
this.eachComment(this.children, (child) => {
|
||||
child.parent?.getChildrenEl().appendChild(child.render())
|
||||
child.playFadeInAnim()
|
||||
})
|
||||
|
||||
this.ctx.trigger('comments-loaded')
|
||||
}
|
||||
|
||||
/** 遍历评论 */
|
||||
private eachComment(commentList: Comment[], action: (comment: Comment, levelList: Comment[]) => boolean|void) {
|
||||
if (commentList.length === 0) return
|
||||
commentList.every((item) => {
|
||||
if (action(item, commentList) === false) return false
|
||||
this.eachComment(item.getChildren(), action)
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
getIsRoot() {
|
||||
return this.parent === null
|
||||
}
|
||||
|
||||
getChildren() {
|
||||
return this.children
|
||||
}
|
||||
|
||||
putChild(childC: Comment) {
|
||||
childC.parent = this
|
||||
childC.nestedNum = this.nestedNum + 1 // 嵌套层数 +1
|
||||
this.children.push(childC)
|
||||
|
||||
this.getChildrenEl().appendChild(childC.getEl())
|
||||
childC.playFadeInAnim()
|
||||
|
||||
// 内容限高
|
||||
childC.checkHeightLimitArea('content')
|
||||
}
|
||||
|
||||
getChildrenEl() {
|
||||
if (this.$children === null) {
|
||||
// console.log(this.nestedNum)
|
||||
if (this.nestedNum < this.maxNestingNum) {
|
||||
this.$children = Utils.createElement('<div class="atk-comment-children"></div>')
|
||||
this.$main.appendChild(this.$children)
|
||||
} else if (this.parent) {
|
||||
this.$children = this.parent.getChildrenEl()
|
||||
}
|
||||
}
|
||||
|
||||
return this.$children
|
||||
}
|
||||
|
||||
getParent() {
|
||||
return this.parent
|
||||
}
|
||||
|
||||
getParents() {
|
||||
const parents: Comment[] = []
|
||||
const once = (c: Comment) => {
|
||||
if (c.parent) {
|
||||
parents.push(c.parent)
|
||||
once(c.parent)
|
||||
}
|
||||
}
|
||||
|
||||
once(this)
|
||||
return parents
|
||||
}
|
||||
|
||||
getEl() {
|
||||
return this.$el
|
||||
}
|
||||
|
||||
getData() {
|
||||
return this.data
|
||||
}
|
||||
|
||||
getGravatarUrl() {
|
||||
return Utils.getGravatarURL(this.ctx, this.data.email_encrypted)
|
||||
}
|
||||
|
||||
getContentMarked() {
|
||||
return Utils.marked(this.ctx, this.data.content)
|
||||
}
|
||||
|
||||
getDateFormatted() {
|
||||
return Utils.timeAgo(new Date(this.data.date))
|
||||
}
|
||||
|
||||
getUserUaBrowser() {
|
||||
const info = UADetect(this.data.ua)
|
||||
return `${info.browser} ${info.version}`
|
||||
}
|
||||
|
||||
getUserUaOS() {
|
||||
const info = UADetect(this.data.ua)
|
||||
return `${info.os} ${info.osVersion}`
|
||||
}
|
||||
|
||||
/** 渐出动画 */
|
||||
playFadeInAnim() {
|
||||
Ui.playFadeInAnim(this.$el)
|
||||
}
|
||||
|
||||
/** 投票操作 */
|
||||
vote(type: 'up'|'down') {
|
||||
const actionBtn = type === 'up' ? this.voteBtnUp : this.voteBtnDown
|
||||
|
||||
new Api(this.ctx).vote(this.data.id, `comment_${type}`)
|
||||
.then((v) => {
|
||||
this.data.vote_up = v.up
|
||||
this.data.vote_down = v.down
|
||||
this.voteBtnUp?.updateText()
|
||||
this.voteBtnDown?.updateText()
|
||||
})
|
||||
.catch((err) => {
|
||||
actionBtn?.setError(`投票失败`)
|
||||
console.log(err)
|
||||
})
|
||||
}
|
||||
|
||||
/** 管理员 - 评论状态修改 */
|
||||
adminEdit(type: 'collapsed'|'pending'|'pinned', btnElem: ActionBtn) {
|
||||
if (btnElem.isLoading) return // 若正在修改中
|
||||
|
||||
btnElem.setLoading(true, '修改中...')
|
||||
|
||||
// 克隆并修改当前数据
|
||||
const modify = { ...this.data }
|
||||
if (type === 'collapsed') {
|
||||
modify.is_collapsed = !modify.is_collapsed
|
||||
} else if (type === 'pending') {
|
||||
modify.is_pending = !modify.is_pending
|
||||
} else if (type === 'pinned') {
|
||||
modify.is_pinned = !modify.is_pinned
|
||||
}
|
||||
|
||||
new Api(this.ctx).commentEdit(modify).then((comment) => {
|
||||
btnElem.setLoading(false)
|
||||
|
||||
// 刷新当前 Comment UI
|
||||
this.data = comment
|
||||
this.refreshUI()
|
||||
Ui.playFadeInAnim(this.$body)
|
||||
|
||||
// 刷新 List UI
|
||||
this.ctx.trigger('list-refresh-ui')
|
||||
}).catch((err) => {
|
||||
console.error(err)
|
||||
btnElem.setError('修改失败')
|
||||
})
|
||||
}
|
||||
|
||||
public onDelete?: (comment: Comment) => void
|
||||
|
||||
/** 管理员 - 评论删除 */
|
||||
adminDelete(btnElem: ActionBtn) {
|
||||
if (btnElem.isLoading) return // 若正在删除中
|
||||
|
||||
btnElem.setLoading(true, '删除中...')
|
||||
new Api(this.ctx).commentDel(this.data.id, this.data.site_name)
|
||||
.then(() => {
|
||||
btnElem.setLoading(false)
|
||||
if (this.onDelete) this.onDelete(this)
|
||||
})
|
||||
.catch((e) => {
|
||||
console.error(e)
|
||||
btnElem.setError('删除失败')
|
||||
})
|
||||
}
|
||||
|
||||
public setUnread(val: boolean) {
|
||||
this.unread = val
|
||||
if (this.unread) this.$el.classList.add('atk-unread')
|
||||
else this.$el.classList.remove('atk-unread')
|
||||
}
|
||||
|
||||
public setOpenURL(url: string) {
|
||||
if (!url) {
|
||||
this.openable = false
|
||||
this.$el.classList.remove('atk-openable')
|
||||
}
|
||||
|
||||
this.openable = true
|
||||
this.openURL = url
|
||||
this.$el.classList.add('atk-openable')
|
||||
}
|
||||
|
||||
/** 内容限高检测 */
|
||||
checkHeightLimit() {
|
||||
this.checkHeightLimitArea('content') // 评论内容限高
|
||||
this.checkHeightLimitArea('children') // 子评论部分限高(嵌套模式)
|
||||
}
|
||||
|
||||
/** 目标内容限高检测 */
|
||||
checkHeightLimitArea(area: 'children'|'content') {
|
||||
// 参数准备
|
||||
const childrenMaxH = this.ctx.conf.heightLimit?.children
|
||||
const contentMaxH = this.ctx.conf.heightLimit?.content
|
||||
|
||||
if (area === 'children' && !childrenMaxH) return
|
||||
if (area === 'content' && !contentMaxH) return
|
||||
|
||||
// 限高
|
||||
let maxHeight: number
|
||||
if (area === 'children') maxHeight = childrenMaxH!
|
||||
if (area === 'content') maxHeight = contentMaxH!
|
||||
|
||||
// 检测指定元素
|
||||
const checkEl = ($el?: HTMLElement|null) => {
|
||||
if (!$el) return
|
||||
|
||||
// 是否超过高度
|
||||
if (Utils.getHeight($el) > maxHeight) {
|
||||
this.heightLimitAdd($el, maxHeight)
|
||||
}
|
||||
}
|
||||
|
||||
// 执行限高检测
|
||||
if (area === 'children') {
|
||||
checkEl(this.$children)
|
||||
} else if (area === 'content') {
|
||||
checkEl(this.$content)
|
||||
checkEl(this.$replyTo)
|
||||
|
||||
// 若有图片 · 图片加载完后再检测一次
|
||||
Utils.onImagesLoaded(this.$content, () => {
|
||||
checkEl(this.$content)
|
||||
})
|
||||
if (this.$replyTo) {
|
||||
Utils.onImagesLoaded(this.$replyTo, () => {
|
||||
checkEl(this.$replyTo)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 操作 · 取消限高
|
||||
heightLimitRemove($el: HTMLElement) {
|
||||
if (!$el) return
|
||||
if (!$el.classList.contains('atk-height-limit')) return
|
||||
|
||||
$el.classList.remove('atk-height-limit')
|
||||
Array.from($el.children).forEach((e) => {
|
||||
if (e.classList.contains('atk-height-limit-btn')) e.remove()
|
||||
})
|
||||
$el.style.height = ''
|
||||
$el.style.overflow = ''
|
||||
}
|
||||
|
||||
// 操作 · 内容限高
|
||||
heightLimitAdd($el: HTMLElement, maxHeight: number) {
|
||||
if (!$el) return
|
||||
if ($el.classList.contains('atk-height-limit')) return
|
||||
|
||||
$el.classList.add('atk-height-limit')
|
||||
$el.style.height = `${maxHeight}px`
|
||||
$el.style.overflow = 'hidden'
|
||||
const $hideMoreOpenBtn = Utils.createElement(`<div class="atk-height-limit-btn">阅读更多</span>`)
|
||||
$hideMoreOpenBtn.onclick = (e) => {
|
||||
e.stopPropagation()
|
||||
this.heightLimitRemove($el)
|
||||
|
||||
// 子评论数等于 1,直接取消限高
|
||||
const children = this.getChildren()
|
||||
if (children.length === 1) children[0].heightLimitRemove(children[0].$content)
|
||||
}
|
||||
$el.append($hideMoreOpenBtn)
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import Context from '~/types/context'
|
||||
import * as Utils from '../lib/utils'
|
||||
|
||||
type BtnClickHandler = (btnEl: HTMLElement, dialog: Dialog) => boolean|void
|
||||
@@ -6,11 +7,14 @@ type BtnClickHandler = (btnEl: HTMLElement, dialog: Dialog) => boolean|void
|
||||
* 对话框
|
||||
*/
|
||||
export default class Dialog {
|
||||
public ctx: Context
|
||||
public $el: HTMLElement
|
||||
public $content: HTMLElement
|
||||
public $actions: HTMLElement
|
||||
|
||||
constructor (contentEl: HTMLElement) {
|
||||
constructor (ctx: Context, contentEl: HTMLElement) {
|
||||
this.ctx = ctx
|
||||
|
||||
this.$el = Utils.createElement(
|
||||
`<div class="atk-layer-dialog-wrap">
|
||||
<div class="atk-layer-dialog">
|
||||
@@ -33,7 +37,7 @@ export default class Dialog {
|
||||
/** 按钮 · 确定 */
|
||||
public setYes(handler: BtnClickHandler) {
|
||||
const btn = Utils.createElement<HTMLButtonElement>(
|
||||
'<button data-action="confirm">确定</button>'
|
||||
`<button data-action="confirm">${this.ctx.$t('confirm')}</button>`
|
||||
)
|
||||
btn.onclick = this.onBtnClick(handler)
|
||||
this.$actions.appendChild(btn)
|
||||
@@ -44,7 +48,7 @@ export default class Dialog {
|
||||
/** 按钮 · 取消 */
|
||||
public setNo(handler: BtnClickHandler) {
|
||||
const btn = Utils.createElement<HTMLButtonElement>(
|
||||
'<button data-action="cancel">取消</button>'
|
||||
`<button data-action="cancel">${this.ctx.$t('cancel')}</button>`
|
||||
)
|
||||
btn.onclick = this.onBtnClick(handler)
|
||||
this.$actions.appendChild(btn)
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
import './_PreviewPlug/PreviewPlug.less'
|
||||
import Editor from '../Editor'
|
||||
import ArtalkContext from '~/src/ArtalkContext'
|
||||
import Utils from '~/src/utils'
|
||||
|
||||
export default class PreviewPlug extends ArtalkContext {
|
||||
public elem: HTMLElement
|
||||
|
||||
constructor (public editor: Editor) {
|
||||
super(editor.artalk)
|
||||
|
||||
this.initElem()
|
||||
}
|
||||
|
||||
initElem () {
|
||||
this.elem = Utils.createElement('<div class="atk-editor-plug-example"></div>')
|
||||
}
|
||||
|
||||
static Name = 'example'
|
||||
static BtnHTML = '栗子'
|
||||
|
||||
getEl () {
|
||||
return this.elem
|
||||
}
|
||||
|
||||
onShow () {}
|
||||
|
||||
onHide () {}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
import Context from "~/src/context"
|
||||
import Editor from "../editor"
|
||||
|
||||
export default abstract class EditorPlug {
|
||||
protected editor: Editor
|
||||
protected ctx: Context
|
||||
public abstract $el: HTMLElement
|
||||
|
||||
constructor (editor: Editor) {
|
||||
this.editor = editor
|
||||
this.ctx = editor.ctx
|
||||
}
|
||||
|
||||
public static Name: string
|
||||
public static BtnHTML: string
|
||||
|
||||
public abstract getEl(): HTMLElement
|
||||
public abstract onShow(): void
|
||||
public abstract onHide(): void
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
import './preview-plug.less'
|
||||
|
||||
import Editor from '../editor'
|
||||
import EditorPlug from './editor-plug'
|
||||
import * as Utils from '~/src/lib/utils'
|
||||
|
||||
export default class PreviewPlug extends EditorPlug {
|
||||
$el!: HTMLElement
|
||||
binded: boolean = false
|
||||
|
||||
constructor (editor: Editor) {
|
||||
super(editor)
|
||||
|
||||
this.initEl()
|
||||
}
|
||||
|
||||
initEl () {
|
||||
this.$el = Utils.createElement('<div class="atk-editor-plug-preview"></div>')
|
||||
this.binded = false
|
||||
}
|
||||
|
||||
static Name = 'preview'
|
||||
static BtnHTML = '预览 <i title="Markdown is supported"><svg class="markdown" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M14.85 3H1.15C.52 3 0 3.52 0 4.15v7.69C0 12.48.52 13 1.15 13h13.69c.64 0 1.15-.52 1.15-1.15v-7.7C16 3.52 15.48 3 14.85 3zM9 11H7V8L5.5 9.92 4 8v3H2V5h2l1.5 2L7 5h2v6zm2.99.5L9.5 8H11V5h2v3h1.5l-2.51 3.5z"></path></svg></i>'
|
||||
|
||||
getEl () {
|
||||
return this.$el
|
||||
}
|
||||
|
||||
onShow () {
|
||||
this.updateContent()
|
||||
if (!this.binded) {
|
||||
const event = () => {
|
||||
this.updateContent()
|
||||
}
|
||||
this.editor.$textarea.addEventListener('input', event)
|
||||
this.editor.$textarea.addEventListener('change', event)
|
||||
this.binded = true
|
||||
}
|
||||
}
|
||||
|
||||
onHide () {}
|
||||
|
||||
updateContent () {
|
||||
if (this.$el.style.display !== 'none') {
|
||||
this.$el.innerHTML = this.editor.getContentMarked()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,450 +0,0 @@
|
||||
import '../style/editor.less'
|
||||
|
||||
import Context from '../context'
|
||||
import Component from '../lib/component'
|
||||
import * as Utils from '../lib/utils'
|
||||
import * as Ui from '../lib/ui'
|
||||
import EditorHTML from './html/editor.html?raw'
|
||||
|
||||
import EmoticonsPlug from './editor-plugs/emoticons-plug'
|
||||
import PreviewPlug from './editor-plugs/preview-plug'
|
||||
import { CommentData } from '~/types/artalk-data'
|
||||
import Api from '../api'
|
||||
|
||||
export default class Editor extends Component {
|
||||
private readonly LOADABLE_PLUG_LIST = [EmoticonsPlug, PreviewPlug]
|
||||
public plugList: { [name: string]: any } = {}
|
||||
|
||||
public $header: HTMLElement
|
||||
public $textareaWrap: HTMLElement
|
||||
public $textarea: HTMLTextAreaElement
|
||||
public $plugWrap: HTMLElement
|
||||
public $bottom: HTMLElement
|
||||
public $plugBtnWrap: HTMLElement
|
||||
public $submitBtn: HTMLButtonElement
|
||||
public $notifyWrap: HTMLElement
|
||||
|
||||
private replyComment: CommentData|null = null
|
||||
private $sendReply: HTMLElement|null = null
|
||||
|
||||
private isTraveling = false
|
||||
|
||||
private get user () {
|
||||
return this.ctx.user
|
||||
}
|
||||
|
||||
constructor (ctx: Context) {
|
||||
super(ctx)
|
||||
|
||||
this.$el = Utils.createElement(EditorHTML)
|
||||
|
||||
this.$header = this.$el.querySelector('.atk-header')!
|
||||
this.$textareaWrap = this.$el.querySelector('.atk-textarea-wrap')!
|
||||
this.$textarea = this.$el.querySelector('.atk-textarea')!
|
||||
this.$plugWrap = this.$el.querySelector('.atk-plug-wrap')!
|
||||
this.$bottom = this.$el.querySelector('.atk-bottom')!
|
||||
this.$plugBtnWrap = this.$el.querySelector('.atk-plug-btn-wrap')!
|
||||
this.$submitBtn = this.$el.querySelector('.atk-send-btn')!
|
||||
this.$notifyWrap = this.$el.querySelector('.atk-notify-wrap')!
|
||||
|
||||
this.initLocalStorage()
|
||||
this.initHeader()
|
||||
this.initTextarea()
|
||||
this.initEditorPlug()
|
||||
this.initBottomPart()
|
||||
|
||||
// 监听事件
|
||||
this.ctx.on('editor-open', () => (this.open()))
|
||||
this.ctx.on('editor-close', () => (this.close()))
|
||||
this.ctx.on('editor-reply', (p) => (this.setReply(p.data, p.$el, p.scroll)))
|
||||
this.ctx.on('editor-reply-cancel', () => (this.cancelReply()))
|
||||
this.ctx.on('editor-show-loading', () => (Ui.showLoading(this.$el)))
|
||||
this.ctx.on('editor-hide-loading', () => (Ui.hideLoading(this.$el)))
|
||||
this.ctx.on('editor-notify', (f) => (this.showNotify(f.msg, f.type)))
|
||||
this.ctx.on('editor-travel', ($el) => (this.travel($el)))
|
||||
this.ctx.on('editor-travel-back', () => (this.travelBack()))
|
||||
}
|
||||
|
||||
initLocalStorage () {
|
||||
const localContent = window.localStorage.getItem('ArtalkContent') || ''
|
||||
if (localContent.trim() !== '') {
|
||||
this.showNotify('已自动恢复', 'i')
|
||||
this.setContent(localContent)
|
||||
}
|
||||
this.$textarea.addEventListener('input', () => {
|
||||
this.saveContent()
|
||||
})
|
||||
}
|
||||
|
||||
initHeader () {
|
||||
Object.keys(this.user.data).forEach((field) => {
|
||||
const inputEl = this.getInputEl(field)
|
||||
if (inputEl && inputEl instanceof HTMLInputElement) {
|
||||
inputEl.value = this.user.data[field] || ''
|
||||
// 绑定事件
|
||||
inputEl.addEventListener('input', () => this.onHeaderInputChanged(field, inputEl))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
getInputEl (field: string) {
|
||||
const inputEl = this.$header.querySelector<HTMLInputElement>(`[name="${field}"]`)
|
||||
return inputEl
|
||||
}
|
||||
|
||||
queryUserInfo = {
|
||||
timeout: <number|null>null,
|
||||
abortFunc: <(() => void)|null>null
|
||||
}
|
||||
|
||||
/** header 输入框内容变化事件 */
|
||||
onHeaderInputChanged (field: string, inputEl: HTMLInputElement) {
|
||||
this.user.data[field] = inputEl.value.trim()
|
||||
|
||||
// 若修改的是 nick or email
|
||||
if (field === 'nick' || field === 'email') {
|
||||
this.user.data.token = '' // 清除 token 登陆状态
|
||||
this.user.data.isAdmin = false
|
||||
|
||||
// 获取用户信息
|
||||
if (this.queryUserInfo.timeout !== null) window.clearTimeout(this.queryUserInfo.timeout) // 清除待发出的请求
|
||||
if (this.queryUserInfo.abortFunc !== null) this.queryUserInfo.abortFunc() // 之前发出未完成的请求立刻中止
|
||||
|
||||
this.queryUserInfo.timeout = window.setTimeout(() => {
|
||||
this.queryUserInfo.timeout = null // 清理
|
||||
|
||||
const {req, abort} = new Api(this.ctx).userGet(
|
||||
this.user.data.nick, this.user.data.email
|
||||
)
|
||||
this.queryUserInfo.abortFunc = abort
|
||||
req.then(data => {
|
||||
if (!data.is_login) {
|
||||
this.user.data.token = ''
|
||||
this.user.data.isAdmin = false
|
||||
}
|
||||
|
||||
// 未读消息更新
|
||||
this.ctx.trigger('unread-update', { notifies: data.unread, })
|
||||
|
||||
// 若用户为管理员,执行登陆操作
|
||||
if (this.user.checkHasBasicUserInfo() && !data.is_login && data.user && data.user.is_admin) {
|
||||
this.showLoginDialog()
|
||||
}
|
||||
|
||||
// 自动填入 link
|
||||
if (data.user && data.user.link) {
|
||||
this.user.data.link = data.user.link
|
||||
this.getInputEl('link')!.value = data.user.link
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
this.queryUserInfo.abortFunc = null // 清理
|
||||
})
|
||||
}, 400) // 延迟执行,减少请求次数
|
||||
}
|
||||
|
||||
this.saveUser()
|
||||
}
|
||||
|
||||
showLoginDialog () {
|
||||
this.ctx.trigger('checker-admin', {
|
||||
onSuccess: () => {
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
saveUser () {
|
||||
this.user.save()
|
||||
this.ctx.trigger('user-changed', this.ctx.user.data)
|
||||
}
|
||||
|
||||
saveContent () {
|
||||
window.localStorage.setItem('ArtalkContent', this.getContentOriginal().trim())
|
||||
}
|
||||
|
||||
initTextarea () {
|
||||
// 占位符
|
||||
this.$textarea.placeholder = this.ctx.conf.placeholder || ''
|
||||
|
||||
// 修复按下 Tab 输入的内容
|
||||
this.$textarea.addEventListener('keydown', (e) => {
|
||||
const keyCode = e.keyCode || e.which
|
||||
|
||||
if (keyCode === 9) {
|
||||
e.preventDefault()
|
||||
this.insertContent('\t')
|
||||
}
|
||||
})
|
||||
|
||||
// 输入框高度随内容而变化
|
||||
this.$textarea.addEventListener('input', (evt) => {
|
||||
this.adjustTextareaHeight()
|
||||
})
|
||||
}
|
||||
|
||||
adjustTextareaHeight () {
|
||||
const diff = this.$textarea.offsetHeight - this.$textarea.clientHeight
|
||||
this.$textarea.style.height = '0px' // it's a magic. 若不加此行,内容减少,高度回不去
|
||||
this.$textarea.style.height = `${this.$textarea.scrollHeight + diff}px`
|
||||
}
|
||||
|
||||
openedPlugName: string|null = null
|
||||
|
||||
initEditorPlug () {
|
||||
this.plugList = {}
|
||||
this.$plugWrap.innerHTML = ''
|
||||
this.$plugWrap.style.display = 'none'
|
||||
this.openedPlugName = null
|
||||
this.$plugBtnWrap.innerHTML = ''
|
||||
|
||||
// 依次实例化 plug
|
||||
this.LOADABLE_PLUG_LIST.forEach((PlugObj) => {
|
||||
// 切换按钮
|
||||
const btnElem = Utils.createElement(`<span class="atk-plug-btn">${PlugObj.BtnHTML}</span>`)
|
||||
this.$plugBtnWrap.appendChild(btnElem)
|
||||
btnElem.addEventListener('click', () => {
|
||||
let plug = this.plugList[PlugObj.Name]
|
||||
if (!plug) {
|
||||
plug = new PlugObj(this)
|
||||
this.plugList[PlugObj.Name] = plug
|
||||
}
|
||||
|
||||
this.$plugBtnWrap.querySelectorAll('.active').forEach(item => item.classList.remove('active'))
|
||||
|
||||
// 若点击已打开的,则收起
|
||||
if (PlugObj.Name === this.openedPlugName) {
|
||||
plug.onHide()
|
||||
this.$plugWrap.style.display = 'none'
|
||||
this.openedPlugName = null
|
||||
return
|
||||
}
|
||||
|
||||
if (this.$plugWrap.querySelector(`[data-plug-name="${PlugObj.Name}"]`) === null) {
|
||||
// 需要初始化
|
||||
const plugEl = plug.getEl()
|
||||
plugEl.setAttribute('data-plug-name', PlugObj.Name)
|
||||
plugEl.style.display = 'none'
|
||||
this.$plugWrap.appendChild(plugEl)
|
||||
}
|
||||
|
||||
(Array.from(this.$plugWrap.children) as HTMLElement[]).forEach((plugItemEl: HTMLElement) => {
|
||||
const plugItemName = plugItemEl.getAttribute('data-plug-name')!
|
||||
if (plugItemName === PlugObj.Name) {
|
||||
plugItemEl.style.display = ''
|
||||
this.plugList[plugItemName].onShow()
|
||||
} else {
|
||||
plugItemEl.style.display = 'none'
|
||||
this.plugList[plugItemName].onHide()
|
||||
}
|
||||
})
|
||||
|
||||
this.$plugWrap.style.display = ''
|
||||
this.openedPlugName = PlugObj.Name
|
||||
|
||||
btnElem.classList.add('active')
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/** 关闭编辑器插件 */
|
||||
closePlug () {
|
||||
this.$plugWrap.innerHTML = ''
|
||||
this.$plugWrap.style.display = 'none'
|
||||
this.openedPlugName = null
|
||||
}
|
||||
|
||||
insertContent (val: string) {
|
||||
if ((document as any).selection) {
|
||||
this.$textarea.focus();
|
||||
(document as any).selection.createRange().text = val
|
||||
this.$textarea.focus()
|
||||
} else if (this.$textarea.selectionStart || this.$textarea.selectionStart === 0) {
|
||||
const sStart = this.$textarea.selectionStart
|
||||
const sEnd = this.$textarea.selectionEnd
|
||||
const sT = this.$textarea.scrollTop
|
||||
this.setContent(this.$textarea.value.substring(0, sStart) + val + this.$textarea.value.substring(sEnd, this.$textarea.value.length))
|
||||
this.$textarea.focus()
|
||||
this.$textarea.selectionStart = sStart + val.length
|
||||
this.$textarea.selectionEnd = sStart + val.length
|
||||
this.$textarea.scrollTop = sT
|
||||
} else {
|
||||
this.$textarea.focus()
|
||||
this.$textarea.value += val
|
||||
}
|
||||
}
|
||||
|
||||
setContent (val: string) {
|
||||
this.$textarea.value = val
|
||||
this.saveContent()
|
||||
if (!!this.plugList && !!this.plugList.preview) {
|
||||
this.plugList.preview.updateContent()
|
||||
}
|
||||
this.adjustTextareaHeight()
|
||||
}
|
||||
|
||||
clearEditor () {
|
||||
this.setContent('')
|
||||
this.cancelReply()
|
||||
}
|
||||
|
||||
getContent () {
|
||||
let content = this.getContentOriginal()
|
||||
|
||||
// 表情包处理
|
||||
if (this.plugList && this.plugList.emoticons) {
|
||||
const emoticonsPlug = this.plugList.emoticons as EmoticonsPlug
|
||||
content = emoticonsPlug.transEmoticonImageText(content)
|
||||
}
|
||||
|
||||
return content
|
||||
}
|
||||
|
||||
getContentOriginal () {
|
||||
return this.$textarea.value || '' // Tip: !!"0" === true
|
||||
}
|
||||
|
||||
getContentMarked () {
|
||||
return Utils.marked(this.ctx, this.getContent())
|
||||
}
|
||||
|
||||
initBottomPart () {
|
||||
this.initReply()
|
||||
this.initSubmit()
|
||||
}
|
||||
|
||||
initReply () {
|
||||
this.replyComment = null
|
||||
this.$sendReply = null
|
||||
}
|
||||
|
||||
setReply (commentData: CommentData, $comment: HTMLElement, scroll = true) {
|
||||
if (this.replyComment !== null) {
|
||||
this.cancelReply()
|
||||
}
|
||||
|
||||
if (this.$sendReply === null) {
|
||||
this.$sendReply = Utils.createElement('<div class="atk-send-reply">回复 <span class="atk-text"></span><span class="atk-cancel" title="取消 AT">×</span></div>');
|
||||
this.$sendReply.querySelector<HTMLElement>('.atk-text')!.innerText = `@${commentData.nick}`
|
||||
this.$sendReply.addEventListener('click', () => {
|
||||
this.cancelReply()
|
||||
})
|
||||
this.$textareaWrap.append(this.$sendReply)
|
||||
}
|
||||
this.replyComment = commentData
|
||||
|
||||
if (this.ctx.conf.editorTravel === true) {
|
||||
this.travel($comment)
|
||||
}
|
||||
|
||||
if (scroll) Ui.scrollIntoView(this.$el)
|
||||
|
||||
this.$textarea.focus()
|
||||
}
|
||||
|
||||
cancelReply () {
|
||||
if (this.$sendReply !== null) {
|
||||
this.$sendReply.remove()
|
||||
this.$sendReply = null
|
||||
}
|
||||
this.replyComment = null
|
||||
|
||||
if (this.ctx.conf.editorTravel === true) {
|
||||
this.travelBack()
|
||||
}
|
||||
}
|
||||
|
||||
initSubmit () {
|
||||
this.$submitBtn.innerText = this.ctx.conf.sendBtn || 'Send'
|
||||
|
||||
this.$submitBtn.addEventListener('click', (evt) => {
|
||||
const btnEl = evt.currentTarget
|
||||
this.submit()
|
||||
})
|
||||
}
|
||||
|
||||
async submit () {
|
||||
if (this.getContent().trim() === '') {
|
||||
this.$textarea.focus()
|
||||
return
|
||||
}
|
||||
|
||||
this.ctx.trigger('editor-submit')
|
||||
|
||||
Ui.showLoading(this.$el)
|
||||
|
||||
try {
|
||||
const nComment = await new Api(this.ctx).add({
|
||||
content: this.getContent(),
|
||||
nick: this.user.data.nick,
|
||||
email: this.user.data.email,
|
||||
link: this.user.data.link,
|
||||
rid: (this.replyComment === null) ? 0 : this.replyComment.id,
|
||||
page_key: (this.replyComment === null) ? this.ctx.conf.pageKey : this.replyComment.page_key,
|
||||
page_title: (this.replyComment === null) ? this.ctx.conf.pageTitle : undefined,
|
||||
site_name: (this.replyComment === null) ? this.ctx.conf.site : this.replyComment.site_name
|
||||
})
|
||||
|
||||
// 回复不同页面的评论
|
||||
if (this.replyComment !== null && this.replyComment.page_key !== this.ctx.conf.pageKey) {
|
||||
window.open(`${this.replyComment.page_key}#atk-comment-${nComment.id}`)
|
||||
}
|
||||
|
||||
this.ctx.trigger('list-insert', nComment)
|
||||
this.clearEditor() // 清空编辑器
|
||||
this.ctx.trigger('editor-submitted')
|
||||
} catch (err: any) {
|
||||
console.error(err)
|
||||
this.showNotify(`评论失败,${err.msg || String(err)}`, 'e')
|
||||
return
|
||||
} finally {
|
||||
Ui.hideLoading(this.$el)
|
||||
}
|
||||
}
|
||||
|
||||
showNotify (msg: string, type) {
|
||||
Ui.showNotify(this.$notifyWrap, msg, type)
|
||||
}
|
||||
|
||||
/** 关闭评论 */
|
||||
close () {
|
||||
if (!this.$textareaWrap.querySelector('.atk-comment-closed'))
|
||||
this.$textareaWrap.prepend(Utils.createElement('<div class="atk-comment-closed">仅管理员可评论</div>'))
|
||||
|
||||
if (!this.user.data.isAdmin) {
|
||||
this.$textarea.style.display = 'none'
|
||||
this.closePlug()
|
||||
this.$bottom.style.display = 'none'
|
||||
} else {
|
||||
// 管理员一直打开评论
|
||||
this.$textarea.style.display = ''
|
||||
this.$bottom.style.display = ''
|
||||
}
|
||||
}
|
||||
|
||||
/** 打开评论 */
|
||||
open () {
|
||||
this.$textareaWrap.querySelector('.atk-comment-closed')?.remove()
|
||||
this.$textarea.style.display = ''
|
||||
this.$bottom.style.display = ''
|
||||
}
|
||||
|
||||
travel ($afterEl: HTMLElement) {
|
||||
if (this.isTraveling) return
|
||||
this.isTraveling = true
|
||||
this.$el.after(Utils.createElement('<div class="atk-editor-travel-placeholder"></div>'))
|
||||
|
||||
const $travelPlace = Utils.createElement('<div></div>')
|
||||
$afterEl.after($travelPlace)
|
||||
$travelPlace.replaceWith(this.$el)
|
||||
}
|
||||
|
||||
travelBack () {
|
||||
if (!this.isTraveling) return
|
||||
this.isTraveling = false
|
||||
this.ctx.$root.querySelector('.atk-editor-travel-placeholder')?.replaceWith(this.$el)
|
||||
|
||||
// 取消回复
|
||||
if (this.replyComment !== null) this.cancelReply()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
<div class="atk-main-editor">
|
||||
<div class="atk-header">
|
||||
<input name="nick" placeholder="昵称" class="atk-nick" type="text" required="required">
|
||||
<input name="email" placeholder="邮箱" class="atk-email" type="email" required="required">
|
||||
<input name="link" placeholder="网址 (https://)" class="atk-link" type="url">
|
||||
</div>
|
||||
<div class="atk-textarea-wrap">
|
||||
<textarea class="atk-textarea" placeholder=""></textarea>
|
||||
</div>
|
||||
<div class="atk-plug-wrap" style="display: none;"></div>
|
||||
<div class="atk-bottom">
|
||||
<div class="atk-item atk-plug-btn-wrap"></div>
|
||||
<div class="atk-item">
|
||||
<button type="button" class="atk-send-btn"></button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="atk-notify-wrap"></div>
|
||||
</div>
|
||||
@@ -38,7 +38,7 @@ export default class Pagination {
|
||||
`<div class="atk-pagination-wrap">
|
||||
<div class="atk-pagination">
|
||||
<div class="atk-btn atk-btn-prev">Prev</div>
|
||||
<input type="text" class="atk-input" />
|
||||
<input type="text" class="atk-input" aria-label="Enter the number of page" />
|
||||
<div class="atk-btn atk-btn-next">Next</div>
|
||||
</div>
|
||||
</div>`)
|
||||
|
||||
@@ -5,6 +5,8 @@ export interface ReadMoreBtnConf {
|
||||
onClick: (offset: number) => void
|
||||
|
||||
pageSize: number
|
||||
|
||||
text?: string
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -17,6 +19,7 @@ export default class ReadMoreBtn {
|
||||
private $text: HTMLElement
|
||||
private offset: number = 0
|
||||
private total: number = 0
|
||||
private origText: string = 'Load More'
|
||||
|
||||
/** 是否有更多内容 */
|
||||
get hasMore() {
|
||||
@@ -25,12 +28,13 @@ export default class ReadMoreBtn {
|
||||
|
||||
public constructor(conf: ReadMoreBtnConf) {
|
||||
this.conf = conf
|
||||
this.origText = this.conf.text || this.origText
|
||||
|
||||
this.$el = Utils.createElement(
|
||||
`<div class="atk-list-read-more" style="display: none;">
|
||||
<div class="atk-list-read-more-inner">
|
||||
<div class="atk-loading-icon" style="display: none;"></div>
|
||||
<span class="atk-text">加载更多</span>
|
||||
<span class="atk-text">${this.origText}</span>
|
||||
</div>
|
||||
</div>`)
|
||||
|
||||
@@ -68,7 +72,7 @@ export default class ReadMoreBtn {
|
||||
this.$text.innerText = errMsg
|
||||
this.$el.classList.add('atk-err')
|
||||
window.setTimeout(() => {
|
||||
this.$text.innerText = '查看更多'
|
||||
this.$text.innerText = this.origText
|
||||
this.$el.classList.remove('atk-err')
|
||||
}, 2000) // 2s后错误提示复原
|
||||
}
|
||||
|
||||
@@ -1,143 +0,0 @@
|
||||
import '../style/sidebar-layer.less'
|
||||
|
||||
import Context from '@/context'
|
||||
import Component from '@/lib/component'
|
||||
import * as Utils from '@/lib/utils'
|
||||
import SidebarHTML from './html/sidebar-layer.html?raw'
|
||||
import * as Ui from '@/lib/ui'
|
||||
import Layer from './layer'
|
||||
|
||||
export default class SidebarLayer extends Component {
|
||||
public layer?: Layer
|
||||
public $header: HTMLElement
|
||||
public $closeBtn: HTMLElement
|
||||
public $iframeWrap: HTMLElement
|
||||
public $iframe?: HTMLIFrameElement
|
||||
|
||||
constructor(ctx: Context) {
|
||||
super(ctx)
|
||||
|
||||
this.$el = Utils.createElement(SidebarHTML)
|
||||
this.$header = this.$el.querySelector('.atk-sidebar-header')!
|
||||
this.$closeBtn = this.$header.querySelector('.atk-sidebar-close')!
|
||||
this.$iframeWrap = this.$el.querySelector('.atk-sidebar-iframe-wrap')!
|
||||
|
||||
this.$closeBtn.onclick = () => {
|
||||
this.hide()
|
||||
}
|
||||
|
||||
// event
|
||||
this.ctx.on('sidebar-show', () => (this.show()))
|
||||
this.ctx.on('sidebar-hide', () => (this.hide()))
|
||||
this.ctx.on('user-changed', () => { this.firstShow = true })
|
||||
}
|
||||
|
||||
private firstShow = true
|
||||
|
||||
/** 显示 */
|
||||
public async show() {
|
||||
this.$el.style.transform = '' // 动画清除,防止二次打开失效
|
||||
|
||||
// 获取 Layer
|
||||
if (this.layer == null) {
|
||||
this.layer = new Layer(this.ctx, 'sidebar', this.$el)
|
||||
this.layer.afterHide = () => {
|
||||
// 防止评论框被吞
|
||||
if (this.ctx.conf.editorTravel === true) {
|
||||
this.ctx.trigger('editor-travel-back')
|
||||
}
|
||||
}
|
||||
}
|
||||
this.layer.show()
|
||||
|
||||
// viewWrap 滚动条归位
|
||||
// this.$viewWrap.scrollTo(0, 0)
|
||||
|
||||
// 执行动画
|
||||
setTimeout(() => {
|
||||
this.$el.style.transform = 'translate(0, 0)'
|
||||
}, 20)
|
||||
|
||||
// 第一次加载
|
||||
if (this.firstShow) {
|
||||
this.$iframeWrap.innerHTML = ''
|
||||
this.$iframe = Utils.createElement<HTMLIFrameElement>('<iframe></iframe>')
|
||||
|
||||
const baseURL = (import.meta.env.MODE === 'development') ? 'http://localhost:23367/'
|
||||
: `${this.conf.server.replace(/\/$/, '')}/../sidebar/`
|
||||
const userData = encodeURIComponent(JSON.stringify(this.ctx.user.data))
|
||||
|
||||
// 测试是否能访问
|
||||
this.iframeLoad(`${baseURL}`
|
||||
+ `?pageKey=${encodeURIComponent(this.conf.pageKey)}`
|
||||
+ `&site=${encodeURIComponent(this.conf.site || '')}`
|
||||
+ `&user=${userData}`
|
||||
+ `${((this.conf.darkMode) ? `&darkMode=1` : ``)}`)
|
||||
|
||||
this.$iframeWrap.append(this.$iframe)
|
||||
this.firstShow = false
|
||||
} else {
|
||||
// 暗黑模式
|
||||
if (this.conf.darkMode && !this.$iframe!.src.match(/darkMode=1$/)) {
|
||||
this.iframeLoad(`${this.$iframe!.src}&darkMode=1`)
|
||||
}
|
||||
if (!this.conf.darkMode && this.$iframe!.src.match(/darkMode=1$/)) {
|
||||
this.iframeLoad(this.$iframe!.src.replace(/&darkMode=1$/, ''))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 隐藏 */
|
||||
public hide() {
|
||||
// 执行动画
|
||||
this.$el.style.transform = ''
|
||||
|
||||
this.layer?.hide()
|
||||
}
|
||||
|
||||
public iframeLoad(src: string) {
|
||||
if (!this.$iframe) return
|
||||
|
||||
this.$iframe.src = src
|
||||
|
||||
// 加载动画
|
||||
Ui.showLoading(this.$iframeWrap)
|
||||
this.$iframe.onload = () => {
|
||||
Ui.hideLoading(this.$iframeWrap)
|
||||
}
|
||||
|
||||
// this.checkReqStatus(src) // 判不准,删了,没啥用
|
||||
}
|
||||
|
||||
loadingTimer: number|null = null
|
||||
|
||||
// 测试可访问性 (由于 iframe 测不准,需要额外请求)
|
||||
public async checkReqStatus(url: string) {
|
||||
if (this.loadingTimer !== null) window.clearTimeout(this.loadingTimer)
|
||||
|
||||
this.loadingTimer = window.setTimeout(async () => {
|
||||
try {
|
||||
await fetch(url)
|
||||
} catch (err) {
|
||||
console.log(err)
|
||||
// 请求失败,显示错误提示
|
||||
const $errAlert = Utils.createElement(
|
||||
`<div class="atk-err-alert">` +
|
||||
` <div class="atk-title">侧边栏似乎打开失败</div>` +
|
||||
` <div class="atk-text"><span id="AtkReload">重新加载</span> / <span id="AtkCancel">取消</span></div>` +
|
||||
`</div>`
|
||||
)
|
||||
const $reloadBtn = $errAlert.querySelector<HTMLElement>('#AtkReload')!
|
||||
const $cancelBtn = $errAlert.querySelector<HTMLElement>('#AtkCancel')!
|
||||
$reloadBtn.onclick = () => {
|
||||
this.iframeLoad(url)
|
||||
$errAlert.remove()
|
||||
}
|
||||
$cancelBtn.onclick = () => { // 提供取消按钮,防止误判
|
||||
$errAlert.remove()
|
||||
}
|
||||
this.$iframeWrap.append($errAlert)
|
||||
}
|
||||
}, 2000) // 2s 后开始检测
|
||||
}
|
||||
}
|
||||
+207
-12
@@ -1,42 +1,237 @@
|
||||
import User from './lib/user'
|
||||
import { marked as libMarked } from 'marked'
|
||||
import ArtalkConfig from '~/types/artalk-config'
|
||||
import { EventPayloadMap, Event, EventScopeType, Handler } from '~/types/event'
|
||||
import { CommentData, NotifyData } from '~/types/artalk-data'
|
||||
import { Event } from '~/types/event'
|
||||
import { internal as internalLocales, I18n } from './i18n'
|
||||
import User from './lib/user'
|
||||
import ContextApi from '../types/context'
|
||||
import Editor from './editor'
|
||||
import Comment from './comment'
|
||||
import ListLite from './list/list-lite'
|
||||
import SidebarLayer, { SidebarShowPayload } from './layer/sidebar-layer'
|
||||
import CheckerLauncher, { CheckerCaptchaPayload, CheckerPayload } from './lib/checker'
|
||||
import Layer, { GetLayerWrap } from './layer'
|
||||
import Api from './api'
|
||||
|
||||
/**
|
||||
* Artalk Context
|
||||
*/
|
||||
export default class Context {
|
||||
export default class Context implements ContextApi {
|
||||
/* 持有同事类 */
|
||||
private api!: Api
|
||||
private editor!: Editor
|
||||
private list!: ListLite
|
||||
private sidebarLayer!: SidebarLayer
|
||||
private checkerLauncher!: CheckerLauncher
|
||||
|
||||
/* 运行参数 */
|
||||
public cid: number // Context 唯一标识
|
||||
public $root: HTMLElement
|
||||
public conf: ArtalkConfig
|
||||
public user: User
|
||||
public $root: HTMLElement
|
||||
public markedInstance?: typeof libMarked
|
||||
public markedReplacers: ((raw: string) => string)[] = []
|
||||
|
||||
private commentList: Comment[] = [] // Note: 无层级结构 + 无须排列
|
||||
|
||||
/* 订阅者模式 */
|
||||
private eventList: Event[] = []
|
||||
|
||||
public constructor (rootEl: HTMLElement, conf: ArtalkConfig) {
|
||||
public constructor(conf: ArtalkConfig, $root?: HTMLElement) {
|
||||
this.cid = +new Date()
|
||||
this.$root = rootEl
|
||||
this.conf = conf
|
||||
this.user = new User(this.conf)
|
||||
this.user = new User(this)
|
||||
|
||||
this.$root = $root || document.createElement('div')
|
||||
this.$root.setAttribute('atk-run-id', this.cid.toString())
|
||||
this.$root.classList.add('artalk')
|
||||
this.$root.innerHTML = ''
|
||||
|
||||
this.api = new Api(this)
|
||||
}
|
||||
|
||||
public on<K extends keyof EventPayloadMap>(name: K, handler: Handler<EventPayloadMap[K]>, scope: EventScopeType = 'internal') {
|
||||
this.eventList.push({ name, handler: handler as any, scope })
|
||||
/* 设置持有的同事类 */
|
||||
public setApi(api: Api): void {
|
||||
this.api = api
|
||||
}
|
||||
|
||||
public off<K extends keyof EventPayloadMap>(name: K, handler?: Handler<EventPayloadMap[K]>, scope: EventScopeType = 'internal') {
|
||||
public setEditor(editor: Editor): void {
|
||||
this.editor = editor
|
||||
}
|
||||
|
||||
public setList(list: ListLite): void {
|
||||
this.list = list
|
||||
}
|
||||
|
||||
public setSidebarLayer(sidebarLayer: SidebarLayer): void {
|
||||
this.sidebarLayer = sidebarLayer
|
||||
}
|
||||
|
||||
public setCheckerLauncher(checkerLauncher: CheckerLauncher): void {
|
||||
this.checkerLauncher = checkerLauncher
|
||||
}
|
||||
|
||||
public getApi() {
|
||||
return this.api
|
||||
}
|
||||
|
||||
/* 评论操作 */
|
||||
public getCommentList() {
|
||||
return this.commentList
|
||||
}
|
||||
|
||||
public getCommentDataList() {
|
||||
return this.commentList.map(c => c.getData())
|
||||
}
|
||||
|
||||
public findComment(id: number): Comment|undefined {
|
||||
return this.commentList.find(c => c.getData().id === id)
|
||||
}
|
||||
|
||||
public deleteComment(_comment: number|Comment) {
|
||||
let comment: Comment
|
||||
if (typeof _comment === 'number') {
|
||||
const findComment = this.findComment(_comment)
|
||||
if (!findComment) throw Error(`Comment ${_comment} cannot be found`)
|
||||
comment = findComment
|
||||
} else comment = _comment
|
||||
|
||||
comment.getEl().remove()
|
||||
this.commentList.splice(this.commentList.indexOf(comment), 1)
|
||||
|
||||
const listData = this.list.getData()
|
||||
if (listData) listData.total -= 1 // 评论数减 1
|
||||
|
||||
this.list.refreshUI()
|
||||
}
|
||||
|
||||
public clearAllComments() {
|
||||
this.list.getCommentsWrapEl().innerHTML = ''
|
||||
this.list.clearData()
|
||||
this.commentList = []
|
||||
}
|
||||
|
||||
public insertComment(commentData: CommentData) {
|
||||
this.list.insertComment(commentData)
|
||||
}
|
||||
|
||||
public replyComment(commentData: CommentData, $comment: HTMLElement, scroll?: boolean): void {
|
||||
this.editor.setReply(commentData, $comment, scroll)
|
||||
}
|
||||
|
||||
public cancelReplyComment(): void {
|
||||
this.editor.cancelReply()
|
||||
}
|
||||
|
||||
public updateNotifies(notifies: NotifyData[]): void {
|
||||
this.list.updateUnread(notifies)
|
||||
}
|
||||
|
||||
/* 评论列表 */
|
||||
public listReload(): void {
|
||||
this.list.reload()
|
||||
}
|
||||
|
||||
public listRefreshUI(): void {
|
||||
this.list.refreshUI()
|
||||
}
|
||||
|
||||
/* 编辑器 */
|
||||
public editorOpen(): void {
|
||||
this.editor.open()
|
||||
}
|
||||
|
||||
public editorClose(): void {
|
||||
this.editor.close()
|
||||
}
|
||||
|
||||
public editorShowLoading(): void {
|
||||
this.editor.showLoading()
|
||||
}
|
||||
|
||||
public editorHideLoading(): void {
|
||||
this.editor.hideLoading()
|
||||
}
|
||||
|
||||
public editorShowNotify(msg, type): void {
|
||||
this.editor.showNotify(msg, type)
|
||||
}
|
||||
|
||||
public editorTravel($el: HTMLElement): void {
|
||||
this.editor.travel($el)
|
||||
}
|
||||
|
||||
public editorTravelBack(): void {
|
||||
this.editor.travelBack()
|
||||
}
|
||||
|
||||
/* 侧边栏 */
|
||||
public showSidebar(payload?: SidebarShowPayload): void {
|
||||
this.sidebarLayer.show(payload)
|
||||
}
|
||||
|
||||
public hideSidebar(): void {
|
||||
this.sidebarLayer.hide()
|
||||
}
|
||||
|
||||
/* 权限检测 */
|
||||
public checkAdmin(payload: CheckerPayload): void {
|
||||
this.checkerLauncher.checkAdmin(payload)
|
||||
}
|
||||
|
||||
public checkCaptcha(payload: CheckerCaptchaPayload): void {
|
||||
this.checkerLauncher.checkCaptcha(payload)
|
||||
}
|
||||
|
||||
public checkAdminShowEl() {
|
||||
const items: HTMLElement[] = []
|
||||
|
||||
this.$root.querySelectorAll<HTMLElement>(`[atk-only-admin-show]`).forEach(item => items.push(item))
|
||||
|
||||
// for layer
|
||||
const { $wrap: $layerWrap } = GetLayerWrap(this)
|
||||
if ($layerWrap) $layerWrap.querySelectorAll<HTMLElement>(`[atk-only-admin-show]`).forEach(item => items.push(item))
|
||||
|
||||
// for sidebar
|
||||
// TODO: 这个其实应该写在 packages/artalk-sidebar 里面的
|
||||
const $sidebarEl = document.querySelector<HTMLElement>('.atk-sidebar')
|
||||
if ($sidebarEl) $sidebarEl.querySelectorAll<HTMLElement>(`[atk-only-admin-show]`).forEach(item => items.push(item))
|
||||
|
||||
items.forEach(($item: HTMLElement) => {
|
||||
if (this.user.data.isAdmin) $item.classList.remove('atk-hide')
|
||||
else $item.classList.add('atk-hide')
|
||||
})
|
||||
}
|
||||
|
||||
/* 订阅模式 */
|
||||
public on(name: any, handler: any, scope: any = 'internal') {
|
||||
this.eventList.push({ name, handler, scope })
|
||||
}
|
||||
|
||||
public off(name: any, handler: any, scope: any = 'internal') {
|
||||
this.eventList = this.eventList.filter((evt) => {
|
||||
if (handler) return !(evt.name === name && evt.handler === handler && evt.scope === scope)
|
||||
return !(evt.name === name && evt.scope === scope) // 删除全部相同 name event
|
||||
})
|
||||
}
|
||||
|
||||
public trigger<K extends keyof EventPayloadMap>(name: K, payload?: EventPayloadMap[K], scope?: EventScopeType) {
|
||||
public trigger(name: any, payload?: any, scope?: any) {
|
||||
this.eventList
|
||||
.filter((evt) => evt.name === name && (scope ? (evt.scope === scope) : true))
|
||||
.map((evt) => evt.handler)
|
||||
.forEach((handler) => handler(payload as any))
|
||||
.forEach((handler) => handler(payload))
|
||||
}
|
||||
|
||||
/* i18n */
|
||||
public $t(key: keyof I18n, args: {[key: string]: string} = {}): string {
|
||||
let locales = this.conf.locale
|
||||
if (typeof locales === 'string') {
|
||||
locales = internalLocales[locales]
|
||||
}
|
||||
|
||||
let str = locales?.[key] || key
|
||||
str = str.replace(/\{\s*(\w+?)\s*\}/g, (_, token) => args[token] || '')
|
||||
|
||||
return str
|
||||
}
|
||||
}
|
||||
@@ -1,25 +1,32 @@
|
||||
import ArtalkConfig from "~/types/artalk-config";
|
||||
import ArtalkConfig from "~/types/artalk-config"
|
||||
|
||||
const defaults: ArtalkConfig = {
|
||||
el: '',
|
||||
pageKey: '',
|
||||
pageTitle: '',
|
||||
server: '',
|
||||
site: '',
|
||||
|
||||
placeholder: '键入内容...',
|
||||
noComment: '「此时无声胜有声」',
|
||||
sendBtn: '发送评论',
|
||||
placeholder: '',
|
||||
noComment: '',
|
||||
sendBtn: '',
|
||||
darkMode: false,
|
||||
editorTravel: true,
|
||||
|
||||
flatMode: 'auto',
|
||||
nestMax: 2,
|
||||
nestSort: 'DATE_ASC',
|
||||
|
||||
emoticons: "https://cdn.jsdelivr.net/gh/ArtalkJS/Emoticons/grps/default.json",
|
||||
|
||||
vote: true,
|
||||
voteDown: false,
|
||||
uaBadge: true,
|
||||
listSort: true,
|
||||
preview: true,
|
||||
countEl: '#ArtalkCount',
|
||||
pvEl: '#ArtalkPV',
|
||||
flatMode: 'auto',
|
||||
maxNesting: 3,
|
||||
|
||||
gravatar: {
|
||||
default: 'mp',
|
||||
mirror: 'https://sdn.geekzu.org/avatar/',
|
||||
@@ -36,8 +43,18 @@ const defaults: ArtalkConfig = {
|
||||
children: 400,
|
||||
},
|
||||
|
||||
imgUpload: true,
|
||||
reqTimeout: 15000,
|
||||
versionCheck: true,
|
||||
useBackendConf: false,
|
||||
|
||||
locale: 'zh-CN',
|
||||
}
|
||||
|
||||
if (ARTALK_LITE) {
|
||||
defaults.vote = false
|
||||
defaults.uaBadge = false
|
||||
defaults.emoticons = false
|
||||
}
|
||||
|
||||
export default defaults
|
||||
@@ -0,0 +1,18 @@
|
||||
<div class="atk-main-editor">
|
||||
<div class="atk-header">
|
||||
<input name="nick" class="atk-nick" type="text" required="required">
|
||||
<input name="email" class="atk-email" type="email" required="required">
|
||||
<input name="link" class="atk-link" type="url">
|
||||
</div>
|
||||
<div class="atk-textarea-wrap">
|
||||
<textarea class="atk-textarea"></textarea>
|
||||
</div>
|
||||
<div class="atk-plug-panel-wrap" style="display: none;"></div>
|
||||
<div class="atk-bottom">
|
||||
<div class="atk-item atk-plug-btn-wrap"></div>
|
||||
<div class="atk-item">
|
||||
<button type="button" class="atk-send-btn"></button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="atk-notify-wrap"></div>
|
||||
</div>
|
||||
@@ -0,0 +1,419 @@
|
||||
import '@/style/editor.less'
|
||||
|
||||
import { CommentData } from '~/types/artalk-data'
|
||||
import Context from '~/types/context'
|
||||
import Component from '../lib/component'
|
||||
import * as Utils from '../lib/utils'
|
||||
import * as Ui from '../lib/ui'
|
||||
|
||||
import EditorHTML from './editor.html?raw'
|
||||
|
||||
import EmoticonsPlug from './plugs/emoticons-plug'
|
||||
import UploadPlug from './plugs/upload-plug'
|
||||
import PreviewPlug from './plugs/preview-plug'
|
||||
import EditorPlug from './plugs/editor-plug'
|
||||
import HeaderInputPlug from './plugs/header-input-plug'
|
||||
|
||||
export default class Editor extends Component {
|
||||
private get user() { return this.ctx.user }
|
||||
|
||||
public $header: HTMLElement
|
||||
public $nick: HTMLInputElement
|
||||
public $email: HTMLInputElement
|
||||
public $link: HTMLInputElement
|
||||
public get $inputs() {
|
||||
return { nick: this.$nick, email: this.$email, link: this.$link }
|
||||
}
|
||||
|
||||
public $textareaWrap: HTMLElement
|
||||
public $textarea: HTMLTextAreaElement
|
||||
public $bottom: HTMLElement
|
||||
public $submitBtn: HTMLButtonElement
|
||||
public $notifyWrap: HTMLElement
|
||||
|
||||
private replyComment: CommentData|null = null
|
||||
private $sendReply: HTMLElement|null = null
|
||||
|
||||
private isTraveling = false
|
||||
|
||||
/** 启用的插件 */
|
||||
private readonly ENABLED_PLUGS = [ EmoticonsPlug, UploadPlug, PreviewPlug, HeaderInputPlug ]
|
||||
public plugList: { [name: string]: EditorPlug } = {}
|
||||
private openedPlugName: string|null = null
|
||||
public $plugPanelWrap: HTMLElement
|
||||
public $plugBtnWrap: HTMLElement
|
||||
|
||||
public constructor(ctx: Context) {
|
||||
super(ctx)
|
||||
|
||||
this.$el = Utils.createElement(EditorHTML)
|
||||
|
||||
this.$header = this.$el.querySelector('.atk-header')!
|
||||
this.$nick = this.$header.querySelector('[name="nick"]')!
|
||||
this.$email = this.$header.querySelector('[name="email"]')!
|
||||
this.$link = this.$header.querySelector('[name="link"]')!
|
||||
|
||||
this.$textareaWrap = this.$el.querySelector('.atk-textarea-wrap')!
|
||||
this.$textarea = this.$el.querySelector('.atk-textarea')!
|
||||
this.$bottom = this.$el.querySelector('.atk-bottom')!
|
||||
this.$submitBtn = this.$el.querySelector('.atk-send-btn')!
|
||||
this.$notifyWrap = this.$el.querySelector('.atk-notify-wrap')!
|
||||
|
||||
this.$plugBtnWrap = this.$el.querySelector('.atk-plug-btn-wrap')!
|
||||
this.$plugPanelWrap = this.$el.querySelector('.atk-plug-panel-wrap')!
|
||||
|
||||
// 执行初始化
|
||||
this.initLocalStorage()
|
||||
this.initHeader()
|
||||
this.initTextarea()
|
||||
this.initPlugs()
|
||||
this.initSubmitBtn()
|
||||
|
||||
// 监听事件
|
||||
this.ctx.on('conf-updated', () => {})
|
||||
}
|
||||
|
||||
private initLocalStorage() {
|
||||
const localContent = window.localStorage.getItem('ArtalkContent') || ''
|
||||
if (localContent.trim() !== '') {
|
||||
this.showNotify(this.$t('restoredMsg'), 'i')
|
||||
this.setContent(localContent)
|
||||
}
|
||||
|
||||
this.$textarea.addEventListener('input', () => (this.saveToLocalStorage()))
|
||||
}
|
||||
|
||||
private saveToLocalStorage() {
|
||||
window.localStorage.setItem('ArtalkContent', this.getContentOriginal().trim())
|
||||
}
|
||||
|
||||
private initHeader() {
|
||||
Object.entries(this.$inputs).forEach(([key, $input]) => {
|
||||
$input.value = this.user.data[key] || ''
|
||||
$input.addEventListener('input', () => this.onHeaderInput(key, $input))
|
||||
|
||||
// 设置 Placeholder
|
||||
$input.placeholder = `${this.$t(key as any)}`
|
||||
})
|
||||
}
|
||||
|
||||
private onHeaderInput(key: string, $input: HTMLInputElement) {
|
||||
this.user.update({
|
||||
[key]: $input.value.trim()
|
||||
})
|
||||
|
||||
// 插件监听事件响应
|
||||
Object.entries(this.plugList).forEach(([plugName, plug]) => {
|
||||
if (plug.onHeaderInput) plug.onHeaderInput(key, $input)
|
||||
})
|
||||
}
|
||||
|
||||
private initTextarea() {
|
||||
// 占位符
|
||||
this.$textarea.placeholder = this.ctx.conf.placeholder || this.$t('placeholder')
|
||||
|
||||
// 修复按下 Tab 输入的内容
|
||||
this.$textarea.addEventListener('keydown', (e) => {
|
||||
const keyCode = e.keyCode || e.which
|
||||
|
||||
if (keyCode === 9) {
|
||||
e.preventDefault()
|
||||
this.insertContent('\t')
|
||||
}
|
||||
})
|
||||
|
||||
// 输入框高度随内容而变化
|
||||
this.$textarea.addEventListener('input', () => {
|
||||
this.adjustTextareaHeight()
|
||||
})
|
||||
}
|
||||
|
||||
private initSubmitBtn() {
|
||||
this.$submitBtn.innerText = this.ctx.conf.sendBtn || this.$t('send')
|
||||
this.$submitBtn.addEventListener('click', () => (this.submit()))
|
||||
}
|
||||
|
||||
/** 最终用于 submit 的数据 */
|
||||
public getFinalContent() {
|
||||
let content = this.getContentOriginal()
|
||||
|
||||
// 表情包处理
|
||||
if (this.plugList.emoticons) {
|
||||
content = (this.plugList.emoticons as EmoticonsPlug).transEmoticonImageText(content)
|
||||
}
|
||||
|
||||
return content
|
||||
}
|
||||
|
||||
public getContentOriginal() {
|
||||
return this.$textarea.value || '' // Tip: !!"0" === true
|
||||
}
|
||||
|
||||
public getContentMarked() {
|
||||
return Utils.marked(this.ctx, this.getFinalContent())
|
||||
}
|
||||
|
||||
public setContent(val: string) {
|
||||
this.$textarea.value = val
|
||||
this.saveToLocalStorage()
|
||||
if (this.plugList.preview) {
|
||||
;(this.plugList.preview as PreviewPlug).updateContent()
|
||||
}
|
||||
|
||||
// 延迟执行防止无效
|
||||
window.setTimeout(() => {
|
||||
this.adjustTextareaHeight()
|
||||
}, 80)
|
||||
}
|
||||
|
||||
public insertContent(val: string) {
|
||||
if ((document as any).selection) {
|
||||
this.$textarea.focus();
|
||||
(document as any).selection.createRange().text = val
|
||||
this.$textarea.focus()
|
||||
} else if (this.$textarea.selectionStart || this.$textarea.selectionStart === 0) {
|
||||
const sStart = this.$textarea.selectionStart
|
||||
const sEnd = this.$textarea.selectionEnd
|
||||
const sT = this.$textarea.scrollTop
|
||||
this.setContent(this.$textarea.value.substring(0, sStart) + val + this.$textarea.value.substring(sEnd, this.$textarea.value.length))
|
||||
this.$textarea.focus()
|
||||
this.$textarea.selectionStart = sStart + val.length
|
||||
this.$textarea.selectionEnd = sStart + val.length
|
||||
this.$textarea.scrollTop = sT
|
||||
} else {
|
||||
this.$textarea.focus()
|
||||
this.$textarea.value += val
|
||||
}
|
||||
}
|
||||
|
||||
public clearEditor() {
|
||||
this.setContent('')
|
||||
this.cancelReply()
|
||||
}
|
||||
|
||||
private adjustTextareaHeight() {
|
||||
const diff = this.$textarea.offsetHeight - this.$textarea.clientHeight
|
||||
this.$textarea.style.height = '0px' // it's a magic. 若不加此行,内容减少,高度回不去
|
||||
this.$textarea.style.height = `${this.$textarea.scrollHeight + diff}px`
|
||||
}
|
||||
|
||||
public setReply(commentData: CommentData, $comment: HTMLElement, scroll = true) {
|
||||
if (this.replyComment !== null) {
|
||||
this.cancelReply()
|
||||
}
|
||||
|
||||
if (this.$sendReply === null) {
|
||||
this.$sendReply = Utils.createElement(`<div class="atk-send-reply">${this.$t('reply')} <span class="atk-text"></span><span class="atk-cancel">×</span></div>`);
|
||||
this.$sendReply.querySelector<HTMLElement>('.atk-text')!.innerText = `@${commentData.nick}`
|
||||
this.$sendReply.addEventListener('click', () => {
|
||||
this.cancelReply()
|
||||
})
|
||||
this.$textareaWrap.append(this.$sendReply)
|
||||
}
|
||||
this.replyComment = commentData
|
||||
|
||||
if (this.ctx.conf.editorTravel === true) {
|
||||
this.travel($comment)
|
||||
}
|
||||
|
||||
if (scroll) Ui.scrollIntoView(this.$el)
|
||||
|
||||
this.$textarea.focus()
|
||||
}
|
||||
|
||||
public cancelReply() {
|
||||
if (this.$sendReply !== null) {
|
||||
this.$sendReply.remove()
|
||||
this.$sendReply = null
|
||||
}
|
||||
this.replyComment = null
|
||||
|
||||
if (this.ctx.conf.editorTravel === true) {
|
||||
this.travelBack()
|
||||
}
|
||||
}
|
||||
|
||||
public showNotify(msg: string, type: "i"|"s"|"w"|"e") {
|
||||
Ui.showNotify(this.$notifyWrap, msg, type)
|
||||
}
|
||||
|
||||
public showLoading() {
|
||||
Ui.showLoading(this.$el)
|
||||
}
|
||||
|
||||
public hideLoading() {
|
||||
Ui.hideLoading(this.$el)
|
||||
}
|
||||
|
||||
/** 提交评论 */
|
||||
public async submit() {
|
||||
if (this.getFinalContent().trim() === '') {
|
||||
this.$textarea.focus()
|
||||
return
|
||||
}
|
||||
|
||||
this.ctx.trigger('editor-submit')
|
||||
|
||||
this.showLoading()
|
||||
|
||||
try {
|
||||
const nComment = await this.ctx.getApi().add({
|
||||
content: this.getFinalContent(),
|
||||
nick: this.user.data.nick,
|
||||
email: this.user.data.email,
|
||||
link: this.user.data.link,
|
||||
rid: (this.replyComment === null) ? 0 : this.replyComment.id,
|
||||
page_key: (this.replyComment === null) ? this.ctx.conf.pageKey : this.replyComment.page_key,
|
||||
page_title: (this.replyComment === null) ? this.ctx.conf.pageTitle : undefined,
|
||||
site_name: (this.replyComment === null) ? this.ctx.conf.site : this.replyComment.site_name
|
||||
})
|
||||
|
||||
// 回复不同页面的评论
|
||||
if (this.replyComment !== null && this.replyComment.page_key !== this.ctx.conf.pageKey) {
|
||||
window.open(`${this.replyComment.page_url}#atk-comment-${nComment.id}`)
|
||||
}
|
||||
|
||||
this.ctx.insertComment(nComment)
|
||||
this.clearEditor() // 清空编辑器
|
||||
this.ctx.trigger('editor-submitted')
|
||||
} catch (err: any) {
|
||||
console.error(err)
|
||||
this.showNotify(`${this.$t('commentFail')},${err.msg || String(err)}`, 'e')
|
||||
return
|
||||
} finally {
|
||||
this.hideLoading()
|
||||
}
|
||||
}
|
||||
|
||||
/** 关闭评论 */
|
||||
public close() {
|
||||
if (!this.$textareaWrap.querySelector('.atk-comment-closed'))
|
||||
this.$textareaWrap.prepend(Utils.createElement(`<div class="atk-comment-closed">${this.$t('onlyAdminCanReply')}</div>`))
|
||||
|
||||
if (!this.user.data.isAdmin) {
|
||||
this.$textarea.style.display = 'none'
|
||||
this.closePlugPanel()
|
||||
this.$bottom.style.display = 'none'
|
||||
} else {
|
||||
// 管理员一直打开评论
|
||||
this.$textarea.style.display = ''
|
||||
this.$bottom.style.display = ''
|
||||
}
|
||||
}
|
||||
|
||||
/** 打开评论 */
|
||||
public open() {
|
||||
this.$textareaWrap.querySelector('.atk-comment-closed')?.remove()
|
||||
this.$textarea.style.display = ''
|
||||
this.$bottom.style.display = ''
|
||||
}
|
||||
|
||||
/** 移动评论框到置顶元素之后 */
|
||||
public travel($afterEl: HTMLElement) {
|
||||
if (this.isTraveling) return
|
||||
this.isTraveling = true
|
||||
this.$el.after(Utils.createElement('<div class="atk-editor-travel-placeholder"></div>'))
|
||||
|
||||
const $travelPlace = Utils.createElement('<div></div>')
|
||||
$afterEl.after($travelPlace)
|
||||
$travelPlace.replaceWith(this.$el)
|
||||
|
||||
this.$el.classList.add('atk-fade-in') // 添加渐入动画
|
||||
}
|
||||
|
||||
/** 评论框归位 */
|
||||
public travelBack() {
|
||||
if (!this.isTraveling) return
|
||||
this.isTraveling = false
|
||||
this.ctx.$root.querySelector('.atk-editor-travel-placeholder')?.replaceWith(this.$el)
|
||||
|
||||
// 取消回复
|
||||
if (this.replyComment !== null) this.cancelReply()
|
||||
}
|
||||
|
||||
/** 插件初始化 */
|
||||
private initPlugs() {
|
||||
this.plugList = {}
|
||||
this.$plugPanelWrap.innerHTML = ''
|
||||
this.$plugPanelWrap.style.display = 'none'
|
||||
this.openedPlugName = null
|
||||
this.$plugBtnWrap.innerHTML = ''
|
||||
|
||||
const disabledPlugs: string[] = []
|
||||
if (!this.conf.emoticons) disabledPlugs.push('emoticons')
|
||||
if (!this.conf.preview) disabledPlugs.push('preview')
|
||||
|
||||
// 初始化 Editor 插件
|
||||
this.ENABLED_PLUGS.forEach((Plug) => {
|
||||
const plugName = Plug.Name
|
||||
|
||||
// 禁用的插件
|
||||
if (disabledPlugs.includes(plugName)) return
|
||||
|
||||
// 插件对象实例化
|
||||
const plug = new Plug(this)
|
||||
this.plugList[plugName] = plug
|
||||
|
||||
// 插件按钮
|
||||
const $btn = plug.getBtn()
|
||||
if ($btn) {
|
||||
this.$plugBtnWrap.appendChild($btn)
|
||||
$btn.onclick = $btn.onclick || (() => {
|
||||
// 其他按钮去除 Active
|
||||
this.$plugBtnWrap.querySelectorAll('.active').forEach(item => item.classList.remove('active'))
|
||||
|
||||
// 若点击已打开的,则关闭打开的面板
|
||||
if (plugName === this.openedPlugName) {
|
||||
this.closePlugPanel()
|
||||
return
|
||||
}
|
||||
|
||||
this.openPlugPanel(plugName)
|
||||
|
||||
// 当前按钮添加 Active
|
||||
$btn.classList.add('active')
|
||||
})
|
||||
|
||||
// 插件面板初始化
|
||||
const $panel = plug.getPanel()
|
||||
if ($panel) {
|
||||
$panel.setAttribute('data-plug-name', plugName)
|
||||
$panel.style.display = 'none'
|
||||
this.$plugPanelWrap.appendChild($panel)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/** 展开插件面板 */
|
||||
public openPlugPanel(plugName: string) {
|
||||
Object.entries(this.plugList).forEach(([aPlugName, plug]) => {
|
||||
const plugPanel = plug.getPanel()
|
||||
if (!plugPanel) return
|
||||
|
||||
if (aPlugName === plugName) {
|
||||
plugPanel.style.display = ''
|
||||
if (plug.onPanelShow) plug.onPanelShow()
|
||||
} else {
|
||||
plugPanel.style.display = 'none'
|
||||
if (plug.onPanelHide) plug.onPanelHide()
|
||||
}
|
||||
})
|
||||
|
||||
this.$plugPanelWrap.style.display = ''
|
||||
this.openedPlugName = plugName
|
||||
}
|
||||
|
||||
/** 收起插件面板 */
|
||||
public closePlugPanel() {
|
||||
if (!this.openedPlugName) return
|
||||
|
||||
const plug = this.plugList[this.openedPlugName]
|
||||
if (!plug) return
|
||||
|
||||
if (plug.onPanelHide) plug.onPanelHide()
|
||||
|
||||
this.$plugPanelWrap.style.display = 'none'
|
||||
this.openedPlugName = null
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
import Editor from './editor'
|
||||
|
||||
export default Editor
|
||||
@@ -0,0 +1,51 @@
|
||||
import * as Utils from '@/lib/utils'
|
||||
import Editor from '../editor'
|
||||
|
||||
/**
|
||||
* Editor 插件
|
||||
*
|
||||
* @desc 使用 Interface x Abstract 合并声明
|
||||
* @see https://www.typescriptlang.org/docs/handbook/declaration-merging.html#merging-interfaces
|
||||
*/
|
||||
interface EditorPlug {
|
||||
onPanelShow?(): void
|
||||
onPanelHide?(): void
|
||||
}
|
||||
|
||||
abstract class EditorPlug {
|
||||
protected editor: Editor
|
||||
protected get ctx() { return this.editor.ctx }
|
||||
protected $panel?: HTMLElement
|
||||
protected $btn?: HTMLElement
|
||||
public onHeaderInput?: (key: string, $input: HTMLElement) => void
|
||||
|
||||
public constructor(editor: Editor) {
|
||||
this.editor = editor
|
||||
}
|
||||
|
||||
public static Name: string
|
||||
|
||||
protected registerPanel(html: string = '<div></div>') {
|
||||
this.$panel = Utils.createElement(html)
|
||||
return this.$panel
|
||||
}
|
||||
|
||||
protected registerBtn(html: string) {
|
||||
this.$btn = Utils.createElement(`<span class="atk-plug-btn" data-plug-name="${this.constructor.name}">${html}</span>`)
|
||||
return this.$btn
|
||||
}
|
||||
|
||||
protected registerHeaderInputEvt(action: (key: string, $input: HTMLElement) => void) {
|
||||
this.onHeaderInput = action
|
||||
}
|
||||
|
||||
public getPanel() {
|
||||
return this.$panel
|
||||
}
|
||||
|
||||
public getBtn() {
|
||||
return this.$btn
|
||||
}
|
||||
}
|
||||
|
||||
export default EditorPlug
|
||||
+2
-1
@@ -27,7 +27,7 @@
|
||||
padding: 5px;
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
border-radius: 2px;
|
||||
border-radius: (@block-radius / 2);
|
||||
font-size: 16px;
|
||||
min-width: 35px;
|
||||
|
||||
@@ -51,6 +51,7 @@
|
||||
background: var(--at-color-bg-transl);
|
||||
height: 30px;
|
||||
border-top: 1px solid var(--at-color-border);
|
||||
border-bottom: 1px solid var(--at-color-border);
|
||||
|
||||
& > span {
|
||||
user-select: none;
|
||||
+82
-59
@@ -1,10 +1,10 @@
|
||||
import './emoticons-plug.less'
|
||||
|
||||
import Editor from '../editor'
|
||||
import EditorPlug from './editor-plug'
|
||||
import * as Utils from '~/src/lib/utils'
|
||||
import * as Ui from '~/src/lib/ui'
|
||||
import { EmoticonListData, EmoticonGrpData } from '~/types/artalk-data'
|
||||
import EditorPlug from './editor-plug'
|
||||
import Editor from '../editor'
|
||||
|
||||
type OwOFormatType = {
|
||||
[key: string] : {
|
||||
@@ -14,38 +14,78 @@ type OwOFormatType = {
|
||||
}
|
||||
|
||||
export default class EmoticonsPlug extends EditorPlug {
|
||||
public $el!: HTMLElement
|
||||
public static Name = 'emoticons'
|
||||
|
||||
declare protected $panel: HTMLElement
|
||||
|
||||
public emoticons: EmoticonListData = []
|
||||
public loadingTask: Promise<void>|null = null
|
||||
|
||||
public $grpWrap!: HTMLElement
|
||||
public $grpSwitcher!: HTMLElement
|
||||
|
||||
constructor (public editor: Editor) {
|
||||
public constructor(public editor: Editor) {
|
||||
super(editor)
|
||||
|
||||
this.$el = Utils.createElement(`<div class="atk-editor-plug-emoticons"></div>`)
|
||||
this.registerPanel(`<div class="atk-editor-plug-emoticons"></div>`)
|
||||
this.registerBtn(this.ctx.$t('emoticon'))
|
||||
|
||||
this.init()
|
||||
// 表情包预加载
|
||||
window.setTimeout(() => {
|
||||
this.loadEmoticonsData()
|
||||
}, 1000) // 延迟 1s 加载
|
||||
}
|
||||
|
||||
async init() {
|
||||
public onPanelShow() {
|
||||
;(async () => {
|
||||
await this.loadEmoticonsData()
|
||||
|
||||
// 初始化元素
|
||||
if (!this.isImgLoaded) {
|
||||
this.initEmoticonsList()
|
||||
this.isImgLoaded = true
|
||||
}
|
||||
|
||||
// 延迟执行,防止无法读取高度
|
||||
setTimeout(() => {
|
||||
this.changeListHeight()
|
||||
}, 30)
|
||||
})()
|
||||
}
|
||||
|
||||
public onPanelHide() {
|
||||
this.$panel.parentElement!.style.height = ''
|
||||
}
|
||||
|
||||
isListLoaded = false
|
||||
isImgLoaded = false
|
||||
|
||||
public async loadEmoticonsData() {
|
||||
if (this.isListLoaded) return
|
||||
if (this.loadingTask !== null) {
|
||||
await this.loadingTask
|
||||
return
|
||||
}
|
||||
|
||||
// 数据处理
|
||||
Ui.showLoading(this.$el)
|
||||
this.emoticons = await this.handleData(this.ctx.conf.emoticons)
|
||||
Ui.hideLoading(this.$el)
|
||||
|
||||
// 初始化元素
|
||||
this.initEmoticonsList()
|
||||
this.loadingTask = (async () => {
|
||||
Ui.showLoading(this.$panel)
|
||||
this.emoticons = await this.handleData(this.ctx.conf.emoticons)
|
||||
Ui.hideLoading(this.$panel)
|
||||
this.loadingTask = null
|
||||
this.isListLoaded = true
|
||||
})()
|
||||
await this.loadingTask
|
||||
}
|
||||
|
||||
async handleData(data: any): Promise<any[]> {
|
||||
private async handleData(data: any): Promise<any[]> {
|
||||
if (!Array.isArray(data) && ['object', 'string'].includes(typeof data)) {
|
||||
data = [data]
|
||||
}
|
||||
|
||||
if (!Array.isArray(data)) {
|
||||
Ui.setError(this.$el, "表情包数据必须为 Array/Object/String 类型")
|
||||
Ui.hideLoading(this.$el)
|
||||
Ui.setError(this.$panel, "表情包数据必须为 Array/Object/String 类型")
|
||||
Ui.hideLoading(this.$panel)
|
||||
return []
|
||||
}
|
||||
|
||||
@@ -85,7 +125,7 @@ export default class EmoticonsPlug extends EditorPlug {
|
||||
// 剔除非法数据
|
||||
data = data.filter((item: any) => (typeof item === 'object' && !Array.isArray(item) && !!item && !!item.name))
|
||||
|
||||
console.log(data)
|
||||
// console.log(data)
|
||||
|
||||
this.solveNullKey(data)
|
||||
this.solveSameKey(data)
|
||||
@@ -94,7 +134,7 @@ export default class EmoticonsPlug extends EditorPlug {
|
||||
}
|
||||
|
||||
/** 远程加载 */
|
||||
async remoteLoad(url: string): Promise<any> {
|
||||
private async remoteLoad(url: string): Promise<any> {
|
||||
if (!url) return []
|
||||
|
||||
try {
|
||||
@@ -102,14 +142,14 @@ export default class EmoticonsPlug extends EditorPlug {
|
||||
const json = await resp.json()
|
||||
return json
|
||||
} catch (err) {
|
||||
Ui.hideLoading(this.$el)
|
||||
Ui.setError(this.$el, `表情加载失败 ${String(err)}`)
|
||||
Ui.hideLoading(this.$panel)
|
||||
Ui.setError(this.$panel, `表情加载失败 ${String(err)}`)
|
||||
return []
|
||||
}
|
||||
}
|
||||
|
||||
/** 避免表情 item.key 为 null 的情况 */
|
||||
solveNullKey(data: EmoticonGrpData[]) {
|
||||
private solveNullKey(data: EmoticonGrpData[]) {
|
||||
data.forEach((grp) => {
|
||||
grp.items.forEach((item, index) => {
|
||||
if (!item.key) item.key = `${grp.name} ${index+1}`
|
||||
@@ -118,7 +158,7 @@ export default class EmoticonsPlug extends EditorPlug {
|
||||
}
|
||||
|
||||
/** 避免相同 item.key */
|
||||
solveSameKey(data: EmoticonGrpData[]) {
|
||||
private solveSameKey(data: EmoticonGrpData[]) {
|
||||
const tmp: {[key: string]: number} = {}
|
||||
data.forEach((grp) => {
|
||||
grp.items.forEach(item => {
|
||||
@@ -132,7 +172,7 @@ export default class EmoticonsPlug extends EditorPlug {
|
||||
}
|
||||
|
||||
/** 判断是否为 OwO 格式 */
|
||||
isOwOFormat(data: any) {
|
||||
private isOwOFormat(data: any) {
|
||||
try {
|
||||
return (typeof data === 'object') && !!Object.values(data).length
|
||||
&& Array.isArray(Object.keys(Object.values<any>(data)[0].container))
|
||||
@@ -141,7 +181,7 @@ export default class EmoticonsPlug extends EditorPlug {
|
||||
}
|
||||
|
||||
/** 转换 OwO 格式数据 */
|
||||
convertOwO(owoData: OwOFormatType): EmoticonListData {
|
||||
private convertOwO(owoData: OwOFormatType): EmoticonListData {
|
||||
const dest: EmoticonListData = []
|
||||
Object.entries(owoData).forEach(([grpName, grp]) => {
|
||||
const nGrp: EmoticonGrpData = { name: grpName, type: grp.type, items: [] }
|
||||
@@ -160,10 +200,10 @@ export default class EmoticonsPlug extends EditorPlug {
|
||||
}
|
||||
|
||||
/** 初始化表情列表界面 */
|
||||
initEmoticonsList () {
|
||||
private initEmoticonsList() {
|
||||
// 表情列表
|
||||
this.$grpWrap = Utils.createElement(`<div class="atk-grp-wrap"></div>`)
|
||||
this.$el.append(this.$grpWrap)
|
||||
this.$panel.append(this.$grpWrap)
|
||||
|
||||
this.emoticons.forEach((grp, index) => {
|
||||
const $grp = Utils.createElement(`<div class="atk-grp" style="display: none;"></div>`)
|
||||
@@ -197,24 +237,25 @@ export default class EmoticonsPlug extends EditorPlug {
|
||||
})
|
||||
})
|
||||
|
||||
// 表情分类
|
||||
this.$grpSwitcher = Utils.createElement(`<div class="atk-grp-switcher"></div>`)
|
||||
this.$el.append(this.$grpSwitcher)
|
||||
this.emoticons.forEach((grp, index) => {
|
||||
const $item = Utils.createElement('<span />')
|
||||
$item.innerText = grp.name
|
||||
$item.setAttribute('data-index', String(index))
|
||||
$item.onclick = () => (this.openGrp(index))
|
||||
this.$grpSwitcher.append($item)
|
||||
})
|
||||
// 表情分类切换 bar
|
||||
if (this.emoticons.length > 1) {
|
||||
this.$grpSwitcher = Utils.createElement(`<div class="atk-grp-switcher"></div>`)
|
||||
this.$panel.append(this.$grpSwitcher)
|
||||
this.emoticons.forEach((grp, index) => {
|
||||
const $item = Utils.createElement('<span />')
|
||||
$item.innerText = grp.name
|
||||
$item.setAttribute('data-index', String(index))
|
||||
$item.onclick = () => (this.openGrp(index))
|
||||
this.$grpSwitcher.append($item)
|
||||
})
|
||||
}
|
||||
|
||||
// 默认打开第一个分类
|
||||
if (this.emoticons.length > 0)
|
||||
this.openGrp(0)
|
||||
if (this.emoticons.length > 0) this.openGrp(0)
|
||||
}
|
||||
|
||||
/** 打开一个表情组 */
|
||||
openGrp (index: number) {
|
||||
public openGrp(index: number) {
|
||||
Array.from(this.$grpWrap.children).forEach((item) => {
|
||||
const el = item as HTMLElement
|
||||
if (el.getAttribute('data-index') !== String(index)) {
|
||||
@@ -230,31 +271,13 @@ export default class EmoticonsPlug extends EditorPlug {
|
||||
this.changeListHeight()
|
||||
}
|
||||
|
||||
static Name = 'emoticons'
|
||||
static BtnHTML = '表情'
|
||||
|
||||
getEl () {
|
||||
return this.$el
|
||||
}
|
||||
|
||||
changeListHeight () {
|
||||
private changeListHeight() {
|
||||
/* const listWrapHeight = Utils.getHeight(this.$grpWrapem)
|
||||
this.editor.plugWrapEl.style.height = `${listWrapHeight > 150 ? listWrapHeight : 150}px` */
|
||||
}
|
||||
|
||||
onShow () {
|
||||
// 延迟执行,防止无法读取高度
|
||||
setTimeout(() => {
|
||||
this.changeListHeight()
|
||||
}, 30)
|
||||
}
|
||||
|
||||
onHide () {
|
||||
this.$el.parentElement!.style.height = ''
|
||||
}
|
||||
|
||||
/** 处理评论 content 中的表情内容 */
|
||||
public transEmoticonImageText (text: string) {
|
||||
public transEmoticonImageText(text: string) {
|
||||
if (!this.emoticons || !Array.isArray(this.emoticons))
|
||||
return text
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
import Editor from '../editor'
|
||||
import EditorPlug from './editor-plug'
|
||||
|
||||
export default class HeaderInputPlug extends EditorPlug {
|
||||
public static Name = 'headerInput'
|
||||
|
||||
public constructor(editor: Editor) {
|
||||
super(editor)
|
||||
|
||||
this.registerHeaderInputEvt((key, $input) => {
|
||||
if (key === 'nick' || key === 'email') {
|
||||
this.fetchUserInfo()
|
||||
}
|
||||
})
|
||||
|
||||
// Link URL 自动补全协议
|
||||
this.editor.$link.addEventListener('change', () => {
|
||||
const link = this.editor.$link.value.trim()
|
||||
if (!!link && !/^(http|https):\/\//.test(link)) {
|
||||
this.editor.$link.value = `https://${link}`
|
||||
this.ctx.user.update({ link: this.editor.$link.value })
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
queryUserInfo = {
|
||||
timeout: <number|null>null,
|
||||
abortFunc: <(() => void)|null>null
|
||||
}
|
||||
|
||||
/** 远程获取用户数据 */
|
||||
fetchUserInfo() {
|
||||
this.ctx.user.logout()
|
||||
|
||||
// 获取用户信息
|
||||
if (this.queryUserInfo.timeout) window.clearTimeout(this.queryUserInfo.timeout) // 清除待发出的请求
|
||||
if (this.queryUserInfo.abortFunc) this.queryUserInfo.abortFunc() // 之前发出未完成的请求立刻中止
|
||||
|
||||
this.queryUserInfo.timeout = window.setTimeout(() => {
|
||||
this.queryUserInfo.timeout = null // 清理
|
||||
|
||||
const {req, abort} = this.ctx.getApi().userGet(
|
||||
this.ctx.user.data.nick, this.ctx.user.data.email
|
||||
)
|
||||
this.queryUserInfo.abortFunc = abort
|
||||
req.then(data => {
|
||||
if (!data.is_login) {
|
||||
this.ctx.user.logout()
|
||||
}
|
||||
|
||||
// 未读消息更新
|
||||
this.ctx.updateNotifies(data.unread)
|
||||
|
||||
// 若用户为管理员,执行登陆操作
|
||||
if (this.ctx.user.checkHasBasicUserInfo() && !data.is_login && data.user?.is_admin) {
|
||||
this.showLoginDialog()
|
||||
}
|
||||
|
||||
// 自动填入 link
|
||||
if (data.user && data.user.link) {
|
||||
this.editor.$link.value = data.user.link
|
||||
this.ctx.user.update({ link: data.user.link })
|
||||
}
|
||||
})
|
||||
.catch(() => {})
|
||||
.finally(() => {
|
||||
this.queryUserInfo.abortFunc = null // 清理
|
||||
})
|
||||
}, 400) // 延迟执行,减少请求次数
|
||||
}
|
||||
|
||||
showLoginDialog() {
|
||||
this.ctx.checkAdmin({
|
||||
onSuccess: () => {
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
File renamed without changes.
@@ -0,0 +1,40 @@
|
||||
import './preview-plug.less'
|
||||
|
||||
import Editor from '../editor'
|
||||
import EditorPlug from './editor-plug'
|
||||
|
||||
export default class PreviewPlug extends EditorPlug {
|
||||
public static Name = 'preview'
|
||||
declare protected $panel: HTMLElement
|
||||
|
||||
private isBind = false
|
||||
|
||||
public constructor(editor: Editor) {
|
||||
super(editor)
|
||||
|
||||
this.registerPanel(`<div class="atk-editor-plug-preview"></div>`)
|
||||
|
||||
let btnText = this.editor.$t('preview')
|
||||
if (this.ctx.markedInstance) btnText += ` <i title="Markdown is supported"><svg class="markdown" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"><path fill-rule="evenodd" d="M14.85 3H1.15C.52 3 0 3.52 0 4.15v7.69C0 12.48.52 13 1.15 13h13.69c.64 0 1.15-.52 1.15-1.15v-7.7C16 3.52 15.48 3 14.85 3zM9 11H7V8L5.5 9.92 4 8v3H2V5h2l1.5 2L7 5h2v6zm2.99.5L9.5 8H11V5h2v3h1.5l-2.51 3.5z"></path></svg></i>`
|
||||
this.registerBtn(btnText)
|
||||
}
|
||||
|
||||
public onPanelShow() {
|
||||
this.updateContent()
|
||||
|
||||
if (!this.isBind) {
|
||||
const event = () => {
|
||||
this.updateContent()
|
||||
}
|
||||
this.editor.$textarea.addEventListener('input', event)
|
||||
this.editor.$textarea.addEventListener('change', event)
|
||||
this.isBind = true
|
||||
}
|
||||
}
|
||||
|
||||
public updateContent() {
|
||||
if (this.$panel.style.display !== 'none') {
|
||||
this.$panel.innerHTML = this.editor.getContentMarked()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import * as Utils from '@/lib/utils'
|
||||
import Editor from '../editor'
|
||||
import EditorPlug from './editor-plug'
|
||||
|
||||
export default class UploadPlug extends EditorPlug {
|
||||
public static Name = 'upload'
|
||||
|
||||
public $imgUploadInput?: HTMLInputElement
|
||||
|
||||
/** 允许的图片格式 */
|
||||
allowImgExts = ['png', 'jpg', 'jpeg', 'gif', 'bmp', 'svg', 'webp']
|
||||
|
||||
public constructor(editor: Editor) {
|
||||
super(editor)
|
||||
|
||||
this.$imgUploadInput = document.createElement('input')
|
||||
this.$imgUploadInput.type = 'file'
|
||||
this.$imgUploadInput.style.display = 'none'
|
||||
this.$imgUploadInput.accept = this.allowImgExts.map(o => `.${o}`).join(',')
|
||||
|
||||
const $btn = this.registerBtn(`${this.ctx.$t('image')}`)
|
||||
$btn.after(this.$imgUploadInput)
|
||||
$btn.onclick = () => {
|
||||
// 选择图片
|
||||
const $input = this.$imgUploadInput!
|
||||
$input.onchange = () => {
|
||||
(async () => { // 解决阻塞 UI 问题
|
||||
if (!$input.files || $input.files.length === 0) return
|
||||
const file = $input.files[0]
|
||||
this.uploadImg(file)
|
||||
})()
|
||||
}
|
||||
$input.click() // 显示选择图片对话框
|
||||
}
|
||||
|
||||
this.ctx.on('conf-updated', () => {
|
||||
if (!this.ctx.conf.imgUpload) {
|
||||
this.getBtn()!.setAttribute('atk-only-admin-show', '')
|
||||
this.ctx.checkAdminShowEl()
|
||||
}
|
||||
})
|
||||
|
||||
// 统一从 FileList 获取文件并上传图片方法
|
||||
const uploadFromFileList = (files?: FileList) => {
|
||||
if (!files) return
|
||||
|
||||
for (let i = 0; i < files.length; i++) {
|
||||
const file = files[i]
|
||||
this.uploadImg(file)
|
||||
}
|
||||
}
|
||||
|
||||
// 拖拽图片
|
||||
// @link https://developer.mozilla.org/zh-CN/docs/Web/API/HTML_Drag_and_Drop_API/File_drag_and_drop
|
||||
// 阻止浏览器的默认释放行为
|
||||
this.editor.$textarea.addEventListener('dragover', (evt) => {
|
||||
evt.stopPropagation()
|
||||
evt.preventDefault()
|
||||
})
|
||||
|
||||
this.editor.$textarea.addEventListener('drop', (evt) => {
|
||||
const files = evt.dataTransfer?.files
|
||||
if (files?.length) {
|
||||
evt.preventDefault()
|
||||
uploadFromFileList(files)
|
||||
}
|
||||
})
|
||||
|
||||
// 粘贴图片
|
||||
this.editor.$textarea.addEventListener('paste', (evt) => {
|
||||
const files = evt.clipboardData?.files
|
||||
if (files?.length) {
|
||||
evt.preventDefault()
|
||||
uploadFromFileList(files)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
public async uploadImg(file: File) {
|
||||
const fileExt = /[^.]+$/.exec(file.name)
|
||||
if (!fileExt || !this.allowImgExts.includes(fileExt[0])) return
|
||||
|
||||
// 未登录提示
|
||||
if (!this.ctx.user.checkHasBasicUserInfo()) {
|
||||
this.editor.showNotify(this.ctx.$t('uploadLoginMsg'), 'w')
|
||||
return
|
||||
}
|
||||
|
||||
// 插入图片前换一行
|
||||
let insertPrefix = '\n'
|
||||
if (this.editor.$textarea.value.trim() === '') insertPrefix = ''
|
||||
|
||||
// 插入占位加载文字
|
||||
const uploadPlaceholderTxt = `${insertPrefix}`
|
||||
this.editor.insertContent(uploadPlaceholderTxt)
|
||||
|
||||
// 上传图片
|
||||
let resp: any
|
||||
try {
|
||||
if (!this.ctx.conf.imgUploader) {
|
||||
// 使用 ArtalkGo 进行图片上传
|
||||
resp = await this.ctx.getApi().imgUpload(file)
|
||||
} else {
|
||||
// 使用自定义的图片上传器
|
||||
resp = await this.ctx.conf.imgUploader(file)
|
||||
}
|
||||
} catch (err: any) {
|
||||
console.error(err)
|
||||
this.editor.showNotify(`${this.ctx.$t('uploadFail')},${err.msg}`, 'e')
|
||||
}
|
||||
if (!!resp && resp.img_url) {
|
||||
let imgURL = resp.img_url as string
|
||||
|
||||
// 若为相对路径,加上 artalk server
|
||||
if (!Utils.isValidURL(imgURL)) imgURL = Utils.getURLBasedOnApi(this.ctx, imgURL)
|
||||
|
||||
// 上传成功插入图片
|
||||
this.editor.setContent(this.editor.$textarea.value.replace(uploadPlaceholderTxt, `${insertPrefix}`))
|
||||
} else {
|
||||
// 上传失败删除加载文字
|
||||
this.editor.setContent(this.editor.$textarea.value.replace(uploadPlaceholderTxt, ''))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
export default {
|
||||
/* Editor */
|
||||
placeholder: 'Leave a comment',
|
||||
noComment: 'No Comment',
|
||||
send: 'Send',
|
||||
nick: 'Nickname',
|
||||
email: 'Email',
|
||||
link: 'Website',
|
||||
emoticon: 'Emoji',
|
||||
preview: 'Preview',
|
||||
image: 'Image',
|
||||
uploadFail: 'Upload Failed',
|
||||
commentFail: 'Failed to comment',
|
||||
restoredMsg: 'Content has been restored',
|
||||
onlyAdminCanReply: 'Only admin can reply',
|
||||
uploadLoginMsg: 'Please fill in your name and email to upload',
|
||||
|
||||
/* List */
|
||||
counter: '{count} Comments',
|
||||
sortLatest: 'Latest',
|
||||
sortOldest: 'Oldest',
|
||||
sortBest: 'Best',
|
||||
sortAuthor: 'Author',
|
||||
openComment: 'Open Comment',
|
||||
closeComment: 'Close Comment',
|
||||
listLoadFailMsg: 'Failed to load comments',
|
||||
listRetry: 'Click to retry',
|
||||
loadMore: 'Load More',
|
||||
|
||||
/* Comment */
|
||||
admin: 'Admin',
|
||||
reply: 'Reply',
|
||||
voteUp: 'Up',
|
||||
voteDown: 'Down',
|
||||
voteFail: 'Vote Failed',
|
||||
readMore: 'Read More',
|
||||
actionConfirm: 'Confirm',
|
||||
collapse: 'Collapse',
|
||||
collapsed: 'Collapsed',
|
||||
collapsedMsg: 'This comment has been collapsed',
|
||||
expand: 'Expand',
|
||||
approved: 'Approved',
|
||||
pending: 'Pending',
|
||||
pendingMsg: 'Pending, visible only to commenter.',
|
||||
delete: 'Delete',
|
||||
deleteConfirm: 'Confirm',
|
||||
pin: 'Pin',
|
||||
unpin: 'Unpin',
|
||||
|
||||
/* Time */
|
||||
seconds: 'seconds ago',
|
||||
minutes: 'minutes ago',
|
||||
hours: 'hours ago',
|
||||
days: 'days ago',
|
||||
now: 'just now',
|
||||
|
||||
/* Checker */
|
||||
adminCheck: 'Enter admin password:',
|
||||
captchaCheck: 'Enter the CAPTCHA to continue:',
|
||||
confirm: 'Confirm',
|
||||
cancel: 'Cancel',
|
||||
|
||||
/* Sidebar */
|
||||
msgCenter: 'Messages',
|
||||
ctrlCenter: 'Admin',
|
||||
|
||||
/* General */
|
||||
frontend: 'Frontend',
|
||||
backend: 'Backend',
|
||||
loading: 'Loading',
|
||||
loadFail: 'Load Failed',
|
||||
editing: 'Editing',
|
||||
editFail: 'Edit Failed',
|
||||
deleting: 'Deleting',
|
||||
deleteFail: 'Delete Failed',
|
||||
reqGot: 'Request got',
|
||||
reqAborted: 'Request timed out or terminated unexpectedly',
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import en from './en'
|
||||
import zhCN from './zh-CN'
|
||||
|
||||
export type I18n = typeof en
|
||||
|
||||
// @note the Key name is followed by `ISO 639`
|
||||
// https://en.wikipedia.org/wiki/ISO_639
|
||||
// https://datatracker.ietf.org/doc/html/rfc5646#section-2.1
|
||||
export const internal = {
|
||||
'en': en,
|
||||
'en-US': en,
|
||||
'zh-CN': zhCN,
|
||||
}
|
||||
|
||||
export const external = {
|
||||
'jp-JP': {},
|
||||
'zh-TW': {},
|
||||
'fr-FR': {},
|
||||
'de-DE': {},
|
||||
'bn-IN': {},
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import { I18n } from '.'
|
||||
|
||||
const zhCN: I18n = {
|
||||
/* Editor */
|
||||
placeholder: '键入内容...',
|
||||
noComment: '「此时无声胜有声」',
|
||||
send: '发送评论',
|
||||
nick: '昵称',
|
||||
email: '邮件',
|
||||
link: '网址',
|
||||
emoticon: '表情',
|
||||
preview: '预览',
|
||||
image: '图片',
|
||||
uploadFail: '上传失败',
|
||||
commentFail: '评论失败',
|
||||
restoredMsg: '内容已自动恢复',
|
||||
onlyAdminCanReply: '仅管理员可评论',
|
||||
uploadLoginMsg: '填入你的名字邮箱才能上传哦',
|
||||
|
||||
/* List */
|
||||
counter: '{count} 条评论',
|
||||
sortLatest: '最新',
|
||||
sortOldest: '最早',
|
||||
sortBest: '最热',
|
||||
sortAuthor: '作者',
|
||||
openComment: '打开评论',
|
||||
closeComment: '关闭评论',
|
||||
listLoadFailMsg: '无法获取评论列表数据',
|
||||
listRetry: '点击重新获取',
|
||||
loadMore: '加载更多',
|
||||
|
||||
/* Comment */
|
||||
admin: '管理员',
|
||||
reply: '回复',
|
||||
voteUp: '赞同',
|
||||
voteDown: '反对',
|
||||
voteFail: '投票失败',
|
||||
readMore: '阅读更多',
|
||||
actionConfirm: '确认操作',
|
||||
collapse: '折叠',
|
||||
collapsed: '已折叠',
|
||||
collapsedMsg: '该评论已被系统或管理员折叠',
|
||||
expand: '取消折叠',
|
||||
approved: '已审',
|
||||
pending: '待审',
|
||||
pendingMsg: '审核中,仅本人可见。',
|
||||
delete: '删除',
|
||||
deleteConfirm: '确认删除',
|
||||
pin: '置顶',
|
||||
unpin: '取消置顶',
|
||||
|
||||
/* Time */
|
||||
seconds: '秒前',
|
||||
minutes: '分钟前',
|
||||
hours: '小时前',
|
||||
days: '天前',
|
||||
now: '刚刚',
|
||||
|
||||
/* Checker */
|
||||
adminCheck: '键入密码来验证管理员身份:',
|
||||
captchaCheck: '键入验证码继续:',
|
||||
confirm: '确认',
|
||||
cancel: '取消',
|
||||
|
||||
/* Sidebar */
|
||||
msgCenter: '通知中心',
|
||||
ctrlCenter: '控制中心',
|
||||
|
||||
/* General */
|
||||
frontend: '前端',
|
||||
backend: '后端',
|
||||
loading: '加载中',
|
||||
loadFail: '加载失败',
|
||||
editing: '修改中',
|
||||
editFail: '修改失败',
|
||||
deleting: '删除中',
|
||||
deleteFail: '删除失败',
|
||||
reqGot: '请求响应',
|
||||
reqAborted: '请求超时或意外终止',
|
||||
}
|
||||
|
||||
export default zhCN
|
||||
@@ -0,0 +1,4 @@
|
||||
import Layer, { GetLayerWrap } from './layer'
|
||||
|
||||
export default Layer
|
||||
export { GetLayerWrap }
|
||||
@@ -1,4 +1,4 @@
|
||||
import Context from '../context'
|
||||
import Context from '~/types/context'
|
||||
import Component from '../lib/component'
|
||||
import * as Utils from '../lib/utils'
|
||||
import * as Ui from '../lib/ui'
|
||||
@@ -10,8 +10,8 @@ export default class Layer extends Component {
|
||||
|
||||
private maskClickHideEnable: boolean = true
|
||||
|
||||
private bodyStyleOrgOverflow = ''
|
||||
private bodyStyleOrgPaddingRight = ''
|
||||
public static BodyOrgOverflow: string
|
||||
public static BodyOrgPaddingRight: string
|
||||
|
||||
public afterHide?: Function
|
||||
|
||||
@@ -40,19 +40,19 @@ export default class Layer extends Component {
|
||||
this.$wrap.append(this.$el)
|
||||
}
|
||||
|
||||
getName () {
|
||||
getName() {
|
||||
return this.name
|
||||
}
|
||||
|
||||
getWrapEl () {
|
||||
getWrapEl() {
|
||||
return this.$wrap
|
||||
}
|
||||
|
||||
getEl () {
|
||||
getEl() {
|
||||
return this.$el
|
||||
}
|
||||
|
||||
show () {
|
||||
show() {
|
||||
this.fireAllActionTimer()
|
||||
|
||||
this.$wrap.style.display = 'block'
|
||||
@@ -65,12 +65,7 @@ export default class Layer extends Component {
|
||||
}
|
||||
|
||||
// body style 禁止滚动 + 防抖
|
||||
this.bodyStyleOrgOverflow = document.body.style.overflow
|
||||
this.bodyStyleOrgPaddingRight = document.body.style.paddingRight
|
||||
document.body.style.overflow = 'hidden'
|
||||
|
||||
const bpr = parseInt(window.getComputedStyle(document.body, null).getPropertyValue('padding-right'), 10)
|
||||
document.body.style.paddingRight = `${Ui.getScrollBarWidth() + bpr || 0}px`
|
||||
this.pageBodyScrollBarHide()
|
||||
}
|
||||
|
||||
hide () {
|
||||
@@ -78,11 +73,11 @@ export default class Layer extends Component {
|
||||
this.$wrap.classList.add('atk-fade-out')
|
||||
this.$el.style.display = 'none'
|
||||
|
||||
// body style 禁止滚动解除
|
||||
this.pageBodyScrollBarShow()
|
||||
|
||||
this.newActionTimer(() => {
|
||||
this.$wrap.style.display = 'none'
|
||||
// body style 禁止滚动解除
|
||||
document.body.style.overflow = this.bodyStyleOrgOverflow
|
||||
document.body.style.paddingRight = this.bodyStyleOrgPaddingRight
|
||||
this.checkCleanLayer()
|
||||
}, 450)
|
||||
this.newActionTimer(() => {
|
||||
@@ -95,6 +90,20 @@ export default class Layer extends Component {
|
||||
this.maskClickHideEnable = enable
|
||||
}
|
||||
|
||||
// 页面滚动条隐藏
|
||||
pageBodyScrollBarHide() {
|
||||
document.body.style.overflow = 'hidden'
|
||||
|
||||
const bpr = parseInt(window.getComputedStyle(document.body, null).getPropertyValue('padding-right'), 10)
|
||||
document.body.style.paddingRight = `${Ui.getScrollBarWidth() + bpr || 0}px`
|
||||
}
|
||||
|
||||
// 页面滚动条显示
|
||||
pageBodyScrollBarShow() {
|
||||
document.body.style.overflow = Layer.BodyOrgOverflow
|
||||
document.body.style.paddingRight = Layer.BodyOrgPaddingRight
|
||||
}
|
||||
|
||||
// Timers
|
||||
private static actionTimers: {act: Function, tid: number}[] = []
|
||||
|
||||
@@ -117,29 +126,29 @@ export default class Layer extends Component {
|
||||
}
|
||||
|
||||
/** 销毁 - 无动画 */
|
||||
disposeNow () {
|
||||
document.body.style.overflow = ''
|
||||
disposeNow() {
|
||||
this.$el.remove()
|
||||
this.pageBodyScrollBarShow()
|
||||
// this.$el dispose
|
||||
this.checkCleanLayer()
|
||||
}
|
||||
|
||||
/** 销毁 */
|
||||
dispose () {
|
||||
dispose() {
|
||||
this.hide()
|
||||
this.$el.remove()
|
||||
// this.$el dispose
|
||||
this.checkCleanLayer()
|
||||
}
|
||||
|
||||
checkCleanLayer () {
|
||||
checkCleanLayer() {
|
||||
if (this.getWrapEl().querySelectorAll('.atk-layer-item').length === 0) {
|
||||
this.$wrap.style.display = 'none'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function GetLayerWrap (ctx: Context): { $wrap: HTMLElement, $mask: HTMLElement } {
|
||||
export function GetLayerWrap(ctx: Context): { $wrap: HTMLElement, $mask: HTMLElement } {
|
||||
let $wrap = document.querySelector<HTMLElement>(`.atk-layer-wrap#ctx-${ctx.cid}`)
|
||||
if (!$wrap) {
|
||||
$wrap = Utils.createElement(
|
||||
File renamed without changes.
@@ -0,0 +1,143 @@
|
||||
import '../style/sidebar-layer.less'
|
||||
|
||||
import Context from '~/types/context'
|
||||
import Component from '@/lib/component'
|
||||
import * as Utils from '@/lib/utils'
|
||||
import * as Ui from '@/lib/ui'
|
||||
import SidebarHTML from './sidebar-layer.html?raw'
|
||||
import Layer from './layer'
|
||||
|
||||
export interface SidebarShowPayload {
|
||||
view?: 'comments'|'sites'|'pages'|'transfer'
|
||||
}
|
||||
|
||||
export default class SidebarLayer extends Component {
|
||||
public layer?: Layer
|
||||
public $header: HTMLElement
|
||||
public $closeBtn: HTMLElement
|
||||
public $iframeWrap: HTMLElement
|
||||
public $iframe?: HTMLIFrameElement
|
||||
|
||||
constructor(ctx: Context) {
|
||||
super(ctx)
|
||||
|
||||
this.$el = Utils.createElement(SidebarHTML)
|
||||
this.$header = this.$el.querySelector('.atk-sidebar-header')!
|
||||
this.$closeBtn = this.$header.querySelector('.atk-sidebar-close')!
|
||||
this.$iframeWrap = this.$el.querySelector('.atk-sidebar-iframe-wrap')!
|
||||
|
||||
this.$closeBtn.onclick = () => {
|
||||
this.hide()
|
||||
}
|
||||
|
||||
// event
|
||||
this.ctx.on('user-changed', () => { this.firstShow = true })
|
||||
}
|
||||
|
||||
private firstShow = true
|
||||
|
||||
/** 显示 */
|
||||
public async show(conf: SidebarShowPayload = {}) {
|
||||
this.$el.style.transform = '' // 动画清除,防止二次打开失效
|
||||
|
||||
// 获取 Layer
|
||||
if (this.layer == null) {
|
||||
this.layer = new Layer(this.ctx, 'sidebar', this.$el)
|
||||
this.layer.afterHide = () => {
|
||||
// 防止评论框被吞
|
||||
if (this.ctx.conf.editorTravel === true) {
|
||||
this.ctx.editorTravelBack()
|
||||
}
|
||||
}
|
||||
}
|
||||
this.layer.show()
|
||||
|
||||
// viewWrap 滚动条归位
|
||||
// this.$viewWrap.scrollTo(0, 0)
|
||||
|
||||
// 执行动画
|
||||
setTimeout(() => {
|
||||
this.$el.style.transform = 'translate(0, 0)'
|
||||
}, 20)
|
||||
|
||||
// 管理员身份验证 (若身份失效,弹出验证窗口)
|
||||
;(async () => {
|
||||
const resp = await this.ctx.getApi().loginStatus()
|
||||
if (resp.is_admin && !resp.is_login) {
|
||||
this.layer?.hide()
|
||||
this.firstShow = true
|
||||
|
||||
this.ctx.checkAdmin({
|
||||
onSuccess: () => {
|
||||
setTimeout(() => {
|
||||
this.show(conf)
|
||||
}, 500)
|
||||
},
|
||||
onCancel: () => {}
|
||||
})
|
||||
}
|
||||
})()
|
||||
|
||||
// 清空 unread
|
||||
this.ctx.updateNotifies([])
|
||||
|
||||
// 第一次加载
|
||||
if (this.firstShow) {
|
||||
this.$iframeWrap.innerHTML = ''
|
||||
this.$iframe = Utils.createElement<HTMLIFrameElement>('<iframe></iframe>')
|
||||
|
||||
// 准备 Iframe 参数
|
||||
const baseURL = (import.meta.env.DEV) ? 'http://localhost:23367/'
|
||||
: Utils.getURLBasedOnApi(this.ctx, '/sidebar/')
|
||||
|
||||
const query: any = {
|
||||
pageKey: this.conf.pageKey,
|
||||
site: this.conf.site || '',
|
||||
user: JSON.stringify(this.ctx.user.data),
|
||||
time: +new Date()
|
||||
}
|
||||
|
||||
if (conf.view) query.view = conf.view
|
||||
if (this.conf.darkMode) query.darkMode = '1'
|
||||
|
||||
const urlParams = new URLSearchParams(query);
|
||||
this.iframeLoad(`${baseURL}?${urlParams.toString()}`)
|
||||
|
||||
this.$iframeWrap.append(this.$iframe)
|
||||
this.firstShow = false
|
||||
} else {
|
||||
// 暗黑模式
|
||||
const isIframeSrcDarkMode = this.$iframe!.src.includes('darkMode=1')
|
||||
|
||||
if (this.conf.darkMode && !isIframeSrcDarkMode)
|
||||
this.iframeLoad(`${this.$iframe!.src}&darkMode=1`)
|
||||
|
||||
if (!this.conf.darkMode && isIframeSrcDarkMode)
|
||||
this.iframeLoad(this.$iframe!.src.replace('&darkMode=1', ''))
|
||||
}
|
||||
|
||||
this.ctx.trigger('sidebar-show')
|
||||
}
|
||||
|
||||
/** 隐藏 */
|
||||
public hide() {
|
||||
// 执行动画
|
||||
this.$el.style.transform = ''
|
||||
|
||||
this.layer?.hide()
|
||||
|
||||
this.ctx.trigger('sidebar-hide')
|
||||
}
|
||||
|
||||
private iframeLoad(src: string) {
|
||||
if (!this.$iframe) return
|
||||
|
||||
this.$iframe.src = src
|
||||
|
||||
// 加载动画
|
||||
Ui.showLoading(this.$iframeWrap)
|
||||
this.$iframe.onload = () => {
|
||||
Ui.hideLoading(this.$iframeWrap)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,33 +1,33 @@
|
||||
import Api from '@/api'
|
||||
import * as Utils from '../utils'
|
||||
import { Checker } from '.'
|
||||
|
||||
const AdminChecker: Checker = {
|
||||
inputType: 'password',
|
||||
|
||||
request(that, inputVal) {
|
||||
request(that, ctx, inputVal) {
|
||||
const data = {
|
||||
name: that.ctx.user.data.nick,
|
||||
email: that.ctx.user.data.email,
|
||||
password: inputVal
|
||||
}
|
||||
|
||||
return new Api(that.ctx).login(data.name, data.email, data.password)
|
||||
return that.ctx.getApi().login(data.name, data.email, data.password)
|
||||
},
|
||||
|
||||
body() {
|
||||
return Utils.createElement('<span>敲入密码来验证管理员身份:</span>')
|
||||
body(that, ctx) {
|
||||
return Utils.createElement(`<span>${that.ctx.$t('adminCheck')}</span>`)
|
||||
},
|
||||
|
||||
onSuccess(that, userToken, inputVal, formEl) {
|
||||
that.ctx.user.data.isAdmin = true
|
||||
that.ctx.user.data.token = userToken
|
||||
that.ctx.user.save()
|
||||
onSuccess(that, ctx, userToken, inputVal, formEl) {
|
||||
that.ctx.user.update({
|
||||
isAdmin: true,
|
||||
token: userToken
|
||||
})
|
||||
that.ctx.trigger('user-changed', that.ctx.user.data)
|
||||
that.ctx.trigger('list-reload')
|
||||
that.ctx.listReload()
|
||||
},
|
||||
|
||||
onError(that, err, inputVal, formEl) {}
|
||||
onError(that, ctx, err, inputVal, formEl) {}
|
||||
}
|
||||
|
||||
export default AdminChecker
|
||||
@@ -1,36 +1,81 @@
|
||||
import Api from '@/api'
|
||||
import * as Utils from '../utils'
|
||||
import * as Ui from '../ui'
|
||||
import { Checker } from '.'
|
||||
|
||||
const CaptchaChecker: Checker = {
|
||||
request(that, inputVal) {
|
||||
return new Api(that.ctx).captchaCheck(inputVal)
|
||||
request(that, ctx, inputVal) {
|
||||
return that.ctx.getApi().captchaCheck(inputVal)
|
||||
},
|
||||
|
||||
body(that) {
|
||||
body(that, ctx) {
|
||||
// Iframe 验证方式
|
||||
if (that.captchaConf.iframe) {
|
||||
const $iframeWrap = Utils.createElement(`<div class="atk-checker-iframe-wrap"></div>`)
|
||||
const $iframe = Utils.createElement<HTMLIFrameElement>(`<iframe class="atk-fade-in"></iframe>`)
|
||||
$iframe.style.display = 'none'
|
||||
Ui.showLoading($iframeWrap, { transparentBg: true })
|
||||
$iframe.src = `${that.ctx.conf.server}/api/captcha/get?t=${+new Date()}`
|
||||
$iframe.onload = () => {
|
||||
$iframe.style.display = ''
|
||||
Ui.hideLoading($iframeWrap)
|
||||
}
|
||||
$iframeWrap.append($iframe)
|
||||
|
||||
const $closeBtn = Utils.createElement(`<div class="atk-close-btn"><i class="atk-icon atk-icon-close"></i></div>`)
|
||||
$iframeWrap.append($closeBtn)
|
||||
|
||||
ctx.hideInteractInput()
|
||||
|
||||
// 轮询状态
|
||||
let stop = false // 打断
|
||||
const sleep = (ms: number) => new Promise((resolve) => { window.setTimeout(() => { resolve(null) }, ms) })
|
||||
;(async function queryStatus() {
|
||||
await sleep(1000)
|
||||
if (stop) return
|
||||
let isPass = false
|
||||
try {
|
||||
const resp = await that.ctx.getApi().captchaStatus()
|
||||
isPass = resp.is_pass
|
||||
} catch { isPass = false }
|
||||
if (isPass) {
|
||||
ctx.triggerSuccess()
|
||||
} else {
|
||||
queryStatus()
|
||||
}
|
||||
})()
|
||||
|
||||
$closeBtn.onclick = () => {
|
||||
stop = true
|
||||
ctx.cancel()
|
||||
}
|
||||
|
||||
return $iframeWrap
|
||||
}
|
||||
|
||||
// 图片验证方式
|
||||
const elem = Utils.createElement(
|
||||
`<span><img class="atk-captcha-img" src="${that.submitCaptchaImgData || ''}" alt="验证码">敲入验证码继续:</span>`
|
||||
`<span><img class="atk-captcha-img" src="${that.captchaConf.imgData || ''}">${that.ctx.$t('captchaCheck')}</span>`
|
||||
);
|
||||
|
||||
// 刷新验证码
|
||||
elem.querySelector<HTMLElement>('.atk-captcha-img')!.onclick = () => {
|
||||
const imgEl = elem.querySelector('.atk-captcha-img')
|
||||
new Api(that.ctx).captchaGet()
|
||||
that.ctx.getApi().captchaGet()
|
||||
.then((imgData) => {
|
||||
imgEl!.setAttribute('src', imgData)
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error('验证码获取失败 ', err)
|
||||
console.error('Failed to get captcha image ', err)
|
||||
})
|
||||
}
|
||||
return elem
|
||||
},
|
||||
|
||||
onSuccess(that, data, inputVal, formEl) {
|
||||
that.submitCaptchaVal = inputVal
|
||||
onSuccess(that, ctx, data, inputVal, formEl) {
|
||||
that.captchaConf.val = inputVal
|
||||
},
|
||||
|
||||
onError(that, err, inputVal, formEl) {
|
||||
onError(that, ctx, err, inputVal, formEl) {
|
||||
formEl.querySelector<HTMLElement>('.atk-captcha-img')!.click() // 刷新验证码
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,22 @@
|
||||
import Context from '@/context'
|
||||
import Layer from '@/components/layer'
|
||||
import Context from '~/types/context'
|
||||
import Dialog from '@/components/dialog'
|
||||
import Layer from '@/layer'
|
||||
import * as Utils from '../utils'
|
||||
import * as Ui from '../ui'
|
||||
import { CheckerPayload } from '~/types/event'
|
||||
import CaptchaChecker from './captcha-checker'
|
||||
import AdminChecker from './admin-checker'
|
||||
|
||||
export interface CheckerCaptchaPayload extends CheckerPayload {
|
||||
imgData?: string
|
||||
iframe?: string
|
||||
}
|
||||
|
||||
export interface CheckerPayload {
|
||||
onSuccess?: (inputVal: string, dialogEl?: HTMLElement) => void
|
||||
onMount?: (dialogEl: HTMLElement) => void
|
||||
onCancel?: () => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Checker 发射台
|
||||
*/
|
||||
@@ -14,47 +24,63 @@ export default class CheckerLauncher {
|
||||
public ctx: Context
|
||||
|
||||
public launched: Checker[] = []
|
||||
public submitCaptchaVal?: string
|
||||
public submitCaptchaImgData?: string
|
||||
public captchaConf: { val?: string, imgData?: string, iframe?: string } = {}
|
||||
|
||||
constructor(ctx: Context) {
|
||||
this.ctx = ctx
|
||||
|
||||
this.initEventBind()
|
||||
}
|
||||
|
||||
/** 初始化事件绑定 */
|
||||
public initEventBind() {
|
||||
this.ctx.on('checker-captcha', (conf) => {
|
||||
if (conf.imgData) {
|
||||
this.submitCaptchaImgData = conf.imgData
|
||||
}
|
||||
this.fire(CaptchaChecker, conf)
|
||||
})
|
||||
public checkCaptcha(payload: CheckerCaptchaPayload) {
|
||||
this.captchaConf.imgData = payload.imgData
|
||||
this.captchaConf.iframe = payload.iframe
|
||||
|
||||
this.ctx.on('checker-admin', (conf) => {
|
||||
this.fire(AdminChecker, conf)
|
||||
})
|
||||
this.fire(CaptchaChecker, payload)
|
||||
}
|
||||
|
||||
public checkAdmin(payload: CheckerPayload) {
|
||||
this.fire(AdminChecker, payload)
|
||||
}
|
||||
|
||||
public fire(checker: Checker, payload: CheckerPayload) {
|
||||
if (this.launched.includes(checker)) return // 阻止同时 fire 相同的 checker
|
||||
this.launched.push(checker)
|
||||
|
||||
// 创建层
|
||||
const layer = new Layer(this.ctx, `checker-${new Date().getTime()}`)
|
||||
layer.setMaskClickHide(false)
|
||||
layer.show()
|
||||
|
||||
const formEl = Utils.createElement()
|
||||
formEl.appendChild(checker.body(this))
|
||||
// Checker 的上下文
|
||||
let hideInteractInput = false
|
||||
const checkerCtx: CheckerCtx = {
|
||||
getLayer: () => layer,
|
||||
hideInteractInput: () => {
|
||||
hideInteractInput = true
|
||||
},
|
||||
triggerSuccess: () => {
|
||||
this.close(checker, layer)
|
||||
if (checker.onSuccess) checker.onSuccess(this, checkerCtx, "", "", formEl)
|
||||
if (payload.onSuccess) payload.onSuccess("", dialog.$el)
|
||||
},
|
||||
cancel: () => {
|
||||
this.close(checker, layer)
|
||||
if (payload.onCancel) payload.onCancel()
|
||||
}
|
||||
}
|
||||
|
||||
const input = Utils.createElement<HTMLInputElement>(
|
||||
// 创建表单
|
||||
const formEl = Utils.createElement()
|
||||
formEl.appendChild(checker.body(this, checkerCtx))
|
||||
|
||||
// 输入框
|
||||
const $input = Utils.createElement<HTMLInputElement>(
|
||||
`<input id="check" type="${checker.inputType || 'text'}" autocomplete="off" required placeholder="">`
|
||||
)
|
||||
formEl.appendChild(input)
|
||||
setTimeout(() => input.focus(), 80) // 延迟 Focus
|
||||
formEl.appendChild($input)
|
||||
setTimeout(() => $input.focus(), 80) // 延迟 Focus
|
||||
|
||||
input.onkeyup = (evt) => {
|
||||
// 绑定键盘事件
|
||||
$input.onkeyup = (evt) => {
|
||||
if (evt.key === 'Enter' || evt.keyCode === 13) {
|
||||
// 按下回车键
|
||||
evt.preventDefault()
|
||||
@@ -66,11 +92,13 @@ export default class CheckerLauncher {
|
||||
}
|
||||
|
||||
let btnTextOrg: string | undefined
|
||||
const dialog = new Dialog(formEl)
|
||||
const dialog = new Dialog(this.ctx, formEl)
|
||||
|
||||
// 确认按钮
|
||||
dialog.setYes((btnEl) => {
|
||||
const inputVal = input.value.trim()
|
||||
const inputVal = $input.value.trim()
|
||||
|
||||
// 按钮操作
|
||||
if (!btnTextOrg) btnTextOrg = btnEl.innerText
|
||||
const btnTextSet = (btnText: string) => {
|
||||
btnEl.innerText = btnText
|
||||
@@ -81,23 +109,27 @@ export default class CheckerLauncher {
|
||||
btnEl.classList.remove('error')
|
||||
}
|
||||
|
||||
btnEl.innerText = '加载中...'
|
||||
btnEl.innerText = `${this.ctx.$t('loading')}...`
|
||||
|
||||
// 发送请求
|
||||
checker
|
||||
.request(this, inputVal)
|
||||
.request(this, checkerCtx, inputVal)
|
||||
.then((data) => {
|
||||
// 请求成功
|
||||
this.done(checker, layer)
|
||||
if (checker.onSuccess) checker.onSuccess(this, data, inputVal, formEl)
|
||||
this.close(checker, layer)
|
||||
|
||||
if (checker.onSuccess) checker.onSuccess(this, checkerCtx, data, inputVal, formEl)
|
||||
if (payload.onSuccess) payload.onSuccess(inputVal, dialog.$el)
|
||||
})
|
||||
.catch((err) => {
|
||||
// 请求失败
|
||||
btnTextSet(String(err.msg || String(err)))
|
||||
if (checker.onError) checker.onError(this, err, inputVal, formEl)
|
||||
|
||||
if (checker.onError) checker.onError(this, checkerCtx, err, inputVal, formEl)
|
||||
|
||||
// 错误显示 3s 后恢复按钮
|
||||
const tf = setTimeout(() => btnTextRestore(), 3000)
|
||||
input.onfocus = () => {
|
||||
$input.onfocus = () => {
|
||||
btnTextRestore()
|
||||
clearTimeout(tf)
|
||||
}
|
||||
@@ -108,17 +140,25 @@ export default class CheckerLauncher {
|
||||
|
||||
// 取消按钮
|
||||
dialog.setNo(() => {
|
||||
this.done(checker, layer)
|
||||
this.close(checker, layer)
|
||||
if (payload.onCancel) payload.onCancel()
|
||||
return false
|
||||
})
|
||||
|
||||
if (hideInteractInput) {
|
||||
$input.style.display = 'none'
|
||||
dialog.$el.querySelector<HTMLElement>('.atk-layer-dialog-actions')!.style.display = 'none'
|
||||
}
|
||||
|
||||
// 层装载 dialog 元素
|
||||
layer.getEl().append(dialog.$el)
|
||||
|
||||
if (payload.onMount) payload.onMount(dialog.$el) // onMount
|
||||
// onMount 回调
|
||||
if (payload.onMount) payload.onMount(dialog.$el)
|
||||
}
|
||||
|
||||
private done(checker: Checker, layer: Layer) {
|
||||
// 关闭 checker 对话框
|
||||
private close(checker: Checker, layer: Layer) {
|
||||
layer.disposeNow()
|
||||
this.launched = this.launched.filter(c => c !== checker)
|
||||
}
|
||||
@@ -127,8 +167,15 @@ export default class CheckerLauncher {
|
||||
export interface Checker {
|
||||
el?: HTMLElement
|
||||
inputType?: 'password' | 'text'
|
||||
body: (launcher: CheckerLauncher) => HTMLElement
|
||||
request: (launcher: CheckerLauncher, inputVal: string) => Promise<string>
|
||||
onSuccess?: (launcher: CheckerLauncher, data: string, inputVal: string, formEl: HTMLElement) => void
|
||||
onError?: (launcher: CheckerLauncher, err: any, inputVal: string, formEl: HTMLElement) => void
|
||||
body: (launcher: CheckerLauncher, ctx: CheckerCtx) => HTMLElement
|
||||
request: (launcher: CheckerLauncher, ctx: CheckerCtx, inputVal: string) => Promise<string>
|
||||
onSuccess?: (launcher: CheckerLauncher, ctx: CheckerCtx, data: string, inputVal: string, formEl: HTMLElement) => void
|
||||
onError?: (launcher: CheckerLauncher, ctx: CheckerCtx, err: any, inputVal: string, formEl: HTMLElement) => void
|
||||
}
|
||||
|
||||
export interface CheckerCtx {
|
||||
getLayer(): Layer
|
||||
hideInteractInput(): void
|
||||
triggerSuccess(): void
|
||||
cancel(): void
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
import ArtalkConfig from '~/types/artalk-config'
|
||||
import Context from '../context'
|
||||
import Context from '~/types/context'
|
||||
import { I18n } from '../i18n'
|
||||
|
||||
export default class Component {
|
||||
export default abstract class Component {
|
||||
public $el!: HTMLElement
|
||||
|
||||
public ctx: Context
|
||||
@@ -11,4 +12,8 @@ export default class Component {
|
||||
this.ctx = ctx
|
||||
this.conf = ctx.conf
|
||||
}
|
||||
|
||||
public $t(key: keyof I18n, args: {[key: string]: string} = {}): string {
|
||||
return this.ctx.$t(key, args)
|
||||
}
|
||||
}
|
||||
@@ -1,263 +0,0 @@
|
||||
/* eslint-disable */
|
||||
var win = window || {}
|
||||
var nav = navigator || {}
|
||||
function Detect (userAgent) {
|
||||
var u = userAgent || nav.userAgent
|
||||
var _this = this
|
||||
|
||||
var match = {
|
||||
// 内核
|
||||
Trident: u.indexOf('Trident') > -1 || u.indexOf('NET CLR') > -1,
|
||||
Presto: u.indexOf('Presto') > -1,
|
||||
WebKit: u.indexOf('AppleWebKit') > -1,
|
||||
Gecko: u.indexOf('Gecko/') > -1,
|
||||
// 浏览器
|
||||
Safari: u.indexOf('Safari') > -1,
|
||||
Chrome: u.indexOf('Chrome') > -1 || u.indexOf('CriOS') > -1,
|
||||
IE: u.indexOf('MSIE') > -1 || u.indexOf('Trident') > -1,
|
||||
Edge: u.indexOf('Edge') > -1,
|
||||
Firefox: u.indexOf('Firefox') > -1 || u.indexOf('FxiOS') > -1,
|
||||
'Firefox Focus': u.indexOf('Focus') > -1,
|
||||
Chromium: u.indexOf('Chromium') > -1,
|
||||
Opera: u.indexOf('Opera') > -1 || u.indexOf('OPR') > -1,
|
||||
Vivaldi: u.indexOf('Vivaldi') > -1,
|
||||
Yandex: u.indexOf('YaBrowser') > -1,
|
||||
Kindle: u.indexOf('Kindle') > -1 || u.indexOf('Silk/') > -1,
|
||||
360: u.indexOf('360EE') > -1 || u.indexOf('360SE') > -1,
|
||||
UC: u.indexOf('UC') > -1 || u.indexOf(' UBrowser') > -1,
|
||||
QQBrowser: u.indexOf('QQBrowser') > -1,
|
||||
QQ: u.indexOf('QQ/') > -1,
|
||||
Baidu: u.indexOf('Baidu') > -1 || u.indexOf('BIDUBrowser') > -1,
|
||||
Maxthon: u.indexOf('Maxthon') > -1,
|
||||
Sogou: u.indexOf('MetaSr') > -1 || u.indexOf('Sogou') > -1,
|
||||
LBBROWSER: u.indexOf('LBBROWSER') > -1,
|
||||
'2345Explorer': u.indexOf('2345Explorer') > -1,
|
||||
TheWorld: u.indexOf('TheWorld') > -1,
|
||||
XiaoMi: u.indexOf('MiuiBrowser') > -1,
|
||||
Quark: u.indexOf('Quark') > -1,
|
||||
Qiyu: u.indexOf('Qiyu') > -1,
|
||||
Wechat: u.indexOf('MicroMessenger') > -1,
|
||||
Taobao: u.indexOf('AliApp(TB') > -1,
|
||||
Alipay: u.indexOf('AliApp(AP') > -1,
|
||||
Weibo: u.indexOf('Weibo') > -1,
|
||||
Douban: u.indexOf('com.douban.frodo') > -1,
|
||||
Suning: u.indexOf('SNEBUY-APP') > -1,
|
||||
iQiYi: u.indexOf('IqiyiApp') > -1,
|
||||
// 系统或平台
|
||||
Windows: u.indexOf('Windows') > -1,
|
||||
Linux: u.indexOf('Linux') > -1 || u.indexOf('X11') > -1,
|
||||
'Mac OS': u.indexOf('Macintosh') > -1,
|
||||
Android: u.indexOf('Android') > -1 || u.indexOf('Adr') > -1,
|
||||
Ubuntu: u.indexOf('Ubuntu') > -1,
|
||||
FreeBSD: u.indexOf('FreeBSD') > -1,
|
||||
Debian: u.indexOf('Debian') > -1,
|
||||
'Windows Phone': u.indexOf('IEMobile') > -1 || u.indexOf('Windows Phone') > -1,
|
||||
BlackBerry: u.indexOf('BlackBerry') > -1 || u.indexOf('RIM') > -1,
|
||||
MeeGo: u.indexOf('MeeGo') > -1,
|
||||
Symbian: u.indexOf('Symbian') > -1,
|
||||
iOS: u.indexOf('like Mac OS X') > -1,
|
||||
'Chrome OS': u.indexOf('CrOS') > -1,
|
||||
WebOS: u.indexOf('hpwOS') > -1,
|
||||
// 设备
|
||||
Mobile: u.indexOf('Mobi') > -1 || u.indexOf('iPh') > -1 || u.indexOf('480') > -1,
|
||||
Tablet: u.indexOf('Tablet') > -1 || u.indexOf('Pad') > -1 || u.indexOf('Nexus 7') > -1
|
||||
}
|
||||
// 修正
|
||||
if (match.Mobile) {
|
||||
match.Mobile = !(u.indexOf('iPad') > -1)
|
||||
} else if (win.showModalDialog && win.chrome) {
|
||||
match['360'] = true
|
||||
}
|
||||
// 基本信息
|
||||
var hash = {
|
||||
engine: ['WebKit', 'Trident', 'Gecko', 'Presto'],
|
||||
browser: ['Safari', 'Chrome', 'Edge', 'IE', 'Firefox', 'Firefox Focus', 'Chromium', 'Opera', 'Vivaldi', 'Yandex', 'Kindle', '360', 'UC', 'QQBrowser', 'QQ', 'Baidu', 'Maxthon', 'Sogou', 'LBBROWSER', '2345Explorer', 'TheWorld', 'XiaoMi', 'Quark', 'Qiyu', 'Wechat', 'Taobao', 'Alipay', 'Weibo', 'Douban', 'Suning', 'iQiYi'],
|
||||
os: ['Windows', 'Linux', 'Mac OS', 'Android', 'Ubuntu', 'FreeBSD', 'Debian', 'iOS', 'Windows Phone', 'BlackBerry', 'MeeGo', 'Symbian', 'Chrome OS', 'WebOS'],
|
||||
device: ['Mobile', 'Tablet']
|
||||
}
|
||||
_this.device = 'PC'
|
||||
_this.language = (function () {
|
||||
var g = (nav.browserLanguage || nav.language)
|
||||
var arr = g.split('-')
|
||||
if (arr[1]) {
|
||||
arr[1] = arr[1].toUpperCase()
|
||||
}
|
||||
return arr.join('_')
|
||||
})()
|
||||
for (var s in hash) {
|
||||
for (var i = 0; i < hash[s].length; i++) {
|
||||
var value = hash[s][i]
|
||||
if (match[value]) {
|
||||
_this[s] = value
|
||||
}
|
||||
}
|
||||
}
|
||||
// 系统版本信息
|
||||
var osVersion = {
|
||||
Windows: function () {
|
||||
var v = u.replace(/^.*Windows NT ([\d.]+);.*$/, '$1')
|
||||
var hash = {
|
||||
6.4: '10',
|
||||
6.3: '8.1',
|
||||
6.2: '8',
|
||||
6.1: '7',
|
||||
'6.0': 'Vista',
|
||||
5.2: 'XP',
|
||||
5.1: 'XP',
|
||||
'5.0': '2000',
|
||||
'10.0': '10',
|
||||
'11.0': '11' // 自定的,不是微软官方的判断方法
|
||||
}
|
||||
return hash[v] || v
|
||||
},
|
||||
Android: function () {
|
||||
return u.replace(/^.*Android ([\d.]+);.*$/, '$1')
|
||||
},
|
||||
iOS: function () {
|
||||
return u.replace(/^.*OS ([\d_]+) like.*$/, '$1').replace(/_/g, '.')
|
||||
},
|
||||
Debian: function () {
|
||||
return u.replace(/^.*Debian\/([\d.]+).*$/, '$1')
|
||||
},
|
||||
'Windows Phone': function () {
|
||||
return u.replace(/^.*Windows Phone( OS)? ([\d.]+);.*$/, '$2')
|
||||
},
|
||||
'Mac OS': function () {
|
||||
return u.replace(/^.*Mac OS X ([\d_]+).*$/, '$1').replace(/_/g, '.')
|
||||
},
|
||||
WebOS: function () {
|
||||
return u.replace(/^.*hpwOS\/([\d.]+);.*$/, '$1')
|
||||
}
|
||||
}
|
||||
_this.osVersion = ''
|
||||
if (osVersion[_this.os]) {
|
||||
_this.osVersion = osVersion[_this.os]()
|
||||
if (_this.osVersion === u) {
|
||||
_this.osVersion = ''
|
||||
}
|
||||
}
|
||||
// 浏览器版本信息
|
||||
var version = {
|
||||
Safari: function () {
|
||||
return u.replace(/^.*Version\/([\d.]+).*$/, '$1')
|
||||
},
|
||||
Chrome: function () {
|
||||
return u.replace(/^.*Chrome\/([\d.]+).*$/, '$1').replace(/^.*CriOS\/([\d.]+).*$/, '$1')
|
||||
},
|
||||
IE: function () {
|
||||
return u.replace(/^.*MSIE ([\d.]+).*$/, '$1').replace(/^.*rv:([\d.]+).*$/, '$1')
|
||||
},
|
||||
Edge: function () {
|
||||
return u.replace(/^.*Edge\/([\d.]+).*$/, '$1')
|
||||
},
|
||||
Firefox: function () {
|
||||
return u.replace(/^.*Firefox\/([\d.]+).*$/, '$1').replace(/^.*FxiOS\/([\d.]+).*$/, '$1')
|
||||
},
|
||||
'Firefox Focus': function () {
|
||||
return u.replace(/^.*Focus\/([\d.]+).*$/, '$1')
|
||||
},
|
||||
Chromium: function () {
|
||||
return u.replace(/^.*Chromium\/([\d.]+).*$/, '$1')
|
||||
},
|
||||
Opera: function () {
|
||||
return u.replace(/^.*Opera\/([\d.]+).*$/, '$1').replace(/^.*OPR\/([\d.]+).*$/, '$1')
|
||||
},
|
||||
Vivaldi: function () {
|
||||
return u.replace(/^.*Vivaldi\/([\d.]+).*$/, '$1')
|
||||
},
|
||||
Yandex: function () {
|
||||
return u.replace(/^.*YaBrowser\/([\d.]+).*$/, '$1')
|
||||
},
|
||||
Kindle: function () {
|
||||
return u.replace(/^.*Version\/([\d.]+).*$/, '$1')
|
||||
},
|
||||
Maxthon: function () {
|
||||
return u.replace(/^.*Maxthon\/([\d.]+).*$/, '$1')
|
||||
},
|
||||
QQBrowser: function () {
|
||||
return u.replace(/^.*QQBrowser\/([\d.]+).*$/, '$1')
|
||||
},
|
||||
QQ: function () {
|
||||
return u.replace(/^.*QQ\/([\d.]+).*$/, '$1')
|
||||
},
|
||||
Baidu: function () {
|
||||
return u.replace(/^.*BIDUBrowser[\s/]([\d.]+).*$/, '$1')
|
||||
},
|
||||
UC: function () {
|
||||
return u.replace(/^.*UC?Browser\/([\d.]+).*$/, '$1')
|
||||
},
|
||||
Sogou: function () {
|
||||
return u.replace(/^.*SE ([\d.X]+).*$/, '$1').replace(/^.*SogouMobileBrowser\/([\d.]+).*$/, '$1')
|
||||
},
|
||||
'2345Explorer': function () {
|
||||
return u.replace(/^.*2345Explorer\/([\d.]+).*$/, '$1')
|
||||
},
|
||||
TheWorld: function () {
|
||||
return u.replace(/^.*TheWorld ([\d.]+).*$/, '$1')
|
||||
},
|
||||
XiaoMi: function () {
|
||||
return u.replace(/^.*MiuiBrowser\/([\d.]+).*$/, '$1')
|
||||
},
|
||||
Quark: function () {
|
||||
return u.replace(/^.*Quark\/([\d.]+).*$/, '$1')
|
||||
},
|
||||
Qiyu: function () {
|
||||
return u.replace(/^.*Qiyu\/([\d.]+).*$/, '$1')
|
||||
},
|
||||
Wechat: function () {
|
||||
return u.replace(/^.*MicroMessenger\/([\d.]+).*$/, '$1')
|
||||
},
|
||||
Taobao: function () {
|
||||
return u.replace(/^.*AliApp\(TB\/([\d.]+).*$/, '$1')
|
||||
},
|
||||
Alipay: function () {
|
||||
return u.replace(/^.*AliApp\(AP\/([\d.]+).*$/, '$1')
|
||||
},
|
||||
Weibo: function () {
|
||||
return u.replace(/^.*weibo__([\d.]+).*$/, '$1')
|
||||
},
|
||||
Douban: function () {
|
||||
return u.replace(/^.*com.douban.frodo\/([\d.]+).*$/, '$1')
|
||||
},
|
||||
Suning: function () {
|
||||
return u.replace(/^.*SNEBUY-APP([\d.]+).*$/, '$1')
|
||||
},
|
||||
iQiYi: function () {
|
||||
return u.replace(/^.*IqiyiVersion\/([\d.]+).*$/, '$1')
|
||||
}
|
||||
}
|
||||
_this.version = ''
|
||||
if (version[_this.browser]) {
|
||||
_this.version = version[_this.browser]()
|
||||
if (_this.version === u) {
|
||||
_this.version = ''
|
||||
}
|
||||
}
|
||||
|
||||
// 简化版本号
|
||||
/* if (_this.osVersion.indexOf('.')) {
|
||||
_this.osVersion = _this.osVersion.substring(0, _this.osVersion.indexOf('.'))
|
||||
} */
|
||||
if (_this.version.indexOf('.')) {
|
||||
_this.version = _this.version.substring(0, _this.version.indexOf('.'))
|
||||
}
|
||||
|
||||
// 修正
|
||||
if (_this.browser === 'Edge') {
|
||||
_this.engine = 'EdgeHTML'
|
||||
} else if (_this.browser === 'Chrome' && parseInt(_this.version) > 27) {
|
||||
_this.engine = 'Blink'
|
||||
} else if (_this.browser === 'Opera' && parseInt(_this.version) > 12) {
|
||||
_this.engine = 'Blink'
|
||||
} else if (_this.browser === 'Yandex') {
|
||||
_this.engine = 'Blink'
|
||||
} else if (_this.browser === undefined) {
|
||||
_this.browser = 'Unknow App'
|
||||
}
|
||||
};
|
||||
|
||||
function detectFactory (u) {
|
||||
return new Detect(u)
|
||||
}
|
||||
|
||||
export default detectFactory
|
||||
@@ -0,0 +1,222 @@
|
||||
const win = (window as any) || {}
|
||||
const nav = navigator || {}
|
||||
|
||||
function Detect (userAgent?: string) {
|
||||
const u = String(userAgent || nav.userAgent)
|
||||
const dest = {
|
||||
os: '',
|
||||
osVersion: '',
|
||||
engine: '',
|
||||
browser: '',
|
||||
device: '',
|
||||
language: '',
|
||||
version: ''
|
||||
}
|
||||
|
||||
// 内核
|
||||
const engineMatch = {
|
||||
Trident: u.includes('Trident') || u.includes('NET CLR'),
|
||||
Presto: u.includes('Presto'),
|
||||
WebKit: u.includes('AppleWebKit'),
|
||||
Gecko: u.includes('Gecko/')
|
||||
}
|
||||
|
||||
// 浏览器
|
||||
const browserMatch = {
|
||||
Safari: u.includes('Safari'),
|
||||
Chrome: u.includes('Chrome') || u.includes('CriOS'),
|
||||
IE: u.includes('MSIE') || u.includes('Trident'),
|
||||
Edge: u.includes('Edge') || u.includes('Edg'),
|
||||
Firefox: u.includes('Firefox') || u.includes('FxiOS'),
|
||||
'Firefox Focus': u.includes('Focus'),
|
||||
Chromium: u.includes('Chromium'),
|
||||
Opera: u.includes('Opera') || u.includes('OPR'),
|
||||
Vivaldi: u.includes('Vivaldi'),
|
||||
Yandex: u.includes('YaBrowser'),
|
||||
Kindle: u.includes('Kindle') || u.includes('Silk/'),
|
||||
360: u.includes('360EE') || u.includes('360SE'),
|
||||
UC: u.includes('UC') || u.includes(' UBrowser'),
|
||||
QQBrowser: u.includes('QQBrowser'),
|
||||
QQ: u.includes('QQ/'),
|
||||
Baidu: u.includes('Baidu') || u.includes('BIDUBrowser'),
|
||||
Maxthon: u.includes('Maxthon'),
|
||||
Sogou: u.includes('MetaSr') || u.includes('Sogou'),
|
||||
LBBROWSER: u.includes('LBBROWSER'),
|
||||
'2345Explorer': u.includes('2345Explorer'),
|
||||
TheWorld: u.includes('TheWorld'),
|
||||
MIUI: u.includes('MiuiBrowser'),
|
||||
Quark: u.includes('Quark'),
|
||||
Qiyu: u.includes('Qiyu'),
|
||||
Wechat: u.includes('MicroMessenger'),
|
||||
Taobao: u.includes('AliApp(TB'),
|
||||
Alipay: u.includes('AliApp(AP'),
|
||||
Weibo: u.includes('Weibo'),
|
||||
Douban: u.includes('com.douban.frodo'),
|
||||
Suning: u.includes('SNEBUY-APP'),
|
||||
iQiYi: u.includes('IqiyiApp'),
|
||||
}
|
||||
|
||||
// 系统或平台
|
||||
const osMatch = {
|
||||
Windows: u.includes('Windows'),
|
||||
Linux: u.includes('Linux') || u.includes('X11'),
|
||||
'macOS': u.includes('Macintosh'),
|
||||
Android: u.includes('Android') || u.includes('Adr'),
|
||||
Ubuntu: u.includes('Ubuntu'),
|
||||
FreeBSD: u.includes('FreeBSD'),
|
||||
Debian: u.includes('Debian'),
|
||||
'Windows Phone': u.includes('IEMobile') || u.includes('Windows Phone'),
|
||||
BlackBerry: u.includes('BlackBerry') || u.includes('RIM'),
|
||||
MeeGo: u.includes('MeeGo'),
|
||||
Symbian: u.includes('Symbian'),
|
||||
iOS: u.includes('like Mac OS X'),
|
||||
'Chrome OS': u.includes('CrOS'),
|
||||
WebOS: u.includes('hpwOS'),
|
||||
}
|
||||
|
||||
// 设备
|
||||
const deviceMatch = {
|
||||
Mobile: u.includes('Mobi') || u.includes('iPh') || u.includes('480'),
|
||||
Tablet: u.includes('Tablet') || u.includes('Pad') || u.includes('Nexus 7')
|
||||
}
|
||||
|
||||
// 修正
|
||||
if (deviceMatch.Mobile) {
|
||||
deviceMatch.Mobile = !(u.includes('iPad'))
|
||||
} else if (browserMatch.Chrome && u.includes('Edg')) {
|
||||
// Chrome 内核的 Edge
|
||||
browserMatch.Chrome = false
|
||||
browserMatch.Edge = true
|
||||
} else if (win.showModalDialog && win.chrome) {
|
||||
browserMatch.Chrome = false
|
||||
browserMatch['360'] = true
|
||||
}
|
||||
|
||||
// 默认设备
|
||||
dest.device = 'PC'
|
||||
|
||||
// 语言
|
||||
dest.language = (() => {
|
||||
const g = ((nav as any).browserLanguage || nav.language)
|
||||
const arr = g.split('-')
|
||||
if (arr[1]) arr[1] = arr[1].toUpperCase()
|
||||
return arr.join('_')
|
||||
})()
|
||||
|
||||
// 应用判断数据
|
||||
const hash = {
|
||||
engine: engineMatch,
|
||||
browser: browserMatch,
|
||||
os: osMatch,
|
||||
device: deviceMatch,
|
||||
}
|
||||
Object.entries(hash).forEach(([type, match]) => {
|
||||
Object.entries(match).forEach(([name, result]) => {
|
||||
if (result === true) dest[type] = name
|
||||
})
|
||||
})
|
||||
|
||||
// 系统版本信息
|
||||
const osVersion = {
|
||||
Windows: () => {
|
||||
const v = u.replace(/^.*Windows NT ([\d.]+);.*$/, '$1')
|
||||
const wvHash = {
|
||||
'6.4': '10',
|
||||
'6.3': '8.1',
|
||||
'6.2': '8',
|
||||
'6.1': '7',
|
||||
'6.0': 'Vista',
|
||||
'5.2': 'XP',
|
||||
'5.1': 'XP',
|
||||
'5.0': '2000',
|
||||
'10.0': '10',
|
||||
'11.0': '11' // 自定的,不是微软官方的判断方法
|
||||
}
|
||||
return wvHash[v] || v
|
||||
},
|
||||
Android: () => u.replace(/^.*Android ([\d.]+);.*$/, '$1'),
|
||||
iOS: () => u.replace(/^.*OS ([\d_]+) like.*$/, '$1').replace(/_/g, '.'),
|
||||
Debian: () => u.replace(/^.*Debian\/([\d.]+).*$/, '$1'),
|
||||
'Windows Phone': () => u.replace(/^.*Windows Phone( OS)? ([\d.]+);.*$/, '$2'),
|
||||
'macOS': () => u.replace(/^.*Mac OS X ([\d_]+).*$/, '$1').replace(/_/g, '.'),
|
||||
WebOS: () => u.replace(/^.*hpwOS\/([\d.]+);.*$/, '$1')
|
||||
}
|
||||
|
||||
dest.osVersion = ''
|
||||
if (osVersion[dest.os]) {
|
||||
dest.osVersion = osVersion[dest.os]()
|
||||
if (dest.osVersion === u) {
|
||||
dest.osVersion = ''
|
||||
}
|
||||
}
|
||||
|
||||
// 浏览器版本信息
|
||||
const version = {
|
||||
Safari: () => u.replace(/^.*Version\/([\d.]+).*$/, '$1'),
|
||||
Chrome: () => u.replace(/^.*Chrome\/([\d.]+).*$/, '$1').replace(/^.*CriOS\/([\d.]+).*$/, '$1'),
|
||||
IE: () => u.replace(/^.*MSIE ([\d.]+).*$/, '$1').replace(/^.*rv:([\d.]+).*$/, '$1'),
|
||||
Edge: () => u.replace(/^.*(Edge|Edg|Edg[A-Z]{1})\/([\d.]+).*$/, '$2'),
|
||||
Firefox: () => u.replace(/^.*Firefox\/([\d.]+).*$/, '$1').replace(/^.*FxiOS\/([\d.]+).*$/, '$1'),
|
||||
'Firefox Focus': () => u.replace(/^.*Focus\/([\d.]+).*$/, '$1'),
|
||||
Chromium: () => u.replace(/^.*Chromium\/([\d.]+).*$/, '$1'),
|
||||
Opera: () => u.replace(/^.*Opera\/([\d.]+).*$/, '$1').replace(/^.*OPR\/([\d.]+).*$/, '$1'),
|
||||
Vivaldi: () => u.replace(/^.*Vivaldi\/([\d.]+).*$/, '$1'),
|
||||
Yandex: () => u.replace(/^.*YaBrowser\/([\d.]+).*$/, '$1'),
|
||||
Kindle: () => u.replace(/^.*Version\/([\d.]+).*$/, '$1'),
|
||||
Maxthon: () => u.replace(/^.*Maxthon\/([\d.]+).*$/, '$1'),
|
||||
QQBrowser: () => u.replace(/^.*QQBrowser\/([\d.]+).*$/, '$1'),
|
||||
QQ: () => u.replace(/^.*QQ\/([\d.]+).*$/, '$1'),
|
||||
Baidu: () => u.replace(/^.*BIDUBrowser[\s/]([\d.]+).*$/, '$1'),
|
||||
UC: () => u.replace(/^.*UC?Browser\/([\d.]+).*$/, '$1'),
|
||||
Sogou: () => u.replace(/^.*SE ([\d.X]+).*$/, '$1').replace(/^.*SogouMobileBrowser\/([\d.]+).*$/, '$1'),
|
||||
'2345Explorer': () => u.replace(/^.*2345Explorer\/([\d.]+).*$/, '$1'),
|
||||
TheWorld: () => u.replace(/^.*TheWorld ([\d.]+).*$/, '$1'),
|
||||
MIUI: () => u.replace(/^.*MiuiBrowser\/([\d.]+).*$/, '$1'),
|
||||
Quark: () => u.replace(/^.*Quark\/([\d.]+).*$/, '$1'),
|
||||
Qiyu: () => u.replace(/^.*Qiyu\/([\d.]+).*$/, '$1'),
|
||||
Wechat: () => u.replace(/^.*MicroMessenger\/([\d.]+).*$/, '$1'),
|
||||
Taobao: () => u.replace(/^.*AliApp\(TB\/([\d.]+).*$/, '$1'),
|
||||
Alipay: () => u.replace(/^.*AliApp\(AP\/([\d.]+).*$/, '$1'),
|
||||
Weibo: () => u.replace(/^.*weibo__([\d.]+).*$/, '$1'),
|
||||
Douban: () => u.replace(/^.*com.douban.frodo\/([\d.]+).*$/, '$1'),
|
||||
Suning: () => u.replace(/^.*SNEBUY-APP([\d.]+).*$/, '$1'),
|
||||
iQiYi: () => u.replace(/^.*IqiyiVersion\/([\d.]+).*$/, '$1'),
|
||||
}
|
||||
|
||||
dest.version = ''
|
||||
if (version[dest.browser]) {
|
||||
dest.version = version[dest.browser]()
|
||||
if (dest.version === u) {
|
||||
dest.version = ''
|
||||
}
|
||||
}
|
||||
|
||||
// 简化版本号
|
||||
/* if (_this.osVersion.indexOf('.')) {
|
||||
_this.osVersion = _this.osVersion.substring(0, _this.osVersion.indexOf('.'))
|
||||
} */
|
||||
if (dest.version.indexOf('.')) {
|
||||
dest.version = dest.version.substring(0, dest.version.indexOf('.'))
|
||||
}
|
||||
|
||||
// 修正
|
||||
if (dest.os === 'iOS' && u.includes('iPad')) {
|
||||
dest.os = 'iPadOS'
|
||||
} else if (dest.browser === 'Edge' && !u.includes('Edg')) {
|
||||
dest.engine = 'EdgeHTML'
|
||||
} else if (dest.browser === 'MIUI') {
|
||||
dest.os = 'Android'
|
||||
} else if (dest.browser === 'Chrome' && Number(dest.version) > 27) {
|
||||
dest.engine = 'Blink'
|
||||
} else if (dest.browser === 'Opera' && Number(dest.version) > 12) {
|
||||
dest.engine = 'Blink'
|
||||
} else if (dest.browser === 'Yandex') {
|
||||
dest.engine = 'Blink'
|
||||
} else if (dest.browser === undefined) {
|
||||
dest.browser = 'Unknow App'
|
||||
}
|
||||
|
||||
return dest
|
||||
}
|
||||
|
||||
export default Detect
|
||||
@@ -0,0 +1,63 @@
|
||||
import ContextApi from '~/types/context'
|
||||
import ArtalkPlug from '~/types/plug'
|
||||
|
||||
export interface CountConf {
|
||||
ctx: ContextApi
|
||||
|
||||
/** 是否增加当前页面 PV 数 */
|
||||
pvAdd?: boolean
|
||||
}
|
||||
|
||||
export const PvCountWidget: ArtalkPlug = (ctx: ContextApi) => {
|
||||
initCountWidget({ ctx, pvAdd: true })
|
||||
}
|
||||
|
||||
/** 初始化评论数和 PV 数量展示元素 */
|
||||
export async function initCountWidget(p: CountConf) {
|
||||
// 评论数
|
||||
const countEl = p.ctx.conf.countEl
|
||||
if (countEl && document.querySelector(countEl)) {
|
||||
handleStatCount(p, { api: 'page_comment', countEl })
|
||||
}
|
||||
|
||||
// PV
|
||||
const curtPagePvNum = p.pvAdd ? await p.ctx.getApi().pv() : undefined
|
||||
const pvEl = p.ctx.conf.pvEl
|
||||
if (pvEl && document.querySelector(pvEl)) {
|
||||
handleStatCount(p, {
|
||||
api: 'page_pv',
|
||||
countEl: pvEl,
|
||||
curtPageCount: curtPagePvNum,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export async function handleStatCount(
|
||||
p: CountConf,
|
||||
args: {
|
||||
api: 'page_pv' | 'page_comment'
|
||||
countEl: string
|
||||
curtPageCount?: number
|
||||
}
|
||||
) {
|
||||
let pageCounts: { [key: string]: number } = {}
|
||||
|
||||
// 当前页面的统计数
|
||||
const curtPageKey = p.ctx.conf.pageKey
|
||||
if (args.curtPageCount) pageCounts[curtPageKey] = args.curtPageCount
|
||||
|
||||
// 查询其他页面的统计数
|
||||
let queryPageKeys = Array.from(document.querySelectorAll(args.countEl))
|
||||
.map((e) => e.getAttribute('data-page-key') || curtPageKey)
|
||||
.filter((pageKey) => pageCounts[pageKey] === undefined)
|
||||
queryPageKeys = [...new Set(queryPageKeys)] // 去重
|
||||
if (queryPageKeys.length > 0) {
|
||||
const counts: any = await p.ctx.getApi().stat(args.api, queryPageKeys)
|
||||
pageCounts = { ...pageCounts, ...counts }
|
||||
}
|
||||
|
||||
document.querySelectorAll(args.countEl).forEach((el) => {
|
||||
const pageKey = el.getAttribute('data-page-key') || curtPageKey
|
||||
el.innerHTML = `${Number(pageCounts[pageKey] || 0)}`
|
||||
})
|
||||
}
|
||||
@@ -1,10 +1,7 @@
|
||||
import * as Utils from './utils'
|
||||
import Context from '../context'
|
||||
|
||||
/** 显示加载 */
|
||||
export function showLoading(parentElem: HTMLElement|Context) {
|
||||
if (parentElem instanceof Context) parentElem = parentElem.$root
|
||||
|
||||
export function showLoading(parentElem: HTMLElement, conf?: { transparentBg?: boolean }) {
|
||||
let $loading = parentElem.querySelector<HTMLElement>('.atk-loading')
|
||||
if (!$loading) {
|
||||
$loading = Utils.createElement(
|
||||
@@ -13,6 +10,7 @@ export function showLoading(parentElem: HTMLElement|Context) {
|
||||
<svg viewBox="25 25 50 50"><circle cx="50" cy="50" r="20" fill="none" stroke-width="2" stroke-miterlimit="10"></circle></svg>
|
||||
</div>
|
||||
</div>`)
|
||||
if (conf?.transparentBg) $loading.style.background = 'transparent'
|
||||
parentElem.appendChild($loading)
|
||||
}
|
||||
$loading.style.display = ''
|
||||
@@ -28,9 +26,7 @@ export function showLoading(parentElem: HTMLElement|Context) {
|
||||
}
|
||||
|
||||
/** 隐藏加载 */
|
||||
export function hideLoading(parentElem: HTMLElement|Context) {
|
||||
if (parentElem instanceof Context) parentElem = parentElem.$root
|
||||
|
||||
export function hideLoading(parentElem: HTMLElement) {
|
||||
const $loading = parentElem.querySelector<HTMLElement>('.atk-loading')
|
||||
if ($loading) $loading.style.display = 'none'
|
||||
}
|
||||
@@ -132,9 +128,7 @@ export function playFadeOutAnim(elem: HTMLElement, after?: () => void) {
|
||||
}
|
||||
|
||||
/** 设置全局错误 */
|
||||
export function setError(parentElem: HTMLElement|Context, html: string | HTMLElement | null, title: string = '<span class="atk-error-title">Artalk Error</span>') {
|
||||
if (parentElem instanceof Context) parentElem = parentElem.$root
|
||||
|
||||
export function setError(parentElem: HTMLElement, html: string | HTMLElement | null, title: string = '<span class="atk-error-title">Artalk Error</span>') {
|
||||
let elem = parentElem.querySelector<HTMLElement>('.atk-error-layer')
|
||||
if (html === null) {
|
||||
if (elem !== null) elem.remove()
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
import ArtalkConfig, { LocalUser } from "~/types/artalk-config"
|
||||
import Context from '~/types/context'
|
||||
|
||||
export default class User {
|
||||
public ctx: Context
|
||||
public data: LocalUser
|
||||
|
||||
constructor (conf: ArtalkConfig) {
|
||||
public constructor(ctx: Context) {
|
||||
this.ctx = ctx
|
||||
|
||||
// 从 localStorage 导入
|
||||
const localUser = JSON.parse(window.localStorage.getItem('ArtalkUser') || '{}')
|
||||
this.data = {
|
||||
@@ -16,12 +20,25 @@ export default class User {
|
||||
}
|
||||
|
||||
/** 保存用户到 localStorage 中 */
|
||||
public save () {
|
||||
public update(obj: Partial<LocalUser> = {}) {
|
||||
Object.entries(obj).forEach(([key, value]) => {
|
||||
this.data[key] = value
|
||||
})
|
||||
|
||||
window.localStorage.setItem('ArtalkUser', JSON.stringify(this.data))
|
||||
this.ctx.trigger('user-changed', this.ctx.user.data)
|
||||
}
|
||||
|
||||
/** 注销,清除用户登录状态 */
|
||||
public logout() {
|
||||
this.update({
|
||||
token: '',
|
||||
isAdmin: false
|
||||
})
|
||||
}
|
||||
|
||||
/** 是否已填写基本用户信息 */
|
||||
public checkHasBasicUserInfo () {
|
||||
public checkHasBasicUserInfo() {
|
||||
return !!this.data.nick && !!this.data.email
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { marked as libMarked } from 'marked'
|
||||
import insane from 'insane'
|
||||
import hanabi from 'hanabi'
|
||||
import Context from '../context'
|
||||
import Context from '~/types/context'
|
||||
|
||||
export function createElement<E extends HTMLElement = HTMLElement>(htmlStr: string = ''): E {
|
||||
const div = document.createElement('div')
|
||||
@@ -58,7 +58,7 @@ export function dateFormat(date: Date) {
|
||||
return `${vYear}-${vMonth}-${vDay}`
|
||||
}
|
||||
|
||||
export function timeAgo(date: Date) {
|
||||
export function timeAgo(date: Date, ctx: Context) {
|
||||
try {
|
||||
const oldTime = date.getTime()
|
||||
const currTime = new Date().getTime()
|
||||
@@ -77,16 +77,16 @@ export function timeAgo(date: Date) {
|
||||
// 计算相差秒数
|
||||
const leave3 = leave2 % (60 * 1000) // 计算分钟数后剩余的毫秒数
|
||||
const seconds = Math.round(leave3 / 1000)
|
||||
return `${seconds} 秒前`
|
||||
return `${seconds} ${ctx.$t('seconds')}`
|
||||
}
|
||||
return `${minutes} 分钟前`
|
||||
return `${minutes} ${ctx.$t('minutes')}`
|
||||
}
|
||||
return `${hours} 小时前`
|
||||
return `${hours} ${ctx.$t('hours')}`
|
||||
}
|
||||
if (days < 0) return '刚刚'
|
||||
if (days < 0) return ctx.$t('now')
|
||||
|
||||
if (days < 8) {
|
||||
return `${days} 天前`
|
||||
return `${days} ${ctx.$t('days')}`
|
||||
}
|
||||
|
||||
return dateFormat(date)
|
||||
@@ -118,7 +118,7 @@ export function onImagesLoaded($container: HTMLElement, event: Function) {
|
||||
}
|
||||
|
||||
export function getGravatarURL(ctx: Context, emailMD5: string) {
|
||||
return `${(ctx.conf.gravatar?.mirror || '').replace(/\/$/, '')}/${emailMD5}?d=${encodeURIComponent(ctx.conf.gravatar?.default || '')}&s=80`
|
||||
return `${(ctx.conf.gravatar.mirror).replace(/\/$/, '')}/${emailMD5}?d=${encodeURIComponent(ctx.conf.gravatar.default)}&s=80`
|
||||
}
|
||||
|
||||
export function sleep(ms: number) {
|
||||
@@ -140,66 +140,200 @@ export function versionCompare(a: string, b: string) {
|
||||
return 0
|
||||
}
|
||||
|
||||
let markedInstance: typeof libMarked
|
||||
export function marked(ctx: Context, src: string): string {
|
||||
if (!markedInstance) {
|
||||
const renderer = new libMarked.Renderer()
|
||||
const linkRenderer = renderer.link
|
||||
renderer.link = (href, title, text) => {
|
||||
const localLink = href?.startsWith(`${window.location.protocol}//${window.location.hostname}`);
|
||||
const html = linkRenderer.call(renderer as any, href, title, text);
|
||||
return html.replace(/^<a /, `<a target="_blank" ${!localLink ? `rel="noreferrer noopener nofollow"` : ''} `);
|
||||
}
|
||||
/** 初始化 marked */
|
||||
export function initMarked(ctx: Context) {
|
||||
try { if (!libMarked.name) return } catch { return }
|
||||
|
||||
// @see https://github.com/markedjs/marked/blob/4afb228d956a415624c4e5554bb8f25d047676fe/src/Tokenizer.js#L329
|
||||
const nMarked = libMarked
|
||||
libMarked.setOptions({
|
||||
renderer,
|
||||
highlight: (code) => hanabi(code),
|
||||
pedantic: false,
|
||||
gfm: true,
|
||||
breaks: true,
|
||||
smartLists: true,
|
||||
smartypants: true,
|
||||
xhtml: false,
|
||||
sanitize: true,
|
||||
sanitizer: (html) => insane(html, {
|
||||
...insane.defaults,
|
||||
allowedAttributes: {
|
||||
...insane.defaults.allowedAttributes,
|
||||
img: ['src', 'atk-emoticon']
|
||||
},
|
||||
}),
|
||||
silent: true,
|
||||
})
|
||||
|
||||
markedInstance = nMarked
|
||||
const renderer = new libMarked.Renderer()
|
||||
const orgLinkRenderer = renderer.link
|
||||
renderer.link = (href, title, text) => {
|
||||
const localLink = href?.startsWith(`${window.location.protocol}//${window.location.hostname}`);
|
||||
const html = orgLinkRenderer.call(renderer as any, href, title, text);
|
||||
return html.replace(/^<a /, `<a target="_blank" ${!localLink ? `rel="noreferrer noopener nofollow"` : ''} `);
|
||||
}
|
||||
|
||||
return markedInstance.parse(src)
|
||||
renderer.code = (block, lang) => {
|
||||
// Colorize the block only if the language is known to highlight.js
|
||||
const realLang = (!lang ? 'plaintext' : lang)
|
||||
let colorized = block
|
||||
if ((window as any).hljs) {
|
||||
if (realLang && (window as any).hljs.getLanguage(realLang)) {
|
||||
colorized = (window as any).hljs.highlight(realLang, block).value
|
||||
}
|
||||
} else {
|
||||
colorized = hanabi(block)
|
||||
}
|
||||
|
||||
return `<pre rel="${realLang}">\n`
|
||||
+ `<code class="hljs language-${realLang}">${colorized.replace(/&/g, '&')}</code>\n`
|
||||
+ `</pre>`
|
||||
}
|
||||
|
||||
// @see https://github.com/markedjs/marked/blob/4afb228d956a415624c4e5554bb8f25d047676fe/src/Tokenizer.js#L329
|
||||
const nMarked = libMarked
|
||||
libMarked.setOptions({
|
||||
renderer,
|
||||
pedantic: false,
|
||||
gfm: true,
|
||||
breaks: true,
|
||||
smartLists: true,
|
||||
smartypants: true,
|
||||
xhtml: false,
|
||||
sanitize: false,
|
||||
silent: true,
|
||||
})
|
||||
|
||||
ctx.markedInstance = nMarked
|
||||
}
|
||||
|
||||
/** 解析 markdown */
|
||||
export function marked(ctx: Context, src: string): string {
|
||||
let markedContent = ctx.markedInstance?.parse(src)
|
||||
if (!markedContent) {
|
||||
// 无 Markdown 模式简单处理
|
||||
markedContent = src
|
||||
// .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
|
||||
.replace(/```\s*([^]+?.*?[^]+?[^]+?)```/g, (_, code) => `<pre><code>${hanabi(code)}</code></pre>`)
|
||||
// .replace(/`([^`]+?)`/g, '<code>$1</code>')
|
||||
.replace(/!\[(.*?)\]\((.*?)\)/g, (_, alt, imgSrc) => `<img src="${imgSrc}" alt="${alt}" />`)
|
||||
.replace(/\[(.*?)\]\((.*?)\)/g, (_, text, link) => `<a href="${link}" target="_blank">${text}</a>`)
|
||||
.replace(/\n/g, '<br>')
|
||||
}
|
||||
|
||||
// @link https://github.com/markedjs/marked/discussions/1232
|
||||
// @link https://gist.github.com/lionel-rowe/bb384465ba4e4c81a9c8dada84167225
|
||||
let dest = insane(markedContent, {
|
||||
allowedClasses: {},
|
||||
allowedSchemes: ['http', 'https', 'mailto'],
|
||||
allowedTags: [
|
||||
'a', 'abbr', 'article', 'b', 'blockquote', 'br', 'caption', 'code', 'del', 'details', 'div', 'em',
|
||||
'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'ins', 'kbd', 'li', 'main', 'mark',
|
||||
'ol', 'p', 'pre', 'section', 'span', 'strike', 'strong', 'sub', 'summary', 'sup', 'table',
|
||||
'tbody', 'td', 'th', 'thead', 'tr', 'u', 'ul'
|
||||
],
|
||||
allowedAttributes: {
|
||||
'*': ['title', 'accesskey'],
|
||||
a: ['href', 'name', 'target', 'aria-label', 'rel'],
|
||||
img: ['src', 'alt', 'title', 'atk-emoticon', 'aria-label'],
|
||||
// for code highlight
|
||||
code: ['class'],
|
||||
span: ['class', 'style'],
|
||||
},
|
||||
filter: node => {
|
||||
// allow hljs style
|
||||
const allowed = [
|
||||
[ 'code', /^hljs\W+language-(.*)$/ ],
|
||||
[ 'span', /^(hljs-.*)$/ ]
|
||||
]
|
||||
allowed.forEach(([ tag, reg ]) => {
|
||||
if (
|
||||
node.tag === tag
|
||||
&& !!node.attrs.class
|
||||
&& !(reg as RegExp).test(node.attrs.class)
|
||||
) {
|
||||
delete node.attrs.class
|
||||
}
|
||||
})
|
||||
|
||||
// allow <span> set color sty
|
||||
if (node.tag === 'span' && !!node.attrs.style
|
||||
&& !/^color:(\W+)?#[0-9a-f]{3,6};?$/i.test(node.attrs.style)) {
|
||||
delete node.attrs.style
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
})
|
||||
|
||||
// 内容替换器
|
||||
ctx.markedReplacers.forEach((replacer) => {
|
||||
if (typeof replacer === 'function') dest = replacer(dest)
|
||||
})
|
||||
|
||||
return dest
|
||||
}
|
||||
|
||||
/** 获取修正后的 UserAgent */
|
||||
export async function getCorrectUserAgent() {
|
||||
const uaRaw = navigator.userAgent
|
||||
const uaData = (navigator as any).userAgentData // @link https://web.dev/migrate-to-ua-ch/
|
||||
if (!uaData || !uaData.getHighEntropyValues) {
|
||||
if (!(navigator as any).userAgentData || !(navigator as any).userAgentData.getHighEntropyValues) {
|
||||
return uaRaw
|
||||
}
|
||||
|
||||
// microsoft f******k you!!!!!
|
||||
// @link https://docs.microsoft.com/en-us/microsoft-edge/web-platform/how-to-detect-win11
|
||||
// @link https://web.dev/migrate-to-ua-ch/
|
||||
// @link https://web.dev/user-agent-client-hints/
|
||||
const uaData = (navigator as any).userAgentData
|
||||
let uaGot: any = null
|
||||
try {
|
||||
uaGot = await uaData.getHighEntropyValues(["platformVersion"])
|
||||
} catch (err) { console.error(err); return uaRaw }
|
||||
|
||||
if (uaData.platform !== "Windows") { return uaRaw }
|
||||
const majorPlatformVersion = Number(uaGot.platformVersion.split('.')[0])
|
||||
if (majorPlatformVersion >= 13) {
|
||||
// Win11 样本:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36"
|
||||
return uaRaw.replace(/Windows\W+NT\W+10.0/, 'Windows NT 11.0')
|
||||
|
||||
if (uaData.platform === "Windows") {
|
||||
if (majorPlatformVersion >= 13) { // @link https://docs.microsoft.com/en-us/microsoft-edge/web-platform/how-to-detect-win11
|
||||
// @date 2022-4-29
|
||||
// Win 11 样本:"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36"
|
||||
return uaRaw.replace(/Windows NT 10.0/, 'Windows NT 11.0')
|
||||
}
|
||||
}
|
||||
if (uaData.platform === "macOS") {
|
||||
if (majorPlatformVersion >= 11) { // 11 => BigSur
|
||||
// @date 2022-4-29
|
||||
// (Intel Chip) macOS 12.3 样本:"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36"
|
||||
// (Arm Chip) macOS 样本:"Mozilla/5.0 (Macintosh; ARM Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0.2 Safari/605.1.15"
|
||||
return uaRaw.replace(/(Mac OS X \d+_\d+_\d+|Mac OS X)/, `Mac OS X ${uaGot.platformVersion.replace(/\./g, '_')}`)
|
||||
}
|
||||
}
|
||||
|
||||
return uaRaw
|
||||
}
|
||||
|
||||
/** 是否为完整的 URL */
|
||||
export function isValidURL(urlRaw: string) {
|
||||
// @link https://www.rfc-editor.org/rfc/rfc3986
|
||||
let url: URL
|
||||
try {
|
||||
url = new URL(urlRaw)
|
||||
} catch (_) { return false }
|
||||
return url.protocol === "http:" || url.protocol === "https:"
|
||||
}
|
||||
|
||||
/** 获取基于 conf.server 的 URL */
|
||||
export function getURLBasedOnApi(ctx: Context, path: string) {
|
||||
return getURLBasedOn(ctx.conf.server, path)
|
||||
}
|
||||
|
||||
/** 获取基于某个 baseURL 的 URL */
|
||||
export function getURLBasedOn(baseURL: string, path: string) {
|
||||
return `${baseURL.replace(/\/$/, '')}/${path.replace(/^\//, '')}`
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs a deep merge of `source` into `target`.
|
||||
* Mutates `target` only but not its objects and arrays.
|
||||
*
|
||||
* @author inspired by [jhildenbiddle](https://stackoverflow.com/a/48218209).
|
||||
* @link https://gist.github.com/ahtcx/0cd94e62691f539160b32ecda18af3d6
|
||||
*/
|
||||
export function mergeDeep(target: any, source: any) {
|
||||
const isObject = (obj: any) => obj && typeof obj === 'object'
|
||||
|
||||
if (!isObject(target) || !isObject(source)) {
|
||||
return source
|
||||
}
|
||||
|
||||
Object.keys(source).forEach(key => {
|
||||
const targetValue = target[key]
|
||||
const sourceValue = source[key]
|
||||
|
||||
if (Array.isArray(targetValue) && Array.isArray(sourceValue)) {
|
||||
target[key] = targetValue.concat(sourceValue)
|
||||
} else if (isObject(targetValue) && isObject(sourceValue)) {
|
||||
target[key] = mergeDeep({ ...targetValue}, sourceValue)
|
||||
} else {
|
||||
target[key] = sourceValue
|
||||
}
|
||||
})
|
||||
|
||||
return target
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
import List from './list'
|
||||
|
||||
export default List
|
||||
+146
-161
@@ -1,25 +1,28 @@
|
||||
import Context from '../context'
|
||||
import { ListData, CommentData, NotifyData } from '~/types/artalk-data'
|
||||
import Context from '~/types/context'
|
||||
import Component from '../lib/component'
|
||||
import * as Utils from '../lib/utils'
|
||||
import * as Ui from '../lib/ui'
|
||||
import Api from '../api'
|
||||
import Comment from './comment'
|
||||
import { ListData, CommentData, NotifyData, ApiVersionData } from '~/types/artalk-data'
|
||||
import Pagination from './pagination'
|
||||
import ReadMoreBtn from './read-more-btn'
|
||||
import Comment from '../comment'
|
||||
import Pagination from '../components/pagination'
|
||||
import ReadMoreBtn from '../components/read-more-btn'
|
||||
import * as ListNest from './list-nest'
|
||||
import { backendMinVersion } from '../../package.json'
|
||||
|
||||
export default class ListLite extends Component {
|
||||
protected $commentsWrap: HTMLElement
|
||||
protected comments: Comment[] = []
|
||||
|
||||
protected data?: ListData
|
||||
protected isLoading: boolean = false
|
||||
|
||||
public noCommentText = '无内容' // 无评论时显示
|
||||
public noCommentText: string // 无评论时显示
|
||||
|
||||
/** 平铺模式 */
|
||||
public flatMode = false
|
||||
|
||||
/** 嵌套模式 */
|
||||
public nestSortBy!: ListNest.SortByType
|
||||
|
||||
/** 分页 */
|
||||
public pageMode: 'pagination'|'read-more' = 'pagination'
|
||||
public pageSize: number = 20 // 每次请求获取量
|
||||
@@ -48,16 +51,31 @@ export default class ListLite extends Component {
|
||||
</div>`)
|
||||
this.$commentsWrap = this.$el.querySelector('.atk-list-comments-wrap')!
|
||||
|
||||
// 评论为空时显示字符
|
||||
this.noCommentText = ctx.conf.noComment || ctx.$t('noComment')
|
||||
|
||||
// 嵌套排序方式
|
||||
this.nestSortBy = this.ctx.conf.nestSort || 'DATE_ASC'
|
||||
|
||||
// 评论时间自动更新
|
||||
window.setInterval(() => {
|
||||
this.$el.querySelectorAll<HTMLElement>('[data-atk-comment-date]').forEach(el => {
|
||||
const date = el.getAttribute('data-atk-comment-date')
|
||||
el.innerText = Utils.timeAgo(new Date(Number(date)))
|
||||
el.innerText = Utils.timeAgo(new Date(Number(date)), this.ctx)
|
||||
})
|
||||
}, 30 * 1000) // 30s 更新一次
|
||||
}
|
||||
|
||||
// 事件监听
|
||||
this.ctx.on('unread-update', (data) => (this.updateUnread(data.notifies)))
|
||||
public getData() {
|
||||
return this.data
|
||||
}
|
||||
|
||||
public clearData() {
|
||||
this.data = undefined
|
||||
}
|
||||
|
||||
public getCommentsWrapEl() {
|
||||
return this.$commentsWrap
|
||||
}
|
||||
|
||||
/** 评论获取 */
|
||||
@@ -80,17 +98,17 @@ export default class ListLite extends Component {
|
||||
showLoading()
|
||||
|
||||
// 事件通知(开始加载评论)
|
||||
this.ctx.trigger('comments-load')
|
||||
this.ctx.trigger('list-load')
|
||||
|
||||
// 清空评论(加载按钮)
|
||||
if (this.pageMode === 'read-more' && offset === 0) { this.clearAllComments() }
|
||||
if (this.pageMode === 'read-more' && offset === 0) { this.ctx.clearAllComments() }
|
||||
|
||||
// 请求评论数据
|
||||
let listData: ListData
|
||||
try {
|
||||
listData = await new Api(this.ctx).get(offset, this.pageSize, this.flatMode, this.paramsEditor)
|
||||
listData = await this.ctx.getApi().get(offset, this.pageSize, this.flatMode, this.paramsEditor)
|
||||
} catch (e: any) {
|
||||
this.onError(e.msg || String(e), offset)
|
||||
this.onError(e.msg || String(e), offset, e.data)
|
||||
throw e
|
||||
} finally {
|
||||
hideLoading()
|
||||
@@ -112,12 +130,19 @@ export default class ListLite extends Component {
|
||||
|
||||
protected onLoad(data: ListData, offset: number) {
|
||||
// 清空评论(分页条)
|
||||
if (this.pageMode === 'pagination') { this.clearAllComments() }
|
||||
if (this.pageMode === 'pagination') { this.ctx.clearAllComments() }
|
||||
|
||||
this.data = data
|
||||
|
||||
// 版本检测
|
||||
if (this.ctx.conf.versionCheck && this.versionCheck(data.api_version)) return
|
||||
const feMinVersion = data.api_version?.fe_min_version || '0.0.0'
|
||||
if (this.ctx.conf.versionCheck && this.versionCheck('frontend', feMinVersion, ARTALK_VERSION)) return
|
||||
if (this.ctx.conf.versionCheck && this.versionCheck('backend', backendMinVersion, data.api_version?.version)) return
|
||||
|
||||
// 图片上传功能
|
||||
if (data.conf && typeof data.conf.img_upload === "boolean") {
|
||||
this.ctx.conf.imgUpload = data.conf.img_upload
|
||||
}
|
||||
|
||||
// 导入数据
|
||||
this.importComments(data.comments)
|
||||
@@ -128,8 +153,9 @@ export default class ListLite extends Component {
|
||||
// 加载后事件
|
||||
this.refreshUI()
|
||||
|
||||
this.ctx.trigger('unread-update', { notifies: data.unread || [] })
|
||||
this.ctx.trigger('comments-loaded')
|
||||
this.ctx.updateNotifies(data.unread || [])
|
||||
this.ctx.trigger('list-loaded')
|
||||
this.ctx.trigger('conf-updated')
|
||||
|
||||
if (this.onAfterLoad) this.onAfterLoad(data)
|
||||
}
|
||||
@@ -158,11 +184,12 @@ export default class ListLite extends Component {
|
||||
onClick: async (o) => {
|
||||
await this.fetchComments(o)
|
||||
},
|
||||
text: this.ctx.$t('loadMore'),
|
||||
})
|
||||
this.$el.append(this.readMoreBtn.$el)
|
||||
|
||||
// 滚动到底部自动加载
|
||||
if (this.conf.pagination?.autoLoad) {
|
||||
if (this.conf.pagination.autoLoad) {
|
||||
// 添加滚动事件监听
|
||||
const at = this.scrollListenerAt || document
|
||||
if (this.autoLoadScrollEvent) at.removeEventListener('scroll', this.autoLoadScrollEvent) // 解除原有
|
||||
@@ -189,7 +216,7 @@ export default class ListLite extends Component {
|
||||
pageSize: this.pageSize,
|
||||
onChange: async (o) => {
|
||||
if (this.ctx.conf.editorTravel === true) {
|
||||
this.ctx.trigger('editor-travel-back') // 防止评论框被吞
|
||||
this.ctx.editorTravelBack() // 防止评论框被吞
|
||||
}
|
||||
|
||||
await this.fetchComments(o)
|
||||
@@ -210,27 +237,42 @@ export default class ListLite extends Component {
|
||||
}
|
||||
|
||||
/** 错误处理 */
|
||||
protected onError(msg: any, offset: number) {
|
||||
protected onError(msg: any, offset: number, errData?: any) {
|
||||
msg = String(msg)
|
||||
console.error(msg)
|
||||
|
||||
// 加载更多按钮显示错误
|
||||
if (offset !== 0 && this.pageMode === 'read-more') {
|
||||
this.readMoreBtn?.showErr(`获取失败`)
|
||||
this.readMoreBtn?.showErr(this.$t('loadFail'))
|
||||
return
|
||||
}
|
||||
|
||||
// 显示错误对话框
|
||||
const $err = Utils.createElement(`<span>${msg},无法获取评论列表数据<br/></span>`)
|
||||
const $err = Utils.createElement(`<span>${msg},${this.$t('listLoadFailMsg')}<br/></span>`)
|
||||
|
||||
const $retryBtn = Utils.createElement('<span style="cursor:pointer;">点击重新获取</span>')
|
||||
const $retryBtn = Utils.createElement(`<span style="cursor:pointer;">${this.$t('listRetry')}</span>`)
|
||||
$retryBtn.onclick = () => (this.fetchComments(0))
|
||||
$err.appendChild($retryBtn)
|
||||
|
||||
const adminBtn = Utils.createElement('<span atk-only-admin-show> | <span style="cursor:pointer;">打开控制台</span></span>')
|
||||
adminBtn.onclick = () => (this.ctx.trigger('sidebar-show'))
|
||||
if (!this.ctx.user.data.isAdmin) adminBtn.classList.add('atk-hide')
|
||||
$err.appendChild(adminBtn)
|
||||
if (!this.ctx.user.data.isAdmin) adminBtn.classList.add('atk-hide')
|
||||
|
||||
let sidebarView = ''
|
||||
|
||||
// 找不到站点错误,打开侧边栏并填入创建站点表单
|
||||
if (errData?.err_no_site) {
|
||||
const viewLoadParam = {
|
||||
create_name: this.ctx.conf.site,
|
||||
create_urls: `${window.location.protocol}//${window.location.host}`
|
||||
}
|
||||
// TODO 真的是飞鸽传书啊
|
||||
sidebarView = `sites|${JSON.stringify(viewLoadParam)}`
|
||||
}
|
||||
|
||||
adminBtn.onclick = () => this.ctx.showSidebar({
|
||||
view: sidebarView as any
|
||||
})
|
||||
|
||||
Ui.setError(this.$el, $err)
|
||||
}
|
||||
@@ -238,7 +280,7 @@ export default class ListLite extends Component {
|
||||
/** 刷新界面 */
|
||||
public refreshUI() {
|
||||
// 无评论
|
||||
const isNoComment = this.comments.length <= 0
|
||||
const isNoComment = this.ctx.getCommentList().length <= 0
|
||||
let $noComment = this.$commentsWrap.querySelector<HTMLElement>('.atk-list-no-comment')
|
||||
|
||||
if (isNoComment) {
|
||||
@@ -252,19 +294,35 @@ export default class ListLite extends Component {
|
||||
}
|
||||
|
||||
// 仅管理员显示控制
|
||||
this.ctx.trigger('check-admin-show-el')
|
||||
this.ctx.checkAdminShowEl()
|
||||
}
|
||||
|
||||
/** 重新加载列表 */
|
||||
public reload() {
|
||||
this.fetchComments(0)
|
||||
}
|
||||
|
||||
/** 创建新评论 */
|
||||
protected createComment(data: CommentData) {
|
||||
const comment = new Comment(this.ctx, data)
|
||||
comment.afterRender = () => {
|
||||
if (this.renderComment) this.renderComment(comment)
|
||||
}
|
||||
comment.onDelete = (c) => {
|
||||
this.deleteComment(c)
|
||||
this.refreshUI()
|
||||
}
|
||||
protected createComment(cData: CommentData, ctxData?: CommentData[]) {
|
||||
if (!ctxData) ctxData = this.ctx.getCommentDataList()
|
||||
|
||||
const comment = new Comment(this.ctx, cData, {
|
||||
isFlatMode: this.flatMode,
|
||||
afterRender: () => {
|
||||
if (this.renderComment) this.renderComment(comment)
|
||||
},
|
||||
onDelete: (c: Comment) => {
|
||||
this.ctx.deleteComment(c)
|
||||
this.refreshUI()
|
||||
},
|
||||
replyTo: (cData.rid ? ctxData.find(c => c.id === cData.rid) : undefined)
|
||||
})
|
||||
|
||||
// 渲染元素
|
||||
comment.render()
|
||||
|
||||
// 放入 comment 总表中
|
||||
this.ctx.getCommentList().push(comment)
|
||||
|
||||
return comment
|
||||
}
|
||||
@@ -276,72 +334,56 @@ export default class ListLite extends Component {
|
||||
this.putCommentFlatMode(commentData, srcData, 'append')
|
||||
})
|
||||
} else {
|
||||
this.importCommentsNesting(srcData)
|
||||
this.importCommentsNest(srcData)
|
||||
}
|
||||
}
|
||||
|
||||
// 导入评论 · 嵌套模式
|
||||
private importCommentsNesting(srcData: CommentData[]) {
|
||||
// 查找并导入所有子评论
|
||||
const loadChildren = (parentC: Comment) => {
|
||||
const children = srcData.filter(o => o.rid === parentC.data.id)
|
||||
children.forEach((childData: CommentData) => {
|
||||
const childC = this.createComment(childData)
|
||||
childC.render()
|
||||
|
||||
// 插入到父评论中
|
||||
parentC.putChild(childC)
|
||||
|
||||
// 递归加载子评论
|
||||
loadChildren(childC)
|
||||
})
|
||||
}
|
||||
|
||||
private importCommentsNest(srcData: CommentData[]) {
|
||||
// 遍历 root 评论
|
||||
const rootComments = srcData.filter((o) => o.rid === 0)
|
||||
rootComments.forEach((rootData: CommentData) => {
|
||||
const rootC = this.createComment(rootData)
|
||||
rootC.render()
|
||||
const rootNodes = ListNest.makeNestCommentNodeList(srcData, this.nestSortBy, this.conf.nestMax)
|
||||
rootNodes.forEach((rootNode: ListNest.CommentNode) => {
|
||||
const rootC = this.createComment(rootNode.comment, srcData)
|
||||
|
||||
// 显示并播放渐入动画
|
||||
this.$commentsWrap.appendChild(rootC.getEl())
|
||||
rootC.playFadeInAnim()
|
||||
|
||||
// 评论放入 comments 总表中
|
||||
this.comments.push(rootC)
|
||||
rootC.getRender().playFadeAnim()
|
||||
|
||||
// 加载子评论
|
||||
loadChildren(rootC)
|
||||
const that = this
|
||||
;(function loadChildren(parentC: Comment, parentNode: ListNest.CommentNode) {
|
||||
parentNode.children.forEach((node: ListNest.CommentNode) => {
|
||||
const childD = node.comment
|
||||
const childC = that.createComment(childD, srcData)
|
||||
|
||||
// 插入到父评论中
|
||||
parentC.putChild(childC)
|
||||
|
||||
// 递归加载子评论
|
||||
loadChildren(childC, node)
|
||||
})
|
||||
})(rootC, rootNode)
|
||||
|
||||
// 限高检测
|
||||
rootC.checkHeightLimit()
|
||||
rootC.getRender().checkHeightLimit()
|
||||
})
|
||||
}
|
||||
|
||||
/** 导入评论 · 平铺模式 */
|
||||
private putCommentFlatMode(cData: CommentData, srcData: CommentData[], insertMode: 'append'|'prepend') {
|
||||
private putCommentFlatMode(cData: CommentData, ctxData: CommentData[], insertMode: 'append'|'prepend') {
|
||||
if (cData.is_collapsed) cData.is_allow_reply = false
|
||||
const comment = this.createComment(cData)
|
||||
if (cData.rid !== 0) {
|
||||
const rComment = srcData.find(o => o.id === cData.rid)
|
||||
if (rComment) comment.replyTo = rComment
|
||||
}
|
||||
comment.render()
|
||||
|
||||
// 将评论导入 comments 总表中
|
||||
if (insertMode === 'append') this.comments.push(comment)
|
||||
if (insertMode === 'prepend') this.comments.unshift(comment)
|
||||
const comment = this.createComment(cData, ctxData)
|
||||
|
||||
// 可见评论添加到界面
|
||||
// 注:不可见评论用于显示 “引用内容”
|
||||
if (cData.visible) {
|
||||
if (insertMode === 'append') this.$commentsWrap.append(comment.getEl())
|
||||
if (insertMode === 'prepend') this.$commentsWrap.prepend(comment.getEl())
|
||||
comment.playFadeInAnim()
|
||||
comment.getRender().playFadeAnim()
|
||||
}
|
||||
|
||||
// 平铺评论插入后 · 内容限高检测
|
||||
comment.checkHeightLimit()
|
||||
comment.getRender().checkHeightLimit()
|
||||
|
||||
return comment
|
||||
}
|
||||
@@ -351,32 +393,30 @@ export default class ListLite extends Component {
|
||||
if (!this.flatMode) {
|
||||
// 嵌套模式
|
||||
const comment = this.createComment(commentData)
|
||||
comment.render()
|
||||
|
||||
if (commentData.rid === 0) {
|
||||
// root评论 新增
|
||||
this.$commentsWrap.prepend(comment.getEl())
|
||||
this.comments.unshift(comment)
|
||||
} else {
|
||||
// 子评论 新增
|
||||
const parent = this.findComment(commentData.rid)
|
||||
const parent = this.ctx.findComment(commentData.rid)
|
||||
if (parent) {
|
||||
parent.putChild(comment)
|
||||
parent.putChild(comment, (this.nestSortBy === 'DATE_ASC' ? 'append' : 'prepend'))
|
||||
|
||||
// 若父评论存在 “子评论部分” 限高,取消限高
|
||||
comment.getParents().forEach((p) => {
|
||||
if (p.$children) p.heightLimitRemove(p.$children)
|
||||
p.getRender().heightLimitRemoveForChildren()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
comment.checkHeightLimit()
|
||||
comment.getRender().checkHeightLimit()
|
||||
|
||||
Ui.scrollIntoView(comment.getEl()) // 滚动到可以见
|
||||
comment.playFadeInAnim() // 播放评论渐出动画
|
||||
comment.getRender().playFadeAnim() // 播放评论渐出动画
|
||||
} else {
|
||||
// 平铺模式
|
||||
const comment = this.putCommentFlatMode(commentData, this.comments.map(c => c.data), 'prepend')
|
||||
const comment = this.putCommentFlatMode(commentData, this.ctx.getCommentDataList(), 'prepend')
|
||||
Ui.scrollIntoView(comment.getEl()) // 滚动到可见
|
||||
}
|
||||
|
||||
@@ -385,61 +425,8 @@ export default class ListLite extends Component {
|
||||
|
||||
// 评论新增后
|
||||
this.refreshUI()
|
||||
this.ctx.trigger('comments-loaded')
|
||||
}
|
||||
|
||||
/** 遍历操作 Comment (包括子评论) */
|
||||
protected eachComment(commentList: Comment[], action: (comment: Comment, levelList: Comment[]) => boolean|void) {
|
||||
if (commentList.length === 0) return
|
||||
commentList.every((item) => {
|
||||
if (action(item, commentList) === false) return false
|
||||
this.eachComment(item.getChildren(), action)
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
/** 查找评论项 */
|
||||
protected findComment(id: number, src?: Comment[]): Comment|null {
|
||||
if (!src) src = this.comments
|
||||
let comment: Comment|null = null
|
||||
this.eachComment(src, (item) => {
|
||||
if (item.data.id === id) {
|
||||
comment = item
|
||||
return false
|
||||
}
|
||||
return true
|
||||
})
|
||||
|
||||
return comment
|
||||
}
|
||||
|
||||
/** 删除评论 */
|
||||
public deleteComment(comment: number|Comment) {
|
||||
let findComment: Comment|null
|
||||
if (typeof comment === 'number') {
|
||||
findComment = this.findComment(comment)
|
||||
if (!findComment) throw Error(`未找到评论 ${comment}`)
|
||||
} else findComment = comment
|
||||
|
||||
findComment.getEl().remove()
|
||||
this.eachComment(this.comments, (item, levelList) => {
|
||||
if (item === findComment) {
|
||||
levelList.splice(levelList.indexOf(item), 1)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
})
|
||||
|
||||
if (this.data) this.data.total -= 1 // 评论数减 1
|
||||
|
||||
this.refreshUI()
|
||||
}
|
||||
|
||||
/** 清空所有评论 */
|
||||
public clearAllComments() {
|
||||
this.$commentsWrap.innerHTML = ''
|
||||
this.data = undefined
|
||||
this.comments = []
|
||||
this.ctx.trigger('list-loaded')
|
||||
this.ctx.trigger('list-inserted', commentData)
|
||||
}
|
||||
|
||||
/** 更新未读数据 */
|
||||
@@ -448,43 +435,41 @@ export default class ListLite extends Component {
|
||||
|
||||
// 高亮评论
|
||||
if (this.unreadHighlight === true) {
|
||||
this.eachComment(this.comments, (comment) => {
|
||||
const notify = this.unread.find(o => o.comment_id === comment.data.id)
|
||||
this.ctx.getCommentList().forEach((comment) => {
|
||||
const notify = this.unread.find(o => o.comment_id === comment.getID())
|
||||
if (notify) {
|
||||
comment.setUnread(true)
|
||||
comment.setOpenURL(notify.read_link)
|
||||
comment.openEvt = () => {
|
||||
this.unread = this.unread.filter(o => o.comment_id !== comment.data.id) // remove
|
||||
this.ctx.trigger('unread-update', {
|
||||
notifies: this.unread
|
||||
})
|
||||
}
|
||||
comment.getRender().setUnread(true)
|
||||
comment.getRender().setOpenAction(() => {
|
||||
window.open(notify.read_link)
|
||||
this.unread = this.unread.filter(o => o.comment_id !== comment.getID()) // remove
|
||||
this.ctx.updateNotifies(this.unread)
|
||||
})
|
||||
} else {
|
||||
comment.setUnread(false)
|
||||
comment.getRender().setUnread(false)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/** 前端版本检测 */
|
||||
public versionCheck(versionData: ApiVersionData): boolean {
|
||||
const needVersion = versionData?.fe_min_version || '0.0.0'
|
||||
const needUpdate = Utils.versionCompare(needVersion, ARTALK_VERSION) === 1
|
||||
/** 版本检测 */
|
||||
public versionCheck(name: 'frontend'|'backend', needVersion: string, curtVersion: string): boolean {
|
||||
const needUpdate = Utils.versionCompare(needVersion, curtVersion) === 1
|
||||
if (needUpdate) {
|
||||
// 需要更新
|
||||
const errEl = Utils.createElement(`<div>前端 Artalk 版本已过时,请更新以获得完整体验<br/>`
|
||||
+ `若您是站点管理员,请前往 “<a href="https://artalk.js.org/" target="_blank">官方文档</a>” 获取帮助`
|
||||
const errEl = Utils.createElement(`<div>Artalk ${this.$t(name)}版本已过时,请更新以获得完整体验<br/>`
|
||||
+ `如果你是管理员,请前往 “<a href="https://artalk.js.org/" target="_blank">官方文档</a>” 获得帮助`
|
||||
+ `<br/><br/>`
|
||||
+ `<span style="color: var(--at-color-meta);">前端版本 ${ARTALK_VERSION},需求版本 >= ${needVersion}</span><br/><br/>`
|
||||
+ `<span style="color: var(--at-color-meta);">当前${this.$t(name)}版本 ${curtVersion},需求版本 >= ${needVersion}</span><br/><br/>`
|
||||
+ `</div>`)
|
||||
const ignoreBtn = Utils.createElement('<span style="cursor:pointer;">忽略</span>')
|
||||
ignoreBtn.onclick = () => {
|
||||
Ui.setError(this.ctx, null)
|
||||
Ui.setError(this.$el.parentElement!, null)
|
||||
this.ctx.conf.versionCheck = false
|
||||
this.ctx.trigger('conf-updated')
|
||||
this.fetchComments(0)
|
||||
}
|
||||
errEl.append(ignoreBtn)
|
||||
Ui.setError(this.ctx, errEl, '<span class="atk-warn-title">Artalk Warn</span>')
|
||||
Ui.setError(this.$el.parentElement!, errEl, '<span class="atk-warn-title">Artalk Warn</span>')
|
||||
}
|
||||
|
||||
return needUpdate
|
||||
@@ -0,0 +1,66 @@
|
||||
import { CommentData } from '~/types/artalk-data'
|
||||
|
||||
export type CommentNode = {
|
||||
id: number
|
||||
comment: CommentData
|
||||
children: CommentNode[]
|
||||
parent?: CommentNode
|
||||
level: number
|
||||
}
|
||||
|
||||
export type SortByType = 'DATE_DESC'|'DATE_ASC'|'SRC_INDEX'|'VOTE_UP_DESC'
|
||||
|
||||
// 构建树状结构列表
|
||||
export function makeNestCommentNodeList(srcData: CommentData[], sortBy: SortByType = 'DATE_DESC', nestMax = 2) {
|
||||
const nodeList: CommentNode[] = []
|
||||
|
||||
const roots = srcData.filter((o) => o.rid === 0)
|
||||
roots.forEach((root: CommentData) => {
|
||||
const rootNode: CommentNode = {
|
||||
id: root.id,
|
||||
comment: root,
|
||||
children: [],
|
||||
level: 1,
|
||||
}
|
||||
|
||||
rootNode.parent = rootNode
|
||||
nodeList.push(rootNode)
|
||||
|
||||
;(function loadChildren(parentNode: CommentNode) {
|
||||
const children = srcData.filter((o) => o.rid === parentNode.id)
|
||||
if (children.length === 0) return
|
||||
if (parentNode.level >= nestMax) parentNode = parentNode.parent!
|
||||
children.forEach((child: CommentData) => {
|
||||
const childNode: CommentNode = {
|
||||
id: child.id,
|
||||
comment: child,
|
||||
children: [],
|
||||
parent: parentNode,
|
||||
level: parentNode.level + 1,
|
||||
}
|
||||
|
||||
parentNode.children.push(childNode)
|
||||
loadChildren(childNode)
|
||||
})
|
||||
})(rootNode)
|
||||
})
|
||||
|
||||
// 排序
|
||||
const sortFunc = (a: CommentNode, b: CommentNode): number => {
|
||||
let v = a.id - b.id
|
||||
if (sortBy === 'DATE_ASC') v = +new Date(a.comment.date) - +new Date(b.comment.date)
|
||||
else if (sortBy === 'DATE_DESC') v = +new Date(b.comment.date) - +new Date(a.comment.date)
|
||||
else if (sortBy === 'SRC_INDEX') v = srcData.indexOf(a.comment) - srcData.indexOf(b.comment)
|
||||
else if (sortBy === 'VOTE_UP_DESC') v = b.comment.vote_up - a.comment.vote_up
|
||||
return v
|
||||
}
|
||||
|
||||
(function sortLevels(nodes: CommentNode[]) {
|
||||
nodes.forEach((node) => {
|
||||
node.children = node.children.sort(sortFunc)
|
||||
sortLevels(node.children)
|
||||
})
|
||||
})(nodeList)
|
||||
|
||||
return nodeList
|
||||
}
|
||||
@@ -1,16 +1,13 @@
|
||||
<div class="atk-list">
|
||||
<div class="atk-list-header">
|
||||
<div class="atk-comment-count">
|
||||
<div class="atk-text">
|
||||
<span class="atk-comment-count-num">0</span>
|
||||
条评论
|
||||
</div>
|
||||
<div class="atk-text"></div>
|
||||
</div>
|
||||
<div class="atk-right-action">
|
||||
<span data-action="admin-close-comment" class="atk-hide" atk-only-admin-show>关闭评论</span>
|
||||
<span data-action="admin-close-comment" class="atk-hide" atk-only-admin-show></span>
|
||||
<span data-action="open-sidebar" class="atk-hide atk-on">
|
||||
<span class="atk-unread-badge" style="display: none;"></span>
|
||||
<div class="atk-text">通知中心</div>
|
||||
<div class="atk-text"></div>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1,18 +1,18 @@
|
||||
import '../style/list.less'
|
||||
|
||||
import Context from '../context'
|
||||
import { ListData, NotifyData } from '~/types/artalk-data'
|
||||
import Context from '~/types/context'
|
||||
import * as Utils from '../lib/utils'
|
||||
import * as Ui from '../lib/ui'
|
||||
import Api from '../api'
|
||||
import ListHTML from './html/list.html?raw'
|
||||
import ListHTML from './list.html?raw'
|
||||
import ListLite from './list-lite'
|
||||
import { ListData } from '~/types/artalk-data'
|
||||
|
||||
export default class List extends ListLite {
|
||||
private $closeCommentBtn!: HTMLElement
|
||||
private $openSidebarBtn!: HTMLElement
|
||||
private $unreadBadge!: HTMLElement
|
||||
private $commentCount!: HTMLElement
|
||||
private $commentCountNum!: HTMLElement
|
||||
private $dropdownWrap?: HTMLElement
|
||||
|
||||
constructor (ctx: Context) {
|
||||
@@ -25,38 +25,39 @@ export default class List extends ListLite {
|
||||
this.$el = el
|
||||
|
||||
// 平铺模式
|
||||
let flatMode = false
|
||||
if (this.ctx.conf.flatMode === 'auto') {
|
||||
if (this.ctx.conf.flatMode === true) {
|
||||
this.flatMode = true // 遵循配置总是开启平铺模式
|
||||
} else if (this.conf.nestMax && this.conf.nestMax <= 1) {
|
||||
this.flatMode = true // 嵌套层数值无效时,强制开启平铺模式
|
||||
} else if (this.ctx.conf.flatMode === 'auto') {
|
||||
// 自动判断启用平铺模式
|
||||
if (window.matchMedia("(max-width: 768px)").matches)
|
||||
flatMode = true
|
||||
} else if (this.ctx.conf.flatMode === true) {
|
||||
flatMode = true
|
||||
this.flatMode = true
|
||||
}
|
||||
this.flatMode = flatMode
|
||||
|
||||
// 分页模式
|
||||
this.pageMode = this.conf.pagination?.readMore ? 'read-more' : 'pagination'
|
||||
this.pageSize = this.conf.pagination?.pageSize || 20
|
||||
this.pageMode = this.conf.pagination.readMore ? 'read-more' : 'pagination'
|
||||
this.pageSize = this.conf.pagination.pageSize || 20
|
||||
this.repositionAt = this.$el
|
||||
|
||||
// 操作按钮
|
||||
this.initListActionBtn()
|
||||
|
||||
// 下拉选择层
|
||||
this.$commentCount = this.$el.querySelector('.atk-comment-count')!
|
||||
this.initDropdown()
|
||||
this.$commentCount.innerHTML = this.$t('counter', {
|
||||
count: '<span class="atk-comment-count-num">0</span>',
|
||||
})
|
||||
this.$commentCountNum = this.$commentCount.querySelector('.atk-comment-count-num')!
|
||||
|
||||
// 评论列表排序 Dropdown 下拉选择层
|
||||
if (this.ctx.conf.listSort) {
|
||||
this.initDropdown()
|
||||
}
|
||||
|
||||
// copyright
|
||||
this.$el.querySelector<HTMLElement>('.atk-copyright')!.innerHTML = `Powered By <a href="https://artalk.js.org" target="_blank" title="Artalk v${ARTALK_VERSION}">Artalk</a>`
|
||||
|
||||
// event listen
|
||||
this.ctx.on('list-reload', () => (this.fetchComments(0))) // 刷新评论
|
||||
this.ctx.on('list-refresh-ui', () => (this.refreshUI()))
|
||||
this.ctx.on('list-import', (data) => (this.importComments(data)))
|
||||
this.ctx.on('list-insert', (data) => (this.insertComment(data)))
|
||||
this.ctx.on('list-delete', (comment) => (this.deleteComment(comment.id)))
|
||||
this.ctx.on('list-update', (updateData) => { updateData(this.data);this.refreshUI() } )
|
||||
this.ctx.on('unread-update', (data) => (this.showUnreadBadge(data.notifies?.length || 0)))
|
||||
}
|
||||
|
||||
private initListActionBtn() {
|
||||
@@ -66,7 +67,7 @@ export default class List extends ListLite {
|
||||
this.$unreadBadge = this.$el.querySelector('.atk-unread-badge')!
|
||||
|
||||
this.$openSidebarBtn.addEventListener('click', () => {
|
||||
this.ctx.trigger('sidebar-show')
|
||||
this.ctx.showSidebar()
|
||||
})
|
||||
|
||||
// 关闭评论按钮
|
||||
@@ -82,7 +83,7 @@ export default class List extends ListLite {
|
||||
public refreshUI() {
|
||||
super.refreshUI()
|
||||
|
||||
this.$el.querySelector<HTMLElement>('.atk-comment-count-num')!.innerText = String(Number(this.data?.total) || 0)
|
||||
this.$commentCountNum.innerText = String(Number(this.data?.total) || 0)
|
||||
|
||||
// 已输入个人信息
|
||||
if (!!this.ctx.user.data.nick && !!this.ctx.user.data.email) {
|
||||
@@ -92,16 +93,17 @@ export default class List extends ListLite {
|
||||
}
|
||||
|
||||
// 仅管理员显示控制
|
||||
this.ctx.trigger('check-admin-show-el')
|
||||
this.$openSidebarBtn.querySelector<HTMLElement>('.atk-text')!.innerText = (!this.ctx.user.data.isAdmin) ? '通知中心' : '控制中心'
|
||||
this.ctx.checkAdminShowEl()
|
||||
this.$openSidebarBtn.querySelector<HTMLElement>('.atk-text')!
|
||||
.innerText = (!this.ctx.user.data.isAdmin) ? this.$t('msgCenter') : this.$t('ctrlCenter')
|
||||
|
||||
// 关闭评论
|
||||
if (!!this.data && !!this.data.page && this.data.page.admin_only === true) {
|
||||
this.ctx.trigger('editor-close')
|
||||
this.$closeCommentBtn.innerHTML = '打开评论'
|
||||
this.ctx.editorClose()
|
||||
this.$closeCommentBtn.innerHTML = this.$t('openComment')
|
||||
} else {
|
||||
this.ctx.trigger('editor-open')
|
||||
this.$closeCommentBtn.innerHTML = '关闭评论'
|
||||
this.ctx.editorOpen()
|
||||
this.$closeCommentBtn.innerHTML = this.$t('closeComment')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -109,11 +111,19 @@ export default class List extends ListLite {
|
||||
super.onLoad(data, offset)
|
||||
|
||||
// 检测锚点跳转
|
||||
this.checkGoToCommentByUrlHash()
|
||||
if (!this.goToCommentFounded) this.checkGoToCommentByUrlHash()
|
||||
|
||||
// 防止评论框被吞
|
||||
if (this.ctx.conf.editorTravel === true) {
|
||||
this.ctx.editorTravelBack()
|
||||
}
|
||||
}
|
||||
|
||||
private goToCommentFounded = false
|
||||
public goToCommentDelay = true
|
||||
|
||||
/** 跳到评论项位置 - 根据 `location.hash` */
|
||||
public async checkGoToCommentByUrlHash () {
|
||||
public checkGoToCommentByUrlHash() {
|
||||
let commentId = Number(Utils.getQueryParam('atk_comment')) // same as backend GetReplyLink()
|
||||
if (!commentId) {
|
||||
const match = window.location.hash.match(/#atk-comment-([0-9]+)/)
|
||||
@@ -122,50 +132,60 @@ export default class List extends ListLite {
|
||||
}
|
||||
if (!commentId) return
|
||||
|
||||
const comment = this.ctx.findComment(commentId)
|
||||
if (!comment) { // 若找不到评论
|
||||
// 自动翻页
|
||||
if (this.readMoreBtn) this.readMoreBtn.click()
|
||||
else if (this.pagination) this.pagination.next()
|
||||
return
|
||||
}
|
||||
|
||||
// 已阅 API
|
||||
const notifyKey = Utils.getQueryParam('atk_notify_key')
|
||||
if (notifyKey) {
|
||||
new Api(this.ctx).markRead(notifyKey)
|
||||
this.ctx.getApi().markRead(notifyKey)
|
||||
.then(() => {
|
||||
this.unread = this.unread.filter(o => o.comment_id !== commentId)
|
||||
this.ctx.trigger('unread-update', {
|
||||
notifies: this.unread
|
||||
})
|
||||
this.updateUnread(this.unread)
|
||||
})
|
||||
}
|
||||
|
||||
const comment = this.findComment(commentId)
|
||||
// TODO 若找不到评论的情况
|
||||
// if (!comment) { // 若找不到评论
|
||||
// if (this.hasMoreComments) { // 阅读更多,并重试
|
||||
// await this.fetchComments()
|
||||
// }
|
||||
// }
|
||||
// 若父评论存在 “子评论部分” 限高,取消限高
|
||||
comment.getParents().forEach((p) => {
|
||||
p.getRender().heightLimitRemoveForChildren()
|
||||
})
|
||||
|
||||
if (!comment) return
|
||||
const goTo = () => {
|
||||
Ui.scrollIntoView(comment.getEl(), false)
|
||||
|
||||
Ui.scrollIntoView(comment.getEl(), false)
|
||||
window.setTimeout(() => {
|
||||
comment.getEl().classList.add('atk-flash-once')
|
||||
}, 800)
|
||||
comment.getEl().classList.remove('atk-flash-once')
|
||||
window.setTimeout(() => {
|
||||
comment.getEl().classList.add('atk-flash-once')
|
||||
}, 150)
|
||||
}
|
||||
|
||||
if (!this.goToCommentDelay) goTo()
|
||||
else window.setTimeout(() => goTo(), 350)
|
||||
|
||||
this.goToCommentFounded = true
|
||||
}
|
||||
|
||||
/** 管理员设置页面信息 */
|
||||
public adminPageEditSave () {
|
||||
if (!this.data || !this.data.page) return
|
||||
|
||||
this.ctx.trigger('editor-show-loading')
|
||||
new Api(this.ctx).pageEdit(this.data.page)
|
||||
this.ctx.editorShowLoading()
|
||||
this.ctx.getApi().pageEdit(this.data.page)
|
||||
.then((page) => {
|
||||
if (this.data)
|
||||
this.data.page = { ...page }
|
||||
this.refreshUI()
|
||||
})
|
||||
.catch(err => {
|
||||
this.ctx.trigger('editor-notify', { msg: `修改页面数据失败:${err.msg || String(err)}`, type: 'e'})
|
||||
this.ctx.editorShowNotify(`${this.$t('editFail')}: ${err.msg || String(err)}`, 'e')
|
||||
})
|
||||
.finally(() => {
|
||||
this.ctx.trigger('editor-hide-loading')
|
||||
this.ctx.editorHideLoading()
|
||||
})
|
||||
}
|
||||
|
||||
@@ -184,7 +204,7 @@ export default class List extends ListLite {
|
||||
this.$commentCount.classList.add('atk-dropdown-wrap')
|
||||
|
||||
// 插入图标
|
||||
this.$commentsWrap.append(Utils.createElement(`<span class="atk-arrow-down-icon"></span>`))
|
||||
this.$dropdownWrap.append(Utils.createElement(`<span class="atk-arrow-down-icon"></span>`))
|
||||
|
||||
const reloadUseParamsEditor = (func: (p: any) => void) => {
|
||||
this.paramsEditor = (p) => { func(p) }
|
||||
@@ -193,10 +213,10 @@ export default class List extends ListLite {
|
||||
|
||||
// 下拉列表
|
||||
const dropdownList = [
|
||||
['最新', () => { reloadUseParamsEditor(p => { p.sort_by = 'date_desc' }) }],
|
||||
['最热', () => { reloadUseParamsEditor(p => { p.sort_by = 'vote' }) }],
|
||||
['最早', () => { reloadUseParamsEditor(p => { p.sort_by = 'date_asc' }) }],
|
||||
['作者', () => { reloadUseParamsEditor(p => { p.view_only_admin = true }) }],
|
||||
[this.$t('sortLatest'), () => { reloadUseParamsEditor(p => { p.sort_by = 'date_desc' }) }],
|
||||
[this.$t('sortBest'), () => { reloadUseParamsEditor(p => { p.sort_by = 'vote' }) }],
|
||||
[this.$t('sortOldest'), () => { reloadUseParamsEditor(p => { p.sort_by = 'date_asc' }) }],
|
||||
[this.$t('sortAuthor'), () => { reloadUseParamsEditor(p => { p.view_only_admin = true }) }],
|
||||
]
|
||||
|
||||
// 列表项点击事件
|
||||
@@ -231,4 +251,9 @@ export default class List extends ListLite {
|
||||
|
||||
this.$dropdownWrap.append($dropdown)
|
||||
}
|
||||
|
||||
public updateUnread(notifies: NotifyData[]): void {
|
||||
super.updateUnread(notifies)
|
||||
this.showUnreadBadge(notifies?.length || 0)
|
||||
}
|
||||
}
|
||||
@@ -2,8 +2,8 @@
|
||||
--at-color-font: #2a2e2e;
|
||||
--at-color-deep: #2a2e2e;
|
||||
--at-color-sub: #757575;
|
||||
--at-color-grey: #999;
|
||||
--at-color-meta: #757e91;
|
||||
--at-color-grey: #747474;
|
||||
--at-color-meta: #697182;
|
||||
--at-color-border: #eceff2;
|
||||
--at-color-light: #4285f4;
|
||||
--at-color-bg: #FFF;
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
@font-family: "Helvetica Neue", "PingFangSC-Light", "Hiragino Sans GB", "Microsoft YaHei", "WenQuanYi Micro Hei", sans-serif;
|
||||
@font-size: 14px;
|
||||
@line-height: 1.6em;
|
||||
@block-radius: 4px;
|
||||
@block-radius: 6px;
|
||||
@@ -1,7 +1,7 @@
|
||||
.atk-comment-wrap {
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
border-bottom: 1px solid var(--at-color-border);
|
||||
border-bottom: 1px solid transparent;
|
||||
|
||||
&.atk-flash-once {
|
||||
animation: atkFlashOnce 1s ease-in-out 0s;
|
||||
@@ -49,20 +49,20 @@
|
||||
float: left;
|
||||
|
||||
img {
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
border-radius: 3px;
|
||||
width: 50px;
|
||||
height: 50px;
|
||||
border-radius: (@block-radius / 2);
|
||||
}
|
||||
}
|
||||
|
||||
& > .atk-main {
|
||||
display: block;
|
||||
margin-left: 62px;
|
||||
margin-left: 63px;
|
||||
|
||||
& > .atk-header {
|
||||
line-height: 1;
|
||||
font-size: 13px;
|
||||
margin-bottom: 3px;
|
||||
margin-bottom: .5em;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
display: flex;
|
||||
@@ -71,6 +71,8 @@
|
||||
|
||||
.atk-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
margin-top: 2px;
|
||||
margin-bottom: 2px;
|
||||
color: var(--at-color-meta);
|
||||
|
||||
@@ -83,20 +85,46 @@
|
||||
color: var(--at-color-main);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
&.atk-reply-at {
|
||||
margin-left: 2px;
|
||||
|
||||
& > .atk-arrow:before {
|
||||
content: '';
|
||||
vertical-align: middle;
|
||||
transform: rotate(90deg);
|
||||
border-bottom: 4px solid var(--at-color-grey);
|
||||
border-left: 3px solid transparent;
|
||||
border-right: 3px solid transparent;
|
||||
display: inline-block;
|
||||
margin-top: -1px;
|
||||
}
|
||||
|
||||
& > .atk-nick {
|
||||
color: var(--at-color-main);
|
||||
cursor: pointer;
|
||||
margin-left: 6px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.badge() {
|
||||
display: inline-block;
|
||||
color: var(--at-color-meta);
|
||||
background: var(--at-color-bg-grey);
|
||||
padding: 0 6px;
|
||||
line-height: 18px;
|
||||
border-radius: 3px;
|
||||
padding: 0px 6px;
|
||||
line-height: 17px;
|
||||
border-radius: (@block-radius / 2);
|
||||
|
||||
&:not(:last-child) {
|
||||
margin-right: 6px;
|
||||
}
|
||||
}
|
||||
|
||||
.atk-badge-wrap > *:last-child {
|
||||
margin-right: 6px;
|
||||
}
|
||||
|
||||
.atk-badge {
|
||||
.badge();
|
||||
color: #fff;
|
||||
@@ -115,6 +143,7 @@
|
||||
.atk-ua-wrap {
|
||||
@media only screen and (max-width: 768px) {
|
||||
display: block;
|
||||
margin-top: 5px;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -167,6 +196,7 @@
|
||||
border-left: 3px solid #eee;
|
||||
margin-bottom: 10px;
|
||||
position: relative;
|
||||
margin-top: 10px;
|
||||
|
||||
.atk-meta {
|
||||
font-size: 15px;
|
||||
@@ -212,6 +242,8 @@
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
margin-bottom: -15px;
|
||||
|
||||
& > span {
|
||||
color: var(--at-color-meta);
|
||||
@@ -220,6 +252,7 @@
|
||||
display: inline-flex;
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
margin-bottom: 15px;
|
||||
|
||||
&.atk-error, &.atk-error:hover {
|
||||
color: var(--at-color-red);
|
||||
@@ -228,7 +261,6 @@
|
||||
&:not(:first-child):not(.atk-hide) {
|
||||
margin-left: 8px;
|
||||
padding-left: 8px;
|
||||
border-left: 1px solid var(--at-color-border);
|
||||
}
|
||||
|
||||
&:hover {
|
||||
@@ -266,6 +298,10 @@
|
||||
font-size: 15px;
|
||||
color: var(--at-color-meta);
|
||||
user-select: none;
|
||||
|
||||
&:hover {
|
||||
background: var(--at-color-bg-grey);
|
||||
}
|
||||
}
|
||||
|
||||
// 避免重复显示按钮
|
||||
@@ -278,15 +314,14 @@
|
||||
.atk-comment-children {
|
||||
& > .atk-comment-wrap {
|
||||
margin-top: 10px;
|
||||
border-left: 1px dashed var(--at-color-border);
|
||||
border-left: 1px dashed transparent;
|
||||
border-bottom-color: transparent;
|
||||
&:not(:last-child) {
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
|
||||
& > .atk-comment {
|
||||
padding-top: 4px;
|
||||
padding-bottom: 4px;
|
||||
padding: 4px 0;
|
||||
|
||||
& > .atk-avatar img {
|
||||
width: 36px;
|
||||
@@ -295,6 +330,9 @@
|
||||
|
||||
& > .atk-main {
|
||||
margin-left: 47px;
|
||||
|
||||
& > .atk-body > .atk-content {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
background: var(--at-color-bg);
|
||||
border: 1px solid var(--at-color-border);
|
||||
border-radius: @block-radius;
|
||||
margin-bottom: 15px;
|
||||
margin-bottom: 10px;
|
||||
|
||||
@media only screen and (max-width: 768px) {
|
||||
margin-bottom: 7px;
|
||||
@@ -15,7 +15,7 @@
|
||||
& > .atk-header {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
padding: calc(@editor-padding / 2) @editor-padding 0;
|
||||
padding: 10px 14px 0;
|
||||
|
||||
input {
|
||||
flex: 1;
|
||||
@@ -23,7 +23,7 @@
|
||||
font-size: 14px;
|
||||
background: transparent;
|
||||
border: 2px solid transparent;
|
||||
border-radius: calc(@block-radius / 2);
|
||||
border-radius: (@block-radius / 2);
|
||||
padding: 6px 5px;
|
||||
resize: none;
|
||||
outline: none;
|
||||
@@ -44,11 +44,11 @@
|
||||
font-size: 15px;
|
||||
background-color: var(--at-color-bg);
|
||||
border: 2px solid transparent;
|
||||
border-radius: calc(@block-radius / 2);
|
||||
border-radius: (@block-radius / 2);
|
||||
width: 100%;
|
||||
min-height: 130px;
|
||||
min-height: 120px;
|
||||
margin-top: 2px;
|
||||
padding: @editor-padding calc(10px + 5px);
|
||||
padding: 10px 20px;
|
||||
resize: none;
|
||||
word-wrap: break-word;
|
||||
outline: none;
|
||||
@@ -61,15 +61,16 @@
|
||||
background-color: var(--at-color-bg);
|
||||
border-top: 1px solid var(--at-color-border);
|
||||
padding: 5px 15px;
|
||||
margin-top: 10px;
|
||||
// background: repeating-linear-gradient(145deg, #f2f2f2, #f2f2f2 15px, #fff 0, #fff 30px);
|
||||
}
|
||||
|
||||
& > .atk-send-reply {
|
||||
z-index: 2;
|
||||
position: absolute;
|
||||
right: 10px;
|
||||
bottom: 8px;
|
||||
max-width: calc(100% - 20px);
|
||||
right: 7px;
|
||||
bottom: 2px;
|
||||
max-width: (100% - 20px);
|
||||
height: 30px;
|
||||
line-height: 30px;
|
||||
font-size: 14px;
|
||||
@@ -79,6 +80,7 @@
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
cursor: pointer;
|
||||
border-radius: (@block-radius / 2);
|
||||
|
||||
.atk-text {
|
||||
}
|
||||
@@ -100,7 +102,7 @@
|
||||
}
|
||||
}
|
||||
|
||||
& > .atk-plug-wrap {
|
||||
& > .atk-plug-panel-wrap {
|
||||
position: relative;
|
||||
height: 180px;
|
||||
width: 100%;
|
||||
@@ -114,8 +116,7 @@
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
justify-content: space-between;
|
||||
border-top: 1px solid var(--at-color-border);
|
||||
padding: 0 0 0 calc(@editor-padding - 5px);
|
||||
padding: 5px 5px 5px 10px;
|
||||
|
||||
& > .atk-item {
|
||||
display: flex;
|
||||
@@ -125,13 +126,19 @@
|
||||
|
||||
.atk-plug-btn {
|
||||
padding: 0 8px;
|
||||
line-height: 24px;
|
||||
cursor: pointer;
|
||||
color: var(--at-color-grey);
|
||||
font-size: @font-size;
|
||||
user-select: none;
|
||||
border-radius: (@block-radius / 2);
|
||||
|
||||
&:not(:last-child) {
|
||||
border-right: 1px solid var(--at-color-border);
|
||||
margin-right: 2px;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
background: var(--at-color-bg-grey);
|
||||
}
|
||||
|
||||
&.active {
|
||||
@@ -164,6 +171,7 @@
|
||||
cursor: pointer;
|
||||
transition: opacity 0.3s ease-in-out;
|
||||
outline: none;
|
||||
border-radius: (@block-radius / 2);
|
||||
|
||||
&:active {
|
||||
opacity: 0.9;
|
||||
@@ -175,7 +183,7 @@
|
||||
z-index: 9;
|
||||
position: absolute;
|
||||
right: -2px;
|
||||
bottom: 36px;
|
||||
bottom: 40px;
|
||||
width: 225px;
|
||||
opacity: 0.83;
|
||||
}
|
||||
|
||||
@@ -4,8 +4,7 @@
|
||||
& > .atk-list-header {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
padding: 10px 10px 5px 10px;
|
||||
border-bottom: 1px solid var(--at-color-border);
|
||||
padding: 10px 17px 10px 17px;
|
||||
|
||||
.atk-text {
|
||||
display: inline-block;
|
||||
@@ -19,11 +18,11 @@
|
||||
.atk-arrow-down-icon {
|
||||
cursor: pointer;
|
||||
vertical-align: middle;
|
||||
border-top: 6px solid var(--at-color-grey);
|
||||
border-left: 4px solid transparent;
|
||||
border-right: 4px solid transparent;
|
||||
border-top: 5px solid var(--at-color-grey);
|
||||
border-left: 3px solid transparent;
|
||||
border-right: 3px solid transparent;
|
||||
margin-top: -1px;
|
||||
margin-left: 0.4rem;
|
||||
margin-left: 0.8rem;
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
@@ -47,7 +46,7 @@
|
||||
padding: 0.6rem 0;
|
||||
border: 1px solid var(--at-color-border);
|
||||
text-align: center;
|
||||
border-radius: 0.25rem;
|
||||
border-radius: @block-radius;
|
||||
white-space: nowrap;
|
||||
margin: 0;
|
||||
list-style: none;
|
||||
@@ -103,7 +102,6 @@
|
||||
&:not(:last-child):not(.atk-hide) {
|
||||
margin-right: 10px;
|
||||
padding-right: 10px;
|
||||
border-right: 1px solid var(--at-color-border);
|
||||
}
|
||||
|
||||
.atk-unread-badge {
|
||||
@@ -127,7 +125,9 @@
|
||||
& > .atk-list-body {
|
||||
min-height: 150px;
|
||||
|
||||
& > .atk-list-comments-wrap {
|
||||
.atk-list-comments-wrap {
|
||||
.atk-main-editor {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -168,8 +168,8 @@
|
||||
|
||||
.atk-list-read-more {
|
||||
border-top: 1px dashed var(--at-color-border);
|
||||
margin-top: 20px;
|
||||
padding-bottom: 20px;
|
||||
margin-top: 28px;
|
||||
padding-bottom: 25px;
|
||||
|
||||
@media only screen and (max-width: 768px) {
|
||||
padding-bottom: 10px;
|
||||
@@ -207,8 +207,8 @@
|
||||
}
|
||||
|
||||
&:hover {
|
||||
background: var(--at-color-bg-grey);
|
||||
& > .atk-text {
|
||||
color: var(--at-color-main);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Loaded 100 of 127 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user