// 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)importCottonValuesimportCottonWritingimport PDFKitimportSwiftUIimport UIKitimportWebKitstructNotesFileViewer: View {let book: NotesBooklet file: NoteFilelet look: WritingLooklet words: WritingWordslet close: () -> Void @State privatevar path: URL? @State privatevar text: String? @State privatevar missing: String? @State privatevar leaving: URL?privatevar theme: WritingTheme { look.theme }privatefunc ui(_ colour: UIColor) -> Color { Color(uiColor: colour) }var body: someView { 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 {iflet 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") } elseiflet path {switch file.opens {case"page":iflet text { NotesSealedPage(html: text) { leaving = $0 }.accessibilityIdentifier("file-viewer-page") }case"note":iflet 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 {iflet 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).staticlet wordsReadMost = 8 * 1024 * 1024/// The file's bytes on this phone (`media.ensure`); a page's or a note's words read from them.privatefunc load() async {iflet refused = file.refused { missing = refusedreturn }guardlet 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 ?? 0guard 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.privatefunc share() {guardlet 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 : namedShareSheet.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.enumNotesFileSeal {staticlet ruleListIdentifier = "cotton.words.file.seal.v2"/// The host that is no host the page's words are handed in at (`.invalid` never resolves).staticlet 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.staticvar 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)returnString(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 staticfunc 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()iflet 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.staticfunc stays(_ url: URL?) -> Bool {guardlet 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 privatestaticvar compiled: WKContentRuleList? @MainActor staticfunc rules() async -> WKContentRuleList? {iflet compiled { return compiled }guardlet store = WKContentRuleListStore.default() else { returnnil }let source = ruleListlet list: WKContentRuleList? = await withCheckedContinuation { done in store.compileContentRuleList(forIdentifier: ruleListIdentifier, encodedContentRuleList: source) { list, _ in done.resume(returning: list) } } compiled = listreturn list }}/// The page, once its seal is in place; nothing at all until then.structNotesSealedPage: View {let html: String/// A link the person tapped: asked before it leaves for the browser.let leave: (URL) -> Void @State privatevar rules: WKContentRuleList?var body: someView { ZStack {iflet rules { NotesSealedWebView(html: html, rules: rules, leave: leave) } } .task { rules = awaitNotesFileSeal.rules() } }}structNotesSealedWebView: UIViewRepresentable {let html: Stringlet rules: WKContentRuleListlet leave: (URL) -> Voidfunc 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) {}finalclassCoordinator: NSObject, WKNavigationDelegate, WKUIDelegate {let leave: (URL) -> Voidinit(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.urllet main = action.targetFrame?.isMainFrame ?? trueif 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 picturestructNotesPDFPage: UIViewRepresentable {let file: URLfunc 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.structNotesZoomPicture: View {let file: URL @State privatevar image: UIImage? @State privatevar scale: CGFloat = 1var body: someView { ZStack {iflet 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 = awaitNotesPictures.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.structNotesReadOnlyNote: View {let book: NotesBooklet text: Stringlet look: WritingLooklet words: WritingWordslet leave: (URL) -> Void @State privatevar editor: WritingEditor?var body: someView { ZStack {iflet editor {WritingEditorView(editor: editor) .ignoresSafeArea(.container, edges: .bottom) .accessibilityIdentifier("file-viewer-note") } } .onAppear {guard editor == nilelse { 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 iniflet 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.structNotesReadingRules: WritingRules {let base: any WritingRulesstructReadOnly: Error {}func style(_ text: String, cursor: Int?) asyncthrows -> WritingStyled { tryawait base.style(text, cursor: nil) }func press(_ ask: WritingAsk) asyncthrows -> WritingChange { throwReadOnly() }func tags(_ prefix: String) asyncthrows -> [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.structNotesFileRows: View {let files: [NoteFile]let look: WritingLookletopen: (NoteFile) -> Voidlet all: () -> Voidprivatevar shown: [NoteFile] { files.count > 3 ? Array(files.prefix(2)) : files }var body: someView { VStack(spacing: 6) {ForEach(Array(shown.enumerated()), id: \.element.id) { at, file inNotesFileRow(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.staticfunc icon(_ file: NoteFile) -> String {switch file.opens {case"picture": "picture"case"note": "notes"default: "file" } }}privatestructNotesFileRow: View {let icon: Stringlet name: Stringlet about: String?let label: Stringlet look: WritingLooklet id: Stringlet tap: () -> Voidvar body: someView {let theme = look.themeButton(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)iflet 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