lazy-widgets
Version:
Typescript retained mode GUI for the HTML canvas API
51 lines • 1.6 kB
JavaScript
import { Variable } from './Variable.js';
/**
* Similar to {@link Variable}, except the variable's value can optionally be
* validated by a {@link Validator | validator function}.
*
* @typeParam V - The type of {@link Variable#value}.
* @typeParam T - The transformed type of a {@link ValidatedVariable#validValue | valid value}.
*
* @category State Management
*/
export class ValidatedVariable extends Variable {
constructor(initialValue, validator = null) {
super(initialValue);
/** See {@link ValidatedVariable#valid}. For internal use only */
this._valid = true;
this.validator = validator;
this.validateAndSet(initialValue);
}
get valid() {
return this._valid;
}
get validValue() {
return this._validValue;
}
setValue(value, group) {
if (this.value === value) {
return false;
}
this.validateAndSet(value);
return super.setValue(value, group);
}
validate(value) {
if (this.validator) {
return this.validator(value);
}
else {
// XXX we have to assume that the user provided the right type
return [true, value];
}
}
validateAndSet(value) {
const [valid, validValueCandidate] = this.validate(value);
// XXX _valid is set in two stages so the type system knows whether
// valid is true or false
this._valid = valid;
if (valid) {
this._validValue = validValueCandidate;
}
}
}
//# sourceMappingURL=ValidatedVariable.js.map