@sankhyalabs/sankhyablocks 1.1.22 → 1.1.23

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