Repository navigation
Expand file tree
/
Copy pathindex.ts
More file actions
1433 lines (1392 loc) · 54.7 KB
/
Copy pathindex.ts
File metadata and controls
1433 lines (1392 loc) · 54.7 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {
Plugin,
showMessage,
confirm,
Dialog,
Menu,
openTab,
adaptHotkey,
getFrontend,
getBackend,
Setting,
fetchPost,
Protyle,
openWindow,
IOperation,
Constants,
openMobileFileById,
lockScreen,
ICard,
ICardData,
exitSiYuan,
getModelByDockType,
getAllEditor,
Files,
platformUtils,
openSetting,
openAttributePanel,
saveLayout,
IKernelPluginState,
IKernelPluginRpcCall,
} from "siyuan";
import type {ICommandContext} from "siyuan";
import * as siyuan from "siyuan";
import "./index.scss";
const STORAGE_NAME = "menu-config";
const DATE_STORAGE_NAME = "date-picker-config";
const TAB_TYPE = "custom_tab";
const DOCK_TYPE = "dock_tab";
const CUSTOM_BLOCK_TYPE = "counter";
export default class PluginSample extends Plugin {
declare i18n: Record<string, string>;
private custom: ReturnType<Plugin["addTab"]>;
private isMobile: boolean;
private isReadonly: boolean;
private isSettingsWindow: boolean;
private publishDataStatus = "";
private refreshDateSetting?: () => void;
private dateSettingsRevision = 0;
private dateSavePending = false;
private dateSettingsSnapshot = {date: ""};
private dateSettingDisposed = false;
private blockIconEventBindThis = this.blockIconEvent.bind(this);
private readonly renderCounterCustomBlock = ({element, content, setContent}: {
element: HTMLElement;
content: string;
setContent: (content: string) => boolean;
}) => {
let count = Number(content);
if (!Number.isSafeInteger(count)) {
count = 0;
}
const button = document.createElement("button");
button.type = "button";
button.className = "b3-button b3-button--outline";
const updateLabel = () => {
const label = this.i18n.customBlockCounter.replace("${count}", count.toString());
button.textContent = label;
button.setAttribute("aria-label", label);
};
const increase = () => {
const nextCount = count + 1;
if (setContent(nextCount.toString())) {
count = nextCount;
updateLabel();
}
};
updateLabel();
button.addEventListener("click", increase);
element.append(button);
return () => button.removeEventListener("click", increase);
};
onload() {
this.isSettingsWindow = document.body.classList.contains("body--settings");
this.isReadonly = Boolean(window.siyuan.config.readonly || window.siyuan.isPublish);
this.data[STORAGE_NAME] = {readonlyText: this.i18n.readonlyText};
this.dateSettingDisposed = false;
const frontEnd = getFrontend();
this.isMobile = frontEnd === "mobile" || frontEnd === "browser-mobile";
this.customBlockRenders[CUSTOM_BLOCK_TYPE] = {
render: this.renderCounterCustomBlock,
};
// 发布端保留内容渲染,管理操作和内核通信仅在可写的管理端注册。
if (this.isReadonly) {
return;
}
// 设置窗口使用自己的配置与样式,文档入口和内核通信示例仅在普通前端注册。
if (this.isSettingsWindow) {
this.initSetting();
return;
}
this.kernel.rpc.bind("unload", this.onKernelPluginUnload);
this.kernel.rpc.bind("notify", this.onKernelPluginNotify);
this.eventBus.on("kernel-plugin-state-change", this.onKernelPluginStateChange);
this.addToolbarItem({
name: "insert-smail-emoji",
icon: "iconEmoji",
hotkey: "⇧⌘I",
tipPosition: "n",
tip: this.i18n.insertEmoji,
click(protyle: Protyle) {
protyle.insert("😊");
},
});
this.addBreadcrumbButton({
id: "fullscreen",
icon: "iconFullscreen",
title: this.i18n.toggleEditorFullscreen,
callback: (event, protyle) => {
event.preventDefault();
const editor = protyle.getInstance();
editor.setFullscreen(!editor.isFullscreen());
},
});
this.addBreadcrumbButton({
id: "insert-custom-block",
icon: "iconAdd",
title: this.i18n.insertCustomBlock,
callback: (event, protyle) => {
event.preventDefault();
if (protyle.disabled) {
return;
}
const info = `${encodeURIComponent(this.name)}/${encodeURIComponent(CUSTOM_BLOCK_TYPE)}`;
const markdown = `;;;${info}\n0\n;;;`;
protyle.getInstance().insert(protyle.lute.Md2BlockDOM(markdown), true);
},
});
// 图标的制作参见帮助文档
this.addIcons(`<symbol id="iconFace" viewBox="0 0 32 32">
<path d="M13.667 17.333c0 0.92-0.747 1.667-1.667 1.667s-1.667-0.747-1.667-1.667 0.747-1.667 1.667-1.667 1.667 0.747 1.667 1.667zM20 15.667c-0.92 0-1.667 0.747-1.667 1.667s0.747 1.667 1.667 1.667 1.667-0.747 1.667-1.667-0.747-1.667-1.667-1.667zM29.333 16c0 7.36-5.973 13.333-13.333 13.333s-13.333-5.973-13.333-13.333 5.973-13.333 13.333-13.333 13.333 5.973 13.333 13.333zM14.213 5.493c1.867 3.093 5.253 5.173 9.12 5.173 0.613 0 1.213-0.067 1.787-0.16-1.867-3.093-5.253-5.173-9.12-5.173-0.613 0-1.213 0.067-1.787 0.16zM5.893 12.627c2.28-1.293 4.040-3.4 4.88-5.92-2.28 1.293-4.040 3.4-4.88 5.92zM26.667 16c0-1.040-0.16-2.040-0.44-2.987-0.933 0.2-1.893 0.32-2.893 0.32-4.173 0-7.893-1.92-10.347-4.92-1.4 3.413-4.187 6.093-7.653 7.4 0.013 0.053 0 0.12 0 0.187 0 5.88 4.787 10.667 10.667 10.667s10.667-4.787 10.667-10.667z"></path>
</symbol>
<symbol id="iconSaving" viewBox="0 0 32 32">
<path d="M20 13.333c0-0.733 0.6-1.333 1.333-1.333s1.333 0.6 1.333 1.333c0 0.733-0.6 1.333-1.333 1.333s-1.333-0.6-1.333-1.333zM10.667 12h6.667v-2.667h-6.667v2.667zM29.333 10v9.293l-3.76 1.253-2.24 7.453h-7.333v-2.667h-2.667v2.667h-7.333c0 0-3.333-11.28-3.333-15.333s3.28-7.333 7.333-7.333h6.667c1.213-1.613 3.147-2.667 5.333-2.667 1.107 0 2 0.893 2 2 0 0.28-0.053 0.533-0.16 0.773-0.187 0.453-0.347 0.973-0.427 1.533l3.027 3.027h2.893zM26.667 12.667h-1.333l-4.667-4.667c0-0.867 0.12-1.72 0.347-2.547-1.293 0.333-2.347 1.293-2.787 2.547h-8.227c-2.573 0-4.667 2.093-4.667 4.667 0 2.507 1.627 8.867 2.68 12.667h2.653v-2.667h8v2.667h2.68l2.067-6.867 3.253-1.093v-4.707z"></path>
</symbol>`);
this.custom = this.addTab({
type: TAB_TYPE,
init() {
this.element.innerHTML = `<div class="plugin-sample__custom-tab">${this.data.text}</div>`;
},
beforeDestroy() {
console.log("before destroy tab:", TAB_TYPE);
},
destroy() {
console.log("destroy tab:", TAB_TYPE);
},
});
this.addCommand({
langKey: "showDialog",
hotkey: "⇧⌘O",
execute: (context: ICommandContext) => {
console.log("showDialog command context:", {
source: context.source,
focus: context.focus,
protyle: context.protyle,
range: context.range,
rangeConnected: Boolean(context.range?.startContainer.isConnected),
fileTree: context.fileTree,
dock: context.dock,
});
this.showDialog();
},
callback: () => {
this.showDialog();
},
editorCallback: () => {
this.showDialog();
},
});
this.addCommand({
langKey: "getTab",
hotkey: "⇧⌘M",
globalCallback: () => {
console.log(this.getOpenedTab());
},
});
this.addDock({
config: {
position: "LeftBottom",
size: {width: 200, height: 0},
icon: "iconSaving",
title: "Custom Dock",
hotkey: "⌥⌘W",
},
data: {
text: "This is my custom dock",
},
type: DOCK_TYPE,
resize() {
console.log(DOCK_TYPE + " resize");
},
update() {
console.log(DOCK_TYPE + " update");
},
init: (dock) => {
if (this.isMobile) {
dock.element.innerHTML = `<div class="toolbar toolbar--border toolbar--dark">
<svg class="toolbar__icon"><use xlink:href="#iconEmoji"></use></svg>
<div class="toolbar__text">Custom Dock</div>
</div>
<div class="fn__flex-1 plugin-sample__custom-dock">
${dock.data.text}
</div>
</div>`;
} else {
dock.element.innerHTML = `<div class="fn__flex-1 fn__flex-column">
<div class="block__icons">
<div class="block__logo">
<svg class="block__logoicon"><use xlink:href="#iconEmoji"></use></svg>Custom Dock
</div>
<span class="fn__flex-1 fn__space"></span>
<span data-type="min" class="block__icon ariaLabel" data-position="north" aria-label="Min ${
adaptHotkey("⌘W")
}"><svg><use xlink:href="#iconMin"></use></svg></span>
</div>
<div class="fn__flex-1 plugin-sample__custom-dock">
${dock.data.text}
</div>
</div>`;
}
},
destroy() {
console.log("destroy dock:", DOCK_TYPE);
},
});
this.initSetting();
this.protyleSlash = [{
filter: ["insert emoji 😊", "插入表情 😊", "crbqwx"],
html:
`<div class="b3-list-item__first"><span class="b3-list-item__text">${this.i18n.insertEmoji}</span><span class="b3-list-item__meta">😊</span></div>`,
id: "insertEmoji",
callback(protyle: Protyle) {
protyle.insert("😊");
},
}];
this.protyleOptions = {
toolbar: [
"block-ref",
"a",
"|",
"text",
"strong",
"em",
"u",
"s",
"mark",
"sup",
"sub",
"clear",
"|",
"code",
"kbd",
"tag",
"inline-math",
"inline-memo",
],
};
console.log(this.i18n.helloPlugin);
}
private initSetting() {
const textareaElement = document.createElement("textarea");
this.setting = new Setting({
// 取消注释后,桌面端用独立窗口打开插件设置(思源 3.8.7+);浏览器、移动端和设置窗口内仍使用对话框。
// openInWindow: true,
confirmCallback: () => {
this.saveData(STORAGE_NAME, {...this.data[STORAGE_NAME], readonlyText: textareaElement.value}).catch(
e => {
showMessage(`[${this.name}] save data [${STORAGE_NAME}] fail: `, e);
},
);
},
});
this.setting.addItem({
title: this.i18n.readonlyText,
direction: "row",
description: this.i18n.readonlyTextTip,
createActionElement: () => {
textareaElement.className = "b3-text-field fn__block";
textareaElement.placeholder = this.i18n.readonlyText;
textareaElement.value = this.data[STORAGE_NAME].readonlyText;
return textareaElement;
},
});
const publishButton = document.createElement("button");
publishButton.className = "b3-button b3-button--outline";
publishButton.textContent = this.i18n.publishData;
publishButton.addEventListener("click", async () => {
publishButton.disabled = true;
try {
await this.publishSettings(textareaElement.value);
} finally {
publishButton.disabled = false;
}
});
this.setting.addItem({
title: this.i18n.publishData,
description: this.i18n.publishDataTip,
actionElement: publishButton,
});
const btnaElement = document.createElement("button");
const colorAction = document.createElement("div");
colorAction.className = "fn__flex";
const colorButton = document.createElement("button");
colorButton.className = "b3-button b3-button--outline";
colorButton.textContent = this.i18n.colorPicker;
colorButton.disabled = this.isReadonly;
const colorPreview = document.createElement("span");
colorPreview.className = "fn__flex-center";
const confirmedColor = () => this.data[STORAGE_NAME]?.color || "#d23f31";
colorPreview.textContent = confirmedColor();
let colorSequence = 0;
colorButton.addEventListener("click", async () => {
if (!("openColorPicker" in siyuan) || typeof siyuan.openColorPicker !== "function") {
showMessage(this.i18n.colorPickerUnavailable);
return;
}
const sequence = ++colorSequence;
const picker = siyuan.openColorPicker({
value: confirmedColor(),
ownerPlugin: this,
ownerElement: colorButton,
title: this.i18n.colorPicker,
onPreview: (value: {hex: string;}) => {
if (sequence === colorSequence) colorPreview.textContent = value.hex;
},
onPreviewEnd: () => {
if (sequence === colorSequence) colorPreview.textContent = confirmedColor();
},
});
const result: {type: "confirm"; value: {hex: string;}; changed: boolean;} | {type: "cancel";} = await picker
.result;
if (result.type === "confirm" && result.changed && sequence === colorSequence) {
try {
await this.saveData(STORAGE_NAME, {...this.data[STORAGE_NAME], color: result.value.hex});
if (sequence === colorSequence) colorPreview.textContent = confirmedColor();
} catch (error) {
showMessage(String(error));
}
}
});
const colorSpace = document.createElement("span");
colorSpace.className = "fn__space";
colorAction.append(colorButton, colorSpace, colorPreview);
this.setting.addItem({
title: this.i18n.colorPicker,
description: this.i18n.colorPickerTip,
actionElement: colorAction,
});
this.setting.addItem({
title: this.i18n.datePicker,
description: this.i18n.datePickerTip,
createActionElement: () => this.createDateSetting(),
});
btnaElement.className = "b3-button b3-button--outline fn__flex-center fn__size200";
btnaElement.textContent = "Open";
btnaElement.addEventListener("click", () => {
window.open("https://github.com/siyuan-note/plugin-sample");
});
this.setting.addItem({
title: "Open plugin url",
description: "Open plugin url in browser",
actionElement: btnaElement,
});
}
private createDateSetting() {
const dateAction = document.createElement("div");
dateAction.className = "fn__flex";
const dateButton = document.createElement("button");
dateButton.className = "b3-button b3-button--outline";
dateButton.textContent = this.i18n.datePicker;
const dateValue = document.createElement("span");
dateValue.className = "fn__flex-center";
const refresh = () => {
dateValue.textContent = this.dateSettingsSnapshot.date;
};
this.refreshDateSetting = refresh;
this.refreshDateSetting();
let datePending = false;
dateButton.addEventListener("click", async () => {
if (datePending || this.refreshDateSetting !== refresh) return;
if (!("openDatePicker" in siyuan) || typeof siyuan.openDatePicker !== "function") {
showMessage(this.i18n.datePickerUnavailable);
return;
}
datePending = true;
try {
const picker = siyuan.openDatePicker({
type: "date",
value: this.dateSettingsSnapshot.date,
ownerPlugin: this,
ownerElement: dateButton,
title: this.i18n.datePicker,
});
const result: {type: "confirm"; value: string; changed: boolean;} | {type: "cancel";} = await picker
.result;
if (
result.type === "confirm" && result.changed && dateButton.isConnected &&
this.refreshDateSetting === refresh
) {
await this.saveDate(result.value);
}
} catch (error) {
showMessage(String(error));
} finally {
datePending = false;
}
});
const dateSpace = document.createElement("span");
dateSpace.className = "fn__space";
dateAction.append(dateButton, dateSpace, dateValue);
return dateAction;
}
private refreshDateData(revision: number, data: {date?: string;}) {
if (revision === this.dateSettingsRevision) {
this.dateSettingsSnapshot = {date: typeof data?.date === "string" ? data.date : ""};
}
this.data[DATE_STORAGE_NAME] = {...this.dateSettingsSnapshot};
this.refreshDateSetting?.();
}
private async loadDateSetting(revision = ++this.dateSettingsRevision) {
this.data[DATE_STORAGE_NAME] = {date: ""};
const data = await this.loadData(DATE_STORAGE_NAME).catch(e => {
console.log(`[${this.name}] load data [${DATE_STORAGE_NAME}] fail: `, e);
return this.dateSettingsSnapshot;
});
this.refreshDateData(revision, data);
}
private async saveDate(value: string) {
if (this.dateSavePending) {
showMessage(this.i18n.datePickerSaveUncertain);
return;
}
const revision = ++this.dateSettingsRevision;
const data = {date: value};
this.dateSavePending = true;
const settle = (response: {code?: number; msg?: string;}, rejected = false) => {
const succeeded = !rejected && response?.code === 0;
// saveData 的回调会先覆写缓存;失败或过期的回调只能恢复最近一次已知的设置。
this.refreshDateData(succeeded ? revision : -1, data);
this.dateSavePending = false;
// 过期的成功响应不代表当前存储值,重新读取以反映其他窗口与本次写入的实际落盘顺序。
if (succeeded && revision !== this.dateSettingsRevision && !this.dateSettingDisposed) {
void this.loadDateSetting();
}
if (!succeeded && this.refreshDateSetting) {
showMessage(`${this.i18n.datePickerSaveFailed}${response?.msg ? `: ${response.msg}` : ""}`);
}
};
const saved = Promise.resolve().then(() => this.saveData(DATE_STORAGE_NAME, data)).then(
response => settle(response),
error => settle(error, true),
);
let timer: ReturnType<typeof setTimeout>;
await Promise.race([
saved,
new Promise<void>(resolve => {
timer = setTimeout(() => {
// 超时不能证明写入失败;允许重新查看日期,但结果未确认前不重试或并发写入。
if (this.refreshDateSetting) showMessage(this.i18n.datePickerSaveUncertain);
resolve();
}, 10000);
}),
]);
clearTimeout(timer);
}
private endDateSetting() {
this.dateSettingsRevision++;
this.dateSettingDisposed = true;
this.refreshDateSetting = undefined;
}
async onLayoutReady() {
if (this.isSettingsWindow) {
// 插件专属类名可作为设置窗口的样式钩子,卸载时由当前实例清理。
document.body.classList.add("plugin-sample--settings");
await this.onDataChanged();
return;
}
const topBarElement = this.addTopBar({
icon: this.isReadonly ? "iconEmoji" : "iconFace",
title: this.i18n.addTopBarIcon,
position: "right",
contextMenu: (menu) => {
if (this.isReadonly || this.isMobile) {
return;
}
// 同步添加当前按钮的操作,宿主负责与显隐菜单之间的分隔线。
menu.addItem({
id: "plugin-sample-settings",
icon: "iconSettings",
label: this.i18n.openPluginSettings,
click: () => this.openSetting(),
});
},
callback: () => {
if (this.isMobile) {
this.addMenu();
} else {
let rect = topBarElement.getBoundingClientRect();
// 如果被隐藏,则使用更多按钮
if (rect.width === 0) {
rect = document.querySelector("#barMore").getBoundingClientRect();
}
if (rect.width === 0) {
rect = document.querySelector("#barPlugins").getBoundingClientRect();
}
this.addMenu(rect);
}
},
});
if (this.isReadonly) {
await this.loadPublishedSettings();
return;
}
const statusIconTemp = document.createElement("template");
statusIconTemp.innerHTML = `<div class="toolbar__item ariaLabel" aria-label="Remove plugin-sample Data">
<svg>
<use xlink:href="#iconTrashcan"></use>
</svg>
</div>`;
statusIconTemp.content.firstElementChild.addEventListener("click", () => {
confirm("⚠️", this.i18n.confirmRemove.replace("${name}", this.name), () => {
if (this.dateSavePending) {
showMessage(this.i18n.datePickerSaveUncertain);
return;
}
Promise.all([STORAGE_NAME, DATE_STORAGE_NAME].map(name => this.removeData(name))).then(() => {
this.data[STORAGE_NAME] = {readonlyText: this.i18n.readonlyText};
this.refreshDateData(++this.dateSettingsRevision, {date: ""});
showMessage(`[${this.name}]: ${this.i18n.removedData}`);
}).catch(e => {
showMessage(`[${this.name}] remove data [${STORAGE_NAME}] fail: `, e);
});
});
});
this.addStatusBar({
element: statusIconTemp.content.firstElementChild as HTMLElement,
});
await this.onDataChanged();
console.log(`frontend: ${getFrontend()}; backend: ${getBackend()}`);
}
async onunload() {
this.endDateSetting();
console.log(this.i18n.byePlugin);
if (this.isSettingsWindow) {
document.body.classList.remove("plugin-sample--settings");
return;
}
if (this.isReadonly) {
return;
}
this.eventBus.off("kernel-plugin-state-change", this.onKernelPluginStateChange);
await Promise.all([
this.kernel.rpc.unbind("unload", this.onKernelPluginUnload),
this.kernel.rpc.unbind("notify", this.onKernelPluginNotify),
]);
}
async uninstall() {
if (this.isReadonly) {
return;
}
// 卸载插件时删除插件数据
// Delete plugin data when uninstalling the plugin
await Promise.all([STORAGE_NAME, DATE_STORAGE_NAME].map(name =>
this.removeData(name).catch(e => {
showMessage(`uninstall [${this.name}] remove data [${name}] fail: ${e.msg}`);
})
));
}
private async loadPublishedSettings() {
// 每次读取先清除旧快照,未授权、未生成及请求失败时都使用默认值,不读取私有存储。
this.data[STORAGE_NAME] = {readonlyText: this.i18n.readonlyText};
this.publishDataStatus = "";
try {
const data = await this.loadPublishData();
if (typeof data.readonlyText === "string") {
this.data[STORAGE_NAME] = {readonlyText: data.readonlyText};
}
} catch (error) {
const code = (error as {code?: number;} | null)?.code;
this.publishDataStatus = code === 403 ?
this.i18n.publishDataUnavailable :
code === 404 ?
this.i18n.publishDataMissing :
this.i18n.publishDataLoadFailed;
}
}
private async publishSettings(readonlyText: string) {
if (this.isReadonly) {
return;
}
try {
// 仅选择声明过的公开字段,完整替换快照,避免将私有配置对象直接传入。
await this.savePublishData({readonlyText});
showMessage(this.i18n.publishDataSaved);
} catch (error) {
const code = (error as {code?: number;} | null)?.code;
showMessage(code === 403 ? this.i18n.publishDataGrantRequired : this.i18n.publishDataSaveFailed);
}
}
// 各前端实例独立读取插件存储;数据被删除时清除缓存,避免 loadData 回退到旧值。
async onDataChanged() {
if (this.isReadonly) {
await this.loadPublishedSettings();
return;
}
const revision = ++this.dateSettingsRevision;
this.data[STORAGE_NAME] = {readonlyText: this.i18n.readonlyText};
await this.loadData(STORAGE_NAME).catch(e => {
console.log(`[${this.name}] load data [${STORAGE_NAME}] fail: `, e);
});
await this.loadDateSetting(revision);
}
async updateCards(options: ICardData) {
options.cards.sort((a: ICard, b: ICard) => {
if (a.blockID < b.blockID) {
return -1;
}
if (a.blockID > b.blockID) {
return 1;
}
return 0;
});
return options;
}
openSetting() {
if (this.isReadonly || !this.setting) {
return;
}
// 基类在设置窗口中通过宿主打开设置,在普通前端中打开当前实例的设置项。
super.openSetting();
}
/* 自定义设置
openSetting() {
const dialog = new Dialog({
title: this.name,
content: `<div class="b3-dialog__content"><textarea class="b3-text-field fn__block" placeholder="readonly text in the menu"></textarea></div>
<div class="b3-dialog__action">
<button class="b3-button b3-button--cancel">${this.i18n.cancel}</button><div class="fn__space"></div>
<button class="b3-button b3-button--text">${this.i18n.save}</button>
</div>`,
width: this.isMobile ? "92vw" : "520px",
});
const inputElement = dialog.element.querySelector("textarea");
inputElement.value = this.data[STORAGE_NAME].readonlyText;
const btnsElement = dialog.element.querySelectorAll(".b3-button");
dialog.bindInput(inputElement, () => {
(btnsElement[1] as HTMLButtonElement).click();
});
inputElement.focus();
btnsElement[0].addEventListener("click", () => {
dialog.destroy();
});
btnsElement[1].addEventListener("click", () => {
this.saveData(STORAGE_NAME, {readonlyText: inputElement.value});
dialog.destroy();
});
}
*/
private readonly eventBusPaste = (event: any) => {
// 如果需异步处理请调用 preventDefault, 否则会进行默认处理
event.preventDefault();
// 如果使用了 preventDefault,必须调用 resolve,否则程序会卡死
event.detail.resolve({
textPlain: event.detail.textPlain.trim(),
});
};
private readonly eventBusLog = ({detail}: any) => {
console.log(detail);
};
private readonly onKernelPluginStateChange = async ({detail}: CustomEvent<IKernelPluginState>) => {
console.log("kernel-plugin-state-change", detail);
switch (detail.code) {
case 2: { // running
const params = ["param 1", "param 2"];
await this.kernel.rpc.notify["echo-notify"](...params);
const result = await this.kernel.rpc.call.echo(...params);
console.group("JSON RPC client -> kernel: call [echo] method");
console.log("params:", params);
console.log("result:", result);
console.groupEnd();
const request: IKernelPluginRpcCall[] = [
{ // call with custom id
id: 0,
method: "echo",
params: {key1: "value1"},
},
{ // call with auto-generated id
method: "echo",
params: ["key2", "value2"],
},
{ // notify will not have response and id
method: "echo-notify",
params: {key3: "value3"},
notification: true,
},
{ // notify will remove id even if it is set
id: "3",
method: "echo-notify",
params: ["key4", "value4"],
notification: true,
},
];
const response = await this.kernel.rpc.batch(...request);
console.group("JSON RPC client -> kernel: batch call [echo] and [notify] method");
console.log("request:", request);
console.log("response:", response);
console.groupEnd();
break;
}
}
};
private onKernelPluginUnload = async (...params: any[]) => {
console.group("JSON RPC kernel -> client: unload");
console.log("params:", params);
console.groupEnd();
};
private onKernelPluginNotify = async (...params: any[]) => {
console.group("JSON RPC kernel -> client: notify");
console.log("params:", params);
console.groupEnd();
};
private blockIconEvent({detail}: any) {
detail.menu.addItem({
id: "pluginSample_removeSpace",
iconHTML: "",
label: this.i18n.removeSpace,
click: () => {
const doOperations: IOperation[] = [];
detail.blockElements.forEach((item: HTMLElement) => {
const editElement = item.querySelector('[contenteditable="true"]');
if (editElement) {
editElement.textContent = editElement.textContent.replace(/ /g, "");
doOperations.push({
id: item.dataset.nodeId,
data: item.outerHTML,
action: "update",
});
}
});
detail.protyle.getInstance().transaction(doOperations);
},
});
}
private showDialog() {
const dialog = new Dialog({
title: `SiYuan ${Constants.SIYUAN_VERSION}`,
content: `<div class="b3-dialog__content">
<div>appId:</div>
<div class="fn__hr"></div>
<div class="plugin-sample__time">${this.app.appId}</div>
<div class="fn__hr"></div>
<div class="fn__hr"></div>
<div>API demo:</div>
<div class="fn__hr"></div>
<div class="plugin-sample__time">System current time: <span id="time"></span></div>
<div class="fn__hr"></div>
<div class="fn__hr"></div>
<div>Protyle demo:</div>
<div class="fn__hr"></div>
<div id="protyle" style="height: 360px;"></div>
</div>`,
width: this.isMobile ? "92vw" : "560px",
height: "540px",
});
new Protyle(this.app, dialog.element.querySelector("#protyle"), {
blockId: this.getEditor().protyle.block.rootID,
});
fetchPost("/api/system/currentTime", {}, (response) => {
dialog.element.querySelector("#time").innerHTML = new Date(response.data).toString();
});
}
private showFlashcardReview() {
const dialog = new Dialog({
title: this.i18n.openSelectedCardTab,
content: '<div class="b3-dialog__content"></div>',
width: "520px",
});
const container = dialog.element.querySelector(".b3-dialog__content");
const addInput = (title: string) => {
const label = document.createElement("label");
label.textContent = title;
const input = document.createElement("textarea");
input.className = "b3-text-field fn__block";
label.append(input);
container.append(label);
return input;
};
const decks = addInput(this.i18n.reviewSetIDs);
const documents = addInput(this.i18n.reviewDocumentIDs);
const button = document.createElement("button");
button.className = "b3-button";
button.textContent = this.i18n.openSelectedCardTab;
button.addEventListener("click", () => {
const parseIDs = (value: string) => Array.from(new Set(value.split(/[\s,]+/).filter(Boolean)));
const reviewSetIDs = parseIDs(decks.value);
if (reviewSetIDs.length === 0) {
showMessage(this.i18n.reviewSetIDsRequired);
return;
}
const rootIDs = parseIDs(documents.value);
// 多个卡包取并集并去重;每张卡保留自身调度预设和每日额度,会话采用工作空间队列限制及默认排序。
const options: Parameters<typeof openTab>[0] = {
app: this.app,
card: {
type: "all",
reviewSetIDs,
reviewMode: "normal",
},
};
// 版本 1 查询 AST 与卡包及 type/id 范围取交集,此处可选地限制到多个文档。
if (rootIDs.length > 0) {
options.card.query = {
version: 1,
root: {operator: "predicate", field: "rootID", comparator: "in", value: rootIDs},
};
}
// 关闭页签结束会话,恢复布局时根据保存的选择重新创建会话。
openTab(options);
dialog.destroy();
});
container.append(button);
}
private addMenu(rect?: DOMRect) {
const menu = new Menu("topBarSample", () => {
console.log(this.i18n.byeMenu);
});
if (this.isReadonly) {
this.addReadonlyText(menu);
if (this.publishDataStatus) {
menu.addItem({label: this.publishDataStatus, type: "readonly"});
}
menu.addItem({
icon: "iconRefresh",
label: this.i18n.publishDataRefresh,
click: async () => {
await this.loadPublishedSettings();
showMessage(this.publishDataStatus || this.i18n.publishDataLoaded);
},
});
this.openMenu(menu, rect);
return;
}
menu.addItem({
icon: "iconSettings",
label: "Open Setting",
click: () => {
openSetting(this.app);
},
});
menu.addItem({
icon: "iconDrag",
label: "Open Attribute Panel",
click: () => {
openAttributePanel({
nodeElement: this.getEditor().protyle.wysiwyg.element.firstElementChild as HTMLElement,
protyle: this.getEditor().protyle,
focusName: "custom",
});
},
});
menu.addItem({
icon: "iconInfo",
label: "Dialog(open doc first)",
accelerator: this.commands[0].customHotkey,
click: () => {
this.showDialog();
},
});
menu.addItem({
icon: "iconFocus",
label: "Select Opened Doc(open doc first)",
click: () => {
(getModelByDockType("file") as Files).selectItem(
this.getEditor().protyle.notebookId,
this.getEditor().protyle.path,
);
},
});
if (!this.isMobile) {
menu.addItem({
icon: "iconFace",
label: "Open Custom Tab",
click: () => {
const tab = openTab({
app: this.app,
custom: {
icon: "iconFace",
title: "Custom Tab",
data: {
text: platformUtils.isHuawei() ? "Hello, Huawei!" : "This is my custom tab",
},
id: this.name + TAB_TYPE,
},
});
console.log(tab);
},
});
menu.addItem({
icon: "iconImage",
label: "Open Asset Tab(First open the Chinese help document)",
click: () => {
const tab = openTab({
app: this.app,
asset: {
path: "assets/paragraph-20210512165953-ag1nib4.svg",
},
});
console.log(tab);
},
});
menu.addItem({
icon: "iconFile",
label: "Open Doc Tab(open doc first)",
click: async () => {
const tab = await openTab({
app: this.app,
doc: {
id: this.getEditor().protyle.block.rootID,
},
});
console.log(tab);
},
});
menu.addItem({
icon: "iconSearch",
label: "Open Search Tab",
click: () => {
const tab = openTab({
app: this.app,
search: {
k: "SiYuan",
},
});
console.log(tab);
},
});
menu.addItem({
icon: "iconRiffCard",
label: "Open Card Tab",
click: () => {
const tab = openTab({
app: this.app,
card: {
type: "all",
},
});
console.log(tab);
},
});
menu.addItem({
icon: "iconRiffCard",
label: this.i18n.openSelectedCardTab,
click: () => this.showFlashcardReview(),