Branchwell

PulseCanvas / app / Sources / PulseCanvas / StudioTimelineView.swift

1import SwiftUI
2import Combine
3
4@MainActor
5struct StudioTimelineView: View {
6 @ObservedObject private var library = ProjectMPresets.shared
7 @ObservedObject var studio: StudioStore
8 @ObservedObject var render: RenderState
9 @ObservedObject var audio: AudioController
10 let exporting: Bool
11 let present: () -> Void
12 var compactness: CGFloat = 0
13 @State private var choosingSegment: Int?
14 @State private var favoritesSegment: Int?
15 @State private var confirmRandomizeTimeline = false
16 @State private var randomizeCapacityError = false
17 @State private var randomizeVisualizers = true
18 @State private var randomizeBarLengths = false
19 @State private var showCommonSettings = false
20 @State private var includeBars = false
21 @State private var commonBars = 4
22 @State private var includeChaos = true
23 @State private var includeZoomSpeed = true
24 @State private var includeMotionSpeed = true
25 @State private var commonChaos: Float = 0.5
26 @State private var commonZoomSpeed: Float = 1.5
27 @State private var commonMotionSpeed: Float = 1
28 @State private var strobeAction: StrobeAction = .keep
29 @State private var commonStrobeSensitivity: Float = 1
30 @State private var commonStrobeStrength: Float = 1
31 private enum StrobeAction: String, CaseIterable {
32 case keep = "Keep individual", add = "Apply all", remove = "Remove all"
33 }
34 private let accent = Color(red: 0.95, green: 0.68, blue: 0.55)
35
36 var body: some View {
37 VStack(alignment: .leading, spacing: 10 - 4 * compactness) {
38 HStack(spacing: 8) {
39
40 if !studio.segments.isEmpty {
41 Text("\(studio.segments.count) sections").font(.system(size: 11)).foregroundStyle(.secondary).layoutPriority(-1)
42 if let bpm = studio.detectedBPM { Text("\(Int(bpm.rounded())) BPM").font(.system(size: 11)).foregroundStyle(.secondary).layoutPriority(-1) }
43 }
44 Spacer()
45 Button {
46 confirmRandomizeTimeline = true
47 } label: { Label("Randomize timeline", systemImage: "shuffle") }
48 .buttonStyle(StudioButtonStyle(treatment: .accent, compact: true)).disabled(studio.segments.isEmpty || exporting)
49 .help("Choose whether to randomize visualizers, bar lengths, or both")
50 Button {
51 showCommonSettings = true
52 } label: { Label("Apply to all", systemImage: "slider.horizontal.3") }
53 .buttonStyle(StudioButtonStyle(treatment: .accent, compact: true))
54 .help("Choose common settings for every visualizer and Studio section")
55 Button(action: present) { Label("Present", systemImage: "play.rectangle.fill") }
56 .buttonStyle(StudioButtonStyle(treatment: .primary, compact: true))
57 .disabled(audio.selectedURL == nil || studio.segments.isEmpty || exporting)
58 .help("Play the Studio timeline full screen from the current position. Escape returns to the editor.")
59 .accessibilityLabel("Present Studio full screen")
60 }.lineLimit(1)
61 if studio.segments.isEmpty {
62 Text("Add a soundtrack to create a sequence of visualizers.").font(.system(size: 12)).foregroundStyle(.secondary)
63 } else {
64 ScrollViewReader { proxy in
65 ScrollView(.horizontal) {
66 LazyHStack(spacing: 8) {
67 // Timing changes move boundaries, not card identities.
68 ForEach(studio.segments.indices, id: \.self) { index in
69 segmentCard(studio.segments[index], index: index).id(index)
70 }
71 }
72 // Keep card borders clear of the scroll view's clipping bounds,
73 // including space reserved by macOS for a horizontal scroller.
74 .padding(.vertical, 6)
75 }.frame(height: 140).scrollIndicators(.hidden)
76 .onAppear { proxy.scrollTo(studio.selectedSegment, anchor: .center) }
77 .onChange(of: studio.selectedSegment) { _, index in proxy.scrollTo(index, anchor: .center) }
78 }
79 }
80 }.padding(.horizontal, 20).padding(.vertical, 12 - 4 * compactness)
81 .background(Color.black.opacity(0.12)).disabled(exporting)
82 .sheet(isPresented: $confirmRandomizeTimeline) { timelineRandomizationConfirmation.dismissOnOutsideClick { confirmRandomizeTimeline = false } }
83 .sheet(isPresented: $showCommonSettings) { commonSettings.dismissOnOutsideClick { showCommonSettings = false } }
84 .alert("Not enough unique visualizers", isPresented: $randomizeCapacityError) {
85 Button("OK", role: .cancel) {}
86 } message: {
87 Text("This timeline has \(studio.segments.count) sections and \(ProjectMPresets.shared.eligibleScenes.count) available visualizers. Use longer sections or add visualizers to randomize without repeats.")
88 }
89 .sheet(isPresented: Binding(get: {choosingSegment != nil}, set: {if !$0 {choosingSegment = nil}})) {
90 if let index = choosingSegment, studio.segments.indices.contains(index) {
91 VStack(spacing:0) {
92 scenePicker(studio.segments[index], index:index)
93 HStack {
94 Spacer()
95 Button("Cancel") {choosingSegment = nil}
96 .buttonStyle(StudioButtonStyle(compact:true)).keyboardShortcut(.cancelAction)
97 }.padding(18)
98 }.dismissOnOutsideClick { choosingSegment = nil }
99 }
100 }
101 .onChange(of: studio.selectedSegment) { _, index in
102 if choosingSegment != index { choosingSegment = nil }
103 favoritesSegment = nil
104 }
105 }
106
107 private var timelineRandomizationConfirmation: some View {
108 VStack(alignment: .leading, spacing: 22) {
109 HStack(alignment: .top, spacing: 16) {
110 Image(systemName: "shuffle").font(.system(size: 24, weight: .medium))
111 .foregroundStyle(accent).frame(width: 56, height: 56)
112 .background(accent.opacity(0.12), in: RoundedRectangle(cornerRadius: 16))
113 .accessibilityHidden(true)
114 VStack(alignment: .leading, spacing: 6) {
115 Text("A fresh take on your Studio").font(.system(size: 21, weight: .semibold))
116 Text("Choose what to randomize across your Studio.")
117 .font(.system(size: 13)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)
118 }
119 }
120 VStack(alignment: .leading, spacing: 14) {
121 HStack {
122 Label("Entire timeline", systemImage: "rectangle.split.3x1")
123 .font(.system(size: 13, weight: .semibold))
124 Spacer()
125 Text("\(studio.segments.count) sections").font(.system(size: 12, weight: .medium)).monospacedDigit()
126 .foregroundStyle(accent).padding(.horizontal, 10).padding(.vertical, 5)
127 .background(accent.opacity(0.1), in: Capsule())
128 }
129 Divider().overlay(.white.opacity(0.05))
130 VStack(alignment: .leading, spacing: 6) {
131 Toggle("Visualizers", isOn: $randomizeVisualizers).toggleStyle(StudioSwitchStyle())
132 .accessibilityLabel("Randomize timeline visualizers")
133 Text(library.pool.enabled ? "Use only your visualizer pool. Small pools repeat to fill the timeline." : "Use favorites first, then unused library visuals. Each visualizer appears once.")
134 .font(.system(size: 11)).foregroundStyle(.secondary)
135 }
136 VStack(alignment: .leading, spacing: 6) {
137 Toggle("Bar lengths", isOn: $randomizeBarLengths).toggleStyle(StudioSwitchStyle())
138 .accessibilityLabel("Randomize timeline bars")
139 .disabled(audio.selectedURL == nil)
140 Text("Choose lengths from 1–8 bars on the song’s beat grid.")
141 .font(.system(size: 11)).foregroundStyle(.secondary)
142 }
143 Divider().overlay(.white.opacity(0.05))
144 Label(randomizeBarLengths ? "Tail sections may be trimmed or repeated to fit the song." : (randomizeVisualizers ? "Your current visualizer choices will be replaced." : "Select at least one option to continue."), systemImage: "arrow.triangle.2.circlepath")
145 .font(.system(size: 12)).foregroundStyle(.white.opacity(0.85))
146 Label(randomizeBarLengths ? (randomizeVisualizers ? "Fresh looks replace visual settings. Your soundtrack stays." : "Visualizer order, soundtrack, and saved settings stay.") : "Fresh looks replace visual settings. Timing and soundtrack stay.", systemImage: "checkmark.circle")
147 .font(.system(size: 12)).foregroundStyle(.secondary)
148 }.padding(16).frame(maxWidth: .infinity, alignment: .leading)
149 .background(.white.opacity(0.045), in: RoundedRectangle(cornerRadius: 14))
150 .overlay(RoundedRectangle(cornerRadius: 14).strokeBorder(.white.opacity(0.08)))
151 HStack(spacing: 10) {
152 Button("Cancel") { confirmRandomizeTimeline = false }
153 .buttonStyle(StudioButtonStyle()).keyboardShortcut(.cancelAction)
154 Spacer()
155 Button {
156 guard !exporting, !studio.segments.isEmpty else { return }
157 confirmRandomizeTimeline = false
158 audio.pause()
159 if randomizeBarLengths {
160 guard let grid = audio.segmentPlan(beatsPerSection: 4) else { return }
161 if audio.previewSectionStart != nil { audio.seek(fraction: audio.progress) }
162 choosingSegment = nil; favoritesSegment = nil
163 guard studio.randomizeBars(grid: grid, render: render) else { return }
164 }
165 if randomizeVisualizers, !studio.randomizeTimeline(render) { randomizeCapacityError = true }
166 } label: { Label("Randomize timeline", systemImage: "shuffle") }
167 .buttonStyle(StudioButtonStyle(treatment: .primary))
168 .disabled(exporting || studio.segments.isEmpty || (!randomizeVisualizers && !randomizeBarLengths))
169 }
170 }.padding(28).frame(width: 490)
171 .background(Color(red: 0.115, green: 0.095, blue: 0.14))
172 .tint(accent)
173 .onAppear { randomizeVisualizers = true; randomizeBarLengths = false }
174 }
175
176 private var commonSettings: some View {
177 VStack(alignment: .leading, spacing: 18) {
178 Label("Apply settings to all", systemImage: "slider.horizontal.3").font(.title2)
179 Text("Choose what to share across all \(ProjectMPresets.shared.availableScenes.count) visualizers and every Studio section. Unselected settings keep their individual values.")
180 .font(.system(size: 13)).foregroundStyle(.secondary)
181 ScrollView {
182 VStack(alignment: .leading, spacing: 18) {
183 VStack(alignment: .leading, spacing: 8) {
184 HStack {
185 Toggle("Bars per section", isOn: $includeBars).toggleStyle(StudioSwitchStyle())
186 .accessibilityLabel("Apply bars to all Studio sections")
187 Spacer()
188 barStepper(value: $commonBars, label: "Bars for all Studio sections")
189 .disabled(!includeBars)
190 }
191 Text("Set every card to this length. Later cards shift to the beat grid; the last ends with the soundtrack.")
192 .font(.system(size: 11)).foregroundStyle(.secondary)
193 }.disabled(studio.segments.isEmpty || audio.selectedURL == nil)
194 Divider()
195 commonControl("Chaos", included: $includeChaos, value: $commonChaos, range: 0...1,
196 help: "How strongly shapes react to music. Zero keeps procedural motion.")
197 commonControl("Zoom speed", included: $includeZoomSpeed, value: $commonZoomSpeed, range: 0...3,
198 help: "Forward travel speed. Zero keeps the framing flat.")
199 commonControl("Motion speed", included: $includeMotionSpeed, value: $commonMotionSpeed, range: 0.05...3,
200 help: "Base animation speed before the music response.")
201 Divider()
202 strobeSettings
203 }.padding(.trailing, 12)
204 }.frame(height: 470)
205 HStack {
206 Button("Cancel") { showCommonSettings = false }.buttonStyle(StudioButtonStyle())
207 .keyboardShortcut(.cancelAction)
208 Spacer()
209 Button("Apply selected settings") {
210 if includeBars { changeBars(commonBars) }
211 studio.applyCommonSettings(chaos: includeChaos ? commonChaos : nil,
212 zoomSpeed: includeZoomSpeed ? commonZoomSpeed : nil,
213 motionSpeed: includeMotionSpeed ? commonMotionSpeed : nil,
214 strobeEnabled: strobeAction == .keep ? nil : strobeAction == .add,
215 strobeSensitivity: strobeAction == .add ? commonStrobeSensitivity : nil,
216 strobeStrength: strobeAction == .add ? commonStrobeStrength : nil, render: render)
217 showCommonSettings = false
218 }.buttonStyle(StudioButtonStyle(treatment: .primary)).keyboardShortcut(.defaultAction)
219 .disabled(!includeBars && !includeChaos && !includeZoomSpeed && !includeMotionSpeed && strobeAction == .keep)
220 }
221 }.padding(28).frame(width: 500).tint(accent).disabled(exporting)
222 .onAppear {
223 includeBars = false
224 commonBars = studio.barsPerSection
225 commonChaos = render.chaos
226 commonZoomSpeed = render.zoomSpeed
227 commonMotionSpeed = render.speed
228 strobeAction = .keep
229 commonStrobeSensitivity = render.strobeSensitivity
230 commonStrobeStrength = render.strobeStrength
231 }
232 }
233
234 private var strobeSettings: some View {
235 VStack(alignment: .leading, spacing: 12) {
236 Label("Hi-hat strobe", systemImage: "bolt.fill").font(.headline)
237 HStack(spacing: 6) {
238 ForEach(StrobeAction.allCases, id: \.self) { action in
239 Button { strobeAction = action } label: {
240 HStack(spacing: 4) {
241 if strobeAction == action { Image(systemName: "checkmark") }
242 Text(action.rawValue)
243 }.frame(maxWidth: .infinity)
244 }.buttonStyle(StudioButtonStyle(treatment: strobeAction == action ? .accent : .secondary, compact: true))
245 .accessibilityLabel("\(action.rawValue) hi-hat strobe")
246 .accessibilityAddTraits(strobeAction == action ? .isSelected : [])
247 }
248 }
249 Text(strobeAction == .remove ? "Turn strobe off everywhere and retain individual flash settings." : "Apply all enables strobe everywhere with the settings below.")
250 .font(.system(size: 11)).foregroundStyle(.secondary)
251 VStack(alignment: .leading, spacing: 8) {
252 HStack { Text("Strobe sensitivity"); Spacer(); Text(commonStrobeSensitivity, format: .number.precision(.fractionLength(2))).monospacedDigit() }
253 Slider(value: $commonStrobeSensitivity, in: 0.25...4).accessibilityLabel("Strobe sensitivity for all visualizers")
254 Text("Higher sensitivity includes softer hi-hat hits.").font(.system(size: 11)).foregroundStyle(.secondary)
255 }.disabled(strobeAction != .add).opacity(strobeAction == .add ? 1 : 0.5)
256 VStack(alignment: .leading, spacing: 8) {
257 HStack { Text("Flash strength"); Spacer(); Text(commonStrobeStrength, format: .percent.precision(.fractionLength(0))).monospacedDigit() }
258 Slider(value: $commonStrobeStrength, in: 0.1...1).accessibilityLabel("Flash strength for all visualizers")
259 }.disabled(strobeAction != .add).opacity(strobeAction == .add ? 1 : 0.5)
260 Text("Flashes follow hi-hat attacks. Zero Chaos keeps flashes off.").font(.system(size: 11)).foregroundStyle(.secondary)
261 }
262 }
263
264 private func commonControl(_ title: LocalizedStringKey, included: Binding<Bool>, value: Binding<Float>, range: ClosedRange<Float>, help: LocalizedStringKey) -> some View {
265 VStack(alignment: .leading, spacing: 8) {
266 HStack {
267 Toggle(title, isOn: included).toggleStyle(StudioSwitchStyle())
268 .accessibilityLabel("Apply \(Text(title)) to all visualizers")
269 Spacer()
270 Text(value.wrappedValue, format: .number.precision(.fractionLength(2))).monospacedDigit()
271 .foregroundStyle(included.wrappedValue ? .primary : .secondary)
272 }
273 Slider(value: value, in: range).disabled(!included.wrappedValue)
274 .accessibilityLabel("\(Text(title)) for all visualizers")
275 Text(help).font(.system(size: 11)).foregroundStyle(.secondary)
276 }
277 }
278
279 private func segmentCard(_ segment: StudioSegment, index: Int) -> some View {
280 let selected = studio.selectedSegment == index
281 let palette = VisualPalette(rawValue: studio.presets[segment.scene]?.palette ?? 0) ?? .ultraviolet
282 return ZStack(alignment: .topTrailing) {
283 Button {
284 choosingSegment = nil
285 preview(segment)
286 } label: {
287 VStack(alignment: .leading, spacing: 10) {
288 HStack {
289 Text("\(time(segment.start)) – \(time(segment.end))").monospacedDigit()
290 Spacer()
291 }.font(.system(size: 11)).foregroundStyle(selected ? accent : .white.opacity(0.7)).frame(height: 36).padding(.trailing, 174)
292 HStack(spacing: 6) {
293 Image(systemName:ProjectMPresets.shared.icon(for:segment.scene)).font(.system(size:14, weight:.light)).foregroundStyle(accent)
294 Text(RenderState.sceneNames[segment.scene]).font(.system(size: 12, weight: .semibold)).lineLimit(1)
295 Spacer(minLength: 0)
296 }.foregroundStyle(.white.opacity(0.92)).frame(minHeight: 28).padding(.trailing, 152)
297 StudioSectionProgress(audio: audio, segment: segment, selected: selected, palette: palette)
298 }.padding(12).frame(width: 364)
299 .background(selected ? accent.opacity(0.08) : Color.white.opacity(0.025), in: RoundedRectangle(cornerRadius: 10))
300 .overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(selected ? accent.opacity(0.6) : .white.opacity(0.09)))
301 .contentShape(RoundedRectangle(cornerRadius: 10))
302 }.buttonStyle(.plain)
303 .accessibilityLabel("Section \(index + 1) visualizer, \(RenderState.sceneNames[segment.scene]), \(time(segment.start)) to \(time(segment.end))")
304 .help("Select this section; keep playing if playback is running, or preview while paused")
305 HStack(spacing: 6) {
306 barStepper(value: Binding(get: {studio.barCount(for: segment)}, set: {changeBars($0, at: index)}),
307 label: "Bars for section \(index + 1)")
308 .help("Set this card’s length in bars. Later cards shift; the last ends with the soundtrack.")
309 Button {
310 choosingSegment = nil
311 audio.playSection(start: segment.start, end: segment.end)
312 studio.follow(time: audio.playbackSeconds, render: render)
313 } label: {
314 Image(systemName: audio.isPlaying && audio.previewSectionStart == segment.start ? "pause.fill" : "play.fill")
315 .font(.system(size: 13, weight: .semibold)).frame(width: 44, height: 44)
316 .background(accent.opacity(0.14), in: RoundedRectangle(cornerRadius: 9))
317 .contentShape(Rectangle())
318 }.buttonStyle(.plain)
319 .accessibilityLabel("\(audio.isPlaying && audio.previewSectionStart == segment.start ? "Pause" : "Play") section \(index + 1)")
320 .help("Loop this section of the soundtrack and visualizer; click again to pause")
321 }.padding(6)
322 }.overlay(alignment: .bottomTrailing) {
323 HStack(spacing: 0) {
324 Button {
325 favoritesSegment = nil
326 preview(segment)
327 choosingSegment = choosingSegment == index ? nil : index
328 } label: {
329 Image(systemName: "chevron.down").font(.system(size: 11, weight: .semibold))
330 .frame(width: 32, height: 44).contentShape(Rectangle())
331 }.buttonStyle(.plain)
332 .accessibilityLabel("Choose visualizer for section \(index + 1)")
333 .help("Change this section’s visualizer")
334 Button {
335 choosingSegment = nil
336 studio.randomizeSegment(at: index, render: render)
337 replay(segment)
338 studio.requestVisualizerReveal()
339 } label: {
340 Image(systemName: "shuffle").font(.system(size: 13, weight: .medium))
341 .frame(width: 44, height: 44).contentShape(Rectangle())
342 }.buttonStyle(.plain)
343 .accessibilityLabel("Random visualizer for section \(index + 1)")
344 .help("Choose a different visualizer and replay this section")
345 Button {
346 choosingSegment = nil
347 studio.randomizeVisuals(at: index, render: render)
348 replay(segment)
349 studio.requestVisualizerReveal()
350 } label: {
351 Image(systemName: "dice.fill").font(.system(size: 16, weight: .medium))
352 .frame(width: 44, height: 44).contentShape(Rectangle())
353 }.buttonStyle(.plain)
354 .accessibilityLabel("Randomize visual style for section \(index + 1)")
355 .help("Roll shared style settings and replay this section; all sections using this visualizer update")
356 Button {
357 choosingSegment = nil
358 favoritesSegment = favoritesSegment == index ? nil : index
359 } label: {
360 Image(systemName: "heart").font(.system(size: 15, weight: .medium))
361 .foregroundStyle(favoritesSegment == index ? accent : .white.opacity(0.85))
362 .frame(width: 44, height: 44).contentShape(Rectangle())
363 }.buttonStyle(.plain)
364 .accessibilityLabel("Choose favorite visualizer for section \(index + 1)")
365 .help("Choose one of your favorites for this section")
366 .popover(isPresented: Binding(get: {favoritesSegment == index}, set: {if !$0 && favoritesSegment == index {favoritesSegment = nil}}), arrowEdge: .top) {
367 StudioFavoritesPicker(selected: segment.scene) { scene in
368 guard studio.segments.indices.contains(index) else {favoritesSegment = nil; return}
369 studio.assignScene(scene, at: index, render: render)
370 favoritesSegment = nil
371 preview(studio.segments[index])
372 }
373 }
374 }.padding(.trailing, 6).padding(.bottom, 11)
375 }
376 }
377 private func scenePicker(_ segment: StudioSegment, index: Int) -> some View {
378 VisualizerBrowser(selected: segment.scene, heading:"Choose visualizer · Section \(index + 1)", appearance: { studio.presets[$0] ?? VisualPreset.defaults(for: $0) }) { scene in
379 guard studio.segments.indices.contains(index) else {choosingSegment = nil; return}
380 studio.assignScene(scene, at: index, render: render)
381 preview(studio.segments[index])
382 choosingSegment = nil
383 }
384 }
385
386 private func barStepper(value: Binding<Int>, label: LocalizedStringKey) -> some View {
387 HStack(spacing: 0) {
388 Button { value.wrappedValue -= 1 } label: {
389 Image(systemName: "minus").font(.system(size: 10, weight: .semibold))
390 .frame(width: 44, height: 44).contentShape(Rectangle())
391 }.buttonStyle(.plain).disabled(value.wrappedValue <= 1)
392 .accessibilityLabel("Fewer \(Text(label))")
393 VStack(spacing: 1) {
394 TextField("Bars", value: value, format: .number.grouping(.never))
395 .textFieldStyle(.plain).font(.system(size: 12, weight: .semibold)).multilineTextAlignment(.center)
396 .accessibilityLabel(label)
397 Text("bars").font(.system(size: 9)).foregroundStyle(.secondary).accessibilityHidden(true)
398 }.frame(width: 34)
399 Button { value.wrappedValue += 1 } label: {
400 Image(systemName: "plus").font(.system(size: 10, weight: .semibold))
401 .frame(width: 44, height: 44).contentShape(Rectangle())
402 }.buttonStyle(.plain).disabled(value.wrappedValue >= Int.max / 4)
403 .accessibilityLabel("More \(Text(label))")
404 }.background(.white.opacity(0.045), in: RoundedRectangle(cornerRadius: 9))
405 }
406
407 private func changeBars(_ value: Int, at index: Int? = nil) {
408 let bars = max(1, min(Int.max / 4, value))
409 if let index, studio.segments.indices.contains(index), studio.barCount(for: studio.segments[index]) == bars { return }
410 guard let grid = audio.segmentPlan(beatsPerSection: 4) else { return }
411 audio.pause()
412 if audio.previewSectionStart != nil { audio.seek(fraction: audio.progress) }
413 choosingSegment = nil; favoritesSegment = nil
414 studio.setBars(bars, at: index, grid: grid, render: render)
415 studio.follow(time: audio.playbackSeconds, render: render)
416 }
417 private func replay(_ segment: StudioSegment) {
418 audio.playSection(start: segment.start, end: segment.end, restart: true)
419 studio.follow(time: audio.playbackSeconds, render: render)
420 }
421 private func preview(_ segment: StudioSegment) {
422 audio.selectSection(start: segment.start, end: segment.end)
423 studio.follow(time: segment.start, render: render)
424 }
425 private func time(_ seconds: Double) -> String { String(format: "%d:%02d", Int(seconds) / 60, Int(seconds) % 60) }
426}
427
428@MainActor
429private struct StudioFavoritesPicker: View {
430 @ObservedObject private var library = ProjectMPresets.shared
431 let selected: Int
432 let choose: (Int) -> Void
433 private var favorites: [Int] {
434 library.eligibleScenes.filter {library.isFavorite($0)}
435 }
436
437 var body: some View {
438 let scenes = favorites
439 VStack(alignment: .leading, spacing: 8) {
440 Label("Favorites", systemImage: "heart.fill").font(.system(size: 13, weight: .semibold))
441 .foregroundStyle(Color(red: 0.95, green: 0.68, blue: 0.55)).padding(.horizontal, 8)
442 if scenes.isEmpty {
443 Text("Tap a visualizer’s heart in the Library to add it here.")
444 .font(.system(size: 12)).foregroundStyle(.secondary).padding(8)
445 } else {
446 ScrollView {
447 LazyVStack(spacing: 3) {
448 ForEach(scenes, id: \.self) { scene in
449 Button {choose(scene)} label: {
450 HStack(spacing: 10) {
451 Image(systemName: library.icon(for: scene)).frame(width: 22)
452 .foregroundStyle(.orange.opacity(0.85))
453 Text(RenderState.sceneNames[scene]).font(.system(size: 12, weight: .medium)).lineLimit(1)
454 Spacer(minLength: 0)
455 if scene == selected {Image(systemName: "checkmark").foregroundStyle(.orange)}
456 }.padding(.horizontal, 10).frame(maxWidth: .infinity, minHeight: 44)
457 .background(scene == selected ? Color.orange.opacity(0.12) : .white.opacity(0.04), in: RoundedRectangle(cornerRadius: 7))
458 .contentShape(Rectangle())
459 }.buttonStyle(.plain).accessibilityLabel("Use favorite \(RenderState.sceneNames[scene])")
460 }
461 }
462 }.frame(height: min(CGFloat(scenes.count) * 47, 330))
463 }
464 }.padding(12).frame(width: 290)
465 }
466}
467
468/// Only the progress fill observes the audio clock; cards change at section boundaries.
469@MainActor
470private struct StudioSectionProgress: View {
471 let audio: AudioController
472 let segment: StudioSegment
473 let selected: Bool
474 let palette: VisualPalette
475 @State private var playbackRevision = 0
476 var body: some View {
477 let _ = playbackRevision
478 let elapsed = min(1, max(0, (audio.playbackSeconds - segment.start) / (segment.end - segment.start)))
479 GeometryReader { space in
480 ZStack(alignment: .leading) {
481 Capsule().fill(.white.opacity(0.07))
482 Capsule().fill(LinearGradient(colors: palette.stops.map { Color(red: Double($0.x), green: Double($0.y), blue: Double($0.z)) }, startPoint: .leading, endPoint: .trailing))
483 .frame(width: selected ? max(3, space.size.width * elapsed) : space.size.width)
484 }
485 }.frame(height: 3)
486 .onReceive(audio.visualizationUpdated.throttle(for: .milliseconds(33), scheduler: RunLoop.main, latest: true)) {
487 if selected { playbackRevision &+= 1 }
488 }
489 }
490}