Repository Public
1import SwiftUI2import WebKit34/// Keeps the engine's script context attached to the window so the system never suspends it while the app is visible.5struct EngineAnchor: View {6 let webView: WKWebView7 var body: some View { Rep(webView: webView).frame(width: 1, height: 1).opacity(0.01).allowsHitTesting(false).accessibilityHidden(true) }8 #if os(macOS)9 struct Rep: NSViewRepresentable {10 let webView: WKWebView11 func makeNSView(context: Context) -> WKWebView { webView }12 func updateNSView(_ v: WKWebView, context: Context) {}13 }14 #else15 struct Rep: UIViewRepresentable {16 let webView: WKWebView17 func makeUIView(context: Context) -> WKWebView { webView }18 func updateUIView(_ v: WKWebView, context: Context) {}19 }20 #endif21}2223struct RootView: View {24 @EnvironmentObject var model: AppModel25 var body: some View {26 ZStack {27 EngineAnchor(webView: model.host.webView)28 switch model.phase {29 case .loading: Stage { ProgressView() }30 case .anon: SignInView()31 case .first: FirstDeviceView()32 case .recoveryKey(let key): RecoveryKeyView(key: key)33 case .link: LinkDeviceView()34 case .pending: PendingView()35 case .ready: MainView()36 case .failed(let message):37 Stage {38 Text(L("Something went wrong", "Un problème est survenu")).font(.largeTitle.bold())39 Text(message).foregroundStyle(.secondary)40 Button(L("Try again", "Réessayer")) { Task { await model.boot() } }.buttonStyle(PrimaryButton())41 }42 }43 }44 .overlay(alignment: .top) {45 if let t = model.toast {46 Text(t).font(.callout).padding(.horizontal, 16).padding(.vertical, 11)47 .background(.regularMaterial, in: RoundedRectangle(cornerRadius: 16, style: .continuous))48 .shadow(color: .black.opacity(0.2), radius: 18, y: 8).padding(.top, 12).padding(.horizontal, 16)49 .transition(.move(edge: .top).combined(with: .opacity))50 .task(id: t) { try? await Task.sleep(for: .seconds(4.5)); withAnimation { model.toast = nil } }51 .accessibilityAddTraits(.isStaticText)52 }53 }54 .animation(.snappy, value: model.toast)55 }56}5758struct Stage<Content: View>: View {59 @ViewBuilder var content: Content60 var body: some View {61 ScrollView {62 VStack(alignment: .leading, spacing: 18) {63 HStack(spacing: 12) { Logo(size: 46); Text("SP Message").font(.title3.bold()) }64 content65 }66 .frame(maxWidth: 440, alignment: .leading).padding(28).frame(maxWidth: .infinity)67 }68 .scrollBounceBehavior(.basedOnSize)69 .frame(maxWidth: .infinity, maxHeight: .infinity)70 .background {71 ZStack {72 Rectangle().fill(.background)73 RadialGradient(colors: [Theme.a.opacity(0.22), .clear], center: .topTrailing, startRadius: 0, endRadius: 620)74 RadialGradient(colors: [Theme.c.opacity(0.16), .clear], center: .bottomLeading, startRadius: 0, endRadius: 620)75 }.ignoresSafeArea()76 }77 }78}7980struct Point: View {81 let icon: String, title: String, text: String82 var body: some View {83 HStack(alignment: .top, spacing: 13) {84 Image(systemName: icon).font(.body.weight(.semibold)).foregroundStyle(Theme.accent).frame(width: 38, height: 38)85 .background(Theme.accent.opacity(0.14), in: RoundedRectangle(cornerRadius: 12, style: .continuous))86 VStack(alignment: .leading, spacing: 2) { Text(title).font(.headline); Text(text).font(.subheadline).foregroundStyle(.secondary) }87 }88 }89}9091struct SignInView: View {92 @EnvironmentObject var model: AppModel93 @State private var busy = false94 @State private var joining = false95 var body: some View {96 Stage {97 (Text(L("Private conversations,\n", "Des conversations privées,\n")) + Text(L("truly yours.", "vraiment à vous.")).foregroundStyle(Theme.gradient))98 .font(.system(size: 32, weight: .bold)).fixedSize(horizontal: false, vertical: true)99 Point(icon: "lock.fill", title: L("Encrypted on your devices", "Chiffré sur vos appareils"), text: L("Messages and files are encrypted before they leave this device. The server stores only ciphertext.", "Messages et fichiers sont chiffrés avant de quitter cet appareil. Le serveur ne conserve que du texte chiffré."))100 Point(icon: "key.fill", title: L("No password", "Aucun mot de passe"), text: L("The same passkey as on the web: Face ID, Touch ID or your device code.", "La même clé d’accès que sur le web : Face ID, Touch ID ou le code de l’appareil."))101 Button { busy = true; Task { await model.signIn(); busy = false } } label: {102 HStack { if busy { ProgressView().controlSize(.small) } else { Image(systemName: "key.fill") }; Text(L("Sign in with a passkey", "Se connecter avec une clé d’accès")) }103 }.buttonStyle(PrimaryButton()).disabled(busy).keyboardShortcut(.defaultAction)104 Button(L("I have an invitation link", "J’ai un lien d’invitation")) { joining = true }.buttonStyle(SoftButton())105 }106 .sheet(isPresented: $joining) { JoinSheet().environmentObject(model) }107 }108}109110struct JoinSheet: View {111 @EnvironmentObject var model: AppModel112 @Environment(\.dismiss) private var dismiss113 @State private var link = ""114 @State private var name = ""115 @State private var handle = ""116 @State private var busy = false117 private var validHandle: Bool { handle.range(of: "^[a-z0-9_.-]{2,32}$", options: .regularExpression) != nil }118 var body: some View {119 VStack(alignment: .leading, spacing: 14) {120 Text(L("Join with an invitation", "Rejoindre avec une invitation")).font(.title2.bold())121 TextField(L("Invitation link", "Lien d’invitation"), text: $link).textFieldStyle(.roundedBorder).autocorrectionDisabled()122 TextField(L("Name shown to your contacts", "Nom affiché à vos contacts"), text: $name).textFieldStyle(.roundedBorder)123 .onChange(of: name) { _, v in handle = v.folding(options: .diacriticInsensitive, locale: nil).lowercased().replacingOccurrences(of: "[^a-z0-9]+", with: ".", options: .regularExpression).trimmingCharacters(in: CharacterSet(charactersIn: ".")) }124 TextField(L("Username", "Nom d’utilisateur"), text: $handle).textFieldStyle(.roundedBorder).autocorrectionDisabled()125 #if os(iOS)126 .textInputAutocapitalization(.never)127 #endif128 Text(L("Your device will create a passkey. Nothing secret is sent to the server.", "Votre appareil va créer une clé d’accès. Rien de secret n’est envoyé au serveur.")).font(.footnote).foregroundStyle(.secondary)129 HStack {130 Button(L("Cancel", "Annuler")) { dismiss() }.buttonStyle(SoftButton())131 Button(L("Create my passkey", "Créer ma clé d’accès")) { busy = true; Task { await model.join(link: link, name: name.trimmingCharacters(in: .whitespaces), handle: handle); busy = false; if model.phase != .anon { dismiss() } } }132 .buttonStyle(PrimaryButton()).disabled(busy || name.trimmingCharacters(in: .whitespaces).isEmpty || !validHandle || link.isEmpty)133 }134 }.padding(24).frame(minWidth: 320, idealWidth: 440)135 }136}137138struct FirstDeviceView: View {139 @EnvironmentObject var model: AppModel140 var body: some View {141 Stage {142 Text(L("Creating your encryption keys", "Création de vos clés de chiffrement")).font(.largeTitle.bold())143 Text(L("They are generated on this device and never leave it unencrypted.", "Elles sont générées sur cet appareil et ne le quittent jamais en clair.")).foregroundStyle(.secondary)144 ProgressView()145 }.task { await model.createIdentity() }146 }147}148149struct RecoveryKeyView: View {150 @EnvironmentObject var model: AppModel151 let key: String152 @State private var stored = false153 var body: some View {154 Stage {155 Text(L("Your recovery key", "Votre clé de récupération")).font(.largeTitle.bold())156 Text(L("If you lose all your devices, this key is the only way to recover your encryption identity. It is shown only once and the server cannot read it.", "Si vous perdez tous vos appareils, cette clé est le seul moyen de retrouver votre identité de chiffrement. Elle n’est affichée qu’une fois et le serveur ne peut pas la lire.")).foregroundStyle(.secondary)157 Text(key).font(.system(.body, design: .monospaced).weight(.semibold)).multilineTextAlignment(.center).textSelection(.enabled)158 .frame(maxWidth: .infinity).padding(18).background(.quaternary, in: RoundedRectangle(cornerRadius: 16, style: .continuous))159 Toggle(L("I have stored my recovery key somewhere safe.", "J’ai rangé ma clé de récupération en lieu sûr."), isOn: $stored)160 Button(L("Open SP Message", "Ouvrir SP Message")) { Task { await model.boot() } }.buttonStyle(PrimaryButton()).disabled(!stored)161 }162 }163}164165struct LinkDeviceView: View {166 @EnvironmentObject var model: AppModel167 @State private var mode = 0168 @State private var code = ""169 @State private var key = ""170 @State private var busy = false171 var body: some View {172 Stage {173 if mode == 1 {174 Text(L("Approve this device", "Approuvez cet appareil")).font(.largeTitle.bold())175 Text(L("Open SP Message on a device where you are already signed in (the web application counts). A request appears there: check that it shows this code, then approve.", "Ouvrez SP Message sur un appareil déjà connecté (l’application web compte). Une demande y apparaît : vérifiez qu’elle affiche ce code, puis approuvez.")).foregroundStyle(.secondary)176 Text(code.isEmpty ? "··· ···" : "\(code.prefix(3)) \(code.suffix(3))").font(.system(size: 40, weight: .bold, design: .monospaced)).frame(maxWidth: .infinity).padding(22)177 .background(.quaternary, in: RoundedRectangle(cornerRadius: 20, style: .continuous)).accessibilityLabel(code)178 HStack { ProgressView().controlSize(.small); Text(L("Waiting for approval…", "En attente d’approbation…")).foregroundStyle(.secondary) }179 Button(L("Cancel", "Annuler")) { Task { _ = try? await model.host.call("cancelLink"); mode = 0 } }.buttonStyle(SoftButton())180 .task {181 do {182 code = try await model.host.call("requestLink", Config.deviceLabel) as? String ?? ""183 while !Task.isCancelled && mode == 1 {184 try await Task.sleep(for: .seconds(2))185 if try await model.host.call("pollLink") as? Bool == true { await model.boot(); return }186 }187 } catch is CancellationError {} catch { model.toast = error.localizedDescription; mode = 0 }188 }189 } else if mode == 2 {190 Text(L("Enter your recovery key", "Saisissez votre clé de récupération")).font(.largeTitle.bold())191 TextField("XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX", text: $key, axis: .vertical).font(.system(.body, design: .monospaced)).textFieldStyle(.roundedBorder).autocorrectionDisabled()192 Button(L("Restore my identity", "Restaurer mon identité")) { busy = true; Task { await model.recover(key); busy = false } }.buttonStyle(PrimaryButton())193 .disabled(busy || key.filter(\.isLetter).count + key.filter(\.isNumber).count < 32)194 Button(L("Back", "Retour")) { mode = 0 }.buttonStyle(SoftButton())195 } else {196 Text(L("Add this device", "Ajouter cet appareil")).font(.largeTitle.bold())197 Text(L("Welcome back, \(model.who). Your passkey proved who you are. To read encrypted conversations this device also needs your encryption identity, which the server does not hold.", "Bon retour, \(model.who). Votre clé d’accès a prouvé votre identité. Pour lire les conversations chiffrées, cet appareil a aussi besoin de votre identité de chiffrement, que le serveur ne détient pas.")).foregroundStyle(.secondary)198 Button { mode = 1 } label: { Label(L("Approve from another device", "Approuver depuis un autre appareil"), systemImage: "iphone.and.arrow.forward") }.buttonStyle(PrimaryButton())199 Button { mode = 2 } label: { Label(L("Use my recovery key", "Utiliser ma clé de récupération"), systemImage: "key.fill") }.buttonStyle(SoftButton())200 Text(L("Messages sent before this device was added stay on your other devices.", "Les messages envoyés avant l’ajout de cet appareil restent sur vos autres appareils.")).font(.footnote).foregroundStyle(.tertiary)201 Button(L("Sign out", "Se déconnecter")) { Task { await model.signOut(wipe: false) } }.buttonStyle(.plain).foregroundStyle(.secondary)202 }203 }204 }205}206207struct PendingView: View {208 @EnvironmentObject var model: AppModel209 var body: some View {210 Stage {211 Text(L("Waiting for approval", "En attente d’approbation")).font(.largeTitle.bold())212 Text(L("An administrator must confirm your registration before you can start a conversation.", "Un administrateur doit confirmer votre inscription avant que vous puissiez commencer une conversation.")).foregroundStyle(.secondary)213 ProgressView()214 Button(L("Sign out", "Se déconnecter")) { Task { await model.signOut(wipe: false) } }.buttonStyle(SoftButton())215 }.task { while !Task.isCancelled { try? await Task.sleep(for: .seconds(8)); await model.boot() } }216 }217}218