-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscenario-manager.js
More file actions
1947 lines (1646 loc) · 75.4 KB
/
scenario-manager.js
File metadata and controls
1947 lines (1646 loc) · 75.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 { BlockTypeManager } from './modules/block-types.js';
import { ProjectManager } from './modules/project-manager.js';
import { ParagraphManager } from './modules/paragraph-manager.js';
import { UIManager } from './modules/ui-manager.js';
import { PreviewManager } from './modules/preview-manager.js';
import { SceneManager } from './modules/scene-manager.js';
import { TextImporter } from './modules/text-importer.js';
import { HistoryManager, MoveBlockOperation, EditBlockOperation, DeleteBlockOperation, AddBlockOperation } from './modules/history-manager.js';
import { ResizeManager } from './modules/resize-manager.js';
import { MetaTagParser } from './modules/meta-tag-parser.js';
import { TextHighlighter } from './modules/text-highlighter.js';
import { MigrationManager } from './modules/migration-manager.js';
import { LocalizationManager } from './modules/localization-manager.js';
class ScenarioManager {
constructor() {
this.blockTypeManager = new BlockTypeManager();
this.projectManager = new ProjectManager();
this.sceneManager = new SceneManager();
this.paragraphManager = new ParagraphManager(this.blockTypeManager);
this.textImporter = new TextImporter(this.paragraphManager, this.blockTypeManager);
this.uiManager = new UIManager(this.blockTypeManager, this.paragraphManager, this.projectManager);
this.previewManager = new PreviewManager(this.paragraphManager, this.uiManager, this.blockTypeManager);
this.historyManager = new HistoryManager();
this.resizeManager = new ResizeManager();
this.metaTagParser = new MetaTagParser();
this.textHighlighter = new TextHighlighter(this.metaTagParser);
this.migrationManager = new MigrationManager(this.paragraphManager, this.uiManager);
this.localizationManager = new LocalizationManager();
// 編集開始時の状態を保存するための変数
this.editStartState = null;
this.editTimer = null;
// グローバルハンドラーを登録
window.deleteParagraphHandler = (id) => this.deleteParagraph(id);
window.reorderParagraphHandler = (draggedId, targetId, insertAfter) => this.reorderParagraphs(draggedId, targetId, insertAfter);
this.initializeUI();
this.bindEvents();
this.updateTitle();
// ブラウザのページ離脱時の確認
this.setupBeforeUnloadHandler();
}
async initializeUI() {
this.uiManager.generateTypeUI();
// 初期状態では編集機能を無効化
this.setEditingEnabled(false);
// 最近のプロジェクト一覧を表示
await this.showRecentProjects();
// メタコマンド定義を読み込み
await this.loadMetaCommands();
}
async loadMetaCommands(metaTagFilePath = 'meta-tag-template.yaml') {
try {
const success = await this.metaTagParser.loadMetaCommandsFromYaml(metaTagFilePath);
if (success) {
// グローバルフラグを設定してハイライト機能が使用可能であることを示す
window.metaCommandsLoaded = true;
// すべてのテキストエリアにハイライトを適用
this.applyHighlightToAllTextAreas();
} else {
window.metaCommandsLoaded = false;
}
} catch (error) {
console.error('メタコマンド定義読み込みエラー:', error);
window.metaCommandsLoaded = false;
}
}
applyHighlightToAllTextAreas() {
// 現在表示されているすべてのテキストエリアにハイライトを適用
const textAreas = document.querySelectorAll('textarea');
textAreas.forEach(textarea => {
if (textarea.id === 'editor-content') {
this.textHighlighter.highlightTextArea(textarea);
}
});
}
setupTextHighlightForNewParagraphs() {
// 新しく追加されたテキストエリアにハイライト機能を適用
const editorContent = document.getElementById('editor-content');
if (editorContent) {
this.textHighlighter.highlightTextArea(editorContent);
}
}
// マイグレーションモーダルを表示
async showMigrationModal() {
if (!this.projectManager.getProjectPath()) {
await window.electronAPI.showMessage({ message: 'プロジェクトが開かれていません' });
return;
}
// マイグレーションスクリプト一覧を読み込み
const migrations = await this.migrationManager.loadAvailableMigrations(this.projectManager.getProjectPath());
if (migrations.length === 0) {
await window.electronAPI.showMessage({ message: 'migrationディレクトリにマイグレーションスクリプトが見つかりません' });
return;
}
this.migrationManager.showMigrationModal();
}
// マイグレーション選択変更時
onMigrationSelectChange() {
const select = document.getElementById('migration-select');
const executeButton = document.getElementById('execute-migration');
const infoDiv = document.getElementById('migration-info');
const descriptionP = document.getElementById('migration-description');
if (select.value) {
executeButton.disabled = false;
// 選択されたマイグレーションの詳細を表示
const selectedMigration = this.migrationManager.getAvailableMigrations()
.find(m => m.fileName === select.value);
if (selectedMigration) {
descriptionP.textContent = selectedMigration.description || '説明なし';
infoDiv.style.display = 'block';
}
} else {
executeButton.disabled = true;
infoDiv.style.display = 'none';
}
}
// マイグレーション実行
async executeMigration() {
const select = document.getElementById('migration-select');
const migrationFileName = select.value;
if (!migrationFileName) {
await window.electronAPI.showMessage({ message: 'マイグレーションスクリプトを選択してください' });
return;
}
// 確認ダイアログ
const confirmed = await window.electronAPI.showConfirm({
message: `マイグレーション "${migrationFileName}" を実行しますか?`,
detail: '現在のブロックデータが置き換えられます。事前に保存することを推奨します。'
});
if (!confirmed) {
return;
}
try {
const result = await this.migrationManager.executeMigration(
this.projectManager.getProjectPath(),
migrationFileName
);
if (result.success) {
this.markAsChanged();
this.migrationManager.closeMigrationModal();
await window.electronAPI.showMessage({ message: result.message });
} else {
await window.electronAPI.showMessage({ type: 'error', message: 'マイグレーション実行エラー', detail: result.error });
}
} catch (error) {
console.error('マイグレーション実行エラー:', error);
await window.electronAPI.showMessage({ type: 'error', message: 'マイグレーション実行中にエラーが発生しました', detail: error.message });
}
}
bindEvents() {
document.getElementById('add-paragraph').addEventListener('click', () => this.addParagraph());
document.getElementById('delete-paragraph').addEventListener('click', () => this.deleteParagraph());
document.getElementById('new-project').addEventListener('click', () => this.newProject());
document.getElementById('save-project').addEventListener('click', () => this.saveProject());
document.getElementById('close-project').addEventListener('click', () => this.closeProject());
document.getElementById('open-project').addEventListener('click', () => this.openProject());
document.getElementById('export-csv').addEventListener('click', () => this.exportCSV());
document.getElementById('export-text').addEventListener('click', () => this.exportText());
document.getElementById('preview-novel').addEventListener('click', () => this.previewManager.showPreview());
document.getElementById('reload-schema').addEventListener('click', () => this.reloadSchema());
document.getElementById('migration').addEventListener('click', () => this.showMigrationModal());
document.getElementById('close-migration').addEventListener('click', () => this.migrationManager.closeMigrationModal());
document.getElementById('cancel-migration').addEventListener('click', () => this.migrationManager.closeMigrationModal());
document.getElementById('execute-migration').addEventListener('click', () => this.executeMigration());
document.getElementById('migration-select').addEventListener('change', () => this.onMigrationSelectChange());
document.getElementById('add-scene').addEventListener('click', () => this.addScene());
document.getElementById('import-text-file').addEventListener('click', () => this.importTextAsScene());
document.getElementById('import-text').addEventListener('click', () => this.showTextInputModal());
document.getElementById('new-project-from-recent').addEventListener('click', () => this.newProject());
document.getElementById('open-project-from-recent').addEventListener('click', () => this.openProject());
document.getElementById('update-localization').addEventListener('click', () => this.updateLocalization());
// キーボードショートカットのバインド
this.bindKeyboardShortcuts();
const editorContent = this.uiManager.getEditorContent();
const tagsInput = this.uiManager.getTagsInput();
const typeSelect = this.uiManager.getTypeSelect();
const sceneMetadataInput = document.getElementById('scene-metadata');
editorContent.addEventListener('input', () => this.updateCurrentParagraph());
editorContent.addEventListener('focus', () => this.startEdit());
editorContent.addEventListener('blur', () => this.finishEdit());
tagsInput.addEventListener('input', () => this.updateCurrentParagraph());
tagsInput.addEventListener('focus', () => this.startEdit());
tagsInput.addEventListener('blur', () => this.finishEdit());
typeSelect.addEventListener('change', () => this.onTypeChange());
// シーンメタデータの変更を監視
sceneMetadataInput.addEventListener('input', () => this.updateSceneMetadata());
sceneMetadataInput.addEventListener('blur', () => this.saveSceneMetadata());
this.bindSchemaEvents();
document.getElementById('close-preview').addEventListener('click', () => this.previewManager.closePreview());
document.getElementById('copy-preview').addEventListener('click', () => this.copyPreviewContent());
const previewFormat = this.uiManager.getPreviewFormat();
previewFormat.addEventListener('change', () => this.previewManager.updatePreview());
const previewModal = this.uiManager.getPreviewModal();
previewModal.addEventListener('click', (e) => {
if (e.target === previewModal) {
this.previewManager.closePreview();
}
});
// プレビューコンテンツでのコピーイベントをインターセプト
const previewContent = document.getElementById('preview-content');
previewContent.addEventListener('copy', (e) => {
e.preventDefault();
const format = this.uiManager.getPreviewFormat().value;
const textContent = this.previewManager.generateTextContent(format);
e.clipboardData.setData('text/plain', textContent);
});
}
bindSchemaEvents() {
// 動的に生成されたパラメータ要素にイベントリスナーを追加
const typeParams = this.uiManager.getTypeParams();
Object.values(typeParams).forEach(params => {
Object.values(params).forEach(element => {
if (element) {
element.addEventListener('input', () => this.updateCurrentParagraph());
element.addEventListener('change', () => this.updateCurrentParagraph());
element.addEventListener('focus', () => this.startEdit());
element.addEventListener('blur', () => this.finishEdit());
}
});
});
}
addParagraph() {
const newParagraph = this.paragraphManager.addParagraph();
this.markAsChanged();
this.uiManager.renderParagraphList();
const selectedParagraph = this.paragraphManager.selectParagraph(newParagraph.id);
if (selectedParagraph) {
this.uiManager.showEditor(selectedParagraph);
this.uiManager.updateParagraphSelection();
}
// Undo/Redo操作を履歴に追加(既に追加済みなのでskipExecute=true)
const operation = new AddBlockOperation(this.paragraphManager, this.uiManager, newParagraph.id);
this.historyManager.executeOperation(operation, true);
}
deleteParagraph(paragraphId = null) {
let idToDelete = paragraphId || this.paragraphManager.getSelectedParagraphId();
if (!idToDelete) return;
// 文字列として渡された場合は整数に変換
if (typeof idToDelete === 'string') {
idToDelete = parseInt(idToDelete);
}
// 削除前にUndo/Redo操作を作成(実行はDeleteBlockOperationのコンストラクタで状態を保存)
const operation = new DeleteBlockOperation(this.paragraphManager, this.uiManager, idToDelete);
// 実際の削除を実行
if (this.paragraphManager.deleteParagraph(idToDelete)) {
this.markAsChanged();
this.uiManager.renderParagraphList();
// 削除したブロックが選択中だった場合のみプレースホルダーを表示
if (idToDelete === this.paragraphManager.getSelectedParagraphId()) {
this.uiManager.showPlaceholder();
}
// 履歴に追加(既に削除済みなのでskipExecute=true)
this.historyManager.executeOperation(operation, true);
}
}
async showRecentProjects() {
try {
const recentProjects = await window.electronAPI.getRecentProjects();
const recentProjectsList = document.getElementById('recent-projects-list');
const recentProjectsPanel = document.getElementById('recent-projects-panel');
recentProjectsList.innerHTML = '';
if (recentProjects.length === 0) {
recentProjectsList.innerHTML = '<div class="recent-projects-empty">最近開いたプロジェクトはありません</div>';
} else {
recentProjects.forEach(project => {
const item = document.createElement('div');
item.className = 'recent-project-item';
const info = document.createElement('div');
info.className = 'recent-project-info';
const name = document.createElement('div');
name.className = 'recent-project-name';
name.textContent = project.name;
const path = document.createElement('div');
path.className = 'recent-project-path';
path.textContent = project.path;
const date = document.createElement('div');
date.className = 'recent-project-date';
const lastOpened = new Date(project.lastOpened);
date.textContent = `最終更新: ${lastOpened.toLocaleDateString()} ${lastOpened.toLocaleTimeString()}`;
info.appendChild(name);
info.appendChild(path);
info.appendChild(date);
item.appendChild(info);
item.addEventListener('click', () => this.openRecentProject(project.path));
recentProjectsList.appendChild(item);
});
}
recentProjectsPanel.style.display = 'block';
} catch (error) {
console.error('Failed to load recent projects:', error);
}
}
hideRecentProjects() {
const recentProjectsPanel = document.getElementById('recent-projects-panel');
recentProjectsPanel.style.display = 'none';
}
async loadProject(projectData, projectPath) {
try {
// 編集中の場合は履歴を確定
this.finishEdit();
// 履歴をクリア
this.historyManager.clear();
this.projectManager.setProjectPath(projectPath);
this.sceneManager.setProjectPath(projectPath);
// スキーマファイルをロード
try {
// プロジェクトマネージャーのスキーマファイル名を設定
this.projectManager.setCurrentSchemaFile(projectData.schemaFile);
await this.blockTypeManager.loadSchemaFile(projectPath, projectData.schemaFile);
} catch (error) {
console.error('スキーマファイル読み込みエラー:', error);
await window.electronAPI.showMessage({ type: 'warning', message: 'スキーマファイルの読み込みに失敗しました', detail: `${error.message}\n\nプロジェクトは開かれましたが、スキーマファイルが正しく読み込まれませんでした。` });
}
// メタタグファイルをロード
try {
// プロジェクトマネージャーのメタタグファイル名を設定
this.projectManager.setCurrentMetaTagFile(projectData.metaTagFile || 'meta-tag-template.yaml');
const metaTagFile = this.projectManager.getCurrentMetaTagFile();
// プロジェクト固有のメタタグファイルがある場合はそれを使用
if (metaTagFile !== 'meta-tag-template.yaml') {
const projectDir = path.dirname(projectPath);
const metaTagPath = `${projectDir}/${metaTagFile}`;
const success = await this.metaTagParser.loadMetaCommandsFromYaml(metaTagPath);
if (success) {
window.metaCommandsLoaded = true;
this.applyHighlightToAllTextAreas();
} else {
await this.loadMetaCommands();
}
} else {
// デフォルトのメタタグファイルを使用
await this.loadMetaCommands();
}
} catch (error) {
console.error('メタタグファイル読み込みエラー:', error);
// メタタグの読み込みに失敗してもプロジェクトは開くことができる
await this.loadMetaCommands();
}
// scenesディレクトリから直接シーン一覧を取得
try {
const scanResult = await window.electronAPI.scanScenesDirectory(projectPath);
if (scanResult.success) {
this.sceneManager.loadScenesFromDirectory(scanResult.scenes);
} else {
console.error('シーンディレクトリスキャンエラー:', scanResult.error);
// エラーが発生しても空のシーンリストで続行
this.sceneManager.loadScenesFromDirectory([]);
}
} catch (error) {
console.error('シーンリスト読み込みエラー:', error);
await window.electronAPI.showMessage({ type: 'error', message: 'シーンリストの読み込みに失敗しました', detail: error.message });
return;
}
// レガシーデータの処理(v1.0.0からのマイグレーション)
try {
if (projectData.paragraphs && projectData.paragraphs.length > 0) {
const defaultScene = this.sceneManager.getCurrentScene();
if (defaultScene) {
defaultScene.paragraphs = projectData.paragraphs;
await window.electronAPI.saveScene(projectPath, defaultScene._fileName, {
_fileName: defaultScene._fileName,
paragraphs: defaultScene.paragraphs
});
}
}
} catch (error) {
console.error('レガシーデータ処理エラー:', error);
console.warn('レガシーデータの処理に失敗しました:', error.message);
}
// 現在のシーンを選択
try {
const currentSceneFileName = projectData.currentSceneFileName || (this.sceneManager.getScenes().length > 0 ? this.sceneManager.getScenes()[0].fileName : null);
if (currentSceneFileName) {
await this.selectScene(currentSceneFileName);
} else {
this.paragraphManager.setParagraphs([]);
this.uiManager.showPlaceholder();
}
} catch (error) {
console.warn('シーン選択エラー:', error);
this.paragraphManager.setParagraphs([]);
this.uiManager.showPlaceholder();
}
// 編集機能を有効化
this.setEditingEnabled(true);
// UIを再生成
try {
this.uiManager.generateTypeUI();
this.bindSchemaEvents();
this.uiManager.renderSceneList(this.sceneManager.getScenes(), this.sceneManager.getCurrentSceneFileName(), (fileName) => this.selectScene(fileName), (fileName, newName) => this.renameScene(fileName, newName), (fileName, sceneName) => this.deleteScene(fileName, sceneName));
} catch (error) {
console.error('UI再生成エラー:', error);
await window.electronAPI.showMessage({ type: 'error', message: 'UIの更新に失敗しました', detail: error.message });
}
this.hideRecentProjects();
this.updateTitle();
} catch (error) {
console.error('プロジェクト読み込みエラー:', error);
await window.electronAPI.showMessage({ type: 'error', message: 'プロジェクトの読み込みに失敗しました', detail: error.message });
}
}
async openRecentProject(projectPath) {
try {
const result = await window.electronAPI.openRecentProject(projectPath);
if (result.success) {
await this.loadProject(result.data, result.path);
} else {
await window.electronAPI.showMessage({ type: 'error', message: 'プロジェクトを開けませんでした', detail: result.error || '不明なエラー' });
}
} catch (error) {
console.error('Open recent project error:', error);
await window.electronAPI.showMessage({ type: 'error', message: 'プロジェクトを開けませんでした', detail: error.message });
}
}
async closeProject() {
// プロジェクトが開かれていない場合は何もしない
if (!this.projectManager.getProjectPath()) {
return;
}
// 変更がある場合は確認ダイアログを表示
if (this.projectManager.hasChanges()) {
const response = await window.electronAPI.showMessage({
type: 'question',
title: 'プロジェクトを閉じる',
message: '保存されていない変更があります。',
detail: 'プロジェクトを閉じる前に変更を保存しますか?',
buttons: ['保存する', '破棄する', 'キャンセル']
});
if (response === 0) {
// 「保存する」を選択
await this.saveProject();
} else if (response === 2) {
// 「キャンセル」を選択
return;
}
// response === 1 の場合は「破棄する」なので何もしない
}
// 編集中の場合は履歴を確定
this.finishEdit();
// 履歴をクリア
this.historyManager.clear();
// プロジェクト状態をクリア
this.projectManager.setProjectPath(null);
this.projectManager.markAsSaved();
this.sceneManager.clearScenes();
this.sceneManager.setProjectPath(null);
this.paragraphManager.setParagraphs([]);
// 編集機能を無効化
this.setEditingEnabled(false);
this.setSceneEditingEnabled(false);
// UIをリセット
this.uiManager.renderSceneList([], null, () => {}, () => {}, () => {});
this.uiManager.updateCurrentSceneName('');
this.uiManager.renderParagraphList();
this.uiManager.showPlaceholder();
// ホーム画面(最近のプロジェクト一覧)を表示
await this.showRecentProjects();
this.updateTitle();
}
async newProject() {
const hasChanges = this.projectManager.hasChanges();
if (hasChanges || this.paragraphManager.getParagraphs().length > 0) {
const confirmed = await window.electronAPI.showConfirm({ message: '現在のプロジェクトを破棄して新規作成しますか?' });
if (!confirmed) return;
}
// 編集中の場合は履歴を確定
this.finishEdit();
// 履歴をクリア
this.historyManager.clear();
// まずプロジェクトファイルを保存
const saveResult = await window.electronAPI.saveProject({
version: '2.0.0',
createdAt: new Date().toISOString(),
schemaFile: '', // 初期値は空文字列、保存後に更新
currentSceneFileName: null
}, null);
if (!saveResult.success) return;
// プロジェクトマネージャーを更新
this.projectManager.setProjectPath(saveResult.path);
this.projectManager.markAsSaved();
// スキーマファイルを読み込み
if (saveResult.schemaFileName) {
// プロジェクトマネージャーのスキーマファイル名を更新
this.projectManager.setCurrentSchemaFile(saveResult.schemaFileName);
// プロジェクトファイルのschemaFileを正しい値で更新(再保存)
await this.projectManager.saveProject([], null);
await this.blockTypeManager.loadSchemaFile(saveResult.path, saveResult.schemaFileName);
this.uiManager.generateTypeUI();
this.bindSchemaEvents();
}
// キャラクターファイルを読み込み
if (saveResult.charactersFileName) {
await this.characterManager.loadCharactersFile(saveResult.path, saveResult.charactersFileName);
this.uiManager.generateTypeUI();
this.bindSchemaEvents();
}
// 新規プロジェクトをセットアップ
this.sceneManager.clearScenes();
this.sceneManager.setProjectPath(saveResult.path);
this.paragraphManager.setParagraphs([]);
// 編集機能を有効化(シーン編集は無効化)
this.setEditingEnabled(true);
this.setSceneEditingEnabled(false);
this.hideRecentProjects();
this.uiManager.renderSceneList([], null, (fileName) => this.selectScene(fileName), (fileName, newName) => this.renameScene(fileName, newName), (fileName, sceneName) => this.deleteScene(fileName, sceneName));
this.uiManager.updateCurrentSceneName('');
this.uiManager.renderParagraphList();
this.uiManager.showPlaceholder();
this.updateTitle();
}
async saveProject() {
// 現在のシーンを保存
await this.saveCurrentScene();
// プロジェクトファイルを保存(シーン一覧は含めない)
const currentSceneFileName = this.sceneManager.getCurrentSceneFileName();
const result = await this.projectManager.saveProject([], currentSceneFileName);
if (result.success) {
this.sceneManager.setProjectPath(result.path);
// すべてのシーンを保存
const scenes = this.sceneManager.getScenes();
for (const scene of scenes) {
// 現在のシーンは最新の段落データを使用
if (scene.fileName === currentSceneFileName) {
const currentParagraphs = this.paragraphManager.getParagraphs();
await window.electronAPI.saveScene(result.path, scene.fileName, {
_fileName: scene._fileName,
metadata: scene.metadata || '',
paragraphs: currentParagraphs
});
this.sceneManager.updateSceneParagraphs(scene.fileName, currentParagraphs);
} else {
// その他のシーンは既存のファイルからデータを読み込む
let sceneParagraphs = [];
// シーンファイルが存在する場合は、必ずファイルから読み込む
if (scene.exists) {
try {
const loadResult = await window.electronAPI.loadScene(result.path, scene._fileName);
if (loadResult.success && loadResult.data.paragraphs) {
sceneParagraphs = loadResult.data.paragraphs;
} else {
console.warn(`シーン ${scene.name} のデータが空または無効です`);
// ファイルが存在するが読み込めない場合は、現在のメモリデータを使用
sceneParagraphs = scene.paragraphs || [];
}
} catch (error) {
console.warn(`シーン ${scene.name} の読み込みに失敗しました:`, error);
// エラーが発生した場合は、現在のメモリデータを使用
sceneParagraphs = scene.paragraphs || [];
}
} else {
// ファイルが存在しない場合は、メモリ上のデータを使用
sceneParagraphs = scene.paragraphs || [];
}
await window.electronAPI.saveScene(result.path, scene.fileName, {
_fileName: scene._fileName,
metadata: scene.metadata || '',
paragraphs: sceneParagraphs
});
}
this.sceneManager.markSceneAsExisting(scene.fileName, true);
}
this.updateTitle();
}
}
async openProject() {
try {
const result = await this.projectManager.openProject();
if (result.success) {
await this.loadProject(result.data, result.path);
} else {
// プロジェクトファイルの選択がキャンセルされた場合は何もしない
if (result.cancelled) {
return;
}
// その他のエラーの場合は詳細なエラーメッセージを表示
await window.electronAPI.showMessage({ type: 'error', message: 'プロジェクトを開けませんでした', detail: result.error || '不明なエラーが発生しました' });
}
} catch (error) {
console.error('プロジェクトオープンエラー:', error);
await window.electronAPI.showMessage({ type: 'error', message: 'プロジェクトを開く際にエラーが発生しました', detail: `${error.message}\n\nファイルが破損している可能性があります。` });
}
}
reorderParagraphs(draggedId, targetId, insertAfter = false) {
// 文字列として渡された場合は整数に変換
if (typeof draggedId === 'string') {
draggedId = parseInt(draggedId);
}
if (typeof targetId === 'string') {
targetId = parseInt(targetId);
}
// 移動前にUndo/Redo操作を作成
const operation = new MoveBlockOperation(this.paragraphManager, this.uiManager, draggedId, targetId, insertAfter);
// 実際の移動を実行
if (this.paragraphManager.reorderParagraphs(draggedId, targetId, insertAfter)) {
this.markAsChanged();
this.uiManager.renderParagraphList();
this.uiManager.updateParagraphSelection();
// 履歴に追加(既に移動済みなのでskipExecute=true)
this.historyManager.executeOperation(operation, true);
}
}
async exportCSV() {
const projectPath = this.projectManager.getProjectPath();
if (!projectPath) {
await window.electronAPI.showMessage({ message: 'プロジェクトが保存されていません。先にプロジェクトを保存してください。' });
return;
}
// 現在のシーンを保存してから全シーンをエクスポート
await this.saveCurrentScene();
const scenes = this.sceneManager.getScenes();
if (scenes.length === 0) {
await window.electronAPI.showMessage({ message: 'エクスポートするシーンがありません。' });
return;
}
// ブロックタイプ定義、構造体定義、列挙型定義を取得
const blockTypes = this.blockTypeManager.getBlockTypes();
const structs = this.blockTypeManager.getStructs();
const enums = this.blockTypeManager.getEnums();
await this.projectManager.exportAllScenesAsCSV(projectPath, scenes, blockTypes, structs, enums);
}
async exportText() {
const projectPath = this.projectManager.getProjectPath();
if (!projectPath) {
await window.electronAPI.showMessage({ message: 'プロジェクトが保存されていません。先にプロジェクトを保存してください。' });
return;
}
// 現在のシーンを保存してから全シーンをエクスポート
await this.saveCurrentScene();
const scenes = this.sceneManager.getScenes();
if (scenes.length === 0) {
await window.electronAPI.showMessage({ message: 'エクスポートするシーンがありません。' });
return;
}
// フォーマット選択のダイアログを表示
const format = await this.showFormatSelectionDialog();
if (!format) return; // キャンセルされた場合
// 全シーンをテキストエクスポート
await this.exportAllScenesAsText(projectPath, scenes, format);
}
showFormatSelectionDialog() {
return new Promise((resolve) => {
// モーダルダイアログを作成
const modal = document.createElement('div');
modal.className = 'modal show';
modal.style.display = 'flex';
const modalContent = document.createElement('div');
modalContent.style.cssText = `
background: #2d2d30;
border-radius: 8px;
padding: 2rem;
max-width: 400px;
text-align: center;
border: 1px solid #3e3e42;
`;
const title = document.createElement('h2');
title.textContent = 'エクスポート形式を選択';
title.style.cssText = 'color: #ffffff; margin-bottom: 1.5rem; font-size: 1.2rem;';
const buttonContainer = document.createElement('div');
buttonContainer.style.cssText = 'display: flex; gap: 1rem; justify-content: center; margin-bottom: 1rem;';
const novelButton = document.createElement('button');
novelButton.textContent = '小説形式';
novelButton.className = 'add-button';
novelButton.style.cssText = 'flex: 1; padding: 1rem; font-size: 1rem;';
const scriptButton = document.createElement('button');
scriptButton.textContent = '台本形式';
scriptButton.className = 'add-button';
scriptButton.style.cssText = 'flex: 1; padding: 1rem; font-size: 1rem;';
const cancelButton = document.createElement('button');
cancelButton.textContent = 'キャンセル';
cancelButton.style.cssText = `
background: #666666;
color: white;
border: none;
border-radius: 4px;
padding: 0.5rem 1rem;
cursor: pointer;
margin-top: 0.5rem;
`;
buttonContainer.appendChild(novelButton);
buttonContainer.appendChild(scriptButton);
modalContent.appendChild(title);
modalContent.appendChild(buttonContainer);
modalContent.appendChild(cancelButton);
modal.appendChild(modalContent);
document.body.appendChild(modal);
const cleanup = () => {
document.body.removeChild(modal);
};
novelButton.addEventListener('click', () => {
cleanup();
resolve('novel');
});
scriptButton.addEventListener('click', () => {
cleanup();
resolve('script');
});
cancelButton.addEventListener('click', () => {
cleanup();
resolve(null);
});
modal.addEventListener('click', (e) => {
if (e.target === modal) {
cleanup();
resolve(null);
}
});
});
}
async exportAllScenesAsText(projectPath, scenes, format) {
try {
// 各シーンのテキストを生成
const sceneTexts = [];
for (const scene of scenes) {
if (!scene.exists) {
console.warn(`シーンファイルが存在しません: ${scene._fileName}`);
continue;
}
try {
// シーンデータを読み込み
const result = await window.electronAPI.loadScene(projectPath, scene._fileName);
if (!result.success || !result.data.paragraphs) {
console.warn(`シーン \"${scene.name}\" のデータが読み込めませんでした`);
continue;
}
// テキストコンテンツを生成
const textContent = this.generateSceneTextContent(result.data.paragraphs, format);
sceneTexts.push({
name: scene.name,
fileName: scene._fileName,
content: textContent
});
} catch (error) {
console.error(`シーン \"${scene.name}\" の処理中にエラー:`, error);
}
}
if (sceneTexts.length === 0) {
await window.electronAPI.showMessage({ message: 'エクスポートできるシーンがありませんでした。' });
return;
}
// メインプロセスに全シーンのテキストエクスポートを依頼
const result = await window.electronAPI.exportAllScenesAsText(projectPath, sceneTexts, format);
if (result.success) {
await window.electronAPI.showMessage({ message: '全シーンのテキストエクスポートが完了しました。', detail: `出力先: ${result.outputDir}\n作成されたファイル数: ${result.fileCount}` });
} else {
const errorMessage = result.error || '不明なエラー';
await window.electronAPI.showMessage({ type: 'error', message: 'テキストエクスポートに失敗しました', detail: errorMessage });
}
} catch (error) {
console.error('全シーンテキストエクスポートエラー:', error);
await window.electronAPI.showMessage({ type: 'error', message: 'テキストエクスポートに失敗しました', detail: error.message });
}
}
generateSceneTextContent(paragraphs, format) {
if (!paragraphs || paragraphs.length === 0) {
return '';
}
let textContent = '';
if (format === 'novel') {
paragraphs.forEach(paragraph => {
if (!paragraph.text || !paragraph.text.trim()) return;
// セリフタイプのブロックは話者の有無に関わらず鍵カッコを表示
if (paragraph.type === 'dialogue') {
// 末尾の改行や空行を除去
const trimmedText = paragraph.text.replace(/[\n\r\s]*$/, '');
textContent += `「${trimmedText}」\n\n`;
} else if (paragraph.type === 'monologue') {
// モノローグは()で囲む
const trimmedText = paragraph.text.replace(/[\n\r\s]*$/, '');
textContent += `(${trimmedText})\n\n`;
} else {
// 地の文など
// 末尾の改行や空行を除去
const trimmedText = paragraph.text.replace(/[\n\r\s]*$/, '');
textContent += `${trimmedText}\n\n`;
}
});
} else if (format === 'script') {
paragraphs.forEach(paragraph => {
if (!paragraph.text || !paragraph.text.trim()) return;
// 台本形式では「セリフ」と「モノローグ」のみを表示
if (paragraph.type !== 'dialogue' && paragraph.type !== 'monologue') {
return;
}
// セリフタイプの場合は話者名を表示(設定されている場合のみ)
const characterName = paragraph.speaker || null;
if (paragraph.type === 'dialogue' && characterName) {
textContent += `${characterName}:\n`;
} else if (paragraph.type === 'monologue' && characterName) {
textContent += `${characterName}(心の声):\n`;
}
// 末尾の改行や空行を除去
const trimmedText = paragraph.text.replace(/[\n\r\s]*$/, '');
// セリフの場合は台本形式では鍵カッコなし、地の文の場合はそのまま
if (paragraph.type === 'dialogue') {
textContent += `${trimmedText}\n\n`;
} else if (paragraph.type === 'monologue') {
textContent += `${trimmedText}\n\n`;
}
});
}
return textContent.trim();
}
onTypeChange() {
const typeSelect = this.uiManager.getTypeSelect();
const editorContent = this.uiManager.getEditorContent();
const newType = typeSelect.value;
const selectedParagraph = this.paragraphManager.getSelectedParagraph();
if (!selectedParagraph) return;
// 変更前の状態を保存
const oldData = JSON.parse(JSON.stringify(selectedParagraph));
// UIを更新
this.uiManager.showTypeParams(newType);
// ブロックタイプ定義に基づいてテキスト入力を制御
const blockType = this.blockTypeManager.getBlockType(newType);
if (blockType && !blockType.requires_text) {
editorContent.style.display = 'none';
editorContent.value = '';
} else {
editorContent.style.display = 'block';
editorContent.disabled = false;
editorContent.placeholder = 'ここにテキストを入力...';
}
const oldType = selectedParagraph.type;
selectedParagraph.type = newType;
selectedParagraph.updatedAt = new Date().toISOString();
// テキストが不要なタイプに変更した場合はテキストをクリア
if (blockType && !blockType.requires_text) {
selectedParagraph.text = '';
}
this.uiManager.clearTypeParams(oldType);
this.paragraphManager.setDefaultParams(selectedParagraph, newType);
this.uiManager.loadTypeParams(selectedParagraph);
// 変更後の状態を保存してundo/redo操作を作成
const newData = JSON.parse(JSON.stringify(selectedParagraph));
const operation = new EditBlockOperation(
this.paragraphManager,
this.uiManager,
selectedParagraph.id,
oldData,
newData
);
// 既に変更が適用されているので、executeをスキップ
this.historyManager.executeOperation(operation, true);
this.markAsChanged();
this.uiManager.updateParagraphListItem(selectedParagraph);