-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathApp.tsx
More file actions
1160 lines (1059 loc) · 54.4 KB
/
App.tsx
File metadata and controls
1160 lines (1059 loc) · 54.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import React, { useState, useCallback, useRef } from 'react';
import JSZip from 'jszip';
import { isEqual } from 'lodash';
import {
Wrench, Search, Globe, Scissors, Scale, Eye,
Upload, Folder, Trash2, Download, FileText,
CheckCircle, AlertCircle, ChevronRight, Menu,
Settings, ListCheck, ArrowLeft, Play, Undo2, Filter, Type, X,
Bold, Italic, Underline, RefreshCw, AArrowUp, AArrowDown
} from 'lucide-react';
import { ProcessedFile, TabId, LogEntry, HierarchySkip } from './types';
interface HeaderInstruction {
id: string;
originalText: string;
shouldSplit: boolean;
addAuthor: boolean;
addBook: boolean;
matchStart?: number;
matchEnd?: number;
}
type SplitMethod = 'tag' | 'header_text' | 'text_pattern';
const NavButton = ({ id, icon: Icon, label, onClick }: { id: TabId, icon: any, label: string, onClick: (id: TabId) => void }) => (
<button
onClick={() => onClick(id)}
className="w-full flex items-center gap-3 px-4 py-3 rounded-xl transition-all duration-200 text-right text-slate-600 hover:bg-blue-50 hover:text-blue-600"
>
<Icon size={18} />
<span className="font-semibold text-sm">{label}</span>
</button>
);
const Modal = ({ isOpen, onClose, title, icon: Icon, children }: { isOpen: boolean, onClose: () => void, title: string, icon: any, children: React.ReactNode }) => {
if (!isOpen) return null;
return (
<div
className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-900/50 backdrop-blur-sm animate-in fade-in duration-200"
onClick={onClose}
>
<div
className="bg-white w-full max-w-4xl max-h-[90vh] rounded-3xl shadow-2xl overflow-hidden flex flex-col animate-in zoom-in-95 duration-200"
onClick={(e) => e.stopPropagation()}
>
<div className="p-6 border-b border-slate-100 flex items-center justify-between bg-white sticky top-0 z-10">
<div className="flex items-center gap-3">
<div className="p-2 bg-blue-50 text-blue-600 rounded-xl">
<Icon size={24} />
</div>
<h3 className="text-xl font-bold text-slate-800">{title}</h3>
</div>
<button
onClick={onClose}
className="p-2 hover:bg-slate-100 rounded-full text-slate-400 transition-colors"
>
<X size={24} />
</button>
</div>
<div className="flex-1 overflow-y-auto p-8">
{children}
</div>
</div>
</div>
);
};
const App: React.FC = () => {
const [loadedFiles, setLoadedFiles] = useState<ProcessedFile[]>([]);
const [history, setHistory] = useState<ProcessedFile[][]>([]);
const [activeTab, setActiveTab] = useState<TabId>('preview');
const [isModalOpen, setIsModalOpen] = useState(false);
const [logs, setLogs] = useState<LogEntry[]>([]);
const [isSidebarOpen, setIsSidebarOpen] = useState(true);
// Form States
const [mergeSrc, setMergeSrc] = useState('h4');
const [mergeTarget, setMergeTarget] = useState('h5');
const [mergeExclude, setMergeExclude] = useState('');
// Split States
const [splitMethod, setSplitMethod] = useState<SplitMethod>('tag');
const [splitTag, setSplitTag] = useState('h2');
const [splitPattern, setSplitPattern] = useState('');
const [splitBookName, setSplitBookName] = useState('');
const [splitAuthor, setSplitAuthor] = useState('');
const [splitRemoveWord, setSplitRemoveWord] = useState('');
const [splitExclude, setSplitExclude] = useState('');
// Split Review State
const [splitStep, setSplitStep] = useState<'setup' | 'review'>('setup');
const [headerInstructions, setHeaderInstructions] = useState<HeaderInstruction[]>([]);
const [repScope, setRepScope] = useState('all');
const [repFind, setRepFind] = useState('');
const [repWith, setRepWith] = useState('');
const [globalFind, setGlobalFind] = useState('');
const [globalReplace, setGlobalReplace] = useState('');
const [hierSkip, setHierSkip] = useState<HierarchySkip>({ h1: false, h2: false, h3: false });
const [previewIdx, setPreviewIdx] = useState(0);
const currentFileContent = loadedFiles[previewIdx]?.content;
const fileInputRef = useRef<HTMLInputElement>(null);
const folderInputRef = useRef<HTMLInputElement>(null);
const textareaRef = useRef<HTMLTextAreaElement>(null);
// --- לוגיקת ניווט וגלילה מעודכנת ---
const scrollToHeader = useCallback((startIndex: number, length: number) => {
const textarea = textareaRef.current;
if (!textarea) return;
textarea.focus();
// בחירת הטקסט גורמת ל-textarea לגלול אוטומטית למיקום (חלקית)
textarea.setSelectionRange(startIndex, startIndex + length);
// ביטול הבחירה הכחולה אחרי זמן קצר מאוד והשארת הסמן שם
setTimeout(() => {
textarea.setSelectionRange(startIndex, startIndex);
// כפיית גלילה על ידי הסרת פוקוס והחזרתו מיד
textarea.blur();
textarea.focus();
}, 0);
}, []);
const previewHeaders = React.useMemo(() => {
if (!currentFileContent) return [];
const headers: { tagName: string; textContent: string; startIndex: number; length: number }[] = [];
// Regex למציאת כותרות ושמירת המיקום המדויק שלהן בטקסט הגולמי
const regex = /<(h[1-6])[^>]*>(.*?)<\/h[1-6]>/gi;
let match;
while ((match = regex.exec(currentFileContent)) !== null) {
headers.push({
tagName: match[1].toUpperCase(),
textContent: match[2].replace(/<[^>]*>/g, ''), // ניקוי תגיות פנימיות
startIndex: match.index,
length: match[0].length
});
}
return headers;
}, [currentFileContent]);
// --------------------------------
const insertTag = (openTag: string, closeTag: string = '') => {
const textarea = textareaRef.current;
if (!textarea) return;
// שמירת מצב להיסטוריה לפני השינוי
pushToHistory();
const start = textarea.selectionStart;
const end = textarea.selectionEnd;
const scrollTop = textarea.scrollTop;
const text = textarea.value;
const selectedText = text.substring(start, end);
let replacement = '';
if (closeTag) {
replacement = `${openTag}${selectedText}${closeTag}`;
} else {
replacement = `${selectedText}${openTag}`;
}
const newContent = text.substring(0, start) + replacement + text.substring(end);
handleContentChange(newContent);
setTimeout(() => {
if (textareaRef.current) {
textareaRef.current.focus();
const newCursorPos = start + openTag.length + selectedText.length + closeTag.length;
textareaRef.current.setSelectionRange(newCursorPos, newCursorPos);
textareaRef.current.scrollTop = scrollTop;
}
}, 10);
};
const addLog = (message: string, type: LogEntry['type'] = 'info') => {
setLogs(prev => [{
timestamp: new Date().toLocaleTimeString(),
message,
type
}, ...prev].slice(0, 50));
};
const pushToHistory = () => {
setHistory(prev => {
if (prev.length > 0 && isEqual(prev[0], loadedFiles)) {
return prev;
}
return [loadedFiles, ...prev].slice(0, 20);
});
};
const undo = () => {
if (history.length === 0) return;
// Find the first state in history that is different from current
let targetIdx = 0;
while (targetIdx < history.length && isEqual(history[targetIdx], loadedFiles)) {
targetIdx++;
}
if (targetIdx >= history.length) {
setHistory([]);
return;
}
const previousState = history[targetIdx];
setHistory(history.slice(targetIdx + 1));
setLoadedFiles(previousState);
addLog("פעולה אחרונה בוטלה. הקבצים הוחזרו למצב קודם.", 'info');
};
const handleNavClick = (id: TabId) => {
setActiveTab(id);
setIsModalOpen(true);
};
const handleFiles = async (files: FileList | null) => {
if (!files) return;
pushToHistory();
const newFiles: ProcessedFile[] = [];
const names: string[] = [];
for (let i = 0; i < files.length; i++) {
const f = files[i];
const content = await f.text();
const cleanFileName = f.name.replace(/\.[^/.]+$/, "");
newFiles.push({
name: cleanFileName,
content: content,
originalName: f.name
});
names.push(cleanFileName);
}
setLoadedFiles(prev => [...prev, ...newFiles]);
addLog(`נטענו ${files.length} קבצים: ${names.join(', ')}`, 'success');
};
const handleContentChange = (newContent: string) => {
const nextFiles = [...loadedFiles];
if (nextFiles[previewIdx]) {
nextFiles[previewIdx] = { ...nextFiles[previewIdx], content: newContent };
setLoadedFiles(nextFiles);
}
};
const handleNameChange = (newName: string) => {
const nextFiles = [...loadedFiles];
if (nextFiles[previewIdx]) {
nextFiles[previewIdx] = { ...nextFiles[previewIdx], name: newName };
setLoadedFiles(nextFiles);
}
};
const checkEx = (text: string, exStr: string) => {
if (!exStr || !exStr.trim()) return false;
const words = exStr.split(',').map(w => w.trim().toLowerCase()).filter(w => w);
return words.some(w => text.toLowerCase().includes(w));
};
const cleanName = (n: string, i: number) => {
return n.replace(/[\\/:*?"<>|]/g, "").substring(0, 80) || `file_${i}`;
};
const applyMerge = () => {
pushToHistory();
let totalMerged = 0;
const nextFiles = loadedFiles.map(f => {
const parser = new DOMParser();
const doc = parser.parseFromString(f.content, 'text/html');
let currentSourceText = "";
let toDel: Element[] = [];
doc.body.querySelectorAll('*').forEach(el => {
const tagName = el.tagName.toLowerCase();
if (tagName === mergeSrc) {
currentSourceText = el.textContent?.trim() || "";
toDel.push(el);
} else if (tagName === mergeTarget) {
if (currentSourceText && !checkEx(el.textContent || "", mergeExclude)) {
el.innerHTML = `${currentSourceText} ${el.innerHTML}`;
totalMerged++;
}
}
});
toDel.forEach(el => {
const next = el.nextSibling;
if (next && next.nodeType === 3 && !next.textContent?.trim()) {
next.remove();
}
el.remove();
});
return { ...f, content: doc.body.innerHTML };
});
setLoadedFiles(nextFiles);
addLog(`חיבור כותרות בוצע. סה"כ חוברו ${totalMerged} כותרות מקור (${mergeSrc}) ליעדים (${mergeTarget}).`, 'success');
};
const applyGlobalReplace = () => {
if (!globalFind) return;
pushToHistory();
const escapedFind = globalFind.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
const regex = new RegExp(escapedFind, 'g');
let totalReplacements = 0;
let filesAffected = 0;
const nextFiles = loadedFiles.map(f => {
const originalContent = f.content;
const matches = originalContent.match(regex);
if (matches) {
const newContent = originalContent.replace(regex, globalReplace);
totalReplacements += matches.length;
filesAffected++;
return { ...f, content: newContent };
}
return f;
});
setLoadedFiles(nextFiles);
addLog(`החלפה גלובלית בוצעה. הוחלפו ${totalReplacements} מופעים ב-${filesAffected} קבצים.`, 'success');
};
const scanHeadersForSplit = () => {
if (loadedFiles.length === 0) {
addLog("אין קבצים טעונים לסריקה", "error");
return;
}
const instructions: HeaderInstruction[] = [];
if (splitMethod === 'tag' || splitMethod === 'header_text') {
loadedFiles.forEach((f, fIdx) => {
const parser = new DOMParser();
const doc = parser.parseFromString(f.content, 'text/html');
doc.body.querySelectorAll(splitTag).forEach((el, elIdx) => {
const text = el.textContent?.trim() || "";
const passesExclude = !checkEx(text, splitExclude);
const matchesPattern = splitMethod === 'header_text' ? text.includes(splitPattern) : true;
if (passesExclude && matchesPattern) {
instructions.push({
id: `${fIdx}-${elIdx}`,
originalText: text,
shouldSplit: true,
addAuthor: !!splitAuthor,
addBook: !!splitBookName
});
}
});
});
} else if (splitMethod === 'text_pattern' && splitPattern) {
loadedFiles.forEach((f, fIdx) => {
const regex = new RegExp(splitPattern.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g');
let match;
let matchCount = 0;
while ((match = regex.exec(f.content)) !== null) {
const context = f.content.substring(Math.max(0, match.index - 20), Math.min(f.content.length, match.index + 20));
instructions.push({
id: `${fIdx}-${matchCount}`,
originalText: context.trim() || `מופע ${matchCount + 1}`,
shouldSplit: true,
addAuthor: !!splitAuthor,
addBook: !!splitBookName,
matchStart: match.index,
matchEnd: regex.lastIndex
});
matchCount++;
}
});
}
setHeaderInstructions(instructions);
setSplitStep('review');
addLog(`נסרקו ${instructions.length} נקודות חיתוך פוטנציאליות בכל הקבצים הטעונים.`, 'info');
};
const applySplit = () => {
pushToHistory();
let newFiles: ProcessedFile[] = [];
let originalFilesAffected = 0;
if (splitMethod === 'tag' || splitMethod === 'header_text') {
loadedFiles.forEach((f, fIdx) => {
const parts = f.content.split(new RegExp(`(<${splitTag}[^>]*>.*?</${splitTag}>)`, 'gi'));
let currentContent = "";
let currentTitle = f.name;
let idx = 0;
let splitCountForThisFile = 0;
parts.forEach(part => {
const isHeader = part.toLowerCase().startsWith(`<${splitTag}`);
if (isHeader) {
const originalText = part.replace(/<[^>]*>/g, '').trim();
let text = originalText;
if (splitRemoveWord) {
const removeRegex = new RegExp(splitRemoveWord.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi');
text = text.replace(removeRegex, '').trim();
}
const instruction = headerInstructions.find(ins => ins.id.startsWith(`${fIdx}-`) && ins.originalText === originalText);
if (instruction && instruction.shouldSplit) {
if (currentContent.trim()) {
newFiles.push({ name: cleanName(currentTitle, idx), content: currentContent.trim() });
splitCountForThisFile++;
}
const finalTitle = (instruction.addBook ? splitBookName + " " : "") + (text || f.name);
currentTitle = finalTitle;
const headerMatch = part.match(/<h[1-6][^>]*>/i);
const openTag = headerMatch ? headerMatch[0] : `<${splitTag}>`;
const closeTag = `</${splitTag}>`;
currentContent = `${openTag}${instruction.addBook ? splitBookName + " " : ""}${text}${closeTag}`;
if (instruction.addAuthor) {
currentContent += `\n${splitAuthor}`;
}
idx++;
} else {
currentContent += part;
}
} else {
currentContent += part;
}
});
if (currentContent.trim()) {
newFiles.push({ name: cleanName(currentTitle, idx), content: currentContent.trim() });
splitCountForThisFile++;
}
if (splitCountForThisFile > 1) originalFilesAffected++;
});
} else {
loadedFiles.forEach((f, fIdx) => {
const fileInstructions = headerInstructions.filter(ins => ins.id.startsWith(`${fIdx}-`) && ins.shouldSplit);
if (fileInstructions.length === 0) {
newFiles.push(f);
return;
}
originalFilesAffected++;
const sortedInstructions = [...fileInstructions].sort((a, b) => (a.matchStart || 0) - (b.matchStart || 0));
let lastPos = 0;
sortedInstructions.forEach((ins, idx) => {
const chunk = f.content.substring(lastPos, ins.matchStart);
if (chunk.trim() || idx > 0) {
newFiles.push({ name: cleanName(`${f.name}_${idx}`, idx), content: chunk.trim() });
}
lastPos = ins.matchStart || 0;
});
const finalChunk = f.content.substring(lastPos);
if (finalChunk.trim()) {
newFiles.push({ name: cleanName(`${f.name}_last`, sortedInstructions.length), content: finalChunk.trim() });
}
});
}
const totalCreated = newFiles.length;
setLoadedFiles(newFiles);
setSplitStep('setup');
addLog(`חיתוך הושלם. נוצרו ${totalCreated} קבצים חדשים מתוך ${originalFilesAffected} קבצי מקור שחולקו.`, 'success');
};
const applyReplaceHeaders = () => {
if (!repFind) return;
pushToHistory();
const regex = new RegExp(repFind, 'g');
let totalUpdated = 0;
const nextFiles = loadedFiles.map(f => {
const parser = new DOMParser();
const doc = parser.parseFromString(f.content, 'text/html');
const selector = repScope === 'all' ? 'h1,h2,h3,h4,h5,h6' : repScope;
doc.body.querySelectorAll(selector).forEach(el => {
if (regex.test(el.innerHTML)) {
el.innerHTML = el.innerHTML.replace(regex, repWith);
totalUpdated++;
}
});
return { ...f, content: doc.body.innerHTML };
});
setLoadedFiles(nextFiles);
addLog(`החלפה בכותרות הושלמה. עודכנו ${totalUpdated} כותרות בטווח ${repScope}.`, 'success');
};
const applySyncH1ToFileName = () => {
pushToHistory();
let totalUpdated = 0;
const nextFiles = loadedFiles.map(f => {
const parser = new DOMParser();
const doc = parser.parseFromString(f.content, 'text/html');
const h1 = doc.querySelector('h1');
if (h1 && h1.textContent?.trim()) {
totalUpdated++;
return { ...f, name: h1.textContent.trim() };
}
return f;
});
setLoadedFiles(nextFiles);
addLog(`שם הקובץ עודכן לפי כותרת H1 ב-${totalUpdated} קבצים.`, 'success');
};
const applySyncFileNameToH1 = () => {
pushToHistory();
let totalUpdated = 0;
const nextFiles = loadedFiles.map(f => {
const parser = new DOMParser();
const doc = parser.parseFromString(f.content, 'text/html');
const h1 = doc.querySelector('h1');
if (h1) {
h1.textContent = f.name;
totalUpdated++;
return { ...f, content: doc.body.innerHTML };
}
return f;
});
setLoadedFiles(nextFiles);
addLog(`כותרת H1 עודכנה לפי שם הקובץ ב-${totalUpdated} קבצים.`, 'success');
};
const applyFixHierarchy = () => {
pushToHistory();
const skipTags = Object.entries(hierSkip).filter(([_, v]) => v).map(([k]) => k);
let totalFilesNormalized = 0;
const nextFiles = loadedFiles.map(f => {
const parser = new DOMParser();
const doc = parser.parseFromString(f.content, 'text/html');
const headers = Array.from(doc.querySelectorAll('h1, h2, h3, h4, h5, h6'));
let found: string[] = [];
headers.forEach(h => {
const tag = h.tagName.toLowerCase();
if(!skipTags.includes(tag)) found.push(tag);
});
found = [...new Set(found)].sort();
const map: Record<string, string> = {};
found.forEach((t, i) => map[t] = 'h' + (i + 1));
let changedInThisFile = false;
headers.forEach(h => {
const oldTag = h.tagName.toLowerCase();
if(map[oldTag] && map[oldTag] !== oldTag) {
const newHeader = doc.createElement(map[oldTag]);
newHeader.innerHTML = h.innerHTML;
h.replaceWith(newHeader);
changedInThisFile = true;
}
});
if (changedInThisFile) totalFilesNormalized++;
return { ...f, content: doc.body.innerHTML };
});
setLoadedFiles(nextFiles);
addLog(`נירמול היררכיה בוצע ב-${totalFilesNormalized} קבצים. רמות שהוחרגו: ${skipTags.length > 0 ? skipTags.join(', ') : 'ללא'}.`, 'success');
};
const downloadAll = async () => {
if (loadedFiles.length === 0) return;
const zip = new JSZip();
loadedFiles.forEach(f => {
zip.file(`${f.name}.txt`, f.content);
});
const blob = await zip.generateAsync({ type: "blob" });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `Otzaria_Output_${new Date().toISOString().split('T')[0]}.zip`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
addLog(`הורדה החלה: קובץ ZIP מכיל ${loadedFiles.length} קבצים.`, 'success');
};
const bulkUpdateInstructions = (field: keyof HeaderInstruction, value: boolean) => {
setHeaderInstructions(prev => prev.map(ins => ({ ...ins, [field]: value })));
};
return (
<div className="flex h-screen bg-slate-50 overflow-hidden" dir="rtl">
<input ref={fileInputRef} type="file" multiple className="hidden" onChange={(e) => handleFiles(e.target.files)} />
<input
ref={folderInputRef}
type="file"
{...({ webkitdirectory: "", directory: "" } as any)}
multiple
className="hidden"
onChange={(e) => handleFiles(e.target.files)}
/>
<aside className={`bg-white border-l border-slate-200 transition-all duration-300 flex flex-col ${isSidebarOpen ? 'w-72' : 'w-0 overflow-hidden'}`}>
<div className="p-6 border-b border-slate-100 flex items-center gap-2">
<div className="p-2 bg-blue-600 rounded-lg text-white">
<Wrench size={24} />
</div>
<h1 className="text-xl font-bold text-slate-800">מעבד קבצים מתקדם</h1>
</div>
<nav className="flex-1 p-4 space-y-2 overflow-y-auto">
<NavButton id="process" icon={Wrench} label="חיבור כותרות" onClick={handleNavClick} />
<NavButton id="replace" icon={Search} label="החלפה בכותרות" onClick={handleNavClick} />
<NavButton id="global" icon={Globe} label="החלפה גלובלית" onClick={handleNavClick} />
<NavButton id="split" icon={Scissors} label="חיתוך מסמך" onClick={handleNavClick} />
<NavButton id="sync_h1" icon={RefreshCw} label="סנכרון H1 ושם קובץ" onClick={handleNavClick} />
<NavButton id="fix" icon={Scale} label="נירמול היררכיה" onClick={handleNavClick} />
</nav>
<div className="p-4 border-t border-slate-100">
<div className="text-xs text-slate-400 text-center">v3.3 - Advanced </div>
</div>
</aside>
<main className="flex-1 flex flex-col min-w-0">
<header className="bg-white border-b border-slate-200 px-8 py-4 flex items-center justify-between sticky top-0 z-10">
<div className="flex items-center gap-4">
<button onClick={() => setIsSidebarOpen(!isSidebarOpen)} className="p-2 hover:bg-slate-100 rounded-lg text-slate-600">
<Menu size={20} />
</button>
<div className="flex items-center gap-2 px-3 py-1 bg-blue-50 text-blue-700 rounded-full text-sm font-medium">
<FileText size={14} />
<span>{loadedFiles.length} קבצים</span>
</div>
</div>
<div className="flex gap-2">
<button
onClick={undo}
disabled={history.length === 0}
className={`flex items-center gap-2 px-3 py-2 rounded-lg transition-colors text-sm font-bold border ${
history.length === 0
? 'text-slate-300 border-slate-100 cursor-not-allowed'
: 'text-slate-600 border-slate-200 hover:bg-slate-50'
}`}
title="בטל פעולה אחרונה"
>
<Undo2 size={16} />
בטל
</button>
<button
onClick={() => fileInputRef.current?.click()}
className="flex items-center gap-2 px-3 py-2 bg-blue-50 text-blue-700 hover:bg-blue-100 rounded-lg transition-colors text-sm font-bold"
>
<FileText size={16} />
טען קבצים
</button>
<button
onClick={() => folderInputRef.current?.click()}
className="flex items-center gap-2 px-3 py-2 bg-blue-50 text-blue-700 hover:bg-blue-100 rounded-lg transition-colors text-sm font-bold"
>
<Folder size={16} />
טען תיקייה
</button>
<button
onClick={() => {
if (loadedFiles.length === 0) return;
pushToHistory();
setLoadedFiles([]);
setHeaderInstructions([]);
setSplitStep('setup');
addLog("כל הקבצים וההגדרות נוקו.", "info");
}}
className="flex items-center gap-2 px-3 py-2 text-red-600 hover:bg-red-50 rounded-lg transition-colors text-sm font-bold mr-2"
>
<Trash2 size={16} />
נקה הכל
</button>
</div>
</header>
<div className="flex-1 overflow-hidden p-8 pb-32 flex flex-col">
<div className="bg-white p-8 rounded-2xl border border-slate-200 shadow-sm flex flex-col flex-1 min-h-0">
<div className="flex items-center justify-between mb-6 shrink-0">
<h3 className="text-xl font-bold text-slate-800 flex items-center gap-2">
<Eye className="text-blue-500" /> תצוגה מקדימה ועריכה
</h3>
<div className="flex items-center gap-4">
<div className="flex items-center gap-2 bg-slate-50 p-2 rounded-lg border border-slate-200">
<span className="text-xs font-bold text-slate-500">שם קובץ:</span>
<input
type="text"
value={loadedFiles[previewIdx]?.name || ''}
onChange={(e) => handleNameChange(e.target.value)}
onFocus={() => pushToHistory()}
className="bg-white border border-slate-200 rounded px-2 py-1 text-xs outline-none focus:ring-1 focus:ring-blue-500 w-48"
/>
</div>
<label className="text-sm font-bold text-slate-600">בחר קובץ:</label>
<select
value={previewIdx}
onChange={e => setPreviewIdx(Number(e.target.value))}
className="p-3 border border-slate-200 rounded-xl text-sm min-w-[200px] outline-none focus:ring-2 focus:ring-blue-500 bg-white"
>
{loadedFiles.length === 0 ? (
<option>אין קבצים טעונים</option>
) : (
loadedFiles.map((f, i) => <option key={i} value={i}>{f.name}</option>)
)}
</select>
</div>
</div>
<div className="flex gap-6 flex-1 min-h-0">
{/* סרגל ניווט כותרות מעודכן עם פונקציית לחיצה */}
<aside className="w-64 border border-slate-200 rounded-xl bg-slate-50 overflow-y-auto p-4 flex flex-col gap-1 shrink-0">
<div className="text-xs font-bold text-slate-400 mb-2 border-b border-slate-200 pb-2">ניווט כותרות</div>
{previewHeaders.length > 0 ? previewHeaders.map((h, i) => (
<button
key={i}
onClick={() => scrollToHeader(h.startIndex, h.length)}
className={`text-right text-[11px] p-1.5 border-r-2 transition-colors hover:bg-white flex flex-col items-start w-full ${
h.tagName === 'H1' ? 'font-bold border-blue-500 bg-blue-50/50' :
h.tagName === 'H2' ? 'mr-2 border-blue-300' :
h.tagName === 'H3' ? 'mr-4 border-slate-300' :
h.tagName === 'H4' ? 'mr-6 border-slate-200' :
h.tagName === 'H5' ? 'mr-8 border-slate-100' :
'mr-10 border-slate-50'
}`}
>
<span className="opacity-50 text-[9px] block mb-0.5">{h.tagName}</span>
<span className="line-clamp-2">{h.textContent}</span>
</button>
)) : <div className="text-xs text-slate-400 italic">לא נמצאו כותרות</div>}
</aside>
{/* אזור העריכה */}
<div className="flex-1 flex flex-col min-h-0 h-full gap-4">
<div className="flex flex-wrap items-center gap-1 p-2 bg-slate-50 border border-slate-200 rounded-xl shrink-0">
<div className="flex items-center gap-1 px-2 border-l border-slate-200 ml-2">
{['H1', 'H2', 'H3', 'H4', 'H5', 'H6'].map(h => (
<button
key={h}
onClick={() => insertTag(`<${h.toLowerCase()}>`, `</${h.toLowerCase()}>`)}
className="px-2 py-1 text-[10px] font-bold bg-white border border-slate-200 rounded hover:bg-blue-50 hover:text-blue-600 transition-colors"
>
{h}
</button>
))}
</div>
<div className="flex items-center gap-1 px-2 border-l border-slate-200 ml-2">
<button onClick={() => insertTag('<b>', '</b>')} className="p-1.5 bg-white border border-slate-200 rounded hover:bg-blue-50 hover:text-blue-600 transition-colors" title="מודגש">
<Bold size={14} />
</button>
<button onClick={() => insertTag('<i>', '</i>')} className="p-1.5 bg-white border border-slate-200 rounded hover:bg-blue-50 hover:text-blue-600 transition-colors" title="נטוי">
<Italic size={14} />
</button>
<button onClick={() => insertTag('<u>', '</u>')} className="p-1.5 bg-white border border-slate-200 rounded hover:bg-blue-50 hover:text-blue-600 transition-colors" title="קו תחתון">
<Underline size={14} />
</button>
</div>
<div className="flex items-center gap-1 px-2 border-l border-slate-200 ml-2">
<button onClick={() => insertTag('<big>', '</big>')} className="p-1.5 bg-white border border-slate-200 rounded hover:bg-blue-50 hover:text-blue-600 transition-colors" title="טקסט גדול">
<AArrowUp size={14} />
</button>
<button onClick={() => insertTag('<small>', '</small>')} className="p-1.5 bg-white border border-slate-200 rounded hover:bg-blue-50 hover:text-blue-600 transition-colors" title="טקסט קטן">
<AArrowDown size={14} />
</button>
</div>
</div>
<div className="flex-1 relative min-h-0">
<textarea
ref={textareaRef}
value={loadedFiles[previewIdx]?.content || ''}
onChange={(e) => handleContentChange(e.target.value)}
onFocus={() => pushToHistory()}
className="w-full h-full bg-white p-8 rounded-2xl border border-slate-200 font-['Assistant'] text-lg leading-[1.6] text-slate-800 outline-none focus:ring-2 focus:ring-blue-400 resize-none overflow-auto shadow-inner"
dir="rtl"
placeholder="אין תוכן להצגה או עריכה"
style={{ fontFeatureSettings: '"kern" 1' }}
/>
</div>
</div>
</div>
</div>
{/* Modals - לא שונו */}
<Modal
isOpen={isModalOpen && activeTab === 'process'}
onClose={() => setIsModalOpen(false)}
title="חיבור כותרות"
icon={Wrench}
>
<div className="space-y-6">
<div className="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
<div>
<label className="block text-sm font-bold text-slate-700 mb-2">מקור:</label>
<select value={mergeSrc} onChange={e => setMergeSrc(e.target.value)} className="w-full p-3 border border-slate-200 rounded-xl outline-none focus:ring-2 focus:ring-blue-500">
{['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].map(h => <option key={h} value={h}>{h.toUpperCase()}</option>)}
</select>
</div>
<div>
<label className="block text-sm font-bold text-slate-700 mb-2">יעד:</label>
<select value={mergeTarget} onChange={e => setMergeTarget(e.target.value)} className="w-full p-3 border border-slate-200 rounded-xl outline-none focus:ring-2 focus:ring-blue-500">
{['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].map(h => <option key={h} value={h}>{h.toUpperCase()}</option>)}
</select>
</div>
</div>
<div className="p-4 bg-orange-50 border border-orange-100 rounded-xl mb-6">
<label className="block text-sm font-bold text-orange-800 mb-2">החרג יעד המכיל (פסיק להפרדה):</label>
<input
type="text"
value={mergeExclude}
onChange={e => setMergeExclude(e.target.value)}
placeholder="מילה1, מילה2..."
className="w-full p-3 bg-white border border-orange-200 rounded-lg outline-none focus:ring-2 focus:ring-orange-500"
/>
</div>
<button onClick={() => { applyMerge(); setIsModalOpen(false); }} className="w-full py-4 bg-slate-800 text-white rounded-xl font-bold hover:bg-slate-900 transition-all shadow-lg">בצע חיבור</button>
</div>
</Modal>
<Modal
isOpen={isModalOpen && activeTab === 'replace'}
onClose={() => setIsModalOpen(false)}
title="החלפה בכותרות"
icon={Search}
>
<div className="space-y-6">
<div className="grid grid-cols-1 gap-6 mb-6">
<div>
<label className="block text-sm font-bold text-slate-700 mb-2">החל על:</label>
<select value={repScope} onChange={e => setRepScope(e.target.value)} className="w-full p-3 border border-slate-200 rounded-xl">
<option value="all">כל הכותרות</option>
{['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].map(h => <option key={h} value={h}>{h.toUpperCase()}</option>)}
</select>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div>
<label className="block text-sm font-bold text-slate-700 mb-2">חפש (Regex תומך):</label>
<input type="text" value={repFind} onChange={e => setRepFind(e.target.value)} className="w-full p-3 border border-slate-200 rounded-xl" />
</div>
<div>
<label className="block text-sm font-bold text-slate-700 mb-2">החלף ב:</label>
<input type="text" value={repWith} onChange={e => setRepWith(e.target.value)} className="w-full p-3 border border-slate-200 rounded-xl" />
</div>
</div>
</div>
<button onClick={() => { applyReplaceHeaders(); setIsModalOpen(false); }} className="w-full py-4 bg-slate-800 text-white rounded-xl font-bold hover:bg-slate-900 transition-all shadow-lg">בצע החלפה</button>
</div>
</Modal>
<Modal
isOpen={isModalOpen && activeTab === 'global'}
onClose={() => setIsModalOpen(false)}
title="החלפה גלובלית בטקסט"
icon={Globe}
>
<div className="space-y-6">
<div className="space-y-6 mb-6">
<div>
<label className="block text-sm font-bold text-slate-700 mb-2">חפש טקסט:</label>
<textarea value={globalFind} onChange={e => setGlobalFind(e.target.value)} rows={3} className="w-full p-4 border border-slate-200 rounded-xl resize-none outline-none focus:ring-2 focus:ring-blue-500" />
</div>
<div>
<label className="block text-sm font-bold text-slate-700 mb-2">החלף בטקסט:</label>
<textarea value={globalReplace} onChange={e => setGlobalReplace(e.target.value)} rows={3} className="w-full p-4 border border-slate-200 rounded-xl resize-none outline-none focus:ring-2 focus:ring-blue-500" />
</div>
</div>
<button onClick={() => { applyGlobalReplace(); setIsModalOpen(false); }} className="w-full py-4 bg-slate-800 text-white rounded-xl font-bold hover:bg-slate-900 transition-all shadow-lg">בצע החלפה גלובלית</button>
</div>
</Modal>
<Modal
isOpen={isModalOpen && activeTab === 'split'}
onClose={() => setIsModalOpen(false)}
title="חיתוך מסמך לקבצים נפרדים"
icon={Scissors}
>
<div className="space-y-6">
{splitStep === 'setup' ? (
<div className="space-y-6 animate-in slide-in-from-right duration-300">
<div className="space-y-6">
<div>
<label className="block text-sm font-bold text-slate-700 mb-2">שיטת חיתוך:</label>
<select
value={splitMethod}
onChange={e => setSplitMethod(e.target.value as SplitMethod)}
className="w-full p-3 border border-slate-200 rounded-xl outline-none focus:ring-2 focus:ring-blue-500"
>
<option value="tag">לפי תגית כותרת בלבד</option>
<option value="header_text">לפי כותרת המכילה מילה</option>
<option value="text_pattern">בכל פעם שמופיע טקסט</option>
</select>
</div>
{splitMethod !== 'text_pattern' && (
<div>
<label className="block text-sm font-bold text-slate-700 mb-2">תגית כותרת:</label>
<select value={splitTag} onChange={e => setSplitTag(e.target.value)} className="w-full p-3 border border-slate-200 rounded-xl outline-none focus:ring-2 focus:ring-blue-500">
{['h1', 'h2', 'h3', 'h4'].map(h => <option key={h} value={h}>{h.toUpperCase()}</option>)}
</select>
</div>
)}
{splitMethod !== 'tag' && (
<div>
<label className="block text-sm font-bold text-slate-700 mb-2">
{splitMethod === 'header_text' ? 'מילה לחיפוש בתוך הכותרת:' : 'טקסט/ביטוי לחיתוך (בכל הופעה):'}
</label>
<input
type="text"
value={splitPattern}
onChange={e => setSplitPattern(e.target.value)}
placeholder={splitMethod === 'header_text' ? 'לדוגמה: "פרק"' : 'לדוגמה: "###"'}
className="w-full p-3 border border-slate-200 rounded-xl outline-none focus:ring-2 focus:ring-blue-500"
/>
</div>
)}
</div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
<div>
<label className="block text-sm font-bold text-slate-700 mb-2">שם המחבר להוספה:</label>
<input type="text" value={splitAuthor} onChange={e => setSplitAuthor(e.target.value)} className="w-full p-3 border border-slate-200 rounded-xl outline-none focus:ring-2 focus:ring-blue-500" />
</div>
<div>
<label className="block text-sm font-bold text-slate-700 mb-2">שם הספר להוספה (בתחילת שם הקובץ):</label>
<input type="text" value={splitBookName} onChange={e => setSplitBookName(e.target.value)} placeholder="לדוגמה: יד דוד על..." className="w-full p-3 border border-slate-200 rounded-xl outline-none focus:ring-2 focus:ring-blue-500" />
</div>
<div>
<label className="block text-sm font-bold text-slate-700 mb-2">מילה להסרה מהכותרת:</label>
<input type="text" value={splitRemoveWord} onChange={e => setSplitRemoveWord(e.target.value)} placeholder="לדוגמה: מסכת" className="w-full p-3 border border-slate-200 rounded-xl outline-none focus:ring-2 focus:ring-blue-500" />
</div>
</div>
<div className="p-4 bg-slate-50 border border-slate-200 rounded-2xl">
<label className="flex items-center gap-2 text-sm font-bold text-slate-700 mb-2">
<AlertCircle size={14} /> סנן והחרג אם מכיל...
</label>
<input
type="text"
value={splitExclude}
onChange={e => setSplitExclude(e.target.value)}
placeholder="לדוגמה: נספח, הקדמה, ביבליוגרפיה..."
className="w-full p-3 bg-white border border-slate-200 rounded-xl outline-none focus:ring-2 focus:ring-blue-500"
/>
</div>
<button
onClick={scanHeadersForSplit}
disabled={loadedFiles.length === 0}
className="w-full py-4 bg-blue-600 text-white rounded-xl font-bold hover:bg-blue-700 transition-all shadow-lg flex items-center justify-center gap-2"
>
<ListCheck size={20} /> סרוק ובחר נקודות חיתוך
</button>
</div>
) : (
<div className="space-y-6 animate-in slide-in-from-left duration-300">
<div className="flex justify-end">
<button
onClick={() => setSplitStep('setup')}
className="flex items-center gap-2 text-sm text-blue-600 hover:text-blue-800 font-bold"
>
<ArrowLeft size={16} /> חזרה להגדרות
</button>
</div>
<div className="bg-slate-50 border border-slate-200 rounded-xl p-4 overflow-x-auto">
<table className="w-full text-right text-sm">
<thead>
<tr className="border-b border-slate-200 text-slate-600">
<th className="pb-3 pr-2">נקודת חיתוך</th>
<th className="pb-3 text-center">
<div>בצע חיתוך?</div>
<div className="flex justify-center gap-2 mt-1">
<button onClick={() => bulkUpdateInstructions('shouldSplit', true)} className="text-[10px] bg-blue-100 text-blue-700 px-1 rounded hover:bg-blue-200">הכל</button>
<button onClick={() => bulkUpdateInstructions('shouldSplit', false)} className="text-[10px] bg-slate-200 text-slate-700 px-1 rounded hover:bg-slate-300">ללא</button>
</div>
</th>
<th className="pb-3 text-center">
<div>הוסף מחבר?</div>
<div className="flex justify-center gap-2 mt-1">
<button onClick={() => bulkUpdateInstructions('addAuthor', true)} className="text-[10px] bg-blue-100 text-blue-700 px-1 rounded hover:bg-blue-200">הכל</button>
<button onClick={() => bulkUpdateInstructions('addAuthor', false)} className="text-[10px] bg-slate-200 text-slate-700 px-1 rounded hover:bg-slate-300">ללא</button>
</div>
</th>
<th className="pb-3 text-center">
<div>הוסף ספר?</div>
<div className="flex justify-center gap-2 mt-1">
<button onClick={() => bulkUpdateInstructions('addBook', true)} className="text-[10px] bg-blue-100 text-blue-700 px-1 rounded hover:bg-blue-200">הכל</button>
<button onClick={() => bulkUpdateInstructions('addBook', false)} className="text-[10px] bg-slate-200 text-slate-700 px-1 rounded hover:bg-slate-300">ללא</button>
</div>
</th>
</tr>
</thead>
<tbody className="divide-y divide-slate-100">
{headerInstructions.map((ins, i) => (
<tr key={ins.id} className="hover:bg-blue-50/30 transition-colors">