Skip to main content
Firstlight

Firstlight / Docs

Recipes for the screens a forms app needs, setup for your coding agent, Laravel on native screens, and accessibility.

View source
Chat

Chat

Chat shows a conversation as native message bubbles. PHP publishes the messages, oldest first; the native list keys them by ID, groups them, opens at the newest one, and reports reads, retries, message actions and file opens back to PHP. It doesn't send, store or sync anything itself: your screen owns the messages and decides how they reach a server.

Pair it with Chat Composer in a <native:bottom-bar>, so the composer sits above the keyboard.

Complete example

<?php

namespace App\NativeComponents;

use FirstlightUI\Media\MediaStorage;
use FirstlightUI\Media\MediaValue;
use FirstlightUI\NativeComponent;
use Illuminate\Support\Str;
use Illuminate\View\View;

class Conversation extends NativeComponent
{
    /** @var list<array<string, mixed>> */
    public array $messages = [];

    /** @var list<MediaValue> */
    public array $pending = [];

    public string $draft = '';

    public function send(): void
    {
        $this->messages[] = [
            'id' => (string) Str::uuid(),
            'author' => (string) auth()->id(),
            'body' => trim($this->draft),
            'sent-at' => now()->toIso8601String(),
            'status' => 'sending',
            'actions' => ['delete'],
            'attachments' => array_map(fn (MediaValue $media, int $index) => [
                'id' => (string) $index,
                'kind' => str_starts_with($media->mime, 'image/') ? 'image' : 'file',
                'source' => $media,
            ], $this->pending, array_keys($this->pending)),
        ];
        $this->draft = '';
        $this->pending = [];
        // Send to your server here, then republish the same id as sent or failed.
    }

    public function addAttachment(string $tempPath): void
    {
        $this->pending[] = MediaStorage::commit($tempPath, 'mobile_public', 'chat');
    }

    public function removeAttachment(int $index): void
    {
        MediaStorage::delete($this->pending[$index] ?? null);
        array_splice($this->pending, $index, 1);
    }

    public function markReadUpTo(string $messageId): void {}

    public function resend(string $messageId): void {}

    public function messageAction(string $key, string $messageId): void {}

    public function render(): View
    {
        return view('native.conversation');
    }
}
<native:column class="w-full flex-1">
    <firstlight:chat
        class="w-full flex-1"
        :messages="$messages"
        me="{{ auth()->id() }}"
        :actions="['delete' => ['label' => 'Delete', 'destructive' => true, 'icon' => 'delete']]"
        @read="markReadUpTo"
        @retry="resend"
        @action="messageAction"
        label="Chat with Sam"
    />

    <native:bottom-bar>
        <firstlight:chat-composer
            native:model.debounce.300ms="draft"
            :attachments="$pending"
            placeholder="Message"
            attach="photos,camera,files"
            @send="send"
            @attach="addAttachment"
            @removeAttachment="removeAttachment"
            label="Message to Sam"
        />
    </native:bottom-bar>
</native:column>

Props

API Accepted type Purpose
messages list of message arrays Required. Oldest first by sent-at; see Messages. At most 500 per publication.
me string Required. The author value of the current user. Messages with this author are outgoing.
label string Required. Accessible name of the transcript, such as "Chat with Sam".
typing list of display names Shows a typing row after the newest message. Empty hides it.
has-older bool Shows an activity row at the top and allows @loadOlder. Defaults to false.
actions map of key to label, or to label, destructive and icon Up to 4 authored message actions. icon takes icon-ios and icon-android overrides.
scroll-to message id Brings that message on screen when the value changes. It must be a published id.
timezone IANA timezone, such as Australia/Sydney Day separators and times use it instead of the phone's timezone.
count, window-from, window-to int Windowed mode; see Long chats. All three or none.
class string External EDGE layout. Give the transcript flex-1 so it fills the screen.

Chat has no native:model, value, selection or editing. @change, @press and @submit are rejected.

Messages

Key Accepted type Purpose
id non-empty string Required and unique. A client-generated UUID works for unsent messages.
author non-empty string Required. Compared with me.
sent-at ISO 8601 instant Required. Messages must be in this order.
body string The text. A message needs a body, attachments, or both.
author-name string Shown above an incoming group when more than one other person writes.
status sending | sent | delivered | read | failed Outgoing only.
read-by list of display names Outgoing only. Who has read this message.
actions list of keys from actions Which authored actions this message offers.
attachments list, at most 10 See below.

Each attachment has an id unique within its message, a kind of image or file, and a source: a MediaValue, an absolute local path, or, for images only, an https:// URL. A file can have no source; opening it then fires @openAttachment. Optional keys are name, mime, size in bytes, width and height for images, progress from 0 to 1 while sending, and a11y-label.

Events

Event Receives When
@read message id The newest incoming message that has been fully on screen while the app is in the foreground, when it is newer than the last one reported. At most once a second.
@loadOlder nothing Once when the reader nears the oldest message while has-older is true. It fires again only after the next publication.
@retry message id The reader chose Try again on a failed message.
@action action key, message id The reader chose an authored action from a message's menu.
@openAttachment message id, attachment id The reader opened a file with no source. Download it and republish it with a local source; it then opens.
@windowChange $from, $to Windowed mode only. The range of messages to publish next.

Programmatic publications never fire events.

Presentation

  • Bubbles. Outgoing messages sit on the trailing side in the theme's primary colour; incoming ones on the leading side in its surface variant. Messages from one author within five minutes on the same day form a group with tighter spacing and one tail.
  • Days. A separator precedes each calendar day, in the application locale and the phone's timezone, or timezone when set. Tap a bubble to show its time.
  • Images show at their aspect ratio; several form a grid of up to four tiles with a "+N" count. Tapping one opens a full-screen viewer with pinch zoom and swiping between the message's images.
  • Files show an icon for the MIME type, the name and the size. Tapping one with a local source opens the platform preview.
  • Sending. An attachment with progress shows a progress ring.
  • Status. Only the newest outgoing message shows its status: Sending, Sent, Delivered, Read, "Read by Sam", "Read by Sam and Alex" or "Read by Sam and 2 others". A failed message shows "Not sent" with Try again.
  • Typing reads "Sam is typing", "Sam and Alex are typing" or "Several people are typing", with pulsing dots that stay still under Reduce Motion.
  • Long press opens the platform menu: Copy for a message with a body, then the message's actions. Destructive actions use the destructive style. Confirm destruction in PHP, for example with Confirmation Dialog.

Copy, Try again, Not sent, statuses, typing and New messages are package chrome; see Localize chrome.

Read receipts

Chat never computes receipts. Set status and read-by on the newest outgoing message from your server's read cursors ("read up to message N" per member); older messages need neither.

Scrolling

  • The transcript opens at the newest message.
  • A new message at the end keeps the reader at the bottom. When they have scrolled up, they stay put and a New messages button shows the count. A new outgoing message always scrolls to the bottom.
  • Older messages published above keep the reader's place.
  • Changing a message's status, body or progress updates that row in place.
  • Scrolling down dismisses the keyboard.

Long chats

Only rows near the screen exist natively, whatever the length. The cost of a long chat is the publication, so Chat has two modes:

  • Plain mode (default): messages is everything loaded so far, at most 500. Use has-older and @loadOlder to fetch more history.
  • Windowed mode, for longer conversations, follows native:virtual-list. count is the total number of messages, index 0 the oldest; messages is only the slice from window-from to window-to inclusive, at most 500. As the reader scrolls, @windowChange($from, $to) asks for the next slice. Rows outside the window keep the height they last had, so nothing on screen moves when a slice arrives. The first window should end at count - 1. Core's HasVirtualListWindow concern can hold the window. Status shows only while the window reaches the newest message.
<firstlight:chat
    class="w-full flex-1"
    :messages="$window"
    me="{{ auth()->id() }}"
    :count="$count"
    :window-from="$from"
    :window-to="$to"
    @windowChange="setWindow"
    label="Chat with Sam"
/>

Accessibility

Each message reads as one element: "You" or the author's name, the body, "2 photos" or the file's name and size, the time, and for the newest outgoing message its status. Copy, each authored action, Try again and Open for each attachment are accessibility actions, so nothing needs a long press. When the reader is at the bottom, an arriving message is announced politely; the typing row is announced when it appears. Day separators are headings, and rows outside a window are hidden from assistive technology.

Validation and failure behaviour

Invalid messages, such as a missing id, a duplicate id, messages out of order, an unknown status, a status on an incoming message, more than 500 messages, more than 10 attachments or an https:// file source, are rejected before publication with a message naming the problem.

Platform behaviour

iOS uses a SwiftUI lazy stack anchored to the bottom, the system context menu, Quick Look for files and a full-screen pager for photos. Android uses a reversed Compose LazyColumn, a Material dropdown menu, the system viewer for files through a FileProvider, and a full-screen pager for photos.

Compatibility

Chat supports the versions listed in the current compatibility reference. The host application must compile both Firstlight-owned native renderers declared by the package manifest.

Screenshots

Platform Light Dark
iOS Chat on iOS in light mode Chat on iOS in dark mode
Android Chat on Android in light mode Chat on Android in dark mode

Served from firstlightui/nativephp on GitHub.