Cotton code
236 lines · 10.1 KB · SwiftRaw
// What the one full-screen viewer shows: a set of pictures, films and// documents, and the one it opened on.//// Every opener — a bubble in a chat, a tile in Photos or Videos, a row in// Documents, an attachment on a note, a person's photo — turns what it holds// into these, so the viewer never learns where it was opened from. A set is// what a swipe walks through: the thread's media, the month, the album, the// person's photos.import CottonKitimport CottonValuesimport SwiftUIpublic typealias TableViewer = DefinitionTableViewerpublic typealias ViewerWords = DefinitionViewerWords/// One thing the viewer can show.struct ViewerItem: Identifiable, Equatable, Sendable {    enum Kind: String, Equatable, Sendable { case photo, video, document }    /// Unique within its set; the tile it opened from is matched by it.    let id: String    let kind: Kind    /// The object key `read.mediaPath` answers about: a picture's own bytes,    /// a film's file, a document's file.    let key: String?    /// A film's poster, drawn until the first frame plays.    var poster: String? = nil    /// The 32 px blur a chat row carries, drawn while the bytes resolve.    var preview: String? = nil    var width: Int? = nil    var height: Int? = nil    /// What it is called — a document's title, a file's name.    var title: String? = nil    /// The words it was sent with — a chat photo's message — shown at the    /// bottom while it is on screen, until the first tap.    var caption: String? = nil    var contentType: String? = nil    /// The record behind it, when there is one: what Details raises.    var record: ViewerRecord? = nil    /// A picture column on a record's page, by the page's table, record and column.    static func pageID(_ table: String, _ record: String, _ column: String) -> String { "page/\(table)/\(record)/\(column)" }    /// The record behind it was removed; the viewer says so.    var missing = false    /// A film shown as a GIF: no sound, plays round.    var loops = false    /// The picture's own shape, when it is known.    var aspect: CGFloat? {        guard let width, let height, width > 0, height > 0 else { return nil }        return CGFloat(width) / CGFloat(height)    }    /// The bytes to show are named: anything else is the absent page.    var hasBytes: Bool { !missing && !(key ?? "").isEmpty }}/// The record an item stands for: its table and id.struct ViewerRecord: Equatable, Hashable, Sendable {    let table: String    let id: String}/// What a note's pictures carry: comments pinned on a picture are filed on/// this record.struct ViewerPins: Equatable, Sendable {    let recordId: String    let recordKind: String}/// What an opener hands the viewer.struct ViewerSet: Identifiable, Equatable, Sendable {    let id: String    let items: [ViewerItem]    /// The place it opened on, clamped into the set.    let start: Int    var pins: ViewerPins? = nil    init(id: String = UUID().uuidString, items: [ViewerItem], start: Int, pins: ViewerPins? = nil) {        self.id = id        self.items = items        self.start = items.isEmpty ? 0 : min(max(0, start), items.count - 1)        self.pins = pins    }}// MARK: - From what each opener holdsextension ViewerItem {    /// A record of a table that opens in the viewer (`viewer` on its    /// definition): what it is follows from the definition — a slip with a    /// `player` is a film, a table whose `kind` column says `video` is a    /// library row of a film, a table with a file column and no picture is a    /// document, anything else a picture. A film's or an episode's record is    /// a film even with no file yet (converting on the Mac): what plays is    /// the core's to say, and its refusal is said.    init?(record: TableRecord, definition: TableDefinition) {        let table = definition.id        let ref = ViewerRecord(table: Self.recordTable(table, record), id: record.id)        let slip = definition.slip        let width = record["width"].number.map { Int($0) }        let height = record["height"].number.map { Int($0) }        if let player = slip.player, record[player].text != nil || FilmPlayer.tables.contains(table) {            self.init(id: "\(table)/\(record.id)", kind: .video, key: record[player].text,                      poster: slip.photo.flatMap { record[$0].text }, width: width, height: height,                      title: record.said?.slip.title, record: ref)        } else if record["kind"].text == "video" {            // A library row of a film: its own file is the video record's,            // read when the page opens; the row's key is the poster.            self.init(id: "\(table)/\(record.id)", kind: .video, key: nil,                      poster: slip.photo.flatMap { record[$0].text }, width: width, height: height, record: ref)        } else if let photo = slip.photo, let key = record[photo].text {            self.init(id: "\(table)/\(record.id)", kind: .photo, key: key, width: width, height: height,                      title: record.said?.slip.title, record: ref)        } else if let file = definition.columns.first(where: { $0.type == .file }), let ref_ = AttachmentValue.read(record[file.key])?.ref ?? record[file.key].text {            self.init(id: "\(table)/\(record.id)", kind: .document, key: ref_,                      title: record.said?.slip.title ?? record["original_name"].text,                      contentType: record["mime"].text ?? record["content_type"].text, record: ref)        } else {            return nil        }    }    /// The table a library row's record lives in: a film's or a picture's.    private static func recordTable(_ table: String, _ record: TableRecord) -> String {        guard table == "media" else { return table }        return record["kind"].text == "video" ? "video" : "photo"    }    /// One attachment of a chat message.    init(message entry: MessageMedia, id: String) {        let kind: Kind = entry.isVideo ? .video : (entry.isImage ? .photo : .document)        self.init(            id: id, kind: kind, key: entry.key, preview: entry.preview,            width: entry.width, height: entry.height, title: entry.name, contentType: entry.contentType,            loops: entry.kind == "gif" || entry.contentType.lowercased() == "image/gif" && entry.isVideo)    }    /// One attachment of a record (a note's, a thought's).    init(attachment: RecordAttachment, label: String) {        let kind: Kind = attachment.kind == "video" ? .video : (attachment.kind == "document" ? .document : .photo)        self.init(            id: attachment.pinKey, kind: kind,            // A film's attachment names its poster; its file is read from            // the record when it plays.            key: kind == .video ? nil : attachment.key,            poster: kind == .video ? attachment.key : nil,            width: attachment.width, height: attachment.height, title: label,            contentType: attachment.contentType,            record: ViewerRecord(table: attachment.kind, id: attachment.id), missing: attachment.missing)    }}// MARK: - The wordsextension ViewerWords {    /// The viewer's lines: the media table's `viewer.words` in the shown    /// database; none where no tool draws media there.    static func reading(_ definitions: TableDefinitions) -> ViewerWords? {        definitions["media"]?.viewer?.words    }    /// "{n} of {count}" filled.    func position(_ index: Int, of count: Int) -> String? {        guard count > 1, index >= 0, index < count else { return nil }        return Self.fill(position, index + 1, count)    }    func page(_ index: Int, of count: Int) -> String { Self.fill(page, index + 1, count) }    static func fill(_ line: String, _ n: Int, _ count: Int) -> String {        line.replacingOccurrences(of: "{n}", with: "\(n)").replacingOccurrences(of: "{count}", with: "\(count)")    }}// MARK: - A conversation's mediaextension MessageMedia {    /// A message's media column, as its entries.    static func entries(of value: RecordValue) -> [MessageMedia] {        guard let bytes = try? JSONEncoder().encode(value),              let json = try? JSONDecoder().decode(JSONValue.self, from: bytes),              case .array(let rows) = json        else { return [] }        return rows.map(MessageMedia.init)    }}/// A conversation's pictures and films, read on a tap: what a picture opened/// in a thread swipes through.struct ViewerThread: Sendable {    struct Message: Sendable {        let id: String        let media: RecordValue        /// The message's words — the caption a photo opened from it shows.        let words: String?        /// The messages' table: a picture's Details raise its message.        var table: String? = nil    }    let messages: @Sendable @MainActor () -> [Message]    init(_ messages: @escaping @Sendable @MainActor () -> [Message]) { self.messages = messages }    static func itemID(_ message: String, _ index: Int) -> String { "message/\(message)/\(index)" }    @MainActor func set(opening id: String) -> ViewerSet? { Self.set(of: messages(), opening: id) }    /// Every picture and film of `messages` in order, opened on `id`, each    /// captioned with its own message's words. Nil when `id` is not among them.    static func set(of messages: [Message], opening id: String) -> ViewerSet? {        var items: [ViewerItem] = []        for message in messages {            for (index, entry) in MessageMedia.entries(of: message.media).enumerated() where entry.isImage || entry.isVideo {                var item = ViewerItem(message: entry, id: itemID(message.id, index))                item.caption = message.words                if let table = message.table { item.record = ViewerRecord(table: table, id: message.id) }                items.append(item)            }        }        guard let start = items.firstIndex(where: { $0.id == id }) else { return nil }        return ViewerSet(items: items, start: start)    }}private struct ViewerThreadKey: EnvironmentKey {    static let defaultValue: ViewerThread? = nil}extension EnvironmentValues {    var viewerThread: ViewerThread? {        get { self[ViewerThreadKey.self] }        set { self[ViewerThreadKey.self] = newValue }    }}