Cotton code
240 lines · 9.5 KB · SwiftRaw
// What a record carries attached — a photo, a video or a document — and the// pins left on them. Opened, an attachment is the one viewer's// (`MediaViewer`), which reads the comments on a note and files a pin as an// ordinary `create_comment` with an anchor naming the attachment and the// point pressed.//// **A thought's pictures open read-only** (store schema 36): a pin is a// COMMENT and a thought carries no conversation, so the viewer is opened with// no pins and nothing is ever filed against an id that is not a note's.import CottonKitimport SwiftUI// ── what a note carries ─────────────────────────────────────────────────────/// One thing attached to a note: a photo, a video or a document.////// `get_record`'s own row (`records_2/record.rs`), read rather than decoded/// into a generated type — the tree the boundary answers is the contract, and/// a field this app does not draw is a field it does not name. Extra fields/// are ignored, so a crate one deploy ahead never breaks the page.struct RecordAttachment: Equatable, Sendable {    /// `photo`, `video` or `document`.    let kind: String    /// The record's own id — `photo:…`, `video:…`, a document's uuid.    let id: String    let position: Int    /// The note's own words about it, when somebody wrote some — the OVERRIDE    /// this note put on the picture, never the record's own.    let caption: String?    /// The record's OWN caption, when it carries one. A photograph captioned in    /// the library says the same thing on every note that files it, and a note    /// that wrote its own words about it says those instead. Absent on a record    /// nobody captioned, which is why the tile falls through to `title`.    let recordCaption: String?    /// What the record calls itself — a document's title.    let title: String?    /// The object key `read.mediaPath` answers about: a photo's own key, a    /// video's POSTER key, and nothing at all for a document, whose bytes this    /// page never asks for.    let key: String?    /// The record behind it was removed. The reference stays and says so —    /// deleting the picture does not silently unwrite the note.    let missing: Bool    /// The picture's own pixel size, when the record carries one. The box is    /// fitted to it so a pin's fraction lands where the thumb was pressed.    let width: Int?    let height: Int?    /// `application/pdf`, `image/jpeg` — what a FILE tile says it is, under    /// either of the read's two spellings (`contentType` for a picture,    /// `mime` for a document). Nothing on this page draws it; the strip under    /// the sheet does, because a card with no picture has to say what it is.    let contentType: String?    /// What the file is, as the core says it from its type ("Web page",    /// "PDF") — a line of set `documents`, never a word in Swift.    let format: String?    init(        kind: String,        id: String,        position: Int,        caption: String? = nil,        recordCaption: String? = nil,        title: String? = nil,        key: String? = nil,        missing: Bool = false,        width: Int? = nil,        height: Int? = nil,        contentType: String? = nil,        format: String? = nil    ) {        self.kind = kind        self.id = id        self.position = position        self.caption = caption        self.recordCaption = recordCaption        self.title = title        self.key = key        self.missing = missing        self.width = width        self.height = height        self.contentType = contentType        self.format = format    }    /// One row of `attachments`, or nothing when it names no record.    init?(_ row: JSONValue) {        guard let kind = row.text("kind"), let id = row.text("id") else { return nil }        self.init(            kind: kind,            id: id,            position: row.number("position") ?? 0,            caption: row.text("caption"),            recordCaption: row.text("recordCaption"),            title: row.text("title"),            key: row.text("key"),            missing: row.flag("missing"),            width: row.number("width"),            height: row.number("height"),            contentType: row.text("contentType") ?? row.text("mime"),            format: row.text("format")        )    }    /// The `attachments` a record read answers, in the order they were filed.    ///    /// `position` is not unique by design — a reorder arrives as fragments and    /// two rows swapping would transiently collide — so the id settles a tie    /// rather than leaving two rows to swap places under a finger.    static func list(from record: JSONValue) -> [RecordAttachment] {        record.list("attachments")            .compactMap(RecordAttachment.init)            .sorted { ($0.position, $0.id) < ($1.position, $1.id) }    }    /// The pair an anchor names. Two kinds could mint the same id, so the key    /// a view is identified by is both halves.    var pinKey: String { "\(kind)/\(id)" }    /// There is a picture to draw, and it is here to be drawn.    var hasPicture: Bool { !missing && !(key ?? "").isEmpty }    /// What this attachment is CALLED, on a page and to VoiceOver: the    /// strip's one rule (`RecordAttachments.caption(of:in:)`).    func label(in definitions: TableDefinitions) -> String {        RecordAttachments.caption(of: self, in: definitions)    }}// ── a pin ───────────────────────────────────────────────────────────────────/// Where a comment is pinned: an attachment on this note, and a point on it.////// `{"attachment":{"kind","id"},"x","y"}` — the same object the crate/// validates and the share page draws from. A comment anchored to TEXT carries/// `quote` and no `attachment`, and is not a pin.struct PinAnchor: Equatable, Sendable {    let kind: String    let id: String    /// Fractions of the drawn picture, always inside 0…1.    let x: Double    let y: Double    init(kind: String, id: String, x: Double, y: Double) {        self.kind = kind        self.id = id        self.x = PinPlacement.clamped(x)        self.y = PinPlacement.clamped(y)    }    /// A comment's `anchor`, when it is a pin — and nothing when it is a text    /// anchor, an anchor half-written, or absent because the crate serving this    /// phone does not answer it yet.    init?(_ anchor: JSONValue?) {        guard            let anchor,            let attachment = anchor["attachment"],            let kind = attachment.text("kind"),            let id = attachment.text("id"),            let x = anchor.decimal("x"),            let y = anchor.decimal("y")        else { return nil }        self.init(kind: kind, id: id, x: x, y: y)    }    /// What `create_comment` is handed.    var json: JSONValue {        .object([            "attachment": .object(["kind": .string(kind), "id": .string(id)]),            "x": .number(x),            "y": .number(y),        ])    }    func isOn(_ attachment: RecordAttachment) -> Bool {        kind == attachment.kind && id == attachment.id    }}/// A pinned thread: the comment, the number it wears, and where it sits.struct RecordPin: Equatable, Sendable {    let commentId: String    let number: Int    let anchor: PinAnchor    /// Settled. The pin stays on the picture and steps back, so the numbering    /// keeps no gaps.    let resolved: Bool    /// The word beside a thread and under a marker.    var label: String { "Pin \(number)" }    /// `PinMarker`'s own row shape, said once for the note lane.    var marker: JSONValue {        .object([            "id": .string(commentId),            "pinNumber": .number(Double(number)),            "x": .number(anchor.x),            "y": .number(anchor.y),            "status": .string(resolved ? "resolved" : "open"),        ])    }}/// The numbering, in one place, because two surfaces say it.enum RecordPins {    /// Every pinned thread on the note, numbered in COMMENT ORDER.    ///    /// The order `read.record` answers the threads in — which is creation    /// order — so Pin 1 is the first pin ever left on this note and stays Pin 1    /// when an earlier one is settled. An unpinned comment takes no number:    /// numbering the whole conversation would put "Pin 4" on the picture beside    /// a page whose fourth comment is a sentence about the title.    static func all(_ threads: [JSONValue]) -> [RecordPin] {        var number = 0        return threads.compactMap { thread in            guard                let anchor = PinAnchor(thread["anchor"]),                let id = thread.text("id")            else { return nil }            number += 1            return RecordPin(                commentId: id,                number: number,                anchor: anchor,                resolved: thread.text("resolvedAt") != nil            )        }    }    /// The pin one thread IS, or nothing when it is an ordinary comment.    static func pin(of thread: JSONValue, in threads: [JSONValue]) -> RecordPin? {        guard let id = thread.text("id") else { return nil }        return all(threads).first { $0.commentId == id }    }    /// The markers to draw over one attachment.    static func markers(_ threads: [JSONValue], on attachment: RecordAttachment) -> [JSONValue] {        all(threads).filter { $0.anchor.isOn(attachment) }.map(\.marker)    }}