@hgdc/ui 0.30.0 → 0.31.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
@@ -109,6 +109,7 @@ Sur ordinateur, la coque ouvre sur la barre des produits (ADR 0011) : organisati
109
109
  | `rank-bar` | `<RankBar label="Pages les plus vues" items={[{ key, label: "/tarifs", value: 640, render: <Link … /> }]} limit={5} />` |
110
110
  | `secret-reveal` | `<SecretReveal label="Clé d'API" value={key} onDismiss={forget} />` : affichée une fois, puis retirée de la page |
111
111
  | `assistant-chat` | `<AssistantConversation><AssistantUserMessage>…</AssistantUserMessage><AssistantReply tools={chips} waiting={pending} actions={<AssistantActionCard title=… status="pending" onConfirm={…} onCancel={…} />}><Markdown>{text}</Markdown></AssistantReply></AssistantConversation>`, `<AssistantComposer value={v} onValueChange={setV} onSubmit={send} busy={busy} />`, `<AssistantExamples examples={…} onPick={setV} />` : le produit rend le Markdown |
112
+ | `assistant-view` | `<AssistantView status={status} threads={threads} threadId={id} onThreadChange={setId} thread={thread} renderText={(t) => <Markdown>{t}</Markdown>} onSend={send} onConfirm={confirm} onCancel={cancel} />` : le panneau complet pour `AppShell` (`assistant.panel`), aux formes de `@hgdc/assistant/convex` ; `subject` (page ouverte), `request` (demande venue de la page), `labels` (vouvoiement) |
112
113
  | `family-loader` | `<FamilyLoaderRoot>{children}</FamilyLoaderRoot>` une fois dans le `body` de la route racine : le seul H d'un chargement de page, fixe sur la zone de contenu de la coque, rendu par le serveur, calé sur l'horloge (même pixel et même phase d'une page et d'un produit à l'autre, ADR 0015). `<FamilyLoader size="lg" />` : le H en ligne (une boucle de 2 s, `transform` et `opacity`). Dans un bouton : `Spinner` |
113
114
  | `page-pending` | `createRouter({ routeTree, ...routerPendingDefaults })` (préchargement au survol, chargement après 50 ms, au moins 300 ms) ; `AppShell {...useRouterState({ select: shellNavigation, structuralSharing: true })}` : la zone de contenu se couvre dès qu'une navigation attend, la coque reste ; `PagePending` : marque la place d'une page qui attend, le H du document s'affiche |
114
115
  | `skeleton` | `<Pending pending={isLoading} fallback={<TableSkeleton columns={3} />}>…</Pending>` : après 200 ms, tenu 400 ms au moins |
@@ -35,7 +35,7 @@ export declare function AssistantReply({ tools, waiting, waitingLabel, error, ac
35
35
  * Une écriture proposée par l'assistant, qui n'a lieu qu'au clic sur « Confirmer ». Une fois
36
36
  * traitée, la carte garde son état (fait, annulé, échec et sa raison).
37
37
  */
38
- export declare function AssistantActionCard({ title, details, status, result, onConfirm, onCancel, confirming, cancelling, confirmLabel, cancelLabel, }: {
38
+ export declare function AssistantActionCard({ title, details, status, result, onConfirm, onCancel, confirming, cancelling, confirmLabel, cancelLabel, pendingLabel, }: {
39
39
  title: ReactNode;
40
40
  details?: ReadonlyArray<{
41
41
  label: string;
@@ -50,6 +50,8 @@ export declare function AssistantActionCard({ title, details, status, result, on
50
50
  cancelling?: boolean;
51
51
  confirmLabel?: string;
52
52
  cancelLabel?: string;
53
+ /** Au-dessus du titre tant que la carte attend. */
54
+ pendingLabel?: string;
53
55
  }): React.JSX.Element;
54
56
  /** Des demandes d'exemple, pour une conversation vide : un clic remplit la saisie. */
55
57
  export declare function AssistantExamples({ examples, onPick, disabled, label, }: {
@@ -1,4 +1,5 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import Alert02Icon from "@hugeicons/core-free-icons/Alert02Icon";
2
3
  import ArrowUp02Icon from "@hugeicons/core-free-icons/ArrowUp02Icon";
3
4
  import Cancel01Icon from "@hugeicons/core-free-icons/Cancel01Icon";
4
5
  import CheckmarkCircle02Icon from "@hugeicons/core-free-icons/CheckmarkCircle02Icon";
@@ -22,7 +23,7 @@ export function AssistantUserMessage({ children }) {
22
23
  export function AssistantToolChips({ tools, label = "Ce que l'assistant a consulté", }) {
23
24
  if (!tools.length)
24
25
  return null;
25
- return (_jsx("ul", { className: "flex flex-wrap gap-1.5", "aria-label": label, children: tools.map((tool) => (_jsx("li", { children: _jsxs(Badge, { tone: tool.status === "error" ? "destructive" : "neutral", children: [tool.status === "running" ? _jsx(Spinner, { size: 3 }) : null, tool.label] }) }, tool.id))) }));
26
+ return (_jsx("ul", { className: "flex flex-wrap gap-1.5", "aria-label": label, children: tools.map((tool) => (_jsx("li", { children: _jsxs(Badge, { tone: tool.status === "error" ? "destructive" : "neutral", "data-status": tool.status, children: [tool.status === "running" ? (_jsx(Spinner, { size: 3 })) : (_jsx(HugeiconsIcon, { icon: tool.status === "done" ? CheckmarkCircle02Icon : Alert02Icon, "aria-hidden": true, className: cn("size-3.5", tool.status === "done" && "text-success") })), tool.label, tool.status === "error" ? _jsx("span", { className: "sr-only", children: " (\u00E9chec)" }) : null] }) }, tool.id))) }));
26
27
  }
27
28
  /**
28
29
  * Une réponse : pastilles, puis le texte rendu par le produit (`children`), puis les cartes.
@@ -40,9 +41,9 @@ const ACTION_BADGE = {
40
41
  * Une écriture proposée par l'assistant, qui n'a lieu qu'au clic sur « Confirmer ». Une fois
41
42
  * traitée, la carte garde son état (fait, annulé, échec et sa raison).
42
43
  */
43
- export function AssistantActionCard({ title, details = [], status, result, onConfirm, onCancel, confirming = false, cancelling = false, confirmLabel = "Confirmer", cancelLabel = "Annuler", }) {
44
+ export function AssistantActionCard({ title, details = [], status, result, onConfirm, onCancel, confirming = false, cancelling = false, confirmLabel = "Confirmer", cancelLabel = "Annuler", pendingLabel = "À confirmer", }) {
44
45
  const badge = status === "pending" ? null : ACTION_BADGE[status];
45
- return (_jsxs(Card, { "data-slot": "assistant-action-card", className: "max-w-xl", children: [_jsx(CardHeader, { children: _jsx(CardTitle, { className: "text-base", children: title }) }), details.length ? (_jsx(CardContent, { children: _jsx("dl", { className: "grid gap-2 text-sm", children: details.map((row) => (_jsxs("div", { className: "grid gap-0.5", children: [_jsx("dt", { className: "text-muted-foreground", children: row.label }), _jsx("dd", { className: "break-words whitespace-pre-wrap", children: row.value })] }, row.label))) }) })) : null, _jsx(CardFooter, { className: "justify-start", children: badge ? (_jsx(Badge, { tone: badge.tone, children: status === "failed" && result ? `${badge.label} : ${result}` : badge.label })) : (_jsxs("div", { className: "flex flex-wrap gap-2", children: [_jsxs(Button, { size: "sm", isLoading: confirming, disabled: cancelling, onClick: onConfirm, children: [_jsx(HugeiconsIcon, { icon: CheckmarkCircle02Icon, "data-icon": "inline-start" }), confirmLabel] }), _jsxs(Button, { size: "sm", variant: "ghost", isLoading: cancelling, disabled: confirming, onClick: onCancel, children: [_jsx(HugeiconsIcon, { icon: Cancel01Icon, "data-icon": "inline-start" }), cancelLabel] })] })) })] }));
46
+ return (_jsxs(Card, { "data-slot": "assistant-action-card", "data-status": status, className: "max-w-xl card-in rounded-2xl motion-reduce:animate-none", children: [_jsxs(CardHeader, { className: "gap-0.5 px-4 pt-3.5 sm:px-4 sm:pt-3.5", children: [status === "pending" ? _jsx("p", { className: "text-xs font-medium text-muted-foreground", children: pendingLabel }) : null, _jsx(CardTitle, { className: "text-[0.9375rem] leading-snug", children: title })] }), details.length ? (_jsx(CardContent, { className: "px-4 py-3 sm:px-4 sm:py-3 [[data-slot=card-header]+&]:pt-2", children: _jsx("dl", { className: "grid grid-cols-[minmax(0,auto)_minmax(0,1fr)] gap-x-4 gap-y-1 text-sm", children: details.map((row) => (_jsxs("div", { className: "contents", children: [_jsx("dt", { className: "text-muted-foreground", children: row.label }), _jsx("dd", { className: "break-words whitespace-pre-wrap", children: row.value })] }, row.label))) }) })) : (_jsx("div", { "aria-hidden": true, className: "h-3" })), _jsx(CardFooter, { className: "justify-start px-4 py-2.5 sm:px-4", children: badge ? (_jsx(Badge, { tone: badge.tone, children: status === "failed" && result ? `${badge.label} : ${result}` : badge.label })) : (_jsxs("div", { className: "flex flex-wrap gap-2", children: [_jsxs(Button, { size: "sm", isLoading: confirming, disabled: cancelling, onClick: onConfirm, children: [_jsx(HugeiconsIcon, { icon: CheckmarkCircle02Icon, "data-icon": "inline-start" }), confirmLabel] }), _jsxs(Button, { size: "sm", variant: "ghost", isLoading: cancelling, disabled: confirming, onClick: onCancel, children: [_jsx(HugeiconsIcon, { icon: Cancel01Icon, "data-icon": "inline-start" }), cancelLabel] })] })) })] }));
46
47
  }
47
48
  /** Des demandes d'exemple, pour une conversation vide : un clic remplit la saisie. */
48
49
  export function AssistantExamples({ examples, onPick, disabled = false, label = "Par exemple :", }) {
@@ -0,0 +1,157 @@
1
+ import { type IconSvgElement } from "@hugeicons/react";
2
+ import { type ReactNode } from "react";
3
+ import { type AssistantActionStatus, type AssistantTool } from "./assistant-chat.tsx";
4
+ /** État de l'assistant pour l'organisation (`readStatus`). */
5
+ export type AssistantStatus = {
6
+ ready: boolean;
7
+ ownKey: {
8
+ hint: string;
9
+ } | null;
10
+ credits: {
11
+ used: number;
12
+ limit: number;
13
+ };
14
+ };
15
+ export type AssistantThreadSummary = {
16
+ _id: string;
17
+ title: string;
18
+ updatedAt: number;
19
+ };
20
+ export type AssistantMessageStatus = "pending" | "streaming" | "done" | "error";
21
+ export type AssistantMessage = {
22
+ _id: string;
23
+ role: "user" | "assistant";
24
+ text: string;
25
+ status: AssistantMessageStatus;
26
+ tools: ReadonlyArray<AssistantTool>;
27
+ };
28
+ export type AssistantAction = {
29
+ _id: string;
30
+ messageId: string;
31
+ summary: string;
32
+ details?: ReadonlyArray<{
33
+ label: string;
34
+ value: string;
35
+ }>;
36
+ status: AssistantActionStatus;
37
+ result?: string | null;
38
+ };
39
+ /** Une conversation ouverte (`readThread`). */
40
+ export type AssistantThread = {
41
+ /** L'historique a atteint sa taille maximale : une nouvelle conversation s'impose. */
42
+ full?: boolean;
43
+ messages: ReadonlyArray<AssistantMessage>;
44
+ actions: ReadonlyArray<AssistantAction>;
45
+ };
46
+ /** La page ouverte, que l'assistant prend comme sujet tant que la personne ne la retire pas. */
47
+ export type AssistantSubject = {
48
+ /** « Campagne « Octobre » », « Déploiement abc123 ». */
49
+ label: string;
50
+ icon?: IconSvgElement;
51
+ attached: boolean;
52
+ onAttachedChange: (attached: boolean) => void;
53
+ /** Bouton pour la rattacher : « Parler de ce déploiement ». */
54
+ attachLabel: string;
55
+ };
56
+ /** Une demande venue d'un bouton de la page (« Écrire avec l'assistant ») : part une seule fois par `nonce`. */
57
+ export type AssistantRequest = {
58
+ prompt?: string;
59
+ nonce: number;
60
+ };
61
+ export type AssistantLabels = {
62
+ welcomeTitle: string;
63
+ welcomeDescription: string;
64
+ notReadyTitle: string;
65
+ notReadyDescription: string;
66
+ exhaustedTitle: string;
67
+ exhaustedDescription: string;
68
+ placeholder: string;
69
+ placeholderBusy: string;
70
+ composerLabel: string;
71
+ history: string;
72
+ noHistory: string;
73
+ newThread: string;
74
+ deleteThread: string;
75
+ deleteConfirm: string;
76
+ deleteYes: string;
77
+ deleteNo: string;
78
+ loadError: string;
79
+ full: string;
80
+ sendError: string;
81
+ creditsLeft: (remaining: number) => string;
82
+ ownKey: (hint: string) => string;
83
+ notReadyShort: string;
84
+ detach: string;
85
+ };
86
+ /** Tutoiement de la console ; un produit qui vouvoie (clients de Portal) remplace ce qu'il faut. */
87
+ export declare const ASSISTANT_LABELS: AssistantLabels;
88
+ /** Le message d'une erreur Convex (`ConvexError` avec un texte) ; sinon `fallback`. */
89
+ export declare function assistantErrorText(error: unknown, fallback: string): string;
90
+ /**
91
+ * Un lien écrit par l'assistant. Un chemin de l'application (`/…`) reste un lien interne ; une
92
+ * adresse `https:` s'ouvre dans un nouvel onglet, sans référent ni accès à la page, avec son domaine
93
+ * affiché à côté du texte (un texte trompeur ne cache pas la destination) ; tout le reste
94
+ * (`javascript:`, `http:`, `data:`…) devient du texte. À passer au rendu Markdown du produit
95
+ * (`components={{ a: AssistantLink }}`) ; `renderInternal` pour le lien du routeur.
96
+ */
97
+ export declare function AssistantLink({ href, children, renderInternal, }: {
98
+ href?: string | undefined;
99
+ children?: ReactNode;
100
+ renderInternal?: (href: string, children: ReactNode) => ReactNode;
101
+ }): React.JSX.Element;
102
+ /** Le rendu par défaut : texte brut en paragraphes, adresses https en liens sûrs. Aucun HTML. */
103
+ export declare function renderPlainText(text: string): ReactNode;
104
+ /** La ligne sous la barre : crédits restants, ou la clé de l'organisation. */
105
+ export declare function AssistantCredits({ status, labels, }: {
106
+ status: AssistantStatus | undefined;
107
+ labels?: Pick<AssistantLabels, "creditsLeft" | "ownKey" | "notReadyShort">;
108
+ }): React.JSX.Element;
109
+ /** Les conversations précédentes et « Nouvelle conversation ». */
110
+ export declare function AssistantHistory({ threads, threadId, onThreadChange, now, labels, }: {
111
+ threads: ReadonlyArray<AssistantThreadSummary> | undefined;
112
+ threadId: string | null;
113
+ onThreadChange: (threadId: string | null) => void;
114
+ now?: number;
115
+ labels?: Pick<AssistantLabels, "history" | "noHistory" | "newThread">;
116
+ }): React.JSX.Element;
117
+ /** La page ouverte en pastille au-dessus de la saisie, ou le lien pour la rattacher. */
118
+ export declare function AssistantSubjectChip({ subject, labels, }: {
119
+ subject: AssistantSubject;
120
+ labels?: Pick<AssistantLabels, "detach">;
121
+ }): React.JSX.Element;
122
+ export type AssistantViewProps = {
123
+ /** `undefined` pendant le chargement. */
124
+ status: AssistantStatus | undefined;
125
+ threads: ReadonlyArray<AssistantThreadSummary> | undefined;
126
+ /** Conversation ouverte ; `null` : une nouvelle. */
127
+ threadId: string | null;
128
+ onThreadChange: (threadId: string | null) => void;
129
+ /** La conversation ouverte ; `undefined` pendant son chargement, `null` si elle ne se lit pas. */
130
+ thread: AssistantThread | null | undefined;
131
+ /**
132
+ * Le texte d'une réponse, rendu par le produit (Markdown avec `AssistantLink` pour les liens,
133
+ * sans image). Par défaut : texte brut, paragraphes, adresses https en liens sûrs.
134
+ */
135
+ renderText?: (text: string) => ReactNode;
136
+ /** Envoie la demande ; une erreur remet le texte dans la saisie et s'affiche au-dessus. */
137
+ onSend: (text: string) => Promise<void>;
138
+ onConfirm: (actionId: string) => Promise<void>;
139
+ onCancel: (actionId: string) => Promise<void>;
140
+ onDeleteThread?: (threadId: string) => Promise<void>;
141
+ examples?: ReadonlyArray<string>;
142
+ /** Remplace le titre et le texte d'accueil (une page ouverte appelle un autre accueil). */
143
+ welcome?: {
144
+ title?: string;
145
+ description?: ReactNode;
146
+ };
147
+ /** Sous l'état « non branché » ou « crédits épuisés » : un lien vers les réglages, pour un admin. */
148
+ setup?: ReactNode;
149
+ subject?: AssistantSubject | null;
150
+ request?: AssistantRequest | null;
151
+ labels?: Partial<AssistantLabels>;
152
+ /** Instant de référence des dates relatives (tests, captures). */
153
+ now?: number;
154
+ className?: string;
155
+ };
156
+ /** Le panneau de l'assistant, prêt pour la colonne de `AppShell`. */
157
+ export declare function AssistantView({ status, threads, threadId, onThreadChange, thread, renderText, onSend, onConfirm, onCancel, onDeleteThread, examples, welcome, setup, subject, request, labels: overrides, now, className, }: AssistantViewProps): React.JSX.Element;
@@ -0,0 +1,232 @@
1
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import Add01Icon from "@hugeicons/core-free-icons/Add01Icon";
3
+ import AiMagicIcon from "@hugeicons/core-free-icons/AiMagicIcon";
4
+ import Alert02Icon from "@hugeicons/core-free-icons/Alert02Icon";
5
+ import Cancel01Icon from "@hugeicons/core-free-icons/Cancel01Icon";
6
+ import Clock01Icon from "@hugeicons/core-free-icons/Clock01Icon";
7
+ import Delete02Icon from "@hugeicons/core-free-icons/Delete02Icon";
8
+ import { HugeiconsIcon } from "@hugeicons/react";
9
+ import { useEffect, useEffectEvent, useRef, useState } from "react";
10
+ import { AssistantActionCard, AssistantComposer, AssistantConversation, AssistantExamples, AssistantReply, AssistantUserMessage, } from "./assistant-chat.js";
11
+ import { Button } from "./button.js";
12
+ import { cn } from "./cn.js";
13
+ import { DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuTrigger, } from "./dropdown-menu.js";
14
+ import { formatRelative } from "./relative-time.js";
15
+ import { Spinner } from "./spinner.js";
16
+ /** Tutoiement de la console ; un produit qui vouvoie (clients de Portal) remplace ce qu'il faut. */
17
+ export const ASSISTANT_LABELS = {
18
+ welcomeTitle: "Qu'est-ce que je fais pour toi ?",
19
+ welcomeDescription: "Je lis ce que tu vois dans l'application et je t'aide à t'y retrouver. Je te demande toujours avant de modifier ou d'envoyer quoi que ce soit.",
20
+ notReadyTitle: "L'assistant n'est pas encore branché",
21
+ notReadyDescription: "Il manque une clé pour le modèle. Un administrateur peut l'ajouter dans les réglages.",
22
+ exhaustedTitle: "Les crédits du mois sont utilisés",
23
+ exhaustedDescription: "Le compteur repart le 1er du mois. Un administrateur peut aussi ajouter la clé de l'organisation dans les réglages.",
24
+ placeholder: "Demande-moi quelque chose",
25
+ placeholderBusy: "L'assistant répond…",
26
+ composerLabel: "Message pour l'assistant",
27
+ history: "Conversations précédentes",
28
+ noHistory: "Aucune conversation pour l'instant",
29
+ newThread: "Nouvelle conversation",
30
+ deleteThread: "Effacer cette conversation",
31
+ deleteConfirm: "Effacer pour de bon ?",
32
+ deleteYes: "Effacer",
33
+ deleteNo: "Garder",
34
+ loadError: "Cette conversation ne s'affiche pas. Réessaie dans un instant.",
35
+ full: "Cette conversation est pleine. Ouvre une nouvelle conversation pour continuer.",
36
+ sendError: "Le message n'est pas parti. Réessaie dans un instant.",
37
+ creditsLeft: (remaining) => remaining <= 0
38
+ ? "Plus de crédits ce mois-ci"
39
+ : `${remaining} crédit${remaining > 1 ? "s" : ""} restant${remaining > 1 ? "s" : ""} ce mois-ci`,
40
+ ownKey: (hint) => `Clé de l'organisation ••••${hint}`,
41
+ notReadyShort: "Pas encore branché",
42
+ detach: "Ne plus parler de cette page",
43
+ };
44
+ /** Le message d'une erreur Convex (`ConvexError` avec un texte) ; sinon `fallback`. */
45
+ export function assistantErrorText(error, fallback) {
46
+ if (typeof error === "object" && error !== null && "data" in error) {
47
+ const data = error.data;
48
+ if (typeof data === "string" && data.trim())
49
+ return data;
50
+ if (typeof data === "object" && data !== null && "message" in data) {
51
+ const message = data.message;
52
+ if (typeof message === "string" && message.trim())
53
+ return message;
54
+ }
55
+ }
56
+ return fallback;
57
+ }
58
+ /**
59
+ * Un lien écrit par l'assistant. Un chemin de l'application (`/…`) reste un lien interne ; une
60
+ * adresse `https:` s'ouvre dans un nouvel onglet, sans référent ni accès à la page, avec son domaine
61
+ * affiché à côté du texte (un texte trompeur ne cache pas la destination) ; tout le reste
62
+ * (`javascript:`, `http:`, `data:`…) devient du texte. À passer au rendu Markdown du produit
63
+ * (`components={{ a: AssistantLink }}`) ; `renderInternal` pour le lien du routeur.
64
+ */
65
+ export function AssistantLink({ href, children, renderInternal, }) {
66
+ const value = (href ?? "").trim();
67
+ const className = "font-medium underline underline-offset-2";
68
+ if (value.startsWith("/") && !value.startsWith("//") && !value.startsWith("/\\")) {
69
+ return renderInternal ? (_jsx(_Fragment, { children: renderInternal(value, children) })) : (_jsx("a", { href: value, className: className, children: children }));
70
+ }
71
+ let url = null;
72
+ try {
73
+ url = new URL(value);
74
+ }
75
+ catch {
76
+ url = null;
77
+ }
78
+ if (!url || url.protocol !== "https:" || url.username || url.password)
79
+ return _jsx("span", { children: children });
80
+ return (_jsxs("a", { href: url.href, target: "_blank", rel: "noopener noreferrer nofollow", className: className, children: [children, _jsxs("span", { className: "ml-1 text-xs font-normal text-muted-foreground no-underline", children: ["(", url.hostname, ")"] })] }));
81
+ }
82
+ const URL_IN_TEXT = /(https:\/\/[^\s<>"')]+)/g;
83
+ /** Le rendu par défaut : texte brut en paragraphes, adresses https en liens sûrs. Aucun HTML. */
84
+ export function renderPlainText(text) {
85
+ return text.split(/\n{2,}/).map((paragraph, i) => (_jsx("p", { className: "my-2 whitespace-pre-wrap first:mt-0 last:mb-0", children: paragraph.split(URL_IN_TEXT).map((part, j) => j % 2 === 1 ? (_jsx(AssistantLink, { href: part, children: part }, j)) : (part)) }, i)));
86
+ }
87
+ function remainingCredits(status) {
88
+ return Math.max(0, Math.floor(status.credits.limit - status.credits.used));
89
+ }
90
+ /** La ligne sous la barre : crédits restants, ou la clé de l'organisation. */
91
+ export function AssistantCredits({ status, labels = ASSISTANT_LABELS, }) {
92
+ return (_jsx("p", { "data-slot": "assistant-credits", className: "min-w-0 truncate text-xs text-muted-foreground", "aria-live": "polite", children: status === undefined
93
+ ? " "
94
+ : status.ownKey
95
+ ? labels.ownKey(status.ownKey.hint)
96
+ : !status.ready
97
+ ? labels.notReadyShort
98
+ : labels.creditsLeft(remainingCredits(status)) }));
99
+ }
100
+ /** Les conversations précédentes et « Nouvelle conversation ». */
101
+ export function AssistantHistory({ threads, threadId, onThreadChange, now, labels = ASSISTANT_LABELS, }) {
102
+ return (_jsxs("div", { className: "flex shrink-0 items-center gap-0.5", children: [_jsxs(DropdownMenu, { children: [_jsx(DropdownMenuTrigger, { render: _jsx(Button, { variant: "ghost", size: "icon-sm", "aria-label": labels.history, title: labels.history, disabled: !threads?.length }), children: _jsx(HugeiconsIcon, { icon: Clock01Icon, "aria-hidden": true }) }), _jsx(DropdownMenuContent, { align: "end", className: "w-72 max-w-[calc(100vw-2rem)]", children: _jsxs(DropdownMenuGroup, { children: [_jsx(DropdownMenuLabel, { children: labels.history }), threads?.length ? (threads.map((thread) => (_jsxs(DropdownMenuItem, { onClick: () => onThreadChange(thread._id), "aria-current": thread._id === threadId ? "true" : undefined, className: "aria-[current]:font-medium", children: [_jsx("span", { className: "min-w-0 flex-1 truncate", children: thread.title }), _jsx("span", { className: "shrink-0 text-xs text-muted-foreground", children: formatRelative(thread.updatedAt, now) })] }, thread._id)))) : (_jsx("p", { className: "px-2 py-1.5 text-sm text-muted-foreground", children: labels.noHistory }))] }) })] }), _jsx(Button, { variant: "ghost", size: "icon-sm", "aria-label": labels.newThread, title: labels.newThread, disabled: threadId === null, onClick: () => onThreadChange(null), children: _jsx(HugeiconsIcon, { icon: Add01Icon, "aria-hidden": true }) })] }));
103
+ }
104
+ /** Un état sans conversation : accueil, non branché, crédits épuisés. */
105
+ function AssistantState({ title, description, tone = "neutral", children, }) {
106
+ return (_jsxs("div", { "data-slot": "assistant-state", className: "grid gap-4 py-4", children: [_jsx("span", { "aria-hidden": true, className: cn("grid size-10 place-items-center rounded-2xl", tone === "warning" ? "bg-status-paused/15 text-status-paused-ink" : "bg-muted text-foreground"), children: _jsx(HugeiconsIcon, { icon: tone === "warning" ? Alert02Icon : AiMagicIcon, strokeWidth: 1.8, className: "size-5" }) }), _jsxs("div", { className: "grid gap-1.5", children: [_jsx("p", { className: "font-heading text-lg leading-snug font-semibold text-balance", children: title }), _jsx("div", { className: "text-sm text-pretty text-muted-foreground", children: description })] }), children] }));
107
+ }
108
+ /** La page ouverte en pastille au-dessus de la saisie, ou le lien pour la rattacher. */
109
+ export function AssistantSubjectChip({ subject, labels = ASSISTANT_LABELS, }) {
110
+ if (!subject.attached) {
111
+ return (_jsx("button", { type: "button", onClick: () => subject.onAttachedChange(true), className: "touch-target w-fit rounded-lg text-xs text-muted-foreground underline-offset-2 outline-none hover:text-foreground hover:underline focus-visible:ring-2 focus-visible:ring-ring/50", children: subject.attachLabel }));
112
+ }
113
+ return (_jsxs("span", { "data-slot": "assistant-subject", className: "flex w-fit max-w-full min-w-0 soft-in items-center gap-1.5 rounded-full bg-muted py-1 pr-1 pl-2.5 text-xs font-medium motion-reduce:animate-none", children: [subject.icon ? _jsx(HugeiconsIcon, { icon: subject.icon, "aria-hidden": true, className: "size-3.5 shrink-0" }) : null, _jsx("span", { className: "truncate", children: subject.label }), _jsx("button", { type: "button", "aria-label": labels.detach, title: labels.detach, onClick: () => subject.onAttachedChange(false), className: "grid size-6 shrink-0 place-items-center rounded-full text-muted-foreground outline-none hover:bg-foreground/[0.08] hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50", children: _jsx(HugeiconsIcon, { icon: Cancel01Icon, "aria-hidden": true, className: "size-3" }) })] }));
114
+ }
115
+ function DeleteThread({ onDelete, labels, }) {
116
+ const [asking, setAsking] = useState(false);
117
+ const [busy, setBusy] = useState(false);
118
+ if (!asking) {
119
+ return (_jsxs("button", { type: "button", onClick: () => setAsking(true), className: "touch-target flex w-fit items-center gap-1 rounded-lg text-xs text-muted-foreground outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50", children: [_jsx(HugeiconsIcon, { icon: Delete02Icon, "aria-hidden": true, className: "size-3.5" }), labels.deleteThread] }));
120
+ }
121
+ return (_jsxs("div", { role: "group", "aria-label": labels.deleteThread, className: "flex items-center gap-2 text-xs", children: [_jsx("span", { className: "text-muted-foreground", children: labels.deleteConfirm }), _jsx(Button, { size: "xs", variant: "destructive", isLoading: busy, onClick: async () => {
122
+ setBusy(true);
123
+ try {
124
+ await onDelete();
125
+ }
126
+ finally {
127
+ setBusy(false);
128
+ setAsking(false);
129
+ }
130
+ }, children: labels.deleteYes }), _jsx(Button, { size: "xs", variant: "ghost", disabled: busy, onClick: () => setAsking(false), children: labels.deleteNo })] }));
131
+ }
132
+ /** Le panneau de l'assistant, prêt pour la colonne de `AppShell`. */
133
+ export function AssistantView({ status, threads, threadId, onThreadChange, thread, renderText = renderPlainText, onSend, onConfirm, onCancel, onDeleteThread, examples = [], welcome, setup, subject, request, labels: overrides, now, className, }) {
134
+ const labels = { ...ASSISTANT_LABELS, ...overrides };
135
+ const [draft, setDraft] = useState("");
136
+ const [sending, setSending] = useState(false);
137
+ const [sendError, setSendError] = useState(null);
138
+ const [actionBusy, setActionBusy] = useState(null);
139
+ const scroller = useRef(null);
140
+ const messages = threadId && thread ? thread.messages : [];
141
+ const last = messages.at(-1);
142
+ const answering = last?.status === "pending" || last?.status === "streaming";
143
+ const busy = sending || answering;
144
+ const exhausted = Boolean(status && status.ready && !status.ownKey && remainingCredits(status) <= 0);
145
+ const full = Boolean(threadId && thread?.full);
146
+ const blocked = status === undefined || !status.ready || exhausted || full;
147
+ // Le fil suit la réponse en cours, sauf si la personne remonte pour relire.
148
+ useEffect(() => {
149
+ const el = scroller.current;
150
+ if (!el)
151
+ return;
152
+ if (el.scrollHeight - el.scrollTop - el.clientHeight < 160)
153
+ el.scrollTo({ top: el.scrollHeight });
154
+ }, [thread]);
155
+ async function submit(text) {
156
+ const value = text.trim();
157
+ if (!value || busy || blocked)
158
+ return;
159
+ setSending(true);
160
+ setSendError(null);
161
+ setDraft("");
162
+ try {
163
+ await onSend(value);
164
+ requestAnimationFrame(() => {
165
+ const el = scroller.current;
166
+ if (el)
167
+ el.scrollTo({ top: el.scrollHeight });
168
+ });
169
+ }
170
+ catch (error) {
171
+ setDraft(value);
172
+ setSendError(assistantErrorText(error, labels.sendError));
173
+ }
174
+ finally {
175
+ setSending(false);
176
+ }
177
+ }
178
+ async function act(id, kind) {
179
+ setActionBusy({ id, kind });
180
+ try {
181
+ await (kind === "confirm" ? onConfirm(id) : onCancel(id));
182
+ }
183
+ catch (error) {
184
+ setSendError(assistantErrorText(error, labels.sendError));
185
+ }
186
+ finally {
187
+ setActionBusy(null);
188
+ }
189
+ }
190
+ // Une demande venue de la page part une seule fois ; sans texte, elle met le curseur dans la saisie.
191
+ const handled = useRef(null);
192
+ const onRequest = useEffectEvent((next) => {
193
+ if (handled.current === next.nonce)
194
+ return;
195
+ handled.current = next.nonce;
196
+ if (next.prompt)
197
+ void submit(next.prompt);
198
+ });
199
+ useEffect(() => {
200
+ // oxlint-disable-next-line react/set-state-in-effect -- la demande est un clic sur la page, transmis par prop : exécutée une seule fois par nonce.
201
+ if (request)
202
+ onRequest(request);
203
+ }, [request]);
204
+ let body;
205
+ if (status === undefined) {
206
+ body = (_jsx("div", { className: "grid place-items-center py-16", children: _jsx(Spinner, { size: 5, label: "Chargement" }) }));
207
+ }
208
+ else if (!status.ready) {
209
+ body = (_jsx(AssistantState, { title: labels.notReadyTitle, description: labels.notReadyDescription, tone: "warning", children: setup }));
210
+ }
211
+ else if (!threadId) {
212
+ body = exhausted ? (_jsx(AssistantState, { title: labels.exhaustedTitle, description: labels.exhaustedDescription, tone: "warning", children: setup })) : (_jsx(AssistantState, { title: welcome?.title ?? labels.welcomeTitle, description: welcome?.description ?? labels.welcomeDescription, children: examples.length ? _jsx(AssistantExamples, { examples: examples, onPick: (e) => void submit(e) }) : null }));
213
+ }
214
+ else if (thread === undefined) {
215
+ body = (_jsx("div", { className: "grid place-items-center py-16", children: _jsx(Spinner, { size: 5, label: "Chargement de la conversation" }) }));
216
+ }
217
+ else if (thread === null) {
218
+ body = (_jsx("p", { role: "alert", className: "py-8 text-sm text-destructive", children: labels.loadError }));
219
+ }
220
+ else {
221
+ body = (_jsx(AssistantConversation, { className: "gap-5", children: thread.messages.map((message) => message.role === "user" ? (_jsx(AssistantUserMessage, { children: message.text }, message._id)) : (_jsx(AssistantReply, { tools: message.tools, waiting: !message.text && (message.status === "pending" || message.status === "streaming"), error: message.status === "error", actions: thread.actions
222
+ .filter((action) => action.messageId === message._id)
223
+ .map((action) => (_jsx(AssistantActionCard, { title: action.summary, details: action.details ?? [], status: action.status, result: action.result ?? null, confirming: actionBusy?.id === action._id && actionBusy.kind === "confirm", cancelling: actionBusy?.id === action._id && actionBusy.kind === "cancel", onConfirm: () => void act(action._id, "confirm"), onCancel: () => void act(action._id, "cancel") }, action._id))), children: message.text ? renderText(message.text) : null }, message._id))) }));
224
+ }
225
+ return (_jsxs("div", { "data-slot": "assistant-view", className: cn("flex min-h-0 flex-1 flex-col", className), children: [_jsxs("div", { className: "flex min-h-11 shrink-0 items-center gap-2 px-4 xl:pr-2 xl:pl-5", children: [_jsx("div", { className: "min-w-0 flex-1", children: _jsx(AssistantCredits, { status: status, labels: labels }) }), _jsx(AssistantHistory, { threads: threads, threadId: threadId, onThreadChange: (id) => {
226
+ setSendError(null);
227
+ onThreadChange(id);
228
+ }, labels: labels, ...(now === undefined ? {} : { now }) })] }), _jsx("div", { ref: scroller, "data-slot": "assistant-scroller", className: "min-h-0 flex-1 overflow-y-auto overscroll-contain px-4 pt-2 pb-4 xl:pr-3 xl:pl-5", children: body }), _jsxs("div", { className: "grid shrink-0 gap-2 border-t border-foreground/5 px-4 pt-3 pb-[max(env(safe-area-inset-bottom),0.75rem)] xl:pr-3 xl:pl-5", children: [sendError ? (_jsx("p", { role: "alert", className: "text-sm text-destructive", children: sendError })) : null, full ? _jsx("p", { className: "text-sm text-muted-foreground", children: labels.full }) : null, subject ? _jsx(AssistantSubjectChip, { subject: subject, labels: labels }) : null, _jsx(AssistantComposer, { value: draft, onValueChange: setDraft, onSubmit: () => void submit(draft), disabled: blocked, busy: answering, sending: sending, label: labels.composerLabel, placeholder: answering ? labels.placeholderBusy : labels.placeholder, hint: null }), threadId && onDeleteThread && thread ? (_jsx(DeleteThread, { labels: labels, onDelete: async () => {
229
+ await onDeleteThread(threadId);
230
+ onThreadChange(null);
231
+ } })) : null] })] }));
232
+ }
@@ -27,6 +27,13 @@ export function niceScale(max, ticks = 4) {
27
27
  const step = nice * magnitude;
28
28
  return { max: Math.ceil(max / step) * step, step };
29
29
  }
30
+ /** Lignes lues par les lecteurs d'écran au plus : au-delà, un échantillon régulier, premier et dernier inclus. */
31
+ const SR_SAMPLE_SIZE = 60;
32
+ function sampleIndices(n) {
33
+ if (n <= SR_SAMPLE_SIZE)
34
+ return Array.from({ length: n }, (_, i) => i);
35
+ return Array.from({ length: SR_SAMPLE_SIZE }, (_, k) => Math.round((k * (n - 1)) / (SR_SAMPLE_SIZE - 1)));
36
+ }
30
37
  /**
31
38
  * Série temporelle en SVG, sans bibliothèque : lignes (aire sous la courbe pour une série seule)
32
39
  * ou barres empilées. Le SVG s'étire à la largeur de son conteneur ; les traits gardent 2 px
@@ -88,5 +95,5 @@ export function TimeChart({ timestamps, series, kind = "line", height = 200, com
88
95
  return v > 0 ? (_jsx("rect", { x: i + 0.15, y: base, width: 0.7, height: h, fill: color(si), opacity: (active === null || active === i ? 1 : 0.55) * (i === incompleteIndex ? 0.5 : 1) }, `${s.key}-${i}`)) : null;
89
96
  });
90
97
  })
91
- : series.map((s, si) => (_jsxs("g", { children: [series.length === 1 ? (_jsx("path", { d: areaPath(s.values, scale.max), fill: color(si), opacity: 0.1 })) : null, _jsx("path", { d: linePath(incompleteIndex < 0 ? s.values : s.values.map((v, i) => (i === incompleteIndex ? null : v)), scale.max), fill: "none", stroke: color(si), strokeWidth: 2, strokeLinejoin: "round", strokeLinecap: "round", vectorEffect: "non-scaling-stroke" }), incompleteIndex >= 0 ? (_jsx("path", { "data-slot": "time-chart-incomplete", d: linePath(s.values.map((v, i) => (i >= incompleteIndex - 1 ? v : null)), scale.max), fill: "none", stroke: color(si), strokeWidth: 2, strokeDasharray: "3 4", strokeLinecap: "round", vectorEffect: "non-scaling-stroke" })) : null] }, s.key))), active !== null ? (_jsx("line", { x1: active + 0.5, x2: active + 0.5, y1: 0, y2: 100, vectorEffect: "non-scaling-stroke", className: "stroke-foreground/25", strokeWidth: 1 })) : null] }), active !== null && activeTime !== undefined ? (_jsxs("div", { "data-slot": "time-chart-tooltip", className: cn("pointer-events-none absolute top-0 z-10 grid min-w-36 gap-1 rounded-xl bg-popover px-3 py-2 text-xs shadow-lg shadow-black/10 [--popover:var(--floating)]", (active + 0.5) / n > 0.6 ? "-translate-x-[calc(100%+0.75rem)]" : "translate-x-3"), style: { left: `${((active + 0.5) / n) * 100}%` }, children: [_jsxs("p", { className: "font-medium", children: [formatTime(activeTime), active === incompleteIndex ? (_jsx("span", { className: "ml-1.5 font-normal text-muted-foreground", children: "En cours" })) : null] }), series.map((s, si) => (_jsxs("p", { className: "flex items-center gap-2", children: [_jsx("span", { "aria-hidden": true, className: "size-2 shrink-0 rounded-[2px]", style: { background: color(si) } }), _jsx("span", { className: "flex-1 text-muted-foreground", children: s.label }), _jsx("span", { className: "font-medium tabular-nums", children: s.values[active] === null ? "-" : formatValue(s.values[active] ?? 0) })] }, s.key)))] })) : null] }), xLabels.length > 0 ? (_jsx("div", { "aria-hidden": true, className: "relative h-4 text-[11px] text-muted-foreground tabular-nums", children: xLabels.map((i, k) => (_jsx("span", { className: cn("absolute", k === 0 ? "left-0" : k === xLabels.length - 1 ? "right-0" : "-translate-x-1/2"), style: k === 0 || k === xLabels.length - 1 ? undefined : { left: `${((i + 0.5) / n) * 100}%` }, children: timestamps[i] !== undefined ? formatTime(timestamps[i]) : null }, i))) })) : null] })] }), _jsxs("table", { className: "sr-only", children: [_jsx("caption", { children: label }), _jsx("thead", { children: _jsxs("tr", { children: [_jsx("th", { scope: "col", children: "Date" }), series.map((s) => (_jsx("th", { scope: "col", children: s.label }, s.key)))] }) }), _jsx("tbody", { children: timestamps.map((t, i) => (_jsxs("tr", { children: [_jsxs("th", { scope: "row", children: [formatTime(t), i === incompleteIndex ? " (en cours)" : ""] }), series.map((s) => (_jsx("td", { children: s.values[i] === null ? "-" : formatValue(s.values[i] ?? 0) }, s.key)))] }, t))) })] })] }));
98
+ : series.map((s, si) => (_jsxs("g", { children: [series.length === 1 ? (_jsx("path", { d: areaPath(s.values, scale.max), fill: color(si), opacity: 0.1 })) : null, _jsx("path", { d: linePath(incompleteIndex < 0 ? s.values : s.values.map((v, i) => (i === incompleteIndex ? null : v)), scale.max), fill: "none", stroke: color(si), strokeWidth: 2, strokeLinejoin: "round", strokeLinecap: "round", vectorEffect: "non-scaling-stroke" }), incompleteIndex >= 0 ? (_jsx("path", { "data-slot": "time-chart-incomplete", d: linePath(s.values.map((v, i) => (i >= incompleteIndex - 1 ? v : null)), scale.max), fill: "none", stroke: color(si), strokeWidth: 2, strokeDasharray: "3 4", strokeLinecap: "round", vectorEffect: "non-scaling-stroke" })) : null] }, s.key))), active !== null ? (_jsx("line", { x1: active + 0.5, x2: active + 0.5, y1: 0, y2: 100, vectorEffect: "non-scaling-stroke", className: "stroke-foreground/25", strokeWidth: 1 })) : null] }), active !== null && activeTime !== undefined ? (_jsxs("div", { "data-slot": "time-chart-tooltip", className: cn("pointer-events-none absolute top-0 z-10 grid min-w-36 gap-1 rounded-xl bg-popover px-3 py-2 text-xs shadow-lg shadow-black/10 [--popover:var(--floating)]", (active + 0.5) / n > 0.6 ? "-translate-x-[calc(100%+0.75rem)]" : "translate-x-3"), style: { left: `${((active + 0.5) / n) * 100}%` }, children: [_jsxs("p", { className: "font-medium", children: [formatTime(activeTime), active === incompleteIndex ? (_jsx("span", { className: "ml-1.5 font-normal text-muted-foreground", children: "En cours" })) : null] }), series.map((s, si) => (_jsxs("p", { className: "flex items-center gap-2", children: [_jsx("span", { "aria-hidden": true, className: "size-2 shrink-0 rounded-[2px]", style: { background: color(si) } }), _jsx("span", { className: "flex-1 text-muted-foreground", children: s.label }), _jsx("span", { className: "font-medium tabular-nums", children: s.values[active] === null ? "-" : formatValue(s.values[active] ?? 0) })] }, s.key)))] })) : null] }), xLabels.length > 0 ? (_jsx("div", { "aria-hidden": true, className: "relative h-4 text-[11px] text-muted-foreground tabular-nums", children: xLabels.map((i, k) => (_jsx("span", { className: cn("absolute", k === 0 ? "left-0" : k === xLabels.length - 1 ? "right-0" : "-translate-x-1/2"), style: k === 0 || k === xLabels.length - 1 ? undefined : { left: `${((i + 0.5) / n) * 100}%` }, children: timestamps[i] !== undefined ? formatTime(timestamps[i]) : null }, i))) })) : null] })] }), _jsx("div", { className: "sr-only", children: _jsxs("table", { children: [_jsx("caption", { children: n > SR_SAMPLE_SIZE ? `${label} (${n} mesures, échantillon de ${SR_SAMPLE_SIZE})` : label }), _jsx("thead", { children: _jsxs("tr", { children: [_jsx("th", { scope: "col", children: "Date" }), series.map((s) => (_jsx("th", { scope: "col", children: s.label }, s.key)))] }) }), _jsx("tbody", { children: sampleIndices(n).map((i) => (_jsxs("tr", { children: [_jsxs("th", { scope: "row", children: [formatTime(timestamps[i] ?? 0), i === incompleteIndex ? " (en cours)" : ""] }), series.map((s) => (_jsx("td", { children: s.values[i] === null ? "-" : formatValue(s.values[i] ?? 0) }, s.key)))] }, timestamps[i]))) })] }) })] }));
92
99
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hgdc/ui",
3
- "version": "0.30.0",
3
+ "version": "0.31.0",
4
4
  "description": "Interface de la H Collection : jetons de la DA, thèmes, polices et composants.",
5
5
  "license": "UNLICENSED",
6
6
  "homepage": "https://github.com/hugogebel-boop/hgdc-kit/tree/main/packages/ui#readme",