Cotton code
599 lines · 26.0 KB · SwiftRaw
// The script home (ink.html "Script home"; wireframes 2): the title (a tap// opens Your scripts), the count line, the cast sideways by lines spoken, the// fixed pills, the scene list under thin dotted rules (hold and drag a scene// to move it; ⋯ or a hold that does not move opens its menu), and the one "+". It// is where the app opens, so it has no back button. A new script with no// scene yet says "Where does it start?" (ink.html "A new script").#if os(iOS)import CottonKitimport SwiftUIimport UIKitstruct InkHome: View {    let model: InkStory    let home: StoryScenesAnswer    /// The phone's width, which the title's size follows (ink.html is drawn 430 wide).    @State private var screen: CGFloat = InkTitle.drawnWidth    /// The scene being dragged, and how far it has come with the page under it.    @State private var dragging: String?    @State private var dragOffset: CGFloat = 0    /// Where the finger and the page stood when the row lifted, and the finger now (window points).    @State private var lift: (finger: CGFloat, page: CGFloat)?    @State private var finger: CGFloat = 0    /// The home's scroll, read and driven while a lifted row nears an edge.    @State private var position = ScrollPosition(edge: .top)    @State private var page: (y: CGFloat, most: CGFloat) = (0, 0)    /// The scroll view's frame in the window.    @State private var viewport: CGRect = .zero    /// Each scene row's height, for where a dragged one lands.    @State private var heights: [String: CGFloat] = [:]    /// The order a drop made, shown until the core answers.    @State private var order: [String]?    @Environment(BootModel.self) private var boot: BootModel?    var body: some View {        ZStack(alignment: .bottomTrailing) {            ScrollView {                VStack(alignment: .leading, spacing: 18) {                    top                    // Where sync stands, in one quiet line (SyncSeenLine); a tap opens Settings on Sync.                    if boot?.home?.bringing == nil {                        SyncSeenLine(font: InkType.count, color: Ink.quiet) {                            SyncSeenOpens.ask()                            model.path.append(.settings)                        }                    }                    // While the first pull still brings its scenes, "No scenes yet" stood over                    // "Loading this script…" (launch-ios walk, 22 Nov 2026): the loading line says it alone.                    if !(home.scenes.isEmpty && boot?.home?.bringing != nil) {                        Text(home.scenes.isEmpty ? InkWords.line("home.no_scenes") : home.story.summary)                            .font(InkType.count)                            .foregroundStyle(Ink.quiet)                            .fixedSize(horizontal: false, vertical: true)                    }                    if let check = model.check, check.story == home.story.id {                        // A printed script just came in: read it through.                        Text(check.words)                            .font(InkType.count)                            .foregroundStyle(Ink.quiet)                            .italic()                            .fixedSize(horizontal: false, vertical: true)                            .onTapGesture { model.check = nil }                            .accessibilityAddTraits(.isStaticText)                    }                    if home.scenes.isEmpty, let bringing = boot?.home?.bringing {                        // Opened while the first pull runs: its scenes may still be coming, so it says so in place.                        VStack(alignment: .leading, spacing: 10) {                            Text(verbatim: InkWords.line("home.loading_script"))                                .font(InkType.scenePreview)                                .foregroundStyle(Ink.ink)                            LoadingLine(bringing: bringing, ink: Ink.quiet, font: InkType.count)                        }                        .padding(.top, 8)                        .accessibilityElement(children: .contain)                        .accessibilityIdentifier("story-script-loading")                    } else if home.scenes.isEmpty {                        InkFirstScene(model: model)                    } else {                        if let cast = home.cast, !cast.isEmpty { InkCastRow(cast: cast) { model.path.append(.character($0)) } }                        pills                        scenes                    }                }                .padding(.horizontal, Ink.gutter)                .padding(.top, 22)                // The last row stands clear of the Plus.                .padding(.bottom, home.scenes.isEmpty ? 26 : 96)            }            .scrollIndicators(.hidden)            .scrollPosition($position)            .onScrollGeometryChange(for: [CGFloat].self) { geometry in                [geometry.contentOffset.y + geometry.contentInsets.top,                 max(0, geometry.contentSize.height + geometry.contentInsets.top + geometry.contentInsets.bottom - geometry.containerSize.height)]            } action: { _, now in page = (now[0], now[1]) }            .onGeometryChange(for: CGRect.self) { $0.frame(in: .global) } action: { viewport = $0 }            // A lifted row holds the page still under the finger; it scrolls only by the edges (`edgeScroll`).            .scrollDisabled(dragging != nil)            .task(id: dragging) { await edgeScroll() }            if !home.scenes.isEmpty {                InkPlus(label: InkWords.line("home.new_scene")) { Task { await model.newScene() } }                    .padding(18)            }        }        .inkGround()        // A sheet's keyboard rises over the home; the home is not laid out again under it.        .ignoresSafeArea(.keyboard, edges: .bottom)        .onGeometryChange(for: CGFloat.self) { $0.size.width } action: { screen = $0 }    }    private var top: some View {        HStack(alignment: .top, spacing: 12) {            let title = home.story.title.isEmpty ? InkWords.line("fan.untitled") : home.story.title            Button { model.sheet = .scripts } label: {                InkTitle(words: title, screen: screen)            }            .buttonStyle(InkPress())            .accessibilityLabel(title)            .accessibilityHint(InkWords.line("home.scripts"))            .accessibilityAddTraits(.isHeader)            HStack(spacing: 0) {                if !home.scenes.isEmpty {                    InkGlyph(symbol: "doc.plaintext", label: InkWords.line("home.read")) {                        model.path.append(.read(story: home.story.id, at: nil))                    }                }                InkGlyph(symbol: "ellipsis", label: InkWords.line("home.more")) { model.sheet = .more }            }            .padding(.top, -2)        }    }    private var pills: some View {        InkFlow(spacing: 10) {            ForEach(home.doors ?? []) { door in                InkPill(words: door.words) { open(door) }            }        }    }    private func open(_ door: StoryScenesAnswer.Door) {        switch door.key {        case "read": model.path.append(.read(story: home.story.id, at: nil))        case "places": model.path.append(.places(story: home.story.id, title: door.words))        default: model.sheet = .views        }    }    /// The scenes in the order shown: the core's, or the one a drop just made    /// until the core answers again.    private var ordered: [StoryScenesAnswer.Row] {        guard let order else { return home.scenes }        let byId = Dictionary(home.scenes.map { ($0.id, $0) }, uniquingKeysWith: { one, _ in one })        let placed = order.compactMap { byId[$0] }        return placed.count == home.scenes.count ? placed : home.scenes    }    private var scenes: some View {        let rows = ordered        let ids = rows.map(\.id)        let from = dragging.flatMap { ids.firstIndex(of: $0) }        let to = from.map { InkReorder.target(from: $0, offset: dragOffset, heights: ids.map { heights[$0] ?? 64 }) }        return VStack(spacing: 0) {            ForEach(Array(rows.enumerated()), id: \.element.id) { at, row in                let lifted = dragging == row.id                VStack(spacing: 0) {                    InkSceneRow(row: row, number: order == nil ? row.number : at + 1, lifted: lifted,                                earlier: at > 0, later: at < rows.count - 1) {                        model.path.append(.scene(row.id, fresh: false))                    } more: {                        model.sheet = .sceneActs(row)                    } move: { by in                        Task { await model.move(row.id, by: by) }                    }                    if at < rows.count - 1 { InkRule() }                }                .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { heights[row.id] = $0 }                .offset(y: lifted ? dragOffset : parting(at, from: from, to: to))                .zIndex(lifted ? 1 : 0)                .animation(lifted ? nil : .easeOut(duration: 0.18), value: to)                .gesture(hold(row, ids: ids))            }        }    }    /// How far a row steps aside for the one being dragged.    private func parting(_ at: Int, from: Int?, to: Int?) -> CGFloat {        guard let from, let to, let id = dragging else { return 0 }        return InkReorder.parting(at, from: from, to: to, lift: heights[id] ?? 64)    }    /// Hold a row still for 0.35 s: it lifts onto the soft blue with a tap    /// of the haptic and follows the finger; the others part; letting go puts    /// it there (`story.scene.move { to }`). A hold that does not move opens    /// the scene's menu instead. The hold is UIKit's long press, which fails    /// the moment the finger moves, so any swipe on a row scrolls the home at    /// once (owner's phone, 20 Nov 2026: SwiftUI's long press sequenced before    /// a drag held every touch on a row and the home stopped scrolling).    private func hold(_ row: StoryScenesAnswer.Row, ids: [String]) -> InkHold {        InkHold { y in            UIImpactFeedbackGenerator(style: .medium).impactOccurred()            lift = (y, page.y)            finger = y            dragOffset = 0            dragging = row.id        } moved: { y in            finger = y            follow()        } ended: { cancelled in            let offset = dragOffset            dragging = nil            dragOffset = 0            lift = nil            guard !cancelled else { return }            guard abs(offset) >= 8, let from = ids.firstIndex(of: row.id) else {                model.sheet = .sceneActs(row)                return            }            let to = InkReorder.target(from: from, offset: offset, heights: ids.map { heights[$0] ?? 64 })            guard to != from else { return }            order = InkReorder.moved(ids, from: from, to: to)            Task {                await model.move(row.id, to: to + 1)                order = nil            }        }    }    /// The lifted row under the finger: how far the finger went, plus how far the page scrolled under it.    private func follow() {        guard let lift else { return }        dragOffset = finger - lift.finger + page.y - lift.page    }    /// While a row is lifted and the finger is near the top or bottom of the    /// home, the page scrolls that way, faster the nearer the edge.    private func edgeScroll() async {        guard dragging != nil else { return }        let band: CGFloat = 80        while dragging != nil, !Task.isCancelled {            try? await Task.sleep(for: .milliseconds(16))            let top = finger - viewport.minY, bottom = viewport.maxY - finger            var step: CGFloat = 0            if top < band { step = -12 * (1 - max(0, top) / band) }            else if bottom < band { step = 12 * (1 - max(0, bottom) / band) }            guard step != 0 else { continue }            let next = min(max(0, page.y + step), page.most)            guard next != page.y else { continue }            position.scrollTo(y: next)            page.y = next            follow()        }    }}/// A row's hold, UIKit's long press: it begins only after 0.35 s with the/// finger still (within 8 points), so a scroll that moves first always wins;/// once begun it reports the finger's height in the window until let go.struct InkHold: UIGestureRecognizerRepresentable {    /// Off, it never begins (a row that cannot be moved).    var enabled = true    let began: (CGFloat) -> Void    let moved: (CGFloat) -> Void    /// Let go (false), or taken away by the system (true).    let ended: (Bool) -> Void    func makeUIGestureRecognizer(context: Context) -> UILongPressGestureRecognizer {        let press = UILongPressGestureRecognizer()        press.minimumPressDuration = 0.35        press.allowableMovement = 8        press.delegate = context.coordinator        press.isEnabled = enabled        return press    }    func updateUIGestureRecognizer(_ press: UILongPressGestureRecognizer, context: Context) {        press.isEnabled = enabled    }    func handleUIGestureRecognizerAction(_ press: UILongPressGestureRecognizer, context: Context) {        let y = press.location(in: nil).y        switch press.state {        case .began: began(y)        case .changed: moved(y)        case .ended: ended(false)        case .cancelled, .failed: ended(true)        default: break        }    }    func makeCoordinator(converter: CoordinateSpaceConverter) -> Delegate { Delegate() }    /// Never holds the scroll view's pan back: the two run side by side, the    /// press failing as soon as the finger moves.    final class Delegate: NSObject, UIGestureRecognizerDelegate {        func gestureRecognizer(_ gesture: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith other: UIGestureRecognizer) -> Bool { true }    }}/// Where a dragged scene lands, and how the others part for it; pure, so a test reads it.enum InkReorder {    /// The place a row dragged `offset` points from `from` lands, the rows    /// being `heights` tall: past half of a neighbour, it takes its place.    static func target(from: Int, offset: CGFloat, heights: [CGFloat]) -> Int {        guard heights.indices.contains(from) else { return from }        var at = from        var left = offset        if offset > 0 {            while at + 1 < heights.count, left > heights[at + 1] / 2 {                left -= heights[at + 1]                at += 1            }        } else {            while at > 0, -left > heights[at - 1] / 2 {                left += heights[at - 1]                at -= 1            }        }        return at    }    /// The order with the row at `from` put at `to`.    static func moved(_ ids: [String], from: Int, to: Int) -> [String] {        guard ids.indices.contains(from), ids.indices.contains(to) else { return ids }        var out = ids        let one = out.remove(at: from)        out.insert(one, at: to)        return out    }    /// How far row `at` steps aside while the row at `from`, `lift` tall, is over `to`.    static func parting(_ at: Int, from: Int, to: Int, lift: CGFloat) -> CGFloat {        if from < to, at > from, at <= to { return -lift }        if from > to, at >= to, at < from { return lift }        return 0    }}/// `.sc`: number, place and time, length, ⋯ for its menu; under them, the/// one line. Lifted (being dragged) it stands on the soft blue.struct InkSceneRow: View {    let row: StoryScenesAnswer.Row    /// Its number as shown: the core's, or its place while a drop is answered.    let number: Int?    var lifted = false    var earlier = false    var later = false    let open: () -> Void    let more: () -> Void    /// Move earlier (-1) or later (1), for VoiceOver.    let move: (Int) -> Void    var body: some View {        HStack(alignment: .firstTextBaseline, spacing: 8) {            Text(number.map(String.init) ?? "")                .font(InkType.sceneNumber)                .foregroundStyle(Ink.blue)                .frame(minWidth: 28, alignment: .leading)            VStack(alignment: .leading, spacing: 3) {                HStack(alignment: .firstTextBaseline, spacing: 8) {                    Text(row.title ?? "")                        .font(InkType.sceneTitle)                        .foregroundStyle(Ink.ink)                        .fixedSize(horizontal: false, vertical: true)                        .frame(maxWidth: .infinity, alignment: .leading)                    if let length = row.minutesWord {                        Text(length)                            .font(InkType.sceneLength)                            .foregroundStyle(Ink.quiet)                    }                }                if let line = row.line ?? row.question {                    Text(line)                        .font(InkType.scenePreview)                        .foregroundStyle(Ink.quiet)                        .lineLimit(2)                        .frame(maxWidth: .infinity, alignment: .leading)                }            }            Button(action: more) {                Image(systemName: "ellipsis")                    .font(.system(size: 15, weight: .regular))                    .foregroundStyle(Ink.quiet)                    .frame(minWidth: 32, minHeight: 32)                    .contentShape(Rectangle())            }            .buttonStyle(InkPress())            .accessibilityHidden(true)        }        .padding(.vertical, 14)        .background(Ink.blueSoft.opacity(lifted ? 1 : 0).padding(.horizontal, -8))        .contentShape(Rectangle())        .onTapGesture(perform: open)        .accessibilityElement(children: .combine)        .accessibilityAddTraits(.isButton)        .accessibilityHint(InkWords.line("home.drag_hint"))        .accessibilityAction { open() }        .accessibilityAction(named: InkWords.line("home.row_more")) { more() }        .accessibilityActions {            if earlier { Button(InkWords.line("acts.move_earlier")) { move(-1) } }            if later { Button(InkWords.line("acts.move_later")) { move(1) } }        }    }}/// `.cast`: the faces sideways, ordered by lines spoken, no "+N".struct InkCastRow: View {    let cast: [StoryScenesAnswer.Person]    /// Opens a character's page.    let open: (String) -> Void    /// The name's size as the phone's text size makes it (`InkType.castName`).    @ScaledMetric(relativeTo: .caption) private var nameSize: CGFloat = 12    /// A face's column: the face's own 70 points, or wider when the name's    /// longest word is, so a larger text size never breaks a name between its    /// letters ("Bin / a" at the largest text). IBM Plex Mono's letters are    /// each 0.6 of its size wide.    private func width(_ name: String) -> CGFloat {        let longest = name.split(separator: " ").map(\.count).max() ?? 0        return max(70, (CGFloat(longest) * nameSize * 0.6).rounded(.up) + 4)    }    var body: some View {        ScrollView(.horizontal) {            HStack(alignment: .top, spacing: 16) {                ForEach(cast) { person in                    Button { open(person.id) } label: {                    VStack(spacing: 6) {                        InkPictureFace(initial: person.initial, picture: person.picture, size: 70)                        Text(person.name)                            .font(InkType.castName)                            .foregroundStyle(Ink.ink)                            .multilineTextAlignment(.center)                            .lineLimit(2)                            .fixedSize(horizontal: false, vertical: true)                    }                    .frame(width: width(person.name))                    }                    .buttonStyle(InkPress())                    .accessibilityElement(children: .ignore)                    .accessibilityLabel(InkWords.line("ink.cast_label", ["name": person.name, "lines": InkCounting.lines(person.lines ?? 0)]))                    .accessibilityAddTraits(.isButton)                }            }            .padding(.horizontal, Ink.gutter)            .padding(.vertical, 2)        }        .scrollIndicators(.hidden)        .padding(.horizontal, -Ink.gutter)        .accessibilityLabel(InkWords.line("home.cast"))    }}/// A face whose picture is a media key: drawn from this phone's bytes when/// they are here, else the blue initial (which looks finished on its own).struct InkPictureFace: View {    let initial: String    let picture: String?    var size: CGFloat = 70    @State private var slot = MediaImageSlot()    @Environment(\.cottonCore) private var core    @Environment(\.displayScale) private var scale    var body: some View {        InkFace(initial: initial, picture: slot.image, size: size)            .task(id: picture) { await load() }            .onMediaArrival {                guard !slot.isReady else { return }                await load()            }    }    private func load() async {        let number = slot.begin(picture)        guard let picture, !picture.isEmpty, let core else {            slot.finish(.absent, for: picture, ask: number)            return        }        slot.finish(await MediaImages.load(from: core, key: picture, edge: size * scale), for: picture, ask: number)    }}/// ink.html "A new script, before any scene": one sentence and the next step.struct InkFirstScene: View {    let model: InkStory    var body: some View {        VStack(alignment: .leading, spacing: 14) {            Text(InkWords.line("home.first_title"))                .font(InkType.big)                .foregroundStyle(Ink.ink)                .accessibilityAddTraits(.isHeader)            Text(InkWords.line("home.first_hint"))                .font(InkType.count)                .foregroundStyle(Ink.quiet)                .fixedSize(horizontal: false, vertical: true)            InkFlow(spacing: 10) {                InkButton(words: InkWords.line("home.first_scene")) { Task { await model.newScene() } }                InkButton(words: InkWords.line("home.bring_in"), ghost: true) { model.bringing = true }            }        }        .padding(.top, 26)        .padding(.bottom, 8)        .frame(maxWidth: .infinity, alignment: .leading)    }}/// The first screen, with no script yet (wireframes 8 "Scripts").struct InkNoScripts: View {    let model: InkStory    var body: some View {        ScrollView {            VStack(alignment: .leading, spacing: 18) {                HStack(alignment: .top, spacing: 12) {                    Text(InkWords.line("app.name"))                        .font(InkType.h1)                        .foregroundStyle(Ink.ink)                        .accessibilityAddTraits(.isHeader)                    Spacer(minLength: 0)                    // Settings (and Sign in) before the first script, as from                    // a script's "more" (launch-ios walk, 22 Nov 2026: a new                    // person, or a reviewer told to sign in, found no way in).                    InkGlyph(symbol: "ellipsis", label: InkWords.line("settings.title")) { model.path.append(.settings) }                        .padding(.top, -2)                        .accessibilityIdentifier("story-none-settings")                }                SyncSeenLine(font: InkType.count, color: Ink.quiet) {                    SyncSeenOpens.ask()                    model.path.append(.settings)                }                VStack(alignment: .leading, spacing: 14) {                    Text(InkWords.line("home.none_title"))                        .font(InkType.big)                        .foregroundStyle(Ink.ink)                    Text(InkWords.line("home.none_hint"))                        .font(InkType.count)                        .foregroundStyle(Ink.quiet)                        .fixedSize(horizontal: false, vertical: true)                    InkFlow(spacing: 10) {                        InkButton(words: InkWords.line("home.new_script")) { model.sheet = .naming }                        InkButton(words: InkWords.line("home.bring_in"), ghost: true) { model.bringing = true }                    }                }                .padding(.top, 26)            }            .padding(.horizontal, Ink.gutter)            .padding(.top, 22)            .frame(maxWidth: .infinity, alignment: .leading)        }        .inkGround()    }}/// `.pills`' wrap: capsules in a row that breaks onto the next line, so a/// larger text size never clips them. One wider than the whole line is/// offered the line's width (its words wrap) rather than running off the side.struct InkFlow: Layout {    var spacing: CGFloat = 10    /// A piece's own size, or, wider than `width`, its size within it.    private func measure(_ view: LayoutSubview, within width: CGFloat) -> CGSize {        let ideal = view.sizeThatFits(.unspecified)        guard width.isFinite, ideal.width > width else { return ideal }        return view.sizeThatFits(ProposedViewSize(width: width, height: nil))    }    func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {        let width = proposal.width ?? .infinity        var x: CGFloat = 0, y: CGFloat = 0, line: CGFloat = 0, widest: CGFloat = 0        for view in subviews {            let size = measure(view, within: width)            if x > 0, x + size.width > width {                y += line + spacing                x = 0                line = 0            }            x += size.width + spacing            line = max(line, size.height)            widest = max(widest, x - spacing)        }        return CGSize(width: min(widest, width), height: y + line)    }    func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {        var x = bounds.minX, y = bounds.minY, line: CGFloat = 0        for view in subviews {            let size = measure(view, within: bounds.width)            if x > bounds.minX, x + size.width > bounds.maxX {                y += line + spacing                x = bounds.minX                line = 0            }            view.place(at: CGPoint(x: x, y: y), proposal: ProposedViewSize(size))            x += size.width + spacing            line = max(line, size.height)        }    }}#endif