-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmnutils.js
More file actions
executable file
·10181 lines (9829 loc) · 323 KB
/
mnutils.js
File metadata and controls
executable file
·10181 lines (9829 loc) · 323 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
if (typeof setTimeout === "undefined") {
// 直接挂载到 globalContext,确保第三方库能访问到
/**
* 设置定时器
* @param {function} callback
* @param {number} delay 延时时间,单位为毫秒或秒,阈值为50
* @returns {number} 定时器ID
*/
globalThis.setTimeout = function(callback, delay) {
// 防止 delay 为空或非数字
var seconds = delay || 0;
if (seconds > 50) {
//防呆设计,阈值为50,如果delay为1,则视为1秒,如果为100时,视为100ms
seconds = seconds/1000.
}
// 调用原生层 (假设你的 NSTimer 接口是这样用的)
// 注意:这里不需要 return new Promise,也不需要 async
let timer = NSTimer.scheduledTimerWithTimeInterval(seconds, false, function () {
// 执行回调
if (typeof callback === 'function') {
callback();
} else if (typeof callback === 'string') {
// 兼容极少数库传字符串的情况 (不推荐但存在)
try { eval(callback); } catch(e){}
}
});
// 标准 setTimeout 会返回一个整数 ID 用于 clearTimeout
// 这里我们随便返回一个数字,防止库报错
let timerId = MNUtil.addTimer(timer);
return timerId;
};
/**
* 设置定时器
* @param {function} callback
* @param {number} interval 间隔时间,单位为毫秒或秒,阈值为50
* @returns {number} 定时器ID
*/
globalThis.setInterval = function(callback, interval) {
// 防止 delay 为空或非数字
var seconds = interval || 0;
if (seconds > 50) {
//防呆设计,阈值为50,如果interval为1,则视为1秒,如果为100时,视为100ms
seconds = seconds/1000.
}
// 调用原生层 (假设你的 NSTimer 接口是这样用的)
// 注意:这里不需要 return new Promise,也不需要 async
let timer = NSTimer.scheduledTimerWithTimeInterval(seconds, true, function () {
// 执行回调
if (typeof callback === 'function') {
callback();
} else if (typeof callback === 'string') {
// 兼容极少数库传字符串的情况 (不推荐但存在)
try { eval(callback); } catch(e){}
}
});
// 标准 setTimeout 会返回一个整数 ID 用于 clearTimeout
// 这里我们随便返回一个数字,防止库报错
let timerId = MNUtil.addTimer(timer);
return timerId;
};
// 3. 最好顺手把 clearTimeout 也补上,防止报错
if (typeof clearTimeout === "undefined") {
globalThis.clearTimeout = function(id) {
// 如果原生没有提供取消 Timer 的接口,这里留空即可
// 至少保证库调用它时不会崩溃
MNUtil.clearTimer(id);
};
}
if (typeof clearInterval === "undefined") {
globalThis.clearInterval = function(id) {
MNUtil.clearTimer(id);
};
}
if (typeof atob === "undefined") {
globalThis.atob = function(str) {
return DataConverter.atob(str)
};
}
}
class Mustache {
/**
*
* @param {string} template
* @param {object} config
* @returns {string}
*/
static render(template,config){
let output = mustache.render(template,config)
return output
}
/**
*
* @param {string} template
* @returns {Array<{type:string,value:string,start:number,end:number}>}
*/
static parse(template){
return mustache.parse(template)
}
}
class Locale{
static init(mainPath){
try {
this.mainPath = mainPath
this.current = NSLocale.currentLocale()
this.isZH = this.current.localeIdentifier().startsWith("zh")
this.isEN = this.current.localeIdentifier().startsWith("en")
this._ZHConfig = this.readJSON(this.mainPath+"/data/zh.json")
this._ENConfig = this.readJSON(this.mainPath+"/data/en.json")
this.cancelString = this.getLocalNameForKey("cancel")
this.confirmString = this.getLocalNameForKey("confirm")
this.language = this.isZH ? "zh" : "en"
} catch (error) {
this.copy(error.message)
}
}
static copy(message){
UIPasteboard.generalPasteboard().string = message
}
static addZHConfig(config){
this._ZHConfig = {...this._ZHConfig, ...config}
}
static addENConfig(config){
this._ENConfig = {...this._ENConfig, ...config}
}
/**
*
* @param {string} path
* @returns {boolean}
*/
static isfileExists(path) {
return NSFileManager.defaultManager().fileExistsAtPath(path)
}
/**
*
* @param {string} path
* @returns {object|undefined}
*/
static readJSON(path){
if (!this.isfileExists(path)) {
return undefined
}
let data = NSData.dataWithContentsOfFile(path)
const res = NSJSONSerialization.JSONObjectWithDataOptions(
data,
1<<0
)
if (NSJSONSerialization.isValidJSONObject(res)) {
return res
}else{
return undefined
}
}
static get preferredLanguages(){
return NSLocale.preferredLanguages()
}
static getZHNameForKey(key){
try {
if (this._ZHConfig === undefined) {
this._ZHConfig = this.readJSON(this.mainPath+"/data/zh.json")
}
if (key in this._ZHConfig) {
return this._ZHConfig[key]
}else{
return this.getENNameForKey(key)
}
} catch (error) {
// this.addErrorLog(error, "Locale.getZHNameForKey",this.mainPath+"/data/zh.json")
return key
}
}
static getENNameForKey(key){
if (this._ENConfig === undefined) {
this._ENConfig = this.readJSON(this.mainPath+"/data/en.json")
}
if (key in this._ENConfig) {
return this._ENConfig[key]
}else{
return key
}
}
static getLocalNameForKey(key){
try {
if (this.isZH) {
return this.getZHNameForKey(key)
}else{
return this.getENNameForKey(key)
}
} catch (error) {
this.copy(error.message)
return key
}
}
static at(key){
try {
if (this.isZH) {
return this.getZHNameForKey(key)
}else{
return this.getENNameForKey(key)
}
} catch (error) {
this.copy(error.message)
return key
}
}
/**
* 渲染模板
* @param {string} template
* @returns {string}
*/
static render(template,additionalConfig = {}){
try {
if (this.isZH) {
return MNUtil.render(template, {...this._ZHConfig, ...additionalConfig})
}else{
return MNUtil.render(template, {...this._ENConfig, ...additionalConfig})
}
} catch (error) {
this.copy(error.message)
return template
}
}
static showHUD(message,additionalConfig = {}){
let renderedMessage = this.render(message,additionalConfig)
MNUtil.showHUD(renderedMessage)
}
}
if (typeof Frame === "undefined") {
class Frame{
static gen(x,y,width,height){
return MNUtil.genFrame(x, y, width, height)
}
/**
*
* @param {UIView} view
* @param {number} x
* @param {number} y
* @param {number} width
* @param {number} height
*/
static set(view,x,y,width,height){
let oldFrame = view.frame
let frame = view.frame
if (x !== undefined) {
frame.x = x
}else if (view.x !== undefined) {
frame.x = view.x
}
if (y !== undefined) {
frame.y = y
}else if (view.y !== undefined) {
frame.y = view.y
}
if (width !== undefined) {
frame.width = width
}else if (view.width !== undefined) {
frame.width = view.width
}
if (height !== undefined) {
frame.height = height
}else if (view.height !== undefined) {
frame.height = view.height
}
if (!this.sameFrame(oldFrame,frame)) {
view.frame = frame
}
}
static sameFrame(frame1,frame2){
if (frame1.x === frame2.x && frame1.y === frame2.y && frame1.width === frame2.width && frame1.height === frame2.height) {
return true
}
return false
}
/**
*
* @param {UIView} view
* @param {number} x
*/
static setX(view,x){
let frame = view.frame
frame.x = x
view.frame = frame
}
/**
*
* @param {UIView} view
* @param {number} y
*/
static setY(view,y){
let frame = view.frame
frame.y = y
view.frame = frame
}
/**
*
* @param {UIView} view
* @param {number} x
* @param {number} y
*/
static setLoc(view,x,y){
let frame = view.frame
frame.x = x
frame.y = y
if (view.width) {
frame.width = view.width
}
if (view.height) {
frame.height = view.height
}
view.frame = frame
}
/**
*
* @param {UIView} view
* @param {number} width
* @param {number} height
*/
static setSize(view,width,height){
let frame = view.frame
frame.width = width
frame.height = height
view.frame = frame
}
/**
*
* @param {UIView} view
* @param {number} width
*/
static setWidth(view,width){
let frame = view.frame
frame.width = width
view.frame = frame
}
/**
*
* @param {UIView} view
* @param {number} height
*/
static setHeight(view,height){
let frame = view.frame
frame.height = height
view.frame = frame
}
/**
*
* @param {UIView} view
* @param {number} xDiff
*/
static moveX(view,xDiff){
let frame = view.frame
frame.x = frame.x+xDiff
view.frame = frame
}
/**
*
* @param {UIView} view
* @param {number} yDiff
*/
static moveY(view,yDiff){
let frame = view.frame
frame.y = frame.y+yDiff
view.frame = frame
}
}
globalThis.Frame = Frame
}
class Menu{
/**
* 左 0, 下 1,3, 上 2, 右 4
* @type {number}
*/
preferredPosition = 2
/**
* @type {string[]}
*/
titles = []
constructor(sender,delegate,width = undefined,preferredPosition = 2){
this.menuController = MenuController.new()
this.delegate = delegate
this.sender = sender
this.commandTable = []
this.minWidth = 100
this.maxHeight = 0
this.menuController.rowHeight = 35
this.preferredPosition = preferredPosition
if (width && width >100) {//宽度必须大于100,否则不允许设置,即转为自动宽度
this.width = width
}
}
/**
*
* @param {UIView|MNButton} sender
* @param {Object} delegate
* @param {number} width
* @param {number} preferredPosition
* @returns {Menu}
*/
static new(sender,delegate,width = undefined,preferredPosition = 2){
if (sender instanceof MNButton) {
sender = sender.button
}
return new Menu(sender,delegate,width,preferredPosition)
}
/**
* @param {object[]} items
*/
set menuItems(items){
this.commandTable = items
}
get menuItems(){
return this.commandTable
}
/**
* @param {number} height
*/
set rowHeight(height){
this.menuController.rowHeight = height
}
get rowHeight(){
return this.menuController.rowHeight
}
/**
* @param {number} size
*/
set fontSize(size){
this.menuController.fontSize = size
}
get fontSize(){
return this.menuController.fontSize
}
addMenuItem(title,selector,params = "",checked=false){
let typeOfTitle = typeof title
if (typeOfTitle === "string") {
this.commandTable.push({title:title,object:this.delegate,selector:selector,param:params,checked:checked})
return
}
let key = title.key
let localeTitle = Locale.getLocalNameForKey(key)
if ("prefix" in title) {
localeTitle = title.prefix + localeTitle
}
if ("suffix" in title) {
localeTitle = localeTitle + title.suffix
}
this.commandTable.push({title:localeTitle,object:this.delegate,selector:selector,param:params,checked:checked})
}
addItem(title,selector,params = "",checked=false){
let typeOfTitle = typeof title
if (typeOfTitle === "string") {
this.commandTable.push({title:title,object:this.delegate,selector:selector,param:params,checked:checked})
return
}
let key = title.key
let localeTitle = Locale.getLocalNameForKey(key)
if ("prefix" in title) {
localeTitle = title.prefix + localeTitle
}
if ("suffix" in title) {
localeTitle = localeTitle + title.suffix
}
this.commandTable.push({title:localeTitle,object:this.delegate,selector:selector,param:params,checked:checked})
}
addMenuItems(items){
let fullItems = items.map(item=>{
if ("object" in item) {
return item
}else{
item.object = this.delegate
return item
}
})
this.commandTable.push(...fullItems)
}
addItems(items){
let fullItems = items.map(item=>{
if ("object" in item) {
return item
}else{
item.object = this.delegate
return item
}
})
this.commandTable.push(...fullItems)
}
insertMenuItem(index,title,selector,params = "",checked=false){
this.commandTable.splice(index,0,{title:title,object:this.delegate,selector:selector,param:params,checked:checked})
}
insertMenuItems(index,items){
let fullItems = items.map(item=>{
if ("object" in item) {
return item
}else{
item.object = this.delegate
return item
}
})
this.commandTable.splice(index,0,...fullItems)
}
show(autoWidth = false,animate = true){
try {
if (autoWidth || !this.width) {//用autoWidth参数来控制是否自动计算宽度,如果menu实例没有width参数,也会自动计算宽度
let widths = this.commandTable.map(item=>{
if (item.checked) {
return MNUtil.strCode(item.title)*9+70
}else{
return MNUtil.strCode(item.title)*9+30
}
})
this.width = Math.max(...widths)
if (this.width < this.minWidth) {
this.width = this.minWidth
}
// let titles = this.commandTable.map(item=>item.title)
// let maxWidth = 0
// // let maxWidth = this.width
// titles.forEach(title=>{
// let width = MNUtil.strCode(title)*9+30
// if (width > maxWidth) {
// maxWidth = width
// }
// })
// this.width = maxWidth
}
let position = this.preferredPosition
this.menuController.commandTable = this.commandTable
let height = this.menuController.rowHeight * this.menuController.commandTable.length
if (this.maxHeight > 50 && height > this.maxHeight) {
height = this.maxHeight
}
this.menuController.preferredContentSize = {
width: this.width,
height: this.menuController.rowHeight * this.menuController.commandTable.length
};
// this.menuController.secHeight = 200
// this.menuController.sections = [{title:"123",length:10,size:10,row:this.commandTable,rows:this.commandTable,cell:this.commandTable}]
// this.menuController.delegate = this.delegate
var popoverController = new UIPopoverController(this.menuController);
let targetView = MNUtil.studyView
var r = this.sender.convertRectToView(this.sender.bounds,targetView);
switch (position) {
case 0:
if (r.x < 50) {
position = 4
}
break;
case 1:
case 3:
if (r.y+r.height > targetView.frame.height - 50) {
position = 2
}
break;
case 2:
if (r.y < 50) {
position = 3
}
break;
case 4:
if (r.x+r.width > targetView.frame.width - 50) {
position = 0
}
break;
default:
break;
}
popoverController.presentPopoverFromRect(r, targetView, position, animate);
popoverController.delegate = this.delegate
// this.menuController.menuTableView.dataSource = this.delegate
Menu.popover = popoverController
} catch (error) {
MNUtil.addErrorLog(error, "Menu.show")
}
}
dismiss(){
if (Menu.popover) {
Menu.popover.dismissPopoverAnimated(true)
Menu.popover = undefined
}
}
static item(title,selector,params = "",checked=false){
return {title:title,selector:selector,param:params,checked:checked}
}
static popover = undefined
static dismissCurrentMenu(animate = true){
if (this.popover) {
this.popover.dismissPopoverAnimated(animate)
}
}
}
class MNUtil {
/**
* 是否正在显示alert
* @type {boolean}
*/
static onAlert = false
static themeColor = {
Gray: UIColor.colorWithHexString("#414141"),
Default: UIColor.colorWithHexString("#FFFFFF"),
Dark: UIColor.colorWithHexString("#000000"),
Green: UIColor.colorWithHexString("#E9FBC7"),
Sepia: UIColor.colorWithHexString("#F5EFDC")
}
/**
* 缓存图片类型
* {
* "xxxx": "png",
* "xxxx": "jpeg",
* }
*/
static imageTypeCache = {}
static popUpNoteInfo = undefined;
static popUpSelectionInfo = undefined;
static mainPath
static initialized = false
/**
* 数据文件夹,和插件位于同一个目录下
*/
static dataFolder = ""
static MNImagePattern = /!\[.*?\]\((marginnote4app\:\/\/markdownimg\/(png|jpeg)\/.*?)(\))/g;
/**
* @type {string}
*/
static extensionPath
static defaultNoteColors = ["#ffffb4","#ccfdc4","#b4d1fb","#f3aebe","#ffff54","#75fb4c","#55bbf9","#ea3323","#ef8733","#377e47","#173dac","#be3223","#ffffff","#dadada","#b4b4b4","#bd9fdc"]
static init(mainPath){
if (this.initialized) {
return
}
this.dotBase64 = this.getFile(Runtime.assets.resolve("assets/dot.png")).base64Encoding()
this.dotBytes = DataConverter.base64ToUint8Array(this.dotBase64)
this.mainPath = Runtime.assets.resolve("")
this.extensionPath = mainPath.replace(/\/marginnote\.extension\.\w+/,"")
this.checkDataDir()
this.initialized = true
}
static checkDataDir(){
let extensionPath = this.extensionPath
if (extensionPath) {
let dataPath = extensionPath+"/data"
if (this.isfileExists(dataPath)) {
this.dataFolder = dataPath
return
}
this.createFolderDev(dataPath)
// NSFileManager.defaultManager().createDirectoryAtPathAttributes(dataPath, undefined)
this.dataFolder = dataPath
}
}
static _currentTimerId = 0
/**
* 定时器列表
* {
* "xxxx": NSTimer,
* "xxxx": NSTimer,
* }
*/
static timers = {}
/**
* 添加定时器
* 返回定时器ID
* @returns {number}
*/
static addTimer(timer){
let timerId = MNUtil._currentTimerId++;
let timerIdString = String(timerId);
this.timers[timerIdString] = timer;
return timerId;
}
/**
* 清除定时器
* @param {number} timerId
*/
static clearTimer(timerId){
let timerIdString = String(timerId);
if (this.timers[timerIdString]) {
this.timers[timerIdString].invalidate();
delete this.timers[timerIdString];
}
}
/**
* 只记录最近十次的操作
* @type {Array<{type:string,time:number,noteId:string,text:string,imageData:NSData,notebookId:string,docMd5:string,pageIndex:number}>}
*/
static focusHistory = []
/**
* 只记录最近十次的操作
* @param {string} type
* @param {{noteId:string,text:string,imageData:NSData,notebookId:string,docMd5:string}} detail
*/
static addHistory(type,detail){
if (this.focusHistory.length>=10) {
this.focusHistory.shift()
}
let history = {type:type,time:Date.now(),...detail}
this.focusHistory.push(history)
// MNUtil.copy(this.focusHistory)
}
static errorLog = []
/**
*
* @param {string|{message:string,level:string,source:string,timestamp:number,detail:string}} error
* @param {string} source
* @param {string} info
*/
static addErrorLog(error,source,info){
MNUtil.showHUD("Runtime Error ("+source+"): "+error)
let tem = {source:source,time:(new Date(Date.now())).toString()}
if (typeof error === "string") {
tem.error = error
}else{
if (error.detail) {
tem.error = {message:error.message,detail:error.detail}
}else{
tem.error = error.message
}
}
if (info) {
tem.info = info
}
this.errorLog.push(tem)
this.copyJSON(this.errorLog)
this.log({
message:source,
level:"ERROR",
source:"MN Utils",
timestamp:Date.now(),
detail:tem
})
}
static customBtoa(str) {
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var output = '';
var idx = 0;
// 确保输入是字符串
str = String(str);
while (idx < str.length) {
// 每次读取 3 个字节
var c1 = str.charCodeAt(idx++);
var c2 = str.charCodeAt(idx++);
var c3 = str.charCodeAt(idx++);
// 将 3 个 8位字节 转换为 4 个 6位索引
var e1 = c1 >> 2;
// c1 的后2位 + c2 的前4位
var e2 = ((c1 & 3) << 4) | (c2 >> 4);
// c2 的后4位 + c3 的前2位
var e3 = ((c2 & 15) << 2) | (c3 >> 6);
// c3 的后6位
var e4 = c3 & 63;
// 处理填充逻辑 (=)
// 如果 c2 是 NaN (也就是字符串结束了),e3 和 e4 都应该是填充符
if (isNaN(c2)) {
e3 = e4 = 64; // 64 对应 chars 里的 '='
}
// 如果 c3 是 NaN,e4 应该是填充符
else if (isNaN(c3)) {
e4 = 64;
}
output += chars.charAt(e1) + chars.charAt(e2) + chars.charAt(e3) + chars.charAt(e4);
}
return output;
}
static utf8_to_b64(str) {//备用
// 第一步:使用 encodeURIComponent 将宽字符转换成 UTF-8 编码的百分号序列
// 第二步:使用 replace 将百分号序列 (%XX) 还原为单字节字符
var binaryStr = encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
function(match, p1) {
return String.fromCharCode('0x' + p1);
});
// 第三步:调用上面的基础版 btoa
return this.customBtoa(binaryStr);
}
static customAtob(input) {
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var str = String(input).replace(/=+$/, ''); // 去除末尾的 padding
var output = '';
if (str.length % 4 == 1) {
throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");
}
for (var bc = 0, bs = 0, buffer, i = 0;
buffer = str.charAt(i++);
~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
// 累积满 24 bit (4个字符) 后,解码出 3个字节
bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
) {
// 获取字符在索引表中的位置
buffer = chars.indexOf(buffer);
}
return output;
}
// 支持中文的解码封装,备用
static b64_to_utf8(str) {
// 1. 基础解码
var binaryStr = customAtob(str);
// 2. 将单字节字符还原回 %XX 格式
var percentStr = binaryStr.split('').map(function(c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join('');
// 3. 解析 URI 组件
return decodeURIComponent(percentStr);
}
static btoa(str) {
return this.customBtoa(str)
// // Encode the string to a WordArray
// const wordArray = CryptoJS.enc.Utf8.parse(str);
// // Convert the WordArray to Base64
// const base64 = CryptoJS.enc.Base64.stringify(wordArray);
// return base64;
}
/**
* 压缩配置,pako压缩效率高,但更消耗资源和时间,lz-string压缩效率低,但更节省资源和时间
* @param {object} jsonObj - 要编码的 JSON 对象
* @param {"pako"|"lz-string"} type - 压缩方式,pako或lz-string
* @returns {string} - 生成的 Base64 字符串
*/
static compressAndEncode(jsonObj,type = "pako") {
try {
const jsonString = JSON.stringify(jsonObj);
if (type == "pako") {
// 1. Gzip 压缩 (得到 Uint8Array)
const compressedUint8 = pako.gzip(jsonString);
// 2. 将 Uint8Array 转换为 CryptoJS 的 WordArray
const wordArray = CryptoJS.lib.WordArray.create(compressedUint8);
// 3. Base64 编码
const base64 = CryptoJS.enc.Base64.stringify(wordArray);
return base64;
}
if (type == "lz-string") {
const base64 = LZString.compressToBase64(jsonString);
return base64;
}
} catch (error) {
this.addErrorLog(error, "compressAndEncode")
return undefined
}
}
/**
* 解码 Base64 字符串,并使用 gzip 解压
* @param {string} base64 - 要解码的 Base64 字符串
* @returns {string} - 解压后的字符串,如果是json字符串需要自行parse为对象
*/
static decodeAndDecompress(base64,type = "pako") {
try {
if (type == "pako") {
let binaryString = this.atob(base64);
// 将二进制字符串转换为 Uint8Array,这是 pako 需要的输入格式
const charData = binaryString.split('').map(x => x.charCodeAt(0));
const binData = new Uint8Array(charData);
// 3. Gzip 解压
// 使用 pako.ungzip 进行解压
const decompressedData = pako.ungzip(binData, { to: 'string' });
return decompressedData
}
if (type == "lz-string") {
const decompressedData = LZString.decompressFromBase64(base64);
return decompressedData
}
} catch (error) {
this.addErrorLog(error, "decodeAndDecompress")
return undefined
}
}
static atob(str) {
return DataConverter.atob(str)
}
/**
* 根据指定的 scheme、host、path、query 和 fragment 生成一个完整的 URL Scheme 字符串。
* URL Scheme 完整格式:scheme://host/path?query#fragment
*
* @param {string} scheme - URL scheme,例如 'myapp'。必须提供。
* @param {string|undefined} [host] - host 部分,例如 'user_profile'。
* @param {string|string[]|undefined} [path] - path 部分,例如 'view/123'。
* @param {Object<string, string|number|boolean|object>|undefined} [query] - 查询参数对象。
* @param {string|undefined} [fragment] - fragment 标识符,即 URL 中 # 后面的部分。
* @returns {string} - 生成的完整 URL 字符串。
*/
static generateURLScheme(scheme, host, path, query, fragment) {
// 1. 处理必须的 scheme
if (!scheme) {
console.error("Scheme is a required parameter.");
return '';
}
// 2. 构建基础部分:scheme 和 host
// 即使 host 为空,也会生成 'scheme://',这对于 'file:///' 这类 scheme 是正确的
let url = `${scheme}://${host || ''}`;
// 3. 添加 path
if (path) {
if (Array.isArray(path)) {
let pathStr = path.join('/')
url += `/${pathStr.replace(/^\/+/, '')}`;
}else{
// 确保 host 和 path 之间只有一个斜杠,并处理 path 开头可能存在的斜杠
url += `/${path.replace(/^\/+/, '')}`;
}
}
// 4. 添加 query 参数
if (query && Object.keys(query).length > 0) {
const queryParts = [];
for (const key in query) {
// 确保我们只处理对象自身的属性
if (Object.prototype.hasOwnProperty.call(query, key)) {
const value = query[key];
const encodedKey = encodeURIComponent(key);
// 对值进行编码,如果是对象,则先序列化为 JSON 字符串
const encodedValue = encodeURIComponent(
typeof value === "object" && value !== null ? JSON.stringify(value) : value
);
queryParts.push(`${encodedKey}=${encodedValue}`);
}
}
if (queryParts.length > 0) {
url += `?${queryParts.join('&')}`;
}
}
// 5. 添加 fragment
if (fragment) {
// Fragment 部分不应该被编码
url += `#${fragment}`;
}
return url;
}
/**
* 解析 MarginNote 4 UIStatus URL
* @param {string} encodedURL - 完整的 marginnote4app URL, 需要先decodeURIComponent
* @returns {object|string} - 解析后的 JSON 对象或字符串,如果解析失败返回 null
*/
static parseMNUIStatusURL(encodedURL) {
try {
let urlString = decodeURIComponent(encodedURL)
// 1. 提取 Payload
// URL 格式通常为: marginnote4app://uistatus/<PAYLOAD>
const scheme = "marginnote4app://uistatus/";
if (!urlString.startsWith(scheme)) {
this.addErrorLog("不是有效的 MarginNote 4 uistatus URL", "parseMNUIStatusURL")
return null;
}
const payload = urlString.slice(scheme.length);
const binData = DataConverter.base64ToUint8Array(payload);
// 3. Gzip 解压
// 使用 pako.ungzip 进行解压
const decompressedData = pako.ungzip(binData, { to: 'string' });
// 4. 尝试解析 JSON
// MarginNote 的数据通常是 JSON 格式,但也可能是纯文本
try {
return JSON.parse(decompressedData);
} catch (e) {
// 如果不是 JSON,直接返回字符串
this.addErrorLog("解压后的数据不是标准 JSON,返回原始字符串", "parseMNUIStatusURL")
return decompressedData;
}
} catch (error) {
this.addErrorLog(error, "parseMNUIStatusURL")
return undefined;
}
}
static async getCurrentUIStatusURL(){
let command = "UIStatusURL"
this.executeCommand(command)
await this.delay(0.1)
let url = this.clipboardText
let config = this.parseMNUIStatusURL(url)
return config
}
/**
* 将 JSON 对象转换为 MarginNote 4 URL
* @param {object} jsonObj - 要编码的 JSON 对象