Cotton code
428 lines · 18.5 KB · SwiftRaw
// A FILE A NOTE CARRIES, READ ONLY (the owner, 22 Nov 2026, WORDS-DRAWER.md;// CONTRACT.md section 15, which Android built first and this follows). The// core answers a note's files with the note (`notes.open`'s `files`: name,// what it is, how it opens, its media key, `here`); they stand as rows under// the note's top bar (NoteWriter), and a tap opens one here, over everything:// Back, the file's name and Share above it, then// - `page`: the page's words in a web view with its scripts off, no network//   (a content rule list blocking every load the page asks for), nothing//   kept, no window, no script message handler and no file access: handed in//   as words at a host that is no host (`https://file.words.invalid/`), never//   as a path. The pane never leaves it; a `#jump` stays in it; a link the//   person taps asks "Open this link in your browser?" first;// - `note`: Markdown or plain text drawn as a note is drawn, by Words' own//   editor and the core's styling, read only: it selects and copies, nothing//   types, a tick does nothing;// - `pdf`: its pages by PDFKit at the reader's width, pinch to enlarge;// - `picture`: whole, pinch to enlarge, double tap back.#if os(iOS)import CottonValuesimport CottonWritingimport PDFKitimport SwiftUIimport UIKitimport WebKitstruct NotesFileViewer: View {    let book: NotesBook    let file: NoteFile    let look: WritingLook    let words: WritingWords    let close: () -> Void    @State private var path: URL?    @State private var text: String?    @State private var missing: String?    @State private var leaving: URL?    private var theme: WritingTheme { look.theme }    private func ui(_ colour: UIColor) -> Color { Color(uiColor: colour) }    var body: some View {        VStack(spacing: 0) {            HStack(spacing: 0) {                NotesRoundButton(icon: "back", name: NotesNav.back, id: "file-viewer-back", look: look, plain: true) { close() }                Text(verbatim: file.name)                    .font(Font(WritingFonts.font(look.type.face, size: 17, weight: .bold)))                    .foregroundStyle(ui(theme.heading))                    .lineLimit(1)                    .truncationMode(.tail)                    .frame(maxWidth: .infinity)                    .accessibilityAddTraits(.isHeader)                    .accessibilityIdentifier("file-viewer-title")                NotesRoundButton(icon: "share", name: notesLine("files.share"), id: "file-viewer-share", look: look, plain: true) { share() }                    .opacity(path == nil ? 0 : 1)                    .disabled(path == nil)            }            .padding(.horizontal, 6).padding(.vertical, 4)            ZStack {                if let missing {                    Text(verbatim: missing)                        .font(Font(look.font([]).withSize(16)))                        .foregroundStyle(ui(theme.dim))                        .multilineTextAlignment(.center)                        .padding(.horizontal, 36).padding(.vertical, 80)                        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)                        .accessibilityIdentifier("file-viewer-refused")                } else if let path {                    switch file.opens {                    case "page":                        if let text { NotesSealedPage(html: text) { leaving = $0 }.accessibilityIdentifier("file-viewer-page") }                    case "note":                        if let text { NotesReadOnlyNote(book: book, text: text, look: look, words: words) { leaving = $0 } }                    case "pdf":                        NotesPDFPage(file: path).accessibilityIdentifier("file-viewer-pdf")                    case "picture":                        NotesZoomPicture(file: path).accessibilityIdentifier("file-viewer-picture")                    default:                        EmptyView()                    }                }            }            .frame(maxWidth: .infinity, maxHeight: .infinity)            .clipped()        }        .frame(maxWidth: .infinity, maxHeight: .infinity)        .background(ui(theme.ground).ignoresSafeArea())        .overlay {            if let url = leaving {                NotesActSheet(acts: [NotesAct(id: "go", label: notesLine("files.link_go"), icon: "link")], look: look,                              title: notesLine("files.link_out"), message: url.absoluteString, onAct: { _ in                    leaving = nil                    UIApplication.shared.open(url)                }) { leaving = nil }            }        }        .accessibilityElement(children: .contain)        .accessibilityIdentifier("notes-file-viewer")        .accessibilityAction(.escape) { close() }        .task { await load() }    }    /// The most of a page's or a note's file read into memory to draw its words (8 MB).    static let wordsReadMost = 8 * 1024 * 1024    /// The file's bytes on this phone (`media.ensure`); a page's or a note's words read from them.    private func load() async {        if let refused = file.refused {            missing = refused            return        }        guard let key = file.key, let found = await book.picturePath(key: key) else {            missing = notesLine("files.offline")            return        }        if file.opens == "page" || file.opens == "note" {            // A page or a note is drawn from its words in memory, so only one of a bounded size is read: a bigger one            // is said unreadable here, and Share still hands it on whole.            let size = (try? FileManager.default.attributesOfItem(atPath: found.path)[.size] as? NSNumber)?.intValue ?? 0            guard size <= Self.wordsReadMost, let data = try? Data(contentsOf: found) else {                missing = notesLine("files.unreadable")                return            }            text = String(decoding: data, as: UTF8.self)        }        path = found    }    /// The file under its own name, to the share sheet.    private func share() {        guard let path else { return }        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("words-share-\(file.id)", isDirectory: true)        try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)        var name = file.name.replacingOccurrences(of: "/", with: "-")        if (name as NSString).pathExtension.isEmpty, !path.pathExtension.isEmpty { name += "." + path.pathExtension }        let named = folder.appendingPathComponent(name)        try? FileManager.default.removeItem(at: named)        let handed = (try? FileManager.default.copyItem(at: path, to: named)) == nil ? path : named        ShareSheet.present(handed)    }}// MARK: - A web page, sealed/// The seal a file's web page is read under: all of it here, and `NotesFileSealTests` holds it.enum NotesFileSeal {    static let ruleListIdentifier = "cotton.words.file.seal.v2"    /// The host that is no host the page's words are handed in at (`.invalid` never resolves).    static let base = URL(string: "https://file.words.invalid/")!    /// Every load the page asks for is blocked: a picture, a script, a style, a font, a frame's own loads, a    /// fetch, a socket, anything else. Only the page's own words, handed in by the app, are drawn.    static var ruleList: String {        let rules: [[String: Any]] = [            ["trigger": ["url-filter": ".*", "resource-type": ["image", "style-sheet", "script", "font", "raw", "svg-document", "media", "popup",                                                             "ping", "fetch", "websocket", "other"]],             "action": ["type": "block"]],        ]        let data = (try? JSONSerialization.data(withJSONObject: rules, options: [.sortedKeys])) ?? Data("[]".utf8)        return String(decoding: data, as: UTF8.self)    }    /// The web view's configuration: the page's scripts off, nothing kept, no handler a script could post to,    /// no window it could open, no media that plays by itself, no detectors that turn words into actions.    @MainActor static func configuration(rules: WKContentRuleList?) -> WKWebViewConfiguration {        let configuration = WKWebViewConfiguration()        configuration.websiteDataStore = .nonPersistent()        configuration.defaultWebpagePreferences.allowsContentJavaScript = false        configuration.preferences.javaScriptCanOpenWindowsAutomatically = false        configuration.preferences.isElementFullscreenEnabled = false        configuration.dataDetectorTypes = []        configuration.allowsInlineMediaPlayback = false        configuration.mediaTypesRequiringUserActionForPlayback = .all        configuration.allowsAirPlayForMediaPlayback = false        configuration.allowsPictureInPictureMediaPlayback = false        configuration.userContentController = WKUserContentController()        if let rules { configuration.userContentController.add(rules) }        return configuration    }    /// Whether the pane may stand at `url`: the page itself (at the host that is no host) or a `#jump` in it.    static func stays(_ url: URL?) -> Bool {        guard let url, url.scheme == base.scheme, url.host == base.host else { return url?.absoluteString == "about:blank" }        return url.path.isEmpty || url.path == "/"    }    /// The compiled list, made once per launch; nil if it will not compile (then the page never loads).    @MainActor private static var compiled: WKContentRuleList?    @MainActor static func rules() async -> WKContentRuleList? {        if let compiled { return compiled }        guard let store = WKContentRuleListStore.default() else { return nil }        let source = ruleList        let list: WKContentRuleList? = await withCheckedContinuation { done in            store.compileContentRuleList(forIdentifier: ruleListIdentifier, encodedContentRuleList: source) { list, _ in                done.resume(returning: list)            }        }        compiled = list        return list    }}/// The page, once its seal is in place; nothing at all until then.struct NotesSealedPage: View {    let html: String    /// A link the person tapped: asked before it leaves for the browser.    let leave: (URL) -> Void    @State private var rules: WKContentRuleList?    var body: some View {        ZStack {            if let rules { NotesSealedWebView(html: html, rules: rules, leave: leave) }        }        .task { rules = await NotesFileSeal.rules() }    }}struct NotesSealedWebView: UIViewRepresentable {    let html: String    let rules: WKContentRuleList    let leave: (URL) -> Void    func makeCoordinator() -> Coordinator { Coordinator(leave: leave) }    func makeUIView(context: Context) -> WKWebView {        let view = WKWebView(frame: .zero, configuration: NotesFileSeal.configuration(rules: rules))        view.navigationDelegate = context.coordinator        view.uiDelegate = context.coordinator        view.isOpaque = false        view.backgroundColor = .clear        view.scrollView.backgroundColor = .clear        // Its words, never a path: no file is readable from the page.        view.loadHTMLString(html, baseURL: NotesFileSeal.base)        return view    }    func updateUIView(_ view: WKWebView, context: Context) {}    final class Coordinator: NSObject, WKNavigationDelegate, WKUIDelegate {        let leave: (URL) -> Void        init(leave: @escaping (URL) -> Void) { self.leave = leave }        /// The pane stays on its page, and a frame inside it goes nowhere. A link the person taps is asked first.        func webView(_ view: WKWebView, decidePolicyFor action: WKNavigationAction,                     decisionHandler: @escaping @MainActor (WKNavigationActionPolicy) -> Void) {            let url = action.request.url            let main = action.targetFrame?.isMainFrame ?? true            if main, NotesFileSeal.stays(url) {                decisionHandler(.allow)                return            }            decisionHandler(.cancel)            if main, action.navigationType == .linkActivated, let link = TableDefinition.webLink(url) { leave(link) }        }        /// No second window, ever.        func webView(_ view: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for action: WKNavigationAction,                     windowFeatures: WKWindowFeatures) -> WKWebView? { nil }    }}// MARK: - A PDF, a picturestruct NotesPDFPage: UIViewRepresentable {    let file: URL    func makeUIView(context: Context) -> PDFView {        let view = PDFView()        view.autoScales = true        view.displayMode = .singlePageContinuous        view.displayDirection = .vertical        view.backgroundColor = .clear        view.document = PDFDocument(url: file)        return view    }    func updateUIView(_ view: PDFView, context: Context) {}}/// A picture whole; pinch to enlarge, double tap back.struct NotesZoomPicture: View {    let file: URL    @State private var image: UIImage?    @State private var scale: CGFloat = 1    var body: some View {        ZStack {            if let image {                Image(uiImage: image)                    .resizable()                    .scaledToFit()                    .scaleEffect(scale)                    .gesture(MagnifyGesture().onChanged { scale = max(1, min(5, $0.magnification)) }.onEnded { _ in                        withAnimation(.spring) { if scale < 1.1 { scale = 1 } }                    })                    .onTapGesture(count: 2) { withAnimation(.spring) { scale = scale > 1 ? 1 : 2.5 } }                    // VoiceOver: the double tap back, by name (files.whole), as Android's TalkBack has it.                    .accessibilityAction(named: Text(verbatim: notesLine("files.whole"))) { scale = 1 }            }        }        .task { image = await NotesPictures.image(at: file, width: 1600) }    }}// MARK: - Markdown or plain text, drawn as a note/// The file's words drawn by Words' own editor and the core's styling, which cannot change them: it selects/// and copies; no keyboard, no ticks, no keys. A web link in it is asked before it opens.struct NotesReadOnlyNote: View {    let book: NotesBook    let text: String    let look: WritingLook    let words: WritingWords    let leave: (URL) -> Void    @State private var editor: WritingEditor?    var body: some View {        ZStack {            if let editor {                WritingEditorView(editor: editor)                    .ignoresSafeArea(.container, edges: .bottom)                    .accessibilityIdentifier("file-viewer-note")            }        }        .onAppear {            guard editor == nil else { return }            let made = WritingEditor(rules: NotesReadingRules(base: book.rules(hideMarks: true)), media: nil, words: words, look: look)            made.load(text)            made.textView.isEditable = false            made.textView.inputAccessoryView = nil            made.tapOpens = { TableDefinition.webLink(URL(string: $0)) != nil }            made.onOpenLink = { url in if let link = TableDefinition.webLink(URL(string: url)) { leave(link) } }            editor = made        }    }}/// The note's styling, read only: every key and tick refused, so nothing a finger does changes the words.struct NotesReadingRules: WritingRules {    let base: any WritingRules    struct ReadOnly: Error {}    func style(_ text: String, cursor: Int?) async throws -> WritingStyled { try await base.style(text, cursor: nil) }    func press(_ ask: WritingAsk) async throws -> WritingChange { throw ReadOnly() }    func tags(_ prefix: String) async throws -> [WritingTagOffer] { [] }    func written(_ tag: String) -> String { base.written(tag) }}// MARK: - The rows under the note's top bar/// The note's files as rows under its top bar: each its mark, its name (one line) and what it is, quiet under/// it. At most three; with more, the third says how many more and opens a sheet of them all.struct NotesFileRows: View {    let files: [NoteFile]    let look: WritingLook    let open: (NoteFile) -> Void    let all: () -> Void    private var shown: [NoteFile] { files.count > 3 ? Array(files.prefix(2)) : files }    var body: some View {        VStack(spacing: 6) {            ForEach(Array(shown.enumerated()), id: \.element.id) { at, file in                NotesFileRow(icon: Self.icon(file), name: file.name, about: file.about, label: file.label ?? file.name, look: look,                             id: "note-file-\(at)") { open(file) }            }            if files.count > 3 {                let more = notesLine("files.more").replacingOccurrences(of: "{n}", with: (files.count - 2).formatted())                NotesFileRow(icon: "more", name: more, about: nil, label: more, look: look, id: "note-files-more") { all() }            }        }        .padding(.horizontal, 14)        .padding(.vertical, 6)        .accessibilityElement(children: .contain)        .accessibilityLabel(Text(verbatim: notesLine("files.title")))    }    /// The mark a file wears, from how it opens.    static func icon(_ file: NoteFile) -> String {        switch file.opens {        case "picture": "picture"        case "note": "notes"        default: "file"        }    }}private struct NotesFileRow: View {    let icon: String    let name: String    let about: String?    let label: String    let look: WritingLook    let id: String    let tap: () -> Void    var body: some View {        let theme = look.theme        Button(action: tap) {            HStack(spacing: 12) {                WritingMark(icon, colour: Color(uiColor: theme.dim), size: 20)                VStack(alignment: .leading, spacing: 1) {                    Text(verbatim: name)                        .font(Font(look.font([]).withSize(15)))                        .foregroundStyle(Color(uiColor: theme.ink))                        .lineLimit(1)                        .truncationMode(.middle)                    if let about {                        Text(verbatim: about)                            .font(Font(look.font([]).withSize(12)))                            .foregroundStyle(Color(uiColor: theme.dim))                            .lineLimit(1)                    }                }                Spacer(minLength: 0)            }            .padding(.horizontal, 12).padding(.vertical, 8)            .frame(maxWidth: .infinity, minHeight: 44, alignment: .leading)            .background(RoundedRectangle(cornerRadius: 12).fill(Color(uiColor: theme.sheet)))            .contentShape(Rectangle())        }        .buttonStyle(.plain)        .accessibilityLabel(Text(verbatim: about.map { label + ", " + $0 } ?? label))        .accessibilityIdentifier(id)    }}#endif