forked from ETWXR9/AnkeEditor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
editor.js
1341 lines (1246 loc) · 46.4 KB
/
editor.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
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
//此版本为离线版本,将图库完全重写为读取本地目录下的图片文件
const { ipcRenderer, clipboard } = require('electron');
const remote = require('@electron/remote');
const { Menu, MenuItem } = require('@electron/remote');
const electron = require('electron');
const fs = require("fs");
const { request } = require("@octokit/request");
const Sortable = require('sortablejs');
const domtoimage = require('dom-to-image');
const iconv = require('iconv-lite');
Array.prototype.remove = function (item) {
var index = this.indexOf(item);
if (index > -1) {
this.splice(index, 1);
}
};
/**
*记忆插入点位置
*/
function HandleSelectionChange() {
if (document.activeElement != inputDiv) {
return;
}
var sel = window.getSelection && window.getSelection();
// console.log("handle sel " + sel);
if (sel && sel.rangeCount > 0) {
savedRange = sel.getRangeAt(0);
// console.log("saveRange " + savedRange);
}
}
var savedRange = null;
//window
let win = null;
//maindiv
let maindiv = null
//输入栏
let inputDiv = null;
//图片栏
let picDiv = null;
//历史栏
let historyDiv = null;
//picData的json
let picData = null;
//group-div
let checkedGroup = "";
let groupDiv = null
//piccheckform
let checkedChara = [];
let checkform = null;
//'groupName:[charaName]'
let unsavedChara = {}
//font-color-input
let fontColorInput = null;
//background-color-input
let backgroundColorInput = null;
//font-size-slider
let fontSizeSlider = null;
//picsizeslider
let picSizeSlider = null;
//inputdiv离开时保存selection
let selectionOnBlur = null;
//设置
let config = {};
let useApi = false;
//文本是否有未保存的改动
let contentUnsaved = false;
//默认保存读取路径
let filePath = "";
//默认根目录路径
let rootDir;
//输入框字体限制
let maxFontSize = 50;
let minFontSize = 10;
//初始化逻辑,取得元素,注册各类事件
window.onload = () => {
rootDir = remote.app.isPackaged ? remote.process.env.PORTABLE_EXECUTABLE_DIR + "/" : "";
maindiv = document.getElementById('main-div')
inputDiv = document.getElementById('input-div');
historyDiv = document.getElementById('history-div');
picDiv = document.getElementById('picture-div');
groupDiv = document.querySelector('#group-div');
//刷新分类
groupDiv.addEventListener('mouseup', e => {
if (e.button == 2) {
reloadGroupName();
}
})
checkform = document.querySelector('#pic-check-form');
//换行逻辑
inputDiv.addEventListener('keydown', breakLineEvent);
//未保存改动状态逻辑
inputDiv.addEventListener('input', e => {
contentUnsaved = true;
})
//字体颜色
fontColorInput = document.getElementById('font-color-input');
fontColorInput.addEventListener("change", onFontColorInputChange)
//背景颜色
backgroundColorInput = document.getElementById('background-color-input');
backgroundColorInput.addEventListener("change", onBackgroundColorInputChange)
//字体大小
fontSizeSlider = document.getElementById('font-size-slider');
fontSizeSlider.addEventListener('change', onFontSizeSliderChange);
//图片大小
picSizeSlider = document.getElementById('pic-size-slider');
picSizeSlider.addEventListener('change', onPicSizeSliderChange);
//隐藏骰子历史侧边栏
document.getElementById('hide-history-button').addEventListener('click', onHideHistoryButtonClick);
//人物名称自动补全开关
document.getElementById('add-name-button').addEventListener('click', onAddNameButtonClick);
//粘贴逻辑
document.querySelector('#input-div').addEventListener("paste", (e) => {
e.stopPropagation();
e.preventDefault();
var text = '', event = (e.originalEvent || e);
text = event.clipboardData.getData('text/html') ? event.clipboardData.getData('text/html') : event.clipboardData.getData('Text');
console.log("复制数据:" + text);
text = CleanWordHTML(text);
//简化br标签
text = text.replace(/<br[^>]*>/g, "<br>");
//清理空格,防止复制时多余空格
text = text.replace(/ /g, "");
//去掉所有\n,防止复制时多出行
text = text.replace(/(\r\n|\n|\r)/gm, "");
//清理所有style
text = text.replace(/style="[^"]*"/gi, "");
//清理掉格式清理后残留的空div
text = text.replace(/<div ><\/div>/g, "");
//提取img的src,替换为纯净的img
let parser = new DOMParser();
let doc = parser.parseFromString(text, 'text/html');
// console.log(doc.body);
if (doc) {
var images = doc.getElementsByTagName('img');
let regexp = /(http|file)((?!(http|file|png|jpg|jpeg)).)*(png|jpg|jpeg)/gi;
// console.log(images);
if (images) {
[...images].forEach(img => {
var mathcSrc = img.src.match(regexp);
while (img.attributes.length > 0)
img.removeAttribute(img.attributes[0].name);
img.src = mathcSrc;
})
}
text = doc.body.innerHTML;
}
console.log("粘贴数据:" + text);
if (document.queryCommandSupported('insertHTML')) {
document.execCommand('insertHTML', false, text);
} else {
document.execCommand('paste', false, text);
}
});
//保存sel
inputDiv.addEventListener("selectstart", () => {
// console.log("Selection started in targetDiv");
document.addEventListener("selectionchange", HandleSelectionChange, false);
});
inputDiv.addEventListener("input", () => {
// console.log("input in targetDiv");
document.addEventListener("selectionchange", HandleSelectionChange);
})
//各类鼠标事件
document.onmousedown = e => {
}
convertOldPicData();
loadGroupNames();
loadConfigs();
}
//退出逻辑,保存人物JSON,保存内容
ipcRenderer.on("onquit", (event) => {
console.log("保存退出 filepath = " + filePath);
try {
if (contentUnsaved) {
let index = remote.dialog.showMessageBoxSync({
title: '提示',
type: 'info',
defaultId: 0,
message: '存在未保存内容,是否保存',
buttons: ['是', '否'],
cancelId: 2
});
if (index == 0) {
//保存然后退出
SaveContent();
// contentUnsaved = false;
remote.app.exit();
}
else if (index == 1) {
// contentUnsaved = false;
remote.app.exit();
}
} else { remote.app.exit(); }
} catch (error) {
remote.app.exit();
}
})
//#region 图库
function loadGroupNames() {
groupDiv.innerHTML = "";
//读取目录
let dirArray;//分类目录的名称(字符串组)
dirArray = getDirectories(rootDir + "图库");
console.log("读取图库" + dirArray);
dirArray.forEach((groupName) => {
//装填分类栏
let groupButton = document.createElement('div');
groupButton.className = 'group-btn';
groupButton.innerText = groupName;
groupDiv.appendChild(groupButton);
//设置颜色
if (checkedGroup == groupName) {
groupButton.style.setProperty('background', 'coral')
loadGroup(groupName);
} else {
groupButton.style.setProperty('background', 'white')
}
//组按钮点击
groupButton.addEventListener('click', e => {
//重置颜色
[...groupDiv.children].forEach(
child => {
child.style.setProperty('background', 'white')
})
e.target.style.setProperty('background', 'coral')
checkedGroup = groupName;
//加载人物目录
loadGroup(e.target.innerText);
})
})
}
function reloadGroupName() {
// win.webContents.send("winlog", "creatpicmenu里的args是" + charaname);
const menu = new Menu();
menu.append(new MenuItem({
label: '刷新图库', click() {
loadGroupNames();
}
}));
menu.popup();
}
/**
* 加载指定组目录下的人物目录
*
* @param {string} 组名称
*/
function loadGroup(groupName) {
checkform.innerHTML = "";
let charaNameArray;
try {
charaNameArray = getDirectories(rootDir + "图库/" + groupName);
} catch (error) {
loadGroupNames();
}
console.log("读取分类,内容为" + charaNameArray);
checkedGroup = groupName;
//生成人物按钮
charaNameArray.forEach(charaName => {
//创建checkbox
let charaBtn = document.createElement('div');
// charaBtn.type = 'div';
charaBtn.innerText = charaName;
charaBtn.className = 'chara-btn';
checkform.appendChild(charaBtn);
//勾选状态
if (checkedChara.find((a => a == groupName + "&&" + charaName))) {
charaBtn.style.background = "coral";
} else {
charaBtn.style.background = "white";
}
// charaBtn.id = charaName + 'btn';
//勾选人物逻辑
charaBtn.addEventListener('click', e => {
if (e.button == 0) {
let foundChecked = checkedChara.find((a => a == groupName + "&&" + charaName));
if (!foundChecked) {
loadChara(groupName, charaName);
}
else {
unloadChara(groupName, charaName);
}
}
//右击弹出删除人物按钮
if (e.button == 2) {
CreateCharaMenu(groupName, charaName);
}
});
});
}
//读取人物图片
/**
* 从人物目录中读取所有图片
*
* @param {*} groupName
* @param {*} charaName
* @return {*}
*/
function loadChara(groupName, charaName) {
//读取目录
let picFileNames = getPictureFiles(groupName, charaName);
//读取排序文件
let picSortJson = {};
try {
picSortJson = fs.readFileSync(rootDir + "图库/" + groupName + "/" + charaName + "/" + "sort.json", "utf-8");
picSortJson = JSON.parse(picSortJson);
} catch (error) {
console.log(error);
alert("检测到人物目录缺乏排序文件sort.json,已自动生成!");
}
if (!picSortJson.sort) {
picSortJson.sort = picFileNames;
}
console.log("读取排序文件结果" + picSortJson.sort);
//给排序文件添加缺少的新图片
for (let i = 0; i < picFileNames.length; i++) {
const v = picFileNames[i];
if (picSortJson.sort.indexOf(v) == -1) {
picSortJson.sort.push(v);
}
}
//给排序文件去除不存在的图片
for (let i = 0; i < picSortJson.sort.length; i++) {
const v = picSortJson.sort[i];
if (picFileNames.indexOf(v) == -1) {
picSortJson.sort.remove(v);
}
}
// console.log("picSortJson.sort = " + picSortJson.sort)
SaveSortJson(groupName, charaName, picSortJson);
let picFileUrls = new Array();
picSortJson.sort.forEach((v, i) => { picFileUrls[i] = rootDir + "图库/" + groupName + "/" + charaName + "/" + v })
//建立JSON
let charaJson;
charaJson = {
"pics": picFileUrls
}
//记录选中状态
if (checkedChara.includes(groupName + "&&" + charaName)) {
alert("加载了已经被标记为加载的人物 " + groupName + " : " + charaName);
}
checkedChara.push(groupName + "&&" + charaName);
console.log("checkedname 为 " + checkedChara);
//如果当前分类正在被选中,则重载以更新人物按钮颜色
if (checkedGroup == groupName) {
loadGroup(groupName);
}
//创建人物栏
let charaDiv = document.createElement("div");
charaDiv.className = 'chara-div';
charaDiv.id = groupName + "&&" + charaName;
document.querySelector('#picture-div').appendChild(charaDiv);
//创建人物标题
let nametitle = document.createElement("div");
nametitle.className = 'chara-name';
charaDiv.appendChild(nametitle);
nametitle.innerText = charaName;
//tooltip
let tooltip = document.createElement("span");
tooltip.className = "chara-name-tooltip";
tooltip.innerText = "(点击收起此人物)";
nametitle.appendChild(tooltip);
nametitle.addEventListener('click', e => {
//点击人物标题卸载人物
if (e.button == 0) {
unloadChara(groupName, charaName);
}
})
//创建可排序图片列表
let pictureList = document.createElement("div");
charaDiv.appendChild(pictureList);
//排序设置+排序回调更新JSON
//由于离线版更新,排序回调预计使用单独的排序json文件来实现
var sortable = Sortable.create(pictureList, {
// Called by any change to the list (add / update / remove)
onSort: function (/**Event*/evt) {
// same properties as onEnd
picSortJson.sort = [];
[...pictureList.children].forEach(img => {
let a = img.src.split("/");
picSortJson.sort.push(a[a.length - 1]);
})
SaveSortJson(groupName, charaName, picSortJson);
},
animation: 150
});
charaJson.pics.forEach(url => {
let imgelement = document.createElement("img");
imgelement.className = 'pic-button';
imgelement.src = url;
pictureList.appendChild(imgelement);
//图片信息
imgelement.setAttribute("index", charaJson.pics.indexOf(url));
//插图逻辑和删除图片
imgelement.addEventListener("click", e => {
//检查输入框是否焦点,防止插入图片到顶部。
if (e.button == 0) {
console.log("准备插入图片")
// inputDiv.focus();
// breakLine();
insertImg(e.target.src)
if (config.addname == true) {
breakLine();
document.execCommand('insertText', false, charaName + ":");
HandleSelectionChange();
}
}
})
});
}
//卸载人物图片
function unloadChara(groupName, charaName) {
let foundChecked = checkedChara.find((a => a == groupName + "&&" + charaName));
if (!foundChecked) {
alert("尝试卸载一个未加载的人物:" + groupName + " : " + charaName);
return;
}
//去除图片栏对应人物
const div = document.getElementById(groupName + "&&" + charaName);
div.parentNode.removeChild(div);
//从checkedname去除
checkedChara.remove(foundChecked);
//如果当前分类正在被选中,则重载以更新人物按钮颜色
if (checkedGroup == groupName) {
loadGroup(groupName);
}
}
//#endregion
//#region 读写
/**
* 取得目录下所有文件夹
*
* @param {*} 目录(结尾不含/)
* @return {string[]} 目录下所有文件夹名
*/
function getDirectories(path) {
return fs.readdirSync(path).filter(function (file) {
return fs.statSync(path + '/' + file).isDirectory();
});
}
/**
* 取得人物目录下所有图片url
*
* @param groupName{*} 组名称
* @param charaName{*} 人物名称
* @return {string[]} 目录下所有图片文件名
*/
function getPictureFiles(groupName, charaName) {
return fs.readdirSync(rootDir + "图库/" + groupName + "/" + charaName).filter(function (file) {
return (!fs.statSync(rootDir + "图库/" + groupName + "/" + charaName + '/' + file).isDirectory()
&& /(.jpg|.png|.jpeg|.gif|.bmp)$/.test(file)
);
});
}
//读取config
function loadConfigs() {
//读取config
let configJson;
configJson = fs.readFileSync(rootDir + "config.json", "utf-8");
config = JSON.parse(configJson);
console.log("读取config文件结果" + configJson);
// win.webContents.send("winlog", "读取config文件结果" + configJson);
//读取APIKEY
// console.log("config.randomapi: "+config.randomapi)
// configData.randomapi = config.randomapi?config.randomapi:"";
// console.log("configData.randomapi: "+configData.randomapi)
//设置字体、图片
fontColorInput.value = config.fontColor;
backgroundColorInput.value = config.backgroundColor ?? "#f5deb3";
onFontColorInputChange();
onBackgroundColorInputChange();
fontSizeSlider.value = config.fontsizeslider;
onFontSizeSliderChange();
picSizeSlider.value = config.picsizeslider;
onPicSizeSliderChange();
//设置是否隐藏历史
// onHideHistoryButtonClick(true);
historyDiv.setAttribute("style", `flex-grow:${config.hideHistoryDiv ? 0 : 1.5};`);
//设置是否带人名
// onAddNameButtonClick(true);
document.getElementById('add-name-button').innerText = config.addname ? "现在插图带人名" : "现在插图不带人名";
CheckVersion();
if (config.randomapi == "" || !config.randomapi) {
console.log("未读取到API")
useApi = false;
return 0;
}
console.log("读取到API " + config.randomapi)
fetch("https://api.random.org/json-rpc/2/invoke", {
method: "POST",
headers: {
'user-agent': 'Chrome',
'content-type': 'application/json'
},
body: JSON.stringify({
"jsonrpc": "2.0",
"method": "getUsage",
"params": {
"apiKey": config.randomapi
},
"id": 15998
})
}).then(response => {
console.log('response' + response.status)
return response.json();
})
.then(myJson => {
console.log("读取myJson " + JSON.stringify(myJson))
if (myJson.result) {
if (myJson.result.status == "running") {
console.log("成功验证APIKey");
let alertOptions = {
type: "none",
buttons: ["好耶"],
title: "提示",
message: "成功验证APIKey"
}
remote.dialog.showMessageBox(win, alertOptions)
// window.log.ShowAlert("showalert", ["成功验证APIKey", "好耶"]);
useApi = true;
return 0;
}
}
console.log("验证APIKey失败");
let alertOptions = {
type: "none",
buttons: ["坏耶"],
title: "提示",
message: "验证APIKey失败,将转换至普通随机"
}
remote.dialog.showMessageBox(win, alertOptions)
useApi = false;
});
}
//保存json
function SaveJson(args) {
console.log("SaveJson " + args[1]);
fs.writeFileSync(rootDir + args[0], args[1], "utf-8");
}
/**
* 保存排序文件
*
* @param {*} groupName
* @param {*} charaName
* @param {json} sortJson
*/
function SaveSortJson(groupName, charaName, sortJson) {
console.log("SaveSortJson " + groupName + " : " + charaName);
fs.writeFileSync(rootDir + "图库/" + groupName + "/" + charaName + "/sort.json", JSON.stringify(sortJson), "utf-8");
}
//新建
ipcRenderer.on('newcontent', () => {
if (contentUnsaved) {
const optionsSave = {
type: "question",
buttons: ["是", "否"],
title: "提示",
defaultId: 0,
message: "存在未保存的内容,是否保存?",
cancelId: 2
}
let result = remote.dialog.showMessageBoxSync(win, optionsSave);
if (result == 0) {
SaveContent();
} else if (result == 2) {
return;
}
}
contentUnsaved = false;
filePath = "";
inputDiv.innerHTML = "";
historyDiv.innerHTML = "";
})
//保存
function SaveContent() {
let contentJson = {};
contentJson.text = inputDiv.innerHTML;
contentJson.history = historyDiv.innerHTML;
// window.fs.SendContentandSave("sendcontentandsave", JSON.stringify(contentJson));
let content;
content = JSON.stringify(contentJson)
if (filePath != "") {
fs.writeFileSync(filePath, content, "utf-8");
contentUnsaved = false;
} else {
const options = {
title: "保存",
defaultPath: remote.process.env.PORTABLE_EXECUTABLE_DIR,
}
let result = remote.dialog.showSaveDialogSync(null, options);
if (result) {
fs.writeFileSync(result, content, "utf-8");
filePath = result;
contentUnsaved = false;
}
}
}
//主进程调用保存
ipcRenderer.on("getcontentandsave", (event) => {
SaveContent();
})
//读取
ipcRenderer.on("loadcontent", (event) => {
if (contentUnsaved) {
const optionsSave = {
type: "question",
buttons: ["是", "否"],
title: "提示",
defaultId: 0,
message: "存在未保存的内容,是否保存?",
cancelId: 2
}
let result = remote.dialog.showMessageBoxSync(win, optionsSave);
if (result == 0) {
SaveContent();
} else if (result == 2) {
return
}
}
const optionsLoad = {
title: "读取",
defaultPath: remote.process.env.PORTABLE_EXECUTABLE_DIR,
multiSelections: false,
}
console.log("打开对话框,参数win = " + win)
let result = remote.dialog.showOpenDialogSync(win, optionsLoad);
if (result) {
let data = fs.readFileSync(result[0], "utf-8");
filePath = result[0];
console.log("读取存档文件结果" + data);
let contentJson = JSON.parse(data);
inputDiv.innerHTML = contentJson.text;
historyDiv.innerHTML = contentJson.history;
contentUnsaved = false;
}
})
function CheckVersion() {
console.log("读取github中");
request('GET /repos/{owner}/{repo}/releases/latest', {
owner: 'ETWXR9',
repo: 'AnkeEditor'
}).then(function (result) {
document.getElementById("version-text").innerHTML = "<b>最新版本为" + result.data.name + " 点击下载</b>";
document.getElementById("version-text").addEventListener('click', e => {
e.preventDefault();
electron.shell.openExternal(result.data.html_url);
})
});
}
//导出为HTML
ipcRenderer.on("gethtmlandexport", (event) => {
const options = {
title: "导出为HTML文件",
defaultPath: process.env.PORTABLE_EXECUTABLE_DIR,
filters: [{ name: 'HTML文件', extensions: ['html'] }],
}
let result = remote.dialog.showSaveDialogSync(null, options);
if (result) {
let content = iconv.encode(inputDiv.innerHTML, "GBK")
fs.writeFileSync(result, content);
}
})
//#endregion
//#region 骰子
//实现方式,首先取得光标坐标,然后生成input元素并绝对定位,聚焦至input,input左侧是1D字样,右侧响应input输入事件即时判断输入有效性,计算总和,回车键调用随机函数,取得随机数,自动聚焦输入框并插入格式化文本(顺便记录结果)。esc键或失去焦点时自动关闭input
//掷骰子逻辑
function setDiceInput() {
//记录光标位置
const sel = document.getSelection()
const r = sel.getRangeAt(0)
const node = r.endContainer;
const offset = r.endOffset;
// console.log("执行setDiceInput")
let pos = getCaretTopPoint();
// console.log("取得光标位置" + pos.left + "," + pos.top)
let dicediv = document.createElement('div');
dicediv.className = "dice-div";
const maindiv = document.querySelector('#main-div');
maindiv.appendChild(dicediv);
dicediv.style.left = pos.left + "px";
dicediv.style.top = pos.top + "px";
let dicetip = document.createElement('div');
dicetip.className = 'dice-tip';
dicetip.innerText = '骰子';
let diceinput = document.createElement('input');
diceinput.className = 'dice-input';
diceinput.placeholder = '多个骰子(ndn)+修正...'
let dicesum = document.createElement('div');
dicesum.className = 'dice-sum';
dicediv.appendChild(dicetip);
dicediv.appendChild(diceinput);
dicediv.appendChild(dicesum);
diceinput.focus();
diceinput.addEventListener("input", (e) => {
let text = e.srcElement.value;
// console.log("检测到输入,dice内容为" + text);
text = text.replaceAll("d","*");
try{
let sum = eval(text);
dicesum.innerText = `总和:${sum}点`;
}catch(e){
console.log(`格式错误:${e}`);
dicesum.innerText = `格式错误`;
}
})
diceinput.addEventListener("keydown", (e) => {
if (e.keyCode === 13) {
e.preventDefault();
let text = e.srcElement.value;
//判空
if (text == "") return;
//关闭输入
diceinput.readOnly = true;
/**
* @description 储存最终的算式表达式。
* @warning 改该变量名时,注意后面有eval,要一起改到
* @type {string}
*/
let resultExpression = text;
//储存text中所有ndn形式的string
let diceValues = resultExpression.match(/[0-9]+d[0-9]+/g);
//检验是否有ndn, 若无, 去除输入框后退出
if(!diceValues){
dicediv.parentNode.removeChild(dicediv);
return;
}
/**
* @param {Number} inputDiceValue 输入的骰子值
* @returns {Number} 1-输入骰子值之间的随机整数值
*/
let getRandomDiceValue = (inputDiceValue)=>{
if(!useApi)return Math.floor(Math.random()*inputDiceValue+1);
//当使用Api时
//!!!未调试!!!
//调用RANDOM.ORG
let randomValue = "(-1)";
dicesum.innerText = `正在获取随机数`;
console.log("发送req" + JSON.stringify({
"jsonrpc": "2.0",
"method": "generateIntegers",
"params": {
"apiKey": config.randomapi,
"n": 1,
"min": 1,
"max": inputDiceValue
},
"id": 1751
}));
fetch("https://api.random.org/json-rpc/2/invoke", {
method: "POST",
headers: {
'user-agent': 'Chrome',
'content-type': 'application/json'
},
body: JSON.stringify({
"jsonrpc": "2.0",
"method": "generateIntegers",
"params": {
"apiKey": config.randomapi,
"n": 1,
"min": 1,
"max": inputDiceValue
},
"id": 1751
})
}).then(function (response) {
return response.json();
}).then(function (myJson) {
console.log("取得random结果 " + JSON.stringify(myJson))
if (myJson.error) {
// dicesum.innerText = `获取失败!`;
let alertOptions = {
type: "none",
buttons: ["坏耶"],
title: "提示",
message: "获取随机数失败!请检查apikey或重试"
}
remote.dialog.showMessageBox(win, alertOptions);
return 0;
}
randomValue = myJson.result.random.data[0];
});
return randomValue;
}
for(var i=0;i<diceValues.length;i++){
let [diceNum,diceValue] = diceValues[i].split("d");
console.log(`[diceNum,diceValue]: [${diceNum},${diceValue}]`);
if(diceNum>=1000 ||diceNum==0 || diceValue==0){
console.log("输出超出设定的范围");
dicediv.parentNode.removeChild(dicediv);
return;
}
let randomValue = `${getRandomDiceValue(diceValue)}`;
for(let i=2;i<=diceNum;i++){
randomValue += `+${getRandomDiceValue(diceValue)}`
}
// 多个骰子的随机值时,用括号包起来。
if(diceNum>=2){
randomValue = `(${randomValue})`;
}
console.log(`randomValue: ${randomValue}`);
resultExpression = resultExpression.replace(diceValues[i],randomValue);
}
//结算,插入总和,记录历史
dicediv.parentNode.removeChild(dicediv);
console.log(`node is ${node},offset is ${offset}`)
// inputDiv.focus();
let newR = document.createRange();
// newR.selectNode(node);
newR.setStart(node, offset);
newR.setEnd(node, offset);
console.log(`resultExpression: ${resultExpression}`);
console.log(`eval(eval("resultExpression")): ${eval(eval("resultExpression"))}`);
let finalText;
if(text.match(/^[0-9]*d[0-9]*$/)){
if(text.split("d")[0]==1){
//若输入仅为 "1dn" 的形式,直接输出结果。 1d100=5
finalText = `【${text}=${resultExpression}】`;
}
//若输入仅为 "ndn" 的形式,因为前面处理时会加个括号,这里把括号去掉,输出多个骰子和相加。2d100=20+10=30
else finalText = `【${text}=${resultExpression.replace(/\(|\)/g,"")}=${eval(eval("resultExpression"))}】`;
}else{
// 输入为多个ndn复合的形式时 "原文本=展开骰子点数的表达式=结果"。1d100+2d10=99+(6+9)=114
// 因为resultExpression带括号,所以要eval两次。
finalText = `【${text}=${resultExpression}=${eval(eval("resultExpression"))}】`;
}
newR.insertNode(document.createTextNode(finalText));
sel.removeAllRanges();
sel.addRange(newR);
newR.collapse(false);
let record = document.createElement('div');
record.className = 'history-record';
record.innerText = finalText;
historyDiv.appendChild(record);
}
else if (e.keyCode === 27 && !diceinput.readOnly) {
e.preventDefault();
dicediv.parentNode.removeChild(dicediv);
// inputDiv.focus();
let newR = document.createRange();
// newR.selectNode(node);
newR.setStart(node, offset);
newR.setEnd(node, offset);
sel.removeAllRanges()
sel.addRange(newR)
console.log(`node is ${node.id},offset is ${offset}`)
// newR.setStart(node,offset);
// newR.setEnd(node,offset);
}
})
}
/**
* Get the caret position in all cases
*
* @returns {object} left, top distance in pixels
*/
function getCaretTopPoint() {
const sel = document.getSelection()
const r = sel.getRangeAt(0)
let rect
let r2
// supposed to be textNode in most cases
// but div[contenteditable] when empty
const node = r.startContainer
const offset = r.startOffset
if (offset > 0) {
// new range, don't influence DOM state
r2 = document.createRange()
r2.setStart(node, (offset - 1))
r2.setEnd(node, offset)
// https://developer.mozilla.org/en-US/docs/Web/API/range.getBoundingClientRect
// IE9, Safari?(but look good in Safari 8)
rect = r2.getBoundingClientRect()
return { left: rect.right, top: rect.top }
} else if (offset < node.length) {
r2 = document.createRange()
// similar but select next on letter
r2.setStart(node, offset)
r2.setEnd(node, (offset + 1))
rect = r2.getBoundingClientRect()
return { left: rect.left, top: rect.top }
} else { // textNode has length
// https://developer.mozilla.org/en-US/docs/Web/API/Element.getBoundingClientRect
rect = node.getBoundingClientRect()
const styles = getComputedStyle(node)
const lineHeight = parseInt(styles.lineHeight)
const fontSize = parseInt(styles.fontSize)
// roughly half the whitespace... but not exactly
const delta = (lineHeight - fontSize) / 2
return { left: rect.left, top: (rect.top + delta) }
}
}
//#endregion
//#region 各项设置
//点击按钮后将#history-div的flex-grow设为0,如果已经为0则设置为1.5;
function onHideHistoryButtonClick() {
// console.log("点击历史button hide:"+config.hideHistoryDiv)
config.hideHistoryDiv = !config.hideHistoryDiv;
historyDiv.setAttribute("style", `flex-grow:${config.hideHistoryDiv ? 0 : 1.5};`);
SaveJson(["config.json", JSON.stringify(config)]);
}
//点击按钮后切换addName变量,改变按钮名字
function onAddNameButtonClick() {
config.addname = !config.addname;
document.getElementById('add-name-button').innerText = config.addname ? "现在插图带人名" : "现在插图不带人名";
SaveJson(["config.json", JSON.stringify(config)]);
}
function onFontSizeSliderChange() {
let v = fontSizeSlider.value;
config.fontsizeslider = v;
let size = Math.floor(v / 100 * (maxFontSize - minFontSize) + minFontSize);
// console.log("fontsliderChange");
// inputDiv.setAttribute("style", `font-size: ${size}px;`);
inputDiv.style.setProperty("--size", `${size}px`);
SaveJson(["config.json", JSON.stringify(config)]);
}
function onPicSizeSliderChange() {
let v = picSizeSlider.value;
config.picsizeslider = v;
let size = 0;
console.log("picsizesliderchange to " + v);
console.log("picsizefloor to " + Math.floor(v / 20));