sheet-widget 0.1.0 → 0.1.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.
@@ -1,796 +0,0 @@
1
- import React, { useEffect, useState, useRef } from 'react';
2
- import { HotTable } from '@handsontable/react';
3
- import Handsontable from 'handsontable';
4
- import { registerAllModules } from 'handsontable/registry';
5
- import { textRenderer } from 'handsontable/renderers/textRenderer';
6
- import axios from 'axios';
7
- import Papa from 'papaparse';
8
- import * as XLSX from 'xlsx-js-style';
9
- import HyperFormula from 'hyperformula';
10
-
11
- registerAllModules();
12
-
13
- const API_BASE = 'http://158.160.73.104:8000/api/tables/';
14
-
15
- function TableEditor({
16
- id,
17
- compactMode = false,
18
- showCompactControls = false,
19
- onTitleChange
20
- }) {
21
- const tableId = id;
22
- const hotRef = useRef(null);
23
- const fileInputRef = useRef(null);
24
- const importMenuRef = useRef(null);
25
- const exportMenuRef = useRef(null);
26
-
27
- const [contextMenuCell, setContextMenuCell] = useState(null);
28
- const [cellSettings, setCellSettings] = useState({});
29
- const [title, setTitle] = useState('');
30
- const [hotData, setHotData] = useState([['']]);
31
- const [tableLoaded, setTableLoaded] = useState(false);
32
- const [showImportMenu, setShowImportMenu] = useState(false);
33
- const [showExportMenu, setShowExportMenu] = useState(false);
34
-
35
- // Закрытие меню при клике вне
36
- useEffect(() => {
37
- const handleClickOutside = (e) => {
38
- if (importMenuRef.current && !importMenuRef.current.contains(e.target)) {
39
- setShowImportMenu(false);
40
- }
41
- if (exportMenuRef.current && !exportMenuRef.current.contains(e.target)) {
42
- setShowExportMenu(false);
43
- }
44
- };
45
-
46
- document.addEventListener('mousedown', handleClickOutside);
47
- return () => document.removeEventListener('mousedown', handleClickOutside);
48
- }, []);
49
-
50
- // Загрузка таблицы
51
- useEffect(() => {
52
- if (tableId) {
53
- axios.get(`${API_BASE}${tableId}/`)
54
- .then(res => {
55
- const nextTitle = res.data.title || 'Без названия';
56
- setTitle(nextTitle);
57
- if (onTitleChange) {
58
- onTitleChange(nextTitle);
59
- }
60
-
61
- let rows = [];
62
- if (Array.isArray(res.data.data)) {
63
- rows = res.data.data;
64
- } else if (res.data.data && Array.isArray(res.data.data.rows)) {
65
- rows = res.data.data.rows;
66
- }
67
-
68
- setHotData(rows.length > 0 ? rows.map(row => row.map(cell => cell ?? '')) : [['']]);
69
- setCellSettings(res.data.cell_settings || {});
70
- setTableLoaded(true);
71
- })
72
- .catch(err => {
73
- console.error('Ошибка загрузки таблицы:', err);
74
- alert('Не удалось загрузить таблицу');
75
- });
76
- } else {
77
- setTitle('Новая таблица');
78
- setTableLoaded(true);
79
- }
80
- }, [tableId]);
81
-
82
- // Сохранение таблицы
83
- const saveTable = () => {
84
- if (!hotRef.current) return;
85
- const hot = hotRef.current.hotInstance;
86
-
87
- let sourceData;
88
- try {
89
- sourceData = hot.getSourceData();
90
- } catch (e) {
91
- // Если метод не поддерживается, попробуем другой способ
92
- console.warn('getSourceData not available, trying alternative');
93
- sourceData = hot.getData();
94
- const formulas = hot.getPlugin('formulas');
95
- if (formulas) {
96
- const formulaData = formulas.getFormulas();
97
- sourceData = sourceData.map((row, rowIndex) =>
98
- row.map((cell, colIndex) => {
99
- const formula = formulaData[rowIndex] && formulaData[rowIndex][colIndex];
100
- return formula || cell;
101
- })
102
- );
103
- }
104
- }
105
-
106
- const payload = {
107
- title,
108
- data: { rows: sourceData }, // ✅ Сохраняем формулы
109
- cell_settings: cellSettings
110
- };
111
-
112
- if (tableId) {
113
- axios.patch(`${API_BASE}${tableId}/`, payload)
114
- .then(() => console.log('Таблица сохранена'))
115
- .catch(err => {
116
- console.error('Ошибка сохранения:', err);
117
- alert('Ошибка при сохранении');
118
- });
119
- } else {
120
- axios.post(`${API_BASE}`, payload)
121
- .then(res => {
122
- window.location.href = `/table/${res.data.id}`;
123
- })
124
- .catch(err => {
125
- console.error('Ошибка создания:', err);
126
- alert('Ошибка при создании таблицы');
127
- });
128
- }
129
- };
130
-
131
- // Импорт (CSV/JSON/Excel)
132
- const handleImport = (format) => {
133
- if (fileInputRef.current) fileInputRef.current.value = '';
134
-
135
- let accept = '';
136
- if (format === 'csv') accept = '.csv';
137
- else if (format === 'json') accept = '.json';
138
- else if (format === 'excel') accept = '.xlsx,.xls';
139
-
140
- fileInputRef.current.accept = accept;
141
- fileInputRef.current.onchange = (event) => {
142
- const file = event.target.files[0];
143
- if (!file) return;
144
-
145
- const reader = new FileReader();
146
-
147
- reader.onload = (e) => {
148
- try {
149
- let rows = [['']];
150
- let cellSettings = {};
151
- let importedTitle = title || 'Импортированная таблица';
152
-
153
- if (file.name.endsWith('.csv')) {
154
- Papa.parse(e.target.result, {
155
- complete: (res) => {
156
- rows = res.data
157
- .filter(row => row.some(cell => cell !== '' && cell != null))
158
- .map(row => row.map(cell => cell ?? ''));
159
- if (rows.length === 0) rows = [['']];
160
- setHotData(rows);
161
- hotRef.current?.hotInstance?.loadData(rows);
162
- setCellSettings({});
163
- },
164
- skipEmptyLines: true,
165
- });
166
- } else if (file.name.endsWith('.json')) {
167
- const json = JSON.parse(e.target.result);
168
- rows = (Array.isArray(json) ? json : json.rows || json.data?.rows || []).map(
169
- row => row.map(cell => cell ?? '')
170
- );
171
- if (rows.length === 0) rows = [['']];
172
- cellSettings = json.cell_settings || {};
173
- importedTitle = json.title || importedTitle;
174
- setHotData(rows);
175
- hotRef.current?.hotInstance?.loadData(rows);
176
- setCellSettings(cellSettings);
177
- setTitle(importedTitle);
178
- } else if (file.name.endsWith('.xlsx') || file.name.endsWith('.xls')) {
179
- const data = new Uint8Array(e.target.result);
180
- const workbook = XLSX.read(data, { type: 'array', cellStyles: true });
181
- const sheetName = workbook.SheetNames[0];
182
- const sheet = workbook.Sheets[sheetName];
183
- rows = XLSX.utils.sheet_to_json(sheet, { header: 1, defval: '' });
184
- if (rows.length === 0) rows = [['']];
185
-
186
- // Извлекаем стили (цвета, шрифты)
187
- cellSettings = {};
188
- const range = XLSX.utils.decode_range(sheet['!ref'] || 'A1');
189
- for (let R = range.s.r; R <= range.e.r; R++) {
190
- for (let C = range.s.c; C <= range.e.c; C++) {
191
- const addr = XLSX.utils.encode_cell({ r: R, c: C });
192
- const cell = sheet[addr];
193
- if (!cell || !cell.s) continue;
194
-
195
- const key = `${R},${C}`;
196
- const style = {};
197
-
198
- if (cell.s.fill?.fgColor?.rgb) {
199
- style.color = `#${cell.s.fill.fgColor.rgb}`;
200
- }
201
- if (cell.s.font?.color?.rgb) {
202
- style.fontColor = `#${cell.s.font.color.rgb}`;
203
- }
204
- if (cell.s.font?.bold) style.bold = true;
205
- if (cell.s.font?.italic) style.italic = true;
206
- if (cell.s.font?.underline) style.underline = true;
207
- if (cell.s.alignment?.horizontal) style.align = cell.s.alignment.horizontal;
208
- if (cell.t === 'b') style.type = 'checkbox';
209
-
210
- if (Object.keys(style).length > 0) {
211
- cellSettings[key] = { color: '#FFFFFF', ...style };
212
- }
213
- }
214
- }
215
-
216
- setHotData(rows);
217
- hotRef.current?.hotInstance?.loadData(rows);
218
- setCellSettings(cellSettings);
219
- }
220
-
221
- setShowImportMenu(false);
222
- alert(`Таблица успешно импортирована из ${format.toUpperCase()}`);
223
- } catch (err) {
224
- console.error('Ошибка импорта:', err);
225
- alert(`Не удалось импортировать файл (${format})`);
226
- }
227
- };
228
-
229
- if (file.name.endsWith('.xlsx') || file.name.endsWith('.xls')) {
230
- reader.readAsArrayBuffer(file);
231
- } else {
232
- reader.readAsText(file);
233
- }
234
- };
235
-
236
- fileInputRef.current.click();
237
- };
238
-
239
- // Экспорт в CSV
240
- const exportToCSV = () => {
241
- if (!hotRef.current) return;
242
- const data = hotRef.current.hotInstance.getData();
243
- const csvContent = 'data:text/csv;charset=utf-8,' +
244
- data.map(row => row.map(cell => `"${String(cell).replace(/"/g, '""')}"`).join(',')).join('\n');
245
- const encodedUri = encodeURI(csvContent);
246
- const link = document.createElement('a');
247
- link.setAttribute('href', encodedUri);
248
- link.setAttribute('download', `${title || 'table'}.csv`);
249
- document.body.appendChild(link);
250
- link.click();
251
- document.body.removeChild(link);
252
- };
253
-
254
- // Экспорт в JSON
255
- const exportToJSON = () => {
256
- if (!hotRef.current) return;
257
- const data = hotRef.current.hotInstance.getData();
258
- const json = {
259
- title,
260
- data: { rows: data },
261
- cell_settings: cellSettings
262
- };
263
- const blob = new Blob([JSON.stringify(json, null, 2)], { type: 'application/json' });
264
- const url = URL.createObjectURL(blob);
265
- const a = document.createElement('a');
266
- a.href = url;
267
- a.download = `${title || 'table'}.json`;
268
- a.click();
269
- URL.revokeObjectURL(url);
270
- };
271
-
272
- // Экспорт в Excel с сохранением форматирования
273
- const exportToExcel = () => {
274
- if (!hotRef.current) return;
275
- const hot = hotRef.current.hotInstance;
276
- const data = hot.getData();
277
-
278
- const ws = XLSX.utils.aoa_to_sheet(data);
279
- const range = XLSX.utils.decode_range(ws['!ref'] || 'A1');
280
-
281
- for (let R = range.s.r; R <= range.e.r; R++) {
282
- for (let C = range.s.c; C <= range.e.c; C++) {
283
- const addr = XLSX.utils.encode_cell({ r: R, c: C });
284
- let cell = ws[addr];
285
- if (!cell) {
286
- cell = { v: data[R]?.[C] ?? '' };
287
- ws[addr] = cell;
288
- }
289
-
290
- const settings = getCellSettings(R, C);
291
- cell.s = {};
292
-
293
- // Фон
294
- if (settings.color && settings.color !== '#FFFFFF') {
295
- cell.s.fill = { fgColor: { rgb: settings.color.replace('#', '') } };
296
- }
297
- // Текст
298
- if (settings.fontColor && settings.fontColor !== '#000000') {
299
- cell.s.font = cell.s.font || {};
300
- cell.s.font.color = { rgb: settings.fontColor.replace('#', '') };
301
- }
302
- // Шрифт
303
- if (settings.bold || settings.italic || settings.underline) {
304
- cell.s.font = cell.s.font || {};
305
- if (settings.bold) cell.s.font.bold = true;
306
- if (settings.italic) cell.s.font.italic = true;
307
- if (settings.underline) cell.s.font.underline = true;
308
- }
309
- // Выравнивание
310
- if (settings.align) {
311
- cell.s.alignment = { horizontal: settings.align };
312
- }
313
- // Чекбокс
314
- if (settings.type === 'checkbox') {
315
- cell.t = 'b';
316
- cell.v = Boolean(data[R]?.[C]);
317
- }
318
- }
319
- }
320
-
321
- // Ширина столбцов
322
- ws['!cols'] = data[0]?.map(() => ({ wch: 15 })) || [];
323
-
324
- const wb = XLSX.utils.book_new();
325
- XLSX.utils.book_append_sheet(wb, ws, 'Лист1');
326
- const safeTitle = (title || 'table').replace(/[<>:"/\\|?*]/g, '_');
327
- XLSX.writeFile(wb, `${safeTitle}.xlsx`);
328
- };
329
-
330
- // Работа с настройками ячеек
331
- const getCellSettings = (row, col) => {
332
- const key = `${row},${col}`;
333
- return cellSettings[key] || { color: '#FFFFFF', type: 'text' };
334
- };
335
-
336
- const updateCellSettings = (row, col, settings) => {
337
- const key = `${row},${col}`;
338
- const newSettings = { ...cellSettings };
339
-
340
- if (settings === null) {
341
- delete newSettings[key];
342
- } else {
343
- newSettings[key] = { ...getCellSettings(row, col), ...settings };
344
- }
345
-
346
- setCellSettings(newSettings);
347
- hotRef.current?.hotInstance.render();
348
- };
349
-
350
- // Контекстное меню на русском
351
- const createContextMenu = () => ({
352
- items: {
353
- 'row_above': { name: 'Вставить строку сверху' },
354
- 'row_below': { name: 'Вставить строку снизу' },
355
- 'col_left': { name: 'Вставить столбец слева' },
356
- 'col_right': { name: 'Вставить столбец справа' },
357
- '---------': { disabled: true },
358
- 'remove_row': { name: 'Удалить строку' },
359
- 'remove_col': { name: 'Удалить столбец' },
360
- 'format_cell': {
361
- name: 'Форматирование ячейки',
362
- callback: (key, selection) => {
363
- if (!selection?.[0]) return;
364
- const { row, col } = selection[0].start;
365
- const settings = getCellSettings(row, col);
366
- setContextMenuCell({ row, col, ...settings });
367
-
368
- const modal = document.getElementById('cellSettingsModal');
369
- if (modal) {
370
- modal.style.display = 'block';
371
- modal.style.left = '50%';
372
- modal.style.top = '50%';
373
- modal.style.transform = 'translate(-50%, -50%)';
374
- }
375
- }
376
- },
377
- 'reset_cell': {
378
- name: 'Сбросить настройки ячейки',
379
- callback: (key, selection) => {
380
- if (!selection?.length) return;
381
- selection.forEach(sel => {
382
- const { start, end } = sel;
383
- for (let r = start.row; r <= end.row; r++) {
384
- for (let c = start.col; c <= end.col; c++) {
385
- updateCellSettings(r, c, null);
386
- }
387
- }
388
- });
389
- saveTable();
390
- }
391
- }
392
- }
393
- });
394
-
395
- // Кастомный рендерер с форматированием
396
- const createRenderer = () => (instance, td, row, col, prop, value, cellProperties) => {
397
- const settings = getCellSettings(row, col);
398
-
399
- td.style.backgroundColor = settings.color && settings.color !== '#FFFFFF' ? settings.color : '';
400
- td.style.color = settings.fontColor && settings.fontColor !== '#000000' ? settings.fontColor : '';
401
- td.style.fontWeight = settings.bold ? 'bold' : '';
402
- td.style.fontStyle = settings.italic ? 'italic' : '';
403
- td.style.textDecoration = settings.underline ? 'underline' : '';
404
- if (settings.align) td.style.textAlign = settings.align;
405
-
406
- if (settings.type === 'checkbox') {
407
- td.innerHTML = '';
408
- td.style.textAlign = 'center';
409
- td.style.verticalAlign = 'middle';
410
-
411
- const checkbox = document.createElement('input');
412
- checkbox.type = 'checkbox';
413
- checkbox.checked = Boolean(value);
414
- checkbox.style.cursor = 'pointer';
415
- checkbox.addEventListener('change', (e) => {
416
- instance.setDataAtCell(row, col, e.target.checked);
417
- saveTable();
418
- });
419
- td.appendChild(checkbox);
420
- } else {
421
- textRenderer(instance, td, row, col, prop, value, cellProperties);
422
- }
423
-
424
- return td;
425
- };
426
-
427
- // Закрытие модального окна
428
- const closeModal = () => {
429
- const modal = document.getElementById('cellSettingsModal');
430
- if (modal) modal.style.display = 'none';
431
- setContextMenuCell(null);
432
- saveTable();
433
- };
434
-
435
- // Пересчёт настроек при перемещении строк/столбцов
436
- const remapCellSettingsAfterMove = (type, movedIndexes, finalIndex) => {
437
- const hot = hotRef.current?.hotInstance;
438
- if (!hot) return;
439
-
440
- const count = type === 'row' ? hot.countRows() : hot.countCols();
441
- const remaining = Array.from({ length: count }, (_, i) => i).filter(i => !movedIndexes.includes(i));
442
- remaining.splice(finalIndex, 0, ...movedIndexes);
443
-
444
- const mapping = {};
445
- remaining.forEach((oldIdx, newIdx) => { mapping[oldIdx] = newIdx; });
446
-
447
- const newSettings = {};
448
- Object.entries(cellSettings).forEach(([key, val]) => {
449
- const [r, c] = key.split(',').map(Number);
450
- const newRow = type === 'row' ? mapping[r] : r;
451
- const newCol = type === 'col' ? mapping[c] : c;
452
- if (newRow !== undefined && newCol !== undefined) {
453
- newSettings[`${newRow},${newCol}`] = val;
454
- }
455
- });
456
-
457
- setCellSettings(newSettings);
458
- };
459
-
460
- const containerStyle = compactMode
461
- ? { height: '100%', display: 'flex', flexDirection: 'column' }
462
- : {};
463
-
464
- const tableWrapperStyle = compactMode
465
- ? { flex: 1, minHeight: '240px', height: '100%' }
466
- : {};
467
-
468
- const hotTableSizing = compactMode
469
- ? {}
470
- : {
471
- height: '70vh',
472
- width: '100%'
473
- };
474
-
475
- return (
476
- <div style={containerStyle} className="nodrag">
477
- {/* Скрытый input для импорта */}
478
- <input
479
- type="file"
480
- ref={fileInputRef}
481
- style={{ display: 'none' }}
482
- />
483
-
484
- {/* Панель управления */}
485
- {!compactMode && (
486
- <div style={{ marginBottom: '15px', display: 'flex', alignItems: 'center', gap: '10px', flexWrap: 'wrap' }}>
487
- <input
488
- value={title}
489
- onChange={e => {
490
- const nextTitle = e.target.value;
491
- setTitle(nextTitle);
492
- if (onTitleChange) {
493
- onTitleChange(nextTitle);
494
- }
495
- }}
496
- style={{ fontSize: '20px', padding: '8px', width: '350px' }}
497
- placeholder="Название таблицы"
498
- />
499
-
500
- <button
501
- onClick={saveTable}
502
- style={{ padding: '10px 20px', background: '#007bff', color: 'white', fontWeight: 'bold' }}
503
- >
504
- Сохранить
505
- </button>
506
-
507
- {/* Импорт */}
508
- <div style={{ position: 'relative', display: 'inline-block' }}>
509
- <button
510
- onClick={() => setShowImportMenu(!showImportMenu)}
511
- style={{ padding: '10px 20px', background: '#28a745', color: 'white' }}
512
- >
513
- Импорт ▼
514
- </button>
515
- {showImportMenu && (
516
- <div
517
- ref={importMenuRef}
518
- style={{
519
- position: 'absolute', zIndex: 1000, background: 'white',
520
- border: '1px solid #ccc', borderRadius: '4px',
521
- boxShadow: '0 4px 12px rgba(0,0,0,0.15)', minWidth: '180px',
522
- marginTop: '5px'
523
- }}
524
- >
525
- <button onClick={() => { setShowImportMenu(false); handleImport('csv'); }}
526
- style={{ display: 'block', width: '100%', padding: '10px', textAlign: 'left', border: 'none', background: 'transparent', cursor: 'pointer' }}>
527
- CSV
528
- </button>
529
- <button onClick={() => { setShowImportMenu(false); handleImport('json'); }}
530
- style={{ display: 'block', width: '100%', padding: '10px', textAlign: 'left', border: 'none', background: 'transparent', cursor: 'pointer' }}>
531
- JSON (с форматированием)
532
- </button>
533
- <button onClick={() => { setShowImportMenu(false); handleImport('excel'); }}
534
- style={{ display: 'block', width: '100%', padding: '10px', textAlign: 'left', border: 'none', background: 'transparent', cursor: 'pointer' }}>
535
- Excel (.xlsx/.xls)
536
- </button>
537
- </div>
538
- )}
539
- </div>
540
-
541
- {/* Экспорт */}
542
- <div style={{ position: 'relative', display: 'inline-block' }}>
543
- <button
544
- onClick={() => setShowExportMenu(!showExportMenu)}
545
- style={{ padding: '10px 20px', background: '#ffc107', color: 'black', fontWeight: 'bold' }}
546
- >
547
- Экспорт ▼
548
- </button>
549
- {showExportMenu && (
550
- <div
551
- ref={exportMenuRef}
552
- style={{
553
- position: 'absolute', zIndex: 1000, background: 'white',
554
- border: '1px solid #ccc', borderRadius: '4px',
555
- boxShadow: '0 4px 12px rgba(0,0,0,0.15)', minWidth: '180px',
556
- marginTop: '5px'
557
- }}
558
- >
559
- <button onClick={() => { setShowExportMenu(false); exportToCSV(); }}
560
- style={{ display: 'block', width: '100%', padding: '10px', textAlign: 'left', border: 'none', background: 'transparent', cursor: 'pointer' }}>
561
- CSV
562
- </button>
563
- <button onClick={() => { setShowExportMenu(false); exportToJSON(); }}
564
- style={{ display: 'block', width: '100%', padding: '10px', textAlign: 'left', border: 'none', background: 'transparent', cursor: 'pointer' }}>
565
- JSON (с форматированием)
566
- </button>
567
- <button onClick={() => { setShowExportMenu(false); exportToExcel(); }}
568
- style={{ display: 'block', width: '100%', padding: '10px', textAlign: 'left', border: 'none', background: 'transparent', cursor: 'pointer' }}>
569
- Excel (.xlsx)
570
- </button>
571
- </div>
572
- )}
573
- </div>
574
- </div>
575
- )}
576
-
577
- {compactMode && showCompactControls && (
578
- <div style={{ marginBottom: '10px', display: 'flex', gap: '8px', flexWrap: 'wrap', flexShrink: 0 }}>
579
- <input
580
- value={title}
581
- onChange={e => {
582
- const nextTitle = e.target.value;
583
- setTitle(nextTitle);
584
- if (onTitleChange) {
585
- onTitleChange(nextTitle);
586
- }
587
- }}
588
- onBlur={saveTable}
589
- placeholder="Название таблицы"
590
- style={{
591
- padding: '6px 10px',
592
- fontSize: '12px',
593
- borderRadius: '6px',
594
- border: '1px solid #d1d5db',
595
- minWidth: '140px',
596
- flex: '1 1 140px'
597
- }}
598
- />
599
- <div style={{ position: 'relative', display: 'inline-block' }}>
600
- <button
601
- onClick={() => setShowImportMenu(!showImportMenu)}
602
- style={{ padding: '6px 12px', background: '#28a745', color: 'white', fontSize: '12px' }}
603
- >
604
- Импорт ▼
605
- </button>
606
- {showImportMenu && (
607
- <div
608
- ref={importMenuRef}
609
- style={{
610
- position: 'absolute', zIndex: 1000, background: 'white',
611
- border: '1px solid #ccc', borderRadius: '4px',
612
- boxShadow: '0 4px 12px rgba(0,0,0,0.15)', minWidth: '160px',
613
- marginTop: '5px'
614
- }}
615
- >
616
- <button onClick={() => { setShowImportMenu(false); handleImport('csv'); }}
617
- style={{ display: 'block', width: '100%', padding: '8px', textAlign: 'left', border: 'none', background: 'transparent', cursor: 'pointer' }}>
618
- CSV
619
- </button>
620
- <button onClick={() => { setShowImportMenu(false); handleImport('json'); }}
621
- style={{ display: 'block', width: '100%', padding: '8px', textAlign: 'left', border: 'none', background: 'transparent', cursor: 'pointer' }}>
622
- JSON (с форматированием)
623
- </button>
624
- <button onClick={() => { setShowImportMenu(false); handleImport('excel'); }}
625
- style={{ display: 'block', width: '100%', padding: '8px', textAlign: 'left', border: 'none', background: 'transparent', cursor: 'pointer' }}>
626
- Excel (.xlsx/.xls)
627
- </button>
628
- </div>
629
- )}
630
- </div>
631
-
632
- <div style={{ position: 'relative', display: 'inline-block' }}>
633
- <button
634
- onClick={() => setShowExportMenu(!showExportMenu)}
635
- style={{ padding: '6px 12px', background: '#ffc107', color: 'black', fontWeight: 'bold', fontSize: '12px' }}
636
- >
637
- Экспорт ▼
638
- </button>
639
- {showExportMenu && (
640
- <div
641
- ref={exportMenuRef}
642
- style={{
643
- position: 'absolute', zIndex: 1000, background: 'white',
644
- border: '1px solid #ccc', borderRadius: '4px',
645
- boxShadow: '0 4px 12px rgba(0,0,0,0.15)', minWidth: '160px',
646
- marginTop: '5px'
647
- }}
648
- >
649
- <button onClick={() => { setShowExportMenu(false); exportToCSV(); }}
650
- style={{ display: 'block', width: '100%', padding: '8px', textAlign: 'left', border: 'none', background: 'transparent', cursor: 'pointer' }}>
651
- CSV
652
- </button>
653
- <button onClick={() => { setShowExportMenu(false); exportToJSON(); }}
654
- style={{ display: 'block', width: '100%', padding: '8px', textAlign: 'left', border: 'none', background: 'transparent', cursor: 'pointer' }}>
655
- JSON (с форматированием)
656
- </button>
657
- <button onClick={() => { setShowExportMenu(false); exportToExcel(); }}
658
- style={{ display: 'block', width: '100%', padding: '8px', textAlign: 'left', border: 'none', background: 'transparent', cursor: 'pointer' }}>
659
- Excel (.xlsx)
660
- </button>
661
- </div>
662
- )}
663
- </div>
664
- </div>
665
- )}
666
-
667
- {/* Таблица */}
668
- {tableLoaded && (
669
- <div style={tableWrapperStyle} className="nodrag">
670
- <HotTable
671
- ref={hotRef}
672
- data={hotData}
673
- rowHeaders={true}
674
- colHeaders={true}
675
- {...hotTableSizing}
676
- rowHeights={48}
677
- colWidths={100}
678
- stretchH="none"
679
- licenseKey="non-commercial-and-evaluation"
680
- formulas={{engine: HyperFormula}}
681
- contextMenu={createContextMenu()}
682
- manualRowResize={true}
683
- manualColumnResize={true}
684
- manualRowMove={true}
685
- manualColumnMove={true}
686
- fixedColumnsStart={1}
687
- cells={(row, col) => {
688
- const settings = getCellSettings(row, col);
689
- return {
690
- renderer: createRenderer(),
691
- type: settings.type === 'checkbox' ? 'checkbox' : 'text',
692
- className: settings.type === 'checkbox' ? 'htCenter htMiddle' : ''
693
- };
694
- }}
695
- afterRowMove={(moved, final) => { remapCellSettingsAfterMove('row', moved, final); setTimeout(saveTable, 100); }}
696
- afterColumnMove={(moved, final) => { remapCellSettingsAfterMove('col', moved, final); setTimeout(saveTable, 100); }}
697
- afterChange={(changes, source) => source === 'edit' && saveTable()}
698
- />
699
- </div>
700
- )}
701
-
702
- {/* Модальное окно форматирования */}
703
- <div id="cellSettingsModal" style={{
704
- display: 'none', position: 'fixed', zIndex: 1000, background: 'white',
705
- border: '1px solid #ccc', borderRadius: '8px', padding: '20px',
706
- boxShadow: '0 4px 20px rgba(0,0,0,0.15)', minWidth: '400px', maxWidth: '500px'
707
- }}>
708
- {contextMenuCell && (
709
- <>
710
- <h4 style={{ marginBottom: '15px', borderBottom: '1px solid #eee', paddingBottom: '10px' }}>
711
- Форматирование ячейки
712
- <button onClick={closeModal} style={{ float: 'right', background: 'none', border: 'none', fontSize: '20px', cursor: 'pointer' }}>×</button>
713
- </h4>
714
-
715
- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '15px' }}>
716
- <div>
717
- <label style={{ display: 'block', marginBottom: '5px', fontWeight: 'bold' }}>Цвет фона:</label>
718
- <input type="color" value={contextMenuCell.color || '#FFFFFF'}
719
- onChange={e => {
720
- const upd = { ...contextMenuCell, color: e.target.value };
721
- setContextMenuCell(upd);
722
- updateCellSettings(contextMenuCell.row, contextMenuCell.col, { color: e.target.value });
723
- }}
724
- style={{ width: '100%', height: '40px', cursor: 'pointer' }}
725
- />
726
- </div>
727
- <div>
728
- <label style={{ display: 'block', marginBottom: '5px', fontWeight: 'bold' }}>Цвет текста:</label>
729
- <input type="color" value={contextMenuCell.fontColor || '#000000'}
730
- onChange={e => {
731
- const upd = { ...contextMenuCell, fontColor: e.target.value };
732
- setContextMenuCell(upd);
733
- updateCellSettings(contextMenuCell.row, contextMenuCell.col, { fontColor: e.target.value });
734
- }}
735
- style={{ width: '100%', height: '40px', cursor: 'pointer' }}
736
- />
737
- </div>
738
- </div>
739
-
740
- <div style={{ marginTop: '15px' }}>
741
- <label style={{ display: 'block', marginBottom: '5px', fontWeight: 'bold' }}>Формат текста:</label>
742
- <div style={{ display: 'flex', gap: '10px' }}>
743
- <button onClick={() => { const b = !contextMenuCell.bold; setContextMenuCell({...contextMenuCell, bold: b}); updateCellSettings(contextMenuCell.row, contextMenuCell.col, { bold: b }); }}
744
- style={{ padding: '8px 12px', background: contextMenuCell.bold ? '#007bff' : '#e9ecef', color: contextMenuCell.bold ? 'white' : '#495057', border: 'none', borderRadius: '4px', fontWeight: 'bold' }}>B</button>
745
- <button onClick={() => { const i = !contextMenuCell.italic; setContextMenuCell({...contextMenuCell, italic: i}); updateCellSettings(contextMenuCell.row, contextMenuCell.col, { italic: i }); }}
746
- style={{ padding: '8px 12px', background: contextMenuCell.italic ? '#007bff' : '#e9ecef', color: contextMenuCell.italic ? 'white' : '#495057', border: 'none', borderRadius: '4px', fontStyle: 'italic' }}>I</button>
747
- <button onClick={() => { const u = !contextMenuCell.underline; setContextMenuCell({...contextMenuCell, underline: u}); updateCellSettings(contextMenuCell.row, contextMenuCell.col, { underline: u }); }}
748
- style={{ padding: '8px 12px', background: contextMenuCell.underline ? '#007bff' : '#e9ecef', color: contextMenuCell.underline ? 'white' : '#495057', border: 'none', borderRadius: '4px', textDecoration: 'underline' }}>U</button>
749
- </div>
750
- </div>
751
-
752
- <div style={{ marginTop: '15px' }}>
753
- <label style={{ display: 'block', marginBottom: '5px', fontWeight: 'bold' }}>Выравнивание:</label>
754
- <div style={{ display: 'flex', gap: '10px' }}>
755
- {['left', 'center', 'right'].map(align => (
756
- <button key={align} onClick={() => { setContextMenuCell({...contextMenuCell, align}); updateCellSettings(contextMenuCell.row, contextMenuCell.col, { align }); }}
757
- style={{ flex: 1, padding: '8px', background: contextMenuCell.align === align ? '#007bff' : '#e9ecef', color: contextMenuCell.align === align ? 'white' : '#495057', border: 'none', borderRadius: '4px' }}>
758
- {align === 'left' ? '←' : align === 'center' ? '↔' : '→'}
759
- </button>
760
- ))}
761
- </div>
762
- </div>
763
-
764
- <div style={{ marginTop: '15px' }}>
765
- <label style={{ display: 'block', marginBottom: '5px', fontWeight: 'bold' }}>Тип данных:</label>
766
- <div style={{ display: 'flex', gap: '10px' }}>
767
- <button onClick={() => { updateCellSettings(contextMenuCell.row, contextMenuCell.col, { type: 'text' }); closeModal(); }}
768
- style={{ flex: 1, padding: '8px 16px', background: contextMenuCell.type === 'text' ? '#007bff' : '#6c757d', color: 'white', border: 'none', borderRadius: '4px' }}>Текст</button>
769
- <button onClick={() => { updateCellSettings(contextMenuCell.row, contextMenuCell.col, { type: 'checkbox' }); closeModal(); }}
770
- style={{ flex: 1, padding: '8px 16px', background: contextMenuCell.type === 'checkbox' ? '#007bff' : '#6c757d', color: 'white', border: 'none', borderRadius: '4px' }}>Чекбокс</button>
771
- </div>
772
- </div>
773
-
774
- <div style={{ marginTop: '20px', paddingTop: '15px', borderTop: '1px solid #eee', display: 'flex', gap: '10px' }}>
775
- <button onClick={() => { updateCellSettings(contextMenuCell.row, contextMenuCell.col, null); closeModal(); }}
776
- style={{ flex: 1, padding: '8px 16px', background: '#dc3545', color: 'white', border: 'none', borderRadius: '4px' }}>Сбросить</button>
777
- <button onClick={closeModal}
778
- style={{ flex: 1, padding: '8px 16px', background: '#28a745', color: 'white', border: 'none', borderRadius: '4px' }}>Применить</button>
779
- </div>
780
- </>
781
- )}
782
- </div>
783
-
784
- {/* Стили */}
785
- <style>{`
786
- .handsontable td { vertical-align: middle; }
787
- .handsontable td:hover { outline: 2px solid rgba(0,123,255,0.3); outline-offset: -2px; }
788
- .htContextMenu table.htCore { min-width: 220px; }
789
- .htContextMenu td { padding: 8px 12px; }
790
- .htContextMenu td:hover { background-color: #f8f9fa; }
791
- `}</style>
792
- </div>
793
- );
794
- }
795
-
796
- export default TableEditor;