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