listmonk/frontend/src/utils.js

98 lines
2.0 KiB
JavaScript
Raw Normal View History

import {
ToastProgrammatic as Toast,
DialogProgrammatic as Dialog,
} from 'buefy';
2018-10-25 15:51:47 +02:00
const reEmail = /(.+?)@(.+?)/ig;
2018-10-25 15:51:47 +02:00
export default class utils {
static months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug',
'Sep', 'Oct', 'Nov', 'Dec'];
2018-10-25 15:51:47 +02:00
static days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
// Parses an ISO timestamp to a simpler form.
static niceDate = (stamp, showTime) => {
2019-03-09 08:46:47 +01:00
if (!stamp) {
return '';
2019-03-09 08:46:47 +01:00
}
2018-10-25 15:51:47 +02:00
const d = new Date(stamp);
let out = `${utils.days[d.getDay()]}, ${d.getDate()}`;
out += ` ${utils.months[d.getMonth()]} ${d.getFullYear()}`;
2019-03-09 08:46:47 +01:00
if (showTime) {
out += ` ${d.getHours()}:${d.getMinutes()}`;
2018-10-25 15:51:47 +02:00
}
return out;
};
2019-03-09 08:46:47 +01:00
// Simple, naive, e-mail address check.
static validateEmail = (e) => e.match(reEmail);
static niceNumber = (n) => {
2020-07-04 18:55:02 +02:00
if (n === null || n === undefined) {
return 0;
}
let pfx = '';
let div = 1;
2018-10-25 15:51:47 +02:00
if (n >= 1.0e+9) {
pfx = 'b';
div = 1.0e+9;
} else if (n >= 1.0e+6) {
pfx = 'm';
div = 1.0e+6;
} else if (n >= 1.0e+4) {
pfx = 'k';
div = 1.0e+3;
} else {
return n;
2018-10-25 15:51:47 +02:00
}
2019-03-09 08:46:47 +01:00
// Whole number without decimals.
const out = (n / div);
if (Math.floor(out) === n) {
return out + pfx;
2018-10-25 15:51:47 +02:00
}
2019-03-09 08:46:47 +01:00
return out.toFixed(2) + pfx;
2019-03-09 08:46:47 +01:00
}
2018-10-25 15:51:47 +02:00
// UI shortcuts.
static confirm = (msg, onConfirm, onCancel) => {
Dialog.confirm({
scroll: 'keep',
message: !msg ? 'Are you sure?' : msg,
onConfirm,
onCancel,
});
};
static prompt = (msg, inputAttrs, onConfirm, onCancel) => {
Dialog.prompt({
scroll: 'keep',
message: msg,
confirmText: 'OK',
inputAttrs: {
type: 'string',
maxlength: 200,
...inputAttrs,
},
trapFocus: true,
onConfirm,
onCancel,
});
};
static toast = (msg, typ) => {
Toast.open({
message: msg,
type: !typ ? 'is-success' : typ,
queue: false,
duration: 3000,
});
};
}