import {imageDimensions,validateInput,subjectBounds,fitSubject,INPUT_LIMITS} from './logo-core.mjs'; import {toolResponseError} from './tool-access.mjs'; for(const root of document.querySelectorAll('.aen-logo-tool')) bind(root); function bind(root) { if(root.dataset.bound)return; root.dataset.bound='1'; const find=s=>root.querySelector(s),file=find('[data-file]'),original=find('[data-original]'),output=find('[data-output]'); const run=find('[data-run]'),cancel=find('[data-cancel]'),share=find('[data-share]'),refreshButton=find('[data-refresh]'); const status=find('[data-status]'),remaining=find('[data-remaining]'),reset=find('[data-reset]'),download=find('[data-download]'); const endpoint=new URL(root.dataset.toolEndpoint),home=root.dataset.home; let selected=null,originalUrl='',outputUrl='',quota=null,busy=false,generation=0,refreshPromise=null; const requests=new Set(); function message(text,error=false){status.textContent=text;status.dataset.error=error?'1':'0';} function controls() { run.disabled=busy||!!root.dataset.securityPending||!selected||!quota?.tools?.logo||quota.tools.logo.remaining<1; file.disabled=busy; for(const select of root.querySelectorAll('[data-setting]'))select.disabled=busy; cancel.hidden=!busy;refreshButton.disabled=busy; share.disabled=busy||!!root.dataset.securityPending||!quota?.tools?.logo||quota.share_claimed; root.setAttribute('aria-busy',busy?'true':'false'); } function showQuota(data) { quota=data; const policy=data.tools?.logo; if(!policy){remaining.textContent='This theme has no active Logo tool.';controls();return;} remaining.textContent=`${policy.remaining} of ${policy.limit} runs remaining today`; const next=new Date(data.reset_at); reset.textContent=`Resets ${next.toLocaleString(undefined,{timeZone:data.timezone})} (${data.timezone}). One image per run.`; share.textContent=data.share_claimed?'Daily bonus claimed':`Get ${policy.share_bonus} extra uses`; controls(); } async function request(path,body) { if(endpoint.origin!==location.origin)throw new Error('Open this tool at its canonical website address.'); const controller=new AbortController();requests.add(controller); const timer=setTimeout(()=>controller.abort(),15000); try { const options={cache:'no-store',credentials:'same-origin',signal:controller.signal}; if(body!==undefined){options.method='POST';options.headers={'Content-Type':'application/json','X-AEN-Tool-Token':quota?.token||''};options.body=JSON.stringify(body);} const response=await fetch(new URL(path,endpoint),options); const data=await response.json(); if(data.tools)showQuota(data); toolResponseError(root,endpoint,response,data); return data; } finally {clearTimeout(timer);requests.delete(controller);} } function refresh() { if(!refreshPromise)refreshPromise=request('status').finally(()=>{refreshPromise=null;}); return refreshPromise; } root.addEventListener('aen-security-change',controls); root.addEventListener('aen-security-verified',()=>refresh().then(()=>message('Security check passed. You can continue; your daily allowance is unchanged.')).catch(e=>message(e.message,true))); function clearResult() { if(outputUrl)URL.revokeObjectURL(outputUrl); outputUrl='';download.hidden=true;download.removeAttribute('href');output.hidden=true; output.getContext('2d').clearRect(0,0,output.width,output.height); find('[data-output-empty]').hidden=false;find('[data-result]').textContent=''; } function clearOriginal() { if(originalUrl)URL.revokeObjectURL(originalUrl); originalUrl='';original.removeAttribute('src');original.hidden=true;find('[data-original-empty]').hidden=false;selected=null; } file.addEventListener('change',async()=>{ const ticket=++generation;clearOriginal();clearResult();controls(); try { if(file.files.length!==1)throw new Error('Choose one image per run.'); const chosen=file.files[0]; if(chosen.size<=0||chosen.size>INPUT_LIMITS.bytes)throw new Error('Choose an image up to10 MiB.'); const bytes=new Uint8Array(await chosen.arrayBuffer()); if(ticket!==generation)return; const header=imageDimensions(bytes); validateInput({size:chosen.size,count:file.files.length,...header}); message('Reading the image on your device…'); originalUrl=URL.createObjectURL(chosen);original.src=originalUrl; await original.decode(); if(ticket!==generation)return; validateInput({size:chosen.size,count:1,width:original.naturalWidth,height:original.naturalHeight}); selected={file:chosen,width:original.naturalWidth,height:original.naturalHeight}; original.hidden=false;find('[data-original-empty]').hidden=true; message(`${selected.width} ×${selected.height}px selected. Adjust the output settings, then normalize.`); } catch(error){if(ticket===generation){clearOriginal();message(error.message||'This image could not be opened.',true);}} finally {controls();} }); run.addEventListener('click',async()=>{ if(busy||!selected)return; const ticket=++generation;busy=true;clearResult();controls();message('Checking today’s allowance…'); try { await refresh();if(ticket!==generation)return; const accepted=await request('run',{tool:'logo',count:1});if(ticket!==generation)return; if(!accepted.accepted)throw new Error('The daily allowance could not be confirmed.'); message('Normalizing locally…');await new Promise(requestAnimationFrame);if(ticket!==generation)return; const setting=name=>find(`[data-setting="${name}"]`).value; const size=Number(setting('size')),margin=Number(setting('margin')),radius=Number(setting('radius')); if(![256,512,1024,2048].includes(size)||![0,5,10,15].includes(margin)||![0,8,16,25].includes(radius))throw new Error('Choose valid output settings.'); const analysis=document.createElement('canvas'),factor=Math.min(1,1024/Math.max(selected.width,selected.height)); analysis.width=Math.max(1,Math.round(selected.width*factor));analysis.height=Math.max(1,Math.round(selected.height*factor)); const a=analysis.getContext('2d',{willReadFrequently:true});a.drawImage(original,0,0,analysis.width,analysis.height); const box=subjectBounds(a.getImageData(0,0,analysis.width,analysis.height),36); const subject={x:box.x*selected.width/analysis.width,y:box.y*selected.height/analysis.height,width:box.width*selected.width/analysis.width,height:box.height*selected.height/analysis.height}; analysis.width=1;analysis.height=1; const transform=fitSubject(subject,size,size,margin);output.width=size;output.height=size; const ctx=output.getContext('2d'),format=setting('format'); if(!['image/png','image/jpeg','image/webp'].includes(format))throw new Error('Choose a supported output format.'); if(format==='image/jpeg'||setting('background')==='white'){ctx.fillStyle='#ffffff';ctx.fillRect(0,0,size,size);} ctx.save();roundedClip(ctx,size,size*radius/100);ctx.imageSmoothingEnabled=true;ctx.imageSmoothingQuality='high'; ctx.drawImage(original,transform.x,transform.y,selected.width*transform.scale,selected.height*transform.scale);ctx.restore(); const blob=await new Promise(resolve=>output.toBlob(resolve,format,.92));if(ticket!==generation)return; if(!blob||!['image/png','image/jpeg','image/webp'].includes(blob.type))throw new Error('The browser could not create an export. Try PNG.'); const ext={'image/png':'png','image/jpeg':'jpg','image/webp':'webp'}[blob.type]; const basename=selected.file.name.replace(/\.[^.]+$/,'').replace(/[^a-z0-9_-]/gi,'-').slice(0,70)||'logo'; outputUrl=URL.createObjectURL(blob);download.href=outputUrl;download.download=`${basename}-normalized.${ext}`;download.textContent=`Download ${ext.toUpperCase()}`;download.hidden=false; output.hidden=false;find('[data-output-empty]').hidden=true; find('[data-result]').textContent=`${size} ×${size}px · ${ext.toUpperCase()} · ${Math.ceil(blob.size/1024)} KiB`; message(blob.type===format?'Ready. Download the result; your original image is unchanged.':`This browser cannot export the requested format. A PNG result is ready instead.`); } catch(error){if(ticket===generation)message(error.name==='AbortError'?'The request was interrupted. Refresh the allowance before another run.':error.message||'The image could not be processed.',true);} finally {if(ticket===generation){busy=false;controls();}} }); cancel.addEventListener('click',()=>{ generation++;for(const request of requests)request.abort();busy=false;clearResult();controls(); message('Cancelled. Runs that already started still count. Refresh the allowance before trying again.'); }); refreshButton.addEventListener('click',()=>{refresh().then(()=>message('Daily allowance refreshed.')).catch(e=>message(e.message||'Daily allowance is temporarily unavailable.',true));}); share.addEventListener('click',async()=>{ if(busy||quota?.share_claimed)return; // Invoke native sharing while the user gesture is still active; a completed share is not required for the daily click bonus. if(navigator.share)navigator.share({title:document.title,url:home}).catch(()=>{}); else if(navigator.clipboard?.writeText)navigator.clipboard.writeText(home).catch(()=>{}); busy=true;controls();message('Checking the daily bonus…'); try {await refresh();const data=await request('share',{});message(data.bonus_granted?'Daily bonus added. Use your share menu or the copied website link to share.':'Today’s bonus was already claimed.');} catch(error){message(error.message||'The daily bonus could not be confirmed.',true);} finally{busy=false;controls();} }); root.addEventListener('change',event=>{if(event.target.matches('[data-setting]'))clearResult();}); addEventListener('pagehide',event=>{ // A cached document is paused, not discarded. Keep its file and previews // together so Back does not restore an enabled button with no selection. if(event.persisted)return; for(const request of requests)request.abort();clearOriginal();clearResult(); }); addEventListener('pageshow',event=>{ if(event.persisted)refresh().catch(error=>message(error.message||'Please refresh the daily allowance.',true)); else { const ticket=generation; // Fresh history documents may regain native form values after pageshow, // but not the old decoded image. Do not display a misleading filename. setTimeout(()=>{if(!selected&&ticket===generation){file.value='';controls();}},0); } }); message('Choose one logo to get started.');refresh().catch(error=>{remaining.textContent='Daily allowance unavailable';message(error.message||'Please refresh the daily allowance.',true);controls();}); } function roundedClip(ctx,size,radius) { const r=Math.max(0,Math.min(radius,size/2)); ctx.beginPath();ctx.moveTo(r,0);ctx.lineTo(size-r,0);ctx.quadraticCurveTo(size,0,size,r);ctx.lineTo(size,size-r);ctx.quadraticCurveTo(size,size,size-r,size);ctx.lineTo(r,size);ctx.quadraticCurveTo(0,size,0,size-r);ctx.lineTo(0,r);ctx.quadraticCurveTo(0,0,r,0);ctx.closePath();ctx.clip(); }