Cotton code
577 lines · 24.6 KB · SwiftRaw
// THE NOTE (DECISIONS.md "The note"), as Android's `NoteScreen.kt`: the note's// text at once (the keyboard up for a new note), Back at the top left, Info and// More at the top right; links open from the bar's Open, `[[note links]]` offer// notes as they are typed and open them, headings and lists fold, pictures// stand at a few widths (hold one), Find stands in the top bar. The surface is// CottonWriting's; this screen opens, saves, tags and moves the note through// `notes.*`, every sheet in Notes' own look.#if os(iOS)import CottonKitimport CottonValuesimport CottonWritingimport PhotosUIimport SwiftUIimport UIKitimport UniformTypeIdentifiersstruct NoteWriter: View {    let model: NotesModel    let themes: NotesThemes    let chosen: NotesSettingsChosen    let id: String    let fresh: Bool    /// Where the caret stands on opening (a linked heading); nil: the note's own place.    var at: Int? = nil    @Environment(\.dismiss) private var dismiss    @Environment(\.colorScheme) private var scheme    @Environment(\.openURL) private var openURL    @State private var page: NoteWriterPage?    @State private var doc: NoteText?    @State private var choosingPicture = false    @State private var library = false    @State private var camera = false    @State private var picked: [PhotosPickerItem] = []    @State private var viewing: URL?    /// The files the note carries (`notes.open`'s `files`), as rows under the top bar.    @State private var files: [NoteFile] = []    /// A file open read-only (NotesFileViewer.swift); one Words cannot show, asked before another app opens it.    @State private var reading: NoteFile?    @State private var elsewhere: NoteFile?    @State private var allFiles = false    @State private var tagging = false    @State private var more = false    @State private var info = false    @State private var asking: NotesAsked?    @State private var sizing: String?    @State private var making: NotesLinked?    @State private var exporting = false    @State private var finding: String?    @State private var foundCount = 0    @State private var foundAt = 0    @State private var pinned = false    @State private var said: String?    @FocusState private var findFocused: Bool    private var book: NotesBook { model.book }    private var look: WritingLook { chosen.look(dark: scheme == .dark) }    private var theme: WritingTheme { look.theme }    private func ui(_ colour: UIColor) -> Color { Color(uiColor: colour) }    var body: some View {        ZStack {            ui(theme.ground).ignoresSafeArea()            VStack(spacing: 0) {                if finding != nil { findBar } else { bar }                if !files.isEmpty, finding == nil {                    NotesFileRows(files: files, look: look, open: { openFile($0) }, all: { allFiles = true })                }                if let page {                    WritingEditorView(editor: page.editor)                        .ignoresSafeArea(.container, edges: .bottom)                        .accessibilityIdentifier("note-writer")                }            }            overlays            NotesSaidLine(said: $said, look: look)        }        .task {            guard page == nil else { return }            do {                let opened = try await book.open(id)                pinned = opened.pinnedInNotes                let made = NoteWriterPage(book: book, opened: opened, look: look, words: NotesBooks.words(themes, hint: opened.hint))                made.editor.onError = { refuse($0) }                made.editor.onPicture = { choosingPicture = true }                if UIImagePickerController.isSourceTypeAvailable(.camera) { made.editor.onCamera = { camera = true } }                // A tag tapped in the note: the list of the notes that carry it (FEEDBACK-4 C1).                made.editor.onOpenTag = { tag in                    page?.close()                    model.show(NotesListAsk(view: "tag", tag: tag))                    dismiss()                }                made.editor.onPutAway = { KeyboardDismissal.resign() }                made.editor.onOpenPicture = { src in                    Task {                        guard let key = made.media.picture(src)?.key else { return }                        viewing = await book.picturePath(key: key)                    }                }                made.editor.onLinkOffers = { text, cursor in try? await book.links(opened.id, text: text, cursor: cursor) }                made.editor.onFind = { text, words in (try? await book.find(text, words)) ?? [] }                made.editor.onOpenLink = { open($0) }                made.editor.onPictureHold = { sizing = $0 }                made.editor.onFound = {                    foundCount = made.editor.found.count                    foundAt = made.editor.foundAt                }                page = made                doc = opened                files = opened.files                if let at { made.editor.show(at) } else if fresh { made.editor.beginWriting() }                #if COTTON_DEV                switch NotesLookSeed.asked {                case "info": info = true                case "more": more = true                case "find":                    finding = "the"                    made.editor.find("the")                case "bar": made.editor.beginWriting()                case "format":                    made.editor.beginWriting()                    made.editor.showFormatting(true)                case "tags", "many": tagging = true                default: break                }                #endif            } catch { refuse(error) }        }        // The app's one keyboard rule (Chrome/KeyboardDismissal.swift), as the list wears it: the note is        // a cover of its own, so the list's rule never reached it, and a tap on the tag picker's title left        // its keyboard up (NotesKeyboardTests). A tap or drag in the note's own words keeps the keyboard.        .cottonScreenFrame()        .onChange(of: scheme) { page?.editor.apply(look) }        .onChange(of: NotesStanding.shared.hideMarks) { page?.editor.apply(look) }        .onDisappear { page?.close() }        .photosPicker(isPresented: $library, selection: $picked, maxSelectionCount: 10, matching: .images)        .onChange(of: picked) {            let items = picked            guard !items.isEmpty else { return }            picked = []            Task {                var pictures: [Data] = []                for item in items {                    if let data = try? await item.loadTransferable(type: Data.self) { pictures.append(data) }                }                page?.editor.place(pictures, type: .jpeg)            }        }        .fullScreenCover(isPresented: $camera) {            NotesCamera { image in                if let image { page?.editor.place([image]) }                camera = false            }            .ignoresSafeArea()        }        .fullScreenCover(item: Binding(get: { viewing.map { NotesPictureViewer.Shown(url: $0) } }, set: { viewing = $0?.url })) { shown in            NotesPictureViewer(url: shown.url, close: notesLine("writer.done"))        }        .fullScreenCover(item: $reading) { file in            NotesFileViewer(book: book, file: file, look: look, words: NotesBooks.words(themes, hint: nil)) { reading = nil }        }    }    /// The sheets that stand over the note, each in Notes' own look.    @ViewBuilder private var overlays: some View {        if let file = elsewhere {            NotesActSheet(acts: [NotesAct(id: "open_with", label: notesLine("files.open_with"), icon: "share")], look: look,                          title: file.name, message: notesLine("files.elsewhere"), onAct: { _ in                elsewhere = nil                openElsewhere(file)            }) { elsewhere = nil }        }        if allFiles {            NotesActSheet(acts: files.map { NotesAct(id: $0.id, label: $0.name, icon: NotesFileRows.icon($0)) }, look: look,                          title: notesLine("files.title"), onAct: { act in                allFiles = false                if let file = files.first(where: { $0.id == act.id }) { openFile(file) }            }) { allFiles = false }        }        if more, let doc {            NotesActSheet(acts: noteActs(doc), look: look, onAct: { act in                more = false                Task { await run(act) }            }) { more = false }        }        if tagging {            NotesTagPicker(model: model, look: look, id: id) {                tagging = false                Task { await tagsChanged() }            }        }        if info, let page {            NoteInfo(model: model, look: look, id: id, close: { info = false }, jump: { at in                info = false                page.editor.show(at)            }, open: { other in                info = false                switchTo(other)            })        }        if choosingPicture {            NotesActSheet(acts: pictureActs, look: look, onAct: { act in                choosingPicture = false                if act.id == "camera" { camera = true } else { library = true }            }) { choosingPicture = false }        }        if let src = sizing {            // Small, Medium or Full: written into the note by the core's `picture_width` button (CONTRACT.md §8).            NotesActSheet(acts: ["small", "medium", "full"].map { NotesAct(id: $0, label: notesLine("picture.width.\($0)"), icon: "picture") },                          look: look, title: notesLine("picture.width.title"), onAct: { act in                sizing = nil                page?.editor.setPictureWidth(src, act.id)            }) { sizing = nil }        }        if let missing = making, let target = missing.title {            NotesActSheet(acts: [NotesAct(id: "make", label: missing.offer ?? "", icon: "compose")], look: look,                          title: notesLine("link.missing"), onAct: { _ in                making = nil                Task { await make(target) }            }) { making = nil }        }        if exporting {            NotesExportSheet(look: look) { format in                exporting = false                Task {                    try? await page?.save()                    await model.export(ids: [id], format)                }            } close: { exporting = false }        }        if let ask = asking {            NotesActSheet(acts: [NotesAct(id: "yes", label: ask.yes, icon: "delete_forever", red: true)], look: look, title: ask.title,                          message: ask.message, onAct: { _ in asking = nil; ask.run() }) { asking = nil }        }    }    private var bar: some View {        HStack(spacing: 2) {            NotesRoundButton(icon: "back", name: NotesNav.back, id: "note-back", look: look, plain: true) {                page?.close()                dismiss()            }            Spacer()            if pinned {                WritingMark("pinned", colour: ui(theme.accent), size: 16).padding(.trailing, 8).accessibilityIdentifier("note-pinned")            }            NotesRoundButton(icon: "info", name: notesLine("info.title"), id: "note-info", look: look, plain: true) {                Task { try? await page?.save() }                info = true            }            NotesRoundButton(icon: "more", name: NotesNav.more, id: "note-more", look: look, plain: true) { more = true }        }        .padding(.horizontal, 8)        .padding(.vertical, 4)    }    /// Find inside the note, in the top bar's place: the words looked for, how many are found, the one before    /// and after, Done.    private var findBar: some View {        HStack(spacing: 2) {            HStack(spacing: 8) {                WritingMark("find", colour: ui(theme.dim), size: 18)                TextField(text: Binding(get: { finding ?? "" }, set: { finding = $0; page?.editor.find($0) })) {                    Text(verbatim: notesLine("find.hint")).foregroundStyle(ui(theme.faint))                }                .font(Font(look.font([]).withSize(16)))                .foregroundStyle(ui(theme.ink))                .tint(ui(theme.accent))                .autocorrectionDisabled()                .textInputAutocapitalization(.never)                .focused($findFocused)                .submitLabel(.search)                .onSubmit { page?.editor.findNext(1) }                .accessibilityIdentifier("find-field")                if let finding, !finding.isEmpty {                    Text(verbatim: foundCount == 0 ? notesLine("find.none") : notesLine("find.count", ["n": String(foundAt + 1), "of": String(foundCount)]))                        .font(Font(look.font([]).withSize(14)))                        .foregroundStyle(ui(theme.dim))                        .accessibilityIdentifier("find-count")                }            }            .padding(.horizontal, 12).padding(.vertical, 9)            .background(RoundedRectangle(cornerRadius: 11).fill(ui(theme.sheet)))            NotesRoundButton(icon: "up", name: notesLine("find.before"), id: "find-before", look: look, plain: true) { page?.editor.findNext(-1) }            NotesRoundButton(icon: "down", name: notesLine("find.after"), id: "find-after", look: look, plain: true) { page?.editor.findNext(1) }            Button {                finding = nil                page?.editor.find(nil)            } label: {                Text(verbatim: notesLine("writer.done"))                    .font(Font(WritingFonts.font(look.type.face, size: 16, weight: .semibold)))                    .foregroundStyle(ui(theme.accent))                    .padding(.horizontal, 8).padding(.vertical, 8)            }            .buttonStyle(.plain)            .accessibilityIdentifier("find-done")        }        .padding(.horizontal, 10)        .padding(.vertical, 6)        .accessibilityElement(children: .contain)        .accessibilityIdentifier("find-bar")    }    private var pictureActs: [NotesAct] {        var acts = [NotesAct(id: "library", label: notesLine("picture.library"), icon: "picture")]        if UIImagePickerController.isSourceTypeAvailable(.camera) {            acts.append(NotesAct(id: "camera", label: notesLine("picture.camera"), icon: "camera"))        }        return acts    }    /// A note's acts, as it stands: Pin, Tags, Find, Archive (or back), Share, Export, Bin; in the bin,    /// Restore and Delete for good.    private func noteActs(_ doc: NoteText) -> [NotesAct] {        if doc.binned == true { return [.of("restore", "restore"), .of("remove", "delete_forever", red: true)] }        return [pinned ? .of("unpin", "unpin") : .of("pin", "pin"), .of("tags", "tag"), .of("find", "find"),                doc.archived == true ? .of("unarchive", "restore") : .of("archive", "archive"), .of("share", "share"), .of("export", "export"),                .of("bin", "bin", red: true)]    }    private func run(_ act: NotesAct) async {        try? await page?.save()        switch act.id {        case "pin", "unpin":            do {                let answer = try await book.pin(id, act.id == "pin")                pinned = act.id == "pin"                if let words = answer.said { said = words }            } catch { refuse(error) }        case "tags": tagging = true        case "find":            finding = ""            page?.editor.find("")            findFocused = true        case "share": if let page { ShareSheet.present(words: page.editor.text) }        case "export": exporting = true        case "remove":            asking = await model.askRemove(id) {                page?.closed = true                dismiss()            }        default: move(act.id)        }    }    /// Archive, the Bin, back from either, or gone for good: the note's screen closes and the list says what happened.    private func move(_ act: String) {        Task {            do {                try await page?.save()                let answer = try await book.move(id, act)                if let words = answer.said { model.tell(words) }                page?.closed = true                dismiss()            } catch { refuse(error) }        }    }    /// The words the picker changed are the note's now: open them again, as one change Undo takes back.    private func tagsChanged() async {        do {            try await page?.save()            let again = try await book.open(id)            doc = again            page?.took(again)        } catch { refuse(error) }    }    /// A link opened: an address in the phone's browser; a `[[note]]` in Notes, or an offer to make it.    private func open(_ url: String) {        if url.hasPrefix("note:") {            let target = String(url.dropFirst(5))            Task {                try? await page?.save()                do {                    let linked = try await book.link(target)                    if let other = linked.id { switchTo(other, at: linked.headingAt) } else if linked.missing == true { making = linked }                } catch { refuse(error) }            }        } else {            let address = url.contains("://") || url.hasPrefix("mailto:") ? url : "https://" + url            if let link = URL(string: address) { openURL(link) }        }    }    /// A note made by the core for a `[[link]]` that named none yet, then opened.    private func make(_ target: String) async {        do {            if let made = try await book.link(target, make: true).id { switchTo(made, fresh: true) }        } catch { refuse(error) }    }    /// Another note opened in this one's place, at `at` (a linked heading) when said.    private func switchTo(_ other: String, at: Int? = nil, fresh: Bool = false) {        page?.close()        model.opened = NotesOpened(id: other, fresh: fresh, at: at)    }    private func refuse(_ error: Error) {        said = ActionRefused.words(for: error)    }    /// A file the note carries, tapped (CONTRACT.md section 15): one this copy does not hold is fetched first    /// (`notes.file`); a refusal is said; one Words cannot show is asked before another app opens it; any    /// other opens read-only.    private func openFile(_ tapped: NoteFile) {        Task {            var file = tapped            if !file.here {                do {                    file = try await book.file(note: id, id: file.id)                    if let at = files.firstIndex(where: { $0.id == file.id }) { files[at] = file }                } catch {                    refuse(error)                    return                }            }            if let refused = file.refused {                said = refused            } else if file.opens == "elsewhere" {                elsewhere = file            } else if file.opens == nil || file.key == nil {                said = notesLine("files.no_file")            } else {                reading = file            }        }    }    /// A file Words cannot show, handed to another app under its own name (the system's Open with).    private func openElsewhere(_ file: NoteFile) {        Task {            guard let key = file.key, let path = await book.picturePath(key: key) else {                said = notesLine("files.offline")                return            }            let folder = FileManager.default.temporaryDirectory.appendingPathComponent("words-share-\(file.id)", isDirectory: true)            try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)            let named = folder.appendingPathComponent(file.name.replacingOccurrences(of: "/", with: "-"))            try? FileManager.default.removeItem(at: named)            ShareSheet.present((try? FileManager.default.copyItem(at: path, to: named)) == nil ? path : named)        }    }}/// The open note: its surface, and its text saved on every pause and on leaving.@MainActorfinal class NoteWriterPage {    let editor: WritingEditor    let media: NotesWritingMedia    private let book: NotesBook    private let id: String    private var saved: String    private var pending: Task<Void, Never>?    /// The title the core read last, and the one the note opened with (`notes.leave` relinks when it changed).    private(set) var title: String?    private let openedTitle: String?    /// Moved away (archived, binned, deleted): nothing more is saved.    var closed = false    init(book: NotesBook, opened: NoteText, look: WritingLook, words: WritingWords) {        self.book = book        id = opened.id        saved = opened.text        title = opened.title        openedTitle = opened.title        media = NotesWritingMedia(book: book, id: opened.id)        media.learn(opened.pictures)        editor = WritingEditor(rules: book.rules(hideMarks: NotesStanding.shared.hideMarks), media: media, words: words, look: look)        editor.load(opened.text)        editor.onChange = { [weak self] _ in self?.later() }    }    /// Saves after a pause in typing.    private func later() {        pending?.cancel()        pending = Task { [weak self] in            try? await Task.sleep(for: .milliseconds(700))            guard !Task.isCancelled else { return }            try? await self?.save()        }    }    func save() async throws {        let text = editor.text        guard !closed, text != saved else { return }        let answer = try await book.edit(id, text: text, cursor: editor.textView.selectedRange.location)        saved = answer.text        title = answer.title        media.learn(answer.pictures)    }    /// The core wrote the note (a tag added at the end): the surface takes    /// its text as one change Undo takes back.    func took(_ answer: NoteText) {        saved = answer.text        title = answer.title        media.learn(answer.pictures)        let end = (answer.text as NSString).length        editor.apply(WritingChange(text: answer.text, selection: answer.selection ?? WritingSelection(start: end, end: end)))    }    /// Leaving: the last words kept; a note left with no words is not kept.    func close() {        pending?.cancel()        guard !closed else { return }        closed = true        let text = editor.text        let unsaved = text != saved        let book = book        let id = id        let opened = openedTitle        Task {            if unsaved { _ = try? await book.edit(id, text: text, cursor: nil) }            try? await book.leave(id, title: opened)        }    }}/// The camera, for a picture placed in the text.struct NotesCamera: UIViewControllerRepresentable {    let took: (UIImage?) -> Void    func makeUIViewController(context: Context) -> UIImagePickerController {        let picker = UIImagePickerController()        picker.sourceType = .camera        picker.delegate = context.coordinator        return picker    }    func updateUIViewController(_ controller: UIImagePickerController, context: Context) {}    func makeCoordinator() -> Coordinator { Coordinator(took: took) }    final class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {        let took: (UIImage?) -> Void        init(took: @escaping (UIImage?) -> Void) { self.took = took }        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {            took(info[.originalImage] as? UIImage)        }        func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { took(nil) }    }}/// A picture of the text, whole, to look at closely.struct NotesPictureViewer: View {    struct Shown: Identifiable { var url: URL; var id: String { url.path } }    let url: URL    let close: String    @Environment(\.dismiss) private var dismiss    @State private var image: UIImage?    @State private var scale: CGFloat = 1    var body: some View {        ZStack(alignment: .topTrailing) {            Color.black.ignoresSafeArea()            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 } }                    .accessibilityIdentifier("notes-picture-viewer")            }            Button { dismiss() } label: {                Image(systemName: "xmark").font(.system(size: 17, weight: .semibold)).foregroundStyle(.white)                    .frame(width: 44, height: 44).background(Circle().fill(.white.opacity(0.18)))            }            .accessibilityLabel(Text(verbatim: close))            .padding(16)        }        .task { image = await NotesPictures.image(at: url, width: 1200) }    }}#endif