import { createLiveEdit } from './live-edit.mjs';
import { applyPegPlan, readPegPlan, resizePegPicks, splicePegPicks, parseNumericPeg } from './peg-plan.mjs';
const emit = (name, detail) => window.dispatchEvent(new CustomEvent(name, { detail }));
const dialog = document.createElement('dialog');
dialog.id = 'pegPlanDialog';
dialog.innerHTML = `
Peg Plan
Filled cell = shaft lifted. Edits apply to every end threaded on that shaft.
Pick range tools
Example 1.3. lifts shafts 1 and 3. Use - for no lift.
`;
document.body.append(dialog);
const get = id => document.getElementById(id);
const pageSize = 16;
let state, lifting, revision, pending, numeric;
let request = 1400000;
function offset(id, total) {
const input = get(id);
const max = Math.ceil(total / pageSize);
input.max = max;
input.value = Math.max(1, Math.min(max, Math.trunc(Number(input.value)) || 1));
return (Number(input.value) - 1) * pageSize;
}
function draw() {
const shafts = lifting[0].length;
const firstPick = offset('pegPickPage', lifting.length);
const firstShaft = offset('pegShaftPage', shafts);
const lastShaft = Math.min(firstShaft + pageSize, shafts);
get('pegSize').textContent = `${lifting.length} picks × ${shafts} shafts`;
const grid = get('pegGrid');
grid.replaceChildren();
const header = grid.insertRow();
const addHeader = (row, value) => {
const cell = document.createElement('th');
cell.textContent = value;
row.append(cell);
};
addHeader(header, 'Pick');
for (let shaft = firstShaft; shaft < lastShaft; shaft++) addHeader(header, shaft + 1);
for (let pick = firstPick; pick < Math.min(firstPick + pageSize, lifting.length); pick++) {
const row = grid.insertRow();
addHeader(row, pick + 1);
for (let shaft = firstShaft; shaft < lastShaft; shaft++) {
const button = document.createElement('button');
button.setAttribute('aria-label', `Pick ${pick + 1}, shaft ${shaft + 1}`);
const update = () => {
button.setAttribute('aria-pressed', Boolean(lifting[pick][shaft]));
button.textContent = lifting[pick][shaft] ? '■' : '□';
};
button.onclick = () => {
const updated=lifting.map((row,index)=>index===pick ? [...row] : row);
updated[pick][shaft] ^= 1;
commitPeg(updated);
update();
};
update();
row.insertCell().append(button);
}
}
}
window.addEventListener('cad:document', event => { state = event.detail; });
function openPeg(asNumeric) {
if (!state || state.raster || state.indexed) throw Error('Open editable yarn CAD first.');
lifting = readPegPlan(state.project).lifting;
revision = state.revision;
get('pegStatus').textContent = '';
get('pegCount').value = lifting.length;
get('pegRangeTools').open = false;
get('pegFirst').value = get('pegLast').value = 1;
get('pegDestination').value = lifting.length + 1;
get('pegPickPage').value = get('pegShaftPage').value = 1;
numeric = asNumeric;
dialog.querySelector('h2').textContent = numeric ? 'Numeric Peg' : 'Peg Plan';
for (const child of dialog.querySelectorAll(':scope > .row, :scope > table, #pegRangeTools')) child.hidden = numeric;
get('numericPegEntry').hidden = !numeric;
if (numeric) get('numericPegText').value = lifting.map(row =>
row.flatMap((value,index) => value ? [index+1] : []).join('.') || '-').join('\n');
draw();
dialog.showModal();
}
window.addEventListener('cad:peg-plan', () => openPeg(false));
window.addEventListener('cad:peg-numeric', () => openPeg(true));
get('pegPickPage').onchange = get('pegShaftPage').onchange = draw;
get('pegResize').onclick = () => {
try {
commitPeg(resizePegPicks(lifting, Number(get('pegCount').value)), true);
} catch (error) {
get('pegStatus').textContent = error.message;
}
};
get('pegMirror').onclick = () => commitPeg([...lifting].reverse(), true);
function editPickRange(operation) {
try {
commitPeg(splicePegPicks(lifting, operation, Number(get('pegFirst').value),
Number(get('pegLast').value), Number(get('pegDestination').value)), true);
} catch (error) {
get('pegStatus').textContent = error.message;
}
}
get('pegDelete').onclick = () => editPickRange('delete');
get('pegDuplicate').onclick = () => editPickRange('duplicate');
get('pegClose').onclick = () => dialog.close();
function commitPeg(updated, redraw=false) {
try {
if (state.revision !== revision || state.raster) throw Error('Design changed. Reopen Peg Plan to edit the current design.');
if (JSON.stringify(updated) === JSON.stringify(lifting)) {
get('pegStatus').textContent='';
return;
}
const project = applyPegPlan(state.project, updated);
pending = {id:++request,redraw};
emit('cad:edit', { id: pending.id, type: 'replace-project', revision, project });
} catch (error) {
get('pegStatus').textContent = error.message;
}
}
const livePeg=createLiveEdit(()=>{
if(!dialog.open||!numeric)return;
try {commitPeg(parseNumericPeg(get('numericPegText').value,lifting[0].length));}
catch(error){get('pegStatus').textContent=error.message;}
});
get('numericPegText').addEventListener('input',livePeg.schedule);
get('numericPegText').addEventListener('change',livePeg.flush);
get('pegClose').addEventListener('click',livePeg.flush,true);
dialog.addEventListener('close',livePeg.cancel);
window.addEventListener('cad:edit-result', event => {
if (event.detail.id !== pending?.id) return;
const {redraw}=pending;
pending=undefined;
if (event.detail.ok) {
revision=state.revision;
lifting=readPegPlan(state.project).lifting;
get('pegCount').value=lifting.length;
get('pegStatus').textContent='';
if(redraw)draw();
} else get('pegStatus').textContent=event.detail.error;
});
emit('cad:request-state');