Cotton code
482 lines · 20.1 KB · SwiftRaw
// What a Cotton conversation draws beyond any other: its composer (words,// a picture, a reply), the other person typing, a stranger's request, the// pictures a message carries, and the page that starts a chat with its two// switches. Every word is the chat lines' (`lines/chat.json`); every refusal// is the core's sentence, said as it came.import CottonKitimport CottonPaperimport CottonValuesimport ImageIOimport SwiftUI#if canImport(PhotosUI) && canImport(UIKit)    import PhotosUI    import UIKit#endif/// A refusal's words: the core's sentence when it said one.@MainActor func chatRefusal(_ error: any Error) -> String {    (error as? CottonCallError)?.message ?? ShellLines.line("conversation", "not_sent")}/// The composer at a Cotton conversation's foot.struct CottonChatComposer: View {    @Environment(\.theme) private var theme    @Environment(ToastCenter.self) private var toasts    let model: ConversationModel    let chat: any CottonChatting    let recipient: String?    let identifier: String    @State private var draft = ""    @State private var sending = false    #if canImport(PhotosUI) && canImport(UIKit)        @State private var pick: PhotosPickerItem?    #endif    var body: some View {        VStack(alignment: .leading, spacing: 0) {            if chat.isTyping(thread: model.thread) {                Text(ShellLines.line("chat", "typing")).paperHand(14, ink: .pencil)                    .padding(.horizontal, 20).padding(.top, 6)                    .accessibilityIdentifier("\(identifier)-typing")            }            if let reply = model.replyingTo {                HStack(spacing: 8) {                    Text(ShellLines.line("chat", "replying", ["words": Self.firstWords(of: reply, body: model.layout.body)]))                        .paperBody(12, ink: .pencil).lineLimit(1)                        .frame(maxWidth: .infinity, alignment: .leading)                    Button {                        model.replyingTo = nil                    } label: {                        Image(systemName: "xmark").font(theme.type.interface(11, weight: .semibold))                            .foregroundStyle(theme.print(.pencil))                            .frame(width: 28, height: 28)                    }                    .buttonStyle(OpacityButtonStyle())                    .accessibilityIdentifier("\(identifier)-reply-cancel")                }                .padding(.horizontal, 20).padding(.top, 6)                .accessibilityIdentifier("\(identifier)-replying")            }            HStack(alignment: .bottom, spacing: 0) {                #if canImport(PhotosUI) && canImport(UIKit)                    PhotosPicker(selection: $pick, matching: .images) {                        Image(systemName: "photo").font(theme.type.interface(17, weight: .regular))                            .foregroundStyle(theme.print(.ink))                            .frame(width: 44, height: 44)                    }                    .disabled(sending)                    .padding(.leading, 8).padding(.bottom, 10)                    .accessibilityLabel(ShellLines.line("chat", "picture"))                    .accessibilityIdentifier("\(identifier)-picture")                    .onChange(of: pick) { _, item in                        guard let item else { return }                        pick = nil                        Task { await sendPicture(item) }                    }                #endif                ChatComposerBar(                    draft: $draft,                    placeholder: recipient.map { ShellLines.line("conversation", "placeholder_to", ["name": $0]) } ?? ShellLines.line("conversation", "placeholder"),                    canSend: !draft.isBlank && !sending,                    identifier: identifier                ) {                    let words = draft                    draft = ""                    Task { await send(words: words, pictures: []) }                }            }        }        .fixedSize(horizontal: false, vertical: true)        .background(theme.colors.groundMuted.color)        .onChange(of: draft) { was, now in            if !now.isEmpty, now != was { chat.typed(thread: model.thread) }        }    }    private func send(words: String, pictures: [ChatPicture]) async {        let body = words.trimmingCharacters(in: .whitespacesAndNewlines)        sending = true        defer { sending = false }        do {            try await chat.send(thread: model.thread, body: body.isEmpty ? nil : body, replyTo: model.replyingTo?.id, pictures: pictures)            model.replyingTo = nil            await model.load()        } catch {            if draft.isEmpty { draft = words }            toasts.show(chatRefusal(error), tone: .error)        }    }    #if canImport(PhotosUI) && canImport(UIKit)        /// A picked picture as a JPEG this app wrote, sent at once with the words written so far.        private func sendPicture(_ item: PhotosPickerItem) async {            guard let data = try? await item.loadTransferable(type: Data.self), let picture = ChatPictureFile.write(data) else {                toasts.show(ShellLines.line("chat", "picture_unread"), tone: .error)                return            }            let words = draft            draft = ""            await send(words: words, pictures: [picture])        }    #endif    static func firstWords(of message: TableRecord, body: String) -> String {        let words = (message[body].text ?? "").split(whereSeparator: \.isNewline).joined(separator: " ")        return words.isEmpty ? ShellLines.line("conversation", "media.photo") : String(words.prefix(60))    }}#if canImport(UIKit)    /// A picked picture written as the file a message carries: a JPEG no    /// longer than 2048 points on its long side.    enum ChatPictureFile {        static let longSide: CGFloat = 2048        static func write(_ data: Data) -> ChatPicture? {            guard let image = UIImage(data: data) else { return nil }            let size = image.size            let scale = min(1, longSide / max(size.width, size.height, 1))            let drawn = CGSize(width: (size.width * scale).rounded(), height: (size.height * scale).rounded())            let format = UIGraphicsImageRendererFormat()            format.scale = 1            let jpeg = UIGraphicsImageRenderer(size: drawn, format: format).jpegData(withCompressionQuality: 0.82) { _ in                image.draw(in: CGRect(origin: .zero, size: drawn))            }            let folder = FileManager.default.temporaryDirectory.appendingPathComponent("chat-sending", isDirectory: true)            try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)            let url = folder.appendingPathComponent(UUID().uuidString + ".jpg")            guard (try? jpeg.write(to: url)) != nil else { return nil }            return ChatPicture(path: url.path, mime: "image/jpeg", width: Int(drawn.width), height: Int(drawn.height))        }    }#endif/// A stranger's first message: who wants to write, and the person's answer./// Nothing is sent back to them until Accept.struct ChatRequestCard: View {    @Environment(\.theme) private var theme    @Environment(ToastCenter.self) private var toasts    let thread: String    let name: String?    let chat: any CottonChatting    var decided: (ChatDecision) async -> Void    @State private var deciding = false    var body: some View {        VStack(alignment: .leading, spacing: 10) {            Text(name.map { ShellLines.line("chat", "request.title", ["name": $0]) } ?? ShellLines.line("chat", "request.unknown_title"))                .paperBody(15)                .fixedSize(horizontal: false, vertical: true)            Text(ShellLines.line("chat", "request.line")).paperBody(12, ink: .pencil)                .fixedSize(horizontal: false, vertical: true)            HStack(spacing: 18) {                answer(.accept, "request.accept", ink: .ink)                answer(.block, "request.block", ink: .red)                answer(.refuse, "request.refuse", ink: .red)            }        }        .padding(.horizontal, 20).padding(.vertical, 14)        .frame(maxWidth: .infinity, alignment: .leading)        .background(theme.colors.groundMuted.color)        .accessibilityElement(children: .contain)        .accessibilityIdentifier("chat-request")    }    private func answer(_ decision: ChatDecision, _ line: String, ink: PaperInk) -> some View {        Button(ShellLines.line("chat", line)) {            deciding = true            Task {                defer { deciding = false }                do {                    try await chat.decide(thread: thread, decision)                    if decision == .block { toasts.show(ShellLines.line("chat", "request.blocked"), tone: .success) }                    await decided(decision)                } catch {                    toasts.show(chatRefusal(error), tone: .error)                }            }        }        .buttonStyle(.plain).paperHand(17, ink: ink)        .disabled(deciding)        .accessibilityIdentifier("chat-request-\(decision.rawValue)")    }}/// The pictures a Cotton message carries, each fetched and opened by the core.struct CottonPictures: View {    let message: String    let count: Int    let chat: any CottonChatting    let width: CGFloat    var body: some View {        VStack(spacing: 6) {            ForEach(0..<count, id: \.self) { index in                CottonPicture(message: message, index: index, chat: chat, width: width)            }        }    }    /// How many pictures a message's `meta.cotton.pictures` names (its own or one it is still sending).    static func count(of message: TableRecord) -> Int {        guard let cotton = meta(of: message)?["cotton"] else { return 0 }        return cotton["pictures"]?.array?.count ?? 0    }    static func meta(of message: TableRecord) -> JSONValue? {        switch message["meta"] {        case .text(let raw): return try? JSONDecoder().decode(JSONValue.self, from: Data(raw.utf8))        case .object(let members): return try? JSONDecoder().decode(JSONValue.self, from: JSONEncoder().encode(members))        default: return nil        }    }}private struct CottonPicture: View {    let message: String    let index: Int    let chat: any CottonChatting    let width: CGFloat    @State private var file: URL?    @State private var failed = false    var body: some View {        Group {            #if canImport(UIKit)                if let file, let image = Self.picture(at: file, width: width) {                    Image(uiImage: image).resizable().scaledToFit()                        .clipShape(RoundedRectangle(cornerRadius: 6))                } else {                    placeholder                }            #else                placeholder            #endif        }        .frame(width: width)        .accessibilityLabel(ShellLines.line("conversation", "media.photo"))        .accessibilityIdentifier("chat-picture-\(message)-\(index)")        .task(id: message) {            do { file = try await chat.picture(message: message, index: index) } catch { failed = true }        }    }    #if canImport(UIKit)        /// The picture drawn at the bubble's width, decoded from its file by        /// ImageIO, never the whole file read into memory: a photograph a        /// friend sent may be tens of megapixels, and a bubble is a few        /// hundred points wide (three pixels a point covers every screen).        private static func picture(at file: URL, width: CGFloat) -> UIImage? {            guard                let source = CGImageSourceCreateWithURL(file as CFURL, nil),                let drawn = CGImageSourceCreateThumbnailAtIndex(                    source, 0,                    [                        kCGImageSourceCreateThumbnailFromImageAlways: true,                        kCGImageSourceCreateThumbnailWithTransform: true,                        kCGImageSourceThumbnailMaxPixelSize: max(1, Int(width * 3)),                    ] as CFDictionary                )            else { return nil }            return UIImage(cgImage: drawn)        }    #endif    private var placeholder: some View {        RoundedRectangle(cornerRadius: 6).fill(.secondary.opacity(0.12))            .frame(height: width * 0.75)            .overlay {                if failed {                    Text(ShellLines.line("chat", "picture_unread")).paperBody(12, ink: .pencil).padding(12)                } else {                    ProgressView()                }            }    }}/// `people.pick`'s answer: New chat's page.struct ChatPickAnswer: Decodable, Equatable, Sendable {    struct Row: Decodable, Equatable, Sendable, Identifiable {        let number: String        let words: String        var detail: String?        var id: String { number }    }    struct Add: Decodable, Equatable, Sendable {        let words: String        let hint: String    }    let title: String    /// What the list is: Your people.    let heading: String    let rows: [Row]    let add: Add    var empty: String?    var unreachable: String?}/// New chat (owner, 15 Nov 2026): pick one of Your people, the core's list/// (`people.pick`, the one Account's Your people reads); the person picked/// opens their chat, started when it is new. Someone not yet among them is/// reached by their number, added as Your people adds a person/// (`people.add`, which never says whether the number is on Cotton), and/// their chat opens. Every word is the core's.struct ChatStartScreen: View {    @Environment(\.theme) private var theme    @Environment(\.cottonCore) private var core    @Environment(\.cottonChat) private var chat    @Environment(ToastCenter.self) private var toasts    @Environment(Navigator.self) private var navigator: Navigator?    @State private var page: ChatPickAnswer?    @State private var typed = ""    @State private var starting = false    private struct Adding: Encodable, Sendable { let number: String }    private struct Added: Decodable, Sendable { let said: String; let number: String }    var body: some View {        PaperScreen(title: page?.title ?? ShellLines.line("chat", "stream.new"), closes: true) {            VStack(alignment: .leading, spacing: 14) {                if chat == nil {                    // An app that carries no chat engine (Cotton) says where chats are written.                    Text(ShellLines.line("chat", "start.elsewhere")).paperBody(15)                        .fixedSize(horizontal: false, vertical: true)                        .accessibilityIdentifier("chat-start-elsewhere")                } else if let page {                    people(page)                    add(page.add)                    // The two switches, only where the app's chats signal at all (the kit's `signals`).                    if let chat, chat.signals { ChatSettingsCard(chat: chat).padding(.top, 24) }                }            }            .padding(.horizontal, 20)            .padding(.top, ScreenBarKnobs.chromeNavCircleTarget + 8)        }        .task { await read() }        .accessibilityIdentifier("chat-start")    }    /// Your people, each to pick; or why nobody stands there.    @ViewBuilder private func people(_ page: ChatPickAnswer) -> some View {        Text(page.heading).paperBody(12, ink: .pencil)            .accessibilityAddTraits(.isHeader)            .accessibilityIdentifier("chat-start-heading")        if let said = page.unreachable ?? page.empty {            Text(said).paperBody(15)                .fixedSize(horizontal: false, vertical: true)                .accessibilityIdentifier("chat-start-none")        }        ForEach(page.rows) { row in            Button { begin(number: row.number) } label: {                VStack(alignment: .leading, spacing: 2) {                    Text(row.words).paperBody(17)                    if let detail = row.detail { Text(detail).paperBody(12, ink: .pencil) }                }                .frame(maxWidth: .infinity, minHeight: 44, alignment: .leading)                .contentShape(Rectangle())            }            .buttonStyle(.plain)            .disabled(starting)            .accessibilityIdentifier("chat-start-person-\(row.number)")        }    }    /// Someone not yet in Your people: their number, added as Your people adds it.    @ViewBuilder private func add(_ add: ChatPickAnswer.Add) -> some View {        Text(add.words).paperBody(12, ink: .pencil)            .padding(.top, 14)            .accessibilityAddTraits(.isHeader)        TextField(add.hint, text: $typed)            .paperBody(15)            #if os(iOS)                .textContentType(.telephoneNumber)                .keyboardType(.phonePad)            #endif            .autocorrectionDisabled()            .padding(12)            .background(RoundedRectangle(cornerRadius: 8).fill(theme.colors.groundMuted.color))            .onSubmit { addPerson() }            .accessibilityIdentifier("chat-start-number")        if Self.isNumber(typed) {            Button(add.words) { addPerson() }                .buttonStyle(.plain).paperHand(19, ink: .ink)                .disabled(starting)                .accessibilityIdentifier("chat-start-go")        }    }    static func isNumber(_ text: String) -> Bool {        let trimmed = text.trimmingCharacters(in: .whitespaces)        return trimmed.first.map { $0 == "+" || $0.isNumber } ?? false    }    private func read() async {        guard chat != nil, let core else { return }        do { page = try await core.call("people.pick", as: ChatPickAnswer.self) } catch { toasts.show(chatRefusal(error), tone: .error) }    }    /// The number typed joins Your people (the same answer for any number),    /// and their chat opens.    private func addPerson() {        let number = typed.trimmingCharacters(in: .whitespaces)        guard let core, Self.isNumber(number), !starting else { return }        starting = true        Task {            do {                let added = try await core.call("people.add", Adding(number: number), as: Added.self)                NotificationCenter.default.post(name: .cottonPeopleChanged, object: nil)                toasts.show(added.said)                starting = false                begin(number: added.number)            } catch {                starting = false                toasts.show(chatRefusal(error), tone: .error)            }        }    }    /// The chat with `number`, opened; made when it is new.    private func begin(number: String) {        guard let chat, !starting else { return }        starting = true        Task {            defer { starting = false }            do {                let thread = try await chat.start(number: number, person: nil)                navigator?.replace(with: .messagesThread(thread: thread))            } catch {                toasts.show(chatRefusal(error), tone: .error)            }        }    }}/// Read receipts and Typing, as the core keeps them. Not drawn while the/// app's chats do not signal (`CottonChatting.signals`, the kit's switch;/// owner, 15 Nov 2026): New chat offers it again the day the kit says so.struct ChatSettingsCard: View {    @Environment(ToastCenter.self) private var toasts    let chat: any CottonChatting    var body: some View {        VStack(alignment: .leading, spacing: 8) {            Text(ShellLines.line("chat", "settings.title")).paperHand(19)            SettingsSwitchRow(label: ShellLines.line("chat", "settings.read_receipts"), caption: ShellLines.line("chat", "settings.read_receipts_line"),                              isOn: chat.readReceipts, identifier: "chat-settings-read") { on in set(readReceipts: on) }            SettingsSwitchRow(label: ShellLines.line("chat", "settings.typing"), caption: ShellLines.line("chat", "settings.typing_line"),                              isOn: chat.sendsTyping, isLast: true, identifier: "chat-settings-typing") { on in set(typing: on) }        }    }    private func set(readReceipts: Bool? = nil, typing: Bool? = nil) {        Task {            do { try await chat.set(readReceipts: readReceipts, typing: typing) } catch { toasts.show(chatRefusal(error), tone: .error) }        }    }}