-
-
Notifications
You must be signed in to change notification settings - Fork 135
Expand file tree
/
Copy pathContentView.swift
More file actions
447 lines (414 loc) · 19.8 KB
/
ContentView.swift
File metadata and controls
447 lines (414 loc) · 19.8 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
//
// ContentView.swift
// TablePro
//
// Created by Ngo Quoc Dat on 16/12/25.
//
import AppKit
import os
import SwiftUI
import TableProPluginKit
struct ContentView: View {
private static let logger = Logger(subsystem: "com.TablePro", category: "ContentView")
/// Payload identifying what this native window-tab should display.
/// nil = default empty query tab (first window on connection).
let payload: EditorTabPayload?
@State private var currentSession: ConnectionSession?
@State private var closingSessionId: UUID?
@State private var columnVisibility: NavigationSplitViewVisibility = .all
@State private var showNewConnectionSheet = false
@State private var showEditConnectionSheet = false
@State private var connectionToEdit: DatabaseConnection?
@State private var connectionToDelete: DatabaseConnection?
@State private var showDeleteConfirmation = false
@State private var rightPanelState: RightPanelState?
@State private var sessionState: SessionStateFactory.SessionState?
@State private var inspectorContext = InspectorContext.empty
@State private var windowTitle: String
@Environment(\.openWindow)
private var openWindow
@Environment(AppState.self) private var appState
private let storage = ConnectionStorage.shared
init(payload: EditorTabPayload?) {
self.payload = payload
let defaultTitle: String
if let tableName = payload?.tableName {
defaultTitle = tableName
} else if let connectionId = payload?.connectionId,
let connection = DatabaseManager.shared.activeSessions[connectionId]?.connection {
let langName = PluginManager.shared.queryLanguageName(for: connection.type)
defaultTitle = "\(langName) Query"
} else {
defaultTitle = "SQL Query"
}
_windowTitle = State(initialValue: defaultTitle)
// Resolve session synchronously to avoid "Connecting..." flash.
// For payload with connectionId: look up that specific session.
// For nil payload (native tab bar "+"): fall back to current session.
var resolvedSession: ConnectionSession?
if let connectionId = payload?.connectionId {
resolvedSession = DatabaseManager.shared.activeSessions[connectionId]
} else if let currentId = DatabaseManager.shared.currentSessionId {
resolvedSession = DatabaseManager.shared.activeSessions[currentId]
}
_currentSession = State(initialValue: resolvedSession)
if let session = resolvedSession {
_rightPanelState = State(initialValue: RightPanelState())
_sessionState = State(initialValue: SessionStateFactory.create(
connection: session.connection, payload: payload
))
} else {
_rightPanelState = State(initialValue: nil)
_sessionState = State(initialValue: nil)
}
}
var body: some View {
mainContent
.frame(minWidth: 1_200, minHeight: 600)
.confirmationDialog(
"Delete Connection",
isPresented: $showDeleteConfirmation,
presenting: connectionToDelete
) { connection in
Button("Delete", role: .destructive) {
deleteConnection(connection)
}
Button("Cancel", role: .cancel) {}
} message: { connection in
Text("Are you sure you want to delete \"\(connection.name)\"?")
}
.onReceive(NotificationCenter.default.publisher(for: .newConnection)) { _ in
openWindow(id: "connection-form", value: nil as UUID?)
}
// Right sidebar toggle is handled by MainContentView (has the binding)
// Left sidebar toggle uses native NSSplitViewController.toggleSidebar via responder chain
.onChange(of: DatabaseManager.shared.currentSessionId, initial: true) { _, newSessionId in
guard closingSessionId == nil else { return }
let ourConnectionId = payload?.connectionId
if ourConnectionId != nil {
guard newSessionId == ourConnectionId else { return }
} else {
guard currentSession == nil else { return }
}
if let connectionId = ourConnectionId ?? newSessionId {
currentSession = DatabaseManager.shared.activeSessions[connectionId]
columnVisibility = currentSession != nil ? .all : .detailOnly
if let session = currentSession {
if rightPanelState == nil {
rightPanelState = RightPanelState()
}
if sessionState == nil {
sessionState = SessionStateFactory.create(
connection: session.connection,
payload: payload
)
}
AppState.shared.isConnected = true
AppState.shared.safeModeLevel = session.connection.safeModeLevel
AppState.shared.editorLanguage = PluginManager.shared.editorLanguage(for: session.connection.type)
AppState.shared.currentDatabaseType = session.connection.type
AppState.shared.supportsDatabaseSwitching = PluginManager.shared.supportsDatabaseSwitching(
for: session.connection.type)
}
} else {
currentSession = nil
columnVisibility = .detailOnly
}
}
.task { handleConnectionStatusChange() }
.onReceive(NotificationCenter.default.publisher(for: .connectionStatusDidChange)) { _ in
handleConnectionStatusChange()
}
.onReceive(NotificationCenter.default.publisher(for: NSWindow.didBecomeKeyNotification)) { notification in
// Only process notifications for our own window to avoid every
// ContentView instance re-rendering on every window focus change.
// Match by checking if the window is registered for our connectionId
// in WindowLifecycleMonitor (subtitle may not be set yet on first appear).
guard let notificationWindow = notification.object as? NSWindow,
let windowId = notificationWindow.identifier?.rawValue,
windowId == "main" || windowId.hasPrefix("main-"),
let connectionId = payload?.connectionId
else { return }
// Verify this notification is for our window. Check WindowLifecycleMonitor
// first (reliable after onAppear registers), fall back to subtitle match
// for the brief window before registration completes.
let isOurWindow = WindowLifecycleMonitor.shared.windows(for: connectionId)
.contains(where: { $0 === notificationWindow })
|| {
guard let name = currentSession?.connection.name, !name.isEmpty else { return false }
return notificationWindow.subtitle == name
|| notificationWindow.subtitle == "\(name) — Preview"
}()
guard isOurWindow else { return }
if let session = DatabaseManager.shared.activeSessions[connectionId] {
AppState.shared.isConnected = true
AppState.shared.safeModeLevel = session.connection.safeModeLevel
AppState.shared.editorLanguage = PluginManager.shared.editorLanguage(for: session.connection.type)
AppState.shared.currentDatabaseType = session.connection.type
AppState.shared.supportsDatabaseSwitching = PluginManager.shared.supportsDatabaseSwitching(
for: session.connection.type)
} else {
AppState.shared.isConnected = false
AppState.shared.safeModeLevel = .silent
AppState.shared.editorLanguage = .sql
AppState.shared.currentDatabaseType = nil
AppState.shared.supportsDatabaseSwitching = true
}
}
.onChange(of: sessionState?.toolbarState.safeModeLevel) { _, newLevel in
if let level = newLevel {
AppState.shared.safeModeLevel = level
}
}
}
// MARK: - View Components
@ViewBuilder
private var mainContent: some View {
NavigationSplitView(columnVisibility: $columnVisibility) {
// MARK: - Sidebar (Left) - Table Browser
if let currentSession = currentSession, let sessionState {
VStack(spacing: 0) {
SidebarView(
tables: sessionTablesBinding,
sidebarState: SharedSidebarState.forConnection(currentSession.connection.id),
activeTableName: windowTitle,
onDoubleClick: { table in
let isView = table.type == .view
if let preview = WindowLifecycleMonitor.shared.previewWindow(for: currentSession.connection.id),
let previewCoordinator = MainContentCoordinator.coordinator(for: preview.windowId) {
// If the preview tab shows this table, promote it
if previewCoordinator.tabManager.selectedTab?.tableName == table.name {
previewCoordinator.promotePreviewTab()
} else {
// Preview shows a different table — promote it first, then open this table permanently
previewCoordinator.promotePreviewTab()
sessionState.coordinator.openTableTab(table.name, isView: isView)
}
} else {
// No preview tab — promote current if it's a preview, otherwise open permanently
sessionState.coordinator.promotePreviewTab()
sessionState.coordinator.openTableTab(table.name, isView: isView)
}
},
pendingTruncates: sessionPendingTruncatesBinding,
pendingDeletes: sessionPendingDeletesBinding,
tableOperationOptions: sessionTableOperationOptionsBinding,
databaseType: currentSession.connection.type,
connectionId: currentSession.connection.id,
schemaProvider: SchemaProviderRegistry.shared.provider(for: currentSession.connection.id),
coordinator: sessionState.coordinator
)
}
.searchable(
text: sidebarSearchTextBinding(for: currentSession.connection.id),
placement: .sidebar,
prompt: sidebarSearchPrompt(for: currentSession.connection.id)
)
.navigationSplitViewColumnWidth(min: 200, ideal: 250, max: 600)
} else {
Color.clear
.navigationSplitViewColumnWidth(min: 200, ideal: 250, max: 600)
}
} detail: {
// MARK: - Detail (Main workspace with optional right sidebar)
if let currentSession = currentSession, let rightPanelState, let sessionState {
HorizontalSplitView(
isTrailingCollapsed: !rightPanelState.isPresented,
trailingWidth: Bindable(rightPanelState).panelWidth,
minTrailingWidth: RightPanelState.minWidth,
maxTrailingWidth: RightPanelState.maxWidth,
autosaveName: "InspectorSplit"
) {
MainContentView(
connection: currentSession.connection,
payload: payload,
windowTitle: $windowTitle,
tables: sessionTablesBinding,
sidebarState: SharedSidebarState.forConnection(currentSession.connection.id),
pendingTruncates: sessionPendingTruncatesBinding,
pendingDeletes: sessionPendingDeletesBinding,
tableOperationOptions: sessionTableOperationOptionsBinding,
inspectorContext: $inspectorContext,
rightPanelState: rightPanelState,
tabManager: sessionState.tabManager,
changeManager: sessionState.changeManager,
filterStateManager: sessionState.filterStateManager,
toolbarState: sessionState.toolbarState,
coordinator: sessionState.coordinator
)
} trailing: {
UnifiedRightPanelView(
state: rightPanelState,
inspectorContext: inspectorContext,
connection: currentSession.connection,
tables: currentSession.tables
)
.background(Color(nsColor: .windowBackgroundColor))
}
} else {
VStack(spacing: 16) {
ProgressView()
.scaleEffect(1.5)
Text("Connecting...")
.font(.headline)
.foregroundStyle(.secondary)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
}
}
.navigationTitle(windowTitle)
.navigationSubtitle(currentSession?.connection.name ?? "")
}
// MARK: - Session State Bindings
/// Generic helper to create bindings that update session state
private func createSessionBinding<T>(
get: @escaping (ConnectionSession) -> T,
set: @escaping (inout ConnectionSession, T) -> Void,
defaultValue: T
) -> Binding<T> {
Binding(
get: {
guard let session = currentSession else {
return defaultValue
}
return get(session)
},
set: { newValue in
guard let sessionId = payload?.connectionId ?? currentSession?.id else { return }
Task { @MainActor in
DatabaseManager.shared.updateSession(sessionId) { session in
set(&session, newValue)
}
}
}
)
}
private var sessionTablesBinding: Binding<[TableInfo]> {
createSessionBinding(
get: { $0.tables },
set: { $0.tables = $1 },
defaultValue: []
)
}
private var sessionPendingTruncatesBinding: Binding<Set<String>> {
createSessionBinding(
get: { $0.pendingTruncates },
set: { $0.pendingTruncates = $1 },
defaultValue: []
)
}
private var sessionPendingDeletesBinding: Binding<Set<String>> {
createSessionBinding(
get: { $0.pendingDeletes },
set: { $0.pendingDeletes = $1 },
defaultValue: []
)
}
private func sidebarSearchTextBinding(for connectionId: UUID) -> Binding<String> {
let state = SharedSidebarState.forConnection(connectionId)
return Binding(
get: { state.searchText },
set: { state.searchText = $0 }
)
}
private func sidebarSearchPrompt(for connectionId: UUID) -> String {
let state = SharedSidebarState.forConnection(connectionId)
switch state.selectedSidebarTab {
case .tables:
return String(localized: "Filter")
case .favorites:
return String(localized: "Filter favorites")
}
}
private var sessionTableOperationOptionsBinding: Binding<[String: TableOperationOptions]> {
createSessionBinding(
get: { $0.tableOperationOptions },
set: { $0.tableOperationOptions = $1 },
defaultValue: [:]
)
}
// MARK: - Connection Status
private func handleConnectionStatusChange() {
guard closingSessionId == nil else {
return
}
let sessions = DatabaseManager.shared.activeSessions
let connectionId = payload?.connectionId ?? currentSession?.id ?? DatabaseManager.shared.currentSessionId
guard let sid = connectionId else {
if currentSession != nil { currentSession = nil }
return
}
guard let newSession = sessions[sid] else {
if currentSession?.id == sid {
closingSessionId = sid
rightPanelState?.teardown()
rightPanelState = nil
sessionState?.coordinator.teardown()
sessionState = nil
currentSession = nil
columnVisibility = .detailOnly
AppState.shared.isConnected = false
AppState.shared.safeModeLevel = .silent
AppState.shared.editorLanguage = .sql
AppState.shared.currentDatabaseType = nil
AppState.shared.supportsDatabaseSwitching = true
// Window cleanup is handled by windowWillClose (opens welcome)
// and windowDidBecomeKey (hides restored orphan windows).
// Do NOT close windows here — it triggers SwiftUI state
// restoration which creates an infinite close→restore loop.
}
return
}
if let existing = currentSession,
existing.isContentViewEquivalent(to: newSession) {
return
}
currentSession = newSession
// Update window title on first session connect (fixes cold-launch stale title)
if payload?.tableName == nil, windowTitle == "SQL Query" || windowTitle.hasSuffix(" Query") {
windowTitle = newSession.connection.name
}
if rightPanelState == nil {
rightPanelState = RightPanelState()
}
if sessionState == nil {
sessionState = SessionStateFactory.create(
connection: newSession.connection,
payload: payload
)
}
AppState.shared.isConnected = true
AppState.shared.safeModeLevel = newSession.connection.safeModeLevel
AppState.shared.editorLanguage = PluginManager.shared.editorLanguage(for: newSession.connection.type)
AppState.shared.currentDatabaseType = newSession.connection.type
AppState.shared.supportsDatabaseSwitching = PluginManager.shared.supportsDatabaseSwitching(
for: newSession.connection.type)
}
// MARK: - Actions
private func connectToDatabase(_ connection: DatabaseConnection) {
Task {
do {
try await DatabaseManager.shared.connectToSession(connection)
} catch {
Self.logger.error("Failed to connect: \(error.localizedDescription)")
}
}
}
private func handleCloseSession(_ sessionId: UUID) {
Task {
await DatabaseManager.shared.disconnectSession(sessionId)
}
}
// MARK: - Persistence
private func deleteConnection(_ connection: DatabaseConnection) {
if DatabaseManager.shared.activeSessions[connection.id] != nil {
Task {
await DatabaseManager.shared.disconnectSession(connection.id)
}
}
storage.deleteConnection(connection)
}
}
#Preview {
ContentView(payload: nil)
}