Files
Kymo/kymo/UI/Charts/ChartTooltipLayer.swift

38 lines
1.6 KiB
Swift

import SwiftUI
/// Charts export their plot anchor; the owning card draws the tooltip above all content.
struct ChartTooltipPresentation {
let plot: Anchor<CGRect>
let point: CGPoint
let content: AnyView
}
struct ChartTooltipPreference: PreferenceKey {
static var defaultValue: ChartTooltipPresentation? { nil }
static func reduce(value: inout ChartTooltipPresentation?, nextValue: () -> ChartTooltipPresentation?) {
if let next = nextValue() { value = next }
}
}
/// Measures the actual localized tooltip, then keeps it inside the card.
struct ChartTooltipLayer: Layout {
let point: CGPoint
var minimumY: CGFloat = 0
func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
proposal.replacingUnspecifiedDimensions()
}
func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
guard let tooltip = subviews.first else { return }
let width = min(180, max(1, bounds.width - 20))
let tooltipProposal = ProposedViewSize(width: width, height: nil)
let size = tooltip.sizeThatFits(tooltipProposal)
let x = min(max(10, point.x + 12), max(10, bounds.width - size.width - 10))
let below = point.y + 10
let preferredY = below + size.height <= bounds.height - 10 ? below : point.y - size.height - 10
let y = min(max(max(10, minimumY), preferredY), max(10, bounds.height - size.height - 10))
tooltip.place(at: CGPoint(x: bounds.minX + x, y: bounds.minY + y), anchor: .topLeading, proposal: tooltipProposal)
}
}