-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
1709 lines (1524 loc) · 60.5 KB
/
Copy pathapp.js
File metadata and controls
1709 lines (1524 loc) · 60.5 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
/* ==========================================================================
DOTBASHRC - BASHRC BUILDER & VISUALIZER APPLICATION SCRIPT
========================================================================== */
// Predefined Prompt Catalog
const TEMPLATES = [
{
id: 'ubuntu-default',
name: 'Ubuntu Classic',
description: 'The standard Ubuntu prompt. Safe, familiar, and colored green/blue.',
ps1: '\\[\\e[01;32m\\]\\u@\\h\\[\\e[00m\\]:\\[\\e[01;34m\\]\\w\\[\\e[00m\\]\\$ ',
tags: ['classic', 'minimal']
},
{
id: 'minimal-arrow',
name: 'Minimal Chevron',
description: 'Sleek path-only layout with a neon green arrow. Perfect for modern workspaces.',
ps1: '\\[\\e[01;34m\\]\\W\\[\\e[00m\\] \\[\\e[01;32m\\]❯\\[\\e[00m\\] ',
tags: ['minimal']
},
{
id: 'cyberpunk-neon',
name: 'Cyberpunk Gold/Cyan',
description: 'High contrast aesthetic combining neon yellow warnings, cyan hosts, and magenta paths.',
ps1: '\\[\\e[01;33m\\]⚡ \\[\\e[01;31m\\]\\u\\[\\e[90m\\]@\\[\\e[01;36m\\]\\h \\[\\e[01;35m\\]\\W\\[\\e[00m\\] \\[\\e[01;33m\\]$ \\[\\e[00m\\]',
tags: ['colorful']
},
{
id: 'git-focused',
name: 'Git-Ready Prompt',
description: 'Designed for developers. Shows username, path, and automatically queries git branch name.',
ps1: '\\[\\e[01;36m\\]\\u\\[\\e[00m\\] at \\[\\e[01;33m\\]\\w\\[\\e[01;35m\\]\\$(__git_ps1)\\[\\e[01;32m\\]\\$ \\[\\e[00m\\]',
tags: ['git', 'colorful']
},
{
id: 'dracula-theme',
name: 'Dracula Segment',
description: 'Beautiful Dracula palette colors: purple user, pink host, and cyan directory.',
ps1: '\\[\\e[01;35m\\]\\u\\[\\e[38;5;141m\\]@\\h \\[\\e[01;36m\\]\\w\\[\\e[01;32m\\] \\$ \\[\\e[00m\\]',
tags: ['colorful', 'classic']
},
{
id: 'powerline-block',
name: 'Powerline Segment',
description: 'Uses glyphs to separate blocks. Requires a Powerline-compatible font to render correctly.',
ps1: '\\[\\e[30;42m\\] \\u \\[\\e[30;44m\\]\\[\\e[37;44m\\] \\W \\[\\e[0m\\e[34m\\]\\[\\e[0m\\] \\$ ',
tags: ['powerline', 'colorful']
},
{
id: 'two-line-node',
name: 'Two-Line Architect',
description: 'Structured multi-line prompt with line connectors. Great for long paths.',
ps1: '\\[\\e[36m\\]┌─ \\[\\e[32m\\]\\u\\[\\e[37m\\]@\\[\\e[32m\\]\\h \\[\\e[90m\\][\\[\\e[33m\\]\\t\\[\\e[90m\\]] \\[\\e[34m\\]\\w\\n\\[\\e[36m\\]└─\\[\\e[35m\\]\\$ \\[\\e[0m\\]',
tags: ['classic', 'git']
},
{
id: 'monochrome-bold',
name: 'Nordic Clean',
description: 'Muted Nord theme style using whites, greys, and icy blues.',
ps1: '\\[\\e[38;5;244m\\]\\u\\[\\e[38;5;239m\\]::\\[\\e[38;5;110m\\]\\h \\[\\e[38;5;250m\\]\\W \\[\\e[38;5;110m\\]$ \\[\\e[0m\\]',
tags: ['minimal']
},
{
id: 'toxic-wasteland',
name: 'Toxic Wasteland',
description: 'Biohazard warning theme featuring glowing radioactive green highlights and red skull warnings.',
ps1: '\\[\\e[95m\\]☣ \\[\\e[01;92m\\]\\u\\[\\e[90m\\]@\\[\\e[01;32m\\]\\h \\[\\e[5;91m\\]☠\\[\\e[00m\\] \\[\\e[36m\\]\\W\\[\\e[00m\\] \\$ ',
tags: ['colorful']
},
{
id: 'ide-statusbar',
name: 'IDE Statusbar',
description: 'Uses inverted colors and chevrons to replicate a Vim or Tmux powerline status indicator line.',
ps1: '\\[\\e[38;5;232;48;5;117m\\] BASH \\[\\e[0;38;5;117;48;5;238m\\]\\[\\e[38;5;253;48;5;238m\\] \\w \\[\\e[0;38;5;238m\\]\\[\\e[0m\\] \\$ ',
tags: ['powerline', 'colorful']
},
{
id: 'emoji-minimal',
name: 'Emoji Minimalist',
description: 'Uses graphic icons (folder, lightning bolt) for structured navigation.',
ps1: '\\[\\e[0m\\]📂 \\[\\e[01;34m\\]\\W\\[\\e[00m\\] \\[\\e[33m\\]⚡\\[\\e[00m\\] \\[\\e[01;36m\\]❯\\[\\e[00m\\] ',
tags: ['minimal']
},
{
id: 'starship-rust',
name: 'Starship Style',
description: 'Modern prompt layout heavily inspired by the Rust Starship shell decorator prompt.',
ps1: '\\[\\e[01;32m\\]🚀 \\[\\e[38;5;45m\\]\\u\\[\\e[00m\\] in \\[\\e[01;34m\\]\\W\\[\\e[38;5;125m\\]\\$(__git_ps1)\\[\\e[00m\\]\\n\\[\\e[01;32m\\]❯\\[\\e[00m\\] ',
tags: ['git', 'minimal']
},
{
id: 'ssh-cloud',
name: 'Cloud Instance (SSH)',
description: 'Clean light-blue environment prompt resembling a cloud server console.',
ps1: '\\[\\e[38;5;111m\\]☁ \\[\\e[38;5;117m\\]\\u@\\h \\[\\e[38;5;153m\\]\\W \\[\\e[38;5;111m\\]☁ \\[\\e[0m\\] \\$ ',
tags: ['classic']
},
{
id: 'glitch-retro',
name: 'Glitch Retro Terminal',
description: 'Imitates a decaying CRT phosphor display with custom glitch characters and alerts.',
ps1: '\\[\\e[31m\\]\\u\\[\\e[33m\\]@\\[\\e[36m\\]\\h\\[\\e[32m\\] \\W \\[\\e[5;31m\\]■\\[\\e[0m\\] ',
tags: ['colorful']
},
{
id: 'elegant-line',
name: 'Timeline Double',
description: 'Double-row prompt tracking execution timestamps above commands.',
ps1: '\\[\\e[90m\\]\\t \\[\\e[34m\\]\\w\\[\\e[0m\\]\\n\\[\\e[32m\\]❯\\[\\e[0m\\] ',
tags: ['classic', 'minimal']
},
{
id: 'matrix-rain',
name: 'Matrix Falling Rain',
description: 'Phosphor green theme with glowing highlights. Emulates the Matrix code interface.',
ps1: '\\[\\e[32m\\]$ \\[\\e[1;32m\\]\\u\\[\\e[0;32m\\]@\\[\\e[1;32m\\]\\h\\[\\e[0;32m\\]:\\w\\$ \\[\\e[0m\\]',
tags: ['colorful', 'minimal']
}
];
// Predefined branch names for simulation
const RANDOM_BRANCHES = [
'main',
'dev',
'feature/auth-bypass',
'feature/login-ui',
'bugfix/db-leak-fix',
'release-v2.3.0',
'hotfix-patch-5'
];
const getRandomBranch = () => RANDOM_BRANCHES[Math.floor(Math.random() * RANDOM_BRANCHES.length)];
// App State
const state = {
config: {
username: 'guest',
hostname: 'linux',
directory: '~/projects/dotbashrc',
gitBranch: getRandomBranch(),
gitEnabled: true,
isRoot: false,
exitStatusFailed: false
},
ps1: TEMPLATES[0].ps1,
terminalTheme: 'dracula',
activeCategory: 'all',
searchQuery: '',
// Extended state for bashrc generator
aliases: {
git: true,
nav: true,
safe: false,
custom: [
{ name: 'c', value: 'clear' }
]
},
functions: {
mkcd: true,
extract: true,
weather: false,
todo: false
},
options: {
autocd: true,
cdspell: true,
globstar: true,
histsize: 10000,
histfilesize: 20000,
ignoredups: true,
ignorespace: true,
timestamp: true
},
// Active simulated todo checklist tasks
todoList: [
'[ ] Learn advanced bash scripting configurations',
'[ ] Customize my prompt theme in dotbashrc dashboard'
]
};
// ==========================================================================
// COLOR HELPER
// ==========================================================================
function get256RGB(n) {
if (n < 8) {
const standardColors = [
'var(--term-black)', 'var(--term-red)', 'var(--term-green)', 'var(--term-yellow)',
'var(--term-blue)', 'var(--term-magenta)', 'var(--term-cyan)', 'var(--term-white)'
];
return standardColors[n];
}
if (n < 16) {
const brightColors = [
'var(--term-bright-black)', 'var(--term-bright-red)', 'var(--term-bright-green)', 'var(--term-bright-yellow)',
'var(--term-bright-blue)', 'var(--term-bright-magenta)', 'var(--term-bright-cyan)', 'var(--term-bright-white)'
];
return brightColors[n - 8];
}
if (n >= 16 && n <= 231) {
const r = Math.floor((n - 16) / 36);
const g = Math.floor(((n - 16) % 36) / 6);
const b = (n - 16) % 6;
const val = [0, 95, 135, 175, 215, 255];
return `rgb(${val[r]}, ${val[g]}, ${val[b]})`;
}
if (n >= 232 && n <= 255) {
const gray = 8 + (n - 232) * 10;
return `rgb(${gray}, ${gray}, ${gray})`;
}
return 'initial';
}
// ==========================================================================
// PS1 PARSER ENGINE
// ==========================================================================
function parsePS1(ps1Str, config) {
const username = config.username || 'guest';
const hostname = config.hostname || 'localhost';
const shortHost = hostname.split('.')[0];
const directory = config.directory || '~';
// Calculate short directory base name
let shortDir = directory;
if (directory === '/') {
shortDir = '/';
} else {
const parts = directory.replace(/\/$/, '').split('/');
shortDir = parts[parts.length - 1] || '/';
}
// Git integration
const gitBranchText = config.gitEnabled && config.gitBranch ? ` (${config.gitBranch})` : '';
// Time & Date strings
const pad = (n) => String(n).padStart(2, '0');
const now = new Date();
const dateStr = now.toDateString().substring(0, 10);
const time24 = `${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`;
let hours12 = now.getHours() % 12;
hours12 = hours12 ? hours12 : 12;
const time12 = `${pad(hours12)}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`;
const ampm = now.getHours() >= 12 ? 'PM' : 'AM';
const timeAmpm = `${pad(hours12)}:${pad(now.getMinutes())} ${ampm}`;
const time24Short = `${pad(now.getHours())}:${pad(now.getMinutes())}`;
// Exit status indicator
const shellSymbol = config.isRoot ? '#' : '$';
const segments = [];
// Active formatting state variables
let bold = false;
let underline = false;
let blink = false;
let fg = null;
let bg = null;
let inlineStyles = {};
// Tokenizer pattern matches: ANSI codes, escaped brackets, macros, and plain strings
const tokenRegex = /(\\e\[[0-9;]*m|\\033\[[0-9;]*m|\\x1b\[[0-9;]*m|\\\[|\\\]|\\u|\\h|\\H|\\w|\\W|\\d|\\t|\\T|\\@|\\A|\\s|\\v|\\V|\\\$|\\n|\\r|\\\\|\\?\\$\\(__git_ps1\\)|[^\$\\\x1b\[\]]+|.)/g;
const matches = ps1Str.match(tokenRegex) || [];
for (let token of matches) {
if (token.startsWith('\\e[') || token.startsWith('\\033[') || token.startsWith('\\x1b[')) {
const paramMatch = token.match(/\[([0-9;]*)m/);
if (paramMatch) {
const paramStr = paramMatch[1];
const codes = paramStr ? paramStr.split(';').map(Number) : [0];
for (let i = 0; i < codes.length; i++) {
const code = codes[i];
if (code === 0) {
bold = false;
underline = false;
blink = false;
fg = null;
bg = null;
inlineStyles = {};
} else if (code === 1) {
bold = true;
} else if (code === 4) {
underline = true;
} else if (code === 5) {
blink = true;
} else if (code >= 30 && code <= 37) {
fg = (code - 30).toString();
} else if (code === 38) {
// Extended 256 or RGB color mode for foreground
if (codes[i + 1] === 5 && i + 2 < codes.length) {
const colorNum = codes[i + 2];
fg = `color256-${colorNum}`;
inlineStyles.color = get256RGB(colorNum);
i += 2;
} else if (codes[i + 1] === 2 && i + 4 < codes.length) {
const r = codes[i + 2];
const g = codes[i + 3];
const b = codes[i + 4];
fg = 'color-rgb';
inlineStyles.color = `rgb(${r},${g},${b})`;
i += 4;
}
} else if (code === 39) {
fg = null;
delete inlineStyles.color;
} else if (code >= 40 && code <= 47) {
bg = (code - 40).toString();
} else if (code === 48) {
// Extended 256 or RGB color mode for background
if (codes[i + 1] === 5 && i + 2 < codes.length) {
const colorNum = codes[i + 2];
bg = `color256-${colorNum}`;
inlineStyles.backgroundColor = get256RGB(colorNum);
i += 2;
} else if (codes[i + 1] === 2 && i + 4 < codes.length) {
const r = codes[i + 2];
const g = codes[i + 3];
const b = codes[i + 4];
bg = 'color-rgb';
inlineStyles.backgroundColor = `rgb(${r},${g},${b})`;
i += 4;
}
} else if (code === 49) {
bg = null;
delete inlineStyles.backgroundColor;
} else if (code >= 90 && code <= 97) {
fg = `bright-${code - 90}`;
} else if (code >= 100 && code <= 107) {
bg = `bright-${code - 100}`;
}
}
}
} else if (token === '\\[' || token === '\\]') {
// Ignored non-printing character wrappers
continue;
} else {
let segmentText = '';
let isSpecial = false;
let type = '';
switch (token) {
case '\\u':
segmentText = username;
isSpecial = true;
type = 'username';
break;
case '\\h':
segmentText = shortHost;
isSpecial = true;
type = 'hostname';
break;
case '\\H':
segmentText = hostname;
isSpecial = true;
type = 'hostname-full';
break;
case '\\w':
segmentText = directory;
isSpecial = true;
type = 'directory';
break;
case '\\W':
segmentText = shortDir;
isSpecial = true;
type = 'directory-base';
break;
case '\\d':
segmentText = dateStr;
isSpecial = true;
type = 'date';
break;
case '\\t':
segmentText = time24;
isSpecial = true;
type = 'time-24';
break;
case '\\T':
segmentText = time12;
isSpecial = true;
type = 'time-12';
break;
case '\\@':
segmentText = timeAmpm;
isSpecial = true;
type = 'time-ampm';
break;
case '\\A':
segmentText = time24Short;
isSpecial = true;
type = 'time-24-short';
break;
case '\\s':
segmentText = 'bash';
isSpecial = true;
type = 'shell';
break;
case '\\v':
segmentText = '5.0';
isSpecial = true;
type = 'version';
break;
case '\\V':
segmentText = '5.0.17';
isSpecial = true;
type = 'release';
break;
case '\\$':
segmentText = shellSymbol;
isSpecial = true;
type = 'symbol';
break;
case '\\n':
segmentText = '\n';
isSpecial = true;
type = 'newline';
break;
case '\\r':
segmentText = '\r';
isSpecial = true;
type = 'carriage-return';
break;
case '\\\\':
segmentText = '\\';
break;
case '$(__git_ps1)':
case '\\$(__git_ps1)':
segmentText = gitBranchText;
isSpecial = true;
type = 'git-branch';
break;
default:
segmentText = token;
}
segments.push({
text: segmentText,
rawToken: token,
bold,
underline,
blink,
fg,
bg,
inlineStyles: { ...inlineStyles },
isSpecial,
type
});
}
}
return segments;
}
// Safe renderer that protects against XSS
function renderPS1ToElement(segments, container) {
if (!container) return;
container.replaceChildren();
segments.forEach(seg => {
if (seg.text === '\n') {
container.appendChild(document.createElement('br'));
return;
}
if (seg.text === '\r') {
return;
}
const span = document.createElement('span');
span.textContent = seg.text; // Safe text insertion prevents XSS
if (seg.bold) span.classList.add('ansi-bold');
if (seg.underline) span.classList.add('ansi-underline');
if (seg.blink) span.classList.add('ansi-blink');
// Mapped class colors
if (seg.fg) {
if (seg.fg.startsWith('color256-') || seg.fg === 'color-rgb') {
span.style.color = seg.inlineStyles.color;
} else {
span.classList.add(`ansi-fg-${seg.fg}`);
}
}
if (seg.bg) {
if (seg.bg.startsWith('color256-') || seg.bg === 'color-rgb') {
span.style.backgroundColor = seg.inlineStyles.backgroundColor;
} else {
span.classList.add(`ansi-bg-${seg.bg}`);
}
}
container.appendChild(span);
});
}
// Update both Terminal Prompts, Exports, and Breakdowns
function updateAllPreviews() {
const segments = parsePS1(state.ps1, state.config);
// Render main active terminal prompt
const activePromptContainer = document.getElementById('terminal-prompt-preview');
if (activePromptContainer) {
renderPS1ToElement(segments, activePromptContainer);
}
// Update exports
updateExportOutput();
// Render PS1 Syntax inspector breakdown
updateSyntaxBreakdown(segments);
}
// ==========================================================================
// EXPORTS DYNAMIC ~/.BASHRC COMPILER
// ==========================================================================
function updateExportOutput() {
const codeOutput = document.getElementById('code-export-output');
if (!codeOutput) return;
let exportBlock = `# ==========================================================================\n`;
exportBlock += `# CUSTOM BASHRC CONFIGURATION\n`;
exportBlock += `# Generated dynamically via dotbashrc — https://deep5050.github.io/dotbashrc/\n`;
exportBlock += `# ==========================================================================\n\n`;
// 1. History Settings
exportBlock += `# --- Terminal History Rules ---\n`;
exportBlock += `export HISTSIZE=${state.options.histsize}\n`;
exportBlock += `export HISTFILESIZE=${state.options.histfilesize}\n`;
let histcontrol = [];
if (state.options.ignoredups) histcontrol.push('ignoredups');
if (state.options.ignorespace) histcontrol.push('ignorespace');
if (histcontrol.length > 0) {
exportBlock += `export HISTCONTROL=${histcontrol.join(':')}\n`;
}
if (state.options.timestamp) {
exportBlock += `export HISTTIMEFORMAT="%Y-%m-%d %H:%M:%S "\n`;
}
exportBlock += `\n`;
// 2. Shell Toggles (shopt)
exportBlock += `# --- Shell Options (shopt) ---\n`;
if (state.options.autocd) exportBlock += `shopt -s autocd 2>/dev/null\n`;
if (state.options.cdspell) exportBlock += `shopt -s cdspell 2>/dev/null\n`;
if (state.options.globstar) exportBlock += `shopt -s globstar 2>/dev/null\n`;
exportBlock += `\n`;
// 3. Git prompt helper
if (state.config.gitEnabled) {
exportBlock += `# --- Git Prompt Integration Helper ---\n`;
exportBlock += `# Source git-sh-prompt to automatically extract active repository branches.\n`;
exportBlock += `if [ -f /usr/lib/git-core/git-sh-prompt ]; then\n`;
exportBlock += ` . /usr/lib/git-core/git-sh-prompt\n`;
exportBlock += `elif [ -f /etc/bash_completion.d/git-prompt ]; then\n`;
exportBlock += ` . /etc/bash_completion.d/git-prompt\n`;
exportBlock += `fi\n\n`;
}
// 4. Prompt configuration (PS1)
exportBlock += `# --- Terminal Prompt (PS1) ---\n`;
exportBlock += `export PS1="${state.ps1}"\n\n`;
// 5. Aliases
exportBlock += `# --- Command Aliases ---\n`;
if (state.aliases.git) {
exportBlock += `# Git shortcuts\n`;
exportBlock += `alias g='git'\n`;
exportBlock += `alias gs='git status'\n`;
exportBlock += `alias gp='git push'\n`;
exportBlock += `alias gd='git diff'\n`;
exportBlock += `alias gcm='git commit -m'\n`;
}
if (state.aliases.nav) {
if (!exportBlock.endsWith('\n\n')) exportBlock += `\n`;
exportBlock += `# Directory navigation\n`;
exportBlock += `alias ..='cd ..'\n`;
exportBlock += `alias ...='cd ../..'\n`;
exportBlock += `alias ll='ls -laF --color=auto'\n`;
exportBlock += `alias la='ls -A --color=auto'\n`;
}
if (state.aliases.safe) {
if (!exportBlock.endsWith('\n\n')) exportBlock += `\n`;
exportBlock += `# Interactive safeguards\n`;
exportBlock += `alias rm='rm -i'\n`;
exportBlock += `alias cp='cp -i'\n`;
exportBlock += `alias mv='mv -i'\n`;
}
if (state.aliases.custom.length > 0) {
if (!exportBlock.endsWith('\n\n')) exportBlock += `\n`;
exportBlock += `# User custom aliases\n`;
state.aliases.custom.forEach(item => {
const escapedValue = item.value.replace(/'/g, "'\\''");
exportBlock += `alias ${item.name}='${escapedValue}'\n`;
});
}
exportBlock += `\n`;
// 6. Functions
if (state.functions.mkcd) {
exportBlock += `# Create directory and navigate into it\n`;
exportBlock += `function mkcd() {\n`;
exportBlock += ` mkdir -p "$1" && cd "$1"\n`;
exportBlock += `}\n\n`;
}
if (state.functions.extract) {
exportBlock += `# Smart universal archive extractor\n`;
exportBlock += `function extract() {\n`;
exportBlock += ` if [ -f "$1" ] ; then\n`;
exportBlock += ` case "$1" in\n`;
exportBlock += ` *.tar.bz2) tar xjf "$1" ;;\n`;
exportBlock += ` *.tar.gz) tar xzf "$1" ;;\n`;
exportBlock += ` *.bz2) bunzip2 "$1" ;;\n`;
exportBlock += ` *.rar) unrar x "$1" ;;\n`;
exportBlock += ` *.gz) gunzip "$1" ;;\n`;
exportBlock += ` *.tar) tar xf "$1" ;;\n`;
exportBlock += ` *.tbz2) tar xjf "$1" ;;\n`;
exportBlock += ` *.tgz) tar xzf "$1" ;;\n`;
exportBlock += ` *.zip) unzip "$1" ;;\n`;
exportBlock += ` *.Z) uncompress "$1" ;;\n`;
exportBlock += ` *.7z) 7z x "$1" ;;\n`;
exportBlock += ` *) echo "'$1' cannot be extracted via extract()" ;;\n`;
exportBlock += ` esac\n`;
exportBlock += ` else\n`;
exportBlock += ` echo "'$1' is not a valid file"\n`;
exportBlock += ` fi\n`;
exportBlock += `}\n\n`;
}
if (state.functions.weather) {
exportBlock += `# Fetch command-line weather forecast summary\n`;
exportBlock += `function weather() {\n`;
exportBlock += ` curl -s "https://wttr.in/\${1:-London}?1m" || echo "Failed to fetch weather data"\n`;
exportBlock += `}\n\n`;
}
if (state.functions.todo) {
exportBlock += `# Simple file-based todo manager\n`;
exportBlock += `function todo() {\n`;
exportBlock += ` local TODO_FILE="$HOME/.todo.txt"\n`;
exportBlock += ` if [ "$1" = "add" ]; then\n`;
exportBlock += ` shift\n`;
exportBlock += ` echo "[ ] $*" >> "$TODO_FILE"\n`;
exportBlock += ` echo "Task added."\n`;
exportBlock += ` elif [ "$1" = "done" ]; then\n`;
exportBlock += ` sed -i "\${2}s/\\[ \\]/\\[x\\]/" "$TODO_FILE"\n`;
exportBlock += ` echo "Task marked as done."\n`;
exportBlock += ` elif [ "$1" = "clear" ]; then\n`;
exportBlock += ` > "$TODO_FILE"\n`;
exportBlock += ` echo "Todo list cleared."\n`;
exportBlock += ` else\n`;
exportBlock += ` if [ -f "$TODO_FILE" ]; then\n`;
exportBlock += ` nl -w2 -s'. ' "$TODO_FILE"\n`;
exportBlock += ` else\n`;
exportBlock += ` echo "No tasks. Run 'todo add <task>' to get started!"\n`;
exportBlock += ` fi\n`;
exportBlock += ` fi\n`;
exportBlock += `}\n\n`;
}
codeOutput.textContent = exportBlock.trim() + '\n';
}
// ==========================================================================
// SYNTAX BREAKDOWN GENERATOR
// ==========================================================================
function updateSyntaxBreakdown(segments) {
const breakdownContainer = document.getElementById('ps1-breakdown');
if (!breakdownContainer) return;
breakdownContainer.replaceChildren();
segments.forEach(seg => {
const tokenDiv = document.createElement('div');
tokenDiv.className = 'inspector-token';
const tokenTag = document.createElement('span');
tokenTag.className = 'token-tag';
tokenTag.textContent = seg.rawToken;
tokenDiv.appendChild(tokenTag);
const tokenDesc = document.createElement('span');
tokenDesc.className = 'token-desc';
let description = '';
if (seg.isSpecial) {
switch (seg.type) {
case 'username': description = 'Username (reads variable)'; break;
case 'hostname': description = 'Short Hostname (reads variable)'; break;
case 'hostname-full': description = 'Full Hostname'; break;
case 'directory': description = 'Full Working Directory Path'; break;
case 'directory-base': description = 'Base Directory Name Only'; break;
case 'date': description = 'Formatted Date'; break;
case 'time-24': description = '24-hour Time (HH:MM:SS)'; break;
case 'time-12': description = '12-hour Time (HH:MM:SS)'; break;
case 'time-ampm': description = '12-hour Time with AM/PM'; break;
case 'time-24-short': description = '24-hour Time short (HH:MM)'; break;
case 'shell': description = 'Shell Program Name'; break;
case 'version': description = 'Shell major version'; break;
case 'release': description = 'Shell release version'; break;
case 'symbol': description = 'Prompt indicator ($ or #)'; break;
case 'newline': description = 'Line break (splits prompt)'; break;
case 'git-branch': description = 'Git Branch indicator'; break;
default: description = 'Special Macro';
}
} else if (seg.rawToken.startsWith('\\e[') || seg.rawToken.startsWith('\\033[')) {
description = 'Color/style formatting';
} else {
description = `Literal Text "${seg.text}"`;
}
tokenDesc.textContent = `→ ${description}`;
tokenDiv.appendChild(tokenDesc);
if (seg.fg) {
if (seg.fg.startsWith('color256-') || seg.fg === 'color-rgb') {
tokenTag.style.color = seg.inlineStyles.color;
} else {
tokenTag.classList.add(`ansi-fg-${seg.fg}`);
}
}
if (seg.bg) {
if (seg.bg.startsWith('color256-') || seg.bg === 'color-rgb') {
tokenTag.style.backgroundColor = seg.inlineStyles.backgroundColor;
} else {
tokenTag.classList.add(`ansi-bg-${seg.bg}`);
}
}
breakdownContainer.appendChild(tokenDiv);
});
}
// ==========================================================================
// CUSTOM ALIAS BUILDER VIEW RENDERER
// ==========================================================================
function renderCustomAliasesList() {
const container = document.getElementById('custom-aliases-list');
if (!container) return;
container.replaceChildren();
if (state.aliases.custom.length === 0) {
const emptyMsg = document.createElement('div');
emptyMsg.className = 'text-muted';
emptyMsg.style.fontSize = '12px';
emptyMsg.textContent = 'No custom aliases configured yet.';
container.appendChild(emptyMsg);
return;
}
state.aliases.custom.forEach((item, idx) => {
const itemDiv = document.createElement('div');
itemDiv.className = 'alias-item';
const textSpan = document.createElement('span');
textSpan.className = 'alias-item-text';
textSpan.textContent = `alias ${item.name}='${item.value}'`;
itemDiv.appendChild(textSpan);
const deleteBtn = document.createElement('button');
deleteBtn.className = 'alias-delete-btn';
deleteBtn.textContent = '×';
deleteBtn.title = 'Remove alias';
deleteBtn.addEventListener('click', () => {
state.aliases.custom.splice(idx, 1);
renderCustomAliasesList();
updateExportOutput();
});
itemDiv.appendChild(deleteBtn);
container.appendChild(itemDiv);
});
}
// Safe error helper to prevent alert dialogue blocking
function showAliasError(msg) {
let errSpan = document.getElementById('alias-error');
if (!errSpan) {
errSpan = document.createElement('span');
errSpan.id = 'alias-error';
errSpan.style.color = '#ff5f56';
errSpan.style.fontSize = '11px';
errSpan.style.marginTop = '4px';
errSpan.style.display = 'none';
const form = document.querySelector('.custom-alias-form');
if (form) form.appendChild(errSpan);
}
if (msg) {
errSpan.textContent = msg;
errSpan.style.display = 'block';
} else {
errSpan.style.display = 'none';
}
}
// ==========================================================================
// INTERACTIVE CONSOLE SYSTEM (TERMINAL PREVIEW)
// ==========================================================================
function getMockFileList(isLong) {
const currentDir = state.config.directory;
let files = ['LICENSE', 'README.md', 'app.js', 'index.html', 'style.css'];
if (currentDir === '~') {
files = ['projects'];
} else if (currentDir === '~/projects') {
files = ['dotbashrc', 'another-app'];
} else if (currentDir.startsWith('~/projects/dotbashrc/')) {
files = ['src', 'assets', 'package.json'];
}
if (isLong) {
const pre = document.createElement('pre');
pre.style.fontFamily = 'var(--font-mono)';
pre.style.fontSize = '13px';
pre.style.lineHeight = '1.4';
let totalSize = files.length * 4;
// Header total line
const totalDiv = document.createElement('div');
totalDiv.textContent = `total ${totalSize}`;
pre.appendChild(totalDiv);
files.forEach(f => {
const isDir = (f === 'projects' || f === 'dotbashrc' || f === 'another-app' || f === 'src' || f === 'assets');
const perm = isDir ? 'drwxr-xr-x' : '-rw-r--r--';
const links = isDir ? '3' : '1';
const size = isDir ? '4096' : (f === 'app.js' ? '40354' : (f === 'style.css' ? '28217' : '13251'));
const colorClass = isDir ? 'color: var(--term-blue); font-weight: bold;' : (f.endsWith('.js') ? 'color: var(--term-green); font-weight: bold;' : 'color: var(--term-fg);');
const spanLine = document.createElement('div');
spanLine.style.display = 'flex';
spanLine.style.gap = '14px';
const metaSpan = document.createElement('span');
metaSpan.style.color = 'var(--term-dim)';
metaSpan.textContent = `${perm} ${links} guest linux ${String(size).padStart(5)} Jun 20 01:10`;
const nameSpan = document.createElement('span');
nameSpan.textContent = f;
nameSpan.setAttribute('style', colorClass);
spanLine.appendChild(metaSpan);
spanLine.appendChild(nameSpan);
pre.appendChild(spanLine);
});
return pre;
} else {
const div = document.createElement('div');
div.style.display = 'flex';
div.style.flexWrap = 'wrap';
div.style.gap = '16px';
div.style.fontFamily = 'var(--font-mono)';
files.forEach(f => {
const span = document.createElement('span');
span.textContent = f;
const isDir = (f === 'projects' || f === 'dotbashrc' || f === 'another-app' || f === 'src' || f === 'assets');
if (isDir) {
span.style.color = 'var(--term-blue)';
span.style.fontWeight = 'bold';
} else if (f.endsWith('.js')) {
span.style.color = 'var(--term-green)';
span.style.fontWeight = 'bold';
} else {
span.style.color = 'var(--term-fg)';
}
div.appendChild(span);
});
return div;
}
}
function getMockWeather() {
const pre = document.createElement('pre');
pre.style.color = 'var(--term-yellow)';
pre.style.fontFamily = 'var(--font-mono)';
pre.style.lineHeight = '1.3';
pre.textContent =
`Weather report: ${state.config.hostname} (Simulated Location)
\\ /
.-. Sunny & Warm
― ( ) ― Temp: 26°C / 79°F
\`-\` Wind: NNE at 8 mph
/ \\ Humidity: 45%
UV Index: 6 (High)
Forecast: Clear skies with cooling terminal breeze tonight.`;
return pre;
}
function getMockTodo(args) {
const sub = args[0] ? args[0].toLowerCase() : '';
const taskText = args.slice(1).join(' ');
const output = document.createElement('div');
output.style.fontFamily = 'var(--font-mono)';
if (sub === 'add') {
if (!taskText) {
output.style.color = 'var(--term-red)';
output.textContent = 'Usage: todo add <task description>';
} else {
state.todoList.push(`[ ] ${taskText}`);
output.textContent = `Task added: "${taskText}"`;
}
} else if (sub === 'done') {
const idx = parseInt(args[1], 10) - 1;
if (isNaN(idx) || idx < 0 || idx >= state.todoList.length) {
output.style.color = 'var(--term-red)';
output.textContent = 'Usage: todo done <task_number>';
} else {
state.todoList[idx] = state.todoList[idx].replace('[ ]', '[x]');
output.textContent = `Task ${idx + 1} marked as completed!`;
}
} else if (sub === 'clear') {
state.todoList = [];
output.textContent = 'Todo checklist cleared successfully.';
} else {
if (state.todoList.length === 0) {
output.textContent = 'No active tasks found. Type "todo add <task>" to write a checklist item!';
} else {
const pre = document.createElement('pre');
pre.style.lineHeight = '1.4';
let content = 'My Todo Checklist:\n';
state.todoList.forEach((t, i) => {
content += ` ${i + 1}. ${t}\n`;
});
pre.textContent = content;
output.appendChild(pre);
}
}
return output;
}
function handleCdCommand(targetDir) {
let currentDir = state.config.directory;
if (!targetDir || targetDir === '~') {
state.config.directory = '~';
} else if (targetDir === '..') {
if (currentDir === '~/projects/dotbashrc') {
state.config.directory = '~/projects';
} else if (currentDir === '~/projects') {
state.config.directory = '~';
} else if (currentDir.startsWith('~/projects/dotbashrc/')) {
state.config.directory = '~/projects/dotbashrc';
}
} else if (targetDir === '../..') {
state.config.directory = '~';
} else {
let matchedDir = targetDir;
if (state.options.cdspell) {
if (targetDir === 'prjects') matchedDir = 'projects';
if (targetDir === 'dotbashr') matchedDir = 'dotbashrc';
}
if (currentDir === '~' && matchedDir === 'projects') {
state.config.directory = '~/projects';
} else if (currentDir === '~/projects' && matchedDir === 'dotbashrc') {
state.config.directory = '~/projects/dotbashrc';
} else {
// Allow dynamic folders
state.config.directory = currentDir + '/' + targetDir;
}
if (state.options.cdspell && matchedDir !== targetDir) {
return `${matchedDir}/ (spelling corrected from ${targetDir}/)`;
}
}
return '';
}
function syncStateToDOMInputs() {
const dirInput = document.getElementById('input-directory');
if (dirInput) {
dirInput.value = state.config.directory;
}
const titleBar = document.getElementById('terminal-window-title');
if (titleBar) {
titleBar.textContent = `bash — ${state.config.username}@${state.config.hostname}: ${state.config.directory}`;
}
}
function setupTerminalSimulator() {
const terminalInput = document.getElementById('terminal-input');
const terminalInputDisplay = document.getElementById('terminal-input-display');
const terminalScreen = document.getElementById('terminal-screen');
const terminalHistory = document.getElementById('terminal-history');
if (!terminalInput || !terminalScreen || !terminalHistory) return;