279 lines · 11.6 KB · SwiftRaw
import AVFoundationimport CottonKitimport CottonValuesimport SwiftUI/// Any conversation's media, under the note it came with: a picture or a film/// as a print that opens the shared gallery, a voice note as a small note on/// its sender's paper that plays through the page's one player, and a file as/// its file column.struct ConversationMedia: View { @Environment(\.theme) private var theme let value: RecordValue let seed: String /// Whose message it is: the owner's media sits at the right. var mine = false /// The paper its sender's notes are written on, for a voice note. var dye: PaperDye = .cream @Environment(\.viewerPresenter) private var viewer @Environment(\.viewerThread) private var thread @Environment(\.conversationVoicePlayer) private var sharedVoice @State private var ownVoice = VoiceNotePlayer() private var voice: VoiceNotePlayer { sharedVoice ?? ownVoice } private static var printWidth: CGFloat { 176 } private var entries: [MessageMedia] { MessageMedia.entries(of: value) } var body: some View { VStack(alignment: mine ? .trailing : .leading, spacing: 8) { ForEach(Array(entries.enumerated()), id: \.offset) { index, entry in if entry.kind == "contact" { // A shared contact: a card with the person's name, on its // sender's paper — never the words "Contact · name". Paper(dye: dye, edge: .cut, seed: "\(seed)-contact-\(index)", inset: 12) { HStack(spacing: 10) { Image(systemName: "person.crop.square") .font(theme.type.interface(22)) .foregroundStyle(theme.print(.pencil)) VStack(alignment: .leading, spacing: 2) { Text((entry.name?.isEmpty == false ? entry.name : nil) ?? ShellLines.line("conversation", "media.a_contact")) .paperBody(15).lineLimit(1) Text(ShellLines.line("conversation", "media.contact")).paperMeta(12) } } .frame(maxWidth: 240, alignment: .leading) .fixedSize() } .fixedSize() .padding(.vertical, 4) .accessibilityElement(children: .combine) .accessibilityIdentifier("conversation-contact-\(seed)-\(index)") } else if entry.isImage || entry.isVideo { picture(entry, at: index) } else if entry.isAudio { voiceNote(entry, at: index) } else if let key = entry.key { // A file: its name on a small note of its sender's paper, then // the file itself (its pages, or the way to fetch it). VStack(alignment: mine ? .trailing : .leading, spacing: 6) { Paper(dye: dye, edge: .cut, seed: "\(seed)-file-\(index)", inset: 12) { HStack(spacing: 8) { Image(systemName: "doc") .font(theme.type.interface(14)) .foregroundStyle(theme.print(.pencil)) Text(entry.name ?? ShellLines.line("conversation", "media.file")).paperBody(15).lineLimit(1).truncationMode(.middle) } .frame(maxWidth: 240) .fixedSize() } .fixedSize() FileColumnContent( value: .object(["ref": .text(key), "name": .text(entry.name ?? ShellLines.line("conversation", "media.file"))]), seed: seed) } .padding(.vertical, 4) } else if let address = entry.url, let url = URL(string: address), ["https", "http"].contains(url.scheme ?? "") { Link(entry.name ?? ShellLines.line("conversation", "media.attachment"), destination: url).paperHand(15) } } } .onDisappear { if sharedVoice == nil { ownVoice.stop() } } } /// Opens the viewer on this picture: over the thread's pictures and films /// when the page hands them down, else over this message's own. private func open(at index: Int) { let id = ViewerThread.itemID(seed, index) let set = thread?.set(opening: id) ?? ViewerThread.set(of: [ViewerThread.Message(id: seed, media: value, words: nil)], opening: id) if let set { viewer?.open(set) } } /// A picture or a film as a print in its own shape; a film's length is /// written in its margin beside a play mark. A tap opens the gallery. private func picture(_ entry: MessageMedia, at index: Int) -> some View { let length = entry.isVideo ? entry.durationMs.map(ChatMessagePreview.duration(ms:)) : nil return VStack(alignment: mine ? .trailing : .leading, spacing: 4) { Button { open(at: index) } label: { if entry.isVideo { InstantPrint( seed: "\(seed)-\(index)", caption: length ?? ShellLines.line("record", "conversation.video"), captionGlyph: "play.fill", photoAspect: Self.aspect(of: entry) ) { KeyedPicture(key: entry.key, edge: Self.printWidth) }.frame(width: Self.printWidth) } else { ConversationPicture(entry: entry, seed: "\(seed)-\(index)", width: Self.printWidth) } } .buttonStyle(OpacityButtonStyle()) .accessibilityLabel(entry.isVideo ? length.map { ShellLines.line("conversation", "media.video_length", ["length": $0]) } ?? ShellLines.line("conversation", "media.video") : ShellLines.line("conversation", "media.photo")) .accessibilityIdentifier("conversation-picture-\(seed)-\(index)") .viewerSource(ViewerThread.itemID(seed, index)) } .padding(.vertical, 4) } private func voiceNote(_ entry: MessageMedia, at index: Int) -> some View { ConversationVoiceNote( entry: entry, seed: "\(seed)-voice-\(index)", identifier: "conversation-voice-\(seed)-\(index)", mine: mine, dye: dye, voice: voice) } /// The print's shape: the picture's own where the sender measured it, else /// the print's. static func aspect(of entry: MessageMedia) -> CGFloat? { guard let width = entry.width, let height = entry.height, width > 0, height > 0 else { return nil } return CGFloat(width) / CGFloat(height) }}/// The local thumbnail is the message. While its bytes are looked for the/// print stands empty at its own shape (no jump when they land); when they are/// not on this phone the slip says so (never a bare "Photo"). Tapping any/// state opens the same viewer, which fetches.private struct ConversationPicture: View { let entry: MessageMedia let seed: String let width: CGFloat @State private var slot = MediaImageSlot() @Environment(\.tableDefinitions) private var definitions var body: some View { Group { if slot.isAbsent { AbsentSlip(kind: .photo, name: entry.name, words: ViewerWords.reading(definitions), compact: true) .frame(width: width) } else { InstantPrint( seed: seed, photoAspect: ConversationMedia.aspect(of: entry) ) { if let image = slot.image { Image(uiImage: image).resizable().scaledToFill() } else { Color.clear } } .frame(width: width) } } .mediaSlot($slot, key: entry.key, edge: width) }}/// Availability is local. A tap on a missing rendition fetches it; an Ogg/// original whose rendition is not made yet remains a voice-message label.private struct ConversationVoiceNote: View { @Environment(\.theme) private var theme let entry: MessageMedia let seed: String let identifier: String let mine: Bool let dye: PaperDye let voice: VoiceNotePlayer @Environment(\.cottonCore) private var core @State private var localKey: String? @State private var measuredMs: Int? @State private var askedKey: String? private var key: String? { entry.audioPlaybackKey } private var available: Bool { key != nil && localKey == key } private var playing: Bool { key != nil && voice.playingKey == key } private var length: String? { (entry.durationMs ?? measuredMs).map(ChatMessagePreview.duration(ms:)) } var body: some View { VStack(alignment: mine ? .trailing : .leading, spacing: 4) { if let key { Button { guard let core else { return } Task { await voice.toggle(key, media: PhotosMediaSource(core: core)) await resolve() } } label: { content } .buttonStyle(OpacityButtonStyle()) .disabled(voice.loadingKey == key) .accessibilityLabel(voiceMessageLabel(available: available, playing: playing, length: length)) .accessibilityIdentifier(identifier) } else { content.accessibilityIdentifier(identifier) } if key == nil { Text(ShellLines.line("conversation", "voice.cannot_play")).paperHand(14) } else if let key, voice.unavailableKey == key, !available { Text(ShellLines.line("conversation", "voice.not_fetched")).paperHand(14) } else if let key, voice.unplayableKey == key { Text(ShellLines.line("conversation", "voice.not_played")).paperHand(14) } } .padding(.vertical, 4) .task(id: key) { askedKey = key localKey = nil measuredMs = nil await resolve() } .onMediaArrival { if !available { await resolve() } } } @ViewBuilder private var content: some View { if available { Paper(dye: dye, edge: .cut, seed: seed, inset: 12) { HStack(spacing: 10) { Image(systemName: playing ? "pause.fill" : "play.fill") .font(theme.type.interface(13, weight: .semibold)) .foregroundStyle(theme.colors.ink.color) .frame(width: 30, height: 30) .background(Circle().fill(NavChrome.circleFill)) if entry.waveform.isEmpty { Text(ShellLines.line("conversation", "voice.recording")).paperHand(15) } else { Waveform(samples: entry.waveform, barFraction: 0.45, theme: theme) .fill(playing ? theme.colors.ink.color : theme.print(.pencil)) .frame(width: 116, height: 24) } if let length { Text(length).paperMeta(12).fixedSize() } }.fixedSize() }.fixedSize() } else { HStack(spacing: 8) { Text(ShellLines.line("conversation", "voice.message")).paperHand(15) if let length { Text(length).paperMeta(12) } }.padding(.vertical, 8) } } private func resolve() async { guard let key, let core else { return } let path = await PhotosMediaSource(core: core).path(for: key) guard askedKey == key, !Task.isCancelled else { return } guard let path else { localKey = nil; return } localKey = key if entry.durationMs == nil { let asset = AVURLAsset(url: URL(fileURLWithPath: path)) if let duration = try? await asset.load(.duration), duration.seconds.isFinite, duration.seconds >= 0, askedKey == key, !Task.isCancelled { measuredMs = Int(min(duration.seconds * 1000, Double(Int32.max))) } } }}extension EnvironmentValues { @Entry var conversationVoicePlayer: VoiceNotePlayer? = nil}/// What a voice message's button says: get, play or pause, with its length/// when known.private func voiceMessageLabel(available: Bool, playing: Bool, length: String?) -> String { let fills = ["length": length ?? ""] switch (available, playing, length == nil) { case (false, _, true): return ShellLines.line("conversation", "voice.get", fills) case (false, _, false): return ShellLines.line("conversation", "voice.get_length", fills) case (true, true, true): return ShellLines.line("conversation", "voice.pause", fills) case (true, true, false): return ShellLines.line("conversation", "voice.pause_length", fills) case (true, false, true): return ShellLines.line("conversation", "voice.play", fills) case (true, false, false): return ShellLines.line("conversation", "voice.play_length", fills) }}