Cotton code
515 lines · 19.7 KB · SwiftRaw
// CottonWriting (notes-new-ios, 19 Nov 2026): the writing surface any Cotton// app drops in — Notes first, then Journal, Story and the rest. It knows// nothing of notes. Its host hands it a `WritingRules` (the core's// `cotton-rules::writing`, through the host's own methods) and draws what it// answers: each line's block, each run's style and how it looks (text, dim,// hidden, a glyph), the tables as grids, what a key does to the text, which// tags to offer. The surface never reads Markdown itself.//// The shapes are `cotton-rules::writing`'s own (`style::Styled`,// `format::Edited`, `table::Table`). Offsets are UTF-16 code units, end// exclusive — the units UIKit's NSString and Android's String count in.import CoreGraphicsimport Foundation/// A text styled for a cursor (`style::Styled`).public struct WritingStyled: Decodable, Hashable, Sendable {    public var blocks: [WritingBlock]    public var spans: [WritingSpan]    public var tables: [WritingTable]    /// Where the text folds (`folds::Fold`): each heading and each list item with deeper items.    public var folds: [WritingFold]    /// The `[[note links]]` written, each with the note it opens when the host's core resolved it.    public var links: [WritingNoteLink]    public init(blocks: [WritingBlock] = [], spans: [WritingSpan] = [], tables: [WritingTable] = [], folds: [WritingFold] = [],                links: [WritingNoteLink] = []) {        self.blocks = blocks        self.spans = spans        self.tables = tables        self.folds = folds        self.links = links    }    enum CodingKeys: String, CodingKey { case blocks, spans, tables, folds, links }    public init(from decoder: Decoder) throws {        let c = try decoder.container(keyedBy: CodingKeys.self)        blocks = try c.decodeIfPresent([WritingBlock].self, forKey: .blocks) ?? []        spans = try c.decodeIfPresent([WritingSpan].self, forKey: .spans) ?? []        tables = try c.decodeIfPresent([WritingTable].self, forKey: .tables) ?? []        folds = try c.decodeIfPresent([WritingFold].self, forKey: .folds) ?? []        links = try c.decodeIfPresent([WritingNoteLink].self, forKey: .links) ?? []    }}/// A line that folds (`folds::Fold`): where it starts, and the range folding hides.public struct WritingFold: Decodable, Hashable, Sendable {    /// `heading` or `list`.    public var kind: String    public var line: Int    public var start: Int    public var end: Int    public var level: Int?    public init(kind: String = "heading", line: Int, start: Int, end: Int, level: Int? = nil) {        self.kind = kind        self.line = line        self.start = start        self.end = end        self.level = level    }}/// A `[[note link]]` as written: its run, its target, and the note it opens (nil: none has that title, or not resolved).public struct WritingNoteLink: Decodable, Hashable, Sendable {    public var start: Int    public var end: Int    public var target: String    public var heading: String?    public var note: String?    public init(start: Int, end: Int, target: String, heading: String? = nil, note: String? = nil) {        self.start = start        self.end = end        self.target = target        self.heading = heading        self.note = note    }}/// The notes a `[[` being typed may name (the host's `notes.links`): what to replace, and each offer.public struct WritingLinkOffers: Hashable, Sendable {    public struct Offer: Hashable, Sendable, Identifiable {        public var id: String        public var title: String        /// What is written in place of `replace`, and where the cursor then stands.        public var with: String        public var cursor: Int        public init(id: String, title: String, with: String, cursor: Int) {            self.id = id            self.title = title            self.with = with            self.cursor = cursor        }    }    public var replace: NSRange    public var offers: [Offer]    /// The words said when nothing matches.    public var none: String?    public init(replace: NSRange, offers: [Offer], none: String? = nil) {        self.replace = replace        self.offers = offers        self.none = none    }}/// One line and what it is (`style::Block`).public struct WritingBlock: Decodable, Hashable, Sendable {    public var start: Int    public var end: Int    /// `paragraph`, `blank`, `heading`, `bullet`, `numbered`, `check`, `quote`,    /// `divider`, `fence`, `code`, `table`, `table_rule`, `picture`.    public var kind: String    /// Where the line's words start, after its marker and indent.    public var content: Int    /// Indent level, 0 at the margin.    public var depth: Int    public var level: Int?    public var checked: Bool?    public var number: Int?    /// The note's title line.    public var title: Bool    /// A picture line's address, as written.    public var src: String?    /// A picture line's width: `small`, `medium` or `full` (nil: full).    public var width: String?    enum CodingKeys: String, CodingKey { case start, end, kind, content, depth, level, checked, number, title, src, width }    public init(start: Int, end: Int, kind: String, content: Int? = nil, depth: Int = 0, level: Int? = nil,                checked: Bool? = nil, number: Int? = nil, title: Bool = false, src: String? = nil, width: String? = nil) {        self.width = width        self.start = start        self.end = end        self.kind = kind        self.content = content ?? start        self.depth = depth        self.level = level        self.checked = checked        self.number = number        self.title = title        self.src = src    }    public init(from decoder: Decoder) throws {        let c = try decoder.container(keyedBy: CodingKeys.self)        start = try c.decode(Int.self, forKey: .start)        end = try c.decode(Int.self, forKey: .end)        kind = try c.decode(String.self, forKey: .kind)        content = try c.decodeIfPresent(Int.self, forKey: .content) ?? start        depth = try c.decodeIfPresent(Int.self, forKey: .depth) ?? 0        level = try c.decodeIfPresent(Int.self, forKey: .level)        checked = try c.decodeIfPresent(Bool.self, forKey: .checked)        number = try c.decodeIfPresent(Int.self, forKey: .number)        title = try c.decodeIfPresent(Bool.self, forKey: .title) ?? false        src = try c.decodeIfPresent(String.self, forKey: .src)        width = try c.decodeIfPresent(String.self, forKey: .width)    }    /// The share of the column a picture line stands at: small 0.4, medium 0.7, full 1.    public var pictureShare: CGFloat {        switch width {        case "small": 0.4        case "medium": 0.7        default: 1        }    }    public var range: NSRange { NSRange(location: start, length: max(0, end - start)) }}/// One run of the text and how it is drawn (`style::Span`).public struct WritingSpan: Decodable, Hashable, Sendable {    public var start: Int    public var end: Int    /// `title`, `heading`, `bold`, `italic`, `underline`, `strike`,    /// `highlight`, `code`, `code_block`, `link`, `image`, `tag`, `quote`,    /// `number`, `done`, `mark`, `indent`. A style this build does not know    /// is drawn as plain text.    public var style: String    /// `text`, `dim` (a mark the cursor is in), `hidden` (a mark away from    /// it), `glyph` (drawn as `glyph` instead of its characters).    public var look: String    public var level: Int?    /// `bullet`, `box`, `ticked`, `rule`.    public var glyph: String?    /// A link's or a picture's address.    public var url: String?    public init(start: Int, end: Int, style: String, look: String = "text", level: Int? = nil, glyph: String? = nil, url: String? = nil) {        self.start = start        self.end = end        self.style = style        self.look = look        self.level = level        self.glyph = glyph        self.url = url    }    public var range: NSRange { NSRange(location: start, length: max(0, end - start)) }}/// A pipe table's rows and cells (`table::Table`): the header row first,/// the delimiter line no row.public struct WritingTable: Decodable, Hashable, Sendable {    public var start: Int    public var end: Int    /// Per column: `none`, `left`, `center`, `right`.    public var align: [String]    public var rows: [[WritingCell]]    public init(start: Int, end: Int, align: [String] = [], rows: [[WritingCell]]) {        self.start = start        self.end = end        self.align = align        self.rows = rows    }    public var columns: Int { rows.map(\.count).max() ?? 0 }    public var range: NSRange { NSRange(location: start, length: max(0, end - start)) }    /// The cells' words alone, for a grid that redraws only when they change.    public var words: [[String]] { rows.map { $0.map(\.text) } }}/// One cell: where its words are (an empty cell is an empty range where words/// would go) and the words.public struct WritingCell: Decodable, Hashable, Sendable {    public var start: Int    public var end: Int    public var text: String    public init(start: Int, end: Int, text: String) {        self.start = start        self.end = end        self.text = text    }}/// One value in an action: words, a number or a yes/no.public enum WritingValue: Codable, Hashable, Sendable {    case text(String)    case number(Double)    case flag(Bool)    public init(from decoder: Decoder) throws {        let c = try decoder.singleValueContainer()        if let flag = try? c.decode(Bool.self) { self = .flag(flag) }        else if let number = try? c.decode(Double.self) { self = .number(number) }        else { self = .text(try c.decode(String.self)) }    }    public func encode(to encoder: Encoder) throws {        var c = encoder.singleValueContainer()        switch self {        case .text(let s): try c.encode(s)        case .number(let n): if n.rounded() == n, abs(n) < 1e15 { try c.encode(Int(n)) } else { try c.encode(n) }        case .flag(let b): try c.encode(b)        }    }    public var text: String? { if case .text(let s) = self { s } else { nil } }    public var number: Double? { if case .number(let n) = self { n } else { nil } }}/// What a key does, in the writing rule's own words (`format::Action`):/// `{"action": "heading", "level": 2}`, `{"action": "table_cell", "row": 1,/// "column": 0, "text": "…"}`. The surface sends it as it was given; it/// names only the few it presses itself (Return, a tick, a table's edits).public struct WritingAction: Codable, Hashable, Sendable {    public var fields: [String: WritingValue]    public init(_ name: String, _ more: [String: WritingValue] = [:]) {        fields = more.merging(["action": .text(name)]) { _, new in new }    }    public init(from decoder: Decoder) throws {        fields = try decoder.singleValueContainer().decode([String: WritingValue].self)    }    public func encode(to encoder: Encoder) throws {        var c = encoder.singleValueContainer()        try c.encode(fields)    }    /// The action's name: `bold`, `heading`, `return`.    public var name: String { fields["action"]?.text ?? "" }}/// A key pressed on a text: what it does, the whole text and the selection.public struct WritingAsk: Hashable, Sendable {    public var action: WritingAction    public var text: String    public var start: Int    public var end: Int    public init(action: WritingAction, text: String, start: Int, end: Int) {        self.action = action        self.text = text        self.start = start        self.end = end    }    public init(action: WritingAction, text: String, selection: NSRange) {        self.init(action: action, text: text, start: selection.location, end: NSMaxRange(selection))    }}public struct WritingSelection: Codable, Hashable, Sendable {    public var start: Int    public var end: Int    public init(start: Int, end: Int) {        self.start = start        self.end = end    }    public init(_ range: NSRange) {        self.init(start: range.location, end: NSMaxRange(range))    }    public var range: NSRange {        let low = min(start, end)        return NSRange(location: low, length: abs(end - start))    }}/// One replacement in the old text (`format::Replace`).public struct WritingReplace: Codable, Hashable, Sendable {    public var start: Int    public var end: Int    public var with: String    public init(start: Int, end: Int, with: String) {        self.start = start        self.end = end        self.with = with    }}/// The core's answer to a key (`format::Edited`): the whole new text, the one/// replacement that makes it, and the selection. Empty: the key does nothing/// here. The surface writes back only the replacement, so Undo takes back/// exactly the key.public struct WritingChange: Decodable, Hashable, Sendable {    public var text: String?    public var replace: WritingReplace?    public var selection: WritingSelection?    public init(text: String?, replace: WritingReplace? = nil, selection: WritingSelection?) {        self.text = text        self.replace = replace        self.selection = selection    }    public static let nothing = WritingChange(text: nil, selection: nil)}/// A tag the core offers while one is typed.public struct WritingTagOffer: Decodable, Hashable, Sendable, Identifiable {    public var tag: String    public var label: String    public var count: Int?    public var id: String { tag }    public init(tag: String, label: String, count: Int? = nil) {        self.tag = tag        self.label = label        self.count = count    }}/// A key on the bar or the formatting panel, as the core names it: what it/// is, what it does (`action`, sent back as it came), the words VoiceOver says, and what it/// wears — `glyph` (a few letters, "H1", "B", drawn in `style`) or `icon`/// (a symbol's name). `delete`, `space` and `return` are typed as the/// keyboard types them (Return through the core: it continues a list).public struct WritingKey: Decodable, Hashable, Sendable, Identifiable {    public var id: String    public var label: String    public var glyph: String?    public var icon: String?    /// `bold`, `italic`, `underline`, `strike`, `mono`: how a glyph is drawn.    public var style: String?    /// The panel's row it sits in.    public var group: String?    /// What it does to the text; nil for the surface's own keys (undo,    /// redo, tag, picture, hide, the panel, delete, space, return, copy, paste).    public var action: WritingAction?    /// An editing key, drawn darker than the marks (the grid's left column, delete, space, return).    public var grey: Bool?    /// What the key offers when held (H2 and H3 behind H1, the camera behind the picture); a corner triangle says so.    public var hold: [WritingKey]?    public init(id: String, label: String, glyph: String? = nil, icon: String? = nil, style: String? = nil, group: String? = nil,                action: WritingAction? = nil, grey: Bool? = nil, hold: [WritingKey]? = nil) {        self.id = id        self.action = action        self.grey = grey        self.hold = hold        self.label = label        self.glyph = glyph        self.icon = icon        self.style = style        self.group = group    }}/// A hardware keyboard's shortcut: the key, its modifiers, and the key it presses.public struct WritingShortcut: Decodable, Hashable, Sendable {    public var key: String    public var ctrl: Bool    public var shift: Bool    public var alt: Bool    public var does: String    enum CodingKeys: String, CodingKey { case key, ctrl, shift, alt, does }    public init(key: String, ctrl: Bool = true, shift: Bool = false, alt: Bool = false, does: String) {        self.key = key        self.ctrl = ctrl        self.shift = shift        self.alt = alt        self.does = does    }    public init(from decoder: Decoder) throws {        let c = try decoder.container(keyedBy: CodingKeys.self)        key = try c.decode(String.self, forKey: .key)        ctrl = try c.decodeIfPresent(Bool.self, forKey: .ctrl) ?? false        shift = try c.decodeIfPresent(Bool.self, forKey: .shift) ?? false        alt = try c.decodeIfPresent(Bool.self, forKey: .alt) ?? false        does = try c.decode(String.self, forKey: .does)    }}/// The surface's keys and words, as the core says them (`notes.keys`): the/// bar above the keyboard and the formatting panel's keys in order, the/// hardware shortcuts, and the words (`hint`, `add_row`, `add_column`,/// `remove_row`, `remove_column`, `cell` "Row {row}, column {column}").public struct WritingWords: Decodable, Hashable, Sendable {    public var bar: [WritingKey]    public var panel: [WritingKey]    public var shortcuts: [WritingShortcut]    public var words: [String: String]    /// The formatting keys as a grid in the keyboard's place, row by row (six across, four down); empty: `panel` in rows.    public var grid: [[WritingKey]]    /// The slim row under the grid: copy at the left, paste at the right.    public var foot: [WritingKey]    enum CodingKeys: String, CodingKey { case bar, panel, shortcuts, words, grid, foot }    public init(bar: [WritingKey], panel: [WritingKey], shortcuts: [WritingShortcut] = [], words: [String: String] = [:],                grid: [[WritingKey]] = [], foot: [WritingKey] = []) {        self.bar = bar        self.panel = panel        self.grid = grid        self.foot = foot        self.shortcuts = shortcuts        self.words = words    }    public init(from decoder: Decoder) throws {        let c = try decoder.container(keyedBy: CodingKeys.self)        bar = try c.decode([WritingKey].self, forKey: .bar)        panel = try c.decode([WritingKey].self, forKey: .panel)        shortcuts = try c.decodeIfPresent([WritingShortcut].self, forKey: .shortcuts) ?? []        words = try c.decodeIfPresent([String: String].self, forKey: .words) ?? [:]        grid = try c.decodeIfPresent([[WritingKey]].self, forKey: .grid) ?? []        foot = try c.decodeIfPresent([WritingKey].self, forKey: .foot) ?? []    }    public func bar(_ id: String) -> WritingKey? { bar.first { $0.id == id } }    public func key(_ id: String) -> WritingKey? {        let every = panel + grid.flatMap { $0 } + foot + bar        return every.first { $0.id == id } ?? every.flatMap { $0.hold ?? [] }.first { $0.id == id }    }    /// A word by its name; the name itself when the core said none, so a    /// missing word is seen, never invented.    public func word(_ name: String) -> String { words[name] ?? name }    func cell(_ row: Int, _ column: Int) -> String {        word("cell").replacingOccurrences(of: "{row}", with: String(row)).replacingOccurrences(of: "{column}", with: String(column))    }}/// What the surface asks of its host's core. Every answer is the core's.public protocol WritingRules: Sendable {    /// The text styled for the cursor (nil: reading, every mark hidden).    func style(_ text: String, cursor: Int?) async throws -> WritingStyled    /// What a key does to the text.    func press(_ ask: WritingAsk) async throws -> WritingChange    /// The tags to offer for the tag typed so far, `#` left off.    func tags(_ prefix: String) async throws -> [WritingTagOffer]    /// A tag as it is written in the text: `#work`, `#two words#`.    func written(_ tag: String) -> String}#if canImport(UIKit)import UIKit/// Where the surface's pictures come from and go to: the host's own store.public protocol WritingMedia: Sendable {    /// The picture an address names, at most `width` points wide.    func image(_ src: String, width: CGFloat) async -> UIImage?    /// Keeps a picture's file with the document and places it in the text at    /// the selection: the core's answer, as for a key.    func add(_ file: URL, text: String, selection: NSRange) async throws -> WritingChange}#endif