Skip to content

Open source CapCut alternative.

TypeScript
38.8 KB
Raw Blame
#if os(iOS)
import SwiftUI
import UIKit
import DonkeyKitModels

/// The clip parked in the corner after a take: the poster the flight
/// animation carries down, and the recording the well opens.
private struct CornerClip: Identifiable {
    var recording: Recording
    var poster: UIImage?

    var id: UUID { recording.id }
}

struct CameraScreen<CameraPreview: View>: View {
    var app: AppModel
    @Bindable var camera: CameraModel
    var ideas: IdeasModel
    var media: MediaModel
    let cameraPreview: () -> CameraPreview

    @State private var showsZoomPicker = false
    @State private var showsQualityPopover = false
    @State private var showsTeleSettings = false
    @State private var showsNotePicker = false
    @State private var playingRecording: Recording?
    /// The take that just finished, docked in the corner until it is watched
    /// or `Self.wellLifetime` passes.
    @State private var corner: CornerClip?
    /// True while the poster is still flying from the stage into the well.
    @State private var isFlying = false
    /// The well's rectangle in stage coordinates — the flight's landing spot.
    @State private var wellFrame: CGRect = .zero
    /// True while a tap is holding the chrome on a stage that would otherwise
    /// be clear. It stays until the next tap: a hand working the controls is
    /// never raced by a clock.
    @State private var showsChrome = false
    @Environment(\.verticalSizeClass) private var verticalSizeClass

    /// The phone held sideways. The shutter crosses to the trailing edge and
    /// the well drops under it, so both stay under the thumb of the hand
    /// gripping the short edge.
    private var isSideways: Bool { verticalSizeClass == .compact }

    private nonisolated static var stageSpace: String { "cameraStage" }
    private static var wellSide: CGFloat { 54 }
    private static var wellLifetime: Duration { .seconds(30) }

    /// Whether the screen belongs to the picture alone.
    ///
    /// Reading a script is the same job whether or not the camera is rolling,
    /// so a rehearsal looks exactly like a take: the buttons go, the words and
    /// the picture stay.
    private var stageIsClear: Bool { camera.isRecording || camera.teleprompter.isRunning }

    /// Whether the controls are on screen at all.
    private var chromeShown: Bool { !stageIsClear || showsChrome }

    var body: some View {
        ZStack {
            stage
            // Short-form chrome is shaded on the picture itself, under the
            // script and the controls, so a take is framed against it too.
            if camera.showsSafeZones, !isSideways, camera.availability == .running {
                SafeZoneOverlay()
            }
            if camera.isFillLightOn, camera.availability == .running {
                FillLightOverlay()
            }
            // Play hands the screen to the prompter, recording or not: the
            // script runs on a loop so the speed and size a person just set
            // are something they can watch before the take.
            if camera.teleprompter.hasScript, camera.teleprompter.isRunning {
                TeleprompterOverlay(camera: camera, onTap: toggleChrome)
            }
            controls
            // The meter rides above the chrome too: a take clears the stage,
            // and the sliver is how a person sees the microphone is live. It
            // sits mid-way down the trailing edge, and climbs to the top
            // corner when the phone is sideways and the shutter takes that
            // edge.
            if camera.showsAudioMeter, camera.availability == .running {
                AudioMeter(level: camera.audioLevel)
                    .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: isSideways ? .topTrailing : .trailing)
                    .padding(.trailing, 14)
                    .padding(.top, isSideways ? 8 : 0)
                    .allowsHitTesting(false)
                    .transition(.opacity)
            }
            // The timer rides above the chrome and outlives it: a take clears
            // the stage, and the red clock is how a person knows the camera is
            // still rolling.
            if camera.isRecording {
                VStack {
                    RecordingTimer(camera: camera)
                    Spacer()
                }
                .padding(.top, 8)
                .allowsHitTesting(false)
                .transition(.opacity)
            }
            if isFlying, let poster = corner?.poster, wellFrame != .zero {
                CaptureFlight(poster: poster, landing: wellFrame, corner: 10) {
                    isFlying = false
                }
            }
        }
        .coordinateSpace(.named(Self.stageSpace))
        // The tabs are chrome too: a run gets the whole screen, and they come
        // back with everything else.
        .toolbar(chromeShown ? .visible : .hidden, for: .tabBar)
        // A tap on the picture works the chrome. The words take their own taps
        // and hand them here; a control takes its own and keeps the chrome up.
        .contentShape(Rectangle())
        .onTapGesture { toggleChrome() }
        .background(.black, ignoresSafeAreaEdges: .all)
        // The stage is live video: the chrome is dark whatever the app-wide
        // appearance says. Setting the environment (not a color-scheme
        // preference) keeps the root appearance choice from overriding it.
        .environment(\.colorScheme, .dark)
        .onChange(of: media.recordings.first?.id) { _, _ in dockLatestTake() }
        // A run begins on a clear stage, and the controls are back the moment
        // it ends.
        .onChange(of: stageIsClear) { _, _ in showsChrome = false }
        // A take keeps the orientation it started in, so the screen keeps it
        // too: the controls stay where the hand left them and the picture
        // matches the file being written.
        .onChange(of: camera.isRecording) { _, recording in
            if recording {
                InterfaceOrientationLock.shared.hold()
            } else {
                InterfaceOrientationLock.shared.release()
            }
        }
        .onDisappear { InterfaceOrientationLock.shared.release() }
        // The docked clip keeps itself to one appearance: watching it or
        // waiting out the timer both retire it.
        .task(id: corner?.id) {
            guard corner != nil else { return }
            try? await Task.sleep(for: Self.wellLifetime)
            guard !Task.isCancelled else { return }
            corner = nil
        }
        .sheet(isPresented: $showsNotePicker) {
            NotePickerSheet(ideas: ideas) { note in
                camera.loadTeleprompter(script: note.script)
                showsNotePicker = false
            }
        }
        .fullScreenCover(item: $playingRecording, onDismiss: { corner = nil }) { recording in
            RecordingPlayerView(url: media.movieURL(for: recording)) {
                playingRecording = nil
                app.selectedTab = .media
            }
        }
    }

    private func dockLatestTake() {
        // The head of the list also changes when a clip is deleted over in the
        // Library; only a take that just finished gets docked.
        guard let recording = media.recordings.first,
              recording.createdAt.timeIntervalSinceNow > -5 else { return }
        let poster = media.thumbnailURL(for: recording)
            .flatMap { UIImage(contentsOfFile: $0.localPath) }
        corner = CornerClip(recording: recording, poster: poster)
        isFlying = poster != nil && wellFrame != .zero
    }

    @ViewBuilder private var stage: some View {
        switch camera.availability {
        case .running, .starting:
            cameraPreview()
                .ignoresSafeArea()
        case .idle:
            Color.black.ignoresSafeArea()
        case .unavailable(let reason):
            VStack(spacing: 8) {
                Image(systemName: "video.slash")
                    .font(.largeTitle)
                Text(reason)
                    .font(.subheadline)
                    .multilineTextAlignment(.center)
            }
            .foregroundStyle(.secondary)
            .padding(.horizontal, 40)
        }
    }

    private var controls: some View {
        VStack {
            if camera.teleprompter.isCardShown, !camera.isRecording {
                TeleprompterCard(
                    camera: camera,
                    showsSettings: $showsTeleSettings,
                    onUseNote: { showsNotePicker = true }
                )
                .padding(.horizontal, 16)
                .padding(.top, 4)
            }
            Spacer()
        }
        // Fill the screen so the leading/bottom overlays anchor to its edges;
        // without this the stack hugs its content and the rail floats mid-screen.
        .frame(maxWidth: .infinity, maxHeight: .infinity)
        .overlay(alignment: .leading) { rail }
        .overlay(alignment: isSideways ? .trailing : .bottom) { recordButton }
        .overlay(alignment: isSideways ? .bottomTrailing : .bottomLeading) { thumbnailWell }
        .animation(.spring(duration: 0.45), value: corner?.id)
        .animation(.spring(duration: 0.45), value: camera.isRecording)
        .padding(.top, 8)
        // A clear stage keeps its controls laid out and invisible: they fade
        // in place, so a tap brings them back exactly where the hand left
        // them, and while they are gone the picture underneath takes every
        // touch.
        .opacity(chromeShown ? 1 : 0)
        .allowsHitTesting(chromeShown)
        .animation(.spring(duration: 0.3), value: chromeShown)
    }

    /// A tap on a clear stage works the controls: one brings them back —
    /// enough to stop the take, light the room, or turn the camera round —
    /// and the next puts them away, on the tap and not a moment later.
    private func toggleChrome() {
        guard stageIsClear else { return }
        showsChrome.toggle()
    }

    /// Where the take lands. The slot holds its place whether or not a clip
    /// is docked, so the flight always has a measured rectangle to fly to.
    private var thumbnailWell: some View {
        Color.clear
            .frame(width: Self.wellSide, height: Self.wellSide)
            .onGeometryChange(for: CGRect.self) { proxy in
                proxy.frame(in: .named(Self.stageSpace))
            } action: { wellFrame = $0 }
            .overlay {
                if let corner, !camera.isRecording, !isFlying {
                    wellButton(corner)
                }
            }
            .padding(isSideways ? .trailing : .leading, 20)
            .padding(.bottom, isSideways ? 20 : 44)
    }

    private func wellButton(_ clip: CornerClip) -> some View {
        Button {
            playingRecording = clip.recording
        } label: {
            ZStack {
                if let poster = clip.poster {
                    Image(uiImage: poster)
                        .resizable()
                        .scaledToFill()
                } else {
                    Rectangle().fill(.fill.secondary)
                    Image(systemName: "play.fill")
                        .foregroundStyle(.white)
                }
            }
            .frame(width: Self.wellSide, height: Self.wellSide)
            .clipShape(RoundedRectangle(cornerRadius: 10))
            .overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(.white.opacity(0.5), lineWidth: 1))
        }
        .buttonStyle(.plain)
        .id(clip.id)
        .transition(.scale(scale: 0.25, anchor: isSideways ? .bottomTrailing : .bottomLeading).combined(with: .opacity))
        .accessibilityLabel("Play last recording")
    }

    private var rail: some View {
        GlassEffectContainer {
            VStack(spacing: 16) {
                Button {
                    showsZoomPicker.toggle()
                    showsQualityPopover = false
                } label: {
                    Text(zoomLabel(camera.zoom))
                        .font(.footnote.weight(.bold))
                        .frame(width: 40, height: 40)
                }
                .glassEffect(.regular.interactive())
                .popover(isPresented: $showsZoomPicker, arrowEdge: .leading) {
                    zoomPicker
                        .presentationCompactAdaptation(.popover)
                        // Camera chrome is dark over the picture in every
                        // appearance, so the popover keeps the stage's dark.
                        .preferredColorScheme(.dark)
                        .presentationBackground(Color.black.opacity(0.78))
                }

                Button {
                    if camera.isRecording {
                        // Mid-take the card stays away, so the button is the
                        // script's own switch: it leaves the picture and comes
                        // back where the pacing has reached, and the take never
                        // pauses for either.
                        camera.teleprompter.isRunning.toggle()
                    } else if camera.teleprompter.isCardShown {
                        camera.dismissTeleprompter()
                    } else {
                        // A running script comes back to the card to be
                        // edited; the picture is clear while it is open.
                        camera.teleprompter.isRunning = false
                        camera.teleprompter.isCardShown = true
                    }
                } label: {
                    Image(systemName: "text.viewfinder")
                        .frame(width: 40, height: 40)
                }
                .glassEffect(camera.teleprompter.isCardShown || camera.teleprompter.isRunning ? .regular.tint(.white.opacity(0.25)).interactive() : .regular.interactive())

                Button {
                    camera.toggleSafeZones()
                } label: {
                    Image(systemName: "rectangle.dashed")
                        .frame(width: 40, height: 40)
                }
                .glassEffect(camera.showsSafeZones ? .regular.tint(.white.opacity(0.25)).interactive() : .regular.interactive())
                .accessibilityLabel(camera.showsSafeZones ? "Hide short-form guide" : "Show short-form guide")

                Button {
                    camera.toggleAudioMeter()
                } label: {
                    Image(systemName: "waveform")
                        .frame(width: 40, height: 40)
                }
                .glassEffect(camera.showsAudioMeter ? .regular.tint(.white.opacity(0.25)).interactive() : .regular.interactive())
                .accessibilityLabel(camera.showsAudioMeter ? "Hide microphone meter" : "Show microphone meter")

                Spacer().frame(height: 10)

                Button {
                    camera.toggleTorch()
                } label: {
                    Image(systemName: camera.isTorchOn ? "bolt.fill" : "bolt.slash")
                        .foregroundStyle(camera.isTorchOn ? .yellow : .white)
                        .frame(width: 40, height: 40)
                }
                .glassEffect(.regular.interactive())
                .disabled(!camera.flashAvailable)
                .opacity(camera.flashAvailable ? 1 : 0.4)

                Button {
                    camera.flip()
                } label: {
                    Image(systemName: "arrow.trianglehead.2.clockwise.rotate.90.camera")
                        .frame(width: 40, height: 40)
                }
                .glassEffect(.regular.interactive())

                Button {
                    showsQualityPopover.toggle()
                    showsZoomPicker = false
                } label: {
                    VStack(spacing: 0) {
                        Text(camera.effectiveSettings.resolution.rawValue)
                        Text("\(camera.effectiveSettings.frameRate.rawValue)")
                    }
                    .font(.caption2.weight(.bold))
                    .frame(width: 40, height: 40)
                }
                .glassEffect(.regular.interactive())
                .popover(isPresented: $showsQualityPopover, arrowEdge: .leading) {
                    qualityPopover
                        .presentationCompactAdaptation(.popover)
                        .preferredColorScheme(.dark)
                        .presentationBackground(Color.black.opacity(0.78))
                }
                .disabled(camera.isRecording)
            }
            .foregroundStyle(.white)
        }
        .padding(.leading, 14)
    }

    private var zoomPicker: some View {
        VStack(spacing: 4) {
            ForEach(camera.zoomMapping.options.reversed(), id: \.self) { option in
                Button {
                    camera.select(zoom: option)
                    showsZoomPicker = false
                } label: {
                    Text(zoomLabel(option))
                        .font(.headline.weight(.bold))
                        .frame(width: 72, height: 44)
                        .background(
                            camera.zoom == option ? AnyShapeStyle(.primary) : AnyShapeStyle(.clear),
                            in: RoundedRectangle(cornerRadius: 14)
                        )
                        .foregroundStyle(camera.zoom == option ? AnyShapeStyle(.background) : AnyShapeStyle(.primary))
                }
                .buttonStyle(.plain)
            }
        }
        .padding(10)
    }

    private var qualityPopover: some View {
        VStack(alignment: .leading, spacing: 12) {
            Text("Resolution")
                .font(.footnote)
                .foregroundStyle(.secondary)
            Picker("Resolution", selection: resolutionBinding) {
                ForEach(CaptureResolution.allCases, id: \.self) { Text($0.rawValue).tag($0) }
            }
            .pickerStyle(.segmented)

            Text("Frame Rate")
                .font(.footnote)
                .foregroundStyle(.secondary)
            Picker("Frame Rate", selection: frameRateBinding) {
                ForEach(CaptureFrameRate.allCases, id: \.self) { Text("\($0.rawValue)").tag($0) }
            }
            .pickerStyle(.segmented)

            Text("Color")
                .font(.footnote)
                .foregroundStyle(.secondary)
            Picker("Color", selection: colorBinding) {
                ForEach(CaptureColorMode.allCases, id: \.self) { Text($0.rawValue).tag($0) }
            }
            .pickerStyle(.segmented)
        }
        .padding(16)
        .frame(minWidth: 280)
    }

    private var resolutionBinding: Binding<CaptureResolution> {
        Binding(
            get: { camera.settings.resolution },
            set: { value in camera.update { $0.resolution = value } }
        )
    }

    private var frameRateBinding: Binding<CaptureFrameRate> {
        Binding(
            get: { camera.settings.frameRate },
            set: { value in camera.update { $0.frameRate = value } }
        )
    }

    private var colorBinding: Binding<CaptureColorMode> {
        Binding(
            get: { camera.settings.colorMode },
            set: { value in camera.update { $0.colorMode = value } }
        )
    }

    private var recordButton: some View {
        Button {
            camera.toggleRecording()
        } label: {
            ZStack {
                Circle()
                    .fill(.white)
                    .frame(width: 84, height: 84)
                RoundedRectangle(cornerRadius: camera.isRecording ? 9 : 34)
                    .fill(Color.recordPink)
                    .frame(
                        width: camera.isRecording ? 34 : 68,
                        height: camera.isRecording ? 34 : 68
                    )
            }
            .animation(.snappy(duration: 0.2), value: camera.isRecording)
        }
        .buttonStyle(.plain)
        .disabled(camera.availability != .running)
        .opacity(camera.availability == .running ? 1 : 0.5)
        .padding(isSideways ? .trailing : .bottom, isSideways ? 24 : 30)
        .accessibilityLabel(camera.isRecording ? "Stop recording" : "Record")
    }
}

/// The take shrinking from the stage into the corner well, the way a
/// screenshot drops to the bottom of the screen.
private struct CaptureFlight: View {
    let poster: UIImage
    let landing: CGRect
    let corner: CGFloat
    let onLanded: () -> Void

    @State private var landed = false

    var body: some View {
        GeometryReader { proxy in
            let frame = landed ? landing : CGRect(origin: .zero, size: proxy.size)
            Image(uiImage: poster)
                .resizable()
                .scaledToFill()
                .frame(width: frame.width, height: frame.height)
                .clipShape(RoundedRectangle(cornerRadius: landed ? corner : 0, style: .continuous))
                .position(x: frame.midX, y: frame.midY)
        }
        .allowsHitTesting(false)
        .task {
            withAnimation(.spring(response: 0.5, dampingFraction: 0.72)) { landed = true }
            try? await Task.sleep(for: .milliseconds(620))
            onLanded()
        }
    }
}

/// A bright frame around the preview: the screen fill light for cameras
/// without a torch.
/// The short-form guide over the picture, drawn the way the editor's
/// preview draws it: each keep-out box a red wash under a diagonal hatch,
/// a dashed red edge, and its name in white. The picture fills the screen,
/// so the 9:16 frame is wider than the screen in portrait and every box is
/// placed against the frame, not the screen.
struct SafeZoneOverlay: View {
    private static let verticalAspect = 9.0 / 16.0
    private static let red = Color(red: 239 / 255, green: 68 / 255, blue: 68 / 255)

    var body: some View {
        Canvas { context, size in
            let frame = FrameRect.aspectFill(
                contentAspect: Self.verticalAspect,
                containerWidth: size.width,
                containerHeight: size.height
            )
            let labelSize = max(9, min(12, frame.width / 36))
            for box in ShortFormGuide.boxes {
                let rect = CGRect(
                    x: frame.x + box.x * frame.width,
                    y: frame.y + box.y * frame.height,
                    width: box.width * frame.width,
                    height: box.height * frame.height
                )
                context.fill(Path(rect), with: .color(Self.red.opacity(0.12)))
                context.drawLayer { hatch in
                    hatch.clip(to: Path(rect))
                    var lines = Path()
                    // Diagonals eight points apart, running up and to the
                    // right across the whole box.
                    let span = rect.width + rect.height
                    var start = -rect.height
                    while start < span {
                        lines.move(to: CGPoint(x: rect.minX + start, y: rect.maxY))
                        lines.addLine(to: CGPoint(x: rect.minX + start + rect.height, y: rect.minY))
                        start += 8 * 2.squareRoot()
                    }
                    hatch.stroke(lines, with: .color(Self.red.opacity(0.45)), lineWidth: 1.5)
                }
                context.stroke(
                    Path(rect.insetBy(dx: 0.5, dy: 0.5)),
                    with: .color(Self.red.opacity(0.8)),
                    style: StrokeStyle(lineWidth: 1, dash: [4, 3])
                )
                // A full-width band names itself at its inner edge; a rail at
                // its top, where the keep-out meets the picture. A strip too
                // narrow for its label runs the label down its length.
                let fullWidth = box.width >= 0.99
                let narrow = rect.width <= 40 && rect.height > 120
                guard narrow || (rect.width > 40 && rect.height > labelSize * 2) else { continue }
                let text = Text(box.label)
                    .font(.system(size: labelSize, weight: .semibold))
                    .foregroundStyle(.white)
                var label = context.resolve(text)
                label.shading = .color(.white)
                let measured = label.measure(in: CGSize(width: 400, height: 40))
                if narrow {
                    context.drawLayer { turned in
                        turned.translateBy(x: rect.midX, y: rect.minY + 8)
                        turned.rotate(by: .degrees(90))
                        turned.draw(label, at: CGPoint(x: 0, y: 0), anchor: .topLeading)
                    }
                } else {
                    let y = fullWidth && box.y <= 0.01 ? rect.maxY - 5 - measured.height : rect.minY + 4
                    context.draw(label, at: CGPoint(x: max(rect.minX, 0) + 6, y: y), anchor: .topLeading)
                }
            }
        }
        .ignoresSafeArea()
        .allowsHitTesting(false)
    }
}

struct FillLightOverlay: View {
    var body: some View {
        Rectangle()
            .strokeBorder(.white.opacity(0.95), lineWidth: 64)
            .blur(radius: 22)
            .ignoresSafeArea()
            .allowsHitTesting(false)
    }
}

/// A vertical sliver that fills from the bottom with the microphone's level,
/// red at a whisper through amber to green at speaking volume. A session
/// with no microphone shows a crossed-out mic over an empty sliver: the take
/// about to be shot would come out silent.
struct AudioMeter: View {
    /// 0...1, nil when the session has no microphone.
    var level: Double?

    private static var length: CGFloat { 140 }
    private static var thickness: CGFloat { 6 }

    private var fill: Color {
        let level = level ?? 0
        // Red below a quarter, amber through the middle, green from a half
        // up: speech at a normal distance lands in the green.
        return Color(hue: 0.33 * min(level * 2, 1), saturation: 0.9, brightness: 0.95)
    }

    var body: some View {
        VStack(spacing: 6) {
            Image(systemName: level == nil ? "mic.slash.fill" : "mic.fill")
                .font(.caption2.weight(.bold))
                .foregroundStyle(level == nil ? .red : .white)
            Capsule()
                .fill(.white.opacity(0.25))
                .overlay(alignment: .bottom) {
                    Capsule()
                        .fill(fill)
                        .frame(height: Self.length * (level ?? 0))
                        .animation(.linear(duration: 0.05), value: level)
                }
                .frame(width: Self.thickness, height: Self.length)
        }
        .padding(8)
        .background(.black.opacity(0.35), in: Capsule())
        .accessibilityElement(children: .ignore)
        .accessibilityLabel(level == nil ? "No microphone" : "Microphone level \(Int((level ?? 0) * 100)) percent")
    }
}

struct RecordingTimer: View {
    var camera: CameraModel

    var body: some View {
        TimelineView(.periodic(from: .now, by: 0.5)) { context in
            if let startedAt = camera.recordingStartedAt {
                let elapsed = context.date.timeIntervalSince(startedAt)
                HStack(spacing: 7) {
                    // The dot blinks on the second, the way a camera's tally
                    // light does.
                    Circle()
                        .fill(.white)
                        .frame(width: 8, height: 8)
                        .opacity(Int(elapsed * 2) % 2 == 0 ? 1 : 0.3)
                    Text(formattedDuration(elapsed))
                        .font(.footnote.weight(.bold))
                        .monospacedDigit()
                }
                .foregroundStyle(.white)
                .padding(.horizontal, 14)
                .padding(.vertical, 6)
                .background(Color.red.opacity(0.9), in: Capsule())
                .accessibilityElement(children: .combine)
                .accessibilityLabel("Recording, \(formattedDuration(elapsed))")
            }
        }
    }
}

struct TeleprompterCard: View {
    @Bindable var camera: CameraModel
    @Binding var showsSettings: Bool
    let onUseNote: () -> Void

    @State private var editing: NoteBodyEditing
    @FocusState private var editingScript: Bool

    init(camera: CameraModel, showsSettings: Binding<Bool>, onUseNote: @escaping () -> Void) {
        self.camera = camera
        _showsSettings = showsSettings
        self.onUseNote = onUseNote
        _editing = State(initialValue: NoteBodyEditing(body: camera.teleprompter.script, look: .scriptCard) { [camera] script in
            camera.teleprompter.script = script
        })
    }

    var body: some View {
        VStack(alignment: .leading, spacing: 8) {
            // The card's controls ride the top row: the camera rail runs up the
            // leading edge and would sit on top of anything in the low corner.
            HStack(spacing: 14) {
                Button {
                    showsSettings.toggle()
                } label: {
                    Image(systemName: "slider.horizontal.3")
                }
                // The card rides the top of the screen, so the sliders drop
                // below the button; upward they run off under the status bar.
                .popover(isPresented: $showsSettings, arrowEdge: .top) {
                    TeleprompterSettingsView(camera: camera)
                        .presentationCompactAdaptation(.popover)
                        // The popover's own chrome follows the phone's
                        // appearance, so in light mode it drew a pale panel
                        // under the camera chrome's white type. It carries the
                        // stage's dark instead.
                        .presentationBackground(Color.black.opacity(0.78))
                }
                Button(action: onUseNote) {
                    Image(systemName: "note.text")
                }
                // A run of the script at the current pace, without spending a
                // take on finding out whether it reads right.
                Button {
                    camera.startTeleprompter()
                } label: {
                    Image(systemName: "play.fill")
                }
                .disabled(!camera.teleprompter.hasScript)
                Spacer()
                Button {
                    camera.dismissTeleprompter()
                } label: {
                    Image(systemName: "xmark")
                        .font(.subheadline.weight(.bold))
                }
            }
            .font(.body.weight(.semibold))
            // The script is a note's body, styles and all, and edits the same
            // way the note does.
            NoteBodyEditor(editing: editing, placeholder: String(localized: "Add your script here..."))
                .scrollContentBackground(.hidden)
                .frame(minHeight: 96, maxHeight: 160)
                .focused($editingScript)
        }
        // A note picked while the card is up replaces the script under it.
        .onChange(of: camera.teleprompter.script) { _, script in
            if script != editing.body { editing.load(script) }
        }
        .toolbar {
            ToolbarItemGroup(placement: .keyboard) {
                NoteFormatControls(editing: editing)
                Spacer()
                Button("Done") { editingScript = false }
                    .font(.body.weight(.bold))
            }
        }
        .foregroundStyle(.white)
        .padding(14)
        .glassEffect(.regular, in: RoundedRectangle(cornerRadius: 22))
    }
}

struct TeleprompterSettingsView: View {
    @Bindable var camera: CameraModel

    var body: some View {
        VStack(alignment: .leading, spacing: 14) {
            VStack(alignment: .leading, spacing: 6) {
                Text("Reading speed · \(Int(camera.teleprompter.settings.wordsPerMinute)) wpm")
                    .font(.footnote)
                    .foregroundStyle(.secondary)
                Slider(value: $camera.teleprompter.settings.wordsPerMinute, in: TeleprompterSettings.speedRange)
            }
            VStack(alignment: .leading, spacing: 6) {
                Text("Text size")
                    .font(.footnote)
                    .foregroundStyle(.secondary)
                Slider(value: $camera.teleprompter.settings.textSize, in: TeleprompterSettings.textSizeRange)
            }
        }
        .padding(16)
        .frame(minWidth: 260)
    }
}

struct TeleprompterOverlay: View {
    var camera: CameraModel
    /// What a tap on the words does. The script covers most of the screen, so
    /// it answers for the picture underneath it.
    var onTap: () -> Void

    /// Rendered height of the paced script, measured off the Text itself so
    /// the scroll rate can pace the exact copy on screen.
    @State private var textHeight: Double = 0
    /// The drag in flight. Its end lands on the model's nudge, beside what
    /// the watch's crown sends.
    @GestureState private var dragging: Double = 0
    /// Breathing room between one pass of the script and the next, as a share
    /// of the prompter's height.
    private static var gapShare: Double { 0.3 }
    /// Room kept at the foot of the screen, clear of the home indicator. The
    /// script only ever runs on a clear stage, so it takes the screen; the
    /// controls a tap brings back float over the words for their few seconds.
    private static var footRoom: Double { 40 }
    /// Margin each side of the script.
    private static var sidePadding: Double { 24 }

    /// The face the script draws in, at the reader's size. Headings draw
    /// larger, styled words in their own weight, slant and color.
    private var look: NoteLook { .prompter(size: camera.teleprompter.settings.textSize) }

    /// The script broken to the width it is drawn in, measured on the very
    /// faces and sizes it will be drawn in. A line holds as many words as the
    /// picture has room for, so a short clause reads on one line with what
    /// follows it. The last point of the width is left to the layout, so a
    /// line measured here as fitting is never broken again as it draws.
    private func script(room: Double) -> AttributedString {
        let look = look
        let paced = camera.teleprompter.displayScript(room: room - 1) { runs, kind in
            look.width(runs, kind)
        }
        return look.text(paced)
    }

    private func scriptText(_ text: AttributedString) -> some View {
        Text(text)
            .font(look.font(.paragraph, NoteMarks()))
            .foregroundStyle(.white)
            .lineSpacing(4)
            .shadow(color: .black.opacity(0.7), radius: 6, y: 1)
            // The window the script scrolls through is a fraction of the
            // screen, and a Text offered that height lays out only what fits
            // and ends the last line in an ellipsis. The script is laid out
            // whole and scrolled past the window.
            .fixedSize(horizontal: false, vertical: true)
            .frame(maxWidth: .infinity, alignment: .leading)
    }

    var body: some View {
        GeometryReader { geometry in
            // The script gets the screen, stopping short of the controls.
            let height = max(geometry.size.height - Self.footRoom, 0)
            let gap = height * Self.gapShare
            let lines = script(room: geometry.size.width - Self.sidePadding * 2)
            TimelineView(.animation) { context in
                let elapsed = elapsed(at: context.date)
                // As many passes as the screen holds, above it and below it:
                // the loop comes round with the words already in place, in a
                // take as in a preview.
                let pass = camera.teleprompter.prompterPass(
                    elapsed: elapsed,
                    overlayHeight: height,
                    textHeight: textHeight,
                    gap: gap,
                    nudge: camera.teleprompter.nudge + dragging
                )
                VStack(alignment: .leading, spacing: gap) {
                    ForEach(0..<pass.copies, id: \.self) { copy in
                        if copy == 0 {
                            scriptText(lines)
                                .onGeometryChange(for: Double.self, of: { $0.size.height }) {
                                    textHeight = $0
                                }
                        } else {
                            scriptText(lines)
                        }
                    }
                }
                .offset(y: pass.offset)
                .padding(.horizontal, Self.sidePadding)
            }
            .frame(height: height, alignment: .top)
            .clipped()
            .background(
                // A scrim over the top of the frame, where the status bar and
                // the brightest part of most rooms are. Past it the script
                // carries its own shadow and the picture stays the picture.
                LinearGradient(
                    colors: [.black.opacity(0.6), .black.opacity(0)],
                    startPoint: .top,
                    endPoint: .bottom
                )
                .frame(height: height * 0.35),
                alignment: .top
            )
            // The reader places the words: a drag anywhere over the picture
            // moves the script. The rail and the record button sit above this
            // in the stack, so they still take their own touches.
            .contentShape(Rectangle())
            .onTapGesture { onTap() }
            .gesture(
                DragGesture(minimumDistance: 6)
                    .updating($dragging) { value, state, _ in state = value.translation.height }
                    .onEnded { camera.nudgeTeleprompter(by: $0.translation.height) }
            )
        }
        .ignoresSafeArea()
    }

    /// Seconds into the script, counted from the press of play — or from the
    /// top of a take that began while the prompter was up. The loop itself
    /// lives in the offset.
    private func elapsed(at now: Date) -> TimeInterval {
        guard let startedAt = camera.teleprompter.runStartedAt else { return 0 }
        return now.timeIntervalSince(startedAt)
    }
}

struct NotePickerSheet: View {
    var ideas: IdeasModel
    let onPick: (Note) -> Void

    private let columns = [GridItem(.adaptive(minimum: 150, maximum: 240), spacing: 12)]

    var body: some View {
        NavigationStack {
            Group {
                if ideas.notes.isEmpty {
                    Text("No notes yet. Write one in Ideas first.")
                        .foregroundStyle(.secondary)
                        .padding(24)
                } else {
                    ScrollView {
                        LazyVGrid(columns: columns, spacing: 12) {
                            ForEach(ideas.notes) { note in
                                Button {
                                    onPick(note)
                                } label: {
                                    NoteCard(note: note, labels: ideas.labels(on: note))
                                }
                                .buttonStyle(.plain)
                            }
                        }
                        .padding(20)
                    }
                }
            }
            .navigationTitle("Use a note")
            .navigationBarTitleDisplayMode(.inline)
        }
        .presentationDetents([.medium, .large])
    }
}
#endif