Transaltor / board.html
Aichatbot12321's picture
Upload 27 files
84e1dd3 verified
Raw History Blame Contribute Delete
45.4 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">
<title>Math Board · AI PRO SUITE</title>
<link rel="stylesheet" href="style.css">
<link href="https://fonts.googleapis.com/css2?family=Kalam:wght@400;700&family=Poppins:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<style>
/* ================= THEME TOKENS (inherits site vars if style.css defines them) ================= */
:root{
--bg-base: var(--bg-base, #f8fafc);
--bg-surface: var(--bg-surface, #ffffff);
--border-light: var(--border-light, #e2e8f0);
--primary: var(--primary, #3b82f6);
--secondary: var(--secondary, #8b5cf6);
--primary-glow: var(--primary-glow, rgba(59,130,246,0.2));
--text-main: var(--text-main, #1e293b);
--text-muted: var(--text-muted, #64748b);
--input-bg: var(--input-bg, #f1f5f9);
--eco: #10b981;
--danger: #ef4444;
}
*{ box-sizing:border-box; }
html,body{ margin:0; padding:0; height:100%; overflow:hidden; background:var(--bg-base); font-family:'Poppins',sans-serif; color:var(--text-main); }
button{ font-family:'Poppins',sans-serif; }
:focus-visible{ outline:2px solid var(--primary); outline-offset:2px; }
@media (prefers-reduced-motion: reduce){ *{ animation-duration:0.001ms !important; transition-duration:0.001ms !important; } }
/* ================= SIDEBAR ================= */
.overlay{ display:none; position:fixed; inset:0; background:rgba(15,23,42,0.5); z-index:400; backdrop-filter:blur(2px); }
.overlay.active{ display:block; animation:fadeIn 0.25s ease; }
.sidebar{ position:fixed; top:0; left:0; width:260px; height:100%; background:var(--bg-surface); border-right:1px solid var(--border-light); z-index:500; transform:translateX(-100%); transition:transform 0.35s cubic-bezier(.16,1,.3,1); display:flex; flex-direction:column; padding:14px; box-shadow:8px 0 30px rgba(0,0,0,0.08); }
.sidebar.active{ transform:translateX(0); }
.sidebar-close-btn{ background:none; border:none; color:var(--text-muted); font-size:13px; font-weight:700; text-align:left; padding:10px 8px 16px; cursor:pointer; }
.sidebar button.nav-link{ display:flex; align-items:center; gap:10px; width:100%; background:transparent; border:none; border-radius:12px; text-align:left; padding:12px 14px; font-size:14px; font-weight:600; color:var(--text-main); cursor:pointer; margin-bottom:4px; transition:0.2s; }
.sidebar button.nav-link:hover{ background:var(--input-bg); }
.sidebar button.nav-link.active{ background:linear-gradient(135deg, var(--primary-glow), transparent); border-left:4px solid var(--primary); color:var(--primary); font-weight:800; }
@keyframes fadeIn{ from{opacity:0;} to{opacity:1;} }
@keyframes popUp{ 0%{transform:scale(0.85) translateY(10px); opacity:0;} 100%{transform:scale(1) translateY(0); opacity:1;} }
@keyframes slideIn{ from{transform:translateX(-16px); opacity:0;} to{transform:translateX(0); opacity:1;} }
/* ================= TOPBAR ================= */
.topbar{ position:fixed; top:0; left:0; width:100%; height:58px; z-index:120; display:flex; align-items:center; justify-content:space-between; padding:0 16px; background:var(--bg-surface); border-bottom:1px solid var(--border-light); box-shadow:0 4px 15px rgba(0,0,0,0.04); transition:transform 0.35s ease; }
.topbar.hidden{ transform:translateY(-100%); }
.icon-btn{ background:none; border:none; font-size:22px; cursor:pointer; color:var(--text-main); display:flex; align-items:center; justify-content:center; padding:4px; border-radius:10px; transition:0.2s; }
.icon-btn:hover{ background:var(--input-bg); }
.app-title{ font-size:17px; font-weight:800; letter-spacing:0.3px; display:flex; align-items:center; gap:8px; }
.eco-chip{ display:flex; align-items:center; gap:6px; background:rgba(16,185,129,0.1); border:1px solid var(--eco); color:var(--eco); padding:6px 12px; border-radius:20px; font-size:11.5px; font-weight:800; white-space:nowrap; }
.topbar-right{ display:flex; align-items:center; gap:8px; }
/* ================= SUB TOOLBAR (page nav + board settings) ================= */
.subbar{ position:fixed; top:58px; left:0; width:100%; height:52px; z-index:110; display:flex; align-items:center; justify-content:space-between; gap:8px; padding:0 12px; background:var(--bg-surface); border-bottom:1px solid var(--border-light); transition:transform 0.35s ease; overflow-x:auto; white-space:nowrap; }
.subbar.hidden{ transform:translateY(-160%); }
.page-nav{ display:flex; align-items:center; gap:6px; position:relative; }
.page-chip{ background:var(--input-bg); border:1px solid var(--border-light); color:var(--text-main); padding:7px 12px; border-radius:14px; font-size:12.5px; font-weight:800; cursor:pointer; display:flex; align-items:center; gap:6px; }
.page-chip:hover{ border-color:var(--primary); }
.nav-arrow{ background:var(--input-bg); border:1px solid var(--border-light); width:32px; height:32px; border-radius:10px; font-size:14px; font-weight:900; cursor:pointer; color:var(--text-main); transition:0.2s; }
.nav-arrow:hover:not(:disabled){ background:var(--primary); color:#fff; border-color:var(--primary); }
.nav-arrow:disabled{ opacity:0.35; cursor:not-allowed; }
.board-selects{ display:flex; gap:8px; align-items:center; }
.board-select{ background:var(--input-bg); border:1px solid var(--border-light); color:var(--text-main); font-size:12px; font-weight:700; padding:7px 8px; border-radius:10px; cursor:pointer; }
.thumb-strip{ display:none; position:absolute; top:44px; left:0; background:var(--bg-surface); border:1px solid var(--border-light); border-radius:14px; padding:10px; gap:8px; z-index:150; box-shadow:0 15px 40px rgba(0,0,0,0.15); animation:popUp 0.2s ease; max-width:80vw; overflow-x:auto; }
.thumb-strip.active{ display:flex; }
.thumb-item{ width:52px; height:38px; border-radius:8px; border:2px solid var(--border-light); background:#fff; cursor:pointer; overflow:hidden; flex-shrink:0; position:relative; }
.thumb-item.current{ border-color:var(--primary); box-shadow:0 0 0 2px var(--primary-glow); }
.thumb-item img{ width:100%; height:100%; object-fit:cover; display:block; }
.thumb-item span{ position:absolute; bottom:1px; right:3px; font-size:8px; font-weight:900; color:var(--text-muted); background:rgba(255,255,255,0.85); border-radius:3px; padding:0 2px; }
/* ================= STAGE ================= */
.stage-wrap{ position:fixed; top:110px; left:0; right:0; bottom:96px; overflow:hidden; touch-action:none; }
.stage-wrap.hidden-chrome{ top:0; bottom:0; }
.stage{ position:relative; width:100%; height:100%; perspective:1400px; }
.stage canvas{ position:absolute; top:0; left:0; }
#bgCanvas{ z-index:1; }
#drawCanvas{ z-index:2; }
#previewCanvas{ z-index:3; touch-action:none; }
.board-flip{ animation:flipPage 0.38s ease; }
@keyframes flipPage{ 0%{ transform:rotateY(0deg); filter:brightness(1);} 45%{ transform:rotateY(8deg); filter:brightness(0.94);} 100%{ transform:rotateY(0deg); filter:brightness(1);} }
.board-hint{ position:absolute; top:50%; left:50%; transform:translate(-50%,-50%); font-family:'Kalam',cursive; font-size:22px; color:var(--text-muted); opacity:0.5; pointer-events:none; text-align:center; z-index:5; transition:opacity 0.4s ease; }
.board-hint.gone{ opacity:0; }
.brush-cursor{ position:fixed; pointer-events:none; border-radius:50%; border:2px solid var(--text-main); z-index:600; transform:translate(-50%,-50%); display:none; }
/* text tool overlay */
.text-editor{ position:absolute; z-index:20; background:rgba(255,255,255,0.05); border:2px dashed var(--primary); border-radius:6px; padding:2px 6px; font-family:'Kalam',cursive; min-width:60px; min-height:1.4em; outline:none; white-space:pre-wrap; }
.text-editor-controls{ position:absolute; z-index:21; display:flex; gap:4px; }
.te-btn{ border:none; border-radius:8px; width:26px; height:26px; font-size:12px; cursor:pointer; color:#fff; display:flex; align-items:center; justify-content:center; box-shadow:0 3px 8px rgba(0,0,0,0.25); }
.te-done{ background:var(--eco); }
.te-cancel{ background:var(--danger); }
/* ================= DOCK ================= */
.dock-wrap{ position:fixed; bottom:12px; left:0; width:100%; display:flex; justify-content:center; z-index:130; transition:transform 0.35s ease; pointer-events:none; }
.dock-wrap.hidden{ transform:translateY(160%); }
.dock{ pointer-events:auto; display:flex; align-items:center; gap:4px; background:var(--bg-surface); border:1px solid var(--border-light); box-shadow:0 15px 40px rgba(0,0,0,0.15); border-radius:22px; padding:8px 10px; max-width:96vw; overflow-x:auto; -webkit-overflow-scrolling:touch; }
.dock::-webkit-scrollbar{ display:none; }
.dock-btn{ position:relative; flex-shrink:0; background:transparent; border:none; width:44px; height:44px; border-radius:14px; font-size:19px; cursor:pointer; display:flex; align-items:center; justify-content:center; transition:0.18s; color:var(--text-main); }
.dock-btn:hover{ background:var(--input-bg); }
.dock-btn.active{ background:linear-gradient(135deg, var(--secondary), var(--primary)); color:#fff; box-shadow:0 4px 12px var(--primary-glow); transform:translateY(-2px); }
.dock-div{ width:1px; height:26px; background:var(--border-light); margin:0 4px; flex-shrink:0; }
.popover{ display:none; position:absolute; bottom:64px; background:var(--bg-surface); border:1px solid var(--border-light); border-radius:16px; padding:14px; box-shadow:0 15px 40px rgba(0,0,0,0.18); animation:popUp 0.22s cubic-bezier(.16,1,.3,1); z-index:140; pointer-events:auto; }
.popover.active{ display:block; }
.swatch-row{ display:flex; gap:8px; margin-bottom:10px; flex-wrap:wrap; max-width:220px; }
.swatch{ width:26px; height:26px; border-radius:50%; border:2px solid var(--border-light); cursor:pointer; transition:0.15s; }
.swatch.selected{ border-color:var(--primary); transform:scale(1.15); box-shadow:0 0 0 2px var(--primary-glow); }
.size-row{ display:flex; align-items:center; gap:10px; }
.size-row input[type=range]{ flex:1; accent-color:var(--primary); }
.size-preview{ width:24px; height:24px; border-radius:50%; background:var(--text-main); flex-shrink:0; }
.dl-option{ display:flex; align-items:center; gap:10px; width:100%; background:var(--input-bg); border:1px solid var(--border-light); border-radius:12px; padding:10px 14px; margin-bottom:8px; font-size:13px; font-weight:700; cursor:pointer; color:var(--text-main); }
.dl-option:last-child{ margin-bottom:0; }
.dl-option:hover{ background:var(--primary); color:#fff; border-color:var(--primary); }
/* ================= FOCUS EXIT ================= */
#exitFocusBtn{ display:none; position:fixed; top:16px; right:16px; background:var(--danger); color:#fff; border:2px solid #fff; width:42px; height:42px; border-radius:50%; font-size:18px; font-weight:800; cursor:pointer; z-index:999999; box-shadow:0 6px 18px rgba(0,0,0,0.35); align-items:center; justify-content:center; }
/* ================= MODAL (calculator) ================= */
.modal-overlay{ display:none; position:fixed; inset:0; background:rgba(15,23,42,0.55); z-index:99999; justify-content:center; align-items:center; backdrop-filter:blur(4px); }
.modal-overlay.active{ display:flex; }
.calc-box{ background:var(--bg-surface); width:92%; max-width:320px; border-radius:24px; padding:18px; position:relative; border:1px solid var(--border-light); box-shadow:0 25px 60px rgba(0,0,0,0.35); animation:popUp 0.28s cubic-bezier(.16,1,.3,1); }
.calc-close{ position:absolute; top:14px; right:14px; background:var(--input-bg); border:none; width:30px; height:30px; border-radius:50%; font-size:14px; font-weight:800; cursor:pointer; color:var(--text-main); }
.calc-close:hover{ background:var(--danger); color:#fff; }
.calc-title{ font-size:14px; font-weight:800; color:var(--primary); text-transform:uppercase; letter-spacing:0.5px; margin-bottom:10px; }
.calc-display{ background:var(--input-bg); border-radius:14px; padding:16px; text-align:right; font-family:monospace; font-size:28px; font-weight:700; margin-bottom:12px; overflow-x:auto; white-space:nowrap; color:var(--text-main); }
.calc-grid{ display:grid; grid-template-columns:repeat(4,1fr); gap:8px; }
.calc-btn{ background:var(--input-bg); border:none; border-radius:12px; padding:14px 0; font-size:16px; font-weight:700; cursor:pointer; color:var(--text-main); transition:0.15s; }
.calc-btn:hover{ filter:brightness(0.95); }
.calc-btn:active{ transform:scale(0.94); }
.calc-btn.op{ background:var(--primary); color:#fff; }
.calc-btn.eq{ background:var(--eco); color:#fff; }
.calc-btn.fn{ background:rgba(139,92,246,0.12); color:var(--secondary); font-size:13px; }
.calc-btn.clr{ background:rgba(239,68,68,0.12); color:var(--danger); }
::-webkit-scrollbar{ width:6px; height:6px; }
::-webkit-scrollbar-thumb{ background:var(--border-light); border-radius:10px; }
</style>
</head>
<body>
<button id="exitFocusBtn" onclick="toggleFocus()">✕</button>
<div class="overlay" id="overlay" onclick="toggleSidebar()"></div>
<div class="sidebar" id="sidebar" style="overflow-y:auto;">
<button class="sidebar-close-btn" onclick="toggleSidebar()">✖ Close Menu</button>
<button onclick="window.location.href='index.html'">🏠 Dashboard</button>
<button onclick="window.location.href='lens.html'">✨ Lens Studio</button>
<button onclick="window.location.href='books.html'">📚 Book Deep Study</button>
<button onclick="window.location.href='maths.html'">🧮 Math Solver</button>
<button onclick="window.location.href='search.html'">🔎 Deep Search</button>
<button onclick="window.location.href='downloader.html'">📥 Video Downloader</button>
<button onclick="window.location.href='board.html'" style="border-left: 4px solid var(--primary); color: var(--primary); background: var(--border-light);">📋 Whiteboard</button>
<button onclick="window.location.href='clone.html'">📑 Website Cloner</button>
<button onclick="window.location.href='runhtml.html'">🌐 Write HTML</button>
<button onclick="window.location.href='youtube.html'">▶️ YouTube Search</button>
<button onclick="window.location.href='managequiz.html'">⚙️ Manage Quiz</button>
<button onclick="window.location.href='tutor.html'">👨‍🏫 AI Tutor</button>
<button onclick="window.location.href='quiz.html'">📝 Take a Quiz!</button>
<button onclick="window.location.href='book_quiz.html'">📝 Take a Book Quiz!</button>
<button onclick="window.location.href='tables.html'">🔢 Maths Table</button>
<button onclick="window.location.href='coding.html'">💻 AI Coding</button>
<button onclick="window.location.href='chess.html'">♟️ Chess AI</button>
<button onclick="window.location.href='translator.html'">🎙️ Text Translator</button>
<button onclick="window.location.href='image.html'">🖼️ Image Translator</button>
<button onclick="window.location.href='create.html'">🎨 Image Creator</button>
<button onclick="window.location.href='qa.html'">📚 Document Q&A</button>
<button onclick="window.location.href='history.html'">🕒 History & Downloads</button>
<button onclick="window.location.href='storage.html'">📂 Storage</button>
<button onclick="window.location.href='hub.html'">🛰️ HF Command Center</button>
<button onclick="window.location.href='live.html'">🗣️ Gemini Live</button>
</div>
<div class="topbar" id="topbar">
<div style="display:flex; align-items:center; gap:12px;">
<button class="icon-btn" onclick="toggleSidebar()">☰</button>
<div class="app-title">✏️ Math Board</div>
</div>
<div class="topbar-right">
<div class="eco-chip" title="Every board here is one less sheet of paper">🌱 <span id="ecoCount">1</span> page saved from paper</div>
<button class="icon-btn" title="Focus mode (hide menus)" onclick="toggleFocus()">⛶</button>
</div>
</div>
<div class="subbar" id="subbar">
<div class="page-nav">
<button class="nav-arrow" id="prevBtn" onclick="goPrev()" title="Previous page">◀</button>
<div class="page-chip" id="pageChip" onclick="toggleThumbs()">📄 <span id="pageLabel">Page 1 / 1</span></div>
<button class="nav-arrow" id="nextBtn" onclick="goNext()" title="Next page">▶</button>
<div class="thumb-strip" id="thumbStrip"></div>
</div>
<div class="board-selects">
<select class="board-select" id="bgStyleSelect" onchange="setBgStyle(this.value)" title="Paper style">
<option value="blank">Blank</option>
<option value="grid">Grid</option>
<option value="ruled">Ruled</option>
</select>
<select class="board-select" id="themeSelect" onchange="setTheme(this.value)" title="Board theme">
<option value="whiteboard">Whiteboard</option>
<option value="chalkboard">Chalkboard</option>
<option value="notebook">Notebook</option>
</select>
</div>
</div>
<div class="stage-wrap" id="stageWrap">
<div class="stage" id="stage">
<canvas id="bgCanvas"></canvas>
<canvas id="drawCanvas"></canvas>
<canvas id="previewCanvas"></canvas>
<div class="board-hint" id="boardHint">✏️ Tap Pen and start writing…<br><span style="font-size:14px;">(no trees were harmed)</span></div>
</div>
</div>
<div class="brush-cursor" id="brushCursor"></div>
<div class="dock-wrap" id="dockWrap">
<div class="dock" id="dock">
<button class="dock-btn active" data-tool="pen" onclick="setTool('pen')" title="Pen (B)">✏️</button>
<button class="dock-btn" data-tool="eraser" onclick="setTool('eraser')" title="Eraser (E)">🧹</button>
<button class="dock-btn" id="colorDockBtn" onclick="togglePanel('colorPopover')" title="Color & size">🎨</button>
<div class="dock-div"></div>
<button class="dock-btn" data-tool="line" onclick="setTool('line')" title="Line (L)">➖</button>
<button class="dock-btn" data-tool="rect" onclick="setTool('rect')" title="Rectangle (R)">▭</button>
<button class="dock-btn" data-tool="ellipse" onclick="setTool('ellipse')" title="Ellipse (O)">⬭</button>
<button class="dock-btn" data-tool="text" onclick="setTool('text')" title="Text (T)">🔤</button>
<div class="dock-div"></div>
<button class="dock-btn" onclick="undo()" title="Undo (Ctrl+Z)">↩️</button>
<button class="dock-btn" onclick="redo()" title="Redo (Ctrl+Y)">↪️</button>
<button class="dock-btn" onclick="clearBoard()" title="Clear board">🗑️</button>
<div class="dock-div"></div>
<button class="dock-btn" onclick="openCalculator()" title="Calculator">🧮</button>
<button class="dock-btn" id="dlDockBtn" onclick="togglePanel('dlPopover')" title="Download">⬇️</button>
</div>
<div class="popover" id="colorPopover" style="left:12px;">
<div class="swatch-row" id="swatchRow"></div>
<input type="color" id="customColor" value="#1e293b" style="width:100%; height:32px; border:none; border-radius:8px; margin-bottom:10px; cursor:pointer;" onchange="setColor(this.value, true)">
<div class="size-row">
<span class="size-preview" id="sizePreview"></span>
<input type="range" id="sizeSlider" min="1" max="40" value="4" oninput="setSize(this.value)">
</div>
</div>
<div class="popover" id="dlPopover" style="right:12px;">
<button class="dl-option" onclick="downloadPNG()">🖼️ Download this page (PNG)</button>
<button class="dl-option" onclick="downloadPDF()">📕 Download all pages (PDF)</button>
</div>
</div>
<div class="modal-overlay" id="calcModal">
<div class="calc-box">
<button class="calc-close" onclick="closeCalculator()">✕</button>
<div class="calc-title">🧮 Calculator</div>
<div class="calc-display" id="calcDisplay">0</div>
<div class="calc-grid">
<button class="calc-btn clr" onclick="calcClear()">C</button>
<button class="calc-btn clr" onclick="calcBackspace()">⌫</button>
<button class="calc-btn fn" onclick="calcPercent()">%</button>
<button class="calc-btn op" onclick="calcOperator('÷')">÷</button>
<button class="calc-btn" onclick="calcDigit('7')">7</button>
<button class="calc-btn" onclick="calcDigit('8')">8</button>
<button class="calc-btn" onclick="calcDigit('9')">9</button>
<button class="calc-btn op" onclick="calcOperator('×')">×</button>
<button class="calc-btn" onclick="calcDigit('4')">4</button>
<button class="calc-btn" onclick="calcDigit('5')">5</button>
<button class="calc-btn" onclick="calcDigit('6')">6</button>
<button class="calc-btn op" onclick="calcOperator('−')">−</button>
<button class="calc-btn" onclick="calcDigit('1')">1</button>
<button class="calc-btn" onclick="calcDigit('2')">2</button>
<button class="calc-btn" onclick="calcDigit('3')">3</button>
<button class="calc-btn op" onclick="calcOperator('+')">+</button>
<button class="calc-btn fn" onclick="calcSqrt()">√</button>
<button class="calc-btn" onclick="calcDigit('0')">0</button>
<button class="calc-btn" onclick="calcDot()">.</button>
<button class="calc-btn eq" onclick="calcEquals()">=</button>
<button class="calc-btn fn" onclick="calcTrig('sin')">sin</button>
<button class="calc-btn fn" onclick="calcTrig('cos')">cos</button>
<button class="calc-btn fn" onclick="calcTrig('tan')">tan</button>
<button class="calc-btn fn" onclick="calcPi()">π</button>
</div>
</div>
</div>
<script>
/* =====================================================================================
MATH BOARD — state
===================================================================================== */
const stageWrap = document.getElementById('stageWrap');
const stage = document.getElementById('stage');
const bgCanvas = document.getElementById('bgCanvas');
const drawCanvas = document.getElementById('drawCanvas');
const previewCanvas = document.getElementById('previewCanvas');
let bgCtx, drawCtx, previewCtx;
const THEMES = {
whiteboard: { bg:'#ffffff', grid:'rgba(59,130,246,0.14)', rule:'rgba(100,116,139,0.28)', margin:'rgba(239,68,68,0.35)', ink:'#1e293b' },
chalkboard: { bg:'#1e3d2f', grid:'rgba(255,255,255,0.10)', rule:'rgba(255,255,255,0.18)', margin:'rgba(255,255,255,0.25)', ink:'#ffffff' },
notebook: { bg:'#fdf6e3', grid:'rgba(59,130,246,0.10)', rule:'rgba(96,141,196,0.4)', margin:'rgba(220,80,80,0.45)', ink:'#1e293b' }
};
const PALETTE = ['#1e293b','#ef4444','#3b82f6','#10b981','#f59e0b','#8b5cf6','#ffffff'];
let state = {
theme: 'whiteboard',
bgStyle: 'blank',
tool: 'pen',
color: '#1e293b',
size: 4,
pages: [ { data:null, undo:[], redo:[] } ],
pageIndex: 0,
totalPagesCreated: 1
};
let isDrawing = false, lastX=0, lastY=0, startX=0, startY=0;
let activeEditor = null;
/* =====================================================================================
CANVAS SETUP / RESIZE
===================================================================================== */
function setupCtx(canvas){
const dpr = window.devicePixelRatio || 1;
const rect = stage.getBoundingClientRect();
canvas.width = Math.max(1, Math.round(rect.width * dpr));
canvas.height = Math.max(1, Math.round(rect.height * dpr));
canvas.style.width = rect.width + 'px';
canvas.style.height = rect.height + 'px';
const ctx = canvas.getContext('2d');
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
return ctx;
}
function stageSize(){
const rect = stage.getBoundingClientRect();
return { w: rect.width, h: rect.height };
}
function drawBackground(){
const { w, h } = stageSize();
const t = THEMES[state.theme];
bgCtx.clearRect(0,0,w,h);
bgCtx.fillStyle = t.bg;
bgCtx.fillRect(0,0,w,h);
if(state.bgStyle === 'grid'){
bgCtx.strokeStyle = t.grid;
bgCtx.lineWidth = 1;
for(let x=0; x<w; x+=26){ bgCtx.beginPath(); bgCtx.moveTo(x,0); bgCtx.lineTo(x,h); bgCtx.stroke(); }
for(let y=0; y<h; y+=26){ bgCtx.beginPath(); bgCtx.moveTo(0,y); bgCtx.lineTo(w,y); bgCtx.stroke(); }
} else if(state.bgStyle === 'ruled'){
bgCtx.strokeStyle = t.rule;
bgCtx.lineWidth = 1.5;
for(let y=34; y<h; y+=34){ bgCtx.beginPath(); bgCtx.moveTo(0,y); bgCtx.lineTo(w,y); bgCtx.stroke(); }
bgCtx.strokeStyle = t.margin;
bgCtx.lineWidth = 2;
bgCtx.beginPath(); bgCtx.moveTo(46,0); bgCtx.lineTo(46,h); bgCtx.stroke();
}
}
function resizeAll(preserveContent){
const oldData = preserveContent ? drawCanvas.toDataURL() : null;
bgCtx = setupCtx(bgCanvas);
drawCtx = setupCtx(drawCanvas);
previewCtx = setupCtx(previewCanvas);
drawBackground();
const { w, h } = stageSize();
if(oldData){
const img = new Image();
img.onload = () => { drawCtx.clearRect(0,0,w,h); drawCtx.drawImage(img,0,0,w,h); };
img.src = oldData;
}
}
let resizeTimer = null;
window.addEventListener('resize', () => {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(() => resizeAll(true), 150);
});
/* =====================================================================================
COORDS
===================================================================================== */
function getPos(e){
const rect = stage.getBoundingClientRect();
const p = (e.touches && e.touches[0]) ? e.touches[0] : e;
return { x: p.clientX - rect.left, y: p.clientY - rect.top };
}
/* =====================================================================================
UNDO / REDO (per page)
===================================================================================== */
function currentPage(){ return state.pages[state.pageIndex]; }
function pushUndo(){
const pg = currentPage();
const snap = drawCanvas.toDataURL();
pg.undo.push(snap);
if(pg.undo.length > 40) pg.undo.shift();
pg.redo = [];
}
function restoreSnapshot(dataUrl, cb){
const { w, h } = stageSize();
drawCtx.clearRect(0,0,w,h);
if(!dataUrl){ if(cb) cb(); return; }
const img = new Image();
img.onload = () => { drawCtx.clearRect(0,0,w,h); drawCtx.drawImage(img,0,0,w,h); if(cb) cb(); };
img.src = dataUrl;
}
function undo(){
const pg = currentPage();
if(pg.undo.length === 0) return;
pg.redo.push(drawCanvas.toDataURL());
const prev = pg.undo.pop();
restoreSnapshot(prev);
}
function redo(){
const pg = currentPage();
if(pg.redo.length === 0) return;
pg.undo.push(drawCanvas.toDataURL());
const next = pg.redo.pop();
restoreSnapshot(next);
}
function clearBoard(){
pushUndo();
const { w, h } = stageSize();
drawCtx.clearRect(0,0,w,h);
}
/* =====================================================================================
PAGES
===================================================================================== */
function saveCurrentPageBeforeLeaving(){
currentPage().data = drawCanvas.toDataURL();
}
function loadPage(i){
state.pageIndex = i;
restoreSnapshot(state.pages[i].data);
updatePageUI();
playFlip();
}
function playFlip(){
stage.classList.remove('board-flip');
void stage.offsetWidth;
stage.classList.add('board-flip');
}
function goNext(){
saveCurrentPageBeforeLeaving();
if(state.pageIndex === state.pages.length - 1){
state.pages.push({ data:null, undo:[], redo:[] });
state.totalPagesCreated++;
updateEco();
}
loadPage(state.pageIndex + 1);
}
function goPrev(){
if(state.pageIndex === 0) return;
saveCurrentPageBeforeLeaving();
loadPage(state.pageIndex - 1);
}
function goToPage(i){
if(i === state.pageIndex) { toggleThumbs(); return; }
saveCurrentPageBeforeLeaving();
loadPage(i);
toggleThumbs();
}
function updatePageUI(){
document.getElementById('pageLabel').textContent = `Page ${state.pageIndex+1} / ${state.pages.length}`;
document.getElementById('prevBtn').disabled = state.pageIndex === 0;
buildThumbs();
}
function buildThumbs(){
const strip = document.getElementById('thumbStrip');
strip.innerHTML = '';
state.pages.forEach((pg, i) => {
const div = document.createElement('div');
div.className = 'thumb-item' + (i === state.pageIndex ? ' current' : '');
div.onclick = () => goToPage(i);
const src = (i === state.pageIndex) ? drawCanvas.toDataURL() : pg.data;
div.innerHTML = `${src ? `<img src="${src}">` : ''}<span>${i+1}</span>`;
strip.appendChild(div);
});
}
function toggleThumbs(){
document.getElementById('thumbStrip').classList.toggle('active');
}
function updateEco(){
document.getElementById('ecoCount').textContent = state.totalPagesCreated;
}
/* =====================================================================================
TOOLS / COLOR / SIZE
===================================================================================== */
function setTool(name){
state.tool = name;
document.querySelectorAll('.dock-btn[data-tool]').forEach(b => b.classList.toggle('active', b.dataset.tool === name));
previewCanvas.style.cursor = (name === 'text') ? 'text' : 'crosshair';
closeAllPopovers();
}
function setColor(hex, fromPicker){
state.color = hex;
document.getElementById('sizePreview').style.background = hex;
document.querySelectorAll('.swatch').forEach(s => s.classList.toggle('selected', !fromPicker && s.dataset.color === hex));
if(fromPicker) document.querySelectorAll('.swatch').forEach(s => s.classList.remove('selected'));
}
function setSize(v){
state.size = parseInt(v, 10);
const preview = document.getElementById('sizePreview');
const d = Math.max(8, Math.min(28, state.size));
preview.style.width = d + 'px';
preview.style.height = d + 'px';
}
function setBgStyle(v){ state.bgStyle = v; drawBackground(); }
function setTheme(v){ state.theme = v; drawBackground(); }
function buildSwatches(){
const row = document.getElementById('swatchRow');
row.innerHTML = '';
PALETTE.forEach(c => {
const b = document.createElement('button');
b.className = 'swatch' + (c === state.color ? ' selected' : '');
b.style.background = c;
b.dataset.color = c;
if(c === '#ffffff') b.style.borderColor = '#cbd5e1';
b.onclick = () => setColor(c);
row.appendChild(b);
});
}
function togglePanel(id){
const el = document.getElementById(id);
const willOpen = !el.classList.contains('active');
closeAllPopovers();
if(willOpen) el.classList.add('active');
}
function closeAllPopovers(){
document.querySelectorAll('.popover').forEach(p => p.classList.remove('active'));
}
document.addEventListener('click', (e) => {
if(!e.target.closest('.popover') && !e.target.closest('#colorDockBtn') && !e.target.closest('#dlDockBtn')) closeAllPopovers();
if(!e.target.closest('.page-nav')) document.getElementById('thumbStrip').classList.remove('active');
});
/* =====================================================================================
DRAWING — pointer handlers on previewCanvas (top layer)
===================================================================================== */
function hideHint(){
const h = document.getElementById('boardHint');
if(h && !h.classList.contains('gone')) h.classList.add('gone');
}
function clearPreview(){
const { w, h } = stageSize();
previewCtx.clearRect(0,0,w,h);
}
function strokeStyleFor(ctx){
ctx.lineWidth = state.size;
ctx.strokeStyle = state.color;
ctx.fillStyle = state.color;
}
function drawShapePreview(x2, y2){
clearPreview();
strokeStyleFor(previewCtx);
previewCtx.beginPath();
if(state.tool === 'line'){
previewCtx.moveTo(startX, startY); previewCtx.lineTo(x2, y2);
} else if(state.tool === 'rect'){
previewCtx.rect(Math.min(startX,x2), Math.min(startY,y2), Math.abs(x2-startX), Math.abs(y2-startY));
} else if(state.tool === 'ellipse'){
const cx = (startX+x2)/2, cy=(startY+y2)/2, rx=Math.abs(x2-startX)/2, ry=Math.abs(y2-startY)/2;
previewCtx.ellipse(cx, cy, rx, ry, 0, 0, Math.PI*2);
}
previewCtx.stroke();
}
function commitShape(x2, y2){
strokeStyleFor(drawCtx);
drawCtx.beginPath();
if(state.tool === 'line'){
drawCtx.moveTo(startX, startY); drawCtx.lineTo(x2, y2);
} else if(state.tool === 'rect'){
drawCtx.rect(Math.min(startX,x2), Math.min(startY,y2), Math.abs(x2-startX), Math.abs(y2-startY));
} else if(state.tool === 'ellipse'){
const cx = (startX+x2)/2, cy=(startY+y2)/2, rx=Math.abs(x2-startX)/2, ry=Math.abs(y2-startY)/2;
drawCtx.ellipse(cx, cy, rx, ry, 0, 0, Math.PI*2);
}
drawCtx.stroke();
clearPreview();
}
function onPointerDown(e){
if(activeEditor) return; // don't start drawing while text box open
const pos = getPos(e);
hideHint();
if(state.tool === 'text'){
startTextEditor(pos.x, pos.y);
return;
}
isDrawing = true;
pushUndo();
lastX = pos.x; lastY = pos.y; startX = pos.x; startY = pos.y;
if(state.tool === 'pen' || state.tool === 'eraser'){
drawCtx.save();
if(state.tool === 'eraser'){
drawCtx.globalCompositeOperation = 'destination-out';
drawCtx.lineWidth = Math.max(state.size*3, 18);
} else {
drawCtx.globalCompositeOperation = 'source-over';
drawCtx.lineWidth = state.size;
drawCtx.strokeStyle = state.color;
}
drawCtx.beginPath();
drawCtx.moveTo(pos.x, pos.y);
drawCtx.lineTo(pos.x+0.1, pos.y+0.1);
drawCtx.stroke();
}
e.preventDefault();
}
function onPointerMove(e){
if(!isDrawing) return;
const pos = getPos(e);
if(state.tool === 'pen' || state.tool === 'eraser'){
drawCtx.lineTo(pos.x, pos.y);
drawCtx.stroke();
} else if(state.tool === 'line' || state.tool === 'rect' || state.tool === 'ellipse'){
drawShapePreview(pos.x, pos.y);
}
lastX = pos.x; lastY = pos.y;
e.preventDefault();
}
function onPointerUp(e){
if(!isDrawing) return;
isDrawing = false;
if(state.tool === 'pen' || state.tool === 'eraser'){
drawCtx.restore();
} else if(state.tool === 'line' || state.tool === 'rect' || state.tool === 'ellipse'){
commitShape(lastX, lastY);
}
}
previewCanvas.addEventListener('pointerdown', onPointerDown);
previewCanvas.addEventListener('pointermove', onPointerMove);
window.addEventListener('pointerup', onPointerUp);
previewCanvas.addEventListener('pointerleave', () => { document.getElementById('brushCursor').style.display='none'; });
/* brush size/color cursor preview */
previewCanvas.addEventListener('pointerenter', () => {
if(state.tool==='pen' || state.tool==='eraser') document.getElementById('brushCursor').style.display='block';
});
previewCanvas.addEventListener('pointermove', (e) => {
const cur = document.getElementById('brushCursor');
if(state.tool!=='pen' && state.tool!=='eraser'){ cur.style.display='none'; return; }
cur.style.display='block';
const d = state.tool==='eraser' ? Math.max(state.size*3,18) : state.size;
cur.style.width = d+'px'; cur.style.height = d+'px';
cur.style.borderColor = state.tool==='eraser' ? 'var(--danger)' : state.color;
cur.style.left = e.clientX+'px'; cur.style.top = e.clientY+'px';
});
/* =====================================================================================
TEXT TOOL
===================================================================================== */
function startTextEditor(x, y){
if(activeEditor) return;
const div = document.createElement('div');
div.className = 'text-editor';
div.contentEditable = 'true';
div.style.left = x + 'px';
div.style.top = y + 'px';
div.style.color = state.color;
div.style.fontSize = Math.max(16, state.size*4) + 'px';
stage.appendChild(div);
div.focus();
const controls = document.createElement('div');
controls.className = 'text-editor-controls';
controls.style.left = x + 'px';
controls.style.top = (y - 32) + 'px';
controls.innerHTML = `<button class="te-btn te-done" title="Add text">✓</button><button class="te-btn te-cancel" title="Cancel">✕</button>`;
stage.appendChild(controls);
controls.querySelector('.te-done').onclick = () => commitTextEditor(div, controls, x, y);
controls.querySelector('.te-cancel').onclick = () => cancelTextEditor(div, controls);
div.addEventListener('keydown', (e) => {
if(e.key === 'Enter' && !e.shiftKey){ e.preventDefault(); commitTextEditor(div, controls, x, y); }
if(e.key === 'Escape'){ e.preventDefault(); cancelTextEditor(div, controls); }
});
activeEditor = div;
}
function commitTextEditor(div, controls, x, y){
const text = div.innerText;
if(text && text.trim().length){
pushUndo();
const fontSize = Math.max(16, state.size*4);
drawCtx.font = fontSize + "px 'Kalam', cursive";
drawCtx.fillStyle = state.color;
drawCtx.textBaseline = 'top';
text.split('\n').forEach((line, i) => {
drawCtx.fillText(line, x+2, y + i*(fontSize*1.15));
});
}
div.remove(); controls.remove(); activeEditor = null;
}
function cancelTextEditor(div, controls){
div.remove(); controls.remove(); activeEditor = null;
}
/* =====================================================================================
FOCUS MODE
===================================================================================== */
let focusOn = false;
function toggleFocus(){
focusOn = !focusOn;
document.getElementById('topbar').classList.toggle('hidden', focusOn);
document.getElementById('subbar').classList.toggle('hidden', focusOn);
document.getElementById('dockWrap').classList.toggle('hidden', focusOn);
document.getElementById('stageWrap').classList.toggle('hidden-chrome', focusOn);
document.getElementById('exitFocusBtn').style.display = focusOn ? 'flex' : 'none';
setTimeout(() => resizeAll(true), 380);
}
/* =====================================================================================
SIDEBAR
===================================================================================== */
function toggleSidebar(){
document.getElementById('sidebar').classList.toggle('active');
document.getElementById('overlay').classList.toggle('active');
}
/* =====================================================================================
DOWNLOAD
===================================================================================== */
function compositeCanvas(bgData, drawData, w, h, cb){
const off = document.createElement('canvas');
off.width = w; off.height = h;
const octx = off.getContext('2d');
const bgImg = new Image();
bgImg.onload = () => {
octx.drawImage(bgImg, 0, 0, w, h);
if(drawData){
const dImg = new Image();
dImg.onload = () => { octx.drawImage(dImg,0,0,w,h); cb(off); };
dImg.src = drawData;
} else cb(off);
};
bgImg.src = bgData;
}
function downloadPNG(){
closeAllPopovers();
saveCurrentPageBeforeLeaving();
const { w, h } = stageSize();
compositeCanvas(bgCanvas.toDataURL(), currentPage().data, w, h, (off) => {
const a = document.createElement('a');
a.download = `math-board-page-${state.pageIndex+1}.png`;
a.href = off.toDataURL('image/png');
a.click();
});
}
function downloadPDF(){
closeAllPopovers();
saveCurrentPageBeforeLeaving();
const { w, h } = stageSize();
const { jsPDF } = window.jspdf;
const orientation = w >= h ? 'l' : 'p';
const pdf = new jsPDF({ orientation, unit:'px', format:[w,h] });
let i = 0;
function addPage(){
const pg = state.pages[i];
const bgData = bgCanvas.toDataURL();
compositeCanvas(bgData, pg.data, w, h, (off) => {
if(i > 0) pdf.addPage([w,h], orientation);
pdf.addImage(off.toDataURL('image/jpeg', 0.92), 'JPEG', 0, 0, w, h);
i++;
if(i < state.pages.length) addPage();
else pdf.save('math-board-notebook.pdf');
});
}
addPage();
}
/* =====================================================================================
CALCULATOR
===================================================================================== */
let calc = { display:'0', first:null, op:null, waiting:false };
function calcRender(){ document.getElementById('calcDisplay').textContent = calc.display; }
function openCalculator(){ document.getElementById('calcModal').classList.add('active'); }
function closeCalculator(){ document.getElementById('calcModal').classList.remove('active'); }
function calcDigit(d){
if(calc.waiting){ calc.display = d; calc.waiting = false; }
else calc.display = (calc.display === '0') ? d : calc.display + d;
calcRender();
}
function calcDot(){
if(calc.waiting){ calc.display = '0.'; calc.waiting = false; calcRender(); return; }
if(!calc.display.includes('.')) calc.display += '.';
calcRender();
}
function calcClear(){ calc = { display:'0', first:null, op:null, waiting:false }; calcRender(); }
function calcBackspace(){
calc.display = calc.display.length > 1 ? calc.display.slice(0,-1) : '0';
calcRender();
}
function calcPercent(){ calc.display = String(parseFloat(calc.display) / 100); calcRender(); }
function calcSqrt(){ calc.display = String(Math.sqrt(parseFloat(calc.display))); calcRender(); }
function calcPi(){ calc.display = String(Math.PI); calc.waiting = false; calcRender(); }
function calcTrig(fn){
const deg = parseFloat(calc.display);
const rad = deg * Math.PI / 180;
let r = 0;
if(fn === 'sin') r = Math.sin(rad);
if(fn === 'cos') r = Math.cos(rad);
if(fn === 'tan') r = Math.tan(rad);
calc.display = String(Math.round(r * 1e10) / 1e10);
calcRender();
}
function calcOperator(op){
if(calc.op && !calc.waiting) calcEquals();
calc.first = parseFloat(calc.display);
calc.op = op;
calc.waiting = true;
}
function calcEquals(){
if(calc.op === null || calc.first === null) return;
const second = parseFloat(calc.display);
let result = 0;
switch(calc.op){
case '+': result = calc.first + second; break;
case '−': result = calc.first - second; break;
case '×': result = calc.first * second; break;
case '÷': result = second === 0 ? NaN : calc.first / second; break;
}
calc.display = String(Math.round(result * 1e10) / 1e10);
calc.op = null; calc.first = null; calc.waiting = true;
calcRender();
}
/* =====================================================================================
KEYBOARD SHORTCUTS
===================================================================================== */
document.addEventListener('keydown', (e) => {
if(activeEditor) return;
if(document.activeElement && ['INPUT','TEXTAREA','SELECT'].includes(document.activeElement.tagName)) return;
if((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'z'){ e.preventDefault(); undo(); return; }
if((e.ctrlKey || e.metaKey) && (e.key.toLowerCase() === 'y')){ e.preventDefault(); redo(); return; }
switch(e.key.toLowerCase()){
case 'b': setTool('pen'); break;
case 'e': setTool('eraser'); break;
case 't': setTool('text'); break;
case 'l': setTool('line'); break;
case 'r': setTool('rect'); break;
case 'o': setTool('ellipse'); break;
case 'delete':
case 'backspace': clearBoard(); break;
}
});
/* =====================================================================================
INIT
===================================================================================== */
function init(){
buildSwatches();
setSize(4);
resizeAll(false);
updatePageUI();
updateEco();
}
window.addEventListener('load', init);
</script>
</body>
</html>