@particle-academy/react-fancy 5.70.1 → 5.71.1
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/CHANGELOG.md +49 -0
- package/README.md +1 -0
- package/dist/autocomplete.cjs +3 -3
- package/dist/autocomplete.js +2 -2
- package/dist/chat-thread.cjs +27 -0
- package/dist/chat-thread.cjs.map +1 -0
- package/dist/chat-thread.d.cts +260 -0
- package/dist/chat-thread.d.ts +260 -0
- package/dist/chat-thread.js +14 -0
- package/dist/chat-thread.js.map +1 -0
- package/dist/{chunk-IR6JSQ4O.cjs → chunk-4TK3IYR6.cjs} +56 -6
- package/dist/chunk-4TK3IYR6.cjs.map +1 -0
- package/dist/chunk-5IE65DIH.cjs +623 -0
- package/dist/chunk-5IE65DIH.cjs.map +1 -0
- package/dist/{chunk-6QAF35AJ.cjs → chunk-7JLKOVHX.cjs} +3 -3
- package/dist/{chunk-6QAF35AJ.cjs.map → chunk-7JLKOVHX.cjs.map} +1 -1
- package/dist/{chunk-TCMOD3WW.js → chunk-A6NYZ3F5.js} +3 -3
- package/dist/{chunk-TCMOD3WW.js.map → chunk-A6NYZ3F5.js.map} +1 -1
- package/dist/{chunk-AVEFCM6T.cjs → chunk-AQ3NPK2X.cjs} +4 -4
- package/dist/{chunk-AVEFCM6T.cjs.map → chunk-AQ3NPK2X.cjs.map} +1 -1
- package/dist/{chunk-6EA3DSPT.cjs → chunk-FGOFG2UZ.cjs} +5 -5
- package/dist/{chunk-6EA3DSPT.cjs.map → chunk-FGOFG2UZ.cjs.map} +1 -1
- package/dist/{chunk-OYDJVGFS.js → chunk-K7SPT7YF.js} +3 -3
- package/dist/{chunk-OYDJVGFS.js.map → chunk-K7SPT7YF.js.map} +1 -1
- package/dist/{chunk-FHRVSYJU.cjs → chunk-MP55W37V.cjs} +3 -3
- package/dist/{chunk-FHRVSYJU.cjs.map → chunk-MP55W37V.cjs.map} +1 -1
- package/dist/{chunk-EZL5DILH.js → chunk-OPDHSOUN.js} +3 -3
- package/dist/{chunk-EZL5DILH.js.map → chunk-OPDHSOUN.js.map} +1 -1
- package/dist/{chunk-Z4CW3U6C.js → chunk-Q72VHIBI.js} +57 -7
- package/dist/chunk-Q72VHIBI.js.map +1 -0
- package/dist/chunk-UWYSJARZ.js +620 -0
- package/dist/chunk-UWYSJARZ.js.map +1 -0
- package/dist/{chunk-M6UAVA2I.js → chunk-XIA2UAVO.js} +3 -3
- package/dist/{chunk-M6UAVA2I.js.map → chunk-XIA2UAVO.js.map} +1 -1
- package/dist/editor.cjs +3 -3
- package/dist/editor.js +3 -3
- package/dist/index.cjs +173 -164
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +26 -25
- package/dist/index.js.map +1 -1
- package/dist/input.cjs +1 -1
- package/dist/input.js +1 -1
- package/dist/inputs.cjs +7 -7
- package/dist/inputs.js +3 -3
- package/dist/json-editor.cjs +16 -16
- package/dist/json-editor.js +5 -5
- package/dist/prompt-input.cjs +1 -1
- package/dist/prompt-input.js +1 -1
- package/dist/select.cjs +3 -3
- package/dist/select.js +2 -2
- package/dist/tree-nav.cjs +4 -4
- package/dist/tree-nav.js +2 -2
- package/dist/virtual-list.cjs +2 -2
- package/dist/virtual-list.js +1 -1
- package/docs/ChatThread.md +318 -0
- package/package.json +11 -1
- package/dist/chunk-IR6JSQ4O.cjs.map +0 -1
- package/dist/chunk-Z4CW3U6C.js.map +0 -1
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
# ChatThread
|
|
2
|
+
|
|
3
|
+
A controlled message list for agent and support conversations: chat with an
|
|
4
|
+
agent in a side panel, a ticket thread with internal notes, an admin chat whose
|
|
5
|
+
agent drafts proposals for a human to approve. `ChatMessage` is the single
|
|
6
|
+
message, usable on its own.
|
|
7
|
+
|
|
8
|
+
Added in `5.71.0`.
|
|
9
|
+
|
|
10
|
+
## Import
|
|
11
|
+
|
|
12
|
+
```tsx
|
|
13
|
+
import { ChatThread, ChatMessage } from "@particle-academy/react-fancy";
|
|
14
|
+
// or the subpath
|
|
15
|
+
import { ChatThread } from "@particle-academy/react-fancy/chat-thread";
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Basic usage
|
|
19
|
+
|
|
20
|
+
```tsx
|
|
21
|
+
const [messages, setMessages] = useState<ChatMessageData[]>([]);
|
|
22
|
+
|
|
23
|
+
<ChatThread
|
|
24
|
+
className="h-full"
|
|
25
|
+
messages={messages}
|
|
26
|
+
composer={
|
|
27
|
+
<Composer
|
|
28
|
+
onSubmit={async (text) => {
|
|
29
|
+
const res = await send(text); // the server appends the message
|
|
30
|
+
if (!res.ok) return { ok: false, error: res.error };
|
|
31
|
+
}}
|
|
32
|
+
/>
|
|
33
|
+
}
|
|
34
|
+
/>
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
The thread renders exactly `messages`, oldest first. It owns no message state.
|
|
38
|
+
It does not ship an input: put `Composer` or `PromptInput` in the `composer`
|
|
39
|
+
slot. Both have acknowledged send (5.70.0), so the draft stays until your
|
|
40
|
+
`onSubmit` Promise resolves.
|
|
41
|
+
|
|
42
|
+
## Messages are JSON
|
|
43
|
+
|
|
44
|
+
```ts
|
|
45
|
+
interface ChatMessageData {
|
|
46
|
+
id: string; // data-chat-message
|
|
47
|
+
role: "user" | "assistant" | "system" | "agent" | "staff" | "customer" | string;
|
|
48
|
+
author?: { name: string; avatar?: string };
|
|
49
|
+
content: string; // markdown, always sanitised
|
|
50
|
+
format?: "markdown" | "text"; // "text" renders literally
|
|
51
|
+
createdAt: string | number; // ISO 8601 or epoch ms
|
|
52
|
+
status?: "pending" | "streaming" | "sent" | "failed"; // default "sent"
|
|
53
|
+
visibility?: "public" | "internal"; // default "public"
|
|
54
|
+
attachments?: { id: string; name: string; url?: string; mimeType?: string; size?: number }[];
|
|
55
|
+
proposal?: { id: string; title?: string; state?: "pending" | "accepted" | "rejected" | "withdrawn";
|
|
56
|
+
acceptLabel?: string; rejectLabel?: string };
|
|
57
|
+
own?: boolean; // default: ownRoles.includes(role)
|
|
58
|
+
meta?: Record<string, unknown>; // carried, never rendered
|
|
59
|
+
}
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
- **Content** goes through `ContentRenderer` with sanitisation on. There is no
|
|
63
|
+
`unsafe` prop on the thread, on purpose: message bodies are text the host did
|
|
64
|
+
not author. `contentOptions` passes `extensions`, `copyButtons`, `onCopy`,
|
|
65
|
+
`clipboardWriter` and `lineSpacing` through.
|
|
66
|
+
- **Streaming.** A message with `status: "streaming"` renders with
|
|
67
|
+
`ContentRenderer`'s `streaming`: by default an unfinished code fence or tag is
|
|
68
|
+
held back until it closes. `streaming="progressive"` on the thread shows it
|
|
69
|
+
as it fills. The message is `aria-busy` while it streams, so screen readers
|
|
70
|
+
are not read every token. Set the status to `"sent"` when the stream ends.
|
|
71
|
+
- **Roles.** The six named roles get default labels. Any other string is
|
|
72
|
+
carried verbatim on `data-chat-role` and rendered neutrally. `system` renders
|
|
73
|
+
as a centred line.
|
|
74
|
+
- **Own messages** align to the end. `ownRoles` (default `["user"]`) decides
|
|
75
|
+
which; `own` on a message overrides it. A support staff view passes
|
|
76
|
+
`ownRoles={["staff"]}`, or sets `own` per message to distinguish colleagues.
|
|
77
|
+
- **Attachments** render as links (unsafe schemes render the name without a
|
|
78
|
+
link). They are never loaded inline. `renderAttachment` replaces one.
|
|
79
|
+
|
|
80
|
+
## Internal notes
|
|
81
|
+
|
|
82
|
+
`visibility: "internal"` renders a dashed amber bubble with a visible
|
|
83
|
+
"Internal note" label (`[data-chat-internal-label]`) on every internal message.
|
|
84
|
+
|
|
85
|
+
**The thread never decides visibility.** It renders exactly what it is given.
|
|
86
|
+
Filter on the server (and in the transformer) and pass only what this viewer
|
|
87
|
+
may see. A component that hid internal notes itself would be a second policy
|
|
88
|
+
nobody tests.
|
|
89
|
+
|
|
90
|
+
## Proposals (approval cards)
|
|
91
|
+
|
|
92
|
+
A message with a `proposal` is an agent's suggested action awaiting a human: a
|
|
93
|
+
drafted reply, a field change, a page edit. Its `content` is the draft.
|
|
94
|
+
|
|
95
|
+
```tsx
|
|
96
|
+
<ChatThread
|
|
97
|
+
messages={messages}
|
|
98
|
+
onProposalAccept={(m) => api.decide(m.proposal!.id, "accept", m.meta?.version)}
|
|
99
|
+
onProposalReject={(m) => openRejectReasonDialog(m)}
|
|
100
|
+
/>
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
- Stable handle `[data-chat-proposal="<proposal id>"]` with
|
|
104
|
+
`data-chat-proposal-state`; buttons are
|
|
105
|
+
`[data-chat-proposal-action="accept" | "reject"]`.
|
|
106
|
+
- **It never acts on its own.** Nothing is called on render. The state is the
|
|
107
|
+
host's: buttons show only while `state` is `"pending"` (the default) and only
|
|
108
|
+
for the callbacks you pass. When the host moves the card to `accepted`,
|
|
109
|
+
`rejected` or `withdrawn`, the buttons are replaced by a status badge.
|
|
110
|
+
- **Acknowledged.** Return a Promise and both buttons are disabled
|
|
111
|
+
(`aria-busy`) until it settles; a second decision is refused even within the
|
|
112
|
+
same event batch. A rejection goes to `onActionError(error, action)`; without
|
|
113
|
+
it the rejection is left unhandled so it still reaches the console.
|
|
114
|
+
- "Edit then approve" and "reject with a reason" are host UI: open your editor
|
|
115
|
+
or dialog from the callback, or from the actions slot.
|
|
116
|
+
|
|
117
|
+
## Scrolling: stick to the bottom without yanking
|
|
118
|
+
|
|
119
|
+
- The thread starts at the bottom and follows new messages, and a streaming
|
|
120
|
+
message as it grows, **only while the reader is at the bottom**
|
|
121
|
+
(`bottomThreshold`, default 48px).
|
|
122
|
+
- A reader who scrolled up stays exactly where they are. An
|
|
123
|
+
"N new messages" control (`[data-react-fancy-chat-thread-jump]`,
|
|
124
|
+
`data-unseen`) appears; it jumps to the latest and moves focus to the log.
|
|
125
|
+
- The viewer's own new message (see `ownRoles`) always scrolls into view.
|
|
126
|
+
- Prepending earlier messages keeps the message under the reader in place.
|
|
127
|
+
- **Only the log's own `scrollTop` is ever set.** The thread never calls
|
|
128
|
+
`scrollIntoView`, and it focuses with `{ preventScroll: true }`, so no
|
|
129
|
+
ancestor and never the page scrolls (the rule `PromptInput` adopted in 5.69.0
|
|
130
|
+
for genie#1290).
|
|
131
|
+
- `stickToBottom={false}` turns following off entirely.
|
|
132
|
+
- `onAtBottomChange(atBottom)` reports the reader arriving at or leaving the
|
|
133
|
+
bottom.
|
|
134
|
+
|
|
135
|
+
### Imperative handle
|
|
136
|
+
|
|
137
|
+
```tsx
|
|
138
|
+
const thread = useRef<ChatThreadHandle>(null);
|
|
139
|
+
<ChatThread ref={thread} messages={messages} />;
|
|
140
|
+
|
|
141
|
+
thread.current?.scrollToLatest();
|
|
142
|
+
thread.current?.scrollToMessage("msg_42"); // false if not rendered
|
|
143
|
+
thread.current?.element; // the log element
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
## Load earlier
|
|
147
|
+
|
|
148
|
+
```tsx
|
|
149
|
+
<ChatThread
|
|
150
|
+
messages={messages}
|
|
151
|
+
hasEarlier={cursor !== null}
|
|
152
|
+
onLoadEarlier={async () => {
|
|
153
|
+
const page = await api.history(cursor);
|
|
154
|
+
setMessages((m) => [...page.items, ...m]);
|
|
155
|
+
setCursor(page.next);
|
|
156
|
+
}}
|
|
157
|
+
/>
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
The control shows while `onLoadEarlier` is set and `hasEarlier` is not
|
|
161
|
+
`false`. A returned Promise disables it until it settles; `loadingEarlier`
|
|
162
|
+
drives the same state from the host.
|
|
163
|
+
|
|
164
|
+
## Day separators and grouping
|
|
165
|
+
|
|
166
|
+
```tsx
|
|
167
|
+
<ChatThread messages={messages} separators="day" groupConsecutive />
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
- `separators="day"` inserts `[data-chat-day-separator="YYYY-MM-DD"]` at each
|
|
171
|
+
local calendar-day change. `formatDay` formats the label.
|
|
172
|
+
- `groupConsecutive` merges consecutive messages from the same role and author
|
|
173
|
+
within 5 minutes (or pass a window in ms): the header and avatar show once
|
|
174
|
+
and later messages carry `data-chat-grouped`. Internal and public messages
|
|
175
|
+
never merge, and neither do proposals or system lines.
|
|
176
|
+
|
|
177
|
+
## Per-message actions
|
|
178
|
+
|
|
179
|
+
```tsx
|
|
180
|
+
<ChatThread
|
|
181
|
+
messages={messages}
|
|
182
|
+
renderActions={(m) =>
|
|
183
|
+
m.role === "assistant" ? (
|
|
184
|
+
<Button size="xs" variant="ghost" icon="copy" onClick={() => copy(m.content)}>Copy</Button>
|
|
185
|
+
) : m.status === "failed" ? (
|
|
186
|
+
<Button size="xs" variant="ghost" onClick={() => retry(m)}>Retry</Button>
|
|
187
|
+
) : null
|
|
188
|
+
}
|
|
189
|
+
/>
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
The slot renders in `[data-chat-message-actions]`; return `null` for none.
|
|
193
|
+
|
|
194
|
+
## Human+
|
|
195
|
+
|
|
196
|
+
- **Controlled.** `messages` is the state. Loading history and deciding a
|
|
197
|
+
proposal are callbacks; the thread holds only view state (scroll position,
|
|
198
|
+
the unseen count).
|
|
199
|
+
- **Stable handles.** `data-react-fancy-chat-thread`,
|
|
200
|
+
`data-chat-message="<id>"` with `data-chat-role`, `data-chat-status`,
|
|
201
|
+
`data-chat-visibility`, and `data-chat-proposal="<id>"`.
|
|
202
|
+
- **Observable activity.** `onActivity` receives every interaction:
|
|
203
|
+
|
|
204
|
+
```ts
|
|
205
|
+
type ChatThreadActivity =
|
|
206
|
+
| { type: "load-earlier" }
|
|
207
|
+
| { type: "proposal-accept"; messageId: string; proposalId: string }
|
|
208
|
+
| { type: "proposal-reject"; messageId: string; proposalId: string }
|
|
209
|
+
| { type: "jump-to-latest"; unseen: number };
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
Map it onto fancy-auto-common's `AutoActivityEvent` in the host, as with
|
|
213
|
+
`JsonEditor`'s `onActivity`.
|
|
214
|
+
- **Trust but verify.** Proposals are the staged-write affordance: the agent
|
|
215
|
+
proposes, the human decides.
|
|
216
|
+
- **Bridgeable.** A bridge reads and writes the same JSON the host renders
|
|
217
|
+
(`messages`, proposal decisions). The thread itself adds nothing an agent
|
|
218
|
+
has to scrape.
|
|
219
|
+
|
|
220
|
+
## Accessibility
|
|
221
|
+
|
|
222
|
+
- The log is `role="log"`, `aria-live="polite"`, `aria-relevant="additions"`,
|
|
223
|
+
focusable (`tabIndex=0`) so it can be scrolled from the keyboard.
|
|
224
|
+
- It is labelled by `heading` (rendered as `h2`, or `headingLevel`), or by
|
|
225
|
+
`labels.log` ("Conversation") when there is no heading.
|
|
226
|
+
- Every string is in `labels` for translation, including role names and the
|
|
227
|
+
"N new messages" text.
|
|
228
|
+
|
|
229
|
+
## Layouts
|
|
230
|
+
|
|
231
|
+
### Side panel (Charlotte)
|
|
232
|
+
|
|
233
|
+
```tsx
|
|
234
|
+
<ResizablePanels defaultValue={68} label="Resize the chat panel">
|
|
235
|
+
<Editor value={session.state.doc} onOp={session.applyHuman} />
|
|
236
|
+
<ChatThread
|
|
237
|
+
className="h-full"
|
|
238
|
+
heading="Charlotte"
|
|
239
|
+
headingLevel={2}
|
|
240
|
+
messages={session.messages} // reduced from the event log
|
|
241
|
+
streaming="progressive"
|
|
242
|
+
ownRoles={["user"]}
|
|
243
|
+
groupConsecutive
|
|
244
|
+
onProposalAccept={(m) => session.accept(m.proposal!.id)}
|
|
245
|
+
onProposalReject={(m) => session.reject(m.proposal!.id)}
|
|
246
|
+
onActivity={(e) => activity.emit(toAutoActivity(e))}
|
|
247
|
+
renderActions={(m) => m.role === "assistant" && m.status === "sent" ? <CopyButton text={m.content} /> : null}
|
|
248
|
+
composer={
|
|
249
|
+
<PromptInput
|
|
250
|
+
placeholder="Ask Charlotte to change the page..."
|
|
251
|
+
sendDisabled={session.running}
|
|
252
|
+
onSubmit={(text) => session.send(text)}
|
|
253
|
+
/>
|
|
254
|
+
}
|
|
255
|
+
/>
|
|
256
|
+
</ResizablePanels>
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
### Ticket thread (support)
|
|
260
|
+
|
|
261
|
+
```tsx
|
|
262
|
+
<ChatThread
|
|
263
|
+
className="h-full"
|
|
264
|
+
heading={`${ticket.reference}: ${ticket.subject}`}
|
|
265
|
+
messages={ticket.messages} // the server already filtered internal notes for customers
|
|
266
|
+
ownRoles={["staff"]}
|
|
267
|
+
separators="day"
|
|
268
|
+
hasEarlier={ticket.hasEarlier}
|
|
269
|
+
onLoadEarlier={() => loadEarlier(ticket.reference)}
|
|
270
|
+
onProposalAccept={(m) => cards.approve(m.proposal!.id, m.meta?.version as number)}
|
|
271
|
+
onProposalReject={(m) => cards.openReject(m.proposal!.id)}
|
|
272
|
+
onActionError={(err) => toast.error(String(err))}
|
|
273
|
+
composer={
|
|
274
|
+
<Composer
|
|
275
|
+
actions={<MultiSwitch value={mode} onValueChange={setMode} list={[{ value: "public", label: "Reply" }, { value: "internal", label: "Internal note" }]} />}
|
|
276
|
+
onSubmit={(text) => postMessage(ticket.reference, { text, visibility: mode })}
|
|
277
|
+
/>
|
|
278
|
+
}
|
|
279
|
+
/>
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
## Props
|
|
283
|
+
|
|
284
|
+
| Prop | Type | Default | Description |
|
|
285
|
+
|------|------|---------|-------------|
|
|
286
|
+
| messages | `ChatMessageData[]` | - | The messages, oldest first. Required |
|
|
287
|
+
| heading | `ReactNode` | - | Visible title; the log is labelled by it |
|
|
288
|
+
| headingLevel | `2 \| 3 \| 4 \| 5 \| 6` | `2` | Heading element |
|
|
289
|
+
| composer | `ReactNode` | - | Rendered below the log (`Composer` / `PromptInput`) |
|
|
290
|
+
| renderActions | `(m) => ReactNode` | - | Per-message actions slot |
|
|
291
|
+
| onLoadEarlier | `() => void \| Promise` | - | Shows the load-earlier control |
|
|
292
|
+
| hasEarlier | `boolean` | `true` with `onLoadEarlier` | Hide the control when there is nothing earlier |
|
|
293
|
+
| loadingEarlier | `boolean` | `false` | Host-driven busy state for the control |
|
|
294
|
+
| onProposalAccept / onProposalReject | `(m) => void \| Promise` | - | Proposal decisions |
|
|
295
|
+
| onActionError | `(error, action) => void` | - | A returned Promise rejected |
|
|
296
|
+
| onActivity | `(e: ChatThreadActivity) => void` | - | Every interaction |
|
|
297
|
+
| stickToBottom | `boolean` | `true` | Follow new messages while at the bottom |
|
|
298
|
+
| bottomThreshold | `number` | `48` | Pixels from the bottom that count as "at the bottom" |
|
|
299
|
+
| onAtBottomChange | `(atBottom) => void` | - | The reader arrived at / left the bottom |
|
|
300
|
+
| separators | `"none" \| "day"` | `"none"` | Day separators |
|
|
301
|
+
| formatDay / formatTime | `(d: Date) => string` | locale | Date and time labels |
|
|
302
|
+
| groupConsecutive | `boolean \| number` | `false` | Merge consecutive messages (5 min, or ms) |
|
|
303
|
+
| ownRoles | `string[]` | `["user"]` | Roles aligned as the viewer's own |
|
|
304
|
+
| streaming | `true \| "progressive"` | `true` | How a streaming message renders its tail |
|
|
305
|
+
| contentOptions | `ChatContentOptions` | - | Passed to every `ContentRenderer` (no `unsafe`) |
|
|
306
|
+
| renderAttachment | `(a, m) => ReactNode` | - | Replace one attachment's rendering |
|
|
307
|
+
| empty | `ReactNode` | - | Shown when there are no messages |
|
|
308
|
+
| labels | `Partial<ChatThreadLabels>` | English | Every visible string |
|
|
309
|
+
| classNames | `ChatThreadClassNames` | - | `root`, `heading`, `log`, `composer`, `separator`, `jump`, `message`, `bubble`, `header`, `actions`, `proposal` |
|
|
310
|
+
| ref | `Ref<ChatThreadHandle>` | - | `scrollToLatest`, `scrollToMessage`, `element` |
|
|
311
|
+
|
|
312
|
+
Other HTML attributes (including `data-*`) go on the root; `onScroll` is
|
|
313
|
+
forwarded from the log, which is the element that scrolls.
|
|
314
|
+
|
|
315
|
+
`ChatMessage` takes `message`, `actions`, `grouped` and the same display props
|
|
316
|
+
(`ownRoles`, `streaming`, `contentOptions`, `labels`, `formatTime`,
|
|
317
|
+
`renderAttachment`, the proposal callbacks, `onActivity`, `onActionError`,
|
|
318
|
+
`classNames`).
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@particle-academy/react-fancy",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.71.1",
|
|
4
4
|
"description": "React UI component library for Human+ UX — controlled, agent-bridgeable primitives",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -173,6 +173,16 @@
|
|
|
173
173
|
"default": "./dist/chat-drawer.cjs"
|
|
174
174
|
}
|
|
175
175
|
},
|
|
176
|
+
"./chat-thread": {
|
|
177
|
+
"import": {
|
|
178
|
+
"types": "./dist/chat-thread.d.ts",
|
|
179
|
+
"default": "./dist/chat-thread.js"
|
|
180
|
+
},
|
|
181
|
+
"require": {
|
|
182
|
+
"types": "./dist/chat-thread.d.cts",
|
|
183
|
+
"default": "./dist/chat-thread.cjs"
|
|
184
|
+
}
|
|
185
|
+
},
|
|
176
186
|
"./checkbox": {
|
|
177
187
|
"import": {
|
|
178
188
|
"types": "./dist/checkbox.d.ts",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/components/VirtualList/VirtualList.tsx"],"names":["useRef","useState","useCallback","useMemo","useEffect","useLayoutEffect","jsx","cn"],"mappings":";;;;;;AA4DO,SAAS,WAAA,CAAsC;AAAA,EACpD,KAAA;AAAA,EACA,SAAA;AAAA,EACA,MAAA,GAAS,MAAA;AAAA,EACT,iBAAA,GAAoB,EAAA;AAAA,EACpB,QAAA,GAAW,CAAA;AAAA,EACX,UAAA,GAAa,KAAA;AAAA,EACb,cAAA;AAAA,EACA,cAAA;AAAA,EACA,UAAA,GAAa,IAAA;AAAA,EACb,oBAAA;AAAA,EACA,SAAA;AAAA,EACA,GAAA;AAAA,EACA,GAAG;AACL,CAAA,EAAwB;AACtB,EAAA,MAAM,WAAA,GAAcA,aAA8B,IAAI,CAAA;AACtD,EAAA,MAAM,SAAA,GAAYA,aAA8B,IAAI,CAAA;AAGpD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,EAAO;AAAA,MAChB,QAAA;AAAA,MACA,OAAA;AAAA,MACA,SAAA;AAAA,MACA,YAAA;AAAA,MACA,WAAA;AAAA,MACC,GAAG,KAAA;AAAA,MAIJ,QAAA,kBAAAD,cAAA;AAAA,QAAC,KAAA;AAAA,QAAA;AAAA,UACC,qCAAA,EAAoC,EAAA;AAAA,UACpC,OAAO,EAAE,MAAA,EAAQ,GAAG,KAAK,CAAA,EAAA,CAAA,EAAM,UAAU,UAAA,EAAW;AAAA,UAEpD,QAAA,kBAAAA,cAAA;AAAA,YAAC,KAAA;AAAA,YAAA;AAAA,cACC,GAAA,EAAK,SAAA;AAAA,cACL,sCAAA,EAAqC,EAAA;AAAA,cACrC,qCAAA,EAAqC,KAAA;AAAA,cACrC,KAAA,EAAO,EAAE,SAAA,EAAW,CAAA,WAAA,EAAc,QAAQ,KAAK,CAAA,IAAK,CAAC,CAAA,GAAA,CAAA,EAAM;AAAA,cAE1D,kBAAQ,GAAA,CAAI,CAAC,IAAA,EAAM,CAAA,oCACjB,KAAA,EAAA,EAAkB,iCAAA,EAAiC,IAAA,CAAK,EAAA,EACtD,oBAAU,IAAA,EAAM,KAAA,GAAQ,CAAC,CAAA,EAAA,EADlB,IAAA,CAAK,EAEf,CACD;AAAA;AAAA;AACH;AAAA;AACF;AAAA,GACF;AAEJ;AAEA,IAAM,WAAA,GAAc,iCAAA;AAEpB,IAAM,YAAA,GAAe,CAAA;AAErB,IAAM,UAAA,GAAa,CAAA;AACnB,IAAM,8BAAc,IAAI,GAAA,CAAI,CAAC,SAAA,EAAW,QAAA,EAAU,MAAM,CAAC,CAAA","file":"chunk-IR6JSQ4O.cjs","sourcesContent":["import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from \"react\";\nimport type { KeyboardEvent, TouchEvent, WheelEvent } from \"react\";\nimport { cn } from \"../../utils/cn\";\nimport type { VirtualListProps, VirtualListRow } from \"./VirtualList.types\";\n\n/**\n * A windowed list for ledgers that run to tens of thousands of rows — only the\n * visible slice is in the DOM, with **measured** variable row heights, deep\n * links by row id, and sticky-bottom tail-following.\n *\n * Built for an agent event stream, where every one of those three is load\n * bearing at once: message rows wrap and event rows do not, a link carries\n * `?at=<rowId>` to the exact row under discussion, and new rows arrive while\n * the human is reading older ones.\n *\n * ## Heights are measured, never predicted\n *\n * `estimateRowHeight` only seeds rows that have never been on screen. The\n * moment a row renders, its real height is measured and replaces the estimate,\n * and every offset after it moves. The alternative — a `rowHeight(item)`\n * callback — is a prediction about text wrapping, font loading and container\n * width, and when it is wrong the error accumulates down the list: rows draw in\n * the wrong place and `scrollToId` lands on a neighbour. Measuring is slower to\n * settle and correct when it does.\n *\n * ## Tail-follow breaks on INTENT, not on position\n *\n * Any upward gesture — wheel, drag, PageUp, Home — stops following\n * immediately, even when the list is still pinned to the bottom and\n * `scrollTop` has not changed yet. Position cannot tell \"the human scrolled\n * up\" from \"content grew downward\", so a position-only implementation keeps\n * following through a wheel-up and yanks the reader back on the next append.\n *\n * ## It is controlled\n *\n * `followTail` is the consumer's state. This component only ever *asks* via\n * `onFollowChange`, so the follow state is readable and writable by an agent\n * over a bridge, as the Human+ component contract requires. The `↓ n new` pill\n * is the consumer's to render, from `onUnseenChange`.\n *\n * @example\n * ```tsx\n * const [following, setFollowing] = useState(true);\n * const [unseen, setUnseen] = useState(0);\n *\n * <VirtualList\n * items={events}\n * renderRow={(e) => <StreamRow event={e} />}\n * height=\"100%\"\n * estimateRowHeight={28}\n * followTail={following}\n * onFollowChange={setFollowing}\n * onUnseenChange={setUnseen}\n * scrollToId={params.at}\n * />\n * {!following && unseen > 0 && (\n * <Button onClick={() => setFollowing(true)}>↓ {unseen} new</Button>\n * )}\n * ```\n */\nexport function VirtualList<T extends VirtualListRow>({\n items,\n renderRow,\n height = \"100%\",\n estimateRowHeight = 32,\n overscan = 6,\n followTail = false,\n onFollowChange,\n onUnseenChange,\n scrollToId = null,\n onScrollToIdResolved,\n className,\n ref,\n ...props\n}: VirtualListProps<T>) {\n const viewportRef = useRef<HTMLDivElement | null>(null);\n const windowRef = useRef<HTMLDivElement | null>(null);\n\n /** Measured heights by row id, so a height follows its row across a reindex. */\n const heights = useRef(new Map<string, number>());\n /** Bumped when a measurement actually changed, to recompute offsets. */\n const [measured, setMeasured] = useState(0);\n\n const [scrollTop, setScrollTop] = useState(0);\n const [clientHeight, setClientHeight] = useState(0);\n\n const attachViewport = useCallback(\n (el: HTMLDivElement | null) => {\n viewportRef.current = el;\n if (typeof ref === \"function\") ref(el);\n else if (ref) (ref as { current: HTMLDivElement | null }).current = el;\n },\n [ref],\n );\n\n // A number `height` IS the viewport height, and is usable before the element\n // has been measured. Without one, render a conservative first window so there\n // is something on screen for the measurement pass to work from.\n const viewport =\n clientHeight > 0 ? clientHeight : typeof height === \"number\" ? height : estimateRowHeight * 20;\n\n /**\n * Prefix sums of row heights: `offsets[i]` is where row `i` starts, and the\n * last entry is the total. Rebuilt whenever rows or measurements change —\n * O(n) once per change, against O(log n) per scroll from the binary search,\n * rather than O(n) on every scroll frame.\n */\n const { offsets, total } = useMemo(() => {\n const offs = new Float64Array(items.length + 1);\n for (let i = 0; i < items.length; i += 1) {\n offs[i + 1] = offs[i] + (heights.current.get(items[i].id) ?? estimateRowHeight);\n }\n\n return { offsets: offs, total: items.length === 0 ? 0 : offs[items.length] };\n }, [items, measured, estimateRowHeight]);\n\n /** First row whose span contains `y`. */\n const indexAt = useCallback(\n (y: number): number => {\n let lo = 0;\n let hi = items.length - 1;\n while (lo < hi) {\n const mid = (lo + hi + 1) >> 1;\n if (offsets[mid] <= y) lo = mid;\n else hi = mid - 1;\n }\n\n return Math.max(0, lo);\n },\n [items.length, offsets],\n );\n\n const start = Math.max(0, indexAt(scrollTop) - overscan);\n const end = Math.min(items.length, indexAt(scrollTop + viewport) + 1 + overscan);\n const visible = useMemo(() => items.slice(start, end), [items, start, end]);\n\n // ---------------------------------------------------------------- measuring\n\n const observer = useRef<ResizeObserver | null>(null);\n\n useEffect(() => {\n // Absent in jsdom and in older runtimes. Without it the list still measures\n // on every render; it just does not notice a row reflowing in place.\n if (typeof ResizeObserver === \"undefined\") return;\n\n const ro = new ResizeObserver(() => setMeasured((v) => v + 1));\n observer.current = ro;\n\n return () => {\n ro.disconnect();\n observer.current = null;\n };\n }, []);\n\n // No dependency array on purpose: every render re-measures what is on screen,\n // and the `changed` guard is what stops it looping. A render that learns\n // nothing new sets no state.\n useLayoutEffect(() => {\n const win = windowRef.current;\n if (!win) return;\n\n let changed = false;\n for (const el of Array.from(win.children) as HTMLElement[]) {\n const id = el.getAttribute(ROW_ID_ATTR);\n if (id === null) continue;\n\n observer.current?.observe(el);\n\n const h = el.getBoundingClientRect().height;\n // A zero height is \"not laid out yet\", not a 0px row. Recording it would\n // collapse the list and make every offset after it wrong.\n if (h > 0 && heights.current.get(id) !== h) {\n heights.current.set(id, h);\n changed = true;\n }\n }\n\n const vp = viewportRef.current;\n if (vp && vp.clientHeight > 0 && vp.clientHeight !== clientHeight) setClientHeight(vp.clientHeight);\n\n if (changed) setMeasured((v) => v + 1);\n });\n\n // ------------------------------------------------------------- deep linking\n\n /** The target this component last moved to, to detect that it has settled. */\n const anchored = useRef<number | null>(null);\n const resolved = useRef<string | null>(null);\n\n useEffect(() => {\n // A new id is a new request, even if the old one had resolved.\n anchored.current = null;\n resolved.current = null;\n }, [scrollToId]);\n\n useLayoutEffect(() => {\n if (scrollToId === null || resolved.current === scrollToId) return;\n\n const index = items.findIndex((item) => item.id === scrollToId);\n if (index < 0) {\n // A link to a row that is no longer in the list. Leaving the viewport\n // where it is and SAYING SO is the only honest outcome — scrolling to the\n // top would be indistinguishable from a successful landing.\n resolved.current = scrollToId;\n onScrollToIdResolved?.(scrollToId, false);\n\n return;\n }\n\n const vp = viewportRef.current;\n if (!vp) return;\n\n // Clamped the way the browser clamps: a row inside the final viewport-height\n // of the list cannot be brought to the top, and pretending otherwise would\n // leave this waiting for a position that can never be reached.\n const target = Math.max(0, Math.min(offsets[index], Math.max(0, total - viewport)));\n\n if (anchored.current !== target) {\n anchored.current = target;\n vp.scrollTop = target;\n setScrollTop(target);\n\n return;\n }\n\n // The target stopped moving as rows above it were measured, and we are on\n // it. Only now is the deep link actually honoured.\n if (Math.abs(vp.scrollTop - target) <= 1) {\n resolved.current = scrollToId;\n onScrollToIdResolved?.(scrollToId, true);\n }\n });\n\n // ------------------------------------------------------------- tail-follow\n\n const reportedFollow = useRef(followTail);\n const programmatic = useRef(false);\n\n useEffect(() => {\n // The prop is the truth, so adopt it rather than remembering what we asked\n // for. Otherwise a consumer that declines an `onFollowChange(false)` would\n // never be asked again.\n reportedFollow.current = followTail;\n }, [followTail]);\n\n const askFollow = useCallback(\n (next: boolean) => {\n if (reportedFollow.current === next) return;\n reportedFollow.current = next;\n onFollowChange?.(next);\n },\n [onFollowChange],\n );\n\n useLayoutEffect(() => {\n if (!followTail) return;\n // A pending deep link wins while it resolves; otherwise the two would fight\n // over the same scrollTop and the link would lose.\n if (scrollToId !== null && resolved.current !== scrollToId) return;\n\n const vp = viewportRef.current;\n if (!vp) return;\n\n const bottom = Math.max(0, total - viewport);\n if (Math.abs(vp.scrollTop - bottom) > 0.5) {\n programmatic.current = true;\n vp.scrollTop = bottom;\n setScrollTop(bottom);\n }\n });\n\n const onScroll = useCallback(() => {\n const vp = viewportRef.current;\n if (!vp) return;\n\n const next = vp.scrollTop;\n const previous = scrollTop;\n setScrollTop(next);\n\n const bottom = Math.max(0, total - viewport);\n const wasProgrammatic = programmatic.current;\n programmatic.current = false;\n\n if (next <= bottom - BOTTOM_SLACK) {\n // Moved up, and not because we moved it.\n if (!wasProgrammatic && next < previous) askFollow(false);\n } else {\n askFollow(true);\n }\n }, [scrollTop, total, viewport, askFollow]);\n\n /** Any upward gesture is a statement of intent, whatever scrollTop says. */\n const onWheel = useCallback(\n (e: WheelEvent<HTMLDivElement>) => {\n if (e.deltaY < 0) askFollow(false);\n },\n [askFollow],\n );\n\n const onKeyDown = useCallback(\n (e: KeyboardEvent<HTMLDivElement>) => {\n if (UPWARD_KEYS.has(e.key)) askFollow(false);\n },\n [askFollow],\n );\n\n const touchStart = useRef<number | null>(null);\n\n const onTouchStart = useCallback((e: TouchEvent<HTMLDivElement>) => {\n touchStart.current = e.touches[0]?.clientY ?? null;\n }, []);\n\n const onTouchMove = useCallback(\n (e: TouchEvent<HTMLDivElement>) => {\n const from = touchStart.current;\n const y = e.touches[0]?.clientY;\n // Finger travelling DOWN drags the content down, which scrolls up.\n if (from !== null && y !== undefined && y - from > TOUCH_SLOP) askFollow(false);\n },\n [askFollow],\n );\n\n // ------------------------------------------------------------ unseen count\n\n const seen = useRef(items.length);\n const reportedUnseen = useRef<number | null>(null);\n\n useEffect(() => {\n const unseen = followTail ? 0 : Math.max(0, items.length - seen.current);\n if (followTail) seen.current = items.length;\n\n if (reportedUnseen.current === unseen) return;\n reportedUnseen.current = unseen;\n onUnseenChange?.(unseen);\n }, [items.length, followTail, onUnseenChange]);\n\n // ------------------------------------------------------------------ render\n\n return (\n <div\n ref={attachViewport}\n data-react-fancy-virtual-list=\"\"\n data-react-fancy-virtual-list-following={followTail ? \"true\" : \"false\"}\n data-react-fancy-virtual-list-rows={items.length}\n role=\"log\"\n tabIndex={0}\n className={cn(\"relative overflow-y-auto overflow-x-hidden outline-none\", className)}\n style={{ height }}\n onScroll={onScroll}\n onWheel={onWheel}\n onKeyDown={onKeyDown}\n onTouchStart={onTouchStart}\n onTouchMove={onTouchMove}\n {...props}\n >\n {/* Holds the full scroll range so the scrollbar is honest from the first\n paint, instead of growing as rows are discovered. */}\n <div\n data-react-fancy-virtual-list-sizer=\"\"\n style={{ height: `${total}px`, position: \"relative\" }}\n >\n <div\n ref={windowRef}\n data-react-fancy-virtual-list-window=\"\"\n data-react-fancy-virtual-list-start={start}\n style={{ transform: `translateY(${offsets[start] ?? 0}px)` }}\n >\n {visible.map((item, i) => (\n <div key={item.id} data-react-fancy-virtual-row-id={item.id}>\n {renderRow(item, start + i)}\n </div>\n ))}\n </div>\n </div>\n </div>\n );\n}\n\nconst ROW_ID_ATTR = \"data-react-fancy-virtual-row-id\";\n/** Within this many px of the bottom counts as \"at the bottom\". */\nconst BOTTOM_SLACK = 4;\n/** Ignore a touch jitter smaller than this before calling it an upward drag. */\nconst TOUCH_SLOP = 4;\nconst UPWARD_KEYS = new Set([\"ArrowUp\", \"PageUp\", \"Home\"]);\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/components/VirtualList/VirtualList.tsx"],"names":[],"mappings":";;;;AA4DO,SAAS,WAAA,CAAsC;AAAA,EACpD,KAAA;AAAA,EACA,SAAA;AAAA,EACA,MAAA,GAAS,MAAA;AAAA,EACT,iBAAA,GAAoB,EAAA;AAAA,EACpB,QAAA,GAAW,CAAA;AAAA,EACX,UAAA,GAAa,KAAA;AAAA,EACb,cAAA;AAAA,EACA,cAAA;AAAA,EACA,UAAA,GAAa,IAAA;AAAA,EACb,oBAAA;AAAA,EACA,SAAA;AAAA,EACA,GAAA;AAAA,EACA,GAAG;AACL,CAAA,EAAwB;AACtB,EAAA,MAAM,WAAA,GAAc,OAA8B,IAAI,CAAA;AACtD,EAAA,MAAM,SAAA,GAAY,OAA8B,IAAI,CAAA;AAGpD,EAAA,MAAM,OAAA,GAAU,MAAA,iBAAO,IAAI,GAAA,EAAqB,CAAA;AAEhD,EAAA,MAAM,CAAC,QAAA,EAAU,WAAW,CAAA,GAAI,SAAS,CAAC,CAAA;AAE1C,EAAA,MAAM,CAAC,SAAA,EAAW,YAAY,CAAA,GAAI,SAAS,CAAC,CAAA;AAC5C,EAAA,MAAM,CAAC,YAAA,EAAc,eAAe,CAAA,GAAI,SAAS,CAAC,CAAA;AAElD,EAAA,MAAM,cAAA,GAAiB,WAAA;AAAA,IACrB,CAAC,EAAA,KAA8B;AAC7B,MAAA,WAAA,CAAY,OAAA,GAAU,EAAA;AACtB,MAAA,IAAI,OAAO,GAAA,KAAQ,UAAA,EAAY,GAAA,CAAI,EAAE,CAAA;AAAA,WAAA,IAC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AAK,CAAC,CAAA,GAAA,CAAA,EAAM;AAAA,cAE1D,kBAAQ,GAAA,CAAI,CAAC,IAAA,EAAM,CAAA,yBACjB,KAAA,EAAA,EAAkB,iCAAA,EAAiC,IAAA,CAAK,EAAA,EACtD,oBAAU,IAAA,EAAM,KAAA,GAAQ,CAAC,CAAA,EAAA,EADlB,IAAA,CAAK,EAEf,CACD;AAAA;AAAA;AACH;AAAA;AACF;AAAA,GACF;AAEJ;AAEA,IAAM,WAAA,GAAc,iCAAA;AAEpB,IAAM,YAAA,GAAe,CAAA;AAErB,IAAM,UAAA,GAAa,CAAA;AACnB,IAAM,8BAAc,IAAI,GAAA,CAAI,CAAC,SAAA,EAAW,QAAA,EAAU,MAAM,CAAC,CAAA","file":"chunk-Z4CW3U6C.js","sourcesContent":["import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from \"react\";\nimport type { KeyboardEvent, TouchEvent, WheelEvent } from \"react\";\nimport { cn } from \"../../utils/cn\";\nimport type { VirtualListProps, VirtualListRow } from \"./VirtualList.types\";\n\n/**\n * A windowed list for ledgers that run to tens of thousands of rows — only the\n * visible slice is in the DOM, with **measured** variable row heights, deep\n * links by row id, and sticky-bottom tail-following.\n *\n * Built for an agent event stream, where every one of those three is load\n * bearing at once: message rows wrap and event rows do not, a link carries\n * `?at=<rowId>` to the exact row under discussion, and new rows arrive while\n * the human is reading older ones.\n *\n * ## Heights are measured, never predicted\n *\n * `estimateRowHeight` only seeds rows that have never been on screen. The\n * moment a row renders, its real height is measured and replaces the estimate,\n * and every offset after it moves. The alternative — a `rowHeight(item)`\n * callback — is a prediction about text wrapping, font loading and container\n * width, and when it is wrong the error accumulates down the list: rows draw in\n * the wrong place and `scrollToId` lands on a neighbour. Measuring is slower to\n * settle and correct when it does.\n *\n * ## Tail-follow breaks on INTENT, not on position\n *\n * Any upward gesture — wheel, drag, PageUp, Home — stops following\n * immediately, even when the list is still pinned to the bottom and\n * `scrollTop` has not changed yet. Position cannot tell \"the human scrolled\n * up\" from \"content grew downward\", so a position-only implementation keeps\n * following through a wheel-up and yanks the reader back on the next append.\n *\n * ## It is controlled\n *\n * `followTail` is the consumer's state. This component only ever *asks* via\n * `onFollowChange`, so the follow state is readable and writable by an agent\n * over a bridge, as the Human+ component contract requires. The `↓ n new` pill\n * is the consumer's to render, from `onUnseenChange`.\n *\n * @example\n * ```tsx\n * const [following, setFollowing] = useState(true);\n * const [unseen, setUnseen] = useState(0);\n *\n * <VirtualList\n * items={events}\n * renderRow={(e) => <StreamRow event={e} />}\n * height=\"100%\"\n * estimateRowHeight={28}\n * followTail={following}\n * onFollowChange={setFollowing}\n * onUnseenChange={setUnseen}\n * scrollToId={params.at}\n * />\n * {!following && unseen > 0 && (\n * <Button onClick={() => setFollowing(true)}>↓ {unseen} new</Button>\n * )}\n * ```\n */\nexport function VirtualList<T extends VirtualListRow>({\n items,\n renderRow,\n height = \"100%\",\n estimateRowHeight = 32,\n overscan = 6,\n followTail = false,\n onFollowChange,\n onUnseenChange,\n scrollToId = null,\n onScrollToIdResolved,\n className,\n ref,\n ...props\n}: VirtualListProps<T>) {\n const viewportRef = useRef<HTMLDivElement | null>(null);\n const windowRef = useRef<HTMLDivElement | null>(null);\n\n /** Measured heights by row id, so a height follows its row across a reindex. */\n const heights = useRef(new Map<string, number>());\n /** Bumped when a measurement actually changed, to recompute offsets. */\n const [measured, setMeasured] = useState(0);\n\n const [scrollTop, setScrollTop] = useState(0);\n const [clientHeight, setClientHeight] = useState(0);\n\n const attachViewport = useCallback(\n (el: HTMLDivElement | null) => {\n viewportRef.current = el;\n if (typeof ref === \"function\") ref(el);\n else if (ref) (ref as { current: HTMLDivElement | null }).current = el;\n },\n [ref],\n );\n\n // A number `height` IS the viewport height, and is usable before the element\n // has been measured. Without one, render a conservative first window so there\n // is something on screen for the measurement pass to work from.\n const viewport =\n clientHeight > 0 ? clientHeight : typeof height === \"number\" ? height : estimateRowHeight * 20;\n\n /**\n * Prefix sums of row heights: `offsets[i]` is where row `i` starts, and the\n * last entry is the total. Rebuilt whenever rows or measurements change —\n * O(n) once per change, against O(log n) per scroll from the binary search,\n * rather than O(n) on every scroll frame.\n */\n const { offsets, total } = useMemo(() => {\n const offs = new Float64Array(items.length + 1);\n for (let i = 0; i < items.length; i += 1) {\n offs[i + 1] = offs[i] + (heights.current.get(items[i].id) ?? estimateRowHeight);\n }\n\n return { offsets: offs, total: items.length === 0 ? 0 : offs[items.length] };\n }, [items, measured, estimateRowHeight]);\n\n /** First row whose span contains `y`. */\n const indexAt = useCallback(\n (y: number): number => {\n let lo = 0;\n let hi = items.length - 1;\n while (lo < hi) {\n const mid = (lo + hi + 1) >> 1;\n if (offsets[mid] <= y) lo = mid;\n else hi = mid - 1;\n }\n\n return Math.max(0, lo);\n },\n [items.length, offsets],\n );\n\n const start = Math.max(0, indexAt(scrollTop) - overscan);\n const end = Math.min(items.length, indexAt(scrollTop + viewport) + 1 + overscan);\n const visible = useMemo(() => items.slice(start, end), [items, start, end]);\n\n // ---------------------------------------------------------------- measuring\n\n const observer = useRef<ResizeObserver | null>(null);\n\n useEffect(() => {\n // Absent in jsdom and in older runtimes. Without it the list still measures\n // on every render; it just does not notice a row reflowing in place.\n if (typeof ResizeObserver === \"undefined\") return;\n\n const ro = new ResizeObserver(() => setMeasured((v) => v + 1));\n observer.current = ro;\n\n return () => {\n ro.disconnect();\n observer.current = null;\n };\n }, []);\n\n // No dependency array on purpose: every render re-measures what is on screen,\n // and the `changed` guard is what stops it looping. A render that learns\n // nothing new sets no state.\n useLayoutEffect(() => {\n const win = windowRef.current;\n if (!win) return;\n\n let changed = false;\n for (const el of Array.from(win.children) as HTMLElement[]) {\n const id = el.getAttribute(ROW_ID_ATTR);\n if (id === null) continue;\n\n observer.current?.observe(el);\n\n const h = el.getBoundingClientRect().height;\n // A zero height is \"not laid out yet\", not a 0px row. Recording it would\n // collapse the list and make every offset after it wrong.\n if (h > 0 && heights.current.get(id) !== h) {\n heights.current.set(id, h);\n changed = true;\n }\n }\n\n const vp = viewportRef.current;\n if (vp && vp.clientHeight > 0 && vp.clientHeight !== clientHeight) setClientHeight(vp.clientHeight);\n\n if (changed) setMeasured((v) => v + 1);\n });\n\n // ------------------------------------------------------------- deep linking\n\n /** The target this component last moved to, to detect that it has settled. */\n const anchored = useRef<number | null>(null);\n const resolved = useRef<string | null>(null);\n\n useEffect(() => {\n // A new id is a new request, even if the old one had resolved.\n anchored.current = null;\n resolved.current = null;\n }, [scrollToId]);\n\n useLayoutEffect(() => {\n if (scrollToId === null || resolved.current === scrollToId) return;\n\n const index = items.findIndex((item) => item.id === scrollToId);\n if (index < 0) {\n // A link to a row that is no longer in the list. Leaving the viewport\n // where it is and SAYING SO is the only honest outcome — scrolling to the\n // top would be indistinguishable from a successful landing.\n resolved.current = scrollToId;\n onScrollToIdResolved?.(scrollToId, false);\n\n return;\n }\n\n const vp = viewportRef.current;\n if (!vp) return;\n\n // Clamped the way the browser clamps: a row inside the final viewport-height\n // of the list cannot be brought to the top, and pretending otherwise would\n // leave this waiting for a position that can never be reached.\n const target = Math.max(0, Math.min(offsets[index], Math.max(0, total - viewport)));\n\n if (anchored.current !== target) {\n anchored.current = target;\n vp.scrollTop = target;\n setScrollTop(target);\n\n return;\n }\n\n // The target stopped moving as rows above it were measured, and we are on\n // it. Only now is the deep link actually honoured.\n if (Math.abs(vp.scrollTop - target) <= 1) {\n resolved.current = scrollToId;\n onScrollToIdResolved?.(scrollToId, true);\n }\n });\n\n // ------------------------------------------------------------- tail-follow\n\n const reportedFollow = useRef(followTail);\n const programmatic = useRef(false);\n\n useEffect(() => {\n // The prop is the truth, so adopt it rather than remembering what we asked\n // for. Otherwise a consumer that declines an `onFollowChange(false)` would\n // never be asked again.\n reportedFollow.current = followTail;\n }, [followTail]);\n\n const askFollow = useCallback(\n (next: boolean) => {\n if (reportedFollow.current === next) return;\n reportedFollow.current = next;\n onFollowChange?.(next);\n },\n [onFollowChange],\n );\n\n useLayoutEffect(() => {\n if (!followTail) return;\n // A pending deep link wins while it resolves; otherwise the two would fight\n // over the same scrollTop and the link would lose.\n if (scrollToId !== null && resolved.current !== scrollToId) return;\n\n const vp = viewportRef.current;\n if (!vp) return;\n\n const bottom = Math.max(0, total - viewport);\n if (Math.abs(vp.scrollTop - bottom) > 0.5) {\n programmatic.current = true;\n vp.scrollTop = bottom;\n setScrollTop(bottom);\n }\n });\n\n const onScroll = useCallback(() => {\n const vp = viewportRef.current;\n if (!vp) return;\n\n const next = vp.scrollTop;\n const previous = scrollTop;\n setScrollTop(next);\n\n const bottom = Math.max(0, total - viewport);\n const wasProgrammatic = programmatic.current;\n programmatic.current = false;\n\n if (next <= bottom - BOTTOM_SLACK) {\n // Moved up, and not because we moved it.\n if (!wasProgrammatic && next < previous) askFollow(false);\n } else {\n askFollow(true);\n }\n }, [scrollTop, total, viewport, askFollow]);\n\n /** Any upward gesture is a statement of intent, whatever scrollTop says. */\n const onWheel = useCallback(\n (e: WheelEvent<HTMLDivElement>) => {\n if (e.deltaY < 0) askFollow(false);\n },\n [askFollow],\n );\n\n const onKeyDown = useCallback(\n (e: KeyboardEvent<HTMLDivElement>) => {\n if (UPWARD_KEYS.has(e.key)) askFollow(false);\n },\n [askFollow],\n );\n\n const touchStart = useRef<number | null>(null);\n\n const onTouchStart = useCallback((e: TouchEvent<HTMLDivElement>) => {\n touchStart.current = e.touches[0]?.clientY ?? null;\n }, []);\n\n const onTouchMove = useCallback(\n (e: TouchEvent<HTMLDivElement>) => {\n const from = touchStart.current;\n const y = e.touches[0]?.clientY;\n // Finger travelling DOWN drags the content down, which scrolls up.\n if (from !== null && y !== undefined && y - from > TOUCH_SLOP) askFollow(false);\n },\n [askFollow],\n );\n\n // ------------------------------------------------------------ unseen count\n\n const seen = useRef(items.length);\n const reportedUnseen = useRef<number | null>(null);\n\n useEffect(() => {\n const unseen = followTail ? 0 : Math.max(0, items.length - seen.current);\n if (followTail) seen.current = items.length;\n\n if (reportedUnseen.current === unseen) return;\n reportedUnseen.current = unseen;\n onUnseenChange?.(unseen);\n }, [items.length, followTail, onUnseenChange]);\n\n // ------------------------------------------------------------------ render\n\n return (\n <div\n ref={attachViewport}\n data-react-fancy-virtual-list=\"\"\n data-react-fancy-virtual-list-following={followTail ? \"true\" : \"false\"}\n data-react-fancy-virtual-list-rows={items.length}\n role=\"log\"\n tabIndex={0}\n className={cn(\"relative overflow-y-auto overflow-x-hidden outline-none\", className)}\n style={{ height }}\n onScroll={onScroll}\n onWheel={onWheel}\n onKeyDown={onKeyDown}\n onTouchStart={onTouchStart}\n onTouchMove={onTouchMove}\n {...props}\n >\n {/* Holds the full scroll range so the scrollbar is honest from the first\n paint, instead of growing as rows are discovered. */}\n <div\n data-react-fancy-virtual-list-sizer=\"\"\n style={{ height: `${total}px`, position: \"relative\" }}\n >\n <div\n ref={windowRef}\n data-react-fancy-virtual-list-window=\"\"\n data-react-fancy-virtual-list-start={start}\n style={{ transform: `translateY(${offsets[start] ?? 0}px)` }}\n >\n {visible.map((item, i) => (\n <div key={item.id} data-react-fancy-virtual-row-id={item.id}>\n {renderRow(item, start + i)}\n </div>\n ))}\n </div>\n </div>\n </div>\n );\n}\n\nconst ROW_ID_ATTR = \"data-react-fancy-virtual-row-id\";\n/** Within this many px of the bottom counts as \"at the bottom\". */\nconst BOTTOM_SLACK = 4;\n/** Ignore a touch jitter smaller than this before calling it an upward drag. */\nconst TOUCH_SLOP = 4;\nconst UPWARD_KEYS = new Set([\"ArrowUp\", \"PageUp\", \"Home\"]);\n"]}
|