forked from javaevolved/javaevolved.github.io
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
491 lines (435 loc) · 16.1 KB
/
app.js
File metadata and controls
491 lines (435 loc) · 16.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
/* ===========================
Modern Java — app.js
Vanilla JS for search, filters, syntax highlighting, and interactions
=========================== */
(() => {
'use strict';
/* ---------- Snippets Data ---------- */
let snippets = [];
const loadSnippets = async () => {
try {
const res = await fetch('/data/snippets.json');
snippets = await res.json();
} catch (e) {
console.warn('Could not load snippets.json:', e);
}
};
/* ==========================================================
1. Search Overlay (⌘K / Ctrl+K)
========================================================== */
const initSearch = () => {
const overlay = document.querySelector('.search-overlay');
const cmdBar = document.querySelector('.cmd-bar');
if (!overlay) return;
const input = overlay.querySelector('.search-input');
const resultsContainer = overlay.querySelector('.search-results');
let selectedIndex = -1;
let visibleResults = [];
const openSearch = () => {
overlay.classList.add('active');
if (input) {
input.value = '';
input.focus();
}
renderResults('');
};
const closeSearch = () => {
overlay.classList.remove('active');
selectedIndex = -1;
};
// Fuzzy match: check if query words appear in target string
const fuzzyMatch = (query, text) => {
const lower = text.toLowerCase();
return query.toLowerCase().split(/\s+/).filter(Boolean)
.every(word => lower.includes(word));
};
const renderResults = (query) => {
if (!resultsContainer) return;
if (!query.trim()) {
visibleResults = snippets.slice(0, 12);
} else {
visibleResults = snippets.filter(s =>
fuzzyMatch(query, s.title) ||
fuzzyMatch(query, s.category) ||
fuzzyMatch(query, s.summary)
);
}
selectedIndex = visibleResults.length > 0 ? 0 : -1;
resultsContainer.innerHTML = visibleResults.map((s, i) => `
<div class="search-result${i === 0 ? ' selected' : ''}" data-slug="${s.slug}">
<div>
<div class="title">${escapeHtml(s.title)}</div>
<div class="desc">${escapeHtml(s.summary)}</div>
</div>
<span class="badge ${s.category}">${s.category}</span>
</div>
`).join('');
// Click handlers on results
resultsContainer.querySelectorAll('.search-result').forEach(el => {
el.addEventListener('click', () => {
window.location.href = '/' + el.dataset.slug + '.html';
});
});
};
const updateSelection = () => {
const items = resultsContainer.querySelectorAll('.search-result');
items.forEach((el, i) => {
el.classList.toggle('selected', i === selectedIndex);
});
// Scroll selected into view
if (items[selectedIndex]) {
items[selectedIndex].scrollIntoView({ block: 'nearest' });
}
};
// Keyboard shortcut: ⌘K / Ctrl+K
document.addEventListener('keydown', (e) => {
if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
e.preventDefault();
openSearch();
}
if (e.key === 'Escape') {
closeSearch();
}
});
// Cmd-bar click
if (cmdBar) {
cmdBar.addEventListener('click', openSearch);
}
// Click backdrop to close
overlay.addEventListener('click', (e) => {
if (e.target === overlay) closeSearch();
});
// Search input events
if (input) {
input.addEventListener('input', () => {
renderResults(input.value);
});
input.addEventListener('keydown', (e) => {
if (e.key === 'ArrowDown') {
e.preventDefault();
if (visibleResults.length > 0) {
selectedIndex = (selectedIndex + 1) % visibleResults.length;
updateSelection();
}
} else if (e.key === 'ArrowUp') {
e.preventDefault();
if (visibleResults.length > 0) {
selectedIndex = (selectedIndex - 1 + visibleResults.length) % visibleResults.length;
updateSelection();
}
} else if (e.key === 'Enter') {
e.preventDefault();
if (selectedIndex >= 0 && visibleResults[selectedIndex]) {
window.location.href = '/' + visibleResults[selectedIndex].slug + '.html';
}
}
});
}
};
/* ==========================================================
2. Category Filter Pills (homepage)
========================================================== */
const initFilters = () => {
const pills = document.querySelectorAll('.filter-pill');
const cards = document.querySelectorAll('.tip-card');
if (!pills.length || !cards.length) return;
pills.forEach(pill => {
pill.addEventListener('click', () => {
const category = pill.dataset.filter || 'all';
// Update active pill
pills.forEach(p => p.classList.remove('active'));
pill.classList.add('active');
// Filter cards
cards.forEach(card => {
if (category === 'all' || card.dataset.category === category) {
card.classList.remove('filter-hidden');
} else {
card.classList.add('filter-hidden');
}
});
});
});
};
/* ==========================================================
3. Card Hover / Touch Toggle (homepage)
========================================================== */
const initCardToggle = () => {
const isTouchDevice = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
if (!isTouchDevice) return;
// Update hover hints for touch devices
document.querySelectorAll('.hover-hint').forEach(hint => {
hint.textContent = '👆 tap or swipe →';
});
document.querySelectorAll('.tip-card').forEach(card => {
let touchStartX = 0;
let touchStartY = 0;
let touchEndX = 0;
let touchEndY = 0;
// Track touch start
card.addEventListener('touchstart', (e) => {
// Only track touches on the card-code area
if (!e.target.closest('.card-code')) return;
touchStartX = e.changedTouches[0].clientX;
touchStartY = e.changedTouches[0].clientY;
}, { passive: true });
// Handle touch end for swipe or tap
// Note: passive:false allows us to preventDefault on tap/swipe while still allowing vertical scrolling
card.addEventListener('touchend', (e) => {
// Only handle touches on the card-code area
if (!e.target.closest('.card-code')) return;
touchEndX = e.changedTouches[0].clientX;
touchEndY = e.changedTouches[0].clientY;
const deltaX = touchEndX - touchStartX;
const deltaY = touchEndY - touchStartY;
const absDeltaX = Math.abs(deltaX);
const absDeltaY = Math.abs(deltaY);
// Determine if it's a swipe (horizontal movement > 50px and more horizontal than vertical)
const isHorizontalSwipe = absDeltaX > 50 && absDeltaX > absDeltaY;
if (isHorizontalSwipe) {
// Prevent default navigation for horizontal swipes
e.preventDefault();
// Swipe left = show modern, swipe right = show old
if (deltaX < 0) {
// Swipe left - show modern
card.classList.add('toggled');
} else {
// Swipe right - show old
card.classList.remove('toggled');
}
} else if (absDeltaX < 10 && absDeltaY < 10) {
// It's a tap (movement under 10px threshold)
e.preventDefault();
card.classList.toggle('toggled');
}
// Note: Vertical scrolling (large deltaY, small deltaX) doesn't call preventDefault
}, { passive: false });
// Prevent click events on card-code from navigating (touch devices only)
// This is a safety net in case touch events trigger click as fallback
card.addEventListener('click', (e) => {
if (e.target.closest('.card-code')) {
e.preventDefault();
e.stopPropagation();
}
});
});
};
/* ==========================================================
4. Copy-to-Clipboard (article pages)
========================================================== */
const initCopyButtons = () => {
document.querySelectorAll('.copy-btn').forEach(btn => {
btn.addEventListener('click', () => {
// Find adjacent code block
const codeBlock = btn.closest('.code-header')?.nextElementSibling
|| btn.closest('.compare-panel-header')?.nextElementSibling?.querySelector('pre, code, .code-text')
|| btn.parentElement?.querySelector('pre, code, .code-text');
if (!codeBlock) return;
const text = codeBlock.textContent;
navigator.clipboard.writeText(text).then(() => {
btn.classList.add('copied');
const original = btn.textContent;
btn.textContent = 'Copied!';
setTimeout(() => {
btn.classList.remove('copied');
btn.textContent = original;
}, 2000);
}).catch(() => {
// Fallback for older browsers
const textarea = document.createElement('textarea');
textarea.value = text;
textarea.style.position = 'fixed';
textarea.style.opacity = '0';
document.body.appendChild(textarea);
textarea.select();
document.execCommand('copy');
document.body.removeChild(textarea);
btn.classList.add('copied');
const original = btn.textContent;
btn.textContent = 'Copied!';
setTimeout(() => {
btn.classList.remove('copied');
btn.textContent = original;
}, 2000);
});
});
});
};
/* ==========================================================
5. Syntax Highlighting (Java)
========================================================== */
const JAVA_KEYWORDS = new Set([
'abstract', 'assert', 'boolean', 'break', 'byte', 'case', 'catch',
'char', 'class', 'const', 'continue', 'default', 'do', 'double',
'else', 'enum', 'extends', 'final', 'finally', 'float', 'for',
'goto', 'if', 'implements', 'import', 'instanceof', 'int',
'interface', 'long', 'module', 'native', 'new', 'null', 'package',
'permits', 'private', 'protected', 'public', 'record', 'return',
'sealed', 'short', 'static', 'strictfp', 'super', 'switch',
'synchronized', 'this', 'throw', 'throws', 'transient', 'try',
'var', 'void', 'volatile', 'when', 'while', 'yield'
]);
const highlightJava = (code) => {
const tokens = [];
let i = 0;
const len = code.length;
while (i < len) {
// Block comments: /* ... */
if (code[i] === '/' && code[i + 1] === '*') {
let end = code.indexOf('*/', i + 2);
if (end === -1) end = len - 2;
const text = code.slice(i, end + 2);
tokens.push(`<span class="cmt">${escapeHtml(text)}</span>`);
i = end + 2;
continue;
}
// Line comments: // ...
if (code[i] === '/' && code[i + 1] === '/') {
let end = code.indexOf('\n', i);
if (end === -1) end = len;
const text = code.slice(i, end);
tokens.push(`<span class="cmt">${escapeHtml(text)}</span>`);
i = end;
continue;
}
// Text blocks: """ ... """
if (code[i] === '"' && code[i + 1] === '"' && code[i + 2] === '"') {
let end = code.indexOf('"""', i + 3);
if (end === -1) end = len - 3;
const text = code.slice(i, end + 3);
tokens.push(`<span class="str">${escapeHtml(text)}</span>`);
i = end + 3;
continue;
}
// String literals: "..."
if (code[i] === '"') {
let j = i + 1;
while (j < len && code[j] !== '"') {
if (code[j] === '\\') j++; // skip escaped char
j++;
}
const text = code.slice(i, j + 1);
tokens.push(`<span class="str">${escapeHtml(text)}</span>`);
i = j + 1;
continue;
}
// Char literals: '...'
if (code[i] === "'") {
let j = i + 1;
while (j < len && code[j] !== "'") {
if (code[j] === '\\') j++;
j++;
}
const text = code.slice(i, j + 1);
tokens.push(`<span class="str">${escapeHtml(text)}</span>`);
i = j + 1;
continue;
}
// Annotations: @Word
if (code[i] === '@' && i + 1 < len && /[A-Za-z_]/.test(code[i + 1])) {
let j = i + 1;
while (j < len && /[\w]/.test(code[j])) j++;
const text = code.slice(i, j);
tokens.push(`<span class="ann">${escapeHtml(text)}</span>`);
i = j;
continue;
}
// Numbers: digits (including hex, binary, underscores, suffixes)
if (/[0-9]/.test(code[i]) && (i === 0 || !/[\w]/.test(code[i - 1]))) {
let j = i;
// Hex/binary prefix
if (code[j] === '0' && (code[j + 1] === 'x' || code[j + 1] === 'X' ||
code[j + 1] === 'b' || code[j + 1] === 'B')) {
j += 2;
}
while (j < len && /[0-9a-fA-F_]/.test(code[j])) j++;
// Decimal part
if (code[j] === '.' && /[0-9]/.test(code[j + 1])) {
j++;
while (j < len && /[0-9_]/.test(code[j])) j++;
}
// Exponent
if (code[j] === 'e' || code[j] === 'E') {
j++;
if (code[j] === '+' || code[j] === '-') j++;
while (j < len && /[0-9_]/.test(code[j])) j++;
}
// Type suffix (L, f, d)
if (/[LlFfDd]/.test(code[j])) j++;
const text = code.slice(i, j);
tokens.push(`<span class="num">${escapeHtml(text)}</span>`);
i = j;
continue;
}
// Words: keywords, types, method calls
if (/[A-Za-z_$]/.test(code[i])) {
let j = i;
while (j < len && /[\w$]/.test(code[j])) j++;
const word = code.slice(i, j);
// Look ahead for method call: word(
let k = j;
while (k < len && code[k] === ' ') k++;
if (JAVA_KEYWORDS.has(word)) {
tokens.push(`<span class="kw">${escapeHtml(word)}</span>`);
} else if (code[k] === '(' && !/^[A-Z]/.test(word)) {
tokens.push(`<span class="fn">${escapeHtml(word)}</span>`);
} else if (/^[A-Z]/.test(word)) {
tokens.push(`<span class="typ">${escapeHtml(word)}</span>`);
} else {
tokens.push(escapeHtml(word));
}
i = j;
continue;
}
// Everything else: operators, punctuation, whitespace
tokens.push(escapeHtml(code[i]));
i++;
}
return tokens.join('');
};
const initSyntaxHighlighting = () => {
document.querySelectorAll('.code-text').forEach(el => {
// Skip if already highlighted
if (el.dataset.highlighted) return;
el.dataset.highlighted = 'true';
const raw = el.textContent;
el.innerHTML = highlightJava(raw);
});
};
/* ==========================================================
6. Newsletter Form
========================================================== */
const initNewsletter = () => {
const form = document.querySelector('.newsletter-form');
if (!form) return;
form.addEventListener('submit', (e) => {
e.preventDefault();
const box = form.closest('.newsletter-box');
if (box) {
box.innerHTML = '<p style="color: var(--accent); font-weight: 600;">Thanks! 🎉 You\'re on the list.</p>';
} else {
form.innerHTML = '<p style="color: var(--accent); font-weight: 600;">Thanks!</p>';
}
});
};
/* ==========================================================
Utilities
========================================================== */
const escapeHtml = (str) => {
const div = document.createElement('div');
div.textContent = str;
return div.innerHTML;
};
/* ==========================================================
Init
========================================================== */
document.addEventListener('DOMContentLoaded', () => {
loadSnippets().then(() => {
initSearch();
});
initFilters();
initCardToggle();
initCopyButtons();
initSyntaxHighlighting();
initNewsletter();
});
})();