-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
614 lines (558 loc) · 41.6 KB
/
index.html
File metadata and controls
614 lines (558 loc) · 41.6 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>AirGapQR PRO | Secure Data Transfer</title>
<script src="lib/tailwind-3.4.1.min.js"></script>
<script src="lib/pako-2.0.3.min.js"></script>
<script src="lib/qrious-4.0.2.min.js"></script>
<script src="lib/html5-qrcode-2.3.8.min.js"></script>
<!-- Engines -->
<script src="lib/engine-fountain.js"></script>
<script src="lib/engine-sequential.js"></script>
<style>
body { background-color: #f8fafc; font-family: ui-sans-serif, system-ui, sans-serif; -webkit-tap-highlight-color: transparent; }
.card { background: white; border-radius: 1.5rem; box-shadow: 0 10px 25px -5px rgba(0,0,0,0.05), 0 8px 10px -6px rgba(0,0,0,0.05); }
.nav-btn { padding: 0.5rem 1.25rem; border-radius: 0.75rem; font-weight: 800; font-size: 0.75rem; letter-spacing: 0.05em; transition: all 0.2s; color: #94a3b8; text-transform: uppercase; }
.nav-btn.active { background: white; color: #2563eb; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1); }
.btn-primary { background: #2563eb; color: white; font-weight: 800; border-radius: 1rem; transition: all 0.2s; box-shadow: 0 4px 14px 0 rgba(37,99,235,0.39); }
.btn-primary:active { transform: scale(0.98); }
.grid-dot { width: 100%; aspect-ratio: 1; background: #e2e8f0; border-radius: 2px; transition: all 0.3s; }
.grid-dot.received { background: #22c55e; box-shadow: 0 0 8px rgba(34,197,94,0.5); }
.recv-row { display: grid; grid-template-columns: 32px repeat(20, 1fr); gap: 3px; align-items: center; margin-bottom: 3px; }
.row-num { font-family: ui-monospace, monospace; font-size: 9px; color: #94a3b8; font-weight: bold; text-align: right; padding-right: 6px; }
#reader { width: 100%; aspect-ratio: 1 / 1 !important; background: black; overflow: hidden; position: relative; border-radius: 1.5rem; }
.dual-range { position: relative; width: 100%; height: 6px; background: #e2e8f0; border-radius: 3px; margin: 20px 0; }
.slider-track { position: absolute; top: 0; bottom: 0; background: #2563eb; opacity: 0.5; border-radius: 3px; z-index: 1; pointer-events: auto; cursor: grab; }
.slider-track:active { cursor: grabbing; }
.dual-range input[type=range] { position: absolute; pointer-events: none; -webkit-appearance: none; appearance: none; z-index: 2; height: 6px; width: 100%; background: none; margin: 0; padding: 0; }
.dual-range input[type=range]::-webkit-slider-thumb { -webkit-appearance: none; appearance: none; pointer-events: auto; width: 24px; height: 24px; border-radius: 50%; background: #2563eb; cursor: pointer; border: 4px solid white; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1), 0 2px 4px -1px rgba(0,0,0,0.06); }
input[type=range] { -webkit-appearance: none; appearance: none; width: 100%; height: 6px; background: #e2e8f0; border-radius: 3px; outline: none; }
input[type=range]::-webkit-slider-thumb { -webkit-appearance: none; appearance: none; width: 18px; height: 18px; border-radius: 50%; background: #2563eb; cursor: pointer; border: 3px solid white; box-shadow: 0 2px 4px rgba(0,0,0,0.1); pointer-events: auto; }
.inline-input { background: transparent; border: none; font-weight: 900; color: inherit; width: 45px; outline: none; transition: background 0.2s; border-radius: 4px; }
.inline-input:focus { background: #eff6ff; color: #2563eb; }
.inline-input::-webkit-outer-spin-button, .inline-input::-webkit-inner-spin-button { -webkit-appearance: none; margin: 0; }
.shortcut-hint { font-size: 10px; color: #94a3b8; margin-top: 2rem; text-align: center; border-top: 1px dashed #e2e8f0; padding-top: 1rem; }
kbd { background: #f1f5f9; border: 1px solid #e2e8f0; border-radius: 4px; padding: 2px 4px; font-family: inherit; font-weight: 800; color: #64748b; margin: 0 2px; box-shadow: 0 1px 0 rgba(0,0,0,0.05); }
</style>
</head>
<body class="p-4 sm:p-8">
<div class="max-w-2xl mx-auto">
<!-- Header -->
<div class="flex flex-col sm:flex-row justify-between items-center bg-slate-200/50 p-1.5 rounded-xl mb-8">
<h1 onclick="window.location.reload()"
class="px-4 py-2 font-black text-xl italic tracking-tighter cursor-pointer hover:opacity-80 transition-opacity">
AirGap<span class="text-blue-600 relative inline-block">QR<span id="edition-badge" class="absolute top-0.5 left-full ml-0.5 px-1 py-0 h-2 flex items-center leading-none bg-blue-600 text-white text-[6px] rounded-sm uppercase not-italic tracking-normal">Pro</span></span>
</h1>
<!-- Engine Toggle Switch -->
<div class="flex items-center bg-slate-300/30 p-1 rounded-lg gap-1 mb-2 sm:mb-0">
<button onclick="setEngine('fountain')" id="mode-fountain" class="px-3 py-1.5 rounded-md text-[10px] font-black uppercase transition-all">Fountain</button>
<button onclick="setEngine('classic')" id="mode-classic" class="px-3 py-1.5 rounded-md text-[10px] font-black uppercase transition-all">Classic</button>
</div>
<div class="flex gap-1 w-full sm:w-auto">
<button onclick="switchTab('send')" id="nav-send" class="nav-btn active flex-1 sm:flex-none">Sender</button>
<button onclick="switchTab('receive')" id="nav-receive" class="nav-btn flex-1 sm:flex-none">Receiver</button>
</div>
</div>
<!-- SENDER SECTION -->
<div id="view-send" class="space-y-6">
<div class="card p-6 space-y-6">
<!-- Data Source Selection -->
<div class="flex gap-2">
<button onclick="setSendMode('file')" id="mode-file" class="flex-1 py-2 rounded-xl text-[10px] font-black uppercase tracking-widest bg-blue-600 text-white shadow-lg transition-all">File Mode</button>
<button onclick="setSendMode('text')" id="mode-text" class="flex-1 py-2 rounded-xl text-[10px] font-black uppercase tracking-widest bg-slate-100 text-slate-500 hover:bg-slate-200 transition-all">Text Mode</button>
</div>
<!-- Input Zones -->
<div id="drop-zone" class="border-2 border-dashed border-slate-200 rounded-2xl p-8 text-center hover:border-blue-400 hover:bg-blue-50/30 transition-all cursor-pointer" onclick="document.getElementById('fileInput').click()">
<input type="file" id="fileInput" class="hidden" onchange="handleFileSelect(event)">
<div id="file-placeholder" class="space-y-2">
<div class="text-blue-600 mx-auto w-12 h-12">
<svg fill="none" stroke="currentColor" stroke-width="2.5" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M12 4.5v15m7.5-7.5h-15"/></svg>
</div>
<p class="text-sm font-bold text-slate-600">Drop file or Click to browse</p>
<p class="text-[10px] text-slate-400 uppercase tracking-widest font-black">Secure Local Encapsulation</p>
</div>
<div id="file-selected" class="hidden">
<p id="selected-file-name" class="font-bold text-blue-600 truncate"></p>
<p id="selected-file-info" class="text-[10px] text-slate-400 uppercase font-bold mt-1"></p>
<button onclick="resetSender(); event.stopPropagation();" class="text-[10px] text-red-500 font-bold mt-2 uppercase">Reset</button>
</div>
</div>
<div id="text-zone" class="hidden">
<textarea id="textInput" placeholder="Paste secure message..." oninput="handleTextInput()"
class="w-full h-32 p-4 bg-slate-50 border border-slate-200 rounded-xl text-sm focus:outline-none focus:border-blue-400 resize-none font-mono"></textarea>
<div class="flex justify-between mt-2"><span id="text-count" class="text-[10px] font-bold text-slate-400 px-2 uppercase">0 CHARS</span></div>
</div>
<!-- Global Settings -->
<div class="grid grid-cols-2 gap-6 p-4 bg-slate-50 rounded-2xl">
<div class="space-y-2">
<div class="flex justify-between items-center text-[10px] font-bold text-slate-400 uppercase">
<span>SPEED (FPS)</span>
<input type="number" id="fps-input" value="12" min="1" max="15" onchange="updateFPS(this.value, 'input')" onkeydown="if(event.key==='Enter')this.blur()" class="inline-input text-blue-600">
</div>
<input type="range" id="fps-slider" min="1" max="15" value="12" oninput="updateFPS(this.value, 'slider')" class="w-full">
</div>
<div class="space-y-2">
<div class="flex justify-between items-center text-[10px] font-bold text-slate-400 uppercase">
<span>QR SIZE</span>
<input type="number" id="chunk-input" value="250" min="100" max="500" step="50" onchange="updateChunkSize(this.value, 'input')" onkeydown="if(event.key==='Enter')this.blur()" class="inline-input text-blue-600">
</div>
<input type="range" id="chunk-slider" min="100" max="500" value="250" step="50" oninput="updateChunkSize(this.value, 'slider')" class="w-full">
</div>
</div>
<div class="pt-2">
<button id="btn-start" disabled onclick="startTransfer()" class="w-full py-5 uppercase text-xs font-black tracking-[0.2em] btn-primary disabled:opacity-50 disabled:shadow-none hover:shadow-blue-500/40 hover:-translate-y-0.5 transition-all">Launch Air-Beam</button>
</div>
</div>
<!-- Active Transfer Box -->
<div id="transfer-box" class="hidden transition-all duration-500 card p-6 space-y-6 border-t-4 border-blue-600">
<div class="flex justify-between items-end">
<div class="space-y-1">
<p class="text-[10px] font-black text-slate-400 uppercase tracking-widest">Active session</p>
<p class="text-2xl font-black italic tracking-tighter">BEAMING <span id="current-frame" class="text-blue-600 inline-block min-w-[1.5em]">0</span><span class="text-slate-300 font-normal"> / <span id="total-frames">0</span></span></p>
</div>
<div class="flex items-center gap-1">
<button onclick="prevFrame()" class="p-2 text-slate-400 hover:text-blue-600 transition-colors"><svg width="20" height="20" fill="none" stroke="currentColor" stroke-width="3"><path d="M15 18l-6-6 6-6"/></svg></button>
<button id="btn-pause" onclick="togglePause()" class="btn-primary px-6 py-2 uppercase text-[10px] tracking-widest">PLAY</button>
<button onclick="nextFrame()" class="p-2 text-slate-400 hover:text-blue-600 transition-colors"><svg width="20" height="20" fill="none" stroke="currentColor" stroke-width="3"><path d="m9 18 6-6-6-6"/></svg></button>
</div>
</div>
<div id="qr-focus-area" class="bg-slate-50 p-6 rounded-3xl border-2 border-slate-100 shadow-inner flex justify-center items-center overflow-hidden">
<canvas id="qrcode-canvas" style="width: 100%; max-width: 400px; height: auto;"></canvas>
</div>
<div class="space-y-2">
<div class="flex justify-between items-center text-[10px] font-bold text-slate-400 uppercase">
<span>Range Selector</span>
<div class="flex items-center text-blue-600 font-mono">
<button onclick="shiftRange('prev')" class="p-1 hover:bg-white rounded transition-colors text-slate-400 hover:text-blue-600">
<svg width="12" height="12" fill="none" stroke="currentColor" stroke-width="3"><path d="M8 10L4 6l4-4"/></svg>
</button>
<input type="number" id="input-start" value="1" min="1" onchange="handleRangeInput('input-start')" onkeydown="if(event.key==='Enter')this.blur()" class="inline-input text-right">
<span class="opacity-20 px-0.5 select-none">-</span>
<input type="number" id="input-end" value="1" min="1" onchange="handleRangeInput('input-end')" onkeydown="if(event.key==='Enter')this.blur()" class="inline-input text-left">
<button onclick="shiftRange('next')" class="p-1 hover:bg-white rounded transition-colors text-slate-400 hover:text-blue-600">
<svg width="12" height="12" fill="none" stroke="currentColor" stroke-width="3"><path d="M4 10l4-4-4-4"/></svg>
</button>
</div>
</div>
<div class="dual-range">
<div id="slider-active-track" class="slider-track"></div>
<input type="range" id="range-start-slider" min="1" value="1" oninput="handleRangeInput('start')">
<input type="range" id="range-end-slider" min="1" value="1" oninput="handleRangeInput('end')">
</div>
</div>
</div>
<div class="shortcut-hint uppercase tracking-tighter font-bold opacity-80">
<kbd>S</kbd> / <kbd>R</kbd> Switch Tab • <kbd>F</kbd> / <kbd>T</kbd> Send Mode • <kbd>Enter</kbd> Prepare • <kbd>Space</kbd> Play/Pause • <kbd>Esc</kbd> Reset
</div>
</div>
<!-- RECEIVER SECTION -->
<div id="view-receive" class="hidden space-y-6">
<div class="card overflow-hidden">
<div id="reader">
<div class="absolute inset-0 z-10 pointer-events-none border-t-[15vh] border-b-[15vh] border-l-[10vw] border-r-[10vw] border-black/40 flex items-center justify-center">
<div class="w-64 h-64 border-2 border-blue-500/80 rounded-3xl shadow-[0_0_40px_rgba(59,130,246,0.3)]"></div>
</div>
</div>
<div class="p-6 space-y-4">
<div class="flex gap-2">
<button id="btn-toggle-scan" onclick="toggleScan()" class="btn-primary flex-[2] py-4 uppercase text-xs tracking-widest">Scan Now</button>
<button id="id-reset-recv" onclick="resetReceiver()" class="flex-1 bg-slate-200 text-slate-600 font-bold rounded-xl text-xs uppercase hover:bg-slate-300 transition-all">Reset</button>
</div>
<div id="receive-status-box" class="space-y-4 pt-4 border-t border-slate-100">
<div class="flex justify-between items-center text-[10px] font-bold text-slate-400 uppercase">
<span>Reception Progress</span>
<span id="receive-stats" class="text-blue-600">0 / 0</span>
</div>
<div id="receive-grid" class="max-h-[300px] overflow-y-auto pr-1"></div>
</div>
<div id="receive-file-info" class="hidden bg-blue-50 p-4 rounded-2xl border border-blue-100 text-[11px] font-bold text-blue-700 truncate text-center"></div>
</div>
</div>
<div id="success-card" class="hidden bg-green-500 p-8 rounded-3xl text-center text-white space-y-6 shadow-xl">
<div class="w-16 h-16 bg-white/20 rounded-full flex items-center justify-center mx-auto">
<svg width="32" height="32" fill="none" stroke="currentColor" stroke-width="4"><path d="M5 13l4 4L19 7"/></svg>
</div>
<div>
<h2 class="text-2xl font-black italic tracking-tighter">DATA RECOVERED!</h2>
<p id="success-file-name" class="text-xs opacity-80 mt-1 truncate"></p>
</div>
<div id="text-preview-box" class="hidden space-y-2">
<textarea id="text-result" readonly class="w-full h-32 p-4 bg-white/10 border border-white/20 rounded-xl text-[11px] font-mono text-white resize-none focus:outline-none"></textarea>
<button onclick="copyReceivedText(this)" class="w-full py-2 bg-white/20 hover:bg-white/30 rounded-lg text-[10px] font-bold uppercase transition-colors">Copy to clipboard</button>
</div>
<button id="btn-download" class="w-full bg-white text-green-600 py-4 rounded-xl font-bold uppercase text-xs shadow-lg transform active:scale-95 transition-all">Save & Download</button>
</div>
</div>
</div>
<script>
const state = {
engineMode: 'fountain', // 'fountain' or 'classic'
tab: 'send', sendMode: 'file',
fps: 12, chunkSize: 250, originalSize: 0, file: null, fileData: null, textData: "",
compressedLength: 0, sessionChunkSize: 0, gzippedData: null, chunks: [],
k: 0, rangeStart: 0, rangeEnd: 0, frameIdx: 0,
isTransferring: false, isPaused: true, isInitialManifest: true,
tid: "", timer: null, qr: null, sprayed: 0, needsPrepare: true,
recv: { active: false, scanner: null, recovered: false, tid: "", k: 0, fileName: "",
blockSize: 0, originalSize: 0, receivedBlocks: {}, solved: new Map(), droplets: [] }
};
window.onload = () => {
state.qr = new QRious({ element: document.getElementById('qrcode-canvas'), size: 400, level: 'M' });
setEngine('fountain');
initSliderDrag();
processUrlParams();
setupHotkeys();
};
function processUrlParams() {
try {
const params = new URLSearchParams(window.location.search);
const mode = params.get('mode');
const text = params.get('text');
if (mode === 'text' || text) {
switchTab('send');
setSendMode('text');
if (text) {
try {
document.getElementById('textInput').value = decodeURIComponent(text);
} catch(e) {
document.getElementById('textInput').value = text;
}
handleTextInput();
} else {
setTimeout(() => document.getElementById('textInput').focus(), 300);
}
} else if (mode === 'file' || mode === 'send') {
switchTab('send');
setSendMode('file');
}
} catch (e) {
console.warn("Failed to parse URL params", e);
}
}
function setEngine(mode) {
if (state.isTransferring) resetSender();
state.engineMode = mode;
const isFountain = mode === 'fountain';
document.getElementById('mode-fountain').className = isFountain ? "px-3 py-1.5 rounded-md text-[10px] font-black uppercase bg-blue-600 text-white shadow-sm" : "px-3 py-1.5 rounded-md text-[10px] font-black uppercase text-slate-400 hover:text-slate-600";
document.getElementById('mode-classic').className = !isFountain ? "px-3 py-1.5 rounded-md text-[10px] font-black uppercase bg-slate-600 text-white shadow-sm" : "px-3 py-1.5 rounded-md text-[10px] font-black uppercase text-slate-400 hover:text-slate-600";
document.getElementById('edition-badge').innerText = isFountain ? "Fountain" : "Classic";
document.getElementById('edition-badge').className = `absolute top-0.5 left-full ml-0.5 px-1 py-0 h-2 flex items-center leading-none text-white text-[6px] rounded-sm uppercase not-italic tracking-normal ${isFountain?'bg-blue-600':'bg-slate-400'}`;
}
const activeEngine = () => state.engineMode === 'fountain' ? window.EngineFountain : window.EngineSequential;
function updateFPS(v, source) { v = Math.min(15, parseInt(v)||1); state.fps=v; (source==='input'?document.getElementById('fps-slider'):document.getElementById('fps-input')).value=v; if(state.isTransferring) restartTimer(); }
function updateChunkSize(v, source) {
const val = parseInt(v) || 250; state.chunkSize = val;
if(source==='slider') document.getElementById('chunk-input').value = val;
else document.getElementById('chunk-slider').value = val;
state.needsPrepare = true;
}
async function prepareChunks() {
let dataArr;
if (state.sendMode === 'file') { if (!state.file) return; dataArr = new Uint8Array(await state.file.arrayBuffer()); }
else { if (!state.textData) return; dataArr = new TextEncoder().encode(state.textData); }
state.originalSize = dataArr.length;
const gzipped = pako.gzip(dataArr, { level: 9, header: { time: 0 } });
state.compressedLength = gzipped.length;
state.sessionChunkSize = state.chunkSize;
// Call underlying engine
state.chunks = activeEngine().prepare(gzipped, state.sessionChunkSize);
state.k = state.chunks.length;
state.rangeStart = 0; state.rangeEnd = state.k - 1;
updatePlaybackRangeUI();
}
async function startTransfer() {
// Re-calculate exactly when 'PREPARE' (Enter/Launch) is triggered
if (state.file || state.textData) await prepareChunks();
if (state.chunks.length === 0) return;
state.tid = Math.random().toString(36).substring(2, 6).toUpperCase();
state.isInitialManifest = true; state.isPaused = true; state.isTransferring = true;
state.frameIdx = state.rangeStart;
document.getElementById('transfer-box').classList.remove('hidden');
document.getElementById('total-frames').innerText = state.k;
document.getElementById('btn-pause').innerText = "PLAY";
state.needsPrepare = false;
renderFrame();
setTimeout(() => document.getElementById('transfer-box').scrollIntoView({ behavior: 'smooth', block: 'start' }), 100);
}
function renderFrame() {
if (state.engineMode === 'fountain') {
state.qr.value = window.EngineFountain.getFrame(state);
document.getElementById('current-frame').innerText = state.isInitialManifest ? "0" : "MIX";
document.getElementById('current-frame').classList.toggle('animate-pulse', !state.isInitialManifest);
} else {
state.qr.value = window.EngineSequential.getFrame(state.tid, state.chunks, state.frameIdx, (state.sendMode==='file'?state.file.name:"message.txt"));
document.getElementById('current-frame').innerText = state.frameIdx + 1;
document.getElementById('current-frame').classList.remove('animate-pulse');
}
}
function restartTimer() { clearInterval(state.timer); state.timer = setInterval(() => { if(!state.isPaused) {
if(state.engineMode === 'classic') { state.frameIdx++; if(state.frameIdx > state.rangeEnd) state.frameIdx = state.rangeStart; }
renderFrame();
}}, 1000/state.fps); }
function togglePause() { state.isPaused = !state.isPaused; document.getElementById('btn-pause').innerText = state.isPaused ? "PLAY" : "PAUSE"; if(!state.isPaused) state.isInitialManifest = false; if(state.isPaused) clearInterval(state.timer); else restartTimer(); renderFrame(); }
function nextFrame() { state.isPaused = true; document.getElementById('btn-pause').innerText = "PLAY"; if(state.engineMode==='classic'){state.frameIdx++; if(state.frameIdx>state.rangeEnd)state.frameIdx=state.rangeStart;} renderFrame(); }
function prevFrame() { state.isPaused = true; document.getElementById('btn-pause').innerText = "PLAY"; if(state.engineMode==='classic'){state.frameIdx--; if(state.frameIdx<state.rangeStart)state.frameIdx=state.rangeEnd;} renderFrame(); }
/* Receiver */
async function toggleScan() {
if (state.recv.active) {
try { await state.recv.scanner.stop(); } catch (e) { }
state.recv.active = false;
document.getElementById('btn-toggle-scan').innerText = "SCAN NOW";
document.getElementById('btn-toggle-scan').classList.replace('bg-red-500', 'bg-blue-600');
document.getElementById('id-reset-recv').disabled = false;
document.getElementById('id-reset-recv').classList.remove('opacity-30', 'cursor-not-allowed');
return;
}
state.recv.scanner = new Html5Qrcode("reader");
await state.recv.scanner.start({ facingMode: "environment" }, { fps: 60, qrbox: (w, h) => ({ width: w * 0.8, height: h * 0.8 }) }, onScanSuccess);
state.recv.active = true;
document.getElementById('btn-toggle-scan').innerText = "STOP SCAN";
document.getElementById('btn-toggle-scan').classList.replace('bg-blue-600', 'bg-red-500');
document.getElementById('id-reset-recv').disabled = true;
document.getElementById('id-reset-recv').classList.add('opacity-30', 'cursor-not-allowed');
}
function onScanSuccess(text) {
if (state.recv.recovered) return;
// First pass parsing via engine logic
let res = window.EngineFountain.parseFrame(text);
if (!res) res = window.EngineSequential.parseFrame(text); // Try fallback
if (!res) return;
if (res.tid !== state.recv.tid) {
state.recv.tid = res.tid; state.recv.k = res.total || res.k;
state.recv.fileName = res.name || "FILE";
state.recv.solved = new Map(); state.recv.droplets = []; state.recv.receivedBlocks = {};
initGrid(state.recv.k);
document.getElementById('receive-file-info').innerText = `RECEIVING: ${state.recv.fileName}`;
document.getElementById('receive-file-info').classList.remove('hidden');
if (res.type === 'M') { state.recv.blockSize = res.blockSize; state.recv.originalSize = res.originalSize; }
} else if (res.name && (state.recv.fileName === "FILE" || state.recv.fileName === "message.txt")) {
state.recv.fileName = res.name;
document.getElementById('receive-file-info').innerText = `RECEIVING: ${state.recv.fileName}`;
}
if (res.type === 'SEQ') {
if (!state.recv.receivedBlocks[res.idx]) {
state.recv.receivedBlocks[res.idx] = window.EngineFountain.fromB64(res.data);
state.recv.solved.set(res.idx, state.recv.receivedBlocks[res.idx]);
updateDot(res.idx);
}
} else if (res.type === 'F') {
processFountainDroplet(res.seed, res.rS, res.rL, res.data);
}
if (state.recv.solved.size === state.recv.k) finalizeTransfer();
}
function processFountainDroplet(seed, rS, rL, block) {
const p = window.EngineFountain.prng(seed); const deg = p.getDegree(rL); const idxs = [];
while(idxs.length < deg) { const id = p.getIndex(rS, rL); if(!idxs.includes(id)) idxs.push(id); }
let dr = { idxs, data: block }, stack = [dr];
while(stack.length > 0) {
let cur = stack.pop();
for (let i = cur.idxs.length - 1; i >= 0; i--) {
let id = cur.idxs[i];
if (state.recv.solved.has(id)) {
for(let j=0; j<cur.data.length; j++) cur.data[j] ^= state.recv.solved.get(id)[j];
cur.idxs.splice(i, 1);
}
}
if (cur.idxs.length === 1) {
let id = cur.idxs[0];
if (!state.recv.solved.has(id)) {
state.recv.solved.set(id, cur.data); updateDot(id);
for (let i = state.recv.droplets.length - 1; i >= 0; i--) {
let other = state.recv.droplets[i];
if (other.idxs.includes(id)) {
for(let j=0; j<other.data.length; j++) other.data[j] ^= cur.data[j];
other.idxs.splice(other.idxs.indexOf(id), 1);
if (other.idxs.length === 1) stack.push(state.recv.droplets.splice(i, 1)[0]);
}
}
}
} else if (cur.idxs.length > 1) { state.recv.droplets.push(cur); }
}
}
function updateDot(idx) {
const d = document.getElementById(`recv-dot-${idx}`); if(d) d.className = "grid-dot received";
document.getElementById('receive-stats').innerText = `${state.recv.solved.size} / ${state.recv.k}`;
checkAndHideRow(idx);
}
function checkAndHideRow(dotIdx) {
const rowIdx = Math.floor(dotIdx / 20);
const rowStart = rowIdx * 20;
const rowEnd = Math.min(rowStart + 20, state.recv.k);
let allDone = true;
for (let k = rowStart; k < rowEnd; k++) {
if (!state.recv.solved.has(k)) { allDone = false; break; }
}
if (allDone) {
const rowEl = document.getElementById(`recv-row-${rowIdx}`);
if (rowEl) rowEl.style.display = 'none';
}
}
function initGrid(k) {
const g = document.getElementById('receive-grid'); g.innerHTML = '';
for (let i = 0; i < k; i += 20) {
const r = document.createElement('div'); r.className = 'recv-row';
r.id = `recv-row-${i / 20}`;
const l = document.createElement('div'); l.className = 'row-num'; l.innerText = i + 1; r.appendChild(l);
for (let j = 0; j < 20 && (i + j) < k; j++) {
const d = document.createElement('div'); d.className = 'grid-dot'; d.id = `recv-dot-${i + j}`; r.appendChild(d);
}
g.appendChild(r);
}
document.getElementById('receive-stats').innerText = `0 / ${k}`;
document.getElementById('receive-status-box').classList.remove('hidden');
}
function resetReceiver() {
state.recv.recovered = false; state.recv.tid = ""; state.recv.k = 0;
state.recv.solved.clear(); state.recv.droplets = []; state.recv.receivedBlocks = {};
document.getElementById('receive-grid').innerHTML = '';
document.getElementById('receive-stats').innerText = "0 / 0";
document.getElementById('receive-file-info').classList.add('hidden');
document.getElementById('text-preview-box').classList.add('hidden');
document.getElementById('text-result').value = "";
document.getElementById('success-card').classList.add('hidden');
document.getElementById('receive-status-box').classList.remove('hidden');
}
async function finalizeTransfer() {
if (state.recv.recovered) return; state.recv.recovered = true;
try { await state.recv.scanner.stop(); } catch(e){}
state.recv.active = false;
document.getElementById('btn-toggle-scan').innerText = "SCAN NOW";
document.getElementById('btn-toggle-scan').classList.replace('bg-red-500', 'bg-blue-600');
// UNLOCK Reset
document.getElementById('id-reset-recv').disabled = false;
document.getElementById('id-reset-recv').classList.remove('opacity-30', 'cursor-not-allowed');
document.getElementById('success-card').classList.remove('hidden');
document.getElementById('receive-status-box').classList.add('hidden');
document.getElementById('success-file-name').innerText = state.recv.fileName;
// Combine blocks and decompress
let totalLen = 0; state.recv.solved.forEach(b => totalLen += b.length);
const combined = new Uint8Array(totalLen); let off = 0;
for(let i=0; i<state.recv.k; i++) { combined.set(state.recv.solved.get(i), off); off += state.recv.solved.get(i).length; }
try {
const decompressed = pako.ungzip(combined);
const isText = state.recv.fileName.endsWith('.txt');
if (isText) {
const text = new TextDecoder().decode(decompressed);
document.getElementById('text-preview-box').classList.remove('hidden');
document.getElementById('text-result').value = text;
} else {
document.getElementById('text-preview-box').classList.add('hidden');
}
document.getElementById('btn-download').onclick = () => {
const blob = new Blob([decompressed]);
const url = URL.createObjectURL(blob);
const a = document.createElement('a'); a.href = url; a.download = state.recv.fileName; a.click();
URL.revokeObjectURL(url);
};
} catch(e) { alert("Decompression Fail: " + e); }
}
// --- SHARED UI HELPERS ---
function switchTab(t) { state.tab=t; document.getElementById('view-send').classList.toggle('hidden', t!=='send'); document.getElementById('view-receive').classList.toggle('hidden', t!=='receive');
document.getElementById('nav-send').classList.toggle('active', t==='send'); document.getElementById('nav-receive').classList.toggle('active', t==='receive'); }
function setSendMode(m) { state.sendMode=m; document.getElementById('drop-zone').classList.toggle('hidden', m!=='file'); document.getElementById('text-zone').classList.toggle('hidden', m!=='text');
document.getElementById('mode-file').className=m==='file'?"flex-1 py-2 rounded-xl text-[10px] font-black uppercase tracking-widest bg-blue-600 text-white shadow-lg transition-all":"flex-1 py-2 rounded-xl text-[10px] font-black uppercase tracking-widest bg-slate-100 text-slate-500 hover:bg-slate-200 transition-all";
document.getElementById('mode-text').className=m!=='file'?"flex-1 py-2 rounded-xl text-[10px] font-black uppercase tracking-widest bg-blue-600 text-white shadow-lg transition-all":"flex-1 py-2 rounded-xl text-[10px] font-black uppercase tracking-widest bg-slate-100 text-slate-500 hover:bg-slate-200 transition-all";
resetSender(); }
function handleFileSelect(e) {
const f=e.target.files[0]; if(!f)return;
state.needsPrepare=true;
state.file=f;
document.getElementById('selected-file-name').innerText=f.name;
document.getElementById('selected-file-info').innerText=formatSize(f.size);
document.getElementById('file-placeholder').classList.add('hidden');
document.getElementById('file-selected').classList.remove('hidden');
document.getElementById('btn-start').disabled=false;
}
function handleTextInput() {
const v=document.getElementById('textInput').value;
state.needsPrepare=true;
state.textData=v;
document.getElementById('text-count').innerText=`${v.length} CHARS`;
document.getElementById('btn-start').disabled=v.length===0;
}
function stopTransfer() {
clearInterval(state.timer);
state.isTransferring=false;
state.isInitialManifest=true;
state.isPaused=false;
document.getElementById('transfer-box').classList.add('hidden');
}
function resetSender() {
stopTransfer();
state.file=null; state.fileData=null; state.textData="";
document.getElementById('fileInput').value="";
document.getElementById('textInput').value="";
document.getElementById('text-count').innerText="0 CHARS";
document.getElementById('file-placeholder').classList.remove('hidden');
document.getElementById('file-selected').classList.add('hidden');
document.getElementById('btn-start').disabled=true;
}
async function copyReceivedText(btn) {
const t = document.getElementById('text-result');
await navigator.clipboard.writeText(t.value);
const old = btn.innerText; btn.innerText = "COPIED! ✅";
setTimeout(() => btn.innerText = old, 1500);
}
function formatSize(s) { if(s<1024)return s+"B"; if(s<1048576)return (s/1024).toFixed(1)+"KB"; return (s/1048576).toFixed(1)+"MB"; }
function setupHotkeys() {
window.addEventListener('keydown', (e) => {
if (e.ctrlKey || e.metaKey || e.altKey) return;
const isTyping = document.activeElement.tagName === 'TEXTAREA' ||
(document.activeElement.tagName === 'INPUT' && document.activeElement.type !== 'range');
if (isTyping) {
if (e.key === 'Escape') document.activeElement.blur();
return;
}
switch (e.key.toLowerCase()) {
case 's': e.preventDefault(); switchTab('send'); break;
case 'r': e.preventDefault(); switchTab('receive'); break;
case 'f':
e.preventDefault();
if (state.tab !== 'send') switchTab('send');
setSendMode('file');
setTimeout(() => document.getElementById('fileInput').click(), 50);
break;
case 't':
e.preventDefault();
if (state.tab !== 'send') switchTab('send');
setSendMode('text');
setTimeout(() => document.getElementById('textInput').focus(), 50);
break;
case ' ':
if (state.isTransferring) {
e.preventDefault();
togglePause();
}
break;
case 'enter':
e.preventDefault();
if (state.tab === 'send' && !document.getElementById('btn-start').disabled) {
if (!state.isTransferring || state.needsPrepare) {
startTransfer();
}
}
break;
case 'escape':
e.preventDefault();
resetSender();
break;
}
});
}
// Slider logic
function updatePlaybackRangeUI() { document.getElementById('range-start-slider').max=state.k; document.getElementById('range-end-slider').max=state.k; document.getElementById('range-start-slider').value=state.rangeStart+1; document.getElementById('range-end-slider').value=state.rangeEnd+1; updateLabelsAndTrack(); }
function handleRangeInput(t) { let s=parseInt(document.getElementById('range-start-slider').value), e=parseInt(document.getElementById('range-end-slider').value); if(t==='input-start')s=parseInt(document.getElementById('input-start').value); if(t==='input-end')e=parseInt(document.getElementById('input-end').value);
if(s>e) { if(t.includes('start')) e=s; else s=e; } state.rangeStart=s-1; state.rangeEnd=e-1; updateLabelsAndTrack(); if(state.isPaused)renderFrame(); }
function updateLabelsAndTrack() { const s=state.rangeStart+1, e=state.rangeEnd+1, t=state.k||1; document.getElementById('input-start').value=s; document.getElementById('input-end').value=e;
const p1=(t>1)?((s-1)/(t-1))*100:0, p2=(t>1)?((e-1)/(t-1))*100:100; document.getElementById('slider-active-track').style.left=p1+"%"; document.getElementById('slider-active-track').style.width=(p2-p1)+"%"; }
function shiftRange(d) { if(!state.k)return; const span=state.rangeEnd-state.rangeStart+1; let ns, ne; if(d==='next'){ns=state.rangeEnd+2; ne=ns+span-1;}else{ne=state.rangeStart; ns=ne-span+1;}
if(ns<1)ns=1; if(ne>state.k)ne=state.k; if(ns>state.k)ns=state.k; if(ne<1)ne=1; if(ns>ne)ns=ne; state.rangeStart=ns-1; state.rangeEnd=ne-1; updatePlaybackRangeUI(); if(state.isPaused)renderFrame(); }
function initSliderDrag() { const track=document.getElementById('slider-active-track'); let d=false,sx=0,is=0,ie=0; const os=e=>{if(state.k<=1)return;d=true;sx=e.type.includes('touch')?e.touches[0].clientX:e.clientX;is=state.rangeStart;ie=state.rangeEnd;};
const om=e=>{if(!d)return; const cx=e.type.includes('touch')?e.touches[0].clientX:e.clientX, r=track.parentElement.getBoundingClientRect(), s=Math.round(((cx-sx)/r.width)*(state.k-1));
let ns=is+s, ne=ie+s; if(ns<0){ns=0;ne=ie-is;} if(ne>=state.k){ne=state.k-1;ns=ne-(ie-is);} if(ns!==state.rangeStart||ne!==state.rangeEnd){state.rangeStart=ns;state.rangeEnd=ne;updatePlaybackRangeUI();if(state.isPaused)renderFrame();}};
const oe=()=>{d=false;}; track.addEventListener('mousedown',os); track.addEventListener('touchstart',os); window.addEventListener('mousemove',om); window.addEventListener('touchmove',om); window.addEventListener('mouseup',oe); window.addEventListener('touchend',oe); }
</script>
</body>
</html>