diff --git a/Stream/DynamicDetentSheet.swift b/Stream/DynamicDetentSheet.swift new file mode 100644 index 0000000..c792d44 --- /dev/null +++ b/Stream/DynamicDetentSheet.swift @@ -0,0 +1,219 @@ +import SwiftUI + +/// Controllable-speed animation for a bottom sheet's height. +/// +/// There are two ways to move a sheet between detents and they honor a custom curve +/// differently. Animating the `CGFloat` behind a single `.height()` detent honors an +/// arbitrary spring/duration reliably (SwiftUI interpolates the value under your +/// transaction and re-applies the detent every frame). Changing a bound +/// `PresentationDetent` (the `selection:` form) only *loosely* honors it — the +/// inter-detent resize uses `UISheetPresentationController`'s own system spring. +/// +/// `DynamicDetentSheetModel` therefore owns the measured, content-hugging height and +/// animates every resize with a caller-supplied curve via the value-animated path. +/// `SelectableDetentSheet` wraps the selection form for the fixed `.medium`/`.large` +/// case, where the system spring is fine. +/// +/// iOS 17+ (`@Observable`, `withAnimation(_:completion:)`); the scroll measurement +/// primitive is iOS 18+ with a `GeometryReader` fallback for older content. + +// MARK: - DynamicDetentSheetModel + +@MainActor +@Observable +final class DynamicDetentSheetModel { + + /// The height committed to the sheet's `.height()` detent. Only the + /// `DynamicHeightDetent` modifier body reads this, so a resize invalidates just + /// that modifier — not the whole sheet body. + private(set) var detentHeight: CGFloat + + /// The single curve that drives every resize. The caller owns it fully — set a + /// slower/heavier spring here to fix a "too fast" resize. + var animation: Animation + + /// Fixed chrome (nav bar/header + grabber + home-indicator inset) added on top of + /// measured CONTENT height so the sheet is exactly tall enough and never clips. + var chrome: CGFloat + + /// Floor so a nearly-empty pane never collapses to a sliver. + var minimumContentHeight: CGFloat + + /// Cached measured content heights, keyed by each pane's OWN identity. Background + /// panes populate this WITHOUT resizing. We store the numeric height because you + /// cannot read the `CGFloat` back out of a `PresentationDetent`, and we need it + /// for the >= 1pt threshold that breaks the measurement feedback loop. + private var measured: [AnyHashable: CGFloat] = [:] + + /// Identity of the pane currently ON TOP. Only its measurements resize the sheet. + private var activeKey: AnyHashable? + + /// First sizing snaps (clean present at the right height); later ones animate. + private var hasSettled = false + + /// True while an animated resize is in flight. Guards against a mid-flight + /// re-measure restarting the spring; cleared (and reconciled) on real completion. + private var isResizing = false + + init(initialHeight: CGFloat = 320, + chrome: CGFloat = 0, + minimumContentHeight: CGFloat = 0, + animation: Animation = .spring(duration: 0.45, bounce: 0.1)) { + self.detentHeight = initialHeight + self.chrome = chrome + self.minimumContentHeight = minimumContentHeight + self.animation = animation + } + + private func resolved(_ content: CGFloat) -> CGFloat { + max(minimumContentHeight, content) + chrome + } + + /// Raw measurement from a pane's scroll/intrinsic geometry. Cheap + idempotent: + /// rounded, thresholded, cached under the pane's key, and it only commits an + /// ANIMATED resize when the reporting pane is the ACTIVE one. A late measurement + /// of an off-screen pane can therefore never kick off a competing resize. + func report(height rawContent: CGFloat, for key: Key) { + let rounded = rawContent.rounded() + let k = AnyHashable(key) + if let existing = measured[k], abs(existing - rounded) < 1 { return } // dedup + measured[k] = rounded + + guard k == activeKey else { return } // background pane: cache only + guard !isResizing else { return } // don't restart mid-flight — settle() reconciles + commit(resolved(rounded)) + } + + /// Switch the on-top pane AND resize to its cached height. Call this INSIDE + /// `animatingResize` together with your content change (e.g. `selected = section`) + /// so the content transition and the resize start as ONE motion. Falls back to the + /// current height when the incoming pane was never measured (first open is a single + /// two-step: transition now, exact fit on the pane's first measurement). + func activate(_ key: Key) { + let k = AnyHashable(key) + activeKey = k + detentHeight = resolved(measured[k] ?? (detentHeight - chrome)) + } + + /// Run `changes` (your content transition + `activate`, or an in-place resize) + /// under the model's curve, and clear the in-flight guard on the animation's REAL + /// completion, reconciling any measurement that landed mid-flight. Put the detent + /// change AND any in-sheet `.transition` change in the same `changes` closure so + /// they ride one transaction and never fight. + func animatingResize(_ changes: () -> Void) { + isResizing = true + // The completion runs on the main run loop; the model is @MainActor, so hop + // back into isolation to reconcile. + withAnimation(animation) { + changes() + } completion: { + MainActor.assumeIsolated { self.settle() } + } + } + + private func commit(_ target: CGFloat) { + guard abs(target - detentHeight) >= 1 else { return } + if hasSettled { + animatingResize { self.detentHeight = target } + } else { + hasSettled = true + detentHeight = target // clean present: snap, no launch animation + } + } + + /// Completion hook: drop the in-flight guard, then commit any measurement that + /// arrived (and was cached but skipped) while the last resize was animating. + private func settle() { + isResizing = false + guard let k = activeKey, let latest = measured[k] else { return } + commit(resolved(latest)) + } +} + +// MARK: - Dynamic-height detent modifier (curve honored) + +/// Applies a single content-hugging `.height()` detent driven by the model. Only THIS +/// body reads `model.detentHeight`, so an animated height change re-evaluates only the +/// modifier and rides whatever transaction mutated the height. +struct DynamicHeightDetent: ViewModifier { + let model: DynamicDetentSheetModel + var dragIndicator: Visibility = .visible + + func body(content: Content) -> some View { + content + .presentationDetents([.height(model.detentHeight)]) + .presentationDragIndicator(dragIndicator) + } +} + +extension View { + /// Drive this sheet's height from a `DynamicDetentSheetModel` (curve-controlled). + func dynamicHeightDetents(_ model: DynamicDetentSheetModel, + dragIndicator: Visibility = .visible) -> some View { + modifier(DynamicHeightDetent(model: model, dragIndicator: dragIndicator)) + } + + /// Report a SCROLLABLE pane's real content height under `key` (iOS 18+). Feedback + /// free: `contentSize` is INTRINSIC, so resizing the sheet does not change it — the + /// "update multiple times per frame" loop cannot form. + @available(iOS 18.0, *) + func measuredDetentHeight( + _ key: Key, into model: DynamicDetentSheetModel + ) -> some View { + onScrollGeometryChange(for: CGFloat.self) { $0.contentSize.height } action: { _, height in + model.report(height: height, for: key) + } + } + + /// Measure NON-scroll / intrinsic content, or an iOS 16–17 fallback for the scroll + /// case. A background `GeometryReader` never joins layout, so it cannot create a loop. + func measuredIntrinsicDetentHeight( + _ key: Key, into model: DynamicDetentSheetModel + ) -> some View { + background( + GeometryReader { proxy in + Color.clear + .onAppear { model.report(height: proxy.size.height, for: key) } + .onChange(of: proxy.size.height) { _, h in + model.report(height: h, for: key) + } + } + ) + } +} + +// MARK: - Selection-binding detents (fixed .medium/.large; curve NOT precisely honored) + +/// Wraps the `presentationDetents(_:selection:)` API for the FIXED-detent case: a +/// `Binding`. Changing `selection` inside `withAnimation` animates, +/// but the resize uses the system spring, so a custom duration/curve is only loosely +/// applied — use `DynamicDetentSheetModel` when you need a dialable curve. +/// +/// INVARIANT: the set handed to SwiftUI ALWAYS contains the current selection, so a +/// programmatic selection can never point outside the set and trigger the "selected +/// detent not in Set" fallback-snap. +struct SelectableDetentSheet: ViewModifier { + let detents: Set + @Binding var selection: PresentationDetent + var dragIndicator: Visibility = .visible + + private var resolvedDetents: Set { detents.union([selection]) } + + func body(content: Content) -> some View { + content + .presentationDetents(resolvedDetents, selection: $selection) + .presentationDragIndicator(dragIndicator) + } +} + +extension View { + /// Snap between fixed detents with a `Binding`. The custom curve is delegated to + /// the system spring (see `SelectableDetentSheet`). + func selectableDetents(_ detents: Set, + selection: Binding, + dragIndicator: Visibility = .visible) -> some View { + modifier(SelectableDetentSheet(detents: detents, + selection: selection, + dragIndicator: dragIndicator)) + } +} diff --git a/Stream/SettingsView.swift b/Stream/SettingsView.swift index 9a7e0b0..9dd7be4 100644 --- a/Stream/SettingsView.swift +++ b/Stream/SettingsView.swift @@ -2,6 +2,7 @@ import SwiftUI import Observation import AVFAudio import StreamCore +import UIKit import os /// The settings sections. Each is launched from the settings list into its own @@ -114,77 +115,67 @@ struct SettingsView: View { /// Dismisses the whole settings drawer (the "Done" affordance). @Environment(\.dismiss) private var dismiss - /// Navigation stack path, tracked so the sheet height can follow the view on - /// top (the launcher, or a pushed section). - @State private var path: [SettingsSection] = [] - /// Real content height of the launcher list, read from its scroll geometry. - @State private var launcherHeight: CGFloat = 300 - /// Real content height of each pushed section's form, keyed by section. - @State private var sectionHeights: [SettingsSection: CGFloat] = [:] - /// The live detent height. Animated toward `targetHeight` on every push/pop or - /// in-section content change so the drawer glides between sizes instead of - /// snapping. Driving the `.height()` detent from state changed inside - /// `withAnimation` is what makes the sheet resize animate. - @State private var sheetHeight: CGFloat = 420 - - /// Chrome around the scrolling content: the inline nav bar + grabber on top - /// and the home-indicator safe area on the bottom. Added to the measured - /// content height so the drawer is exactly tall enough and never clips. - private static let sheetChrome: CGFloat = 92 - - /// The height the drawer should settle at: the on-top view's measured content - /// height (clamped to a sane floor) plus chrome. `.height()` caps it at the - /// available space, so unusually tall sections simply scroll. - private var targetHeight: CGFloat { - let content = path.last.flatMap { sectionHeights[$0] } ?? launcherHeight - return max(160, content) + Self.sheetChrome - } + /// The section currently shown, or `nil` for the launcher. Not a full stack — + /// the drawer is exactly two levels deep (launcher → one section), so a single + /// optional models it. Owning the level ourselves (instead of a NavigationStack + /// push) lets ONE `withAnimation` drive the content morph and the detent resize + /// together as a single motion. + @State private var selected: SettingsSection? + + /// Owns the content-sized detent and animates every resize with ITS curve, and — + /// crucially — guards a late re-measurement from restarting the spring mid-resize + /// (the real cause of the height feeling "desynced"). The resize speed lives in + /// this one initializer: 0.45s reads as settled where the old 0.3s outran the slide. + @State private var detent = DynamicDetentSheetModel( + initialHeight: 420, + chrome: 100, // nav bar + grabber + home-indicator inset + minimumContentHeight: 160, // floor so a short section never collapses + animation: .spring(duration: 0.45, bounce: 0.1) + ) var body: some View { - NavigationStack(path: $path) { - List { - Section { - ForEach(SettingsSection.allCases) { section in - NavigationLink(value: section) { - sectionRow(section) - } - } - } footer: { - Text("Tap a section to adjust it. Changes save automatically.") + // A NavigationStack purely for the system Liquid Glass chrome — the glass nav + // bar, glass toolbar buttons, and inline title. It does NOT push via the nav + // stack: the launcher and section are swapped with a directional slide + // (section in from trailing / launcher out to leading = a forward push; the + // reverse on back = a pop), driven by our own `withAnimation` so the slide + // and the detent resize ride the same transaction. + NavigationStack { + ZStack(alignment: .top) { + if let section = selected { + sectionDetail(section) + .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top) + .transition(.move(edge: .trailing)) + } else { + launcherPane + .transition(.move(edge: .leading)) } } - .onScrollGeometryChange(for: CGFloat.self) { $0.contentSize.height } action: { _, height in - let rounded = height.rounded() - if abs(rounded - launcherHeight) >= 1 { launcherHeight = rounded } - } - .navigationTitle("Settings") + // Measure every section's height off-screen so the FIRST open resizes + // in lockstep with the slide, not a beat after it. + .background(sectionHeightPrewarm) + .navigationTitle(selected?.title ?? "Settings") .navigationBarTitleDisplayMode(.inline) - .navigationDestination(for: SettingsSection.self) { section in - sectionDetail(section) - } .toolbar { + if selected != nil { + ToolbarItem(placement: .topBarLeading) { + Button { back() } label: { Image(systemName: "chevron.left") } + .accessibilityLabel("Back") + } + } ToolbarItem(placement: .topBarTrailing) { Button("Done") { Haptics.tap(); dismiss() } } } } - .presentationDetents([.height(sheetHeight)]) - .presentationDragIndicator(.visible) + .dynamicHeightDetents(detent) // curve-controlled height + drag indicator .presentationCornerRadius(55) - // Haptic when a section row is tapped (push) or dismissed (pop). - .sensoryFeedback(.impact(weight: .light), trigger: path) - .onChange(of: targetHeight) { _, newHeight in - guard abs(newHeight - sheetHeight) >= 1 else { return } - // Defer to the next runloop tick so the animated detent change doesn't - // re-enter layout within the same frame (which SwiftUI flags as - // "tried to update multiple times per frame"). - Task { @MainActor in - withAnimation(.snappy(duration: 0.32, extraBounce: 0.04)) { - sheetHeight = newHeight - } - } - } + // Haptic when a section is opened (push) or closed (pop). + .sensoryFeedback(.impact(weight: .light), trigger: selected) .onAppear { + // Launcher is the active pane on present; in-place field growth then + // animates automatically via each pane's measuredDetentHeight report. + detent.activate(SettingsSection?.none) // Enumerate inputs/capabilities so the launcher summaries are accurate; // the live mic meter only runs while the Audio detail is open. audio.refresh(requestPermission: false) @@ -193,6 +184,48 @@ struct SettingsView: View { } } + // MARK: - Drill-in navigation (custom, so the content morph + resize are one motion) + + /// Open a section: it slides in (push) and the drawer resizes to fit — both + /// inside ONE `withAnimation`, so they move as a single motion. + private func open(_ section: SettingsSection) { + // No explicit tap here: `.sensoryFeedback(trigger: selected)` already fires + // one light impact whenever `selected` changes. The slide (.transition) and the + // detent resize ride ONE transaction (detent.animation), so they move together. + detent.animatingResize { + selected = section + detent.activate(Optional(section)) + } + } + + /// Return to the launcher (the nav-bar back button). + private func back() { + // Haptic comes from `.sensoryFeedback(trigger: selected)` (see `open`). + detent.animatingResize { + selected = nil + detent.activate(SettingsSection?.none) + } + } + + // MARK: - Launcher pane + + private var launcherPane: some View { + List { + Section { + ForEach(SettingsSection.allCases) { section in + Button { open(section) } label: { + sectionRow(section) + } + .buttonStyle(.plain) + } + } footer: { + Text("Tap a section to adjust it. Changes save automatically.") + } + } + .scrollBounceBehavior(.basedOnSize) + .measuredDetentHeight(SettingsSection?.none, into: detent) // launcher's own identity + } + // MARK: - Launcher rows @ViewBuilder @@ -211,18 +244,27 @@ struct SettingsView: View { .foregroundStyle(.secondary) .lineLimit(1) } + Spacer(minLength: 8) + // Disclosure affordance the old NavigationLink drew for us. + Image(systemName: "chevron.right") + .font(.footnote.weight(.semibold)) + .foregroundStyle(.tertiary) } + .contentShape(Rectangle()) .accessibilityElement(children: .combine) + .accessibilityAddTraits(.isButton) } - // MARK: - Pushed section detail + // MARK: - Section detail body - /// One section's controls, pushed onto the settings navigation stack. The - /// single enclosing sheet (`presentationSizing(.form)` in `ContentView`) - /// resizes to fit whichever section's Form is on screen, and re-sizes as - /// fields appear/hide within it. + /// One section's controls — the Form that fills the section pane below its + /// header. The enclosing drawer resizes to fit whichever section is on screen + /// (via `sectionHeights` → `currentTarget`), and re-sizes as fields appear/hide + /// within it. + /// A section's Form (controls only), reused by both the visible detail and the + /// hidden height pre-warm — so measuring it off-screen triggers no side effects. @ViewBuilder - private func sectionDetail(_ section: SettingsSection) -> some View { + private func sectionForm(_ section: SettingsSection) -> some View { Form { switch section { case .connection: connectionSection @@ -233,22 +275,40 @@ struct SettingsView: View { case .chat: chatSection } } - .onScrollGeometryChange(for: CGFloat.self) { $0.contentSize.height } action: { _, height in - let rounded = height.rounded() - if abs(rounded - (sectionHeights[section] ?? 0)) >= 1 { sectionHeights[section] = rounded } - } - .navigationTitle(section.title) - .navigationBarTitleDisplayMode(.inline) .scrollBounceBehavior(.basedOnSize) - .onAppear { - guard section == .audio else { return } - micLevel.setGain(settings.micVolume) - micLevel.setPreferredInput(settings.preferredAudioInputUID) - micLevel.start() - } - .onDisappear { - if section == .audio { micLevel.stop() } + } + + /// One section's controls, shown in the detail pane: reports its height under its + /// own identity and runs the live mic meter only while the Audio detail is open. + private func sectionDetail(_ section: SettingsSection) -> some View { + sectionForm(section) + .measuredDetentHeight(Optional(section), into: detent) // this section's own identity + .onAppear { + guard section == .audio else { return } + micLevel.setGain(settings.micVolume) + micLevel.setPreferredInput(settings.preferredAudioInputUID) + micLevel.start() + } + .onDisappear { + if section == .audio { micLevel.stop() } + } + } + + /// Renders every section's Form once, hidden, so its content height is measured + /// and cached BEFORE its first open — then `open` resizes in lockstep with the + /// slide instead of a two-step (height jumping after the push). `report` only + /// CACHES for non-active panes (never resizes the sheet), and a `.background` + /// never affects the foreground's size. + private var sectionHeightPrewarm: some View { + ZStack { + ForEach(SettingsSection.allCases) { section in + sectionForm(section) + .measuredDetentHeight(Optional(section), into: detent) + } } + .opacity(0) + .allowsHitTesting(false) + .accessibilityHidden(true) } // MARK: - Launcher summaries