-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEditorArea.tsx
More file actions
838 lines (792 loc) · 35.2 KB
/
EditorArea.tsx
File metadata and controls
838 lines (792 loc) · 35.2 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
import Editor, { DiffEditor } from '@monaco-editor/react'
import { useShuriStore } from '../state/store'
import { useMemo, useRef, useEffect, useState } from 'react'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faBookOpen, faWandMagicSparkles, faPaperPlane } from '@fortawesome/free-solid-svg-icons'
export function EditorArea() {
const {
editor,
setEditor,
addEditorPage,
closeEditorPage,
setActiveEditorPage,
updateEditorPageContent,
renameEditorPage,
addChatTab,
closeChatTab,
setActiveChatTab,
addChatMessage,
renameChatTab,
addKanjiGuide,
removeKanjiGuide,
updateKanjiGuide,
createSeries,
renameSeries,
deleteSeries,
setActiveSeries,
} = useShuriStore()
const activePage = useMemo(() => editor.pages.find(p => p.id === editor.activePageId) || null, [editor.pages, editor.activePageId])
const leftWidth = 0
const rightWidth = editor.rightPanelWidth
const resizing = useRef<{ side: 'left' | 'right' | null }>({ side: null })
const editorRef = useRef<any>(null)
const monacoRef = useRef<any>(null)
function insertPrefixAtLineStart(prefix: string) {
if (!activePage || !editorRef.current || !monacoRef.current) return
const ed = editorRef.current
const monaco = monacoRef.current
const pos = ed.getPosition()
if (!pos) return
const lineNumber = pos.lineNumber
ed.executeEdits('format-prefix', [
{
range: new monaco.Range(lineNumber, 1, lineNumber, 1),
text: `${prefix} `,
forceMoveMarkers: true,
},
])
// keep cursor after inserted text automatically by Monaco
}
// Keyboard shortcuts (adapted to avoid Monaco conflicts):
// Alt+I: * | Ctrl+B: [* | Alt+H: ~ | Ctrl+Shift+H: ~! | Ctrl+W: ~...
// Ctrl+1: !! | Ctrl+2: /!! | Ctrl+3: () | Ctrl+4: "" | Ctrl+5: []
useEffect(() => {
function onKey(e: KeyboardEvent) {
if (!editorRef.current || !editorRef.current.hasTextFocus?.()) return
let prefix: string | null = null
const k = e.key
if (e.altKey && (k === 'i' || k === 'I')) prefix = '*'
else if (e.ctrlKey && (k === 'b' || k === 'B')) prefix = '[*'
else if (e.ctrlKey && (k === 'w' || k === 'W')) prefix = '~...'
else if (e.altKey && k === 'h') prefix = '~'
else if (e.ctrlKey && k === 'H') prefix = '~!'
else if (e.ctrlKey && k === '1') prefix = '!!'
else if (e.ctrlKey && k === '2') prefix = '/!!'
else if (e.ctrlKey && k === '3') prefix = '()'
else if (e.ctrlKey && k === '4') prefix = '""'
else if (e.ctrlKey && k === '5') prefix = '[]'
if (prefix) {
e.preventDefault()
insertPrefixAtLineStart(prefix)
}
}
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [])
// UI state for inline tab rename
const [editingTabId, setEditingTabId] = useState<string | null>(null)
const [tabDraft, setTabDraft] = useState<string>('')
function commitTabRename() {
if (editingTabId) {
renameEditorPage(editingTabId, tabDraft.trim() || 'Untitled')
setEditingTabId(null)
}
}
// Global mouse listeners for reliable resizing
useEffect(() => {
function handleMove(e: MouseEvent) {
if (resizing.current.side === 'left') {
const newWidth = Math.max(260, Math.min(520, e.clientX))
setEditor({ leftPanelWidth: newWidth })
} else if (resizing.current.side === 'right') {
const container = (document.querySelector('#editor-root') as HTMLElement)
const total = container ? container.getBoundingClientRect().width : window.innerWidth
const newWidth = Math.max(220, Math.min(560, total - e.clientX))
setEditor({ rightPanelWidth: newWidth })
}
}
function handleUp() { resizing.current.side = null }
window.addEventListener('mousemove', handleMove)
window.addEventListener('mouseup', handleUp)
return () => {
window.removeEventListener('mousemove', handleMove)
window.removeEventListener('mouseup', handleUp)
}
}, [setEditor])
// Auto-resize character panel to fit controls row
useEffect(() => {
// No left panel
}, [])
const tabBg = 'bg-gray-800'
const tabHoverBg = 'hover:bg-gray-700'
const monoGreen = '#a6e22e'
const activeChatTab = useMemo(() => editor.chatTabs.find(t => t.id === editor.activeChatTabId) || null, [editor.chatTabs, editor.activeChatTabId])
const [chatInput, setChatInput] = useState('')
const [chatAskDiff, setChatAskDiff] = useState(false)
const [isTyping, setIsTyping] = useState(false)
const [typingDots, setTypingDots] = useState('')
const [showInlineDiff, setShowInlineDiff] = useState<{ original: string; modified: string } | null>(null)
const chatListRef = useRef<HTMLDivElement | null>(null)
// Kanji guide panel state
const [showKanjiGuide, setShowKanjiGuide] = useState(false)
const [newKanji, setNewKanji] = useState('')
const [newTranslation, setNewTranslation] = useState('')
const [newContext, setNewContext] = useState('')
// Series modals state
const [showNewSeriesModal, setShowNewSeriesModal] = useState(false)
const [showRenameSeriesModal, setShowRenameSeriesModal] = useState(false)
const [showDeleteSeriesModal, setShowDeleteSeriesModal] = useState(false)
const [seriesInput, setSeriesInput] = useState('')
// Edit kanji modal state
const [editingKanji, setEditingKanji] = useState<string | null>(null)
const [kanjiDraft, setKanjiDraft] = useState('')
const [translationDraft, setTranslationDraft] = useState('')
const [contextDraft, setContextDraft] = useState('')
// Get current series kanji guides for AI context
const currentSeriesKanjiGuides = useMemo(() => {
const activeSeries = editor.activeSeries || 'Default'
return editor.seriesPresets[activeSeries]?.kanjiGuides || []
}, [editor.seriesPresets, editor.activeSeries])
// Helper function to format kanji guides for AI prompts
const formatKanjiGuides = (guides: typeof currentSeriesKanjiGuides) => {
if (guides.length === 0) return ''
return `\n\nKanji Guide Reference (use these translations for consistency):\n${guides.map(guide =>
`• ${guide.kanji}: ${guide.translation}${guide.context ? ` (${guide.context})` : ''}`
).join('\n')}`
}
// Kanji guide management functions
const handleAddKanjiGuide = () => {
if (!newKanji.trim() || !newTranslation.trim()) return
const activeSeries = editor.activeSeries || 'Default'
addKanjiGuide(activeSeries, newKanji.trim(), newTranslation.trim(), newContext.trim() || undefined)
setNewKanji('')
setNewTranslation('')
setNewContext('')
}
const handleRemoveKanjiGuide = (kanji: string) => {
const activeSeries = editor.activeSeries || 'Default'
removeKanjiGuide(activeSeries, kanji)
}
const handleUpdateKanjiGuide = (oldKanji: string, newKanji: string, translation: string, context?: string) => {
const activeSeries = editor.activeSeries || 'Default'
updateKanjiGuide(activeSeries, oldKanji, newKanji, translation, context)
}
useEffect(() => {
// auto scroll to bottom
const el = chatListRef.current
if (el) el.scrollTop = el.scrollHeight
}, [activeChatTab?.messages])
// Typing animation effect
useEffect(() => {
let interval: NodeJS.Timeout
if (isTyping) {
let dots = ''
interval = setInterval(() => {
dots = dots.length >= 3 ? '' : dots + '.'
setTypingDots(dots)
}, 500)
}
return () => {
if (interval) clearInterval(interval)
}
}, [isTyping])
async function handleChatSend() {
const text = chatInput.trim()
if (!text || !activeChatTab) return
const userMessage = { role: 'user' as const, text, timestamp: Date.now() }
addChatMessage(activeChatTab.id, userMessage)
setChatInput('')
setIsTyping(true)
try {
const { chatComplete } = await import('../api/client')
const pageText = activePage?.content || ''
const kanjiContext = formatKanjiGuides(currentSeriesKanjiGuides)
const wantsDiff = chatAskDiff
if (wantsDiff) {
// For diff requests, ask for the improved text only
const system = 'You are assisting with manga dialogue editing. Be conservative. Suggest improvements only if necessary. CRITICAL: Maintain EXACT line count, spacing, and empty lines - these are important for manga formatting and dialogue timing. Do NOT remove or consolidate empty lines. PRESERVE spaces after formatting prefixes (like ~, ~!, ~..., !!, etc.) as they are required for TyperTools compatibility. Only make improvements to spelling, grammar, word choice, and character consistency. IMPORTANT: Output ONLY the improved text with no explanations, no markdown, no code blocks, no quotes, no delimiters, and ABSOLUTELY NO kanji guide references or any other reference material in your response.'
const prompt = pageText
? `${system}\n\n=== TEXT TO IMPROVE ===\n${pageText}\n\n=== REFERENCE ONLY - DO NOT INCLUDE IN OUTPUT ===\n${kanjiContext}\n\n=== USER REQUEST ===\n${text}\n\n=== OUTPUT ONLY THE IMPROVED TEXT BELOW THIS LINE ===\n`
: `${system}\n\n=== REFERENCE ONLY - DO NOT INCLUDE IN OUTPUT ===\n${kanjiContext}\n\n=== USER REQUEST ===\n${text}\n\n=== OUTPUT ONLY THE IMPROVED TEXT BELOW THIS LINE ===\n`
const response = await chatComplete(prompt)
let improvedText = response.text.trim()
// Clean up any potential formatting artifacts
improvedText = improvedText.replace(/^---+\n?/gm, '') // Remove leading ---
improvedText = improvedText.replace(/\n?---+$/gm, '') // Remove trailing ---
improvedText = improvedText.replace(/^```.*\n?/gm, '') // Remove code block markers
improvedText = improvedText.replace(/\n?```$/gm, '') // Remove code block end markers
improvedText = improvedText.replace(/^\s*["']|["']\s*$/gm, '') // Remove quotes
// Remove any kanji guide references that might have slipped through
improvedText = improvedText.replace(/\n*Kanji Guide Reference:.*?(?=\n\n|\n*$)/gis, '') // Remove kanji guide sections
improvedText = improvedText.replace(/\n*=== REFERENCE ONLY.*?(?=\n===|\n*$)/gis, '') // Remove reference sections
improvedText = improvedText.replace(/\n*=== OUTPUT ONLY.*?(?=\n\n|\n*$)/gis, '') // Remove output instruction sections
// Check if there are actual changes
if (improvedText === pageText.trim()) {
// No changes needed - show a toast notification
addChatMessage(activeChatTab.id, {
role: 'assistant',
text: '✅ No improvements needed. Your text is already good!',
timestamp: Date.now()
})
setShowInlineDiff(null)
} else {
// Show diff inline in the editor
setShowInlineDiff({
original: pageText,
modified: improvedText
})
addChatMessage(activeChatTab.id, {
role: 'assistant',
text: `📝 Suggested improvements shown in editor. You can accept or reject them.\n\n💰 Cost: ${response.cost}`,
timestamp: Date.now()
})
}
} else {
// Regular chat response
const system = 'You are assisting with manga dialogue editing. Be helpful and concise. Remember that empty lines are important for manga formatting and dialogue timing - do not suggest removing them. Also preserve spaces after formatting prefixes (like ~, ~!, ~..., !!, etc.) as they are required for TyperTools compatibility.'
const prompt = pageText
? `${system}\n\nCurrent page content (for context only):\n${pageText}\n\nKanji Guide Reference:\n${kanjiContext}\n\nUser request:\n${text}`
: `${system}\n\nKanji Guide Reference:\n${kanjiContext}\n\nUser request:\n${text}`
const response = await chatComplete(prompt)
addChatMessage(activeChatTab.id, {
role: 'assistant',
text: `${response.text}\n\n💰 Cost: ${response.cost}`,
timestamp: Date.now()
})
}
} catch (e) {
console.error('Chat error:', e)
addChatMessage(activeChatTab.id, { role: 'assistant', text: '❌ Error: failed to get reply', timestamp: Date.now() })
} finally {
setIsTyping(false)
}
}
return (
<>
<main id="editor-root" className="flex-1 bg-gray-900 flex overflow-hidden">
{/* Left resizable Characters panel */}
{/* Left resizer */}
<div
onMouseDown={() => { resizing.current.side = 'left' }}
className="w-1 cursor-col-resize bg-gray-700/50"
/>
{/* Center editor */}
<section className="flex-1 flex flex-col overflow-hidden">
{/* Tabs and toolbar */}
<div className="h-10 flex items-stretch px-0 border-b border-gray-700 bg-gray-800 flex-shrink-0">
{/* Tabs */}
<div className={`flex items-stretch overflow-x-auto overflow-y-hidden flex-nowrap w-full scrollbar-h-transparent`}>
{editor.pages.map(p => (
<div
key={p.id}
className={`h-10 px-3 border-r border-gray-700 rounded-none flex items-center gap-2 flex-shrink-0 select-none ${tabBg} ${tabHoverBg} ${editor.activePageId===p.id ? 'text-[#a6e22e] border-b-2' : 'text-gray-300'} `}
onClick={()=>setActiveEditorPage(p.id)}
onDoubleClick={(e)=>{ e.stopPropagation(); setEditingTabId(p.id); setTabDraft(p.name) }}
>
{editingTabId === p.id ? (
<input autoFocus value={tabDraft} onChange={(e)=>setTabDraft(e.target.value)} onBlur={commitTabRename} onKeyDown={(e)=>{ if (e.key==='Enter') commitTabRename(); if (e.key==='Escape') setEditingTabId(null) }} className="bg-transparent text-xs text-gray-200 border border-gray-700 rounded px-1 max-w-[160px]" />
) : (
<span className="text-xs truncate max-w-[160px]">{p.name}</span>
)}
<button className="text-gray-500 hover:text-gray-300 text-xs" onClick={(e)=>{e.stopPropagation(); closeEditorPage(p.id)}}>x</button>
</div>
))}
<button className={`h-10 px-3 border-l border-gray-700 rounded-none flex items-center justify-center flex-shrink-0 ${tabBg} ${tabHoverBg} text-[#a6e22e]`} onClick={()=>addEditorPage('New Page')}>+</button>
</div>
</div>
{/* Toolbar row (no gaps; monokai green and body background) */}
<div className="h-11 border-b border-gray-700 bg-gray-800 flex-shrink-0">
<div className={`grid grid-flow-col auto-cols-[minmax(52px,1fr)] gap-0 w-full h-full overflow-x-auto scrollbar-h-transparent`}>
{['kanji', 'grammar', 'I', 'B', 'H', 'HB', 'W', '!!', 'I!!', '()', '""', '[]'].map((t) => {
const isFormat = ['I','B','H','HB','W','!!','!!!','()','""','[]'].includes(t)
const formatMap: Record<string,string> = { I: '*', B: '[*', H: '~', HB: '~!', W: '~...', '!!': '!!', 'I!!': '/!!', '()': '()', '""': '""', '[]': '[]' }
return (
<button
key={t}
title={
t === 'kanji' ? 'Kanji Guide' :
t === 'grammar' ? 'Quick Grammar Check' : t
}
className={`rounded-none ${tabBg} ${tabHoverBg} text-xs text-[#a6e22e] grid place-items-center h-full border-r border-gray-700`}
onClick={() => {
if (t === 'kanji') { setShowKanjiGuide(!showKanjiGuide); return }
if (t === 'grammar') {
// Quick grammar check - automatically trigger with "Request diff" enabled
const originalAskDiff = chatAskDiff
const originalChatInput = chatInput
setChatAskDiff(true)
setChatInput('Please check for grammar and style improvements.')
// Use setTimeout to ensure state updates before calling handleChatSend
setTimeout(() => {
handleChatSend()
setChatAskDiff(originalAskDiff)
setChatInput(originalChatInput)
}, 0)
return
}
if (isFormat) insertPrefixAtLineStart(formatMap[t] || t)
}}
>
{t === 'kanji' ? (
<FontAwesomeIcon icon={faBookOpen} className="text-sm" />
) : t === 'grammar' ? (
<FontAwesomeIcon icon={faWandMagicSparkles} className="text-xs" />
) : (
t
)}
</button>
)
})}
</div>
</div>
{/* Kanji Guide Dropdown Overlay */}
{showKanjiGuide && (
<div className="absolute left-1/2 transform -translate-x-1/2 top-3 z-50 bg-gray-800 border border-gray-700 rounded-lg shadow-xl max-w-md w-full mx-2">
<div className="p-4 pt-6">
<div className="flex items-center justify-between mb-3">
<div className="flex items-center gap-2">
<h4 className="text-xs font-medium text-gray-300">Kanji Guide</h4>
<select
value={editor.activeSeries}
onChange={(e) => setActiveSeries(e.target.value)}
className="bg-gray-700 border border-gray-600 rounded px-2 py-1 text-xs text-gray-200"
>
{Object.keys(editor.seriesPresets).map(series => (
<option key={series} value={series}>{series}</option>
))}
</select>
</div>
<div className="flex items-center gap-2">
<button
onClick={() => { setSeriesInput(''); setShowNewSeriesModal(true) }}
className="bg-gray-700 hover:bg-gray-600 text-xs px-2 py-1 rounded text-gray-200"
title="New Series"
>
New
</button>
<button
onClick={() => { setSeriesInput(editor.activeSeries); setShowRenameSeriesModal(true) }}
className="bg-gray-700 hover:bg-gray-600 text-xs px-2 py-1 rounded text-gray-200"
title="Rename Series"
>
Rename
</button>
<button
onClick={() => setShowDeleteSeriesModal(true)}
className="bg-red-800 hover:bg-red-700 text-xs px-2 py-1 rounded text-gray-200"
title="Delete Series"
>
Delete
</button>
<button
onClick={() => setShowKanjiGuide(false)}
className="text-gray-500 hover:text-gray-300 text-xs ml-1"
title="Close"
>
✕
</button>
</div>
</div>
{/* Add New Kanji */}
<div className="flex flex-col gap-2 mb-3">
<div className="flex gap-2">
<input
type="text"
placeholder="Kanji"
value={newKanji}
onChange={(e) => setNewKanji(e.target.value)}
className="w-20 bg-gray-700 border border-gray-600 rounded px-2 py-1 text-xs text-gray-200"
maxLength={10}
/>
<input
type="text"
placeholder="Translation"
value={newTranslation}
onChange={(e) => setNewTranslation(e.target.value)}
className="flex-1 bg-gray-700 border border-gray-600 rounded px-2 py-1 text-xs text-gray-200"
/>
</div>
<div className="flex gap-2">
<input
type="text"
placeholder="Context (optional)"
value={newContext}
onChange={(e) => setNewContext(e.target.value)}
className="flex-1 bg-gray-700 border border-gray-600 rounded px-2 py-1 text-xs text-gray-200"
/>
<button
onClick={handleAddKanjiGuide}
className="bg-gray-700 hover:bg-gray-600 text-xs px-3 py-1 rounded text-gray-200 whitespace-nowrap"
>
Add
</button>
</div>
</div>
{/* Kanji List */}
<div className="space-y-1 max-h-40 overflow-y-auto">
{currentSeriesKanjiGuides.length === 0 ? (
<div className="text-gray-500 text-xs text-center py-4">
No kanji guides defined for this series.
</div>
) : (
currentSeriesKanjiGuides.map((guide, index) => (
<div key={index} className="flex items-center justify-between bg-gray-700 p-2 rounded">
<div className="flex-1 min-w-0">
<span className="font-medium">{guide.kanji}</span>
<span className="mx-2">→</span>
<span className="text-gray-200">{guide.translation}</span>
{guide.context && (
<span className="text-gray-500 text-xs ml-2 truncate">({guide.context})</span>
)}
</div>
<div className="flex items-center gap-1 ml-2 flex-shrink-0">
<button
onClick={() => {
setEditingKanji(guide.kanji)
setKanjiDraft(guide.kanji)
setTranslationDraft(guide.translation)
setContextDraft(guide.context || '')
}}
className="text-gray-400 hover:text-gray-200 text-xs px-1 py-0.5 rounded bg-gray-700"
title="Edit"
>
Edit
</button>
<button
onClick={() => handleRemoveKanjiGuide(guide.kanji)}
className="text-gray-500 hover:text-red-400 text-xs px-1 py-0.5 rounded bg-gray-700"
title="Delete"
>
✕
</button>
</div>
</div>
))
)}
</div>
</div>
</div>
)}
<div className="flex-1 min-h-0 relative">
{showInlineDiff ? (
<div className="absolute inset-0">
<div className="h-full flex flex-col">
<div className="bg-gray-700 border-b border-gray-600 px-3 py-2 flex items-center justify-between">
<span className="text-gray-300">Diff View - Suggested Changes</span>
<div className="flex items-center gap-2">
<button
onClick={() => {
if (activePage) {
updateEditorPageContent(activePage.id, showInlineDiff.modified)
}
setShowInlineDiff(null)
}}
className="px-3 py-1 bg-green-600 hover:bg-green-500 rounded text-xs text-white"
>
Accept Changes
</button>
<button
onClick={() => setShowInlineDiff(null)}
className="px-3 py-1 bg-gray-600 hover:bg-gray-500 rounded text-xs text-white"
>
Reject
</button>
</div>
</div>
<div className="flex-1">
<DiffEditor
original={showInlineDiff.original}
modified={showInlineDiff.modified}
language="markdown"
theme="vs-dark"
options={{
minimap: { enabled: false },
readOnly: true,
scrollBeyondLastLine: false,
automaticLayout: true,
renderSideBySide: true
}}
/>
</div>
</div>
</div>
) : (
<Editor
height="100%"
defaultLanguage="markdown"
theme="vs-dark"
value={activePage?.content || ''}
onChange={(val)=> activePage && updateEditorPageContent(activePage.id, val || '')}
options={{
minimap: { enabled: false },
fontSize: 14,
lineNumbers: 'on',
readOnly: !activePage,
scrollBeyondLastLine: false,
automaticLayout: true,
// Enhanced editor configuration for better UX
tabSize: 2,
insertSpaces: true,
trimAutoWhitespace: false,
wordWrap: 'off',
wrappingIndent: 'none'
}}
className="absolute inset-0"
onMount={(editorInstance, monaco) => {
editorRef.current = editorInstance;
monacoRef.current = monaco;
// Add custom undo/redo commands with better UX
editorInstance.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyZ, () => {
editorInstance.trigger('keyboard', 'undo', null);
});
editorInstance.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyMod.Shift | monaco.KeyCode.KeyZ, () => {
editorInstance.trigger('keyboard', 'redo', null);
});
editorInstance.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyY, () => {
editorInstance.trigger('keyboard', 'redo', null);
});
}}
/>
)}
</div>
</section>
{/* Right resizer */}
<div
onMouseDown={() => { resizing.current.side = 'right' }}
onMouseUp={() => { resizing.current.side = null }}
onMouseMove={(e) => {
if (resizing.current.side === 'right') {
const total = (e.currentTarget.parentElement?.getBoundingClientRect().width || 1200)
setEditor({ rightPanelWidth: Math.max(200, Math.min(520, total - e.clientX)) })
}
}}
className="w-1 cursor-col-resize bg-gray-700/50"
/>
{/* Right AI Chat panel */}
<aside className="bg-gray-800 border-l border-gray-700 flex-shrink-0 overflow-hidden" style={{ width: rightWidth }}>
{/* Chat Tabs */}
<div className="h-10 flex items-stretch border-b border-gray-700">
<div className={`flex items-stretch overflow-x-auto overflow-y-hidden flex-nowrap w-full scrollbar-h-transparent`}>
{editor.chatTabs.map(t => (
<div
key={t.id}
className={`h-10 px-3 border-r border-gray-700 rounded-none flex items-center gap-2 flex-shrink-0 select-none ${tabBg} ${tabHoverBg} ${editor.activeChatTabId===t.id ? 'text-[#a6e22e] border-b-2' : 'text-gray-300'} `}
style={editor.activeChatTabId===t.id ? { borderBottomColor: monoGreen } : undefined}
onClick={()=>setActiveChatTab(t.id)}
onDoubleClick={()=>{ const newName = prompt('Rename chat tab:', t.name); if (newName) renameChatTab(t.id, newName) }}
>
<span className="text-xs truncate max-w-[120px] text-inherit">{t.name}</span>
<button className="text-gray-500 hover:text-gray-300 text-xs" onClick={(e)=>{e.stopPropagation(); closeChatTab(t.id)}}>x</button>
</div>
))}
<button className={`h-10 px-3 border-l border-gray-700 rounded-none flex items-center justify-center flex-shrink-0 ${tabBg} ${tabHoverBg} text-[#a6e22e]`} onClick={()=>addChatTab('New Chat')}>+</button>
</div>
</div>
{/* Chat Content */}
<div className="h-[calc(100%-2.5rem)] flex flex-col p-2 text-xs text-gray-300 space-y-2 pb-4">
{activeChatTab ? (
<>
<div ref={chatListRef} className="flex-1 overflow-auto p-2 space-y-2 pr-1">
{activeChatTab.messages.length === 0 ? (
<div className="text-gray-500 text-xs text-center">Ask for rewrites, tone, or suggestions. Toggle diff to get an applied comparison.</div>
) : (
<>
{activeChatTab.messages.map((m, i) => (
<div key={i} className={`w-full flex ${m.role==='user' ? 'justify-end' : 'justify-start'}`}>
<div className={`${m.role==='user' ? 'bg-green-900/20 border-green-500/30 text-white' : 'bg-gray-800 border-gray-700 text-gray-200'} border rounded-lg px-3 py-2 max-w-[90%] whitespace-pre-wrap`}>
{m.text}
</div>
</div>
))}
{isTyping && (
<div className="w-full flex justify-start">
<div className="bg-gray-800 border-gray-700 border rounded-lg px-3 py-2 max-w-[90%] text-gray-300">
<div className="flex items-center gap-2">
<div className="flex space-x-1">
<div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce"></div>
<div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '0.1s' }}></div>
<div className="w-2 h-2 bg-gray-400 rounded-full animate-bounce" style={{ animationDelay: '0.2s' }}></div>
</div>
<span className="text-xs text-gray-400">AI is thinking{typingDots}</span>
</div>
</div>
</div>
)}
</>
)}
</div>
<div className="pt-2 border-t border-gray-700">
<div className="flex items-center justify-between mb-2">
<label className="inline-flex items-center cursor-pointer gap-2 text-[11px] text-gray-400">
<input
type="checkbox"
className="sr-only peer"
checked={chatAskDiff}
onChange={(e) => setChatAskDiff(e.target.checked)}
/>
<div className="relative w-9 h-5 bg-gray-400 rounded-full peer peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-white after:border-zinc-300 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-[#a6e22e]"></div>
Request diff
</label>
</div>
<div className="flex items-stretch gap-2">
<textarea
rows={1}
value={chatInput}
onChange={(e)=>setChatInput(e.target.value)}
onKeyDown={(e)=>{ if (e.key==='Enter' && !e.shiftKey) { e.preventDefault(); handleChatSend() } }}
className="flex-1 bg-gray-900 border border-gray-700 rounded px-2 py-2 text-xs text-gray-200 resize-none placeholder:text-gray-500"
placeholder="Ask AI..."
disabled={!activeChatTab}
/>
<button
onClick={handleChatSend}
disabled={!activeChatTab || !chatInput.trim()}
className="px-3 py-2 bg-gray-700 hover:bg-gray-600 disabled:opacity-50 disabled:cursor-not-allowed rounded text-xs flex items-center justify-center w-10"
title="Send message"
>
<FontAwesomeIcon icon={faPaperPlane} className="text-xs" />
</button>
</div>
</div>
</>
) : (
<div className="flex-1 flex items-center justify-center">
<div className="text-gray-500 text-xs text-center">
No chat tabs open.<br/>
Click the + button above to create a new chat.
</div>
</div>
)}
</div>
</aside>
</main>
{/* Series Modals */}
{showNewSeriesModal && (
<div className="fixed inset-0 bg-black/50 grid place-items-center z-[60]">
<div className="bg-gray-800 border border-gray-700 rounded p-4 w-80">
<div className="text-white mb-3">Create New Series</div>
<input
className="w-full bg-gray-900 border border-gray-700 rounded px-2 py-1 text-white mb-3"
value={seriesInput}
onChange={(e)=>setSeriesInput(e.target.value)}
placeholder="Series name"
autoFocus
onKeyDown={(e) => { if (e.key === 'Enter') { if (seriesInput.trim()) { createSeries(seriesInput.trim()); setShowNewSeriesModal(false); setShowKanjiGuide(true) } } if (e.key === 'Escape') setShowNewSeriesModal(false) }}
/>
<div className="flex gap-2 justify-end">
<button className="px-3 py-1 bg-gray-700 hover:bg-gray-600 rounded text-white" onClick={()=>{setShowNewSeriesModal(false); setShowKanjiGuide(true)}}>Cancel</button>
<button className="px-3 py-1 bg-green-600 hover:bg-green-500 rounded text-white" onClick={()=>{ if (seriesInput.trim()) { createSeries(seriesInput.trim()); setShowNewSeriesModal(false); setShowKanjiGuide(true) } }}>Create</button>
</div>
</div>
</div>
)}
{showRenameSeriesModal && (
<div className="fixed inset-0 bg-black/50 grid place-items-center z-[60]">
<div className="bg-gray-800 border border-gray-700 rounded p-4 w-80">
<div className="text-white mb-3">Rename Series</div>
<input
className="w-full bg-gray-900 border border-gray-700 rounded px-2 py-1 text-white mb-3"
value={seriesInput}
onChange={(e)=>setSeriesInput(e.target.value)}
placeholder="New series name"
autoFocus
onKeyDown={(e) => { if (e.key === 'Enter') { if (seriesInput.trim() && editor.activeSeries) { renameSeries(editor.activeSeries, seriesInput.trim()); setShowRenameSeriesModal(false); setShowKanjiGuide(true) } } if (e.key === 'Escape') setShowRenameSeriesModal(false) }}
/>
<div className="flex gap-2 justify-end">
<button className="px-3 py-1 bg-gray-700 hover:bg-gray-600 rounded text-white" onClick={()=>{setShowRenameSeriesModal(false); setShowKanjiGuide(true)}}>Cancel</button>
<button className="px-3 py-1 bg-green-600 hover:bg-green-500 rounded text-white" onClick={()=>{ if (seriesInput.trim() && editor.activeSeries) { renameSeries(editor.activeSeries, seriesInput.trim()); setShowRenameSeriesModal(false); setShowKanjiGuide(true) } }}>Rename</button>
</div>
</div>
</div>
)}
{showDeleteSeriesModal && (
<div className="fixed inset-0 bg-black/50 grid place-items-center z-[60]">
<div className="bg-gray-800 border border-gray-700 rounded p-4 w-80">
<div className="text-white mb-3">Delete Series</div>
<div className="text-xs text-gray-300 mb-3">Are you sure you want to delete "{editor.activeSeries}"?</div>
<div className="flex gap-2 justify-end">
<button className="px-3 py-1 bg-gray-700 hover:bg-gray-600 rounded text-white" onClick={()=>{setShowDeleteSeriesModal(false); setShowKanjiGuide(true)}}>Cancel</button>
<button className="px-3 py-1 bg-red-600 hover:bg-red-500 rounded text-white" onClick={()=>{ deleteSeries(editor.activeSeries); setShowDeleteSeriesModal(false); setShowKanjiGuide(true) }}>Delete</button>
</div>
</div>
</div>
)}
{/* Edit Kanji Guide Modal */}
{editingKanji && (
<div className="fixed inset-0 bg-black/50 grid place-items-center z-[60]">
<div className="bg-gray-800 border border-gray-700 rounded p-4 w-80">
<div className="text-white mb-3">Edit Kanji Guide</div>
<div className="space-y-3">
<div>
<label className="block text-xs text-gray-400 mb-1">Kanji</label>
<input
className="w-full bg-gray-900 border border-gray-700 rounded px-2 py-1 text-white"
value={kanjiDraft}
onChange={(e)=>setKanjiDraft(e.target.value)}
placeholder="漢字"
autoFocus
onKeyDown={(e) => {
if (e.key === 'Enter') {
if (kanjiDraft.trim() && translationDraft.trim()) {
updateKanjiGuide(editor.activeSeries, editingKanji, kanjiDraft.trim(), translationDraft.trim(), contextDraft.trim() || undefined)
setEditingKanji(null)
setKanjiDraft('')
setTranslationDraft('')
setContextDraft('')
setShowKanjiGuide(true)
}
}
if (e.key === 'Escape') {
setEditingKanji(null)
setKanjiDraft('')
setTranslationDraft('')
setContextDraft('')
setShowKanjiGuide(true)
}
}}
/>
</div>
<div>
<label className="block text-xs text-gray-400 mb-1">Translation</label>
<input
className="w-full bg-gray-900 border border-gray-700 rounded px-2 py-1 text-white"
value={translationDraft}
onChange={(e)=>setTranslationDraft(e.target.value)}
placeholder="English translation"
/>
</div>
<div>
<label className="block text-xs text-gray-400 mb-1">Context (optional)</label>
<input
className="w-full bg-gray-900 border border-gray-700 rounded px-2 py-1 text-white"
value={contextDraft}
onChange={(e)=>setContextDraft(e.target.value)}
placeholder="e.g., character name, situation"
/>
</div>
</div>
<div className="flex gap-2 justify-end mt-4">
<button
className="px-3 py-1 bg-gray-700 hover:bg-gray-600 rounded text-white"
onClick={() => {
setEditingKanji(null)
setKanjiDraft('')
setTranslationDraft('')
setContextDraft('')
setShowKanjiGuide(true)
}}
>
Cancel
</button>
<button
className="px-3 py-1 bg-green-600 hover:bg-green-500 rounded text-white"
onClick={() => {
if (kanjiDraft.trim() && translationDraft.trim()) {
updateKanjiGuide(editor.activeSeries, editingKanji, kanjiDraft.trim(), translationDraft.trim(), contextDraft.trim() || undefined)
setEditingKanji(null)
setKanjiDraft('')
setTranslationDraft('')
setContextDraft('')
setShowKanjiGuide(true)
}
}}
>
Update
</button>
</div>
</div>
</div>
)}
</>
)
}