SPB Git

Repository Public

ChatView.swift 24.4 KB 377 lines swift

1import PhotosUI2import QuickLook3import SwiftUI4import UniformTypeIdentifiers56struct ChatView: View {7    @EnvironmentObject var model: AppModel8    let conv: Conv9    @State private var text = ""10    @State private var reply: Message?11    @State private var editing: Message?12    @State private var importing = false13    @State private var photo: PhotosPickerItem?14    @State private var busy = false15    @State private var preview: URL?16    @State private var details = false17    @State private var lastTyping = Date.distantPast18    @FocusState private var focused: Bool1920    var body: some View {21        VStack(spacing: 0) {22            banners23            ScrollViewReader { proxy in24                ScrollView {25                    LazyVStack(spacing: 3) {26                        if model.messages.isEmpty {27                            VStack(spacing: 8) {28                                Image(systemName: "lock.fill").font(.title).foregroundStyle(Theme.accent).frame(width: 64, height: 64).background(Theme.accent.opacity(0.14), in: RoundedRectangle(cornerRadius: 20, style: .continuous))29                                Text(L("This conversation is end-to-end encrypted", "Cette conversation est chiffrée de bout en bout")).font(.headline)30                                Text(L("Only the devices of its members hold the keys.", "Seuls les appareils de ses membres détiennent les clés.")).font(.subheadline).foregroundStyle(.secondary)31                            }.padding(.top, 80).multilineTextAlignment(.center)32                        }33                        ForEach(Array(model.messages.enumerated()), id: \.element.id) { i, m in34                            let prev = i > 0 ? model.messages[i - 1] : nil35                            if prev == nil || !Calendar.current.isDate(prev!.date, inSameDayAs: m.date) {36                                Text(m.date.formatted(.dateTime.weekday(.wide).day().month(.wide))).font(.caption.weight(.semibold)).foregroundStyle(.secondary)37                                    .padding(.horizontal, 12).padding(.vertical, 4).background(.quaternary, in: Capsule()).padding(.top, 12).padding(.bottom, 6)38                            }39                            MessageRow(m: m, group: conv.kind == "group", first: prev?.from != m.from || prev?.kind != "text", onReply: { reply = m; editing = nil; focused = true },40                                       onEdit: { editing = m; reply = nil; text = m.body; focused = true }, onOpen: open, conv: conv.id)41                                .id(m.id)42                        }43                        Color.clear.frame(height: 1).id("end")44                    }.padding(.horizontal, 14).padding(.vertical, 8)45                }46                .defaultScrollAnchor(.bottom)47                .onChange(of: model.messages.last?.id) { _, _ in withAnimation(.snappy) { proxy.scrollTo("end", anchor: .bottom) } }48                .onAppear { proxy.scrollTo("end", anchor: .bottom) }49            }50            if !conv.typing.isEmpty {51                Text("\(conv.typing.joined(separator: ", ")) \(L("is typing…", "écrit…"))").font(.caption).foregroundStyle(.secondary).frame(maxWidth: .infinity, alignment: .leading).padding(.horizontal, 18).padding(.bottom, 2)52            }53            if !conv.left { composer }54        }55        .background {56            ZStack { Rectangle().fill(.background); RadialGradient(colors: [Theme.b.opacity(0.07), .clear], center: .topTrailing, startRadius: 0, endRadius: 700) }.ignoresSafeArea()57        }58        .navigationTitle(conv.title)59        #if os(iOS)60        .navigationBarTitleDisplayMode(.inline)61        #else62        .navigationSubtitle(subtitle)63        #endif64        .toolbar { ToolbarItem(placement: .primaryAction) { Button { details = true } label: { Label(L("Details", "Détails"), systemImage: "info.circle") } } }65        .sheet(isPresented: $details) { DetailsSheet(conv: conv).environmentObject(model) }66        .fileImporter(isPresented: $importing, allowedContentTypes: [.item], allowsMultipleSelection: true) { result in67            guard case .success(let urls) = result else { return }68            for u in urls { sendFile(url: u) }69        }70        .onChange(of: photo) { _, item in71            guard let item else { return }72            photo = nil73            Task {74                if let data = try? await item.loadTransferable(type: Data.self) {75                    let type = item.supportedContentTypes.first76                    await upload(data, name: "photo.\(type?.preferredFilenameExtension ?? "jpg")", mime: type?.preferredMIMEType ?? "image/jpeg")77                }78            }79        }80        .dropDestination(for: URL.self) { urls, _ in urls.forEach(sendFile); return !urls.isEmpty }81        .quickLookPreview($preview)82    }8384    private var subtitle: String {85        (conv.kind == "group" ? "\(conv.members.count) \(L("members", "membres")) · " : "") + L("End-to-end encrypted", "Chiffré de bout en bout")86    }8788    @ViewBuilder private var banners: some View {89        VStack(spacing: 6) {90            ForEach(conv.warnings) { w in91                Banner(icon: "exclamationmark.triangle.fill", tint: .orange, text: L("The security key of \(w.name) has changed. Verify with them before you continue.", "La clé de sécurité de \(w.name) a changé. Vérifiez avec cette personne avant de continuer."),92                       action: w.canAccept == true ? (L("Accept new key", "Accepter la nouvelle clé"), { model.run { try await model.host.call("acceptKey", w.id) } }) : nil)93            }94            ForEach(conv.missing) { u in95                Banner(icon: "key.fill", tint: Theme.accent, text: L("\(u.name) currently holds no key for this conversation and cannot read it.", "\(u.name) ne détient actuellement aucune clé pour cette conversation et ne peut pas la lire."),96                       action: (L("Add them back", "Réintégrer"), { model.run { try await model.host.call("reAdd", conv.id, u.id) } }))97            }98            if conv.waiting { Banner(icon: "hourglass", tint: Theme.accent, text: L("Waiting for another member's device to share the encryption keys with this device…", "En attente qu’un appareil d’un autre membre partage les clés de chiffrement avec cet appareil…"), action: nil) }99            if conv.left { Banner(icon: "person.fill.xmark", tint: .secondary, text: L("You are no longer a member of this conversation.", "Vous ne faites plus partie de cette conversation."), action: nil) }100        }.padding(.horizontal, 12).padding(.top, conv.warnings.isEmpty && conv.missing.isEmpty && !conv.waiting && !conv.left ? 0 : 8)101    }102103    private var composer: some View {104        VStack(spacing: 6) {105            if let r = reply ?? editing {106                HStack {107                    Image(systemName: editing != nil ? "pencil" : "arrowshape.turn.up.left.fill").foregroundStyle(Theme.accent)108                    Text(editing != nil ? L("Editing message", "Modification du message") : "\(r.fromName) · \(r.body.isEmpty ? (r.files.first?.name ?? "") : r.body)").font(.subheadline).lineLimit(1)109                    Spacer()110                    Button { if editing != nil { text = "" }; reply = nil; editing = nil } label: { Image(systemName: "xmark.circle.fill").foregroundStyle(.secondary) }.buttonStyle(.plain).accessibilityLabel(L("Cancel", "Annuler"))111                }.padding(.horizontal, 12).padding(.vertical, 8).background(.quaternary, in: RoundedRectangle(cornerRadius: 12, style: .continuous))112            }113            HStack(alignment: .bottom, spacing: 6) {114                Menu {115                    PhotosPicker(selection: $photo, matching: .any(of: [.images, .videos])) { Label(L("Photo or video", "Photo ou vidéo"), systemImage: "photo") }116                    Button { importing = true } label: { Label(L("File", "Fichier"), systemImage: "doc") }117                } label: { Image(systemName: "paperclip").font(.title3).frame(width: 36, height: 36) }118                    .menuStyle(.borderlessButton).menuIndicator(.hidden).fixedSize().disabled(conv.waiting || editing != nil).accessibilityLabel(L("Attach", "Joindre"))119                TextField(conv.waiting ? L("Waiting for keys…", "En attente des clés…") : "Message", text: $text, axis: .vertical)120                    .lineLimit(1...8).textFieldStyle(.plain).focused($focused).disabled(conv.waiting).padding(.vertical, 8)121                    .onSubmit { send() }122                    .onChange(of: text) { _, v in123                        if !v.isEmpty, Date.now.timeIntervalSince(lastTyping) > 3 { lastTyping = .now; Task { _ = try? await model.host.call("typing", conv.id) } }124                    }125                Button(action: send) {126                    Group { if busy { ProgressView().controlSize(.small) } else { Image(systemName: editing != nil ? "checkmark" : "arrow.up").font(.body.weight(.bold)) } }127                        .foregroundStyle(Theme.ink).frame(width: 36, height: 36).background(Theme.gradient, in: Circle())128                }.buttonStyle(.plain).disabled(text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || busy || conv.waiting).opacity(text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? 0.4 : 1)129                    .keyboardShortcut(.return, modifiers: .command).accessibilityLabel(L("Send", "Envoyer"))130            }131            .padding(.horizontal, 8).padding(.vertical, 4)132            .background(.regularMaterial, in: RoundedRectangle(cornerRadius: 24, style: .continuous))133            .overlay(RoundedRectangle(cornerRadius: 24, style: .continuous).stroke(focused ? Theme.accent.opacity(0.6) : Color.secondary.opacity(0.25)))134        }.padding(.horizontal, 12).padding(.bottom, 10).padding(.top, 4)135    }136137    private func send() {138        let body = text.trimmingCharacters(in: .whitespacesAndNewlines)139        guard !body.isEmpty else { return }140        let r = reply, e = editing141        text = ""; reply = nil; editing = nil142        model.run {143            if let e { if body != e.body { try await model.host.call("edit", conv.id, e.id, body) } }144            else { try await model.host.call("send", conv.id, body, r?.id ?? NSNull() as Any) }145        }146    }147    private func sendFile(url: URL) {148        let scoped = url.startAccessingSecurityScopedResource()149        defer { if scoped { url.stopAccessingSecurityScopedResource() } }150        guard let data = try? Data(contentsOf: url) else { return }151        let mime = UTType(filenameExtension: url.pathExtension)?.preferredMIMEType ?? "application/octet-stream"152        Task { await upload(data, name: url.lastPathComponent, mime: mime) }153    }154    private func upload(_ data: Data, name: String, mime: String) async {155        guard data.count <= 200 * 1024 * 1024 else { model.toast = L("Files above 200 MB must be sent from the web application.", "Les fichiers de plus de 200 Mo doivent être envoyés depuis l’application web."); return }156        busy = true157        defer { busy = false }158        do { try await model.host.call("sendFile", conv.id, name, mime, data.base64EncodedString(), "") } catch { model.toast = error.localizedDescription }159    }160    /// Decrypts an attachment into the app's temporary folder and shows it with Quick Look.161    private func open(_ a: Attachment) {162        model.run {163            guard let b64 = try await model.host.call("fetchFile", a.ref) as? String, let data = Data(base64Encoded: b64) else { return }164            let dir = FileManager.default.temporaryDirectory.appendingPathComponent("spm-\(a.id)", isDirectory: true)165            try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)166            let url = dir.appendingPathComponent(a.name.replacingOccurrences(of: "/", with: "_"))167            try data.write(to: url, options: .completeFileProtection)168            preview = url169        }170    }171}172173struct Banner: View {174    let icon: String, tint: Color, text: String175    let action: (String, () -> Void)?176    var body: some View {177        HStack(alignment: .top, spacing: 10) {178            Image(systemName: icon).foregroundStyle(tint)179            Text(text).font(.footnote).frame(maxWidth: .infinity, alignment: .leading)180            if let action { Button(action.0, action: action.1).font(.footnote.weight(.semibold)) }181        }.padding(11).background(tint.opacity(0.13), in: RoundedRectangle(cornerRadius: 14, style: .continuous))182    }183}184185struct MessageRow: View {186    @EnvironmentObject var model: AppModel187    let m: Message188    let group: Bool189    let first: Bool190    let onReply: () -> Void191    let onEdit: () -> Void192    let onOpen: (Attachment) -> Void193    let conv: String194    private let quick = ["👍", "❤️", "😂", "😮", "😢", "🙏"]195196    var body: some View {197        if m.kind != "text" {198            Text(systemText).font(.caption).foregroundStyle(.secondary).multilineTextAlignment(.center).padding(.vertical, 6).frame(maxWidth: .infinity)199        } else {200            HStack(alignment: .bottom, spacing: 8) {201                if m.mine { Spacer(minLength: 48) }202                if group && !m.mine { if first { Avatar(id: m.from, name: m.fromName, size: 28) } else { Color.clear.frame(width: 28, height: 1) } }203                VStack(alignment: m.mine ? .trailing : .leading, spacing: 3) {204                    if group && !m.mine && first { Text(m.fromName).font(.caption.weight(.semibold)).foregroundStyle(.secondary).padding(.leading, 4) }205                    bubble206                    if !m.reactions.isEmpty {207                        HStack(spacing: 4) {208                            ForEach(m.reactions) { r in209                                Button { model.run { try await model.host.call("react", conv, m.id, r.emoji) } } label: {210                                    Text(r.count > 1 ? "\(r.emoji) \(r.count)" : r.emoji).font(.footnote).padding(.horizontal, 8).padding(.vertical, 3)211                                        .background(r.mine ? AnyShapeStyle(Theme.accent.opacity(0.18)) : AnyShapeStyle(.quaternary), in: Capsule())212                                        .overlay(Capsule().stroke(r.mine ? Theme.accent : .clear))213                                }.buttonStyle(.plain)214                            }215                        }216                    }217                }218                if !m.mine { Spacer(minLength: 48) }219            }220            .padding(.top, first ? 8 : 0)221            .frame(maxWidth: .infinity, alignment: m.mine ? .trailing : .leading)222        }223    }224225    private var bubble: some View {226        VStack(alignment: .trailing, spacing: 4) {227        VStack(alignment: .leading, spacing: 5) {228            if let f = m.fwd { Label("\(L("Forwarded from", "Transféré de")) \(f)", systemImage: "arrowshape.turn.up.right.fill").font(.caption).italic().opacity(0.75) }229            if let r = m.reply {230                (Text(r.name).bold() + Text(" · \(r.excerpt)")).font(.footnote).lineLimit(1).padding(.horizontal, 9).padding(.vertical, 5)231                    .background(.black.opacity(0.1), in: RoundedRectangle(cornerRadius: 10, style: .continuous))232            }233            if m.deleted { Text(L("Message deleted", "Message supprimé")).italic().opacity(0.6) }234            else {235                ForEach(m.files) { a in AttachmentView(a: a, mine: m.mine).onTapGesture { onOpen(a) } }236                if !m.body.isEmpty { Text(linkified).textSelection(.enabled) }237            }238        }239            HStack(spacing: 4) {240                if m.untrusted { Image(systemName: "exclamationmark.triangle.fill") }241                if m.pinned { Image(systemName: "pin.fill") }242                if m.edited && !m.deleted { Text(L("edited", "modifié")) }243                Text(m.date.formatted(date: .omitted, time: .shortened))244                if m.mine {245                    Image(systemName: m.status == "failed" ? "exclamationmark.circle.fill" : m.seq == 0 ? "clock" : m.receipt == 2 ? "checkmark.circle.fill" : m.receipt == 1 ? "checkmark.circle" : "checkmark")246                        .accessibilityLabel(m.status == "failed" ? L("Not sent", "Non envoyé") : m.seq == 0 ? L("Sending", "Envoi") : m.receipt == 2 ? L("Read", "Lu") : m.receipt == 1 ? L("Delivered", "Distribué") : L("Sent", "Envoyé"))247                }248            }.font(.caption2).opacity(0.65)249        }250        .fixedSize(horizontal: false, vertical: true)251        .padding(.horizontal, 12).padding(.vertical, 8)252        .foregroundStyle(m.mine ? AnyShapeStyle(Theme.ink) : AnyShapeStyle(.primary))253        .background(m.mine ? AnyShapeStyle(Theme.bubble) : AnyShapeStyle(.regularMaterial), in: UnevenRoundedRectangle(topLeadingRadius: m.mine ? 19 : 7, bottomLeadingRadius: 19, bottomTrailingRadius: 19, topTrailingRadius: m.mine ? 7 : 19, style: .continuous))254        .frame(maxWidth: 520, alignment: m.mine ? .trailing : .leading)255        .contextMenu {256            if !m.deleted {257                ControlGroup { ForEach(quick, id: \.self) { e in Button(e) { model.run { try await model.host.call("react", conv, m.id, e) } } } }258                Button(action: onReply) { Label(L("Reply", "Répondre"), systemImage: "arrowshape.turn.up.left") }259                if !m.body.isEmpty { Button { copy(m.body) } label: { Label(L("Copy", "Copier"), systemImage: "doc.on.doc") } }260                Button { model.run { try await model.host.call("pin", conv, m.id, !m.pinned) } } label: { Label(m.pinned ? L("Unpin", "Désépingler") : L("Pin", "Épingler"), systemImage: "pin") }261                if m.mine && !m.body.isEmpty { Button(action: onEdit) { Label(L("Edit", "Modifier"), systemImage: "pencil") } }262                if m.mine { Button(role: .destructive) { model.run { try await model.host.call("remove", conv, m.id) } } label: { Label(L("Delete for everyone", "Supprimer pour tous"), systemImage: "trash") } }263            }264        }265    }266267    private var linkified: AttributedString {268        var s = AttributedString(m.body)269        if let det = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) {270            for match in det.matches(in: m.body, range: NSRange(m.body.startIndex..., in: m.body)) {271                guard let url = match.url, url.scheme == "https" || url.scheme == "http", let r = Range(match.range, in: m.body), let ar = Range(r, in: s) else { continue }272                s[ar].link = url273                s[ar].underlineStyle = .single274            }275        }276        return s277    }278    private var systemText: String {279        guard let s = m.sys else { return "" }280        let who = m.mine ? L("You", "Vous") : m.fromName, names = s.users.joined(separator: ", ")281        switch s.type {282        case "added": return "\(who) \(L("added", "a ajouté")) \(names)"283        case "removed": return "\(who) \(L("removed", "a retiré")) \(names)"284        case "device": return L("A new device was added for \(names)", "Un nouvel appareil a été ajouté pour \(names)")285        case "renamed": return "\(who) \(L("named the group", "a nommé le groupe")) « \(s.text) »"286        case "ttl": return Int(s.text) ?? 0 > 0 ? "\(who) \(L("turned on disappearing messages", "a activé les messages éphémères"))" : "\(who) \(L("turned off disappearing messages", "a désactivé les messages éphémères"))"287        case "call": return (s.video ? "📹 " + L("Video call", "Appel vidéo") : "📞 " + L("Voice call", "Appel vocal")) + " · " + m.date.formatted(date: .omitted, time: .shortened)288        default: return ""289        }290    }291    private func copy(_ s: String) {292        #if os(macOS)293        NSPasteboard.general.clearContents(); NSPasteboard.general.setString(s, forType: .string)294        #else295        UIPasteboard.general.string = s296        #endif297    }298}299300struct AttachmentView: View {301    let a: Attachment302    let mine: Bool303    var body: some View {304        if a.isVisual, let data = Data(base64Encoded: a.thumb), let img = platformImage(data) {305            img.resizable().aspectRatio(contentMode: .fill)306                .frame(width: 240, height: min(320, max(120, 240 * CGFloat(a.h > 0 && a.w > 0 ? a.h / a.w : 0.75)))).clipShape(RoundedRectangle(cornerRadius: 14, style: .continuous))307                .overlay { if a.mime.hasPrefix("video/") { Image(systemName: "play.circle.fill").font(.system(size: 44)).foregroundStyle(.white).shadow(radius: 6) } }308                .accessibilityLabel(a.name)309        } else {310            HStack(spacing: 10) {311                Image(systemName: a.voice || a.mime.hasPrefix("audio/") ? "waveform" : a.mime.hasPrefix("video/") ? "film" : "doc.fill").frame(width: 38, height: 38).background(.black.opacity(0.12), in: RoundedRectangle(cornerRadius: 11, style: .continuous))312                VStack(alignment: .leading, spacing: 1) {313                    Text(a.voice ? L("Voice message", "Message vocal") : a.name).font(.subheadline.weight(.semibold)).lineLimit(1)314                    Text(ByteCountFormatter.string(fromByteCount: Int64(a.size), countStyle: .file)).font(.caption2).opacity(0.7)315                }316                Spacer(minLength: 8)317                Image(systemName: "arrow.down.circle").opacity(0.7)318            }.frame(minWidth: 200).contentShape(Rectangle())319        }320    }321    private func platformImage(_ d: Data) -> Image? {322        #if os(macOS)323        return NSImage(data: d).map(Image.init(nsImage:))324        #else325        return UIImage(data: d).map(Image.init(uiImage:))326        #endif327    }328}329330struct DetailsSheet: View {331    @EnvironmentObject var model: AppModel332    @Environment(\.dismiss) private var dismiss333    let conv: Conv334    @State private var safety: [String: String] = [:]335    private let ttls = [0, 300, 3600, 86400, 604800, 2592000]336    var body: some View {337        NavigationStack {338            Form {339                Section(L("Security", "Sécurité")) {340                    Label(L("End-to-end encrypted with MLS (RFC 9420) · epoch \(conv.epoch) · \(conv.devices) devices", "Chiffré de bout en bout avec MLS (RFC 9420) · époque \(conv.epoch) · \(conv.devices) appareils"), systemImage: "lock.fill")341                    Picker(L("Disappearing messages", "Messages éphémères"), selection: Binding(get: { conv.ttl }, set: { v in model.run { try await model.host.call("setTtl", conv.id, v) } })) {342                        ForEach(ttls, id: \.self) { s in Text(s == 0 ? L("Off", "Désactivé") : s < 3600 ? "\(s / 60) min" : s < 86400 ? "\(s / 3600) h" : "\(s / 86400) \(L("days", "jours"))").tag(s) }343                    }.disabled(conv.waiting)344                    Toggle(L("Mute notifications", "Couper les notifications"), isOn: Binding(get: { conv.muted }, set: { v in model.run { try await model.host.call("setMuted", conv.id, v) } }))345                }346                Section(conv.kind == "group" ? L("Members", "Membres") : L("Contact", "Contact")) {347                    ForEach(conv.members) { m in348                        VStack(alignment: .leading, spacing: 8) {349                            HStack(spacing: 10) {350                                Avatar(id: m.id, name: m.name, size: 34)351                                Text(m.name + (m.me ? " (\(L("you", "vous")))" : ""))352                                Spacer()353                                if m.verified { Label(L("Verified", "Vérifié"), systemImage: "checkmark.shield.fill").labelStyle(.iconOnly).foregroundStyle(.green) }354                                if !m.me { Button(L("Verify", "Vérifier")) { model.run { safety[m.id] = try await model.host.call("safety", m.id) as? String ?? "" } } }355                            }356                            if let n = safety[m.id], !n.isEmpty {357                                Text(n).font(.system(.callout, design: .monospaced)).textSelection(.enabled)358                                Text(L("Compare this number with the one shown on their device. If identical, nobody is impersonating either of you.", "Comparez ce numéro avec celui affiché sur son appareil. S’ils sont identiques, personne n’usurpe l’identité de l’un de vous.")).font(.footnote).foregroundStyle(.secondary)359                                Button(m.verified ? L("Remove verification", "Retirer la vérification") : L("Mark as verified", "Marquer comme vérifié")) { model.run { try await model.host.call("setVerified", m.id, !m.verified); await model.refresh() } }360                            }361                        }362                    }363                }364                if conv.kind == "group" && !conv.left {365                    Section { Button(L("Leave the group", "Quitter le groupe"), role: .destructive) { model.run { try await model.host.call("leave", conv.id); dismiss() } } }366                }367            }368            .formStyle(.grouped)369            .navigationTitle(conv.title)370            .toolbar { ToolbarItem(placement: .confirmationAction) { Button(L("Done", "OK")) { dismiss() } } }371        }372        #if os(macOS)373        .frame(width: 500, height: 560)374        #endif375    }376}377
Files main
Menu

Theme