// 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.importCottonFacesimportCottonKitimportCottonValuesimportSwiftUIstructConversationPage: View { @Environment(\.headRowTrailing) privatevar headRowTrailing @Environment(\.theme) privatevar themelet definition: TableDefinitionlet record: TableRecordlet model: ConversationModel/// The thread narrowed to its photos and files (browsing, not reading).var mediaOnly = falsevar 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) privatevar definitions @Environment(ToastCenter.self) privatevar toasts/// The messages whose envelope is open. @State privatevar openEnvelopes: Set<String> = []/// The older mail opened from its folded line (`folds`). @State privatevar unfolded: Set<String> = [] @State privatevar voice = VoiceNotePlayer()/// The message whose own page a long press asked for. @State privatevar detailed: TableRecord? @Environment(\.actLift) privatevar lift @Environment(\.cottonHaptics) privatevar haptics @Environment(\.openURL) privatevar openURL @Environment(PendingTaps.self) privatevar pendingTaps: PendingTaps? @State privatevar frames = MessageFrames()/// Cotton chat's engine, in an app that carries one. @Environment(\.cottonChat) privatevar chatprivatevar layout: ConversationLayout { model.layout }/// The message table's definition, for its status column's words.privatevar messages: TableDefinition? { definitions[layout.table] }var body: someView { 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] inguardlet 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 iniflet 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 privatevar conversationHead: someView {if showsTitle { title }ForEach(Array(layout.headerPieces(of: record, in: definition).enumerated()), id: \.offset) { index, piece inswitch 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 inMarkdownBlockView(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)") } } }privatevar title: someView {// 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 privatevar thread: someView {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 })iflet 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 inGroup {if item.isMessage { message(item, index: index, assigned: assigned) } elseif !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)) } elseif !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")) }iflet 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.iflet change = model.lastChange {ChangeReceipt( change: change, table: messages, undone: model.lastChangeUndone, onUndone: { _ inTask { 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 privatefunc bubble(_ item: ConversationItem, index: Int, opens: Bool, headed: String?, dye: PaperDye, isGroup: Bool, assigned: [String: PaperDye]) -> someView {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 {iflet key = layout.photoKey(of: message), !key.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {InstantPrint(seed: key, size: .thumb, tilts: false) {KeyedPicture(key: key, edge: Self.faceLane) } } elseiflet 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 = mediaOnlylet envelope = layout.folds ? layout.envelopeHead(of: message, messages: messages, day: true) : layout.envelopeHead(of: message, messages: messages)iflet 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 inText(line).paperBody(12, ink: .pencil) .fixedSize(horizontal: false, vertical: true) } } }// A Cotton message that answers another says which, in pencil above it.ifCottonChatRows.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).isEmptylet 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() } elseif wordless {iflet 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) }iflet 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) } elseiflet 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) }iflet 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)") } } }iflet 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 privatefunc message(_ item: ConversationItem, index: Int, assigned: [String: PaperDye]) -> someView {let message = item.recordif !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 ?? "") }iflet 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 {switchConversationTap.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.privatefunc hold(_ item: ConversationItem, index: Int, opens: Bool, headed: String?, dye: PaperDye, isGroup: Bool, assigned: [String: PaperDye]) {guardlet 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)) }privatestaticfunc 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.privatefunc acts(of message: TableRecord) -> [LiftedAct] {var acts: [LiftedAct] = []iflet chat, CottonChatRows.isCotton(message: message), record.said?.readOnly != true {ifCottonDelivery(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) }) }iflet 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.privatefunc 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.privatefunc foldedLine(_ item: ConversationItem) -> someView {let message = item.recordlet day = item.day?.headinglet 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: " ")returnButton { 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) {iflet 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.privatefuncopen(_ link: URL) {if !RecordAddress.open(link, taps: pendingTaps, external: { openURL($0) }) { toasts.show(ShellLines.line("record", "address_failed"), tone: .error) } }privatefunc mayActOnFailure(_ message: TableRecord) -> Bool { record.said?.readOnly != true && model.canRetryOrBin(message) }privatefunc binFailed(_ message: TableRecord) {Task {do { _ = tryawait model.binFailed(message) }catch { toasts.show(CottonStrings.writeFailure(error), tone: .error) } } }/// A Cotton message that failed, tried again by the core's outbox.privatefunc retryCotton(_ message: TableRecord, _ chat: any CottonChatting) {Task {do {tryawait chat.retry(message: message.id)await model.load() } catch { toasts.show(chatRefusal(error), tone: .error) } } }privatefunc retry(_ message: TableRecord) {Task {do { _ = tryawait model.retry(message) }catch { toasts.show(CottonStrings.writeFailure(error), tone: .error) } } }privatestaticvar faceLane: CGFloat { 30 }/// Whether the thread keeps a lane for its senders' pictures: a group/// whose layout names a `photo` column.privatevar 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.privatefunc opensRun(_ index: Int) -> Bool {guard !startsDay(index), let before = model.items[..<index].last(where: { $0.isMessage }) else { returntrue }let message = model.items[index]iflet system = layout.system, before.record[system].bool == true { returntrue }return before.mine != message.mine || layout.writer(of: before.record) != layout.writer(of: message.record) }/// The `header` columns' words above the message at `index`; nil when/// they hold nothing, or say what the message before it on the same day/// already said (a sender's name stands above the first of a run).privatefunc heading(_ index: Int) -> String? {let message = model.items[index].recordguardlet words = layout.metadata(layout.header, of: message, messages: messages) else { returnnil }guard !opensRun(index), let before = model.items[..<index].last(where: { $0.isMessage }) else { return words }return layout.metadata(layout.header, of: before.record, messages: messages) == words ? nil : words }privatefunc hasMedia(_ message: TableRecord) -> 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.staticfunc timeStandsAlone(wordless: Bool, media: Bool) -> Bool { wordless || media }staticfunc hasMedia(_ message: TableRecord, layout: ConversationLayout) -> Bool {guardlet media = layout.media else { returnfalse }switch message[media] {case .list(let entries): return !entries.isEmptycase .null: returnfalsedefault: returntrue } }/// Whether the message at `index` in the stream is the first of its day/// among the messages.privatefunc startsDay(_ index: Int) -> Bool {guardlet day = model.items[index].day?.day else { returnfalse }let previous = model.items[..<index].last { $0.isMessage }guardlet before = previous?.day?.day else { returntrue }return day != before }}/// A record of an `also` table whose face is `slip`, drawn in the stream as/// its own table's slip — page-wide, between the notes, with its time/// handwritten under it as a note's is.structConversationSlip: View {let key: Stringlet definition: TableDefinitionlet record: TableRecordlet footer: String?var body: someView { VStack(alignment: .leading, spacing: 2) {SlipFace(definition: definition, record: record)iflet footer {Text(footer) .paperHand(14) .padding(.leading, 4) } } .frame(maxWidth: .infinity, alignment: .leading) .padding(.vertical, 6) .accessibilityElement(children: .combine) .accessibilityIdentifier("conversation-slip-\(key)") }}/// A note's words. As written, unless the body column says `markdown`: then/// emphasis, links and code in a line; a list, a quote, a heading or fenced/// code as its own block; and words with no block in them still set line for/// line.structConversationWords: View { @Environment(\.theme) privatevar themelet words: Stringvar isLetter = falsevar markdown = false/// Off where holding a bubble raises the tray with its acts (Copy among/// them): the hold is the tray's, never the system's selection. @Environment(\.conversationWordsSelectable) privatevar selectablevar body: someView {let blocks = markdown ? MarkdownBlocks.parse(words) : []if !markdown || Self.isPlain(blocks) {Text(markdown ? MarkdownInline.attributed(words, theme: theme) : AttributedString(words)) .paperBody(15) .lineSpacing(isLetter ? 6 : 3) .fixedSize(horizontal: false, vertical: true) .modifier(WordsSelectable(on: selectable)) } else { VStack(alignment: .leading, spacing: 0) {ForEach(Array(blocks.enumerated()), id: \.offset) { at, block inMarkdownBlockView(block: block, voice: .note) .padding(.top, Self.gap(before: block, first: at == 0)) } } .modifier(WordsSelectable(on: selectable)) } }/// Whether every block is a plain line: nothing but inline Markdown.staticfunc isPlain(_ blocks: [MarkdownBlock]) -> Bool { blocks.allSatisfy { ifcase .line = $0 { returntrue } else { returnfalse } } }/// The air above a block on a note: closer than a page's, a note is small.staticfunc gap(before block: MarkdownBlock, first: Bool) -> CGFloat {if first { return0 }switch block {case .line: return6case .item, .numbered: return4default: return10 } }}/// A line handwritten in pencil down the middle of the conversation.structConversationLine: View {let text: Stringvar body: someView {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.structConversationNote: View {let key: Stringlet words: Stringlet mine: Boollet footer: String?/// Media keys, drawn as instant prints above the words.var media: [String] = []var sender: String? = nilvar isGroup = falsevar 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 = falseprivatestaticvar sideLane: CGFloat { 44 }privatestaticvar printWidth: CGFloat { 132 }privatevar isLetter: Bool { sheet || ChatPaper.isLetter(words) }var body: someView { HStack(alignment: .top, spacing: 0) {if mine && !isLetter { Spacer(minLength: Self.sideLane) } VStack(alignment: mine ? .trailing : .leading, spacing: 6) {iflet name {Text(name) .paperMeta(12) .padding(.horizontal, 4) .padding(.bottom, -2) .accessibilityIdentifier("conversation-sender-\(key)") }if !media.isEmpty { prints } noteiflet 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)") }privatevar note: someView {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).privatevar prints: someView { HStack(spacing: 8) {ForEach(media, id: \.self) { key inInstantPrint(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.structConversationComposer: View { @Environment(\.theme) privatevar themelet model: ConversationModellet 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? = nilvar onSent: () async -> Void = {} @Environment(ToastCenter.self) privatevar toasts @State privatevar draft = ""var body: someView {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.guardtryawait model.send(words) != nilelse {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.privatestructConversationWordsSelectableKey: EnvironmentKey {staticlet defaultValue = true}extensionEnvironmentValues {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.privatefinalclassMessageFrames {var frames: [String: CGRect] = [:]}/// Words that can be selected, or not.privatestructWordsSelectable: ViewModifier {let on: Boolfunc body(content: Content) -> someView {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.enumConversationTap: Equatable {case failurecaseopen(URL)case nothingstaticfunc 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.staticfunc link(in body: String) -> URL? {iflet markdown = try? AttributedString(markdown: body, options: .init(interpretedSyntax: .inlineOnlyPreservingWhitespace)),let link = markdown.runs.lazy.compactMap(\.link).first {return link }guardlet detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) else { returnnil }let range = NSRange(body.startIndex..., in: body)return detector.firstMatch(in: body, range: range)?.url }}