@pbroom/color-kit/driverColor input

parseColorInputExpression

Parses text typed into a channel input into a number in channel units. Returns null for empty or unparseable input. The result is not clamped or wrapped; resolveColorInputDraftValue does that.

functionimport { parseColorInputExpression } from '@pbroom/color-kit/driver';color-input-parser.ts:300
function parseColorInputExpression(
  input: string,
  options: ParseColorInputExpressionOptions,
): number | null;

Grammar, after trimming whitespace:

  • Number: digits with an optional fraction (12, 0.5, .5), then an optional suffix. deg (any case) is ignored; % means that percentage of the range span, offset by range[0] (50% on [100, 200] is 150). Exponents (1e3) are rejected.
  • Without allowExpressions: one number with an optional leading + or -, nothing else (-2 is the absolute value -2).
  • With allowExpressions: + - * / with the usual precedence, unary + and -, and parentheses. Input that starts with an operator is relative to currentValue (+10, -5, *2, /4), and there % is a plain fraction of the span (+10% adds 10% of the span). In an absolute expression every % number is a position in the range, exactly like a lone 50%: on [100, 200], 50% + 10 is 150 + 10 = 160 and 50% * 2 is 300. Division by zero or another non-finite result returns null.

Parameters

inputstring

Returns

number | null

Example

TypeScript
import { parseColorInputExpression } from '@pbroom/color-kit/driver';

const options = { currentValue: 100, range: [0, 360] as [number, number] };
parseColorInputExpression('50%', options); // → 180
parseColorInputExpression('1+1', options); // → null
const expressions = { ...options, allowExpressions: true };
parseColorInputExpression('2*(3+4)', expressions); // → 14
parseColorInputExpression('+10%', expressions); // → 136
const offset = { ...expressions, range: [100, 200] as [number, number] };
parseColorInputExpression('50% + 10', offset); // → 160
parseColorInputExpression('50% * 2', offset); // → 300
parseColorInputExpression('/4', expressions); // → 25