1022 lines · 46.3 KB · SwiftRaw
// Calls inside Cotton Chat: the header's Call and Video// call, a call's line in its thread, the Calls tile, and the call screen// with its returning bar. Chat only places, says and draws a call: the call// itself is CottonCalls' engine (CallCenter, CallKit, PushKit, WebRTC), as// the Calling flavour has it, handed in through `ChatCalling` because that// module sits above this one. Every word, control and state is the core's// (`chat.call`, `chat.calls`, `chat.callScreen`).#if os(iOS)import CottonKitimport SwiftUIimport osimport UIKit/// The call engine as Chat uses it, filled by CottonCalls (`ChatCallsShell`).@MainActorpublic protocol ChatCalling: AnyObject { /// Changes whenever the call or the phone's route does (read inside a /// view, it redraws the view; observed, it says to ask the screen again). var stamp: String { get } /// The phone's own route: the loudspeaker on. var speaker: Bool { get } /// `chat.call`: from a conversation (`thread`) or calling back a call /// (`call`), after the microphone (and camera for video) is allowed. A /// refusal's words go to `refused`. func place(thread: String?, call: String?, video: Bool?, refused: @escaping @MainActor (String) -> Void) /// Into a group's call going on, late or again (`chat.call { thread, join: true }`): no ring. func join(thread: String, video: Bool, refused: @escaping @MainActor (String) -> Void) /// `chat.flush`, asked when `chat.call` answers `flush: true` (a group's call is told to the group), off the main /// thread as after a send. Filled by the app, which holds the chat key. var flush: (@Sendable () async -> Void)? { get set } /// A read the engine performs nothing for (`chat.callScreen`). func read(_ method: String, _ request: JSONValue) async -> JSONValue? func answer() func decline() func end() func toggleMute() func toggleVideo() func toggleSpeaker() func flipCamera() /// The other person's picture, full size, and one's own, small. func remoteVideo() -> AnyView func localVideo() -> AnyView /// One person's video on a group call, by the room's member id (their picture stands while none comes). func memberVideo(_ member: String) -> AnyView}private struct ChatCallsKey: EnvironmentKey { static var defaultValue: (any ChatCalling)? { nil }}extension EnvironmentValues { /// The call engine, where this app carries one. public var chatCalls: (any ChatCalling)? { get { self[ChatCallsKey.self] } set { self[ChatCallsKey.self] = newValue } }}// MARK: a group's call going on/// The strip under a group's header while its call goes on (CONTRACT.md "Group calls", the banner): the call's mark,/// the core's words, who is in it, and Join; on this phone's own call, the core's "You're in this call". Asked when the/// chat opens, when its items change (`revision`), when the call does, and every 20 seconds while it stays open.struct ChatGroupCallBanner: View { let thread: String let revision: Int let calls: any ChatCalling let join: (Bool) -> Void @Environment(\.chatLook) private var look @State private var state: ChatGroupCallState? var body: some View { Group { if let state, state.live, let banner = state.banner { HStack(spacing: 12) { Image(systemName: state.video == true ? "video.fill" : "phone.fill") .font(.system(size: 15 * look.scale, weight: .semibold)) .foregroundStyle(look.colours.accent) .accessibilityHidden(true) VStack(alignment: .leading, spacing: 2) { Text(verbatim: banner).font(look.font(15, .semibold)).foregroundStyle(look.colours.text) if let who = state.in { Text(verbatim: who).font(look.font(13)).foregroundStyle(look.colours.dim) } if state.here == true, let here = state.hereText { Text(verbatim: here).font(look.font(13)).foregroundStyle(look.colours.dim) .accessibilityIdentifier("chat-group-call-here") } } .fixedSize(horizontal: false, vertical: true) .accessibilityElement(children: .combine) Spacer(minLength: 8) if state.here != true, let words = state.join { WarmPill(words: words, id: "chat-group-call-banner-join", accent: true) { join(state.video == true) } } } .padding(.horizontal, 16) .padding(.vertical, 10) .background(RoundedRectangle(cornerRadius: 20, style: .continuous).fill(look.colours.bar)) .padding(.horizontal, Warm.side - 6) .accessibilityElement(children: .contain) .accessibilityIdentifier("chat-group-call-banner") } } .task(id: "\(thread)-\(revision)-\(calls.stamp)") { await ask() } .task(id: thread) { while !Task.isCancelled { try? await Task.sleep(for: .seconds(20)) if Task.isCancelled { return } await ask() } } } private func ask() async { guard let value = await calls.read(ChatMethod.groupCall, .object(["thread": .string(thread)])), let data = try? JSONEncoder().encode(value), let read = try? JSONDecoder().decode(ChatGroupCallState.self, from: data) else { return } // Offline the call is not known: what stands stays, never said as over. if read.unknown == true { return } state = read }}// MARK: the header's buttons/// Call and Video call, as `header.calls` offers them.struct ChatCallButtons: View { let thread: String let buttons: [ChatCallButton] @Environment(\.chatCalls) private var calls @Environment(\.chatLook) private var look @Environment(ToastCenter.self) private var toasts: ToastCenter? var body: some View { if let calls { ForEach(buttons, id: \.self) { button in Button { calls.place(thread: thread, call: nil, video: button.video) { said in toasts?.show(said, tone: .error) } } label: { Image(systemName: button.video ? "video" : "phone") .font(.system(size: 18, weight: .semibold)) .foregroundStyle(look.colours.accent) .frame(width: 40, height: 44) } .accessibilityLabel(Text(verbatim: button.label)) .accessibilityIdentifier(button.video ? "chat-video-call" : "chat-call") } } }}// MARK: the Calls tile/// Calls (warm.html "Structure"): the log under its large title, newest/// first; a missed call's line in the refusal colour; a tap on a row, or its/// round at the end, rings them again the same way (`chat.calls`).struct ChatCallsScreen: View { let book: any ChatBook let look: ChatLook @State private var answer: ChatCallsAnswer? @State private var rows: [ChatCallRow] = [] @State private var asking = false /// A recording's page stands over Calls (CONTRACT.md "Recordings"). @State private var opened: String? @State private var bringing = false @State private var recorder = ChatRecorder.shared /// Record's card before the phone is asked for the microphone (its reason, Continue, Not now), or after it refused /// (Open Settings, Not now): the reviewer pass, 24 Nov 2026, as Android. Nothing opens Settings unasked. @State private var micAsk: MicAsk? @Environment(\.chatCalls) private var calls @Environment(\.cottonCore) private var core @Environment(ToastCenter.self) private var toasts: ToastCenter? var body: some View { Group { if let opened { // While recording, the recording screen is all there is: VoiceOver does not reach what is under it. ChatRecordingPageView(recording: opened) { self.opened = nil; Task { await first() } } .accessibilityHidden(recorder.live != nil) } else { list .accessibilityHidden(recorder.live != nil) } } .preference(key: ChatYouPageUp.self, value: opened != nil || recorder.live != nil) .overlay { if let live = recorder.live { ChatRecordingLiveView(live: live, recorder: recorder) } } .onChange(of: recorder.heard) { _, _ in Task { await first() } } .onChange(of: recorder.saved) { _, saved in if let saved { opened = saved; recorder.saved = nil } } .onAppear { if let saved = recorder.saved { opened = saved; recorder.saved = nil } } .fileImporter(isPresented: $bringing, allowedContentTypes: ChatRecorder.audioTypes) { result in guard case .success(let url) = result else { return } Task { await bring(url) } } .environment(\.chatLook, look) .environment(\.chatBook, book) } private var list: some View { ScrollView { LazyVStack(alignment: .leading, spacing: 0) { HStack(alignment: .center, spacing: 10) { Text(verbatim: answer?.words.title ?? "") .font(look.font(34, .bold)) .kerning(-0.7) .foregroundStyle(look.colours.text) .accessibilityAddTraits(.isHeader) Spacer(minLength: 8) if let bring = answer?.words.import { WarmRound(symbol: "square.and.arrow.down", label: bring, id: "calls-bring") { bringing = true } } if let record = answer?.words.record { ChatRecordButton(label: record) { Task { await recordAsked() } } } } .padding(.horizontal, Warm.side) .padding(.top, 10) .padding(.bottom, 8) if let answer, rows.isEmpty { Text(verbatim: answer.words.empty).font(look.font(16)).foregroundStyle(look.colours.dim) .multilineTextAlignment(.center) .frame(maxWidth: .infinity) .padding(.horizontal, 32).padding(.vertical, 64) .accessibilityIdentifier("calls-empty") } ForEach(Array(rows.enumerated()), id: \.element.id) { at, row in if let day = row.day, at == 0 || rows[at - 1].day != day { ChatCallsDay(day: day) } Group { if row.isRecording { ChatRecordingRowView(row: row) { opened = row.recording } } else { ChatCallRowView(row: row, back: answer?.words.back ?? "", notes: row.recording.map { recording in { opened = recording } }) { call(row) } } } .onAppear { if row.id == rows.last?.id { Task { await more() } } } } } .padding(.bottom, Warm.footRoom) } .scrollIndicators(.hidden) .background(look.colours.ground.ignoresSafeArea()) .accessibilityIdentifier("chat-calls") .task { await first() } .cottonCard(isPresented: Binding(get: { micAsk != nil }, set: { if !$0 { micAsk = nil } })) { if let ask = micAsk { let words = micWords(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) .accessibilityIdentifier("record-ask-line") ChatPanelChoice(choice: LookChoice(id: "record-ask-go", label: words.go, colour: look.colours.accent) { Task { await goOn(ask) } }, font: look.font(17, .semibold)) ChatPanelChoice(choice: LookChoice(id: "record-ask-not-now", label: ShellLines.line("voice", "control.not_now"), colour: look.colours.dim) { micAsk = nil }, font: look.font(17, .semibold)) } .padding(.bottom, 12) } } } enum MicAsk: Equatable { case why, settings } /// Record: the microphone's reason first while the phone has not asked, Open Settings once it refused; else it records. private func recordAsked() async { switch await microphone() { case .notDetermined: micAsk = .why case .denied, .restricted: micAsk = .settings default: await start() } } private func microphone() async -> CapabilityAccess { #if COTTON_DEV if let held = ChatWarmSeed.microphone { return held } #endif return await SystemCapabilityAuthority().status(.microphone) } private func start() async { guard let refused = await recorder.start(core: core, blocked: answer?.words.no_microphone) else { return } if refused.isEmpty { // The microphone was turned off for Comms and the core has no words for it: the card says so, with Open Settings. micAsk = .settings } else { toasts?.show(refused, tone: .error) } } /// The card's words: the core's reason or refusal, the voice kit's Continue, Open Settings and Not now. private func micWords(_ ask: MicAsk) -> (line: String, go: String) { switch ask { case .why: (ShellLines.line("chat", "app.recording.mic.why"), ShellLines.line("voice", "control.go_on")) case .settings: (ShellLines.line("chat", "app.recording.mic.refused"), ShellLines.line("voice", "control.open_settings")) } } private func goOn(_ ask: MicAsk) async { micAsk = nil switch ask { case .why: await start() case .settings: if let settings = URL(string: UIApplication.openSettingsURLString) { await UIApplication.shared.open(settings) } } } private func bring(_ url: URL) async { let answer = await recorder.bring(url, core: core) if let refused = answer.refused { toasts?.show(refused, tone: .error) } if let said = answer.said { toasts?.show(said) } if let meeting = answer.meeting { opened = meeting } } private func call(_ row: ChatCallRow) { calls?.place(thread: nil, call: row.call, video: nil) { said in toasts?.show(said, tone: .error) } } private func first() async { guard let fresh = try? await book.calls(after: nil) else { return } answer = fresh rows = fresh.rows } private func more() async { guard !asking, let next = answer?.next else { return } asking = true defer { asking = false } guard let fresh = try? await book.calls(after: next) else { return } answer = fresh let known = Set(rows.map(\.id)) rows += fresh.rows.filter { !known.contains($0.id) } }}struct ChatCallRowView: View { let row: ChatCallRow let back: String /// The notes this person took on the call: a small mark after its line opens them; the rest of the row calls back. var notes: (() -> Void)? = nil let tap: () -> Void @Environment(\.chatLook) private var look var body: some View { HStack(spacing: 0) { Button(action: tap) { HStack(spacing: 13) { ChatAvatarView(avatar: row.picture, side: Warm.rowPicture * min(look.scale, 1.3)) VStack(alignment: .leading, spacing: 2) { Text(verbatim: row.name) .font(look.font(17, .semibold)) .foregroundStyle(look.colours.text) .lineLimit(1) Text(verbatim: row.line).font(look.font(15)).foregroundStyle(row.missed ? look.colours.danger : look.colours.dim).lineLimit(1) } Spacer(minLength: 8) } .padding(.leading, Warm.side) .padding(.vertical, 10) .contentShape(Rectangle()) } .buttonStyle(.plain) .accessibilityElement(children: .ignore) .accessibilityLabel(Text(verbatim: [row.name, row.line, row.when, back].filter { !$0.isEmpty }.joined(separator: ", "))) .accessibilityAddTraits(.isButton) .accessibilityIdentifier("chat-call-row") if let notes { Button(action: notes) { Image(systemName: "note.text") .font(.system(size: 15 * min(look.scale, 1.3), weight: .semibold)) .foregroundStyle(look.colours.accent) .frame(width: 44, height: 44) .contentShape(Rectangle()) } .buttonStyle(.plain) .accessibilityLabel(Text(verbatim: row.name)) .accessibilityIdentifier("chat-call-notes-\(row.recording ?? "")") } Button(action: tap) { HStack(spacing: 0) { Text(verbatim: row.when).font(look.font(13)).foregroundStyle(look.colours.faint).lineLimit(1) .padding(.horizontal, 10) Image(systemName: row.video ? "video" : "phone") .font(.system(size: 17, weight: .medium)) .foregroundStyle(look.colours.text) .frame(width: Warm.round, height: Warm.round) .background(Circle().fill(look.colours.bar)) } .padding(.trailing, Warm.side) .padding(.vertical, 10) .contentShape(Rectangle()) } .buttonStyle(.plain) .accessibilityHidden(true) } }}// MARK: the call screen and its returning bar/// Round the app's root: whenever the call changes, the core is asked what/// the call screen shows (`chat.callScreen {speaker}`) and that is drawn —/// the full screen, or folded behind the returning bar at the top.public struct ChatCallOverlay: View { let calls: any ChatCalling @State private var screen = ChatCallScreen.hidden @State private var folded = false @State private var reading: Task<Void, Never>? @Environment(\.colorScheme) private var scheme public init(calls: any ChatCalling) { self.calls = calls } /// Chat's Warm look, as the app it rings over. private var look: ChatLook { ChatLook.warm(dark: scheme == .dark) } public var body: some View { ZStack(alignment: .top) { if screen.shown { if folded, let bar = screen.bar { ChatCallBar(text: bar, liveAt: screen.liveAt, notes: screen.notes) { withAnimation(.easeOut(duration: 0.2)) { folded = false } } .transition(.move(edge: .top)) .onGeometryChange(for: CGRect.self, of: { $0.frame(in: .global) }) { frame in ChatCallTouch.frame = frame ChatCallFold.shared.height = frame.height } .onDisappear { ChatCallFold.shared.height = 0 } } else { ChatCallScreenView(screen: screen, calls: calls) { withAnimation(.easeOut(duration: 0.2)) { folded = true } } .transition(.opacity) .onGeometryChange(for: CGRect.self, of: { $0.frame(in: .global) }) { ChatCallTouch.frame = $0 } } } } // The window's whole height, so the folded bar sits at its top, not in the middle (seen on dev). .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top) .onChange(of: screen.shown, initial: true) { _, shown in if !shown { ChatCallTouch.frame = nil } } .environment(\.chatLook, look) .onChange(of: calls.stamp, initial: true) { _, _ in ask() } } private func ask() { reading?.cancel() reading = Task { let request: JSONValue = .object(["speaker": .bool(calls.speaker)]) guard let value = await calls.read(ChatMethod.callScreen, request) else { ChatCallLog.write("chat.callScreen: no answer") return } guard let data = try? JSONEncoder().encode(value), !Task.isCancelled else { return } let fresh: ChatCallScreen do { fresh = try JSONDecoder().decode(ChatCallScreen.self, from: data) } catch { // A screen this build cannot read would leave a call undrawn: said, never silent. ChatCallLog.write("chat.callScreen unreadable: \(error)") return } if fresh.shown != screen.shown || fresh.phase != screen.phase { ChatCallLog.write("chat.callScreen: \(fresh.phase) shown \(fresh.shown)") } if !fresh.shown || fresh.ring != nil { folded = false } screen = fresh // After an end the screen stands a moment, then is asked again. if fresh.shown, fresh.status != nil, fresh.controls.isEmpty, fresh.ring == nil, fresh.endedFor > 0 { try? await Task.sleep(for: .milliseconds(Int(fresh.endedFor))) if !Task.isCancelled { ask() } } } }}/// Where the call screen takes touches, in the window's points: the whole screen, the folded bar, or nowhere/// (`nil`). Its window lies over the app's and lets every other touch through to it; SwiftUI's content hits as/// the hosting view itself, so the window cannot tell from a hit test alone (seen on dev: Mute and Leave fell/// through to the chat underneath).@MainActorpublic enum ChatCallTouch { public static var frame: CGRect?}/// How tall the folded call bar stands over the app, 0 when it does not: the app beneath steps down by it, or the bar/// (in its own window, `ChatCallsShell`) covered the thread's header, its Back and call buttons (CALLS WALK 1).@MainActor @Observablepublic final class ChatCallFold { public static let shared = ChatCallFold() public var height: CGFloat = 0}extension View { /// Room at the top for the folded call bar: on Comms' root and on each of its whole-screen covers (a cover is its /// own presentation, so the root's room does not reach it). public func chatCallRoom() -> some View { modifier(ChatCallRoom()) }}private struct ChatCallRoom: ViewModifier { private let fold = ChatCallFold.shared func body(content: Content) -> some View { content.safeAreaInset(edge: .top, spacing: 0) { Color.clear.frame(height: fold.height) } }}/// What the call screen says to the log.public enum ChatCallLog { public static let logger = Logger(subsystem: "com.cottondb.chat", category: "calls") public static func write(_ words: String) { logger.log("\(words, privacy: .public)") }}/// The call clock from when it went live: m:ss, or h:mm:ss past an hour.enum ChatCallClock { static func text(liveAt: Double, now: Date) -> String { let seconds = max(0, Int(now.timeIntervalSince1970 - liveAt / 1000)) let duration = Duration.seconds(seconds) return seconds >= 3600 ? duration.formatted(.time(pattern: .hourMinuteSecond)) : duration.formatted(.time(pattern: .minuteSecond)) }}/// The returning bar: the core's line and the clock; a tap opens the call.struct ChatCallBar: View { let text: String let liveAt: Double? var notes: ChatCallNotes? = nil let open: () -> Void @Environment(\.chatLook) private var look var body: some View { Button(action: open) { HStack(spacing: 8) { Image(systemName: "phone.fill").font(.system(size: 13, weight: .semibold)) Text(verbatim: text).font(look.font(14, .semibold)).lineLimit(1) if let liveAt { TimelineView(.periodic(from: .now, by: 1)) { context in Text(verbatim: ChatCallClock.text(liveAt: liveAt, now: context.date)) .font(look.font(14, .semibold)).monospacedDigit() } } // Notes being taken: the mark stands on the folded bar too, for as long as it runs. if let notes, notes.mark { Circle().fill(look.colours.onAccent).frame(width: 7, height: 7).accessibilityHidden(true) Text(verbatim: notes.line).font(look.font(13, .medium)).lineLimit(1) } } .foregroundStyle(look.colours.onAccent) .frame(maxWidth: .infinity) .padding(.vertical, 8) .background(look.colours.accent.ignoresSafeArea(edges: .top)) } .buttonStyle(.plain) .accessibilityIdentifier("chat-call-bar") }}/// The call (warm.html): ringing (Decline and Answer), the call (the core's/// controls on round chips, End below in the refusal colour) and a video call/// (theirs full screen, yours small in a corner), on the Warm ground.struct ChatCallScreenView: View { let screen: ChatCallScreen let calls: any ChatCalling let fold: () -> Void @Environment(\.chatLook) private var look @Environment(\.dynamicTypeSize) private var typeSize var body: some View { if screen.group == true, screen.ring == nil { ChatGroupCallScreenView(screen: screen, calls: calls, fold: fold) } else { oneToOne } } private var oneToOne: some View { ZStack { (screen.video ? Color.black : look.colours.ground).ignoresSafeArea() if screen.video { calls.remoteVideo().ignoresSafeArea() } VStack(spacing: 0) { HStack { if screen.bar != nil { Button(action: fold) { Image(systemName: "chevron.down") .font(.system(size: 18, weight: .semibold)) .foregroundStyle(ink) .frame(width: Warm.round, height: Warm.round) .background(Circle().fill(ink.opacity(0.1))) } .accessibilityLabel(Text(verbatim: screen.bar ?? "")) .accessibilityIdentifier("chat-call-fold") } Spacer() } .frame(height: 44) if let notes = screen.notes { ChatCallNotesMark(notes: notes, ink: ink) } if let notice = screen.notice { ChatCallNotice(words: notice, ink: ink) } Spacer().frame(height: screen.video ? 8 : (typeSize.isAccessibilitySize ? 20 : 48)) if !screen.video { ChatAvatarView(avatar: screen.picture, side: typeSize.isAccessibilitySize ? 96 : 120) .accessibilityHidden(true) .padding(.bottom, 20) } Text(verbatim: screen.name) .font(look.font(28, .bold)) .kerning(-0.3) .foregroundStyle(ink) .multilineTextAlignment(.center) .lineLimit(2) .accessibilityAddTraits(.isHeader) .accessibilityIdentifier("chat-call-name") .padding(.horizontal, screen.camera ? 112 : 0) status.padding(.top, 6) Spacer() if let ring = screen.ring { HStack { Spacer() key(ring.decline, glyph: "xmark", fill: look.colours.danger, mark: look.colours.ground, id: "decline") { calls.decline() } Spacer() key(ring.answer, glyph: screen.video ? "video.fill" : "phone.fill", fill: look.colours.accent, mark: look.colours.onAccent, id: "answer") { calls.answer() } Spacer() } .accessibilityElement(children: .contain) .accessibilityLabel(Text(verbatim: ring.title)) } else { controls if let end = screen.controls.first(where: { $0.id == "end" }) { key(end.label, glyph: "phone.down.fill", fill: look.colours.danger, mark: look.colours.ground, id: "end") { calls.end() } .padding(.top, 24) } } Spacer().frame(height: 12) } .padding(24) if screen.camera { VStack { HStack { Spacer() calls.localVideo() .frame(width: 108, height: 156) .clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous)) .padding(16) } Spacer() } .accessibilityHidden(true) } } .accessibilityElement(children: .contain) .accessibilityAddTraits(.isModal) .accessibilityIdentifier("chat-call-screen") } private var ink: Color { screen.video ? .white : look.colours.text } private var ground: Color { screen.video ? .black : look.colours.ground } @ViewBuilder private var status: some View { if let status = screen.status { Text(verbatim: status).font(look.font(16)).foregroundStyle(screen.video ? .white.opacity(0.85) : look.colours.dim) .multilineTextAlignment(.center) .accessibilityIdentifier("chat-call-status") } else if let liveAt = screen.liveAt { TimelineView(.periodic(from: .now, by: 1)) { context in Text(verbatim: ChatCallClock.text(liveAt: liveAt, now: context.date)) .font(look.font(16)).monospacedDigit() .foregroundStyle(screen.video ? .white.opacity(0.85) : look.colours.dim) } .accessibilityIdentifier("chat-call-live") } } /// The core's controls but End, on round chips: on, the ink; off, a tint of it. private var controls: some View { let shown = screen.offered.filter { $0.id != "end" } let columns = typeSize.isAccessibilitySize ? min(3, shown.count) : shown.count return LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 8), count: max(1, columns)), spacing: 16) { ForEach(shown) { control in key(control.label, glyph: glyph(control), fill: control.on ? ink : ink.opacity(0.1), mark: control.on ? ground : ink, id: control.id, on: control.on) { perform(control) } } } } private func key(_ word: String, glyph: String, fill: Color, mark: Color, id: String, on: Bool = false, tap: @escaping () -> Void) -> some View { Button(action: tap) { VStack(spacing: 8) { Image(systemName: glyph) .font(.system(size: 24, weight: .semibold)) .foregroundStyle(mark) .frame(width: 68, height: 68) .background(Circle().fill(fill)) Text(verbatim: word).font(look.font(13)).foregroundStyle(ink.opacity(0.8)).lineLimit(typeSize.isAccessibilitySize ? 2 : 1) .multilineTextAlignment(.center) } } .buttonStyle(.plain) .accessibilityElement(children: .ignore) .accessibilityLabel(Text(verbatim: word)) .accessibilityAddTraits(on ? [.isButton, .isSelected] : .isButton) .accessibilityIdentifier("chat-call-\(id)") } private func glyph(_ control: ChatCallControl) -> String { switch control.id { case "mute": control.on ? "mic.slash.fill" : "mic.fill" case "speaker", "audio": control.on ? "speaker.wave.3.fill" : "speaker.fill" case "video": control.on ? "video.fill" : "video.slash.fill" case "flip": "arrow.triangle.2.circlepath.camera" case "end": "phone.down.fill" case "notes": control.on ? "note.text" : "square.and.pencil" default: "circle" } } private func perform(_ control: ChatCallControl) { switch control.id { case "mute": calls.toggleMute() case "speaker", "audio": calls.toggleSpeaker() case "video": calls.toggleVideo() case "flip": calls.flipCamera() case "end": calls.end() // Take notes or Stop notes: the room is asked; the mark and the recording follow its answer (CONTRACT.md "Take notes"). case "notes": Task { _ = await calls.read("calls.notes", .object(["on": .bool(!control.on)])) } default: break } }}/// A group call (CONTRACT.md "Group calls", the screen): the group's name and clock, "Protected in transit" (a tap says/// more), the notes mark, a tile per person in the core's grid, then the call's controls and Leave.struct ChatGroupCallScreenView: View { let screen: ChatCallScreen let calls: any ChatCalling let fold: () -> Void @Environment(\.chatLook) private var look @Environment(\.dynamicTypeSize) private var typeSize @State private var privacyOpen = false private var ink: Color { look.colours.text } var body: some View { ZStack { look.colours.ground.ignoresSafeArea() VStack(spacing: 10) { head if let notes = screen.notes { ChatCallNotesMark(notes: notes, ink: ink) } if let notice = screen.notice { ChatCallNotice(words: notice, ink: ink) } ChatCallTiles(tiles: screen.tiles ?? [], grid: screen.grid, calls: calls) .frame(maxHeight: .infinity) controls } .padding(.horizontal, 16) .padding(.top, 4) .padding(.bottom, 12) } .accessibilityElement(children: .contain) .accessibilityAddTraits(.isModal) .accessibilityIdentifier("chat-call-screen") } private var head: some View { VStack(spacing: 6) { HStack(alignment: .center, spacing: 10) { if screen.bar != nil { Button(action: fold) { Image(systemName: "chevron.down") .font(.system(size: 18, weight: .semibold)) .foregroundStyle(ink) .frame(width: 44, height: 44) .background(Circle().fill(ink.opacity(0.1))) } .accessibilityLabel(Text(verbatim: screen.bar ?? "")) .accessibilityIdentifier("chat-call-fold") } VStack(alignment: .leading, spacing: 1) { Text(verbatim: screen.name).font(look.font(20, .bold)).foregroundStyle(ink).lineLimit(2) .accessibilityAddTraits(.isHeader) .accessibilityIdentifier("chat-call-name") status } Spacer(minLength: 0) } if let privacy = screen.privacy { Button { withAnimation(.easeOut(duration: 0.2)) { privacyOpen.toggle() } } label: { VStack(alignment: .leading, spacing: 4) { HStack(spacing: 6) { Image(systemName: "lock.fill").font(.system(size: 11 * look.scale, weight: .semibold)).accessibilityHidden(true) Text(verbatim: privacy).font(look.font(13, .medium)) } if privacyOpen, let detail = screen.privacyDetail { Text(verbatim: detail).font(look.font(13)).foregroundStyle(look.colours.dim) .multilineTextAlignment(.leading) .fixedSize(horizontal: false, vertical: true) .accessibilityIdentifier("chat-call-privacy-detail") } } .foregroundStyle(ink) .padding(.horizontal, 12).padding(.vertical, 6) .background(RoundedRectangle(cornerRadius: 14, style: .continuous).fill(ink.opacity(0.08))) .frame(maxWidth: .infinity, alignment: .leading) } .buttonStyle(.plain) .accessibilityElement(children: .combine) .accessibilityAddTraits(privacyOpen ? [.isButton, .isSelected] : .isButton) .accessibilityIdentifier("chat-call-privacy") } } } @ViewBuilder private var status: some View { if let status = screen.status { Text(verbatim: status).font(look.font(14)).foregroundStyle(look.colours.dim) .accessibilityIdentifier("chat-call-status") } else if let liveAt = screen.liveAt { TimelineView(.periodic(from: .now, by: 1)) { context in Text(verbatim: ChatCallClock.text(liveAt: liveAt, now: context.date)) .font(look.font(14)).monospacedDigit().foregroundStyle(look.colours.dim) } .accessibilityIdentifier("chat-call-live") } } /// The core's controls on small round chips in one row (wrapping at a large text size), Leave in the refusal /// colour at the end. private var controls: some View { let shown = screen.offered let columns = typeSize.isAccessibilitySize ? min(3, shown.count) : shown.count return LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 6), count: max(1, columns)), spacing: 12) { ForEach(shown) { control in let leave = control.id == "end" Button { perform(control) } label: { VStack(spacing: 6) { Image(systemName: glyph(control)) .font(.system(size: 20, weight: .semibold)) .foregroundStyle(leave ? look.colours.ground : (control.on ? look.colours.ground : ink)) .frame(width: 56, height: 56) .background(Circle().fill(leave ? look.colours.danger : (control.on ? ink : ink.opacity(0.1)))) Text(verbatim: control.label).font(look.font(12)).foregroundStyle(ink.opacity(0.8)) .lineLimit(typeSize.isAccessibilitySize ? 2 : 1).multilineTextAlignment(.center) } } .buttonStyle(.plain) .accessibilityElement(children: .ignore) .accessibilityLabel(Text(verbatim: control.label)) .accessibilityAddTraits(control.on && !leave ? [.isButton, .isSelected] : .isButton) .accessibilityIdentifier("chat-call-\(control.id)") } } } private func glyph(_ control: ChatCallControl) -> String { switch control.id { case "mute": control.on ? "mic.slash.fill" : "mic.fill" case "speaker", "audio": control.on ? "speaker.wave.3.fill" : "speaker.fill" case "video": control.on ? "video.fill" : "video.slash.fill" case "flip": "arrow.triangle.2.circlepath.camera" case "end": "phone.down.fill" case "notes": control.on ? "note.text" : "square.and.pencil" default: "circle" } } private func perform(_ control: ChatCallControl) { switch control.id { case "mute": calls.toggleMute() case "speaker", "audio": calls.toggleSpeaker() case "video": calls.toggleVideo() case "flip": calls.flipCamera() // Leave: the others go on (the core's `calls.end` on a group call). case "end": calls.end() case "notes": Task { _ = await calls.read("calls.notes", .object(["on": .bool(!control.on)])) } default: break } }}/// The tiles in the core's grid: columns by rows, each filling its cell.struct ChatCallTiles: View { let tiles: [ChatCallTile] let grid: ChatCallGrid? let calls: any ChatCalling var body: some View { let columns = max(1, grid?.columns ?? 1) let rows = max(1, grid?.rows ?? max(1, tiles.count)) GeometryReader { geometry in let gap: CGFloat = 8 let width = (geometry.size.width - gap * CGFloat(columns - 1)) / CGFloat(columns) let height = (geometry.size.height - gap * CGFloat(rows - 1)) / CGFloat(rows) VStack(spacing: gap) { ForEach(0..<rows, id: \.self) { row in HStack(spacing: gap) { ForEach(0..<columns, id: \.self) { column in let at = row * columns + column if at < tiles.count { ChatCallTileView(tile: tiles[at], calls: calls) .frame(width: width, height: max(0, height)) } else { Color.clear.frame(width: width, height: max(0, height)) } } } } } } .accessibilityElement(children: .contain) .accessibilityIdentifier("chat-call-tiles") }}/// One person: their video while their camera is on (yours mirrored), else their picture; a ring in the accent while/// they talk; the mute mark; their name (and "Ringing…") on a chip at the foot.struct ChatCallTileView: View { let tile: ChatCallTile let calls: any ChatCalling @Environment(\.chatLook) private var look var body: some View { ZStack { RoundedRectangle(cornerRadius: 18, style: .continuous).fill(look.colours.text.opacity(0.08)) if tile.camera { (tile.you ? calls.localVideo() : calls.memberVideo(tile.member)) .clipShape(RoundedRectangle(cornerRadius: 18, style: .continuous)) } else { GeometryReader { g in ChatAvatarView(avatar: tile.picture, side: min(96, min(g.size.width, g.size.height) * 0.42)) .frame(maxWidth: .infinity, maxHeight: .infinity) } .accessibilityHidden(true) .opacity(tile.joined ? 1 : 0.55) } } .overlay { if tile.speaking { RoundedRectangle(cornerRadius: 18, style: .continuous).strokeBorder(look.colours.accent, lineWidth: 3) .accessibilityIdentifier("chat-call-tile-speaking") } } .overlay(alignment: .topTrailing) { if tile.muted { Image(systemName: "mic.slash.fill") .font(.system(size: 12, weight: .bold)) .foregroundStyle(.white) .frame(width: 26, height: 26) .background(Circle().fill(Color.black.opacity(0.55))) .padding(8) .accessibilityIdentifier("chat-call-tile-muted") } } .overlay(alignment: .bottomLeading) { HStack(spacing: 5) { if tile.notes { Circle().fill(look.colours.danger).frame(width: 7, height: 7) } Text(verbatim: tile.state.map { "\(tile.name) · \($0)" } ?? tile.name) .font(look.font(12, .semibold)).foregroundStyle(.white).lineLimit(2) } .padding(.horizontal, 9).padding(.vertical, 4) .background(Capsule().fill(Color.black.opacity(0.55))) .accessibilityElement(children: .combine) .accessibilityIdentifier("chat-call-tile-name") .padding(8) } .accessibilityElement(children: .contain) .accessibilityAddTraits(tile.speaking ? .isSelected : []) .accessibilityIdentifier("chat-call-tile-\(tile.you ? "you" : tile.member)") }}/// Take notes refused or stopped, in the core's words, under the call's name.struct ChatCallNotice: View { let words: String let ink: Color @Environment(\.chatLook) private var look var body: some View { Text(verbatim: words).font(look.font(14)).foregroundStyle(ink.opacity(0.85)) .multilineTextAlignment(.center) .fixedSize(horizontal: false, vertical: true) .padding(.horizontal, 14).padding(.vertical, 7) .background(RoundedRectangle(cornerRadius: 14, style: .continuous).fill(ink.opacity(0.08))) .accessibilityIdentifier("chat-call-notice") .onAppear { UIAccessibility.post(notification: .announcement, argument: words) } .onChange(of: words) { _, said in UIAccessibility.post(notification: .announcement, argument: said) } }}/// Notes being taken on this call: a red dot and the core's line, at the top of the call screen while it stands. The/// moment it starts (or who takes them changes) VoiceOver says it too: everyone is told (chat DECISIONS "Take notes").struct ChatCallNotesMark: View { let notes: ChatCallNotes let ink: Color @Environment(\.chatLook) private var look var body: some View { // `mark` false: notes stopped, said as a quiet line with no dot until they start again. HStack(spacing: 8) { if notes.mark { Circle().fill(look.colours.danger).frame(width: 9, height: 9).accessibilityHidden(true) } Text(verbatim: notes.line).font(look.font(14, notes.mark ? .semibold : .regular)).foregroundStyle(ink.opacity(notes.mark ? 1 : 0.75)) .multilineTextAlignment(.center) .fixedSize(horizontal: false, vertical: true) } .padding(.horizontal, 14).padding(.vertical, 7) .background(Capsule().fill(ink.opacity(notes.mark ? 0.1 : 0))) .accessibilityElement(children: .combine) .accessibilityIdentifier("chat-call-notes") .onAppear { UIAccessibility.post(notification: .announcement, argument: notes.line) } .onChange(of: notes.line) { _, said in UIAccessibility.post(notification: .announcement, argument: said) } }}#endif