@playbooks/hooks
Version:
A collection of React hooks for Playbooks.
439 lines (438 loc) • 15.2 kB
JavaScript
import { useState } from "react";
import { useHooks } from "./context.es.js";
var accounting = { exports: {} };
/*!
* accounting.js v0.4.1
* Copyright 2014 Open Exchange Rates
*
* Freely distributable under the MIT license.
* Portions of accounting.js are inspired or borrowed from underscore.js
*
* Full details and documentation:
* http://openexchangerates.github.io/accounting.js/
*/
var hasRequiredAccounting;
function requireAccounting() {
if (hasRequiredAccounting) return accounting.exports;
hasRequiredAccounting = 1;
(function(module, exports) {
(function(root, undefined$1) {
var lib = {};
lib.version = "0.4.1";
lib.settings = {
currency: {
symbol: "$",
// default currency symbol is '$'
format: "%s%v",
// controls output: %s = symbol, %v = value (can be object, see docs)
decimal: ".",
// decimal point separator
thousand: ",",
// thousands separator
precision: 2,
// decimal places
grouping: 3
// digit grouping (not implemented yet)
},
number: {
precision: 0,
// default precision on numbers is 0
grouping: 3,
// digit grouping (not implemented yet)
thousand: ",",
decimal: "."
}
};
var nativeMap = Array.prototype.map, nativeIsArray = Array.isArray, toString = Object.prototype.toString;
function isString(obj) {
return !!(obj === "" || obj && obj.charCodeAt && obj.substr);
}
function isArray(obj) {
return nativeIsArray ? nativeIsArray(obj) : toString.call(obj) === "[object Array]";
}
function isObject(obj) {
return obj && toString.call(obj) === "[object Object]";
}
function defaults(object, defs) {
var key;
object = object || {};
defs = defs || {};
for (key in defs) {
if (defs.hasOwnProperty(key)) {
if (object[key] == null) object[key] = defs[key];
}
}
return object;
}
function map(obj, iterator, context) {
var results = [], i, j;
if (!obj) return results;
if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
for (i = 0, j = obj.length; i < j; i++) {
results[i] = iterator.call(context, obj[i], i, obj);
}
return results;
}
function checkPrecision(val, base) {
val = Math.round(Math.abs(val));
return isNaN(val) ? base : val;
}
function checkCurrencyFormat(format) {
var defaults2 = lib.settings.currency.format;
if (typeof format === "function") format = format();
if (isString(format) && format.match("%v")) {
return {
pos: format,
neg: format.replace("-", "").replace("%v", "-%v"),
zero: format
};
} else if (!format || !format.pos || !format.pos.match("%v")) {
return !isString(defaults2) ? defaults2 : lib.settings.currency.format = {
pos: defaults2,
neg: defaults2.replace("%v", "-%v"),
zero: defaults2
};
}
return format;
}
var unformat = lib.unformat = lib.parse = function(value, decimal) {
if (isArray(value)) {
return map(value, function(val) {
return unformat(val, decimal);
});
}
value = value || 0;
if (typeof value === "number") return value;
decimal = decimal || lib.settings.number.decimal;
var regex = new RegExp("[^0-9-" + decimal + "]", ["g"]), unformatted = parseFloat(
("" + value).replace(/\((.*)\)/, "-$1").replace(regex, "").replace(decimal, ".")
// make sure decimal point is standard
);
return !isNaN(unformatted) ? unformatted : 0;
};
var toFixed = lib.toFixed = function(value, precision) {
precision = checkPrecision(precision, lib.settings.number.precision);
var power = Math.pow(10, precision);
return (Math.round(lib.unformat(value) * power) / power).toFixed(precision);
};
var formatNumber = lib.formatNumber = lib.format = function(number, precision, thousand, decimal) {
if (isArray(number)) {
return map(number, function(val) {
return formatNumber(val, precision, thousand, decimal);
});
}
number = unformat(number);
var opts = defaults(
isObject(precision) ? precision : {
precision,
thousand,
decimal
},
lib.settings.number
), usePrecision = checkPrecision(opts.precision), negative = number < 0 ? "-" : "", base = parseInt(toFixed(Math.abs(number || 0), usePrecision), 10) + "", mod = base.length > 3 ? base.length % 3 : 0;
return negative + (mod ? base.substr(0, mod) + opts.thousand : "") + base.substr(mod).replace(/(\d{3})(?=\d)/g, "$1" + opts.thousand) + (usePrecision ? opts.decimal + toFixed(Math.abs(number), usePrecision).split(".")[1] : "");
};
var formatMoney = lib.formatMoney = function(number, symbol, precision, thousand, decimal, format) {
if (isArray(number)) {
return map(number, function(val) {
return formatMoney(val, symbol, precision, thousand, decimal, format);
});
}
number = unformat(number);
var opts = defaults(
isObject(symbol) ? symbol : {
symbol,
precision,
thousand,
decimal,
format
},
lib.settings.currency
), formats = checkCurrencyFormat(opts.format), useFormat = number > 0 ? formats.pos : number < 0 ? formats.neg : formats.zero;
return useFormat.replace("%s", opts.symbol).replace("%v", formatNumber(Math.abs(number), checkPrecision(opts.precision), opts.thousand, opts.decimal));
};
lib.formatColumn = function(list, symbol, precision, thousand, decimal, format) {
if (!list) return [];
var opts = defaults(
isObject(symbol) ? symbol : {
symbol,
precision,
thousand,
decimal,
format
},
lib.settings.currency
), formats = checkCurrencyFormat(opts.format), padAfterSymbol = formats.pos.indexOf("%s") < formats.pos.indexOf("%v") ? true : false, maxLength = 0, formatted = map(list, function(val, i) {
if (isArray(val)) {
return lib.formatColumn(val, opts);
} else {
val = unformat(val);
var useFormat = val > 0 ? formats.pos : val < 0 ? formats.neg : formats.zero, fVal = useFormat.replace("%s", opts.symbol).replace("%v", formatNumber(Math.abs(val), checkPrecision(opts.precision), opts.thousand, opts.decimal));
if (fVal.length > maxLength) maxLength = fVal.length;
return fVal;
}
});
return map(formatted, function(val, i) {
if (isString(val) && val.length < maxLength) {
return padAfterSymbol ? val.replace(opts.symbol, opts.symbol + new Array(maxLength - val.length + 1).join(" ")) : new Array(maxLength - val.length + 1).join(" ") + val;
}
return val;
});
};
{
if (module.exports) {
exports = module.exports = lib;
}
exports.accounting = lib;
}
})();
})(accounting, accounting.exports);
return accounting.exports;
}
requireAccounting();
var dist = {};
var abbreviateNumber = {};
var _const = {};
var hasRequired_const;
function require_const() {
if (hasRequired_const) return _const;
hasRequired_const = 1;
Object.defineProperty(_const, "__esModule", { value: true });
_const.defaultSymbols = ["", "k", "M", "G", "T", "P", "E"];
return _const;
}
var hasRequiredAbbreviateNumber;
function requireAbbreviateNumber() {
if (hasRequiredAbbreviateNumber) return abbreviateNumber;
hasRequiredAbbreviateNumber = 1;
Object.defineProperty(abbreviateNumber, "__esModule", { value: true });
var const_1 = require_const();
var defaultOptions = {
padding: true,
symbols: const_1.defaultSymbols
};
function abbreviateNumber$1(num, digit, options) {
if (digit === void 0) {
digit = 1;
}
if (Array.isArray(options)) {
options = { symbols: options };
}
var _a = Object.assign({}, defaultOptions, options), symbols = _a.symbols, padding = _a.padding;
var sign = Math.sign(num) >= 0;
num = Math.abs(num);
var tier = Math.log10(num) / 3 | 0;
if (tier == 0)
return (!sign ? "-" : "") + num.toString();
var suffix = symbols[tier];
if (!suffix)
throw new RangeError();
var scale = Math.pow(10, tier * 3);
var scaled = num / scale;
var rounded = scaled.toFixed(digit);
if (!padding) {
rounded = String(Number(rounded));
}
return (!sign ? "-" : "") + rounded + suffix;
}
abbreviateNumber.abbreviateNumber = abbreviateNumber$1;
return abbreviateNumber;
}
var unabbreviateNumber = {};
var utils = {};
var hasRequiredUtils;
function requireUtils() {
if (hasRequiredUtils) return utils;
hasRequiredUtils = 1;
Object.defineProperty(utils, "__esModule", { value: true });
utils.symbolPow = function(index) {
if (index === void 0) {
index = 0;
}
return Math.pow(10, index * 3);
};
return utils;
}
var hasRequiredUnabbreviateNumber;
function requireUnabbreviateNumber() {
if (hasRequiredUnabbreviateNumber) return unabbreviateNumber;
hasRequiredUnabbreviateNumber = 1;
Object.defineProperty(unabbreviateNumber, "__esModule", { value: true });
var const_1 = require_const();
var utils_1 = requireUtils();
function unabbreviateNumber$1(num, symbols) {
if (symbols === void 0) {
symbols = const_1.defaultSymbols;
}
var numberPattern = "[+-]?([0-9]*[.])?[0-9]+";
var symbolPattern = "" + symbols.join("|");
var pattern = "^(" + numberPattern + ")(" + symbolPattern + ")$";
var regex = new RegExp(pattern);
var match = num.match(pattern) || [];
if (regex.test(num) && match.length > 3) {
var symbol = match[3];
var symbolValue = utils_1.symbolPow(symbols.indexOf(symbol));
var pureNum = Number(match[1]);
return pureNum * symbolValue;
} else {
throw Error("This is not a valid input");
}
}
unabbreviateNumber.unabbreviateNumber = unabbreviateNumber$1;
return unabbreviateNumber;
}
var hasRequiredDist;
function requireDist() {
if (hasRequiredDist) return dist;
hasRequiredDist = 1;
(function(exports) {
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__export(requireAbbreviateNumber());
__export(requireUnabbreviateNumber());
})(dist);
return dist;
}
requireDist();
const capitalize = (data = "") => {
return data.charAt(0).toUpperCase() + data.slice(1);
};
const useInit = (method) => {
const [error, setError] = useState(null);
const [loading, setLoading] = useState(true);
const { toast } = useHooks();
const onQuery = async (data) => {
try {
setLoading(true);
await method(data);
} catch (e) {
setError(e);
toast.showError(e);
} finally {
setLoading(false);
}
};
return [onQuery, loading, error];
};
const useQuery = (method) => {
const [error, setError] = useState(null);
const [loading, setLoading] = useState(false);
const { toast } = useHooks();
const onQuery = async (data) => {
try {
setLoading(true);
await method(data);
} catch (e) {
setError(e);
toast.showError(e);
} finally {
setLoading(false);
}
};
return [onQuery, loading, error];
};
const useAction = (model, method) => {
const [error, setError] = useState(null);
const [task, setTask] = useState({ id: "", name: "action", running: false });
const { toast } = useHooks();
const onAction = async (record) => {
try {
setTask({ ...task, id: record?.id || model?.id, running: true });
await method(record);
} catch (e) {
setError(e);
toast.showError(e);
} finally {
setTask({ ...task, id: null, running: false });
}
};
return [onAction, task, error];
};
const useConfirm = (model, message, method) => {
const [error, setError] = useState(null);
const [task, setTask] = useState({ id: "", name: "save", running: false });
const { toast } = useHooks();
const useConfirm2 = async (record) => {
try {
setTask({ ...task, id: record?.id || model?.id, running: true });
const confirmed = window.confirm(message);
if (!confirmed) return;
await method(record);
} catch (e) {
setError(e);
toast.showError(e);
} finally {
setTask({ ...task, id: null, running: false });
}
};
return [useConfirm2, task, error];
};
const useSave = (model, modelName, method) => {
const [error, setError] = useState(null);
const [task, setTask] = useState({ id: "", name: "save", running: false });
const { toast } = useHooks();
const onSave = async (record) => {
try {
setTask({ ...task, id: record?.id || model?.id, running: true });
await method(record);
toast.showSuccess(200, `${capitalize(modelName)} saved!`);
} catch (e) {
setError(e);
toast.showError(e);
} finally {
setTask({ ...task, id: null, running: false });
}
};
return [onSave, task, error];
};
const useDelete = (model, modelName, method) => {
const [error, setError] = useState(null);
const [task, setTask] = useState({ id: "", name: "delete", running: false });
const { toast } = useHooks();
const onDelete = async (record) => {
try {
setTask({ ...task, id: record?.id || model?.id, running: true });
const confirmed = window.confirm(`Are you sure you want to delete this ${modelName}?`);
if (!confirmed) return;
await method(record);
toast.showSuccess(200, `${capitalize(modelName)} deleted!`);
} catch (e) {
setError(e);
toast.showError(e);
} finally {
setTask({ ...task, id: null, running: false });
}
};
return [onDelete, task, error];
};
const useDeletes = (model, modelName, method) => {
const [error, setError] = useState(null);
const [task, setTask] = useState({ id: "", name: "delete", running: false });
const { toast } = useHooks();
const onDelete = async (record) => {
try {
setTask({ ...task, id: record?.id || model?.id, running: true });
const confirmed = window.confirm(`Are you sure you want to delete ${model.length} ${modelName}?`);
if (!confirmed) return;
await method(record);
toast.showSuccess(200, `${capitalize(modelName)} deleted!`);
} catch (e) {
setError(e);
toast.showError(e);
} finally {
setTask({ ...task, id: null, running: false });
}
};
return [onDelete, task, error];
};
export {
useAction,
useConfirm,
useDelete,
useDeletes,
useInit,
useQuery,
useSave
};