Allow arithmetic expressions in inventory number fields

A user can type a calculation into any numeric inventory field (number,
quantity magnitude, calories) and have it evaluated in place — e.g. weigh a
400 g box of nails, enter '400 - 20', and Tab/Enter swaps in 380.  The result
feeds dependent logic like count-by-weight automatically.

- evaluateExpression() (units.js) reuses the scoped mathjs instance, guarded by
  a strict regex so only bare arithmetic (digits, + - * / ( ) and spaces) is
  evaluated; anything with a letter, a plain number, or unparseable input is
  left untouched.  Float noise is rounded off.
- FieldCell evaluates on blur (Tab/click-away) and on Enter: in a numeric field
  the first Enter resolves a pending expression, a second submits the row.
- NUMERIC_TYPES is exported once from units.js and shared by the table and cell
  editors.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
Roland 2026-06-19 15:07:29 -06:00
parent 305c73921e
commit e7c737fe0c
No known key found for this signature in database
GPG key ID: 1BA620CE6C9A4680
5 changed files with 138 additions and 7 deletions

View file

@ -1,6 +1,6 @@
import React from "react";
import {Input, Select} from "semantic-ui-react";
import {ALL_UNITS, UNIT_GROUPS} from "./units";
import {ALL_UNITS, evaluateExpression, NUMERIC_TYPES, UNIT_GROUPS} from "./units";
// Renders the correct editor for a single field/value, wiring up keyboard navigation. The `inputRef` is attached
// to the primary <input> so the parent table can focus the first cell of a new row.
@ -45,13 +45,40 @@ export function FieldCell({field, value, unitValue, onChange, onUnitChange, onEn
}
}, [autoFocus]);
const numeric = NUMERIC_TYPES.includes(field.type);
// Evaluate an arithmetic expression in this field and swap in the result (no-op for a plain number). Routed
// through onChange so dependent logic (e.g. count-by-weight) recomputes from the resolved value.
const resolveExpression = () => {
const evaluated = evaluateExpression(value);
// Compare against the raw value: evaluateExpression returns its input unchanged when there's no expression,
// so a null/undefined backing value (an unfilled item field) compares equal and never spuriously fires.
if (evaluated !== value) {
onChange(evaluated);
return true;
}
return false;
};
const handleKeyDown = (e) => {
if (e.key === 'Enter' && onEnter) {
if (e.key !== 'Enter') {
return;
}
// In a numeric field, the first Enter resolves a pending expression ("400 - 20" -> "380"); a second Enter
// (now a plain number) submits the row as usual.
if (numeric && resolveExpression()) {
e.preventDefault();
return;
}
if (onEnter) {
e.preventDefault();
onEnter();
}
};
// Numeric fields accept arithmetic, so they are text inputs that evaluate on blur (Tab/click-away) and Enter.
const onBlur = numeric ? resolveExpression : undefined;
const common = {
value: value ?? '',
onChange: (e, data) => onChange(data ? data.value : e.target.value),
@ -81,20 +108,23 @@ export function FieldCell({field, value, unitValue, onChange, onUnitChange, onEn
}
if (field.type === 'number' || field.type === 'calories') {
// `calories` is a number (kcal per unit) that the Summary's ration estimate detects by type.
return <Input {...common} type='number' fluid ref={setRef}/>;
// `calories` is a number (kcal per unit) that the Summary's ration estimate detects by type. Text (not
// number) input so arithmetic expressions can be typed; evaluated on blur/Enter.
return <Input {...common} type='text' inputMode='decimal' fluid ref={setRef} onBlur={onBlur}/>;
}
if (field.type === 'quantity') {
const unitOptions = ALL_UNITS.map(u => ({key: u, value: u, text: u}));
return <Input
type='number'
type='text'
inputMode='decimal'
fluid
ref={setRef}
name={field.key}
value={value ?? ''}
onChange={(e) => onChange(e.target.value)}
onKeyDown={handleKeyDown}
onBlur={onBlur}
aria-label={field.label}
label={<Select
compact

View file

@ -3,10 +3,10 @@ import {Checkbox, TableBody, TableCell, TableFooter, TableHeader, TableHeaderCel
import {Button, Icon, Table} from "../Theme";
import {FieldCell} from "./FieldCell";
import {applyComputedCounts, computedCountConfigs} from "./computeFields";
import {NUMERIC_TYPES} from "./units";
const LOCATION_LIST_ID = 'inventory-location-suggestions';
const CATALOG_LIST_ID = 'inventory-catalog-names';
const NUMERIC_TYPES = ['number', 'quantity', 'calories'];
// Fields copied from a catalog entry onto the new-item row when its name matches a catalog entry.
const CATALOG_KEYS = ['name', 'category', 'subcategory', 'item_size', 'item_size_unit', 'calories'];

View file

@ -124,6 +124,48 @@ describe('InventoryTable count by weight', () => {
expect(within(row).getByLabelText('Count').value).toBe('');
});
test('a math expression in a weight evaluates on blur and recomputes the count', () => {
render(<InventoryTable slug='s' fields={FIELDS} items={[]} locations={[]} onChange={jest.fn()}/>);
fireEvent.change(screen.getByLabelText('Unit Weight'), {target: {value: '5'}});
const total = screen.getByLabelText('Total Weight');
fireEvent.change(total, {target: {value: '400 - 20'}}); // weigh a 400 g box, subtract the 20 g box
fireEvent.blur(total);
expect(screen.getByLabelText('Total Weight').value).toBe('380');
expect(screen.getByLabelText('Count').value).toBe('76'); // 380 / 5
});
test('Enter resolves a weight expression before the row can be submitted', () => {
const onChange = jest.fn();
render(<InventoryTable slug='s' fields={FIELDS} items={[]} locations={[]} onChange={onChange}/>);
fireEvent.change(screen.getByLabelText('Unit Weight'), {target: {value: '5'}});
const total = screen.getByLabelText('Total Weight');
fireEvent.change(total, {target: {value: '400 - 20'}});
// First Enter resolves the expression; the row is NOT submitted yet.
fireEvent.keyDown(total, {key: 'Enter'});
expect(onChange).not.toHaveBeenCalled();
expect(screen.getByLabelText('Total Weight').value).toBe('380');
// Second Enter (now a plain number) submits the resolved row with the recomputed count.
fireEvent.keyDown(screen.getByLabelText('Total Weight'), {key: 'Enter'});
const item = onChange.mock.calls[0][0][0];
expect(item.total_weight).toBe('380');
expect(item.count).toBe('76');
});
test('Enter submits an existing row from an unfilled numeric cell (null backing value)', () => {
const onChange = jest.fn();
// count is absent (undefined) — an item field that was never filled in.
const items = [{id: 1, name: 'Salt'}];
render(<InventoryTable slug='s' fields={FIELDS} items={items} locations={[]} onChange={onChange}/>);
fireEvent.click(screen.getByText('Salt')); // enter edit mode
const row = screen.getByDisplayValue('Salt').closest('tr');
// A null/undefined value must not be mistaken for an unresolved expression; Enter submits immediately.
fireEvent.keyDown(within(row).getByLabelText('Count'), {key: 'Enter'});
expect(onChange).toHaveBeenCalledTimes(1);
});
test('reducing a weight below one item shows 0, not the stale count', () => {
const items = [{id: 1, name: 'Screws', unit_weight: '5', unit_weight_unit: 'g',
total_weight: '1000', total_weight_unit: 'g', count: '200'}];

View file

@ -15,6 +15,10 @@ export const UNIT_GROUPS = [
export const ALL_UNITS = UNIT_GROUPS.flatMap(g => g.units);
// Field types whose value is a number the user may type as an arithmetic expression (e.g. "400 - 20"). Shared
// so the table editor and cell editor can't drift apart when a new numeric type is added.
export const NUMERIC_TYPES = ['number', 'quantity', 'calories'];
// Compaction ladders (ascending): a summed quantity is displayed in the largest unit on a compatible ladder where
// the magnitude is still >= 1 (mirrors the old backend `compact_unit`, e.g. 2000 lb -> 1 ton, 16 oz + 1 lb -> 2 lb).
const COMPACTION_LADDERS = [
@ -41,6 +45,34 @@ function toUnit(value, unit) {
}
}
/**
* Evaluate a simple arithmetic expression typed into a numeric field to its numeric string, so a user can do math
* inline — e.g. "400 - 20" -> "380" (weigh a 400 g box of nails, subtract the 20 g box). Only bare arithmetic is
* allowed (digits, `. + - * / ( )` and spaces); anything containing a letter is rejected, so there are no function
* calls or constants to evaluate. A plain number, a bare negative, or anything unparseable is returned unchanged.
* Float noise is rounded off (0.1 + 0.2 -> 0.3).
*/
export function evaluateExpression(value) {
if (typeof value !== 'string') {
return value;
}
const expr = value.trim();
// Must look like arithmetic AND contain an operator beyond an optional leading sign (so "380" and "-20" are
// left alone rather than needlessly rewritten).
if (expr === '' || !/^[\d\s.+\-*/()]+$/.test(expr) || !/[+\-*/]/.test(expr.replace(/^[+-]/, ''))) {
return value;
}
try {
const result = math.evaluate(expr);
if (typeof result === 'number' && Number.isFinite(result)) {
return String(Math.round(result * 1e6) / 1e6);
}
} catch {
// Not a valid expression (e.g. "400-") — leave it as typed.
}
return value;
}
// Convert a {value, unit} to another unit. Returns a number, or null when incompatible/unparseable.
export function convert(value, fromUnit, toUnitName) {
const u = toUnit(value, fromUnit);

View file

@ -1,4 +1,31 @@
import {convert, countByWeight, formatTotals, sumQuantities} from "./units";
import {convert, countByWeight, evaluateExpression, formatTotals, sumQuantities} from "./units";
describe('evaluateExpression', () => {
test('evaluates arithmetic to a numeric string', () => {
expect(evaluateExpression('400 - 20')).toBe('380');
expect(evaluateExpression('400-20')).toBe('380');
expect(evaluateExpression('(400 - 20) * 2')).toBe('760');
expect(evaluateExpression('10/4')).toBe('2.5');
});
test('rounds off floating-point noise', () => {
expect(evaluateExpression('0.1 + 0.2')).toBe('0.3');
});
test('leaves a plain number or bare negative unchanged', () => {
expect(evaluateExpression('380')).toBe('380');
expect(evaluateExpression('-20')).toBe('-20');
expect(evaluateExpression('')).toBe('');
expect(evaluateExpression(' ')).toBe(' ');
});
test('refuses anything with letters (no functions/constants) or unparseable input', () => {
expect(evaluateExpression('2 kg')).toBe('2 kg'); // unit text left for the unit field
expect(evaluateExpression('sqrt(9)')).toBe('sqrt(9)');
expect(evaluateExpression('400 -')).toBe('400 -'); // incomplete expression
expect(evaluateExpression('1/0')).toBe('1/0'); // Infinity is not finite -> unchanged
});
});
describe('countByWeight', () => {
test('divides total by unit weight and rounds to a whole number', () => {