Cotton code
463 lines · 22.5 KB · SwiftRaw
// A THREAD (mail.html "Reading a thread"): Back, Archive and Delete at the top; the subject in the reading face;// earlier mails folded to one line each, the newest open, its words in Newsreader so it reads like a letter; its links// tappable (Read here, or Open in Sites…); attachments as rows that say whether they are on the phone, fetched and// opened inside Post on a tap; "Show the designed page" with remote pictures off until he asks; Reply, Reply all and// Forward at the foot, all written in Post. Reading marks it read here and in his mailbox (the core does both).// `mail.thread`, `mail.page`, `mail.file`, `mail.link`, `mail.act`, `mail.archive`.#if os(iOS)import CottonKitimport SwiftUIimport UIKitimport WebKitstruct PostThreadScreen: View {    let model: PostModel    let thread: String    @State private var read: PostRead<PostThread>?    @State private var opened: Set<String> = []    @State private var after: PostAfter?    @State private var designed: String?    @State private var said: [String: String] = [:]    /// The mails whose quoted tail he unfolded.    @State private var unfolded: Set<String> = []    @State private var link: (url: URL, choice: PostLinkChoice?)?    var body: some View {        VStack(spacing: 0) {            PostBar(back: PostWords.line("home.title"), onBack: { model.pop() }) {                if let thread = read?.answer?.thread {                    // The whole conversation: Archive takes all its mail in the Inbox, Delete all of it.                    HStack(spacing: 18) {                        iconButton("archivebox", PostWords.line("act.archive"), id: "post-thread-archive") {                            Task { if case .read(let done) = await model.archive(scope: "thread", key: thread) { after = done } }                        }                        iconButton("trash", PostWords.line("act.delete"), id: "post-thread-delete") {                            Task { if case .read(let done) = await model.act("delete", thread: thread) { after = done } }                        }                    }                }            }            .padding(.horizontal, PostInk.side)            ScrollView {                VStack(alignment: .leading, spacing: 0) {                    switch read {                    case .read(let thread)?: content(thread)                    case .refused(let line)?: PostRefused(line: line)                    case nil: EmptyView()                    }                }                .padding(.horizontal, PostInk.side)                .padding(.bottom, 24)            }            if let acts = read?.answer?.acts { foot(acts) }        }        .background(PostInk.ground)        .task(id: model.generation) {            let now = await model.read("mail.thread", ["thread": .string(thread)], as: PostThread.self)            read = now            if opened.isEmpty, let newest = now.answer?.messages.last { opened = [newest.email] }        }        .confirmationDialog("", isPresented: Binding(get: { link?.choice != nil }, set: { if !$0 { link = nil } }), titleVisibility: .hidden) {            if let link, let choice = link.choice {                Button(choice.read) { model.sheet = .reader(link.url, back: read?.answer?.subject ?? PostWords.line("home.title")) }                if let sites = choice.sitesURL { Button(choice.sites) { UIApplication.shared.open(sites) } }            }        }        .accessibilityIdentifier("post-thread")    }    private func iconButton(_ symbol: String, _ label: String, id: String, _ action: @escaping () -> Void) -> some View {        Button(action: action) {            Image(systemName: symbol).font(.system(size: 18, weight: .light)).foregroundStyle(PostInk.ink).frame(width: 36, height: 44).contentShape(Rectangle())        }        .buttonStyle(PostPressStyle())        .accessibilityLabel(Text(label))        .accessibilityIdentifier(id)    }    @ViewBuilder private func content(_ thread: PostThread) -> some View {        Text(thread.subject)            .font(PostType.serif(30, .medium, relativeTo: .largeTitle))            .foregroundStyle(PostInk.ink)            .fixedSize(horizontal: false, vertical: true)            .padding(.top, 4)            .accessibilityAddTraits(.isHeader)        Text(thread.with.name).font(PostType.small).foregroundStyle(PostInk.quiet).padding(.top, 2)        PostAfterView(model: model, after: $after).padding(.top, 8)        ForEach(Array(thread.messages.enumerated()), id: \.element.id) { index, message in            // A machine's mail wears the machine's square mark; his own and a person's, a round face.            let shown = message.mine || thread.who != "machine" ? message : message.wearing("machine")            if opened.contains(message.email) {                letter(shown, thread: thread)            } else {                folded(shown)            }            if index < thread.messages.count - 1 { PostRule() }        }    }    /// An earlier mail, folded to one line: who, when, and how it begins. A tap opens it.    private func folded(_ message: PostThread.Message) -> some View {        Button { opened.insert(message.email) } label: {            HStack(alignment: .top, spacing: 10) {                PostFace(from: message.from, size: 26)                VStack(alignment: .leading, spacing: 3) {                    HStack {                        Text(message.from.name).font(PostType.sans(16, .medium)).foregroundStyle(PostInk.ink)                        Spacer()                        Text(message.when).font(PostType.end).foregroundStyle(PostInk.quiet)                    }                    Text(message.text.split(whereSeparator: \.isNewline).first.map(String.init) ?? "")                        .font(PostType.small).foregroundStyle(PostInk.quiet).lineLimit(1)                }            }            .padding(.vertical, 12)            .contentShape(Rectangle())        }        .buttonStyle(PostPressStyle())        .accessibilityElement(children: .combine)        .accessibilityIdentifier("post-folded-\(message.email)")    }    /// The open mail: who, to whom and when; its words in the reading face; its attachments; the designed page.    @ViewBuilder private func letter(_ message: PostThread.Message, thread: PostThread) -> some View {        VStack(alignment: .leading, spacing: 0) {            HStack(alignment: .top, spacing: 10) {                PostFace(from: message.from, size: 36)                VStack(alignment: .leading, spacing: 1) {                    Text(message.from.name).font(PostType.sans(16.5, .bold)).foregroundStyle(PostInk.ink)                    Text([message.to, message.when].compactMap { $0 }.joined(separator: " · "))                        .font(PostType.small).foregroundStyle(PostInk.quiet).fixedSize(horizontal: false, vertical: true)                    if let cc = message.cc { Text(cc).font(PostType.small).foregroundStyle(PostInk.quiet).fixedSize(horizontal: false, vertical: true) }                }                Spacer(minLength: 0)            }            .accessibilityElement(children: .combine)            .padding(.top, 14)            if designed == message.email {                PostDesignedPage(model: model, email: message.email, pictures: thread.page?.pictures)                    .padding(.top, 12)            } else {                Text(words(message.text, links: message.links))                    .font(PostType.letter)                    .foregroundStyle(PostInk.ink)                    .lineSpacing(5)                    .textSelection(.enabled)                    .fixedSize(horizontal: false, vertical: true)                    .padding(.top, 12)                    .environment(\.openURL, OpenURLAction { url in                        Task { await choose(url) }                        return .handled                    })            }            if let quoted = message.quoted {                PostWordButton(label: quoted.label, accent: false, id: "post-thread-quoted") {                    if unfolded.contains(message.email) { unfolded.remove(message.email) } else { unfolded.insert(message.email) }                }                .padding(.top, 8)                if unfolded.contains(message.email) {                    Text(words(quoted.text, links: quoted.links))                        .font(PostType.letter)                        .foregroundStyle(PostInk.quiet)                        .lineSpacing(4)                        .textSelection(.enabled)                        .fixedSize(horizontal: false, vertical: true)                        .padding(.leading, 12)                        .overlay(alignment: .leading) { Rectangle().fill(PostInk.rule).frame(width: 2) }                        .padding(.top, 6)                        .environment(\.openURL, OpenURLAction { url in                            Task { await choose(url) }                            return .handled                        })                }            }            if let page = thread.page, !message.mine {                PostWordButton(label: designed == message.email ? PostWords.line("thread.plain") : page.label, accent: false, id: "post-thread-page") {                    designed = designed == message.email ? nil : message.email                }                .padding(.top, 8)            }            ForEach(message.attachments) { attachment in                attachmentRow(attachment, email: message.email)            }        }        .padding(.bottom, 14)    }    /// The mail's words with its links marked where the core found them, each opening the choice of where to read it.    private func words(_ source: String, links: [PostThread.Link]?) -> AttributedString {        var text = AttributedString(source)        let utf16 = Array(source.utf16)        for link in links ?? [] where link.at.count == 2 {            guard link.at[0] >= 0, link.at[1] <= utf16.count, link.at[0] < link.at[1], let url = URL(string: link.url) else { continue }            let start = String.Index(utf16Offset: link.at[0], in: source)            let end = String.Index(utf16Offset: link.at[1], in: source)            guard let lower = AttributedString.Index(start, within: text), let upper = AttributedString.Index(end, within: text) else { continue }            text[lower..<upper].link = url            text[lower..<upper].underlineStyle = .single            text[lower..<upper].foregroundColor = PostInk.ink        }        return text    }    private func attachmentRow(_ attachment: PostThread.Attachment, email: String) -> some View {        let key = "\(email)/\(attachment.index)"        return Button { Task { await open(attachment, email: email) } } label: {            HStack(spacing: 12) {                PostFileMark(name: attachment.name)                VStack(alignment: .leading, spacing: 2) {                    Text(attachment.name).font(PostType.sans(15.5, .bold)).foregroundStyle(PostInk.ink).lineLimit(2)                    if let size = attachment.size { Text(size).font(PostType.small).foregroundStyle(PostInk.quiet) }                    if let note = said[key] ?? attachment.note {                        Text(note).font(PostType.small).foregroundStyle(PostInk.quiet).fixedSize(horizontal: false, vertical: true)                    }                }                Spacer(minLength: 8)                if let line = attachment.line {                    HStack(spacing: 4) {                        Image(systemName: "checkmark").font(.system(size: 11))                        Text(line).font(PostType.end)                    }                    .foregroundStyle(PostInk.quiet)                } else if attachment.can {                    Image(systemName: "icloud.and.arrow.down").font(.system(size: 15, weight: .light)).foregroundStyle(PostInk.quiet)                }            }            .padding(.vertical, 10)            .contentShape(Rectangle())            .overlay(alignment: .top) { PostRule() }        }        .buttonStyle(PostPressStyle())        .disabled(attachment.opens == false)        .accessibilityElement(children: .combine)        .accessibilityIdentifier("post-attachment-\(attachment.index)")    }    /// Fetched when tapped and opened in Post; offline or still coming, it says so on its own row.    private func open(_ attachment: PostThread.Attachment, email: String) async {        let key = "\(email)/\(attachment.index)"        said[key] = nil        let request: [String: JSONValue] = ["email": .string(email), "index": .number(Double(attachment.index)), "dir": .string(PostFilesDir.path), "online": .bool(model.online)]        switch await model.read("mail.file", request, as: PostOpened.self) {        case .read(let file): model.sheet = .file(path: file.path, name: file.name ?? attachment.name, back: read?.answer?.subject ?? PostWords.line("home.title"))        case .refused(let line): said[key] = line        }    }    /// A link: where to read it, as the core words the choice. Sites is offered only when it is on this phone; without    /// an answer, Post's own reader opens it.    private func choose(_ url: URL) async {        guard ["http", "https"].contains(url.scheme?.lowercased() ?? "") else {            if let line = await model.read("mail.link", ["url": .string(url.absoluteString)], as: PostLinkChoice.self).refusal { after = PostAfter(after: "link", line: line) }            return        }        switch await model.read("mail.link", ["url": .string(url.absoluteString)], as: PostLinkChoice.self) {        case .read(var choice):            choice.resolve(url)            if choice.sitesURL == nil {                model.sheet = .reader(url, back: read?.answer?.subject ?? PostWords.line("home.title"))            } else {                link = (url, choice)            }        case .refused:            model.sheet = .reader(url, back: read?.answer?.subject ?? PostWords.line("home.title"))        }    }    private func foot(_ acts: PostThread.Acts) -> some View {        VStack(spacing: 0) {            PostRule()            HStack(spacing: 0) {                footAct("arrowshape.turn.up.left", acts.reply)                if let all = acts.reply_all { footAct("arrowshape.turn.up.left.2", all) }                footAct("arrowshape.turn.up.right", acts.forward)            }            .padding(.top, 6)        }        .padding(.horizontal, PostInk.side)        .dynamicTypeSize(...DynamicTypeSize.xxxLarge)        .accessibilityShowsLargeContentViewer()    }    private func footAct(_ symbol: String, _ act: PostThread.Act) -> some View {        Button {            let newest = read?.answer?.messages.last?.email            model.sheet = .write(mode: act.mode, thread: thread, email: newest, draft: nil)        } label: {            VStack(spacing: 3) {                Image(systemName: symbol).font(.system(size: 17, weight: .light))                Text(act.label).font(PostType.sans(13, relativeTo: .footnote)).lineLimit(1)            }            .foregroundStyle(PostInk.ink)            .frame(maxWidth: .infinity, minHeight: 48)            .contentShape(Rectangle())        }        .buttonStyle(PostPressStyle())        .accessibilityIdentifier("post-thread-\(act.mode)")    }}extension PostThread.Message {    func wearing(_ face: String) -> PostThread.Message {        var copy = self        copy.from.face = face        return copy    }}/// Where attachments and designed pages land on this phone for Post to open them.enum PostFilesDir {    static var path: String {        let dir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appendingPathComponent("post-files", isDirectory: true)        try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)        return dir.path    }}/// `mail.link`: the two ways to read a link, in the core's words. Sites is offered only when it is installed.struct PostLinkChoice: Decodable, Equatable, Sendable {    struct Sites: Decodable, Equatable, Sendable {        struct IOS: Decodable, Equatable, Sendable { var live: String; var dev: String }        var label: String        var ios: IOS?    }    var read: String    var sitesWords: Sites?    var missing: String?    var sitesURL: URL?    var sites: String { sitesWords?.label ?? "" }    enum CodingKeys: String, CodingKey { case read, sitesWords = "sites", missing }    /// The Sites address for `url` when Sites (this build's flavour of it) is on the phone.    @MainActor mutating func resolve(_ url: URL) {        guard let ios = sitesWords?.ios else { return }        let scheme = AppFlavourDev.isDev ? ios.dev : ios.live        let encoded = url.absoluteString.addingPercentEncoding(withAllowedCharacters: .alphanumerics) ?? url.absoluteString        guard let open = URL(string: "\(scheme)://open?url=\(encoded)&from=post"), UIApplication.shared.canOpenURL(open) else { return }        sitesURL = open    }}/// Whether this build is a Dev one (its bundle id ends in `.dev`).enum AppFlavourDev {    static var isDev: Bool { Bundle.main.bundleIdentifier?.hasSuffix(".dev") ?? true }}/// The sender's designed page, with remote pictures held back until he taps Load pictures: loading them tells the/// sender he opened it, and roughly where he is. `mail.page`; "Always for" is `mail.pictures.always`.struct PostDesignedPage: View {    let model: PostModel    let email: String    let pictures: PostThread.Pictures?    @State private var page: PostRead<PostPage>?    @State private var load = false    @State private var said: String?    @State private var height: CGFloat = 420    var body: some View {        VStack(alignment: .leading, spacing: 8) {            if let pictures, !load, page?.answer?.path != nil {                VStack(alignment: .leading, spacing: 6) {                    Text(pictures.line).font(PostType.small).foregroundStyle(PostInk.ink).fixedSize(horizontal: false, vertical: true)                    HStack(spacing: 18) {                        PostWordButton(label: pictures.load, id: "post-pictures-load") { load = true }                        PostWordButton(label: pictures.always, accent: false, id: "post-pictures-always") {                            Task {                                let who: [String: JSONValue] = pictures.sender.map { ["sender": .string($0)] } ?? ["email": .string(email)]                                switch await model.read("mail.pictures.always", who, as: JSONValue.self) {                                case .read: load = true                                case .refused(let line): said = line                                }                            }                        }                    }                    if let said { Text(said).font(PostType.small).foregroundStyle(PostInk.quiet) }                }                .padding(.bottom, 4)                .overlay(alignment: .bottom) { PostRule() }            }            switch page {            case .read(let page)?:                if let path = page.path {                    PostWebPage(file: URL(fileURLWithPath: path), pictures: load, height: $height)                        .frame(height: height)                        .clipShape(RoundedRectangle(cornerRadius: 12))                        .overlay(RoundedRectangle(cornerRadius: 12).strokeBorder(PostInk.rule, lineWidth: 1))                } else if let coming = page.coming {                    PostNote(text: coming)                }            case .refused(let line)?: PostRefused(line: line)            case nil: ProgressView().tint(PostInk.quiet)            }        }        .task {            if pictures?.on == true { load = true }            page = await model.read("mail.page", ["email": .string(email), "dir": .string(PostFilesDir.path), "online": .bool(model.online)], as: PostPage.self)        }    }}/// A sender's page from its file on the phone, with nothing from the web loaded until `pictures` says so, links held/// (a tap is given back to the thread), and its height measured so the thread scrolls it as one.struct PostWebPage: UIViewRepresentable {    let file: URL    let pictures: Bool    @Binding var height: CGFloat    func makeCoordinator() -> Coordinator { Coordinator(height: $height) }    func makeUIView(context: Context) -> WKWebView {        let config = WKWebViewConfiguration()        // Keeps nothing: no cookies, no cache, nothing written for the next page.        config.websiteDataStore = .nonPersistent()        config.defaultWebpagePreferences.allowsContentJavaScript = false        let view = WKWebView(frame: .zero, configuration: config)        view.navigationDelegate = context.coordinator        view.scrollView.isScrollEnabled = false        view.isOpaque = false        view.backgroundColor = .clear        context.coordinator.apply(pictures: pictures, to: view, file: file)        return view    }    func updateUIView(_ view: WKWebView, context: Context) {        if context.coordinator.pictures != pictures { context.coordinator.apply(pictures: pictures, to: view, file: file) }    }    @MainActor    final class Coordinator: NSObject, WKNavigationDelegate {        var height: Binding<CGFloat>        var pictures: Bool?        init(height: Binding<CGFloat>) { self.height = height }        /// Remote loads blocked by a rule unless pictures are asked for; the page read again either way.        func apply(pictures: Bool, to view: WKWebView, file: URL) {            self.pictures = pictures            let store = WKContentRuleListStore.default()            view.configuration.userContentController.removeAllContentRuleLists()            let load = { view.loadFileURL(file, allowingReadAccessTo: file.deletingLastPathComponent()) }            guard !pictures else { load(); return }            let rules = #"[{"trigger":{"url-filter":"^https?://.*"},"action":{"type":"block"}}]"#            store?.compileContentRuleList(forIdentifier: "post-no-remote", encodedContentRuleList: rules) { list, _ in                Task { @MainActor in                    if let list { view.configuration.userContentController.add(list) }                    load()                }            }        }        func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {            webView.evaluateJavaScript("document.documentElement.scrollHeight") { value, _ in                if let h = value as? CGFloat { Task { @MainActor in self.height.wrappedValue = max(200, h) } }            }        }        func webView(_ webView: WKWebView, decidePolicyFor action: WKNavigationAction) async -> WKNavigationActionPolicy {            // The page itself loads; a tapped link never navigates inside it.            action.navigationType == .linkActivated ? .cancel : .allow        }    }}#endif