const $=id=>document.getElementById(id),emit=(n,d)=>window.dispatchEvent(new CustomEvent(n,{detail:d}));const catalogs=new Map(),loading=new Map();let source='arah',selected=null,state=null,request=100000,pending=null;const send=(type,extra={})=>{const id=++request;emit('cad:edit',{id,type,...extra});return id;};function showBrowser(requestedSource){ emit('cad:show-window','yarnBrowser'); if(requestedSource)selectSource(requestedSource); else if(!catalogs.has(source))selectSource(source); }function profilePreview(canvas,profile,rgb){const ctx=canvas.getContext('2d'),w=canvas.width,h=canvas.height;ctx.fillStyle='#2186b1';ctx.fillRect(0,0,w,h);const out=ctx.getImageData(0,0,w,h);for(let x=0;xMath.min(255,v*(rgb?.[k]??profile.baseRGB[k])/Math.max(1,profile.baseRGB[k])));if(profile.colourMode==='tint'){const linear=v=>{v/=255;return v<=.04045?v/12.92:((v+.055)/1.055)**2.4;},lum=a=>a.reduce((s,v,k)=>s+linear(v)*[.2126,.7152,.0722][k],0),ratio=lum(profile.rgba.slice(src,src+3))/Math.max(.0003,lum(profile.baseRGB));c=(rgb||profile.baseRGB).map(v=>{const l=linear(v)*ratio;return Math.min(255,255*(l<=.0031308?12.92*l:1.055*l**(1/2.4)-.055));});}}else{const u=(y/h-.5)*2;a=Math.abs(u)<.7?1:0;const q=.58+.42*Math.sqrt(Math.max(0,1-u*u));c=(rgb||[220,202,160]).map(v=>v*q*(.96+.04*Math.sin((x+y)*.6)));}const at=(y*w+x)*4;for(let k=0;k<3;k++)out.data[at+k]=Math.round(out.data[at+k]*(1-a)+c[k]*a);}ctx.putImageData(out,0,0);} function current(){return state?.yarns.find(y=>y.id===$('yarn').value);}function refresh(){const y=current();if(!y)return;const profile=y.appearance?.demoYarn,locked=$('count').disabled;for(const button of $('demoYarnList').querySelectorAll('button'))button.disabled=locked;$('yarnEditorPalette').replaceChildren();for(const yarn of state.yarns){const b=document.createElement('button');b.textContent=yarn.id.replace(/^weft_slot_([0-9]+)$/,'w$1');b.style.background='rgb('+yarn.rgb+')';b.style.color=(yarn.rgb.reduce((a,b)=>a+b,0)<350)?'white':'#142638';b.classList.toggle('active',yarn.id===y.id);b.disabled=state.raster;b.title=(yarn.axis?'Weft ':'Warp ')+yarn.id;b.onclick=()=>{$('yarn').value=yarn.id;$('yarn').dispatchEvent(new Event('change'));refresh();};$('yarnEditorPalette').append(b);}profilePreview($('selectedYarnPreview'),profile,y.rgb);$('yarnUnit').value=y.unit||'Ne';$('yarnModel').value=profile?String(profile.model):'simple';$('dimensionFactor').value=profile?.dimensionFactor||y.demoSource?.dimensionFactor||18;const tex=y.unit==='Ne'?590.541/y.count:y.unit==='Denier'?y.count/9:y.count,diameter=y.diameterMm||Math.sqrt(tex*y.ply)/18;$('yarnDiameter').textContent=locked?'':diameter.toFixed(3)+' mm';for(const[id,k,f]of[['materialLuster','luster',10],['materialHairLength','hairLength',0],['materialHairProbability','hairProbability',0]]){$(id).value=profile?.[k]??f;$(id).disabled=locked||!profile;}$('yarnSourceInfo').textContent=profile?'Loaded: '+profile.name+(y.demoSource?.count?' · source count '+y.demoSource.count+' '+y.demoSource.unit:'')+' · shape interpreted in browser':y.textronicDrawing?'Textronic drawing width · browser simulation':'Simple yarn · projected multi-ply simulation';for(const id of ['yarnUnit','yarnModel','dimensionFactor','yarnThinner','yarnThicker','removeYarnProfile'])$(id).disabled=locked;const tbody=$('yarnProperties').querySelector('tbody');tbody.replaceChildren();for(const v of state.yarns){const tr=document.createElement('tr');for(const text of [v.id,v.count?v.count.toFixed(2)+'/'+v.ply+' '+v.unit:'—',v.diameterMm?v.diameterMm.toFixed(3)+' mm':'Auto',v.appearance?.twistTPM??600,v.appearance?.demoYarn?.name||'Simple']){const td=document.createElement('td');td.textContent=text;tr.append(td);}tr.onclick=()=>{$('yarn').value=v.id;$('yarn').dispatchEvent(new Event('change'));refresh();};tbody.append(tr);}} function drawRecipe(canvas,recipe){ if(recipe.metadataOnly&&!recipe.profile){ const context=canvas.getContext('2d'); context.fillStyle='rgb('+recipe.rgb.join(',')+')'; context.fillRect(0,0,canvas.width,canvas.height); }else profilePreview(canvas,recipe.profile); } function choose(recipe){ selected=recipe; for(const button of $('demoYarnList').querySelectorAll('button')) button.classList.toggle('selected',button.dataset.id===recipe?.id); $('recipeName').textContent=recipe?.name||'Select a yarn'; const preview=$('recipePreview'); preview.hidden=!recipe; $('keepYarnCount').disabled=!!(recipe?.textureOnly||recipe?.metadataOnly&&!recipe.unit); $('keepYarnColour').disabled=!!recipe?.textureOnly; const details=document.createElement('dl'); if(recipe){ drawRecipe(preview,recipe); const proof=recipe.evidence; const fields=proof?[ ['Material profile', proof.status], ['Source count', recipe.name], ['Archive usage', proof.usage.designs+' designs · '+proof.usage.warp+' warp · '+proof.usage.weft+' weft'], ['Textronic count match', proof.textronicRecords.join(', ') || 'No exact library record'], ['Preview texture', 'Textronic '+proof.textureSource], ['Arah weight reference', proof.arahReference.name+' · '+proof.arahReference.weightDifferencePercent+'% difference · reference only'], ]:recipe.textureOnly?[ ['Source',recipe.filename],['Texture',recipe.dimensions.join(' × ')+' px'],['Slots',recipe.colors.length], ]:recipe.metadataOnly?[ ['Source',recipe.filename],['Reference',recipe.reference||'—'], ['Count',recipe.count+' '+(recipe.unit||'(source unit '+recipe.unitCode+')')],['Ply',recipe.ply], ...(recipe.dimensions?[['Texture',recipe.dimensions.join(' × ')+' px']]:[]), ...(recipe.drawing?[['Source drawing width',(recipe.drawing.widthPx/recipe.drawing.dpi*25.4).toFixed(3)+' mm'],['Finishing','Browser approximation']]:[]), ]:[ ['Count',recipe.count+' '+recipe.unit],['Ply',recipe.ply],['Diameter ≈',recipe.diameterMm.toFixed(3)+' mm'], ['Twists / m',recipe.twistTPM+' '+recipe.direction], ['Model',['Simple','Mouliné','Mélange','Multicolor','Custom'][recipe.profile.model]],['Colours',recipe.colors.length], ['Shape',recipe.custom?recipe.custom.width+' × '+recipe.custom.height+' source pixels':'Generated from saved definition'], ]; for(const [name,value] of fields){ const label=document.createElement('dt'),field=document.createElement('dd'); label.textContent=name;field.textContent=value;details.append(label,field); } } $('recipeFields').replaceChildren(details); $('recipeStatus').textContent=recipe?.evidence?'Estimated texture. Keeps this yarn’s colour, count, ply and width.':recipe?.textureOnly?'Applies the source texture preview. Keeps your count and colour.': recipe?.metadataOnly?(recipe.unit?'Applies saved colour and count.':'Applies saved colour. Source count unit still needs verification.')+(recipe.profile?' Includes the saved texture preview.':recipe.drawing?' Uses the saved drawing width. Keeps your current texture.':' Keeps your current texture.'): recipe?'Source physical-unit mapping is provisional.':''; } function list(){ const group=$('yarnGroup').value,query=$('yarnSearch').value.trim().toLowerCase(); const records=catalogs.get(source)?.records||[]; const matches=records.filter(recipe=>(!group||recipe.group===group)&& (recipe.name+' '+(recipe.reference||'')).toLowerCase().includes(query)); const panel=$('demoYarnList'); panel.replaceChildren(); for(const recipe of matches){ const card=document.createElement('button'); card.className='demo-yarn-card'; card.dataset.id=recipe.id; const canvas=document.createElement('canvas'); canvas.width=240;canvas.height=60; drawRecipe(canvas,recipe); const name=document.createElement('b'),description=document.createElement('small'); name.textContent=recipe.name; description.textContent=recipe.evidence?recipe.evidence.usage.designs+' designs · Estimated':recipe.textureOnly?'Texture · '+recipe.dimensions.join(' × ')+' px': recipe.metadataOnly?(recipe.unit?recipe.count+'/'+recipe.ply+' '+recipe.unit+(recipe.profile?' · Texture + colour':recipe.drawing?' · Width + colour':' · Colour'):'Saved colour'): recipe.count+' '+recipe.unit+' / '+recipe.ply+' · '+recipe.colors.length+' colours'; card.append(canvas,name,description); card.disabled=$('count').disabled; card.onclick=()=>{choose(recipe);loadSelectedYarn();}; panel.append(card); } choose(matches.includes(selected)?selected:matches[0]); if(!matches.length&&catalogs.has(source))$('recipeStatus').textContent='No matching yarns.'; } async function load(sourceKey){ if(catalogs.has(sourceKey))return catalogs.get(sourceKey); if(!loading.has(sourceKey))loading.set(sourceKey,(async()=>{ const endpoints={arah:'/api/demo-yarns',textronic:'/api/textronic-yarns',paramount:'/api/paramount-yarns'}; const response=await fetch(endpoints[sourceKey]); if(!response.ok)throw Error('Cannot load yarns.'); const data=await response.json(); if(!Array.isArray(data.records))throw Error('Yarn library is unavailable.'); catalogs.set(sourceKey,data); return data; })().finally(()=>loading.delete(sourceKey))); return loading.get(sourceKey); } async function selectSource(sourceKey){ source=sourceKey; for(const tab of document.querySelectorAll('[data-yarn-source]')){ const active=tab.dataset.yarnSource===source; tab.classList.toggle('active',active); tab.setAttribute('aria-pressed',String(active)); } $('yarnSearch').value=''; $('yarnGroup').replaceChildren(new Option('All yarns','')); $('demoYarnList').replaceChildren(); $('demoYarnList').scrollTop=0; choose(null); $('recipeStatus').textContent='Loading yarns…'; try{ const data=await load(sourceKey); if(source!==sourceKey)return; const groups=[...new Set(data.records.map(recipe=>recipe.group))]; $('yarnGroup').replaceChildren(new Option('All yarns · '+data.records.length,''),...groups.map(group=>new Option(group,group))); list(); if(data.unavailable?.length)$('recipeStatus').textContent+=' '+data.unavailable.length+' source files could not be opened.'; }catch(error){if(source===sourceKey)$('recipeStatus').textContent=error.message;} } for(const tab of document.querySelectorAll('[data-yarn-source]')) tab.onclick=()=>selectSource(tab.dataset.yarnSource); window.addEventListener('cad:document',e=>{state=e.detail;refresh();});$('yarn').addEventListener('change',refresh);$('yarnPalette').addEventListener('click',()=>setTimeout(refresh,0));document.addEventListener('click',e=>{const opener=e.target.closest('[data-action="yarn-browser"]');if(opener)showBrowser(opener.dataset.openYarnSource);});$('yarnGroup').onchange=list;$('yarnSearch').oninput=list;function loadSelectedYarn(){if(!selected||!state||$('count').disabled)return;pending=request+1;$('recipeStatus').textContent='Applying '+selected.name+'…';send('apply-demo-yarn',{record:selected,options:{keepColour:$('keepYarnColour').checked,keepCount:$('keepYarnCount').checked}});} window.addEventListener('cad:edit-result',e=>{if(e.detail.id===pending){$('recipeStatus').textContent=e.detail.ok?'Applied to yarn '+$('yarn').value+'. View Fabric simulation to see its shape and texture.':e.detail.error;pending=null;emit('cad:request-state');}});$('removeYarnProfile').onclick=()=>send('simple-yarn');$('yarnUnit').onchange=()=>send('set-yarn-unit',{unit:$('yarnUnit').value});$('dimensionFactor').onchange=()=>send('set-yarn-diameter',{factor:Number($('dimensionFactor').value)});$('yarnThinner').onclick=()=>send('set-yarn-diameter',{factor:Math.min(100,Number($('dimensionFactor').value)+1)});$('yarnThicker').onclick=()=>send('set-yarn-diameter',{factor:Math.max(1,Number($('dimensionFactor').value)-1)});$('yarnModel').onchange=async()=>{const model=$('yarnModel').value;if(model==='simple'){send('simple-yarn');return;}const {records}=await load('arah');const r=records.find(r=>String(r.profile.model)===model);if(r)send('apply-demo-yarn',{record:r,options:{keepColour:true,keepCount:true}});};$('viewYarnDetail').onclick=()=>{const y=current();if(!y)return;profilePreview($('yarnDetailCanvas'),y.appearance?.demoYarn,y.rgb);$('yarnDetailInfo').textContent=y.appearance?.demoYarn?'Source: '+y.appearance.demoYarn.name+' · three repetitions · shape is shown across the yarn width':'Simple projected yarn';$('yarnDetailDialog').showModal();};emit('cad:request-state');selectSource('arah'); new MutationObserver(refresh).observe($('count'),{attributes:true,attributeFilter:['disabled']}); for(const[id,key]of[['materialLuster','luster'],['materialHairLength','hairLength'],['materialHairProbability','hairProbability']])$(id).onchange=()=>send('set-demo-material',{parameters:{[key]:Number($(id).value)}});