import {MAX_BYTES,bounds,inspect,rgba} from './image-engine.r149.mjs'; import {downloadCSV} from '../expansion/result-export.r147.mjs'; const $=id=>document.getElementById(id),canvas=$('image-canvas'),ctx=canvas.getContext('2d',{willReadFrequently:true});let version=0,loaded=false,current=null,colors=[]; const say=s=>$('activity-status').textContent=s; function controls(){for(const id of ['sample-pixel','image-x','image-y'])$(id).disabled=!loaded;for(const id of ['copy-color','add-color','send-color'])$(id).disabled=!current||current.alpha!==255;$('export-colors').disabled=!colors.length;} function clearImage(){loaded=false;current=null;canvas.width=1;canvas.height=1;canvas.hidden=true;$('pixel-result').textContent='No pixel selected.';controls();} function sample(x,y){if(!loaded)return;if(!Number.isInteger(x)||!Number.isInteger(y)||x<0||y<0||x>=canvas.width||y>=canvas.height){say('Enter valid pixel coordinates.');return;}$('image-x').value=x;$('image-y').value=y;current=rgba(...ctx.getImageData(x,y,1,1).data);$('pixel-result').textContent=`${current.hex.toUpperCase()} · ${current.rgb} · Alpha ${current.alpha}/255`;$('pixel-swatch').getContext('2d').clearRect(0,0,64,64);const c=$('pixel-swatch').getContext('2d');c.fillStyle=current.rgb;c.globalAlpha=current.alpha/255;c.fillRect(0,0,64,64);c.globalAlpha=1;controls();say(current.alpha===255?'Pixel sampled.':'Transparent or translucent pixel; choose an opaque pixel to copy or transfer.');} function renderColors(){const root=$('picked-colors');root.replaceChildren();for(const [i,c] of colors.entries()){const li=document.createElement('li'),sw=document.createElement('canvas'),b=document.createElement('button');sw.width=32;sw.height=32;sw.setAttribute('aria-hidden','true');const g=sw.getContext('2d');g.fillStyle=c;g.fillRect(0,0,32,32);b.type='button';b.textContent='Remove '+c;b.addEventListener('click',()=>{colors.splice(i,1);renderColors()});li.append(sw,document.createTextNode(c.toUpperCase()),b);root.append(li)}controls()} $('image-file').addEventListener('change',async()=>{const token=++version;clearImage();$('pixel-swatch').getContext('2d').clearRect(0,0,64,64);const file=$('image-file').files[0];if(!file)return;let image;try{if(file.size>MAX_BYTES)throw Error('Choose a PNG or JPEG up to 10 MB.');const bytes=await file.arrayBuffer();const info=inspect(bytes);if(token!==version)return;say('Decoding image locally…');image=await createImageBitmap(new Blob([bytes],{type:info.type}));if(token!==version)return;bounds(image.width,image.height);canvas.width=image.width;canvas.height=image.height;ctx.drawImage(image,0,0);loaded=true;canvas.hidden=false;$('image-x').max=image.width-1;$('image-y').max=image.height-1;say(`${image.width} × ${image.height} decoded pixels. Click the image or enter coordinates.`);sample(0,0);}catch(e){if(token===version){clearImage();say(e.message||'Image could not be decoded.')}}finally{image?.close()}}); canvas.addEventListener('click',e=>{if(!loaded)return;const r=canvas.getBoundingClientRect();sample(Math.min(canvas.width-1,Math.max(0,Math.floor((e.clientX-r.left)*canvas.width/r.width))),Math.min(canvas.height-1,Math.max(0,Math.floor((e.clientY-r.top)*canvas.height/r.height))))}); $('sample-pixel').addEventListener('click',()=>{if(!$('image-x').value.trim()||!$('image-y').value.trim()){say('Enter both pixel coordinates.');return;}sample(Number($('image-x').value),Number($('image-y').value));}); $('clear-image').addEventListener('click',()=>{version++;$('image-file').value='';clearImage();$('pixel-swatch').getContext('2d').clearRect(0,0,64,64);say('Image cleared. Collected colors remain until cleared separately.');}); $('copy-color').addEventListener('click',async()=>{if(!current||current.alpha!==255)return;try{await navigator.clipboard.writeText(current.hex.toUpperCase());say('HEX copied.')}catch{say('Clipboard unavailable. Select the visible HEX text to copy.')}}); $('add-color').addEventListener('click',()=>{if(!current||current.alpha!==255)return;if(colors.includes(current.hex)){say('Color already collected.');return;}if(colors.length>=20){say('Collection limit reached (20 colors).');return;}colors.push(current.hex);renderColors();say('Color collected.');}); $('clear-colors').addEventListener('click',()=>{colors=[];renderColors();say('Collected colors cleared.');});$('export-colors').addEventListener('click',()=>{if(colors.length)downloadCSV([['HEX'],...colors.map(c=>[c])],'pme-image-colors.csv')}); $('send-color').addEventListener('click',()=>{if(!current||current.alpha!==255)return;try{const key='pme-image-color-transfer-v1';if(sessionStorage.getItem(key)&&!confirm('Replace pending color transfer?'))return;sessionStorage.setItem(key,JSON.stringify({version:1,createdAt:Date.now(),hex:current.hex}));location.assign('/tools/color-palette-generator/');}catch{say('Transfer unavailable. Copy HEX manually.')}});controls();