Cotton code
735 lines · 33.1 KB · SwiftRaw
// A SITE OPEN (sites/DECISIONS.md "A site open", sites.html): the page fills the phone; one bar at the foot, under// the thumb: Sites (the list's three rules, "Back to sites", never an ×), Back, Forward, the name (which sign-in this// is, always; tap to switch, swipe to step) and More. While a page loads, a single thread is pulled along the top edge// of the bar in the accent and ties a small knot when the page is in: the one delight.#if os(iOS)import QuickLookimport SwiftUIimport UIKitstruct SitesSiteView: View {    @Bindable var model: SitesModel    let page: SitesPage    @State private var arrivedShown = true    var body: some View {        VStack(spacing: 0) {            strip            ZStack {                Color.white.opacity(0.001)                SitesWebView(page: page)                    .accessibilityIdentifier("sites-page")                if let picture = page.picture {                    // The page as it was left, while one the system took back loads again. Nothing is said.                    Image(uiImage: picture).resizable().scaledToFill()                        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)                        .clipped()                        .allowsHitTesting(false)                        .accessibilityHidden(true)                }                if let failing = page.failed {                    SitesFailedPage(model: model, page: page, url: failing)                }            }            .frame(maxWidth: .infinity, maxHeight: .infinity)            if model.finding {                SitesFindBar(model: model, page: page)            } else {                SitesBar(model: model, page: page)            }        }        .background(Cranberry.ground.ignoresSafeArea())        .overlay { asking }        .task(id: page.arrived?.line) {            guard page.arrived != nil else { return }            arrivedShown = true            try? await Task.sleep(for: .seconds(6))            withAnimation(.easeOut(duration: 0.3)) { arrivedShown = false }            page.arrived = nil        }    }    /// `.strip`: what a quick visit or a search says, or where a link from another app landed.    @ViewBuilder private var strip: some View {        if let arrived = page.arrived, arrivedShown {            SitesStrip(icon: .check, words: arrived.line, end: arrived.wrong) {                if let url = page.url?.absoluteString { Task { await model.choose(url, moving: true) } }            }            .accessibilityIdentifier("sites-arrived")        } else if let quick = page.quick {            SitesStrip(icon: .quick, words: quick.strip, end: nil, act: nil)                .accessibilityIdentifier("sites-quick-strip")        }    }    /// A page's question, a link out, a file, a result to choose for: each in Sites' own sheet, headed by the address.    @ViewBuilder private var asking: some View {        if let asked = page.asking {            switch asked {            case .panel(let kind, let text, let defaultText, let answer):                SitesPanelSheet(model: model, page: page, kind: kind, text: text, defaultText: defaultText) { yes, typed in                    page.asking = nil                    answer(yes, typed)                }            case .exit(let url):                SitesExitSheet(model: model, url: url) { page.asking = nil }            case .file(let file, let from):                SitesFileViewer(file: file, from: from) { page.asking = nil }                    .transition(.move(edge: .bottom))            case .choose(let url):                Color.clear.task {                    page.asking = nil                    await model.choose(url.absoluteString)                }            }        }    }}/// `.strip`: one line the app lays over a page, in its own paper.struct SitesStrip: View {    let icon: SitesIcon    let words: String    let end: String?    let act: (() -> Void)?    var body: some View {        HStack(alignment: .firstTextBaseline, spacing: 10) {            SitesGlyph(icon: icon, size: 18).alignmentGuide(.firstTextBaseline) { $0[.bottom] - 4 }            Text(words).font(SitesType.line).foregroundStyle(Cranberry.ink)                .frame(maxWidth: .infinity, alignment: .leading)            if let end, let act {                Button(action: act) { Text(end).font(SitesType.sans(14, .bold)).foregroundStyle(Cranberry.ink) }                    .buttonStyle(.plain)                    .accessibilityIdentifier("sites-wrong-place")            }        }        .padding(.horizontal, 16).padding(.vertical, 10)        .background(Cranberry.ground)        .overlay(alignment: .bottom) { SitesRule() }        .accessibilityElement(children: .combine)    }}// MARK: - The barstruct SitesBar: View {    @Bindable var model: SitesModel    let page: SitesPage    @State private var swipe: CGFloat = 0    var body: some View {        HStack(spacing: 4) {            button(.sites, SitesWords.line("a11y.sites"), "sites-bar-sites") { Task { await model.backToList() } }            button(.back, SitesWords.line("bar.back"), "sites-bar-back", off: !page.canBack) { page.web.goBack() }            button(.next, SitesWords.line("bar.forward"), "sites-bar-forward", off: !page.canForward) { page.web.goForward() }            name            if let quick = page.quick {                button(.close, quick.close, "sites-bar-close") { Task { await model.closePage() } }            } else {                button(.more, SitesWords.line("bar.more"), "sites-bar-more") { model.sheet = .more }            }        }        .padding(.horizontal, 12)        .padding(.top, 9)        .padding(.bottom, 6)        .background(Cranberry.ground.ignoresSafeArea(edges: .bottom))        .overlay(alignment: .top) {            ZStack(alignment: .top) {                SitesRule()                SitesThread(loading: page.loading, progress: page.progress)            }        }    }    private func button(_ icon: SitesIcon, _ label: String, _ tag: String, off: Bool = false, _ act: @escaping () -> Void) -> some View {        Button(action: act) {            SitesGlyph(icon: icon)                .foregroundStyle(off ? Cranberry.faint : Cranberry.ink)                .frame(width: 40, height: 44)                .contentShape(Rectangle())        }        .buttonStyle(.plain)        .disabled(off)        .accessibilityLabel(label)        .accessibilityIdentifier(tag)    }    /// `.pillx`: the site's letter, its name, the address under it. Tap to switch; only the name takes a sideways    /// swipe, so it never fights the page's own.    private var name: some View {        let quick = page.quick        let address = page.url.map { url in (url.host().map { $0.hasPrefix("www.") ? String($0.dropFirst(4)) : $0 } ?? "") + (url.path == "/" ? "" : url.path) } ?? ""        return Button { model.sheet = .switcher } label: {            HStack(spacing: 9) {                if let row = page.row {                    SitesLetter(letter: row.letter, kind: row.hidden ? .hidden : .plain, size: 24)                } else {                    SitesLetter(letter: "", kind: .quick, size: 24)                }                VStack(alignment: .leading, spacing: 0) {                    Text(page.row?.label ?? quick?.name ?? "").font(SitesType.barName).foregroundStyle(Cranberry.ink).lineLimit(1).minimumScaleFactor(0.6)                    Text(quick != nil && page.engineHost != nil ? (quick?.nameLine ?? "") : address)                        .font(SitesType.barAddress).foregroundStyle(Cranberry.quiet).lineLimit(1).truncationMode(.middle)                }                .frame(maxWidth: .infinity, alignment: .leading)            }            .padding(.leading, 7).padding(.trailing, 10).padding(.vertical, 6)            .overlay(RoundedRectangle(cornerRadius: 14).strokeBorder(Cranberry.rule, style: StrokeStyle(lineWidth: 1, dash: quick == nil ? [] : [4, 3])))            .contentShape(RoundedRectangle(cornerRadius: 14))            .offset(x: swipe)        }        .buttonStyle(.plain)        .simultaneousGesture(DragGesture(minimumDistance: 18).onChanged { drag in            guard page.row != nil, abs(drag.translation.width) > abs(drag.translation.height) else { return }            swipe = drag.translation.width / 3        }.onEnded { drag in            withAnimation(.easeOut(duration: 0.18)) { swipe = 0 }            guard page.row != nil, abs(drag.translation.width) > 60, abs(drag.translation.width) > abs(drag.translation.height) else { return }            Task { await model.step(drag.translation.width < 0 ? 1 : -1) }        })        .accessibilityElement(children: .ignore)        .accessibilityLabel([page.row?.label ?? quick?.name, address].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: ", "))        .accessibilityAddTraits(.isButton)        .accessibilityHint(SitesWords.line("bar.switch"))        .accessibilityIdentifier("sites-bar-name")        .accessibilityAdjustableAction { direction in            Task { await model.step(direction == .increment ? 1 : -1) }        }    }}/// The thread: pulled along the top edge of the bar while a page loads, a small knot tied at the end when it is in,/// then gone. With reduced motion it stands drawn, then goes.struct SitesThread: View {    let loading: Bool    let progress: Double    @Environment(\.accessibilityReduceMotion) private var still    @State private var drawn: CGFloat = 0    @State private var knot: CGFloat = 0    @State private var shown = false    var body: some View {        GeometryReader { box in            ZStack(alignment: .leading) {                Rectangle().fill(Cranberry.accent).frame(width: box.size.width * drawn, height: 1.5)                Circle().strokeBorder(Cranberry.accent, lineWidth: 1.5)                    .frame(width: 9, height: 9)                    .scaleEffect(knot)                    .offset(x: box.size.width - 9, y: -0.25)            }            .opacity(shown ? 1 : 0)        }        .frame(height: 1.5)        .offset(y: -1)        .allowsHitTesting(false)        .accessibilityHidden(true)        .onChange(of: loading, initial: true) { _, now in now ? begin() : end() }        .onChange(of: progress) { _, now in            guard loading, !still else { return }            withAnimation(.timingCurve(0.3, 0.6, 0.3, 1, duration: 0.6)) { drawn = max(drawn, CGFloat(max(0.12, now)) * 0.96) }        }    }    private func begin() {        knot = 0        shown = true        if still { drawn = 1; return }        drawn = 0        withAnimation(.timingCurve(0.3, 0.6, 0.3, 1, duration: 0.6)) { drawn = CGFloat(max(0.12, progress)) * 0.96 }    }    private func end() {        guard shown else { return }        if still {            Task { @MainActor in try? await Task.sleep(for: .milliseconds(400)); shown = false }            return        }        withAnimation(.easeOut(duration: 0.25)) { drawn = 1 }        withAnimation(.spring(response: 0.3, dampingFraction: 0.5).delay(0.22)) { knot = 1 }        Task { @MainActor in            try? await Task.sleep(for: .milliseconds(900))            withAnimation(.easeOut(duration: 0.4)) { shown = false }        }    }}// MARK: - Find on this pagestruct SitesFindBar: View {    @Bindable var model: SitesModel    let page: SitesPage    @State private var words = ""    @State private var count = 0    @State private var at = 0    @FocusState private var focused: Bool    var body: some View {        HStack(spacing: 8) {            HStack(spacing: 8) {                SitesGlyph(icon: .search, size: 18).foregroundStyle(Cranberry.quiet)                TextField(SitesWords.line("find.line"), text: $words)                    .font(SitesType.bodySmall)                    .foregroundStyle(Cranberry.ink)                    .tint(Cranberry.accent)                    .focused($focused)                    .submitLabel(.search)                    .textInputAutocapitalization(.never)                    .autocorrectionDisabled()                    .onSubmit { step(back: false) }                    .accessibilityIdentifier("sites-find-field")                if !words.isEmpty {                    Text(countWords).font(SitesType.line).foregroundStyle(Cranberry.quiet).lineLimit(1)                        .accessibilityIdentifier("sites-find-count")                }            }            .padding(.horizontal, 12).padding(.vertical, 9)            .overlay(RoundedRectangle(cornerRadius: 14).strokeBorder(Cranberry.ink, lineWidth: 1))            Button { step(back: true) } label: { SitesGlyph(icon: .back).frame(width: 34, height: 44) }                .buttonStyle(.plain).accessibilityLabel(SitesWords.line("find.previous"))            Button { step(back: false) } label: { SitesGlyph(icon: .next).frame(width: 34, height: 44) }                .buttonStyle(.plain).accessibilityLabel(SitesWords.line("find.next"))            Button { model.finding = false } label: {                Text(SitesWords.line("find.done")).font(SitesType.sans(17, .bold)).padding(.horizontal, 4)            }            .buttonStyle(.plain)            .accessibilityIdentifier("sites-find-done")        }        .foregroundStyle(Cranberry.ink)        .padding(.horizontal, 12).padding(.top, 9).padding(.bottom, 6)        .background(Cranberry.ground.ignoresSafeArea(edges: .bottom))        .overlay(alignment: .top) { SitesRule() }        .onAppear { focused = true }        .task(id: words) {            try? await Task.sleep(for: .milliseconds(250))            guard !Task.isCancelled else { return }            count = await page.count(words)            at = count > 0 ? 1 : 0            if count > 0 { _ = await page.find(words, back: false) }        }    }    private var countWords: String {        if count == 0 { return SitesWords.line("find.count.zero") }        return "\(at) / \(count)"    }    private func step(back: Bool) {        guard count > 0 else { return }        Task {            _ = await page.find(words, back: back)            at = back ? (at <= 1 ? count : at - 1) : (at >= count ? 1 : at + 1)        }    }}// MARK: - When a page can't loadstruct SitesFailedPage: View {    @Bindable var model: SitesModel    let page: SitesPage    let url: URL    @State private var words: SitesFailed?    @State private var waiting = false    private var reach: SitesReach { SitesReach.shared }    var body: some View {        ScrollView {            VStack(alignment: .leading, spacing: 0) {                SitesGlyph(icon: reach.online ? .rest : .wifi, size: 44, weight: 1.4)                    .foregroundStyle(Cranberry.ink)                if let words {                    Text(words.title)                        .font(SitesType.sans(26, .bold, .title1))                        .foregroundStyle(Cranberry.ink)                        .fixedSize(horizontal: false, vertical: true)                        .padding(.top, 18)                        .accessibilityAddTraits(.isHeader)                        .accessibilityIdentifier("sites-failed-title")                    Text(words.line)                        .font(SitesType.body).foregroundStyle(Cranberry.quiet)                        .fixedSize(horizontal: false, vertical: true)                        .padding(.top, 14)                    VStack(spacing: 10) {                        Button(words.again) { page.again() }                            .buttonStyle(SitesButtonStyle(kind: .go))                            .accessibilityIdentifier("sites-failed-again")                        if let whenBack = words.whenBack, !waiting {                            Button(whenBack) { waiting = true }                                .buttonStyle(SitesButtonStyle(kind: .quiet))                                .accessibilityIdentifier("sites-failed-when-back")                        }                    }                    .padding(.top, 28)                }            }            .padding(.horizontal, 26)            .padding(.top, 60)            .frame(maxWidth: .infinity, alignment: .leading)        }        .background(Cranberry.ground)        .task(id: reach.online) {            words = try? await model.book.failed(id: page.row?.id, url: url.absoluteString, offline: !reach.online)            // Offline it tries again by itself once the phone is back; asked, it tries again when the site answers.            if reach.online, wasOffline { page.again() }            wasOffline = !reach.online        }        .task(id: waiting) {            guard waiting else { return }            while waiting, !Task.isCancelled {                try? await Task.sleep(for: .seconds(15))                if (try? await URLSession(configuration: .ephemeral).data(for: URLRequest(url: url, timeoutInterval: 10))) != nil {                    page.again()                    waiting = false                }            }        }    }    @State private var wasOffline = false}// MARK: - Morestruct SitesMoreSheet: View {    @Bindable var model: SitesModel    var body: some View {        if let page = model.page {            VStack(alignment: .leading, spacing: 0) {                head(page)                VStack(spacing: 0) {                    control(.find, SitesWords.line("more.find"), tag: "sites-more-find") { model.sheet = nil; model.finding = true }                    if let url = page.url {                        ShareLink(item: url) {                            controlLabel(.share, SitesWords.line("more.share"), end: nil)                        }                        .buttonStyle(.plain)                        .accessibilityIdentifier("sites-more-share")                        SitesRule()                        control(.copy, SitesWords.line("more.copy"), tag: "sites-more-copy") {                            UIPasteboard.general.url = url                            model.sheet = nil                            model.tell(SitesWords.line("more.copied"))                        }                    }                    control(nil, SitesWords.line("more.size"), end: "\(Int((page.zoom * 100).rounded()))%", tag: "sites-more-size") { model.sheet = .size }                    if let url = page.url {                        control(.move, SitesWords.line("more.open_in"), tag: "sites-more-open-in") {                            Task { await model.choose(url.absoluteString, moving: true) }                        }                    }                    control(.reload, SitesWords.line("more.again"), tag: "sites-more-again") { model.sheet = nil; page.again() }                    if let row = page.row {                        if row.stay {                            control(.close, SitesWords.line("more.close"), line: SitesWords.line("more.close_line"), tag: "sites-more-close") {                                Task { await model.closePage() }                            }                        } else {                            control(.close, SitesWords.line("more.forget"), tag: "sites-more-forget") { Task { await model.askForget() } }                        }                        control(.gear, SitesWords.line("more.settings"), tag: "sites-more-settings", last: true) { model.sheet = .site(row) }                    } else {                        control(.close, page.quick?.close ?? SitesWords.line("bar.close"), tag: "sites-more-close", last: true) {                            Task { await model.closePage() }                        }                    }                }                .padding(.top, 8)            }        }    }    private func head(_ page: SitesPage) -> some View {        HStack(spacing: 12) {            if let row = page.row { SitesLetter(letter: row.letter, kind: row.hidden ? .hidden : .plain) } else { SitesLetter(letter: "", kind: .quick) }            VStack(alignment: .leading, spacing: 2) {                Text(page.row?.label ?? page.quick?.name ?? "").font(SitesType.sans(18, .bold, .headline)).foregroundStyle(Cranberry.ink)                Text([page.url.map { ($0.host() ?? "") + ($0.path == "/" ? "" : $0.path) }, page.row.flatMap { $0.stay ? nil : SitesWords.line("row.forgets") }]                        .compactMap { $0 }.joined(separator: " · "))                    .font(SitesType.line).foregroundStyle(Cranberry.quiet).lineLimit(2)            }        }        .accessibilityElement(children: .combine)    }    private func controlLabel(_ icon: SitesIcon?, _ label: String, line: String? = nil, end: String?) -> some View {        HStack(spacing: 12) {            Group {                if let icon { SitesGlyph(icon: icon) } else { Text("Aa").font(SitesType.sans(15, .bold)) }            }            .frame(minWidth: 28)            VStack(alignment: .leading, spacing: 2) {                Text(label).font(SitesType.body).foregroundStyle(Cranberry.ink)                if let line { Text(line).font(SitesType.line).foregroundStyle(Cranberry.quiet) }            }            .frame(maxWidth: .infinity, alignment: .leading)            if let end { Text(end).font(SitesType.line).foregroundStyle(Cranberry.quiet) }        }        .foregroundStyle(Cranberry.ink)        .padding(.vertical, 12)        .contentShape(Rectangle())    }    private func control(_ icon: SitesIcon?, _ label: String, line: String? = nil, end: String? = nil, tag: String, last: Bool = false, _ act: @escaping () -> Void) -> some View {        VStack(spacing: 0) {            Button(action: act) { controlLabel(icon, label, line: line, end: end) }                .buttonStyle(.plain)                .accessibilityElement(children: .combine)                .accessibilityIdentifier(tag)            if !last { SitesRule() }        }    }}/// Page text size: smaller, larger, reset; kept for the site while Sites runs.struct SitesSizeSheet: View {    @Bindable var model: SitesModel    var body: some View {        if let page = model.page {            VStack(alignment: .leading, spacing: 14) {                Text(SitesWords.line("size.title")).font(SitesType.sheetTitle).foregroundStyle(Cranberry.ink)                    .accessibilityAddTraits(.isHeader)                Text("\(Int((page.zoom * 100).rounded()))%")                    .font(SitesType.sans(30, .bold, .title1)).foregroundStyle(Cranberry.ink)                    .accessibilityIdentifier("sites-size-value")                HStack(spacing: 10) {                    Button(SitesWords.line("size.smaller")) { change(page, -0.1) }.buttonStyle(SitesButtonStyle(kind: .plain))                        .accessibilityIdentifier("sites-size-smaller")                    Button(SitesWords.line("size.larger")) { change(page, 0.1) }.buttonStyle(SitesButtonStyle(kind: .plain))                        .accessibilityIdentifier("sites-size-larger")                }                Button(SitesWords.line("size.reset")) { page.zoom = 1; SitesLive.shared.keepZoom(page) }                    .buttonStyle(SitesButtonStyle(kind: .quiet))            }        }    }    private func change(_ page: SitesPage, _ by: CGFloat) {        page.zoom = min(2, max(0.5, (page.zoom + by) * 10).rounded() / 10)        SitesLive.shared.keepZoom(page)    }}// MARK: - Switchingstruct SitesSwitcherSheet: View {    @Bindable var model: SitesModel    var body: some View {        VStack(alignment: .leading, spacing: 0) {            Button { model.sheet = nil; model.place = .search } label: {                HStack(spacing: 8) {                    SitesGlyph(icon: .search, size: 20)                    Text(SitesWords.line("search.line")).font(SitesType.bodySmall).frame(maxWidth: .infinity, alignment: .leading)                }                .foregroundStyle(Cranberry.faint)                .padding(.horizontal, 12).padding(.vertical, 11)                .overlay(RoundedRectangle(cornerRadius: 14).strokeBorder(Cranberry.rule, lineWidth: 1))                .contentShape(Rectangle())            }            .buttonStyle(.plain)            .accessibilityIdentifier("sites-switcher-search")            VStack(spacing: 0) {                ForEach(Array(model.rows.enumerated()), id: \.element.id) { at, row in                    let here = model.page?.row?.id == row.id                    Button {                        if here { model.sheet = nil } else { Task { await model.open(row) } }                    } label: {                        HStack(spacing: 12) {                            SitesLetter(letter: row.letter, kind: row.hidden ? .hidden : .plain)                            VStack(alignment: .leading, spacing: 2) {                                Text(row.label).font(SitesType.name).foregroundStyle(Cranberry.ink).lineLimit(2)                                Text(row.line).font(SitesType.line).foregroundStyle(Cranberry.quiet).lineLimit(2)                            }                            .frame(maxWidth: .infinity, alignment: .leading)                            if here {                                Text(SitesWords.line("switch.here")).font(SitesType.sans(13, .bold, .footnote)).foregroundStyle(Cranberry.accent)                            } else if model.isLive(row.id) {                                SitesLiveDot()                            }                        }                        .padding(.vertical, 11)                        .contentShape(Rectangle())                    }                    .buttonStyle(.plain)                    .accessibilityElement(children: .ignore)                    .accessibilityLabel([row.label, row.line, here ? SitesWords.line("switch.here") : (model.isLive(row.id) ? SitesWords.line("a11y.live") : nil)]                        .compactMap { $0 }.joined(separator: ", "))                    .accessibilityAddTraits(here ? [.isButton, .isSelected] : .isButton)                    .accessibilityIdentifier("sites-switch-\(row.id)")                    if at < model.rows.count - 1 { SitesRule() }                }            }            .padding(.top, 6)            HStack(spacing: 10) {                Button { model.startQuick() } label: {                    HStack(spacing: 8) { SitesGlyph(icon: .quick, size: 20); Text(SitesWords.line("quick.label")) }                }                .buttonStyle(SitesButtonStyle(kind: .quiet))                .accessibilityIdentifier("sites-switcher-quick")                Button(SitesWords.line("switch.all")) { model.sheet = nil; Task { await model.backToList() } }                    .buttonStyle(SitesButtonStyle(kind: .quiet))                    .accessibilityIdentifier("sites-switcher-all")            }            .padding(.top, 14)        }    }}// MARK: - A page's questions, links out, files/// An alert, a confirm or a prompt: the page's own words drawn under Sites' head ("club.example asks"), as text.struct SitesPanelSheet: View {    @Bindable var model: SitesModel    let page: SitesPage    let kind: String    let text: String    let defaultText: String?    let answer: (Bool, String?) -> Void    @State private var words: SitesPanel?    @State private var typed = ""    var body: some View {        SitesSheet(close: { answer(false, nil) }, tag: "sites-panel-\(kind)") {            VStack(alignment: .leading, spacing: 0) {                Text(words?.head ?? "").font(SitesType.line).foregroundStyle(Cranberry.quiet)                    .padding(.top, 4)                    .accessibilityIdentifier("sites-panel-head")                Text(text)                    .font(SitesType.sans(21, .bold, .title3)).foregroundStyle(Cranberry.ink)                    .fixedSize(horizontal: false, vertical: true)                    .padding(.top, 6)                if kind == "prompt" {                    TextField("", text: $typed)                        .font(SitesType.body).foregroundStyle(Cranberry.ink).tint(Cranberry.accent)                        .padding(.vertical, 12)                        .overlay(alignment: .bottom) { Rectangle().fill(Cranberry.ink).frame(height: 1) }                        .padding(.top, 12)                        .accessibilityIdentifier("sites-panel-field")                }                HStack(spacing: 10) {                    if kind != "alert" {                        Button(words?.cancel ?? "") { answer(false, nil) }.buttonStyle(SitesButtonStyle(kind: .quiet))                            .accessibilityIdentifier("sites-panel-cancel")                    }                    Button(words?.ok ?? "") { answer(true, typed) }.buttonStyle(SitesButtonStyle(kind: .go))                        .accessibilityIdentifier("sites-panel-ok")                }                .padding(.top, 24)            }        }        .task {            typed = defaultText ?? ""            words = try? await model.book.panel(kind, url: page.url?.absoluteString ?? "")        }    }}/// A link out of the web: where it goes, asked first, with Stay here never hidden.struct SitesExitSheet: View {    @Bindable var model: SitesModel    let url: URL    let done: () -> Void    @State private var words: SitesExit?    @Environment(\.openURL) private var openURL    var body: some View {        SitesSheet(close: done, tag: "sites-exit") {            VStack(alignment: .leading, spacing: 0) {                if let line = words?.line {                    Text(line)                        .font(SitesType.sans(24, .bold, .title2)).foregroundStyle(Cranberry.ink)                        .fixedSize(horizontal: false, vertical: true)                        .padding(.top, 6)                        .accessibilityIdentifier("sites-exit-line")                    VStack(spacing: 10) {                        Button(words?.go ?? "") { done(); openURL(url) }.buttonStyle(SitesButtonStyle(kind: .go))                            .accessibilityIdentifier("sites-exit-go")                        Button(words?.stay ?? "") { done() }.buttonStyle(SitesButtonStyle(kind: .quiet))                            .accessibilityIdentifier("sites-exit-stay")                    }                    .padding(.top, 22)                }            }        }        .task {            do {                let answer = try await model.book.exit(url.absoluteString)                if answer.inside == true { done(); model.page?.go(url) } else { words = answer }            } catch {                done()                model.tell((error as? SitesRefusal)?.words ?? SitesWords.line("exit.refused"))            }        }    }}/// A file a page gave: Sites' own viewer, held only while open; Save to Files keeps it, Share hands it on.struct SitesFileViewer: View {    let file: URL    let from: String    let done: () -> Void    @State private var saving = false    var body: some View {        VStack(spacing: 0) {            HStack {                Button(SitesWords.line("viewer.close")) { finish() }                    .font(SitesType.sans(17, .bold)).foregroundStyle(Cranberry.ink).buttonStyle(.plain)                    .accessibilityIdentifier("sites-viewer-close")                Text(file.lastPathComponent).font(SitesType.sans(15, .semibold)).foregroundStyle(Cranberry.ink)                    .lineLimit(1).truncationMode(.middle).frame(maxWidth: .infinity)                Color.clear.frame(width: 50, height: 1)            }            .padding(.horizontal, Cranberry.side).padding(.vertical, 12)            SitesQuickLook(file: file)                .clipShape(RoundedRectangle(cornerRadius: 10))                .overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(Cranberry.rule, lineWidth: 1))                .padding(.horizontal, 14)            Text(SitesWords.line("viewer.from", ["host": from]))                .font(SitesType.line).foregroundStyle(Cranberry.quiet).padding(.top, 10)            HStack(spacing: 10) {                Button { saving = true } label: {                    HStack(spacing: 8) { SitesGlyph(icon: .open, size: 20); Text(SitesWords.line("viewer.save")) }                }                .buttonStyle(SitesButtonStyle(kind: .quiet))                .accessibilityIdentifier("sites-viewer-save")                ShareLink(item: file) {                    HStack(spacing: 8) { SitesGlyph(icon: .share, size: 20); Text(SitesWords.line("viewer.share")) }                }                .buttonStyle(SitesButtonStyle(kind: .quiet))                .accessibilityIdentifier("sites-viewer-share")            }            .padding(.horizontal, Cranberry.side).padding(.vertical, 12)        }        .background(Cranberry.ground.ignoresSafeArea())        .fileMover(isPresented: $saving, file: file) { _ in }    }    private func finish() {        try? FileManager.default.removeItem(at: file.deletingLastPathComponent())        done()    }}struct SitesQuickLook: UIViewControllerRepresentable {    let file: URL    func makeUIViewController(context: Context) -> QLPreviewController {        let preview = QLPreviewController()        preview.dataSource = context.coordinator        return preview    }    func updateUIViewController(_ preview: QLPreviewController, context: Context) {}    func makeCoordinator() -> Source { Source(file: file) }    final class Source: NSObject, QLPreviewControllerDataSource {        let file: URL        init(file: URL) { self.file = file }        func numberOfPreviewItems(in controller: QLPreviewController) -> Int { 1 }        func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem { file as NSURL }    }}#endif