BaniGuru
Initial commit
911e360
Raw History Blame
97.5 kB
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Gurbani Wave Section Editor</title> <style> /* ========================================================================== DESIGN TOKENS ========================================================================== */ :root { /* Softer dark surfaces */ --bg: #202522; --panel: #282e2a; --panel2: #323934; /* Softer text — avoid pure/bright white */ --text: #d7ddd8; --muted: #9ca89f; /* Low-contrast borders */ --border: #414a43; /* Calm green */ --accent: #6fae7b; --accent2: #82bd8c; --ok: #75b982; /* Softer warning red */ --danger: #d66c68; /* Waveform background */ --wavescroll: #252b27; /* Section overlay */ --waveregion: rgba(211, 180, 88, 0.20); } /* ========================================================================== BASE ELEMENTS ========================================================================== */ * { box-sizing: border-box } html { width: 100%; max-width: 100%; overflow-x: hidden; } body { margin: 0; width: 100%; max-width: 100%; overflow-x: hidden; background: var(--bg); color: var(--text); font: 14px/1.45 Inter, system-ui, -apple-system, Segoe UI, sans-serif } button, input, select, textarea { font: inherit } /* ========================================================================== HEADER ========================================================================== */ header { display: flex; gap: 10px; align-items: end; flex-wrap: wrap; padding: 14px 18px; border-bottom: 1px solid var(--border); position: sticky; top: 0; z-index: 20 } h1 { font-size: 17px; margin: 0 auto 4px 0 } .field { min-width: 190px } .field label, .label { display: block; color: var(--muted); font-size: 15px; margin-bottom: 4px } select, input, textarea { background: var(--bg); color: var(--text); border: 1px solid var(--border); border-radius: 8px; padding: 8px 10px; outline: none } select:focus, input:focus, textarea:focus { border-color: var(--accent) } select { min-width: 320px } .btn { background: var(--panel2); border: 1px solid var(--border); color: var(--text); padding: 8px 12px; border-radius: 8px; cursor: pointer } .btn:hover { border-color: var(--accent) } .btn.primary { background: var(--accent); color: #ffffff; border-color: var(--accent); font-weight: 700 } .btn:disabled { opacity: .45; cursor: not-allowed } /* ========================================================================== LAYOUT AND PANELS ========================================================================== */ main { display: flex; flex-direction: column; gap: 12px; padding: 12px } .panel { border: 1px solid var(--border); background: var(--panel); border-radius: 12px; overflow: hidden } /* ========================================================================== WAVEFORM PANEL ========================================================================== */ .wave-head { display: flex; gap: 10px; align-items: center; padding: 10px 12px; border-bottom: 1px solid var(--border); position: relative; } #fileTitle { font-weight: 650; white-space: nowrap; overflow: hidden; text-overflow: ellipsis } #currentSectionText { position: absolute; left: 50%; transform: translateX(-50%); max-width: 60%; text-align: center; font-size: 18px; font-weight: 700; line-height: 1.35; color: var(--text); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .spacer { flex: 1 } #waveScroll { overflow-x: auto; overflow-y: hidden; background: var(--wavescroll); padding: 12px; border-bottom: 1px solid var(--border) } #waveform { min-height: 170px } /* Wave region transcript labels */ #waveform ::part(region-content) { color: #e0e5e1; background: rgba(37, 43, 39, 0.82); text-shadow: none; box-shadow: 0 1px 3px rgba(0, 0, 0, 0.25); border-radius: 4px; padding: 3px 6px; margin: 4px; max-width: calc(100% - 8px); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; pointer-events: none; font-size: 15px; font-weight: 650; line-height: 1.35; } /* ========================================================================== TOOLBAR ========================================================================== */ .toolbar { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; padding: 10px 12px; border-top: 1px solid var(--border) } #time { font-variant-numeric: tabular-nums; color: var(--muted) } #status { color: var(--muted) } .review-toggle { display: flex; align-items: center; gap: 7px; padding: 6px 9px; border: 1px solid var(--border); border-radius: 8px; color: var(--text); white-space: nowrap } .review-toggle input { margin: 0 } .review-toggle small { color: var(--muted) } #status.ok { color: var(--ok) } #status.error { color: var(--danger) } /* ========================================================================== SECTION EDITOR ========================================================================== */ aside { display: grid; grid-template-columns: minmax(0, 1.7fr) minmax(320px, .8fr); align-items: stretch; position: static; max-height: none } .editor { padding: 12px; display: grid; grid-template-columns: minmax(420px, 1.1fr) minmax(360px, 1fr); gap: 12px; align-items: start } .grid { display: grid; grid-template-columns: repeat(3, minmax(120px, 1fr)); gap: 9px } .grid input { width: 100% } textarea { width: 100%; resize: vertical; min-height: 92px; font-size: 18px; line-height: 1.55 } .raw { min-height: 92px; font-size: 14px } .transcript-fields { display: grid; gap: 10px } .transcript-fields label { margin-top: 0 !important } /* ========================================================================== SECTION LIST ========================================================================== */ .section-list { overflow: auto; border-top: 0; border-left: 1px solid var(--border); max-height: 300px } .section-row { padding: 9px 11px; border-bottom: 1px solid var(--border); cursor: pointer } .section-row:hover { background: #21262D; } .section-row.active { background: #1C2B22; border-left: 3px solid var(--accent); padding-left: 8px; } .meta { color: var(--muted); font-size: 11px } .text { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; margin-top: 2px } .empty { padding: 30px; color: var(--muted); text-align: center } .badge { display: inline-block; padding: 2px 7px; border-radius: 999px; background: #000; color: #93adbc; font-size: 11px } .dirty { color: #93adbc; background: #000 } .bottom-actions { display: flex; justify-content: flex-start; padding: 0 0 8px; } .bottom-actions .btn { min-width: 150px; } /* ========================================================================== TOP TABS ========================================================================== */ .top-tabs { display: flex; gap: 6px; padding: 8px 12px 0; background: #ffffff; border-bottom: 1px solid var(--border); position: sticky; top: 72px; z-index: 19; } .tab-button { border: 1px solid var(--border); border-bottom: 0; border-radius: 8px 8px 0 0; background: var(--panel2); color: var(--text); padding: 8px 16px; cursor: pointer; } .tab-button.active { background: var(--bg); color: var(--accent); font-weight: 700; position: relative; top: 1px; } .tab-page[hidden] { display: none !important; } /* ========================================================================== LINEAR TRANSCRIPT EDITOR ========================================================================== */ #transcriptPage { max-width: 1100px; width: 100%; margin: 0 auto; padding: 12px; } .linear-transcripts { display: flex; flex-direction: column; gap: 8px; } .linear-transcript-row { display: grid; grid-template-columns: minmax(105px, auto) minmax(0, 1fr); gap: 10px; align-items: start; padding: 8px; border: 1px solid var(--border); border-radius: 9px; background: #ffffff; scroll-margin-top: 125px; } .linear-transcript-meta { color: var(--muted); font-size: 11px; line-height: 1.45; padding-top: 7px; font-variant-numeric: tabular-nums; } .linear-transcript-input { width: 100%; min-height: 64px; resize: vertical; font-size: 18px; line-height: 1.5; background: #ffffff; } .linear-transcript-row:focus-within { border-color: var(--accent); box-shadow: 0 0 0 2px rgba(37, 99, 235, 0.12); } .linear-save-bar { display: flex; justify-content: flex-start; padding: 14px 0 6px; } .linear-save-bar .btn { min-width: 150px; } @media(max-width:700px) { .top-tabs { top: 112px; } .linear-transcript-row { grid-template-columns: 1fr; } .linear-transcript-meta { padding-top: 0; } } /* Keep the application inside the viewport. The waveform itself may still scroll horizontally inside #waveScroll. */ header, main, .panel, aside, .editor, .transcript-fields, .wave-head, .toolbar, .tab-page, #transcriptPage { width: 100%; max-width: 100%; min-width: 0; } header>*, .wave-head>*, .toolbar>*, .editor>*, .transcript-fields>* { min-width: 0; } #waveScroll { width: 100%; max-width: 100%; } #fileTitle { min-width: 0; display: none; } .playback-rate-control { display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; } .playback-rate-control label { color: var(--muted); font-size: 15px; } #playbackRate { min-width: 84px; width: auto; padding: 7px 9px; } @media(max-width:1100px) { aside { grid-template-columns: 1fr } .editor { grid-template-columns: 1fr } .section-list { border-left: 0; border-top: 1px solid var(--border); max-height: 300px } .grid { grid-template-columns: repeat(2, minmax(120px, 1fr)) } } @media(max-width:700px) { .transcript-fields { grid-template-columns: 1fr } .grid { grid-template-columns: 1fr 1fr } select { min-width: 220px; max-width: 75vw } } </style> </head> <body> <header> <div class="field"><label for="fileSelect">Project folder</label><select id="fileSelect"> <option>Loading project folders…</option> </select></div> <button class="btn" id="refreshBtn">Refresh</button> <button class="btn primary" disabled="" id="saveBtn">Save</button> <button class="btn" disabled="" id="validateAllBtn">Validate</button> </header> <!-- <nav class="top-tabs" aria-label="Editor pages"> <button class="tab-button active" id="waveTab" type="button" data-tab="wavePage">Wave editor</button> <button class="tab-button" id="transcriptTab" type="button" data-tab="transcriptPage">Transcripts</button> </nav> --> <main id="wavePage" class="tab-page"> <section class="panel"> <div class="wave-head"> <span id="fileTitle">Select a file</span> <span class="badge" id="dirty">Saved</span> <span id="currentSectionText" aria-live="polite"></span> <span class="spacer"></span> <span class="badge" id="count">0 sections</span> </div> </div> <div id="waveScroll"> <div id="waveform"></div> <div id="timeline"></div> </div> <div class="toolbar"> <button class="btn" id="playBtn">Play / Pause</button> <span class="playback-rate-control"> <label for="playbackRate">Speed</label> <select id="playbackRate" aria-label="Playback speed"> <option value="1">1×</option> <option value="1.25">1.25×</option> <option value="1.5">1.5×</option> <option value="1.75">1.75×</option> <option value="2">2×</option> <option value="2.25">2.25×</option> <option value="2.5">2.5×</option> <option value="2.75">2.75×</option> <option value="3">3×</option> </select> </span> <button class="btn" id="addBtn">Add 500 ms</button><button class="btn" id="splitBtn">Split</button><button class="btn" id="deleteBtn">Delete</button> <button class="btn" id="zoomOut">− Zoom</button><button class="btn" id="zoomIn">+ Zoom</button> <span id="time">00:00.000 / 00:00.000</span><label class="review-toggle" for="pauseOnStart"><input id="pauseOnStart" type="checkbox" /><span>Pause on start</span></label><span class="spacer"></span><span id="status">Choose a project folder</span> </div> </section> <aside class="panel"> <div class="editor"> <div class="grid"> <div><label class="label" for="sectionId">Section</label><input id="sectionId" readonly="" /></div> <!-- <div><label class="label" for="confidence">Confidence</label><input id="confidence" max="100" min="0" type="number" /></div> --> <div><label class="label" for="start">Start</label><input id="start" step="0.001" type="number" /> </div> <div><label class="label" for="end">End</label><input id="end" step="0.001" type="number" /></div> <!-- <div><label class="label" for="shabadId">Shabad ID</label><input id="shabadId" /></div> --> <!-- <div><label class="label" for="lineId">Line ID</label><input id="lineId" /></div> --> </div> <div class="transcript-fields"> <div> <label class="label" for="transcript">Transcript</label> <textarea id="transcript"></textarea> </div> </div> <div> <div> <label class="label" for="rawTranscript">Raw transcript</label> <textarea class="raw" id="rawTranscript"></textarea> </div> </div> </div> <div class="section-list" id="sectionList"> <div class="empty">No project loaded</div> </div> </aside> </main> <section id="transcriptPage" class="tab-page" hidden> <div id="linearTranscripts" class="linear-transcripts"> <div class="empty">Select a project folder</div> </div> <div class="linear-save-bar"> <button class="btn primary" id="transcriptSaveBtn" type="button" disabled>Save</button> </div> </section> <script type="module"> import WaveSurfer from 'https://cdn.jsdelivr.net/npm/wavesurfer.js@7.11.1/+esm'; import RegionsPlugin from 'https://cdn.jsdelivr.net/npm/wavesurfer.js@7.11.1/dist/plugins/regions.esm.js/+esm'; import TimelinePlugin from 'https://cdn.jsdelivr.net/npm/wavesurfer.js@7.11.1/dist/plugins/timeline.esm.js/+esm'; import HoverPlugin from 'https://cdn.jsdelivr.net/npm/wavesurfer.js@7.11.1/dist/plugins/hover.esm.js/+esm'; // ============================================================================ // DOM HELPERS // ============================================================================ const $ = s => document.querySelector(s); // ============================================================================ // WAVESURFER SETUP // ============================================================================ const regions = RegionsPlugin.create(); const ws = WaveSurfer.create({ container: '#waveform', height: 160, waveColor: '#3FB950', progressColor: '#56D364', cursorColor: '#F85149', cursorWidth: 2, normalize: true, minPxPerSec: 16, barWidth: 2, barGap: 1, barRadius: 2, autoScroll: false, autoCenter: false, plugins: [regions, TimelinePlugin.create({ container: '#timeline', style: { fontSize: '11px', color: '#475569' }, primaryLabelInterval: 10, secondaryLabelInterval: 5, primaryLabelSpacing: 4, secondaryLabelSpacing: 2 }), HoverPlugin.create({ lineColor: '#dc2626', lineWidth: 1, labelBackground: '#ffffff', labelColor: '#1f2937' })] }); // ============================================================================ // APPLICATION STATE // ============================================================================ let sections = [], projectData = {}, active = -1, currentAudio = '', zoom = 16, dirty = false, suppress = false, files = [], reviewSkipGuard = false; let longerThreshold = null, structureChanged = false; let lastCursorTime = 0; let validationTrackingEnabled = false; let currentTab = 'wavePage'; // Calm waveform viewport. let waveScrollAnimation = null; let viewportSectionIndex = -1; let lastViewportAdvanceSection = -1; const VIEWPORT_NEXT_SECTION_RIGHT_RATIO = 0.82; const VIEWPORT_SECTION_TARGET_RATIO = 0.10; const VIEWPORT_EDGE_GUARD_RATIO = 0.18; const VIEWPORT_ADVANCE_DURATION_MS = 520; const LAST_SECTION_SCROLL_TRIGGER_RATIO = 0.18; // Native scroll safety guard: only intervene when the cursor gets too // close to the right edge, then nudge it back without constant motion. let nativeGuardAnimation = null; let lastAutoCenterAdjustmentAt = 0; const AUTO_CENTER_MIN_INTERVAL_MS = 900; const AUTO_CENTER_TRIGGER_RATIO = 0.80; const AUTO_CENTER_TARGET_RATIO = 0.50; const NATIVE_GUARD_DURATION_MS = 500; const WAVE_LEFT_MARGIN_PX = 80; const WAVE_SECTION_CENTER_RATIO = 0.50; const WAVE_CURSOR_TARGET_RATIO = 0.15; const WAVE_CURSOR_LEFT_SAFE_RATIO = 0.08; const WAVE_CURSOR_RIGHT_SAFE_RATIO = 0.85; const WAVE_SCROLL_DURATION_MS = 1000; // Fast playback (>1×) switches to 1× after a section ends. A short // 50 ms settle pause is used when changing playback rate. If the next // section begins within two seconds, playback pauses for half a second at // that section start and then resumes at the selected speed. let playbackRate = 1; let fastPlaybackSection = -1; let fastTransitionPending = false; let fastTransitionTimer = null; let transitionSectionIndex = -1; let transitionEndTime = 0; let transitionNextIndex = -1; const TRANSITION_RATE = 1; const TRANSITION_WINDOW_SECONDS = 2; const NEXT_SECTION_START_PAUSE_MS = 500; const RATE_SETTLE_PAUSE_MS = 50; const FAST_END_TOLERANCE_SECONDS = 0.035; const NEXT_START_GUARD_SECONDS = 0.14; const JOIN_BOUNDARY_END_PROXIMITY_SECONDS = 0.5; // ============================================================================ // DISPLAY CONSTANTS // ============================================================================ const normalColor = 'rgba(242, 204, 96, 0.28)'; const warningColor = 'rgba(248, 81, 73, 0.50)'; const hasWarningDuration = s => { const d = num(s.end_time) - num(s.start_time); return d < 4 || d > 20; }; const needsReview = s => num(s.confidence) < 90; const pauseOnStart = () => $('#pauseOnStart').checked; const fieldIds = ['start', 'end', 'transcript', 'rawTranscript']; const num = (v, d = 0) => Number.isFinite(Number(v)) ? Number(v) : d; const fmt = t => { t = Math.max(0, num(t)); const m = Math.floor(t / 60), s = t - m * 60; return `${String(m).padStart(2, '0')}:${s.toFixed(3).padStart(6, '0')}`; }; const sectionDuration = section => num(section.end_time) - num(section.start_time); function sectionsForDisplay(items) { const valid = Array.isArray(items) ? items : []; return longerThreshold === null ? valid : valid.filter(section => sectionDuration(section) > longerThreshold); } // ============================================================================ // DATA NORMALISATION // ============================================================================ function clean(s) { const out = structuredClone(s || {}); if (!Object.prototype.hasOwnProperty.call(out, '__source_section_id')) { out.__source_section_id = out.section_id ?? null; } return out; } function renumber() { sections.sort((a, b) => a.start_time - b.start_time || a.end_time - b.end_time); const reserved = new Set(sections.map(s => s.section_id).filter(Boolean)); const seen = new Set(); let nextId = 1; for (const section of sections) { if (section.section_id && !seen.has(section.section_id)) { seen.add(section.section_id); continue; } let candidate; do { candidate = `section-${nextId++}`; } while (reserved.has(candidate) || seen.has(candidate)); section.section_id = candidate; reserved.add(candidate); seen.add(candidate); } $('#count').textContent = `${sections.length} sections`; } function renumberSectionIdsFrom(index) { for (let i = Math.max(0, index); i < sections.length; i++) { sections[i].section_id = `section-${i + 1}`; } } function setDirty(value = true) { dirty = value; $('#dirty').textContent = value ? 'Unsaved' : 'Saved'; $('#dirty').classList.toggle('dirty', value); $('#saveBtn').disabled = !currentAudio || !value; $('#transcriptSaveBtn').disabled = !currentAudio || !value; $('#validateAllBtn').disabled = !currentAudio || !sections.length; } function status(text, type = '') { const el = $('#status'); el.textContent = text; el.className = type; } function firstUnvalidatedIndex() { return sections.findIndex(section => section.validated !== true); } function resumeTimeAfterValidation() { if (!sections.length) return 0; const firstPending = firstUnvalidatedIndex(); if (firstPending >= 0) return sections[firstPending].start_time; return sections[sections.length - 1].end_time; } function validateSectionsPassed(previousTime, currentTime) { if (!validationTrackingEnabled || currentTime <= previousTime + 0.001) return 0; let changed = 0; for (const section of sections) { if (section.validated === true) continue; if (section.end_time > previousTime + 0.001 && section.end_time <= currentTime + 0.001) { section.validated = true; changed += 1; } } if (changed) { setDirty(); renderList(); } return changed; } function validateSectionsUpToCurrentPosition() { if (!validationTrackingEnabled || !sections.length) return 0; const currentTime = ws.getCurrentTime(); let changed = 0; for (let i = 0; i < sections.length; i++) { const section = sections[i]; if (section.validated === true) continue; // Validate any section whose end has already been passed. if (section.end_time <= currentTime + 0.001) { section.validated = true; changed++; continue; } // If this is the active LAST section, validate it on Save. if ( i === sections.length - 1 && i === active && currentTime >= section.start_time ) { section.validated = true; changed++; } } if (changed) { setDirty(); renderList(); } return changed; } function loadNextProject() { const select = $('#fileSelect'); if (!select || select.selectedIndex < 0) return; // Find next enabled option with a real value. for (let i = select.selectedIndex + 1; i < select.options.length; i++) { const option = select.options[i]; if (!option.disabled && option.value) { select.selectedIndex = i; loadProject(option.value).catch(err => status(err.message, 'error') ); return; } } status('Already at last project folder', 'ok'); } // ============================================================================ // PAGE TABS AND LINEAR TRANSCRIPT EDITOR // ============================================================================ function switchTab(pageId) { currentTab = pageId; document.querySelectorAll('.tab-page').forEach(page => { page.hidden = page.id !== pageId; }); document.querySelectorAll('.tab-button').forEach(button => { button.classList.toggle('active', button.dataset.tab === pageId); }); if (pageId === 'transcriptPage') { renderLinearTranscripts(); } else { if (active >= 0 && sections[active]) { select(active, false, false); } positionAllRegionLabels(); } } function renderLinearTranscripts() { const box = $('#linearTranscripts'); box.innerHTML = ''; if (!sections.length) { box.innerHTML = longerThreshold === null ? '<div class="empty">Select a project folder</div>' : `<div class="empty">No sections longer than ${longerThreshold} seconds remain</div>`; $('#transcriptSaveBtn').disabled = true; return; } sections.forEach((section, index) => { const row = document.createElement('div'); row.className = 'linear-transcript-row'; row.dataset.sectionIndex = String(index); const meta = document.createElement('div'); meta.className = 'linear-transcript-meta'; meta.innerHTML = `<strong>${section.section_id}</strong><br>` + `${fmt(section.start_time)}–${fmt(section.end_time)}`; const textarea = document.createElement('textarea'); textarea.className = 'linear-transcript-input'; textarea.dataset.sectionIndex = String(index); textarea.value = section.transcript || ''; textarea.setAttribute('aria-label', `Transcript ${section.section_id}`); textarea.addEventListener('input', () => { section.transcript = textarea.value; if (active === index) { $('#currentSectionText').textContent = section.transcript || section.section_id || ''; } setDirty(); renderList(); if (active === index) { $('#transcript').value = textarea.value; } }); textarea.addEventListener('focus', () => { active = index; renderList(); highlight(); }); row.append(meta, textarea); box.appendChild(row); }); $('#transcriptSaveBtn').disabled = !currentAudio; } function syncLinearTranscriptInputs() { document.querySelectorAll('.linear-transcript-input').forEach(textarea => { const index = Number(textarea.dataset.sectionIndex); if (Number.isInteger(index) && sections[index]) { sections[index].transcript = textarea.value; } }); } function isFullyVisible(element) { const rect = element.getBoundingClientRect(); return rect.top >= 0 && rect.bottom <= window.innerHeight; } function focusNextNonVisibleTranscript() { const inputs = [...document.querySelectorAll('.linear-transcript-input')]; if (!inputs.length) return; const focused = document.activeElement; let startIndex = inputs.indexOf(focused); if (startIndex < 0) startIndex = -1; let target = null; for (let step = 1; step <= inputs.length; step++) { const candidate = inputs[(startIndex + step) % inputs.length]; if (!isFullyVisible(candidate)) { target = candidate; break; } } // If every transcript is visible, move to the next transcript. if (!target) { target = inputs[(startIndex + 1 + inputs.length) % inputs.length]; } target.scrollIntoView({ behavior: 'smooth', block: 'center' }); window.setTimeout(() => { target.focus({ preventScroll: true }); const end = target.value.length; target.setSelectionRange(end, end); }, 220); } // ============================================================================ // SERVER API // ============================================================================ async function api(url, options) { const r = await fetch(url, options); const data = await r.json(); if (!r.ok) throw new Error(data.error || `HTTP ${r.status}`); return data; } async function refreshFiles(keep = true) { const selected = keep ? $('#fileSelect').value : ''; const data = await api('/api/files'); longerThreshold = data.longer_seconds == null ? null : num(data.longer_seconds); files = data.files; const sel = $('#fileSelect'); sel.innerHTML = '<option value="">Select audio folder…</option>'; for (const f of files) { const o = document.createElement('option'); o.value = f.name; const projectLabel = f.display_name || f.name; const validationMark = f.all_validated ? '✓ ' : ''; o.textContent = `${validationMark}${projectLabel}`; const progress = Number.isFinite(Number(f.section_count)) ? `${Number(f.validated_count || 0)}/${Number(f.section_count || 0)} validated` : 'validation status unavailable'; o.title = `${f.audio_file_name || f.audio_name || '*.mp3'} · ` + `${f.json_name || 'aligned_transcript.json'} · ${progress}`; o.disabled = !f.has_json; sel.appendChild(o); } if (selected && files.some(f => f.name === selected && f.has_json)) sel.value = selected; status(`${files.length} project folders found`); } async function loadProject(name) { if (!name) return; if (dirty && !confirm('Discard unsaved changes and load another file?')) { $('#fileSelect').value = currentAudio; return; } status('Loading project…'); const p = await api(`/api/project?name=${encodeURIComponent(name)}`); currentAudio = p.audio_name; projectData = structuredClone(p.data || {}); sections = sectionsForDisplay(projectData.sections || []).map(clean); structureChanged = false; renumber(); active = sections.length ? 0 : -1; lastCursorTime = 0; viewportSectionIndex = -1; lastViewportAdvanceSection = -1; validationTrackingEnabled = false; resetWaveViewportToStart(); $('#fileTitle').textContent = `${p.project_name || p.audio_name} · ${p.audio_file_name || '*.mp3'} · ${p.json_name}`; setDirty(false); renderList(); renderLinearTranscripts(); ws.load(p.audio_url); status('Loading waveform…'); } // ============================================================================ // CALM WAVEFORM VIEWPORT // ============================================================================ function waveScrollElement() { const wrapper = ws.getWrapper?.(); if (!wrapper) return null; // The wrapper is the full-width waveform content. Its nearest // ancestor with a smaller client width is the actual viewport. let element = wrapper.parentElement; while (element) { if ( element.clientWidth > 0 && ( element.scrollWidth > element.clientWidth + 1 || element.clientWidth < wrapper.clientWidth - 1 ) ) { return element; } element = element.parentElement; } return null; } function waveViewportWidth() { const viewport = waveScrollElement(); return Math.max( 1, viewport?.clientWidth || $('#waveform')?.clientWidth || $('#waveScroll')?.clientWidth || 1 ); } function waveformContentWidth() { const wrapper = ws.getWrapper?.(); return Math.max( waveViewportWidth(), wrapper?.scrollWidth || 0, wrapper?.clientWidth || 0 ); } function timeToWavePixel(time) { const duration = ws.getDuration(); if (!duration || duration <= 0) { return 0; } return Math.max(0, Math.min(duration, time)) / duration * waveformContentWidth(); } function clampWaveScroll(value) { const viewport = waveScrollElement(); if (!viewport) { return 0; } return Math.max( 0, Math.min( value, Math.max( 0, viewport.scrollWidth - viewport.clientWidth ) ) ); } function cancelWaveScrollAnimation() { if (waveScrollAnimation !== null) { cancelAnimationFrame(waveScrollAnimation); waveScrollAnimation = null; } } function currentWaveScroll() { const viewport = waveScrollElement(); return viewport?.scrollLeft || 0; } function applyWaveScroll(value) { const viewport = waveScrollElement(); if (!viewport) return; viewport.scrollLeft = clampWaveScroll(value); positionAllRegionLabels(); } function scrollWaveTo(target, animate = false) { const viewport = waveScrollElement(); if (!viewport) return; target = clampWaveScroll(target); const current = viewport.scrollLeft; if (!animate || Math.abs(current - target) < 2) { applyWaveScroll(target); return; } const distance = target - current; const startedAt = performance.now(); const step = now => { const progress = Math.min( 1, (now - startedAt) / WAVE_SCROLL_DURATION_MS ); const eased = 1 - Math.pow(1 - progress, 3); applyWaveScroll(current + distance * eased); if (progress < 1) { waveScrollAnimation = requestAnimationFrame(step); } else { waveScrollAnimation = null; } }; waveScrollAnimation = requestAnimationFrame(step); } function positionSectionInViewport(index, animate = false) { // Native WaveSurfer auto-scroll now controls the viewport. viewportSectionIndex = index; } function keepPlaybackVisible(time, hit) { // Intentionally left to WaveSurfer's built-in autoScroll. if (hit >= 0) { viewportSectionIndex = hit; } } function nativeWaveScrollElement() { const wrapper = ws.getWrapper?.(); if (!wrapper) return null; let element = wrapper.parentElement; while (element) { if ( element.clientWidth > 0 && element.scrollWidth > element.clientWidth + 1 ) return element; element = element.parentElement; } return null; } function cancelNativeGuardAnimation() { if (nativeGuardAnimation !== null) { cancelAnimationFrame(nativeGuardAnimation); nativeGuardAnimation = null; } } function nudgeNativeScrollTo(target) { const viewport = nativeWaveScrollElement(); if (!viewport) return; const maxScroll = Math.max(0, viewport.scrollWidth - viewport.clientWidth); target = Math.max(0, Math.min(target, maxScroll)); cancelNativeGuardAnimation(); const start = viewport.scrollLeft; const distance = target - start; const startedAt = performance.now(); const step = now => { const progress = Math.min(1, (now - startedAt) / VIEWPORT_ADVANCE_DURATION_MS); const eased = 1 - Math.pow(1 - progress, 3); viewport.scrollLeft = start + distance * eased; if (progress < 1) nativeGuardAnimation = requestAnimationFrame(step); else nativeGuardAnimation = null; }; nativeGuardAnimation = requestAnimationFrame(step); } function maybeAdvanceViewportForSection(time, hit) { if (!ws.isPlaying() || hit < 0 || !sections[hit]) return; if (lastViewportAdvanceSection === hit) return; const section = sections[hit]; const nextSection = sections[hit + 1]; const duration = section.end_time - section.start_time; if (duration <= 0) return; const progress = (time - section.start_time) / duration; const viewport = nativeWaveScrollElement(); const totalDuration = ws.getDuration(); if (!viewport || !totalDuration) return; // Final section: once playback is clearly inside it, reveal the // complete right side so its ending boundary remains visible. if (!nextSection) { if (progress < LAST_SECTION_SCROLL_TRIGGER_RATIO) return; lastViewportAdvanceSection = hit; nudgeNativeScrollTo( viewport.scrollWidth - viewport.clientWidth ); return; } // For ordinary sections, avoid movement right at either boundary. if ( progress < VIEWPORT_EDGE_GUARD_RATIO || progress > 1 - VIEWPORT_EDGE_GUARD_RATIO ) { return; } const contentWidth = viewport.scrollWidth; const currentStartX = section.start_time / totalDuration * contentWidth; const nextStartX = nextSection.start_time / totalDuration * contentWidth; const nextStartInView = nextStartX - viewport.scrollLeft; const rightLimit = viewport.clientWidth * VIEWPORT_NEXT_SECTION_RIGHT_RATIO; // Advance early enough that the upcoming section boundary appears // before the cursor reaches the far-right edge. if (nextStartInView <= rightLimit) return; const target = currentStartX - viewport.clientWidth * VIEWPORT_SECTION_TARGET_RATIO; lastViewportAdvanceSection = hit; nudgeNativeScrollTo(target); } function resetWaveViewportToStart() { cancelNativeGuardAnimation(); lastViewportAdvanceSection = -1; viewportSectionIndex = -1; const viewport = nativeWaveScrollElement(); if (viewport) { viewport.scrollLeft = 0; } } // ============================================================================ // RENDERING // ============================================================================ function getRegionLabelElement(region) { if (!region?.element) return null; return region.element.querySelector('[part="region-content"]') || region.element.querySelector('[data-region-content]') || region.element.firstElementChild; } function positionRegionLabel(region) { const label = getRegionLabelElement(region); const element = region?.element; if (!label || !element) return; // Keep every transcript label permanently anchored to the left // edge of its own section, regardless of playback position, // scrolling, zoom, or viewport location. label.style.position = 'absolute'; label.style.left = '4px'; label.style.right = 'auto'; label.style.transform = 'none'; label.style.textAlign = 'left'; label.style.justifyContent = 'flex-start'; } function positionAllRegionLabels() { requestAnimationFrame(() => regions.getRegions().forEach(positionRegionLabel)); } function renderRegions() { suppress = true; regions.clearRegions(); sections.forEach((s, i) => { const warning = hasWarningDuration(s); const r = regions.addRegion({ id: `section-region-${i}`, start: s.start_time, end: s.end_time, color: warning ? warningColor : normalColor, drag: true, resize: true, content: s.transcript || s.section_id }); if (r.element) { r.element.dataset.durationWarning = warning ? 'true' : 'false'; r.element.title = warning ? `Duration ${(s.end_time - s.start_time).toFixed(3)}s — expected 4–20 seconds` : ''; positionRegionLabel(r); } r.on('click', e => { e.stopPropagation(); clearFastTransition(); ws.pause(); // Region clicks do not reliably trigger WaveSurfer's normal // interaction seek. Calculate the exact clicked time ourselves. const wrapper = ws.getWrapper(); const bounds = wrapper.getBoundingClientRect(); const ratio = Math.max(0, Math.min(1, (e.clientX - bounds.left) / bounds.width)); const clickedTime = ratio * ws.getDuration(); ws.setTime(clickedTime); select(i, false); status(`Cursor positioned at ${fmt(clickedTime)} — playback paused`, 'ok'); }); r.on('update-end', () => { if (suppress) return; applyBoundary(i, r.start, r.end); setDirty(); renderRegions(); select(i, false); }); }); suppress = false; highlight(); positionAllRegionLabels(); } function highlight() { regions.getRegions().forEach((r, i) => { if (!r.element) return; const warning = hasWarningDuration(sections[i]); r.element.style.outline = i === active ? `3px solid ${warning ? '#dc2626' : '#2563eb'}` : 'none'; r.element.style.outlineOffset = '-2px'; }); } function keepActiveSectionRowVisible() { const list = $('#sectionList'); const row = list?.querySelector('.section-row.active'); if (!list || !row) return; const rowTop = row.offsetTop; const rowBottom = rowTop + row.offsetHeight; const visibleTop = list.scrollTop; const visibleBottom = visibleTop + list.clientHeight; if (rowTop < visibleTop) { list.scrollTop = rowTop; } else if (rowBottom > visibleBottom) { list.scrollTop = rowBottom - list.clientHeight; } } function renderList() { const box = $('#sectionList'); box.innerHTML = ''; if (!sections.length) { box.innerHTML = longerThreshold === null ? '<div class="empty">No sections</div>' : `<div class="empty">No sections longer than ${longerThreshold} seconds remain</div>`; return; } let shown = 0; sections.forEach((s, i) => { shown++; const row = document.createElement('div'); row.className = 'section-row' + (i === active ? ' active' : ''); row.innerHTML = `<div class="meta">${s.section_id} · ${fmt(s.start_time)}–${fmt(s.end_time)} · confidence ${Math.round(num(s.confidence))}</div><div class="text"></div>`; row.querySelector('.text').textContent = s.transcript || '(empty transcript)'; row.addEventListener('click', () => { ws.pause(); select(i, true); status('Moved to section start — playback paused', 'ok'); }); box.appendChild(row); }); if (!shown) box.innerHTML = '<div class="empty">No sections</div>'; keepActiveSectionRowVisible(); } // ============================================================================ // SECTION SELECTION AND FORM EDITING // ============================================================================ function select(i, seek = true, alignViewport = seek) { if (!sections.length) return; active = Math.max(0, Math.min(i, sections.length - 1)); const s = sections[active]; $('#sectionId').value = s.section_id; $('#start').value = s.start_time.toFixed(3); $('#end').value = s.end_time.toFixed(3); $('#transcript').value = s.transcript; $('#rawTranscript').value = s.transcript_raw ?? ''; $('#currentSectionText').textContent = s.transcript || s.section_id || ''; if (seek) { ws.setTime(s.start_time); } renderList(); highlight(); if (alignViewport) { // scroll section into user view requestAnimationFrame(() => { const viewport = nativeWaveScrollElement(); const section = sections[active]; const duration = ws.getDuration(); if (!viewport || !section || !duration) return; const startX = (section.start_time / duration) * viewport.scrollWidth; const endX = (section.end_time / duration) * viewport.scrollWidth; const visibleLeft = viewport.scrollLeft; const visibleRight = visibleLeft + viewport.clientWidth; // Already completely visible → don't move viewport if (startX >= visibleLeft && endX <= visibleRight) { return; } // Not visible → bring it into view const centerX = (startX + endX) / 2; viewport.scrollLeft = Math.max( 0, Math.min( centerX - viewport.clientWidth / 2, viewport.scrollWidth - viewport.clientWidth ) ); }); } else if (active !== viewportSectionIndex && seek) { viewportSectionIndex = active; } } function commit() { if (active < 0) return; const s = sections[active]; s.start_time = num($('#start').value, s.start_time); s.end_time = num($('#end').value, s.end_time); s.transcript = $('#transcript').value; applyBoundary(active, s.start_time, s.end_time); renumber(); setDirty(); renderRegions(); select(active, false); } function applyBoundary(i, start, end) { const duration = ws.getDuration() || Infinity; start = Math.max(0, Math.min(start, duration)); end = Math.max(start + .02, Math.min(end, duration)); if (i > 0 && start < sections[i - 1].end_time) sections[i - 1].end_time = start; if (i < sections.length - 1 && end > sections[i + 1].start_time) sections[i + 1].start_time = end; sections[i].start_time = start; sections[i].end_time = end; } function afterEdit(message, renumberIdsFrom = null) { renumber(); if (renumberIdsFrom !== null) renumberSectionIdsFrom(renumberIdsFrom); setDirty(); renderRegions(); select(active, false); status(message, 'ok'); } // ============================================================================ // BOUNDARY EDITING // ============================================================================ function setStart(t) { if (active < 0) return; const s = sections[active]; t = Math.max(0, Math.min(t, s.end_time - .02)); if (active > 0 && sections[active - 1].end_time > t) sections[active - 1].end_time = t; s.start_time = t; afterEdit('Start moved'); } function setEnd(t) { if (active < 0) return; const s = sections[active]; t = Math.min(ws.getDuration(), Math.max(t, s.start_time + .02)); if (active < sections.length - 1 && sections[active + 1].start_time < t) sections[active + 1].start_time = t; s.end_time = t; afterEdit('End moved'); } function nearest() { if (active < 0) return; const t = ws.getCurrentTime(), s = sections[active]; Math.abs(t - s.start_time) <= Math.abs(t - s.end_time) ? setStart(t) : setEnd(t); } function goToStart() { if (active < 0) return; ws.pause(); ws.setTime(sections[active].start_time); status('Moved to section start — playback paused', 'ok'); } function goToEnd() { if (active < 0) return; ws.pause(); ws.setTime(sections[active].end_time); status('Moved to section end — playback paused', 'ok'); } function sectionRightOfCursor(t) { // Select the first section that starts at, or after, the cursor. // When the cursor is exactly on a shared boundary, this selects // the section on the right rather than skipping over it. return sections.findIndex(section => section.start_time >= t - 0.001); } function sectionLeftOfCursor(t) { // Select the last section that starts before the cursor. // When the cursor is exactly at a section start, this selects the // previous section rather than treating the right section as left. for (let i = sections.length - 1; i >= 0; i--) { if (sections[i].start_time < t - 0.001) { return i; } } return -1; } function setRightSectionStartAtCursor() { const t = ws.getCurrentTime(), i = sectionRightOfCursor(t); if (i < 0) return status('No section exists to the right of the cursor', 'error'); const s = sections[i]; if (t >= s.end_time - .02) return status('Cursor is too close to the section end', 'error'); // Move only the selected right section's start boundary. // Do not change the end boundary of the section on its left. s.start_time = Math.max(0, t); active = i; afterEdit('Right section start moved'); } function setLeftSectionEndAtCursor() { const t = ws.getCurrentTime(), i = sectionLeftOfCursor(t); if (i < 0) return status('No section exists to the left of the cursor', 'error'); const s = sections[i]; if (t <= s.start_time + .02) return status('Cursor is too close to the section start', 'error'); // Move only the selected left section's end boundary. // Do not change the start boundary of the section on its right. s.end_time = Math.min(ws.getDuration(), t); active = i; afterEdit('Left section end moved'); } function joinAdjacentBoundariesAtCursor() { const t = ws.getCurrentTime(); let leftIndex; let rightIndex; const activeSection = active >= 0 && active < sections.length ? sections[active] : null; const cursorNearActiveEnd = activeSection && Math.abs(t - activeSection.end_time) <= JOIN_BOUNDARY_END_PROXIMITY_SECONDS; if (cursorNearActiveEnd) { // When the cursor is close to the active section's end, treat // that active section as the left side and its immediate next // section as the right side. leftIndex = active; rightIndex = active + 1; } else { leftIndex = sectionLeftOfCursor(t); rightIndex = sectionRightOfCursor(t); } if (leftIndex < 0 || leftIndex >= sections.length) { return status( 'No section exists to the left of the cursor', 'error' ); } if (rightIndex < 0 || rightIndex >= sections.length) { return status( 'No section exists to the right of the cursor', 'error' ); } if (leftIndex === rightIndex) { return status( 'Cursor must be between two sections', 'error' ); } const leftSection = sections[leftIndex]; const rightSection = sections[rightIndex]; if (t <= leftSection.start_time + 0.02) { return status( 'Cursor is too close to the left section start', 'error' ); } if (t >= rightSection.end_time - 0.02) { return status( 'Cursor is too close to the right section end', 'error' ); } leftSection.end_time = Math.min(ws.getDuration(), t); rightSection.start_time = Math.max(0, t); active = rightIndex; afterEdit('Left end and right start joined at cursor'); } // ============================================================================ // SECTION OPERATIONS // ============================================================================ function split() { if (active < 0) return; const t = ws.getCurrentTime(), left = sections[active]; if (t <= left.start_time + .05 || t >= left.end_time - .05) return status('Cursor must be inside the current section', 'error'); const right = { section_id: '', __source_section_id: null, transcript: '', start_time: t, end_time: left.end_time }; left.end_time = t; sections.splice(active + 1, 0, right); active++; structureChanged = true; afterEdit('Section split at audio cursor', active - 1); } function join() { if (active < 0 || active >= sections.length - 1) return; const a = sections[active], b = sections[active + 1]; if (longerThreshold !== null && a.__source_section_id && b.__source_section_id) { const originalSections = projectData.sections || []; const aPosition = originalSections.findIndex(section => section.section_id === a.__source_section_id); const bPosition = originalSections.findIndex(section => section.section_id === b.__source_section_id); if (aPosition >= 0 && bPosition > aPosition + 1) { return status('A shorter hidden section lies between these sections; clear the duration filter to join them.', 'error'); } } a.end_time = b.end_time; a.transcript = [a.transcript, b.transcript].filter(Boolean).join(' ').trim(); sections.splice(active + 1, 1); structureChanged = true; afterEdit('Joined with next section', active); } function add() { const t = ws.getCurrentTime(), duration = ws.getDuration(); let i = sections.findIndex(s => s.start_time > t); if (i < 0) i = sections.length; const previous = i > 0 ? sections[i - 1] : null; const next = i < sections.length ? sections[i] : null; let start = Math.max(0, t); if (previous && start < previous.end_time) start = previous.end_time; const availableEnd = next ? next.start_time : duration; const end = Math.min(availableEnd, start + .5); if (end - start < .02) return status('Not enough free space for a non-overlapping section', 'error'); sections.splice(i, 0, { section_id: '', __source_section_id: null, start_time: start, end_time: end, transcript: '', transcript_raw: '', words: [], shabad_id: null, line_id: null, confidence: null, source_section_ids: [], merged_short_tail: false }); active = i; structureChanged = true; afterEdit('New 500 ms section added'); $('#transcript').focus(); } function removeSection() { if (active < 0) return; const removed = sections[active]; sections.splice(active, 1); structureChanged = true; active = Math.min(active, sections.length - 1); renumber(); setDirty(); renderRegions(); renderList(); if (active >= 0) select(active, false); else { $('#sectionId').value = ''; $('#currentSectionText').textContent = ''; fieldIds.forEach(id => $('#' + id).value = ''); } status(`Deleted ${removed.section_id}`, 'ok'); } function samePankti(left, right) { if (!left || !right) return false; if ( left.lyric_index !== null && left.lyric_index !== undefined && right.lyric_index !== null && right.lyric_index !== undefined ) { return String(left.lyric_index) === String(right.lyric_index); } return Boolean( String(left.canonical_pankti || '').trim() && String(left.canonical_pankti || '').trim() === String(right.canonical_pankti || '').trim() && String(left.line_id || '').trim() === String(right.line_id || '').trim() && String(left.shabad_id || '').trim() === String(right.shabad_id || '').trim() ); } function mergeAlignedShortPanktiParts(firstPending) { let merged = 0; let i = Math.max(0, firstPending); while (i < sections.length - 1) { const left = sections[i]; const right = sections[i + 1]; if (!samePankti(left, right)) { i++; continue; } const leftDuration = num(left.end_time) - num(left.start_time); const rightDuration = num(right.end_time) - num(right.start_time); const joinedDuration = num(right.end_time) - num(left.start_time); if ( !(leftDuration < 4 || rightDuration < 4) || joinedDuration >= 20 ) { i++; continue; } left.end_time = right.end_time; left.transcript = [left.transcript, right.transcript] .filter(Boolean).join(' ').trim(); left.transcript_raw = [ left.transcript_raw, right.transcript_raw ].filter(Boolean).join(' ').trim(); left.words = [ ...(Array.isArray(left.words) ? left.words : []), ...(Array.isArray(right.words) ? right.words : []) ]; left.validated = left.validated === true && right.validated === true; left.merged_short_parts = true; left.merged_short_tail = true; left.source_section_ids = [ ...new Set([ ...(Array.isArray(left.source_section_ids) ? left.source_section_ids : [left.section_id]), ...(Array.isArray(right.source_section_ids) ? right.source_section_ids : [right.section_id]) ].filter(Boolean)) ]; sections.splice(i + 1, 1); merged++; } if (merged) { structureChanged = true; renumber(); } return merged; } function nextWarning() { if (!sections.length) return; let found = -1; for (let step = 1; step <= sections.length; step++) { const i = (Math.max(active, 0) + step) % sections.length; if (hasWarningDuration(sections[i])) { found = i; break; } } if (found < 0) return status('No duration warning sections found', 'ok'); select(found, true); const d = (sections[found].end_time - sections[found].start_time).toFixed(3); status(`Warning section ${sections[found].section_id} · ${d}s`, 'error'); } // ============================================================================ // PLAYBACK SPEED AND SECTION-ONLY FAST REVIEW // ============================================================================ function nextSectionAtOrAfter(time) { return sections.findIndex(section => section.end_time > time + 0.001); } function sectionStrictlyAfter(index) { return index >= 0 && index + 1 < sections.length ? index + 1 : -1; } function clearFastTransition() { if (fastTransitionTimer !== null) { clearTimeout(fastTransitionTimer); fastTransitionTimer = null; } fastTransitionPending = false; transitionSectionIndex = -1; transitionEndTime = 0; transitionNextIndex = -1; if (playbackRate > 0) { ws.setPlaybackRate(playbackRate, true); } } function setPlaybackSpeed(value) { const parsed = Number(value); playbackRate = Number.isFinite(parsed) ? Math.max(1, Math.min(3, parsed)) : 1; ws.setPlaybackRate(playbackRate, true); clearFastTransition(); if (playbackRate <= 1) { fastPlaybackSection = -1; status('Playback speed 1×', 'ok'); return; } const time = ws.getCurrentTime(); const hit = sectionAtTime(time); fastPlaybackSection = hit >= 0 ? hit : nextSectionAtOrAfter(time); status( pauseOnStart() ? `${playbackRate}× playback · pauses 0.5 seconds at nearby section starts` : `${playbackRate}× normal continuous playback`, 'ok' ); } function startFastPlaybackFromCurrentPosition() { if (playbackRate <= 1 || !sections.length) return true; const time = ws.getCurrentTime(); const index = sectionAtTime(time); // Do not skip gaps automatically. If playback starts in a gap, // continue normally until audio reaches the next section. if (index < 0) { fastPlaybackSection = -1; return true; } fastPlaybackSection = index; active = index; select(index, false); return true; } function beginSlowTransition(currentIndex) { if (playbackRate <= 1 || fastTransitionPending) return; const current = sections[currentIndex]; if (!current) return; const nextIndex = sectionStrictlyAfter(currentIndex); const next = nextIndex >= 0 ? sections[nextIndex] : null; const gapToNext = next ? next.start_time - current.end_time : Infinity; fastTransitionPending = true; transitionSectionIndex = currentIndex; transitionEndTime = current.end_time; transitionNextIndex = next && gapToNext >= -0.001 && gapToNext <= TRANSITION_WINDOW_SECONDS + 0.001 ? nextIndex : -1; ws.pause(); if (fastTransitionTimer !== null) { clearTimeout(fastTransitionTimer); } fastTransitionTimer = window.setTimeout(() => { fastTransitionTimer = null; if (!fastTransitionPending || playbackRate <= 1) return; ws.setPlaybackRate(TRANSITION_RATE, true); ws.play(); if (transitionNextIndex >= 0) { status( `Transitioning at 1× to ${sections[transitionNextIndex].section_id}`, 'ok' ); } else { status( 'Transitioning at 1× for up to 2 seconds', 'ok' ); } }, RATE_SETTLE_PAUSE_MS); } function pauseAtNextSectionStart(nextIndex) { if (nextIndex < 0 || !sections[nextIndex]) { clearFastTransition(); return; } ws.pause(); // The browser may dispatch time updates in coarse intervals. We // pause before the boundary and only then park the cursor at the // exact next-section start, preventing a short preview of its audio. const nextStart = sections[nextIndex].start_time; ws.setTime(nextStart); active = nextIndex; fastPlaybackSection = nextIndex; select(nextIndex, false); if (fastTransitionTimer !== null) { clearTimeout(fastTransitionTimer); } status( `Paused 0.5 seconds at ${sections[nextIndex].section_id} start`, 'ok' ); fastTransitionTimer = window.setTimeout(() => { fastTransitionTimer = null; if (playbackRate <= 1) { fastTransitionPending = false; transitionSectionIndex = -1; transitionEndTime = 0; transitionNextIndex = -1; return; } // Give the browser a short moment to settle before changing // back to the selected review speed. window.setTimeout(() => { fastTransitionPending = false; transitionSectionIndex = -1; transitionEndTime = 0; transitionNextIndex = -1; ws.setPlaybackRate(playbackRate, true); ws.play(); }, RATE_SETTLE_PAUSE_MS); }, NEXT_SECTION_START_PAUSE_MS); } function finishSlowTransitionWithoutNextSection() { ws.pause(); if (fastTransitionTimer !== null) { clearTimeout(fastTransitionTimer); } fastTransitionTimer = window.setTimeout(() => { fastTransitionTimer = null; fastTransitionPending = false; transitionSectionIndex = -1; transitionEndTime = 0; transitionNextIndex = -1; ws.setPlaybackRate(playbackRate, true); ws.play(); status(`Returned to ${playbackRate}× playback`, 'ok'); }, RATE_SETTLE_PAUSE_MS); } function handleFastPlaybackTime(time) { if (playbackRate <= 1 || !pauseOnStart() || !ws.isPlaying()) { return false; } if (fastTransitionPending) { if (transitionNextIndex >= 0) { const nextStart = sections[transitionNextIndex]?.start_time; if (Number.isFinite(nextStart) && time >= nextStart - NEXT_START_GUARD_SECONDS) { pauseAtNextSectionStart(transitionNextIndex); return true; } } if (time >= transitionEndTime + TRANSITION_WINDOW_SECONDS) { finishSlowTransitionWithoutNextSection(); } return false; } const hit = sectionAtTime(time); // Playback through gaps remains continuous. if (hit < 0) { fastPlaybackSection = -1; return false; } if (fastPlaybackSection !== hit) { fastPlaybackSection = hit; active = hit; select(hit, false); } const section = sections[fastPlaybackSection]; if (!section) return false; if (time >= section.end_time - FAST_END_TOLERANCE_SECONDS) { beginSlowTransition(fastPlaybackSection); } return false; } // ============================================================================ // REVIEW AND NAVIGATION // ============================================================================ function reviewIndex(from, direction = 1, includeCurrent = false) { if (!sections.length) return -1; const start = Math.max(0, Math.min(from, sections.length - 1)); for (let step = includeCurrent ? 0 : 1; step <= sections.length; step++) { const i = (start + direction * step + sections.length) % sections.length; if (needsReview(sections[i])) return i; } return -1; } function navigateSection(direction) { if (!sections.length) return; const wasPlaying = ws.isPlaying(); const nextIndex = Math.max( 0, Math.min(active + direction, sections.length - 1) ); clearFastTransition(); select(nextIndex, true, true); if (wasPlaying) { ws.play(); } status( direction > 0 ? `Moved to next section${wasPlaying ? ' — playback continues' : ''}` : `Moved to previous section${wasPlaying ? ' — playback continues' : ''}`, 'ok' ); } function applyPauseOnStartMode() { clearFastTransition(); if (pauseOnStart()) { status( 'Pause on start enabled · 0.5-second pause at nearby section starts', 'ok' ); } else { status( 'Pause on start disabled · normal continuous playback', 'ok' ); } } // ============================================================================ // VALIDATION // ============================================================================ function validateAllSections() { if (!sections.length || !currentAudio) { return status('Load a project first', 'error'); } let changed = 0; for (const section of sections) { if (section.validated !== true) { section.validated = true; changed++; } } validationTrackingEnabled = true; if (changed > 0) { setDirty(); renderList(); renderRegions(); renderLinearTranscripts(); if (active >= 0) { select(active, false); } status(`Validated ${changed} sections · press Save to write changes`, 'ok'); } else { status('All sections are already validated', 'ok'); } } // ============================================================================ // SAVING // ============================================================================ async function save() { // The transcript page edits sections directly. Its focused row can // change `active` while the hidden waveform form still contains a // different section, so never commit that hidden form from here. if (currentTab === 'transcriptPage') { syncLinearTranscriptInputs(); } else { commit(); } status('Saving…'); try { const preserveSectionIds = longerThreshold === null ? null : (projectData.sections || []) .filter(section => sectionDuration(section) <= longerThreshold) .map(section => section.section_id) .filter(Boolean); const out = await api('/api/save', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ audio_name: currentAudio, data: { ...projectData, sections: sections.map(clean) }, preserve_section_ids: preserveSectionIds, renumber_section_ids: structureChanged }) }); projectData = structuredClone(out.data || {}); sections = sectionsForDisplay(projectData.sections || []).map(clean); structureChanged = false; renumber(); active = sections.length ? Math.min(Math.max(active, 0), sections.length - 1) : -1; setDirty(false); lastCursorTime = ws.getCurrentTime(); renderRegions(); renderList(); renderLinearTranscripts(); if (currentTab === 'wavePage' && active >= 0) { select(active, false, false); } else if (active < 0) { $('#sectionId').value = ''; $('#currentSectionText').textContent = ''; fieldIds.forEach(id => $('#' + id).value = ''); } // Refresh project metadata so the dropdown gains its completion // tick immediately when the final section becomes validated. await refreshFiles(true); const savedMessage = longerThreshold === null ? `Saved ${out.sections} sections` : `Saved. ${sections.length} section${sections.length === 1 ? '' : 's'} longer than ${longerThreshold} seconds remain`; status(`${savedMessage}${out.backup_name ? ' · backup created' : ''}`, 'ok'); } catch (e) { status(e.message, 'error'); } } // $('#waveTab').addEventListener('click', () => switchTab('wavePage')); // $('#transcriptTab').addEventListener('click', () => switchTab('transcriptPage')); $('#transcriptSaveBtn').addEventListener('click', save); $('#refreshBtn').addEventListener('click', () => refreshFiles().catch(e => status(e.message, 'error'))); $('#fileSelect').addEventListener('change', e => loadProject(e.target.value).catch(err => status(err.message, 'error'))); $('#saveBtn').addEventListener('click', save); $('#validateAllBtn').addEventListener('click', validateAllSections); $('#playBtn').addEventListener('click', () => { clearFastTransition(); if (ws.isPlaying()) { ws.pause(); return; } if (playbackRate > 1 && !startFastPlaybackFromCurrentPosition()) { return; } ws.play(); }); $('#playbackRate').addEventListener('change', event => { setPlaybackSpeed(event.target.value); }); $('#addBtn').addEventListener('click', add); $('#splitBtn').addEventListener('click', split); $('#deleteBtn').addEventListener('click', removeSection); $('#zoomIn').addEventListener('click', () => { zoom = Math.min(400, zoom * 1.4); ws.zoom(zoom); positionAllRegionLabels(); }); $('#zoomOut').addEventListener('click', () => { zoom = Math.max(1, zoom / 1.4); ws.zoom(zoom); positionAllRegionLabels(); }); $('#pauseOnStart').addEventListener('change', applyPauseOnStartMode); fieldIds.forEach(id => $('#' + id).addEventListener('change', commit)); $('#transcript').addEventListener('input', () => { if (active >= 0) { sections[active].transcript = $('#transcript').value; $('#currentSectionText').textContent = sections[active].transcript || sections[active].section_id || ''; setDirty(); renderList(); const linear = document.querySelector( `.linear-transcript-input[data-section-index="${active}"]` ); if (linear && linear.value !== sections[active].transcript) { linear.value = sections[active].transcript; } } }); $('#rawTranscript').addEventListener('input', () => { if (active >= 0) { sections[active].transcript_raw = $('#rawTranscript').value; setDirty(); } }); ws.on('ready', () => { ws.setPlaybackRate(playbackRate, true); // WaveSurfer creates its scroll container during loading, so reset // again here to guarantee every newly selected file starts at left. requestAnimationFrame(() => { resetWaveViewportToStart(); }); const calmViewport = waveScrollElement(); if (calmViewport && !calmViewport.dataset.calmViewportBound) { calmViewport.dataset.calmViewportBound = 'true'; calmViewport.addEventListener( 'scroll', positionAllRegionLabels, { passive: true } ); calmViewport.addEventListener( 'pointerdown', cancelWaveScrollAnimation, { passive: true } ); } renderRegions(); const resumeTime = resumeTimeAfterValidation(); const pendingIndex = firstUnvalidatedIndex(); active = pendingIndex >= 0 ? pendingIndex : (sections.length ? sections.length - 1 : -1); ws.setTime(Math.min(resumeTime, ws.getDuration())); lastCursorTime = ws.getCurrentTime(); if (active >= 0) { select(active, false, false); requestAnimationFrame(() => { requestAnimationFrame(() => { const viewport = nativeWaveScrollElement(); if (!viewport || active < 0) return; const section = sections[active]; const duration = ws.getDuration(); if (!section || !duration) return; const sectionX = (section.start_time / duration) * viewport.scrollWidth; viewport.scrollLeft = Math.max( 0, sectionX - viewport.clientWidth * 0.5 ); }); }); } validationTrackingEnabled = true; status(pendingIndex >= 0 ? `Ready · resumed at first unvalidated section ${sections[pendingIndex].section_id}` : `Ready · all sections validated`, 'ok'); }); function sectionAtTime(t) { let lo = 0, hi = sections.length - 1; while (lo <= hi) { const mid = (lo + hi) >> 1, s = sections[mid]; const isLast = mid === sections.length - 1; if (t < s.start_time) hi = mid - 1; else if (t > s.end_time || (!isLast && t === s.end_time)) lo = mid + 1; else return mid; } return -1; } ws.on('timeupdate', t => { $('#time').textContent = `${fmt(t)} / ${fmt(ws.getDuration())}`; const previousTime = lastCursorTime; validateSectionsPassed(previousTime, t); lastCursorTime = t; if (handleFastPlaybackTime(t)) { return; } const hit = sectionAtTime(t); // Automatically jump across large gaps. const AUTO_SKIP_GAP_SECONDS = 3; const GAP_PREVIEW_SECONDS = 4; if ( ws.isPlaying() && active >= 0 && active < sections.length - 1 ) { const current = sections[active]; const next = sections[active + 1]; const gap = next.start_time - current.end_time; // if ( // gap >= AUTO_SKIP_GAP_SECONDS && // t >= current.end_time + GAP_PREVIEW_SECONDS && // t < next.start_time // ) { // navigateSection(1); // return; // } } maybeAdvanceViewportForSection(t, hit); if (hit >= 0 && hit !== active) { select(hit, false, false); } keepPlaybackVisible(t, hit); if (hit < 0) { return; } }); ws.on('interaction', () => { clearFastTransition(); cancelNativeGuardAnimation(); ws.pause(); const t = ws.getCurrentTime(); const hit = sectionAtTime(t); if (hit >= 0) { select(hit, false, false); viewportSectionIndex = hit; } else { viewportSectionIndex = -1; } status(hit >= 0 ? 'Cursor positioned in section — playback paused' : 'Cursor positioned — playback paused', 'ok'); }); // Copy/paste operates on the selected section's transcript, except // while a textarea is focused. Focused textareas keep the browser's // native copy/paste behavior, including selected-text copy and // insertion at the caret. function isTextareaTarget(target) { return target instanceof HTMLTextAreaElement || document.activeElement instanceof HTMLTextAreaElement; } document.addEventListener('copy', e => { const target = document.activeElement; // Keep normal Ctrl+C when the user has actually selected text. if ( target instanceof HTMLTextAreaElement && target.selectionStart !== target.selectionEnd ) { return; } // Otherwise copy the complete active section transcript. if (active < 0 || !sections[active] || !e.clipboardData) return; e.clipboardData.setData( 'text/plain', sections[active].transcript || '' ); e.preventDefault(); }); document.addEventListener('paste', e => { if (isTextareaTarget(e.target)) return; if (active < 0 || !sections[active] || !e.clipboardData) return; const transcript = e.clipboardData.getData('text/plain'); sections[active].transcript = transcript; $('#transcript').value = transcript; document.querySelectorAll('.linear-transcript-input').forEach(textarea => { if (Number(textarea.dataset.sectionIndex) === active) textarea.value = transcript; }); $('#currentSectionText').textContent = transcript || sections[active].section_id || ''; setDirty(); renderList(); renderRegions(); e.preventDefault(); }); document.addEventListener('keydown', e => { const editing = ['INPUT', 'TEXTAREA', 'SELECT'].includes(document.activeElement.tagName); if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 's') { e.preventDefault(); if (currentAudio) save(); return; } if (currentTab === 'transcriptPage' && (e.ctrlKey || e.metaKey) && e.key === 'ArrowRight') { e.preventDefault(); focusNextNonVisibleTranscript(); return; } if (e.code === 'Space' && !editing) { e.preventDefault(); clearFastTransition(); if (ws.isPlaying()) { ws.pause(); } else if (playbackRate <= 1 || startFastPlaybackFromCurrentPosition()) { ws.play(); } return; } if (editing) return; if (e.key === 'ArrowUp') { e.preventDefault(); joinAdjacentBoundariesAtCursor(); } else if (e.key === 'ArrowLeft' && e.shiftKey && (e.ctrlKey || e.metaKey)) { e.preventDefault(); setLeftSectionEndAtCursor(); } else if (e.key === 'ArrowRight' && e.shiftKey && (e.ctrlKey || e.metaKey)) { e.preventDefault(); setRightSectionStartAtCursor(); } else if (e.key === 'ArrowLeft' && e.shiftKey) { e.preventDefault(); goToStart(); } else if (e.key === 'ArrowRight' && e.shiftKey) { e.preventDefault(); goToEnd(); } // Ctrl + Right → next project/dropdown option else if (e.ctrlKey && e.key === 'ArrowRight') { e.preventDefault(); loadNextProject(); return; } else if (e.key === 'ArrowRight') { e.preventDefault(); // joinAdjacentBoundariesAtCursor(); // remote navigateSection(1); } else if (e.key === 'ArrowLeft' && e.ctrlKey) { e.preventDefault(); joinAdjacentBoundariesAtCursor(); } else if (e.key === 'ArrowLeft') { e.preventDefault(); // remote // clearFastTransition(); // if (ws.isPlaying()) { // ws.pause(); // } else if (playbackRate <= 1 || startFastPlaybackFromCurrentPosition()) { // ws.play(); // } navigateSection(-1); } else if (e.key === 'Enter' || e.key === 'ArrowDown') { e.preventDefault(); nearest(); } else if (e.key.toLowerCase() === 's') { e.preventDefault(); split(); } else if (e.key.toLowerCase() === 'j') { e.preventDefault(); join(); } else if (e.key.toLowerCase() === 'a') { e.preventDefault(); add(); } else if (e.key === 'Delete' || e.key === 'Backspace') { e.preventDefault(); removeSection(); } }); $('#waveScroll').addEventListener('scroll', positionAllRegionLabels, { passive: true }); window.addEventListener('resize', positionAllRegionLabels); window.addEventListener('beforeunload', e => { clearFastTransition(); cancelWaveScrollAnimation(); if (dirty) { e.preventDefault(); e.returnValue = ''; } }); // ============================================================================ // STARTUP // ============================================================================ refreshFiles(false).catch(e => status(e.message, 'error')); </script> </body> </html>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Gurbani Wave Section Editor</title>
<style>
/* ==========================================================================
DESIGN TOKENS
========================================================================== */
:root {
/* Softer dark surfaces */
--bg: #202522;
--panel: #282e2a;
--panel2: #323934;
/* Softer text — avoid pure/bright white */
--text: #d7ddd8;
--muted: #9ca89f;
/* Low-contrast borders */
--border: #414a43;
/* Calm green */
--accent: #6fae7b;
--accent2: #82bd8c;
--ok: #75b982;
/* Softer warning red */
--danger: #d66c68;
/* Waveform background */
--wavescroll: #252b27;
/* Section overlay */
--waveregion: rgba(211, 180, 88, 0.20);
}
/* ==========================================================================
BASE ELEMENTS
========================================================================== */
* {
box-sizing: border-box
}
html {
width: 100%;
max-width: 100%;
overflow-x: hidden;
}
body {
margin: 0;
width: 100%;
max-width: 100%;
overflow-x: hidden;
background: var(--bg);
color: var(--text);
font: 14px/1.45 Inter, system-ui, -apple-system, Segoe UI, sans-serif
}
button,
input,
select,
textarea {
font: inherit
}
/* ==========================================================================
HEADER
========================================================================== */
header {
display: flex;
gap: 10px;
align-items: end;
flex-wrap: wrap;
padding: 14px 18px;
border-bottom: 1px solid var(--border);
position: sticky;
top: 0;
z-index: 20
}
h1 {
font-size: 17px;
margin: 0 auto 4px 0
}
.field {
min-width: 190px
}
.field label,
.label {
display: block;
color: var(--muted);
font-size: 15px;
margin-bottom: 4px