@12-apps/chat 1.2.1 → 1.3.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 CHANGED
@@ -183,10 +183,49 @@ internal `ChatPlatform`, the one place platform styling lives:
183
183
  | `MessageList` | the bubbles, `label`, `scrollKey`, `onVisibleChange?` | `ScrollArea` + `IntersectionObserver` | `ScrollView`, visible on mount |
184
184
  | `Bubble` | `{ mine, children }` | ui `Box` with `sx` (tint, `min(80%, 60ch)`) | ui `Box` with `style` (tint, `80%`) |
185
185
  | `Composer` | the controlled field and its send action | `Input` + Enter | `Input` + the keyboard's send key |
186
+ | `QuickReplies` | the chips' keys and labels, the heading | ui `Chip`s, wrapping | ui `Chip`s or pills; wrapping, or one sideways line |
187
+ | `Notice` | a failed send's line, tone and look | ui `Alert`, or icon + caption | the same, measured for `onNoticeHeight` |
186
188
 
187
189
  The package opens no socket. Bump `refreshSignal` when your live channel says
188
190
  the thread moved.
189
191
 
192
+ ### Host options
193
+
194
+ Both surfaces take these on the config, all optional; a config without them
195
+ draws the thread exactly as before. A value outside the listed ones throws
196
+ `ChatConfigError` when the surface is built.
197
+
198
+ | config | default | what it changes |
199
+ |---|---|---|
200
+ | `quickReplyLabel(key, text)` | the server's sentence | A chip's label. For chips that are shorter names for the replies: a tap still sends the KEY, so the thread stores the full sentence. Return `text` (or a blank) for a key you do not know. |
201
+ | `quickRepliesHeading` | `"visible"` | `"label"` drops `copy.quickReplies` from the screen and keeps it as the row's accessible name. |
202
+ | `emptyDescription` | `"always"` | `"withQuickReplies"` shows `copy.emptyDescription` only while chips are drawn below, for a description that points at them. |
203
+ | `sendFailureMessage(failure)` | server sentence, else `copy.sendFailed` | The line a failed send shows; return null for the default. `failure.code` is the package's (`contact_info`, …). |
204
+ | `sendFailureNotice` | `"alert"` | `"compact"`: an icon and at most two lines right on the composer, gone once the draft is edited; a `contact_info` refusal reads as a warning, anything else as an error. `"alert"` stays over the chips until the next send. |
205
+ | `sendWhenEmpty` | `"disabled"` | `"inert"` keeps the send button drawn enabled on a blank field; a blank send does nothing. |
206
+
207
+ `createNativeChat` also takes two that only the native row draws:
208
+
209
+ | config | default | what it changes |
210
+ |---|---|---|
211
+ | `quickReplyLook` | `"chip"` | `"pill"`: neutral filled pills with bold labels, at least `NATIVE_CHAT_METRICS.quickReplyMinHeight` (40) dp tall, instead of ui's 32-tall outlined chips. |
212
+ | `quickReplyScrollBelowWidth` | none (always wrap) | Below this window width, in dp, the chips sit on one line that scrolls sideways instead of wrapping. |
213
+
214
+ Chips sit `NATIVE_CHAT_METRICS.quickReplyGap` (8) dp apart either way.
215
+
216
+ `ChatThread` takes three props for a host that sizes the room around the
217
+ thread (a small phone with the keyboard up):
218
+
219
+ - `foldQuickReplies` leaves the chips out; the draft and the list stay.
220
+ - `onNoticeHeight(height)` (native) gets the send-failure notice's height in dp
221
+ on every layout, and 0 whenever none is drawn (dismissed, the thread turned
222
+ read-only, unmounted). It excludes the gap over the notice:
223
+ `theme.spacing(0.5)` on the composer in the compact look, `theme.spacing(2)`
224
+ in the alert look.
225
+ - `onComposerFocusChange(focused)` reports the field taking and losing the
226
+ focus, and `false` when it goes away focused, so a host that hides its
227
+ chrome while someone types never stays hidden.
228
+
190
229
  ## Copy
191
230
 
192
231
  Every sentence is required config, with no defaults. `PT_BR_*` and `EN_US_*`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@12-apps/chat",
3
- "version": "1.2.1",
3
+ "version": "1.3.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.",
@@ -49,7 +49,7 @@
49
49
  "devDependencies": {
50
50
  "@12-apps/eslint-config": "^1.22.0",
51
51
  "@12-apps/typescript-config": "^1.21.0",
52
- "@12-apps/ui": "^6.71.0",
52
+ "@12-apps/ui": "^6.75.0",
53
53
  "@12-apps/wiring": "^1.17.0",
54
54
  "@testing-library/react": "^16.3.1",
55
55
  "@types/node": "^22.10.6",
@@ -16,14 +16,23 @@ import { Box } from "@12-apps/ui/layout/Box";
16
16
  import type { JSX } from "react";
17
17
  import type { TextInputProps } from "react-native";
18
18
 
19
+ import { useFocusReport } from "../ui/focus";
19
20
  import type { ChatComposerProps } from "../ui/thread-view";
20
21
 
21
22
  /** The native field's own events, typed by react-native itself. */
22
23
  type NativeFieldEvents = Required<
23
- Pick<TextInputProps, "onChangeText" | "onSubmitEditing" | "returnKeyType" | "submitBehavior" | "accessibilityLabel">
24
- >;
24
+ Pick<
25
+ TextInputProps,
26
+ "onChangeText" | "onSubmitEditing" | "returnKeyType" | "submitBehavior" | "accessibilityLabel"
27
+ >
28
+ > & {
29
+ /** Argument-free, so the same handler also fits the web `Input`'s focus events the web type-check sees. */
30
+ readonly onFocus: () => void;
31
+ readonly onBlur: () => void;
32
+ };
25
33
 
26
34
  export function NativeComposer(props: ChatComposerProps): JSX.Element {
35
+ const focus = useFocusReport(props.onFocusChange);
27
36
  // A bag rather than attributes so the web type-check (`tsc -p tsconfig.json`,
28
37
  // which sees the web `Input`) accepts the file too; `tsconfig.native.json`
29
38
  // checks the same spread against the native `Input`.
@@ -33,6 +42,8 @@ export function NativeComposer(props: ChatComposerProps): JSX.Element {
33
42
  returnKeyType: "send",
34
43
  submitBehavior: "submit",
35
44
  accessibilityLabel: props.copy.placeholder,
45
+ onFocus: focus.onFocus,
46
+ onBlur: focus.onBlur,
36
47
  };
37
48
  return (
38
49
  <Box direction="row" gap={1} align="center">
@@ -42,7 +53,7 @@ export function NativeComposer(props: ChatComposerProps): JSX.Element {
42
53
  <Button
43
54
  variant="solid"
44
55
  onClick={props.onSubmit}
45
- disabled={props.sending || props.value.trim() === ""}
56
+ disabled={props.sending || (props.disableSendWhenEmpty && props.value.trim() === "")}
46
57
  testID="chat-send"
47
58
  >
48
59
  {props.sending ? props.copy.sending : props.copy.send}
@@ -5,17 +5,46 @@
5
5
  * `react-native` export condition), with a native frame, list and composer.
6
6
  */
7
7
 
8
+ import { ChatConfigError } from "../core/errors";
8
9
  import { buildChatSurface, type ChatSurface, type ChatSurfaceConfig } from "../ui/surface";
9
10
  import { NativeComposer } from "./composer";
10
11
  import { NativeBubble, NativeFrame, NativeMessageList } from "./layout";
12
+ import { NativeNotice } from "./notice";
13
+ import { nativeQuickReplies, type NativeQuickReplyLook } from "./quick-replies";
11
14
 
12
- export function createNativeChat(config: ChatSurfaceConfig): ChatSurface {
15
+ /** The shared config, plus what only the native row draws. */
16
+ export interface NativeChatSurfaceConfig extends ChatSurfaceConfig {
17
+ /**
18
+ * `"chip"` (default): ui's outlined chips with a bolt, as on the web.
19
+ * `"pill"`: neutral filled pills with bold labels, at least
20
+ * `NATIVE_CHAT_METRICS.quickReplyMinHeight` (40) dp tall.
21
+ */
22
+ readonly quickReplyLook?: NativeQuickReplyLook;
23
+ /**
24
+ * Below this window width, in dp, the quick replies sit on one line that
25
+ * scrolls sideways instead of wrapping. Default: they always wrap.
26
+ */
27
+ readonly quickReplyScrollBelowWidth?: number;
28
+ }
29
+
30
+ const LOOKS: readonly NativeQuickReplyLook[] = ["chip", "pill"];
31
+
32
+ export function createNativeChat(config: NativeChatSurfaceConfig): ChatSurface {
33
+ const look = config.quickReplyLook ?? "chip";
34
+ if (!LOOKS.includes(look)) throw new ChatConfigError(`quickReplyLook must be one of ${LOOKS.join(", ")}.`);
35
+ const below = config.quickReplyScrollBelowWidth;
36
+ if (below !== undefined && !(Number.isFinite(below) && below > 0)) {
37
+ throw new ChatConfigError("quickReplyScrollBelowWidth must be a positive number of dp when given.");
38
+ }
13
39
  return buildChatSurface(config, {
14
40
  Frame: NativeFrame,
15
41
  MessageList: NativeMessageList,
16
42
  Bubble: NativeBubble,
17
43
  Composer: NativeComposer,
44
+ QuickReplies: nativeQuickReplies(look, below),
45
+ Notice: NativeNotice,
18
46
  });
19
47
  }
20
48
 
49
+ export { NATIVE_CHAT_METRICS, type NativeQuickReplyLook } from "./quick-replies";
21
50
  export type { ChatSurface, ChatSurfaceConfig, ChatThreadProps } from "../ui/surface";
@@ -0,0 +1,47 @@
1
+ /**
2
+ * The React Native send-failure notice: ui's alert, or — in the compact look —
3
+ * an icon and at most two lines of small text on the composer, not a card
4
+ * that takes the list's room on a small phone. Given `onHeight`, it reports
5
+ * its drawn height, so a host sizing the room around the thread can count it.
6
+ */
7
+
8
+ import { Alert } from "@12-apps/ui/data-display/Alert";
9
+ import { Icon } from "@12-apps/ui/icons";
10
+ import { Text } from "@12-apps/ui/typography/Text";
11
+ import type { JSX } from "react";
12
+ import { StyleSheet, View, type LayoutChangeEvent, type TextProps } from "react-native";
13
+
14
+ import type { ChatNoticeProps } from "../ui/thread-view";
15
+
16
+ const styles = StyleSheet.create({
17
+ line: { flexDirection: "row", alignItems: "flex-start", gap: 6 },
18
+ text: { flexShrink: 1 },
19
+ });
20
+
21
+ /** A bag rather than an attribute, so the web type-check (which sees the web `Text`) accepts the file too. */
22
+ const TWO_LINES: Pick<TextProps, "numberOfLines"> = { numberOfLines: 2 };
23
+
24
+ export function NativeNotice(props: ChatNoticeProps): JSX.Element {
25
+ const measure = props.onHeight
26
+ ? (event: LayoutChangeEvent): void => props.onHeight?.(Math.ceil(event.nativeEvent.layout.height))
27
+ : undefined;
28
+ if (!props.compact) {
29
+ // The default alert, exactly as before (its own role and ids); wrapped, with no role, only to be measured.
30
+ const alert = <Alert variant="danger" description={props.text} testID={props.testID} />;
31
+ return measure ? <View onLayout={measure}>{alert}</View> : alert;
32
+ }
33
+ return (
34
+ <View
35
+ onLayout={measure}
36
+ accessibilityRole="alert"
37
+ accessibilityLiveRegion="polite"
38
+ testID={props.testID}
39
+ style={styles.line}
40
+ >
41
+ <Icon name="WarningAmber" size={16} color={props.tone} />
42
+ <Text variant="body" size="xs" color={props.tone} style={styles.text} {...TWO_LINES}>
43
+ {props.text}
44
+ </Text>
45
+ </View>
46
+ );
47
+ }
@@ -0,0 +1,142 @@
1
+ /**
2
+ * The React Native quick-reply row, in one of two looks:
3
+ * - `chip` (the default): ui's outlined chips with a bolt, as on the web;
4
+ * - `pill`: a neutral filled pill with a bold label, at least
5
+ * {@link NATIVE_CHAT_METRICS.quickReplyMinHeight} dp tall — a thumb's
6
+ * touch target on the road. Drawn here rather than with ui's `Chip`, whose
7
+ * pill is 32 tall and whose filled neutral label is regular weight.
8
+ *
9
+ * The default (chips, wrapping, heading drawn) is the shared row the web
10
+ * draws. Otherwise the chips wrap, {@link NATIVE_CHAT_METRICS.quickReplyGap} dp apart. Below
11
+ * `scrollBelowWidth` (the window's width, in dp) they sit on ONE line that
12
+ * scrolls sideways instead, so a narrow phone does not give the messages'
13
+ * height to four rows of chips.
14
+ */
15
+
16
+ import { Chip } from "@12-apps/ui/data-display/Chip";
17
+ import { Icon } from "@12-apps/ui/icons";
18
+ import { useUiTheme } from "@12-apps/ui/provider";
19
+ import { Text } from "@12-apps/ui/typography/Text";
20
+ import type { ComponentType, JSX, ReactNode } from "react";
21
+ import { Pressable, ScrollView, StyleSheet, View, useWindowDimensions, type TextProps } from "react-native";
22
+
23
+ import { ChipQuickReplies, type ChatQuickRepliesProps } from "../ui/thread-view";
24
+
25
+ /** The quick-reply row's numbers, for a host that sizes the room around the thread. */
26
+ export const NATIVE_CHAT_METRICS = {
27
+ /** A `pill` quick reply's least height, in dp. */
28
+ quickReplyMinHeight: 40,
29
+ /** Between two quick replies, across and down, in dp. */
30
+ quickReplyGap: 8,
31
+ } as const;
32
+
33
+ export type NativeQuickReplyLook = "chip" | "pill";
34
+
35
+ const { quickReplyMinHeight, quickReplyGap } = NATIVE_CHAT_METRICS;
36
+
37
+ const styles = StyleSheet.create({
38
+ block: { gap: quickReplyGap },
39
+ wrap: { flexDirection: "row", flexWrap: "wrap", gap: quickReplyGap },
40
+ line: { flexDirection: "row", gap: quickReplyGap },
41
+ pill: {
42
+ minHeight: quickReplyMinHeight,
43
+ paddingHorizontal: 14,
44
+ borderRadius: quickReplyMinHeight / 2,
45
+ borderWidth: StyleSheet.hairlineWidth,
46
+ alignItems: "center",
47
+ justifyContent: "center",
48
+ },
49
+ disabled: { opacity: 0.5 },
50
+ });
51
+
52
+ const ONE_LINE: Pick<TextProps, "numberOfLines"> = { numberOfLines: 1 };
53
+
54
+ function Pill(props: { label: string; disabled: boolean; onPress: () => void; testID: string }): JSX.Element {
55
+ const { palette } = useUiTheme();
56
+ return (
57
+ <Pressable
58
+ accessibilityRole="button"
59
+ accessibilityLabel={props.label}
60
+ accessibilityState={{ disabled: props.disabled }}
61
+ disabled={props.disabled}
62
+ onPress={props.onPress}
63
+ style={({ pressed }) => [
64
+ styles.pill,
65
+ { backgroundColor: pressed ? palette.action.hover : palette.action.selected, borderColor: palette.divider },
66
+ props.disabled ? styles.disabled : null,
67
+ ]}
68
+ testID={props.testID}
69
+ >
70
+ <Text variant="body" size="sm" weight="bold" {...ONE_LINE}>
71
+ {props.label}
72
+ </Text>
73
+ </Pressable>
74
+ );
75
+ }
76
+
77
+ function Line(props: { oneLine: boolean; children: ReactNode }): JSX.Element {
78
+ if (!props.oneLine) {
79
+ return (
80
+ <View style={styles.wrap} testID="chat-quick-row">
81
+ {props.children}
82
+ </View>
83
+ );
84
+ }
85
+ return (
86
+ <ScrollView
87
+ horizontal
88
+ showsHorizontalScrollIndicator={false}
89
+ keyboardShouldPersistTaps="handled"
90
+ contentContainerStyle={styles.line}
91
+ testID="chat-quick-row"
92
+ >
93
+ {props.children}
94
+ </ScrollView>
95
+ );
96
+ }
97
+
98
+ /** The row for one surface's look and narrow-phone width, built once per `createNativeChat`. */
99
+ export function nativeQuickReplies(look: NativeQuickReplyLook, scrollBelowWidth?: number): ComponentType<ChatQuickRepliesProps> {
100
+ return function NativeQuickReplies(props: ChatQuickRepliesProps): JSX.Element {
101
+ const { width } = useWindowDimensions();
102
+ const oneLine = scrollBelowWidth !== undefined && width < scrollBelowWidth;
103
+ // The default — chips, wrapping, heading drawn — is the shared row, the same tree as the web's.
104
+ if (look === "chip" && !oneLine && props.headingVisible) return <ChipQuickReplies {...props} />;
105
+ return (
106
+ <View
107
+ style={styles.block}
108
+ accessibilityLabel={props.headingVisible ? undefined : props.heading}
109
+ testID="chat-quick-replies"
110
+ >
111
+ {props.headingVisible ? (
112
+ <Text variant="caption" color="secondary">
113
+ {props.heading}
114
+ </Text>
115
+ ) : null}
116
+ <Line oneLine={oneLine}>
117
+ {props.replies.map((reply) =>
118
+ look === "pill" ? (
119
+ <Pill
120
+ key={reply.key}
121
+ label={reply.label}
122
+ disabled={props.disabled}
123
+ onPress={() => props.onPick(reply.key)}
124
+ testID={`chat-quick-${reply.key}`}
125
+ />
126
+ ) : (
127
+ <Chip
128
+ key={reply.key}
129
+ label={reply.label}
130
+ icon={<Icon name="Bolt" size={14} />}
131
+ variant="outlined"
132
+ disabled={props.disabled}
133
+ onClick={() => props.onPick(reply.key)}
134
+ testID={`chat-quick-${reply.key}`}
135
+ />
136
+ ),
137
+ )}
138
+ </Line>
139
+ </View>
140
+ );
141
+ };
142
+ }
@@ -19,10 +19,12 @@ import { Icon } from "@12-apps/ui/icons";
19
19
  import { Box } from "@12-apps/ui/layout/Box";
20
20
  import { useRef, type JSX, type KeyboardEvent } from "react";
21
21
 
22
+ import { useFocusReport } from "../ui/focus";
22
23
  import type { ChatComposerProps } from "../ui/thread-view";
23
24
 
24
25
  export function WebComposer(props: ChatComposerProps): JSX.Element {
25
26
  const field = useRef<HTMLInputElement | null>(null);
27
+ const focus = useFocusReport(props.onFocusChange);
26
28
  const onKeyDown = (event: KeyboardEvent<HTMLInputElement>): void => {
27
29
  if (event.key !== "Enter" || event.shiftKey || event.nativeEvent.isComposing) return;
28
30
  event.preventDefault();
@@ -43,6 +45,8 @@ export function WebComposer(props: ChatComposerProps): JSX.Element {
43
45
  inputProps={{ maxLength: props.maxLength, ref: field }}
44
46
  onChange={(event) => props.onChange(event.target.value)}
45
47
  onKeyDown={onKeyDown}
48
+ onFocus={focus.onFocus}
49
+ onBlur={focus.onBlur}
46
50
  testID="chat-input"
47
51
  />
48
52
  </Box>
@@ -54,7 +58,7 @@ export function WebComposer(props: ChatComposerProps): JSX.Element {
54
58
  title={props.copy.send}
55
59
  loading={props.sending}
56
60
  onClick={onSend}
57
- disabled={props.sending || props.value.trim() === ""}
61
+ disabled={props.sending || (props.disableSendWhenEmpty && props.value.trim() === "")}
58
62
  testID="chat-send"
59
63
  />
60
64
  </Box>
@@ -6,7 +6,9 @@
6
6
 
7
7
  import { buildChatSurface, type ChatSurface, type ChatSurfaceConfig } from "../ui/surface";
8
8
  import { WebComposer } from "./composer";
9
+ import { ChipQuickReplies } from "../ui/thread-view";
9
10
  import { WebBubble, WebFrame, WebMessageList } from "./layout";
11
+ import { WebNotice } from "./notice";
10
12
 
11
13
  export function createWebChat(config: ChatSurfaceConfig): ChatSurface {
12
14
  return buildChatSurface(config, {
@@ -14,6 +16,8 @@ export function createWebChat(config: ChatSurfaceConfig): ChatSurface {
14
16
  MessageList: WebMessageList,
15
17
  Bubble: WebBubble,
16
18
  Composer: WebComposer,
19
+ QuickReplies: ChipQuickReplies,
20
+ Notice: WebNotice,
17
21
  });
18
22
  }
19
23
 
@@ -0,0 +1,24 @@
1
+ /**
2
+ * The web's send-failure notice: ui's alert, or — in the compact look — an
3
+ * icon and a line of small text on the composer.
4
+ */
5
+
6
+ import { Alert } from "@12-apps/ui/data-display/Alert";
7
+ import { Icon } from "@12-apps/ui/icons";
8
+ import { Box } from "@12-apps/ui/layout/Box";
9
+ import { Text } from "@12-apps/ui/typography/Text";
10
+ import type { JSX } from "react";
11
+
12
+ import type { ChatNoticeProps } from "../ui/thread-view";
13
+
14
+ export function WebNotice(props: ChatNoticeProps): JSX.Element {
15
+ if (!props.compact) return <Alert variant="danger" description={props.text} testID={props.testID} />;
16
+ return (
17
+ <Box direction="row" gap={0.75} align="start" role="alert" testID={props.testID}>
18
+ <Icon name="WarningAmber" size={16} color={props.tone} />
19
+ <Text variant="caption" color={props.tone}>
20
+ {props.text}
21
+ </Text>
22
+ </Box>
23
+ );
24
+ }
@@ -0,0 +1,27 @@
1
+ /**
2
+ * The composer's focus, reported to the host: `true` when the field takes it,
3
+ * `false` when it loses it — and `false` when the field goes away while it
4
+ * holds it (the thread turned read-only, the screen closed), so a host that
5
+ * hides its chrome while someone types never stays hidden.
6
+ */
7
+
8
+ import { useEffect, useRef } from "react";
9
+
10
+ export function useFocusReport(onFocusChange?: (focused: boolean) => void): { onFocus: () => void; onBlur: () => void } {
11
+ const latest = useRef(onFocusChange);
12
+ const focused = useRef(false);
13
+ useEffect(() => {
14
+ latest.current = onFocusChange;
15
+ }, [onFocusChange]);
16
+ useEffect(
17
+ () => () => {
18
+ if (focused.current) latest.current?.(false);
19
+ },
20
+ [],
21
+ );
22
+ const report = (next: boolean): void => {
23
+ focused.current = next;
24
+ latest.current?.(next);
25
+ };
26
+ return { onFocus: () => report(true), onBlur: () => report(false) };
27
+ }
@@ -9,11 +9,11 @@ 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, type ChatAutoMarkRead } from "../client/use-chat-thread";
12
+ import { useChatThread, type ChatAutoMarkRead, type ChatSendFailure } from "../client/use-chat-thread";
13
13
  import { ChatConfigError } from "../core/errors";
14
- import { ChatThreadView, type ChatPlatform } from "./thread-view";
14
+ import { ChatThreadView, DEFAULT_CHAT_VIEW_OPTIONS, type ChatPlatform, type ChatViewOptions } from "./thread-view";
15
15
 
16
- /** What a host supplies once. All REQUIRED. */
16
+ /** What a host supplies once. The first three are REQUIRED; the rest change how the thread draws. */
17
17
  export interface ChatSurfaceConfig {
18
18
  /** The host's credentialed fetch (cookie session, Bearer link, …). */
19
19
  readonly fetch: ChatFetch;
@@ -21,6 +21,42 @@ export interface ChatSurfaceConfig {
21
21
  readonly copy: ChatUiCopy;
22
22
  /** How a message's time reads — the host's locale and clock conventions. */
23
23
  readonly formatTime: (iso: string) => string;
24
+ /**
25
+ * A quick reply's chip label, from the server's reply `key` and its full
26
+ * sentence `text`: for a host whose chips are shorter names for the replies.
27
+ * A tap still sends the KEY, so the thread stores the full sentence. Return
28
+ * the `text` (or a blank) for a key you do not know. Default: the sentence.
29
+ */
30
+ readonly quickReplyLabel?: (key: string, text: string) => string;
31
+ /**
32
+ * `"visible"` (default) draws `copy.quickReplies` over the chips; `"label"`
33
+ * keeps it only as the row's accessible name.
34
+ */
35
+ readonly quickRepliesHeading?: "visible" | "label";
36
+ /**
37
+ * `"always"` (default) shows `copy.emptyDescription` under an empty thread's
38
+ * title; `"withQuickReplies"` only while quick replies are drawn below it,
39
+ * for a description that points at them.
40
+ */
41
+ readonly emptyDescription?: "always" | "withQuickReplies";
42
+ /**
43
+ * The line a failed send shows. Return null for the default: the server's
44
+ * own sentence, else `copy.sendFailed`. The failure's `code` is the
45
+ * package's (`contact_info`, `rate_limited`, …), `message` the server's.
46
+ */
47
+ readonly sendFailureMessage?: (failure: ChatSendFailure) => string | null;
48
+ /**
49
+ * `"alert"` (default): a full alert over the quick replies, until the next
50
+ * send. `"compact"`: an icon and at most two lines right on the composer,
51
+ * gone as soon as the draft is edited; a refused message (`contact_info`)
52
+ * reads as a warning, any other failure as an error.
53
+ */
54
+ readonly sendFailureNotice?: "alert" | "compact";
55
+ /**
56
+ * `"disabled"` (default) greys the send button while the field is blank;
57
+ * `"inert"` keeps it drawn enabled, and a blank send does nothing.
58
+ */
59
+ readonly sendWhenEmpty?: "disabled" | "inert";
24
60
  }
25
61
 
26
62
  export interface ChatThreadProps {
@@ -45,6 +81,23 @@ export interface ChatThreadProps {
45
81
  * header), in dp, so the composer clears the keyboard exactly. Default 0.
46
82
  */
47
83
  readonly keyboardOffset?: number;
84
+ /**
85
+ * Leave the quick replies out — for a host short of room (a small phone
86
+ * with the keyboard up). Change it freely: the draft and the list stay.
87
+ */
88
+ readonly foldQuickReplies?: boolean;
89
+ /**
90
+ * Native only: called with the send-failure notice's height in dp each time
91
+ * it is laid out, and with 0 whenever none is drawn (dismissed, the thread
92
+ * turned read-only, the thread unmounted) — so a host sizing the room around
93
+ * the thread can count it. It does not include the gap over it.
94
+ */
95
+ readonly onNoticeHeight?: (height: number) => void;
96
+ /**
97
+ * The composer's field took (`true`) or lost (`false`) the focus; `false`
98
+ * also when the field goes away while focused.
99
+ */
100
+ readonly onComposerFocusChange?: (focused: boolean) => void;
48
101
  readonly testID?: string;
49
102
  }
50
103
 
@@ -60,6 +113,7 @@ export function buildChatSurface(config: ChatSurfaceConfig, platform: ChatPlatfo
60
113
  throw new ChatConfigError(`copy is required, with every key non-blank — missing: ${missing.join(", ")}.`);
61
114
  }
62
115
  const { fetch, copy, formatTime } = config;
116
+ const options = viewOptionsOf(config);
63
117
 
64
118
  function ChatThread(props: ChatThreadProps): JSX.Element {
65
119
  const client = useMemo(() => createChatClient({ fetch, endpoint: props.endpoint }), [props.endpoint]);
@@ -77,7 +131,11 @@ export function buildChatSurface(config: ChatSurfaceConfig, platform: ChatPlatfo
77
131
  copy={copy}
78
132
  formatTime={formatTime}
79
133
  platform={platform}
134
+ options={options}
80
135
  keyboardOffset={props.keyboardOffset}
136
+ foldQuickReplies={props.foldQuickReplies}
137
+ onNoticeHeight={props.onNoticeHeight}
138
+ onComposerFocusChange={props.onComposerFocusChange}
81
139
  testID={props.testID}
82
140
  />
83
141
  );
@@ -85,3 +143,27 @@ export function buildChatSurface(config: ChatSurfaceConfig, platform: ChatPlatfo
85
143
 
86
144
  return { ChatThread };
87
145
  }
146
+
147
+ /** One of `allowed`, or the default when absent; anything else is a config mistake, said at build time. */
148
+ function oneOf<T extends string>(name: string, value: T | undefined, allowed: readonly T[], fallback: T): T {
149
+ if (value === undefined) return fallback;
150
+ if (!allowed.includes(value)) throw new ChatConfigError(`${name} must be one of ${allowed.join(", ")}.`);
151
+ return value;
152
+ }
153
+
154
+ function optionalFunction<T>(name: string, value: T | undefined): T | undefined {
155
+ if (value !== undefined && typeof value !== "function") throw new ChatConfigError(`${name} must be a function when given.`);
156
+ return value;
157
+ }
158
+
159
+ function viewOptionsOf(config: ChatSurfaceConfig): ChatViewOptions {
160
+ const defaults = DEFAULT_CHAT_VIEW_OPTIONS;
161
+ return {
162
+ quickReplyLabel: optionalFunction("quickReplyLabel", config.quickReplyLabel),
163
+ sendFailureMessage: optionalFunction("sendFailureMessage", config.sendFailureMessage),
164
+ quickRepliesHeading: oneOf("quickRepliesHeading", config.quickRepliesHeading, ["visible", "label"], defaults.quickRepliesHeading),
165
+ emptyDescription: oneOf("emptyDescription", config.emptyDescription, ["always", "withQuickReplies"], defaults.emptyDescription),
166
+ sendFailureNotice: oneOf("sendFailureNotice", config.sendFailureNotice, ["alert", "compact"], defaults.sendFailureNotice),
167
+ sendWhenEmpty: oneOf("sendWhenEmpty", config.sendWhenEmpty, ["disabled", "inert"], defaults.sendWhenEmpty),
168
+ };
169
+ }
@@ -22,11 +22,11 @@ import { Box } from "@12-apps/ui/layout/Box";
22
22
  import { Stack } from "@12-apps/ui/layout/Stack";
23
23
  import { Icon } from "@12-apps/ui/icons";
24
24
  import { Text } from "@12-apps/ui/typography/Text";
25
- import { useState, type ComponentType, type JSX, type ReactNode } from "react";
25
+ import { useEffect, useRef, useState, type ComponentType, type JSX, type ReactNode } from "react";
26
26
 
27
- import type { ChatThreadControls } from "../client/use-chat-thread";
27
+ import type { ChatSendFailure, ChatThreadControls } from "../client/use-chat-thread";
28
28
  import type { ChatUiCopy } from "../client/copy";
29
- import type { ChatQuickReply, ChatWireMessage } from "../core/types";
29
+ import type { ChatQuickReply, ChatWireMessage, ChatWireThread } from "../core/types";
30
30
 
31
31
  /** What a platform's composer receives: a controlled field plus its send action. */
32
32
  export interface ChatComposerProps {
@@ -37,6 +37,42 @@ export interface ChatComposerProps {
37
37
  readonly sending: boolean;
38
38
  readonly maxLength: number;
39
39
  readonly copy: ChatUiCopy;
40
+ /**
41
+ * `true` (the default look): the send button is disabled while the field is
42
+ * blank. `false`: it stays drawn as enabled and a tap on a blank field does
43
+ * nothing (the thread's submit ignores it) — {@link ChatViewOptions.sendWhenEmpty}.
44
+ */
45
+ readonly disableSendWhenEmpty: boolean;
46
+ /** The field took or lost the focus — and `false` if it goes away focused. */
47
+ readonly onFocusChange?: (focused: boolean) => void;
48
+ }
49
+
50
+ /** One quick reply as drawn: the key a tap sends, and the label the host chose for it. */
51
+ export interface ChatQuickReplyItem {
52
+ readonly key: string;
53
+ readonly label: string;
54
+ }
55
+
56
+ /** What a platform's quick-reply row receives. Never rendered with an empty `replies`. */
57
+ export interface ChatQuickRepliesProps {
58
+ readonly replies: readonly ChatQuickReplyItem[];
59
+ readonly disabled: boolean;
60
+ /** The row's heading (`copy.quickReplies`): drawn over it, or only its accessible name. */
61
+ readonly heading: string;
62
+ readonly headingVisible: boolean;
63
+ readonly onPick: (key: string) => void;
64
+ }
65
+
66
+ /** What a platform's send-failure notice receives. */
67
+ export interface ChatNoticeProps {
68
+ readonly text: string;
69
+ /** `warning` for a refused message (the contact filter), `danger` for anything else. */
70
+ readonly tone: "warning" | "danger";
71
+ /** A one- or two-line notice on the composer, rather than a full alert over the quick replies. */
72
+ readonly compact: boolean;
73
+ /** Native: the notice's height as drawn, in dp, on every layout. */
74
+ readonly onHeight?: (height: number) => void;
75
+ readonly testID: string;
40
76
  }
41
77
 
42
78
  /** What a platform's message list receives: the bubbles, and when to follow the newest. */
@@ -75,14 +111,49 @@ export interface ChatPlatform {
75
111
  readonly MessageList: ComponentType<ChatMessageListProps>;
76
112
  readonly Bubble: ComponentType<ChatBubbleProps>;
77
113
  readonly Composer: ComponentType<ChatComposerProps>;
114
+ readonly QuickReplies: ComponentType<ChatQuickRepliesProps>;
115
+ readonly Notice: ComponentType<ChatNoticeProps>;
116
+ }
117
+
118
+ /**
119
+ * How the thread draws the parts a host may want differently — every one
120
+ * optional on the surface config, resolved to these defaults by the surface.
121
+ */
122
+ export interface ChatViewOptions {
123
+ /** A quick reply's chip label from its key and the server's sentence; the sentence by default. */
124
+ readonly quickReplyLabel?: (key: string, text: string) => string;
125
+ /** `visible` draws `copy.quickReplies` over the chips; `label` keeps it only as their accessible name. */
126
+ readonly quickRepliesHeading: "visible" | "label";
127
+ /** `withQuickReplies` shows `copy.emptyDescription` only while quick replies are drawn under the list. */
128
+ readonly emptyDescription: "always" | "withQuickReplies";
129
+ /** The line a failed send shows; return null for the default (the server's sentence, else `copy.sendFailed`). */
130
+ readonly sendFailureMessage?: (failure: ChatSendFailure) => string | null;
131
+ /** `alert` over the quick replies until the next send; `compact` on the composer, cleared once the draft is edited. */
132
+ readonly sendFailureNotice: "alert" | "compact";
133
+ /** `disabled` greys the send button on a blank field; `inert` keeps it drawn enabled, and a blank send does nothing. */
134
+ readonly sendWhenEmpty: "disabled" | "inert";
78
135
  }
79
136
 
137
+ export const DEFAULT_CHAT_VIEW_OPTIONS: ChatViewOptions = {
138
+ quickRepliesHeading: "visible",
139
+ emptyDescription: "always",
140
+ sendFailureNotice: "alert",
141
+ sendWhenEmpty: "disabled",
142
+ };
143
+
80
144
  interface ChatThreadViewProps {
81
145
  readonly controls: ChatThreadControls;
82
146
  readonly copy: ChatUiCopy;
83
147
  readonly formatTime: (iso: string) => string;
84
148
  readonly platform: ChatPlatform;
149
+ readonly options: ChatViewOptions;
85
150
  readonly keyboardOffset?: number;
151
+ /** Leave the quick replies out (the host has no room for them now). */
152
+ readonly foldQuickReplies?: boolean;
153
+ /** The send-failure notice's drawn height (native), and 0 whenever none is drawn. */
154
+ readonly onNoticeHeight?: (height: number) => void;
155
+ /** The composer's field took or lost the focus. */
156
+ readonly onComposerFocusChange?: (focused: boolean) => void;
86
157
  readonly testID?: string;
87
158
  }
88
159
 
@@ -109,23 +180,25 @@ function Message(props: {
109
180
  );
110
181
  }
111
182
 
112
- function QuickReplies(props: {
113
- replies: readonly ChatQuickReply[];
114
- disabled: boolean;
115
- copy: ChatUiCopy;
116
- onPick: (key: string) => void;
117
- }): JSX.Element | null {
118
- if (props.replies.length === 0) return null;
183
+ /**
184
+ * The web's quick-reply row, and native's default (`chip`, wrapping, heading
185
+ * shown): ui's outlined chips, wrapping. A hidden heading stays the row's
186
+ * accessible name (`aria-label`; native routes that case to its own row).
187
+ */
188
+ export function ChipQuickReplies(props: ChatQuickRepliesProps): JSX.Element {
189
+ const named = props.headingVisible ? {} : { "aria-label": props.heading };
119
190
  return (
120
- <Stack gap={1} testID="chat-quick-replies">
121
- <Text variant="caption" color="secondary">
122
- {props.copy.quickReplies}
123
- </Text>
191
+ <Stack gap={1} testID="chat-quick-replies" {...named}>
192
+ {props.headingVisible ? (
193
+ <Text variant="caption" color="secondary">
194
+ {props.heading}
195
+ </Text>
196
+ ) : null}
124
197
  <Box direction="row" wrap gap={1}>
125
198
  {props.replies.map((reply) => (
126
199
  <Chip
127
200
  key={reply.key}
128
- label={reply.text}
201
+ label={reply.label}
129
202
  icon={<Icon name="Bolt" size={14} />}
130
203
  variant="outlined"
131
204
  disabled={props.disabled}
@@ -138,50 +211,145 @@ function QuickReplies(props: {
138
211
  );
139
212
  }
140
213
 
141
- function Writing(props: ChatThreadViewProps): JSX.Element {
142
- const { controls, copy, platform } = props;
143
- const { Composer } = platform;
214
+ /** A quick reply's label: the host's, unless it has none (or a blank one) for this key. */
215
+ function labelOf(options: ChatViewOptions, reply: ChatQuickReply): string {
216
+ const label = options.quickReplyLabel?.(reply.key, reply.text);
217
+ return typeof label === "string" && label.trim() !== "" ? label : reply.text;
218
+ }
219
+
220
+ /** The line a failed send shows, and its tone. */
221
+ function noticeOf(options: ChatViewOptions, copy: ChatUiCopy, failure: ChatSendFailure): Pick<ChatNoticeProps, "text" | "tone"> {
222
+ const own = options.sendFailureMessage?.(failure);
223
+ const text = typeof own === "string" && own.trim() !== "" ? own : (failure.message ?? copy.sendFailed);
224
+ // A refusal is the sender's to fix, not a fault: on the compact line it reads as a warning.
225
+ const tone = options.sendFailureNotice === "compact" && failure.code === "contact_info" ? "warning" : "danger";
226
+ return { text, tone };
227
+ }
228
+
229
+ /** Tell the host 0 whenever no notice is drawn, and when the writing area goes away. */
230
+ function useNoticeHeight(drawn: boolean, onNoticeHeight?: (height: number) => void): ((height: number) => void) | undefined {
231
+ const latest = useRef(onNoticeHeight);
232
+ useEffect(() => {
233
+ latest.current = onNoticeHeight;
234
+ }, [onNoticeHeight]);
235
+ useEffect(() => {
236
+ if (!drawn) latest.current?.(0);
237
+ }, [drawn]);
238
+ useEffect(() => () => latest.current?.(0), []);
239
+ // Measured only for a host that asked: the default path draws the notice exactly as before.
240
+ return onNoticeHeight ? (height) => latest.current?.(height) : undefined;
241
+ }
242
+
243
+ /**
244
+ * The failure on screen. In the compact look an edit made while one shows
245
+ * dismisses it (`onEdit`); a later failure is a new one, and shows again.
246
+ */
247
+ function useShownFailure(
248
+ failure: ChatSendFailure | null,
249
+ compact: boolean,
250
+ ): { shown: ChatSendFailure | null; onEdit?: () => void } {
251
+ const [dismissed, setDismissed] = useState<ChatSendFailure | null>(null);
252
+ const shown = failure !== null && failure !== dismissed ? failure : null;
253
+ return { shown, onEdit: compact && shown ? () => setDismissed(shown) : undefined };
254
+ }
255
+
256
+ /** The chips under the list, unless the host folded them or the role has none. */
257
+ function ReplyRow(props: ChatThreadViewProps & { thread: ChatWireThread }): JSX.Element | null {
258
+ const { controls, copy, options, thread } = props;
259
+ const { QuickReplies } = props.platform;
260
+ if (props.foldQuickReplies || thread.quickReplies.length === 0) return null;
261
+ return (
262
+ <QuickReplies
263
+ replies={thread.quickReplies.map((reply) => ({ key: reply.key, label: labelOf(options, reply) }))}
264
+ disabled={controls.sending}
265
+ heading={copy.quickReplies}
266
+ headingVisible={options.quickRepliesHeading === "visible"}
267
+ onPick={(key) => void controls.sendQuickReply(key)}
268
+ />
269
+ );
270
+ }
271
+
272
+ /**
273
+ * The field and its send action. In the compact look it is wrapped with the
274
+ * notice slot right over it — always, so the field is never remounted (and
275
+ * the keyboard never dropped) when a notice comes or goes; in the default
276
+ * look it is the writing area's own child, as it always was.
277
+ */
278
+ function ComposerBlock(
279
+ props: ChatThreadViewProps & { thread: ChatWireThread; compact: boolean; notice: ReactNode; onEdit?: () => void },
280
+ ): JSX.Element | null {
281
+ const { controls, copy, options, thread } = props;
282
+ const { Composer } = props.platform;
144
283
  const [draft, setDraft] = useState("");
145
- const thread = controls.payload?.thread;
146
- if (!thread) return <></>;
147
- if (!thread.canWrite) {
148
- return <Alert variant="info" description={copy.closed} testID="chat-closed" />;
149
- }
150
284
  const submit = async (): Promise<void> => {
151
285
  if (draft.trim() === "" || controls.sending) return;
152
286
  const sent = draft;
153
287
  // Only what was sent is cleared: the field stays live during the send.
154
288
  if (await controls.send(sent)) setDraft((current) => (current === sent ? "" : current));
155
289
  };
290
+ const composer = thread.freeText ? (
291
+ <Composer
292
+ value={draft}
293
+ onChange={(text) => {
294
+ props.onEdit?.();
295
+ setDraft(text);
296
+ }}
297
+ onSubmit={() => void submit()}
298
+ sending={controls.sending}
299
+ maxLength={thread.maxLength}
300
+ copy={copy}
301
+ disableSendWhenEmpty={options.sendWhenEmpty === "disabled"}
302
+ onFocusChange={props.onComposerFocusChange}
303
+ />
304
+ ) : null;
305
+ if (!props.compact) return composer;
306
+ if (props.notice === null && composer === null) return null;
307
+ return (
308
+ <Stack gap={0.5}>
309
+ {props.notice}
310
+ {composer}
311
+ </Stack>
312
+ );
313
+ }
314
+
315
+ function Writing(props: ChatThreadViewProps): JSX.Element {
316
+ const { controls, copy, options } = props;
317
+ const { Notice } = props.platform;
318
+ const compact = options.sendFailureNotice === "compact";
319
+ const failure = useShownFailure(controls.sendFailure, compact);
320
+ const thread = controls.payload?.thread;
321
+ const onHeight = useNoticeHeight(thread?.canWrite === true && failure.shown !== null, props.onNoticeHeight);
322
+ if (!thread) return <></>;
323
+ if (!thread.canWrite) {
324
+ return <Alert variant="info" description={copy.closed} testID="chat-closed" />;
325
+ }
326
+ const notice = failure.shown ? (
327
+ <Notice {...noticeOf(options, copy, failure.shown)} compact={compact} onHeight={onHeight} testID="chat-send-failed" />
328
+ ) : null;
329
+ // The compact notice sits right on the composer, and goes once the draft is edited.
156
330
  return (
157
331
  <Stack gap={2}>
158
- {controls.sendFailure ? (
159
- <Alert variant="danger" description={controls.sendFailure.message ?? copy.sendFailed} testID="chat-send-failed" />
160
- ) : null}
161
- <QuickReplies
162
- replies={thread.quickReplies}
163
- disabled={controls.sending}
164
- copy={copy}
165
- onPick={(key) => void controls.sendQuickReply(key)}
332
+ {compact ? null : notice}
333
+ <ReplyRow {...props} thread={thread} />
334
+ <ComposerBlock
335
+ {...props}
336
+ thread={thread}
337
+ compact={compact}
338
+ notice={compact ? notice : null}
339
+ onEdit={failure.onEdit}
166
340
  />
167
- {thread.freeText ? (
168
- <Composer
169
- value={draft}
170
- onChange={setDraft}
171
- onSubmit={() => void submit()}
172
- sending={controls.sending}
173
- maxLength={thread.maxLength}
174
- copy={copy}
175
- />
176
- ) : null}
177
341
  </Stack>
178
342
  );
179
343
  }
180
344
 
181
345
  function Messages(props: ChatThreadViewProps & { messages: readonly ChatWireMessage[] }): JSX.Element {
182
- const { copy, formatTime, messages } = props;
346
+ const { copy, formatTime, messages, options } = props;
183
347
  const { MessageList, Bubble } = props.platform;
184
348
  const newest = messages.at(-1);
349
+ const thread = props.controls.payload?.thread;
350
+ // "Tap a quick reply below" only while there is one below to tap.
351
+ const repliesBelow = thread?.canWrite === true && !props.foldQuickReplies && thread.quickReplies.length > 0;
352
+ const description = options.emptyDescription === "always" || repliesBelow ? copy.emptyDescription : undefined;
185
353
  return (
186
354
  <MessageList
187
355
  label={copy.messagesLabel}
@@ -190,7 +358,7 @@ function Messages(props: ChatThreadViewProps & { messages: readonly ChatWireMess
190
358
  onVisibleChange={props.controls.onVisibleChange}
191
359
  >
192
360
  {messages.length === 0 ? (
193
- <EmptyState variant="minimal" title={copy.emptyTitle} description={copy.emptyDescription} testID="chat-empty" />
361
+ <EmptyState variant="minimal" title={copy.emptyTitle} description={description} testID="chat-empty" />
194
362
  ) : (
195
363
  messages.map((message) => <Message key={message.id} message={message} formatTime={formatTime} Bubble={Bubble} />)
196
364
  )}