Compare commits

...
100 Commits
Author SHA1 Message Date
qwqcode 0738e6e782 v2.3.4
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-06-17 18:51:53 +08:00
renovate[bot] bb804cdb37 chore(deps): update typescript-eslint monorepo to v5.28.0 (#198)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-06-17 18:41:04 +08:00
renovate[bot] 1c53c52564 chore(deps): update dependency eslint to v8.17.0 (#196)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-06-17 18:39:12 +08:00
renovate[bot] 06133012f7 chore(deps): update dependency rollup to v2.75.6 (#192)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-06-17 18:38:31 +08:00
renovate[bot] 80b879e02a chore(deps): update dependency typescript to v4.7.3 (#193)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-06-17 18:36:30 +08:00
renovate[bot] fe0e95ddbd fix(deps): update dependency katex to ^0.16.0 (#199)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-06-17 18:34:57 +08:00
renovate[bot] dcf9297ac6 chore(deps): update dependency prettier to v2.7.1 (#197)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-06-17 18:32:54 +08:00
renovate[bot] b0f04c55e0 chore(deps): update node.js to v16.15.1 (#195)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-06-17 18:31:17 +08:00
renovate[bot] c01a65ccbd chore(deps): update dependency vite to v2.9.12 (#194)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-06-17 18:31:05 +08:00
renovate[bot] 34b25f8d1c chore(deps): update dependency @types/node to v16.11.41 (#191)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-06-17 18:28:57 +08:00
renovate[bot] 44b3f1f100 fix(deps): update dependency marked to ^4.0.17 (#190)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2022-06-17 18:27:59 +08:00
qwqcode 8743d79d56 chore: plugin-katex v0.1.3
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-06-17 18:21:57 +08:00
qwqcode 2deea89c1b refactor(func-use): Use lowercase function name instead (#189)
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-06-17 18:19:28 +08:00
qwqcode ce8bea8efa refactor(i18n): Modify zh-CN expand locale
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-06-17 17:40:55 +08:00
qwqcode 81c4031d2f style: Modify some details
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-06-17 17:38:58 +08:00
qwqcode a993601f76 feat: comment edit (#188)
* feat(comment-edit): Support submit for editing a comment

Signed-off-by: qwqcode <qwqcode@gmail.com>

* feat(comment-edit): Provide entrance for editing comment

Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-06-17 13:04:10 +08:00
qwqcode 2b0ab60ee6 refactor(api): Always pass parameter site_name to api call
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-06-15 18:32:27 +08:00
qwqcode 7719f9bcc7 chore(pkg-manager): Upgrade pnpm to 7.2.1
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-06-15 13:47:06 +08:00
renovate[bot]andRenovate Bot e25f4a965d chore(deps): update dependency @types/node to v16.11.39 (#186)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-06-14 17:40:00 +08:00
renovate[bot]andRenovate Bot 2cf81ea592 chore(deps): update dependency less to v4.1.3 (#187)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-06-14 17:39:46 +08:00
qwqcode 6747a7133e chore(ctx): Add setDarkMode method to context obj
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-06-11 13:32:45 +08:00
qwqcode a80beaf182 chore(docs): Update README.md
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-06-09 21:53:21 +08:00
renovate[bot]andRenovate Bot 9a6312d388 chore(deps): update dependency rollup to v2.75.5 (#179)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-06-06 22:38:16 +08:00
renovate[bot] 7b7caafcb6 chore(deps): update dependency @types/node to v16.11.38 (#178) 2022-06-06 22:38:16 +08:00
qwqcode 1f8f5d5f0b chore(docs): Replace cover image 2022-06-06 22:38:16 +08:00
qwqcode e0cd30baf9 chore(docs): Update README.md
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-06-06 22:38:16 +08:00
qwqcode bfe0ee4fc2 v2.3.3
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-05-31 09:30:12 +08:00
qwqcode 431258ca0c chore(typo): Fix typo in zh-CN for email
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-05-31 09:28:42 +08:00
Renovate Bot 9941522ce6 chore(deps): update pnpm/action-setup action to v2.2.2 2022-05-30 21:16:25 +08:00
Renovate Bot 25256f5e0a chore(deps): update dependency rollup to v2.75.3 2022-05-30 21:15:48 +08:00
Renovate Bot b8eb5cf283 chore(deps): update typescript-eslint monorepo to v5.26.0 2022-05-27 13:10:44 +08:00
renovate[bot] e9560857d9 chore(deps): update dependency vite-tsconfig-paths to v3.5.0 (#172) 2022-05-27 13:09:04 +08:00
renovate[bot] 9b1a83f44f chore(deps): update dependency typescript to v4.7.2 (#171) 2022-05-27 13:08:33 +08:00
inkss d54b3eeb72 fix(emoticons): Hide grpSwitcher error when there is only one grp 2022-05-23 17:28:19 +08:00
qwqcode 913a3bec5e v2.3.2
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-05-22 01:04:27 +08:00
qwqcode 2770c13a56 fix(loading): Editor with two layers of loading not working
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-05-22 01:01:17 +08:00
qwqcode 0a4d94f133 chore(type): Update imgUploader type
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-05-21 23:48:08 +08:00
inkss 3384b6abe9 chore(conf): imgUploader just returns img_url string (#166) 2022-05-21 22:30:18 +08:00
qwqcode 7d79beaf7c v2.3.1
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-05-21 18:17:19 +08:00
qwqcode d4d1729b0f feat(plugs): Use Plugs & LoadCountWidget method & Normalize locale conf option
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-05-21 16:36:58 +08:00
qwqcode 3e793c55db chore(import): Remove unused Api imports
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-05-21 14:10:59 +08:00
renovate[bot]andRenovate Bot 8cb439c1b9 chore(deps): update dependency eslint to v8.16.0 (#164)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-05-21 13:28:01 +08:00
renovate[bot]andRenovate Bot 231ff2bbbf fix(deps): update dependency katex to ^0.15.6 (#163)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-05-21 13:27:34 +08:00
renovate[bot]andRenovate Bot 1b8b809122 chore(deps): update dependency rollup to v2.74.1 (#162)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-05-21 13:27:23 +08:00
qwqcode 4222adae59 feat(style): Remove default font-family & better rounded corners
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-05-21 13:22:36 +08:00
qwqcode 2858a770df v2.3.0
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-05-21 01:16:04 +08:00
qwqcode f567841ab2 feat(style): unbounded style, remove redundant lines
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-05-21 01:12:12 +08:00
qwqcode 9b7a74e1a4 chore(build): Build ArtalkLite version
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-05-21 00:15:52 +08:00
qwqcode b2783d7945 feat(lite): ArtalkLite without marked dep
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-05-20 23:41:15 +08:00
qwqcode 7451a4723a chore(editor): Hide icon when marked dep does not exist
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-05-20 22:22:01 +08:00
qwqcode 617279573b feat(count): Show the number of comments anywhere
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-05-20 22:10:37 +08:00
qwqcode 4bcc16b4f7 chore(api): Modify stat api types
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-05-20 21:26:36 +08:00
qwqcode 4514f0a25f feat(conf): Allow el option to be empty
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-05-20 21:10:20 +08:00
qwqcode 8fa9a869a0 feat(pv): Support for multiple PV elements
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-05-20 20:58:24 +08:00
qwqcode f3776c8fb5 feat(api): Add statistic api usage
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-05-20 19:45:45 +08:00
qwqcode ada8fa6d91 chore(i18n): Modify some translations
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-05-20 17:55:24 +08:00
qwqcode 957ddfe70e refactor(sidebar): Use abstract class for SidebarView
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-05-20 15:28:39 +08:00
qwqcode 77cc5ff890 chore(conf): Modify i18n option to locale
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-05-19 22:01:08 +08:00
qwqcode 5d8d05a291 feat(editor): Add support for using custom imgUploader
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-05-19 21:40:02 +08:00
qwqcode 93b1ab7b12 chore(deps): Update pnpm to 7.1.2
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-05-19 21:24:59 +08:00
qwqcode 751793b313 refactor: Use Mediator Pattern (#161)
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-05-19 21:16:24 +08:00
renovate[bot]andRenovate Bot 67d24fe4a4 fix(deps): update dependency marked to ^4.0.16 (#158)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-05-19 17:28:40 +08:00
renovate[bot]andRenovate Bot 7f42a79d68 chore(deps): update dependency rollup to v2.74.0 (#159)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-05-19 17:28:27 +08:00
renovate[bot]andRenovate Bot bc5a0540e8 chore(deps): update typescript-eslint monorepo to v5.25.0 (#160)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-05-19 17:28:01 +08:00
renovate[bot]andRenovate Bot 43080cbf4c chore(deps): update dependency vite to v2.9.9 (#157)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-05-19 12:09:43 +08:00
renovate[bot]andRenovate Bot b70666decb chore(deps): update dependency postcss to v8.4.14 (#156)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-05-19 12:09:30 +08:00
renovate[bot]andRenovate Bot 1d52311bd7 chore(deps): update dependency @types/node to v16.11.36 (#155)
Co-authored-by: Renovate Bot <bot@renovateapp.com>
2022-05-19 12:09:07 +08:00
qwqcode 672cda65ae refactor: comment & editor (#154)
* refactor(editor): User profile input actions

Signed-off-by: qwqcode <qwqcode@gmail.com>

* refactor(user): Provide update method

Signed-off-by: qwqcode <qwqcode@gmail.com>

* refactor(context): Modified to interface-oriented

Signed-off-by: qwqcode <qwqcode@gmail.com>

* refactor(comment): Reorganize the methods

Signed-off-by: qwqcode <qwqcode@gmail.com>

* refactor(editor): Add the concept of EditorPanel and EditorBtn

Signed-off-by: qwqcode <qwqcode@gmail.com>

* chore: Move list folder to up-level directory

Signed-off-by: qwqcode <qwqcode@gmail.com>

* chore: Move layer folder to up-level directory

Signed-off-by: qwqcode <qwqcode@gmail.com>

* chore(conf): Remove ArtalkConfig optional symbol

Signed-off-by: qwqcode <qwqcode@gmail.com>

* chore: Remove useless code

Signed-off-by: qwqcode <qwqcode@gmail.com>

* feat(artalk-lite): ArtalkLite without bundled marked deps

Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-05-19 00:43:54 +08:00
qwqcodeandPercy Ma 8a4dc9d926 i18n: Add basic internationalization support (#150)
* feat(i18n): Add support for i18n

Signed-off-by: qwqcode <qwqcode@gmail.com>

* chore(docs): Add English README.md

Signed-off-by: qwqcode <qwqcode@gmail.com>

* chore(i18n): Modify some content

Co-authored-by: Percy Ma <kecrily@gmail.com>

* chore(docs): Modify README.en.md

Signed-off-by: qwqcode <qwqcode@gmail.com>

Co-authored-by: Percy Ma <kecrily@gmail.com>
2022-05-13 11:41:10 +08:00
qwqcode b88f6f3cd6 chore(conf): Disable darkMode by default
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-05-12 19:01:03 +08:00
Percy Ma 11efba69c8 chore(dep): reduce detection frequency 2022-05-11 13:34:46 +08:00
Renovate Bot e96371b7c6 chore(deps): update dependency @types/node to v16.11.34 2022-05-11 09:35:00 +08:00
renovate[bot] 04639e0e9b chore(deps): update typescript-eslint monorepo to v5.23.0 (#148) 2022-05-10 11:57:13 +08:00
qwqcode 2fbad53fad chore(circleci): Ignore gh-pages branch 2022-05-09 11:43:23 +08:00
Percy Ma 4c5d48a51b chore(dep): fix wrong renovate branch field 2022-05-09 10:42:20 +08:00
qwqcode 9783c5e434 Merge pull request #145 from ArtalkJS/renovate/chore/eslint-config-airbnb-typescript-17.x
chore(deps): update dependency eslint-config-airbnb-typescript to v17
2022-05-08 23:50:15 +08:00
Renovate Bot 7efff73127 chore(deps): update dependency eslint-config-airbnb-typescript to v17 2022-05-08 15:48:36 +00:00
qwqcode c0c1797ff4 Merge pull request #144 from ArtalkJS/renovate/chore/actions-checkout-3.x
chore(deps): update actions/checkout action to v3
2022-05-08 23:47:16 +08:00
Renovate Bot 49eb8907fd chore(deps): update actions/checkout action to v3 2022-05-08 15:46:17 +00:00
qwqcode 5f0c8a0be6 Merge pull request #142 from ArtalkJS/renovate/chore/pnpm-action-setup-2.x
chore(deps): update pnpm/action-setup action to v2.2.1
2022-05-08 23:45:48 +08:00
qwqcode 4b092a6688 Merge pull request #141 from ArtalkJS/renovate/chore/pin-dependencies
chore(deps): pin dependencies
2022-05-08 23:42:47 +08:00
Renovate Bot 87156fefcb chore(deps): update pnpm/action-setup action to v2.2.1 2022-05-08 15:31:37 +00:00
Renovate Bot 017e2e10d6 chore(deps): pin dependencies 2022-05-08 15:31:33 +00:00
qwqcode 20d03053e7 Merge pull request #140 from ArtalkJS/chore/renovate
chore: use renovate to auto update deps
2022-05-08 23:30:16 +08:00
Percy Ma c2890e7a43 chore: use renovate to auto update deps 2022-05-08 21:52:33 +08:00
qwqcode 304d691e1c chore(docs): Update README.md
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-05-05 21:50:01 +08:00
qwqcode 2de21a64d9 chore(test): Add CircleCI config
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-05-05 21:20:18 +08:00
qwqcode f44adad3ec chore(pkg-manager): Update pnpm to 7.0.0
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-05-04 23:45:03 +08:00
qwqcode 25552f7994 v2.2.12
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-05-04 23:30:37 +08:00
qwqcode a1de9c2138 chore(docs): Update README.md
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-05-04 23:15:37 +08:00
qwqcode 182f631936 feat(conf): Support setting emoticons to false to disable
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-05-04 23:13:03 +08:00
qwqcode c2698b4edb feat(darkMode): Auto switch DarkMode by listening 'prefers-color-scheme: dark'
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-05-04 22:29:00 +08:00
qwqcode 0e9498009b chore(list-lite): Combine all render method calls into one
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-05-04 22:06:59 +08:00
qwqcode a37992c381 fix(list): Reply a newly created comment cannot be found
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-05-04 21:58:50 +08:00
qwqcode 088d97784f chore(AbortController): Add polyfill and perform real abort when timeout
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-05-04 21:38:29 +08:00
qwqcode e2de49ad79 Merge pull request #136 from ArtalkJS/chore/browsers
chore: add browser compatibility lint
2022-05-04 16:50:52 +08:00
Percy Ma 0c66798762 chore: add browser compatibility lint 2022-05-04 14:47:51 +08:00
qwqcode f0ea373b47 fix(sidebar): No interact after reply a comment in sidebar
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-05-01 17:41:12 +08:00
qwqcode 6f1f48c18f v2.2.11
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-05-01 17:13:10 +08:00
qwqcode 91a0406d44 feat(conf): Add nestSort option
Signed-off-by: qwqcode <qwqcode@gmail.com>
2022-05-01 17:12:55 +08:00
102 changed files with 3819 additions and 2534 deletions

No files matched your search

+31
View File
@@ -0,0 +1,31 @@
version: 2.1
orbs:
node: circleci/node@5.0.2
jobs:
build:
docker:
- image: 'cimg/node:16.15.1'
steps:
- node/install
- checkout
- run:
name: Print the node version
command: node -v
- run:
name: Install pnpm
command: npm i -g pnpm@7.2.1
- 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
+5
View File
@@ -1,6 +1,7 @@
module.exports = {
root: true,
parser: "@typescript-eslint/parser",
env: { "browser": true} ,
parserOptions: {
project: ['./packages/*/tsconfig.json'],
tsconfigRootDir: __dirname,
@@ -11,6 +12,7 @@ module.exports = {
'prettier',
'plugin:import/recommended',
'plugin:import/typescript',
"plugin:compat/recommended",
],
plugins: ['@typescript-eslint', 'import'],
rules: {
@@ -35,5 +37,8 @@ module.exports = {
"project": [__dirname + "/packages/*/tsconfig.json"]
},
},
'polyfills': [
'AbortController'
]
},
}
+10
View File
@@ -0,0 +1,10 @@
{
"extends": ["config:base", "schedule:weekly"],
"branchPrefix": "chore/",
"labels": ["dependencies"],
"rangeStrategy": "bump",
"reviewers": [
"qwqcode",
"kecrily"
]
}
+3 -3
View File
@@ -16,9 +16,9 @@ jobs:
uses: actions/checkout@v3
- name: Use pnpm
uses: pnpm/action-setup@v2.0.1
uses: pnpm/action-setup@v2.2.2
with:
version: 7.0.0-rc.3
version: 7.2.1
- name: Set node version to 16.x
uses: actions/setup-node@v3
@@ -58,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 }}
+3 -3
View File
@@ -11,12 +11,12 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v2
uses: actions/checkout@v3
- name: Use pnpm
uses: pnpm/action-setup@v2.0.1
uses: pnpm/action-setup@v2.2.2
with:
version: 7.0.0-rc.3
version: 7.2.1
- name: Set node version to 16.x
uses: actions/setup-node@v3
+1 -1
View File
@@ -12,7 +12,7 @@ cache:
directories:
- "~/.pnpm-store"
before_install:
- curl -f https://get.pnpm.io/v6.16.js | node - add --global pnpm@7.0.0-rc.3
- curl -fsSL https://get.pnpm.io/install.sh | sh -
- pnpm config set store-dir ~/.pnpm-store
install:
- pnpm install
+143
View File
@@ -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://img.shields.io/npm/v/artalk.svg?style=flat-square)](https://www.npmjs.com/package/artalk)
[![](https://img.shields.io/npm/dt/artalk.svg?style=flat-square)](https://www.npmjs.com/package/artalk)
[![](https://badgen.net/bundlephobia/minzip/artalk?style=flat-square)](https://bundlephobia.com/package/artalk)
[![CircleCI](https://circleci.com/gh/ArtalkJS/Artalk/tree/master.svg?style=svg)](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://contrib.rocks/image?repo=ArtalkJS/Artalk)](https://github.com/ArtalkJS/Artalk/graphs/contributors)
## Supporters
[![Stargazers repo roster for @ArtalkJS/Artalk](https://reporoster.com/stars/ArtalkJS/Artalk)](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
[![Stargazers over time](https://starchart.cc/ArtalkJS/Artalk.svg)](https://starchart.cc/ArtalkJS/Artalk)
## License
[LGPL-3.0](./LICENSE)
[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2FArtalkJS%2FArtalk.svg?type=shield)](https://app.fossa.com/projects/git%2Bgithub.com%2FArtalkJS%2FArtalk?ref=badge_shield)
[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2FArtalkJS%2FArtalk.svg?type=large)](https://app.fossa.com/projects/git%2Bgithub.com%2FArtalkJS%2FArtalk?ref=badge_large)
+44 -42
View File
@@ -1,5 +1,5 @@
<p align="center">
<img src="https://user-images.githubusercontent.com/22412567/137740516-d9e97af0-fb3b-4dab-b331-671a9a2a3a63.png" alt="Artalk" width="100%">
<img src="https://user-images.githubusercontent.com/22412567/171680920-6e74b77c-c565-487b-bff1-4f94976ecbe7.png" alt="Artalk" width="100%">
</p>
# Artalk
@@ -7,44 +7,38 @@
[![](https://img.shields.io/npm/v/artalk.svg?style=flat-square)](https://www.npmjs.com/package/artalk)
[![](https://img.shields.io/npm/dt/artalk.svg?style=flat-square)](https://www.npmjs.com/package/artalk)
[![](https://badgen.net/bundlephobia/minzip/artalk?style=flat-square)](https://bundlephobia.com/package/artalk)
[![](https://img.shields.io/github/last-commit/ArtalkJS/Artalk/master.svg?style=flat-square)](https://github.com/ArtalkJS/Artalk/commits/master)
[![](https://img.shields.io/github/issues-raw/ArtalkJS/Artalk.svg?style=flat-square)](https://github.com/ArtalkJS/Artalk/issues)
[![](https://img.shields.io/github/issues-pr-raw/ArtalkJS/Artalk.svg?style=flat-square)](https://github.com/ArtalkJS/Artalk/pulls)
[![](https://img.shields.io/travis/com/ArtalkJS/Artalk?style=flat-square)](https://travis-ci.com/ArtalkJS/Artalk)
[![](https://img.shields.io/github/license/ArtalkJS/Artalk.svg?style=flat-square)](./LICENSE)
[![CircleCI](https://circleci.com/gh/ArtalkJS/Artalk/tree/master.svg?style=svg)](https://circleci.com/gh/ArtalkJS/Artalk/tree/master)
> 🌌 一款简洁的自托管评论系统 | A Selfhosted Comment System.
> 🌌 Golang 自托管评论系统
可参考:[“官方文档”](https://artalk.js.org)
最新版:[“Releases”](https://github.com/ArtalkJS/ArtalkGo/releases)
[English](./README.en.md) / [官方文档](https://artalk.js.org) / [最新后端](https://github.com/ArtalkJS/ArtalkGo/releases) / [ArtalkGo](https://github.com/ArtalkJS/ArtalkGo)
---
- 轻量级 (~30kB)
- 自托管 (数据安全)
- 易上手 (防秃顶)
- Golang 后端 (易部署 / 跨平台)
- TypeScript & Vanilla (纯天然无添加 / 无依赖)
- 🍃 轻量 (~30kB)
- 👨‍👧‍👦 安全 (自托管)
- 🐳 易上手 (防脱发)
- 🍱 Golang 后端 (快速 / 跨平台)
- 🌊 Vanilla x TypeScript × Vite (纯天然 / 无依赖)
## 特性
- 侧 边 栏 :所见即所得的管理方式
- 通知中心:红点的标记 / 已读记录
- 侧 边 栏 :支持多站点集中化管理
- 通知中心:红点的标记 / 提及列表
- 身份验证:徽标自定义 / 密码验证
- 评论审核:反垃圾检测 / 验证码频率限制
- 表情符号:插入表情包 / 快速导入表情包
- 邮件提醒:模版自定义 / 多管理员通知
- 站点隔离:多站点管理 / 管理员分配
- 评论审核:反垃圾检测 / 频率限制
- 表情符号:插入表情包 / 快速导入
- 邮件提醒:模版自定义 / 多管理员
- 站点隔离:管理员分配 / 多个站点
- 页面管理:标题可显示 / 快速跳转
- 图片上传:上传到本地 / 多种图床
- 树洞模式:仅自己可见 / 说说功能
- 多元推送:支持钉钉飞书 TG
- 多元推送:支持 钉钉 飞书 TG
- 无限层级:可切换为平铺模式
- 评论投票:赞同还是反对评论
- 评论排序:按热度或时间排序
- 评论置顶:重要消息置顶显示
- 只看作者:仅显示作者的评论
- 说说模式:仅自己可发布评论
- 异步处理:发送评论无需等待
- 滚动加载:评论内容分页处置
- 自动保存:用户输入防丢功能
@@ -53,15 +47,14 @@
- 暗黑模式:防止眼部疾病伤害
- 评论折叠:这个不打算给你康
- 数据备份:防止评论数据丢失
- 数据迁移:在不同评论系统之间来回切换
- 一页多评:一页多个评论区(似乎没啥用
- Markdown:语法默认支持
- 支持 Latex:引入 Artalk 的 Katex 插件
- [Vite](https://github.com/vitejs/vite):开发者的极致体验
- 数据迁移:快速切换评论系统
- Markdown:默认支持 MD 语法
- 支持 Latex:提供集成 Katex 插件
- 使用 [Vite](https://github.com/vitejs/vite):属于开发者的极致体验
## 食用方针
前往:[“**文档 · 部署**”](https://artalk.js.org/guide/deploy.html)
前往:[“**部署文档**”](https://artalk.js.org/guide/deploy.html)
```sh
$ pnpm add artalk
@@ -86,13 +79,19 @@ new Artalk({
mkdir Artalk
cd Artalk
# 下载配置文件模版
curl -L https://raw.githubusercontent.com/ArtalkJS/ArtalkGo/master/artalk-go.example.yml > conf.yml
# 拉取 docker 镜像
docker pull artalk/artalk-go
# 生成配置文件
docker run -it -v $(pwd)/data:/data --rm artalk/artalk-go gen config data/artalk-go.yml
# 编辑配置文件
vim data/artalk-go.yml
# 运行 docker 容器
docker run -d \
--name artalk \
--name artalk-go \
-p 0.0.0.0:8080:23366 \
-v $(pwd)/conf.yml:/conf.yml \
-v $(pwd)/data:/data \
artalk/artalk-go
```
@@ -113,9 +112,8 @@ services:
container_name: artalk
image: artalk/artalk-go
ports:
- 8080:23366
- 端口号:23366
volumes:
- ./conf.yml:/conf.yml
- ./data:/data
```
@@ -123,10 +121,18 @@ services:
docker-compose up -d
```
## Contributors
[![](https://contrib.rocks/image?repo=ArtalkJS/Artalk)](https://github.com/ArtalkJS/Artalk/graphs/contributors)
## Supporters
[![Stargazers repo roster for @ArtalkJS/Artalk](https://reporoster.com/stars/ArtalkJS/Artalk)](https://github.com/ArtalkJS/Artalk/stargazers)
## 特别致谢
感谢社区提供的帮助与反馈,若有好的建议与意见欢迎前往 [ISSUES](https://github.com/ArtalkJS/Artalk/issues) 随时告知。
## TODOs
- [x] [Golang 后端](https://github.com/ArtalkJS/ArtalkGo)
@@ -192,7 +198,7 @@ docker-compose up -d
- [x] Bark
- [x] Slack
- [x] LINE
- [ ] 自定义 HTTP 回调
- [x] 自定义 HTTP 回调
- [ ] 命令行管理
- [ ] 博客邮件订阅
- [x] 用户鉴权机制
@@ -202,7 +208,7 @@ docker-compose up -d
- [x] 时区自定义
- [x] 只看作者功能
- [ ] AT 提及 (@)
- [ ] 评论提及 (#)
- [ ] 评论话题 (#)
- [ ] 表情包统一管理
- [ ] 导入表情包
- [ ] 表情包图片地址控制
@@ -216,13 +222,9 @@ docker-compose up -d
- [ ] 扩展中心
- [ ] 开放用户注册
- [ ] 接入第三方登录
- [ ] 国际化 (i18n)
- [x] 国际化 (i18n)
- [x] 一键升级
## 特别致谢
感谢社区提供的帮助与反馈,若有好的建议与意见欢迎前往 [ISSUES](https://github.com/ArtalkJS/Artalk/issues) 随时告知。
## Stargazers over time
[![Stargazers over time](https://starchart.cc/ArtalkJS/Artalk.svg)](https://starchart.cc/ArtalkJS/Artalk)
+22 -18
View File
@@ -10,23 +10,27 @@
"build:all": "pnpm build && pnpm build:sidebar"
},
"devDependencies": {
"@rollup/plugin-dynamic-import-vars": "^1.4.3",
"@types/node": "^16.11.27",
"@typescript-eslint/eslint-plugin": "^5.20.0",
"@typescript-eslint/parser": "^5.20.0",
"autoprefixer": "^10.4.4",
"eslint": "^8.13.0",
"@rollup/plugin-dynamic-import-vars": "1.4.3",
"@types/node": "16.11.41",
"@typescript-eslint/eslint-plugin": "5.28.0",
"@typescript-eslint/parser": "5.28.0",
"autoprefixer": "10.4.7",
"eslint": "8.17.0",
"eslint-config-airbnb-base": "15.0.0",
"eslint-config-airbnb-typescript": "^16.2.0",
"eslint-config-prettier": "^8.5.0",
"eslint-import-resolver-typescript": "^2.7.1",
"eslint-plugin-import": "^2.26.0",
"less": "^4.1.2",
"postcss": "^8.4.12",
"prettier": "^2.6.2",
"rollup": "^2.70.2",
"typescript": "^4.6.3",
"vite": "^2.9.5",
"vite-tsconfig-paths": "^3.4.1"
}
"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.3",
"postcss": "8.4.14",
"prettier": "2.7.1",
"rollup": "2.75.6",
"typescript": "4.7.3",
"vite": "2.9.12",
"vite-tsconfig-paths": "3.5.0"
},
"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"
]
}
+1 -1
View File
@@ -21,7 +21,7 @@
InitSidebar({
el: '#ArtalkSidebar',
server: (import.meta.env.MODE === 'development') ? 'http://localhost:23366' : '../',
server: (import.meta.env.DEV) ? 'http://localhost:23366' : '../',
pageKey,
site,
darkMode,
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@artalkjs/artalk-sidebar",
"version": "0.1.1",
"version": "0.2.0",
"license": "LGPL-3.0",
"description": "The sidebar of artalk",
"repository": {
@@ -12,7 +12,7 @@
"bugs": "https://github.com/ArtalkJS/Artalk/issue",
"scripts": {
"dev": "vite --port 23367",
"build": "pnpm -F artalk build && pnpm lint && vite build",
"build": "pnpm lint && vite build",
"serve": "vite preview",
"lint": "eslint --ext .js,.ts src"
},
@@ -1,10 +1,9 @@
import '../style/page-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 { PageData } from 'artalk/types/artalk-data'
import Api from 'artalk/src/api'
import ActionBtn from 'artalk/src/components/action-btn'
import Component from '../sidebar-component'
import { SidebarCtx } from '../main'
@@ -39,9 +38,9 @@ export default class PageList extends Component {
// 缓存操作按钮
const $cacheFlushBtn = this.$el.querySelector<HTMLElement>('.atk-cache-flush-all-btn')!
$cacheFlushBtn.onclick = () => { new Api(this.ctx).cacheFlushAll().then((d: any) => alert(d.msg)).catch(() => alert('操作失败')) }
$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 = () => { new Api(this.ctx).cacheWarmUp().then((d: any) => alert(d.msg)).catch(() => alert('操作失败')) }
$cacheWarmBtn.onclick = () => { this.ctx.getApi().cacheWarmUp().then((d: any) => alert(d.msg)).catch(() => alert('操作失败')) }
// 更新全部页面标题按钮
;(async () => {
@@ -58,7 +57,7 @@ export default class PageList extends Component {
}, 1500)
}
const checkStatus = async () => {
const status = await new Api(this.ctx).pageFetch(undefined, undefined, true)
const status = await this.ctx.getApi().pageFetch(undefined, undefined, true)
return status
}
const startWatchdog = () => {
@@ -66,7 +65,7 @@ export default class PageList extends Component {
// 不完美的轮询更新状态
const timerID = window.setInterval(async () => {
const d = await new Api(this.ctx).pageFetch(undefined, undefined, true)
const d = await this.ctx.getApi().pageFetch(undefined, undefined, true)
if (d.is_progress === false) {
clearInterval(timerID)
@@ -93,7 +92,7 @@ export default class PageList extends Component {
// 发起任务
try {
await new Api(this.ctx).pageFetch(undefined, this.sidebar.curtSite)
await this.ctx.getApi().pageFetch(undefined, this.sidebar.curtSite)
} catch (err: any) {
alert(err.msg)
done()
@@ -188,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)
@@ -208,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')
@@ -220,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)
@@ -235,7 +234,7 @@ export default class PageList extends Component {
showLoading()
let p: PageData
try {
p = (await new Api(this.ctx).pageFetch(page.id)).page
p = (await this.ctx.getApi().pageFetch(page.id)).page
} catch (err: any) {
showError(`同步失败:${err.msg || '未知错误'}`)
console.log(err)
@@ -249,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)}`)
@@ -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,7 +49,7 @@ 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.substring(0, 1))
})
@@ -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'
import Component from '../sidebar-component'
import { SidebarCtx } from '../main'
import ItemTextEditor from '../lib/item-text-editor'
@@ -181,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)
@@ -212,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)}`)
@@ -274,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)
+2 -4
View File
@@ -11,11 +11,9 @@ export default async function InitSidebar(conf: ArtalkConfig, user: LocalUser, v
// 初始化用户数据
user = user || {}
artalk.ctx.user.data = {
...artalk.ctx.user.data,
artalk.ctx.user.update({
...user
}
artalk.ctx.user.save()
})
// 初始化 Sidebar
const sidebarCtx = new SidebarCtx()
@@ -1,8 +1,9 @@
import ArtalkComponent from 'artalk/src/lib/component'
import Context from 'artalk/src/context'
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) {
+27 -28
View File
@@ -1,32 +1,29 @@
import './style/sidebar.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 Comment from 'artalk/src/components/comment'
import { SiteData } from 'artalk/types/artalk-data'
import Api from 'artalk/src/api'
import Component from './sidebar-component'
import { SidebarCtx } from './main'
import SidebarHTML from './sidebar.html?raw'
import SidebarView from './sidebar-view'
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 './admin/site-list-floater'
import SiteListFloater from './components/site-list-floater'
import SettingView from './sidebar-views/setting-view'
import MD5 from './lib/md5'
const REGISTER_VIEWS: (typeof SidebarView)[] = [
const REGISTER_VIEWS = [
CommentsView, PagesView, SitesView, TransferView, // SettingView
]
export default class SidebarRoot extends Component {
public static DEFAULT_VIEW = 'comments'
public static readonly DEFAULT_VIEW = 'comments'
public $header: HTMLElement
public $headerMenu: HTMLElement
@@ -73,6 +70,7 @@ export default class SidebarRoot extends Component {
this.$viewWrap = this.$el.querySelector('.atk-sidebar-view-wrap')!
// init UI
this.initViewInstances()
this.initViewSwitcher()
// 重载操作
@@ -81,6 +79,14 @@ export default class SidebarRoot extends Component {
}
}
/** 初始化 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 = () => {
@@ -88,18 +94,18 @@ export default class SidebarRoot extends Component {
}
this.$navViews.innerHTML = ''
REGISTER_VIEWS.forEach(view => {
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', view.viewName)
$item.innerText = view.viewTitle
if (view.viewName === this.curtView) {
$item.setAttribute('data-name', viewName)
$item.innerText = view.viewTitle()
if (viewName === this.curtView) {
$item.classList.add('atk-active')
this.$curtViewBtnText.innerText = view.viewTitle
this.$curtViewBtnText.innerText = view.viewTitle()
}
$item.onclick = () => {
// 切换 view
this.switchView(view.viewName)
this.switchView(viewName)
this.toggleViewSwitcher()
}
@@ -195,25 +201,18 @@ export default class SidebarRoot extends Component {
/** 切换 View */
public switchView(viewName: string) {
if (!REGISTER_VIEWS.find(o => o.viewName === viewName))
const view = this.viewInstances[viewName]
if (!view)
throw new Error(`Sidebar View "${viewName}" not found`)
let view = this.viewInstances[viewName]
if (!view) {
// 初始化 View
const View = REGISTER_VIEWS.find(o => o.viewName === viewName)!
view = new View(this.ctx, this.sidebar, this.$viewWrap)
this.viewInstances[viewName] = view
}
// init view
view.mount()
this.curtView = viewName
this.curtTab = view.viewActiveTab
this.curtTab = view.getActiveTab()
// update view indicator
this.$curtViewBtnText.innerText = (view.constructor as typeof SidebarView).viewTitle
this.$curtViewBtnText.innerText = view.viewTitle()
this.$navViews.querySelectorAll('.atk-tab-item').forEach((e) => {
if (e.getAttribute('data-name') === viewName) {
e.classList.add('atk-active')
@@ -232,16 +231,16 @@ export default class SidebarRoot extends Component {
if (c.startsWith('atk-view-name-'))
this.$viewWrap.classList.remove(c)
})
this.$viewWrap.classList.add(`atk-view-name-${(view.constructor as typeof SidebarView).viewName}`)
this.$viewWrap.classList.add(`atk-view-name-${view.getName()}`)
}
private loadViewTabs(view: SidebarView) {
this.$navTabs.innerHTML = ''
Object.entries<string>(view.viewTabs).forEach(([tabName, label]) => {
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.viewActiveTab === tabName) $tab.classList.add('atk-active')
if (view.getActiveTab() === tabName) $tab.classList.add('atk-active')
// 切换 tab
$tab.onclick = () => {
@@ -1,27 +0,0 @@
import Context from 'artalk/src/context'
import * as Utils from 'artalk/src/lib/utils'
import Comment from 'artalk/src/components/comment'
import Component from './sidebar-component'
import { SidebarCtx } from './main'
export default class SidebarView extends Component {
static viewName = ''
static viewTitle = ''
static viewAdminOnly = false
viewTabs = {}
viewActiveTab = ''
protected $parent: HTMLElement
constructor(ctx: Context, sidebar: SidebarCtx, $parent: HTMLElement) {
super(ctx, sidebar)
this.$parent = $parent
this.$el = Utils.createElement(`<div class="atk-sidebar-view"></div>`)
}
mount() {}
switchTab(tab: string): boolean|void {}
}
@@ -1,68 +1,64 @@
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() {
// 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) => {
const pageURL = comment.data.page_url
comment.setOpenURL(`${pageURL}#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 = 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)
this.switchTab(this.activeTab)
}
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 = this.sidebar.curtSite
@@ -1,22 +1,17 @@
import Api from 'artalk/src/api'
import Context from 'artalk/src/context'
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 SidebarView from '../sidebar-view'
import PageList from '../admin/page-list'
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
@@ -28,7 +23,7 @@ export default class PagesView extends SidebarView {
this.$el.append(this.pageList.$el)
}
this.switchTab(this.viewActiveTab)
this.switchTab(this.activeTab)
}
switchTab(tab: string): boolean|void {
@@ -42,7 +37,7 @@ export default class PagesView extends SidebarView {
if (this.isFirstLoad) Ui.showLoading(this.$el)
else this.pagination.setLoading(true)
const data = await new Api(this.ctx).pageGet(this.sidebar.curtSite, 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 || [])
@@ -1,18 +1,12 @@
import Api from 'artalk/src/api'
import Context from 'artalk/src/context'
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() {
}
@@ -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,18 +1,13 @@
import Api from 'artalk/src/api'
import Context from 'artalk/src/context'
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
@@ -30,7 +25,7 @@ export default class SitesView extends SidebarView {
}
async reqSites() {
const sites = await new Api(this.ctx).siteGet()
const sites = await this.ctx.getApi().siteGet()
this.siteList.loadSites(sites)
}
}
@@ -1,22 +1,17 @@
import Api from 'artalk/src/api'
import Context from 'artalk/src/context'
import * as Utils from 'artalk/src/lib/utils'
import * as Ui from 'artalk/src/lib/ui'
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 TransferView extends SidebarView {
static viewName = 'transfer'
static viewTitle = '迁移'
static viewAdminOnly = true
protected readonly viewName = 'transfer'
public readonly viewAdminOnly = true
viewTitle() { return '迁移' }
viewTabs = {
protected tabs = {
'import': '导入',
'export': '导出',
}
viewActiveTab = 'import'
protected activeTab = 'import'
mount() {
this.switchTab('import')
@@ -281,7 +276,7 @@ export default class TransferView extends SidebarView {
Ui.showLoading(this.$el)
try {
const d = await new Api(this.ctx).export()
const d = await this.ctx.getApi().export()
this.download(`backup-${this.getYmdHisFilename()}.artrans`, d)
} catch (err: any) {
console.log(err)
@@ -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,6 +1,10 @@
@header-height: 60px;
@nav-height: 40px;
.artalk, .atk-layer-wrap {
font-family: @font-family;
}
.atk-sidebar {
@width: 430px;
position: fixed;
@@ -334,7 +338,7 @@
&[type="file"]::-webkit-file-upload-button {
background: transparent;
color: #000;
color: var(--at-color-font);
border: 0;
border-right: 2px solid #eee;
border-left: 0;
@@ -469,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;
+5 -3
View File
@@ -38,7 +38,9 @@
<script src="https://unpkg.com/vconsole@latest/dist/vconsole.min.js"></script>
<script>
// VConsole will be exported to `window.VConsole` by default.
var vConsole = new window.VConsole();
if (navigator.userAgentData.mobile) {
var vConsole = new window.VConsole();
}
</script>
</head>
<body>
@@ -65,8 +67,8 @@
el: '#comments',
pageKey: 'https://artalk.js.org/',
pageTitle: 'Artalk Home',
server: (import.meta.env.MODE === 'development') ? 'http://localhost:23366' : 'https://artalk.qwqaq.com',
site: 'ArtalkDemo',
server: (import.meta.env.DEV) ? 'http://localhost:23366' : 'https://artalk.qwqaq.com',
site: 'ArtalkDocs',
//useBackendConf: true,
});
+7 -5
View File
@@ -1,7 +1,7 @@
{
"name": "artalk",
"version": "2.2.10",
"backendMinVersion": "2.1.4",
"version": "2.3.4",
"backendMinVersion": "2.1.10",
"license": "LGPL-3.0",
"description": "A Selfhosted Comment System",
"keywords": [
@@ -25,7 +25,8 @@
"types": "./types/index.d.ts",
"scripts": {
"dev": "vite",
"build": "pnpm 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",
@@ -34,11 +35,12 @@
"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.17",
"abortcontroller-polyfill": "^1.7.3"
}
}
+31 -6
View File
@@ -1,8 +1,9 @@
import { CommentData, ListData, UserData, PageData, SiteData, NotifyData } from '~/types/artalk-data'
import ArtalkConfig from '~/types/artalk-config'
import Context from '../context'
import { Fetch, ToFormData, POST, GET } from './request'
import Context from '~/types/context'
import { Fetch, ToFormData, POST } from './request'
import * as Utils from '../lib/utils'
import 'abortcontroller-polyfill/dist/polyfill-patch-fetch'
export default class Api {
private ctx: Context
@@ -57,7 +58,7 @@ export default class Api {
}
/** 评论 · 修改 */
public async commentEdit(data: CommentData) {
public async commentEdit(data: Partial<CommentData>) {
const params: any = {
...data,
}
@@ -95,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 || '')
}
@@ -104,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,
@@ -127,6 +126,11 @@ export default class Api {
return (data || { is_login: false, is_admin: false }) as { is_login: boolean, is_admin: boolean }
}
/** 用户 · 注销 */
public async logout() {
return POST(this.ctx, `${this.baseURL}/logout`)
}
// ============================
// 页面 Page
// ============================
@@ -275,6 +279,25 @@ 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 = {
@@ -307,6 +330,8 @@ export default class Api {
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
}
}
+65 -92
View File
@@ -1,84 +1,61 @@
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
}
// 跨域请求携带 cookie (无需)
// init.credentials = 'include'
// 请求操作
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,
iframe: json.data.iframe,
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 请求 */
@@ -86,19 +63,20 @@ export async function POST<T>(ctx: Context, url: string, data?: {[key: string]:
const init: RequestInit = {
method: 'POST',
}
if (data) init.body = ToFormData(data)
data = { site_name: ctx.conf.site || '', ...(data || {}) } // 总是携带 site_name
init.body = ToFormData(data)
const json = await Fetch(ctx, url, init)
return ((json.data || {}) as T)
}
/** 公共 GET 请求 */
export async function GET<T>(ctx: Context, url: string, data?: {[key: string]: any}) {
const json = await Fetch(ctx, url + (data ? (`?${new URLSearchParams(data)}`) : ''), {
method: 'GET',
})
return ((json.data || {}) as T)
}
/** 公共 GET 请求 (无 GET 方式 API) */
// export async function GET<T>(ctx: Context, url: string, data?: {[key: string]: any}) {
// const json = await Fetch(ctx, url + (data ? (`?${new URLSearchParams(data)}`) : ''), {
// method: 'GET',
// })
// return ((json.data || {}) as T)
// }
/** 对象转 FormData */
export function ToFormData(object: {[key: string]: any}): FormData {
@@ -108,21 +86,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
}
+141 -142
View File
@@ -2,28 +2,32 @@ import './style/main.less'
import ArtalkConfig from '~/types/artalk-config'
import { EventPayloadMap, Handler } from '~/types/event'
import Context from './context'
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 Layer, { GetLayerWrap } from './components/layer'
import Api from './api'
import Layer 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 ctx!: Context
public $root!: HTMLElement
public checkerLauncher!: CheckerLauncher
@@ -31,79 +35,51 @@ export default class Artalk {
public list!: List
public sidebarLayer!: SidebarLayer
constructor (customConf: ArtalkConfig) {
// 配置
this.conf = Utils.mergeDeep(Artalk.defaults, customConf)
this.conf.server = this.conf.server.replace(/\/$/, '').replace(/\/api\/?$/, '')
/** Plugins (in global scope) */
protected static Plugins: ArtalkPlug[] = [ Stat.PvCountWidget ]
// 默认 pageKey
if (!this.conf.pageKey) {
// @link http://bl.ocks.org/abernier/3070589
this.conf.pageKey = `${window.location.pathname}`
}
/** Plugins (in a instance scope) */
protected instancePlugins: ArtalkPlug[] = []
// 默认 pageTitle
if (!this.conf.pageTitle) {
this.conf.pageTitle = `${document.title}`
}
constructor(customConf: Partial<ArtalkConfig>) {
/* 初始化基本配置 */
this.conf = Artalk.HandelBaseConf(customConf)
if (this.conf.el instanceof HTMLElement) this.$root = this.conf.el
// 列表显示模式
if (this.conf.nestMax && this.conf.nestMax <= 1) {
this.conf.flatMode = true
}
/* 初始化 Context */
this.ctx = new ConcreteContext(this.conf, this.$root)
// 装载元素
if (!!this.conf.el && this.conf.el instanceof HTMLElement) {
this.$root = this.conf.el
} else {
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.')
}
}
// @ts-ignore 远程加载引用后端的配置
if (this.conf.useBackendConf) return this.loadConfRemoteAndInitComponents()
// Context 初始化
this.ctx = new Context(this.$root, this.conf)
// 界面初始化
this.$root.classList.add('artalk')
this.$root.innerHTML = ''
// 初始化组件
if (this.conf.useBackendConf) {
// 复用后端的配置
// @ts-ignore
return (async () => {
await this.loadConfRemote()
this.initCore()
return this // Promise<Artalk>
})()
}
this.initCore()
/* 初始化组件 */
this.initComponents()
}
private initCore() {
// 组件初始化
/** 组件初始化 */
private initComponents() {
this.initLocale()
this.initLayer()
this.initDarkMode()
Utils.initMarked(this.ctx)
// CheckerLauncher
this.checkerLauncher = new CheckerLauncher(this.ctx)
Utils.initMarked(this.ctx) // 初始化 marked
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)
// 评论获取
@@ -112,29 +88,66 @@ export default class Artalk {
// 事件绑定初始化
this.initEventBind()
// 其他
this.initPV()
// 插件初始化
// 插件初始化 (global scope)
Artalk.Plugins.forEach(plugin => {
if (typeof plugin === 'function') {
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 (new Api(this.ctx)).conf()
} catch (err) { console.error("配置远程获取失败", err) }
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', () => {
@@ -142,89 +155,49 @@ export default class Artalk {
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'
}
}
}
/** Layer 初始化 */
initLayer() {
private initLayer() {
// 记录页面原始 Styles
Layer.BodyOrgOverflow = document.body.style.overflow
Layer.BodyOrgPaddingRight = document.body.style.paddingRight
}
/** 暗黑模式 · 初始化 */
public initDarkMode() {
const darkModeClassName = 'atk-dark-mode'
if (this.conf.darkMode) {
this.$root.classList.add(darkModeClassName)
/** 暗黑模式初始化 */
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.$root.classList.remove(darkModeClassName)
this.setDarkMode(this.conf.darkMode || false)
}
// for Layer
const { $wrap: $layerWrap } = GetLayerWrap(this.ctx)
if ($layerWrap) {
if (this.conf.darkMode) {
$layerWrap.classList.add(darkModeClassName)
} else {
$layerWrap.classList.remove(darkModeClassName)
}
}
}
/** 暗黑模式 · 设定 */
public setDarkMode(darkMode: boolean) {
this.ctx.conf.darkMode = darkMode
this.ctx.trigger('conf-updated')
this.initDarkMode()
}
/** PV */
public async initPV() {
const pvNum = await new Api(this.ctx).pv()
if (Number.isNaN(Number(pvNum)))
return
if (!this.conf.pvEl || !document.querySelector(this.conf.pvEl))
return
const $pv = document.querySelector<HTMLElement>(this.conf.pvEl)!
// $pv.innerText = '-' // 默认占位符
$pv.innerText = String(pvNum)
}
/** 监听事件 */
@@ -242,11 +215,37 @@ export default class Artalk {
this.ctx.trigger(name, payload, 'external')
}
/** Plugins */
protected static Plugins: ((ctx: Context) => void)[] = []
/** 重新加载 */
public reload() {
this.ctx.listReload()
}
/** Enable Plugin */
public static Use(plugin: ((ctx: Context) => void)) {
/** 设置暗黑模式 */
public setDarkMode(darkMode: boolean) {
this.ctx.setDarkMode(darkMode)
}
/** Use Plugin (specific instance) */
public use(plugin: ArtalkPlug) {
this.instancePlugins.push(plugin)
if (typeof plugin === 'function') plugin(this.ctx)
}
/** Use Plugin (static method for global scope) */
public static use(plugin: ArtalkPlug) {
this.Plugins.push(plugin)
}
/** @deprecated Please replace it with lowercase function name `use(...)`. */
public static Use(plugin: ArtalkPlug) {
this.use(plugin)
console.warn('`Use(...)` is deprecated, replace it with lowercase `use(...)`.')
}
/** 装载数量统计元素 */
public static LoadCountWidget(customConf: Partial<ArtalkConfig>) {
const conf = this.HandelBaseConf(customConf)
const ctx = new ConcreteContext(conf)
Stat.initCountWidget({ ctx, pvAdd: false })
}
}
+86
View File
@@ -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')) // 强制触发事件
}
}
@@ -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">
+191
View File
@@ -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
}
}
+3
View File
@@ -0,0 +1,3 @@
import Comment from './comment'
export default Comment
+435
View File
@@ -0,0 +1,435 @@
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 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)
})
// 编辑按钮
const editBtn = new ActionBtn(this.ctx, {
text: this.ctx.$t('edit'),
adminOnly: true
})
editBtn.appendTo(this.$actions)
editBtn.setClick(() => {
this.ctx.editComment(this.data, this.$el)
})
// 删除按钮
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)
})
}
/** 内容限高检测 */
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)
}
}
+6 -3
View File
@@ -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()
-605
View File
@@ -1,605 +0,0 @@
import '../style/comment.less'
import { CommentData } from '~/types/artalk-data'
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 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 $headerNick!: HTMLElement
public $headerBadge?: 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 nestCurt: number
private nestMax: number // 最大嵌套层数
private children: Comment[] = []
public flatMode: boolean = false
public replyTo?: CommentData // 回复对象
public $replyTo?: HTMLElement // 回复评论内容 (平铺下显示)
public $replyAt?: HTMLElement // 回复 AT(层级嵌套下显示)
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.nestMax = ctx.conf.nestMax || 3
this.data = { ...data }
this.data.date = this.data.date.replace(/-/g, '/') // 解决 Safari 日期解析 NaN 问题
this.parent = null
this.nestCurt = 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.renderReplyAt()
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() {
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.$headerBadge = this.$el.querySelector<HTMLElement>('.atk-badge')!
if (this.data.badge_name) {
this.$headerBadge.innerText = this.data.badge_name
if (this.data.badge_color)
this.$headerBadge.style.backgroundColor = this.data.badge_color
} else {
this.$headerBadge.remove()
this.$headerBadge = undefined
}
if (this.data.is_pinned) {
const $pinnedBadge = Utils.createElement(`<span class="atk-item atk-pinned-badge">置顶</span>`) // 置顶徽章
this.$headerNick.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 = '查看内容'
}
})
}
// 层级嵌套模式显示 At
private renderReplyAt() {
if (this.flatMode || this.data.rid === 0) return // not 平铺模式 或 根评论
if (this.$replyAt) return // not 关闭显示 或 已经显示
if (!this.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.replyTo.nick}`
this.$replyAt.onclick = () => { this.goToReplyComment() }
const $after = this.$headerBadge || this.$headerNick
$after.insertAdjacentElement('afterend', this.$replyAt)
}
// 回复的对象
private renderReplyTo() {
if (!this.flatMode) return // 仅平铺模式显示
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>`)
const $nick = this.$replyTo.querySelector<HTMLElement>('.atk-nick')!
$nick.innerText = `@${this.replyTo.nick}`
$nick.onclick = () => { this.goToReplyComment() }
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)
}
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')) // 强制触发事件
}
// 待审核状态
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.data.rid === 0
}
getChildren() {
return this.children
}
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.playFadeInAnim()
// 内容限高
childC.checkHeightLimitArea('content')
}
getChildrenEl(): HTMLElement {
if (!this.$children) {
// console.log(this.nestCurt)
if (this.nestCurt < this.nestMax) {
this.$children = Utils.createElement('<div class="atk-comment-children"></div>')
this.$main.append(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)
}
}
+7 -3
View File
@@ -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 * as Utils from '~/src/lib/utils'
import Editor from '../editor'
import EditorPlug from './editor-plug'
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()
}
}
}
-604
View File
@@ -1,604 +0,0 @@
import '../style/editor.less'
import { CommentData } from '~/types/artalk-data'
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 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 $imgUploadBtn?: HTMLElement
public $imgUploadInput?: HTMLInputElement
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()))
this.ctx.on('conf-updated', () => (this.refreshUploadBtn()))
}
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.onHeaderInput(field, inputEl))
}
})
// Link URL 自动补全协议
const $linkInput = this.getInputEl('link')
if ($linkInput) {
$linkInput.addEventListener('change', () => {
const link = $linkInput.value.trim()
if (!!link && !/^(http|https):\/\//.test(link)) {
$linkInput.value = `https://${link}`
this.user.data.link = $linkInput.value
this.saveUser()
}
})
}
}
getInputEl (field: string) {
const inputEl = this.$header.querySelector<HTMLInputElement>(`[name="${field}"]`)
return inputEl
}
queryUserInfo = {
timeout: <number|null>null,
abortFunc: <(() => void)|null>null
}
/** header 输入框内容变化事件 */
onHeaderInput(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" data-plug-name="${PlugObj.Name}">${PlugObj.BtnHTML}</span>`)
this.$plugBtnWrap.appendChild(btnElem)
// 表情包插件预加载
if (PlugObj.Name === 'emoticons') {
const emoPlug = new PlugObj(this) as EmoticonsPlug
this.plugList[PlugObj.Name] = emoPlug
window.setTimeout(() => {
emoPlug.loadEmoticonsData()
}, 1000) // 延迟 1s 加载
}
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')
})
})
this.initImgUpload()
}
/** 关闭编辑器插件 */
closePlug () {
this.$plugWrap.innerHTML = ''
this.$plugWrap.style.display = 'none'
this.openedPlugName = null
}
/** 允许的图片格式 */
allowImgExts = ['png', 'jpg', 'jpeg', 'gif', 'bmp', 'svg', 'webp']
/** 初始化图片上传功能 */
initImgUpload() {
this.$imgUploadBtn = Utils.createElement(`<span class="atk-plug-btn">图片</span>`)
this.$plugBtnWrap.querySelector('[data-plug-name="preview"]')!.before(this.$imgUploadBtn) // 显示在预览图标之前
this.$imgUploadInput = document.createElement('input')
this.$imgUploadInput.type = 'file'
this.$imgUploadInput.style.display = 'none'
this.$imgUploadInput.accept = this.allowImgExts.map(o => `.${o}`).join(',')
this.$imgUploadBtn.after(this.$imgUploadInput)
// 按钮点击
this.$imgUploadBtn.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() // 显示选择图片对话框
}
// 统一从 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.$textarea.addEventListener('dragover', (evt) => {
evt.stopPropagation()
evt.preventDefault()
})
this.$textarea.addEventListener('drop', (evt) => {
const files = evt.dataTransfer?.files
if (files?.length) {
evt.preventDefault()
uploadFromFileList(files)
}
})
// 粘贴图片
this.$textarea.addEventListener('paste', (evt) => {
const files = evt.clipboardData?.files
if (files?.length) {
evt.preventDefault()
uploadFromFileList(files)
}
})
}
/** 刷新图片上传按钮 */
refreshUploadBtn() {
if (!this.$imgUploadBtn) return
if (!this.ctx.conf.imgUpload) {
this.$imgUploadBtn.setAttribute('atk-only-admin-show', '')
this.ctx.trigger('check-admin-show-el')
}
}
async uploadImg(file: File) {
const fileExt = /[^.]+$/.exec(file.name)
if (!fileExt || !this.allowImgExts.includes(fileExt[0])) return
// 未登录提示
if (!this.ctx.user.checkHasBasicUserInfo()) {
this.showNotify('填入你的名字邮箱才能上传哦', 'w')
return
}
// 插入图片前换一行
let insertPrefix = '\n'
if (this.$textarea.value.trim() === '') insertPrefix = ''
// 插入占位加载文字
const uploadPlaceholderTxt = `${insertPrefix}![](Uploading ${file.name}...)`
this.insertContent(uploadPlaceholderTxt)
// 上传图片
let resp: any
try {
resp = await new Api(this.ctx).imgUpload(file)
} catch (err: any) {
console.error(err)
this.showNotify(`图片上传失败,${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.setContent(this.$textarea.value.replace(uploadPlaceholderTxt, `${insertPrefix}![](${imgURL})`))
} else {
// 上传失败删除加载文字
this.setContent(this.$textarea.value.replace(uploadPlaceholderTxt, ''))
}
}
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()
}
// 延迟执行防止无效
window.setTimeout(() => {
this.adjustTextareaHeight()
}, 80)
}
clearEditor () {
this.setContent('')
this.cancelReply()
}
/** 获取最终用于 submit 的数据 */
getFinalContent () {
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.getFinalContent())
}
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.getFinalContent().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.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.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)
this.$el.classList.add('atk-fade-in') // 添加渐入动画
}
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()
}
initRemoteEmoticons () {
}
}
@@ -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>
@@ -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后错误提示复原
}
+243 -13
View File
@@ -1,46 +1,276 @@
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 updateComment(commentData: CommentData): void {
this.list.updateComment(commentData)
}
public replyComment(commentData: CommentData, $comment: HTMLElement, scroll?: boolean): void {
this.editor.setReply(commentData, $comment, scroll)
}
public cancelReplyComment(): void {
this.editor.cancelReply()
}
public editComment(commentData: CommentData, $comment: HTMLElement): void {
this.editor.setEditComment(commentData, $comment)
}
public cancelEditComment(): void {
this.editor.cancelEditComment()
}
public updateNotifies(notifies: NotifyData[]): void {
this.list.updateUnread(notifies)
}
/* 评论列表 */
public listReload(): void {
this.list.reload()
}
public reload(): void {
this.listReload()
}
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))
}
public markedInstance!: typeof libMarked
public markedReplacers: ((raw: string) => string)[] = []
/* 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
}
public setDarkMode(darkMode: boolean): void {
const darkModeClassName = 'atk-dark-mode'
this.conf.darkMode = darkMode
this.trigger('conf-updated')
if (this.conf.darkMode) {
this.$root.classList.add(darkModeClassName)
} else {
this.$root.classList.remove(darkModeClassName)
}
// for Layer
const { $wrap: $layerWrap } = GetLayerWrap(this)
if ($layerWrap) {
if (this.conf.darkMode) {
$layerWrap.classList.add(darkModeClassName)
} else {
$layerWrap.classList.remove(darkModeClassName)
}
}
}
}
+19 -6
View File
@@ -1,26 +1,31 @@
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',
nestMax: 2,
gravatar: {
default: 'mp',
@@ -42,6 +47,14 @@ const defaults: ArtalkConfig = {
reqTimeout: 15000,
versionCheck: true,
useBackendConf: false,
locale: 'zh-CN',
}
if (ARTALK_LITE) {
defaults.vote = false
defaults.uaBadge = false
defaults.emoticons = false
}
export default defaults
+18
View File
@@ -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>
+514
View File
@@ -0,0 +1,514 @@
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
// Editor 的不同状态
private isTraveling = false
/** 回复评论 */
private replyComment: CommentData|null = null
private $sendReply: HTMLElement|null = null
public get isReplyMode() { return this.replyComment !== null }
/** 编辑评论 */
private editComment: CommentData|null = null
private $editCancelBtn: HTMLElement|null = null
public get isEditMode() { return this.editComment !== null }
/** 启用的插件 */
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) {
if (this.isEditMode) return // 评论编辑模式,不修改个人信息
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 refreshSendBtnText() {
if (this.isEditMode) this.$submitBtn.innerText = this.$t('save')
else this.$submitBtn.innerText = this.ctx.conf.sendBtn || this.$t('send')
}
private initSubmitBtn() {
this.refreshSendBtnText()
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
}
}
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.isEditMode) this.cancelEditComment()
if (this.isReplyMode) 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 setEditComment(commentData: CommentData, $comment: HTMLElement) {
if (this.isEditMode) this.cancelEditComment()
if (this.isReplyMode) this.cancelReply()
if (this.$editCancelBtn === null) {
this.$editCancelBtn = Utils.createElement(`<div class="atk-send-reply">${this.$t('editCancel')}<span class="atk-cancel">×</span></div>`);
this.$editCancelBtn.onclick = () => {
this.cancelEditComment()
}
this.$textareaWrap.append(this.$editCancelBtn)
}
this.editComment = commentData
this.$header.style.display = 'none' // TODO 暂时隐藏
this.travel($comment)
this.$nick.value = commentData.nick
this.$email.value = commentData.email || ''
this.$link.value = commentData.link
this.setContent(commentData.content)
this.$textarea.focus()
this.refreshSendBtnText()
}
/** 取消编辑评论 */
public cancelEditComment() {
if (this.$editCancelBtn !== null) {
this.$editCancelBtn.remove()
this.$editCancelBtn = null
}
this.editComment = null
this.travelBack()
this.$nick.value = this.user.data.nick
this.$email.value = this.user.data.email
this.$link.value = this.user.data.link
this.setContent('')
this.refreshSendBtnText()
this.$header.style.display = '' // TODO
}
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()
if (!this.isEditMode) {
await this.submitAdd()
} else {
await this.submitEdit()
}
this.hideLoading()
}
/** 创建评论 */
public async submitAdd() {
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.setContent('')
this.cancelReply()
this.ctx.trigger('editor-submitted')
} catch (err: any) {
console.error(err)
this.showNotify(`${this.$t('commentFail')},${err.msg || String(err)}`, 'e')
}
}
/** 修改评论 */
public async submitEdit() {
try {
const saveData = {
content: this.getFinalContent(),
nick: this.$nick.value,
email: this.$email.value,
link: this.$link.value,
}
const nComment = await this.ctx.getApi().commentEdit({
...this.editComment, ...saveData
})
this.ctx.updateComment(nComment)
// 复原编辑器
this.setContent('')
this.cancelEditComment()
this.ctx.trigger('editor-submitted')
} catch (err: any) {
console.error(err)
this.showNotify(`${this.$t('commentFail')},${err.msg || String(err)}`, 'e')
}
}
/** 关闭评论 */
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
}
}
+3
View File
@@ -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
@@ -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;
@@ -14,24 +14,53 @@ 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
public loadingTask: Promise<void>|null = null
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'))
// 表情包预加载
window.setTimeout(() => {
this.loadEmoticonsData()
}, 1000) // 延迟 1s 加载
}
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
async loadEmoticonsData() {
public async loadEmoticonsData() {
if (this.isListLoaded) return
if (this.loadingTask !== null) {
await this.loadingTask
@@ -40,23 +69,23 @@ export default class EmoticonsPlug extends EditorPlug {
// 数据处理
this.loadingTask = (async () => {
Ui.showLoading(this.$el)
Ui.showLoading(this.$panel)
this.emoticons = await this.handleData(this.ctx.conf.emoticons)
Ui.hideLoading(this.$el)
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 []
}
@@ -105,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 {
@@ -113,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}`
@@ -129,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 => {
@@ -143,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))
@@ -152,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: [] }
@@ -171,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>`)
@@ -208,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)) {
@@ -235,47 +265,19 @@ export default class EmoticonsPlug extends EditorPlug {
}
})
this.$grpSwitcher.querySelectorAll('span.active').forEach(item => item.classList.remove('active'))
this.$grpSwitcher.querySelector(`span[data-index="${index}"]`)?.classList.add('active')
this.$grpSwitcher?.querySelectorAll('span.active').forEach(item => item.classList.remove('active'))
this.$grpSwitcher?.querySelector(`span[data-index="${index}"]`)?.classList.add('active')
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 () {
;(async () => {
await this.loadEmoticonsData()
// 初始化元素
if (!this.isImgLoaded) {
this.initEmoticonsList()
this.isImgLoaded = true
}
// 延迟执行,防止无法读取高度
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: () => {
}
})
}
}
@@ -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}![](Uploading ${file.name}...)`
this.editor.insertContent(uploadPlaceholderTxt)
// 上传图片
let resp: any
try {
if (!this.ctx.conf.imgUploader) {
// 使用 ArtalkGo 进行图片上传
resp = await this.ctx.getApi().imgUpload(file)
} else {
// 使用自定义的图片上传器
resp = {img_url: 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}![](${imgURL})`))
} else {
// 上传失败删除加载文字
this.editor.setContent(this.editor.$textarea.value.replace(uploadPlaceholderTxt, ''))
}
}
}
+81
View File
@@ -0,0 +1,81 @@
export default {
/* Editor */
placeholder: 'Leave a comment',
noComment: 'No Comment',
send: 'Send',
save: 'Save',
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.',
edit: 'Edit',
editCancel: 'Cancel Edit',
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',
}
+21
View File
@@ -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': {},
}
+85
View File
@@ -0,0 +1,85 @@
import { I18n } from '.'
const zhCN: I18n = {
/* Editor */
placeholder: '键入内容...',
noComment: '「此时无声胜有声」',
send: '发送评论',
save: '保存评论',
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: '审核中,仅本人可见。',
edit: '编辑',
editCancel: '取消编辑',
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
+4
View File
@@ -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'
@@ -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'
@@ -126,7 +126,7 @@ export default class Layer extends Component {
}
/** 销毁 - 无动画 */
disposeNow () {
disposeNow() {
this.$el.remove()
this.pageBodyScrollBarShow()
// this.$el dispose
@@ -134,21 +134,21 @@ export default class Layer extends Component {
}
/** 销毁 */
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(
@@ -1,13 +1,15 @@
import '../style/sidebar-layer.less'
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'
import { SidebarShowPayload } from '~/types/event'
import SidebarHTML from './html/sidebar-layer.html?raw'
import SidebarHTML from './sidebar-layer.html?raw'
import Layer from './layer'
import Api from '../api'
export interface SidebarShowPayload {
view?: 'comments'|'sites'|'pages'|'transfer'
}
export default class SidebarLayer extends Component {
public layer?: Layer
@@ -29,15 +31,13 @@ export default class SidebarLayer extends Component {
}
// event
this.ctx.on('sidebar-show', (conf) => (this.show(conf || {})))
this.ctx.on('sidebar-hide', () => (this.hide()))
this.ctx.on('user-changed', () => { this.firstShow = true })
}
private firstShow = true
/** 显示 */
public async show(conf: SidebarShowPayload) {
public async show(conf: SidebarShowPayload = {}) {
this.$el.style.transform = '' // 动画清除,防止二次打开失效
// 获取 Layer
@@ -46,7 +46,7 @@ export default class SidebarLayer extends Component {
this.layer.afterHide = () => {
// 防止评论框被吞
if (this.ctx.conf.editorTravel === true) {
this.ctx.trigger('editor-travel-back')
this.ctx.editorTravelBack()
}
}
}
@@ -62,12 +62,12 @@ export default class SidebarLayer extends Component {
// 管理员身份验证 (若身份失效,弹出验证窗口)
;(async () => {
const resp = await new Api(this.ctx).loginStatus()
const resp = await this.ctx.getApi().loginStatus()
if (resp.is_admin && !resp.is_login) {
this.layer?.hide()
this.firstShow = true
this.ctx.trigger('checker-admin', {
this.ctx.checkAdmin({
onSuccess: () => {
setTimeout(() => {
this.show(conf)
@@ -79,7 +79,7 @@ export default class SidebarLayer extends Component {
})()
// 清空 unread
this.ctx.trigger('unread-update', { notifies: [] })
this.ctx.updateNotifies([])
// 第一次加载
if (this.firstShow) {
@@ -87,7 +87,7 @@ export default class SidebarLayer extends Component {
this.$iframe = Utils.createElement<HTMLIFrameElement>('<iframe></iframe>')
// 准备 Iframe 参数
const baseURL = (import.meta.env.MODE === 'development') ? 'http://localhost:23367/'
const baseURL = (import.meta.env.DEV) ? 'http://localhost:23367/'
: Utils.getURLBasedOnApi(this.ctx, '/sidebar/')
const query: any = {
@@ -115,6 +115,8 @@ export default class SidebarLayer extends Component {
if (!this.conf.darkMode && isIframeSrcDarkMode)
this.iframeLoad(this.$iframe!.src.replace('&darkMode=1', ''))
}
this.ctx.trigger('sidebar-show')
}
/** 隐藏 */
@@ -123,9 +125,11 @@ export default class SidebarLayer extends Component {
this.$el.style.transform = ''
this.layer?.hide()
this.ctx.trigger('sidebar-hide')
}
public iframeLoad(src: string) {
private iframeLoad(src: string) {
if (!this.$iframe) return
this.$iframe.src = src
@@ -135,39 +139,5 @@ export default class SidebarLayer extends Component {
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 后开始检测
}
}
@@ -1,4 +1,3 @@
import Api from '@/api'
import * as Utils from '../utils'
import { Checker } from '.'
@@ -12,19 +11,20 @@ const AdminChecker: Checker = {
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(that, ctx) {
return Utils.createElement('<span>敲入密码来验证管理员身份:</span>')
return Utils.createElement(`<span>${that.ctx.$t('adminCheck')}</span>`)
},
onSuccess(that, ctx, userToken, inputVal, formEl) {
that.ctx.user.data.isAdmin = true
that.ctx.user.data.token = userToken
that.ctx.user.save()
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, ctx, err, inputVal, formEl) {}
@@ -1,11 +1,10 @@
import Api from '@/api'
import * as Utils from '../utils'
import * as Ui from '../ui'
import { Checker } from '.'
const CaptchaChecker: Checker = {
request(that, ctx, inputVal) {
return new Api(that.ctx).captchaCheck(inputVal)
return that.ctx.getApi().captchaCheck(inputVal)
},
body(that, ctx) {
@@ -35,7 +34,7 @@ const CaptchaChecker: Checker = {
if (stop) return
let isPass = false
try {
const resp = await new Api(that.ctx).captchaStatus()
const resp = await that.ctx.getApi().captchaStatus()
isPass = resp.is_pass
} catch { isPass = false }
if (isPass) {
@@ -55,18 +54,18 @@ const CaptchaChecker: Checker = {
// 图片验证方式
const elem = Utils.createElement(
`<span><img class="atk-captcha-img" src="${that.captchaConf.imgData || ''}" 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
+22 -17
View File
@@ -1,12 +1,22 @@
import Context from '@/context'
import Layer from '@/components/layer'
import Context from '~/types/context'
import Dialog from '@/components/dialog'
import { CheckerPayload } from '~/types/event'
import Layer from '@/layer'
import * as Utils from '../utils'
import * as Ui from '../ui'
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 发射台
*/
@@ -18,22 +28,17 @@ export default class CheckerLauncher {
constructor(ctx: Context) {
this.ctx = ctx
this.initEventBind()
}
/** 初始化事件绑定 */
public initEventBind() {
this.ctx.on('checker-captcha', (conf) => {
if (conf.imgData) this.captchaConf.imgData = conf.imgData
if (conf.iframe) this.captchaConf.iframe = conf.iframe
public checkCaptcha(payload: CheckerCaptchaPayload) {
this.captchaConf.imgData = payload.imgData
this.captchaConf.iframe = payload.iframe
this.fire(CaptchaChecker, conf)
})
this.fire(CaptchaChecker, payload)
}
this.ctx.on('checker-admin', (conf) => {
this.fire(AdminChecker, conf)
})
public checkAdmin(payload: CheckerPayload) {
this.fire(AdminChecker, payload)
}
public fire(checker: Checker, payload: CheckerPayload) {
@@ -87,7 +92,7 @@ export default class CheckerLauncher {
}
let btnTextOrg: string | undefined
const dialog = new Dialog(formEl)
const dialog = new Dialog(this.ctx, formEl)
// 确认按钮
dialog.setYes((btnEl) => {
@@ -104,7 +109,7 @@ export default class CheckerLauncher {
btnEl.classList.remove('error')
}
btnEl.innerText = '加载中...'
btnEl.innerText = `${this.ctx.$t('loading')}...`
// 发送请求
checker
+7 -2
View File
@@ -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)
}
}
+63
View File
@@ -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)}`
})
}
+6 -12
View File
@@ -1,11 +1,9 @@
import * as Utils from './utils'
import Context from '../context'
/** 显示加载 */
export function showLoading(parentElem: HTMLElement|Context, conf?: { transparentBg?: boolean }) {
if (parentElem instanceof Context) parentElem = parentElem.$root
let $loading = parentElem.querySelector<HTMLElement>('.atk-loading')
export function showLoading(parentElem: HTMLElement, conf?: { transparentBg?: boolean }) {
// Use :scope https://developer.mozilla.org/en-US/docs/Web/CSS/:scope
let $loading = parentElem.querySelector<HTMLElement>(':scope > .atk-loading')
if (!$loading) {
$loading = Utils.createElement(
`<div class="atk-loading atk-fade-in" style="display: none;">
@@ -29,10 +27,8 @@ export function showLoading(parentElem: HTMLElement|Context, conf?: { transparen
}
/** 隐藏加载 */
export function hideLoading(parentElem: HTMLElement|Context) {
if (parentElem instanceof Context) parentElem = parentElem.$root
const $loading = parentElem.querySelector<HTMLElement>('.atk-loading')
export function hideLoading(parentElem: HTMLElement) {
const $loading = parentElem.querySelector<HTMLElement>(':scope > .atk-loading')
if ($loading) $loading.style.display = 'none'
}
@@ -133,9 +129,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()
+20 -3
View File
@@ -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
}
}
+23 -9
View File
@@ -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) {
@@ -142,6 +142,8 @@ export function versionCompare(a: string, b: string) {
/** 初始化 marked */
export function initMarked(ctx: Context) {
try { if (!libMarked.name) return } catch { return }
const renderer = new libMarked.Renderer()
const orgLinkRenderer = renderer.link
renderer.link = (href, title, text) => {
@@ -186,9 +188,21 @@ export function initMarked(ctx: Context) {
/** 解析 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(ctx.markedInstance.parse(src), {
let dest = insane(markedContent, {
allowedClasses: {},
allowedSchemes: ['http', 'https', 'mailto'],
allowedTags: [
+3
View File
@@ -0,0 +1,3 @@
import List from './list'
export default List
@@ -1,31 +1,27 @@
import { ListData, CommentData, NotifyData, ApiVersionData } from '~/types/artalk-data'
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 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 commentList: Comment[] = [] // Note: 无层级结构 + 无须排列
protected get commentDataList() { return this.commentList.map(c => c.data) }
protected data?: ListData
protected isLoading: boolean = false
public noCommentText = '无内容' // 无评论时显示
public noCommentText: string // 无评论时显示
/** 平铺模式 */
public flatMode = false
/** 嵌套模式 */
public nestSortBy: ListNest.SortByType = 'DATE_DESC'
public nestSortBy!: ListNest.SortByType
/** 分页 */
public pageMode: 'pagination'|'read-more' = 'pagination'
@@ -56,18 +52,30 @@ export default class ListLite extends Component {
this.$commentsWrap = this.$el.querySelector('.atk-list-comments-wrap')!
// 评论为空时显示字符
if (ctx.conf.noComment) this.noCommentText = ctx.conf.noComment
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
}
/** 评论获取 */
@@ -90,15 +98,15 @@ 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, e.data)
throw e
@@ -122,14 +130,14 @@ 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
// 版本检测
const feMinVersion = data.api_version?.fe_min_version || '0.0.0'
if (this.ctx.conf.versionCheck && this.versionCheck('前端', feMinVersion, ARTALK_VERSION)) return
if (this.ctx.conf.versionCheck && this.versionCheck('后端', backendMinVersion, data.api_version?.version)) return
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") {
@@ -145,8 +153,8 @@ 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)
@@ -176,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) // 解除原有
@@ -207,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)
@@ -234,14 +243,14 @@ export default class ListLite extends Component {
// 加载更多按钮显示错误
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)
@@ -261,9 +270,9 @@ export default class ListLite extends Component {
sidebarView = `sites|${JSON.stringify(viewLoadParam)}`
}
adminBtn.onclick = () => (this.ctx.trigger('sidebar-show', {
view: sidebarView
}))
adminBtn.onclick = () => this.ctx.showSidebar({
view: sidebarView as any
})
Ui.setError(this.$el, $err)
}
@@ -271,7 +280,7 @@ export default class ListLite extends Component {
/** 刷新界面 */
public refreshUI() {
// 无评论
const isNoComment = this.commentList.length <= 0
const isNoComment = this.ctx.getCommentList().length <= 0
let $noComment = this.$commentsWrap.querySelector<HTMLElement>('.atk-list-no-comment')
if (isNoComment) {
@@ -285,25 +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(cData: CommentData, ctxData?: CommentData[]) {
if (!ctxData) ctxData = this.commentDataList
if (!ctxData) ctxData = this.ctx.getCommentDataList()
const comment = new Comment(this.ctx, cData)
comment.flatMode = this.flatMode
comment.afterRender = () => {
if (this.renderComment) this.renderComment(comment)
}
comment.onDelete = (c) => {
this.deleteComment(c)
this.refreshUI()
}
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.replyTo = (cData.rid ? ctxData.find(c => c.id === cData.rid) : undefined)
// 渲染元素
comment.render()
// 放入 comment 总表中
this.ctx.getCommentList().push(comment)
return comment
}
@@ -325,14 +344,10 @@ export default class ListLite extends Component {
const rootNodes = ListNest.makeNestCommentNodeList(srcData, this.nestSortBy, this.conf.nestMax)
rootNodes.forEach((rootNode: ListNest.CommentNode) => {
const rootC = this.createComment(rootNode.comment, srcData)
rootC.render()
// 显示并播放渐入动画
this.$commentsWrap.appendChild(rootC.getEl())
rootC.playFadeInAnim()
// 评论放入 comments 总表中
this.commentList.push(rootC)
rootC.getRender().playFadeAnim()
// 加载子评论
const that = this
@@ -340,20 +355,17 @@ export default class ListLite extends Component {
parentNode.children.forEach((node: ListNest.CommentNode) => {
const childD = node.comment
const childC = that.createComment(childD, srcData)
childC.render()
// 插入到父评论中
parentC.putChild(childC)
that.commentList.push(childC)
// 递归加载子评论
loadChildren(childC, node)
})
})(rootC, rootNode)
// 限高检测
rootC.checkHeightLimit()
rootC.getRender().checkHeightLimit()
})
}
@@ -361,21 +373,17 @@ export default class ListLite extends Component {
private putCommentFlatMode(cData: CommentData, ctxData: CommentData[], insertMode: 'append'|'prepend') {
if (cData.is_collapsed) cData.is_allow_reply = false
const comment = this.createComment(cData, ctxData)
comment.render()
// 将评论导入 comments 总表中
this.commentList.push(comment)
// 可见评论添加到界面
// 注:不可见评论用于显示 “引用内容”
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
}
@@ -388,30 +396,27 @@ export default class ListLite extends Component {
if (commentData.rid === 0) {
// root评论 新增
comment.render()
this.$commentsWrap.prepend(comment.getEl())
this.commentList.push(comment)
} else {
// 子评论 新增
const parent = this.findComment(commentData.rid)
const parent = this.ctx.findComment(commentData.rid)
if (parent) {
comment.render()
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.commentDataList, 'prepend')
const comment = this.putCommentFlatMode(commentData, this.ctx.getCommentDataList(), 'prepend')
Ui.scrollIntoView(comment.getEl()) // 滚动到可见
}
@@ -420,36 +425,16 @@ export default class ListLite extends Component {
// 评论新增后
this.refreshUI()
this.ctx.trigger('comments-loaded')
this.ctx.trigger('list-loaded')
this.ctx.trigger('list-inserted', commentData)
}
/** 查找评论项 */
protected findComment(id: number): Comment|undefined {
return this.commentList.find(c => c.data.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 = findComment
} else comment = _comment
comment.getEl().remove()
this.commentList.splice(this.commentList.indexOf(comment), 1)
if (this.data) this.data.total -= 1 // 评论数减 1
this.refreshUI()
}
/** 清空所有评论 */
public clearAllComments() {
this.$commentsWrap.innerHTML = ''
this.data = undefined
this.commentList = []
/** 更新评论 */
public updateComment(commentData: CommentData) {
const comment = this.ctx.findComment(commentData.id)
if (comment) {
comment.setData(commentData)
}
}
/** 更新未读数据 */
@@ -458,33 +443,31 @@ export default class ListLite extends Component {
// 高亮评论
if (this.unreadHighlight === true) {
this.commentList.forEach((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(name: '前端'|'后端', needVersion: string, curtVersion: string): boolean {
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 ${name}版本已过时,请更新以获得完整体验<br/>`
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);">当前${name}版本 ${curtVersion},需求版本 >= ${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 = () => {
@@ -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,11 +1,10 @@
import '../style/list.less'
import { ListData } from '~/types/artalk-data'
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'
export default class List extends ListLite {
@@ -13,6 +12,7 @@ export default class List extends ListLite {
private $openSidebarBtn!: HTMLElement
private $unreadBadge!: HTMLElement
private $commentCount!: HTMLElement
private $commentCountNum!: HTMLElement
private $dropdownWrap?: HTMLElement
constructor (ctx: Context) {
@@ -25,24 +25,29 @@ 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.$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) {
@@ -53,13 +58,6 @@ export default class List extends ListLite {
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() {
@@ -69,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()
})
// 关闭评论按钮
@@ -85,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) {
@@ -95,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')
}
}
@@ -116,7 +115,7 @@ export default class List extends ListLite {
// 防止评论框被吞
if (this.ctx.conf.editorTravel === true) {
this.ctx.trigger('editor-travel-back')
this.ctx.editorTravelBack()
}
}
@@ -133,7 +132,7 @@ export default class List extends ListLite {
}
if (!commentId) return
const comment = this.findComment(commentId)
const comment = this.ctx.findComment(commentId)
if (!comment) { // 若找不到评论
// 自动翻页
if (this.readMoreBtn) this.readMoreBtn.click()
@@ -144,18 +143,16 @@ export default class List extends ListLite {
// 已阅 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)
})
}
// 若父评论存在 “子评论部分” 限高,取消限高
comment.getParents().forEach((p) => {
if (p.$children) p.heightLimitRemove(p.$children)
p.getRender().heightLimitRemoveForChildren()
})
const goTo = () => {
@@ -177,18 +174,18 @@ export default class List extends ListLite {
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()
})
}
@@ -216,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 }) }],
]
// 列表项点击事件
@@ -254,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)
}
}
+1 -2
View File
@@ -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;
+28 -16
View File
@@ -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);
@@ -107,17 +109,22 @@
}
.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;
@@ -136,6 +143,7 @@
.atk-ua-wrap {
@media only screen and (max-width: 768px) {
display: block;
margin-top: 5px;
}
}
}
@@ -250,10 +258,8 @@
color: var(--at-color-red);
}
&:not(:first-child):not(.atk-hide) {
margin-left: 8px;
padding-left: 8px;
border-left: 1px solid var(--at-color-border);
&:not(:last-child):not(.atk-hide) {
margin-right: 16px;
}
&:hover {
@@ -291,6 +297,10 @@
font-size: 15px;
color: var(--at-color-meta);
user-select: none;
&:hover {
background: var(--at-color-bg-grey);
}
}
// 避免重复显示按钮
@@ -303,15 +313,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;
@@ -320,6 +329,9 @@
& > .atk-main {
margin-left: 47px;
& > .atk-body > .atk-content {
}
}
}
}
+22 -14
View File
@@ -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;
}
+6 -9
View File
@@ -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;
@@ -23,7 +22,7 @@
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 {
@@ -129,7 +127,6 @@
.atk-list-comments-wrap {
.atk-main-editor {
margin-top: -1px;
}
}
}
@@ -171,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;
@@ -210,8 +207,8 @@
}
&:hover {
background: var(--at-color-bg-grey);
& > .atk-text {
color: var(--at-color-main);
}
}
}
+9 -8
View File
@@ -7,9 +7,7 @@
}
.artalk, .atk-layer-wrap {
line-height: @line-height;
color: var(--at-color-font);
font-family: @font-family;
word-wrap: break-word;
word-break: break-all;
@@ -28,7 +26,9 @@
code {
font-family: @codeFont;
margin: 0 .3em;
padding: .1em .2em;
padding: 0 .5em;
display: inline-block;
font-size: .9em;
background-color: var(--at-color-bg-grey);
color: var(--at-color-font);
border-radius: @block-radius;
@@ -62,6 +62,7 @@
padding: 10px 20px 10px 20px;
background: var(--at-color-bg-grey);
border-left: 4px solid #687a86;
color: var(--at-color-font);
}
p:first-child {
@@ -309,10 +310,10 @@ i.atk-icon {
input {
width: 100%;
line-height: calc(@formInputHeight + 4px);
line-height: (@formInputHeight + 4px);
background-color: var(--at-color-bg);
border: 1px solid var(--at-color-border);
border-radius: calc(@block-radius / 2);
border-radius: (@block-radius / 2);
outline: none;
padding: 0 6px;
display: block;
@@ -333,7 +334,7 @@ i.atk-icon {
border: 1px solid var(--at-color-main);
background: transparent;
color: var(--at-color-main);
border-radius: calc(@block-radius / 2);
border-radius: (@block-radius / 2);
padding: 0 15px;
line-height: @formInputHeight;
outline: none;
@@ -403,10 +404,10 @@ i.atk-icon {
overflow: hidden;
background-color: #2c2c2c;
color: #FFF;
border-radius: 2px;
border-radius: (@block-radius / 2);
cursor: pointer;
font-size: 14px;
padding: 4px 15px;
padding: 5px 15px;
&:not(:last-child) {
margin-bottom: 3px;
+1 -1
View File
@@ -8,7 +8,7 @@
& > .atk-btn,
& > .atk-input {
font-size: 15px;
height: 32px;
height: 30px;
border: 1px solid var(--at-color-border);
border-radius: 3px;
padding: 0 5px;
+16
View File
@@ -0,0 +1,16 @@
<script src="../dist/Artalk.js"></script>
<div class="pv" data-page-key="https://artalk.js.org/">0</div>
<div class="pv" data-page-key="https://artalk.js.org/guide/intro.html">0</div>
<div class="count" data-page-key="https://artalk.js.org/">0</div>
<div class="count" data-page-key="https://artalk.js.org/guide/intro.html">0</div>
<script>
var artalk = Artalk.LoadCountWidget({
server: 'http://localhost:23366',
site: 'ArtalkDocs',
pvEl: '.pv',
countEl: ".count",
});
</script>
+15
View File
@@ -0,0 +1,15 @@
<link rel="stylesheet" href="../dist/Artalk.css">
<script src="../dist/Artalk.js"></script>
<div id="comments"></div>
<script>
var artalk = new Artalk({
el: '#comments',
pageKey: 'https://artalk.js.org/',
pageTitle: 'Artalk Home',
server: 'http://localhost:23366',
site: 'ArtalkDocs',
locale: 'auto',
});
</script>
+15
View File
@@ -0,0 +1,15 @@
<!-- <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script> -->
<link rel="stylesheet" href="../dist/ArtalkLite.css">
<script src="../dist/ArtalkLite.js"></script>
<div id="comments"></div>
<script>
var artalk = new Artalk({
el: '#comments',
pageKey: 'https://artalk.js.org/',
pageTitle: 'Artalk Home',
server: 'http://localhost:23366',
site: 'ArtalkDocs',
});
</script>
+26
View File
@@ -0,0 +1,26 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSRF Test</title>
<!-- 解除注释来测试当 referer 为空时的行为 -->
<!-- <meta name="referrer" content="never"> -->
</head>
<body>
<form action="http://localhost:23366/api/add" method="post">
<input type="text" name="name" value="admin">
<input type="text" name="email" value="test@example.com">
<input type="text" name="link" value="">
<input type="text" name="content" value="CSRF Success">
<input type="text" name="rid" value="0">
<input type="text" name="page_key" value="https://artalk.js.org/">
<input type="text" name="site_name" value="ArtalkDocs">
<button type="submit">Fire!</button>
</form>
</body>
</html>
+52 -31
View File
@@ -1,3 +1,5 @@
import { I18n } from '~/src/i18n'
export default interface ArtalkConfig {
/** 装载元素 */
el: string|HTMLElement
@@ -6,93 +8,112 @@ export default interface ArtalkConfig {
pageKey: string
/** 页面标题 */
pageTitle?: string
pageTitle: string
/** 服务器地址 */
server: string
/** 站点名 */
site?: string
site: string
/** 评论框占位字符 */
placeholder?: string
placeholder: string
/** 评论为空时显示字符 */
noComment?: string
noComment: string
/** 发送按钮文字 */
sendBtn?: string
sendBtn: string
/** 评论框旅行(显示在待回复评论后面) */
editorTravel?: boolean
editorTravel: boolean
/** 表情包 */
emoticons?: any
emoticons: object|any[]|string|false
/** Gravatar 头像 */
gravatar?: {
gravatar: {
/** 镜像 */
mirror?: string
mirror: string
/** 默认头像(URL or Gravatar Type) */
default?: string
default: string
}
/** 分页配置 */
pagination?: {
pagination: {
/** 每次请求获取数量 */
pageSize?: number
pageSize: number
/** 阅读更多模式 */
readMore?: boolean
readMore: boolean
/** 滚动到底部自动加载 */
autoLoad?: boolean
autoLoad: boolean
}
/** 内容限高 */
heightLimit?: {
heightLimit: {
/** 评论内容限高 */
content?: number
content: number
/** 子评论区域限高 */
children?: number
children: number
}
/** 评论投票按钮 */
vote?: boolean
vote: boolean
/** 评论投票反对按钮 */
voteDown?: boolean
voteDown: boolean
/** PV 元素 Selector */
pvEl?: string
/** 评论预览功能 */
preview: boolean
/** 评论数绑定元素 Selector */
countEl: string
/** PV 数绑定元素 Selector */
pvEl: string
/** 暗黑模式 */
darkMode?: boolean
darkMode: boolean|'auto'
/** 请求超时(单位:秒) */
reqTimeout?: number
reqTimeout: number
/** 平铺模式 */
flatMode?: boolean|'auto'
flatMode: boolean|'auto'
/** 嵌套模式 · 最大层数 */
nestMax?: number
nestMax: number
/** 嵌套模式 · 排序方式 */
nestSort: 'DATE_ASC'|'DATE_DESC'
/** 显示 UA 徽标 */
uaBadge?: boolean
uaBadge: boolean
/** 评论列表排序功能 (显示 Dropdown) */
listSort?: boolean
listSort: boolean
/** 图片上传功能 */
imgUpload?: boolean
imgUpload: boolean
/** 图片上传器 */
imgUploader?: (file: File) => Promise<string>
/** 版本检测 */
versionCheck?: boolean
versionCheck: boolean
/** 复用后端配置 */
useBackendConf?: boolean
/** 应用后端配置 */
useBackendConf: boolean
/** 语言本地化 */
locale: I18n|string
}
/**
* 本地持久化用户数据
* @note 始终保持一层结构,不支持多层结构
*/
export interface LocalUser {
/** 昵称 */
nick: string
+3
View File
@@ -8,6 +8,9 @@ export interface CommentData {
/** 用户昵称 */
nick: string
/** 用户邮箱 (该字段仅管理员可见) */
email?: string
/** 用户邮箱(已加密) */
email_encrypted: string
+143
View File
@@ -0,0 +1,143 @@
import { marked as libMarked } from 'marked'
import ArtalkConfig from './artalk-config'
import { CommentData, NotifyData } from './artalk-data'
import { EventPayloadMap, Event, EventScopeType, Handler } from './event'
import { internal as internalLocales, I18n } from '../src/i18n'
import Api from '../src/api'
import User from '../src/lib/user'
import Editor from '../src/editor'
import Comment from '../src/comment'
import ListLite from '../src/list/list-lite'
import SidebarLayer, { SidebarShowPayload } from '../src/layer/sidebar-layer'
import CheckerLauncher, { CheckerCaptchaPayload, CheckerPayload } from '../src/lib/checker'
/**
* Context 接口
*
* (面向接口的编程)
*/
export default interface ContextApi {
/** Context 唯一标识 */
cid: number
/** Artalk 根元素对象 */
$root: HTMLElement
/** 配置对象 */
conf: ArtalkConfig
/** 用户对象 */
user: User
/** marked 依赖对象 */
markedInstance?: typeof libMarked
/** marked 内容替换器 */
markedReplacers: ((raw: string) => string)[]
/* 设置持有的同事类 (中介者模式) */
setApi(api: Api): void
setEditor(editor: Editor): void
setList(list: ListLite): void
setSidebarLayer(list: SidebarLayer): void
setCheckerLauncher(checkerLauncher: CheckerLauncher): void
/** 获取 API 以供 HTTP 请求 */
getApi(): Api
/** 获取评论实例对象列表 */
getCommentList(): Comment[]
/** 获取评论数据列表 */
getCommentDataList(): CommentData[]
/** 查找评论 */
findComment(id: number): Comment|undefined
/** 删除评论 */
deleteComment(comment: number|Comment): void
/** 清空评论 */
clearAllComments(): void
/** 插入评论 */
insertComment(commentData: CommentData): void
/** 更新评论 */
updateComment(commentData: CommentData): void
/** 评论回复 */
replyComment(commentData: CommentData, $comment: HTMLElement, scroll?: boolean): void
/** 取消回复评论 */
cancelReplyComment(): void
/** 编辑评论 */
editComment(commentData: CommentData, $comment: HTMLElement): void
/** 取消编辑评论 */
cancelEditComment(): void
/** 更新通知数据 */
updateNotifies(notifies: NotifyData[]): void
/** 列表 - 重新加载数据 */
listReload(): void
/** 列表 - 重新加载数据 (别名) */
reload(): void
/** 列表 - UI 更新 */
listRefreshUI(): void
/** 显示侧边栏 */
showSidebar(payload?: SidebarShowPayload): void
/** 隐藏侧边栏 */
hideSidebar(): void
/** 编辑器 - 关闭评论 */
editorClose(): void
/** 编辑器 - 打开评论 */
editorOpen(): void
/** 编辑器 - 显示加载 */
editorShowLoading(): void
/** 编辑器 - 隐藏加载 */
editorHideLoading(): void
/** 编辑器 - 显示提示消息 */
editorShowNotify(msg: string, type: "i" | "s" | "w" | "e"): void
/** 评论框 - 位置移动 */
editorTravel($el: HTMLElement): void
/** 评论框 - 位置回归 */
editorTravelBack(): void
/** 验证码检测 */
checkCaptcha(payload: CheckerCaptchaPayload): void
/** 管理员检测 */
checkAdmin(payload: CheckerPayload): void
/** 管理员显示元素可见性更新 */
checkAdminShowEl(): void
/** 订阅注册 */
on<K extends keyof EventPayloadMap>(name: K, handler: Handler<EventPayloadMap[K]>, scope?: EventScopeType): void
/** 订阅取消 */
off<K extends keyof EventPayloadMap>(name: K, handler?: Handler<EventPayloadMap[K]>, scope?: EventScopeType): void
/** 订阅发布 */
trigger<K extends keyof EventPayloadMap>(name: K, payload?: EventPayloadMap[K], scope?: EventScopeType): void
/** i18n 翻译 */
$t(key: keyof I18n, args?: {[key: string]: string}): string
/** 设置暗黑模式 */
setDarkMode(darkMode: boolean): void
}
+6 -66
View File
@@ -1,77 +1,17 @@
import { ListData, CommentData, NotifyData } from './artalk-data'
import { CommentData } from './artalk-data'
import { LocalUser } from './artalk-config'
/** EventName to EventPayload Type */
export interface EventPayloadMap {
'comments-load': undefined // 评论加载时
'comments-loaded': undefined // 评论装载后
'list-load': undefined // 评论加载时
'list-loaded': undefined // 评论装载后
'list-inserted': CommentData // 评论插入后
'editor-submit': undefined // 编辑器提交时
'editor-submitted': undefined // 编辑器提交后
'user-changed': LocalUser // 本地用户数据变更时
'conf-updated': undefined // Artalk 配置变更时
// List 操作(外部:不建议 listen,仅 trigger)
'list-reload': undefined // 重新加载 List
'list-import': CommentData[] // 评论导入
'list-insert': CommentData // 评论添加
'list-delete': CommentData // 评论删除
'list-update': ListUpdatePayload // 更新评论数据
'list-refresh-ui': undefined // 刷新 List UI
// Sidebar
'sidebar-show': SidebarShowPayload // 侧边栏显示
'sidebar-hide': undefined // 侧边栏隐藏
// Editor
'editor-open': undefined // 打开评论
'editor-close': undefined // 关闭评论
'editor-show-loading': undefined // 加载显示
'editor-hide-loading': undefined // 加载隐藏
'editor-notify': NotifyConf // 显示提示
'editor-reply': EditorReplyPayload // 设置回复
'editor-reply-cancel': undefined // 取消回复
'editor-travel': HTMLElement
'editor-travel-back': undefined
// Notify
'unread-update': UnreadUpdatePayload // 未读数据更新
// Checker
'checker-admin': CheckerPayload // 检查管理员
'checker-captcha': CheckerCaptchaPayload // 检查验证码
'check-admin-show-el': undefined // 检查并更新仅管理员显示的元素
}
export interface CheckerPayload {
onSuccess?: (inputVal: string, dialogEl?: HTMLElement) => void
onMount?: (dialogEl: HTMLElement) => void
onCancel?: () => void
}
export interface NotifyConf {
msg: string
type: any
}
export interface CheckerCaptchaPayload extends CheckerPayload {
imgData?: string
iframe?: string
}
export interface UnreadUpdatePayload {
notifies: NotifyData[]
}
export type ListUpdatePayload = (data: ListData | undefined) => void
export interface EditorReplyPayload {
data: CommentData
$el: HTMLElement
scroll?: boolean
}
export interface SidebarShowPayload {
view?: 'comments'|'sites'|'pages'|'transfer'|string
'sidebar-show': undefined // 侧边栏显示
'sidebar-hide': undefined // 侧边栏隐藏
}
// ============================================
+1
View File
@@ -1 +1,2 @@
declare const ARTALK_VERSION: string
declare const ARTALK_LITE: boolean
+4
View File
@@ -0,0 +1,4 @@
import ContextApi from './context'
type ArtalkPlug = (ctx: ContextApi) => void
export default ArtalkPlug
@@ -1,9 +1,10 @@
import { UserConfigExport } from 'vite'
import { defineConfig } from 'vite'
import tsconfigPaths from 'vite-tsconfig-paths'
import { version } from './package.json'
export default {
export default defineConfig({
define: {
ARTALK_VERSION: JSON.stringify(version)
ARTALK_VERSION: JSON.stringify(version),
},
css: {
preprocessorOptions: {
@@ -12,4 +13,5 @@ export default {
},
},
},
} as UserConfigExport
plugins: [tsconfigPaths()],
})
+2 -4
View File
@@ -1,7 +1,6 @@
import { defineConfig } from 'vite'
import { resolve } from 'path'
import commonConf from './vite-common.config'
import tsconfigPaths from 'vite-tsconfig-paths'
import baseConf from './vite-base.config'
export default defineConfig({
build: {
@@ -9,6 +8,5 @@ export default defineConfig({
outDir: resolve(__dirname, "deploy"),
rollupOptions: {}
},
plugins: [tsconfigPaths()],
...commonConf
...baseConf
})
+22
View File
@@ -0,0 +1,22 @@
import fullVersionConf from './vite.config'
import * as Utils from './src/lib/utils'
export default Utils.mergeDeep(fullVersionConf, {
build: {
lib: {
fileName: (format) => ((format == "umd") ? 'ArtalkLite.js' : `ArtalkLite.${format}.js`),
},
rollupOptions: {
external: ['marked'],
output: {
globals: {
marked: 'marked',
},
assetFileNames: (assetInfo) => (/\.css$/.test(assetInfo.name) ? "ArtalkLite.css" : "[name].[ext]")
}
}
},
define: {
ARTALK_LITE: true,
},
})
+9 -18
View File
@@ -1,13 +1,14 @@
import { defineConfig } from 'vite'
import { resolve } from 'path'
import commonConf from './vite-common.config'
import tsconfigPaths from 'vite-tsconfig-paths'
import baseConf from './vite-base.config'
import * as Utils from './src/lib/utils'
export default defineConfig({
export default Utils.mergeDeep(baseConf, defineConfig({
build: {
target: 'es2015',
outDir: resolve(__dirname, "dist"),
minify: 'terser',
emptyOutDir: false,
lib: {
entry: resolve(__dirname, 'src/main.ts'),
name: 'Artalk',
@@ -15,22 +16,12 @@ export default defineConfig({
formats: ["es", "umd", "iife"]
},
rollupOptions: {
// 确保外部化处理那些你不想打包进库的依赖
external: ['vue'],
output: {
assetFileNames: assetInfo => {
if (/\.css$/.test(assetInfo.name)) {
return 'Artalk.css'
}
return "[name].[ext]"
},
// 在 UMD 构建模式下为这些外部化的依赖提供一个全局变量
globals: {
vue: 'Vue'
}
assetFileNames: (assetInfo) => (/\.css$/.test(assetInfo.name) ? "Artalk.css" : "[name].[ext]")
}
}
},
plugins: [tsconfigPaths()],
...commonConf
})
define: {
ARTALK_LITE: false,
},
}))
+1 -1
View File
@@ -20,7 +20,7 @@
el: '#comments',
pageKey: 'https://artalk.js.org/',
pageTitle: 'Artalk Home',
server: (import.meta.env.MODE === 'development') ? 'http://localhost:23366' : 'https://artalk.qwqaq.com',
server: (import.meta.env.DEV) ? 'http://localhost:23366' : 'https://artalk.qwqaq.com',
site: 'ArtalkDemo',
});
</script>
+1 -1
View File
@@ -4,7 +4,7 @@ import Artalk from 'artalk'
import katex from 'katex'
// @link https://github.com/markedjs/marked/issues/1538#issuecomment-575838181
Artalk.Use((ctx) => {
Artalk.use((ctx) => {
let i = 0
const nextID = () => `__atk_katext_id_${i++}__`
const mathExpressions: { [key: string]: { type: 'block' | 'inline', expression: string } } = {}
Loaded 100 of 102 files, more files were not shown because too many files have changed in this diff. Show more