forked from knadh/listmonk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.js
235 lines (197 loc) · 6.02 KB
/
utils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
import {
ToastProgrammatic as Toast,
DialogProgrammatic as Dialog,
} from 'buefy';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import updateLocale from 'dayjs/plugin/updateLocale';
dayjs.extend(updateLocale);
dayjs.extend(relativeTime);
const reEmail = /(.+?)@(.+?)/ig;
const prefKey = 'listmonk_pref';
const htmlEntities = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/',
'`': '`',
'=': '=',
};
export default class Utils {
constructor(i18n) {
this.i18n = i18n;
this.intlNumFormat = new Intl.NumberFormat();
if (i18n) {
dayjs.updateLocale('en', {
relativeTime: {
future: '%s',
past: '%s',
s: `${i18n.tc('globals.terms.second', 2)}`,
m: `1 ${i18n.tc('globals.terms.minute', 1)}`,
mm: `%d ${i18n.tc('globals.terms.minute', 2)}`,
h: `1 ${i18n.tc('globals.terms.hour', 1)}`,
hh: `%d ${i18n.tc('globals.terms.hour', 2)}`,
d: `1 ${i18n.tc('globals.terms.day', 1)}`,
dd: `%d ${i18n.tc('globals.terms.day', 2)}`,
M: `1 ${i18n.tc('globals.terms.month', 1)}`,
MM: `%d ${i18n.tc('globals.terms.month', 2)}`,
y: `${i18n.tc('globals.terms.year', 1)}`,
yy: `%d ${i18n.tc('globals.terms.year', 2)}`,
},
});
}
}
getDate = (d) => dayjs(d);
// Parses an ISO timestamp to a simpler form.
niceDate = (stamp, showTime) => {
if (!stamp) {
return '';
}
const d = dayjs(stamp);
const day = this.i18n.t(`globals.days.${d.day()}`);
const month = this.i18n.t(`globals.months.${d.month() + 1}`);
let out = d.format(`[${day},] DD [${month}] YYYY`);
if (showTime) {
out += d.format(', HH:mm');
}
return out;
};
duration = (start, end) => dayjs(end).from(dayjs(start), true);
// Simple, naive, e-mail address check.
validateEmail = (e) => e.match(reEmail);
niceNumber = (n) => {
if (n === null || n === undefined) {
return 0;
}
let pfx = '';
let div = 1;
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;
}
// Whole number without decimals.
const out = (n / div);
if (Math.floor(out) === n) {
return out + pfx;
}
return out.toFixed(2) + pfx;
}
formatNumber(v) {
return this.intlNumFormat.format(v);
}
// Parse one or more numeric ids as query params and return as an array of ints.
parseQueryIDs = (ids) => {
if (!ids) {
return [];
}
if (typeof ids === 'string') {
return [parseInt(ids, 10)];
}
if (typeof ids === 'number') {
return [parseInt(ids, 10)];
}
return ids.map((id) => parseInt(id, 10));
}
// https://stackoverflow.com/a/12034334
escapeHTML = (html) => html.replace(/[&<>"'`=/]/g, (s) => htmlEntities[s]);
titleCase = (str) => str[0].toUpperCase() + str.substr(1).toLowerCase();
// UI shortcuts.
confirm = (msg, onConfirm, onCancel) => {
Dialog.confirm({
scroll: 'keep',
message: !msg ? this.i18n.t('globals.messages.confirm') : this.escapeHTML(msg),
confirmText: this.i18n.t('globals.buttons.ok'),
cancelText: this.i18n.t('globals.buttons.cancel'),
onConfirm,
onCancel,
});
};
prompt = (msg, inputAttrs, onConfirm, onCancel) => {
Dialog.prompt({
scroll: 'keep',
message: this.escapeHTML(msg),
confirmText: this.i18n.t('globals.buttons.ok'),
cancelText: this.i18n.t('globals.buttons.cancel'),
inputAttrs: {
type: 'string',
maxlength: 200,
...inputAttrs,
},
trapFocus: true,
onConfirm,
onCancel,
});
};
toast = (msg, typ, duration) => {
Toast.open({
message: this.escapeHTML(msg),
type: !typ ? 'is-success' : typ,
queue: false,
duration: duration || 3000,
position: 'is-top',
pauseOnHover: true,
});
};
// Takes a props.row from a Buefy b-column <td> template and
// returns a `data-id` attribute which Buefy then applies to the td.
tdID = (row) => ({ 'data-id': row.id.toString() });
camelString = (str) => {
const s = str.replace(/[-_\s]+(.)?/g, (match, chr) => (chr ? chr.toUpperCase() : ''));
return s.substr(0, 1).toLowerCase() + s.substr(1);
}
// camelKeys recursively camelCases all keys in a given object (array or {}).
// For each key it traverses, it passes a dot separated key path to an optional testFunc() bool.
// so that it can camelcase or leave a particular key alone based on what testFunc() returns.
// eg: The keypath for {"data": {"results": ["created_at": 123]}} is
// .data.results.*.created_at (array indices become *)
// testFunc() can examine this key and return true to convert it to camelcase
// or false to leave it as-is.
camelKeys = (obj, testFunc, keys) => {
if (obj === null) {
return obj;
}
if (Array.isArray(obj)) {
return obj.map((o) => this.camelKeys(o, testFunc, `${keys || ''}.*`));
}
if (obj.constructor === Object) {
return Object.keys(obj).reduce((result, key) => {
const keyPath = `${keys || ''}.${key}`;
let k = key;
// If there's no testfunc or if a function is defined and it returns true, convert.
if (testFunc === undefined || testFunc(keyPath)) {
k = this.camelString(key);
}
return {
...result,
[k]: this.camelKeys(obj[key], testFunc, keyPath),
};
}, {});
}
return obj;
};
getPref = (key) => {
if (localStorage.getItem(prefKey) === null) {
return null;
}
const p = JSON.parse(localStorage.getItem(prefKey));
return key in p ? p[key] : null;
};
setPref = (key, val) => {
let p = {};
if (localStorage.getItem(prefKey) !== null) {
p = JSON.parse(localStorage.getItem(prefKey));
}
p[key] = val;
localStorage.setItem(prefKey, JSON.stringify(p));
}
}