feat(ui): 实现全卡堆叠趋势与单页资源进程布局
This commit is contained in:
@@ -46,10 +46,8 @@ import AppKit
|
||||
scenes = settings
|
||||
openSettingsAction = { settings.environment.openSettings() }
|
||||
configureMainMenu()
|
||||
metrics.setDetailDemand(processes: true, slowMetrics: true)
|
||||
menuBar = MenuPanelController(visibility: { [metrics] in metrics.setPanelVisible($0) },
|
||||
pageChanged: { [metrics] page in
|
||||
metrics.setDetailDemand(processes: page == .processes, slowMetrics: page == .overview)
|
||||
},
|
||||
menuTitle: { [language] key in
|
||||
AppLocalization.string("status." + key, locale: language.locale, table: "StatusItem")
|
||||
}, openSettings: { [weak self] in self?.settingsCommand() }) { [self] panel in
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import SwiftUI
|
||||
|
||||
/// One row per core kind; every equal-width meter represents one real core.
|
||||
/// Core-kind columns contain one vertical segmented meter per real core.
|
||||
struct CPUCoreGrid: View {
|
||||
let values: [Double]
|
||||
let kinds: [Int: CPUCoreTopology.Kind]
|
||||
@@ -40,34 +40,34 @@ struct CPUCoreGrid: View {
|
||||
return order.map { kind in (0..<max(0, count)).filter { kinds[$0] == kind } }.filter { !$0.isEmpty }
|
||||
}
|
||||
|
||||
static let labelWidth: CGFloat = 44
|
||||
|
||||
static func groupWidths(groups: [[Int]], width: CGFloat) -> [CGFloat] {
|
||||
let available = width.isFinite ? max(0, width - labelWidth - 6) : 0
|
||||
return Array(repeating: available, count: groups.count)
|
||||
guard !groups.isEmpty else { return [] }
|
||||
let available = width.isFinite ? max(0, width - CGFloat(groups.count - 1) * 8) : 0
|
||||
let minimum = min(44, available / CGFloat(groups.count))
|
||||
let remaining = max(0, available - minimum * CGFloat(groups.count))
|
||||
let total = max(1, groups.reduce(0) { $0 + $1.count })
|
||||
return groups.map { minimum + remaining * CGFloat($0.count) / CGFloat(total) }
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
let groups = Self.groups(count: values.count, kinds: kinds)
|
||||
GeometryReader { geometry in
|
||||
let widths = Self.groupWidths(groups: groups, width: geometry.size.width)
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
HStack(alignment: .top, spacing: 8) {
|
||||
ForEach(groups.indices, id: \.self) { group in
|
||||
HStack(alignment: .top, spacing: 6) {
|
||||
VStack(alignment: .leading, spacing: 4) {
|
||||
HStack(spacing: 2) {
|
||||
Circle().fill(color(kinds[groups[group][0]])).frame(width: 3, height: 3)
|
||||
if let kind = kinds[groups[group][0]] { label(kind, compact: true) }
|
||||
else { Text("cpu.core") }
|
||||
Text(verbatim: "\(groups[group].count)").foregroundStyle(.secondary)
|
||||
}
|
||||
.font(.system(size: 8, weight: .medium))
|
||||
.lineLimit(1).minimumScaleFactor(0.65)
|
||||
.frame(width: Self.labelWidth, height: CPUCoreGridLayout.rowHeight, alignment: .leading)
|
||||
.font(.system(size: 8, weight: .medium)).lineLimit(1).minimumScaleFactor(0.65)
|
||||
.frame(height: 10)
|
||||
CPUCoreGridLayout {
|
||||
ForEach(groups[group], id: \.self) { index in core(index: index) }
|
||||
}
|
||||
.frame(width: widths[group])
|
||||
}
|
||||
}.frame(width: widths[group], alignment: .topLeading)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -78,15 +78,15 @@ struct CPUCoreGrid: View {
|
||||
|
||||
private func gridHeight(groups: [[Int]]) -> CGFloat {
|
||||
let widths = Self.groupWidths(groups: groups, width: availableWidth)
|
||||
let rows = zip(groups, widths).map { CPUCoreGridLayout.rowCounts(count: $0.0.count, width: $0.1).count }.reduce(0, +)
|
||||
return CGFloat(rows) * CPUCoreGridLayout.rowHeight + CGFloat(max(0, rows - 1)) * CPUCoreGridLayout.rowSpacing
|
||||
let rows = zip(groups, widths).map { CPUCoreGridLayout.rowCounts(count: $0.0.count, width: $0.1).count }.max() ?? 0
|
||||
return 14 + CGFloat(rows) * CPUCoreGridLayout.rowHeight + CGFloat(max(0, rows - 1)) * CPUCoreGridLayout.rowSpacing
|
||||
}
|
||||
|
||||
private func core(index: Int) -> some View {
|
||||
let kind = kinds[index]
|
||||
let measured = values[index].isFinite ? values[index] : nil
|
||||
return MetricProgressBar(value: measured ?? 0, color: color(kind), cornerRadius: 2)
|
||||
.frame(height: 8)
|
||||
return SegmentedCoreBar(value: measured, color: color(kind))
|
||||
.frame(height: 30)
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
.help(Text("\(kind.map { label($0) } ?? Text("cpu.core")) · \(index + 1): \(MetricFormat.percent(measured))"))
|
||||
.accessibilityElement(children: .ignore)
|
||||
@@ -98,8 +98,8 @@ struct CPUCoreGrid: View {
|
||||
struct CPUCoreGridLayout: Layout {
|
||||
static let columnSpacing: CGFloat = 3
|
||||
static let rowSpacing: CGFloat = 4
|
||||
static let rowHeight: CGFloat = 10
|
||||
static let minimumCellWidth: CGFloat = 8
|
||||
static let rowHeight: CGFloat = 30
|
||||
static let minimumCellWidth: CGFloat = 6
|
||||
|
||||
static func rowCounts(count: Int, width: CGFloat) -> [Int] {
|
||||
guard count > 0 else { return [] }
|
||||
|
||||
@@ -2,14 +2,10 @@ import AppKit
|
||||
import SwiftUI
|
||||
import Observation
|
||||
|
||||
enum PanelPage: Hashable { case overview, processes }
|
||||
|
||||
@MainActor @Observable final class PanelPresentation {
|
||||
fileprivate(set) var isOpen = false
|
||||
var isPinned = false { didSet { onPinChange?(isPinned) } }
|
||||
var page: PanelPage = .overview { didSet { if oldValue != page { onPageChange?(page) } } }
|
||||
@ObservationIgnored var onPinChange: ((Bool) -> Void)?
|
||||
@ObservationIgnored var onPageChange: ((PanelPage) -> Void)?
|
||||
}
|
||||
|
||||
/// Owns only status-item/window behavior. Sampling and settings are injected by App.
|
||||
@@ -33,7 +29,6 @@ enum PanelPage: Hashable { case overview, processes }
|
||||
private var preferredContentHeight = PanelLayout.defaultHeight
|
||||
|
||||
init<Content: View>(installStatusItem: Bool = true, visibility: @escaping (Bool) -> Void,
|
||||
pageChanged: @escaping (PanelPage) -> Void = { _ in },
|
||||
menuTitle: @escaping (String) -> String = { $0 },
|
||||
openSettings: @escaping () -> Void = {},
|
||||
@ViewBuilder content: @escaping (PanelPresentation) -> Content) {
|
||||
@@ -57,7 +52,6 @@ enum PanelPage: Hashable { case overview, processes }
|
||||
panel.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary]
|
||||
panel.dismiss = { [weak self] in self?.hide() }
|
||||
presentation.onPinChange = { [weak self] pinned in self?.panel.level = pinned ? .floating : .normal }
|
||||
presentation.onPageChange = pageChanged
|
||||
if installStatusItem {
|
||||
let item = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)
|
||||
item.button?.image = NSImage(named: "BrandMark")
|
||||
@@ -123,7 +117,6 @@ enum PanelPage: Hashable { case overview, processes }
|
||||
func show() {
|
||||
guard !panel.isVisible else { panel.makeKeyAndOrderFront(nil); return }
|
||||
place()
|
||||
presentation.page = .overview
|
||||
presentation.isOpen = true
|
||||
panel.contentView = content(presentation)
|
||||
panel.level = presentation.isPinned ? .floating : .normal
|
||||
|
||||
@@ -39,7 +39,7 @@ extension MenuPanelView {
|
||||
second: samples.map(\.cpuUser), third: samples.map(\.cpuSystem),
|
||||
color: Color("MetricCPU"), secondColor: Color("SeriesUser"), thirdColor: Color("SeriesSystem"),
|
||||
firstLabel: "gpu.totalUtilization", secondLabel: "cpu.user", thirdLabel: "cpu.system", expectedInterval: chartInterval,
|
||||
boundaryDates: chartBoundaries, intervals: chartIntervals)
|
||||
boundaryDates: chartBoundaries, intervals: chartIntervals, stackOrder: [2, 1])
|
||||
}
|
||||
) {
|
||||
HStack(spacing: 5) {
|
||||
@@ -64,10 +64,12 @@ extension MenuPanelView {
|
||||
chart: {
|
||||
PanelTrendChart(
|
||||
dates: samples.map(\.date), first: samples.map(\.gpu),
|
||||
second: samples.map(\.gpuRenderer), third: samples.map(\.gpuTiler),
|
||||
color: Color("MetricGPU"), secondColor: Color("MetricCPU"), thirdColor: Color("SeriesSystem"),
|
||||
firstLabel: "gpu.totalUtilization", secondLabel: "gpu.renderer", thirdLabel: "gpu.tiler",
|
||||
expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals)
|
||||
second: samples.map { $0.gpu.map { max(0, 1 - $0) } },
|
||||
third: samples.map(\.gpuRenderer), fourth: samples.map(\.gpuTiler),
|
||||
color: Color("MetricGPU"), secondColor: Color("MemoryAvailable"),
|
||||
thirdColor: Color("MetricCPU"), fourthColor: Color("SeriesSystem"),
|
||||
firstLabel: "gpu.totalUtilization", secondLabel: "gpu.idle", thirdLabel: "gpu.renderer", fourthLabel: "gpu.tiler",
|
||||
expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals, stackOrder: [0, 1])
|
||||
}
|
||||
) {
|
||||
HStack(spacing: 5) {
|
||||
@@ -75,8 +77,6 @@ extension MenuPanelView {
|
||||
Text(verbatim: String(format: AppLocalization.string("gpu.coreCountFormat", locale: locale), count))
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
inlineMetric("gpu.renderer", MetricFormat.percent(snapshot.gpu?.renderer))
|
||||
inlineMetric("gpu.tiler", MetricFormat.percent(snapshot.gpu?.tiler))
|
||||
}.font(.system(size: 9)).lineLimit(1).minimumScaleFactor(0.75).frame(height: 12)
|
||||
let fans = displayedFans
|
||||
if !fans.isEmpty {
|
||||
@@ -85,7 +85,8 @@ extension MenuPanelView {
|
||||
FanSpeedIndicator(
|
||||
title: fans.count == 2
|
||||
? (fan.id == 0 ? Text("gpu.fanLeft") : Text("gpu.fanRight"))
|
||||
: Text("gpu.fanNumber \(fan.id + 1)"), rpm: fan.rpm)
|
||||
: Text("gpu.fanNumber \(fan.id + 1)"), rpm: fan.rpm,
|
||||
isActive: metrics.isPanelVisible && !metrics.isPaused && !metrics.isSystemSleeping && !metrics.isDisplaySleeping)
|
||||
.frame(height: 12)
|
||||
}
|
||||
}
|
||||
@@ -114,7 +115,7 @@ extension MenuPanelView {
|
||||
thirdColor: Color("MemoryWired"), fourthColor: Color("MemoryCompressed"), fixedScale: Double(snapshot.memory?.total ?? 1),
|
||||
firstValueFormat: .memory, firstLabel: "gpu.totalUtilization",
|
||||
secondLabel: "memory.app", thirdLabel: "memory.wired", fourthLabel: "memory.compressed",
|
||||
expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals)
|
||||
expectedInterval: chartInterval, boundaryDates: chartBoundaries, intervals: chartIntervals, stackOrder: [1, 2, 3])
|
||||
}
|
||||
) {
|
||||
if let memory = snapshot.memory {
|
||||
|
||||
@@ -35,7 +35,7 @@ struct MenuPanelView: View {
|
||||
let coreCount = max(CPUCoreTopology.cores.count, ProcessInfo.processInfo.processorCount, snapshot.cpu?.cores.count ?? 0)
|
||||
let groups = CPUCoreGrid.groups(count: coreCount, kinds: CPUCoreTopology.cores)
|
||||
let widths = CPUCoreGrid.groupWidths(groups: groups, width: cardContentWidth)
|
||||
let coreRows = zip(groups, widths).map { CPUCoreGridLayout.rowCounts(count: $0.0.count, width: $0.1).count }.reduce(0, +)
|
||||
let coreRows = zip(groups, widths).map { CPUCoreGridLayout.rowCounts(count: $0.0.count, width: $0.1).count }.max() ?? 0
|
||||
let fanCount = reservedFanCount > 0 ? max(reservedFanCount, snapshot.fans?.count ?? 0) : snapshot.fans?.count
|
||||
return PanelLayout.cardHeights(coreRows: coreRows, fanCount: fanCount)
|
||||
}
|
||||
@@ -51,17 +51,11 @@ struct MenuPanelView: View {
|
||||
var body: some View {
|
||||
VStack(spacing: PanelStyle.gap) {
|
||||
header
|
||||
if presentation.page == .overview {
|
||||
if PanelLayout.needsResourceScroll(size: panelSize, heights: cardHeights) {
|
||||
ScrollView { resourceGrid }
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
} else {
|
||||
resourceGrid
|
||||
.frame(maxHeight: .infinity, alignment: .top)
|
||||
}
|
||||
} else if presentation.isOpen {
|
||||
PanelProcessSection(metrics: metrics, state: processState)
|
||||
if PanelLayout.needsDashboardScroll(size: panelSize, heights: cardHeights) {
|
||||
ScrollView { dashboard }
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
} else {
|
||||
dashboard.frame(maxHeight: .infinity, alignment: .top)
|
||||
}
|
||||
footer
|
||||
}
|
||||
@@ -91,6 +85,17 @@ struct MenuPanelView: View {
|
||||
.modifier(AppearanceStyle(preferences: preferences))
|
||||
}
|
||||
|
||||
private var dashboard: some View {
|
||||
VStack(spacing: PanelStyle.gap) {
|
||||
resourceGrid
|
||||
if presentation.isOpen {
|
||||
PanelProcessSection(metrics: metrics, state: processState)
|
||||
.frame(maxWidth: .infinity)
|
||||
.frame(height: PanelLayout.processHeight(heights: cardHeights))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var resourceGrid: some View {
|
||||
let rows = PanelLayout.cardRows(columns: columns)
|
||||
let heights = PanelLayout.rowHeights(columns: columns, heights: cardHeights)
|
||||
@@ -130,25 +135,11 @@ struct MenuPanelView: View {
|
||||
}
|
||||
}
|
||||
|
||||
private var pagePicker: some View {
|
||||
NeutralTabPicker(title: "panel.page", selection: Binding(get: { presentation.page }, set: { presentation.page = $0 }),
|
||||
options: [(.overview, "panel.overview"), (.processes, "panel.processes")])
|
||||
.frame(width: 164)
|
||||
.accessibilityIdentifier("panel.tabs")
|
||||
}
|
||||
|
||||
private var header: some View {
|
||||
VStack(spacing: 4) {
|
||||
HStack(spacing: 8) {
|
||||
brand
|
||||
Spacer(minLength: 8)
|
||||
controls
|
||||
}
|
||||
.frame(height: 32)
|
||||
.overlay {
|
||||
if panelSize.width >= 560 { pagePicker }
|
||||
}
|
||||
if panelSize.width < 560 { pagePicker.frame(maxWidth: .infinity).frame(height: 28) }
|
||||
HStack(spacing: 8) {
|
||||
brand
|
||||
Spacer(minLength: 8)
|
||||
controls
|
||||
}
|
||||
.frame(height: PanelLayout.headerHeight(width: panelSize.width))
|
||||
.padding(.horizontal, 4)
|
||||
|
||||
@@ -9,7 +9,7 @@ nonisolated enum PanelLayout {
|
||||
static let footerHeight: CGFloat = 26
|
||||
static let maximumWidth: CGFloat = ResourceCardMetrics.preferredWidth * 3 + 32
|
||||
static let maximumHeight: CGFloat = 800
|
||||
static func headerHeight(width: CGFloat) -> CGFloat { width >= 560 ? 32 : 64 }
|
||||
static func headerHeight(width: CGFloat) -> CGFloat { 32 }
|
||||
static func columns(width: CGFloat) -> Int { width >= 620 ? 3 : width >= 430 ? 2 : 1 }
|
||||
static func cardWidth(size: CGSize) -> CGFloat {
|
||||
let count = columns(width: size.width)
|
||||
@@ -25,19 +25,21 @@ nonisolated enum PanelLayout {
|
||||
}
|
||||
}
|
||||
|
||||
/// Foreground details and the edge-to-edge background trend have separate budgets.
|
||||
/// Structural foreground height determines the full-height background chart.
|
||||
static func cardHeights(coreRows: Int, fanCount: Int?) -> [PanelCard: CGFloat] {
|
||||
let base = ResourceCardMetrics.minimumHeight
|
||||
let fanRows = fanCount.map { (max(0, $0) + 1) / 2 } ?? 1
|
||||
return [.cpu: base + CGFloat(max(0, coreRows - 2)) * 14,
|
||||
return [.cpu: base + CGFloat(max(0, coreRows - 1)) * 34,
|
||||
.gpu: base + CGFloat(max(0, fanRows - 1)) * 14,
|
||||
.memory: base, .battery: base, .storage: base, .network: base]
|
||||
}
|
||||
|
||||
static func rowHeights(columns: Int, heights: [PanelCard: CGFloat]) -> [CGFloat] {
|
||||
cardRows(columns: columns).map { cards in
|
||||
cards.map { heights[$0] ?? 0 }.max() ?? 0
|
||||
}
|
||||
Array(repeating: processHeight(heights: heights), count: cardRows(columns: columns).count)
|
||||
}
|
||||
|
||||
static func processHeight(heights: [PanelCard: CGFloat]) -> CGFloat {
|
||||
heights.values.max() ?? ResourceCardMetrics.minimumHeight
|
||||
}
|
||||
|
||||
static func resourceHeight(columns: Int, heights: [PanelCard: CGFloat]) -> CGFloat {
|
||||
@@ -45,17 +47,21 @@ nonisolated enum PanelLayout {
|
||||
return rows.reduce(0, +) + CGFloat(max(0, rows.count - 1)) * 6
|
||||
}
|
||||
|
||||
static func dashboardHeight(columns: Int, heights: [PanelCard: CGFloat]) -> CGFloat {
|
||||
resourceHeight(columns: columns, heights: heights) + 6 + processHeight(heights: heights)
|
||||
}
|
||||
|
||||
static func preferredHeight(width: CGFloat, heights: [PanelCard: CGFloat]) -> CGFloat {
|
||||
min(maximumHeight, resourceHeight(columns: columns(width: width), heights: heights)
|
||||
min(maximumHeight, dashboardHeight(columns: columns(width: width), heights: heights)
|
||||
+ 20 + headerHeight(width: width) + footerHeight + 12)
|
||||
}
|
||||
|
||||
static var defaultHeight: CGFloat {
|
||||
preferredHeight(width: maximumWidth, heights: cardHeights(coreRows: 2, fanCount: nil))
|
||||
preferredHeight(width: maximumWidth, heights: cardHeights(coreRows: 1, fanCount: nil))
|
||||
}
|
||||
|
||||
static func needsResourceScroll(size: CGSize, heights: [PanelCard: CGFloat]) -> Bool {
|
||||
resourceHeight(columns: columns(width: size.width), heights: heights)
|
||||
static func needsDashboardScroll(size: CGSize, heights: [PanelCard: CGFloat]) -> Bool {
|
||||
dashboardHeight(columns: columns(width: size.width), heights: heights)
|
||||
> size.height - 20 - headerHeight(width: size.width) - footerHeight - 12
|
||||
}
|
||||
|
||||
|
||||
@@ -58,7 +58,6 @@ import AppKit
|
||||
mark("hidden10")
|
||||
for cycle in 1...3 {
|
||||
controller.show()
|
||||
if ProcessInfo.processInfo.environment["KYMO_AUDIT_PAGE"] == "processes" { controller.presentation.page = .processes }
|
||||
mark("open\(cycle).0")
|
||||
await wait(1); mark("open\(cycle).1")
|
||||
await wait(9); mark("open\(cycle).10")
|
||||
|
||||
@@ -39,11 +39,13 @@ struct ProcessTableView: View {
|
||||
if snapshot?.failed == true { Text("panel.processFailed") }
|
||||
else if snapshot == nil { Text("metric.waiting").foregroundStyle(.secondary) }
|
||||
NativeProcessTable(rows: rows, selection: $state.selected, sorting: $state.sortOrder, locale: locale, onExit: handleExit)
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
.overlay { if snapshot != nil && rows.isEmpty && snapshot?.failed != true { Text("panel.noResults").foregroundStyle(.secondary).allowsHitTesting(false) } }
|
||||
if exitedSelection != nil, let departed = state.departed {
|
||||
HStack { Text(verbatim: departed.name); Text("panel.exited"); Button("panel.dismiss") { state.selected = nil; state.departed = nil } }
|
||||
}
|
||||
}
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
|
||||
.font(.system(size: 12)).padding(10)
|
||||
.modifier(CardSurface())
|
||||
.onAppear { rebuild(retainOrder: false) }
|
||||
|
||||
@@ -1,6 +1,28 @@
|
||||
{
|
||||
"sourceLanguage" : "en",
|
||||
"strings" : {
|
||||
"gpu.idle" : {
|
||||
"localizations": {
|
||||
"en": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "Idle"
|
||||
}
|
||||
},
|
||||
"zh-Hans": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "空闲"
|
||||
}
|
||||
},
|
||||
"zh-Hant": {
|
||||
"stringUnit": {
|
||||
"state": "translated",
|
||||
"value": "閒置"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"disk.lifeShort" : {
|
||||
"localizations": {
|
||||
"en": {
|
||||
|
||||
@@ -10,6 +10,7 @@ struct NativePanelCurve: NSViewRepresentable {
|
||||
var hoveredIndex: Int? = nil
|
||||
var visibleSeriesCount: Int? = nil
|
||||
var filledSeriesCount = 1
|
||||
var stacked = false
|
||||
|
||||
func sizeThatFits(_ proposal: ProposedViewSize, nsView: PlotView, context: Context) -> CGSize? {
|
||||
CGSize(width: proposal.width.flatMap { $0.isFinite ? $0 : nil } ?? 10,
|
||||
@@ -18,7 +19,7 @@ struct NativePanelCurve: NSViewRepresentable {
|
||||
func makeNSView(context: Context) -> PlotView { PlotView() }
|
||||
func updateNSView(_ view: PlotView, context: Context) {
|
||||
view.configure(Input(frame: frame, colors: colors, scales: scales, maximumGap: maximumGap,
|
||||
hoveredIndex: hoveredIndex, visibleSeriesCount: visibleSeriesCount, filledSeriesCount: filledSeriesCount))
|
||||
hoveredIndex: hoveredIndex, visibleSeriesCount: visibleSeriesCount, filledSeriesCount: filledSeriesCount, stacked: stacked))
|
||||
}
|
||||
struct Input: Equatable {
|
||||
let frame: PanelCurveFrame
|
||||
@@ -28,6 +29,7 @@ struct NativePanelCurve: NSViewRepresentable {
|
||||
var hoveredIndex: Int? = nil
|
||||
var visibleSeriesCount: Int? = nil
|
||||
var filledSeriesCount = 1
|
||||
var stacked = false
|
||||
}
|
||||
final class PlotView: NSView {
|
||||
private(set) var input: Input?
|
||||
@@ -38,6 +40,7 @@ struct NativePanelCurve: NSViewRepresentable {
|
||||
private var hoverDots: [CAShapeLayer] = []
|
||||
private var seriesLayers: [SeriesLayer] = []
|
||||
private var palette: [NSColor] = []
|
||||
private var plottedBands: [StackedSeries.Band] = []
|
||||
override var isFlipped: Bool { true }
|
||||
override func hitTest(_ point: NSPoint) -> NSView? { nil }
|
||||
|
||||
@@ -67,7 +70,7 @@ struct NativePanelCurve: NSViewRepresentable {
|
||||
for index in seriesLayers.indices {
|
||||
seriesLayers[index].root.isHidden = index >= (value.visibleSeriesCount ?? value.frame.series.count)
|
||||
}
|
||||
if frameChanged || old?.scales != value.scales || old?.maximumGap != value.maximumGap {
|
||||
if frameChanged || old?.scales != value.scales || old?.maximumGap != value.maximumGap || old?.stacked != value.stacked {
|
||||
rebuildPaths()
|
||||
}
|
||||
updateHover()
|
||||
@@ -122,13 +125,16 @@ struct NativePanelCurve: NSViewRepresentable {
|
||||
}
|
||||
let domain = PanelCurveFrame.domain(begin: first, end: last)
|
||||
let frame = input.frame
|
||||
plottedBands = input.stacked ? StackedSeries.bands(frame.series, count: frame.dates.count, limit: input.scales.first) : []
|
||||
for index in frame.series.indices {
|
||||
let series = seriesLayers[index]
|
||||
series.resize(bounds)
|
||||
let value = input.scales[min(index, input.scales.count - 1)]
|
||||
let value = input.scales[input.stacked ? 0 : min(index, input.scales.count - 1)]
|
||||
let scale = value.isFinite && value > 0 ? value : 1
|
||||
let runs = PanelCurveGeometry.runs(dates: frame.dates, values: frame.series[index], maximumGap: input.maximumGap,
|
||||
boundaryDates: frame.boundaryDates, intervals: frame.intervals)
|
||||
let upper = input.stacked ? plottedBands[index].upper : frame.series[index]
|
||||
let lower = input.stacked ? plottedBands[index].lower : nil
|
||||
let runs = PanelCurveGeometry.runs(dates: frame.dates, values: upper, maximumGap: input.maximumGap,
|
||||
boundaryDates: frame.boundaryDates, intervals: frame.intervals, lowerValues: lower)
|
||||
let line = CGMutablePath(), dots = CGMutablePath(), area = CGMutablePath()
|
||||
for run in runs {
|
||||
let points = run.map { CGPoint(x: bounds.width * domain.position($0.date),
|
||||
@@ -143,11 +149,16 @@ struct NativePanelCurve: NSViewRepresentable {
|
||||
segment.addCurve(to: b, control1: CGPoint(x: mid, y: a.y), control2: CGPoint(x: mid, y: b.y))
|
||||
}
|
||||
line.addPath(segment)
|
||||
// Each continuous run closes against its own baseline, preserving real gaps.
|
||||
// Close against the matching lower boundary, never against another run or missing component.
|
||||
let lowerPoints = run.reversed().map { CGPoint(x: bounds.width * domain.position($0.date),
|
||||
y: bounds.height * (1 - min(1, max(0, $0.lower / scale)))) }
|
||||
let fill = CGMutablePath(); fill.addPath(segment)
|
||||
fill.addLine(to: CGPoint(x: points.last!.x, y: bounds.height))
|
||||
fill.addLine(to: CGPoint(x: start.x, y: bounds.height)); fill.closeSubpath()
|
||||
area.addPath(fill)
|
||||
if let lowerStart = lowerPoints.first { fill.addLine(to: lowerStart) }
|
||||
for (a, b) in zip(lowerPoints, lowerPoints.dropFirst()) {
|
||||
let mid = (a.x + b.x) / 2
|
||||
fill.addCurve(to: b, control1: CGPoint(x: mid, y: a.y), control2: CGPoint(x: mid, y: b.y))
|
||||
}
|
||||
fill.closeSubpath(); area.addPath(fill)
|
||||
}
|
||||
series.line.path = line
|
||||
series.points.path = dots
|
||||
@@ -164,9 +175,9 @@ struct NativePanelCurve: NSViewRepresentable {
|
||||
let path = CGMutablePath(); path.move(to: CGPoint(x: x, y: 0)); path.addLine(to: CGPoint(x: x, y: bounds.height)); hoverLine.path = path
|
||||
for series in input.frame.series.indices {
|
||||
guard series < (input.visibleSeriesCount ?? input.frame.series.count) else { continue }
|
||||
let values = input.frame.series[series]
|
||||
let values = input.stacked && plottedBands.indices.contains(series) ? plottedBands[series].upper : input.frame.series[series]
|
||||
guard values.indices.contains(index), let value = values[index], value.isFinite else { continue }
|
||||
let scale = input.scales[min(series, input.scales.count - 1)]
|
||||
let scale = input.scales[input.stacked ? 0 : min(series, input.scales.count - 1)]
|
||||
let y = bounds.height * (1 - min(1, max(0, value / (scale.isFinite && scale > 0 ? scale : 1))))
|
||||
hoverDots[series].path = CGPath(ellipseIn: CGRect(x: x - 2.5, y: y - 2.5, width: 5, height: 5), transform: nil)
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ nonisolated enum PanelCurveGeometry {
|
||||
struct Sample {
|
||||
let date: Date
|
||||
let value: Double
|
||||
var lower: Double = 0
|
||||
}
|
||||
|
||||
static func allowedGap(at index: Int, intervals: [TimeInterval], fallback: TimeInterval) -> TimeInterval {
|
||||
@@ -12,7 +13,7 @@ nonisolated enum PanelCurveGeometry {
|
||||
return interval.isFinite && interval > 0 ? max(5, interval * 2) : fallback
|
||||
}
|
||||
|
||||
static func runs(dates: [Date], values: [Double?], maximumGap: TimeInterval = 5, boundaryDates: Set<Date> = [], intervals: [TimeInterval] = []) -> [[Sample]] {
|
||||
static func runs(dates: [Date], values: [Double?], maximumGap: TimeInterval = 5, boundaryDates: Set<Date> = [], intervals: [TimeInterval] = [], lowerValues: [Double?]? = nil) -> [[Sample]] {
|
||||
var result: [[Sample]] = []
|
||||
var run: [Sample] = []
|
||||
func flush() { if !run.isEmpty { result.append(run); run.removeAll(keepingCapacity: true) } }
|
||||
@@ -20,7 +21,12 @@ nonisolated enum PanelCurveGeometry {
|
||||
if index > 0 && (boundaryDates.contains(dates[index]) || dates[index].timeIntervalSince(dates[index - 1]) > allowedGap(at: index, intervals: intervals, fallback: maximumGap) || dates[index] <= dates[index - 1]) { flush() }
|
||||
// Missing values do not create vertices, but their timestamps can still carry a real break.
|
||||
guard index < values.count, let value = values[index], value.isFinite else { continue }
|
||||
run.append(Sample(date: dates[index], value: value))
|
||||
var lower = 0.0
|
||||
if let lowerValues {
|
||||
guard lowerValues.indices.contains(index), let base = lowerValues[index], base.isFinite else { continue }
|
||||
lower = base
|
||||
}
|
||||
run.append(Sample(date: dates[index], value: value, lower: lower))
|
||||
}
|
||||
flush()
|
||||
return result
|
||||
|
||||
@@ -31,6 +31,7 @@ struct PanelTrendChart: View {
|
||||
var boundaryDates: Set<Date> = []
|
||||
var intervals: [TimeInterval] = []
|
||||
var visibleSeriesCount = 1
|
||||
var stackOrder: [Int] = []
|
||||
@State private var retainedScale: Double = 1
|
||||
@State private var smallSamples = 0
|
||||
@State private var retainedSecondScale: Double = 1
|
||||
@@ -45,7 +46,22 @@ struct PanelTrendChart: View {
|
||||
intervals: intervals.count == dates.count ? intervals : Array(repeating: expectedInterval, count: dates.count),
|
||||
boundaryDates: boundaryDates)
|
||||
}
|
||||
private var maximum: Double { max(1, (first + second + third + fourth).compactMap { $0 }.filter(\.isFinite).max() ?? 1) }
|
||||
private var renderFrame: PanelCurveFrame {
|
||||
let raw = inputFrame
|
||||
guard !stackOrder.isEmpty else { return raw }
|
||||
return PanelCurveFrame(dates: raw.dates, series: stackOrder.map { index in
|
||||
raw.series.indices.contains(index) ? raw.series[index] : Array(repeating: nil, count: raw.dates.count)
|
||||
}, intervals: raw.intervals, boundaryDates: raw.boundaryDates)
|
||||
}
|
||||
private var renderColors: [Color] {
|
||||
let colors = [color, secondColor, thirdColor, fourthColor]
|
||||
return stackOrder.isEmpty ? colors : stackOrder.map { colors[min(max(0, $0), colors.count - 1)] }
|
||||
}
|
||||
private var maximum: Double {
|
||||
let values = stackOrder.isEmpty ? first + second + third + fourth
|
||||
: StackedSeries.bands(renderFrame.series, count: dates.count).last?.upper ?? []
|
||||
return max(1, values.compactMap { $0 }.filter(\.isFinite).max() ?? 1)
|
||||
}
|
||||
private var secondMaximum: Double { max(1, second.compactMap { $0 }.filter(\.isFinite).max() ?? 1) }
|
||||
private var scale: Double { max(0.0001, fixedScale ?? retainedScale) }
|
||||
private var secondaryScale: Double { max(0.0001, retainedSecondScale) }
|
||||
@@ -94,10 +110,11 @@ struct PanelTrendChart: View {
|
||||
|
||||
var body: some View {
|
||||
GeometryReader { proxy in
|
||||
NativePanelCurve(frame: inputFrame, colors: [color, secondColor, thirdColor, fourthColor],
|
||||
NativePanelCurve(frame: renderFrame, colors: renderColors,
|
||||
scales: [scale, hasSecondaryScale ? secondaryScale : scale, scale, scale],
|
||||
maximumGap: max(5, expectedInterval * 2), hoveredIndex: hoveredDate == nil ? nil : index,
|
||||
visibleSeriesCount: visibleSeriesCount, filledSeriesCount: visibleSeriesCount)
|
||||
visibleSeriesCount: stackOrder.isEmpty ? visibleSeriesCount : stackOrder.count,
|
||||
filledSeriesCount: stackOrder.isEmpty ? visibleSeriesCount : stackOrder.count, stacked: !stackOrder.isEmpty)
|
||||
.contentShape(Rectangle())
|
||||
.onContinuousHover { phase in
|
||||
switch phase {
|
||||
@@ -114,7 +131,7 @@ struct PanelTrendChart: View {
|
||||
return ChartTooltipPresentation(plot: plot, point: hoverPoint, content: AnyView(tooltip(index: index)))
|
||||
}
|
||||
}
|
||||
.frame(height: ResourceCardMetrics.plotHeight)
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
.onAppear {
|
||||
retainedScale = maximum
|
||||
retainedSecondScale = secondMaximum
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import Foundation
|
||||
|
||||
/// Additive components retain their raw values; only render boundaries are cumulative.
|
||||
nonisolated enum StackedSeries {
|
||||
struct Band {
|
||||
var lower: [Double?]
|
||||
var upper: [Double?]
|
||||
}
|
||||
|
||||
static func bands(_ components: [[Double?]], count: Int, limit: Double? = nil) -> [Band] {
|
||||
var result = components.map { _ in Band(lower: Array(repeating: nil, count: count), upper: Array(repeating: nil, count: count)) }
|
||||
guard !components.isEmpty else { return result }
|
||||
for point in 0..<count {
|
||||
var values: [Double] = []
|
||||
for component in components {
|
||||
guard component.indices.contains(point), let value = component[point], value.isFinite, value >= 0 else { break }
|
||||
values.append(value)
|
||||
}
|
||||
guard values.count == components.count else { continue }
|
||||
let total = values.reduce(0, +)
|
||||
guard total.isFinite else { continue }
|
||||
if let limit, limit.isFinite, limit > 0, total > limit + max(1, limit) * 1e-12 { continue }
|
||||
var lower = 0.0
|
||||
for (series, value) in values.enumerated() {
|
||||
result[series].lower[point] = lower
|
||||
lower += value
|
||||
result[series].upper[point] = lower
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,43 @@
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
|
||||
/// Historical visual speed tiers; they deliberately do not reproduce physical RPM.
|
||||
nonisolated struct FanRotation {
|
||||
private(set) var phase: Double = 0
|
||||
private(set) var speed: Double = 0
|
||||
private var reference: TimeInterval = 0
|
||||
|
||||
static func speed(rpm: Double?, reducedMotion: Bool) -> Double {
|
||||
guard !reducedMotion, let rpm, rpm.isFinite, rpm > 0 else { return 0 }
|
||||
switch rpm {
|
||||
case ..<2000: return 90
|
||||
case ..<4000: return 180
|
||||
case ..<6000: return 300
|
||||
default: return 450
|
||||
}
|
||||
}
|
||||
|
||||
func angle(at time: TimeInterval) -> Double {
|
||||
(phase + max(0, time - reference) * speed).truncatingRemainder(dividingBy: 360)
|
||||
}
|
||||
|
||||
mutating func update(rpm: Double?, reducedMotion: Bool, at time: TimeInterval) {
|
||||
phase = angle(at: time)
|
||||
reference = time
|
||||
speed = Self.speed(rpm: rpm, reducedMotion: reducedMotion)
|
||||
}
|
||||
}
|
||||
|
||||
struct FanSpeedIndicator: View {
|
||||
let title: Text
|
||||
let rpm: Double?
|
||||
var isActive = true
|
||||
@Environment(\.accessibilityReduceMotion) private var reduceMotion
|
||||
|
||||
var body: some View {
|
||||
HStack(spacing: 4) {
|
||||
HStack(spacing: 3) {
|
||||
FanRotor(rpm: rpm, isActive: isActive, reduceMotion: reduceMotion)
|
||||
.frame(width: 11, height: 11).accessibilityHidden(true)
|
||||
title.foregroundStyle(.secondary)
|
||||
MetricText(value: rpm.map { "\(Int($0.rounded())) RPM" } ?? "-- RPM")
|
||||
.monospacedDigit().fontWeight(.medium)
|
||||
@@ -13,3 +45,64 @@ struct FanSpeedIndicator: View {
|
||||
.font(.system(size: 9)).lineLimit(1).minimumScaleFactor(0.7)
|
||||
}
|
||||
}
|
||||
|
||||
/// Only this native icon animates; sampling updates do not create display timers.
|
||||
struct FanRotor: NSViewRepresentable {
|
||||
let rpm: Double?
|
||||
let isActive: Bool
|
||||
let reduceMotion: Bool
|
||||
|
||||
func makeNSView(context: Context) -> RotorView { RotorView() }
|
||||
func updateNSView(_ view: RotorView, context: Context) {
|
||||
view.configure(rpm: rpm, active: isActive, reducedMotion: reduceMotion)
|
||||
}
|
||||
static func dismantleNSView(_ view: RotorView, coordinator: ()) { view.stop() }
|
||||
|
||||
final class RotorView: NSImageView {
|
||||
static let animationKey = "fan.rotation"
|
||||
private var rpm: Double?
|
||||
private var active = false
|
||||
private var reducedMotion = false
|
||||
private(set) var rotation = FanRotation()
|
||||
|
||||
init() {
|
||||
super.init(frame: .zero)
|
||||
wantsLayer = true
|
||||
image = NSImage(systemSymbolName: "fanblades.fill", accessibilityDescription: nil)
|
||||
contentTintColor = .secondaryLabelColor
|
||||
imageScaling = .scaleProportionallyUpOrDown
|
||||
setAccessibilityElement(false)
|
||||
}
|
||||
required init?(coder: NSCoder) { nil }
|
||||
|
||||
func configure(rpm: Double?, active: Bool, reducedMotion: Bool) {
|
||||
self.rpm = rpm; self.active = active; self.reducedMotion = reducedMotion
|
||||
refresh()
|
||||
}
|
||||
func stop() {
|
||||
active = false; refresh()
|
||||
layer?.removeAnimation(forKey: Self.animationKey)
|
||||
}
|
||||
override func viewDidMoveToWindow() { super.viewDidMoveToWindow(); refresh() }
|
||||
|
||||
private func refresh() {
|
||||
let readable = active && window != nil ? rpm : nil
|
||||
let speed = FanRotation.speed(rpm: readable, reducedMotion: reducedMotion)
|
||||
guard speed != rotation.speed else { return }
|
||||
rotation.update(rpm: readable, reducedMotion: reducedMotion, at: CACurrentMediaTime())
|
||||
let radians = rotation.phase * .pi / 180
|
||||
CATransaction.begin(); CATransaction.setDisableActions(true)
|
||||
layer?.removeAnimation(forKey: Self.animationKey)
|
||||
layer?.transform = CATransform3DMakeRotation(radians, 0, 0, 1)
|
||||
if speed > 0 {
|
||||
let animation = CABasicAnimation(keyPath: "transform.rotation.z")
|
||||
animation.fromValue = radians; animation.toValue = radians + .pi * 2
|
||||
animation.duration = 360 / speed
|
||||
animation.repeatCount = .infinity
|
||||
animation.timingFunction = CAMediaTimingFunction(name: .linear)
|
||||
layer?.add(animation, forKey: Self.animationKey)
|
||||
}
|
||||
CATransaction.commit()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,8 +28,8 @@ struct CardField<Content: View>: View {
|
||||
|
||||
struct CardSurface: ViewModifier {
|
||||
func body(content: Content) -> some View {
|
||||
content.modifier(PanelCardBackground(radius: 10))
|
||||
.overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(.primary.opacity(0.14)))
|
||||
content.modifier(PanelCardBackground(radius: ResourceCardMetrics.radius))
|
||||
.overlay(RoundedRectangle(cornerRadius: ResourceCardMetrics.radius).strokeBorder(.primary.opacity(0.06)))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ struct ResourceCard<Chart: View, Content: View>: View {
|
||||
GeometryReader { bounds in
|
||||
ZStack(alignment: .bottomLeading) {
|
||||
chart()
|
||||
.frame(width: bounds.size.width, height: ResourceCardMetrics.plotHeight)
|
||||
.frame(width: bounds.size.width, height: bounds.size.height)
|
||||
VStack(alignment: .leading, spacing: ResourceCardMetrics.gap) {
|
||||
header
|
||||
HStack(alignment: .firstTextBaseline, spacing: 6) {
|
||||
@@ -42,7 +42,6 @@ struct ResourceCard<Chart: View, Content: View>: View {
|
||||
}
|
||||
.font(.system(size: 9))
|
||||
.padding(ResourceCardMetrics.padding)
|
||||
.padding(.bottom, ResourceCardMetrics.plotHeight - ResourceCardMetrics.padding)
|
||||
.frame(width: bounds.size.width, height: bounds.size.height, alignment: .topLeading)
|
||||
}
|
||||
.background(Color("PanelCard"))
|
||||
|
||||
@@ -6,7 +6,6 @@ nonisolated enum ResourceCardMetrics {
|
||||
static let minimumHeight: CGFloat = 176
|
||||
static let padding: CGFloat = 10
|
||||
static let radius: CGFloat = 16
|
||||
static let plotHeight: CGFloat = 48
|
||||
static let titleHeight: CGFloat = 14
|
||||
static let headlineHeight: CGFloat = 34
|
||||
static let gap: CGFloat = 4
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import SwiftUI
|
||||
|
||||
/// Four square blocks fill from bottom to top; partial blocks retain the actual fraction.
|
||||
struct SegmentedCoreBar: View {
|
||||
let value: Double?
|
||||
let color: Color
|
||||
|
||||
static func portions(_ value: Double?, count: Int = 4) -> [Double] {
|
||||
guard count > 0 else { return [] }
|
||||
let fraction = value.flatMap { $0.isFinite ? min(1, max(0, $0)) : nil } ?? 0
|
||||
return (0..<count).map { min(1, max(0, fraction * Double(count) - Double($0))) }
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
let fills = Self.portions(value)
|
||||
VStack(spacing: 2) {
|
||||
ForEach(Array(fills.indices.reversed()), id: \.self) { index in
|
||||
ZStack(alignment: .bottom) {
|
||||
Rectangle().fill(color.opacity(0.15))
|
||||
Rectangle().fill(color).frame(height: 6 * fills[index])
|
||||
}.frame(width: 6, height: 6).clipped()
|
||||
}
|
||||
}
|
||||
.accessibilityHidden(true)
|
||||
.transaction { $0.animation = nil; $0.disablesAnimations = true }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user