-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcanvas.html
More file actions
873 lines (747 loc) · 40.1 KB
/
canvas.html
File metadata and controls
873 lines (747 loc) · 40.1 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Content Editor</title>
<!-- Load Tailwind CSS for styling and responsiveness -->
<script src="https://cdn.tailwindcss.com"></script>
<!-- Scary display font for redaction UI -->
<link href="https://fonts.googleapis.com/css2?family=Creepster&display=swap" rel="stylesheet">
<!-- Load GSAP Core Library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.5/gsap.min.js"></script>
<style>
.font-scary {
font-family: 'Creepster', 'Papyrus', fantasy;
}
body {
font-family: 'Inter', sans-serif;
background-color: #f3f4f6;
overflow-x: hidden;
/* Prevent horizontal scroll from character movement */
}
.mode-select {
appearance: none;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 20 20'%3E%3Cpath fill='%236B7280' d='M9.293 12.95l.707.707L15.657 8l-1.414-1.414L10 10.828 5.757 6.586 4.343 8z'/%3E%3C/svg%3E");
background-repeat: no-repeat;
background-position: right 0.75rem center;
background-size: 1.5em;
}
/* Style for the document container */
.document-card {
background-color: #ffffff;
border-radius: 1rem;
box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1);
max-width: 4xl;
width: 90%;
/* Relative position needed for absolute children (character layer) */
position: relative;
}
/* Layer for the animated characters, positioned over the content */
#character-layer {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
/* Allows clicks to pass through to the document below */
z-index: 10;
}
.character {
width: 48px;
height: 48px;
border-radius: 50%;
position: absolute;
opacity: 0.9;
pointer-events: none;
box-shadow: 0 6px 14px rgba(16, 24, 40, 0.12);
}
/* Make the match sprite larger and keep it circular */
#char-1 {
width: 80px;
height: 80px;
}
/* Words are inline-block so we can transform/blur individual words without collapsing layout */
.word {
display: inline-block;
white-space: pre;
/* preserve spaces/newlines between words */
will-change: transform, filter;
}
/* Redacted text styling - black highlight effect */
.redacted {
background-color: #000000 !important;
color: transparent !important;
text-shadow: none !important;
user-select: none;
border-radius: 3px;
position: relative;
padding: 2px 4px;
margin: 0 1px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}
/* Ensure redacted text can't be selected or revealed */
.redacted::selection {
background-color: #000000;
color: transparent;
}
@keyframes redact-in {
from {
background-color: transparent;
transform: scaleX(0);
}
to {
background-color: #000000;
transform: scaleX(1);
}
}
/* Kristina sprite sizing */
#char-5 {
width: 100px;
height: 140px;
}
/* Make the UCSC jeff sprite twice the base character size */
#char-3 {
width: 96px;
height: 96px;
}
/* baby girl Jeff */
#char-6 {
width: 170px;
height: 210px;
}
/* Make the Cal sprite larger */
#char-7 {
width: 146px;
height: 146px;
}
/* Carmen sprite sizing */
#char-4 {
width: 100px;
height: 160px;
}
/* Sabina sprite sizing */
#char-2 {
width: 50px;
height: 150px;
}
/* Full-area red overlay for special collision effect (initially transparent) */
#screen-overlay {
position: absolute;
inset: 0;
background-color: rgba(255, 0, 0, 0);
pointer-events: none;
z-index: 40;
border-radius: 1rem;
}
</style>
</head>
<body class="flex flex-col items-center min-h-screen p-6 md:p-10">
<!-- Document Container -->
<div id="document-card" class="document-card p-8 md:p-16 w-full">
<a href="index.html" class="inline-flex items-center text-blue-600 hover:text-blue-800 mb-6 font-medium">
<!-- Back Arrow SVG Icon -->
<svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18">
</path>
</svg>
Back to Input
</a>
<!-- Title Section -->
<h1 id="notebook-title"
class="text-4xl md:text-5xl font-black mb-4 text-gray-800 border-b-2 pb-4 border-gray-200">
Focus Mode
</h1>
<!-- Mode Selector Dropdown -->
<div class="mb-10 flex flex-col sm:flex-row sm:items-center space-y-3 sm:space-y-0 sm:space-x-4">
<label for="style-mode" class="text-lg font-semibold text-gray-700">Select Mode:</label>
<select id="style-mode"
class="mode-select block w-full sm:w-64 p-3 border border-gray-300 rounded-lg bg-gray-50 focus:ring-blue-500 focus:border-blue-500 text-base mode-select cursor-pointer">
<option value="corporate">💼 LinkedIn Speak </option>
<option value="emoji">😂 Emoji Enhanced Text</option>
<option value="argumentative">⚔️ Argumentative Mode</option>
<option value="forgetful">🤔 Forgetful Mode</option>
<option value="brainrot">🤪 Brainrot </option>
</select>
</div>
<!-- Redaction Status Indicator -->
<div id="redaction-status" class="mb-4 p-3 bg-gray-100 rounded-lg border border-gray-300 hidden">
<div class="flex items-center justify-between">
<span class="text-2xl font-semibold text-gray-700 font-scary">🔒 Redaction Progress:</span>
<span id="redaction-counter" class="text-5xl text-green-700 font-semibold font-scary">0 / 0</span>
</div>
<div class="mt-2 w-full bg-gray-300 rounded-full h-2">
<div id="redaction-progress-bar" class="bg-green-600 h-2 rounded-full transition-all duration-300"
style="width: 0%"></div>
</div>
</div>
<!-- Output Area for Generated Text -->
<div id="output-area" class="space-y-6 text-lg text-gray-700 leading-relaxed min-h-[400px]">
<!-- Content will be injected here by JavaScript -->
<p>Paste text on the home page to begin transformation.</p>
</div>
<!-- Character Animation Layer (hidden until text transform completes) -->
<div id="character-layer" style="opacity: 0; pointer-events: none;">
<div id="char-1" class="character"
style="background-image: url('assets/match.png'); background-size: 140%; background-position: center; background-repeat: no-repeat; background-color: #a21f1f;">
</div>
<!-- char-2 uses Sabina.png sprite -->
<div id="char-2" class="character"
style="background-image: url('assets/Sabina.png'); background-size: cover; background-position: center; background-repeat: no-repeat;">
</div>
<!-- char-3 uses an image sprite from assets/ucscjeff.png -->
<div id="char-3" class="character"
style="background-image: url('assets/ucscjeff.png'); background-size: cover; background-position: center; background-repeat: no-repeat;">
</div>
<!-- char-4 uses Carmen.png sprite -->
<div id="char-4" class="character"
style="background-image: url('assets/Carmen.png'); background-size: cover; background-position: center; background-repeat: no-repeat;">
</div>
<!-- char-5 uses an image sprite from assets/Kristina.png -->
<div id="char-5" class="character"
style="background-image: url('assets/Kristina.png'); background-size: cover; background-position: center; background-repeat: no-repeat;">
</div>
<!-- char-6 uses bomb.png sprite -->
<div id="char-6" class="character"
style="background-image: url('assets/bomb.png'); background-size: cover; background-position: center; background-repeat: no-repeat;">
</div>
<!-- char-7 uses Cal.png sprite -->
<div id="char-7" class="character"
style="background-image: url('assets/Cal.png'); background-size: cover; background-position: center; background-repeat: no-repeat;">
</div>
</div>
<!-- Red overlay used when Cal + Baby Jeff collide -->
<div id="screen-overlay" aria-hidden="true"></div>
</div>
<script>
// --- TEXT PARSING FUNCTIONS ---
/**
* Splits raw text into paragraphs based on double newlines and wraps them in <p> tags.
* @param {string} rawText The text content to process.
* @returns {string} HTML string with text wrapped in <p> tags.
*/
function splitParagraphs(rawText) {
// Split text by two or more newlines to identify distinct paragraphs
// Wrap each word in a <span class="word"> so collisions can affect individual words
return rawText.split(/\n\s*\n/)
.map(p => p.trim())
.filter(p => p.length > 0) // Filter out empty strings
.map(p => {
// Split on spaces but keep separators so spacing is preserved.
// We'll create spans for words and join with a single space.
const words = p.split(/\s+/).map(w => `<span class="word">${w}</span>`).join(' ');
return `<p>${words}</p>`;
})
.join('');
}
/**
* Parent function for organized text processing before display.
* @param {string} textForDisplay The final transformed text ready for the DOM.
* @returns {string} HTML string for injection.
*/
function ParseInput(textForDisplay) {
return splitParagraphs(textForDisplay);
}
// --- APPLICATION LOGIC ---
window.onload = function () {
const title = document.getElementById('notebook-title');
const documentCard = document.getElementById('document-card');
const outputArea = document.getElementById('output-area');
const modeSelect = document.getElementById('style-mode');
const characterLayer = document.getElementById('character-layer');
const characters = document.querySelectorAll('.character');
const redactionStatus = document.getElementById('redaction-status');
const redactionCounter = document.getElementById('redaction-counter');
const redactionProgressBar = document.getElementById('redaction-progress-bar');
let animationFrameId = null;
let currentWords = [];
// Fonts to rotate through when words are hit
const collisionFonts = [
'Arial, sans-serif',
"'Comic Sans MS', 'Comic Sans', cursive",
"'Papyrus', fantasy",
"'Rubik Glitch', 'Arial', sans-serif"
];
// --- 1. Get Input Text from URL ---
// Default text if accessed directly without content parameter
// const rawInputText = urlParams.get('content') || "This is default placeholder text because no content was pasted on the home page. Now try selecting a mode to see it transform! The characters will move and bump into these words to demonstrate collisions.";
let rawInputText = localStorage.getItem('animationText') || "No text provided from index.html. Enter text in the previous step to see content here.";
// --- 2. API Integration with FastAPI Backend ---
const API_URL = 'http://localhost:8000/transform';
const KEYPHRASE_API_URL = 'http://localhost:8001/extract';
// Store keyphrases and redaction state
let keyphraseIndices = [];
let redactedCount = 0;
let redactionEnabled = false;
let originalTransformedText = ''; // Store the original transformed text
let lastRedactionTime = 0; // Cooldown timer for progressive redaction
const REDACTION_COOLDOWN = 1000; // Minimum milliseconds between redactions
// New batching/delay behavior for progressive redaction
let _isProcessingRedactionBatch = false;
const REDACTION_BATCH_FRACTION = 0.2; // portion of total keyphrases to redact per batch (20%)
const REDACTION_BATCH_DELAY = 500; // milliseconds to wait after each batch
/**
* Calls the FastAPI backend which uses model.py to transform text with Gemini AI
* @param {string} text - The text to transform
* @param {string} mode - The transformation mode
* @returns {Promise<string>} - The transformed text
*/
async function transformTextWithAPI(text, mode) {
try {
const response = await fetch(API_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text, mode })
});
let data = null;
try {
data = await response.json();
} catch (jsonErr) {
console.error('Transform API returned non-JSON response', jsonErr, response);
return fallbackTransform(text, mode);
}
console.log('Transform API response', response.status, data);
if (data && data.success) return data.transformed_text;
// If backend returned an error payload, log it for debugging
if (data && data.error) {
console.error('Transform API error:', data.error);
}
return fallbackTransform(text, mode);
} catch (error) {
console.error('Network/error calling transform API:', error);
return fallbackTransform(text, mode);
}
}
/**
* Fetches keyphrases from the keyphrase extraction API
* @param {string} text - The text to analyze
* @returns {Promise<Array>} - Array of [start, end] indices
*/
async function fetchKeyphrases(text) {
try {
console.log('Fetching keyphrases from API...');
const response = await fetch(KEYPHRASE_API_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
text: text,
p: 0.3 // Extract 30% of keyphrases for progressive redaction
})
});
const data = await response.json();
console.log(`Received ${data.keyphrases.length} keyphrases`);
return data.keyphrases;
} catch (error) {
console.error('Failed to fetch keyphrases:', error);
return [];
}
}
/**
* Finds and marks text nodes that fall within keyphrase indices
* @param {Array} indices - Array of [start, end] pairs to redact
*/
function applyRedactionToDOM(indices) {
if (!indices || indices.length === 0) return;
// Get all text content to build character position map
const allText = originalTransformedText;
let charPosition = 0;
// Walk through all paragraph elements
const paragraphs = outputArea.querySelectorAll('p');
paragraphs.forEach(paragraph => {
const words = paragraph.querySelectorAll('.word');
words.forEach(word => {
const wordText = word.textContent;
const wordStart = charPosition;
const wordEnd = charPosition + wordText.length;
// Check if this word overlaps with any keyphrase to redact
let shouldRedact = false;
indices.forEach(([start, end]) => {
// Check if word range overlaps with keyphrase range
if (!(wordEnd <= start || wordStart >= end)) {
shouldRedact = true;
}
});
if (shouldRedact && !word.classList.contains('redacted')) {
word.classList.add('redacted');
// Trigger animation
gsap.from(word, {
scaleX: 0,
duration: 0.4,
ease: 'power2.out'
});
}
charPosition += wordText.length;
// Account for space after word
if (word.nextSibling && word.nextSibling.nodeType === Node.TEXT_NODE) {
charPosition += word.nextSibling.textContent.length;
} else {
charPosition += 1; // space between words
}
});
// Account for paragraph breaks
charPosition += 2; // \n\n between paragraphs
});
}
function updateRedactionStatus() {
const redactionStatusEl = document.getElementById('redaction-status');
const redactionCounterEl = document.getElementById('redaction-counter');
const redactionProgressBarEl = document.getElementById('redaction-progress-bar');
if (!redactionStatusEl || !redactionCounterEl || !redactionProgressBarEl) return;
if (!redactionEnabled) {
redactionStatusEl.classList.add('hidden');
return;
}
redactionStatusEl.classList.remove('hidden');
redactionCounterEl.textContent = `${redactedCount} / ${keyphraseIndices.length}`;
// If the counter text is long (e.g. "13 / 13"), make it a bit smaller
// so it fits and doesn't overpower the UI.
const counterTextLen = redactionCounterEl.textContent.trim().length;
if (counterTextLen >= 6) {
// smaller for multi-digit counts
redactionCounterEl.classList.remove('text-5xl');
if (!redactionCounterEl.classList.contains('text-4xl')) {
redactionCounterEl.classList.add('text-4xl');
}
} else {
// default bigger size for small counts
redactionCounterEl.classList.remove('text-4xl');
if (!redactionCounterEl.classList.contains('text-5xl')) {
redactionCounterEl.classList.add('text-5xl');
}
}
const pct = keyphraseIndices.length ? (redactedCount / keyphraseIndices.length) * 100 : 0;
redactionProgressBarEl.style.width = `${pct}%`;
// Keep the progress bar green at all times
redactionProgressBarEl.classList.remove('bg-black');
if (!redactionProgressBarEl.classList.contains('bg-green-600')) {
redactionProgressBarEl.classList.add('bg-green-600');
}
}
/**
* Progressively redacts text on collision events
* Redacts one more keyphrase each time it's called
*/
// Helper sleep for async delays
function sleep(ms) { return new Promise(res => setTimeout(res, ms)); }
/**
* Progressively redacts text on collision events
* Processes a small batch (fraction of total keyphrases) and then waits 500ms.
*/
async function progressiveRedact() {
if (!redactionEnabled || redactedCount >= keyphraseIndices.length) {
return;
}
// If a batch is currently being processed, ignore new triggers
if (_isProcessingRedactionBatch) return;
// Cooldown check: prevent extremely rapid triggers
const now = Date.now();
if (now - lastRedactionTime < REDACTION_COOLDOWN) {
return; // Too soon, skip this redaction
}
lastRedactionTime = now;
// Start batch processing
_isProcessingRedactionBatch = true;
// Decide batch size as a fraction of total keyphrases (at least 1)
const remaining = keyphraseIndices.length - redactedCount;
let batchSize = Math.max(1, Math.ceil(keyphraseIndices.length * REDACTION_BATCH_FRACTION));
batchSize = Math.min(batchSize, remaining);
console.log(`Processing redaction batch of ${batchSize} (remaining ${remaining})`);
for (let i = 0; i < batchSize; i++) {
if (redactedCount >= keyphraseIndices.length) break;
redactedCount++;
const newKeyphraseIndex = [keyphraseIndices[redactedCount - 1]];
console.log(`Redacting ${redactedCount}/${keyphraseIndices.length} indices:`, newKeyphraseIndex);
applyRedactionToDOM(newKeyphraseIndex);
updateRedactionStatus();
// small micro-yield to let DOM updates/animations start (no visible delay)
await sleep(20);
}
// After batch is done, wait the configured batch delay before allowing more
await sleep(REDACTION_BATCH_DELAY);
_isProcessingRedactionBatch = false;
}
// --- 3. Fallback Transformation Logic (if API fails) ---
function fallbackTransform(text, mode) {
const contentTransforms = {
corporate: (text) => text
.replace(/problem/gi, 'challenge')
.replace(/solution/gi, 'synergistic outcome')
.replace(/goal/gi, 'key deliverable')
.replace(/work on/gi, 'operationalize')
.replace(/plan/gi, 'strategic roadmap'),
emoji: (text) => text
.replace(/[.!?]/g, ' ✨ ')
.replace(/ /g, ' 💅 ') + ' 👑',
argumentative: (text) => "It is indefensible to assume: " + text.toUpperCase() + ". Furthermore, the premise is fundamentally flawed.",
forgetful: (text) => text
.replace(/the /g, ' that one... ')
.replace(/is /g, ' wait, is it? ')
.replace(/and/g, ' or was it... and? '),
brainrot: (text) => text
.replace(/good/g, 'bussin\'')
.replace(/winning/g, 'slaying') + ' no cap fr.'
};
return contentTransforms[mode] ? contentTransforms[mode](text) : text;
}
function animateCharacter(charElement) {
const layerBounds = characterLayer.getBoundingClientRect();
const charWidth = charElement.clientWidth || 20;
const charHeight = charElement.clientHeight || 20;
const bg = (charElement.style.backgroundImage || '').toLowerCase();
let behavior = 'normal';
if (bg.includes('carmen')) behavior = 'carmen';
else if (bg.includes('cal')) behavior = 'cal';
else if (bg.includes('jeff')) behavior = 'jeff';
// Treat the match sprite (char-1 / match.png) like 'cal'
else if (charElement.id === 'char-1' || bg.includes('match')) behavior = 'cal';
function getRandomPositionFor(type) {
const maxX = Math.max(0, layerBounds.width - charWidth);
const maxY = Math.max(0, layerBounds.height - charHeight);
const x = gsap.utils.random(0, maxX);
const y = type === 'jeff' ?
gsap.utils.random(maxY * 0.4, maxY * 0.85) :
gsap.utils.random(0, maxY);
return { x, y };
}
function move() {
const newPos = getRandomPositionFor(behavior);
let duration = 4;
let ease = 'sine.inOut';
if (behavior === 'carmen') {
duration = gsap.utils.random(0.8, 2.2);
ease = 'power2.inOut';
} else if (behavior === 'jeff') {
duration = gsap.utils.random(6, 11);
} else if (behavior === 'cal') {
// Default Cal timings
duration = gsap.utils.random(0.35, 1.1);
ease = 'power1.inOut';
// If this is the match sprite (char-1) make it snappier (faster side-to-side)
if (charElement.id === 'char-1') {
duration = gsap.utils.random(0.12, 0.45);
ease = 'power1.inOut';
}
} else {
duration = gsap.utils.random(3.5, 7.5);
}
gsap.to(charElement, {
x: newPos.x,
y: newPos.y,
duration,
ease,
onComplete: move
});
if (behavior === 'carmen') {
gsap.to(charElement, { rotation: gsap.utils.random(-18, 18), duration: Math.max(0.3, duration / 3), ease: 'sine.inOut', yoyo: true, repeat: 1 });
} else if (behavior === 'cal') {
if (charElement.id === 'char-1') {
// match: more rotation and faster rotation tween for a lively effect
gsap.to(charElement, { rotation: gsap.utils.random(-22, 22), duration: gsap.utils.random(0.03, 0.12), ease: 'none', yoyo: true, repeat: 1 });
} else {
gsap.to(charElement, { rotation: gsap.utils.random(-12, 12), duration: gsap.utils.random(0.06, 0.25), ease: 'none', yoyo: true, repeat: 1 });
}
} else if (behavior === 'jeff') {
// Make Jeff slowly rotate continuously over time
// Use a long random duration so each Jeff spins at a slightly different slow rate
// speed up Jeff's slow spin (shorter rotation period)
const spinDuration = gsap.utils.random(18, 35);
gsap.to(charElement, { rotation: '+=360', duration: spinDuration, ease: 'linear', repeat: -1 });
}
}
// Set initial random position and start the loop
const initialPos = getRandomPositionFor(behavior);
gsap.set(charElement, { x: initialPos.x, y: initialPos.y, rotation: 0 });
move();
}
// --- 4. Collision Detection ---
/**
* Checks for collisions between characters and text paragraphs.
*/
function checkCollisions() {
if (!currentWords || currentWords.length === 0) return;
redactionRequestedThisFrame = false;
const cardRect = documentCard.getBoundingClientRect();
characters.forEach(char => {
const charRect = char.getBoundingClientRect();
currentWords.forEach((w, idx) => {
const wRect = w.getBoundingClientRect();
const overlap = !(charRect.right < wRect.left ||
charRect.left > wRect.right ||
charRect.bottom < wRect.top ||
charRect.top > wRect.bottom);
if (overlap) {
if (w._isBouncing) return;
// Trigger progressive redaction on any character-word collision
progressiveRedact();
// We'll animate this word and a small clump around it (previous + next)
const neighbors = [w];
const clumpRadius = 1;
for (let r = 1; r <= clumpRadius; r++) {
if (currentWords[idx - r]) neighbors.push(currentWords[idx - r]);
if (currentWords[idx + r]) neighbors.push(currentWords[idx + r]);
}
neighbors.forEach(n => { n._isBouncing = true; n.style.transformOrigin = 'center center'; });
const tl = gsap.timeline({
onComplete: () => {
neighbors.forEach(n => {
n._isBouncing = false;
n.style.willChange = '';
if (n._prevFont !== undefined) {
n.style.fontFamily = n._prevFont;
delete n._prevFont;
}
});
}
});
const skewAmt = gsap.utils.random(-4, 4);
tl.to(neighbors, {
duration: 0.12,
y: 4,
scaleX: 1.02,
skewX: skewAmt,
filter: 'blur(2px)',
ease: 'power1.out',
stagger: 0.02,
onStart: () => {
neighbors.forEach(n => {
n.style.willChange = 'transform, filter';
n._prevFont = n.style.fontFamily || window.getComputedStyle(n).fontFamily;
const pick = collisionFonts[Math.floor(Math.random() * collisionFonts.length)];
n.style.fontFamily = pick;
});
}
});
tl.to(neighbors, {
duration: 0.6,
y: 0,
scaleX: 1,
skewX: 0,
filter: 'blur(0px)',
ease: 'elastic.out(1, 0.6)',
stagger: 0.02
});
gsap.fromTo(char, { scale: 1 }, { scale: 1.12, duration: 0.12, yoyo: true, repeat: 1, ease: 'power1.out' });
}
});
});
try {
// Special collision: trigger when the bomb (char-6 / bomb.png) touches the match (char-1 / match.png)
const bombEl = Array.from(characters).find(c => c.id === 'char-6' || (c.style.backgroundImage || '').toLowerCase().includes('bomb'));
const matchEl = Array.from(characters).find(c => c.id === 'char-1' || (c.style.backgroundImage || '').toLowerCase().includes('match'));
if (bombEl && matchEl) {
const brect = bombEl.getBoundingClientRect();
const mrect = matchEl.getBoundingClientRect();
const overlapSpecial = !(brect.right < mrect.left || brect.left > mrect.right || brect.bottom < mrect.top || brect.top > mrect.bottom);
if (overlapSpecial && !window._isScreenShaking) {
window._isScreenShaking = true;
const overlay = document.getElementById('screen-overlay');
if (overlay) {
gsap.killTweensOf(overlay);
gsap.to(overlay, { backgroundColor: 'rgba(255,0,0,0.55)', duration: 0.08, ease: 'power1.out' });
gsap.to(overlay, { backgroundColor: 'rgba(255,0,0,0)', delay: 0.6, duration: 0.6, ease: 'power1.inOut' });
}
gsap.fromTo(documentCard, { x: 0 }, { x: 12, duration: 0.05, yoyo: true, repeat: 8, ease: 'power1.inOut', onComplete: () => { gsap.to(documentCard, { x: 0, duration: 0.08 }); } });
// Show explosion.gif at the collision point
try {
const layerBounds = characterLayer.getBoundingClientRect();
// center point between bomb and match
const midX = (brect.left + brect.right + mrect.left + mrect.right) / 4;
const midY = (brect.top + brect.bottom + mrect.top + mrect.bottom) / 4;
const size = Math.max(80, Math.min(220, Math.max(brect.width, brect.height, mrect.width, mrect.height)));
const img = document.createElement('img');
img.src = 'assets/explosion.gif';
img.className = 'explosion-temp';
img.style.position = 'absolute';
img.style.left = `${Math.round(midX - layerBounds.left - size / 2)}px`;
img.style.top = `${Math.round(midY - layerBounds.top - size / 2)}px`;
img.style.width = `${size}px`;
img.style.height = `${size}px`;
img.style.pointerEvents = 'none';
img.style.zIndex = 50;
img.style.opacity = '0';
characterLayer.appendChild(img);
gsap.fromTo(img, { scale: 0, opacity: 0 }, { scale: 1, opacity: 1, duration: 0.12, ease: 'power2.out' });
gsap.to(img, { opacity: 0, delay: 0.7, duration: 0.4, onComplete: () => { try { img.remove(); } catch (e) { } } });
} catch (e) { console.warn('Failed to show explosion gif', e); }
// Also shake the redaction status UI so it matches the screen shake
try {
const redStatusEl = document.getElementById('redaction-status');
if (redStatusEl) {
gsap.fromTo(redStatusEl, { x: 0 }, { x: 12, duration: 0.05, yoyo: true, repeat: 8, ease: 'power1.inOut', onComplete: () => { gsap.to(redStatusEl, { x: 0, duration: 0.08 }); } });
}
} catch (e) { }
setTimeout(() => { window._isScreenShaking = false; }, 900);
}
}
} catch (err) { }
animationFrameId = requestAnimationFrame(checkCollisions);
}
// --- 5. Function to Handle Content Change and Animation (GSAP) ---
async function updateContent(mode, instant = false) {
// Stop collision checks during content transition
if (animationFrameId) cancelAnimationFrame(animationFrameId);
outputArea.innerHTML = '<p class="text-gray-400 italic animate-pulse">🤖 AI is Improving your text...</p>';
const transformedText = await transformTextWithAPI(rawInputText, mode);
// Store the original transformed text for redaction
originalTransformedText = transformedText;
// Fetch keyphrases from the extraction API
keyphraseIndices = await fetchKeyphrases(transformedText);
redactedCount = 0;
redactionEnabled = keyphraseIndices.length > 0;
lastRedactionTime = 0; // Reset cooldown timer for new content
if (redactionEnabled) {
console.log(`Redaction enabled with ${keyphraseIndices.length} keyphrases`);
} else {
console.log('No keyphrases found - redaction disabled');
}
// Update the UI progress bar immediately
updateRedactionStatus();
const newContentHTML = ParseInput(transformedText);
if (instant) {
outputArea.innerHTML = newContentHTML;
currentWords = outputArea.querySelectorAll('.word');
gsap.set(currentWords, { opacity: 1, y: 0, scaleX: 1, skewX: 0, filter: 'none' });
animationFrameId = requestAnimationFrame(checkCollisions);
return;
}
gsap.to(outputArea.children, {
opacity: 0,
y: 10,
duration: 0.18,
stagger: 0.02,
ease: "power1.in",
onComplete: () => {
outputArea.innerHTML = newContentHTML;
currentWords = outputArea.querySelectorAll('.word');
gsap.from(currentWords, {
opacity: 0,
y: -6,
duration: 0.18,
stagger: 0.005,
ease: "power2.out",
onComplete: () => {
animationFrameId = requestAnimationFrame(checkCollisions);
}
});
}
});
}
async function initialize() {
// Wait for the initial content transform to finish
await updateContent(modeSelect.value, true);
// Reveal the character layer once the LLM transform and DOM injection are complete
gsap.to(characterLayer, { opacity: 1, duration: 0.6, ease: 'power2.out' });
gsap.from(title, { opacity: 0, y: -20, duration: 1, ease: "power2.out" });
// Start character animations after revealing the layer
characters.forEach(animateCharacter);
}
modeSelect.addEventListener('change', (e) => updateContent(e.target.value));
initialize();
};
</script>
</body>
</html>