@bnsights/bbsf-utilities 1.0.32 → 1.0.33

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 (124) hide show
  1. package/README.md +4 -4
  2. package/bnsights-bbsf-utilities-1.0.33.tgz +0 -0
  3. package/bnsights-bbsf-utilities.d.ts +0 -1
  4. package/bnsights-bbsf-utilities.metadata.json +1 -0
  5. package/bundles/bnsights-bbsf-utilities.umd.js +4865 -0
  6. package/bundles/bnsights-bbsf-utilities.umd.js.map +1 -0
  7. package/esm2015/lib/bbsf-utilities.module.js +52 -0
  8. package/esm2015/lib/shared/authentication/auth.service.js +236 -0
  9. package/esm2015/lib/shared/config/word/constants.js +105 -0
  10. package/esm2015/lib/shared/config/word/docx-document.js +351 -0
  11. package/esm2015/lib/shared/config/word/helpers/index.js +4 -0
  12. package/esm2015/lib/shared/config/word/helpers/render-document-file.js +278 -0
  13. package/esm2015/lib/shared/config/word/helpers/xml-builder.js +1765 -0
  14. package/esm2015/lib/shared/config/word/html-to-docx.js +195 -0
  15. package/esm2015/lib/shared/config/word/index.js +55 -0
  16. package/esm2015/lib/shared/config/word/namespaces.js +37 -0
  17. package/esm2015/lib/shared/config/word/schemas/content-types.js +26 -0
  18. package/esm2015/lib/shared/config/word/schemas/core.js +29 -0
  19. package/esm2015/lib/shared/config/word/schemas/document-rels.js +16 -0
  20. package/esm2015/lib/shared/config/word/schemas/document.template.js +109 -0
  21. package/esm2015/lib/shared/config/word/schemas/font-table.js +40 -0
  22. package/esm2015/lib/shared/config/word/schemas/generic-rels.js +11 -0
  23. package/esm2015/lib/shared/config/word/schemas/index.js +13 -0
  24. package/esm2015/lib/shared/config/word/schemas/numbering.js +19 -0
  25. package/esm2015/lib/shared/config/word/schemas/rels.js +11 -0
  26. package/esm2015/lib/shared/config/word/schemas/settings.js +13 -0
  27. package/esm2015/lib/shared/config/word/schemas/styles.js +149 -0
  28. package/esm2015/lib/shared/config/word/schemas/theme.js +200 -0
  29. package/esm2015/lib/shared/config/word/schemas/web-settings.js +9 -0
  30. package/esm2015/lib/shared/config/word/utils/color-conversion.js +60 -0
  31. package/esm2015/lib/shared/config/word/utils/list.js +51 -0
  32. package/esm2015/lib/shared/config/word/utils/unit-conversion.js +30 -0
  33. package/esm2015/lib/shared/config/word/utils/url.js +9 -0
  34. package/esm2015/lib/shared/config/word/utils/vnode.js +3 -0
  35. package/esm2015/lib/shared/config/word/word-work/templates/documentTemplate.js +54 -0
  36. package/esm2015/lib/shared/config/word/word-work/templates/index.js +4 -0
  37. package/esm2015/lib/shared/config/word/word-work/templates/mhtDocumentTemplate.js +22 -0
  38. package/esm2015/lib/shared/config/word/word-work/templates/mhtPartTemplate.js +10 -0
  39. package/esm2015/lib/shared/config/word/word-work/utils.js +26 -0
  40. package/esm2015/lib/shared/models/WordDocumentModel.js +8 -0
  41. package/esm2015/lib/shared/services/AppearanceConfiguration.service.js +37 -0
  42. package/esm2015/lib/shared/services/configuration.service.js +26 -0
  43. package/esm2015/lib/shared/services/controlvalidation.service.js +168 -0
  44. package/esm2015/lib/shared/services/environment.service.js +48 -0
  45. package/esm2015/lib/shared/services/masterlayout.service.js +96 -0
  46. package/esm2015/lib/shared/services/requesthandler.service.js +206 -0
  47. package/esm2015/lib/shared/services/stylesbundle.service.js +56 -0
  48. package/esm2015/lib/shared/services/translate.service.js +13 -0
  49. package/esm2015/lib/shared/services/translationresolver.service.js +20 -0
  50. package/esm2015/lib/shared/services/utility.service.js +96 -0
  51. package/esm2015/lib/shared/services/word-document.service.js +39 -0
  52. package/esm2015/public-api.js +20 -0
  53. package/fesm2015/bnsights-bbsf-utilities.js +4634 -0
  54. package/fesm2015/bnsights-bbsf-utilities.js.map +1 -0
  55. package/lib/bbsf-utilities.module.d.ts +0 -9
  56. package/lib/shared/authentication/auth.service.d.ts +0 -3
  57. package/lib/shared/config/word/constants.d.ts +124 -0
  58. package/lib/shared/config/word/docx-document.d.ts +73 -0
  59. package/lib/shared/config/word/helpers/index.d.ts +1 -0
  60. package/lib/shared/config/word/helpers/render-document-file.d.ts +4 -0
  61. package/lib/shared/config/word/helpers/xml-builder.d.ts +14 -0
  62. package/lib/shared/config/word/html-to-docx.d.ts +1 -0
  63. package/lib/shared/config/word/index.d.ts +1 -0
  64. package/lib/shared/config/word/namespaces.d.ts +36 -0
  65. package/lib/shared/config/word/schemas/content-types.d.ts +1 -0
  66. package/lib/shared/config/word/schemas/core.d.ts +1 -0
  67. package/lib/shared/config/word/schemas/document-rels.d.ts +1 -0
  68. package/lib/shared/config/word/schemas/document.template.d.ts +4 -0
  69. package/lib/shared/config/word/schemas/font-table.d.ts +1 -0
  70. package/lib/shared/config/word/schemas/generic-rels.d.ts +1 -0
  71. package/lib/shared/config/word/schemas/index.d.ts +12 -0
  72. package/lib/shared/config/word/schemas/numbering.d.ts +1 -0
  73. package/lib/shared/config/word/schemas/rels.d.ts +1 -0
  74. package/lib/shared/config/word/schemas/settings.d.ts +1 -0
  75. package/lib/shared/config/word/schemas/styles.d.ts +1 -0
  76. package/lib/shared/config/word/schemas/theme.d.ts +1 -0
  77. package/lib/shared/config/word/schemas/web-settings.d.ts +1 -0
  78. package/lib/shared/config/word/utils/color-conversion.d.ts +7 -0
  79. package/lib/shared/config/word/utils/list.d.ts +6 -0
  80. package/lib/shared/config/word/utils/unit-conversion.d.ts +29 -0
  81. package/lib/shared/config/word/utils/url.d.ts +1 -0
  82. package/lib/shared/config/word/utils/vnode.d.ts +1 -0
  83. package/lib/shared/config/word/word-work/templates/documentTemplate.d.ts +12 -0
  84. package/lib/shared/config/word/word-work/templates/index.d.ts +3 -0
  85. package/lib/shared/config/word/word-work/templates/mhtDocumentTemplate.d.ts +1 -0
  86. package/lib/shared/config/word/word-work/templates/mhtPartTemplate.d.ts +1 -0
  87. package/lib/shared/config/word/word-work/utils.d.ts +1 -0
  88. package/lib/shared/models/WordDocumentModel.d.ts +16 -0
  89. package/lib/shared/services/AppearanceConfiguration.service.d.ts +0 -3
  90. package/lib/shared/services/configuration.service.d.ts +0 -3
  91. package/lib/shared/services/controlvalidation.service.d.ts +0 -3
  92. package/lib/shared/services/environment.service.d.ts +0 -3
  93. package/lib/shared/services/masterlayout.service.d.ts +0 -3
  94. package/lib/shared/services/requesthandler.service.d.ts +0 -3
  95. package/lib/shared/services/stylesbundle.service.d.ts +0 -3
  96. package/lib/shared/services/translate.service.d.ts +0 -3
  97. package/lib/shared/services/translationresolver.service.d.ts +0 -3
  98. package/lib/shared/services/utility.service.d.ts +0 -3
  99. package/lib/shared/services/word-document.service.d.ts +5 -0
  100. package/package.json +7 -19
  101. package/public-api.d.ts +2 -0
  102. package/bnsights-bbsf-utilities-1.0.32.tgz +0 -0
  103. package/esm2020/lib/bbsf-utilities.module.mjs +0 -74
  104. package/esm2020/lib/shared/authentication/auth.service.mjs +0 -217
  105. package/esm2020/lib/shared/services/AppearanceConfiguration.service.mjs +0 -35
  106. package/esm2020/lib/shared/services/configuration.service.mjs +0 -24
  107. package/esm2020/lib/shared/services/controlvalidation.service.mjs +0 -166
  108. package/esm2020/lib/shared/services/environment.service.mjs +0 -50
  109. package/esm2020/lib/shared/services/masterlayout.service.mjs +0 -84
  110. package/esm2020/lib/shared/services/requesthandler.service.mjs +0 -202
  111. package/esm2020/lib/shared/services/stylesbundle.service.mjs +0 -55
  112. package/esm2020/lib/shared/services/translate.service.mjs +0 -14
  113. package/esm2020/lib/shared/services/translationresolver.service.mjs +0 -18
  114. package/esm2020/lib/shared/services/utility.service.mjs +0 -90
  115. package/esm2020/public-api.mjs +0 -18
  116. package/fesm2015/bnsights-bbsf-utilities.mjs +0 -1009
  117. package/fesm2015/bnsights-bbsf-utilities.mjs.map +0 -1
  118. package/fesm2020/bnsights-bbsf-utilities.mjs +0 -997
  119. package/fesm2020/bnsights-bbsf-utilities.mjs.map +0 -1
  120. /package/{esm2020/bnsights-bbsf-utilities.mjs → esm2015/bnsights-bbsf-utilities.js} +0 -0
  121. /package/{esm2020/lib/shared/config/environment.mjs → esm2015/lib/shared/config/environment.js} +0 -0
  122. /package/{esm2020/lib/shared/models/AreaModel.mjs → esm2015/lib/shared/models/AreaModel.js} +0 -0
  123. /package/{esm2020/lib/shared/models/ErrorModel.mjs → esm2015/lib/shared/models/ErrorModel.js} +0 -0
  124. /package/{esm2020/lib/shared/models/RequestOptionsModel.mjs → esm2015/lib/shared/models/RequestOptionsModel.js} +0 -0
@@ -0,0 +1,4634 @@
1
+ import * as i1$1 from '@angular/common';
2
+ import { DOCUMENT, CommonModule } from '@angular/common';
3
+ import * as i0 from '@angular/core';
4
+ import { Injectable, Inject, Injector, NgModule } from '@angular/core';
5
+ import * as i1$2 from '@angular/router';
6
+ import { Router, RouterModule } from '@angular/router';
7
+ import * as i1 from '@ngx-translate/core';
8
+ import { TranslateService } from '@ngx-translate/core';
9
+ import { BlockUI, BlockUIModule } from 'ng-block-ui';
10
+ import { ToastrService, ToastrModule } from 'ngx-toastr';
11
+ import { HttpModule } from '@angular/http';
12
+ import { __awaiter, __decorate, __rest } from 'tslib';
13
+ import * as i1$3 from '@angular/common/http';
14
+ import { HttpHeaders, HttpClient, HttpParams } from '@angular/common/http';
15
+ import { UserManager, WebStorageStateStore } from 'oidc-client';
16
+ import { Subject, Observable, throwError, BehaviorSubject } from 'rxjs';
17
+ import { takeUntil, tap, map } from 'rxjs/operators';
18
+ import { plainToClass } from 'class-transformer';
19
+ import JSZip from 'jszip';
20
+ import { fragment, create } from 'xmlbuilder2';
21
+ import VNode from 'virtual-dom/vnode/vnode';
22
+ import VText from 'virtual-dom/vnode/vtext';
23
+ import HTMLToVDOM from 'html-to-vdom';
24
+ import { cloneDeep } from 'lodash';
25
+ import { nanoid } from 'nanoid';
26
+ import isVNode from 'virtual-dom/vnode/is-vnode';
27
+ import isVText from 'virtual-dom/vnode/is-vtext';
28
+ import escape from 'escape-html';
29
+ import sizeOf from 'image-size';
30
+ import imageToBase64 from 'image-to-base64';
31
+ import mimeTypes from 'mime-types';
32
+ import colorNames from 'color-name';
33
+
34
+ // This file can be replaced during build by using the `fileReplacements` array.
35
+ // `ng build ---prod` replaces `environment.ts` with `environment.prod.ts`.
36
+ // The list of file replacements can be found in `angular.json`.
37
+ const environment = Object.assign({}, window.Environment);
38
+ /*
39
+ * In development mode, to ignore zone related error stack frames such as
40
+ * `zone.run`, `zoneDelegate.invokeTask` for easier debugging, you can
41
+ * import the following file, but please comment it out in production mode
42
+ * because it will have performance impact when throw error
43
+ */
44
+ // import 'zone.js/dist/zone-error'; // Included with Angular CLI.
45
+
46
+ class EnvironmentService {
47
+ getEnvironmentObject() {
48
+ return environment;
49
+ }
50
+ getBaseUrl() {
51
+ let Url = environment["BBSF_BaseURL"];
52
+ return Url;
53
+ }
54
+ getApiUrl() {
55
+ let Url = environment["BBSF_ApiUrl"];
56
+ return Url;
57
+ }
58
+ getProductionMode() {
59
+ let Mode = environment["BBSF_IsProduction"];
60
+ return Mode;
61
+ }
62
+ getDefaultLanguage() {
63
+ let Mode = environment["BBSF_DefaultLanguage"];
64
+ return Mode;
65
+ }
66
+ getIdentityServerUrl() {
67
+ let Url = environment["BBSF_IdentityServerUrl"];
68
+ return Url;
69
+ }
70
+ getIsIdentityServerExternal() {
71
+ let Mode = environment["BBSF_IsExternalIdentityServer"];
72
+ return Mode;
73
+ }
74
+ getIsIdentityServerClientId() {
75
+ let Mode = environment["BBSF_IdentityServer_Client_Id"];
76
+ return Mode;
77
+ }
78
+ getIsIdentityServerClientSecret() {
79
+ let Mode = environment["BBSF_IdentityServer_Client_Secret"];
80
+ return Mode;
81
+ }
82
+ }
83
+ EnvironmentService.AreaList = [];
84
+ EnvironmentService.ɵprov = i0.ɵɵdefineInjectable({ factory: function EnvironmentService_Factory() { return new EnvironmentService(); }, token: EnvironmentService, providedIn: "root" });
85
+ EnvironmentService.decorators = [
86
+ { type: Injectable, args: [{
87
+ providedIn: 'root'
88
+ },] }
89
+ ];
90
+
91
+ class BBSFTranslateService extends TranslateService {
92
+ }
93
+ BBSFTranslateService.ɵprov = i0.ɵɵdefineInjectable({ factory: function BBSFTranslateService_Factory() { return new BBSFTranslateService(i0.ɵɵinject(i1.TranslateStore), i0.ɵɵinject(i1.TranslateLoader), i0.ɵɵinject(i1.TranslateCompiler), i0.ɵɵinject(i1.TranslateParser), i0.ɵɵinject(i1.MissingTranslationHandler), i0.ɵɵinject(i1.USE_DEFAULT_LANG), i0.ɵɵinject(i1.USE_STORE), i0.ɵɵinject(i1.USE_EXTEND), i0.ɵɵinject(i1.DEFAULT_LANGUAGE)); }, token: BBSFTranslateService, providedIn: "root" });
94
+ BBSFTranslateService.decorators = [
95
+ { type: Injectable, args: [{
96
+ providedIn: 'root'
97
+ },] }
98
+ ];
99
+
100
+ class RequestOptionsModel {
101
+ constructor() {
102
+ this.disableSuccessNotification = false;
103
+ this.disableBlockUI = false;
104
+ this.disableErrorHandler = false;
105
+ this.responseType = "";
106
+ this.formGroup = null;
107
+ this.castResponsetoClass = true;
108
+ }
109
+ }
110
+
111
+ class RequestHandlerService {
112
+ constructor(http, authService, environmentService, utilityService, bbsfTranslateService, router) {
113
+ //using localStorage to avoid call getCurrentLanguage() because it is not all to use async in constructor
114
+ this.http = http;
115
+ this.authService = authService;
116
+ this.environmentService = environmentService;
117
+ this.utilityService = utilityService;
118
+ this.bbsfTranslateService = bbsfTranslateService;
119
+ this.router = router;
120
+ this.requestOptions = new RequestOptionsModel();
121
+ this.currentLanguage = "";
122
+ this.onDestroy$ = new Subject();
123
+ this.bbsfTranslateService.onLangChange.subscribe((event) => {
124
+ if (this.currentLanguage != event.lang) {
125
+ this.currentLanguage = event.lang;
126
+ }
127
+ });
128
+ }
129
+ getLuckyNumber() {
130
+ return Observable.create((subject) => {
131
+ setInterval(() => {
132
+ const number = Math.floor(Math.random() * 10);
133
+ console.log(number);
134
+ subject.next(number);
135
+ }, 1000);
136
+ }).pipe(takeUntil(this.onDestroy$));
137
+ }
138
+ get(Url, params, responseType, requestOptions) {
139
+ if (requestOptions)
140
+ this.requestOptions = requestOptions;
141
+ let headers = this.getHeaders();
142
+ if (!this.requestOptions.disableBlockUI)
143
+ this.utilityService.startBlockUI();
144
+ let object;
145
+ return this.http.get(this.environmentService.getApiUrl() + Url, { headers: headers, params: params }).pipe(takeUntil(this.onDestroy$), tap((result) => {
146
+ if (!this.requestOptions.disableBlockUI)
147
+ this.utilityService.stopBlockUI();
148
+ }, error => {
149
+ if (!this.requestOptions.disableErrorHandler)
150
+ this.handleError(error);
151
+ }), map((data) => {
152
+ if (this.requestOptions.castResponsetoClass)
153
+ return plainToClass(responseType, data, { excludeExtraneousValues: true });
154
+ else
155
+ return data;
156
+ }));
157
+ }
158
+ post(Url, model, responseType, params, requestOptions) {
159
+ if (requestOptions)
160
+ this.requestOptions = requestOptions;
161
+ let headers = this.getHeaders();
162
+ if (!this.requestOptions.disableBlockUI)
163
+ this.utilityService.startBlockUI();
164
+ return this.http.post(this.environmentService.getApiUrl() + Url, model, { headers: headers, params: params, responseType: this.requestOptions.responseType }).pipe(takeUntil(this.onDestroy$), tap((result) => {
165
+ if (!this.requestOptions.disableBlockUI)
166
+ this.utilityService.stopBlockUI();
167
+ }, error => {
168
+ if (!this.requestOptions.disableErrorHandler)
169
+ this.handleError(error);
170
+ }), map((data) => {
171
+ if (this.requestOptions.castResponsetoClass)
172
+ return plainToClass(responseType, data, { excludeExtraneousValues: true });
173
+ else
174
+ return data;
175
+ }));
176
+ }
177
+ delete(Url, deletedId, requestOptions, responseType, params) {
178
+ if (requestOptions)
179
+ this.requestOptions = requestOptions;
180
+ let headers = this.getHeaders();
181
+ if (!this.requestOptions.disableBlockUI)
182
+ this.utilityService.startBlockUI();
183
+ return this.http.delete(this.environmentService.getApiUrl() + Url + `/${deletedId}`, { headers: headers, params: params }).pipe(takeUntil(this.onDestroy$), tap((result) => {
184
+ if (!this.requestOptions.disableBlockUI)
185
+ this.utilityService.stopBlockUI();
186
+ }, error => {
187
+ if (!this.requestOptions.disableErrorHandler)
188
+ this.handleError(error);
189
+ }), map((data) => {
190
+ if (this.requestOptions.castResponsetoClass)
191
+ return plainToClass(responseType, data, { excludeExtraneousValues: true });
192
+ else
193
+ return data;
194
+ }));
195
+ }
196
+ put(Url, model, params, responseType, requestOptions) {
197
+ if (requestOptions)
198
+ this.requestOptions = requestOptions;
199
+ let headers = this.getHeaders();
200
+ if (!this.requestOptions.disableBlockUI)
201
+ this.utilityService.startBlockUI();
202
+ return this.http.put(this.environmentService.getApiUrl() + Url, model, { headers: headers, params: params, responseType: this.requestOptions.responseType }).pipe(takeUntil(this.onDestroy$), tap((result) => {
203
+ if (!this.requestOptions.disableBlockUI)
204
+ this.utilityService.stopBlockUI();
205
+ }, error => {
206
+ if (!this.requestOptions.disableErrorHandler)
207
+ this.handleError(error);
208
+ }), map((data) => {
209
+ if (this.requestOptions.castResponsetoClass)
210
+ return plainToClass(responseType, data, { excludeExtraneousValues: true });
211
+ else
212
+ return data;
213
+ }));
214
+ }
215
+ patch(Url, model, responseType, params, requestOptions) {
216
+ if (requestOptions)
217
+ this.requestOptions = requestOptions;
218
+ let headers = new HttpHeaders({
219
+ 'Content-Type': 'application/json',
220
+ 'Authorization': this.authService.authorizationHeaderValue(),
221
+ });
222
+ this.currentLanguage = localStorage.getItem('language');
223
+ headers = headers.set('Accept-Language', this.currentLanguage.toString());
224
+ headers = headers.set('ignore-cookies', 'true');
225
+ if (!this.requestOptions.disableBlockUI)
226
+ this.utilityService.startBlockUI();
227
+ return this.http.patch(this.environmentService.getApiUrl() + Url, model, { headers: headers, params: params, responseType: this.requestOptions.responseType }).pipe(takeUntil(this.onDestroy$), tap((result) => {
228
+ if (!this.requestOptions.disableBlockUI)
229
+ this.utilityService.stopBlockUI();
230
+ }, error => {
231
+ if (!this.requestOptions.disableErrorHandler)
232
+ this.handleError(error);
233
+ }), map((data) => {
234
+ if (this.requestOptions.castResponsetoClass)
235
+ return plainToClass(responseType, data, { excludeExtraneousValues: true });
236
+ else
237
+ return data;
238
+ }));
239
+ }
240
+ download(Url, params, requestOptions) {
241
+ if (requestOptions)
242
+ this.requestOptions = requestOptions;
243
+ let headers = this.getHeaders();
244
+ if (!this.requestOptions.disableBlockUI)
245
+ this.utilityService.startBlockUI();
246
+ return this.http.get(this.environmentService.getApiUrl() + Url, { headers: headers, params: params, responseType: this.requestOptions.responseType }).pipe(takeUntil(this.onDestroy$), tap((result) => {
247
+ if (!this.requestOptions.disableBlockUI)
248
+ this.utilityService.stopBlockUI();
249
+ }, error => {
250
+ if (!this.requestOptions.disableErrorHandler)
251
+ this.handleError(error);
252
+ }));
253
+ }
254
+ destroyHandler() {
255
+ this.onDestroy$.next();
256
+ }
257
+ ngOnDestroy() {
258
+ console.log("clearInterval");
259
+ this.destroyHandler();
260
+ }
261
+ handleError(err) {
262
+ var isEnglish = this.utilityService.getCurrentLanguage() == "en";
263
+ if (err.error instanceof ErrorEvent) {
264
+ this.utilityService.notifyErrorMessage();
265
+ }
266
+ else {
267
+ if (err.status == 400)
268
+ throwError(err); //error 400 is thrown to be catch by the Form component to handle Fluent validation errors
269
+ else if (err.status == 401)
270
+ this.router.navigate(["/Admin/account/login"]);
271
+ else if (err.status == 403)
272
+ this.utilityService.notifyErrorMessage(isEnglish ? "Sorry, You're not authorized to access this action" : "عذرا ليس لديك الصلاحيه لهذا الطلب");
273
+ else if (err.status == 510)
274
+ this.utilityService.notifyErrorMessage(isEnglish ? "Can not delete this item as it is related to others" : "لا يمكن حذف هذا العنصر لأنه مرتبط بعناصر أخرى");
275
+ else if (err.status == 515)
276
+ this.utilityService.notifyErrorMessage((err.error ? err.error.Message : err.message));
277
+ else {
278
+ console.log(`error message is: ${err.error ? err.error.Message : err.message}`);
279
+ this.utilityService.notifyErrorMessage(this.utilityService.getResourceValue("ErrorMassage"));
280
+ }
281
+ }
282
+ this.utilityService.stopBlockUI();
283
+ }
284
+ getHeaders() {
285
+ return new HttpHeaders({
286
+ 'Content-Type': 'application/json',
287
+ 'Authorization': this.authService.authorizationHeaderValue(),
288
+ 'Client-Local-Time-Zone': Intl.DateTimeFormat().resolvedOptions().timeZone,
289
+ 'Accept-Language': localStorage.getItem('language'),
290
+ 'ignore-cookies': 'true'
291
+ });
292
+ }
293
+ }
294
+ RequestHandlerService.decorators = [
295
+ { type: Injectable }
296
+ ];
297
+ RequestHandlerService.ctorParameters = () => [
298
+ { type: HttpClient },
299
+ { type: AuthService },
300
+ { type: EnvironmentService },
301
+ { type: UtilityService },
302
+ { type: BBSFTranslateService },
303
+ { type: Router }
304
+ ];
305
+
306
+ class StylesBundleService {
307
+ constructor(document, translateService) {
308
+ this.document = document;
309
+ this.translateService = translateService;
310
+ }
311
+ loadThemes(lang, bundleEnglishName, bundleArabicName) {
312
+ if (lang == "ar") {
313
+ this.loadStyleBundle(bundleArabicName.toString());
314
+ document.querySelector('html').setAttribute("b-lang", "ar"); //use b-lang instead of lang to fix firefox number inputs in Arabic locale
315
+ document.querySelector('html').setAttribute("dir", "rtl");
316
+ }
317
+ else {
318
+ this.loadStyleBundle(bundleEnglishName.toString());
319
+ document.querySelector('html').setAttribute("b-lang", "en");
320
+ document.querySelector('html').setAttribute("dir", "ltr");
321
+ }
322
+ }
323
+ loadThemesColor(theme, bundleDarkName, bundleLightName) {
324
+ if (theme == "Light")
325
+ this.loadStyleBundle(bundleLightName.toString());
326
+ else
327
+ this.loadStyleBundle(bundleDarkName.toString());
328
+ }
329
+ loadStyleBundle(styleName) {
330
+ const head = this.document.getElementsByTagName('head')[0];
331
+ let themeLink = this.document.getElementById('client-theme');
332
+ if (themeLink && themeLink.href.includes(styleName)) {
333
+ return;
334
+ }
335
+ else if (themeLink && !themeLink.href.includes(styleName)) {
336
+ themeLink.remove();
337
+ }
338
+ const style = this.document.createElement('link');
339
+ style.id = 'client-theme';
340
+ style.rel = 'stylesheet';
341
+ style.href = `${styleName}`;
342
+ head.appendChild(style);
343
+ }
344
+ }
345
+ StylesBundleService.ɵprov = i0.ɵɵdefineInjectable({ factory: function StylesBundleService_Factory() { return new StylesBundleService(i0.ɵɵinject(i1$1.DOCUMENT), i0.ɵɵinject(BBSFTranslateService)); }, token: StylesBundleService, providedIn: "root" });
346
+ StylesBundleService.decorators = [
347
+ { type: Injectable, args: [{
348
+ providedIn: 'root'
349
+ },] }
350
+ ];
351
+ StylesBundleService.ctorParameters = () => [
352
+ { type: Document, decorators: [{ type: Inject, args: [DOCUMENT,] }] },
353
+ { type: BBSFTranslateService }
354
+ ];
355
+
356
+ class MasterLayoutService {
357
+ constructor(router, http, authService, stylesBundleService, translate, environmentService) {
358
+ this.router = router;
359
+ this.http = http;
360
+ this.authService = authService;
361
+ this.stylesBundleService = stylesBundleService;
362
+ this.translate = translate;
363
+ this.environmentService = environmentService;
364
+ this.ApiUrl = '/api/Home/';
365
+ }
366
+ switchLang(lang, bundleEnglishName, bundleArabicName) {
367
+ this.changeLanguage(lang).subscribe((result) => {
368
+ this.updateUserInfo().subscribe((Value) => {
369
+ let UserInfoObject = Value;
370
+ this.authService.getUser();
371
+ this.authService.user.profile = Object.assign(this.authService.user.profile, UserInfoObject);
372
+ this.authService.storUser(this.authService.user);
373
+ this.stylesBundleService.loadThemes(lang, bundleEnglishName, bundleArabicName);
374
+ localStorage.setItem('language', lang);
375
+ this.translate.use(lang);
376
+ });
377
+ });
378
+ }
379
+ reloadComponent() {
380
+ let currentUrl = this.router.url;
381
+ this.router.routeReuseStrategy.shouldReuseRoute = () => false;
382
+ this.router.onSameUrlNavigation = 'reload';
383
+ this.router.navigate([currentUrl]);
384
+ }
385
+ changeLanguage(key) {
386
+ let params = new HttpParams();
387
+ params = params.append('UserId', this.authService.user.profile.id);
388
+ params = params.append('LanguageKey', key);
389
+ return this.http.post(this.ApiUrl + 'UpdateLanguage', null, null, params);
390
+ }
391
+ getUserClaims() {
392
+ return this.http.get(this.ApiUrl + 'GetUserClaims', null, null);
393
+ }
394
+ logError(error) {
395
+ let params = new HttpParams();
396
+ params = params.append('error', error);
397
+ return this.http.post(this.ApiUrl + 'LogError', null, null, params);
398
+ }
399
+ updateUserInfo() {
400
+ let isExternal = this.environmentService.getIsIdentityServerExternal().toLowerCase() == 'true';
401
+ if (isExternal)
402
+ return this.getUserClaims();
403
+ return this.http.get('/connect/userinfo');
404
+ }
405
+ switchRole(permissionSetID) {
406
+ this.updateRole(permissionSetID).subscribe((result) => {
407
+ this.updateUserInfo().subscribe((Value) => {
408
+ let UserInfoObject = Value;
409
+ this.authService.getUser();
410
+ this.authService.user.profile = Object.assign(this.authService.user.profile, UserInfoObject);
411
+ this.authService.storUser(this.authService.user);
412
+ });
413
+ });
414
+ }
415
+ updateRole(permissionSetID) {
416
+ let params = new HttpParams();
417
+ params = params.append('UserId', this.authService.user.profile.id);
418
+ params = params.append('RoleID', permissionSetID);
419
+ return this.http.post(this.ApiUrl + 'SwitchRole', null, null, params);
420
+ }
421
+ }
422
+ MasterLayoutService.ɵprov = i0.ɵɵdefineInjectable({ factory: function MasterLayoutService_Factory() { return new MasterLayoutService(i0.ɵɵinject(i1$2.Router), i0.ɵɵinject(RequestHandlerService), i0.ɵɵinject(AuthService), i0.ɵɵinject(StylesBundleService), i0.ɵɵinject(i1.TranslateService), i0.ɵɵinject(EnvironmentService)); }, token: MasterLayoutService, providedIn: "root" });
423
+ MasterLayoutService.decorators = [
424
+ { type: Injectable, args: [{
425
+ providedIn: 'root',
426
+ },] }
427
+ ];
428
+ MasterLayoutService.ctorParameters = () => [
429
+ { type: Router },
430
+ { type: RequestHandlerService },
431
+ { type: AuthService },
432
+ { type: StylesBundleService },
433
+ { type: TranslateService },
434
+ { type: EnvironmentService }
435
+ ];
436
+
437
+ class AuthService {
438
+ constructor(injector, http, environmentService, translateService, router) {
439
+ this.injector = injector;
440
+ this.http = http;
441
+ this.environmentService = environmentService;
442
+ this.translateService = translateService;
443
+ this.router = router;
444
+ // Observable navItem source
445
+ this._authNavStatusSource = new BehaviorSubject(false);
446
+ // Observable navItem stream
447
+ this.authNavStatus$ = this._authNavStatusSource.asObservable();
448
+ // Observable navItem source
449
+ this._userSource = new Subject();
450
+ this.UserStatus$ = this._userSource.asObservable();
451
+ this.manager = this.getUserManager();
452
+ this.redirectUrl = '';
453
+ this.manager.getUser().then((user) => __awaiter(this, void 0, void 0, function* () {
454
+ this.manager.storeUser(user);
455
+ AuthService.user = user;
456
+ this.user = user;
457
+ this._authNavStatusSource.next(yield this.isAuthenticated());
458
+ }));
459
+ this.manager.events.addAccessTokenExpired((_) => {
460
+ this._authNavStatusSource.next(false);
461
+ });
462
+ }
463
+ getUserManager() {
464
+ let user = null;
465
+ let isExternal = this.environmentService.getIsIdentityServerExternal().toLowerCase() ==
466
+ 'true';
467
+ if (isExternal) {
468
+ user = new UserManager({
469
+ authority: this.environmentService.getIdentityServerUrl(),
470
+ client_id: this.environmentService.getIsIdentityServerClientId(),
471
+ client_secret: this.environmentService.getIsIdentityServerClientSecret(),
472
+ redirect_uri: this.environmentService.getBaseUrl() +
473
+ '/Admin/authentication/auth-callback',
474
+ post_logout_redirect_uri: this.environmentService.getBaseUrl(),
475
+ response_type: 'code',
476
+ scope: 'openid profile email',
477
+ filterProtocolClaims: true,
478
+ loadUserInfo: true,
479
+ automaticSilentRenew: true,
480
+ silent_redirect_uri: this.environmentService.getBaseUrl() + '/assets/silent-callback.html',
481
+ userStore: new WebStorageStateStore({ store: window.localStorage }),
482
+ });
483
+ }
484
+ else {
485
+ user = new UserManager({
486
+ authority: this.environmentService.getIdentityServerUrl(),
487
+ client_id: 'angular_spa',
488
+ redirect_uri: this.environmentService.getBaseUrl() +
489
+ '/Admin/authentication/auth-callback',
490
+ post_logout_redirect_uri: this.environmentService.getBaseUrl(),
491
+ response_type: 'id_token token',
492
+ scope: 'openid profile email IdentityServerApi',
493
+ filterProtocolClaims: true,
494
+ loadUserInfo: true,
495
+ automaticSilentRenew: true,
496
+ silent_redirect_uri: this.environmentService.getBaseUrl() + '/assets/silent-callback.html',
497
+ userStore: new WebStorageStateStore({ store: window.localStorage }),
498
+ });
499
+ }
500
+ return user;
501
+ }
502
+ login() {
503
+ return this.manager.signinRedirect();
504
+ }
505
+ getUser() {
506
+ this.manager.getUser().then((user) => __awaiter(this, void 0, void 0, function* () {
507
+ AuthService.user = user;
508
+ this.user = user;
509
+ this._authNavStatusSource.next(yield this.isAuthenticated());
510
+ }));
511
+ }
512
+ storUser(User) {
513
+ this.manager.storeUser(User);
514
+ }
515
+ revokeAccessToken() {
516
+ this.manager.revokeAccessToken();
517
+ }
518
+ signinSilent() {
519
+ let x = this.manager.signinSilentCallback();
520
+ x.then((s) => {
521
+ //console.log(s)
522
+ });
523
+ }
524
+ completeAuthentication() {
525
+ return __awaiter(this, void 0, void 0, function* () {
526
+ this.user = yield this.manager.signinRedirectCallback();
527
+ AuthService.user = this.user;
528
+ this._userSource.next(AuthService.user);
529
+ this._authNavStatusSource.next(yield this.isAuthenticated());
530
+ let isExternal = this.environmentService.getIsIdentityServerExternal().toLowerCase() ==
531
+ 'true';
532
+ if (isExternal) {
533
+ const masterLayoutService = this.injector.get(MasterLayoutService);
534
+ let userClaims = yield masterLayoutService
535
+ .getUserClaims()
536
+ .toPromise()
537
+ .then((e) => {
538
+ AuthService.UserClaims = e;
539
+ }, (error) => {
540
+ console.log(error);
541
+ });
542
+ AuthService.user.profile = Object.assign(AuthService.user.profile, AuthService.UserClaims);
543
+ }
544
+ this.storUser(AuthService.user);
545
+ if (!localStorage.getItem('language') ||
546
+ localStorage.getItem('language') == this.user.profile.locale)
547
+ localStorage.setItem('language', this.user.profile.locale);
548
+ if (this.translateService.currentLang != localStorage.getItem('language')) {
549
+ this.translateService.resetLang(this.translateService.currentLang);
550
+ yield this.translateService
551
+ .reloadLang(localStorage.getItem('language'))
552
+ .subscribe((res) => {
553
+ console.log(res);
554
+ });
555
+ }
556
+ this._userSource.next(AuthService.user);
557
+ this._authNavStatusSource.next(yield this.isAuthenticated());
558
+ this.user = AuthService.user;
559
+ });
560
+ }
561
+ refreshToken(token) {
562
+ return __awaiter(this, void 0, void 0, function* () {
563
+ const httpOptions = {
564
+ headers: new HttpHeaders({
565
+ 'Content-Type': 'application/json',
566
+ Authorization: token,
567
+ }),
568
+ };
569
+ this.manager.revokeAccessToken();
570
+ return yield this.http
571
+ .post(`${this.environmentService.getIdentityServerUrl()}/users/refresh-token`, httpOptions, { withCredentials: true })
572
+ .subscribe((user) => {
573
+ this._userSource.next(user);
574
+ AuthService.user = user;
575
+ this.user = user;
576
+ });
577
+ });
578
+ }
579
+ getCurrentUser() {
580
+ return this.manager.getUser();
581
+ }
582
+ isAuthenticated() {
583
+ return __awaiter(this, void 0, void 0, function* () {
584
+ let user = yield this.manager.getUser().then((user) => {
585
+ return user;
586
+ });
587
+ return this.user != null && !this.user.expired;
588
+ });
589
+ }
590
+ isUserInRole(allowedPermission) {
591
+ let selectedPermissionSetID = Number.parseInt(this.user.profile['selectedpermissionsetid']);
592
+ return allowedPermission.includes(selectedPermissionSetID);
593
+ }
594
+ authorizationHeaderValue() {
595
+ return AuthService.user
596
+ ? `${AuthService.user.token_type} ${AuthService.user.access_token}`
597
+ : '';
598
+ }
599
+ name() {
600
+ return AuthService.user != null ? AuthService.user.profile.given_name : '';
601
+ }
602
+ setUrl(url) {
603
+ localStorage.setItem('redirectUrl', url);
604
+ }
605
+ getUrl() {
606
+ return localStorage.getItem('redirectUrl');
607
+ }
608
+ signinSilentCallback() {
609
+ return __awaiter(this, void 0, void 0, function* () {
610
+ let user = yield this.manager.signinSilentCallback();
611
+ //await this.manager.storeUser(user);
612
+ AuthService.user = user;
613
+ console.log('Token from signinSilentCallback :' + AuthService.user);
614
+ this.user = user;
615
+ });
616
+ }
617
+ signout() {
618
+ return __awaiter(this, void 0, void 0, function* () {
619
+ if (yield !this.isAuthenticated())
620
+ this.router.navigate(['/Admin/account/login']), localStorage.clear();
621
+ let isExternal = this.environmentService.getIsIdentityServerExternal().toLowerCase() ==
622
+ 'true';
623
+ if (isExternal) {
624
+ yield this.clearUserSessionClaims()
625
+ .toPromise()
626
+ .then((res) => {
627
+ let result = res;
628
+ });
629
+ }
630
+ yield this.manager.signoutRedirect();
631
+ });
632
+ }
633
+ clearUserSessionClaims() {
634
+ const httpOptions = {
635
+ headers: new HttpHeaders({
636
+ 'Content-Type': 'application/json',
637
+ }),
638
+ };
639
+ let ApiUrl = '/api/Home/';
640
+ return this.http.get(this.environmentService.getBaseUrl() + ApiUrl + 'ClearCurrentUserSession', httpOptions);
641
+ }
642
+ }
643
+ AuthService.user = null;
644
+ AuthService.UserClaims = null;
645
+ AuthService.ɵprov = i0.ɵɵdefineInjectable({ factory: function AuthService_Factory() { return new AuthService(i0.ɵɵinject(i0.INJECTOR), i0.ɵɵinject(i1$3.HttpClient), i0.ɵɵinject(EnvironmentService), i0.ɵɵinject(BBSFTranslateService), i0.ɵɵinject(i1$2.Router)); }, token: AuthService, providedIn: "root" });
646
+ AuthService.decorators = [
647
+ { type: Injectable, args: [{
648
+ providedIn: 'root',
649
+ },] }
650
+ ];
651
+ AuthService.ctorParameters = () => [
652
+ { type: Injector },
653
+ { type: HttpClient },
654
+ { type: EnvironmentService },
655
+ { type: BBSFTranslateService },
656
+ { type: Router }
657
+ ];
658
+
659
+ class UtilityService {
660
+ constructor(translator, authService, environmentService) {
661
+ this.translator = translator;
662
+ this.authService = authService;
663
+ this.environmentService = environmentService;
664
+ this.isCreatedBefore = false;
665
+ }
666
+ getResourceValue(Key) {
667
+ let ResourceValue = this.translator.instant(Key);
668
+ return ResourceValue;
669
+ }
670
+ getCurrentLanguage() {
671
+ let currentLanguage = this.environmentService.getDefaultLanguage();
672
+ let lang = localStorage.getItem('language');
673
+ if (lang)
674
+ currentLanguage = lang;
675
+ else
676
+ localStorage.setItem('language', currentLanguage);
677
+ return currentLanguage;
678
+ }
679
+ isCurrentLanguageEnglish() {
680
+ return this.getCurrentLanguage() == "en";
681
+ }
682
+ isCurrentLanguageArabic() {
683
+ return this.getCurrentLanguage() == "ar";
684
+ }
685
+ notifySuccessMessage(Message, title, time, showHeader = true) {
686
+ let MessageTemplate = this.getResourceValue("SuccessMessage");
687
+ let titleTemplate;
688
+ if (Message) {
689
+ MessageTemplate = Message;
690
+ }
691
+ if (title) {
692
+ titleTemplate = title;
693
+ }
694
+ let toaster = AppInjector.get(ToastrService);
695
+ showHeader ? toaster.success(MessageTemplate, titleTemplate) : toaster.success(MessageTemplate);
696
+ }
697
+ notifyErrorMessage(Message, title, time, showHeader = true) {
698
+ let MessageTemplate = this.getResourceValue("ErrorMessage");
699
+ let titleTemplate = this.getResourceValue("Error");
700
+ if (Message) {
701
+ MessageTemplate = Message;
702
+ }
703
+ if (title) {
704
+ titleTemplate = title;
705
+ }
706
+ const toaster = AppInjector.get(ToastrService);
707
+ showHeader ? toaster.error(MessageTemplate, titleTemplate) : toaster.error(MessageTemplate);
708
+ }
709
+ notifyWarningMessage(Message, title, time, showHeader = true) {
710
+ let MessageTemplate = this.getResourceValue("WarningMessage");
711
+ let titleTemplate = this.getResourceValue("Warning");
712
+ if (Message) {
713
+ MessageTemplate = Message;
714
+ }
715
+ if (title) {
716
+ titleTemplate = title;
717
+ }
718
+ const toaster = AppInjector.get(ToastrService);
719
+ showHeader ? toaster.warning(MessageTemplate, titleTemplate) : toaster.warning(MessageTemplate);
720
+ }
721
+ startBlockUI() {
722
+ this.blockUI.start();
723
+ }
724
+ stopBlockUI() {
725
+ this.blockUI.stop();
726
+ }
727
+ }
728
+ UtilityService.ɵprov = i0.ɵɵdefineInjectable({ factory: function UtilityService_Factory() { return new UtilityService(i0.ɵɵinject(BBSFTranslateService), i0.ɵɵinject(AuthService), i0.ɵɵinject(EnvironmentService)); }, token: UtilityService, providedIn: "root" });
729
+ UtilityService.decorators = [
730
+ { type: Injectable, args: [{
731
+ providedIn: 'root'
732
+ },] }
733
+ ];
734
+ UtilityService.ctorParameters = () => [
735
+ { type: BBSFTranslateService },
736
+ { type: AuthService },
737
+ { type: EnvironmentService }
738
+ ];
739
+ __decorate([
740
+ BlockUI()
741
+ ], UtilityService.prototype, "blockUI", void 0);
742
+
743
+ class ControlValidationService {
744
+ constructor(utilityService) {
745
+ this.utilityService = utilityService;
746
+ this.requestOptions = new RequestOptionsModel();
747
+ this.isCreatedBefor = false;
748
+ }
749
+ showGlobalError(errorMessage, formId, deleteOld) {
750
+ let globalErorrElement = document.getElementsByClassName('alert alert-InvalidValidation bg-light-danger text-danger');
751
+ if (globalErorrElement.length > 0) {
752
+ this.removeElementsByClass('alert alert-InvalidValidation bg-light-danger text-danger');
753
+ }
754
+ if (this.isCreatedBefor == true) {
755
+ this.removeElementsByClass('alert alert-InvalidValidation bg-light-danger text-danger');
756
+ }
757
+ // tslint:disable-next-line: prefer-const
758
+ if (!formId)
759
+ formId = "currentForm";
760
+ var object = document.getElementById(formId);
761
+ const tagName = 'div';
762
+ // tslint:disable-next-line: prefer-const
763
+ var elementToAppend = document.createElement(tagName); // Your tag name here
764
+ let message = "";
765
+ if (!errorMessage || (typeof errorMessage == "string")) {
766
+ if (localStorage.getItem('language') == "ar")
767
+ message = errorMessage ? errorMessage : "لديك بعص الأخطاء . من فضلك قم بالمراجعه ";
768
+ else
769
+ message = errorMessage ? errorMessage : "You have some validation errors. Please check below";
770
+ elementToAppend.innerHTML = "<ul class='list-unstyled m-0 py-3 d-flex align-items-center fs-6'><li><i class='fa fa-times-circle text-danger me-3 fs-2'></i>" + message + "</li></ul>";
771
+ elementToAppend.className += 'alert alert-InvalidValidation bg-light-danger text-danger';
772
+ elementToAppend.id += 'errorId';
773
+ // tslint:disable-next-line: prefer-for-of
774
+ const elementToAppen = elementToAppend.cloneNode(true);
775
+ // let targetElement = object.getElementsByClassName("b-control")[0];
776
+ object.insertBefore(elementToAppen, object.firstChild);
777
+ }
778
+ else {
779
+ elementToAppend.innerHTML = "<ul>";
780
+ for (const iterator of errorMessage) {
781
+ elementToAppend.innerHTML = "<li>" + iterator + "</li>";
782
+ }
783
+ elementToAppend.innerHTML = "</ul>";
784
+ elementToAppend.className += 'alert alert-InvalidValidation bg-light-danger text-danger';
785
+ elementToAppend.id += 'errorId';
786
+ // tslint:disable-next-line: prefer-for-of
787
+ const elementToAppen = elementToAppend.cloneNode(true);
788
+ // let targetElement = object.getElementsByClassName("b-control")[0];
789
+ object.insertBefore(elementToAppen, object.firstChild);
790
+ }
791
+ this.isCreatedBefor = true;
792
+ }
793
+ RemoveGlobalError() {
794
+ const removedList = document.getElementsByClassName('alert alert-InvalidValidation bg-light-danger text-danger');
795
+ // tslint:disable-next-line: prefer-for-of
796
+ for (let index = 0; index < removedList.length; index++) {
797
+ const element = removedList[index];
798
+ element.remove();
799
+ }
800
+ this.isCreatedBefor = false;
801
+ }
802
+ showInputErro(errors) {
803
+ // show error on top of form
804
+ this.showGlobalError();
805
+ // remove old error from server
806
+ this.removeElementsByClass('errortemplet');
807
+ // Looping in error Object
808
+ for (const key in errors) {
809
+ if (errors.hasOwnProperty(key)) {
810
+ for (const iterator of errors[key]) {
811
+ const input = document.querySelectorAll('[ng-reflect-name=' + key + ']')[0];
812
+ if (input.attributes['ng-reflect-name'].value === key) {
813
+ this.removeElementsByClass('erroclass-' + key);
814
+ const tagName = 'p';
815
+ const elementToAppend = document.createElement(tagName); // Your tag name here
816
+ elementToAppend.innerHTML = iterator;
817
+ elementToAppend.style.color = 'red';
818
+ elementToAppend.className += 'errortemplet erroclass-' + key;
819
+ const elementToappen = elementToAppend.cloneNode(true);
820
+ input.parentNode.insertBefore(elementToappen, input.lastChild);
821
+ break;
822
+ }
823
+ }
824
+ }
825
+ }
826
+ }
827
+ removeElementsByClass(className) {
828
+ const elements = document.getElementsByClassName(className);
829
+ while (elements.length > 0) {
830
+ elements[0].parentNode.removeChild(elements[0]);
831
+ }
832
+ }
833
+ renderServerErrors(form, err, requestOptions, formId) {
834
+ if (err.error == null) {
835
+ return;
836
+ }
837
+ let errorsArray = [];
838
+ this.requestOptions = requestOptions;
839
+ err.error.validation_errors.forEach((element) => {
840
+ let fieldName = element.field;
841
+ let controlName = element.controlName;
842
+ let message = element.message;
843
+ if (form == null) {
844
+ this.requestOptions.customErrorMessage ? this.utilityService.notifyErrorMessage(this.requestOptions.customErrorMessage) : this.utilityService.notifyErrorMessage(`${message}`);
845
+ }
846
+ else if (controlName && !this.hasControlName(form, controlName)) {
847
+ errorsArray.push(`${fieldName}: ${message}`);
848
+ // this.showGlobalError(`${fieldName}: ${message}`,formId )
849
+ }
850
+ else {
851
+ this.setFieldError(form, controlName, fieldName, message);
852
+ }
853
+ });
854
+ if (errorsArray.length > 0)
855
+ this.showGlobalError(errorsArray, formId);
856
+ }
857
+ hasControlName(form, controlName) {
858
+ let control = form.get(controlName);
859
+ return control != null;
860
+ }
861
+ setFieldError(form, controlName, fieldName, message) {
862
+ let control = null;
863
+ if (controlName)
864
+ control = form.get(controlName);
865
+ else
866
+ control = form.get(fieldName.split('.')[0]);
867
+ let errors = { "errorMassage": message };
868
+ let fieldNameArray = fieldName.split('.');
869
+ if (fieldNameArray.length >= 1) {
870
+ switch (fieldNameArray[fieldNameArray.length - 1].toLocaleLowerCase()) {
871
+ case "english":
872
+ let englishControl = control.get("English");
873
+ englishControl.setErrors(errors);
874
+ break;
875
+ case "arabic":
876
+ let arabicControl = control.get("Arabic");
877
+ arabicControl.setErrors(errors);
878
+ break;
879
+ default:
880
+ control.setErrors(errors);
881
+ }
882
+ }
883
+ else if (fieldNameArray.length == 1) {
884
+ control.setErrors(errors);
885
+ }
886
+ else {
887
+ this.requestOptions.customErrorMessage ? this.utilityService.notifyErrorMessage(this.requestOptions.customErrorMessage) : this.utilityService.notifyErrorMessage(`${message}`);
888
+ }
889
+ }
890
+ }
891
+ ControlValidationService.ɵprov = i0.ɵɵdefineInjectable({ factory: function ControlValidationService_Factory() { return new ControlValidationService(i0.ɵɵinject(UtilityService)); }, token: ControlValidationService, providedIn: "root" });
892
+ ControlValidationService.decorators = [
893
+ { type: Injectable, args: [{
894
+ providedIn: 'root'
895
+ },] }
896
+ ];
897
+ ControlValidationService.ctorParameters = () => [
898
+ { type: UtilityService }
899
+ ];
900
+ __decorate([
901
+ BlockUI()
902
+ ], ControlValidationService.prototype, "blockUI", void 0);
903
+
904
+ class ConfigurationService {
905
+ constructor(httpClient) {
906
+ this.httpClient = httpClient;
907
+ this.httpClient.get("./assets/config/configurations.json").subscribe(data => {
908
+ ConfigurationService.JsonData = data;
909
+ });
910
+ }
911
+ getConfigurationValue(key) {
912
+ return ConfigurationService.JsonData[key];
913
+ }
914
+ }
915
+ ConfigurationService.JsonData = [];
916
+ ConfigurationService.ɵprov = i0.ɵɵdefineInjectable({ factory: function ConfigurationService_Factory() { return new ConfigurationService(i0.ɵɵinject(i1$3.HttpClient)); }, token: ConfigurationService, providedIn: "root" });
917
+ ConfigurationService.decorators = [
918
+ { type: Injectable, args: [{
919
+ providedIn: 'root'
920
+ },] }
921
+ ];
922
+ ConfigurationService.ctorParameters = () => [
923
+ { type: HttpClient }
924
+ ];
925
+
926
+ let AppInjector;
927
+ class BBSFUtilitiesModule {
928
+ constructor(injector) {
929
+ this.injector = injector;
930
+ AppInjector = this.injector;
931
+ }
932
+ }
933
+ BBSFUtilitiesModule.decorators = [
934
+ { type: NgModule, args: [{
935
+ declarations: [],
936
+ imports: [
937
+ CommonModule,
938
+ BlockUIModule.forRoot(),
939
+ HttpModule,
940
+ RouterModule,
941
+ ToastrModule.forRoot(),
942
+ ],
943
+ exports: [],
944
+ providers: [
945
+ UtilityService,
946
+ EnvironmentService,
947
+ AuthService,
948
+ RequestHandlerService,
949
+ StylesBundleService,
950
+ TranslateService,
951
+ BBSFTranslateService,
952
+ ControlValidationService,
953
+ MasterLayoutService,
954
+ ConfigurationService
955
+ ]
956
+ },] }
957
+ ];
958
+ BBSFUtilitiesModule.ctorParameters = () => [
959
+ { type: Injector }
960
+ ];
961
+
962
+ class TranslationResolverService {
963
+ constructor(translateService) {
964
+ this.translateService = translateService;
965
+ }
966
+ resolve() {
967
+ return this.translateService.getTranslation(this.translateService.currentLang);
968
+ }
969
+ }
970
+ TranslationResolverService.ɵprov = i0.ɵɵdefineInjectable({ factory: function TranslationResolverService_Factory() { return new TranslationResolverService(i0.ɵɵinject(BBSFTranslateService)); }, token: TranslationResolverService, providedIn: "root" });
971
+ TranslationResolverService.decorators = [
972
+ { type: Injectable, args: [{ providedIn: 'root' },] }
973
+ ];
974
+ TranslationResolverService.ctorParameters = () => [
975
+ { type: BBSFTranslateService }
976
+ ];
977
+
978
+ class AppearanceConfigurationService {
979
+ constructor(configService) {
980
+ this.configService = configService;
981
+ }
982
+ getLayoutTheme() {
983
+ return this.configService.getConfigurationValue('AnonymousLayout_Theme');
984
+ }
985
+ getFooterText() {
986
+ return this.configService.getConfigurationValue('AnonymousLayout_FooterText');
987
+ }
988
+ getPageTitle() {
989
+ return this.configService.getConfigurationValue('AnonymousLayout_PageTitle');
990
+ }
991
+ getFavIcon() {
992
+ return this.configService.getConfigurationValue('AnonymousLayout_FavIcon');
993
+ }
994
+ getCustomStyles() {
995
+ return this.configService.getConfigurationValue('AnonymousLayout_CustomStyles');
996
+ }
997
+ getLogo() {
998
+ return this.configService.getConfigurationValue('AnonymousLayout_Logo');
999
+ }
1000
+ }
1001
+ AppearanceConfigurationService.ɵprov = i0.ɵɵdefineInjectable({ factory: function AppearanceConfigurationService_Factory() { return new AppearanceConfigurationService(i0.ɵɵinject(ConfigurationService)); }, token: AppearanceConfigurationService, providedIn: "root" });
1002
+ AppearanceConfigurationService.decorators = [
1003
+ { type: Injectable, args: [{
1004
+ providedIn: 'root'
1005
+ },] }
1006
+ ];
1007
+ AppearanceConfigurationService.ctorParameters = () => [
1008
+ { type: ConfigurationService }
1009
+ ];
1010
+
1011
+ const contentTypesXML = `
1012
+ <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
1013
+
1014
+ <Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
1015
+ <Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml" />
1016
+ <Default Extension="jpeg" ContentType="image/jpeg"/>
1017
+ <Default Extension="png" ContentType="image/png"/>
1018
+ <Default Extension="xml" ContentType="application/xml"/>
1019
+ <Override PartName="/_rels/.rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
1020
+ <Override PartName="/word/_rels/document.xml.rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
1021
+ <Override PartName="/word/_rels/footer1.xml.rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
1022
+ <Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>
1023
+ <Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/>
1024
+ <Override PartName="/word/numbering.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml"/>
1025
+ <Override PartName="/word/theme/theme1.xml" ContentType="application/vnd.openxmlformats-officedocument.theme+xml"/>
1026
+ <Override PartName="/word/fontTable.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.fontTable+xml"/>
1027
+ <Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/>
1028
+ <Override PartName="/word/settings.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml"/>
1029
+ <Override PartName="/word/webSettings.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.webSettings+xml"/>
1030
+ <Override PartName="/word/afchunk.mht" ContentType="message/rfc822"/>
1031
+ <Override PartName="/word/afchunkheader.mht" ContentType="message/rfc822"/>
1032
+ <Override PartName="/word/afchunkfooter.mht" ContentType="message/rfc822"/>
1033
+ </Types>
1034
+ `;
1035
+
1036
+ const namespaces = {
1037
+ a: 'http://schemas.openxmlformats.org/drawingml/2006/main',
1038
+ b: 'http://schemas.openxmlformats.org/officeDocument/2006/bibliography',
1039
+ cdr: 'http://schemas.openxmlformats.org/drawingml/2006/chartDrawing',
1040
+ dc: 'http://purl.org/dc/elements/1.1/',
1041
+ dcmitype: 'http://purl.org/dc/dcmitype/',
1042
+ dcterms: 'http://purl.org/dc/terms/',
1043
+ o: 'urn:schemas-microsoft-com:office:office',
1044
+ pic: 'http://schemas.openxmlformats.org/drawingml/2006/picture',
1045
+ r: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships',
1046
+ v: 'urn:schemas-microsoft-com:vml',
1047
+ ve: 'http://schemas.openxmlformats.org/markup-compatibility/2006',
1048
+ vt: 'http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes',
1049
+ w: 'http://schemas.openxmlformats.org/wordprocessingml/2006/main',
1050
+ w10: 'urn:schemas-microsoft-com:office:word',
1051
+ wp: 'http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing',
1052
+ wne: 'http://schemas.microsoft.com/office/word/2006/wordml',
1053
+ xsd: 'http://www.w3.org/2001/XMLSchema',
1054
+ xsi: 'http://www.w3.org/2001/XMLSchema-instance',
1055
+ numbering: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering',
1056
+ hyperlinks: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink',
1057
+ images: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/image',
1058
+ styles: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles',
1059
+ headers: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/header',
1060
+ footers: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/footer',
1061
+ themes: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/theme',
1062
+ coreProperties: 'http://schemas.openxmlformats.org/package/2006/metadata/core-properties',
1063
+ officeDocumentRelation: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument',
1064
+ corePropertiesRelation: 'http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties',
1065
+ settingsRelation: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/settings',
1066
+ webSettingsRelation: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships/webSettings',
1067
+ sl: 'http://schemas.openxmlformats.org/schemaLibrary/2006/main',
1068
+ contentTypes: 'http://schemas.openxmlformats.org/package/2006/content-types',
1069
+ relationship: 'http://schemas.openxmlformats.org/package/2006/relationships',
1070
+ };
1071
+
1072
+ const applicationName = 'html-to-docx';
1073
+ const defaultOrientation = 'portrait';
1074
+ const landscapeWidth = 15840;
1075
+ const landscapeHeight = 12240;
1076
+ const landscapeMargins = {
1077
+ top: 1800,
1078
+ right: 1440,
1079
+ bottom: 1800,
1080
+ left: 1440,
1081
+ header: 720,
1082
+ footer: 720,
1083
+ gutter: 0,
1084
+ };
1085
+ const portraitMargins = {
1086
+ top: 1440,
1087
+ right: 1800,
1088
+ bottom: 1440,
1089
+ left: 1800,
1090
+ header: 720,
1091
+ footer: 720,
1092
+ gutter: 0,
1093
+ };
1094
+ const defaultFont = 'Times New Roman';
1095
+ const defaultFontSize = 22;
1096
+ const defaultDocumentOptions = {
1097
+ orientation: defaultOrientation,
1098
+ margins: cloneDeep(portraitMargins),
1099
+ title: '',
1100
+ subject: '',
1101
+ creator: applicationName,
1102
+ keywords: [applicationName],
1103
+ description: '',
1104
+ lastModifiedBy: applicationName,
1105
+ revision: 1,
1106
+ createdAt: new Date(),
1107
+ modifiedAt: new Date(),
1108
+ headerType: 'default',
1109
+ header: false,
1110
+ footerType: 'default',
1111
+ footer: false,
1112
+ font: defaultFont,
1113
+ fontSize: defaultFontSize,
1114
+ complexScriptFontSize: defaultFontSize,
1115
+ table: {
1116
+ row: {
1117
+ cantSplit: false,
1118
+ },
1119
+ },
1120
+ pageSize: {
1121
+ width: landscapeHeight,
1122
+ height: landscapeWidth,
1123
+ },
1124
+ pageNumber: false,
1125
+ skipFirstHeaderFooter: false,
1126
+ lineNumber: false,
1127
+ lineNumberOptions: {
1128
+ countBy: 1,
1129
+ start: 0,
1130
+ restart: 'continuous',
1131
+ },
1132
+ numbering: {
1133
+ defaultOrderedListStyleType: 'decimal',
1134
+ },
1135
+ };
1136
+ const defaultHTMLString = '<p></p>';
1137
+ const relsFolderName = '_rels';
1138
+ const headerFileName = 'header1';
1139
+ const footerFileName = 'footer1';
1140
+ const themeFileName = 'theme1';
1141
+ const documentFileName = 'document';
1142
+ const headerType = 'header';
1143
+ const footerType = 'footer';
1144
+ const themeType = 'theme';
1145
+ const hyperlinkType = 'hyperlink';
1146
+ const imageType = 'image';
1147
+ const internalRelationship = 'Internal';
1148
+ const wordFolder = 'word';
1149
+ const themeFolder = 'theme';
1150
+ const paragraphBordersObject = {
1151
+ top: {
1152
+ size: 0,
1153
+ spacing: 3,
1154
+ color: 'FFFFFF',
1155
+ },
1156
+ left: {
1157
+ size: 0,
1158
+ spacing: 3,
1159
+ color: 'FFFFFF',
1160
+ },
1161
+ bottom: {
1162
+ size: 0,
1163
+ spacing: 3,
1164
+ color: 'FFFFFF',
1165
+ },
1166
+ right: {
1167
+ size: 0,
1168
+ spacing: 3,
1169
+ color: 'FFFFFF',
1170
+ },
1171
+ };
1172
+ const colorlessColors = ['transparent', 'auto'];
1173
+ const verticalAlignValues = ['top', 'middle', 'bottom'];
1174
+
1175
+ const generateCoreXML = (title = '', subject = '', creator = applicationName, keywords = [applicationName], description = '', lastModifiedBy = applicationName, revision = 1, createdAt = new Date(), modifiedAt = new Date()) => `
1176
+ <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
1177
+
1178
+ <cp:coreProperties
1179
+ xmlns:cp="${namespaces.coreProperties}"
1180
+ xmlns:dc="${namespaces.dc}"
1181
+ xmlns:dcterms="${namespaces.dcterms}"
1182
+ xmlns:dcmitype="${namespaces.dcmitype}"
1183
+ xmlns:xsi="${namespaces.xsi}"
1184
+ >
1185
+ <dc:title>${title}</dc:title>
1186
+ <dc:subject>${subject}</dc:subject>
1187
+ <dc:creator>${creator}</dc:creator>
1188
+ ${keywords && Array.isArray(keywords)
1189
+ ? `<cp:keywords>${keywords.join(', ')}</cp:keywords>`
1190
+ : ''}
1191
+ <dc:description>${description}</dc:description>
1192
+ <cp:lastModifiedBy>${lastModifiedBy}</cp:lastModifiedBy>
1193
+ <cp:revision>${revision}</cp:revision>
1194
+ <dcterms:created xsi:type="dcterms:W3CDTF">${createdAt instanceof Date ? createdAt.toISOString() : new Date().toISOString()}</dcterms:created>
1195
+ <dcterms:modified xsi:type="dcterms:W3CDTF">${modifiedAt instanceof Date ? modifiedAt.toISOString() : new Date().toISOString()}</dcterms:modified>
1196
+ </cp:coreProperties>
1197
+ `;
1198
+ const ɵ0$8 = generateCoreXML;
1199
+
1200
+ const documentRelsXML = `
1201
+ <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
1202
+
1203
+ <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
1204
+ <Relationship Id="rId1" Type="${namespaces.numbering}" Target="numbering.xml"/>
1205
+ <Relationship Id="rId2" Type="${namespaces.styles}" Target="styles.xml"/>
1206
+ <Relationship Id="rId3" Type="${namespaces.settingsRelation}" Target="settings.xml"/>
1207
+ <Relationship Id="rId4" Type="${namespaces.webSettingsRelation}" Target="webSettings.xml"/>
1208
+ <Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/aFChunk" Target="/word/afchunk.mht" Id="htmlChunk" />
1209
+ <Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/aFChunk" Target="/word/afchunkheader.mht" Id="htmlChunkHeader" />
1210
+ <Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/aFChunk" Target="/word/afchunkfooter.mht" Id="htmlChunkFooter" />
1211
+ </Relationships>
1212
+ `;
1213
+
1214
+ const relsXML = `
1215
+ <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
1216
+
1217
+ <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
1218
+ <Relationship Id="rId1" Type="${namespaces.officeDocumentRelation}" Target="word/document.xml"/>
1219
+ <Relationship Id="rId2" Type="${namespaces.corePropertiesRelation}" Target="docProps/core.xml"/>
1220
+ </Relationships>
1221
+ `;
1222
+
1223
+ const generateNumberingXMLTemplate = () => `
1224
+ <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
1225
+
1226
+ <w:numbering
1227
+ xmlns:w="${namespaces.w}"
1228
+ xmlns:ve="${namespaces.ve}"
1229
+ xmlns:o="${namespaces.o}"
1230
+ xmlns:r="${namespaces.r}"
1231
+ xmlns:v="${namespaces.v}"
1232
+ xmlns:wp="${namespaces.wp}"
1233
+ xmlns:w10="${namespaces.w10}"
1234
+ xmlns:wne="${namespaces.wne}">
1235
+ </w:numbering>
1236
+ `;
1237
+ const ɵ0$7 = generateNumberingXMLTemplate;
1238
+
1239
+ const generateStylesXML = (font = defaultFont, fontSize = defaultFontSize, complexScriptFontSize = defaultFontSize) => `
1240
+ <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
1241
+
1242
+ <w:styles xmlns:w="${namespaces.w}" xmlns:r="${namespaces.r}">
1243
+ <w:docDefaults>
1244
+ <w:rPrDefault>
1245
+ <w:rPr>
1246
+ <w:rFonts w:ascii="${font}" w:eastAsiaTheme="minorHAnsi" w:hAnsiTheme="minorHAnsi" w:cstheme="minorBidi" />
1247
+ <w:sz w:val="${fontSize}" />
1248
+ <w:szCs w:val="${complexScriptFontSize}" />
1249
+ <w:lang w:val="en-US" w:eastAsia="en-US" w:bidi="ar-SA" />
1250
+ </w:rPr>
1251
+ </w:rPrDefault>
1252
+ <w:pPrDefault>
1253
+ <w:pPr>
1254
+ <w:spacing w:after="120" w:line="240" w:lineRule="atLeast" />
1255
+ </w:pPr>
1256
+ </w:pPrDefault>
1257
+ </w:docDefaults>
1258
+ <w:style w:type="character" w:styleId="Hyperlink">
1259
+ <w:name w:val="Hyperlink" />
1260
+ <w:rPr>
1261
+ <w:color w:val="0000FF" />
1262
+ <w:u w:val="single" />
1263
+ </w:rPr>
1264
+ </w:style>
1265
+ <w:style w:type="paragraph" w:styleId="Heading1">
1266
+ <w:name w:val="heading 1" />
1267
+ <w:basedOn w:val="Normal" />
1268
+ <w:next w:val="Normal" />
1269
+ <w:uiPriority w:val="9" />
1270
+ <w:qFormat />
1271
+ <w:pPr>
1272
+ <w:keepNext />
1273
+ <w:keepLines />
1274
+ <w:spacing w:before="480" />
1275
+ <w:outlineLvl w:val="0" />
1276
+ </w:pPr>
1277
+ <w:rPr>
1278
+ <w:b />
1279
+ <w:sz w:val="48" />
1280
+ <w:szCs w:val="48" />
1281
+ </w:rPr>
1282
+ </w:style>
1283
+ <w:style w:type="paragraph" w:styleId="Heading2">
1284
+ <w:name w:val="heading 2" />
1285
+ <w:basedOn w:val="Normal" />
1286
+ <w:next w:val="Normal" />
1287
+ <w:uiPriority w:val="9" />
1288
+ <w:unhideWhenUsed />
1289
+ <w:qFormat />
1290
+ <w:pPr>
1291
+ <w:keepNext />
1292
+ <w:keepLines />
1293
+ <w:spacing w:before="360" w:after="80" />
1294
+ <w:outlineLvl w:val="1" />
1295
+ </w:pPr>
1296
+ <w:rPr>
1297
+ <w:b />
1298
+ <w:sz w:val="36" />
1299
+ <w:szCs w:val="36" />
1300
+ </w:rPr>
1301
+ </w:style>
1302
+ <w:style w:type="paragraph" w:styleId="Heading3">
1303
+ <w:name w:val="heading 3" />
1304
+ <w:basedOn w:val="Normal" />
1305
+ <w:next w:val="Normal" />
1306
+ <w:uiPriority w:val="9" />
1307
+ <w:semiHidden />
1308
+ <w:unhideWhenUsed />
1309
+ <w:qFormat />
1310
+ <w:pPr>
1311
+ <w:keepNext />
1312
+ <w:keepLines />
1313
+ <w:spacing w:before="280" w:after="80" />
1314
+ <w:outlineLvl w:val="2" />
1315
+ </w:pPr>
1316
+ <w:rPr>
1317
+ <w:b />
1318
+ <w:sz w:val="28" />
1319
+ <w:szCs w:val="28" />
1320
+ </w:rPr>
1321
+ </w:style>
1322
+ <w:style w:type="paragraph" w:styleId="Heading4">
1323
+ <w:name w:val="heading 4" />
1324
+ <w:basedOn w:val="Normal" />
1325
+ <w:next w:val="Normal" />
1326
+ <w:uiPriority w:val="9" />
1327
+ <w:semiHidden />
1328
+ <w:unhideWhenUsed />
1329
+ <w:qFormat />
1330
+ <w:pPr>
1331
+ <w:keepNext />
1332
+ <w:keepLines />
1333
+ <w:spacing w:before="240" w:after="40" />
1334
+ <w:outlineLvl w:val="3" />
1335
+ </w:pPr>
1336
+ <w:rPr>
1337
+ <w:b />
1338
+ <w:sz w:val="24" />
1339
+ <w:szCs w:val="24" />
1340
+ </w:rPr>
1341
+ </w:style>
1342
+ <w:style w:type="paragraph" w:styleId="Heading5">
1343
+ <w:name w:val="heading 5" />
1344
+ <w:basedOn w:val="Normal" />
1345
+ <w:next w:val="Normal" />
1346
+ <w:uiPriority w:val="9" />
1347
+ <w:semiHidden />
1348
+ <w:unhideWhenUsed />
1349
+ <w:qFormat />
1350
+ <w:pPr>
1351
+ <w:keepNext />
1352
+ <w:keepLines />
1353
+ <w:spacing w:before="220" w:after="40" />
1354
+ <w:outlineLvl w:val="4" />
1355
+ </w:pPr>
1356
+ <w:rPr>
1357
+ <w:b />
1358
+ </w:rPr>
1359
+ </w:style>
1360
+ <w:style w:type="paragraph" w:styleId="Heading6">
1361
+ <w:name w:val="heading 6" />
1362
+ <w:basedOn w:val="Normal" />
1363
+ <w:next w:val="Normal" />
1364
+ <w:uiPriority w:val="9" />
1365
+ <w:semiHidden />
1366
+ <w:unhideWhenUsed />
1367
+ <w:qFormat />
1368
+ <w:pPr>
1369
+ <w:keepNext />
1370
+ <w:keepLines />
1371
+ <w:spacing w:before="200" w:after="40" />
1372
+ <w:outlineLvl w:val="5" />
1373
+ </w:pPr>
1374
+ <w:rPr>
1375
+ <w:b />
1376
+ <w:sz w:val="20" />
1377
+ <w:szCs w:val="20" />
1378
+ </w:rPr>
1379
+ </w:style>
1380
+ </w:styles>
1381
+ `;
1382
+ const ɵ0$6 = generateStylesXML;
1383
+
1384
+ const fontTableXML = `
1385
+ <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
1386
+
1387
+ <w:fonts
1388
+ xmlns:r="${namespaces.r}"
1389
+ xmlns:w="${namespaces.w}"
1390
+ >
1391
+ <w:font w:name="Symbol">
1392
+ <w:panose1 w:val="05050102010706020507"/>
1393
+ <w:charset w:val="02"/>
1394
+ <w:family w:val="decorative"/>
1395
+ <w:pitch w:val="variable"/>
1396
+ <w:sig w:usb0="00000000" w:usb1="10000000" w:usb2="00000000" w:usb3="00000000" w:csb0="80000000" w:csb1="00000000"/>
1397
+ </w:font>
1398
+ <w:font w:name="Calibri">
1399
+ <w:panose1 w:val="020F0502020204030204"/>
1400
+ <w:charset w:val="00"/>
1401
+ <w:family w:val="swiss"/>
1402
+ <w:pitch w:val="variable"/>
1403
+ <w:sig w:usb0="E4002EFF" w:usb1="C000247B" w:usb2="00000009" w:usb3="00000000" w:csb0="000001FF" w:csb1="00000000"/>
1404
+ </w:font>
1405
+ <w:font w:name="Times New Roman">
1406
+ <w:panose1 w:val="02020603050405020304"/>
1407
+ <w:charset w:val="00"/>
1408
+ <w:family w:val="roman"/>
1409
+ <w:pitch w:val="variable"/>
1410
+ <w:sig w:usb0="E0002EFF" w:usb1="C000785B" w:usb2="00000009" w:usb3="00000000" w:csb0="000001FF" w:csb1="00000000"/>
1411
+ </w:font>
1412
+ <w:font w:name="Calibri Light">
1413
+ <w:panose1 w:val="020F0302020204030204"/>
1414
+ <w:charset w:val="00"/>
1415
+ <w:family w:val="swiss"/>
1416
+ <w:pitch w:val="variable"/>
1417
+ <w:sig w:usb0="E4002EFF" w:usb1="C000247B" w:usb2="00000009" w:usb3="00000000" w:csb0="000001FF" w:csb1="00000000"/>
1418
+ </w:font>
1419
+ </w:fonts>
1420
+ `;
1421
+
1422
+ const generateThemeXML = (font = defaultFont) => `
1423
+ <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
1424
+
1425
+ <a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="Office Theme">
1426
+ <a:themeElements>
1427
+ <a:clrScheme name="Office">
1428
+ <a:dk1>
1429
+ <a:sysClr val="windowText" lastClr="000000"/>
1430
+ </a:dk1>
1431
+ <a:lt1>
1432
+ <a:sysClr val="window" lastClr="FFFFFF"/>
1433
+ </a:lt1>
1434
+ <a:dk2>
1435
+ <a:srgbClr val="44546A"/>
1436
+ </a:dk2>
1437
+ <a:lt2>
1438
+ <a:srgbClr val="E7E6E6"/>
1439
+ </a:lt2>
1440
+ <a:accent1>
1441
+ <a:srgbClr val="4472C4"/>
1442
+ </a:accent1>
1443
+ <a:accent2>
1444
+ <a:srgbClr val="ED7D31"/>
1445
+ </a:accent2>
1446
+ <a:accent3>
1447
+ <a:srgbClr val="A5A5A5"/>
1448
+ </a:accent3>
1449
+ <a:accent4>
1450
+ <a:srgbClr val="FFC000"/>
1451
+ </a:accent4>
1452
+ <a:accent5>
1453
+ <a:srgbClr val="5B9BD5"/>
1454
+ </a:accent5>
1455
+ <a:accent6>
1456
+ <a:srgbClr val="70AD47"/>
1457
+ </a:accent6>
1458
+ <a:hlink>
1459
+ <a:srgbClr val="0563C1"/>
1460
+ </a:hlink>
1461
+ <a:folHlink>
1462
+ <a:srgbClr val="954F72"/>
1463
+ </a:folHlink>
1464
+ </a:clrScheme>
1465
+ <a:fontScheme name="Office">
1466
+ <a:majorFont>
1467
+ <a:latin typeface="${font}"/>
1468
+ <a:ea typeface="${font}"/>
1469
+ <a:cs typeface=""/>
1470
+ </a:majorFont>
1471
+ <a:minorFont>
1472
+ <a:latin typeface="${font}"/>
1473
+ <a:ea typeface="${font}"/>
1474
+ <a:cs typeface=""/>
1475
+ </a:minorFont>
1476
+ </a:fontScheme>
1477
+ <a:fmtScheme name="Office">
1478
+ <a:fillStyleLst>
1479
+ <a:solidFill>
1480
+ <a:schemeClr val="phClr"/>
1481
+ </a:solidFill>
1482
+ <a:gradFill rotWithShape="1">
1483
+ <a:gsLst>
1484
+ <a:gs pos="0">
1485
+ <a:schemeClr val="phClr">
1486
+ <a:lumMod val="110000"/>
1487
+ <a:satMod val="105000"/>
1488
+ <a:tint val="67000"/>
1489
+ </a:schemeClr>
1490
+ </a:gs>
1491
+ <a:gs pos="50000">
1492
+ <a:schemeClr val="phClr">
1493
+ <a:lumMod val="105000"/>
1494
+ <a:satMod val="103000"/>
1495
+ <a:tint val="73000"/>
1496
+ </a:schemeClr>
1497
+ </a:gs>
1498
+ <a:gs pos="100000">
1499
+ <a:schemeClr val="phClr">
1500
+ <a:lumMod val="105000"/>
1501
+ <a:satMod val="109000"/>
1502
+ <a:tint val="81000"/>
1503
+ </a:schemeClr>
1504
+ </a:gs>
1505
+ </a:gsLst>
1506
+ <a:lin ang="5400000" scaled="0"/>
1507
+ </a:gradFill>
1508
+ <a:gradFill rotWithShape="1">
1509
+ <a:gsLst>
1510
+ <a:gs pos="0">
1511
+ <a:schemeClr val="phClr">
1512
+ <a:satMod val="103000"/>
1513
+ <a:lumMod val="102000"/>
1514
+ <a:tint val="94000"/>
1515
+ </a:schemeClr>
1516
+ </a:gs>
1517
+ <a:gs pos="50000">
1518
+ <a:schemeClr val="phClr">
1519
+ <a:satMod val="110000"/>
1520
+ <a:lumMod val="100000"/>
1521
+ <a:shade val="100000"/>
1522
+ </a:schemeClr>
1523
+ </a:gs>
1524
+ <a:gs pos="100000">
1525
+ <a:schemeClr val="phClr">
1526
+ <a:lumMod val="99000"/>
1527
+ <a:satMod val="120000"/>
1528
+ <a:shade val="78000"/>
1529
+ </a:schemeClr>
1530
+ </a:gs>
1531
+ </a:gsLst>
1532
+ <a:lin ang="5400000" scaled="0"/>
1533
+ </a:gradFill>
1534
+ </a:fillStyleLst>
1535
+ <a:lnStyleLst>
1536
+ <a:ln w="6350" cap="flat" cmpd="sng" algn="ctr">
1537
+ <a:solidFill>
1538
+ <a:schemeClr val="phClr"/>
1539
+ </a:solidFill>
1540
+ <a:prstDash val="solid"/>
1541
+ <a:miter lim="800000"/>
1542
+ </a:ln>
1543
+ <a:ln w="12700" cap="flat" cmpd="sng" algn="ctr">
1544
+ <a:solidFill>
1545
+ <a:schemeClr val="phClr"/>
1546
+ </a:solidFill>
1547
+ <a:prstDash val="solid"/>
1548
+ <a:miter lim="800000"/>
1549
+ </a:ln>
1550
+ <a:ln w="19050" cap="flat" cmpd="sng" algn="ctr">
1551
+ <a:solidFill>
1552
+ <a:schemeClr val="phClr"/>
1553
+ </a:solidFill>
1554
+ <a:prstDash val="solid"/>
1555
+ <a:miter lim="800000"/>
1556
+ </a:ln>
1557
+ </a:lnStyleLst>
1558
+ <a:effectStyleLst>
1559
+ <a:effectStyle>
1560
+ <a:effectLst/>
1561
+ </a:effectStyle>
1562
+ <a:effectStyle>
1563
+ <a:effectLst/>
1564
+ </a:effectStyle>
1565
+ <a:effectStyle>
1566
+ <a:effectLst>
1567
+ <a:outerShdw blurRad="57150" dist="19050" dir="5400000" algn="ctr" rotWithShape="0">
1568
+ <a:srgbClr val="000000">
1569
+ <a:alpha val="63000"/>
1570
+ </a:srgbClr>
1571
+ </a:outerShdw>
1572
+ </a:effectLst>
1573
+ </a:effectStyle>
1574
+ </a:effectStyleLst>
1575
+ <a:bgFillStyleLst>
1576
+ <a:solidFill>
1577
+ <a:schemeClr val="phClr"/>
1578
+ </a:solidFill>
1579
+ <a:solidFill>
1580
+ <a:schemeClr val="phClr">
1581
+ <a:tint val="95000"/>
1582
+ <a:satMod val="170000"/>
1583
+ </a:schemeClr>
1584
+ </a:solidFill>
1585
+ <a:gradFill rotWithShape="1">
1586
+ <a:gsLst>
1587
+ <a:gs pos="0">
1588
+ <a:schemeClr val="phClr">
1589
+ <a:tint val="93000"/>
1590
+ <a:satMod val="150000"/>
1591
+ <a:shade val="98000"/>
1592
+ <a:lumMod val="102000"/>
1593
+ </a:schemeClr>
1594
+ </a:gs>
1595
+ <a:gs pos="50000">
1596
+ <a:schemeClr val="phClr">
1597
+ <a:tint val="98000"/>
1598
+ <a:satMod val="130000"/>
1599
+ <a:shade val="90000"/>
1600
+ <a:lumMod val="103000"/>
1601
+ </a:schemeClr>
1602
+ </a:gs>
1603
+ <a:gs pos="100000">
1604
+ <a:schemeClr val="phClr">
1605
+ <a:shade val="63000"/>
1606
+ <a:satMod val="120000"/>
1607
+ </a:schemeClr>
1608
+ </a:gs>
1609
+ </a:gsLst>
1610
+ <a:lin ang="5400000" scaled="0"/>
1611
+ </a:gradFill>
1612
+ </a:bgFillStyleLst>
1613
+ </a:fmtScheme>
1614
+ </a:themeElements>
1615
+ </a:theme>
1616
+ `;
1617
+ const ɵ0$5 = generateThemeXML;
1618
+
1619
+ const settingsXML = `
1620
+ <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
1621
+
1622
+ <w:settings xmlns:w="${namespaces.w}" xmlns:o="${namespaces.o}" xmlns:r="${namespaces.r}" xmlns:v="${namespaces.v}" xmlns:w10="${namespaces.w10}" xmlns:sl="${namespaces.sl}">
1623
+ <w:zoom w:percent="100"/>
1624
+ <w:defaultTabStop w:val="720"/>
1625
+ <w:decimalSymbol w:val="."/>
1626
+ <w:listSeparator w:val=","/>
1627
+ </w:settings>
1628
+ `;
1629
+
1630
+ const webSettingsXML = `
1631
+ <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
1632
+
1633
+ <w:webSettings xmlns:w="${namespaces.w}" xmlns:r="${namespaces.r}">
1634
+ </w:webSettings>
1635
+ `;
1636
+
1637
+ const genericRelsXML = `
1638
+ <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
1639
+
1640
+ <Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
1641
+ <Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/aFChunk" Target="/word/afchunk.mht" Id="htmlChunk" />
1642
+ <Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/aFChunk" Target="/word/afchunkheader.mht" Id="htmlChunkHeader" />
1643
+ <Relationship Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/aFChunk" Target="/word/afchunkfooter.mht" Id="htmlChunkFooter" />
1644
+ </Relationships>
1645
+ `;
1646
+
1647
+ const generateDocumentTemplate = (width, height, orientation, margins) => `
1648
+ <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
1649
+ <w:document
1650
+ xmlns:a="${namespaces.a}"
1651
+ xmlns:cdr="${namespaces.cdr}"
1652
+ xmlns:o="${namespaces.o}"
1653
+ xmlns:pic="${namespaces.pic}"
1654
+ xmlns:r="${namespaces.r}"
1655
+ xmlns:v="${namespaces.v}"
1656
+ xmlns:ve="${namespaces.ve}"
1657
+ xmlns:vt="${namespaces.vt}"
1658
+ xmlns:w="${namespaces.w}"
1659
+ xmlns:w10="${namespaces.w10}"
1660
+ xmlns:wp="${namespaces.wp}"
1661
+ xmlns:wne="${namespaces.wne}"
1662
+ >
1663
+ <w:body>
1664
+
1665
+ <w:altChunk r:id="htmlChunk" />
1666
+ <w:sectPr>
1667
+ <w:pgSz w:w="${width}" w:h="${height}" w:orient="${orientation}" />
1668
+ <w:pgMar w:top="${margins.top}"
1669
+ w:right="${margins.right}"
1670
+ w:bottom="${margins.bottom}"
1671
+ w:left="${margins.left}"
1672
+ w:header="${margins.header}"
1673
+ w:footer="${margins.footer}"
1674
+ w:gutter="${margins.gutter}"/>
1675
+ </w:sectPr>
1676
+ </w:body>
1677
+ </w:document>
1678
+ `;
1679
+ const ɵ0$4 = generateDocumentTemplate;
1680
+ const generateDocumentTemplateHeader = `
1681
+ <w:hdr
1682
+ xmlns:a="${namespaces.a}"
1683
+ xmlns:cdr="${namespaces.cdr}"
1684
+ xmlns:o="${namespaces.o}"
1685
+ xmlns:pic="${namespaces.pic}"
1686
+ xmlns:r="${namespaces.r}"
1687
+ xmlns:v="${namespaces.v}"
1688
+ xmlns:ve="${namespaces.ve}"
1689
+ xmlns:vt="${namespaces.vt}"
1690
+ xmlns:w="${namespaces.w}"
1691
+ xmlns:w10="${namespaces.w10}"
1692
+ xmlns:wp="${namespaces.wp}"
1693
+ xmlns:wne="${namespaces.wne}"
1694
+ >
1695
+ <w:altChunk r:id="htmlChunkHeader" />
1696
+ </w:hdr>
1697
+ `;
1698
+ const generateDocumentTemplateFooter = `
1699
+ <w:ftr
1700
+ xmlns:a="${namespaces.a}"
1701
+ xmlns:cdr="${namespaces.cdr}"
1702
+ xmlns:o="${namespaces.o}"
1703
+ xmlns:pic="${namespaces.pic}"
1704
+ xmlns:r="${namespaces.r}"
1705
+ xmlns:v="${namespaces.v}"
1706
+ xmlns:ve="${namespaces.ve}"
1707
+ xmlns:vt="${namespaces.vt}"
1708
+ xmlns:w="${namespaces.w}"
1709
+ xmlns:w10="${namespaces.w10}"
1710
+ xmlns:wp="${namespaces.wp}"
1711
+ >
1712
+ <w:altChunk r:id="htmlChunkFooter" />
1713
+ <w:p w:rsidR="0014021C" w:rsidRDefault="0014021C" w:rsidP="0014021C">
1714
+ <w:pPr>
1715
+ <w:pStyle w:val="Footer"/>
1716
+ <w:jc w:val="center"/>
1717
+ </w:pPr>
1718
+ <w:fldSimple xmlns:ns2="http://schemas.openxmlformats.org/wordprocessingml/2006/main" ns2:instr="PAGE">
1719
+ <w:r/>
1720
+ </w:fldSimple>
1721
+ </w:p>
1722
+ </w:ftr>
1723
+ `;
1724
+ const generateDocumentTemplateFooterWithoutPaging = `
1725
+ <w:ftr
1726
+ xmlns:a="${namespaces.a}"
1727
+ xmlns:cdr="${namespaces.cdr}"
1728
+ xmlns:o="${namespaces.o}"
1729
+ xmlns:pic="${namespaces.pic}"
1730
+ xmlns:r="${namespaces.r}"
1731
+ xmlns:v="${namespaces.v}"
1732
+ xmlns:ve="${namespaces.ve}"
1733
+ xmlns:vt="${namespaces.vt}"
1734
+ xmlns:w="${namespaces.w}"
1735
+ xmlns:w10="${namespaces.w10}"
1736
+ xmlns:wp="${namespaces.wp}"
1737
+ >
1738
+ <w:altChunk r:id="htmlChunkFooter" />
1739
+ </w:ftr>
1740
+ `;
1741
+ { /* <w:altChunk r:id="htmlChunkFooter" /> */ }
1742
+ {
1743
+ /* <w:altChunk r:id="htmlChunkFooter" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" /> */
1744
+ }
1745
+ {
1746
+ /* <w:ftr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
1747
+ <fldSimple xmlns:ns2="http://schemas.openxmlformats.org/wordprocessingml/2006/main" ns2:instr="PAGE">
1748
+ </fldSimple>
1749
+ <w:altChunk r:id="htmlChunkFooter" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" />
1750
+ </w:ftr> */
1751
+ }
1752
+
1753
+ /* eslint-disable no-param-reassign */
1754
+ const rgbRegex = /rgb\((\d+),\s*([\d.]+),\s*([\d.]+)\)/i;
1755
+ const hslRegex = /hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/i;
1756
+ const hexRegex = /#([0-9A-F]{6})/i;
1757
+ const hex3Regex = /#([0-9A-F])([0-9A-F])([0-9A-F])/i;
1758
+ // eslint-disable-next-line import/prefer-default-export
1759
+ const rgbToHex = (red, green, blue) => {
1760
+ const hexColorCode = [red, green, blue]
1761
+ .map((x) => {
1762
+ // eslint-disable-next-line radix, no-param-reassign
1763
+ x = parseInt(x).toString(16);
1764
+ return x.length === 1 ? `0${x}` : x;
1765
+ })
1766
+ .join('');
1767
+ return hexColorCode;
1768
+ };
1769
+ const hslToHex = (hue, saturation, luminosity) => {
1770
+ hue /= 360;
1771
+ saturation /= 100;
1772
+ luminosity /= 100;
1773
+ // eslint-disable-next-line one-var
1774
+ let red, green, blue;
1775
+ if (saturation === 0) {
1776
+ // eslint-disable-next-line no-multi-assign
1777
+ red = green = blue = luminosity; // achromatic
1778
+ }
1779
+ else {
1780
+ const hue2rgb = (p, q, t) => {
1781
+ if (t < 0)
1782
+ t += 1;
1783
+ if (t > 1)
1784
+ t -= 1;
1785
+ if (t < 1 / 6)
1786
+ return p + (q - p) * 6 * t;
1787
+ if (t < 1 / 2)
1788
+ return q;
1789
+ if (t < 2 / 3)
1790
+ return p + (q - p) * (2 / 3 - t) * 6;
1791
+ return p;
1792
+ };
1793
+ const q = luminosity < 0.5
1794
+ ? luminosity * (1 + saturation)
1795
+ : luminosity + saturation - luminosity * saturation;
1796
+ const p = 2 * luminosity - q;
1797
+ red = hue2rgb(p, q, hue + 1 / 3);
1798
+ green = hue2rgb(p, q, hue);
1799
+ blue = hue2rgb(p, q, hue - 1 / 3);
1800
+ }
1801
+ return [red, green, blue]
1802
+ .map((x) => {
1803
+ const hex = Math.round(x * 255).toString(16);
1804
+ return hex.length === 1 ? `0${hex}` : hex;
1805
+ })
1806
+ .join('');
1807
+ };
1808
+ const hex3ToHex = (red, green, blue) => {
1809
+ const hexColorCode = [red, green, blue].map((x) => `${x}${x}`).join('');
1810
+ return hexColorCode;
1811
+ };
1812
+
1813
+ const pixelRegex = /([\d.]+)px/i;
1814
+ const percentageRegex = /([\d.]+)%/i;
1815
+ const pointRegex = /([\d.]+)pt/i;
1816
+ const cmRegex = /([\d.]+)cm/i;
1817
+ const inchRegex = /([\d.]+)in/i;
1818
+ const pixelToEMU = (pixelValue) => Math.round(pixelValue * 9525);
1819
+ const EMUToPixel = (EMUValue) => Math.round(EMUValue / 9525);
1820
+ const TWIPToEMU = (TWIPValue) => Math.round(TWIPValue * 635);
1821
+ const EMUToTWIP = (EMUValue) => Math.round(EMUValue / 635);
1822
+ const pointToTWIP = (pointValue) => Math.round(pointValue * 20);
1823
+ const TWIPToPoint = (TWIPValue) => Math.round(TWIPValue / 20);
1824
+ const pointToHIP = (pointValue) => Math.round(pointValue * 2);
1825
+ const HIPToPoint = (HIPValue) => Math.round(HIPValue / 2);
1826
+ const HIPToTWIP = (HIPValue) => Math.round(HIPValue * 10);
1827
+ const TWIPToHIP = (TWIPValue) => Math.round(TWIPValue / 10);
1828
+ const pixelToTWIP = (pixelValue) => EMUToTWIP(pixelToEMU(pixelValue));
1829
+ const TWIPToPixel = (TWIPValue) => EMUToPixel(TWIPToEMU(TWIPValue));
1830
+ const pixelToHIP = (pixelValue) => TWIPToHIP(EMUToTWIP(pixelToEMU(pixelValue)));
1831
+ const HIPToPixel = (HIPValue) => EMUToPixel(TWIPToEMU(HIPToTWIP(HIPValue)));
1832
+ const inchToPoint = (inchValue) => Math.round(inchValue * 72);
1833
+ const inchToTWIP = (inchValue) => pointToTWIP(inchToPoint(inchValue));
1834
+ const cmToInch = (cmValue) => cmValue * 0.3937008;
1835
+ const cmToTWIP = (cmValue) => inchToTWIP(cmToInch(cmValue));
1836
+ const pixelToPoint = (pixelValue) => HIPToPoint(pixelToHIP(pixelValue));
1837
+ const pointToPixel = (pointValue) => HIPToPixel(pointToHIP(pointValue));
1838
+ const EIPToPoint = (EIPValue) => Math.round(EIPValue / 8);
1839
+ const pointToEIP = (PointValue) => Math.round(PointValue * 8);
1840
+ const pixelToEIP = (pixelValue) => pointToEIP(pixelToPoint(pixelValue));
1841
+ const EIPToPixel = (EIPValue) => pointToPixel(EIPToPoint(EIPValue));
1842
+
1843
+ // eslint-disable-next-line import/prefer-default-export
1844
+ const vNodeHasChildren = (vNode) => vNode && vNode.children && Array.isArray(vNode.children) && vNode.children.length;
1845
+
1846
+ const isValidUrl = (urlString) => {
1847
+ const urlRegex = /http(s)?:\/\/(\w+:?\w*@)?(\S+)(:\d+)?((?<=\.)\w+)+(\/([\w#!:.?+=&%@!\-/])*)?/gi;
1848
+ return Boolean(urlRegex.test(urlString));
1849
+ };
1850
+ const ɵ0$3 = isValidUrl;
1851
+
1852
+ // eslint-disable-next-line consistent-return
1853
+ const fixupColorCode = (colorCodeString) => {
1854
+ if (Object.prototype.hasOwnProperty.call(colorNames, colorCodeString.toLowerCase())) {
1855
+ const [red, green, blue] = colorNames[colorCodeString.toLowerCase()];
1856
+ return rgbToHex(red, green, blue);
1857
+ }
1858
+ else if (rgbRegex.test(colorCodeString)) {
1859
+ const matchedParts = colorCodeString.match(rgbRegex);
1860
+ const red = matchedParts[1];
1861
+ const green = matchedParts[2];
1862
+ const blue = matchedParts[3];
1863
+ return rgbToHex(red, green, blue);
1864
+ }
1865
+ else if (hslRegex.test(colorCodeString)) {
1866
+ const matchedParts = colorCodeString.match(hslRegex);
1867
+ const hue = matchedParts[1];
1868
+ const saturation = matchedParts[2];
1869
+ const luminosity = matchedParts[3];
1870
+ return hslToHex(hue, saturation, luminosity);
1871
+ }
1872
+ else if (hexRegex.test(colorCodeString)) {
1873
+ const matchedParts = colorCodeString.match(hexRegex);
1874
+ return matchedParts[1];
1875
+ }
1876
+ else if (hex3Regex.test(colorCodeString)) {
1877
+ const matchedParts = colorCodeString.match(hex3Regex);
1878
+ const red = matchedParts[1];
1879
+ const green = matchedParts[2];
1880
+ const blue = matchedParts[3];
1881
+ return hex3ToHex(red, green, blue);
1882
+ }
1883
+ else {
1884
+ return '000000';
1885
+ }
1886
+ };
1887
+ const ɵ0$2 = fixupColorCode;
1888
+ const buildRunFontFragment = (fontName = defaultFont) => fragment({ namespaceAlias: { w: namespaces.w } })
1889
+ .ele('@w', 'rFonts')
1890
+ .att('@w', 'ascii', fontName)
1891
+ .att('@w', 'hAnsi', fontName)
1892
+ .up();
1893
+ const ɵ1$1 = buildRunFontFragment;
1894
+ const buildRunStyleFragment = (type = 'Hyperlink') => fragment({ namespaceAlias: { w: namespaces.w } })
1895
+ .ele('@w', 'rStyle')
1896
+ .att('@w', 'val', type)
1897
+ .up();
1898
+ const ɵ2$1 = buildRunStyleFragment;
1899
+ const buildTableRowHeight = (tableRowHeight) => fragment({ namespaceAlias: { w: namespaces.w } })
1900
+ .ele('@w', 'trHeight')
1901
+ .att('@w', 'val', tableRowHeight)
1902
+ .att('@w', 'hRule', 'atLeast')
1903
+ .up();
1904
+ const ɵ3$1 = buildTableRowHeight;
1905
+ const buildVerticalAlignment = (verticalAlignment) => {
1906
+ if (verticalAlignment.toLowerCase() === 'middle') {
1907
+ verticalAlignment = 'center';
1908
+ }
1909
+ return fragment({ namespaceAlias: { w: namespaces.w } })
1910
+ .ele('@w', 'vAlign')
1911
+ .att('@w', 'val', verticalAlignment)
1912
+ .up();
1913
+ };
1914
+ const ɵ4 = buildVerticalAlignment;
1915
+ const buildVerticalMerge = (verticalMerge = 'continue') => fragment({ namespaceAlias: { w: namespaces.w } })
1916
+ .ele('@w', 'vMerge')
1917
+ .att('@w', 'val', verticalMerge)
1918
+ .up();
1919
+ const ɵ5 = buildVerticalMerge;
1920
+ const buildColor = (colorCode) => fragment({ namespaceAlias: { w: namespaces.w } })
1921
+ .ele('@w', 'color')
1922
+ .att('@w', 'val', colorCode)
1923
+ .up();
1924
+ const ɵ6 = buildColor;
1925
+ const buildFontSize = (fontSize) => fragment({ namespaceAlias: { w: namespaces.w } })
1926
+ .ele('@w', 'sz')
1927
+ .att('@w', 'val', fontSize)
1928
+ .up();
1929
+ const ɵ7 = buildFontSize;
1930
+ const buildShading = (colorCode) => fragment({ namespaceAlias: { w: namespaces.w } })
1931
+ .ele('@w', 'shd')
1932
+ .att('@w', 'val', 'clear')
1933
+ .att('@w', 'fill', colorCode)
1934
+ .up();
1935
+ const ɵ8 = buildShading;
1936
+ const buildHighlight = (color = 'yellow') => fragment({ namespaceAlias: { w: namespaces.w } })
1937
+ .ele('@w', 'highlight')
1938
+ .att('@w', 'val', color)
1939
+ .up();
1940
+ const ɵ9 = buildHighlight;
1941
+ const buildVertAlign = (type = 'baseline') => fragment({ namespaceAlias: { w: namespaces.w } })
1942
+ .ele('@w', 'vertAlign')
1943
+ .att('@w', 'val', type)
1944
+ .up();
1945
+ const ɵ10 = buildVertAlign;
1946
+ const buildStrike = () => fragment({ namespaceAlias: { w: namespaces.w } })
1947
+ .ele('@w', 'strike')
1948
+ .att('@w', 'val', true)
1949
+ .up();
1950
+ const ɵ11 = buildStrike;
1951
+ const buildBold = () => fragment({ namespaceAlias: { w: namespaces.w } })
1952
+ .ele('@w', 'b')
1953
+ .up();
1954
+ const ɵ12 = buildBold;
1955
+ const buildItalics = () => fragment({ namespaceAlias: { w: namespaces.w } })
1956
+ .ele('@w', 'i')
1957
+ .up();
1958
+ const ɵ13 = buildItalics;
1959
+ const buildUnderline = (type = 'single') => fragment({ namespaceAlias: { w: namespaces.w } })
1960
+ .ele('@w', 'u')
1961
+ .att('@w', 'val', type)
1962
+ .up();
1963
+ const ɵ14 = buildUnderline;
1964
+ const buildLineBreak = (type = 'textWrapping') => fragment({ namespaceAlias: { w: namespaces.w } })
1965
+ .ele('@w', 'br')
1966
+ .att('@w', 'type', type)
1967
+ .up();
1968
+ const ɵ15 = buildLineBreak;
1969
+ const buildBorder = (borderSide = 'top', borderSize = 0, borderSpacing = 0, borderColor = fixupColorCode('black'), borderStroke = 'single') => fragment({ namespaceAlias: { w: namespaces.w } })
1970
+ .ele('@w', borderSide)
1971
+ .att('@w', 'val', borderStroke)
1972
+ .att('@w', 'sz', borderSize)
1973
+ .att('@w', 'space', borderSpacing)
1974
+ .att('@w', 'color', borderColor)
1975
+ .up();
1976
+ const ɵ16 = buildBorder;
1977
+ const buildTextElement = (text) => fragment({ namespaceAlias: { w: namespaces.w } })
1978
+ .ele('@w', 't')
1979
+ .att('@xml', 'space', 'preserve')
1980
+ .txt(text)
1981
+ .up();
1982
+ const ɵ17 = buildTextElement;
1983
+ // eslint-disable-next-line consistent-return
1984
+ const fixupLineHeight = (lineHeight, fontSize) => {
1985
+ // FIXME: If line height is anything other than a number
1986
+ // eslint-disable-next-line no-restricted-globals
1987
+ if (!isNaN(lineHeight)) {
1988
+ if (fontSize) {
1989
+ const actualLineHeight = +lineHeight * fontSize;
1990
+ return HIPToTWIP(actualLineHeight);
1991
+ }
1992
+ else {
1993
+ // 240 TWIP or 12 point is default line height
1994
+ return +lineHeight * 240;
1995
+ }
1996
+ }
1997
+ else {
1998
+ // 240 TWIP or 12 point is default line height
1999
+ return 240;
2000
+ }
2001
+ };
2002
+ const ɵ18 = fixupLineHeight;
2003
+ // eslint-disable-next-line consistent-return
2004
+ const fixupFontSize$1 = (fontSizeString) => {
2005
+ if (pointRegex.test(fontSizeString)) {
2006
+ const matchedParts = fontSizeString.match(pointRegex);
2007
+ // convert point to half point
2008
+ return pointToHIP(matchedParts[1]);
2009
+ }
2010
+ else if (pixelRegex.test(fontSizeString)) {
2011
+ const matchedParts = fontSizeString.match(pixelRegex);
2012
+ // convert pixels to half point
2013
+ return pixelToHIP(matchedParts[1]);
2014
+ }
2015
+ };
2016
+ const ɵ19 = fixupFontSize$1;
2017
+ // eslint-disable-next-line consistent-return
2018
+ const fixupRowHeight = (rowHeightString) => {
2019
+ if (pointRegex.test(rowHeightString)) {
2020
+ const matchedParts = rowHeightString.match(pointRegex);
2021
+ // convert point to half point
2022
+ return pointToTWIP(matchedParts[1]);
2023
+ }
2024
+ else if (pixelRegex.test(rowHeightString)) {
2025
+ const matchedParts = rowHeightString.match(pixelRegex);
2026
+ // convert pixels to half point
2027
+ return pixelToTWIP(matchedParts[1]);
2028
+ }
2029
+ else if (cmRegex.test(rowHeightString)) {
2030
+ const matchedParts = rowHeightString.match(cmRegex);
2031
+ return cmToTWIP(matchedParts[1]);
2032
+ }
2033
+ else if (inchRegex.test(rowHeightString)) {
2034
+ const matchedParts = rowHeightString.match(inchRegex);
2035
+ return inchToTWIP(matchedParts[1]);
2036
+ }
2037
+ };
2038
+ const ɵ20 = fixupRowHeight;
2039
+ // eslint-disable-next-line consistent-return
2040
+ const fixupColumnWidth = (columnWidthString) => {
2041
+ if (pointRegex.test(columnWidthString)) {
2042
+ const matchedParts = columnWidthString.match(pointRegex);
2043
+ return pointToTWIP(matchedParts[1]);
2044
+ }
2045
+ else if (pixelRegex.test(columnWidthString)) {
2046
+ const matchedParts = columnWidthString.match(pixelRegex);
2047
+ return pixelToTWIP(matchedParts[1]);
2048
+ }
2049
+ else if (cmRegex.test(columnWidthString)) {
2050
+ const matchedParts = columnWidthString.match(cmRegex);
2051
+ return cmToTWIP(matchedParts[1]);
2052
+ }
2053
+ else if (inchRegex.test(columnWidthString)) {
2054
+ const matchedParts = columnWidthString.match(inchRegex);
2055
+ return inchToTWIP(matchedParts[1]);
2056
+ }
2057
+ };
2058
+ const ɵ21 = fixupColumnWidth;
2059
+ // eslint-disable-next-line consistent-return
2060
+ const fixupMargin = (marginString) => {
2061
+ if (pointRegex.test(marginString)) {
2062
+ const matchedParts = marginString.match(pointRegex);
2063
+ // convert point to half point
2064
+ return pointToTWIP(matchedParts[1]);
2065
+ }
2066
+ else if (pixelRegex.test(marginString)) {
2067
+ const matchedParts = marginString.match(pixelRegex);
2068
+ // convert pixels to half point
2069
+ return pixelToTWIP(matchedParts[1]);
2070
+ }
2071
+ };
2072
+ const ɵ22 = fixupMargin;
2073
+ const modifiedStyleAttributesBuilder = (vNode, attributes, options) => {
2074
+ const modifiedAttributes = Object.assign({}, attributes);
2075
+ // styles
2076
+ if (isVNode(vNode) && vNode.properties && vNode.properties.style) {
2077
+ if (vNode.properties.style.color && !colorlessColors.includes(vNode.properties.style.color)) {
2078
+ modifiedAttributes.color = fixupColorCode(vNode.properties.style.color);
2079
+ }
2080
+ if (vNode.properties.style['background-color'] &&
2081
+ !colorlessColors.includes(vNode.properties.style['background-color'])) {
2082
+ modifiedAttributes.backgroundColor = fixupColorCode(vNode.properties.style['background-color']);
2083
+ }
2084
+ if (vNode.properties.style['vertical-align'] &&
2085
+ verticalAlignValues.includes(vNode.properties.style['vertical-align'])) {
2086
+ modifiedAttributes.verticalAlign = vNode.properties.style['vertical-align'];
2087
+ }
2088
+ if (vNode.properties.style['text-align'] &&
2089
+ ['left', 'right', 'center', 'justify'].includes(vNode.properties.style['text-align'])) {
2090
+ modifiedAttributes.textAlign = vNode.properties.style['text-align'];
2091
+ }
2092
+ // FIXME: remove bold check when other font weights are handled.
2093
+ if (vNode.properties.style['font-weight'] && vNode.properties.style['font-weight'] === 'bold') {
2094
+ modifiedAttributes.strong = vNode.properties.style['font-weight'];
2095
+ }
2096
+ if (vNode.properties.style['font-size']) {
2097
+ modifiedAttributes.fontSize = fixupFontSize$1(vNode.properties.style['font-size']);
2098
+ }
2099
+ if (vNode.properties.style['line-height']) {
2100
+ modifiedAttributes.lineHeight = fixupLineHeight(vNode.properties.style['line-height'], vNode.properties.style['font-size']
2101
+ ? fixupFontSize$1(vNode.properties.style['font-size'])
2102
+ : null);
2103
+ }
2104
+ if (vNode.properties.style['margin-left'] || vNode.properties.style['margin-right']) {
2105
+ const leftMargin = fixupMargin(vNode.properties.style['margin-left']);
2106
+ const rightMargin = fixupMargin(vNode.properties.style['margin-right']);
2107
+ const indentation = {};
2108
+ if (leftMargin) {
2109
+ indentation.left = leftMargin;
2110
+ }
2111
+ if (rightMargin) {
2112
+ indentation.right = rightMargin;
2113
+ }
2114
+ if (leftMargin || rightMargin) {
2115
+ modifiedAttributes.indentation = indentation;
2116
+ }
2117
+ }
2118
+ if (vNode.properties.style.display) {
2119
+ modifiedAttributes.display = vNode.properties.style.display;
2120
+ }
2121
+ if (vNode.properties.style.width) {
2122
+ modifiedAttributes.width = vNode.properties.style.width;
2123
+ }
2124
+ }
2125
+ // paragraph only
2126
+ if (options && options.isParagraph) {
2127
+ if (isVNode(vNode) && vNode.tagName === 'blockquote') {
2128
+ modifiedAttributes.indentation = { left: 284 };
2129
+ modifiedAttributes.textAlign = 'justify';
2130
+ }
2131
+ else if (isVNode(vNode) && vNode.tagName === 'code') {
2132
+ modifiedAttributes.highlightColor = 'lightGray';
2133
+ }
2134
+ else if (isVNode(vNode) && vNode.tagName === 'pre') {
2135
+ modifiedAttributes.font = 'Courier';
2136
+ }
2137
+ }
2138
+ return modifiedAttributes;
2139
+ };
2140
+ const ɵ23 = modifiedStyleAttributesBuilder;
2141
+ // html tag to formatting function
2142
+ // options are passed to the formatting function if needed
2143
+ const buildFormatting = (htmlTag, options) => {
2144
+ switch (htmlTag) {
2145
+ case 'strong':
2146
+ case 'b':
2147
+ return buildBold();
2148
+ case 'em':
2149
+ case 'i':
2150
+ return buildItalics();
2151
+ case 'ins':
2152
+ case 'u':
2153
+ return buildUnderline();
2154
+ case 'strike':
2155
+ case 'del':
2156
+ case 's':
2157
+ return buildStrike();
2158
+ case 'sub':
2159
+ return buildVertAlign('subscript');
2160
+ case 'sup':
2161
+ return buildVertAlign('superscript');
2162
+ case 'mark':
2163
+ return buildHighlight();
2164
+ case 'code':
2165
+ return buildHighlight('lightGray');
2166
+ case 'highlightColor':
2167
+ return buildHighlight(options && options.color ? options.color : 'lightGray');
2168
+ case 'font':
2169
+ case 'pre':
2170
+ return buildRunFontFragment('Courier');
2171
+ case 'color':
2172
+ return buildColor(options && options.color ? options.color : 'black');
2173
+ case 'backgroundColor':
2174
+ return buildShading(options && options.color ? options.color : 'black');
2175
+ case 'fontSize':
2176
+ // does this need a unit of measure?
2177
+ return buildFontSize(options && options.fontSize ? options.fontSize : 10);
2178
+ case 'hyperlink':
2179
+ return buildRunStyleFragment('Hyperlink');
2180
+ }
2181
+ return null;
2182
+ };
2183
+ const ɵ24 = buildFormatting;
2184
+ const buildRunProperties = (attributes) => {
2185
+ const runPropertiesFragment = fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'rPr');
2186
+ if (attributes && attributes.constructor === Object) {
2187
+ Object.keys(attributes).forEach((key) => {
2188
+ const options = {};
2189
+ if (key === 'color' || key === 'backgroundColor' || key === 'highlightColor') {
2190
+ options.color = attributes[key];
2191
+ }
2192
+ if (key === 'fontSize') {
2193
+ options.fontSize = attributes[key];
2194
+ }
2195
+ const formattingFragment = buildFormatting(key, options);
2196
+ if (formattingFragment) {
2197
+ runPropertiesFragment.import(formattingFragment);
2198
+ }
2199
+ });
2200
+ }
2201
+ runPropertiesFragment.up();
2202
+ return runPropertiesFragment;
2203
+ };
2204
+ const ɵ25 = buildRunProperties;
2205
+ const buildRun = (vNode, attributes, docxDocumentInstance) => __awaiter(void 0, void 0, void 0, function* () {
2206
+ const runFragment = fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'r');
2207
+ const runPropertiesFragment = buildRunProperties(cloneDeep(attributes));
2208
+ // case where we have recursive spans representing font changes
2209
+ if (isVNode(vNode) && vNode.tagName === 'span') {
2210
+ // eslint-disable-next-line no-use-before-define
2211
+ return buildRunOrRuns(vNode, attributes, docxDocumentInstance);
2212
+ }
2213
+ if (isVNode(vNode) &&
2214
+ [
2215
+ 'strong',
2216
+ 'b',
2217
+ 'em',
2218
+ 'i',
2219
+ 'u',
2220
+ 'ins',
2221
+ 'strike',
2222
+ 'del',
2223
+ 's',
2224
+ 'sub',
2225
+ 'sup',
2226
+ 'mark',
2227
+ 'blockquote',
2228
+ 'code',
2229
+ 'pre',
2230
+ ].includes(vNode.tagName)) {
2231
+ const runFragmentsArray = [];
2232
+ let vNodes = [vNode];
2233
+ // create temp run fragments to split the paragraph into different runs
2234
+ let tempAttributes = cloneDeep(attributes);
2235
+ let tempRunFragment = fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'r');
2236
+ while (vNodes.length) {
2237
+ const tempVNode = vNodes.shift();
2238
+ if (isVText(tempVNode)) {
2239
+ const textFragment = buildTextElement(tempVNode.text);
2240
+ const tempRunPropertiesFragment = buildRunProperties(Object.assign(Object.assign({}, attributes), tempAttributes));
2241
+ tempRunFragment.import(tempRunPropertiesFragment);
2242
+ tempRunFragment.import(textFragment);
2243
+ runFragmentsArray.push(tempRunFragment);
2244
+ // re initialize temp run fragments with new fragment
2245
+ tempAttributes = cloneDeep(attributes);
2246
+ tempRunFragment = fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'r');
2247
+ }
2248
+ else if (isVNode(tempVNode)) {
2249
+ if ([
2250
+ 'strong',
2251
+ 'b',
2252
+ 'em',
2253
+ 'i',
2254
+ 'u',
2255
+ 'ins',
2256
+ 'strike',
2257
+ 'del',
2258
+ 's',
2259
+ 'sub',
2260
+ 'sup',
2261
+ 'mark',
2262
+ 'code',
2263
+ 'pre',
2264
+ ].includes(tempVNode.tagName)) {
2265
+ tempAttributes = {};
2266
+ switch (tempVNode.tagName) {
2267
+ case 'strong':
2268
+ case 'b':
2269
+ tempAttributes.strong = true;
2270
+ break;
2271
+ case 'i':
2272
+ tempAttributes.i = true;
2273
+ break;
2274
+ case 'u':
2275
+ tempAttributes.u = true;
2276
+ break;
2277
+ case 'sub':
2278
+ tempAttributes.sub = true;
2279
+ break;
2280
+ case 'sup':
2281
+ tempAttributes.sup = true;
2282
+ break;
2283
+ }
2284
+ const formattingFragment = buildFormatting(tempVNode);
2285
+ if (formattingFragment) {
2286
+ runPropertiesFragment.import(formattingFragment);
2287
+ }
2288
+ // go a layer deeper if there is a span somewhere in the children
2289
+ }
2290
+ else if (tempVNode.tagName === 'span') {
2291
+ // eslint-disable-next-line no-use-before-define
2292
+ const spanFragment = yield buildRunOrRuns(tempVNode, Object.assign(Object.assign({}, attributes), tempAttributes), docxDocumentInstance);
2293
+ // if spanFragment is an array, we need to add each fragment to the runFragmentsArray. If the fragment is an array, perform a depth first search on the array to add each fragment to the runFragmentsArray
2294
+ if (Array.isArray(spanFragment)) {
2295
+ spanFragment.flat(Infinity);
2296
+ runFragmentsArray.push(...spanFragment);
2297
+ }
2298
+ else {
2299
+ runFragmentsArray.push(spanFragment);
2300
+ }
2301
+ // do not slice and concat children since this is already accounted for in the buildRunOrRuns function
2302
+ // eslint-disable-next-line no-continue
2303
+ continue;
2304
+ }
2305
+ }
2306
+ if (tempVNode.children && tempVNode.children.length) {
2307
+ if (tempVNode.children.length > 1) {
2308
+ attributes = Object.assign(Object.assign({}, attributes), tempAttributes);
2309
+ }
2310
+ vNodes = tempVNode.children.slice().concat(vNodes);
2311
+ }
2312
+ }
2313
+ if (runFragmentsArray.length) {
2314
+ return runFragmentsArray;
2315
+ }
2316
+ }
2317
+ runFragment.import(runPropertiesFragment);
2318
+ if (isVText(vNode)) {
2319
+ const textFragment = buildTextElement(vNode.text);
2320
+ runFragment.import(textFragment);
2321
+ }
2322
+ else if (attributes && attributes.type === 'picture') {
2323
+ let response = null;
2324
+ const base64Uri = decodeURIComponent(vNode.properties.src);
2325
+ if (base64Uri) {
2326
+ response = docxDocumentInstance.createMediaFile(base64Uri);
2327
+ }
2328
+ if (response) {
2329
+ docxDocumentInstance.zip
2330
+ .folder('word')
2331
+ .folder('media')
2332
+ .file(response.fileNameWithExtension, Buffer.from(response.fileContent, 'base64'), {
2333
+ createFolders: false,
2334
+ });
2335
+ const documentRelsId = docxDocumentInstance.createDocumentRelationships(docxDocumentInstance.relationshipFilename, imageType, `media/${response.fileNameWithExtension}`, internalRelationship);
2336
+ attributes.inlineOrAnchored = true;
2337
+ attributes.relationshipId = documentRelsId;
2338
+ attributes.id = response.id;
2339
+ attributes.fileContent = response.fileContent;
2340
+ attributes.fileNameWithExtension = response.fileNameWithExtension;
2341
+ }
2342
+ const { type, inlineOrAnchored } = attributes, otherAttributes = __rest(attributes, ["type", "inlineOrAnchored"]);
2343
+ // eslint-disable-next-line no-use-before-define
2344
+ const imageFragment = buildDrawing(inlineOrAnchored, type, otherAttributes);
2345
+ runFragment.import(imageFragment);
2346
+ }
2347
+ else if (isVNode(vNode) && vNode.tagName === 'br') {
2348
+ const lineBreakFragment = buildLineBreak();
2349
+ runFragment.import(lineBreakFragment);
2350
+ }
2351
+ runFragment.up();
2352
+ return runFragment;
2353
+ });
2354
+ const ɵ26 = buildRun;
2355
+ const buildRunOrRuns = (vNode, attributes, docxDocumentInstance) => __awaiter(void 0, void 0, void 0, function* () {
2356
+ if (isVNode(vNode) && vNode.tagName === 'span') {
2357
+ let runFragments = [];
2358
+ for (let index = 0; index < vNode.children.length; index++) {
2359
+ const childVNode = vNode.children[index];
2360
+ const modifiedAttributes = modifiedStyleAttributesBuilder(vNode, attributes);
2361
+ const tempRunFragments = yield buildRun(childVNode, modifiedAttributes, docxDocumentInstance);
2362
+ runFragments = runFragments.concat(Array.isArray(tempRunFragments) ? tempRunFragments : [tempRunFragments]);
2363
+ }
2364
+ return runFragments;
2365
+ }
2366
+ else {
2367
+ const tempRunFragments = yield buildRun(vNode, attributes, docxDocumentInstance);
2368
+ return tempRunFragments;
2369
+ }
2370
+ });
2371
+ const ɵ27 = buildRunOrRuns;
2372
+ const buildRunOrHyperLink = (vNode, attributes, docxDocumentInstance) => __awaiter(void 0, void 0, void 0, function* () {
2373
+ if (isVNode(vNode) && vNode.tagName === 'a') {
2374
+ const relationshipId = docxDocumentInstance.createDocumentRelationships(docxDocumentInstance.relationshipFilename, hyperlinkType, vNode.properties && vNode.properties.href ? vNode.properties.href : '');
2375
+ const hyperlinkFragment = fragment({ namespaceAlias: { w: namespaces.w, r: namespaces.r } })
2376
+ .ele('@w', 'hyperlink')
2377
+ .att('@r', 'id', `rId${relationshipId}`);
2378
+ const modifiedAttributes = Object.assign({}, attributes);
2379
+ modifiedAttributes.hyperlink = true;
2380
+ const runFragments = yield buildRunOrRuns(vNode.children[0], modifiedAttributes, docxDocumentInstance);
2381
+ if (Array.isArray(runFragments)) {
2382
+ for (let index = 0; index < runFragments.length; index++) {
2383
+ const runFragment = runFragments[index];
2384
+ hyperlinkFragment.import(runFragment);
2385
+ }
2386
+ }
2387
+ else {
2388
+ hyperlinkFragment.import(runFragments);
2389
+ }
2390
+ hyperlinkFragment.up();
2391
+ return hyperlinkFragment;
2392
+ }
2393
+ const runFragments = yield buildRunOrRuns(vNode, attributes, docxDocumentInstance);
2394
+ return runFragments;
2395
+ });
2396
+ const ɵ28 = buildRunOrHyperLink;
2397
+ const buildNumberingProperties = (levelId, numberingId) => fragment({ namespaceAlias: { w: namespaces.w } })
2398
+ .ele('@w', 'numPr')
2399
+ .ele('@w', 'ilvl')
2400
+ .att('@w', 'val', String(levelId))
2401
+ .up()
2402
+ .ele('@w', 'numId')
2403
+ .att('@w', 'val', String(numberingId))
2404
+ .up()
2405
+ .up();
2406
+ const ɵ29 = buildNumberingProperties;
2407
+ const buildNumberingInstances = () => fragment({ namespaceAlias: { w: namespaces.w } })
2408
+ .ele('@w', 'num')
2409
+ .ele('@w', 'abstractNumId')
2410
+ .up()
2411
+ .up();
2412
+ const ɵ30 = buildNumberingInstances;
2413
+ const buildSpacing = (lineSpacing, beforeSpacing, afterSpacing) => {
2414
+ const spacingFragment = fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'spacing');
2415
+ if (lineSpacing) {
2416
+ spacingFragment.att('@w', 'line', lineSpacing);
2417
+ }
2418
+ if (beforeSpacing) {
2419
+ spacingFragment.att('@w', 'before', beforeSpacing);
2420
+ }
2421
+ if (afterSpacing) {
2422
+ spacingFragment.att('@w', 'after', afterSpacing);
2423
+ }
2424
+ spacingFragment.att('@w', 'lineRule', 'auto').up();
2425
+ return spacingFragment;
2426
+ };
2427
+ const ɵ31 = buildSpacing;
2428
+ const buildIndentation = ({ left, right }) => {
2429
+ const indentationFragment = fragment({
2430
+ namespaceAlias: { w: namespaces.w },
2431
+ }).ele('@w', 'ind');
2432
+ if (left) {
2433
+ indentationFragment.att('@w', 'left', left);
2434
+ }
2435
+ if (right) {
2436
+ indentationFragment.att('@w', 'right', right);
2437
+ }
2438
+ indentationFragment.up();
2439
+ return indentationFragment;
2440
+ };
2441
+ const ɵ32 = buildIndentation;
2442
+ const buildPStyle = (style = 'Normal') => fragment({ namespaceAlias: { w: namespaces.w } })
2443
+ .ele('@w', 'pStyle')
2444
+ .att('@w', 'val', style)
2445
+ .up();
2446
+ const ɵ33 = buildPStyle;
2447
+ const buildHorizontalAlignment = (horizontalAlignment) => {
2448
+ if (horizontalAlignment === 'justify') {
2449
+ horizontalAlignment = 'both';
2450
+ }
2451
+ return fragment({ namespaceAlias: { w: namespaces.w } })
2452
+ .ele('@w', 'jc')
2453
+ .att('@w', 'val', horizontalAlignment)
2454
+ .up();
2455
+ };
2456
+ const ɵ34 = buildHorizontalAlignment;
2457
+ const buildParagraphBorder = () => {
2458
+ const paragraphBorderFragment = fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'pBdr');
2459
+ const bordersObject = cloneDeep(paragraphBordersObject);
2460
+ Object.keys(bordersObject).forEach((borderName) => {
2461
+ if (bordersObject[borderName]) {
2462
+ const { size, spacing, color } = bordersObject[borderName];
2463
+ const borderFragment = buildBorder(borderName, size, spacing, color);
2464
+ paragraphBorderFragment.import(borderFragment);
2465
+ }
2466
+ });
2467
+ paragraphBorderFragment.up();
2468
+ return paragraphBorderFragment;
2469
+ };
2470
+ const ɵ35 = buildParagraphBorder;
2471
+ const buildParagraphProperties = (attributes) => {
2472
+ const paragraphPropertiesFragment = fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'pPr');
2473
+ if (attributes && attributes.constructor === Object) {
2474
+ Object.keys(attributes).forEach((key) => {
2475
+ switch (key) {
2476
+ case 'numbering':
2477
+ const { levelId, numberingId } = attributes[key];
2478
+ const numberingPropertiesFragment = buildNumberingProperties(levelId, numberingId);
2479
+ paragraphPropertiesFragment.import(numberingPropertiesFragment);
2480
+ // eslint-disable-next-line no-param-reassign
2481
+ delete attributes.numbering;
2482
+ break;
2483
+ case 'textAlign':
2484
+ const horizontalAlignmentFragment = buildHorizontalAlignment(attributes[key]);
2485
+ paragraphPropertiesFragment.import(horizontalAlignmentFragment);
2486
+ // eslint-disable-next-line no-param-reassign
2487
+ delete attributes.textAlign;
2488
+ break;
2489
+ case 'backgroundColor':
2490
+ // Add shading to Paragraph Properties only if display is block
2491
+ // Essentially if background color needs to be across the row
2492
+ if (attributes.display === 'block') {
2493
+ const shadingFragment = buildShading(attributes[key]);
2494
+ paragraphPropertiesFragment.import(shadingFragment);
2495
+ // FIXME: Inner padding in case of shaded paragraphs.
2496
+ const paragraphBorderFragment = buildParagraphBorder();
2497
+ paragraphPropertiesFragment.import(paragraphBorderFragment);
2498
+ // eslint-disable-next-line no-param-reassign
2499
+ delete attributes.backgroundColor;
2500
+ }
2501
+ break;
2502
+ case 'paragraphStyle':
2503
+ const pStyleFragment = buildPStyle(attributes.paragraphStyle);
2504
+ paragraphPropertiesFragment.import(pStyleFragment);
2505
+ delete attributes.paragraphStyle;
2506
+ break;
2507
+ case 'indentation':
2508
+ const indentationFragment = buildIndentation(attributes[key]);
2509
+ paragraphPropertiesFragment.import(indentationFragment);
2510
+ // eslint-disable-next-line no-param-reassign
2511
+ delete attributes.indentation;
2512
+ break;
2513
+ }
2514
+ });
2515
+ const spacingFragment = buildSpacing(attributes.lineHeight, attributes.beforeSpacing, attributes.afterSpacing);
2516
+ // eslint-disable-next-line no-param-reassign
2517
+ delete attributes.lineHeight;
2518
+ // eslint-disable-next-line no-param-reassign
2519
+ delete attributes.beforeSpacing;
2520
+ // eslint-disable-next-line no-param-reassign
2521
+ delete attributes.afterSpacing;
2522
+ paragraphPropertiesFragment.import(spacingFragment);
2523
+ }
2524
+ paragraphPropertiesFragment.up();
2525
+ return paragraphPropertiesFragment;
2526
+ };
2527
+ const ɵ36 = buildParagraphProperties;
2528
+ const computeImageDimensions = (vNode, attributes) => {
2529
+ const { maximumWidth, originalWidth, originalHeight } = attributes;
2530
+ const aspectRatio = originalWidth / originalHeight;
2531
+ const maximumWidthInEMU = TWIPToEMU(maximumWidth);
2532
+ let originalWidthInEMU = pixelToEMU(originalWidth);
2533
+ let originalHeightInEMU = pixelToEMU(originalHeight);
2534
+ if (originalWidthInEMU > maximumWidthInEMU) {
2535
+ originalWidthInEMU = maximumWidthInEMU;
2536
+ originalHeightInEMU = Math.round(originalWidthInEMU / aspectRatio);
2537
+ }
2538
+ let modifiedHeight;
2539
+ let modifiedWidth;
2540
+ if (vNode.properties && vNode.properties.style) {
2541
+ if (vNode.properties.style.width) {
2542
+ if (vNode.properties.style.width !== 'auto') {
2543
+ if (pixelRegex.test(vNode.properties.style.width)) {
2544
+ modifiedWidth = pixelToEMU(vNode.properties.style.width.match(pixelRegex)[1]);
2545
+ }
2546
+ else if (percentageRegex.test(vNode.properties.style.width)) {
2547
+ const percentageValue = vNode.properties.style.width.match(percentageRegex)[1];
2548
+ modifiedWidth = Math.round((percentageValue / 100) * originalWidthInEMU);
2549
+ }
2550
+ }
2551
+ else {
2552
+ // eslint-disable-next-line no-lonely-if
2553
+ if (vNode.properties.style.height && vNode.properties.style.height === 'auto') {
2554
+ modifiedWidth = originalWidthInEMU;
2555
+ modifiedHeight = originalHeightInEMU;
2556
+ }
2557
+ }
2558
+ }
2559
+ if (vNode.properties.style.height) {
2560
+ if (vNode.properties.style.height !== 'auto') {
2561
+ if (pixelRegex.test(vNode.properties.style.height)) {
2562
+ modifiedHeight = pixelToEMU(vNode.properties.style.height.match(pixelRegex)[1]);
2563
+ }
2564
+ else if (percentageRegex.test(vNode.properties.style.height)) {
2565
+ const percentageValue = vNode.properties.style.width.match(percentageRegex)[1];
2566
+ modifiedHeight = Math.round((percentageValue / 100) * originalHeightInEMU);
2567
+ if (!modifiedWidth) {
2568
+ modifiedWidth = Math.round(modifiedHeight * aspectRatio);
2569
+ }
2570
+ }
2571
+ }
2572
+ else {
2573
+ // eslint-disable-next-line no-lonely-if
2574
+ if (modifiedWidth) {
2575
+ if (!modifiedHeight) {
2576
+ modifiedHeight = Math.round(modifiedWidth / aspectRatio);
2577
+ }
2578
+ }
2579
+ else {
2580
+ modifiedHeight = originalHeightInEMU;
2581
+ modifiedWidth = originalWidthInEMU;
2582
+ }
2583
+ }
2584
+ }
2585
+ if (modifiedWidth && !modifiedHeight) {
2586
+ modifiedHeight = Math.round(modifiedWidth / aspectRatio);
2587
+ }
2588
+ else if (modifiedHeight && !modifiedWidth) {
2589
+ modifiedWidth = Math.round(modifiedHeight * aspectRatio);
2590
+ }
2591
+ }
2592
+ else {
2593
+ modifiedWidth = originalWidthInEMU;
2594
+ modifiedHeight = originalHeightInEMU;
2595
+ }
2596
+ // eslint-disable-next-line no-param-reassign
2597
+ attributes.width = modifiedWidth;
2598
+ // eslint-disable-next-line no-param-reassign
2599
+ attributes.height = modifiedHeight;
2600
+ };
2601
+ const ɵ37 = computeImageDimensions;
2602
+ const buildParagraph = (vNode, attributes, docxDocumentInstance) => __awaiter(void 0, void 0, void 0, function* () {
2603
+ const paragraphFragment = fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'p');
2604
+ const modifiedAttributes = modifiedStyleAttributesBuilder(vNode, attributes, {
2605
+ isParagraph: true,
2606
+ });
2607
+ const paragraphPropertiesFragment = buildParagraphProperties(modifiedAttributes);
2608
+ paragraphFragment.import(paragraphPropertiesFragment);
2609
+ if (isVNode(vNode) && vNodeHasChildren(vNode)) {
2610
+ if ([
2611
+ 'span',
2612
+ 'strong',
2613
+ 'b',
2614
+ 'em',
2615
+ 'i',
2616
+ 'u',
2617
+ 'ins',
2618
+ 'strike',
2619
+ 'del',
2620
+ 's',
2621
+ 'sub',
2622
+ 'sup',
2623
+ 'mark',
2624
+ 'a',
2625
+ 'code',
2626
+ 'pre',
2627
+ ].includes(vNode.tagName)) {
2628
+ const runOrHyperlinkFragments = yield buildRunOrHyperLink(vNode, modifiedAttributes, docxDocumentInstance);
2629
+ if (Array.isArray(runOrHyperlinkFragments)) {
2630
+ for (let iteratorIndex = 0; iteratorIndex < runOrHyperlinkFragments.length; iteratorIndex++) {
2631
+ const runOrHyperlinkFragment = runOrHyperlinkFragments[iteratorIndex];
2632
+ paragraphFragment.import(runOrHyperlinkFragment);
2633
+ }
2634
+ }
2635
+ else {
2636
+ paragraphFragment.import(runOrHyperlinkFragments);
2637
+ }
2638
+ }
2639
+ else if (vNode.tagName === 'blockquote') {
2640
+ const runFragmentOrFragments = yield buildRun(vNode, attributes);
2641
+ if (Array.isArray(runFragmentOrFragments)) {
2642
+ for (let index = 0; index < runFragmentOrFragments.length; index++) {
2643
+ paragraphFragment.import(runFragmentOrFragments[index]);
2644
+ }
2645
+ }
2646
+ else {
2647
+ paragraphFragment.import(runFragmentOrFragments);
2648
+ }
2649
+ }
2650
+ else {
2651
+ for (let index = 0; index < vNode.children.length; index++) {
2652
+ const childVNode = vNode.children[index];
2653
+ if (childVNode.tagName === 'img') {
2654
+ let base64String;
2655
+ const imageSource = childVNode.properties.src;
2656
+ if (isValidUrl(imageSource)) {
2657
+ base64String = yield imageToBase64(imageSource).catch((error) => {
2658
+ // eslint-disable-next-line no-console
2659
+ console.warning(`skipping image download and conversion due to ${error}`);
2660
+ });
2661
+ if (base64String && mimeTypes.lookup(imageSource)) {
2662
+ childVNode.properties.src = `data:${mimeTypes.lookup(imageSource)};base64, ${base64String}`;
2663
+ }
2664
+ else {
2665
+ break;
2666
+ }
2667
+ }
2668
+ else {
2669
+ // eslint-disable-next-line no-useless-escape, prefer-destructuring
2670
+ base64String = imageSource.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/)[2];
2671
+ }
2672
+ const imageBuffer = Buffer.from(decodeURIComponent(base64String), 'base64');
2673
+ const imageProperties = sizeOf(imageBuffer);
2674
+ modifiedAttributes.maximumWidth =
2675
+ modifiedAttributes.maximumWidth || docxDocumentInstance.availableDocumentSpace;
2676
+ modifiedAttributes.originalWidth = imageProperties.width;
2677
+ modifiedAttributes.originalHeight = imageProperties.height;
2678
+ computeImageDimensions(childVNode, modifiedAttributes);
2679
+ }
2680
+ const runOrHyperlinkFragments = yield buildRunOrHyperLink(childVNode, isVNode(childVNode) && childVNode.tagName === 'img'
2681
+ ? Object.assign(Object.assign({}, modifiedAttributes), { type: 'picture' }) : modifiedAttributes, docxDocumentInstance);
2682
+ if (Array.isArray(runOrHyperlinkFragments)) {
2683
+ for (let iteratorIndex = 0; iteratorIndex < runOrHyperlinkFragments.length; iteratorIndex++) {
2684
+ const runOrHyperlinkFragment = runOrHyperlinkFragments[iteratorIndex];
2685
+ paragraphFragment.import(runOrHyperlinkFragment);
2686
+ }
2687
+ }
2688
+ else {
2689
+ paragraphFragment.import(runOrHyperlinkFragments);
2690
+ }
2691
+ }
2692
+ }
2693
+ }
2694
+ else {
2695
+ // In case paragraphs has to be rendered where vText is present. Eg. table-cell
2696
+ // Or in case the vNode is something like img
2697
+ if (isVNode(vNode) && vNode.tagName === 'img') {
2698
+ const imageSource = vNode.properties.src;
2699
+ let base64String = imageSource;
2700
+ if (isValidUrl(imageSource)) {
2701
+ base64String = yield imageToBase64(imageSource).catch((error) => {
2702
+ // eslint-disable-next-line no-console
2703
+ console.warning(`skipping image download and conversion due to ${error}`);
2704
+ });
2705
+ if (base64String && mimeTypes.lookup(imageSource)) {
2706
+ vNode.properties.src = `data:${mimeTypes.lookup(imageSource)};base64, ${base64String}`;
2707
+ }
2708
+ else {
2709
+ paragraphFragment.up();
2710
+ return paragraphFragment;
2711
+ }
2712
+ }
2713
+ else {
2714
+ // eslint-disable-next-line no-useless-escape, prefer-destructuring
2715
+ base64String = base64String.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/)[2];
2716
+ }
2717
+ const imageBuffer = Buffer.from(decodeURIComponent(base64String), 'base64');
2718
+ const imageProperties = sizeOf(imageBuffer);
2719
+ modifiedAttributes.maximumWidth =
2720
+ modifiedAttributes.maximumWidth || docxDocumentInstance.availableDocumentSpace;
2721
+ modifiedAttributes.originalWidth = imageProperties.width;
2722
+ modifiedAttributes.originalHeight = imageProperties.height;
2723
+ computeImageDimensions(vNode, modifiedAttributes);
2724
+ }
2725
+ const runFragments = yield buildRunOrRuns(vNode, modifiedAttributes, docxDocumentInstance);
2726
+ if (Array.isArray(runFragments)) {
2727
+ for (let index = 0; index < runFragments.length; index++) {
2728
+ const runFragment = runFragments[index];
2729
+ paragraphFragment.import(runFragment);
2730
+ }
2731
+ }
2732
+ else {
2733
+ paragraphFragment.import(runFragments);
2734
+ }
2735
+ }
2736
+ paragraphFragment.up();
2737
+ return paragraphFragment;
2738
+ });
2739
+ const ɵ38 = buildParagraph;
2740
+ const buildGridSpanFragment = (spanValue) => fragment({ namespaceAlias: { w: namespaces.w } })
2741
+ .ele('@w', 'gridSpan')
2742
+ .att('@w', 'val', spanValue)
2743
+ .up();
2744
+ const ɵ39 = buildGridSpanFragment;
2745
+ const buildTableCellSpacing = (cellSpacing = 0) => fragment({ namespaceAlias: { w: namespaces.w } })
2746
+ .ele('@w', 'tblCellSpacing')
2747
+ .att('@w', 'w', cellSpacing)
2748
+ .att('@w', 'type', 'dxa')
2749
+ .up();
2750
+ const ɵ40 = buildTableCellSpacing;
2751
+ const buildTableCellBorders = (tableCellBorder) => {
2752
+ const tableCellBordersFragment = fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'tcBorders');
2753
+ const { color, stroke } = tableCellBorder, borders = __rest(tableCellBorder, ["color", "stroke"]);
2754
+ Object.keys(borders).forEach((border) => {
2755
+ if (tableCellBorder[border]) {
2756
+ const borderFragment = buildBorder(border, tableCellBorder[border], 0, color, stroke);
2757
+ tableCellBordersFragment.import(borderFragment);
2758
+ }
2759
+ });
2760
+ tableCellBordersFragment.up();
2761
+ return tableCellBordersFragment;
2762
+ };
2763
+ const ɵ41 = buildTableCellBorders;
2764
+ const buildTableCellWidth = (tableCellWidth) => fragment({ namespaceAlias: { w: namespaces.w } })
2765
+ .ele('@w', 'tcW')
2766
+ .att('@w', 'w', fixupColumnWidth(tableCellWidth))
2767
+ .att('@w', 'type', 'dxa')
2768
+ .up();
2769
+ const ɵ42 = buildTableCellWidth;
2770
+ const buildTableCellProperties = (attributes) => {
2771
+ const tableCellPropertiesFragment = fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'tcPr');
2772
+ if (attributes && attributes.constructor === Object) {
2773
+ Object.keys(attributes).forEach((key) => {
2774
+ switch (key) {
2775
+ case 'backgroundColor':
2776
+ const shadingFragment = buildShading(attributes[key]);
2777
+ tableCellPropertiesFragment.import(shadingFragment);
2778
+ // eslint-disable-next-line no-param-reassign
2779
+ delete attributes.backgroundColor;
2780
+ break;
2781
+ case 'verticalAlign':
2782
+ const verticalAlignmentFragment = buildVerticalAlignment(attributes[key]);
2783
+ tableCellPropertiesFragment.import(verticalAlignmentFragment);
2784
+ // eslint-disable-next-line no-param-reassign
2785
+ delete attributes.verticalAlign;
2786
+ break;
2787
+ case 'colSpan':
2788
+ const gridSpanFragment = buildGridSpanFragment(attributes[key]);
2789
+ tableCellPropertiesFragment.import(gridSpanFragment);
2790
+ // eslint-disable-next-line no-param-reassign
2791
+ delete attributes.colSpan;
2792
+ break;
2793
+ case 'tableCellBorder':
2794
+ const tableCellBorderFragment = buildTableCellBorders(attributes[key]);
2795
+ tableCellPropertiesFragment.import(tableCellBorderFragment);
2796
+ // eslint-disable-next-line no-param-reassign
2797
+ delete attributes.tableCellBorder;
2798
+ break;
2799
+ case 'rowSpan':
2800
+ const verticalMergeFragment = buildVerticalMerge(attributes[key]);
2801
+ tableCellPropertiesFragment.import(verticalMergeFragment);
2802
+ delete attributes.rowSpan;
2803
+ break;
2804
+ case 'width':
2805
+ const widthFragment = buildTableCellWidth(attributes[key]);
2806
+ tableCellPropertiesFragment.import(widthFragment);
2807
+ delete attributes.width;
2808
+ break;
2809
+ }
2810
+ });
2811
+ }
2812
+ tableCellPropertiesFragment.up();
2813
+ return tableCellPropertiesFragment;
2814
+ };
2815
+ const ɵ43 = buildTableCellProperties;
2816
+ const fixupTableCellBorder = (vNode, attributes) => {
2817
+ if (Object.prototype.hasOwnProperty.call(vNode.properties.style, 'border')) {
2818
+ if (vNode.properties.style.border === 'none' || vNode.properties.style.border === 0) {
2819
+ attributes.tableCellBorder = {};
2820
+ }
2821
+ else {
2822
+ // eslint-disable-next-line no-use-before-define
2823
+ const [borderSize, borderStroke, borderColor] = cssBorderParser(vNode.properties.style.border);
2824
+ attributes.tableCellBorder = {
2825
+ top: borderSize,
2826
+ left: borderSize,
2827
+ bottom: borderSize,
2828
+ right: borderSize,
2829
+ color: borderColor,
2830
+ stroke: borderStroke,
2831
+ };
2832
+ }
2833
+ }
2834
+ if (vNode.properties.style['border-top'] && vNode.properties.style['border-top'] === '0') {
2835
+ attributes.tableCellBorder = Object.assign(Object.assign({}, attributes.tableCellBorder), { top: 0 });
2836
+ }
2837
+ else if (vNode.properties.style['border-top'] && vNode.properties.style['border-top'] !== '0') {
2838
+ // eslint-disable-next-line no-use-before-define
2839
+ const [borderSize, borderStroke, borderColor] = cssBorderParser(vNode.properties.style['border-top']);
2840
+ attributes.tableCellBorder = Object.assign(Object.assign({}, attributes.tableCellBorder), { top: borderSize, color: borderColor, stroke: borderStroke });
2841
+ }
2842
+ if (vNode.properties.style['border-left'] && vNode.properties.style['border-left'] === '0') {
2843
+ attributes.tableCellBorder = Object.assign(Object.assign({}, attributes.tableCellBorder), { left: 0 });
2844
+ }
2845
+ else if (vNode.properties.style['border-left'] &&
2846
+ vNode.properties.style['border-left'] !== '0') {
2847
+ // eslint-disable-next-line no-use-before-define
2848
+ const [borderSize, borderStroke, borderColor] = cssBorderParser(vNode.properties.style['border-left']);
2849
+ attributes.tableCellBorder = Object.assign(Object.assign({}, attributes.tableCellBorder), { left: borderSize, color: borderColor, stroke: borderStroke });
2850
+ }
2851
+ if (vNode.properties.style['border-bottom'] && vNode.properties.style['border-bottom'] === '0') {
2852
+ attributes.tableCellBorder = Object.assign(Object.assign({}, attributes.tableCellBorder), { bottom: 0 });
2853
+ }
2854
+ else if (vNode.properties.style['border-bottom'] &&
2855
+ vNode.properties.style['border-bottom'] !== '0') {
2856
+ // eslint-disable-next-line no-use-before-define
2857
+ const [borderSize, borderStroke, borderColor] = cssBorderParser(vNode.properties.style['border-bottom']);
2858
+ attributes.tableCellBorder = Object.assign(Object.assign({}, attributes.tableCellBorder), { bottom: borderSize, color: borderColor, stroke: borderStroke });
2859
+ }
2860
+ if (vNode.properties.style['border-right'] && vNode.properties.style['border-right'] === '0') {
2861
+ attributes.tableCellBorder = Object.assign(Object.assign({}, attributes.tableCellBorder), { right: 0 });
2862
+ }
2863
+ else if (vNode.properties.style['border-right'] &&
2864
+ vNode.properties.style['border-right'] !== '0') {
2865
+ // eslint-disable-next-line no-use-before-define
2866
+ const [borderSize, borderStroke, borderColor] = cssBorderParser(vNode.properties.style['border-right']);
2867
+ attributes.tableCellBorder = Object.assign(Object.assign({}, attributes.tableCellBorder), { right: borderSize, color: borderColor, stroke: borderStroke });
2868
+ }
2869
+ };
2870
+ const ɵ44 = fixupTableCellBorder;
2871
+ const buildTableCell = (vNode, attributes, rowSpanMap, columnIndex, docxDocumentInstance) => __awaiter(void 0, void 0, void 0, function* () {
2872
+ const tableCellFragment = fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'tc');
2873
+ let modifiedAttributes = Object.assign({}, attributes);
2874
+ if (isVNode(vNode) && vNode.properties) {
2875
+ if (vNode.properties.rowSpan) {
2876
+ rowSpanMap.set(columnIndex.index, { rowSpan: vNode.properties.rowSpan - 1, colSpan: 0 });
2877
+ modifiedAttributes.rowSpan = 'restart';
2878
+ }
2879
+ else {
2880
+ const previousSpanObject = rowSpanMap.get(columnIndex.index);
2881
+ rowSpanMap.set(columnIndex.index,
2882
+ // eslint-disable-next-line prefer-object-spread
2883
+ Object.assign({}, previousSpanObject, {
2884
+ rowSpan: 0,
2885
+ colSpan: (previousSpanObject && previousSpanObject.colSpan) || 0,
2886
+ }));
2887
+ }
2888
+ if (vNode.properties.colSpan ||
2889
+ (vNode.properties.style && vNode.properties.style['column-span'])) {
2890
+ modifiedAttributes.colSpan =
2891
+ vNode.properties.colSpan ||
2892
+ (vNode.properties.style && vNode.properties.style['column-span']);
2893
+ const previousSpanObject = rowSpanMap.get(columnIndex.index);
2894
+ rowSpanMap.set(columnIndex.index,
2895
+ // eslint-disable-next-line prefer-object-spread
2896
+ Object.assign({}, previousSpanObject, {
2897
+ colSpan: parseInt(modifiedAttributes.colSpan) || 0,
2898
+ }));
2899
+ columnIndex.index += parseInt(modifiedAttributes.colSpan) - 1;
2900
+ }
2901
+ if (vNode.properties.style) {
2902
+ modifiedAttributes = Object.assign(Object.assign({}, modifiedAttributes), modifiedStyleAttributesBuilder(vNode, attributes));
2903
+ fixupTableCellBorder(vNode, modifiedAttributes);
2904
+ }
2905
+ }
2906
+ const tableCellPropertiesFragment = buildTableCellProperties(modifiedAttributes);
2907
+ tableCellFragment.import(tableCellPropertiesFragment);
2908
+ if (vNodeHasChildren(vNode)) {
2909
+ for (let index = 0; index < vNode.children.length; index++) {
2910
+ const childVNode = vNode.children[index];
2911
+ if (isVNode(childVNode) && childVNode.tagName === 'img') {
2912
+ const imageFragment = yield buildImage(docxDocumentInstance, childVNode, modifiedAttributes.maximumWidth);
2913
+ if (imageFragment) {
2914
+ tableCellFragment.import(imageFragment);
2915
+ }
2916
+ }
2917
+ else if (isVNode(childVNode) && childVNode.tagName === 'figure') {
2918
+ if (vNodeHasChildren(childVNode)) {
2919
+ // eslint-disable-next-line no-plusplus
2920
+ for (let iteratorIndex = 0; iteratorIndex < childVNode.children.length; iteratorIndex++) {
2921
+ const grandChildVNode = childVNode.children[iteratorIndex];
2922
+ if (grandChildVNode.tagName === 'img') {
2923
+ const imageFragment = yield buildImage(docxDocumentInstance, grandChildVNode, modifiedAttributes.maximumWidth);
2924
+ if (imageFragment) {
2925
+ tableCellFragment.import(imageFragment);
2926
+ }
2927
+ }
2928
+ }
2929
+ }
2930
+ }
2931
+ else if (isVNode(childVNode) && ['ul', 'ol'].includes(childVNode.tagName)) {
2932
+ // render list in table
2933
+ if (vNodeHasChildren(childVNode)) {
2934
+ yield buildList(childVNode, docxDocumentInstance, tableCellFragment);
2935
+ }
2936
+ }
2937
+ else {
2938
+ const paragraphFragment = yield buildParagraph(childVNode, modifiedAttributes, docxDocumentInstance);
2939
+ tableCellFragment.import(paragraphFragment);
2940
+ }
2941
+ }
2942
+ }
2943
+ else {
2944
+ // TODO: Figure out why building with buildParagraph() isn't working
2945
+ const paragraphFragment = fragment({ namespaceAlias: { w: namespaces.w } })
2946
+ .ele('@w', 'p')
2947
+ .up();
2948
+ tableCellFragment.import(paragraphFragment);
2949
+ }
2950
+ tableCellFragment.up();
2951
+ return tableCellFragment;
2952
+ });
2953
+ const ɵ45 = buildTableCell;
2954
+ const buildRowSpanCell = (rowSpanMap, columnIndex, attributes) => {
2955
+ const rowSpanCellFragments = [];
2956
+ let spanObject = rowSpanMap.get(columnIndex.index);
2957
+ while (spanObject && spanObject.rowSpan) {
2958
+ const rowSpanCellFragment = fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'tc');
2959
+ const tableCellPropertiesFragment = buildTableCellProperties(Object.assign(Object.assign({}, attributes), { rowSpan: 'continue', colSpan: spanObject.colSpan ? spanObject.colSpan : 0 }));
2960
+ rowSpanCellFragment.import(tableCellPropertiesFragment);
2961
+ const paragraphFragment = fragment({ namespaceAlias: { w: namespaces.w } })
2962
+ .ele('@w', 'p')
2963
+ .up();
2964
+ rowSpanCellFragment.import(paragraphFragment);
2965
+ rowSpanCellFragment.up();
2966
+ rowSpanCellFragments.push(rowSpanCellFragment);
2967
+ if (spanObject.rowSpan - 1 === 0) {
2968
+ rowSpanMap.delete(columnIndex.index);
2969
+ }
2970
+ else {
2971
+ rowSpanMap.set(columnIndex.index, {
2972
+ rowSpan: spanObject.rowSpan - 1,
2973
+ colSpan: spanObject.colSpan || 0,
2974
+ });
2975
+ }
2976
+ columnIndex.index += spanObject.colSpan || 1;
2977
+ spanObject = rowSpanMap.get(columnIndex.index);
2978
+ }
2979
+ return rowSpanCellFragments;
2980
+ };
2981
+ const ɵ46 = buildRowSpanCell;
2982
+ const buildTableRowProperties = (attributes) => {
2983
+ const tableRowPropertiesFragment = fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'trPr');
2984
+ if (attributes && attributes.constructor === Object) {
2985
+ Object.keys(attributes).forEach((key) => {
2986
+ switch (key) {
2987
+ case 'tableRowHeight':
2988
+ const tableRowHeightFragment = buildTableRowHeight(attributes[key]);
2989
+ tableRowPropertiesFragment.import(tableRowHeightFragment);
2990
+ // eslint-disable-next-line no-param-reassign
2991
+ delete attributes.tableRowHeight;
2992
+ break;
2993
+ case 'rowCantSplit':
2994
+ if (attributes.rowCantSplit) {
2995
+ const cantSplitFragment = fragment({ namespaceAlias: { w: namespaces.w } })
2996
+ .ele('@w', 'cantSplit')
2997
+ .up();
2998
+ tableRowPropertiesFragment.import(cantSplitFragment);
2999
+ // eslint-disable-next-line no-param-reassign
3000
+ delete attributes.rowCantSplit;
3001
+ }
3002
+ break;
3003
+ }
3004
+ });
3005
+ }
3006
+ tableRowPropertiesFragment.up();
3007
+ return tableRowPropertiesFragment;
3008
+ };
3009
+ const ɵ47 = buildTableRowProperties;
3010
+ const buildTableRow = (vNode, attributes, rowSpanMap, docxDocumentInstance) => __awaiter(void 0, void 0, void 0, function* () {
3011
+ const tableRowFragment = fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'tr');
3012
+ const modifiedAttributes = Object.assign({}, attributes);
3013
+ if (isVNode(vNode) && vNode.properties) {
3014
+ // FIXME: find a better way to get row height from cell style
3015
+ if ((vNode.properties.style && vNode.properties.style.height) ||
3016
+ (vNode.children[0] &&
3017
+ isVNode(vNode.children[0]) &&
3018
+ vNode.children[0].properties.style &&
3019
+ vNode.children[0].properties.style.height)) {
3020
+ modifiedAttributes.tableRowHeight = fixupRowHeight((vNode.properties.style && vNode.properties.style.height) ||
3021
+ (vNode.children[0] &&
3022
+ isVNode(vNode.children[0]) &&
3023
+ vNode.children[0].properties.style &&
3024
+ vNode.children[0].properties.style.height
3025
+ ? vNode.children[0].properties.style.height
3026
+ : undefined));
3027
+ }
3028
+ if (vNode.properties.style) {
3029
+ fixupTableCellBorder(vNode, modifiedAttributes);
3030
+ }
3031
+ }
3032
+ const tableRowPropertiesFragment = buildTableRowProperties(modifiedAttributes);
3033
+ tableRowFragment.import(tableRowPropertiesFragment);
3034
+ const columnIndex = { index: 0 };
3035
+ if (vNodeHasChildren(vNode)) {
3036
+ const tableColumns = vNode.children.filter((childVNode) => ['td', 'th'].includes(childVNode.tagName));
3037
+ const maximumColumnWidth = docxDocumentInstance.availableDocumentSpace / tableColumns.length;
3038
+ // eslint-disable-next-line no-restricted-syntax
3039
+ for (const column of tableColumns) {
3040
+ const rowSpanCellFragments = buildRowSpanCell(rowSpanMap, columnIndex, modifiedAttributes);
3041
+ if (Array.isArray(rowSpanCellFragments)) {
3042
+ for (let iteratorIndex = 0; iteratorIndex < rowSpanCellFragments.length; iteratorIndex++) {
3043
+ const rowSpanCellFragment = rowSpanCellFragments[iteratorIndex];
3044
+ tableRowFragment.import(rowSpanCellFragment);
3045
+ }
3046
+ }
3047
+ const tableCellFragment = yield buildTableCell(column, Object.assign(Object.assign({}, modifiedAttributes), { maximumWidth: maximumColumnWidth }), rowSpanMap, columnIndex, docxDocumentInstance);
3048
+ columnIndex.index++;
3049
+ tableRowFragment.import(tableCellFragment);
3050
+ }
3051
+ }
3052
+ if (columnIndex.index < rowSpanMap.size) {
3053
+ const rowSpanCellFragments = buildRowSpanCell(rowSpanMap, columnIndex, modifiedAttributes);
3054
+ if (Array.isArray(rowSpanCellFragments)) {
3055
+ for (let iteratorIndex = 0; iteratorIndex < rowSpanCellFragments.length; iteratorIndex++) {
3056
+ const rowSpanCellFragment = rowSpanCellFragments[iteratorIndex];
3057
+ tableRowFragment.import(rowSpanCellFragment);
3058
+ }
3059
+ }
3060
+ }
3061
+ tableRowFragment.up();
3062
+ return tableRowFragment;
3063
+ });
3064
+ const ɵ48 = buildTableRow;
3065
+ const buildTableGridCol = (gridWidth) => fragment({ namespaceAlias: { w: namespaces.w } })
3066
+ .ele('@w', 'gridCol')
3067
+ .att('@w', 'w', String(gridWidth));
3068
+ const ɵ49 = buildTableGridCol;
3069
+ const buildTableGrid = (vNode, attributes) => {
3070
+ const tableGridFragment = fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'tblGrid');
3071
+ if (vNodeHasChildren(vNode)) {
3072
+ const gridColumns = vNode.children.filter((childVNode) => childVNode.tagName === 'col');
3073
+ const gridWidth = attributes.maximumWidth / gridColumns.length;
3074
+ for (let index = 0; index < gridColumns.length; index++) {
3075
+ const tableGridColFragment = buildTableGridCol(gridWidth);
3076
+ tableGridFragment.import(tableGridColFragment);
3077
+ }
3078
+ }
3079
+ tableGridFragment.up();
3080
+ return tableGridFragment;
3081
+ };
3082
+ const ɵ50 = buildTableGrid;
3083
+ const buildTableGridFromTableRow = (vNode, attributes) => {
3084
+ const tableGridFragment = fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'tblGrid');
3085
+ if (vNodeHasChildren(vNode)) {
3086
+ const numberOfGridColumns = vNode.children.reduce((accumulator, childVNode) => {
3087
+ const colSpan = childVNode.properties.colSpan ||
3088
+ (childVNode.properties.style && childVNode.properties.style['column-span']);
3089
+ return accumulator + (colSpan ? parseInt(colSpan) : 1);
3090
+ }, 0);
3091
+ const gridWidth = attributes.maximumWidth / numberOfGridColumns;
3092
+ for (let index = 0; index < numberOfGridColumns; index++) {
3093
+ const tableGridColFragment = buildTableGridCol(gridWidth);
3094
+ tableGridFragment.import(tableGridColFragment);
3095
+ }
3096
+ }
3097
+ tableGridFragment.up();
3098
+ return tableGridFragment;
3099
+ };
3100
+ const ɵ51 = buildTableGridFromTableRow;
3101
+ const buildTableBorders = (tableBorder) => {
3102
+ const tableBordersFragment = fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'tblBorders');
3103
+ const { color, stroke } = tableBorder, borders = __rest(tableBorder, ["color", "stroke"]);
3104
+ Object.keys(borders).forEach((border) => {
3105
+ if (borders[border]) {
3106
+ const borderFragment = buildBorder(border, borders[border], 0, color, stroke);
3107
+ tableBordersFragment.import(borderFragment);
3108
+ }
3109
+ });
3110
+ tableBordersFragment.up();
3111
+ return tableBordersFragment;
3112
+ };
3113
+ const ɵ52 = buildTableBorders;
3114
+ const buildTableWidth = (tableWidth) => fragment({ namespaceAlias: { w: namespaces.w } })
3115
+ .ele('@w', 'tblW')
3116
+ .att('@w', 'type', 'dxa')
3117
+ .att('@w', 'w', String(tableWidth))
3118
+ .up();
3119
+ const ɵ53 = buildTableWidth;
3120
+ const buildCellMargin = (side, margin) => fragment({ namespaceAlias: { w: namespaces.w } })
3121
+ .ele('@w', side)
3122
+ .att('@w', 'type', 'dxa')
3123
+ .att('@w', 'w', String(margin))
3124
+ .up();
3125
+ const ɵ54 = buildCellMargin;
3126
+ const buildTableCellMargins = (margin) => {
3127
+ const tableCellMarFragment = fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'tblCellMar');
3128
+ ['top', 'bottom'].forEach((side) => {
3129
+ const marginFragment = buildCellMargin(side, margin / 2);
3130
+ tableCellMarFragment.import(marginFragment);
3131
+ });
3132
+ ['left', 'right'].forEach((side) => {
3133
+ const marginFragment = buildCellMargin(side, margin);
3134
+ tableCellMarFragment.import(marginFragment);
3135
+ });
3136
+ return tableCellMarFragment;
3137
+ };
3138
+ const ɵ55 = buildTableCellMargins;
3139
+ const buildTableProperties = (attributes) => {
3140
+ const tablePropertiesFragment = fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'tblPr');
3141
+ if (attributes && attributes.constructor === Object) {
3142
+ Object.keys(attributes).forEach((key) => {
3143
+ switch (key) {
3144
+ case 'tableBorder':
3145
+ const tableBordersFragment = buildTableBorders(attributes[key]);
3146
+ tablePropertiesFragment.import(tableBordersFragment);
3147
+ // eslint-disable-next-line no-param-reassign
3148
+ delete attributes.tableBorder;
3149
+ break;
3150
+ case 'tableCellSpacing':
3151
+ const tableCellSpacingFragment = buildTableCellSpacing(attributes[key]);
3152
+ tablePropertiesFragment.import(tableCellSpacingFragment);
3153
+ // eslint-disable-next-line no-param-reassign
3154
+ delete attributes.tableCellSpacing;
3155
+ break;
3156
+ case 'width':
3157
+ if (attributes[key]) {
3158
+ const tableWidthFragment = buildTableWidth(attributes[key]);
3159
+ tablePropertiesFragment.import(tableWidthFragment);
3160
+ }
3161
+ // eslint-disable-next-line no-param-reassign
3162
+ delete attributes.width;
3163
+ break;
3164
+ }
3165
+ });
3166
+ }
3167
+ const tableCellMarginFragment = buildTableCellMargins(160);
3168
+ tablePropertiesFragment.import(tableCellMarginFragment);
3169
+ // by default, all tables are center aligned.
3170
+ const alignmentFragment = buildHorizontalAlignment('center');
3171
+ tablePropertiesFragment.import(alignmentFragment);
3172
+ tablePropertiesFragment.up();
3173
+ return tablePropertiesFragment;
3174
+ };
3175
+ const ɵ56 = buildTableProperties;
3176
+ const cssBorderParser = (borderString) => {
3177
+ let [size, stroke, color] = borderString.split(' ');
3178
+ if (pointRegex.test(size)) {
3179
+ const matchedParts = size.match(pointRegex);
3180
+ // convert point to eighth of a point
3181
+ size = pointToEIP(matchedParts[1]);
3182
+ }
3183
+ else if (pixelRegex.test(size)) {
3184
+ const matchedParts = size.match(pixelRegex);
3185
+ // convert pixels to eighth of a point
3186
+ size = pixelToEIP(matchedParts[1]);
3187
+ }
3188
+ stroke = stroke && ['dashed', 'dotted', 'double'].includes(stroke) ? stroke : 'single';
3189
+ color = color && fixupColorCode(color).toUpperCase();
3190
+ return [size, stroke, color];
3191
+ };
3192
+ const ɵ57 = cssBorderParser;
3193
+ const buildTable = (vNode, attributes, docxDocumentInstance) => __awaiter(void 0, void 0, void 0, function* () {
3194
+ const tableFragment = fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'tbl');
3195
+ const modifiedAttributes = Object.assign({}, attributes);
3196
+ if (isVNode(vNode) && vNode.properties) {
3197
+ const tableAttributes = vNode.properties.attributes || {};
3198
+ const tableStyles = vNode.properties.style || {};
3199
+ const tableBorders = {};
3200
+ const tableCellBorders = {};
3201
+ let [borderSize, borderStrike, borderColor] = [2, 'single', '000000'];
3202
+ // eslint-disable-next-line no-restricted-globals
3203
+ if (!isNaN(tableAttributes.border)) {
3204
+ borderSize = parseInt(tableAttributes.border, 10);
3205
+ }
3206
+ // css style overrides table border properties
3207
+ if (tableStyles.border) {
3208
+ const [cssSize, cssStroke, cssColor] = cssBorderParser(tableStyles.border);
3209
+ borderSize = cssSize || borderSize;
3210
+ borderColor = cssColor || borderColor;
3211
+ borderStrike = cssStroke || borderStrike;
3212
+ }
3213
+ tableBorders.top = borderSize;
3214
+ tableBorders.bottom = borderSize;
3215
+ tableBorders.left = borderSize;
3216
+ tableBorders.right = borderSize;
3217
+ tableBorders.stroke = borderStrike;
3218
+ tableBorders.color = borderColor;
3219
+ if (tableStyles['border-collapse'] === 'collapse') {
3220
+ tableBorders.insideV = borderSize;
3221
+ tableBorders.insideH = borderSize;
3222
+ }
3223
+ else {
3224
+ tableBorders.insideV = 0;
3225
+ tableBorders.insideH = 0;
3226
+ tableCellBorders.top = 1;
3227
+ tableCellBorders.bottom = 1;
3228
+ tableCellBorders.left = 1;
3229
+ tableCellBorders.right = 1;
3230
+ }
3231
+ modifiedAttributes.tableBorder = tableBorders;
3232
+ modifiedAttributes.tableCellSpacing = 0;
3233
+ if (Object.keys(tableCellBorders).length) {
3234
+ modifiedAttributes.tableCellBorder = tableCellBorders;
3235
+ }
3236
+ let minimumWidth;
3237
+ let maximumWidth;
3238
+ let width;
3239
+ // Calculate minimum width of table
3240
+ if (pixelRegex.test(tableStyles['min-width'])) {
3241
+ minimumWidth = pixelToTWIP(tableStyles['min-width'].match(pixelRegex)[1]);
3242
+ }
3243
+ else if (percentageRegex.test(tableStyles['min-width'])) {
3244
+ const percentageValue = tableStyles['min-width'].match(percentageRegex)[1];
3245
+ minimumWidth = Math.round((percentageValue / 100) * attributes.maximumWidth);
3246
+ }
3247
+ // Calculate maximum width of table
3248
+ if (pixelRegex.test(tableStyles['max-width'])) {
3249
+ pixelRegex.lastIndex = 0;
3250
+ maximumWidth = pixelToTWIP(tableStyles['max-width'].match(pixelRegex)[1]);
3251
+ }
3252
+ else if (percentageRegex.test(tableStyles['max-width'])) {
3253
+ percentageRegex.lastIndex = 0;
3254
+ const percentageValue = tableStyles['max-width'].match(percentageRegex)[1];
3255
+ maximumWidth = Math.round((percentageValue / 100) * attributes.maximumWidth);
3256
+ }
3257
+ // Calculate specified width of table
3258
+ if (pixelRegex.test(tableStyles.width)) {
3259
+ pixelRegex.lastIndex = 0;
3260
+ width = pixelToTWIP(tableStyles.width.match(pixelRegex)[1]);
3261
+ }
3262
+ else if (percentageRegex.test(tableStyles.width)) {
3263
+ percentageRegex.lastIndex = 0;
3264
+ const percentageValue = tableStyles.width.match(percentageRegex)[1];
3265
+ width = Math.round((percentageValue / 100) * attributes.maximumWidth);
3266
+ }
3267
+ // If width isn't supplied, we should have min-width as the width.
3268
+ if (width) {
3269
+ modifiedAttributes.width = width;
3270
+ if (maximumWidth) {
3271
+ modifiedAttributes.width = Math.min(modifiedAttributes.width, maximumWidth);
3272
+ }
3273
+ if (minimumWidth) {
3274
+ modifiedAttributes.width = Math.max(modifiedAttributes.width, minimumWidth);
3275
+ }
3276
+ }
3277
+ else if (minimumWidth) {
3278
+ modifiedAttributes.width = minimumWidth;
3279
+ }
3280
+ if (modifiedAttributes.width) {
3281
+ modifiedAttributes.width = Math.min(modifiedAttributes.width, attributes.maximumWidth);
3282
+ }
3283
+ }
3284
+ const tablePropertiesFragment = buildTableProperties(modifiedAttributes);
3285
+ tableFragment.import(tablePropertiesFragment);
3286
+ const rowSpanMap = new Map();
3287
+ if (vNodeHasChildren(vNode)) {
3288
+ for (let index = 0; index < vNode.children.length; index++) {
3289
+ const childVNode = vNode.children[index];
3290
+ if (childVNode.tagName === 'colgroup') {
3291
+ const tableGridFragment = buildTableGrid(childVNode, modifiedAttributes);
3292
+ tableFragment.import(tableGridFragment);
3293
+ }
3294
+ else if (childVNode.tagName === 'thead') {
3295
+ for (let iteratorIndex = 0; iteratorIndex < childVNode.children.length; iteratorIndex++) {
3296
+ const grandChildVNode = childVNode.children[iteratorIndex];
3297
+ if (grandChildVNode.tagName === 'tr') {
3298
+ if (iteratorIndex === 0) {
3299
+ const tableGridFragment = buildTableGridFromTableRow(grandChildVNode, modifiedAttributes);
3300
+ tableFragment.import(tableGridFragment);
3301
+ }
3302
+ const tableRowFragment = yield buildTableRow(grandChildVNode, modifiedAttributes, rowSpanMap, docxDocumentInstance);
3303
+ tableFragment.import(tableRowFragment);
3304
+ }
3305
+ }
3306
+ }
3307
+ else if (childVNode.tagName === 'tbody') {
3308
+ for (let iteratorIndex = 0; iteratorIndex < childVNode.children.length; iteratorIndex++) {
3309
+ const grandChildVNode = childVNode.children[iteratorIndex];
3310
+ if (grandChildVNode.tagName === 'tr') {
3311
+ if (iteratorIndex === 0) {
3312
+ const tableGridFragment = buildTableGridFromTableRow(grandChildVNode, modifiedAttributes);
3313
+ tableFragment.import(tableGridFragment);
3314
+ }
3315
+ const tableRowFragment = yield buildTableRow(grandChildVNode, modifiedAttributes, rowSpanMap, docxDocumentInstance);
3316
+ tableFragment.import(tableRowFragment);
3317
+ }
3318
+ }
3319
+ }
3320
+ else if (childVNode.tagName === 'tr') {
3321
+ if (index === 0) {
3322
+ const tableGridFragment = buildTableGridFromTableRow(childVNode, modifiedAttributes);
3323
+ tableFragment.import(tableGridFragment);
3324
+ }
3325
+ const tableRowFragment = yield buildTableRow(childVNode, modifiedAttributes, rowSpanMap, docxDocumentInstance);
3326
+ tableFragment.import(tableRowFragment);
3327
+ }
3328
+ }
3329
+ }
3330
+ tableFragment.up();
3331
+ return tableFragment;
3332
+ });
3333
+ const ɵ58 = buildTable;
3334
+ const buildPresetGeometry = () => fragment({ namespaceAlias: { a: namespaces.a } })
3335
+ .ele('@a', 'prstGeom')
3336
+ .att('prst', 'rect')
3337
+ .up();
3338
+ const ɵ59 = buildPresetGeometry;
3339
+ const buildExtents = ({ width, height }) => fragment({ namespaceAlias: { a: namespaces.a } })
3340
+ .ele('@a', 'ext')
3341
+ .att('cx', width)
3342
+ .att('cy', height)
3343
+ .up();
3344
+ const ɵ60 = buildExtents;
3345
+ const buildOffset = () => fragment({ namespaceAlias: { a: namespaces.a } })
3346
+ .ele('@a', 'off')
3347
+ .att('x', '0')
3348
+ .att('y', '0')
3349
+ .up();
3350
+ const ɵ61 = buildOffset;
3351
+ const buildGraphicFrameTransform = (attributes) => {
3352
+ const graphicFrameTransformFragment = fragment({ namespaceAlias: { a: namespaces.a } }).ele('@a', 'xfrm');
3353
+ const offsetFragment = buildOffset();
3354
+ graphicFrameTransformFragment.import(offsetFragment);
3355
+ const extentsFragment = buildExtents(attributes);
3356
+ graphicFrameTransformFragment.import(extentsFragment);
3357
+ graphicFrameTransformFragment.up();
3358
+ return graphicFrameTransformFragment;
3359
+ };
3360
+ const ɵ62 = buildGraphicFrameTransform;
3361
+ const buildShapeProperties = (attributes) => {
3362
+ const shapeProperties = fragment({ namespaceAlias: { pic: namespaces.pic } }).ele('@pic', 'spPr');
3363
+ const graphicFrameTransformFragment = buildGraphicFrameTransform(attributes);
3364
+ shapeProperties.import(graphicFrameTransformFragment);
3365
+ const presetGeometryFragment = buildPresetGeometry();
3366
+ shapeProperties.import(presetGeometryFragment);
3367
+ shapeProperties.up();
3368
+ return shapeProperties;
3369
+ };
3370
+ const ɵ63 = buildShapeProperties;
3371
+ const buildFillRect = () => fragment({ namespaceAlias: { a: namespaces.a } })
3372
+ .ele('@a', 'fillRect')
3373
+ .up();
3374
+ const ɵ64 = buildFillRect;
3375
+ const buildStretch = () => {
3376
+ const stretchFragment = fragment({ namespaceAlias: { a: namespaces.a } }).ele('@a', 'stretch');
3377
+ const fillRectFragment = buildFillRect();
3378
+ stretchFragment.import(fillRectFragment);
3379
+ stretchFragment.up();
3380
+ return stretchFragment;
3381
+ };
3382
+ const ɵ65 = buildStretch;
3383
+ const buildSrcRectFragment = () => fragment({ namespaceAlias: { a: namespaces.a } })
3384
+ .ele('@a', 'srcRect')
3385
+ .att('b', '0')
3386
+ .att('l', '0')
3387
+ .att('r', '0')
3388
+ .att('t', '0')
3389
+ .up();
3390
+ const ɵ66 = buildSrcRectFragment;
3391
+ const buildBinaryLargeImageOrPicture = (relationshipId) => fragment({
3392
+ namespaceAlias: { a: namespaces.a, r: namespaces.r },
3393
+ })
3394
+ .ele('@a', 'blip')
3395
+ .att('@r', 'embed', `rId${relationshipId}`)
3396
+ // FIXME: possible values 'email', 'none', 'print', 'hqprint', 'screen'
3397
+ .att('cstate', 'print')
3398
+ .up();
3399
+ const ɵ67 = buildBinaryLargeImageOrPicture;
3400
+ const buildBinaryLargeImageOrPictureFill = (relationshipId) => {
3401
+ const binaryLargeImageOrPictureFillFragment = fragment({
3402
+ namespaceAlias: { pic: namespaces.pic },
3403
+ }).ele('@pic', 'blipFill');
3404
+ const binaryLargeImageOrPictureFragment = buildBinaryLargeImageOrPicture(relationshipId);
3405
+ binaryLargeImageOrPictureFillFragment.import(binaryLargeImageOrPictureFragment);
3406
+ const srcRectFragment = buildSrcRectFragment();
3407
+ binaryLargeImageOrPictureFillFragment.import(srcRectFragment);
3408
+ const stretchFragment = buildStretch();
3409
+ binaryLargeImageOrPictureFillFragment.import(stretchFragment);
3410
+ binaryLargeImageOrPictureFillFragment.up();
3411
+ return binaryLargeImageOrPictureFillFragment;
3412
+ };
3413
+ const ɵ68 = buildBinaryLargeImageOrPictureFill;
3414
+ const buildNonVisualPictureDrawingProperties = () => fragment({ namespaceAlias: { pic: namespaces.pic } })
3415
+ .ele('@pic', 'cNvPicPr')
3416
+ .up();
3417
+ const ɵ69 = buildNonVisualPictureDrawingProperties;
3418
+ const buildNonVisualDrawingProperties = (pictureId, pictureNameWithExtension, pictureDescription = '') => fragment({ namespaceAlias: { pic: namespaces.pic } })
3419
+ .ele('@pic', 'cNvPr')
3420
+ .att('id', pictureId)
3421
+ .att('name', pictureNameWithExtension)
3422
+ .att('descr', pictureDescription)
3423
+ .up();
3424
+ const ɵ70 = buildNonVisualDrawingProperties;
3425
+ const buildNonVisualPictureProperties = (pictureId, pictureNameWithExtension, pictureDescription) => {
3426
+ const nonVisualPicturePropertiesFragment = fragment({
3427
+ namespaceAlias: { pic: namespaces.pic },
3428
+ }).ele('@pic', 'nvPicPr');
3429
+ // TODO: Handle picture attributes
3430
+ const nonVisualDrawingPropertiesFragment = buildNonVisualDrawingProperties(pictureId, pictureNameWithExtension, pictureDescription);
3431
+ nonVisualPicturePropertiesFragment.import(nonVisualDrawingPropertiesFragment);
3432
+ const nonVisualPictureDrawingPropertiesFragment = buildNonVisualPictureDrawingProperties();
3433
+ nonVisualPicturePropertiesFragment.import(nonVisualPictureDrawingPropertiesFragment);
3434
+ nonVisualPicturePropertiesFragment.up();
3435
+ return nonVisualPicturePropertiesFragment;
3436
+ };
3437
+ const ɵ71 = buildNonVisualPictureProperties;
3438
+ const buildPicture = ({ id, fileNameWithExtension, description, relationshipId, width, height, }) => {
3439
+ const pictureFragment = fragment({ namespaceAlias: { pic: namespaces.pic } }).ele('@pic', 'pic');
3440
+ const nonVisualPicturePropertiesFragment = buildNonVisualPictureProperties(id, fileNameWithExtension, description);
3441
+ pictureFragment.import(nonVisualPicturePropertiesFragment);
3442
+ const binaryLargeImageOrPictureFill = buildBinaryLargeImageOrPictureFill(relationshipId);
3443
+ pictureFragment.import(binaryLargeImageOrPictureFill);
3444
+ const shapeProperties = buildShapeProperties({ width, height });
3445
+ pictureFragment.import(shapeProperties);
3446
+ pictureFragment.up();
3447
+ return pictureFragment;
3448
+ };
3449
+ const ɵ72 = buildPicture;
3450
+ const buildGraphicData = (graphicType, attributes) => {
3451
+ const graphicDataFragment = fragment({ namespaceAlias: { a: namespaces.a } })
3452
+ .ele('@a', 'graphicData')
3453
+ .att('uri', 'http://schemas.openxmlformats.org/drawingml/2006/picture');
3454
+ if (graphicType === 'picture') {
3455
+ const pictureFragment = buildPicture(attributes);
3456
+ graphicDataFragment.import(pictureFragment);
3457
+ }
3458
+ graphicDataFragment.up();
3459
+ return graphicDataFragment;
3460
+ };
3461
+ const ɵ73 = buildGraphicData;
3462
+ const buildGraphic = (graphicType, attributes) => {
3463
+ const graphicFragment = fragment({ namespaceAlias: { a: namespaces.a } }).ele('@a', 'graphic');
3464
+ // TODO: Handle drawing type
3465
+ const graphicDataFragment = buildGraphicData(graphicType, attributes);
3466
+ graphicFragment.import(graphicDataFragment);
3467
+ graphicFragment.up();
3468
+ return graphicFragment;
3469
+ };
3470
+ const ɵ74 = buildGraphic;
3471
+ const buildDrawingObjectNonVisualProperties = (pictureId, pictureName) => fragment({ namespaceAlias: { wp: namespaces.wp } })
3472
+ .ele('@wp', 'docPr')
3473
+ .att('id', pictureId)
3474
+ .att('name', pictureName)
3475
+ .up();
3476
+ const ɵ75 = buildDrawingObjectNonVisualProperties;
3477
+ const buildWrapSquare = () => fragment({ namespaceAlias: { wp: namespaces.wp } })
3478
+ .ele('@wp', 'wrapSquare')
3479
+ .att('wrapText', 'bothSides')
3480
+ .att('distB', '228600')
3481
+ .att('distT', '228600')
3482
+ .att('distL', '228600')
3483
+ .att('distR', '228600')
3484
+ .up();
3485
+ const ɵ76 = buildWrapSquare;
3486
+ // eslint-disable-next-line no-unused-vars
3487
+ const buildWrapNone = () => fragment({ namespaceAlias: { wp: namespaces.wp } })
3488
+ .ele('@wp', 'wrapNone')
3489
+ .up();
3490
+ const ɵ77 = buildWrapNone;
3491
+ const buildEffectExtentFragment = () => fragment({ namespaceAlias: { wp: namespaces.wp } })
3492
+ .ele('@wp', 'effectExtent')
3493
+ .att('b', '0')
3494
+ .att('l', '0')
3495
+ .att('r', '0')
3496
+ .att('t', '0')
3497
+ .up();
3498
+ const ɵ78 = buildEffectExtentFragment;
3499
+ const buildExtent = ({ width, height }) => fragment({ namespaceAlias: { wp: namespaces.wp } })
3500
+ .ele('@wp', 'extent')
3501
+ .att('cx', width)
3502
+ .att('cy', height)
3503
+ .up();
3504
+ const ɵ79 = buildExtent;
3505
+ const buildPositionV = () => fragment({ namespaceAlias: { wp: namespaces.wp } })
3506
+ .ele('@wp', 'positionV')
3507
+ .att('relativeFrom', 'paragraph')
3508
+ .ele('@wp', 'posOffset')
3509
+ .txt('19050')
3510
+ .up()
3511
+ .up();
3512
+ const ɵ80 = buildPositionV;
3513
+ const buildPositionH = () => fragment({ namespaceAlias: { wp: namespaces.wp } })
3514
+ .ele('@wp', 'positionH')
3515
+ .att('relativeFrom', 'column')
3516
+ .ele('@wp', 'posOffset')
3517
+ .txt('19050')
3518
+ .up()
3519
+ .up();
3520
+ const ɵ81 = buildPositionH;
3521
+ const buildSimplePos = () => fragment({ namespaceAlias: { wp: namespaces.wp } })
3522
+ .ele('@wp', 'simplePos')
3523
+ .att('x', '0')
3524
+ .att('y', '0')
3525
+ .up();
3526
+ const ɵ82 = buildSimplePos;
3527
+ const buildAnchoredDrawing = (graphicType, attributes) => {
3528
+ const anchoredDrawingFragment = fragment({ namespaceAlias: { wp: namespaces.wp } })
3529
+ .ele('@wp', 'anchor')
3530
+ .att('distB', '0')
3531
+ .att('distL', '0')
3532
+ .att('distR', '0')
3533
+ .att('distT', '0')
3534
+ .att('relativeHeight', '0')
3535
+ .att('behindDoc', 'false')
3536
+ .att('locked', 'true')
3537
+ .att('layoutInCell', 'true')
3538
+ .att('allowOverlap', 'false')
3539
+ .att('simplePos', 'false');
3540
+ // Even though simplePos isnt supported by Word 2007 simplePos is required.
3541
+ const simplePosFragment = buildSimplePos();
3542
+ anchoredDrawingFragment.import(simplePosFragment);
3543
+ const positionHFragment = buildPositionH();
3544
+ anchoredDrawingFragment.import(positionHFragment);
3545
+ const positionVFragment = buildPositionV();
3546
+ anchoredDrawingFragment.import(positionVFragment);
3547
+ const extentFragment = buildExtent({ width: attributes.width, height: attributes.height });
3548
+ anchoredDrawingFragment.import(extentFragment);
3549
+ const effectExtentFragment = buildEffectExtentFragment();
3550
+ anchoredDrawingFragment.import(effectExtentFragment);
3551
+ const wrapSquareFragment = buildWrapSquare();
3552
+ anchoredDrawingFragment.import(wrapSquareFragment);
3553
+ const drawingObjectNonVisualPropertiesFragment = buildDrawingObjectNonVisualProperties(attributes.id, attributes.fileNameWithExtension);
3554
+ anchoredDrawingFragment.import(drawingObjectNonVisualPropertiesFragment);
3555
+ const graphicFragment = buildGraphic(graphicType, attributes);
3556
+ anchoredDrawingFragment.import(graphicFragment);
3557
+ anchoredDrawingFragment.up();
3558
+ return anchoredDrawingFragment;
3559
+ };
3560
+ const ɵ83 = buildAnchoredDrawing;
3561
+ const buildInlineDrawing = (graphicType, attributes) => {
3562
+ const inlineDrawingFragment = fragment({ namespaceAlias: { wp: namespaces.wp } })
3563
+ .ele('@wp', 'inline')
3564
+ .att('distB', '0')
3565
+ .att('distL', '0')
3566
+ .att('distR', '0')
3567
+ .att('distT', '0');
3568
+ const extentFragment = buildExtent({ width: attributes.width, height: attributes.height });
3569
+ inlineDrawingFragment.import(extentFragment);
3570
+ const effectExtentFragment = buildEffectExtentFragment();
3571
+ inlineDrawingFragment.import(effectExtentFragment);
3572
+ const drawingObjectNonVisualPropertiesFragment = buildDrawingObjectNonVisualProperties(attributes.id, attributes.fileNameWithExtension);
3573
+ inlineDrawingFragment.import(drawingObjectNonVisualPropertiesFragment);
3574
+ const graphicFragment = buildGraphic(graphicType, attributes);
3575
+ inlineDrawingFragment.import(graphicFragment);
3576
+ inlineDrawingFragment.up();
3577
+ return inlineDrawingFragment;
3578
+ };
3579
+ const ɵ84 = buildInlineDrawing;
3580
+ const buildDrawing = (inlineOrAnchored = false, graphicType, attributes) => {
3581
+ const drawingFragment = fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'drawing');
3582
+ const inlineOrAnchoredDrawingFragment = inlineOrAnchored
3583
+ ? buildInlineDrawing(graphicType, attributes)
3584
+ : buildAnchoredDrawing(graphicType, attributes);
3585
+ drawingFragment.import(inlineOrAnchoredDrawingFragment);
3586
+ drawingFragment.up();
3587
+ return drawingFragment;
3588
+ };
3589
+ const ɵ85 = buildDrawing;
3590
+
3591
+ const convertHTML$1 = HTMLToVDOM({
3592
+ VNode,
3593
+ VText,
3594
+ });
3595
+ // eslint-disable-next-line consistent-return, no-shadow
3596
+ const buildImage = (docxDocumentInstance, vNode, maximumWidth = null) => __awaiter(void 0, void 0, void 0, function* () {
3597
+ let response = null;
3598
+ let base64Uri = null;
3599
+ try {
3600
+ const imageSource = vNode.properties.src;
3601
+ if (isValidUrl(imageSource)) {
3602
+ const base64String = yield imageToBase64(imageSource).catch((error) => {
3603
+ // eslint-disable-next-line no-console
3604
+ console.warning(`skipping image download and conversion due to ${error}`);
3605
+ });
3606
+ if (base64String) {
3607
+ base64Uri = `data:${mimeTypes.lookup(imageSource)};base64, ${base64String}`;
3608
+ }
3609
+ }
3610
+ else {
3611
+ base64Uri = decodeURIComponent(vNode.properties.src);
3612
+ }
3613
+ if (base64Uri) {
3614
+ response = docxDocumentInstance.createMediaFile(base64Uri);
3615
+ }
3616
+ }
3617
+ catch (error) {
3618
+ // NOOP
3619
+ }
3620
+ if (response) {
3621
+ docxDocumentInstance.zip
3622
+ .folder('word')
3623
+ .folder('media')
3624
+ .file(response.fileNameWithExtension, Buffer.from(response.fileContent, 'base64'), {
3625
+ createFolders: false,
3626
+ });
3627
+ const documentRelsId = docxDocumentInstance.createDocumentRelationships(docxDocumentInstance.relationshipFilename, imageType, `media/${response.fileNameWithExtension}`, internalRelationship);
3628
+ const imageBuffer = Buffer.from(response.fileContent, 'base64');
3629
+ const imageProperties = sizeOf(imageBuffer);
3630
+ const imageFragment = yield buildParagraph(vNode, Object.assign(Object.assign({ type: 'picture', inlineOrAnchored: true, relationshipId: documentRelsId }, response), { maximumWidth: maximumWidth || docxDocumentInstance.availableDocumentSpace, originalWidth: imageProperties.width, originalHeight: imageProperties.height }), docxDocumentInstance);
3631
+ return imageFragment;
3632
+ }
3633
+ });
3634
+ const buildList = (vNode, docxDocumentInstance, xmlFragment) => __awaiter(void 0, void 0, void 0, function* () {
3635
+ const listElements = [];
3636
+ let vNodeObjects = [
3637
+ {
3638
+ node: vNode,
3639
+ level: 0,
3640
+ type: vNode.tagName,
3641
+ numberingId: docxDocumentInstance.createNumbering(vNode.tagName, vNode.properties),
3642
+ },
3643
+ ];
3644
+ while (vNodeObjects.length) {
3645
+ const tempVNodeObject = vNodeObjects.shift();
3646
+ if (isVText(tempVNodeObject.node) ||
3647
+ (isVNode(tempVNodeObject.node) && !['ul', 'ol', 'li'].includes(tempVNodeObject.node.tagName))) {
3648
+ const paragraphFragment = yield buildParagraph(tempVNodeObject.node, {
3649
+ numbering: { levelId: tempVNodeObject.level, numberingId: tempVNodeObject.numberingId },
3650
+ }, docxDocumentInstance);
3651
+ xmlFragment.import(paragraphFragment);
3652
+ }
3653
+ if (tempVNodeObject.node.children &&
3654
+ tempVNodeObject.node.children.length &&
3655
+ ['ul', 'ol', 'li'].includes(tempVNodeObject.node.tagName)) {
3656
+ const tempVNodeObjects = tempVNodeObject.node.children.reduce((accumulator, childVNode) => {
3657
+ if (['ul', 'ol'].includes(childVNode.tagName)) {
3658
+ accumulator.push({
3659
+ node: childVNode,
3660
+ level: tempVNodeObject.level + 1,
3661
+ type: childVNode.tagName,
3662
+ numberingId: docxDocumentInstance.createNumbering(childVNode.tagName, childVNode.properties),
3663
+ });
3664
+ }
3665
+ else {
3666
+ // eslint-disable-next-line no-lonely-if
3667
+ if (accumulator.length > 0 &&
3668
+ isVNode(accumulator[accumulator.length - 1].node) &&
3669
+ accumulator[accumulator.length - 1].node.tagName.toLowerCase() === 'p') {
3670
+ accumulator[accumulator.length - 1].node.children.push(childVNode);
3671
+ }
3672
+ else {
3673
+ const paragraphVNode = new VNode('p', null,
3674
+ // eslint-disable-next-line no-nested-ternary
3675
+ isVText(childVNode)
3676
+ ? [childVNode]
3677
+ : // eslint-disable-next-line no-nested-ternary
3678
+ isVNode(childVNode)
3679
+ ? childVNode.tagName.toLowerCase() === 'li'
3680
+ ? [...childVNode.children]
3681
+ : [childVNode]
3682
+ : []);
3683
+ accumulator.push({
3684
+ // eslint-disable-next-line prettier/prettier, no-nested-ternary
3685
+ node: isVNode(childVNode)
3686
+ ? // eslint-disable-next-line prettier/prettier, no-nested-ternary
3687
+ childVNode.tagName.toLowerCase() === 'li'
3688
+ ? childVNode
3689
+ : childVNode.tagName.toLowerCase() !== 'p'
3690
+ ? paragraphVNode
3691
+ : childVNode
3692
+ : // eslint-disable-next-line prettier/prettier
3693
+ paragraphVNode,
3694
+ level: tempVNodeObject.level,
3695
+ type: tempVNodeObject.type,
3696
+ numberingId: tempVNodeObject.numberingId,
3697
+ });
3698
+ }
3699
+ }
3700
+ return accumulator;
3701
+ }, []);
3702
+ vNodeObjects = tempVNodeObjects.concat(vNodeObjects);
3703
+ }
3704
+ }
3705
+ return listElements;
3706
+ });
3707
+ function findXMLEquivalent(docxDocumentInstance, vNode, xmlFragment) {
3708
+ return __awaiter(this, void 0, void 0, function* () {
3709
+ if (vNode.tagName === 'div' &&
3710
+ (vNode.properties.attributes.class === 'page-break' ||
3711
+ (vNode.properties.style && vNode.properties.style['page-break-after']))) {
3712
+ const paragraphFragment = fragment({ namespaceAlias: { w: namespaces.w } })
3713
+ .ele('@w', 'p')
3714
+ .ele('@w', 'r')
3715
+ .ele('@w', 'br')
3716
+ .att('@w', 'type', 'page')
3717
+ .up()
3718
+ .up()
3719
+ .up();
3720
+ xmlFragment.import(paragraphFragment);
3721
+ return;
3722
+ }
3723
+ switch (vNode.tagName) {
3724
+ case 'h1':
3725
+ case 'h2':
3726
+ case 'h3':
3727
+ case 'h4':
3728
+ case 'h5':
3729
+ case 'h6':
3730
+ const headingFragment = yield buildParagraph(vNode, {
3731
+ paragraphStyle: `Heading${vNode.tagName[1]}`,
3732
+ }, docxDocumentInstance);
3733
+ xmlFragment.import(headingFragment);
3734
+ return;
3735
+ case 'span':
3736
+ case 'strong':
3737
+ case 'b':
3738
+ case 'em':
3739
+ case 'i':
3740
+ case 'u':
3741
+ case 'ins':
3742
+ case 'strike':
3743
+ case 'del':
3744
+ case 's':
3745
+ case 'sub':
3746
+ case 'sup':
3747
+ case 'mark':
3748
+ case 'p':
3749
+ case 'a':
3750
+ case 'blockquote':
3751
+ case 'code':
3752
+ case 'pre':
3753
+ const paragraphFragment = yield buildParagraph(vNode, {}, docxDocumentInstance);
3754
+ xmlFragment.import(paragraphFragment);
3755
+ return;
3756
+ case 'figure':
3757
+ if (vNodeHasChildren(vNode)) {
3758
+ // eslint-disable-next-line no-plusplus
3759
+ for (let index = 0; index < vNode.children.length; index++) {
3760
+ const childVNode = vNode.children[index];
3761
+ if (childVNode.tagName === 'table') {
3762
+ const tableFragment = yield buildTable(childVNode, {
3763
+ maximumWidth: docxDocumentInstance.availableDocumentSpace,
3764
+ rowCantSplit: docxDocumentInstance.tableRowCantSplit,
3765
+ }, docxDocumentInstance);
3766
+ xmlFragment.import(tableFragment);
3767
+ // Adding empty paragraph for space after table
3768
+ const emptyParagraphFragment = yield buildParagraph(null, {});
3769
+ xmlFragment.import(emptyParagraphFragment);
3770
+ }
3771
+ else if (childVNode.tagName === 'img') {
3772
+ const imageFragment = yield buildImage(docxDocumentInstance, childVNode);
3773
+ if (imageFragment) {
3774
+ xmlFragment.import(imageFragment);
3775
+ }
3776
+ }
3777
+ }
3778
+ }
3779
+ return;
3780
+ case 'table':
3781
+ const tableFragment = yield buildTable(vNode, {
3782
+ maximumWidth: docxDocumentInstance.availableDocumentSpace,
3783
+ rowCantSplit: docxDocumentInstance.tableRowCantSplit,
3784
+ }, docxDocumentInstance);
3785
+ xmlFragment.import(tableFragment);
3786
+ // Adding empty paragraph for space after table
3787
+ const emptyParagraphFragment = yield buildParagraph(null, {});
3788
+ xmlFragment.import(emptyParagraphFragment);
3789
+ return;
3790
+ case 'ol':
3791
+ case 'ul':
3792
+ yield buildList(vNode, docxDocumentInstance, xmlFragment);
3793
+ return;
3794
+ case 'img':
3795
+ const imageFragment = yield buildImage(docxDocumentInstance, vNode);
3796
+ if (imageFragment) {
3797
+ xmlFragment.import(imageFragment);
3798
+ }
3799
+ return;
3800
+ case 'br':
3801
+ const linebreakFragment = yield buildParagraph(null, {});
3802
+ xmlFragment.import(linebreakFragment);
3803
+ return;
3804
+ }
3805
+ if (vNodeHasChildren(vNode)) {
3806
+ // eslint-disable-next-line no-plusplus
3807
+ for (let index = 0; index < vNode.children.length; index++) {
3808
+ const childVNode = vNode.children[index];
3809
+ // eslint-disable-next-line no-use-before-define
3810
+ yield convertVTreeToXML(docxDocumentInstance, childVNode, xmlFragment);
3811
+ }
3812
+ }
3813
+ });
3814
+ }
3815
+ // eslint-disable-next-line consistent-return
3816
+ function convertVTreeToXML(docxDocumentInstance, vTree, xmlFragment) {
3817
+ return __awaiter(this, void 0, void 0, function* () {
3818
+ if (!vTree) {
3819
+ // eslint-disable-next-line no-useless-return
3820
+ return '';
3821
+ }
3822
+ if (Array.isArray(vTree) && vTree.length) {
3823
+ // eslint-disable-next-line no-plusplus
3824
+ for (let index = 0; index < vTree.length; index++) {
3825
+ const vNode = vTree[index];
3826
+ yield convertVTreeToXML(docxDocumentInstance, vNode, xmlFragment);
3827
+ }
3828
+ }
3829
+ else if (isVNode(vTree)) {
3830
+ yield findXMLEquivalent(docxDocumentInstance, vTree, xmlFragment);
3831
+ }
3832
+ else if (isVText(vTree)) {
3833
+ buildTextElement(xmlFragment, escape(String(vTree.text)));
3834
+ }
3835
+ return xmlFragment;
3836
+ });
3837
+ }
3838
+ function renderDocumentFile(docxDocumentInstance) {
3839
+ return __awaiter(this, void 0, void 0, function* () {
3840
+ const vTree = convertHTML$1(docxDocumentInstance.htmlString);
3841
+ const xmlFragment = fragment({ namespaceAlias: { w: namespaces.w } });
3842
+ const populatedXmlFragment = yield convertVTreeToXML(docxDocumentInstance, vTree, xmlFragment);
3843
+ return populatedXmlFragment;
3844
+ });
3845
+ }
3846
+
3847
+ /* eslint-disable import/prefer-default-export */
3848
+
3849
+ class ListStyleBuilder {
3850
+ // defaults is an object passed in from constants.js / numbering with the following properties:
3851
+ // defaultOrderedListStyleType: 'decimal' (unless otherwise specified)
3852
+ constructor(defaults) {
3853
+ this.defaults = defaults || { defaultOrderedListStyleType: 'decimal' };
3854
+ }
3855
+ // eslint-disable-next-line class-methods-use-this
3856
+ getListStyleType(listType) {
3857
+ switch (listType) {
3858
+ case 'upper-roman':
3859
+ return 'upperRoman';
3860
+ case 'lower-roman':
3861
+ return 'lowerRoman';
3862
+ case 'upper-alpha':
3863
+ case 'upper-alpha-bracket-end':
3864
+ return 'upperLetter';
3865
+ case 'lower-alpha':
3866
+ case 'lower-alpha-bracket-end':
3867
+ return 'lowerLetter';
3868
+ case 'decimal':
3869
+ case 'decimal-bracket':
3870
+ return 'decimal';
3871
+ default:
3872
+ return this.defaults.defaultOrderedListStyleType;
3873
+ }
3874
+ }
3875
+ getListPrefixSuffix(style, lvl) {
3876
+ let listType = this.defaults.defaultOrderedListStyleType;
3877
+ if (style && style['list-style-type']) {
3878
+ listType = style['list-style-type'];
3879
+ }
3880
+ switch (listType) {
3881
+ case 'upper-roman':
3882
+ case 'lower-roman':
3883
+ case 'upper-alpha':
3884
+ case 'lower-alpha':
3885
+ return `%${lvl + 1}.`;
3886
+ case 'upper-alpha-bracket-end':
3887
+ case 'lower-alpha-bracket-end':
3888
+ case 'decimal-bracket-end':
3889
+ return `%${lvl + 1})`;
3890
+ case 'decimal-bracket':
3891
+ return `(%${lvl + 1})`;
3892
+ case 'decimal':
3893
+ default:
3894
+ return `%${lvl + 1}.`;
3895
+ }
3896
+ }
3897
+ }
3898
+
3899
+ function generateContentTypesFragments(contentTypesXML, type, objects) {
3900
+ if (objects && Array.isArray(objects)) {
3901
+ objects.forEach((object) => {
3902
+ const contentTypesFragment = fragment({ defaultNamespace: { ele: namespaces.contentTypes } })
3903
+ .ele('Override')
3904
+ .att('PartName', `/word/${type}${object[`${type}Id`]}.xml`)
3905
+ .att('ContentType', `application/vnd.openxmlformats-officedocument.wordprocessingml.${type}+xml`)
3906
+ .up();
3907
+ contentTypesXML.root().import(contentTypesFragment);
3908
+ });
3909
+ }
3910
+ }
3911
+ function generateSectionReferenceXML(documentXML, documentSectionType, objects, isEnabled) {
3912
+ if (isEnabled && objects && Array.isArray(objects) && objects.length) {
3913
+ const xmlFragment = fragment();
3914
+ objects.forEach(({ relationshipId, type }) => {
3915
+ const objectFragment = fragment({ namespaceAlias: { w: namespaces.w, r: namespaces.r } })
3916
+ .ele('@w', `${documentSectionType}Reference`)
3917
+ .att('@r', 'id', `rId${relationshipId}`)
3918
+ .att('@w', 'type', type)
3919
+ .up();
3920
+ xmlFragment.import(objectFragment);
3921
+ });
3922
+ documentXML.root().first().first().import(xmlFragment);
3923
+ }
3924
+ }
3925
+ function generateXMLString(xmlString) {
3926
+ const xmlDocumentString = create({ encoding: 'UTF-8', standalone: true }, xmlString);
3927
+ return xmlDocumentString.toString({ prettyPrint: true });
3928
+ }
3929
+ function generateSectionXML(vTree, type = 'header') {
3930
+ return __awaiter(this, void 0, void 0, function* () {
3931
+ debugger;
3932
+ const sectionXML = create({
3933
+ encoding: 'UTF-8',
3934
+ standalone: true,
3935
+ namespaceAlias: {
3936
+ a: namespaces.a,
3937
+ cdr: namespaces.cdr,
3938
+ o: namespaces.o,
3939
+ pic: namespaces.pic,
3940
+ r: namespaces.r,
3941
+ v: namespaces.v,
3942
+ ve: namespaces.ve,
3943
+ vt: namespaces.vt,
3944
+ w: namespaces.w,
3945
+ w10: namespaces.w10,
3946
+ wp: namespaces.wp,
3947
+ wne: namespaces.wne
3948
+ },
3949
+ }).ele('@w', type === 'header' ? 'hdr' : 'ftr');
3950
+ const XMLFragment = fragment();
3951
+ yield convertVTreeToXML(this, vTree, XMLFragment);
3952
+ if (type === 'footer' && XMLFragment.first().node.tagName === 'p' && this.pageNumber) {
3953
+ XMLFragment.first().import(fragment({ namespaceAlias: { w: namespaces.w } })
3954
+ .ele('@w', 'fldSimple')
3955
+ .att('@w', 'instr', 'PAGE')
3956
+ .ele('@w', 'r')
3957
+ .up()
3958
+ .up());
3959
+ }
3960
+ sectionXML.root().import(XMLFragment);
3961
+ const referenceName = type === 'header' ? 'Header' : 'Footer';
3962
+ this[`last${referenceName}Id`] += 1;
3963
+ return { [`${type}Id`]: this[`last${referenceName}Id`], [`${type}XML`]: sectionXML };
3964
+ });
3965
+ }
3966
+ class DocxDocument {
3967
+ constructor(properties) {
3968
+ this.zip = properties.zip;
3969
+ this.htmlString = properties.htmlString;
3970
+ this.orientation = properties.orientation;
3971
+ this.pageSize = properties.pageSize || defaultDocumentOptions.pageSize;
3972
+ const isPortraitOrientation = this.orientation === defaultOrientation;
3973
+ const height = this.pageSize.height ? this.pageSize.height : landscapeHeight;
3974
+ const width = this.pageSize.width ? this.pageSize.width : landscapeWidth;
3975
+ this.width = isPortraitOrientation ? width : height;
3976
+ this.height = isPortraitOrientation ? height : width;
3977
+ const marginsObject = properties.margins;
3978
+ this.margins =
3979
+ // eslint-disable-next-line no-nested-ternary
3980
+ marginsObject && Object.keys(marginsObject).length
3981
+ ? marginsObject
3982
+ : isPortraitOrientation
3983
+ ? portraitMargins
3984
+ : landscapeMargins;
3985
+ this.availableDocumentSpace = this.width - this.margins.left - this.margins.right;
3986
+ this.title = properties.title || '';
3987
+ this.subject = properties.subject || '';
3988
+ this.creator = properties.creator || applicationName;
3989
+ this.keywords = properties.keywords || [applicationName];
3990
+ this.description = properties.description || '';
3991
+ this.lastModifiedBy = properties.lastModifiedBy || applicationName;
3992
+ this.revision = properties.revision || 1;
3993
+ this.createdAt = properties.createdAt || new Date();
3994
+ this.modifiedAt = properties.modifiedAt || new Date();
3995
+ this.headerType = properties.headerType || 'default';
3996
+ this.header = properties.header || false;
3997
+ this.footerType = properties.footerType || 'default';
3998
+ this.footer = properties.footer || false;
3999
+ this.font = properties.font || defaultFont;
4000
+ this.fontSize = properties.fontSize || defaultFontSize;
4001
+ this.complexScriptFontSize = properties.complexScriptFontSize || defaultFontSize;
4002
+ this.tableRowCantSplit =
4003
+ (properties.table && properties.table.row && properties.table.row.cantSplit) || false;
4004
+ this.pageNumber = properties.pageNumber || false;
4005
+ this.skipFirstHeaderFooter = properties.skipFirstHeaderFooter || false;
4006
+ this.lineNumber = properties.lineNumber ? properties.lineNumberOptions : null;
4007
+ this.lastNumberingId = 0;
4008
+ this.lastMediaId = 0;
4009
+ this.lastHeaderId = 0;
4010
+ this.lastFooterId = 0;
4011
+ this.stylesObjects = [];
4012
+ this.numberingObjects = [];
4013
+ this.relationshipFilename = documentFileName;
4014
+ this.relationships = [{ fileName: documentFileName, lastRelsId: 4, rels: [] }];
4015
+ this.mediaFiles = [];
4016
+ this.headerObjects = [];
4017
+ this.footerObjects = [];
4018
+ this.documentXML = null;
4019
+ this.generateContentTypesXML = this.generateContentTypesXML.bind(this);
4020
+ this.generateDocumentXML = this.generateDocumentXML.bind(this);
4021
+ this.generateCoreXML = this.generateCoreXML.bind(this);
4022
+ this.generateSettingsXML = this.generateSettingsXML.bind(this);
4023
+ this.generateWebSettingsXML = this.generateWebSettingsXML.bind(this);
4024
+ this.generateStylesXML = this.generateStylesXML.bind(this);
4025
+ this.generateFontTableXML = this.generateFontTableXML.bind(this);
4026
+ this.generateThemeXML = this.generateThemeXML.bind(this);
4027
+ this.generateNumberingXML = this.generateNumberingXML.bind(this);
4028
+ this.generateRelsXML = this.generateRelsXML.bind(this);
4029
+ this.createMediaFile = this.createMediaFile.bind(this);
4030
+ this.createDocumentRelationships = this.createDocumentRelationships.bind(this);
4031
+ this.generateHeaderXML = this.generateHeaderXML.bind(this);
4032
+ this.generateFooterXML = this.generateFooterXML.bind(this);
4033
+ this.generateSectionXML = generateSectionXML.bind(this);
4034
+ this.ListStyleBuilder = new ListStyleBuilder(properties.numbering);
4035
+ }
4036
+ generateContentTypesXML() {
4037
+ const contentTypesXML$1 = create({ encoding: 'UTF-8', standalone: true }, contentTypesXML);
4038
+ generateContentTypesFragments(contentTypesXML$1, 'header', this.headerObjects);
4039
+ generateContentTypesFragments(contentTypesXML$1, 'footer', this.footerObjects);
4040
+ return contentTypesXML$1.toString({ prettyPrint: true });
4041
+ }
4042
+ generateDocumentXML() {
4043
+ const documentXML = create({ encoding: 'UTF-8', standalone: true }, generateDocumentTemplate(this.width, this.height, this.orientation, this.margins));
4044
+ // documentXML.root().first().import(this.documentXML);
4045
+ generateSectionReferenceXML(documentXML, 'header', this.headerObjects, this.header);
4046
+ generateSectionReferenceXML(documentXML, 'footer', this.footerObjects, this.footer);
4047
+ if ((this.header || this.footer) && this.skipFirstHeaderFooter) {
4048
+ documentXML
4049
+ .root()
4050
+ .first()
4051
+ .first()
4052
+ .import(fragment({ namespaceAlias: { w: namespaces.w } }).ele('@w', 'titlePg'));
4053
+ }
4054
+ if (this.lineNumber) {
4055
+ const { countBy, start, restart } = this.lineNumber;
4056
+ documentXML
4057
+ .root()
4058
+ .first()
4059
+ .first()
4060
+ .import(fragment({ namespaceAlias: { w: namespaces.w } })
4061
+ .ele('@w', 'lnNumType')
4062
+ .att('@w', 'countBy', countBy)
4063
+ .att('@w', 'start', start)
4064
+ .att('@w', 'restart', restart));
4065
+ }
4066
+ return documentXML.toString({ prettyPrint: true });
4067
+ }
4068
+ generateCoreXML() {
4069
+ return generateXMLString(generateCoreXML(this.title, this.subject, this.creator, this.keywords, this.description, this.lastModifiedBy, this.revision, this.createdAt, this.modifiedAt));
4070
+ }
4071
+ // eslint-disable-next-line class-methods-use-this
4072
+ generateSettingsXML() {
4073
+ return generateXMLString(settingsXML);
4074
+ }
4075
+ // eslint-disable-next-line class-methods-use-this
4076
+ generateWebSettingsXML() {
4077
+ return generateXMLString(webSettingsXML);
4078
+ }
4079
+ generateStylesXML() {
4080
+ return generateXMLString(generateStylesXML(this.font, this.fontSize, this.complexScriptFontSize));
4081
+ }
4082
+ // eslint-disable-next-line class-methods-use-this
4083
+ generateFontTableXML() {
4084
+ return generateXMLString(fontTableXML);
4085
+ }
4086
+ generateThemeXML() {
4087
+ return generateXMLString(generateThemeXML(this.font));
4088
+ }
4089
+ generateNumberingXML() {
4090
+ const numberingXML = create({ encoding: 'UTF-8', standalone: true }, generateNumberingXMLTemplate());
4091
+ const abstractNumberingFragments = fragment();
4092
+ const numberingFragments = fragment();
4093
+ this.numberingObjects.forEach(({ numberingId, type, properties }) => {
4094
+ const abstractNumberingFragment = fragment({ namespaceAlias: { w: namespaces.w } })
4095
+ .ele('@w', 'abstractNum')
4096
+ .att('@w', 'abstractNumId', String(numberingId));
4097
+ [...Array(8).keys()].forEach((level) => {
4098
+ const levelFragment = fragment({ namespaceAlias: { w: namespaces.w } })
4099
+ .ele('@w', 'lvl')
4100
+ .att('@w', 'ilvl', level)
4101
+ .ele('@w', 'start')
4102
+ .att('@w', 'val', type === 'ol'
4103
+ ? (properties.attributes && properties.attributes['data-start']) || 1
4104
+ : '1')
4105
+ .up()
4106
+ .ele('@w', 'numFmt')
4107
+ .att('@w', 'val', type === 'ol'
4108
+ ? this.ListStyleBuilder.getListStyleType(properties.style && properties.style['list-style-type'])
4109
+ : 'bullet')
4110
+ .up()
4111
+ .ele('@w', 'lvlText')
4112
+ .att('@w', 'val', type === 'ol' ? this.ListStyleBuilder.getListPrefixSuffix(properties.style, level) : '')
4113
+ .up()
4114
+ .ele('@w', 'lvlJc')
4115
+ .att('@w', 'val', 'left')
4116
+ .up()
4117
+ .ele('@w', 'pPr')
4118
+ .ele('@w', 'tabs')
4119
+ .ele('@w', 'tab')
4120
+ .att('@w', 'val', 'num')
4121
+ .att('@w', 'pos', (level + 1) * 720)
4122
+ .up()
4123
+ .up()
4124
+ .ele('@w', 'ind')
4125
+ .att('@w', 'left', (level + 1) * 720)
4126
+ .att('@w', 'hanging', 360)
4127
+ .up()
4128
+ .up()
4129
+ .up();
4130
+ if (type === 'ul') {
4131
+ levelFragment.last().import(fragment({ namespaceAlias: { w: namespaces.w } })
4132
+ .ele('@w', 'rPr')
4133
+ .ele('@w', 'rFonts')
4134
+ .att('@w', 'ascii', 'Symbol')
4135
+ .att('@w', 'hAnsi', 'Symbol')
4136
+ .att('@w', 'hint', 'default')
4137
+ .up()
4138
+ .up());
4139
+ }
4140
+ abstractNumberingFragment.import(levelFragment);
4141
+ });
4142
+ abstractNumberingFragment.up();
4143
+ abstractNumberingFragments.import(abstractNumberingFragment);
4144
+ numberingFragments.import(fragment({ namespaceAlias: { w: namespaces.w } })
4145
+ .ele('@w', 'num')
4146
+ .att('@w', 'numId', String(numberingId))
4147
+ .ele('@w', 'abstractNumId')
4148
+ .att('@w', 'val', String(numberingId))
4149
+ .up()
4150
+ .up());
4151
+ });
4152
+ numberingXML.root().import(abstractNumberingFragments);
4153
+ numberingXML.root().import(numberingFragments);
4154
+ return numberingXML.toString({ prettyPrint: true });
4155
+ }
4156
+ // eslint-disable-next-line class-methods-use-this
4157
+ appendRelationships(xmlFragment, relationships) {
4158
+ relationships.forEach(({ relationshipId, type, target, targetMode }) => {
4159
+ xmlFragment.import(fragment({ defaultNamespace: { ele: namespaces.relationship } })
4160
+ .ele('Relationship')
4161
+ .att('Id', `rId${relationshipId}`)
4162
+ .att('Type', type)
4163
+ .att('Target', target)
4164
+ .att('TargetMode', targetMode)
4165
+ .up());
4166
+ });
4167
+ }
4168
+ generateRelsXML() {
4169
+ const relationshipXMLStrings = this.relationships.map(({ fileName, rels }) => {
4170
+ const xmlFragment = create({ encoding: 'UTF-8', standalone: true }, fileName === documentFileName ? documentRelsXML : genericRelsXML);
4171
+ this.appendRelationships(xmlFragment.root(), rels);
4172
+ return { fileName, xmlString: xmlFragment.toString({ prettyPrint: true }) };
4173
+ });
4174
+ return relationshipXMLStrings;
4175
+ }
4176
+ createNumbering(type, properties) {
4177
+ this.lastNumberingId += 1;
4178
+ this.numberingObjects.push({ numberingId: this.lastNumberingId, type, properties });
4179
+ return this.lastNumberingId;
4180
+ }
4181
+ createMediaFile(base64String) {
4182
+ // eslint-disable-next-line no-useless-escape
4183
+ const matches = base64String.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/);
4184
+ if (matches.length !== 3) {
4185
+ throw new Error('Invalid base64 string');
4186
+ }
4187
+ const base64FileContent = matches[2];
4188
+ // matches array contains file type in base64 format - image/jpeg and base64 stringified data
4189
+ const fileExtension = matches[1].match(/\/(.*?)$/)[1] === 'octet-stream' ? 'png' : matches[1].match(/\/(.*?)$/)[1];
4190
+ const fileNameWithExtension = `image-${nanoid()}.${fileExtension}`;
4191
+ this.lastMediaId += 1;
4192
+ return { id: this.lastMediaId, fileContent: base64FileContent, fileNameWithExtension };
4193
+ }
4194
+ createDocumentRelationships(fileName = 'document', type, target, targetMode = 'External') {
4195
+ debugger;
4196
+ let relationshipObject = this.relationships.find((relationship) => relationship.fileName === fileName);
4197
+ let lastRelsId = 1;
4198
+ if (relationshipObject) {
4199
+ lastRelsId = relationshipObject.lastRelsId + 1;
4200
+ relationshipObject.lastRelsId = lastRelsId;
4201
+ }
4202
+ else {
4203
+ relationshipObject = { fileName, lastRelsId, rels: [] };
4204
+ this.relationships.push(relationshipObject);
4205
+ }
4206
+ let relationshipType;
4207
+ switch (type) {
4208
+ case hyperlinkType:
4209
+ relationshipType = namespaces.hyperlinks;
4210
+ break;
4211
+ case imageType:
4212
+ relationshipType = namespaces.images;
4213
+ break;
4214
+ case headerType:
4215
+ relationshipType = namespaces.headers;
4216
+ break;
4217
+ case footerType:
4218
+ relationshipType = namespaces.footers;
4219
+ break;
4220
+ case themeType:
4221
+ relationshipType = namespaces.themes;
4222
+ break;
4223
+ }
4224
+ relationshipObject.rels.push({
4225
+ relationshipId: lastRelsId,
4226
+ type: relationshipType,
4227
+ target,
4228
+ targetMode,
4229
+ });
4230
+ console.log(fileName);
4231
+ console.log(relationshipObject.rels);
4232
+ return lastRelsId;
4233
+ }
4234
+ generateHeaderXML(vTree) {
4235
+ return this.generateSectionXML(vTree, 'header');
4236
+ }
4237
+ generateFooterXML(vTree) {
4238
+ return this.generateSectionXML(vTree, 'footer');
4239
+ }
4240
+ }
4241
+
4242
+ const defaultMargins = {
4243
+ top: 1440,
4244
+ right: 1440,
4245
+ bottom: 1440,
4246
+ left: 1440,
4247
+ header: 720,
4248
+ footer: 720,
4249
+ gutter: 0,
4250
+ };
4251
+ const documentTemplate = (width, height, orient, margins) => {
4252
+ return `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
4253
+ <w:document
4254
+ xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"
4255
+ xmlns:m="http://schemas.openxmlformats.org/officeDocument/2006/math"
4256
+ xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"
4257
+ xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"
4258
+ xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"
4259
+ xmlns:ns6="http://schemas.openxmlformats.org/schemaLibrary/2006/main"
4260
+ xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart"
4261
+ xmlns:ns8="http://schemas.openxmlformats.org/drawingml/2006/chartDrawing"
4262
+ xmlns:dgm="http://schemas.openxmlformats.org/drawingml/2006/diagram"
4263
+ xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"
4264
+ xmlns:ns11="http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing"
4265
+ xmlns:dsp="http://schemas.microsoft.com/office/drawing/2008/diagram"
4266
+ xmlns:ns13="urn:schemas-microsoft-com:office:excel"
4267
+ xmlns:o="urn:schemas-microsoft-com:office:office"
4268
+ xmlns:v="urn:schemas-microsoft-com:vml"
4269
+ xmlns:w10="urn:schemas-microsoft-com:office:word"
4270
+ xmlns:ns17="urn:schemas-microsoft-com:office:powerpoint"
4271
+ xmlns:odx="http://opendope.org/xpaths"
4272
+ xmlns:odc="http://opendope.org/conditions"
4273
+ xmlns:odq="http://opendope.org/questions"
4274
+ xmlns:odi="http://opendope.org/components"
4275
+ xmlns:odgm="http://opendope.org/SmartArt/DataHierarchy"
4276
+ xmlns:ns24="http://schemas.openxmlformats.org/officeDocument/2006/bibliography"
4277
+ xmlns:ns25="http://schemas.openxmlformats.org/drawingml/2006/compatibility"
4278
+ xmlns:ns26="http://schemas.openxmlformats.org/drawingml/2006/lockedCanvas">
4279
+ <w:body>
4280
+ <w:altChunk r:id="htmlChunk" />
4281
+ <w:sectPr>
4282
+ <w:pgSz w:w="${width}" w:h="${height}" w:orient="${orient}" />
4283
+ <w:pgMar w:top="${margins.top}"
4284
+ w:right="${margins.right}"
4285
+ w:bottom="${margins.bottom}"
4286
+ w:left="${margins.left}"
4287
+ w:header="${margins.header}"
4288
+ w:footer="${margins.footer}"
4289
+ w:gutter="${margins.gutter}"/>
4290
+ </w:sectPr>
4291
+ </w:body>
4292
+ </w:document>
4293
+ `;
4294
+ };
4295
+
4296
+ const mhtDocumentTemplate = (htmlSource, contentParts) => {
4297
+ debugger;
4298
+ return `MIME-Version: 1.0
4299
+ Content-Type: multipart/related;
4300
+ type="text/html";
4301
+ boundary="----=mhtDocumentPart"
4302
+
4303
+
4304
+ ------=mhtDocumentPart
4305
+ Content-Type: text/html;
4306
+ charset="utf-8"
4307
+ Content-Transfer-Encoding: quoted-printable
4308
+ Content-Location: file:///C:/fake/document.html
4309
+
4310
+ ${htmlSource}
4311
+
4312
+ ${contentParts}
4313
+
4314
+ ------=mhtDocumentPart--
4315
+ `;
4316
+ };
4317
+
4318
+ const mhtPartTemplate = (contentType, contentEncoding, contentLocation, encodedContent) => {
4319
+ return `------=mhtDocumentPart
4320
+ Content-Type: ${contentType}
4321
+ Content-Transfer-Encoding: ${contentEncoding}
4322
+ Content-Location: ${contentLocation}
4323
+
4324
+ ${encodedContent}
4325
+ `;
4326
+ };
4327
+
4328
+ function getMHTdocument(htmlSource) {
4329
+ debugger;
4330
+ const ref = _prepareImageParts(htmlSource);
4331
+ const imageContentPartsString = ref.imageContentParts.join('\n');
4332
+ htmlSource = ref.htmlSource.replace(/\=/g, '=3D');
4333
+ return mhtDocumentTemplate(htmlSource, imageContentPartsString);
4334
+ }
4335
+ function _prepareImageParts(htmlSource) {
4336
+ debugger;
4337
+ const imageContentParts = [];
4338
+ const inlinedSrcPattern = /"data:(\w+\/\w+);(\w+),(\S+)"/g;
4339
+ const inlinedReplacer = (match, contentType, contentEncoding, encodedContent) => {
4340
+ const index = imageContentParts.length;
4341
+ const extension = contentType.split('/')[1];
4342
+ const contentLocation = `file:///C:/fake/image${index}.${extension}`;
4343
+ imageContentParts.push(mhtPartTemplate(contentType, contentEncoding, contentLocation, encodedContent));
4344
+ return `\"${contentLocation}\"`;
4345
+ };
4346
+ if (!/<img/g.test(htmlSource)) {
4347
+ return { htmlSource, imageContentParts };
4348
+ }
4349
+ htmlSource = htmlSource.replace(inlinedSrcPattern, inlinedReplacer);
4350
+ return { htmlSource, imageContentParts };
4351
+ }
4352
+
4353
+ const convertHTML = HTMLToVDOM({
4354
+ VNode,
4355
+ VText,
4356
+ });
4357
+ const mergeOptions = (options, patch) => (Object.assign(Object.assign({}, options), patch));
4358
+ const ɵ0$1 = mergeOptions;
4359
+ const fixupFontSize = (fontSize) => {
4360
+ let normalizedFontSize;
4361
+ if (pointRegex.test(fontSize)) {
4362
+ const matchedParts = fontSize.match(pointRegex);
4363
+ normalizedFontSize = pointToHIP(matchedParts[1]);
4364
+ }
4365
+ else if (fontSize) {
4366
+ // assuming it is already in HIP
4367
+ normalizedFontSize = fontSize;
4368
+ }
4369
+ else {
4370
+ normalizedFontSize = null;
4371
+ }
4372
+ return normalizedFontSize;
4373
+ };
4374
+ const ɵ1 = fixupFontSize;
4375
+ const normalizeUnits = (dimensioningObject, defaultDimensionsProperty) => {
4376
+ let normalizedUnitResult = {};
4377
+ if (typeof dimensioningObject === 'object' && dimensioningObject !== null) {
4378
+ Object.keys(dimensioningObject).forEach((key) => {
4379
+ if (pixelRegex.test(dimensioningObject[key])) {
4380
+ const matchedParts = dimensioningObject[key].match(pixelRegex);
4381
+ normalizedUnitResult[key] = pixelToTWIP(matchedParts[1]);
4382
+ }
4383
+ else if (cmRegex.test(dimensioningObject[key])) {
4384
+ const matchedParts = dimensioningObject[key].match(cmRegex);
4385
+ normalizedUnitResult[key] = cmToTWIP(matchedParts[1]);
4386
+ }
4387
+ else if (inchRegex.test(dimensioningObject[key])) {
4388
+ const matchedParts = dimensioningObject[key].match(inchRegex);
4389
+ normalizedUnitResult[key] = inchToTWIP(matchedParts[1]);
4390
+ }
4391
+ else if (dimensioningObject[key]) {
4392
+ normalizedUnitResult[key] = dimensioningObject[key];
4393
+ }
4394
+ else {
4395
+ // incase value is something like 0
4396
+ normalizedUnitResult[key] = defaultDimensionsProperty[key];
4397
+ }
4398
+ });
4399
+ }
4400
+ else {
4401
+ // eslint-disable-next-line no-param-reassign
4402
+ normalizedUnitResult = null;
4403
+ }
4404
+ return normalizedUnitResult;
4405
+ };
4406
+ const ɵ2 = normalizeUnits;
4407
+ const normalizeDocumentOptions = (documentOptions) => {
4408
+ const normalizedDocumentOptions = Object.assign({}, documentOptions);
4409
+ Object.keys(documentOptions).forEach((key) => {
4410
+ // eslint-disable-next-line default-case
4411
+ switch (key) {
4412
+ case 'pageSize':
4413
+ case 'margins':
4414
+ normalizedDocumentOptions[key] = normalizeUnits(documentOptions[key], defaultDocumentOptions[key]);
4415
+ break;
4416
+ case 'fontSize':
4417
+ case 'complexScriptFontSize':
4418
+ normalizedDocumentOptions[key] = fixupFontSize(documentOptions[key]);
4419
+ break;
4420
+ }
4421
+ });
4422
+ return normalizedDocumentOptions;
4423
+ };
4424
+ const ɵ3 = normalizeDocumentOptions;
4425
+ // Ref: https://en.wikipedia.org/wiki/Office_Open_XML_file_formats
4426
+ // http://officeopenxml.com/anatomyofOOXML.php
4427
+ function addFilesToContainer(zip, htmlString, suppliedDocumentOptions, headerHTMLString, footerHTMLString) {
4428
+ return __awaiter(this, void 0, void 0, function* () {
4429
+ debugger;
4430
+ const normalizedDocumentOptions = normalizeDocumentOptions(suppliedDocumentOptions);
4431
+ const documentOptions = mergeOptions(defaultDocumentOptions, normalizedDocumentOptions);
4432
+ if (documentOptions.header && !headerHTMLString) {
4433
+ // eslint-disable-next-line no-param-reassign
4434
+ headerHTMLString = defaultHTMLString;
4435
+ }
4436
+ if (documentOptions.footer && !footerHTMLString) {
4437
+ // eslint-disable-next-line no-param-reassign
4438
+ footerHTMLString = defaultHTMLString;
4439
+ }
4440
+ const docxDocument = new DocxDocument(Object.assign({ zip, htmlString }, documentOptions));
4441
+ // Conversion to Word XML happens here
4442
+ docxDocument.documentXML = yield renderDocumentFile(docxDocument);
4443
+ debugger;
4444
+ zip
4445
+ .folder(relsFolderName)
4446
+ .file('.rels', create({ encoding: 'UTF-8', standalone: true }, relsXML).toString({ prettyPrint: true }), { createFolders: false });
4447
+ zip.folder('docProps').file('core.xml', docxDocument.generateCoreXML(), {
4448
+ createFolders: false,
4449
+ });
4450
+ if (docxDocument.header && headerHTMLString) {
4451
+ const vTree = convertHTML(headerHTMLString);
4452
+ docxDocument.relationshipFilename = headerFileName;
4453
+ const { headerId, headerXML } = yield docxDocument.generateHeaderXML(vTree);
4454
+ docxDocument.relationshipFilename = documentFileName;
4455
+ const fileNameWithExt = `${headerType}${headerId}.xml`;
4456
+ const relationshipId = docxDocument.createDocumentRelationships(docxDocument.relationshipFilename, headerType, fileNameWithExt, internalRelationship);
4457
+ zip.folder(wordFolder).file(fileNameWithExt, generateDocumentTemplateHeader.toString({ prettyPrint: true }), {
4458
+ createFolders: false,
4459
+ });
4460
+ docxDocument.headerObjects.push({ headerId, relationshipId, type: docxDocument.headerType });
4461
+ }
4462
+ if (docxDocument.footer && footerHTMLString) {
4463
+ const vTree = convertHTML(footerHTMLString);
4464
+ docxDocument.relationshipFilename = footerFileName;
4465
+ const { footerId, footerXML } = yield docxDocument.generateFooterXML(vTree);
4466
+ docxDocument.relationshipFilename = documentFileName;
4467
+ const fileNameWithExt = `${footerType}${footerId}.xml`;
4468
+ const relationshipId = docxDocument.createDocumentRelationships(docxDocument.relationshipFilename, footerType, fileNameWithExt, internalRelationship);
4469
+ console.log(footerXML.toString({ prettyPrint: true }));
4470
+ if (suppliedDocumentOptions.pageNumber)
4471
+ zip.folder(wordFolder).file(fileNameWithExt, generateDocumentTemplateFooter.toString({ prettyPrint: true }), {
4472
+ createFolders: false,
4473
+ });
4474
+ else
4475
+ zip.folder(wordFolder).file(fileNameWithExt, generateDocumentTemplateFooterWithoutPaging.toString({ prettyPrint: true }), {
4476
+ createFolders: false,
4477
+ });
4478
+ docxDocument.footerObjects.push({ footerId, relationshipId, type: docxDocument.footerType });
4479
+ }
4480
+ const themeFileNameWithExt = `${themeFileName}.xml`;
4481
+ docxDocument.createDocumentRelationships(docxDocument.relationshipFilename, themeType, `${themeFolder}/${themeFileNameWithExt}`, internalRelationship);
4482
+ zip
4483
+ .folder(wordFolder)
4484
+ .folder(themeFolder)
4485
+ .file(themeFileNameWithExt, docxDocument.generateThemeXML(), {
4486
+ createFolders: false,
4487
+ });
4488
+ zip
4489
+ .folder(wordFolder)
4490
+ .file('document.xml', docxDocument.generateDocumentXML(), { createFolders: false })
4491
+ .file('afchunk.mht', getMHTdocument(htmlString), {
4492
+ createFolders: false,
4493
+ })
4494
+ .file('afchunkheader.mht', getMHTdocument(headerHTMLString), {
4495
+ createFolders: false,
4496
+ })
4497
+ .file('afchunkfooter.mht', getMHTdocument(footerHTMLString), {
4498
+ createFolders: false,
4499
+ })
4500
+ .file('fontTable.xml', docxDocument.generateFontTableXML(), { createFolders: false })
4501
+ .file('styles.xml', docxDocument.generateStylesXML(), { createFolders: false })
4502
+ .file('numbering.xml', docxDocument.generateNumberingXML(), { createFolders: false })
4503
+ .file('settings.xml', docxDocument.generateSettingsXML(), { createFolders: false })
4504
+ .file('webSettings.xml', docxDocument.generateWebSettingsXML(), { createFolders: false });
4505
+ const relationshipXMLs = docxDocument.generateRelsXML();
4506
+ if (relationshipXMLs && Array.isArray(relationshipXMLs)) {
4507
+ relationshipXMLs.forEach(({ fileName, xmlString }) => {
4508
+ console.log(xmlString);
4509
+ zip.folder(wordFolder).folder(relsFolderName).file(`${fileName}.xml.rels`, xmlString, {
4510
+ createFolders: false,
4511
+ });
4512
+ });
4513
+ }
4514
+ if (relationshipXMLs && Array.isArray(relationshipXMLs)) {
4515
+ relationshipXMLs.forEach(({ fileName, xmlString }) => {
4516
+ zip.folder(wordFolder).folder(relsFolderName).file(`header1.xml.rels`, xmlString, {
4517
+ createFolders: false,
4518
+ });
4519
+ });
4520
+ }
4521
+ if (relationshipXMLs && Array.isArray(relationshipXMLs)) {
4522
+ relationshipXMLs.forEach(({ fileName, xmlString }) => {
4523
+ zip.folder(wordFolder).folder(relsFolderName).file(`footer1.xml.rels`, xmlString, {
4524
+ createFolders: false,
4525
+ });
4526
+ });
4527
+ }
4528
+ zip.file('[Content_Types].xml', docxDocument.generateContentTypesXML(), { createFolders: false });
4529
+ return zip;
4530
+ });
4531
+ }
4532
+
4533
+ const minifyHTMLString = (htmlString) => {
4534
+ try {
4535
+ if (typeof htmlString === 'string' || htmlString instanceof String) {
4536
+ const minifiedHTMLString = htmlString
4537
+ .replace(/\n/g, ' ')
4538
+ .replace(/\r/g, ' ')
4539
+ .replace(/\r\n/g, ' ')
4540
+ .replace(/[\t]+\</g, '<')
4541
+ .replace(/\>[\t ]+\</g, '><')
4542
+ .replace(/\>[\t ]+$/g, '>');
4543
+ return minifiedHTMLString;
4544
+ }
4545
+ throw new Error('invalid html string');
4546
+ }
4547
+ catch (error) {
4548
+ return null;
4549
+ }
4550
+ };
4551
+ const ɵ0 = minifyHTMLString;
4552
+ function generateContainer(htmlString, headerHTMLString, documentOptions = {}, footerHTMLString) {
4553
+ return __awaiter(this, void 0, void 0, function* () {
4554
+ const zip = new JSZip();
4555
+ let contentHTML = htmlString;
4556
+ let headerHTML = headerHTMLString;
4557
+ let footerHTML = footerHTMLString;
4558
+ if (htmlString) {
4559
+ contentHTML = minifyHTMLString(contentHTML);
4560
+ }
4561
+ if (headerHTMLString) {
4562
+ headerHTML = minifyHTMLString(headerHTML);
4563
+ }
4564
+ if (footerHTMLString) {
4565
+ footerHTML = minifyHTMLString(footerHTML);
4566
+ }
4567
+ yield addFilesToContainer(zip, contentHTML, documentOptions, headerHTML, footerHTML);
4568
+ const buffer = yield zip.generateAsync({ type: 'arraybuffer' });
4569
+ if (Object.prototype.hasOwnProperty.call(global, 'Buffer')) {
4570
+ return Buffer.from(new Uint8Array(buffer));
4571
+ }
4572
+ if (Object.prototype.hasOwnProperty.call(global, 'Blob')) {
4573
+ // eslint-disable-next-line no-undef
4574
+ return new Blob([buffer], {
4575
+ type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
4576
+ });
4577
+ }
4578
+ throw new Error('Add blob support using a polyfill eg https://github.com/bjornstar/blob-polyfill');
4579
+ });
4580
+ }
4581
+
4582
+ class WordDocumentService {
4583
+ generateWordByteFile(model) {
4584
+ return __awaiter(this, void 0, void 0, function* () {
4585
+ let documentOptions = {};
4586
+ if (model.options.isLandscape)
4587
+ documentOptions.orientation = 'landscape';
4588
+ documentOptions.pageSize = {
4589
+ width: model.options.pageWidth * 15,
4590
+ height: model.options.pageHeight * 15,
4591
+ };
4592
+ documentOptions.margins = {
4593
+ top: model.options.top * 15,
4594
+ right: model.options.right * 15,
4595
+ bottom: model.options.bottom * 15,
4596
+ left: model.options.left * 15,
4597
+ header: model.options.top * 15 * 2,
4598
+ footer: model.options.bottom * 15 * 2,
4599
+ gutter: 0,
4600
+ };
4601
+ documentOptions.footer = true;
4602
+ documentOptions.header = true;
4603
+ documentOptions.pageNumber = model.options.showPaging;
4604
+ documentOptions.table = { row: { cantSplit: true } };
4605
+ var fileBuffer = yield generateContainer(model.body, model.header, documentOptions, model.footer);
4606
+ return fileBuffer;
4607
+ });
4608
+ }
4609
+ }
4610
+ WordDocumentService.ɵprov = i0.ɵɵdefineInjectable({ factory: function WordDocumentService_Factory() { return new WordDocumentService(); }, token: WordDocumentService, providedIn: "root" });
4611
+ WordDocumentService.decorators = [
4612
+ { type: Injectable, args: [{
4613
+ providedIn: 'root',
4614
+ },] }
4615
+ ];
4616
+
4617
+ class WordDocumentModel {
4618
+ constructor() {
4619
+ this.options = new DocumentOptionsModel();
4620
+ }
4621
+ }
4622
+ class DocumentOptionsModel {
4623
+ }
4624
+
4625
+ /*
4626
+ * Public API Surface of @bnsights/bbsf-utilities
4627
+ */
4628
+
4629
+ /**
4630
+ * Generated bundle index. Do not edit.
4631
+ */
4632
+
4633
+ export { AppInjector, AppearanceConfigurationService, AuthService, BBSFTranslateService, BBSFUtilitiesModule, ConfigurationService, ControlValidationService, DocumentOptionsModel, EnvironmentService, MasterLayoutService, RequestHandlerService, RequestOptionsModel, StylesBundleService, TranslationResolverService, UtilityService, WordDocumentModel, WordDocumentService, environment };
4634
+ //# sourceMappingURL=bnsights-bbsf-utilities.js.map