Cotton code
852 lines · 37.6 KB · SwiftRaw
// COTTON NOTES' ROOT (assets/design/notes/DECISIONS.md "Structure on a// phone"), as Android's `NotesSurface.kt`: the whole app, mounted by the root// in place of the fan and the board (`RootView.hosts`), as Days and Story// are. No fan. The list is where Notes opens: the place's name with its small// arrow (tap it, or swipe in from the left edge, for the side page), More at// the right, search under the header, the rows, the new-note button low on// the right. The side page slides in from the left and pushes the list right,// its edge still showing (NotesDrawer.swift). A note opens over everything; Settings and Account stand as pages of their own.#if os(iOS)import CottonKitimport CottonValuesimport CottonWritingimport SwiftUIimport UIKit@MainActor@Observablefinal class NotesModel {    let book: NotesBook    var themes: NotesThemes?    /// The look and type chosen (`notes.settings`): standing from the moment it is answered, and kept for the next launch.    var chosen: NotesSettingsChosen? {        didSet { if let chosen { NotesStanding.shared.take(chosen) } }    }    /// The place the list stands on (a view, and its tag or list).    var place = NotesListAsk(view: "all")    var list: NotesList?    var side: NotesSide?    var query = ""    var opened: NotesOpened?    /// How far the side page stands open, as drawn (it pushes the list: NotesDrawer.swift).    let drawer = NotesDrawer()    /// The side page is open, or going there; a change springs it the rest of the way.    var sideOpen = false {        didSet { if sideOpen != oldValue { drawer.go(sideOpen) } }    }    var settingsOpen = false    var accountOpen = false    /// The assistant's memory, read-only (`notes.memory`, CONTRACT.md §13).    var memoryOpen = false    /// The web page an assistant made being read: its list row (`kind` page).    var page: NotesRow?    var importing = false    /// Words said once at the top (a receipt, a refusal).    var said: String?    /// The thumbnails drawn, by the media key the core named.    var thumbs: [String: UIImage] = [:]    init(book: NotesBook) { self.book = book }    /// The looks and the type, once; the list and the side page each time.    func load() async throws {        if themes == nil { themes = try await book.themes() }        if chosen == nil { chosen = try await book.settings() }        try await reload()    }    func reload() async throws {        list = try await book.list(place, search: query.isEmpty ? nil : query)        side = try await book.side()    }    /// Stand the list on another place.    func show(_ ask: NotesListAsk) {        place = ask        query = ""        Task { await attempt { try await reload() } }    }    /// A finger let go of the side page or the list's edge, moving `across` points a second; nil is a tap,    /// which closes it.    func letGoOfSide(_ across: CGFloat?) {        if let across {            sideOpen = drawer.release(across)        } else {            drawer.go(false)            sideOpen = false        }    }    /// A note written, moved or made: the list and the side page read again.    func moved() async { await attempt { try await reload() } }    func tell(_ words: String) { said = words }    func attempt(_ work: () async throws -> Void) async {        do { try await work() } catch { tell(ActionRefused.words(for: error)) }    }    /// What the screens draw with, once the core has said it.    func look(dark: Bool) -> WritingLook? { chosen?.look(dark: dark) }    /// A row's thumbnail: the first picture the core named, drawn small once.    func needThumb(_ row: NotesRow) async {        guard let key = row.thumbnail, thumbs[key] == nil, let url = await book.picturePath(key: key) else { return }        thumbs[key] = await NotesPictures.image(at: url, width: 60)    }    /// Pin or unpin a note: inside the tag a tag's list stands on, else in Notes. Unpinning in a tag's list    /// takes both pins off, so the row leaves the top.    func pin(_ row: NotesRow, _ on: Bool) async {        let tag = place.view == "tag" ? place.tag : nil        await attempt {            var said = try await book.pin(row.id, tag: tag, on).said            if !on, tag != nil, row.pinnedInNotes { said = try await book.pin(row.id, false).said }            if let said { tell(said) }        }        await moved()    }    /// A row's act: Pin, Unpin, or one of the core's moves (archive, unarchive, bin, restore).    func act(_ row: NotesRow, _ act: String) async {        switch act {        case "pin", "unpin": await pin(row, act == "pin")        default:            await attempt {                let answer = try await book.move(row.id, act)                if let words = answer.said { tell(words) }            }            await moved()        }    }    /// Delete for good, asked first: the core's ask, shown in Notes' look; on its act, deleted with `confirmed`.    func askRemove(_ id: String, then done: @escaping () -> Void = {}) async -> NotesAsked? {        do {            guard let ask = try await book.remove(id, confirmed: false).ask else { return nil }            return NotesAsked(ask: ask) { [weak self] in                Task {                    guard let self else { return }                    await self.attempt {                        let answer = try await self.book.remove(id, confirmed: true)                        if let words = answer.said { self.tell(words) }                    }                    done()                    await self.moved()                }            }        } catch {            tell(ActionRefused.words(for: error))            return nil        }    }    /// Empty the bin, asked first as Delete for good is.    func askEmptyBin() async -> NotesAsked? {        do {            guard let ask = try await book.emptyBin(confirmed: false).ask else { return nil }            return NotesAsked(ask: ask) { [weak self] in                Task {                    guard let self else { return }                    await self.attempt {                        let answer = try await self.book.emptyBin(confirmed: true)                        if let words = answer.said { self.tell(words) }                    }                    await self.moved()                }            }        } catch {            tell(ActionRefused.words(for: error))            return nil        }    }    /// Notes as a file in `format`, handed to the share sheet.    func export(ids: [String]? = nil, view: String? = nil, _ format: String) async {        await attempt {            let made = try await book.export(ids: ids, view: view, format: format)            ShareSheet.present(URL(fileURLWithPath: made.path))        }    }}/// A note open for writing; `fresh` raises the keyboard at once.struct NotesOpened: Identifiable, Equatable {    var id: String    var fresh: Bool    /// Where to stand the caret (a linked heading), when said.    var at: Int? = nil}/// One act on a sheet: its id, its words, its icon, red when it cannot be taken back.struct NotesAct: Identifiable, Equatable {    var id: String    var label: String    var icon: String    var red = false    static func of(_ id: String, _ icon: String, red: Bool = false) -> NotesAct {        NotesAct(id: id, label: notesLine("acts.\(id)"), icon: icon, red: red)    }}/// A question asked before an act that cannot be undone (Delete for good, Empty the bin), in the core's words.struct NotesAsked: Identifiable {    var title: String    var message: String    var yes: String    var run: () -> Void    var id: String { title + message }    init(ask: NotesAsk, run: @escaping () -> Void) {        title = ask.title        message = ask.message        yes = ask.act        self.run = run    }}/// Cotton Notes, the whole app.struct NotesRoot: View {    /// Cotton Notes' own build (Notes, Notes Dev).    static var applies: Bool { NotesBooks.isNotes }    @State private var model: NotesModel    @Environment(\.colorScheme) private var scheme    @Environment(\.cottonSync) private var sync    @Environment(BootModel.self) private var boot: BootModel?    @Environment(\.scenePhase) private var phase    @Environment(\.accessibilityReduceMotion) private var reduceMotion    init(core: any CottonCalling, start: NotesListAsk = NotesListAsk(view: "all")) {        let model = NotesModel(book: NotesBook(core: core))        model.place = start        _model = State(initialValue: model)    }    private var standing: WritingTheme { NotesLook.standing(dark: scheme == .dark) }    var body: some View {        ZStack {            Color(uiColor: standing.ground).ignoresSafeArea()            if let look = model.look(dark: scheme == .dark) {                // The side page pushes the list: the list moves right with it, its left edge still showing                // in the last fifth, barely dimmed; a tap or a drag there closes the page (NotesDrawer.swift;                // DECISIONS.md "The drawer").                NotesListScreen(model: model, look: look)                    .accessibilityHidden(model.sideOpen || model.drawer.visible)                    // The edge stands from the moment the page is asked open, not from its first move.                    .overlay { if model.sideOpen || model.drawer.visible { NotesListEdge(model: model) } }                    .offset(x: model.drawer.shown * model.drawer.width)                NotesSidePage(model: model, look: look)                if model.settingsOpen, let themes = model.themes, let chosen = model.chosen {                    NotesSettings(book: model.book, themes: themes, chosen: chosen, look: look, said: { model.tell($0) },                                  importing: { model.importing = true }, changed: { model.chosen = $0 }, close: { model.settingsOpen = false },                                  themesChanged: { model.themes = $0 })                        .transition(.move(edge: .trailing))                        .zIndex(3)                }                // Account is Settings' Profile, opened there; its Back closes it.                if model.accountOpen, let themes = model.themes, let chosen = model.chosen {                    NotesSettings(book: model.book, themes: themes, chosen: chosen, look: look, said: { model.tell($0) },                                  importing: { model.importing = true }, changed: { model.chosen = $0 }, close: { model.accountOpen = false },                                  opensAt: .profile, themesChanged: { model.themes = $0 })                        .transition(.move(edge: .trailing))                        .zIndex(3)                }                if model.memoryOpen {                    NotesMemoryPage(model: model, look: look)                        .transition(.move(edge: .trailing))                        .zIndex(3)                }                if let page = model.page {                    NotesPageReader(model: model, row: page, look: look)                        .id(page.id)                        .transition(.move(edge: .bottom))                        .zIndex(4)                }                NotesSaidLine(said: $model.said, look: look).zIndex(5)            }        }        .animation(.easeOut(duration: 0.2), value: model.settingsOpen)        .animation(.easeOut(duration: 0.2), value: model.accountOpen)        .animation(.easeOut(duration: 0.2), value: model.memoryOpen)        .animation(.easeOut(duration: 0.2), value: model.page?.id)        // The app's one keyboard rule (Chrome/KeyboardDismissal.swift): a drag down or a tap outside a field        // puts the keyboard away, on the list, the side page, Settings, Account and every sheet. Notes wore        // none, so the search's keyboard stood over the list after a tap beside it (NotesKeyboardTests).        .cottonScreenFrame()        // The side page's width: four fifths of the screen, so a fifth of the list shows beside it.        .onGeometryChange(for: CGFloat.self, of: { $0.size.width }) { model.drawer.width = NotesDrawer.width(across: $0) }        .onChange(of: reduceMotion, initial: true) { _, now in model.drawer.reduceMotion = now }        .task {            #if COTTON_DEV            await NotesLookSeed.prepare(model.book)            #endif            await model.attempt { try await model.load() }            // The first content is read: the splash goes now, never at the            // launch's ceiling (launch-fast, 20 Nov 2026).            FanLaunch.firstContent()            // Settings draws whole on its first frame from the list last read; a phone with none yet reads it now.            Task { await SettingsHome.warm(model.book.core) }            #if COTTON_DEV            NotesLookSeed.open(model)            #endif        }        // Another device or an assistant wrote: read again.        .onChange(of: sync?.foreignRevision) { _, _ in Task { await model.moved() } }        .onChange(of: phase) { _, now in if now == .active { Task { await model.moved() } } }        // The first pull ended: what came is read whole.        .onChange(of: boot?.home?.bringing == nil) { _, done in if done { Task { await model.moved() } } }        .fullScreenCover(item: $model.opened, onDismiss: { Task { await model.moved() } }) { opened in            if let themes = model.themes, let chosen = model.chosen {                NoteWriter(model: model, themes: themes, chosen: chosen, id: opened.id, fresh: opened.fresh, at: opened.at)                    // A note covers the window: the shell's lines are drawn over it, in Words' toast.                    .receiptsOverCover()            }        }        .fileImporter(isPresented: $model.importing, allowedContentTypes: NotesImport.types, allowsMultipleSelection: true) { result in            NotesImport.shared.start(result, book: model.book) { await model.moved() }        }        .overlay {            if let look = model.look(dark: scheme == .dark) {                NotesImportProgress(importer: NotesImport.shared, look: look, close: notesLine("writer.done"))            }        }    }}/// A fan card's list (`TableRoute`), for a build that still routes there: Notes' own root on that place.struct NotesHome: View {    let view: NotesListAsk    @Environment(\.cottonCore) private var core    var body: some View {        if let core { NotesRoot(core: core, start: view) }    }}// MARK: - The listprivate struct NotesListScreen: View {    @Bindable var model: NotesModel    let look: WritingLook    @Environment(BootModel.self) private var boot: BootModel?    @State private var more = false    @State private var held: NotesRow?    @State private var tagging: String?    @State private var exporting: String?    @State private var asking: NotesAsked?    private var theme: WritingTheme { look.theme }    private func ui(_ colour: UIColor) -> Color { Color(uiColor: colour) }    private var view: String { model.place.view }    private var heading: String { model.list?.heading ?? notesLine("side.\(view)") }    var body: some View {        VStack(spacing: 0) {            header            // Where sync stands, in one quiet line (SyncSeenLine); the first pull's loading line says it while it runs.            if boot?.home?.bringing == nil {                SyncSeenLine(font: Font(UIFontMetrics(forTextStyle: .footnote).scaledFont(for: look.font([]).withSize(13))), color: ui(theme.dim)) {                    SyncSeenOpens.ask()                    model.settingsOpen = true                }                .padding(.horizontal, 20)                .frame(maxWidth: .infinity, alignment: .leading)            }            NotesSearchField(look: look, hint: model.list?.searchHint ?? notesLine("list.search_hint"), query: $model.query)                .onChange(of: model.query) { Task { await model.moved() } }            ZStack(alignment: .bottomTrailing) {                rows                if let list = model.list, view != "bin", view != "archive", view != "assistant" {                    NotesRoundButton(icon: "compose", name: list.compose, id: "notes-compose", look: look, filled: true, size: 58) { compose() }                        .padding(.trailing, 20)                        .padding(.bottom, 18)                }            }        }        // A swipe in from the left edge opens the side page, as its header does, following the finger.        .gesture(NotesEdgeSwipe(began: { model.drawer.grab() }, moved: { model.drawer.follow($0) },                                ended: { model.letGoOfSide($0) }))        .overlay {            if more {                NotesActSheet(acts: listActs, look: look, onAct: { act in                    more = false                    switch act.id {                    case "settings": model.settingsOpen = true                    case "import": model.importing = true                    case "empty_bin": Task { asking = await model.askEmptyBin() }                    default: break                    }                }) { more = false }            }            if let row = held {                NotesActSheet(acts: rowActs(row), look: look, title: row.title ?? String(row.preview.prefix(48)), onAct: { act in                    held = nil                    switch act.id {                    case "tags": tagging = row.id                    case "export": exporting = row.id                    case "remove": Task { asking = await model.askRemove(row.id) }                    default: Task { await model.act(row, act.id) }                    }                }) { held = nil }            }            if let id = tagging {                NotesTagPicker(model: model, look: look, id: id) {                    tagging = nil                    Task { await model.moved() }                }            }            if let id = exporting {                NotesExportSheet(look: look) { format in                    exporting = nil                    Task { await model.export(ids: [id], format) }                } close: { exporting = nil }            }            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 }            }        }    }    /// The header: the side page's button, the place's name with its small arrow (the side page too), More at    /// the right.    private var header: some View {        HStack(spacing: 0) {            // The side mark (DECISIONS.md "The drawer"): Words' own `side` drawing (scripts/draw-notes-icons.py),            // 22 points in the text colour, plain, 48 points to touch, as Android draws it.            NotesRoundButton(icon: "side", name: notesLine("side.open"), id: "notes-menu", look: look, plain: true, size: 48, mark: 22) {                model.sideOpen = true            }            Button { model.sideOpen = true } label: {                HStack(spacing: 4) {                    Text(verbatim: heading)                        .font(Font(WritingFonts.font(look.type.face, size: 28, weight: .bold, scaled: false)))                        .foregroundStyle(ui(theme.heading))                        .lineLimit(1)                        .accessibilityIdentifier("notes-title")                    WritingMark("chevron_down", colour: ui(theme.dim), size: 20)                }                .padding(.horizontal, 8)                .padding(.vertical, 6)                .frame(maxWidth: .infinity, alignment: .leading)                .contentShape(Rectangle())            }            .buttonStyle(.plain)            .accessibilityLabel(Text(verbatim: notesLine("side.open") + ", " + heading))            .accessibilityAddTraits(.isHeader)            .accessibilityIdentifier("notes-place")            NotesRoundButton(icon: "more", name: NotesNav.more, id: "notes-more", look: look) { more = true }        }        .padding(.leading, 8)        .padding(.trailing, 8)        .padding(.top, 6)    }    private var rows: some View {        List {            if let list = model.list {                // While the first pull runs: the one quiet line ("Loading your                // data… 42%") above what has come, never "no notes" (launch-fast).                if let bringing = boot?.home?.bringing {                    LoadingLine(bringing: bringing, ink: ui(theme.dim), font: Font(look.font([]).withSize(13)))                        .padding(.horizontal, 20)                        .padding(.vertical, 8)                        .notesRowPlain()                }                if list.rows.isEmpty, boot?.home?.bringing == nil, let empty = list.empty {                    Text(verbatim: empty)                        .font(Font(look.font([]).withSize(16)))                        .foregroundStyle(ui(theme.dim))                        .multilineTextAlignment(.center)                        .frame(maxWidth: .infinity)                        .padding(.horizontal, 36)                        .padding(.vertical, 80)                        .notesRowPlain()                        .accessibilityIdentifier("notes-empty")                }                // One tap from the person's own notes to what the assistant wrote (CONTRACT.md §13).                if let to = list.assistant {                    toAssistant(to)                }                ForEach(list.rows) { row in                    if row.kind == "page" {                        pageRow(row)                    } else {                    WritingListRow(title: row.title, preview: row.preview, date: row.date, lines: row.previewLines, look: look,                                   pinned: row.pinned, done: row.checklist?.done ?? 0, total: row.checklist?.total ?? 0,                                   thumbnail: row.thumbnail.flatMap { model.thumbs[$0] })                        .onTapGesture { model.opened = NotesOpened(id: row.id, fresh: false) }                        .onLongPressGesture(minimumDuration: 0.4) { held = row }                        .accessibilityAddTraits(.isButton)                        .accessibilityAction(named: Text(verbatim: NotesNav.more)) { held = row }                        .accessibilityIdentifier("notes-row")                        .swipeActions(edge: .leading, allowsFullSwipe: true) { swipe(swipes(row).start, row) }                        .swipeActions(edge: .trailing, allowsFullSwipe: true) { swipe(swipes(row).end, row) }                        .task(id: row.thumbnail) { await model.needThumb(row) }                        .notesRowPlain()                    }                }            }            Color.clear.frame(height: 104).notesRowPlain().accessibilityHidden(true)        }        .listStyle(.plain)        .scrollContentBackground(.hidden)        .environment(\.defaultMinListRowHeight, 1)        .scrollDismissesKeyboard(.immediately)        .refreshable { await model.moved() }        .accessibilityIdentifier("notes-list")    }    /// Notes' quiet line to what the assistant wrote: its mark, its name and how many, a small arrow.    private func toAssistant(_ to: NotesList.ToAssistant) -> some View {        let said = to.label + " · " + to.count.formatted()        return Button { model.show(to.list) } label: {            HStack(spacing: 10) {                WritingMark("assistant", colour: ui(theme.dim), size: 18)                Text(verbatim: said)                    .font(Font(WritingFonts.font(look.type.face, size: 15)))                    .foregroundStyle(ui(theme.dim))                    .frame(maxWidth: .infinity, alignment: .leading)                WritingMark("chevron_right", colour: ui(theme.faint), size: 16)            }            .padding(.horizontal, 20)            .padding(.vertical, 10)            .contentShape(Rectangle())        }        .buttonStyle(.plain)        .accessibilityLabel(Text(verbatim: said))        .accessibilityIdentifier("list-to-assistant")        .notesRowPlain()    }    /// A web page an assistant made: read only, no swipes and no acts; a tap opens the sealed reader,    /// or says why it cannot.    private func pageRow(_ row: NotesRow) -> some View {        WritingListRow(title: row.title, preview: row.preview, date: row.date, lines: row.previewLines, look: look,                       pinned: false, done: 0, total: 0, thumbnail: nil)            .onTapGesture {                if let refused = row.page?.refused { model.tell(refused) } else { model.page = row }            }            .accessibilityAddTraits(.isButton)            .accessibilityIdentifier("notes-page-row")            .notesRowPlain()    }    /// The swipes, by where the note stands: Pin (or Unpin) and Bin; from the archive, back and Bin;    /// in the bin, Restore and Delete for good.    private func swipes(_ row: NotesRow) -> (start: NotesAct, end: NotesAct) {        switch view {        case "bin": (.of("restore", "restore"), .of("remove", "delete_forever", red: true))        case "archive": (.of("unarchive", "restore"), .of("bin", "bin", red: true))        default: (row.pinned ? .of("unpin", "unpin") : .of("pin", "pin"), .of("bin", "bin", red: true))        }    }    private func swipe(_ act: NotesAct, _ row: NotesRow) -> some View {        Button {            if act.id == "remove" { Task { asking = await model.askRemove(row.id) } } else { Task { await model.act(row, act.id) } }        } label: {            Label {                Text(verbatim: act.label)            } icon: {                if let image = WritingMarks.image(act.icon) { Image(uiImage: image) }            }        }        .tint(act.red ? ui(theme.danger) : ui(theme.dim))    }    /// The list's More: the look and type, bringing notes in, and in the bin, emptying it.    private var listActs: [NotesAct] {        var acts = [NotesAct(id: "settings", label: notesLine("side.settings"), icon: "settings"),                    NotesAct(id: "import", label: notesLine("import.door"), icon: "import")]        if view == "bin", model.list?.rows.isEmpty == false { acts.append(.of("empty_bin", "delete_forever", red: true)) }        return acts    }    /// A held row's acts: Pin, Tags, Archive (or back), Export, Bin; in the bin, Restore and Delete for good.    private func rowActs(_ row: NotesRow) -> [NotesAct] {        if view == "bin" { return [.of("restore", "restore"), .of("remove", "delete_forever", red: true)] }        return [row.pinned ? .of("unpin", "unpin") : .of("pin", "pin"), .of("tags", "tag"),                view == "archive" ? .of("unarchive", "restore") : .of("archive", "archive"), .of("export", "export"), .of("bin", "bin", red: true)]    }    private func compose() {        Task {            await model.attempt {                let note = try await model.book.new(tag: view == "tag" ? model.place.tag : nil)                if view == "pinned" { _ = try await model.book.pin(note.id, true) }                model.opened = NotesOpened(id: note.id, fresh: true)            }        }    }}// MARK: - Pieces/// A swipe in from the left edge: UIKit's edge pan, so a swipe up or down that starts at the edge is still/// the list's. An 18-point strip laid over the list's left edge took every touch there, and a scroll begun/// on a row's first letters left the list where it was. The list's own pans (its scroll, a row's swipe) wait/// on it, so a swipe in from the edge opens the side page and never pins the row under it.struct NotesEdgeSwipe: UIGestureRecognizerRepresentable {    /// A finger came in from the edge.    let began: @MainActor () -> Void    /// It has moved this many points across since.    let moved: @MainActor (CGFloat) -> Void    /// It let go, moving this many points a second across.    let ended: @MainActor (CGFloat) -> Void    func makeUIGestureRecognizer(context: Context) -> UIScreenEdgePanGestureRecognizer {        let pan = UIScreenEdgePanGestureRecognizer()        pan.edges = .left        pan.delegate = context.coordinator        return pan    }    func handleUIGestureRecognizerAction(_ pan: UIScreenEdgePanGestureRecognizer, context: Context) {        // In the window's points: the list itself moves under the finger.        switch pan.state {        case .began: began(); moved(pan.translation(in: nil).x)        case .changed: moved(pan.translation(in: nil).x)        case .ended: ended(pan.velocity(in: nil).x)        case .cancelled, .failed: ended(-10_000)  // taken away: it closes        default: break        }    }    func makeCoordinator(converter: CoordinateSpaceConverter) -> Delegate { Delegate() }    final class Delegate: NSObject, UIGestureRecognizerDelegate {        func gestureRecognizer(_ gesture: UIGestureRecognizer, shouldBeRequiredToFailBy other: UIGestureRecognizer) -> Bool {            other is UIPanGestureRecognizer && !(other is UIScreenEdgePanGestureRecognizer)        }    }}/// The search under the header: a rounded field in the raised sheet colour; words like `#tag`, `-word`,/// `@todo` narrow it.struct NotesSearchField: View {    let look: WritingLook    let hint: String    @Binding var query: String    @FocusState private var focused: Bool    var body: some View {        let theme = look.theme        HStack(spacing: 9) {            WritingMark("search", colour: Color(uiColor: theme.dim), size: 18)            TextField(text: $query) { Text(verbatim: hint).foregroundStyle(Color(uiColor: theme.faint)) }                .font(Font(look.font([]).withSize(16)))                .foregroundStyle(Color(uiColor: theme.ink))                .tint(Color(uiColor: theme.accent))                .focused($focused)                .submitLabel(.search)                .autocorrectionDisabled()                .textInputAutocapitalization(.never)                .accessibilityIdentifier("notes-search-field")            if !query.isEmpty {                Button { query = ""; focused = false } label: { WritingMark("close", colour: Color(uiColor: theme.dim), size: 16) }                    .frame(width: 24, height: 24)                    .accessibilityLabel(Text(verbatim: NotesNav.close))            }        }        .padding(.horizontal, 12)        .padding(.vertical, 9)        .background(RoundedRectangle(cornerRadius: 11).fill(Color(uiColor: theme.sheet)))        .padding(.horizontal, WritingListRow.side - 4)        .padding(.vertical, 8)    }}/// A round button holding one of the set's marks, named by the core's words: back, info, more, compose.struct NotesRoundButton: View {    let icon: String    let name: String    let id: String    let look: WritingLook    var filled = false    var plain = false    var size: CGFloat = 40    /// The drawing's size; nil: 24 filled, else 20.    var mark: CGFloat? = nil    let tap: () -> Void    var body: some View {        let theme = look.theme        Button(action: tap) {            ZStack {                if filled {                    Circle().fill(Color(uiColor: theme.accent)).shadow(color: .black.opacity(0.18), radius: 6, y: 3)                } else if !plain {                    Circle().fill(Color(uiColor: theme.sheet))                }                WritingMark(icon, colour: Color(uiColor: filled ? theme.onAccent : theme.ink), size: mark ?? (filled ? 24 : 20))            }            .frame(width: size, height: size)            .frame(minWidth: 44, minHeight: 44)            .contentShape(Circle())        }        .buttonStyle(.plain)        .accessibilityLabel(Text(verbatim: name))        .accessibilityIdentifier(id)    }}/// A sheet of acts standing over the screen (a note's More, the list's More, a held row): each act a row;/// a tap outside or a pull down on any part of it closes it (as Android's NotesSheet, 38fb329f72). Drawn in/// Notes' look, never a system sheet.struct NotesActSheet: View {    let acts: [NotesAct]    let look: WritingLook    var title: String?    var message: String?    let onAct: (NotesAct) -> Void    let onClose: () -> Void    var body: some View {        let theme = look.theme        ZStack(alignment: .bottom) {            Color.black.opacity(0.28).ignoresSafeArea()                .onTapGesture(perform: onClose)                .accessibilityLabel(Text(verbatim: NotesNav.close))                .accessibilityAddTraits(.isButton)                .accessibilityIdentifier("notes-act-scrim")            VStack(alignment: .leading, spacing: 0) {                if let title {                    Text(verbatim: title)                        .font(Font(look.font([]).withSize(16)))                        .foregroundStyle(Color(uiColor: theme.ink))                        .padding(.horizontal, 20)                        .padding(.top, 12)                        .padding(.bottom, message == nil ? 12 : 4)                        .accessibilityIdentifier("notes-act-title")                }                if let message {                    Text(verbatim: message)                        .font(Font(look.font([]).withSize(15)))                        .foregroundStyle(Color(uiColor: theme.dim))                        .fixedSize(horizontal: false, vertical: true)                        .padding(.horizontal, 20)                        .padding(.bottom, 12)                }                ForEach(acts) { act in                    Button { onAct(act) } label: {                        HStack(spacing: 16) {                            WritingMark(act.icon, colour: Color(uiColor: act.red ? theme.danger : theme.ink), size: 22)                            Text(verbatim: act.label)                                .font(Font(look.font([]).withSize(17)))                                .foregroundStyle(Color(uiColor: act.red ? theme.danger : theme.ink))                            Spacer(minLength: 0)                        }                        .padding(.horizontal, 20)                        .padding(.vertical, 14)                        .contentShape(Rectangle())                    }                    .buttonStyle(.plain)                    .accessibilityIdentifier("notes-act-\(act.id)")                }            }            .padding(.vertical, 8)            .background(RoundedRectangle(cornerRadius: 18).fill(Color(uiColor: theme.ground)))            .lookPanelPull(close: onClose)            .padding(12)        }        .transition(.opacity)        .zIndex(4)    }}/// Words said once (a receipt, a refusal) at the top edge, for 3.5 s, in the theme's inks reversed.struct NotesSaidLine: View {    @Binding var said: String?    let look: WritingLook    var body: some View {        VStack {            if let said {                Text(verbatim: said)                    .font(Font(look.font([]).withSize(15)))                    .foregroundStyle(Color(uiColor: look.theme.ground))                    .multilineTextAlignment(.center)                    .padding(.horizontal, 16)                    .padding(.vertical, 12)                    .background(RoundedRectangle(cornerRadius: 12).fill(Color(uiColor: look.theme.ink)))                    .padding(.horizontal, 24)                    .padding(.top, 8)                    .transition(.move(edge: .top).combined(with: .opacity))                    .accessibilityIdentifier("notes-said")                    .accessibilityAddTraits(.updatesFrequently)                    .task(id: said) {                        try? await Task.sleep(for: .seconds(3.5))                        withAnimation { self.said = nil }                    }            }            Spacer()        }        .animation(.easeOut(duration: 0.2), value: said)        .allowsHitTesting(false)    }}/// The shell's passing line (an approval, a sync failure, a sealed key) in Words' own toast (`AppToast`): the said/// line's face, at the top edge, in the standing theme's inks reversed, with Undo when the line carries one.struct NotesToast: View {    let toast: CottonToast    let onUndo: () -> Void    let onDismiss: () -> Void    @Environment(\.colorScheme) private var scheme    var body: some View {        let theme = NotesLook.standing(dark: scheme == .dark)        HStack(spacing: 12) {            Text(verbatim: toast.message)                .font(AppLookFace.figtree.font(15, weight: 400))                .foregroundStyle(Color(uiColor: theme.ground))                .multilineTextAlignment(toast.undo == nil ? .center : .leading)                .lineLimit(AppToastView.lineLimit(toast.tone))                .fixedSize(horizontal: false, vertical: true)            if toast.undo != nil {                Button(action: onUndo) {                    Text(CottonStrings.undo)                        .font(AppLookFace.figtree.font(15, weight: 600))                        .foregroundStyle(Color(uiColor: theme.ground))                        .underline()                        .frame(minWidth: 44, minHeight: 44)                        .contentShape(Rectangle())                }                .buttonStyle(.plain)            }        }        .padding(.horizontal, 16)        .padding(.vertical, toast.undo == nil ? 12 : 2)        .background(RoundedRectangle(cornerRadius: 12).fill(Color(uiColor: theme.ink)))        .padding(.horizontal, 24)        .padding(.top, 8)        .onTapGesture(perform: onDismiss)        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)    }}/// Export: the formats the core makes (CONTRACT.md §9), each in its words; the file goes to the share sheet.struct NotesExportSheet: View {    let look: WritingLook    let chose: (String) -> Void    let close: () -> Void    var body: some View {        NotesActSheet(acts: NotesBook.exportFormats.map { NotesAct(id: $0, label: notesLine("export.\($0)"), icon: "export") }, look: look,                      title: notesLine("export.title"), onAct: { chose($0.id) }, onClose: close)    }}extension View {    func notesRowPlain() -> some View {        listRowInsets(EdgeInsets()).listRowSeparator(.hidden).listRowBackground(Color.clear)    }}#endif