1124 lines · 55.2 KB · SwiftRaw
// A Cotton Chat thread: the header (back, picture, name and status, more),// the pinned bar under it, the bubbles, the round jump-to-latest button// with its count, and the composer (or why there is none). A long press// lifts the bubble with a row of reactions above it and its acts below; a// swipe to the left replies. It slides in from the side over the list and// a swipe from the leading edge takes it back.#if os(iOS)import CottonComposerimport CottonKitimport ImageIOimport QuickLookimport SwiftUIimport UIKit/// Cotton did not find them (never said as more certain than that): what is/// written waits on this phone and goes when they can be reached. Under the/// header, so it never pushes the writing box under the keyboard (owner, Comms/// build 19, the largest text): with the keyboard up it is one line, its name/// and Invite, and it never stands taller than a third of the page (`page`), a/// quarter while typing, scrolling inside past that with Invite at its top.struct ChatReachBanner: View { let page: CGFloat let invite: () -> Void @Environment(\.chatLook) private var look @State private var typing = false @State private var tall: CGFloat = 0 var body: some View { Group { if tall > cap { ScrollView(.vertical) { words } .scrollBounceBehavior(.basedOnSize) .frame(height: cap) } else { words } } .background(RoundedRectangle(cornerRadius: 20, style: .continuous).fill(look.colours.bar)) .padding(.horizontal, Warm.side - 6) .accessibilityElement(children: .contain) .accessibilityIdentifier("chat-reach") .onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillShowNotification)) { _ in typing = true } .onReceive(NotificationCenter.default.publisher(for: UIResponder.keyboardWillHideNotification)) { _ in typing = false } } private var cap: CGFloat { max(60, page / (typing ? 4 : 3)) } private var words: some View { HStack(alignment: tall > cap ? .top : .center, spacing: 12) { VStack(alignment: .leading, spacing: 2) { Text(verbatim: ChatWords.line("reach.not_yet")).font(look.font(15, .semibold)).foregroundStyle(look.colours.text) .lineLimit(typing ? 1 : nil) if !typing { Text(verbatim: ChatWords.line("reach.waiting")).font(look.font(13)).foregroundStyle(look.colours.dim) .fixedSize(horizontal: false, vertical: true) } } .accessibilityElement(children: .combine) Spacer(minLength: 8) WarmPill(words: ChatWords.line("reach.invite"), id: "chat-reach-invite", accent: true, run: invite) } .padding(.horizontal, 16) .padding(.vertical, 12) .fixedSize(horizontal: false, vertical: true) .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { tall = $0 } }}struct ChatThreadScreen: View { let row: ChatListRow let book: any ChatBook let close: () -> Void /// When the row was tapped, to measure tap → drawn thread. @MainActor static var tapped: ContinuousClock.Instant? @Environment(\.chatLook) private var look @Environment(\.layoutDirection) private var direction @Environment(ToastCenter.self) private var toasts: ToastCenter? @Environment(\.chatCalls) private var calls @Environment(\.scenePhase) private var scenePhase @Environment(\.cottonSync) private var sync @State private var model: ChatThreadModel? @State private var atBottom = true @State private var toBottom = 0 @State private var pressed: (bubble: ChatBubble, frame: CGRect)? @State private var viewing: ChatViewing? @State private var shift: CGFloat = 1 @State private var drag: CGFloat = 0 @State private var forwarding: ChatBubble? /// A received file, shown by Quick Look. @State private var looking: URL? /// How far the times are pulled into view, 0 … 1. @State private var times: CGFloat = 0 /// The floating header's and writing box's frames, for the page's insets. @State private var headerFrame: CGRect = .zero @State private var footFrame: CGRect = .zero @State private var person = false /// The safety number's screen, opened from the chat's quiet line. @State private var safety = false @State private var inviting = false /// The attachment sheet, and what was chosen in it (run by the plus). @State private var attaching = false @State private var attachChosen: ChatAttachChoice? /// The sheet a poll is made on, open. @State private var pollMaking = false /// A message of the person's own whose Message info is open (a Cotton group). @State private var informing: ChatBubble? /// A poll whose Votes are open, by its message: read from the page as it stands, so votes arriving show. @State private var pollOpen: ChatPollOpen? /// The app is in front: a chat behind the lock screen is not being read. @MainActor private static var inFront: Bool { UIApplication.shared.applicationState == .active } var body: some View { GeometryReader { geometry in ZStack(alignment: .top) { look.colours.ground.ignoresSafeArea() if let model { // The table is wider than the screen by the times' column, so it // stands in an overlay: it never widens the header or the writing box. Color.clear.overlay(alignment: .topLeading) { ChatThreadTable(model: model, revision: model.revision, look: look, book: book, taps: taps, atBottom: { atBottom = $0 }, reply: { b in Task { await model.reply(to: b.message) } }, pressed: { b, f in withAnimation(.spring(duration: 0.28)) { pressed = (b, f) } }, times: { pulled in times = pulled }, toBottom: toBottom, head: headerFrame.maxY, foot: footFrame.minY) .frame(width: geometry.size.width + geometry.safeAreaInsets.leading + geometry.safeAreaInsets.trailing + WarmTimes.width) .offset(x: -WarmTimes.width * times) } .clipped() .ignoresSafeArea() // A chat opened while the first pull runs and nothing of it has come says so in place, never an empty page. if let loading = model.loading, model.items.isEmpty { Text(verbatim: loading) .font(look.font(15)) .foregroundStyle(look.colours.dim) .multilineTextAlignment(.center) .padding(32) .frame(maxWidth: .infinity, maxHeight: .infinity) .accessibilityIdentifier("chat-thread-loading") } } VStack(spacing: 0) { VStack(spacing: 8) { header // A group's call going on: the strip, with Join (CONTRACT.md "Group calls"). if model?.header?.group == true, let calls { ChatGroupCallBanner(thread: row.thread, revision: model?.revision ?? 0, calls: calls) { video in calls.join(thread: row.thread, video: video) { said in toasts?.show(said, tone: .error) } } } if let reach = model?.reach, reach.state == "notYet" { ChatReachBanner(page: geometry.size.height) { inviting = true } } } .onGeometryChange(for: CGRect.self) { $0.frame(in: .global) } action: { headerFrame = $0 } // The header's own ground, above the page: opaque from the screen's top (under the clock) // to the header's foot, then a short fade, so nothing of the page shows through, beside or // above the pill and the rounds while it scrolls (owner, Chat build 14 on an iPhone). .background(alignment: .top) { headGround } Spacer(minLength: 0) ZStack(alignment: .bottomTrailing) { jumpButton } .frame(maxWidth: .infinity, alignment: .trailing) foot .background(alignment: .bottom) { LinearGradient(colors: [look.colours.ground.opacity(0), look.colours.ground], startPoint: .top, endPoint: .center) .padding(.top, -14) .ignoresSafeArea(edges: .bottom) .allowsHitTesting(false) } .onGeometryChange(for: CGRect.self) { $0.frame(in: .global) } action: { footFrame = $0 } } .zIndex(1) if let pressed, let model { ChatMessageMenu(bubble: pressed.bubble, frame: pressed.frame, foot: footFrame.minY, group: row.group, words: model.actions, choose: { act, emoji in choose(act, emoji: emoji, on: pressed.bubble) }, dismiss: { withAnimation(.easeOut(duration: 0.18)) { self.pressed = nil } }) .transition(.opacity) // Above the header and the writing box (zIndex 1), so nothing of the menu is ever under them // (owner, FEEDBACK-4 B1: the menu was cut off by the message box below). .zIndex(2) } } .environment(\.chatLook, look) .environment(\.chatBook, book) .offset(x: (shift * geometry.size.width + drag) * (direction == .rightToLeft ? -1 : 1)) .gesture(backSwipe(width: geometry.size.width)) } .background(Color.clear) .presentationBackground(.clear) .task { let made = model ?? ChatThreadModel(book: book, thread: row.thread) model = made withAnimation(.spring(duration: 0.32, bounce: 0)) { shift = 0 } await made.open() if let tapped = Self.tapped { ChatSpeed.mark("tap.to.thread", since: tapped) Self.tapped = nil } // Whether this chat's person is still on Cotton (the header says so when not). if !row.group { let thread = row.thread; Task { await ChatCircleGone.shared.read(threads: [thread]) } } // Shown is read: the core stamps theirs and says whether to tell the person's other phones. if Self.inFront { await made.markRead() } // The voice speed as the core keeps it, the person's (one for every note). await ChatVoicePlayer.shared.open(book) #if COTTON_DEV if ChatWarmSeed.asked, let seconds = ChatWarmSeed.timer { await made.setTimer(seconds) } if ChatWarmSeed.asked, ChatWarmSeed.person { person = true } if ChatWarmSeed.asked, ChatWarmSeed.sendPicture != nil { await made.send("", attachments: (0..<5).compactMap(ChatWarmSeed.inventedAttachment)) if let one = ChatWarmSeed.inventedAttachment(5) { await made.send("", attachments: [one]) } } #endif } // A voice message playing stops when its chat is left. .onDisappear { ChatVoicePlayer.shared.stop() } .task { for await change in book.changes() { await model?.apply(change) // Something came in while the chat stays shown: read too, but // never while the app is behind (a push landed it there). if case .arrived(let thread) = change, thread == row.thread, Self.inFront { await model?.markRead() } } } .onChange(of: scenePhase) { _, phase in // Back to an open chat: what came in meanwhile is read now, and the chat is asked again. if phase == .active { Task { await model?.reread(); await model?.markRead() } } } // A sync brought what others wrote (a WhatsApp text's state from the Mac, its sent message): asked again. .onChange(of: sync?.foreignRevision) { _, _ in Task { await model?.reread() } } // A message whose time comes while he looks leaves then: asked again 300 ms past the core's moment. .task(id: model?.erasesAt) { guard let at = model?.erasesAt else { return } try? await Task.sleep(for: .seconds(max(0, at.timeIntervalSinceNow) + 0.3)) guard !Task.isCancelled else { return } await model?.reread() } // The person's own message sent: down to it. .onChange(of: model?.sentHere) { _, _ in toBottom += 1 } .onChange(of: model?.said) { _, said in if let said { toasts?.show(said, tone: model?.saidTone ?? .notice); model?.heard() } } .fullScreenCover(item: $viewing) { viewing in ChatViewer(viewing: viewing, book: book) { self.viewing = nil } .receiptsOverCover() .chatCallRoom() } .quickLookPreview($looking) .lookPanel(isPresented: $inviting, style: look.panel) { ChatInviteSheet(thread: row.thread, number: nil, name: model?.header?.name ?? row.name) { inviting = false } } .lookPanel(isPresented: $attaching, style: look.panel) { ChatAttachSheet(files: model?.composer?.attach ?? true, poll: model?.composer?.poll?.label) { choice in attaching = false if choice == .poll { pollMaking = true } else { attachChosen = choice } } } // Making a poll (CONTRACT.md "Making a poll"): its card stands in the chat at once once the core took it. .lookPanel(isPresented: $pollMaking, style: look.panel, tall: true, name: model?.composer?.poll?.label) { if let words = model?.composer?.poll { ChatPollSheet(words: words) { question, options, many in Task { guard await model?.makePoll(question: question, options: options, many: many) == true else { return } pollMaking = false // Down to its card once the sheet and its keyboard have gone, which move the page as they go. try? await Task.sleep(for: .milliseconds(450)) toBottom += 1 } } } } .lookPanel(item: $informing, style: look.panel, tall: true) { bubble in ChatMessageInfoSheet(message: bubble.message) } .lookPanel(item: $pollOpen, style: look.panel) { open in if let poll = model?.items.lazy.compactMap({ $0.item.bubble }).first(where: { $0.message == open.message })?.poll { ChatPollVotesSheet(poll: poll) } } .fullScreenCover(isPresented: $person) { Group { if model?.header?.group == true { ChatGroupScreen(row: row, header: model?.header, items: model?.items ?? [], book: book, timer: model?.timer, setTimer: { seconds in Task { await model?.setTimer(seconds) } }) { person = false } } else { ChatPersonScreen(row: row, header: model?.header, items: model?.items ?? [], book: book, timer: model?.timer, setTimer: { seconds in Task { await model?.setTimer(seconds) } }) { person = false } } } .environment(\.chatLook, look) .environment(\.chatBook, book) .receiptsOverCover() .chatCallRoom() } .fullScreenCover(isPresented: $safety) { ChatSafetyScreen(thread: row.thread) { safety = false } .environment(\.chatLook, look) .receiptsOverCover() .chatCallRoom() } // Forward rises in Chat's own look, never a system sheet (NoBottomSheetsTests). .lookPanel(item: Binding(get: { forwarding.map(ChatForwarding.init) }, set: { forwarding = $0?.bubble }), style: LookPanelStyle(scrim: Color.black.opacity(0.32), ground: look.colours.ground, corner: 26), tall: true) { f in ChatForwardSheet(book: book, from: row.thread, look: look) { targets in Task { await model?.act("forward", message: f.bubble.message, to: targets) } forwarding = nil } } } // MARK: header /// The ground the floating header stands on: the page's ground, opaque, with a short fade under it. private var headGround: some View { VStack(spacing: 0) { look.colours.ground LinearGradient(colors: [look.colours.ground, look.colours.ground.opacity(0)], startPoint: .top, endPoint: .bottom) .frame(height: 14) } .padding(.bottom, -14) .ignoresSafeArea(edges: .top) .allowsHitTesting(false) .accessibilityHidden(true) } /// The floating header: back, the person (a tap opens their page), call and video. private var header: some View { HStack(spacing: 8) { WarmRound(symbol: direction == .rightToLeft ? "chevron.right" : "chevron.left", label: ShellLines.line("chat", "stream.close"), id: "chat-back", tap: goBack) Button { person = true } label: { HStack(spacing: 9) { ChatAvatarView(avatar: model?.header?.picture ?? row.picture, side: 34) VStack(alignment: .leading, spacing: 0) { Text(verbatim: model?.header?.name ?? row.name) .font(look.font(16, .semibold)) .foregroundStyle(look.colours.text) .lineLimit(1) // Where his words go, under the name ("2 members · via WhatsApp"), read with it. // Their person no longer on Cotton (CIRCLE 2): the core's words in place of the status. if let under = Self.underName(status: ChatCircleGone.shared.words(row.thread) ?? model?.header?.status, place: model?.header?.place) { Text(verbatim: under) .font(look.font(12)) .foregroundStyle(look.colours.dim) .lineLimit(1) // At the largest text the mark shrinks before it is cut ("on Cott…"). .minimumScaleFactor(0.6) } } Spacer(minLength: 0) } .padding(.leading, 5) .padding(.trailing, 14) .padding(.vertical, 5) .background(Capsule().fill(look.colours.bar)) .contentShape(Capsule()) } .buttonStyle(.plain) .accessibilityElement(children: .combine) .accessibilityAddTraits(.isHeader) .accessibilityHint(Text(verbatim: ChatWords.line("thread.person"))) .accessibilityIdentifier("chat-person") ForEach(model?.header?.calls ?? [], id: \.video) { button in WarmRound(symbol: button.video ? "video" : "phone", label: button.label, id: button.video ? "chat-video" : "chat-call") { calls?.place(thread: row.thread, call: nil, video: button.video) { said in toasts?.show(said, tone: .error) } } } } .padding(.horizontal, Warm.side - 6) .padding(.top, 2) } /// The header's line under the name: the status, then where a message written here goes, when the core says. static func underName(status: String?, place: ChatGoes?) -> String? { let parts = [status, place?.mark].compactMap { $0 }.filter { !$0.isEmpty } return parts.isEmpty ? nil : parts.joined(separator: " · ") } /// The writing box (or the stranger's request, or why it is read only), floating at the foot. @ViewBuilder private var foot: some View { if let model { VStack(spacing: 8) { if let pinned = model.pinned { pinnedBar(pinned) } if let request = model.request { ChatRequestView(card: request) { method in Task { do { try await book.decide(row.thread, method); await model.open() } catch { toasts?.show(String(describing: error), tone: .error) } } } } if let composer = model.composer { // The link written fetches its card on this phone (FEEDBACK-4 B4), standing above the writing box. if let card = model.card { ChatLinkCardStrip(card: card) { model.closeCard() } } #if COTTON_DEV ChatWarmLinkLog() #endif ChatComposerView(model: model, composer: composer, attaching: $attaching, attachChosen: $attachChosen) .task(id: composer.preview?.url) { await model.fetchCard(composer.preview?.url) } } else if let readOnly = model.readOnly { Text(verbatim: readOnly) .font(look.font(13.5)) .foregroundStyle(look.colours.dim) .multilineTextAlignment(.center) .frame(maxWidth: .infinity) .padding(.vertical, 12) .accessibilityIdentifier("chat-read-only") } } .padding(.horizontal, Warm.side - 6) .padding(.bottom, 6) } } private func pinnedBar(_ pinned: ChatPinnedBar) -> some View { Button { Task { await model?.go(to: pinned.message) } } label: { HStack(spacing: 10) { RoundedRectangle(cornerRadius: 1.5).fill(look.colours.accent).frame(width: 3, height: 32) VStack(alignment: .leading, spacing: 1) { Text(verbatim: pinned.title).font(look.font(13, .semibold)).foregroundStyle(look.colours.accent) Text(verbatim: pinned.line).font(look.font(13.5)).foregroundStyle(look.colours.text).lineLimit(1) } Spacer() Image(systemName: "pin.fill").rotationEffect(.degrees(45)).foregroundStyle(look.colours.faint) } .padding(.horizontal, 14) .padding(.vertical, 6) .background(RoundedRectangle(cornerRadius: 18, style: .continuous).fill(look.colours.bar)) } .buttonStyle(.plain) .accessibilityIdentifier("chat-pinned-bar") } @ViewBuilder private var jumpButton: some View { let away = !atBottom || !(model?.atNewest ?? true) if away { Button { Task { if model?.atNewest == false { await model?.jumpToLatest() } toBottom += 1 } } label: { Image(systemName: "chevron.down") .font(.system(size: 17, weight: .semibold)) .foregroundStyle(look.colours.text) .frame(width: 44, height: 44) .background(Circle().fill(look.colours.bar)) .overlay(alignment: .topTrailing) { // New below: the unread dot, never a number. if (model?.jump?.count ?? 0) + (model?.arrivedBelow ?? 0) > 0 { Circle().fill(look.colours.accent).frame(width: 9, height: 9).offset(x: -2, y: 2) } } } // The core's words when something new waits below, else the kit's Jump to latest. .accessibilityLabel(Text(verbatim: model?.jump.flatMap { $0.label.isEmpty ? nil : $0.label } ?? ShellLines.line("chat", "app.thread.jump"))) .accessibilityIdentifier("chat-jump") .padding(.trailing, Warm.side - 6) .padding(.bottom, 8) .transition(.scale.combined(with: .opacity)) } } // MARK: acts private var taps: ChatBubbleTaps { ChatBubbleTaps( quote: { id in Task { await model?.go(to: id) } }, media: { bubble, index in viewing = ChatViewing(bubble: bubble, index: index) }, link: { url in ChatLinks.shared.open(url) }, reaction: { bubble, reaction in guard bubble.actions.contains("react") else { return } Task { await model?.act(reaction.mine ? "unreact" : "react", message: bubble.message, emoji: reaction.emoji) } }, pinned: { id in Task { await model?.go(to: id) } }, call: { line in calls?.place(thread: nil, call: line.call, video: nil) { said in toasts?.show(said, tone: .error) } }, join: { line in calls?.join(thread: row.thread, video: line.video) { said in toasts?.show(said, tone: .error) } }, file: { bubble, index in // A file is the core's to fetch and write (`chat.file`), under // its own extension, and opens in Quick Look (a video file plays // there too). A refusal (`file_gone`, `file_offline`) is said in // its own words. Task { do { // Through the message its part names, when it is not the bubble's (FEEDBACK-4 B3). let message = bubble.media.first { $0.index == index }?.opens(in: bubble) ?? bubble.message looking = try await book.file(message: message, index: index).url } catch let refusal as CottonCallError { toasts?.show(refusal.message, tone: .error) } catch { toasts?.show(ShellLines.line("chat", "app.notice.file_offline"), tone: .error) } } }, retry: { bubble in Task { await model?.retry(bubble.message) } }, safety: { safety = true }, voicePlayed: { message in Task { await model?.act("played", message: message) } }, poll: { bubble in pollOpen = ChatPollOpen(message: bubble.message) }, vote: { bubble, option in Task { await model?.vote(bubble.message, option: option) } }) } private func choose(_ act: String, emoji: String?, on bubble: ChatBubble) { withAnimation(.easeOut(duration: 0.18)) { pressed = nil } guard let model else { return } switch act { case "react": let mine = bubble.reactions.first(where: \.mine)?.emoji == emoji Task { await model.act(mine ? "unreact" : "react", message: bubble.message, emoji: emoji) } case "reply": Task { await model.reply(to: bubble.message) } case "edit": Task { await model.edit(bubble.message) } case "copy": UIPasteboard.general.string = bubble.text if let copied = model.actions?.copied { toasts?.show(copied) } case "forward": forwarding = bubble case "select": break case "info": informing = bubble case "retry": Task { await model.retry(bubble.message) } default: Task { await model.act(act, message: bubble.message) } } } private func goBack() { withAnimation(.spring(duration: 0.28, bounce: 0)) { shift = 1 } completion: { close() } } private func backSwipe(width: CGFloat) -> some Gesture { DragGesture(minimumDistance: 12) .onChanged { value in let from = direction == .rightToLeft ? width - value.startLocation.x : value.startLocation.x let moved = direction == .rightToLeft ? -value.translation.width : value.translation.width guard from < 28, moved > 0 else { return } drag = moved } .onEnded { value in let moved = direction == .rightToLeft ? -value.translation.width : value.translation.width if drag > 0, moved > width * 0.3 || value.velocity.width * (direction == .rightToLeft ? -1 : 1) > 600 { withAnimation(.spring(duration: 0.24, bounce: 0)) { shift = 1; drag = 0 } completion: { close() } } else { withAnimation(.spring(duration: 0.24)) { drag = 0 } } } }}/// The thread's ground: plain, or a quiet pattern in the theme's own ink.struct ChatGroundView: View { let ground: String @Environment(\.chatLook) private var look var body: some View { ZStack { look.colours.ground switch ground { case "dots": Canvas { context, size in let step: CGFloat = 22 var y: CGFloat = 0 var row = 0 while y < size.height { var x: CGFloat = row % 2 == 0 ? 0 : step / 2 while x < size.width { context.fill(Path(ellipseIn: CGRect(x: x, y: y, width: 2.4, height: 2.4)), with: .color(look.colours.pattern)) x += step } y += step * 0.866 row += 1 } } case "weave": Canvas { context, size in let step: CGFloat = 18 var path = Path() var x: CGFloat = -size.height while x < size.width { path.move(to: CGPoint(x: x, y: 0)) path.addLine(to: CGPoint(x: x + size.height, y: size.height)) path.move(to: CGPoint(x: x + size.height, y: 0)) path.addLine(to: CGPoint(x: x, y: size.height)) x += step } context.stroke(path, with: .color(look.colours.pattern), lineWidth: 0.8) } default: EmptyView() } } .ignoresSafeArea() .accessibilityHidden(true) }}// MARK: the composer/// The shared composer (CottonComposer) mounted for a thread: the words/// and the send state are the core's (`chat.compose`), the reply or edit/// strip and Attach are Chat's own, dictation runs Cotton's voice session./// One microphone (owner's feedback H, 22 Nov 2026): a tap dictates into the/// field; held while the field is empty (the core's `mic`), it records a/// voice message, sent on letting go, thrown out when slid away first.struct ChatComposerView: View { let model: ChatThreadModel let composer: ChatComposeAnswer /// The attachment sheet stands at the conversation's root; the plus opens it and runs its choice. @Binding var attaching: Bool @Binding var attachChosen: ChatAttachChoice? @Environment(\.chatLook) private var look @Environment(\.cottonCore) private var core @State private var text = "" @State private var typing = false @State private var voice: ComposerVoice? @State private var recorder = ChatVoiceRecorder() /// The height standing over the field inside the box: where it goes, the strip, the pictures waiting. @State private var over: CGFloat = 0 var body: some View { VStack(spacing: 0) { // Where this message goes, said before Send ("via WhatsApp", "on Cotton"); nothing where the core says nothing. VStack(spacing: 0) { if let place = composer.place { placeView(place) } if let strip = composer.strip { stripView(strip) } if !model.attached.isEmpty { attachedRow } } .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { over = $0 } Composer( text: $text, lines: lines, style: style, dictation: composer.dictate ? voice : nil, // Held, the microphone records a voice message where the core answers `mic` (nothing written, a chat that takes them). recorder: composer.button == .mic || recorder.recording ? recorder : nil, sendRule: composer.sendEnabled, returnSends: composer.returnSends, focused: $typing, identifier: "chat-composer", leading: { // The plus stands for files, and for a poll alone where no file goes (CONTRACT.md "Making a poll"). if composer.attach || composer.poll != nil { ChatAttachButton(label: composer.attachLabel, chosen: $attachChosen, open: { attaching = true }, stage: { files in // The pictures wait in the box and the field takes the keyboard for their caption. Task { await model.attach(files) } typing = true }) { files in Task { await model.send("", attachments: files) } } } }, send: send ) .reserving(over) .padding(.horizontal, 6) .padding(.vertical, 4) } // The writing box floats over the page: rounded, a step off the ground, the one soft shadow. .background(RoundedRectangle(cornerRadius: 26, style: .continuous).fill(look.colours.color("field"))) .overlay(RoundedRectangle(cornerRadius: 26, style: .continuous).strokeBorder(look.colours.rule, lineWidth: 1)) .shadow(color: Color(red: 60 / 255, green: 40 / 255, blue: 20 / 255).opacity(0.06), radius: 11, y: 6) .onAppear { text = composer.text recorder.send = { [model] voice in Task { await model.sendVoice(voice) } } if voice == nil, let core { let thread = model.thread voice = ComposerVoice(core: core) { VoicePlanRequest(surface: "chat.thread", table: "message", column: "text", record: thread, mode: .dictate) } } } .onDisappear { // The writing box gone (the chat left) throws away a recording still held. recorder.end(cancelled: true) } // Dictation's reason before the phone is asked, or Open Settings after it refused; Not now beside either // (voice control.*, store pass, 24 Nov 2026). A card at the window, over the chat. .cottonCard(isPresented: Binding(get: { voice?.ask != nil }, set: { if !$0 { voice?.notNow() } })) { if let voice, let ask = voice.ask { let words = voice.askWords(ask) VStack(spacing: 0) { Text(verbatim: words.line).font(look.font(16)).foregroundStyle(look.colours.text) .multilineTextAlignment(.center) .fixedSize(horizontal: false, vertical: true) .padding(.horizontal, 24).padding(.vertical, 18) ChatPanelChoice(choice: LookChoice(id: "voice-ask-go", label: words.go, colour: look.colours.accent) { Task { await voice.goOn(ask) } }, font: look.font(17, .semibold)) ChatPanelChoice(choice: LookChoice(id: "voice-ask-not-now", label: words.notNow, colour: look.colours.dim) { voice.notNow() }, font: look.font(17, .semibold)) } .padding(.bottom, 12) } } .onChange(of: text) { _, now in guard now != composer.text else { return } Task { await model.type(now) } } .onChange(of: composer.strip?.message) { _, message in // A reply or an edit begun: the field takes the keyboard; an edit // brings the message's words into it. if message != nil { if composer.strip?.kind == .edit { text = composer.text } typing = true } } } private var lines: ComposerLines { // The core's label for `mic` is the microphone's ("Hold to record"); the send arrow beside it is still Send (as Android's). let send = composer.button == .mic ? ShellLines.line("chat", "app.compose.send") : composer.buttonLabel if let voice, composer.dictate { return voice.lines(hint: composer.placeholder, send: send) } return ComposerLines(hint: composer.placeholder, send: send, mic: recorder.holdLabel, stop: "", cancel: "", listening: "") } private var style: ComposerStyle { let c = look.colours let face = ComposerFace(name: look.uiFont(17).fontName, size: 17 * look.scale, textStyle: .body) return ComposerStyle(panel: c.color("field"), rim: c.color("field"), ink: c.text, faint: c.faint, chip: c.pill, accent: c.accent, onAccent: c.onAccent, face: face, cornerRadius: 20, danger: c.danger) } private func placeView(_ place: ChatGoes) -> some View { Text(verbatim: place.mark) .font(look.font(12)) .foregroundStyle(look.colours.dim) .fixedSize(horizontal: false, vertical: true) .frame(maxWidth: .infinity, alignment: .leading) .padding(.horizontal, 16) .padding(.top, 8) .accessibilityIdentifier("chat-composer-place") } private func stripView(_ strip: ChatStrip) -> some View { HStack(spacing: 10) { Image(systemName: strip.kind == .edit ? "pencil" : "arrowshape.turn.up.left.fill") .foregroundStyle(look.colours.accent) RoundedRectangle(cornerRadius: 1.5).fill(look.colours.accent).frame(width: 3, height: 32) VStack(alignment: .leading, spacing: 1) { Text(verbatim: strip.title).font(look.font(13, .semibold)).foregroundStyle(look.colours.accent).lineLimit(1) Text(verbatim: strip.line).font(look.font(13.5)).foregroundStyle(look.colours.dim).lineLimit(1) } Spacer() Button { if strip.kind == .edit { text = "" } Task { await model.cancelStrip() } } label: { Image(systemName: "xmark").font(.system(size: 14, weight: .semibold)).foregroundStyle(look.colours.dim) .frame(width: 32, height: 32) } .accessibilityLabel(Text(verbatim: strip.cancel)) .accessibilityIdentifier("chat-strip-cancel") } .padding(.horizontal, 12) .padding(.top, 6) .accessibilityIdentifier("chat-strip") } /// The pictures waiting for their caption, in a row above the field, with the strip's Cancel to take them out. private var attachedRow: some View { HStack(spacing: 10) { ScrollView(.horizontal, showsIndicators: false) { HStack(spacing: 8) { ForEach(Array(model.attached.enumerated()), id: \.offset) { _, file in ChatAttachedTile(file: file) } } } Button { Task { await model.unattach() } } label: { Image(systemName: "xmark").font(.system(size: 14, weight: .semibold)).foregroundStyle(look.colours.dim) .frame(width: 32, height: 32) } .accessibilityLabel(Text(verbatim: ShellLines.line("chat", "app.compose.cancel"))) .accessibilityIdentifier("chat-attached-cancel") } .padding(.leading, 12) .padding(.trailing, 12) .padding(.top, 10) .accessibilityElement(children: .contain) .accessibilityIdentifier("chat-attached") } private func send() { let words = text guard composer.sendEnabled || !words.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return } text = "" // What is written goes as the waiting pictures' caption. let files = model.takeAttached() let refused = model.refusedSends Task { await model.send(words, attachments: files) // Refused: the words stand in the field again, beside the pictures put back in the box. if model.refusedSends != refused, text.isEmpty { text = words } } }}/// One picture waiting in the writing box: its own small picture, read at the tile's size (never the whole file).struct ChatAttachedTile: View { let file: ChatAttachment @Environment(\.chatLook) private var look @State private var image: UIImage? private var mark: ChatMark { ChatMark(rawValue: file.kind ?? "photo") ?? .photo } var body: some View { if mark == .file { fileChip } else { picture } } /// A file put back in the box (a send refused): its mark and the name it was picked under, so which file waits /// is seen and heard. private var fileChip: some View { HStack(spacing: 8) { Image(systemName: ChatMarks.symbol(.file)).foregroundStyle(look.colours.dim) Text(verbatim: file.name ?? "") .font(look.font(13, .semibold)) .foregroundStyle(look.colours.text) .lineLimit(2) .fixedSize(horizontal: false, vertical: true) } .padding(.horizontal, 12) .padding(.vertical, 8) .frame(minHeight: 64) .frame(maxWidth: 220, alignment: .leading) .background(RoundedRectangle(cornerRadius: 12, style: .continuous).fill(look.colours.bar)) .accessibilityElement() .accessibilityLabel(Text(verbatim: [ChatMarks.spoken(.file), file.name ?? ""].filter { !$0.isEmpty }.joined(separator: ", "))) } private var picture: some View { RoundedRectangle(cornerRadius: 12, style: .continuous) .fill(look.colours.bar) .frame(width: 64, height: 64) .overlay { if let image { Image(uiImage: image).resizable().scaledToFill() } else { Image(systemName: ChatMarks.symbol(mark)).foregroundStyle(look.colours.dim) } } .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous)) .accessibilityElement() .accessibilityLabel(Text(verbatim: ChatMarks.spoken(mark))) .task(id: file.path) { let path = file.path image = await Task.detached(priority: .userInitiated) { () -> UIImage? in guard let source = CGImageSourceCreateWithURL(URL(fileURLWithPath: path) as CFURL, nil) else { return nil } let options: [CFString: Any] = [kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceThumbnailMaxPixelSize: 192, kCGImageSourceCreateThumbnailWithTransform: true] return CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary).map { UIImage(cgImage: $0) } }.value } }}// MARK: a stranger's request/// A stranger's first message waits: their words stand above, and Accept,/// Block and Delete answer it (`chat.accept`, `chat.block`, `chat.refuse`).struct ChatRequestView: View { let card: ChatAskCard let decide: (String) -> Void @Environment(\.chatLook) private var look var body: some View { VStack(spacing: 10) { Text(verbatim: card.title).font(look.font(15, .semibold)).foregroundStyle(look.colours.text) .multilineTextAlignment(.center) Text(verbatim: card.line).font(look.font(13.5)).foregroundStyle(look.colours.dim) .multilineTextAlignment(.center) HStack(spacing: 10) { choice(card.refuse, "chat.refuse", ink: look.colours.danger, fill: look.colours.pill) choice(card.block, "chat.block", ink: look.colours.danger, fill: look.colours.pill) choice(card.accept, "chat.accept", ink: look.colours.onAccent, fill: look.colours.accent) } } .padding(14) .frame(maxWidth: .infinity) .background(look.colours.bar.ignoresSafeArea(edges: .bottom)) // The card's id must not stand on its buttons too: each keeps its own (`chat-request-chat.accept`, …). .accessibilityElement(children: .contain) .accessibilityIdentifier("chat-request") } private func choice(_ word: String, _ method: String, ink: Color, fill: Color) -> some View { Button { decide(method) } label: { Text(verbatim: word).font(look.font(15, .semibold)).foregroundStyle(ink) .frame(maxWidth: .infinity).padding(.vertical, 10) .background(RoundedRectangle(cornerRadius: 12, style: .continuous).fill(fill)) } .buttonStyle(.plain) .accessibilityIdentifier("chat-request-\(method)") }}// MARK: the long press/// The bubble lifted over a dimmed thread: a row of reactions above it and/// its acts below, in the core's order and words.struct ChatMessageMenu: View { let bubble: ChatBubble let frame: CGRect /// Where the writing box starts (global): the menu stands whole above it, never under it nor over it. var foot: CGFloat = .infinity let group: Bool let words: ChatActionWords? let choose: (String, String?) -> Void let dismiss: () -> Void @Environment(\.chatLook) private var look /// The menu's own height as drawn (its rows grow with the text size), and the reactions' row's. @State private var menuDrawn: CGFloat = 0 @State private var reactDrawn: CGFloat = 0 /// The room kept clear at the top and the foot of the screen. static let margin: CGFloat = 12 /// The least of the bubble that still shows when the room is short. static let leastBubble: CGFloat = 56 /// Where the lifted bubble, the reactions above it and the menu below go: the whole menu always on screen /// (FEEDBACK-4 B1). The block stands where the bubble stood, moved up or down only as far as it must; a bubble /// too tall for the room shows its top part; a menu too tall for the room scrolls. struct Placement: Equatable { var top: CGFloat var bubble: CGFloat var menu: CGFloat var scrolls: Bool static func of(room: CGFloat, bubbleMinY: CGFloat, bubbleHeight: CGFloat, react: CGFloat, menu: CGFloat) -> Placement { let gap: CGFloat = 8 let above = react > 0 ? react + gap : 0 let usable = max(0, room - 2 * margin) // The menu whole if it fits beside the least of the bubble; else as much as fits, scrolling. let menuShown = min(menu, max(0, usable - above - leastBubble - gap)) let bubbleShown = max(0, min(bubbleHeight, usable - above - gap - menuShown)) let block = above + bubbleShown + gap + menuShown let wanted = bubbleMinY - above let top = min(max(margin, wanted), max(margin, room - margin - block)) return Placement(top: top, bubble: bubbleShown, menu: menuShown, scrolls: menuShown < menu - 0.5) } } var body: some View { GeometryReader { geometry in let origin = geometry.frame(in: .global).origin let local = frame.offsetBy(dx: -origin.x, dy: -origin.y) let acts = bubble.actions.filter { $0 != "react" } let reacts = bubble.actions.contains("react") && words?.emoji != nil // Before the first drawing, as the rows are laid out: 46 pt each at this size. let menuHeight = menuDrawn > 0 ? menuDrawn : CGFloat(acts.count) * 46 * look.scale let reactHeight: CGFloat = reacts ? (reactDrawn > 0 ? reactDrawn : 54) : 0 let room = min(geometry.size.height, foot.isFinite && foot > origin.y ? foot - origin.y : geometry.size.height) let place = Placement.of(room: room, bubbleMinY: local.minY, bubbleHeight: local.height, react: reactHeight, menu: menuHeight) ZStack(alignment: .topLeading) { look.colours.scrim .ignoresSafeArea() .onTapGesture(perform: dismiss) VStack(alignment: bubble.mine ? .trailing : .leading, spacing: 8) { if reacts, let emoji = words?.emoji { reactions(emoji) .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { reactDrawn = $0 } } ChatBubbleRow(bubble: bubble, group: group, taps: ChatBubbleTaps()) .frame(width: geometry.size.width) .frame(height: max(0, place.bubble), alignment: .top) .clipped() .allowsHitTesting(false) Group { if place.scrolls { ScrollView { menu(acts) } .frame(height: place.menu) .scrollBounceBehavior(.basedOnSize) // A scroll view's own name only: its acts keep theirs (`chat-act-<act>`). .accessibilityIdentifier("chat-menu-scroll") } else { menu(acts) } } .padding(.horizontal, 12) } .frame(width: geometry.size.width, alignment: bubble.mine ? .trailing : .leading) .offset(y: place.top) } } .accessibilityAddTraits(.isModal) } private func reactions(_ emoji: [String]) -> some View { HStack(spacing: 4) { ForEach(emoji, id: \.self) { e in Button { choose("react", e) } label: { Text(verbatim: e) .font(.system(size: 28)) .frame(width: 44, height: 44) .background(Circle().fill(bubble.reactions.contains { $0.mine && $0.emoji == e } ? look.colours.pill : Color.clear)) } .accessibilityLabel(Text(verbatim: "\(words?.react ?? "") \(e)")) } } .padding(.horizontal, 8) .padding(.vertical, 5) .background(Capsule().fill(look.colours.sheet)) .shadow(color: .black.opacity(0.15), radius: 12, y: 4) .padding(.horizontal, 12) .accessibilityIdentifier("chat-react-row") } private func menu(_ acts: [String]) -> some View { VStack(spacing: 0) { ForEach(Array(acts.enumerated()), id: \.element) { i, act in Button { choose(act, nil) } label: { HStack { Text(verbatim: words?.word(act) ?? act) .font(look.font(16)) Spacer() Image(systemName: Self.symbol(act)) } .foregroundStyle(act == "delete" || act == "deleteMine" ? look.colours.danger : look.colours.text) .padding(.horizontal, 16) // At least 46 pt at this size, and taller where the words need it (the largest text). .frame(minHeight: 46 * look.scale) .contentShape(Rectangle()) } .buttonStyle(.plain) .accessibilityIdentifier("chat-act-\(act)") if i < acts.count - 1 { Rectangle().fill(look.colours.rule).frame(height: 0.5) } } } .frame(width: 240) .background(RoundedRectangle(cornerRadius: 14, style: .continuous).fill(look.colours.sheet)) .shadow(color: .black.opacity(0.15), radius: 12, y: 4) .onGeometryChange(for: CGFloat.self) { $0.size.height } action: { menuDrawn = $0 } } static func symbol(_ act: String) -> String { switch act { case "reply": "arrowshape.turn.up.left" case "copy": "doc.on.doc" case "forward": "arrowshape.turn.up.right" case "edit": "pencil" case "pin": "pin" case "unpin": "pin.slash" case "delete": "trash" case "deleteMine": "trash.slash" case "star": "star" case "unstar": "star.slash" case "select": "checkmark.circle" case "info": "info.circle" case "retry": "arrow.clockwise" default: "circle" } }}// MARK: forwardstruct ChatForwarding: Identifiable { let bubble: ChatBubble var id: String { bubble.message }}/// Where a message goes: the conversations the core says can be written/// into (`chat.list {sendable: true}`), chosen by name; the core carries a/// Cotton message's files, sealed again for each.struct ChatForwardSheet: View { let book: any ChatBook let from: String let look: ChatLook let send: ([String]) -> Void @State private var rows: [ChatListRow] = [] @State private var chosen: Set<String> = [] @Environment(\.dismiss) private var dismiss @Environment(\.closeCard) private var close var body: some View { // Its own head, in Chat's look: no NavigationStack (NavigationSweepTests). VStack(spacing: 0) { HStack { Button { CardClosing.close(close, else: dismiss) } label: { Image(systemName: "xmark").frame(width: 44, height: 44).contentShape(Rectangle()) } Spacer() Button { send(Array(chosen)) } label: { Image(systemName: "paperplane.fill").frame(width: 44, height: 44).contentShape(Rectangle()) } .disabled(chosen.isEmpty) .accessibilityIdentifier("chat-forward-send") } .font(.system(size: 17, weight: .semibold)) .foregroundStyle(look.colours.accent) .padding(.horizontal, 8) .padding(.top, 8) List(rows) { row in Button { if chosen.contains(row.thread) { chosen.remove(row.thread) } else { chosen.insert(row.thread) } } label: { HStack(spacing: 12) { ChatAvatarView(avatar: row.picture, side: 38) Text(verbatim: row.name).font(look.font(16)).foregroundStyle(look.colours.text) Spacer() Image(systemName: chosen.contains(row.thread) ? "checkmark.circle.fill" : "circle") .foregroundStyle(chosen.contains(row.thread) ? look.colours.accent : look.colours.faint) } } .listRowBackground(look.colours.ground) } .listStyle(.plain) .scrollContentBackground(.hidden) } .background(look.colours.ground) .environment(\.chatLook, look) .environment(\.chatBook, book) .task { rows = (try? await book.list(ChatListAsk(filter: "all", sendable: true)).rows.filter { $0.thread != from }) ?? [] } }}#endif