import { compoundWeave } from './compound-weave.mjs';
import { applyCompoundWeave, generatePegAndDraft, weaveFace } from './native-workspace-tools.mjs';
import { generateWeave } from './weave-generators.mjs';
const emit=(name,detail)=>window.dispatchEvent(new CustomEvent(name,{detail}));
const dialog=document.createElement('dialog');
dialog.id='compoundWeaveDialog';
dialog.innerHTML=`
Compound Weave
`;
document.body.append(dialog);
const $=id=>document.getElementById(id);
const library={
plain:{type:'plain'}, twill:{type:'twill'}, basket:{type:'basket'}, satin:{type:'satin',a:5,step:2}
};
for(const id of ['compoundFirst','compoundSecond']){
const select=$(id);
for(const item of [['Current weave','current'],['Plain 1/1','plain'],['Twill 2/2','twill'],
['Basket 2×2','basket'],['Satin 5','satin']]) select.add(new Option(...item));
select.onchange=preview;
}
$('compoundAxis').onchange=preview;
let state, revision, sourceWeave, matrix, pending;
let sequence=1700000;
function source(key){return key==='current'?sourceWeave:generateWeave(library[key]);}
function preview(){
matrix=undefined;
$('compoundError').textContent='';
const canvas=$('compoundPreview'),ctx=canvas.getContext('2d');
ctx.clearRect(0,0,canvas.width,canvas.height);
try{
matrix=compoundWeave(source($('compoundFirst').value),source($('compoundSecond').value),$('compoundAxis').value);
const w=matrix[0].length,h=matrix.length;
$('compoundSize').textContent=`${w} ends × ${h} picks`;
const sampleW=Math.min(w,canvas.width),sampleH=Math.min(h,canvas.height);
const dx=canvas.width/sampleW,dy=canvas.height/sampleH;
for(let y=0;y{state=event.detail;});
function validateState(){
if(!state||state.indexed||state.raster||state.project.cloth)throw Error('Open an editable single-cloth design.');
}
window.addEventListener('cad:compound-weave',()=>{
try{
validateState();
sourceWeave=weaveFace(state.project);
revision=state.revision;
$('compoundFirst').value='plain';
$('compoundSecond').value='satin';
$('compoundAxis').value='ends';
preview();
dialog.showModal();
}catch(error){$('status').textContent=error.message;}
});
window.addEventListener('cad:generate-peg-draft',()=>{
try{
validateState();
const project=generatePegAndDraft(state.project);
emit('cad:edit',{id:++sequence,revision:state.revision,type:'replace-project',project});
}catch(error){$('status').textContent=error.message;}
});
$('compoundApply').onclick=()=>{
try{
if(state.revision!==revision||state.raster)throw Error('Design changed. Reopen Compound Weave.');
const project=applyCompoundWeave(state.project,matrix);
pending=++sequence;
emit('cad:edit',{id:pending,revision,type:'replace-project',project});
}catch(error){$('compoundError').textContent=error.message;}
};
$('compoundClose').onclick=()=>dialog.close();
window.addEventListener('cad:edit-result',event=>{
if(event.detail.id!==pending)return;
pending=undefined;
if(event.detail.ok)dialog.close();
else $('compoundError').textContent=event.detail.error;
});
emit('cad:request-state');