Commit 1fa68be3 authored by Kourser's avatar Kourser
Browse files

feat(player): a side panel on large screens, and a half-open iPhone Duo

On an iPad or an iPhone Duo open, the player now sits in a panel beside
the episodes instead of a sheet over them, and stays there while
browsing; it is remembered from one launch to the next. The mini bar
opens it and steps aside while it shows. It is a column of our own:
`.inspector` showed itself, empty, when the Duo was opened with nothing
playing.

In the panel, the transcript opens under a compact player rather than in
a sheet, follows the playback and starts at the line being said.

Standing half open on a table, the iPhone Duo gets the player on its
whole screen: artwork and title on the upright half, large controls on
the flat one, nothing on the fold. The hinge comes from onHingeChange,
the fold from the view's division reserved region (iOS 27.1); closed by
hand, it waits until the device is next set down.

For screenshots and tests (DEBUG): -uiTabletop simulates the fold, which
the simulator only does from Device Hub; -uiScreen player opens the panel
on a wide screen, -uiScreen transcript with its transcript; the demo
episode gains a transcript.

Checked on the iPhone Duo simulator: inner screen (panel, transcript,
tabletop) and outer screen (sheet, tabletop, portrait and landscape).

Co-Authored-By: default avatarClaude Opus 5.5 <noreply@anthropic.com>
parent 31fd9db0
Loading
Loading
Loading
Loading
+19 −1
Changes for Skingomz/AppModel.swift: 19 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -203,6 +203,23 @@ final class AppModel {
        let base = 1_750_000_000.0
        let demoChaptersJSON = "{\"chapters\":[{\"startTime\":0,\"title\":\"Introduction\"},{\"startTime\":600,\"title\":\"Analyse de la situation\"},{\"startTime\":1800,\"title\":\"Perspectives et conclusion\"}]}"
        let chaptersURL = URL(string: "data:application/json," + (demoChaptersJSON.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? ""))
        // A transcript too, for the player's panel (iPad, iPhone Duo open).
        let demoTranscript = [
            (0, "Bonjour à toutes et à tous, et bienvenue dans le Collimateur."),
            (8, "Aujourd'hui, on revient sur un conflit ancien, rarement raconté de ce côté de la Méditerranée."),
            (19, "Pour en parler, deux invités qui suivent la région depuis longtemps."),
            (31, "Commençons par le commencement : d'où vient la rivalité entre l'Algérie et le Maroc ?"),
            (46, "Il faut remonter à l'indépendance, et à la guerre des Sables de 1963."),
            (60, "La frontière n'avait jamais été vraiment fixée par la puissance coloniale."),
            (74, "Et la question du Sahara occidental s'y ajoute à partir de 1975."),
            (90, "Depuis, les deux pays se livrent une compétition diplomatique et militaire permanente."),
            (106, "Regardons les budgets de défense : ils ont doublé en quinze ans."),
            (121, "Ce qui frappe, c'est la nature des achats : avions, défense aérienne, drones."),
        ]
        let demoTranscriptJSON = "{\"segments\":[" + demoTranscript.map { start, body in
            "{\"startTime\":\(start),\"body\":\"\(body)\"}"
        }.joined(separator: ",") + "]}"
        let transcriptURL = URL(string: "data:application/json," + (demoTranscriptJSON.addingPercentEncoding(withAllowedCharacters: .alphanumerics) ?? ""))
        let episodes = titles.enumerated().map { i, title in
            Episode(
                guid: "demo-\(i)",
@@ -212,7 +229,8 @@ final class AppModel {
                enclosureURL: URL(string: "https://feeds.audiomeans.fr/demo/\(i).mp3"),
                duration: Double(3600 + i * 420),
                imageURL: artwork,
                chaptersURL: i == 0 ? chaptersURL : nil
                chaptersURL: i == 0 ? chaptersURL : nil,
                transcriptURL: i == 0 ? transcriptURL : nil
            )
        }
        guard let stored = try? await store.save(podcast: podcast, episodes: episodes) else { return }
+76
Changes for Skingomz/DeviceHinge.swift: 76 added lines, 0 removed lines.
Original line number Diff line number Diff line
import SwiftUI

// The iPhone Duo can stand half open, its lower half flat on a table and the
// upper half upright, like a small laptop: the "tabletop" posture. Listening
// in the kitchen or at the bedside, the player then puts what is playing on
// the upright half and large controls on the flat one, never across the fold.
//
// Two pieces of information make the posture: the hinge status (half open)
// from `onHingeChange`, read once at the root, and where the fold crosses a
// view, from its geometry (the "division" reserved region). The fold is
// horizontal in the tabletop posture; vertical, the device is held like a
// book and the usual layouts apply.

extension EnvironmentValues {
    /// The device's hinge is partially open (iPhone Duo, iOS 27.1+).
    @Entry var isHalfOpen = false
}

#if os(iOS)
extension View {
    /// Follows the hinge and shares whether it is half open below this view.
    func readsDeviceHinge() -> some View {
        modifier(DeviceHingeReader())
    }
}

private struct DeviceHingeReader: ViewModifier {
    @State private var isHalfOpen = false

    func body(content: Content) -> some View {
        Group {
            if #available(iOS 27.1, *) {
                content.onHingeChange { _, new in
                    isHalfOpen = new.hinge?.status == .partiallyOpen
                }
            } else {
                content
            }
        }
        .environment(\.isHalfOpen, isHalfOpen || TabletopSimulation.isOn)
    }
}

extension GeometryProxy {
    /// The fold across this view, in its own coordinates, when the device
    /// stands half open with the fold horizontal; nil otherwise.
    func tabletopFold(isHalfOpen: Bool) -> CGRect? {
        guard isHalfOpen else { return nil }
        if TabletopSimulation.isOn { return TabletopSimulation.fold(in: self) }
        guard #available(iOS 27.1, *) else { return nil }
        let bounds = CGRect(origin: .zero, size: size)
        // Inactive regions too: whether the region counts as active while the
        // hinge moves is the system's business; the status above decides.
        return reservedRegions(kind: .division, options: .includeInactive)
            .map(\.frame)
            .first { $0.width > $0.height && $0.intersects(bounds) }
    }
}

/// `-uiTabletop` (DEBUG): pretends the device stands half open, folded
/// across the middle of each view that asks — the root, the panel and the
/// full-screen player all span the window's height, so that is the window's
/// middle. The simulator folds only from Device Hub.
enum TabletopSimulation {
    #if DEBUG
    static let isOn = ProcessInfo.processInfo.arguments.contains("-uiTabletop")
    #else
    static let isOn = false
    #endif

    fileprivate static func fold(in proxy: GeometryProxy) -> CGRect {
        let band: CGFloat = 24
        return CGRect(x: 0, y: (proxy.size.height - band) / 2, width: proxy.size.width, height: band)
    }
}
#endif
+10 −4
Changes for Skingomz/NowPlayingBar.swift: 10 added lines, 4 removed lines.
Original line number Diff line number Diff line
@@ -11,6 +11,10 @@ struct NowPlayingBar: View {
    @Environment(PlaybackSettings.self) private var settings
    @State private var showingPlayer = false

    /// Opens the player somewhere else than in a sheet: the side panel of a
    /// large screen (iPad, iPhone Duo open).
    var openPlayer: (() -> Void)?

    private static let rates: [Float] = [0.8, 1.0, 1.2, 1.5, 1.8, 2.0, 2.5, 3.0]

    var body: some View {
@@ -58,9 +62,9 @@ struct NowPlayingBar: View {
            .sheet(isPresented: $showingPlayer) {
                PlayerView()
                    .environment(playback)
                    // On a large screen — an iPad, the iPhone Duo opened — a
                    // sheet is a centred card of reduced height: the player
                    // asks for the page size instead.
                    // Wide screens open the side panel instead; a large but
                    // narrow window (iPad split view) still gets a sheet, as a
                    // full page rather than a short centred card.
                    .presentationSizing(.page)
            }
            #endif
@@ -85,7 +89,9 @@ struct NowPlayingBar: View {
            Spacer(minLength: 4)
        }
        .contentShape(Rectangle())
        .onTapGesture { showingPlayer = true }
        .onTapGesture {
            if let openPlayer { openPlayer() } else { showingPlayer = true }
        }
        .help("Ouvrir le lecteur")
    }

+204 −31
Changes for Skingomz/PlayerView.swift: 204 added lines, 31 removed lines.
Original line number Diff line number Diff line
import SwiftUI
import PlaybackKit
import PodcastModel

/// Full-screen player presented when tapping the mini bar. Provides a draggable
/// position slider plus the usual transport controls.
/// The full player, opened from the mini bar. Provides a draggable position
/// slider plus the usual transport controls.
struct PlayerView: View {
    /// Where the player is shown.
    enum Presentation {
        /// A sheet over the app: iPhone, any narrow window, the Mac's popover.
        case sheet
        /// A panel beside the episodes: iPad, the iPhone Duo open.
        case panel
        /// The whole screen of an iPhone Duo standing half open.
        case tabletop
    }

    var presentation: Presentation = .sheet
    /// Closes the panel or the full-screen player; a sheet dismisses itself.
    var close: (() -> Void)?

    @Environment(PlaybackController.self) private var playback
    @Environment(AppModel.self) private var model
    @Environment(PlaybackSettings.self) private var settings
    @Environment(\.dismiss) private var dismiss
    @Environment(\.isHalfOpen) private var isHalfOpen

    @State private var isScrubbing = false
    @State private var scrubTime: Double = 0
    @State private var showingChapters = false
    @State private var showingTranscript = false
    @State private var showingTranscript = Self.opensWithTranscript

    private var artworkURL: URL? {
        playback.currentEpisode.flatMap { model.playerArtworkURL(for: $0) }
@@ -20,6 +36,11 @@ struct PlayerView: View {

    var body: some View {
        GeometryReader { proxy in
            if let fold = tabletopFold(proxy) {
                tabletopLayout(in: proxy.size, fold: fold)
            } else if showsTranscriptInPanel, let episode = playback.currentEpisode {
                panelWithTranscript(episode)
            } else {
                ScrollView {
                    Group {
                        if Self.isWide(proxy.size) {
@@ -35,10 +56,15 @@ struct PlayerView: View {
                // large text, or a window shorter than any iPhone.
                .scrollBounceBehavior(.basedOnSize)
            }
        }
        .sheet(isPresented: $showingChapters) {
            ChaptersListView()
        }
        .sheet(isPresented: $showingTranscript) {
        // In the panel the transcript opens in place, under the player.
        .sheet(isPresented: Binding(
            get: { showingTranscript && presentation != .panel },
            set: { showingTranscript = $0 }
        )) {
            if let episode = playback.currentEpisode {
                TranscriptView(episode: episode)
            }
@@ -124,6 +150,132 @@ struct PlayerView: View {
        return min(max(available, 96), 360, size.width * 0.38)
    }

    // MARK: Panel with the transcript

    /// `-uiScreen transcript` (DEBUG screenshots): the transcript open at once.
    private static var opensWithTranscript: Bool {
        #if DEBUG
        AppModel.uiDemoScreen == "transcript"
        #else
        false
        #endif
    }

    private var showsTranscriptInPanel: Bool {
        presentation == .panel && showingTranscript && hasTranscript
    }

    /// The transcript under a compact player, both beside the episode list:
    /// what is said, where the listening is, and what comes next.
    private func panelWithTranscript(_ episode: Episode) -> some View {
        VStack(spacing: 0) {
            VStack(spacing: 14) {
                HStack {
                    closeButton
                    Spacer()
                    transcriptButton
                        .buttonStyle(.bordered)
                }
                HStack(spacing: 12) {
                    ArtworkView(url: artworkURL, size: 64)
                    VStack(alignment: .leading, spacing: 4) {
                        Text(episode.title)
                            .font(.headline)
                            .lineLimit(2)
                        if hasChapters { chaptersButton }
                    }
                    Spacer(minLength: 0)
                }
                progress
                transport
                HStack(spacing: 28) {
                    rateMenu {
                        Label(Self.rateLabel(playback.playbackRate), systemImage: "gauge.with.dots.needle.67percent")
                            .font(.subheadline.weight(.medium))
                            .monospacedDigit()
                    }
                    secondaryControls
                }
            }
            .padding(20)
            Divider()
            TranscriptContent(episode: episode)
        }
    }

    // MARK: Tabletop

    private func tabletopFold(_ proxy: GeometryProxy) -> CGRect? {
        #if os(iOS)
        proxy.tabletopFold(isHalfOpen: isHalfOpen)
        #else
        nil
        #endif
    }

    /// Half open on a table: what is playing on the upright half, large
    /// controls on the flat half, within reach, and nothing on the fold.
    private func tabletopLayout(in size: CGSize, fold: CGRect) -> some View {
        let upper = max(fold.minY, 0)
        let lower = max(size.height - fold.maxY, 0)
        let side = size.width >= 560
        let artwork = side
            ? min(max(upper - 48, 64), 260)
            : min(max(upper - 130, 56), 200, size.width - 48)
        return VStack(spacing: 0) {
            Group {
                if side {
                    HStack(spacing: 24) {
                        ArtworkView(url: artworkURL, size: artwork)
                            .shadow(radius: 10, y: 6)
                        tabletopInfo(alignment: .leading)
                            .frame(maxWidth: 420, alignment: .leading)
                    }
                } else {
                    VStack(spacing: 12) {
                        ArtworkView(url: artworkURL, size: artwork)
                            .shadow(radius: 10, y: 6)
                        tabletopInfo(alignment: .center)
                    }
                }
            }
            .padding(.horizontal, 24)
            .frame(maxWidth: .infinity)
            .frame(height: upper)
            // The artwork reaches the leading corner; this one stays clear.
            .overlay(alignment: .topTrailing) {
                closeButton.padding(16)
            }

            // The fold itself.
            Spacer().frame(height: fold.height)

            VStack(spacing: 18) {
                progress
                    .frame(maxWidth: 560)
                transport(large: true)
                HStack(spacing: 32) {
                    speedControl
                    sleepMenu
                }
            }
            .padding(.horizontal, 24)
            .frame(maxWidth: .infinity)
            .frame(height: lower)
        }
    }

    private func tabletopInfo(alignment: HorizontalAlignment) -> some View {
        VStack(alignment: alignment, spacing: 10) {
            Text(playback.currentEpisode?.title ?? "")
                .font(.title2.weight(.semibold))
                .multilineTextAlignment(alignment == .leading ? .leading : .center)
                .lineLimit(3)
            if hasChapters { chaptersButton }
            if hasTranscript { transcriptButton }
        }
    }

    private var hasChapters: Bool { !model.currentChapters.isEmpty }
    private var hasTranscript: Bool { playback.currentEpisode?.transcriptURL != nil }

@@ -138,7 +290,12 @@ struct PlayerView: View {

            // Most feeds set artwork on the podcast, not per episode: the
            // artwork above falls back to the podcast's image.
            if hasChapters {
            if hasChapters { chaptersButton }
            if hasTranscript { transcriptButton }
        }
    }

    private var chaptersButton: some View {
        Button { showingChapters = true } label: {
            Label(model.currentChapter(at: playback.currentTime)?.title ?? "Chapitres",
                  systemImage: "list.bullet")
@@ -147,14 +304,13 @@ struct PlayerView: View {
        }
    }

            if hasTranscript {
                Button { showingTranscript = true } label: {
    /// Opens the transcript; in the panel, shows or hides it under the player.
    private var transcriptButton: some View {
        Button { showingTranscript.toggle() } label: {
            Label("Transcription", systemImage: "text.quote")
                .font(.subheadline)
        }
    }
        }
    }

    @ViewBuilder
    private var progress: some View {
@@ -176,13 +332,21 @@ struct PlayerView: View {

    private var header: some View {
        HStack {
            Button { dismiss() } label: {
                Image(systemName: "chevron.down")
            closeButton
            Spacer()
        }
    }

    private var closeButton: some View {
        Button {
            if let close { close() } else { dismiss() }
        } label: {
            // A sheet slides back down; the panel and the full screen close.
            Image(systemName: presentation == .sheet ? "chevron.down" : "xmark")
                .font(.title3.weight(.semibold))
        }
        .buttonStyle(.borderless)
            Spacer()
        }
        .accessibilityLabel("Fermer")
    }

    // MARK: Scrubber
@@ -226,19 +390,22 @@ struct PlayerView: View {
            .foregroundStyle(.red)
    }

    private var transport: some View {
        HStack(spacing: 44) {
    private var transport: some View { transport(large: false) }

    /// `large`: the flat half of a half-open iPhone Duo, out of arm's reach.
    private func transport(large: Bool) -> some View {
        HStack(spacing: large ? 64 : 44) {
            Button { playback.skipBackward(TimeInterval(settings.skipBackward)) } label: {
                Image(systemName: settings.backwardSymbol).font(.title)
                Image(systemName: settings.backwardSymbol).font(large ? .system(size: 44) : .title)
            }
            .help("Reculer de \(settings.skipBackward) s")
            Button { playback.togglePlayPause() } label: {
                Image(systemName: playback.isPlaying ? "pause.circle.fill" : "play.circle.fill")
                    .font(.system(size: 64))
                    .font(.system(size: large ? 96 : 64))
            }
            .help(playback.isPlaying ? "Pause" : "Lecture")
            Button { playback.skipForward(TimeInterval(settings.skipForward)) } label: {
                Image(systemName: settings.forwardSymbol).font(.title)
                Image(systemName: settings.forwardSymbol).font(large ? .system(size: 44) : .title)
            }
            .help("Avancer de \(settings.skipForward) s")
        }
@@ -251,19 +418,7 @@ struct PlayerView: View {
                Image(systemName: "minus.circle").font(.title3)
            }
            .help("Moins vite")
            Menu {
                ForEach(PlaybackSettings.rates, id: \.self) { rate in
                    Button {
                        playback.setRate(rate)
                    } label: {
                        if rate == playback.playbackRate {
                            Label(Self.rateLabel(rate), systemImage: "checkmark")
                        } else {
                            Text(Self.rateLabel(rate))
                        }
                    }
                }
            } label: {
            rateMenu {
                Text("Vitesse · \(Self.rateLabel(playback.playbackRate))")
                    .font(.subheadline.weight(.medium))
                    .monospacedDigit()
@@ -297,6 +452,24 @@ struct PlayerView: View {
        .frame(maxWidth: 280)
    }

    private func rateMenu(@ViewBuilder label: () -> some View) -> some View {
        Menu {
            ForEach(PlaybackSettings.rates, id: \.self) { rate in
                Button {
                    playback.setRate(rate)
                } label: {
                    if rate == playback.playbackRate {
                        Label(Self.rateLabel(rate), systemImage: "checkmark")
                    } else {
                        Text(Self.rateLabel(rate))
                    }
                }
            }
        } label: {
            label()
        }
    }

    /// Adjusts the rate by `delta`, snapped to 0.1 and clamped to 0.5×–3×.
    private func adjustRate(_ delta: Float) {
        let next = ((playback.playbackRate + delta) * 10).rounded() / 10
+90 −4
Changes for Skingomz/RootView.swift: 90 added lines, 4 removed lines.
Original line number Diff line number Diff line
@@ -24,6 +24,17 @@ struct RootView: View {
    @State private var sortOrder: SubscriptionSort = .recent
    @State private var tagFilter: String?

    #if os(iOS)
    @Environment(\.horizontalSizeClass) private var horizontalSizeClass
    @Environment(\.isHalfOpen) private var isHalfOpen
    /// The player panel stays open from one launch to the next.
    @SceneStorage("player.panel") private var playerPanelOpen = false
    /// The window's fold is horizontal: half open, the device stands on a table.
    @State private var foldIsHorizontal = false
    /// Closed by hand: the full-screen player waits for the next time.
    @State private var tabletopDeclined = false
    #endif

    #if DEBUG
    @Environment(PlaybackController.self) private var demoPlayback
    @State private var showDemoPlayer = false
@@ -52,6 +63,7 @@ struct RootView: View {

    var body: some View {
        @Bindable var commands = commands
        HStack(spacing: 0) {
            NavigationSplitView {
                List(selection: $selection) {
                    if searchText.isEmpty {
@@ -110,8 +122,24 @@ struct RootView: View {
                detail
            }
            .safeAreaInset(edge: .bottom) {
            NowPlayingBar()
                if !showsPlayerPanel {
                    NowPlayingBar(openPlayer: playerPanelOpener)
                }
            }
            playerPanel
        }
        #if os(iOS)
        // Half open on a table: the player takes the screen, either side of the fold.
        .fullScreenCover(isPresented: tabletopBinding) {
            PlayerView(presentation: .tabletop) { tabletopDeclined = true }
        }
        .onGeometryChange(for: Bool.self) { proxy in
            proxy.tabletopFold(isHalfOpen: true) != nil
        } action: { foldIsHorizontal = $0 }
        .onChange(of: isHalfOpen) { _, halfOpen in
            if !halfOpen { tabletopDeclined = false }
        }
        #endif
        .task(id: searchText) {
            episodeResults = searchText.isEmpty ? [] : await model.searchEpisodes(searchText)
        }
@@ -249,6 +277,53 @@ struct RootView: View {
        #endif
    }

    // MARK: Player placement

    private var showsPlayerPanel: Bool {
        #if os(iOS)
        horizontalSizeClass == .regular && playerPanelOpen && playback.currentEpisode != nil
        #else
        false
        #endif
    }

    /// Where the mini bar opens the player: the panel when the screen is wide
    /// enough, its own sheet otherwise (and the popover on the Mac).
    private var playerPanelOpener: (() -> Void)? {
        #if os(iOS)
        horizontalSizeClass == .regular ? { withAnimation { playerPanelOpen = true } } : nil
        #else
        nil
        #endif
    }

    /// Large screens: the player stays beside the episodes while browsing.
    /// A column of our own rather than `.inspector`, which showed itself, empty,
    /// when the iPhone Duo was opened (compact to regular) with nothing playing.
    @ViewBuilder private var playerPanel: some View {
        #if os(iOS)
        if showsPlayerPanel {
            Divider()
                .ignoresSafeArea()
            PlayerView(presentation: .panel) {
                withAnimation { playerPanelOpen = false }
            }
            .frame(width: 340)
            .background(.background.secondary)
            .transition(.move(edge: .trailing))
        }
        #endif
    }

    #if os(iOS)
    private var tabletopBinding: Binding<Bool> {
        Binding(
            get: { isHalfOpen && foldIsHorizontal && !tabletopDeclined && playback.currentEpisode != nil },
            set: { if !$0 && isHalfOpen { tabletopDeclined = true } }
        )
    }
    #endif

    // MARK: Sidebar content

    @ViewBuilder private var searchResults: some View {
@@ -521,13 +596,24 @@ struct RootView: View {
        case "inbox": selection = .inbox
        case "queue": selection = .queue
        case "sync", "settings": selection = .settings
        case "detail", "player": selection = model.podcasts.first.map { Destination.podcast($0.id) }
        case "detail", "player", "transcript": selection = model.podcasts.first.map { Destination.podcast($0.id) }
        default: selection = nil
        }
        if screen == "player", let first = model.podcasts.first {
        if screen == "player" || screen == "transcript", let first = model.podcasts.first {
            let episodes = await model.episodes(for: first)
            if let episode = episodes.first { await model.play(episode) }
            // "transcript": the demo episode that has one.
            let episode = screen == "transcript"
                ? episodes.first { $0.transcriptURL != nil } ?? episodes.first
                : episodes.first
            if let episode { await model.play(episode) }
            try? await Task.sleep(for: .milliseconds(500))
            #if os(iOS)
            // Large screens show the player in its panel.
            if horizontalSizeClass == .regular {
                playerPanelOpen = true
                return
            }
            #endif
            showDemoPlayer = true
        }
        #endif
Loading