UNPKG

1.57 kBPlain TextView Raw
1import { fetchCommentCount } from './api';
2import { decodePath, errorHandler, getServerURL } from './utils';
3import type { WalineAbort } from './typings';
4
5export interface WalineCommentCountOptions {
6 /**
7 * Waline 服务端地址
8 *
9 * Waline server url
10 */
11 serverURL: string;
12
13 /**
14 * 评论数 CSS 选择器
15 *
16 * Comment count CSS selector
17 *
18 * @default '.waline-comment-count'
19 */
20 selector?: string;
21
22 /**
23 * 需要获取的默认路径
24 *
25 * Path to be fetched by default
26 *
27 * @default window.location.pathname
28 */
29 path?: string;
30
31 /**
32 * 错误提示消息所使用的语言
33 *
34 * Language of error message
35 *
36 * @default navigator.language
37 */
38 lang?: string;
39}
40
41export 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 // comment count
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};