@partrunner-ai/ui 2.4.4 → 2.5.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.
@@ -0,0 +1,461 @@
1
+ # Recipe: Inbox
2
+
3
+ The person works through many records, with one open at a time.
4
+
5
+ This is the full source of a screen that compiles and is tested. Copy the structure and
6
+ the props. Replace the sample data with the data of the app.
7
+
8
+ - `./fixtures` is sample data and two format helpers (`formatMoney`, `formatDate`). Use the
9
+ app's own data and its shared format helpers.
10
+ - `./states` is in `states.md`.
11
+ - The `state` prop exists only to show each state in the catalogue. In an app, the state
12
+ comes from the data request.
13
+ - The rules are in `../DESIGN.md`.
14
+
15
+ <!-- Generated from packages/showcase/src/recipes/InboxRecipe.tsx. Do not edit. -->
16
+
17
+ ```tsx
18
+ import { useMemo, useState } from 'react';
19
+ import { FileText, MessageSquare, Send } from 'lucide-react';
20
+ import {
21
+ Avatar,
22
+ Badge,
23
+ Button,
24
+ DetailItem,
25
+ DetailList,
26
+ EmptyState,
27
+ FilterChip,
28
+ FilterChipRow,
29
+ Input,
30
+ ItemList,
31
+ ItemRow,
32
+ MultiSelect,
33
+ Page,
34
+ PageHeader,
35
+ PageSkeleton,
36
+ SearchField,
37
+ SectionHeading,
38
+ Separator,
39
+ Stack,
40
+ SplitView,
41
+ Tabs,
42
+ TabsContent,
43
+ TabsList,
44
+ TabsTrigger,
45
+ Toolbar,
46
+ ToolbarSpacer,
47
+ toneFromString,
48
+ } from '@partrunner-ai/ui';
49
+ import {
50
+ INBOX_FLEETS,
51
+ INBOX_PEOPLE,
52
+ formatDate,
53
+ formatMoney,
54
+ type ChatItem,
55
+ type ChatMessage,
56
+ type InboxFleet,
57
+ type NextStep,
58
+ } from './fixtures';
59
+ import { ErrorNotice, ForbiddenState, NoResults, type RecipeProps } from './states';
60
+
61
+ type View = 'all' | NextStep | 'overdue';
62
+
63
+ const STEP_ORDER: Record<NextStep, number> = { reply: 0, work: 1, fleet: 2 };
64
+ const STATE_LABEL: Record<NextStep, string> = {
65
+ reply: 'Espera respuesta',
66
+ work: 'En proceso',
67
+ fleet: 'Espera a la flota',
68
+ };
69
+
70
+ function plural(count: number, one: string, many: string): string {
71
+ return `${count} ${count === 1 ? one : many}`;
72
+ }
73
+
74
+ /** Text of the third line: the state, what is open and who has it. The urgency badge goes before it. */
75
+ function rowFooter(fleet: InboxFleet): string {
76
+ const parts: string[] = [];
77
+ if (fleet.nextStep !== 'reply') parts.push(fleet.nextStep === 'work' ? 'En proceso' : 'Espera a la flota');
78
+ if (fleet.openCases > 0) parts.push(plural(fleet.openCases, 'aclaración', 'aclaraciones'));
79
+ if (fleet.openChats > 0) parts.push(plural(fleet.openChats, 'chat', 'chats'));
80
+ parts.push(fleet.owner ? `Atiende ${fleet.owner}` : 'Sin asignar');
81
+ return parts.join(' · ');
82
+ }
83
+
84
+ function isWide(): boolean {
85
+ return typeof window !== 'undefined' && window.matchMedia('(min-width: 900px)').matches;
86
+ }
87
+
88
+ interface ThreadGroup {
89
+ key: string;
90
+ from: ChatMessage['from'];
91
+ author: string;
92
+ messages: ChatMessage[];
93
+ }
94
+
95
+ type ThreadBlock = { type: 'group'; group: ThreadGroup } | { type: 'event'; item: Extract<ChatItem, { kind: 'event' }> };
96
+
97
+ /** One group for each run of consecutive messages of one author. */
98
+ function toBlocks(items: ChatItem[]): ThreadBlock[] {
99
+ const blocks: ThreadBlock[] = [];
100
+ for (const item of items) {
101
+ if (item.kind === 'event') {
102
+ blocks.push({ type: 'event', item });
103
+ continue;
104
+ }
105
+ const last = blocks[blocks.length - 1];
106
+ if (last?.type === 'group' && last.group.author === item.author) {
107
+ last.group.messages.push(item);
108
+ } else {
109
+ blocks.push({ type: 'group', group: { key: item.id, from: item.from, author: item.author, messages: [item] } });
110
+ }
111
+ }
112
+ return blocks;
113
+ }
114
+
115
+ function Conversation({ fleet }: { fleet: InboxFleet }) {
116
+ const [draft, setDraft] = useState('');
117
+ return (
118
+ <Stack>
119
+ <div className="chat" role="log" aria-label={`Conversación con ${fleet.name}`}>
120
+ {toBlocks(fleet.messages).map((block) =>
121
+ block.type === 'event' ? (
122
+ <div key={block.item.id} className="chat__event">
123
+ <Badge tone="info" icon={FileText}>
124
+ {block.item.label}
125
+ </Badge>
126
+ <Button variant="link" size="sm">
127
+ {block.item.caseTitle}
128
+ </Button>
129
+ <span className="chat__event-time">{block.item.time}</span>
130
+ </div>
131
+ ) : (
132
+ <div key={block.group.key} className={`chat__group chat__group--${block.group.from}`}>
133
+ <div className="chat__author">
134
+ <Avatar name={block.group.author} size="sm" tone={toneFromString(block.group.author)} decorative />
135
+ <span>{block.group.author}</span>
136
+ </div>
137
+ {block.group.messages.map((message) => (
138
+ <div key={message.id} className={`chat__bubble chat__bubble--${message.from}`}>
139
+ {message.text}
140
+ <span className="chat__meta">{message.time}</span>
141
+ </div>
142
+ ))}
143
+ </div>
144
+ ),
145
+ )}
146
+ </div>
147
+ <Separator />
148
+ <form
149
+ onSubmit={(event) => {
150
+ event.preventDefault();
151
+ setDraft('');
152
+ }}
153
+ >
154
+ <Input
155
+ fullWidth
156
+ aria-label="Escribir mensaje"
157
+ placeholder="Escribe un mensaje a la flota"
158
+ value={draft}
159
+ onChange={(event) => setDraft(event.target.value)}
160
+ trailing={
161
+ <Button type="submit" size="sm" icon={Send} disabled={draft.trim() === ''}>
162
+ Enviar
163
+ </Button>
164
+ }
165
+ />
166
+ </form>
167
+ </Stack>
168
+ );
169
+ }
170
+
171
+ function Clarifications({ fleet }: { fleet: InboxFleet }) {
172
+ if (fleet.cases.length === 0) {
173
+ return (
174
+ <EmptyState
175
+ title="Sin aclaraciones abiertas"
176
+ description="Esta flota no tiene casos pendientes con Finanzas."
177
+ />
178
+ );
179
+ }
180
+ return (
181
+ <Stack>
182
+ {fleet.cases.map((item, index) => (
183
+ <div key={item.id} className="recipes-stack">
184
+ {index > 0 ? <Separator /> : null}
185
+ <SectionHeading
186
+ headingLevel={3}
187
+ title={item.title}
188
+ actions={
189
+ <Badge tone={item.status === 'open' ? 'warning' : 'success'}>
190
+ {item.status === 'open' ? 'Abierta' : 'Respondida'}
191
+ </Badge>
192
+ }
193
+ />
194
+ <DetailList columns={2}>
195
+ <DetailItem label="Motivo" span="full">
196
+ {item.reason}
197
+ </DetailItem>
198
+ <DetailItem label="Monto" numeric>
199
+ {formatMoney(item.amount)}
200
+ </DetailItem>
201
+ <DetailItem label="Abierta el">{formatDate(item.opened)}</DetailItem>
202
+ <DetailItem label="Responsable">{item.owner}</DetailItem>
203
+ </DetailList>
204
+ </div>
205
+ ))}
206
+ </Stack>
207
+ );
208
+ }
209
+
210
+ function Profile({ fleet }: { fleet: InboxFleet }) {
211
+ const { profile } = fleet;
212
+ return (
213
+ <DetailList layout="inline">
214
+ <DetailItem label="RFC">{fleet.rfc}</DetailItem>
215
+ <DetailItem label="Régimen fiscal">{profile.regime}</DetailItem>
216
+ <DetailItem label="Ciudad">{fleet.city}</DetailItem>
217
+ <DetailItem label="Unidades" numeric>
218
+ {profile.units}
219
+ </DetailItem>
220
+ <DetailItem label="Saldo a cargo" numeric>
221
+ {formatMoney(profile.balance)}
222
+ </DetailItem>
223
+ <DetailItem label="Contacto">{profile.contact}</DetailItem>
224
+ <DetailItem label="Teléfono">{profile.phone}</DetailItem>
225
+ <DetailItem label="Cliente desde">{formatDate(profile.since)}</DetailItem>
226
+ </DetailList>
227
+ );
228
+ }
229
+
230
+ function FleetDetail({ fleet }: { fleet: InboxFleet }) {
231
+ return (
232
+ <Stack>
233
+ <SectionHeading
234
+ title={
235
+ <>
236
+ {fleet.name}{' '}
237
+ <Badge tone={fleet.nextStep === 'reply' ? (fleet.urgency ?? 'warning') : 'neutral'}>
238
+ {STATE_LABEL[fleet.nextStep]}
239
+ </Badge>
240
+ </>
241
+ }
242
+ description={`${fleet.rfc} · ${fleet.city}`}
243
+ actions={
244
+ <>
245
+ <Button size="sm" variant="ghost">
246
+ Abrir ficha
247
+ </Button>
248
+ <Button size="sm" variant="secondary">
249
+ Marcar resuelta
250
+ </Button>
251
+ </>
252
+ }
253
+ />
254
+ <Tabs defaultValue="chat" key={fleet.id}>
255
+ <TabsList>
256
+ <TabsTrigger value="chat">Conversación</TabsTrigger>
257
+ <TabsTrigger value="cases">Aclaraciones</TabsTrigger>
258
+ <TabsTrigger value="profile">Perfil</TabsTrigger>
259
+ </TabsList>
260
+ <TabsContent value="chat">
261
+ <Conversation fleet={fleet} />
262
+ </TabsContent>
263
+ <TabsContent value="cases">
264
+ <Clarifications fleet={fleet} />
265
+ </TabsContent>
266
+ <TabsContent value="profile">
267
+ <Profile fleet={fleet} />
268
+ </TabsContent>
269
+ </Tabs>
270
+ </Stack>
271
+ );
272
+ }
273
+
274
+ /** Recipe 2.3 · Inbox: a ticket desk. Toolbar with filters above a SplitView. */
275
+ export function InboxRecipe({ state, onRetry }: RecipeProps) {
276
+ const [view, setView] = useState<View>('all');
277
+ const [people, setPeople] = useState<string[]>([]);
278
+ const [query, setQuery] = useState('');
279
+ const [selectedId, setSelectedId] = useState<string | null>(() =>
280
+ isWide() ? (INBOX_FLEETS[0]?.id ?? null) : null,
281
+ );
282
+
283
+ const header = <PageHeader title="Bandeja de flotas" subtitle="Mensajes y aclaraciones que esperan al equipo." />;
284
+
285
+ const all = useMemo(
286
+ () =>
287
+ state === 'empty'
288
+ ? []
289
+ : [...INBOX_FLEETS].sort((a, b) => STEP_ORDER[a.nextStep] - STEP_ORDER[b.nextStep]),
290
+ [state],
291
+ );
292
+ const counts = useMemo(
293
+ () => ({
294
+ all: all.length,
295
+ reply: all.filter((fleet) => fleet.nextStep === 'reply').length,
296
+ work: all.filter((fleet) => fleet.nextStep === 'work').length,
297
+ fleet: all.filter((fleet) => fleet.nextStep === 'fleet').length,
298
+ overdue: all.filter((fleet) => fleet.urgency === 'danger').length,
299
+ }),
300
+ [all],
301
+ );
302
+ const fleets = useMemo(() => {
303
+ const needle = query.trim().toLowerCase();
304
+ return all.filter((fleet) => {
305
+ if (view === 'overdue' ? fleet.urgency !== 'danger' : view !== 'all' && fleet.nextStep !== view) return false;
306
+ if (people.length > 0 && !(fleet.owner && people.includes(fleet.owner))) return false;
307
+ return !needle || fleet.name.toLowerCase().includes(needle) || fleet.rfc.toLowerCase().includes(needle);
308
+ });
309
+ }, [all, view, people, query]);
310
+ const filtered = view !== 'all' || people.length > 0 || query.trim() !== '';
311
+ const clearFilters = () => {
312
+ setView('all');
313
+ setPeople([]);
314
+ setQuery('');
315
+ };
316
+
317
+ if (state === 'forbidden') {
318
+ return (
319
+ <Page width="wide">
320
+ {header}
321
+ <ForbiddenState who="Finanzas y Soporte a flotas" />
322
+ </Page>
323
+ );
324
+ }
325
+ if (state === 'loading') {
326
+ return (
327
+ <Page width="wide">
328
+ <PageSkeleton variant="chat" label="Cargando bandeja" />
329
+ </Page>
330
+ );
331
+ }
332
+
333
+ const selected = fleets.find((fleet) => fleet.id === selectedId) ?? null;
334
+ const chips: Array<{ value: View; label: string; tone?: 'danger' }> = [
335
+ { value: 'all', label: 'Todas' },
336
+ { value: 'reply', label: 'Esperan respuesta' },
337
+ { value: 'work', label: 'En proceso' },
338
+ { value: 'fleet', label: 'Esperan a la flota' },
339
+ { value: 'overdue', label: 'Vencidas', tone: 'danger' },
340
+ ];
341
+
342
+ return (
343
+ <Page width="wide">
344
+ {header}
345
+ {state === 'error' ? <ErrorNotice what="la bandeja" onRetry={onRetry} /> : null}
346
+ <Toolbar>
347
+ <FilterChipRow aria-label="Vista">
348
+ {chips.map((chip) => (
349
+ <FilterChip
350
+ key={chip.value}
351
+ active={view === chip.value}
352
+ count={counts[chip.value]}
353
+ tone={chip.tone}
354
+ dot={chip.tone != null}
355
+ onClick={() => setView(chip.value)}
356
+ >
357
+ {chip.label}
358
+ </FilterChip>
359
+ ))}
360
+ </FilterChipRow>
361
+ <ToolbarSpacer />
362
+ <MultiSelect
363
+ variant="filter"
364
+ aria-label="Atiende"
365
+ placeholder="Atiende"
366
+ options={INBOX_PEOPLE.map((person) => ({ value: person, label: person }))}
367
+ value={people}
368
+ onChange={setPeople}
369
+ />
370
+ </Toolbar>
371
+ <SplitView
372
+ className="inbox-split"
373
+ listWidth="lg"
374
+ listLabel="Conversaciones"
375
+ detailLabel="Detalle de la flota"
376
+ detailOpen={selected !== null}
377
+ onBack={() => setSelectedId(null)}
378
+ backLabel="Volver a la bandeja"
379
+ listHeader={
380
+ <div className="inbox-list-head">
381
+ <SearchField
382
+ fullWidth
383
+ aria-label="Buscar flota"
384
+ placeholder="Buscar flota o RFC"
385
+ value={query}
386
+ onChange={(event) => setQuery(event.target.value)}
387
+ />
388
+ <SectionHeading
389
+ headingLevel={3}
390
+ title={
391
+ filtered
392
+ ? `${fleets.length} de ${counts.all} flotas`
393
+ : plural(counts.all, 'flota', 'flotas')
394
+ }
395
+ />
396
+ </div>
397
+ }
398
+ list={
399
+ fleets.length === 0 ? (
400
+ state === 'empty' ? (
401
+ <NoResults title="La bandeja está al día" description="No hay conversaciones abiertas con flotas." />
402
+ ) : (
403
+ <EmptyState
404
+ title="Ninguna flota con este filtro"
405
+ description="Prueba con otro filtro o con otro nombre."
406
+ action={
407
+ <Button variant="secondary" size="sm" onClick={clearFilters}>
408
+ Quitar filtros
409
+ </Button>
410
+ }
411
+ />
412
+ )
413
+ ) : (
414
+ // compact = the dense work queue: three text lines in 59 px a row. Do not restyle the row parts.
415
+ <ItemList aria-label="Flotas" density="compact">
416
+ {fleets.map((fleet) => (
417
+ <ItemRow
418
+ key={fleet.id}
419
+ tone={fleet.urgency ?? undefined}
420
+ leading={<Avatar name={fleet.name} size="sm" tone={toneFromString(fleet.id)} decorative />}
421
+ title={fleet.name}
422
+ unread={fleet.nextStep === 'reply'}
423
+ description={
424
+ <>
425
+ <strong>{fleet.lastSpeaker}:</strong> {fleet.lastMessage}
426
+ </>
427
+ }
428
+ meta={fleet.lastSeen}
429
+ footer={
430
+ <>
431
+ {fleet.urgency && fleet.signal ? (
432
+ <Badge tone={fleet.urgency} size="sm">
433
+ {fleet.signal}
434
+ </Badge>
435
+ ) : null}
436
+ {rowFooter(fleet)}
437
+ </>
438
+ }
439
+ selected={fleet.id === selectedId}
440
+ onClick={() => setSelectedId(fleet.id)}
441
+ />
442
+ ))}
443
+ </ItemList>
444
+ )
445
+ }
446
+ detail={
447
+ selected ? (
448
+ <FleetDetail fleet={selected} />
449
+ ) : (
450
+ <EmptyState
451
+ icon={MessageSquare}
452
+ title="Elige una conversación"
453
+ description="Selecciona una flota de la lista para ver sus mensajes y aclaraciones."
454
+ />
455
+ )
456
+ }
457
+ />
458
+ </Page>
459
+ );
460
+ }
461
+ ```