const $ = selector => document.querySelector(selector); const api = window.filebowDialog; let config, preview, crop, items, aspect = 1; const field = (label, id, type = 'number', value = '') => { const box = document.createElement('label'); box.className='field'; const span=document.createElement('span');span.textContent=label; const input=document.createElement('input');input.id=id;input.type=type;input.value=value; if(type==='number'){input.min='0';input.max='30000';input.step='1';} box.append(span,input);return box; }; function text(value, cls='info'){const node=document.createElement('p');node.className=cls;node.textContent=value;return node;} function check(label,id){const node=document.createElement('label');node.className='check';const input=document.createElement('input');input.type='checkbox';input.id=id;node.append(input,document.createTextNode(label));return node;} function error(message){$('#error').hidden=false;$('#error').textContent=message;} function list(){const box=$('#files');box.replaceChildren();items.forEach((file,index)=>{ const row=document.createElement('div');row.className='file-row';const name=document.createElement('span');name.textContent=file.name;row.append(name); for(const [label,offset] of [['↑',-1],['↓',1],['Entfernen',0]]){const b=document.createElement('button');b.textContent=label;b.title=offset?'Reihenfolge ändern':'Datei entfernen';b.disabled=offset ? index+offset<0||index+offset>=items.length : items.length===1;b.onclick=()=>{if(offset)[items[index],items[index+offset]]=[items[index+offset],items[index]];else items.splice(index,1);list();};row.append(b);}box.append(row); });} async function init(){ config=await api.init();document.documentElement.dataset.theme=config.theme;items=[...config.files]; $('#filename').textContent=items.length===1?items[0].name:`${items.length} Dateien`; const content=$('#content'); if(config.type==='compress'){ $('#title').textContent='Komprimieren';content.append(text('PNG, WebP und AVIF behalten ihr Format. Andere Bilder werden als JPEG gespeichert, bei Transparenz als PNG. Videos werden MP4, Audio MP3. PDFs behalten ihr Format.')); const q=field('Qualität: 75 %','quality','range',75);q.lastChild.min=5;q.lastChild.max=95;q.lastChild.oninput=e=>q.firstChild.textContent=`Qualität: ${e.target.value} %`;content.append(q,field('Maximale Größe pro Datei (MB, optional)','maxSizeMB','number','')); $('#maxSizeMB').step='.1';content.append(text('Eine Zielgröße ist bei manchen Dateien nicht erreichbar. Das Ergebnis wird dann entsprechend gekennzeichnet.')); content.append(text('PNG wird verlustfrei optimiert. Eine kleinere Zielgröße kann die Bildabmessungen verringern.')); const estimate=text('Größe wird berechnet …');estimate.id='estimate';estimate.setAttribute('aria-live','polite');content.append(estimate); if(items.length>1)content.append(text(`Die Prognose bezieht sich auf ${items[0].name}. Die Einstellungen gelten für alle ausgewählten Dateien.`)); let timer, revision=0; const bytes=value=>value<1024*1024?`${(value/1024).toLocaleString('de-DE',{maximumFractionDigits:1})} KB`:`${(value/1024/1024).toLocaleString('de-DE',{maximumFractionDigits:2})} MB`; const update=()=>{const current=++revision;clearTimeout(timer);estimate.textContent='Größe wird berechnet …';timer=setTimeout(async()=>{try{ const result=await api.estimate({quality:Number($('#quality').value),maxSizeMB:Number($('#maxSizeMB').value)}); if(current!==revision||!result)return; const change=result.originalSize?Math.round((1-result.size/result.originalSize)*100):0; estimate.textContent=`${result.exact?'Voraussichtliche Größe':'Geschätzte Größe'}: ${bytes(result.size)} (${result.format.toUpperCase()}) · ${change>=0?`${change} % kleiner`:`${-change} % größer`} als ${bytes(result.originalSize)}${result.targetMet?'':' · Zielgröße voraussichtlich nicht erreichbar'}`; }catch(e){if(current===revision)estimate.textContent=`Keine Prognose verfügbar: ${e.message}`;}},500);}; $('#quality').addEventListener('input',update);$('#maxSizeMB').addEventListener('input',update);update(); }else if(config.type==='format'){ $('#title').textContent='Bildformat wählen'; const row=document.createElement('label');row.className='field';row.append(document.createTextNode('Ausgabeformat')); const select=document.createElement('select');select.id='format'; for(const fmt of ['jpg','png','webp','gif','avif','tiff','ico','bmp','heic','heif','pdf']){const option=document.createElement('option');option.value=fmt;option.textContent=fmt.toUpperCase();select.append(option);} row.append(select);content.append(row); }else if(config.type==='password'){ $('#title').textContent=config.mode==='add'?'PDF mit Passwort schützen':'PDF-Passwort entfernen'; content.append(field(config.mode==='add'?'Neues Passwort':'Aktuelles Passwort','password','password')); if(config.mode==='add')content.append(field('Passwort wiederholen','confirm','password')); }else if(config.type==='combine'){ $('#title').textContent='Dateien zusammenfügen';content.append(text('Die Dateien werden in dieser Reihenfolge zusammengefügt.')); const row=document.createElement('label');row.className='field';row.append(document.createTextNode('Ausgabeformat'));const select=document.createElement('select');select.id='format';for(const fmt of ['pdf','txt','md']){const option=document.createElement('option');option.value=fmt;option.textContent=fmt.toUpperCase();select.append(option);}row.append(select);content.append(row); const box=document.createElement('div');box.id='files';content.append(box);list(); }else if(config.type==='frame'){ $('#title').textContent='Einzelbild speichern';const box=document.createElement('div');box.className='preview';const video=document.createElement('video');video.controls=true;video.src=items[0].url;box.append(video);content.append(box,field('Zeitpunkt (Sekunden)','time','number',0));$('#time').step='.01';$('#time').max='1000000';video.ontimeupdate=()=>$('#time').value=video.currentTime.toFixed(2);$('#time').onchange=()=>video.currentTime=Number($('#time').value);video.onerror=()=>{box.replaceChildren(text('Keine Videovorschau verfügbar. Den Zeitpunkt kannst du unten angeben.'));}; }else if(config.type==='edit'){ $('#title').textContent={crop:'Zuschneiden',resize:'Größe ändern',rotate:'Drehen / Spiegeln'}[config.mode]; $('#save').disabled=true;content.append(text('Vorschau wird geladen …','muted')); try{preview=await api.preview();content.replaceChildren();aspect=preview.width/preview.height; if(preview.dataUrl){const box=document.createElement('div');box.className='preview';const canvas=document.createElement('canvas');const image=new Image();image.src=preview.dataUrl;await image.decode();canvas.width=image.width;canvas.height=image.height;box.append(canvas);content.append(box);const ctx=canvas.getContext('2d');const draw=()=>{ctx.clearRect(0,0,canvas.width,canvas.height);ctx.drawImage(image,0,0);if(crop){const sx=canvas.width/preview.width,sy=canvas.height/preview.height;ctx.fillStyle='#ffffff25';ctx.fillRect(crop.x*sx,crop.y*sy,crop.width*sx,crop.height*sy);ctx.strokeStyle='#ffad76';ctx.lineWidth=2;ctx.strokeRect(crop.x*sx,crop.y*sy,crop.width*sx,crop.height*sy);}};draw(); if(config.mode==='crop'){content.append(text('Zum Zuschneiden einen Bereich im Bild aufziehen.'));let start;const point=e=>{const r=canvas.getBoundingClientRect();return{x:Math.round(Math.max(0,Math.min(1,(e.clientX-r.left)/r.width))*preview.width),y:Math.round(Math.max(0,Math.min(1,(e.clientY-r.top)/r.height))*preview.height)};};canvas.onpointerdown=e=>{start=point(e);canvas.setPointerCapture(e.pointerId);};canvas.onpointermove=e=>{if(!start)return;const p=point(e);crop={x:Math.min(start.x,p.x),y:Math.min(start.y,p.y),width:Math.max(1,Math.abs(p.x-start.x)),height:Math.max(1,Math.abs(p.y-start.y))};draw();};canvas.onpointerup=()=>start=null;} } if(config.mode==='resize'){const fields=document.createElement('div');fields.className='fields';fields.append(field('Breite (px)','width','number',preview.width),field('Höhe (px)','height','number',preview.height));content.append(fields,check('Seitenverhältnis beibehalten','aspect'));$('#aspect').checked=true;$('#width').oninput=()=>{if($('#aspect').checked)$('#height').value=Math.max(1,Math.round(Number($('#width').value)/aspect));};$('#height').oninput=()=>{if($('#aspect').checked)$('#width').value=Math.max(1,Math.round(Number($('#height').value)*aspect));};} if(config.mode==='rotate'){const label=document.createElement('label');label.className='field';label.append(document.createTextNode('Drehung im Uhrzeigersinn'));const select=document.createElement('select');select.id='rotate';for(const angle of [0,90,180,270]){const option=document.createElement('option');option.value=angle;option.textContent=`${angle}°`;select.append(option);}label.append(select);content.append(label,check('Horizontal spiegeln','flipH'),check('Vertikal spiegeln','flipV'));} $('#save').disabled=false; }catch(e){error(e.message);} } if(!['combine','password','format'].includes(config.type))content.append(field('Dateiname (optional, ohne Endung)','outputName','text')); } $('#cancel').onclick=()=>api.submit(null); $('#save').onclick=()=>{ $('#error').hidden=true; const invalid=[...document.querySelectorAll('input')].find(input=>!input.checkValidity());if(invalid){invalid.reportValidity();return;} if(config.type==='password'){const password=$('#password').value;if(!password)return error('Bitte ein Passwort eingeben.');if(config.mode==='add'&&password!==$('#confirm').value)return error('Die Passwörter stimmen nicht überein.');return api.submit(password);} if(config.type==='combine')return api.submit({files:items.map(x=>x.path),format:$('#format').value}); if(config.type==='format')return api.submit($('#format').value); const result={};for(const id of ['quality','maxSizeMB','width','height','rotate','time']){if($('#'+id)&&$('#'+id).value!=='')result[id]=Number($('#'+id).value);} for(const id of ['flipH','flipV'])if($('#'+id))result[id]=$('#'+id).checked; if(config.type==='edit'&&config.mode==='crop'){if(!crop||crop.width<2||crop.height<2)return error('Bitte einen Bildbereich auswählen.');result.crop=crop;} if($('#outputName')?.value.trim())result.outputName=$('#outputName').value.trim();api.submit(result); }; document.addEventListener('keydown',e=>{if(e.key==='Escape')api.submit(null);});init().catch(e=>error(e.message));