-
-
Notifications
You must be signed in to change notification settings - Fork 297
/
Copy pathword count 字数统计组件.js
73 lines (56 loc) · 2.05 KB
/
word count 字数统计组件.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/*
* 一个显示当前笔记字数的小组件.
* 给一个笔记加上 #字数统计 的标签就能启用字数统计功能, 你也可以把它设为可继承的标签属性, 这样所有的子笔记也会开启字数统计
*
* 可以到"读书"笔记和子笔记里看到效果
*/
const TPL = `<div style="padding: 10px; border-top: 1px solid var(--main-border-color); contain: none;">
<strong>字数: </strong>
<span class="word-count"></span>
<strong>字符数: </strong>
<span class="character-count"></span>
</div>`;
class WordCountWidget extends api.NoteContextAwareWidget {
get position() { return 100; } // higher value means position towards the bottom/right
get parentWidget() { return 'center-pane'; }
isEnabled() {
// 只在有 "字数统计" 这个标签的笔记里才显示组件
return super.isEnabled()
&& this.note.type === 'text'
&& this.note.hasLabel('字数统计');
}
doRender() {
this.$widget = $(TPL);
this.$wordCount = this.$widget.find('.word-count');
this.$characterCount = this.$widget.find('.character-count');
return this.$widget;
}
async refreshWithNote(note) {
const {content} = await note.getNoteComplement();
const text = $(content).text(); // get plain text only
const counts = this.getCounts(text);
this.$wordCount.text(counts.words);
this.$characterCount.text(counts.characters);
}
getCounts(text) {
const chunks = text
.split(/[\s-+:,/\\]+/)
.filter(chunk => chunk !== '');
let words;
if (chunks.length === 1 && chunks[0] === '') {
words = 0;
}
else {
words = chunks.length;
}
const characters = chunks.join('').length;
return {words, characters};
}
async entitiesReloadedEvent({loadResults}) {
if (loadResults.isNoteContentReloaded(this.noteId)) {
this.refresh();
}
}
}
module.exports = new WordCountWidget();