Transaltor / lens.html
Aichatbot12321's picture
Upload 27 files
84e1dd3 verified
Raw History Blame Contribute Delete
81.9 kB
<!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, viewport-fit=cover"> <title>Lens Studio</title> <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700;800&display=swap" rel="stylesheet"> <script src="https://cdn.jsdelivr.net/npm/marked@4.3.0/marked.min.js"></script> <!-- 🚨 MATH FIX: MathJax must be CONFIGURED before it loads, otherwise it only recognizes \( \) for inline math and ignores single $ ... $, which is what made fractions/equations show up as raw text like "\frac{1}{2}" or "fac(0)" instead of being rendered. This config + the LaTeX system-prompt rules below are what actually fix that. --> <script> window.MathJax = { tex: { inlineMath: [['$', '$'], ['\\(', '\\)']], displayMath: [['$$', '$$'], ['\\[', '\\]']] }, options: { skipHtmlTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code'] }, chtml: { displayAlign: 'left' } }; </script> <script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script> <style> /* ============ THEME VARIABLES (LIGHT / DARK) ============ */ :root { --accent: #4285F4; --accent-2: #ff9500; --danger: #ff3b30; --success: #34c759; --lens-blue: #4285F4; --lens-red: #EA4335; --lens-yellow: #FBBC04; --lens-green: #34A853; --bg-color: #f2f2f7; --pane-bg: rgba(255, 255, 255, 0.96); --text-dark: #1c1c1e; --text-sub: #6e6e73; --bubble-ai: #ffffff; --bubble-user: #4285F4; --chip-bg: rgba(120,120,128,0.12); --grad-1: #e0c3fc; --grad-2: #8ec5fc; } [data-theme="dark"] { --bg-color: #0e0e10; --pane-bg: rgba(28, 28, 32, 0.97); --text-dark: #f2f2f7; --text-sub: #a0a0a8; --bubble-ai: #232327; --chip-bg: rgba(255,255,255,0.08); --grad-1: #1a1a2e; --grad-2: #16213e; } * { box-sizing: border-box; margin: 0; padding: 0; } /* ===== NO CONTEXT MENUS / NO NATIVE LONG-PRESS CALLOUTS — Android, iOS, desktop ===== */ *, *::before, *::after { -webkit-touch-callout: none; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } img, video, canvas { -webkit-user-drag: none; -khtml-user-drag: none; -moz-user-drag: none; -o-user-drag: none; user-drag: none; -webkit-touch-callout: none; } #chat-input { -webkit-user-select: text; user-select: text; } select { -webkit-user-select: auto; user-select: auto; } body, html { width: 100%; height: 100dvh; background: linear-gradient(120deg, var(--grad-1) 0%, var(--grad-2) 100%); font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", Roboto, sans-serif; overflow: hidden; color: var(--text-dark); } /* ===== DECORATION: soft floating orbs + sparkle dust (cheap: transform/opacity only) ===== */ @keyframes floatOrb { 0%, 100% { transform: translate(0, 0) scale(1); } 50% { transform: translate(16px, -18px) scale(1.06); } } .deco-orb { position: absolute; border-radius: 50%; pointer-events: none; z-index: 0; will-change: transform; } .orb-a { width: 260px; height: 260px; top: -80px; left: -80px; background: radial-gradient(circle, rgba(255,149,0,0.25), rgba(255,149,0,0) 70%); animation: floatOrb 16s ease-in-out infinite; } .orb-b { width: 220px; height: 220px; bottom: 5%; right: -70px; background: radial-gradient(circle, rgba(52,199,89,0.22), rgba(52,199,89,0) 70%); animation: floatOrb 20s ease-in-out infinite reverse; } .orb-c { width: 180px; height: 180px; top: 40%; right: -60px; background: radial-gradient(circle, rgba(66,133,244,0.2), rgba(66,133,244,0) 70%); animation: floatOrb 24s ease-in-out infinite; } @keyframes sparkleTwinkle { 0%, 100% { opacity: 0; transform: scale(0.4); } 50% { opacity: 0.85; transform: scale(1); } } .sparkle { position: absolute; width: 4px; height: 4px; border-radius: 50%; background: #fff; opacity: 0; pointer-events: none; z-index: 1; box-shadow: 0 0 6px 1px rgba(255,255,255,0.7); animation: sparkleTwinkle 3.2s ease-in-out infinite; } #camera-view, #captured-view { position: absolute; top: 0; left: 0; width: 100%; height: 100dvh; display: flex; flex-direction: column; justify-content: center; align-items: center; } #captured-view { display: none; background: #000; } video { width: 100%; height: 100%; object-fit: cover; touch-action: none; will-change: transform; } #image-stage { position: absolute; top: 0; left: 0; width: 100%; height: 100%; transition: transform 0.3s cubic-bezier(0.2,0.8,0.2,1); } #crop-canvas { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 5; touch-action: none; } /* ===== VIEWFINDER CORNER FRAME + RULE-OF-THIRDS GRID (camera-view only) ===== */ #viewfinder { position: absolute; inset: 0; z-index: 4; pointer-events: none; } @keyframes vfPulse { 0%, 100% { opacity: 0.5; } 50% { opacity: 1; } } .vf-corner { position: absolute; width: 26px; height: 26px; border-color: rgba(255,255,255,0.92); opacity: 0.75; animation: vfPulse 3.2s ease-in-out infinite; } .vf-tl { top: 80px; left: 18px; border-top: 3px solid; border-left: 3px solid; border-radius: 14px 0 0 0; } .vf-tr { top: 80px; right: 18px; border-top: 3px solid; border-right: 3px solid; border-radius: 0 14px 0 0; } .vf-bl { bottom: 186px; left: 18px; border-bottom: 3px solid; border-left: 3px solid; border-radius: 0 0 0 14px; } .vf-br { bottom: 186px; right: 18px; border-bottom: 3px solid; border-right: 3px solid; border-radius: 0 0 14px 0; } #grid-overlay { position: absolute; inset: 0; z-index: 3; pointer-events: none; opacity: 0; transition: opacity 0.25s; } #grid-overlay.show { opacity: 1; } .grid-line { position: absolute; background: rgba(255,255,255,0.38); } .grid-line.v { top: 0; bottom: 0; width: 1px; } .grid-line.h { left: 0; right: 0; height: 1px; } #zoom-pill { position: absolute; bottom: 195px; left: 50%; transform: translateX(-50%); z-index: 11; background: rgba(0,0,0,0.55); color: #fff; padding: 5px 14px; border-radius: 14px; font-size: 0.8rem; font-weight: 700; opacity: 0; transition: opacity 0.2s; pointer-events: none; } #zoom-pill.show { opacity: 1; } /* ===== TEXT DETECTION OVERLAY (selectable / copyable text, like Lens) ===== */ #text-overlay { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 6; pointer-events: none; } .text-box { position: absolute; background: rgba(66,133,244,0.16); border: 1.5px solid rgba(255,255,255,0.65); border-radius: 4px; pointer-events: auto; cursor: pointer; opacity: 0; transition: background 0.15s, opacity 0.25s; } .text-box.selected { background: rgba(66,133,244,0.42); border-color: #4285F4; } .text-box.translated-label { background: rgba(52,199,89,0.92); border-color: #fff; color: #fff; opacity: 1 !important; font-size: 0.72rem; font-weight: 700; padding: 2px 4px; overflow: hidden; display: flex; align-items: center; box-shadow: 0 4px 10px rgba(0,0,0,0.25); } /* ===== MAGNIFIER LOUPE (shown while dragging a crop selection) ===== */ #magnifier { position: fixed; width: 116px; height: 116px; border-radius: 50%; border: 3px solid #fff; box-shadow: 0 10px 26px rgba(0,0,0,0.4); pointer-events: none; z-index: 60; display: none; overflow: hidden; transform: translate(-50%, -145%); } #magnifier canvas { width: 100%; height: 100%; image-rendering: pixelated; } #magnifier::after { content: ''; position: absolute; top: 50%; left: 50%; width: 14px; height: 14px; margin: -7px 0 0 -7px; border: 1.5px solid rgba(255,59,48,0.9); border-radius: 50%; } /* ===== SELECTION TOOLBAR (copy selected words) ===== */ #selection-toolbar { position: absolute; bottom: 130px; left: 50%; transform: translateX(-50%) translateY(20px); z-index: 25; display: none; gap: 8px; align-items: center; flex-wrap: wrap; justify-content: center; max-width: 92vw; background: rgba(20,20,24,0.95); padding: 10px 14px; border-radius: 26px; box-shadow: 0 10px 30px rgba(0,0,0,0.35); opacity: 0; transition: opacity 0.25s, transform 0.25s; } #selection-toolbar.show { display: flex; opacity: 1; transform: translateX(-50%) translateY(0); } #selection-toolbar button { border: none; border-radius: 20px; padding: 9px 14px; font-weight: 700; font-size: 0.8rem; cursor: pointer; transition: transform 0.15s; white-space: nowrap; } #selection-toolbar button:active { transform: scale(0.92); } #sel-copy-btn { background: #fff; color: #1c1c1e; } #sel-copyall-btn { background: rgba(255,255,255,0.15); color: #fff; } #sel-google-btn { background: var(--lens-blue); color: #fff; } #sel-clear-btn { background: rgba(255,255,255,0.15); color: #fff; } #sel-count { color: #fff; font-size: 0.78rem; font-weight: 600; opacity: 0.85; padding: 0 2px; } /* ===== SMART MODE SUGGESTION CHIP ===== */ #smart-suggestion { position: absolute; top: 108px; left: 50%; transform: translateX(-50%) translateY(-10px); z-index: 22; display: none; align-items: center; gap: 10px; max-width: 90vw; background: rgba(20,20,24,0.94); color: #fff; padding: 10px 14px; border-radius: 20px; font-size: 0.82rem; font-weight: 600; box-shadow: 0 10px 26px rgba(0,0,0,0.3); } #smart-suggestion.show { display: flex; animation: slideUpBounce 0.4s cubic-bezier(0.2,0.8,0.2,1); } #smart-suggestion button { border: none; border-radius: 14px; padding: 6px 12px; font-weight: 700; font-size: 0.76rem; cursor: pointer; white-space: nowrap; } #smart-suggestion-btn { background: #fff; color: #1c1c1e; } #smart-suggestion-close { background: rgba(255,255,255,0.18); color: #fff; } .top-controls { position: absolute; top: max(16px, env(safe-area-inset-top)); left: 16px; right: 16px; display: flex; justify-content: space-between; flex-wrap: nowrap; z-index: 10; gap: 8px; } .top-controls-left, .top-controls-right { display: flex; gap: 8px; flex-wrap: wrap; } .icon-btn { background: rgba(0,0,0,0.38); border: 1px solid rgba(255,255,255,0.3); border-radius: 50%; width: 46px; height: 46px; display: flex; justify-content: center; align-items: center; font-size: 20px; color: #fff; cursor: pointer; transition: transform 0.2s ease; position: relative; flex-shrink: 0; } .icon-btn:active { transform: scale(0.82); } .icon-btn.active { background: rgba(255,204,0,0.9); border-color: rgba(255,204,0,0.9); } .ripple { position: absolute; border-radius: 50%; background: rgba(255,255,255,0.6); transform: scale(0); animation: rippleAnim 0.6s ease-out; pointer-events: none; } @keyframes rippleAnim { to { transform: scale(4); opacity: 0; } } @keyframes breathe { 0%, 100% { transform: translateX(-50%) scale(1); } 50% { transform: translateX(-50%) scale(1.05); } } /* ===================================================================== CAPTURE BUTTON — plain white circle like real Google Lens (no colorful ring gimmick), and ALWAYS perfectly centered via its own left:50% + translateX(-50%), completely independent of the last-shot thumbnail next to it (that was why it looked "pushed left" before — it was sharing a grid track with a sibling that could shift the whole row). ===================================================================== */ .capture-container { position: absolute; bottom: 40px; left: 0; right: 0; height: 76px; z-index: 10; } .capture-btn { position: absolute; left: 50%; top: 0; transform: translateX(-50%); width: 76px; height: 76px; background: #ffffff; border-radius: 50%; border: 4px solid rgba(255,255,255,0.95); cursor: pointer; transition: transform 0.15s; animation: breathe 3s ease-in-out infinite; box-shadow: 0 10px 26px rgba(0,0,0,0.28); } .capture-btn:active { transform: translateX(-50%) scale(0.9); animation: none; background: #eaeaea; } .thumb-fab { position: absolute; left: 50%; top: 50%; transform: translate(calc(-50% - 108px), -50%); width: 46px; height: 46px; border-radius: 14px; overflow: hidden; border: 2px solid rgba(255,255,255,0.85); box-shadow: 0 6px 16px rgba(0,0,0,0.3); background: rgba(0,0,0,0.35); cursor: pointer; display: none; align-items: center; justify-content: center; transition: transform 0.15s; } .thumb-fab img { width: 100%; height: 100%; object-fit: cover; } .thumb-fab:active { transform: translate(calc(-50% - 108px), -50%) scale(0.88); } /* ===== tap-to-focus ring ===== */ .focus-ring { position: fixed; width: 64px; height: 64px; margin-left: -32px; margin-top: -32px; border: 2px solid #fff; border-radius: 12px; pointer-events: none; z-index: 998; animation: focusRingAnim 0.6s ease-out forwards; } @keyframes focusRingAnim { 0% { transform: scale(1.3); opacity: 1; } 100% { transform: scale(1); opacity: 0; } } .confetti-piece { position: fixed; width: 8px; height: 8px; border-radius: 2px; pointer-events: none; z-index: 999; animation: confettiBurst 0.9s ease-out forwards; } @keyframes confettiBurst { 0% { transform: translate(0,0) rotate(0deg) scale(1); opacity: 1; } 100% { transform: translate(var(--dx), var(--dy)) rotate(var(--rot)) scale(0.3); opacity: 0; } } /* ===================================================================== MODE TABS — shared pill style used in THREE places: 1) #mode-selector-precapture — floats above the shutter, camera-view only 2) #mode-selector-sheet — lives INSIDE the results sheet's own header 3) #mode-selector-translate — lives inside the dedicated translate panel Because (2) and (3) are normal in-flow children of their own panel (not fixed/floating), they can never overlap or squeeze anything else — they simply appear and disappear together with their parent panel. ===================================================================== */ .mode-tabs { display: flex; gap: 7px; overflow-x: auto; scrollbar-width: none; -webkit-overflow-scrolling: touch; } .mode-tabs::-webkit-scrollbar { display: none; } @keyframes chipBounceIn { 0% { opacity: 0; transform: translateY(-8px); } 100% { opacity: 1; transform: translateY(0); } } .mode-chip { background: rgba(0,0,0,0.42); color: #fff; font-weight: 600; font-size: 0.78rem; padding: 7px 14px; border-radius: 20px; cursor: pointer; white-space: nowrap; border: 1px solid rgba(255,255,255,0.3); transition: background 0.2s, color 0.2s, transform 0.15s; flex-shrink: 0; } .mode-chip.selected { background: #4285F4; color: #fff; border-color: #4285F4; } #mode-selector-precapture { position: absolute; bottom: 132px; left: 0; right: 0; padding: 0 16px; z-index: 10; animation: chipBounceIn 0.3s ease; } #mode-selector-sheet .mode-chip, #mode-selector-translate .mode-chip { background: var(--chip-bg); color: var(--text-dark); border-color: transparent; } #mode-selector-sheet .mode-chip.selected, #mode-selector-translate .mode-chip.selected { background: #4285F4; color: #fff; } #mode-selector-sheet { width: 100%; max-width: 800px; padding-bottom: 10px; } #mode-selector-translate { padding-bottom: 2px; } #back-btn { position: absolute; top: 16px; left: 16px; z-index: 20; display: none; background: rgba(0,0,0,0.45); } #gallery-strip { position: absolute; top: 68px; left: 0; right: 0; z-index: 15; display: none; gap: 10px; padding: 6px 16px; overflow-x: auto; -webkit-overflow-scrolling: touch; } .gallery-thumb { width: 48px; height: 48px; border-radius: 14px; object-fit: cover; flex-shrink: 0; border: 2px solid rgba(255,255,255,0.7); cursor: pointer; transition: transform 0.2s; box-shadow: 0 4px 10px rgba(0,0,0,0.2); } .gallery-thumb:active { transform: scale(1.1); } .gallery-thumb.current { border-color: var(--accent-2); } /* Blur is fine here — sheets sit over a static image, not the moving camera feed. */ #bottom-pane { position: absolute; left: 0; right: 0; bottom: 0; height: 85dvh; background: var(--pane-bg); backdrop-filter: blur(18px); -webkit-backdrop-filter: blur(18px); border-radius: 28px 28px 0 0; box-shadow: 0 -10px 40px rgba(0,0,0,0.15); transition: transform 0.5s cubic-bezier(0.2, 0.8, 0.2, 1); z-index: 30; display: none; flex-direction: column; align-items: center; padding: 10px 20px 15px; transform: translateY(100%); font-family: 'Poppins', -apple-system, BlinkMacSystemFont, sans-serif; } #bottom-pane.peek { transform: translateY(45%); } #bottom-pane.full { transform: translateY(0%); } #bottom-pane.closed { transform: translateY(calc(100% - 45px)); } .drag-handle-container { width: 100%; height: 26px; display: flex; justify-content: center; align-items: center; cursor: grab; flex-shrink: 0; } .drag-handle { width: 50px; height: 5px; background: #c7c7cc; border-radius: 5px; transition: 0.3s; } .drag-handle-container:active .drag-handle { background: #8e8e93; transform: scaleX(1.2); } #pane-title { font-size: 0.85rem; font-weight: 800; text-align: center; margin: 4px 0 8px; display: flex; align-items: center; justify-content: center; gap: 8px; flex-shrink: 0; } .pane-title-text { background: linear-gradient(90deg, var(--lens-blue), var(--lens-red), var(--lens-yellow), var(--lens-green), var(--lens-blue)); background-size: 300% auto; -webkit-background-clip: text; background-clip: text; color: transparent; animation: shimmerText 4s linear infinite; } @keyframes shimmerText { to { background-position: 300% center; } } .lens-dots { display: inline-flex; gap: 3px; } .lens-dots i { width: 6px; height: 6px; border-radius: 50%; display: inline-block; font-style: normal; } .lens-dots i:nth-child(1) { background: var(--lens-blue); } .lens-dots i:nth-child(2) { background: var(--lens-red); } .lens-dots i:nth-child(3) { background: var(--lens-yellow); } .lens-dots i:nth-child(4) { background: var(--lens-green); } #chat-history { width: 100%; max-width: 800px; flex-grow: 1; overflow-y: auto; overflow-x: hidden; padding: 6px 0 20px 0; display: flex; flex-direction: column; gap: 18px; } @keyframes slideUpBounce { 0% { opacity: 0; transform: translateY(30px) scale(0.95); } 60% { opacity: 1; transform: translateY(-5px) scale(1.02); } 100% { opacity: 1; transform: translateY(0) scale(1); } } .msg { font-size: 1.05rem; line-height: 1.5; display: flex; flex-direction: column; animation: slideUpBounce 0.4s cubic-bezier(0.2, 0.8, 0.2, 1) forwards; } .msg.user { align-items: flex-end; } .msg.user .bubble { background: var(--bubble-user); color: #fff; padding: 14px 20px; border-radius: 22px 22px 6px 22px; box-shadow: 0 4px 15px rgba(66,133,244,0.3); display: inline-block; max-width: 85%; } .msg.ai { align-items: flex-start; } .msg.ai .bubble { background: var(--bubble-ai); color: var(--text-dark); padding: 14px 20px; border-radius: 22px 22px 22px 6px; box-shadow: 0 4px 20px rgba(0,0,0,0.08); display: inline-block; width: max-content; max-width: 90%; transition: width 0.2s cubic-bezier(0.2, 0.8, 0.2, 1); } .msg.ai strong { color: inherit; font-weight: 700; } .msg img.chat-crop { max-width: 200px; border-radius: 16px; margin-bottom: 8px; display: block; box-shadow: 0 4px 15px rgba(0,0,0,0.1); } .msg.ai .bubble mjx-container[display="true"] { display: block; overflow-x: auto; -webkit-overflow-scrolling: touch; max-width: 100%; padding: 6px 0; touch-action: pan-x; } .msg.ai .bubble mjx-container[display="true"]::-webkit-scrollbar { height: 4px; } .msg.ai .bubble mjx-container[display="true"]::-webkit-scrollbar-thumb { background: rgba(0,0,0,0.15); border-radius: 4px; } .msg.ai .bubble mjx-container { max-width: 100%; } .msg-actions { display: flex; gap: 10px; margin-top: 6px; opacity: 0.8; flex-wrap: wrap; } .msg-actions button { background: none; border: none; cursor: pointer; font-size: 0.85rem; color: var(--text-sub); display: flex; align-items: center; gap: 4px; transition: transform 0.2s, color 0.2s; } .msg-actions button:hover { color: var(--accent); transform: translateY(-1px); } .msg-actions button:active { transform: scale(0.9); } .msg-actions button.done { color: #34c759; } .msg-actions button.speaking { color: #ff3b30; } .fade-in { animation: fadeIn 0.25s ease-out forwards; opacity: 0; display: inline; } @keyframes fadeIn { to { opacity: 1; } } /* ===================================================================== THINKING INDICATOR — a plain card with ONE simple spinning ring (single accent color). No conic-gradient wedge, no moving color blob. ===================================================================== */ .thinking-wrap { padding: 2px 0; } .thinking-card { display: flex; align-items: center; gap: 14px; padding: 14px 18px; border-radius: 20px; background: var(--bubble-ai); box-shadow: 0 4px 20px rgba(0,0,0,0.08); min-width: 210px; } .thinking-orb { width: 22px; height: 22px; border-radius: 50%; flex-shrink: 0; border: 3px solid rgba(66,133,244,0.15); border-top-color: var(--lens-blue); animation: spin 0.85s linear infinite; } @keyframes spin { to { transform: rotate(360deg); } } .thinking-copy { display: flex; flex-direction: column; min-width: 140px; } .thinking-label { font-size: 0.85rem; font-weight: 700; color: var(--text-sub); margin-bottom: 6px; } .thinking-bar { width: 140px; height: 4px; border-radius: 4px; background: rgba(120,120,128,0.18); overflow: hidden; position: relative; } .thinking-bar span { position: absolute; left: -40%; width: 40%; height: 100%; background: linear-gradient(90deg, transparent, var(--accent), transparent); animation: scanBar 1.2s infinite linear; } @keyframes scanBar { 0% { left: -40%; } 100% { left: 100%; } } #progress-bar { position: fixed; top: 0; left: 0; height: 3px; width: 0%; background: linear-gradient(90deg, var(--lens-blue), var(--lens-red), var(--lens-yellow), var(--lens-green)); z-index: 999; transition: width 0.3s ease; box-shadow: 0 0 8px var(--accent); } #input-area { width: 100%; max-width: 800px; display: flex; gap: 8px; padding-bottom: 10px; align-items: center; flex-shrink: 0; } #chat-input { flex-grow: 1; padding: 15px 22px; border-radius: 30px; border: none; min-width: 0; background: rgba(120,120,128,0.1); box-shadow: inset 0 2px 5px rgba(0,0,0,0.05); color: var(--text-dark); font-size: 1.05rem; outline: none; transition: 0.3s; font-family: 'Poppins', -apple-system, BlinkMacSystemFont, sans-serif; } #chat-input:focus { background: rgba(120,120,128,0.16); box-shadow: 0 4px 20px rgba(0,0,0,0.1); } #mic-btn { width: 46px; height: 46px; border-radius: 50%; border: none; background: var(--chip-bg); font-size: 1.1rem; cursor: pointer; flex-shrink: 0; transition: 0.3s; } #mic-btn.listening { background: #ff3b30; color: #fff; animation: micPulse 1s ease-in-out infinite; } @keyframes micPulse { 0%,100% { box-shadow: 0 0 0 0 rgba(255,59,48,0.6); } 50% { box-shadow: 0 0 0 10px rgba(255,59,48,0); } } #send-btn { width: 48px; height: 48px; border-radius: 50%; border: none; font-weight: 700; font-size: 1.2rem; background: var(--lens-blue); color: white; cursor: pointer; transition: 0.3s cubic-bezier(0.2, 0.8, 0.2, 1); box-shadow: 0 4px 15px rgba(66, 133, 244, 0.35); flex-shrink: 0; display: flex; align-items: center; justify-content: center; } #send-btn.stop { background: #ff3b30; box-shadow: 0 4px 15px rgba(255, 59, 48, 0.3); } #send-btn:active { transform: scale(0.88) rotate(10deg); } #send-btn svg { width: 20px; height: 20px; } #analyze-crop-btn { position: absolute; bottom: 118px; left: 50%; transform: translateX(-50%); z-index: 20; padding: 15px 30px; background: rgba(255,255,255,0.95); color: var(--text-dark); border-radius: 30px; font-weight: 700; border: none; display: none; box-shadow: 0 10px 30px rgba(0,0,0,0.2); cursor: pointer; backdrop-filter: blur(10px); animation: slideUpBounce 0.4s forwards; font-size: 0.9rem; } #toast-container { position: fixed; bottom: 24px; left: 50%; transform: translateX(-50%); z-index: 9999; display: flex; flex-direction: column; gap: 8px; align-items: center; } .toast { background: rgba(30,30,34,0.92); color: #fff; padding: 12px 22px; border-radius: 20px; font-size: 0.9rem; font-weight: 600; box-shadow: 0 6px 20px rgba(0,0,0,0.3); backdrop-filter: blur(10px); animation: toastIn 0.35s cubic-bezier(0.2,0.8,0.2,1) forwards, toastOut 0.35s ease-in forwards 2.2s; } @keyframes toastIn { from { opacity: 0; transform: translateY(20px) scale(0.9); } to { opacity: 1; transform: translateY(0) scale(1); } } @keyframes toastOut { to { opacity: 0; transform: translateY(-10px) scale(0.9); } } /* ===================================================================== DEDICATED TRANSLATE PANEL — shown INSTEAD of the chat sheet. No AI conversation lives here at all: just the mode tabs (so you can still switch away) and a Google-Translate-style "Detected -> Language" row. Picking a language auto-translates immediately. ===================================================================== */ #translate-toolbar { position: fixed; left: 0; right: 0; bottom: 0; z-index: 30; display: none; flex-direction: column; background: var(--pane-bg); backdrop-filter: blur(18px); -webkit-backdrop-filter: blur(18px); border-radius: 28px 28px 0 0; box-shadow: 0 -10px 30px rgba(0,0,0,0.18); padding: 16px 18px max(16px, env(safe-area-inset-bottom)); gap: 12px; font-family: 'Poppins', -apple-system, BlinkMacSystemFont, sans-serif; } .translate-row { display: flex; align-items: center; gap: 10px; } .translate-box { flex: 1; min-width: 0; background: var(--chip-bg); border-radius: 14px; padding: 8px 12px; } .translate-box-label { display: block; font-size: 0.62rem; text-transform: uppercase; letter-spacing: 0.5px; color: var(--text-sub); font-weight: 800; margin-bottom: 2px; } .translate-box-value { display: block; font-size: 0.85rem; color: var(--text-dark); font-weight: 700; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .translate-arrow { color: var(--text-sub); font-size: 1.1rem; flex-shrink: 0; } .target-wrap { position: relative; padding: 0; background: transparent; } #translate-lang-select { width: 100%; background: var(--chip-bg); color: var(--text-dark); border: 1.5px solid rgba(120,120,128,0.25); border-radius: 14px; padding: 10px 30px 10px 12px; font-size: 0.85rem; font-weight: 700; cursor: pointer; appearance: none; -webkit-appearance: none; font-family: inherit; } .target-wrap::after { content: '▾'; position: absolute; right: 12px; top: 50%; transform: translateY(-50%); color: var(--text-sub); pointer-events: none; font-size: 0.8rem; } /* ===== SMALL SCREEN RESPONSIVE FIXES ===== */ @media (max-width: 400px) { .icon-btn { width: 40px; height: 40px; font-size: 17px; } .mode-chip { font-size: 0.7rem; padding: 6px 11px; } .capture-btn { width: 66px; height: 66px; } .capture-container { bottom: 36px; height: 66px; } .thumb-fab { width: 40px; height: 40px; transform: translate(calc(-50% - 92px), -50%); } .thumb-fab:active { transform: translate(calc(-50% - 92px), -50%) scale(0.88); } #mode-selector-precapture { bottom: 112px; } .vf-bl, .vf-br { bottom: 168px; } #zoom-pill { bottom: 178px; } #chat-input { padding: 12px 18px; font-size: 0.95rem; } #send-btn, #mic-btn { width: 42px; height: 42px; } .msg-actions { gap: 6px; } .msg-actions button { font-size: 0.78rem; } } </style> </head> <body> <style> /* === UNIVERSAL SIDEBAR (shared across the app) === */ #globalMenuBtn { position: fixed; top: 14px; left: 14px; z-index: 999997; width: 44px; height: 44px; border-radius: 50%; border: none; background: var(--primary, #4285F4); color: #fff; font-size: 18px; display: flex; align-items: center; justify-content: center; cursor: pointer; box-shadow: 0 4px 14px rgba(0,0,0,0.3); } #overlay { position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 999998; display: none; opacity: 0; transition: 0.3s; } #overlay.active { display: block; opacity: 1; } .sidebar { position: fixed; top: 0; left: -300px; width: 280px; height: 100%; background: var(--bg-surface, #ffffff); z-index: 999999; transition: left 0.35s cubic-bezier(0.2,0.8,0.2,1); box-shadow: 4px 0 30px rgba(0,0,0,0.3); padding: 0; box-sizing: border-box; overflow-y: auto; display: flex; flex-direction: column; font-family: 'Poppins', -apple-system, BlinkMacSystemFont, sans-serif; } .sidebar.active { left: 0; } .sidebar-header { padding: max(22px, env(safe-area-inset-top)) 18px 16px; display: flex; align-items: center; justify-content: space-between; background: linear-gradient(120deg, #4285F4, #EA4335, #FBBC04, #34A853); background-size: 300% auto; animation: sidebarGradient 8s linear infinite; flex-shrink: 0; } @keyframes sidebarGradient { to { background-position: 300% center; } } .sidebar-brand { color: #fff; font-weight: 800; font-size: 1rem; letter-spacing: 0.2px; display: flex; align-items: center; gap: 8px; text-shadow: 0 1px 4px rgba(0,0,0,0.25); } .sidebar-close-btn { width: 30px; height: 30px; border-radius: 50%; border: none; background: rgba(0,0,0,0.2); color: #fff; font-size: 15px; cursor: pointer; display: flex; align-items: center; justify-content: center; flex-shrink: 0; } .sidebar-nav { padding: 10px 10px 24px; display: flex; flex-direction: column; gap: 2px; overflow-y: auto; } .nav-item { display: flex; align-items: center; gap: 12px; width: 100%; text-align: left; padding: 12px 12px; border-radius: 14px; border: none; background: transparent; color: var(--text-main, #1e293b); font-size: 14px; font-weight: 600; cursor: pointer; transition: background 0.18s, transform 0.15s; } .nav-item:hover { background: rgba(66,133,244,0.1); transform: translateX(2px); } .nav-item .emoji { font-size: 16px; flex-shrink: 0; width: 20px; text-align: center; } .nav-item.current { background: rgba(66,133,244,0.14); color: #4285F4; font-weight: 800; box-shadow: inset 3px 0 0 #4285F4; } </style> <button id="globalMenuBtn" onclick="toggleSidebar()">☰</button> <div class="overlay" id="overlay" onclick="toggleSidebar()"></div> <div class="sidebar" id="sidebar"> <div class="sidebar-header"> <span class="sidebar-brand">✨ AI PRO SUITE</span> <button class="sidebar-close-btn" onclick="toggleSidebar()">✕</button> </div> <div class="sidebar-nav"> <button class="nav-item" onclick="window.location.href='index.html'"><span class="emoji">🏠</span><span>Dashboard</span></button> <button class="nav-item current" onclick="window.location.href='lens.html'"><span class="emoji">✨</span><span>Lens Studio</span></button> <button class="nav-item" onclick="window.location.href='books.html'"><span class="emoji">📚</span><span>Book Deep Study</span></button> <button class="nav-item" onclick="window.location.href='maths.html'"><span class="emoji">🧮</span><span>Math Solver</span></button> <button class="nav-item" onclick="window.location.href='search.html'"><span class="emoji">🔎</span><span>Deep Search</span></button> <button class="nav-item" onclick="window.location.href='downloader.html'"><span class="emoji">📥</span><span>Video Downloader</span></button> <button class="nav-item" onclick="window.location.href='board.html'"><span class="emoji">📋</span><span>Whiteboard</span></button> <button class="nav-item" onclick="window.location.href='clone.html'"><span class="emoji">📑</span><span>Website Cloner</span></button> <button class="nav-item" onclick="window.location.href='runhtml.html'"><span class="emoji">🌐</span><span>Write HTML</span></button> <button class="nav-item" onclick="window.location.href='youtube.html'"><span class="emoji">▶️</span><span>YouTube Search</span></button> <button class="nav-item" onclick="window.location.href='managequiz.html'"><span class="emoji">⚙️</span><span>Manage Quiz</span></button> <button class="nav-item" onclick="window.location.href='tutor.html'"><span class="emoji">👨‍🏫</span><span>AI Tutor</span></button> <button class="nav-item" onclick="window.location.href='quiz.html'"><span class="emoji">📝</span><span>Take a Quiz!</span></button> <button class="nav-item" onclick="window.location.href='book_quiz.html'"><span class="emoji">📝</span><span>Take a Book Quiz!</span></button> <button class="nav-item" onclick="window.location.href='tables.html'"><span class="emoji">🔢</span><span>Maths Table</span></button> <button class="nav-item" onclick="window.location.href='coding.html'"><span class="emoji">💻</span><span>AI Coding</span></button> <button class="nav-item" onclick="window.location.href='chess.html'"><span class="emoji">♟️</span><span>Chess AI</span></button> <button class="nav-item" onclick="window.location.href='translator.html'"><span class="emoji">🎙️</span><span>Text Translator</span></button> <button class="nav-item" onclick="window.location.href='image.html'"><span class="emoji">🖼️</span><span>Image Translator</span></button> <button class="nav-item" onclick="window.location.href='create.html'"><span class="emoji">🎨</span><span>Image Creator</span></button> <button class="nav-item" onclick="window.location.href='qa.html'"><span class="emoji">📚</span><span>Document Q&A</span></button> <button class="nav-item" onclick="window.location.href='history.html'"><span class="emoji">🕒</span><span>History & Downloads</span></button> <button class="nav-item" onclick="window.location.href='storage.html'"><span class="emoji">📂</span><span>Storage</span></button> <button class="nav-item" onclick="window.location.href='hub.html'"><span class="emoji">🛰️</span><span>HF Command Center</span></button> <button class="nav-item" onclick="window.location.href='live.html'"><span class="emoji">🗣️</span><span>Gemini Live</span></button> </div> </div> <script> function toggleSidebar() { const s = document.getElementById("sidebar"), o = document.getElementById("overlay"); const a = !s.classList.contains("active"); s.classList.toggle("active", a); o.classList.toggle("active", a); } </script> <div id="progress-bar"></div> <div id="toast-container"></div> <div class="deco-orb orb-a"></div> <div class="deco-orb orb-b"></div> <div class="deco-orb orb-c"></div> <div id="camera-view"> <video id="video" autoplay playsinline muted></video> <div id="viewfinder"> <span class="vf-corner vf-tl"></span> <span class="vf-corner vf-tr"></span> <span class="vf-corner vf-bl"></span> <span class="vf-corner vf-br"></span> </div> <div id="grid-overlay"> <span class="grid-line v" style="left:33.333%"></span> <span class="grid-line v" style="left:66.666%"></span> <span class="grid-line h" style="top:33.333%"></span> <span class="grid-line h" style="top:66.666%"></span> </div> <div id="zoom-pill">1.0x</div> <div class="top-controls"> <div class="top-controls-left"> <label class="icon-btn" for="file-upload" title="Upload image">📁</label> <input type="file" id="file-upload" accept="image/*" style="display: none;"> <div class="icon-btn" id="torch-btn" title="Flashlight">⚡</div> <div class="icon-btn" id="grid-btn" title="Grid">▦</div> </div> <div class="top-controls-right"> <div class="icon-btn" id="flip-btn" title="Flip camera">🔄</div> <div class="icon-btn" id="theme-btn" title="Toggle dark mode">🌙</div> </div> </div> <!-- Mode tabs BEFORE a photo is taken — sit right above the shutter, like real Lens --> <div id="mode-selector-precapture" class="mode-tabs"> <div class="mode-chip selected" data-mode="search">🔎 Search</div> <div class="mode-chip" data-mode="text">📝 Text</div> <div class="mode-chip" data-mode="translate">🌐 Translate</div> <div class="mode-chip" data-mode="homework">🧮 Homework</div> <div class="mode-chip" data-mode="shopping">🛍️ Shopping</div> </div> <div class="capture-container"> <div class="capture-btn" id="capture-btn"></div> <button class="thumb-fab" id="last-shot-btn" title="Last shot"><img id="last-shot-img" alt="Last capture"></button> </div> </div> <div id="captured-view"> <div class="icon-btn" id="back-btn">←</div> <div id="gallery-strip"></div> <div id="smart-suggestion"> <span id="smart-suggestion-text"></span> <button id="smart-suggestion-btn">Switch</button> <button id="smart-suggestion-close">✕</button> </div> <div id="image-stage"> <canvas id="crop-canvas"></canvas> <div id="text-overlay"></div> </div> <div id="magnifier"><canvas id="magnifier-canvas" width="150" height="150"></canvas></div> <button id="analyze-crop-btn">Analyze Focus</button> <div id="selection-toolbar"> <span id="sel-count">0 selected</span> <button id="sel-copy-btn">📋 Copy</button> <button id="sel-copyall-btn">📑 Copy All</button> <button id="sel-google-btn">🔎 Google</button> <button id="sel-clear-btn">Clear</button> </div> </div> <!-- ===== Normal results sheet: Search / Text / Homework / Shopping ===== --> <div id="bottom-pane"> <div class="drag-handle-container" id="drag-handle"> <div class="drag-handle"></div> </div> <!-- Mode tabs live INSIDE the sheet's own header, like real Lens results tabs — they scroll and appear/disappear together with the sheet, never floating loose. --> <div id="mode-selector-sheet" class="mode-tabs"> <div class="mode-chip selected" data-mode="search">🔎 Search</div> <div class="mode-chip" data-mode="text">📝 Text</div> <div class="mode-chip" data-mode="translate">🌐 Translate</div> <div class="mode-chip" data-mode="homework">🧮 Homework</div> <div class="mode-chip" data-mode="shopping">🛍️ Shopping</div> </div> <div id="pane-title"> <span class="lens-dots"><i></i><i></i><i></i><i></i></span> <span class="pane-title-text">Lens Studio</span> </div> <div id="chat-history"></div> <div id="input-area"> <button id="mic-btn" title="Voice input">🎙️</button> <input type="text" id="chat-input" placeholder="Ask something..."> <button id="send-btn" title="Send"> <svg viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M12 20V4M12 4L5 11M12 4L19 11" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"/></svg> </button> </div> </div> <!-- ===== Dedicated Translate panel — no AI chat here, just detect + pick language ===== --> <div id="translate-toolbar"> <div id="mode-selector-translate" class="mode-tabs"> <div class="mode-chip" data-mode="search">🔎 Search</div> <div class="mode-chip" data-mode="text">📝 Text</div> <div class="mode-chip selected" data-mode="translate">🌐 Translate</div> <div class="mode-chip" data-mode="homework">🧮 Homework</div> <div class="mode-chip" data-mode="shopping">🛍️ Shopping</div> </div> <div class="translate-row"> <div class="translate-box"> <span class="translate-box-label">Detected</span> <span class="translate-box-value" id="translate-detected-count">Scanning…</span> </div> <div class="translate-arrow">→</div> <div class="translate-box target-wrap"> <select id="translate-lang-select"> <option value="" disabled selected>Select language</option> <option value="Hindi">Hindi — हिंदी</option> <option value="English">English</option> <option value="Sanskrit">Sanskrit — संस्कृत</option> <option value="Bengali">Bengali — বাংলা</option> <option value="Tamil">Tamil — தமிழ்</option> <option value="Telugu">Telugu — తెలుగు</option> <option value="Marathi">Marathi — मराठी</option> <option value="Gujarati">Gujarati — ગુજરાતી</option> <option value="Punjabi">Punjabi — ਪੰਜਾਬੀ</option> <option value="Urdu">Urdu — اردو</option> <option value="Spanish">Spanish</option> <option value="French">French</option> <option value="German">German</option> <option value="Chinese">Chinese</option> <option value="Japanese">Japanese</option> <option value="Arabic">Arabic</option> <option value="Russian">Russian</option> <option value="Portuguese">Portuguese</option> <option value="Korean">Korean</option> </select> </div> </div> </div> <script> // ============================================================ // LENS STUDIO — app logic // ============================================================ const video = document.getElementById('video'); const cameraView = document.getElementById('camera-view'); const capturedView = document.getElementById('captured-view'); const cropCanvas = document.getElementById('crop-canvas'); const ctx = cropCanvas.getContext('2d'); const imageStage = document.getElementById('image-stage'); const captureBtn = document.getElementById('capture-btn'); const backBtn = document.getElementById('back-btn'); const analyzeCropBtn = document.getElementById('analyze-crop-btn'); const bottomPane = document.getElementById('bottom-pane'); const dragHandle = document.getElementById('drag-handle'); const chatHistoryDiv = document.getElementById('chat-history'); const chatInput = document.getElementById('chat-input'); const sendBtn = document.getElementById('send-btn'); const fileUpload = document.getElementById('file-upload'); const torchBtn = document.getElementById('torch-btn'); const gridBtn = document.getElementById('grid-btn'); const gridOverlay = document.getElementById('grid-overlay'); const flipBtn = document.getElementById('flip-btn'); const themeBtn = document.getElementById('theme-btn'); const micBtn = document.getElementById('mic-btn'); const galleryStrip = document.getElementById('gallery-strip'); const progressBar = document.getElementById('progress-bar'); const toastContainer = document.getElementById('toast-container'); const modeChips = document.querySelectorAll('.mode-chip'); // 3 synced groups: precapture / sheet / translate const textOverlay = document.getElementById('text-overlay'); const selectionToolbar = document.getElementById('selection-toolbar'); const selCopyBtn = document.getElementById('sel-copy-btn'); const selCopyAllBtn = document.getElementById('sel-copyall-btn'); const selGoogleBtn = document.getElementById('sel-google-btn'); const selClearBtn = document.getElementById('sel-clear-btn'); const selCount = document.getElementById('sel-count'); const translateToolbar = document.getElementById('translate-toolbar'); const translateLangSelect = document.getElementById('translate-lang-select'); const translateDetectedCount = document.getElementById('translate-detected-count'); const zoomPill = document.getElementById('zoom-pill'); const lastShotBtn = document.getElementById('last-shot-btn'); const lastShotImg = document.getElementById('last-shot-img'); const magnifier = document.getElementById('magnifier'); const magnifierCanvas = document.getElementById('magnifier-canvas'); const magnifierCtx = magnifierCanvas.getContext('2d'); const smartSuggestionEl = document.getElementById('smart-suggestion'); const smartSuggestionText = document.getElementById('smart-suggestion-text'); const smartSuggestionBtn = document.getElementById('smart-suggestion-btn'); const smartSuggestionClose = document.getElementById('smart-suggestion-close'); let streamRef = null; let videoTrack = null; let baseImage = new Image(); let currentFullBase64 = ""; let serverChatHistory = []; let hasCrop = false; let startX, startY, rectW = 0, rectH = 0, isDrawing = false; let abortController = null; let isGenerating = false; let currentMode = "search"; let torchOn = false; let isDarkMode = false; let captureHistory = []; let recognizing = false; let speechRec = null; let usingFrontCam = false; let camZoom = 1; let pinchStartDist = 0; let pinchStartZoom = 1; let zoomHideTimer = null; let stageZoomed = false; let lastTapTime = 0, lastTapX = 0, lastTapY = 0; let textBlocks = []; // detected text blocks {id, text, translated, x, y, w, h} let selectedBoxIds = new Set(); // ids currently selected let selectionModeActive = false; let targetLang = ""; // blank until the user picks one in Translate mode // ---------------- NO CONTEXT MENUS / NO NATIVE CALLOUTS (Android / iOS / Desktop) ---------------- // document.addEventListener('contextmenu', (e) => e.preventDefault()); document.addEventListener('dragstart', (e) => e.preventDefault()); // ---------------- TOASTS ---------------- // function showToast(msg) { const t = document.createElement('div'); t.className = 'toast'; t.innerText = msg; toastContainer.appendChild(t); setTimeout(() => t.remove(), 2600); } function haptic(ms) { if (navigator.vibrate) navigator.vibrate(ms || 25); } function attachRipple(el) { el.addEventListener('click', (e) => { const r = document.createElement('span'); r.className = 'ripple'; const rect = el.getBoundingClientRect(); r.style.left = (e.clientX - rect.left - 10) + 'px'; r.style.top = (e.clientY - rect.top - 10) + 'px'; r.style.width = r.style.height = '20px'; el.appendChild(r); setTimeout(() => r.remove(), 650); }); } document.querySelectorAll('.icon-btn, .capture-btn, .thumb-fab').forEach(attachRipple); function burstConfetti(x, y) { const colors = ['#4285F4', '#EA4335', '#FBBC04', '#34A853']; for (let i = 0; i < 16; i++) { const p = document.createElement('div'); p.className = 'confetti-piece'; p.style.left = x + 'px'; p.style.top = y + 'px'; p.style.background = colors[i % colors.length]; const angle = Math.random() * Math.PI * 2; const dist = 55 + Math.random() * 80; p.style.setProperty('--dx', Math.cos(angle) * dist + 'px'); p.style.setProperty('--dy', Math.sin(angle) * dist + 'px'); p.style.setProperty('--rot', (Math.random() * 360) + 'deg'); document.body.appendChild(p); setTimeout(() => p.remove(), 950); } } // decorative sparkles scattered on load (function scatterSparkles() { for (let i = 0; i < 10; i++) { const s = document.createElement('div'); s.className = 'sparkle'; s.style.left = Math.random() * 100 + 'vw'; s.style.top = Math.random() * 100 + 'vh'; s.style.animationDelay = (Math.random() * 3) + 's'; document.body.appendChild(s); } })(); themeBtn.addEventListener('click', () => { isDarkMode = !isDarkMode; document.body.setAttribute('data-theme', isDarkMode ? 'dark' : 'light'); themeBtn.innerText = isDarkMode ? '☀️' : '🌙'; themeBtn.classList.toggle('active', isDarkMode); showToast(isDarkMode ? 'Dark mode on' : 'Light mode on'); }); // ---------------- BOTTOM PANE STATE ---------------- // function setPaneState(state) { bottomPane.className = state; } function defaultPromptForMode() { const map = { search: "Describe this photo briefly and identify key subjects.", text: "Read and transcribe all visible text in this image clearly.", homework: "Identify the problem in this image and solve it step by step.", shopping: "Identify this product and describe its likely brand, category and key features." }; return map[currentMode] || map.search; } // Translate mode has NO chat panel at all — shows the dedicated translate // toolbar instead. Every other mode uses the normal chat sheet. function updatePostCaptureUI() { if (currentMode === 'translate') { bottomPane.style.display = 'none'; translateToolbar.style.display = 'flex'; } else { translateToolbar.style.display = 'none'; bottomPane.style.display = 'flex'; } } // ---------------- MATH-SAFE + LANGUAGE-AWARE SYSTEM PROMPT ---------------- // // Fixes: (1) "fac(0" style raw-text math, (2) replies defaulting to English // when the app's default language is Hindi. function buildSystemPrompt(mode) { let sp = `You are "Lens Studio", a fast visual AI assistant built into a camera app. The user is looking at a photo or live camera frame and asking about it. Keep answers concise and skimmable. 🗣️ DEFAULT LANGUAGE (IMPORTANT): Reply in natural, conversational Hindi (Devanagari script) by default. Only switch away from Hindi if the user's own message clearly asks for another language (e.g. "answer in English", "reply in Tamil", "explain in Spanish") or the user writes their message primarily in another language — in that case, reply in that language instead, and keep using it for the rest of the conversation until they change it again. 📐 MATH & FORMULA FORMATTING (MANDATORY, NO EXCEPTIONS): - Every piece of math, however small, MUST be written in proper LaTeX wrapped in delimiters: use $...$ for inline math and $$...$$ for a standalone equation on its own line. - ALWAYS write fractions with \\frac{numerator}{denominator} — never as plain text like "1/2" and never as a bare word like "frac(...)" outside math delimiters. - Use \\times for multiplication. Use \\div or \\frac for division, whichever reads cleaner. - Never put plain words, unit labels, or currency symbols inside a $ ... $ / $$ ... $$ block — keep labels and explanations in normal text outside the math delimiters. - Use standard markdown: **bold** for headings/emphasis, short bullet points where useful.`; if (mode === 'homework') { sp += ` 🧮 HOMEWORK MODE — follow this structure exactly: **1. What's given** — restate the problem in one short line **2. Steps** — the worked solution, one clean equation per line inside $$...$$, using \\frac for every fraction, \\times for multiplication **3. ✅ Final Answer** — one short plain-text sentence stating the result.`; } else if (mode === 'shopping') { sp += ` 🛍️ SHOPPING MODE: Identify the product, likely brand, category, an approximate price range if reasonably inferable, and 2-3 key features. Be brief.`; } else if (mode === 'text') { sp += ` 📝 TEXT MODE: Transcribe the visible text accurately first, then briefly answer the user's question about it.`; } return sp; } async function startCamera(facing) { const facingMode = facing || 'environment'; try { if (streamRef) streamRef.getTracks().forEach(t => t.stop()); const stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: facingMode } }); streamRef = stream; video.srcObject = stream; videoTrack = stream.getVideoTracks()[0]; camZoom = 1; video.style.transform = ''; } catch (err) { console.warn("Camera error", err); showToast("Camera unavailable"); } } startCamera(); torchBtn.addEventListener('click', async () => { if (!videoTrack) return; const caps = videoTrack.getCapabilities ? videoTrack.getCapabilities() : {}; if (!caps.torch) { showToast("Torch not supported on this device"); return; } torchOn = !torchOn; try { await videoTrack.applyConstraints({ advanced: [{ torch: torchOn }] }); torchBtn.classList.toggle('active', torchOn); showToast(torchOn ? 'Flash on' : 'Flash off'); } catch (e) { showToast("Couldn't toggle torch"); } }); flipBtn.addEventListener('click', async () => { haptic(20); usingFrontCam = !usingFrontCam; await startCamera(usingFrontCam ? 'user' : 'environment'); torchOn = false; torchBtn.classList.remove('active'); showToast(usingFrontCam ? 'Front camera' : 'Back camera'); }); gridBtn.addEventListener('click', () => { gridOverlay.classList.toggle('show'); gridBtn.classList.toggle('active'); haptic(15); }); // ---------------- PINCH TO ZOOM (live camera) ---------------- // function touchDist(a, b) { return Math.hypot(b.clientX - a.clientX, b.clientY - a.clientY); } video.addEventListener('touchstart', (e) => { if (e.touches.length === 2) { pinchStartDist = touchDist(e.touches[0], e.touches[1]); pinchStartZoom = camZoom; } }, { passive: true }); video.addEventListener('touchmove', (e) => { if (e.touches.length === 2 && pinchStartDist > 0) { e.preventDefault(); const d = touchDist(e.touches[0], e.touches[1]); camZoom = Math.min(3, Math.max(1, pinchStartZoom * (d / pinchStartDist))); video.style.transform = `scale(${camZoom})`; zoomPill.textContent = camZoom.toFixed(1) + 'x'; zoomPill.classList.add('show'); clearTimeout(zoomHideTimer); zoomHideTimer = setTimeout(() => zoomPill.classList.remove('show'), 1100); } }, { passive: false }); video.addEventListener('touchend', (e) => { if (e.touches.length < 2) pinchStartDist = 0; }); // ---------------- TAP TO FOCUS ---------------- // video.addEventListener('click', (e) => { const ring = document.createElement('div'); ring.className = 'focus-ring'; ring.style.left = e.clientX + 'px'; ring.style.top = e.clientY + 'px'; document.body.appendChild(ring); setTimeout(() => ring.remove(), 650); if (videoTrack && videoTrack.getCapabilities) { try { const caps = videoTrack.getCapabilities(); if (caps.focusMode && caps.focusMode.includes('single-shot')) { videoTrack.applyConstraints({ advanced: [{ focusMode: 'single-shot' }] }).catch(() => {}); } } catch (err) {} } }); function resizeCanvas() { cropCanvas.width = window.innerWidth; cropCanvas.height = window.innerHeight; if (capturedView.style.display === 'flex') { drawImageToCanvas(); positionTextOverlay(); } } window.addEventListener('resize', resizeCanvas); resizeCanvas(); let imgRect = { cx: 0, cy: 0, w: 0, h: 0 }; function drawImageToCanvas() { ctx.clearRect(0, 0, cropCanvas.width, cropCanvas.height); const hRatio = cropCanvas.width / baseImage.width; const vRatio = cropCanvas.height / baseImage.height; const ratio = Math.min(hRatio, vRatio); const cx = (cropCanvas.width - baseImage.width * ratio) / 2; const cy = (cropCanvas.height - baseImage.height * ratio) / 2; imgRect = { cx, cy, w: baseImage.width * ratio, h: baseImage.height * ratio }; ctx.drawImage(baseImage, 0, 0, baseImage.width, baseImage.height, cx, cy, baseImage.width * ratio, baseImage.height * ratio); } function updateLastShotThumb() { if (captureHistory.length === 0) { lastShotBtn.style.display = 'none'; return; } lastShotImg.src = captureHistory[captureHistory.length - 1]; lastShotBtn.style.display = 'flex'; } function addToGallery(fullBase64) { captureHistory.push(fullBase64); renderGallery(); } function renderGallery() { galleryStrip.innerHTML = ""; updateLastShotThumb(); if (captureHistory.length < 1) { galleryStrip.style.display = 'none'; return; } galleryStrip.style.display = 'flex'; captureHistory.forEach((b64) => { const img = document.createElement('img'); img.src = b64; img.className = 'gallery-thumb'; if (b64 === currentFullBase64) img.classList.add('current'); img.addEventListener('click', () => { if (b64 !== currentFullBase64) reopenFromGallery(b64); }); galleryStrip.appendChild(img); }); } function reopenFromGallery(b64) { currentFullBase64 = b64; baseImage.src = b64; baseImage.onload = () => { resetStageZoom(); drawImageToCanvas(); chatHistoryDiv.innerHTML = ""; serverChatHistory = []; clearSelectionState(); renderGallery(); updatePostCaptureUI(); hideSmartSuggestion(); if (currentMode !== 'translate') triggerAI(currentFullBase64, defaultPromptForMode(), true); detectText(); }; } function resetStageZoom() { stageZoomed = false; imageStage.style.transform = 'scale(1)'; } function processImage(base64Data, alreadyInHistory) { if (streamRef) streamRef.getTracks().forEach(t => t.stop()); currentFullBase64 = base64Data; baseImage.src = base64Data; baseImage.onload = () => { cameraView.style.display = 'none'; capturedView.style.display = 'flex'; backBtn.style.display = 'flex'; analyzeCropBtn.style.display = 'none'; hasCrop = false; resetStageZoom(); drawImageToCanvas(); if (!alreadyInHistory) addToGallery(base64Data); else renderGallery(); clearSelectionState(); hideSmartSuggestion(); translateLangSelect.value = ""; updatePostCaptureUI(); if (currentMode !== 'translate') { bottomPane.style.display = 'flex'; setTimeout(() => { setPaneState("peek"); }, 50); chatHistoryDiv.innerHTML = ""; serverChatHistory = []; triggerAI(currentFullBase64, defaultPromptForMode(), true); } detectText(); }; } captureBtn.addEventListener('click', () => { haptic(30); const rect = captureBtn.getBoundingClientRect(); burstConfetti(rect.left + rect.width / 2, rect.top + rect.height / 2); const tcv = document.createElement('canvas'); tcv.width = video.videoWidth; tcv.height = video.videoHeight; tcv.getContext('2d').drawImage(video, 0, 0); processImage(tcv.toDataURL('image/jpeg')); }); lastShotBtn.addEventListener('click', () => { if (!captureHistory.length) return; haptic(15); processImage(captureHistory[captureHistory.length - 1], true); }); fileUpload.addEventListener('change', (e) => { const file = e.target.files[0]; if (file) { const r = new FileReader(); r.onload = (ev) => processImage(ev.target.result); r.readAsDataURL(file); } }); // ---------------- MODE CHIPS (3 synced groups; work before AND after capture) ---------------- // function syncModeChipsUI() { modeChips.forEach(c => c.classList.toggle('selected', c.dataset.mode === currentMode)); } modeChips.forEach(chip => { chip.addEventListener('click', () => { if (chip.dataset.mode === currentMode) return; currentMode = chip.dataset.mode; syncModeChipsUI(); haptic(15); const placeholders = { search: "Ask something...", text: "Ask about the text...", homework: "Ask for the solution steps...", shopping: "Ask about this product..." }; chatInput.placeholder = placeholders[currentMode] || "Ask something..."; if (capturedView.style.display === 'flex' && currentFullBase64) { hasCrop = false; analyzeCropBtn.style.display = 'none'; resetStageZoom(); drawImageToCanvas(); clearSelectionState(); hideSmartSuggestion(); updatePostCaptureUI(); if (currentMode !== 'translate') { chatHistoryDiv.innerHTML = ""; serverChatHistory = []; setPaneState("peek"); triggerAI(currentFullBase64, defaultPromptForMode(), true); } detectText(); } showToast('Mode: ' + chip.textContent.trim()); }); }); // ---------------- TEXT DETECTION (SELECTABLE / COPYABLE TEXT) ---------------- // async function detectText() { textBlocks = []; textOverlay.innerHTML = ""; clearSelectionState(); hideSmartSuggestion(); translateDetectedCount.textContent = "Scanning…"; try { const res = await fetch('/analyze', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ imageBase64: currentFullBase64, targetLang: targetLang || "Hindi" }) }); if (!res.ok) { translateDetectedCount.textContent = "No text found"; return; } const data = await res.json(); textBlocks = (data.text_blocks || []).map((b, i) => { const ymin = b.bbox_2d[0] / 10; const xmin = b.bbox_2d[1] / 10; const ymax = b.bbox_2d[2] / 10; const xmax = b.bbox_2d[3] / 10; return { id: 't' + i, text: b.original_text, translated: b.translated_text, x: xmin, y: ymin, w: xmax - xmin, h: ymax - ymin }; }); renderTextOverlay(); translateDetectedCount.textContent = textBlocks.length === 1 ? '1 line found' : (textBlocks.length + ' lines found'); if (textBlocks.length === 0) translateDetectedCount.textContent = "No text found"; suggestSmartMode(); } catch (e) { console.error("Text detection failed", e); translateDetectedCount.textContent = "No text found"; } } function positionTextOverlay() { document.querySelectorAll('.text-box').forEach(el => { const id = el.dataset.id; const block = textBlocks.find(b => b.id === id); if (!block) return; el.style.left = (imgRect.cx + (block.x / 100) * imgRect.w) + 'px'; el.style.top = (imgRect.cy + (block.y / 100) * imgRect.h) + 'px'; el.style.width = ((block.w / 100) * imgRect.w) + 'px'; el.style.height = ((block.h / 100) * imgRect.h) + 'px'; }); } function renderTextOverlay() { textOverlay.innerHTML = ""; textBlocks.forEach(block => { const box = document.createElement('div'); box.className = 'text-box'; box.dataset.id = block.id; box.title = block.text; let holdTimer = null; const startHold = () => { holdTimer = setTimeout(() => { haptic(35); selectionModeActive = true; toggleBoxSelection(block.id, box); }, 420); }; const cancelHold = () => { if (holdTimer) clearTimeout(holdTimer); }; box.addEventListener('mousedown', startHold); box.addEventListener('touchstart', startHold, { passive: true }); box.addEventListener('mouseup', cancelHold); box.addEventListener('touchend', cancelHold); box.addEventListener('mouseleave', cancelHold); box.addEventListener('click', () => { if (selectionModeActive) toggleBoxSelection(block.id, box); }); textOverlay.appendChild(box); }); positionTextOverlay(); if (currentMode === 'translate' && targetLang) applyAllTranslations(); } function toggleBoxSelection(id, el) { if (selectedBoxIds.has(id)) { selectedBoxIds.delete(id); el.classList.remove('selected'); } else { selectedBoxIds.add(id); el.classList.add('selected'); } updateSelectionToolbar(); } function updateSelectionToolbar() { if (selectedBoxIds.size > 0) { selectionToolbar.classList.add('show'); selCount.innerText = selectedBoxIds.size + ' selected'; } else { selectionToolbar.classList.remove('show'); selectionModeActive = false; } } function clearSelectionState() { selectedBoxIds.clear(); selectionModeActive = false; selectionToolbar.classList.remove('show'); document.querySelectorAll('.text-box.selected').forEach(el => el.classList.remove('selected')); } selClearBtn.addEventListener('click', clearSelectionState); selCopyBtn.addEventListener('click', () => { const chosen = textBlocks.filter(b => selectedBoxIds.has(b.id)); const text = chosen.map(b => b.translated || b.text).join(' '); navigator.clipboard.writeText(text).then(() => { const original = selCopyBtn.innerHTML; selCopyBtn.innerHTML = '✅ Copied!'; showToast('Copied to clipboard'); setTimeout(() => { selCopyBtn.innerHTML = original; }, 2500); }); }); selCopyAllBtn.addEventListener('click', () => { if (textBlocks.length === 0) { showToast('No text detected'); return; } const text = textBlocks.map(b => b.translated || b.text).join(' '); navigator.clipboard.writeText(text).then(() => { haptic(15); showToast('Copied all text'); }); }); function openGoogleSearch(query) { const q = (query || "").trim(); if (!q) { showToast('Nothing to search'); return; } window.open('https://www.google.com/search?q=' + encodeURIComponent(q.slice(0, 300)), '_blank'); } selGoogleBtn.addEventListener('click', () => { const chosen = textBlocks.filter(b => selectedBoxIds.has(b.id)); const source = chosen.length ? chosen : textBlocks; const text = source.map(b => b.translated || b.text).join(' '); openGoogleSearch(text || defaultPromptForMode()); }); // ---------------- SMART MODE SUGGESTION ---------------- // function showSmartSuggestion(targetMode, label) { smartSuggestionText.textContent = label; smartSuggestionBtn.textContent = 'Switch to ' + (targetMode === 'homework' ? 'Homework' : 'Text'); smartSuggestionBtn.onclick = () => { const chip = Array.from(modeChips).find(c => c.dataset.mode === targetMode); if (chip) chip.click(); hideSmartSuggestion(); }; smartSuggestionEl.classList.add('show'); } function hideSmartSuggestion() { smartSuggestionEl.classList.remove('show'); } smartSuggestionClose.addEventListener('click', hideSmartSuggestion); function suggestSmartMode() { if (currentMode === 'translate') { hideSmartSuggestion(); return; } if (textBlocks.length === 0) { hideSmartSuggestion(); return; } const allText = textBlocks.map(b => b.text).join(' '); const cleaned = allText.replace(/\s/g, ''); if (!cleaned) { hideSmartSuggestion(); return; } const mathChars = (allText.match(/[0-9+\-*/=^]/g) || []).length; const mathRatio = mathChars / allText.length; if (currentMode !== 'homework' && mathRatio > 0.22 && cleaned.length > 4) { showSmartSuggestion('homework', '🧮 This looks like a math problem.'); } else if (currentMode === 'search' && cleaned.length > 60) { showSmartSuggestion('text', '📝 Lots of text detected here.'); } else { hideSmartSuggestion(); } } // ---------------- TRANSLATE PANEL (auto-translates the moment a language is picked) ---------------- // translateLangSelect.addEventListener('change', async () => { const lang = translateLangSelect.value; if (!lang) return; targetLang = lang; haptic(15); showToast('Translating to ' + lang + '…'); await detectText(); applyAllTranslations(); }); function applyAllTranslations() { textBlocks.forEach(t => { const boxEl = textOverlay.querySelector('.text-box[data-id="' + t.id + '"]'); if (boxEl && t.translated) { boxEl.classList.add('translated-label'); boxEl.innerText = t.translated; } }); } // ---------------- CROP / FOCUS SELECTION (+ loupe magnifier) ---------------- // function getPos(e) { const rect = cropCanvas.getBoundingClientRect(); const cx = e.touches ? e.touches[0].clientX : e.clientX; const cy = e.touches ? e.touches[0].clientY : e.clientY; return { x: cx - rect.left, y: cy - rect.top, clientX: cx, clientY: cy }; } function updateMagnifier(p) { magnifier.style.display = 'block'; magnifier.style.left = p.clientX + 'px'; magnifier.style.top = p.clientY + 'px'; const size = 60; magnifierCtx.imageSmoothingEnabled = false; magnifierCtx.clearRect(0, 0, magnifierCanvas.width, magnifierCanvas.height); magnifierCtx.drawImage(cropCanvas, p.x - size / 2, p.y - size / 2, size, size, 0, 0, magnifierCanvas.width, magnifierCanvas.height); } function hideMagnifier() { magnifier.style.display = 'none'; } function handleDraw(e, type) { if (stageZoomed) return; // avoid coordinate mismatch while double-tap zoomed if (bottomPane.className !== "closed") return; if (type === 'start') { drawImageToCanvas(); isDrawing = true; const p = getPos(e); startX = p.x; startY = p.y; rectW = 0; rectH = 0; analyzeCropBtn.style.display = 'none'; hasCrop = false; updateMagnifier(p); } if (type === 'move' && isDrawing) { const p = getPos(e); rectW = p.x - startX; rectH = p.y - startY; drawImageToCanvas(); ctx.fillStyle = 'rgba(0,0,0,0.35)'; ctx.fillRect(0, 0, cropCanvas.width, cropCanvas.height); ctx.clearRect(startX, startY, rectW, rectH); ctx.save(); ctx.beginPath(); ctx.rect(startX, startY, rectW, rectH); ctx.clip(); drawImageToCanvas(); ctx.restore(); ctx.strokeStyle = '#fff'; ctx.lineWidth = 2; ctx.strokeRect(startX, startY, rectW, rectH); updateMagnifier(p); } if (type === 'end') { isDrawing = false; hideMagnifier(); if (Math.abs(rectW) > 30 && Math.abs(rectH) > 30) { hasCrop = true; analyzeCropBtn.style.display = 'block'; } else { hasCrop = false; drawImageToCanvas(); analyzeCropBtn.style.display = 'none'; } } } cropCanvas.addEventListener('mousedown', e => handleDraw(e, 'start')); cropCanvas.addEventListener('mousemove', e => handleDraw(e, 'move')); cropCanvas.addEventListener('mouseup', e => handleDraw(e, 'end')); cropCanvas.addEventListener('touchstart', e => handleDraw(e, 'start')); cropCanvas.addEventListener('touchmove', e => handleDraw(e, 'move')); cropCanvas.addEventListener('touchend', e => handleDraw(e, 'end')); // ---------------- DOUBLE-TAP TO ZOOM CAPTURED IMAGE ---------------- // function toggleStageZoom(clientX, clientY) { stageZoomed = !stageZoomed; const rect = imageStage.getBoundingClientRect(); const originX = ((clientX - rect.left) / rect.width) * 100; const originY = ((clientY - rect.top) / rect.height) * 100; imageStage.style.transformOrigin = originX + '% ' + originY + '%'; imageStage.style.transform = stageZoomed ? 'scale(2.2)' : 'scale(1)'; haptic(20); } cropCanvas.addEventListener('touchend', (e) => { if (Math.abs(rectW) > 30 && Math.abs(rectH) > 30) return; // was a crop drag, not a tap const touch = e.changedTouches && e.changedTouches[0]; if (!touch) return; const now = Date.now(); const dx = touch.clientX - lastTapX, dy = touch.clientY - lastTapY; if (now - lastTapTime < 320 && Math.hypot(dx, dy) < 25) { toggleStageZoom(touch.clientX, touch.clientY); lastTapTime = 0; } else { lastTapTime = now; lastTapX = touch.clientX; lastTapY = touch.clientY; } }); cropCanvas.addEventListener('dblclick', (e) => { toggleStageZoom(e.clientX, e.clientY); }); analyzeCropBtn.addEventListener('click', () => { const tcv = document.createElement('canvas'); const cw = Math.abs(rectW); const ch = Math.abs(rectH); const cx = Math.min(startX, startX + rectW); const cy = Math.min(startY, startY + rectH); tcv.width = cw; tcv.height = ch; tcv.getContext('2d').drawImage(cropCanvas, cx, cy, cw, ch, 0, 0, cw, ch); analyzeCropBtn.style.display = 'none'; setPaneState("full"); const croppedBase64 = tcv.toDataURL('image/jpeg'); triggerAI(croppedBase64, "I selected this part. What is it?", false, croppedBase64); }); // ---------------- AI CHAT ENGINE ---------------- // function addMessageToUI(sender, htmlContent, imageBase64) { const div = document.createElement('div'); div.className = `msg ${sender}`; let content = ""; if (imageBase64) content += `<img src="${imageBase64}" class="chat-crop">`; content += `<div class="bubble">${htmlContent}</div>`; div.innerHTML = content; if (sender === 'ai') { const actions = document.createElement('div'); actions.className = 'msg-actions'; actions.innerHTML = ` <button class="act-copy">📋 Copy</button> <button class="act-listen">🔊 Listen</button> <button class="act-google">🔎 Google</button> <button class="act-share">💬 WhatsApp</button> `; div.appendChild(actions); const copyBtn = actions.querySelector('.act-copy'); copyBtn.addEventListener('click', () => { const text = div.querySelector('.bubble').innerText; navigator.clipboard.writeText(text).then(() => { const original = copyBtn.innerHTML; copyBtn.innerHTML = '✅ Copied'; copyBtn.classList.add('done'); setTimeout(() => { copyBtn.innerHTML = original; copyBtn.classList.remove('done'); }, 2500); }); }); const listenBtn = actions.querySelector('.act-listen'); listenBtn.addEventListener('click', () => { if (!('speechSynthesis' in window)) { showToast('Speech not supported'); return; } if (listenBtn.classList.contains('speaking')) { speechSynthesis.cancel(); listenBtn.innerHTML = '🔊 Listen'; listenBtn.classList.remove('speaking'); return; } speechSynthesis.cancel(); document.querySelectorAll('.act-listen.speaking').forEach(b => { b.innerHTML = '🔊 Listen'; b.classList.remove('speaking'); }); const text = div.querySelector('.bubble').innerText; const utter = new SpeechSynthesisUtterance(text); utter.onend = () => { listenBtn.innerHTML = '🔊 Listen'; listenBtn.classList.remove('speaking'); }; listenBtn.innerHTML = '⏹️ Stop'; listenBtn.classList.add('speaking'); speechSynthesis.speak(utter); }); actions.querySelector('.act-google').addEventListener('click', () => { const text = div.querySelector('.bubble').innerText; openGoogleSearch(text.slice(0, 200)); }); actions.querySelector('.act-share').addEventListener('click', () => { const text = div.querySelector('.bubble').innerText; window.open('https://wa.me/?text=' + encodeURIComponent(text), '_blank'); }); } chatHistoryDiv.appendChild(div); return div; } async function triggerAI(base64Data, promptText, isDefault, displayImage) { if (isGenerating) return; if (!isDefault) addMessageToUI('user', promptText, displayImage || null); chatHistoryDiv.scrollTop = chatHistoryDiv.scrollHeight; isGenerating = true; progressBar.style.width = '30%'; sendBtn.classList.add('stop'); const thinkingDiv = document.createElement('div'); thinkingDiv.className = 'thinking-wrap'; thinkingDiv.innerHTML = `<div class="thinking-card"><div class="thinking-orb"></div><div class="thinking-copy"><div class="thinking-label">Analyzing...</div><div class="thinking-bar"><span></span></div></div></div>`; chatHistoryDiv.appendChild(thinkingDiv); chatHistoryDiv.scrollTop = chatHistoryDiv.scrollHeight; abortController = new AbortController(); try { progressBar.style.width = '65%'; const res = await fetch('/api/other', { method: 'POST', headers: { 'Content-Type': 'application/json' }, signal: abortController.signal, body: JSON.stringify({ imageBase64: base64Data, userPrompt: promptText, history: serverChatHistory, mode: currentMode, systemPrompt: buildSystemPrompt(currentMode) }) }); thinkingDiv.remove(); if (!res.ok) throw new Error("Network Error"); const data = await res.json(); progressBar.style.width = '100%'; serverChatHistory.push({ role: "user", parts: promptText }); const replyText = data.text || "No response generated."; serverChatHistory.push({ role: "model", parts: replyText }); const aiBubbleContainer = addMessageToUI('ai', ""); typeWriterFadeMathSafe(replyText, aiBubbleContainer.querySelector('.bubble')); } catch (e) { thinkingDiv.remove(); if (e.name === 'AbortError') addMessageToUI('ai', "<i>Generation stopped.</i>"); else addMessageToUI('ai', "<i>Error connecting.</i>"); } finally { isGenerating = false; sendBtn.classList.remove('stop'); setTimeout(() => { progressBar.style.width = '0%'; }, 400); } } async function typeWriterFadeMathSafe(markdownText, container) { container.innerHTML = marked.parse(markdownText); if (window.MathJax && MathJax.typesetPromise) { try { MathJax.typesetClear([container]); await MathJax.typesetPromise([container]); } catch (e) { console.warn('MathJax render skipped', e); } } const nodes = Array.from(container.childNodes); container.innerHTML = ""; nodes.forEach(node => { const wrapper = document.createElement('span'); wrapper.className = 'fade-in'; wrapper.style.animationPlayState = 'paused'; wrapper.appendChild(node); container.appendChild(wrapper); }); const wrappers = container.querySelectorAll('.fade-in'); let i = 0; const interval = setInterval(() => { if (i >= wrappers.length || (abortController && abortController.signal.aborted)) { clearInterval(interval); return; } wrappers[i].style.animationPlayState = 'running'; i++; }, 120); } function handleSend() { if (isGenerating) { abortController.abort(); return; } const msg = chatInput.value.trim(); if (msg !== "") { haptic(15); chatInput.value = ""; setPaneState("full"); triggerAI(currentFullBase64, msg, false); } } sendBtn.addEventListener('click', handleSend); chatInput.addEventListener('keypress', (e) => { if (e.key === 'Enter') { e.preventDefault(); handleSend(); } }); const SpeechRecognitionCtor = window.SpeechRecognition || window.webkitSpeechRecognition; if (SpeechRecognitionCtor) { speechRec = new SpeechRecognitionCtor(); speechRec.continuous = false; speechRec.interimResults = false; speechRec.onresult = (event) => { chatInput.value = event.results[0][0].transcript; }; speechRec.onend = () => { recognizing = false; micBtn.classList.remove('listening'); }; speechRec.onerror = () => { recognizing = false; micBtn.classList.remove('listening'); showToast('Voice input error'); }; } micBtn.addEventListener('click', () => { if (!speechRec) { showToast('Voice input not supported'); return; } if (recognizing) { speechRec.stop(); return; } recognizing = true; micBtn.classList.add('listening'); speechRec.start(); }); let paneStartY = 0, currentY = 0, isPaneDragging = false; function hStart(e) { if (e.target.id === 'chat-input' || e.target.id === 'send-btn') return; isPaneDragging = true; paneStartY = e.type.includes('mouse') ? e.clientY : e.touches[0].clientY; bottomPane.style.transition = 'none'; } function hMove(e) { if (!isPaneDragging) return; currentY = e.type.includes('mouse') ? e.clientY : e.touches[0].clientY; const dy = currentY - paneStartY; if (bottomPane.className === "closed" && dy < 0) { bottomPane.style.transform = `translateY(calc(100% - 45px + ${dy}px))`; } else if (bottomPane.className === "peek") { bottomPane.style.transform = `translateY(calc(45% + ${dy}px))`; } else if (bottomPane.className === "full" && dy > 0) { bottomPane.style.transform = `translateY(${dy}px)`; } } function hEnd() { if (!isPaneDragging) return; isPaneDragging = false; bottomPane.style.transition = 'transform 0.5s cubic-bezier(0.2, 0.8, 0.2, 1)'; bottomPane.style.transform = ''; const dy = currentY - paneStartY; if (bottomPane.className === "closed" && dy < -30) { setPaneState("peek"); drawImageToCanvas(); analyzeCropBtn.style.display = 'none'; } else if (bottomPane.className === "peek") { if (dy < -40) setPaneState("full"); else if (dy > 40) setPaneState("closed"); } else if (bottomPane.className === "full" && dy > 50) { setPaneState("peek"); } } dragHandle.addEventListener('mousedown', hStart); document.addEventListener('mousemove', hMove); document.addEventListener('mouseup', hEnd); dragHandle.addEventListener('touchstart', hStart); document.addEventListener('touchmove', hMove); document.addEventListener('touchend', hEnd); backBtn.addEventListener('click', () => { if (isGenerating) abortController.abort(); speechSynthesis.cancel(); capturedView.style.display = 'none'; backBtn.style.display = 'none'; analyzeCropBtn.style.display = 'none'; cameraView.style.display = 'flex'; setPaneState("closed"); translateToolbar.style.display = 'none'; setTimeout(() => { bottomPane.style.display = 'none'; }, 500); chatHistoryDiv.innerHTML = ""; serverChatHistory = []; clearSelectionState(); textBlocks = []; textOverlay.innerHTML = ""; hideSmartSuggestion(); resetStageZoom(); hasCrop = false; startCamera(usingFrontCam ? 'user' : 'environment'); }); </script> </body> </html>
<!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, viewport-fit=cover">
<title>Lens Studio</title>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/marked@4.3.0/marked.min.js"></script>
<!-- 🚨 MATH FIX: MathJax must be CONFIGURED before it loads, otherwise it only
recognizes \( \) for inline math and ignores single $ ... $, which is what
made fractions/equations show up as raw text like "\frac{1}{2}" or "fac(0)"
instead of being rendered. This config + the LaTeX system-prompt rules below
are what actually fix that. -->
<script>
window.MathJax = {
tex: { inlineMath: [['$', '$'], ['\\(', '\\)']], displayMath: [['$$', '$$'], ['\\[', '\\]']] },
options: { skipHtmlTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code'] },
chtml: { displayAlign: 'left' }
};
</script>
<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
<style>
/* ============ THEME VARIABLES (LIGHT / DARK) ============ */
:root {
--accent: #4285F4;
--accent-2: #ff9500;
--danger: #ff3b30;
--success: #34c759;
--lens-blue: #4285F4;
--lens-red: #EA4335;
--lens-yellow: #FBBC04;
--lens-green: #34A853;
--bg-color: #f2f2f7;
--pane-bg: rgba(255, 255, 255, 0.96);
--text-dark: #1c1c1e;
--text-sub: #6e6e73;
--bubble-ai: #ffffff;
--bubble-user: #4285F4;
--chip-bg: rgba(120,120,128,0.12);
--grad-1: #e0c3fc;
--grad-2: #8ec5fc;
}
[data-theme="dark"] {
--bg-color: #0e0e10;
--pane-bg: rgba(28, 28, 32, 0.97);
--text-dark: #f2f2f7;
--text-sub: #a0a0a8;
--bubble-ai: #232327;
--chip-bg: rgba(255,255,255,0.08);
--grad-1: #1a1a2e;
--grad-2: #16213e;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
/* ===== NO CONTEXT MENUS / NO NATIVE LONG-PRESS CALLOUTS — Android, iOS, desktop ===== */
*, *::before, *::after {
-webkit-touch-callout: none;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
img, video, canvas {
-webkit-user-drag: none; -khtml-user-drag: none; -moz-user-drag: none; -o-user-drag: none; user-drag: none;
-webkit-touch-callout: none;
}
#chat-input { -webkit-user-select: text; user-select: text; }
select { -webkit-user-select: auto; user-select: auto; }
body, html {
width: 100%; height: 100dvh;
background: linear-gradient(120deg, var(--grad-1) 0%, var(--grad-2) 100%);
font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", Roboto, sans-serif;
overflow: hidden; color: var(--text-dark);
}
/* ===== DECORATION: soft floating orbs + sparkle dust (cheap: transform/opacity only) ===== */
@keyframes floatOrb { 0%, 100% { transform: translate(0, 0) scale(1); } 50% { transform: translate(16px, -18px) scale(1.06); } }
.deco-orb { position: absolute; border-radius: 50%; pointer-events: none; z-index: 0; will-change: transform; }
.orb-a { width: 260px; height: 260px; top: -80px; left: -80px; background: radial-gradient(circle, rgba(255,149,0,0.25), rgba(255,149,0,0) 70%); animation: floatOrb 16s ease-in-out infinite; }
.orb-b { width: 220px; height: 220px; bottom: 5%; right: -70px; background: radial-gradient(circle, rgba(52,199,89,0.22), rgba(52,199,89,0) 70%); animation: floatOrb 20s ease-in-out infinite reverse; }
.orb-c { width: 180px; height: 180px; top: 40%; right: -60px; background: radial-gradient(circle, rgba(66,133,244,0.2), rgba(66,133,244,0) 70%); animation: floatOrb 24s ease-in-out infinite; }
@keyframes sparkleTwinkle { 0%, 100% { opacity: 0; transform: scale(0.4); } 50% { opacity: 0.85; transform: scale(1); } }
.sparkle { position: absolute; width: 4px; height: 4px; border-radius: 50%; background: #fff; opacity: 0; pointer-events: none; z-index: 1; box-shadow: 0 0 6px 1px rgba(255,255,255,0.7); animation: sparkleTwinkle 3.2s ease-in-out infinite; }
#camera-view, #captured-view { position: absolute; top: 0; left: 0; width: 100%; height: 100dvh; display: flex; flex-direction: column; justify-content: center; align-items: center; }
#captured-view { display: none; background: #000; }
video { width: 100%; height: 100%; object-fit: cover; touch-action: none; will-change: transform; }
#image-stage { position: absolute; top: 0; left: 0; width: 100%; height: 100%; transition: transform 0.3s cubic-bezier(0.2,0.8,0.2,1); }
#crop-canvas { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 5; touch-action: none; }
/* ===== VIEWFINDER CORNER FRAME + RULE-OF-THIRDS GRID (camera-view only) ===== */
#viewfinder { position: absolute; inset: 0; z-index: 4; pointer-events: none; }
@keyframes vfPulse { 0%, 100% { opacity: 0.5; } 50% { opacity: 1; } }
.vf-corner { position: absolute; width: 26px; height: 26px; border-color: rgba(255,255,255,0.92); opacity: 0.75; animation: vfPulse 3.2s ease-in-out infinite; }