@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.
@@ -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,210 @@
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 initialOpened = false;
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
+ initialOpened = false;
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
+ if (!initialOpened && options.initialRecipient) {
95
+ initialOpened = true;
96
+ const person = data.contacts.find((c) => c.id === options.initialRecipient());
97
+ if (person)
98
+ await open(person);
99
+ }
100
+ } catch (cause) {
101
+ if (token === version)
102
+ failure(cause);
103
+ } finally {
104
+ if (token === version)
105
+ loading.set(false);
106
+ }
107
+ }
108
+ async function open(contact) {
109
+ checkScope();
110
+ if (selected())
111
+ drafts.set(selected().id, draft());
112
+ const token = ++version;
113
+ sending.set(false);
114
+ selected.set(contact);
115
+ draft.set(drafts.get(contact.id) ?? "");
116
+ threadId.set("");
117
+ messages.set([]);
118
+ hasMore.set(false);
119
+ error.set("");
120
+ threadLoading.set(true);
121
+ try {
122
+ const data = await json("/conversations", { method: "POST", body: JSON.stringify({ recipient_id: contact.id }) });
123
+ if (token !== version || options.scopeKey() !== scope)
124
+ return;
125
+ threadId.set(data.id);
126
+ await refreshThread(token, data.id);
127
+ } catch (cause) {
128
+ if (token === version)
129
+ failure(cause);
130
+ } finally {
131
+ if (token === version)
132
+ threadLoading.set(false);
133
+ }
134
+ }
135
+ function back() {
136
+ if (selected())
137
+ drafts.set(selected().id, draft());
138
+ version++;
139
+ sending.set(false);
140
+ threadLoading.set(false);
141
+ selected.set(null);
142
+ threadId.set("");
143
+ messages.set([]);
144
+ error.set("");
145
+ }
146
+ async function send() {
147
+ checkScope();
148
+ if (!canSend())
149
+ return;
150
+ const id = threadId(), body = draft().trim(), token = version;
151
+ const key = retry?.body === body && retry.thread === id ? retry.key : crypto.randomUUID();
152
+ retry = { body, key, thread: id };
153
+ sending.set(true);
154
+ error.set("");
155
+ try {
156
+ await json(`/conversations/${id}/messages`, { method: "POST", body: JSON.stringify({ body, client_key: key }) });
157
+ if (token !== version || options.scopeKey() !== scope)
158
+ return;
159
+ if (draft().trim() === body)
160
+ draft.set("");
161
+ drafts.delete(selected().id);
162
+ retry = null;
163
+ await refreshThread(token, id);
164
+ await load();
165
+ } catch (cause) {
166
+ if (token === version)
167
+ failure(cause);
168
+ } finally {
169
+ if (token === version)
170
+ sending.set(false);
171
+ }
172
+ }
173
+ async function older() {
174
+ const id = threadId(), before = messages()[0]?.id, token = version;
175
+ if (!id || !before || threadLoading())
176
+ return;
177
+ threadLoading.set(true);
178
+ try {
179
+ const data = await json(`/conversations/${id}?before=${before}`);
180
+ if (token === version && id === threadId()) {
181
+ messages.set([...data.messages, ...messages()]);
182
+ hasMore.set(data.has_more);
183
+ }
184
+ } catch (cause) {
185
+ if (token === version)
186
+ failure(cause);
187
+ } finally {
188
+ if (token === version)
189
+ threadLoading.set(false);
190
+ }
191
+ }
192
+ async function refresh(markRead = false) {
193
+ if (refreshing || sending() || threadLoading())
194
+ return;
195
+ refreshing = true;
196
+ try {
197
+ await load();
198
+ if (markRead && threadId())
199
+ await refreshThread(version, threadId());
200
+ } catch (cause) {
201
+ failure(cause);
202
+ } finally {
203
+ refreshing = false;
204
+ }
205
+ }
206
+ 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 };
207
+ }
208
+ export {
209
+ createChat
210
+ };
package/dist/index.d.ts CHANGED
@@ -96,3 +96,4 @@ export * from './utils/keep-alive';
96
96
  export * from './utils/lazy-loading';
97
97
  export * from './utils/prop-validation';
98
98
  export * from './utils/theme';
99
+ export * from './ui/chat/index';