@12-apps/chat 1.0.0 → 1.1.0
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/README.md +43 -2
- package/package.json +1 -1
- package/prisma/chat.prisma +2 -0
- package/prisma/migrations/20261003120000_add_chat_thread_activity_index/migration.sql +2 -0
- package/src/client/index.ts +1 -0
- package/src/client/use-chat-thread.ts +88 -18
- package/src/native/index.ts +7 -2
- package/src/native/layout.tsx +40 -4
- package/src/react/composer.tsx +14 -4
- package/src/react/index.ts +7 -2
- package/src/react/layout.tsx +73 -6
- package/src/ui/bubble-tint.ts +19 -0
- package/src/ui/surface.tsx +7 -3
- package/src/ui/thread-view.tsx +37 -10
package/README.md
CHANGED
|
@@ -14,7 +14,7 @@ same thread screen renders in a web SPA and in a React Native app.
|
|
|
14
14
|
| `./react` | `createWebChat(config) → { ChatThread }`: the web surface. |
|
|
15
15
|
| `./native` | `createNativeChat(config) → { ChatThread }`: the React Native surface. |
|
|
16
16
|
| `./manifest*` | wiring manifests for the server, web and native runtimes. |
|
|
17
|
-
| `prisma/` | `chat.prisma` (`ChatThread`, `ChatMessage`, `ChatReadMarker`) plus its
|
|
17
|
+
| `prisma/` | `chat.prisma` (`ChatThread`, `ChatMessage`, `ChatReadMarker`) plus its migrations. `pnpm --filter @12-apps/chat prisma:sync` copies the partial into a host schema folder. |
|
|
18
18
|
|
|
19
19
|
## The host decides who is in a thread
|
|
20
20
|
|
|
@@ -118,6 +118,14 @@ or anonymise API: retention (LGPD, GDPR) is the host's. The
|
|
|
118
118
|
`created_at` comes from the app process's clock, and messages in the same
|
|
119
119
|
millisecond are ordered by id.
|
|
120
120
|
|
|
121
|
+
### Indexes for the host's own queries
|
|
122
|
+
|
|
123
|
+
`chat_threads (tenant_id, last_message_at)` (1.1.0, migration
|
|
124
|
+
`20261003120000_add_chat_thread_activity_index`) serves a host badge that
|
|
125
|
+
counts the threads with activity since a moment (`tenant_id = ? AND
|
|
126
|
+
last_message_at >= ?`). A host that copies the package's migrations picks it
|
|
127
|
+
up with its next sync; it is additive, so it needs no release choreography.
|
|
128
|
+
|
|
121
129
|
## The screen
|
|
122
130
|
|
|
123
131
|
```tsx
|
|
@@ -129,6 +137,31 @@ The thread marks itself read up to the newest message it showed, and
|
|
|
129
137
|
`onUnreadChange` then gets the server's remaining count (normally 0). Pass
|
|
130
138
|
`autoMarkRead={false}` to mount it hidden only for its unread count.
|
|
131
139
|
|
|
140
|
+
`autoMarkRead="visible"` is for a thread that may be mounted out of sight (the
|
|
141
|
+
lower half of a drawer): a load's unread messages wait until the message list
|
|
142
|
+
is on screen, and are marked read then; a load that finds unread while the
|
|
143
|
+
list is already on screen marks at once. On the web the list is watched with
|
|
144
|
+
an `IntersectionObserver` (on screen from its first pixel); a browser without
|
|
145
|
+
one marks at once, as `true` does. On native a mounted list counts as on
|
|
146
|
+
screen. A host testing in jsdom stubs `IntersectionObserver` to drive it.
|
|
147
|
+
A host drawing its own list with `useChatThread({ autoMarkRead: "visible" })`
|
|
148
|
+
reports it through `controls.onVisibleChange(visible)`.
|
|
149
|
+
|
|
150
|
+
A read-only thread (`canWrite: false`) with no messages shows only the closed
|
|
151
|
+
notice: no empty-thread invitation to write the first message, and no list.
|
|
152
|
+
|
|
153
|
+
Own messages and the others' are told apart by their surface: the reader's
|
|
154
|
+
own bubbles are a tint of the theme's `palette.primary.main` (8% in light
|
|
155
|
+
mode, 16% in dark), the others' sit on the paper surface. The label is body
|
|
156
|
+
text on the own tint and secondary text on paper; the primary colour itself
|
|
157
|
+
reads under 4.5:1 on its own tint, so it is not used for text there. A bubble is at most 80% of the thread wide (and 60
|
|
158
|
+
characters, on the web).
|
|
159
|
+
|
|
160
|
+
Accessibility: the list is a polite live region (`aria-live` on the web,
|
|
161
|
+
`accessibilityLiveRegion` on native), so an arriving message is announced.
|
|
162
|
+
On the web a click on the send button hands focus back to the field, and the
|
|
163
|
+
role's `maxLength` sits on the `<input>` itself.
|
|
164
|
+
|
|
132
165
|
Layout:
|
|
133
166
|
- **Web:** the messages sit in ui's `ScrollArea` (up to 60% of the viewport
|
|
134
167
|
tall), which keeps the newest in view. `ScrollArea` needs `ResizeObserver`,
|
|
@@ -141,7 +174,15 @@ Layout:
|
|
|
141
174
|
`createNativeChat` takes the same config. Both surfaces draw the thread from
|
|
142
175
|
`@12-apps/ui` primitives using only their cross-platform props, so a React
|
|
143
176
|
Native bundle resolves each primitive to its native twin through ui's
|
|
144
|
-
`react-native` export condition.
|
|
177
|
+
`react-native` export condition. What differs per platform is a slot of the
|
|
178
|
+
internal `ChatPlatform`, the one place platform styling lives:
|
|
179
|
+
|
|
180
|
+
| slot | receives | web | native |
|
|
181
|
+
|---|---|---|---|
|
|
182
|
+
| `Frame` | the list and the writing area | a `Stack` | a keyboard-avoiding `Screen` |
|
|
183
|
+
| `MessageList` | the bubbles, `label`, `scrollKey`, `onVisibleChange?` | `ScrollArea` + `IntersectionObserver` | `ScrollView`, visible on mount |
|
|
184
|
+
| `Bubble` | `{ mine, children }` | ui `Box` with `sx` (tint, `min(80%, 60ch)`) | ui `Box` with `style` (tint, `80%`) |
|
|
185
|
+
| `Composer` | the controlled field and its send action | `Input` + Enter | `Input` + the keyboard's send key |
|
|
145
186
|
|
|
146
187
|
The package opens no socket. Bump `refreshSignal` when your live channel says
|
|
147
188
|
the thread moved.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@12-apps/chat",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"sideEffects": false,
|
|
6
6
|
"description": "Conversation threads between the parties to one piece of work, each shown only by a host-chosen role label: framework-neutral HTTP routes with per-role write windows, a contact-info filter and quick replies, plus one thread screen built from @12-apps/ui primitives for web hosts and React Native hosts alike.",
|
package/prisma/chat.prisma
CHANGED
package/src/client/index.ts
CHANGED
|
@@ -5,7 +5,10 @@
|
|
|
5
5
|
* when its live channel says the thread moved, so the package needs no socket
|
|
6
6
|
* of its own. A reload keeps the messages on screen (no spinner after the
|
|
7
7
|
* first). Unless `autoMarkRead` is off, the thread is marked read up to the
|
|
8
|
-
* newest message a load SHOWED whenever that load found unread messages.
|
|
8
|
+
* newest message a load SHOWED whenever that load found unread messages. With
|
|
9
|
+
* `autoMarkRead: "visible"` a load's unread wait until the list reports itself
|
|
10
|
+
* on screen (`controls.onVisibleChange(true)`): a thread mounted below the fold
|
|
11
|
+
* is marked read when it is scrolled to, not when it is mounted.
|
|
9
12
|
*
|
|
10
13
|
* Three races are closed here rather than left to the host:
|
|
11
14
|
* - a load that resolves after a send never drops the sent message: what is
|
|
@@ -41,8 +44,21 @@ export interface ChatThreadControls extends ChatThreadState {
|
|
|
41
44
|
send(text: string): Promise<boolean>;
|
|
42
45
|
sendQuickReply(key: string): Promise<boolean>;
|
|
43
46
|
reload(): void;
|
|
47
|
+
/**
|
|
48
|
+
* Set only with `autoMarkRead: "visible"`. The message list calls it with
|
|
49
|
+
* whether it is on screen now, and with `false` when it unmounts; nothing is
|
|
50
|
+
* marked read until it has said `true`.
|
|
51
|
+
*/
|
|
52
|
+
readonly onVisibleChange?: (visible: boolean) => void;
|
|
44
53
|
}
|
|
45
54
|
|
|
55
|
+
/**
|
|
56
|
+
* When the thread marks itself read: after each load that found unread
|
|
57
|
+
* (`true`, the default), never (`false`, a hidden badge-only mount), or once
|
|
58
|
+
* the message list is on screen (`"visible"`).
|
|
59
|
+
*/
|
|
60
|
+
export type ChatAutoMarkRead = boolean | "visible";
|
|
61
|
+
|
|
46
62
|
/** The state, tagged with the client (thread) it belongs to. */
|
|
47
63
|
interface OwnedState extends ChatThreadState {
|
|
48
64
|
readonly owner: ChatClient;
|
|
@@ -113,8 +129,21 @@ interface UseChatThreadOptions {
|
|
|
113
129
|
refreshSignal?: unknown;
|
|
114
130
|
/** Told the unread count each load found (before marking read), then what is left once marked read. */
|
|
115
131
|
onUnreadChange?: (unread: number) => void;
|
|
116
|
-
/** Mark the thread read after a load shows unread messages. Default true;
|
|
117
|
-
autoMarkRead?:
|
|
132
|
+
/** Mark the thread read after a load shows unread messages. Default true; see {@link ChatAutoMarkRead}. */
|
|
133
|
+
autoMarkRead?: ChatAutoMarkRead;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** What a load showed, and whether that load is still the latest. */
|
|
137
|
+
interface Shown {
|
|
138
|
+
readonly payload: ChatThreadPayload;
|
|
139
|
+
readonly isCurrent: () => boolean;
|
|
140
|
+
/** The thread the payload came from: a mark goes to it, never to whichever thread is open now. */
|
|
141
|
+
readonly client: ChatClient;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
interface Loader {
|
|
145
|
+
readonly load: () => Promise<void>;
|
|
146
|
+
readonly onVisibleChange: (visible: boolean) => void;
|
|
118
147
|
}
|
|
119
148
|
|
|
120
149
|
/** The latest value, readable from callbacks without re-creating them. */
|
|
@@ -151,23 +180,63 @@ function useOwnedState(client: ChatClient): { state: OwnedState; update: Update;
|
|
|
151
180
|
return { state, update, latest };
|
|
152
181
|
}
|
|
153
182
|
|
|
154
|
-
/**
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
const
|
|
183
|
+
/**
|
|
184
|
+
* Mark read what a load showed — at once, or (`"visible"`) once the list is on
|
|
185
|
+
* screen. Only the latest load's unread wait; a newer load replaces them.
|
|
186
|
+
*/
|
|
187
|
+
function useMarkRead(options: UseChatThreadOptions, onUnread: { readonly current?: (unread: number) => void }) {
|
|
188
|
+
const client = useLatest(options.client);
|
|
189
|
+
const mode = useLatest(options.autoMarkRead ?? true);
|
|
190
|
+
const visible = useRef(false);
|
|
191
|
+
const pending = useRef<Shown | null>(null);
|
|
160
192
|
|
|
161
|
-
const
|
|
162
|
-
async (payload
|
|
193
|
+
const markRead = useCallback(
|
|
194
|
+
async ({ payload, isCurrent, client: from }: Shown) => {
|
|
163
195
|
const upTo = payload.messages.at(-1)?.createdAt;
|
|
164
|
-
if (
|
|
165
|
-
const left = await
|
|
196
|
+
if (payload.unread === 0 || upTo === undefined) return;
|
|
197
|
+
const left = await from.markRead(upTo).catch(() => null);
|
|
166
198
|
if (left !== null && isCurrent()) report(onUnread, left);
|
|
167
199
|
},
|
|
168
|
-
[
|
|
200
|
+
[onUnread],
|
|
169
201
|
);
|
|
170
202
|
|
|
203
|
+
const markShown = useCallback(
|
|
204
|
+
async (shown: Shown) => {
|
|
205
|
+
pending.current = null;
|
|
206
|
+
if (mode.current === false || shown.payload.unread === 0) return;
|
|
207
|
+
if (mode.current === "visible" && !visible.current) {
|
|
208
|
+
pending.current = shown;
|
|
209
|
+
return;
|
|
210
|
+
}
|
|
211
|
+
await markRead(shown);
|
|
212
|
+
},
|
|
213
|
+
[mode, markRead],
|
|
214
|
+
);
|
|
215
|
+
|
|
216
|
+
const onVisibleChange = useCallback(
|
|
217
|
+
(now: boolean) => {
|
|
218
|
+
visible.current = now;
|
|
219
|
+
const waiting = pending.current;
|
|
220
|
+
if (!now || waiting === null || mode.current !== "visible") return;
|
|
221
|
+
pending.current = null;
|
|
222
|
+
// A load overtaken by a refresh of the SAME thread still showed these
|
|
223
|
+
// messages (they stay on screen until the newer load lands, and after it
|
|
224
|
+
// fails), so they are marked; a load from another thread is not.
|
|
225
|
+
if (waiting.client === client.current) void markRead(waiting);
|
|
226
|
+
},
|
|
227
|
+
[mode, markRead, client],
|
|
228
|
+
);
|
|
229
|
+
|
|
230
|
+
return { markShown, onVisibleChange };
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** Load on mount and on every signal; ignore a load something newer overtook; mark read what a load showed. */
|
|
234
|
+
function useLoader(options: UseChatThreadOptions, update: Update): Loader {
|
|
235
|
+
const { client, refreshSignal } = options;
|
|
236
|
+
const generation = useRef(0);
|
|
237
|
+
const onUnread = useLatest(options.onUnreadChange);
|
|
238
|
+
const { markShown, onVisibleChange } = useMarkRead(options, onUnread);
|
|
239
|
+
|
|
171
240
|
const load = useCallback(async () => {
|
|
172
241
|
const mine = ++generation.current;
|
|
173
242
|
const isCurrent = () => mine === generation.current;
|
|
@@ -181,7 +250,7 @@ function useLoader(options: UseChatThreadOptions, update: Update): () => Promise
|
|
|
181
250
|
if (!isCurrent()) return;
|
|
182
251
|
update(client, (previous) => afterLoad(previous, payload));
|
|
183
252
|
report(onUnread, payload.unread);
|
|
184
|
-
await markShown(payload, isCurrent);
|
|
253
|
+
await markShown({ payload, isCurrent, client });
|
|
185
254
|
}, [client, update, markShown, onUnread]);
|
|
186
255
|
|
|
187
256
|
useEffect(() => {
|
|
@@ -192,13 +261,13 @@ function useLoader(options: UseChatThreadOptions, update: Update): () => Promise
|
|
|
192
261
|
};
|
|
193
262
|
}, [load, refreshSignal]);
|
|
194
263
|
|
|
195
|
-
return load;
|
|
264
|
+
return { load, onVisibleChange };
|
|
196
265
|
}
|
|
197
266
|
|
|
198
267
|
export function useChatThread(options: UseChatThreadOptions): ChatThreadControls {
|
|
199
268
|
const { client } = options;
|
|
200
269
|
const { state, update, latest } = useOwnedState(client);
|
|
201
|
-
const load = useLoader(options, update);
|
|
270
|
+
const { load, onVisibleChange } = useLoader(options, update);
|
|
202
271
|
|
|
203
272
|
const deliver = useCallback(
|
|
204
273
|
async (input: ChatSendInput): Promise<boolean> => {
|
|
@@ -228,5 +297,6 @@ export function useChatThread(options: UseChatThreadOptions): ChatThreadControls
|
|
|
228
297
|
}, [client, update, load]);
|
|
229
298
|
|
|
230
299
|
const visible = state.owner === client ? state : fresh(client);
|
|
231
|
-
|
|
300
|
+
const seen = options.autoMarkRead === "visible" ? { onVisibleChange } : {};
|
|
301
|
+
return { ...visibleOf(visible), send, sendQuickReply, reload, ...seen };
|
|
232
302
|
}
|
package/src/native/index.ts
CHANGED
|
@@ -7,10 +7,15 @@
|
|
|
7
7
|
|
|
8
8
|
import { buildChatSurface, type ChatSurface, type ChatSurfaceConfig } from "../ui/surface";
|
|
9
9
|
import { NativeComposer } from "./composer";
|
|
10
|
-
import { NativeFrame, NativeMessageList } from "./layout";
|
|
10
|
+
import { NativeBubble, NativeFrame, NativeMessageList } from "./layout";
|
|
11
11
|
|
|
12
12
|
export function createNativeChat(config: ChatSurfaceConfig): ChatSurface {
|
|
13
|
-
return buildChatSurface(config, {
|
|
13
|
+
return buildChatSurface(config, {
|
|
14
|
+
Frame: NativeFrame,
|
|
15
|
+
MessageList: NativeMessageList,
|
|
16
|
+
Bubble: NativeBubble,
|
|
17
|
+
Composer: NativeComposer,
|
|
18
|
+
});
|
|
14
19
|
}
|
|
15
20
|
|
|
16
21
|
export type { ChatSurface, ChatSurfaceConfig, ChatThreadProps } from "../ui/surface";
|
package/src/native/layout.tsx
CHANGED
|
@@ -1,27 +1,35 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The React Native thread's frame
|
|
2
|
+
* The React Native thread's frame, message list and bubble.
|
|
3
3
|
*
|
|
4
4
|
* The frame is the design system's `Screen` with its own scrolling off and no
|
|
5
5
|
* safe-area edges (the host's screen owns those): it fills its parent and
|
|
6
6
|
* lifts above the soft keyboard, so the composer pinned under the list is
|
|
7
7
|
* never covered. The list is a `ScrollView` that follows the newest message
|
|
8
8
|
* whenever its content grows or its viewport shrinks (the keyboard opening),
|
|
9
|
-
* and lets a tap on the send button land while the keyboard is up.
|
|
9
|
+
* and lets a tap on the send button land while the keyboard is up. It is a
|
|
10
|
+
* polite live region, so TalkBack reads a message as it arrives; and it is on
|
|
11
|
+
* screen whenever it is mounted, so it reports itself visible on mount for a
|
|
12
|
+
* thread that marks read only once seen.
|
|
10
13
|
*
|
|
11
14
|
* Mount the thread in a bounded parent (a `Screen` with `scroll={false}`, a
|
|
12
15
|
* flex-1 view) — inside another ScrollView it has no height to fill. Pass
|
|
13
16
|
* `keyboardOffset` when a navigator header sits above it.
|
|
14
17
|
*/
|
|
15
18
|
|
|
19
|
+
import { Box } from "@12-apps/ui/layout/Box";
|
|
16
20
|
import { Screen } from "@12-apps/ui/layout/Screen";
|
|
17
21
|
import { Stack } from "@12-apps/ui/layout/Stack";
|
|
18
|
-
import {
|
|
22
|
+
import { useUiTheme } from "@12-apps/ui/provider";
|
|
23
|
+
import { useEffect, useRef, type JSX } from "react";
|
|
19
24
|
import { ScrollView, StyleSheet } from "react-native";
|
|
20
25
|
|
|
21
|
-
import
|
|
26
|
+
import { ownBubbleTint } from "../ui/bubble-tint";
|
|
27
|
+
import type { ChatBubbleProps, ChatFrameProps, ChatMessageListProps } from "../ui/thread-view";
|
|
22
28
|
|
|
23
29
|
const NO_EDGES = [] as const;
|
|
24
30
|
const styles = StyleSheet.create({ fill: { flex: 1 } });
|
|
31
|
+
/** A bubble's widest, as a share of the thread. */
|
|
32
|
+
const BUBBLE_MAX_WIDTH = "80%" as const;
|
|
25
33
|
|
|
26
34
|
export function NativeFrame(props: ChatFrameProps): JSX.Element {
|
|
27
35
|
return (
|
|
@@ -39,9 +47,24 @@ export function NativeFrame(props: ChatFrameProps): JSX.Element {
|
|
|
39
47
|
);
|
|
40
48
|
}
|
|
41
49
|
|
|
50
|
+
/** On screen while mounted: report it once, and `false` when the list goes away. */
|
|
51
|
+
function useMountedVisibility(onVisibleChange?: (visible: boolean) => void): void {
|
|
52
|
+
const latest = useRef(onVisibleChange);
|
|
53
|
+
useEffect(() => {
|
|
54
|
+
latest.current = onVisibleChange;
|
|
55
|
+
}, [onVisibleChange]);
|
|
56
|
+
const wanted = onVisibleChange !== undefined;
|
|
57
|
+
useEffect(() => {
|
|
58
|
+
if (!wanted) return undefined;
|
|
59
|
+
latest.current?.(true);
|
|
60
|
+
return () => latest.current?.(false);
|
|
61
|
+
}, [wanted]);
|
|
62
|
+
}
|
|
63
|
+
|
|
42
64
|
export function NativeMessageList(props: ChatMessageListProps): JSX.Element {
|
|
43
65
|
const list = useRef<ScrollView>(null);
|
|
44
66
|
const toEnd = (): void => list.current?.scrollToEnd({ animated: true });
|
|
67
|
+
useMountedVisibility(props.onVisibleChange);
|
|
45
68
|
return (
|
|
46
69
|
<ScrollView
|
|
47
70
|
ref={list}
|
|
@@ -52,9 +75,22 @@ export function NativeMessageList(props: ChatMessageListProps): JSX.Element {
|
|
|
52
75
|
onContentSizeChange={toEnd}
|
|
53
76
|
onLayout={toEnd}
|
|
54
77
|
accessibilityLabel={props.label}
|
|
78
|
+
accessibilityLiveRegion="polite"
|
|
55
79
|
testID={props.testID}
|
|
56
80
|
>
|
|
57
81
|
<Stack gap={1}>{props.children}</Stack>
|
|
58
82
|
</ScrollView>
|
|
59
83
|
);
|
|
60
84
|
}
|
|
85
|
+
|
|
86
|
+
export function NativeBubble(props: ChatBubbleProps): JSX.Element {
|
|
87
|
+
const theme = useUiTheme();
|
|
88
|
+
// One plain object, not a style array: the web type-check (`tsc -p tsconfig.json`) reads this
|
|
89
|
+
// file against the web `Box`, whose `style` is CSS. An own bubble's tint replaces the paper surface.
|
|
90
|
+
const style = props.mine ? { maxWidth: BUBBLE_MAX_WIDTH, backgroundColor: ownBubbleTint(theme) } : { maxWidth: BUBBLE_MAX_WIDTH };
|
|
91
|
+
return (
|
|
92
|
+
<Box bg={props.mine ? undefined : "paper"} bordered radius="md" px={2} py={1} gap={0.5} style={style}>
|
|
93
|
+
{props.children}
|
|
94
|
+
</Box>
|
|
95
|
+
);
|
|
96
|
+
}
|
package/src/react/composer.tsx
CHANGED
|
@@ -5,22 +5,32 @@
|
|
|
5
5
|
*
|
|
6
6
|
* The field stays enabled while a message is in flight: disabling it would
|
|
7
7
|
* drop focus after every Enter. Only the send action is gated (here, and again
|
|
8
|
-
* in the thread's submit).
|
|
8
|
+
* in the thread's submit). A click on the send button hands focus back to the
|
|
9
|
+
* field: the button disables itself while the message is in flight, and a
|
|
10
|
+
* focused control that turns disabled drops focus to the page.
|
|
11
|
+
*
|
|
12
|
+
* `maxLength` and the field's ref ride `inputProps`: given to `Input` itself
|
|
13
|
+
* they land on the text field's root `<div>`, where neither means anything.
|
|
9
14
|
*/
|
|
10
15
|
|
|
11
16
|
import { Button } from "@12-apps/ui/form/Button";
|
|
12
17
|
import { Input } from "@12-apps/ui/form/Input";
|
|
13
18
|
import { Box } from "@12-apps/ui/layout/Box";
|
|
14
|
-
import type
|
|
19
|
+
import { useRef, type JSX, type KeyboardEvent } from "react";
|
|
15
20
|
|
|
16
21
|
import type { ChatComposerProps } from "../ui/thread-view";
|
|
17
22
|
|
|
18
23
|
export function WebComposer(props: ChatComposerProps): JSX.Element {
|
|
24
|
+
const field = useRef<HTMLInputElement | null>(null);
|
|
19
25
|
const onKeyDown = (event: KeyboardEvent<HTMLInputElement>): void => {
|
|
20
26
|
if (event.key !== "Enter" || event.shiftKey || event.nativeEvent.isComposing) return;
|
|
21
27
|
event.preventDefault();
|
|
22
28
|
props.onSubmit();
|
|
23
29
|
};
|
|
30
|
+
const onSend = (): void => {
|
|
31
|
+
props.onSubmit();
|
|
32
|
+
field.current?.focus();
|
|
33
|
+
};
|
|
24
34
|
return (
|
|
25
35
|
<Box direction="row" gap={1} align="center">
|
|
26
36
|
<Box flex={1}>
|
|
@@ -29,7 +39,7 @@ export function WebComposer(props: ChatComposerProps): JSX.Element {
|
|
|
29
39
|
value={props.value}
|
|
30
40
|
placeholder={props.copy.placeholder}
|
|
31
41
|
aria-label={props.copy.placeholder}
|
|
32
|
-
|
|
42
|
+
inputProps={{ maxLength: props.maxLength, ref: field }}
|
|
33
43
|
onChange={(event) => props.onChange(event.target.value)}
|
|
34
44
|
onKeyDown={onKeyDown}
|
|
35
45
|
testID="chat-input"
|
|
@@ -37,7 +47,7 @@ export function WebComposer(props: ChatComposerProps): JSX.Element {
|
|
|
37
47
|
</Box>
|
|
38
48
|
<Button
|
|
39
49
|
variant="solid"
|
|
40
|
-
onClick={
|
|
50
|
+
onClick={onSend}
|
|
41
51
|
disabled={props.sending || props.value.trim() === ""}
|
|
42
52
|
testID="chat-send"
|
|
43
53
|
>
|
package/src/react/index.ts
CHANGED
|
@@ -6,10 +6,15 @@
|
|
|
6
6
|
|
|
7
7
|
import { buildChatSurface, type ChatSurface, type ChatSurfaceConfig } from "../ui/surface";
|
|
8
8
|
import { WebComposer } from "./composer";
|
|
9
|
-
import { WebFrame, WebMessageList } from "./layout";
|
|
9
|
+
import { WebBubble, WebFrame, WebMessageList } from "./layout";
|
|
10
10
|
|
|
11
11
|
export function createWebChat(config: ChatSurfaceConfig): ChatSurface {
|
|
12
|
-
return buildChatSurface(config, {
|
|
12
|
+
return buildChatSurface(config, {
|
|
13
|
+
Frame: WebFrame,
|
|
14
|
+
MessageList: WebMessageList,
|
|
15
|
+
Bubble: WebBubble,
|
|
16
|
+
Composer: WebComposer,
|
|
17
|
+
});
|
|
13
18
|
}
|
|
14
19
|
|
|
15
20
|
export type { ChatSurface, ChatSurfaceConfig, ChatThreadProps } from "../ui/surface";
|
package/src/react/layout.tsx
CHANGED
|
@@ -1,18 +1,27 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The web thread's frame
|
|
3
|
-
* scroll region, bounded to a share of the viewport so a long thread
|
|
4
|
-
* inside it while the composer stays in view, and it follows the
|
|
5
|
-
* message whenever one is added (a send, a reload that brought one in).
|
|
2
|
+
* The web thread's frame, message list and bubble. The list is the design
|
|
3
|
+
* system's scroll region, bounded to a share of the viewport so a long thread
|
|
4
|
+
* scrolls inside it while the composer stays in view, and it follows the
|
|
5
|
+
* newest message whenever one is added (a send, a reload that brought one in).
|
|
6
|
+
* It is a polite live region, so a screen reader hears a message arrive
|
|
7
|
+
* without the reader's place being taken from them.
|
|
6
8
|
*/
|
|
7
9
|
|
|
10
|
+
import { Box } from "@12-apps/ui/layout/Box";
|
|
8
11
|
import { ScrollArea } from "@12-apps/ui/layout/ScrollArea";
|
|
9
12
|
import { Stack } from "@12-apps/ui/layout/Stack";
|
|
13
|
+
import { useUiTheme } from "@12-apps/ui/provider";
|
|
10
14
|
import { useEffect, useRef, type JSX } from "react";
|
|
11
15
|
|
|
12
|
-
import
|
|
16
|
+
import { ownBubbleTint } from "../ui/bubble-tint";
|
|
17
|
+
import type { ChatBubbleProps, ChatFrameProps, ChatMessageListProps } from "../ui/thread-view";
|
|
13
18
|
|
|
14
19
|
/** The list's ceiling: relative to the viewport, so it holds at every width and zoom. */
|
|
15
20
|
const LIST_MAX_HEIGHT = "60vh";
|
|
21
|
+
/** A bubble's widest: a share of the thread, and never a line too long to read. */
|
|
22
|
+
const BUBBLE_MAX_WIDTH = "min(80%, 60ch)";
|
|
23
|
+
/** On screen from the first sliver: 0 catches entering, the next step a pixel or so in. */
|
|
24
|
+
const VISIBLE_THRESHOLDS = [0, 0.01];
|
|
16
25
|
|
|
17
26
|
export function WebFrame(props: ChatFrameProps): JSX.Element {
|
|
18
27
|
return (
|
|
@@ -22,15 +31,73 @@ export function WebFrame(props: ChatFrameProps): JSX.Element {
|
|
|
22
31
|
);
|
|
23
32
|
}
|
|
24
33
|
|
|
34
|
+
/**
|
|
35
|
+
* Tell `report` whether `element` is on screen, and `false` once it is gone.
|
|
36
|
+
* A browser without IntersectionObserver reports it on screen at once: the
|
|
37
|
+
* thread then marks read as it always did, rather than never.
|
|
38
|
+
*/
|
|
39
|
+
function observeVisibility(element: HTMLElement, report: (visible: boolean) => void): () => void {
|
|
40
|
+
if (typeof IntersectionObserver === "undefined") {
|
|
41
|
+
report(true);
|
|
42
|
+
return () => report(false);
|
|
43
|
+
}
|
|
44
|
+
const observer = new IntersectionObserver(
|
|
45
|
+
(entries) => {
|
|
46
|
+
const entry = entries.at(-1);
|
|
47
|
+
if (entry) report(entry.isIntersecting && entry.intersectionRatio > 0);
|
|
48
|
+
},
|
|
49
|
+
{ threshold: VISIBLE_THRESHOLDS },
|
|
50
|
+
);
|
|
51
|
+
observer.observe(element);
|
|
52
|
+
return () => {
|
|
53
|
+
observer.disconnect();
|
|
54
|
+
report(false);
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Report the viewport's visibility while the host asked for it; the latest callback, never a re-subscription. */
|
|
59
|
+
function useVisibility(viewport: { readonly current: HTMLDivElement | null }, onVisibleChange?: (visible: boolean) => void): void {
|
|
60
|
+
const latest = useRef(onVisibleChange);
|
|
61
|
+
useEffect(() => {
|
|
62
|
+
latest.current = onVisibleChange;
|
|
63
|
+
}, [onVisibleChange]);
|
|
64
|
+
const wanted = onVisibleChange !== undefined;
|
|
65
|
+
useEffect(() => {
|
|
66
|
+
const element = viewport.current;
|
|
67
|
+
if (!wanted || !element) return undefined;
|
|
68
|
+
return observeVisibility(element, (visible) => latest.current?.(visible));
|
|
69
|
+
}, [viewport, wanted]);
|
|
70
|
+
}
|
|
71
|
+
|
|
25
72
|
export function WebMessageList(props: ChatMessageListProps): JSX.Element {
|
|
26
73
|
const viewport = useRef<HTMLDivElement | null>(null);
|
|
27
74
|
useEffect(() => {
|
|
28
75
|
const element = viewport.current;
|
|
29
76
|
if (element) element.scrollTop = element.scrollHeight;
|
|
30
77
|
}, [props.scrollKey]);
|
|
78
|
+
useVisibility(viewport, props.onVisibleChange);
|
|
31
79
|
return (
|
|
32
80
|
<ScrollArea regionLabel={props.label} scrollRef={viewport} height="auto" maxHeight={LIST_MAX_HEIGHT} testId={props.testID}>
|
|
33
|
-
<Stack gap={1}
|
|
81
|
+
<Stack gap={1} aria-live="polite" testID={`${props.testID}-live`}>
|
|
82
|
+
{props.children}
|
|
83
|
+
</Stack>
|
|
34
84
|
</ScrollArea>
|
|
35
85
|
);
|
|
36
86
|
}
|
|
87
|
+
|
|
88
|
+
export function WebBubble(props: ChatBubbleProps): JSX.Element {
|
|
89
|
+
const theme = useUiTheme();
|
|
90
|
+
return (
|
|
91
|
+
<Box
|
|
92
|
+
bg={props.mine ? undefined : "paper"}
|
|
93
|
+
bordered
|
|
94
|
+
radius="md"
|
|
95
|
+
px={2}
|
|
96
|
+
py={1}
|
|
97
|
+
gap={0.5}
|
|
98
|
+
sx={{ maxWidth: BUBBLE_MAX_WIDTH, ...(props.mine ? { backgroundColor: ownBubbleTint(theme) } : {}) }}
|
|
99
|
+
>
|
|
100
|
+
{props.children}
|
|
101
|
+
</Box>
|
|
102
|
+
);
|
|
103
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The surface of the reader's OWN bubbles: the theme's primary colour, washed
|
|
3
|
+
* out to a tint the body text still reads on. Derived from the theme on every
|
|
4
|
+
* render, so a host's brand colour (and its dark mode) reaches the thread with
|
|
5
|
+
* nothing to configure.
|
|
6
|
+
*
|
|
7
|
+
* The others' bubbles keep the paper surface. Both surfaces used to be a
|
|
8
|
+
* surface token, and the two tokens resolve to the same colour in most themes,
|
|
9
|
+
* so which side wrote a line was told only by the label's colour.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { alpha, type UiTheme } from "@12-apps/ui/tokens";
|
|
13
|
+
|
|
14
|
+
/** How much of the primary colour shows through: light text on dark needs more to be seen. */
|
|
15
|
+
const OWN_TINT_STRENGTH = { light: 0.08, dark: 0.16 } as const;
|
|
16
|
+
|
|
17
|
+
export function ownBubbleTint(theme: UiTheme): string {
|
|
18
|
+
return alpha(theme.palette.primary.main, OWN_TINT_STRENGTH[theme.mode]);
|
|
19
|
+
}
|
package/src/ui/surface.tsx
CHANGED
|
@@ -9,7 +9,7 @@ import { useMemo, type JSX } from "react";
|
|
|
9
9
|
import { createChatClient, type ChatFetch } from "../client/api";
|
|
10
10
|
import { missingUiCopy } from "../client/assert";
|
|
11
11
|
import type { ChatUiCopy } from "../client/copy";
|
|
12
|
-
import { useChatThread } from "../client/use-chat-thread";
|
|
12
|
+
import { useChatThread, type ChatAutoMarkRead } from "../client/use-chat-thread";
|
|
13
13
|
import { ChatConfigError } from "../core/errors";
|
|
14
14
|
import { ChatThreadView, type ChatPlatform } from "./thread-view";
|
|
15
15
|
|
|
@@ -33,9 +33,13 @@ export interface ChatThreadProps {
|
|
|
33
33
|
/**
|
|
34
34
|
* Mark the thread read once a load shows unread messages. Default true.
|
|
35
35
|
* A host that mounts the thread hidden only to drive a badge passes false,
|
|
36
|
-
* so nothing is marked read that nobody saw.
|
|
36
|
+
* so nothing is marked read that nobody saw. `"visible"` waits until the
|
|
37
|
+
* message list is on screen: for a thread mounted below the fold (a drawer's
|
|
38
|
+
* lower half), so mounting it is not reading it. On the web that is an
|
|
39
|
+
* IntersectionObserver on the list; on native the list is on screen once
|
|
40
|
+
* it is mounted.
|
|
37
41
|
*/
|
|
38
|
-
readonly autoMarkRead?:
|
|
42
|
+
readonly autoMarkRead?: ChatAutoMarkRead;
|
|
39
43
|
/**
|
|
40
44
|
* Native only: the distance from the window top to the thread (a navigator
|
|
41
45
|
* header), in dp, so the composer clears the keyboard exactly. Default 0.
|
package/src/ui/thread-view.tsx
CHANGED
|
@@ -6,8 +6,8 @@
|
|
|
6
6
|
* Native app (the package's `react-native` export condition resolves each
|
|
7
7
|
* primitive to its native twin). The pieces that differ per platform arrive
|
|
8
8
|
* as a {@link ChatPlatform}: the frame (keyboard avoidance on native), the
|
|
9
|
-
* scrolling message list,
|
|
10
|
-
* same shape.
|
|
9
|
+
* scrolling message list, a message's bubble (its surface is styled beyond the
|
|
10
|
+
* shared props), and the composer, whose change events are not the same shape.
|
|
11
11
|
*
|
|
12
12
|
* Every word on screen is host copy or server data: role labels come from the
|
|
13
13
|
* server (the host's role config), the rest from {@link ChatUiCopy}.
|
|
@@ -46,6 +46,18 @@ export interface ChatMessageListProps {
|
|
|
46
46
|
/** Changes whenever a message is added — the list scrolls to its end on each change. */
|
|
47
47
|
readonly scrollKey: string;
|
|
48
48
|
readonly testID: string;
|
|
49
|
+
/**
|
|
50
|
+
* Set only when the thread marks itself read once SEEN (`autoMarkRead="visible"`):
|
|
51
|
+
* the list reports whether it is on screen now, and `false` when it unmounts.
|
|
52
|
+
*/
|
|
53
|
+
readonly onVisibleChange?: (visible: boolean) => void;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** What a platform's bubble receives: whose message it is, and its label, time and text. */
|
|
57
|
+
export interface ChatBubbleProps {
|
|
58
|
+
/** The reader's own message: drawn on a tint of the theme's primary colour, others on paper. */
|
|
59
|
+
readonly mine: boolean;
|
|
60
|
+
readonly children: ReactNode;
|
|
49
61
|
}
|
|
50
62
|
|
|
51
63
|
/** What a platform's frame receives: the list above, the writing area pinned below. */
|
|
@@ -60,6 +72,7 @@ export interface ChatFrameProps {
|
|
|
60
72
|
export interface ChatPlatform {
|
|
61
73
|
readonly Frame: ComponentType<ChatFrameProps>;
|
|
62
74
|
readonly MessageList: ComponentType<ChatMessageListProps>;
|
|
75
|
+
readonly Bubble: ComponentType<ChatBubbleProps>;
|
|
63
76
|
readonly Composer: ComponentType<ChatComposerProps>;
|
|
64
77
|
}
|
|
65
78
|
|
|
@@ -72,12 +85,18 @@ interface ChatThreadViewProps {
|
|
|
72
85
|
readonly testID?: string;
|
|
73
86
|
}
|
|
74
87
|
|
|
75
|
-
function
|
|
88
|
+
function Message(props: {
|
|
89
|
+
message: ChatWireMessage;
|
|
90
|
+
formatTime: (iso: string) => string;
|
|
91
|
+
Bubble: ChatPlatform["Bubble"];
|
|
92
|
+
}): JSX.Element {
|
|
93
|
+
const { message, formatTime, Bubble } = props;
|
|
76
94
|
return (
|
|
77
95
|
<Box direction="row" justify={message.mine ? "end" : "start"} testID={`chat-message-${message.id}`}>
|
|
78
|
-
<
|
|
96
|
+
<Bubble mine={message.mine}>
|
|
79
97
|
<Stack direction="row" gap={1} align="baseline">
|
|
80
|
-
|
|
98
|
+
{/* Body-text colour on the own tint: the primary colour on its own tint falls under 4.5:1. */}
|
|
99
|
+
<Text variant="caption" weight="semibold" color={message.mine ? "neutral" : "secondary"}>
|
|
81
100
|
{message.label}
|
|
82
101
|
</Text>
|
|
83
102
|
<Text variant="caption" color="secondary">
|
|
@@ -85,7 +104,7 @@ function Bubble({ message, formatTime }: { message: ChatWireMessage; formatTime:
|
|
|
85
104
|
</Text>
|
|
86
105
|
</Stack>
|
|
87
106
|
<Text>{message.body}</Text>
|
|
88
|
-
</
|
|
107
|
+
</Bubble>
|
|
89
108
|
</Box>
|
|
90
109
|
);
|
|
91
110
|
}
|
|
@@ -160,14 +179,19 @@ function Writing(props: ChatThreadViewProps): JSX.Element {
|
|
|
160
179
|
|
|
161
180
|
function Messages(props: ChatThreadViewProps & { messages: readonly ChatWireMessage[] }): JSX.Element {
|
|
162
181
|
const { copy, formatTime, messages } = props;
|
|
163
|
-
const { MessageList } = props.platform;
|
|
182
|
+
const { MessageList, Bubble } = props.platform;
|
|
164
183
|
const newest = messages.at(-1);
|
|
165
184
|
return (
|
|
166
|
-
<MessageList
|
|
185
|
+
<MessageList
|
|
186
|
+
label={copy.messagesLabel}
|
|
187
|
+
scrollKey={`${messages.length}:${newest?.id ?? ""}`}
|
|
188
|
+
testID="chat-messages"
|
|
189
|
+
onVisibleChange={props.controls.onVisibleChange}
|
|
190
|
+
>
|
|
167
191
|
{messages.length === 0 ? (
|
|
168
192
|
<EmptyState variant="minimal" title={copy.emptyTitle} description={copy.emptyDescription} testID="chat-empty" />
|
|
169
193
|
) : (
|
|
170
|
-
messages.map((message) => <
|
|
194
|
+
messages.map((message) => <Message key={message.id} message={message} formatTime={formatTime} Bubble={Bubble} />)
|
|
171
195
|
)}
|
|
172
196
|
</MessageList>
|
|
173
197
|
);
|
|
@@ -189,9 +213,12 @@ export function ChatThreadView(props: ChatThreadViewProps): JSX.Element {
|
|
|
189
213
|
/>
|
|
190
214
|
);
|
|
191
215
|
}
|
|
216
|
+
const { thread, messages } = controls.payload;
|
|
217
|
+
// A closed thread nobody wrote in has nothing to show and nothing to invite: only the notice.
|
|
218
|
+
const nothingToShow = !thread.canWrite && messages.length === 0;
|
|
192
219
|
return (
|
|
193
220
|
<Frame testID={props.testID ?? "chat-thread"} keyboardOffset={props.keyboardOffset}>
|
|
194
|
-
<Messages {...props} messages={
|
|
221
|
+
{nothingToShow ? null : <Messages {...props} messages={messages} />}
|
|
195
222
|
<Writing {...props} />
|
|
196
223
|
</Frame>
|
|
197
224
|
);
|