// The "conversation" page style: a thread-shaped record drawn as the chat the // session and message screens draw — its title, then its messages as notes, // the owner's on blue at the right and the others' on cream at the left, a // long one a page-wide letter, the time and any status word ("withdrawn") // handwritten under each, and "ended" in pencil down the middle once the // thread's `ended` column holds a day. The one input with the microphone and // the send (`ChatComposerBar`) stands at the page's foot; the Page surface // mounts it (`ConversationRoute`, `ConversationComposer`). // // The thread's own columns are its card on the deck; this is its inside. // // What the definition's `conversation` names besides, each drawn only when it // is named: the `header` columns in pencil under the title (what the thread // is doing now) — a long text among them drawn whole, as Markdown, so a pull // request's description stands at the top as its old page drew it — the `started` line first in the thread, the `also` tables' // records merged into it (`ConversationModel.items`), a `footer` column the // store writes in place of the status word, `media` drawn as prints above the // words, and the input's `placeholder`. // // And what an imported chat names: a day's line between days, a `system` // message as a pencilled line (a deleted message and one the export left out // are answered as system lines: nobody wrote them), the `header_columns` // envelope above a note, the `header` message columns — who said it — inside // the note's own lane, close above its paper, on the first note of a run, the // sender's `photo` beside that note in a group (a photo or typed initials), `color_by` // dyeing a group's notes, its `media` entries (a picture or a film as a print, // a voice note as a note that plays, files) under the note, the `footer` // message columns and the time after the media, "Message details" behind a // long press on the message, the latest page first with "Load older messages", // "Browse photos and files" once a message holds some, and no input where // `can_send` is false. A note's words are read as Markdown where the body // column says `markdown` (`ConversationWords`); otherwise as written. A `header` or `footer` names the thread's // columns or the message's, and each is read from the record that holds it. // // Mail is paper where the layout `folds` (an email thread): every message a // page-wide sheet, the newest open under its envelope, each older one folded // to its one line — when, who, its first words — that opens on a tap; no // day lines, as each sheet says its own day. // // Drawn once for every table whose definition names the `messages` part in // `page_parts` and a `conversation` layout; never per table. import CottonFaces import CottonKit import CottonValues import SwiftUI struct ConversationPage: View { @Environment(\.headRowTrailing) private var headRowTrailing @Environment(\.theme) private var theme let definition: TableDefinition let record: TableRecord let model: ConversationModel /// The thread narrowed to its photos and files (browsing, not reading). var mediaOnly = false var showsTitle = true /// Whether the thread says its own archive line at its end: off where the /// page's foot says it in the composer's place (`ChatStream`). var saysArchive = true @Environment(\.tableDefinitions) private var definitions @Environment(ToastCenter.self) private var toasts /// The messages whose envelope is open. @State private var openEnvelopes: Set = [] /// The older mail opened from its folded line (`folds`). @State private var unfolded: Set = [] @State private var voice = VoiceNotePlayer() /// The message whose own page a long press asked for. @State private var detailed: TableRecord? @Environment(\.actLift) private var lift @Environment(\.cottonHaptics) private var haptics @Environment(\.openURL) private var openURL @Environment(PendingTaps.self) private var pendingTaps: PendingTaps? @State private var frames = MessageFrames() /// Cotton chat's engine, in an app that carries one. @Environment(\.cottonChat) private var chat private var layout: ConversationLayout { model.layout } /// The message table's definition, for its status column's words. private var messages: TableDefinition? { definitions[layout.table] } var body: some View { VStack(alignment: .leading, spacing: 0) { conversationHead thread } .environment(\.conversationVoicePlayer, voice) // A hold lifts the message with its acts (Copy among them): the hold // is the lift's, never the system's selection. .environment(\.conversationWordsSelectable, false) // A picture opened here swipes through the thread's pictures and // films, oldest first — read when it is tapped, never per frame. .environment(\.viewerThread, ViewerThread { [messages = model.messages, layout, table = layout.table] in guard let column = layout.media else { return [] } return messages.map { ViewerThread.Message(id: $0.id, media: $0[column], words: $0[layout.body].text, table: table) } }) .onDisappear { voice.stop() } // "Message details": the message on its card, in the deck of this // thread's messages. .pageDestination(item: $detailed) { message in if let messages { RecordOpening(definition: messages, opens: .record(message.id, message), within: layout.links.first.map { [$0: RecordValue.text(record.id)] } ?? [:]) .cottonScreenFrame() } } } /// A conversation's own head: its title and the header lines. @ViewBuilder private var conversationHead: some View { if showsTitle { title } ForEach(Array(layout.headerPieces(of: record, in: definition).enumerated()), id: \.offset) { index, piece in switch piece { case .line(let line): Text(line) .paperHand(15) .fixedSize(horizontal: false, vertical: true) .padding(.top, 2) .accessibilityIdentifier("page-\(definition.id)-header-\(index)") case .markdown(let text): let blocks = MarkdownBlocks.parse(text) VStack(alignment: .leading, spacing: 0) { ForEach(Array(blocks.enumerated()), id: \.offset) { at, block in MarkdownBlockView(block: block, voice: .page) .padding(.top, MarkdownBlocks.gap(before: block, first: at == 0)) } } .textSelection(.enabled) .frame(maxWidth: .infinity, alignment: .leading) .padding(.vertical, 6) .accessibilityIdentifier("page-\(definition.id)-header-\(index)") } } } private var title: some View { // The head row's first line, short of its circles (fan3 part 10). Text(record.said?.slip.name ?? definition.name) .paperTitle(theme.scale[.headRecordTitleSize]) .lineLimit(Int(PaperTitleLinesKnobs.pageTitleLines)) .multilineTextAlignment(.leading) .padding(.trailing, headRowTrailing) .accessibilityAddTraits(.isHeader) .accessibilityIdentifier("page-\(definition.id)-heading") } @ViewBuilder private var thread: some View { switch model.phase { case .loading: // No loader: the messages are the phone's own and land next frame. EmptyView() case .failed: QuietState( title: ShellLines.line("conversation", "unreadable"), message: ShellLines.line("empty", "unchanged"), actionLabel: ShellLines.line("record", "try_again"), action: { Task { await model.load() } }) case .loaded: let assigned = ChatPaper.groupDyes(model.messages.map { $0[layout.colorBy].text }) if let started = layout.startedLine(of: record) { ConversationLine(text: started) } if model.items.isEmpty { Text(ShellLines.line("empty", "conversation")) .paperHand(16) .frame(maxWidth: .infinity, alignment: .center) .padding(.vertical, 24) } if model.hasMore { Button(ShellLines.line("conversation", "load_older")) { Task { await model.loadMore() } } .buttonStyle(.plain).paperHand(16) } ForEach(Array(model.items.enumerated()), id: \.element.id) { index, item in Group { if item.isMessage { message(item, index: index, assigned: assigned) } else if !mediaOnly { if item.slip, let table = definitions[item.table] { ConversationSlip( key: item.id, definition: table, record: item.record, footer: layout.footer(of: item, messages: messages)) } else if !item.slip || !item.words.isEmpty { // A slip whose table this app has no definition for is // drawn as a note only if it has words; never an empty bubble. ConversationNote( key: item.id, words: item.words, mine: item.mine, footer: layout.footer(of: item, messages: messages), media: item.media, markdown: layout.also.first { $0.table == item.table } .flatMap { source in source.body.flatMap { definitions[item.table]?.column($0) } }? .markdown == true) } } } // A message keeps its own id, the one the page scrolls to. .id(item.isMessage ? item.record.id : item.id) } if saysArchive, !layout.sendGate.allows(record) { ConversationLine(text: ShellLines.line("conversation", "archive")) } if let ended = layout.endedLine(of: record) { ConversationLine(text: ended) } // The newest message sent from here, read back as its receipt // under the thread — above the input, never over it. if let change = model.lastChange { ChangeReceipt( change: change, table: messages, undone: model.lastChangeUndone, onUndone: { _ in Task { await model.undone(change) } }, onDismiss: { model.dismissChange() }) .id(change.id) .padding(.top, 12) .accessibilityIdentifier("page-\(definition.id)-receipt") } } } /// A message's row: the sender's picture lane beside its envelope, note /// and media — as the thread draws it, and as it lifts. @ViewBuilder private func bubble(_ item: ConversationItem, index: Int, opens: Bool, headed: String?, dye: PaperDye, isGroup: Bool, assigned: [String: PaperDye]) -> some View { let message = item.record HStack(alignment: .top, spacing: 8) { // A group's lane for its senders' pictures: the photo // beside the first note of a run, the lane kept under it. // Typed initials on the slip’s stock when the sender has no picture. if photoLane, !item.mine { Group { if opens { if let key = layout.photoKey(of: message), !key.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { InstantPrint(seed: key, size: .thumb, tilts: false) { KeyedPicture(key: key, edge: Self.faceLane) } } else if let name = layout.writer(of: message) { InitialsMount(name: name, typed: true) .frame(width: Self.faceLane, height: Self.faceLane) } } } .frame(width: Self.faceLane, alignment: .top) .padding(.top, headed == nil ? 0 : 18) .accessibilityHidden(true) } VStack(alignment: item.mine ? .trailing : .leading, spacing: 4) { // An envelope is one line — who and when; the address, // the recipients and the rest open under it on a tap. // Browsing the media shows the media alone: each print or // file, then who sent it and when — never the words again. let browsing = mediaOnly let envelope = layout.folds ? layout.envelopeHead(of: message, messages: messages, day: true) : layout.envelopeHead(of: message, messages: messages) if let envelope, !browsing { let lines = layout.envelopeLines( of: message, messages: messages, threadTitle: record.said?.slip.name) Button { if !openEnvelopes.insert(message.id).inserted { openEnvelopes.remove(message.id) } } label: { HStack(spacing: 4) { Text(envelope).paperBody(12, ink: .pencil) .frame(minHeight: 28) if !lines.isEmpty { Image(systemName: openEnvelopes.contains(message.id) ? "chevron.up" : "chevron.down") .font(theme.type.interface(9, weight: .semibold)) .foregroundStyle(theme.print(.pencil)) } } } .contentShape(Rectangle()) .buttonStyle(OpacityButtonStyle()) .disabled(lines.isEmpty) .accessibilityIdentifier("conversation-envelope-\(message.id)") if openEnvelopes.contains(message.id) { ForEach(lines, id: \.self) { line in Text(line).paperBody(12, ink: .pencil) .fixedSize(horizontal: false, vertical: true) } } } // A Cotton message that answers another says which, in pencil above it. if CottonChatRows.isCotton(message: message), !browsing, let replied = message["reply_to_id"].text, let quoted = model.messages.first(where: { $0.id == replied }) { Text("\u{21A9} " + CottonChatComposer.firstWords(of: quoted, body: layout.body)) .paperBody(12, ink: .pencil).lineLimit(1) .padding(.horizontal, 4) .accessibilityIdentifier("conversation-reply-\(message.id)") } // A message with no words has none to put on paper: its // name, the media if any, then its time. let wordless = item.words.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty let media = hasMedia(message) // The envelope's line already said the time. let delivery = MessageDelivery(message) let footer = layout.footer(of: item, messages: messages, time: envelope == nil) if browsing { EmptyView() } else if wordless { if let headed { Text(headed).paperMeta(12).padding(.horizontal, 4) } } else { // The time comes after the media, when there is some. ConversationNote( key: message.id, words: item.words, mine: item.mine, footer: Self.timeStandsAlone(wordless: wordless, media: media) ? nil : footer, media: item.media, sender: message[layout.colorBy].text, isGroup: isGroup, assigned: assigned, topGap: 0, name: headed, markdown: messages?.column(layout.body)?.markdown == true, sheet: layout.folds) } if let mediaColumn = layout.media, media { ConversationMedia(value: message[mediaColumn], seed: message.id, mine: item.mine, dye: dye) if browsing { // Who and when, under what they sent. let who = [envelope ?? layout.metadata(layout.header, of: message, messages: messages), envelope == nil ? footer : nil] .compactMap { $0 }.joined(separator: " \u{00B7} ") if !who.isEmpty { Text(who).paperHand(14).padding(.horizontal, 4) } } } if !browsing, Self.timeStandsAlone(wordless: wordless, media: media), let footer { Text(footer).paperHand(14).padding(.horizontal, 4) } if chat != nil, CottonChatRows.isCotton(message: message), !browsing, let send = SendRow.item(of: message) { // A send: the real card, and what the core says of it (`SendCard`). SendCard(item: send) } else if let chat, CottonChatRows.isCotton(message: message), !browsing { let pictures = CottonPictures.count(of: message) if pictures > 0 { CottonPictures(message: message.id, count: pictures, chat: chat, width: 220) } if let cotton = CottonDelivery(message) { Text(cotton.words).paperHand(14, ink: cotton.failed ? .red : .ink) .fixedSize(horizontal: false, vertical: true) .accessibilityIdentifier("conversation-send-\(message.id)") if cotton.failed, record.said?.readOnly != true { Button(ShellLines.line("conversation", "retry")) { retryCotton(message, chat) } .buttonStyle(.plain).paperHand(14, ink: .red) .fixedSize() .accessibilityIdentifier("conversation-retry-\(message.id)") } } } if let delivery { switch delivery { case .queued, .sending, .sent, .delivered, .seen: Text(delivery.words).paperHand(14, ink: .ink) .accessibilityIdentifier("conversation-send-\(message.id)") case .failed: VStack(alignment: .leading, spacing: 8) { Text(delivery.words).paperHand(14, ink: .red) .fixedSize(horizontal: false, vertical: true) .accessibilityIdentifier("conversation-send-\(message.id)") if mayActOnFailure(message) { Button(ShellLines.line("conversation", "retry")) { retry(message) } .buttonStyle(.plain).paperHand(14, ink: .red) .fixedSize() .disabled(model.retrying.contains(message.id) || model.binning.contains(message.id)) .accessibilityIdentifier("conversation-retry-\(message.id)") } } } } } .frame(maxWidth: .infinity, alignment: item.mine ? .trailing : .leading) } } /// One message: its day's line when it opens a day, then a system line, /// or its envelope and header above its note, its media under it and /// "Message details". While browsing media, only a message holding some. @ViewBuilder private func message(_ item: ConversationItem, index: Int, assigned: [String: PaperDye]) -> some View { let message = item.record if !mediaOnly || hasMedia(message) { if layout.folds, !mediaOnly, folded(item) { foldedLine(item) } else { // Mail's sheets each say their own day: no day lines between them. if startsDay(index), !layout.folds { ConversationLine(text: item.day?.heading ?? "") } if let system = layout.system, message[system].bool == true { ConversationLine(text: message[layout.body].text ?? "") } else { let opens = opensRun(index) let headed = heading(index) let isGroup = record["kind"].text == "group" let dye = ChatPaper.dye( mine: item.mine, sender: message[layout.colorBy].text, isGroup: isGroup, assigned: assigned) bubble(item, index: index, opens: opens, headed: headed, dye: dye, isGroup: isGroup, assigned: assigned) .padding(.top, opens ? 14 : 6) // Lifted, the message is drawn over its own place, which keeps its room. .opacity(lift?.lifted?.id == Self.lifted(message) ? 0 : 1) .onGeometryChange(for: CGRect.self) { $0.frame(in: .global) } action: { frames.frames[message.id] = $0 } .contentShape(Rectangle()) .onTapGesture { switch ConversationTap.of(failed: mayActOnFailure(message), body: message[layout.body].text) { case .failure: hold(item, index: index, opens: opens, headed: headed, dye: dye, isGroup: isGroup, assigned: assigned) case .open(let link): open(link) case .nothing: return } } .onLongPressGesture { hold(item, index: index, opens: opens, headed: headed, dye: dye, isGroup: isGroup, assigned: assigned) } } } } } /// A message held: it lifts over the dimmed screen and its acts hang by /// it, as a held slip's do (slipacts rule 5) — never the system's menu. private func hold(_ item: ConversationItem, index: Int, opens: Bool, headed: String?, dye: PaperDye, isGroup: Bool, assigned: [String: PaperDye]) { guard let lift, let frame = frames.frames[item.record.id] else { return } let acts = acts(of: item.record) guard !acts.isEmpty else { return } haptics.press() lift.lift(Lifted(id: Self.lifted(item.record), frame: frame, face: AnyView(bubble(item, index: index, opens: opens, headed: headed, dye: dye, isGroup: isGroup, assigned: assigned).padding(.top, opens ? 14 : 6)), acts: acts)) } private static func lifted(_ message: TableRecord) -> String { "message/" + message.id } /// A held message's acts: Retry and Delete for one that failed to send, /// Copy for one with words, and its details. private func acts(of message: TableRecord) -> [LiftedAct] { var acts: [LiftedAct] = [] if let chat, CottonChatRows.isCotton(message: message), record.said?.readOnly != true { if CottonDelivery(message)?.failed == true { acts.append(LiftedAct(id: "message-retry", word: ShellLines.line("conversation", "retry"), object: .retry, destroys: false) { retryCotton(message, chat) }) } if !CottonChatRows.isRequest(thread: record) { acts.append(LiftedAct(id: "message-reply", word: ShellLines.line("chat", "reply"), object: .chat, destroys: false) { model.replyingTo = message }) } } if mayActOnFailure(message), !model.retrying.contains(message.id), !model.binning.contains(message.id) { acts.append(LiftedAct(id: "message-retry", word: ShellLines.line("conversation", "retry"), object: .retry, destroys: false) { retry(message) }) } if let words = message[layout.body].text, !words.isEmpty { acts.append(LiftedAct(id: "message-copy", word: ShellLines.line("faces", "page.copy"), object: .copy, destroys: false) { toasts.show(RecordActionOutcomes.copy(words), tone: .success) }) } if messages != nil { acts.append(LiftedAct(id: "message-details", word: ShellLines.line("record", "conversation.details"), object: .file, destroys: false) { detailed = message }) } if mayActOnFailure(message), !model.retrying.contains(message.id), !model.binning.contains(message.id) { acts.append(LiftedAct(id: "message-delete", word: ShellLines.line("conversation", "delete"), object: .bin, destroys: true) { binFailed(message) }) } return acts } /// Whether a message of folding mail is folded to its line: every one /// but the newest, until it is opened. private func folded(_ item: ConversationItem) -> Bool { model.items.last(where: { $0.isMessage })?.id != item.id && !unfolded.contains(item.record.id) } /// An older mail folded to one line on its paper: its day, who wrote it /// and its first words. A tap opens it. private func foldedLine(_ item: ConversationItem) -> some View { let message = item.record let day = item.day?.heading let who = layout.envelopeHead(of: message, messages: messages, time: false) // Its words run on across their lines, so a greeting alone is never the line. let first = item.words.split(whereSeparator: { $0.isWhitespace || $0.isNewline }).joined(separator: " ") return Button { unfolded.insert(message.id) } label: { Paper(dye: ChatPaper.dye(mine: item.mine, sender: nil, isGroup: false, assigned: [:]), edge: .cut, seed: message.id, inset: 12) { HStack(alignment: .firstTextBaseline, spacing: 8) { if let day { Text(day).paperHand(15).fixedSize() } Text([who, first].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: " \u{00B7} ")) .paperBody(13) .lineLimit(1) .truncationMode(.tail) .frame(maxWidth: .infinity, alignment: .leading) } .padding(12) } } .buttonStyle(OpacityButtonStyle()) .padding(.top, 8) .accessibilityIdentifier("conversation-fold-\(message.id)") } /// A link message's one act: its link opens where it points — in its /// database for Cotton's own addresses, else outside. private func open(_ link: URL) { if !RecordAddress.open(link, taps: pendingTaps, external: { openURL($0) }) { toasts.show(ShellLines.line("record", "address_failed"), tone: .error) } } private func mayActOnFailure(_ message: TableRecord) -> Bool { record.said?.readOnly != true && model.canRetryOrBin(message) } private func binFailed(_ message: TableRecord) { Task { do { _ = try await model.binFailed(message) } catch { toasts.show(CottonStrings.writeFailure(error), tone: .error) } } } /// A Cotton message that failed, tried again by the core's outbox. private func retryCotton(_ message: TableRecord, _ chat: any CottonChatting) { Task { do { try await chat.retry(message: message.id) await model.load() } catch { toasts.show(chatRefusal(error), tone: .error) } } } private func retry(_ message: TableRecord) { Task { do { _ = try await model.retry(message) } catch { toasts.show(CottonStrings.writeFailure(error), tone: .error) } } } private static var faceLane: CGFloat { 30 } /// Whether the thread keeps a lane for its senders' pictures: a group /// whose layout names a `photo` column. private var photoLane: Bool { layout.photo != nil && record["kind"].text == "group" } /// Whether the message at `index` opens a run: the first of its day, or /// the first by its writer after another's note or a system line. A /// run's first note carries who wrote it and their picture; the rest sit /// close under it. private func opensRun(_ index: Int) -> Bool { guard !startsDay(index), let before = model.items[.. String? { let message = model.items[index].record guard let words = layout.metadata(layout.header, of: message, messages: messages) else { return nil } guard !opensRun(index), let before = model.items[.. Bool { Self.hasMedia(message, layout: layout) } /// Whether a message's time stands on its own line under it rather than /// in its note: after its media, or under its name when it holds no /// words at all — a wordless message keeps its time, media or not. static func timeStandsAlone(wordless: Bool, media: Bool) -> Bool { wordless || media } static func hasMedia(_ message: TableRecord, layout: ConversationLayout) -> Bool { guard let media = layout.media else { return false } switch message[media] { case .list(let entries): return !entries.isEmpty case .null: return false default: return true } } /// Whether the message at `index` in the stream is the first of its day /// among the messages. private func startsDay(_ index: Int) -> Bool { guard let day = model.items[index].day?.day else { return false } let previous = model.items[.. Bool { blocks.allSatisfy { if case .line = $0 { return true } else { return false } } } /// The air above a block on a note: closer than a page's, a note is small. static func gap(before block: MarkdownBlock, first: Bool) -> CGFloat { if first { return 0 } switch block { case .line: return 6 case .item, .numbered: return 4 default: return 10 } } } /// A line handwritten in pencil down the middle of the conversation. struct ConversationLine: View { let text: String var body: some View { Text(text) .paperHand(15) .multilineTextAlignment(.center) .frame(maxWidth: .infinity, alignment: .center) .padding(.vertical, 12) } } /// One message on the paper the chat puts it on: the owner's on blue at the /// right, the others' on cream at the left, a long one a page-wide letter; /// the footer handwritten under the paper on its outer side. struct ConversationNote: View { let key: String let words: String let mine: Bool let footer: String? /// Media keys, drawn as instant prints above the words. var media: [String] = [] var sender: String? = nil var isGroup = false var assigned: [String: PaperDye] = [:] /// The air above the note; the page gives a run's own air instead. var topGap: CGFloat = 8 /// Who said it, written close above the paper on the note's own lane. var name: String? = nil /// Whether the words are read as Markdown (the body column says so). var markdown = false /// A page-wide sheet whatever its length: mail is paper (`folds`). var sheet = false private static var sideLane: CGFloat { 44 } private static var printWidth: CGFloat { 132 } private var isLetter: Bool { sheet || ChatPaper.isLetter(words) } var body: some View { HStack(alignment: .top, spacing: 0) { if mine && !isLetter { Spacer(minLength: Self.sideLane) } VStack(alignment: mine ? .trailing : .leading, spacing: 6) { if let name { Text(name) .paperMeta(12) .padding(.horizontal, 4) .padding(.bottom, -2) .accessibilityIdentifier("conversation-sender-\(key)") } if !media.isEmpty { prints } note if let footer { Text(footer) .paperHand(14) .padding(.horizontal, 4) } } if !mine && !isLetter { Spacer(minLength: Self.sideLane) } } .padding(.top, topGap) .accessibilityElement(children: .contain) .accessibilityIdentifier("conversation-note-\(key)") } private var note: some View { ChatSlip(seed: key, dye: ChatPaper.dye(mine: mine, sender: sender, isGroup: isGroup, assigned: assigned), letter: isLetter) { ConversationWords(words: words, isLetter: isLetter, markdown: markdown) } } /// The attachments as the session chat drew them: instant prints by /// media key (`SessionNote`'s). private var prints: some View { HStack(spacing: 8) { ForEach(media, id: \.self) { key in InstantPrint(seed: "\(self.key)-\(key)", size: .grid) { CapturedImage(key: key, title: ShellLines.line("conversation", "media.attachment"), width: Self.printWidth, height: Self.printWidth) } .frame(width: Self.printWidth) } } } } /// The conversation's one input at the page's foot: the chat composer, whose /// send writes the owner's message through the model; the page reads the /// change back as its receipt, with its undo, as every write is. struct ConversationComposer: View { @Environment(\.theme) private var theme let model: ConversationModel let identifier: String /// After a message lands: the page reads its record again, because what /// the thread's record says about itself (a question now answered, its /// state) can change with a send, and no sync may name it for a while. var recipient: String? = nil var onSent: () async -> Void = {} @Environment(ToastCenter.self) private var toasts @State private var draft = "" var body: some View { ChatComposerBar( draft: $draft, placeholder: model.layout.placeholder ?? recipient.map { ShellLines.line("conversation", "placeholder_to", ["name": $0]) } ?? ShellLines.line("conversation", "placeholder"), canSend: !draft.isBlank && !model.sending, identifier: identifier ) { let words = draft draft = "" Task { do { // Nil when a send was already on its way: the words go // back to the field rather than vanish. guard try await model.send(words) != nil else { if draft.isEmpty { draft = words } return } await onSent() } catch { // The words come back to the field rather than vanish, // and a store that refused in a sentence is heard in it. if draft.isEmpty { draft = words } toasts.show((error as? ActionRefused)?.sentence ?? ShellLines.line("conversation", "not_sent"), tone: .error) } } } // Its ideal height, not the inset's offer (the session chat's reason). .fixedSize(horizontal: false, vertical: true) .background(theme.colors.groundMuted.color) } } /// Whether a conversation's words can be selected — off where a hold raises the tray. private struct ConversationWordsSelectableKey: EnvironmentKey { static let defaultValue = true } extension EnvironmentValues { var conversationWordsSelectable: Bool { get { self[ConversationWordsSelectableKey.self] } set { self[ConversationWordsSelectableKey.self] = newValue } } } /// Where each message stands on the screen, kept out of the view's /// state: a scroll moves every message, and a lift reads it only on a hold. private final class MessageFrames { var frames: [String: CGRect] = [:] } /// Words that can be selected, or not. private struct WordsSelectable: ViewModifier { let on: Bool func body(content: Content) -> some View { if on { content.textSelection(.enabled) } else { content } } } /// What a single tap on a message does. A message that failed to send lifts /// its answers (Retry, Delete); one that carries a link opens it — one act, /// and the tap does it (walker 298: a tap on a link message opened nothing); /// any other message has nothing a tap does: a hold lifts its acts. enum ConversationTap: Equatable { case failure case open(URL) case nothing static func of(failed: Bool, body: String?) -> ConversationTap { if failed { return .failure } return link(in: body ?? "").map(ConversationTap.open) ?? .nothing } /// The message's link: a markdown link's target, else the first web /// address its words hold. static func link(in body: String) -> URL? { if let markdown = try? AttributedString(markdown: body, options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace)), let link = markdown.runs.lazy.compactMap(\.link).first { return link } guard let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) else { return nil } let range = NSRange(body.startIndex..., in: body) return detector.firstMatch(in: body, range: range)?.url } }