@ammarkhalidfarooq/dashboard-package 0.5.11 → 0.5.13

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