@sankhyalabs/ezui 1.1.96 → 1.1.97

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 (33) hide show
  1. package/dist/cjs/UnitMetadata-2e11c5d3.js +1310 -0
  2. package/dist/cjs/ez-calendar_14.cjs.entry.js +58 -29
  3. package/dist/cjs/ez-grid.cjs.entry.js +32 -16
  4. package/dist/cjs/ez-icon.cjs.entry.js +2 -2
  5. package/dist/cjs/ez-modal_2.cjs.entry.js +1 -1
  6. package/dist/cjs/ez-popover.cjs.entry.js +1 -1
  7. package/dist/cjs/ez-time-input.cjs.entry.js +6 -6
  8. package/dist/collection/components/ez-form/DataBinder.js +13 -0
  9. package/dist/collection/components/ez-form/fieldbuilder/tpl/SearchInput.tpl.js +1 -1
  10. package/dist/collection/components/ez-icon/ez-icon.css +5 -0
  11. package/dist/custom-elements/index.js +208 -6311
  12. package/dist/esm/UnitMetadata-8b1bbaa2.js +1304 -0
  13. package/dist/esm/ez-calendar_14.entry.js +31 -2
  14. package/dist/esm/ez-grid.entry.js +17 -1
  15. package/dist/esm/ez-icon.entry.js +2 -2
  16. package/dist/esm/ez-modal_2.entry.js +1 -1
  17. package/dist/esm/ez-popover.entry.js +1 -1
  18. package/dist/esm/ez-time-input.entry.js +1 -1
  19. package/dist/ezui/ezui.esm.js +1 -1
  20. package/dist/ezui/p-07b60fe9.js +1 -0
  21. package/dist/ezui/p-2336c9ce.entry.js +1 -0
  22. package/dist/ezui/{p-2617733e.entry.js → p-45a25c30.entry.js} +1 -1
  23. package/dist/ezui/{p-6714a1b2.entry.js → p-532b5b24.entry.js} +10 -10
  24. package/dist/ezui/p-614fbb4e.entry.js +1 -0
  25. package/dist/ezui/{p-a943d501.entry.js → p-7165ac4f.entry.js} +1 -1
  26. package/dist/ezui/{p-ef393d36.entry.js → p-d3f87e18.entry.js} +1 -1
  27. package/dist/types/components/ez-form/DataBinder.d.ts +1 -0
  28. package/package.json +2 -2
  29. package/dist/cjs/index-6164b259.js +0 -7460
  30. package/dist/esm/index-74a9c220.js +0 -7452
  31. package/dist/ezui/p-38589c64.entry.js +0 -1
  32. package/dist/ezui/p-b139372f.entry.js +0 -1
  33. package/dist/ezui/p-c6762896.js +0 -1
@@ -0,0 +1,1304 @@
1
+ const NUMBERINPUTS_REGEX_SCIENTIFIC_PARTS = /^([+-])?(\d+).?(\d*)[eE]([-+]?\d+)$/;
2
+ /**
3
+ * `NumberUtils` é uma biblioteca para manipulação de números
4
+ *
5
+ * `Métodos`:
6
+ *
7
+ * @stringToNumber: converte um número em formato de string em um valor numérico nativo do javascript
8
+ * @format: arredonda um número em formato de string baseado nos parâmetros "presision" e "prettyPrecision";
9
+ */
10
+ class NumberUtils {
11
+ }
12
+ /**
13
+ * @stringToNumber: converte um numero em formato de string em numero
14
+ *
15
+ * @param value numero em formato de string a ser convertido (Importante: formato PT-BR ou já em formato numérico: ######.##)
16
+ *
17
+ * @returns string based number
18
+ *
19
+ * @Exemples
20
+ * @"100,12" | 100.12
21
+ * @"100.12" | 100.12
22
+ * @"-100,12" | -100.12
23
+ * @"R$100,12" | 100.12
24
+ * @"-R$100,12" | -100.12
25
+ * @"string" | NaN
26
+ */
27
+ NumberUtils.stringToNumber = (value) => {
28
+ if (value === '' || value === null || value === undefined) {
29
+ return NaN;
30
+ }
31
+ if (value) {
32
+ value = value.toString();
33
+ var negative = (value.charAt(0) === '-');
34
+ if (!NUMBERINPUTS_REGEX_SCIENTIFIC_PARTS.test(value)) {
35
+ value = value.replace(/[^\d.,]/g, '');
36
+ }
37
+ else {
38
+ value = value.replace(/^-/g, '');
39
+ }
40
+ //In case of simple string such as: "@@@@@@@"
41
+ if (value === '') {
42
+ return Number(NaN);
43
+ }
44
+ var indexV = value.indexOf(',');
45
+ var indexP = value.indexOf('.');
46
+ if (indexP > indexV) {
47
+ value = value.replace(',', '');
48
+ }
49
+ else if (indexP < indexV) {
50
+ value = value.replace(/\./g, '@').replace(',', '.').replace(/@/g, '');
51
+ }
52
+ if (negative) {
53
+ value = '-' + value;
54
+ }
55
+ }
56
+ return Number(value);
57
+ };
58
+ /**
59
+ * @format: converte um numero em formato de string em um numero em formato de string formatado de acordo com os parametros de "precision" e "prettyPrecision"
60
+ *
61
+ * @param value numero em formato de string a ser convertido (Importante: formato PT-BR ou já em formato numérico<sem separadors de milhares>: ######.##)
62
+ * @param precision (numero de decimais)
63
+ * @param prettyPrecision (numero de zeros nos decimais)
64
+ *
65
+ * @returns numero em formato de string formatado em PT-BR
66
+ */
67
+ NumberUtils.format = (value, precision, prettyPrecision = NaN) => {
68
+ if (value === '' || value === undefined || value === "NaN") {
69
+ return NaN.toString();
70
+ }
71
+ let newValue = NumberUtils.stringToNumber(value);
72
+ if (newValue === NaN) {
73
+ return NaN.toString();
74
+ }
75
+ //Validation "precision":
76
+ // Case1: precision < 0 => does not use precision
77
+ // Case2: presicion not int => does not use precision
78
+ if (precision < 0 || Math.abs(Math.round(precision * 1) / 1) !== precision) {
79
+ //Once stringToNumber returns number format, we need to change to pt-br
80
+ return NumberUtils.changeFormat(newValue.toString());
81
+ }
82
+ //Validation "prettyPrecision"
83
+ let prettyPrecisionInternal = 0;
84
+ // Case1: prettyPrecision < 0 => prettyPrecision does not change de format that means: prettyPrecisionInternal = precision;
85
+ // Case2: prettyPrecision not int => prettyPrecision does not change de format that means: prettyPrecisionInternal = precision;
86
+ if (prettyPrecision === NaN || Math.abs(Math.round(prettyPrecision * 1) / 1) !== prettyPrecision) {
87
+ prettyPrecisionInternal = precision;
88
+ }
89
+ else {
90
+ prettyPrecisionInternal = prettyPrecision;
91
+ }
92
+ let newValueStr;
93
+ newValueStr = (Math.round(newValue * Math.pow(10, precision)) / Math.pow(10, precision)).toLocaleString('pt-br', { minimumFractionDigits: precision });
94
+ //prettyPrecision
95
+ const varSettingPP = precision - prettyPrecisionInternal;
96
+ if (varSettingPP > 0) {
97
+ for (let i = 0; i < varSettingPP; i++) {
98
+ if (newValueStr.substring(newValueStr.length - 1) == "0" && precision > 0) {
99
+ newValueStr = newValueStr.substring(0, newValueStr.length - 1);
100
+ }
101
+ }
102
+ }
103
+ //in Case "." or "," in the end of the string
104
+ if (newValueStr.substring(newValueStr.length - 1) == "." || newValueStr.substring(newValueStr.length - 1) == ",") {
105
+ newValueStr = newValueStr.substring(0, newValueStr.length - 1);
106
+ }
107
+ return newValueStr;
108
+ };
109
+ /**
110
+ * @keepOnlyDecimalSeparator: retira os separadores de milhar de um número em formato de string
111
+ *
112
+ * @param value numero em formato de string a ser convertido
113
+ * @param formatnumber (formatação de ENTRADA e SAÍDA do utilitário: pt-BR="###.###,##" en-US="###,###.##"; Default: "pt-BR")
114
+ *
115
+ * @returns numero em formato de string formatado apenas com separador decimal
116
+ */
117
+ NumberUtils.keepOnlyDecimalSeparator = (value, formatnumber = 'pt-BR') => {
118
+ //Formatting formatnumber to be able to get lowercases
119
+ formatnumber = formatnumber.toUpperCase();
120
+ //Formatting value following formatnumber parameter
121
+ //keep only decimal character in order to correct format the string
122
+ //This transformation is due the "stringtoNumber" method is a general method that tries to convert all formated strings
123
+ if (formatnumber === 'EN-US') {
124
+ value = value.replace(/\,/g, '');
125
+ }
126
+ else {
127
+ value = value.replace(/\./g, '');
128
+ }
129
+ return value;
130
+ };
131
+ /**
132
+ * @changeFormat: troca o formato do numero string de "PT-BR" para "EN-US" e vice-versa
133
+ *
134
+ * @param value numero em formato de string a ser convertido
135
+ *
136
+ * @returns numero em formato de string formatado de "PT-BR" para "EN-US" e vice-versa
137
+ */
138
+ NumberUtils.changeFormat = (value) => {
139
+ //Formatting output following formatnumber
140
+ return value.replace(/\./g, '_').replace(/\,/g, '.').replace(/\_/g, ',');
141
+ };
142
+
143
+ /**
144
+ * `MaskFormatter` é usado para formatar strings. Seu comportamento
145
+ * é controlado pela formato do atributo `mask` que especifica quais
146
+ * caracteres são válidos e onde devem estar posicionados, intercalando-os
147
+ * com eventuais caracteres literais expressados no padrão informado.
148
+ * Sua implementação é inspirada pela implementação em Java do [MaskFormatter](https://docs.oracle.com/javase/7/docs/api/javax/swing/text/MaskFormatter.html).
149
+ *
150
+ * Para o padrão da máscara podem ser usados os seguintes caracteres especiais:
151
+ *
152
+ * | Caractere | Comportamento |
153
+ * |:---------:|-------------------------------------------------------------------------------------------------------------|
154
+ * | # | Qualquer número |
155
+ * | ' | "Escapa" o caractere que vem na sequência. Útil quando desejamos converter um caractere especial em literal.|
156
+ * | U | Qualquer letra. Transforma letras maiúsculas em maiúsculas. |
157
+ * | L | Qualquer letra. Transforma letras maiúsculas em minúsculas. |
158
+ * | A | Qualquer letra ou número. |
159
+ * | ? | Qualquer letra. Preserva maiúsculas e minúsculas. |
160
+ * | * | Qualquer caractere. |
161
+ *
162
+ * Os demais caracteres presentes no padrão serão tratados como literais, isto é,
163
+ * serão apenas inseridos naquela posição.
164
+ *
165
+ * Quando o o valor a ser formatado é menor que a máscara um 'placeHolder'
166
+ * será inserido em cada posição ausente, completando a formatação.
167
+ * Por padrão será usado um espaço em branco como 'placeHolder' mas
168
+ * esse valor pode ser alterado.
169
+ *
170
+ * For por exemplo:
171
+ * '''
172
+ * const formatter: MaskFormatter = new MaskFormatter("###-####");
173
+ * formatter.placeholder = '_';
174
+ * console.log(formatter.format("123"));
175
+ * '''
176
+ * resultaria na string '123-____'.
177
+ *
178
+ * ##Veja mais alguns exemplos:
179
+ * |Padrão |Máscara |Entrada |Saída |
180
+ * |----------------|------------------|--------------|------------------|
181
+ * |Telefone |(##) ####-#### |3432192515 |(34) 3219-2515 |
182
+ * |CPF |###.###.###-## |12345678901 |123.456.789-01 |
183
+ * |CNPJ |##.###.###/####-##|12345678901234|12.345.678/9012-34|
184
+ * |CEP |##.###-### |12345678 |12.345-678 |
185
+ * |PLACA (veículo) |UUU-#### |abc1234 |ABC-1234 |
186
+ * |Cor RGB |'#AAAAAA |00000F0 |#0000F0 |
187
+ *
188
+ */
189
+ class MaskFormatter {
190
+ constructor(mask) {
191
+ this._mask = '';
192
+ this._maskChars = new Array();
193
+ /**
194
+ * Determina qual caractere será usado dos caracteres não presentes no valor
195
+ * ou seja, aqueles que o usuário ainda não informou. Por padrão usamos um espaço
196
+ */
197
+ this.placeholder = ' ';
198
+ this.mask = mask;
199
+ }
200
+ /**
201
+ * Setter para mask. Trata-se do padrão que se espera ao formatar o texto.
202
+ */
203
+ set mask(mask) {
204
+ this._mask = mask;
205
+ this.updateInternalMask();
206
+ }
207
+ /**
208
+ * Getter para mask
209
+ *
210
+ * @return A última máscara informada.
211
+ */
212
+ get mask() {
213
+ return this._mask;
214
+ }
215
+ /**
216
+ * Formata a string passada baseada na máscara definda pelo atributo mask.
217
+ *
218
+ * @param value Valor a ser formatado
219
+ * @return O valor processado de acordo com o padrão
220
+ */
221
+ format(value) {
222
+ let result = '';
223
+ const index = [0];
224
+ let counter = 0;
225
+ const maxCounter = this._maskChars.length;
226
+ while (counter < maxCounter) {
227
+ result = this._maskChars[counter].append(result, value, index);
228
+ counter++;
229
+ }
230
+ return result;
231
+ }
232
+ /**
233
+ * Preparamos a formatação internamente de acordo com o padrão.
234
+ */
235
+ updateInternalMask() {
236
+ this._maskChars.length = 0;
237
+ if (this.mask != null) {
238
+ let counter = 0;
239
+ const maxCounter = this.mask.length;
240
+ while (counter < maxCounter) {
241
+ let maskChar = this.mask.charAt(counter);
242
+ switch (maskChar) {
243
+ case MaskFormatter.DIGIT_KEY:
244
+ this._maskChars.push(new MaskFormatter.DigitMaskCharacter(this, maskChar));
245
+ break;
246
+ case MaskFormatter.LITERAL_KEY:
247
+ if (++counter < maxCounter) {
248
+ maskChar = this.mask.charAt(counter);
249
+ this._maskChars.push(new MaskFormatter.LiteralCharacter(this, maskChar));
250
+ }
251
+ break;
252
+ case MaskFormatter.UPPERCASE_KEY:
253
+ this._maskChars.push(new MaskFormatter.UpperCaseCharacter(this, maskChar));
254
+ break;
255
+ case MaskFormatter.LOWERCASE_KEY:
256
+ this._maskChars.push(new MaskFormatter.LowerCaseCharacter(this, maskChar));
257
+ break;
258
+ case MaskFormatter.ALPHA_NUMERIC_KEY:
259
+ this._maskChars.push(new MaskFormatter.AlphaNumericCharacter(this, maskChar));
260
+ break;
261
+ case MaskFormatter.CHARACTER_KEY:
262
+ this._maskChars.push(new MaskFormatter.CharCharacter(this, maskChar));
263
+ break;
264
+ case MaskFormatter.ANYTHING_KEY:
265
+ this._maskChars.push(new MaskFormatter.MaskCharacter(this, maskChar));
266
+ break;
267
+ default:
268
+ this._maskChars.push(new MaskFormatter.LiteralCharacter(this, maskChar));
269
+ break;
270
+ }
271
+ counter++;
272
+ }
273
+ }
274
+ }
275
+ }
276
+ MaskFormatter.DIGIT_KEY = "#";
277
+ MaskFormatter.LITERAL_KEY = "'";
278
+ MaskFormatter.UPPERCASE_KEY = "U";
279
+ MaskFormatter.LOWERCASE_KEY = "L";
280
+ MaskFormatter.ALPHA_NUMERIC_KEY = "A";
281
+ MaskFormatter.CHARACTER_KEY = "?";
282
+ MaskFormatter.ANYTHING_KEY = "*";
283
+ //
284
+ // Classes internas usadas para representar a máscara.
285
+ //
286
+ MaskFormatter.MaskCharacter = class {
287
+ constructor(maskFormatter, type) {
288
+ this.maskFormatter = maskFormatter;
289
+ this.type = type;
290
+ }
291
+ /**
292
+ * Cada subclasse deve sobrescrever o retornando true, caso represente
293
+ * um caractere literal. Por padrão o retorno é false.
294
+ */
295
+ isLiteral() {
296
+ return false;
297
+ }
298
+ /**
299
+ * Returns true if <code>aChar</code> is a valid reprensentation of
300
+ * the receiver. The default implementation returns true if the
301
+ * receiver represents a literal character and <code>getChar</code>
302
+ * == aChar. Otherwise, this will return true is <code>aChar</code>
303
+ * is contained in the valid characters and not contained
304
+ * in the invalid characters.
305
+ */
306
+ isValidCharacter(aChar) {
307
+ if (this.isLiteral()) {
308
+ return (this.getChar(aChar) == aChar);
309
+ }
310
+ aChar = this.getChar(aChar);
311
+ return true;
312
+ }
313
+ /**
314
+ * Returns the character to insert for <code>aChar</code>. The
315
+ * default implementation returns <code>aChar</code>. Subclasses
316
+ * that wish to do some sort of mapping, perhaps lower case to upper
317
+ * case should override this and do the necessary mapping.
318
+ */
319
+ getChar(aChar) {
320
+ return aChar;
321
+ }
322
+ /**
323
+ * Appends the necessary character in <code>formatting</code> at
324
+ * <code>index</code> to <code>buff</code>.
325
+ */
326
+ append(result, formatting, index) {
327
+ const inString = index[0] < formatting.length;
328
+ const aChar = inString ? formatting.charAt(index[0]) : '';
329
+ if (this.isLiteral()) {
330
+ const literal = this.getChar(aChar);
331
+ result += literal;
332
+ if (literal === aChar) {
333
+ index[0] = index[0] + 1;
334
+ }
335
+ }
336
+ else if (index[0] >= formatting.length) {
337
+ result += this.maskFormatter.placeholder;
338
+ index[0] = index[0] + 1;
339
+ }
340
+ else if (this.isValidCharacter(aChar)) {
341
+ result += this.getChar(aChar);
342
+ index[0] = index[0] + 1;
343
+ }
344
+ else {
345
+ throw new Error(`Valor inválido: "${aChar}". Na posição ${index[0] + 1} espera-se ${this.getFormatMessage()}.`);
346
+ }
347
+ return result;
348
+ }
349
+ getFormatMessage() {
350
+ let message;
351
+ switch (this.type) {
352
+ case MaskFormatter.UPPERCASE_KEY:
353
+ case MaskFormatter.LOWERCASE_KEY:
354
+ case MaskFormatter.CHARACTER_KEY:
355
+ message = 'uma letra';
356
+ break;
357
+ case MaskFormatter.DIGIT_KEY:
358
+ message = 'um número';
359
+ break;
360
+ case MaskFormatter.ALPHA_NUMERIC_KEY:
361
+ message = 'uma letra ou um número';
362
+ break;
363
+ default:
364
+ message = '';
365
+ }
366
+ return message;
367
+ }
368
+ };
369
+ MaskFormatter.LiteralCharacter = class extends MaskFormatter.MaskCharacter {
370
+ constructor(maskFormatter, fixedChar) {
371
+ super(maskFormatter, fixedChar);
372
+ this._fixedChar = fixedChar;
373
+ }
374
+ isLiteral() {
375
+ return true;
376
+ }
377
+ getChar(aChar) {
378
+ return this._fixedChar;
379
+ }
380
+ };
381
+ MaskFormatter.DigitMaskCharacter = class extends MaskFormatter.MaskCharacter {
382
+ isValidCharacter(aChar) {
383
+ return (this.isDigit(aChar) && super.isValidCharacter(aChar));
384
+ }
385
+ isDigit(char) {
386
+ return char >= '0' && char <= '9';
387
+ }
388
+ };
389
+ MaskFormatter.UpperCaseCharacter = class extends MaskFormatter.MaskCharacter {
390
+ isValidCharacter(aChar) {
391
+ return (/[a-z]/i.test(aChar) && super.isValidCharacter(aChar));
392
+ }
393
+ getChar(aChar) {
394
+ return aChar.toUpperCase();
395
+ }
396
+ };
397
+ MaskFormatter.LowerCaseCharacter = class extends MaskFormatter.MaskCharacter {
398
+ isValidCharacter(aChar) {
399
+ return (/[a-z]/i.test(aChar) && super.isValidCharacter(aChar));
400
+ }
401
+ getChar(aChar) {
402
+ return aChar.toLocaleLowerCase();
403
+ }
404
+ };
405
+ MaskFormatter.AlphaNumericCharacter = class extends MaskFormatter.MaskCharacter {
406
+ isValidCharacter(aChar) {
407
+ //FIXME: talvez seja problema usar regex aqui... avaliar se existe forma mais barata
408
+ return (/[a-z0-9]/i.test(aChar)) && super.isValidCharacter(aChar);
409
+ }
410
+ };
411
+ MaskFormatter.CharCharacter = class extends MaskFormatter.MaskCharacter {
412
+ isValidCharacter(aChar) {
413
+ //FIXME: talvez seja problema usar regex aqui... avaliar se existe forma mais barata
414
+ return (/[a-z]/i.test(aChar) && super.isValidCharacter(aChar));
415
+ }
416
+ };
417
+
418
+ /**
419
+ * `TimeFormatter` é um utilitário para formatação de strings desformatadas em strings válidas de horários
420
+ */
421
+ class TimeFormatter {
422
+ /**
423
+ * @prepareValue: converts an unformated time string into a formatted time.
424
+ *
425
+ * @param value unformated time string to convert
426
+ *
427
+ * @returns formatted time string
428
+ *
429
+ * @Exemples
430
+ * @"1012" | "10:12"
431
+ * @"10:12" | "10:12:00"
432
+ * @"100112" | "10:01:12"
433
+ */
434
+ static prepareValue(value, showSeconds) {
435
+ if (value && value.length > 0 && value != "NaN") {
436
+ let validationValue = value.replace(/:/g, "");
437
+ if (showSeconds) {
438
+ this._maskFormatter.mask = "##:##:##";
439
+ if (validationValue.length < 6) {
440
+ while (validationValue.length < 6) {
441
+ validationValue = "0".concat(validationValue);
442
+ }
443
+ }
444
+ }
445
+ else {
446
+ this._maskFormatter.mask = "##:##";
447
+ if (validationValue.length < 4) {
448
+ while (validationValue.length < 4) {
449
+ validationValue = "0".concat(validationValue);
450
+ }
451
+ }
452
+ }
453
+ if (this._maskFormatter) {
454
+ try {
455
+ value = this._maskFormatter.format(validationValue);
456
+ return value;
457
+ }
458
+ catch (e) {
459
+ throw new Error(e.message);
460
+ }
461
+ }
462
+ }
463
+ return '';
464
+ }
465
+ /**
466
+ * @validateTime: validates if an input string has the corect time format.
467
+ *
468
+ * @param value input string to validate
469
+ *
470
+ * @returns true or false
471
+ *
472
+ * @Exemples
473
+ * @"1012" | true
474
+ * @"14e4" | false
475
+ * @"2624" | false
476
+ */
477
+ static validateTime(value, showSeconds) {
478
+ let isValid = true;
479
+ if (value) {
480
+ let validationValue = value.replace(/:/g, "");
481
+ if (showSeconds) {
482
+ if (!["1", "2", "0"].includes(validationValue[0])) {
483
+ isValid = false;
484
+ }
485
+ if (!["0", "1", "2", "3", "4", "5"].includes(validationValue[2])) {
486
+ isValid = false;
487
+ }
488
+ if (!["0", "1", "2", "3", "4", "5"].includes(validationValue[4])) {
489
+ isValid = false;
490
+ }
491
+ if (validationValue[0] == "2" && !["0", "1", "2", "3"].includes(validationValue[1])) {
492
+ isValid = false;
493
+ }
494
+ }
495
+ else {
496
+ if (!["1", "2", "0"].includes(validationValue[0])) {
497
+ isValid = false;
498
+ }
499
+ if (!["0", "1", "2", "3", "4", "5"].includes(validationValue[2])) {
500
+ isValid = false;
501
+ }
502
+ if (validationValue[0] == "2" && !["0", "1", "2", "3"].includes(validationValue[1])) {
503
+ isValid = false;
504
+ }
505
+ }
506
+ }
507
+ else {
508
+ isValid = false;
509
+ }
510
+ return isValid;
511
+ }
512
+ }
513
+ TimeFormatter._maskFormatter = new MaskFormatter("##:##");
514
+
515
+ /**
516
+ * Representa as propriedades necessárias para se executar uma requisição.
517
+ */
518
+ /** Representa os verbos HTTP suportados */
519
+ var Method;
520
+ (function (Method) {
521
+ Method[Method["GET"] = 0] = "GET";
522
+ Method[Method["PUT"] = 1] = "PUT";
523
+ Method[Method["POST"] = 2] = "POST";
524
+ Method[Method["DELETE"] = 3] = "DELETE";
525
+ })(Method || (Method = {}));
526
+
527
+ var DataType;
528
+ (function (DataType) {
529
+ DataType["NUMBER"] = "NUMBER";
530
+ DataType["DATE"] = "DATE";
531
+ DataType["TEXT"] = "TEXT";
532
+ DataType["BOOLEAN"] = "BOOLEAN";
533
+ DataType["OBJECT"] = "OBJECT";
534
+ })(DataType || (DataType = {}));
535
+ const convertType = (dataType, value) => {
536
+ if (value === undefined || value === null) {
537
+ return value;
538
+ }
539
+ switch (dataType) {
540
+ case DataType.NUMBER:
541
+ return value === "" || isNaN(value) ? null : Number(value);
542
+ case DataType.OBJECT:
543
+ return typeof value === "string" ? JSON.parse(value) : value;
544
+ case DataType.BOOLEAN:
545
+ return Boolean(value);
546
+ case DataType.DATE:
547
+ return new Date(value.toString());
548
+ default:
549
+ return value;
550
+ }
551
+ };
552
+
553
+ class DataUnitAction {
554
+ constructor(type, payload) {
555
+ this._type = type;
556
+ this._payload = payload;
557
+ }
558
+ get type() {
559
+ return this._type;
560
+ }
561
+ get payload() {
562
+ return this._payload;
563
+ }
564
+ }
565
+ var Action;
566
+ (function (Action) {
567
+ Action["LOADING_METADATA"] = "loadingMetadata";
568
+ Action["METADATA_LOADED"] = "metadataLoaded";
569
+ Action["LOADING_DATA"] = "loadingData";
570
+ Action["DATA_LOADED"] = "dataLoaded";
571
+ Action["SAVING_DATA"] = "savingData";
572
+ Action["DATA_SAVED"] = "dataSaved";
573
+ Action["RECORDS_REMOVED"] = "recordsRemoved";
574
+ Action["RECORDS_ADDED"] = "recordsAdded";
575
+ Action["RECORDS_COPIED"] = "recordsCopied";
576
+ Action["DATA_CHANGED"] = "dataChanged";
577
+ Action["EDITION_CANCELED"] = "editionCanceled";
578
+ Action["CHANGE_UNDONE"] = "changeUndone";
579
+ Action["CHANGE_REDONE"] = "changeRedone";
580
+ Action["SELECTION_CHANGED"] = "selectionChanged";
581
+ Action["NEXT_SELECTED"] = "nextSelected";
582
+ Action["PREVIOUS_SELECTED"] = "previousSelected";
583
+ Action["STATE_CHANGED"] = "stateChanged";
584
+ })(Action || (Action = {}));
585
+
586
+ /**
587
+ * Essa classe representa uma interpretação do padrão de projetos Flux.
588
+ * No padrão Flux os dados da aplicação são chamados de "estado" e existem
589
+ * algumas regras para gerenciamento/manipulação desse estado:
590
+ *
591
+ * 1 - O estado é imutável.
592
+ * 2 - Toda modificação de estado é representada por uma "ação".
593
+ * 3 - Quando "ações" acontecem a "store" cria um novo estado e notifica a todos interessados.
594
+ *
595
+ * Nessa interpretação desse design pattern, o StateManager faz o papel da store,
596
+ * notificando os manipuladores de estado (handlers), que são responsáveis por pedaços
597
+ * do estado (slices).
598
+ *
599
+ * O StateManager mantém dois tipos de estados: "Histórico" e "Não Histórico". No estado
600
+ * "Histórico", sempre que uma alteração de estado acontece, o estado anterior é guardado em
601
+ * uma pilha, o que permite que possamos voltar no tempo, desfazendo algumas ações
602
+ */
603
+ class StateManager {
604
+ constructor(reducers) {
605
+ this._past = [];
606
+ this._future = [];
607
+ this._present = {};
608
+ this._nonHist = {};
609
+ this._histClean = false;
610
+ this._reducers = reducers;
611
+ }
612
+ process(action) {
613
+ const oldPresent = this._present;
614
+ let hasHistChange = false;
615
+ this._histClean = false;
616
+ this._reducers.forEach(reducer => {
617
+ const sliceName = reducer.sliceName;
618
+ const isHistoric = this.isHistoric(sliceName);
619
+ const oldSlice = this.getSlice(sliceName, isHistoric);
620
+ const newSlice = reducer.reduce(this, oldSlice, action);
621
+ if (newSlice !== oldSlice) {
622
+ this.updateSlice(sliceName, newSlice, isHistoric);
623
+ hasHistChange || (hasHistChange = isHistoric);
624
+ }
625
+ });
626
+ if (hasHistChange && !this._histClean) {
627
+ this._past.push(oldPresent);
628
+ this._future = [];
629
+ document.dispatchEvent(new CustomEvent("undoableAction", { detail: this }));
630
+ }
631
+ }
632
+ select(sliceName, selector) {
633
+ const isHistoric = this.isHistoric(sliceName);
634
+ return selector(this.getSlice(sliceName, isHistoric));
635
+ }
636
+ isHistoric(slice) {
637
+ return slice.startsWith("hist::");
638
+ }
639
+ updateSlice(name, slice, isHistoric) {
640
+ if (isHistoric) {
641
+ this._present = Object.assign(Object.assign({}, this._present), { [name]: slice });
642
+ if (slice === undefined) {
643
+ delete this._present[name];
644
+ }
645
+ }
646
+ else {
647
+ this._nonHist = Object.assign(Object.assign({}, this._nonHist), { [name]: slice });
648
+ if (slice === undefined) {
649
+ delete this._nonHist[name];
650
+ }
651
+ }
652
+ }
653
+ getSlice(name, isHistoric) {
654
+ return isHistoric ? this._present[name] : this._nonHist[name];
655
+ }
656
+ canUndo() {
657
+ return this._past.length > 0;
658
+ }
659
+ canRedo() {
660
+ return this._future.length > 0;
661
+ }
662
+ undo() {
663
+ if (this.canUndo()) {
664
+ this._future.push(this._present);
665
+ this._present = this._past.pop();
666
+ }
667
+ }
668
+ redo() {
669
+ if (this.canRedo()) {
670
+ this._past.push(this._present);
671
+ this._present = this._future.pop();
672
+ }
673
+ }
674
+ clearUndo() {
675
+ this._histClean = true;
676
+ this._past = [];
677
+ this._future = [];
678
+ }
679
+ persist() {
680
+ }
681
+ }
682
+
683
+ class HistReducerImpl {
684
+ constructor() {
685
+ this.sliceName = "";
686
+ }
687
+ reduce(stateManager, _currentState, action) {
688
+ switch (action.type) {
689
+ case Action.DATA_SAVED:
690
+ case Action.EDITION_CANCELED:
691
+ stateManager.clearUndo();
692
+ break;
693
+ case Action.CHANGE_UNDONE:
694
+ stateManager.undo();
695
+ break;
696
+ case Action.CHANGE_REDONE:
697
+ stateManager.redo();
698
+ break;
699
+ }
700
+ }
701
+ }
702
+ const HistReducer = new HistReducerImpl();
703
+ const canUndo = (stateManager) => {
704
+ return stateManager.canUndo();
705
+ };
706
+ const canRedo = (stateManager) => {
707
+ return stateManager.canRedo();
708
+ };
709
+
710
+ class UnitMetadataReducerImpl {
711
+ constructor() {
712
+ this.sliceName = "unitMetadata";
713
+ }
714
+ reduce(_stateManager, currentState, action) {
715
+ if (action.type === Action.METADATA_LOADED) {
716
+ return action.payload;
717
+ }
718
+ return currentState;
719
+ }
720
+ }
721
+ const UnitMetadataReducer = new UnitMetadataReducerImpl();
722
+ const getMetadata = (stateManager) => {
723
+ return stateManager.select(UnitMetadataReducer.sliceName, (state) => state);
724
+ };
725
+ const getField = (stateManager, fieldName) => {
726
+ const md = getMetadata(stateManager);
727
+ return md ? md.fields.find(fmd => fmd.name === fieldName) : undefined;
728
+ };
729
+
730
+ class RemovedRecordsReducerImpl {
731
+ constructor() {
732
+ this.sliceName = "hist::removedRecords";
733
+ }
734
+ reduce(_stateManager, currentState, action) {
735
+ switch (action.type) {
736
+ case Action.RECORDS_REMOVED:
737
+ return (currentState || []).concat(action.payload);
738
+ case Action.EDITION_CANCELED:
739
+ case Action.DATA_SAVED:
740
+ return undefined;
741
+ }
742
+ return currentState;
743
+ }
744
+ }
745
+ const RemovedRecordsReducer = new RemovedRecordsReducerImpl();
746
+ const getRemovedRecords = (stateManager) => {
747
+ return stateManager.select(RemovedRecordsReducer.sliceName, (state) => state);
748
+ };
749
+
750
+ class RecordsReducerImpl {
751
+ constructor() {
752
+ this.sliceName = "records";
753
+ }
754
+ reduce(stateManager, currentState, action) {
755
+ switch (action.type) {
756
+ case Action.DATA_LOADED:
757
+ return action.payload;
758
+ case Action.DATA_SAVED:
759
+ const recordsMap = new Map();
760
+ const currentRecords = getRecords(stateManager);
761
+ if (currentRecords) {
762
+ const removed = getRemovedRecords(stateManager) || [];
763
+ currentRecords.forEach(r => {
764
+ if (!removed.includes(r.__record__id__)) {
765
+ recordsMap.set(r.__record__id__, r);
766
+ }
767
+ });
768
+ }
769
+ const savedRecords = action.payload.records;
770
+ savedRecords.forEach(sr => {
771
+ const recordId = sr.__old__id__ || sr.__record__id__;
772
+ const newRecord = Object.assign({}, sr);
773
+ delete newRecord["__old__id__"];
774
+ recordsMap.set(recordId, newRecord);
775
+ });
776
+ return Array.from(recordsMap.values());
777
+ }
778
+ return currentState;
779
+ }
780
+ }
781
+ const RecordsReducer = new RecordsReducerImpl();
782
+ const getRecords = (stateManager) => {
783
+ return stateManager.select(RecordsReducer.sliceName, (state) => state);
784
+ };
785
+
786
+ class AddedRecordsReducerImpl {
787
+ constructor() {
788
+ this.sliceName = "hist::addedRecords";
789
+ }
790
+ reduce(_stateManager, currentState, action) {
791
+ switch (action.type) {
792
+ case Action.RECORDS_ADDED:
793
+ case Action.RECORDS_COPIED:
794
+ return (currentState || []).concat(action.payload);
795
+ case Action.DATA_SAVED:
796
+ case Action.EDITION_CANCELED:
797
+ return undefined;
798
+ }
799
+ return currentState;
800
+ }
801
+ }
802
+ const AddedRecordsReducer = new AddedRecordsReducerImpl();
803
+ const getAddedRecords = (stateManager) => {
804
+ return stateManager.select(AddedRecordsReducer.sliceName, (state) => state);
805
+ };
806
+ const prepareAddedRecordId = (stateManager, source) => {
807
+ let index = (getAddedRecords(stateManager) || []).length;
808
+ return source.map(item => { return Object.assign(Object.assign({}, item), { __record__id__: "NEW_" + (index++) }); });
809
+ };
810
+
811
+ class ChangesReducerImpl {
812
+ constructor() {
813
+ this.sliceName = "hist::changes";
814
+ }
815
+ reduce(stateManager, currentState, action) {
816
+ switch (action.type) {
817
+ case Action.DATA_CHANGED:
818
+ const selection = action.payload.records || getSelection(stateManager);
819
+ if (selection) {
820
+ const newState = new Map(currentState);
821
+ selection.forEach(recordId => {
822
+ const newChanges = Object.assign(Object.assign({}, newState.get(recordId)), action.payload);
823
+ delete newChanges.records;
824
+ newState.set(recordId, newChanges);
825
+ });
826
+ return newState;
827
+ }
828
+ return currentState;
829
+ case Action.DATA_SAVED:
830
+ case Action.EDITION_CANCELED:
831
+ return undefined;
832
+ }
833
+ return currentState;
834
+ }
835
+ }
836
+ const ChangesReducer = new ChangesReducerImpl();
837
+ const getChanges = (stateManager) => {
838
+ return stateManager.select(ChangesReducer.sliceName, (state) => state);
839
+ };
840
+ const isDirty = (stateManager) => {
841
+ if (getAddedRecords(stateManager) !== undefined) {
842
+ return true;
843
+ }
844
+ if (getRemovedRecords(stateManager) !== undefined) {
845
+ return true;
846
+ }
847
+ return getChanges(stateManager) !== undefined;
848
+ };
849
+ const getChangesToSave = (dataUnit, stateManager) => {
850
+ const result = [];
851
+ const changes = getChanges(stateManager);
852
+ const records = getRecords(stateManager);
853
+ records === null || records === void 0 ? void 0 : records.forEach(r => {
854
+ if (changes) {
855
+ const c = changes.get(r.__record__id__);
856
+ if (c) {
857
+ result.push(new Change(dataUnit, r, c, ChangeOperation.UPDATE));
858
+ }
859
+ }
860
+ });
861
+ const addedRecords = getAddedRecords(stateManager);
862
+ if (addedRecords) {
863
+ addedRecords.forEach(r => {
864
+ result.push(new Change(dataUnit, r, changes === null || changes === void 0 ? void 0 : changes.get(r.__record__id__), ChangeOperation.INSERT));
865
+ });
866
+ }
867
+ const removedRecords = getRemovedRecords(stateManager);
868
+ const recordsById = {};
869
+ records === null || records === void 0 ? void 0 : records.forEach(r => recordsById[r.__record__id__] = r);
870
+ if (removedRecords) {
871
+ removedRecords.forEach(id => {
872
+ result.push(new Change(dataUnit, recordsById[id], undefined, ChangeOperation.DELETE));
873
+ });
874
+ }
875
+ return result;
876
+ };
877
+
878
+ class CurrentRecordsReducerImpl {
879
+ constructor() {
880
+ this.sliceName = "currentRecords";
881
+ }
882
+ reduce(stateManager, _currentState, _action) {
883
+ let records = getRecords(stateManager);
884
+ const added = getAddedRecords(stateManager);
885
+ if (!records && !added) {
886
+ return undefined;
887
+ }
888
+ if (added) {
889
+ records = (records || []).concat(added);
890
+ }
891
+ const removedRecords = getRemovedRecords(stateManager);
892
+ if (removedRecords) {
893
+ records = records.filter(r => !removedRecords.includes(r.__record__id__));
894
+ }
895
+ const changes = getChanges(stateManager);
896
+ return new Map(records.map(r => {
897
+ const recordId = r.__record__id__;
898
+ const record = Object.assign(Object.assign({}, r), changes === null || changes === void 0 ? void 0 : changes.get(recordId));
899
+ return [recordId, record];
900
+ }));
901
+ }
902
+ }
903
+ const CurrentRecordsReducer = new CurrentRecordsReducerImpl();
904
+ const getCurrentRecords = (stateManager) => {
905
+ return stateManager.select(CurrentRecordsReducer.sliceName, (state) => state);
906
+ };
907
+ const getFieldValue = (stateManager, fieldName) => {
908
+ const selection = getSelection(stateManager);
909
+ if (selection && selection.length > 0) {
910
+ const currentRecords = getCurrentRecords(stateManager);
911
+ if (currentRecords) {
912
+ const record = currentRecords.get(selection[0]);
913
+ return record ? record[fieldName] : undefined;
914
+ }
915
+ }
916
+ return undefined;
917
+ };
918
+
919
+ class SelectionReducerImpl {
920
+ constructor() {
921
+ this.sliceName = "hist::selection";
922
+ }
923
+ reduce(stateManager, currentState, action) {
924
+ switch (action.type) {
925
+ case Action.RECORDS_ADDED:
926
+ case Action.RECORDS_COPIED:
927
+ return action.payload.map((r) => r.__record__id__);
928
+ case Action.DATA_SAVED:
929
+ return updateSavedIds(stateManager, action.payload.records);
930
+ case Action.RECORDS_REMOVED:
931
+ const removed = action.payload;
932
+ if (currentState && removed) {
933
+ return currentState.filter(recordId => !removed.includes(recordId));
934
+ }
935
+ return currentState;
936
+ case Action.NEXT_SELECTED:
937
+ case Action.PREVIOUS_SELECTED:
938
+ const currentRecords = getCurrentRecords(stateManager);
939
+ if (currentRecords && currentRecords.size > 0) {
940
+ let index;
941
+ if (!currentState || currentState.length === 0) {
942
+ index = action.type === Action.PREVIOUS_SELECTED ? 0 : Math.min(1, currentRecords.size);
943
+ }
944
+ else {
945
+ index = getItemIndex(currentState[0], currentRecords) + (action.type === Action.PREVIOUS_SELECTED ? -1 : 1);
946
+ }
947
+ if (index < currentRecords.size && index >= 0) {
948
+ return [Array.from(currentRecords.values())[index].__record__id__];
949
+ }
950
+ }
951
+ return undefined;
952
+ case Action.SELECTION_CHANGED:
953
+ const { type, selection: selectionSource } = action.payload;
954
+ if (selectionSource && type === "index") {
955
+ const currentRecords = getCurrentRecords(stateManager);
956
+ if (currentRecords) {
957
+ const records = Array.from(currentRecords.values());
958
+ const selectionById = [];
959
+ selectionSource.forEach((i) => {
960
+ if (i > 0 && i < currentRecords.size) {
961
+ selectionById.push(records[i].__record__id__);
962
+ }
963
+ });
964
+ return selectionById;
965
+ }
966
+ }
967
+ return selectionSource;
968
+ }
969
+ return currentState;
970
+ }
971
+ }
972
+ const SelectionReducer = new SelectionReducerImpl();
973
+ const getSelection = (stateManager) => {
974
+ let selection = stateManager.select(SelectionReducer.sliceName, (state) => state);
975
+ const currentRecords = Array.from((getCurrentRecords(stateManager) || new Map()).keys());
976
+ if (selection) {
977
+ selection = selection.filter(id => currentRecords.includes(id));
978
+ }
979
+ if (!selection || selection.length === 0) {
980
+ if (currentRecords && currentRecords.length > 0) {
981
+ return [currentRecords[0]];
982
+ }
983
+ }
984
+ return selection;
985
+ };
986
+ const hasNext = (stateManager) => {
987
+ const records = getCurrentRecords(stateManager);
988
+ if (records) {
989
+ const selection = stateManager.select(SelectionReducer.sliceName, (state) => state);
990
+ if (!selection || selection.length === 0) {
991
+ return records.size > 0;
992
+ }
993
+ return records.size > (getItemIndex(selection[0], records) + 1);
994
+ }
995
+ return false;
996
+ };
997
+ const hasPrevious = (stateManager) => {
998
+ const records = getCurrentRecords(stateManager);
999
+ if (records) {
1000
+ const selection = stateManager.select(SelectionReducer.sliceName, (state) => state);
1001
+ if (!selection || selection.length === 0) {
1002
+ return false;
1003
+ }
1004
+ return getItemIndex(selection[0], records) > 0;
1005
+ }
1006
+ return false;
1007
+ };
1008
+ function getItemIndex(key, map) {
1009
+ return Array.from(map.keys()).indexOf(key);
1010
+ }
1011
+ function updateSavedIds(stateManager, savedRecords) {
1012
+ const currentSelection = getSelection(stateManager);
1013
+ if (currentSelection) {
1014
+ const newSelection = [];
1015
+ currentSelection.forEach(id => {
1016
+ const record = savedRecords.find(r => r.__old__id__ === id);
1017
+ if (record) {
1018
+ newSelection.push(record.__record__id__);
1019
+ }
1020
+ else {
1021
+ newSelection.push(id);
1022
+ }
1023
+ });
1024
+ return newSelection;
1025
+ }
1026
+ return currentSelection;
1027
+ }
1028
+
1029
+ var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
1030
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
1031
+ return new (P || (P = Promise))(function (resolve, reject) {
1032
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
1033
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
1034
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
1035
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
1036
+ });
1037
+ };
1038
+ class DataUnit {
1039
+ constructor(name) {
1040
+ this._name = name;
1041
+ this._stateManager = new StateManager([
1042
+ HistReducer,
1043
+ UnitMetadataReducer,
1044
+ RecordsReducer,
1045
+ RemovedRecordsReducer,
1046
+ AddedRecordsReducer,
1047
+ SelectionReducer,
1048
+ ChangesReducer,
1049
+ CurrentRecordsReducer
1050
+ ]);
1051
+ this._observers = [];
1052
+ this._filterProviders = [];
1053
+ this._sortingProvider = undefined;
1054
+ this._interceptors = [];
1055
+ }
1056
+ get name() {
1057
+ return this._name;
1058
+ }
1059
+ // Métodos privados
1060
+ validateAndTypeValue(fieldName, newValue) {
1061
+ //FIXME: Validações devem ser feitas aqui
1062
+ const descriptor = this.getField(fieldName);
1063
+ return descriptor ? convertType(descriptor.dataType, newValue) : newValue;
1064
+ }
1065
+ getFilters() {
1066
+ let filters = undefined;
1067
+ this._filterProviders.forEach(p => {
1068
+ const f = p.getFilter(this.name);
1069
+ if (f) {
1070
+ filters = (filters || []).concat(f);
1071
+ }
1072
+ });
1073
+ return filters;
1074
+ }
1075
+ getSort() {
1076
+ return this._sortingProvider ? this._sortingProvider.getSort(this._name) : undefined;
1077
+ }
1078
+ // Loaders
1079
+ loadMetadata() {
1080
+ return __awaiter(this, void 0, void 0, function* () {
1081
+ this.dispatchAction(Action.LOADING_METADATA);
1082
+ return new Promise((resolve, fail) => {
1083
+ if (this.metadataLoader) {
1084
+ this.metadataLoader(this).then(metadata => {
1085
+ this.metadata = metadata;
1086
+ resolve(this.metadata);
1087
+ }).catch(error => fail(error));
1088
+ }
1089
+ });
1090
+ });
1091
+ }
1092
+ loadData() {
1093
+ return __awaiter(this, void 0, void 0, function* () {
1094
+ this.dispatchAction(Action.LOADING_DATA);
1095
+ return new Promise((resolve, fail) => {
1096
+ if (this.dataLoader) {
1097
+ const sort = this.getSort();
1098
+ const filters = this.getFilters();
1099
+ this.dataLoader(this, sort, filters).then(records => {
1100
+ this.records = records;
1101
+ resolve(this.records);
1102
+ }).catch(error => fail(error));
1103
+ }
1104
+ });
1105
+ });
1106
+ }
1107
+ saveData() {
1108
+ return __awaiter(this, void 0, void 0, function* () {
1109
+ const changes = getChangesToSave(this._name, this._stateManager);
1110
+ if (changes.length > 0) {
1111
+ this.dispatchAction(Action.SAVING_DATA);
1112
+ return new Promise((resolve, fail) => {
1113
+ if (this.saveLoader) {
1114
+ this.saveLoader(this, changes).then(records => this.dispatchAction(Action.DATA_SAVED, { changes, records })).catch(error => fail(error));
1115
+ }
1116
+ });
1117
+ }
1118
+ return Promise.resolve();
1119
+ });
1120
+ }
1121
+ // API
1122
+ valueFromString(fieldName, value) {
1123
+ const descriptor = this.getField(fieldName);
1124
+ return descriptor ? convertType(descriptor.dataType, value) : value;
1125
+ }
1126
+ addInterceptor(interceptor) {
1127
+ this._interceptors.push(interceptor);
1128
+ }
1129
+ addFilterProvider(provider) {
1130
+ this._filterProviders.push(provider);
1131
+ }
1132
+ set sortingProvider(provider) {
1133
+ this._sortingProvider = provider;
1134
+ }
1135
+ set metadata(md) {
1136
+ this.dispatchAction(Action.METADATA_LOADED, md);
1137
+ }
1138
+ get metadata() {
1139
+ return getMetadata(this._stateManager);
1140
+ }
1141
+ set records(r) {
1142
+ this.dispatchAction(Action.DATA_LOADED, r);
1143
+ }
1144
+ get records() {
1145
+ const records = getCurrentRecords(this._stateManager);
1146
+ return records ? Array.from(records.values()) : [];
1147
+ }
1148
+ getField(fieldName) {
1149
+ return getField(this._stateManager, fieldName);
1150
+ }
1151
+ addRecord() {
1152
+ this.dispatchAction(Action.RECORDS_ADDED, prepareAddedRecordId(this._stateManager, [{}]));
1153
+ }
1154
+ copySelected() {
1155
+ const selectedRecords = this.getSelectedRecords();
1156
+ if (selectedRecords) {
1157
+ this.dispatchAction(Action.RECORDS_COPIED, prepareAddedRecordId(this._stateManager, selectedRecords));
1158
+ }
1159
+ }
1160
+ removeSelectedRecords() {
1161
+ const selection = getSelection(this._stateManager);
1162
+ if (selection) {
1163
+ this.dispatchAction(Action.RECORDS_REMOVED, selection);
1164
+ }
1165
+ }
1166
+ getFieldValue(fieldName) {
1167
+ return getFieldValue(this._stateManager, fieldName);
1168
+ }
1169
+ setFieldValue(fieldName, newValue, records) {
1170
+ const typedValue = this.validateAndTypeValue(fieldName, newValue);
1171
+ const currentValue = this.getFieldValue(fieldName);
1172
+ if (currentValue !== typedValue) {
1173
+ this.dispatchAction(Action.DATA_CHANGED, { [fieldName]: typedValue, records });
1174
+ }
1175
+ }
1176
+ getSelection() {
1177
+ return getSelection(this._stateManager);
1178
+ }
1179
+ setSelection(selection) {
1180
+ this.dispatchAction(Action.SELECTION_CHANGED, { type: "id", selection });
1181
+ }
1182
+ setSelectionByIndex(selection) {
1183
+ this.dispatchAction(Action.SELECTION_CHANGED, { type: "index", selection });
1184
+ }
1185
+ getSelectedRecords() {
1186
+ const selection = this.getSelection();
1187
+ if (selection) {
1188
+ const currentRecords = this.records;
1189
+ return currentRecords === null || currentRecords === void 0 ? void 0 : currentRecords.filter(r => selection.includes(r.__record__id__));
1190
+ }
1191
+ }
1192
+ nextRecord() {
1193
+ this.dispatchAction(Action.NEXT_SELECTED);
1194
+ }
1195
+ previousRecord() {
1196
+ this.dispatchAction(Action.PREVIOUS_SELECTED);
1197
+ }
1198
+ cancelEdition() {
1199
+ this.dispatchAction(Action.EDITION_CANCELED);
1200
+ }
1201
+ isDirty() {
1202
+ return isDirty(this._stateManager);
1203
+ }
1204
+ hasNext() {
1205
+ return hasNext(this._stateManager);
1206
+ }
1207
+ hasPrevious() {
1208
+ return hasPrevious(this._stateManager);
1209
+ }
1210
+ canUndo() {
1211
+ return canUndo(this._stateManager);
1212
+ }
1213
+ canRedo() {
1214
+ return canRedo(this._stateManager);
1215
+ }
1216
+ undo() {
1217
+ this.dispatchAction(Action.CHANGE_UNDONE);
1218
+ }
1219
+ redo() {
1220
+ this.dispatchAction(Action.CHANGE_REDONE);
1221
+ }
1222
+ toString() {
1223
+ return this.name;
1224
+ }
1225
+ // Actions / State manager
1226
+ dispatchAction(actionType, payload) {
1227
+ var _a;
1228
+ let action = new DataUnitAction(actionType, payload);
1229
+ (_a = this._interceptors) === null || _a === void 0 ? void 0 : _a.forEach(interceptor => {
1230
+ if (action) {
1231
+ action = interceptor.interceptAction(action);
1232
+ }
1233
+ });
1234
+ if (action) {
1235
+ this._stateManager.process(action);
1236
+ this._observers.forEach(f => f(action));
1237
+ }
1238
+ }
1239
+ subscribe(observer) {
1240
+ this._observers.push(observer);
1241
+ }
1242
+ unsubscribe(observer) {
1243
+ this._observers = this._observers.filter(f => f !== observer);
1244
+ }
1245
+ }
1246
+ var ChangeOperation;
1247
+ (function (ChangeOperation) {
1248
+ ChangeOperation["INSERT"] = "INSERT";
1249
+ ChangeOperation["UPDATE"] = "UPDATE";
1250
+ ChangeOperation["DELETE"] = "DELETE";
1251
+ })(ChangeOperation || (ChangeOperation = {}));
1252
+ class Change {
1253
+ constructor(dataUnit, record, updates, operation) {
1254
+ this.dataUnit = dataUnit;
1255
+ this.record = record;
1256
+ this.updatingFields = updates;
1257
+ this._operation = operation;
1258
+ }
1259
+ get operation() {
1260
+ return this._operation.toString();
1261
+ }
1262
+ isInsert() {
1263
+ return this._operation === ChangeOperation.INSERT;
1264
+ }
1265
+ isDelete() {
1266
+ return this._operation === ChangeOperation.DELETE;
1267
+ }
1268
+ isUpdate() {
1269
+ return this._operation === ChangeOperation.UPDATE;
1270
+ }
1271
+ }
1272
+
1273
+ var SortMode;
1274
+ (function (SortMode) {
1275
+ SortMode["ASC"] = "ASC";
1276
+ SortMode["DESC"] = "DESC";
1277
+ })(SortMode || (SortMode = {}));
1278
+ var DependencyType;
1279
+ (function (DependencyType) {
1280
+ DependencyType["SEARCHING"] = "SEARCHING";
1281
+ DependencyType["REQUIREMENT"] = "REQUIREMENT";
1282
+ DependencyType["VISIBILITY"] = "REQUIREMENT";
1283
+ })(DependencyType || (DependencyType = {}));
1284
+ var UserInterface;
1285
+ (function (UserInterface) {
1286
+ UserInterface["FILE"] = "FILE";
1287
+ UserInterface["IMAGE"] = "IMAGE";
1288
+ UserInterface["DATE"] = "DATE";
1289
+ UserInterface["DATETIME"] = "DATETIME";
1290
+ UserInterface["ELAPSEDTIME"] = "ELAPSEDTIME";
1291
+ UserInterface["CHECKBOX"] = "CHECKBOX";
1292
+ UserInterface["SWITCH"] = "SWITCH";
1293
+ UserInterface["OPTIONSELECTOR"] = "OPTIONSELECTOR";
1294
+ UserInterface["DECIMALNUMBER"] = "DECIMALNUMBER";
1295
+ UserInterface["INTEGERNUMBER"] = "INTEGERNUMBER";
1296
+ UserInterface["SEARCH"] = "SEARCH";
1297
+ UserInterface["SHORTTEXT"] = "SHORTTEXT";
1298
+ UserInterface["PASSWORD"] = "PASSWORD";
1299
+ UserInterface["MASKEDTEXT"] = "MASKEDTEXT";
1300
+ UserInterface["LONGTEXT"] = "LONGTEXT";
1301
+ UserInterface["HTML"] = "HTML";
1302
+ })(UserInterface || (UserInterface = {}));
1303
+
1304
+ export { Action as A, DataUnitAction as D, MaskFormatter as M, NumberUtils as N, SortMode as S, TimeFormatter as T, UserInterface as U, DataUnit as a, DataType as b };