-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathPlayerBar.swift
More file actions
529 lines (472 loc) · 19.9 KB
/
PlayerBar.swift
File metadata and controls
529 lines (472 loc) · 19.9 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
import AVKit
import SwiftUI
// MARK: - PlayerBar
/// Player bar shown at the bottom of the content area, styled like Apple Music with Liquid Glass.
@available(macOS 26.0, *)
struct PlayerBar: View {
@Environment(PlayerService.self) private var playerService
@Environment(WebKitManager.self) private var webKitManager
/// Namespace for glass effect morphing and unioning.
@Namespace private var playerNamespace
@State private var isHovering = false
/// Local seek value for smooth slider dragging without network calls on every change.
@State private var seekValue: Double = 0
@State private var isSeeking = false
/// Local volume value for smooth slider dragging.
@State private var volumeValue: Double = 1.0
@State private var isAdjustingVolume = false
/// Cached formatted progress string to avoid repeated formatting.
@State private var formattedProgress: String = "0:00"
@State private var formattedRemaining: String = "-0:00"
/// Last integer second of progress to reduce string formatting frequency.
@State private var lastProgressSecond: Int = -1
var body: some View {
GlassEffectContainer(spacing: 0) {
HStack(spacing: 0) {
// Left section: Playback controls
self.playbackControls
Spacer()
// Center section: Track info OR seek bar (on hover)
self.centerSection
Spacer()
// Right section: Volume control
self.volumeControl
}
.padding(.horizontal, 20)
.padding(.vertical, 8)
.frame(height: 52)
.glassEffect(.regular.interactive(), in: .capsule)
.glassEffectID("playerBar", in: self.playerNamespace)
}
.padding(.horizontal, 16)
.padding(.bottom, 12)
.onHover { hovering in
withAnimation(.easeInOut(duration: 0.15)) {
self.isHovering = hovering
}
}
.background {
// Keyboard shortcuts for media controls
Group {
// Space: Play/Pause
Button("") {
Task { await self.playerService.playPause() }
}
.keyboardShortcut(.space, modifiers: [])
.opacity(0)
// Command + Right Arrow: Next track
Button("") {
Task { await self.playerService.next() }
}
.keyboardShortcut(.rightArrow, modifiers: .command)
.opacity(0)
// Command + Left Arrow: Previous track
Button("") {
Task { await self.playerService.previous() }
}
.keyboardShortcut(.leftArrow, modifiers: .command)
.opacity(0)
// Command + Up Arrow: Volume up
Button("") {
Task { await self.playerService.setVolume(min(1.0, self.playerService.volume + 0.1)) }
}
.keyboardShortcut(.upArrow, modifiers: .command)
.opacity(0)
// Command + Down Arrow: Volume down
Button("") {
Task { await self.playerService.setVolume(max(0.0, self.playerService.volume - 0.1)) }
}
.keyboardShortcut(.downArrow, modifiers: .command)
.opacity(0)
// Command + M: Toggle mute
Button("") {
Task { await self.playerService.toggleMute() }
}
.keyboardShortcut("m", modifiers: .command)
.opacity(0)
}
}
.onChange(of: self.playerService.progress) { _, newValue in
// Sync local seek value when not actively seeking
if !self.isSeeking, self.playerService.duration > 0 {
self.seekValue = newValue / self.playerService.duration
}
// Only update formatted strings when the second changes to reduce Text view updates
let currentSecond = Int(newValue)
if currentSecond != self.lastProgressSecond {
self.lastProgressSecond = currentSecond
self.formattedProgress = self.formatTime(newValue)
self.formattedRemaining = "-\(self.formatTime(self.playerService.duration - newValue))"
}
}
.onChange(of: self.playerService.volume) { _, newValue in
// Sync local volume value when not actively adjusting
if !self.isAdjustingVolume {
self.volumeValue = newValue
}
}
.onAppear {
// Sync local volume value from saved state on initial load
self.volumeValue = self.playerService.volume
}
}
// MARK: - Center Section (track info blurs, seek bar appears on hover)
private var centerSection: some View {
ZStack {
// Track info (blurred when hovering and track is playing)
self.trackInfoView
.blur(radius: self.isHovering && self.playerService.currentTrack != nil ? 8 : 0)
.opacity(self.isHovering && self.playerService.currentTrack != nil ? 0 : 1)
// Seek bar (shown when hovering and track is playing)
if self.isHovering, self.playerService.currentTrack != nil {
self.seekBarView
.transition(.opacity)
}
}
.frame(maxWidth: 400)
}
// MARK: - Track Info View
private var trackInfoView: some View {
HStack(spacing: 10) {
// Thumbnail
CachedAsyncImage(url: self.playerService.currentTrack?.thumbnailURL?.highQualityThumbnailURL) { image in
image
.resizable()
.aspectRatio(contentMode: .fill)
} placeholder: {
RoundedRectangle(cornerRadius: 4)
.fill(.quaternary)
.overlay {
CassetteIcon(size: 20)
.foregroundStyle(.secondary)
}
}
.frame(width: 36, height: 36)
.clipShape(RoundedRectangle(cornerRadius: 4))
// Track info
if let track = playerService.currentTrack {
VStack(alignment: .leading, spacing: 1) {
Text(track.title)
.font(.system(size: 12, weight: .medium))
.lineLimit(1)
.foregroundStyle(.primary)
Text(track.artistsDisplay.isEmpty ? "Unknown Artist" : track.artistsDisplay)
.font(.system(size: 10))
.lineLimit(1)
.foregroundStyle(.secondary)
}
.frame(maxWidth: 200, alignment: .leading)
}
}
}
// MARK: - Seek Bar View (replaces track info on hover)
private var seekBarView: some View {
HStack(spacing: 10) {
// Elapsed time - use cached formatted string when not seeking
Text(self.isSeeking ? self.formatTime(self.seekValue * self.playerService.duration) : self.formattedProgress)
.font(.system(size: 11))
.foregroundStyle(.secondary)
.frame(minWidth: 45, alignment: .trailing)
.monospacedDigit()
// Seek slider
Slider(value: self.$seekValue, in: 0 ... 1) { editing in
if editing {
// User started dragging
self.isSeeking = true
} else {
// User finished dragging - perform seek
self.performSeek()
}
}
.controlSize(.small)
// Remaining time - use cached formatted string when not seeking
Text(self.isSeeking ? "-\(self.formatTime(self.playerService.duration - self.seekValue * self.playerService.duration))" : self.formattedRemaining)
.font(.system(size: 11))
.foregroundStyle(.secondary)
.frame(minWidth: 45, alignment: .leading)
.monospacedDigit()
}
}
/// Performs the actual seek operation after slider interaction ends.
private func performSeek() {
guard self.isSeeking else { return }
let seekTime = self.seekValue * self.playerService.duration
Task {
await self.playerService.seek(to: seekTime)
self.isSeeking = false
}
}
private func formatTime(_ seconds: TimeInterval) -> String {
guard seconds.isFinite, seconds >= 0 else { return "0:00" }
let totalSeconds = Int(seconds)
let hours = totalSeconds / 3600
let mins = (totalSeconds % 3600) / 60
let secs = totalSeconds % 60
if hours > 0 {
return String(format: "%d:%02d:%02d", hours, mins, secs)
} else {
return String(format: "%d:%02d", mins, secs)
}
}
// MARK: - Playback Controls
private var playbackControls: some View {
HStack(spacing: 16) {
// Shuffle
Button {
HapticService.toggle()
self.playerService.toggleShuffle()
} label: {
Image(systemName: "shuffle")
.font(.system(size: 15, weight: .medium))
.foregroundStyle(self.playerService.shuffleEnabled ? .red : .primary.opacity(0.85))
.contentTransition(.symbolEffect(.replace))
}
.buttonStyle(.pressable)
.accessibilityLabel("Shuffle")
.accessibilityValue(self.playerService.shuffleEnabled ? "On" : "Off")
// Previous
Button {
HapticService.playback()
Task {
await self.playerService.previous()
}
} label: {
Image(systemName: "backward.fill")
.font(.system(size: 17, weight: .medium))
.foregroundStyle(.primary)
}
.buttonStyle(.pressable)
.accessibilityLabel("Previous track")
// Play/Pause
Button {
HapticService.playback()
Task {
await self.playerService.playPause()
}
} label: {
Image(systemName: self.playerService.isPlaying ? "pause.fill" : "play.fill")
.font(.system(size: 22, weight: .medium))
.foregroundStyle(.primary)
.contentTransition(.symbolEffect(.replace))
}
.buttonStyle(.pressable)
.glassEffectID("playPause", in: self.playerNamespace)
.accessibilityLabel(self.playerService.isPlaying ? "Pause" : "Play")
// Next
Button {
HapticService.playback()
Task {
await self.playerService.next()
}
} label: {
Image(systemName: "forward.fill")
.font(.system(size: 17, weight: .medium))
.foregroundStyle(.primary)
}
.buttonStyle(.pressable)
.accessibilityLabel("Next track")
// Repeat
Button {
HapticService.toggle()
self.playerService.cycleRepeatMode()
} label: {
Image(systemName: self.repeatIcon)
.font(.system(size: 15, weight: .medium))
.foregroundStyle(self.playerService.repeatMode != .off ? .red : .primary.opacity(0.85))
.contentTransition(.symbolEffect(.replace))
}
.buttonStyle(.pressable)
.accessibilityLabel("Repeat")
.accessibilityValue(self.repeatAccessibilityValue)
}
}
private var repeatIcon: String {
switch self.playerService.repeatMode {
case .off, .all:
"repeat"
case .one:
"repeat.1"
}
}
private var repeatAccessibilityValue: String {
switch self.playerService.repeatMode {
case .off:
"Off"
case .all:
"All"
case .one:
"One"
}
}
// MARK: - Volume Control
private var volumeControl: some View {
HStack(spacing: 8) {
// Like/Dislike/Library actions
self.actionButtons
// AirPlay button
AirPlayButton()
.frame(width: 20, height: 20)
Divider()
.frame(height: 20)
.padding(.horizontal, 4)
Image(systemName: self.volumeIcon)
.font(.system(size: 15, weight: .medium))
.foregroundStyle(.primary.opacity(0.85))
.frame(width: 18)
// Volume slider with immediate updates
Slider(value: self.$volumeValue, in: 0 ... 1) { editing in
if editing {
// User started dragging
self.isAdjustingVolume = true
} else {
// User finished dragging/clicking - apply volume change
self.isAdjustingVolume = false
// Always apply volume when interaction ends to ensure WebView is synced
Task {
await self.playerService.setVolume(self.volumeValue)
}
}
}
.frame(width: 80)
.controlSize(.small)
.onChange(of: self.volumeValue) { oldValue, newValue in
// Apply volume changes in real-time during dragging for immediate feedback
if self.isAdjustingVolume {
// Haptic feedback at slider boundaries
if (oldValue > 0 && newValue == 0) || (oldValue < 1 && newValue == 1) {
HapticService.sliderBoundary()
}
Task {
await self.playerService.setVolume(newValue)
}
}
}
}
}
// MARK: - Action Buttons (Like/Dislike/Lyrics/Queue)
private var actionButtons: some View {
@Bindable var player = self.playerService
return HStack(spacing: 12) {
// Dislike button
Button {
HapticService.toggle()
self.playerService.dislikeCurrentTrack()
} label: {
Image(systemName: self.playerService.currentTrackLikeStatus == .dislike
? "hand.thumbsdown.fill"
: "hand.thumbsdown")
.font(.system(size: 15, weight: .medium))
.foregroundStyle(self.playerService.currentTrackLikeStatus == .dislike ? .red : .primary.opacity(0.85))
.contentTransition(.symbolEffect(.replace))
}
.buttonStyle(.pressable)
.symbolEffect(.bounce, value: self.playerService.currentTrackLikeStatus == .dislike)
.accessibilityLabel("Dislike")
.accessibilityValue(self.playerService.currentTrackLikeStatus == .dislike ? "Disliked" : "Not disliked")
.disabled(self.playerService.currentTrack == nil)
// Like button
Button {
HapticService.toggle()
self.playerService.likeCurrentTrack()
} label: {
Image(systemName: self.playerService.currentTrackLikeStatus == .like
? "hand.thumbsup.fill"
: "hand.thumbsup")
.font(.system(size: 15, weight: .medium))
.foregroundStyle(self.playerService.currentTrackLikeStatus == .like ? .red : .primary.opacity(0.85))
.contentTransition(.symbolEffect(.replace))
}
.buttonStyle(.pressable)
.symbolEffect(.bounce, value: self.playerService.currentTrackLikeStatus == .like)
.accessibilityLabel("Like")
.accessibilityValue(self.playerService.currentTrackLikeStatus == .like ? "Liked" : "Not liked")
.disabled(self.playerService.currentTrack == nil)
// Lyrics button
Button {
HapticService.toggle()
withAnimation(AppAnimation.standard) {
player.showLyrics.toggle()
}
} label: {
Image(systemName: "quote.bubble")
.font(.system(size: 15, weight: .medium))
.foregroundStyle(self.playerService.showLyrics ? .red : .primary.opacity(0.85))
}
.buttonStyle(.pressable)
.glassEffectID("lyrics", in: self.playerNamespace)
.accessibilityIdentifier(AccessibilityID.PlayerBar.lyricsButton)
.accessibilityLabel("Lyrics")
.accessibilityValue(self.playerService.showLyrics ? "Showing" : "Hidden")
// Queue button
Button {
HapticService.toggle()
withAnimation(AppAnimation.standard) {
player.showQueue.toggle()
}
} label: {
Image(systemName: "list.bullet")
.font(.system(size: 15, weight: .medium))
.foregroundStyle(self.playerService.showQueue ? .red : .primary.opacity(0.85))
}
.buttonStyle(.pressable)
.glassEffectID("queue", in: self.playerNamespace)
.accessibilityIdentifier(AccessibilityID.PlayerBar.queueButton)
.accessibilityLabel("Queue")
.accessibilityValue(self.playerService.showQueue ? "Showing" : "Hidden")
// Video button - only shown when track has video
if self.playerService.currentTrackHasVideo {
Button {
HapticService.toggle()
DiagnosticsLogger.player.debug(
"Video button clicked, toggling showVideo from \(self.playerService.showVideo)")
withAnimation(AppAnimation.standard) {
player.showVideo.toggle()
}
} label: {
Image(systemName: self.playerService.showVideo ? "tv.fill" : "tv")
.font(.system(size: 15, weight: .medium))
.foregroundStyle(self.playerService.showVideo ? .red : .primary.opacity(0.85))
.contentTransition(.symbolEffect(.replace))
}
.buttonStyle(.pressable)
.glassEffectID("video", in: self.playerNamespace)
.keyboardShortcut("v", modifiers: [.command, .shift])
.accessibilityIdentifier(AccessibilityID.PlayerBar.videoButton)
.accessibilityLabel("Video")
.accessibilityValue(self.playerService.showVideo ? "Playing" : "Off")
}
}
}
private var volumeIcon: String {
let currentVolume = self.isAdjustingVolume ? self.volumeValue : self.playerService.volume
if currentVolume == 0 {
return "speaker.slash.fill"
} else if currentVolume < 0.5 {
return "speaker.wave.1.fill"
} else {
return "speaker.wave.2.fill"
}
}
}
// MARK: - AirPlayButton
/// A SwiftUI wrapper for AVRoutePickerView to show AirPlay destinations.
@available(macOS 26.0, *)
struct AirPlayButton: NSViewRepresentable {
func makeNSView(context _: Context) -> AVRoutePickerView {
let routePickerView = AVRoutePickerView()
routePickerView.isRoutePickerButtonBordered = false
return routePickerView
}
func updateNSView(_: AVRoutePickerView, context _: Context) {
// No updates needed
}
}
@available(macOS 26.0, *)
#Preview {
PlayerBar()
.environment(PlayerService())
.environment(WebKitManager.shared)
.frame(width: 600)
.padding()
.background(Color(nsColor: .windowBackgroundColor))
}