ivt
Version:
Ivt Components Library
365 lines (357 loc) • 14.1 kB
JavaScript
import React__default, { useState } from 'react';
import { f as formatDateToBrazilian } from './date-Dqmv8Nr4.mjs';
import { c as createLucideIcon } from './createLucideIcon-C11Tr46U.mjs';
import { B as Button } from './button-CZpmCmNo.mjs';
import { c as cn } from './utils-BDcRwQMd.mjs';
import { B as ButtonGroup } from './button-group-ChymO3Hm.mjs';
import { D as DropdownMenu, b as DropdownMenuTrigger, c as DropdownMenuContent, f as DropdownMenuItem } from './dropdown-menu-DnPBut1Q.mjs';
import { U as Upload } from './upload-DvgPaJGb.mjs';
import { C as ChevronDown } from './chevron-down-CDFTds2-.mjs';
const __iconNode = [
[
"path",
{
d: "M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",
key: "ih7n3h"
}
],
[
"polyline",
{
points: "7 10 12 15 17 10",
key: "2ggqvy"
}
],
[
"line",
{
x1: "12",
x2: "12",
y1: "15",
y2: "3",
key: "1vk2je"
}
]
];
const Download = createLucideIcon("Download", __iconNode);
var q;
(function(x) {
x["csv"] = "text/csv";
x["tsv"] = "text/tab-separated-values";
x["plain"] = "text/plain";
})(q || (q = {}));
var X = (W)=>W, z = (W)=>W, Z = X, _ = X, Y = X, N = X, V = X;
var h = {
fieldSeparator: ",",
decimalSeparator: ".",
quoteStrings: true,
quoteCharacter: '"',
showTitle: false,
title: "My Generated Report",
filename: "generated",
showColumnHeaders: true,
useTextFile: false,
fileExtension: "csv",
mediaType: q.csv,
useBom: true,
columnHeaders: [],
useKeysAsHeaders: false,
boolDisplay: {
true: "TRUE",
false: "FALSE"
},
replaceUndefinedWith: ""
}, F = "\r\n", R = "\uFEFF", G = (W)=>Object.assign({}, h, W);
class K extends Error {
constructor(W){
super(W);
this.name = "CsvGenerationError";
}
}
class B extends Error {
constructor(W){
super(W);
this.name = "EmptyHeadersError";
}
}
class L extends Error {
constructor(W){
super(W);
this.name = "CsvDownloadEnvironmentError";
}
}
class P extends Error {
constructor(W){
super(W);
this.name = "UnsupportedDataFormatError";
}
}
var s = function(W, $) {
if ($ == '"' && W.indexOf('"') > -1) return W.replace(/"/g, '""');
return W;
}, w = (W)=>typeof W === "object" ? N(W.key) : N(W), y = (W)=>typeof W === "object" ? V(W.displayLabel) : V(W), T = (W, ...$)=>$.reduce((j, x)=>x(j), W), E = (W)=>($)=>W.useBom ? _(z($) + R) : $, M = (W)=>($)=>W.showTitle ? S(_(z($) + W.title))(Y("")) : $, S = (W)=>($)=>_(z(W) + z($) + F), O = (W)=>($, j)=>l(W)(Y(z($) + z(j))), l = (W)=>($)=>X(z($) + W.fieldSeparator), b = (W, $)=>(j)=>{
if (!W.showColumnHeaders) return j;
if ($.length < 1) throw new B("Option to show headers but none supplied. Make sure there are keys in your collection or that you've supplied headers through the config options.");
let x = Y("");
for(let A = 0; A < $.length; A++){
const J = y($[A]);
x = O(W)(x, v(W, z(J)));
}
return x = Y(z(x).slice(0, -1)), S(j)(x);
}, C = (W, $, j)=>(x)=>{
let A = x;
for(var J = 0; J < j.length; J++){
let I = Y("");
for(let U = 0; U < $.length; U++){
const H = w($[U]), D = j[J][z(H)];
I = O(W)(I, v(W, D));
}
I = Y(z(I).slice(0, -1)), A = S(A)(I);
}
return A;
}, m = (W)=>+W === W && (!isFinite(W) || Boolean(W % 1)), p = (W, $)=>{
if (m($)) {
if (W.decimalSeparator === "locale") return Z($.toLocaleString());
if (W.decimalSeparator) return Z($.toString().replace(".", W.decimalSeparator));
}
return Z($.toString());
}, Q = (W, $)=>{
let j = $;
if (W.quoteStrings || W.fieldSeparator && $.indexOf(W.fieldSeparator) > -1 || W.quoteCharacter && $.indexOf(W.quoteCharacter) > -1 || $.indexOf("\n") > -1 || $.indexOf("\r") > -1) j = W.quoteCharacter + s($, W.quoteCharacter) + W.quoteCharacter;
return Z(j);
}, g = (W, $)=>{
const j = $ ? "true" : "false";
return Z(W.boolDisplay[j]);
}, r = (W, $)=>{
if (typeof $ === "undefined" && W.replaceUndefinedWith !== void 0) return Q(W, W.replaceUndefinedWith + "");
if ($ === null) return Q(W, "null");
return Q(W, "");
}, v = (W, $)=>{
if (typeof $ === "number") return p(W, $);
if (typeof $ === "string") return Q(W, $);
if (typeof $ === "boolean" && W.boolDisplay) return g(W, $);
if ($ === null || typeof $ === "undefined") return r(W, $);
throw new P(`
typeof ${typeof $} isn't supported. Only number, string, boolean, null and undefined are supported.
Please convert the data in your object to one of those before generating the CSV.
`);
};
var BW = (W)=>($)=>{
const j = G(W), x = j.useKeysAsHeaders ? Object.keys($[0]) : j.columnHeaders;
let A = T(_(""), E(j), M(j), b(j, x), C(j, x, $));
if (z(A).length < 1) throw new K("Output is empty. Is your data formatted correctly?");
return A;
}, f = (W)=>($)=>{
const j = G(W), x = z($), A = j.useTextFile ? "text/plain" : j.mediaType;
return new Blob([
x
], {
type: `${A};charset=utf8;`
});
}, LW = (W)=>($)=>{
if (!window) throw new L("Downloading only supported in a browser environment.");
const j = f(W)($), x = G(W), A = x.useTextFile ? "txt" : x.fileExtension, J = `${x.filename}.${A}`, I = document.createElement("a");
I.download = J, I.href = URL.createObjectURL(j), I.setAttribute("visibility", "hidden"), document.body.appendChild(I), I.click(), document.body.removeChild(I);
};
/*! js-cookie v3.0.5 | MIT */ /* eslint-disable no-var */ function assign(target) {
for(var i = 1; i < arguments.length; i++){
var source = arguments[i];
for(var key in source){
target[key] = source[key];
}
}
return target;
}
/* eslint-enable no-var */ /* eslint-disable no-var */ var defaultConverter = {
read: function(value) {
if (value[0] === '"') {
value = value.slice(1, -1);
}
return value.replace(/(%[\dA-F]{2})+/gi, decodeURIComponent);
},
write: function(value) {
return encodeURIComponent(value).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g, decodeURIComponent);
}
};
/* eslint-enable no-var */ /* eslint-disable no-var */ function init(converter, defaultAttributes) {
function set(name, value, attributes) {
if (typeof document === 'undefined') {
return;
}
attributes = assign({}, defaultAttributes, attributes);
if (typeof attributes.expires === 'number') {
attributes.expires = new Date(Date.now() + attributes.expires * 864e5);
}
if (attributes.expires) {
attributes.expires = attributes.expires.toUTCString();
}
name = encodeURIComponent(name).replace(/%(2[346B]|5E|60|7C)/g, decodeURIComponent).replace(/[()]/g, escape);
var stringifiedAttributes = '';
for(var attributeName in attributes){
if (!attributes[attributeName]) {
continue;
}
stringifiedAttributes += '; ' + attributeName;
if (attributes[attributeName] === true) {
continue;
}
// Considers RFC 6265 section 5.2:
// ...
// 3. If the remaining unparsed-attributes contains a %x3B (";")
// character:
// Consume the characters of the unparsed-attributes up to,
// not including, the first %x3B (";") character.
// ...
stringifiedAttributes += '=' + attributes[attributeName].split(';')[0];
}
return document.cookie = name + '=' + converter.write(value, name) + stringifiedAttributes;
}
function get(name) {
if (typeof document === 'undefined' || arguments.length && !name) {
return;
}
// To prevent the for loop in the first place assign an empty array
// in case there are no cookies at all.
var cookies = document.cookie ? document.cookie.split('; ') : [];
var jar = {};
for(var i = 0; i < cookies.length; i++){
var parts = cookies[i].split('=');
var value = parts.slice(1).join('=');
try {
var found = decodeURIComponent(parts[0]);
jar[found] = converter.read(value, found);
if (name === found) {
break;
}
} catch (e) {}
}
return name ? jar[name] : jar;
}
return Object.create({
set,
get,
remove: function(name, attributes) {
set(name, '', assign({}, attributes, {
expires: -1
}));
},
withAttributes: function(attributes) {
return init(this.converter, assign({}, this.attributes, attributes));
},
withConverter: function(converter) {
return init(assign({}, this.converter, converter), this.attributes);
}
}, {
attributes: {
value: Object.freeze(defaultAttributes)
},
converter: {
value: Object.freeze(converter)
}
});
}
var api = init(defaultConverter, {
path: '/'
});
function getValueByPath(obj, path) {
// biome-ignore lint/suspicious/noExplicitAny: <any>
return path.split(".").reduce((acc, key)=>acc?.[key], obj);
}
const useExportCsv = ()=>{
const [isExporting, setIsExporting] = useState(false);
const exportToCsv = async ({ fetchData, config, fileName, skipDateSuffix = false })=>{
try {
setIsExporting(true);
const data = await fetchData();
if (!data || data.length === 0) {
throw new Error(config.emptyMessage ?? "Nenhum dado encontrado para os filtros selecionados.");
}
const rowData = data.map((row)=>{
return config.exportableFields.reduce((acc, path)=>{
const rawValue = getValueByPath(row, path);
const newKey = config.columnMapping[path] || path;
const formatter = config.fieldFormatters?.[path];
const formattedOrRawValue = formatter != null ? formatter(rawValue, row) : rawValue;
acc[newKey] = formattedOrRawValue == null ? "" : String(formattedOrRawValue);
return acc;
}, {});
});
const dateCookie = api.get("date");
const dateSuffix = formatDateToBrazilian(dateCookie ?? new Date(), "dd_MM_yyyy");
const finalFileName = skipDateSuffix ? `${fileName ?? config.defaultFileName}` : `${fileName ?? config.defaultFileName}-${dateSuffix}`;
const csvConfig = G({
fieldSeparator: ";",
decimalSeparator: ",",
useKeysAsHeaders: true,
filename: finalFileName
});
const csv = BW(csvConfig)(rowData);
LW(csvConfig)(csv);
} catch (error) {
console.error("Erro durante a exportação para CSV:", error);
throw error;
} finally{
setIsExporting(false);
}
};
return {
exportToCsv,
isExporting
};
};
const ButtonExportCsv = ({ table, disabled, action, fileName, config, text = "Exportar", rowsToExport })=>{
const { exportToCsv, isExporting } = useExportCsv();
async function handleExportData() {
if (!config) {
console.warn("props de config não foi passada");
return;
}
exportToCsv({
fetchData: async ()=>{
return rowsToExport ?? table.getFilteredRowModel().rows.map((r)=>r.original);
},
config,
fileName,
skipDateSuffix: false
});
}
return /*#__PURE__*/ React__default.createElement(Button, {
variant: "secondary",
size: "sm",
disabled: table?.getRowCount?.() === 0 || disabled || isExporting,
onClick: ()=>action ? action() : handleExportData()
}, /*#__PURE__*/ React__default.createElement(Download, {
className: "size-4",
"aria-hidden": "true"
}), text);
};
function ExportButtons({ options = [], buttonLabel = "Exportar", disabledButtons }) {
const [open, setOpen] = React__default.useState(false);
if (options.length === 0) return null;
return /*#__PURE__*/ React__default.createElement(ButtonGroup, null, /*#__PURE__*/ React__default.createElement(DropdownMenu, {
open: open,
onOpenChange: setOpen
}, /*#__PURE__*/ React__default.createElement(DropdownMenuTrigger, {
disabled: disabledButtons,
asChild: true
}, /*#__PURE__*/ React__default.createElement(Button, {
variant: "secondary",
className: "flex items-center gap-2",
"aria-label": "Exportar opções",
disabled: disabledButtons
}, /*#__PURE__*/ React__default.createElement(Upload, {
className: "size-4",
"aria-hidden": "true"
}), buttonLabel, /*#__PURE__*/ React__default.createElement(ChevronDown, {
className: cn("size-4 transition-transform duration-200", open ? "rotate-180" : "rotate-0"),
"aria-hidden": "true"
}))), /*#__PURE__*/ React__default.createElement(DropdownMenuContent, {
className: "w-44"
}, options.map((option, index)=>/*#__PURE__*/ React__default.createElement(DropdownMenuItem, {
key: index,
onClick: option.onExport,
disabled: option.disabled
}, option.label)))));
}
export { ButtonExportCsv as B, Download as D, ExportButtons as E, api as a };
//# sourceMappingURL=ExportButtons-BtYHz3q3.mjs.map