1 | import { fetchCommentCount } from './api';
|
2 | import { decodePath, errorHandler, getServerURL } from './utils';
|
3 | import type { WalineAbort } from './typings';
|
4 |
|
5 | export interface WalineCommentCountOptions {
|
6 | |
7 |
|
8 |
|
9 |
|
10 |
|
11 | serverURL: string;
|
12 |
|
13 | |
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 | selector?: string;
|
21 |
|
22 | |
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 | path?: string;
|
30 |
|
31 | |
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 |
|
38 | lang?: string;
|
39 | }
|
40 |
|
41 | export const commentCount = ({
|
42 | serverURL,
|
43 | path = window.location.pathname,
|
44 | selector = '.waline-comment-count',
|
45 | lang = navigator.language,
|
46 | }: WalineCommentCountOptions): WalineAbort => {
|
47 | const controller = new AbortController();
|
48 |
|
49 |
|
50 | const elements = document.querySelectorAll<HTMLElement>(selector);
|
51 |
|
52 | if (elements.length)
|
53 | void fetchCommentCount({
|
54 | serverURL: getServerURL(serverURL),
|
55 | paths: Array.from(elements).map((element) =>
|
56 | decodePath(element.dataset.path || element.getAttribute('id') || path)
|
57 | ),
|
58 | lang,
|
59 | signal: controller.signal,
|
60 | })
|
61 | .then((counts) => {
|
62 | elements.forEach((element, index) => {
|
63 | element.innerText = counts[index].toString();
|
64 | });
|
65 | })
|
66 | .catch(errorHandler);
|
67 |
|
68 | return controller.abort.bind(controller);
|
69 | };
|