x4js 1.4.3 → 1.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/lib/index.d.ts +55 -0
  2. package/lib/index.js +55 -56
  3. package/lib/router.d.ts +1 -8
  4. package/lib/router.js +1 -1
  5. package/package.json +2 -1
  6. package/src/index.ts +55 -0
  7. package/src/router.ts +1 -1
  8. package/tsconfig.json +2 -1
  9. package/lib/application.d.ts +0 -95
  10. package/lib/application.js +0 -137
  11. package/lib/base64.d.ts +0 -31
  12. package/lib/base64.js +0 -135
  13. package/lib/base_component.d.ts +0 -64
  14. package/lib/base_component.js +0 -77
  15. package/lib/button.d.ts +0 -145
  16. package/lib/button.js +0 -235
  17. package/lib/calendar.d.ts +0 -77
  18. package/lib/calendar.js +0 -236
  19. package/lib/canvas.d.ts +0 -88
  20. package/lib/canvas.js +0 -354
  21. package/lib/cardview.d.ts +0 -83
  22. package/lib/cardview.js +0 -152
  23. package/lib/checkbox.d.ts +0 -72
  24. package/lib/checkbox.js +0 -126
  25. package/lib/color.d.ts +0 -144
  26. package/lib/color.js +0 -584
  27. package/lib/component.d.ts +0 -572
  28. package/lib/component.js +0 -1712
  29. package/lib/dom_events.d.ts +0 -284
  30. package/lib/dom_events.js +0 -13
  31. package/lib/hosts/host.d.ts +0 -44
  32. package/lib/hosts/host.js +0 -69
  33. package/lib/i18n.d.ts +0 -67
  34. package/lib/i18n.js +0 -169
  35. package/lib/icon.d.ts +0 -56
  36. package/lib/icon.js +0 -173
  37. package/lib/input.d.ts +0 -86
  38. package/lib/input.js +0 -172
  39. package/lib/label.d.ts +0 -54
  40. package/lib/label.js +0 -86
  41. package/lib/layout.d.ts +0 -77
  42. package/lib/layout.js +0 -261
  43. package/lib/list.txt +0 -56
  44. package/lib/menu.d.ts +0 -122
  45. package/lib/menu.js +0 -276
  46. package/lib/popup.d.ts +0 -71
  47. package/lib/popup.js +0 -373
  48. package/lib/settings.d.ts +0 -33
  49. package/lib/settings.js +0 -63
  50. package/lib/styles.d.ts +0 -81
  51. package/lib/styles.js +0 -262
  52. package/lib/tools.d.ts +0 -382
  53. package/lib/tools.js +0 -1096
  54. package/lib/x4_events.d.ts +0 -253
  55. package/lib/x4_events.js +0 -363
  56. package/list.txt +0 -0
package/lib/tools.js DELETED
@@ -1,1096 +0,0 @@
1
- /**
2
- * ___ ___ __
3
- * \ \_/ / / _
4
- * \ / /_| |_
5
- * / _ \____ _|
6
- * /__/ \__\ |_|
7
- *
8
- * @file tools.ts
9
- * @author Etienne Cochard
10
- * @license
11
- * Copyright (c) 2019-2021 R-libre ingenierie
12
- *
13
- * This program is free software; you can redistribute it and/or modify
14
- * it under the terms of the GNU General Public License as published by
15
- * the Free Software Foundation; either version 3 of the License, or
16
- * (at your option) any later version.
17
- *
18
- * This program is distributed in the hope that it will be useful,
19
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
20
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21
- * GNU General Public License for more details.
22
- *
23
- * You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
24
- **/
25
- import { _tr } from './i18n'; // you MUST create a file named translation.js
26
- // :: ENVIRONMENT ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
27
- /**
28
- * @return true is the device has touch
29
- */
30
- export function isTouchDevice() {
31
- return 'ontouchstart' in window;
32
- }
33
- // :: NUMBERS ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
34
- /**
35
- * round to a given number of decimals
36
- * @param num numbre to round
37
- * @param ndec number of decimals
38
- * @returns number rounded
39
- */
40
- export function roundTo(num, ndec) {
41
- let mul = Math.pow(10, ndec);
42
- let res = Math.round(num * mul) / mul;
43
- if (Object.is(res, -0)) { // res===-0.0
44
- res = 0;
45
- }
46
- return res;
47
- }
48
- /**
49
- * parse an intl formatted number
50
- * understand grouping and ',' separator
51
- * @review us format: grouping = ','
52
- * @param num
53
- */
54
- export function parseIntlFloat(num) {
55
- num = num.replace(/\s*/g, ''); // group separator
56
- num = num.replace(',', '.'); // decimal separator
57
- // accept empty & return 0.0
58
- if (num.length == 0) {
59
- return 0.0;
60
- }
61
- return parseFloat(num);
62
- }
63
- // :: STRING MANIP ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
64
- const RE_PCASE = /([a-z][A-Z])/g;
65
- const RE_PCASE2 = /[^-a-z0-9]+/g;
66
- /**
67
- * inverse of camel case
68
- * theThingToCase -> the-thing-to-case
69
- * @param {String} str
70
- */
71
- export function pascalCase(string) {
72
- let result = string;
73
- result = result.replace(/([a-z])([A-Z])/g, "$1 $2");
74
- result = result.toLowerCase();
75
- result = result.replace(/[^- a-z0-9]+/g, ' ');
76
- if (result.indexOf(' ') < 0) {
77
- return result;
78
- }
79
- result = result.trim();
80
- return result.replace(/ /g, '-');
81
- }
82
- export class Point {
83
- x;
84
- y;
85
- constructor(x = 0, y = 0) {
86
- this.x = x;
87
- this.y = y;
88
- }
89
- }
90
- export class Size {
91
- width;
92
- height;
93
- constructor(w = 0, h = 0) {
94
- this.width = w;
95
- this.height = h;
96
- }
97
- }
98
- export class Rect {
99
- left;
100
- top;
101
- width;
102
- height;
103
- constructor(left, top, width, height) {
104
- if (left === undefined) {
105
- this.left = this.top = this.right = this.bottom = 0;
106
- }
107
- else if (left instanceof Rect || left instanceof DOMRect) {
108
- let rc = left;
109
- this.left = rc.left;
110
- this.top = rc.top;
111
- this.width = rc.width;
112
- this.height = rc.height;
113
- }
114
- else {
115
- this.left = left;
116
- this.top = top;
117
- this.width = width;
118
- this.height = height;
119
- }
120
- }
121
- set(left, top, width, height) {
122
- this.left = left;
123
- this.top = top;
124
- this.width = width;
125
- this.height = height;
126
- }
127
- get bottom() {
128
- return this.top + this.height;
129
- }
130
- set bottom(bottom) {
131
- this.height = bottom - this.top;
132
- }
133
- get right() {
134
- return this.left + this.width;
135
- }
136
- set right(right) {
137
- this.width = right - this.left;
138
- }
139
- get topLeft() {
140
- return new Point(this.left, this.top);
141
- }
142
- get bottomRight() {
143
- return new Point(this.right, this.bottom);
144
- }
145
- get size() {
146
- return new Size(this.width, this.height);
147
- }
148
- moveTo(left, top) {
149
- this.left = left;
150
- this.top = top;
151
- return this;
152
- }
153
- movedTo(left, top) {
154
- return new Rect(left, top, this.width, this.height);
155
- }
156
- moveBy(dx, dy) {
157
- this.left += dx;
158
- this.top += dy;
159
- return this;
160
- }
161
- movedBy(dx, dy) {
162
- return new Rect(this.left + dx, this.top + dy, this.width, this.height);
163
- }
164
- isEmpty() {
165
- return this.width == 0 && this.height == 0;
166
- }
167
- normalize() {
168
- let w = this.width, h = this.height;
169
- if (w < 0) {
170
- this.left += w;
171
- this.width = -w;
172
- }
173
- if (h < 0) {
174
- this.top += h;
175
- this.height = -h;
176
- }
177
- return this;
178
- }
179
- normalized() {
180
- let rc = new Rect(this);
181
- let w = rc.width, h = rc.height;
182
- if (w < 0) {
183
- rc.left += w;
184
- rc.width = -w;
185
- }
186
- if (h < 0) {
187
- rc.top += h;
188
- rc.height = -h;
189
- }
190
- return rc;
191
- }
192
- /**
193
- * @deprecated
194
- */
195
- containsPt(x, y) {
196
- return x >= this.left && x <= this.right && y >= this.top && y <= this.bottom;
197
- }
198
- contains(arg) {
199
- if (arg instanceof Rect) {
200
- return arg.left >= this.left && arg.right <= this.right && arg.top >= this.top && arg.bottom <= this.bottom;
201
- }
202
- else {
203
- return arg.x >= this.left && arg.x < this.right && arg.y >= this.top && arg.y < this.bottom;
204
- }
205
- }
206
- touches(rc) {
207
- if (this.left > rc.right || this.right < rc.left || this.top > rc.bottom || this.bottom < rc.top) {
208
- return false;
209
- }
210
- return true;
211
- }
212
- inflate(dx, dy) {
213
- if (dy === undefined) {
214
- dy = dx;
215
- }
216
- this.left -= dx;
217
- this.top -= dy;
218
- this.width += dx + dx;
219
- this.height += dy + dy;
220
- }
221
- inflatedBy(dx, dy) {
222
- if (dy === undefined) {
223
- dy = dx;
224
- }
225
- return new Rect(this.left - dx, this.top - dy, this.width + dx + dx, this.height + dy + dy);
226
- }
227
- combine(rc) {
228
- let left = Math.min(this.left, rc.left);
229
- let top = Math.min(this.top, rc.top);
230
- let right = Math.max(this.right, rc.right);
231
- let bottom = Math.max(this.bottom, rc.bottom);
232
- this.left = left;
233
- this.top = top;
234
- this.right = right;
235
- this.bottom = bottom;
236
- }
237
- }
238
- /**
239
- * replace {0..9} by given arguments
240
- * @param format string
241
- * @param args
242
- *
243
- * @example ```ts
244
- *
245
- * console.log( sprintf( 'here is arg 1 {1} and arg 0 {0}', 'argument 0', 'argument 1' ) )
246
- */
247
- export function sprintf(format, ...args) {
248
- return format.replace(/{(\d+)}/g, function (match, index) {
249
- return typeof args[index] != 'undefined' ? args[index] : match;
250
- });
251
- }
252
- /**
253
- * replace special characters for display
254
- * @param unsafe
255
- *
256
- * console.log( escapeHtml('<div style="width:50px; height: 50px; background-color:red"></div>') );
257
- */
258
- export function escapeHtml(unsafe, nl_br = false) {
259
- if (!unsafe || unsafe.length == 0) {
260
- return unsafe;
261
- }
262
- let result = unsafe.replace(/[<>\&\"\']/g, function (c) {
263
- return '&#' + c.charCodeAt(0) + ';';
264
- });
265
- if (nl_br) {
266
- result = result.replace(/(\r\n|\n\r|\r|\n)/g, '<br/>');
267
- }
268
- return result;
269
- }
270
- /**
271
- * replace special characters for display
272
- * @author Steven Levithan <http://slevithan.com/>
273
- * @param unsafe
274
- *
275
- * console.log( removeHtmlTags('<h1>sss</h1>') );
276
- */
277
- export function removeHtmlTags(unsafe, nl_br = false) {
278
- if (!unsafe || unsafe.length == 0) {
279
- return unsafe;
280
- }
281
- debugger;
282
- let ret_val = '';
283
- for (let i = 0; i < unsafe.length; i++) {
284
- const ch = unsafe.codePointAt(i);
285
- if (ch > 127) {
286
- ret_val += '&#' + ch + ';';
287
- }
288
- else if (ch == 60 /*<*/) {
289
- ret_val += '&lt;';
290
- }
291
- else {
292
- ret_val += unsafe.charAt(i);
293
- }
294
- }
295
- return ret_val;
296
- }
297
- // :: DATES ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
298
- let cur_locale = 'fr-FR';
299
- /**
300
- * change the current locale for misc translations (date...)
301
- * @param locale
302
- */
303
- export function _date_set_locale(locale) {
304
- cur_locale = locale;
305
- }
306
- /**
307
- *
308
- * @param date
309
- * @param options
310
- * @example
311
- * let date = new Date( );
312
- * let options = { day: 'numeric', month: 'numeric', year: 'numeric', hour: 'numeric', minute: 'numeric' };
313
- * let text = date_format( date, options );
314
- */
315
- export function date_format(date, options) {
316
- //return new Intl.DateTimeFormat(cur_locale, options).format( date );
317
- return formatIntlDate(date);
318
- }
319
- /**
320
- *
321
- * @param date
322
- * @param options
323
- */
324
- export function date_diff(date1, date2, options) {
325
- var dt = (date1.getTime() - date2.getTime()) / 1000;
326
- // seconds
327
- let sec = dt;
328
- if (sec < 60) {
329
- return sprintf(_tr.global.diff_date_seconds, Math.round(sec));
330
- }
331
- // minutes
332
- let min = Math.floor(sec / 60);
333
- if (min < 60) {
334
- return sprintf(_tr.global.diff_date_minutes, Math.round(min));
335
- }
336
- // hours
337
- let hrs = Math.floor(min / 60);
338
- return sprintf(_tr.global.diff_date_hours, hrs, min % 60);
339
- }
340
- export function date_to_sql(date, withHours) {
341
- if (withHours) {
342
- return formatIntlDate(date, 'Y-M-D H:I:S');
343
- }
344
- else {
345
- return formatIntlDate(date, 'Y-M-D');
346
- }
347
- }
348
- /**
349
- * construct a date from an utc date time (sql format)
350
- * YYYY-MM-DD HH:MM:SS
351
- */
352
- export function date_sql_utc(date) {
353
- let result = new Date(date + ' GMT');
354
- return result;
355
- }
356
- /**
357
- * return a number that is a representation of the date
358
- * this number can be compared with another hash
359
- */
360
- export function date_hash(date) {
361
- return date.getFullYear() << 16 | date.getMonth() << 8 | date.getDate();
362
- }
363
- Date.prototype.hash = function () {
364
- return date_hash(this);
365
- };
366
- /**
367
- * return a copy of a date
368
- */
369
- export function date_clone(date) {
370
- return new Date(date.getTime());
371
- }
372
- /**
373
- * return the week number of a date
374
- */
375
- export function date_calc_weeknum(date) {
376
- const firstDayOfYear = new Date(date.getFullYear(), 0, 1);
377
- const pastDaysOfYear = (date.valueOf() - firstDayOfYear.valueOf()) / 86400000;
378
- return Math.ceil((pastDaysOfYear + firstDayOfYear.getDay() + 1) / 7);
379
- }
380
- /**
381
- * parse a date according to the given format
382
- * @param value - string date to parse
383
- * @param fmts - format list - i18 tranlation by default
384
- * allowed format specifiers:
385
- * d or D: date (1 or 2 digits)
386
- * m or M: month (1 or 2 digits)
387
- * y or Y: year (2 or 4 digits)
388
- * h or H: hours (1 or 2 digits)
389
- * i or I: minutes (1 or 2 digits)
390
- * s or S: seconds (1 or 2 digits)
391
- * <space>: 1 or more spaces
392
- * any other char: <0 or more spaces><the char><0 or more spaces>
393
- * each specifiers is separated from other by a pipe (|)
394
- * more specific at first
395
- * @example
396
- * 'd/m/y|d m Y|dmy|y-m-d h:i:s|y-m-d'
397
- */
398
- export function parseIntlDate(value, fmts = _tr.global.date_input_formats) {
399
- let formats = fmts.split('|');
400
- for (let fmatch of formats) {
401
- //review: could do that only once & keep result
402
- //review: add hours, minutes, seconds
403
- let smatch = '';
404
- for (let c of fmatch) {
405
- if (c == 'd' || c == 'D') {
406
- smatch += '(?<day>\\d{1,2})';
407
- }
408
- else if (c == 'm' || c == 'M') {
409
- smatch += '(?<month>\\d{1,2})';
410
- }
411
- else if (c == 'y' || c == 'Y') {
412
- smatch += '(?<year>\\d{1,4})';
413
- }
414
- else if (c == 'h' || c == 'H') {
415
- smatch += '(?<hour>\\d{1,2})';
416
- }
417
- else if (c == 'i' || c == 'I') {
418
- smatch += '(?<min>\\d{1,2})';
419
- }
420
- else if (c == 's' || c == 'S') {
421
- smatch += '(?<sec>\\d{1,2})';
422
- }
423
- else if (c == ' ') {
424
- smatch += '\\s+';
425
- }
426
- else {
427
- smatch += '\\s*\\' + c + '\\s*';
428
- }
429
- }
430
- let rematch = new RegExp('^' + smatch + '$', 'm');
431
- let match = rematch.exec(value);
432
- if (match) {
433
- let d = parseInt(match.groups.day ?? '1');
434
- let m = parseInt(match.groups.month ?? '1');
435
- let y = parseInt(match.groups.year ?? '1970');
436
- let h = parseInt(match.groups.hour ?? '0');
437
- let i = parseInt(match.groups.min ?? '0');
438
- let s = parseInt(match.groups.sec ?? '0');
439
- if (y > 0 && y < 100) {
440
- y += 2000;
441
- }
442
- let result = new Date(y, m - 1, d, h, i, s, 0);
443
- // we test the vdate validity (without adjustments)
444
- // without this test, date ( 0, 0, 0) is accepted and transformed to 1969/11/31 (not fun)
445
- let ty = result.getFullYear(), tm = result.getMonth() + 1, td = result.getDate();
446
- if (ty != y || tm != m || td != d) {
447
- //debugger;
448
- return null;
449
- }
450
- return result;
451
- }
452
- }
453
- return null;
454
- }
455
- /**
456
- * format a date as string
457
- * @param date - date to format
458
- * @param fmt - format
459
- * format specifiers:
460
- * d: date
461
- * D: 2 digits date padded with 0
462
- * j: day of week short mode 'mon'
463
- * J: day of week long mode 'monday'
464
- * w: week number
465
- * m: month
466
- * M: 2 digits month padded with 0
467
- * o: month short mode 'jan'
468
- * O: month long mode 'january'
469
- * y or Y: year
470
- * h: hour (24 format)
471
- * H: 2 digits hour (24 format) padded with 0
472
- * i: minutes
473
- * I: 2 digits minutes padded with 0
474
- * s: seconds
475
- * S: 2 digits seconds padded with 0
476
- * a: am or pm
477
- * anything else is inserted
478
- * if you need to insert some text, put it between {}
479
- *
480
- * @example
481
- *
482
- * 01/01/1970 11:25:00 with '{this is my demo date formatter: }H-i*M'
483
- * "this is my demo date formatter: 11-25*january"
484
- */
485
- export function formatIntlDate(date, fmt = _tr.global.date_format) {
486
- if (!date) {
487
- return '';
488
- }
489
- let now = {
490
- year: date.getFullYear(),
491
- month: date.getMonth() + 1,
492
- day: date.getDate(),
493
- wday: date.getDay(),
494
- hours: date.getHours(),
495
- minutes: date.getMinutes(),
496
- seconds: date.getSeconds(),
497
- milli: date.getMilliseconds()
498
- };
499
- let result = '';
500
- let esc = 0;
501
- for (let c of fmt) {
502
- if (c == '{') {
503
- if (++esc == 1) {
504
- continue;
505
- }
506
- }
507
- else if (c == '}') {
508
- if (--esc == 0) {
509
- continue;
510
- }
511
- }
512
- if (esc) {
513
- result += c;
514
- continue;
515
- }
516
- if (c == 'd') {
517
- result += now.day;
518
- }
519
- else if (c == 'D') {
520
- result += pad(now.day, -2);
521
- }
522
- else if (c == 'j') { // day short
523
- result += _tr.global.day_short[now.wday];
524
- }
525
- else if (c == 'J') { // day long
526
- result += _tr.global.day_long[now.wday];
527
- }
528
- else if (c == 'w') { // week
529
- result += date_calc_weeknum(date);
530
- }
531
- else if (c == 'W') { // week
532
- result += pad(date_calc_weeknum(date), -2);
533
- }
534
- else if (c == 'm') {
535
- result += now.month;
536
- }
537
- else if (c == 'M') {
538
- result += pad(now.month, -2);
539
- }
540
- else if (c == 'o') { // month short
541
- result += _tr.global.month_short[now.month - 1];
542
- }
543
- else if (c == 'O') { // month long
544
- result += _tr.global.month_long[now.month - 1];
545
- }
546
- else if (c == 'y' || c == 'Y') {
547
- result += pad(now.year, -4);
548
- }
549
- else if (c == 'a' || c == 'A') {
550
- result += now.hours < 12 ? 'am' : 'pm';
551
- }
552
- else if (c == 'h') {
553
- result += now.hours;
554
- }
555
- else if (c == 'H') {
556
- result += pad(now.hours, -2);
557
- }
558
- else if (c == 'i') {
559
- result += now.minutes;
560
- }
561
- else if (c == 'I') {
562
- result += pad(now.minutes, -2);
563
- }
564
- else if (c == 's') {
565
- result += now.seconds;
566
- }
567
- else if (c == 'S') {
568
- result += pad(now.seconds, -2);
569
- }
570
- else if (c == 'l') {
571
- result += now.milli;
572
- }
573
- else if (c == 'L') {
574
- result += pad(now.milli, -3);
575
- }
576
- else {
577
- result += c;
578
- }
579
- }
580
- return result;
581
- }
582
- export function calcAge(birth, ref) {
583
- if (ref === undefined) {
584
- ref = new Date();
585
- }
586
- if (!birth) {
587
- return 0;
588
- }
589
- let age = ref.getFullYear() - birth.getFullYear();
590
- if (ref.getMonth() < birth.getMonth() || (ref.getMonth() == birth.getMonth() && ref.getDate() < birth.getDate())) {
591
- age--;
592
- }
593
- return age;
594
- }
595
- Date.prototype.isSameDay = function (date) {
596
- return this.getDate() == date.getDate() && this.getMonth() == date.getMonth() && this.getFullYear() == date.getFullYear();
597
- };
598
- Date.prototype.hash = function () {
599
- return date_hash(this);
600
- };
601
- Date.prototype.clone = function () {
602
- return date_clone(this);
603
- };
604
- Date.prototype.weekNum = function () {
605
- return date_calc_weeknum(this);
606
- };
607
- Date.prototype.format = function (fmt) {
608
- return formatIntlDate(this, fmt);
609
- };
610
- Date.prototype.addDays = function (days) {
611
- this.setDate(this.getDate() + days);
612
- return this;
613
- };
614
- // :: FILE CREATION ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
615
- /**
616
- *
617
- * @param data data to export
618
- * @param mimetype - 'text/plain'
619
- */
620
- export function downloadData(data, mimetype, filename) {
621
- //if (data !== null && navigator.msSaveBlob) {
622
- // return navigator.msSaveBlob(new Blob([data], { type: mimetype }), filename);
623
- //}
624
- let blob = new Blob([data], { type: mimetype });
625
- let url = window.URL.createObjectURL(blob);
626
- let a = document.createElement("a");
627
- a.style['display'] = "none";
628
- a.href = url;
629
- a.download = filename;
630
- document.body.appendChild(a);
631
- a.click();
632
- window.URL.revokeObjectURL(url);
633
- }
634
- // :: MISC ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
635
- /**
636
- * check if a value is a string
637
- * @param val
638
- */
639
- export function isString(val) {
640
- return typeof val === 'string';
641
- }
642
- /**
643
- * check is a value is an array
644
- * @param val
645
- */
646
- export function isArray(val) {
647
- return val instanceof Array;
648
- }
649
- /**
650
- *
651
- */
652
- export function isFunction(val) {
653
- return val instanceof Function;
654
- }
655
- /**
656
- *
657
- */
658
- export function isLiteralObject(val) {
659
- return (!!val) && (val.constructor === Object);
660
- }
661
- ;
662
- /**
663
- * prepend 0 to a value to a given length
664
- * @param value
665
- * @param length
666
- */
667
- export function pad(what, size, ch = '0') {
668
- let value;
669
- if (!isString(what)) {
670
- value = '' + what;
671
- }
672
- else {
673
- value = what;
674
- }
675
- if (size > 0) {
676
- return value.padEnd(size, ch);
677
- }
678
- else {
679
- return value.padStart(-size, ch);
680
- }
681
- }
682
- /**
683
- * return true if val is a finite number
684
- */
685
- export function isNumber(val) {
686
- return typeof val === 'number' && isFinite(val);
687
- }
688
- /**
689
- *
690
- * @param name
691
- */
692
- export function waitFontLoading(name) {
693
- // tip for waiting font loading:
694
- // by default, body is created invisible ((opacity = 0)
695
- // we create a div inside with the font we need to wait the loading
696
- // as soon as the font is loaded, it's size will change, the browser end font loading
697
- // we can remove the div.
698
- // pitfall: if the font is already loaded, ne never end.
699
- // @review that
700
- let ct = document.createElement('div');
701
- ct.style.position = 'absolute';
702
- ct.style.fontFamily = name;
703
- ct.style.fontSize = '44px';
704
- ct.style.opacity = '0.001';
705
- ct.innerText = 'X';
706
- document.body.appendChild(ct);
707
- return new Promise((resolve) => {
708
- let irc = ct.getBoundingClientRect();
709
- let tm = setInterval(() => {
710
- let nrc = ct.getBoundingClientRect();
711
- if (nrc.height != irc.height) {
712
- clearInterval(tm);
713
- document.body.removeChild(ct);
714
- resolve();
715
- }
716
- }, 0);
717
- });
718
- }
719
- /**
720
- *
721
- * @param fn
722
- * @param tm
723
- *
724
- * @example:
725
- *
726
- * defer( ( ) => {
727
- * console.log( x );
728
- * } )( );
729
- */
730
- export function deferCall(fn, tm = 0, ...args) {
731
- setTimeout(fn, tm, ...args);
732
- }
733
- /**
734
- *
735
- */
736
- export function asap(cb) {
737
- requestAnimationFrame(cb);
738
- }
739
- /**
740
- * micro md to html
741
- *
742
- * understand:
743
- * **bold**
744
- * *italic*
745
- *
746
- * > quote
747
- * - list
748
- * # title lvl 1
749
- * ## title lvl 2
750
- * ### title lvl 3 ...
751
- *
752
- */
753
- export function markdownToHtml(text) {
754
- if (!text) {
755
- return '';
756
- }
757
- let lines = text.split('\n');
758
- let state = 'para';
759
- let div = 'p';
760
- let result = [];
761
- lines.forEach((l) => {
762
- let txt = l.trim();
763
- if (state == 'para') {
764
- // entree en mode list
765
- if (txt[0] == '-') {
766
- txt = txt.substr(1);
767
- result.push('<ul>');
768
- state = 'list';
769
- div = 'li';
770
- }
771
- else if (txt[0] == '>') {
772
- txt = txt.substr(1);
773
- result.push('<blockquote>');
774
- state = 'quote';
775
- div = 'p';
776
- }
777
- else if (txt[0] == '#') {
778
- let lvl = 0;
779
- do {
780
- txt = txt.substr(1);
781
- lvl++;
782
- } while (txt[0] == '#' && lvl < 5);
783
- div = 'h' + lvl;
784
- state = 'title';
785
- }
786
- }
787
- else if (state == 'list') {
788
- // sortie du mode list
789
- if (txt[0] != '-') {
790
- result.push('</ul>');
791
- state = 'para';
792
- div = 'p';
793
- }
794
- else {
795
- txt = txt.substr(1);
796
- }
797
- }
798
- else if (state == 'quote') {
799
- // sortie du mode blockquote
800
- if (txt[0] != '>') {
801
- result.push('</blockquote>');
802
- state = 'para';
803
- div = 'p';
804
- }
805
- else {
806
- txt = txt.substr(1);
807
- }
808
- }
809
- let reBold = /\*\*([^*]+)\*\*/gi;
810
- txt = escapeHtml(txt, false);
811
- txt = txt.replace(reBold, (sub, ...a) => {
812
- return '<b>' + sub.substr(2, sub.length - 4) + '</b>';
813
- });
814
- let reItalic = /\*([^*]+)\*/gi;
815
- txt = txt.replace(reItalic, (sub, ...a) => {
816
- return '<i>' + sub.substr(1, sub.length - 2) + '</i>';
817
- });
818
- // keep empty lines
819
- if (txt == '') {
820
- txt = '&nbsp;';
821
- }
822
- result.push(`<${div}>` + txt + `</${div}>`);
823
- if (state == 'title') {
824
- state = 'para';
825
- div = 'p';
826
- }
827
- });
828
- if (state == 'list') {
829
- result.push('</ul>');
830
- }
831
- else if (state == 'quote') {
832
- result.push('</blockquote>');
833
- }
834
- return result.join('');
835
- }
836
- /**
837
- *
838
- */
839
- export class NetworkError extends Error {
840
- m_code;
841
- constructor(a, b) {
842
- if (a instanceof Response) {
843
- super(a.statusText);
844
- this.m_code = a.status;
845
- }
846
- else {
847
- super(b);
848
- this.m_code = a;
849
- }
850
- }
851
- get code() {
852
- return this.m_code;
853
- }
854
- }
855
- /**
856
- * return the mouse pos in client coordinates
857
- * handle correctly touch & mouse
858
- */
859
- export function getMousePos(ev, fromDoc) {
860
- let x_name = 'offsetX', y_name = 'offsetY';
861
- if (fromDoc) {
862
- x_name = 'clientX';
863
- y_name = 'clientY';
864
- }
865
- if (ev.type == 'mousemove' || ev.type == 'mousedown' || ev.type == 'mouseup') {
866
- let em = ev;
867
- return new Point(em[x_name], em[y_name]);
868
- }
869
- else if (ev.type == 'pointermove' || ev.type == 'pointerdown' || ev.type == 'pointerup') {
870
- let em = ev;
871
- return new Point(em[x_name], em[y_name]);
872
- }
873
- else if (ev.type == 'touchmove' || ev.type == 'touchstart') {
874
- let et = ev;
875
- return new Point(et.touches[0][x_name], et.touches[0][y_name]);
876
- }
877
- else if (ev.type == 'contextmenu') {
878
- let em = ev;
879
- return new Point(em[x_name], em[y_name]);
880
- }
881
- else {
882
- return new Point(0, 0);
883
- }
884
- }
885
- /**
886
- * clamp a value
887
- * @param v - value to clamp
888
- * @param min - min value
889
- * @param max - max value
890
- * @returns clamped value
891
- */
892
- export function clamp(v, min, max) {
893
- return Math.min(Math.max(v, min), max);
894
- }
895
- // :: HTML strings ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
896
- export class HtmlString extends String {
897
- constructor(text) { super(text); }
898
- static from(text) {
899
- return new HtmlString(text);
900
- }
901
- }
902
- export function html(a, ...b) {
903
- return HtmlString.from(String.raw(a, ...b));
904
- }
905
- export function isHtmlString(val) {
906
- return val instanceof HtmlString;
907
- }
908
- // :: CLIPBOARD ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
909
- export class Clipboard {
910
- static copy(data) {
911
- if (navigator.clipboard) {
912
- navigator.clipboard.writeText(JSON.stringify(data));
913
- }
914
- }
915
- static paste(cb) {
916
- if (navigator.clipboard) {
917
- navigator.clipboard.readText().then(v => cb(v));
918
- }
919
- else {
920
- console.error('no clipboard, are you in https ?');
921
- }
922
- }
923
- }
924
- // :: CRC32 ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
925
- /**
926
- * Calculates the CRC32 checksum of a string.
927
- * taken from: https://gist.github.com/wqli78/1330293/6d85cc967f32cccfcbad94ae7d088a3dcfc14bd9
928
- *
929
- * @param {String} str
930
- * @param {Boolean} hex
931
- * @return {String} checksum
932
- * @api public
933
- */
934
- export function crc32(str) {
935
- let crc = ~0;
936
- for (let i = 0, l = str.length; i < l; i++) {
937
- crc = (crc >>> 8) ^ crc32tab[(crc ^ str.charCodeAt(i)) & 0xff];
938
- }
939
- return Math.abs(crc ^ -1);
940
- }
941
- var crc32tab = [
942
- 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba,
943
- 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3,
944
- 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
945
- 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91,
946
- 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de,
947
- 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
948
- 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec,
949
- 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5,
950
- 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
951
- 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b,
952
- 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940,
953
- 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
954
- 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116,
955
- 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f,
956
- 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
957
- 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d,
958
- 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a,
959
- 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
960
- 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818,
961
- 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01,
962
- 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
963
- 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457,
964
- 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c,
965
- 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
966
- 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2,
967
- 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb,
968
- 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
969
- 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9,
970
- 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086,
971
- 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
972
- 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4,
973
- 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad,
974
- 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
975
- 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683,
976
- 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8,
977
- 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
978
- 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe,
979
- 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7,
980
- 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
981
- 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5,
982
- 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252,
983
- 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
984
- 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60,
985
- 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79,
986
- 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
987
- 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f,
988
- 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04,
989
- 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
990
- 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a,
991
- 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713,
992
- 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
993
- 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21,
994
- 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e,
995
- 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
996
- 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c,
997
- 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45,
998
- 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
999
- 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db,
1000
- 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0,
1001
- 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
1002
- 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6,
1003
- 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf,
1004
- 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
1005
- 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d
1006
- ];
1007
- // :: MIXINS ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
1008
- /**
1009
- * taken from this excellent article:
1010
- * https://justinfagnani.com/2015/12/21/real-mixins-with-javascript-classes/
1011
- *
1012
- * @example:
1013
- * class MyClass extends mix(MyBaseClass).with(Mixin1, Mixin2) {
1014
- * }
1015
- **/
1016
- export const mix = (superclass) => new MixinBuilder(superclass);
1017
- class MixinBuilder {
1018
- superclass;
1019
- constructor(superclass) {
1020
- this.superclass = superclass;
1021
- }
1022
- with(...mixins) {
1023
- return mixins.reduce((c, mixin) => mixin(c), this.superclass);
1024
- }
1025
- }
1026
- /**
1027
- * @example
1028
- *
1029
- * ```
1030
- * const cls = classNames( 'class1 class2', {
1031
- * 'class3': false,
1032
- * 'class4': true,
1033
- * });
1034
- *
1035
- * // even shorter
1036
- * const class1 = true, class2 = false;
1037
- * const cls = classNames( { class1, class2 } ); // cls = "class1"
1038
- *
1039
- * ```
1040
- *
1041
- * @returns
1042
- */
1043
- export function classNames(...args) {
1044
- let result = '';
1045
- for (const cls of args) {
1046
- if (typeof cls === 'string') {
1047
- result += ' ' + cls;
1048
- }
1049
- else if (cls) {
1050
- for (const c in cls) {
1051
- if (cls[c])
1052
- result += ' ' + c;
1053
- }
1054
- }
1055
- }
1056
- return result;
1057
- }
1058
- export function generatePassword(length, rules) {
1059
- if (!length || length == undefined) {
1060
- length = 8;
1061
- }
1062
- if (!rules) {
1063
- rules = [
1064
- { chars: "abcdefghijklmnopqrstuvwxyz", min: 3 },
1065
- { chars: "ABCDEFGHIJKLMNOPQRSTUVWXYZ", min: 2 },
1066
- { chars: "0123456789", min: 2 },
1067
- { chars: "!@#$*|%+-_.;", min: 2 } // At least 1 special char
1068
- ];
1069
- }
1070
- let allChars = "";
1071
- let allMin = 0;
1072
- rules.forEach(function (rule) {
1073
- allChars += rule.chars;
1074
- allMin += rule.min;
1075
- });
1076
- if (length < allMin) {
1077
- length = allMin;
1078
- }
1079
- rules.push({ chars: allChars, min: length - allMin });
1080
- let pswd = "";
1081
- rules.forEach(function (rule) {
1082
- if (rule.min > 0) {
1083
- pswd += shuffle(rule.chars, rule.min);
1084
- }
1085
- });
1086
- return shuffle(pswd);
1087
- }
1088
- function shuffle(str, maxlength) {
1089
- let shuffled = str.split('').sort(() => {
1090
- return 0.5 - Math.random();
1091
- }).join('');
1092
- if (maxlength > 0) {
1093
- shuffled = shuffled.substr(0, maxlength);
1094
- }
1095
- return shuffled;
1096
- }