Cotton code
329 lines · 15.6 KB · SwiftRaw
// SETTINGS, grouped as Comms' You (owner, 23 Nov 2026; SettingsGrouped.swift),// as Android's `NotesSettings.kt` must: the person's card (Profile: who, Getting// back in, Sign out, Delete account), Sync and Your Claude; then Words' own// rows, Look (the shared Look screen, `Chrome/LookScreen.swift`: a note drawn// live, the papers for light and dark, the ink, the face and the size, then// More with the line spacing, the line width and whether marks hide, and// Reset to default; shared/DECISIONS.md "Look"), Import notes and Export all// notes, and Storage; then Help and feedback and About. The choices, their// bounds, their defaults and their words are the core's (`notes.themes`,// `notes.settings`, CONTRACT.md §10). No paragraph spacing, on either phone.#if os(iOS)import CottonKitimport CottonWritingimport SwiftUIimport UIKitstruct NotesSettings: View {    let book: NotesBook    @State var themes: NotesThemes    @State var chosen: NotesSettingsChosen    let look: WritingLook    let said: (String) -> Void    let importing: () -> Void    let changed: (NotesSettingsChosen) -> Void    /// The looks asked again after the ink is written: every paper's colours changed with it.    var themesChanged: (NotesThemes) -> Void = { _ in }    let close: () -> Void    /// Opened from the side page's Account: Settings stands on Profile, and its Back closes it.    var opensAt: SettingsPlace?    @State private var exporting = false    /// Reset to default, asked before it is written.    @State private var askingReset = false    /// Words' look as the core's `look` answers it (shared/DECISIONS.md "Look").    @State private var lookModel = LookModel.standing("notes")    /// The core's sample note, styled for the preview.    @State private var previewStyled: WritingStyled?    /// The list and the page standing (SettingsGrouped.swift): the person's card, Sync and Your Claude, Words' own    /// rows (Look, Type, Import notes, Export) and Storage, then Help and feedback and About.    @State private var home = SettingsHome()    @Environment(\.cottonCore) private var core    @Environment(\.cottonSync) private var sync    init(book: NotesBook, themes: NotesThemes, chosen: NotesSettingsChosen, look: WritingLook, said: @escaping (String) -> Void,         importing: @escaping () -> Void, changed: @escaping (NotesSettingsChosen) -> Void, close: @escaping () -> Void,         opensAt: SettingsPlace? = nil, themesChanged: @escaping (NotesThemes) -> Void = { _ in }) {        self.book = book        _themes = State(initialValue: themes)        self.themesChanged = themesChanged        _chosen = State(initialValue: chosen)        self.look = look        self.said = said        self.importing = importing        self.changed = changed        self.close = close        self.opensAt = opensAt        let home = SettingsHome()        home.place = opensAt ?? home.place        _home = State(initialValue: home)    }    private var theme: WritingTheme { look.theme }    private func ui(_ colour: UIColor) -> Color { Color(uiColor: colour) }    private func face(_ size: CGFloat, _ weight: UIFont.Weight = .regular) -> Font {        Font(WritingFonts.font(look.type.face, size: size, weight: weight))    }    var body: some View {        VStack(spacing: 0) {            HStack {                NotesRoundButton(icon: "back", name: NotesNav.back, id: "settings-back", look: look) { back() }                Spacer()                Text(verbatim: home.title(own: ownTitle) ?? notesLine("side.settings")).font(face(19, .bold)).foregroundStyle(ui(theme.heading))                    .lineLimit(2).multilineTextAlignment(.center)                    .accessibilityAddTraits(.isHeader)                Spacer()                Color.clear.frame(width: 48, height: 1)            }            .padding(.horizontal, 8).padding(.vertical, 4)            ScrollView {                VStack(alignment: .leading, spacing: 10) {                    page                    Color.clear.frame(height: 40)                }                .padding(.horizontal, 20).padding(.vertical, 8)            }            .id(home.place)        }        .frame(maxWidth: .infinity, maxHeight: .infinity)        .background(ui(theme.ground).ignoresSafeArea())        .overlay {            if askingReset, let answer = lookModel.answer {                NotesActSheet(acts: [NotesAct(id: "reset", label: answer.word("reset_yes"), icon: "undo")], look: look,                              title: answer.word("reset_title"), message: answer.word("reset_ask"),                              onAct: { _ in askingReset = false; resetLook() }) { askingReset = false }            }        }        .accessibilityElement(children: .contain)        .accessibilityIdentifier(home.place == .profile ? "notes-account" : "notes-settings")        .task(id: sync?.revision) { await home.read(core) }    }    /// Back: from a page to the list, from the list (or from Profile opened as Account) out.    private func back() {        if let opensAt, home.place == opensAt { close() } else { home.back(close: close) }    }    @ViewBuilder    private var page: some View {        switch home.place {        case nil:            SettingsHomeList(home: home, look: .notes(look), own: own) {                SettingsYouCard(home: home, core: core, look: .notes(look), said: said)            }        case .profile?:            profile        case .own("look")?:            lookPage        case .own?:            EmptyView()        case let shared?:            SettingsSharedPage(place: shared, home: home, core: core, look: .notes(look), said: said) { Task { await home.read(core) } }        }    }    /// Words' own rows, each saying how it stands.    private var own: [SettingsOwnRow] {        func named(_ id: String) -> String { themes.themes.first { $0.id == id }?.name ?? id }        return [            SettingsOwnRow(id: "look", label: notesLine("theme.title"),                           line: [named(chosen.lightTheme), named(chosen.darkTheme)].joined(separator: " · ")),            SettingsOwnRow(id: "import", label: notesLine("import.door"), line: notesLine("import.door_hint")) { importing() },            SettingsOwnRow(id: "export", label: notesLine("export.all"), line: notesLine("export.hint")) { Task { await exportAll() } },        ]    }    private func ownTitle(_ id: String) -> String? {        own.first { $0.id == id }?.label    }    /// LOOK, the shared screen (shared/DECISIONS.md "Look"): a note drawn live in the paper, ink, face and size chosen,    /// then the papers, the inks, the faces and the size, from the core's `look`; More holds Words' other type settings    /// (`notes.settings`); Reset asks first.    @ViewBuilder    private var lookPage: some View {        if let answer = lookModel.answer {            LookScreen(choices: LookChoices(answer), words: LookWords(answer), skin: lookSkin, gutter: 20,                       choose: { pick in Task { await lookModel.choose(pick, core: core); await lookChanged() } },                       reset: { askingReset = true }) { dark in                lookPreview(dark: dark)            } more: {                VStack(alignment: .leading, spacing: 14) {                    Text(verbatim: answer.word("more")).font(face(14, .semibold)).foregroundStyle(ui(theme.dim))                        .accessibilityAddTraits(.isHeader)                    stepper(themes.word("line_height"), chosen.lineHeight, themes.lineHeight, "%.1f") { set("line_height", .number($0)) }                    choices(themes.word("line_width"), themes.lineWidths.map { (String(Int($0.value)), $0.name) }, String(Int(chosen.lineWidth))) {                        set("line_width", .number(Double($0) ?? 0))                    }                    toggle(themes.word("hide_marks"), notesLine("type.hide_marks_hint"), chosen.hideMarks) {                        set("hide_marks", .flag($0))                    }                }            }            .task(id: answer.preview?.text) {                guard let text = answer.preview?.text else { return }                previewStyled = try? await book.rules(hideMarks: chosen.hideMarks).style(text, cursor: nil)            }        } else {            Color.clear.frame(height: 200).task { await lookModel.read(core) }        }    }    /// After a choice in Look: Words' settings and papers read again, so every screen draws in what now stands.    private func lookChanged() async {        if let refused = lookModel.refused { said(refused); lookModel.refused = nil }        do {            chosen = try await book.settings()            changed(chosen)            let asked = try await book.themes()            themes = asked            themesChanged(asked)        } catch { said(ActionRefused.words(for: error)) }    }    /// The screen in Words' own look: its paper and ink, Figtree, and each face in itself.    private var lookSkin: LookSkin {        LookSkin(ground: ui(theme.ground), ink: ui(theme.ink), quiet: ui(theme.dim), accent: ui(theme.accent), onAccent: ui(theme.onAccent),                 sheet: ui(theme.sheet), rule: ui(theme.rule),                 font: { size, weight in face(size, Self.weight(weight)) },                 face: { id, size in Font(WritingFonts.font(LookFaces.drawn(id, own: NotesLook.face("sans")), size: size)) })    }    private static func weight(_ weight: Font.Weight) -> UIFont.Weight {        switch weight {        case .bold: .bold        case .semibold: .semibold        case .medium: .medium        default: .regular        }    }    /// The preview: the core's sample note (a heading, bold, a highlight, a ticked and an open item, a tag), styled by    /// the core and drawn in the paper of that appearance, the ink, the face and the size chosen, whole at any text size.    @ViewBuilder    private func lookPreview(dark: Bool) -> some View {        let paper = themes.themes.first { $0.id == (dark ? chosen.darkTheme : chosen.lightTheme) }?.writing(dark: dark) ?? theme        let drawn = WritingLook(theme: paper, type: chosen.type)        VStack(alignment: .leading, spacing: 0) {            if let previewStyled, let text = lookModel.answer?.preview?.text {                LookSampleText(text: writingAttributed(text, styled: previewStyled, look: drawn))            } else {                Color.clear.frame(height: 120)            }        }        .padding(18)        .frame(maxWidth: .infinity, alignment: .leading)        .background(RoundedRectangle(cornerRadius: 18).fill(Color(uiColor: paper.ground)))        .overlay(RoundedRectangle(cornerRadius: 18).strokeBorder(Color(uiColor: paper.rule), lineWidth: 0.5))    }    /// Reset to default: the look's choices back to Words' defaults (the core's `look`); line spacing, line width and    /// hide marks stay as they were.    private func resetLook() {        Task {            await lookModel.reset(core: core)            await lookChanged()        }    }    /// PROFILE: the name large, the number, then any other account act, Getting back in, Sign out and Delete account.    @ViewBuilder    private var profile: some View {        SettingsProfileHead(home: home, look: .notes(look))        SettingsProfileFoot(home: home, core: core, look: .notes(look), said: said) { close() }    }    /// A row of choices, each a pill in its own words; the chosen one in the accent.    private func choices(_ title: String, _ options: [(String, String)], _ current: String, pick: @escaping (String) -> Void) -> some View {        VStack(alignment: .leading, spacing: 8) {            Text(verbatim: title).font(face(14)).foregroundStyle(ui(theme.dim))            ScrollView(.horizontal, showsIndicators: false) {                HStack(spacing: 8) {                    ForEach(options, id: \.0) { id, label in                        let on = id == current                        Button { pick(id) } label: {                            Text(verbatim: label).font(face(15, on ? .bold : .medium))                                .foregroundStyle(ui(on ? theme.onAccent : theme.ink))                                .padding(.horizontal, 16).padding(.vertical, 9)                                .background(Capsule().fill(ui(on ? theme.accent : theme.sheet)))                        }                        .buttonStyle(.plain)                        .accessibilityAddTraits(on ? [.isSelected] : [])                        .accessibilityIdentifier("choice-\(id)")                    }                }            }        }    }    /// A number the core bounds: its name and value, with a smaller and a larger step either side.    private func stepper(_ title: String, _ value: Double, _ range: NotesThemes.Range, _ format: String, set: @escaping (Double) -> Void) -> some View {        let step = range.step > 0 ? range.step : 1        func next(_ by: Double) -> Double { min(range.max, max(range.min, ((value + by) / step).rounded() * step)) }        return HStack {            Text(verbatim: title).font(face(14)).foregroundStyle(ui(theme.dim))            Spacer()            stepKey("−", "\(title) −") { let n = next(-step); if n != value { set(n) } }            Text(verbatim: String(format: format, value)).font(face(16, .semibold)).foregroundStyle(ui(theme.ink)).padding(.horizontal, 6)                .accessibilityIdentifier("stepper-value")            stepKey("+", "\(title) +") { let n = next(step); if n != value { set(n) } }        }    }    private func stepKey(_ mark: String, _ name: String, tap: @escaping () -> Void) -> some View {        Button(action: tap) {            Text(verbatim: mark).font(face(20)).foregroundStyle(ui(theme.ink))                .frame(width: 40, height: 40).background(Circle().fill(ui(theme.sheet)))        }        .buttonStyle(.plain)        .frame(minWidth: 44, minHeight: 44)        .accessibilityLabel(Text(verbatim: name))    }    /// A switch: its name and what it does, on or off in the accent.    private func toggle(_ title: String, _ hint: String, _ on: Bool, set: @escaping (Bool) -> Void) -> some View {        Button { set(!on) } label: {            HStack {                VStack(alignment: .leading, spacing: 2) {                    Text(verbatim: title).font(face(15)).foregroundStyle(ui(theme.ink))                    Text(verbatim: hint).font(face(13)).foregroundStyle(ui(theme.dim))                }                Spacer()                ZStack(alignment: on ? .trailing : .leading) {                    Capsule().fill(ui(on ? theme.accent : theme.rule)).frame(width: 46, height: 28)                    Circle().fill(ui(theme.ground)).frame(width: 22, height: 22).padding(3)                }            }            .contentShape(Rectangle())        }        .buttonStyle(.plain)        .accessibilityAddTraits(on ? [.isSelected] : [])        .accessibilityIdentifier("settings-hide-marks")    }    private func set(_ key: String, _ value: NotesSetting) {        Task {            do {                chosen = try await book.settings([key: value])                changed(chosen)            } catch { said(ActionRefused.words(for: error)) }        }    }    /// Every live note as Markdown files in one `.zip` (the core's `notes.export`, its words in `export.hint`), through the share sheet.    private func exportAll() async {        guard !exporting else { return }        exporting = true        defer { exporting = false }        do {            let made = try await book.export(view: "all", format: "markdown")            ShareSheet.present(URL(fileURLWithPath: made.path))        } catch { said(ActionRefused.words(for: error)) }    }}private extension String {    var nonEmpty: String? { isEmpty ? nil : self }}#endif