@marktiderman/genesis-chat
0.14.1Primitive · CollaborationChat for Genesis apps, in the app's own Supabase: conversations of kinds the app defines (direct, group, cohort, support ticket) with members, observers and internal notes; messages with replies, threads, topics, mentions, reactions, edits and deletes; photos, files, voice notes and videos; read state, live updates and typing over private Realtime topics; an outbox for push, transcripts and storage cleanup. A headless core, React hooks, web and native renderers on Genesis UI, and a server runner. Part of the Genesis framework.
Chat for Genesis apps, in the app's own Supabase: direct messages, groups and the app's own kinds of conversation (a cohort, a support ticket), with photos, files, voice notes and videos, replies, threads, reactions, read state, live updates and push.
const chat = createChatClient(supabase);
pnpm add @marktiderman/genesis-chatOther exports (66)
activityLine · ALLOWED_EXTENSIONS · attachmentKindFor · awayLine · awaySummary · CHAT_BUCKET · CHAT_LIMITS · CHAT_SCHEMA · ChatError · conversationInbox · conversationTopic · createChatClient · createMemoryChatClient · createOutbox · currentActivity · dayLabel · extractLinks · fileExtension · firstUnreadId · formatDuration · hoursSummary · isAllowedExtension · isAway · isHttpsUrl · isSchedulable · isWithinWorkingHours · itemSender · itemTime · localClock · MAX_RANGES_PER_DAY · memoryOutboxStore · mergeThread · minutesOf · namesLine · nextPlaybackRate · normalizeHours · parseMentions · PLAYBACK_RATES · previewText · randomId · recordingLimitMs · releaseObjectUrl · sameDay · scheduleLabel · scheduleQuickPicks · sendBytes · snippetParts · startsDay · startsGroup · summarizeReactions · throttle · timeZoneLabel · toAttachment · toAvailability · toLinkPreview · toMessage · topicKey · toScheduled · toSearchHit · toTopic · untilLabel · upsertMessages · userTopic · waveformFromMetering · waveformPeaks · WEEKDAYS
And 57 types.
Components (1)
- ChatProvider
Puts chat in reach of every hook below it. Needs a TanStack QueryClientProvider above it.
Hooks (18)
- useAvailability
Availability: yours (`mine`, `setMine`) and, given a conversation, its members' (`members`, `forUser`). Pair with `awayLine` and `isWithinWorkingHours` from the core.
- useBroadcast
Sends one message into many conversations (replies come back privately in each).
- useChat
- useConversation
- useDebouncedValue
The value, once it has stopped changing for `ms`.
- useFileUrls
Signed links for files (cached by the client until shortly before they expire). While a new set of paths loads (a photo arrives), the links already signed stay: the photos on screen don't blank.
- useInbox
Your conversations, live. `kind` narrows to one kind; `archived` shows the archived ones.
- useInboxActions
Your own actions on one inbox row (Mark as Unread or Read, Pin, Hide Alerts, Archive, Delete for me), refreshing the inbox and badge afterwards. Each takes the row's item and returns the call's promise, so a failure reaches the caller to...
- useLinkPreviews
Link previews for these messages, by message id, in link order (only those the server has fetched). Pass the messages whose text has links (`extractLinks(body).length > 0`). One query per message, so a new message asks only for its own, ...
- useMessageActions
Edit, delete, react, pin, save and report, refreshing what they change.
- usePeople
Names and avatars for these people, from the provider's `loadPeople`, fetched as one batch per set of ids and cached. Unknown ids are left out.
- usePerson
One person's name and avatar (see usePeople).
- usePins
The pinned message ids of a conversation.
- useScheduled
Your scheduled messages (in one conversation, or all), soonest first, with `schedule` and `cancel` (which also removes one that failed). `schedule` uploads its files to storage first, the way `send` does (the provider's `upload` hook, or...
- useSearch
Search, debounced (250 ms by default), in one conversation or all of yours. Queries under two characters return nothing.
- useStartConversation
Starts (or finds again) a conversation, then refreshes the inbox.
- useTopics
A conversation's topics, live (set_topic's hint refreshes them), and `setTopic` for owners and admins: add one (`setTopic("week-1", { title: "Week 1" })`), close or reopen it.
- useUnreadTotal
How many messages wait for you everywhere (for a badge), live.
Other exports (8)
belongsTo · CATCH_UP_MAX_PAGES · CATCH_UP_PAGE · chatKeys · defaultInboxActionLabels · hostedUploadFrom · inboxRowActions · LINK_PREVIEW_CONCURRENCY
And 11 types.
Components (25)
- ChatAttachmentCard
A card for an app's own attachment kind: an icon, a title, a subtitle and one action.
- ChatAvailabilitySettings
Your availability: an away message (and until when), working hours per weekday, and the time zone they're read in. One range per day here; extra ranges saved elsewhere are kept for the days you don't change.
- ChatAwayBanner
"Mark replies Mon–Fri, 9–5 (Eastern)", "Away until Monday: Back Monday", "Sam, Lee and 2 others are away"; nothing when everyone is around.
- ChatBroadcast
- ChatComposer
- ChatDock
The dock's windows (wide screens) or its sheet and bubble (narrow). Render it once, under `ChatDockProvider`: in AppShell's `dock` slot, or anywhere fixed positioning is free.
- ChatDockProvider
- ChatEmojiPicker
- ChatErrorBoundary
- ChatInbox
- ChatLinkPreview
- ChatMarkdown
Renders a message body's inline markdown as React elements.
- ChatPanel
- ChatScheduledList
Your scheduled messages, soonest first, each with when it goes and Cancel (Remove for one that failed).
- ChatScheduleMenu
The chevron beside Send: "Schedule message" with quick picks and a custom time.
- ChatSearch
- ChatThread
- ChatTopicBar
- ChatVideoPlayer
Plays a chat video: Mux HLS (native, else hls.js loaded on demand), or a file.
- ChatVideoRecorder
The composer's video dialog: preview, record (to the role's limit), review, retake, send.
- ImageGrid
Up to four photos in a grid (a "+N" on the fourth for more), opening a lightbox.
- Lightbox
- MessageAttachments
Every attachment of one message, photos grouped into one grid.
- MessageRow
- VoiceNote
Hooks (5)
- useChatDock
The dock: open a conversation or a panel in it from anywhere under `ChatDockProvider`.
- useConfirmDialog
A `ChatConfirm` drawn as genesis-ui's AlertDialog: the confirm to pass, and the dialog to render. When the dialog closes, focus returns to the control that asked.
- useOptionalChatDock
The dock when there is one, else null: for a button that opens in the dock when the app has one, and navigates when it doesn't.
- useVideoRecorder
- useVoiceRecorder
Other exports (30)
canPickEmoji · chatDockReducer · chatDockWindowsThatFit · clockTime · createMemoryChatClient · defaultChatDockLabels · emptyChatDock · FileChip · forgetChatDock · formatBytes · GenericAttachment · inboxTitle · isSafeHref · linkPreviewImageSrc · messageLabel · muxPosterUrl · muxStreamUrl · parseMarkdown · pickVideoMimeType · pickVoiceMimeType · plainText · QUICK_REACTIONS · relativeTime · SearchSnippet · toAttachmentView · toLocalInput · uploadVideo · VideoAttachment · videoFile · voiceFile
And 34 types.
Components (41)
- AppAttachment
One app attachment in a bubble: through the app's slot when there is one, else the card.
- ChatAccessError
- ChatAttachmentCard
- ChatAvailabilityScreen
Your availability, as a Settings sub-page: an away message and, optionally, until when; working hours per weekday (one range a day here; extra ranges saved elsewhere are kept for the days you don't turn off); the time zone they're read i...
- ChatAwayLine
The away line, as a quiet strip under the header; nothing when `text` is null.
- ChatBroadcastSheet
- ChatBubbleShape
The bubble, drawn alone (the long-press preview, the inbox's peek).
- ChatComposer
- ChatContextOverlay
The long-press layer: the screen softens, the pressed thing lifts where it was, `above` sits over it and the glass menu opens under it, moving the preview when there isn't room. A choice runs once the layer has closed (iOS presents nothi...
- ChatConversationPreview
A conversation's latest messages, on a card: the inbox row's long-press peek.
- ChatDetailsScreen
- ChatEmojiPicker
- ChatEmojiPickerSheet
The picker in a sheet, with a title and Done.
- ChatFace
A contact's circle as Messages draws it: their picture, else white initials on the grey gradient, else a person.
- ChatGlassCircle
A round glass button (the composer's +, the details' actions, the search field's Cancel).
- ChatGlassMenu
- ChatGlassPanel
A floating panel: Liquid Glass where it can be drawn, else Messages' solid panel, with a shadow either way.
- ChatIconButton
- ChatInboxScreen
- ChatLinkPreviewCard
- ChatMediaViewer
One picture in the full-screen viewer (`ChatPhotoViewer` pages through several).
- ChatMessageMenu
- ChatNativeProvider
Inside `ChatProvider` (from `/react`). Optional: without it there are no native extras and people are "Someone".
- ChatPhotoViewer
Chat's photos full screen: genesis-ui-native's `NativeLightbox` (pinch and double-tap zoom, pull down to close, an adjustable pager), with chat's words and its Save and Share buttons when the app passes `mediaLibrary` and `sharing` to `C...
- ChatScheduledBar
"2 scheduled messages" over the composer when there are any, opening their list.
- ChatScheduledList
Your scheduled messages, soonest first, each with when it goes and Cancel.
- ChatScheduleSheet
- ChatSearchScreen
- ChatStartSheet
- ChatSymbol
An SF Symbol on iOS, Genesis's icon elsewhere. Decorative: label what it sits in.
- ChatThreadScreen
- ChatThreadTitle
- ChatTopicBar
- ChatTypingBubble
- ChatVideoPlayer
The bubble's video. Renders nothing without `modules.video` (the bubble shows a row instead).
- ChatVideoRecorder
Renders nothing without `modules.camera`.
- MessageActionsSheet
- MessageBubble
- VideoUploadTray
- VoiceNotePlayer
- VoiceTranscript
A voice note's transcript under the player: "Transcribing…" while it is made, then the text, folded to three lines with "Show more" when it is longer. The bubble reads the whole transcript to VoiceOver, so the toggle is for sight only.
Hooks (16)
- useAwayLine
`awayLineFor` over the conversation's members, live (`useAvailability`), re-read each minute.
- useCardRuns
Runs the app's actions for a message's cards (tick a task, answer a check-in) and keeps each card's state by attachment id: `pending` until the action settles, then `error` (the copy's `cardActionFailed`) if it threw or rejected. Only a ...
- useChatAutoRetry
- useChatColors
`chatColors` for the app's light or dark scheme.
- useChatComposer
`userId` is the signed-in person's (`useChat().userId`): drafts are kept per person.
- useChatFeel
Messages' haptics, through Genesis's: a light tap for a choice or tapback, medium when a menu opens, a soft one on send.
- useChatMotion
Springs and fades from Genesis's motion tokens. Under Reduce Motion `reduced` is true and durations are 0.
- useChatNative
- useChatThreadStackOptions
`chatThreadStackOptions` on the chat role `pageSolid`: the page as a plain string for the scheme, since the native header takes no PlatformColor for its background. It follows a scheme change.
- useJumpToMessage
- useOnline
Whether the phone is online, from the app's NetInfo (`modules.netInfo`); null without it or until it says.
- usePlayingVideo
Which of these videos is playing, or null (re-renders only when that answer changes).
- usePlayingVoiceNote
Which of these voice notes is playing, or null (re-renders only when that answer changes).
- useScheduleSend
Scheduled send from a thread's composer: `request` (Send held) checks there's text and no files and opens the sheet; `scheduleAt` schedules what's written, then empties the composer if it still holds just that. Pass `enabled: false` wher...
- useVideoUploads
The signed-in person's videos on their way to this conversation, live.
- useVoiceRecorder
Other exports (196)
activePlaybackId · alertConfirm · applyInboxFilter · AT_BOTTOM_POINTS · attachmentKindOf · attachmentPaths · attachmentPreview · availabilityInput · awayLineFor · barsThatFit · base64ToBytes · base64Utf8 · broadcastOutcome · broadcastRows · bubbleCorners · bubblePosition · buildThreadRows · BUILT_IN_KINDS · canManageTopics · canReactTo · canSend · CARD_ACTION_TIMEOUT_MS · cardAction · CardError · cardTitle · CHAT_MARK_READ_ACTION · CHAT_METRICS · CHAT_PUSH_CATEGORY · CHAT_REPLY_ACTION · CHAT_TYPE · ChatAccentIcon · ChatAutoRetry · ChatBubbleTail · chatClock · chatColors · ChatConversationMenu · ChatDetailsActions · ChatDetailsDanger · ChatDetailsHero · ChatDetailsMembers · ChatDetailsSettings · ChatGlassList · ChatInboxRowContent · chatNativeCopy · chatNotificationActions · chatOrganiseCopy · chatPath · ChatPinnedFaces · ChatPlusList · chatPushCategory · chatPushCopy · chatPushPayload · ChatSearchField · ChatStartButton · ChatTap · chatThreadMatch · chatThreadStackOptions · checkTopicName · chunkedPut · claimPlayback · clearDrafts · clockToDate · composerDisabledReason · composerReducer · connectionState · conversationIdFromData · countUnseenBelow · createDraftSaver · createTusUpload · createVideoUploads · cycleVideoRate · cycleVoiceNoteRate · dateToClock · defaultInboxFilters · defaultScheduleAt · defaultWeek · deviceTimeZone · DISMISS_DISTANCE · DISMISS_VELOCITY · displayBody · draftKey · EMOJI_CATEGORIES · emojiEntry · emojiInCategory · emptyComposer · failedReply · fileFromDataUri · filesFromAssets · fileSource · fill · forgetRecentEmoji · formatClock · formFrom · fullScreenVideo · galleryFor · handleChatPushResponse · haptic · hoursFromWeek · idleRecorder · inboxHeaderItems · inboxRow · initials · initialVideoRecorder · insertAtSelection · invertedRows · isGroupConversation · isLocalUri · isOnline · isOpenableHref · isSelfConversation · isSelfMembers · isVideoPlaying · lastSentReceipt · linkHost · linkPreviewIds · liveBars · loadDraft · loadRecentEmoji · matchesInboxSearch · MAX_ZOOM · memoryDraftStorage · messageActionsFor · MessageAttachments · messagePreview · ModerationMarker · moderationNote · moderationText · muxPosterUrl · muxStreamUrl · nearBottom · nextOffset · openChatLink · panLimit · pauseChatPlayback · pinchScale · pinnedConversations · previewToShow · PUSH_REPLY_WAIT_MS · pushRecentEmoji · QUICK_REACTIONS · readWhen · receiptText · RECENT_EMOJI_MAX · recentEmojiKey · recordedVideoFile · recorderStep · recordingType · registerChatNotificationActions · releasePlayback · replyClientId · replyClientIdFor · replyTargetFor · resolveChatCopy · rowIndexOf · rowKey · runPositions · sameTimeDays · saveRecentEmoji · scheduleInputFrom · scrubSeconds · searchEmoji · SearchSnippet · shouldDismiss · slotUrl · snippetText · splitCardAttachments · startsTimeReveal · startsTimeSeparator · TAPBACKS · threadListMode · TIME_REVEAL_WIDTH · TIME_SEPARATOR_GAP_MS · timeRevealFor · timeSeparatorLabel · timeZones · toggleVideo · toggleVideoMute · toggleVoiceNote · topicClosedFor · topicMenuFor · toSend · TRANSCRIPT_LINES · transcriptIsLong · TUS_CHUNK_BYTES · VIDEO_CHUNK_BYTES · VIDEO_HOLD_MS · VIDEO_MIN_MS · videoRecorderStep · videoSource · videoState · videoUploads · voiceNoteFile · waveformBars · weekFromHours · withDay · withTime
And 119 types.
Other exports (16)
CHAT_MARK_READ_ACTION · CHAT_PUSH_CATEGORY · CHAT_REPLY_ACTION · chatNotificationActions · chatPath · chatPushCategory · chatPushCopy · chatPushPayload · chatThreadMatch · conversationIdFromData · failedReply · handleChatPushResponse · PUSH_REPLY_WAIT_MS · registerChatNotificationActions · replyClientId · replyClientIdFor
And 8 types.
Other exports (41)
ANTHROPIC_MESSAGES_URL · ANTHROPIC_VERSION · carriesCredential · CHAT_ASSISTANT_MODEL · CHAT_MAX_ATTEMPTS · CHAT_NOTIFICATION_CATEGORIES · CHAT_NOTIFICATION_TYPE_ID · CHAT_NOTIFICATION_TYPES · chatNotifyInput · chatRunnerHandler · chatUploadPassthrough · createChatAssistant · createChatRunner · createExpoDeliver · createLinkUnfurler · createVideoUploadHandler · deadTokens · decodeEntities · deepgramTranscriber · draftPrompt · draftSystem · EXPO_BATCH · EXPO_SEND_URL · fakeVideoProvider · guardedLookup · isPrivateAddress · moderationVerdict · muxPlaybackToken · muxPlaybackUrl · muxVideo · notificationsDeliver · OPENAI_MODERATION_CATEGORIES · OPENAI_MODERATIONS_URL · openAiModerator · openAiTranscriber · parseChatUploadPassthrough · parseOpenGraph · recapPrompt · recapSystem · transcriptLines · verifyMuxSignature
And 43 types.
Other exports (3)
CHAT_AI_REFUSALS · chatDraftReplyTask · chatRecapTask
And 4 types.