refactor(ui): 统一胶囊页签并将面板收窄至640点
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
|
||||
/// Tab navigation uses AppKit's toolbar-style capsule in either hosting context.
|
||||
struct NeutralTabPicker<Selection: Hashable>: NSViewRepresentable {
|
||||
let title: String
|
||||
@Binding var selection: Selection
|
||||
let options: [(Selection, String)]
|
||||
@Environment(\.locale) private var locale
|
||||
|
||||
func makeCoordinator() -> NeutralTabPickerCoordinator { NeutralTabPickerCoordinator() }
|
||||
|
||||
func makeNSView(context: Context) -> NSSegmentedControl {
|
||||
let control = NSSegmentedControl()
|
||||
control.trackingMode = .selectOne
|
||||
control.segmentStyle = .capsule
|
||||
control.role = .tabs
|
||||
control.borderShape = .capsule
|
||||
control.segmentDistribution = .fillEqually
|
||||
control.controlSize = .regular
|
||||
control.target = context.coordinator
|
||||
control.action = #selector(NeutralTabPickerCoordinator.changed(_:))
|
||||
return control
|
||||
}
|
||||
|
||||
func updateNSView(_ control: NSSegmentedControl, context: Context) {
|
||||
if control.segmentCount != options.count { control.segmentCount = options.count }
|
||||
for (index, option) in options.enumerated() {
|
||||
let label = AppLocalization.string(option.1, locale: locale)
|
||||
if control.label(forSegment: index) != label { control.setLabel(label, forSegment: index) }
|
||||
}
|
||||
let selected = options.firstIndex { $0.0 == selection } ?? -1
|
||||
if control.selectedSegment != selected { control.selectedSegment = selected }
|
||||
control.setAccessibilityLabel(AppLocalization.string(title, locale: locale))
|
||||
let binding = $selection, values = options.map(\.0)
|
||||
context.coordinator.onSelect = { index in
|
||||
guard values.indices.contains(index) else { return }
|
||||
binding.wrappedValue = values[index]
|
||||
}
|
||||
}
|
||||
|
||||
func sizeThatFits(_ proposal: ProposedViewSize, nsView: NSSegmentedControl, context: Context) -> CGSize? {
|
||||
CGSize(width: proposal.width ?? nsView.intrinsicContentSize.width,
|
||||
height: max(24, nsView.intrinsicContentSize.height))
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor final class NeutralTabPickerCoordinator: NSObject {
|
||||
var onSelect: ((Int) -> Void)?
|
||||
@objc func changed(_ sender: NSSegmentedControl) { onSelect?(sender.selectedSegment) }
|
||||
}
|
||||
Reference in New Issue
Block a user