-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
663 lines (595 loc) · 21.2 KB
/
main.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
import { fileToHtml, manipulateFile, stringToHtml } from './helpers/markdown.js';
import { fillNavBar } from './helpers/navBar.js';
import { metalist,metalist2str} from './blogs/meta.js'; // metalist is a list of blog metadata
import { initPage } from './helpers/init.js';
import { getWeather } from './src/Terminal/weather.js';
initPage();
import * as Terminal from '/src/Terminal/index.js';
const Data = Terminal.Data.Data;
const Parser = Terminal.Parser.Parser;
const tokenization = Terminal.Parser.tokenization;
const View = Terminal.View.View;
const animationEngine = Terminal.View.animationEngine;
const run = Terminal.Strategy.run;
const chat = Terminal.Strategy.chat;
const createCanvas = Terminal.View.createCanvas;
const infoBobble = Terminal.View.infoBobble;
const isMobile = Terminal.View.isMobile;
const trie = Terminal.Parser.commandTrie; // 获得已经注入命令行关键词的前缀树
trie.insertArray(metalist2str()); // 将 metalist 中的 title 注入前缀树
closeLoadingBar();
// ==== 页面部分 ====
let darkBG = "#0d1117";
let lightBG = "#d4dbe197";
let mode = 'dark'; // dark or light
let currentMarkdown = '/README.md'; // 当前渲染的 markdown 文件
// 获取系统是否处于 dark mode
const darkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
if (darkMode){
document.body.style.backgroundColor = darkBG;
mode = 'dark';
}else{
document.body.style.backgroundColor = lightBG;
mode = 'light';
}
function refreshContent(){ // 刷新 content
fileToHtml(currentMarkdown,document.getElementById('content'), getMDStyle(mode));
}
// ==== 终端部分 ====
const helpInfo = [
"cd : change directory",
"ls : list files",
"help : get help",
"clear : clear terminal options: -all",
"chat : enter chat mode",
"exit : exit chat mode",
"style : change style: style -dark or style -light",
"about : about me and weather & time",
"mdr : render markdown string to this page",
"echo : echo string",
"cm : current markdown file path",
"cache : cache history to localStorage",
"load : load history from localStorage and clear cache",
"nav : show navBar options: -on or -off",
];
// 将 helpInfo 中除了标点符号的单词提取至数组
let helpInfoWords = [];
helpInfo.forEach(item => {
let words = item.split(' ');
words.forEach(word => {
if (word !== '-' && word !== ':'){
helpInfoWords.push(word);
}
});
});
// 注入 前缀树
trie.insertArray(helpInfoWords);
let isChatMode = false; // 是否处于聊天模式
let myCanvas = createCanvas(document.getElementById('terminal'), window.innerWidth * 0.81, 648);
let testStyle = {
'font-family': 'monospace',
'font-size': '36px',
'color': 'white',
'background-color': 'black',
};
let data = Data.fromString(`- Use it like a regular terminal! \n- Type "help" and press enter to get help.`,trie); // 初始化 data
// console.log(data);
let c = 0;
let hc = 0; // history cursor
let canvasy = 0;
let activey = 0;
let scrollMode = false;
let i = 0;// 用于控制光标闪烁
let view = new View(data,myCanvas,testStyle);
const lineHeight = view.getLineHeight(); // 获取行高
let ctx = myCanvas.getContext('2d');
animationEngine(100/60, () => {
let y = 0;
ctx.clearRect(0,0,myCanvas.width,myCanvas.height);
if (myCanvas === document.activeElement){
if (i % 60 < 30){
y = view.render(c,hc,canvasy,true);
}else{
y = view.render(c,hc,canvasy,false);
}
}else{
y = view.render(c,hc,canvasy,false);
}
if (y > myCanvas.height && !scrollMode){
canvasy -= y - myCanvas.height;
}
activey = canvasy + hc*lineHeight;
i++;
});
// 监听键盘事件输入字母
myCanvas.addEventListener('keydown',function(e){
scrollMode = false;
// com + c or ctrl + c
if (e.key === 'c' && e.metaKey || e.key === 'c' && e.ctrlKey){
// copy cmd + c
let text = data._history[hc];
if(text){
navigator.clipboard.writeText(text).then(function() {
let info = new infoBobble('copy success','success',1000);
info.render();
}, function(err) {
console.error('Async: Could not copy text: ', err);
let info = new infoBobble('copy failed','error',1000);
info.render();
});
}else{
let info = new infoBobble('can not copy undefined','error',1000);
info.render();
}
}else if (e.key === 'v' && e.metaKey || e.key === 'v' && e.ctrlKey){
// paste cmd + v
navigator.clipboard.readText().then(function(text) {
if(text === ''){
let info = new infoBobble('paste failed: no text in clipboard','error',1000);
info.render();
}else{
let info = new infoBobble('paste success','success',1000);
info.render();
c = data.paste(c,text);
}
}, function(err) {
let info = new infoBobble('paste failed: other error','error',1000);
info.render();
});
} else if(e.key === 'z' && e.metaKey || e.key === 'z' && e.ctrlKey){
c = data.undo();
}else if(e.key === 'y' && e.metaKey || e.key === 'y' && e.ctrlKey){
c = data.redo();
}
else if (e.key.length === 1){
// 输入字母
c = data.paste(c,e.key);
let com = trie.autoComplete(data.getActiveWord(c-1));
// console.log(com);
data._candidates = com;
}
if (e.key === 'Backspace'){
// 删除字母
c = data.delete(c);
let com = trie.autoComplete(data.getActiveWord(c-1));
data._candidates = com;
}
if (e.key === 'Enter'){
if(!isChatMode){
let obj = Parser(tokenization(data._current));
c = data.enter();
run(obj,data,callBackList);
}else{
let obj = Parser(tokenization(data._current));
// only run exit command
if (obj.command === 'exit'){
c = data.enter();
run(obj,data,callBackList);
}else{
chat(data,data._current);
c = data.enter();
}
}
// 清除候选词
data._candidates = [];
data.clearUndoRedo();
}
// 按下左右键
if (e.key === 'ArrowLeft'){
if (c > 0){
c--;
}else{
c = 0;
}
}
if (e.key === 'ArrowRight'){
if (c < data._current.length){
c++;
}else{
c = data._current.length;
}
}
// 按下上下键
if (e.key === 'ArrowUp'){
hc--;
if (hc < 0){
hc = 0;
canvasy = 0;
}
activey = canvasy + hc*lineHeight;
if(activey < 0){
canvasy += lineHeight;
}
scrollMode = true;
}
if (e.key === 'ArrowDown'){
hc++;
if (hc > data._history.length - 1){
hc = data._history.length - 1;
}
activey = canvasy + hc*lineHeight;
if(activey + lineHeight >= myCanvas.height){
canvasy -= lineHeight;
}
scrollMode = true;
}
// 按下 tab 键
if (e.key === 'Tab'){
c = data.tab(c);
// 清除候选词
data._candidates = [];
}
});
// 监听鼠标滚动事件
myCanvas.addEventListener('wheel',function(e){
scrollMode = true;
canvasy -= Math.sign(e.deltaY) * lineHeight; // lineHeight 的整数倍 :确保每次滚动一行
if(canvasy > 0){
canvasy = 0;
}
activey = canvasy + hc*lineHeight;
});
// 若为移动设备则监听触摸事件
if (isMobile()){
let startY = 0;
myCanvas.addEventListener('touchstart',function(e){
scrollMode = true;
startY = e.touches[0].clientY;
});
myCanvas.addEventListener('touchmove',function(e){
scrollMode = true;
canvasy += e.touches[0].clientY - startY;
startY = e.touches[0].clientY;
if(canvasy > 0){
canvasy = 0;
}
});
}
const callBackList =
{
"cd": {
"callBack": function cd(comObj,terminal){
// 判断是否有 path
if(comObj.path){
if(comObj.path === '/'){
fileToHtml('/README.md',document.getElementById('content'), getMDStyle(mode));
terminal.writeHistory("cd success " + comObj.path + " original file content: ");
manipulateFile(comObj.path,function(data){
terminal.writeHistory(data);
});
// 更新 currentMarkdown
currentMarkdown = comObj.path;
return;
}
// 判断 path 是否在 metalist 中
let flag = false;
metalist.forEach(item => {
if (item.path === comObj.path){
flag = true;
}
});
if (flag){
fileToHtml(comObj.path,document.getElementById('content'), getMDStyle(mode));
terminal.writeHistory("cd success " + comObj.path + " original file content: ");
// let info = new infoBobble('enable scroll','success',1000);
// info.render();
let info = new infoBobble(`cd success ${comObj.path}`,'success',1000);
info.render();
manipulateFile(comObj.path,function(data){
terminal.writeHistory(data);
});
// 更新 currentMarkdown
currentMarkdown = comObj.path;
}else{
terminal.writeHistory("no such path " + comObj.path);
}
}else{
terminal.writeHistory("no path");
}
}
},
"ls": {
"callBack": function ls(comObj,terminal){
let head = ['date','command','path', 'tag', 'title'];; // 表头
// 打印表头
terminal.writeHistory(head.join(' '));
metalist.forEach(item => {
let row = [];
row.push(item.date);
row.push(item.command);
row.push(item.path);
row.push(item.tag);
row.push(item.title);
terminal.writeHistory(row.join(' '));
});
}
},
"help": {
"callBack": function help(comObj,terminal){
helpInfo.forEach(item => {
terminal.writeHistory(item);
});
}
},
"clear": {
"callBack": function clear(comObj,terminal){
terminal.clear();
canvasy = 0;
hc = 0;
c = 0;
// // 清除剪贴板
// navigator.clipboard.writeText("");
// // 清除 content
// document.getElementById('content').innerHTML = '';
// -all 选项代表清除所有内容
if (comObj.options == '-all'){
// 清除剪贴板
navigator.clipboard.writeText("");
// 清除 content
document.getElementById('content').innerHTML = '';
// 本页面的所有缓存
localStorage.clear();
}
}
},
"chat":{
"callBack": function chat(comObj,terminal){
isChatMode = true;
terminal.writeHistory("=== chat mode ===");
view.cursorColor = "#ebbbff";
view.currentRectColor = "#ebbbff";
view.currentRectBackgroundColor = "rgba(0,255,0,0.1)";
}
},
"exit":{
"callBack": function exit(comObj,terminal){
if(isChatMode){
isChatMode = false;
terminal.writeHistory("=== exit chat mode ===");
view.cursorColor = "white";
view.currentRectColor = "white";
view.currentRectBackgroundColor = null;
}else{
terminal.writeHistory("not in chat mode");
}
}
},
"style":{
"callBack": function style(comObj,terminal){
if (!comObj.options || comObj.options.length == 0){
terminal.writeHistory("no style. please input -dark or -light");
return;
}
if (comObj.options == '-dark'){
if(mode === 'dark'){
terminal.writeHistory("already in dark mode");
return;
}else{
document.body.style.backgroundColor = darkBG;
mode = 'dark';
refreshContent();
terminal.writeHistory("change to dark mode 🌙 ");
}
}else if (comObj.options == '-light'){
if(mode === 'light'){
terminal.writeHistory("already in light mode");
return;
}else{
document.body.style.backgroundColor = lightBG;
mode = 'light';
refreshContent();
terminal.writeHistory("change to light mode 🔆 ");
}
}else{
console.log(comObj.options);
terminal.writeHistory("no such style: " + comObj.options);
}
}
},
"about":{
"callBack": function about(comObj,terminal){
terminal.writeHistory("=== about ===");
terminal.writeHistory("[Powered by pcvterm.js & Gemini ✨]");
terminal.writeHistory("[春江潮水连海平,海上明月共潮生。]");
// 打印当前时间
let date = new Date();
// 格式化时间
let time = date.toLocaleString();
// 根据时间判断问候语
let hour = date.getHours();
let greeting = "";
if (hour >= 0 && hour < 6){
greeting = "good midnight 🌛";
}else if (hour >= 6 && hour < 12){
greeting = "good morning 🌞";
}else if (hour >= 12 && hour < 18){
greeting = "good afternoon 🌞";
}else{
greeting = "good evening 🌛";
}
terminal.writeHistory("current time: " + time + " " + greeting + "!");
// open loading bar
openLoadingBar();
const callBack = function(weatherData){
// terminal.writeHistory(weatherData);
weatherData.forEach(item => {
terminal.writeHistory(item);
});
terminal.writeHistory("=== end ===");
closeLoadingBar();
}
getWeather(callBack);
// 打印 网站字体
terminal.writeHistory("font-family: monospace");
},
},
"mdr":{
"callBack": function mdRender(comObj,terminal){
let md = comObj.others;
if (md){
// console.log(md);
stringToHtml(md,document.getElementById('content'), getMDStyle(mode));
}else{
terminal.writeHistory("no md string");
}
}
},
"echo":{
"callBack": function echo(comObj,terminal){
let str = comObj.others;
if (str){
terminal.writeHistory(str);
}else{
terminal.writeHistory("no string");
}
}
},
"cm":{
"callBack": function cm(comObj,terminal){
terminal.writeHistory(currentMarkdown);
console.log(currentMarkdown);
}
},
"cache":{
"callBack": function saveHistory2JSON(comObj,terminal){
let json = data.toJSON();
console.log(json);
// 将 json 缓存至浏览器
localStorage.setItem('myHistory',json);
terminal.writeHistory( `save success to ${data._timeStamp}`);
}
},
"load":{
"callBack": function loadHistoryFromJSON(comObj,terminal){
let json = localStorage.getItem('myHistory');
if (json){
// console.log(json);
data.readJSON(json);
terminal.writeHistory(`load success from ${data._timeStamp}`);
// 默认清除 cache
localStorage.removeItem('myHistory');
}else{
terminal.writeHistory("load failed");
}
}
},
"nav":{
"callBack": function nav(comObj,terminal){
if(comObj.options == '-on'){
// 检查是否已经存在 navBar 若存在则不再创建
if (document.getElementById("navBar").innerHTML !='' && document.getElementById("blogsColumn").innerHTML !=''){
terminal.writeHistory("navBar already exists");
return;
}
fillNavBar(document.getElementById('navBar'),
[
{
"text": "Home",
"action": function(){
fileToHtml('/README.md',document.getElementById('content'), getMDStyle(mode));
currentMarkdown = '/README.md';
}
},
{
'text':'toggleTerminal',
'action': function(){
// 控制 terminal 是否固定在顶部
const terminal = document.getElementById('terminal');
// 在固定模式与非固定模式之间切换
if (terminal.style.position === 'sticky'){
terminal.style.position = 'static';
terminal.style.top = '0';
terminal.style.zIndex = '1';
// 改变自身样式
this.style.backgroundColor = '#0d1117';
this.style.color = 'white';
} else {
terminal.style.position = 'sticky';
terminal.style.top = '0';
terminal.style.zIndex = '1';
// 改变自身样式
this.style.backgroundColor = 'white';
this.style.color = 'green';
}}
}
],
{
'width': '100%',
'height': 'auto',
'display': 'flex',
'flex-direction': 'row',
'align-items': 'center',
// 'border-bottom':'1px solid gray',
}
);
fillNavBar(document.getElementById("blogsColumn"),
metalist.map(item => {
return {
"text": item.title,
"action": function(){
fileToHtml(item.path, document.getElementById('content'), getMDStyle(mode));
},
"info": item.date + " " + item.tag + " " + item.title,
};
}),
{
'width': '100%',
'height': 'auto',
'display': 'flex',
'flex-direction': 'column',
'align-items': 'center',
'border-bottom':'1px solid gray',
'padding': '10px',
}
);
terminal.writeHistory("nav on");
}
else if(comObj.options == '-off'){
document.getElementById("blogsColumn").innerHTML = '';
document.getElementById("navBar").innerHTML = '';
terminal.writeHistory("nav off");
}
}
}
}
const mdStyle = {
'padding': '10px',
'font-family': 'monospace',
'font-size': '25px',
'overflow': 'auto',
'border-bottom': '1px solid white',
'border-radius': '5px',
'background-color': '#161b22',
'width': '80%',
'color': 'white',
}; // style for the markdown content
const mdStyle2 = { // 浅色主题
'padding': '10px',
'font-family': 'monospace',
'font-size': '25px',
'overflow': 'auto',
'border-bottom': '1px solid black',
'border-radius': '5px',
'background-color': 'white',
'width': '80%',
'color': 'black',
}; // style for the markdown content
function getMDStyle(mode){
if (mode === 'dark'){
return mdStyle;
}else{
return mdStyle2;
}
}
fileToHtml('/README.md',document.getElementById('content'), getMDStyle(mode));
// 在所有资源加载完成后隐藏加载动画
window.addEventListener('load', function() {
var loadingOverlay = document.getElementById('loading-overlay');
loadingOverlay.style.display = 'none';
});
function closeLoadingBar(){
document.getElementById("loading-bar").style.display = "none";
}
function openLoadingBar(){
document.getElementById("loading-bar").style.display = "block";
}