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 type { GizmoState, TransformMode } from './gizmo.js';
import { cross, sub, length } from './mesh.js';
import type { Mesh, V3 } from './mesh.js';
import { deriveSolid, edgeKey, selectionVertices, transform } from './modelling.js';
import type { ElementKind, Solid } from './modelling.js';
import type { DocumentCommands, Arguments } from './commands.js';
import { toolDefinitions } from './tool-definitions.js';
export class ModellingUI {
kind: ElementKind = 'polygon';
gizmoMode: TransformMode | 'off' = 'move';
previewMesh?: Mesh;
private gesture?: {
solid: Solid;
kind: ElementKind;
ids: string[];
operation: TransformMode;
revision: number;
values?: V3;
valid: boolean;
};
get transforming() {
return !!this.gesture;
}
gizmo(): GizmoState | undefined {
if (this.gizmoMode === 'off' || !this.ids.length) return;
try {
const s = this.commands.solid(),
d = deriveSolid(s),
selected = selectionVertices(s, this.kind, this.ids);
const vs = d.vertexIds.flatMap((id, i) =>
selected.includes(id) ? [d.mesh.vertices[i]] : [],
);
const center = [0, 1, 2].map(
(axis) => vs.reduce((sum, v) => sum + v[axis], 0) / vs.length,
) as V3;
return { center, operation: this.gizmoMode, size: d.size };
} catch {
return;
}
}
startTransform() {
if (this.gizmoMode === 'off' || !this.ids.length || this.commands.busy()) return false;
this.gesture = {
solid: structuredClone(this.commands.solid()),
kind: this.kind,
ids: [...this.ids],
operation: this.gizmoMode,
revision: this.commands.revision,
valid: false,
};
return true;
}
previewTransform(values: V3) {
const g = this.gesture;
if (!g) return;
g.values = values;
g.valid = false;
const issue = this.root.querySelector<HTMLElement>('#modellingIssue')!;
try {
const copy = structuredClone(g.solid);
transform(copy, g.kind, g.ids, g.operation, values);
deriveSolid(copy); // Same planar/topology validation as a committed toolbar edit.
const original = deriveSolid(g.solid),
byId = new Map(copy.vertices.map((v) => [v.id, v.point]));
const used = g.solid.vertices.filter((v) => original.vertexIds.includes(v.id));
const center = [0, 1, 2].map(
(axis) =>
(Math.min(...used.map((v) => v.point[axis])) +
Math.max(...used.map((v) => v.point[axis]))) /
2,
);
const vertices = original.vertexIds.map(
(id) => byId.get(id)!.map((n, i) => (n - center[i]) / original.size) as V3,
);
this.previewMesh = {
...original.mesh,
vertices,
normals: original.mesh.faces.map((f) => {
const n = cross(sub(vertices[f[1]], vertices[f[0]]), sub(vertices[f[2]], vertices[f[0]]));
return n.map((v) => v / length(n)) as V3;
}),
};
g.valid = true;
issue.textContent = `${g.operation}: ${values.map((v) => +v.toFixed(2)).join(', ')} ${g.operation === 'move' ? 'mm' : g.operation === 'rotate' ? '°' : '×'} · Release to apply; Escape cancels.`;
} catch (error) {
this.previewMesh = undefined;
issue.textContent = (error as Error).message;
}
}
endTransform(commit: boolean) {
const g = this.gesture;
this.gesture = undefined;
this.previewMesh = undefined;
if (commit && g?.values) {
if (!g.valid) {
this.redraw();
this.root.querySelector<HTMLElement>('#modellingIssue')!.textContent =
'Edit cancelled: it would warp or collapse a polygon. Split the affected face first.';
return;
}
if (g.revision !== this.commands.revision) {
this.redraw();
return;
}
if (g.values.some((v) => Math.abs(v - (g.operation === 'scale' ? 1 : 0)) > 1e-8))
this.run('transform_geometry', {
kind: g.kind,
ids: g.ids,
operation: g.operation,
values: g.values,
});
}
this.redraw();
}
ids: string[] = [];
private root: HTMLElement;
private fields: HTMLElement;
private operation = 'extrude_faces';
private toolButtons: HTMLButtonElement[] = [];
private elements: HTMLSelectElement;
private fingerprint = '';
constructor(
private commands: DocumentCommands,
private run: (name: string, args: Arguments) => void,
private redraw: () => void,
) {
this.root = document.createElement('section');
this.root.className = 'inspector-section modeller';
this.root.innerHTML = `<h2>Shape the model <span id="modelRevision" class="badge"></span></h2>
<label for="modelElements">Selected elements <span>Ctrl / ⌘ for multiple</span></label><select id="modelElements" multiple size="3"></select>
<h3 id="modelOperationTitle">Extrude</h3><div id="modelFields"></div>
<button id="modelApply" class="primary">Apply to model</button><p class="hint" id="modellingIssue" role="status"></p><p class="hint">Geometry edits rebuild seams and layout. Undo restores both. Distances in mm.</p>`;
document.querySelector('.inspector')!.prepend(this.root);
this.fields = this.root.querySelector('#modelFields')!;
this.elements = this.root.querySelector('#modelElements')!;
const names = [
'create_primitive',
'transform_geometry',
'extrude_faces',
'inset_face',
'split_edge',
'collapse_edge',
'weld_vertices',
'delete_faces',
'fill_boundary',
];
const tools = document.createElement('div');
tools.className = 'model-toolbar modelling-tools';
tools.setAttribute('role', 'toolbar');
tools.setAttribute('aria-label', 'Modelling tools');
const labels = [
'+ Primitive',
'↔ Transform',
'⇧ Extrude',
'▣ Inset',
'⋈ Split edge',
'⇥ Collapse',
'⊕ Weld',
'− Delete',
'▰ Fill',
];
this.toolButtons = names.map((name, i) => {
const b = document.createElement('button');
b.type = 'button';
b.dataset.operation = name;
const [symbol, ...words] = labels[i].split(' ');
const icon = document.createElement('span');
icon.setAttribute('aria-hidden', 'true');
icon.textContent = symbol;
const label = document.createElement('span');
label.className = 'model-tool-name';
label.textContent = ' ' + words.join(' ');
b.append(icon, label);
b.setAttribute('aria-label', labels[i]);
b.title = toolDefinitions.find((t) => t.name === name)!.description;
b.onclick = () => {
this.operation = name;
this.form();
if (innerWidth <= 1100) document.querySelector<HTMLElement>('#app')!.dataset.view = 'tools';
this.root.scrollIntoView({ block: 'nearest' });
this.fields.querySelector<HTMLElement>('input,select')?.focus();
};
tools.append(b);
return b;
});
this.toolButtons.forEach((b, i) => (b.tabIndex = i ? -1 : 0));
tools.addEventListener('focusin', (e) =>
this.toolButtons.forEach((b) => (b.tabIndex = b === e.target ? 0 : -1)),
);
tools.addEventListener('keydown', (e) => {
if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(e.key)) return;
const i = this.toolButtons.indexOf(document.activeElement as HTMLButtonElement),
n = this.toolButtons.length;
e.preventDefault();
this.toolButtons[
e.key === 'Home'
? 0
: e.key === 'End'
? n - 1
: (i + (e.key === 'ArrowRight' ? 1 : -1) + n) % n
].focus();
});
const compactTouch = matchMedia('(max-width: 650px) and (pointer: coarse)');
const placeTools = () => {
if (compactTouch.matches) this.root.querySelector('#modelOperationTitle')!.before(tools);
else document.querySelector('.model-pane .canvas-wrap')!.before(tools);
};
placeTools();
compactTouch.addEventListener('change', placeTools);
this.elements.onchange = () => {
this.ids = [...this.elements.selectedOptions].map((o) => o.value);
this.redraw();
};
this.root.querySelector('#modelApply')!.addEventListener('click', () => {
const args: Arguments = {};
for (const el of this.fields.querySelectorAll<HTMLInputElement | HTMLSelectElement>(
'[data-arg]',
)) {
if (!el.value.trim()) continue;
args[el.dataset.arg!] =
el.dataset.type === 'number'
? Number(el.value)
: el.dataset.type === 'array'
? el.value.split(',').map(Number)
: el.value;
}
const name = this.operation;
if (name === 'transform_geometry')
Object.assign(args, { kind: this.kind, ids: [...this.ids] });
if (['extrude_faces', 'delete_faces'].includes(name))
args.polygonIds = this.kind === 'polygon' ? [...this.ids] : [];
if (name === 'inset_face')
args.polygonId = this.kind === 'polygon' && this.ids.length === 1 ? this.ids[0] : '';
if (['split_edge', 'collapse_edge', 'fill_boundary'].includes(name))
args.edgeId = this.kind === 'edge' && this.ids.length === 1 ? this.ids[0] : '';
if (name === 'weld_vertices') args.vertexIds = this.kind === 'vertex' ? [...this.ids] : [];
this.run(name, args);
});
const toolbar = document.createElement('div');
toolbar.className = 'model-toolbar';
toolbar.setAttribute('role', 'toolbar');
toolbar.setAttribute('aria-label', 'Model selection');
toolbar.innerHTML = `<button data-select="vertex">Vertex</button><button data-select="edge">Edge</button><button data-select="polygon">Polygon</button><label><input id="modelMulti" type="checkbox"> Multi</label><button id="modelTools">Model tools ↗</button>`;
document.querySelector('.model-pane .canvas-wrap')!.before(toolbar);
toolbar.querySelectorAll<HTMLButtonElement>('[data-select]').forEach(
(b) =>
(b.onclick = () => {
this.kind = b.dataset.select as ElementKind;
this.ids = [];
this.fingerprint = '';
this.redraw();
}),
);
toolbar.querySelector('#modelTools')!.addEventListener('click', () => {
const app = document.querySelector<HTMLElement>('#app')!;
if (innerWidth <= 1100) app.dataset.view = 'tools';
this.root.scrollIntoView({ block: 'nearest' });
this.fields.querySelector<HTMLElement>('input,select')?.focus();
});
const controls = [...toolbar.querySelectorAll<HTMLElement>('button,input')];
// Native focusgroup is progressive; the fallback preserves a single tab stop.
if ('focusGroup' in HTMLElement.prototype) toolbar.setAttribute('focusgroup', 'toolbar wrap');
else {
controls.forEach((c, i) => (c.tabIndex = i ? -1 : 0));
toolbar.addEventListener('focusin', (e) =>
controls.forEach((c) => (c.tabIndex = c === e.target ? 0 : -1)),
);
toolbar.addEventListener('keydown', (e) => {
if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(e.key)) return;
const at = controls.indexOf(document.activeElement as HTMLElement),
delta = e.key === 'ArrowRight' ? 1 : -1;
const index =
e.key === 'Home'
? 0
: e.key === 'End'
? controls.length - 1
: (at + delta + controls.length) % controls.length;
e.preventDefault();
controls[index].focus();
});
}
const gizmoTools = document.createElement('div');
gizmoTools.className = 'model-toolbar gizmo-tools';
gizmoTools.setAttribute('role', 'group');
gizmoTools.setAttribute('aria-label', 'Transform gizmo');
gizmoTools.innerHTML = '<span>Gizmo</span>';
for (const mode of ['move', 'rotate', 'scale', 'off'] as const) {
const b = document.createElement('button');
b.type = 'button';
b.textContent = mode[0].toUpperCase() + mode.slice(1);
b.dataset.gizmo = mode;
b.setAttribute('aria-pressed', String(mode === this.gizmoMode));
b.onclick = () => {
this.endTransform(false);
this.gizmoMode = mode;
gizmoTools
.querySelectorAll<HTMLButtonElement>('button')
.forEach((button) => button.setAttribute('aria-pressed', String(button === b)));
this.redraw();
};
gizmoTools.append(b);
}
const help = document.createElement('span');
help.className = 'gizmo-hint';
help.textContent = 'Axes: 1D · squares: 2D · rings: rotate · Shift: snap · Esc: cancel';
gizmoTools.append(help);
document.querySelector('.model-pane .canvas-wrap')!.before(gizmoTools);
this.form();
}
private form() {
this.toolButtons.forEach((b) =>
b.setAttribute('aria-pressed', String(b.dataset.operation === this.operation)),
);
this.root.querySelector('#modelOperationTitle')!.textContent = this.toolButtons.find(
(b) => b.dataset.operation === this.operation,
)!.textContent;
this.fields.replaceChildren();
const def = toolDefinitions.find((t) => t.name === this.operation)!;
const hidden = new Set([
'expectedRevision',
'kind',
'ids',
'polygonIds',
'polygonId',
'edgeId',
'vertexIds',
]);
const defaults: Record<string, string> = {
kind: 'box',
sizeMm: '40',
segments: '8',
operation: 'move',
values: '0, 0, 5',
distanceMm: '10',
ratio: '0.7',
fraction: '0.5',
};
for (const [name, raw] of Object.entries(def.inputSchema.properties)) {
if (hidden.has(name) && !(name === 'kind' && def.name === 'create_primitive')) continue;
const p = raw as { type: string; description?: string; enum?: string[] };
const label = document.createElement('label');
label.htmlFor = `model-${name}`;
label.textContent = p.description || name;
const el = p.enum ? document.createElement('select') : document.createElement('input');
el.id = label.htmlFor;
el.dataset.arg = name;
el.dataset.type = p.type === 'integer' ? 'number' : p.type;
if (p.enum) (el as HTMLSelectElement).replaceChildren(...p.enum.map((v) => new Option(v, v)));
else if (p.type === 'number' || p.type === 'integer') {
(el as HTMLInputElement).type = 'number';
(el as HTMLInputElement).step = 'any';
}
el.value = defaults[name] || '';
this.fields.append(label, el);
if (name === 'operation')
el.addEventListener('change', () => {
const values = this.fields.querySelector<HTMLInputElement>('[data-arg=values]');
if (values) values.value = el.value === 'scale' ? '1, 1, 1' : '0, 0, 0';
});
}
}
pick(face: number, edge: number, vertex: number, additive: boolean) {
let d;
try {
d = deriveSolid(this.commands.solid());
} catch {
return;
}
const id =
this.kind === 'polygon'
? d.facePolygons[face]
: this.kind === 'vertex'
? d.vertexIds[vertex]
: edge < 0
? undefined
: edgeKey(d.vertexIds[d.mesh.edges[edge].a], d.vertexIds[d.mesh.edges[edge].b]);
if (!id || (this.kind === 'edge' && !d.edges.some((e) => e.id === id))) return;
const multi =
additive || document.querySelector<HTMLInputElement>('#modelMulti')?.checked === true;
this.ids = multi
? this.ids.includes(id)
? this.ids.filter((i) => i !== id)
: [...this.ids, id]
: [id];
}
highlights() {
try {
const d = deriveSolid(this.commands.solid());
return {
faces:
this.kind === 'polygon'
? d.facePolygons.flatMap((id, i) => (this.ids.includes(id) ? [i] : []))
: [],
edges:
this.kind === 'edge'
? d.mesh.edges
.filter((e) => this.ids.includes(edgeKey(d.vertexIds[e.a], d.vertexIds[e.b])))
.map((e) => e.id)
: [],
vertices:
this.kind === 'vertex'
? d.vertexIds.flatMap((id, i) => (this.ids.includes(id) ? [i] : []))
: [],
vertexMode: this.kind === 'vertex',
};
} catch {
return { faces: [], edges: [], vertices: [], vertexMode: false };
}
}
update() {
const issue = this.root.querySelector<HTMLElement>('#modellingIssue')!;
let s, d;
try {
s = this.commands.solid();
d = deriveSolid(s);
issue.textContent = '';
} catch (error) {
this.elements.replaceChildren();
issue.textContent = `This imported mesh can still be unfolded. Modelling needs repaired topology: ${(error as Error).message}`;
return;
}
const options =
this.kind === 'vertex'
? s.vertices.map((v) => ({
id: v.id,
label: `${v.id} · ${v.point.map((n) => +n.toFixed(1)).join(', ')} mm`,
}))
: this.kind === 'polygon'
? s.polygons.map((p) => ({
id: p.id,
label: `${p.id} · ${p.vertices.length} sides`,
}))
: d.edges.map((e) => ({
id: e.id,
label: `${e.id} · ${e.polygons.length === 1 ? 'open' : 'shared'}`,
}));
this.ids = this.ids.filter((id) => options.some((o) => o.id === id));
const key = this.kind + this.commands.revision;
if (key !== this.fingerprint) {
this.elements.replaceChildren(...options.map((o) => new Option(o.label, o.id)));
this.fingerprint = key;
}
[...this.elements.options].forEach((o) => (o.selected = this.ids.includes(o.value)));
document
.querySelectorAll<HTMLButtonElement>('[data-select]')
.forEach((b) => b.setAttribute('aria-pressed', String(b.dataset.select === this.kind)));
this.root.querySelector('#modelRevision')!.textContent = `r${this.commands.revision}`;
}
}
