From 2f2682e73c3239565141907ee4868f0a17797251 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Tue, 3 Nov 2026 11:19:11 +0700 Subject: [PATCH 01/13] refactor(ui): tint only status symbols and drop hand-drawn notice fills, dots and chips --- .../Models/Database/DatabaseMetadata.swift | 6 - .../Theme/MaterialAccessibility.swift | 4 +- .../Views/AIChat/AIChatContextChipView.swift | 24 +--- .../AIChat/AIChatWalkthroughBlockView.swift | 28 ++-- .../Views/Compare/CompareApplySheetView.swift | 20 +-- .../Views/Compare/CompareDataPlansView.swift | 3 +- .../Views/Compare/CompareDetailView.swift | 5 +- .../Views/Compare/CompareProgressView.swift | 18 +-- .../Views/Compare/CompareRowDiffPane.swift | 6 +- .../Views/Compare/CompareScriptPane.swift | 3 +- .../Compare/CompareTableScopeEditor.swift | 3 +- .../Components/DatabaseEndpointPicker.swift | 16 ++- .../Views/Components/NoticeLabel.swift | 60 ++++++++ .../Views/Components/NumberEntryPopover.swift | 12 +- .../Views/Components/PaneNoticeBar.swift | 129 ++++++++++++++++++ .../TablePro/Views/Components/TypeBadge.swift | 10 +- .../ConnectionExportOptionsSheet.swift | 3 +- .../Connection/ConnectionImportSheet.swift | 3 +- .../Connection/ConnectionWarningBanner.swift | 55 ++------ .../Connection/DeeplinkImportSheet.swift | 24 ++-- .../Views/Connection/GroupEditorSheet.swift | 4 +- .../Import/ImportConnectionRowView.swift | 9 +- .../Import/ImportQueryRowView.swift | 3 +- .../Connection/Import/ImportReviewStep.swift | 8 +- .../AWSDiscoveryConfigurationStep.swift | 6 +- .../Views/Connection/PasswordSourceTest.swift | 3 +- .../Connection/SSHProfileEditorView.swift | 9 +- .../Components/CredentialProfilePicker.swift | 8 +- .../Components/ImportFromURLSheet.swift | 3 +- .../Panes/GeneralPaneView.swift | 43 ++---- .../ConnectionForm/Panes/SSLSections.swift | 3 +- .../CloudSQLProxyTransportSections.swift | 8 +- .../CloudflareTransportSections.swift | 8 +- .../Panes/Transports/SSHServerSections.swift | 6 +- .../Transports/SSHTransportSections.swift | 11 +- .../Views/DataGrid/DataGridFindBar.swift | 2 +- .../CreateDatabaseSheet.swift | 27 ++-- .../DatabaseSwitcher/SchemaEditorSheet.swift | 14 +- .../Editor/History/HistoryDetailPane.swift | 16 ++- .../Editor/QueryParameterPanelView.swift | 12 +- .../Editor/SourceFileDiskChangeBanner.swift | 36 +---- .../TablePro/Views/Export/ExportDialog.swift | 7 +- .../Views/Export/ExportRowScopeEditor.swift | 3 +- .../Export/TableTransferMappingEditor.swift | 4 +- .../Views/Export/TableTransferSheet.swift | 31 +++-- .../Views/Import/RowImportBatchSheet.swift | 5 +- .../Views/Import/RowImportSheet.swift | 3 +- .../IntegrationsActivityLogPane.swift | 8 +- .../IntegrationsConnectedClientsPane.swift | 6 +- .../Integrations/IntegrationsFormatting.swift | 2 +- .../Main/Child/DocumentEditorSheet.swift | 4 +- .../Main/Child/MainEditorContentView.swift | 12 -- .../ObjectCopy/CopyObjectsReviewView.swift | 10 +- .../Views/ObjectCopy/CopyObjectsSheet.swift | 10 +- .../ObjectSource/ObjectSourceTabView.swift | 5 +- .../UserType/CreateUserTypeSheet.swift | 9 +- .../UserType/UserTypeMemberSheet.swift | 4 +- .../UserType/UserTypePendingChangesView.swift | 21 ++- .../UserType/UserTypeTabView.swift | 5 +- .../QueryInsightsActivityChart.swift | 112 +++++++-------- .../QueryInsightsGroupList.swift | 24 ++-- .../QueryInsightsSummaryBar.swift | 36 ++--- .../QueryInsights/QueryInsightsView.swift | 15 +- .../QuickSwitcherPanelView.swift | 6 +- .../QuickSwitcherRowChrome.swift | 12 +- .../Views/Results/ColumnJumpPanelView.swift | 6 +- .../Views/Results/ForeignKeyPickerView.swift | 14 +- .../Views/Results/ForeignKeyPreviewView.swift | 14 +- .../Views/Results/HexEditorContentView.swift | 5 +- .../Views/Results/InlineErrorBanner.swift | 43 ++---- .../TreeOutlineAccessoryViews.swift | 20 +-- .../FieldEditors/BlobHexEditorView.swift | 5 +- .../FieldEditors/JsonEditorView.swift | 56 ++++---- .../FieldEditors/MultiLineEditorView.swift | 57 ++++---- .../ServerDashboard/DashboardTileView.swift | 22 +-- .../DashboardToolbarView.swift | 6 +- .../ServerDashboard/MetricsBarView.swift | 45 +++--- .../ServerDashboard/SessionsTableView.swift | 6 +- .../ServerDashboard/SlowQueryListView.swift | 6 +- .../Settings/Appearance/ThemeEditorView.swift | 4 +- .../Appearance/ThemeLibrarySection.swift | 4 +- .../IntegrationStatusIndicator.swift | 6 +- .../Settings/CustomSlashCommandsSection.swift | 3 +- .../CredentialProfileEditorSheet.swift | 17 +-- .../Settings/Sections/DataGridSection.swift | 6 +- .../Sections/MCPOutsideServerSheet.swift | 6 +- .../Sections/PairingApprovalSheet.swift | 2 +- .../Views/Shared/FieldDrivenList.swift | 52 +------ .../Views/Shared/FieldDrivenListEntry.swift | 24 ++-- .../Views/Sidebar/EditSequenceSheet.swift | 4 +- .../Views/Sidebar/FavoriteEditDialog.swift | 6 +- .../Views/Sidebar/FavoriteRowView.swift | 4 - .../LinkedFavoriteMetadataDialog.swift | 28 +--- .../Views/Sidebar/LinkedFavoriteRowView.swift | 5 +- .../Sidebar/LinkedFolderCommitSheet.swift | 4 +- .../Views/Sidebar/ObjectCommentSheet.swift | 10 +- .../Views/Sidebar/SetSequenceValueSheet.swift | 4 +- .../Structure/CreateTableFormFieldRow.swift | 3 +- .../StructureTablePropertiesView.swift | 4 +- .../Views/Structure/TriggerEditorView.swift | 6 +- .../Views/UsersRoles/UsersRolesSheets.swift | 6 +- .../Views/FieldDrivenListEntryTests.swift | 17 --- .../ConnectionSwitcherFilterTests.swift | 15 -- 103 files changed, 747 insertions(+), 823 deletions(-) create mode 100644 apple/TablePro/Views/Components/NoticeLabel.swift create mode 100644 apple/TablePro/Views/Components/PaneNoticeBar.swift diff --git a/apple/TablePro/Models/Database/DatabaseMetadata.swift b/apple/TablePro/Models/Database/DatabaseMetadata.swift index 6e7c4e750a..176a98cccc 100644 --- a/apple/TablePro/Models/Database/DatabaseMetadata.swift +++ b/apple/TablePro/Models/Database/DatabaseMetadata.swift @@ -18,12 +18,6 @@ struct DatabaseMetadata: Identifiable, Equatable { let isSystemDatabase: Bool // Whether this is a system database (mysql, information_schema, etc.) let icon: String // SF Symbol name for icon - /// Formatted size string (e.g., "14.2 MB") - var formattedSize: String { - guard let bytes = sizeBytes else { return "—" } - return ByteCountFormatter.string(fromByteCount: bytes, countStyle: .file) - } - /// Relative time string (e.g., "2 hours ago", "just now") var relativeAccessTime: String { guard let accessed = lastAccessed else { return "never" } diff --git a/apple/TablePro/Theme/MaterialAccessibility.swift b/apple/TablePro/Theme/MaterialAccessibility.swift index e185645a2b..ada488a4cb 100644 --- a/apple/TablePro/Theme/MaterialAccessibility.swift +++ b/apple/TablePro/Theme/MaterialAccessibility.swift @@ -1,14 +1,12 @@ import SwiftUI internal enum MaterialRole { - case banner case toolbar - case inlineControl case scrim var solidFallback: Color { switch self { - case .banner, .toolbar, .inlineControl: + case .toolbar: Color(nsColor: .controlBackgroundColor) case .scrim: Color(nsColor: .windowBackgroundColor) diff --git a/apple/TablePro/Views/AIChat/AIChatContextChipView.swift b/apple/TablePro/Views/AIChat/AIChatContextChipView.swift index 1cfeae5ed6..7c2ba14d27 100644 --- a/apple/TablePro/Views/AIChat/AIChatContextChipView.swift +++ b/apple/TablePro/Views/AIChat/AIChatContextChipView.swift @@ -10,31 +10,19 @@ struct AIChatContextChipView: View { var onRemove: (() -> Void)? var body: some View { - HStack(spacing: 4) { - Image(systemName: item.symbolName) - .font(.caption2) - Text(item.displayLabel) + HStack(spacing: 2) { + Label(item.displayLabel, systemImage: item.symbolName) .font(.caption) .lineLimit(1) .truncationMode(.middle) if let onRemove { - Button(action: onRemove) { - Image(systemName: "xmark") - .font(.caption2.weight(.semibold)) - } - .buttonStyle(.plain) - .foregroundStyle(.secondary) - .accessibilityLabel(String(localized: "Remove attachment")) + Button(String(localized: "Remove attachment"), systemImage: "xmark", action: onRemove) + .labelStyle(.iconOnly) + .buttonStyle(.borderless) + .controlSize(.small) } } - .padding(.horizontal, 8) - .padding(.vertical, 4) - .background(.tint.opacity(0.08), in: Capsule()) - .overlay( - Capsule() - .stroke(.tint.opacity(0.2), lineWidth: 0.5) - ) .help(item.helpText ?? item.displayLabel) } } diff --git a/apple/TablePro/Views/AIChat/AIChatWalkthroughBlockView.swift b/apple/TablePro/Views/AIChat/AIChatWalkthroughBlockView.swift index f417403b01..8b7c1e00ab 100644 --- a/apple/TablePro/Views/AIChat/AIChatWalkthroughBlockView.swift +++ b/apple/TablePro/Views/AIChat/AIChatWalkthroughBlockView.swift @@ -538,15 +538,19 @@ struct AIChatWalkthroughBlockView: View { private struct ImportancePillView: View { let importance: SqlWalkthroughImportance + // A critical step carries the one symbol; the others read as plain secondary text. var body: some View { - Text(label) - .font(.caption2) - .padding(.horizontal, 5) - .padding(.vertical, 2) - .background(color.opacity(0.15)) - .foregroundStyle(color) - .clipShape(Capsule()) - .accessibilityLabel(Text(verbatim: "\(String(localized: "Importance")): \(label)")) + Group { + if importance == .critical { + NoticeLabel(label, severity: .error) + } else { + Text(label) + .foregroundStyle(.secondary) + } + } + .font(.caption2) + .accessibilityElement(children: .ignore) + .accessibilityLabel(Text(verbatim: "\(String(localized: "Importance")): \(label)")) } private var label: String { @@ -556,12 +560,4 @@ private struct ImportancePillView: View { case .context: String(localized: "Context") } } - - private var color: Color { - switch importance { - case .critical: .red - case .normal: .accentColor - case .context: .secondary - } - } } diff --git a/apple/TablePro/Views/Compare/CompareApplySheetView.swift b/apple/TablePro/Views/Compare/CompareApplySheetView.swift index fba6d1f2f5..a0c6aa2c25 100644 --- a/apple/TablePro/Views/Compare/CompareApplySheetView.swift +++ b/apple/TablePro/Views/Compare/CompareApplySheetView.swift @@ -158,11 +158,12 @@ internal struct CompareApplySheetView: View { if session.unacknowledgedHazardCount > 0 { Label { Text(heldBackText) + .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) } icon: { Image(systemName: "hand.raised.fill") + .foregroundStyle(CompareStatusStyle.warning) } - .foregroundStyle(CompareStatusStyle.warning) } } .frame(maxWidth: .infinity, alignment: .leading) @@ -252,11 +253,12 @@ internal struct CompareApplySheetView: View { ), commitFailure )) + .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) } icon: { Image(systemName: "exclamationmark.octagon.fill") + .foregroundStyle(CompareStatusStyle.error) } - .foregroundStyle(CompareStatusStyle.error) } if result.cancelled { @@ -289,7 +291,7 @@ internal struct CompareApplySheetView: View { if let error = outcome.error { RevealedTextView(error) .font(.caption) - .foregroundStyle(CompareStatusStyle.error) + .foregroundStyle(.secondary) .textSelection(.enabled) .fixedSize(horizontal: false, vertical: true) } @@ -373,9 +375,7 @@ internal struct CompareApplySheetView: View { .padding(.vertical, 2) } - /// Only a statement the classifier refuses by default has an allowance to grant. A hazard that - /// runs anyway gets a label rather than a checkbox, because a checkbox that cannot stop it would - /// say the opposite of what it does. + // A hazard that runs anyway gets a label, not a checkbox: a checkbox that cannot stop it would say the opposite. @ViewBuilder private func hazardHeadline(_ statement: SyncStatement) -> some View { if statement.isRefusedByDefault { @@ -393,8 +393,8 @@ internal struct CompareApplySheetView: View { .lineLimit(1) } icon: { Image(systemName: "play.circle.fill") + .foregroundStyle(CompareStatusStyle.warning) } - .foregroundStyle(CompareStatusStyle.warning) } } @@ -405,12 +405,13 @@ internal struct CompareApplySheetView: View { if session.unacknowledgedHazardCount > 0 { Label { Text("Allow every held-back statement on the Warnings tab, or exclude the objects that produced them, before applying.") + .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) } icon: { Image(systemName: "hand.raised.fill") + .foregroundStyle(CompareStatusStyle.warning) } .font(.callout) - .foregroundStyle(CompareStatusStyle.warning) } Spacer(minLength: 0) Button("Cancel") { @@ -450,11 +451,12 @@ internal struct CompareApplySheetView: View { private func noticeLabel(_ text: String, systemImage: String) -> some View { Label { Text(text) + .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) } icon: { Image(systemName: systemImage) + .foregroundStyle(CompareStatusStyle.warning) } .font(.callout) - .foregroundStyle(CompareStatusStyle.warning) } } diff --git a/apple/TablePro/Views/Compare/CompareDataPlansView.swift b/apple/TablePro/Views/Compare/CompareDataPlansView.swift index 72ef721687..4b47273255 100644 --- a/apple/TablePro/Views/Compare/CompareDataPlansView.swift +++ b/apple/TablePro/Views/Compare/CompareDataPlansView.swift @@ -256,11 +256,12 @@ if #available(macOS 14.0, *) { if let reason = plan.unavailableReason ?? plan.comparisonFailure { Label { Text(reason) + .foregroundStyle(.secondary) .lineLimit(1) } icon: { Image(systemName: "exclamationmark.triangle.fill") + .selectionAwareTint(differentiateWithoutColor ? .primary : CompareStatusStyle.warning) } - .foregroundStyle(differentiateWithoutColor ? .primary : CompareStatusStyle.warning) .help(reason) } else { Text(plan.keyColumns.joined(separator: ", ")) diff --git a/apple/TablePro/Views/Compare/CompareDetailView.swift b/apple/TablePro/Views/Compare/CompareDetailView.swift index 4b8d88cb90..05d1c0c403 100644 --- a/apple/TablePro/Views/Compare/CompareDetailView.swift +++ b/apple/TablePro/Views/Compare/CompareDetailView.swift @@ -81,11 +81,12 @@ internal struct CompareDefinitionsPane: View { if let error = result.comparisonError { Label { RevealedTextView(error) + .foregroundStyle(.secondary) .textSelection(.enabled) } icon: { Image(systemName: "exclamationmark.triangle.fill") + .foregroundStyle(CompareStatusStyle.warning) } - .foregroundStyle(CompareStatusStyle.warning) .fixedSize(horizontal: false, vertical: true) } @@ -124,8 +125,8 @@ internal struct CompareDefinitionsPane: View { .textSelection(.enabled) } icon: { Image(systemName: change.isDestructive ? "exclamationmark.triangle.fill" : "pencil") + .foregroundStyle(changeTint(change)) } - .foregroundStyle(changeTint(change)) .font(.callout) .fixedSize(horizontal: false, vertical: true) } diff --git a/apple/TablePro/Views/Compare/CompareProgressView.swift b/apple/TablePro/Views/Compare/CompareProgressView.swift index b4984522e7..ae118f4537 100644 --- a/apple/TablePro/Views/Compare/CompareProgressView.swift +++ b/apple/TablePro/Views/Compare/CompareProgressView.swift @@ -69,24 +69,18 @@ internal struct CompareProgressView: View { private func messageLabel(_ text: String, systemImage: String, tint: Color) -> some View { Label { RevealedTextView(text) + .foregroundStyle(.secondary) .textSelection(.enabled) .fixedSize(horizontal: false, vertical: true) } icon: { Image(systemName: systemImage) + .foregroundStyle(tint) } .font(.callout) - .foregroundStyle(tint) } } -/// Every error and notice the session raises, at the top of the pane the user is already reading. -/// -/// A message is set exactly when work stops, so anything that renders one only while the session is -/// busy renders it never: a failed comparison, a capability refusal, a cross-engine warning, a -/// cancelled run, a denied Apply authorization and "Nothing is selected to apply." all produced no -/// output at all. It is inline rather than an alert because the HIG reserves an alert for a -/// situation the user must resolve before continuing and allows one at a time, and a restored -/// window can raise several at once. +// Inline rather than an alert: a message is set when work stops, and a restored window can raise several at once. internal struct CompareMessageBanner: View { @ObservedObject internal var session: CompareSyncSession @@ -96,8 +90,7 @@ internal struct CompareMessageBanner: View { if session.errorMessage != nil || session.informationalMessage != nil || session.setupErrorMessage != nil { VStack(alignment: .leading, spacing: 6) { - /// A problem with the setup rather than with a comparison, so it outlives the reset - /// that changing the setup performs and is dismissed on its own. + // A setup problem outlives the reset a setup change performs, so it is dismissed on its own. if let message = session.setupErrorMessage { messageRow( message, @@ -147,12 +140,13 @@ internal struct CompareMessageBanner: View { HStack(alignment: .firstTextBaseline, spacing: 8) { Label { RevealedTextView(text) + .foregroundStyle(.secondary) .textSelection(.enabled) .fixedSize(horizontal: false, vertical: true) } icon: { Image(systemName: systemImage) + .foregroundStyle(differentiateWithoutColor ? Color.primary : tint) } - .foregroundStyle(differentiateWithoutColor ? Color.primary : tint) Spacer(minLength: 0) diff --git a/apple/TablePro/Views/Compare/CompareRowDiffPane.swift b/apple/TablePro/Views/Compare/CompareRowDiffPane.swift index 325a195137..542c2d52e9 100644 --- a/apple/TablePro/Views/Compare/CompareRowDiffPane.swift +++ b/apple/TablePro/Views/Compare/CompareRowDiffPane.swift @@ -169,11 +169,12 @@ internal struct CompareRowDiffPane: View { HStack(spacing: 8) { Label { Text("Some included tables have not been compared with their current settings.") + .foregroundStyle(.secondary) } icon: { Image(systemName: "exclamationmark.arrow.circlepath") + .foregroundStyle(CompareStatusStyle.warning) } .font(.callout) - .foregroundStyle(CompareStatusStyle.warning) .fixedSize(horizontal: false, vertical: true) Spacer(minLength: 0) Button("Compare", action: onCompare) @@ -259,11 +260,12 @@ internal struct CompareRowDiffPane: View { private func notice(_ text: String, systemImage: String) -> some View { Label { Text(text) + .foregroundStyle(.secondary) } icon: { Image(systemName: systemImage) + .foregroundStyle(CompareStatusStyle.warning) } .font(.callout) - .foregroundStyle(CompareStatusStyle.warning) .fixedSize(horizontal: false, vertical: true) .frame(maxWidth: .infinity, alignment: .leading) .padding(.horizontal, 12) diff --git a/apple/TablePro/Views/Compare/CompareScriptPane.swift b/apple/TablePro/Views/Compare/CompareScriptPane.swift index 6b91ebc8f2..27e65ee2cd 100644 --- a/apple/TablePro/Views/Compare/CompareScriptPane.swift +++ b/apple/TablePro/Views/Compare/CompareScriptPane.swift @@ -71,11 +71,12 @@ internal struct CompareScriptPane: View { if !heldBackStatements.isEmpty { Label { Text(heldBackSummary) + .foregroundStyle(.secondary) } icon: { Image(systemName: "hand.raised.fill") + .foregroundStyle(CompareStatusStyle.warning) } .font(.callout) - .foregroundStyle(CompareStatusStyle.warning) } Spacer(minLength: 0) Button("Copy") { diff --git a/apple/TablePro/Views/Compare/CompareTableScopeEditor.swift b/apple/TablePro/Views/Compare/CompareTableScopeEditor.swift index 3624e9e4d0..8b2bc61e46 100644 --- a/apple/TablePro/Views/Compare/CompareTableScopeEditor.swift +++ b/apple/TablePro/Views/Compare/CompareTableScopeEditor.swift @@ -74,11 +74,12 @@ internal struct CompareTableScopeEditor: View { ) { Label { Text(error) + .foregroundStyle(.secondary) } icon: { Image(systemName: "exclamationmark.triangle.fill") + .foregroundStyle(CompareStatusStyle.warning) } .font(.callout) - .foregroundStyle(CompareStatusStyle.warning) .fixedSize(horizontal: false, vertical: true) } diff --git a/apple/TablePro/Views/Components/DatabaseEndpointPicker.swift b/apple/TablePro/Views/Components/DatabaseEndpointPicker.swift index f81bc6817a..238cfb4538 100644 --- a/apple/TablePro/Views/Components/DatabaseEndpointPicker.swift +++ b/apple/TablePro/Views/Components/DatabaseEndpointPicker.swift @@ -152,7 +152,8 @@ internal struct DatabaseEndpointPicker: View { .foregroundStyle(.secondary) } } icon: { - swatch(connection.color) + swatch(connection) + .opacity(0.5) } .foregroundStyle(.tertiary) } else { @@ -160,7 +161,7 @@ internal struct DatabaseEndpointPicker: View { Label { Text(connection.name) } icon: { - swatch(connection.color) + swatch(connection) } } } @@ -318,10 +319,13 @@ internal struct DatabaseEndpointPicker: View { } } - private func swatch(_ color: ConnectionColor) -> some View { - Circle() - .fill(color == .none ? Color.secondary.opacity(0.35) : color.color) - .frame(width: 10, height: 10) + private func swatch(_ connection: DatabaseConnection) -> some View { + ConnectionTile( + type: connection.type, + iconName: connection.iconName, + identityColor: connection.identityColor, + size: 16 + ) } private func label(_ database: String, _ connection: DatabaseConnection) -> String { diff --git a/apple/TablePro/Views/Components/NoticeLabel.swift b/apple/TablePro/Views/Components/NoticeLabel.swift new file mode 100644 index 0000000000..0656e26c4c --- /dev/null +++ b/apple/TablePro/Views/Components/NoticeLabel.swift @@ -0,0 +1,60 @@ +// +// NoticeLabel.swift +// TablePro +// + +import SwiftUI + +internal enum NoticeSeverity: Equatable, Sendable { + case warning + case error + case success + + internal var symbolName: String { + switch self { + case .warning, .error: "exclamationmark.triangle.fill" + case .success: "checkmark.circle.fill" + } + } + + internal var tint: Color { + switch self { + case .warning: .orange + case .error: .red + case .success: .green + } + } +} + +// A status line in a form, a sheet or a popover: the hue goes on the symbol only and the words stay +// secondary, so a warning never turns into colored text. +internal struct NoticeLabel: View { + let text: String + var severity: NoticeSeverity = .warning + + init(_ text: String, severity: NoticeSeverity = .warning) { + self.text = text + self.severity = severity + } + + var body: some View { + Label { + Text(verbatim: text) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } icon: { + Image(systemName: severity.symbolName) + .foregroundStyle(severity.tint) + .accessibilityHidden(true) + } + } +} + +#Preview { + VStack(alignment: .leading, spacing: 8) { + NoticeLabel("Passwords do not match.", severity: .error) + NoticeLabel("The server certificate is not verified.") + NoticeLabel("Connection successful", severity: .success) + } + .padding() +} diff --git a/apple/TablePro/Views/Components/NumberEntryPopover.swift b/apple/TablePro/Views/Components/NumberEntryPopover.swift index c7e9744197..930b35e34e 100644 --- a/apple/TablePro/Views/Components/NumberEntryPopover.swift +++ b/apple/TablePro/Views/Components/NumberEntryPopover.swift @@ -38,9 +38,15 @@ struct NumberEntryPopover: View { .keyboardShortcut(.defaultAction) .disabled(!isValid) } - Text(rangeHint) - .font(.caption2) - .foregroundStyle(isValid ? .secondary : Color.red) + Group { + if isValid { + Text(rangeHint) + .foregroundStyle(.secondary) + } else { + NoticeLabel(rangeHint, severity: .error) + } + } + .font(.caption2) } .padding(12) .onAppear { isFocused.wrappedValue = true } diff --git a/apple/TablePro/Views/Components/PaneNoticeBar.swift b/apple/TablePro/Views/Components/PaneNoticeBar.swift new file mode 100644 index 0000000000..3aa44ec28b --- /dev/null +++ b/apple/TablePro/Views/Components/PaneNoticeBar.swift @@ -0,0 +1,129 @@ +// +// PaneNoticeBar.swift +// TablePro +// + +import SwiftUI + +// The one shape for a notice over a pane, as the transaction and recovery bars draw it: color only on +// the symbol, small stock buttons, the pane bar material. A sheet passes `onBar: false`, since a bar +// material inside a sheet reads as a stray band. +internal struct PaneNoticeBar: View { + let severity: NoticeSeverity + var alignment: VerticalAlignment = .center + var onBar = true + var dismissLabel = String(localized: "Dismiss") + var onDismiss: (() -> Void)? + @ViewBuilder let content: Content + @ViewBuilder let actions: Actions + + var body: some View { + let bar = HStack(alignment: alignment, spacing: 10) { + HStack(alignment: alignment, spacing: 8) { + Image(systemName: severity.symbolName) + .foregroundStyle(severity.tint) + .accessibilityHidden(true) + content + .frame(maxWidth: .infinity, alignment: .leading) + } + actions + if let onDismiss { + Button(dismissLabel, systemImage: "xmark", action: onDismiss) + .labelStyle(.iconOnly) + .buttonStyle(.borderless) + .help(dismissLabel) + } + } + .controlSize(.small) + .padding(.horizontal, 12) + .padding(.vertical, 6) + + if onBar { + bar.paneBarBackground() + } else { + bar + } + } +} + +internal extension PaneNoticeBar where Actions == EmptyView { + init( + severity: NoticeSeverity, + alignment: VerticalAlignment = .center, + onBar: Bool = true, + dismissLabel: String = String(localized: "Dismiss"), + onDismiss: (() -> Void)? = nil, + @ViewBuilder content: () -> Content + ) { + self.init( + severity: severity, + alignment: alignment, + onBar: onBar, + dismissLabel: dismissLabel, + onDismiss: onDismiss, + content: content, + actions: { EmptyView() } + ) + } +} + +// A title over a secondary detail, the text block every pane notice shows. +internal struct PaneNoticeText: View { + let title: String + var detail: String? + var detailLineLimit = 1 + + var body: some View { + VStack(alignment: .leading, spacing: 1) { + Text(title) + .font(.callout.weight(.semibold)) + .lineLimit(1) + if let detail, !detail.isEmpty { + Text(detail) + .font(.callout) + .foregroundStyle(.secondary) + .lineLimit(detailLineLimit) + .truncationMode(.tail) + .fixedSize(horizontal: false, vertical: true) + .textSelection(.enabled) + .help(detail) + } + } + } +} + +// Copies the notice's text. The pasteboard change is the feedback; VoiceOver hears it said. +internal struct PaneNoticeCopyButton: View { + let text: String + let label: String + + var body: some View { + Button(label, systemImage: "doc.on.doc") { + ClipboardService.shared.writeText(text) + AccessibilityAnnouncement.post(String(localized: "Copied to clipboard")) + } + .labelStyle(.iconOnly) + .buttonStyle(.borderless) + .help(label) + } +} + +#Preview { + VStack(spacing: 0) { + PaneNoticeBar(severity: .warning, onDismiss: {}) { + PaneNoticeText(title: "Connected with a warning", detail: "ORA-28002: the password will expire within 7 days") + } actions: { + PaneNoticeCopyButton(text: "ORA-28002", label: "Copy Warning") + } + Divider() + PaneNoticeBar(severity: .error, onDismiss: {}) { + Text("near \"Album\": syntax error") + .font(.callout) + } actions: { + Button("Fix with AI") {} + } + Divider() + Spacer() + } + .frame(width: 640, height: 200) +} diff --git a/apple/TablePro/Views/Components/TypeBadge.swift b/apple/TablePro/Views/Components/TypeBadge.swift index 37fb608dda..683e0c9b77 100644 --- a/apple/TablePro/Views/Components/TypeBadge.swift +++ b/apple/TablePro/Views/Components/TypeBadge.swift @@ -14,19 +14,13 @@ struct TypeBadge: View { self.accessibilityDescription = accessibilityDescription } - /// The badge keeps its one line and its measured width whatever it is put next to. Without this - /// a compressed `HStack` wraps the text inside the capsule instead of giving way: at the - /// inspector's 270pt minimum, a long column name squeezed "date" into "dat" over "e" and grew - /// the row by 11pt. + // Fixed width: at the inspector's 270pt minimum a compressed HStack wrapped "date" over two lines. var body: some View { Text(label) - .font(.caption2.weight(.medium)) + .font(.caption2) .foregroundStyle(.tertiary) .lineLimit(1) .fixedSize(horizontal: true, vertical: false) - .padding(.horizontal, 6) - .padding(.vertical, 1) - .background(.quaternary, in: Capsule()) .accessibilityLabel(Text("Type: \(accessibilityDescription ?? label)")) } } diff --git a/apple/TablePro/Views/Connection/ConnectionExportOptionsSheet.swift b/apple/TablePro/Views/Connection/ConnectionExportOptionsSheet.swift index d84d125e79..a79aa275e5 100644 --- a/apple/TablePro/Views/Connection/ConnectionExportOptionsSheet.swift +++ b/apple/TablePro/Views/Connection/ConnectionExportOptionsSheet.swift @@ -210,9 +210,8 @@ struct ConnectionExportOptionsSheet: View { } private func warningLabel(_ text: String) -> some View { - Label(text, systemImage: "exclamationmark.triangle.fill") + NoticeLabel(text) .font(.caption) - .foregroundStyle(.orange) } private var footer: some View { diff --git a/apple/TablePro/Views/Connection/ConnectionImportSheet.swift b/apple/TablePro/Views/Connection/ConnectionImportSheet.swift index 52bc4aceba..c0bb8ea2eb 100644 --- a/apple/TablePro/Views/Connection/ConnectionImportSheet.swift +++ b/apple/TablePro/Views/Connection/ConnectionImportSheet.swift @@ -102,9 +102,8 @@ struct ConnectionImportSheet: View { .onSubmit { requestDecrypt() } if let passphraseError { - Label(passphraseError, systemImage: "exclamationmark.triangle.fill") + NoticeLabel(passphraseError) .font(.subheadline) - .foregroundStyle(.orange) } Spacer() diff --git a/apple/TablePro/Views/Connection/ConnectionWarningBanner.swift b/apple/TablePro/Views/Connection/ConnectionWarningBanner.swift index 4f688408f3..36b4e1fd2e 100644 --- a/apple/TablePro/Views/Connection/ConnectionWarningBanner.swift +++ b/apple/TablePro/Views/Connection/ConnectionWarningBanner.swift @@ -5,57 +5,22 @@ import SwiftUI -/// The warning a server sent with a login that succeeded, shown in place rather than in an alert: the -/// connection works and nothing here acts on the warning, and the HIG keeps alerts for what needs action. +// A server warning on a login that worked shows in place: nothing here acts on it, and the HIG keeps +// alerts for what needs a decision. internal struct ConnectionWarningBanner: View { let message: String let onDismiss: () -> Void var body: some View { - HStack(alignment: .top, spacing: 8) { - Image(systemName: "exclamationmark.triangle.fill") - .foregroundStyle(.yellow) - .accessibilityHidden(true) - - VStack(alignment: .leading, spacing: 2) { - Text(String(localized: "Connected with a warning")) - .font(.callout.weight(.semibold)) - Text(message) - .font(.callout) - .foregroundStyle(.secondary) - .lineLimit(3) - .truncationMode(.tail) - .fixedSize(horizontal: false, vertical: true) - .textSelection(.enabled) - .help(message) - } - - Spacer(minLength: 8) - - Button { - ClipboardService.shared.writeText(message) - } label: { - Image(systemName: "doc.on.doc") - .imageScale(.small) - } - .buttonStyle(.borderless) - .help(String(localized: "Copy Warning")) - .accessibilityLabel(String(localized: "Copy Warning")) - - Button { - onDismiss() - } label: { - Image(systemName: "xmark") - .imageScale(.small) - } - .buttonStyle(.borderless) - .help(String(localized: "Dismiss")) - .accessibilityLabel(String(localized: "Dismiss")) + PaneNoticeBar(severity: .warning, onDismiss: onDismiss) { + PaneNoticeText( + title: String(localized: "Connected with a warning"), + detail: message, + detailLineLimit: 3 + ) + } actions: { + PaneNoticeCopyButton(text: message, label: String(localized: "Copy Warning")) } - .padding(.horizontal, 12) - .padding(.vertical, 8) - // A shape style background reaches into the safe area by default, which tints the toolbar above. - .background(.yellow.opacity(0.12), ignoresSafeAreaEdges: []) .accessibilityElement(children: .contain) .accessibilityIdentifier("connection-warning-banner") } diff --git a/apple/TablePro/Views/Connection/DeeplinkImportSheet.swift b/apple/TablePro/Views/Connection/DeeplinkImportSheet.swift index 2319fb63ec..95a5eb008f 100644 --- a/apple/TablePro/Views/Connection/DeeplinkImportSheet.swift +++ b/apple/TablePro/Views/Connection/DeeplinkImportSheet.swift @@ -66,8 +66,12 @@ struct DeeplinkImportSheet: View { return Form { Section { HStack(spacing: 10) { - DatabaseType(rawValue: connection.type).iconImage - .frame(width: 28, height: 28) + ConnectionTile( + type: DatabaseType(rawValue: connection.type), + iconName: connection.iconName, + identityColor: Self.displayColor(connection.color), + size: 28 + ) Text(DatabaseType(rawValue: connection.type).displayName) .font(.headline) } @@ -188,12 +192,8 @@ struct DeeplinkImportSheet: View { if let startupCommands = connection.startupCommands, !startupCommands.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { Section { - Label( - String(localized: "This connection runs SQL every time it connects, using your credentials."), - systemImage: "exclamationmark.triangle.fill" - ) - .foregroundStyle(.orange) - .font(.callout) + NoticeLabel(String(localized: "This connection runs SQL every time it connects, using your credentials.")) + .font(.callout) CodeWell(startupCommands, font: .system(.caption, design: .monospaced)) } header: { @@ -228,9 +228,8 @@ struct DeeplinkImportSheet: View { Section { if let color { LabeledContent(String(localized: "Color")) { - Circle() - .fill(color.color) - .frame(width: 12, height: 12) + Text(color.displayName) + .foregroundStyle(.secondary) } } if let customSymbol { @@ -265,8 +264,7 @@ struct DeeplinkImportSheet: View { if !notices.isEmpty { Section { ForEach(notices, id: \.self) { notice in - Label(notice, systemImage: "exclamationmark.triangle.fill") - .foregroundStyle(.orange) + NoticeLabel(notice, severity: libraryError == nil ? .warning : .error) .font(.callout) } } diff --git a/apple/TablePro/Views/Connection/GroupEditorSheet.swift b/apple/TablePro/Views/Connection/GroupEditorSheet.swift index 8b47183c73..77006155c4 100644 --- a/apple/TablePro/Views/Connection/GroupEditorSheet.swift +++ b/apple/TablePro/Views/Connection/GroupEditorSheet.swift @@ -76,10 +76,8 @@ internal struct GroupEditorSheet: View { } if let errorMessage { - Label(errorMessage, systemImage: "exclamationmark.triangle.fill") + NoticeLabel(errorMessage, severity: .error) .font(.caption) - .foregroundStyle(.red) - .fixedSize(horizontal: false, vertical: true) .frame(maxWidth: .infinity, alignment: .leading) } diff --git a/apple/TablePro/Views/Connection/Import/ImportConnectionRowView.swift b/apple/TablePro/Views/Connection/Import/ImportConnectionRowView.swift index eee841296e..ff399e30dd 100644 --- a/apple/TablePro/Views/Connection/Import/ImportConnectionRowView.swift +++ b/apple/TablePro/Views/Connection/Import/ImportConnectionRowView.swift @@ -36,7 +36,6 @@ internal struct ImportConnectionRowView: View { let notes = Self.notes(for: row) if let note = notes.first { Text(verbatim: note) - .foregroundStyle(.orange) .help(notes.joined(separator: "\n")) } } @@ -86,7 +85,7 @@ internal struct ImportConnectionRowView: View { } else if !row.warnings.isEmpty { Image(systemName: "exclamationmark.triangle.fill") .font(.callout) - .foregroundStyle(.yellow) + .foregroundStyle(.orange) .accessibilityLabel(String(localized: "Warning")) } else { Image(systemName: "checkmark.circle.fill") @@ -124,11 +123,5 @@ internal struct ImportRowTag: View { Text(verbatim: text) .font(.caption) .foregroundStyle(.secondary) - .padding(.horizontal, 4) - .padding(.vertical, 1) - .background( - RoundedRectangle(cornerRadius: 3) - .fill(Color(nsColor: .quaternaryLabelColor)) - ) } } diff --git a/apple/TablePro/Views/Connection/Import/ImportQueryRowView.swift b/apple/TablePro/Views/Connection/Import/ImportQueryRowView.swift index dc7ac3756c..5e823f818b 100644 --- a/apple/TablePro/Views/Connection/Import/ImportQueryRowView.swift +++ b/apple/TablePro/Views/Connection/Import/ImportQueryRowView.swift @@ -38,8 +38,7 @@ internal struct ImportQueryRowView: View { Text(verbatim: row.folderPath.joined(separator: " / ")) } if let note = Self.note(for: row, status: status) { - Text(verbatim: note) - .foregroundStyle(.orange) + NoticeLabel(note) .help(note) } } diff --git a/apple/TablePro/Views/Connection/Import/ImportReviewStep.swift b/apple/TablePro/Views/Connection/Import/ImportReviewStep.swift index 29faf35cfd..c707ae4479 100644 --- a/apple/TablePro/Views/Connection/Import/ImportReviewStep.swift +++ b/apple/TablePro/Views/Connection/Import/ImportReviewStep.swift @@ -77,16 +77,18 @@ internal struct ImportReviewStep: View { private func bannerLabel(_ text: String, symbol: String) -> some View { Label { Text(verbatim: text) - .font(.caption) + .foregroundStyle(.secondary) .lineLimit(3) .help(text) } icon: { Image(systemName: symbol) .foregroundStyle(.orange) + .accessibilityHidden(true) } - .padding(8) + .font(.caption) + .padding(.horizontal, 16) + .padding(.bottom, 8) .frame(maxWidth: .infinity, alignment: .leading) - .background(.orange.opacity(0.12)) } private var footer: some View { diff --git a/apple/TablePro/Views/Connection/ImportFromAWS/AWSDiscoveryConfigurationStep.swift b/apple/TablePro/Views/Connection/ImportFromAWS/AWSDiscoveryConfigurationStep.swift index 91cf4b9786..6bcd121ece 100644 --- a/apple/TablePro/Views/Connection/ImportFromAWS/AWSDiscoveryConfigurationStep.swift +++ b/apple/TablePro/Views/Connection/ImportFromAWS/AWSDiscoveryConfigurationStep.swift @@ -101,9 +101,7 @@ struct AWSDiscoveryConfigurationStep: View { private func credentialFailureView(_ failure: AWSDiscoverySession.CredentialFailure) -> some View { HStack(alignment: .firstTextBaseline, spacing: 8) { - Image(systemName: "exclamationmark.triangle.fill") - .foregroundStyle(.orange) - Text(verbatim: failure.message) + NoticeLabel(failure.message) .font(.caption) .lineLimit(3) .textSelection(.enabled) @@ -117,9 +115,7 @@ struct AWSDiscoveryConfigurationStep: View { .disabled(session.isSigningIn) } } - .padding(8) .frame(maxWidth: .infinity, alignment: .leading) - .background(.orange.opacity(0.12)) } private var footer: some View { diff --git a/apple/TablePro/Views/Connection/PasswordSourceTest.swift b/apple/TablePro/Views/Connection/PasswordSourceTest.swift index a7e13271ef..fdf9a8081e 100644 --- a/apple/TablePro/Views/Connection/PasswordSourceTest.swift +++ b/apple/TablePro/Views/Connection/PasswordSourceTest.swift @@ -86,9 +86,8 @@ struct PasswordSourceTestView: View { } SecretRevealToggle(reveal: reveal, requiresAuthentication: true) case .failed(let message): - Label(message, systemImage: "exclamationmark.triangle.fill") + NoticeLabel(message, severity: .error) .font(.caption) - .foregroundStyle(.red) .textSelection(.enabled) case nil: EmptyView() diff --git a/apple/TablePro/Views/Connection/SSHProfileEditorView.swift b/apple/TablePro/Views/Connection/SSHProfileEditorView.swift index bb868c6366..b989517cf0 100644 --- a/apple/TablePro/Views/Connection/SSHProfileEditorView.swift +++ b/apple/TablePro/Views/Connection/SSHProfileEditorView.swift @@ -364,19 +364,16 @@ struct SSHProfileEditorView: View { .disabled(isTesting || !isValid) if let saveError { - Label(saveError, systemImage: "exclamationmark.triangle.fill") + NoticeLabel(saveError, severity: .error) .font(.caption) - .foregroundStyle(.red) .lineLimit(2) .truncationMode(.tail) } else if testSucceeded { - Text(String(localized: "Connected")) + NoticeLabel(String(localized: "Connected"), severity: .success) .font(.caption) - .foregroundStyle(.green) } else if let testError { - Label(testError, systemImage: "exclamationmark.triangle.fill") + NoticeLabel(testError) .font(.caption) - .foregroundStyle(.orange) .lineLimit(2) .truncationMode(.tail) } diff --git a/apple/TablePro/Views/ConnectionForm/Components/CredentialProfilePicker.swift b/apple/TablePro/Views/ConnectionForm/Components/CredentialProfilePicker.swift index 0c3842e74a..029f4797d7 100644 --- a/apple/TablePro/Views/ConnectionForm/Components/CredentialProfilePicker.swift +++ b/apple/TablePro/Views/ConnectionForm/Components/CredentialProfilePicker.swift @@ -28,12 +28,8 @@ struct CredentialProfilePicker: View { .accessibilityIdentifier("connection-form-credential-profile") if auth.credentialProfileIsMissing { - Label( - String(localized: "This connection uses a credential profile that isn't on this Mac."), - systemImage: "exclamationmark.triangle.fill" - ) - .font(.caption) - .foregroundStyle(.yellow) + NoticeLabel(String(localized: "This connection uses a credential profile that isn't on this Mac.")) + .font(.caption) Button(String(localized: "Enter Credentials Here")) { auth.credentialMode = .inline } diff --git a/apple/TablePro/Views/ConnectionForm/Components/ImportFromURLSheet.swift b/apple/TablePro/Views/ConnectionForm/Components/ImportFromURLSheet.swift index 7a7d21efbc..3d88044887 100644 --- a/apple/TablePro/Views/ConnectionForm/Components/ImportFromURLSheet.swift +++ b/apple/TablePro/Views/ConnectionForm/Components/ImportFromURLSheet.swift @@ -34,9 +34,8 @@ struct ImportFromURLSheet: View { .onSubmit(submit) if let parseError { - Label(parseError, systemImage: "exclamationmark.triangle.fill") + NoticeLabel(parseError) .font(.caption) - .foregroundStyle(.orange) } else if let parsed = parsedURL { previewView(parsed) } diff --git a/apple/TablePro/Views/ConnectionForm/Panes/GeneralPaneView.swift b/apple/TablePro/Views/ConnectionForm/Panes/GeneralPaneView.swift index 2d31ba4d43..6a6f4dd3c1 100644 --- a/apple/TablePro/Views/ConnectionForm/Panes/GeneralPaneView.swift +++ b/apple/TablePro/Views/ConnectionForm/Panes/GeneralPaneView.swift @@ -216,12 +216,8 @@ struct GeneralPaneView: View { .accessibilityIdentifier("connection-form-port-tls-note") } else if coordinator.ssl.mode == .disabled { HStack { - Label( - String(format: String(localized: "Port %lld usually requires TLS, and SSL Mode is Disabled."), port), - systemImage: "exclamationmark.triangle.fill" - ) - .foregroundStyle(.orange) - .font(.caption) + NoticeLabel(String(format: String(localized: "Port %lld usually requires TLS, and SSL Mode is Disabled."), port)) + .font(.caption) Spacer() Button(String(format: String(localized: "Use %@"), impliedMode.displayLabel)) { coordinator.ssl.select(impliedMode) @@ -306,33 +302,17 @@ struct GeneralPaneView: View { case .notChecked: EmptyView() case .fileNotFound: - Label( - String(localized: "~/.pgpass not found"), - systemImage: "exclamationmark.triangle.fill" - ) - .foregroundStyle(.yellow) - .font(.caption) + NoticeLabel(String(localized: "~/.pgpass not found")) + .font(.caption) case .badPermissions: - Label( - String(localized: "~/.pgpass has incorrect permissions (needs chmod 0600)"), - systemImage: "exclamationmark.triangle.fill" - ) - .foregroundStyle(.orange) - .font(.caption) + NoticeLabel(String(localized: "~/.pgpass has incorrect permissions (needs chmod 0600)")) + .font(.caption) case .matchFound: - Label( - String(localized: "~/.pgpass found, matching entry exists"), - systemImage: "checkmark.circle.fill" - ) - .foregroundStyle(.green) - .font(.caption) + NoticeLabel(String(localized: "~/.pgpass found, matching entry exists"), severity: .success) + .font(.caption) case .noMatch: - Label( - String(localized: "~/.pgpass found, no matching entry"), - systemImage: "exclamationmark.triangle.fill" - ) - .foregroundStyle(.yellow) - .font(.caption) + NoticeLabel(String(localized: "~/.pgpass found, no matching entry")) + .font(.caption) } } @@ -347,9 +327,8 @@ struct GeneralPaneView: View { .foregroundStyle(.secondary) // MariaDB's server names its own principal, so only these two take it from the host. if hostIsIPAddress, usesWindowsAuthentication || type.pluginTypeId == "PostgreSQL" { - Label(kerberosHostWarning, systemImage: "exclamationmark.triangle.fill") + NoticeLabel(kerberosHostWarning) .font(.caption) - .foregroundStyle(.yellow) } } } diff --git a/apple/TablePro/Views/ConnectionForm/Panes/SSLSections.swift b/apple/TablePro/Views/ConnectionForm/Panes/SSLSections.swift index 4f0883b3dc..269e46cdaa 100644 --- a/apple/TablePro/Views/ConnectionForm/Panes/SSLSections.swift +++ b/apple/TablePro/Views/ConnectionForm/Panes/SSLSections.swift @@ -48,8 +48,7 @@ struct SSLSections: View { } .accessibilityIdentifier("connection-form-ssl-mode") if sslMode == .preferred, !databaseType.supportsOpportunisticTLS { - Label(noOpportunisticTLSWarning, systemImage: "exclamationmark.triangle.fill") - .foregroundStyle(databaseType == .oracle ? .red : .orange) + NoticeLabel(noOpportunisticTLSWarning, severity: databaseType == .oracle ? .error : .warning) .font(.caption) } } footer: { diff --git a/apple/TablePro/Views/ConnectionForm/Panes/Transports/CloudSQLProxyTransportSections.swift b/apple/TablePro/Views/ConnectionForm/Panes/Transports/CloudSQLProxyTransportSections.swift index 0a67912bfc..8e9283d82a 100644 --- a/apple/TablePro/Views/ConnectionForm/Panes/Transports/CloudSQLProxyTransportSections.swift +++ b/apple/TablePro/Views/ConnectionForm/Panes/Transports/CloudSQLProxyTransportSections.swift @@ -136,9 +136,8 @@ struct CloudSQLProxyTransportSections: View { } if let error = viewModel.downloadError { - Label(error, systemImage: "exclamationmark.triangle.fill") + NoticeLabel(error) .font(.caption) - .foregroundStyle(.orange) .textSelection(.enabled) } @@ -147,9 +146,8 @@ struct CloudSQLProxyTransportSections: View { LabeledContent(String(localized: "Detected"), value: resolved) .foregroundStyle(.secondary) } else if viewModel.didResolveBinary { - Label(viewModel.binaryNotFoundMessage, systemImage: "exclamationmark.triangle.fill") - .foregroundStyle(.orange) - .textSelection(.enabled) + NoticeLabel(viewModel.binaryNotFoundMessage) + .textSelection(.enabled) } } } header: { diff --git a/apple/TablePro/Views/ConnectionForm/Panes/Transports/CloudflareTransportSections.swift b/apple/TablePro/Views/ConnectionForm/Panes/Transports/CloudflareTransportSections.swift index 116c185028..1c1ed7a3b6 100644 --- a/apple/TablePro/Views/ConnectionForm/Panes/Transports/CloudflareTransportSections.swift +++ b/apple/TablePro/Views/ConnectionForm/Panes/Transports/CloudflareTransportSections.swift @@ -47,9 +47,8 @@ struct CloudflareTransportSections: View { } .disabled(coordinator.cloudflareTunnel.state.accessHostname.trimmingCharacters(in: .whitespaces).isEmpty) if let signInError = viewModel.signInError { - Label(signInError, systemImage: "exclamationmark.triangle.fill") + NoticeLabel(signInError) .font(.caption) - .foregroundStyle(.orange) } else { Text("Signs in to Cloudflare Access once and caches the token, so connecting doesn't open a browser.") .font(.caption) @@ -106,9 +105,8 @@ struct CloudflareTransportSections: View { LabeledContent(String(localized: "Detected"), value: resolved) .foregroundStyle(.secondary) } else if viewModel.didResolveBinary { - Label(viewModel.binaryNotFoundMessage, systemImage: "exclamationmark.triangle.fill") - .foregroundStyle(.orange) - .textSelection(.enabled) + NoticeLabel(viewModel.binaryNotFoundMessage) + .textSelection(.enabled) } } } header: { diff --git a/apple/TablePro/Views/ConnectionForm/Panes/Transports/SSHServerSections.swift b/apple/TablePro/Views/ConnectionForm/Panes/Transports/SSHServerSections.swift index 67719bd8e7..5a3c8fc47b 100644 --- a/apple/TablePro/Views/ConnectionForm/Panes/Transports/SSHServerSections.swift +++ b/apple/TablePro/Views/ConnectionForm/Panes/Transports/SSHServerSections.swift @@ -20,11 +20,7 @@ struct SSHServerSections: View { if sshState.selectedProfile == nil, sshState.profileId != nil { Section { - Label( - String(localized: "Selected SSH profile no longer exists."), - systemImage: "exclamationmark.triangle.fill" - ) - .foregroundStyle(.yellow) + NoticeLabel(String(localized: "Selected SSH profile no longer exists.")) Button(String(localized: "Switch to Inline Configuration")) { sshState.profileId = nil } diff --git a/apple/TablePro/Views/ConnectionForm/Panes/Transports/SSHTransportSections.swift b/apple/TablePro/Views/ConnectionForm/Panes/Transports/SSHTransportSections.swift index 0a3f94d7d5..7a80ac509b 100644 --- a/apple/TablePro/Views/ConnectionForm/Panes/Transports/SSHTransportSections.swift +++ b/apple/TablePro/Views/ConnectionForm/Panes/Transports/SSHTransportSections.swift @@ -79,9 +79,14 @@ struct SSHTransportSections: View { } private func caption(_ message: String, systemImage: String, tint: Color) -> some View { - Label(message, systemImage: systemImage) - .font(.caption) - .foregroundStyle(tint) + Label { + Text(message) + .foregroundStyle(.secondary) + } icon: { + Image(systemName: systemImage) + .foregroundStyle(tint) + } + .font(.caption) } } diff --git a/apple/TablePro/Views/DataGrid/DataGridFindBar.swift b/apple/TablePro/Views/DataGrid/DataGridFindBar.swift index 4e5f950bc2..2879242aea 100644 --- a/apple/TablePro/Views/DataGrid/DataGridFindBar.swift +++ b/apple/TablePro/Views/DataGrid/DataGridFindBar.swift @@ -85,7 +85,7 @@ struct DataGridFindBar: View { Text(counterText) .font(.callout) - .foregroundStyle(find.problem == nil || status != nil ? Color.secondary : Color(nsColor: .systemRed)) + .foregroundStyle(.secondary) .monospacedDigit() .lineLimit(1) .accessibilityLabel(counterText) diff --git a/apple/TablePro/Views/DatabaseSwitcher/CreateDatabaseSheet.swift b/apple/TablePro/Views/DatabaseSwitcher/CreateDatabaseSheet.swift index ccf8bed4e7..7cdc8a564d 100644 --- a/apple/TablePro/Views/DatabaseSwitcher/CreateDatabaseSheet.swift +++ b/apple/TablePro/Views/DatabaseSwitcher/CreateDatabaseSheet.swift @@ -30,11 +30,6 @@ struct CreateDatabaseSheet: View { .padding(.horizontal, 20) .padding(.vertical, 16) - if let error = errorMessage { - Divider() - errorBanner(error) - } - Divider() buttonBar @@ -80,6 +75,10 @@ struct CreateDatabaseSheet: View { case .failed(let message): failureRow(message: message) } + + if let errorMessage { + errorRow(errorMessage) + } } .formStyle(.columns) } @@ -106,18 +105,18 @@ struct CreateDatabaseSheet: View { } } - private func errorBanner(_ message: String) -> some View { - HStack(spacing: 8) { - Image(systemName: "exclamationmark.triangle.fill") - .foregroundStyle(.orange) + private func errorRow(_ message: String) -> some View { + Label { RevealedTextView(message) - .font(.callout) - .foregroundStyle(.primary) + .foregroundStyle(.secondary) .lineLimit(2) - Spacer() + .fixedSize(horizontal: false, vertical: true) + } icon: { + Image(systemName: NoticeSeverity.error.symbolName) + .foregroundStyle(NoticeSeverity.error.tint) + .accessibilityHidden(true) } - .padding(.horizontal, 20) - .padding(.vertical, 10) + .font(.callout) } private var buttonBar: some View { diff --git a/apple/TablePro/Views/DatabaseSwitcher/SchemaEditorSheet.swift b/apple/TablePro/Views/DatabaseSwitcher/SchemaEditorSheet.swift index 7cd2f5b8d4..449176abe8 100644 --- a/apple/TablePro/Views/DatabaseSwitcher/SchemaEditorSheet.swift +++ b/apple/TablePro/Views/DatabaseSwitcher/SchemaEditorSheet.swift @@ -163,9 +163,15 @@ struct SchemaEditorSheet: View { .formStyle(.columns) if let problem = model.nameProblem, !model.name.isEmpty { - Label(problem.message, systemImage: "exclamationmark.circle") - .font(.caption) - .foregroundStyle(.red) + Label { + Text(problem.message) + .foregroundStyle(.secondary) + } icon: { + Image(systemName: "exclamationmark.circle") + .foregroundStyle(NoticeSeverity.error.tint) + .accessibilityHidden(true) + } + .font(.caption) } } } @@ -295,7 +301,7 @@ struct SchemaEditorSheet: View { private var footer: some View { VStack(spacing: 8) { if let failure = model.failure { - InlineErrorBanner(message: failure) + InlineErrorBanner(message: failure, onBar: false) } HStack(spacing: 12) { if let count = statementCount { diff --git a/apple/TablePro/Views/Editor/History/HistoryDetailPane.swift b/apple/TablePro/Views/Editor/History/HistoryDetailPane.swift index 9d5650c35f..6ed8b8cee0 100644 --- a/apple/TablePro/Views/Editor/History/HistoryDetailPane.swift +++ b/apple/TablePro/Views/Editor/History/HistoryDetailPane.swift @@ -90,11 +90,17 @@ struct HistoryDetailPane: View { } if let errorMessage = entry.errorMessage { - RevealedTextView(errorMessage) - .font(.caption) - .foregroundStyle(.red) - .textSelection(.enabled) - .fixedSize(horizontal: false, vertical: true) + Label { + RevealedTextView(errorMessage) + .foregroundStyle(.secondary) + .textSelection(.enabled) + .fixedSize(horizontal: false, vertical: true) + } icon: { + Image(systemName: NoticeSeverity.error.symbolName) + .foregroundStyle(NoticeSeverity.error.tint) + .accessibilityHidden(true) + } + .font(.caption) } } .padding(10) diff --git a/apple/TablePro/Views/Editor/QueryParameterPanelView.swift b/apple/TablePro/Views/Editor/QueryParameterPanelView.swift index 67aea4cb07..b552706cb2 100644 --- a/apple/TablePro/Views/Editor/QueryParameterPanelView.swift +++ b/apple/TablePro/Views/Editor/QueryParameterPanelView.swift @@ -52,13 +52,11 @@ struct QueryParameterPanelView: View { .buttonStyle(.bordered) .controlSize(.small) - Button(action: onDismiss) { - Image(systemName: "xmark") - .frame(width: 24, height: 24) - } - .buttonStyle(.borderless) - .help(String(localized: "Close parameter panel")) - .accessibilityLabel(String(localized: "Close parameter panel")) + Button(String(localized: "Close parameter panel"), systemImage: "xmark", action: onDismiss) + .labelStyle(.iconOnly) + .buttonStyle(.borderless) + .controlSize(.small) + .help(String(localized: "Close parameter panel")) } .padding(.horizontal, 12) .padding(.vertical, 8) diff --git a/apple/TablePro/Views/Editor/SourceFileDiskChangeBanner.swift b/apple/TablePro/Views/Editor/SourceFileDiskChangeBanner.swift index 15692cd5d7..347ec89193 100644 --- a/apple/TablePro/Views/Editor/SourceFileDiskChangeBanner.swift +++ b/apple/TablePro/Views/Editor/SourceFileDiskChangeBanner.swift @@ -13,35 +13,17 @@ internal struct SourceFileDiskChangeBanner: View { let onDismiss: () -> Void var body: some View { - HStack(spacing: 8) { - Image(systemName: "exclamationmark.triangle.fill") - .foregroundStyle(.yellow) - .accessibilityHidden(true) - + PaneNoticeBar(severity: .warning, onDismiss: onDismiss) { Text(message) .font(.callout) .lineLimit(1) .truncationMode(.middle) - - Spacer() - + .help(message) + } actions: { actionButton - .controlSize(.small) - .buttonStyle(.bordered) - - Button { - onDismiss() - } label: { - Image(systemName: "xmark") - .imageScale(.small) - } - .buttonStyle(.borderless) - .help(String(localized: "Dismiss")) - .accessibilityLabel(String(localized: "Dismiss")) } - .padding(.horizontal, 12) - .padding(.vertical, 6) - .background(.yellow.opacity(0.12)) + .accessibilityElement(children: .contain) + .accessibilityIdentifier("source-file-disk-change-banner") } private var message: String { @@ -57,13 +39,9 @@ internal struct SourceFileDiskChangeBanner: View { private var actionButton: some View { switch change { case .modified: - Button(String(localized: "Reload")) { - onReload() - } + Button(String(localized: "Reload"), action: onReload) case .missing: - Button(String(localized: "Save As…")) { - onSaveAs() - } + Button(String(localized: "Save As…"), action: onSaveAs) } } } diff --git a/apple/TablePro/Views/Export/ExportDialog.swift b/apple/TablePro/Views/Export/ExportDialog.swift index b23a834de8..6105f0461e 100644 --- a/apple/TablePro/Views/Export/ExportDialog.swift +++ b/apple/TablePro/Views/Export/ExportDialog.swift @@ -534,9 +534,10 @@ struct ExportDialog: View { .foregroundStyle(.secondary) if let plugin = currentPlugin, !type(of: plugin).perTableOptionColumns.isEmpty, exportableCount < selectedCount { - Text("\(selectedCount - exportableCount) skipped (no options)") - .font(.subheadline) - .foregroundStyle(.orange) + NoticeLabel( + String(format: String(localized: "%lld skipped (no options)"), Int64(selectedCount - exportableCount)) + ) + .font(.subheadline) } } } diff --git a/apple/TablePro/Views/Export/ExportRowScopeEditor.swift b/apple/TablePro/Views/Export/ExportRowScopeEditor.swift index a7a9b1e403..d0fad757e1 100644 --- a/apple/TablePro/Views/Export/ExportRowScopeEditor.swift +++ b/apple/TablePro/Views/Export/ExportRowScopeEditor.swift @@ -43,9 +43,8 @@ internal struct ExportRowScopeEditor: View { .font(themeEngine.valueFontSwiftUI) .accessibilityIdentifier("row-scope-filter") if hasRejectedFilter { - Text("A filter is one expression. Remove the semicolon.") + NoticeLabel(String(localized: "A filter is one expression. Remove the semicolon."), severity: .error) .font(.caption) - .foregroundStyle(.red) } } diff --git a/apple/TablePro/Views/Export/TableTransferMappingEditor.swift b/apple/TablePro/Views/Export/TableTransferMappingEditor.swift index 8b4ae7898c..a857b8a8c1 100644 --- a/apple/TablePro/Views/Export/TableTransferMappingEditor.swift +++ b/apple/TablePro/Views/Export/TableTransferMappingEditor.swift @@ -70,10 +70,8 @@ internal struct TableTransferMappingEditor: View { .frame(height: 200) if !contested.isEmpty { - Text(Self.contestedMappingMessage) + NoticeLabel(Self.contestedMappingMessage, severity: .error) .font(.caption) - .foregroundStyle(.red) - .fixedSize(horizontal: false, vertical: true) } if !match.unmatchedDestination.isEmpty { diff --git a/apple/TablePro/Views/Export/TableTransferSheet.swift b/apple/TablePro/Views/Export/TableTransferSheet.swift index 1bd0d1ce1a..899ddfbe92 100644 --- a/apple/TablePro/Views/Export/TableTransferSheet.swift +++ b/apple/TablePro/Views/Export/TableTransferSheet.swift @@ -164,10 +164,16 @@ struct TableTransferSheet: View { .toggleStyle(.checkbox) if let errorMessage { - RevealedTextView(errorMessage) - .font(.subheadline) - .foregroundStyle(.red) - .fixedSize(horizontal: false, vertical: true) + Label { + RevealedTextView(errorMessage) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } icon: { + Image(systemName: NoticeSeverity.error.symbolName) + .foregroundStyle(NoticeSeverity.error.tint) + .accessibilityHidden(true) + } + .font(.subheadline) } } .padding(16) @@ -184,9 +190,8 @@ struct TableTransferSheet: View { .lineLimit(1) .truncationMode(.middle) } else if hasContestedMapping { - Text(TableTransferMappingEditor.contestedMappingMessage) + NoticeLabel(TableTransferMappingEditor.contestedMappingMessage, severity: .error) .font(.caption) - .foregroundStyle(.red) .lineLimit(2) } } actions: { @@ -219,8 +224,7 @@ struct TableTransferSheet: View { ) } - /// Says how a table will map before anything is written, and opens the editor. A table whose - /// columns match nothing is called out here rather than failing on its first batch. + // A table whose columns match nothing is called out here rather than failing on its first batch. @ViewBuilder private func mappingSummary(for table: String) -> some View { let match = resolvedMatch(for: table) @@ -230,9 +234,8 @@ struct TableTransferSheet: View { .scaleEffect(0.5) .frame(width: 16) } else if destinationColumns[table] == nil { - Text("No such table") + NoticeLabel(String(localized: "No such table"), severity: .error) .font(.caption) - .foregroundStyle(.red) } else { Button { inspectedTable = table @@ -240,7 +243,13 @@ struct TableTransferSheet: View { HStack(spacing: 3) { Text(mappingLabel(match)) .font(.caption) - .foregroundStyle(cannotTransfer ? Color.red : .secondary) + .foregroundStyle(.secondary) + if cannotTransfer { + Image(systemName: NoticeSeverity.error.symbolName) + .font(.caption) + .foregroundStyle(NoticeSeverity.error.tint) + .accessibilityHidden(true) + } Image(systemName: "arrow.left.arrow.right") .font(.caption) } diff --git a/apple/TablePro/Views/Import/RowImportBatchSheet.swift b/apple/TablePro/Views/Import/RowImportBatchSheet.swift index c043952aa7..0497bb6b21 100644 --- a/apple/TablePro/Views/Import/RowImportBatchSheet.swift +++ b/apple/TablePro/Views/Import/RowImportBatchSheet.swift @@ -212,7 +212,7 @@ struct RowImportBatchSheet: View { HStack(spacing: 6) { if let problem = batch.problem(of: file), file.isIncluded { Image(systemName: "exclamationmark.triangle.fill") - .foregroundStyle(.yellow) + .foregroundStyle(.orange) .help(problem) .accessibilityLabel(Text(problem)) } @@ -366,9 +366,8 @@ struct RowImportBatchSheet: View { private var footerView: some View { DialogFooter { if let message = batch.problem, !batch.isReading || batch.includedFiles.isEmpty { - Text(message) + NoticeLabel(message, severity: .error) .font(.caption) - .foregroundStyle(.red) .lineLimit(2) } else if batch.isReading { Text("Reading the files…") diff --git a/apple/TablePro/Views/Import/RowImportSheet.swift b/apple/TablePro/Views/Import/RowImportSheet.swift index fde83e3ed4..f40430363e 100644 --- a/apple/TablePro/Views/Import/RowImportSheet.swift +++ b/apple/TablePro/Views/Import/RowImportSheet.swift @@ -411,9 +411,8 @@ struct RowImportSheet: View { private var footerView: some View { DialogFooter { if let message = validationMessage { - Text(message) + NoticeLabel(message, severity: .error) .font(.caption) - .foregroundStyle(.red) .lineLimit(2) } } actions: { diff --git a/apple/TablePro/Views/Integrations/IntegrationsActivityLogPane.swift b/apple/TablePro/Views/Integrations/IntegrationsActivityLogPane.swift index 099d929d3d..ae059a6d62 100644 --- a/apple/TablePro/Views/Integrations/IntegrationsActivityLogPane.swift +++ b/apple/TablePro/Views/Integrations/IntegrationsActivityLogPane.swift @@ -356,7 +356,7 @@ private struct ActivityLogTable: View { if let name = entry.tokenName { Text(IntegrationsFormatting.displayTokenName(name)) } else { - Text(verbatim: "—").foregroundStyle(.tertiary) + Text(verbatim: "-").foregroundStyle(.tertiary) } } @@ -365,7 +365,7 @@ private struct ActivityLogTable: View { if let label = connectionLabel(entry.connectionId) { Text(label) } else { - Text(verbatim: "—").foregroundStyle(.tertiary) + Text(verbatim: "-").foregroundStyle(.tertiary) } } @@ -439,13 +439,13 @@ private struct ActivityLogInspector: View { Section(String(localized: "Source")) { LabeledContent(String(localized: "Token")) { - let tokenText = entry.tokenName.map(IntegrationsFormatting.displayTokenName) ?? "—" + let tokenText = entry.tokenName.map(IntegrationsFormatting.displayTokenName) ?? String(localized: "None") Text(tokenText) .foregroundStyle(entry.tokenName == nil ? .tertiary : .primary) .textSelection(.enabled) } LabeledContent(String(localized: "Connection")) { - Text(connectionLabel(entry.connectionId) ?? "—") + Text(connectionLabel(entry.connectionId) ?? String(localized: "None")) .foregroundStyle(entry.connectionId == nil ? .tertiary : .primary) .textSelection(.enabled) } diff --git a/apple/TablePro/Views/Integrations/IntegrationsConnectedClientsPane.swift b/apple/TablePro/Views/Integrations/IntegrationsConnectedClientsPane.swift index be772fe6a0..136e22745c 100644 --- a/apple/TablePro/Views/Integrations/IntegrationsConnectedClientsPane.swift +++ b/apple/TablePro/Views/Integrations/IntegrationsConnectedClientsPane.swift @@ -156,7 +156,7 @@ private struct ConnectedClientsTable: View { if let version = client.clientVersion { Text(version).foregroundStyle(.secondary) } else { - Text(verbatim: "—").foregroundStyle(.tertiary) + Text(verbatim: "-").foregroundStyle(.tertiary) } } @@ -165,7 +165,7 @@ private struct ConnectedClientsTable: View { if let name = client.tokenName { Text(IntegrationsFormatting.displayTokenName(name)) } else { - Text(verbatim: "—").foregroundStyle(.tertiary) + Text(verbatim: "-").foregroundStyle(.tertiary) } } @@ -174,7 +174,7 @@ private struct ConnectedClientsTable: View { if let address = client.remoteAddress { Text(address).font(.system(.body, design: .monospaced)) } else { - Text(verbatim: "—").foregroundStyle(.tertiary) + Text(verbatim: "-").foregroundStyle(.tertiary) } } diff --git a/apple/TablePro/Views/Integrations/IntegrationsFormatting.swift b/apple/TablePro/Views/Integrations/IntegrationsFormatting.swift index 71e8c1e78e..aa7b9f4354 100644 --- a/apple/TablePro/Views/Integrations/IntegrationsFormatting.swift +++ b/apple/TablePro/Views/Integrations/IntegrationsFormatting.swift @@ -18,7 +18,7 @@ enum IntegrationsFormatting { case .success: "checkmark.circle.fill" case .denied, .rateLimited: "exclamationmark.triangle.fill" case .error: "xmark.octagon.fill" - case .none: "circle.fill" + case .none: "questionmark.circle" } } diff --git a/apple/TablePro/Views/Main/Child/DocumentEditorSheet.swift b/apple/TablePro/Views/Main/Child/DocumentEditorSheet.swift index 8658571664..55cd91c5ae 100644 --- a/apple/TablePro/Views/Main/Child/DocumentEditorSheet.swift +++ b/apple/TablePro/Views/Main/Child/DocumentEditorSheet.swift @@ -88,10 +88,8 @@ struct DocumentEditorSheet: View { .stroke(Color(nsColor: .separatorColor)) ) if let saveError { - Text(saveError) + NoticeLabel(saveError, severity: .error) .font(.callout) - .foregroundStyle(.red) - .fixedSize(horizontal: false, vertical: true) .textSelection(.enabled) .accessibilityIdentifier("document-editor-error") } else { diff --git a/apple/TablePro/Views/Main/Child/MainEditorContentView.swift b/apple/TablePro/Views/Main/Child/MainEditorContentView.swift index a3de00ddeb..3e767d029c 100644 --- a/apple/TablePro/Views/Main/Child/MainEditorContentView.swift +++ b/apple/TablePro/Views/Main/Child/MainEditorContentView.swift @@ -1086,12 +1086,6 @@ struct MainEditorContentView: View { Text("⌘T") .font(.callout.monospaced()) .foregroundStyle(.tertiary) - .padding(.horizontal, 6) - .padding(.vertical, 2) - .background( - RoundedRectangle(cornerRadius: 4) - .fill(Color(nsColor: .quaternaryLabelColor)) - ) Text( "Open \(PluginManager.shared.queryLanguageName(for: connection.type)) Editor" ) @@ -1113,12 +1107,6 @@ struct MainEditorContentView: View { Text("⌘K") .font(.callout.monospaced()) .foregroundStyle(.tertiary) - .padding(.horizontal, 6) - .padding(.vertical, 2) - .background( - RoundedRectangle(cornerRadius: 4) - .fill(Color(nsColor: .quaternaryLabelColor)) - ) Text(String( format: String(localized: "Switch %@"), PluginManager.shared.containerEntityName(for: connection.type) diff --git a/apple/TablePro/Views/ObjectCopy/CopyObjectsReviewView.swift b/apple/TablePro/Views/ObjectCopy/CopyObjectsReviewView.swift index e54c46fa5b..59def800ef 100644 --- a/apple/TablePro/Views/ObjectCopy/CopyObjectsReviewView.swift +++ b/apple/TablePro/Views/ObjectCopy/CopyObjectsReviewView.swift @@ -41,10 +41,8 @@ internal struct CopyObjectsReviewView: View { VStack(alignment: .leading, spacing: 14) { headline(plan) ForEach(plan.warnings, id: \.self) { warning in - Label(warning, systemImage: "exclamationmark.triangle") + NoticeLabel(warning, severity: .warning) .font(.callout) - .foregroundStyle(.orange) - .fixedSize(horizontal: false, vertical: true) } rowPlan(plan) conversions(plan) @@ -135,17 +133,17 @@ internal struct CopyObjectsReviewView: View { } } - /// The table goes beside the reason, as the "Partly copied" and "Left out" rows put it: a - /// copy of several tables listed `status: enum(…) → VARCHAR(9)` once per table that had one. + // The table goes beside the reason: a copy of several tables listed the same change once per table. private func conversion(_ note: CrossEngineConversionNote) -> some View { VStack(alignment: .leading, spacing: 2) { Label { summary(note) + .foregroundStyle(.secondary) } icon: { Image(systemName: note.isLossy ? "exclamationmark.triangle" : "arrow.right.circle") + .foregroundStyle(note.isLossy ? AnyShapeStyle(.orange) : AnyShapeStyle(.secondary)) } .font(.callout) - .foregroundStyle(note.isLossy ? AnyShapeStyle(.orange) : AnyShapeStyle(.secondary)) Text(verbatim: "\(note.table): \(note.reason)") .font(.caption) .foregroundStyle(.secondary) diff --git a/apple/TablePro/Views/ObjectCopy/CopyObjectsSheet.swift b/apple/TablePro/Views/ObjectCopy/CopyObjectsSheet.swift index b874a76e94..b4dfb32783 100644 --- a/apple/TablePro/Views/ObjectCopy/CopyObjectsSheet.swift +++ b/apple/TablePro/Views/ObjectCopy/CopyObjectsSheet.swift @@ -106,16 +106,16 @@ internal struct CopyObjectsSheet: View { @ViewBuilder private var statusText: some View { if let message = session.errorMessage { - /// A driver's message is the only account of what went wrong, and it is routinely - /// longer than two lines, so it stays selectable and reachable in full from the - /// pointer rather than being truncated into something nobody can act on. + // A driver's message often runs past two lines, so it stays selectable and whole in the tooltip. Label { RevealedTextView(message) + .foregroundStyle(.secondary) } icon: { - Image(systemName: "exclamationmark.triangle") + Image(systemName: NoticeSeverity.error.symbolName) + .foregroundStyle(NoticeSeverity.error.tint) + .accessibilityHidden(true) } .font(.callout) - .foregroundStyle(.red) .lineLimit(2) .textSelection(.enabled) .help(RevealedText(message).plainText) diff --git a/apple/TablePro/Views/ObjectSource/ObjectSourceTabView.swift b/apple/TablePro/Views/ObjectSource/ObjectSourceTabView.swift index 3fa873cc87..289b6e133e 100644 --- a/apple/TablePro/Views/ObjectSource/ObjectSourceTabView.swift +++ b/apple/TablePro/Views/ObjectSource/ObjectSourceTabView.swift @@ -167,9 +167,8 @@ struct ObjectSourceTabView: View { Text(objectRef.kindDisplayName) .font(.caption) .foregroundStyle(.secondary) - .padding(.horizontal, 6) - .padding(.vertical, 2) - .background(Color(nsColor: .quaternaryLabelColor), in: Capsule()) + .lineLimit(1) + .fixedSize() Spacer() Text("Read Only") .font(.caption) diff --git a/apple/TablePro/Views/ObjectSource/UserType/CreateUserTypeSheet.swift b/apple/TablePro/Views/ObjectSource/UserType/CreateUserTypeSheet.swift index ccf0045d37..31526e51b4 100644 --- a/apple/TablePro/Views/ObjectSource/UserType/CreateUserTypeSheet.swift +++ b/apple/TablePro/Views/ObjectSource/UserType/CreateUserTypeSheet.swift @@ -97,10 +97,15 @@ struct CreateUserTypeSheet: View { .disabled(isCreating) Divider() DialogFooter { - if let message = failure ?? draft.problems.first { + if let failure { + NoticeLabel(failure, severity: .error) + .font(.callout) + .lineLimit(3) + .textSelection(.enabled) + } else if let message = draft.problems.first { Text(message) .font(.callout) - .foregroundStyle(failure == nil ? Color.secondary : Color.red) + .foregroundStyle(.secondary) .lineLimit(3) .textSelection(.enabled) } diff --git a/apple/TablePro/Views/ObjectSource/UserType/UserTypeMemberSheet.swift b/apple/TablePro/Views/ObjectSource/UserType/UserTypeMemberSheet.swift index ea3d153aa5..87b26dcca4 100644 --- a/apple/TablePro/Views/ObjectSource/UserType/UserTypeMemberSheet.swift +++ b/apple/TablePro/Views/ObjectSource/UserType/UserTypeMemberSheet.swift @@ -37,10 +37,8 @@ struct UserTypeMemberSheet: View { Form { fields if let problem { - Text(problem) + NoticeLabel(problem, severity: .error) .font(.callout) - .foregroundStyle(.red) - .fixedSize(horizontal: false, vertical: true) } } .formStyle(.grouped) diff --git a/apple/TablePro/Views/ObjectSource/UserType/UserTypePendingChangesView.swift b/apple/TablePro/Views/ObjectSource/UserType/UserTypePendingChangesView.swift index 5456bf4741..daea18b4c7 100644 --- a/apple/TablePro/Views/ObjectSource/UserType/UserTypePendingChangesView.swift +++ b/apple/TablePro/Views/ObjectSource/UserType/UserTypePendingChangesView.swift @@ -4,6 +4,7 @@ // import SwiftUI +import TableProPluginKit /// The queue, in the order it runs, with the server's answer on the change it refused. struct UserTypePendingChangesView: View { @@ -38,9 +39,8 @@ struct UserTypePendingChangesView: View { private func row(_ change: StagedTypeChange) -> some View { let message = model.message(for: change) return HStack(alignment: .firstTextBaseline, spacing: 8) { - Image(systemName: message == nil ? "circle.fill" : "exclamationmark.triangle.fill") - .font(.caption2) - .foregroundStyle(message == nil ? Color.secondary : Color.red) + Image(systemName: message == nil ? Self.symbolName(for: change.change) : NoticeSeverity.error.symbolName) + .foregroundStyle(message == nil ? Color.secondary : NoticeSeverity.error.tint) .accessibilityHidden(true) VStack(alignment: .leading, spacing: 2) { Text(change.summary) @@ -49,7 +49,7 @@ struct UserTypePendingChangesView: View { if let message { Text(message) .font(.callout) - .foregroundStyle(.red) + .foregroundStyle(.secondary) .fixedSize(horizontal: false, vertical: true) .textSelection(.enabled) } @@ -69,6 +69,19 @@ struct UserTypePendingChangesView: View { .font(.subheadline) } + private static func symbolName(for change: PluginUserDefinedTypeChange) -> String { + switch change { + case .addEnumLabel, .addCheck, .addField: + return "plus.circle" + case .dropConstraint, .dropField: + return "minus.circle" + case .validateConstraint: + return "checkmark.circle" + default: + return "pencil.circle" + } + } + private var bar: some View { HStack(spacing: 12) { if let summary = model.saveSummary { diff --git a/apple/TablePro/Views/ObjectSource/UserType/UserTypeTabView.swift b/apple/TablePro/Views/ObjectSource/UserType/UserTypeTabView.swift index c4a73e2b75..6712245768 100644 --- a/apple/TablePro/Views/ObjectSource/UserType/UserTypeTabView.swift +++ b/apple/TablePro/Views/ObjectSource/UserType/UserTypeTabView.swift @@ -79,9 +79,8 @@ struct UserTypeTabView: View { Text(model.objectRef.kindDisplayName) .font(.caption) .foregroundStyle(.secondary) - .padding(.horizontal, 6) - .padding(.vertical, 2) - .background(Color(nsColor: .quaternaryLabelColor), in: Capsule()) + .lineLimit(1) + .fixedSize() Spacer() if model.isSaving { ProgressView().controlSize(.small) diff --git a/apple/TablePro/Views/QueryInsights/QueryInsightsActivityChart.swift b/apple/TablePro/Views/QueryInsights/QueryInsightsActivityChart.swift index a4286d60fd..9ed755f607 100644 --- a/apple/TablePro/Views/QueryInsights/QueryInsightsActivityChart.swift +++ b/apple/TablePro/Views/QueryInsights/QueryInsightsActivityChart.swift @@ -43,57 +43,50 @@ struct QueryInsightsActivityChart: View { // the default grid line and no plot fill. var body: some View { let gridLine = ThemeShapeStyle.override(.gridLine, engine: themeEngine, contrast: contrast) - return QueryInsightsSection( - title: String(localized: "Activity"), - systemImage: "chart.bar.xaxis", - isEmpty: buckets.isEmpty, - emptyMessage: String(localized: "No queries in this range.") - ) { - Chart(segments) { segment in - BarMark( - x: .value(String(localized: "Date"), segment.date, unit: granularity.component), - y: .value(String(localized: "Queries"), segment.queryCount) - ) - .foregroundStyle(by: .value(String(localized: "Outcome"), segment.outcome)) - .accessibilityLabel(accessibilityLabel(for: segment)) - .accessibilityValue(segment.queryCount.formatted()) - } - .chartForegroundStyleScale([ - Outcome.succeeded: Color.accentColor, - Outcome.failed: Color.orange, - ]) - .chartLegend(position: .top, alignment: .trailing, spacing: 8) - .chartYAxis { - AxisMarks(position: .leading) { value in - if let gridLine { - AxisGridLine().foregroundStyle(gridLine) - } else { - AxisGridLine() - } - AxisValueLabel { - if let count = value.as(Int.self) { - Text(count.formatted()) - .monospacedDigit() - } - } + return Chart(segments) { segment in + BarMark( + x: .value(String(localized: "Date"), segment.date, unit: granularity.component), + y: .value(String(localized: "Queries"), segment.queryCount) + ) + .foregroundStyle(by: .value(String(localized: "Outcome"), segment.outcome)) + .accessibilityLabel(accessibilityLabel(for: segment)) + .accessibilityValue(segment.queryCount.formatted()) + } + .chartForegroundStyleScale([ + Outcome.succeeded: Color.accentColor, + Outcome.failed: Color.orange, + ]) + .chartLegend(position: .top, alignment: .trailing, spacing: 8) + .chartYAxis { + AxisMarks(position: .leading) { value in + if let gridLine { + AxisGridLine().foregroundStyle(gridLine) + } else { + AxisGridLine() } - } - .chartXAxis { - AxisMarks(values: .automatic(desiredCount: 6)) { _ in - if let gridLine { - AxisGridLine().foregroundStyle(gridLine) - } else { - AxisGridLine() + AxisValueLabel { + if let count = value.as(Int.self) { + Text(count.formatted()) + .monospacedDigit() } - AxisValueLabel(format: axisFormat, centered: false) } } - .chartPlotStyle { plotArea in - plotArea.themeBackground(.gridBackground, native: Color.clear, in: .rect(cornerRadius: 8)) + } + .chartXAxis { + AxisMarks(values: .automatic(desiredCount: 6)) { _ in + if let gridLine { + AxisGridLine().foregroundStyle(gridLine) + } else { + AxisGridLine() + } + AxisValueLabel(format: axisFormat, centered: false) } - .frame(height: 180) - .padding(.top, 4) } + .chartPlotStyle { plotArea in + plotArea.themeBackground(.gridBackground, native: Color.clear, in: .rect(cornerRadius: 8)) + } + .frame(height: 180) + .padding(.top, 4) } private var axisFormat: Date.FormatStyle { @@ -110,8 +103,7 @@ struct QueryInsightsActivityChart: View { } } -/// The shared frame every panel on the insights tab sits in, so a section that has nothing to show -/// still occupies its place with a reason rather than collapsing and shuffling the ones below it. +// An empty section keeps its place with a reason, so the sections below it never shuffle. struct QueryInsightsSection: View { let title: String let systemImage: String @@ -137,26 +129,26 @@ struct QueryInsightsSection: View { } var body: some View { - VStack(alignment: .leading, spacing: 8) { + GroupBox { + Group { + if isEmpty { + Text(emptyMessage) + .font(.callout) + .foregroundStyle(.secondary) + .padding(.vertical, 16) + } else { + content() + } + } + .frame(maxWidth: .infinity, alignment: .leading) + } label: { HStack(spacing: 8) { Label(title, systemImage: systemImage) .font(.headline) Spacer() accessory } - - if isEmpty { - Text(emptyMessage) - .font(.callout) - .foregroundStyle(.secondary) - .frame(maxWidth: .infinity, alignment: .leading) - .padding(.vertical, 16) - } else { - content() - } } - .padding(12) - .background(.quaternary.opacity(0.35), in: RoundedRectangle(cornerRadius: 10)) .padding(.horizontal, 16) } } diff --git a/apple/TablePro/Views/QueryInsights/QueryInsightsGroupList.swift b/apple/TablePro/Views/QueryInsights/QueryInsightsGroupList.swift index d15a42970e..8683acaf54 100644 --- a/apple/TablePro/Views/QueryInsights/QueryInsightsGroupList.swift +++ b/apple/TablePro/Views/QueryInsights/QueryInsightsGroupList.swift @@ -32,7 +32,6 @@ struct QueryInsightsGroupList: View { .font(.system(.callout, design: .monospaced)) .fontWeight(.medium) .monospacedDigit() - .foregroundStyle(headlineTint(group)) .frame(minWidth: 76, alignment: .trailing) VStack(alignment: .leading, spacing: 3) { @@ -47,10 +46,16 @@ struct QueryInsightsGroupList: View { .foregroundStyle(.secondary) if let error = group.latestErrorMessage, case .failures = metric { - RevealedTextView(error) - .font(.caption) - .foregroundStyle(.orange) - .lineLimit(2) + Label { + RevealedTextView(error) + .foregroundStyle(.secondary) + .lineLimit(2) + } icon: { + Image(systemName: NoticeSeverity.warning.symbolName) + .foregroundStyle(NoticeSeverity.warning.tint) + .accessibilityHidden(true) + } + .font(.caption) } } @@ -85,14 +90,6 @@ struct QueryInsightsGroupList: View { } } - private func headlineTint(_ group: QueryInsightsGroup) -> Color { - switch metric { - case .failures: return .orange - case .duration: return .primary - case .callCount: return .primary - } - } - private func subtitle(_ group: QueryInsightsGroup) -> String { var parts: [String] = [ String( @@ -161,7 +158,6 @@ struct QueryInsightsRegressionList: View { .font(.system(.callout, design: .monospaced)) .fontWeight(.medium) .monospacedDigit() - .foregroundStyle(.orange) .frame(minWidth: 76, alignment: .trailing) VStack(alignment: .leading, spacing: 3) { diff --git a/apple/TablePro/Views/QueryInsights/QueryInsightsSummaryBar.swift b/apple/TablePro/Views/QueryInsights/QueryInsightsSummaryBar.swift index dc489f5ad0..5054644156 100644 --- a/apple/TablePro/Views/QueryInsights/QueryInsightsSummaryBar.swift +++ b/apple/TablePro/Views/QueryInsights/QueryInsightsSummaryBar.swift @@ -62,28 +62,32 @@ struct QueryInsightsSummaryBar: View { systemImage: String, tint: Color ) -> some View { - VStack(alignment: .leading, spacing: 4) { - Label(label, systemImage: systemImage) + GroupBox { + VStack(alignment: .leading, spacing: 4) { + Label { + Text(label) + } icon: { + Image(systemName: systemImage) + .foregroundStyle(tint) + } .font(.caption) .foregroundStyle(.secondary) .labelStyle(.titleAndIcon) - Text(value) - .font(.title2) - .fontWeight(.medium) - .monospacedDigit() - .foregroundStyle(tint == .secondary ? Color.primary : tint) - .lineLimit(1) - .minimumScaleFactor(0.6) + Text(value) + .font(.title2) + .fontWeight(.medium) + .monospacedDigit() + .lineLimit(1) + .minimumScaleFactor(0.6) - Text(detail) - .font(.caption2) - .foregroundStyle(.tertiary) - .lineLimit(1) + Text(detail) + .font(.caption2) + .foregroundStyle(.tertiary) + .lineLimit(1) + } + .frame(maxWidth: .infinity, alignment: .leading) } - .frame(maxWidth: .infinity, alignment: .leading) - .padding(10) - .background(.quaternary.opacity(0.5), in: RoundedRectangle(cornerRadius: 8)) .accessibilityElement(children: .combine) .accessibilityLabel("\(label): \(value), \(detail)") } diff --git a/apple/TablePro/Views/QueryInsights/QueryInsightsView.swift b/apple/TablePro/Views/QueryInsights/QueryInsightsView.swift index 80dca7f58f..9d84bed533 100644 --- a/apple/TablePro/Views/QueryInsights/QueryInsightsView.swift +++ b/apple/TablePro/Views/QueryInsights/QueryInsightsView.swift @@ -80,10 +80,17 @@ struct QueryInsightsView: View { LazyVStack(alignment: .leading, spacing: 12) { QueryInsightsSummaryBar(totals: viewModel.snapshot.totals) - QueryInsightsActivityChart( - buckets: viewModel.snapshot.activity, - granularity: viewModel.snapshot.granularity - ) + QueryInsightsSection( + title: String(localized: "Activity"), + systemImage: "chart.bar.xaxis", + isEmpty: viewModel.snapshot.activity.isEmpty, + emptyMessage: String(localized: "No queries in this range.") + ) { + QueryInsightsActivityChart( + buckets: viewModel.snapshot.activity, + granularity: viewModel.snapshot.granularity + ) + } QueryInsightsSection( title: String(localized: "Most Run"), diff --git a/apple/TablePro/Views/QuickSwitcher/QuickSwitcherPanelView.swift b/apple/TablePro/Views/QuickSwitcher/QuickSwitcherPanelView.swift index 73b026d8f4..c18dec0af5 100644 --- a/apple/TablePro/Views/QuickSwitcher/QuickSwitcherPanelView.swift +++ b/apple/TablePro/Views/QuickSwitcher/QuickSwitcherPanelView.swift @@ -341,11 +341,9 @@ struct QuickSwitcherPanelContent: View { if item.isOpenInTab, !isSelected { Text(String(localized: "Open")) - .font(.caption2.weight(.medium)) + .font(.caption2) .foregroundStyle(secondaryColor) - .padding(.horizontal, 5) - .padding(.vertical, 1) - .background(Capsule().fill(Color(nsColor: .quaternaryFill))) + .lineLimit(1) } if showsSubtitle(for: item, isSelected: isSelected) { diff --git a/apple/TablePro/Views/QuickSwitcher/QuickSwitcherRowChrome.swift b/apple/TablePro/Views/QuickSwitcher/QuickSwitcherRowChrome.swift index a40ef8b2b6..78e6e5f283 100644 --- a/apple/TablePro/Views/QuickSwitcher/QuickSwitcherRowChrome.swift +++ b/apple/TablePro/Views/QuickSwitcher/QuickSwitcherRowChrome.swift @@ -45,17 +45,9 @@ internal struct QuickSwitcherKeyHint: View { } } } - .font(.caption.weight(.medium)) - .foregroundStyle(.secondary) - .padding(.horizontal, 5) - .frame(minWidth: 20, minHeight: 17) - .background( - RoundedRectangle(cornerRadius: 4, style: .continuous) - .fill(Color(nsColor: .quaternaryFill)) - ) Text(label) - .font(.caption) - .foregroundStyle(.secondary) } + .font(.caption) + .foregroundStyle(.secondary) } } diff --git a/apple/TablePro/Views/Results/ColumnJumpPanelView.swift b/apple/TablePro/Views/Results/ColumnJumpPanelView.swift index d5404f6b96..20184da9ba 100644 --- a/apple/TablePro/Views/Results/ColumnJumpPanelView.swift +++ b/apple/TablePro/Views/Results/ColumnJumpPanelView.swift @@ -160,11 +160,9 @@ struct ColumnJumpPanelContent: View { if entry.isHidden { Text(String(localized: "Hidden")) - .font(.caption2.weight(.medium)) + .font(.caption2) .foregroundStyle(secondaryColor) - .padding(.horizontal, 5) - .padding(.vertical, 1) - .background(Capsule().fill(Color(nsColor: .quaternaryFill))) + .lineLimit(1) } else if let position = entry.position { Text(positionLabel(position)) .font(.callout) diff --git a/apple/TablePro/Views/Results/ForeignKeyPickerView.swift b/apple/TablePro/Views/Results/ForeignKeyPickerView.swift index ee1e6910c0..91c25aeda8 100644 --- a/apple/TablePro/Views/Results/ForeignKeyPickerView.swift +++ b/apple/TablePro/Views/Results/ForeignKeyPickerView.swift @@ -141,10 +141,16 @@ struct ForeignKeyPickerView: View { @ViewBuilder private var content: some View { if let errorMessage { - RevealedTextView(errorMessage) - .foregroundStyle(.red) - .font(.callout) - .frame(maxWidth: .infinity, alignment: .leading) + Label { + RevealedTextView(errorMessage) + .foregroundStyle(.secondary) + } icon: { + Image(systemName: NoticeSeverity.error.symbolName) + .foregroundStyle(NoticeSeverity.error.tint) + .accessibilityHidden(true) + } + .font(.callout) + .frame(maxWidth: .infinity, alignment: .leading) .padding(10) .frame(height: Self.listHeight) } else if entries.isEmpty { diff --git a/apple/TablePro/Views/Results/ForeignKeyPreviewView.swift b/apple/TablePro/Views/Results/ForeignKeyPreviewView.swift index d836ab5156..0aeedb25ae 100644 --- a/apple/TablePro/Views/Results/ForeignKeyPreviewView.swift +++ b/apple/TablePro/Views/Results/ForeignKeyPreviewView.swift @@ -104,10 +104,16 @@ struct ForeignKeyPreviewView: View { .frame(maxWidth: .infinity, alignment: .center) .frame(height: 60) } else if let errorMessage { - RevealedTextView(errorMessage) - .foregroundStyle(.red) - .font(.callout) - .padding(10) + Label { + RevealedTextView(errorMessage) + .foregroundStyle(.secondary) + } icon: { + Image(systemName: NoticeSeverity.error.symbolName) + .foregroundStyle(NoticeSeverity.error.tint) + .accessibilityHidden(true) + } + .font(.callout) + .padding(10) } else if values.isEmpty { Text("Referenced row not found") .foregroundStyle(.secondary) diff --git a/apple/TablePro/Views/Results/HexEditorContentView.swift b/apple/TablePro/Views/Results/HexEditorContentView.swift index b6f8e494e7..a200b5f95e 100644 --- a/apple/TablePro/Views/Results/HexEditorContentView.swift +++ b/apple/TablePro/Views/Results/HexEditorContentView.swift @@ -100,11 +100,10 @@ struct HexEditorBody: View { if sourceIsTruncated || isTruncated { Text(String(localized: "Truncated, read only")) .font(.caption) - .foregroundStyle(.orange) + .foregroundStyle(.secondary) } else if !isValid, !editableHex.isEmpty { - Text(String(localized: "Invalid hex")) + NoticeLabel(String(localized: "Invalid hex"), severity: .error) .font(.caption) - .foregroundStyle(.red) } Spacer() diff --git a/apple/TablePro/Views/Results/InlineErrorBanner.swift b/apple/TablePro/Views/Results/InlineErrorBanner.swift index c688976a06..266370a7e6 100644 --- a/apple/TablePro/Views/Results/InlineErrorBanner.swift +++ b/apple/TablePro/Views/Results/InlineErrorBanner.swift @@ -2,8 +2,6 @@ // InlineErrorBanner.swift // TablePro // -// Dismissable red error banner for query errors, displayed inline above results. -// import AppKit import SwiftUI @@ -12,6 +10,8 @@ struct InlineErrorBanner: View { let message: String var onFixWithAI: (() -> Void)? var onDismiss: (() -> Void)? + // A sheet footer shows it without the pane bar material. + var onBar = true private let maxMessageHeight: CGFloat = 96 private let minMessageHeight: CGFloat = 16 @@ -21,12 +21,16 @@ struct InlineErrorBanner: View { private var messageFits: Bool { messageHeight <= shownHeight + 0.5 } var body: some View { - HStack(alignment: .top, spacing: 8) { - Image(systemName: "exclamationmark.triangle.fill") - .foregroundStyle(.red) + PaneNoticeBar( + severity: .error, + alignment: .top, + onBar: onBar, + dismissLabel: String(localized: "Dismiss error"), + onDismiss: onDismiss + ) { ScrollView(.vertical) { RevealedTextView(message) - .font(.subheadline) + .font(.callout) .textSelection(.enabled) .frame(maxWidth: .infinity, alignment: .leading) .accessibilityIdentifier("query-error-message") @@ -48,33 +52,12 @@ struct InlineErrorBanner: View { } .scrollDisabled(messageFits) .scrollBounceBasedOnSize() + } actions: { if let onFixWithAI { - Button(String(localized: "Fix with AI")) { onFixWithAI() } - .controlSize(.small) - } - Button { - ClipboardService.shared.writeText(message) - } label: { - Image(systemName: "doc.on.doc") - .frame(width: 24, height: 24) - .foregroundStyle(.secondary) - } - .buttonStyle(.plain) - .help(String(localized: "Copy error message")) - .accessibilityLabel(String(localized: "Copy error message")) - if let onDismiss { - Button { onDismiss() } label: { - Image(systemName: "xmark") - .frame(width: 24, height: 24) - .foregroundStyle(.secondary) - } - .buttonStyle(.plain) - .accessibilityLabel(String(localized: "Dismiss error")) + Button(String(localized: "Fix with AI"), action: onFixWithAI) } + PaneNoticeCopyButton(text: message, label: String(localized: "Copy error message")) } - .padding(.horizontal, 12) - .padding(.vertical, 8) - .background(.red.opacity(0.08)) } } diff --git a/apple/TablePro/Views/Results/TreeOutline/TreeOutlineAccessoryViews.swift b/apple/TablePro/Views/Results/TreeOutline/TreeOutlineAccessoryViews.swift index f873640801..5fceb4bed1 100644 --- a/apple/TablePro/Views/Results/TreeOutline/TreeOutlineAccessoryViews.swift +++ b/apple/TablePro/Views/Results/TreeOutline/TreeOutlineAccessoryViews.swift @@ -70,11 +70,8 @@ internal final class TreeColorSwatchView: NSView { } internal final class TreeBadgeView: NSView { - private static let horizontalPadding: CGFloat = 6 - private static let verticalPadding: CGFloat = 1 - private static var font: NSFont { - .systemFont(ofSize: NSFont.preferredFont(forTextStyle: .caption2).pointSize, weight: .medium) + .preferredFont(forTextStyle: .caption2) } internal var text = "" { @@ -94,22 +91,15 @@ internal final class TreeBadgeView: NSView { override internal var intrinsicContentSize: NSSize { let size = (text as NSString).size(withAttributes: [.font: Self.font]) - return NSSize( - width: ceil(size.width) + 2 * Self.horizontalPadding, - height: ceil(size.height) + 2 * Self.verticalPadding - ) + return NSSize(width: ceil(size.width), height: ceil(size.height)) } override internal func draw(_ dirtyRect: NSRect) { - let selectedText = NSColor.alternateSelectedControlTextColor - let fill = isOnEmphasizedRow ? selectedText.withAlphaComponent(0.2) : NSColor.quaternaryLabelColor - fill.setFill() - let radius = bounds.height / 2 - NSBezierPath(roundedRect: bounds, xRadius: radius, yRadius: radius).fill() - let attributes: [NSAttributedString.Key: Any] = [ .font: Self.font, - .foregroundColor: isOnEmphasizedRow ? selectedText.withAlphaComponent(0.8) : NSColor.tertiaryLabelColor + .foregroundColor: isOnEmphasizedRow + ? NSColor.alternateSelectedControlTextColor.withAlphaComponent(0.8) + : NSColor.tertiaryLabelColor ] let size = (text as NSString).size(withAttributes: attributes) let origin = NSPoint(x: bounds.midX - size.width / 2, y: bounds.midY - size.height / 2) diff --git a/apple/TablePro/Views/RowInspector/FieldEditors/BlobHexEditorView.swift b/apple/TablePro/Views/RowInspector/FieldEditors/BlobHexEditorView.swift index 61f1e31fe2..0a3583e812 100644 --- a/apple/TablePro/Views/RowInspector/FieldEditors/BlobHexEditorView.swift +++ b/apple/TablePro/Views/RowInspector/FieldEditors/BlobHexEditorView.swift @@ -103,11 +103,10 @@ internal struct BlobHexEditorView: View { if isTruncated { Text("Truncated, read only") .font(.caption2) - .foregroundStyle(.orange) + .foregroundStyle(.secondary) } else if BlobFormattingService.shared.parseHex(hexEditText) == nil, !hexEditText.isEmpty { - Text("Invalid hex") + NoticeLabel(String(localized: "Invalid hex"), severity: .error) .font(.caption2) - .foregroundStyle(.red) } } } diff --git a/apple/TablePro/Views/RowInspector/FieldEditors/JsonEditorView.swift b/apple/TablePro/Views/RowInspector/FieldEditors/JsonEditorView.swift index 231f0c5d11..509332cab1 100644 --- a/apple/TablePro/Views/RowInspector/FieldEditors/JsonEditorView.swift +++ b/apple/TablePro/Views/RowInspector/FieldEditors/JsonEditorView.swift @@ -31,40 +31,44 @@ internal struct JsonEditorView: View { } var body: some View { - ResizableEditorContainer( - column: context.columnName, - defaultHeight: ResizableFieldMetrics.defaultJsonHeight, - range: ResizableFieldMetrics.jsonHeightRange, - expandedHeight: isExpanded ? ResizableFieldMetrics.expandedHeight : nil - ) { - JSONCodeEditor( - text: editorText, - isEditable: !context.isReadOnly, - accessibilityIdentifier: "inspector-json-field" - ) - .valueWell(clipsContent: true) - .overlay(alignment: .bottomTrailing) { actionButtons } + VStack(alignment: .leading, spacing: 2) { + if let onPopOut { + header(onPopOut: onPopOut) + } + ResizableEditorContainer( + column: context.columnName, + defaultHeight: ResizableFieldMetrics.defaultJsonHeight, + range: ResizableFieldMetrics.jsonHeightRange, + expandedHeight: isExpanded ? ResizableFieldMetrics.expandedHeight : nil + ) { + JSONCodeEditor( + text: editorText, + isEditable: !context.isReadOnly, + accessibilityIdentifier: "inspector-json-field" + ) + .valueWell(clipsContent: true) + } } + // On a bare container the row's accessibility value lands on the Open in Window button too. + .accessibilityElement(children: .contain) // `newValue`, never `context.value`: the action's context is a render behind and undid every keystroke (#3051). .onChange(of: context.value.wrappedValue) { newValue in _ = model.received(newValue) } } - private var actionButtons: some View { - HStack(spacing: 2) { - if let onPopOut { - Button { onPopOut(model.displayText) } label: { - Image(systemName: "arrow.up.forward.app") - .font(.caption2) - .padding(4) - .themeMaterial(.inlineControl, .ultraThinMaterial, in: RoundedRectangle(cornerRadius: 4)) - } - .buttonStyle(.borderless) - .help(String(localized: "Open in Window")) - .accessibilityLabel(String(localized: "Open in Window")) + private func header(onPopOut: @escaping (String) -> Void) -> some View { + HStack(spacing: 8) { + Spacer(minLength: 4) + Button(String(localized: "Open in Window"), systemImage: "arrow.up.forward.app") { + onPopOut(model.displayText) } + .labelStyle(.iconOnly) + .buttonStyle(.borderless) + .controlSize(.small) + .font(.caption) + .help(String(localized: "Open in Window")) + .accessibilityLabel(String(localized: "Open in Window")) } - .padding(4) } } diff --git a/apple/TablePro/Views/RowInspector/FieldEditors/MultiLineEditorView.swift b/apple/TablePro/Views/RowInspector/FieldEditors/MultiLineEditorView.swift index b324f11faf..31b682b5ec 100644 --- a/apple/TablePro/Views/RowInspector/FieldEditors/MultiLineEditorView.swift +++ b/apple/TablePro/Views/RowInspector/FieldEditors/MultiLineEditorView.swift @@ -13,24 +13,30 @@ internal struct MultiLineEditorView: View { var isExpanded = false var body: some View { - ResizableEditorContainer( - column: context.columnName, - defaultHeight: ResizableFieldMetrics.defaultTextHeight, - range: ResizableFieldMetrics.textHeightRange, - expandedHeight: isExpanded ? ResizableFieldMetrics.expandedHeight : nil - ) { - TextValueEditor( - text: context.value, - isEditable: !context.isReadOnly, - font: themeEngine.valueFont, - movesFocusOnTab: true, - style: .code, - marksInvisibleCharacters: settingsManager.dataGrid.showInvisibleCharacters - ) - .valueWell(clipsContent: true) - .overlay(alignment: .topLeading) { placeholder } - .overlay(alignment: .bottomTrailing) { popOutButton } + VStack(alignment: .leading, spacing: 2) { + if let onPopOut { + header(onPopOut: onPopOut) + } + ResizableEditorContainer( + column: context.columnName, + defaultHeight: ResizableFieldMetrics.defaultTextHeight, + range: ResizableFieldMetrics.textHeightRange, + expandedHeight: isExpanded ? ResizableFieldMetrics.expandedHeight : nil + ) { + TextValueEditor( + text: context.value, + isEditable: !context.isReadOnly, + font: themeEngine.valueFont, + movesFocusOnTab: true, + style: .code, + marksInvisibleCharacters: settingsManager.dataGrid.showInvisibleCharacters + ) + .valueWell(clipsContent: true) + .overlay(alignment: .topLeading) { placeholder } + } } + // On a bare container the row's accessibility value lands on the Open in Window button too. + .accessibilityElement(children: .contain) } @ViewBuilder @@ -44,19 +50,18 @@ internal struct MultiLineEditorView: View { } } - @ViewBuilder - private var popOutButton: some View { - if let onPopOut { - Button { onPopOut(context.value.wrappedValue) } label: { - Image(systemName: "arrow.up.forward.app") - .font(.caption2) - .padding(4) - .themeMaterial(.inlineControl, .ultraThinMaterial, in: RoundedRectangle(cornerRadius: 4)) + private func header(onPopOut: @escaping (String) -> Void) -> some View { + HStack(spacing: 8) { + Spacer(minLength: 4) + Button(String(localized: "Open in Window"), systemImage: "arrow.up.forward.app") { + onPopOut(context.value.wrappedValue) } + .labelStyle(.iconOnly) .buttonStyle(.borderless) + .controlSize(.small) + .font(.caption) .help(String(localized: "Open in Window")) .accessibilityLabel(String(localized: "Open in Window")) - .padding(4) } } } diff --git a/apple/TablePro/Views/ServerDashboard/DashboardTileView.swift b/apple/TablePro/Views/ServerDashboard/DashboardTileView.swift index 6c60afd7c3..36a0b9b3e5 100644 --- a/apple/TablePro/Views/ServerDashboard/DashboardTileView.swift +++ b/apple/TablePro/Views/ServerDashboard/DashboardTileView.swift @@ -20,18 +20,18 @@ struct DashboardTileView: View { @State private var isDropTarget = false var body: some View { - VStack(alignment: .leading, spacing: 6) { - header - content - .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) - footer + GroupBox { + VStack(alignment: .leading, spacing: 6) { + header + content + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading) + footer + } } - .padding(10) .frame(height: 168) - .background(.quaternary.opacity(0.5), in: RoundedRectangle(cornerRadius: 8)) .overlay { if isDropTarget { - RoundedRectangle(cornerRadius: 8) + RoundedRectangle(cornerRadius: 6) .strokeBorder(Color.accentColor, lineWidth: 2) } } @@ -113,11 +113,13 @@ struct DashboardTileView: View { Label { RevealedTextView(message) .lineLimit(lineLimit) + .foregroundStyle(.secondary) } icon: { - Image(systemName: "exclamationmark.triangle") + Image(systemName: NoticeSeverity.error.symbolName) + .foregroundStyle(NoticeSeverity.error.tint) + .accessibilityHidden(true) } .font(.caption) - .foregroundStyle(.red) .help(RevealedText(message).plainText) } diff --git a/apple/TablePro/Views/ServerDashboard/DashboardToolbarView.swift b/apple/TablePro/Views/ServerDashboard/DashboardToolbarView.swift index a7eea66297..b95c84742a 100644 --- a/apple/TablePro/Views/ServerDashboard/DashboardToolbarView.swift +++ b/apple/TablePro/Views/ServerDashboard/DashboardToolbarView.swift @@ -62,9 +62,9 @@ struct DashboardToolbarView: View { Text(viewModel.databaseType.rawValue) .font(.caption) - .padding(.horizontal, 6) - .padding(.vertical, 2) - .background(.quaternary, in: Capsule()) + .foregroundStyle(.secondary) + .lineLimit(1) + .fixedSize() } .padding(.horizontal, 12) .padding(.vertical, 6) diff --git a/apple/TablePro/Views/ServerDashboard/MetricsBarView.swift b/apple/TablePro/Views/ServerDashboard/MetricsBarView.swift index 89f4c503d6..ff877ded32 100644 --- a/apple/TablePro/Views/ServerDashboard/MetricsBarView.swift +++ b/apple/TablePro/Views/ServerDashboard/MetricsBarView.swift @@ -13,11 +13,13 @@ struct MetricsBarView: View { if let error { Label { RevealedTextView(error) + .foregroundStyle(.secondary) } icon: { - Image(systemName: "exclamationmark.triangle") + Image(systemName: NoticeSeverity.error.symbolName) + .foregroundStyle(NoticeSeverity.error.tint) + .accessibilityHidden(true) } .font(.caption) - .foregroundStyle(.red) } } .padding(.horizontal, 12) @@ -41,30 +43,29 @@ struct MetricsBarView: View { } private func metricCard(_ metric: DashboardMetric) -> some View { - HStack(spacing: 8) { - Image(systemName: metric.icon) - .foregroundStyle(.secondary) - .frame(width: 16) - - VStack(alignment: .leading, spacing: 2) { - Text(metric.label) - .font(.caption) + GroupBox { + HStack(spacing: 8) { + Image(systemName: metric.icon) .foregroundStyle(.secondary) - HStack(alignment: .firstTextBaseline, spacing: 2) { - Text(metric.value) - .font(.system(.body, design: .monospaced)) - .fontWeight(.medium) - .monospacedDigit() - if !metric.unit.isEmpty { - Text(metric.unit) - .font(.caption2) - .foregroundStyle(.tertiary) + .frame(width: 16) + + VStack(alignment: .leading, spacing: 2) { + Text(metric.label) + .font(.caption) + .foregroundStyle(.secondary) + HStack(alignment: .firstTextBaseline, spacing: 2) { + Text(metric.value) + .font(.system(.body, design: .monospaced)) + .fontWeight(.medium) + .monospacedDigit() + if !metric.unit.isEmpty { + Text(metric.unit) + .font(.caption2) + .foregroundStyle(.tertiary) + } } } } } - .padding(.horizontal, 10) - .padding(.vertical, 6) - .background(.quaternary.opacity(0.5), in: RoundedRectangle(cornerRadius: 6)) } } diff --git a/apple/TablePro/Views/ServerDashboard/SessionsTableView.swift b/apple/TablePro/Views/ServerDashboard/SessionsTableView.swift index f054023658..fb19bff02f 100644 --- a/apple/TablePro/Views/ServerDashboard/SessionsTableView.swift +++ b/apple/TablePro/Views/ServerDashboard/SessionsTableView.swift @@ -30,11 +30,13 @@ internal struct SessionsTableView: View { if let error = viewModel.panelErrors[.activeSessions] { Label { RevealedTextView(error) + .foregroundStyle(.secondary) } icon: { - Image(systemName: "exclamationmark.triangle") + Image(systemName: NoticeSeverity.error.symbolName) + .foregroundStyle(NoticeSeverity.error.tint) + .accessibilityHidden(true) } .font(.caption) - .foregroundStyle(.red) } sessionActions } diff --git a/apple/TablePro/Views/ServerDashboard/SlowQueryListView.swift b/apple/TablePro/Views/ServerDashboard/SlowQueryListView.swift index eb9f91a1fd..cdf81f67c6 100644 --- a/apple/TablePro/Views/ServerDashboard/SlowQueryListView.swift +++ b/apple/TablePro/Views/ServerDashboard/SlowQueryListView.swift @@ -21,11 +21,13 @@ internal struct SlowQueryListView: View { if let error { Label { RevealedTextView(error) + .foregroundStyle(.secondary) } icon: { - Image(systemName: "exclamationmark.triangle.fill") + Image(systemName: NoticeSeverity.warning.symbolName) + .foregroundStyle(NoticeSeverity.warning.tint) + .accessibilityHidden(true) } .font(.caption) - .foregroundStyle(.orange) } } .padding(.horizontal, 12) diff --git a/apple/TablePro/Views/Settings/Appearance/ThemeEditorView.swift b/apple/TablePro/Views/Settings/Appearance/ThemeEditorView.swift index 92597541e5..e16232a3b6 100644 --- a/apple/TablePro/Views/Settings/Appearance/ThemeEditorView.swift +++ b/apple/TablePro/Views/Settings/Appearance/ThemeEditorView.swift @@ -124,10 +124,8 @@ internal struct ThemeEditorView: View { } private func fieldError(_ message: String, identifier: String) -> some View { - Text(message) + NoticeLabel(message, severity: .error) .font(.callout) - .foregroundStyle(.red) - .fixedSize(horizontal: false, vertical: true) .accessibilityIdentifier(identifier) } diff --git a/apple/TablePro/Views/Settings/Appearance/ThemeLibrarySection.swift b/apple/TablePro/Views/Settings/Appearance/ThemeLibrarySection.swift index 4409346595..e5da101404 100644 --- a/apple/TablePro/Views/Settings/Appearance/ThemeLibrarySection.swift +++ b/apple/TablePro/Views/Settings/Appearance/ThemeLibrarySection.swift @@ -180,10 +180,8 @@ internal struct ThemeLibrarySection: View { } .accessibilityIdentifier("appearance-theme-rename-field") if let renameError { - Text(renameError) + NoticeLabel(renameError, severity: .error) .font(.caption) - .foregroundStyle(.red) - .fixedSize(horizontal: false, vertical: true) .accessibilityIdentifier("appearance-theme-rename-error") } } diff --git a/apple/TablePro/Views/Settings/Components/IntegrationStatusIndicator.swift b/apple/TablePro/Views/Settings/Components/IntegrationStatusIndicator.swift index 34e9a38f16..41638da0da 100644 --- a/apple/TablePro/Views/Settings/Components/IntegrationStatusIndicator.swift +++ b/apple/TablePro/Views/Settings/Components/IntegrationStatusIndicator.swift @@ -41,7 +41,7 @@ struct IntegrationStatusIndicator: View { case .stopped: return "stop.circle.fill" case .starting: - return "clock.fill" + return "clock" case .failed, .error, .revoked: return "xmark.circle.fill" case .warning: @@ -55,10 +55,8 @@ struct IntegrationStatusIndicator: View { switch status { case .running, .success, .active: return .green - case .stopped: + case .stopped, .starting: return Color(nsColor: .secondaryLabelColor) - case .starting: - return .orange case .failed, .error: return .red case .warning, .expired: diff --git a/apple/TablePro/Views/Settings/CustomSlashCommandsSection.swift b/apple/TablePro/Views/Settings/CustomSlashCommandsSection.swift index 48257b3d6e..4c9b2a599c 100644 --- a/apple/TablePro/Views/Settings/CustomSlashCommandsSection.swift +++ b/apple/TablePro/Views/Settings/CustomSlashCommandsSection.swift @@ -146,12 +146,11 @@ struct CustomSlashCommandEditorSheet: View { } } footer: { if SlashCommand.isBuiltIn(name: draft.name) { - Text(String( + NoticeLabel(String( format: String(localized: "/%@ is a built-in command. Typing it runs the built-in; this one runs only from the command menu."), draft.name.trimmingCharacters(in: .whitespaces).lowercased() )) .font(.caption) - .foregroundStyle(.orange) } } Section { diff --git a/apple/TablePro/Views/Settings/Profiles/CredentialProfileEditorSheet.swift b/apple/TablePro/Views/Settings/Profiles/CredentialProfileEditorSheet.swift index 2dc3c51e75..cea90a444d 100644 --- a/apple/TablePro/Views/Settings/Profiles/CredentialProfileEditorSheet.swift +++ b/apple/TablePro/Views/Settings/Profiles/CredentialProfileEditorSheet.swift @@ -79,12 +79,8 @@ struct CredentialProfileEditorSheet: View { TextField(String(localized: "Name"), text: $name, prompt: Text("Production reader")) .accessibilityIdentifier("credential-profile-name") if !trimmedName.isEmpty && !nameIsUnique { - Label( - String(localized: "Another profile already has this name."), - systemImage: "exclamationmark.triangle.fill" - ) - .font(.caption) - .foregroundStyle(.yellow) + NoticeLabel(String(localized: "Another profile already has this name.")) + .font(.caption) } TextField( String(localized: "Username"), @@ -97,12 +93,10 @@ struct CredentialProfileEditorSheet: View { if !secretsWereReadable { Section { - Label( - String(localized: "The Keychain could not be read, so the stored secrets are not shown. Editing the name is safe; they are left as they are."), - systemImage: "exclamationmark.triangle.fill" + NoticeLabel( + String(localized: "The Keychain could not be read, so the stored secrets are not shown. Editing the name is safe; they are left as they are.") ) .font(.caption) - .foregroundStyle(.yellow) } } passwordSection @@ -356,9 +350,8 @@ struct CredentialProfileEditorSheet: View { } if let saveError { - Label(saveError, systemImage: "exclamationmark.triangle.fill") + NoticeLabel(saveError, severity: .error) .font(.caption) - .foregroundStyle(.red) .lineLimit(2) } diff --git a/apple/TablePro/Views/Settings/Sections/DataGridSection.swift b/apple/TablePro/Views/Settings/Sections/DataGridSection.swift index d4b94ba4e9..38533e8a2b 100644 --- a/apple/TablePro/Views/Settings/Sections/DataGridSection.swift +++ b/apple/TablePro/Views/Settings/Sections/DataGridSection.swift @@ -27,9 +27,8 @@ struct DataGridSection: View { .help("Max \(SettingsValidationRules.nullDisplayMaxLength) characters") if let error = settings.nullDisplayValidationError { - Text(error) + NoticeLabel(error, severity: .error) .font(.caption) - .foregroundStyle(.red) } } @@ -107,9 +106,8 @@ struct DataGridSection: View { } if let error = settings.queryResultRowCapValidationError { - Text(error) + NoticeLabel(error, severity: .error) .font(.caption) - .foregroundStyle(.red) } } } header: { diff --git a/apple/TablePro/Views/Settings/Sections/MCPOutsideServerSheet.swift b/apple/TablePro/Views/Settings/Sections/MCPOutsideServerSheet.swift index 0fdff475b5..c957e0ccbf 100644 --- a/apple/TablePro/Views/Settings/Sections/MCPOutsideServerSheet.swift +++ b/apple/TablePro/Views/Settings/Sections/MCPOutsideServerSheet.swift @@ -66,9 +66,8 @@ internal struct MCPOutsideServerSheet: View { Text("Server") } footer: { if let validationError { - Text(message(for: validationError)) + NoticeLabel(message(for: validationError), severity: .error) .font(.caption) - .foregroundStyle(.red) } else { Text("The address has to be HTTPS unless the server runs on this Mac. The token is kept in your Keychain and never synced.") .font(.caption) @@ -89,9 +88,8 @@ internal struct MCPOutsideServerSheet: View { .font(.callout) .foregroundStyle(.secondary) case .failed(let message): - Text(message) + NoticeLabel(message, severity: .error) .font(.callout) - .foregroundStyle(.red) .lineLimit(2) } } diff --git a/apple/TablePro/Views/Settings/Sections/PairingApprovalSheet.swift b/apple/TablePro/Views/Settings/Sections/PairingApprovalSheet.swift index 8071838ce3..08ed74db2d 100644 --- a/apple/TablePro/Views/Settings/Sections/PairingApprovalSheet.swift +++ b/apple/TablePro/Views/Settings/Sections/PairingApprovalSheet.swift @@ -125,7 +125,7 @@ struct PairingApprovalSheet: View { Text(countdownText) .font(.caption) .monospacedDigit() - .foregroundStyle(isExpired ? .red : .secondary) + .foregroundStyle(.secondary) .contentTransition(.numericText()) } } diff --git a/apple/TablePro/Views/Shared/FieldDrivenList.swift b/apple/TablePro/Views/Shared/FieldDrivenList.swift index 24dd13fccf..e6bc31406a 100644 --- a/apple/TablePro/Views/Shared/FieldDrivenList.swift +++ b/apple/TablePro/Views/Shared/FieldDrivenList.swift @@ -9,15 +9,11 @@ import SwiftUI internal struct FieldDrivenListSection: Identifiable { internal let id: String internal let title: String? - /// Drawn as a dot beside the title, for a section that stands for something the user gave a - /// colour to. Nil leaves the header as a plain label. - internal let accentColor: NSColor? internal let items: [Item] - internal init(id: String, title: String? = nil, accentColor: NSColor? = nil, items: [Item]) { + internal init(id: String, title: String? = nil, items: [Item]) { self.id = id self.title = title - self.accentColor = accentColor self.items = items } } @@ -217,8 +213,8 @@ internal struct FieldDrivenList: NSViewRepresenta internal func tableView(_ tableView: NSTableView, viewFor column: NSTableColumn?, row: Int) -> NSView? { guard row < entries.count else { return nil } switch entries[row] { - case .header(_, let title, let accentColor): - return FieldDrivenHeaderView.make(title: title, accentColor: accentColor) + case .header(_, let title): + return FieldDrivenHeaderView.make(title: title) case .item(let item): let cell = tableView.makeView( withIdentifier: FieldDrivenCellView.reuseIdentifier, @@ -487,9 +483,7 @@ internal final class FieldDrivenCellView: NSTableCellView { } internal enum FieldDrivenHeaderView { - private static let dotSize: CGFloat = 6 - - internal static func make(title: String, accentColor: NSColor? = nil) -> NSView { + internal static func make(title: String) -> NSView { let label = NSTextField(labelWithString: title) label.font = .preferredFont(forTextStyle: .caption1) label.textColor = .secondaryLabelColor @@ -498,46 +492,10 @@ internal enum FieldDrivenHeaderView { let container = NSView() container.addSubview(label) NSLayoutConstraint.activate([ + label.leadingAnchor.constraint(equalTo: container.leadingAnchor, constant: 4), label.trailingAnchor.constraint(lessThanOrEqualTo: container.trailingAnchor), label.centerYAnchor.constraint(equalTo: container.centerYAnchor), ]) - - guard let accentColor else { - label.leadingAnchor.constraint(equalTo: container.leadingAnchor, constant: 4).isActive = true - return container - } - - let dot = ColorDotView(color: accentColor) - dot.translatesAutoresizingMaskIntoConstraints = false - container.addSubview(dot) - NSLayoutConstraint.activate([ - dot.leadingAnchor.constraint(equalTo: container.leadingAnchor, constant: 4), - dot.centerYAnchor.constraint(equalTo: label.centerYAnchor), - dot.widthAnchor.constraint(equalToConstant: dotSize), - dot.heightAnchor.constraint(equalToConstant: dotSize), - label.leadingAnchor.constraint(equalTo: dot.trailingAnchor, constant: 5), - ]) return container } } - -/// A dot that repaints itself when the appearance changes, because a dynamic system colour -/// resolved once into a layer stays at the appearance it was resolved in. -private final class ColorDotView: NSView { - private let color: NSColor - - init(color: NSColor) { - self.color = color - super.init(frame: .zero) - } - - @available(*, unavailable) - required init?(coder: NSCoder) { - fatalError("ColorDotView does not support NSCoder init") - } - - override func draw(_ dirtyRect: NSRect) { - color.setFill() - NSBezierPath(ovalIn: bounds).fill() - } -} diff --git a/apple/TablePro/Views/Shared/FieldDrivenListEntry.swift b/apple/TablePro/Views/Shared/FieldDrivenListEntry.swift index 242a236638..4a8d47da6c 100644 --- a/apple/TablePro/Views/Shared/FieldDrivenListEntry.swift +++ b/apple/TablePro/Views/Shared/FieldDrivenListEntry.swift @@ -3,12 +3,11 @@ // TablePro // -import AppKit +import Foundation -/// One row of a `FieldDrivenList`, after sections have been flattened into the single index space -/// an `NSTableView` works in. +// A `FieldDrivenList` row after sections are flattened into the single index space an `NSTableView` works in. internal enum FieldDrivenListEntry where Item.ID: Hashable { - case header(id: String, title: String, accentColor: NSColor?) + case header(id: String, title: String) case item(Item) internal var isHeader: Bool { @@ -21,29 +20,23 @@ internal enum FieldDrivenListEntry where Item.ID: Hashable { return item.id } - /// Identity, not content. A refilter that produces the same rows in the same order reloads - /// nothing, which keeps the hosted SwiftUI views and their state alive. - /// - /// A header is the exception: only item rows are refreshed in place, so a header identified by - /// its section id alone would keep a group's old name and colour on screen after a rename - /// arrives from another device. Its drawn content is part of what identifies it. + // Only item rows refresh in place, so a header's title is part of its identity: a rename from another device redraws it. internal var identity: AnyHashable { switch self { - case .header(let id, let title, let accentColor): - return AnyHashable(HeaderIdentity(id: id, title: title, accentColor: accentColor)) + case .header(let id, let title): + return AnyHashable(HeaderIdentity(id: id, title: title)) case .item(let item): return AnyHashable(item.id) } } - /// A section contributes a header only when it is named and has something under it, so an - /// empty section leaves no stray title behind. + // A section with no rows contributes no header, so an empty section leaves no stray title behind. internal static func flatten(_ sections: [FieldDrivenListSection]) -> [FieldDrivenListEntry] { sections.flatMap { section -> [FieldDrivenListEntry] in guard !section.items.isEmpty else { return [] } let rows = section.items.map { FieldDrivenListEntry.item($0) } guard let title = section.title else { return rows } - return [.header(id: section.id, title: title, accentColor: section.accentColor)] + rows + return [.header(id: section.id, title: title)] + rows } } } @@ -51,5 +44,4 @@ internal enum FieldDrivenListEntry where Item.ID: Hashable { private struct HeaderIdentity: Hashable { let id: String let title: String - let accentColor: NSColor? } diff --git a/apple/TablePro/Views/Sidebar/EditSequenceSheet.swift b/apple/TablePro/Views/Sidebar/EditSequenceSheet.swift index f3541c1e38..11ae7629f4 100644 --- a/apple/TablePro/Views/Sidebar/EditSequenceSheet.swift +++ b/apple/TablePro/Views/Sidebar/EditSequenceSheet.swift @@ -105,9 +105,7 @@ struct EditSequenceSheet: View { TextField(String(localized: "Cache"), text: field(\.cacheSize)) Toggle(String(localized: "Cycle"), isOn: cycles) if let message = problem ?? saveError { - Text(message) - .foregroundStyle(.red) - .fixedSize(horizontal: false, vertical: true) + NoticeLabel(message, severity: .error) .textSelection(.enabled) } } diff --git a/apple/TablePro/Views/Sidebar/FavoriteEditDialog.swift b/apple/TablePro/Views/Sidebar/FavoriteEditDialog.swift index cafa646f52..8f77e0b9b3 100644 --- a/apple/TablePro/Views/Sidebar/FavoriteEditDialog.swift +++ b/apple/TablePro/Views/Sidebar/FavoriteEditDialog.swift @@ -189,9 +189,8 @@ internal struct FavoriteEditDialog: View { .accessibilityLabel(String(localized: "Query")) if let message = draft.sizeValidation.displayText { - Text(message) + NoticeLabel(message, severity: .error) .font(.callout) - .foregroundStyle(Color.red) } } header: { Text("Query") @@ -217,9 +216,8 @@ internal struct FavoriteEditDialog: View { } if let message = keywordField.validation.displayText { - Text(message) + NoticeLabel(message, severity: keywordField.validation.isWarning ? .warning : .error) .font(.callout) - .foregroundStyle(keywordField.validation.isWarning ? Color.orange : Color.red) } Toggle(isOn: $isGlobal) { diff --git a/apple/TablePro/Views/Sidebar/FavoriteRowView.swift b/apple/TablePro/Views/Sidebar/FavoriteRowView.swift index 4b93c52621..50268ecb6b 100644 --- a/apple/TablePro/Views/Sidebar/FavoriteRowView.swift +++ b/apple/TablePro/Views/Sidebar/FavoriteRowView.swift @@ -5,7 +5,6 @@ import SwiftUI -/// Row view for a single SQL favorite in the sidebar internal struct FavoriteRowView: View { let favorite: SQLFavorite @@ -30,9 +29,6 @@ internal struct FavoriteRowView: View { Text(keyword) .font(.system(.caption, design: .monospaced).weight(.medium)) .foregroundStyle(.secondary) - .padding(.horizontal, 6) - .padding(.vertical, 1) - .background(Capsule().fill(.quaternary)) .accessibilityHidden(true) } } diff --git a/apple/TablePro/Views/Sidebar/LinkedFavoriteMetadataDialog.swift b/apple/TablePro/Views/Sidebar/LinkedFavoriteMetadataDialog.swift index ad88707ada..0c049579b4 100644 --- a/apple/TablePro/Views/Sidebar/LinkedFavoriteMetadataDialog.swift +++ b/apple/TablePro/Views/Sidebar/LinkedFavoriteMetadataDialog.swift @@ -36,14 +36,15 @@ internal struct LinkedFavoriteMetadataDialog: View { Form { identitySection keywordSection + if let saveError { + Section { + NoticeLabel(saveError, severity: .error) + .font(.callout) + } + } } .formStyle(.grouped) - if let saveError { - Divider() - errorBanner(saveError) - } - Divider() buttonBar @@ -89,27 +90,12 @@ internal struct LinkedFavoriteMetadataDialog: View { } if let message = keywordField.validation.displayText { - Text(message) + NoticeLabel(message, severity: keywordField.validation.isWarning ? .warning : .error) .font(.callout) - .foregroundStyle(keywordField.validation.isWarning ? Color.orange : Color.red) } } } - private func errorBanner(_ message: String) -> some View { - HStack(spacing: 8) { - Image(systemName: "exclamationmark.triangle.fill") - .foregroundStyle(.orange) - Text(message) - .font(.callout) - .foregroundStyle(.primary) - .lineLimit(2) - Spacer() - } - .padding(.horizontal, 20) - .padding(.vertical, 10) - } - private var buttonBar: some View { HStack { Spacer() diff --git a/apple/TablePro/Views/Sidebar/LinkedFavoriteRowView.swift b/apple/TablePro/Views/Sidebar/LinkedFavoriteRowView.swift index 5d59033e85..85eec0a782 100644 --- a/apple/TablePro/Views/Sidebar/LinkedFavoriteRowView.swift +++ b/apple/TablePro/Views/Sidebar/LinkedFavoriteRowView.swift @@ -25,7 +25,7 @@ internal struct LinkedFavoriteRowView: View { if favorite.encodingCannotRepresentEveryCharacter { Image(systemName: "exclamationmark.triangle.fill") .font(.caption) - .selectionAwareTint(.yellow) + .selectionAwareTint(.orange) .help(String( format: String( localized: "Encoded as %@. Saving keeps this encoding, and a character it can't represent stops the save." @@ -39,9 +39,6 @@ internal struct LinkedFavoriteRowView: View { Text(keyword) .font(.system(.caption, design: .monospaced).weight(.medium)) .foregroundStyle(.secondary) - .padding(.horizontal, 6) - .padding(.vertical, 1) - .background(Capsule().fill(.quaternary)) .accessibilityHidden(true) } diff --git a/apple/TablePro/Views/Sidebar/LinkedFolderCommitSheet.swift b/apple/TablePro/Views/Sidebar/LinkedFolderCommitSheet.swift index b021902a57..b7d2424be8 100644 --- a/apple/TablePro/Views/Sidebar/LinkedFolderCommitSheet.swift +++ b/apple/TablePro/Views/Sidebar/LinkedFolderCommitSheet.swift @@ -223,10 +223,8 @@ internal struct LinkedFolderCommitSheet: View { private func commitErrorView(_ error: LinkedFolderGitError) -> some View { VStack(alignment: .leading, spacing: 4) { - Text(error.errorDescription ?? "") + NoticeLabel(error.errorDescription ?? "", severity: .error) .font(.callout) - .foregroundStyle(.red) - .fixedSize(horizontal: false, vertical: true) if let output = error.output { ScrollView { Text(verbatim: output) diff --git a/apple/TablePro/Views/Sidebar/ObjectCommentSheet.swift b/apple/TablePro/Views/Sidebar/ObjectCommentSheet.swift index 7044a1a511..bdc4397a00 100644 --- a/apple/TablePro/Views/Sidebar/ObjectCommentSheet.swift +++ b/apple/TablePro/Views/Sidebar/ObjectCommentSheet.swift @@ -6,11 +6,7 @@ import os import SwiftUI -/// Edits the comment on one table, view, materialized view or foreign table. -/// -/// A sheet with an explicit Save rather than a field that commits on its own: the write is a -/// statement against the server, and a popover or an inspector field that saves when it loses -/// focus would run it on a stray click. +// An explicit Save, not a field that commits on blur: the write is a server statement a stray click would run. struct ObjectCommentSheet: View { @ObservedObject private var themeEngine = ThemeEngine.shared private static let logger = Logger(subsystem: "com.TablePro", category: "ObjectCommentSheet") @@ -96,10 +92,8 @@ struct ObjectCommentSheet: View { .accessibilityLabel(String(localized: "Comment")) .accessibilityIdentifier("object-comment-editor") if let saveError { - Text(saveError) + NoticeLabel(saveError, severity: .error) .font(.callout) - .foregroundStyle(.red) - .fixedSize(horizontal: false, vertical: true) .textSelection(.enabled) } else { Text("Leave the comment empty to remove it.") diff --git a/apple/TablePro/Views/Sidebar/SetSequenceValueSheet.swift b/apple/TablePro/Views/Sidebar/SetSequenceValueSheet.swift index 99c1bcc77f..e63e765d73 100644 --- a/apple/TablePro/Views/Sidebar/SetSequenceValueSheet.swift +++ b/apple/TablePro/Views/Sidebar/SetSequenceValueSheet.swift @@ -112,9 +112,7 @@ struct SetSequenceValueSheet: View { .disabled(source != .value) .accessibilityIdentifier("sequence-next-value") if let saveError { - Text(saveError) - .foregroundStyle(.red) - .fixedSize(horizontal: false, vertical: true) + NoticeLabel(saveError, severity: .error) .textSelection(.enabled) } } diff --git a/apple/TablePro/Views/Structure/CreateTableFormFieldRow.swift b/apple/TablePro/Views/Structure/CreateTableFormFieldRow.swift index 8291281d20..30d0ba4e0e 100644 --- a/apple/TablePro/Views/Structure/CreateTableFormFieldRow.swift +++ b/apple/TablePro/Views/Structure/CreateTableFormFieldRow.swift @@ -21,9 +21,8 @@ internal struct CreateTableFormFieldRow: View { .foregroundStyle(.secondary) } if let message { - Text(message) + NoticeLabel(message, severity: .error) .font(.callout) - .foregroundStyle(.red) } } diff --git a/apple/TablePro/Views/Structure/Inspector/StructureTablePropertiesView.swift b/apple/TablePro/Views/Structure/Inspector/StructureTablePropertiesView.swift index 1cfce1caf4..4cbe65387f 100644 --- a/apple/TablePro/Views/Structure/Inspector/StructureTablePropertiesView.swift +++ b/apple/TablePro/Views/Structure/Inspector/StructureTablePropertiesView.swift @@ -370,10 +370,8 @@ private struct StructureTableOptionsSection: View { } if let message = AutoIncrementEntry(counterText, maximum: maximum, original: original?.autoIncrement).message { Group { - Text(message) + NoticeLabel(message, severity: .error) .font(.caption) - .foregroundStyle(.red) - .fixedSize(horizontal: false, vertical: true) .accessibilityIdentifier("structure-options-auto-increment-error") } } diff --git a/apple/TablePro/Views/Structure/TriggerEditorView.swift b/apple/TablePro/Views/Structure/TriggerEditorView.swift index a9a8dc7ed8..2693da77dd 100644 --- a/apple/TablePro/Views/Structure/TriggerEditorView.swift +++ b/apple/TablePro/Views/Structure/TriggerEditorView.swift @@ -62,10 +62,12 @@ struct TriggerEditorView: View { Divider() Label { RevealedTextView(errorMessage) + .foregroundStyle(.secondary) } icon: { - Image(systemName: "exclamationmark.triangle.fill") + Image(systemName: NoticeSeverity.error.symbolName) + .foregroundStyle(NoticeSeverity.error.tint) + .accessibilityHidden(true) } - .foregroundStyle(.red) .font(.callout) .frame(maxWidth: .infinity, alignment: .leading) .padding(8) diff --git a/apple/TablePro/Views/UsersRoles/UsersRolesSheets.swift b/apple/TablePro/Views/UsersRoles/UsersRolesSheets.swift index f5456cd85e..7bdbc24c2c 100644 --- a/apple/TablePro/Views/UsersRoles/UsersRolesSheets.swift +++ b/apple/TablePro/Views/UsersRoles/UsersRolesSheets.swift @@ -81,9 +81,8 @@ struct CreatePrincipalSheet: View { if duplicateName, !trimmedName.isEmpty { LabeledContent("") { - Text("A user or role with this name already exists.") + NoticeLabel(String(localized: "A user or role with this name already exists."), severity: .error) .font(.caption) - .foregroundStyle(.red) } } @@ -161,9 +160,8 @@ struct ChangePasswordSheet: View { if mismatch { LabeledContent("") { - Text("The passwords do not match.") + NoticeLabel(String(localized: "The passwords do not match."), severity: .error) .font(.caption) - .foregroundStyle(.red) } } } diff --git a/apple/TableProTests/Views/FieldDrivenListEntryTests.swift b/apple/TableProTests/Views/FieldDrivenListEntryTests.swift index d947a3de6d..7d62f16bd0 100644 --- a/apple/TableProTests/Views/FieldDrivenListEntryTests.swift +++ b/apple/TableProTests/Views/FieldDrivenListEntryTests.swift @@ -3,7 +3,6 @@ // TableProTests // -import AppKit @testable import TablePro import Testing @@ -82,22 +81,6 @@ struct FieldDrivenListEntryTests { #expect(before.map(\.identity) != after.map(\.identity)) } - @Test("A recoloured section is a different header") - func headerIdentityFollowsItsAccent() { - let plain = FieldDrivenListSection(id: "g", title: "ACME", items: [Item(id: "one")]) - let coloured = FieldDrivenListSection( - id: "g", - title: "ACME", - accentColor: .systemRed, - items: [Item(id: "one")] - ) - - #expect( - FieldDrivenListEntry.flatten([plain]).map(\.identity) - != FieldDrivenListEntry.flatten([coloured]).map(\.identity) - ) - } - @Test("A header never reports an item id") func headerHasNoItemId() { let entries = FieldDrivenListEntry.flatten([section("a", title: "ACTIVE", ["one"])]) diff --git a/apple/TableProTests/Views/Toolbar/ConnectionSwitcherFilterTests.swift b/apple/TableProTests/Views/Toolbar/ConnectionSwitcherFilterTests.swift index 47688fe988..71c4b7c472 100644 --- a/apple/TableProTests/Views/Toolbar/ConnectionSwitcherFilterTests.swift +++ b/apple/TableProTests/Views/Toolbar/ConnectionSwitcherFilterTests.swift @@ -294,21 +294,6 @@ struct ConnectionSwitcherSectionsTests { #expect(titles(sections) == ["ACTIVE CONNECTIONS", "ACME / EUROPE"]) } - @Test("A group header carries no colored dot, whatever color the group has") - func groupHeadersHaveNoDot() { - let coloured = ConnectionGroup(name: "Prod", color: .red) - let plain = ConnectionGroup(name: "Scratch", sortOrder: 1) - - let sections = ConnectionSwitcherSections.build( - active: [], - saved: [connection("a", groupId: coloured.id), connection("b", groupId: plain.id)], - groups: [coloured, plain], - isFiltering: false - ) - - #expect(sections.allSatisfy { $0.accentColor == nil }) - } - @Test("Favorites and recent connections come before the groups and are not repeated in them") func favoritesAndRecentLeadTheLibrary() { let acme = ConnectionGroup(name: "Acme") From f840e2a68a3d5e1bc4dcd24c0941bbd0a095be53 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Tue, 3 Nov 2026 11:19:12 +0700 Subject: [PATCH 02/13] refactor(ui): show results in place instead of info-only alerts and copy toasts --- .../SignIn/ConnectionSignInProvider.swift | 16 +--- .../Storage/QueryHistoryManager+Rewind.swift | 4 + .../QueryHistoryStorage+RewindSnapshots.swift | 21 +++++ .../Extensions/View+SymbolEffectCompat.swift | 11 --- ...oritesSidebarViewModel+LinkedFolders.swift | 6 +- .../WelcomeViewModel+TeamLibrary.swift | 24 +---- .../Views/AIChat/AIChatCodeBlockView.swift | 17 +--- .../Views/Components/SQLReviewSheet.swift | 14 +-- .../ConnectionFormCoordinator.swift | 10 +-- .../Editor/History/HistoryListPane.swift | 20 ++++- .../Editor/History/HistoryPanelView.swift | 10 +++ .../Views/Filter/SQLPreviewSheet.swift | 14 +-- ...ntentCoordinator+DatabaseObjectTools.swift | 8 +- ...ainContentCoordinator+SidebarActions.swift | 76 +++++++++------- .../Views/QueryPlan/QueryPlanResultView.swift | 20 +---- .../Views/Results/ResultsJsonView.swift | 18 +--- .../Components/CopyableCodeBlock.swift | 17 ++-- .../Sections/MCPTokenRevealSheet.swift | 37 ++------ .../Views/Sidebar/FavoritesTabView.swift | 19 ++-- .../ConnectionSignInRegistryTests.swift | 1 - .../Storage/RewindSnapshotStorageTests.swift | 43 ++++++++- .../FavoritesLinkedFolderTests.swift | 10 +-- .../Main/MaintenanceResultNoteTests.swift | 88 +++++++++++++++++++ 23 files changed, 279 insertions(+), 225 deletions(-) create mode 100644 apple/TableProTests/Views/Main/MaintenanceResultNoteTests.swift diff --git a/apple/TablePro/Core/Database/SignIn/ConnectionSignInProvider.swift b/apple/TablePro/Core/Database/SignIn/ConnectionSignInProvider.swift index b9fb83802b..1b8fe361e0 100644 --- a/apple/TablePro/Core/Database/SignIn/ConnectionSignInProvider.swift +++ b/apple/TablePro/Core/Database/SignIn/ConnectionSignInProvider.swift @@ -8,21 +8,13 @@ enum ConnectionSignInKind: String, Equatable, CaseIterable { case vaultOIDC } -/// A driver credential that a person can renew by signing in again. -/// -/// Connect failures are otherwise terminal: the user reads an error and has nothing to click. A -/// provider says which failures it recognises and what to run to recover, so both the connection -/// form and the real connect path can offer the same recovery without either knowing which driver -/// is involved. +// The form and the real connect path share one recovery without knowing which driver failed. struct ConnectionSignInProvider: Sendable { let kind: ConnectionSignInKind - - /// Whether this provider recognises the failure. Kept free of UI so it stays testable. + // Free of UI so it stays testable. let claims: @Sendable (Error, [String: String]) -> Bool - let title: String let message: @Sendable ([String: String]) -> String - let signedInMessage: String let failureTitle: String // Gets the failure it claimed, which can carry what to sign in to. let signIn: @MainActor @Sendable (Error, [String: String], NSWindow?) async throws -> Void @@ -76,7 +68,6 @@ extension ConnectionSignInProvider { AWSSSOLoginService.signInProfileName(from: fields) ) }, - signedInMessage: String(localized: "AWS SSO sign-in finished. Test the connection again."), failureTitle: String(localized: "AWS SSO Sign-In Failed"), signIn: { _, fields, _ in try await AWSSSOLoginService.signIn(profileName: AWSSSOLoginService.signInProfileName(from: fields)) @@ -88,7 +79,6 @@ extension ConnectionSignInProvider { claims: { error, _ in EntraSignInService.needsSignIn(error) }, title: String(localized: "Microsoft Entra ID Sign-In Required"), message: { _ in String(localized: "Sign in to Microsoft Entra ID with your browser?") }, - signedInMessage: String(localized: "Microsoft Entra ID sign-in finished. Test the connection again."), failureTitle: String(localized: "Microsoft Entra ID Sign-In Failed"), signIn: { _, fields, window in try await EntraSignInService.signIn(fields: fields, window: window) @@ -100,7 +90,6 @@ extension ConnectionSignInProvider { claims: { error, fields in GoogleSignInService.claims(error, fields: fields) }, title: String(localized: "Google Sign-In Required"), message: { _ in String(localized: "Sign in to Google with your browser?") }, - signedInMessage: String(localized: "Google sign-in finished. Test the connection again."), failureTitle: String(localized: "Google Sign-In Failed"), signIn: { _, fields, _ in try await GoogleSignInService.signIn(fields: fields) @@ -112,7 +101,6 @@ extension ConnectionSignInProvider { claims: { error, _ in (error as? VaultError)?.oidcLogin != nil }, title: String(localized: "Vault Sign-In Required"), message: { _ in String(localized: "Sign in to Vault with your browser?") }, - signedInMessage: String(localized: "Vault sign-in finished. Test the connection again."), failureTitle: String(localized: "Vault Sign-In Failed"), signIn: { error, _, _ in guard let login = (error as? VaultError)?.oidcLogin else { return } diff --git a/apple/TablePro/Core/Storage/QueryHistoryManager+Rewind.swift b/apple/TablePro/Core/Storage/QueryHistoryManager+Rewind.swift index 30e2a8b755..0ff260ab54 100644 --- a/apple/TablePro/Core/Storage/QueryHistoryManager+Rewind.swift +++ b/apple/TablePro/Core/Storage/QueryHistoryManager+Rewind.swift @@ -31,6 +31,10 @@ extension QueryHistoryManager { await storage.rewindSnapshotId(forHistoryId: historyId) } + func rewindSnapshotHistoryIds() async -> Set? { + await storage.rewindSnapshotHistoryIds() + } + @discardableResult func deleteRewindSnapshot(id: UUID) async -> Bool { await storage.deleteRewindSnapshot(id: id) diff --git a/apple/TablePro/Core/Storage/QueryHistoryStorage+RewindSnapshots.swift b/apple/TablePro/Core/Storage/QueryHistoryStorage+RewindSnapshots.swift index 0a6b924945..a5de485368 100644 --- a/apple/TablePro/Core/Storage/QueryHistoryStorage+RewindSnapshots.swift +++ b/apple/TablePro/Core/Storage/QueryHistoryStorage+RewindSnapshots.swift @@ -148,6 +148,27 @@ extension QueryHistoryStorage { return UUID(uuidString: String(cString: raw)) } + // Retention bounds the table, so the drawer reads every id when its list loads. Nil when the store cannot answer. + func rewindSnapshotHistoryIds() -> Set? { + guard let db else { return nil } + var statement: OpaquePointer? + defer { sqlite3_finalize(statement) } + guard sqlite3_prepare_v2( + db, "SELECT history_id FROM rewind_snapshots WHERE history_id IS NOT NULL;", -1, &statement, nil + ) == SQLITE_OK else { + logSqliteError(context: "prepare rewind snapshot history ids") + return nil + } + var ids: Set = [] + while sqlite3_step(statement) == SQLITE_ROW { + guard let raw = sqlite3_column_text(statement, 0), + let id = UUID(uuidString: String(cString: raw)) + else { continue } + ids.insert(id) + } + return ids + } + /// The most recent saves against one table, newest first. func rewindSnapshots( connectionId: UUID, diff --git a/apple/TablePro/Extensions/View+SymbolEffectCompat.swift b/apple/TablePro/Extensions/View+SymbolEffectCompat.swift index 7f77476f40..5edb38d698 100644 --- a/apple/TablePro/Extensions/View+SymbolEffectCompat.swift +++ b/apple/TablePro/Extensions/View+SymbolEffectCompat.swift @@ -6,17 +6,6 @@ import SwiftUI internal extension View { - /// `contentTransition(.symbolEffect(.replace))` is macOS 14. On 13 the symbol swaps - /// without the morph, which is what the view did before the effect was added. - @ViewBuilder - func symbolReplaceTransition() -> some View { - if #available(macOS 14.0, *) { - contentTransition(.symbolEffect(.replace)) - } else { - self - } - } - /// `symbolEffect(.pulse, isActive:)` is macOS 14. The fallback pulses the opacity, so a /// running sync still reads as running rather than as a static icon. @ViewBuilder diff --git a/apple/TablePro/ViewModels/FavoritesSidebarViewModel+LinkedFolders.swift b/apple/TablePro/ViewModels/FavoritesSidebarViewModel+LinkedFolders.swift index 5b71ce9413..4989feacb6 100644 --- a/apple/TablePro/ViewModels/FavoritesSidebarViewModel+LinkedFolders.swift +++ b/apple/TablePro/ViewModels/FavoritesSidebarViewModel+LinkedFolders.swift @@ -15,7 +15,7 @@ extension FavoritesSidebarViewModel { internal enum AddFolderOutcome: Equatable { case added case reEnabled - case alreadyLinked(name: String) + case alreadyLinked(folderId: UUID) } internal func startWatchingLinkedFolders() { @@ -39,8 +39,6 @@ extension FavoritesSidebarViewModel { SQLFolderWatcher.shared.reload() } - /// Choosing a folder that is already linked but disabled re-enables it. Refusing it outright, - /// which is what happened before, pointed the user at a list the folder was invisible in. @discardableResult internal func addLinkedFolder(at url: URL) -> AddFolderOutcome { let path = PathPortability.contractHome(url.path) @@ -53,7 +51,7 @@ extension FavoritesSidebarViewModel { setLinkedFolder(existing, enabled: true) return .reEnabled } - return .alreadyLinked(name: url.lastPathComponent) + return .alreadyLinked(folderId: existing.id) } internal func revealLinkedFolder(_ folder: LinkedSQLFolder) { diff --git a/apple/TablePro/ViewModels/WelcomeViewModel+TeamLibrary.swift b/apple/TablePro/ViewModels/WelcomeViewModel+TeamLibrary.swift index 66b9d067e3..c3f690bda5 100644 --- a/apple/TablePro/ViewModels/WelcomeViewModel+TeamLibrary.swift +++ b/apple/TablePro/ViewModels/WelcomeViewModel+TeamLibrary.swift @@ -10,7 +10,7 @@ import AppKit internal enum TeamLibraryConnectionPublishOutcome { case declined - case published(connectionCount: Int) + case published case failed(Error) } @@ -24,12 +24,7 @@ extension WelcomeViewModel { through: TeamLibrarySyncCoordinator.shared, confirm: Self.confirmPublishToTeamLibrary ) - switch outcome { - case .declined: - return - case .published(let connectionCount): - presentTeamLibrarySuccess(connectionCount: connectionCount) - case .failed(let error): + if case .failed(let error) = outcome { presentTeamLibraryError(error) } } @@ -42,8 +37,8 @@ extension WelcomeViewModel { ) async -> TeamLibraryConnectionPublishOutcome { guard await confirm(connections) else { return .declined } do { - let response = try await coordinator.publish(connections: connections, favorites: [], folders: []) - return .published(connectionCount: response.connectionCount) + try await coordinator.publish(connections: connections, favorites: [], folders: []) + return .published } catch { return .failed(error) } @@ -74,17 +69,6 @@ extension WelcomeViewModel { return String(format: String(localized: "Publish “%@” to your team?"), connection.name) } - private func presentTeamLibrarySuccess(connectionCount: Int) { - AlertHelper.showInfoSheet( - title: String(localized: "Published to the team library"), - message: String( - format: String(localized: "Your team can now see %d shared connections. Passwords were not included."), - connectionCount - ), - window: nil - ) - } - private func presentTeamLibraryError(_ error: Error) { AlertHelper.showErrorSheet( title: String(localized: "Couldn't publish to the team library"), diff --git a/apple/TablePro/Views/AIChat/AIChatCodeBlockView.swift b/apple/TablePro/Views/AIChat/AIChatCodeBlockView.swift index c4e0fe0a95..7daaacab37 100644 --- a/apple/TablePro/Views/AIChat/AIChatCodeBlockView.swift +++ b/apple/TablePro/Views/AIChat/AIChatCodeBlockView.swift @@ -22,7 +22,6 @@ struct AIChatCodeBlockView: View, Equatable { && lhs.isSettled == rhs.isSettled } - @State private var isCopied: Bool = false @State private var highlighted: (key: String, text: AttributedString)? @Environment(\.commandActions) private var actions @@ -42,29 +41,17 @@ struct AIChatCodeBlockView: View, Equatable { if let resolvedLanguage { Text(resolvedLanguage.uppercased()) .font(.caption2) - .fontWeight(.medium) .foregroundStyle(.secondary) .lineLimit(1) - .padding(.horizontal, 6) - .padding(.vertical, 2) - .background(Color(nsColor: .separatorColor)) - .clipShape(RoundedRectangle(cornerRadius: 4)) } Spacer(minLength: 0) Button { ClipboardService.shared.writeText(code) - isCopied = true - Task { @MainActor in - try? await Task.sleep(for: .seconds(1.5)) - isCopied = false - } + AccessibilityAnnouncement.post(String(localized: "Copied to clipboard")) } label: { - Label( - isCopied ? String(localized: "Copied") : String(localized: "Copy"), - systemImage: isCopied ? "checkmark" : "doc.on.doc" - ) + Label(String(localized: "Copy"), systemImage: "doc.on.doc") .font(.caption2) .lineLimit(1) } diff --git a/apple/TablePro/Views/Components/SQLReviewSheet.swift b/apple/TablePro/Views/Components/SQLReviewSheet.swift index 48bf974613..dd8a23bd7e 100644 --- a/apple/TablePro/Views/Components/SQLReviewSheet.swift +++ b/apple/TablePro/Views/Components/SQLReviewSheet.swift @@ -79,7 +79,6 @@ struct SQLReviewSheet: View { var onOpenInEditor: (() -> Void)? @State private var prepared: Prepared? - @State private var copied = false @State private var isExecuting = false enum DisplayMode { @@ -225,10 +224,7 @@ struct SQLReviewSheet: View { Spacer() if !statements.isEmpty { Button(action: copyAll) { - Label( - copied ? String(localized: "Copied") : String(localized: "Copy All"), - systemImage: copied ? "checkmark" : "doc.on.doc" - ) + Label(String(localized: "Copy All"), systemImage: "doc.on.doc") } .buttonStyle(.bordered) .controlSize(.small) @@ -272,7 +268,7 @@ struct SQLReviewSheet: View { private var footer: some View { VStack(spacing: 8) { if let failure { - InlineErrorBanner(message: failure) + InlineErrorBanner(message: failure, onBar: false) } HStack(spacing: 12) { if let onOpenInEditor { @@ -340,10 +336,6 @@ struct SQLReviewSheet: View { private func copyAll() { guard let prepared else { return } ClipboardService.shared.writeText(prepared.full) - copied = true - Task { @MainActor in - try? await Task.sleep(for: .seconds(1.5)) - copied = false - } + AccessibilityAnnouncement.post(String(localized: "Copied to clipboard")) } } diff --git a/apple/TablePro/Views/ConnectionForm/ConnectionFormCoordinator.swift b/apple/TablePro/Views/ConnectionForm/ConnectionFormCoordinator.swift index 8b0680ae80..a28e238b4c 100644 --- a/apple/TablePro/Views/ConnectionForm/ConnectionFormCoordinator.swift +++ b/apple/TablePro/Views/ConnectionForm/ConnectionFormCoordinator.swift @@ -769,8 +769,8 @@ final class ConnectionFormCoordinator: ObservableObject { } } - /// Testing tears down first so the sheet never covers a running test, and the result is left - /// alone rather than marked failed: the credential was the problem, not the settings. + // The test tears down first so the sign-in sheet never covers a running one; a finished + // sign-in tests again, so the Test button reports the result in place. private func offerSignIn( _ provider: ConnectionSignInProvider, for error: Error, @@ -782,11 +782,7 @@ final class ConnectionFormCoordinator: ObservableObject { isTesting = false testTask = nil guard await ConnectionSignInPrompt.offer(provider, for: error, fields: fields, window: window) else { return } - AlertHelper.showInfoSheet( - title: String(localized: "Signed In"), - message: provider.signedInMessage, - window: window - ) + test() } private struct TunnelFormStates { diff --git a/apple/TablePro/Views/Editor/History/HistoryListPane.swift b/apple/TablePro/Views/Editor/History/HistoryListPane.swift index c1321c5b52..475d2afef0 100644 --- a/apple/TablePro/Views/Editor/History/HistoryListPane.swift +++ b/apple/TablePro/Views/Editor/History/HistoryListPane.swift @@ -8,8 +8,12 @@ struct HistoryListPane: View { let onRunInNewTab: (QueryHistoryEntry) -> Void let onCopy: (QueryHistoryEntry) -> Void let onSaveAsFavorite: (QueryHistoryEntry) -> Void + let canRestorePreviousValues: (QueryHistoryEntry, _ historyIdsWithSnapshot: Set?) -> Bool + let loadHistoryIdsWithSnapshot: @MainActor () async -> Set? let onRestorePreviousValues: (QueryHistoryEntry) -> Void + @State private var historyIdsWithSnapshot: Set? + var body: some View { content .frame(maxWidth: .infinity, maxHeight: .infinity) @@ -62,6 +66,15 @@ struct HistoryListPane: View { loadMoreBar } } + .task(id: rowEditEntryIds) { + let ids = await loadHistoryIdsWithSnapshot() + guard !Task.isCancelled else { return } + historyIdsWithSnapshot = ids + } + } + + private var rowEditEntryIds: [UUID] { + viewModel.sections.flatMap(\.entries).compactMap { $0.source == .rowEdit ? $0.id : nil } } private var selectionBinding: Binding> { @@ -148,11 +161,14 @@ struct HistoryListPane: View { ] } - /// Only a grid save has rows to put back. Everything else in this list is SQL somebody typed. + // Only a grid save has rows to put back. Everything else in this list is SQL somebody typed. private func rewindItems(for entry: QueryHistoryEntry) -> [FieldDrivenMenuItem] { guard entry.source == .rowEdit else { return [] } return [ - FieldDrivenMenuItem(title: String(localized: "Restore Previous Values…")) { + FieldDrivenMenuItem( + title: String(localized: "Restore Previous Values…"), + isEnabled: canRestorePreviousValues(entry, historyIdsWithSnapshot) + ) { onRestorePreviousValues(entry) }, .separator, diff --git a/apple/TablePro/Views/Editor/History/HistoryPanelView.swift b/apple/TablePro/Views/Editor/History/HistoryPanelView.swift index c92d3cf43d..0099d88a80 100644 --- a/apple/TablePro/Views/Editor/History/HistoryPanelView.swift +++ b/apple/TablePro/Views/Editor/History/HistoryPanelView.swift @@ -75,6 +75,8 @@ struct HistoryPanelView: View { onRunInNewTab: { runInNewTab($0) }, onCopy: { copy($0) }, onSaveAsFavorite: { favoriteDialogQuery = FavoriteDialogQuery(query: $0.query) }, + canRestorePreviousValues: { canRestore($0, historyIdsWithSnapshot: $1) }, + loadHistoryIdsWithSnapshot: { await services.queryHistoryManager.rewindSnapshotHistoryIds() }, onRestorePreviousValues: { coordinator.rewindSave(historyId: $0.id) } ) } secondary: { @@ -97,6 +99,14 @@ struct HistoryPanelView: View { entry.connectionId == connectionId } + // Unlicensed saves keep no snapshot, so their item stays enabled and the click explains the licence. + // A nil set is a list still loading; the coordinator's sheets cover a snapshot pruned since. + private func canRestore(_ entry: QueryHistoryEntry, historyIdsWithSnapshot: Set?) -> Bool { + guard canRun(entry), coordinator.canRewindSelectedTab else { return false } + guard services.licenseManager.isFeatureAvailable(.dataRewind), let historyIdsWithSnapshot else { return true } + return historyIdsWithSnapshot.contains(entry.id) + } + private func load(_ entry: QueryHistoryEntry) { coordinator.openQuery( entry.query, diff --git a/apple/TablePro/Views/Filter/SQLPreviewSheet.swift b/apple/TablePro/Views/Filter/SQLPreviewSheet.swift index 8ffaf1a8db..422d59cfe7 100644 --- a/apple/TablePro/Views/Filter/SQLPreviewSheet.swift +++ b/apple/TablePro/Views/Filter/SQLPreviewSheet.swift @@ -9,7 +9,6 @@ struct SQLPreviewSheet: View { let sql: String let databaseType: DatabaseType @Environment(\.dismiss) private var dismiss - @State private var copied = false var body: some View { VStack(spacing: 16) { @@ -27,12 +26,7 @@ struct SQLPreviewSheet: View { HStack { Button(action: copyToClipboard) { - HStack(spacing: 4) { - Image(systemName: copied ? "checkmark" : "doc.on.doc") - .font(.subheadline) - Text(copied ? "Copied!" : "Copy") - .font(.callout) - } + Label(String(localized: "Copy"), systemImage: "doc.on.doc") } .buttonStyle(.bordered) .controlSize(.small) @@ -56,12 +50,6 @@ struct SQLPreviewSheet: View { private func copyToClipboard() { ClipboardService.shared.writeText(sql) - copied = true AccessibilityAnnouncement.post(String(localized: "Copied to clipboard")) - - Task { @MainActor in - try? await Task.sleep(for: .seconds(1.5)) - copied = false - } } } diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+DatabaseObjectTools.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+DatabaseObjectTools.swift index 59b0c1d16d..79a3777531 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+DatabaseObjectTools.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+DatabaseObjectTools.swift @@ -87,14 +87,12 @@ extension MainContentCoordinator { private func runMaterializedViewRefresh(_ target: DatabaseObjectTarget, concurrently: Bool) { Task { do { + // The refresh posts a rows change, which reloads every tab showing the view. try await MaterializedViewRefreshing.refresh(target, concurrently: concurrently, connection: connection) - AlertHelper.showInfoSheet( - title: String(localized: "Materialized View Refreshed"), - message: String(format: String(localized: "“%@” now holds the current result of its query."), target.qualifiedName), - window: contentWindow - ) + AccessibilityAnnouncement.post(String(localized: "Materialized View Refreshed")) } catch ExecutionGateError.cancelledByUser { } catch { + Self.objectToolsLogger.error("Materialized view refresh failed: \(error.publicLogShape, privacy: .public)") AlertHelper.showErrorSheet( title: String(localized: "Couldn't Refresh Materialized View"), message: error.localizedDescription, diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+SidebarActions.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+SidebarActions.swift index 7b37d1a066..1e5f9ff31e 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+SidebarActions.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+SidebarActions.swift @@ -418,15 +418,7 @@ extension MainContentCoordinator { ) ?? [] } - /// Runs against the database the object it names lives in, on a scoped lease. - /// - /// A maintenance statement names its table and nothing else, so where it lands is decided - /// entirely by the connection's current database. Executing on the session driver directly left - /// that to chance: a cross-database tab pins the shared handle to its own database for the - /// length of its query and deliberately writes no session state back, so `OPTIMIZE TABLE - /// role_ability` could optimize the copy in another database while the sheet reported success. - /// Every other statement the user owns takes a scoped lease; this one now does too, which also - /// puts it behind the same gate rather than interleaving with a tab's work on one handle. + // A scoped lease on the object's own database: a cross-database tab can pin the shared handle elsewhere. func executeMaintenance( operation: PluginMaintenanceOperation, tableName: String, @@ -438,16 +430,11 @@ extension MainContentCoordinator { operation: operation, tableName: tableName, schema: schema, options: options ) guard !statements.isEmpty else { return } - /// The object the user picked names its own database, and only a command that names none - /// falls back to where the browser is pointing. `resolvedScope` is what decides that, so a - /// schema is never carried across a database boundary. + // Only a command that names no database falls back to where the browser is pointing. guard let scope = services.databaseManager.resolvedScope( database: database, schema: schema, for: connectionId ) ?? browseScope else { return } - /// What the statement acts on, which is the database itself for an operation that names no - /// object. Reporting the table there claimed work the statement never asked for. - let subject = operation.target(tableName) ?? scope.database Task { [weak self] in guard let self else { return } let decision = await self.executionGate.authorize( @@ -472,30 +459,25 @@ extension MainContentCoordinator { return } do { - var lastResult: QueryResult? + var results: [QueryResult] = [] let route = DatabaseManager.shared.executionRoute(for: scope) for sql in statements { - /// `.protectedWrite`: a half-applied OPTIMIZE or REPAIR cannot be undone by - /// retrying, so the lease is registered to mark the connection busy and is never - /// reachable by Stop. - lastResult = try await DatabaseManager.shared.withScopedDriver( + // A half-applied OPTIMIZE or REPAIR cannot be undone by retrying, so Stop never reaches it. + let result = try await DatabaseManager.shared.withScopedDriver( scope: scope, route: route, cancellation: .protectedWrite ) { scopedDriver in try await scopedDriver.execute(query: sql) } + results.append(result) + } + let title = String(format: String(localized: "%@ completed"), operation.name) + if let note = MaintenanceResultNote.note(from: results) { + await AlertHelper.showInfoSheet(title: title, message: note, window: self.contentWindow) + } else { + AccessibilityAnnouncement.post(title) } - await AlertHelper.showInfoSheet( - title: String(format: String(localized: "%@ completed"), operation.name), - message: lastResult?.statusMessage - ?? String( - format: String(localized: "%@ on %@ completed successfully."), - operation.name, - subject - ), - window: self.contentWindow - ) } catch { await AlertHelper.showErrorSheet( title: String(format: String(localized: "%@ failed"), operation.name), @@ -507,6 +489,40 @@ extension MainContentCoordinator { } } +// MySQL and MariaDB answer with Msg_text rows and SQLite's integrity_check with one row per problem. +// A plain "OK" carries nothing the person has to read. +internal enum MaintenanceResultNote { + private static let noteColumns: Set = ["msg_text", "integrity_check", "quick_check"] + + static func note(from results: [QueryResult]) -> String? { + let notes = results.flatMap(noteLines(in:)) + return notes.isEmpty ? nil : notes.joined(separator: "\n") + } + + private static func noteLines(in result: QueryResult) -> [String] { + var notes: [String] = [] + if let status = result.statusMessage.map(trimmed), !isPlainOK(status) { + notes.append(status) + } + guard let column = result.columns.firstIndex(where: { noteColumns.contains($0.lowercased()) }) else { + return notes + } + for row in result.rows where column < row.count { + guard let text = row[column].asText.map(trimmed), !isPlainOK(text) else { continue } + notes.append(text) + } + return notes + } + + private static func trimmed(_ text: String) -> String { + text.trimmingCharacters(in: .whitespacesAndNewlines) + } + + private static func isPlainOK(_ text: String) -> Bool { + text.isEmpty || text.caseInsensitiveCompare("OK") == .orderedSame + } +} + private enum ViewDefinitionRead: Sendable { case definition(String) case unreadable(any Error, template: String?) diff --git a/apple/TablePro/Views/QueryPlan/QueryPlanResultView.swift b/apple/TablePro/Views/QueryPlan/QueryPlanResultView.swift index a84f4c1fba..f425beab8a 100644 --- a/apple/TablePro/Views/QueryPlan/QueryPlanResultView.swift +++ b/apple/TablePro/Views/QueryPlan/QueryPlanResultView.swift @@ -76,9 +76,6 @@ struct QueryPlanResultView: View { @ObservedObject var planState: QueryPlanViewState @ObservedObject private var comparison: QueryPlanComparisonModel - @State private var showCopyConfirmation = false - @State private var copyResetTask: Task? - /// Resolved once per plan rather than per body evaluation. Working it out costs a walk of the /// whole tree for each metric, and the toolbar asks for it several times per render, which a /// ten-thousand-node MySQL tree plan would feel. @@ -211,15 +208,6 @@ struct QueryPlanResultView: View { Spacer() - if showCopyConfirmation { - HStack { - Image(systemName: "checkmark.circle.fill") - .foregroundStyle(.green) - Text(String(localized: "Copied!")) - } - .transition(.opacity) - } - Button(action: copyText) { Label(String(localized: "Copy"), systemImage: "doc.on.doc") } @@ -350,13 +338,7 @@ struct QueryPlanResultView: View { private func copyText() { ClipboardService.shared.writeText(rawText) - withMotion { showCopyConfirmation = true } - copyResetTask?.cancel() - copyResetTask = Task { @MainActor in - try? await Task.sleep(for: .milliseconds(1_500)) - guard !Task.isCancelled else { return } - withMotion { showCopyConfirmation = false } - } + AccessibilityAnnouncement.post(String(localized: "Copied to clipboard")) } private func formattedDuration(_ duration: TimeInterval) -> String { diff --git a/apple/TablePro/Views/Results/ResultsJsonView.swift b/apple/TablePro/Views/Results/ResultsJsonView.swift index ef6606d4a9..d8cc4d3395 100644 --- a/apple/TablePro/Views/Results/ResultsJsonView.swift +++ b/apple/TablePro/Views/Results/ResultsJsonView.swift @@ -26,8 +26,6 @@ internal struct ResultsJsonView: View { @State private var heldBackDeletionCount = 0 @State private var hasRendered = false @State private var renderedKey: RenderKey? - @State private var copied = false - @State private var copyCooldownTask: Task? init( tableRows: TableRows, @@ -132,21 +130,9 @@ internal struct ResultsJsonView: View { Button { ClipboardService.shared.writeText(cachedJson) - copied = true - copyCooldownTask?.cancel() - copyCooldownTask = Task { @MainActor in - do { - try await Task.sleep(for: .milliseconds(1_500)) - copied = false - } catch { - // cancelled by next press - } - } + AccessibilityAnnouncement.post(String(localized: "Copied to clipboard")) } label: { - Label( - copied ? String(localized: "Copied!") : String(localized: "Copy JSON"), - systemImage: copied ? "checkmark" : "doc.on.doc" - ) + Label(String(localized: "Copy JSON"), systemImage: "doc.on.doc") } .buttonStyle(.borderless) .controlSize(.small) diff --git a/apple/TablePro/Views/Settings/Components/CopyableCodeBlock.swift b/apple/TablePro/Views/Settings/Components/CopyableCodeBlock.swift index a9781b4425..414b86118f 100644 --- a/apple/TablePro/Views/Settings/Components/CopyableCodeBlock.swift +++ b/apple/TablePro/Views/Settings/Components/CopyableCodeBlock.swift @@ -1,9 +1,8 @@ -import AppKit import SwiftUI struct CopyableCodeBlock: View { let text: String - @State private var copied = false + var isSecret = false var body: some View { HStack(alignment: .top) { @@ -16,16 +15,14 @@ struct CopyableCodeBlock: View { .clipShape(RoundedRectangle(cornerRadius: 6)) Button { - NSPasteboard.general.clearContents() - NSPasteboard.general.setString(text, forType: .string) - copied = true - Task { @MainActor in - try? await Task.sleep(for: .seconds(1.5)) - copied = false + if isSecret { + ClipboardService.shared.writeSecretText(text) + } else { + ClipboardService.shared.writeText(text) } + AccessibilityAnnouncement.post(String(localized: "Copied to clipboard")) } label: { - Image(systemName: copied ? "checkmark" : "doc.on.doc") - .symbolReplaceTransition() + Image(systemName: "doc.on.doc") } .accessibilityLabel(String(localized: "Copy")) .help(String(localized: "Copy to clipboard")) diff --git a/apple/TablePro/Views/Settings/Sections/MCPTokenRevealSheet.swift b/apple/TablePro/Views/Settings/Sections/MCPTokenRevealSheet.swift index 80de9cadf5..9c2c59ab94 100644 --- a/apple/TablePro/Views/Settings/Sections/MCPTokenRevealSheet.swift +++ b/apple/TablePro/Views/Settings/Sections/MCPTokenRevealSheet.swift @@ -8,7 +8,6 @@ struct MCPTokenRevealSheet: View { @Environment(\.dismiss) private var dismiss @State private var isTokenRevealed = false - @State private var tokenCopied = false @State private var selectedClient: IntegrationClient = .claudeCode @FocusState private var doneFocused: Bool @@ -37,21 +36,8 @@ struct MCPTokenRevealSheet: View { } private var warningBanner: some View { - Label { - Text(String(localized: "This token will not be shown again")) - .fontWeight(.medium) - } icon: { - Image(systemName: "exclamationmark.triangle.fill") - .foregroundStyle(.orange) - } - .padding(12) - .frame(maxWidth: .infinity, alignment: .leading) - .themeMaterial(.banner, .thinMaterial) - .overlay( - RoundedRectangle(cornerRadius: 8) - .strokeBorder(.orange, lineWidth: 1) - ) - .clipShape(RoundedRectangle(cornerRadius: 8)) + NoticeLabel(String(localized: "This token will not be shown again"), severity: .warning) + .frame(maxWidth: .infinity, alignment: .leading) } private var tokenDisplay: some View { @@ -86,19 +72,8 @@ struct MCPTokenRevealSheet: View { Button { copyToClipboard(plaintext) - tokenCopied = true - Task { @MainActor in - try? await Task.sleep(for: .seconds(1.5)) - tokenCopied = false - } } label: { - HStack(spacing: 4) { - Image(systemName: tokenCopied ? "checkmark" : "doc.on.doc") - .symbolReplaceTransition() - Text(tokenCopied - ? String(localized: "Copied") - : String(localized: "Copy Token")) - } + Label(String(localized: "Copy Token"), systemImage: "doc.on.doc") } .buttonStyle(.borderedProminent) .accessibilityLabel(String(localized: "Copy token")) @@ -122,7 +97,7 @@ struct MCPTokenRevealSheet: View { .labelsHidden() .pickerStyle(.segmented) - CopyableCodeBlock(text: configSnippet(for: selectedClient)) + CopyableCodeBlock(text: configSnippet(for: selectedClient), isSecret: true) } } @@ -163,7 +138,7 @@ struct MCPTokenRevealSheet: View { } private func copyToClipboard(_ text: String) { - NSPasteboard.general.clearContents() - NSPasteboard.general.setString(text, forType: .string) + ClipboardService.shared.writeSecretText(text) + AccessibilityAnnouncement.post(String(localized: "Copied to clipboard")) } } diff --git a/apple/TablePro/Views/Sidebar/FavoritesTabView.swift b/apple/TablePro/Views/Sidebar/FavoritesTabView.swift index eacf434743..24a5d5eb85 100644 --- a/apple/TablePro/Views/Sidebar/FavoritesTabView.swift +++ b/apple/TablePro/Views/Sidebar/FavoritesTabView.swift @@ -288,10 +288,13 @@ internal struct FavoritesTabView: View { } guard await confirmPublishSavedQueries(count: favorites.count) else { return } do { - _ = try await TeamLibrarySyncCoordinator.shared.publish(connections: [], favorites: favorites, folders: folders) - presentTeamLibraryInfo(String(format: String(localized: "Published %d saved queries to your team."), favorites.count)) + try await TeamLibrarySyncCoordinator.shared.publish(connections: [], favorites: favorites, folders: folders) } catch { - presentTeamLibraryInfo(error.localizedDescription) + AlertHelper.showErrorSheet( + title: String(localized: "Couldn't publish to the team library"), + message: error.localizedDescription, + window: nil + ) } } } @@ -776,12 +779,10 @@ internal struct FavoritesTabView: View { panel.beginSheetModal(for: window) { response in guard response == .OK, let url = panel.url else { return } MainActor.assumeIsolated { - guard case .alreadyLinked(let name) = viewModel.addLinkedFolder(at: url) else { return } - AlertHelper.showInfoSheet( - title: String(localized: "This folder is already linked"), - message: String(format: String(localized: "%@ is already in the favorites list."), name), - window: window - ) + guard case .alreadyLinked(let folderId) = viewModel.addLinkedFolder(at: url), + let row = viewModel.nodes.first(where: { $0.asLinkedFolder?.id == folderId }) + else { return } + sharedSidebarState.selectedFavorite = .node(id: row.id) } } } diff --git a/apple/TableProTests/Core/Database/ConnectionSignInRegistryTests.swift b/apple/TableProTests/Core/Database/ConnectionSignInRegistryTests.swift index 667b9818b3..c18dcbd248 100644 --- a/apple/TableProTests/Core/Database/ConnectionSignInRegistryTests.swift +++ b/apple/TableProTests/Core/Database/ConnectionSignInRegistryTests.swift @@ -108,7 +108,6 @@ struct ConnectionSignInRegistryTests { for provider in ConnectionSignInRegistry.providers { #expect(!provider.title.isEmpty) #expect(!provider.message([:]).isEmpty) - #expect(!provider.signedInMessage.isEmpty) #expect(!provider.failureTitle.isEmpty) } } diff --git a/apple/TableProTests/Core/Storage/RewindSnapshotStorageTests.swift b/apple/TableProTests/Core/Storage/RewindSnapshotStorageTests.swift index 9d51b5147f..8210ce954c 100644 --- a/apple/TableProTests/Core/Storage/RewindSnapshotStorageTests.swift +++ b/apple/TableProTests/Core/Storage/RewindSnapshotStorageTests.swift @@ -21,12 +21,13 @@ struct RewindSnapshotStorageTests { table: String = "users", schema: String? = nil, capturedAt: Date = Date(timeIntervalSince1970: 1_700_000_000), - refusal: RewindRefusal? = nil + refusal: RewindRefusal? = nil, + historyId: UUID? = nil ) -> RewindRecord { let target = DataWriteTarget(database: "shop", schema: schema, table: table) return RewindRecord( id: UUID(), - historyId: nil, + historyId: historyId, connectionId: connectionId, databaseType: .sqlite, target: target, @@ -59,6 +60,44 @@ struct RewindSnapshotStorageTests { #expect(read == record) } + private func recordSave(in storage: QueryHistoryStorage) async -> UUID { + let id = UUID() + _ = await storage.record(QueryHistoryEntry( + id: id, + query: "UPDATE users SET name = 'Grace' WHERE id = 7", + connectionId: connectionId, + databaseName: "shop", + databaseType: .sqlite, + schemaName: nil, + source: .rowEdit, + executionTime: 0.1, + rowCount: 1, + wasSuccessful: true + )) + return id + } + + @Test("The drawer learns which saves still have their snapshot, and a deleted one drops out") + func historyIdsWithASnapshot() async { + let storage = makeStorage() + let cipher = RewindCipher(keychain: InMemoryKeychain()) + let kept = await recordSave(in: storage) + let deleted = await recordSave(in: storage) + let withoutSnapshot = await recordSave(in: storage) + let deletedRecord = makeRecord(historyId: deleted) + await storage.recordRewindSnapshot(makeRecord(historyId: kept), cipher: cipher) + await storage.recordRewindSnapshot(deletedRecord, cipher: cipher) + await storage.recordRewindSnapshot(makeRecord(), cipher: cipher) + + #expect(await storage.rewindSnapshotHistoryIds() == [kept, deleted]) + + await storage.deleteRewindSnapshot(id: deletedRecord.id) + + let ids = await storage.rewindSnapshotHistoryIds() + #expect(ids == [kept]) + #expect(ids?.contains(withoutSnapshot) == false) + } + @Test("Snapshots come back newest first, and only for the table asked for") func listsByTargetNewestFirst() async { let storage = makeStorage() diff --git a/apple/TableProTests/ViewModels/FavoritesLinkedFolderTests.swift b/apple/TableProTests/ViewModels/FavoritesLinkedFolderTests.swift index 31eb7602c7..d6d19f939b 100644 --- a/apple/TableProTests/ViewModels/FavoritesLinkedFolderTests.swift +++ b/apple/TableProTests/ViewModels/FavoritesLinkedFolderTests.swift @@ -56,17 +56,17 @@ struct FavoritesLinkedFolderTests { #expect(LinkedSQLFolderStorage.shared.loadFolders().last?.isEnabled == true) } - @Test("A folder that is already linked and enabled reports itself by name") - func reportsAnAlreadyLinkedFolder() { + @Test("A folder that is already linked and enabled reports the stored folder, so its row can be selected") + func reportsAnAlreadyLinkedFolder() throws { clearStoredFolders() defer { clearStoredFolders() } let viewModel = makeViewModel() defer { release(viewModel) } - let name = "tablepro-linked-\(UUID().uuidString)" - let url = URL(fileURLWithPath: "/tmp/\(name)") + let url = URL(fileURLWithPath: "/tmp/tablepro-linked-\(UUID().uuidString)") #expect(viewModel.addLinkedFolder(at: url) == .added) + let stored = try #require(LinkedSQLFolderStorage.shared.loadFolders().last) - #expect(viewModel.addLinkedFolder(at: url) == .alreadyLinked(name: name)) + #expect(viewModel.addLinkedFolder(at: url) == .alreadyLinked(folderId: stored.id)) } @Test("Disabling a folder leaves it stored, so its row and its Enable command survive") diff --git a/apple/TableProTests/Views/Main/MaintenanceResultNoteTests.swift b/apple/TableProTests/Views/Main/MaintenanceResultNoteTests.swift new file mode 100644 index 0000000000..9ba895a4a3 --- /dev/null +++ b/apple/TableProTests/Views/Main/MaintenanceResultNoteTests.swift @@ -0,0 +1,88 @@ +// +// MaintenanceResultNoteTests.swift +// TableProTests +// + +import Foundation +@testable import TablePro +import TableProPluginKit +import Testing + +struct MaintenanceResultNoteTests { + private func result( + columns: [String] = [], + rows: [[PluginCellValue]] = [], + statusMessage: String? = nil + ) -> QueryResult { + var result = QueryResult( + columns: columns, + columnTypes: [], + rows: rows, + rowsAffected: 0, + executionTime: 0, + error: nil + ) + result.statusMessage = statusMessage + return result + } + + private let mysqlColumns = ["Table", "Op", "Msg_type", "Msg_text"] + + @Test("MySQL's OPTIMIZE note on InnoDB reaches the person, its OK row does not") + func keepsTheOptimizeNote() { + let optimize = result(columns: mysqlColumns, rows: [ + [.text("shop.orders"), .text("optimize"), .text("note"), + .text("Table does not support optimize, doing recreate + analyze instead")], + [.text("shop.orders"), .text("optimize"), .text("status"), .text("OK")] + ]) + + #expect(MaintenanceResultNote.note(from: [optimize]) + == "Table does not support optimize, doing recreate + analyze instead") + } + + @Test("A plain OK from the server is no note") + func plainOKIsNoNote() { + let analyze = result(columns: mysqlColumns, rows: [ + [.text("shop.orders"), .text("analyze"), .text("status"), .text("OK")] + ]) + let integrity = result(columns: ["integrity_check"], rows: [[.text("ok")]]) + + #expect(MaintenanceResultNote.note(from: [analyze, integrity]) == nil) + #expect(MaintenanceResultNote.note(from: [result(statusMessage: "OK")]) == nil) + } + + @Test("A statement that returns nothing is no note") + func silentStatementIsNoNote() { + #expect(MaintenanceResultNote.note(from: [result(), result(statusMessage: " ")]) == nil) + } + + @Test("Every problem SQLite's integrity check lists is kept") + func keepsIntegrityProblems() { + let integrity = result(columns: ["integrity_check"], rows: [ + [.text("row 4 missing from index idx_orders_total")], + [.text("wrong # of entries in index idx_orders_total")] + ]) + + #expect(MaintenanceResultNote.note(from: [integrity]) + == "row 4 missing from index idx_orders_total\nwrong # of entries in index idx_orders_total") + } + + @Test("A driver's status message is kept beside the rows of the other statements") + func keepsTheStatusMessage() { + let first = result(statusMessage: "Table status: UPDATING") + let second = result(columns: mysqlColumns, rows: [ + [.text("shop.orders"), .text("repair"), .text("note"), + .text("The storage engine for the table doesn't support repair")] + ]) + + #expect(MaintenanceResultNote.note(from: [first, second]) + == "Table status: UPDATING\nThe storage engine for the table doesn't support repair") + } + + @Test("Rows of an unrelated shape are not read as notes") + func ignoresOtherColumns() { + let response = result(columns: ["TableName", "Status"], rows: [[.text("orders"), .text("ACTIVE")]]) + + #expect(MaintenanceResultNote.note(from: [response]) == nil) + } +} From 041625a7894a24db4821f1b808bb7137c1e1b387 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Tue, 3 Nov 2026 11:19:12 +0700 Subject: [PATCH 03/13] refactor(plugins): list plugins that could not load and offer Relaunch and Try Again in place --- .../Plugins/PluginManager+AutoUpdate.swift | 23 +- .../Views/Settings/GeneralSettingsView.swift | 13 +- .../Plugins/InstalledPluginsView.swift | 268 ++++++++++-------- .../Plugins/PluginListSelection.swift | 52 ++++ .../PluginRegistryUpdatePassTests.swift | 45 +++ .../Settings/PluginListSelectionTests.swift | 68 +++++ 6 files changed, 339 insertions(+), 130 deletions(-) create mode 100644 apple/TablePro/Views/Settings/Plugins/PluginListSelection.swift create mode 100644 apple/TableProTests/Views/Settings/PluginListSelectionTests.swift diff --git a/apple/TablePro/Core/Plugins/PluginManager+AutoUpdate.swift b/apple/TablePro/Core/Plugins/PluginManager+AutoUpdate.swift index a3cb3634ab..a9285d4163 100644 --- a/apple/TablePro/Core/Plugins/PluginManager+AutoUpdate.swift +++ b/apple/TablePro/Core/Plugins/PluginManager+AutoUpdate.swift @@ -195,7 +195,7 @@ extension PluginManager { } } - private func markUnfinishedRejectedPlugins() { + func markUnfinishedRejectedPlugins() { for rejected in rejectedPlugins where rejected.isOutdated { let reason: String switch rejectedAction(for: rejected) { @@ -236,11 +236,11 @@ extension PluginManager { } private func registryUnreachableReason() -> String { - String(localized: "TablePro couldn't reach the plugin registry to update this plugin. Check your connection and reopen TablePro.") + String(localized: "TablePro couldn't reach the plugin registry to update this plugin. Check your connection and try again.") } private func temporaryFailureReason() -> String { - String(localized: "Updating this plugin didn't finish. TablePro will try again the next time it launches.") + String(localized: "Updating this plugin didn't finish. Update it again to keep using it.") } // Only plist checks here: the signature was checked when staged and is checked again before any code loads. @@ -368,6 +368,23 @@ extension PluginManager { AppEvents.shared.pluginsRejected.send(rejectedPlugins) } + // Try Again on a plugin that could not load: fetch the manifest now, repair what can be repaired, and + // say again what each one still waits for. Returns false when the registry is still out of reach. + @discardableResult + func retryRejectedPluginRepairs(registryClient: RegistryClient = .shared) async -> Bool { + guard isUpdatingEnabled else { return false } + await waitForRejectedPluginRepairs() + guard let manifest = await registryClient.fetch(policy: .mustBeCurrent) else { + Self.logger.warning("Retrying plugin repairs: the plugin manifest is unavailable") + return false + } + let targets = registryUpdateTargets(appBuild: Bundle.main.buildNumber).filter { $0.rejectedURL != nil } + _ = await repairRejectedPlugins(targets, manifest: manifest) + markUnfinishedRejectedPlugins() + AppEvents.shared.pluginsRejected.send(rejectedPlugins) + return true + } + func registryUpdateTargets(forTypeId typeId: String, appBuild: Int) -> [RegistryUpdateTarget] { let rejectedURLs = Set( rejectedPlugins diff --git a/apple/TablePro/Views/Settings/GeneralSettingsView.swift b/apple/TablePro/Views/Settings/GeneralSettingsView.swift index 4ef3802a57..927fb09a5e 100644 --- a/apple/TablePro/Views/Settings/GeneralSettingsView.swift +++ b/apple/TablePro/Views/Settings/GeneralSettingsView.swift @@ -30,9 +30,16 @@ struct GeneralSettingsView: View { } if let initial = initialLanguage, settings.language != initial { - Text("Restart TablePro for the language change to take full effect.") - .font(.caption) - .foregroundStyle(.secondary) + LabeledContent { + Button(String(localized: "Relaunch")) { + UpdateCenter.shared.relaunch() + } + .accessibilityIdentifier("language-relaunch-button") + } label: { + Text("Relaunch TablePro to finish switching languages.") + .font(.caption) + .foregroundStyle(.secondary) + } } Picker("When TablePro starts:", selection: $settings.startupBehavior) { diff --git a/apple/TablePro/Views/Settings/Plugins/InstalledPluginsView.swift b/apple/TablePro/Views/Settings/Plugins/InstalledPluginsView.swift index 9e7d57a1be..c099822f1b 100644 --- a/apple/TablePro/Views/Settings/Plugins/InstalledPluginsView.swift +++ b/apple/TablePro/Views/Settings/Plugins/InstalledPluginsView.swift @@ -12,13 +12,12 @@ struct InstalledPluginsView: View { @ObservedObject private var modules = AppModuleSettings.shared @ObservedObject private var updates = UpdateCenter.shared - @State private var selectedPluginId: String? + @State private var selection: PluginListSelection? @State private var searchText = "" @State private var showErrorAlert = false @State private var errorAlertTitle = "" @State private var errorAlertMessage = "" - @State private var dismissedRestartBanner = false - @State private var dismissedRejectedBanner = false + @State private var isRetryingRejected = false init(registryClient: RegistryClient = .shared) { self.registryClient = registryClient @@ -33,22 +32,18 @@ struct InstalledPluginsView: View { AppModule.allCases.filter { $0.matches(filter: searchText) } } - var body: some View { - VStack(spacing: 0) { - if !pluginManager.rejectedPlugins.isEmpty && !dismissedRejectedBanner { - rejectedPluginsBanner - } - if pluginManager.needsRestart && !dismissedRestartBanner { - restartBanner - } + private var filteredRejected: [RejectedPlugin] { + if searchText.isEmpty { return pluginManager.rejectedPlugins } + return pluginManager.rejectedPlugins.filter { $0.name.localizedCaseInsensitiveContains(searchText) } + } - HSplitView { - pluginList - .frame(minWidth: 200, idealWidth: 240, maxWidth: 280) + var body: some View { + HSplitView { + pluginList + .frame(minWidth: 200, idealWidth: 240, maxWidth: 280) - detailPane - .frame(minWidth: 340) - } + detailPane + .frame(minWidth: 340) } .task { await registryClient.fetch(policy: .ifStale) @@ -76,110 +71,92 @@ struct InstalledPluginsView: View { } } - // MARK: - Restart Banner + // MARK: - Relaunch Row - private var restartBanner: some View { + // Untagged, so it never takes the selection; the list is where the pending removal is. + private var relaunchRow: some View { HStack(spacing: 8) { - Image(systemName: "exclamationmark.triangle") - .foregroundStyle(.yellow) - Text("Relaunch TablePro to finish removing plugins.") - .font(.callout) - Spacer() + Label { + Text("Relaunch to finish removing plugins.") + .lineLimit(2) + } icon: { + Image(systemName: "arrow.clockwise") + .foregroundStyle(.secondary) + } + Spacer(minLength: 4) Button(String(localized: "Relaunch")) { updates.relaunch() } - .buttonStyle(.bordered) .controlSize(.small) - Button("Dismiss") { dismissedRestartBanner = true } - .buttonStyle(.borderless) - .font(.callout) - } - .padding(.horizontal, 12) - .padding(.vertical, 6) - } - - // MARK: - Rejected Plugins Banner - - private var rejectedPluginsBanner: some View { - let actions = rejectedActionsByURL - let recoverable = !actions.values.contains { if case .notInRegistry = $0 { return true } else { return false } } - return VStack(alignment: .leading, spacing: 0) { - HStack(spacing: 8) { - Image(systemName: recoverable ? "arrow.triangle.2.circlepath" : "exclamationmark.circle.fill") - .foregroundStyle(recoverable ? .orange : .red) - Text(rejectedBannerTitle(recoverable: recoverable)) - .font(.callout.weight(.medium)) - Spacer() - Button(String(localized: "Dismiss")) { dismissedRejectedBanner = true } - .buttonStyle(.borderless) - .font(.callout) - } - .padding(.horizontal, 12) - .padding(.vertical, 6) - - Divider() - - ScrollView { - LazyVStack(spacing: 0) { - ForEach(pluginManager.rejectedPlugins, id: \.url) { plugin in - rejectedPluginRow(plugin, action: actions[plugin.url] ?? .awaitingCompatibleBuild) - Divider().padding(.leading, 12) - } - } - } - .frame(maxHeight: Self.rejectedBannerMaxHeight) - - Divider() + .accessibilityIdentifier("plugins-relaunch-button") } + .padding(.vertical, 2) } - private static let rejectedBannerMaxHeight: CGFloat = 168 + // MARK: - Rejected Plugins - private var rejectedActionsByURL: [URL: RejectedPluginAction] { - var result: [URL: RejectedPluginAction] = [:] - for plugin in pluginManager.rejectedPlugins { - result[plugin.url] = pluginManager.rejectedAction(for: plugin) - } - return result - } - - private func rejectedBannerTitle(recoverable: Bool) -> String { - let count = pluginManager.rejectedPlugins.count - if recoverable { - return count == 1 - ? String(localized: "1 plugin needs an update to load.") - : String(format: String(localized: "%d plugins need an update to load."), count) - } - return count == 1 - ? String(localized: "1 plugin could not be loaded.") - : String(format: String(localized: "%d plugins could not be loaded."), count) - } - - @ViewBuilder - private func rejectedPluginRow(_ plugin: RejectedPlugin, action: RejectedPluginAction) -> some View { - HStack(spacing: 8) { + private func rejectedRow(_ plugin: RejectedPlugin) -> some View { + let status = RejectedPluginStatus(action: pluginManager.rejectedAction(for: plugin)) + return HStack(spacing: 8) { PluginIconView(name: PluginManager.iconName(forPrimaryTypeId: plugin.providedDatabaseTypeIds.first)) .font(.title3) .frame(width: 24, height: 24) .foregroundStyle(.tertiary) + VStack(alignment: .leading, spacing: 2) { Text(plugin.name) - .font(.callout.weight(.medium)) .lineLimit(1) - Text(plugin.reason) + Text(status.caption) .font(.caption) .foregroundStyle(.secondary) - .lineLimit(2) + .lineLimit(1) } + Spacer() - rejectedActionControl(for: plugin, action: action) - Button(String(localized: "Remove")) { - removeRejectedPlugin(plugin) + + Image(systemName: status.severity.symbolName) + .selectionAwareTint(status.severity.tint) + .accessibilityHidden(true) + } + .padding(.vertical, 2) + .accessibilityElement(children: .combine) + } + + private func rejectedDetail(_ plugin: RejectedPlugin) -> some View { + let action = pluginManager.rejectedAction(for: plugin) + let status = RejectedPluginStatus(action: action) + return ScrollView { + VStack(alignment: .leading, spacing: 16) { + Text(plugin.name) + .font(.title3.weight(.semibold)) + + NoticeLabel(plugin.reason, severity: status.severity) + .font(.callout) + + if let bundleId = plugin.bundleId { + Divider() + Grid(alignment: .leading, horizontalSpacing: 16, verticalSpacing: 10) { + GridRow { + Text("Bundle ID") + .foregroundStyle(.secondary) + Text(bundleId) + .textSelection(.enabled) + } + } + .font(.callout) + } + + Divider() + + HStack(spacing: 8) { + rejectedActionControl(for: plugin, action: action) + Button(String(localized: "Remove")) { + removeRejectedPlugin(plugin) + } + .accessibilityLabel(String(format: String(localized: "Remove %@"), plugin.name)) + } } - .buttonStyle(.bordered) - .controlSize(.small) - .accessibilityLabel(String(format: String(localized: "Remove %@"), plugin.name)) + .padding(20) + .frame(maxWidth: .infinity, alignment: .leading) } - .padding(.horizontal, 12) - .padding(.vertical, 6) } @ViewBuilder @@ -189,22 +166,38 @@ struct InstalledPluginsView: View { Button(String(localized: "Update Now")) { updatePlugin(registryPlugin) } - .buttonStyle(.borderedProminent) - .controlSize(.small) + .disabled(pluginManager.isInstalling) .accessibilityLabel(String(format: String(localized: "Update %@"), plugin.name)) case .requiresAppUpdate: Button(updates.status.appUpdateTitle) { updates.performAppUpdateAction() } - .buttonStyle(.bordered) - .controlSize(.small) .disabled(!updates.isAppUpdateActionEnabled) .help(String(localized: "A newer TablePro is required to load this plugin.")) - case .awaitingCompatibleBuild, .notInRegistry: + case .awaitingCompatibleBuild: + if pluginManager.isUpdatingEnabled { + if isRetryingRejected { + ProgressView() + .controlSize(.small) + } else { + Button(String(localized: "Try Again")) { + retryRejectedPlugins() + } + } + } + case .notInRegistry: EmptyView() } } + private func retryRejectedPlugins() { + isRetryingRejected = true + Task { + defer { isRetryingRejected = false } + await pluginManager.retryRejectedPluginRepairs(registryClient: registryClient) + } + } + private func removeRejectedPlugin(_ plugin: RejectedPlugin) { let fm = FileManager.default if fm.fileExists(atPath: plugin.url.path) { @@ -219,6 +212,7 @@ struct InstalledPluginsView: View { } } pluginManager.removeFromRejected(url: plugin.url) + if selection == .rejected(plugin.url) { selection = nil } } // MARK: - Plugin List @@ -230,7 +224,12 @@ struct InstalledPluginsView: View { .padding(.vertical, 6) ScrollViewReader { proxy in - List(selection: $selectedPluginId) { + List(selection: $selection) { + if pluginManager.needsRestart { + Section { + relaunchRow + } + } if !filteredModules.isEmpty { // Untagged, so a module row toggles but never takes the plugin selection. Section(String(localized: "Modules")) { @@ -239,11 +238,20 @@ struct InstalledPluginsView: View { } } } + if !filteredRejected.isEmpty { + Section(String(localized: "Couldn't Load")) { + ForEach(filteredRejected, id: \.url) { plugin in + rejectedRow(plugin) + .tag(PluginListSelection.rejected(plugin.url)) + .id(PluginListSelection.rejected(plugin.url)) + } + } + } Section(String(localized: "Plugins")) { ForEach(filteredPlugins) { plugin in pluginRow(plugin) - .tag(plugin.id) - .id(plugin.id) + .tag(PluginListSelection.plugin(plugin.id)) + .id(PluginListSelection.plugin(plugin.id)) } } } @@ -255,15 +263,20 @@ struct InstalledPluginsView: View { .onChange(of: navigation.pendingRequest) { _ in revealRequestedPlugin() } - .onChange(of: selectedPluginId) { pluginId in - guard let pluginId else { return } - proxy.scrollTo(pluginId) + .onChange(of: selection) { selection in + guard let selection else { return } + proxy.scrollTo(selection) } } } .onChange(of: searchText) { _ in - if let selectedPluginId, !filteredPlugins.contains(where: { $0.id == selectedPluginId }) { - self.selectedPluginId = nil + switch selection { + case .plugin(let id) where !filteredPlugins.contains(where: { $0.id == id }): + selection = nil + case .rejected(let url) where !filteredRejected.contains(where: { $0.url == url }): + selection = nil + default: + break } } } @@ -348,13 +361,20 @@ struct InstalledPluginsView: View { // MARK: - Detail Pane private var selectedPlugin: PluginEntry? { - guard let id = selectedPluginId else { return nil } + guard case .plugin(let id) = selection else { return nil } return pluginManager.plugins.first { $0.id == id } } + private var selectedRejected: RejectedPlugin? { + guard case .rejected(let url) = selection else { return nil } + return pluginManager.rejectedPlugins.first { $0.url == url } + } + @ViewBuilder private var detailPane: some View { - if let selected = selectedPlugin { + if let rejected = selectedRejected { + rejectedDetail(rejected) + } else if let selected = selectedPlugin { ScrollView { VStack(alignment: .leading, spacing: 16) { Text(selected.name) @@ -459,14 +479,14 @@ struct InstalledPluginsView: View { // MARK: - Actions private func revealRequestedPlugin() { - guard let request = navigation.consumePendingRequest() else { return } - guard let pluginId = request.pluginId, - pluginManager.plugins.contains(where: { $0.id == pluginId }) else { - dismissedRejectedBanner = false - return - } + guard let request = navigation.consumePendingRequest(), + let target = PluginListSelection.revealTarget( + pluginId: request.pluginId, + loadedIds: pluginManager.plugins.map(\.id), + rejected: pluginManager.rejectedPlugins + ) else { return } searchText = "" - selectedPluginId = pluginId + selection = target } private func installFromFile() { @@ -488,7 +508,7 @@ struct InstalledPluginsView: View { Task { do { let entry = try await pluginManager.installPlugin(from: url) - selectedPluginId = entry.id + selection = .plugin(entry.id) } catch { errorAlertTitle = String(localized: "Plugin Installation Failed") errorAlertMessage = error.localizedDescription @@ -510,7 +530,7 @@ struct InstalledPluginsView: View { do { try await pluginManager.uninstallPlugin(id: plugin.id) - selectedPluginId = nil + selection = nil } catch { errorAlertTitle = String(localized: "Uninstall Failed") errorAlertMessage = error.localizedDescription diff --git a/apple/TablePro/Views/Settings/Plugins/PluginListSelection.swift b/apple/TablePro/Views/Settings/Plugins/PluginListSelection.swift new file mode 100644 index 0000000000..56ca05867d --- /dev/null +++ b/apple/TablePro/Views/Settings/Plugins/PluginListSelection.swift @@ -0,0 +1,52 @@ +// +// PluginListSelection.swift +// TablePro +// + +import Foundation + +// A rejected bundle can carry the id of a loaded plugin, so rejected rows are told apart by URL. +internal enum PluginListSelection: Hashable { + case plugin(String) + case rejected(URL) + + // A loaded plugin wins over a rejected copy of the same id. With no id, the first plugin that needs + // an update is shown, since that is what a connection failure that names none is about. + internal static func revealTarget( + pluginId: String?, + loadedIds: [String], + rejected: [RejectedPlugin] + ) -> PluginListSelection? { + if let pluginId { + if loadedIds.contains(pluginId) { return .plugin(pluginId) } + if let match = rejected.first(where: { $0.bundleId == pluginId || $0.registryId == pluginId }) { + return .rejected(match.url) + } + return nil + } + let first = rejected.first(where: \.isOutdated) ?? rejected.first + return first.map { .rejected($0.url) } + } +} + +internal struct RejectedPluginStatus: Equatable { + let caption: String + let severity: NoticeSeverity + + internal init(action: RejectedPluginAction) { + switch action { + case .updateAvailable: + caption = String(localized: "Update available") + severity = .warning + case .awaitingCompatibleBuild: + caption = String(localized: "Waiting for a compatible build") + severity = .warning + case .requiresAppUpdate: + caption = String(localized: "Needs a newer TablePro") + severity = .warning + case .notInRegistry: + caption = String(localized: "Can't be loaded") + severity = .error + } + } +} diff --git a/apple/TableProTests/Core/Plugins/PluginRegistryUpdatePassTests.swift b/apple/TableProTests/Core/Plugins/PluginRegistryUpdatePassTests.swift index 0af405ce48..52575e2203 100644 --- a/apple/TableProTests/Core/Plugins/PluginRegistryUpdatePassTests.swift +++ b/apple/TableProTests/Core/Plugins/PluginRegistryUpdatePassTests.swift @@ -460,6 +460,51 @@ struct PluginRegistryUpdatePassTests { #expect(registry.requestCount == 0) } + @Test("Try Again repairs a rejected plugin as soon as the registry answers") + func tryAgainRepairsARejectedPlugin() async throws { + let installer = FixtureRegistryInstaller() + let fixture = try makeFixture(installer: installer, isUpdatingEnabled: true) + defer { try? FileManager.default.removeItem(at: fixture.root) } + fixture.manager.rejectedPlugins = [makeRejected(bundleId: "com.example.driver")] + let (client, manifestURL) = try makeRegistryClient(servingBuild: 20) + + let reached = await fixture.manager.retryRejectedPluginRepairs(registryClient: client) + + #expect(reached) + #expect(ManifestStubProtocol.requestCount(for: manifestURL) == 1) + let installedIds = await installer.installedIds + #expect(installedIds == ["com.example.driver"]) + } + + @Test("Try Again with the registry still refused reports it and installs nothing") + func tryAgainReportsAnUnreachableRegistry() async throws { + let installer = FixtureRegistryInstaller() + let fixture = try makeFixture(installer: installer, isUpdatingEnabled: true) + defer { try? FileManager.default.removeItem(at: fixture.root) } + fixture.manager.rejectedPlugins = [makeRejected(bundleId: "com.example.driver")] + let (client, _) = try makeRegistryClient(servingBuild: 20, signedBy: nil) + + let reached = await fixture.manager.retryRejectedPluginRepairs(registryClient: client) + + #expect(!reached) + let installedIds = await installer.installedIds + #expect(installedIds.isEmpty) + #expect(fixture.manager.rejectedPlugins.count == 1) + } + + @Test("Try Again does nothing where updating is off") + func tryAgainNeedsUpdating() async throws { + let fixture = try makeFixture(isUpdatingEnabled: false) + defer { try? FileManager.default.removeItem(at: fixture.root) } + fixture.manager.rejectedPlugins = [makeRejected(bundleId: "com.example.driver")] + let registry = try OfflineRegistry() + + let reached = await fixture.manager.retryRejectedPluginRepairs(registryClient: registry.client) + + #expect(!reached) + #expect(registry.requestCount == 0) + } + @Test("A manifest without a newer build yet keeps the pass retrying") func staleManifestRetries() async throws { let fixture = try makeFixture() diff --git a/apple/TableProTests/Views/Settings/PluginListSelectionTests.swift b/apple/TableProTests/Views/Settings/PluginListSelectionTests.swift new file mode 100644 index 0000000000..925cbfb29c --- /dev/null +++ b/apple/TableProTests/Views/Settings/PluginListSelectionTests.swift @@ -0,0 +1,68 @@ +import Foundation +@testable import TablePro +import Testing + +struct PluginListSelectionTests { + private func rejected(bundleId: String?, registryId: String? = nil, isOutdated: Bool = true) -> RejectedPlugin { + RejectedPlugin( + url: URL(fileURLWithPath: "/tmp/\(UUID().uuidString).tableplugin"), + bundleId: bundleId, + registryId: registryId, + name: "Driver", + reason: "Built for an older PluginKit", + isOutdated: isOutdated, + providedDatabaseTypeIds: [] + ) + } + + @Test("A loaded plugin wins over a rejected copy with the same id") + func loadedWins() { + let copy = rejected(bundleId: "com.example.driver") + let target = PluginListSelection.revealTarget( + pluginId: "com.example.driver", + loadedIds: ["com.example.driver"], + rejected: [copy] + ) + #expect(target == .plugin("com.example.driver")) + } + + @Test("A connection failure naming a plugin that could not load selects its row") + func rejectedByBundleOrRegistryId() { + let byBundle = rejected(bundleId: "com.example.driver") + let byRegistry = rejected(bundleId: nil, registryId: "com.example.other") + #expect( + PluginListSelection.revealTarget(pluginId: "com.example.driver", loadedIds: [], rejected: [byBundle, byRegistry]) + == .rejected(byBundle.url) + ) + #expect( + PluginListSelection.revealTarget(pluginId: "com.example.other", loadedIds: [], rejected: [byBundle, byRegistry]) + == .rejected(byRegistry.url) + ) + } + + @Test("A failure that names no plugin selects the first one waiting for an update") + func noIdPicksTheFirstOutdated() { + let broken = rejected(bundleId: "com.example.broken", isOutdated: false) + let outdated = rejected(bundleId: "com.example.outdated") + #expect( + PluginListSelection.revealTarget(pluginId: nil, loadedIds: [], rejected: [broken, outdated]) + == .rejected(outdated.url) + ) + #expect(PluginListSelection.revealTarget(pluginId: nil, loadedIds: [], rejected: []) == nil) + } + + @Test("An unknown id selects nothing") + func unknownIdSelectsNothing() { + #expect( + PluginListSelection.revealTarget(pluginId: "com.example.none", loadedIds: ["a"], rejected: [rejected(bundleId: "b")]) + == nil + ) + } + + @Test("Only a plugin missing from the registry reads as an error") + func statusSeverity() { + #expect(RejectedPluginStatus(action: .awaitingCompatibleBuild).severity == .warning) + #expect(RejectedPluginStatus(action: .requiresAppUpdate).severity == .warning) + #expect(RejectedPluginStatus(action: .notInRegistry).severity == .error) + } +} From cd2b64e3ea028d3481c889f03ba8f7c4aee88f34 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Tue, 3 Nov 2026 11:19:13 +0700 Subject: [PATCH 04/13] refactor(mcp): type the server failure and offer Try Again in the Status row --- .../Core/MCP/Lifecycle/MCPServerManager.swift | 28 ++++++--- .../Views/Settings/Sections/MCPSection.swift | 50 +++++++--------- .../MCPServerStatusPresentation.swift | 58 +++++++++++++++++++ .../Settings/Sections/MCPTokenListView.swift | 22 ++----- .../Lifecycle/MCPServerLifecycleTests.swift | 3 +- .../Lifecycle/MCPServerOffContractTests.swift | 11 ++++ .../MCPServerStatusPresentationTests.swift | 58 +++++++++++++++++++ 7 files changed, 174 insertions(+), 56 deletions(-) create mode 100644 apple/TablePro/Views/Settings/Sections/MCPServerStatusPresentation.swift create mode 100644 apple/TableProTests/Views/Settings/MCPServerStatusPresentationTests.swift diff --git a/apple/TablePro/Core/MCP/Lifecycle/MCPServerManager.swift b/apple/TablePro/Core/MCP/Lifecycle/MCPServerManager.swift index b96217f9a5..1aac839762 100644 --- a/apple/TablePro/Core/MCP/Lifecycle/MCPServerManager.swift +++ b/apple/TablePro/Core/MCP/Lifecycle/MCPServerManager.swift @@ -7,7 +7,15 @@ internal enum MCPServerState: Sendable, Equatable { case stopped case starting case running(port: UInt16) - case failed(String) + case failed(MCPServerFailure) +} + +internal enum MCPServerFailure: Sendable, Equatable { + case socketFolderUnusable + case listenerUnavailable(detail: String) + case noBoundPort + case credentialUnavailable + case listenerStopped(detail: String) } internal enum MCPServerStartError: Error, LocalizedError, Equatable { @@ -111,6 +119,11 @@ internal final class MCPServerManager: ObservableObject { } } + // Try Again in Settings. performStart still refuses while the server is turned off. + internal func retry() { + scheduleRestart(port: UInt16(clamping: AppSettingsManager.shared.mcp.port)) + } + internal func scheduleRestart(port: UInt16) { lifecycle.enqueue { [weak self] in guard let self else { return } @@ -184,7 +197,7 @@ internal final class MCPServerManager: ObservableObject { socketPath = try handshake.prepareSocketPath() } catch { Self.logger.error("MCP socket folder is not usable: \(error.publicLogShape, privacy: .public)") - state = .failed(String(localized: "The MCP server could not prepare its private socket folder")) + state = .failed(.socketFolderUnusable) tokenStore = nil return nil } @@ -208,9 +221,8 @@ internal final class MCPServerManager: ObservableObject { return nil } - let failure = MCPPortAllocatorError.everyCandidateRejected(lastFailure: lastFailure) Self.logger.error("MCP server failed to start: \(lastFailure, privacy: .private)") - state = .failed(failure.localizedDescription) + state = .failed(.listenerUnavailable(detail: lastFailure)) tokenStore = nil return nil } @@ -218,14 +230,14 @@ internal final class MCPServerManager: ObservableObject { private func activate(_ built: MCPServerComposition, generation: Int, store: MCPTokenStore) async { guard let boundPort = await built.transport.listeningPort else { await built.transport.stop() - state = .failed(String(localized: "The MCP server started without a port")) + state = .failed(.noBoundPort) tokenStore = nil return } guard let credential = await mintBridgeCredential(store: store) else { await built.transport.stop() - state = .failed(String(localized: "The MCP server could not issue its bridge credential")) + state = .failed(.credentialUnavailable) tokenStore = nil return } @@ -436,10 +448,10 @@ internal final class MCPServerManager: ObservableObject { case .running(let port): state = .running(port: port) case .failed(let reason): - state = .failed(reason) + state = .failed(.listenerStopped(detail: reason)) lifecycle.enqueue { [weak self] in await self?.performStop() - self?.state = .failed(reason) + self?.state = .failed(.listenerStopped(detail: reason)) } } } diff --git a/apple/TablePro/Views/Settings/Sections/MCPSection.swift b/apple/TablePro/Views/Settings/Sections/MCPSection.swift index f4143212da..cb74a2c5c1 100644 --- a/apple/TablePro/Views/Settings/Sections/MCPSection.swift +++ b/apple/TablePro/Views/Settings/Sections/MCPSection.swift @@ -18,9 +18,7 @@ struct MCPSection: View { .accessibilityIdentifier("mcp-enable-server-toggle") if settings.enabled { - LabeledContent(String(localized: "Status")) { - MCPStatusIndicator() - } + MCPStatusRow(configuredPort: settings.port) } } @@ -165,36 +163,30 @@ struct MCPSection: View { } } -private struct MCPStatusIndicator: View { +private struct MCPStatusRow: View { @ObservedObject private var manager = MCPServerManager.shared + let configuredPort: Int var body: some View { - IntegrationStatusIndicator(status: status, label: statusText) - } - - private var status: IntegrationStatus { - switch manager.state { - case .stopped: .stopped - case .starting: .starting - case .running: .running - case .failed: .failed - } - } - - private var statusText: String { - switch manager.state { - case .stopped: - String(localized: "Stopped") - case .starting: - String(localized: "Starting…") - case .running(let port): - String(format: String(localized: "Running on port %d"), port) - case .failed(let message): - if message.contains("48") || message.lowercased().contains("address already in use") { - String(localized: "Port is already in use. Try a different port or close the other process.") - } else { - String(format: String(localized: "Failed: %@"), message) + let presentation = MCPServerStatusPresentation(state: manager.state, configuredPort: configuredPort) + LabeledContent(String(localized: "Status")) { + HStack(spacing: 8) { + IntegrationStatusIndicator(status: presentation.status, label: presentation.title) + if presentation.offersRetry { + Button(String(localized: "Try Again")) { + manager.retry() + } + .controlSize(.small) + .accessibilityIdentifier("mcp-status-try-again") + } } } + if let detail = presentation.detail { + Text(detail) + .font(.caption) + .foregroundStyle(.secondary) + .textSelection(.enabled) + .fixedSize(horizontal: false, vertical: true) + } } } diff --git a/apple/TablePro/Views/Settings/Sections/MCPServerStatusPresentation.swift b/apple/TablePro/Views/Settings/Sections/MCPServerStatusPresentation.swift new file mode 100644 index 0000000000..2b81c5367b --- /dev/null +++ b/apple/TablePro/Views/Settings/Sections/MCPServerStatusPresentation.swift @@ -0,0 +1,58 @@ +// +// MCPServerStatusPresentation.swift +// TablePro +// + +import Foundation +import TableProMCP + +internal struct MCPServerStatusPresentation: Equatable { + let status: IntegrationStatus + let title: String + let detail: String? + let offersRetry: Bool + + internal init(state: MCPServerState, configuredPort: Int) { + switch state { + case .stopped: + status = .stopped + title = String(localized: "Stopped") + detail = nil + offersRetry = false + case .starting: + status = .starting + title = String(localized: "Starting…") + detail = nil + offersRetry = false + case .running(let port): + status = .running + title = String(format: String(localized: "Running on port %d"), Int(port)) + // The server falls back to a port the system picks; a client set up for the configured one + // would not reach it. + detail = configuredPort > 0 && Int(port) != configuredPort + ? String(format: String(localized: "Port %d was in use."), configuredPort) + : nil + offersRetry = false + case .failed(let failure): + status = .failed + offersRetry = true + switch failure { + case .socketFolderUnusable: + title = String(localized: "Couldn't start") + detail = String(localized: "The MCP server could not prepare its private socket folder.") + case .listenerUnavailable(let reason): + title = String(localized: "Couldn't start") + detail = MCPPortAllocatorError.everyCandidateRejected(lastFailure: reason).localizedDescription + case .noBoundPort: + title = String(localized: "Couldn't start") + detail = String(localized: "The MCP server started without a port.") + case .credentialUnavailable: + title = String(localized: "Couldn't start") + detail = String(localized: "The MCP server could not issue its bridge credential.") + case .listenerStopped(let reason): + title = String(localized: "Stopped unexpectedly") + detail = reason.isEmpty ? nil : reason + } + } + } +} diff --git a/apple/TablePro/Views/Settings/Sections/MCPTokenListView.swift b/apple/TablePro/Views/Settings/Sections/MCPTokenListView.swift index 87e5ba83c4..e949d0b88c 100644 --- a/apple/TablePro/Views/Settings/Sections/MCPTokenListView.swift +++ b/apple/TablePro/Views/Settings/Sections/MCPTokenListView.swift @@ -125,19 +125,13 @@ private struct MCPTokenRow: View { var body: some View { HStack(spacing: 10) { VStack(alignment: .leading, spacing: 3) { - HStack(spacing: 6) { - Text(token.name) + Text(token.name) + HStack(spacing: 8) { Text(token.permissions.displayName) - .font(.caption2) - .padding(.horizontal, 6) - .padding(.vertical, 2) - .background(permissionColor.opacity(0.15)) - .foregroundStyle(permissionColor) - .clipShape(Capsule()) - } + .font(.caption) + .foregroundStyle(.secondary) - HStack(spacing: 8) { Text(token.prefix + "…") .font(.system(.caption, design: .monospaced)) .foregroundStyle(.secondary) @@ -179,12 +173,4 @@ private struct MCPTokenRow: View { formatter.unitsStyle = .full return formatter.localizedString(for: lastUsed, relativeTo: .now) } - - private var permissionColor: Color { - switch token.permissions { - case .readOnly: .blue - case .readWrite: .orange - case .fullAccess: .red - } - } } diff --git a/apple/TableProTests/Core/MCP/Lifecycle/MCPServerLifecycleTests.swift b/apple/TableProTests/Core/MCP/Lifecycle/MCPServerLifecycleTests.swift index f79e98e4c6..ea65c5dd33 100644 --- a/apple/TableProTests/Core/MCP/Lifecycle/MCPServerLifecycleTests.swift +++ b/apple/TableProTests/Core/MCP/Lifecycle/MCPServerLifecycleTests.swift @@ -149,7 +149,8 @@ final class MCPServerManagerIdleStateTests: XCTestCase { func testServerStatesAreDistinguishable() { XCTAssertNotEqual(MCPServerState.stopped, .starting) XCTAssertNotEqual(MCPServerState.running(port: 1), .running(port: 2)) - XCTAssertEqual(MCPServerState.failed("boom"), .failed("boom")) + XCTAssertEqual(MCPServerState.failed(.listenerStopped(detail: "boom")), .failed(.listenerStopped(detail: "boom"))) + XCTAssertNotEqual(MCPServerState.failed(.noBoundPort), .failed(.credentialUnavailable)) } } diff --git a/apple/TableProTests/Core/MCP/Lifecycle/MCPServerOffContractTests.swift b/apple/TableProTests/Core/MCP/Lifecycle/MCPServerOffContractTests.swift index 0592aae74d..59ce1fdab2 100644 --- a/apple/TableProTests/Core/MCP/Lifecycle/MCPServerOffContractTests.swift +++ b/apple/TableProTests/Core/MCP/Lifecycle/MCPServerOffContractTests.swift @@ -69,6 +69,17 @@ struct MCPServerOffContractTests { _ = try readRefusal() } + @Test("Try Again in Settings is refused while MCP is off") + func tryAgainIsRefused() async throws { + let manager = makeManager() + + manager.retry() + await manager.stop() + + expectNoListener(manager) + _ = try readRefusal() + } + @Test("Pairing is refused before the approval prompt while MCP is off") func pairingIsRefused() async throws { let manager = makeManager() diff --git a/apple/TableProTests/Views/Settings/MCPServerStatusPresentationTests.swift b/apple/TableProTests/Views/Settings/MCPServerStatusPresentationTests.swift new file mode 100644 index 0000000000..0b4ddd3ba9 --- /dev/null +++ b/apple/TableProTests/Views/Settings/MCPServerStatusPresentationTests.swift @@ -0,0 +1,58 @@ +import Foundation +@testable import TablePro +import Testing + +struct MCPServerStatusPresentationTests { + @Test("Every failure offers Try Again and names its cause") + func failuresOfferRetry() { + let failures: [MCPServerFailure] = [ + .socketFolderUnusable, + .listenerUnavailable(detail: "Address already in use"), + .noBoundPort, + .credentialUnavailable, + .listenerStopped(detail: "The listener closed"), + ] + for failure in failures { + let presentation = MCPServerStatusPresentation(state: .failed(failure), configuredPort: 23_508) + #expect(presentation.status == .failed) + #expect(presentation.offersRetry) + #expect(presentation.detail?.isEmpty == false) + } + } + + @Test("A listener failure keeps the system's reason in the detail") + func listenerReasonShows() { + let presentation = MCPServerStatusPresentation( + state: .failed(.listenerUnavailable(detail: "Address already in use")), + configuredPort: 23_508 + ) + #expect(presentation.detail?.contains("Address already in use") == true) + } + + @Test("A path that happens to contain 48 is not read as a busy port") + func noFalsePortInUse() { + let presentation = MCPServerStatusPresentation( + state: .failed(.listenerUnavailable(detail: "/var/folders/48/T/mcp.sock: permission denied")), + configuredPort: 23_508 + ) + #expect(presentation.title == String(localized: "Couldn't start")) + #expect(presentation.detail?.contains("Port 23508") != true) + } + + @Test("Running on a port the system picked says the configured one was in use") + func fallbackPortIsNamed() { + let fallback = MCPServerStatusPresentation(state: .running(port: 51_234), configuredPort: 23_508) + #expect(fallback.status == .running) + #expect(fallback.detail == String(format: String(localized: "Port %d was in use."), 23_508)) + #expect(!fallback.offersRetry) + + let configured = MCPServerStatusPresentation(state: .running(port: 23_508), configuredPort: 23_508) + #expect(configured.detail == nil) + } + + @Test("Stopped and starting offer nothing") + func idleStatesOfferNothing() { + #expect(!MCPServerStatusPresentation(state: .stopped, configuredPort: 23_508).offersRetry) + #expect(!MCPServerStatusPresentation(state: .starting, configuredPort: 23_508).offersRetry) + } +} From 1bca221755daa8a85214964e6f77583996f875aa Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Tue, 3 Nov 2026 11:19:13 +0700 Subject: [PATCH 05/13] refactor(ai): one provider status for the Settings row, the provider sheet and the chat panel --- .../AI/ClaudeAgent/ClaudeAgentService.swift | 25 ---- .../TablePro/Models/AI/AIProviderStatus.swift | 131 ++++++++++++++++++ .../Views/AIChat/AIChatPanelView.swift | 82 +++++------ .../Settings/AIProviderDetailSheet.swift | 60 ++++---- .../Views/Settings/AISettingsView.swift | 91 +++--------- .../Components/AIProviderStatusLabel.swift | 32 +++++ .../Models/AIProviderStatusTests.swift | 78 +++++++++++ 7 files changed, 330 insertions(+), 169 deletions(-) create mode 100644 apple/TablePro/Models/AI/AIProviderStatus.swift create mode 100644 apple/TablePro/Views/Settings/Components/AIProviderStatusLabel.swift create mode 100644 apple/TableProTests/Models/AIProviderStatusTests.swift diff --git a/apple/TablePro/Core/AI/ClaudeAgent/ClaudeAgentService.swift b/apple/TablePro/Core/AI/ClaudeAgent/ClaudeAgentService.swift index 2e2d5f2c6b..496748303e 100644 --- a/apple/TablePro/Core/AI/ClaudeAgent/ClaudeAgentService.swift +++ b/apple/TablePro/Core/AI/ClaudeAgent/ClaudeAgentService.swift @@ -64,31 +64,6 @@ final class ClaudeAgentService: ObservableObject { } } - var statusDescription: String { - switch state { - case .unknown: - return String(localized: "Checking for the Claude Code command line tool…") - case .notInstalled: - return String(localized: "Claude Code is not installed.") - case .outdated(let version): - return String( - format: String(localized: "Claude Code %@ is too old. Version %@ or newer is required."), - version, - ClaudeAgentCLI.minimumVersion - ) - case .signedOut: - return String(localized: "Claude Code is installed but not signed in.") - case .signedIn(let account, let plan): - if let account, let plan { - return String(format: String(localized: "Signed in as %@ on the %@ plan."), account, plan) - } - if let account { - return String(format: String(localized: "Signed in as %@."), account) - } - return String(localized: "Signed in.") - } - } - var remedyCommand: String? { switch state { case .notInstalled, .outdated: diff --git a/apple/TablePro/Models/AI/AIProviderStatus.swift b/apple/TablePro/Models/AI/AIProviderStatus.swift new file mode 100644 index 0000000000..760df5387e --- /dev/null +++ b/apple/TablePro/Models/AI/AIProviderStatus.swift @@ -0,0 +1,131 @@ +// +// AIProviderStatus.swift +// TablePro +// + +import Foundation + +// One answer to "can this provider answer right now", read by the Settings row, the provider sheet +// and the chat panel, so they never disagree. +internal enum AIProviderStatus: Equatable, Sendable { + case checking + case ready(detail: String?) + case needsAPIKey + case needsSignIn + case signingIn + case needsInstall + case needsUpdate(version: String) + case failed(message: String) + case notConfigured + + internal enum Action: Equatable, Sendable { + case addAPIKey + case signIn + case install + case openSettings + } + + internal var isReady: Bool { + if case .ready = self { return true } + return false + } + + internal var title: String { + switch self { + case .checking: String(localized: "Checking…") + case .ready(let detail): detail ?? String(localized: "Ready") + case .needsAPIKey: String(localized: "Needs an API key") + case .needsSignIn: String(localized: "Not signed in") + case .signingIn: String(localized: "Signing in…") + case .needsInstall: String(localized: "Claude Code not installed") + case .needsUpdate(let version): String(format: String(localized: "Claude Code %@ is too old"), version) + case .failed(let message): message + case .notConfigured: String(localized: "Not configured") + } + } + + // Only a state the user has to fix carries a symbol; a working or busy provider shows none. + internal var severity: NoticeSeverity? { + switch self { + case .checking, .ready, .signingIn: nil + case .failed: .error + case .needsAPIKey, .needsSignIn, .needsInstall, .needsUpdate, .notConfigured: .warning + } + } + + internal var action: Action? { + switch self { + case .checking, .ready, .signingIn: nil + case .needsAPIKey: .addAPIKey + case .needsSignIn: .signIn + case .needsInstall, .needsUpdate: .install + case .failed, .notConfigured: .openSettings + } + } + + internal var actionTitle: String? { + switch action { + case .addAPIKey: String(localized: "Add API Key…") + case .signIn: String(localized: "Sign In…") + case .install: String(localized: "Set Up…") + case .openSettings: String(localized: "Settings…") + case nil: nil + } + } + + internal static func resolve( + provider: AIProviderConfig, + hasAPIKey: Bool, + oauthState: OAuthAuthState?, + serviceError: String?, + claudeAgent: ClaudeAgentService.InstallState + ) -> AIProviderStatus { + switch provider.authStyle { + case .apiKey: + return hasAPIKey ? .ready(detail: String(localized: "API key set")) : .needsAPIKey + case .optionalApiKey: + if hasAPIKey { return .ready(detail: String(localized: "API key set")) } + return endpointStatus(provider.endpoint.isEmpty ? provider.defaultEndpoint : provider.endpoint) + case .oauth: + if let serviceError, !serviceError.isEmpty { return .failed(message: serviceError) } + // No state yet: the sign-in lives in a service that has not answered. + guard let oauthState else { return .checking } + switch oauthState { + case .signedIn(let identity): + return .ready(detail: identity.isEmpty + ? String(localized: "Signed in") + : String(format: String(localized: "Signed in as %@"), identity)) + case .signingIn: + return .signingIn + case .signedOut: + return .needsSignIn + } + case .none: + if provider.type == .claudeAgent { return claudeAgentStatus(claudeAgent) } + return endpointStatus(provider.endpoint.isEmpty ? provider.defaultEndpoint : provider.endpoint) + } + } + + private static func endpointStatus(_ endpoint: String) -> AIProviderStatus { + guard !endpoint.isEmpty else { return .notConfigured } + guard let host = URL(string: endpoint)?.host, !host.isEmpty else { return .ready(detail: endpoint) } + if host == "localhost" || host == "127.0.0.1" { return .ready(detail: String(localized: "Local")) } + return .ready(detail: host) + } + + private static func claudeAgentStatus(_ state: ClaudeAgentService.InstallState) -> AIProviderStatus { + switch state { + case .unknown: + return .checking + case .notInstalled: + return .needsInstall + case .outdated(let version): + return .needsUpdate(version: version) + case .signedOut: + return .needsSignIn + case .signedIn(let account, _): + guard let account, !account.isEmpty else { return .ready(detail: String(localized: "Signed in")) } + return .ready(detail: String(format: String(localized: "Signed in as %@"), account)) + } + } +} diff --git a/apple/TablePro/Views/AIChat/AIChatPanelView.swift b/apple/TablePro/Views/AIChat/AIChatPanelView.swift index 8f2558e756..a79fa47227 100644 --- a/apple/TablePro/Views/AIChat/AIChatPanelView.swift +++ b/apple/TablePro/Views/AIChat/AIChatPanelView.swift @@ -10,7 +10,6 @@ import SwiftUI /// AI chat panel displayed alongside the main editor content struct AIChatPanelView: View { @ObservedObject private var slashCommandStorage = CustomSlashCommandStorage.shared - private static let warningBackgroundOpacity: Double = 0.1 let connection: DatabaseConnection var currentQuery: String? @@ -53,6 +52,7 @@ struct AIChatPanelView: View { } if let error = viewModel.errorMessage { + Divider() errorBanner(error) } @@ -107,44 +107,37 @@ struct AIChatPanelView: View { .frame(maxWidth: .infinity, maxHeight: .infinity) } - /// A transcript outlives the provider that produced it, so removing the active provider leaves - /// this pane with messages and nothing to send another. Without this the pane keeps the - /// transcript and drops the composer, the model picker and the send button with no reason - /// given and no route back: the "Go to Settings…" affordance lives on the empty-transcript - /// branch alone. + // The empty pane and the footer under a transcript say the same thing. + private static let noProviderTitle = String(localized: "No AI Provider") + private static let noProviderDetail = String(localized: "Choose an AI provider in Settings to chat.") + + // A transcript outlives the provider that wrote it, so the pane keeps it read-only with a way back. private var noProviderFooter: some View { - VStack(alignment: .leading, spacing: 6) { + VStack(spacing: 0) { Divider() - HStack(spacing: 8) { - Image(systemName: "exclamationmark.triangle") - .foregroundStyle(.secondary) - Text("No AI provider is active, so this conversation is read-only.") - .font(.callout) - .foregroundStyle(.secondary) - .fixedSize(horizontal: false, vertical: true) - Spacer() + PaneNoticeBar(severity: .warning, onBar: false) { + PaneNoticeText(title: Self.noProviderTitle, detail: Self.noProviderDetail) + } actions: { if viewModel.isStreaming { Button(String(localized: "Stop Generating")) { viewModel.cancelStream() } - .controlSize(.small) } Button(String(localized: "Settings…")) { WindowOpener.shared.openSettings(tab: .ai) } - .controlSize(.small) } .chatColumn(contentWidth) - .padding(8) + .paneBarBackground() } } private var noProviderState: some View { EmptyStateView( - icon: "gear", - title: String(localized: "AI Not Configured"), - description: String(localized: "Configure an AI provider in Settings to start chatting."), - actionTitle: String(localized: "Go to Settings…"), + icon: "sparkles", + title: Self.noProviderTitle, + description: Self.noProviderDetail, + actionTitle: String(localized: "Settings…"), action: { WindowOpener.shared.openSettings(tab: .ai) } @@ -155,37 +148,28 @@ struct AIChatPanelView: View { // MARK: - Error Banner private func errorBanner(_ message: String) -> some View { - HStack(spacing: 6) { - Image(systemName: "exclamationmark.triangle.fill") - .foregroundStyle(.yellow) - VStack(alignment: .leading, spacing: 4) { - Text(message) - .font(.caption) - .foregroundStyle(.secondary) - .lineLimit(3) - .help(message) - if viewModel.onDeviceRefusal != nil, let provider = viewModel.fallbackProviderName { - Button(String(format: String(localized: "Send to %@"), provider)) { - viewModel.sendRefusedTurnToProvider() - } - .controlSize(.small) + PaneNoticeBar( + severity: .warning, + onBar: false, + dismissLabel: String(localized: "Dismiss error"), + onDismiss: { viewModel.clearError() } + ) { + Text(message) + .font(.callout) + .lineLimit(3) + .fixedSize(horizontal: false, vertical: true) + .textSelection(.enabled) + .help(message) + } actions: { + if viewModel.onDeviceRefusal != nil, let provider = viewModel.fallbackProviderName { + Button(String(format: String(localized: "Send to %@"), provider)) { + viewModel.sendRefusedTurnToProvider() } } - Spacer() - Button { - viewModel.clearError() - } label: { - Image(systemName: "xmark") - .frame(width: 24, height: 24) - .foregroundStyle(.secondary) - } - .buttonStyle(.plain) - .accessibilityLabel(String(localized: "Dismiss error")) } + // Capped like the transcript, while the bar material spans the pane. .chatColumn(contentWidth) - .padding(.horizontal, 12) - .padding(.vertical, 6) - .background(.yellow.opacity(Self.warningBackgroundOpacity)) + .paneBarBackground() } // MARK: - Input Area diff --git a/apple/TablePro/Views/Settings/AIProviderDetailSheet.swift b/apple/TablePro/Views/Settings/AIProviderDetailSheet.swift index f77d3cff6a..dde30a684a 100644 --- a/apple/TablePro/Views/Settings/AIProviderDetailSheet.swift +++ b/apple/TablePro/Views/Settings/AIProviderDetailSheet.swift @@ -188,11 +188,7 @@ struct AIProviderDetailSheet: View { private var claudeAgentAuthSection: some View { Section { HStack(spacing: 8) { - Image(systemName: claudeAgentService.state.isUsable - ? "checkmark.circle.fill" - : "exclamationmark.triangle.fill") - .foregroundStyle(claudeAgentService.state.isUsable ? Color.green : Color.orange) - Text(claudeAgentService.statusDescription) + AIProviderStatusLabel(status: claudeAgentStatus) .font(.callout) Spacer() Button(String(localized: "Recheck")) { @@ -200,6 +196,18 @@ struct AIProviderDetailSheet: View { } .disabled(claudeAgentService.isRefreshing) } + switch claudeAgentService.state { + case .signedIn(_, let plan?) where !plan.isEmpty: + Text(String(format: String(localized: "Plan: %@"), plan)) + .font(.caption) + .foregroundStyle(.secondary) + case .outdated: + Text(String(format: String(localized: "Version %@ or newer is required."), ClaudeAgentCLI.minimumVersion)) + .font(.caption) + .foregroundStyle(.secondary) + default: + EmptyView() + } if let command = claudeAgentService.remedyCommand { HStack { Text(command) @@ -222,6 +230,16 @@ struct AIProviderDetailSheet: View { ClaudeAgentDisclosureSection() } + private var claudeAgentStatus: AIProviderStatus { + AIProviderStatus.resolve( + provider: draft, + hasAPIKey: false, + oauthState: nil, + serviceError: nil, + claudeAgent: claudeAgentService.state + ) + } + private var apiKeyAuthSection: some View { Section { SecureField(String(localized: "API Key"), text: $apiKey) @@ -244,12 +262,10 @@ struct AIProviderDetailSheet: View { .disabled(isTesting || (draft.authStyle == .apiKey && apiKey.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)) } if case .success = testResult { - Label(String(localized: "Connection successful"), systemImage: "checkmark.circle.fill") - .foregroundStyle(.green) + NoticeLabel(String(localized: "Connection successful"), severity: .success) .font(.caption) } else if case .failure(let message) = testResult { - Label(message, systemImage: "xmark.circle.fill") - .foregroundStyle(.red) + NoticeLabel(message, severity: .error) .font(.caption) .lineLimit(3) } @@ -295,11 +311,7 @@ struct AIProviderDetailSheet: View { case .signedIn(let username): HStack { - Label( - String(format: String(localized: "Signed in as %@"), username), - systemImage: "checkmark.circle.fill" - ) - .foregroundStyle(.green) + NoticeLabel(String(format: String(localized: "Signed in as %@"), username), severity: .success) Spacer() Button(String(localized: "Sign Out")) { Task { await copilotService.signOut() } @@ -307,10 +319,9 @@ struct AIProviderDetailSheet: View { } } - if let copilotErrorMessage { - Text(copilotErrorMessage) + if let message = copilotErrorMessage ?? copilotService.statusMessage { + NoticeLabel(message, severity: .error) .font(.caption) - .foregroundStyle(.red) } statusRow @@ -348,8 +359,7 @@ struct AIProviderDetailSheet: View { case .signedIn(let email, let planType): VStack(alignment: .leading, spacing: 6) { HStack { - Label(chatGPTCodexSignedInLabel(email: email), systemImage: "checkmark.circle.fill") - .foregroundStyle(.green) + NoticeLabel(chatGPTCodexSignedInLabel(email: email), severity: .success) Spacer() Button(String(localized: "Sign Out")) { Task { await chatGPTCodexService.signOut() } @@ -364,9 +374,8 @@ struct AIProviderDetailSheet: View { } if let message = chatGPTCodexService.errorMessage { - Text(message) + NoticeLabel(message, severity: .error) .font(.caption) - .foregroundStyle(.red) .lineLimit(3) } } header: { @@ -420,8 +429,7 @@ struct AIProviderDetailSheet: View { case .running: EmptyView() case .error(let message): - Label(message, systemImage: "exclamationmark.triangle.fill") - .foregroundStyle(.orange) + NoticeLabel(message, severity: .error) .font(.caption) .lineLimit(2) } @@ -472,8 +480,7 @@ struct AIProviderDetailSheet: View { .foregroundStyle(.secondary) } if resolvedEndpoint?.isPlaintextToRemoteHost == true { - Label(cleartextCaution, systemImage: "exclamationmark.triangle.fill") - .foregroundStyle(.orange) + NoticeLabel(cleartextCaution) .font(.caption) .lineLimit(2) } @@ -654,9 +661,8 @@ struct AIProviderDetailSheet: View { } if let modelFetchError { HStack { - Text(modelFetchError) + NoticeLabel(modelFetchError, severity: .error) .font(.caption) - .foregroundStyle(.red) .lineLimit(2) Spacer() Button(String(localized: "Reload")) { diff --git a/apple/TablePro/Views/Settings/AISettingsView.swift b/apple/TablePro/Views/Settings/AISettingsView.swift index 6fc07cb1ee..1f60581248 100644 --- a/apple/TablePro/Views/Settings/AISettingsView.swift +++ b/apple/TablePro/Views/Settings/AISettingsView.swift @@ -175,9 +175,8 @@ struct AISettingsView: View { VStack(alignment: .leading, spacing: 2) { Text(provider.displayName) .fontWeight(.regular) - Text(statusText(for: provider)) + AIProviderStatusLabel(status: status(for: provider), showsReadySymbol: false) .font(.caption) - .foregroundStyle(.secondary) } Spacer() @@ -368,78 +367,34 @@ struct AISettingsView: View { return String(format: String(localized: "Remove %@?"), provider.displayName) } - // MARK: - Status text - - private func statusText(for provider: AIProviderConfig) -> String { - switch provider.authStyle { - case .oauth: - return oauthStatusText(for: provider.type) - case .apiKey: - return apiKeyStatusText(for: provider) - case .optionalApiKey: - if provider.type == .custom { - return customStatusText(for: provider) - } - return apiKeyStatusText(for: provider) - case .none: - if provider.type == .claudeAgent { - return claudeAgentStatusText() - } - let endpoint = provider.endpoint.isEmpty ? provider.defaultEndpoint : provider.endpoint - guard !endpoint.isEmpty else { return String(localized: "Not configured") } - if let host = URL(string: endpoint)?.host, host == "localhost" || host == "127.0.0.1" { - return String(localized: "Local") - } - return endpoint - } - } + // MARK: - Status - private func apiKeyStatusText(for provider: AIProviderConfig) -> String { - providersWithKey.contains(provider.id) - ? String(localized: "API key set") - : String(localized: "Not configured") - } - - private func oauthStatusText(for type: AIProviderType) -> String { - switch OAuthProviderRegistry.service(for: type)?.oauthState ?? .signedOut { - case .signedIn(let identity): - return identity.isEmpty - ? String(localized: "Signed in") - : String(format: String(localized: "Signed in as %@"), identity) - case .signingIn: - return String(localized: "Signing in…") - case .signedOut: - return String(localized: "Not signed in") - } + private func status(for provider: AIProviderConfig) -> AIProviderStatus { + AIProviderStatus.resolve( + provider: provider, + hasAPIKey: providersWithKey.contains(provider.id), + oauthState: oauthState(for: provider.type), + serviceError: serviceError(for: provider.type), + claudeAgent: claudeAgentService.state + ) } - /// Claude Agent authenticates through the CLI rather than an endpoint or a key, so the endpoint - /// arm this type used to fall into could only ever answer "Not configured", however well the - /// provider was working. The sheet has always read the service; this row now reads the same one. - private func claudeAgentStatusText() -> String { - switch claudeAgentService.state { - case .signedIn(let account, _): - guard let account, !account.isEmpty else { return String(localized: "Signed in") } - return String(format: String(localized: "Signed in as %@"), account) - case .signedOut: - return String(localized: "Not signed in") - case .outdated(let version): - return String(format: String(localized: "Claude Code %@ is too old"), version) - case .notInstalled: - return String(localized: "Claude Code not installed") - case .unknown: - return String(localized: "Checking…") - } + // Copilot's sign-in is known only once its language server runs, which this row starts. + private func oauthState(for type: AIProviderType) -> OAuthAuthState? { + if type == .copilot, copilotService.status != .running { return nil } + return OAuthProviderRegistry.service(for: type)?.oauthState } - private func customStatusText(for provider: AIProviderConfig) -> String { - if providersWithKey.contains(provider.id) { - return String(localized: "API key set") - } - if let host = URL(string: provider.endpoint)?.host, !host.isEmpty { - return host + private func serviceError(for type: AIProviderType) -> String? { + switch type { + case .copilot: + if case .error(let message) = copilotService.status { return message } + return copilotService.statusMessage + case .chatgptCodex: + return chatGPTCodexService.errorMessage + default: + return nil } - return String(localized: "Not configured") } private func refreshAccountStatus(of types: Set) async { diff --git a/apple/TablePro/Views/Settings/Components/AIProviderStatusLabel.swift b/apple/TablePro/Views/Settings/Components/AIProviderStatusLabel.swift new file mode 100644 index 0000000000..c3329020ea --- /dev/null +++ b/apple/TablePro/Views/Settings/Components/AIProviderStatusLabel.swift @@ -0,0 +1,32 @@ +// +// AIProviderStatusLabel.swift +// TablePro +// + +import SwiftUI + +internal struct AIProviderStatusLabel: View { + let status: AIProviderStatus + var showsReadySymbol = true + + var body: some View { + switch status { + case .checking, .signingIn: + HStack(spacing: 6) { + ProgressView() + .controlSize(.small) + Text(status.title) + .foregroundStyle(.secondary) + } + default: + if let severity = status.severity { + NoticeLabel(status.title, severity: severity) + } else if showsReadySymbol { + NoticeLabel(status.title, severity: .success) + } else { + Text(status.title) + .foregroundStyle(.secondary) + } + } + } +} diff --git a/apple/TableProTests/Models/AIProviderStatusTests.swift b/apple/TableProTests/Models/AIProviderStatusTests.swift new file mode 100644 index 0000000000..0cdeb75884 --- /dev/null +++ b/apple/TableProTests/Models/AIProviderStatusTests.swift @@ -0,0 +1,78 @@ +import Foundation +@testable import TablePro +import Testing + +@MainActor +struct AIProviderStatusTests { + private func status( + _ type: AIProviderType, + endpoint: String? = nil, + hasAPIKey: Bool = false, + oauthState: OAuthAuthState? = nil, + serviceError: String? = nil, + claudeAgent: ClaudeAgentService.InstallState = .unknown + ) -> AIProviderStatus { + var provider = AIProviderConfig(name: "", type: type) + if let endpoint { provider.endpoint = endpoint } + return AIProviderStatus.resolve( + provider: provider, + hasAPIKey: hasAPIKey, + oauthState: oauthState, + serviceError: serviceError, + claudeAgent: claudeAgent + ) + } + + @Test("A provider that needs a key says so and offers to add one") + func missingKey() { + let missing = status(.openAI) + #expect(missing == .needsAPIKey) + #expect(missing.action == .addAPIKey) + #expect(missing.severity == .warning) + #expect(status(.openAI, hasAPIKey: true).isReady) + } + + @Test("A provider whose key is optional is ready without one") + func optionalKeyIsReadyWithoutOne() { + #expect(status(.openCode).isReady) + #expect(status(.custom, endpoint: "https://llm.example.com/v1") == .ready(detail: "llm.example.com")) + #expect(status(.custom, endpoint: "") == .notConfigured) + } + + @Test("A Copilot error shows on the row, not only in the sheet") + func serviceErrorWins() { + let failed = status(.copilot, oauthState: .signedIn(identity: "octocat"), serviceError: "Copilot subscription inactive") + #expect(failed == .failed(message: "Copilot subscription inactive")) + #expect(failed.severity == .error) + } + + @Test("Sign-in states read from the service, and an unanswered service is still checking") + func oauthStates() { + #expect(status(.copilot) == .checking) + #expect(status(.copilot, oauthState: .signedOut) == .needsSignIn) + #expect(status(.chatgptCodex, oauthState: .signingIn) == .signingIn) + #expect(status(.chatgptCodex, oauthState: .signedIn(identity: "me@example.com")).isReady) + } + + @Test("Claude Code states map one to one") + func claudeAgentStates() { + #expect(status(.claudeAgent, claudeAgent: .unknown) == .checking) + #expect(status(.claudeAgent, claudeAgent: .notInstalled) == .needsInstall) + #expect(status(.claudeAgent, claudeAgent: .outdated(version: "1.0.0")) == .needsUpdate(version: "1.0.0")) + #expect(status(.claudeAgent, claudeAgent: .signedOut) == .needsSignIn) + #expect(status(.claudeAgent, claudeAgent: .signedIn(account: "me", plan: "Max")).isReady) + } + + @Test("A local server reads as local") + func localServer() { + #expect(status(.ollama) == .ready(detail: String(localized: "Local"))) + } + + @Test("Only states the user has to fix carry a symbol and an action") + func readyAndBusyStatesAreQuiet() { + for quiet in [AIProviderStatus.checking, .signingIn, .ready(detail: nil)] { + #expect(quiet.severity == nil) + #expect(quiet.action == nil) + } + } +} From 8cc42e97fc1454d2b596244d933c2aaaf459cb64 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Tue, 3 Nov 2026 11:19:13 +0700 Subject: [PATCH 06/13] fix(notifications): read the permission again when TablePro becomes active --- .../NotificationPermissionMonitor.swift | 40 +++++++++++++ .../Settings/NotificationsSettingsView.swift | 10 ++-- .../NotificationPermissionMonitorTests.swift | 58 +++++++++++++++++++ 3 files changed, 102 insertions(+), 6 deletions(-) create mode 100644 apple/TablePro/Core/Services/Notifications/NotificationPermissionMonitor.swift create mode 100644 apple/TableProTests/Views/Settings/NotificationPermissionMonitorTests.swift diff --git a/apple/TablePro/Core/Services/Notifications/NotificationPermissionMonitor.swift b/apple/TablePro/Core/Services/Notifications/NotificationPermissionMonitor.swift new file mode 100644 index 0000000000..87721602aa --- /dev/null +++ b/apple/TablePro/Core/Services/Notifications/NotificationPermissionMonitor.swift @@ -0,0 +1,40 @@ +// +// NotificationPermissionMonitor.swift +// TablePro +// + +import AppKit +import Combine +import UserNotifications + +// The permission changes in System Settings while TablePro is in the background, so the pane reads +// it again each time the app comes back. It never asks for permission: NotificationAuthorization +// is the one requester. +@MainActor +internal final class NotificationPermissionMonitor: ObservableObject { + @Published internal private(set) var status: UNAuthorizationStatus = .notDetermined + + private let authorization: NotificationAuthorization + private var activation: AnyCancellable? + private var generation = 0 + + internal init( + authorization: NotificationAuthorization = .shared, + center: NotificationCenter = .default + ) { + self.authorization = authorization + activation = center.publisher(for: NSApplication.didBecomeActiveNotification) + .sink { [weak self] _ in + Task { @MainActor in await self?.refresh() } + } + } + + // A slower earlier read never overwrites a newer one. + internal func refresh() async { + generation += 1 + let current = generation + let latest = await authorization.refresh() + guard current == generation else { return } + status = latest + } +} diff --git a/apple/TablePro/Views/Settings/NotificationsSettingsView.swift b/apple/TablePro/Views/Settings/NotificationsSettingsView.swift index 6a4e147837..7517f80564 100644 --- a/apple/TablePro/Views/Settings/NotificationsSettingsView.swift +++ b/apple/TablePro/Views/Settings/NotificationsSettingsView.swift @@ -10,7 +10,7 @@ import UserNotifications struct NotificationsSettingsView: View { @Binding var settings: NotificationSettings - @State private var authorizationStatus: UNAuthorizationStatus = .notDetermined + @StateObject private var permission = NotificationPermissionMonitor() var body: some View { Form { @@ -32,12 +32,10 @@ struct NotificationsSettingsView: View { .foregroundStyle(.secondary) } - if authorizationStatus == .denied { + if permission.status == .denied { Section { HStack(spacing: 8) { - Image(systemName: "exclamationmark.triangle.fill") - .foregroundStyle(.orange) - Text("Notifications are turned off for TablePro in System Settings.") + NoticeLabel(String(localized: "Notifications are turned off for TablePro in System Settings.")) Spacer() Button("Open System Settings", action: Self.openSystemSettings) } @@ -46,7 +44,7 @@ struct NotificationsSettingsView: View { } .formStyle(.grouped) .task { - authorizationStatus = await NotificationAuthorization.shared.refresh() + await permission.refresh() } } diff --git a/apple/TableProTests/Views/Settings/NotificationPermissionMonitorTests.swift b/apple/TableProTests/Views/Settings/NotificationPermissionMonitorTests.swift new file mode 100644 index 0000000000..3b6f9d5813 --- /dev/null +++ b/apple/TableProTests/Views/Settings/NotificationPermissionMonitorTests.swift @@ -0,0 +1,58 @@ +import AppKit +import Foundation +@testable import TablePro +import TableProTestSupport +import Testing +import UserNotifications + +@MainActor +private final class StubPermissionPresenter: UserNotificationPresenting { + var status: UNAuthorizationStatus = .authorized + private(set) var requests = 0 + + func authorizationStatus() async -> UNAuthorizationStatus { status } + + func requestAuthorization(options: UNAuthorizationOptions) async -> Bool { + requests += 1 + return false + } + + func setCategories(_ categories: Set) {} + + func post(_ request: UNNotificationRequest) async throws {} + + func removeDelivered(identifiers: [String]) {} +} + +@MainActor +struct NotificationPermissionMonitorTests { + @Test("A permission turned off in System Settings shows once TablePro is active again") + func readsAgainOnActivation() async throws { + let presenter = StubPermissionPresenter() + let center = NotificationCenter() + let monitor = NotificationPermissionMonitor( + authorization: NotificationAuthorization(presenter: presenter), + center: center + ) + await monitor.refresh() + #expect(monitor.status == .authorized) + + presenter.status = .denied + center.post(name: NSApplication.didBecomeActiveNotification, object: nil) + + try await waitUntil { monitor.status == .denied } + } + + @Test("Reading the permission never asks for it") + func neverRequests() async { + let presenter = StubPermissionPresenter() + presenter.status = .notDetermined + let monitor = NotificationPermissionMonitor( + authorization: NotificationAuthorization(presenter: presenter), + center: NotificationCenter() + ) + await monitor.refresh() + #expect(monitor.status == .notDetermined) + #expect(presenter.requests == 0) + } +} From 37c1c8d47b5fdb9c06a06ddb117ea281fd05e634 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Tue, 3 Nov 2026 11:19:13 +0700 Subject: [PATCH 07/13] refactor(connections): edit connection tags in a token field --- .../Connection/ConnectionTagEditor.swift | 106 +++++------- .../Connection/ConnectionTagTokenField.swift | 157 ++++++++++++++++++ .../ConnectionTagTokenFieldTests.swift | 84 ++++++++++ .../Connection/ConnectionTagTokensTests.swift | 28 ++++ 4 files changed, 309 insertions(+), 66 deletions(-) create mode 100644 apple/TablePro/Views/Connection/ConnectionTagTokenField.swift create mode 100644 apple/TableProTests/Views/Connection/ConnectionTagTokenFieldTests.swift create mode 100644 apple/TableProTests/Views/Connection/ConnectionTagTokensTests.swift diff --git a/apple/TablePro/Views/Connection/ConnectionTagEditor.swift b/apple/TablePro/Views/Connection/ConnectionTagEditor.swift index fc890845e6..a146c1839c 100644 --- a/apple/TablePro/Views/Connection/ConnectionTagEditor.swift +++ b/apple/TablePro/Views/Connection/ConnectionTagEditor.swift @@ -3,14 +3,19 @@ // TablePro // +import AppKit +import os import SwiftUI +// Tags are a set the person names, so they edit as tokens: type to complete or create one, Delete to +// remove one. The pull-down beside it keeps the tag colors, creation with a color and deletion. struct ConnectionTagEditor: View { @Binding var tagIds: [UUID] @State private var allTags: [ConnectionTag] = [] @State private var showingCreateSheet = false private let tagStorage = TagStorage.shared + private static let logger = Logger(subsystem: "com.TablePro", category: "ConnectionTagEditor") private var selectedTags: [ConnectionTag] { tagIds.compactMap { id in allTags.first { $0.id == id } } @@ -18,7 +23,11 @@ struct ConnectionTagEditor: View { var body: some View { HStack(spacing: 6) { - selectionView + ConnectionTagTokenField( + tokens: selectedTags.map(\.name), + completions: allTags.map(\.name), + onChange: applyTokens + ) tagMenu } .task { allTags = tagStorage.loadTags() } @@ -32,45 +41,27 @@ struct ConnectionTagEditor: View { } } - @ViewBuilder - private var selectionView: some View { - if !selectedTags.isEmpty { - HStack(spacing: 4) { - ForEach(selectedTags) { tag in - tagChip(tag) + private func applyTokens(_ names: [String]) { + var created = false + let ids: [UUID] = ConnectionTagTokens.resolve(names, among: allTags).compactMap { entry in + switch entry { + case .existing(let id): + return id + case .new(let name): + let tag = ConnectionTag(name: name, isPreset: false, color: .gray) + do { + try tagStorage.addTag(tag) + created = true + return tag.id + } catch { + Self.logger.error("Could not create a tag from the token field: \(error.publicLogShape, privacy: .public)") + return nil } } } - } - - private func tagChip(_ tag: ConnectionTag) -> some View { - HStack(spacing: 4) { - Circle() - .fill(tag.color.color) - .frame(width: 7, height: 7) - .accessibilityHidden(true) - Text(tag.name) - .lineLimit(1) - Button { toggle(tag) } label: { - Image(systemName: "xmark") - .imageScale(.small) - .foregroundStyle(.secondary) - } - .buttonStyle(.borderless) - .help(Text(removeLabel(for: tag))) - .accessibilityLabel(Text(removeLabel(for: tag))) - } - .padding(.leading, 7) - .padding(.trailing, 5) - .padding(.vertical, 2) - .background(tag.color.color.opacity(0.14), in: Capsule()) - .overlay(Capsule().strokeBorder(tag.color.color.opacity(0.35), lineWidth: 1)) - .accessibilityElement(children: .contain) - .accessibilityLabel(Text(tag.name)) - } - - private func removeLabel(for tag: ConnectionTag) -> String { - String(format: String(localized: "Remove tag %@"), tag.name) + if created { allTags = tagStorage.loadTags() } + guard ids != tagIds else { return } + tagIds = ids } private var tagMenu: some View { @@ -80,7 +71,7 @@ struct ConnectionTagEditor: View { toggle(tag) } label: { HStack { - Image(nsImage: colorDot(tag.color.color)) + Image(nsImage: Self.tagSymbol(tag.color)) Text(tag.name) if tagIds.contains(tag.id) { Spacer() @@ -112,32 +103,19 @@ struct ConnectionTagEditor: View { } } } label: { - menuLabel + Image(systemName: "tag") } .menuStyle(.button) .buttonStyle(.borderless) .menuIndicator(.visible) .fixedSize() - .help(Text("Add tags")) + .help(Text("Choose Tags")) + // An icon-only pull-down publishes no name of its own. + .accessibilityElement(children: .contain) + .accessibilityLabel(Text("Choose Tags")) .accessibilityIdentifier("connection-form-tags") } - /// The placeholder is the pull-down's own title, the way every macOS pull-down names itself, - /// so the words open the menu instead of sitting beside it as unclickable text. Once a tag is - /// picked the chips say what is selected, and the title moves into an icon-less `Label` so the - /// control keeps its name while showing nothing but its own disclosure chevron. A chevron drawn - /// here would land beside that one, not replace it. - @ViewBuilder - private var menuLabel: some View { - if selectedTags.isEmpty { - Text("Add tags") - .foregroundStyle(.secondary) - } else { - Label { Text("Add tags") } icon: { EmptyView() } - .labelStyle(.iconOnly) - } - } - private func toggle(_ tag: ConnectionTag) { if tagIds.contains(tag.id) { tagIds = tagIds.filter { $0 != tag.id } @@ -159,13 +137,11 @@ struct ConnectionTagEditor: View { allTags = tagStorage.loadTags() } - private func colorDot(_ color: Color) -> NSImage { - let size = NSSize(width: 10, height: 10) - let image = NSImage(size: size, flipped: false) { rect in - NSColor(color).setFill() - NSBezierPath(ovalIn: rect).fill() - return true - } + // A menu draws a SwiftUI symbol as a template and drops its tint, so the colored tag is an image. + private static func tagSymbol(_ color: ConnectionColor) -> NSImage { + let configuration = NSImage.SymbolConfiguration(paletteColors: [NSColor(color.color)]) + let image = NSImage(systemSymbolName: "tag.fill", accessibilityDescription: nil)? + .withSymbolConfiguration(configuration) ?? NSImage() image.isTemplate = false return image } @@ -200,10 +176,8 @@ private struct CreateTagSheet: View { } if let errorMessage { - Label(errorMessage, systemImage: "exclamationmark.triangle.fill") + NoticeLabel(errorMessage, severity: .error) .font(.caption) - .foregroundStyle(.red) - .fixedSize(horizontal: false, vertical: true) .frame(maxWidth: .infinity, alignment: .leading) } diff --git a/apple/TablePro/Views/Connection/ConnectionTagTokenField.swift b/apple/TablePro/Views/Connection/ConnectionTagTokenField.swift new file mode 100644 index 0000000000..2e178e277a --- /dev/null +++ b/apple/TablePro/Views/Connection/ConnectionTagTokenField.swift @@ -0,0 +1,157 @@ +// +// ConnectionTagTokenField.swift +// TablePro +// + +import AppKit +import SwiftUI + +internal enum ConnectionTagTokens { + internal enum Entry: Equatable { + case existing(UUID) + case new(String) + } + + // Names are stored lowercased, so a typed "Prod" is the tag "prod". Order is kept, repeats drop. + internal static func normalized(_ name: String) -> String { + name.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + } + + // The field reports unfinished text as a token too, so only a list that lost tokens and gained + // nothing is a deletion; anything else waits for the field to commit. + internal static func isRemoval(_ current: [String], from committed: [String]) -> Bool { + guard current.count < committed.count else { return false } + var remaining = Dictionary(committed.map { ($0, 1) }, uniquingKeysWith: +) + for name in current { + guard let count = remaining[name], count > 0 else { return false } + remaining[name] = count - 1 + } + return true + } + + internal static func resolve(_ names: [String], among tags: [ConnectionTag]) -> [Entry] { + var seen: Set = [] + var entries: [Entry] = [] + for raw in names { + let name = normalized(raw) + guard !name.isEmpty, seen.insert(name).inserted else { continue } + if let tag = tags.first(where: { $0.name.lowercased() == name }) { + entries.append(.existing(tag.id)) + } else { + entries.append(.new(name)) + } + } + return entries + } +} + +// A token's represented object, so text still being typed (a plain String in objectValue) is never +// taken for a finished tag. +internal final class TagToken: NSObject { + let name: String + + init(name: String) { + self.name = name + } +} + +internal struct ConnectionTagTokenField: NSViewRepresentable { + let tokens: [String] + let completions: [String] + let onChange: ([String]) -> Void + + func makeCoordinator() -> Coordinator { + Coordinator(parent: self) + } + + func makeNSView(context: Context) -> NSTokenField { + let field = NSTokenField() + field.delegate = context.coordinator + field.tokenStyle = .rounded + field.completionDelay = 0 + field.placeholderString = String(localized: "Add tags") + field.cell?.wraps = false + field.cell?.isScrollable = true + field.setContentHuggingPriority(.defaultLow, for: .horizontal) + field.setContentCompressionResistancePriority(.defaultLow, for: .horizontal) + field.setAccessibilityLabel(String(localized: "Tags")) + field.setAccessibilityIdentifier("connection-form-tag-field") + field.objectValue = tokens.map(TagToken.init(name:)) + return field + } + + func updateNSView(_ field: NSTokenField, context: Context) { + context.coordinator.parent = self + // Only a change from outside, such as a tag picked in the menu, resets the field; a reset + // would drop the text being typed. + guard context.coordinator.committed != tokens else { return } + context.coordinator.committed = tokens + field.objectValue = tokens.map(TagToken.init(name:)) + } + + @MainActor + final class Coordinator: NSObject, NSTokenFieldDelegate { + var parent: ConnectionTagTokenField + var committed: [String] + + init(parent: ConnectionTagTokenField) { + self.parent = parent + self.committed = parent.tokens + } + + static func names(in field: NSTokenField) -> [String] { + ((field.objectValue as? [Any]) ?? []).compactMap { ($0 as? TagToken)?.name } + } + + func tokenField( + _ tokenField: NSTokenField, + completionsForSubstring substring: String, + indexOfToken tokenIndex: Int, + indexOfSelectedItem selectedIndex: UnsafeMutablePointer? + ) -> [Any]? { + let prefix = ConnectionTagTokens.normalized(substring) + let taken = Set(committed) + return parent.completions.filter { $0.hasPrefix(prefix) && !taken.contains($0) } + } + + func tokenField(_ tokenField: NSTokenField, representedObjectForEditing editingString: String) -> Any? { + let name = ConnectionTagTokens.normalized(editingString) + return name.isEmpty ? nil : TagToken(name: name) + } + + func tokenField(_ tokenField: NSTokenField, displayStringForRepresentedObject representedObject: Any) -> String? { + (representedObject as? TagToken)?.name + } + + func tokenField(_ tokenField: NSTokenField, editingStringForRepresentedObject representedObject: Any) -> String? { + (representedObject as? TagToken)?.name + } + + // The one place a typed name becomes a token: Return, a comma, a completion or leaving the field. + func tokenField(_ tokenField: NSTokenField, shouldAdd tokens: [Any], at index: Int) -> [Any] { + let added = tokens.compactMap { ($0 as? TagToken)?.name } + var next = committed + next.insert(contentsOf: added, at: min(max(index, 0), next.count)) + commit(next) + return tokens + } + + func controlTextDidChange(_ notification: Notification) { + guard let field = notification.object as? NSTokenField else { return } + let current = Self.names(in: field) + guard ConnectionTagTokens.isRemoval(current, from: committed) else { return } + commit(current) + } + + func controlTextDidEndEditing(_ notification: Notification) { + guard let field = notification.object as? NSTokenField else { return } + commit(Self.names(in: field)) + } + + private func commit(_ names: [String]) { + guard names != committed else { return } + committed = names + parent.onChange(names) + } + } +} diff --git a/apple/TableProTests/Views/Connection/ConnectionTagTokenFieldTests.swift b/apple/TableProTests/Views/Connection/ConnectionTagTokenFieldTests.swift new file mode 100644 index 0000000000..d581413408 --- /dev/null +++ b/apple/TableProTests/Views/Connection/ConnectionTagTokenFieldTests.swift @@ -0,0 +1,84 @@ +import AppKit +@testable import TablePro +import Testing + +@MainActor +struct ConnectionTagTokenFieldTests { + private final class Recorder { + var reports: [[String]] = [] + } + + private func makeField( + committed: [String] = [], + recorder: Recorder + ) -> (window: NSWindow, field: NSTokenField, coordinator: ConnectionTagTokenField.Coordinator) { + let representable = ConnectionTagTokenField( + tokens: committed, + completions: ["production", "staging"], + onChange: { recorder.reports.append($0) } + ) + let coordinator = representable.makeCoordinator() + let field = NSTokenField(frame: NSRect(x: 0, y: 0, width: 240, height: 22)) + field.delegate = coordinator + field.objectValue = committed.map(TagToken.init(name:)) + let window = NSWindow( + contentRect: NSRect(x: 0, y: 0, width: 300, height: 60), + styleMask: [.titled], + backing: .buffered, + defer: false + ) + window.isReleasedWhenClosed = false + window.contentView?.addSubview(field) + return (window, field, coordinator) + } + + @Test("Typing a name without committing it creates nothing") + func typingAloneCommitsNothing() throws { + let recorder = Recorder() + let (window, field, _) = makeField(recorder: recorder) + defer { window.orderOut(nil) } + #expect(window.makeFirstResponder(field)) + let editor = try #require(field.currentEditor() as? NSTextView) + + editor.insertText("s", replacementRange: NSRange(location: NSNotFound, length: 0)) + editor.insertText("t", replacementRange: NSRange(location: NSNotFound, length: 0)) + + #expect(recorder.reports.isEmpty) + } + + @Test("Return turns the typed name into one committed tag") + func returnCommitsTheName() throws { + let recorder = Recorder() + let (window, field, _) = makeField(recorder: recorder) + defer { window.orderOut(nil) } + #expect(window.makeFirstResponder(field)) + let editor = try #require(field.currentEditor() as? NSTextView) + + editor.insertText("Analytics", replacementRange: NSRange(location: NSNotFound, length: 0)) + editor.insertNewline(nil) + + #expect(recorder.reports.last == ["analytics"]) + #expect(recorder.reports.allSatisfy { $0 == ["analytics"] }) + } + + @Test("Deleting a committed token reports the shorter list") + func deletionCommits() { + let recorder = Recorder() + let (window, field, coordinator) = makeField(committed: ["production", "staging"], recorder: recorder) + defer { window.orderOut(nil) } + + field.objectValue = [TagToken(name: "staging")] + coordinator.controlTextDidChange(Notification(name: NSControl.textDidChangeNotification, object: field)) + + #expect(recorder.reports == [["staging"]]) + } + + @Test("Only a list that lost tokens and gained none is a deletion") + func removalRule() { + #expect(ConnectionTagTokens.isRemoval(["a"], from: ["a", "b"])) + #expect(!ConnectionTagTokens.isRemoval(["a", "b", "c"], from: ["a", "b"])) + #expect(!ConnectionTagTokens.isRemoval(["a", "pro"], from: ["a", "b", "c"])) + #expect(!ConnectionTagTokens.isRemoval(["a", "b"], from: ["a", "b"])) + #expect(ConnectionTagTokens.isRemoval(["a"], from: ["a", "a"])) + } +} diff --git a/apple/TableProTests/Views/Connection/ConnectionTagTokensTests.swift b/apple/TableProTests/Views/Connection/ConnectionTagTokensTests.swift new file mode 100644 index 0000000000..77d363e6a5 --- /dev/null +++ b/apple/TableProTests/Views/Connection/ConnectionTagTokensTests.swift @@ -0,0 +1,28 @@ +import Foundation +@testable import TablePro +import Testing + +struct ConnectionTagTokensTests { + private let production = ConnectionTag(name: "production", color: .red) + private let staging = ConnectionTag(name: "staging", color: .orange) + + @Test("A typed name matches its tag whatever the case") + func matchesIgnoringCase() { + let entries = ConnectionTagTokens.resolve(["Production", " staging "], among: [production, staging]) + #expect(entries == [.existing(production.id), .existing(staging.id)]) + } + + @Test("An unknown name becomes a new tag, stored lowercased") + func unknownNameIsNew() { + #expect(ConnectionTagTokens.resolve(["Analytics"], among: [production]) == [.new("analytics")]) + } + + @Test("Repeats and blanks drop, and the order stays as typed") + func repeatsAndBlanksDrop() { + let entries = ConnectionTagTokens.resolve( + ["staging", "", "PRODUCTION", "Staging", "new", "new"], + among: [production, staging] + ) + #expect(entries == [.existing(staging.id), .existing(production.id), .new("new")]) + } +} From 3f1e0908aa1a1b35ba0c2dfdb9cf60bd06ac6e75 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Tue, 3 Nov 2026 11:47:16 +0700 Subject: [PATCH 08/13] fix(connections): commit a tag still being typed when the form saves --- .../Components/ConnectionFormActionBar.swift | 7 +++ .../ConnectionTagTokenFieldTests.swift | 48 ++++++++++++++----- 2 files changed, 42 insertions(+), 13 deletions(-) diff --git a/apple/TablePro/Views/ConnectionForm/Components/ConnectionFormActionBar.swift b/apple/TablePro/Views/ConnectionForm/Components/ConnectionFormActionBar.swift index 35b20512dd..276d308139 100644 --- a/apple/TablePro/Views/ConnectionForm/Components/ConnectionFormActionBar.swift +++ b/apple/TablePro/Views/ConnectionForm/Components/ConnectionFormActionBar.swift @@ -38,11 +38,13 @@ struct ConnectionFormActionBar: View { .keyboardShortcut(.cancelAction) if coordinator.isNew { Button(String(localized: "Save")) { + endEditing() coordinator.save() } .disabled(!canCommit) } Button(defaultActionTitle) { + endEditing() coordinator.commit() } .keyboardShortcut(.defaultAction) @@ -53,6 +55,11 @@ struct ConnectionFormActionBar: View { .padding(.vertical, 12) } + // A click does not end editing, so a tag still being typed in the token field is committed first. + private func endEditing() { + NSApp.keyWindow?.makeFirstResponder(nil) + } + /// Restores the Delete the editor shipped through 0.38.0. /// /// It sat at `ToolbarItemPlacement.destructiveAction` until #995 rebuilt the form and dropped diff --git a/apple/TableProTests/Views/Connection/ConnectionTagTokenFieldTests.swift b/apple/TableProTests/Views/Connection/ConnectionTagTokenFieldTests.swift index d581413408..1d7b94be2d 100644 --- a/apple/TableProTests/Views/Connection/ConnectionTagTokenFieldTests.swift +++ b/apple/TableProTests/Views/Connection/ConnectionTagTokenFieldTests.swift @@ -35,30 +35,52 @@ struct ConnectionTagTokenFieldTests { @Test("Typing a name without committing it creates nothing") func typingAloneCommitsNothing() throws { let recorder = Recorder() - let (window, field, _) = makeField(recorder: recorder) + let (window, field, coordinator) = makeField(recorder: recorder) defer { window.orderOut(nil) } - #expect(window.makeFirstResponder(field)) - let editor = try #require(field.currentEditor() as? NSTextView) + // The field holds its delegate weakly. + try withExtendedLifetime(coordinator) { + #expect(window.makeFirstResponder(field)) + let editor = try #require(field.currentEditor() as? NSTextView) - editor.insertText("s", replacementRange: NSRange(location: NSNotFound, length: 0)) - editor.insertText("t", replacementRange: NSRange(location: NSNotFound, length: 0)) + editor.insertText("s", replacementRange: NSRange(location: NSNotFound, length: 0)) + editor.insertText("t", replacementRange: NSRange(location: NSNotFound, length: 0)) - #expect(recorder.reports.isEmpty) + #expect(recorder.reports.isEmpty) + #expect(coordinator.committed.isEmpty) + } } @Test("Return turns the typed name into one committed tag") func returnCommitsTheName() throws { let recorder = Recorder() - let (window, field, _) = makeField(recorder: recorder) + let (window, field, coordinator) = makeField(recorder: recorder) defer { window.orderOut(nil) } - #expect(window.makeFirstResponder(field)) - let editor = try #require(field.currentEditor() as? NSTextView) + try withExtendedLifetime(coordinator) { + #expect(window.makeFirstResponder(field)) + let editor = try #require(field.currentEditor() as? NSTextView) - editor.insertText("Analytics", replacementRange: NSRange(location: NSNotFound, length: 0)) - editor.insertNewline(nil) + editor.insertText("Analytics", replacementRange: NSRange(location: NSNotFound, length: 0)) + editor.insertNewline(nil) - #expect(recorder.reports.last == ["analytics"]) - #expect(recorder.reports.allSatisfy { $0 == ["analytics"] }) + #expect(recorder.reports == [["analytics"]]) + } + } + + @Test("Ending editing commits a name still being typed, as a Save click does") + func endingEditingCommitsPendingText() throws { + let recorder = Recorder() + let (window, field, coordinator) = makeField(committed: ["production"], recorder: recorder) + defer { window.orderOut(nil) } + try withExtendedLifetime(coordinator) { + #expect(window.makeFirstResponder(field)) + let editor = try #require(field.currentEditor() as? NSTextView) + editor.moveToEndOfDocument(nil) + editor.insertText("billing", replacementRange: NSRange(location: NSNotFound, length: 0)) + + #expect(window.makeFirstResponder(nil)) + + #expect(recorder.reports.last == ["production", "billing"]) + } } @Test("Deleting a committed token reports the shorter list") From 91ccb1120152b53789b7cac27da8c998fa13abae Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Tue, 3 Nov 2026 12:14:32 +0700 Subject: [PATCH 09/13] fix(connections): resolve typed tags against the current store and keep Copilot's known state --- .../Connection/ConnectionTagEditor.swift | 35 +++++++++------ .../Connection/ConnectionTagTokenField.swift | 39 +++++++++++++---- .../Views/Settings/AISettingsView.swift | 5 ++- .../ConnectionTagTokenFieldTests.swift | 43 ++++++++++++++++++- 4 files changed, 96 insertions(+), 26 deletions(-) diff --git a/apple/TablePro/Views/Connection/ConnectionTagEditor.swift b/apple/TablePro/Views/Connection/ConnectionTagEditor.swift index a146c1839c..60080cbf2a 100644 --- a/apple/TablePro/Views/Connection/ConnectionTagEditor.swift +++ b/apple/TablePro/Views/Connection/ConnectionTagEditor.swift @@ -41,27 +41,34 @@ struct ConnectionTagEditor: View { } } - private func applyTokens(_ names: [String]) { - var created = false + // Resolves against the store as it is now: another window or iCloud may have added a tag since + // this form loaded. Returns the names that ended up selected, so the field drops one that failed. + private func applyTokens(_ names: [String]) -> [String] { + allTags = tagStorage.loadTags() let ids: [UUID] = ConnectionTagTokens.resolve(names, among: allTags).compactMap { entry in switch entry { case .existing(let id): return id case .new(let name): - let tag = ConnectionTag(name: name, isPreset: false, color: .gray) - do { - try tagStorage.addTag(tag) - created = true - return tag.id - } catch { - Self.logger.error("Could not create a tag from the token field: \(error.publicLogShape, privacy: .public)") - return nil - } + return createTag(named: name) } } - if created { allTags = tagStorage.loadTags() } - guard ids != tagIds else { return } - tagIds = ids + allTags = tagStorage.loadTags() + if ids != tagIds { tagIds = ids } + return ids.compactMap { id in allTags.first { $0.id == id }?.name } + } + + private func createTag(named name: String) -> UUID? { + let tag = ConnectionTag(name: name, isPreset: false, color: .gray) + do { + try tagStorage.addTag(tag) + return tag.id + } catch TagStorageError.duplicateName { + return tagStorage.loadTags().first { $0.name.lowercased() == name }?.id + } catch { + Self.logger.error("Could not create a tag from the token field: \(error.publicLogShape, privacy: .public)") + return nil + } } private var tagMenu: some View { diff --git a/apple/TablePro/Views/Connection/ConnectionTagTokenField.swift b/apple/TablePro/Views/Connection/ConnectionTagTokenField.swift index 2e178e277a..c0c2aed7dc 100644 --- a/apple/TablePro/Views/Connection/ConnectionTagTokenField.swift +++ b/apple/TablePro/Views/Connection/ConnectionTagTokenField.swift @@ -29,6 +29,15 @@ internal enum ConnectionTagTokens { return true } + // How many more of each name one list holds than another. + internal static func surplus(of names: [String], over base: [String]) -> [String: Int] { + var counts = Dictionary(names.map { ($0, 1) }, uniquingKeysWith: +) + for name in base { + counts[name, default: 0] -= 1 + } + return counts.filter { $0.value > 0 } + } + internal static func resolve(_ names: [String], among tags: [ConnectionTag]) -> [Entry] { var seen: Set = [] var entries: [Entry] = [] @@ -58,7 +67,8 @@ internal final class TagToken: NSObject { internal struct ConnectionTagTokenField: NSViewRepresentable { let tokens: [String] let completions: [String] - let onChange: ([String]) -> Void + // Takes the committed names and returns the ones that were kept. + let onChange: ([String]) -> [String] func makeCoordinator() -> Coordinator { Coordinator(parent: self) @@ -130,10 +140,17 @@ internal struct ConnectionTagTokenField: NSViewRepresentable { // The one place a typed name becomes a token: Return, a comma, a completion or leaving the field. func tokenField(_ tokenField: NSTokenField, shouldAdd tokens: [Any], at index: Int) -> [Any] { let added = tokens.compactMap { ($0 as? TagToken)?.name } - var next = committed + let before = committed + var next = before next.insert(contentsOf: added, at: min(max(index, 0), next.count)) - commit(next) - return tokens + let accepted = commit(next) + // A repeat or a tag that could not be stored never becomes a token. + var room = ConnectionTagTokens.surplus(of: accepted, over: before) + return tokens.filter { token in + guard let name = (token as? TagToken)?.name, let count = room[name], count > 0 else { return false } + room[name] = count - 1 + return true + } } func controlTextDidChange(_ notification: Notification) { @@ -145,13 +162,17 @@ internal struct ConnectionTagTokenField: NSViewRepresentable { func controlTextDidEndEditing(_ notification: Notification) { guard let field = notification.object as? NSTokenField else { return } - commit(Self.names(in: field)) + let accepted = commit(Self.names(in: field)) + if Self.names(in: field) != accepted { + field.objectValue = accepted.map(TagToken.init(name:)) + } } - private func commit(_ names: [String]) { - guard names != committed else { return } - committed = names - parent.onChange(names) + @discardableResult + private func commit(_ names: [String]) -> [String] { + guard names != committed else { return committed } + committed = parent.onChange(names) + return committed } } } diff --git a/apple/TablePro/Views/Settings/AISettingsView.swift b/apple/TablePro/Views/Settings/AISettingsView.swift index 1f60581248..b75d3ea480 100644 --- a/apple/TablePro/Views/Settings/AISettingsView.swift +++ b/apple/TablePro/Views/Settings/AISettingsView.swift @@ -379,9 +379,10 @@ struct AISettingsView: View { ) } - // Copilot's sign-in is known only once its language server runs, which this row starts. + // Copilot's sign-in is known only once its language server answers, which this row starts. A + // server stopped after it answered keeps the state it reported. private func oauthState(for type: AIProviderType) -> OAuthAuthState? { - if type == .copilot, copilotService.status != .running { return nil } + if type == .copilot, copilotService.status == .starting { return nil } return OAuthProviderRegistry.service(for: type)?.oauthState } diff --git a/apple/TableProTests/Views/Connection/ConnectionTagTokenFieldTests.swift b/apple/TableProTests/Views/Connection/ConnectionTagTokenFieldTests.swift index 1d7b94be2d..10e185ad3a 100644 --- a/apple/TableProTests/Views/Connection/ConnectionTagTokenFieldTests.swift +++ b/apple/TableProTests/Views/Connection/ConnectionTagTokenFieldTests.swift @@ -6,6 +6,12 @@ import Testing struct ConnectionTagTokenFieldTests { private final class Recorder { var reports: [[String]] = [] + var refused: Set = [] + + func keeps(_ names: [String]) -> [String] { + var seen: Set = [] + return names.filter { !refused.contains($0) && seen.insert($0).inserted } + } } private func makeField( @@ -15,7 +21,10 @@ struct ConnectionTagTokenFieldTests { let representable = ConnectionTagTokenField( tokens: committed, completions: ["production", "staging"], - onChange: { recorder.reports.append($0) } + onChange: { names in + recorder.reports.append(names) + return recorder.keeps(names) + } ) let coordinator = representable.makeCoordinator() let field = NSTokenField(frame: NSRect(x: 0, y: 0, width: 240, height: 22)) @@ -95,6 +104,38 @@ struct ConnectionTagTokenFieldTests { #expect(recorder.reports == [["staging"]]) } + @Test("A name typed twice, or one the store refuses, never shows as a token") + func refusedNamesDoNotStay() throws { + let recorder = Recorder() + recorder.refused = ["broken"] + let (window, field, coordinator) = makeField(committed: ["production"], recorder: recorder) + defer { window.orderOut(nil) } + try withExtendedLifetime(coordinator) { + #expect(window.makeFirstResponder(field)) + let editor = try #require(field.currentEditor() as? NSTextView) + editor.moveToEndOfDocument(nil) + + editor.insertText("production", replacementRange: NSRange(location: NSNotFound, length: 0)) + editor.insertNewline(nil) + #expect(coordinator.committed == ["production"]) + + if !window.makeFirstResponder(field) { Issue.record("The field must take focus again") } + let again = try #require(field.currentEditor() as? NSTextView) + again.moveToEndOfDocument(nil) + again.insertText("broken", replacementRange: NSRange(location: NSNotFound, length: 0)) + #expect(window.makeFirstResponder(nil)) + + #expect(coordinator.committed == ["production"]) + #expect(ConnectionTagTokenField.Coordinator.names(in: field) == ["production"]) + } + } + + @Test("Surplus counts what a list adds over another") + func surplusCounts() { + #expect(ConnectionTagTokens.surplus(of: ["a", "b", "b"], over: ["b"]) == ["a": 1, "b": 1]) + #expect(ConnectionTagTokens.surplus(of: ["a"], over: ["a", "a"]).isEmpty) + } + @Test("Only a list that lost tokens and gained none is a deletion") func removalRule() { #expect(ConnectionTagTokens.isRemoval(["a"], from: ["a", "b"])) From 6ca419992cf48b9e72e54b92522d37145a878faa Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Tue, 3 Nov 2026 12:16:30 +0700 Subject: [PATCH 10/13] refactor(ios): drop the row saved toast and draw NULL, state and type labels with stock controls --- .../Views/Components/MetadataBadge.swift | 22 +++++--------- .../TableProMobile/Views/InsertRowView.swift | 9 ++---- .../Views/QueryEditorView.swift | 1 - .../TableProMobile/Views/RowDetailView.swift | 29 +++++++------------ .../Views/SavedQueries/SavedQueryRow.swift | 3 -- .../TableProMobile/Views/StructureView.swift | 4 +-- 6 files changed, 23 insertions(+), 45 deletions(-) diff --git a/apple/TableProMobile/TableProMobile/Views/Components/MetadataBadge.swift b/apple/TableProMobile/TableProMobile/Views/Components/MetadataBadge.swift index 87c493fb20..8ea95190e6 100644 --- a/apple/TableProMobile/TableProMobile/Views/Components/MetadataBadge.swift +++ b/apple/TableProMobile/TableProMobile/Views/Components/MetadataBadge.swift @@ -1,25 +1,19 @@ import SwiftUI -struct MetadataBadge: View { +// A type, a row count or an index kind beside a row's title: secondary text, never a chip. +struct MetadataBadge: View { let text: String - var foreground: Color = .secondary - var background: Background + + init(_ text: String) { + self.text = text + } var body: some View { - Text(text) + Text(verbatim: text) .font(.caption2) .fontWeight(.medium) - .foregroundStyle(foreground) + .foregroundStyle(.secondary) .lineLimit(1) - .padding(.horizontal, 6) - .padding(.vertical, 2) - .background(background, in: Capsule()) .dynamicTypeSize(...DynamicTypeSize.accessibility1) } } - -extension MetadataBadge where Background == HierarchicalShapeStyle { - init(_ text: String, foreground: Color = .secondary) { - self.init(text: text, foreground: foreground, background: .tertiary) - } -} diff --git a/apple/TableProMobile/TableProMobile/Views/InsertRowView.swift b/apple/TableProMobile/TableProMobile/Views/InsertRowView.swift index ef10672058..cea001a54a 100644 --- a/apple/TableProMobile/TableProMobile/Views/InsertRowView.swift +++ b/apple/TableProMobile/TableProMobile/Views/InsertRowView.swift @@ -195,13 +195,10 @@ struct InsertRowView: View { } } label: { Text(stateBadge(for: column)) - .font(.caption2) - .foregroundStyle(fields[column.name] == .null ? .white : .secondary) - .padding(.horizontal, 6) - .padding(.vertical, 2) - .background(fields[column.name] == .null ? Color.accentColor : Color(.systemFill)) - .clipShape(Capsule()) } + .menuStyle(.button) + .buttonStyle(.bordered) + .controlSize(.mini) .accessibilityLabel(Text(String(format: String(localized: "Value for %@"), column.name))) } diff --git a/apple/TableProMobile/TableProMobile/Views/QueryEditorView.swift b/apple/TableProMobile/TableProMobile/Views/QueryEditorView.swift index c3c8841ab8..0f0fe9019b 100644 --- a/apple/TableProMobile/TableProMobile/Views/QueryEditorView.swift +++ b/apple/TableProMobile/TableProMobile/Views/QueryEditorView.swift @@ -539,7 +539,6 @@ struct QueryEditorView: View { } .padding(.horizontal, 12) .padding(.vertical, 6) - .background(.thinMaterial) } private var rowLayout: RowLayout { diff --git a/apple/TableProMobile/TableProMobile/Views/RowDetailView.swift b/apple/TableProMobile/TableProMobile/Views/RowDetailView.swift index f0b61ea75b..2329d6c960 100644 --- a/apple/TableProMobile/TableProMobile/Views/RowDetailView.swift +++ b/apple/TableProMobile/TableProMobile/Views/RowDetailView.swift @@ -69,15 +69,10 @@ struct RowDetailView: View { .onChange(of: viewModel.currentIndex) { hapticSelection += 1 } - .overlay(alignment: .bottom) { - if viewModel.showSaveSuccess { - Label("Row updated", systemImage: "checkmark.circle.fill") - .font(.subheadline) - .padding() - .background(.regularMaterial, in: Capsule()) - .padding(.bottom) - .transition(.move(edge: .bottom).combined(with: .opacity)) - } + // The saved values in the fields and the success haptic say it; VoiceOver hears it. + .onChange(of: viewModel.showSaveSuccess) { _, saved in + guard saved else { return } + AccessibilityNotification.Announcement(String(localized: "Row updated")).post() } .bottomSafeAreaBar { if viewModel.showsRowNavigator { @@ -366,18 +361,14 @@ struct RowDetailView: View { } if offersNull { - Button { - viewModel.toggleNull(at: index) - } label: { + Toggle(isOn: Binding( + get: { isNull }, + set: { _ in viewModel.toggleNull(at: index) } + )) { Text("NULL") - .font(.caption2) - .foregroundStyle(isNull ? .white : .secondary) - .padding(.horizontal, 6) - .padding(.vertical, 2) - .background(isNull ? Color.accentColor : Color(.systemFill)) - .clipShape(Capsule()) } - .buttonStyle(.plain) + .toggleStyle(.button) + .controlSize(.mini) } } } diff --git a/apple/TableProMobile/TableProMobile/Views/SavedQueries/SavedQueryRow.swift b/apple/TableProMobile/TableProMobile/Views/SavedQueries/SavedQueryRow.swift index e77590eab0..c7fbf5a896 100644 --- a/apple/TableProMobile/TableProMobile/Views/SavedQueries/SavedQueryRow.swift +++ b/apple/TableProMobile/TableProMobile/Views/SavedQueries/SavedQueryRow.swift @@ -67,9 +67,6 @@ struct SavedQueryRow: View { .font(.system(.caption, design: .monospaced).weight(.medium)) .foregroundStyle(.secondary) .lineLimit(1) - .padding(.horizontal, 6) - .padding(.vertical, 1) - .background(Capsule().fill(.quaternary)) .accessibilityHidden(true) } } diff --git a/apple/TableProMobile/TableProMobile/Views/StructureView.swift b/apple/TableProMobile/TableProMobile/Views/StructureView.swift index 10485126de..d1ff0db75d 100644 --- a/apple/TableProMobile/TableProMobile/Views/StructureView.swift +++ b/apple/TableProMobile/TableProMobile/Views/StructureView.swift @@ -138,11 +138,11 @@ struct StructureView: View { Spacer() if index.isPrimary { - MetadataBadge(text: "Primary", foreground: .orange, background: Color.orange.opacity(0.15)) + MetadataBadge(String(localized: "Primary")) } if index.isUnique && !index.isPrimary { - MetadataBadge(text: "Unique", foreground: .blue, background: Color.blue.opacity(0.15)) + MetadataBadge(String(localized: "Unique")) } if !index.type.isEmpty { From a193ba0c8b933b153822137547d40084c1456e10 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Tue, 3 Nov 2026 12:34:08 +0700 Subject: [PATCH 11/13] fix(history): disable Restore Previous Values only for what is known when the list loads --- .../Storage/QueryHistoryManager+Rewind.swift | 4 -- .../QueryHistoryStorage+RewindSnapshots.swift | 21 --------- .../Editor/History/HistoryListPane.swift | 16 +------ .../Editor/History/HistoryPanelView.swift | 11 +---- .../Storage/RewindSnapshotStorageTests.swift | 43 +------------------ 5 files changed, 5 insertions(+), 90 deletions(-) diff --git a/apple/TablePro/Core/Storage/QueryHistoryManager+Rewind.swift b/apple/TablePro/Core/Storage/QueryHistoryManager+Rewind.swift index 0ff260ab54..30e2a8b755 100644 --- a/apple/TablePro/Core/Storage/QueryHistoryManager+Rewind.swift +++ b/apple/TablePro/Core/Storage/QueryHistoryManager+Rewind.swift @@ -31,10 +31,6 @@ extension QueryHistoryManager { await storage.rewindSnapshotId(forHistoryId: historyId) } - func rewindSnapshotHistoryIds() async -> Set? { - await storage.rewindSnapshotHistoryIds() - } - @discardableResult func deleteRewindSnapshot(id: UUID) async -> Bool { await storage.deleteRewindSnapshot(id: id) diff --git a/apple/TablePro/Core/Storage/QueryHistoryStorage+RewindSnapshots.swift b/apple/TablePro/Core/Storage/QueryHistoryStorage+RewindSnapshots.swift index a5de485368..0a6b924945 100644 --- a/apple/TablePro/Core/Storage/QueryHistoryStorage+RewindSnapshots.swift +++ b/apple/TablePro/Core/Storage/QueryHistoryStorage+RewindSnapshots.swift @@ -148,27 +148,6 @@ extension QueryHistoryStorage { return UUID(uuidString: String(cString: raw)) } - // Retention bounds the table, so the drawer reads every id when its list loads. Nil when the store cannot answer. - func rewindSnapshotHistoryIds() -> Set? { - guard let db else { return nil } - var statement: OpaquePointer? - defer { sqlite3_finalize(statement) } - guard sqlite3_prepare_v2( - db, "SELECT history_id FROM rewind_snapshots WHERE history_id IS NOT NULL;", -1, &statement, nil - ) == SQLITE_OK else { - logSqliteError(context: "prepare rewind snapshot history ids") - return nil - } - var ids: Set = [] - while sqlite3_step(statement) == SQLITE_ROW { - guard let raw = sqlite3_column_text(statement, 0), - let id = UUID(uuidString: String(cString: raw)) - else { continue } - ids.insert(id) - } - return ids - } - /// The most recent saves against one table, newest first. func rewindSnapshots( connectionId: UUID, diff --git a/apple/TablePro/Views/Editor/History/HistoryListPane.swift b/apple/TablePro/Views/Editor/History/HistoryListPane.swift index 475d2afef0..13ab89077e 100644 --- a/apple/TablePro/Views/Editor/History/HistoryListPane.swift +++ b/apple/TablePro/Views/Editor/History/HistoryListPane.swift @@ -8,12 +8,9 @@ struct HistoryListPane: View { let onRunInNewTab: (QueryHistoryEntry) -> Void let onCopy: (QueryHistoryEntry) -> Void let onSaveAsFavorite: (QueryHistoryEntry) -> Void - let canRestorePreviousValues: (QueryHistoryEntry, _ historyIdsWithSnapshot: Set?) -> Bool - let loadHistoryIdsWithSnapshot: @MainActor () async -> Set? + let canRestorePreviousValues: (QueryHistoryEntry) -> Bool let onRestorePreviousValues: (QueryHistoryEntry) -> Void - @State private var historyIdsWithSnapshot: Set? - var body: some View { content .frame(maxWidth: .infinity, maxHeight: .infinity) @@ -66,15 +63,6 @@ struct HistoryListPane: View { loadMoreBar } } - .task(id: rowEditEntryIds) { - let ids = await loadHistoryIdsWithSnapshot() - guard !Task.isCancelled else { return } - historyIdsWithSnapshot = ids - } - } - - private var rowEditEntryIds: [UUID] { - viewModel.sections.flatMap(\.entries).compactMap { $0.source == .rowEdit ? $0.id : nil } } private var selectionBinding: Binding> { @@ -167,7 +155,7 @@ struct HistoryListPane: View { return [ FieldDrivenMenuItem( title: String(localized: "Restore Previous Values…"), - isEnabled: canRestorePreviousValues(entry, historyIdsWithSnapshot) + isEnabled: canRestorePreviousValues(entry) ) { onRestorePreviousValues(entry) }, diff --git a/apple/TablePro/Views/Editor/History/HistoryPanelView.swift b/apple/TablePro/Views/Editor/History/HistoryPanelView.swift index 0099d88a80..b25ca84e0c 100644 --- a/apple/TablePro/Views/Editor/History/HistoryPanelView.swift +++ b/apple/TablePro/Views/Editor/History/HistoryPanelView.swift @@ -75,8 +75,7 @@ struct HistoryPanelView: View { onRunInNewTab: { runInNewTab($0) }, onCopy: { copy($0) }, onSaveAsFavorite: { favoriteDialogQuery = FavoriteDialogQuery(query: $0.query) }, - canRestorePreviousValues: { canRestore($0, historyIdsWithSnapshot: $1) }, - loadHistoryIdsWithSnapshot: { await services.queryHistoryManager.rewindSnapshotHistoryIds() }, + canRestorePreviousValues: { canRun($0) && coordinator.canRewindSelectedTab }, onRestorePreviousValues: { coordinator.rewindSave(historyId: $0.id) } ) } secondary: { @@ -99,14 +98,6 @@ struct HistoryPanelView: View { entry.connectionId == connectionId } - // Unlicensed saves keep no snapshot, so their item stays enabled and the click explains the licence. - // A nil set is a list still loading; the coordinator's sheets cover a snapshot pruned since. - private func canRestore(_ entry: QueryHistoryEntry, historyIdsWithSnapshot: Set?) -> Bool { - guard canRun(entry), coordinator.canRewindSelectedTab else { return false } - guard services.licenseManager.isFeatureAvailable(.dataRewind), let historyIdsWithSnapshot else { return true } - return historyIdsWithSnapshot.contains(entry.id) - } - private func load(_ entry: QueryHistoryEntry) { coordinator.openQuery( entry.query, diff --git a/apple/TableProTests/Core/Storage/RewindSnapshotStorageTests.swift b/apple/TableProTests/Core/Storage/RewindSnapshotStorageTests.swift index 8210ce954c..9d51b5147f 100644 --- a/apple/TableProTests/Core/Storage/RewindSnapshotStorageTests.swift +++ b/apple/TableProTests/Core/Storage/RewindSnapshotStorageTests.swift @@ -21,13 +21,12 @@ struct RewindSnapshotStorageTests { table: String = "users", schema: String? = nil, capturedAt: Date = Date(timeIntervalSince1970: 1_700_000_000), - refusal: RewindRefusal? = nil, - historyId: UUID? = nil + refusal: RewindRefusal? = nil ) -> RewindRecord { let target = DataWriteTarget(database: "shop", schema: schema, table: table) return RewindRecord( id: UUID(), - historyId: historyId, + historyId: nil, connectionId: connectionId, databaseType: .sqlite, target: target, @@ -60,44 +59,6 @@ struct RewindSnapshotStorageTests { #expect(read == record) } - private func recordSave(in storage: QueryHistoryStorage) async -> UUID { - let id = UUID() - _ = await storage.record(QueryHistoryEntry( - id: id, - query: "UPDATE users SET name = 'Grace' WHERE id = 7", - connectionId: connectionId, - databaseName: "shop", - databaseType: .sqlite, - schemaName: nil, - source: .rowEdit, - executionTime: 0.1, - rowCount: 1, - wasSuccessful: true - )) - return id - } - - @Test("The drawer learns which saves still have their snapshot, and a deleted one drops out") - func historyIdsWithASnapshot() async { - let storage = makeStorage() - let cipher = RewindCipher(keychain: InMemoryKeychain()) - let kept = await recordSave(in: storage) - let deleted = await recordSave(in: storage) - let withoutSnapshot = await recordSave(in: storage) - let deletedRecord = makeRecord(historyId: deleted) - await storage.recordRewindSnapshot(makeRecord(historyId: kept), cipher: cipher) - await storage.recordRewindSnapshot(deletedRecord, cipher: cipher) - await storage.recordRewindSnapshot(makeRecord(), cipher: cipher) - - #expect(await storage.rewindSnapshotHistoryIds() == [kept, deleted]) - - await storage.deleteRewindSnapshot(id: deletedRecord.id) - - let ids = await storage.rewindSnapshotHistoryIds() - #expect(ids == [kept]) - #expect(ids?.contains(withoutSnapshot) == false) - } - @Test("Snapshots come back newest first, and only for the table asked for") func listsByTargetNewestFirst() async { let storage = makeStorage() From 9ecb214e33682fdb515a358897b9633e1f146778 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Tue, 3 Nov 2026 14:00:40 +0700 Subject: [PATCH 12/13] chore(l10n): add the notice and status strings; drop unused provider actions --- .../TablePro/Models/AI/AIProviderStatus.swift | 27 --------- .../TablePro/Resources/Localizable.xcstrings | 60 +++++++++++++++++++ .../Models/AIProviderStatusTests.swift | 6 +- 3 files changed, 62 insertions(+), 31 deletions(-) diff --git a/apple/TablePro/Models/AI/AIProviderStatus.swift b/apple/TablePro/Models/AI/AIProviderStatus.swift index 760df5387e..84599b0fc4 100644 --- a/apple/TablePro/Models/AI/AIProviderStatus.swift +++ b/apple/TablePro/Models/AI/AIProviderStatus.swift @@ -18,13 +18,6 @@ internal enum AIProviderStatus: Equatable, Sendable { case failed(message: String) case notConfigured - internal enum Action: Equatable, Sendable { - case addAPIKey - case signIn - case install - case openSettings - } - internal var isReady: Bool { if case .ready = self { return true } return false @@ -53,26 +46,6 @@ internal enum AIProviderStatus: Equatable, Sendable { } } - internal var action: Action? { - switch self { - case .checking, .ready, .signingIn: nil - case .needsAPIKey: .addAPIKey - case .needsSignIn: .signIn - case .needsInstall, .needsUpdate: .install - case .failed, .notConfigured: .openSettings - } - } - - internal var actionTitle: String? { - switch action { - case .addAPIKey: String(localized: "Add API Key…") - case .signIn: String(localized: "Sign In…") - case .install: String(localized: "Set Up…") - case .openSettings: String(localized: "Settings…") - case nil: nil - } - } - internal static func resolve( provider: AIProviderConfig, hasAPIKey: Bool, diff --git a/apple/TablePro/Resources/Localizable.xcstrings b/apple/TablePro/Resources/Localizable.xcstrings index 2b305db2f8..ddcaa7eda6 100644 --- a/apple/TablePro/Resources/Localizable.xcstrings +++ b/apple/TablePro/Resources/Localizable.xcstrings @@ -33304,6 +33304,9 @@ } } } + }, + "Can't be loaded" : { + }, "Can't Debug %@" : { @@ -38318,6 +38321,9 @@ } } } + }, + "Choose an AI provider in Settings to chat." : { + }, "Choose an auth method for this connection." : { "extractionState" : "manual", @@ -38697,6 +38703,9 @@ }, "Choose Schema" : { + }, + "Choose Tags" : { + }, "Choose the .proto file or descriptor set the values in this column were written with." : { @@ -54608,6 +54617,9 @@ }, "Couldn't Import Formatter Rules" : { + }, + "Couldn't Load" : { + }, "Couldn't Move File to Trash" : { "localizations" : { @@ -54920,6 +54932,9 @@ } } } + }, + "Couldn't start" : { + }, "Count" : { "localizations" : { @@ -113113,6 +113128,9 @@ } } } + }, + "Needs a newer TablePro" : { + }, "Needs a valid unique index on the view's columns, with no WHERE clause and no expressions." : { "localizations" : { @@ -113123,6 +113141,9 @@ } } } + }, + "Needs an API key" : { + }, "Needs attention" : { @@ -115380,6 +115401,9 @@ } } } + }, + "No AI Provider" : { + }, "No AI provider configured. Go to Settings > AI to add one." : { "localizations" : { @@ -135125,6 +135149,9 @@ } } } + }, + "Port %d was in use." : { + }, "Port %lld uses TLS, so SSL Mode is %@." : { "localizations" : { @@ -145429,9 +145456,15 @@ }, "Relaunch TablePro to finish removing plugins." : { + }, + "Relaunch TablePro to finish switching languages." : { + }, "Relaunch TablePro to finish updating." : { + }, + "Relaunch to finish removing plugins." : { + }, "Relaunch to Update" : { @@ -174901,6 +174934,9 @@ } } } + }, + "Stopped unexpectedly" : { + }, "Stopped." : { @@ -180173,6 +180209,9 @@ } } } + }, + "TablePro couldn't reach the plugin registry to update this plugin. Check your connection and try again." : { + }, "TablePro Data Was Removed from iCloud" : { "extractionState" : "manual", @@ -188656,9 +188695,15 @@ } } } + }, + "The MCP server could not issue its bridge credential." : { + }, "The MCP server could not prepare its private socket folder" : { + }, + "The MCP server could not prepare its private socket folder." : { + }, "The MCP server is turned off. Turn it on in Settings > MCP." : { @@ -188702,6 +188747,9 @@ } } } + }, + "The MCP server started without a port." : { + }, "the message is larger than the broker accepts" : { "extractionState" : "manual", @@ -208193,6 +208241,9 @@ } } } + }, + "Update available" : { + }, "Update Available" : { @@ -208714,6 +208765,9 @@ } } } + }, + "Updating this plugin didn't finish. Update it again to keep using it." : { + }, "Updating…" : { "extractionState" : "stale", @@ -212073,6 +212127,9 @@ } } } + }, + "Version %@ or newer is required." : { + }, "Version 4 (random)" : { @@ -212783,6 +212840,9 @@ } } } + }, + "Waiting for a compatible build" : { + }, "Waiting for the tunnel" : { "localizations" : { diff --git a/apple/TableProTests/Models/AIProviderStatusTests.swift b/apple/TableProTests/Models/AIProviderStatusTests.swift index 0cdeb75884..20283cde74 100644 --- a/apple/TableProTests/Models/AIProviderStatusTests.swift +++ b/apple/TableProTests/Models/AIProviderStatusTests.swift @@ -23,11 +23,10 @@ struct AIProviderStatusTests { ) } - @Test("A provider that needs a key says so and offers to add one") + @Test("A provider that needs a key says so with a warning") func missingKey() { let missing = status(.openAI) #expect(missing == .needsAPIKey) - #expect(missing.action == .addAPIKey) #expect(missing.severity == .warning) #expect(status(.openAI, hasAPIKey: true).isReady) } @@ -68,11 +67,10 @@ struct AIProviderStatusTests { #expect(status(.ollama) == .ready(detail: String(localized: "Local"))) } - @Test("Only states the user has to fix carry a symbol and an action") + @Test("Only states the user has to fix carry a symbol") func readyAndBusyStatesAreQuiet() { for quiet in [AIProviderStatus.checking, .signingIn, .ready(detail: nil)] { #expect(quiet.severity == nil) - #expect(quiet.action == nil) } } } From 60ae34c0bb8523af479c009842f7e4500193e6b3 Mon Sep 17 00:00:00 2001 From: Ngo Quoc Dat Date: Tue, 3 Nov 2026 14:02:11 +0700 Subject: [PATCH 13/13] chore(changelog): add notes for the native notices refactor --- apple/changelog.d/4007.added.md | 1 + apple/changelog.d/4007.changed.1.md | 1 + apple/changelog.d/4007.changed.2.md | 1 + apple/changelog.d/4007.changed.3.md | 1 + apple/changelog.d/4007.changed.md | 1 + apple/changelog.d/4007.fixed.1.md | 1 + apple/changelog.d/4007.fixed.2.md | 1 + apple/changelog.d/4007.fixed.3.md | 1 + apple/changelog.d/4007.fixed.md | 1 + 9 files changed, 9 insertions(+) create mode 100644 apple/changelog.d/4007.added.md create mode 100644 apple/changelog.d/4007.changed.1.md create mode 100644 apple/changelog.d/4007.changed.2.md create mode 100644 apple/changelog.d/4007.changed.3.md create mode 100644 apple/changelog.d/4007.changed.md create mode 100644 apple/changelog.d/4007.fixed.1.md create mode 100644 apple/changelog.d/4007.fixed.2.md create mode 100644 apple/changelog.d/4007.fixed.3.md create mode 100644 apple/changelog.d/4007.fixed.md diff --git a/apple/changelog.d/4007.added.md b/apple/changelog.d/4007.added.md new file mode 100644 index 0000000000..06636a1ab0 --- /dev/null +++ b/apple/changelog.d/4007.added.md @@ -0,0 +1 @@ +Settings > MCP offers Try Again when the server fails to start, and says when the port you set was in use. diff --git a/apple/changelog.d/4007.changed.1.md b/apple/changelog.d/4007.changed.1.md new file mode 100644 index 0000000000..e42108569d --- /dev/null +++ b/apple/changelog.d/4007.changed.1.md @@ -0,0 +1 @@ +Plugins that could not load are listed in Settings > Extensions with the reason, Update, Try Again and Remove. diff --git a/apple/changelog.d/4007.changed.2.md b/apple/changelog.d/4007.changed.2.md new file mode 100644 index 0000000000..d0d150ace8 --- /dev/null +++ b/apple/changelog.d/4007.changed.2.md @@ -0,0 +1 @@ +Connection tags are edited in a token field: type a name to add or create a tag, and press Delete to remove one. diff --git a/apple/changelog.d/4007.changed.3.md b/apple/changelog.d/4007.changed.3.md new file mode 100644 index 0000000000..af79a01292 --- /dev/null +++ b/apple/changelog.d/4007.changed.3.md @@ -0,0 +1 @@ +On iOS, a saved row no longer shows a toast, and NULL, Default and column types use standard buttons and text. diff --git a/apple/changelog.d/4007.changed.md b/apple/changelog.d/4007.changed.md new file mode 100644 index 0000000000..efafeda4aa --- /dev/null +++ b/apple/changelog.d/4007.changed.md @@ -0,0 +1 @@ +Notices, warnings and errors use the standard macOS look: color only on the symbol, with no tinted boxes, dots or chips. diff --git a/apple/changelog.d/4007.fixed.1.md b/apple/changelog.d/4007.fixed.1.md new file mode 100644 index 0000000000..44d5f618dd --- /dev/null +++ b/apple/changelog.d/4007.fixed.1.md @@ -0,0 +1 @@ +A GitHub Copilot error showed only inside its provider sheet while the provider row said Not signed in. diff --git a/apple/changelog.d/4007.fixed.2.md b/apple/changelog.d/4007.fixed.2.md new file mode 100644 index 0000000000..1cae3fb68c --- /dev/null +++ b/apple/changelog.d/4007.fixed.2.md @@ -0,0 +1 @@ +Settings > Notifications kept showing an old permission after it was changed in System Settings. diff --git a/apple/changelog.d/4007.fixed.3.md b/apple/changelog.d/4007.fixed.3.md new file mode 100644 index 0000000000..a15b273d2f --- /dev/null +++ b/apple/changelog.d/4007.fixed.3.md @@ -0,0 +1 @@ +Notes from MySQL and SQLite maintenance, such as an OPTIMIZE note or an integrity check problem, were never shown. diff --git a/apple/changelog.d/4007.fixed.md b/apple/changelog.d/4007.fixed.md new file mode 100644 index 0000000000..79102020a7 --- /dev/null +++ b/apple/changelog.d/4007.fixed.md @@ -0,0 +1 @@ +The MCP status said the port was in use whenever the failure text happened to contain 48.