tweak-tools
Version:
Tweak your React projects until awesomeness
79 lines (78 loc) • 3.16 kB
JavaScript
;
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.sanitizeStep = exports.normalize = exports.format = exports.sanitize = exports.schema = void 0;
const utils_1 = require("../../utils");
const schema = (v) => {
if (typeof v === 'number')
return true;
// we consider a string as a number if it starts with a number and it's suffix is less than 4 characters
if (typeof v === 'string') {
const _v = parseFloat(v);
if (isNaN(_v))
return false;
const suffix = v.substring(('' + _v).length).trim();
return suffix.length < 4;
}
return false;
};
exports.schema = schema;
const sanitize = (v, { min = -Infinity, max = Infinity, suffix }) => {
const _v = parseFloat(v);
if (v === '' || isNaN(_v))
throw Error('Invalid number');
const f = (0, utils_1.clamp)(_v, min, max);
return suffix ? f + suffix : f;
};
exports.sanitize = sanitize;
const format = (v, { pad = 0, suffix }) => {
const f = parseFloat(v).toFixed(pad);
return suffix ? f + suffix : f;
};
exports.format = format;
const normalize = (_a) => {
var { value } = _a, settings = __rest(_a, ["value"]);
const { min = -Infinity, max = Infinity } = settings, _settings = __rest(settings, ["min", "max"]);
let _value = parseFloat(value);
const suffix = typeof value === 'string' ? value.substring(('' + _value).length) : undefined;
_value = (0, utils_1.clamp)(_value, min, max);
// ideally:
// 3 -> 3.0
// { value: 10, step: 0.2 } -> 10.0
// { value: 10, step: 0.25 } -> 10.00
let step = settings.step;
if (!step) {
if (Number.isFinite(min))
if (Number.isFinite(max))
step = +(Math.abs(max - min) / 100).toPrecision(1);
else
step = +(Math.abs(_value - min) / 100).toPrecision(1);
else if (Number.isFinite(max))
step = +(Math.abs(max - _value) / 100).toPrecision(1);
}
// padStep should be based on step first
const padStep = step ? (0, utils_1.getStep)(step) * 10 : (0, utils_1.getStep)(_value);
step = step || padStep / 10;
const pad = Math.round((0, utils_1.clamp)(Math.log10(1 / padStep), 0, 2));
return {
value: suffix ? _value + suffix : _value,
settings: Object.assign({ initialValue: _value, step, pad, min, max, suffix }, _settings),
};
};
exports.normalize = normalize;
// TODO fix this function, probably not needed
const sanitizeStep = (v, { step, initialValue }) => {
const steps = Math.round((v - initialValue) / step);
return initialValue + steps * step;
};
exports.sanitizeStep = sanitizeStep;