feat(menubar): 实现趋势面板外侧详情与三语外观设置
接入有界趋势、平滑滚动、菜单式外侧详情、底部操作与三语文案,装配独立外观设置和 Dock 生命周期。 合并跟随系统外观刷新、自选颜色入口与色块绘制修复,保留用户确认的配色联动、重启保存及滚动验收。 多场景视觉与长期资源验证边界仍记录于 docs。
This commit is contained in:
@@ -0,0 +1,82 @@
|
||||
import SwiftUI
|
||||
|
||||
struct MiniTrendChart: View {
|
||||
let values: [Double?]
|
||||
let color: Color
|
||||
|
||||
@Environment(\.accessibilityReduceMotion) private var reduceMotion
|
||||
@State private var displayed: [Double?] = []
|
||||
@State private var progress: CGFloat = 1
|
||||
@State private var scrolling = false
|
||||
|
||||
var body: some View {
|
||||
TrendCanvas(values: displayed, color: color, progress: progress, scrolling: scrolling)
|
||||
.clipped()
|
||||
.accessibilityHidden(true)
|
||||
.onAppear { displayed = values; scrolling = false; progress = 1 }
|
||||
.onChange(of: values) { old, new in
|
||||
var transaction = Transaction()
|
||||
transaction.disablesAnimations = true
|
||||
withTransaction(transaction) {
|
||||
scrolling = !reduceMotion && TrendScroll.isAppend(from: old, to: new)
|
||||
displayed = scrolling ? old + [new.last!] : new
|
||||
progress = scrolling ? 0 : 1
|
||||
}
|
||||
}
|
||||
.task(id: values) {
|
||||
guard scrolling, !reduceMotion else { return }
|
||||
// Commit the starting frame before requesting interpolation; no repeating timer.
|
||||
do { try await Task.sleep(for: .milliseconds(16)) } catch { return }
|
||||
guard !Task.isCancelled else { return }
|
||||
withAnimation(.easeInOut(duration: 0.35)) { progress = 1 }
|
||||
}
|
||||
.onChange(of: reduceMotion) { _, reduced in
|
||||
if reduced {
|
||||
var transaction = Transaction()
|
||||
transaction.disablesAnimations = true
|
||||
withTransaction(transaction) { displayed = values; scrolling = false; progress = 1 }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private struct TrendCanvas: View, Animatable {
|
||||
let values: [Double?]
|
||||
let color: Color
|
||||
var progress: CGFloat
|
||||
let scrolling: Bool
|
||||
var animatableData: CGFloat {
|
||||
get { progress }
|
||||
set { progress = newValue }
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
Canvas { context, size in
|
||||
guard values.count > 1 else { return }
|
||||
var path = Path()
|
||||
var run: [CGPoint] = []
|
||||
func appendRun() {
|
||||
guard let first = run.first, let last = run.last else { return }
|
||||
path.move(to: first)
|
||||
if run.count == 1 { path.addLine(to: CGPoint(x: first.x + 0.1, y: first.y)) }
|
||||
for index in 1..<run.count {
|
||||
let previous = run[index - 1]
|
||||
let current = run[index]
|
||||
let midpoint = CGPoint(x: (previous.x + current.x) / 2, y: (previous.y + current.y) / 2)
|
||||
path.addQuadCurve(to: midpoint, control: previous)
|
||||
}
|
||||
path.addQuadCurve(to: last, control: last)
|
||||
run.removeAll(keepingCapacity: true)
|
||||
}
|
||||
for (index, value) in values.enumerated() {
|
||||
guard let value, value.isFinite else { appendRun(); continue }
|
||||
let x = size.width * TrendScroll.position(index: index, count: values.count,
|
||||
progress: progress, scrolling: scrolling)
|
||||
run.append(CGPoint(x: x, y: 2 + (size.height - 4) * (1 - min(1, max(0, value)))))
|
||||
}
|
||||
appendRun()
|
||||
context.stroke(path, with: .color(color.opacity(0.85)), style: StrokeStyle(lineWidth: 1.8, lineCap: .round, lineJoin: .round))
|
||||
}
|
||||
.accessibilityHidden(true)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import Foundation
|
||||
|
||||
/// Geometry for a single appended sample, including the outgoing point at full capacity.
|
||||
nonisolated enum TrendScroll {
|
||||
static func isAppend(from old: [Double?], to new: [Double?]) -> Bool {
|
||||
guard !old.isEmpty, !new.isEmpty else { return false }
|
||||
if old.count < MetricHistory.capacity {
|
||||
return new.count == old.count + 1 && Array(new.dropLast()) == old
|
||||
}
|
||||
return new.count == old.count && Array(old.dropFirst()) == Array(new.dropLast())
|
||||
}
|
||||
|
||||
static func position(index: Int, count: Int, progress: CGFloat, scrolling: Bool) -> CGFloat {
|
||||
let offset = MetricHistory.capacity - count
|
||||
let shift = scrolling ? 1 - min(1, max(0, progress)) : 0
|
||||
return (CGFloat(index + offset) + shift) / CGFloat(MetricHistory.capacity - 1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import SwiftUI
|
||||
import AppKit
|
||||
import Observation
|
||||
|
||||
extension AppAppearance {
|
||||
func resolved(systemIsDark: Bool) -> AppAppearance {
|
||||
self == .system ? (systemIsDark ? .dark : .light) : self
|
||||
}
|
||||
|
||||
var windowAppearance: NSAppearance? {
|
||||
switch self {
|
||||
case .system: nil
|
||||
case .light: NSAppearance(named: .aqua)
|
||||
case .dark: NSAppearance(named: .darkAqua)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension AppearancePreferences {
|
||||
var tintColor: Color {
|
||||
switch accent {
|
||||
case .system: .accentColor
|
||||
case .blue: .blue
|
||||
case .purple: .purple
|
||||
case .teal: .teal
|
||||
case .green: .green
|
||||
case .orange: .orange
|
||||
case .pink: .pink
|
||||
case .custom: Color(red: red, green: green, blue: blue)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct AppearanceStyle: ViewModifier {
|
||||
let preferences: AppearancePreferences
|
||||
@State private var system = SystemAppearanceObserver()
|
||||
private var resolved: AppAppearance { preferences.appearance.resolved(systemIsDark: system.isDark) }
|
||||
private var scheme: ColorScheme { resolved == .dark ? .dark : .light }
|
||||
func body(content: Content) -> some View {
|
||||
content
|
||||
.background(WindowAppearanceBridge(choice: resolved))
|
||||
.preferredColorScheme(scheme)
|
||||
.environment(\.colorScheme, scheme)
|
||||
.tint(preferences.tintColor)
|
||||
}
|
||||
}
|
||||
|
||||
/// Explicitly clear the NSWindow override when returning to system appearance.
|
||||
private struct WindowAppearanceBridge: NSViewRepresentable {
|
||||
let choice: AppAppearance
|
||||
func makeNSView(context: Context) -> AppearanceView { AppearanceView() }
|
||||
func updateNSView(_ view: AppearanceView, context: Context) { view.choice = choice }
|
||||
|
||||
final class AppearanceView: NSView {
|
||||
override func hitTest(_ point: NSPoint) -> NSView? { nil }
|
||||
var choice = AppAppearance.system { didSet { apply() } }
|
||||
override func viewDidMoveToWindow() { super.viewDidMoveToWindow(); apply() }
|
||||
private func apply() {
|
||||
WindowAppearance.apply(choice, to: window)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor enum WindowAppearance {
|
||||
static func apply(_ choice: AppAppearance, to window: NSWindow?) {
|
||||
let appearance = choice.windowAppearance
|
||||
if window?.appearance?.name != appearance?.name { window?.appearance = appearance }
|
||||
for child in window?.childWindows ?? [] where child.appearance?.name != appearance?.name {
|
||||
child.appearance = appearance
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// System source is independent of the color scheme inherited by this window.
|
||||
@MainActor @Observable final class SystemAppearanceObserver {
|
||||
private(set) var isDark = false
|
||||
@ObservationIgnored private var observation: NSKeyValueObservation?
|
||||
@ObservationIgnored private var themeToken: NSObjectProtocol?
|
||||
|
||||
init() {
|
||||
refresh()
|
||||
observation = NSApp.observe(\.effectiveAppearance, options: [.new]) { [weak self] _, _ in
|
||||
guard let self else { return }
|
||||
Task { @MainActor in self.refresh() }
|
||||
}
|
||||
themeToken = DistributedNotificationCenter.default().addObserver(
|
||||
forName: Notification.Name("AppleInterfaceThemeChangedNotification"), object: nil, queue: .main
|
||||
) { [weak self] _ in
|
||||
guard let self else { return }
|
||||
Task { @MainActor in self.refresh() }
|
||||
}
|
||||
}
|
||||
|
||||
private func refresh() {
|
||||
// Read the global domain, not this app's effective window appearance.
|
||||
isDark = Self.isDark(globalDomain: UserDefaults.standard.persistentDomain(forName: UserDefaults.globalDomain))
|
||||
}
|
||||
|
||||
static func isDark(globalDomain: [String: Any]?) -> Bool {
|
||||
(globalDomain?["AppleInterfaceStyle"] as? String)?.caseInsensitiveCompare("Dark") == .orderedSame
|
||||
}
|
||||
|
||||
deinit { if let themeToken { DistributedNotificationCenter.default().removeObserver(themeToken) } }
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import Foundation
|
||||
import CoreGraphics
|
||||
|
||||
|
||||
/// Screen coordinates: prefer the parent's right side, otherwise use its left.
|
||||
nonisolated enum DetailPlacement {
|
||||
static func frame(anchor: CGRect, parent: CGRect, content: CGSize, visible: CGRect) -> CGRect {
|
||||
let gap: CGFloat = 4
|
||||
let width = min(content.width, visible.width)
|
||||
let height = min(content.height, visible.height)
|
||||
let right = parent.maxX + gap
|
||||
let left = parent.minX - gap - width
|
||||
let candidate = right + width <= visible.maxX ? right : left
|
||||
let x = max(visible.minX, min(candidate, visible.maxX - width))
|
||||
let y = max(visible.minY, min(anchor.maxY - height, visible.maxY - height))
|
||||
return CGRect(x: x, y: y, width: width, height: height)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import SwiftUI
|
||||
import AppKit
|
||||
|
||||
/// A non-activating child window: outside the parent layout, below no other app.
|
||||
struct HoverDetailPresenter<Detail: View>: NSViewRepresentable {
|
||||
let isPresented: Bool
|
||||
let detail: Detail
|
||||
let onHover: (Bool) -> Void
|
||||
let onDismiss: () -> Void
|
||||
|
||||
func makeNSView(context: Context) -> AnchorView { AnchorView() }
|
||||
func updateNSView(_ view: AnchorView, context: Context) {
|
||||
view.configure(presented: isPresented, detail: AnyView(detail), onHover: onHover, onDismiss: onDismiss)
|
||||
}
|
||||
static func dismantleNSView(_ view: AnchorView, coordinator: ()) { view.detach() }
|
||||
|
||||
final class AnchorView: NSView {
|
||||
override func hitTest(_ point: NSPoint) -> NSView? { nil }
|
||||
private var panel: DetailPanel?
|
||||
private var host: NSHostingView<AnyView>?
|
||||
private var tokens: [NSObjectProtocol] = []
|
||||
private var presented = false
|
||||
private var detail = AnyView(EmptyView())
|
||||
private var onHover: (Bool) -> Void = { _ in }
|
||||
private var onDismiss: () -> Void = {}
|
||||
|
||||
func configure(presented: Bool, detail: AnyView,
|
||||
onHover: @escaping (Bool) -> Void, onDismiss: @escaping () -> Void) {
|
||||
self.presented = presented
|
||||
self.detail = detail
|
||||
self.onHover = onHover
|
||||
self.onDismiss = onDismiss
|
||||
refresh()
|
||||
}
|
||||
|
||||
override func viewDidMoveToWindow() {
|
||||
super.viewDidMoveToWindow()
|
||||
detach()
|
||||
guard let window else { return }
|
||||
for name in [NSWindow.willCloseNotification, NSWindow.didChangeOcclusionStateNotification] {
|
||||
tokens.append(NotificationCenter.default.addObserver(forName: name, object: window, queue: .main) { [weak self, weak window] notification in
|
||||
MainActor.assumeIsolated {
|
||||
guard notification.name == NSWindow.willCloseNotification || window?.occlusionState.contains(.visible) != true else { return }
|
||||
self?.hide()
|
||||
let dismiss = self?.onDismiss
|
||||
DispatchQueue.main.async { dismiss?() }
|
||||
}
|
||||
})
|
||||
}
|
||||
refresh()
|
||||
}
|
||||
|
||||
func detach() {
|
||||
hide()
|
||||
for token in tokens { NotificationCenter.default.removeObserver(token) }
|
||||
tokens.removeAll()
|
||||
}
|
||||
|
||||
private func refresh() {
|
||||
guard presented, let parent = window, parent.isVisible, let screen = parent.screen else { hide(); return }
|
||||
let content = AnyView(detail
|
||||
.font(.caption)
|
||||
.padding(12)
|
||||
.frame(width: 280)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
.onHover { [weak self] inside in self?.onHover(inside) })
|
||||
if panel == nil {
|
||||
let panel = DetailPanel(contentRect: .zero, styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false)
|
||||
panel.isReleasedWhenClosed = false
|
||||
panel.isOpaque = false
|
||||
panel.backgroundColor = .clear
|
||||
panel.hasShadow = true
|
||||
panel.hidesOnDeactivate = false
|
||||
panel.level = parent.level
|
||||
let material = NSVisualEffectView()
|
||||
material.material = .menu
|
||||
material.blendingMode = .behindWindow
|
||||
material.state = .active
|
||||
material.wantsLayer = true
|
||||
material.layer?.cornerRadius = 12
|
||||
material.layer?.masksToBounds = true
|
||||
let host = NSHostingView(rootView: content)
|
||||
host.translatesAutoresizingMaskIntoConstraints = false
|
||||
material.addSubview(host)
|
||||
NSLayoutConstraint.activate([
|
||||
host.leadingAnchor.constraint(equalTo: material.leadingAnchor),
|
||||
host.trailingAnchor.constraint(equalTo: material.trailingAnchor),
|
||||
host.topAnchor.constraint(equalTo: material.topAnchor),
|
||||
host.bottomAnchor.constraint(equalTo: material.bottomAnchor)
|
||||
])
|
||||
panel.contentView = material
|
||||
self.panel = panel
|
||||
self.host = host
|
||||
parent.addChildWindow(panel, ordered: .above)
|
||||
}
|
||||
guard let panel, let host else { return }
|
||||
host.rootView = content
|
||||
panel.appearance = parent.appearance
|
||||
let row = parent.convertToScreen(convert(bounds, to: nil))
|
||||
let size = host.fittingSize
|
||||
panel.setFrame(DetailPlacement.frame(anchor: row, parent: parent.frame,
|
||||
content: CGSize(width: 280, height: max(40, size.height)),
|
||||
visible: screen.visibleFrame), display: true)
|
||||
panel.orderFront(nil)
|
||||
}
|
||||
|
||||
private func hide() {
|
||||
guard let panel else { return }
|
||||
panel.parent?.removeChildWindow(panel)
|
||||
panel.orderOut(nil)
|
||||
panel.contentView = nil
|
||||
panel.close()
|
||||
host = nil
|
||||
self.panel = nil
|
||||
}
|
||||
|
||||
deinit { for token in tokens { NotificationCenter.default.removeObserver(token) } }
|
||||
}
|
||||
|
||||
final class DetailPanel: NSPanel {
|
||||
override var canBecomeKey: Bool { false }
|
||||
override var canBecomeMain: Bool { false }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import SwiftUI
|
||||
|
||||
struct MetricRow<Detail: View>: View {
|
||||
let title: LocalizedStringKey
|
||||
let symbol: String
|
||||
let value: String
|
||||
let usage: Double?
|
||||
let history: [Double?]
|
||||
let accent: Color
|
||||
@ViewBuilder let detail: () -> Detail
|
||||
@Environment(\.accessibilityReduceMotion) private var reduceMotion
|
||||
@State private var visible = false
|
||||
@State private var rowHovered = false
|
||||
@State private var detailHovered = false
|
||||
@State private var expanded = false
|
||||
private var inside: Bool { rowHovered || detailHovered }
|
||||
|
||||
private var color: Color {
|
||||
guard let usage else { return .secondary }
|
||||
return usage > 0.95 ? .red : usage >= 0.8 ? .orange : accent
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
Button { expanded.toggle() } label: {
|
||||
HStack(spacing: 10) {
|
||||
Image(systemName: symbol)
|
||||
.font(.system(size: 13, weight: .medium))
|
||||
.foregroundStyle(color)
|
||||
.frame(width: 20)
|
||||
Text(title).font(.system(size: 13, weight: .medium))
|
||||
.frame(width: 52, alignment: .leading)
|
||||
MiniTrendChart(values: history, color: color).frame(height: 24)
|
||||
Text(verbatim: value)
|
||||
.font(.system(size: 13, weight: .semibold, design: .rounded))
|
||||
.monospacedDigit()
|
||||
.contentTransition(.numericText())
|
||||
.frame(width: 46, alignment: .trailing)
|
||||
}
|
||||
.contentShape(Rectangle())
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.accessibilityLabel(Text(title))
|
||||
.accessibilityValue(Text(verbatim: value))
|
||||
.accessibilityHint(expanded ? Text("detail.expanded") : Text("detail.collapsed"))
|
||||
.padding(10)
|
||||
.background(expanded ? Color.primary.opacity(0.035) : .clear, in: .rect(cornerRadius: 14))
|
||||
.background(HoverDetailPresenter(isPresented: expanded && visible, detail: detail(),
|
||||
onHover: { detailHovered = $0 },
|
||||
onDismiss: { expanded = false; detailHovered = false }))
|
||||
.onHover { rowHovered = $0 }
|
||||
.task(id: inside) {
|
||||
do { try await Task.sleep(for: .milliseconds(inside ? 150 : 120)) }
|
||||
catch { return }
|
||||
guard !Task.isCancelled else { return }
|
||||
expanded = inside
|
||||
}
|
||||
.onAppear { visible = true }
|
||||
.onDisappear { visible = false; rowHovered = false; detailHovered = false; expanded = false }
|
||||
.animation(!visible || reduceMotion ? nil : .spring(duration: 0.3, bounce: 0), value: value)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user