import { editScope, scopeIsExplicit, scopeForAxis, scopeButtons, openPatternColour } from './edit-scope.mjs'; import { createLiveEdit } from './live-edit.mjs'; import {planRows,expandRows,parsePlan,transformRows,copyAxis,buildProject,extractRows,swapPatterns,copyByDensity,evenWeft,copyWarpColours,importThreadPattern,makeEvenPattern,compressPattern,swapYarnSystems,prepareWeftSlots} from './thread-authoring.mjs'; const win=document.getElementById('threadWindow'),host=document.createElement('div');host.id='threadAuthoring';win.querySelector('.window-content').insertBefore(host,document.getElementById('warp').closest('label')); let state,base,revision,draft,dirty=false,stale=false,request=1200000,pending;const rows={warp:[],weft:[]},opts={},pages={warp:0,weft:0},pageSize=30;const emit=(name,detail)=>window.dispatchEvent(new CustomEvent(name,{detail}));const status=document.createElement('p');status.className='ta-status';status.setAttribute('role','status');const body=document.createElement('div');const actions=document.createElement('div');actions.className='ta-apply';actions.append(status);host.append(body,actions);function fail(e){status.textContent=e.message||String(e)}function button(text,fn){const b=document.createElement('button');b.type='button';b.textContent=text;b.onclick=()=>{try{fn()}catch(e){fail(e)}};return b}function touch(){dirty=true;livePattern.schedule();}function reset(){livePattern.cancel();if(!state?.project||state.indexed||state.raster){body.textContent='Open an editable yarn design to author thread values.';return}base=structuredClone(state.project);draft=structuredClone(base);revision=state.revision;for(const key of ['warp','weft']){rows[key]=planRows(base[key]);opts[key]={unit:'threads',repeat:1};pages[key]=0}dirty=false;stale=false;status.textContent='';render()} function current(){return buildProject(draft,rows,opts)}function normalize(key){rows[key]=planRows(expandRows(rows[key],{density:base.construction[key==='warp'?'epi':'ppi'],...opts[key]}));opts[key]={unit:'threads',repeat:1}} function acceptProject(q){draft=q;for(const key of ['warp','weft']){rows[key]=planRows(q[key]);opts[key]={unit:'threads',repeat:1};pages[key]=0}touch();render()} function fold(label,id,open){const details=document.createElement('details'),summary=document.createElement('summary');details.className='ta-options';details.id=id;details.open=open;summary.textContent=label;details.append(summary);return details} function render(){const opened=new Set([...body.querySelectorAll('details[open]')].map(node=>node.id));body.replaceChildren();const common=document.createElement('div');common.className='ta-common';const advanced=fold('Pattern operations','ta-pattern-operations',opened.has('ta-pattern-operations'));const axes=document.createElement('div');axes.className='ta-axes';body.append(common,axes,advanced);common.append(scopeButtons('Pattern edit scope')); common.append(button('Prepare missing weft colour slots',()=>{const before=draft.yarns.length;acceptProject(prepareWeftSlots(current()));status.textContent=(draft.yarns.length-before)+' new draft weft colour slots reuse the current weft yarn specifications. Choose Make check to update the pattern.'}));common.append(button('Pattern Equalizer · Make check',()=>{draft=copyWarpColours(copyAxis(current()));rows.weft=planRows(draft.weft);opts.weft={unit:'threads',repeat:1};touch();render()}),button('Warp stripes',()=>stripes('weft')),button('Weft stripes',()=>stripes('warp')));advanced.append(button('Load pattern JSON',loadPattern),button('Reload current design',reset),button('Warp=Weft Pattern',()=>{draft=copyAxis(current());rows.weft=planRows(draft.weft);opts.weft={unit:'threads',repeat:1};touch();render()}),button('Swap yarn systems + patterns',()=>{acceptProject(swapYarnSystems(current()));status.textContent='Yarn systems and patterns swapped.'}),button('Swap warp / weft patterns',()=>acceptProject(swapPatterns(current()))),button('Copy as per reed / pick ratio',()=>acceptProject(copyByDensity(current()))),button('Warp=Weft Color',()=>acceptProject(copyWarpColours(current()))));const total=document.createElement('input');total.type='number';total.min=1;total.max=1000000;total.value=base.weft.length;total.setAttribute('aria-label','Distribute picks equally target picks');advanced.append(' Target picks ',total,button('Distribute picks equally',()=>acceptProject(evenWeft(current(),+total.value))));advanced.append(button('Even Weft (odd → next even)',()=>{acceptProject(makeEvenPattern(current(),1));status.textContent='Odd weft runs rounded to the next even count.'}));for(const [axis,key] of ['warp','weft'].entries()){const section=document.createElement('section');section.className='ta-axis';const title=document.createElement('strong');title.textContent=axis?'Weft · picks':'Warp · ends';section.append(title);const unit=document.createElement('select');for(const u of ['threads','mm','inch'])unit.add(new Option(u,u));unit.value=opts[key].unit;unit.onchange=()=>{const previous=opts[key].unit;try{normalize(key);const density=base.construction[axis?'ppi':'epi'];for(const row of rows[key])row.value*=unit.value==='mm'?25.4/density:unit.value==='inch'?1/density:1;opts[key].unit=unit.value;touch();render()}catch(e){opts[key].unit=previous;fail(e)}};const repeat=document.createElement('input');repeat.type='number';repeat.min=1;repeat.max=1000000;repeat.value=opts[key].repeat;repeat.setAttribute('aria-label',key+' group repeats');repeat.dataset.patternAxis=key;repeat.oninput=()=>{ scopeForAxis(key); opts[key].repeat=+repeat.value; if(editScope()==='both'){ const other=otherAxis(key); opts[other].repeat=opts[key].repeat; body.querySelector(`[aria-label="${other} group repeats"]`).value=repeat.value; } touch(); summary(); };const setup=document.createElement('div');setup.className='ta-axis-setup'; const units=document.createElement('label'),repeats=document.createElement('label');units.append('Units',unit);repeats.append('Repeats',repeat);setup.append(units,repeats);section.append(setup); const operations=fold(axis?'Weft operations':'Warp operations','ta-'+key+'-operations',opened.has('ta-'+key+'-operations')); for(const op of ['reverse','mirror','rotate','left'])operations.append(button(({reverse:'Flip Pattern',mirror:'Mirror Pattern',rotate:'Shift Right Pattern',left:'Shift Left Pattern'})[op],()=>{normalize(key);rows[key]=transformRows(rows[key],op);touch();render()}));operations.append(button('Compress Pattern',()=>{normalize(key);const compressed=compressPattern(expandRows(rows[key]));rows[key]=compressed.rows;opts[key].repeat=compressed.repeat;touch();render()}));const first=document.createElement('input'),last=document.createElement('input');for(const field of [first,last]){field.type='number';field.min=1;field.max=rows[key].length}first.value=1;last.value=rows[key].length;first.setAttribute('aria-label',key+' extract first row');last.setAttribute('aria-label',key+' extract last row');operations.append(' Keep rows ',first,' through ',last,button('Keep selected rows',()=>{rows[key]=extractRows(rows[key],+first.value,+last.value);pages[key]=0;touch();render()}));operations.append(button('Extract Pattern (ungroup)',()=>{normalize(key);touch();render()}));const table=document.createElement('table');const head=document.createElement('thead');head.innerHTML='Yarn IDWidth / countRow';table.append(head);pages[key]=Math.max(0,Math.min(pages[key],Math.max(0,Math.ceil(rows[key].length/pageSize)-1)));const start=pages[key]*pageSize;rows[key].slice(start,start+pageSize).forEach((r,i)=>{const index=start+i,tr=document.createElement('tr'),yarn=document.createElement('select');yarn.setAttribute('aria-label',key+' yarn '+(index+1));for(const y of draft.yarns.filter(y=>y.axis===axis))yarn.add(new Option(y.id,y.id));yarn.value=r.id;const swatch=button('',()=>{ livePattern.flush(); if(dirty)throw Error('Correct the pattern values before editing yarn colours.'); openPatternColour(key,{warp:rows.warp[index]?.id,weft:rows.weft[index]?.id}); }); swatch.className='ta-swatch'; const labelSwatch=()=>{ swatch.title='Colour · '+key+' '+r.id; swatch.setAttribute('aria-label','Edit '+key+' row '+(index+1)+' colour'); }; labelSwatch();const paintSwatch=()=>{swatch.style.background='rgb('+(draft.yarns.find(y=>y.id===r.id)?.rgb||[190,190,190]).join(',')+')';};paintSwatch();yarn.onchange=()=>{r.id=yarn.value;labelSwatch();paintSwatch();touch();summary()};const value=document.createElement('input');value.type='number';value.min=opts[key].unit==='threads'?1:.00001;value.step=opts[key].unit==='threads'?'1':'any';value.value=r.value;value.setAttribute('aria-label',key+' width '+(index+1));value.dataset.patternWidth=key+':'+index;value.dataset.patternAxis=key; value.oninput=()=>changeWidth(key,index,value);const cells=[document.createElement('td'),document.createElement('td'),document.createElement('td')];cells[0].append(swatch,yarn);cells[1].append(value);cells[2].className='ta-rowtools';cells[2].append(button('↑',()=>move(key,index,-1)),button('↓',()=>move(key,index,1)),button('×',()=>{rows[key].splice(index,1);pages[key]=Math.min(pages[key],Math.max(0,Math.ceil(rows[key].length/pageSize)-1));touch();render()}));tr.append(...cells);table.append(tr)});section.append(table,button('+ Add row',()=>{rows[key].push({id:draft.yarns.find(y=>y.axis===axis)?.id,value:1});pages[key]=Math.floor((rows[key].length-1)/pageSize);touch();render()}),...(rows[key].length>pageSize?[button('Previous rows',()=>{pages[key]=Math.max(0,pages[key]-1);render()}),button('Next rows',()=>{pages[key]=Math.min(Math.max(0,Math.ceil(rows[key].length/pageSize)-1),pages[key]+1);render()}),` ${start+1}–${Math.min(start+pageSize,rows[key].length)} / ${rows[key].length}`]:[]));const info=document.createElement('p');info.id='ta-'+key+'-summary';section.append(info);operations.append(button('Read '+key+' text below',()=>{rows[key]=parsePlan(document.getElementById(key).value,draft.yarns.filter(y=>y.axis===axis).map(y=>y.id));opts[key]={unit:'threads',repeat:1};pages[key]=0;touch();render()}));section.append(operations);axes.append(section)}syncEditScope();summary()} function syncEditScope(){ for(const field of body.querySelectorAll('[data-pattern-axis]')){ field.disabled=scopeIsExplicit()&&editScope()!=='both'&&field.dataset.patternAxis!==editScope(); } } window.addEventListener('cad:edit-scope',syncEditScope); const otherAxis=key=>key==='warp'?'weft':'warp'; function pairedWidth(value,key,other){ const from=opts[key].unit,to=opts[other].unit; if(from===to)return value; const fromDensity=base.construction[key==='warp'?'epi':'ppi']; const toDensity=base.construction[other==='warp'?'epi':'ppi']; const inches=from==='mm'?value/25.4:from==='inch'?value:value/fromDensity; return to==='mm'?inches*25.4:to==='inch'?inches:Math.max(1,Math.round(inches*toDensity)); } function changeWidth(key,index,input){ scopeForAxis(key); const other=otherAxis(key); const paired=editScope()==='both'; if(paired&&!rows[other][index]){ input.value=rows[key][index].value; fail('Both needs a Warp and Weft row at this position.'); return; } rows[key][index].value=+input.value; if(paired){ const next=pairedWidth(+input.value,key,other); rows[other][index].value=next; const peer=body.querySelector(`[data-pattern-width="${other}:${index}"]`); if(peer)peer.value=next; } touch(); summary(); } function summary(){for(const [axis,key] of ['warp','weft'].entries()){try{const count=expandRows(rows[key],{density:base.construction[axis?'ppi':'epi'],...opts[key]}).length;document.getElementById('ta-'+key+'-summary').textContent=`${count.toLocaleString()} ${axis?'picks':'ends'} · actual ${(count/base.construction[axis?'ppi':'epi']*25.4).toFixed(3)} mm · ${(count/base.construction[axis?'ppi':'epi']).toFixed(4)} in`}catch(e){document.getElementById('ta-'+key+'-summary').textContent=e.message}}} function move(key,i,by){const j=i+by;if(j<0||j>=rows[key].length)return;[rows[key][i],rows[key][j]]=[rows[key][j],rows[key][i]];pages[key]=Math.floor(j/pageSize);touch();render()} function stripes(key){normalize(key);const first=rows[key][0]?.id;if(!first)throw Error('Add a yarn row first.');const n=expandRows(rows[key]).length;rows[key]=[{id:first,value:n}];touch();render()} function apply(){ if(!dirty || pending || !state || state.indexed || state.raster || win.hidden)return; try { if(stale||state.revision!==revision)throw Error('Design changed elsewhere. Reload current design.'); const project=current(); const sameThreads=['warp','weft'].every(key=>project[key].length===state.project[key].length&& project[key].every((id,index)=>id===state.project[key][index])); if(sameThreads) { if(state.project.sourceRepeatInches)project.sourceRepeatInches=state.project.sourceRepeatInches; if(JSON.stringify(project.yarns)===JSON.stringify(state.project.yarns)) { dirty=false; status.textContent=''; return; } } pending=++request; emit('cad:edit',{id:pending,type:'replace-project',revision,project}); }catch(e){fail(e);} } const livePattern=createLiveEdit(apply); host.addEventListener('keydown',event=>{ if(event.key==='Enter'&&event.target.matches('input[type=number]')){ event.preventDefault(); livePattern.flush(); } }); win.querySelector('[data-close=thread]').addEventListener('click',()=>livePattern.flush(),true); window.addEventListener('cad:document',e=>{const lockChanged=state?.raster!==e.detail.raster||state?.indexed!==e.detail.indexed;const prior=state?.project; state=e.detail; if(pending)return; if(!dirty&&!lockChanged&&prior!==state.project&&prior?.warp&&state.project.warp&& ['warp','weft','construction'].every(key=>JSON.stringify(prior[key])===JSON.stringify(state.project[key]))){ base=structuredClone(state.project);draft=structuredClone(base);revision=state.revision;render();return; } if(!dirty&&(lockChanged||state.revision!==revision))reset();else if(dirty&&state.revision!==revision){stale=true;status.textContent='Design changed elsewhere. Reload current design before making further edits.'}});window.addEventListener('cad:edit-result',e=>{if(e.detail.id!==pending)return;pending=null;if(e.detail.ok){ base=structuredClone(state.project); draft=structuredClone(state.project); revision=state.revision; dirty=stale=false; status.textContent='Pattern updated.'; }else fail(e.detail.error)});emit('cad:request-state'); window.addEventListener('cad:thread-authoring',e=>{host.hidden=false;host.scrollIntoView({block:'nearest'});status.textContent=''}); const patternFile=document.createElement('input');patternFile.type='file';patternFile.accept='.json,application/json';patternFile.hidden=true;patternFile.setAttribute('aria-label','Load Paramount thread pattern JSON, not native PAT');host.append(patternFile);let loadRevision,loadDraft; function loadPattern(){if(dirty||stale||pending)throw Error('Correct or reload the current pattern before loading JSON.');loadRevision=state.revision;loadDraft=draft;patternFile.value='';patternFile.click()} patternFile.onchange=async()=>{const file=patternFile.files?.[0];if(!file)return;try{if(file.size>64*1024*1024)throw Error('Pattern JSON must be 64 MB or smaller.');const text=await file.text();if(dirty||stale||pending||state.revision!==loadRevision||draft!==loadDraft)throw Error('Design or draft changed while reading. Current values retained; load the pattern again.');const payload=JSON.parse(text);const q=importThreadPattern(draft,payload);acceptProject(q);livePattern.flush();}catch(e){fail(e)}};