Cotton code
184 lines · 10.0 KB · SwiftRaw
// A look on a simulator opens a screen by name, as Days' `-days-open`:// `-notes-open list|side|note|info|more|find|bar|format|tags|many|settings|account|long|bin|tag|assistant|memory|reader`.// Before the first read, made-up notes are written through the core's own// `notes.new` and `notes.edit` into this dev build's local database, once,// when it holds none. `-notes-crowd YES` adds the crowd for the long-list// checks (`notes-crowd.json`, sixty-four invented notes over thirty-six// invented tags, and one wearing seven), once, when they are not there yet;// `many` opens that note's tag picker. Never the owner's data: a look runs// on a fresh simulator, signed out. Dev builds only.// `-notes-files YES` (or a look at `files`) adds one invented note carrying// invented files, a web page, a Markdown file, a PDF, a picture and an// archive Words cannot show (`notes-files-seed.json`), attached through the// core's `developer.inventNoteFiles`, once; `files` opens it.#if os(iOS) && COTTON_DEVimport CottonKitimport Foundationimport UIKit@MainActorenum NotesLookSeed {    static var asked: String? { UserDefaults.standard.string(forKey: "notes-open") }    static var crowd: Bool { UserDefaults.standard.bool(forKey: "notes-crowd") }    /// `-notes-files YES` (or a look at `files`): the invented note that carries a file of each kind.    static var files: Bool { UserDefaults.standard.bool(forKey: "notes-files") || asked == "files" }    /// `-notes-assistant YES` (or a look at Your assistant): invented writing an assistant made.    static var assistant: Bool {        UserDefaults.standard.bool(forKey: "notes-assistant") || ["assistant", "memory", "reader"].contains(asked ?? "")    }    /// The made-up notes, a bundled file (`Resources/Fixtures/notes-dev-seed.json`), so no English a person    /// reads is a Swift literal (as Vault Dev's seed, 9889b18d4).    private struct Seed: Decodable {        struct Long: Decodable { let heading: String; let words: String; let title: String; let named: String; let opens: String }        let notes: [String]        let long: Long    }    /// The crowd (`Resources/Fixtures/notes-crowd.json`): its notes, and the title of the one wearing seven tags.    private struct Crowd: Decodable {        let notes: [String]        let many: String    }    /// The invented files (`Resources/Fixtures/notes-files-seed.json`).    private struct Files: Decodable {        struct Page: Decodable { let name: String; let html: String }        struct Markdown: Decodable { let name: String; let text: String }        struct PDF: Decodable { let name: String; let lines: [String] }        struct Named: Decodable { let name: String; let words: String }        let title: String        let body: String        let page: Page        let markdown: Markdown        let pdf: PDF        let picture: Named        let other: Named    }    private static let invented: Files? = fixture("notes-files-seed")    private static let seed: Seed? = fixture("notes-dev-seed")    private static let crowded: Crowd? = fixture("notes-crowd")    private static func fixture<T: Decodable>(_ name: String) -> T? {        guard let url = Bundle.module.url(forResource: name, withExtension: "json", subdirectory: "Fixtures"),              let data = try? Data(contentsOf: url) else { return nil }        return try? JSONDecoder().decode(T.self, from: data)    }    /// Writes the made-up notes once, when this database holds none; then the crowd, once, when it is asked    /// and its notes are not there yet.    static func prepare(_ book: NotesBook) async {        guard asked != nil || crowd || files, let list = try? await book.list(NotesListAsk(view: "all"), search: nil) else { return }        var texts: [String] = []        if list.rows.isEmpty, let seed {            texts = seed.notes            if asked == "long" { texts.append(longNote(seed.long)) }        }        if crowd, let crowded, !list.rows.contains(where: { $0.title == crowded.many }) { texts += crowded.notes }        for text in texts {            guard let made = try? await book.new(tag: nil) else { continue }            _ = try? await book.edit(made.id, text: text, cursor: nil)        }        if files, let invented, await filesNote(book) == nil { await attachFiles(invented, book) }        // The assistant's invented notes, pages and memory, written as an assistant's writes land        // (Cotton Dev only; the same rows each time, never more).        if assistant, let writing = inventedWriting {            _ = try? await book.core.callJSON("developer.inventAssistantWriting", writing)        }    }    /// The note carrying a file of each kind: each written to this phone's temporary folder first (a PDF and a    /// picture drawn here from the fixture's words) and handed to the core, which keeps its own copy.    private static func attachFiles(_ files: Files, _ book: NotesBook) async {        let folder = FileManager.default.temporaryDirectory.appendingPathComponent("notes-files-seed", isDirectory: true)        try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)        let pdf = UIGraphicsPDFRenderer(bounds: CGRect(x: 0, y: 0, width: 420, height: 595)).pdfData { context in            context.beginPage()            for (n, line) in files.pdf.lines.enumerated() {                (line as NSString).draw(at: CGPoint(x: 36, y: 48 + CGFloat(n) * 40),                                        withAttributes: [.font: UIFont.systemFont(ofSize: n == 0 ? 26 : 17, weight: n == 0 ? .bold : .regular)])            }        }        let picture = UIGraphicsImageRenderer(size: CGSize(width: 600, height: 400)).pngData { context in            UIColor(red: 0.55, green: 0.70, blue: 0.80, alpha: 1).setFill()            context.fill(CGRect(x: 0, y: 0, width: 600, height: 260))            UIColor(red: 0.80, green: 0.72, blue: 0.55, alpha: 1).setFill()            context.fill(CGRect(x: 0, y: 260, width: 600, height: 140))            (files.picture.words as NSString).draw(at: CGPoint(x: 24, y: 24), withAttributes: [.font: UIFont.systemFont(ofSize: 30, weight: .semibold)])        }        let kinds: [(String, Data, String)] = [(files.page.name, Data(files.page.html.utf8), "text/html"),                                              (files.markdown.name, Data(files.markdown.text.utf8), "application/octet-stream"),                                              (files.pdf.name, pdf, "application/pdf"),                                              (files.picture.name, picture, "image/png"),                                              (files.other.name, Data(files.other.words.utf8), "application/octet-stream")]        // As a picker hands them: the server takes no `text/markdown` or zip type, and the core reads what a        // file is from its name when its type says nothing (`file_format`).        var handed: [JSONValue] = []        for (name, data, mime) in kinds {            let file = folder.appendingPathComponent(name)            guard (try? data.write(to: file)) != nil else { continue }            handed.append(.object(["path": .string(file.path), "mime": .string(mime), "name": .string(name)]))        }        let invented = try? await book.core.callJSON("developer.inventNoteFiles",                                                 JSONValue.object(["title": .string(files.title), "body": .string(files.body), "files": .array(handed)]))        if case .object(let answer)? = invented, case .string(let id)? = answer["id"] { UserDefaults.standard.set(id, forKey: filesKey) }    }    /// The invented note with files, once made: an assistant's writing (it is made as an assistant attaches    /// files), so it stands in From your assistant, not in Notes.    private static func filesNote(_ book: NotesBook) async -> String? {        guard let id = UserDefaults.standard.string(forKey: filesKey), (try? await book.open(id)) != nil else { return nil }        return id    }    /// Where this phone keeps the invented note's id, once made.    private static let filesKey = "notes-files-seed.note"    /// `Resources/Fixtures/notes-assistant-seed.json`, handed to the core as it stands.    private static let inventedWriting: JSONValue? = fixture("notes-assistant-seed")    /// A long note, about 50,000 characters, to type in.    private static func longNote(_ long: Seed.Long) -> String {        var out = long.title        var n = 0        while (out as NSString).length < 50_000 {            n += 1            out += long.heading + String(n) + "\n" + long.words        }        return out    }    static func open(_ model: NotesModel) {        guard let open = asked else { return }        let first = model.list?.rows.first { $0.title == seed?.long.opens } ?? model.list?.rows.first        let many = model.list?.rows.first { $0.title == crowded?.many }        switch open {        case "side": model.sideOpen = true        case "settings": model.settingsOpen = true        case "account": model.accountOpen = true        case "bin": model.show(NotesListAsk(view: "bin"))        case "tag": model.show(NotesListAsk(view: "tag", tag: "home/garden"))        case "note", "info", "find", "format", "more", "bar", "tags":            if let first { model.opened = NotesOpened(id: first.id, fresh: false) }        case "many":            if let many { model.opened = NotesOpened(id: many.id, fresh: false) }        case "long":            if let row = model.list?.rows.first(where: { $0.title == seed?.long.named }) { model.opened = NotesOpened(id: row.id, fresh: true) }        case "assistant": model.show(NotesListAsk(view: "assistant"))        case "memory": model.memoryOpen = true        case "files":            Task { if let id = await filesNote(model.book) { model.opened = NotesOpened(id: id, fresh: false) } }        case "reader":            Task {                model.place = NotesListAsk(view: "assistant")                await model.moved()                model.page = model.list?.rows.first { $0.kind == "page" && $0.page?.refused == nil }            }        default: break        }    }}#endif