nillud-data-table 1.0.0 → 1.0.2

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/README.md CHANGED
@@ -24,6 +24,7 @@ yarn add nillud-data-table
24
24
 
25
25
  ```tsx
26
26
  import { DataTable } from 'nillud-data-table'
27
+ import 'nillud-data-table/styles.css'
27
28
 
28
29
  const columns = [{ field: 'name', title: 'Имя' }]
29
30
  const data = [{ name: 'Иван' }]
@@ -37,6 +38,7 @@ const data = [{ name: 'Иван' }]
37
38
 
38
39
  ```tsx
39
40
  import { DataTable } from 'nillud-data-table'
41
+ import 'nillud-data-table/styles.css'
40
42
 
41
43
  const columns = [{ field: 'name', title: 'Имя' }]
42
44
  const data = [{ name: 'Иван' }]
@@ -432,23 +434,19 @@ excelCustomColumns={[
432
434
 
433
435
  Для использования модуля Excel необходимо установить библиотеку [exceljs](https://www.npmjs.com/package/exceljs)
434
436
 
435
- ```tsx
436
- npm i exceljs
437
- -или-
438
- yarn add exceljs
439
- ```
437
+ Для использования модуля экспорта необходимо его подключить
438
+ ```ts
439
+ import { exportToExcel } from 'nillud-data-table/export-excel';
440
+ ```
440
441
 
441
442
  ### wordBtn
442
443
 
443
444
  Необязательный параметр. Тип **boolean**, по умолчанию **false**. При значении **true** над таблицей с правой стороны появляется кнопка экспорта Word, которая по умолчанию принимает в себя исходный массив **tableData**
444
445
 
445
- Для использования модуля Word необходимо установить библиотеки [docx](https://www.npmjs.com/package/docx) и [file-saver](https://www.npmjs.com/package/file-saver)
446
-
447
- ```tsx
448
- npm i docx file-saver
449
- -или-
450
- yarn add docx file-saver
451
- ```
446
+ Для использования модуля экспорта необходимо его подключить
447
+ ```ts
448
+ import { exportToWord } from 'nillud-data-table/export-word';
449
+ ```
452
450
 
453
451
  ### wordOptions
454
452
 
@@ -494,3 +492,25 @@ groupBy={'status'}
494
492
  ```tsx
495
493
  isTitles
496
494
  ```
495
+
496
+ ### Возможности useRef
497
+
498
+ Возможность подключиться напрямую к таблице и получить данные после всех манипуляций
499
+
500
+ ```tsx
501
+ import { useRef } from "react";
502
+
503
+ const tableRef = useRef<DataTableRef>(null);
504
+
505
+ <DataTable
506
+ ...
507
+ ref={tableRef}
508
+ ...
509
+ />
510
+
511
+ const func = () => {
512
+ const data = tableRef.current.getData() // Получить текущие данные, после сортировки и фильтрации
513
+ const currData = tableRef.current.getCurrentData() // Получить данные с текущей таблицы пагинации
514
+ }
515
+
516
+ ```
@@ -0,0 +1,247 @@
1
+ // components/export/WordExport.tsx
2
+ import {
3
+ AlignmentType,
4
+ Document,
5
+ Packer,
6
+ PageOrientation,
7
+ Paragraph,
8
+ Table,
9
+ TableCell,
10
+ TableRow,
11
+ TextRun,
12
+ VerticalAlign,
13
+ WidthType
14
+ } from "docx";
15
+ import saveAs from "file-saver";
16
+
17
+ // utils/exportUtils/ExportHelpers.ts
18
+ function prepareExportRows(columns, data) {
19
+ return data.map(
20
+ (row) => columns.map((col) => {
21
+ const value = row[col.field];
22
+ return typeof col.exportCustomCell !== "undefined" ? col.exportCustomCell(String(value), row) : String(value != null ? value : "");
23
+ })
24
+ );
25
+ }
26
+ function prepareExportHeaders(columns) {
27
+ return columns.map((col) => col.title);
28
+ }
29
+
30
+ // components/export/WordExport.tsx
31
+ import { jsx } from "react/jsx-runtime";
32
+ var WordExport = ({
33
+ wordData,
34
+ columns,
35
+ title,
36
+ options = {
37
+ fontSize: 20,
38
+ boldHeaders: false,
39
+ autoLandscape: false,
40
+ maxColumnsBeforeLandscape: 5
41
+ }
42
+ // exportCustomColumns
43
+ }) => {
44
+ const createNewWord = async () => {
45
+ const {
46
+ fontSize = 0,
47
+ boldHeaders = true,
48
+ autoLandscape = true,
49
+ maxColumnsBeforeLandscape = 5
50
+ } = options;
51
+ const isLandscape = autoLandscape && columns.length > maxColumnsBeforeLandscape;
52
+ const headerCells = prepareExportHeaders(columns).map((header) => new TableCell({
53
+ children: [new Paragraph({
54
+ children: [new TextRun({
55
+ text: header,
56
+ size: fontSize,
57
+ bold: boldHeaders
58
+ })],
59
+ alignment: AlignmentType.CENTER
60
+ })],
61
+ verticalAlign: VerticalAlign.CENTER
62
+ }));
63
+ const tableHeaderRow = new TableRow({ children: headerCells });
64
+ const rows = prepareExportRows(columns, wordData).map((cells) => {
65
+ const rowCells = cells.map(
66
+ (value) => new TableCell({
67
+ children: [new Paragraph({
68
+ children: [new TextRun({
69
+ text: value,
70
+ size: fontSize
71
+ })],
72
+ alignment: AlignmentType.CENTER
73
+ })],
74
+ verticalAlign: VerticalAlign.CENTER
75
+ })
76
+ );
77
+ return new TableRow({ children: rowCells });
78
+ });
79
+ const table = new Table({
80
+ rows: [tableHeaderRow, ...rows],
81
+ width: { size: 11e3, type: WidthType.DXA },
82
+ indent: { size: -1e3, type: WidthType.DXA }
83
+ });
84
+ const doc = new Document({
85
+ sections: [{
86
+ children: [table, new Paragraph({ text: "" })],
87
+ properties: isLandscape ? { page: { size: { orientation: PageOrientation.LANDSCAPE } } } : {}
88
+ }]
89
+ });
90
+ Packer.toBlob(doc).then((blob) => {
91
+ saveAs(blob, `${title}.docx`);
92
+ });
93
+ };
94
+ return /* @__PURE__ */ jsx("button", { className: `ndt-buttonExport ndt-Word}`, onClick: createNewWord, children: "\u0421\u043A\u0430\u0447\u0430\u0442\u044C Word" });
95
+ };
96
+ var WordExport_default = WordExport;
97
+
98
+ // utils/exportUtils/exportUtils.ts
99
+ var generateExcelColumns = (columns, exportCustomColumns) => {
100
+ let excelColumns = columns.map((column) => ({
101
+ header: column.title,
102
+ key: column.field,
103
+ width: 20
104
+ }));
105
+ if (exportCustomColumns) {
106
+ exportCustomColumns.forEach((custom) => {
107
+ excelColumns = excelColumns.map(
108
+ (col) => col.key === custom.key ? { ...col, ...custom } : col
109
+ );
110
+ });
111
+ }
112
+ return excelColumns;
113
+ };
114
+ var applyHeaderStyles = (row, columnCount) => {
115
+ row.height = 40;
116
+ row.font = { size: 12, bold: true };
117
+ row.alignment = { vertical: "middle", horizontal: "center" };
118
+ for (let i = 1; i <= columnCount; i++) {
119
+ const cell = row.getCell(i);
120
+ cell.alignment = { wrapText: true, vertical: "middle", horizontal: "center" };
121
+ cell.border = {
122
+ top: { style: "thin" },
123
+ left: { style: "thin" },
124
+ bottom: { style: "thin" },
125
+ right: { style: "thin" }
126
+ };
127
+ }
128
+ };
129
+ var applyRowStyles = (row, columnCount) => {
130
+ row.height = 40;
131
+ row.font = { size: 12 };
132
+ row.alignment = { vertical: "middle", horizontal: "center" };
133
+ for (let i = 1; i <= columnCount; i++) {
134
+ const cell = row.getCell(i);
135
+ cell.alignment = { wrapText: true, vertical: "middle", horizontal: "center" };
136
+ cell.border = {
137
+ top: { style: "thin" },
138
+ left: { style: "thin" },
139
+ bottom: { style: "thin" },
140
+ right: { style: "thin" }
141
+ };
142
+ }
143
+ };
144
+ var generateExcelDataRows = (columns, data) => {
145
+ return data.map((element) => {
146
+ const rowData = {};
147
+ columns.forEach((col) => {
148
+ const value = element[col.field];
149
+ rowData[col.field] = typeof col.exportCustomCell !== "undefined" ? col.exportCustomCell(String(value), element) : value != null ? value : "";
150
+ });
151
+ return rowData;
152
+ });
153
+ };
154
+ var setColumnAutoWidths = (sheet) => {
155
+ var _a;
156
+ (_a = sheet.columns) == null ? void 0 : _a.forEach((column) => {
157
+ var _a2;
158
+ let maxLength = 10;
159
+ (_a2 = column.eachCell) == null ? void 0 : _a2.call(column, { includeEmpty: true }, (cell) => {
160
+ const cellValue = cell.value ? String(cell.value) : "";
161
+ maxLength = Math.max(maxLength, cellValue.length + 5);
162
+ });
163
+ column.width = maxLength;
164
+ });
165
+ };
166
+
167
+ // components/export/ExportExcel.tsx
168
+ import ExcelJS from "exceljs";
169
+ import { jsx as jsx2 } from "react/jsx-runtime";
170
+ var ExportExcel = ({ columns, excelData, title, exportCustomColumns }) => {
171
+ const exportExcel = () => {
172
+ const workbook = new ExcelJS.Workbook();
173
+ const sheet = workbook.addWorksheet(title, {
174
+ pageSetup: {
175
+ fitToPage: true,
176
+ fitToHeight: 2,
177
+ fitToWidth: 1,
178
+ orientation: "landscape"
179
+ },
180
+ headerFooter: {
181
+ oddFooter: "\u0421\u0442\u0440\u0430\u043D\u0438\u0446\u0430 &P \u0438\u0437 &N",
182
+ evenFooter: "\u0421\u0442\u0440\u0430\u043D\u0438\u0446\u0430 &P \u0438\u0437 &N"
183
+ }
184
+ });
185
+ const excelColumns = generateExcelColumns(columns, exportCustomColumns);
186
+ sheet.columns = excelColumns;
187
+ const headerRow = sheet.getRow(1);
188
+ applyHeaderStyles(headerRow, sheet.columns.length);
189
+ const dataRows = generateExcelDataRows(columns, excelData);
190
+ dataRows.forEach((data) => {
191
+ const row = sheet.addRow(data);
192
+ applyRowStyles(row, sheet.columns.length);
193
+ });
194
+ setColumnAutoWidths(sheet);
195
+ if (excelData.length > 15) {
196
+ sheet.pageSetup.fitToHeight = Math.floor(excelData.length / 15);
197
+ } else {
198
+ sheet.pageSetup.fitToHeight = 1;
199
+ }
200
+ workbook.xlsx.writeBuffer().then((data) => {
201
+ const blob = new Blob([data], {
202
+ type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
203
+ });
204
+ const url = window.URL.createObjectURL(blob);
205
+ const anchor = document.createElement("a");
206
+ anchor.href = url;
207
+ anchor.download = `${title}.xlsx`;
208
+ anchor.click();
209
+ window.URL.revokeObjectURL(url);
210
+ });
211
+ };
212
+ return /* @__PURE__ */ jsx2("button", { className: `ndt-buttonExport ndt-Excel`, onClick: exportExcel, children: "\u0421\u043A\u0430\u0447\u0430\u0442\u044C Excel" });
213
+ };
214
+ var ExportExcel_default = ExportExcel;
215
+
216
+ // components/ExportSection.tsx
217
+ import { Fragment, jsx as jsx3, jsxs } from "react/jsx-runtime";
218
+ var ExportSection = ({ wordBtn, excelBtn, downloadSectionLeftSideContent, tableData, columns, tableName, exportCustomColumns, wordOptions }) => {
219
+ return /* @__PURE__ */ jsx3(Fragment, { children: /* @__PURE__ */ jsxs("div", { className: "ndt-download-section", children: [
220
+ /* @__PURE__ */ jsx3("div", { className: "ndt-download-content", children: (wordBtn || excelBtn) && downloadSectionLeftSideContent !== null && downloadSectionLeftSideContent }),
221
+ /* @__PURE__ */ jsxs("div", { className: "ndt-download-buttons", children: [
222
+ wordBtn && /* @__PURE__ */ jsx3(
223
+ WordExport_default,
224
+ {
225
+ wordData: tableData,
226
+ columns,
227
+ title: tableName,
228
+ exportCustomColumns,
229
+ options: wordOptions
230
+ }
231
+ ),
232
+ excelBtn && /* @__PURE__ */ jsx3(
233
+ ExportExcel_default,
234
+ {
235
+ excelData: tableData,
236
+ columns,
237
+ title: tableName,
238
+ exportCustomColumns
239
+ }
240
+ )
241
+ ] })
242
+ ] }) });
243
+ };
244
+ var ExportSection_default = ExportSection;
245
+ export {
246
+ ExportSection_default as default
247
+ };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,4 @@
1
- import * as react from 'react';
2
- import { ReactElement } from 'react';
1
+ import React, { ReactElement } from 'react';
3
2
 
4
3
  type TableElement = {
5
4
  [key: string]: string | number;
@@ -53,6 +52,6 @@ type DataTableRef = {
53
52
  getCurrentData: () => TableData;
54
53
  };
55
54
 
56
- declare const DataTable: react.ForwardRefExoticComponent<TableProps & react.RefAttributes<DataTableRef>>;
55
+ declare const DataTable: React.ForwardRefExoticComponent<TableProps & React.RefAttributes<DataTableRef>>;
57
56
 
58
57
  export { type Column, DataTable, type TableElement, type TableProps };