@ammarkhalidfarooq/dashboard-package 0.5.12 → 0.5.14

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.
package/dist/index.cjs.js CHANGED
@@ -64,6 +64,31 @@ function _arrayWithHoles(r) {
64
64
  function _arrayWithoutHoles(r) {
65
65
  if (Array.isArray(r)) return _arrayLikeToArray(r);
66
66
  }
67
+ function asyncGeneratorStep(n, t, e, r, o, a, c) {
68
+ try {
69
+ var i = n[a](c),
70
+ u = i.value;
71
+ } catch (n) {
72
+ return void e(n);
73
+ }
74
+ i.done ? t(u) : Promise.resolve(u).then(r, o);
75
+ }
76
+ function _asyncToGenerator(n) {
77
+ return function () {
78
+ var t = this,
79
+ e = arguments;
80
+ return new Promise(function (r, o) {
81
+ var a = n.apply(t, e);
82
+ function _next(n) {
83
+ asyncGeneratorStep(a, r, o, _next, _throw, "next", n);
84
+ }
85
+ function _throw(n) {
86
+ asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
87
+ }
88
+ _next(void 0);
89
+ });
90
+ };
91
+ }
67
92
  function _defineProperty(e, r, t) {
68
93
  return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
69
94
  value: t,
@@ -126,6 +151,114 @@ function _objectSpread2(e) {
126
151
  }
127
152
  return e;
128
153
  }
154
+ function _regenerator() {
155
+ /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/babel/babel/blob/main/packages/babel-helpers/LICENSE */
156
+ var e,
157
+ t,
158
+ r = "function" == typeof Symbol ? Symbol : {},
159
+ n = r.iterator || "@@iterator",
160
+ o = r.toStringTag || "@@toStringTag";
161
+ function i(r, n, o, i) {
162
+ var c = n && n.prototype instanceof Generator ? n : Generator,
163
+ u = Object.create(c.prototype);
164
+ return _regeneratorDefine(u, "_invoke", function (r, n, o) {
165
+ var i,
166
+ c,
167
+ u,
168
+ f = 0,
169
+ p = o || [],
170
+ y = false,
171
+ G = {
172
+ p: 0,
173
+ n: 0,
174
+ v: e,
175
+ a: d,
176
+ f: d.bind(e, 4),
177
+ d: function (t, r) {
178
+ return i = t, c = 0, u = e, G.n = r, a;
179
+ }
180
+ };
181
+ function d(r, n) {
182
+ for (c = r, u = n, t = 0; !y && f && !o && t < p.length; t++) {
183
+ var o,
184
+ i = p[t],
185
+ d = G.p,
186
+ l = i[2];
187
+ r > 3 ? (o = l === n) && (u = i[(c = i[4]) ? 5 : (c = 3, 3)], i[4] = i[5] = e) : i[0] <= d && ((o = r < 2 && d < i[1]) ? (c = 0, G.v = n, G.n = i[1]) : d < l && (o = r < 3 || i[0] > n || n > l) && (i[4] = r, i[5] = n, G.n = l, c = 0));
188
+ }
189
+ if (o || r > 1) return a;
190
+ throw y = true, n;
191
+ }
192
+ return function (o, p, l) {
193
+ if (f > 1) throw TypeError("Generator is already running");
194
+ for (y && 1 === p && d(p, l), c = p, u = l; (t = c < 2 ? e : u) || !y;) {
195
+ i || (c ? c < 3 ? (c > 1 && (G.n = -1), d(c, u)) : G.n = u : G.v = u);
196
+ try {
197
+ if (f = 2, i) {
198
+ if (c || (o = "next"), t = i[o]) {
199
+ if (!(t = t.call(i, u))) throw TypeError("iterator result is not an object");
200
+ if (!t.done) return t;
201
+ u = t.value, c < 2 && (c = 0);
202
+ } else 1 === c && (t = i.return) && t.call(i), c < 2 && (u = TypeError("The iterator does not provide a '" + o + "' method"), c = 1);
203
+ i = e;
204
+ } else if ((t = (y = G.n < 0) ? u : r.call(n, G)) !== a) break;
205
+ } catch (t) {
206
+ i = e, c = 1, u = t;
207
+ } finally {
208
+ f = 1;
209
+ }
210
+ }
211
+ return {
212
+ value: t,
213
+ done: y
214
+ };
215
+ };
216
+ }(r, o, i), true), u;
217
+ }
218
+ var a = {};
219
+ function Generator() {}
220
+ function GeneratorFunction() {}
221
+ function GeneratorFunctionPrototype() {}
222
+ t = Object.getPrototypeOf;
223
+ var c = [][n] ? t(t([][n]())) : (_regeneratorDefine(t = {}, n, function () {
224
+ return this;
225
+ }), t),
226
+ u = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(c);
227
+ function f(e) {
228
+ return Object.setPrototypeOf ? Object.setPrototypeOf(e, GeneratorFunctionPrototype) : (e.__proto__ = GeneratorFunctionPrototype, _regeneratorDefine(e, o, "GeneratorFunction")), e.prototype = Object.create(u), e;
229
+ }
230
+ return GeneratorFunction.prototype = GeneratorFunctionPrototype, _regeneratorDefine(u, "constructor", GeneratorFunctionPrototype), _regeneratorDefine(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = "GeneratorFunction", _regeneratorDefine(GeneratorFunctionPrototype, o, "GeneratorFunction"), _regeneratorDefine(u), _regeneratorDefine(u, o, "Generator"), _regeneratorDefine(u, n, function () {
231
+ return this;
232
+ }), _regeneratorDefine(u, "toString", function () {
233
+ return "[object Generator]";
234
+ }), (_regenerator = function () {
235
+ return {
236
+ w: i,
237
+ m: f
238
+ };
239
+ })();
240
+ }
241
+ function _regeneratorDefine(e, r, n, t) {
242
+ var i = Object.defineProperty;
243
+ try {
244
+ i({}, "", {});
245
+ } catch (e) {
246
+ i = 0;
247
+ }
248
+ _regeneratorDefine = function (e, r, n, t) {
249
+ function o(r, n) {
250
+ _regeneratorDefine(e, r, function (e) {
251
+ return this._invoke(r, n, e);
252
+ });
253
+ }
254
+ r ? i ? i(e, r, {
255
+ value: n,
256
+ enumerable: !t,
257
+ configurable: !t,
258
+ writable: !t
259
+ }) : e[r] = n : (o("next", 0), o("throw", 1), o("return", 2));
260
+ }, _regeneratorDefine(e, r, n, t);
261
+ }
129
262
  function _slicedToArray(r, e) {
130
263
  return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
131
264
  }
@@ -754,6 +887,19 @@ var Dashboard = function Dashboard(_ref) {
754
887
  });
755
888
  };
756
889
 
890
+ function formatNumber(num) {
891
+ if (num >= 1000000000) {
892
+ return (num / 1000000000).toFixed(1).replace(/\.0$/, "") + "B";
893
+ }
894
+ if (num >= 1000000) {
895
+ return (num / 1000000).toFixed(1).replace(/\.0$/, "") + "M";
896
+ }
897
+ if (num >= 1000) {
898
+ return (num / 1000).toFixed(1).replace(/\.0$/, "") + "K";
899
+ }
900
+ return (num !== null && num !== void 0 ? num : 0).toString();
901
+ }
902
+
757
903
  var OverallSection$2 = /*#__PURE__*/React.lazy(function () {
758
904
  return Promise.resolve().then(function () { return OverallSection$1; });
759
905
  });
@@ -793,9 +939,426 @@ var NewOverview = function NewOverview(_ref) {
793
939
  }
794
940
  }, [activeSectionProp]);
795
941
  React.useEffect(function () {
796
- if (exportTrigger > 0) {
797
- console.log("EXPORT TRIGGER");
798
- }
942
+ if (exportTrigger <= 0) return;
943
+ var buildAndDownloadPdf = /*#__PURE__*/function () {
944
+ var _ref2 = _asyncToGenerator(/*#__PURE__*/_regenerator().m(function _callee() {
945
+ var _apiData$overviewStat, _apiData$overviewStat2, _apiData$trafficSourc, _apiData$recurringBar, _apiData$recurringBar2, _apiData$roasCard, _apiData$overviewStat3, _apiData$overviewStat4, _apiData$overviewStat5, _apiData$overviewStat6, _apiData$overviewStat7, _apiData$overviewStat8, _doc$lastAutoTable, _doc$lastAutoTable2, _apiData$orderBumpDet, _apiData$orderBumpDet2, _apiData$orderBumpDet3, _apiData$orderBumpDet4, _apiData$upSellDetail, _apiData$upSellDetail2, _apiData$downSellDeta, _apiData$downSellDeta2, _apiData$referralDeta, _apiData$referralDeta2, _yield$Promise$all, _yield$Promise$all2, jsPDF, autoTableModule, autoTable, growth, overview, dateLabel, generatedAt, generatedLabel, fmtPct, fmtSigned, doc, pageWidth, marginX, contentWidth, cardGap, cardWidth, addHeader, addFooter, metricCard, donorMixRaw, newDonorsCount, returningDonorsCount, avgGift, newDonorsObj, returningDonorsObj, totalAmount, totalCount, activeCampaignRows, trafficRows, donorMixRows, recurringTotal, oneTimeTotalValue, donorGeoRows, refundsData, totalRaised, netRaised, totalDonors, convRate, avgDonation, totalVisits, passThrough, refundRate, chargebackRate, page1Cards, y, trendY, donorCardTop, cardsTop, halfGap, halfW, drawInfoCard, safeDate, _t;
946
+ return _regenerator().w(function (_context) {
947
+ while (1) switch (_context.p = _context.n) {
948
+ case 0:
949
+ _context.p = 0;
950
+ _context.n = 1;
951
+ return Promise.all([import('jspdf'), Promise.resolve().then(function () { return jspdf_plugin_autotable; })]);
952
+ case 1:
953
+ _yield$Promise$all = _context.v;
954
+ _yield$Promise$all2 = _slicedToArray(_yield$Promise$all, 2);
955
+ jsPDF = _yield$Promise$all2[0].jsPDF;
956
+ autoTableModule = _yield$Promise$all2[1];
957
+ autoTable = autoTableModule["default"] || autoTableModule.autoTable || autoTableModule;
958
+ growth = (apiData === null || apiData === void 0 || (_apiData$overviewStat = apiData.overviewStats) === null || _apiData$overviewStat === void 0 || (_apiData$overviewStat = _apiData$overviewStat.overview) === null || _apiData$overviewStat === void 0 ? void 0 : _apiData$overviewStat.growthPercentage) || {};
959
+ overview = (apiData === null || apiData === void 0 || (_apiData$overviewStat2 = apiData.overviewStats) === null || _apiData$overviewStat2 === void 0 ? void 0 : _apiData$overviewStat2.overview) || {};
960
+ dateLabel = dateName || "Last Period";
961
+ generatedAt = new Date();
962
+ generatedLabel = "".concat(generatedAt.toLocaleDateString(), " ").concat(generatedAt.toLocaleTimeString());
963
+ fmtPct = function fmtPct(value) {
964
+ var digits = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2;
965
+ return "".concat(Number(value || 0).toFixed(digits), "%");
966
+ };
967
+ fmtSigned = function fmtSigned(value) {
968
+ var suffix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "";
969
+ var numeric = Number(value || 0);
970
+ var sign = numeric > 0 ? "+" : "";
971
+ return "".concat(sign).concat(numeric.toFixed(2)).concat(suffix);
972
+ };
973
+ doc = new jsPDF({
974
+ unit: "pt",
975
+ format: "a4"
976
+ });
977
+ pageWidth = doc.internal.pageSize.getWidth();
978
+ marginX = 40;
979
+ contentWidth = pageWidth - marginX * 2;
980
+ cardGap = 10;
981
+ cardWidth = (contentWidth - cardGap * 2) / 3;
982
+ addHeader = function addHeader() {
983
+ doc.setFont("helvetica", "bold");
984
+ doc.setTextColor(17, 24, 39);
985
+ doc.setFontSize(18);
986
+ doc.text("Madinah", marginX, 34);
987
+ doc.setFontSize(10);
988
+ doc.setTextColor(75, 85, 99);
989
+ doc.text("PERFORMANCE REPORT", marginX, 50);
990
+ doc.setTextColor(17, 24, 39);
991
+ doc.setFontSize(13);
992
+ doc.text("Dashboard overview — Overall", marginX, 72);
993
+ doc.setFont("helvetica", "normal");
994
+ doc.setFontSize(10);
995
+ doc.setTextColor(107, 114, 128);
996
+ doc.text("".concat(dateLabel, " \xB7 30-day window \xB7 Generated ").concat(generatedLabel), marginX, 88);
997
+ var activeFilters = (apiData === null || apiData === void 0 ? void 0 : apiData.activeFilters) || "";
998
+ if (activeFilters) {
999
+ doc.setFontSize(8.5);
1000
+ doc.setTextColor(55, 65, 81);
1001
+ doc.text("ACTIVE FILTERS ".concat(activeFilters), marginX, 100);
1002
+ }
1003
+ };
1004
+ addFooter = function addFooter(pageNumber, totalPages) {
1005
+ doc.setFont("helvetica", "normal");
1006
+ doc.setTextColor(107, 114, 128);
1007
+ doc.setFontSize(8.5);
1008
+ doc.text("Confidential \xB7 Generated by Dashboard \xB7 ".concat(generatedLabel, " \xB7 Page ").concat(pageNumber, " of ").concat(totalPages, " \xB7 madinah.com"), marginX, 818);
1009
+ };
1010
+ metricCard = function metricCard(_ref3) {
1011
+ var x = _ref3.x,
1012
+ y = _ref3.y,
1013
+ title = _ref3.title,
1014
+ value = _ref3.value,
1015
+ trend = _ref3.trend,
1016
+ detail = _ref3.detail;
1017
+ var positive = !"".concat(trend).trim().startsWith("-");
1018
+ doc.setDrawColor(229, 231, 235);
1019
+ doc.setFillColor(255, 255, 255);
1020
+ doc.roundedRect(x, y, cardWidth, 96, 6, 6, "FD");
1021
+ doc.setFont("helvetica", "bold");
1022
+ doc.setFontSize(9);
1023
+ doc.setTextColor(75, 85, 99);
1024
+ doc.text(title.toUpperCase(), x + 10, y + 16);
1025
+ doc.setFontSize(17);
1026
+ doc.setTextColor(17, 24, 39);
1027
+ doc.text(value, x + 10, y + 42);
1028
+ doc.setFont("helvetica", "normal");
1029
+ doc.setFontSize(9.5);
1030
+ doc.setTextColor.apply(doc, _toConsumableArray(positive ? [22, 163, 74] : [220, 38, 38]));
1031
+ doc.text(trend, x + 10, y + 61);
1032
+ doc.setTextColor(107, 114, 128);
1033
+ doc.setFontSize(8.5);
1034
+ doc.text(detail, x + 10, y + 77, {
1035
+ maxWidth: cardWidth - 20
1036
+ });
1037
+ };
1038
+ donorMixRaw = apiData === null || apiData === void 0 ? void 0 : apiData.donorPieChartData;
1039
+ newDonorsCount = 0;
1040
+ returningDonorsCount = 0;
1041
+ avgGift = 0;
1042
+ if (Array.isArray(donorMixRaw)) {
1043
+ newDonorsObj = donorMixRaw.find(function (d) {
1044
+ return d.type === "New Donors" || d.type === "New donors";
1045
+ }) || {};
1046
+ returningDonorsObj = donorMixRaw.find(function (d) {
1047
+ return d.type === "Returning Donors" || d.type === "Returning";
1048
+ }) || {};
1049
+ newDonorsCount = newDonorsObj.totalDonations || 0;
1050
+ returningDonorsCount = returningDonorsObj.totalDonations || 0;
1051
+ totalAmount = (newDonorsObj.totalAmount || 0) + (returningDonorsObj.totalAmount || 0);
1052
+ totalCount = newDonorsCount + returningDonorsCount;
1053
+ avgGift = totalCount > 0 ? Number((totalAmount / totalCount).toFixed(2)) : 0;
1054
+ } else if (donorMixRaw && _typeof(donorMixRaw) === "object") {
1055
+ newDonorsCount = donorMixRaw.newDonors || 0;
1056
+ returningDonorsCount = donorMixRaw.returningDonors || 0;
1057
+ avgGift = donorMixRaw.avgGift || 0;
1058
+ }
1059
+ activeCampaignRows = ((apiData === null || apiData === void 0 ? void 0 : apiData.activeCampaigns) || []).map(function (campaign) {
1060
+ return [campaign.title || "Untitled Campaign", "$".concat(formatNumber(campaign.collectedAmount || 0)), "".concat(Math.round((campaign.collectedAmount || 0) / (campaign.usdTargetAmount || 1) * 100), "%"), "".concat(formatNumber(campaign.uniqueDonationsCount || 0)), "$".concat(formatNumber(campaign.avgGift || 0)), campaign.status || "Active"];
1061
+ });
1062
+ trafficRows = ((apiData === null || apiData === void 0 || (_apiData$trafficSourc = apiData.trafficSourceData) === null || _apiData$trafficSourc === void 0 ? void 0 : _apiData$trafficSourc.data) || []).map(function (item) {
1063
+ return [(item === null || item === void 0 ? void 0 : item.source) || (item === null || item === void 0 ? void 0 : item.name) || "-", "".concat(formatNumber((item === null || item === void 0 ? void 0 : item.donors) || (item === null || item === void 0 ? void 0 : item.totalDonors) || 0)), "$".concat(formatNumber((item === null || item === void 0 ? void 0 : item.revenue) || (item === null || item === void 0 ? void 0 : item.raised) || 0))];
1064
+ });
1065
+ donorMixRows = [["New donors", "".concat(formatNumber(newDonorsCount))], ["Returning donors", "".concat(formatNumber(returningDonorsCount))], ["Avg gift", "$".concat(formatNumber(avgGift))]];
1066
+ recurringTotal = Number((apiData === null || apiData === void 0 || (_apiData$recurringBar = apiData.recurringBarChartData) === null || _apiData$recurringBar === void 0 ? void 0 : _apiData$recurringBar.recurringTotal) || 0);
1067
+ oneTimeTotalValue = Number((apiData === null || apiData === void 0 || (_apiData$recurringBar2 = apiData.recurringBarChartData) === null || _apiData$recurringBar2 === void 0 ? void 0 : _apiData$recurringBar2.oneTimeTotal) || 0);
1068
+ donorGeoRows = ((apiData === null || apiData === void 0 ? void 0 : apiData.donorGeography) || []).slice(0, 6).map(function (item) {
1069
+ return [item.country || item.name || "-", "".concat(formatNumber(item.totalDonors || item.donors || 0)), "".concat(formatNumber(item.percentage || 0), "%")];
1070
+ });
1071
+ refundsData = (apiData === null || apiData === void 0 ? void 0 : apiData.refundAndChargeBacks) || {};
1072
+ totalRaised = Number((overview === null || overview === void 0 ? void 0 : overview.totalRevenue) || 0);
1073
+ netRaised = Number((overview === null || overview === void 0 ? void 0 : overview.netRevenue) || 0);
1074
+ totalDonors = Number((overview === null || overview === void 0 ? void 0 : overview.totalDonations) || 0);
1075
+ convRate = Number((overview === null || overview === void 0 ? void 0 : overview.conversionRate) || 0);
1076
+ avgDonation = Number((overview === null || overview === void 0 ? void 0 : overview.overallAVGDonations) || 0);
1077
+ totalVisits = Number((apiData === null || apiData === void 0 ? void 0 : apiData.totalVisits) || 0);
1078
+ passThrough = totalRaised > 0 ? "".concat((netRaised / totalRaised * 100).toFixed(1), "% pass-through") : "0% pass-through";
1079
+ refundRate = Number((refundsData === null || refundsData === void 0 ? void 0 : refundsData.refundRate) || 0);
1080
+ chargebackRate = Number((refundsData === null || refundsData === void 0 ? void 0 : refundsData.chargebackRate) || 0);
1081
+ page1Cards = [{
1082
+ title: "Total Raised",
1083
+ value: "$".concat(formatNumber(totalRaised)),
1084
+ trend: "".concat(fmtSigned(growth === null || growth === void 0 ? void 0 : growth.totalRevenue, "%"), " vs ").concat(dateLabel),
1085
+ detail: "".concat(passThrough, " \xB7 ").concat(formatNumber(totalDonors), " donors \xB7 $").concat(formatNumber(avgDonation), " avg \xB7 ").concat(formatNumber(totalVisits), " visits")
1086
+ }, {
1087
+ title: "Net Raised",
1088
+ value: "$".concat(formatNumber(netRaised)),
1089
+ trend: fmtSigned(growth === null || growth === void 0 ? void 0 : growth.netRevenue, "%"),
1090
+ detail: passThrough
1091
+ }, {
1092
+ title: "Total Donors",
1093
+ value: "".concat(formatNumber(totalDonors)),
1094
+ trend: fmtSigned(growth === null || growth === void 0 ? void 0 : growth.totalDonations, "%"),
1095
+ detail: "".concat(formatNumber(newDonorsCount), " new \xB7 ").concat(formatNumber(returningDonorsCount), " returning")
1096
+ }, {
1097
+ title: "Avg Donation",
1098
+ value: "$".concat(formatNumber(avgDonation)),
1099
+ trend: fmtSigned(growth === null || growth === void 0 ? void 0 : growth.overallAVGDonations, "%"),
1100
+ detail: "Median $".concat(formatNumber((apiData === null || apiData === void 0 ? void 0 : apiData.medianGift) || 0), " \xB7 top decile $").concat(formatNumber((apiData === null || apiData === void 0 ? void 0 : apiData.topDecileGift) || 0))
1101
+ }, {
1102
+ title: "ROAS",
1103
+ value: "".concat(formatNumber((_apiData$roasCard = apiData === null || apiData === void 0 ? void 0 : apiData.roasCard) !== null && _apiData$roasCard !== void 0 ? _apiData$roasCard : 0), "x"),
1104
+ trend: fmtSigned(apiData === null || apiData === void 0 ? void 0 : apiData.roasCardPrev, "x"),
1105
+ detail: "$".concat(formatNumber((apiData === null || apiData === void 0 ? void 0 : apiData.adSpend) || 0), " spend \xB7 $").concat(formatNumber((apiData === null || apiData === void 0 ? void 0 : apiData.attributedRevenue) || 0), " attrib.")
1106
+ }, {
1107
+ title: "Conversion",
1108
+ value: fmtPct(convRate, 1),
1109
+ trend: fmtSigned(growth === null || growth === void 0 ? void 0 : growth.conversionRate, "pp"),
1110
+ detail: "".concat(formatNumber(totalDonors), " from ").concat(formatNumber(totalVisits), " visits")
1111
+ }, {
1112
+ title: "Refund Rate",
1113
+ value: fmtPct(refundRate, 2),
1114
+ trend: fmtSigned(refundsData === null || refundsData === void 0 ? void 0 : refundsData.refundRateChange, "pp"),
1115
+ detail: "".concat(formatNumber((refundsData === null || refundsData === void 0 ? void 0 : refundsData.refundCount) || 0), " refunds this period")
1116
+ }];
1117
+ addHeader();
1118
+ y = 114;
1119
+ page1Cards.forEach(function (card, idx) {
1120
+ var col = idx % 3;
1121
+ var row = Math.floor(idx / 3);
1122
+ metricCard(_objectSpread2({
1123
+ x: marginX + col * (cardWidth + cardGap),
1124
+ y: y + row * (96 + 10)
1125
+ }, card));
1126
+ });
1127
+ trendY = y + Math.ceil(page1Cards.length / 3) * (96 + 10) + 8;
1128
+ doc.setDrawColor(229, 231, 235);
1129
+ doc.roundedRect(marginX, trendY, contentWidth, 130, 6, 6);
1130
+ doc.setFont("helvetica", "bold");
1131
+ doc.setFontSize(12);
1132
+ doc.setTextColor(17, 24, 39);
1133
+ doc.text("Total revenue trend", marginX + 12, trendY + 20);
1134
+ doc.setFont("helvetica", "normal");
1135
+ doc.setFontSize(9.5);
1136
+ doc.setTextColor(107, 114, 128);
1137
+ doc.text("Last 30 days · daily aggregation", marginX + 12, trendY + 35);
1138
+ doc.setFont("helvetica", "bold");
1139
+ doc.setFontSize(14);
1140
+ doc.setTextColor(17, 24, 39);
1141
+ doc.text("$".concat(formatNumber(totalRaised)), marginX + 12, trendY + 58);
1142
+ doc.setFont("helvetica", "normal");
1143
+ doc.setFontSize(9.5);
1144
+ doc.setTextColor(22, 163, 74);
1145
+ doc.text("".concat(fmtSigned(growth === null || growth === void 0 ? void 0 : growth.totalRevenue, "%"), " vs ").concat(dateLabel), marginX + 110, trendY + 58);
1146
+ autoTable(doc, {
1147
+ startY: trendY + 68,
1148
+ head: [["Channel", "Total"]],
1149
+ body: [["Email", "$".concat(formatNumber((apiData === null || apiData === void 0 || (_apiData$overviewStat3 = apiData.overviewStats) === null || _apiData$overviewStat3 === void 0 || (_apiData$overviewStat3 = _apiData$overviewStat3.totalRaised) === null || _apiData$overviewStat3 === void 0 || (_apiData$overviewStat3 = _apiData$overviewStat3.email) === null || _apiData$overviewStat3 === void 0 || (_apiData$overviewStat4 = _apiData$overviewStat3.reduce) === null || _apiData$overviewStat4 === void 0 ? void 0 : _apiData$overviewStat4.call(_apiData$overviewStat3, function (s, i) {
1150
+ return s + ((i === null || i === void 0 ? void 0 : i.value) || 0);
1151
+ }, 0)) || 0))], ["Organic", "$".concat(formatNumber((apiData === null || apiData === void 0 || (_apiData$overviewStat5 = apiData.overviewStats) === null || _apiData$overviewStat5 === void 0 || (_apiData$overviewStat5 = _apiData$overviewStat5.totalRaised) === null || _apiData$overviewStat5 === void 0 || (_apiData$overviewStat5 = _apiData$overviewStat5.organic) === null || _apiData$overviewStat5 === void 0 || (_apiData$overviewStat6 = _apiData$overviewStat5.reduce) === null || _apiData$overviewStat6 === void 0 ? void 0 : _apiData$overviewStat6.call(_apiData$overviewStat5, function (s, i) {
1152
+ return s + ((i === null || i === void 0 ? void 0 : i.value) || 0);
1153
+ }, 0)) || 0))], ["Paid Ads", "$".concat(formatNumber((apiData === null || apiData === void 0 || (_apiData$overviewStat7 = apiData.overviewStats) === null || _apiData$overviewStat7 === void 0 || (_apiData$overviewStat7 = _apiData$overviewStat7.totalRaised) === null || _apiData$overviewStat7 === void 0 || (_apiData$overviewStat7 = _apiData$overviewStat7.paidAds) === null || _apiData$overviewStat7 === void 0 || (_apiData$overviewStat8 = _apiData$overviewStat7.reduce) === null || _apiData$overviewStat8 === void 0 ? void 0 : _apiData$overviewStat8.call(_apiData$overviewStat7, function (s, i) {
1154
+ return s + ((i === null || i === void 0 ? void 0 : i.value) || 0);
1155
+ }, 0)) || 0))]],
1156
+ margin: {
1157
+ left: marginX + 12,
1158
+ right: marginX + 12
1159
+ },
1160
+ styles: {
1161
+ fontSize: 9,
1162
+ cellPadding: 4
1163
+ },
1164
+ headStyles: {
1165
+ fillColor: [241, 245, 249],
1166
+ textColor: [51, 65, 85]
1167
+ },
1168
+ alternateRowStyles: {
1169
+ fillColor: [248, 250, 252]
1170
+ }
1171
+ });
1172
+ addFooter(1, 2);
1173
+ doc.addPage();
1174
+ addHeader();
1175
+ doc.setFont("helvetica", "bold");
1176
+ doc.setFontSize(12);
1177
+ doc.setTextColor(17, 24, 39);
1178
+ doc.text("Active campaigns", marginX, 112);
1179
+ doc.setFont("helvetica", "normal");
1180
+ doc.setFontSize(9.5);
1181
+ doc.setTextColor(107, 114, 128);
1182
+ doc.text("Live fundraisers ranked by velocity", marginX, 126);
1183
+ doc.setTextColor(99, 102, 241);
1184
+ doc.text("View all →", pageWidth - marginX, 126, {
1185
+ align: "right"
1186
+ });
1187
+ autoTable(doc, {
1188
+ startY: 136,
1189
+ head: [["CAMPAIGN", "RAISED", "PROGRESS", "DONORS", "AVG GIFT", "STATUS"]],
1190
+ body: activeCampaignRows.length ? activeCampaignRows : [["-", "$0", "0%", "0", "$0", "-"]],
1191
+ margin: {
1192
+ left: marginX,
1193
+ right: marginX
1194
+ },
1195
+ styles: {
1196
+ fontSize: 9,
1197
+ cellPadding: 5
1198
+ },
1199
+ headStyles: {
1200
+ fillColor: [241, 245, 249],
1201
+ textColor: [51, 65, 85]
1202
+ },
1203
+ alternateRowStyles: {
1204
+ fillColor: [248, 250, 252]
1205
+ }
1206
+ });
1207
+ donorCardTop = (((_doc$lastAutoTable = doc.lastAutoTable) === null || _doc$lastAutoTable === void 0 ? void 0 : _doc$lastAutoTable.finalY) || 230) + 14;
1208
+ doc.setDrawColor(229, 231, 235);
1209
+ doc.roundedRect(marginX, donorCardTop, 250, 108, 6, 6);
1210
+ doc.setFont("helvetica", "bold");
1211
+ doc.setFontSize(11);
1212
+ doc.setTextColor(17, 24, 39);
1213
+ doc.text("Donor mix", marginX + 10, donorCardTop + 18);
1214
+ doc.setFont("helvetica", "normal");
1215
+ doc.setFontSize(9);
1216
+ doc.setTextColor(107, 114, 128);
1217
+ doc.text("Acquisition vs retention", marginX + 10, donorCardTop + 32);
1218
+ autoTable(doc, {
1219
+ startY: donorCardTop + 38,
1220
+ head: [["Type", "Value"]],
1221
+ body: donorMixRows,
1222
+ margin: {
1223
+ left: marginX + 10,
1224
+ right: pageWidth - (marginX + 240)
1225
+ },
1226
+ styles: {
1227
+ fontSize: 9,
1228
+ cellPadding: 4
1229
+ },
1230
+ headStyles: {
1231
+ fillColor: [241, 245, 249],
1232
+ textColor: [51, 65, 85]
1233
+ }
1234
+ });
1235
+ autoTable(doc, {
1236
+ startY: donorCardTop,
1237
+ head: [["SOURCE", "DONORS", "REVENUE"]],
1238
+ body: trafficRows.length > 0 ? trafficRows : [["-", "0", "$0"]],
1239
+ margin: {
1240
+ left: marginX + 266,
1241
+ right: marginX
1242
+ },
1243
+ styles: {
1244
+ fontSize: 9,
1245
+ cellPadding: 5
1246
+ },
1247
+ headStyles: {
1248
+ fillColor: [241, 245, 249],
1249
+ textColor: [51, 65, 85]
1250
+ },
1251
+ alternateRowStyles: {
1252
+ fillColor: [248, 250, 252]
1253
+ }
1254
+ });
1255
+ cardsTop = (((_doc$lastAutoTable2 = doc.lastAutoTable) === null || _doc$lastAutoTable2 === void 0 ? void 0 : _doc$lastAutoTable2.finalY) || donorCardTop + 120) + 12;
1256
+ halfGap = 12;
1257
+ halfW = (contentWidth - halfGap) / 2;
1258
+ drawInfoCard = function drawInfoCard(_ref4) {
1259
+ var x = _ref4.x,
1260
+ y = _ref4.y,
1261
+ w = _ref4.w,
1262
+ h = _ref4.h,
1263
+ title = _ref4.title,
1264
+ subtitle = _ref4.subtitle,
1265
+ _ref4$lines = _ref4.lines,
1266
+ lines = _ref4$lines === void 0 ? [] : _ref4$lines;
1267
+ doc.setDrawColor(229, 231, 235);
1268
+ doc.roundedRect(x, y, w, h, 6, 6);
1269
+ doc.setFont("helvetica", "bold");
1270
+ doc.setTextColor(17, 24, 39);
1271
+ doc.setFontSize(10);
1272
+ doc.text(title, x + 10, y + 16);
1273
+ doc.setFont("helvetica", "normal");
1274
+ doc.setFontSize(8.5);
1275
+ doc.setTextColor(107, 114, 128);
1276
+ doc.text(subtitle, x + 10, y + 30);
1277
+ doc.setTextColor(55, 65, 81);
1278
+ lines.forEach(function (line, idx) {
1279
+ doc.text(line, x + 10, y + 46 + idx * 12, {
1280
+ maxWidth: w - 20
1281
+ });
1282
+ });
1283
+ };
1284
+ drawInfoCard({
1285
+ x: marginX,
1286
+ y: cardsTop,
1287
+ w: halfW,
1288
+ h: 86,
1289
+ title: "Recurring vs one-time",
1290
+ subtitle: "Donation type · weekly",
1291
+ lines: ["Recurring $".concat(formatNumber(recurringTotal)), "One-time $".concat(formatNumber(oneTimeTotalValue))]
1292
+ });
1293
+ drawInfoCard({
1294
+ x: marginX + halfW + halfGap,
1295
+ y: cardsTop,
1296
+ w: halfW,
1297
+ h: 86,
1298
+ title: "Refunds & chargebacks",
1299
+ subtitle: "Trust health · 30-day window",
1300
+ lines: ["Refunds ".concat(fmtPct(refundRate, 2), " (").concat(fmtSigned(refundsData === null || refundsData === void 0 ? void 0 : refundsData.refundRateChange, "pp"), ")"), "Chargebacks ".concat(fmtPct(chargebackRate, 2), " (").concat(fmtSigned(refundsData === null || refundsData === void 0 ? void 0 : refundsData.chargebackRateChange, "pp"), ")"), "$".concat(formatNumber((refundsData === null || refundsData === void 0 ? void 0 : refundsData.refundAmount) || 0), " refunded \xB7 $").concat(formatNumber((refundsData === null || refundsData === void 0 ? void 0 : refundsData.disputedAmount) || 0), " disputed")]
1301
+ });
1302
+ drawInfoCard({
1303
+ x: marginX,
1304
+ y: cardsTop + 96,
1305
+ w: halfW,
1306
+ h: 88,
1307
+ title: "Order Bump",
1308
+ subtitle: "Revenue trend · last 30 days",
1309
+ lines: ["$".concat(formatNumber((apiData === null || apiData === void 0 || (_apiData$orderBumpDet = apiData.orderBumpDetails) === null || _apiData$orderBumpDet === void 0 ? void 0 : _apiData$orderBumpDet.totalRevenue) || 0), " (").concat(fmtSigned(apiData === null || apiData === void 0 || (_apiData$orderBumpDet2 = apiData.orderBumpDetails) === null || _apiData$orderBumpDet2 === void 0 ? void 0 : _apiData$orderBumpDet2.growthPercentage, "%"), ")"), "Avg/day $".concat(formatNumber((apiData === null || apiData === void 0 || (_apiData$orderBumpDet3 = apiData.orderBumpDetails) === null || _apiData$orderBumpDet3 === void 0 ? void 0 : _apiData$orderBumpDet3.averagePerDay) || 0), " \xB7 Orders ").concat(formatNumber((apiData === null || apiData === void 0 || (_apiData$orderBumpDet4 = apiData.orderBumpDetails) === null || _apiData$orderBumpDet4 === void 0 ? void 0 : _apiData$orderBumpDet4.totalOrders) || 0))]
1310
+ });
1311
+ drawInfoCard({
1312
+ x: marginX + halfW + halfGap,
1313
+ y: cardsTop + 96,
1314
+ w: halfW,
1315
+ h: 88,
1316
+ title: "Upsell / Downsell / Referrals",
1317
+ subtitle: "Acceptance & raised",
1318
+ lines: ["Upsell $".concat(formatNumber((apiData === null || apiData === void 0 || (_apiData$upSellDetail = apiData.upSellDetails) === null || _apiData$upSellDetail === void 0 ? void 0 : _apiData$upSellDetail.raised) || 0), " \xB7 ").concat(fmtPct((apiData === null || apiData === void 0 || (_apiData$upSellDetail2 = apiData.upSellDetails) === null || _apiData$upSellDetail2 === void 0 ? void 0 : _apiData$upSellDetail2.acceptanceRate) || 0, 1), " accepted"), "Downsell $".concat(formatNumber((apiData === null || apiData === void 0 || (_apiData$downSellDeta = apiData.downSellDetails) === null || _apiData$downSellDeta === void 0 ? void 0 : _apiData$downSellDeta.raised) || 0), " \xB7 ").concat(fmtPct((apiData === null || apiData === void 0 || (_apiData$downSellDeta2 = apiData.downSellDetails) === null || _apiData$downSellDeta2 === void 0 ? void 0 : _apiData$downSellDeta2.acceptanceRate) || 0, 1), " accepted"), "Referrals $".concat(formatNumber((apiData === null || apiData === void 0 || (_apiData$referralDeta = apiData.referralDetails) === null || _apiData$referralDeta === void 0 ? void 0 : _apiData$referralDeta.totalRevenue) || 0), " \xB7 ").concat(fmtPct((apiData === null || apiData === void 0 || (_apiData$referralDeta2 = apiData.referralDetails) === null || _apiData$referralDeta2 === void 0 ? void 0 : _apiData$referralDeta2.conversionRate) || 0, 1), " conv.")]
1319
+ });
1320
+ if (donorGeoRows.length > 0) {
1321
+ autoTable(doc, {
1322
+ startY: cardsTop + 192,
1323
+ head: [["COUNTRY", "DONORS", "SHARE"]],
1324
+ body: donorGeoRows,
1325
+ margin: {
1326
+ left: marginX,
1327
+ right: marginX
1328
+ },
1329
+ styles: {
1330
+ fontSize: 9,
1331
+ cellPadding: 4.5
1332
+ },
1333
+ headStyles: {
1334
+ fillColor: [241, 245, 249],
1335
+ textColor: [51, 65, 85]
1336
+ },
1337
+ alternateRowStyles: {
1338
+ fillColor: [248, 250, 252]
1339
+ }
1340
+ });
1341
+ }
1342
+ addFooter(2, 2);
1343
+ safeDate = new Date().toISOString().slice(0, 10);
1344
+ doc.save("DashboardOverview_report_".concat(safeDate, ".pdf"));
1345
+ _context.n = 3;
1346
+ break;
1347
+ case 2:
1348
+ _context.p = 2;
1349
+ _t = _context.v;
1350
+ // Keep console message for host app debugging when export dependency is missing.
1351
+ console.error("Failed to export overall dashboard PDF:", _t);
1352
+ case 3:
1353
+ return _context.a(2);
1354
+ }
1355
+ }, _callee, null, [[0, 2]]);
1356
+ }));
1357
+ return function buildAndDownloadPdf() {
1358
+ return _ref2.apply(this, arguments);
1359
+ };
1360
+ }();
1361
+ buildAndDownloadPdf();
799
1362
  }, [exportTrigger]);
800
1363
  var currentData = metric === "Revenue" ? revenueData : donationsData;
801
1364
  var oneTimeData = (apiData === null || apiData === void 0 ? void 0 : apiData.oneTimeDonations) || [];
@@ -3034,19 +3597,6 @@ var DonorMixCard = function DonorMixCard(_ref) {
3034
3597
  });
3035
3598
  };
3036
3599
 
3037
- function formatNumber(num) {
3038
- if (num >= 1000000000) {
3039
- return (num / 1000000000).toFixed(1).replace(/\.0$/, "") + "B";
3040
- }
3041
- if (num >= 1000000) {
3042
- return (num / 1000000).toFixed(1).replace(/\.0$/, "") + "M";
3043
- }
3044
- if (num >= 1000) {
3045
- return (num / 1000).toFixed(1).replace(/\.0$/, "") + "K";
3046
- }
3047
- return (num !== null && num !== void 0 ? num : 0).toString();
3048
- }
3049
-
3050
3600
  var TrafficSourceCard = function TrafficSourceCard(_ref) {
3051
3601
  var _ref$title = _ref.title,
3052
3602
  title = _ref$title === void 0 ? "Traffic source" : _ref$title,
@@ -6965,6 +7515,2106 @@ var EmailSection$1 = /*#__PURE__*/Object.freeze({
6965
7515
  default: EmailSection
6966
7516
  });
6967
7517
 
7518
+ /**
7519
+ * Improved text function with halign and valign support
7520
+ * Inspiration from: http://stackoverflow.com/questions/28327510/align-text-right-using-jspdf/28433113#28433113
7521
+ */
7522
+ function autoTableText (text, x, y, styles, doc) {
7523
+ styles = styles || {};
7524
+ var PHYSICAL_LINE_HEIGHT = 1.15;
7525
+ var k = doc.internal.scaleFactor;
7526
+ var fontSize = doc.internal.getFontSize() / k;
7527
+ var lineHeightFactor = doc.getLineHeightFactor
7528
+ ? doc.getLineHeightFactor()
7529
+ : PHYSICAL_LINE_HEIGHT;
7530
+ var lineHeight = fontSize * lineHeightFactor;
7531
+ var splitRegex = /\r\n|\r|\n/g;
7532
+ var splitText = '';
7533
+ var lineCount = 1;
7534
+ if (styles.valign === 'middle' ||
7535
+ styles.valign === 'bottom' ||
7536
+ styles.halign === 'center' ||
7537
+ styles.halign === 'right') {
7538
+ splitText = typeof text === 'string' ? text.split(splitRegex) : text;
7539
+ lineCount = splitText.length || 1;
7540
+ }
7541
+ // Align the top
7542
+ y += fontSize * (2 - PHYSICAL_LINE_HEIGHT);
7543
+ if (styles.valign === 'middle')
7544
+ y -= (lineCount / 2) * lineHeight;
7545
+ else if (styles.valign === 'bottom')
7546
+ y -= lineCount * lineHeight;
7547
+ if (styles.halign === 'center' || styles.halign === 'right') {
7548
+ var alignSize = fontSize;
7549
+ if (styles.halign === 'center')
7550
+ alignSize *= 0.5;
7551
+ if (splitText && lineCount >= 1) {
7552
+ for (var iLine = 0; iLine < splitText.length; iLine++) {
7553
+ doc.text(splitText[iLine], x - doc.getStringUnitWidth(splitText[iLine]) * alignSize, y);
7554
+ y += lineHeight;
7555
+ }
7556
+ return doc;
7557
+ }
7558
+ x -= doc.getStringUnitWidth(text) * alignSize;
7559
+ }
7560
+ if (styles.halign === 'justify') {
7561
+ doc.text(text, x, y, { maxWidth: styles.maxWidth || 100, align: 'justify' });
7562
+ }
7563
+ else {
7564
+ doc.text(text, x, y);
7565
+ }
7566
+ return doc;
7567
+ }
7568
+
7569
+ var globalDefaults = {};
7570
+ var DocHandler = /** @class */ (function () {
7571
+ function DocHandler(jsPDFDocument) {
7572
+ this.jsPDFDocument = jsPDFDocument;
7573
+ this.userStyles = {
7574
+ // Black for versions of jspdf without getTextColor
7575
+ textColor: jsPDFDocument.getTextColor
7576
+ ? this.jsPDFDocument.getTextColor()
7577
+ : 0,
7578
+ fontSize: jsPDFDocument.internal.getFontSize(),
7579
+ fontStyle: jsPDFDocument.internal.getFont().fontStyle,
7580
+ font: jsPDFDocument.internal.getFont().fontName,
7581
+ // 0 for versions of jspdf without getLineWidth
7582
+ lineWidth: jsPDFDocument.getLineWidth
7583
+ ? this.jsPDFDocument.getLineWidth()
7584
+ : 0,
7585
+ // Black for versions of jspdf without getDrawColor
7586
+ lineColor: jsPDFDocument.getDrawColor
7587
+ ? this.jsPDFDocument.getDrawColor()
7588
+ : 0,
7589
+ };
7590
+ }
7591
+ DocHandler.setDefaults = function (defaults, doc) {
7592
+ if (doc === void 0) { doc = null; }
7593
+ if (doc) {
7594
+ doc.__autoTableDocumentDefaults = defaults;
7595
+ }
7596
+ else {
7597
+ globalDefaults = defaults;
7598
+ }
7599
+ };
7600
+ DocHandler.unifyColor = function (c) {
7601
+ if (Array.isArray(c)) {
7602
+ return c;
7603
+ }
7604
+ else if (typeof c === 'number') {
7605
+ return [c, c, c];
7606
+ }
7607
+ else if (typeof c === 'string') {
7608
+ return [c];
7609
+ }
7610
+ else {
7611
+ return null;
7612
+ }
7613
+ };
7614
+ DocHandler.prototype.applyStyles = function (styles, fontOnly) {
7615
+ // Font style needs to be applied before font
7616
+ // https://github.com/simonbengtsson/jsPDF-AutoTable/issues/632
7617
+ var _a, _b, _c;
7618
+ if (fontOnly === void 0) { fontOnly = false; }
7619
+ if (styles.fontStyle && this.jsPDFDocument.setFontStyle) {
7620
+ this.jsPDFDocument.setFontStyle(styles.fontStyle);
7621
+ }
7622
+ var _d = this.jsPDFDocument.internal.getFont(), fontStyle = _d.fontStyle, fontName = _d.fontName;
7623
+ if (styles.font)
7624
+ fontName = styles.font;
7625
+ if (styles.fontStyle) {
7626
+ fontStyle = styles.fontStyle;
7627
+ var availableFontStyles = this.getFontList()[fontName];
7628
+ if (availableFontStyles &&
7629
+ availableFontStyles.indexOf(fontStyle) === -1 &&
7630
+ this.jsPDFDocument.setFontStyle) {
7631
+ // Common issue was that the default bold in headers
7632
+ // made custom fonts not work. For example:
7633
+ // https://github.com/simonbengtsson/jsPDF-AutoTable/issues/653
7634
+ this.jsPDFDocument.setFontStyle(availableFontStyles[0]);
7635
+ fontStyle = availableFontStyles[0];
7636
+ }
7637
+ }
7638
+ this.jsPDFDocument.setFont(fontName, fontStyle);
7639
+ if (styles.fontSize)
7640
+ this.jsPDFDocument.setFontSize(styles.fontSize);
7641
+ if (fontOnly) {
7642
+ return; // Performance improvement
7643
+ }
7644
+ var color = DocHandler.unifyColor(styles.fillColor);
7645
+ if (color)
7646
+ (_a = this.jsPDFDocument).setFillColor.apply(_a, color);
7647
+ color = DocHandler.unifyColor(styles.textColor);
7648
+ if (color)
7649
+ (_b = this.jsPDFDocument).setTextColor.apply(_b, color);
7650
+ color = DocHandler.unifyColor(styles.lineColor);
7651
+ if (color)
7652
+ (_c = this.jsPDFDocument).setDrawColor.apply(_c, color);
7653
+ if (typeof styles.lineWidth === 'number') {
7654
+ this.jsPDFDocument.setLineWidth(styles.lineWidth);
7655
+ }
7656
+ };
7657
+ DocHandler.prototype.splitTextToSize = function (text, size, opts) {
7658
+ return this.jsPDFDocument.splitTextToSize(text, size, opts);
7659
+ };
7660
+ /**
7661
+ * Adds a rectangle to the PDF
7662
+ * @param x Coordinate (in units declared at inception of PDF document) against left edge of the page
7663
+ * @param y Coordinate (in units declared at inception of PDF document) against upper edge of the page
7664
+ * @param width Width (in units declared at inception of PDF document)
7665
+ * @param height Height (in units declared at inception of PDF document)
7666
+ * @param fillStyle A string specifying the painting style or null. Valid styles include: 'S' [default] - stroke, 'F' - fill, and 'DF' (or 'FD') - fill then stroke.
7667
+ */
7668
+ DocHandler.prototype.rect = function (x, y, width, height, fillStyle) {
7669
+ // null is excluded from fillStyle possible values because it isn't needed
7670
+ // and is prone to bugs as it's used to postpone setting the style
7671
+ // https://rawgit.com/MrRio/jsPDF/master/docs/jsPDF.html#rect
7672
+ return this.jsPDFDocument.rect(x, y, width, height, fillStyle);
7673
+ };
7674
+ DocHandler.prototype.getLastAutoTable = function () {
7675
+ return this.jsPDFDocument.lastAutoTable || null;
7676
+ };
7677
+ DocHandler.prototype.getTextWidth = function (text) {
7678
+ return this.jsPDFDocument.getTextWidth(text);
7679
+ };
7680
+ DocHandler.prototype.getDocument = function () {
7681
+ return this.jsPDFDocument;
7682
+ };
7683
+ DocHandler.prototype.setPage = function (page) {
7684
+ this.jsPDFDocument.setPage(page);
7685
+ };
7686
+ DocHandler.prototype.addPage = function () {
7687
+ return this.jsPDFDocument.addPage();
7688
+ };
7689
+ DocHandler.prototype.getFontList = function () {
7690
+ return this.jsPDFDocument.getFontList();
7691
+ };
7692
+ DocHandler.prototype.getGlobalOptions = function () {
7693
+ return globalDefaults || {};
7694
+ };
7695
+ DocHandler.prototype.getDocumentOptions = function () {
7696
+ return this.jsPDFDocument.__autoTableDocumentDefaults || {};
7697
+ };
7698
+ DocHandler.prototype.pageSize = function () {
7699
+ var pageSize = this.jsPDFDocument.internal.pageSize;
7700
+ // JSPDF 1.4 uses get functions instead of properties on pageSize
7701
+ if (pageSize.width == null) {
7702
+ pageSize = { width: pageSize.getWidth(), height: pageSize.getHeight() };
7703
+ }
7704
+ return pageSize;
7705
+ };
7706
+ DocHandler.prototype.scaleFactor = function () {
7707
+ return this.jsPDFDocument.internal.scaleFactor;
7708
+ };
7709
+ DocHandler.prototype.getLineHeightFactor = function () {
7710
+ var doc = this.jsPDFDocument;
7711
+ return doc.getLineHeightFactor ? doc.getLineHeightFactor() : 1.15;
7712
+ };
7713
+ DocHandler.prototype.getLineHeight = function (fontSize) {
7714
+ return (fontSize / this.scaleFactor()) * this.getLineHeightFactor();
7715
+ };
7716
+ DocHandler.prototype.pageNumber = function () {
7717
+ var pageInfo = this.jsPDFDocument.internal.getCurrentPageInfo();
7718
+ if (!pageInfo) {
7719
+ // Only recent versions of jspdf has pageInfo
7720
+ return this.jsPDFDocument.internal.getNumberOfPages();
7721
+ }
7722
+ return pageInfo.pageNumber;
7723
+ };
7724
+ return DocHandler;
7725
+ }());
7726
+
7727
+ /******************************************************************************
7728
+ Copyright (c) Microsoft Corporation.
7729
+
7730
+ Permission to use, copy, modify, and/or distribute this software for any
7731
+ purpose with or without fee is hereby granted.
7732
+
7733
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
7734
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
7735
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
7736
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
7737
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
7738
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
7739
+ PERFORMANCE OF THIS SOFTWARE.
7740
+ ***************************************************************************** */
7741
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
7742
+
7743
+ var extendStatics = function(d, b) {
7744
+ extendStatics = Object.setPrototypeOf ||
7745
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
7746
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7747
+ return extendStatics(d, b);
7748
+ };
7749
+
7750
+ function __extends(d, b) {
7751
+ if (typeof b !== "function" && b !== null)
7752
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
7753
+ extendStatics(d, b);
7754
+ function __() { this.constructor = d; }
7755
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
7756
+ }
7757
+
7758
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
7759
+ var e = new Error(message);
7760
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
7761
+ };
7762
+
7763
+ var HtmlRowInput = /** @class */ (function (_super) {
7764
+ __extends(HtmlRowInput, _super);
7765
+ function HtmlRowInput(element) {
7766
+ var _this = _super.call(this) || this;
7767
+ _this._element = element;
7768
+ return _this;
7769
+ }
7770
+ return HtmlRowInput;
7771
+ }(Array));
7772
+ // Base style for all themes
7773
+ function defaultStyles(scaleFactor) {
7774
+ return {
7775
+ font: 'helvetica', // helvetica, times, courier
7776
+ fontStyle: 'normal', // normal, bold, italic, bolditalic
7777
+ overflow: 'linebreak', // linebreak, ellipsize, visible or hidden
7778
+ fillColor: false, // Either false for transparent, rbg array e.g. [255, 255, 255] or gray level e.g 200
7779
+ textColor: 20,
7780
+ halign: 'left', // left, center, right, justify
7781
+ valign: 'top', // top, middle, bottom
7782
+ fontSize: 10,
7783
+ cellPadding: 5 / scaleFactor, // number or {top,left,right,left,vertical,horizontal}
7784
+ lineColor: 200,
7785
+ lineWidth: 0,
7786
+ cellWidth: 'auto', // 'auto'|'wrap'|number
7787
+ minCellHeight: 0,
7788
+ minCellWidth: 0,
7789
+ };
7790
+ }
7791
+ function getTheme(name) {
7792
+ var themes = {
7793
+ striped: {
7794
+ table: { fillColor: 255, textColor: 80, fontStyle: 'normal' },
7795
+ head: { textColor: 255, fillColor: [41, 128, 185], fontStyle: 'bold' },
7796
+ body: {},
7797
+ foot: { textColor: 255, fillColor: [41, 128, 185], fontStyle: 'bold' },
7798
+ alternateRow: { fillColor: 245 },
7799
+ },
7800
+ grid: {
7801
+ table: {
7802
+ fillColor: 255,
7803
+ textColor: 80,
7804
+ fontStyle: 'normal',
7805
+ lineWidth: 0.1,
7806
+ },
7807
+ head: {
7808
+ textColor: 255,
7809
+ fillColor: [26, 188, 156],
7810
+ fontStyle: 'bold',
7811
+ lineWidth: 0,
7812
+ },
7813
+ body: {},
7814
+ foot: {
7815
+ textColor: 255,
7816
+ fillColor: [26, 188, 156],
7817
+ fontStyle: 'bold',
7818
+ lineWidth: 0,
7819
+ },
7820
+ alternateRow: {},
7821
+ },
7822
+ plain: { head: { fontStyle: 'bold' }, foot: { fontStyle: 'bold' } },
7823
+ };
7824
+ return themes[name];
7825
+ }
7826
+
7827
+ function getStringWidth(text, styles, doc) {
7828
+ doc.applyStyles(styles, true);
7829
+ var textArr = Array.isArray(text) ? text : [text];
7830
+ var widestLineWidth = textArr
7831
+ .map(function (text) { return doc.getTextWidth(text); })
7832
+ .reduce(function (a, b) { return Math.max(a, b); }, 0);
7833
+ return widestLineWidth;
7834
+ }
7835
+ function addTableBorder(doc, table, startPos, cursor) {
7836
+ var lineWidth = table.settings.tableLineWidth;
7837
+ var lineColor = table.settings.tableLineColor;
7838
+ doc.applyStyles({ lineWidth: lineWidth, lineColor: lineColor });
7839
+ var fillStyle = getFillStyle(lineWidth, false);
7840
+ if (fillStyle) {
7841
+ doc.rect(startPos.x, startPos.y, table.getWidth(doc.pageSize().width), cursor.y - startPos.y, fillStyle);
7842
+ }
7843
+ }
7844
+ function getFillStyle(lineWidth, fillColor) {
7845
+ var drawLine = lineWidth > 0;
7846
+ var drawBackground = fillColor || fillColor === 0;
7847
+ if (drawLine && drawBackground) {
7848
+ return 'DF'; // Fill then stroke
7849
+ }
7850
+ else if (drawLine) {
7851
+ return 'S'; // Only stroke (transparent background)
7852
+ }
7853
+ else if (drawBackground) {
7854
+ return 'F'; // Only fill, no stroke
7855
+ }
7856
+ else {
7857
+ return null;
7858
+ }
7859
+ }
7860
+ function parseSpacing(value, defaultValue) {
7861
+ var _a, _b, _c, _d;
7862
+ value = value || defaultValue;
7863
+ if (Array.isArray(value)) {
7864
+ if (value.length >= 4) {
7865
+ return {
7866
+ top: value[0],
7867
+ right: value[1],
7868
+ bottom: value[2],
7869
+ left: value[3],
7870
+ };
7871
+ }
7872
+ else if (value.length === 3) {
7873
+ return {
7874
+ top: value[0],
7875
+ right: value[1],
7876
+ bottom: value[2],
7877
+ left: value[1],
7878
+ };
7879
+ }
7880
+ else if (value.length === 2) {
7881
+ return {
7882
+ top: value[0],
7883
+ right: value[1],
7884
+ bottom: value[0],
7885
+ left: value[1],
7886
+ };
7887
+ }
7888
+ else if (value.length === 1) {
7889
+ value = value[0];
7890
+ }
7891
+ else {
7892
+ value = defaultValue;
7893
+ }
7894
+ }
7895
+ if (typeof value === 'object') {
7896
+ if (typeof value.vertical === 'number') {
7897
+ value.top = value.vertical;
7898
+ value.bottom = value.vertical;
7899
+ }
7900
+ if (typeof value.horizontal === 'number') {
7901
+ value.right = value.horizontal;
7902
+ value.left = value.horizontal;
7903
+ }
7904
+ return {
7905
+ left: (_a = value.left) !== null && _a !== void 0 ? _a : defaultValue,
7906
+ top: (_b = value.top) !== null && _b !== void 0 ? _b : defaultValue,
7907
+ right: (_c = value.right) !== null && _c !== void 0 ? _c : defaultValue,
7908
+ bottom: (_d = value.bottom) !== null && _d !== void 0 ? _d : defaultValue,
7909
+ };
7910
+ }
7911
+ if (typeof value !== 'number') {
7912
+ value = defaultValue;
7913
+ }
7914
+ return { top: value, right: value, bottom: value, left: value };
7915
+ }
7916
+ function getPageAvailableWidth(doc, table) {
7917
+ var margins = parseSpacing(table.settings.margin, 0);
7918
+ return doc.pageSize().width - (margins.left + margins.right);
7919
+ }
7920
+
7921
+ // Limitations
7922
+ // - No support for border spacing
7923
+ // - No support for transparency
7924
+ function parseCss(supportedFonts, element, scaleFactor, style, window) {
7925
+ var result = {};
7926
+ var pxScaleFactor = 96 / 72;
7927
+ var backgroundColor = parseColor(element, function (elem) {
7928
+ return window.getComputedStyle(elem)['backgroundColor'];
7929
+ });
7930
+ if (backgroundColor != null)
7931
+ result.fillColor = backgroundColor;
7932
+ var textColor = parseColor(element, function (elem) {
7933
+ return window.getComputedStyle(elem)['color'];
7934
+ });
7935
+ if (textColor != null)
7936
+ result.textColor = textColor;
7937
+ var padding = parsePadding(style, scaleFactor);
7938
+ if (padding)
7939
+ result.cellPadding = padding;
7940
+ var borderColorSide = 'borderTopColor';
7941
+ var finalScaleFactor = pxScaleFactor * scaleFactor;
7942
+ var btw = style.borderTopWidth;
7943
+ if (style.borderBottomWidth === btw &&
7944
+ style.borderRightWidth === btw &&
7945
+ style.borderLeftWidth === btw) {
7946
+ var borderWidth = (parseFloat(btw) || 0) / finalScaleFactor;
7947
+ if (borderWidth)
7948
+ result.lineWidth = borderWidth;
7949
+ }
7950
+ else {
7951
+ result.lineWidth = {
7952
+ top: (parseFloat(style.borderTopWidth) || 0) / finalScaleFactor,
7953
+ right: (parseFloat(style.borderRightWidth) || 0) / finalScaleFactor,
7954
+ bottom: (parseFloat(style.borderBottomWidth) || 0) / finalScaleFactor,
7955
+ left: (parseFloat(style.borderLeftWidth) || 0) / finalScaleFactor,
7956
+ };
7957
+ // Choose border color of first available side
7958
+ // could be improved by supporting object as lineColor
7959
+ if (!result.lineWidth.top) {
7960
+ if (result.lineWidth.right) {
7961
+ borderColorSide = 'borderRightColor';
7962
+ }
7963
+ else if (result.lineWidth.bottom) {
7964
+ borderColorSide = 'borderBottomColor';
7965
+ }
7966
+ else if (result.lineWidth.left) {
7967
+ borderColorSide = 'borderLeftColor';
7968
+ }
7969
+ }
7970
+ }
7971
+ var borderColor = parseColor(element, function (elem) {
7972
+ return window.getComputedStyle(elem)[borderColorSide];
7973
+ });
7974
+ if (borderColor != null)
7975
+ result.lineColor = borderColor;
7976
+ var accepted = ['left', 'right', 'center', 'justify'];
7977
+ if (accepted.indexOf(style.textAlign) !== -1) {
7978
+ result.halign = style.textAlign;
7979
+ }
7980
+ accepted = ['middle', 'bottom', 'top'];
7981
+ if (accepted.indexOf(style.verticalAlign) !== -1) {
7982
+ result.valign = style.verticalAlign;
7983
+ }
7984
+ var res = parseInt(style.fontSize || '');
7985
+ if (!isNaN(res))
7986
+ result.fontSize = res / pxScaleFactor;
7987
+ var fontStyle = parseFontStyle(style);
7988
+ if (fontStyle)
7989
+ result.fontStyle = fontStyle;
7990
+ var font = (style.fontFamily || '').toLowerCase();
7991
+ if (supportedFonts.indexOf(font) !== -1) {
7992
+ result.font = font;
7993
+ }
7994
+ return result;
7995
+ }
7996
+ function parseFontStyle(style) {
7997
+ var res = '';
7998
+ if (style.fontWeight === 'bold' ||
7999
+ style.fontWeight === 'bolder' ||
8000
+ parseInt(style.fontWeight) >= 700) {
8001
+ res = 'bold';
8002
+ }
8003
+ if (style.fontStyle === 'italic' || style.fontStyle === 'oblique') {
8004
+ res += 'italic';
8005
+ }
8006
+ return res;
8007
+ }
8008
+ function parseColor(element, styleGetter) {
8009
+ var cssColor = realColor(element, styleGetter);
8010
+ if (!cssColor)
8011
+ return null;
8012
+ var rgba = cssColor.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d*\.?\d*))?\)$/);
8013
+ if (!rgba || !Array.isArray(rgba)) {
8014
+ return null;
8015
+ }
8016
+ var color = [
8017
+ parseInt(rgba[1]),
8018
+ parseInt(rgba[2]),
8019
+ parseInt(rgba[3]),
8020
+ ];
8021
+ var alpha = parseInt(rgba[4]);
8022
+ if (alpha === 0 || isNaN(color[0]) || isNaN(color[1]) || isNaN(color[2])) {
8023
+ return null;
8024
+ }
8025
+ return color;
8026
+ }
8027
+ function realColor(elem, styleGetter) {
8028
+ var bg = styleGetter(elem);
8029
+ if (bg === 'rgba(0, 0, 0, 0)' ||
8030
+ bg === 'transparent' ||
8031
+ bg === 'initial' ||
8032
+ bg === 'inherit') {
8033
+ if (elem.parentElement == null) {
8034
+ return null;
8035
+ }
8036
+ return realColor(elem.parentElement, styleGetter);
8037
+ }
8038
+ else {
8039
+ return bg;
8040
+ }
8041
+ }
8042
+ function parsePadding(style, scaleFactor) {
8043
+ var val = [
8044
+ style.paddingTop,
8045
+ style.paddingRight,
8046
+ style.paddingBottom,
8047
+ style.paddingLeft,
8048
+ ];
8049
+ var pxScaleFactor = 96 / (72 / scaleFactor);
8050
+ var linePadding = (parseInt(style.lineHeight) - parseInt(style.fontSize)) / scaleFactor / 2;
8051
+ var inputPadding = val.map(function (n) {
8052
+ return parseInt(n || '0') / pxScaleFactor;
8053
+ });
8054
+ var padding = parseSpacing(inputPadding, 0);
8055
+ if (linePadding > padding.top) {
8056
+ padding.top = linePadding;
8057
+ }
8058
+ if (linePadding > padding.bottom) {
8059
+ padding.bottom = linePadding;
8060
+ }
8061
+ return padding;
8062
+ }
8063
+
8064
+ function parseHtml(doc, input, window, includeHiddenHtml, useCss) {
8065
+ var _a, _b;
8066
+ if (includeHiddenHtml === void 0) { includeHiddenHtml = false; }
8067
+ if (useCss === void 0) { useCss = false; }
8068
+ var tableElement;
8069
+ if (typeof input === 'string') {
8070
+ tableElement = window.document.querySelector(input);
8071
+ }
8072
+ else {
8073
+ tableElement = input;
8074
+ }
8075
+ var supportedFonts = Object.keys(doc.getFontList());
8076
+ var scaleFactor = doc.scaleFactor();
8077
+ var head = [], body = [], foot = [];
8078
+ if (!tableElement) {
8079
+ console.error('Html table could not be found with input: ', input);
8080
+ return { head: head, body: body, foot: foot };
8081
+ }
8082
+ for (var i = 0; i < tableElement.rows.length; i++) {
8083
+ var element = tableElement.rows[i];
8084
+ var tagName = (_b = (_a = element === null || element === void 0 ? void 0 : element.parentElement) === null || _a === void 0 ? void 0 : _a.tagName) === null || _b === void 0 ? void 0 : _b.toLowerCase();
8085
+ var row = parseRowContent(supportedFonts, scaleFactor, window, element, includeHiddenHtml, useCss);
8086
+ if (!row)
8087
+ continue;
8088
+ if (tagName === 'thead') {
8089
+ head.push(row);
8090
+ }
8091
+ else if (tagName === 'tfoot') {
8092
+ foot.push(row);
8093
+ }
8094
+ else {
8095
+ // Add to body both if parent is tbody or table
8096
+ body.push(row);
8097
+ }
8098
+ }
8099
+ return { head: head, body: body, foot: foot };
8100
+ }
8101
+ function parseRowContent(supportedFonts, scaleFactor, window, row, includeHidden, useCss) {
8102
+ var resultRow = new HtmlRowInput(row);
8103
+ for (var i = 0; i < row.cells.length; i++) {
8104
+ var cell = row.cells[i];
8105
+ var style_1 = window.getComputedStyle(cell);
8106
+ if (includeHidden || style_1.display !== 'none') {
8107
+ var cellStyles = void 0;
8108
+ if (useCss) {
8109
+ cellStyles = parseCss(supportedFonts, cell, scaleFactor, style_1, window);
8110
+ }
8111
+ resultRow.push({
8112
+ rowSpan: cell.rowSpan,
8113
+ colSpan: cell.colSpan,
8114
+ styles: cellStyles,
8115
+ _element: cell,
8116
+ content: parseCellContent(cell),
8117
+ });
8118
+ }
8119
+ }
8120
+ var style = window.getComputedStyle(row);
8121
+ if (resultRow.length > 0 && (includeHidden || style.display !== 'none')) {
8122
+ return resultRow;
8123
+ }
8124
+ }
8125
+ function parseCellContent(orgCell) {
8126
+ // Work on cloned node to make sure no changes are applied to html table
8127
+ var cell = orgCell.cloneNode(true);
8128
+ // Remove extra space and line breaks in markup to make it more similar to
8129
+ // what would be shown in html
8130
+ cell.innerHTML = cell.innerHTML.replace(/\n/g, '').replace(/ +/g, ' ');
8131
+ // Preserve <br> tags as line breaks in the pdf
8132
+ cell.innerHTML = cell.innerHTML
8133
+ .split(/<br.*?>/) //start with '<br' and ends with '>'.
8134
+ .map(function (part) { return part.trim(); })
8135
+ .join('\n');
8136
+ // innerText for ie
8137
+ return cell.innerText || cell.textContent || '';
8138
+ }
8139
+
8140
+ function validateInput(global, document, current) {
8141
+ for (var _i = 0, _a = [global, document, current]; _i < _a.length; _i++) {
8142
+ var options = _a[_i];
8143
+ if (options && typeof options !== 'object') {
8144
+ console.error('The options parameter should be of type object, is: ' + typeof options);
8145
+ }
8146
+ if (options.startY && typeof options.startY !== 'number') {
8147
+ console.error('Invalid value for startY option', options.startY);
8148
+ delete options.startY;
8149
+ }
8150
+ }
8151
+ }
8152
+
8153
+ /* eslint-disable @typescript-eslint/no-unused-vars */
8154
+ // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign
8155
+ function assign(target, s, s1, s2, s3) {
8156
+ if (target == null) {
8157
+ throw new TypeError('Cannot convert undefined or null to object');
8158
+ }
8159
+ var to = Object(target);
8160
+ for (var index = 1; index < arguments.length; index++) {
8161
+ // eslint-disable-next-line prefer-rest-params
8162
+ var nextSource = arguments[index];
8163
+ if (nextSource != null) {
8164
+ // Skip over if undefined or null
8165
+ for (var nextKey in nextSource) {
8166
+ // Avoid bugs when hasOwnProperty is shadowed
8167
+ if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
8168
+ to[nextKey] = nextSource[nextKey];
8169
+ }
8170
+ }
8171
+ }
8172
+ }
8173
+ return to;
8174
+ }
8175
+
8176
+ function parseInput(d, current) {
8177
+ var doc = new DocHandler(d);
8178
+ var document = doc.getDocumentOptions();
8179
+ var global = doc.getGlobalOptions();
8180
+ validateInput(global, document, current);
8181
+ var options = assign({}, global, document, current);
8182
+ var win;
8183
+ if (typeof window !== 'undefined') {
8184
+ win = window;
8185
+ }
8186
+ var styles = parseStyles(global, document, current);
8187
+ var hooks = parseHooks(global, document, current);
8188
+ var settings = parseSettings(doc, options);
8189
+ var content = parseContent$1(doc, options, win);
8190
+ return { id: current.tableId, content: content, hooks: hooks, styles: styles, settings: settings };
8191
+ }
8192
+ function parseStyles(gInput, dInput, cInput) {
8193
+ var styleOptions = {
8194
+ styles: {},
8195
+ headStyles: {},
8196
+ bodyStyles: {},
8197
+ footStyles: {},
8198
+ alternateRowStyles: {},
8199
+ columnStyles: {},
8200
+ };
8201
+ var _loop_1 = function (prop) {
8202
+ if (prop === 'columnStyles') {
8203
+ var global = gInput[prop];
8204
+ var document_1 = dInput[prop];
8205
+ var current = cInput[prop];
8206
+ styleOptions.columnStyles = assign({}, global, document_1, current);
8207
+ }
8208
+ else {
8209
+ var allOptions = [gInput, dInput, cInput];
8210
+ var styles = allOptions.map(function (opts) { return opts[prop] || {}; });
8211
+ styleOptions[prop] = assign({}, styles[0], styles[1], styles[2]);
8212
+ }
8213
+ };
8214
+ for (var _i = 0, _a = Object.keys(styleOptions); _i < _a.length; _i++) {
8215
+ var prop = _a[_i];
8216
+ _loop_1(prop);
8217
+ }
8218
+ return styleOptions;
8219
+ }
8220
+ function parseHooks(global, document, current) {
8221
+ var allOptions = [global, document, current];
8222
+ var result = {
8223
+ didParseCell: [],
8224
+ willDrawCell: [],
8225
+ didDrawCell: [],
8226
+ willDrawPage: [],
8227
+ didDrawPage: [],
8228
+ };
8229
+ for (var _i = 0, allOptions_1 = allOptions; _i < allOptions_1.length; _i++) {
8230
+ var options = allOptions_1[_i];
8231
+ if (options.didParseCell)
8232
+ result.didParseCell.push(options.didParseCell);
8233
+ if (options.willDrawCell)
8234
+ result.willDrawCell.push(options.willDrawCell);
8235
+ if (options.didDrawCell)
8236
+ result.didDrawCell.push(options.didDrawCell);
8237
+ if (options.willDrawPage)
8238
+ result.willDrawPage.push(options.willDrawPage);
8239
+ if (options.didDrawPage)
8240
+ result.didDrawPage.push(options.didDrawPage);
8241
+ }
8242
+ return result;
8243
+ }
8244
+ function parseSettings(doc, options) {
8245
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
8246
+ var margin = parseSpacing(options.margin, 40 / doc.scaleFactor());
8247
+ var startY = (_a = getStartY(doc, options.startY)) !== null && _a !== void 0 ? _a : margin.top;
8248
+ var showFoot;
8249
+ if (options.showFoot === true) {
8250
+ showFoot = 'everyPage';
8251
+ }
8252
+ else if (options.showFoot === false) {
8253
+ showFoot = 'never';
8254
+ }
8255
+ else {
8256
+ showFoot = (_b = options.showFoot) !== null && _b !== void 0 ? _b : 'everyPage';
8257
+ }
8258
+ var showHead;
8259
+ if (options.showHead === true) {
8260
+ showHead = 'everyPage';
8261
+ }
8262
+ else if (options.showHead === false) {
8263
+ showHead = 'never';
8264
+ }
8265
+ else {
8266
+ showHead = (_c = options.showHead) !== null && _c !== void 0 ? _c : 'everyPage';
8267
+ }
8268
+ var useCss = (_d = options.useCss) !== null && _d !== void 0 ? _d : false;
8269
+ var theme = options.theme || (useCss ? 'plain' : 'striped');
8270
+ var horizontalPageBreak = !!options.horizontalPageBreak;
8271
+ var horizontalPageBreakRepeat = (_e = options.horizontalPageBreakRepeat) !== null && _e !== void 0 ? _e : null;
8272
+ return {
8273
+ includeHiddenHtml: (_f = options.includeHiddenHtml) !== null && _f !== void 0 ? _f : false,
8274
+ useCss: useCss,
8275
+ theme: theme,
8276
+ startY: startY,
8277
+ margin: margin,
8278
+ pageBreak: (_g = options.pageBreak) !== null && _g !== void 0 ? _g : 'auto',
8279
+ rowPageBreak: (_h = options.rowPageBreak) !== null && _h !== void 0 ? _h : 'auto',
8280
+ tableWidth: (_j = options.tableWidth) !== null && _j !== void 0 ? _j : 'auto',
8281
+ showHead: showHead,
8282
+ showFoot: showFoot,
8283
+ tableLineWidth: (_k = options.tableLineWidth) !== null && _k !== void 0 ? _k : 0,
8284
+ tableLineColor: (_l = options.tableLineColor) !== null && _l !== void 0 ? _l : 200,
8285
+ horizontalPageBreak: horizontalPageBreak,
8286
+ horizontalPageBreakRepeat: horizontalPageBreakRepeat,
8287
+ horizontalPageBreakBehaviour: (_m = options.horizontalPageBreakBehaviour) !== null && _m !== void 0 ? _m : 'afterAllRows',
8288
+ };
8289
+ }
8290
+ function getStartY(doc, userStartY) {
8291
+ var previous = doc.getLastAutoTable();
8292
+ var sf = doc.scaleFactor();
8293
+ var currentPage = doc.pageNumber();
8294
+ var isSamePageAsPreviousTable = false;
8295
+ if (previous && previous.startPageNumber) {
8296
+ var endingPage = previous.startPageNumber + previous.pageNumber - 1;
8297
+ isSamePageAsPreviousTable = endingPage === currentPage;
8298
+ }
8299
+ if (typeof userStartY === 'number') {
8300
+ return userStartY;
8301
+ }
8302
+ else if (userStartY == null || userStartY === false) {
8303
+ if (isSamePageAsPreviousTable && (previous === null || previous === void 0 ? void 0 : previous.finalY) != null) {
8304
+ // Some users had issues with overlapping tables when they used multiple
8305
+ // tables without setting startY so setting it here to a sensible default.
8306
+ return previous.finalY + 20 / sf;
8307
+ }
8308
+ }
8309
+ return null;
8310
+ }
8311
+ function parseContent$1(doc, options, window) {
8312
+ var head = options.head || [];
8313
+ var body = options.body || [];
8314
+ var foot = options.foot || [];
8315
+ if (options.html) {
8316
+ var hidden = options.includeHiddenHtml;
8317
+ if (window) {
8318
+ var htmlContent = parseHtml(doc, options.html, window, hidden, options.useCss) || {};
8319
+ head = htmlContent.head || head;
8320
+ body = htmlContent.body || head;
8321
+ foot = htmlContent.foot || head;
8322
+ }
8323
+ else {
8324
+ console.error('Cannot parse html in non browser environment');
8325
+ }
8326
+ }
8327
+ var columns = options.columns || parseColumns(head, body, foot);
8328
+ return { columns: columns, head: head, body: body, foot: foot };
8329
+ }
8330
+ function parseColumns(head, body, foot) {
8331
+ var firstRow = head[0] || body[0] || foot[0] || [];
8332
+ var result = [];
8333
+ Object.keys(firstRow)
8334
+ .filter(function (key) { return key !== '_element'; })
8335
+ .forEach(function (key) {
8336
+ var colSpan = 1;
8337
+ var input;
8338
+ if (Array.isArray(firstRow)) {
8339
+ input = firstRow[parseInt(key)];
8340
+ }
8341
+ else {
8342
+ input = firstRow[key];
8343
+ }
8344
+ if (typeof input === 'object' && !Array.isArray(input)) {
8345
+ colSpan = (input === null || input === void 0 ? void 0 : input.colSpan) || 1;
8346
+ }
8347
+ for (var i = 0; i < colSpan; i++) {
8348
+ var id = void 0;
8349
+ if (Array.isArray(firstRow)) {
8350
+ id = result.length;
8351
+ }
8352
+ else {
8353
+ id = key + (i > 0 ? "_".concat(i) : '');
8354
+ }
8355
+ var rowResult = { dataKey: id };
8356
+ result.push(rowResult);
8357
+ }
8358
+ });
8359
+ return result;
8360
+ }
8361
+
8362
+ var HookData = /** @class */ (function () {
8363
+ function HookData(doc, table, cursor) {
8364
+ this.table = table;
8365
+ this.pageNumber = table.pageNumber;
8366
+ this.settings = table.settings;
8367
+ this.cursor = cursor;
8368
+ this.doc = doc.getDocument();
8369
+ }
8370
+ return HookData;
8371
+ }());
8372
+ var CellHookData = /** @class */ (function (_super) {
8373
+ __extends(CellHookData, _super);
8374
+ function CellHookData(doc, table, cell, row, column, cursor) {
8375
+ var _this = _super.call(this, doc, table, cursor) || this;
8376
+ _this.cell = cell;
8377
+ _this.row = row;
8378
+ _this.column = column;
8379
+ _this.section = row.section;
8380
+ return _this;
8381
+ }
8382
+ return CellHookData;
8383
+ }(HookData));
8384
+
8385
+ var Table = /** @class */ (function () {
8386
+ function Table(input, content) {
8387
+ this.pageNumber = 1;
8388
+ this.id = input.id;
8389
+ this.settings = input.settings;
8390
+ this.styles = input.styles;
8391
+ this.hooks = input.hooks;
8392
+ this.columns = content.columns;
8393
+ this.head = content.head;
8394
+ this.body = content.body;
8395
+ this.foot = content.foot;
8396
+ }
8397
+ Table.prototype.getHeadHeight = function (columns) {
8398
+ return this.head.reduce(function (acc, row) { return acc + row.getMaxCellHeight(columns); }, 0);
8399
+ };
8400
+ Table.prototype.getFootHeight = function (columns) {
8401
+ return this.foot.reduce(function (acc, row) { return acc + row.getMaxCellHeight(columns); }, 0);
8402
+ };
8403
+ Table.prototype.allRows = function () {
8404
+ return this.head.concat(this.body).concat(this.foot);
8405
+ };
8406
+ Table.prototype.callCellHooks = function (doc, handlers, cell, row, column, cursor) {
8407
+ for (var _i = 0, handlers_1 = handlers; _i < handlers_1.length; _i++) {
8408
+ var handler = handlers_1[_i];
8409
+ var data = new CellHookData(doc, this, cell, row, column, cursor);
8410
+ var result = handler(data) === false;
8411
+ // Make sure text is always string[] since user can assign string
8412
+ cell.text = Array.isArray(cell.text) ? cell.text : [cell.text];
8413
+ if (result) {
8414
+ return false;
8415
+ }
8416
+ }
8417
+ return true;
8418
+ };
8419
+ Table.prototype.callEndPageHooks = function (doc, cursor) {
8420
+ doc.applyStyles(doc.userStyles);
8421
+ for (var _i = 0, _a = this.hooks.didDrawPage; _i < _a.length; _i++) {
8422
+ var handler = _a[_i];
8423
+ handler(new HookData(doc, this, cursor));
8424
+ }
8425
+ };
8426
+ Table.prototype.callWillDrawPageHooks = function (doc, cursor) {
8427
+ for (var _i = 0, _a = this.hooks.willDrawPage; _i < _a.length; _i++) {
8428
+ var handler = _a[_i];
8429
+ handler(new HookData(doc, this, cursor));
8430
+ }
8431
+ };
8432
+ Table.prototype.getWidth = function (pageWidth) {
8433
+ if (typeof this.settings.tableWidth === 'number') {
8434
+ return this.settings.tableWidth;
8435
+ }
8436
+ else if (this.settings.tableWidth === 'wrap') {
8437
+ var wrappedWidth = this.columns.reduce(function (total, col) { return total + col.wrappedWidth; }, 0);
8438
+ return wrappedWidth;
8439
+ }
8440
+ else {
8441
+ var margin = this.settings.margin;
8442
+ return pageWidth - margin.left - margin.right;
8443
+ }
8444
+ };
8445
+ return Table;
8446
+ }());
8447
+ var Row = /** @class */ (function () {
8448
+ function Row(raw, index, section, cells, spansMultiplePages) {
8449
+ if (spansMultiplePages === void 0) { spansMultiplePages = false; }
8450
+ this.height = 0;
8451
+ this.raw = raw;
8452
+ if (raw instanceof HtmlRowInput) {
8453
+ this.raw = raw._element;
8454
+ this.element = raw._element;
8455
+ }
8456
+ this.index = index;
8457
+ this.section = section;
8458
+ this.cells = cells;
8459
+ this.spansMultiplePages = spansMultiplePages;
8460
+ }
8461
+ Row.prototype.getMaxCellHeight = function (columns) {
8462
+ var _this = this;
8463
+ return columns.reduce(function (acc, column) { var _a; return Math.max(acc, ((_a = _this.cells[column.index]) === null || _a === void 0 ? void 0 : _a.height) || 0); }, 0);
8464
+ };
8465
+ Row.prototype.hasRowSpan = function (columns) {
8466
+ var _this = this;
8467
+ return (columns.filter(function (column) {
8468
+ var cell = _this.cells[column.index];
8469
+ if (!cell)
8470
+ return false;
8471
+ return cell.rowSpan > 1;
8472
+ }).length > 0);
8473
+ };
8474
+ Row.prototype.canEntireRowFit = function (height, columns) {
8475
+ return this.getMaxCellHeight(columns) <= height;
8476
+ };
8477
+ Row.prototype.getMinimumRowHeight = function (columns, doc) {
8478
+ var _this = this;
8479
+ return columns.reduce(function (acc, column) {
8480
+ var cell = _this.cells[column.index];
8481
+ if (!cell)
8482
+ return 0;
8483
+ var lineHeight = doc.getLineHeight(cell.styles.fontSize);
8484
+ var vPadding = cell.padding('vertical');
8485
+ var oneRowHeight = vPadding + lineHeight;
8486
+ return oneRowHeight > acc ? oneRowHeight : acc;
8487
+ }, 0);
8488
+ };
8489
+ return Row;
8490
+ }());
8491
+ var Cell = /** @class */ (function () {
8492
+ function Cell(raw, styles, section) {
8493
+ var _a;
8494
+ this.contentHeight = 0;
8495
+ this.contentWidth = 0;
8496
+ this.wrappedWidth = 0;
8497
+ this.minReadableWidth = 0;
8498
+ this.minWidth = 0;
8499
+ this.width = 0;
8500
+ this.height = 0;
8501
+ this.x = 0;
8502
+ this.y = 0;
8503
+ this.styles = styles;
8504
+ this.section = section;
8505
+ this.raw = raw;
8506
+ var content = raw;
8507
+ if (raw != null && typeof raw === 'object' && !Array.isArray(raw)) {
8508
+ this.rowSpan = raw.rowSpan || 1;
8509
+ this.colSpan = raw.colSpan || 1;
8510
+ content = (_a = raw.content) !== null && _a !== void 0 ? _a : raw;
8511
+ if (raw._element) {
8512
+ this.raw = raw._element;
8513
+ }
8514
+ }
8515
+ else {
8516
+ this.rowSpan = 1;
8517
+ this.colSpan = 1;
8518
+ }
8519
+ // Stringify 0 and false, but not undefined or null
8520
+ var text = content != null ? '' + content : '';
8521
+ var splitRegex = /\r\n|\r|\n/g;
8522
+ this.text = text.split(splitRegex);
8523
+ }
8524
+ Cell.prototype.getTextPos = function () {
8525
+ var y;
8526
+ if (this.styles.valign === 'top') {
8527
+ y = this.y + this.padding('top');
8528
+ }
8529
+ else if (this.styles.valign === 'bottom') {
8530
+ y = this.y + this.height - this.padding('bottom');
8531
+ }
8532
+ else {
8533
+ var netHeight = this.height - this.padding('vertical');
8534
+ y = this.y + netHeight / 2 + this.padding('top');
8535
+ }
8536
+ var x;
8537
+ if (this.styles.halign === 'right') {
8538
+ x = this.x + this.width - this.padding('right');
8539
+ }
8540
+ else if (this.styles.halign === 'center') {
8541
+ var netWidth = this.width - this.padding('horizontal');
8542
+ x = this.x + netWidth / 2 + this.padding('left');
8543
+ }
8544
+ else {
8545
+ x = this.x + this.padding('left');
8546
+ }
8547
+ return { x: x, y: y };
8548
+ };
8549
+ // TODO (v4): replace parameters with only (lineHeight)
8550
+ Cell.prototype.getContentHeight = function (scaleFactor, lineHeightFactor) {
8551
+ if (lineHeightFactor === void 0) { lineHeightFactor = 1.15; }
8552
+ var lineCount = Array.isArray(this.text) ? this.text.length : 1;
8553
+ var lineHeight = (this.styles.fontSize / scaleFactor) * lineHeightFactor;
8554
+ var height = lineCount * lineHeight + this.padding('vertical');
8555
+ return Math.max(height, this.styles.minCellHeight);
8556
+ };
8557
+ Cell.prototype.padding = function (name) {
8558
+ var padding = parseSpacing(this.styles.cellPadding, 0);
8559
+ if (name === 'vertical') {
8560
+ return padding.top + padding.bottom;
8561
+ }
8562
+ else if (name === 'horizontal') {
8563
+ return padding.left + padding.right;
8564
+ }
8565
+ else {
8566
+ return padding[name];
8567
+ }
8568
+ };
8569
+ return Cell;
8570
+ }());
8571
+ var Column = /** @class */ (function () {
8572
+ function Column(dataKey, raw, index) {
8573
+ this.wrappedWidth = 0;
8574
+ this.minReadableWidth = 0;
8575
+ this.minWidth = 0;
8576
+ this.width = 0;
8577
+ this.dataKey = dataKey;
8578
+ this.raw = raw;
8579
+ this.index = index;
8580
+ }
8581
+ Column.prototype.getMaxCustomCellWidth = function (table) {
8582
+ var max = 0;
8583
+ for (var _i = 0, _a = table.allRows(); _i < _a.length; _i++) {
8584
+ var row = _a[_i];
8585
+ var cell = row.cells[this.index];
8586
+ if (cell && typeof cell.styles.cellWidth === 'number') {
8587
+ max = Math.max(max, cell.styles.cellWidth);
8588
+ }
8589
+ }
8590
+ return max;
8591
+ };
8592
+ return Column;
8593
+ }());
8594
+
8595
+ /**
8596
+ * Calculate the column widths
8597
+ */
8598
+ function calculateWidths(doc, table) {
8599
+ calculate(doc, table);
8600
+ var resizableColumns = [];
8601
+ var initialTableWidth = 0;
8602
+ table.columns.forEach(function (column) {
8603
+ var customWidth = column.getMaxCustomCellWidth(table);
8604
+ if (customWidth) {
8605
+ // final column width
8606
+ column.width = customWidth;
8607
+ }
8608
+ else {
8609
+ // initial column width (will be resized)
8610
+ column.width = column.wrappedWidth;
8611
+ resizableColumns.push(column);
8612
+ }
8613
+ initialTableWidth += column.width;
8614
+ });
8615
+ // width difference that needs to be distributed
8616
+ var resizeWidth = table.getWidth(doc.pageSize().width) - initialTableWidth;
8617
+ // first resize attempt: with respect to minReadableWidth and minWidth
8618
+ if (resizeWidth) {
8619
+ resizeWidth = resizeColumns(resizableColumns, resizeWidth, function (column) {
8620
+ return Math.max(column.minReadableWidth, column.minWidth);
8621
+ });
8622
+ }
8623
+ // second resize attempt: ignore minReadableWidth but respect minWidth
8624
+ if (resizeWidth) {
8625
+ resizeWidth = resizeColumns(resizableColumns, resizeWidth, function (column) { return column.minWidth; });
8626
+ }
8627
+ resizeWidth = Math.abs(resizeWidth);
8628
+ if (!table.settings.horizontalPageBreak &&
8629
+ resizeWidth > 0.1 / doc.scaleFactor()) {
8630
+ // Table can't get smaller due to custom-width or minWidth restrictions
8631
+ // We can't really do much here. Up to user to for example
8632
+ // reduce font size, increase page size or remove custom cell widths
8633
+ // to allow more columns to be reduced in size
8634
+ resizeWidth = resizeWidth < 1 ? resizeWidth : Math.round(resizeWidth);
8635
+ console.log("Of the table content, ".concat(resizeWidth, " units width could not fit page"));
8636
+ }
8637
+ applyColSpans(table);
8638
+ fitContent(table, doc);
8639
+ applyRowSpans(table);
8640
+ }
8641
+ function calculate(doc, table) {
8642
+ var sf = doc.scaleFactor();
8643
+ var horizontalPageBreak = table.settings.horizontalPageBreak;
8644
+ var availablePageWidth = getPageAvailableWidth(doc, table);
8645
+ table.allRows().forEach(function (row) {
8646
+ for (var _i = 0, _a = table.columns; _i < _a.length; _i++) {
8647
+ var column = _a[_i];
8648
+ var cell = row.cells[column.index];
8649
+ if (!cell)
8650
+ continue;
8651
+ var hooks = table.hooks.didParseCell;
8652
+ table.callCellHooks(doc, hooks, cell, row, column, null);
8653
+ var padding = cell.padding('horizontal');
8654
+ cell.contentWidth = getStringWidth(cell.text, cell.styles, doc) + padding;
8655
+ // Using [^\S\u00A0] instead of \s ensures that we split the text on all
8656
+ // whitespace except non-breaking spaces (\u00A0). We need to preserve
8657
+ // them in the split process to ensure correct word separation and width
8658
+ // calculation.
8659
+ var longestWordWidth = getStringWidth(cell.text.join(' ').split(/[^\S\u00A0]+/), cell.styles, doc);
8660
+ cell.minReadableWidth = longestWordWidth + cell.padding('horizontal');
8661
+ if (typeof cell.styles.cellWidth === 'number') {
8662
+ cell.minWidth = cell.styles.cellWidth;
8663
+ cell.wrappedWidth = cell.styles.cellWidth;
8664
+ }
8665
+ else if (cell.styles.cellWidth === 'wrap' ||
8666
+ horizontalPageBreak === true) {
8667
+ // cell width should not be more than available page width
8668
+ if (cell.contentWidth > availablePageWidth) {
8669
+ cell.minWidth = availablePageWidth;
8670
+ cell.wrappedWidth = availablePageWidth;
8671
+ }
8672
+ else {
8673
+ cell.minWidth = cell.contentWidth;
8674
+ cell.wrappedWidth = cell.contentWidth;
8675
+ }
8676
+ }
8677
+ else {
8678
+ // auto
8679
+ var defaultMinWidth = 10 / sf;
8680
+ cell.minWidth = cell.styles.minCellWidth || defaultMinWidth;
8681
+ cell.wrappedWidth = cell.contentWidth;
8682
+ if (cell.minWidth > cell.wrappedWidth) {
8683
+ cell.wrappedWidth = cell.minWidth;
8684
+ }
8685
+ }
8686
+ }
8687
+ });
8688
+ table.allRows().forEach(function (row) {
8689
+ for (var _i = 0, _a = table.columns; _i < _a.length; _i++) {
8690
+ var column = _a[_i];
8691
+ var cell = row.cells[column.index];
8692
+ // For now we ignore the minWidth and wrappedWidth of colspan cells when calculating colspan widths.
8693
+ // Could probably be improved upon however.
8694
+ if (cell && cell.colSpan === 1) {
8695
+ column.wrappedWidth = Math.max(column.wrappedWidth, cell.wrappedWidth);
8696
+ column.minWidth = Math.max(column.minWidth, cell.minWidth);
8697
+ column.minReadableWidth = Math.max(column.minReadableWidth, cell.minReadableWidth);
8698
+ }
8699
+ else {
8700
+ // Respect cellWidth set in columnStyles even if there is no cells for this column
8701
+ // or if the column only have colspan cells. Since the width of colspan cells
8702
+ // does not affect the width of columns, setting columnStyles cellWidth enables the
8703
+ // user to at least do it manually.
8704
+ // Note that this is not perfect for now since for example row and table styles are
8705
+ // not accounted for
8706
+ var columnStyles = table.styles.columnStyles[column.dataKey] ||
8707
+ table.styles.columnStyles[column.index] ||
8708
+ {};
8709
+ var cellWidth = columnStyles.cellWidth || columnStyles.minCellWidth;
8710
+ if (cellWidth && typeof cellWidth === 'number') {
8711
+ column.minWidth = cellWidth;
8712
+ column.wrappedWidth = cellWidth;
8713
+ }
8714
+ }
8715
+ if (cell) {
8716
+ // Make sure all columns get at least min width even though width calculations are not based on them
8717
+ if (cell.colSpan > 1 && !column.minWidth) {
8718
+ column.minWidth = cell.minWidth;
8719
+ }
8720
+ if (cell.colSpan > 1 && !column.wrappedWidth) {
8721
+ column.wrappedWidth = cell.minWidth;
8722
+ }
8723
+ }
8724
+ }
8725
+ });
8726
+ }
8727
+ /**
8728
+ * Distribute resizeWidth on passed resizable columns
8729
+ */
8730
+ function resizeColumns(columns, resizeWidth, getMinWidth) {
8731
+ var initialResizeWidth = resizeWidth;
8732
+ var sumWrappedWidth = columns.reduce(function (acc, column) { return acc + column.wrappedWidth; }, 0);
8733
+ for (var i = 0; i < columns.length; i++) {
8734
+ var column = columns[i];
8735
+ var ratio = column.wrappedWidth / sumWrappedWidth;
8736
+ var suggestedChange = initialResizeWidth * ratio;
8737
+ var suggestedWidth = column.width + suggestedChange;
8738
+ var minWidth = getMinWidth(column);
8739
+ var newWidth = suggestedWidth < minWidth ? minWidth : suggestedWidth;
8740
+ resizeWidth -= newWidth - column.width;
8741
+ column.width = newWidth;
8742
+ }
8743
+ resizeWidth = Math.round(resizeWidth * 1e10) / 1e10;
8744
+ // Run the resizer again if there's remaining width needs
8745
+ // to be distributed and there're columns that can be resized
8746
+ if (resizeWidth) {
8747
+ var resizableColumns = columns.filter(function (column) {
8748
+ return resizeWidth < 0
8749
+ ? column.width > getMinWidth(column) // check if column can shrink
8750
+ : true; // check if column can grow
8751
+ });
8752
+ if (resizableColumns.length) {
8753
+ resizeWidth = resizeColumns(resizableColumns, resizeWidth, getMinWidth);
8754
+ }
8755
+ }
8756
+ return resizeWidth;
8757
+ }
8758
+ function applyRowSpans(table) {
8759
+ var rowSpanCells = {};
8760
+ var colRowSpansLeft = 1;
8761
+ var all = table.allRows();
8762
+ for (var rowIndex = 0; rowIndex < all.length; rowIndex++) {
8763
+ var row = all[rowIndex];
8764
+ for (var _i = 0, _a = table.columns; _i < _a.length; _i++) {
8765
+ var column = _a[_i];
8766
+ var data = rowSpanCells[column.index];
8767
+ if (colRowSpansLeft > 1) {
8768
+ colRowSpansLeft--;
8769
+ delete row.cells[column.index];
8770
+ }
8771
+ else if (data) {
8772
+ data.cell.height += row.height;
8773
+ colRowSpansLeft = data.cell.colSpan;
8774
+ delete row.cells[column.index];
8775
+ data.left--;
8776
+ if (data.left <= 1) {
8777
+ delete rowSpanCells[column.index];
8778
+ }
8779
+ }
8780
+ else {
8781
+ var cell = row.cells[column.index];
8782
+ if (!cell) {
8783
+ continue;
8784
+ }
8785
+ cell.height = row.height;
8786
+ if (cell.rowSpan > 1) {
8787
+ var remaining = all.length - rowIndex;
8788
+ var left = cell.rowSpan > remaining ? remaining : cell.rowSpan;
8789
+ rowSpanCells[column.index] = { cell: cell, left: left, row: row };
8790
+ }
8791
+ }
8792
+ }
8793
+ }
8794
+ }
8795
+ function applyColSpans(table) {
8796
+ var all = table.allRows();
8797
+ for (var rowIndex = 0; rowIndex < all.length; rowIndex++) {
8798
+ var row = all[rowIndex];
8799
+ var colSpanCell = null;
8800
+ var combinedColSpanWidth = 0;
8801
+ var colSpansLeft = 0;
8802
+ for (var columnIndex = 0; columnIndex < table.columns.length; columnIndex++) {
8803
+ var column = table.columns[columnIndex];
8804
+ // Width and colspan
8805
+ colSpansLeft -= 1;
8806
+ if (colSpansLeft > 1 && table.columns[columnIndex + 1]) {
8807
+ combinedColSpanWidth += column.width;
8808
+ delete row.cells[column.index];
8809
+ }
8810
+ else if (colSpanCell) {
8811
+ var cell = colSpanCell;
8812
+ delete row.cells[column.index];
8813
+ colSpanCell = null;
8814
+ cell.width = column.width + combinedColSpanWidth;
8815
+ }
8816
+ else {
8817
+ var cell = row.cells[column.index];
8818
+ if (!cell)
8819
+ continue;
8820
+ colSpansLeft = cell.colSpan;
8821
+ combinedColSpanWidth = 0;
8822
+ if (cell.colSpan > 1) {
8823
+ colSpanCell = cell;
8824
+ combinedColSpanWidth += column.width;
8825
+ continue;
8826
+ }
8827
+ cell.width = column.width + combinedColSpanWidth;
8828
+ }
8829
+ }
8830
+ }
8831
+ }
8832
+ function fitContent(table, doc) {
8833
+ var rowSpanHeight = { count: 0, height: 0 };
8834
+ for (var _i = 0, _a = table.allRows(); _i < _a.length; _i++) {
8835
+ var row = _a[_i];
8836
+ for (var _b = 0, _c = table.columns; _b < _c.length; _b++) {
8837
+ var column = _c[_b];
8838
+ var cell = row.cells[column.index];
8839
+ if (!cell)
8840
+ continue;
8841
+ doc.applyStyles(cell.styles, true);
8842
+ var textSpace = cell.width - cell.padding('horizontal');
8843
+ if (cell.styles.overflow === 'linebreak') {
8844
+ // Add one pt to textSpace to fix rounding error
8845
+ cell.text = doc.splitTextToSize(cell.text, textSpace + 1 / doc.scaleFactor(), { fontSize: cell.styles.fontSize });
8846
+ }
8847
+ else if (cell.styles.overflow === 'ellipsize') {
8848
+ cell.text = ellipsize(cell.text, textSpace, cell.styles, doc, '...');
8849
+ }
8850
+ else if (cell.styles.overflow === 'hidden') {
8851
+ cell.text = ellipsize(cell.text, textSpace, cell.styles, doc, '');
8852
+ }
8853
+ else if (typeof cell.styles.overflow === 'function') {
8854
+ var result = cell.styles.overflow(cell.text, textSpace);
8855
+ if (typeof result === 'string') {
8856
+ cell.text = [result];
8857
+ }
8858
+ else {
8859
+ cell.text = result;
8860
+ }
8861
+ }
8862
+ cell.contentHeight = cell.getContentHeight(doc.scaleFactor(), doc.getLineHeightFactor());
8863
+ var realContentHeight = cell.contentHeight / cell.rowSpan;
8864
+ if (cell.rowSpan > 1 &&
8865
+ rowSpanHeight.count * rowSpanHeight.height <
8866
+ realContentHeight * cell.rowSpan) {
8867
+ rowSpanHeight = { height: realContentHeight, count: cell.rowSpan };
8868
+ }
8869
+ else if (rowSpanHeight && rowSpanHeight.count > 0) {
8870
+ if (rowSpanHeight.height > realContentHeight) {
8871
+ realContentHeight = rowSpanHeight.height;
8872
+ }
8873
+ }
8874
+ if (realContentHeight > row.height) {
8875
+ row.height = realContentHeight;
8876
+ }
8877
+ }
8878
+ rowSpanHeight.count--;
8879
+ }
8880
+ }
8881
+ function ellipsize(text, width, styles, doc, overflow) {
8882
+ return text.map(function (str) { return ellipsizeStr(str, width, styles, doc, overflow); });
8883
+ }
8884
+ function ellipsizeStr(text, width, styles, doc, overflow) {
8885
+ var precision = 10000 * doc.scaleFactor();
8886
+ width = Math.ceil(width * precision) / precision;
8887
+ if (width >= getStringWidth(text, styles, doc)) {
8888
+ return text;
8889
+ }
8890
+ while (width < getStringWidth(text + overflow, styles, doc)) {
8891
+ if (text.length <= 1) {
8892
+ break;
8893
+ }
8894
+ text = text.substring(0, text.length - 1);
8895
+ }
8896
+ return text.trim() + overflow;
8897
+ }
8898
+
8899
+ function createTable(jsPDFDoc, input) {
8900
+ var doc = new DocHandler(jsPDFDoc);
8901
+ var content = parseContent(input, doc.scaleFactor());
8902
+ var table = new Table(input, content);
8903
+ calculateWidths(doc, table);
8904
+ doc.applyStyles(doc.userStyles);
8905
+ return table;
8906
+ }
8907
+ function parseContent(input, sf) {
8908
+ var content = input.content;
8909
+ var columns = createColumns(content.columns);
8910
+ // If no head or foot is set, try generating it with content from columns
8911
+ if (content.head.length === 0) {
8912
+ var sectionRow = generateSectionRow(columns, 'head');
8913
+ if (sectionRow)
8914
+ content.head.push(sectionRow);
8915
+ }
8916
+ if (content.foot.length === 0) {
8917
+ var sectionRow = generateSectionRow(columns, 'foot');
8918
+ if (sectionRow)
8919
+ content.foot.push(sectionRow);
8920
+ }
8921
+ var theme = input.settings.theme;
8922
+ var styles = input.styles;
8923
+ return {
8924
+ columns: columns,
8925
+ head: parseSection('head', content.head, columns, styles, theme, sf),
8926
+ body: parseSection('body', content.body, columns, styles, theme, sf),
8927
+ foot: parseSection('foot', content.foot, columns, styles, theme, sf),
8928
+ };
8929
+ }
8930
+ function parseSection(sectionName, sectionRows, columns, styleProps, theme, scaleFactor) {
8931
+ var rowSpansLeftForColumn = {};
8932
+ var result = sectionRows.map(function (rawRow, rowIndex) {
8933
+ var skippedRowForRowSpans = 0;
8934
+ var cells = {};
8935
+ var colSpansAdded = 0;
8936
+ var columnSpansLeft = 0;
8937
+ for (var _i = 0, columns_1 = columns; _i < columns_1.length; _i++) {
8938
+ var column = columns_1[_i];
8939
+ if (rowSpansLeftForColumn[column.index] == null ||
8940
+ rowSpansLeftForColumn[column.index].left === 0) {
8941
+ if (columnSpansLeft === 0) {
8942
+ var rawCell = void 0;
8943
+ if (Array.isArray(rawRow)) {
8944
+ rawCell =
8945
+ rawRow[column.index - colSpansAdded - skippedRowForRowSpans];
8946
+ }
8947
+ else {
8948
+ rawCell = rawRow[column.dataKey];
8949
+ }
8950
+ var cellInputStyles = {};
8951
+ if (typeof rawCell === 'object' && !Array.isArray(rawCell)) {
8952
+ cellInputStyles = (rawCell === null || rawCell === void 0 ? void 0 : rawCell.styles) || {};
8953
+ }
8954
+ var styles = cellStyles(sectionName, column, rowIndex, theme, styleProps, scaleFactor, cellInputStyles);
8955
+ var cell = new Cell(rawCell, styles, sectionName);
8956
+ // dataKey is not used internally no more but keep for
8957
+ // backwards compat in hooks
8958
+ cells[column.dataKey] = cell;
8959
+ cells[column.index] = cell;
8960
+ columnSpansLeft = cell.colSpan - 1;
8961
+ rowSpansLeftForColumn[column.index] = {
8962
+ left: cell.rowSpan - 1,
8963
+ times: columnSpansLeft,
8964
+ };
8965
+ }
8966
+ else {
8967
+ columnSpansLeft--;
8968
+ colSpansAdded++;
8969
+ }
8970
+ }
8971
+ else {
8972
+ rowSpansLeftForColumn[column.index].left--;
8973
+ columnSpansLeft = rowSpansLeftForColumn[column.index].times;
8974
+ skippedRowForRowSpans++;
8975
+ }
8976
+ }
8977
+ return new Row(rawRow, rowIndex, sectionName, cells);
8978
+ });
8979
+ return result;
8980
+ }
8981
+ function generateSectionRow(columns, section) {
8982
+ var sectionRow = {};
8983
+ columns.forEach(function (col) {
8984
+ if (col.raw != null) {
8985
+ var title = getSectionTitle(section, col.raw);
8986
+ if (title != null)
8987
+ sectionRow[col.dataKey] = title;
8988
+ }
8989
+ });
8990
+ return Object.keys(sectionRow).length > 0 ? sectionRow : null;
8991
+ }
8992
+ function getSectionTitle(section, column) {
8993
+ if (section === 'head') {
8994
+ if (typeof column === 'object') {
8995
+ return column.header || null;
8996
+ }
8997
+ else if (typeof column === 'string' || typeof column === 'number') {
8998
+ return column;
8999
+ }
9000
+ }
9001
+ else if (section === 'foot' && typeof column === 'object') {
9002
+ return column.footer;
9003
+ }
9004
+ return null;
9005
+ }
9006
+ function createColumns(columns) {
9007
+ return columns.map(function (input, index) {
9008
+ var _a;
9009
+ var key;
9010
+ if (typeof input === 'object') {
9011
+ key = (_a = input.dataKey) !== null && _a !== void 0 ? _a : index;
9012
+ }
9013
+ else {
9014
+ key = index;
9015
+ }
9016
+ return new Column(key, input, index);
9017
+ });
9018
+ }
9019
+ function cellStyles(sectionName, column, rowIndex, themeName, styles, scaleFactor, cellInputStyles) {
9020
+ var theme = getTheme(themeName);
9021
+ var sectionStyles;
9022
+ if (sectionName === 'head') {
9023
+ sectionStyles = styles.headStyles;
9024
+ }
9025
+ else if (sectionName === 'body') {
9026
+ sectionStyles = styles.bodyStyles;
9027
+ }
9028
+ else if (sectionName === 'foot') {
9029
+ sectionStyles = styles.footStyles;
9030
+ }
9031
+ var otherStyles = assign({}, theme.table, theme[sectionName], styles.styles, sectionStyles);
9032
+ var columnStyles = styles.columnStyles[column.dataKey] ||
9033
+ styles.columnStyles[column.index] ||
9034
+ {};
9035
+ var colStyles = sectionName === 'body' ? columnStyles : {};
9036
+ var rowStyles = sectionName === 'body' && rowIndex % 2 === 0
9037
+ ? assign({}, theme.alternateRow, styles.alternateRowStyles)
9038
+ : {};
9039
+ var defaultStyle = defaultStyles(scaleFactor);
9040
+ var themeStyles = assign({}, defaultStyle, otherStyles, rowStyles, colStyles);
9041
+ return assign(themeStyles, cellInputStyles);
9042
+ }
9043
+
9044
+ // get columns can be fit into page
9045
+ function getColumnsCanFitInPage(doc, table, config) {
9046
+ var _a;
9047
+ if (config === void 0) { config = {}; }
9048
+ // Get page width
9049
+ var remainingWidth = getPageAvailableWidth(doc, table);
9050
+ // Get column data key to repeat
9051
+ var repeatColumnsMap = new Map();
9052
+ var colIndexes = [];
9053
+ var columns = [];
9054
+ var horizontalPageBreakRepeat = [];
9055
+ if (Array.isArray(table.settings.horizontalPageBreakRepeat)) {
9056
+ horizontalPageBreakRepeat = table.settings.horizontalPageBreakRepeat;
9057
+ // It can be a single value of type string or number (even number: 0)
9058
+ }
9059
+ else if (typeof table.settings.horizontalPageBreakRepeat === 'string' ||
9060
+ typeof table.settings.horizontalPageBreakRepeat === 'number') {
9061
+ horizontalPageBreakRepeat = [table.settings.horizontalPageBreakRepeat];
9062
+ }
9063
+ // Code to repeat the given column in split pages
9064
+ horizontalPageBreakRepeat.forEach(function (field) {
9065
+ var col = table.columns.find(function (item) { return item.dataKey === field || item.index === field; });
9066
+ if (col && !repeatColumnsMap.has(col.index)) {
9067
+ repeatColumnsMap.set(col.index, true);
9068
+ colIndexes.push(col.index);
9069
+ columns.push(table.columns[col.index]);
9070
+ remainingWidth -= col.wrappedWidth;
9071
+ }
9072
+ });
9073
+ var first = true;
9074
+ var i = (_a = config === null || config === void 0 ? void 0 : config.start) !== null && _a !== void 0 ? _a : 0; // make sure couter is initiated outside the loop
9075
+ while (i < table.columns.length) {
9076
+ // Prevent duplicates
9077
+ if (repeatColumnsMap.has(i)) {
9078
+ i++;
9079
+ continue;
9080
+ }
9081
+ var colWidth = table.columns[i].wrappedWidth;
9082
+ // Take at least one column even if it doesn't fit
9083
+ if (first || remainingWidth >= colWidth) {
9084
+ first = false;
9085
+ colIndexes.push(i);
9086
+ columns.push(table.columns[i]);
9087
+ remainingWidth -= colWidth;
9088
+ }
9089
+ else {
9090
+ break;
9091
+ }
9092
+ i++;
9093
+ }
9094
+ return { colIndexes: colIndexes, columns: columns, lastIndex: i - 1 };
9095
+ }
9096
+ function calculateAllColumnsCanFitInPage(doc, table) {
9097
+ var allResults = [];
9098
+ for (var i = 0; i < table.columns.length; i++) {
9099
+ var result = getColumnsCanFitInPage(doc, table, { start: i });
9100
+ if (result.columns.length) {
9101
+ allResults.push(result);
9102
+ i = result.lastIndex;
9103
+ }
9104
+ }
9105
+ return allResults;
9106
+ }
9107
+
9108
+ function drawTable(jsPDFDoc, table) {
9109
+ var settings = table.settings;
9110
+ var startY = settings.startY;
9111
+ var margin = settings.margin;
9112
+ var cursor = { x: margin.left, y: startY };
9113
+ var sectionsHeight = table.getHeadHeight(table.columns) + table.getFootHeight(table.columns);
9114
+ var minTableBottomPos = startY + margin.bottom + sectionsHeight;
9115
+ if (settings.pageBreak === 'avoid') {
9116
+ var rows = table.body;
9117
+ var tableHeight = rows.reduce(function (acc, row) { return acc + row.height; }, 0);
9118
+ minTableBottomPos += tableHeight;
9119
+ }
9120
+ var doc = new DocHandler(jsPDFDoc);
9121
+ if (settings.pageBreak === 'always' ||
9122
+ (settings.startY != null && minTableBottomPos > doc.pageSize().height)) {
9123
+ nextPage(doc);
9124
+ cursor.y = margin.top;
9125
+ }
9126
+ table.callWillDrawPageHooks(doc, cursor);
9127
+ var startPos = assign({}, cursor);
9128
+ table.startPageNumber = doc.pageNumber();
9129
+ if (settings.horizontalPageBreak) {
9130
+ // managed flow for split columns
9131
+ printTableWithHorizontalPageBreak(doc, table, startPos, cursor);
9132
+ }
9133
+ else {
9134
+ // normal flow
9135
+ doc.applyStyles(doc.userStyles);
9136
+ if (settings.showHead === 'firstPage' ||
9137
+ settings.showHead === 'everyPage') {
9138
+ table.head.forEach(function (row) {
9139
+ return printRow(doc, table, row, cursor, table.columns);
9140
+ });
9141
+ }
9142
+ doc.applyStyles(doc.userStyles);
9143
+ table.body.forEach(function (row, index) {
9144
+ var isLastRow = index === table.body.length - 1;
9145
+ printFullRow(doc, table, row, isLastRow, startPos, cursor, table.columns);
9146
+ });
9147
+ doc.applyStyles(doc.userStyles);
9148
+ if (settings.showFoot === 'lastPage' || settings.showFoot === 'everyPage') {
9149
+ table.foot.forEach(function (row) {
9150
+ return printRow(doc, table, row, cursor, table.columns);
9151
+ });
9152
+ }
9153
+ }
9154
+ addTableBorder(doc, table, startPos, cursor);
9155
+ table.callEndPageHooks(doc, cursor);
9156
+ table.finalY = cursor.y;
9157
+ jsPDFDoc.lastAutoTable = table;
9158
+ doc.applyStyles(doc.userStyles);
9159
+ }
9160
+ function printTableWithHorizontalPageBreak(doc, table, startPos, cursor) {
9161
+ // calculate width of columns and render only those which can fit into page
9162
+ var allColumnsCanFitResult = calculateAllColumnsCanFitInPage(doc, table);
9163
+ var settings = table.settings;
9164
+ if (settings.horizontalPageBreakBehaviour === 'afterAllRows') {
9165
+ allColumnsCanFitResult.forEach(function (colsAndIndexes, index) {
9166
+ doc.applyStyles(doc.userStyles);
9167
+ // add page to print next columns in new page
9168
+ if (index > 0) {
9169
+ // When adding a page here, make sure not to print the footers
9170
+ // because they were already printed before on this same loop
9171
+ addPage(doc, table, startPos, cursor, colsAndIndexes.columns, true);
9172
+ }
9173
+ else {
9174
+ // print head for selected columns
9175
+ printHead(doc, table, cursor, colsAndIndexes.columns);
9176
+ }
9177
+ // print body & footer for selected columns
9178
+ printBody(doc, table, startPos, cursor, colsAndIndexes.columns);
9179
+ printFoot(doc, table, cursor, colsAndIndexes.columns);
9180
+ });
9181
+ }
9182
+ else {
9183
+ var lastRowIndexOfLastPage_1 = -1;
9184
+ var firstColumnsToFitResult = allColumnsCanFitResult[0];
9185
+ var _loop_1 = function () {
9186
+ // Print the first columns, taking note of the last row printed
9187
+ var lastPrintedRowIndex = lastRowIndexOfLastPage_1;
9188
+ if (firstColumnsToFitResult) {
9189
+ doc.applyStyles(doc.userStyles);
9190
+ var firstColumnsToFit = firstColumnsToFitResult.columns;
9191
+ if (lastRowIndexOfLastPage_1 >= 0) {
9192
+ // When adding a page here, make sure not to print the footers
9193
+ // because they were already printed before on this same loop
9194
+ addPage(doc, table, startPos, cursor, firstColumnsToFit, true);
9195
+ }
9196
+ else {
9197
+ printHead(doc, table, cursor, firstColumnsToFit);
9198
+ }
9199
+ lastPrintedRowIndex = printBodyWithoutPageBreaks(doc, table, lastRowIndexOfLastPage_1 + 1, cursor, firstColumnsToFit);
9200
+ printFoot(doc, table, cursor, firstColumnsToFit);
9201
+ }
9202
+ // Check how many rows were printed, so that the next columns would not print more rows than that
9203
+ var maxNumberOfRows = lastPrintedRowIndex - lastRowIndexOfLastPage_1;
9204
+ // Print the next columns, never exceding maxNumberOfRows
9205
+ allColumnsCanFitResult.slice(1).forEach(function (colsAndIndexes) {
9206
+ doc.applyStyles(doc.userStyles);
9207
+ // When adding a page here, make sure not to print the footers
9208
+ // because they were already printed before on this same loop
9209
+ addPage(doc, table, startPos, cursor, colsAndIndexes.columns, true);
9210
+ printBodyWithoutPageBreaks(doc, table, lastRowIndexOfLastPage_1 + 1, cursor, colsAndIndexes.columns, maxNumberOfRows);
9211
+ printFoot(doc, table, cursor, colsAndIndexes.columns);
9212
+ });
9213
+ lastRowIndexOfLastPage_1 = lastPrintedRowIndex;
9214
+ };
9215
+ while (lastRowIndexOfLastPage_1 < table.body.length - 1) {
9216
+ _loop_1();
9217
+ }
9218
+ }
9219
+ }
9220
+ function printHead(doc, table, cursor, columns) {
9221
+ var settings = table.settings;
9222
+ doc.applyStyles(doc.userStyles);
9223
+ if (settings.showHead === 'firstPage' || settings.showHead === 'everyPage') {
9224
+ table.head.forEach(function (row) { return printRow(doc, table, row, cursor, columns); });
9225
+ }
9226
+ }
9227
+ function printBody(doc, table, startPos, cursor, columns) {
9228
+ doc.applyStyles(doc.userStyles);
9229
+ table.body.forEach(function (row, index) {
9230
+ var isLastRow = index === table.body.length - 1;
9231
+ printFullRow(doc, table, row, isLastRow, startPos, cursor, columns);
9232
+ });
9233
+ }
9234
+ function printBodyWithoutPageBreaks(doc, table, startRowIndex, cursor, columns, maxNumberOfRows) {
9235
+ doc.applyStyles(doc.userStyles);
9236
+ maxNumberOfRows = maxNumberOfRows !== null && maxNumberOfRows !== void 0 ? maxNumberOfRows : table.body.length;
9237
+ var endRowIndex = Math.min(startRowIndex + maxNumberOfRows, table.body.length);
9238
+ var lastPrintedRowIndex = -1;
9239
+ var rows = table.body.slice(startRowIndex, endRowIndex);
9240
+ for (var index = 0; index < rows.length; index++) {
9241
+ var row = rows[index];
9242
+ var isLastRow = startRowIndex + index === table.body.length - 1;
9243
+ var remainingSpace = getRemainingPageSpace(doc, table, isLastRow, cursor);
9244
+ if (row.canEntireRowFit(remainingSpace, columns)) {
9245
+ printRow(doc, table, row, cursor, columns);
9246
+ lastPrintedRowIndex = startRowIndex + index;
9247
+ }
9248
+ else {
9249
+ break;
9250
+ }
9251
+ }
9252
+ return lastPrintedRowIndex;
9253
+ }
9254
+ function printFoot(doc, table, cursor, columns) {
9255
+ var settings = table.settings;
9256
+ doc.applyStyles(doc.userStyles);
9257
+ if (settings.showFoot === 'lastPage' || settings.showFoot === 'everyPage') {
9258
+ table.foot.forEach(function (row) { return printRow(doc, table, row, cursor, columns); });
9259
+ }
9260
+ }
9261
+ function getRemainingLineCount(cell, remainingPageSpace, doc) {
9262
+ var lineHeight = doc.getLineHeight(cell.styles.fontSize);
9263
+ var vPadding = cell.padding('vertical');
9264
+ var remainingLines = Math.floor((remainingPageSpace - vPadding) / lineHeight);
9265
+ return Math.max(0, remainingLines);
9266
+ }
9267
+ function modifyRowToFit(row, remainingPageSpace, table, doc) {
9268
+ var cells = {};
9269
+ row.spansMultiplePages = true;
9270
+ row.height = 0;
9271
+ var rowHeight = 0;
9272
+ for (var _i = 0, _a = table.columns; _i < _a.length; _i++) {
9273
+ var column = _a[_i];
9274
+ var cell = row.cells[column.index];
9275
+ if (!cell)
9276
+ continue;
9277
+ if (!Array.isArray(cell.text)) {
9278
+ cell.text = [cell.text];
9279
+ }
9280
+ var remainderCell = new Cell(cell.raw, cell.styles, cell.section);
9281
+ remainderCell = assign(remainderCell, cell);
9282
+ remainderCell.text = [];
9283
+ var remainingLineCount = getRemainingLineCount(cell, remainingPageSpace, doc);
9284
+ if (cell.text.length > remainingLineCount) {
9285
+ remainderCell.text = cell.text.splice(remainingLineCount, cell.text.length);
9286
+ }
9287
+ var scaleFactor = doc.scaleFactor();
9288
+ var lineHeightFactor = doc.getLineHeightFactor();
9289
+ cell.contentHeight = cell.getContentHeight(scaleFactor, lineHeightFactor);
9290
+ if (cell.contentHeight >= remainingPageSpace) {
9291
+ cell.contentHeight = remainingPageSpace;
9292
+ remainderCell.styles.minCellHeight -= remainingPageSpace;
9293
+ }
9294
+ if (cell.contentHeight > row.height) {
9295
+ row.height = cell.contentHeight;
9296
+ }
9297
+ remainderCell.contentHeight = remainderCell.getContentHeight(scaleFactor, lineHeightFactor);
9298
+ if (remainderCell.contentHeight > rowHeight) {
9299
+ rowHeight = remainderCell.contentHeight;
9300
+ }
9301
+ cells[column.index] = remainderCell;
9302
+ }
9303
+ var remainderRow = new Row(row.raw, -1, row.section, cells, true);
9304
+ remainderRow.height = rowHeight;
9305
+ for (var _b = 0, _c = table.columns; _b < _c.length; _b++) {
9306
+ var column = _c[_b];
9307
+ var remainderCell = remainderRow.cells[column.index];
9308
+ if (remainderCell) {
9309
+ remainderCell.height = remainderRow.height;
9310
+ }
9311
+ var cell = row.cells[column.index];
9312
+ if (cell) {
9313
+ cell.height = row.height;
9314
+ }
9315
+ }
9316
+ return remainderRow;
9317
+ }
9318
+ function shouldPrintOnCurrentPage(doc, row, remainingPageSpace, table) {
9319
+ var pageHeight = doc.pageSize().height;
9320
+ var margin = table.settings.margin;
9321
+ var marginHeight = margin.top + margin.bottom;
9322
+ var maxRowHeight = pageHeight - marginHeight;
9323
+ if (row.section === 'body') {
9324
+ // Should also take into account that head and foot is not
9325
+ // on every page with some settings
9326
+ maxRowHeight -=
9327
+ table.getHeadHeight(table.columns) + table.getFootHeight(table.columns);
9328
+ }
9329
+ var minRowHeight = row.getMinimumRowHeight(table.columns, doc);
9330
+ var minRowFits = minRowHeight < remainingPageSpace;
9331
+ if (minRowHeight > maxRowHeight) {
9332
+ console.log("Will not be able to print row ".concat(row.index, " correctly since it's minimum height is larger than page height"));
9333
+ return true;
9334
+ }
9335
+ if (!minRowFits) {
9336
+ return false;
9337
+ }
9338
+ var rowHasRowSpanCell = row.hasRowSpan(table.columns);
9339
+ var rowHigherThanPage = row.getMaxCellHeight(table.columns) > maxRowHeight;
9340
+ if (rowHigherThanPage) {
9341
+ if (rowHasRowSpanCell) {
9342
+ console.log("The content of row ".concat(row.index, " will not be drawn correctly since drawing rows with a height larger than the page height and has cells with rowspans is not supported."));
9343
+ }
9344
+ return true;
9345
+ }
9346
+ if (rowHasRowSpanCell) {
9347
+ // Currently a new page is required whenever a rowspan row don't fit a page.
9348
+ return false;
9349
+ }
9350
+ if (table.settings.rowPageBreak === 'avoid') {
9351
+ return false;
9352
+ }
9353
+ // In all other cases print the row on current page
9354
+ return true;
9355
+ }
9356
+ function printFullRow(doc, table, row, isLastRow, startPos, cursor, columns) {
9357
+ var remainingSpace = getRemainingPageSpace(doc, table, isLastRow, cursor);
9358
+ if (row.canEntireRowFit(remainingSpace, columns)) {
9359
+ // The row fits in the current page
9360
+ printRow(doc, table, row, cursor, columns);
9361
+ }
9362
+ else if (shouldPrintOnCurrentPage(doc, row, remainingSpace, table)) {
9363
+ // The row gets split in two here, each piece in one page
9364
+ var remainderRow = modifyRowToFit(row, remainingSpace, table, doc);
9365
+ printRow(doc, table, row, cursor, columns);
9366
+ addPage(doc, table, startPos, cursor, columns);
9367
+ printFullRow(doc, table, remainderRow, isLastRow, startPos, cursor, columns);
9368
+ }
9369
+ else {
9370
+ // The row get printed entirelly on the next page
9371
+ addPage(doc, table, startPos, cursor, columns);
9372
+ printFullRow(doc, table, row, isLastRow, startPos, cursor, columns);
9373
+ }
9374
+ }
9375
+ function printRow(doc, table, row, cursor, columns) {
9376
+ cursor.x = table.settings.margin.left;
9377
+ for (var _i = 0, columns_1 = columns; _i < columns_1.length; _i++) {
9378
+ var column = columns_1[_i];
9379
+ var cell = row.cells[column.index];
9380
+ if (!cell) {
9381
+ cursor.x += column.width;
9382
+ continue;
9383
+ }
9384
+ doc.applyStyles(cell.styles);
9385
+ cell.x = cursor.x;
9386
+ cell.y = cursor.y;
9387
+ var result = table.callCellHooks(doc, table.hooks.willDrawCell, cell, row, column, cursor);
9388
+ if (result === false) {
9389
+ cursor.x += column.width;
9390
+ continue;
9391
+ }
9392
+ drawCellRect(doc, cell, cursor);
9393
+ var textPos = cell.getTextPos();
9394
+ autoTableText(cell.text, textPos.x, textPos.y, {
9395
+ halign: cell.styles.halign,
9396
+ valign: cell.styles.valign,
9397
+ maxWidth: Math.ceil(cell.width - cell.padding('left') - cell.padding('right')),
9398
+ }, doc.getDocument());
9399
+ table.callCellHooks(doc, table.hooks.didDrawCell, cell, row, column, cursor);
9400
+ cursor.x += column.width;
9401
+ }
9402
+ cursor.y += row.height;
9403
+ }
9404
+ function drawCellRect(doc, cell, cursor) {
9405
+ var cellStyles = cell.styles;
9406
+ // https://github.com/simonbengtsson/jsPDF-AutoTable/issues/774
9407
+ // TODO (v4): better solution?
9408
+ doc.getDocument().setFillColor(doc.getDocument().getFillColor());
9409
+ if (typeof cellStyles.lineWidth === 'number') {
9410
+ // Draw cell background with normal borders
9411
+ var fillStyle = getFillStyle(cellStyles.lineWidth, cellStyles.fillColor);
9412
+ if (fillStyle) {
9413
+ doc.rect(cell.x, cursor.y, cell.width, cell.height, fillStyle);
9414
+ }
9415
+ }
9416
+ else if (typeof cellStyles.lineWidth === 'object') {
9417
+ // Draw cell background
9418
+ if (cellStyles.fillColor) {
9419
+ doc.rect(cell.x, cursor.y, cell.width, cell.height, 'F');
9420
+ }
9421
+ // Draw cell individual borders
9422
+ drawCellBorders(doc, cell, cursor, cellStyles.lineWidth);
9423
+ }
9424
+ }
9425
+ /**
9426
+ * Draw all specified borders. Borders are centered on cell's edge and lengthened
9427
+ * to overlap with neighbours to create sharp corners.
9428
+ * @param doc
9429
+ * @param cell
9430
+ * @param cursor
9431
+ * @param fillColor
9432
+ * @param lineWidth
9433
+ */
9434
+ function drawCellBorders(doc, cell, cursor, lineWidth) {
9435
+ var x1, y1, x2, y2;
9436
+ if (lineWidth.top) {
9437
+ x1 = cursor.x;
9438
+ y1 = cursor.y;
9439
+ x2 = cursor.x + cell.width;
9440
+ y2 = cursor.y;
9441
+ if (lineWidth.right) {
9442
+ x2 += 0.5 * lineWidth.right;
9443
+ }
9444
+ if (lineWidth.left) {
9445
+ x1 -= 0.5 * lineWidth.left;
9446
+ }
9447
+ drawLine(lineWidth.top, x1, y1, x2, y2);
9448
+ }
9449
+ if (lineWidth.bottom) {
9450
+ x1 = cursor.x;
9451
+ y1 = cursor.y + cell.height;
9452
+ x2 = cursor.x + cell.width;
9453
+ y2 = cursor.y + cell.height;
9454
+ if (lineWidth.right) {
9455
+ x2 += 0.5 * lineWidth.right;
9456
+ }
9457
+ if (lineWidth.left) {
9458
+ x1 -= 0.5 * lineWidth.left;
9459
+ }
9460
+ drawLine(lineWidth.bottom, x1, y1, x2, y2);
9461
+ }
9462
+ if (lineWidth.left) {
9463
+ x1 = cursor.x;
9464
+ y1 = cursor.y;
9465
+ x2 = cursor.x;
9466
+ y2 = cursor.y + cell.height;
9467
+ if (lineWidth.top) {
9468
+ y1 -= 0.5 * lineWidth.top;
9469
+ }
9470
+ if (lineWidth.bottom) {
9471
+ y2 += 0.5 * lineWidth.bottom;
9472
+ }
9473
+ drawLine(lineWidth.left, x1, y1, x2, y2);
9474
+ }
9475
+ if (lineWidth.right) {
9476
+ x1 = cursor.x + cell.width;
9477
+ y1 = cursor.y;
9478
+ x2 = cursor.x + cell.width;
9479
+ y2 = cursor.y + cell.height;
9480
+ if (lineWidth.top) {
9481
+ y1 -= 0.5 * lineWidth.top;
9482
+ }
9483
+ if (lineWidth.bottom) {
9484
+ y2 += 0.5 * lineWidth.bottom;
9485
+ }
9486
+ drawLine(lineWidth.right, x1, y1, x2, y2);
9487
+ }
9488
+ function drawLine(width, x1, y1, x2, y2) {
9489
+ doc.getDocument().setLineWidth(width);
9490
+ doc.getDocument().line(x1, y1, x2, y2, 'S');
9491
+ }
9492
+ }
9493
+ function getRemainingPageSpace(doc, table, isLastRow, cursor) {
9494
+ var bottomContentHeight = table.settings.margin.bottom;
9495
+ var showFoot = table.settings.showFoot;
9496
+ if (showFoot === 'everyPage' || (showFoot === 'lastPage' && isLastRow)) {
9497
+ bottomContentHeight += table.getFootHeight(table.columns);
9498
+ }
9499
+ return doc.pageSize().height - cursor.y - bottomContentHeight;
9500
+ }
9501
+ function addPage(doc, table, startPos, cursor, columns, suppressFooter) {
9502
+ if (columns === void 0) { columns = []; }
9503
+ if (suppressFooter === void 0) { suppressFooter = false; }
9504
+ doc.applyStyles(doc.userStyles);
9505
+ if (table.settings.showFoot === 'everyPage' && !suppressFooter) {
9506
+ table.foot.forEach(function (row) { return printRow(doc, table, row, cursor, columns); });
9507
+ }
9508
+ // Add user content just before adding new page ensure it will
9509
+ // be drawn above other things on the page
9510
+ table.callEndPageHooks(doc, cursor);
9511
+ var margin = table.settings.margin;
9512
+ addTableBorder(doc, table, startPos, cursor);
9513
+ nextPage(doc);
9514
+ table.pageNumber++;
9515
+ cursor.x = margin.left;
9516
+ cursor.y = margin.top;
9517
+ startPos.y = margin.top;
9518
+ // call didAddPage hooks before any content is added to the page
9519
+ table.callWillDrawPageHooks(doc, cursor);
9520
+ if (table.settings.showHead === 'everyPage') {
9521
+ table.head.forEach(function (row) { return printRow(doc, table, row, cursor, columns); });
9522
+ doc.applyStyles(doc.userStyles);
9523
+ }
9524
+ }
9525
+ function nextPage(doc) {
9526
+ var current = doc.pageNumber();
9527
+ doc.setPage(current + 1);
9528
+ var newCurrent = doc.pageNumber();
9529
+ if (newCurrent === current) {
9530
+ doc.addPage();
9531
+ return true;
9532
+ }
9533
+ return false;
9534
+ }
9535
+
9536
+ function applyPlugin(jsPDF) {
9537
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
9538
+ jsPDF.API.autoTable = function () {
9539
+ var args = [];
9540
+ for (var _i = 0; _i < arguments.length; _i++) {
9541
+ args[_i] = arguments[_i];
9542
+ }
9543
+ var options = args[0];
9544
+ var input = parseInput(this, options);
9545
+ var table = createTable(this, input);
9546
+ drawTable(this, table);
9547
+ return this;
9548
+ };
9549
+ // Assign false to enable `doc.lastAutoTable.finalY || 40` sugar
9550
+ jsPDF.API.lastAutoTable = false;
9551
+ jsPDF.API.autoTableText = function (text, x, y, styles) {
9552
+ autoTableText(text, x, y, styles, this);
9553
+ };
9554
+ jsPDF.API.autoTableSetDefaults = function (defaults) {
9555
+ DocHandler.setDefaults(defaults, this);
9556
+ return this;
9557
+ };
9558
+ jsPDF.autoTableSetDefaults = function (defaults, doc) {
9559
+ DocHandler.setDefaults(defaults, doc);
9560
+ };
9561
+ jsPDF.API.autoTableHtmlToJson = function (tableElem, includeHiddenElements) {
9562
+ var _a;
9563
+ if (includeHiddenElements === void 0) { includeHiddenElements = false; }
9564
+ if (typeof window === 'undefined') {
9565
+ console.error('Cannot run autoTableHtmlToJson in non browser environment');
9566
+ return null;
9567
+ }
9568
+ var doc = new DocHandler(this);
9569
+ var _b = parseHtml(doc, tableElem, window, includeHiddenElements, false), head = _b.head, body = _b.body;
9570
+ var columns = ((_a = head[0]) === null || _a === void 0 ? void 0 : _a.map(function (c) { return c.content; })) || [];
9571
+ return { columns: columns, rows: body, data: body };
9572
+ };
9573
+ }
9574
+
9575
+ var _a;
9576
+ function autoTable(d, options) {
9577
+ var input = parseInput(d, options);
9578
+ var table = createTable(d, input);
9579
+ drawTable(d, table);
9580
+ }
9581
+ // Experimental export
9582
+ function __createTable(d, options) {
9583
+ var input = parseInput(d, options);
9584
+ return createTable(d, input);
9585
+ }
9586
+ function __drawTable(d, table) {
9587
+ drawTable(d, table);
9588
+ }
9589
+ try {
9590
+ if (typeof window !== 'undefined' && window) {
9591
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
9592
+ var anyWindow = window;
9593
+ var jsPDF = anyWindow.jsPDF || ((_a = anyWindow.jspdf) === null || _a === void 0 ? void 0 : _a.jsPDF);
9594
+ if (jsPDF) {
9595
+ applyPlugin(jsPDF);
9596
+ }
9597
+ }
9598
+ }
9599
+ catch (error) {
9600
+ console.error('Could not apply autoTable plugin', error);
9601
+ }
9602
+
9603
+ var jspdf_plugin_autotable = /*#__PURE__*/Object.freeze({
9604
+ __proto__: null,
9605
+ Cell: Cell,
9606
+ CellHookData: CellHookData,
9607
+ Column: Column,
9608
+ HookData: HookData,
9609
+ Row: Row,
9610
+ Table: Table,
9611
+ __createTable: __createTable,
9612
+ __drawTable: __drawTable,
9613
+ applyPlugin: applyPlugin,
9614
+ autoTable: autoTable,
9615
+ default: autoTable
9616
+ });
9617
+
6968
9618
  exports.AbandonedDonationRecovery = AbandonedDonationRecovery;
6969
9619
  exports.Dashboard = Dashboard;
6970
9620
  exports.DashboardTheme = theme;