Files

778 lines
36 KiB
JavaScript

/**
* VIZ 2.0 - UI Controls & Event Listeners
*/
import { state } from '../state.js';
import { formatTime } from '../utils.js';
import { initParticles } from '../rendering/particles.js';
import {
loadAudioFile,
loadImageFile,
loadWasserzeichenLogo,
startPlayback,
pausePlayback,
getCurrentPlaybackTime
} from '../audio/engine.js';
import {
setAwnMode,
applyPreset
} from './presets.js';
import {
startExport,
cancelExport,
fetchRenderHistory
} from '../export/video-export.js';
// --- UI Synchronizer ---
export function updateConfigFromUI() {
const coverUploadContainer = document.getElementById('coverUploadContainer');
const checkedShape = document.querySelector('input[name="shapeType"]:checked');
if (checkedShape) state.config.shapeType = checkedShape.value;
state.config.showCover = document.getElementById('showCover').checked;
state.config.circleRadius = parseInt(document.getElementById('circleRadius').value, 10);
state.config.pulseIntensity = parseFloat(document.getElementById('pulseIntensity').value);
state.config.pulseDecay = parseFloat(document.getElementById('pulseDecay').value);
state.config.showBorder = document.getElementById('showBorder').checked;
state.config.borderWidth = parseInt(document.getElementById('borderWidth').value, 10);
state.config.borderColor = document.getElementById('borderColor').value;
state.config.showProgressRing = document.getElementById('showProgressRing').checked;
state.config.progressRingColor = document.getElementById('progressRingColor').value;
state.config.progressRingWidth = parseInt(document.getElementById('progressRingWidth').value, 10);
state.config.rotationSpeed = parseFloat(document.getElementById('rotationSpeed').value);
state.config.beatSpinImpulse = document.getElementById('beatSpinImpulse').checked;
state.config.showSpectrum = document.getElementById('showSpectrum').checked;
const checkedMode = document.querySelector('input[name="spectrumMode"]:checked');
if (checkedMode) state.config.spectrumMode = checkedMode.value;
state.config.linearAlignment = document.getElementById('linearAlignment').value;
state.config.barCount = parseInt(document.getElementById('barCount').value, 10);
state.config.spectrumMaxHeight = parseInt(document.getElementById('spectrumMaxHeight').value, 10);
state.config.barWidth = parseFloat(document.getElementById('barWidth').value);
state.config.barSpacing = parseInt(document.getElementById('barSpacing').value, 10);
state.config.barCornerRadius = parseFloat(document.getElementById('barCornerRadius').value);
state.config.freqSensitivity = parseFloat(document.getElementById('freqSensitivity').value);
state.config.freqFocus = document.getElementById('freqFocus').value;
state.config.mirrorSpectrum = document.getElementById('mirrorSpectrum').checked;
state.config.enableParticles = document.getElementById('enableParticles').checked;
state.config.particleType = document.getElementById('particleType').value;
state.config.particleCount = parseInt(document.getElementById('particleCount').value, 10);
state.config.particleSpeed = parseFloat(document.getElementById('particleSpeed').value);
state.config.particleWarp = parseFloat(document.getElementById('particleWarp').value);
state.config.particleAudioReactivity = parseFloat(document.getElementById('particleAudioReactivity')?.value ?? 1.5);
state.config.enableGrid = document.getElementById('enableGrid').checked;
state.config.colorGrid = document.getElementById('colorGrid').value;
state.config.gridPerspective = parseFloat(document.getElementById('gridPerspective').value);
state.config.gridAudioReactive = parseFloat(document.getElementById('gridAudioReactive').value);
state.config.enableShake = document.getElementById('enableShake').checked;
state.config.camShakeIntensity = parseFloat(document.getElementById('camShakeIntensity').value);
state.config.enableGlitch = document.getElementById('enableGlitch').checked;
state.config.rgbSplitIntensity = parseFloat(document.getElementById('rgbSplitIntensity').value);
state.config.beatFlash = document.getElementById('beatFlash').checked;
state.config.enableBassZoom = document.getElementById('enableBassZoom').checked;
state.config.colorMode = document.getElementById('colorMode').value;
state.config.colorGrad1 = document.getElementById('colorGrad1').value;
state.config.colorGrad2 = document.getElementById('colorGrad2').value;
state.config.colorGrad3 = document.getElementById('colorGrad3').value;
state.config.colorParticle = document.getElementById('colorParticle').value;
state.config.gradientStyle = document.getElementById('gradientStyle').value;
state.config.enableGlow = document.getElementById('enableGlow').checked;
state.config.glowIntensity = parseFloat(document.getElementById('glowIntensity').value);
state.config.glowBlur = parseInt(document.getElementById('glowBlur').value, 10);
state.config.laserCore = document.getElementById('laserCore').checked;
state.config.backgroundMode = document.getElementById('backgroundMode').value;
state.config.showTextOverlay = document.getElementById('showTextOverlay').checked;
state.config.fontFamily = document.getElementById('fontFamily').value;
state.config.textPosition = document.getElementById('textPosition').value;
state.config.textOffsetY = parseInt(document.getElementById('textOffsetY').value, 10) || 0;
state.config.textSpacing = parseInt(document.getElementById('textSpacing').value, 10) || 10;
state.config.textPulseWithBeat = document.getElementById('textPulseWithBeat').checked;
state.config.textGlow = document.getElementById('textGlow').checked;
state.config.showTrackTitle = document.getElementById('showTrackTitle').checked;
state.config.titleFontSize = parseInt(document.getElementById('titleFontSize').value, 10) || 38;
state.config.titleColor = document.getElementById('titleColor').value || '#ffffff';
state.config.titleFontWeight = document.getElementById('titleFontWeight').value || '700';
state.config.titleUppercase = document.getElementById('titleUppercase').checked;
state.config.showTrackArtist = document.getElementById('showTrackArtist').checked;
state.config.artistFontSize = parseInt(document.getElementById('artistFontSize').value, 10) || 22;
state.config.artistColor = document.getElementById('artistColor').value || '#cccccc';
state.config.artistFontWeight = document.getElementById('artistFontWeight').value || '500';
state.config.artistUppercase = document.getElementById('artistUppercase').checked;
state.config.showTimecode = document.getElementById('showTimecode').checked;
state.config.timecodeFontSize = parseInt(document.getElementById('timecodeFontSize').value, 10) || 16;
state.config.timecodeColor = document.getElementById('timecodeColor').value || '#00f0ff';
state.config.timecodeMode = document.getElementById('timecodeMode').value || 'elapsed_and_total';
state.config.showProgressBar = document.getElementById('showProgressBar').checked;
state.config.progressBarWidth = parseInt(document.getElementById('progressBarWidth').value, 10) || 380;
state.config.progressBarHeight = parseInt(document.getElementById('progressBarHeight').value, 10) || 4;
state.config.progressBarColor = document.getElementById('progressBarColor').value || '#00f0ff';
const trackTitleEl = document.getElementById('trackTitle');
if (trackTitleEl) state.config.trackTitle = trackTitleEl.value;
const trackArtistEl = document.getElementById('trackArtist');
if (trackArtistEl) state.config.trackArtist = trackArtistEl.value;
const awnToggleEl = document.getElementById('awnModeToggle');
if (awnToggleEl) state.config.awnMode = awnToggleEl.checked;
// Stereo L/R Split
const stereoSplitEl = document.getElementById('stereoSplit');
if (stereoSplitEl) state.config.stereoSplit = stereoSplitEl.checked;
const stereoModeEl = document.getElementById('stereoMode');
if (stereoModeEl) state.config.stereoMode = stereoModeEl.value;
// 3-Band Routing
const routePulseEl = document.getElementById('routePulse');
if (routePulseEl) state.config.routePulse = routePulseEl.value;
const routeParticlesEl = document.getElementById('routeParticles');
if (routeParticlesEl) state.config.routeParticles = routeParticlesEl.value;
const routeShakeEl = document.getElementById('routeShake');
if (routeShakeEl) state.config.routeShake = routeShakeEl.value;
// BPM & Beat Synchronization
const bpmSyncEl = document.getElementById('bpmSync');
if (bpmSyncEl) state.config.bpmSync = bpmSyncEl.checked;
const bpmValEl = document.getElementById('bpmValue');
if (bpmValEl) {
state.config.bpmValue = parseFloat(bpmValEl.value) || 128;
state.bpm = state.config.bpmValue;
}
const bpmSyncRotEl = document.getElementById('bpmSyncRotation');
if (bpmSyncRotEl) state.config.bpmSyncRotation = bpmSyncRotEl.checked;
const bpmSyncGridEl = document.getElementById('bpmSyncGrid');
if (bpmSyncGridEl) state.config.bpmSyncGrid = bpmSyncGridEl.checked;
// Retro VHS & Scanlines
const enableVhsEl = document.getElementById('enableVhs');
if (enableVhsEl) state.config.enableVhs = enableVhsEl.checked;
const vhsScanlineEl = document.getElementById('vhsScanlineIntensity');
if (vhsScanlineEl) state.config.vhsScanlineIntensity = parseFloat(vhsScanlineEl.value);
const vhsNoiseEl = document.getElementById('vhsNoiseIntensity');
if (vhsNoiseEl) state.config.vhsNoiseIntensity = parseFloat(vhsNoiseEl.value);
const vhsCrtEl = document.getElementById('vhsCrtCurvature');
if (vhsCrtEl) state.config.vhsCrtCurvature = vhsCrtEl.checked;
// Phosphor Afterglow / Trails
const enableAfterglowEl = document.getElementById('enableAfterglow');
if (enableAfterglowEl) state.config.enableAfterglow = enableAfterglowEl.checked;
const afterglowDecayEl = document.getElementById('afterglowDecay');
if (afterglowDecayEl) state.config.afterglowDecay = parseFloat(afterglowDecayEl.value);
const afterglowModeEl = document.getElementById('afterglowMode');
if (afterglowModeEl) state.config.afterglowMode = afterglowModeEl.value;
// Sub-containers opacity / display
const textOpts = document.getElementById('textOptionsContainer');
const titleOpts = document.getElementById('titleOptionsContainer');
const artistOpts = document.getElementById('artistOptionsContainer');
const timeOpts = document.getElementById('timecodeOptionsContainer');
const progOpts = document.getElementById('progressBarOptionsContainer');
if (textOpts) textOpts.style.opacity = state.config.showTextOverlay ? '1' : '0.35';
if (titleOpts) titleOpts.style.opacity = (state.config.showTextOverlay && state.config.showTrackTitle) ? '1' : '0.35';
if (artistOpts) artistOpts.style.opacity = (state.config.showTextOverlay && state.config.showTrackArtist) ? '1' : '0.35';
if (timeOpts) timeOpts.style.opacity = (state.config.showTextOverlay && state.config.showTimecode) ? '1' : '0.35';
if (progOpts) progOpts.style.opacity = (state.config.showTextOverlay && state.config.showProgressBar) ? '1' : '0.35';
// Option containers hidden toggle
const stereoOpts = document.getElementById('stereoOptionsContainer');
if (stereoOpts) stereoOpts.classList.toggle('hidden', !state.config.stereoSplit);
const bpmOpts = document.getElementById('bpmOptionsContainer');
if (bpmOpts) bpmOpts.classList.toggle('hidden', !state.config.bpmSync);
const vhsOpts = document.getElementById('vhsOptionsContainer');
if (vhsOpts) vhsOpts.classList.toggle('hidden', !state.config.enableVhs);
const afterglowOpts = document.getElementById('afterglowOptionsContainer');
if (afterglowOpts) afterglowOpts.classList.toggle('hidden', !state.config.enableAfterglow);
// Toggle container visibility based on shape & toggles
document.getElementById('linearAlignmentSection').style.display = state.config.shapeType === 'linear' ? 'block' : 'none';
if (coverUploadContainer) coverUploadContainer.style.opacity = state.config.showCover ? '1' : '0.4';
// Update value badge labels
document.getElementById('valCircleRadius').textContent = `${state.config.circleRadius}px`;
document.getElementById('valPulseIntensity').textContent = `${Math.round(state.config.pulseIntensity * 100)}%`;
document.getElementById('valPulseDecay').textContent = `${Math.round(state.config.pulseDecay * 100)}%`;
document.getElementById('valBorderWidth').textContent = `${state.config.borderWidth}px`;
document.getElementById('valProgressRingWidth').textContent = `${state.config.progressRingWidth}px`;
document.getElementById('valRotationSpeed').textContent = `${state.config.rotationSpeed} RPM`;
document.getElementById('valBarCount').textContent = state.config.barCount;
document.getElementById('valSpectrumMaxHeight').textContent = `${state.config.spectrumMaxHeight}px`;
document.getElementById('valBarWidth').textContent = `${state.config.barWidth}px`;
document.getElementById('valBarSpacing').textContent = `${state.config.barSpacing}px`;
document.getElementById('valBarCornerRadius').textContent = `${state.config.barCornerRadius}px`;
document.getElementById('valFreqSensitivity').textContent = `${state.config.freqSensitivity}x`;
document.getElementById('valParticleCount').textContent = state.config.particleCount;
document.getElementById('valParticleSpeed').textContent = `${state.config.particleSpeed}x`;
document.getElementById('valParticleWarp').textContent = `${state.config.particleWarp}x`;
const valParticleReactivity = document.getElementById('valParticleAudioReactivity');
if (valParticleReactivity) valParticleReactivity.textContent = `${(state.config.particleAudioReactivity ?? 1.5).toFixed(1)}x`;
document.getElementById('valGridPerspective').textContent = `${Math.round(state.config.gridPerspective * 100)}%`;
document.getElementById('valGridAudioReactive').textContent = `${Math.round(state.config.gridAudioReactive * 100)}%`;
document.getElementById('valCamShakeIntensity').textContent = `${Math.round(state.config.camShakeIntensity * 100)}%`;
document.getElementById('valRgbSplitIntensity').textContent = `${Math.round(state.config.rgbSplitIntensity * 100)}%`;
document.getElementById('valGlowIntensity').textContent = `${Math.round(state.config.glowIntensity * 100)}%`;
document.getElementById('valGlowBlur').textContent = `${state.config.glowBlur}px`;
document.getElementById('valTextOffsetY').textContent = `${state.config.textOffsetY}px`;
document.getElementById('valTextSpacing').textContent = `${state.config.textSpacing}px`;
document.getElementById('valTitleFontSize').textContent = `${state.config.titleFontSize}px`;
document.getElementById('valArtistFontSize').textContent = `${state.config.artistFontSize}px`;
document.getElementById('valTimecodeFontSize').textContent = `${state.config.timecodeFontSize}px`;
document.getElementById('valProgressBarWidth').textContent = `${state.config.progressBarWidth}px`;
document.getElementById('valProgressBarHeight').textContent = `${state.config.progressBarHeight}px`;
const valVhsScan = document.getElementById('valVhsScanlineIntensity');
if (valVhsScan) valVhsScan.textContent = `${Math.round((state.config.vhsScanlineIntensity ?? 0.25) * 100)}%`;
const valVhsNoise = document.getElementById('valVhsNoiseIntensity');
if (valVhsNoise) valVhsNoise.textContent = `${Math.round((state.config.vhsNoiseIntensity ?? 0.15) * 100)}%`;
const valAfterglow = document.getElementById('valAfterglowDecay');
if (valAfterglow) valAfterglow.textContent = `${Math.round((state.config.afterglowDecay ?? 0.82) * 100)}%`;
initParticles(state.config.particleCount);
}
export function setAspectRatio(aspect) {
const aspectBtns = document.querySelectorAll('.aspect-btn');
const canvasWrapper = document.getElementById('canvasWrapper');
const toggleAlphaGrid = document.getElementById('toggleAlphaGrid');
const canvas = document.getElementById('vizCanvas');
state.aspectRatio = aspect;
aspectBtns.forEach(btn => {
btn.classList.toggle('active', btn.dataset.aspect === aspect);
});
canvasWrapper.className = 'canvas-wrapper';
if (toggleAlphaGrid.checked) canvasWrapper.classList.add('alpha-bg');
if (aspect === '16:9') {
canvasWrapper.classList.add('aspect-16-9');
state.width = 1920;
state.height = 1080;
} else if (aspect === '9:16') {
canvasWrapper.classList.add('aspect-9-16');
state.width = 1080;
state.height = 1920;
} else if (aspect === '1:1') {
canvasWrapper.classList.add('aspect-1-1');
state.width = 1080;
state.height = 1080;
}
canvas.width = state.width;
canvas.height = state.height;
initParticles(state.config.particleCount);
}
// --- Event Listeners & Binding ---
export function setupEvents() {
const canvas = document.getElementById('vizCanvas');
const canvasWrapper = document.getElementById('canvasWrapper');
const audioDropzone = document.getElementById('audioDropzone');
const imageDropzone = document.getElementById('imageDropzone');
const audioFileInput = document.getElementById('audioFileInput');
const imageFileInput = document.getElementById('imageFileInput');
const coverUploadContainer = document.getElementById('coverUploadContainer');
const btnPlayPause = document.getElementById('btnPlayPause');
const btnRewind = document.getElementById('btnRewind');
const btnForward = document.getElementById('btnForward');
const btnLoop = document.getElementById('btnLoop');
const seekScrubber = document.getElementById('seekScrubber');
const currentTimeEl = document.getElementById('currentTime');
const volumeSlider = document.getElementById('volumeSlider');
const aspectBtns = document.querySelectorAll('.aspect-btn');
const toggleSafeZone = document.getElementById('toggleSafeZone');
const safeZoneOverlay = document.getElementById('safeZoneOverlay');
const toggleAlphaGrid = document.getElementById('toggleAlphaGrid');
const quickPresetSelect = document.getElementById('quickPresetSelect');
const tabBtns = document.querySelectorAll('.tab-btn');
const tabPanels = document.querySelectorAll('.tab-panel');
const btnStartExport = document.getElementById('btnStartExport');
const headerExportBtn = document.getElementById('headerExportBtn');
const btnCancelExport = document.getElementById('btnCancelExport');
const btnSavePreset = document.getElementById('btnSavePreset');
const btnExportPresetJson = document.getElementById('btnExportPresetJson');
const btnImportPresetJson = document.getElementById('btnImportPresetJson');
const importPresetInput = document.getElementById('importPresetInput');
audioDropzone?.addEventListener('click', () => audioFileInput.click());
imageDropzone?.addEventListener('click', () => imageFileInput.click());
audioFileInput?.addEventListener('change', (e) => {
if (e.target.files.length) loadAudioFile(e.target.files[0]);
});
imageFileInput?.addEventListener('change', (e) => {
if (e.target.files.length) loadImageFile(e.target.files[0]);
});
[audioDropzone, imageDropzone].forEach(dz => {
dz.addEventListener('dragover', (e) => { e.preventDefault(); dz.classList.add('dragover'); });
dz.addEventListener('dragleave', () => dz.classList.remove('dragover'));
dz.addEventListener('drop', (e) => {
e.preventDefault();
dz.classList.remove('dragover');
if (dz === audioDropzone && e.dataTransfer.files.length) {
loadAudioFile(e.dataTransfer.files[0]);
} else if (dz === imageDropzone && e.dataTransfer.files.length) {
loadImageFile(e.dataTransfer.files[0]);
}
});
});
btnPlayPause?.addEventListener('click', () => {
if (state.isPlaying) {
pausePlayback();
} else {
startPlayback(state.pauseOffset || 0);
}
});
btnRewind?.addEventListener('click', () => {
const cur = getCurrentPlaybackTime();
const target = Math.max(0, cur - 5);
seekScrubber.value = target;
currentTimeEl.textContent = formatTime(target);
const pct = (target / (state.duration || 1)) * 100;
const bar = document.getElementById('timelineProgressBar');
if (bar) bar.style.width = `${pct}%`;
if (state.isPlaying) {
startPlayback(target);
} else {
state.pauseOffset = target;
}
});
btnForward?.addEventListener('click', () => {
const cur = getCurrentPlaybackTime();
const target = Math.min(state.duration || 0, cur + 5);
seekScrubber.value = target;
currentTimeEl.textContent = formatTime(target);
const pct = (target / (state.duration || 1)) * 100;
const bar = document.getElementById('timelineProgressBar');
if (bar) bar.style.width = `${pct}%`;
if (state.isPlaying) {
startPlayback(target);
} else {
state.pauseOffset = target;
}
});
btnLoop?.addEventListener('click', () => {
state.loop = !state.loop;
btnLoop.classList.toggle('active', state.loop);
if (state.audioSource) state.audioSource.loop = state.loop;
});
seekScrubber?.addEventListener('input', (e) => {
const t = parseFloat(e.target.value);
currentTimeEl.textContent = formatTime(t);
const pct = (t / (state.duration || 1)) * 100;
const bar = document.getElementById('timelineProgressBar');
if (bar) bar.style.width = `${pct}%`;
if (state.isPlaying) {
startPlayback(t);
} else {
state.pauseOffset = t;
}
});
volumeSlider?.addEventListener('input', (e) => {
const v = parseFloat(e.target.value);
if (state.gainNode) state.gainNode.gain.value = v;
});
aspectBtns.forEach(btn => {
btn.addEventListener('click', () => setAspectRatio(btn.dataset.aspect));
});
toggleSafeZone?.addEventListener('change', (e) => {
safeZoneOverlay.classList.toggle('hidden', !e.target.checked);
});
toggleAlphaGrid?.addEventListener('change', (e) => {
canvasWrapper.classList.toggle('alpha-bg', e.target.checked);
});
quickPresetSelect?.addEventListener('change', (e) => {
applyPreset(e.target.value);
});
// Tap Tempo & BPM Handling
const btnTapTempo = document.getElementById('btnTapTempo');
if (btnTapTempo) {
btnTapTempo.addEventListener('click', () => {
const now = performance.now();
if (state.tapTimes.length > 0 && (now - state.tapTimes[state.tapTimes.length - 1] > 2500)) {
state.tapTimes = [];
}
state.tapTimes.push(now);
if (state.tapTimes.length > 8) state.tapTimes.shift();
if (state.tapTimes.length >= 2) {
const intervals = [];
for (let i = 1; i < state.tapTimes.length; i++) {
intervals.push(state.tapTimes[i] - state.tapTimes[i - 1]);
}
const avgInterval = intervals.reduce((a, b) => a + b, 0) / intervals.length;
const tapBpm = Math.round(60000 / avgInterval);
if (tapBpm >= 40 && tapBpm <= 260) {
state.bpm = tapBpm;
state.config.bpmValue = tapBpm;
const bpmInp = document.getElementById('bpmValue');
if (bpmInp) bpmInp.value = tapBpm;
const badge = document.getElementById('bpmDetectedBadge');
if (badge) badge.textContent = `Tapped: ${tapBpm}`;
}
}
});
}
const bpmInput = document.getElementById('bpmValue');
if (bpmInput) {
bpmInput.addEventListener('input', (e) => {
const val = parseFloat(e.target.value);
if (val >= 40 && val <= 260) {
state.bpm = val;
state.config.bpmValue = val;
const badge = document.getElementById('bpmDetectedBadge');
if (badge) badge.textContent = `Manuell: ${val}`;
}
});
}
// AIWentNonsense Mode Toggle (Header Button)
const btnAiWentNonsenseMode = document.getElementById('btnAiWentNonsenseMode');
if (btnAiWentNonsenseMode) {
btnAiWentNonsenseMode.addEventListener('click', () => {
setAwnMode(!state.config.awnMode, !state.config.awnMode);
});
}
// AIWentNonsense Mode Switch (Tab 7 Toggle)
const awnModeToggle = document.getElementById('awnModeToggle');
if (awnModeToggle) {
awnModeToggle.addEventListener('change', (e) => {
setAwnMode(e.target.checked, e.target.checked);
});
}
// AIWentNonsense Cover Loader
const btnLoadAiWentNonsenseCover = document.getElementById('btnLoadAiWentNonsenseCover');
if (btnLoadAiWentNonsenseCover) {
btnLoadAiWentNonsenseCover.addEventListener('click', () => {
loadWasserzeichenLogo(() => {
const showCoverCb = document.getElementById('showCover');
if (showCoverCb) {
showCoverCb.checked = true;
state.config.showCover = true;
}
});
});
}
// Preset Library Cards
document.querySelectorAll('.preset-select-btn').forEach(btn => {
btn.addEventListener('click', () => {
applyPreset(btn.dataset.preset);
quickPresetSelect.value = btn.dataset.preset;
});
});
// 1-Click Palette Chips
document.querySelectorAll('.palette-chip').forEach(chip => {
chip.addEventListener('click', () => {
document.getElementById('colorGrad1').value = chip.dataset.p1;
document.getElementById('colorGrad2').value = chip.dataset.p2;
document.getElementById('colorGrad3').value = chip.dataset.p3;
document.getElementById('colorParticle').value = chip.dataset.p1;
document.getElementById('colorGrid').value = chip.dataset.p2;
updateConfigFromUI();
});
});
// Tabs
const sidebarTabs = document.getElementById('sidebarTabs') || document.querySelector('.sidebar-tabs');
const tabNavPrev = document.getElementById('tabNavPrev');
const tabNavNext = document.getElementById('tabNavNext');
function updateTabNavArrows() {
if (!sidebarTabs) return;
const maxScroll = sidebarTabs.scrollWidth - sidebarTabs.clientWidth;
if (maxScroll <= 2) {
if (tabNavPrev) tabNavPrev.classList.add('hidden');
if (tabNavNext) tabNavNext.classList.add('hidden');
return;
}
if (tabNavPrev) {
if (sidebarTabs.scrollLeft <= 3) {
tabNavPrev.classList.add('hidden');
} else {
tabNavPrev.classList.remove('hidden');
}
}
if (tabNavNext) {
if (sidebarTabs.scrollLeft >= maxScroll - 3) {
tabNavNext.classList.add('hidden');
} else {
tabNavNext.classList.remove('hidden');
}
}
}
function scrollTabIntoView(btn) {
if (!sidebarTabs || !btn) return;
const tabLeft = btn.offsetLeft;
const tabWidth = btn.offsetWidth;
const containerWidth = sidebarTabs.clientWidth;
const targetScrollLeft = tabLeft - (containerWidth / 2) + (tabWidth / 2);
sidebarTabs.scrollTo({ left: targetScrollLeft, behavior: 'smooth' });
}
tabBtns.forEach(btn => {
btn.addEventListener('click', () => {
tabBtns.forEach(b => b.classList.remove('active'));
tabPanels.forEach(p => p.classList.remove('active'));
btn.classList.add('active');
const panel = document.getElementById(btn.dataset.tab);
if (panel) panel.classList.add('active');
scrollTabIntoView(btn);
setTimeout(updateTabNavArrows, 300);
});
});
if (sidebarTabs) {
// 1. Mouse wheel horizontal scrolling
sidebarTabs.addEventListener('wheel', (e) => {
if (Math.abs(e.deltaY) > Math.abs(e.deltaX)) {
e.preventDefault();
const delta = e.deltaMode === 1 ? e.deltaY * 30 : e.deltaY;
sidebarTabs.scrollLeft += delta;
updateTabNavArrows();
}
}, { passive: false });
// 2. Navigation arrow buttons
if (tabNavPrev) {
tabNavPrev.addEventListener('click', () => {
sidebarTabs.scrollBy({ left: -160, behavior: 'smooth' });
});
}
if (tabNavNext) {
tabNavNext.addEventListener('click', () => {
sidebarTabs.scrollBy({ left: 160, behavior: 'smooth' });
});
}
sidebarTabs.addEventListener('scroll', () => {
updateTabNavArrows();
}, { passive: true });
window.addEventListener('resize', () => {
updateTabNavArrows();
});
// 3. Mouse Drag-to-Scroll
let isDown = false;
let startX = 0;
let scrollStart = 0;
let dragThresholdExceeded = false;
sidebarTabs.addEventListener('mousedown', (e) => {
if (e.button !== 0) return;
isDown = true;
dragThresholdExceeded = false;
startX = e.pageX - sidebarTabs.offsetLeft;
scrollStart = sidebarTabs.scrollLeft;
});
window.addEventListener('mouseup', () => {
if (isDown) {
isDown = false;
sidebarTabs.classList.remove('is-dragging');
}
});
sidebarTabs.addEventListener('mousemove', (e) => {
if (!isDown) return;
const x = e.pageX - sidebarTabs.offsetLeft;
const walk = x - startX;
if (Math.abs(walk) > 5) {
dragThresholdExceeded = true;
sidebarTabs.classList.add('is-dragging');
}
if (dragThresholdExceeded) {
e.preventDefault();
sidebarTabs.scrollLeft = scrollStart - walk;
updateTabNavArrows();
}
});
// Suppress tab button click if drag took place
sidebarTabs.addEventListener('click', (e) => {
if (dragThresholdExceeded) {
e.preventDefault();
e.stopPropagation();
dragThresholdExceeded = false;
}
}, true);
// Initial check
setTimeout(updateTabNavArrows, 150);
}
// Two-way UI sync
document.querySelectorAll('.sidebar-content input, .sidebar-content select').forEach(el => {
el.addEventListener('input', updateConfigFromUI);
el.addEventListener('change', updateConfigFromUI);
});
// Preset Manager
btnSavePreset?.addEventListener('click', () => {
const name = prompt('Preset Name eingeben:', 'Mein Custom Style');
if (!name) return;
const key = 'custom_' + Date.now();
const presetObj = Object.assign({}, state.config, { name });
const saved = JSON.parse(localStorage.getItem('viz_user_presets') || '{}');
saved[key] = presetObj;
localStorage.setItem('viz_user_presets', JSON.stringify(saved));
alert(`Preset "${name}" erfolgreich gespeichert!`);
});
btnExportPresetJson?.addEventListener('click', () => {
updateConfigFromUI();
const exportConfig = Object.assign({}, state.config);
const fileName = (exportConfig.name || exportConfig.trackTitle || 'custom').toLowerCase().replace(/[^a-z0-9]/g, '_');
const dataStr = 'data:text/json;charset=utf-8,' + encodeURIComponent(JSON.stringify(exportConfig, null, 2));
const a = document.createElement('a');
a.href = dataStr;
a.download = `viz_preset_${fileName}.json`;
a.click();
});
if (btnImportPresetJson) {
btnImportPresetJson.addEventListener('click', () => {
importPresetInput.value = '';
importPresetInput.click();
});
}
importPresetInput?.addEventListener('change', (e) => {
if (e.target.files.length) {
const reader = new FileReader();
reader.onload = (evt) => {
try {
const imported = JSON.parse(evt.target.result);
applyPreset(imported);
alert('Preset erfolgreich geladen!');
} catch (err) {
alert('Ungültiges Preset JSON');
}
};
reader.readAsText(e.target.files[0]);
}
});
// Export format listener removed as it is now static
btnStartExport?.addEventListener('click', startExport);
headerExportBtn?.addEventListener('click', () => {
document.querySelector('[data-tab="tab-export"]').click();
});
btnCancelExport?.addEventListener('click', cancelExport);
const btnRefreshHistory = document.getElementById('btnRefreshHistory');
if (btnRefreshHistory) {
btnRefreshHistory.addEventListener('click', fetchRenderHistory);
}
const exportHistoryList = document.getElementById('exportHistoryList');
if (exportHistoryList) {
exportHistoryList.addEventListener('click', async (e) => {
const btnDelete = e.target.closest('.btn-delete-render');
if (btnDelete) {
const id = btnDelete.dataset.id;
if (confirm('Bist du sicher, dass du diesen Render (inkl. Videodateien) unwiderruflich löschen möchtest?')) {
try {
const res = await fetch(`/api/export/history/${id}`, { method: 'DELETE' });
const data = await res.json();
if (res.ok) {
fetchRenderHistory();
} else {
alert(data.error || 'Fehler beim Löschen.');
}
} catch (err) {
alert('Fehler: ' + err.message);
}
}
return;
}
const btnRerender = e.target.closest('.btn-rerender');
if (btnRerender) {
try {
const settingsStr = btnRerender.dataset.settings;
if (!settingsStr) throw new Error('Keine Einstellungen gefunden.');
const settings = JSON.parse(settingsStr);
// Apply config to UI
if (settings.config) {
applyPreset(settings.config);
}
// Restore other settings
if (settings.aspectRatio) {
const arSelect = document.getElementById('exportAspectRatio');
if (arSelect) {
arSelect.value = settings.aspectRatio;
// Dispatch change event to update width/height
arSelect.dispatchEvent(new Event('change'));
}
}
if (settings.fps) {
const fpsInput = document.getElementById('exportFps');
if (fpsInput) fpsInput.value = settings.fps;
}
if (settings.title) {
const titleInput = document.getElementById('exportTitle');
if (titleInput) titleInput.value = settings.title;
}
// Switch to editor view
const targetTab = document.querySelector('[data-tab="tab-editor"]') || document.querySelector('[data-tab="tab-media"]');
if (targetTab) targetTab.click();
window.scrollTo({ top: 0, behavior: 'smooth' });
alert('Die Einstellungen für dieses Rendering wurden erfolgreich geladen!');
} catch (err) {
console.error('Fehler beim Laden der Einstellungen:', err);
alert('Fehler beim Laden der Einstellungen.');
}
}
});
}
window.addEventListener('keydown', (e) => {
if (e.code === 'Space' && e.target.tagName !== 'INPUT') {
e.preventDefault();
btnPlayPause.click();
}
});
}