This repository was archived by the owner on Nov 7, 2026. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathContentView.swift
More file actions
2270 lines (2108 loc) · 93.2 KB
/
Copy pathContentView.swift
File metadata and controls
2270 lines (2108 loc) · 93.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
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 SwiftUI
import UniformTypeIdentifiers
import VisuStructCore
#if canImport(UIKit)
import QuickLook
import UIKit
#endif
#if canImport(WebKit)
import WebKit
#endif
#if canImport(AppKit)
import AppKit
#endif
// MARK: - ContentView
@MainActor
struct ContentView: View {
@Environment(\.displayScale) private var displayScale
@Environment(\.horizontalSizeClass) private var horizontalSizeClass
@Environment(\.appLanguage) private var lang
@EnvironmentObject private var incomingDocuments: IncomingDocumentOpener
private var isPhone: Bool {
#if canImport(UIKit)
return UIDevice.current.userInterfaceIdiom == .phone
#else
return false
#endif
}
@FocusState private var focusedField: DiagramEditorFocusTarget?
@State private var tabsModel: DiagramSheetTabsModel
@State private var documentServices: DiagramEditorDocumentServices
@State private var showImporter = false
@State private var showExporter = false
@State private var showInfo = false
@State private var showCodeGeneratorPaywall = false
@State private var showCodeGeneratorPlaceholder = false
@State private var isSimulationMode = false
@State private var simulationEngine: VisuStructSimulationEngine
@State private var simulationPlayTask: Task<Void, Never>? = nil
@State private var isSimulationPlaying = false
@State private var simulationWasPlayingBeforeInput = false
@State private var simulationInputText = ""
@ObservedObject private var recentFilesStore: RecentFilesStore
/// Erhöhen bei jedem Tipp auf „Code erzeugen“, damit die Anzeige neu aufgebaut wird (auch wenn der Dialog schon offen ist).
@State private var codeGeneratorRegenerationToken: Int = 0
/// Wenn `CodeGeneratorPurchaseGate.requiresPurchase`: nach erfolgreichem Kauf auf `true` (StoreKit / `UserDefaults`).
@AppStorage("visustruct.codegen.unlocked") private var codeGeneratorUnlocked = false
/// Freigabe für die Code-Generator-UI: ohne Kaufzwang immer offen; mit Kaufzwang nur nach Freischaltung.
private var codeGeneratorAccessGranted: Bool {
!CodeGeneratorPurchaseGate.requiresPurchase || codeGeneratorUnlocked
}
// iPhone UX: Einfügemarke + Inspector einklappen beim Einfügen.
@State private var insertTarget: DiagramInsertTarget? = nil
/// iPhone: Inspector startet eingeklappt, damit das Diagramm Platz hat.
@State private var hideInspectorOnPhone: Bool = true
// iPhone UX: Palette automatisch einklappen beim Text-Editieren.
/// iPhone: Palette als Sheet über dem Editor (statt fest über der Navigationsleiste).
@State private var showPaletteOnPhone: Bool = false
/// iPhone: Diagrammtitel wird in einem kleinen Dialog bearbeitet statt in einem eigenen Feld über dem Diagramm.
@State private var showPhoneTitleEditor: Bool = false
@State private var phoneTitleDraft: String = ""
// In-App Zwischenablage für Diagramm-Elemente (Copy/Cut/Paste).
@State private var elementClipboard: VisuStructElement? = nil
#if canImport(UIKit)
@State private var pngSharePayload: PNGSharePayload?
@State private var fileURLSharePayload: FileURLSharePayload?
/// PDF: Quick Look (System-Vorschau), statt nur Share Sheet.
@State private var pdfQuickLookURL: URL?
@State private var keyboardOverlap: CGFloat = 0
#endif
@AppStorage(ExportFilenameStyle.appStorageKey) private var exportFilenameStyleRaw: String = ExportFilenameStyle.dateAndTitle.rawValue
@AppStorage(VisuStructUIScaleStep.appStorageKeyCanvas) private var canvasScaleRaw: String = VisuStructUIScaleStep.small.rawValue
@AppStorage(VisuStructUIScaleStep.appStorageKeyInspector) private var inspectorScaleRaw: String = VisuStructUIScaleStep.small.rawValue
@State private var editorFocusToken = UUID()
@AppStorage(SimulationStepDelayOption.appStorageKey) private var simulationStepDelayRaw: String = SimulationStepDelayOption.defaultRawValue
@AppStorage(SimulationHighlightMode.appStorageKey) private var simulationHighlightModeRaw: String = SimulationHighlightMode.defaultRawValue
private var canvasScaleStep: VisuStructUIScaleStep {
VisuStructUIScaleStep(rawValue: canvasScaleRaw) ?? .small
}
private var inspectorScaleStep: VisuStructUIScaleStep {
VisuStructUIScaleStep(rawValue: inspectorScaleRaw) ?? .small
}
private var exportFilenameStyle: ExportFilenameStyle {
ExportFilenameStyle.fromStored(exportFilenameStyleRaw)
}
private var simulationStepDelay: SimulationStepDelayOption {
SimulationStepDelayOption.fromStored(simulationStepDelayRaw)
}
private var simulationHighlightMode: SimulationHighlightMode {
SimulationHighlightMode.fromStored(simulationHighlightModeRaw)
}
init() {
let startupLang = AppLanguage.currentFromDefaults()
let model = DiagramSheetTabsModel.makeInitial(language: startupLang)
let recentStore = RecentFilesStore.shared
_tabsModel = State(initialValue: model)
_recentFilesStore = ObservedObject(wrappedValue: recentStore)
_documentServices = State(initialValue: DiagramEditorDocumentServices(tabsModel: model, recentFilesStore: recentStore))
_simulationEngine = State(initialValue: VisuStructSimulationEngine(document: model.tabs[0].document))
}
// MARK: - Tab-Titel & Dokument öffnen
@discardableResult
private func openDocument(from url: URL) -> Bool {
documentServices.openDocument(
from: url,
resetHistoryAndDocument: resetHistoryAndDocument,
refreshLineEditor: refreshLineEditor,
setError: setErrorOnCurrentTab
)
}
private func openRecentFile(_ recentFile: RecentVisuStructFile) {
documentServices.openRecentFile(
recentFile,
resetHistoryAndDocument: resetHistoryAndDocument,
refreshLineEditor: refreshLineEditor,
setError: setErrorOnCurrentTab
)
}
/// Finder / Dateien: Doppelklick bzw. „Öffnen mit“ auf `.visustruct` oder `.strk`.
private func openIncomingDocument(from url: URL) {
guard url.isFileURL else { return }
guard VisuStructDiagramFile.isOpenableDiagram(url: url) else { return }
if isSimulationMode {
endSimulationMode()
}
let tab = tabsModel.tabs[tabsModel.currentTabIndex]
if tabsModel.tabHasUnsavedChanges(tab) || tab.linkedFileBookmarkData != nil {
addDiagramTab()
}
_ = openDocument(from: url)
}
private var document: VisuStructDocument {
tabsModel.tabs[tabsModel.currentTabIndex].document
}
private var selectedPath: [Int]? {
tabsModel.tabs[tabsModel.currentTabIndex].selectedPath
}
private func replaceSelectedPathOnCurrentTab(_ path: [Int]?) {
var tabs = tabsModel.tabs
let i = tabsModel.currentTabIndex
tabs[i].selectedPath = path
tabsModel.tabs = tabs
}
private var unsavedCloseAlertBinding: Binding<Bool> {
Binding(
get: { tabsModel.pendingCloseTabId != nil },
set: { if !$0 { tabsModel.pendingCloseTabId = nil } }
)
}
// MARK: - body
var body: some View {
Group {
if horizontalSizeClass == .regular {
NavigationSplitView {
iPadPaletteSidebarColumn
} detail: {
mainEditorNavigationStack
}
.navigationSplitViewStyle(.balanced)
} else {
VStack(spacing: 0) {
if !isPhone {
paletteListPanel
.frame(maxHeight: 300, alignment: .top)
.background(Color(.secondarySystemGroupedBackground))
.clipped()
}
Divider()
mainEditorNavigationStack
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
.sheet(isPresented: phonePaletteSheetBinding) {
paletteListPanel
.environment(\.appLanguage, lang)
.presentationDetents([.medium, .large])
// Diagramm bleibt bedienbar, z. B. um eine Einfügestelle zu wählen.
.presentationBackgroundInteraction(.enabled(upThrough: .medium))
.presentationDragIndicator(.visible)
}
}
}
#if canImport(UIKit)
.onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillChangeFrameNotification)) { n in
updateKeyboardOverlap(from: n)
}
.onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillHideNotification)) { _ in
keyboardOverlap = 0
}
#endif
.onAppear {
refreshLineEditor()
DiagramCommandCenter.shared.update(file: diagramFileActions, edit: diagramEditActions)
if let url = incomingDocuments.pendingURL {
incomingDocuments.pendingURL = nil
openIncomingDocument(from: url)
}
}
.onReceive(NotificationCenter.default.publisher(for: DiagramMenuNotification.newDocument)) { _ in
guard !isSimulationMode else { return }
addDiagramTab()
}
.onReceive(NotificationCenter.default.publisher(for: DiagramMenuNotification.open)) { _ in
guard !isSimulationMode else { return }
showImporter = true
}
.background {
Button(lang.tr("menu_open")) {
guard !isSimulationMode else { return }
showImporter = true
}
.keyboardShortcut("o", modifiers: .command)
.opacity(0.001)
.accessibilityHidden(true)
}
.onReceive(NotificationCenter.default.publisher(for: DiagramMenuNotification.save)) { _ in
guard !isSimulationMode else { return }
performPrimarySave()
}
.onReceive(NotificationCenter.default.publisher(for: DiagramMenuNotification.saveAs)) { _ in
guard !isSimulationMode else { return }
showExporter = true
}
.onReceive(NotificationCenter.default.publisher(for: DiagramMenuNotification.printDocument)) { _ in
guard !isSimulationMode else { return }
#if canImport(UIKit)
printDiagram()
#endif
}
.onReceive(NotificationCenter.default.publisher(for: DiagramMenuNotification.close)) { _ in
guard !isSimulationMode else { return }
requestCloseDiagramTab(id: tabsModel.selectedTabId)
}
.onReceive(NotificationCenter.default.publisher(for: DiagramMenuNotification.openRecent)) { note in
guard !isSimulationMode else { return }
guard let id = note.userInfo?[DiagramMenuNotification.recentFileIDKey] as? String,
let file = recentFilesStore.files.first(where: { $0.id == id }) else { return }
openRecentFile(file)
}
.onChange(of: isSimulationMode) { _, _ in
DiagramCommandCenter.shared.update(file: diagramFileActions, edit: diagramEditActions)
}
.onChange(of: incomingDocuments.pendingURL) { _, url in
guard let url else { return }
incomingDocuments.pendingURL = nil
openIncomingDocument(from: url)
}
.alert(lang.tr("close_unsaved_title"), isPresented: unsavedCloseAlertBinding) {
Button(lang.tr("menu_save")) {
savePendingCloseTab()
}
Button(lang.tr("close_unsaved_discard"), role: .destructive) {
discardPendingCloseTab()
}
Button(lang.tr("close_unsaved_cancel"), role: .cancel) {
tabsModel.pendingCloseTabId = nil
}
} message: {
Text(lang.tr("close_unsaved_message"))
}
.fileImporter(
isPresented: $showImporter,
allowedContentTypes: VisuStructFileDocument.readableContentTypes,
allowsMultipleSelection: false
) { result in
switch result {
case .success(let urls):
guard let url = urls.first else { return }
Task { @MainActor in
openDocument(from: url)
}
case .failure(let err):
let message = err.localizedDescription
Task { @MainActor in
setErrorOnCurrentTab(message)
}
}
}
.fileExporter(
isPresented: $showExporter,
document: VisuStructFileDocument(document: document),
contentType: VisuStructFileDocument.preferredExportContentType,
defaultFilename: exportFilenameForCurrentTab()
) { result in
switch result {
case .success(let url):
Task { @MainActor in
guard documentServices.finalizeExporterSave(to: url, language: lang, setError: setErrorOnCurrentTab) else { return }
if let pendingId = tabsModel.closeTabAfterSuccessfulExportId {
tabsModel.closeTabAfterSuccessfulExportId = nil
performCloseDiagramTab(id: pendingId)
}
}
case .failure(let err):
let message = err.localizedDescription
Task { @MainActor in
tabsModel.closeTabAfterSuccessfulExportId = nil
setErrorOnCurrentTab(message)
}
}
}
.sheet(isPresented: $showInfo) {
AboutVisuStructView()
}
.sheet(isPresented: $showCodeGeneratorPaywall) {
CodeGeneratorPaywallSheet()
}
.sheet(isPresented: Binding(
get: { isPhone && showCodeGeneratorPlaceholder },
set: { if !$0 { showCodeGeneratorPlaceholder = false } }
)) {
CodeGeneratorPlaceholderSheet(
document: documentBinding,
regenerationToken: codeGeneratorRegenerationToken
)
}
.overlay {
if !isPhone && showCodeGeneratorPlaceholder {
DraggableCodeGeneratorFloatingPanel(
isPresented: $showCodeGeneratorPlaceholder,
document: documentBinding,
regenerationToken: codeGeneratorRegenerationToken
)
.transition(.opacity)
}
}
#if canImport(UIKit)
.sheet(item: $pngSharePayload) { payload in
ActivityShareSheet(items: [payload.image])
}
.sheet(item: $fileURLSharePayload) { payload in
ActivityShareSheet(items: [payload.url])
}
.quickLookPreview($pdfQuickLookURL)
#endif
.onChange(of: tabsModel.selectedTabId) { _, _ in
refreshLineEditor()
DiagramCommandCenter.shared.update(file: diagramFileActions, edit: diagramEditActions)
}
.onChange(of: insertTarget) { _, newTarget in
// iPhone: Einfügestelle gewählt → Palette öffnen, damit gleich ein Element gewählt werden kann.
guard isPhone, newTarget != nil else { return }
showPaletteOnPhone = true
}
.onChange(of: focusedField) { _, newVal in
// iPhone: Sobald Textbearbeitung startet, Palette einklappen für mehr Platz.
guard isPhone else { return }
if newVal != nil {
withAnimation(.easeInOut(duration: 0.15)) {
showPaletteOnPhone = false
}
}
}
.background {
DiagramMenuCommandSync(
fileActions: diagramFileActions,
editActions: diagramEditActions,
refreshToken: "\(tabsModel.selectedTabId.uuidString)-\(isSimulationMode)"
)
}
}
private var diagramEditActions: DiagramEditActions {
let isTyping: Bool = {
switch focusedField {
case .none: return false
case .caption, .caseLabel, .textEditor, .forLoopPart(_): return true
}
}()
let hasSelection = selectedPath != nil
let canCopy = !isTyping && hasSelection
let canPaste = !isTyping && elementClipboard != nil
let canCut = canCopy && (selectedPath.map { VisuStructDocumentEditing.canDeleteElement(at: $0, in: document) } ?? false)
let canDelete = !isTyping && (selectedPath.map { VisuStructDocumentEditing.canDeleteElement(at: $0, in: document) } ?? false)
return DiagramEditActions(
canUndo: !isTyping && !tabsModel.tabs[tabsModel.currentTabIndex].undoStack.isEmpty,
canRedo: !isTyping && !tabsModel.tabs[tabsModel.currentTabIndex].redoStack.isEmpty,
canCopy: canCopy,
canCut: canCut,
canPaste: canPaste,
canDelete: canDelete,
undo: { performUndo() },
redo: { performRedo() },
copy: { copySelectionToClipboard() },
cut: { cutSelectionToClipboard() },
paste: { pasteClipboardAtSelectionOrRoot() },
delete: { deleteSelection() }
)
}
private var diagramFileActions: DiagramFileActions {
let fileEnabled = !isSimulationMode
return DiagramFileActions(
canNew: fileEnabled,
canOpen: fileEnabled,
canSave: fileEnabled,
canSaveAs: fileEnabled,
canPrint: fileEnabled,
canClose: fileEnabled && tabsModel.tabs.count > 1,
newDocument: { addDiagramTab() },
open: { showImporter = true },
save: { performPrimarySave() },
saveAs: { showExporter = true },
printDocument: {
#if canImport(UIKit)
printDiagram()
#endif
},
close: { requestCloseDiagramTab(id: tabsModel.selectedTabId) },
recentFiles: recentFilesStore.files,
openRecent: openRecentFile,
clearRecent: { recentFilesStore.clear() }
)
}
// MARK: - Zwischenablage (Diagramm)
private func copySelectionToClipboard() {
guard let path = selectedPath,
let el = try? VisuStructDocumentEditing.element(at: path, in: document) else { return }
elementClipboard = el
}
private func cutSelectionToClipboard() {
guard let path = selectedPath,
let el = try? VisuStructDocumentEditing.element(at: path, in: document) else { return }
elementClipboard = el
deleteSelection()
}
private func pasteClipboardAtSelectionOrRoot() {
guard let clip = elementClipboard else { return }
let doc = document
do {
if let path = selectedPath {
if VisuStructDocumentEditing.isPlaceholderSlot(at: path, in: doc) {
commitDocument(try VisuStructDocumentEditing.replaceAtPath(doc, path: path, with: clip))
var tabs = tabsModel.tabs
tabs[tabsModel.currentTabIndex].selectedPath = path
tabs[tabsModel.currentTabIndex].errorText = nil
tabsModel.tabs = tabs
refreshLineEditor()
return
}
if (try? VisuStructDocumentEditing.element(at: path, in: doc)) != nil {
commitDocument(try VisuStructDocumentEditing.insertAfterSibling(doc, clip, after: path))
let newPath = Array(path.dropLast()) + [path.last! + 1]
var tabs = tabsModel.tabs
tabs[tabsModel.currentTabIndex].selectedPath = newPath
tabs[tabsModel.currentTabIndex].errorText = nil
tabsModel.tabs = tabs
refreshLineEditor()
return
}
}
appendRoot(clip)
} catch {
setErrorOnCurrentTab(error.localizedDescription)
}
}
// MARK: - Palette
/// iPad: Sidebar-Spalte mit System-Split (ein-/ausblendbar, Standardbreiten).
private var iPadPaletteSidebarColumn: some View {
NavigationStack {
paletteListStackBody
.navigationTitle(lang.tr("palette_header"))
.navigationBarTitleDisplayMode(.inline)
.toolbarBackground(.visible, for: .navigationBar)
.toolbarBackground(Color(.secondarySystemGroupedBackground), for: .navigationBar)
}
.background(Color(.secondarySystemGroupedBackground))
.navigationSplitViewColumnWidth(min: 220, ideal: 288, max: 400)
}
/// iPhone: Überschrift im Panel + Liste (kein doppelter Titel wie in der Sidebar).
private var paletteListPanel: some View {
VStack(spacing: 0) {
Text(lang.tr("palette_header"))
.font(.headline)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.horizontal, 16)
.padding(.top, 10)
.padding(.bottom, 8)
paletteListStackBody
}
}
/// Gemeinsamer List-Inhalt für Palette + Aktionen.
@ViewBuilder
private var paletteListStackBody: some View {
let isCompact = horizontalSizeClass != .regular
List {
Section {
ForEach(ElementPalette.PaletteItem.paletteOrder) { item in
paletteStructureRow(item, isCompact: isCompact)
}
}
Section {
Button {
deleteSelection()
} label: {
Label(lang.tr("action_delete_selection"), systemImage: "trash")
}
.buttonStyle(PaletteListElementButtonStyle(emphasis: .destructive))
.disabledAndDimmed(isSimulationMode)
.listRowInsets(
isCompact
? EdgeInsets(top: 4, leading: 10, bottom: 3, trailing: 10)
: EdgeInsets(top: 8, leading: 12, bottom: 5, trailing: 12)
)
.listRowSeparator(.hidden)
.listRowBackground(Color.clear)
.disabled(
isSimulationMode || (selectedPath.map { path in
!VisuStructDocumentEditing.canDeleteElement(at: path, in: document)
} ?? true)
)
Button {
if !isSimulationMode {
applyLineEditorRespectingTextFocus()
DispatchQueue.main.async {
beginSimulationMode()
}
} else {
endSimulationMode()
}
} label: {
Label(
isSimulationMode ? lang.tr("action_diagram") : lang.tr("action_simulation"),
systemImage: isSimulationMode ? "rectangle.split.3x1" : "play.circle"
)
}
.buttonStyle(PaletteListElementButtonStyle())
.listRowInsets(
isCompact
? EdgeInsets(top: 3, leading: 10, bottom: 3, trailing: 10)
: EdgeInsets(top: 5, leading: 12, bottom: 5, trailing: 12)
)
.listRowSeparator(.hidden)
.listRowBackground(Color.clear)
.accessibilityLabel(isSimulationMode ? lang.tr("action_diagram") : lang.tr("action_simulation"))
Button {
if codeGeneratorAccessGranted {
// Wichtig: Text im Inspector ist nicht immer sofort ins Dokument geschrieben (Button „Text übernehmen“).
// Für Code-Generierung wollen wir immer den aktuell sichtbaren Stand verwenden.
applyLineEditorRespectingTextFocus()
DispatchQueue.main.async {
codeGeneratorRegenerationToken &+= 1
showCodeGeneratorPlaceholder = true
}
} else {
showCodeGeneratorPaywall = true
}
} label: {
HStack(spacing: 10) {
Label(lang.tr("action_generate_code"), systemImage: "chevron.left.forwardslash.chevron.right")
.foregroundStyle(isSimulationMode ? .tertiary : .primary)
Spacer(minLength: 8)
if !codeGeneratorAccessGranted {
Image(systemName: "lock.fill")
.font(.body)
.foregroundStyle(.secondary)
}
}
}
.buttonStyle(PaletteListElementButtonStyle())
.disabledAndDimmed(isSimulationMode)
.listRowInsets(
isCompact
? EdgeInsets(top: 3, leading: 10, bottom: 3, trailing: 10)
: EdgeInsets(top: 5, leading: 12, bottom: 5, trailing: 12)
)
.listRowSeparator(.hidden)
.listRowBackground(Color.clear)
.accessibilityLabel(
codeGeneratorAccessGranted ? lang.tr("a11y_generate_code") : lang.tr("a11y_generate_code_locked")
)
Button {
exportPNG()
} label: {
Label(lang.tr("action_share_png"), systemImage: "square.and.arrow.up")
.foregroundStyle(isSimulationMode ? .tertiary : .primary)
}
.buttonStyle(PaletteListElementButtonStyle())
.disabledAndDimmed(isSimulationMode)
.listRowInsets(
isCompact
? EdgeInsets(top: 3, leading: 10, bottom: 3, trailing: 10)
: EdgeInsets(top: 5, leading: 12, bottom: 5, trailing: 12)
)
.listRowSeparator(.hidden)
.listRowBackground(Color.clear)
Button {
shareDocumentAsFile()
} label: {
Label(lang.tr("action_share_document"), systemImage: "square.and.arrow.up.on.square")
.foregroundStyle(isSimulationMode ? .tertiary : .primary)
}
.buttonStyle(PaletteListElementButtonStyle())
.disabledAndDimmed(isSimulationMode)
.listRowInsets(
isCompact
? EdgeInsets(top: 3, leading: 10, bottom: 3, trailing: 10)
: EdgeInsets(top: 5, leading: 12, bottom: 5, trailing: 12)
)
.listRowSeparator(.hidden)
.listRowBackground(Color.clear)
Button {
shareDiagramPDF()
} label: {
Label(lang.tr("action_export_pdf"), systemImage: "doc.text.magnifyingglass")
.foregroundStyle(isSimulationMode ? .tertiary : .primary)
}
.buttonStyle(PaletteListElementButtonStyle())
.disabledAndDimmed(isSimulationMode)
.listRowInsets(
isCompact
? EdgeInsets(top: 3, leading: 10, bottom: 3, trailing: 10)
: EdgeInsets(top: 5, leading: 12, bottom: 5, trailing: 12)
)
.listRowSeparator(.hidden)
.listRowBackground(Color.clear)
Button {
showInfo = true
} label: {
Label(lang.tr("action_about"), systemImage: "info.circle")
}
.buttonStyle(PaletteListElementButtonStyle())
.listRowInsets(
isCompact
? EdgeInsets(top: 3, leading: 10, bottom: 4, trailing: 10)
: EdgeInsets(top: 5, leading: 12, bottom: 8, trailing: 12)
)
.listRowSeparator(.hidden)
.listRowBackground(Color.clear)
}
}
.listStyle(.insetGrouped)
.listSectionSpacing(isCompact ? 8 : 18)
.environment(\.defaultMinListRowHeight, isCompact ? 34 : 48)
.scrollContentBackground(.hidden)
}
// MARK: - Haupteditor (NavigationStack, Tabs, Fehler)
private var mainEditorNavigationStack: some View {
NavigationStack {
ZStack(alignment: .topLeading) {
VStack(spacing: 0) {
DiagramTabStrip(
tabs: tabsModel.tabs,
selectedTabId: tabsModel.selectedTabId,
displayTitle: { tabsModel.diagramTabDisplayTitle($0, language: lang) },
hasUnsavedChanges: { tabsModel.tabHasUnsavedChanges($0) },
onSelectTab: { id in
tabsModel.selectedTabId = id
refreshLineEditor()
},
onAddTab: addDiagramTab,
onRequestCloseTab: { requestCloseDiagramTab(id: $0) }
)
Group {
if let err = tabsModel.tabs[tabsModel.currentTabIndex].errorText {
VStack(spacing: 20) {
ContentUnavailableView(
lang.tr("error_title"),
systemImage: "exclamationmark.triangle",
description: Text(verbatim: err)
)
Button(lang.tr("error_back_editor")) {
clearErrorOnCurrentTab()
}
.buttonStyle(.borderedProminent)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
} else {
editorDetail
}
}
}
// Explizit `navigationTitle` setzen, nicht nur `ToolbarItem(placement: .principal)`: sonst reserviert SwiftUI
// in der Navigationsleiste oft keinen sichtbaren Mittelbereich (Titel wirkend „invisible“ / Breite 0, bes. iPhone).
.navigationTitle(tabsModel.diagramTabDisplayTitle(tabsModel.tabs[tabsModel.currentTabIndex], language: lang))
.navigationBarTitleDisplayMode(.inline)
.toolbarBackground(.visible, for: .navigationBar)
.toolbarBackground(.regularMaterial, for: .navigationBar)
.toolbar {
mainEditorToolbarItems()
}
}
}
.background(Color(.systemGroupedBackground))
}
private func mainEditorToolbarItems() -> DiagramMainEditorToolbar {
let tab = tabsModel.tabs[tabsModel.currentTabIndex]
let displayTitle = tabsModel.diagramTabDisplayTitle(tab, language: lang)
let unsaved = tabsModel.tabHasUnsavedChanges(tab)
let isTyping: Bool = {
switch focusedField {
case .none: return false
case .caption, .caseLabel, .textEditor, .forLoopPart(_): return true
}
}()
#if canImport(UIKit)
let printAction: (() -> Void)? = { printDiagram() }
#else
let printAction: (() -> Void)? = nil
#endif
return DiagramMainEditorToolbar(
principalTitle: displayTitle,
principalShowsUnsaved: unsaved,
principalAccessibilityLabel: unsaved ? "\(displayTitle), \(lang.tr("a11y_unsaved_changes"))" : displayTitle,
canUndo: !isTyping && !tab.undoStack.isEmpty,
canRedo: !isTyping && !tab.redoStack.isEmpty,
onUndo: performUndo,
onRedo: performRedo,
isSimulationMode: isSimulationMode,
isPhone: isPhone,
onTogglePalettePhone: {
withAnimation(.easeInOut(duration: 0.15)) {
showPaletteOnPhone.toggle()
}
},
recentFiles: recentFilesStore.files,
onOpenImporter: { showImporter = true },
onPickRecent: openRecentFile,
onClearRecent: { recentFilesStore.clear() },
onSave: performPrimarySave,
onSaveAs: { showExporter = true },
onPrint: printAction,
onKeyboardDismiss: {
focusedField = nil
if isPhone { hideInspectorOnPhone = true }
}
)
}
// MARK: - Editor-Ansicht (Bearbeiten vs. Simulation)
@ViewBuilder
private var editorDetail: some View {
Group {
if isSimulationMode {
simulationDetailView
} else {
VStack(alignment: .leading, spacing: 20) {
canvasAndCaptionBlock
.layoutPriority(1)
inspectorPanelPhoneAware
}
}
}
.padding(horizontalSizeClass == .regular ? EdgeInsets(top: 16, leading: 18, bottom: 16, trailing: 18) : EdgeInsets(top: 16, leading: 14, bottom: 16, trailing: 14))
#if canImport(UIKit)
// iPad: Tastatur kann den Inspector/TextEditor verdecken. Nur im Bearbeitungsmodus ausgleichen.
.padding(.bottom, (!isSimulationMode && horizontalSizeClass == .regular && focusedField != nil) ? keyboardOverlap : 0)
#endif
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
}
// MARK: - Simulations-Ansicht
@ViewBuilder
private var simulationDetailView: some View {
GeometryReader { geo in
// Seitenspalte nur im Querformat; hochkant wäre sie gequetscht und unter dem Diagramm bliebe Platz frei.
let useColumns = geo.size.width >= 760 && geo.size.width > geo.size.height
// iPad hochkant: Diagramm oben, Steuerfeld darunter über die volle Breite.
let useWideStack = !useColumns && geo.size.width >= 600 && geo.size.height >= 700
let panelWidth = min(max(geo.size.width * 0.32, 280), 360)
if useColumns {
HStack(alignment: .top, spacing: 16) {
simulationCanvasBlock
.layoutPriority(1)
SimulationStatePanel(
engine: simulationEngine,
isPlaying: isSimulationPlaying,
inputText: $simulationInputText,
highlightModeRaw: $simulationHighlightModeRaw,
onPlay: playSimulation,
onPause: pauseSimulation,
onStep: stepSimulation,
onSubmitInput: submitSimulationInput,
onStop: resetSimulation
)
.frame(width: panelWidth)
.frame(maxHeight: .infinity, alignment: .top)
}
} else if useWideStack {
VStack(alignment: .leading, spacing: 16) {
simulationCanvasBlock
.frame(height: geo.size.height * 0.5)
SimulationStatePanel(
engine: simulationEngine,
isPlaying: isSimulationPlaying,
inputText: $simulationInputText,
highlightModeRaw: $simulationHighlightModeRaw,
onPlay: playSimulation,
onPause: pauseSimulation,
onStep: stepSimulation,
onSubmitInput: submitSimulationInput,
onStop: resetSimulation,
usesWideLayout: true
)
.frame(maxHeight: .infinity)
}
} else {
ScrollView {
VStack(alignment: .leading, spacing: 16) {
simulationCanvasBlock
.frame(height: max(340, geo.size.height * 0.55))
SimulationStatePanel(
engine: simulationEngine,
isPlaying: isSimulationPlaying,
inputText: $simulationInputText,
highlightModeRaw: $simulationHighlightModeRaw,
onPlay: playSimulation,
onPause: pauseSimulation,
onStep: stepSimulation,
onSubmitInput: submitSimulationInput,
onStop: resetSimulation
)
}
.frame(maxWidth: .infinity, alignment: .leading)
}
}
}
}
// MARK: - Canvas (Simulation)
private var simulationCanvasBlock: some View {
let diagramPaper = Color(white: 0.98)
let blockCorner: CGFloat = horizontalSizeClass == .regular ? 14 : 12
return GeometryReader { geo in
ScrollView([.horizontal, .vertical]) {
DiagramCanvasView(
document: documentBinding,
selectedPath: selectedPathBinding,
errorText: errorTextBinding,
insertTarget: $insertTarget,
elementClipboard: $elementClipboard,
canvasScaleStep: canvasScaleStep,
minViewportSize: CGSize(width: geo.size.width, height: geo.size.height),
usesSimulationSelectionHighlight: true
)
.padding(.vertical, 8)
.fixedSize(horizontal: true, vertical: false)
.allowsHitTesting(false)
}
.scrollBounceBehavior(isPhone ? .always : .basedOnSize, axes: [.horizontal, .vertical])
.scrollIndicators(.automatic)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background {
RoundedRectangle(cornerRadius: blockCorner, style: .continuous)
.fill(diagramPaper)
}
.clipShape(RoundedRectangle(cornerRadius: blockCorner, style: .continuous))
.overlay {
RoundedRectangle(cornerRadius: blockCorner, style: .continuous)
.strokeBorder(Color.primary.opacity(0.08), lineWidth: 1)
}
}
// MARK: - Canvas & Diagrammtitel (Bearbeitung)
/// Oberer Bereich: Diagramm-Titel + Canvas in **einer** visuellen Einheit (gleiche Fläche wie `diagramCanvasFill` in `DiagramCanvasView`).
private var canvasAndCaptionBlock: some View {
let diagramPaper = Color(white: 0.98)
let blockCorner: CGFloat = horizontalSizeClass == .regular ? 14 : 12
return VStack(alignment: .leading, spacing: 0) {
if isPhone {
phoneCaptionRow
} else {
VStack(alignment: .leading, spacing: 8) {
Text(lang.tr("diagram_title_label"))
.font(horizontalSizeClass == .regular ? .caption : .subheadline)
.foregroundStyle(.secondary)
TextField(lang.tr("diagram_title_placeholder"), text: captionBinding)
.font(horizontalSizeClass == .regular ? .subheadline : .body)
.textFieldStyle(.roundedBorder)
.textInputAutocapitalization(.never)
.autocorrectionDisabled(true)
.focused($focusedField, equals: .caption)
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.horizontal, 14)
.padding(.top, 8)
.padding(.bottom, 6)
}
// Innerer Trennstrich — Titel zählt zum Diagramm-„Blatt“, nicht als losgelöster Bereich oberhalb.
Rectangle()
.fill(Color.primary.opacity(0.1))
.frame(height: 1)
.padding(.horizontal, 10)
GeometryReader { geo in
ScrollView([.horizontal, .vertical]) {
DiagramCanvasView(
document: documentBinding,
selectedPath: selectedPathBinding,
errorText: errorTextBinding,
insertTarget: $insertTarget,
elementClipboard: $elementClipboard,
canvasScaleStep: canvasScaleStep,
minViewportSize: CGSize(width: geo.size.width, height: geo.size.height)
)
.padding(.vertical, 8)
// WICHTIG: horizontal nicht komprimieren lassen → sonst hat der ScrollView keine Content-Breite zum Scrollen.
.fixedSize(horizontal: true, vertical: false)
}
// iPhone: horizontales Scrollen muss zuverlässig funktionieren, sobald das Diagramm breiter als der Viewport ist.
.scrollBounceBehavior(isPhone ? .always : .basedOnSize, axes: [.horizontal, .vertical])
.scrollIndicators(.automatic)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
.background {
RoundedRectangle(cornerRadius: blockCorner, style: .continuous)
.fill(diagramPaper)
}
.clipShape(RoundedRectangle(cornerRadius: blockCorner, style: .continuous))
.overlay {
RoundedRectangle(cornerRadius: blockCorner, style: .continuous)
.strokeBorder(Color.primary.opacity(0.08), lineWidth: 1)
}
}
/// iPhone: Titel als eine kompakte Zeile; Tippen öffnet einen Dialog zum Bearbeiten.
private var phoneCaptionRow: some View {
Button {
phoneTitleDraft = document.caption
showPhoneTitleEditor = true
} label: {
HStack(spacing: 6) {
Text(document.caption.isEmpty ? lang.tr("diagram_title_placeholder") : document.caption)
.font(.subheadline.weight(.semibold))
.foregroundStyle(document.caption.isEmpty ? .secondary : .primary)
.lineLimit(1)
Image(systemName: "pencil")
.font(.caption)
.foregroundStyle(.secondary)
}
.frame(maxWidth: .infinity, alignment: .leading)
.contentShape(Rectangle())
}
.buttonStyle(.plain)
.accessibilityLabel(lang.tr("diagram_title_label"))
.padding(.horizontal, 14)
.padding(.vertical, 8)
.alert(lang.tr("diagram_title_label"), isPresented: $showPhoneTitleEditor) {
TextField(lang.tr("diagram_title_placeholder"), text: $phoneTitleDraft)
.textInputAutocapitalization(.never)
.autocorrectionDisabled(true)
Button(lang.tr("phone_title_done")) {
if phoneTitleDraft != document.caption {
captionBinding.wrappedValue = phoneTitleDraft
}
}
}
}
private var phonePaletteSheetBinding: Binding<Bool> {
Binding(
get: { isPhone && showPaletteOnPhone },
set: { showPaletteOnPhone = $0 }
)
}