-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.html
More file actions
1136 lines (1032 loc) · 38.5 KB
/
app.html
File metadata and controls
1136 lines (1032 loc) · 38.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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>DFA & Regex Password Lab</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
:root {
--bg: #0f1419;
--panel: #1a1f2e;
--ink: #e8eef7;
--muted: #9da3b3;
--brand: #6366f1;
--brand-light: #818cf8;
--ok: #10b981;
--bad: #ef4444;
--line: #2d3748;
--accent: #8b5cf6;
}
* { box-sizing: border-box; }
html, body { height: 100%; margin: 0; }
body {
display: flex;
background: var(--bg);
color: var(--ink);
font: 15px/1.6 'Segoe UI', Roboto, sans-serif;
}
.sidebar {
width: 260px;
padding: 24px;
background: linear-gradient(135deg, #1a1f2e 0%, #141829 100%);
border-right: 1px solid var(--line);
position: sticky;
top: 0;
height: 100vh;
overflow-y: auto;
display: flex;
flex-direction: column;
}
.sidebar h1 {
font-size: 24px;
margin: 0 0 20px;
background: linear-gradient(135deg, var(--brand-light), var(--accent));
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
.sidebar nav {
display: flex;
flex-direction: column;
gap: 8px;
flex: 1;
}
.tab-btn {
all: unset;
padding: 12px 14px;
border-radius: 10px;
cursor: pointer;
background: transparent;
border: 1px solid transparent;
transition: all 0.3s ease;
color: var(--muted);
font-weight: 500;
}
.tab-btn:hover {
background: rgba(99, 102, 241, 0.1);
color: var(--brand-light);
border-color: var(--line);
}
.tab-btn.active {
background: linear-gradient(135deg, var(--brand), var(--accent));
color: white;
border-color: transparent;
}
.sidebar footer {
color: var(--muted);
font-size: 12px;
margin-top: auto;
padding-top: 16px;
border-top: 1px solid var(--line);
}
.content {
flex: 1;
padding: 32px;
overflow-y: auto;
}
h2 {
margin: 0 0 24px;
font-size: 28px;
color: var(--ink);
}
.row {
display: flex;
gap: 12px;
align-items: center;
flex-wrap: wrap;
margin: 16px 0;
}
.grid {
display: grid;
gap: 20px;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
}
label {
display: flex;
flex-direction: column;
gap: 8px;
font-weight: 600;
font-size: 14px;
color: var(--muted);
}
input, textarea {
background: var(--panel);
border: 1px solid var(--line);
color: var(--ink);
padding: 12px 14px;
border-radius: 8px;
font-family: inherit;
transition: all 0.3s ease;
}
input:focus, textarea:focus {
outline: none;
border-color: var(--brand);
box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
}
button {
padding: 12px 18px;
border-radius: 8px;
border: none;
background: linear-gradient(135deg, var(--brand), var(--accent));
color: white;
cursor: pointer;
font-weight: 600;
transition: all 0.3s ease;
font-size: 14px;
}
button:hover {
transform: translateY(-2px);
box-shadow: 0 8px 16px rgba(99, 102, 241, 0.3);
}
button:active {
transform: translateY(0);
}
.pill {
padding: 10px 16px;
border-radius: 20px;
background: var(--panel);
border: 1px solid var(--line);
color: var(--muted);
font-size: 13px;
font-weight: 500;
}
.cards {
list-style: none;
padding: 0;
margin: 0;
display: grid;
gap: 10px;
}
.cards li, #pwdResult > * {
background: var(--panel);
padding: 14px 16px;
border: 1px solid var(--line);
border-radius: 10px;
transition: all 0.3s ease;
}
.cards li:hover {
border-color: var(--brand);
background: rgba(99, 102, 241, 0.05);
}
.code {
background: #0f1419;
color: #a0aec0;
border: 1px solid var(--line);
border-radius: 8px;
padding: 14px;
overflow: auto;
white-space: pre-wrap;
word-break: break-word;
font-family: 'Courier New', monospace;
font-size: 12px;
max-height: 280px;
}
.viz-wrap {
background: var(--panel);
border: 1px solid var(--line);
border-radius: 12px;
padding: 12px;
margin: 12px 0;
}
.viz {
width: 100%;
height: 360px;
display: block;
}
.node { fill: var(--panel); stroke: var(--brand); stroke-width: 2; }
.node.accept { stroke: var(--ok); stroke-width: 3; }
.nodeLabel { font-size: 12px; fill: var(--ink); pointer-events: none; }
.edge { stroke: var(--line); stroke-width: 1.8; }
.edgeLabel { fill: var(--muted); font-size: 11px; }
.highlight { stroke: var(--brand-light); stroke-width: 3; }
.bad { color: var(--bad); font-weight: 600; }
.ok { color: var(--ok); font-weight: 600; }
.tab-panel { display: none; }
.tab-panel.show { display: block; }
.policy {
display: grid;
gap: 10px;
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
margin-bottom: 16px;
}
.policy label {
padding: 12px 14px;
background: var(--panel);
border: 1px solid var(--line);
border-radius: 8px;
cursor: pointer;
transition: all 0.3s ease;
margin: 0;
gap: 10px;
flex-direction: row;
align-items: center;
}
.policy label:hover {
border-color: var(--brand);
background: rgba(99, 102, 241, 0.05);
}
.policy input[type="checkbox"] {
width: auto;
margin: 0;
cursor: pointer;
}
.hint {
color: var(--muted);
font-size: 13px;
margin-top: 12px;
padding: 12px 14px;
background: rgba(99, 102, 241, 0.05);
border-left: 3px solid var(--brand);
border-radius: 4px;
}
.section-title {
font-size: 14px;
font-weight: 600;
color: var(--brand-light);
text-transform: uppercase;
letter-spacing: 1px;
margin: 20px 0 12px;
}
</style>
</head>
<body>
<aside class="sidebar">
<h1>🔐 DFA Lab</h1>
<nav>
<button class="tab-btn active" data-tab="learn">📚 Learn</button>
<button class="tab-btn" data-tab="regex">⚙️ Build Regex</button>
<button class="tab-btn" data-tab="simulate">▶️ Simulate</button>
<button class="tab-btn" data-tab="analysis">📊 Analysis</button>
<button class="tab-btn" data-tab="policy">🔒 Password Policy</button>
</nav>
<footer>
<p>Build automata from regex patterns. Understand NFAs, DFAs & validation.</p>
</footer>
</aside>
<main class="content">
<!-- LEARN -->
<section class="tab-panel show" id="learn">
<h2>Understanding DFA & Regex</h2>
<ol class="cards">
<li><strong>Tokenize & Parse</strong> – Break down regex into abstract syntax tree (AST)</li>
<li><strong>Thompson's Construction</strong> – Convert AST to NFA with ε-transitions</li>
<li><strong>Subset Construction</strong> – Transform NFA into deterministic DFA</li>
<li><strong>Simulation</strong> – Watch the automaton process your input step-by-step</li>
<li><strong>Validation</strong> – Apply to real-world password policies</li>
</ol>
<div class="hint">
<strong>Supported Features:</strong> Groups <code>()</code>, Alternation <code>|</code>, Quantifiers <code>* + ?</code>, Character classes <code>[a-z]</code>, Escapes <code>\d \w \s</code>
</div>
</section>
<!-- REGEX BUILD -->
<section class="tab-panel" id="regex">
<h2>Build: Regex → NFA → DFA</h2>
<div class="row">
<label style="flex:1">
Regex Pattern
<input id="regexInput" placeholder="e.g. (a|b)\w+\d+" />
</label>
<button id="buildBtn">Build Automata</button>
</div>
<div class="grid">
<div>
<div class="section-title">Abstract Syntax Tree</div>
<pre id="astOut" class="code"></pre>
</div>
<div>
<div class="section-title">NFA (Thompson)</div>
<div class="viz-wrap">
<svg id="nfaSvg" class="viz"></svg>
</div>
<pre id="nfaOut" class="code"></pre>
</div>
</div>
<div style="margin-top: 20px;">
<div class="section-title">DFA (Subset Construction)</div>
<div class="viz-wrap">
<svg id="dfaSvg" class="viz"></svg>
</div>
<pre id="dfaOut" class="code"></pre>
</div>
</section>
<!-- SIMULATE -->
<section class="tab-panel" id="simulate">
<h2>Simulate Input</h2>
<div class="row">
<label style="flex:1">
Input String
<input id="simInput" placeholder="Test password…" />
</label>
<button id="simStep">Step</button>
<button id="simRun">Run All</button>
<button id="simReset">Reset</button>
</div>
<div class="section-title">State Visualization</div>
<div class="viz-wrap">
<svg id="simSvg" class="viz"></svg>
</div>
<div class="row">
<div class="pill" id="simStatus">⏳ Build a DFA first</div>
</div>
<div class="section-title">Execution Log</div>
<pre id="simLog" class="code"></pre>
</section>
<!-- ANALYSIS -->
<section class="tab-panel" id="analysis">
<h2>Graph Analysis: NFA vs DFA</h2>
<div class="row">
<label>Chart Width (px)
<input id="gaWidth" type="number" value="700" style="min-width:120px" />
</label>
<label>Chart Height (px)
<input id="gaHeight" type="number" value="280" style="min-width:120px" />
</label>
<label>Y Step
<input id="gaYStep" type="number" value="2" style="min-width:80px" />
</label>
<button id="gaRender">Generate</button>
</div>
<div class="section-title">Comparison Stats</div>
<div class="cards" style="margin: 0">
<div id="gaStats" class="code"></div>
</div>
<div class="section-title">States & Transitions Chart</div>
<div class="viz-wrap">
<svg id="gaSvg" class="viz"></svg>
</div>
</section>
<!-- PASSWORD POLICY -->
<section class="tab-panel" id="policy">
<h2>Password Policy Checker</h2>
<div class="section-title">Select Rules</div>
<div class="policy">
<label><input type="checkbox" class="rule" data-regex=".{8,}"> Minimum 8 characters</label>
<label><input type="checkbox" class="rule" data-regex=".*[A-Z].*"> Uppercase letter</label>
<label><input type="checkbox" class="rule" data-regex=".*[a-z].*"> Lowercase letter</label>
<label><input type="checkbox" class="rule" data-regex=".*\\d.*"> Contains digit</label>
<label><input type="checkbox" class="rule" data-regex=".*[@#$%^&*()].*"> Special char (@#$%^&*)</label>
</div>
<div class="row">
<label style="flex:1">
Test Password
<div style="display:flex; gap:8px; align-items:center;">
<input id="pwdInput" type="password" placeholder="Enter password…" style="flex:1;" />
<button id="togglePwd" style="padding:8px 12px; width:auto;" title="Show/Hide">👁️</button>
</div>
</label>
<button id="pwdCheck">Validate</button>
</div>
<div class="section-title">Results</div>
<div id="pwdResult" class="cards"></div>
<div class="section-title">Rule Visualization</div>
<div class="viz-wrap">
<svg id="policySvg" class="viz"></svg>
</div>
</section>
</main>
<script>
(() => {
let gid = 0;
const uid = (p = "q") => `${p}${gid++}`;
const setKey = (s) => Array.from(s).sort().join(",");
const clone = (o) => JSON.parse(JSON.stringify(o));
const byId = (id) => document.getElementById(id);
// Tab switching
document.querySelectorAll(".tab-btn").forEach(btn => {
btn.addEventListener("click", () => {
document.querySelectorAll(".tab-btn").forEach(b => b.classList.remove("active"));
btn.classList.add("active");
document.querySelectorAll(".tab-panel").forEach(p => p.classList.remove("show"));
const panel = document.getElementById(btn.dataset.tab);
if (panel) panel.classList.add("show");
});
});
// Tokenizer
const Tok = {
Char:"Char", Range:"Range", LParen:"(", RParen:")", Alt:"|",
Star:"*", Plus:"+", Q:"?", EOF:"EOF"
};
const expandEscape = (c) => {
if (c === "d") return [..."0123456789"];
if (c === "w") return [..."abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_"];
if (c === "s") return [" ","\t","\n","\r"];
return [c];
};
function lexRegex(src){
const out=[];
for(let i=0;i<src.length;i++){
let c=src[i];
if(c==="\\"){
i++; if(i>=src.length) throw Error("Dangling escape");
const esc=src[i];
out.push({t:Tok.Char,v:"\\"+esc});
continue;
}
if(c==="(") out.push({t:Tok.LParen});
else if(c===")") out.push({t:Tok.RParen});
else if(c==="|") out.push({t:Tok.Alt});
else if(c==="*") out.push({t:Tok.Star});
else if(c==="+") out.push({t:Tok.Plus});
else if(c==="?") out.push({t:Tok.Q});
else if(c==="["){
const chars=[]; let j=i+1; let last=null; let invert=false;
if(src[j]==="^"){invert=true;j++;}
for(;j<src.length;j++){
let cc=src[j];
if(cc==="]") break;
if(cc==="\\"){ j++; if(j>=src.length) throw Error("Dangling escape in []");
const ex=expandEscape(src[j]); chars.push(...ex); last=ex.length===1?ex[0]:null; continue;
}
if(cc==="-" && last && j+1<src.length && src[j+1]!=="]"){
const next=src[j+1]; const a=last.charCodeAt(0), b=next.charCodeAt(0);
for(let k=a+1;k<=b;k++) chars.push(String.fromCharCode(k));
j++; last=null; continue;
}
chars.push(cc); last=cc;
}
if(j>=src.length || src[j]!=="]") throw Error("Unclosed []");
i=j;
let vals=chars;
if(invert){
const universe=Array.from({length:128},(_,k)=>String.fromCharCode(k));
const set=new Set(chars); vals=universe.filter(ch=>!set.has(ch));
}
out.push({t:Tok.Range,v:vals});
} else {
out.push({t:Tok.Char,v:c});
}
}
out.push({t:Tok.EOF});
return out;
}
// Parser
function parse(tokens){
let i=0;
const peek=()=>tokens[i];
const eat=(t)=>{ const x=tokens[i++]; if(t && x.t!==t) throw Error(`Expected ${t}`); return x; };
function regex(){ return alt(); }
function alt(){
let left=concat();
while(peek().t===Tok.Alt){ eat(); const right=concat(); left={kind:"Alt",left,right}; }
return left;
}
function concat(){
const parts=[];
while(true){
const t=peek().t;
if(t===Tok.RParen || t===Tok.EOF || t===Tok.Alt) break;
parts.push(repeat());
}
return parts.length===1?parts[0]:{kind:"Concat",parts};
}
function repeat(){
let node=atom();
while(true){
const t=peek().t;
if(t===Tok.Star){eat(); node={kind:"Star",expr:node};}
else if(t===Tok.Plus){eat(); node={kind:"Plus",expr:node};}
else if(t===Tok.Q){eat(); node={kind:"QMark",expr:node};}
else break;
}
return node;
}
function atom(){
const t=peek();
if(t.t===Tok.Char){
eat();
if(t.v.startsWith("\\")){
const chs=expandEscape(t.v.slice(1));
return chs.length===1?{kind:"Char",ch:chs[0]}:{kind:"Class",chars:chs};
}
if(t.v===".") {
const printable=[...Array.from({length:95},(_,i)=>String.fromCharCode(32+i))];
return {kind:"Class",chars:printable};
}
return {kind:"Char",ch:t.v};
}
if(t.t===Tok.Range){ eat(); return {kind:"Class",chars:t.v}; }
if(t.t===Tok.LParen){ eat(Tok.LParen); const r=regex(); eat(Tok.RParen); return r; }
throw Error("Unexpected token");
}
const ast=regex(); eat(Tok.EOF); return ast;
}
// Thompson NFA
function newState(){ return { id:uid(), trans:{}, eps:new Set() }; }
function connect(a,b,sym){
if(sym===undefined) a.eps.add(b.id);
else { if(!a.trans[sym]) a.trans[sym]=new Set(); a.trans[sym].add(b.id); }
}
function thompson(ast){
function build(n){
if(n.kind==="Char"){
const s=newState(), e=newState(); connect(s,e,n.ch); return {start:s,end:e,states:[s,e]};
}
if(n.kind==="Class"){
const s=newState(), e=newState(); n.chars.forEach(ch=>connect(s,e,ch)); return {start:s,end:e,states:[s,e]};
}
if(n.kind==="Concat"){
let acc=build(n.parts[0]);
for(let i=1;i<n.parts.length;i++){
const b=build(n.parts[i]); connect(acc.end,b.start); acc={start:acc.start,end:b.end,states:[...acc.states,...b.states]};
} return acc;
}
if(n.kind==="Alt"){
const a=build(n.left), b=build(n.right), s=newState(), e=newState();
connect(s,a.start); connect(s,b.start); connect(a.end,e); connect(b.end,e);
return {start:s,end:e,states:[s,e,...a.states,...b.states]};
}
if(n.kind==="Star"){
const a=build(n.expr), s=newState(), e=newState();
connect(s,a.start); connect(s,e); connect(a.end,a.start); connect(a.end,e);
return {start:s,end:e,states:[s,e,...a.states]};
}
if(n.kind==="Plus"){
const a=build(n.expr), s=newState(), e=newState();
connect(s,a.start); connect(a.end,a.start); connect(a.end,e);
return {start:s,end:e,states:[s,e,...a.states]};
}
if(n.kind==="QMark"){
const a=build(n.expr), s=newState(), e=newState();
connect(s,a.start); connect(s,e); connect(a.end,e);
return {start:s,end:e,states:[s,e,...a.states]};
}
throw Error("Unknown node");
}
const {start,end,states}=build(ast);
const map={}; states.forEach(s=>map[s.id]=s);
return { start:start.id, accept:new Set([end.id]), states:map };
}
// Subset Construction
function epsilonClosure(nfa, S){
const stack=[...S]; const seen=new Set(S);
while(stack.length){
const x=stack.pop();
for(const y of nfa.states[x].eps) if(!seen.has(y)){ seen.add(y); stack.push(y); }
} return seen;
}
function move(nfa,S,a){
const out=new Set();
for(const s of S){ const tr=nfa.states[s].trans[a]; if(tr) for(const t of tr) out.add(t); }
return out;
}
function nfaAlphabet(nfa){
const A=new Set(); Object.values(nfa.states).forEach(s=>Object.keys(s.trans).forEach(a=>A.add(a)));
return [...A];
}
function subsetConstruction(nfa){
const alphabet=nfaAlphabet(nfa);
const startSet=epsilonClosure(nfa,new Set([nfa.start]));
const startKey=setKey(startSet);
const Q={}, queue=[startKey];
const isAccept=S=>Array.from(nfa.accept).some(a=>S.has(a));
Q[startKey]={id:startKey,nfaSet:startSet,trans:{},accept:isAccept(startSet)};
while(queue.length){
const Ukey=queue.shift(); const U=Q[Ukey];
for(const a of alphabet){
const M=move(nfa,U.nfaSet,a);
const V=epsilonClosure(nfa,M); if(V.size===0) continue;
const Vkey=setKey(V);
if(!Q[Vkey]){ Q[Vkey]={id:Vkey,nfaSet:V,trans:{},accept:isAccept(V)}; queue.push(Vkey); }
U.trans[a]=Vkey;
}
}
return { start:startKey, states:Q, alphabet };
}
// SVG Renderers
function clearSVG(svg){
while(svg.firstChild) svg.removeChild(svg.firstChild);
const defs=document.createElementNS("http://www.w3.org/2000/svg","defs");
const marker=document.createElementNS("http://www.w3.org/2000/svg","marker");
marker.setAttribute("id","arrow");
marker.setAttribute("viewBox","0 0 10 10");
marker.setAttribute("refX","10"); marker.setAttribute("refY","5");
marker.setAttribute("markerWidth","6"); marker.setAttribute("markerHeight","6");
marker.setAttribute("orient","auto-start-reverse");
const path=document.createElementNS("http://www.w3.org/2000/svg","path");
path.setAttribute("d","M 0 0 L 10 5 L 0 10 z"); path.setAttribute("fill","#818cf8");
marker.appendChild(path); defs.appendChild(marker); svg.appendChild(defs);
}
function circleLayout(nodes, w, h){
const r=Math.min(w,h)/2 - 40;
const cx=w/2, cy=h/2;
return nodes.map((n,i)=>({id:n.id, x:cx+r*Math.cos(2*Math.PI*i/nodes.length), y:cy+r*Math.sin(2*Math.PI*i/nodes.length)}));
}
function renderDFA(svg, dfa, highlight=null){
clearSVG(svg);
const w=svg.clientWidth||800, h=svg.clientHeight||360;
const nodes=Object.values(dfa.states);
if(nodes.length===0) return;
const layout=circleLayout(nodes,w,h);
const pos={}; layout.forEach(p=>pos[p.id]=p);
for(const s of nodes){
for(const [a,t] of Object.entries(s.trans||{})){
const line=document.createElementNS("http://www.w3.org/2000/svg","line");
line.setAttribute("x1",pos[s.id].x);
line.setAttribute("y1",pos[s.id].y);
line.setAttribute("x2",pos[t].x);
line.setAttribute("y2",pos[t].y);
line.setAttribute("class","edge"+((highlight && highlight.from===s.id && highlight.to===t)? " highlight": ""));
line.setAttribute("marker-end","url(#arrow)");
svg.appendChild(line);
const tx=(pos[s.id].x+pos[t].x)/2;
const ty=(pos[s.id].y+pos[t].y)/2;
const text=document.createElementNS("http://www.w3.org/2000/svg","text");
text.setAttribute("x",tx);
text.setAttribute("y",ty);
text.setAttribute("class","edgeLabel");
text.textContent=a;
svg.appendChild(text);
}
}
for(const s of nodes){
const g=document.createElementNS("http://www.w3.org/2000/svg","g");
const c=document.createElementNS("http://www.w3.org/2000/svg","circle");
c.setAttribute("cx",pos[s.id].x);
c.setAttribute("cy",pos[s.id].y);
c.setAttribute("r","20");
c.setAttribute("class","node"+(s.accept?" accept":"")+((highlight && highlight.at===s.id)?" highlight":""));
g.appendChild(c);
if(s.accept){
const c2=document.createElementNS("http://www.w3.org/2000/svg","circle");
c2.setAttribute("cx",pos[s.id].x);
c2.setAttribute("cy",pos[s.id].y);
c2.setAttribute("r","14");
c2.setAttribute("fill","none");
c2.setAttribute("stroke","#10b981");
c2.setAttribute("stroke-width","2");
g.appendChild(c2);
}
const t=document.createElementNS("http://www.w3.org/2000/svg","text");
t.setAttribute("x",pos[s.id].x);
t.setAttribute("y",pos[s.id].y+4);
t.setAttribute("text-anchor","middle");
t.setAttribute("class","nodeLabel");
t.textContent=s.id;
g.appendChild(t);
svg.appendChild(g);
}
}
function renderNFA(svg, nfa){
clearSVG(svg);
const w=svg.clientWidth||800, h=svg.clientHeight||360;
const states=Object.values(nfa.states).map(s=>({id:s.id, accept:nfa.accept.has(s.id)}));
if(states.length===0) return;
const layout=circleLayout(states,w,h);
const pos={}; layout.forEach(p=>pos[p.id]=p);
for(const s of states){
const node=nfa.states[s.id];
for(const t of node.eps){
const line=document.createElementNS("http://www.w3.org/2000/svg","line");
line.setAttribute("x1",pos[s.id].x);
line.setAttribute("y1",pos[s.id].y);
line.setAttribute("x2",pos[t].x);
line.setAttribute("y2",pos[t].y);
line.setAttribute("class","edge");
line.setAttribute("marker-end","url(#arrow)");
svg.appendChild(line);
const tx=(pos[s.id].x+pos[t].x)/2;
const ty=(pos[s.id].y+pos[t].y)/2;
const text=document.createElementNS("http://www.w3.org/2000/svg","text");
text.setAttribute("x",tx);
text.setAttribute("y",ty);
text.setAttribute("class","edgeLabel");
text.textContent="ε";
svg.appendChild(text);
}
for(const [a,set] of Object.entries(node.trans)){
for(const t of set){
const line=document.createElementNS("http://www.w3.org/2000/svg","line");
line.setAttribute("x1",pos[s.id].x);
line.setAttribute("y1",pos[s.id].y);
line.setAttribute("x2",pos[t].x);
line.setAttribute("y2",pos[t].y);
line.setAttribute("class","edge");
line.setAttribute("marker-end","url(#arrow)");
svg.appendChild(line);
const tx=(pos[s.id].x+pos[t].x)/2;
const ty=(pos[s.id].y+pos[t].y)/2;
const text=document.createElementNS("http://www.w3.org/2000/svg","text");
text.setAttribute("x",tx);
text.setAttribute("y",ty);
text.setAttribute("class","edgeLabel");
text.textContent=a;
svg.appendChild(text);
}
}
}
for(const s of states){
const g=document.createElementNS("http://www.w3.org/2000/svg","g");
const c=document.createElementNS("http://www.w3.org/2000/svg","circle");
c.setAttribute("cx",pos[s.id].x);
c.setAttribute("cy",pos[s.id].y);
c.setAttribute("r","20");
c.setAttribute("class","node"+(s.accept?" accept":""));
g.appendChild(c);
if(s.accept){
const c2=document.createElementNS("http://www.w3.org/2000/svg","circle");
c2.setAttribute("cx",pos[s.id].x);
c2.setAttribute("cy",pos[s.id].y);
c2.setAttribute("r","14");
c2.setAttribute("fill","none");
c2.setAttribute("stroke","#10b981");
c2.setAttribute("stroke-width","2");
g.appendChild(c2);
}
const t=document.createElementNS("http://www.w3.org/2000/svg","text");
t.setAttribute("x",pos[s.id].x);
t.setAttribute("y",pos[s.id].y+4);
t.setAttribute("text-anchor","middle");
t.setAttribute("class","nodeLabel");
t.textContent=s.id;
g.appendChild(t);
svg.appendChild(g);
}
}
function inferAlphabetFromDFA(dfa){
const A=new Set();
Object.values(dfa.states).forEach(s=>{
Object.keys(s.trans||{}).forEach(a=>A.add(a));
});
return [...A];
}
function simulateString(dfa, str){
let s=dfa.start;
const path=[s];
for(const ch of str){
const trans=dfa.states[s].trans||{};
let nxt=null;
if(trans[ch]!==undefined) nxt=trans[ch];
else {
for(const [sym,target] of Object.entries(trans)){
if(sym.length>1 && sym.includes(ch)) { nxt=target; break; }
}
}
if(nxt==null) return {accepted:false, path, end:s};
s=nxt; path.push(s);
}
return {accepted: !!dfa.states[s].accept, path, end:s};
}
let CURRENT = { ast:null, nfa:null, dfa:null, sim:{state:null,idx:0,input:""} };
const astOut=byId("astOut");
const nfaOut=byId("nfaOut");
const dfaOut=byId("dfaOut");
const nfaSvg=byId("nfaSvg");
const dfaSvg=byId("dfaSvg");
const simSvg=byId("simSvg");
const simLog=byId("simLog");
const simStatus=byId("simStatus");
byId("buildBtn").addEventListener("click",()=>{
try{
gid=0;
const src=(byId("regexInput").value || "(?!)");
const toks=lexRegex(src);
const ast=parse(toks);
const nfa=thompson(ast);
const dfa=subsetConstruction(nfa);
CURRENT.ast=ast; CURRENT.nfa=nfa; CURRENT.dfa=dfa;
astOut.textContent=JSON.stringify(ast,null,2);
nfaOut.textContent=JSON.stringify(nfa,null,2);
dfaOut.textContent=JSON.stringify(dfa,null,2);
renderNFA(nfaSvg,nfa);
renderDFA(dfaSvg,dfa);
CURRENT.sim.state=dfa.start;
CURRENT.sim.idx=0;
simStatus.textContent="✅ Ready to simulate";
renderDFA(simSvg,dfa,{at:dfa.start});
}catch(e){astOut.textContent="❌ Error: "+e.message;}
});
byId("simReset").addEventListener("click",()=>{
if(!CURRENT.dfa) return;
CURRENT.sim.state=CURRENT.dfa.start;
CURRENT.sim.idx=0;
simLog.textContent="Reset.\n";
renderDFA(simSvg,CURRENT.dfa,{at:CURRENT.sim.state});
});
function simStep(){
if(!CURRENT.dfa)return;
const s=CURRENT.sim.state;
const str=byId("simInput").value;
const i=CURRENT.sim.idx;
if(i>=str.length){
simStatus.innerHTML=CURRENT.dfa.states[s].accept?"✅ Accepted":"❌ Rejected";
renderDFA(simSvg,CURRENT.dfa,{at:s});
return;
}
const ch=str[i];
const trans=CURRENT.dfa.states[s].trans||{};
let nxt = trans[ch];
if(nxt==null){
for(const [sym,target] of Object.entries(trans)){
if(sym.length>1 && sym.includes(ch)){ nxt=target; break; }
}
}
simLog.textContent+=`(${s}) --${ch}--> ${nxt}\n`;
if(!nxt){simStatus.textContent="❌ Rejected"; renderDFA(simSvg,CURRENT.dfa,{at:s}); return;}
CURRENT.sim.state=nxt; CURRENT.sim.idx++;
renderDFA(simSvg,CURRENT.dfa,{from:s,to:nxt,at:nxt});
}
byId("simStep").addEventListener("click",simStep);
byId("simRun").addEventListener("click",()=>{
const L=(byId("simInput").value||"").length;
for(let i=0;i<L+1;i++) simStep();
});
// Password Policy
const ruleBoxes = document.querySelectorAll(".rule");
const pwdInput = byId("pwdInput");
const pwdCheck = byId("pwdCheck");
const pwdResult = byId("pwdResult");
const policySvg = byId("policySvg");
// Toggle password visibility
const togglePwdBtn = byId("togglePwd");
if(togglePwdBtn){
togglePwdBtn.addEventListener("click", ()=>{
const type = pwdInput.type === "password" ? "text" : "password";
pwdInput.type = type;
togglePwdBtn.textContent = type === "password" ? "👁️" : "🙈";
});
}
function buildLengthAtLeast(n, alphabet){
const A = alphabet ?? [...Array.from({length:95}, (_,i)=>String.fromCharCode(32+i))];
const states = {};
for(let i=0;i<n;i++){
const id = "q"+i;
states[id] = {id, trans:{}, accept:false};
}
const accId = "q"+n;
states[accId] = {id:accId, trans:{}, accept:true};
for(let i=0;i<n;i++){
for(const ch of A){
const to = (i+1<=n)? "q"+(i+1) : accId;
states["q"+i].trans[ch] = to;
}
}
for(const ch of A) states[accId].trans[ch] = accId;
return { start:"q0", states, alphabet:A };
}
function compilePolicyRegexToDFA(pattern){
if(pattern.includes("{8,")){
return buildLengthAtLeast(8);
}
const ast = parse(lexRegex(pattern));
const nfa = thompson(ast);
return subsetConstruction(nfa);
}
function addResultCard(ok, label){
const div = document.createElement("div");
div.innerHTML = (ok ? "✅ " : "❌ ") + label;
if(ok) div.classList.add("ok"); else div.classList.add("bad");
pwdResult.appendChild(div);
}
if(pwdCheck){
pwdCheck.addEventListener("click",()=>{
pwdResult.innerHTML = "";
clearSVG(policySvg);
const s = (pwdInput.value ?? "");
const selected = [...ruleBoxes].filter(b=>b.checked);
if(selected.length===0){
addResultCard(false, "No rules selected.");
return;
}
let allOk = true;
let lastDFA = null;
selected.forEach(rule=>{
const pat = rule.dataset.regex;
let ok = false;
try{
const rx = new RegExp(pat);
ok = rx.test(s);
}catch(_e){
ok = false;
}
addResultCard(ok, `Rule: ${pat}`);
allOk = allOk && ok;
try{
lastDFA = compilePolicyRegexToDFA(pat);
}catch(_e){}
});
if(lastDFA){
renderDFA(policySvg, lastDFA);
}
const finalDiv = document.createElement("div");
finalDiv.innerHTML = (allOk ? "✅ Password ACCEPTED (all rules met)" : "❌ Password REJECTED (some rules failed)");
finalDiv.classList.add(allOk ? "ok" : "bad");