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,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', () => {