@ammarkhalidfarooq/dashboard-package 0.5.12 → 0.5.14

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