File size: 26,587 Bytes
c015809 f6522be c015809 24f6106 c015809 f6522be c015809 f6522be c015809 f6522be 24f6106 f6522be c015809 f6522be c015809 f6522be c015809 f6522be c015809 f6522be c015809 f6522be c015809 beff9f5 c015809 beff9f5 c015809 f6522be c015809 f6522be c015809 f6522be c015809 f6522be c015809 f6522be c015809 f6522be c015809 f6522be c015809 f6522be c015809 f6522be c015809 f6522be c015809 24f6106 c015809 24f6106 c015809 24f6106 c015809 24f6106 f6522be c015809 f6522be c015809 f6522be c015809 f6522be c015809 888b6b8 f6522be 888b6b8 c015809 f6522be c015809 f6522be c015809 888b6b8 c015809 f6522be 888b6b8 c015809 888b6b8 f6522be c015809 24f6106 c015809 f6522be c015809 f6522be c015809 f6522be c015809 f6522be c015809 24f6106 c015809 24f6106 f6522be c015809 24f6106 c015809 f6522be c015809 24f6106 c015809 | 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 | /**
* Quote Studio - Main Application Logic
* Integrates live preview, avatar processing, Hugging Face Space API calls, and code exports.
*/
// API Configuration
// Subdomain Proxy: Direct POST to Vercel subdomain qc.mangrusdi.my.id
const SUBDOMAIN_URL = typeof window !== 'undefined' && window.location.origin.includes('qc.mangrusdi.my.id')
? 'https://qc.mangrusdi.my.id'
: (typeof window !== 'undefined' ? window.location.origin : 'https://qc.mangrusdi.my.id');
const HF_BACKEND_URL = 'https://ilhamdev-quote-api.hf.space';
const PRIMARY_ENDPOINT = '/generate';
const PROXY_ENDPOINT = '/api/generate';
const STATUS_ENDPOINT = '/status';
// DOM Elements
const form = document.getElementById('quoteForm');
const senderNameInput = document.getElementById('senderName');
const senderTitleInput = document.getElementById('senderTitle');
const avatarUrlInput = document.getElementById('avatarUrl');
const avatarUploadInput = document.getElementById('avatarUploadInput');
const messageTextInput = document.getElementById('messageText');
const replyToggle = document.getElementById('replyToggle');
const replyFields = document.getElementById('replyFields');
const replyNameInput = document.getElementById('replyName');
const replyTextInput = document.getElementById('replyText');
const mediaToggle = document.getElementById('mediaToggle');
const mediaFields = document.getElementById('mediaFields');
const mediaUrlInput = document.getElementById('mediaUrl');
const quoteTypeSelect = document.getElementById('quoteType');
const imageFormatSelect = document.getElementById('imageFormat');
const bgColorInput = document.getElementById('bgColor');
const bgColorTextInput = document.getElementById('bgColorText');
const watermarkInput = document.getElementById('watermark');
const watermarkGroup = document.getElementById('watermarkGroup');
const hpWebsiteInput = document.getElementById('hpWebsite');
const charCountBadge = document.getElementById('charCountBadge');
// Preview Elements
const prevAvatar = document.getElementById('prevAvatar');
const prevSenderName = document.getElementById('prevSenderName');
const prevSenderTitle = document.getElementById('prevSenderTitle');
const prevReplyBox = document.getElementById('prevReplyBox');
const prevReplyName = document.getElementById('prevReplyName');
const prevReplyText = document.getElementById('prevReplyText');
const prevMediaBox = document.getElementById('prevMediaBox');
const prevMediaImg = document.getElementById('prevMediaImg');
const prevMessageText = document.getElementById('prevMessageText');
const prevTimestamp = document.getElementById('prevTimestamp');
const simulatedBubble = document.getElementById('simulatedBubble');
const previewModeTag = document.getElementById('previewModeTag');
const previewStage = document.getElementById('previewStage');
// Action & Result Elements
const generateBtn = document.getElementById('generateBtn');
const resetFormBtn = document.getElementById('resetFormBtn');
const generatedResultBox = document.getElementById('generatedResultBox');
const renderedImage = document.getElementById('renderedImage');
const resultMeta = document.getElementById('resultMeta');
const downloadBtn = document.getElementById('downloadBtn');
const copyImageBtn = document.getElementById('copyImageBtn');
const apiStatusBadge = document.getElementById('apiStatusBadge');
const apiStatusText = document.getElementById('apiStatusText');
const toastEl = document.getElementById('toast');
const prevFormatMeta = document.getElementById('prevFormatMeta');
const prevBgMeta = document.getElementById('prevBgMeta');
// Code Playground Elements
const codeSnippet = document.getElementById('codeSnippet');
const copySnippetBtn = document.getElementById('copySnippetBtn');
const tabButtons = document.querySelectorAll('.tab-btn');
// Theme Elements
const themeToggleBtn = document.getElementById('themeToggleBtn');
const themeIconSun = document.getElementById('themeIconSun');
const themeIconMoon = document.getElementById('themeIconMoon');
let currentTab = 'curl';
let currentGeneratedBlob = null;
let lastGenerateTime = 0;
// Analytics & Event Tracking (Checklist Points 14, 15, 16)
function trackEvent(eventName, params = {}) {
const payload = {
event: eventName,
timestamp: new Date().toISOString(),
...params,
};
// 1. Google Tag Manager / GA4 dataLayer
window.dataLayer = window.dataLayer || [];
window.dataLayer.push(payload);
// 2. Custom DOM Event for client-side analytics listeners
window.dispatchEvent(new CustomEvent('analytics:track', { detail: payload }));
}
// Character Counter Update (Checklist Point 12)
function updateCharCount() {
if (!messageTextInput || !charCountBadge) return;
const count = messageTextInput.value.length;
charCountBadge.textContent = `${count} / 3000`;
if (count > 2800) {
charCountBadge.className = 'char-count-badge limit-danger';
} else if (count > 2000) {
charCountBadge.className = 'char-count-badge limit-warning';
} else {
charCountBadge.className = 'char-count-badge';
}
}
// Theme Functions
function initTheme() {
const saved = localStorage.getItem('qc_theme');
const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
const theme = saved || (prefersDark ? 'dark' : 'light');
setTheme(theme);
}
function setTheme(theme) {
if (theme === 'dark') {
document.documentElement.setAttribute('data-theme', 'dark');
if (themeIconSun) themeIconSun.style.display = 'none';
if (themeIconMoon) themeIconMoon.style.display = 'block';
} else {
document.documentElement.removeAttribute('data-theme');
if (themeIconSun) themeIconSun.style.display = 'block';
if (themeIconMoon) themeIconMoon.style.display = 'none';
}
localStorage.setItem('qc_theme', theme);
}
function toggleTheme() {
const isDark = document.documentElement.getAttribute('data-theme') === 'dark';
setTheme(isDark ? 'light' : 'dark');
}
// Initialize Timestamp
function updateTimestamp() {
const now = new Date();
const hours = String(now.getHours()).padStart(2, '0');
const minutes = String(now.getMinutes()).padStart(2, '0');
if (prevTimestamp) prevTimestamp.textContent = `${hours}:${minutes}`;
}
// Show Toast Notification
function showToast(message, type = 'info', duration = 3500) {
if (!toastEl) return;
toastEl.textContent = message;
toastEl.className = `toast ${type}`;
setTimeout(() => {
toastEl.className = 'toast hidden';
}, duration);
}
// Check Hugging Face API Status
async function checkApiStatus() {
try {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 6000);
// Check Subdomain Proxy /status first, fallback to HF backend directly
let res;
try {
res = await fetch(STATUS_ENDPOINT, { signal: controller.signal });
} catch {
// Subdomain failed, try /api/status or direct HF
}
if (!res || !res.ok) {
try {
res = await fetch(`${HF_BACKEND_URL}/status`, { signal: controller.signal });
} catch {
// Direct HF failed as well
}
}
clearTimeout(timeout);
if (res && res.ok) {
const data = await res.json();
apiStatusBadge.className = 'status-badge online';
apiStatusText.textContent = 'API Space Online';
apiStatusBadge.title = 'API Space Online';
} else {
throw new Error('Non-200 status');
}
} catch (err) {
apiStatusBadge.className = 'status-badge checking';
apiStatusText.textContent = 'HF Space Sleeping / Ready';
apiStatusBadge.title = 'HF Space Sleeping / Ready';
}
}
// Synchronize Live Preview with Form
function updateLivePreview() {
const name = senderNameInput.value.trim() || 'Anonymous';
const title = senderTitleInput.value.trim();
const avatar = avatarUrlInput.value.trim();
const text = messageTextInput.value.trim() || '...';
const isReply = replyToggle.checked;
const replyName = replyNameInput.value.trim() || 'Someone';
const replyText = replyTextInput.value.trim() || '';
const isMedia = mediaToggle.checked;
const mediaUrl = mediaUrlInput.value.trim();
const type = quoteTypeSelect.value;
const bgColor = bgColorInput.value;
// Sender Name & Tag
prevSenderName.textContent = name;
if (title) {
prevSenderTitle.textContent = title;
prevSenderTitle.style.display = 'inline-block';
} else {
prevSenderTitle.style.display = 'none';
}
// Avatar
if (avatar) {
prevAvatar.src = avatar;
}
// Bubble Background
simulatedBubble.querySelector('.tg-bubble-col').style.backgroundColor = bgColor;
// Quoted Reply Box
if (isReply) {
prevReplyBox.classList.remove('hidden');
prevReplyName.textContent = replyName;
prevReplyText.textContent = replyText;
replyFields.classList.remove('hidden');
} else {
prevReplyBox.classList.add('hidden');
replyFields.classList.add('hidden');
}
// Media Box
if (isMedia && mediaUrl) {
prevMediaBox.classList.remove('hidden');
prevMediaImg.src = mediaUrl;
mediaFields.classList.remove('hidden');
} else {
prevMediaBox.classList.add('hidden');
if (!isMedia) mediaFields.classList.add('hidden');
}
// Text
prevMessageText.textContent = text;
// Mode Tag & Watermark visibility
const fmt = (imageFormatSelect.value || 'png').toUpperCase();
if (type === 'stories') {
previewModeTag.textContent = 'Stories Mode (9:16)';
watermarkGroup.style.display = 'flex';
previewStage.style.minHeight = '320px';
if (prevFormatMeta) prevFormatMeta.textContent = `${fmt} (1080×1920) • Stories 9:16`;
} else if (type === 'image') {
previewModeTag.textContent = 'Image Mode';
watermarkGroup.style.display = 'flex';
previewStage.style.minHeight = '240px';
if (prevFormatMeta) prevFormatMeta.textContent = `${fmt} (1280×720) • Canvas`;
} else {
previewModeTag.textContent = 'Quote Mode';
watermarkGroup.style.display = 'none';
previewStage.style.minHeight = '200px';
if (prevFormatMeta) prevFormatMeta.textContent = `${fmt} (512px max) • Sticker`;
}
if (prevBgMeta) {
prevBgMeta.textContent = bgColor.toUpperCase();
}
// Update Code Snippets
updateCodeSnippets();
}
// Build JSON Payload for API
function buildApiPayload() {
const type = quoteTypeSelect.value;
const format = imageFormatSelect.value;
const bgColor = bgColorInput.value;
const watermark = watermarkInput.value.trim();
const isReply = replyToggle.checked;
const isMedia = mediaToggle.checked;
const mediaUrl = mediaUrlInput.value.trim();
const messageObj = {
entities: 'auto',
avatar: true,
from: {
id: 1,
name: senderNameInput.value.trim() || 'Mang Rusdi',
title: senderTitleInput.value.trim() || undefined,
photo: {
url: avatarUrlInput.value.trim() || undefined,
},
},
text: messageTextInput.value.trim() || 'Hello world',
};
if (isReply) {
messageObj.replyMessage = {
name: replyNameInput.value.trim() || 'Someone',
text: replyTextInput.value.trim() || 'Quoted text',
entities: 'auto',
};
}
if (isMedia && mediaUrl) {
messageObj.media = {
url: mediaUrl,
};
}
const payload = {
type: type === 'quote' ? '' : type,
format: format,
backgroundColor: bgColor,
width: 512,
height: type === 'stories' ? 1280 : 720,
scale: type === 'stories' ? 4 : 2,
messages: [messageObj],
};
if (watermark && (type === 'stories' || type === 'image')) {
payload.watermark = watermark;
}
return payload;
}
// Update Developer Code Snippets
function updateCodeSnippets() {
const payload = buildApiPayload();
const jsonString = JSON.stringify(payload, null, 2);
const targetApiUrl = `${SUBDOMAIN_URL}${PRIMARY_ENDPOINT}`;
if (currentTab === 'curl') {
codeSnippet.textContent = `curl -X POST "${targetApiUrl}" \\
-H "Content-Type: application/json" \\
-d '${jsonString}'`;
} else if (currentTab === 'js') {
codeSnippet.textContent = `const response = await fetch('${targetApiUrl}', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(${jsonString})
});
const data = await response.json();
const imageBase64 = data.image; // data:image/png;base64,...`;
} else if (currentTab === 'py') {
codeSnippet.textContent = `import requests
url = "${targetApiUrl}"
payload = ${JSON.stringify(payload, null, 4)}
response = requests.post(url, json=payload)
data = response.json()
image_base64 = data["image"]`;
}
}
// Switch Mobile Studio Tabs (Customizer vs Live Preview)
function switchMobileTab(target) {
const tabEditorBtn = document.getElementById('tabEditorBtn');
const tabPreviewBtn = document.getElementById('tabPreviewBtn');
const editorPanel = document.getElementById('editorPanel');
const previewPanel = document.getElementById('previewPanel');
if (target === 'editor') {
tabEditorBtn?.classList.add('active');
tabEditorBtn?.setAttribute('aria-selected', 'true');
tabPreviewBtn?.classList.remove('active');
tabPreviewBtn?.setAttribute('aria-selected', 'false');
editorPanel?.classList.add('active-mobile-view');
previewPanel?.classList.remove('active-mobile-view');
} else {
tabPreviewBtn?.classList.add('active');
tabPreviewBtn?.setAttribute('aria-selected', 'true');
tabEditorBtn?.classList.remove('active');
tabEditorBtn?.setAttribute('aria-selected', 'false');
previewPanel?.classList.add('active-mobile-view');
editorPanel?.classList.remove('active-mobile-view');
}
}
// Generate Quote via Backend API
async function generateQuote() {
// Point 13: Anti-spam Honeypot Trap
if (hpWebsiteInput && hpWebsiteInput.value.trim() !== '') {
console.warn('Spam bot blocked silently via honeypot trap.');
showToast('Quote berhasil digenerate!', 'success');
return;
}
const text = messageTextInput.value.trim();
const name = senderNameInput.value.trim();
// Point 12: Form Validation
if (!name) {
showToast('Nama pengirim tidak boleh kosong!', 'error');
senderNameInput.focus();
return;
}
if (name.length > 64) {
showToast('Nama pengirim maksimal 64 karakter!', 'error');
senderNameInput.focus();
return;
}
if (!text) {
showToast('Pesan chat tidak boleh kosong!', 'error');
messageTextInput.focus();
return;
}
if (text.length > 3000) {
showToast('Pesan chat maksimal 3000 karakter!', 'error');
messageTextInput.focus();
return;
}
// Points 14 & 16: Track form submission
trackEvent('form_submit', {
form: 'quoteForm',
quote_type: quoteTypeSelect.value,
format: imageFormatSelect.value,
});
// Client-side Cooldown Protection against Spam
const now = Date.now();
if (now - lastGenerateTime < 1500) {
showToast('Tunggu sebentar sebelum mengenerate kembali.', 'info');
return;
}
lastGenerateTime = now;
// Set Loading State
generateBtn.disabled = true;
const originalContent = generateBtn.innerHTML;
generateBtn.innerHTML = `
<span class="btn-icon">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" class="spin">
<circle cx="12" cy="12" r="10" stroke-opacity="0.25"></circle>
<path d="M12 2a10 10 0 0 1 10 10"></path>
</svg>
</span>
<span>Generating via Subdomain Proxy...</span>
`;
// On mobile screens, automatically switch to Preview tab so user sees loading & generated result
if (window.innerWidth <= 960) {
switchMobileTab('preview');
}
const payload = buildApiPayload();
const controller = new AbortController();
const timeoutTimer = setTimeout(() => controller.abort(), 35000);
try {
let response;
// Attempt request to Subdomain /generate first, then /api/generate, then direct HF
try {
response = await fetch(PRIMARY_ENDPOINT, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
signal: controller.signal,
});
} catch (e1) {
if (e1.name === 'AbortError') throw new Error('Request timeout setelah 35 detik');
}
if (!response || !response.ok) {
try {
response = await fetch(PROXY_ENDPOINT, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
signal: controller.signal,
});
} catch (e2) {
if (e2.name === 'AbortError') throw new Error('Request timeout setelah 35 detik');
}
}
if (!response || !response.ok) {
try {
response = await fetch(`${HF_BACKEND_URL}/`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
signal: controller.signal,
});
} catch (e3) {
if (e3.name === 'AbortError') throw new Error('Request timeout setelah 35 detik');
}
}
clearTimeout(timeoutTimer);
if (!response || !response.ok) {
if (response && response.status === 429) {
throw new Error('Batas permintaan (Rate Limit 30 req/min) tercapai untuk mengamankan kuota Hugging Face Space. Harap tunggu sebentar.');
}
if (response && response.status === 503) {
throw new Error('Server rendering sedang sibuk menangani antrean grafis. Coba lagi dalam beberapa detik.');
}
throw new Error(`Server returned HTTP ${response ? response.status : 'offline'}`);
}
const data = await response.json();
if (!data || !data.image) {
throw new Error(data?.message || 'API did not return image data');
}
// Process Base64 Image
const format = imageFormatSelect.value || 'png';
const base64Data = data.image.startsWith('data:')
? data.image
: `data:image/${format};base64,${data.image}`;
renderedImage.src = base64Data;
resultMeta.textContent = `${format.toUpperCase()} • ${data.width || 512}x${data.height || 'auto'}`;
downloadBtn.href = base64Data;
downloadBtn.download = `quote-${Date.now()}.${format}`;
// Convert to Blob for Clipboard
try {
const fetchBlob = await fetch(base64Data);
currentGeneratedBlob = await fetchBlob.blob();
} catch (e) {
console.warn('Could not cache blob for clipboard', e);
}
generatedResultBox.classList.remove('hidden');
generatedResultBox.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
showToast('Quote berhasil digenerate!', 'success');
// Point 14 & 16: Track successful generation
trackEvent('quote_generated_success', {
quote_type: quoteTypeSelect.value,
format: format,
duration_ms: Date.now() - now,
});
} catch (err) {
console.error('Generate Error:', err);
showToast(`Gagal: ${err.message}`, 'error', 6000);
} finally {
generateBtn.disabled = false;
generateBtn.innerHTML = originalContent;
}
}
// Copy Image to Clipboard
async function copyImageToClipboard() {
if (!currentGeneratedBlob) {
showToast('Gambar belum tersedia untuk disalin', 'error');
return;
}
try {
if (navigator.clipboard && window.ClipboardItem) {
// Browsers often require PNG for image clipboard items
const item = new ClipboardItem({ [currentGeneratedBlob.type]: currentGeneratedBlob });
await navigator.clipboard.write([item]);
showToast('Gambar berhasil disalin ke clipboard!', 'success');
} else {
throw new Error('ClipboardItem API not supported');
}
} catch (err) {
console.warn('Clipboard write failed, trying fallback', err);
showToast('Gunakan klik kanan "Copy Image" atau tombol Download Image', 'info');
}
}
// Copy Code Snippet
function copyCodeSnippet() {
const code = codeSnippet.textContent;
if (!code) return;
navigator.clipboard.writeText(code).then(() => {
showToast('Kode snippet disalin!', 'success');
const label = copySnippetBtn.querySelector('.copy-label') || copySnippetBtn.querySelector('span');
if (label) {
const prev = label.textContent;
label.textContent = 'Copied!';
setTimeout(() => { label.textContent = prev; }, 2000);
}
}).catch(() => {
showToast('Gagal menyalin snippet', 'error');
});
}
// Setup Event Listeners
function setupEvents() {
// Theme Toggle
if (themeToggleBtn) {
themeToggleBtn.addEventListener('click', toggleTheme);
}
// Real-time input updates
const inputs = [
senderNameInput,
senderTitleInput,
avatarUrlInput,
messageTextInput,
replyNameInput,
replyTextInput,
mediaUrlInput,
watermarkInput,
];
inputs.forEach(input => input.addEventListener('input', updateLivePreview));
// Selects & Toggles
replyToggle.addEventListener('change', updateLivePreview);
mediaToggle.addEventListener('change', updateLivePreview);
quoteTypeSelect.addEventListener('change', updateLivePreview);
imageFormatSelect.addEventListener('change', updateLivePreview);
// Background Color Sync
bgColorInput.addEventListener('input', () => {
bgColorTextInput.value = bgColorInput.value;
updateLivePreview();
});
bgColorTextInput.addEventListener('input', () => {
const val = bgColorTextInput.value.trim();
if (/^#[0-9A-Fa-f]{6}$/.test(val)) {
bgColorInput.value = val;
updateLivePreview();
}
});
// Preset Avatars
document.querySelectorAll('.preset-avatar-btn').forEach(btn => {
btn.addEventListener('click', () => {
const url = btn.dataset.url;
if (url) {
avatarUrlInput.value = url;
updateLivePreview();
}
});
});
// Preset Colors
document.querySelectorAll('.palette-btn').forEach(btn => {
btn.addEventListener('click', () => {
const color = btn.dataset.color;
if (color) {
document.querySelectorAll('.palette-btn').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
bgColorInput.value = color;
bgColorTextInput.value = color;
updateLivePreview();
}
});
});
// Avatar Upload Local File
avatarUploadInput.addEventListener('change', (e) => {
const file = e.target.files[0];
if (!file) return;
if (!file.type.startsWith('image/')) {
showToast('Harap pilih file gambar yang valid', 'error');
return;
}
const reader = new FileReader();
reader.onload = (event) => {
const base64Data = event.target.result;
avatarUrlInput.value = base64Data;
updateLivePreview();
showToast('Avatar lokal berhasil dimuat!', 'success');
};
reader.readAsDataURL(file);
});
// Form Reset
resetFormBtn.addEventListener('click', () => {
senderNameInput.value = 'Mang Rusdi';
senderTitleInput.value = 'Owner';
avatarUrlInput.value = 'https://avatars.githubusercontent.com/u/108991206?v=4';
messageTextInput.value = 'Halo semuanya! Quote API Telegram sekarang sudah live dan siap digunakan 🚀';
replyToggle.checked = true;
replyNameInput.value = 'Dika Ardnt';
replyTextInput.value = 'Kapan Quote API selesai dideploy?';
mediaToggle.checked = false;
mediaUrlInput.value = '';
quoteTypeSelect.value = 'quote';
imageFormatSelect.value = 'png';
bgColorInput.value = '#1b1e23';
bgColorTextInput.value = '#1b1e23';
watermarkInput.value = 'qc.mangrusdi.my.id';
generatedResultBox.classList.add('hidden');
updateLivePreview();
updateCharCount();
showToast('Form direset ke default', 'info');
});
// Form Submission Handler (Point 12 & 14)
if (form) {
form.addEventListener('submit', (e) => {
e.preventDefault();
generateQuote();
});
}
// Character Counter Input Listener (Point 12)
if (messageTextInput) {
messageTextInput.addEventListener('input', updateCharCount);
}
// Mobile menu toggle
const mobileMenuBtn = document.getElementById('mobileMenuBtn');
const navLinks = document.querySelector('.nav-links');
if (mobileMenuBtn && navLinks) {
mobileMenuBtn.addEventListener('click', (e) => {
e.stopPropagation();
const isOpen = navLinks.classList.toggle('open');
mobileMenuBtn.setAttribute('aria-expanded', String(isOpen));
});
navLinks.querySelectorAll('.nav-anchor').forEach(link => {
link.addEventListener('click', () => {
navLinks.classList.remove('open');
mobileMenuBtn.setAttribute('aria-expanded', 'false');
});
});
document.addEventListener('click', (e) => {
if (!navLinks.contains(e.target) && !mobileMenuBtn.contains(e.target)) {
navLinks.classList.remove('open');
mobileMenuBtn.setAttribute('aria-expanded', 'false');
}
});
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
navLinks.classList.remove('open');
mobileMenuBtn.setAttribute('aria-expanded', 'false');
}
});
}
// Mobile Studio Switcher Tabs
const tabEditorBtn = document.getElementById('tabEditorBtn');
const tabPreviewBtn = document.getElementById('tabPreviewBtn');
if (tabEditorBtn && tabPreviewBtn) {
tabEditorBtn.addEventListener('click', () => switchMobileTab('editor'));
tabPreviewBtn.addEventListener('click', () => switchMobileTab('preview'));
}
// Generate Button
generateBtn.addEventListener('click', generateQuote);
// Copy Image Button
copyImageBtn.addEventListener('click', copyImageToClipboard);
// Copy Snippet Button
copySnippetBtn.addEventListener('click', copyCodeSnippet);
// Playground Tabs
tabButtons.forEach(btn => {
btn.addEventListener('click', () => {
tabButtons.forEach(b => b.classList.remove('active'));
btn.classList.add('active');
currentTab = btn.dataset.tab;
updateCodeSnippets();
});
});
// Automatic Data-Track Event Listeners (Points 14, 15, 16)
document.querySelectorAll('[data-track]').forEach((el) => {
el.addEventListener('click', () => {
trackEvent(el.dataset.track, {
text: el.innerText ? el.innerText.trim().slice(0, 50) : (el.title || el.id || 'unlabeled'),
tag: el.tagName.toLowerCase(),
href: el.getAttribute('href') || undefined,
});
});
});
}
// App Initialization
function init() {
initTheme();
updateTimestamp();
updateCharCount();
updateLivePreview();
setupEvents();
checkApiStatus();
}
// Run on DOM Ready
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
|