Branchwell

Graphley / app · graphley.ai / Sources / AnalyticsUI / Components.swift

Raw 32.3 KB on d80f63aea8f10988b2fe7107ba87bf71b30173fb
1import SwiftUI
2#if os(macOS)
3import AppKit
4#else
5import UIKit
6#endif
7
8// Graphley's own controls (design/DESIGN.md, section 2). The window, sidebar container, toolbar,
9// menus, sheets and confirmation dialogs stay native; everything inside the content uses these.
10
11// MARK: Buttons
12
13public struct TideButtonStyle: ButtonStyle {
14 public enum Kind { case primary, secondary, quiet, destructive, quietDestructive }
15 public enum Size { case small, regular, large }
16 let kind: Kind, size: Size
17 public init(_ kind: Kind = .secondary, size: Size = .regular) { self.kind = kind; self.size = size }
18
19 public func makeBody(configuration c: Configuration) -> some View { Styled(configuration: c, kind: kind, size: size) }
20
21 struct Styled: View {
22 let configuration: Configuration, kind: Kind, size: Size
23 @Environment(\.isEnabled) private var enabled
24 @State private var hover = false
25
26 var body: some View {
27 let pressed = configuration.isPressed
28 configuration.label
29 .font(Tide.sans(fontSize, .semibold))
30 .labelStyle(TideLabelStyle())
31 .lineLimit(1)
32 .padding(.horizontal, size == .small ? 10 : size == .large ? 18 : 14)
33 .frame(minHeight: height)
34 .foregroundStyle(fg(pressed))
35 .background(bg(pressed), in: RoundedRectangle(cornerRadius: 8))
36 .overlay(RoundedRectangle(cornerRadius: 8).strokeBorder(border(pressed), lineWidth: 1))
37 .contentShape(RoundedRectangle(cornerRadius: 8))
38 .onHover { hover = $0 }
39 .animation(.easeOut(duration: 0.15), value: hover)
40 .animation(.easeOut(duration: 0.1), value: pressed)
41 }
42 var fontSize: CGFloat { Tide.phone ? 16 : size == .small ? 12 : size == .large ? 14 : 13 }
43 var height: CGFloat { Tide.phone ? 44 : size == .small ? 24 : size == .large ? 36 : 30 }
44
45 func fg(_ pressed: Bool) -> Color {
46 guard enabled else { return Tide.muted }
47 switch kind {
48 case .primary: return Tide.accentInk
49 case .secondary: return Tide.ink
50 case .quiet: return Tide.accent
51 case .destructive: return Tide.onDown
52 case .quietDestructive: return Tide.downText
53 }
54 }
55 func bg(_ pressed: Bool) -> Color {
56 switch kind {
57 case .primary: return !enabled ? Tide.sunk : pressed ? Tide.fillPressed : hover ? Tide.fillHover : Tide.fill
58 case .secondary: return !enabled ? Tide.surface : pressed ? Tide.sunk : hover ? Tide.surface2 : Tide.surface
59 case .quiet: return !enabled ? .clear : pressed ? Tide.accentTint2 : hover ? Tide.accentTint : .clear
60 case .destructive: return !enabled ? Tide.sunk : pressed ? Tide.downPressed : hover ? Tide.downHover : Tide.down
61 case .quietDestructive: return !enabled ? .clear : (pressed || hover) ? Tide.down.opacity(0.12) : .clear
62 }
63 }
64 func border(_ pressed: Bool) -> Color {
65 switch kind {
66 case .secondary: return !enabled ? Tide.line : (pressed || hover) ? Tide.accent : Tide.line2
67 case .quietDestructive: return pressed ? Tide.down : .clear
68 default: return .clear
69 }
70 }
71 }
72}
73
74/// Icon, 6 pt gap, title. Keeps SF Symbols at 13 pt next to button text.
75struct TideLabelStyle: LabelStyle {
76 func makeBody(configuration: Configuration) -> some View {
77 HStack(spacing: 6) { configuration.icon.font(.system(size: 12, weight: .semibold)); configuration.title }
78 }
79}
80
81public extension ButtonStyle where Self == TideButtonStyle {
82 static var tidePrimary: TideButtonStyle { TideButtonStyle(.primary) }
83 static var tideSecondary: TideButtonStyle { TideButtonStyle(.secondary) }
84 static var tideQuiet: TideButtonStyle { TideButtonStyle(.quiet) }
85 static func tide(_ kind: TideButtonStyle.Kind, size: TideButtonStyle.Size = .regular) -> TideButtonStyle { TideButtonStyle(kind, size: size) }
86}
87
88/// 28×28 glyph button for toolbars and rows. Always give it `.help` and an accessibility label.
89public struct IconButtonStyle: ButtonStyle {
90 public init() {}
91 public func makeBody(configuration c: Configuration) -> some View { Styled(configuration: c) }
92 struct Styled: View {
93 let configuration: Configuration
94 @Environment(\.isEnabled) private var enabled
95 @State private var hover = false
96 var body: some View {
97 configuration.label
98 .labelStyle(.iconOnly)
99 .font(.system(size: 14, weight: .medium))
100 .foregroundStyle(!enabled ? Tide.line2 : hover ? Tide.ink : Tide.muted)
101 .frame(width: Tide.phone ? 44 : 28, height: Tide.phone ? 44 : 28)
102 .background(configuration.isPressed ? Tide.sunk : hover && enabled ? Tide.surface2 : .clear, in: RoundedRectangle(cornerRadius: 7))
103 .contentShape(RoundedRectangle(cornerRadius: 7))
104 .onHover { hover = $0 }
105 .animation(.easeOut(duration: 0.15), value: hover)
106 }
107 }
108}
109
110public extension ButtonStyle where Self == IconButtonStyle { static var tideIcon: IconButtonStyle { IconButtonStyle() } }
111
112/// Copies `text`, then shows "Copied" for 1.5 seconds.
113public struct CopyButton: View {
114 let text: String, label: String
115 @State private var copied = false
116 public init(_ text: String, label: String = "Copy") { self.text = text; self.label = label }
117 public var body: some View {
118 Button {
119 Clipboard.copy(text)
120 copied = true
121 AccessibilityNotification.Announcement("Copied").post()
122 Task { try? await Task.sleep(for: .seconds(1.5)); copied = false }
123 } label: {
124 ZStack {
125 Label(label, systemImage: "doc.on.doc").opacity(copied ? 0 : 1)
126 Label("Copied", systemImage: "checkmark").foregroundStyle(Tide.up).opacity(copied ? 1 : 0)
127 }
128 }
129 .buttonStyle(.tide(.secondary, size: .small))
130 .help("Copy to the clipboard")
131 }
132}
133
134public enum Clipboard {
135 public static func copy(_ text: String) {
136 #if os(macOS)
137 NSPasteboard.general.clearContents(); NSPasteboard.general.setString(text, forType: .string)
138 #else
139 UIPasteboard.general.string = text
140 #endif
141 }
142}
143
144// MARK: Toggle
145
146/// 32×18 switch in Tide colors (Mac). The iPhone keeps the native switch with the accent tint.
147public struct TideToggleStyle: ToggleStyle {
148 public init() {}
149 public func makeBody(configuration c: Configuration) -> some View {
150 HStack(alignment: .firstTextBaseline) {
151 c.label
152 Spacer(minLength: 12)
153 Switch(isOn: c.$isOn)
154 }
155 .contentShape(Rectangle())
156 .onTapGesture { Switch.flip(c.$isOn) }
157 }
158 struct Switch: View {
159 @Binding var isOn: Bool
160 @Environment(\.isEnabled) private var enabled
161 @Environment(\.accessibilityReduceMotion) private var reduceMotion
162 static func flip(_ binding: Binding<Bool>) { binding.wrappedValue.toggle() }
163 var body: some View {
164 ZStack(alignment: isOn ? .trailing : .leading) {
165 Capsule().fill(isOn ? Tide.fill : Tide.control).frame(width: 32, height: 18)
166 Circle().fill(Tide.knob).frame(width: 14, height: 14).padding(2).shadow(color: .black.opacity(0.18), radius: 0.5, y: 1)
167 }
168 .opacity(enabled ? 1 : 0.45)
169 .animation(reduceMotion ? nil : .spring(duration: 0.18), value: isOn)
170 .alignmentGuide(.firstTextBaseline) { $0[VerticalAlignment.center] + 4 }
171 .accessibilityHidden(true)
172 }
173 }
174}
175
176/// Settings row: title, description, switch on the trailing edge. The whole row toggles.
177public struct ToggleRow: View {
178 let title: String, detail: String
179 @Binding var isOn: Bool
180 public init(_ title: String, detail: String, isOn: Binding<Bool>) { self.title = title; self.detail = detail; _isOn = isOn }
181 public var body: some View {
182 #if os(macOS)
183 Toggle(isOn: $isOn) { RowText(title: title, detail: detail) }
184 .toggleStyle(TideToggleStyle())
185 .accessibilityElement(children: .ignore)
186 .accessibilityLabel(title).accessibilityHint(detail)
187 .accessibilityValue(isOn ? "On" : "Off")
188 .accessibilityAddTraits(.isButton)
189 .accessibilityAction { isOn.toggle() }
190 #else
191 Toggle(isOn: $isOn) { RowText(title: title, detail: detail) }.tint(Tide.accent)
192 #endif
193 }
194}
195
196struct RowText: View {
197 let title: String, detail: String
198 var body: some View {
199 VStack(alignment: .leading, spacing: 3) {
200 Text(title).font(Tide.rowTitle).foregroundStyle(Tide.ink)
201 if !detail.isEmpty {
202 Text(detail).font(Tide.secondary).foregroundStyle(Tide.muted).frame(maxWidth: 440, alignment: .leading)
203 .fixedSize(horizontal: false, vertical: true)
204 }
205 }
206 }
207}
208
209// MARK: Text field
210
211public struct TideField: View {
212 let label: String, placeholder: String, help: String?, error: String?, monospaced: Bool
213 @Binding var text: String
214 @FocusState private var focused: Bool
215 @State private var hover = false
216 public init(_ label: String, text: Binding<String>, placeholder: String = "", help: String? = nil, error: String? = nil, monospaced: Bool = false) {
217 self.label = label; _text = text; self.placeholder = placeholder; self.help = help; self.error = error; self.monospaced = monospaced
218 }
219 public var body: some View {
220 VStack(alignment: .leading, spacing: 6) {
221 Text(label).font(Tide.fieldLabel).foregroundStyle(Tide.ink)
222 TextField(label, text: $text, prompt: Text(placeholder).foregroundStyle(Tide.muted))
223 .textFieldStyle(.plain)
224 .labelsHidden()
225 .font(monospaced ? Tide.figure(13) : Tide.sans(13))
226 .autocorrectionDisabled()
227 .focused($focused)
228 .padding(.horizontal, 10)
229 .frame(height: Tide.phone ? 44 : 30)
230 .background(Tide.ground, in: RoundedRectangle(cornerRadius: 8))
231 .overlay(RoundedRectangle(cornerRadius: 8).strokeBorder(borderColor, lineWidth: focused || error != nil ? 2 : 1))
232 .onHover { hover = $0 }
233 .focusEffectDisabled()
234 if let error {
235 Label(error, systemImage: "exclamationmark.circle.fill").font(Tide.caption).foregroundStyle(Tide.downText)
236 .fixedSize(horizontal: false, vertical: true)
237 } else if let help {
238 Text(help).font(Tide.caption).foregroundStyle(Tide.muted).fixedSize(horizontal: false, vertical: true)
239 }
240 }
241 }
242 var borderColor: Color { error != nil ? Tide.down : focused ? Tide.accent : hover ? Tide.muted : Tide.control }
243}
244
245// MARK: Range selector
246
247/// Pill segmented control for 7 / 30 / 90 days. Replaces the stock segmented picker.
248public struct RangeSelector: View {
249 @Binding var selection: Int
250 let options: [Int]
251 @Namespace private var ns
252 @Environment(\.accessibilityReduceMotion) private var reduceMotion
253 public init(selection: Binding<Int>, options: [Int] = [7, 30, 90]) { _selection = selection; self.options = options }
254 public var body: some View {
255 HStack(spacing: 2) {
256 ForEach(options, id: \.self) { n in
257 Segment(title: "\(n) days", selected: selection == n, ns: ns) {
258 withAnimation(reduceMotion ? nil : .spring(duration: 0.18)) { selection = n }
259 }
260 }
261 }
262 .padding(3)
263 .frame(height: Tide.phone ? nil : 30)
264 .background(Tide.sunk, in: Capsule())
265 .overlay(Capsule().strokeBorder(Tide.line))
266 .accessibilityRepresentation {
267 Picker("Date range", selection: $selection) { ForEach(options, id: \.self) { Text("Last \($0) days").tag($0) } }
268 }
269 }
270 struct Segment: View {
271 let title: String, selected: Bool, ns: Namespace.ID, action: () -> Void
272 @State private var hover = false
273 @State private var pressed = false
274 var body: some View {
275 Button(action: action) {
276 // Touch sizes on iPhone and iPad, pointer sizes on the Mac.
277 Text(title).font(Tide.sans(Tide.phone ? 14 : 12.5, .medium))
278 .foregroundStyle(selected || hover ? Tide.ink : Tide.phone ? Tide.muted : Tide.pillText)
279 .padding(.horizontal, Tide.phone ? 14 : 11).frame(height: Tide.phone ? 34 : 24)
280 .background {
281 if selected {
282 Capsule().fill(Tide.pillSelected).shadow(color: Color(light: 0x0E2830, dark: 0x000000).opacity(0.18), radius: 1, y: 1)
283 .matchedGeometryEffect(id: "range", in: ns)
284 } else if hover && !Tide.phone {
285 Capsule().fill(Tide.surface2)
286 }
287 }
288 .animation(.easeOut(duration: 0.15), value: hover)
289 .contentShape(Capsule())
290 }
291 .buttonStyle(.plain)
292 .onHover { hover = $0 }
293 }
294 }
295}
296
297// MARK: Refresh pill
298
299/// What the top bar's status says. Checked in this order: refreshing, failed, stale, fresh, then
300/// `dataThrough` (numbers in the store but no refresh recorded) and `never` (an empty store).
301public enum RefreshPillStatus: Equatable {
302 case never, dataThrough(String), fresh(String), stale(String), refreshing, failed(Int)
303}
304
305/// "● Updated 9:01 PM ┊ ↻" in one capsule built like RangeSelector: 30 pt tall, 3 pt inset,
306/// `sunk` fill and a `line` border. The refresh circle shares its centre with the rounded end.
307public struct RefreshPill: View {
308 let status: RefreshPillStatus
309 let refresh: () -> Void
310 let openSources: () -> Void
311 /// The label shown when the refresh started, so the pill never shrinks mid-refresh.
312 @State private var heldLabel = ""
313 public init(status: RefreshPillStatus, refresh: @escaping () -> Void, openSources: @escaping () -> Void) {
314 self.status = status; self.refresh = refresh; self.openSources = openSources
315 }
316
317 public var body: some View {
318 HStack(spacing: 0) {
319 statusSegment
320 Rectangle().fill(Tide.line2).frame(width: 1, height: 14)
321 RefreshCircle(turning: status == .refreshing, action: refresh)
322 }
323 .padding(.leading, 3)
324 .frame(height: 30)
325 .background(Tide.sunk, in: Capsule())
326 .overlay(Capsule().strokeBorder(Tide.line))
327 .fixedSize()
328 .accessibilityElement(children: .contain)
329 .accessibilityLabel("Refresh status")
330 .onChange(of: status) { old, new in
331 if new == .refreshing { heldLabel = Self.label(old) }
332 if old == .refreshing { announce(new) }
333 }
334 }
335
336 @ViewBuilder var statusSegment: some View {
337 if case .failed = status {
338 Button(action: openSources) { statusContent.modifier(SegmentHover()) }
339 .buttonStyle(.plain)
340 .help("Open Sources & keys")
341 .accessibilityLabel(Self.label(status))
342 .accessibilityHint("Opens Sources and keys")
343 } else {
344 statusContent
345 .accessibilityElement(children: .ignore)
346 .accessibilityLabel(spoken)
347 .help(tooltip)
348 }
349 }
350
351 var statusContent: some View {
352 HStack(spacing: 6) {
353 Circle().fill(dot).frame(width: 6, height: 6).accessibilityHidden(true)
354 ZStack(alignment: .leading) {
355 // The label from before the refresh holds the width, so the pill never shrinks mid-refresh.
356 Text(heldLabel).hidden()
357 Text(Self.label(status)).foregroundStyle(isFailed ? Tide.downText : Tide.pillText)
358 .contentTransition(.opacity)
359 }
360 .font(Tide.sans(12.5)).monospacedDigit().lineLimit(1)
361 .animation(.easeOut(duration: 0.15), value: status)
362 }
363 .padding(.leading, 11).padding(.trailing, 10)
364 .frame(height: 24)
365 .contentShape(Capsule())
366 }
367
368 var isFailed: Bool { if case .failed = status { true } else { false } }
369
370 var dot: Color {
371 switch status {
372 case .fresh: Tide.up
373 case .stale: Tide.attention
374 case .failed: Tide.down
375 case .never, .dataThrough: Tide.muted
376 case .refreshing: Tide.line2
377 }
378 }
379
380 static func label(_ status: RefreshPillStatus) -> String {
381 switch status {
382 case .never: "Not refreshed yet"
383 case .dataThrough(let day): "Data through \(day)"
384 case .fresh(let when), .stale(let when): "Updated \(when)"
385 case .refreshing: "Refreshing…"
386 case .failed(let n): n == 1 ? "1 source needs attention" : "\(n) sources need attention"
387 }
388 }
389
390 var spoken: String {
391 switch status {
392 case .fresh(let when): "Updated at \(when)"
393 case .stale(let when): "Updated \(when). Numbers may be out of date."
394 case .refreshing: "Refreshing"
395 default: Self.label(status)
396 }
397 }
398
399 var tooltip: String {
400 switch status {
401 case .stale: "These numbers may be out of date. Refresh now with ⌘R."
402 case .never, .dataThrough: "Refresh now with ⌘R."
403 default: "Graphley refreshes on its own every day."
404 }
405 }
406
407 func announce(_ status: RefreshPillStatus) {
408 let text = isFailed ? Self.label(status) : "Numbers updated"
409 AccessibilityNotification.Announcement(text).post()
410 }
411}
412
413/// The 24 pt refresh circle at the pill's right end. The arrow turns while refreshing and
414/// finishes its turn before it rests, so it never snaps.
415struct RefreshCircle: View {
416 let turning: Bool, action: () -> Void
417 @State private var hover = false
418 @State private var startedAt: Date?
419 @Environment(\.accessibilityReduceMotion) private var reduceMotion
420 static let period = 0.9
421
422 var body: some View {
423 Button(action: action) {
424 TimelineView(.animation(paused: startedAt == nil)) { context in
425 Image(systemName: "arrow.clockwise")
426 .font(.system(size: 12, weight: .medium))
427 .foregroundStyle(turning ? Tide.accent : hover ? Tide.ink : Tide.pillText)
428 // The symbol's ink sits 1 pt low in its frame (measured); lift it so it centres on the pill's end.
429 .offset(y: -1)
430 .frame(width: 24, height: 24)
431 .rotationEffect(.degrees(angle(at: context.date)))
432 }
433 .background(Circle().fill(hover && !turning ? Tide.surface2 : .clear))
434 .frame(width: 30, height: 30)
435 .contentShape(Rectangle())
436 }
437 .buttonStyle(PressFill())
438 .disabled(turning)
439 .onHover { hover = $0 }
440 .animation(.easeOut(duration: 0.15), value: hover)
441 .help("Refresh now (⌘R)")
442 .accessibilityLabel(turning ? "Refreshing" : "Refresh now")
443 .onChange(of: turning, initial: true) { _, now in
444 if now && !reduceMotion && startedAt == nil { startedAt = .now }
445 if !now, let start = startedAt {
446 // Finish the current revolution, then rest at 0°.
447 let elapsed = Date.now.timeIntervalSince(start)
448 let left = Self.period - elapsed.truncatingRemainder(dividingBy: Self.period)
449 Task { try? await Task.sleep(for: .seconds(left)); if !turning { startedAt = nil } }
450 }
451 }
452 }
453
454 func angle(at date: Date) -> Double {
455 guard let start = startedAt else { return 0 }
456 return date.timeIntervalSince(start) / Self.period * 360
457 }
458}
459
460/// Pressed state for the refresh circle: a `line` fill on the 24 pt circle.
461struct PressFill: ButtonStyle {
462 func makeBody(configuration c: Configuration) -> some View {
463 c.label.background(Circle().fill(c.isPressed ? Tide.line : .clear).frame(width: 24, height: 24))
464 }
465}
466
467/// Hover fill for the failed status segment.
468struct SegmentHover: ViewModifier {
469 @State private var hover = false
470 func body(content: Content) -> some View {
471 content.background(Capsule().fill(hover ? Tide.surface2 : .clear))
472 .onHover { hover = $0 }
473 .animation(.easeOut(duration: 0.15), value: hover)
474 }
475}
476
477// MARK: Pill
478
479public struct StatusPill: View {
480 public enum Kind { case ok, attention, error, info, neutral }
481 let text: String, kind: Kind
482 public init(_ text: String, _ kind: Kind) { self.text = text; self.kind = kind }
483 public var body: some View {
484 let (bg, fg) = colors
485 HStack(spacing: 6) { Circle().fill(fg).frame(width: 6, height: 6); Text(text).font(Tide.sans(11.5, .semibold)) }
486 .foregroundStyle(fg)
487 .padding(.horizontal, 8).frame(height: 20)
488 .background(bg, in: Capsule())
489 .accessibilityElement(children: .ignore).accessibilityLabel(text)
490 }
491 var colors: (Color, Color) {
492 switch kind {
493 case .ok: (Color(light: 0xDAE8E2, dark: 0x1E423F), Color(light: 0x276E51, dark: 0x5CC594))
494 case .attention: (Color(light: 0xF1EADE, dark: 0x373C34), Color(light: 0x755B36, dark: 0xE3A45A))
495 case .error: (Color(light: 0xEDE2DE, dark: 0x373739), Color(light: 0x984A38, dark: 0xE58A72))
496 case .info: (Color(light: 0xD8E6E9, dark: 0x1F3F4A), Color(light: 0x1D6E8A, dark: 0x5DB6D2))
497 case .neutral: (Color(light: 0xE0E7E6, dark: 0x263C41), Color(light: 0x4A6566, dark: 0x88A2A2))
498 }
499 }
500}
501
502// MARK: Card, heading, code, disclosure, empty state
503
504public struct TideCard<Content: View, Accessory: View>: View {
505 let title: String?, subtitle: String?, icon: String?, padding: CGFloat
506 let accessory: Accessory
507 let content: Content
508 public init(_ title: String? = nil, subtitle: String? = nil, icon: String? = nil, padding: CGFloat = 16,
509 @ViewBuilder accessory: () -> Accessory, @ViewBuilder content: () -> Content) {
510 self.title = title; self.subtitle = subtitle; self.icon = icon; self.padding = padding; self.accessory = accessory(); self.content = content()
511 }
512 public var body: some View {
513 VStack(alignment: .leading, spacing: 12) {
514 if title != nil || subtitle != nil {
515 HStack(alignment: .top, spacing: 10) {
516 if let icon {
517 Image(systemName: icon).font(.system(size: 14, weight: .medium)).foregroundStyle(Tide.accent)
518 .frame(width: 28, height: 28).background(Tide.sunk, in: RoundedRectangle(cornerRadius: 7))
519 }
520 VStack(alignment: .leading, spacing: 3) {
521 if let title { Text(title).font(Tide.cardTitle).foregroundStyle(Tide.ink) }
522 if let subtitle { Text(subtitle).font(Tide.secondary).foregroundStyle(Tide.muted).fixedSize(horizontal: false, vertical: true) }
523 }
524 .padding(.top, icon == nil ? 0 : 5)
525 Spacer(minLength: 8)
526 accessory.padding(.top, icon == nil ? 0 : 4)
527 }
528 }
529 content
530 }
531 .padding(padding)
532 .frame(maxWidth: .infinity, alignment: .leading)
533 .background(Tide.surface, in: RoundedRectangle(cornerRadius: Tide.phone ? 16 : 12))
534 .overlay(RoundedRectangle(cornerRadius: Tide.phone ? 16 : 12).strokeBorder(Tide.line))
535 }
536}
537
538public extension TideCard where Accessory == EmptyView {
539 init(_ title: String? = nil, subtitle: String? = nil, icon: String? = nil, padding: CGFloat = 16, @ViewBuilder content: () -> Content) {
540 self.init(title, subtitle: subtitle, icon: icon, padding: padding, accessory: { EmptyView() }, content: content)
541 }
542}
543
544/// Divider between rows inside a card.
545public struct RowDivider: View {
546 public init() {}
547 public var body: some View { Rectangle().fill(Tide.line).frame(height: 1) }
548}
549
550public struct ScreenHeading<Trailing: View, Footnote: View>: View {
551 let title: String, subtitle: String?
552 let link: (title: String, url: URL)?
553 let trailing: Trailing
554 let footnote: Footnote
555 public init(_ title: String, subtitle: String? = nil, link: (title: String, url: URL)? = nil,
556 @ViewBuilder trailing: () -> Trailing, @ViewBuilder footnote: () -> Footnote) {
557 self.title = title; self.subtitle = subtitle; self.link = link; self.trailing = trailing(); self.footnote = footnote()
558 }
559 public var body: some View {
560 HStack(alignment: .bottom, spacing: 12) {
561 VStack(alignment: .leading, spacing: 4) {
562 Text(title).font(Tide.screenTitle).tracking(-0.3).foregroundStyle(Tide.ink).accessibilityAddTraits(.isHeader)
563 if subtitle != nil || link != nil { subtitleText.fixedSize(horizontal: false, vertical: true) }
564 footnote.padding(.top, 4)
565 }
566 Spacer(minLength: 0)
567 trailing
568 }
569 .frame(maxWidth: .infinity, alignment: .leading)
570 .padding(.bottom, 6)
571 }
572
573 /// The subtitle, with an optional link at its end ("… · protomota.com ↗").
574 var subtitleText: some View {
575 // En spaces around "·" so the separator doesn't read as a word space.
576 let sep = "\u{2002}·\u{2002}"
577 var text = AttributedString((subtitle ?? "").replacingOccurrences(of: " · ", with: sep))
578 text.foregroundColor = Tide.muted
579 if let link {
580 if subtitle != nil { var dot = AttributedString(sep); dot.foregroundColor = Tide.muted; text += dot }
581 var l = AttributedString("\(link.title) ↗")
582 l.link = link.url
583 l.foregroundColor = Tide.accent
584 l.font = Tide.sans(Tide.phone ? 14 : 12.5, .medium)
585 text += l
586 }
587 return Text(text).font(Tide.secondary).tint(Tide.accent)
588 .help(link.map { "Open \($0.title)" } ?? "")
589 }
590}
591
592public extension ScreenHeading where Footnote == EmptyView {
593 init(_ title: String, subtitle: String? = nil, link: (title: String, url: URL)? = nil, @ViewBuilder trailing: () -> Trailing) {
594 self.init(title, subtitle: subtitle, link: link, trailing: trailing) { EmptyView() }
595 }
596}
597
598public extension ScreenHeading where Trailing == EmptyView, Footnote == EmptyView {
599 init(_ title: String, subtitle: String? = nil, link: (title: String, url: URL)? = nil) {
600 self.init(title, subtitle: subtitle, link: link) { EmptyView() } footnote: { EmptyView() }
601 }
602}
603
604/// Selectable command or prompt with a Copy button in its corner.
605public struct CopyBlock: View {
606 let text: String, wraps: Bool
607 @Environment(\.colorScheme) private var scheme
608 public init(_ text: String, wraps: Bool = false) { self.text = text; self.wraps = wraps }
609 public var body: some View {
610 HStack(alignment: .top, spacing: 10) {
611 Group {
612 if wraps {
613 Text(text).fixedSize(horizontal: false, vertical: true).frame(maxWidth: .infinity, alignment: .leading)
614 } else {
615 ScrollView(.horizontal, showsIndicators: false) { Text(text).fixedSize() }
616 }
617 }
618 .font(Tide.code).foregroundStyle(Tide.ink).textSelection(.enabled)
619 .padding(.top, 3)
620 CopyButton(text)
621 }
622 .padding(.vertical, 10).padding(.horizontal, 12)
623 .background(scheme == .dark ? Tide.sunk : Tide.ground, in: RoundedRectangle(cornerRadius: 8))
624 .overlay(RoundedRectangle(cornerRadius: 8).strokeBorder(Tide.line))
625 }
626}
627
628/// "› Or let your agent do it": a quiet disclosure with a rotating chevron.
629public struct TideDisclosure<Content: View>: View {
630 let title: String
631 @Binding var isOpen: Bool
632 let content: Content
633 public init(_ title: String, isOpen: Binding<Bool>, @ViewBuilder content: () -> Content) { self.title = title; _isOpen = isOpen; self.content = content() }
634 public var body: some View {
635 VStack(alignment: .leading, spacing: 10) {
636 Button { withAnimation(.easeOut(duration: 0.2)) { isOpen.toggle() } } label: {
637 HStack(spacing: 6) {
638 Image(systemName: "chevron.right").font(.system(size: 10, weight: .bold)).rotationEffect(.degrees(isOpen ? 90 : 0))
639 Text(title).font(Tide.sans(13, .medium))
640 }
641 .foregroundStyle(Tide.accent).contentShape(Rectangle())
642 }
643 .buttonStyle(.plain)
644 .accessibilityValue(isOpen ? "Expanded" : "Collapsed")
645 if isOpen { content.transition(.opacity) }
646 }
647 }
648}
649
650public struct EmptyState<Actions: View>: View {
651 let title: String?, message: String
652 let actions: Actions
653 public init(_ title: String? = nil, message: String, @ViewBuilder actions: () -> Actions) { self.title = title; self.message = message; self.actions = actions() }
654 public var body: some View {
655 HStack(alignment: .top, spacing: 14) {
656 // Titled empty states carry the brand mark, so a first launch looks like Graphley, not a blank form.
657 if title != nil { TideMark(size: 40) }
658 VStack(alignment: .leading, spacing: 6) {
659 if let title { Text(title).font(Tide.cardTitle).foregroundStyle(Tide.ink) }
660 Text(message).font(Tide.secondary).foregroundStyle(Tide.ink2).frame(maxWidth: 460, alignment: .leading).fixedSize(horizontal: false, vertical: true)
661 HStack(spacing: 8) { actions }.padding(.top, 6)
662 }
663 }
664 .padding(title == nil ? 0 : 4)
665 .frame(maxWidth: .infinity, alignment: .leading)
666 }
667}
668
669public extension EmptyState where Actions == EmptyView {
670 init(_ title: String? = nil, message: String) { self.init(title, message: message) { EmptyView() } }
671}
672
673/// A small button that copies a ready-made prompt for the user's agent.
674public struct PromptChip: View {
675 let prompt: String
676 @State private var copied = false
677 public init(_ prompt: String) { self.prompt = prompt }
678 public var body: some View {
679 Button {
680 Clipboard.copy(prompt); copied = true
681 Task { try? await Task.sleep(for: .seconds(1.5)); copied = false }
682 } label: {
683 Label(copied ? "Copied" : "“\(prompt)”", systemImage: copied ? "checkmark" : "doc.on.doc")
684 .lineLimit(1).truncationMode(.tail)
685 }
686 .buttonStyle(.tide(.secondary, size: .small))
687 .help("Copy this prompt for your agent")
688 }
689}
690
691/// "Try: “…” Copy": a quiet, wrapping prompt line for under a screen's subtitle.
692public struct PromptLine: View {
693 let prompt: String
694 @State private var copied = false
695 @State private var hover = false
696 public init(_ prompt: String) { self.prompt = prompt }
697 public var body: some View {
698 HStack(alignment: .firstTextBaseline, spacing: 10) {
699 Text("Try: “\(prompt)”").foregroundStyle(Tide.muted)
700 .font(Tide.secondary).textSelection(.enabled)
701 .fixedSize(horizontal: false, vertical: true)
702 Button {
703 Clipboard.copy(prompt); copied = true
704 AccessibilityNotification.Announcement("Copied").post()
705 Task { try? await Task.sleep(for: .seconds(1.5)); copied = false }
706 } label: {
707 // Everything sits on the prompt's text baseline, so "Copy" lines up with "Try".
708 ZStack(alignment: Alignment(horizontal: .leading, vertical: .firstTextBaseline)) {
709 HStack(alignment: .firstTextBaseline, spacing: 4) { Image(systemName: "checkmark").font(.system(size: 10, weight: .bold)); Text("Copied") }.hidden()
710 if copied {
711 HStack(alignment: .firstTextBaseline, spacing: 4) { Image(systemName: "checkmark").font(.system(size: 10, weight: .bold)); Text("Copied") }
712 .foregroundStyle(Tide.up)
713 } else {
714 HStack(alignment: .firstTextBaseline, spacing: 4) { Image(systemName: "doc.on.doc").font(.system(size: 10, weight: .semibold)); Text("Copy").underline(hover) }
715 .foregroundStyle(hover ? Tide.accentStrong : Tide.accent)
716 }
717 }
718 .font(Tide.sans(12.5, .semibold))
719 .contentShape(Rectangle())
720 }
721 .buttonStyle(.plain)
722 .onHover { hover = $0 }
723 .help("Copy this prompt for your agent")
724 .accessibilityLabel("Copy prompt")
725 }
726 .frame(maxWidth: 640, alignment: .leading)
727 }
728}