// 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.importCottonKitimportCottonValuesimportSwiftUIpublictypealiasTableViewer = DefinitionTableViewerpublictypealiasViewerWords = DefinitionViewerWords/// One thing the viewer can show.structViewerItem: Identifiable, Equatable, Sendable {enumKind: String, Equatable, Sendable { case photo, video, document }/// Unique within its set; the tile it opened from is matched by it.let id: Stringlet 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? = nilvar width: Int? = nilvar 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? = nilvar 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.staticfunc 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? {guardlet width, let height, width > 0, height > 0else { returnnil }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.structViewerRecord: Equatable, Hashable, Sendable {let table: Stringlet id: String}/// What a note's pictures carry: comments pinned on a picture are filed on/// this record.structViewerPins: Equatable, Sendable {let recordId: Stringlet recordKind: String}/// What an opener hands the viewer.structViewerSet: Identifiable, Equatable, Sendable {let id: Stringlet items: [ViewerItem]/// The place it opened on, clamped into the set.let start: Intvar pins: ViewerPins? = nilinit(id: String = UUID().uuidString, items: [ViewerItem], start: Int, pins: ViewerPins? = nil) {self.id = idself.items = itemsself.start = items.isEmpty ? 0 : min(max(0, start), items.count - 1)self.pins = pins }}// MARK: - From what each opener holdsextensionViewerItem {/// 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.idlet ref = ViewerRecord(table: Self.recordTable(table, record), id: record.id)let slip = definition.sliplet width = record["width"].number.map { Int($0) }let height = record["height"].number.map { Int($0) }iflet 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) } elseif 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) } elseiflet 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) } elseiflet 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 {returnnil } }/// The table a library row's record lives in: a film's or a picture's.privatestaticfunc 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 wordsextensionViewerWords {/// The viewer's lines: the media table's `viewer.words` in the shown/// database; none where no tool draws media there.staticfunc 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 { returnnil }returnSelf.fill(position, index + 1, count) }func page(_ index: Int, of count: Int) -> String { Self.fill(page, index + 1, count) }staticfunc fill(_ line: String, _ n: Int, _ count: Int) -> String { line.replacingOccurrences(of: "{n}", with: "\(n)").replacingOccurrences(of: "{count}", with: "\(count)") }}// MARK: - A conversation's mediaextensionMessageMedia {/// A message's media column, as its entries.staticfunc entries(of value: RecordValue) -> [MessageMedia] {guardlet bytes = try? JSONEncoder().encode(value),let json = try? JSONDecoder().decode(JSONValue.self, from: bytes),case .array(let rows) = jsonelse { 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.structViewerThread: Sendable {structMessage: Sendable {let id: Stringlet 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 }staticfunc 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.staticfunc set(of messages: [Message], opening id: String) -> ViewerSet? {var items: [ViewerItem] = []for message in messages {for (index, entry) inMessageMedia.entries(of: message.media).enumerated() where entry.isImage || entry.isVideo {var item = ViewerItem(message: entry, id: itemID(message.id, index)) item.caption = message.wordsiflet table = message.table { item.record = ViewerRecord(table: table, id: message.id) } items.append(item) } }guardlet start = items.firstIndex(where: { $0.id == id }) else { returnnil }returnViewerSet(items: items, start: start) }}privatestructViewerThreadKey: EnvironmentKey {staticlet defaultValue: ViewerThread? = nil}extensionEnvironmentValues {var viewerThread: ViewerThread? { get { self[ViewerThreadKey.self] } set { self[ViewerThreadKey.self] = newValue } }}