@stacksjs/components 0.2.428 → 0.2.430
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-wrcezr7k.stx +106 -0
- package/dist/ChatLauncher-39r68zj2.stx +45 -0
- package/dist/ChatMessage-rj37tdgn.stx +12 -0
- package/dist/ChatUnreadBadge-sp06phw6.stx +11 -0
- package/dist/chat/controller.js +214 -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 +8 -0
- package/package.json +8 -3
- package/src/index.ts +2 -0
- package/src/ui/chat/ChatInbox.stx +106 -0
- package/src/ui/chat/ChatLauncher.stx +45 -0
- package/src/ui/chat/ChatMessage.stx +12 -0
- package/src/ui/chat/ChatUnreadBadge.stx +11 -0
- package/src/ui/chat/README.md +54 -0
- package/src/ui/chat/controller.ts +188 -0
- package/src/ui/chat/index.ts +9 -0
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
<script server>
|
|
2
|
+
export const storeName = $props.store || 'chat'
|
|
3
|
+
export const className = $props.className || ''
|
|
4
|
+
export const active = $props.active == null || $props.active === true || $props.active === 'true'
|
|
5
|
+
export const compact = $props.compact === true || $props.compact === 'true'
|
|
6
|
+
export const sizeClasses = compact ? 'min-h-[340px] h-[min(560px,calc(100dvh-230px))]' : 'min-h-[540px] h-[calc(100dvh-180px)]'
|
|
7
|
+
export const selectedInboxClass = compact ? 'hidden' : 'hidden md:flex'
|
|
8
|
+
export const backButtonClass = compact ? '' : 'md:hidden'
|
|
9
|
+
export const inboxWidth = compact ? 'w-full' : 'w-full md:w-80'
|
|
10
|
+
</script>
|
|
11
|
+
<script client>
|
|
12
|
+
const active = useReactiveProp('active', {{ active }})
|
|
13
|
+
const compact = {{ compact }}
|
|
14
|
+
const selectedInboxClass = {{ selectedInboxClass }}
|
|
15
|
+
const chat = useStore({{ storeName }})
|
|
16
|
+
const rows = chat.rows
|
|
17
|
+
const selected = chat.selected
|
|
18
|
+
const messages = chat.messages
|
|
19
|
+
const draft = chat.draft
|
|
20
|
+
const search = chat.search
|
|
21
|
+
const unreadOnly = chat.unreadOnly
|
|
22
|
+
const unread = chat.unread
|
|
23
|
+
const error = chat.error
|
|
24
|
+
const loading = chat.loading
|
|
25
|
+
const threadLoading = chat.threadLoading
|
|
26
|
+
const hasMore = chat.hasMore
|
|
27
|
+
const canSend = chat.canSend
|
|
28
|
+
const sending = chat.sending
|
|
29
|
+
const maxLength = chat.maxLength
|
|
30
|
+
const selfId = chat.selfId
|
|
31
|
+
const history = useRef('chat-history')
|
|
32
|
+
const composer = useRef('chat-composer')
|
|
33
|
+
let lastThread = ''
|
|
34
|
+
let lastMessage = 0
|
|
35
|
+
effect(() => {
|
|
36
|
+
if (!active()) return
|
|
37
|
+
const id = chat.threadId()
|
|
38
|
+
const list = messages()
|
|
39
|
+
const last = list.at(-1)
|
|
40
|
+
const changedThread = id !== lastThread
|
|
41
|
+
const newMessage = last && last.id !== lastMessage
|
|
42
|
+
const element = history()
|
|
43
|
+
const nearBottom = element && element.scrollHeight - element.scrollTop - element.clientHeight < 120
|
|
44
|
+
if (element && (changedThread || newMessage && (nearBottom || last.sender_id === selfId()))) {
|
|
45
|
+
nextTick(() => { element.scrollTop = element.scrollHeight })
|
|
46
|
+
}
|
|
47
|
+
if (changedThread && id) nextTick(() => composer()?.focus())
|
|
48
|
+
lastThread = id
|
|
49
|
+
lastMessage = last?.id || 0
|
|
50
|
+
})
|
|
51
|
+
const hasSelection = derived(() => !!selected())
|
|
52
|
+
const noSelection = derived(() => !selected() && !compact)
|
|
53
|
+
const emptyRows = derived(() => !loading() && rows().length === 0)
|
|
54
|
+
const emptyThread = derived(() => hasSelection() && !threadLoading() && messages().length === 0)
|
|
55
|
+
const selectedName = derived(() => selected()?.name || '')
|
|
56
|
+
const selectedRole = derived(() => selected()?.role || '')
|
|
57
|
+
const sendLabel = derived(() => sending() ? 'Sending...' : 'Send message')
|
|
58
|
+
function initials(name) { return String(name || '').split(' ').map(p => p[0]).slice(0, 2).join('').toUpperCase() }
|
|
59
|
+
function timestamp(value) { return new Date(value).toLocaleString([], { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) }
|
|
60
|
+
function submit() { return chat.send() }
|
|
61
|
+
function keyboard(event) { if ((event.ctrlKey || event.metaKey) && event.key === 'Enter' && !event.isComposing) { event.preventDefault(); chat.send() } }
|
|
62
|
+
onMount(() => chat.load())
|
|
63
|
+
effect(() => { if (active()) chat.refresh(true) })
|
|
64
|
+
useInterval(() => chat.refresh(active()), 10000, { whileVisible: true })
|
|
65
|
+
</script>
|
|
66
|
+
<section aria-label="Messages" class="flex flex-col {{ sizeClasses }} max-h-[900px] overflow-hidden bg-white dark:bg-slate-950 border border-slate-200 dark:border-slate-800 rounded-2xl {{ className }}">
|
|
67
|
+
<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">
|
|
68
|
+
<span :text="error"></span><button type="button" @click="chat.refresh(true)" class="font-semibold underline">Try again</button>
|
|
69
|
+
</div>
|
|
70
|
+
<div class="flex flex-1 min-h-0">
|
|
71
|
+
<aside aria-label="Conversations" :class="hasSelection ? selectedInboxClass : 'flex'" class="flex-col {{ inboxWidth }} shrink-0 border-r border-slate-200 dark:border-slate-800">
|
|
72
|
+
<div class="px-5 pt-5 pb-4 space-y-4">
|
|
73
|
+
<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>
|
|
74
|
+
<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>
|
|
75
|
+
<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>
|
|
76
|
+
</div>
|
|
77
|
+
<p :if="loading" role="status" class="px-5 pb-2 text-xs text-slate-500 dark:text-slate-400">Updating messages...</p>
|
|
78
|
+
<div class="flex-1 overflow-y-auto px-2 pb-2">
|
|
79
|
+
<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">
|
|
80
|
+
<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>
|
|
81
|
+
<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>
|
|
82
|
+
</button>
|
|
83
|
+
<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>
|
|
84
|
+
</div>
|
|
85
|
+
</aside>
|
|
86
|
+
<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">
|
|
87
|
+
<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>
|
|
88
|
+
</div>
|
|
89
|
+
<div :if="hasSelection" class="flex flex-1 flex-col min-w-0">
|
|
90
|
+
<header class="flex items-center gap-3 px-4 md:px-6 py-4 border-b border-slate-200 dark:border-slate-800">
|
|
91
|
+
<button type="button" @click="chat.back()" aria-label="Back to inbox" class="{{ backButtonClass }} 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>
|
|
92
|
+
</header>
|
|
93
|
+
<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">
|
|
94
|
+
<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>
|
|
95
|
+
<p :if="threadLoading" role="status" class="text-center text-sm text-slate-500 dark:text-slate-400">Loading conversation...</p>
|
|
96
|
+
<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>
|
|
97
|
+
<article :for="message in messages" :class="message.sender_id === selfId ? 'items-end' : 'items-start'" class="flex flex-col gap-1.5">
|
|
98
|
+
<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>
|
|
99
|
+
</article>
|
|
100
|
+
</div>
|
|
101
|
+
<form @submit.prevent="submit()" class="px-4 md:px-6 pt-3 pb-4 border-t border-slate-200 dark:border-slate-800">
|
|
102
|
+
<label class="block"><span class="sr-only">Write a message</span><textarea ref="chat-composer" 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></label><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>
|
|
103
|
+
</form>
|
|
104
|
+
</div>
|
|
105
|
+
</div>
|
|
106
|
+
</section>
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
<script server>
|
|
2
|
+
export const storeName = $props.store || 'chat'
|
|
3
|
+
export const href = $props.href || '/messages'
|
|
4
|
+
export const inline = $props.placement === 'inline'
|
|
5
|
+
export const className = $props.className || ''
|
|
6
|
+
</script>
|
|
7
|
+
<script client>
|
|
8
|
+
const chat = useStore({{ storeName }})
|
|
9
|
+
const unread = chat.unread
|
|
10
|
+
const open = state(false)
|
|
11
|
+
const toggle = useRef('chat-toggle')
|
|
12
|
+
const closeButton = useRef('chat-close')
|
|
13
|
+
const launcherLabel = derived(() => unread() ? `Messages, ${unread()} unread` : 'Messages')
|
|
14
|
+
function show() {
|
|
15
|
+
open.set(!open())
|
|
16
|
+
if (open()) nextTick(() => closeButton()?.focus())
|
|
17
|
+
}
|
|
18
|
+
function close() {
|
|
19
|
+
open.set(false)
|
|
20
|
+
nextTick(() => toggle()?.focus())
|
|
21
|
+
}
|
|
22
|
+
function keyboard(event) { if (event.key === 'Escape') close() }
|
|
23
|
+
onMount(() => chat.load())
|
|
24
|
+
useInterval(() => chat.refresh(false), 15000, { whileVisible: true })
|
|
25
|
+
</script>
|
|
26
|
+
<div class="{{ className }}">
|
|
27
|
+
@if(inline)
|
|
28
|
+
<StxLink to="{{ href }}" :aria-label="launcherLabel" class="relative inline-flex items-center justify-center w-11 h-11 rounded-full text-blue-700 dark:text-blue-300 bg-blue-50 dark:bg-blue-950 hover:bg-blue-100 dark:hover:bg-blue-900 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500">
|
|
29
|
+
<span class="i-lucide-message-circle text-xl" aria-hidden="true"></span>
|
|
30
|
+
<span :if="unread" class="absolute -top-1 -right-1 min-w-5 h-5 px-1 flex items-center justify-center text-[10px] font-semibold text-white bg-blue-600 border-2 border-white dark:border-slate-950 rounded-full" :text="unread"></span>
|
|
31
|
+
</StxLink>
|
|
32
|
+
@else
|
|
33
|
+
<section :if="open" role="dialog" aria-label="Messages" @keydown="keyboard($event)" class="fixed right-6 bottom-24 z-40 w-[420px] max-w-[calc(100vw-48px)] rounded-2xl border border-slate-200 dark:border-slate-800 bg-white dark:bg-slate-950 shadow-xl overflow-hidden">
|
|
34
|
+
<header class="flex items-center justify-between px-4 py-3 border-b border-slate-200 dark:border-slate-800">
|
|
35
|
+
<StxLink to="{{ href }}" class="font-semibold text-sm text-slate-900 dark:text-white hover:text-blue-600">Messages <span aria-hidden="true" class="i-lucide-arrow-up-right inline-block"></span></StxLink>
|
|
36
|
+
<button ref="chat-close" type="button" @click="close()" aria-label="Close chat" class="inline-flex items-center justify-center w-9 h-9 text-slate-500 dark:text-slate-400 rounded-full hover:bg-slate-100 dark:hover:bg-slate-800 focus-visible:ring-2 focus-visible:ring-blue-500"><span aria-hidden="true" class="i-lucide-x text-lg"></span></button>
|
|
37
|
+
</header>
|
|
38
|
+
<ChatInbox :active="open" store="{{ storeName }}" compact="true" className="border-0 rounded-none" />
|
|
39
|
+
</section>
|
|
40
|
+
<button ref="chat-toggle" type="button" @click="show()" :aria-label="launcherLabel" :aria-expanded="open" aria-haspopup="dialog" class="fixed right-6 bottom-6 z-40 inline-flex items-center justify-center w-14 h-14 text-white bg-blue-600 hover:bg-blue-700 rounded-full shadow-lg transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500 focus-visible:ring-offset-2">
|
|
41
|
+
<span class="i-lucide-message-circle text-2xl" aria-hidden="true"></span>
|
|
42
|
+
<span :if="unread" class="absolute -top-1 -right-1 min-w-6 h-6 px-1 flex items-center justify-center text-xs font-semibold text-white bg-rose-600 border-2 border-white dark:border-slate-950 rounded-full" :text="unread"></span>
|
|
43
|
+
</button>
|
|
44
|
+
@endif
|
|
45
|
+
</div>
|
|
@@ -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,214 @@
|
|
|
1
|
+
// src/ui/chat/controller.ts
|
|
2
|
+
import { derived, state } from "@stacksjs/stx";
|
|
3
|
+
function createChat(options) {
|
|
4
|
+
const endpoint = options.endpoint ?? "/messages";
|
|
5
|
+
const contacts = state([]);
|
|
6
|
+
const conversations = state([]);
|
|
7
|
+
const selected = state(null);
|
|
8
|
+
const threadId = state("");
|
|
9
|
+
const messages = state([]);
|
|
10
|
+
const loading = state(false);
|
|
11
|
+
const threadLoading = state(false);
|
|
12
|
+
const sending = state(false);
|
|
13
|
+
const error = state("");
|
|
14
|
+
const draft = state("");
|
|
15
|
+
const search = state("");
|
|
16
|
+
const unreadOnly = state(false);
|
|
17
|
+
const hasMore = state(false);
|
|
18
|
+
const maxLength = state(4000);
|
|
19
|
+
let scope = "";
|
|
20
|
+
let version = 0;
|
|
21
|
+
let drafts = new Map;
|
|
22
|
+
let retry = null;
|
|
23
|
+
let refreshing = false;
|
|
24
|
+
let initialRecipient = 0;
|
|
25
|
+
function reset() {
|
|
26
|
+
version++;
|
|
27
|
+
contacts.set([]);
|
|
28
|
+
conversations.set([]);
|
|
29
|
+
selected.set(null);
|
|
30
|
+
threadId.set("");
|
|
31
|
+
messages.set([]);
|
|
32
|
+
draft.set("");
|
|
33
|
+
error.set("");
|
|
34
|
+
loading.set(false);
|
|
35
|
+
threadLoading.set(false);
|
|
36
|
+
sending.set(false);
|
|
37
|
+
drafts = new Map;
|
|
38
|
+
retry = null;
|
|
39
|
+
initialRecipient = 0;
|
|
40
|
+
hasMore.set(false);
|
|
41
|
+
}
|
|
42
|
+
function checkScope() {
|
|
43
|
+
const key = options.scopeKey();
|
|
44
|
+
if (key !== scope) {
|
|
45
|
+
reset();
|
|
46
|
+
scope = key;
|
|
47
|
+
}
|
|
48
|
+
return version;
|
|
49
|
+
}
|
|
50
|
+
async function json(path, init) {
|
|
51
|
+
const response = await options.request(`${endpoint}${path}`, init);
|
|
52
|
+
const body = await response.json().catch(() => ({}));
|
|
53
|
+
if (!response.ok)
|
|
54
|
+
throw new Error(body.error || "Could not load messages. Try again.");
|
|
55
|
+
return body;
|
|
56
|
+
}
|
|
57
|
+
const rows = derived(() => {
|
|
58
|
+
const q = search().toLowerCase().trim();
|
|
59
|
+
return contacts().map((contact) => ({ ...contact, conversation: conversations().find((c) => c.recipient_id === contact.id) })).filter((row) => (!q || `${row.name} ${row.role}`.toLowerCase().includes(q)) && (!unreadOnly() || (row.conversation?.unread ?? 0) > 0)).sort((a, b) => (b.conversation?.last_message?.id ?? 0) - (a.conversation?.last_message?.id ?? 0) || a.name.localeCompare(b.name));
|
|
60
|
+
});
|
|
61
|
+
const unread = derived(() => conversations().reduce((sum, c) => sum + c.unread, 0));
|
|
62
|
+
const canSend = derived(() => !!threadId() && !!draft().trim() && draft().trim().length <= maxLength() && !sending() && !threadLoading());
|
|
63
|
+
const selfId = derived(options.selfId);
|
|
64
|
+
function failure(cause) {
|
|
65
|
+
error.set(cause instanceof Error ? cause.message : "Could not load messages. Try again.");
|
|
66
|
+
}
|
|
67
|
+
async function refreshThread(token, id, mark = true) {
|
|
68
|
+
const data = await json(`/conversations/${id}`);
|
|
69
|
+
if (token !== version || id !== threadId() || options.scopeKey() !== scope)
|
|
70
|
+
return;
|
|
71
|
+
const first = data.messages[0]?.id;
|
|
72
|
+
messages.set([...messages().filter((m) => first && m.id < first), ...data.messages]);
|
|
73
|
+
if (messages().length === data.messages.length)
|
|
74
|
+
hasMore.set(data.has_more);
|
|
75
|
+
const last = data.messages.at(-1);
|
|
76
|
+
if (mark && last) {
|
|
77
|
+
await json(`/conversations/${id}/read`, { method: "POST", body: JSON.stringify({ through_id: last.id }) });
|
|
78
|
+
if (token === version && id === threadId())
|
|
79
|
+
conversations.update((list) => list.map((c) => c.id === id ? { ...c, unread: 0 } : c));
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
async function load() {
|
|
83
|
+
const token = checkScope();
|
|
84
|
+
loading.set(true);
|
|
85
|
+
error.set("");
|
|
86
|
+
try {
|
|
87
|
+
const data = await json("");
|
|
88
|
+
if (token !== version || options.scopeKey() !== scope)
|
|
89
|
+
return;
|
|
90
|
+
contacts.set(data.contacts);
|
|
91
|
+
conversations.set(data.conversations);
|
|
92
|
+
maxLength.set(data.max_length);
|
|
93
|
+
loading.set(false);
|
|
94
|
+
const recipientId = options.initialRecipient?.() ?? 0;
|
|
95
|
+
if (recipientId > 0 && recipientId !== initialRecipient) {
|
|
96
|
+
const person = data.contacts.find((c) => c.id === recipientId);
|
|
97
|
+
if (person) {
|
|
98
|
+
initialRecipient = recipientId;
|
|
99
|
+
await open(person);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
} catch (cause) {
|
|
103
|
+
if (token === version)
|
|
104
|
+
failure(cause);
|
|
105
|
+
} finally {
|
|
106
|
+
if (token === version)
|
|
107
|
+
loading.set(false);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
async function open(contact) {
|
|
111
|
+
checkScope();
|
|
112
|
+
if (selected())
|
|
113
|
+
drafts.set(selected().id, draft());
|
|
114
|
+
const token = ++version;
|
|
115
|
+
sending.set(false);
|
|
116
|
+
selected.set(contact);
|
|
117
|
+
draft.set(drafts.get(contact.id) ?? "");
|
|
118
|
+
threadId.set("");
|
|
119
|
+
messages.set([]);
|
|
120
|
+
hasMore.set(false);
|
|
121
|
+
error.set("");
|
|
122
|
+
threadLoading.set(true);
|
|
123
|
+
try {
|
|
124
|
+
const data = await json("/conversations", { method: "POST", body: JSON.stringify({ recipient_id: contact.id }) });
|
|
125
|
+
if (token !== version || options.scopeKey() !== scope)
|
|
126
|
+
return;
|
|
127
|
+
threadId.set(data.id);
|
|
128
|
+
await refreshThread(token, data.id);
|
|
129
|
+
} catch (cause) {
|
|
130
|
+
if (token === version)
|
|
131
|
+
failure(cause);
|
|
132
|
+
} finally {
|
|
133
|
+
if (token === version)
|
|
134
|
+
threadLoading.set(false);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
function back() {
|
|
138
|
+
if (selected())
|
|
139
|
+
drafts.set(selected().id, draft());
|
|
140
|
+
version++;
|
|
141
|
+
sending.set(false);
|
|
142
|
+
threadLoading.set(false);
|
|
143
|
+
selected.set(null);
|
|
144
|
+
threadId.set("");
|
|
145
|
+
messages.set([]);
|
|
146
|
+
error.set("");
|
|
147
|
+
}
|
|
148
|
+
async function send() {
|
|
149
|
+
checkScope();
|
|
150
|
+
if (!canSend())
|
|
151
|
+
return;
|
|
152
|
+
const id = threadId(), body = draft().trim(), token = version;
|
|
153
|
+
const key = retry?.body === body && retry.thread === id ? retry.key : crypto.randomUUID();
|
|
154
|
+
retry = { body, key, thread: id };
|
|
155
|
+
sending.set(true);
|
|
156
|
+
error.set("");
|
|
157
|
+
try {
|
|
158
|
+
await json(`/conversations/${id}/messages`, { method: "POST", body: JSON.stringify({ body, client_key: key }) });
|
|
159
|
+
if (token !== version || options.scopeKey() !== scope)
|
|
160
|
+
return;
|
|
161
|
+
if (draft().trim() === body)
|
|
162
|
+
draft.set("");
|
|
163
|
+
drafts.delete(selected().id);
|
|
164
|
+
retry = null;
|
|
165
|
+
await refreshThread(token, id);
|
|
166
|
+
await load();
|
|
167
|
+
} catch (cause) {
|
|
168
|
+
if (token === version)
|
|
169
|
+
failure(cause);
|
|
170
|
+
} finally {
|
|
171
|
+
if (token === version)
|
|
172
|
+
sending.set(false);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
async function older() {
|
|
176
|
+
const id = threadId(), before = messages()[0]?.id, token = version;
|
|
177
|
+
if (!id || !before || threadLoading())
|
|
178
|
+
return;
|
|
179
|
+
threadLoading.set(true);
|
|
180
|
+
try {
|
|
181
|
+
const data = await json(`/conversations/${id}?before=${before}`);
|
|
182
|
+
if (token === version && id === threadId()) {
|
|
183
|
+
messages.set([...data.messages, ...messages()]);
|
|
184
|
+
hasMore.set(data.has_more);
|
|
185
|
+
}
|
|
186
|
+
} catch (cause) {
|
|
187
|
+
if (token === version)
|
|
188
|
+
failure(cause);
|
|
189
|
+
} finally {
|
|
190
|
+
if (token === version)
|
|
191
|
+
threadLoading.set(false);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
async function refresh(markRead = false) {
|
|
195
|
+
if (refreshing || sending() || threadLoading())
|
|
196
|
+
return;
|
|
197
|
+
refreshing = true;
|
|
198
|
+
try {
|
|
199
|
+
await load();
|
|
200
|
+
if (markRead && selected() && !threadId())
|
|
201
|
+
await open(selected());
|
|
202
|
+
else if (markRead && threadId())
|
|
203
|
+
await refreshThread(version, threadId());
|
|
204
|
+
} catch (cause) {
|
|
205
|
+
failure(cause);
|
|
206
|
+
} finally {
|
|
207
|
+
refreshing = false;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
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 };
|
|
211
|
+
}
|
|
212
|
+
export {
|
|
213
|
+
createChat
|
|
214
|
+
};
|
package/dist/index.d.ts
CHANGED