@sankhyalabs/ezui 1.2.0-beta.8 → 2.0.0

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 (290) hide show
  1. package/dist/cjs/{ApplicationUtils-2ac1b73e.js → ApplicationUtils-edc62c5c.js} +4 -1
  2. package/dist/cjs/CheckMode-ecb90b87.js +7 -0
  3. package/dist/cjs/{DialogType-a1e288e6.js → DialogType-aa435c52.js} +1 -0
  4. package/dist/cjs/ez-actions-button.cjs.entry.js +68 -17
  5. package/dist/cjs/ez-application.cjs.entry.js +1 -1
  6. package/dist/cjs/ez-button.cjs.entry.js +13 -11
  7. package/dist/cjs/ez-calendar.cjs.entry.js +5 -5
  8. package/dist/cjs/ez-card-item.cjs.entry.js +1 -1
  9. package/dist/cjs/ez-check.cjs.entry.js +11 -9
  10. package/dist/cjs/ez-chip.cjs.entry.js +17 -7
  11. package/dist/cjs/ez-collapsible-box.cjs.entry.js +85 -7
  12. package/dist/cjs/ez-combo-box.cjs.entry.js +51 -20
  13. package/dist/cjs/ez-date-input.cjs.entry.js +13 -18
  14. package/dist/cjs/ez-date-time-input.cjs.entry.js +12 -17
  15. package/dist/cjs/ez-dialog.cjs.entry.js +43 -8
  16. package/dist/cjs/ez-filter-input.cjs.entry.js +1 -1
  17. package/dist/cjs/ez-form.cjs.entry.js +99 -486
  18. package/dist/cjs/ez-grid-config.cjs.entry.js +8 -9
  19. package/dist/cjs/ez-grid.cjs.entry.js +1073 -1168
  20. package/dist/cjs/ez-icon.cjs.entry.js +3 -3
  21. package/dist/cjs/ez-list.cjs.entry.js +2 -4
  22. package/dist/cjs/ez-loading-bar.cjs.entry.js +1 -1
  23. package/dist/cjs/ez-modal-container.cjs.entry.js +58 -0
  24. package/dist/cjs/ez-modal.cjs.entry.js +1 -1
  25. package/dist/cjs/ez-number-input.cjs.entry.js +4 -4
  26. package/dist/cjs/ez-popover.cjs.entry.js +6 -6
  27. package/dist/cjs/ez-popup.cjs.entry.js +8 -4
  28. package/dist/cjs/ez-radio-button.cjs.entry.js +3 -3
  29. package/dist/cjs/ez-scroller.cjs.entry.js +2 -2
  30. package/dist/cjs/ez-search.cjs.entry.js +1 -1
  31. package/dist/cjs/ez-select-box.cjs.entry.js +1 -1
  32. package/dist/cjs/ez-tabselector.cjs.entry.js +8 -7
  33. package/dist/cjs/ez-text-area.cjs.entry.js +7 -7
  34. package/dist/cjs/ez-text-edit.cjs.entry.js +103 -0
  35. package/dist/cjs/ez-text-input.cjs.entry.js +14 -4
  36. package/dist/cjs/ez-time-input.cjs.entry.js +7 -7
  37. package/dist/cjs/ez-toast.cjs.entry.js +2 -2
  38. package/dist/cjs/ez-upload.cjs.entry.js +4 -4
  39. package/dist/cjs/ez-view-stack.cjs.entry.js +10 -7
  40. package/dist/cjs/ezui.cjs.js +4 -112
  41. package/dist/cjs/loader.cjs.js +2 -18
  42. package/dist/collection/collection-manifest.json +2 -0
  43. package/dist/collection/components/ez-actions-button/ez-actions-button.css +49 -20
  44. package/dist/collection/components/ez-actions-button/ez-actions-button.js +219 -23
  45. package/dist/collection/components/ez-button/ez-button.css +0 -6
  46. package/dist/collection/components/ez-button/ez-button.js +11 -9
  47. package/dist/collection/components/ez-calendar/ez-calendar.css +17 -20
  48. package/dist/collection/components/ez-check/CheckMode.js +5 -0
  49. package/dist/collection/components/ez-check/ez-check.css +23 -24
  50. package/dist/collection/components/ez-check/ez-check.js +10 -8
  51. package/dist/collection/components/ez-chip/ez-chip.css +4 -2
  52. package/dist/collection/components/ez-chip/ez-chip.js +16 -6
  53. package/dist/collection/components/ez-collapsible-box/ez-collapsible-box.css +16 -0
  54. package/dist/collection/components/ez-collapsible-box/ez-collapsible-box.js +226 -7
  55. package/dist/collection/components/ez-combo-box/ez-combo-box.css +1 -22
  56. package/dist/collection/components/ez-combo-box/ez-combo-box.js +51 -20
  57. package/dist/collection/components/ez-date-input/ez-date-input.js +8 -13
  58. package/dist/collection/components/ez-date-time-input/ez-date-time-input.js +8 -13
  59. package/dist/collection/components/ez-dialog/DialogType.js +1 -0
  60. package/dist/collection/components/ez-dialog/ez-dialog.css +19 -25
  61. package/dist/collection/components/ez-dialog/ez-dialog.js +41 -6
  62. package/dist/collection/components/ez-form/DataBinder.js +1 -0
  63. package/dist/collection/components/ez-form/ez-form.js +22 -13
  64. package/dist/collection/components/ez-form/fieldbuilder/FieldBuilder.js +3 -3
  65. package/dist/collection/components/ez-form/fieldbuilder/tpl/CheckBox.tpl.js +2 -1
  66. package/dist/collection/components/ez-form/fieldbuilder/tpl/DateInput.tpl.js +4 -4
  67. package/dist/collection/components/ez-form/structure/FormSheetMetadata.js +25 -15
  68. package/dist/collection/components/ez-grid/controller/DataUnitBridge.js +3 -0
  69. package/dist/collection/components/ez-grid/controller/ag-grid/AgGridController.js +51 -15
  70. package/dist/collection/components/ez-grid/controller/ag-grid/components/cellRenderer.js +31 -0
  71. package/dist/collection/components/ez-grid/ez-grid.js +40 -3
  72. package/dist/collection/components/ez-grid/subcomponents/ez-grid-config/ez-grid-config.css +38 -27
  73. package/dist/collection/components/ez-grid/subcomponents/ez-grid-config/ez-grid-config.js +1 -2
  74. package/dist/collection/components/ez-grid/subcomponents/ez-select-box/ez-select-box.js +5 -4
  75. package/dist/collection/components/ez-list/ez-list.css +12 -4
  76. package/dist/collection/components/ez-modal-container/ez-modal-container.css +38 -0
  77. package/dist/collection/components/ez-modal-container/ez-modal-container.js +190 -0
  78. package/dist/collection/components/ez-modal-container/index.js +2 -0
  79. package/dist/collection/components/ez-modal-container/modal-action.js +8 -0
  80. package/dist/collection/components/ez-modal-container/modal-button-status.js +7 -0
  81. package/dist/collection/components/ez-popover/ez-popover.css +1 -1
  82. package/dist/collection/components/ez-popup/ez-popup.css +6 -1
  83. package/dist/collection/components/ez-popup/ez-popup.js +26 -4
  84. package/dist/collection/components/ez-radio-button/ez-radio-button.css +16 -5
  85. package/dist/collection/components/ez-radio-button/ez-radio-button.js +1 -1
  86. package/dist/collection/components/ez-scroller/ez-scroller.css +3 -2
  87. package/dist/collection/components/ez-search/ez-search.js +6 -6
  88. package/dist/collection/components/ez-tabselector/ez-tabselector.css +10 -1
  89. package/dist/collection/components/ez-tabselector/ez-tabselector.js +7 -3
  90. package/dist/collection/components/ez-text-area/ez-text-area.css +6 -3
  91. package/dist/collection/components/ez-text-area/ez-text-area.js +5 -5
  92. package/dist/collection/components/ez-text-edit/ez-text-edit.css +19 -0
  93. package/dist/collection/components/ez-text-edit/ez-text-edit.js +188 -0
  94. package/dist/collection/components/ez-text-input/ez-text-input.css +18 -2
  95. package/dist/collection/components/ez-text-input/ez-text-input.js +28 -0
  96. package/dist/collection/components/ez-toast/ez-toast.css +1 -1
  97. package/dist/collection/components/ez-upload/ez-upload.css +1 -1
  98. package/dist/collection/components/ez-view-stack/ez-view-stack.js +12 -6
  99. package/dist/collection/utils/ApplicationUtils.js +3 -0
  100. package/dist/collection/utils/index.js +1 -0
  101. package/dist/custom-elements/index.d.ts +12 -0
  102. package/dist/custom-elements/index.js +1595 -4005
  103. package/dist/{ezui/ApplicationUtils-30a69eb0.js → esm/ApplicationUtils-205ac4bc.js} +4 -2
  104. package/dist/esm/CheckMode-bdb2ec19.js +7 -0
  105. package/dist/esm/{DialogType-72afa679.js → DialogType-4059dc4d.js} +1 -0
  106. package/dist/esm/ez-actions-button.entry.js +68 -17
  107. package/dist/esm/ez-application.entry.js +1 -1
  108. package/dist/esm/ez-button.entry.js +13 -11
  109. package/dist/esm/ez-calendar.entry.js +3 -3
  110. package/dist/esm/ez-card-item.entry.js +1 -1
  111. package/dist/esm/ez-check.entry.js +11 -9
  112. package/dist/esm/ez-chip.entry.js +17 -7
  113. package/dist/esm/ez-collapsible-box.entry.js +85 -7
  114. package/dist/esm/ez-combo-box.entry.js +48 -17
  115. package/dist/esm/ez-date-input.entry.js +10 -15
  116. package/dist/esm/ez-date-time-input.entry.js +10 -15
  117. package/dist/esm/ez-dialog.entry.js +43 -8
  118. package/dist/esm/ez-filter-input.entry.js +1 -1
  119. package/dist/esm/ez-form.entry.js +65 -452
  120. package/dist/esm/ez-grid-config.entry.js +6 -7
  121. package/dist/esm/ez-grid.entry.js +1039 -1134
  122. package/dist/esm/ez-icon.entry.js +2 -2
  123. package/dist/esm/ez-list.entry.js +2 -4
  124. package/dist/esm/ez-loading-bar.entry.js +1 -1
  125. package/dist/esm/ez-modal-container.entry.js +54 -0
  126. package/dist/esm/ez-modal.entry.js +1 -1
  127. package/dist/esm/ez-number-input.entry.js +2 -2
  128. package/dist/esm/ez-popover.entry.js +3 -3
  129. package/dist/esm/ez-popup.entry.js +8 -4
  130. package/dist/esm/ez-radio-button.entry.js +3 -3
  131. package/dist/esm/ez-scroller.entry.js +2 -2
  132. package/dist/esm/ez-search.entry.js +1 -1
  133. package/dist/esm/ez-select-box.entry.js +1 -1
  134. package/dist/esm/ez-tabselector.entry.js +8 -7
  135. package/dist/esm/ez-text-area.entry.js +7 -7
  136. package/dist/esm/ez-text-edit.entry.js +99 -0
  137. package/dist/esm/ez-text-input.entry.js +13 -3
  138. package/dist/esm/ez-time-input.entry.js +2 -2
  139. package/dist/esm/ez-toast.entry.js +2 -2
  140. package/dist/esm/ez-upload.entry.js +4 -4
  141. package/dist/esm/ez-view-stack.entry.js +10 -7
  142. package/dist/esm/ezui.js +4 -112
  143. package/dist/esm/loader.js +2 -18
  144. package/dist/ezui/ezui.esm.js +1 -125
  145. package/dist/ezui/index.esm.js +0 -1
  146. package/dist/ezui/p-04a41a44.entry.js +1 -0
  147. package/dist/ezui/p-0b44cf1c.js +1 -0
  148. package/dist/ezui/p-0c7203d5.entry.js +1 -0
  149. package/dist/ezui/p-2213da1f.entry.js +1 -0
  150. package/dist/ezui/p-2c6398b3.entry.js +1 -0
  151. package/dist/ezui/p-2ccad880.entry.js +1 -0
  152. package/dist/ezui/p-333d79c4.entry.js +1 -0
  153. package/dist/ezui/p-3987f8d8.entry.js +1 -0
  154. package/dist/ezui/{p-81eb2738.entry.js → p-42c6493e.entry.js} +1 -1
  155. package/dist/ezui/{p-b4ad3b15.entry.js → p-482c3dd8.entry.js} +1 -1
  156. package/dist/ezui/p-5bdb1a41.entry.js +1 -0
  157. package/dist/ezui/{p-b2cf7db2.entry.js → p-63d567cc.entry.js} +1 -1
  158. package/dist/ezui/p-659616e4.entry.js +1 -0
  159. package/dist/ezui/p-6608b9a5.entry.js +1 -0
  160. package/dist/ezui/p-77ec47ac.entry.js +1 -0
  161. package/dist/ezui/p-9b9ebf95.entry.js +1 -0
  162. package/dist/ezui/{p-88bfdea4.entry.js → p-ae5af8f9.entry.js} +1 -1
  163. package/dist/ezui/p-b853763b.js +1 -0
  164. package/dist/ezui/p-be06251d.entry.js +1 -0
  165. package/dist/ezui/{p-e7d03a0d.entry.js → p-bffae598.entry.js} +1 -1
  166. package/dist/ezui/p-cd4677d4.entry.js +1 -0
  167. package/dist/ezui/p-cfcc23e6.entry.js +1 -0
  168. package/dist/ezui/p-dfcf55e0.entry.js +1 -0
  169. package/dist/ezui/p-e1148f5c.js +1 -0
  170. package/dist/ezui/p-e1f2b5da.entry.js +1 -0
  171. package/dist/ezui/p-e230bfd2.entry.js +1 -0
  172. package/dist/ezui/{p-867aac16.entry.js → p-e3ee814c.entry.js} +1 -1
  173. package/dist/ezui/p-e697ffd5.entry.js +1 -0
  174. package/dist/ezui/{p-4eb273f8.entry.js → p-efa32bcc.entry.js} +1 -1
  175. package/dist/types/components/ez-actions-button/ez-actions-button.d.ts +42 -9
  176. package/dist/types/components/ez-check/CheckMode.d.ts +4 -0
  177. package/dist/types/components/ez-chip/ez-chip.d.ts +2 -1
  178. package/dist/types/components/ez-collapsible-box/ez-collapsible-box.d.ts +46 -1
  179. package/dist/types/components/ez-combo-box/ez-combo-box.d.ts +15 -5
  180. package/dist/types/components/ez-date-input/ez-date-input.d.ts +0 -1
  181. package/dist/types/components/ez-date-time-input/ez-date-time-input.d.ts +0 -1
  182. package/dist/types/components/ez-dialog/DialogType.d.ts +1 -0
  183. package/dist/types/components/ez-dialog/ez-dialog.d.ts +3 -0
  184. package/dist/types/components/ez-form/DataBinder.d.ts +2 -2
  185. package/dist/types/components/ez-form/ez-form.d.ts +21 -11
  186. package/dist/types/components/ez-form/fieldbuilder/tpl/CheckBox.tpl.d.ts +3 -3
  187. package/dist/types/components/ez-form/fieldbuilder/tpl/DateInput.tpl.d.ts +4 -2
  188. package/dist/types/components/ez-form/fieldbuilder/tpl/NumberInput.tpl.d.ts +2 -5
  189. package/dist/types/components/ez-form/structure/FormSheetMetadata.d.ts +3 -3
  190. package/dist/types/components/ez-grid/controller/EzGridController.d.ts +11 -0
  191. package/dist/types/components/ez-grid/controller/ag-grid/AgGridController.d.ts +4 -1
  192. package/dist/types/components/ez-grid/controller/ag-grid/components/cellRenderer.d.ts +9 -0
  193. package/dist/types/components/ez-grid/ez-grid.d.ts +8 -3
  194. package/dist/types/components/ez-grid/subcomponents/ez-select-box/ez-select-box.d.ts +2 -6
  195. package/dist/types/components/ez-modal-container/ez-modal-container.d.ts +47 -0
  196. package/dist/types/components/ez-modal-container/index.d.ts +2 -0
  197. package/dist/types/components/ez-modal-container/modal-action.d.ts +7 -0
  198. package/dist/types/components/ez-modal-container/modal-button-status.d.ts +6 -0
  199. package/dist/types/components/ez-popup/ez-popup.d.ts +4 -0
  200. package/dist/types/components/ez-search/ez-search.d.ts +3 -3
  201. package/dist/types/components/ez-tabselector/ez-tabselector.d.ts +2 -0
  202. package/dist/types/components/ez-text-edit/ez-text-edit.d.ts +39 -0
  203. package/dist/types/components/ez-text-input/ez-text-input.d.ts +5 -0
  204. package/dist/types/components/ez-view-stack/ez-view-stack.d.ts +5 -1
  205. package/dist/types/components.d.ts +274 -28
  206. package/dist/types/utils/ApplicationUtils.d.ts +1 -0
  207. package/dist/types/utils/index.d.ts +1 -0
  208. package/package.json +5 -5
  209. package/react/components.d.ts +2 -0
  210. package/react/components.js +2 -0
  211. package/react/components.js.map +1 -1
  212. package/dist/cjs/ApplicationUtils-475b50d9.js +0 -63
  213. package/dist/cjs/app-globals-3a1e7e63.js +0 -5
  214. package/dist/cjs/css-shim-3bfdba4f.js +0 -6
  215. package/dist/cjs/dom-8ac1ad03.js +0 -75
  216. package/dist/cjs/index-2ec1da82.js +0 -2307
  217. package/dist/cjs/index-55178184.js +0 -6
  218. package/dist/cjs/index-d9c5cb88.js +0 -3068
  219. package/dist/cjs/shadow-css-41d9783d.js +0 -390
  220. package/dist/esm/ApplicationUtils-30a69eb0.js +0 -61
  221. package/dist/esm/ApplicationUtils-a4a76132.js +0 -60
  222. package/dist/esm/app-globals-0f993ce5.js +0 -3
  223. package/dist/esm/css-shim-20dbffa5.js +0 -4
  224. package/dist/esm/dom-c5ed0ba5.js +0 -73
  225. package/dist/esm/index-1e9d524f.js +0 -3031
  226. package/dist/esm/index-b96183c8.js +0 -2295
  227. package/dist/esm/index-f32470b5.js +0 -3
  228. package/dist/esm/shadow-css-8c625855.js +0 -388
  229. package/dist/ezui/CSSVarsUtils-00f67f32.js +0 -70
  230. package/dist/ezui/DialogType-72afa679.js +0 -8
  231. package/dist/ezui/app-globals-0f993ce5.js +0 -3
  232. package/dist/ezui/css-shim-20dbffa5.js +0 -4
  233. package/dist/ezui/dom-c5ed0ba5.js +0 -73
  234. package/dist/ezui/ez-actions-button.entry.js +0 -98
  235. package/dist/ezui/ez-application.entry.js +0 -22
  236. package/dist/ezui/ez-button.entry.js +0 -73
  237. package/dist/ezui/ez-calendar.entry.js +0 -219
  238. package/dist/ezui/ez-card-item.entry.js +0 -40
  239. package/dist/ezui/ez-check.entry.js +0 -72
  240. package/dist/ezui/ez-chip.entry.js +0 -97
  241. package/dist/ezui/ez-collapsible-box.entry.js +0 -57
  242. package/dist/ezui/ez-combo-box.entry.js +0 -439
  243. package/dist/ezui/ez-date-input.entry.js +0 -159
  244. package/dist/ezui/ez-date-time-input.entry.js +0 -214
  245. package/dist/ezui/ez-dialog.entry.js +0 -108
  246. package/dist/ezui/ez-filter-input.entry.js +0 -75
  247. package/dist/ezui/ez-form.entry.js +0 -1395
  248. package/dist/ezui/ez-grid-config.entry.js +0 -433
  249. package/dist/ezui/ez-grid.entry.js +0 -115419
  250. package/dist/ezui/ez-icon.entry.js +0 -37
  251. package/dist/ezui/ez-list.entry.js +0 -516
  252. package/dist/ezui/ez-loading-bar.entry.js +0 -24
  253. package/dist/ezui/ez-modal.entry.js +0 -67
  254. package/dist/ezui/ez-number-input.entry.js +0 -148
  255. package/dist/ezui/ez-popover.entry.js +0 -141
  256. package/dist/ezui/ez-popup.entry.js +0 -49
  257. package/dist/ezui/ez-radio-button.entry.js +0 -45
  258. package/dist/ezui/ez-scroller.entry.js +0 -101
  259. package/dist/ezui/ez-search.entry.js +0 -83
  260. package/dist/ezui/ez-select-box.entry.js +0 -18
  261. package/dist/ezui/ez-tabselector.entry.js +0 -195
  262. package/dist/ezui/ez-text-area.entry.js +0 -158
  263. package/dist/ezui/ez-text-input.entry.js +0 -235
  264. package/dist/ezui/ez-time-input.entry.js +0 -164
  265. package/dist/ezui/ez-toast.entry.js +0 -84
  266. package/dist/ezui/ez-upload.entry.js +0 -379
  267. package/dist/ezui/ez-view-stack.entry.js +0 -74
  268. package/dist/ezui/index-1e9d524f.js +0 -3031
  269. package/dist/ezui/index-b96183c8.js +0 -2295
  270. package/dist/ezui/index-f32470b5.js +0 -3
  271. package/dist/ezui/p-2f02347d.entry.js +0 -1
  272. package/dist/ezui/p-416bedbe.entry.js +0 -1
  273. package/dist/ezui/p-544f0c63.entry.js +0 -1
  274. package/dist/ezui/p-62110996.entry.js +0 -1
  275. package/dist/ezui/p-719e9ef9.entry.js +0 -1
  276. package/dist/ezui/p-787fbdfe.js +0 -1
  277. package/dist/ezui/p-9d5be6a7.entry.js +0 -1
  278. package/dist/ezui/p-a27dafa4.entry.js +0 -1
  279. package/dist/ezui/p-aba3fa6c.entry.js +0 -1
  280. package/dist/ezui/p-adbe4188.js +0 -1
  281. package/dist/ezui/p-af43be42.entry.js +0 -1
  282. package/dist/ezui/p-b7467ad6.entry.js +0 -1
  283. package/dist/ezui/p-c019e137.entry.js +0 -1
  284. package/dist/ezui/p-c9d2060e.entry.js +0 -1
  285. package/dist/ezui/p-cccd8cde.entry.js +0 -1
  286. package/dist/ezui/p-d0671e14.entry.js +0 -1
  287. package/dist/ezui/p-e0f06d73.entry.js +0 -1
  288. package/dist/ezui/p-e59adce6.entry.js +0 -1
  289. package/dist/ezui/p-ed835b36.entry.js +0 -1
  290. package/dist/ezui/shadow-css-8c625855.js +0 -388
@@ -1,2307 +0,0 @@
1
- 'use strict';
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
- }
55
- /**
56
- * Calcula um código hash para uma string.
57
- *
58
- * @param value String que será gerado o hash code.
59
- */
60
- static hashCode(value) {
61
- let hash = 0, i, chr;
62
- if (value.length === 0)
63
- return hash.toString();
64
- for (i = 0; i < value.length; i++) {
65
- chr = value.charCodeAt(i);
66
- hash = ((hash << 5) - hash) + chr;
67
- hash |= 0; // Convert to 32bit integer
68
- }
69
- return hash.toString();
70
- }
71
- /**
72
- * Converte um valor em string para booleano
73
- *
74
- * @param value Valor a ser convertido
75
- * @param defaultValue Será retornado esse caso seja passado valores diferentes do esperado(true, false, "true", "false", "S", "N")
76
- */
77
- static getBooleanValue(value, defaultValue = false) {
78
- if ([true, "true", "S"].includes(value)) {
79
- return true;
80
- }
81
- else if ([false, "false", "N"].includes(value)) {
82
- return false;
83
- }
84
- else {
85
- return defaultValue;
86
- }
87
- }
88
- }
89
-
90
- const NUMBERINPUTS_REGEX_SCIENTIFIC_PARTS = /^([+-])?(\d+).?(\d*)[eE]([-+]?\d+)$/;
91
- /**
92
- * `NumberUtils` é uma biblioteca para manipulação de números
93
- *
94
- * `Métodos`:
95
- *
96
- * @stringToNumber: converte um número em formato de string em um valor numérico nativo do javascript
97
- * @format: arredonda um número em formato de string baseado nos parâmetros "presision" e "prettyPrecision";
98
- */
99
- class NumberUtils {
100
- }
101
- /**
102
- * @stringToNumber: converte um numero em formato de string em numero
103
- *
104
- * @param value numero em formato de string a ser convertido (Importante: formato PT-BR ou já em formato numérico: ######.##)
105
- *
106
- * @returns string based number
107
- *
108
- * @Exemples
109
- * @"100,12" | 100.12
110
- * @"100.12" | 100.12
111
- * @"-100,12" | -100.12
112
- * @"R$100,12" | 100.12
113
- * @"-R$100,12" | -100.12
114
- * @"string" | NaN
115
- */
116
- NumberUtils.stringToNumber = (value) => {
117
- if (value === '' || value === null || value === undefined) {
118
- return NaN;
119
- }
120
- if (value) {
121
- value = value.toString();
122
- const negative = (value.charAt(0) === '-');
123
- if (!NUMBERINPUTS_REGEX_SCIENTIFIC_PARTS.test(value)) {
124
- value = value.replace(/[^\d.,]/g, '');
125
- }
126
- else {
127
- value = value.replace(/^-/g, '');
128
- }
129
- //In case of simple string such as: "@@@@@@@"
130
- if (value === '') {
131
- return Number(NaN);
132
- }
133
- const indexV = value.indexOf(',');
134
- const indexP = value.indexOf('.');
135
- if (indexP > indexV) {
136
- value = value.replace(',', '');
137
- }
138
- else if (indexP < indexV) {
139
- value = value.replace(/\./g, '@').replace(',', '.').replace(/@/g, '');
140
- }
141
- if (negative) {
142
- value = '-' + value;
143
- }
144
- }
145
- return Number(value);
146
- };
147
- /**
148
- * @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"
149
- *
150
- * @param value numero em formato de string a ser convertido (Importante: formato PT-BR ou já em formato numérico<sem separadors de milhares>: ######.##)
151
- * @param precision (numero de decimais)
152
- * @param prettyPrecision (numero de zeros nos decimais)
153
- *
154
- * @returns numero em formato de string formatado em PT-BR
155
- */
156
- NumberUtils.format = (value, precision, prettyPrecision = NaN) => {
157
- if (value === '' || value === undefined || value === "NaN") {
158
- return NaN.toString();
159
- }
160
- const newValue = NumberUtils.stringToNumber(value);
161
- if (isNaN(newValue)) {
162
- return NaN.toString();
163
- }
164
- //Validation "precision":
165
- // Case1: precision < 0 => does not use precision
166
- // Case2: presicion not int => does not use precision
167
- if (precision < 0 || Math.abs(Math.round(precision * 1) / 1) !== precision) {
168
- //Once stringToNumber returns number format, we need to change to pt-br
169
- return NumberUtils.changeFormat(newValue.toString());
170
- }
171
- //Validation "prettyPrecision"
172
- let prettyPrecisionInternal = 0;
173
- // Case1: prettyPrecision < 0 => prettyPrecision does not change de format that means: prettyPrecisionInternal = precision;
174
- // Case2: prettyPrecision not int => prettyPrecision does not change de format that means: prettyPrecisionInternal = precision;
175
- if (isNaN(prettyPrecision) || Math.abs(Math.round(prettyPrecision * 1) / 1) !== prettyPrecision) {
176
- prettyPrecisionInternal = precision;
177
- }
178
- else {
179
- prettyPrecisionInternal = prettyPrecision;
180
- }
181
- let newValueStr;
182
- newValueStr = (Math.round(newValue * Math.pow(10, precision)) / Math.pow(10, precision)).toLocaleString('pt-br', { minimumFractionDigits: precision });
183
- //prettyPrecision
184
- const varSettingPP = precision - prettyPrecisionInternal;
185
- if (varSettingPP > 0) {
186
- for (let i = 0; i < varSettingPP; i++) {
187
- if (newValueStr.substring(newValueStr.length - 1) == "0" && precision > 0) {
188
- newValueStr = newValueStr.substring(0, newValueStr.length - 1);
189
- }
190
- }
191
- }
192
- //in Case "." or "," in the end of the string
193
- if (newValueStr.substring(newValueStr.length - 1) == "." || newValueStr.substring(newValueStr.length - 1) == ",") {
194
- newValueStr = newValueStr.substring(0, newValueStr.length - 1);
195
- }
196
- return newValueStr;
197
- };
198
- /**
199
- * @keepOnlyDecimalSeparator: retira os separadores de milhar de um número em formato de string
200
- *
201
- * @param value numero em formato de string a ser convertido
202
- * @param formatnumber (formatação de ENTRADA e SAÍDA do utilitário: pt-BR="###.###,##" en-US="###,###.##"; Default: "pt-BR")
203
- *
204
- * @returns numero em formato de string formatado apenas com separador decimal
205
- */
206
- NumberUtils.keepOnlyDecimalSeparator = (value, formatnumber = 'pt-BR') => {
207
- //Formatting formatnumber to be able to get lowercases
208
- formatnumber = formatnumber.toUpperCase();
209
- //Formatting value following formatnumber parameter
210
- //keep only decimal character in order to correct format the string
211
- //This transformation is due the "stringtoNumber" method is a general method that tries to convert all formated strings
212
- if (formatnumber === 'EN-US') {
213
- value = value.replace(/\,/g, '');
214
- }
215
- else {
216
- value = value.replace(/\./g, '');
217
- }
218
- return value;
219
- };
220
- /**
221
- * @changeFormat: troca o formato do numero string de "PT-BR" para "EN-US" e vice-versa
222
- *
223
- * @param value numero em formato de string a ser convertido
224
- *
225
- * @returns numero em formato de string formatado de "PT-BR" para "EN-US" e vice-versa
226
- */
227
- NumberUtils.changeFormat = (value) => {
228
- //Formatting output following formatnumber
229
- return value.replace(/\./g, '_').replace(/\,/g, '.').replace(/\_/g, ',');
230
- };
231
-
232
- /**
233
- * `MaskFormatter` é usado para formatar strings. Seu comportamento
234
- * é controlado pela formato do atributo `mask` que especifica quais
235
- * caracteres são válidos e onde devem estar posicionados, intercalando-os
236
- * com eventuais caracteres literais expressados no padrão informado.
237
- * Sua implementação é inspirada pela implementação em Java do [MaskFormatter](https://docs.oracle.com/javase/7/docs/api/javax/swing/text/MaskFormatter.html).
238
- *
239
- * Para o padrão da máscara podem ser usados os seguintes caracteres especiais:
240
- *
241
- * | Caractere | Comportamento |
242
- * |:---------:|-------------------------------------------------------------------------------------------------------------|
243
- * | # | Qualquer número |
244
- * | ' | "Escapa" o caractere que vem na sequência. Útil quando desejamos converter um caractere especial em literal.|
245
- * | U | Qualquer letra. Transforma letras maiúsculas em maiúsculas. |
246
- * | L | Qualquer letra. Transforma letras maiúsculas em minúsculas. |
247
- * | A | Qualquer letra ou número. |
248
- * | ? | Qualquer letra. Preserva maiúsculas e minúsculas. |
249
- * | * | Qualquer caractere. |
250
- *
251
- * Os demais caracteres presentes no padrão serão tratados como literais, isto é,
252
- * serão apenas inseridos naquela posição.
253
- *
254
- * Quando o o valor a ser formatado é menor que a máscara um 'placeHolder'
255
- * será inserido em cada posição ausente, completando a formatação.
256
- * Por padrão será usado um espaço em branco como 'placeHolder' mas
257
- * esse valor pode ser alterado.
258
- *
259
- * For por exemplo:
260
- * '''
261
- * const formatter: MaskFormatter = new MaskFormatter("###-####");
262
- * formatter.placeholder = '_';
263
- * console.log(formatter.format("123"));
264
- * '''
265
- * resultaria na string '123-____'.
266
- *
267
- * ##Veja mais alguns exemplos:
268
- * |Padrão |Máscara |Entrada |Saída |
269
- * |----------------|------------------|--------------|------------------|
270
- * |Telefone |(##) ####-#### |3432192515 |(34) 3219-2515 |
271
- * |CPF |###.###.###-## |12345678901 |123.456.789-01 |
272
- * |CNPJ |##.###.###/####-##|12345678901234|12.345.678/9012-34|
273
- * |CEP |##.###-### |12345678 |12.345-678 |
274
- * |PLACA (veículo) |UUU-#### |abc1234 |ABC-1234 |
275
- * |Cor RGB |'#AAAAAA |00000F0 |#0000F0 |
276
- *
277
- */
278
- class MaskFormatter {
279
- constructor(mask) {
280
- this._mask = '';
281
- this._maskChars = new Array();
282
- /**
283
- * Determina qual caractere será usado dos caracteres não presentes no valor
284
- * ou seja, aqueles que o usuário ainda não informou. Por padrão usamos um espaço
285
- */
286
- this.placeholder = ' ';
287
- this.mask = mask;
288
- }
289
- /**
290
- * Setter para mask. Trata-se do padrão que se espera ao formatar o texto.
291
- */
292
- set mask(mask) {
293
- this._mask = mask;
294
- this.updateInternalMask();
295
- }
296
- /**
297
- * Getter para mask
298
- *
299
- * @return A última máscara informada.
300
- */
301
- get mask() {
302
- return this._mask;
303
- }
304
- /**
305
- * Formata a string passada baseada na máscara definda pelo atributo mask.
306
- *
307
- * @param value Valor a ser formatado
308
- * @return O valor processado de acordo com o padrão
309
- */
310
- format(value) {
311
- let result = '';
312
- const index = [0];
313
- let counter = 0;
314
- const maxCounter = this._maskChars.length;
315
- while (counter < maxCounter) {
316
- result = this._maskChars[counter].append(result, value, index);
317
- counter++;
318
- }
319
- return result;
320
- }
321
- /**
322
- * Preparamos a formatação internamente de acordo com o padrão.
323
- */
324
- updateInternalMask() {
325
- this._maskChars.length = 0;
326
- if (this.mask != null) {
327
- let counter = 0;
328
- const maxCounter = this.mask.length;
329
- while (counter < maxCounter) {
330
- let maskChar = this.mask.charAt(counter);
331
- switch (maskChar) {
332
- case MaskFormatter.DIGIT_KEY:
333
- this._maskChars.push(new MaskFormatter.DigitMaskCharacter(this, maskChar));
334
- break;
335
- case MaskFormatter.LITERAL_KEY:
336
- if (++counter < maxCounter) {
337
- maskChar = this.mask.charAt(counter);
338
- this._maskChars.push(new MaskFormatter.LiteralCharacter(this, maskChar));
339
- }
340
- break;
341
- case MaskFormatter.UPPERCASE_KEY:
342
- this._maskChars.push(new MaskFormatter.UpperCaseCharacter(this, maskChar));
343
- break;
344
- case MaskFormatter.LOWERCASE_KEY:
345
- this._maskChars.push(new MaskFormatter.LowerCaseCharacter(this, maskChar));
346
- break;
347
- case MaskFormatter.ALPHA_NUMERIC_KEY:
348
- this._maskChars.push(new MaskFormatter.AlphaNumericCharacter(this, maskChar));
349
- break;
350
- case MaskFormatter.CHARACTER_KEY:
351
- this._maskChars.push(new MaskFormatter.CharCharacter(this, maskChar));
352
- break;
353
- case MaskFormatter.ANYTHING_KEY:
354
- this._maskChars.push(new MaskFormatter.MaskCharacter(this, maskChar));
355
- break;
356
- default:
357
- this._maskChars.push(new MaskFormatter.LiteralCharacter(this, maskChar));
358
- break;
359
- }
360
- counter++;
361
- }
362
- }
363
- }
364
- }
365
- MaskFormatter.DIGIT_KEY = "#";
366
- MaskFormatter.LITERAL_KEY = "'";
367
- MaskFormatter.UPPERCASE_KEY = "U";
368
- MaskFormatter.LOWERCASE_KEY = "L";
369
- MaskFormatter.ALPHA_NUMERIC_KEY = "A";
370
- MaskFormatter.CHARACTER_KEY = "?";
371
- MaskFormatter.ANYTHING_KEY = "*";
372
- //
373
- // Classes internas usadas para representar a máscara.
374
- //
375
- MaskFormatter.MaskCharacter = class {
376
- constructor(maskFormatter, type) {
377
- this.maskFormatter = maskFormatter;
378
- this.type = type;
379
- }
380
- /**
381
- * Cada subclasse deve sobrescrever o retornando true, caso represente
382
- * um caractere literal. Por padrão o retorno é false.
383
- */
384
- isLiteral() {
385
- return false;
386
- }
387
- /**
388
- * Returns true if <code>aChar</code> is a valid reprensentation of
389
- * the receiver. The default implementation returns true if the
390
- * receiver represents a literal character and <code>getChar</code>
391
- * == aChar. Otherwise, this will return true is <code>aChar</code>
392
- * is contained in the valid characters and not contained
393
- * in the invalid characters.
394
- */
395
- isValidCharacter(aChar) {
396
- if (this.isLiteral()) {
397
- return (this.getChar(aChar) == aChar);
398
- }
399
- aChar = this.getChar(aChar);
400
- return true;
401
- }
402
- /**
403
- * Returns the character to insert for <code>aChar</code>. The
404
- * default implementation returns <code>aChar</code>. Subclasses
405
- * that wish to do some sort of mapping, perhaps lower case to upper
406
- * case should override this and do the necessary mapping.
407
- */
408
- getChar(aChar) {
409
- return aChar;
410
- }
411
- /**
412
- * Appends the necessary character in <code>formatting</code> at
413
- * <code>index</code> to <code>buff</code>.
414
- */
415
- append(result, formatting, index) {
416
- const inString = index[0] < formatting.length;
417
- const aChar = inString ? formatting.charAt(index[0]) : '';
418
- if (this.isLiteral()) {
419
- const literal = this.getChar(aChar);
420
- result += literal;
421
- if (literal === aChar) {
422
- index[0] = index[0] + 1;
423
- }
424
- }
425
- else if (index[0] >= formatting.length) {
426
- result += this.maskFormatter.placeholder;
427
- index[0] = index[0] + 1;
428
- }
429
- else if (this.isValidCharacter(aChar)) {
430
- result += this.getChar(aChar);
431
- index[0] = index[0] + 1;
432
- }
433
- else {
434
- throw new Error(`Valor inválido: "${aChar}". Na posição ${index[0] + 1} espera-se ${this.getFormatMessage()}.`);
435
- }
436
- return result;
437
- }
438
- getFormatMessage() {
439
- let message;
440
- switch (this.type) {
441
- case MaskFormatter.UPPERCASE_KEY:
442
- case MaskFormatter.LOWERCASE_KEY:
443
- case MaskFormatter.CHARACTER_KEY:
444
- message = 'uma letra';
445
- break;
446
- case MaskFormatter.DIGIT_KEY:
447
- message = 'um número';
448
- break;
449
- case MaskFormatter.ALPHA_NUMERIC_KEY:
450
- message = 'uma letra ou um número';
451
- break;
452
- default:
453
- message = '';
454
- }
455
- return message;
456
- }
457
- };
458
- MaskFormatter.LiteralCharacter = class extends MaskFormatter.MaskCharacter {
459
- constructor(maskFormatter, fixedChar) {
460
- super(maskFormatter, fixedChar);
461
- this._fixedChar = fixedChar;
462
- }
463
- isLiteral() {
464
- return true;
465
- }
466
- getChar(aChar) {
467
- aChar;
468
- return this._fixedChar;
469
- }
470
- };
471
- MaskFormatter.DigitMaskCharacter = class extends MaskFormatter.MaskCharacter {
472
- isValidCharacter(aChar) {
473
- return (this.isDigit(aChar) && super.isValidCharacter(aChar));
474
- }
475
- isDigit(char) {
476
- return char >= '0' && char <= '9';
477
- }
478
- };
479
- MaskFormatter.UpperCaseCharacter = class extends MaskFormatter.MaskCharacter {
480
- isValidCharacter(aChar) {
481
- return (/[a-z]/i.test(aChar) && super.isValidCharacter(aChar));
482
- }
483
- getChar(aChar) {
484
- return aChar.toUpperCase();
485
- }
486
- };
487
- MaskFormatter.LowerCaseCharacter = class extends MaskFormatter.MaskCharacter {
488
- isValidCharacter(aChar) {
489
- return (/[a-z]/i.test(aChar) && super.isValidCharacter(aChar));
490
- }
491
- getChar(aChar) {
492
- return aChar.toLocaleLowerCase();
493
- }
494
- };
495
- MaskFormatter.AlphaNumericCharacter = class extends MaskFormatter.MaskCharacter {
496
- isValidCharacter(aChar) {
497
- //FIXME: talvez seja problema usar regex aqui... avaliar se existe forma mais barata
498
- return (/[a-z0-9]/i.test(aChar)) && super.isValidCharacter(aChar);
499
- }
500
- };
501
- MaskFormatter.CharCharacter = class extends MaskFormatter.MaskCharacter {
502
- isValidCharacter(aChar) {
503
- //FIXME: talvez seja problema usar regex aqui... avaliar se existe forma mais barata
504
- return (/[a-z]/i.test(aChar) && super.isValidCharacter(aChar));
505
- }
506
- };
507
-
508
- class FloatingEntry {
509
- constructor(parent, content, opts) {
510
- try {
511
- this.weakRefParent = new WeakRef(parent);
512
- this.weakRefContent = new WeakRef(content);
513
- }
514
- catch (error) {
515
- this.strongRefParent = parent;
516
- this.strongRefContent = content;
517
- }
518
- this.options = opts;
519
- }
520
- get parent() {
521
- if (this.weakRefParent) {
522
- return this.weakRefParent.deref();
523
- }
524
- return this.strongRefParent;
525
- }
526
- get content() {
527
- if (this.weakRefContent) {
528
- return this.weakRefContent.deref();
529
- }
530
- return this.strongRefContent;
531
- }
532
- }
533
- class FloatingManager {
534
- static init() {
535
- FloatingManager.entries = [];
536
- document.addEventListener('mousedown', FloatingManager.handleDocumentEvent);
537
- document.addEventListener('keydown', FloatingManager.handleKeyboardEvent);
538
- FloatingManager.initialized = true;
539
- }
540
- static innerClick(container, node) {
541
- if (container.contains(node)) {
542
- return true;
543
- }
544
- if (container.shadowRoot && container.shadowRoot.contains(node)) {
545
- return true;
546
- }
547
- return false;
548
- }
549
- static doClose(id, entry, target, event) {
550
- if (!target || entry.options.autoClose) {
551
- const parent = entry.parent;
552
- const content = entry.content;
553
- if (parent && content) {
554
- const innerClickFunction = entry.options.innerClickTest ? entry.options.innerClickTest : FloatingManager.innerClick;
555
- const backClickFunction = entry.options.backClickListener ? entry.options.backClickListener : () => { };
556
- if (!target || !innerClickFunction(content, target, event)) {
557
- content.remove();
558
- delete FloatingManager.entries[id];
559
- backClickFunction();
560
- }
561
- }
562
- else {
563
- delete FloatingManager.entries[id];
564
- }
565
- }
566
- }
567
- static handleDocumentEvent(event) {
568
- FloatingManager.entries.forEach((entry, index) => {
569
- FloatingManager.doClose(index, entry, event.composedPath()[0], event);
570
- });
571
- }
572
- static handleKeyboardEvent(event) {
573
- if (event.key === 'Escape') {
574
- for (let index = FloatingManager.entries.length; index >= 0; index--) {
575
- const entry = FloatingManager.entries[index];
576
- if (entry) {
577
- FloatingManager.close(index);
578
- break;
579
- }
580
- }
581
- }
582
- }
583
- static applyStyle(element, propertyName, value) {
584
- if (value) {
585
- element.style.setProperty(propertyName, value);
586
- }
587
- }
588
- static getFloatIndex(content, parent) {
589
- for (let index = 0; index < FloatingManager.entries.length; index++) {
590
- const entry = FloatingManager.entries[index];
591
- if (entry && content === entry.content && parent === entry.parent) {
592
- return index;
593
- }
594
- }
595
- return -1;
596
- }
597
- static isFloating(id) {
598
- return FloatingManager.entries[id] !== undefined;
599
- }
600
- static float(content, parent, options = { autoClose: true }) {
601
- if (!FloatingManager.initialized) {
602
- FloatingManager.init();
603
- }
604
- const alreadyFloatingIndex = FloatingManager.getFloatIndex(content, parent);
605
- if (alreadyFloatingIndex > -1) {
606
- return alreadyFloatingIndex;
607
- }
608
- content.style.position = 'absolute';
609
- FloatingManager.applyStyle(content, "top", options.top);
610
- FloatingManager.applyStyle(content, "left", options.left);
611
- FloatingManager.applyStyle(content, "right", options.right);
612
- FloatingManager.applyStyle(content, "bottom", options.bottom);
613
- parent.appendChild(content);
614
- FloatingManager.entries.push(new FloatingEntry(parent, content, options));
615
- return FloatingManager.entries.length - 1;
616
- }
617
- static updateFloatPosition(content, parent, options = { autoClose: true }) {
618
- const alreadyFloatingIndex = FloatingManager.getFloatIndex(content, parent);
619
- if (alreadyFloatingIndex > -1) {
620
- FloatingManager.applyStyle(content, "top", options.top);
621
- FloatingManager.applyStyle(content, "left", options.left);
622
- FloatingManager.applyStyle(content, "right", options.right);
623
- FloatingManager.applyStyle(content, "bottom", options.bottom);
624
- }
625
- }
626
- static close(id) {
627
- if (FloatingManager.entries[id]) {
628
- FloatingManager.doClose(id, FloatingManager.entries[id], undefined);
629
- }
630
- }
631
- }
632
-
633
- class DateUtils {
634
- static clearTime(date, adjustDayLightSavingTime = true) {
635
- const newDate = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0, 0);
636
- return adjustDayLightSavingTime ? DateUtils.adjustDLST(newDate) : newDate;
637
- }
638
- static strToDate(strValue, adjustDayLightSavingTime = true, monthYearMode = false) {
639
- /** monthYearMode é um booleano para usar o formato MM/YYYY.
640
- * Quando ativado, é retornado o primeiro dia do mês apenas para construir a data.
641
- * Não há necessidade de verificar o horário de verão quando utilizado esse modo. */
642
- let parts;
643
- if (monthYearMode) {
644
- 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);
645
- }
646
- else {
647
- 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);
648
- }
649
- if (!parts) {
650
- return undefined;
651
- }
652
- const day = monthYearMode ? 1 : Number(parts[1]);
653
- const month = Number(parts[(monthYearMode ? 1 : 2)]);
654
- let year = Number(parts[(monthYearMode ? 2 : 3)]);
655
- const hour = Number(parts[(monthYearMode ? 3 : 4)] || 0);
656
- const min = Number(parts[(monthYearMode ? 4 : 5)] || 0);
657
- const sec = Number(parts[(monthYearMode ? 5 : 6)] || 0);
658
- if (year < 100) {
659
- year += year < 30 ? 2000 : 1900;
660
- }
661
- let date = new Date(year, month - 1, day, hour, min, sec, 0);
662
- if (adjustDayLightSavingTime === true && !monthYearMode && hour == 0) {
663
- date = DateUtils.adjustDLST(date);
664
- }
665
- return date;
666
- }
667
- static adjustDLST(date) {
668
- //Work around para corrigir o Bug do horário de verão.
669
- if (date.getHours() == 23) {
670
- return new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1, 1, 0, 0, 0);
671
- }
672
- return date;
673
- }
674
- }
675
-
676
- /**
677
- * `TimeFormatter` é um utilitário para formatação de strings desformatadas em strings válidas de horários
678
- */
679
- class TimeFormatter {
680
- /**
681
- * @prepareValue: converts an unformated time string into a formatted time.
682
- *
683
- * @param value unformated time string to convert
684
- *
685
- * @returns formatted time string
686
- *
687
- * @Exemples
688
- * @"1012" | "10:12"
689
- * @"10:12" | "10:12:00"
690
- * @"100112" | "10:01:12"
691
- */
692
- static prepareValue(value, showSeconds) {
693
- if (value && value.length > 0 && value != "NaN") {
694
- let validationValue = value.replace(/:/g, "");
695
- if (showSeconds) {
696
- this._maskFormatter.mask = "##:##:##";
697
- if (validationValue.length < 6) {
698
- while (validationValue.length < 6) {
699
- validationValue = "0".concat(validationValue);
700
- }
701
- }
702
- }
703
- else {
704
- this._maskFormatter.mask = "##:##";
705
- if (validationValue.length < 4) {
706
- while (validationValue.length < 4) {
707
- validationValue = "0".concat(validationValue);
708
- }
709
- }
710
- }
711
- if (this._maskFormatter) {
712
- try {
713
- value = this._maskFormatter.format(validationValue);
714
- return value;
715
- }
716
- catch (e) {
717
- throw new Error(e.message);
718
- }
719
- }
720
- }
721
- return '';
722
- }
723
- /**
724
- * @validateTime: validates if an input string has the corect time format.
725
- *
726
- * @param value input string to validate
727
- *
728
- * @returns true or false
729
- *
730
- * @Exemples
731
- * @"1012" | true
732
- * @"14e4" | false
733
- * @"2624" | false
734
- */
735
- static validateTime(value, showSeconds) {
736
- let isValid = true;
737
- if (value) {
738
- let validationValue = value.replace(/:/g, "");
739
- if (showSeconds) {
740
- if (!["1", "2", "0"].includes(validationValue[0])) {
741
- isValid = false;
742
- }
743
- if (!["0", "1", "2", "3", "4", "5"].includes(validationValue[2])) {
744
- isValid = false;
745
- }
746
- if (!["0", "1", "2", "3", "4", "5"].includes(validationValue[4])) {
747
- isValid = false;
748
- }
749
- if (validationValue[0] == "2" && !["0", "1", "2", "3"].includes(validationValue[1])) {
750
- isValid = false;
751
- }
752
- }
753
- else {
754
- if (!["1", "2", "0"].includes(validationValue[0])) {
755
- isValid = false;
756
- }
757
- if (!["0", "1", "2", "3", "4", "5"].includes(validationValue[2])) {
758
- isValid = false;
759
- }
760
- if (validationValue[0] == "2" && !["0", "1", "2", "3"].includes(validationValue[1])) {
761
- isValid = false;
762
- }
763
- }
764
- }
765
- else {
766
- isValid = false;
767
- }
768
- return isValid;
769
- }
770
- }
771
- TimeFormatter._maskFormatter = new MaskFormatter("##:##");
772
-
773
- /**
774
- * Representa as propriedades necessárias para se executar uma requisição.
775
- */
776
- class RequestMetadata {
777
- /**
778
- * @param {string} url A URL que deve ser chamada.
779
- * @param {Method} method O Método da requisição (GET, PUT, POST ou DELETE).
780
- */
781
- constructor(url, method, headers) {
782
- /** Tempo limite de espera pela resposta */
783
- this.timeout = 30000;
784
- this.url = url;
785
- this.method = method;
786
- this.headers = headers || [];
787
- }
788
- }
789
- /** Representa os verbos HTTP suportados */
790
- var Method;
791
- (function (Method) {
792
- Method[Method["GET"] = 0] = "GET";
793
- Method[Method["PUT"] = 1] = "PUT";
794
- Method[Method["POST"] = 2] = "POST";
795
- Method[Method["DELETE"] = 3] = "DELETE";
796
- })(Method || (Method = {}));
797
-
798
- /**
799
- * Abstração do XMLHttpRequest. Este serviço é responsável por realizar as requisições
800
- * ao backend. Todos os métodos são estáticos.
801
- */
802
- class HttpProvider {
803
- /**
804
- * Faz uma requisição usando o método GET do HTTP para uma URL específica.
805
- *
806
- * @param {string} url A URL que deve ser chamada.
807
- * @param {Array<Header>} headers [Opcional] Cabeçalhos HTTP.
808
- * @returns {Promise<Object>} Uma promessa de que a requisição será preenchida.
809
- */
810
- static get(url, headers) {
811
- return this.dispatch(new RequestMetadata(url, Method.GET, headers));
812
- }
813
- /**
814
- * Faz uma requisição usando o método POST do HTTP para uma URL específica.
815
- *
816
- * @param {string} url A URL que deve ser chamada.
817
- * @param {Object} payload Informações a serem enviadas.
818
- * @param {Array<Header>} headers [Opcional] Cabeçalhos HTTP.
819
- * @returns {Promise<Object>} Uma promessa de que a requisição será preenchida.
820
- */
821
- static post(url, payload, headers) {
822
- return this.dispatch(new RequestMetadata(url, Method.POST, headers), payload);
823
- }
824
- static dispatch(requestMetadata, payload) {
825
- return new Promise((resolve, reject) => {
826
- const request = new XMLHttpRequest();
827
- request.timeout = requestMetadata.timeout;
828
- request.onerror = function handleError() {
829
- reject({
830
- status: 404,
831
- statusText: 'Not Found'
832
- });
833
- };
834
- request.ontimeout = function handleTimeout() {
835
- reject({
836
- status: 408,
837
- statusText: 'Request Timeout'
838
- });
839
- };
840
- request.onreadystatechange = () => {
841
- // While readState isn't done, there's nothing to do...
842
- if (request.readyState != 4) {
843
- return;
844
- }
845
- const status = request.status;
846
- // The request has failed so we'll handled by onerror instead
847
- if (status === 0) {
848
- return;
849
- }
850
- const response = {
851
- status,
852
- statusText: request.statusText,
853
- };
854
- // Anything out of this range is an error, so we just send the status and statusText.
855
- if (status >= 200 && status < 300) {
856
- resolve(Object.assign(Object.assign({}, response), { data: request.response, dataAsString: request.responseText }));
857
- }
858
- else {
859
- reject(response);
860
- }
861
- };
862
- request.open(requestMetadata.method.toString(), requestMetadata.url, true);
863
- requestMetadata.headers.map((h) => request.setRequestHeader(h.name, h.value));
864
- if (payload != null) {
865
- request.send(JSON.stringify(payload));
866
- }
867
- });
868
- }
869
- }
870
-
871
- class SkwHttpProvider {
872
- static callService(serviceName, content) {
873
- return new Promise((resolve, reject) => {
874
- let host = "http://192.168.1.218:8503/mge/";
875
- let appName = "ListaTarefa";
876
- let module = 'mge';
877
- this._counter++;
878
- if (serviceName.indexOf("@") > -1) {
879
- let s = serviceName.split("@");
880
- module = s[0];
881
- serviceName = s[1];
882
- }
883
- let url = `${host}/${module}/service.sbr?serviceName=${serviceName}&counter=${this._counter}&application=${appName}&outputType=json&preventTransform=false`;
884
- let requestContent = {
885
- serviceName: serviceName,
886
- requestBody: content
887
- };
888
- let headers = new Headers();
889
- headers.append("Content-Type", "application/json");
890
- //headers.append("Access-Control-Allow-Methods", "GET, POST, OPTIONS, PUT, PATCH, DELETE");
891
- //headers.append("Access-Control-Allow-Origin", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
892
- fetch(url, {
893
- body: JSON.stringify(requestContent),
894
- method: 'POST',
895
- headers: headers
896
- })
897
- .then(res => res.json())
898
- .then((data) => {
899
- console.log(data);
900
- });
901
- /*HttpProvider.post(url, requestContent, headers)
902
- .then(res => {
903
- if (!res.hasOwnProperty('status') ||
904
- res.status == this.STATUS_ERROR ||
905
- res.status == this.STATUS_TIMEOUT) {
906
-
907
- let statusMessage = res.statusMessage;
908
-
909
- if (!statusMessage) {
910
- statusMessage = 'Erro não identificado.'
911
- }
912
- //TODO: No futuro, exibir mensagens de erro. (MessageUtils.showError)
913
- reject(new Error(statusMessage));
914
- }else if (res.status == this.STATUS_CANCELED) {
915
- if (res.statusMessage){
916
- console.warn(res.statusMessage);
917
- }
918
- }else{
919
- resolve(res);
920
- }
921
-
922
- if (res.status == this.STATUS_INFO) {
923
- //TODO: No futuro, exibir mensagens de erro. (MessageUtils.showAlert)
924
- console.info(res.statusMessage);
925
- }
926
- })
927
- .catch((e)=>{reject(e)});*/
928
- });
929
- }
930
- }
931
- SkwHttpProvider._counter = 0;
932
- SkwHttpProvider.STATUS_ERROR = 0;
933
- SkwHttpProvider.STATUS_OK = 1;
934
- SkwHttpProvider.STATUS_INFO = 2;
935
- SkwHttpProvider.STATUS_TIMEOUT = 3;
936
- SkwHttpProvider.STATUS_CANCELED = 4;
937
-
938
- var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
939
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
940
- return new (P || (P = Promise))(function (resolve, reject) {
941
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
942
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
943
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
944
- step((generator = generator.apply(thisArg, _arguments || [])).next());
945
- });
946
- };
947
- class AuthorizedServiceCaller {
948
- constructor(serverURL, unauthorizedPath) {
949
- this.serverURL = "http://192.168.1.218:8503"; //todo request deve fazer replace de ${serverURL} pelo conteúdo da variável
950
- this.unauthorizedPath = "/";
951
- this.serverURL = serverURL;
952
- this.unauthorizedPath = unauthorizedPath;
953
- }
954
- requestService(request, callback) {
955
- return __awaiter$1(this, void 0, void 0, function* () {
956
- const token = localStorage.getItem('token');
957
- const body = request === null || request === void 0 ? void 0 : request.body;
958
- const method = request === null || request === void 0 ? void 0 : request.method;
959
- let headers;
960
- if (!token) {
961
- window.location.pathname = this.unauthorizedPath;
962
- }
963
- else {
964
- headers = {
965
- 'Authorization': `${token}`,
966
- 'Content-Type': 'application/json',
967
- 'Customer-Host': 'http://localhost:8080/sankhyaw'
968
- };
969
- }
970
- const response = yield yield fetch(this.serverURL, {
971
- method: method,
972
- headers: headers,
973
- body: body
974
- })
975
- .catch(e => {
976
- console.log(e);
977
- });
978
- if (response instanceof Response && response.status === 401) {
979
- localStorage.removeItem('token');
980
- window.location.pathname = this.unauthorizedPath;
981
- }
982
- if (callback && response instanceof Response) {
983
- callback(response.json().then());
984
- }
985
- else {
986
- return response;
987
- }
988
- });
989
- }
990
- }
991
-
992
- exports.DataType = void 0;
993
- (function (DataType) {
994
- DataType["NUMBER"] = "NUMBER";
995
- DataType["DATE"] = "DATE";
996
- DataType["TEXT"] = "TEXT";
997
- DataType["BOOLEAN"] = "BOOLEAN";
998
- DataType["OBJECT"] = "OBJECT";
999
- })(exports.DataType || (exports.DataType = {}));
1000
- const convertType = (dataType, value) => {
1001
- if (value === undefined || value === null) {
1002
- return value;
1003
- }
1004
- if (typeof value === "object" && dataType !== exports.DataType.OBJECT && "value" in value) {
1005
- value = value.value;
1006
- }
1007
- switch (dataType) {
1008
- case exports.DataType.NUMBER:
1009
- return value === "" || isNaN(value) ? null : Number(value);
1010
- case exports.DataType.OBJECT:
1011
- return typeof value === "string" ? JSON.parse(value) : value;
1012
- case exports.DataType.BOOLEAN:
1013
- if (typeof value == 'string') {
1014
- return Boolean(value === 'true');
1015
- }
1016
- return Boolean(value);
1017
- case exports.DataType.DATE:
1018
- return new Date(value.toString());
1019
- default:
1020
- return value;
1021
- }
1022
- };
1023
- const toString = (dataType, value) => {
1024
- if (value === undefined || value === null) {
1025
- return value;
1026
- }
1027
- if (dataType) {
1028
- if (dataType === exports.DataType.OBJECT) {
1029
- return JSON.stringify(value);
1030
- }
1031
- else if (dataType === exports.DataType.DATE) {
1032
- return value.toISOString();
1033
- }
1034
- else {
1035
- return value.toString();
1036
- }
1037
- }
1038
- else {
1039
- if (typeof value === "string") {
1040
- return value;
1041
- }
1042
- else if (value instanceof Date) {
1043
- return value.toISOString();
1044
- }
1045
- else {
1046
- try {
1047
- return JSON.stringify(value);
1048
- }
1049
- catch (_a) {
1050
- value = value.toString();
1051
- }
1052
- return value;
1053
- }
1054
- }
1055
- };
1056
-
1057
- class DataUnitAction {
1058
- constructor(type, payload) {
1059
- this._type = type;
1060
- this._payload = payload;
1061
- }
1062
- get type() {
1063
- return this._type;
1064
- }
1065
- get payload() {
1066
- return this._payload;
1067
- }
1068
- }
1069
- exports.Action = void 0;
1070
- (function (Action) {
1071
- Action["LOADING_METADATA"] = "loadingMetadata";
1072
- Action["METADATA_LOADED"] = "metadataLoaded";
1073
- Action["LOADING_DATA"] = "loadingData";
1074
- Action["DATA_LOADED"] = "dataLoaded";
1075
- Action["SAVING_DATA"] = "savingData";
1076
- Action["DATA_SAVED"] = "dataSaved";
1077
- Action["REMOVING_RECORDS"] = "removingRecords";
1078
- Action["RECORDS_REMOVED"] = "recordsRemoved";
1079
- Action["RECORDS_ADDED"] = "recordsAdded";
1080
- Action["RECORDS_COPIED"] = "recordsCopied";
1081
- Action["CHANGING_DATA"] = "changingData";
1082
- Action["WAITING_CHANGE_CANCELED"] = "waitingChangeCanceled";
1083
- Action["DATA_CHANGED"] = "dataChanged";
1084
- Action["EDITION_CANCELED"] = "editionCanceled";
1085
- Action["CHANGE_UNDONE"] = "changeUndone";
1086
- Action["CHANGE_REDONE"] = "changeRedone";
1087
- Action["SELECTION_CHANGED"] = "selectionChanged";
1088
- Action["NEXT_SELECTED"] = "nextSelected";
1089
- Action["PREVIOUS_SELECTED"] = "previousSelected";
1090
- Action["STATE_CHANGED"] = "stateChanged";
1091
- })(exports.Action || (exports.Action = {}));
1092
-
1093
- /**
1094
- * Essa classe representa uma interpretação do padrão de projetos Flux.
1095
- * No padrão Flux os dados da aplicação são chamados de "estado" e existem
1096
- * algumas regras para gerenciamento/manipulação desse estado:
1097
- *
1098
- * 1 - O estado é imutável.
1099
- * 2 - Toda modificação de estado é representada por uma "ação".
1100
- * 3 - Quando "ações" acontecem a "store" cria um novo estado e notifica a todos interessados.
1101
- *
1102
- * Nessa interpretação desse design pattern, o StateManager faz o papel da store,
1103
- * notificando os manipuladores de estado (handlers), que são responsáveis por pedaços
1104
- * do estado (slices).
1105
- *
1106
- * O StateManager mantém dois tipos de estados: "Histórico" e "Não Histórico". No estado
1107
- * "Histórico", sempre que uma alteração de estado acontece, o estado anterior é guardado em
1108
- * uma pilha, o que permite que possamos voltar no tempo, desfazendo algumas ações
1109
- */
1110
- class StateManager {
1111
- constructor(reducers) {
1112
- this._past = [];
1113
- this._future = [];
1114
- this._present = {};
1115
- this._nonHist = {};
1116
- this._histClean = false;
1117
- this._reducers = reducers;
1118
- }
1119
- process(action) {
1120
- const oldPresent = this._present;
1121
- let hasHistChange = false;
1122
- this._histClean = false;
1123
- this._reducers.forEach(reducer => {
1124
- const sliceName = reducer.sliceName;
1125
- const isHistoric = this.isHistoric(sliceName);
1126
- const oldSlice = this.getSlice(sliceName, isHistoric);
1127
- const newSlice = reducer.reduce(this, oldSlice, action);
1128
- if (newSlice !== oldSlice) {
1129
- this.updateSlice(sliceName, newSlice, isHistoric);
1130
- hasHistChange || (hasHistChange = isHistoric);
1131
- }
1132
- });
1133
- if (hasHistChange && !this._histClean) {
1134
- this._past.push(oldPresent);
1135
- this._future = [];
1136
- document.dispatchEvent(new CustomEvent("undoableAction", { detail: this }));
1137
- }
1138
- }
1139
- select(sliceName, selector) {
1140
- const isHistoric = this.isHistoric(sliceName);
1141
- return selector(this.getSlice(sliceName, isHistoric));
1142
- }
1143
- isHistoric(slice) {
1144
- return slice.startsWith("hist::");
1145
- }
1146
- updateSlice(name, slice, isHistoric) {
1147
- if (isHistoric) {
1148
- this._present = Object.assign(Object.assign({}, this._present), { [name]: slice });
1149
- if (slice === undefined) {
1150
- delete this._present[name];
1151
- }
1152
- }
1153
- else {
1154
- this._nonHist = Object.assign(Object.assign({}, this._nonHist), { [name]: slice });
1155
- if (slice === undefined) {
1156
- delete this._nonHist[name];
1157
- }
1158
- }
1159
- }
1160
- getSlice(name, isHistoric) {
1161
- return isHistoric ? this._present[name] : this._nonHist[name];
1162
- }
1163
- canUndo() {
1164
- return this._past.length > 0;
1165
- }
1166
- canRedo() {
1167
- return this._future.length > 0;
1168
- }
1169
- undo() {
1170
- if (this.canUndo()) {
1171
- this._future.push(this._present);
1172
- this._present = this._past.pop();
1173
- }
1174
- }
1175
- redo() {
1176
- if (this.canRedo()) {
1177
- this._past.push(this._present);
1178
- this._present = this._future.pop();
1179
- }
1180
- }
1181
- clearUndo() {
1182
- this._histClean = true;
1183
- this._past = [];
1184
- this._future = [];
1185
- }
1186
- persist() {
1187
- }
1188
- }
1189
-
1190
- class ErrorException extends Error {
1191
- constructor(title, message) {
1192
- super(message);
1193
- this.title = title;
1194
- this.message = message;
1195
- }
1196
- }
1197
-
1198
- class WaitingChangeException extends Error {
1199
- constructor(title, message) {
1200
- super(message);
1201
- this.title = title;
1202
- this.message = message;
1203
- }
1204
- }
1205
-
1206
- class AddedRecordsReducerImpl {
1207
- constructor() {
1208
- this.sliceName = "hist::addedRecords";
1209
- }
1210
- reduce(_stateManager, currentState, action) {
1211
- switch (action.type) {
1212
- case exports.Action.RECORDS_ADDED:
1213
- case exports.Action.RECORDS_COPIED:
1214
- return (currentState || []).concat(action.payload);
1215
- case exports.Action.DATA_SAVED:
1216
- case exports.Action.EDITION_CANCELED:
1217
- return undefined;
1218
- }
1219
- return currentState;
1220
- }
1221
- }
1222
- const AddedRecordsReducer = new AddedRecordsReducerImpl();
1223
- const getAddedRecords = (stateManager) => {
1224
- return stateManager.select(AddedRecordsReducer.sliceName, (state) => state);
1225
- };
1226
- const prepareAddedRecordId = (stateManager, source) => {
1227
- let index = (getAddedRecords(stateManager) || []).length;
1228
- return source.map(item => { return Object.assign(Object.assign({}, item), { __record__id__: "NEW_" + (index++) }); });
1229
- };
1230
- const prepareCopiedRecord = (stateManager, source) => {
1231
- let index = (getAddedRecords(stateManager) || []).length;
1232
- return source.map(item => { return Object.assign(Object.assign({}, item), { __record__id__: "NEW_" + (index++), __record__source__id__: item.__record__id__, __copy__: true }); });
1233
- };
1234
-
1235
- class RemovedRecordsReducerImpl {
1236
- constructor() {
1237
- this.sliceName = "hist::removedRecords";
1238
- }
1239
- reduce(_stateManager, currentState, action) {
1240
- switch (action.type) {
1241
- case exports.Action.RECORDS_REMOVED:
1242
- const { records, buffered } = action.payload;
1243
- if (buffered) {
1244
- return (currentState || []).concat(records);
1245
- }
1246
- return currentState;
1247
- case exports.Action.EDITION_CANCELED:
1248
- case exports.Action.DATA_SAVED:
1249
- return undefined;
1250
- }
1251
- return currentState;
1252
- }
1253
- }
1254
- const RemovedRecordsReducer = new RemovedRecordsReducerImpl();
1255
- const getRemovedRecords = (stateManager) => {
1256
- return stateManager.select(RemovedRecordsReducer.sliceName, (state) => state);
1257
- };
1258
-
1259
- class RecordsReducerImpl {
1260
- constructor() {
1261
- this.sliceName = "records";
1262
- }
1263
- reduce(stateManager, currentState, action) {
1264
- switch (action.type) {
1265
- case exports.Action.DATA_LOADED:
1266
- return action.payload ? action.payload.records : undefined;
1267
- case exports.Action.RECORDS_REMOVED:
1268
- const { records, buffered } = action.payload;
1269
- if (!buffered) {
1270
- return currentState.filter(r => !records.includes(r.__record__id__));
1271
- }
1272
- return currentState;
1273
- case exports.Action.DATA_SAVED:
1274
- const recordsMap = new Map();
1275
- const currentRecords = getRecords(stateManager);
1276
- if (currentRecords) {
1277
- const removed = getRemovedRecords(stateManager) || [];
1278
- currentRecords.forEach(r => {
1279
- if (!removed.includes(r.__record__id__)) {
1280
- recordsMap.set(r.__record__id__, r);
1281
- }
1282
- });
1283
- }
1284
- const newRecords = [];
1285
- const savedRecords = action.payload.records;
1286
- savedRecords.forEach(sr => {
1287
- const recordId = sr.__old__id__ || sr.__record__id__;
1288
- const newRecord = Object.assign({}, sr);
1289
- delete newRecord["__old__id__"];
1290
- if (recordsMap.has(recordId)) {
1291
- recordsMap.set(recordId, newRecord);
1292
- }
1293
- else {
1294
- newRecords.push(newRecord);
1295
- }
1296
- });
1297
- return newRecords.concat(Array.from(recordsMap.values()));
1298
- }
1299
- return currentState;
1300
- }
1301
- }
1302
- const RecordsReducer = new RecordsReducerImpl();
1303
- const getRecords = (stateManager) => {
1304
- return stateManager.select(RecordsReducer.sliceName, (state) => state);
1305
- };
1306
-
1307
- class CurrentRecordsReducerImpl {
1308
- constructor() {
1309
- this.sliceName = "currentRecords";
1310
- }
1311
- reduce(stateManager) {
1312
- let records = getRecords(stateManager);
1313
- const added = getAddedRecords(stateManager);
1314
- if (!records && !added) {
1315
- return undefined;
1316
- }
1317
- if (added) {
1318
- records = (added || []).concat(records || []);
1319
- }
1320
- const removedRecords = getRemovedRecords(stateManager);
1321
- if (removedRecords) {
1322
- records = records.filter(r => !removedRecords.includes(r.__record__id__));
1323
- }
1324
- const changes = getChanges(stateManager);
1325
- return new Map(records.map(r => {
1326
- const recordId = r.__record__id__;
1327
- const record = Object.assign(Object.assign({}, r), changes === null || changes === void 0 ? void 0 : changes.get(recordId));
1328
- return [recordId, record];
1329
- }));
1330
- }
1331
- }
1332
- const CurrentRecordsReducer = new CurrentRecordsReducerImpl();
1333
- const getCurrentRecords = (stateManager) => {
1334
- return stateManager.select(CurrentRecordsReducer.sliceName, (state) => state);
1335
- };
1336
- const getModifiedRecords = (stateManager) => {
1337
- const currentRecords = getCurrentRecords(stateManager);
1338
- if (!currentRecords) {
1339
- return undefined;
1340
- }
1341
- const changes = getChanges(stateManager);
1342
- const added = getAddedRecords(stateManager);
1343
- if (!changes && !added) {
1344
- return undefined;
1345
- }
1346
- let modifiedIDs = changes ? Array.from(changes.keys()) : [];
1347
- if (added) {
1348
- modifiedIDs = modifiedIDs.concat(added.map(r => r.__record__id__));
1349
- }
1350
- return Array.from(currentRecords.values()).filter(r => modifiedIDs.includes(r.__record__id__));
1351
- };
1352
- const getFieldValue = (stateManager, fieldName) => {
1353
- const selection = getSelection(stateManager);
1354
- if (selection && selection.length > 0) {
1355
- const currentRecords = getCurrentRecords(stateManager);
1356
- if (currentRecords) {
1357
- const record = currentRecords.get(selection[0]);
1358
- return record ? record[fieldName] : undefined;
1359
- }
1360
- }
1361
- return undefined;
1362
- };
1363
-
1364
- class SelectionReducerImpl {
1365
- constructor() {
1366
- this.sliceName = "hist::selection";
1367
- }
1368
- reduce(stateManager, currentState, action) {
1369
- switch (action.type) {
1370
- case exports.Action.RECORDS_ADDED:
1371
- case exports.Action.RECORDS_COPIED:
1372
- return { currentSelection: action.payload.map((r) => r.__record__id__), lastSelection: currentState === null || currentState === void 0 ? void 0 : currentState.currentSelection };
1373
- case exports.Action.DATA_SAVED:
1374
- return { currentSelection: updateSavedIds(stateManager, action.payload.records) };
1375
- case exports.Action.RECORDS_REMOVED:
1376
- const removed = action.payload.records;
1377
- if (currentState && removed) {
1378
- const currentSelection = currentState.currentSelection;
1379
- const record = currentSelection.filter(recordId => !removed.includes(recordId));
1380
- if (record.length === 0) {
1381
- const currentRecords = getCurrentRecords(stateManager);
1382
- let removedIndex = action.payload.removedIndex.slice(-1)[0];
1383
- let currentIndex = 0;
1384
- if (removedIndex >= currentRecords.size - 1) {
1385
- removedIndex--;
1386
- }
1387
- else {
1388
- removedIndex++;
1389
- }
1390
- currentRecords.forEach((value, key) => {
1391
- if (currentIndex === removedIndex) {
1392
- record.push(key);
1393
- }
1394
- currentIndex++;
1395
- });
1396
- }
1397
- return { currentSelection: record };
1398
- }
1399
- return currentState;
1400
- case exports.Action.NEXT_SELECTED:
1401
- case exports.Action.PREVIOUS_SELECTED:
1402
- const currentRecords = getCurrentRecords(stateManager);
1403
- const currentSelection = currentState === null || currentState === void 0 ? void 0 : currentState.currentSelection;
1404
- if (currentRecords && currentRecords.size > 0) {
1405
- let index;
1406
- if (!currentState || currentSelection.length === 0) {
1407
- index = action.type === exports.Action.PREVIOUS_SELECTED ? 0 : Math.min(1, currentRecords.size);
1408
- }
1409
- else {
1410
- index = getItemIndex(currentSelection[0], currentRecords) + (action.type === exports.Action.PREVIOUS_SELECTED ? -1 : 1);
1411
- }
1412
- if (index < currentRecords.size && index >= 0) {
1413
- return { currentSelection: [Array.from(currentRecords.values())[index].__record__id__] };
1414
- }
1415
- }
1416
- return undefined;
1417
- case exports.Action.SELECTION_CHANGED:
1418
- const { type, selection: selectionSource } = action.payload;
1419
- if (selectionSource && type === "index") {
1420
- const currentRecords = getCurrentRecords(stateManager);
1421
- if (currentRecords) {
1422
- const records = Array.from(currentRecords.values());
1423
- const selectionById = [];
1424
- selectionSource.forEach((i) => {
1425
- if (i >= 0 && i < currentRecords.size) {
1426
- selectionById.push(records[i].__record__id__);
1427
- }
1428
- });
1429
- return { currentSelection: selectionById };
1430
- }
1431
- }
1432
- return { currentSelection: selectionSource };
1433
- case exports.Action.EDITION_CANCELED:
1434
- if (currentState === null || currentState === void 0 ? void 0 : currentState.lastSelection) {
1435
- return { currentSelection: currentState.lastSelection };
1436
- }
1437
- }
1438
- return currentState;
1439
- }
1440
- }
1441
- const SelectionReducer = new SelectionReducerImpl();
1442
- const getSelection = (stateManager) => {
1443
- let selection = getCurrentSelection(stateManager);
1444
- const currentRecords = Array.from((getCurrentRecords(stateManager) || new Map()).keys());
1445
- if (selection) {
1446
- selection = selection.filter(id => currentRecords.includes(id));
1447
- }
1448
- if (!selection || selection.length === 0) {
1449
- return [];
1450
- }
1451
- return selection;
1452
- };
1453
- const hasNext = (stateManager) => {
1454
- const records = getCurrentRecords(stateManager);
1455
- if (records) {
1456
- const selection = getCurrentSelection(stateManager);
1457
- if (!selection || selection.length === 0) {
1458
- return records.size > 0;
1459
- }
1460
- return records.size > (getItemIndex(selection[0], records) + 1);
1461
- }
1462
- return false;
1463
- };
1464
- const hasPrevious = (stateManager) => {
1465
- const records = getCurrentRecords(stateManager);
1466
- if (records) {
1467
- const selection = getCurrentSelection(stateManager);
1468
- if (!selection || selection.length === 0) {
1469
- return false;
1470
- }
1471
- return getItemIndex(selection[0], records) > 0;
1472
- }
1473
- return false;
1474
- };
1475
- function getItemIndex(key, map) {
1476
- return Array.from(map.keys()).indexOf(key);
1477
- }
1478
- function updateSavedIds(stateManager, savedRecords) {
1479
- const currentSelection = getSelection(stateManager);
1480
- if (currentSelection) {
1481
- const newSelection = [];
1482
- currentSelection.forEach(id => {
1483
- const record = savedRecords.find(r => r.__old__id__ === id);
1484
- if (record) {
1485
- newSelection.push(record.__record__id__);
1486
- }
1487
- else {
1488
- newSelection.push(id);
1489
- }
1490
- });
1491
- return newSelection;
1492
- }
1493
- return currentSelection;
1494
- }
1495
- function getCurrentSelection(stateManager) {
1496
- var _a;
1497
- return (_a = stateManager.select(SelectionReducer.sliceName, (state) => state)) === null || _a === void 0 ? void 0 : _a.currentSelection;
1498
- }
1499
-
1500
- class WaitingCheangesReducerImpl {
1501
- constructor() {
1502
- this.sliceName = "waitingChanges";
1503
- }
1504
- reduce(stateManager, currentState, action) {
1505
- let newState;
1506
- switch (action.type) {
1507
- case exports.Action.CHANGING_DATA:
1508
- newState = new Map(currentState);
1509
- Object.entries(action.payload).forEach(([key, value]) => {
1510
- newState.set(key, value);
1511
- });
1512
- return newState;
1513
- case exports.Action.WAITING_CHANGE_CANCELED:
1514
- newState = new Map(currentState);
1515
- newState.delete(action.payload.fieldName);
1516
- return newState.size === 0 ? undefined : newState;
1517
- case exports.Action.DATA_CHANGED:
1518
- newState = new Map(currentState);
1519
- Object.entries(action.payload).forEach(([key]) => {
1520
- newState.delete(key);
1521
- });
1522
- return newState.size === 0 ? undefined : newState;
1523
- case exports.Action.DATA_SAVED:
1524
- case exports.Action.EDITION_CANCELED:
1525
- return undefined;
1526
- }
1527
- return currentState;
1528
- }
1529
- }
1530
- const WaitingChangesReducer = new WaitingCheangesReducerImpl();
1531
- const getWaitingChanges = (stateManager) => {
1532
- return stateManager.select(WaitingChangesReducer.sliceName, (state) => state);
1533
- };
1534
- const isWaiting = (stateManager, fieldName) => {
1535
- const allWC = getWaitingChanges(stateManager);
1536
- return allWC ? allWC.has(fieldName) : false;
1537
- };
1538
- const getBlockingWaitingChanges = (stateManager) => {
1539
- const allWC = getWaitingChanges(stateManager);
1540
- if (allWC) {
1541
- return new Map(Array.from(allWC.entries())
1542
- .filter(entry => entry[1].blocking)
1543
- .map(entry => [entry[0], entry[1]]));
1544
- }
1545
- };
1546
- const getWaitingChangePromisses = (stateManager) => {
1547
- const allWC = getWaitingChanges(stateManager);
1548
- if (allWC) {
1549
- return Array.from(allWC.values())
1550
- .filter(wc => !wc.blocking)
1551
- .map(wc => wc.promise);
1552
- }
1553
- };
1554
-
1555
- class ChangesReducerImpl {
1556
- constructor() {
1557
- this.sliceName = "hist::changes";
1558
- }
1559
- reduce(stateManager, currentState, action) {
1560
- switch (action.type) {
1561
- case exports.Action.RECORDS_COPIED:
1562
- const records = action.payload;
1563
- const changes = new Map(getChanges(stateManager));
1564
- records.forEach(r => {
1565
- const rChanges = Object.assign(Object.assign({}, changes.get(r.__record__id__)), r);
1566
- delete rChanges.__old__id__;
1567
- delete rChanges.__record__id__;
1568
- delete rChanges.__parent__record__id__;
1569
- delete rChanges.__record__source__id__;
1570
- delete rChanges.__copy__;
1571
- changes.set(r.__record__id__, rChanges);
1572
- });
1573
- return changes;
1574
- case exports.Action.DATA_CHANGED:
1575
- const selection = action.payload.records || getSelection(stateManager);
1576
- if (selection) {
1577
- const newState = new Map(currentState);
1578
- selection.forEach(recordId => {
1579
- const newChanges = Object.assign(Object.assign({}, newState.get(recordId)), action.payload);
1580
- delete newChanges.records;
1581
- newState.set(recordId, newChanges);
1582
- });
1583
- return newState;
1584
- }
1585
- return currentState;
1586
- case exports.Action.DATA_SAVED:
1587
- case exports.Action.EDITION_CANCELED:
1588
- return undefined;
1589
- }
1590
- return currentState;
1591
- }
1592
- }
1593
- const ChangesReducer = new ChangesReducerImpl();
1594
- const getChanges = (stateManager) => {
1595
- return stateManager.select(ChangesReducer.sliceName, (state) => state);
1596
- };
1597
- const isDirty = (stateManager) => {
1598
- if (getAddedRecords(stateManager) !== undefined) {
1599
- return true;
1600
- }
1601
- if (getRemovedRecords(stateManager) !== undefined) {
1602
- return true;
1603
- }
1604
- if (getWaitingChanges(stateManager) !== undefined) {
1605
- return true;
1606
- }
1607
- return getChanges(stateManager) !== undefined;
1608
- };
1609
- const getChangesToSave = (dataUnit, stateManager) => {
1610
- const result = [];
1611
- const changes = getChanges(stateManager);
1612
- const records = getRecords(stateManager);
1613
- records === null || records === void 0 ? void 0 : records.forEach(r => {
1614
- if (changes) {
1615
- const c = changes.get(r.__record__id__);
1616
- if (c) {
1617
- result.push(new Change(dataUnit, r, c, ChangeOperation.UPDATE));
1618
- }
1619
- }
1620
- });
1621
- const addedRecords = getAddedRecords(stateManager);
1622
- if (addedRecords) {
1623
- addedRecords.forEach(r => {
1624
- const operation = r.__copy__ ? ChangeOperation.COPY : ChangeOperation.INSERT;
1625
- result.push(new Change(dataUnit, r, changes === null || changes === void 0 ? void 0 : changes.get(r.__record__id__), operation, r.__record__source__id__));
1626
- });
1627
- }
1628
- const removedRecords = getRemovedRecords(stateManager);
1629
- const recordsById = {};
1630
- records === null || records === void 0 ? void 0 : records.forEach(r => recordsById[r.__record__id__] = r);
1631
- if (removedRecords) {
1632
- removedRecords.forEach(id => {
1633
- result.push(new Change(dataUnit, recordsById[id], undefined, ChangeOperation.DELETE));
1634
- });
1635
- }
1636
- return result;
1637
- };
1638
-
1639
- class LoadControlReducerImpl {
1640
- constructor() {
1641
- this.sliceName = "pagination";
1642
- }
1643
- reduce(stateManager, currentState, action) {
1644
- var _a;
1645
- switch (action.type) {
1646
- case exports.Action.LOADING_DATA:
1647
- return Object.assign(Object.assign({}, currentState), { lastRequest: action.payload });
1648
- case exports.Action.DATA_LOADED:
1649
- return Object.assign(Object.assign({}, currentState), { paginationInfo: (_a = action.payload) === null || _a === void 0 ? void 0 : _a.paginationInfo });
1650
- }
1651
- return currentState;
1652
- }
1653
- }
1654
- const LoadControlReducer = new LoadControlReducerImpl();
1655
- const getPaginationInfo = (stateManager) => {
1656
- const state = stateManager.select(LoadControlReducer.sliceName, (state) => state);
1657
- return state ? state.paginationInfo : undefined;
1658
- };
1659
- const getCurrentRequest = (stateManager) => {
1660
- const state = stateManager.select(LoadControlReducer.sliceName, (state) => state);
1661
- return state ? state.lastRequest : undefined;
1662
- };
1663
- const getCurrentPage = (stateManager) => {
1664
- const paginationInfo = getPaginationInfo(stateManager);
1665
- return paginationInfo ? paginationInfo.currentPage : 0;
1666
- };
1667
- const getLastPage = (stateManager, pageSize) => {
1668
- const paginationInfo = getPaginationInfo(stateManager);
1669
- return paginationInfo ? Math.ceil(paginationInfo.total / pageSize) : 0;
1670
- };
1671
- const hasMorePages = (stateManager) => {
1672
- const paginationInfo = getPaginationInfo(stateManager);
1673
- if (paginationInfo && paginationInfo.hasMore) {
1674
- return true;
1675
- }
1676
- return false;
1677
- };
1678
-
1679
- class UnitMetadataReducerImpl {
1680
- constructor() {
1681
- this.sliceName = "unitMetadata";
1682
- }
1683
- reduce(_stateManager, currentState, action) {
1684
- if (action.type === exports.Action.METADATA_LOADED) {
1685
- return action.payload;
1686
- }
1687
- return currentState;
1688
- }
1689
- }
1690
- const UnitMetadataReducer = new UnitMetadataReducerImpl();
1691
- const getMetadata = (stateManager) => {
1692
- return stateManager.select(UnitMetadataReducer.sliceName, (state) => state);
1693
- };
1694
- const getField = (stateManager, fieldName) => {
1695
- const md = getMetadata(stateManager);
1696
- return md ? md.fields.find(fmd => fmd.name === fieldName) : undefined;
1697
- };
1698
-
1699
- class HistReducerImpl {
1700
- constructor() {
1701
- this.sliceName = "";
1702
- }
1703
- reduce(stateManager, _currentState, action) {
1704
- switch (action.type) {
1705
- case exports.Action.DATA_SAVED:
1706
- case exports.Action.EDITION_CANCELED:
1707
- stateManager.clearUndo();
1708
- break;
1709
- case exports.Action.CHANGE_UNDONE:
1710
- stateManager.undo();
1711
- break;
1712
- case exports.Action.CHANGE_REDONE:
1713
- stateManager.redo();
1714
- break;
1715
- }
1716
- }
1717
- }
1718
- const HistReducer = new HistReducerImpl();
1719
- const canUndo = (stateManager) => {
1720
- return stateManager.canUndo();
1721
- };
1722
- const canRedo = (stateManager) => {
1723
- return stateManager.canRedo();
1724
- };
1725
-
1726
- var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
1727
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
1728
- return new (P || (P = Promise))(function (resolve, reject) {
1729
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
1730
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
1731
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
1732
- step((generator = generator.apply(thisArg, _arguments || [])).next());
1733
- });
1734
- };
1735
- class DataUnit {
1736
- constructor(name) {
1737
- this._name = name;
1738
- this._pageSize = 0;
1739
- this._stateManager = new StateManager([
1740
- HistReducer,
1741
- UnitMetadataReducer,
1742
- LoadControlReducer,
1743
- RecordsReducer,
1744
- RemovedRecordsReducer,
1745
- AddedRecordsReducer,
1746
- SelectionReducer,
1747
- ChangesReducer,
1748
- WaitingChangesReducer,
1749
- CurrentRecordsReducer
1750
- ]);
1751
- this._observers = [];
1752
- this._filterProviders = new Map();
1753
- this._sortingProvider = undefined;
1754
- this._interceptors = [];
1755
- }
1756
- get name() {
1757
- return this._name;
1758
- }
1759
- // Métodos privados
1760
- validateAndTypeValue(fieldName, newValue) {
1761
- const descriptor = this.getField(fieldName);
1762
- return descriptor ? convertType(descriptor.dataType, newValue) : newValue;
1763
- }
1764
- getFilters() {
1765
- let filters = undefined;
1766
- this._filterProviders.forEach(p => {
1767
- const f = p.getFilter(this.name);
1768
- if (f) {
1769
- filters = (filters || []).concat(f);
1770
- }
1771
- });
1772
- return filters;
1773
- }
1774
- getSort() {
1775
- return this._sortingProvider ? this._sortingProvider.getSort(this._name) : undefined;
1776
- }
1777
- getFielterProviderKey(provider) {
1778
- if (provider.getKey) {
1779
- return provider.getKey();
1780
- }
1781
- return StringUtils.hashCode(provider.getFilter.toString());
1782
- }
1783
- executeLoadData(request, executionCtx) {
1784
- return new Promise((resolve, fail) => __awaiter(this, void 0, void 0, function* () {
1785
- if (yield this.dispatchAction(exports.Action.LOADING_DATA, request, executionCtx)) {
1786
- if (this.dataLoader) {
1787
- this.dataLoader(this, request).then(response => {
1788
- this.dispatchAction(exports.Action.DATA_LOADED, response, executionCtx);
1789
- resolve(response);
1790
- }).catch(error => fail(new ErrorException("Problema carregando registros", error)));
1791
- }
1792
- }
1793
- }));
1794
- }
1795
- // Loaders
1796
- loadMetadata(executionCtx) {
1797
- return __awaiter(this, void 0, void 0, function* () {
1798
- if (yield this.dispatchAction(exports.Action.LOADING_METADATA, undefined, executionCtx)) {
1799
- return new Promise((resolve, fail) => {
1800
- if (this.metadataLoader) {
1801
- this.metadataLoader(this).then(metadata => {
1802
- this.metadata = metadata;
1803
- resolve(this.metadata);
1804
- }).catch(error => fail(new ErrorException("Problema carregando metadados", error)));
1805
- }
1806
- });
1807
- }
1808
- });
1809
- }
1810
- loadData(quickFilter, executionCtx) {
1811
- return __awaiter(this, void 0, void 0, function* () {
1812
- const loadDataRequest = {
1813
- quickFilter,
1814
- filters: this.getFilters(),
1815
- sort: this.getSort()
1816
- };
1817
- if (this._pageSize > 0) {
1818
- loadDataRequest.limit = this._pageSize;
1819
- loadDataRequest.offset = 0;
1820
- }
1821
- return this.executeLoadData(loadDataRequest, executionCtx);
1822
- });
1823
- }
1824
- gotoPage(page, executionCtx) {
1825
- return __awaiter(this, void 0, void 0, function* () {
1826
- let request = getCurrentRequest(this._stateManager);
1827
- if (!request) {
1828
- request = {
1829
- filters: this.getFilters(),
1830
- sort: this.getSort()
1831
- };
1832
- }
1833
- if (page >= 0 && page <= getLastPage(this._stateManager, this._pageSize)) {
1834
- return this.executeLoadData(Object.assign(Object.assign({}, request), { limit: this._pageSize, offset: page * this._pageSize }), executionCtx);
1835
- }
1836
- });
1837
- }
1838
- nextPage(executionCtx) {
1839
- return __awaiter(this, void 0, void 0, function* () {
1840
- return this.gotoPage(getCurrentPage(this._stateManager) + 1, executionCtx);
1841
- });
1842
- }
1843
- previousPage(executionCtx) {
1844
- return __awaiter(this, void 0, void 0, function* () {
1845
- return this.gotoPage(getCurrentPage(this._stateManager) - 1, executionCtx);
1846
- });
1847
- }
1848
- saveData(executionCtx) {
1849
- return __awaiter(this, void 0, void 0, function* () {
1850
- const blockingWaitingChanges = getBlockingWaitingChanges(this._stateManager);
1851
- if (blockingWaitingChanges && blockingWaitingChanges.size > 0) {
1852
- const [field, waitingChange] = blockingWaitingChanges.entries().next().value;
1853
- return Promise.reject(new WaitingChangeException("Aguardando alteração de campo", waitingChange.waitmessage));
1854
- }
1855
- else {
1856
- if (isDirty(this._stateManager)) {
1857
- if (yield this.dispatchAction(exports.Action.SAVING_DATA, undefined, executionCtx)) {
1858
- const promisses = getWaitingChangePromisses(this._stateManager);
1859
- return new Promise((resolve, fail) => {
1860
- Promise.all(promisses || []).then(() => {
1861
- if (this.saveLoader) {
1862
- const changes = getChangesToSave(this._name, this._stateManager);
1863
- this.saveLoader(this, changes).then(records => {
1864
- this.dispatchAction(exports.Action.DATA_SAVED, { changes, records }, executionCtx);
1865
- resolve();
1866
- }).catch(cause => fail(new ErrorException("Erro salvando alterações", cause)));
1867
- }
1868
- else {
1869
- resolve();
1870
- }
1871
- });
1872
- });
1873
- }
1874
- }
1875
- }
1876
- return Promise.resolve();
1877
- });
1878
- }
1879
- removeSelectedRecords(buffered = false) {
1880
- return __awaiter(this, void 0, void 0, function* () {
1881
- const selection = getSelection(this._stateManager);
1882
- if (selection) {
1883
- return this.removeRecords(selection, buffered);
1884
- }
1885
- return Promise.resolve(selection);
1886
- });
1887
- }
1888
- removeRecords(records, buffered = false, executionCtx) {
1889
- return __awaiter(this, void 0, void 0, function* () {
1890
- if (records) {
1891
- if (buffered || !this.removeLoader) {
1892
- this.dispatchAction(exports.Action.RECORDS_REMOVED, { records, buffered: true }, executionCtx);
1893
- }
1894
- else {
1895
- if (yield this.dispatchAction(exports.Action.REMOVING_RECORDS, undefined, executionCtx)) {
1896
- return new Promise((resolve, fail) => {
1897
- if (this.removeLoader) {
1898
- this.removeLoader(this, records).then(records => {
1899
- let currentIndex = 0;
1900
- const removedIndex = [];
1901
- const currentRecords = getCurrentRecords(this._stateManager);
1902
- currentRecords.forEach((value, key) => {
1903
- if (records.includes(key)) {
1904
- removedIndex.push(currentIndex);
1905
- }
1906
- currentIndex++;
1907
- });
1908
- this.dispatchAction(exports.Action.RECORDS_REMOVED, { records, removedIndex, buffered: false }, executionCtx);
1909
- resolve(records);
1910
- }).catch(error => fail(new ErrorException("Problema removendo registros", error)));
1911
- }
1912
- });
1913
- }
1914
- }
1915
- }
1916
- return Promise.resolve(records);
1917
- });
1918
- }
1919
- // API
1920
- valueFromString(fieldName, value) {
1921
- const descriptor = this.getField(fieldName);
1922
- return descriptor ? convertType(descriptor.dataType, value) : value;
1923
- }
1924
- valueToString(fieldName, value) {
1925
- const descriptor = this.getField(fieldName);
1926
- return toString(descriptor === null || descriptor === void 0 ? void 0 : descriptor.dataType, value);
1927
- }
1928
- addInterceptor(interceptor) {
1929
- this._interceptors.push(interceptor);
1930
- }
1931
- removeInterceptor(interceptor) {
1932
- this._interceptors = this._interceptors.filter(i => i !== interceptor);
1933
- }
1934
- addFilterProvider(provider) {
1935
- this._filterProviders.set(this.getFielterProviderKey(provider), provider);
1936
- }
1937
- getPaginationInfo() {
1938
- return getPaginationInfo(this._stateManager);
1939
- }
1940
- set sortingProvider(provider) {
1941
- this._sortingProvider = provider;
1942
- }
1943
- set metadata(md) {
1944
- this.dispatchAction(exports.Action.METADATA_LOADED, md, undefined);
1945
- }
1946
- get metadata() {
1947
- return getMetadata(this._stateManager);
1948
- }
1949
- set records(r) {
1950
- this.dispatchAction(exports.Action.DATA_LOADED, { records: this.records }, undefined);
1951
- }
1952
- get records() {
1953
- const records = getCurrentRecords(this._stateManager);
1954
- return records ? Array.from(records.values()) : [];
1955
- }
1956
- set pageSize(size) {
1957
- this._pageSize = size;
1958
- }
1959
- get pageSize() {
1960
- return this._pageSize;
1961
- }
1962
- getModifiedRecords() {
1963
- const modified = getModifiedRecords(this._stateManager);
1964
- return modified || [];
1965
- }
1966
- getField(fieldName) {
1967
- return getField(this._stateManager, fieldName);
1968
- }
1969
- addRecord(executionCtx) {
1970
- this.dispatchAction(exports.Action.RECORDS_ADDED, prepareAddedRecordId(this._stateManager, [{}]), executionCtx);
1971
- }
1972
- copySelected(executionCtx) {
1973
- const selectedRecords = this.getSelectedRecords();
1974
- if (selectedRecords) {
1975
- this.dispatchAction(exports.Action.RECORDS_COPIED, prepareCopiedRecord(this._stateManager, selectedRecords), executionCtx);
1976
- }
1977
- }
1978
- waitingForChange(fieldName) {
1979
- return isWaiting(this._stateManager, fieldName);
1980
- }
1981
- getFieldValue(fieldName) {
1982
- return getFieldValue(this._stateManager, fieldName);
1983
- }
1984
- setFieldValue(fieldName, newValue, records) {
1985
- const typedValue = this.validateAndTypeValue(fieldName, newValue);
1986
- const currentValue = this.getFieldValue(fieldName);
1987
- if (currentValue !== typedValue) {
1988
- this.dispatchAction(exports.Action.DATA_CHANGED, { [fieldName]: typedValue, records }, undefined);
1989
- }
1990
- }
1991
- startChange(fieldName, waitingChange) {
1992
- this.dispatchAction(exports.Action.CHANGING_DATA, { [fieldName]: waitingChange }, undefined);
1993
- }
1994
- cancelWaitingChange(fieldName) {
1995
- this.dispatchAction(exports.Action.WAITING_CHANGE_CANCELED, { fieldName }, undefined);
1996
- }
1997
- getSelection() {
1998
- return getSelection(this._stateManager);
1999
- }
2000
- setSelection(selection, executionCtx) {
2001
- this.dispatchAction(exports.Action.SELECTION_CHANGED, { type: "id", selection }, executionCtx);
2002
- }
2003
- selectFirst(executionCtx) {
2004
- if (this.records.length > 0) {
2005
- this.setSelectionByIndex([0], executionCtx);
2006
- }
2007
- }
2008
- selectLast(executionCtx) {
2009
- if (this.records.length > 0) {
2010
- this.setSelectionByIndex([this.records.length - 1], executionCtx);
2011
- }
2012
- }
2013
- setSelectionByIndex(selection, executionCtx) {
2014
- this.dispatchAction(exports.Action.SELECTION_CHANGED, { type: "index", selection }, executionCtx);
2015
- }
2016
- getSelectedRecords() {
2017
- const selection = this.getSelection();
2018
- if (selection) {
2019
- const currentRecords = this.records;
2020
- return currentRecords === null || currentRecords === void 0 ? void 0 : currentRecords.filter(r => selection.includes(r.__record__id__));
2021
- }
2022
- }
2023
- nextRecord(executionCtx) {
2024
- if (!hasNext(this._stateManager)) {
2025
- if (hasMorePages(this._stateManager)) {
2026
- this.nextPage({
2027
- before: act => {
2028
- if (executionCtx && executionCtx.before) {
2029
- act = executionCtx.before(act);
2030
- }
2031
- return act;
2032
- },
2033
- after: act => {
2034
- this.selectFirst(executionCtx);
2035
- }
2036
- });
2037
- }
2038
- }
2039
- else {
2040
- this.dispatchAction(exports.Action.NEXT_SELECTED, undefined, executionCtx);
2041
- }
2042
- }
2043
- previousRecord(executionCtx) {
2044
- if (!hasPrevious(this._stateManager)) {
2045
- if (getCurrentPage(this._stateManager) > 0) {
2046
- this.previousPage({
2047
- before: act => {
2048
- if (executionCtx && executionCtx.before) {
2049
- act = executionCtx.before(act);
2050
- }
2051
- return act;
2052
- },
2053
- after: act => {
2054
- this.selectLast(executionCtx);
2055
- }
2056
- });
2057
- }
2058
- }
2059
- else {
2060
- this.dispatchAction(exports.Action.PREVIOUS_SELECTED, undefined, executionCtx);
2061
- }
2062
- }
2063
- cancelEdition(executionCtx) {
2064
- this.dispatchAction(exports.Action.EDITION_CANCELED, undefined, executionCtx);
2065
- }
2066
- isDirty() {
2067
- return isDirty(this._stateManager);
2068
- }
2069
- hasNext() {
2070
- let result = hasNext(this._stateManager);
2071
- if (!result) {
2072
- result = hasMorePages(this._stateManager);
2073
- }
2074
- return result;
2075
- }
2076
- hasPrevious() {
2077
- let result = hasPrevious(this._stateManager);
2078
- if (!result) {
2079
- result = getCurrentPage(this._stateManager) > 0;
2080
- }
2081
- return result;
2082
- }
2083
- canUndo() {
2084
- return canUndo(this._stateManager);
2085
- }
2086
- canRedo() {
2087
- return canRedo(this._stateManager);
2088
- }
2089
- undo(executionCtx) {
2090
- this.dispatchAction(exports.Action.CHANGE_UNDONE, undefined, executionCtx);
2091
- }
2092
- redo(executionCtx) {
2093
- this.dispatchAction(exports.Action.CHANGE_REDONE, undefined, executionCtx);
2094
- }
2095
- toString() {
2096
- return this.name;
2097
- }
2098
- // Actions / State manager
2099
- dispatchAction(actionType, payload, executionCtx) {
2100
- return __awaiter(this, void 0, void 0, function* () {
2101
- return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {
2102
- let action = new DataUnitAction(actionType, payload);
2103
- if (executionCtx && executionCtx.before) {
2104
- action = executionCtx.before(action);
2105
- }
2106
- if (action && this._interceptors && this._interceptors.length > 0) {
2107
- action = yield this.intercept(action, this._interceptors.values());
2108
- }
2109
- if (action) {
2110
- this.doDispatchAction(action);
2111
- if (executionCtx && executionCtx.after) {
2112
- executionCtx.after(action);
2113
- }
2114
- resolve(true);
2115
- }
2116
- else {
2117
- resolve(false);
2118
- }
2119
- }));
2120
- });
2121
- }
2122
- intercept(action, interceptors) {
2123
- return __awaiter(this, void 0, void 0, function* () {
2124
- return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () {
2125
- let ite;
2126
- while (action && !(ite = interceptors.next()).done) {
2127
- action = yield ite.value.interceptAction(action);
2128
- }
2129
- resolve(action);
2130
- }));
2131
- });
2132
- }
2133
- doDispatchAction(action) {
2134
- this._stateManager.process(action);
2135
- this._observers.forEach(f => {
2136
- /*
2137
- if some observer throws exceptions,
2138
- should be continued
2139
- */
2140
- try {
2141
- f(action);
2142
- }
2143
- catch (e) {
2144
- console.warn("[DataUnit] error while call observer", e);
2145
- }
2146
- });
2147
- }
2148
- subscribe(observer) {
2149
- this._observers.push(observer);
2150
- }
2151
- unsubscribe(observer) {
2152
- this._observers = this._observers.filter(f => f !== observer);
2153
- }
2154
- }
2155
- var ChangeOperation;
2156
- (function (ChangeOperation) {
2157
- ChangeOperation["INSERT"] = "INSERT";
2158
- ChangeOperation["COPY"] = "COPY";
2159
- ChangeOperation["UPDATE"] = "UPDATE";
2160
- ChangeOperation["DELETE"] = "DELETE";
2161
- })(ChangeOperation || (ChangeOperation = {}));
2162
- class Change {
2163
- constructor(dataUnit, record, updates, operation, sourceId) {
2164
- this.dataUnit = dataUnit;
2165
- this.record = record;
2166
- this.sourceId = sourceId;
2167
- this.updatingFields = updates;
2168
- this._operation = operation;
2169
- }
2170
- get operation() {
2171
- return this._operation.toString();
2172
- }
2173
- isInsert() {
2174
- return this._operation === ChangeOperation.INSERT;
2175
- }
2176
- isCopy() {
2177
- return this._operation === ChangeOperation.COPY;
2178
- }
2179
- isDelete() {
2180
- return this._operation === ChangeOperation.DELETE;
2181
- }
2182
- isUpdate() {
2183
- return this._operation === ChangeOperation.UPDATE;
2184
- }
2185
- }
2186
-
2187
- exports.SortMode = void 0;
2188
- (function (SortMode) {
2189
- SortMode["ASC"] = "ASC";
2190
- SortMode["DESC"] = "DESC";
2191
- })(exports.SortMode || (exports.SortMode = {}));
2192
- var DependencyType;
2193
- (function (DependencyType) {
2194
- DependencyType["SEARCHING"] = "SEARCHING";
2195
- DependencyType["REQUIREMENT"] = "REQUIREMENT";
2196
- DependencyType["VISIBILITY"] = "REQUIREMENT";
2197
- })(DependencyType || (DependencyType = {}));
2198
- exports.UserInterface = void 0;
2199
- (function (UserInterface) {
2200
- UserInterface["FILE"] = "FILE";
2201
- UserInterface["IMAGE"] = "IMAGE";
2202
- UserInterface["DATE"] = "DATE";
2203
- UserInterface["DATETIME"] = "DATETIME";
2204
- UserInterface["TIME"] = "TIME";
2205
- UserInterface["ELAPSEDTIME"] = "ELAPSEDTIME";
2206
- UserInterface["CHECKBOX"] = "CHECKBOX";
2207
- UserInterface["SWITCH"] = "SWITCH";
2208
- UserInterface["OPTIONSELECTOR"] = "OPTIONSELECTOR";
2209
- UserInterface["DECIMALNUMBER"] = "DECIMALNUMBER";
2210
- UserInterface["INTEGERNUMBER"] = "INTEGERNUMBER";
2211
- UserInterface["SEARCH"] = "SEARCH";
2212
- UserInterface["SHORTTEXT"] = "SHORTTEXT";
2213
- UserInterface["PASSWORD"] = "PASSWORD";
2214
- UserInterface["MASKEDTEXT"] = "MASKEDTEXT";
2215
- UserInterface["LONGTEXT"] = "LONGTEXT";
2216
- UserInterface["HTML"] = "HTML";
2217
- })(exports.UserInterface || (exports.UserInterface = {}));
2218
-
2219
- class ApplicationContext {
2220
- static getContextValue(key) {
2221
- return ApplicationContext.getCtx()[key];
2222
- }
2223
- static setContextValue(key, value) {
2224
- ApplicationContext.getCtx()[key] = value;
2225
- }
2226
- static getCtx() {
2227
- let ctx = window.___snkcore___ctx___;
2228
- if (!ctx) {
2229
- ctx = {};
2230
- window.___snkcore___ctx___ = ctx;
2231
- }
2232
- return ctx;
2233
- }
2234
- }
2235
-
2236
- class ReadyUtil {
2237
- clean() {
2238
- this.resolve = undefined;
2239
- this.promise = undefined;
2240
- }
2241
- start() {
2242
- if (!this.promise)
2243
- this.promise = new Promise((accept) => {
2244
- this.resolve = () => accept(true);
2245
- });
2246
- }
2247
- end() {
2248
- this.resolve && this.resolve();
2249
- }
2250
- whenReady() {
2251
- this.start();
2252
- return new Promise((accept) => {
2253
- this.promise.then(() => {
2254
- accept(true);
2255
- this.clean();
2256
- });
2257
- });
2258
- }
2259
- }
2260
-
2261
- class ObjectUtils {
2262
- static copy(data) {
2263
- return this.stringToObject(this.objectToString(data));
2264
- }
2265
- static objectToString(data) {
2266
- return JSON.stringify(data);
2267
- }
2268
- static stringToObject(data) {
2269
- return JSON.parse(data);
2270
- }
2271
- }
2272
-
2273
- class WarningException extends Error {
2274
- constructor(title, message) {
2275
- super(message);
2276
- this.title = title;
2277
- this.message = message;
2278
- }
2279
- }
2280
-
2281
- class ErrorTracking {
2282
- static init() {
2283
- const rollbar = window.Rollbar;
2284
- if (rollbar) {
2285
- rollbar.configure({
2286
- checkIgnore: function (isUncaught, args, payload) {
2287
- return args[1] ? ErrorTracking.isInternalException(args[1]) : false;
2288
- }
2289
- });
2290
- }
2291
- }
2292
- static isInternalException(error) {
2293
- return (error instanceof ErrorException || error instanceof WaitingChangeException || error instanceof WarningException);
2294
- }
2295
- }
2296
-
2297
- exports.ApplicationContext = ApplicationContext;
2298
- exports.DataUnit = DataUnit;
2299
- exports.DataUnitAction = DataUnitAction;
2300
- exports.DateUtils = DateUtils;
2301
- exports.FloatingManager = FloatingManager;
2302
- exports.MaskFormatter = MaskFormatter;
2303
- exports.NumberUtils = NumberUtils;
2304
- exports.ObjectUtils = ObjectUtils;
2305
- exports.StringUtils = StringUtils;
2306
- exports.TimeFormatter = TimeFormatter;
2307
- exports.WaitingChangeException = WaitingChangeException;