SwiftyChat SwiftUI Framework

repository·master·Indexed 43 days ago

https://github.com/eneskaraosman/swiftychat

A lightweight, cross-platform SwiftUI framework for building chat user interfaces on iOS 17+ and macOS 14+. Optimized for AI chatbots and customer support, it features 11 built-in message types (including carousels, quick replies, and loading indicators), 8 pre-built themes, and a flexible styling system via ChatMessageCellStyle. It provides core components like ChatView and BasicInputView, and supports custom message cells through the .registerCustomCell modifier.

Tokens
9.2K
Snippets
24
Records
29
Agent score
56%

What's inside SwiftyChat

  1. Key Strengths and Unique Features of SwiftyChat

    master

    SwiftyChat is a lightweight, cross-platform SwiftUI chat UI library designed for iOS and macOS. Unlike many competitors, it is specifically optimized for Chatbot and AI use cases by providing first-class support for structured responses.

    Core Strengths:

    • Chatbot-first message types: Includes built-in support for carousel, quick reply, and loading indicator message kinds.
    • Cross-platform: Single codebase supports both iOS and macOS.
    • Theming system: Provides 8 built-in themes and uses an environment-based ChatMessageCellStyle for customization.
    • Performance: Optimized with O(n) metadata caching, shared DateFormatter, Equatable cells, and LazyVStack for efficient scrolling.
  2. Customize Chat UI styling with ChatMessageCellStyle

    master
    You can customize every visual aspect of the chat (text styles, edge insets, avatar styles, and cell styles) by injecting a ChatMessageCellStyle into the SwiftUI environment using the .environment(\.chatStyle, ...) modifier.
  3. Implement ChatView in SwiftUI

    master

    Integrate the chat interface by adding ChatView to your view hierarchy. ChatView requires a binding to your array of messages and a binding to a scrollToBottom boolean. You must also provide a trailing closure containing an input view (such as BasicInputView) to handle user text entry.

    BasicInputView takes a binding to the input text, a placeholder string, and an onCommit closure which provides the ChatMessageKind of the message being sent.

    import SwiftyChat
    
    let currentUser = User(userName: "Alice")
    
    struct ContentView: View {
        @State private var messages: [Message] = []
        @State private var inputText = ""
        @State private var scrollToBottom = false
    
        var body: some View {
            ChatView(messages: $messages, scrollToBottom: $scrollToBottom) {
                BasicInputView(
                    message: $inputText,
                    placeholder: "Type a message...",
                    onCommit: { messageKind in
                        messages.append(Message(
                            user: currentUser,
                            messageKind: messageKind,
                            isSender: true
                        ))
                    }
                )
            }
            .environment(\.chatStyle, ChatMessageCellStyle())
        }
    }
  4. Use pre-built chat themes

    master

    SwiftyChat provides 8 ready-to-use themes to quickly skin your chat interface. These themes vary by accent color and aesthetic style:

    ThemeAccent ColorDescription
    ModernBlueClean and minimal
    ClassicGreenTraditional messaging
    Dark NeonPinkCyberpunk vibes
    MinimalGraySubtle and clean
    OceanTealCalming sea-inspired
    SunsetOrangeWarm gradients
    NatureGreenFresh and eco-friendly
    LavenderPurpleSoft and relaxing
  5. Install SwiftyChat via Swift Package Manager

    master

    Add SwiftyChat to your Xcode project using the following URL via File → Add Package Dependencies:

    https://github.com/EnesKaraosman/SwiftyChat.git

    Alternatively, add it directly to your Package.swift file:

    dependencies: [
        .package(url: "https://github.com/EnesKaraosman/SwiftyChat.git", from: "4.1.1")
    ]
  6. Register a custom cell for custom message types

    master

    To render message types that are not part of the standard set, use the .registerCustomCell modifier on your ChatView. This allows you to map a ChatMessageKind.custom value to a specific SwiftUI view.

    The closure provided to .registerCustomCell receives an Any value. This value is the payload passed into the .custom(Any) kind. You must cast this Any value to your expected type inside the cell or the registration closure to access its properties.

    ChatView(messages: $messages) {
        // input view ...
    }
    .registerCustomCell { data in
        MyCustomCell(data: data)
    }
  7. Implement the ChatView and BasicInputView

    master

    The core of the SwiftyChat UI consists of two main components:

    1. ChatView: The primary container for the chat interface. It requires a binding to your messages array and a binding to a scrollToBottom boolean to control scrolling behavior.
    2. BasicInputView: The input component used within the ChatView closure. It manages the text input state via a binding to a string, accepts a placeholder, and provides an onCommit closure that returns the messageKind when the user submits a message.

    You can customize the overall look of messages by applying a ChatMessageCellStyle via the .environment(\.chatStyle, ...) modifier.

    ChatView(messages: $messages, scrollToBottom: $scrollToBottom) {
        BasicInputView(
            message: $message,
            placeholder: "Type something",
            onCommit: { messageKind in
                // Handle message submission
            }
        )
    }
    .environment(\.chatStyle, ChatMessageCellStyle())
  8. Quick Start with ChatView and BasicInputView

    master

    To implement a basic chat interface, use ChatView with a collection of messages conforming to the ChatMessage protocol. You can provide a custom input view using the inputView closure. The ChatView also supports an environment modifier to apply custom styles via ChatMessageCellStyle.

    import SwiftyChat
    
    struct ContentView: View {
        @State private var messages: [YourMessage] = []
        @State private var message = ""
        @State private var scrollToBottom = false
    
        var body: some View {
            ChatView(messages: $messages, scrollToBottom: $scrollToBottom) {
                BasicInputView(
                    message: $message,
                    placeholder: "Type something",
                    onCommit: { messageKind in
                        messages.append(/* your message */)
                    }
                )
            }
            .environment(\.chatStyle, ChatMessageCellStyle())
        }
    }
  9. Define required models for SwiftyChat

    master

    To use SwiftyChat, you must define two models that conform to the required protocols:

    1. ChatUser: Represents the participants in the chat. It requires an id, userName, and optional avatar (as PlatformImage) or avatarURL.
    2. ChatMessage: Represents an individual message. It requires an id, the user who sent it, a messageKind (of type ChatMessageKind), a boolean isSender to distinguish between incoming and outgoing messages, and a date.
    struct User: ChatUser {
        var id = UUID().uuidString
        var userName: String
        var avatar: PlatformImage?
        var avatarURL: URL?
    }
    
    struct Message: ChatMessage {
        let id = UUID()
        var user: User
        var messageKind: ChatMessageKind
        var isSender: Bool
        var date: Date = .init()
    }
  10. Quick Start with SwiftyChat

    master

    SwiftyChat is a lightweight, cross-platform SwiftUI chat UI framework designed for iOS 17+ and macOS 14+. It provides a ready-to-use chat interface including 11 message types and 8 pre-built themes. To implement a basic chat interface, use ChatView to display messages and BasicInputView to handle user input.

    ChatView(messages: $messages, scrollToBottom: $scrollToBottom) {
        BasicInputView(
            message: $message,
            placeholder: "Type something",
            onCommit: { messageKind in
                messages.append(/* your message */)
            }
        )
    }
    .environment(\.chatStyle, ChatMessageCellStyle())
  11. Customize chat appearance with ChatMessageCellStyle

    master

    You can control the visual appearance of the chat (colors, fonts, corner radii, and avatars) by injecting a ChatMessageCellStyle into the environment using the .environment(\.chatStyle, ...) modifier on ChatView.

    Use TextCellStyle to define specific properties for incomingTextStyle and outgoingTextStyle.

    .environment(\.chatStyle, ChatMessageCellStyle(
        incomingTextStyle: TextCellStyle(
            cellBackgroundColor: .gray.opacity(0.2),
            cellCornerRadius: 16
        ),
        outgoingTextStyle: TextCellStyle(
            textStyle: CommonTextStyle(textColor: .white),
            cellBackgroundColor: .blue,
            cellCornerRadius: 16
        )
    ))