77 lines
2.8 KiB
Swift
77 lines
2.8 KiB
Swift
import SwiftUI
|
|
|
|
/// The design's tooltip: `raised` surface, text-5 border, radius 2, Sans 12/1.5, no arrow, no shadow.
|
|
/// Name the current state in amber with `Tooltip.stated`, then say what a click does.
|
|
public struct Tooltip: View {
|
|
var text: Text
|
|
|
|
public init(_ text: Text) {
|
|
self.text = text
|
|
}
|
|
|
|
public init(_ string: String) {
|
|
text = Text(string)
|
|
}
|
|
|
|
/// "Lead: *state* — rest", with the state word in amber.
|
|
public static func stated(_ lead: String, _ state: String, _ rest: String) -> Text {
|
|
Text(lead).foregroundColor(Palette.text2) + Text(state).foregroundColor(Palette.amber) + Text(rest).foregroundColor(Palette.text2)
|
|
}
|
|
|
|
public var body: some View {
|
|
text
|
|
.typeRole(Typography.tooltip)
|
|
.foregroundStyle(Palette.text2)
|
|
.multilineTextAlignment(.leading)
|
|
.fixedSize(horizontal: false, vertical: true)
|
|
.padding(.horizontal, 10)
|
|
.padding(.vertical, 8)
|
|
.frame(maxWidth: Metrics.tooltipMaxWidth, alignment: .leading)
|
|
.fixedSize()
|
|
.background(Palette.raised, in: RoundedRectangle(cornerRadius: Metrics.radiusSmall))
|
|
.overlay(RoundedRectangle(cornerRadius: Metrics.radiusSmall).strokeBorder(Palette.tooltipBorder, lineWidth: Metrics.hairline))
|
|
}
|
|
}
|
|
|
|
struct TooltipModifier: ViewModifier {
|
|
var text: Text
|
|
var edge: HorizontalAlignment
|
|
@State private var isShown = false
|
|
@State private var pending: Task<Void, Never>?
|
|
|
|
func body(content: Content) -> some View {
|
|
content
|
|
.onHover { inside in
|
|
pending?.cancel()
|
|
if inside {
|
|
pending = Task { @MainActor in
|
|
try? await Task.sleep(for: Metrics.tooltipDelay)
|
|
if !Task.isCancelled { isShown = true }
|
|
}
|
|
} else {
|
|
isShown = false
|
|
}
|
|
}
|
|
.simultaneousGesture(TapGesture().onEnded { pending?.cancel(); isShown = false })
|
|
.overlay(alignment: Alignment(horizontal: edge, vertical: .bottom)) {
|
|
if isShown {
|
|
Tooltip(text)
|
|
.alignmentGuide(.bottom) { $0[.top] - 8 }
|
|
.allowsHitTesting(false)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
extension View {
|
|
/// Shows a design tooltip 350ms after the pointer rests on the view, 8pt below it.
|
|
/// The host must sit above its neighbours (`zIndex`) so the tip is not drawn under them.
|
|
public func tip(_ text: Text, edge: HorizontalAlignment = .leading) -> some View {
|
|
modifier(TooltipModifier(text: text, edge: edge))
|
|
}
|
|
|
|
public func tip(_ string: String, edge: HorizontalAlignment = .leading) -> some View {
|
|
tip(Text(string), edge: edge)
|
|
}
|
|
}
|