@bnsights/bbsf-utilities 1.0.40 → 1.0.42

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