SOURCE / PINNED RELEASE
Made of little things.
Nappakura
- Release
- a75ca0f8b596…
- Author-recorded commit
- 4463126213fa…
- License
- LICENSE
- Author’s source reference
- nostr://npub182jczunncwe0jn6frpqwq3e0qjws7yqqnc3auccqv9nte2dnd63scjm4rf/wss%3A%2F%2Fgit.napplet.soy%2F/n-8db03001b62
Archive hash verified: b448d77b767ae754…. The source-to-build association is the author’s claim; it has not been independently rebuilt.
import './styles.css';
import { DocumentCommands } from './commands.js';
import type { Arguments } from './commands.js';
import { installAgentTools } from './agent-tools.js';
import { ModellingUI } from './modelling-ui.js';
import { storage, config } from '@napplet/sdk';
import { runtimeHasDomain } from './domain-availability.js';
import { polygonCount, polygonEdges, demoMesh, parseModel } from './mesh.js';
import type { V3 } from './mesh.js';
import {
newPattern,
toggleSeam,
pack,
printIssues,
pageCount,
paperSize,
pieceBounds,
} from './unfold.js';
import type { PrintSettings } from './unfold.js';
import { Views } from './views.js';
import type { Selection, Mode } from './views.js';
import { serialize, deserialize } from './project.js';
import type { Document } from './project.js';
import { importFile, exportFile } from './files.js';
import { createPDF } from './pdf.js';
import { setupPreferences } from './napplet-settings.js';
// App-owned drafting colors; host theme is deliberately optional and unused.
const FOLLOW_HOST_THEME = false;
void FOLLOW_HOST_THEME;
const $ = <T extends HTMLElement = HTMLElement>(id: string) => document.getElementById(id) as T;
const input = (id: string) => $<HTMLInputElement>(id);
const button = (id: string) => $<HTMLButtonElement>(id);
const select = (id: string) => $<HTMLSelectElement>(id);
const mesh = demoMesh();
let doc: Document = { mesh, pattern: newPattern(mesh) };
let selection: Selection = { face: 0, edge: polygonEdges(mesh, 0)[0], piece: 0 };
let mode: Mode = 'select',
page = 0,
preview = false,
wire = true,
busy = false,
moveSnapshot = '';
let issueList: string[] = [];
const commands = new DocumentCommands(
() => doc,
(value) => (doc = value),
() => busy || !!moveSnapshot || !!modeller?.transforming,
() => agentAccess?.reset(),
);
const { undoStack, redoStack } = commands;
let modeller: ModellingUI | undefined;
let agentAccess: { reset: () => void } | undefined;
const hasFiles = runtimeHasDomain('fs'),
hasStorage = runtimeHasDomain('storage'),
hasConfig = runtimeHasDomain('config');
const views = new Views(
$('modelCanvas'),
$('paperCanvas'),
() => ({
...doc,
selection,
mode,
page,
preview,
wire,
modelling: modeller?.highlights(),
gizmo: modeller?.gizmo(),
previewMesh: modeller?.previewMesh,
}),
{
select: (face, edge, vertex = -1, additive = false) => {
if (mode === 'select') {
try {
modeller?.pick(face, edge, vertex, additive);
} catch (error) {
status(errorMessage(error), true);
}
}
selection.face = face;
selection.edge = edge >= 0 ? edge : polygonEdges(doc.mesh, face)[0];
selection.piece =
doc.pattern.pieces.find((p) => p.faces.some((f) => f.face === face))?.id ?? 0;
page = doc.pattern.pieces[selection.piece].page;
if (!preview && mode === 'seam' && edge >= 0) editSeam();
else if (!preview && mode === 'tab' && edge >= 0) editTab();
else {
status(
`Polygon ${[...new Set(doc.mesh.facePolygons)].indexOf(doc.mesh.facePolygons[face]) + 1} · Piece ${selection.piece + 1}${edge >= 0 ? ` · Edge ${edge + 1}` : ''}`,
);
render();
}
},
transformStart: () => modeller?.startTransform() ?? false,
transformPreview: (values) => modeller?.previewTransform(values),
transformEnd: (commit) => modeller?.endTransform(commit),
startMove: () => {
moveSnapshot = serialize(doc);
},
move: (piece, dx, dy) => {
const p = doc.pattern.pieces[piece];
p.x += dx;
p.y += dy;
},
endMove: () => {
if (moveSnapshot) {
pushUndo(moveSnapshot);
moveSnapshot = '';
refreshDocument();
status('Piece moved. Use Undo to restore its position.');
}
},
},
);
function status(message: string, error = false) {
$('status').textContent = message;
$('status').style.color = error ? '#a14425' : '';
}
function errorMessage(error: unknown) {
return error instanceof Error
? error.message
: typeof error === 'object' && error && 'message' in error
? String(error.message)
: String(error);
}
function pushUndo(snapshot: string) {
commands.record(snapshot);
}
function runCommand(name: string, args: Arguments = {}, manualHistory = false) {
try {
const result = commands.run(name, args, manualHistory);
refreshDocument();
status(name.replaceAll('_', ' ') + ': done.');
return result;
} catch (error) {
refreshDocument();
status(errorMessage(error), true);
throw error;
}
}
function mutate(action: () => void, message: string) {
try {
commands.change(action);
refreshDocument();
status(message);
} catch (error) {
refreshDocument();
status(errorMessage(error), true);
}
}
function refreshDocument() {
selection.face = Math.min(selection.face, doc.mesh.faces.length - 1);
selection.edge = Math.min(selection.edge, doc.mesh.edges.length - 1);
selection.piece =
doc.pattern.pieces.find((p) => p.faces.some((f) => f.face === selection.face))?.id ?? 0;
page = Math.max(0, Math.min(page, pageCount(doc.pattern) - 1));
issueList = printIssues(doc.mesh, doc.pattern);
render();
}
function render() {
modeller?.update();
const { mesh, pattern } = doc,
s = pattern.settings,
piece = pattern.pieces[selection.piece],
edge = mesh.edges[selection.edge];
$('modelName').textContent = mesh.name;
$('modelStats').textContent = `${polygonCount(mesh)} polygons · ${mesh.vertices.length} vertices`;
$('pieceCount').textContent =
`${pattern.pieces.length} piece${pattern.pieces.length === 1 ? '' : 's'} · ${pageCount(pattern)} sheet${pageCount(pattern) === 1 ? '' : 's'}`;
$('pageLabel').textContent = `Sheet ${page + 1} / ${pageCount(pattern)}`;
const paper = paperSize(s);
$('paperBadge').textContent = `${s.paper === 'a4' ? 'A4' : 'LETTER'} · ${paper[0]} × ${paper[1]}`;
const pieceOptions = pattern.pieces
.map(
(p) =>
`${p.id}:${polygonCount(
mesh,
p.faces.map((f) => f.face),
)}`,
)
.join(',');
if (select('pieceSelect').dataset.options !== pieceOptions) {
select('pieceSelect').replaceChildren(
...pattern.pieces.map(
(p) =>
new Option(
`Piece ${p.id + 1} · ${polygonCount(
mesh,
p.faces.map((f) => f.face),
)} polygons`,
String(p.id),
),
),
);
select('pieceSelect').dataset.options = pieceOptions;
}
select('pieceSelect').value = String(selection.piece);
// Edge options are limited to the selected face for practical keyboard navigation.
select('edgeSelect').replaceChildren(
...polygonEdges(mesh, selection.face).map(
(id) =>
new Option(
`Edge ${id + 1} · ${pattern.joined.includes(id) ? 'joined' : mesh.edges[id].faces.length === 2 ? 'cut' : 'open'}`,
String(id),
),
),
);
select('edgeSelect').value = String(selection.edge);
input('faceSelect').max = String(polygonCount(mesh));
input('faceSelect').value = String(
[...new Set(mesh.facePolygons)].indexOf(mesh.facePolygons[selection.face]) + 1,
);
input('piecePage').value = String(piece.page + 1);
input('pieceX').value = piece.x.toFixed(1);
input('pieceY').value = piece.y.toFixed(1);
input('pieceRotation').value = String(Math.round(piece.rotation));
const fields: Record<string, number> = {
modelSize: s.size,
margin: s.margin,
tabDepth: s.tabDepth,
tabTaper: s.tabTaper,
lineWidth: s.lineWidth,
labelSize: s.labelSize,
};
for (const [id, value] of Object.entries(fields)) input(id).value = String(value);
select('paperSize').value = s.paper;
input('landscape').checked = s.landscape;
input('labels').checked = s.labels;
input('tabs').checked = s.tabs;
document.querySelectorAll<HTMLButtonElement>('[data-mode]').forEach((b) => {
b.setAttribute('aria-pressed', String(b.dataset.mode === mode));
});
button('preview').setAttribute('aria-pressed', String(preview));
button('wire').setAttribute('aria-pressed', String(wire));
button('seamToggle').textContent = pattern.joined.includes(selection.edge)
? 'Cut edge'
: 'Join edge';
button('tabHide').textContent = pattern.hiddenTabs.includes(selection.edge)
? 'Show tab'
: 'Hide tab';
document
.querySelectorAll<HTMLButtonElement | HTMLInputElement | HTMLSelectElement>(
'.editor button,.editor input,.editor select',
)
.forEach((el) => (el.disabled = busy));
button('import').disabled = busy || !hasFiles;
button('projectSave').disabled = busy || !hasFiles;
button('export').disabled = busy || !hasFiles || issueList.length > 0;
button('draftSave').disabled = busy || !hasStorage;
button('draftLoad').disabled = busy || !hasStorage;
button('settings').disabled = busy || !hasConfig;
button('undo').disabled = busy || !undoStack.length;
button('redo').disabled = busy || !redoStack.length;
button('pagePrev').disabled = busy || page <= 0;
button('pageNext').disabled = busy || page >= pageCount(pattern) - 1;
button('seamToggle').disabled = busy || edge?.faces.length !== 2;
for (const id of ['tabFlip', 'tabHide'])
button(id).disabled =
busy || edge?.faces.length !== 2 || pattern.joined.includes(selection.edge);
$('capabilities').textContent =
`Files: ${hasFiles ? 'host connected' : 'unavailable in this host'}. Draft storage: ${hasStorage ? 'connected' : 'unavailable'}. ${!hasFiles ? 'The example remains editable; open this napplet in a host with file support to import or export.' : 'Exported files appear in the host’s file panel for download.'}`;
const warnings = [...issueList, ...mesh.warnings];
$('issues').textContent = warnings.join(' ');
$('issues').hidden = !warnings.length;
$('app').setAttribute('aria-busy', String(busy));
views.draw();
}
function chooseFace(face: number) {
if (face < 0 || face >= doc.mesh.faces.length) return;
selection.face = face;
selection.edge = polygonEdges(doc.mesh, face)[0];
selection.piece = doc.pattern.pieces.find((p) => p.faces.some((f) => f.face === face))!.id;
page = doc.pattern.pieces[selection.piece].page;
render();
}
function editSeam() {
mutate(
() => toggleSeam(doc.mesh, doc.pattern, selection.edge),
'Seam updated and pieces rearranged.',
);
}
function editTab() {
mutate(() => {
const id = selection.edge,
e = doc.mesh.edges[id];
if (e.faces.length !== 2 || doc.pattern.joined.includes(id))
throw new Error('Select a cut edge with two matching faces to switch its tab.');
const a = doc.pattern.flipped,
index = a.indexOf(id);
if (index < 0) a.push(id);
else a.splice(index, 1);
}, 'Tab moved to the matching edge.');
}
function on(id: string, action: () => void) {
button(id).addEventListener('click', action);
}
async function fileAction(action: () => Promise<string>) {
if (busy) return;
busy = true;
render();
status('Waiting for the host…');
try {
status(await action());
} catch (error) {
status(errorMessage(error), true);
} finally {
busy = false;
refreshDocument();
}
}
function replaceDocument(next: Document) {
pushUndo(serialize(doc));
commands.resetContext();
doc = next;
selection = { face: 0, edge: polygonEdges(doc.mesh, 0)[0], piece: 0 };
page = 0;
views.fit();
}
const filename = (extension: string) =>
`${
doc.mesh.name
.replace(/\.[^.]+$/, '')
.replace(/[^a-zA-Z0-9_-]/g, '-')
.slice(0, 70) || 'pattern'
}.${extension}`;
on(
'import',
() =>
void fileAction(async () => {
const file = await importFile();
const next = file.name.toLowerCase().endsWith('.nappakura')
? deserialize(new TextDecoder().decode(file.bytes))
: (() => {
const mesh = parseModel(file.bytes, file.name);
return { mesh, pattern: newPattern(mesh) };
})();
replaceDocument(next);
return 'Opened and unfolded. Check the intended finished size in Tools.';
}),
);
on(
'projectSave',
() =>
void fileAction(async () => {
await exportFile(new TextEncoder().encode(serialize(doc)), filename('nappakura'));
return 'Project ready. Download it from the host’s file panel.';
}),
);
on(
'export',
() =>
void fileAction(async () => {
const bytes = createPDF(doc.mesh, doc.pattern);
await exportFile(bytes, filename('pdf'));
return 'PDF ready. Use the shell’s Download button, then print at 100% / Actual size.';
}),
);
on(
'draftSave',
() =>
void fileAction(async () => {
const text = serialize(doc);
if (new TextEncoder().encode(text).length > 450000)
throw new Error('This project is too large for draft storage. Use Save project instead.');
await storage.setItem('nappakura-draft-v1', text);
return 'Draft saved in this host.';
}),
);
on(
'draftLoad',
() =>
void fileAction(async () => {
const text = await storage.getItem('nappakura-draft-v1');
if (!text) throw new Error('No saved draft yet. Use Save draft first.');
replaceDocument(deserialize(text));
return 'Saved draft restored.';
}),
);
on(
'settings',
() =>
void fileAction(async () => {
config.openSettings();
return 'Preferences opened in the host.';
}),
);
on('example', () => {
if (busy || moveSnapshot) return;
const mesh = demoMesh();
replaceDocument({ mesh, pattern: newPattern(mesh) });
refreshDocument();
status('Example loaded. Undo restores the previous document.');
});
on('undo', () => {
try {
runCommand('undo', { expectedRevision: commands.revision }, true);
} catch {
/* Reported above. */
}
});
on('redo', () => {
try {
runCommand('redo', { expectedRevision: commands.revision }, true);
} catch {
/* Reported above. */
}
});
on('unfold', () =>
mutate(() => {
doc.pattern = newPattern(doc.mesh, { ...doc.pattern.settings });
page = 0;
}, 'New automatic unfolding. Undo restores your seam and layout edits.'),
);
on('arrange', () =>
mutate(() => pack(doc.mesh, doc.pattern), 'Pieces arranged without changing model scale.'),
);
on('seamToggle', editSeam);
on('tabFlip', editTab);
on('tabHide', () =>
mutate(() => {
const a = doc.pattern.hiddenTabs,
i = a.indexOf(selection.edge);
if (i < 0) a.push(selection.edge);
else a.splice(i, 1);
}, 'Tab visibility updated.'),
);
on('rotate', () =>
mutate(() => {
const piece = doc.pattern.pieces[selection.piece],
before = pieceBounds(doc.mesh, doc.pattern, piece);
piece.rotation = (piece.rotation + 90) % 360;
const after = pieceBounds(doc.mesh, doc.pattern, piece);
piece.x += before.minX - after.minX;
piece.y += before.minY - after.minY;
}, 'Piece rotated 90°.'),
);
on('addPage', () =>
mutate(() => {
if (pageCount(doc.pattern) >= 64) throw new Error('This version supports up to 64 sheets.');
page = pageCount(doc.pattern);
doc.pattern.pieces[selection.piece].page = page;
}, 'Selected piece moved to a new sheet.'),
);
on('flipNormals', () =>
mutate(() => {
doc.mesh.inverted = !doc.mesh.inverted;
doc.mesh.normals = doc.mesh.normals.map((n) => n.map((v) => -v) as V3);
}, 'Surface normals reversed. Mountain and valley folds are swapped.'),
);
on('turnModel', () =>
mutate(() => {
if (doc.editable)
doc.editable.vertices.forEach((v) => {
const [x, y, z] = v.point;
v.point = [x, -z, y];
});
doc.mesh.vertices = doc.mesh.vertices.map(([x, y, z]) => [x, -z, y] as V3);
doc.mesh.normals = doc.mesh.normals.map(([x, y, z]) => [x, -z, y] as V3);
const [dx, dy, dz] = doc.mesh.dimensions;
doc.mesh.dimensions = [dx, dz, dy];
}, 'Model turned 90° around X. Print dimensions are unchanged.'),
);
on('preview', () => {
preview = !preview;
status(
preview
? 'Print preview: selection colors hidden. Print the exported PDF at actual size.'
: 'Editing view.',
);
render();
});
on('wire', () => {
wire = !wire;
render();
});
on('pagePrev', () => {
page--;
render();
});
on('pageNext', () => {
page++;
render();
});
on('help', () => $<HTMLDialogElement>('helpDialog').showModal());
on('modelFit', () => views.fit('model'));
on('paperFit', () => views.fit('paper'));
on('modelPlus', () => views.zoom('model', 1.25));
on('modelMinus', () => views.zoom('model', 0.8));
on('paperPlus', () => views.zoom('paper', 1.25));
on('paperMinus', () => views.zoom('paper', 0.8));
on('orbitLeft', () => views.orbit(-0.3, 0));
on('orbitRight', () => views.orbit(0.3, 0));
on('orbitUp', () => views.orbit(0, -0.25));
on('orbitDown', () => views.orbit(0, 0.25));
select('pieceSelect').addEventListener('change', () =>
chooseFace(doc.pattern.pieces[Number(select('pieceSelect').value)].faces[0].face),
);
select('edgeSelect').addEventListener('change', () => {
selection.edge = Number(select('edgeSelect').value);
render();
});
input('faceSelect').addEventListener('change', () => {
if (input('faceSelect').checkValidity())
chooseFace(
doc.mesh.facePolygons.indexOf(
[...new Set(doc.mesh.facePolygons)][Number(input('faceSelect').value) - 1],
),
);
else render();
});
for (const [id, key] of [
['pieceX', 'x'],
['pieceY', 'y'],
['pieceRotation', 'rotation'],
['piecePage', 'page'],
] as const)
input(id).addEventListener('change', () => {
const el = input(id);
if (!el.checkValidity() || !el.value) return render();
const n = Number(el.value);
if (!Number.isFinite(n) || Math.abs(n) > 10000) return render();
mutate(() => {
doc.pattern.pieces[selection.piece][key] = key === 'page' ? Math.round(n) - 1 : n;
if (key === 'page') page = Math.round(n) - 1;
}, 'Piece placement updated.');
});
for (const [id, key] of [
['modelSize', 'size'],
['margin', 'margin'],
['tabDepth', 'tabDepth'],
['tabTaper', 'tabTaper'],
['lineWidth', 'lineWidth'],
['labelSize', 'labelSize'],
] as const)
input(id).addEventListener('change', () => {
const el = input(id);
if (!el.value || !el.checkValidity()) {
status('Enter a value within the shown limits.', true);
return render();
}
const value = Number(el.value);
mutate(() => {
if (key === 'size' && doc.editable) {
const factor = value / doc.pattern.settings.size;
doc.editable.vertices.forEach((v) => (v.point = v.point.map((n) => n * factor) as V3));
}
doc.pattern.settings[key] = value;
if (key === 'size' || key === 'margin') pack(doc.mesh, doc.pattern);
}, 'Drawing dimensions updated.');
});
select('paperSize').addEventListener('change', () => {
const value = select('paperSize').value as PrintSettings['paper'];
mutate(() => {
doc.pattern.settings.paper = value;
pack(doc.mesh, doc.pattern);
page = 0;
views.fit('paper');
}, 'Paper size updated.');
});
for (const key of ['landscape', 'labels', 'tabs'] as const)
input(key).addEventListener('change', () => {
const value = input(key).checked;
mutate(() => {
doc.pattern.settings[key] = value;
if (key === 'landscape') pack(doc.mesh, doc.pattern);
}, 'Drawing options updated.');
});
document.querySelectorAll<HTMLButtonElement>('[data-mode]').forEach((b) =>
b.addEventListener('click', () => {
mode = b.dataset.mode as Mode;
preview = false;
status(
mode === 'seam'
? 'Click a shared edge to cut or join. This rearranges the pattern.'
: mode === 'tab'
? 'Click a cut edge to switch its glue tab to the other face.'
: 'Drag pieces to arrange. Drag empty paper to pan.',
);
render();
}),
);
function syncViewButtons() {
const view = $('app').dataset.view;
const active = view === 'split' && innerWidth <= 650 ? 'model' : view;
document
.querySelectorAll<HTMLButtonElement>('.view-switch [data-view]')
.forEach((b) => b.setAttribute('aria-pressed', String(b.dataset.view === active)));
}
document.querySelectorAll<HTMLButtonElement>('.view-switch [data-view]').forEach((b) =>
b.addEventListener('click', () => {
$('app').dataset.view = b.dataset.view;
syncViewButtons();
views.draw();
}),
);
window.addEventListener('resize', syncViewButtons);
syncViewButtons();
setupPreferences((values) => {
wire = values.showMeshEdges !== false;
render();
});
window.addEventListener('pagehide', () => views.dispose(), { once: true });
modeller = new ModellingUI(
commands,
(name, args) => {
try {
runCommand(name, { ...args, expectedRevision: commands.revision });
} catch {
/* Visible error already reported. */
}
},
render,
);
agentAccess = installAgentTools(
runCommand,
async (args, signal) => {
if (busy || moveSnapshot) throw new Error('Finish the current file operation or drag first.');
if (args.expectedRevision !== commands.revision)
throw new Error(`Stale document: inspect revision ${commands.revision} before exporting.`);
if (signal.aborted) throw new Error('Export cancelled.');
busy = true;
render();
try {
const bytes = createPDF(doc.mesh, doc.pattern),
name = filename('pdf');
await exportFile(bytes, name, signal);
status('PDF ready. Use the shell’s Download button, then print at Actual size.');
return {
revision: commands.revision,
name,
mime: 'application/pdf',
bytes: bytes.length,
sheets: pageCount(doc.pattern),
status: 'ready-in-host-file-panel',
};
} finally {
busy = false;
refreshDocument();
}
},
hasFiles,
status,
);
refreshDocument();
status('Explore the gem, or open an OBJ / STL to begin.');
