Updated Custom Widget (markdown)

zadam 2021-01-19 15:26:37 +01:00
parent 93784c0e4a
commit 654474f74c

@ -8,7 +8,7 @@ Positions are:
## Example - word count widget
Create a code note of type JS frontend and give it `widget` label.
Create a code note of type JS frontend and **give it a `widget` label**.
```javascript
/*
@ -29,55 +29,55 @@ const TPL = `<div style="contain: none; padding: 10px; border-top: 1px solid var
class WordCountWidget extends api.TabAwareWidget {
get position() { return 100; } // higher value means position towards the bottom/right
get parentWidget() { return 'center-pane'; }
doRender() {
this.$widget = $(TPL);
this.$wordCount = this.$widget.find('.word-count');
this.$characterCount = this.$widget.find('.character-count');
return this.$widget;
}
async refreshWithNote(note) {
if (note.type !== 'text' || !note.hasLabel('wordCount')) {
// show widget only on text notes and when marked with 'wordCount' label
this.toggleInt(false); // hide
return;
}
this.toggleInt(true); // display
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();