tweak-tools
Version:
Tweak your React projects until awesomeness
91 lines (90 loc) • 3.03 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.format = exports.sanitize = exports.normalize = exports.createPlugin = exports.createInternalPlugin = exports.register = exports.getValueType = exports.Plugins = void 0;
const log_1 = require("./utils/log");
const Schemas = [];
exports.Plugins = {};
function getValueType(_a) {
var { value } = _a, settings = __rest(_a, ["value"]);
for (let checker of Schemas) {
const type = checker(value, settings);
if (type)
return type;
}
return undefined;
}
exports.getValueType = getValueType;
/**
* Populates Schemas and Plugins singletons that are used globally.
*
* @param type
* @param plugin
*/
function register(type, _a) {
var { schema } = _a, plugin = __rest(_a, ["schema"]);
if (type in exports.Plugins) {
console.warn(log_1.TweakErrors.ALREADY_REGISTERED_TYPE, type);
return;
}
Schemas.push((value, settings) => schema(value, settings) && type);
exports.Plugins[type] = plugin;
}
exports.register = register;
const getUniqueType = () => '__CUSTOM__PLUGIN__' + Math.random().toString(36).substr(2, 9);
/**
* helper function for types
* @param plugin
*/
function createInternalPlugin(plugin) {
return plugin;
}
exports.createInternalPlugin = createInternalPlugin;
/**
* This function should be used by custom plugins. It is mostly used as a way
* to properly type the input return value.
*
* @param plugin
*/
function createPlugin(plugin) {
const type = getUniqueType();
exports.Plugins[type] = plugin;
return (input) => {
return { type, __customInput: input };
};
}
exports.createPlugin = createPlugin;
function normalize(type, input, path, data) {
const { normalize: _normalize } = exports.Plugins[type];
if (_normalize)
return _normalize(input, path, data);
if (typeof input !== 'object' || !('value' in input))
return { value: input };
const { value } = input, settings = __rest(input, ["value"]);
return { value, settings };
}
exports.normalize = normalize;
function sanitize(type, value, settings, prevValue, path, store) {
const { sanitize } = exports.Plugins[type];
if (sanitize)
return sanitize(value, settings, prevValue, path, store);
return value;
}
exports.sanitize = sanitize;
function format(type, value, settings) {
const { format } = exports.Plugins[type];
if (format)
return format(value, settings);
return value;
}
exports.format = format;