@stacksjs/components 0.2.428 → 0.2.429
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ChatInbox-tjcdj8c1.stx +95 -0
- package/dist/ChatMessage-rj37tdgn.stx +12 -0
- package/dist/ChatUnreadBadge-sp06phw6.stx +11 -0
- package/dist/chat/controller.js +210 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +9 -9
- package/dist/ui/chat/controller.d.ts +40 -0
- package/dist/ui/chat/index.d.ts +6 -0
- package/package.json +8 -3
- package/src/index.ts +2 -0
- package/src/ui/chat/ChatInbox.stx +95 -0
- package/src/ui/chat/ChatMessage.stx +12 -0
- package/src/ui/chat/ChatUnreadBadge.stx +11 -0
- package/src/ui/chat/README.md +46 -0
- package/src/ui/chat/controller.ts +184 -0
- package/src/ui/chat/index.ts +6 -0
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
<script server>
|
|
2
|
+
export const storeName = $props.store || 'chat'
|
|
3
|
+
export const className = $props.className || ''
|
|
4
|
+
</script>
|
|
5
|
+
<script client>
|
|
6
|
+
const chat = useStore({{ storeName }})
|
|
7
|
+
const rows = chat.rows
|
|
8
|
+
const selected = chat.selected
|
|
9
|
+
const messages = chat.messages
|
|
10
|
+
const draft = chat.draft
|
|
11
|
+
const search = chat.search
|
|
12
|
+
const unreadOnly = chat.unreadOnly
|
|
13
|
+
const unread = chat.unread
|
|
14
|
+
const error = chat.error
|
|
15
|
+
const loading = chat.loading
|
|
16
|
+
const threadLoading = chat.threadLoading
|
|
17
|
+
const hasMore = chat.hasMore
|
|
18
|
+
const canSend = chat.canSend
|
|
19
|
+
const sending = chat.sending
|
|
20
|
+
const maxLength = chat.maxLength
|
|
21
|
+
const selfId = chat.selfId
|
|
22
|
+
const history = useRef('chat-history')
|
|
23
|
+
const composer = useRef('chat-composer')
|
|
24
|
+
let lastThread = ''
|
|
25
|
+
let lastMessage = 0
|
|
26
|
+
effect(() => {
|
|
27
|
+
const id = chat.threadId()
|
|
28
|
+
const list = messages()
|
|
29
|
+
const last = list.at(-1)
|
|
30
|
+
const changedThread = id !== lastThread
|
|
31
|
+
const newMessage = last && last.id !== lastMessage
|
|
32
|
+
const element = history()
|
|
33
|
+
const nearBottom = element && element.scrollHeight - element.scrollTop - element.clientHeight < 120
|
|
34
|
+
if (element && (changedThread || newMessage && (nearBottom || last.sender_id === selfId()))) {
|
|
35
|
+
nextTick(() => { element.scrollTop = element.scrollHeight })
|
|
36
|
+
}
|
|
37
|
+
if (changedThread && id) nextTick(() => composer()?.focus())
|
|
38
|
+
lastThread = id
|
|
39
|
+
lastMessage = last?.id || 0
|
|
40
|
+
})
|
|
41
|
+
const hasSelection = derived(() => !!selected())
|
|
42
|
+
const noSelection = derived(() => !selected())
|
|
43
|
+
const emptyRows = derived(() => !loading() && rows().length === 0)
|
|
44
|
+
const emptyThread = derived(() => hasSelection() && !threadLoading() && messages().length === 0)
|
|
45
|
+
const selectedName = derived(() => selected()?.name || '')
|
|
46
|
+
const selectedRole = derived(() => selected()?.role || '')
|
|
47
|
+
const sendLabel = derived(() => sending() ? 'Sending...' : 'Send message')
|
|
48
|
+
function initials(name) { return String(name || '').split(' ').map(p => p[0]).slice(0, 2).join('').toUpperCase() }
|
|
49
|
+
function timestamp(value) { return new Date(value).toLocaleString([], { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) }
|
|
50
|
+
function submit() { return chat.send() }
|
|
51
|
+
function keyboard(event) { if ((event.ctrlKey || event.metaKey) && event.key === 'Enter' && !event.isComposing) { event.preventDefault(); chat.send() } }
|
|
52
|
+
onMount(() => chat.load())
|
|
53
|
+
useInterval(() => chat.refresh(true), 10000, { whileVisible: true })
|
|
54
|
+
</script>
|
|
55
|
+
<section aria-label="Messages" class="flex flex-col min-h-[540px] h-[calc(100dvh-180px)] max-h-[900px] overflow-hidden bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-2xl {{ className }}">
|
|
56
|
+
<div :if="error" role="alert" class="flex gap-3 items-center justify-between px-4 py-3 text-sm text-rose-800 dark:text-rose-200 bg-rose-50 dark:bg-rose-950">
|
|
57
|
+
<span :text="error"></span><button type="button" @click="chat.refresh(true)" class="font-semibold underline">Try again</button>
|
|
58
|
+
</div>
|
|
59
|
+
<div class="flex flex-1 min-h-0">
|
|
60
|
+
<aside aria-label="Conversations" :class="hasSelection ? 'hidden md:flex' : 'flex'" class="flex-col w-full md:w-80 shrink-0 border-r border-slate-200 dark:border-slate-800">
|
|
61
|
+
<div class="px-5 pt-5 pb-4 space-y-4">
|
|
62
|
+
<div class="flex items-center justify-between"><h2 class="font-semibold text-slate-900 dark:text-white">Inbox</h2><span :if="unread" class="px-2 py-0.5 text-xs font-semibold text-blue-700 dark:text-blue-200 bg-blue-50 dark:bg-blue-950 rounded-full"><span :text="unread"></span> unread</span></div>
|
|
63
|
+
<label class="block"><span class="sr-only">Search people</span><input type="search" x-model="search" placeholder="Search athletes or staff" class="w-full px-3 py-2.5 text-sm text-slate-900 dark:text-white bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"></label>
|
|
64
|
+
<label class="flex gap-2 items-center text-sm text-slate-600 dark:text-slate-300"><input type="checkbox" x-model="unreadOnly" class="accent-blue-600">Unread only</label>
|
|
65
|
+
</div>
|
|
66
|
+
<p :if="loading" role="status" class="px-5 pb-2 text-xs text-slate-500 dark:text-slate-400">Updating messages...</p>
|
|
67
|
+
<div class="flex-1 overflow-y-auto px-2 pb-2">
|
|
68
|
+
<button :for="person in rows" type="button" @click="chat.open(person)" :aria-pressed="selected && selected.id === person.id" :class="selected && selected.id === person.id ? 'bg-blue-50 dark:bg-blue-950' : 'hover:bg-slate-50 dark:hover:bg-slate-900'" class="flex gap-3 items-start w-full p-3 text-left rounded-xl focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500">
|
|
69
|
+
<span class="flex items-center justify-center w-10 h-10 shrink-0 text-sm font-semibold text-slate-600 dark:text-slate-200 bg-slate-100 dark:bg-slate-800 rounded-full" :text="initials(person.name)"></span>
|
|
70
|
+
<span class="flex-1 min-w-0"><span class="flex items-center justify-between gap-2"><span class="font-semibold text-sm text-slate-900 dark:text-white truncate" :text="person.name"></span><span :if="person.conversation && person.conversation.unread" class="px-1.5 min-w-5 text-center text-xs font-semibold text-white bg-blue-600 rounded-full" :text="person.conversation.unread"></span></span><span class="block mt-0.5 text-xs text-slate-500 dark:text-slate-400" :text="person.role"></span><span class="block mt-1 text-sm text-slate-600 dark:text-slate-300 truncate" :text="person.conversation && person.conversation.last_message ? person.conversation.last_message.body : 'Start a conversation'"></span></span>
|
|
71
|
+
</button>
|
|
72
|
+
<div :if="emptyRows" class="px-4 py-10 text-center"><p class="font-semibold text-sm text-slate-900 dark:text-white">No conversations here yet</p><p class="mt-2 text-sm text-slate-500 dark:text-slate-400">Try another search or turn off the unread filter. Your connected athletes and gym team appear here.</p></div>
|
|
73
|
+
</div>
|
|
74
|
+
</aside>
|
|
75
|
+
<div :if="noSelection" class="hidden md:flex flex-1 flex-col items-center justify-center px-8 text-center bg-slate-50/50 dark:bg-slate-900/30">
|
|
76
|
+
<span class="i-lucide-messages-square text-3xl text-blue-600 dark:text-blue-400" aria-hidden="true"></span><h2 class="mt-4 text-lg font-semibold text-slate-900 dark:text-white">A place for the conversation</h2><p class="mt-2 max-w-xs text-sm leading-6 text-slate-500 dark:text-slate-400">Training questions, session feedback, or a quick check-in. Choose someone from your inbox to get started.</p>
|
|
77
|
+
</div>
|
|
78
|
+
<div :if="hasSelection" class="flex flex-1 flex-col min-w-0">
|
|
79
|
+
<header class="flex items-center gap-3 px-4 md:px-6 py-4 border-b border-slate-200 dark:border-slate-800">
|
|
80
|
+
<button type="button" @click="chat.back()" aria-label="Back to inbox" class="md:hidden p-2 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800"><span class="i-lucide-arrow-left" aria-hidden="true"></span></button><div class="flex-1"><h2 class="font-semibold text-slate-900 dark:text-white" :text="selectedName"></h2><p class="mt-0.5 text-xs text-slate-500 dark:text-slate-400" :text="selectedRole"></p></div><button type="button" @click="chat.refresh(true)" aria-label="Refresh conversation" class="p-2 text-slate-500 dark:text-slate-400 rounded-lg hover:bg-slate-100 dark:hover:bg-slate-800"><span class="i-lucide-refresh-cw" aria-hidden="true"></span></button>
|
|
81
|
+
</header>
|
|
82
|
+
<div ref="chat-history" role="log" aria-label="Conversation history" aria-live="polite" aria-relevant="additions" :aria-busy="threadLoading" class="flex flex-col flex-1 min-h-0 overflow-y-auto px-4 md:px-6 py-5 gap-4">
|
|
83
|
+
<button :if="hasMore" type="button" @click="chat.older()" :disabled="threadLoading" class="self-center text-sm text-blue-700 dark:text-blue-300 font-medium underline">Load earlier messages</button>
|
|
84
|
+
<p :if="threadLoading" role="status" class="text-center text-sm text-slate-500 dark:text-slate-400">Loading conversation...</p>
|
|
85
|
+
<div :if="emptyThread" class="my-auto text-center"><p class="font-semibold text-slate-900 dark:text-white">Start with a question or a check-in</p><p class="mt-2 text-sm text-slate-500 dark:text-slate-400">Messages stay here so you can pick up where you left off.</p></div>
|
|
86
|
+
<article :for="message in messages" :class="message.sender_id === selfId ? 'items-end' : 'items-start'" class="flex flex-col gap-1.5">
|
|
87
|
+
<p :class="message.sender_id === selfId ? 'bg-blue-600 text-white' : 'bg-slate-100 dark:bg-slate-800 text-slate-900 dark:text-white'" class="max-w-[88%] md:max-w-[75%] whitespace-pre-wrap break-words px-4 py-3 rounded-2xl text-sm leading-6" :text="message.body"></p><span class="text-[11px] text-slate-500 dark:text-slate-400"><time :datetime="message.created_at" :text="timestamp(message.created_at)"></time><span :if="message.sender_id === selfId" :text="message.read_at ? ' · Read' : ' · Sent'"></span></span>
|
|
88
|
+
</article>
|
|
89
|
+
</div>
|
|
90
|
+
<form @submit.prevent="submit()" class="px-4 md:px-6 pt-3 pb-4 border-t border-slate-200 dark:border-slate-800">
|
|
91
|
+
<label for="chat-draft" class="sr-only">Write a message</label><textarea ref="chat-composer" id="chat-draft" x-model="draft" @keydown="keyboard($event)" :maxlength="maxLength" :disabled="sending" rows="3" placeholder="Write a message..." class="w-full resize-none px-3 py-2 text-sm leading-6 text-slate-900 dark:text-white placeholder:text-slate-500 bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-700 rounded-xl focus:outline-none focus:ring-2 focus:ring-blue-500"></textarea><div class="flex items-center justify-between gap-3 mt-2"><span class="text-xs text-slate-500 dark:text-slate-400">Ctrl or ⌘ + Enter to send</span><button type="submit" :disabled="!canSend" class="shrink-0 inline-flex gap-2 items-center px-4 py-2.5 text-sm font-semibold text-white bg-blue-600 hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed rounded-lg focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2"><span :text="sendLabel">Send message</span><span class="i-lucide-send" aria-hidden="true"></span></button></div>
|
|
92
|
+
</form>
|
|
93
|
+
</div>
|
|
94
|
+
</div>
|
|
95
|
+
</section>
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
<script server>
|
|
2
|
+
export const body = $props.body || ''
|
|
3
|
+
export const author = $props.author || ''
|
|
4
|
+
export const time = $props.time || ''
|
|
5
|
+
export const outgoing = $bool($props.outgoing)
|
|
6
|
+
export const className = $props.className || ''
|
|
7
|
+
</script>
|
|
8
|
+
<article class="flex flex-col gap-1 {{ outgoing ? 'items-end' : 'items-start' }} {{ className }}">
|
|
9
|
+
<span class="text-xs text-fg-muted">{{ author }}</span>
|
|
10
|
+
<p class="max-w-[85%] whitespace-pre-wrap break-words rounded-panel px-4 py-3 text-sm {{ outgoing ? 'bg-accent text-accent-ink' : 'bg-surface-sunken text-fg' }}">{{ body }}</p>
|
|
11
|
+
<time class="text-xs text-fg-muted">{{ time }}</time>
|
|
12
|
+
</article>
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
<script server>
|
|
2
|
+
export const storeName = $props.store || 'chat'
|
|
3
|
+
</script>
|
|
4
|
+
<script client>
|
|
5
|
+
const chat = useStore({{ storeName }})
|
|
6
|
+
const unread = chat.unread
|
|
7
|
+
const label = derived(() => unread() + ' unread messages')
|
|
8
|
+
onMount(() => chat.load())
|
|
9
|
+
useInterval(() => chat.refresh(), 15000, { whileVisible: true })
|
|
10
|
+
</script>
|
|
11
|
+
<span :if="unread" :aria-label="label" class="inline-flex items-center justify-center min-w-5 px-1.5 py-0.5 text-[11px] font-semibold text-white bg-blue-600 rounded-full" :text="unread"></span>
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# Chat
|
|
2
|
+
|
|
3
|
+
A responsive inbox, conversation history, read receipts and composer for STX.
|
|
4
|
+
`ChatMessage` is also available for standalone server-rendered messages.
|
|
5
|
+
|
|
6
|
+
```ts
|
|
7
|
+
// resources/stores/chat.ts
|
|
8
|
+
import { createChat } from '@stacksjs/components/chat'
|
|
9
|
+
import { defineStore } from '@stacksjs/stx'
|
|
10
|
+
|
|
11
|
+
defineStore('chat', () => createChat({
|
|
12
|
+
request: authenticatedFetch,
|
|
13
|
+
selfId: () => currentUser().id,
|
|
14
|
+
scopeKey: () => `${currentUser().id}:${currentGym().id}`,
|
|
15
|
+
endpoint: '/messages',
|
|
16
|
+
}))
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
```html
|
|
20
|
+
<ChatInbox store="chat" />
|
|
21
|
+
<ChatUnreadBadge store="chat" />
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
`store` defaults to `chat`. Both components use the same controller. Polling
|
|
25
|
+
pauses when the page is hidden; an inbox acknowledges only displayed messages.
|
|
26
|
+
Drafts stay per contact until sent and clear when the account or tenant changes.
|
|
27
|
+
Failed sends preserve the draft and retry key. Ctrl/Command + Enter sends;
|
|
28
|
+
plain Enter starts a new line. Message bodies render as escaped text.
|
|
29
|
+
|
|
30
|
+
The injected transport returns JSON:
|
|
31
|
+
|
|
32
|
+
| Request | Response |
|
|
33
|
+
| --- | --- |
|
|
34
|
+
| GET /messages | `{ contacts: [{ id, name, role }], conversations: [{ id, recipient_id, unread, last_message }], max_length }` |
|
|
35
|
+
| POST /messages/conversations `{ recipient_id }` | `{ id, recipient_id }` |
|
|
36
|
+
| GET /messages/conversations/:id?before=:messageId | `{ messages, has_more }` |
|
|
37
|
+
| POST /messages/conversations/:id/messages `{ body, client_key }` | saved message |
|
|
38
|
+
| POST /messages/conversations/:id/read `{ through_id }` | success |
|
|
39
|
+
|
|
40
|
+
Messages contain `id`, `sender_id`, `body`, `created_at`, `read_at`, and
|
|
41
|
+
`client_key`. HTTP failures use `{ error }`. The server owns authorization and
|
|
42
|
+
scope selection. Stacks' native `createMessenger` supplies this persistence API.
|
|
43
|
+
|
|
44
|
+
The browser controller has its own public entry, `@stacksjs/components/chat`,
|
|
45
|
+
so pages do not import the library's server syntax-highlighting dependencies.
|
|
46
|
+
Run the component build before running its published-entry regression test.
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import type { Signal, DerivedSignal } from '@stacksjs/stx'
|
|
2
|
+
import { derived, state } from '@stacksjs/stx'
|
|
3
|
+
|
|
4
|
+
export interface ChatContact { id: number, name: string, role: string }
|
|
5
|
+
export interface ChatMessage { id: number, sender_id: number, body: string, created_at: string, read_at: string | null, client_key: string }
|
|
6
|
+
export interface ChatConversation { id: string, recipient_id: number, unread: number, last_message: ChatMessage | null }
|
|
7
|
+
export interface ChatOptions {
|
|
8
|
+
request: (path: string, init?: RequestInit) => Promise<Response>
|
|
9
|
+
selfId: () => number
|
|
10
|
+
/** Include both the account and selected tenant. Clears private state when either changes. */
|
|
11
|
+
scopeKey: () => string
|
|
12
|
+
initialRecipient?: () => number
|
|
13
|
+
endpoint?: string
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface ChatController {
|
|
17
|
+
contacts: Signal<ChatContact[]>
|
|
18
|
+
conversations: Signal<ChatConversation[]>
|
|
19
|
+
selected: Signal<ChatContact | null>
|
|
20
|
+
threadId: Signal<string>
|
|
21
|
+
messages: Signal<ChatMessage[]>
|
|
22
|
+
loading: Signal<boolean>
|
|
23
|
+
threadLoading: Signal<boolean>
|
|
24
|
+
sending: Signal<boolean>
|
|
25
|
+
error: Signal<string>
|
|
26
|
+
draft: Signal<string>
|
|
27
|
+
search: Signal<string>
|
|
28
|
+
unreadOnly: Signal<boolean>
|
|
29
|
+
hasMore: Signal<boolean>
|
|
30
|
+
maxLength: Signal<number>
|
|
31
|
+
rows: DerivedSignal<Array<ChatContact & { conversation: ChatConversation | undefined }>>
|
|
32
|
+
unread: DerivedSignal<number>
|
|
33
|
+
canSend: DerivedSignal<boolean>
|
|
34
|
+
selfId: DerivedSignal<number>
|
|
35
|
+
load: () => Promise<void>
|
|
36
|
+
open: (contact: ChatContact) => Promise<void>
|
|
37
|
+
back: () => void
|
|
38
|
+
send: () => Promise<void>
|
|
39
|
+
older: () => Promise<void>
|
|
40
|
+
refresh: (markRead?: boolean) => Promise<void>
|
|
41
|
+
reset: () => void
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Transport-injected messaging state shared by any STX app. */
|
|
45
|
+
export function createChat(options: ChatOptions): ChatController {
|
|
46
|
+
const endpoint = options.endpoint ?? '/messages'
|
|
47
|
+
const contacts = state<ChatContact[]>([])
|
|
48
|
+
const conversations = state<ChatConversation[]>([])
|
|
49
|
+
const selected = state<ChatContact | null>(null)
|
|
50
|
+
const threadId = state('')
|
|
51
|
+
const messages = state<ChatMessage[]>([])
|
|
52
|
+
const loading = state(false)
|
|
53
|
+
const threadLoading = state(false)
|
|
54
|
+
const sending = state(false)
|
|
55
|
+
const error = state('')
|
|
56
|
+
const draft = state('')
|
|
57
|
+
const search = state('')
|
|
58
|
+
const unreadOnly = state(false)
|
|
59
|
+
const hasMore = state(false)
|
|
60
|
+
const maxLength = state(4000)
|
|
61
|
+
let scope = ''
|
|
62
|
+
let version = 0
|
|
63
|
+
let drafts = new Map<number, string>()
|
|
64
|
+
let retry: { body: string, key: string, thread: string } | null = null
|
|
65
|
+
let refreshing = false
|
|
66
|
+
let initialOpened = false
|
|
67
|
+
|
|
68
|
+
function reset() {
|
|
69
|
+
version++
|
|
70
|
+
contacts.set([]); conversations.set([]); selected.set(null); threadId.set(''); messages.set([])
|
|
71
|
+
draft.set(''); error.set(''); loading.set(false); threadLoading.set(false); sending.set(false)
|
|
72
|
+
drafts = new Map(); retry = null; initialOpened = false; hasMore.set(false)
|
|
73
|
+
}
|
|
74
|
+
function checkScope() {
|
|
75
|
+
const key = options.scopeKey()
|
|
76
|
+
if (key !== scope) { reset(); scope = key }
|
|
77
|
+
return version
|
|
78
|
+
}
|
|
79
|
+
async function json(path: string, init?: RequestInit) {
|
|
80
|
+
const response = await options.request(`${endpoint}${path}`, init)
|
|
81
|
+
const body = await response.json().catch(() => ({}))
|
|
82
|
+
if (!response.ok) throw new Error(body.error || 'Could not load messages. Try again.')
|
|
83
|
+
return body
|
|
84
|
+
}
|
|
85
|
+
const rows = derived(() => {
|
|
86
|
+
const q = search().toLowerCase().trim()
|
|
87
|
+
return contacts().map(contact => ({ ...contact, conversation: conversations().find(c => c.recipient_id === contact.id) }))
|
|
88
|
+
.filter(row => (!q || `${row.name} ${row.role}`.toLowerCase().includes(q)) && (!unreadOnly() || (row.conversation?.unread ?? 0) > 0))
|
|
89
|
+
.sort((a, b) => (b.conversation?.last_message?.id ?? 0) - (a.conversation?.last_message?.id ?? 0) || a.name.localeCompare(b.name))
|
|
90
|
+
})
|
|
91
|
+
const unread = derived(() => conversations().reduce((sum, c) => sum + c.unread, 0))
|
|
92
|
+
const canSend = derived(() => !!threadId() && !!draft().trim() && draft().trim().length <= maxLength() && !sending() && !threadLoading())
|
|
93
|
+
const selfId = derived(options.selfId)
|
|
94
|
+
function failure(cause: unknown) { error.set(cause instanceof Error ? cause.message : 'Could not load messages. Try again.') }
|
|
95
|
+
|
|
96
|
+
async function refreshThread(token: number, id: string, mark = true) {
|
|
97
|
+
const data = await json(`/conversations/${id}`)
|
|
98
|
+
if (token !== version || id !== threadId() || options.scopeKey() !== scope) return
|
|
99
|
+
// Keep older history the person already loaded while refreshing the latest page.
|
|
100
|
+
const first = data.messages[0]?.id
|
|
101
|
+
messages.set([...messages().filter(m => first && m.id < first), ...data.messages])
|
|
102
|
+
if (messages().length === data.messages.length) hasMore.set(data.has_more)
|
|
103
|
+
const last = data.messages.at(-1)
|
|
104
|
+
if (mark && last) {
|
|
105
|
+
await json(`/conversations/${id}/read`, { method: 'POST', body: JSON.stringify({ through_id: last.id }) })
|
|
106
|
+
if (token === version && id === threadId()) conversations.update(list => list.map(c => c.id === id ? { ...c, unread: 0 } : c))
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
async function load() {
|
|
110
|
+
const token = checkScope()
|
|
111
|
+
loading.set(true); error.set('')
|
|
112
|
+
try {
|
|
113
|
+
const data = await json('')
|
|
114
|
+
if (token !== version || options.scopeKey() !== scope) return
|
|
115
|
+
contacts.set(data.contacts); conversations.set(data.conversations); maxLength.set(data.max_length); loading.set(false)
|
|
116
|
+
if (!initialOpened && options.initialRecipient) {
|
|
117
|
+
initialOpened = true
|
|
118
|
+
const person = data.contacts.find((c: ChatContact) => c.id === options.initialRecipient!())
|
|
119
|
+
if (person) await open(person)
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
catch (cause) { if (token === version) failure(cause) }
|
|
123
|
+
finally { if (token === version) loading.set(false) }
|
|
124
|
+
}
|
|
125
|
+
async function open(contact: ChatContact) {
|
|
126
|
+
checkScope()
|
|
127
|
+
if (selected()) drafts.set(selected()!.id, draft())
|
|
128
|
+
const token = ++version
|
|
129
|
+
sending.set(false); selected.set(contact); draft.set(drafts.get(contact.id) ?? ''); threadId.set(''); messages.set([]); hasMore.set(false)
|
|
130
|
+
error.set(''); threadLoading.set(true)
|
|
131
|
+
try {
|
|
132
|
+
const data = await json('/conversations', { method: 'POST', body: JSON.stringify({ recipient_id: contact.id }) })
|
|
133
|
+
if (token !== version || options.scopeKey() !== scope) return
|
|
134
|
+
threadId.set(data.id)
|
|
135
|
+
await refreshThread(token, data.id)
|
|
136
|
+
}
|
|
137
|
+
catch (cause) { if (token === version) failure(cause) }
|
|
138
|
+
finally { if (token === version) threadLoading.set(false) }
|
|
139
|
+
}
|
|
140
|
+
function back() {
|
|
141
|
+
if (selected()) drafts.set(selected()!.id, draft())
|
|
142
|
+
version++; sending.set(false); threadLoading.set(false); selected.set(null); threadId.set(''); messages.set([]); error.set('')
|
|
143
|
+
}
|
|
144
|
+
async function send() {
|
|
145
|
+
checkScope()
|
|
146
|
+
if (!canSend()) return
|
|
147
|
+
const id = threadId(), body = draft().trim(), token = version
|
|
148
|
+
const key = retry?.body === body && retry.thread === id ? retry.key : crypto.randomUUID()
|
|
149
|
+
retry = { body, key, thread: id }
|
|
150
|
+
sending.set(true); error.set('')
|
|
151
|
+
try {
|
|
152
|
+
await json(`/conversations/${id}/messages`, { method: 'POST', body: JSON.stringify({ body, client_key: key }) })
|
|
153
|
+
if (token !== version || options.scopeKey() !== scope) return
|
|
154
|
+
if (draft().trim() === body) draft.set('')
|
|
155
|
+
drafts.delete(selected()!.id); retry = null
|
|
156
|
+
await refreshThread(token, id)
|
|
157
|
+
await load()
|
|
158
|
+
}
|
|
159
|
+
catch (cause) { if (token === version) failure(cause) }
|
|
160
|
+
finally { if (token === version) sending.set(false) }
|
|
161
|
+
}
|
|
162
|
+
async function older() {
|
|
163
|
+
const id = threadId(), before = messages()[0]?.id, token = version
|
|
164
|
+
if (!id || !before || threadLoading()) return
|
|
165
|
+
threadLoading.set(true)
|
|
166
|
+
try {
|
|
167
|
+
const data = await json(`/conversations/${id}?before=${before}`)
|
|
168
|
+
if (token === version && id === threadId()) { messages.set([...data.messages, ...messages()]); hasMore.set(data.has_more) }
|
|
169
|
+
}
|
|
170
|
+
catch (cause) { if (token === version) failure(cause) }
|
|
171
|
+
finally { if (token === version) threadLoading.set(false) }
|
|
172
|
+
}
|
|
173
|
+
async function refresh(markRead = false) {
|
|
174
|
+
if (refreshing || sending() || threadLoading()) return
|
|
175
|
+
refreshing = true
|
|
176
|
+
try {
|
|
177
|
+
await load()
|
|
178
|
+
if (markRead && threadId()) await refreshThread(version, threadId())
|
|
179
|
+
}
|
|
180
|
+
catch (cause) { failure(cause) }
|
|
181
|
+
finally { refreshing = false }
|
|
182
|
+
}
|
|
183
|
+
return { contacts, conversations, selected, threadId, messages, loading, threadLoading, sending, error, draft, search, unreadOnly, hasMore, maxLength, rows, unread, canSend, selfId, load, open, back, send, older, refresh, reset }
|
|
184
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { default as ChatInbox } from './ChatInbox.stx'
|
|
2
|
+
export { default as ChatMessage } from './ChatMessage.stx'
|
|
3
|
+
export * from './controller'
|
|
4
|
+
export interface ChatInboxProps { store?: string, className?: string }
|
|
5
|
+
export interface ChatMessageProps { body?: string, author?: string, time?: string, outgoing?: boolean, className?: string }
|
|
6
|
+
export { default as ChatUnreadBadge } from './ChatUnreadBadge.stx'
|