Cotton code
500 lines · 25.1 KB · SwiftRaw
// THE SIDE PAGE (DECISIONS.md "Structure" 2), as Android's `NotesSide.kt`: it// slides in from the left. Top: Notes, Pinned, Todo, Today, Untagged. Then// Tags as a tree (nested behind an arrow, each with its own drawn icon, root// tags pinnable by a hold), then the hand-made Lists, then Archive and Bin,// then Settings and Account as two plain lines. It pushes the list rather// than covering it (the owner, 22 Nov 2026): the list moves right with it and// its edge shows beside it (NotesDrawer.swift). A tap stands the list on that// place and closes the page; a swipe back to the left, or a tap or drag on// the list's edge, closes it, following the finger. Also here: the tag// picker and Account.#if os(iOS)import CottonKitimport CottonValuesimport CottonWritingimport SwiftUIimport UIKitstruct NotesSidePage: View {    @Bindable var model: NotesModel    let look: WritingLook    @State private var folded: Set<String> = []    @State private var held: NotesSideTag?    @State private var choosing: NotesSideTag?    @State private var icons: NotesTagIcons?    /// A finger is moving the page across.    @State private var dragging = false    private var theme: WritingTheme { look.theme }    private func ui(_ colour: UIColor) -> Color { Color(uiColor: colour) }    var body: some View {        ZStack(alignment: .leading) {            // Drawn while it shows at all: it stands where the drawer says, the list beside it (NotesRoot).            if model.sideOpen || model.drawer.visible {                page                    .frame(width: model.drawer.width)                    .frame(maxHeight: .infinity)                    .offset(x: (model.drawer.shown - 1) * model.drawer.width)            }            if let tag = held {                // A root tag pins to the top; any tag may choose its icon (the core's words for both).                let words = model.side?.words ?? [:]                let pin = NotesAct(id: "pin", label: words[tag.pinned ? "unpin_tag" : "pin_tag"] ?? "", icon: tag.pinned ? "unpin" : "pin")                let icon = NotesAct(id: "icon", label: words["choose_icon"] ?? "", icon: tag.icon)                NotesActSheet(acts: tag.depth == 0 ? [pin, icon] : [icon], look: look, title: "#" + tag.tag, onAct: { act in                    held = nil                    if act.id == "icon" {                        choosing = tag                        return                    }                    Task { await model.attempt { model.side = try await model.book.pinTag(tag.tag, !tag.pinned) } }                }) { held = nil }            }            if let tag = choosing {                NotesIconPicker(look: look, icons: icons, current: tag.icon) { id in                    choosing = nil                    Task { await model.attempt { model.side = try await model.book.tagIcon(tag.tag, id) } }                } close: { choosing = nil }                .task { if icons == nil { icons = try? await model.book.tagIcons() } }            }        }        // The whole screen, the page at its left edge (a ZStack the page's width stood centred).        .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)        .zIndex(2)        .task(id: model.sideOpen) { if model.sideOpen { await model.moved() } }    }    private var page: some View {        VStack(spacing: 0) {            ScrollView {                VStack(alignment: .leading, spacing: 0) {                    Text(verbatim: notesLine("app.name"))                        .font(Font(WritingFonts.font(look.type.face, size: 22, weight: .bold, scaled: false)))                        .foregroundStyle(ui(theme.heading))                        .padding(.leading, 12).padding(.top, 10).padding(.bottom, 12)                        .accessibilityAddTraits(.isHeader)                        .accessibilityIdentifier("side-title")                    if let side = model.side {                        ForEach(side.places) { place in                            NotesPlaceRow(icon: place.icon, label: place.label, count: place.count, current: standing(place.list), look: look,                                          id: "side-\(place.id)") { go(place.list) }                        }                        if !side.tags.items.isEmpty {                            section(side.tags.label)                            ForEach(flat(side.tags.items)) { tag in                                let open = !folded.contains(tag.tag)                                NotesPlaceRow(icon: tag.icon, label: tag.name, count: tag.count, current: standing(tag.list), look: look,                                              id: "side-tag-\(tag.tag)", depth: tag.depth, pinned: tag.pinned,                                              fold: tag.children.isEmpty ? nil : open,                                              onFold: { if open { folded.insert(tag.tag) } else { folded.remove(tag.tag) } },                                              onHold: { held = tag }) { go(tag.list) }                            }                        }                        if !side.lists.items.isEmpty {                            section(side.lists.label)                            ForEach(side.lists.items) { list in                                NotesPlaceRow(icon: list.icon, label: list.label, count: list.count, current: standing(list.list), look: look,                                              id: "side-list-\(list.id)") { go(list.list) }                            }                        }                        // What the assistant wrote, and its memory (CONTRACT.md §13).                        if let assistant = side.assistant, !assistant.items.isEmpty {                            section(assistant.label)                            ForEach(assistant.items) { place in                                NotesPlaceRow(icon: place.icon, label: place.label, count: place.count,                                              current: place.opens == nil && standing(place.list), look: look,                                              id: "side-\(place.id)") {                                    if place.opens == "memory" {                                        model.sideOpen = false                                        model.memoryOpen = true                                    } else {                                        go(place.list)                                    }                                }                            }                        }                        Color.clear.frame(height: 12)                        ForEach(side.foot) { place in                            NotesPlaceRow(icon: place.icon, label: place.label, count: place.count, current: standing(place.list), look: look,                                          id: "side-\(place.id)") { go(place.list) }                        }                    }                }                .padding(.horizontal, 10)                .padding(.vertical, 8)            }            Rectangle().fill(ui(theme.rule)).frame(height: 0.5).padding(.horizontal, 22)            VStack(alignment: .leading, spacing: 0) {                ForEach(model.side?.more ?? []) { more in                    Button {                        model.sideOpen = false                        if more.id == "settings" { model.settingsOpen = true } else if more.id == "account" { model.accountOpen = true }                    } label: {                        Text(verbatim: more.label)                            .font(Font(look.font([]).withSize(16)))                            .foregroundStyle(ui(theme.ink))                            .padding(.horizontal, 12).padding(.vertical, 11)                            .frame(maxWidth: .infinity, alignment: .leading)                            .contentShape(Rectangle())                    }                    .buttonStyle(.plain)                    .accessibilityIdentifier("side-\(more.id)")                }            }            .padding(.horizontal, 10)            .padding(.vertical, 8)        }        .frame(maxHeight: .infinity)        // Rows scrolled up ran under the clock (launch-ios walk, 22 Nov 2026):        // the sheet stands over the status bar as a zero-high band whose ground        // reaches into the safe area (as Comms' c4194e3cfb).        .overlay(alignment: .top) {            Color.clear.frame(height: 0).background(ui(theme.sheet), ignoresSafeAreaEdges: .top)        }        .background(ui(theme.sheet).ignoresSafeArea())        // Where it meets the list: one hairline, no shadow.        .overlay(alignment: .trailing) { Rectangle().fill(ui(theme.rule)).frame(width: 0.5).ignoresSafeArea() }        // A drag across the page moves it with the finger (a drag up or down is its scroll's).        .gesture(DragGesture(minimumDistance: 18, coordinateSpace: .global)            .onChanged { drag in                if !dragging, abs(drag.translation.width) > abs(drag.translation.height) {                    dragging = true                    model.drawer.grab()                }                if dragging { model.drawer.follow(drag.translation.width) }            }            .onEnded { drag in                guard dragging else { return }                dragging = false                model.letGoOfSide(drag.velocity.width)            })        .accessibilityAction(.escape) { model.sideOpen = false }        .accessibilityElement(children: .contain)        .accessibilityIdentifier("side-page")    }    /// The tree as drawn: each tag, then its children unless it is folded.    private func flat(_ tags: [NotesSideTag]) -> [NotesSideTag] {        tags.flatMap { [$0] + (folded.contains($0.tag) ? [] : flat($0.children)) }    }    private func standing(_ list: NotesListAsk) -> Bool {        list.view == model.place.view && list.tag == model.place.tag && list.list == model.place.list    }    private func go(_ list: NotesListAsk) {        model.show(list)        model.sideOpen = false    }    private func section(_ title: String) -> some View {        Text(verbatim: title)            .font(Font(WritingFonts.font(look.type.face, size: 13, weight: .semibold, scaled: false)))            .foregroundStyle(ui(theme.dim))            .padding(.leading, 12).padding(.top, 18).padding(.bottom, 6)            .accessibilityAddTraits(.isHeader)    }}/// One place on the side page: its icon, its name, its count; the place standing wears the accent on a faint ground.private struct NotesPlaceRow: View {    let icon: String    let label: String    let count: Int    let current: Bool    let look: WritingLook    let id: String    var depth = 0    var pinned = false    var fold: Bool?    var onFold: () -> Void = {}    var onHold: (() -> Void)?    let onTap: () -> Void    var body: some View {        let theme = look.theme        HStack(spacing: 0) {            WritingMark(icon, colour: Color(uiColor: current ? theme.accent : theme.dim), size: 20)            Text(verbatim: label)                .font(Font(WritingFonts.font(look.type.face, size: 16, weight: current ? .semibold : .medium)))                .foregroundStyle(Color(uiColor: current ? theme.accent : theme.ink))                // A name takes up to three lines at the largest sizes rather than be cut ("From your a…", CONTRACT.md §13).                .lineLimit(3)                .padding(.leading, 13)                .frame(maxWidth: .infinity, alignment: .leading)            if pinned {                WritingMark("pinned", colour: Color(uiColor: theme.faint), size: 13).padding(.trailing, 6)            }            if count > 0 {                // Grouped by the person's locale ("5,040"), never "5040".                Text(verbatim: count.formatted())                    .font(Font(WritingFonts.font(look.type.face, size: 14, weight: .medium)))                    .foregroundStyle(Color(uiColor: theme.faint))            }            if let fold {                Button(action: onFold) {                    WritingMark(fold ? "chevron_down" : "chevron_right", colour: Color(uiColor: theme.dim), size: 16)                        .frame(width: 32, height: 32)                        .contentShape(Rectangle())                }                .buttonStyle(.plain)                .accessibilityLabel(Text(verbatim: notesLine(fold ? "side.fold" : "side.unfold")))                .accessibilityIdentifier("\(id)-fold")            } else {                Color.clear.frame(width: 32, height: 1)            }        }        .padding(.leading, 12 + CGFloat(depth * 18))        .padding(.trailing, 6)        .padding(.vertical, 9)        .background(RoundedRectangle(cornerRadius: 10).fill(current ? Color(uiColor: theme.chip) : .clear))        .padding(.vertical, 1)        .contentShape(Rectangle())        .onTapGesture(perform: onTap)        .onLongPressGesture(minimumDuration: 0.4) { onHold?() }        .accessibilityElement(children: .combine)        .accessibilityLabel(Text(verbatim: count > 0 ? "\(label), \(count.formatted())" : label))        .accessibilityAddTraits(current ? [.isButton, .isSelected] : .isButton)        .accessibilityIdentifier(id)    }}// MARK: - The tag picker/// THE TAG PICKER: the note's tags with a way to take each off, the tags that begin with what is typed, and a/// new tag from the words typed. A tag picked is written into the note by the core (`notes.tag`), one taken off/// taken out by it (`notes.untag`).struct NotesTagPicker: View {    let model: NotesModel    let look: WritingLook    let id: String    let done: () -> Void    @State private var typed = ""    @State private var mine: [String] = []    @State private var all: [NotesTag] = []    @State private var turn = 0    /// How tall the note's own tags stand wrapped, so their scroll is no taller than they are.    @State private var mineHigh: CGFloat = 0    @FocusState private var focused: Bool    /// The most the note's own tags take before they scroll: four lines at the usual size, one chip at the largest.    private static let mineMost: CGFloat = 160    private struct Tags: Decodable { var tags: [String]? }    private struct Id: Encodable { let id: String }    private var clean: String {        typed.trimmingCharacters(in: .whitespaces).trimmingCharacters(in: CharacterSet(charactersIn: "#")).trimmingCharacters(in: .whitespaces)    }    var body: some View {        let theme = look.theme        // Every tag is offered, in a list that scrolls (as Android, c56e1758d8).        let offers = all.filter { t in !mine.contains(t.tag) && (clean.isEmpty || t.tag.localizedCaseInsensitiveContains(clean)) }        ZStack(alignment: .bottom) {            Color.black.opacity(0.28).ignoresSafeArea().onTapGesture(perform: done)            VStack(alignment: .leading, spacing: 10) {                Text(verbatim: notesLine("tag.ask"))                    .font(Font(WritingFonts.font(look.type.face, size: 18, weight: .bold)))                    .foregroundStyle(Color(uiColor: theme.heading))                    .accessibilityAddTraits(.isHeader)                if !mine.isEmpty {                    // All of the note's tags, wrapped onto as many lines as they need (as Android's FlowRow,                    // 1f20eb2031): in a row of four, the largest text squeezed each to a letter a line.                    ScrollView {                        InkFlow(spacing: 8) {                            ForEach(mine, id: \.self) { t in                                Button {                                    Task { await model.attempt { try await untag(t) }; turn += 1 }                                } label: {                                    HStack(spacing: 4) {                                        Text(verbatim: "#" + t).font(Font(WritingFonts.font(look.type.face, size: 15, weight: .medium)))                                            .multilineTextAlignment(.leading)                                        WritingMark("close", colour: Color(uiColor: theme.chipInk), size: 14)                                    }                                    .foregroundStyle(Color(uiColor: theme.chipInk))                                    .padding(.leading, 12).padding(.trailing, 8).padding(.vertical, 6)                                    .background(Capsule().fill(Color(uiColor: theme.chip)))                                }                                .buttonStyle(.plain)                                .accessibilityLabel(Text(verbatim: notesLine("tag.remove", ["tag": t])))                                .accessibilityIdentifier("tag-mine")                            }                        }                        .frame(maxWidth: .infinity, alignment: .leading)                        .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { mineHigh = $0 }                    }                    .frame(height: min(mineHigh, Self.mineMost))                }                TextField(text: $typed) { Text(verbatim: notesLine("tag.hint")).foregroundStyle(Color(uiColor: theme.faint)) }                    .font(Font(look.font([]).withSize(16)))                    .foregroundStyle(Color(uiColor: theme.ink))                    .tint(Color(uiColor: theme.accent))                    .textInputAutocapitalization(.never)                    .autocorrectionDisabled()                    .focused($focused)                    .submitLabel(.done)                    .onSubmit { if !clean.isEmpty { add(clean) } }                    .padding(.horizontal, 12).padding(.vertical, 11)                    .background(RoundedRectangle(cornerRadius: 11).fill(Color(uiColor: theme.sheet)))                    .accessibilityIdentifier("tag-field")                ScrollView {                    VStack(alignment: .leading, spacing: 0) {                        if !clean.isEmpty, !all.contains(where: { $0.tag.caseInsensitiveCompare(clean) == .orderedSame }) {                            offer(notesLine("tag.new", ["tag": clean]), nil, "plus") { add(clean) }                        }                        ForEach(offers) { t in                            offer("#" + t.tag, t.count, model.side?.icon(of: t.tag) ?? "hash") { add(t.tag) }                        }                    }                }                .frame(maxHeight: 260)                HStack {                    Spacer()                    Button(action: done) {                        Text(verbatim: notesLine("writer.done"))                            .font(Font(WritingFonts.font(look.type.face, size: 16, weight: .semibold)))                            .foregroundStyle(Color(uiColor: theme.accent))                            .padding(.horizontal, 8).padding(.vertical, 6)                    }                    .buttonStyle(.plain)                    .accessibilityIdentifier("tag-done")                }            }            .padding(18)            .background(RoundedRectangle(cornerRadius: 18).fill(Color(uiColor: theme.ground)))            .lookPanelPull(close: done)            .padding(10)            .accessibilityElement(children: .contain)            .accessibilityIdentifier("tag-picker")        }        .zIndex(4)        .task(id: turn) {            mine = (try? await model.book.core.call("notes.open", Id(id: id), as: Tags.self).tags) ?? []            all = (try? await model.book.tags()) ?? []        }    }    /// A tag taken off: the core takes its hashtag out of the words (`notes.untag`).    private func untag(_ tag: String) async throws { _ = try await model.book.untag(id, tag) }    private func add(_ tag: String) {        Task {            await model.attempt { _ = try await model.book.tag(id, tag) }            typed = ""            turn += 1        }    }    private func offer(_ label: String, _ count: Int?, _ icon: String, tap: @escaping () -> Void) -> some View {        Button(action: tap) {            HStack(spacing: 12) {                WritingMark(icon, colour: Color(uiColor: look.theme.dim), size: 18)                Text(verbatim: label).font(Font(look.font([]).withSize(16))).foregroundStyle(Color(uiColor: look.theme.ink))                Spacer()                if let count { Text(verbatim: String(count)).font(Font(look.font([]).withSize(14))).foregroundStyle(Color(uiColor: look.theme.faint)) }            }            .padding(.vertical, 10).padding(.horizontal, 4)            .contentShape(Rectangle())        }        .buttonStyle(.plain)        .accessibilityIdentifier("tag-offer")    }}// MARK: - Choosing a tag's icon/// The icons a tag may wear (`notes.tag_icons`), in a grid, each with its name; the one worn ringed.struct NotesIconPicker: View {    let look: WritingLook    let icons: NotesTagIcons?    let current: String    let chose: (String) -> Void    let close: () -> Void    var body: some View {        let theme = look.theme        ZStack(alignment: .bottom) {            Color.black.opacity(0.28).ignoresSafeArea().onTapGesture(perform: close)                .accessibilityLabel(Text(verbatim: NotesNav.close)).accessibilityAddTraits(.isButton)            VStack(alignment: .leading, spacing: 12) {                if let icons {                    Text(verbatim: icons.title)                        .font(Font(WritingFonts.font(look.type.face, size: 18, weight: .bold)))                        .foregroundStyle(Color(uiColor: theme.heading))                        .accessibilityAddTraits(.isHeader)                    LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 8), count: 4), spacing: 12) {                        ForEach(icons.icons) { icon in                            Button { chose(icon.id) } label: {                                VStack(spacing: 6) {                                    WritingMark(icon.id, colour: Color(uiColor: icon.id == current ? theme.accent : theme.ink), size: 24)                                        .frame(width: 48, height: 48)                                        .background(Circle().fill(Color(uiColor: theme.sheet)))                                        .overlay(Circle().stroke(Color(uiColor: theme.accent), lineWidth: icon.id == current ? 1.5 : 0))                                    Text(verbatim: icon.label)                                        .font(Font(WritingFonts.font(look.type.face, size: 12, weight: .medium)))                                        .foregroundStyle(Color(uiColor: theme.dim))                                        .lineLimit(1)                                }                                .contentShape(Rectangle())                            }                            .buttonStyle(.plain)                            .accessibilityLabel(Text(verbatim: icon.label))                            .accessibilityAddTraits(icon.id == current ? [.isButton, .isSelected] : .isButton)                            .accessibilityIdentifier("icon-\(icon.id)")                        }                    }                } else {                    ProgressView().frame(maxWidth: .infinity).padding(.vertical, 40)                }            }            .padding(20)            .background(RoundedRectangle(cornerRadius: 18).fill(Color(uiColor: theme.ground)))            .lookPanelPull(close: close)            .padding(10)        }        .zIndex(5)    }}#endif#if os(iOS)@MainActorextension SettingsLook {    /// The shared settings parts in Notes' look: its face, the theme's ink and dim, acts on its raised sheet,    /// choices as its pills.    static func notes(_ look: WritingLook) -> SettingsLook {        let theme = look.theme        func face(_ size: CGFloat, _ weight: UIFont.Weight = .regular) -> Font { Font(WritingFonts.font(look.type.face, size: size, weight: weight)) }        return SettingsLook(            ink: Color(uiColor: theme.ink), quiet: Color(uiColor: theme.dim), rule: Color(uiColor: theme.rule),            ground: Color(uiColor: theme.ground), body: face(15), small: face(13),            heading: { title in                AnyView(Text(verbatim: title).font(face(17, .bold)).foregroundStyle(Color(uiColor: theme.heading))                    .padding(.top, 18).padding(.bottom, 4).accessibilityAddTraits(.isHeader))            },            act: { words, id, enabled, tap in                AnyView(Button(action: tap) {                    Text(verbatim: words).font(face(16, .semibold)).foregroundStyle(Color(uiColor: theme.accent))                        .padding(.horizontal, 16).padding(.vertical, 12)                        .background(RoundedRectangle(cornerRadius: 12).fill(Color(uiColor: theme.sheet)))                }                .buttonStyle(.plain).disabled(!enabled).opacity(enabled ? 1 : 0.45).accessibilityIdentifier(id))            },            choice: { words, on, id, enabled, tap in                AnyView(Button(action: tap) {                    Text(verbatim: words).font(face(14, on ? .bold : .medium))                        .foregroundStyle(Color(uiColor: on ? theme.onAccent : theme.ink))                        .padding(.horizontal, 14).padding(.vertical, 7)                        .background(Capsule().fill(Color(uiColor: on ? theme.accent : theme.sheet)))                }                .buttonStyle(.plain).disabled(!enabled).accessibilityAddTraits(on ? [.isSelected] : []).accessibilityIdentifier(id))            },            danger: Color(uiColor: theme.danger),            title: face(26, .bold)        )    }}#endif