Repository Public
1import SwiftUI23struct MainView: View {4 @EnvironmentObject var model: AppModel5 @State private var query = ""6 @State private var newChat = false7 @State private var settings = false8 @State private var hits: [SearchHit] = []910 var body: some View {11 NavigationSplitView {12 List(selection: $model.open) {13 if !model.snap.online {14 Label(L("Offline. Messages are kept and sent on reconnection.", "Hors ligne. Les messages sont conservés et envoyés à la reconnexion."), systemImage: "wifi.slash").font(.footnote).foregroundStyle(.orange)15 }16 ForEach(filtered) { c in ConvRow(c: c).tag(c.id) }17 if query.count >= 2 && !hits.isEmpty {18 Section(L("Messages", "Messages")) {19 ForEach(hits) { h in20 Button { model.open = h.conv } label: {21 VStack(alignment: .leading, spacing: 2) {22 Text("\(h.from) · \(h.title)").font(.caption).foregroundStyle(.secondary)23 Text(h.body).lineLimit(2)24 }25 }.buttonStyle(.plain)26 }27 }28 }29 }30 .listStyle(.sidebar)31 .overlay {32 if model.snap.convs.isEmpty {33 ContentUnavailableView { Label(L("No conversation yet", "Aucune conversation"), systemImage: "bubble.left.and.bubble.right") } description: { Text(L("Start one with someone from your private network.", "Commencez-en une avec une personne de votre réseau privé.")) } actions: { Button(L("New conversation", "Nouvelle conversation")) { newChat = true } }34 }35 }36 .searchable(text: $query, prompt: L("Search messages and people", "Chercher messages et personnes"))37 .onChange(of: query) { _, q in38 Task { hits = q.count >= 2 ? ((try? await model.host.call("search", q) as? String).flatMap { try? JSONDecoder().decode([SearchHit].self, from: Data($0.utf8)) } ?? []) : [] }39 }40 .navigationTitle(L("Chats", "Discussions"))41 #if os(macOS)42 .navigationSplitViewColumnWidth(min: 260, ideal: 320, max: 420)43 #endif44 .toolbar {45 ToolbarItem(placement: .primaryAction) { Button { newChat = true } label: { Label(L("New conversation", "Nouvelle conversation"), systemImage: "square.and.pencil") }.keyboardShortcut("n", modifiers: .command) }46 ToolbarItem(placement: .automatic) { Button { settings = true } label: { Label(L("Settings", "Réglages"), systemImage: "gearshape") }.keyboardShortcut(",", modifiers: .command) }47 }48 } detail: {49 if let id = model.open, let c = model.snap.convs.first(where: { $0.id == id }) {50 ChatView(conv: c).id(id)51 } else {52 ContentUnavailableView { Label(L("Select a conversation", "Choisissez une conversation"), systemImage: "lock.fill") } description: { Text(L("Everything you send is encrypted on this device before it leaves.", "Tout ce que vous envoyez est chiffré sur cet appareil avant d’en sortir.")) }53 }54 }55 .sheet(isPresented: $newChat) { NewChatSheet().environmentObject(model) }56 .sheet(isPresented: $settings) { SettingsSheet().environmentObject(model) }57 .sheet(item: Binding(get: { model.snap.pending.first }, set: { _ in })) { d in DeviceApprovalSheet(device: d).environmentObject(model).interactiveDismissDisabled() }58 }5960 private var filtered: [Conv] {61 query.isEmpty ? model.snap.convs : model.snap.convs.filter { $0.title.localizedCaseInsensitiveContains(query) }62 }63}6465struct SearchHit: Decodable, Identifiable { let id, conv, title, from, body: String }6667struct ConvRow: View {68 let c: Conv69 var body: some View {70 HStack(spacing: 12) {71 Avatar(id: c.peer.isEmpty ? c.id : c.peer, name: c.title, size: 44)72 .overlay(alignment: .bottomTrailing) { if c.online { Circle().fill(.green).frame(width: 11, height: 11).overlay(Circle().stroke(.background, lineWidth: 2)) } }73 VStack(alignment: .leading, spacing: 3) {74 HStack {75 Text(c.title).font(.headline).lineLimit(1)76 Spacer(minLength: 4)77 if c.muted { Image(systemName: "bell.slash.fill").font(.caption2).foregroundStyle(.tertiary) }78 Text(shortTime(Date(timeIntervalSince1970: c.lastTs / 1000))).font(.caption).foregroundStyle(.tertiary)79 }80 HStack {81 Group {82 if !c.typing.isEmpty { Text(L("typing…", "écrit…")).foregroundStyle(Theme.accent) }83 else if c.waiting { Text(L("Waiting for keys…", "En attente des clés…")) }84 else { Text(c.preview.isEmpty ? L("No messages yet", "Aucun message") : c.preview) }85 }.font(.subheadline).foregroundStyle(.secondary).lineLimit(1)86 Spacer(minLength: 4)87 if !c.warnings.isEmpty { Image(systemName: "exclamationmark.triangle.fill").font(.caption).foregroundStyle(.orange) }88 if c.unread > 0 { Text("\(c.unread)").font(.caption2.bold()).foregroundStyle(Theme.ink).padding(.horizontal, 7).padding(.vertical, 2).background(Theme.gradient, in: Capsule()) }89 }90 }91 }.padding(.vertical, 4)92 }93}9495struct NewChatSheet: View {96 @EnvironmentObject var model: AppModel97 @Environment(\.dismiss) private var dismiss98 @State private var people: [Contact]?99 @State private var picked = Set<String>()100 @State private var name = ""101 @State private var busy = false102 var body: some View {103 NavigationStack {104 List {105 if picked.count > 1 { TextField(L("Group name", "Nom du groupe"), text: $name) }106 ForEach(people ?? []) { p in107 Button { if picked.contains(p.id) { picked.remove(p.id) } else { picked.insert(p.id) } } label: {108 HStack(spacing: 12) {109 Avatar(id: p.id, name: p.name, size: 38)110 VStack(alignment: .leading) { Text(p.name).font(.headline); Text("@\(p.handle)").font(.caption).foregroundStyle(.secondary) }111 Spacer()112 if p.verified { Image(systemName: "checkmark.shield.fill").foregroundStyle(.green) }113 Image(systemName: picked.contains(p.id) ? "checkmark.circle.fill" : "circle").foregroundStyle(picked.contains(p.id) ? Theme.accent : .secondary)114 }.contentShape(Rectangle())115 }.buttonStyle(.plain)116 }117 }118 .overlay {119 if people == nil { ProgressView() }120 else if people?.isEmpty == true { ContentUnavailableView(L("Nobody else yet", "Personne d’autre pour l’instant"), systemImage: "person.2", description: Text(L("People appear here once they accepted an invitation.", "Les personnes apparaissent ici après avoir accepté une invitation."))) }121 }122 .navigationTitle(L("New conversation", "Nouvelle conversation"))123 #if os(iOS)124 .navigationBarTitleDisplayMode(.inline)125 #endif126 .toolbar {127 ToolbarItem(placement: .cancellationAction) { Button(L("Cancel", "Annuler")) { dismiss() } }128 ToolbarItem(placement: .confirmationAction) {129 Button(picked.count > 1 ? L("Create group", "Créer le groupe") : L("Start", "Commencer")) {130 busy = true131 model.run {132 defer { busy = false }133 if let id = try await model.host.call("create", Array(picked), picked.count > 1 && !name.isEmpty ? name : NSNull() as Any) as? String { model.open = id; dismiss() }134 }135 }.disabled(picked.isEmpty || busy)136 }137 }138 .task { people = (try? await model.host.call("directory") as? String).flatMap { try? JSONDecoder().decode([Contact].self, from: Data($0.utf8)) } ?? [] }139 }140 #if os(macOS)141 .frame(width: 440, height: 520)142 #endif143 }144}145146struct DeviceApprovalSheet: View {147 @EnvironmentObject var model: AppModel148 let device: PendingDevice149 var body: some View {150 VStack(alignment: .leading, spacing: 16) {151 Text(L("A new device wants to join your account", "Un nouvel appareil veut rejoindre votre compte")).font(.title2.bold())152 Text(L("Someone signed in with your passkey on “\(device.label)”. Approve only if it is you and if that device shows exactly this code:", "Quelqu’un s’est connecté avec votre clé d’accès sur « \(device.label) ». N’approuvez que s’il s’agit de vous et si cet appareil affiche exactement ce code :")).foregroundStyle(.secondary)153 Text("\(device.code.prefix(3)) \(device.code.suffix(3))").font(.system(size: 38, weight: .bold, design: .monospaced)).frame(maxWidth: .infinity).padding(20)154 .background(.quaternary, in: RoundedRectangle(cornerRadius: 18, style: .continuous))155 HStack {156 Button(L("Refuse", "Refuser")) { model.run { try await model.host.call("reject", device.id) } }.buttonStyle(SoftButton())157 Button(L("Codes match: approve", "Les codes concordent : approuver")) { model.run { try await model.host.call("approve", device.id) } }.buttonStyle(PrimaryButton())158 }159 }.padding(24).frame(minWidth: 320, idealWidth: 460)160 }161}162163struct SettingsSheet: View {164 @EnvironmentObject var model: AppModel165 @Environment(\.dismiss) private var dismiss166 @State private var devices: [DeviceRow] = []167 @State private var fingerprint = ""168 @State private var newKey: String?169 @State private var confirmWipe = false170 var body: some View {171 NavigationStack {172 Form {173 if let me = model.snap.me {174 Section { HStack(spacing: 12) { Avatar(id: me.id, name: me.name, size: 48); VStack(alignment: .leading) { Text(me.name).font(.headline); Text("@\(me.handle)").foregroundStyle(.secondary) } } }175 }176 Section(L("Privacy", "Confidentialité")) {177 Toggle(L("Read receipts", "Accusés de lecture"), isOn: pref(\.readReceipts, "readReceipts"))178 Toggle(L("Notifications (never show message text)", "Notifications (jamais le texte du message)"), isOn: pref(\.notify, "notify"))179 Toggle(L("Reduce large photos before sending", "Réduire les grandes photos avant l’envoi"), isOn: pref(\.compress, "compress"))180 }181 Section(L("Trusted devices", "Appareils de confiance")) {182 ForEach(devices) { d in183 HStack {184 Image(systemName: "laptopcomputer.and.iphone").foregroundStyle(.secondary)185 VStack(alignment: .leading) { Text(d.label); Text(d.current ? L("this device", "cet appareil") : d.status == "pending" ? L("waiting for approval", "en attente d’approbation") : (d.enrolled_via ?? "")).font(.caption).foregroundStyle(.secondary) }186 Spacer()187 if !d.current { Button(L("Remove", "Retirer"), role: .destructive) { model.run { try await model.host.call("removeDevice", d.id); await load() } } }188 }189 }190 }191 Section(L("Security", "Sécurité")) {192 LabeledContent(L("Identity key fingerprint", "Empreinte de la clé d’identité")) { Text(fingerprint).font(.system(.caption, design: .monospaced)).textSelection(.enabled) }193 Button(L("Generate a new recovery key", "Générer une nouvelle clé de récupération")) { model.run { newKey = try await model.host.call("newRecoveryKey") as? String } }194 Text(L("Administration (invitations, accounts) and calls are available in the web application.", "L’administration (invitations, comptes) et les appels sont disponibles dans l’application web.")).font(.footnote).foregroundStyle(.secondary)195 }196 Section {197 Button(L("Sign out", "Se déconnecter")) { Task { dismiss(); await model.signOut(wipe: false) } }198 Button(L("Sign out and erase this device", "Se déconnecter et effacer cet appareil"), role: .destructive) { confirmWipe = true }199 }200 }201 .formStyle(.grouped)202 .navigationTitle(L("Settings", "Réglages"))203 .toolbar { ToolbarItem(placement: .confirmationAction) { Button(L("Done", "OK")) { dismiss() } } }204 .task { await load() }205 .alert(L("New recovery key", "Nouvelle clé de récupération"), isPresented: Binding(get: { newKey != nil }, set: { if !$0 { newKey = nil } })) { Button("OK") {} } message: { Text((newKey ?? "") + "\n\n" + L("Store it now: it will not be shown again. The previous key no longer works.", "Rangez-la maintenant : elle ne sera plus affichée. L’ancienne clé ne fonctionne plus.")) }206 .confirmationDialog(L("This device will be removed from your account and its message history erased.", "Cet appareil sera retiré de votre compte et son historique effacé."), isPresented: $confirmWipe, titleVisibility: .visible) {207 Button(L("Erase and sign out", "Effacer et se déconnecter"), role: .destructive) { Task { dismiss(); await model.signOut(wipe: true) } }208 }209 }210 #if os(macOS)211 .frame(width: 520, height: 620)212 #endif213 }214 private func load() async {215 devices = (try? await model.host.call("devices") as? String).flatMap { try? JSONDecoder().decode([DeviceRow].self, from: Data($0.utf8)) } ?? []216 fingerprint = (try? await model.host.call("myFingerprint") as? String) ?? ""217 }218 private func pref(_ kp: KeyPath<Prefs, Bool>, _ name: String) -> Binding<Bool> {219 Binding(get: { model.snap.prefs?[keyPath: kp] ?? true }, set: { v in model.run { try await model.host.call("setPref", name, v); await model.refresh() } })220 }221}222