demo D217
A type of your own
A part number, AB-1234-X, in five functions: matches, parse, format, compare
dataTypes: { partNumber: { base, matches, parse, format, compare } }
Loading a live grid…
The configuration
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@toclocoinc/lattice-grid@1.13.0/lattice-grid.min.css">
<script src="https://cdn.jsdelivr.net/npm/@toclocoinc/lattice-grid@1.13.0/lattice-grid.min.js"></script>
<div id="grid" style="height: 480px"></div>
<script>
// A part number, AB-1234-X: a family, a serial and a revision. A type is five
// functions; this defines all five, then registers it under one name.
const PART = /^\s*([A-Za-z]{2})[-\s]?(\d{1,4})[-\s]?([A-Za-z])\s*$/;
const read = (v) => {
const m = PART.exec(String(v ?? ''));
return m ? { family: m[1].toUpperCase(), serial: +m[2], rev: m[3].toUpperCase() } : null;
};
const canonical = (v) => {
const p = read(v);
return p ? `${p.family}-${String(p.serial).padStart(4, '0')}-${p.rev}` : null;
};
const partNumber = {
base: 'text',
matches: (v) => read(v) != null, // claim the value when inferring
parse: ({ text }) => canonical(text) ?? text, // ab12x -> AB-0012-X
format: ({ value }) => canonical(value) ?? String(value ?? ''),
compare: (a, b) => { // sort on the serial as a number
const x = read(a), y = read(b);
if (!x || !y) return x ? -1 : y ? 1 : 0;
return x.family.localeCompare(y.family) || x.serial - y.serial || x.rev.localeCompare(y.rev);
},
};
const grid = LatticeGrid.createGrid(document.getElementById('grid'), {
rowKey: 'id',
dataTypes: { partNumber }, // registered in one line
columns: [
{ field: 'part', title: 'Part number', type: 'partNumber', editor: 'text', layout: { width: 160, pin: 'start' } },
{ field: 'description', title: 'Description', layout: { width: 240 } },
{ field: 'qty', title: 'On hand', type: 'number', total: 'sum' },
{ field: 'price', title: 'Unit price', type: 'number',
format: { style: 'currency', currency: 'GBP' }, total: 'mean' },
],
rows, // e.g. [{ id: 1, part: 'AB-1000-A', description: 'Bracket', qty: 240, price: 3.75 }, …]
state: { sort: [{ col: 'part', dir: 'asc' }] },
});
</script>