Merge profile to dashboard

This commit is contained in:
世界
2025-11-26 22:25:52 +08:00
parent 4f0d1098e6
commit 264c37218c
27 changed files with 1590 additions and 306 deletions
@@ -12,6 +12,9 @@ public struct ActiveDashboardView: View {
@State private var cardConfigurationVersion = 0
#if os(iOS) || os(tvOS)
@State private var showCardManagement = false
@State private var showGroups = false
@State private var showConnections = false
@State private var buttonState = ButtonVisibilityState()
#endif
private let externalCardConfigurationVersion: Int?
@@ -42,20 +45,15 @@ public struct ActiveDashboardView: View {
@ViewBuilder
private var content: some View {
VStack {
#if os(iOS) || os(tvOS)
if ApplicationLibrary.inPreview || profile.status.isConnectedStrict {
pageSelector
pageContent
} else {
overviewPage
}
#else
overviewPage
#endif
}
overviewPage
#if os(iOS) || os(tvOS)
.toolbar { toolbar }
.sheet(isPresented: $showGroups) {
groupsSheetContent
}
.sheet(isPresented: $showConnections) {
connectionsSheetContent
}
#endif
.onAppear {
if ApplicationLibrary.inPreview {
@@ -83,45 +81,23 @@ public struct ActiveDashboardView: View {
}
}
}
#if os(iOS) || os(tvOS)
.onReceive(environments.commandClient.$groups) { _ in
updateButtonVisibility()
}
.onReceive(environments.commandClient.$connections) { _ in
updateButtonVisibility()
}
.onReceive(profile.$status) { _ in
updateButtonVisibility()
}
.onAppear {
updateButtonVisibility()
}
#endif
.alertBinding($coordinator.alert)
}
#if os(iOS) || os(tvOS)
@ViewBuilder
private var pageSelector: some View {
Picker("Page", selection: $coordinator.selection) {
ForEach(DashboardPage.enabledCases()) { page in
page.label
}
}
.pickerStyle(.segmented)
#if os(iOS)
.padding([.leading, .trailing])
.navigationBarTitleDisplayMode(.inline)
#endif
}
@ViewBuilder
private var pageContent: some View {
TabView(selection: $coordinator.selection) {
ForEach(DashboardPage.enabledCases()) { page in
page.contentView(
$coordinator.profileList,
$coordinator.selectedProfileID,
$coordinator.systemProxyAvailable,
$coordinator.systemProxyEnabled,
externalCardConfigurationVersion ?? cardConfigurationVersion
)
.tag(page)
}
}
#if os(iOS)
.navigationBarTitleDisplayMode(.inline)
#endif
.tabViewStyle(.page(indexDisplayMode: .never))
}
#endif
@ViewBuilder
private var overviewPage: some View {
OverviewView(
@@ -134,26 +110,68 @@ public struct ActiveDashboardView: View {
}
#if os(iOS) || os(tvOS)
private func updateButtonVisibility() {
buttonState.update(profile: profile, commandClient: environments.commandClient)
}
@ToolbarContentBuilder
private var toolbar: some ToolbarContent {
ToolbarItem(placement: .topBarTrailing) {
if coordinator.selection == .overview {
if #available(iOS 16.0, tvOS 17.0, *) {
cardManagementButton
ToolbarItem(placement: .topBarLeading) {
#if os(iOS)
if #available(iOS 26.0, *), !Variant.debugNoIOS26 {
EmptyView()
} else {
navigationButtons
}
#else
navigationButtons
#endif
}
ToolbarItem(placement: .topBarTrailing) {
if #available(iOS 16.0, tvOS 17.0, *) {
cardManagementButton
}
}
ToolbarItem(placement: .topBarTrailing) {
if #available(iOS 26.0, *), !Variant.debugNoIOS26 {
EmptyView()
} else {
StartStopButton()
}
#if os(iOS)
if #available(iOS 26.0, *), !Variant.debugNoIOS26 {
EmptyView()
} else {
HStack(spacing: 12) {
Divider()
StartStopButton()
}
}
#else
HStack(spacing: 12) {
Divider()
StartStopButton()
}
#endif
}
}
private var navigationButtons: some View {
NavigationButtonsView(
showGroupsButton: buttonState.showGroupsButton,
showConnectionsButton: buttonState.showConnectionsButton,
groupsCount: buttonState.groupsCount,
connectionsCount: buttonState.connectionsCount,
onGroupsTap: { showGroups = true },
onConnectionsTap: { showConnections = true }
)
}
#endif
#if os(iOS) || os(tvOS)
private var groupsSheetContent: some View {
GroupsSheetContent()
}
private var connectionsSheetContent: some View {
ConnectionsSheetContent()
}
@available(iOS 16.0, tvOS 17.0, *)
@ViewBuilder
private var cardManagementButton: some View {
@@ -168,7 +186,8 @@ public struct ActiveDashboardView: View {
}
.sheet(isPresented: $showCardManagement) {
CardManagementSheet(configurationVersion: $cardConfigurationVersion)
.presentationDetents([.medium, .large])
.presentationDetents([.large])
.presentationDragIndicator(.visible)
}
}
#endif
@@ -0,0 +1,38 @@
import Foundation
import Library
@MainActor
public struct ButtonVisibilityState {
public var showGroupsButton = false
public var showConnectionsButton = false
public var groupsCount = 0
public var connectionsCount = 0
public init() {}
public mutating func update(
profile: ExtensionProfile?,
commandClient: CommandClient,
requireAnyConnection: Bool = false
) {
guard let profile else {
reset()
return
}
groupsCount = commandClient.groups?.count ?? 0
connectionsCount = commandClient.connections?.count ?? 0
let isConnected = ApplicationLibrary.inPreview || profile.status.isConnectedStrict
showConnectionsButton = isConnected && (!requireAnyConnection || commandClient.hasAnyConnection)
showGroupsButton = isConnected && (commandClient.groups?.isEmpty == false)
}
private mutating func reset() {
showGroupsButton = false
showConnectionsButton = false
groupsCount = 0
connectionsCount = 0
}
}
@@ -11,7 +11,7 @@ public struct ClashModeCard: View {
public var body: some View {
if shouldShowPicker {
DashboardCardView(title: "Mode", isHalfWidth: false) {
DashboardCardView(title: String(localized: "Mode"), isHalfWidth: false) {
Picker("", selection: Binding(get: {
clashMode
}, set: { newMode in
@@ -8,7 +8,7 @@ public struct ConnectionsCard: View {
public init() {}
public var body: some View {
DashboardCardView(title: "Connections", isHalfWidth: true) {
DashboardCardView(title: String(localized: "Connections"), isHalfWidth: true) {
VStack(alignment: .leading, spacing: 8) {
if ApplicationLibrary.inPreview {
DashboardCardLine(String(localized: "Inbound"), "34")
@@ -1,7 +1,14 @@
import Foundation
import Libbox
import Library
import QRCode
import SwiftUI
@MainActor
public struct ProfileCard: View {
@EnvironmentObject private var environments: ExtensionEnvironments
@StateObject private var viewModel = ViewModel()
@Binding private var profileList: [ProfilePreview]
@Binding private var selectedProfileID: Int64
@@ -13,39 +20,431 @@ public struct ProfileCard: View {
_selectedProfileID = selectedProfileID
}
private var selectedProfile: ProfilePreview? {
profileList.first { $0.id == selectedProfileID }
}
public var body: some View {
DashboardCardView(title: "Profile", isHalfWidth: false) {
VStack(alignment: .leading, spacing: 12) {
#if os(iOS) || os(tvOS)
Picker("", selection: $selectedProfileID) {
ForEach(profileList, id: \.id) { profile in
Text(profile.name).tag(profile.id)
}
DashboardCardView(title: "") {
VStack(alignment: .leading, spacing: 16) {
headerView
profileSelectorView
}
}
.disabled(viewModel.isUpdating)
.sheet(isPresented: $viewModel.showNewProfile, onDismiss: {
environments.profileUpdate.send()
}) {
NewProfileNavigationView()
.environmentObject(environments)
}
.sheet(isPresented: $viewModel.showManageProfiles) {
manageProfilesSheet
}
.sheet(item: $viewModel.profileToEdit) { profile in
editProfileSheet(for: profile)
}
#if os(iOS) || os(tvOS)
.sheet(isPresented: $viewModel.showQRCode) {
if let profile = selectedProfile, let remoteURL = profile.remoteURL {
QRCodeSheet(profileName: profile.name, remoteURL: remoteURL)
}
}
#endif
.alertBinding($viewModel.alert)
}
private var headerView: some View {
HStack {
Text("Profile")
.font(.headline)
.foregroundColor(.primary)
Spacer()
Button {
viewModel.showNewProfile = true
} label: {
Image(systemName: "plus")
.font(.system(size: 16))
}
.buttonStyle(.plain)
.actionButtonStyle()
if !profileList.isEmpty {
Button {
viewModel.showManageProfiles = true
} label: {
Image(systemName: "line.3.horizontal")
.font(.system(size: 16))
}
.buttonStyle(.plain)
.actionButtonStyle()
}
}
}
private var profileSelectorView: some View {
VStack(alignment: .leading, spacing: 12) {
if profileList.isEmpty {
Text("Empty profiles")
.foregroundStyle(.secondary)
.padding(.vertical, 8)
} else {
ProfileSelectorButton(
items: profileList,
selectedItem: selectedProfile,
onSelect: { selectedProfileID = $0 }
)
if let profile = selectedProfile {
VStack(alignment: .leading, spacing: 12) {
profileInfo(for: profile)
actionButtonsRow(for: profile)
}
.pickerStyle(.menu)
.labelsHidden()
#elseif os(macOS)
VStack(alignment: .leading, spacing: 8) {
ForEach(profileList, id: \.id) { profile in
HStack {
Button {
selectedProfileID = profile.id
} label: {
HStack(spacing: 8) {
Image(systemName: selectedProfileID == profile.id ? "circle.fill" : "circle")
.font(.system(size: 12))
Text(profile.name)
.font(.subheadline)
Spacer()
}
}
.buttonStyle(.plain)
.foregroundColor(selectedProfileID == profile.id ? .accentColor : .primary)
}
}
}
#endif
}
}
}
}
@ViewBuilder
private func actionButtonsRow(for profile: ProfilePreview) -> some View {
HStack(spacing: 12) {
editButton(for: profile)
if profile.type == .remote {
updateButton(for: profile)
qrCodeButton(for: profile)
}
ProfileShareButton($viewModel.alert, profile.origin) {
Image(systemName: "square.and.arrow.up")
.font(.system(size: 16))
}
.buttonStyle(.plain)
.actionButtonStyle()
}
}
@ViewBuilder
private func editButton(for profile: ProfilePreview) -> some View {
Button {
viewModel.profileToEdit = profile.origin
} label: {
Image(systemName: "pencil")
.font(.system(size: 16))
}
.buttonStyle(.plain)
.actionButtonStyle()
}
@ViewBuilder
private func updateButton(for profile: ProfilePreview) -> some View {
Button {
viewModel.isUpdating = true
Task {
await viewModel.updateProfile(profile.origin, environments: environments)
}
} label: {
Image(systemName: "arrow.clockwise")
.font(.system(size: 16))
.rotationEffect(.degrees(viewModel.isUpdating ? 360 : 0))
.animation(
viewModel.isUpdating
? .linear(duration: 1).repeatForever(autoreverses: false)
: .default,
value: viewModel.isUpdating
)
}
.buttonStyle(.plain)
.actionButtonStyle()
.disabled(viewModel.isUpdating)
}
@ViewBuilder
private func qrCodeButton(for profile: ProfilePreview) -> some View {
#if os(iOS) || os(tvOS)
Button {
viewModel.showQRCode = true
} label: {
Image(systemName: "qrcode")
.font(.system(size: 16))
}
.buttonStyle(.plain)
.actionButtonStyle()
#elseif os(macOS)
Button {
viewModel.showQRCode = true
} label: {
Image(systemName: "qrcode")
.font(.system(size: 16))
}
.buttonStyle(.plain)
.actionButtonStyle()
.popover(isPresented: $viewModel.showQRCode, arrowEdge: .bottom) {
if let remoteURL = profile.remoteURL {
QRCodeContentView(profileName: profile.name, remoteURL: remoteURL)
}
}
#endif
}
@ViewBuilder
private func profileInfo(for profile: ProfilePreview) -> some View {
HStack(spacing: 8) {
HStack(spacing: 4) {
Image(systemName: profile.type == .remote ? "cloud.fill" : "doc.fill")
.font(.system(size: 12))
.foregroundColor(.secondary)
Text(profile.type == .remote ? "Remote" : "Local")
.font(.caption)
.foregroundColor(.primary)
}
if profile.type == .remote, let lastUpdated = profile.lastUpdated {
HStack(spacing: 4) {
Image(systemName: "clock.fill")
.font(.system(size: 12))
.foregroundColor(.secondary)
Text(lastUpdated.myFormat)
.font(.caption)
.foregroundColor(.primary)
}
}
}
}
private var manageProfilesSheet: some View {
NavigationSheet(
title: "Profiles",
showDoneButton: true,
onDismiss: { viewModel.showManageProfiles = false }
) {
ManageProfilesView()
.environmentObject(environments)
}
}
@ViewBuilder
private func editProfileSheet(for profile: Profile) -> some View {
NavigationSheet(title: "Edit Profile") {
EditProfileView()
.environmentObject(profile)
.environmentObject(environments)
}
}
}
// MARK: - ViewModel
extension ProfileCard {
@MainActor
class ViewModel: ObservableObject {
@Published var showNewProfile = false
@Published var showManageProfiles = false
@Published var showQRCode = false
@Published var isUpdating = false
@Published var alert: Alert?
@Published var profileToEdit: Profile?
func updateProfile(_ profile: Profile, environments: ExtensionEnvironments) async {
defer { isUpdating = false }
do {
try await profile.updateRemoteProfile()
environments.profileUpdate.send()
} catch {
alert = Alert(
title: Text("Update Failed"),
message: Text(error.localizedDescription)
)
}
}
}
}
// MARK: - NewProfileNavigationView
extension ProfileCard {
@MainActor
struct NewProfileNavigationView: View {
@EnvironmentObject private var environments: ExtensionEnvironments
@State private var createdProfile: Profile?
var body: some View {
NavigationStackCompat {
if let profile = createdProfile {
EditProfileView()
.environmentObject(profile)
.environmentObject(environments)
} else {
NewProfileView { profile in
createdProfile = profile
}
.environmentObject(environments)
#if os(iOS)
.navigationBarTitleDisplayMode(.inline)
#endif
}
}
#if os(iOS) || os(tvOS)
.presentationDetentsIfAvailable()
#endif
}
}
}
// MARK: - ManageProfilesView
extension ProfileCard {
@MainActor
struct ManageProfilesView: View {
@EnvironmentObject private var environments: ExtensionEnvironments
@StateObject private var viewModel = ProfileViewModel()
var body: some View {
VStack {
if viewModel.isLoading {
ProgressView().onAppear {
viewModel.setEnvironments(environments)
Task {
await viewModel.doReload()
}
}
} else {
FormView {
if viewModel.profileList.isEmpty {
Text("Empty profiles")
} else {
List {
ForEach(viewModel.profileList, id: \.id) { profile in
ManageProfileItem(viewModel, profile)
}
.onMove(perform: moveProfile)
#if os(macOS)
.onDelete(perform: deleteProfile)
#endif
}
#if os(iOS) || os(tvOS)
.environment(\.editMode, .constant(.active))
.deleteDisabled(true)
#endif
}
}
}
}
.disabled(viewModel.isUpdating)
.alertBinding($viewModel.alert, $viewModel.isLoading)
.onReceive(environments.profileUpdate) { _ in
Task {
await viewModel.doReload()
}
}
}
private func moveProfile(from source: IndexSet, to destination: Int) {
viewModel.moveProfile(from: source, to: destination)
}
private func deleteProfile(where profileIndex: IndexSet) {
viewModel.deleteProfile(where: profileIndex)
}
}
@MainActor
struct ManageProfileItem: View {
@EnvironmentObject private var environments: ExtensionEnvironments
@ObservedObject private var viewModel: ProfileViewModel
@State private var profile: ProfilePreview
@State private var shareLinkPresented = false
init(_ viewModel: ProfileViewModel, _ profile: ProfilePreview) {
self.viewModel = viewModel
_profile = State(initialValue: profile)
}
var body: some View {
HStack {
Image(systemName: "line.3.horizontal")
.foregroundStyle(.secondary)
VStack(alignment: .leading) {
Text(profile.name)
#if os(macOS)
if profile.type == .remote {
Spacer(minLength: 4)
Text("Last Updated: \(profile.origin.lastUpdated!.myFormat)").font(.caption)
}
#endif
}
Spacer()
HStack(spacing: 8) {
if profile.type == .remote {
Button {
viewModel.isUpdating = true
Task {
await viewModel.updateProfile(profile.origin)
profile = ProfilePreview(profile.origin)
}
} label: {
Image(systemName: "arrow.clockwise")
.font(.system(size: 16))
.rotationEffect(.degrees(viewModel.isUpdating ? 360 : 0))
.animation(
viewModel.isUpdating
? .linear(duration: 1).repeatForever(autoreverses: false)
: .default,
value: viewModel.isUpdating
)
}
.buttonStyle(.plain)
.actionButtonStyle()
.disabled(viewModel.isUpdating)
Button {
shareLinkPresented = true
} label: {
Image(systemName: "qrcode")
.font(.system(size: 16))
}
.buttonStyle(.plain)
.actionButtonStyle()
#if os(macOS)
.popover(isPresented: $shareLinkPresented, arrowEdge: .bottom) {
QRCodeContentView(profileName: profile.name, remoteURL: profile.remoteURL!)
}
#elseif os(iOS) || os(tvOS)
.sheet(isPresented: $shareLinkPresented) {
QRCodeSheet(profileName: profile.name, remoteURL: profile.remoteURL!)
}
#endif
}
ShareButtonCompat($viewModel.alert) {
Image(systemName: "square.and.arrow.up")
.font(.system(size: 16))
} itemURL: {
try profile.origin.toContent().generateShareFile()
}
.actionButtonStyle()
Button {
Task {
await viewModel.deleteProfile(profile.origin)
}
} label: {
Image(systemName: "trash")
.font(.system(size: 16))
}
.buttonStyle(.plain)
.actionButtonStyle()
}
}
#if os(macOS)
.padding(.vertical, 4)
#endif
}
}
}
@@ -0,0 +1,288 @@
import Library
import SwiftUI
#if os(iOS) || os(tvOS)
import UIKit
#elseif os(macOS)
import AppKit
#endif
/// A custom view that looks like a navigation link but opens a dropdown menu
struct ProfileSelectorButton: View {
let items: [ProfilePreview]
let selectedItem: ProfilePreview?
let onSelect: (Int64) -> Void
init(
items: [ProfilePreview],
selectedItem: ProfilePreview?,
onSelect: @escaping (Int64) -> Void
) {
self.items = items
self.selectedItem = selectedItem
self.onSelect = onSelect
}
var body: some View {
#if os(iOS) || os(tvOS)
ProfileSelectorUIButton(
items: items,
selectedItem: selectedItem,
onSelect: onSelect
)
.frame(height: 44)
.selectorBackground()
#elseif os(macOS)
ProfileSelectorNSButton(
items: items,
selectedItem: selectedItem,
onSelect: onSelect
)
.frame(height: 32)
.selectorBackground()
#endif
}
}
// MARK: - UIKit Implementation (iOS/tvOS)
#if os(iOS) || os(tvOS)
/// Custom UIButton subclass that allows customizing menu attachment point
private class MenuAttachmentButton: UIButton {
override func menuAttachmentPoint(for _: UIContextMenuConfiguration) -> CGPoint {
// Attach menu to bottom-leading corner of the button
CGPoint(x: 0, y: bounds.height)
}
}
/// UIViewRepresentable wrapper for UIButton with UIMenu
private struct ProfileSelectorUIButton: UIViewRepresentable {
let items: [ProfilePreview]
let selectedItem: ProfilePreview?
let onSelect: (Int64) -> Void
func makeUIView(context _: Context) -> MenuAttachmentButton {
let button = MenuAttachmentButton(type: .system)
button.showsMenuAsPrimaryAction = true
button.contentHorizontalAlignment = .fill
// Configure button appearance
var config = UIButton.Configuration.plain()
config.contentInsets = NSDirectionalEdgeInsets(top: 10, leading: 14, bottom: 10, trailing: 14)
button.configuration = config
updateButtonContent(button)
updateMenu(button)
return button
}
func updateUIView(_ button: MenuAttachmentButton, context _: Context) {
updateButtonContent(button)
updateMenu(button)
}
private func updateButtonContent(_ button: MenuAttachmentButton) {
// Remove existing subviews
for subview in button.subviews {
if subview is UIStackView {
subview.removeFromSuperview()
}
}
// Create content stack
let stackView = UIStackView()
stackView.axis = .horizontal
stackView.alignment = .center
stackView.distribution = .fill
stackView.spacing = 8
stackView.isUserInteractionEnabled = false
stackView.translatesAutoresizingMaskIntoConstraints = false
// Title label
let titleLabel = UILabel()
titleLabel.text = selectedItem?.name ?? "Select Profile"
titleLabel.font = .systemFont(ofSize: 17, weight: .medium)
titleLabel.textColor = .label
titleLabel.setContentHuggingPriority(.defaultLow, for: .horizontal)
// Chevron image
let chevronConfig = UIImage.SymbolConfiguration(pointSize: 12, weight: .semibold)
let chevronImage = UIImage(systemName: "chevron.up.chevron.down", withConfiguration: chevronConfig)
let chevronView = UIImageView(image: chevronImage)
chevronView.tintColor = .secondaryLabel
chevronView.setContentHuggingPriority(.required, for: .horizontal)
stackView.addArrangedSubview(titleLabel)
stackView.addArrangedSubview(chevronView)
button.addSubview(stackView)
NSLayoutConstraint.activate([
stackView.leadingAnchor.constraint(equalTo: button.leadingAnchor, constant: 14),
stackView.trailingAnchor.constraint(equalTo: button.trailingAnchor, constant: -14),
stackView.centerYAnchor.constraint(equalTo: button.centerYAnchor),
])
}
private func updateMenu(_ button: MenuAttachmentButton) {
let actions = items.map { item in
UIAction(
title: item.name,
image: UIImage(systemName: item.type.iconName)
) { [item] _ in
onSelect(item.id)
}
}
button.menu = UIMenu(children: actions)
}
}
#endif
// MARK: - AppKit Implementation (macOS)
#if os(macOS)
/// NSViewRepresentable wrapper for a clickable view with NSMenu
private struct ProfileSelectorNSButton: NSViewRepresentable {
let items: [ProfilePreview]
let selectedItem: ProfilePreview?
let onSelect: (Int64) -> Void
func makeNSView(context: Context) -> NSView {
let containerView = MenuContainerView()
containerView.coordinator = context.coordinator
updateContent(containerView)
context.coordinator.updateMenu(items: items, onSelect: onSelect)
return containerView
}
func updateNSView(_ nsView: NSView, context: Context) {
guard let containerView = nsView as? MenuContainerView else { return }
updateContent(containerView)
context.coordinator.updateMenu(items: items, onSelect: onSelect)
}
func makeCoordinator() -> Coordinator {
Coordinator()
}
private func updateContent(_ containerView: MenuContainerView) {
containerView.titleText = selectedItem?.name ?? "Select Profile"
}
private class MenuContainerView: NSView {
weak var coordinator: Coordinator?
private let titleLabel = NSTextField(labelWithString: "")
private let chevronView = NSImageView()
var titleText: String = "" {
didSet {
titleLabel.stringValue = titleText
}
}
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
setupViews()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setupViews()
}
private func setupViews() {
titleLabel.font = .systemFont(ofSize: 13, weight: .medium)
titleLabel.textColor = .labelColor
titleLabel.alignment = .left
titleLabel.translatesAutoresizingMaskIntoConstraints = false
addSubview(titleLabel)
let chevronConfig = NSImage.SymbolConfiguration(pointSize: 10, weight: .semibold)
chevronView.image = NSImage(systemSymbolName: "chevron.up.chevron.down", accessibilityDescription: nil)?
.withSymbolConfiguration(chevronConfig)
chevronView.contentTintColor = .secondaryLabelColor
chevronView.translatesAutoresizingMaskIntoConstraints = false
addSubview(chevronView)
NSLayoutConstraint.activate([
titleLabel.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 14),
titleLabel.centerYAnchor.constraint(equalTo: centerYAnchor),
chevronView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -14),
chevronView.centerYAnchor.constraint(equalTo: centerYAnchor),
titleLabel.trailingAnchor.constraint(lessThanOrEqualTo: chevronView.leadingAnchor, constant: -8),
])
}
override func mouseDown(with _: NSEvent) {
coordinator?.showMenu(in: self)
}
override func resetCursorRects() {
addCursorRect(bounds, cursor: .pointingHand)
}
}
class Coordinator: NSObject {
private var menu = NSMenu()
private var onSelectCallback: ((Int64) -> Void)?
func updateMenu(items: [ProfilePreview], onSelect: @escaping (Int64) -> Void) {
menu.removeAllItems()
onSelectCallback = onSelect
for item in items {
let menuItem = NSMenuItem(
title: item.name,
action: #selector(menuItemSelected(_:)),
keyEquivalent: ""
)
menuItem.target = self
menuItem.tag = Int(item.id)
menuItem.image = NSImage(systemSymbolName: item.type.iconName, accessibilityDescription: nil)
menu.addItem(menuItem)
}
}
@objc private func menuItemSelected(_ sender: NSMenuItem) {
onSelectCallback?(Int64(sender.tag))
}
func showMenu(in view: NSView) {
let location = NSPoint(x: 0, y: view.bounds.height + 4)
menu.popUp(positioning: nil, at: location, in: view)
}
}
}
#endif
// MARK: - ProfileType Extension
private extension ProfileType {
var iconName: String {
switch self {
case .local:
"doc.fill"
case .icloud:
"icloud.fill"
case .remote:
"cloud.fill"
}
}
}
// MARK: - View Extension
private extension View {
@ViewBuilder
func selectorBackground() -> some View {
if #available(iOS 26.0, macOS 26.0, tvOS 26.0, *) {
self.glassEffect(.regular.interactive(), in: .rect(cornerRadius: 12))
} else {
background(
RoundedRectangle(cornerRadius: 12)
.fill(Color.secondary.opacity(0.1))
)
}
}
}
@@ -8,7 +8,7 @@ public struct StatusCard: View {
public init() {}
public var body: some View {
DashboardCardView(title: "Status", isHalfWidth: true) {
DashboardCardView(title: String(localized: "Status"), isHalfWidth: true) {
VStack(alignment: .leading, spacing: 8) {
if ApplicationLibrary.inPreview {
DashboardCardLine(String(localized: "Memory"), "6.4 MB")
@@ -8,7 +8,7 @@ public struct TrafficCard: View {
public init() {}
public var body: some View {
DashboardCardView(title: "Traffic", isHalfWidth: true) {
DashboardCardView(title: String(localized: "Traffic"), isHalfWidth: true) {
VStack(alignment: .leading, spacing: 8) {
if ApplicationLibrary.inPreview {
DashboardCardLine(String(localized: "Uplink"), "38 B/s")
@@ -8,7 +8,7 @@ public struct TrafficTotalCard: View {
public init() {}
public var body: some View {
DashboardCardView(title: "Traffic Total", isHalfWidth: true) {
DashboardCardView(title: String(localized: "Traffic Total"), isHalfWidth: true) {
VStack(alignment: .leading, spacing: 8) {
if ApplicationLibrary.inPreview {
DashboardCardLine(String(localized: "Uplink"), "52 MB")
@@ -6,8 +6,11 @@ import SwiftUI
public struct DashboardView: View {
@Environment(\.openURL) private var openURL
@Environment(\.cardConfigurationVersion) private var cardConfigurationVersion
@Environment(\.importProfile) private var importProfile
@Environment(\.importRemoteProfile) private var importRemoteProfile
@EnvironmentObject private var environments: ExtensionEnvironments
@StateObject private var coordinator = DashboardCoordinator()
@State private var importRemoteProfileRequest: NewProfileView.ImportRequest?
#if os(macOS)
@Environment(\.controlActiveState) private var controlActiveState
@@ -22,6 +25,17 @@ public struct DashboardView: View {
#if os(macOS)
Task { await coordinator.reload() }
#endif
handleImportProfile()
handleImportRemoteProfile()
}
.onChangeCompat(of: importProfile.wrappedValue) { _ in
handleImportProfile()
}
.onChangeCompat(of: importRemoteProfile.wrappedValue) { _ in
handleImportRemoteProfile()
}
.sheet(item: $importRemoteProfileRequest) { request in
importRemoteProfileSheet(for: request)
}
#if os(macOS)
.onChangeCompat(of: controlActiveState) { state in
@@ -31,6 +45,52 @@ public struct DashboardView: View {
#endif
}
private func handleImportProfile() {
if let profile = importProfile.wrappedValue {
importProfile.wrappedValue = nil
coordinator.alert = Alert(
title: Text("Import Profile"),
message: Text("Are you sure to import profile \(profile.name)?"),
primaryButton: .default(Text("Import")) {
Task {
do {
try await profile.importProfile()
} catch {
coordinator.alert = Alert(error)
return
}
environments.profileUpdate.send()
}
},
secondaryButton: .cancel()
)
}
}
private func handleImportRemoteProfile() {
if let remoteProfile = importRemoteProfile.wrappedValue {
importRemoteProfile.wrappedValue = nil
coordinator.alert = Alert(
title: Text("Import Remote Profile"),
message: Text("Are you sure to import remote profile \(remoteProfile.name)? You will connect to \(remoteProfile.host) to download the configuration."),
primaryButton: .default(Text("Import")) {
importRemoteProfileRequest = .init(name: remoteProfile.name, url: remoteProfile.url)
},
secondaryButton: .cancel()
)
}
}
@ViewBuilder
private func importRemoteProfileSheet(for request: NewProfileView.ImportRequest) -> some View {
NavigationSheet(title: "Import Profile", onDismiss: {
environments.profileUpdate.send()
}) {
NewProfileView(request)
.environmentObject(environments)
}
}
@ViewBuilder
private var content: some View {
#if os(macOS)
@@ -34,13 +34,6 @@ public struct OverviewView: View {
Group {
if configuration.isLoading {
ProgressView()
} else if profileList.isEmpty {
VStack {
Spacer()
Text("Empty profiles")
.foregroundStyle(.secondary)
Spacer()
}
} else {
ScrollView {
cardGrid