forked from home-assistant/iOS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLiveActivitySettingsView.swift
More file actions
689 lines (637 loc) · 27.5 KB
/
LiveActivitySettingsView.swift
File metadata and controls
689 lines (637 loc) · 27.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
#if os(iOS) && !targetEnvironment(macCatalyst)
import ActivityKit
import Shared
import SwiftUI
// MARK: - Entry point
/// Deployment target is iOS 15. The settings item is filtered from the list on < iOS 17.2
/// (see SettingsItem.allVisibleCases), so this view is only ever navigated to on iOS 17.2+.
@available(iOS 17.2, *)
struct LiveActivitySettingsView: View {
// MARK: State
@State private var activities: [ActivitySnapshot] = []
@State private var authorizationEnabled: Bool = false
@State private var frequentUpdatesEnabled: Bool = false
@State private var showEndAllConfirmation = false
// MARK: Body
var body: some View {
List {
AppleLikeListTopRowHeader(
image: .playBoxOutlineIcon,
title: L10n.LiveActivity.title,
subtitle: L10n.LiveActivity.subtitle
)
statusSection
if activities.isEmpty {
Section(L10n.LiveActivity.Section.active) {
HStack {
Text(L10n.LiveActivity.emptyState)
.foregroundStyle(.secondary)
Spacer()
}
}
} else {
Section(L10n.LiveActivity.Section.active) {
ForEach(activities) { snapshot in
ActivityRow(snapshot: snapshot) {
endActivity(tag: snapshot.tag)
}
}
Button(role: .destructive) {
showEndAllConfirmation = true
} label: {
Label(L10n.LiveActivity.EndAll.button, systemSymbol: .xmarkCircle)
}
.confirmationDialog(
L10n.LiveActivity.EndAll.Confirm.title,
isPresented: $showEndAllConfirmation,
titleVisibility: .visible
) {
Button(L10n.LiveActivity.EndAll.Confirm.button, role: .destructive) {
endAllActivities()
}
Button(L10n.cancelLabel, role: .cancel) {}
}
}
}
#if DEBUG
debugSection
#endif
privacySection
if #available(iOS 17.2, *) {
frequentUpdatesSection
}
}
.navigationTitle(L10n.LiveActivity.title)
.task { await loadActivities() }
}
// MARK: - Sections
private var statusSection: some View {
Section(L10n.LiveActivity.Section.status) {
HStack {
Label(L10n.LiveActivity.title, systemSymbol: .livephoto)
Spacer()
if authorizationEnabled {
Text(L10n.LiveActivity.Status.enabled)
.foregroundStyle(.green)
} else if UIDevice.current.userInterfaceIdiom == .pad {
Text(L10n.LiveActivity.Status.notSupported)
.foregroundStyle(.secondary)
} else {
Button(L10n.LiveActivity.Status.openSettings) {
if let url = URL(string: UIApplication.openSettingsURLString) {
UIApplication.shared.open(url)
}
}
.foregroundStyle(.orange)
}
}
}
}
// MARK: - Debug (DEBUG builds only)
//
// Two sections: Static (fixed snapshots to verify layout) and Animated (multi-stage
// self-updating sequences to simulate real HA automation behavior).
//
// Each scenario tests a unique combination of ContentState fields so they can be
// run independently without duplicating coverage.
//
// HOW TO USE:
// 1. Tap any button to start the activity.
// 2. Tap Allow on the permission prompt.
// 3. Lock the simulator immediately (Device menu → Lock, or ⌘L).
// 4. Watch the lock screen — animated scenarios update themselves automatically.
// 5. End individual activities via the × button in the Active section above.
//
// NOTE: criticalText is only visible in the Dynamic Island compact trailing slot.
// It does NOT appear on the lock screen. Use a Dynamic Island device or
// simulator (iPhone 14 Pro+) to see it.
#if DEBUG
private var debugSection: some View {
Group {
Section {
// Minimum viable layout — only the message field is set.
// Verifies the bare layout renders without icon, progress, or timer.
Button("Plain Message") {
startTestActivity(
tag: "debug-plain",
title: "Home Assistant",
state: .init(message: "Everything looks good at home.")
)
}
// icon = nil code path. Layout must not shift or break when no icon is provided.
// color = nil so the progress bar uses the default HA-blue tint.
// criticalText ("Active") visible in DI compact trailing only.
Button("No Icon · Default Color") {
startTestActivity(
tag: "debug-no-icon",
title: "Script Running",
state: .init(
message: "Irrigation zone 3 is active",
criticalText: "Active",
progress: 35,
progressMax: 100
)
)
}
// Short 60-second countdown with no progress bar.
// Red color communicates urgency. Watch the timer count down in real time.
// Represents automations like alarm arming delays or reminder countdowns.
Button("Alarm · 60 sec Countdown") {
startTestActivity(
tag: "debug-alarm",
title: "Security Alarm",
state: .init(
message: "Motion at back door · Arms in 60 seconds",
criticalText: "60 sec",
chronometer: true,
countdownEnd: Date().addingTimeInterval(60),
icon: "mdi:alarm-light",
color: "#F44336"
)
)
}
// Every ContentState field active at the same time.
// Lock screen shows: icon → live countdown → progress bar.
// criticalText ("5 min") visible in DI compact trailing only.
// Use this to confirm no layout collisions when all fields are populated.
Button("All Fields · Max Load") {
startTestActivity(
tag: "debug-all",
title: "All Fields",
state: .init(
message: "All content state fields active",
criticalText: "5 min",
progress: 42,
progressMax: 100,
chronometer: true,
countdownEnd: Date().addingTimeInterval(5 * 60),
icon: "mdi:home-assistant",
color: "#03A9F4"
)
)
}
} header: {
Text("Debug · Static")
} footer: {
Text("Fixed state — no updates after start. Good for checking layout at a glance.")
}
Section {
// Progress bar advances through five named stages.
// criticalText tracks the current stage name in the DI compact trailing slot.
// Icon swaps from washing-machine to check-circle on the final update.
// Represents any multi-step appliance cycle automation.
Button("Washing Machine · Stage Labels (~12 s)") { startWashingMachineCycle() }
// Numeric percentage in criticalText updates alongside the progress bar.
// Color shifts from green to yellow-green as the charge nears 100 %.
// Represents any "% complete with time remaining" automation pattern.
Button("EV Charging · Numeric % (~16 s)") { startEVChargingSimulation() }
// The only scenario where both progress (playback position) and a live countdown
// (time remaining in track) are active and updating at the same time.
// Simulates a track change mid-sequence: progress resets, countdown resets.
Button("Media Player · Progress + Timer (~20 s)") { startMediaNowPlaying() }
// Message, criticalText, and icon all change on every update — no progress bar.
// Represents automations where the status category itself changes (not just a value).
Button("Package Delivery · All Text Fields (~15 s)") { startPackageJourney() }
// No progress bar — state communicated entirely through color and icon.
// Escalates orange (motion) → red (person) → green (all clear).
// Represents any alert-and-resolve automation pattern.
Button("Security Escalation · Color + Icon (~8 s)") { startSecuritySequence() }
// Cycles through wash stages then calls activity.end() with .default dismissal.
// The only scenario that tests the full lifecycle: start → update → end.
// After ending, the final "Done" state lingers on the lock screen (up to 4 h).
Button("Dishwasher · Full Lifecycle, Ends Itself (~12 s)") { startDishwasherAutoComplete() }
// Fires 6 updates 2 seconds apart (12 s total).
// On iOS 18 the system enforces ~15 s between rendered updates — some will be
// silently dropped. Watch the counter skip values to see the rate limit in action.
// On the simulator and iOS 17 all 6 updates should render.
Button("Rate Limit · 6 Rapid Updates, 2 s Apart (~12 s)") { startRapidUpdateStressTest() }
} header: {
Text("Debug · Animated")
} footer: {
Text(
"Activity updates itself after you tap. Tap, then immediately lock (⌘L) " +
"to watch updates on the lock screen in real time."
)
}
}
}
#endif
#if DEBUG
// MARK: - Debug helpers
/// Starts a single-state activity (no subsequent updates).
private func startTestActivity(tag: String, title: String, state: HALiveActivityAttributes.ContentState) {
Task {
let attributes = HALiveActivityAttributes(tag: tag, title: title)
_ = try? Activity<HALiveActivityAttributes>.request(
attributes: attributes,
content: ActivityContent(state: state, staleDate: Date().addingTimeInterval(30 * 60)),
pushType: nil
)
await loadActivities()
}
}
/// Starts an activity and drives it through `stages` sequentially.
///
/// - Parameters:
/// - stages: Array of `(delayAfterPrevious seconds, ContentState)`. The first entry's
/// delay is ignored — it becomes the initial content. Each subsequent entry waits
/// `delay` seconds after the previous stage before pushing the update.
/// - endAfterCompletion: When `true`, calls `activity.end()` with `.default` dismissal
/// after the final stage, leaving the last state visible on the lock screen (up to 4 h).
private func startAnimatedActivity(
tag: String,
title: String,
stages: [(delay: Double, state: HALiveActivityAttributes.ContentState)],
endAfterCompletion: Bool = false
) {
guard let first = stages.first else { return }
Task {
let attributes = HALiveActivityAttributes(tag: tag, title: title)
guard let activity = try? Activity<HALiveActivityAttributes>.request(
attributes: attributes,
content: ActivityContent(state: first.state, staleDate: Date().addingTimeInterval(30 * 60)),
pushType: nil
) else { return }
await loadActivities()
for stage in stages.dropFirst() {
try? await Task.sleep(nanoseconds: UInt64(stage.delay * 1_000_000_000))
await activity.update(ActivityContent(
state: stage.state,
staleDate: Date().addingTimeInterval(30 * 60)
))
await loadActivities()
}
if endAfterCompletion, let last = stages.last {
await activity.end(
ActivityContent(state: last.state, staleDate: Date().addingTimeInterval(30 * 60)),
dismissalPolicy: .default
)
await loadActivities()
}
}
}
// MARK: - Animated scenario implementations
/// Progress advances through five named wash stages.
/// criticalText tracks the stage name (DI compact trailing).
/// Icon swaps to check-circle on the final update.
private func startWashingMachineCycle() {
startAnimatedActivity(
tag: "debug-washing",
title: "Washing Machine",
stages: [
(0, .init(
message: "Starting soak",
criticalText: "Soak",
progress: 5, progressMax: 100,
icon: "mdi:washing-machine", color: "#2196F3"
)),
(3, .init(
message: "Washing · Heavy cycle",
criticalText: "Wash",
progress: 30, progressMax: 100,
icon: "mdi:washing-machine", color: "#2196F3"
)),
(3, .init(
message: "Rinsing · 1 of 2",
criticalText: "Rinse",
progress: 60, progressMax: 100,
icon: "mdi:washing-machine", color: "#2196F3"
)),
(3, .init(
message: "Final spin",
criticalText: "Spin",
progress: 85, progressMax: 100,
icon: "mdi:washing-machine", color: "#2196F3"
)),
(3, .init(
message: "Cycle complete",
criticalText: "Done",
progress: 100, progressMax: 100,
icon: "mdi:check-circle", color: "#4CAF50"
)),
]
)
}
/// Numeric percentage in criticalText updates alongside the progress bar.
/// Color shifts from green to yellow-green as the charge nears full.
private func startEVChargingSimulation() {
startAnimatedActivity(
tag: "debug-ev",
title: "EV Charging",
stages: [
(0, .init(
message: "Charging · Est. 45 min remaining",
criticalText: "45%",
progress: 45, progressMax: 100,
icon: "mdi:ev-station", color: "#4CAF50"
)),
(4, .init(
message: "Charging · Est. 30 min remaining",
criticalText: "60%",
progress: 60, progressMax: 100,
icon: "mdi:ev-station", color: "#4CAF50"
)),
(4, .init(
message: "Charging · Est. 15 min remaining",
criticalText: "78%",
progress: 78, progressMax: 100,
icon: "mdi:ev-station", color: "#8BC34A"
)),
(4, .init(
message: "Charge complete",
criticalText: "Full",
progress: 100, progressMax: 100,
icon: "mdi:battery-charging", color: "#4CAF50"
)),
]
)
}
/// Both progress (playback position) and a live countdown (time remaining) update together.
/// countdownEnd is fixed once at tap time so the timer runs smoothly across all stages.
/// Simulates a track change: progress resets and countdownEnd resets on the final stage.
private func startMediaNowPlaying() {
let track1End = Date().addingTimeInterval(2 * 60)
startAnimatedActivity(
tag: "debug-media",
title: "Now Playing",
stages: [
(0, .init(
message: "Bohemian Rhapsody · Queen",
criticalText: "1 / 12",
progress: 20, progressMax: 100,
chronometer: true, countdownEnd: track1End,
icon: "mdi:music-note", color: "#9C27B0"
)),
(5, .init(
message: "Bohemian Rhapsody · Queen",
criticalText: "1 / 12",
progress: 42, progressMax: 100,
chronometer: true, countdownEnd: track1End,
icon: "mdi:music-note", color: "#9C27B0"
)),
(5, .init(
message: "Bohemian Rhapsody · Queen",
criticalText: "1 / 12",
progress: 67, progressMax: 100,
chronometer: true, countdownEnd: track1End,
icon: "mdi:music-note", color: "#9C27B0"
)),
// Track changes — message, progress, and countdownEnd all reset together.
(5, .init(
message: "Don't Stop Me Now · Queen",
criticalText: "2 / 12",
progress: 8, progressMax: 100,
chronometer: true, countdownEnd: Date().addingTimeInterval(3 * 60 + 29),
icon: "mdi:music-note", color: "#9C27B0"
)),
]
)
}
/// Message, criticalText, and icon all change on every update — no progress bar.
/// Represents automations where the status category itself changes, not just a value.
private func startPackageJourney() {
startAnimatedActivity(
tag: "debug-delivery",
title: "Package Delivery",
stages: [
(0, .init(
message: "Order shipped · Est. today",
criticalText: "Shipped",
icon: "mdi:package-variant-closed", color: "#795548"
)),
(5, .init(
message: "Out for delivery · 8 stops away",
criticalText: "On way",
icon: "mdi:truck-delivery", color: "#FF9800"
)),
(5, .init(
message: "Nearby · 2 stops away",
criticalText: "Nearby",
icon: "mdi:truck-delivery", color: "#FF5722"
)),
(5, .init(
message: "Delivered to front door",
criticalText: "Done",
icon: "mdi:package-variant", color: "#4CAF50"
)),
]
)
}
/// State communicated through color and icon only — no progress bar.
/// Escalates orange → red → green to show the alert-and-resolve pattern.
private func startSecuritySequence() {
startAnimatedActivity(
tag: "debug-security",
title: "Security Alert",
stages: [
(0, .init(
message: "Motion detected at front door",
criticalText: "Motion",
icon: "mdi:motion-sensor", color: "#FF9800"
)),
(4, .init(
message: "Person detected · Camera 1",
criticalText: "Person",
icon: "mdi:cctv", color: "#F44336"
)),
(4, .init(
message: "Disarmed · All clear",
criticalText: "Safe",
icon: "mdi:shield-check", color: "#4CAF50"
)),
]
)
}
/// Cycles through wash stages then calls activity.end() with .default dismissal.
/// After ending, the "Done" state lingers on the lock screen for up to 4 hours —
/// this is the expected UX for any automation that represents a completed task.
private func startDishwasherAutoComplete() {
startAnimatedActivity(
tag: "debug-dishwasher",
title: "Dishwasher",
stages: [
(0, .init(
message: "Pre-wash in progress",
criticalText: "Pre-wash",
progress: 20, progressMax: 100,
icon: "mdi:dishwasher", color: "#26C6DA"
)),
(3, .init(
message: "Main wash · Hot cycle",
criticalText: "Wash",
progress: 50, progressMax: 100,
icon: "mdi:dishwasher", color: "#26C6DA"
)),
(3, .init(
message: "Rinse and dry",
criticalText: "Rinse",
progress: 80, progressMax: 100,
icon: "mdi:dishwasher", color: "#26C6DA"
)),
(3, .init(
message: "Dishes are clean",
criticalText: "Done",
progress: 100, progressMax: 100,
icon: "mdi:check-circle", color: "#4CAF50"
)),
],
endAfterCompletion: true
)
}
/// Fires 6 updates spaced 2 seconds apart (12 s total).
/// On iOS 18 the system enforces ~15 s between rendered updates — excess updates are
/// silently dropped and the counter will appear to skip values on device.
/// On the simulator and iOS 17 all 6 updates should render without skipping.
private func startRapidUpdateStressTest() {
startAnimatedActivity(
tag: "debug-rapid",
title: "Rate Limit Test",
stages: [
(0, .init(
message: "Update 1 of 6 · Watch for skipped values on device",
criticalText: "#1",
progress: 0, progressMax: 100,
icon: "mdi:lightning-bolt", color: "#FF9800"
)),
(2, .init(
message: "Update 2 of 6",
criticalText: "#2",
progress: 17, progressMax: 100,
icon: "mdi:lightning-bolt", color: "#FF9800"
)),
(2, .init(
message: "Update 3 of 6",
criticalText: "#3",
progress: 33, progressMax: 100,
icon: "mdi:lightning-bolt", color: "#FF9800"
)),
(2, .init(
message: "Update 4 of 6",
criticalText: "#4",
progress: 50, progressMax: 100,
icon: "mdi:lightning-bolt", color: "#FF9800"
)),
(2, .init(
message: "Update 5 of 6",
criticalText: "#5",
progress: 67, progressMax: 100,
icon: "mdi:lightning-bolt", color: "#FF9800"
)),
(2, .init(
message: "Update 6 of 6 · All done",
criticalText: "#6",
progress: 100, progressMax: 100,
icon: "mdi:lightning-bolt", color: "#FF9800"
)),
]
)
}
#endif
private var privacySection: some View {
Section {
Label(L10n.LiveActivity.Privacy.message, systemSymbol: .lockShield)
.font(.footnote)
.foregroundStyle(.secondary)
} header: {
Text(L10n.LiveActivity.Section.privacy)
}
}
@available(iOS 17.2, *)
private var frequentUpdatesSection: some View {
let appName = Bundle.main.infoDictionary?["CFBundleDisplayName"] as? String ?? "Home Assistant"
return Section {
HStack {
Label(L10n.LiveActivity.FrequentUpdates.title, systemSymbol: .bolt)
Spacer()
if frequentUpdatesEnabled {
Text(L10n.LiveActivity.Status.enabled)
.foregroundStyle(.green)
} else {
Button(L10n.LiveActivity.Status.openSettings) {
if let url = URL(string: UIApplication.openSettingsURLString) {
UIApplication.shared.open(url)
}
}
.foregroundStyle(.secondary)
}
}
} header: {
Text(L10n.LiveActivity.FrequentUpdates.title)
} footer: {
Text(L10n.LiveActivity.FrequentUpdates.footer(appName))
}
}
// MARK: - Data
private func loadActivities() async {
let info = ActivityAuthorizationInfo()
authorizationEnabled = info.areActivitiesEnabled
if #available(iOS 17.2, *) {
frequentUpdatesEnabled = info.frequentPushesEnabled
}
activities = Activity<HALiveActivityAttributes>.activities.map {
ActivitySnapshot(activity: $0)
}
}
private func endActivity(tag: String) {
Task {
await Current.liveActivityRegistry?.end(tag: tag, dismissalPolicy: .immediate)
await loadActivities()
}
}
private func endAllActivities() {
Task {
let tags = activities.map(\.tag)
await withTaskGroup(of: Void.self) { group in
for tag in tags {
group.addTask {
await Current.liveActivityRegistry?.end(tag: tag, dismissalPolicy: .immediate)
}
}
}
await loadActivities()
}
}
}
// MARK: - Activity row
@available(iOS 17.2, *)
private struct ActivityRow: View {
let snapshot: ActivitySnapshot
let onEnd: () -> Void
var body: some View {
HStack {
VStack(alignment: .leading, spacing: 2) {
Text(snapshot.title)
.font(.body)
Text(snapshot.message)
.font(.caption)
.foregroundStyle(.secondary)
.lineLimit(1)
Text("tag: \(snapshot.tag)")
.font(.caption2)
.foregroundStyle(.tertiary)
.lineLimit(1)
}
Spacer()
Button(role: .destructive, action: onEnd) {
Image(systemSymbol: .xmarkCircleFill)
.foregroundStyle(.red)
}
.buttonStyle(.plain)
}
}
}
// MARK: - Snapshot model
@available(iOS 17.2, *)
private struct ActivitySnapshot: Identifiable {
let id: String
let tag: String
let title: String
let message: String
init(activity: Activity<HALiveActivityAttributes>) {
self.id = activity.id
self.tag = activity.attributes.tag
self.title = activity.attributes.title
self.message = activity.content.state.message
}
}
#endif