import LChatCore import SwiftUI // Start a new chat, iMessage-style: the sheet lists people — tap one and the DM // starts immediately (the server dedupes, so an existing DM just opens). "New // group" pushes the multi-select flow. Agent helpers get their own section with // a BOT badge, mirroring the web picker. All key wrapping happens natively in // ThreadStore.createChat. struct NewChatView: View { @ObservedObject var store: ThreadStore @Environment(\.dismiss) private var dismiss let onCreated: (String) -> Void @State private var busyWith: String? // user id of the DM being created ("admin" = the Admin row) @State private var error: String? @State private var search = "" private var query: String { search.trimmingCharacters(in: .whitespaces) } private var others: [RosterEntry] { store.roster.filter { $0.user_id != store.myUserId } } private var people: [RosterEntry] { store.rosterMatches(others.filter { !$0.isAgent }, query) } // Bots off empties the Helpers section (matching the web picker) — existing // bot DMs stay in the sidebar; only starting new ones hides. private var helpers: [RosterEntry] { store.botsEnabled ? store.rosterMatches(others.filter { $0.isAgent }, query) : [] } // Personal apps from the registry (places ∋ "you", listed) — the web // picker's Apps section, searchable by title like people are (Mac's // NewChatPopover does the same). Hidden entirely when apps are off. private var visibleApps: [AppManifest] { guard store.appsEnabled else { return [] } let apps = store.registry.personalApps return query.isEmpty ? apps : apps.filter { $0.title.localizedCaseInsensitiveContains(query) } } var body: some View { NavigationStack { List { // The action rows step aside while a query is live — search // results are people, not actions (clear the field to get // them back). The web keeps its equivalents in the sheet // header, so they never compete with matches there either. if query.isEmpty { Section { NavigationLink { NewGroupView(store: store, onCreated: finish) } label: { Label { Text("New group").font(.body.weight(.medium)) } icon: { Image(systemName: "person.3.fill") .foregroundStyle(Color.accentColor) } } // Bring someone new onto the server (if the admin allows // member invites — the server says no otherwise). NavigationLink { InviteSomeoneView(store: store) { _ in dismiss() } } label: { Label { Text("Invite someone").font(.body.weight(.medium)) } icon: { Image(systemName: "person.badge.plus") .foregroundStyle(Color.accentColor) } } // The community directory: open groups anyone can join. NavigationLink { DiscoverGroupsView(store: store, onOpen: finish) } label: { Label { Text("Discover groups").font(.body.weight(.medium)) } icon: { Image(systemName: "safari") .foregroundStyle(Color.accentColor) } } // The Admin app, admins only (the roster carries our role; the // server re-checks it) — same open-the-app-thread action as the // web picker's Apps row, so /admin isn't the only way in. if store.isAdmin { Button { openAdmin() } label: { HStack { Label { Text("Admin").font(.body.weight(.medium)) } icon: { Image(systemName: "gearshape") .foregroundStyle(Color.accentColor) } Spacer() if busyWith == "admin" { ProgressView() } } .contentShape(Rectangle()) } .buttonStyle(.plain) .disabled(busyWith != nil) .accessibilityLabel("Admin") .accessibilityHint("Opens this space's admin panel") } } } if others.isEmpty { Section { Text("No one else has joined this chat yet.") .foregroundStyle(.secondary) } } else if !query.isEmpty && people.isEmpty && helpers.isEmpty && visibleApps.isEmpty { Section { Text("No matches.") .foregroundStyle(.secondary) } } if !people.isEmpty { Section("People") { ForEach(people, id: \.user_id) { person in personRow(person) } } } if !helpers.isEmpty { Section("Helpers") { ForEach(helpers, id: \.user_id) { person in personRow(person) } } } if !visibleApps.isEmpty { Section("Apps") { ForEach(visibleApps) { app in appRow(app) } } } if let error { Section { Text(error).foregroundStyle(.red) } } } .navigationTitle("New chat") .navigationBarTitleDisplayMode(.inline) // Always-visible, like the web picker's Search field — hiding it // behind a pull-down would read as "no way to filter" all over again. .searchable(text: $search, placement: .navigationBarDrawer(displayMode: .always), prompt: "Search") // Return opens the top match, same as Enter on the web — but only // mid-query: a stray Search tap on an empty field shouldn't start // a DM with whoever happens to sort first. .onSubmit(of: .search) { guard !query.isEmpty, busyWith == nil else { return } if let first = people.first ?? helpers.first { startDM(first) } } .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } } } } } private func personRow(_ person: RosterEntry) -> some View { Button { startDM(person) } label: { HStack(spacing: 12) { // Nickname-resolved, like every other member list — the filter // matches this name, so the row must show it too. Avatar(name: store.displayName(for: person), size: 36, source: store.avatarSource(for: person)) Text(store.displayName(for: person)).foregroundStyle(.primary) if person.isAgent { BotBadge() } Spacer() if busyWith == person.user_id { ProgressView() } } // A .plain button only hit-tests its label's opaque content — the // Spacer and row padding were dead zones. Make the whole row tappable. .contentShape(Rectangle()) } .buttonStyle(.plain) .disabled(busyWith != nil) } private func startDM(_ person: RosterEntry) { busyWith = person.user_id error = nil Task { let id = await store.createChat(memberIDs: [person.user_id], groupName: nil) busyWith = nil if let id { finish(id) } else { error = store.loadError ?? "Couldn't start the chat." } } } // A personal app row: open (creating on first use) its app-thread and // dismiss into it — the same land-in-the-thread shape as picking a person. private func appRow(_ app: AppManifest) -> some View { Button { busyWith = app.name error = nil Task { let id = await store.openOrCreateAppThread(app: app.name, title: app.title) busyWith = nil if let id { finish(id) } else { error = store.loadError ?? "Couldn't open \(app.title)." } } } label: { HStack(spacing: 12) { Text(app.glyph) .font(.system(size: 17)) .frame(width: 36, height: 36) .background(Circle().fill(.primary.opacity(0.06))) VStack(alignment: .leading, spacing: 1) { Text(app.title).foregroundStyle(.primary) if let blurb = app.blurb, !blurb.isEmpty { Text(blurb).font(.footnote).foregroundStyle(.secondary).lineLimit(1) } } Spacer() if busyWith == app.name { ProgressView() } } .contentShape(Rectangle()) } .buttonStyle(.plain) .disabled(busyWith != nil) .accessibilityLabel(app.title) .accessibilityHint("Opens the \(app.title) app") } // Open (creating on first use) the Admin app-thread, then dismiss into it — // the same land-in-the-thread shape as picking a person. private func openAdmin() { busyWith = "admin" // an app id can't collide with a user id here error = nil Task { let id = await store.openOrCreateAppThread(app: "admin", title: "Admin") busyWith = nil if let id { finish(id) } else { error = store.loadError ?? "Couldn't open Admin." } } } private func finish(_ id: String) { onCreated(id) dismiss() } } // The multi-select group flow, pushed from NewChatView. struct NewGroupView: View { @ObservedObject var store: ThreadStore let onCreated: (String) -> Void @State private var selected: Set = [] @State private var selectedApps: Set = [] @State private var groupName = "" @State private var openGroup = false @State private var busy = false @State private var error: String? @State private var search = "" private var query: String { search.trimmingCharacters(in: .whitespaces) } // Bots off drops agents from the member picker, same as the web's // add-to-group sheet (adding a bot to a group is starting new bot use). private var others: [RosterEntry] { store.rosterMatches(store.roster.filter { $0.user_id != store.myUserId && (store.botsEnabled || !$0.isAgent) }, query) } var body: some View { Form { Section("Group name") { TextField("Optional", text: $groupName) .autocorrectionDisabled() } // Open community group — offered only once the instance key is // here (it carries the group key to future joiners), matching the // web sheet and how photos wait on the same key. if store.instanceKey() != nil { Section { Toggle("Open group", isOn: $openGroup) } footer: { Text("Anyone in this space can find it under Discover and join.") } } Section(header: Text(selected.isEmpty ? "Add people" : "\(selected.count) selected")) { if others.isEmpty && !query.isEmpty { Text("No matches.").foregroundStyle(.secondary) } ForEach(others, id: \.user_id) { person in Button { toggle(person.user_id) } label: { HStack(spacing: 12) { Avatar(name: store.displayName(for: person), size: 32, source: store.avatarSource(for: person)) Text(store.displayName(for: person)).foregroundStyle(.primary) if person.isAgent { BotBadge() } Spacer() if selected.contains(person.user_id) { Image(systemName: "checkmark.circle.fill").foregroundStyle(.tint) } else { Image(systemName: "circle").foregroundStyle(.tertiary) } } // Same as personRow: without an explicit content shape only // the glyphs hit-test, so selecting felt like tapping radio // buttons. The whole row should toggle. .contentShape(Rectangle()) } .buttonStyle(.plain) } } // Shared apps, picked at birth — each one lands as a groupapps.add // in the fresh log, so every member folds the same list (the same // apps you could add later from ⋯ → Manage Apps). Hidden entirely // when the admin turned apps off. if store.appsEnabled { Section { // Every group-capable app from the registry (places ∋ // "chat", listed) — the same list the ⋮ → Manage Apps // sheet offers, custom and member apps included. ForEach(store.registry.groupApps) { app in Button { toggleApp(app.name) } label: { HStack(spacing: 12) { Image(systemName: AppIdentity.symbol(for: app.name) ?? "square.grid.2x2") .font(.system(size: 14, weight: .medium)) .foregroundStyle(.primary) .frame(width: 32, height: 32) .background(Circle().fill(.primary.opacity(0.06))) Text(app.title).foregroundStyle(.primary) Spacer() if selectedApps.contains(app.name) { Image(systemName: "checkmark.circle.fill").foregroundStyle(.tint) } else { Image(systemName: "circle").foregroundStyle(.tertiary) } } .contentShape(Rectangle()) } .buttonStyle(.plain) } } header: { Text("Apps") } footer: { Text("Apps are shared with everyone in the group — one list, one set of data.") } } if let error { Section { Text(error).foregroundStyle(.red) } } } .navigationTitle("New group") .navigationBarTitleDisplayMode(.inline) .searchable(text: $search, placement: .navigationBarDrawer(displayMode: .always), prompt: "Search") .toolbar { ToolbarItem(placement: .confirmationAction) { if busy { ProgressView() } else { // An open group may start with just its creator — others // find it in Discover; a closed group still needs people. Button("Create") { create() } .disabled(selected.isEmpty && !openGroup) } } } } private func toggle(_ id: String) { if selected.contains(id) { selected.remove(id) } else { selected.insert(id) } } private func toggleApp(_ id: String) { if selectedApps.contains(id) { selectedApps.remove(id) } else { selectedApps.insert(id) } } private func create() { busy = true error = nil Task { let id = await store.createChat(memberIDs: Array(selected), groupName: groupName, group: true, apps: Array(selectedApps).sorted(), openGroup: openGroup) busy = false if let id { onCreated(id) } else { error = store.loadError ?? "Couldn't create the group." } } } } // The "BOT" tag next to agent helpers — mirrors the web picker's badge. struct BotBadge: View { var body: some View { Text("BOT") .font(.caption2.weight(.bold)) .padding(.horizontal, 5) .padding(.vertical, 2) .background(Color.accentColor.opacity(0.15), in: RoundedRectangle(cornerRadius: 4)) .foregroundStyle(Color.accentColor) } }