Cotton code
294 lines · 13.1 KB · SwiftRaw
// FILES, SEARCH, AN OPEN FILE AND THE READER (mail.html "Files", "Search", "An attachment"):// - Files: every attachment anyone sent him, newest first, filtered by kind; each names who sent it, so it is found by//   memory of the person; a tap fetches it and opens it in Post. `mail.files {kind?, after?}`.// - Search: over every mail on the phone, grouped People, Mail, Files. `mail.search {text}`.// - An open file: Quick Look inside Post; Share and Save are offered, never forced.// - The reader: a link read inside Post, keeping nothing.#if os(iOS)import CottonKitimport QuickLookimport SwiftUIimport UIKitimport WebKitstruct PostFilesScreen: View {    let model: PostModel    @State private var kind = "all"    @State private var files: PostRead<PostFiles>?    @State private var more: [PostFile] = []    @State private var next: String?    @State private var said: [String: String] = [:]    var body: some View {        ScrollView {            LazyVStack(alignment: .leading, spacing: 0) {                PostTitle(text: files?.answer?.title ?? PostWords.line("files.title")).padding(.top, 8)                switch files {                case .read(let answer)?:                    PostChips {                        ForEach(answer.kinds) { k in PostChip(label: k.label, on: k.on, id: "post-files-\(k.id)") { kind = k.id } }                    }                    .padding(.top, 10)                    let rows = answer.rows + more                    if rows.isEmpty, let empty = answer.empty { PostEmpty(line: empty, first: answer.firstSync) }                    ForEach(Array(rows.enumerated()), id: \.element.id) { index, file in                        PostFileRow(model: model, file: file, last: index == rows.count - 1, said: $said)                            .onAppear { if index == rows.count - 1 { Task { await page() } } }                    }                case .refused(let line)?: PostRefused(line: line)                case nil: EmptyView()                }            }            .padding(.horizontal, PostInk.side)            .padding(.bottom, 24)        }        .refreshable { model.changed() }        .background(PostInk.ground)        .task(id: "\(model.generation)/\(kind)") {            files = await model.read("mail.files", ["kind": .string(kind)], as: PostFiles.self)            more = []            next = files?.answer?.after        }        .accessibilityIdentifier("post-files")    }    private func page() async {        guard let cursor = next else { return }        next = nil        if case .read(let page) = await model.read("mail.files", ["kind": .string(kind), "after": .string(cursor)], as: PostFiles.self) {            more += page.rows            next = page.after        }    }}/// One file: its kind, its name, who sent it and when, its size; a tap fetches and opens it, or says why not.struct PostFileRow: View {    let model: PostModel    let file: PostFile    var last = false    /// Where the open file's Back returns to.    var back: String = PostWords.line("files.title")    @Binding var said: [String: String]    var body: some View {        Button { Task { await open() } } label: {            HStack(spacing: 12) {                PostFileMark(name: file.name)                VStack(alignment: .leading, spacing: 2) {                    Text(file.name).font(PostType.sans(15.5, .bold)).foregroundStyle(PostInk.ink).lineLimit(2)                    if let line = said[file.id] ?? file.line {                        Text(line).font(PostType.small).foregroundStyle(PostInk.quiet).fixedSize(horizontal: false, vertical: true)                    }                }                Spacer(minLength: 8)                if let size = file.size { Text(size).font(PostType.end).foregroundStyle(PostInk.quiet) }            }            .padding(.vertical, 10)            .contentShape(Rectangle())            .overlay(alignment: .bottom) { if !last { PostRule() } }        }        .buttonStyle(PostPressStyle())        .accessibilityElement(children: .combine)        .accessibilityIdentifier("post-file-\(file.id)")    }    private func open() async {        said[file.id] = nil        let request: [String: JSONValue] = ["email": .string(file.email), "index": .number(Double(file.index)), "dir": .string(PostFilesDir.path), "online": .bool(model.online)]        switch await model.read("mail.file", request, as: PostOpened.self) {        case .read(let opened): model.sheet = .file(path: opened.path, name: opened.name ?? file.name, back: back)        case .refused(let line): said[file.id] = line        }    }}/// SEARCH: the field with its hint, then People, Mail and Files that hold the words. Searched on this phone.struct PostSearchPage: View {    let model: PostModel    @State private var text = ""    @State private var found: PostRead<PostSearch>?    @State private var said: [String: String] = [:]    @FocusState private var focused: Bool    var body: some View {        VStack(spacing: 0) {            HStack(spacing: 10) {                HStack(spacing: 8) {                    Image(systemName: "magnifyingglass").font(.system(size: 15)).foregroundStyle(PostInk.quiet)                    TextField("", text: $text, prompt: Text(PostWords.line("search.hint")).foregroundStyle(PostInk.quiet))                        .font(PostType.sans(16))                        .foregroundStyle(PostInk.ink)                        .focused($focused)                        .submitLabel(.search)                        .autocorrectionDisabled()                        .textInputAutocapitalization(.never)                        .accessibilityIdentifier("post-search-field")                }                .padding(.horizontal, 14)                .frame(minHeight: 44)                .overlay(RoundedRectangle(cornerRadius: 12, style: .continuous).strokeBorder(PostInk.ink, lineWidth: PostInk.stroke))                PostWordButton(label: PostWords.line("write.cancel"), accent: false, id: "post-search-cancel") { model.sheet = nil }            }            .padding(.horizontal, PostInk.side)            .padding(.top, 8)            ScrollView {                VStack(alignment: .leading, spacing: 0) {                    switch found {                    case .read(let found)?:                        if let people = found.people, !people.rows.isEmpty {                            PostSection(title: people.title)                            ForEach(Array(people.rows.enumerated()), id: \.element.id) { index, row in                                PostRowView(row: row, last: index == people.rows.count - 1) { open(row) }                            }                        }                        if let files = found.files, !files.rows.isEmpty {                            PostSection(title: files.title, end: files.rows.count.formatted())                            ForEach(Array(files.rows.enumerated()), id: \.element.id) { index, file in                                PostFileRow(model: model, file: file, last: index == files.rows.count - 1, back: PostWords.line("search.files"), said: $said)                            }                        }                        if let mail = found.mail, !mail.rows.isEmpty {                            PostSection(title: mail.title, end: mail.rows.count.formatted())                            ForEach(Array(mail.rows.enumerated()), id: \.element.id) { index, row in                                PostRowView(row: row, last: index == mail.rows.count - 1, face: false) { open(row) }                            }                        }                        if let empty = found.empty { PostRefused(line: empty) }                    case .refused(let line)?: PostRefused(line: line)                    case nil: EmptyView()                    }                }                .padding(.horizontal, PostInk.side)                .padding(.bottom, 24)            }            .scrollDismissesKeyboard(.interactively)        }        .background(PostInk.ground)        .onAppear { focused = true }        .task(id: text) {            try? await Task.sleep(for: .milliseconds(text.isEmpty ? 0 : 250))            guard !Task.isCancelled else { return }            found = await model.read("mail.search", ["text": .string(text)], as: PostSearch.self)        }        .accessibilityIdentifier("post-search")    }    private func open(_ row: PostRow) {        guard let thread = row.thread else { return }        model.sheet = nil        model.tab = .mail        model.paths[.mail] = [.thread(thread)]    }}/// AN ATTACHMENT: opened in place, the page itself first (Quick Look); Share and Save hand the untouched file to the/// phone, offered, never forced.struct PostFilePage: View {    let model: PostModel    let path: String    let name: String    let back: String    @State private var saving = false    var body: some View {        VStack(spacing: 0) {            PostBar(back: back, onBack: { model.sheet = nil }) {                ShareLink(item: URL(fileURLWithPath: path)) {                    Image(systemName: "square.and.arrow.up").font(.system(size: 18, weight: .light)).foregroundStyle(PostInk.ink).frame(width: 44, height: 44)                }                .accessibilityLabel(Text(PostWords.line("thread.share")))                .accessibilityIdentifier("post-file-share")            }            .padding(.horizontal, PostInk.side)            PostQuickLook(url: URL(fileURLWithPath: path))                .clipShape(RoundedRectangle(cornerRadius: 10))                .overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(PostInk.rule, lineWidth: 1))                .padding(.horizontal, PostInk.side)            VStack(alignment: .leading, spacing: 10) {                HStack(spacing: 12) {                    PostFileMark(name: name)                    Text(name).font(PostType.sans(15.5, .bold)).foregroundStyle(PostInk.ink).lineLimit(2)                    Spacer()                }                HStack(spacing: 10) {                    ShareLink(item: URL(fileURLWithPath: path)) {                        Text(PostWords.line("thread.share")).font(PostType.sans(15, .semibold)).foregroundStyle(PostInk.ink)                            .frame(maxWidth: .infinity, minHeight: 44)                            .overlay(RoundedRectangle(cornerRadius: 12).strokeBorder(PostInk.rule, lineWidth: PostInk.stroke))                    }                    PostButton(label: PostWords.line("thread.save"), weight: .quiet, id: "post-file-save") { saving = true }                }                Text(PostWords.line("thread.attachment_kept")).font(PostType.small).foregroundStyle(PostInk.quiet)            }            .padding(.horizontal, PostInk.side)            .padding(.vertical, 12)        }        .background(PostInk.ground)        .sheet(isPresented: $saving) { PostSaveCopy(url: URL(fileURLWithPath: path)).ignoresSafeArea() }        .accessibilityIdentifier("post-file-page")    }}/// Save: a copy of the file put where he chooses in Files; the one in Post stays.struct PostSaveCopy: UIViewControllerRepresentable {    let url: URL    func makeUIViewController(context: Context) -> UIDocumentPickerViewController {        UIDocumentPickerViewController(forExporting: [url], asCopy: true)    }    func updateUIViewController(_ controller: UIDocumentPickerViewController, context: Context) {}}struct PostQuickLook: UIViewControllerRepresentable {    let url: URL    func makeCoordinator() -> Source { Source(url: url) }    func makeUIViewController(context: Context) -> QLPreviewController {        let controller = QLPreviewController()        controller.dataSource = context.coordinator        return controller    }    func updateUIViewController(_ controller: QLPreviewController, context: Context) {}    final class Source: NSObject, QLPreviewControllerDataSource {        let url: URL        init(url: URL) { self.url = url }        func numberOfPreviewItems(in controller: QLPreviewController) -> Int { 1 }        func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem { url as NSURL }    }}/// THE READER: a link from a mail read inside Post. It keeps nothing: no cookies, no history, nothing for the next page.struct PostReaderPage: View {    let model: PostModel    let url: URL    let back: String    var body: some View {        VStack(spacing: 0) {            PostBar(back: back, onBack: { model.sheet = nil }) {                Text(url.host ?? "").font(PostType.small).foregroundStyle(PostInk.quiet).lineLimit(1)            }            .padding(.horizontal, PostInk.side)            PostReaderView(url: url)        }        .background(PostInk.ground)        .accessibilityIdentifier("post-reader")    }}struct PostReaderView: UIViewRepresentable {    let url: URL    func makeUIView(context: Context) -> WKWebView {        let config = WKWebViewConfiguration()        config.websiteDataStore = .nonPersistent()        let view = WKWebView(frame: .zero, configuration: config)        view.load(URLRequest(url: url))        return view    }    func updateUIView(_ view: WKWebView, context: Context) {}}#endif