Sources/OrgstarWidgets/ClockActivityWidget.swift
86 lines · 3335 bytes
1#if os(iOS)
2import ActivityKit
3import AppIntents
4import OrgApp
5import SwiftUI
6import WidgetKit
7
8/// The running clock on the Lock Screen and in the Dynamic Island: the heading and the time
9/// so far, which ticks by itself.
10struct ClockActivityWidget: Widget {
11 var body: some WidgetConfiguration {
12 ActivityConfiguration(for: ClockActivityAttributes.self) { context in
13 HStack(spacing: 12) {
14 Image(systemName: "stopwatch").font(.title2).foregroundStyle(.orange)
15 VStack(alignment: .leading, spacing: 2) {
16 Text("Clocked in").font(.caption).foregroundStyle(.secondary)
17 Text(context.state.heading).font(.headline).lineLimit(2)
18 }
19 Spacer(minLength: 0)
20 VStack(alignment: .trailing, spacing: 6) {
21 ElapsedText(state: context.state).font(.title3.weight(.semibold))
22 ClockOutButton()
23 }
24 }
25 .padding()
26 .widgetURL(AppLink.clock.url)
27 } dynamicIsland: { context in
28 DynamicIsland {
29 DynamicIslandExpandedRegion(.leading) {
30 Image(systemName: "stopwatch").font(.title2).foregroundStyle(.orange)
31 }
32 DynamicIslandExpandedRegion(.trailing) {
33 ElapsedText(state: context.state).font(.title3.weight(.semibold)).frame(width: 84, alignment: .trailing)
34 }
35 DynamicIslandExpandedRegion(.center) {
36 Text(context.state.heading).font(.headline).lineLimit(1)
37 }
38 DynamicIslandExpandedRegion(.bottom) {
39 ClockOutButton()
40 }
41 } compactLeading: {
42 Image(systemName: "stopwatch").foregroundStyle(.orange)
43 } compactTrailing: {
44 ElapsedText(state: context.state).frame(maxWidth: 56)
45 } minimal: {
46 Image(systemName: "stopwatch").foregroundStyle(.orange)
47 }
48 .widgetURL(AppLink.clock.url)
49 }
50 }
51}
52
53/// Time since the clock started, `1:05:09`.
54struct ElapsedText: View {
55 let state: ClockActivityAttributes.ContentState
56
57 var body: some View {
58 Text(timerInterval: state.startedAt...Date.distantFuture, countsDown: false)
59 .monospacedDigit()
60 .lineLimit(1)
61 .minimumScaleFactor(0.7)
62 .multilineTextAlignment(.trailing)
63 }
64}
65
66struct ClockOutButton: View {
67 var body: some View {
68 Button(intent: ClockOutIntent()) {
69 Label("Clock Out", systemImage: "stop.fill").font(.caption.weight(.semibold))
70 }
71 .tint(.orange)
72 }
73}
74
75#Preview("Lock Screen", as: .content, using: ClockActivityAttributes(path: "/notes/work.org", start: "2026-10-09 Fri 09:00")) {
76 ClockActivityWidget()
77} contentStates: {
78 ClockActivityAttributes.ContentState(heading: "Review the draft", startedAt: .now.addingTimeInterval(-3725))
79}
80
81#Preview("Expanded", as: .dynamicIsland(.expanded), using: ClockActivityAttributes(path: "/notes/work.org", start: "2026-10-09 Fri 09:00")) {
82 ClockActivityWidget()
83} contentStates: {
84 ClockActivityAttributes.ContentState(heading: "Review the draft", startedAt: .now.addingTimeInterval(-3725))
85}
86#endif