Cotton code
486 lines · 21.2 KB · SwiftRaw
// A PERSON'S PAGE in the Warm look (warm.html "A person"): their photo, name// and the name they gave themselves, Message / Call / Video, Not on Cotton yet// with Invite, what is between you (the latest photos, then how many photos,// videos, voice messages, files and links), and at the foot Mute (for a time,// `chat.contact`'s `mutes`) and Block. Read from `chat.contact` (lane// chat-people); a group's header opens its own page (`ChatGroupScreen`).// Disappearing messages stands under the pills when the core answers the// chat's timer (ChatTimer.swift). Someone on Cotton has a Safety number row above the foot, with a small// Verified mark while `chat.contact` says `verified`; it opens the safety// number's screen (`ChatSafetyScreen`, CONTRACT.md "Safety number").#if os(iOS)import CottonKitimport SwiftUI/// The latest photos between you, from the conversation on the phone ("the/// lists themselves are the thread's pictures, for now", CONTRACT.md §6).struct ChatPersonPhotos {    static func of(_ items: [ChatDrawn]) -> [ChatPersonPhoto] {        let bubbles = items.compactMap { drawn -> ChatBubble? in            if case .bubble(let bubble) = drawn.item { return bubble }            return nil        }        let photos = bubbles.reversed().flatMap { bubble in            bubble.media.filter { $0.kind == .photo }.map { ChatPersonPhoto(message: $0.opens(in: bubble), index: $0.index) }        }        return Array(photos.prefix(9))    }}struct ChatPersonPhoto: Equatable, Hashable, Identifiable {    var message: String    var index: Int    var id: String { "\(message)#\(index)" }}struct ChatPersonScreen: View {    let row: ChatListRow    let header: ChatHeader?    let items: [ChatDrawn]    let book: any ChatBook    /// The chat's disappearing timer (`chat.thread`'s), and what sets it: no row where the core answers none.    var timer: ChatTimerCard? = nil    var setTimer: (Int) -> Void = { _ in }    let close: () -> Void    @Environment(\.chatLook) private var look    @Environment(\.chatCalls) private var calls    @Environment(\.cottonCore) private var core    @Environment(ToastCenter.self) private var toasts: ToastCenter?    @State private var contact: ChatContactAnswer?    @State private var picture: UIImage?    @State private var muting = false    @State private var blocking = false    @State private var inviting = false    @State private var safety = false    @State private var timing = false    private var name: String { contact?.name ?? header?.name ?? row.name }    var body: some View {        ScrollView {            VStack(alignment: .leading, spacing: 0) {                HStack {                    WarmRound(symbol: "chevron.left", label: ShellLines.line("words", "back"), id: "chat-person-back", tap: close)                    Spacer()                }                .padding(.horizontal, Warm.side - 6)                top                acts                if contact?.reach == "notYet" { notYet }                // Disappearing messages stands first of the page's settings, under the pills, where it is found.                if let timer {                    ChatTimerRow(card: timer) { timing = true }                        .padding(.horizontal, Warm.side)                        .padding(.top, 10)                }                between                if contact?.reach == "on" { safetyRow }                foot            }            .padding(.bottom, 40)        }        .scrollIndicators(.hidden)        .background(look.colours.ground.ignoresSafeArea())        .accessibilityIdentifier("chat-person-page")        .task { await read() }        #if COTTON_DEV        .task { if ChatWarmSeed.asked, ChatWarmSeed.timerSheet, timer?.choices.isEmpty == false { timing = true } }        #endif        // The sheet stands over the page, never inside its scrolling column (Android 4a4b37f257).        .lookPanel(isPresented: $timing, style: look.panel, name: timer?.title) {            if let timer { ChatTimerSheet(card: timer, set: setTimer) { timing = false } }        }        .lookPanel(isPresented: $muting, style: look.panel, name: ChatWords.line("person.mute_for")) { muteSheet }        .lookAsk(isPresented: $blocking, style: look.panel, font: look.font(17, .semibold),                 message: ChatWords.line("confirm.block", ["name": name]), messageColour: look.colours.text,                 choices: [                    LookChoice(id: "block", label: ChatWords.line("confirm.block_yes"), colour: look.colours.danger) { decide(ChatPeopleMethod.block) },                    LookChoice(id: "keep", label: ChatWords.line("confirm.keep"), colour: look.colours.text) {},                 ])        .lookPanel(isPresented: $inviting, style: look.panel) {            ChatInviteSheet(thread: row.thread, number: nil, name: name) { inviting = false }        }        .fullScreenCover(isPresented: $safety, onDismiss: { Task { await read() } }) {            ChatSafetyScreen(thread: row.thread) { safety = false }                .environment(\.chatLook, look)        }    }    /// Safety number, with Verified beside it while it holds.    private var safetyRow: some View {        let verified = contact?.verified == true        return Button { safety = true } label: {            HStack(spacing: 12) {                Image(systemName: verified ? "checkmark.shield" : "lock.shield")                    .font(.system(size: 16 * min(look.scale, 1.3)))                    .foregroundStyle(verified ? look.colours.accent : look.colours.dim)                    .frame(width: 24)                    .accessibilityHidden(true)                Text(verbatim: ChatWords.line("safety.title")).font(look.font(16)).foregroundStyle(look.colours.text)                Spacer(minLength: 8)                if verified {                    HStack(spacing: 4) {                        Image(systemName: "checkmark.seal.fill").accessibilityHidden(true)                        Text(verbatim: ChatWords.line("safety.verified")).font(look.font(14, .semibold))                    }                    .foregroundStyle(look.colours.accent)                }            }            .frame(maxWidth: .infinity, minHeight: 48, alignment: .leading)            .contentShape(Rectangle())        }        .buttonStyle(.plain)        .accessibilityIdentifier("chat-person-safety")        .padding(.horizontal, Warm.side)        .padding(.top, 22)    }    /// The row's own Mute or Unmute, with its label (a group's page uses it).    static func muteAct(_ row: ChatListRow) -> ChatSwipe? {        (row.trailing + row.leading).first { $0.act == "mute" || $0.act == "unmute" }    }    private func read() async {        guard let core else { return }        contact = try? await core.call(ChatPeopleMethod.contact, ["thread": row.thread], as: ChatContactAnswer.self)        if contact?.hasPicture == true, let number = contact?.number,           let found = try? await core.call(ChatPeopleMethod.profilePicture, ["number": number, "dir": ChatPeopleFiles.pictures], as: ChatPicturePath.self),           let path = found.path {            picture = await ChatPictures.shared.image(URL(fileURLWithPath: path), side: 200)        }    }    private var top: some View {        VStack(spacing: 6) {            Group {                if let picture {                    Image(uiImage: picture).resizable().scaledToFill()                        .frame(width: 96 * min(look.scale, 1.3), height: 96 * min(look.scale, 1.3))                        .clipShape(Circle())                } else {                    ChatAvatarView(avatar: header?.picture ?? row.picture, side: 96 * min(look.scale, 1.3))                }            }            .accessibilityHidden(true)            Text(verbatim: name)                .font(look.font(26, .bold))                .kerning(-0.3)                .foregroundStyle(look.colours.text)                .multilineTextAlignment(.center)                .accessibilityAddTraits(.isHeader)            if let theirs = contact?.theirName, theirs != name {                Text(verbatim: ChatWords.line("person.their_name", ["name": theirs]))                    .font(look.font(14)).foregroundStyle(look.colours.dim)            } else if let status = header?.status, !status.isEmpty {                Text(verbatim: status).font(look.font(14)).foregroundStyle(look.colours.dim)            }            if let number = contact?.number {                Text(verbatim: number).font(look.font(14)).foregroundStyle(look.colours.faint)            }        }        .frame(maxWidth: .infinity)        .padding(.top, 8)        .padding(.horizontal, Warm.side)    }    /// Message, Call, Video: pills side by side.    private var acts: some View {        HStack(spacing: 10) {            WarmPill(words: ChatWords.line("person.message"), id: "chat-person-message", run: close)            if contact?.blocked != true {                ForEach(header?.calls ?? [], id: \.video) { button in                    WarmPill(words: ChatWords.line(button.video ? "person.video" : "person.call"), id: button.video ? "chat-person-video" : "chat-person-call") {                        calls?.place(thread: row.thread, call: nil, video: button.video) { said in toasts?.show(said, tone: .error) }                    }                }            }        }        .frame(maxWidth: .infinity)        .padding(.top, 12)        .padding(.bottom, 6)    }    /// Cotton did not find them: never said as more certain than that.    private var notYet: some View {        VStack(alignment: .leading, spacing: 8) {            Text(verbatim: ChatWords.line("reach.not_yet")).font(look.font(16, .semibold)).foregroundStyle(look.colours.text)            Text(verbatim: ChatWords.line("reach.waiting")).font(look.font(14)).foregroundStyle(look.colours.dim)                .fixedSize(horizontal: false, vertical: true)            WarmPill(words: ChatWords.line("reach.invite"), id: "chat-person-invite", accent: true) { inviting = true }        }        .padding(16)        .frame(maxWidth: .infinity, alignment: .leading)        .background(RoundedRectangle(cornerRadius: 20, style: .continuous).fill(look.colours.bar))        .padding(.horizontal, Warm.side)        .padding(.top, 14)    }    @ViewBuilder private var between: some View {        let photos = ChatPersonPhotos.of(items)        let counts = contact?.between        let total = counts.map { $0.photos + $0.videos + $0.voice + $0.files + $0.links } ?? 0        VStack(alignment: .leading, spacing: 0) {            WarmHeading(words: ChatWords.line("person.between"))            if photos.isEmpty, total == 0 {                Text(verbatim: ChatWords.line("person.nothing")).font(look.font(15)).foregroundStyle(look.colours.dim)            }            if !photos.isEmpty {                LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 6), count: 3), spacing: 6) {                    ForEach(photos) { photo in ChatPersonPhotoTile(photo: photo, book: book) }                }                .padding(.bottom, 6)            }            if let counts {                if counts.photos > 0 { WarmLine(label: ChatWords.line("person.photos"), said: String(counts.photos)) }                if counts.videos > 0 { WarmLine(label: ChatWords.line("person.videos"), said: String(counts.videos)) }                if counts.voice > 0 { WarmLine(label: ChatWords.line("person.voices"), said: String(counts.voice)) }                if counts.files > 0 { WarmLine(label: ChatWords.line("person.files"), said: String(counts.files)) }                if counts.links > 0 { WarmLine(label: ChatWords.line("person.links"), said: String(counts.links)) }            }        }        .padding(.horizontal, Warm.side)    }    /// Export chat (chat CONTRACT.md "Export"), then Mute (for a time, or Unmute with when it ends), then Block or Unblock.    private var foot: some View {        VStack(alignment: .leading, spacing: 0) {            WarmRow(symbol: "square.and.arrow.up", words: ChatWords.line("export.one"), id: "chat-person-export") {                Task { await ChatExport.share(core, thread: row.thread) { toasts?.show($0, tone: .error) } }            }            if let contact {                if let until = contact.mutedUntil {                    WarmRow(symbol: "bell", words: ChatWords.line("person.unmute"), detail: ChatWhen.said(until),                            id: "chat-person-unmute") { act("unmute", until: nil) }                } else {                    WarmRow(symbol: "bell.slash", words: ChatWords.line("person.mute"), id: "chat-person-mute") { muting = true }                }                if contact.blocked {                    WarmRow(symbol: "hand.raised", words: ChatWords.line("person.unblock"), detail: ChatWords.line("person.blocked"),                            id: "chat-person-unblock") { decide(ChatPeopleMethod.unblock) }                } else {                    WarmRow(symbol: "hand.raised", words: ChatWords.line("person.block"), id: "chat-person-block", danger: true) { blocking = true }                }            }        }        .padding(.horizontal, Warm.side)        .padding(.top, 22)    }    /// The kit's lengths, as `chat.contact` answers them.    private var muteSheet: some View {        VStack(alignment: .leading, spacing: 4) {            Text(verbatim: ChatWords.line("person.mute_for"))                .font(look.font(20, .bold)).foregroundStyle(look.colours.text)                .padding(.bottom, 6)                .accessibilityAddTraits(.isHeader)            ForEach(contact?.mutes ?? [], id: \.self) { mute in                WarmRow(symbol: nil, words: mute.label, id: "chat-person-mute-\(mute.until == nil ? "always" : mute.label)") {                    muting = false                    act("mute", until: mute.until)                }            }        }        .padding(.horizontal, Warm.side)        .padding(.vertical, 18)    }    private func act(_ verb: String, until: String?) {        Task {            var ask = ChatActAsk(act: verb, thread: row.thread)            ask.until = until            if let answer = try? await book.act(ask), let said = answer.said { toasts?.show(said) }            await read()        }    }    private func decide(_ method: String) {        Task {            do {                _ = try await core?.callJSON(method, ["thread": row.thread])            } catch {                toasts?.show(ActionRefused.words(for: error), tone: .error)            }            await read()        }    }}/// One photo between you, square, decoded at its size.private struct ChatPersonPhotoTile: View {    let photo: ChatPersonPhoto    let book: any ChatBook    @State private var image: UIImage?    @Environment(\.chatLook) private var look    var body: some View {        Color.clear            .aspectRatio(1, contentMode: .fit)            .background(look.colours.bar)            .overlay {                if let image {                    Image(uiImage: image).resizable().scaledToFill()                } else if ChatPictureTries.shared.gone.contains(ChatPictureTries.key(photo.message, photo.index)) {                    ChatPictureGone(words: nil)                }            }            .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous))            .accessibilityHidden(true)            .task(id: photo.id) {                guard let url = await ChatPictureTries.shared.url(message: photo.message, index: photo.index, book: book) else { return }                image = await ChatPictures.shared.image(url, side: 120)            }    }}// MARK: the Warm page parts, shared by the person's page, You, a group and New chat/// A section's small capitals heading.struct WarmHeading: View {    let words: String    @Environment(\.chatLook) private var look    var body: some View {        Text(verbatim: words.uppercased())            .font(look.font(12, .semibold))            .kerning(0.7)            .foregroundStyle(look.colours.dim)            .padding(.top, 22)            .padding(.bottom, 8)            .accessibilityAddTraits(.isHeader)            .accessibilityLabel(Text(verbatim: words))    }}/// A line of a page: its name, and what it says at the end, quiet.struct WarmLine: View {    let label: String    let said: String    @Environment(\.chatLook) private var look    var body: some View {        HStack(alignment: .firstTextBaseline) {            Text(verbatim: label).font(look.font(16)).foregroundStyle(look.colours.text)            Spacer(minLength: 12)            Text(verbatim: said).font(look.font(14)).foregroundStyle(look.colours.dim).multilineTextAlignment(.trailing)        }        .frame(maxWidth: .infinity, minHeight: 44)        .accessibilityElement(children: .combine)    }}/// A tappable row: a mark, its words and a quiet line under them.struct WarmRow: View {    let symbol: String?    let words: String    var detail: String? = nil    let id: String    var danger = false    let tap: () -> Void    @Environment(\.chatLook) private var look    var body: some View {        Button(action: tap) {            HStack(spacing: 12) {                if let symbol {                    Image(systemName: symbol)                        .font(.system(size: 16 * min(look.scale, 1.3)))                        .foregroundStyle(danger ? look.colours.danger : look.colours.dim)                        .frame(width: 24)                        .accessibilityHidden(true)                }                VStack(alignment: .leading, spacing: 2) {                    Text(verbatim: words).font(look.font(16)).foregroundStyle(danger ? look.colours.danger : look.colours.text)                    if let detail { Text(verbatim: detail).font(look.font(13)).foregroundStyle(look.colours.dim) }                }                Spacer(minLength: 0)            }            .frame(maxWidth: .infinity, minHeight: 48, alignment: .leading)            .contentShape(Rectangle())        }        .buttonStyle(.plain)        .accessibilityIdentifier(id)    }}/// A pill button: chip-grey, or the accent for the one main act.struct WarmPill: View {    let words: String    let id: String    var accent = false    let run: () -> Void    @Environment(\.chatLook) private var look    var body: some View {        Button(action: run) {            Text(verbatim: words)                .font(look.font(14, .semibold))                .foregroundStyle(accent ? look.colours.onAccent : look.colours.text)                .padding(.horizontal, 16)                .frame(minHeight: 40)                .background(Capsule().fill(accent ? look.colours.accent : look.colours.bar))                .contentShape(Capsule())        }        .buttonStyle(.plain)        .accessibilityIdentifier(id)    }}/// Invite someone: the words Cotton wrote, sent from the person's own phone,/// as a text message or through the share sheet (`chat.invite`). Cotton never/// sends it.struct ChatInviteSheet: View {    let thread: String?    let number: String?    let name: String    let close: () -> Void    @Environment(\.chatLook) private var look    @Environment(\.cottonCore) private var core    @Environment(\.openURL) private var openURL    @Environment(ToastCenter.self) private var toasts: ToastCenter?    @State private var invite: ChatInviteAnswer?    @State private var sharing = false    var body: some View {        VStack(alignment: .leading, spacing: 8) {            Text(verbatim: invite?.name ?? name)                .font(look.font(20, .bold)).foregroundStyle(look.colours.text)                .accessibilityAddTraits(.isHeader)            if let invite {                Text(verbatim: invite.text)                    .font(look.font(15)).foregroundStyle(look.colours.text)                    .padding(14)                    .frame(maxWidth: .infinity, alignment: .leading)                    .background(RoundedRectangle(cornerRadius: 18, style: .continuous).fill(look.colours.bubbleOut))                    .padding(.vertical, 6)                WarmRow(symbol: "message", words: ChatWords.line("reach.text"), id: "chat-invite-sms") {                    if let url = URL(string: invite.sms) { openURL(url) }                    close()                }                ShareLink(item: invite.text) {                    HStack(spacing: 12) {                        Image(systemName: "square.and.arrow.up").foregroundStyle(look.colours.dim).frame(width: 24).accessibilityHidden(true)                        Text(verbatim: ChatWords.line("reach.share")).font(look.font(16)).foregroundStyle(look.colours.text)                        Spacer(minLength: 0)                    }                    .frame(maxWidth: .infinity, minHeight: 48, alignment: .leading)                    .contentShape(Rectangle())                }                .buttonStyle(.plain)                .accessibilityIdentifier("chat-invite-share")            }        }        .padding(.horizontal, Warm.side)        .padding(.vertical, 18)        .task {            var ask: [String: String] = [:]            if let thread { ask["thread"] = thread } else if let number { ask["number"] = number }            do {                invite = try await core?.call(ChatPeopleMethod.invite, ask, as: ChatInviteAnswer.self)            } catch {                toasts?.show(ActionRefused.words(for: error), tone: .error)            }        }    }}#endif