@adecore/agents-react 0.21.2 → 0.22.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.
Files changed (104) hide show
  1. package/dist/agents/model-requirement.d.ts +6 -0
  2. package/dist/agents/model-requirement.js +26 -0
  3. package/dist/chat/chat-client.d.ts +2 -1
  4. package/dist/chat/chat-client.js +2 -0
  5. package/dist/chat/drafts.d.ts +2 -1
  6. package/dist/chat/drafts.js +15 -5
  7. package/dist/chat/logic/picker-entries.d.ts +10 -0
  8. package/dist/chat/logic/picker-entries.js +19 -0
  9. package/dist/chat/logic/timeline.d.ts +5 -0
  10. package/dist/chat/logic/timeline.js +10 -1
  11. package/dist/chat/prompt-hold.d.ts +8 -0
  12. package/dist/chat/prompt-hold.js +16 -0
  13. package/dist/chat/quote.d.ts +4 -0
  14. package/dist/chat/quote.js +19 -0
  15. package/dist/chat/stash.d.ts +8 -2
  16. package/dist/chat/stash.js +21 -5
  17. package/dist/chat/subagent-list.d.ts +7 -1
  18. package/dist/chat/subagent-list.js +13 -1
  19. package/dist/chat/timeline-scroll.d.ts +6 -2
  20. package/dist/chat/timeline-scroll.js +12 -7
  21. package/dist/chat/ui/ChatActivity.js +22 -8
  22. package/dist/chat/ui/Composer.js +103 -19
  23. package/dist/chat/ui/ComposerInput.d.ts +3 -1
  24. package/dist/chat/ui/ComposerInput.js +13 -4
  25. package/dist/chat/ui/Pickers.js +26 -18
  26. package/dist/chat/ui/PromptComposer.d.ts +8 -1
  27. package/dist/chat/ui/PromptComposer.js +18 -6
  28. package/dist/chat/ui/QuoteButton.js +2 -2
  29. package/dist/chat/ui/SubagentControls.d.ts +4 -2
  30. package/dist/chat/ui/SubagentControls.js +12 -8
  31. package/dist/chat/ui/SubagentInfo.d.ts +1 -1
  32. package/dist/chat/ui/SubagentInfo.js +9 -15
  33. package/dist/chat/ui/SubagentStopButton.js +2 -1
  34. package/dist/chat/ui/Timeline.js +24 -3
  35. package/dist/chat/ui/composer/menu-aria.d.ts +10 -0
  36. package/dist/chat/ui/composer/menu-aria.js +18 -0
  37. package/dist/chat/ui/intelligent-ui/UiBlockFrame.js +3 -3
  38. package/dist/chat/ui/intelligent-ui/UiFallbackPart.js +1 -1
  39. package/dist/chat/ui/intelligent-ui/chart-data.d.ts +22 -2
  40. package/dist/chat/ui/intelligent-ui/chart-data.js +83 -19
  41. package/dist/chat/ui/intelligent-ui/renderers/chart.d.ts +1 -1
  42. package/dist/chat/ui/intelligent-ui/renderers/chart.js +99 -35
  43. package/dist/chat/ui/intelligent-ui/renderers/choices.d.ts +1 -1
  44. package/dist/chat/ui/intelligent-ui/renderers/choices.js +8 -2
  45. package/dist/chat/ui/intelligent-ui/renderers/content.js +5 -3
  46. package/dist/chat/ui/intelligent-ui/renderers/inputs.js +9 -4
  47. package/dist/chat/ui/intelligent-ui/renderers/links.js +1 -1
  48. package/dist/chat/ui/intelligent-ui/renderers/text.js +5 -2
  49. package/dist/chat/ui/intelligent-ui/table-data.js +4 -4
  50. package/dist/chat/ui/intelligent-ui/use-truncated.d.ts +1 -0
  51. package/dist/chat/ui/intelligent-ui/use-truncated.js +28 -0
  52. package/dist/chat/ui/quote-selection.d.ts +5 -2
  53. package/dist/chat/ui/quote-selection.js +3 -2
  54. package/dist/chat/ui/rows/MessageRows.js +24 -5
  55. package/dist/chat/ui/rows/Rows.js +1 -1
  56. package/dist/chat/ui/rows/WorkRows.d.ts +3 -1
  57. package/dist/chat/ui/rows/WorkRows.js +4 -4
  58. package/dist/host.d.ts +1 -0
  59. package/dist/host.js +1 -0
  60. package/dist/locales/en/agent-chat.json +39 -10
  61. package/dist/locales/nl/agent-chat.json +39 -10
  62. package/dist/state/chats.d.ts +2 -1
  63. package/dist/state/chats.js +19 -1
  64. package/package.json +29 -4
  65. package/src/agents/model-requirement.ts +36 -0
  66. package/src/chat/chat-client.ts +5 -0
  67. package/src/chat/drafts.ts +27 -7
  68. package/src/chat/logic/picker-entries.ts +25 -0
  69. package/src/chat/logic/timeline.ts +17 -2
  70. package/src/chat/prompt-hold.ts +27 -0
  71. package/src/chat/quote.ts +20 -0
  72. package/src/chat/stash.ts +31 -5
  73. package/src/chat/subagent-list.ts +19 -5
  74. package/src/chat/timeline-scroll.ts +24 -10
  75. package/src/chat/ui/ChatActivity.tsx +35 -9
  76. package/src/chat/ui/Composer.tsx +197 -52
  77. package/src/chat/ui/ComposerInput.tsx +18 -3
  78. package/src/chat/ui/Pickers.tsx +51 -30
  79. package/src/chat/ui/PromptComposer.tsx +37 -8
  80. package/src/chat/ui/QuoteButton.tsx +3 -2
  81. package/src/chat/ui/SubagentControls.tsx +22 -19
  82. package/src/chat/ui/SubagentInfo.tsx +24 -42
  83. package/src/chat/ui/SubagentStopButton.tsx +2 -1
  84. package/src/chat/ui/Timeline.tsx +26 -4
  85. package/src/chat/ui/composer/menu-aria.ts +29 -0
  86. package/src/chat/ui/intelligent-ui/UiBlockFrame.tsx +5 -5
  87. package/src/chat/ui/intelligent-ui/UiFallbackPart.tsx +6 -1
  88. package/src/chat/ui/intelligent-ui/chart-data.ts +106 -20
  89. package/src/chat/ui/intelligent-ui/renderers/chart.tsx +237 -72
  90. package/src/chat/ui/intelligent-ui/renderers/choices.tsx +9 -4
  91. package/src/chat/ui/intelligent-ui/renderers/content.tsx +31 -15
  92. package/src/chat/ui/intelligent-ui/renderers/inputs.tsx +16 -5
  93. package/src/chat/ui/intelligent-ui/renderers/links.tsx +3 -3
  94. package/src/chat/ui/intelligent-ui/renderers/text.tsx +18 -8
  95. package/src/chat/ui/intelligent-ui/table-data.ts +4 -4
  96. package/src/chat/ui/intelligent-ui/use-truncated.ts +33 -0
  97. package/src/chat/ui/quote-selection.ts +6 -4
  98. package/src/chat/ui/rows/MessageRows.tsx +44 -5
  99. package/src/chat/ui/rows/Rows.tsx +3 -1
  100. package/src/chat/ui/rows/WorkRows.tsx +15 -1
  101. package/src/host.ts +3 -0
  102. package/src/locales/en/agent-chat.json +39 -10
  103. package/src/locales/nl/agent-chat.json +39 -10
  104. package/src/state/chats.ts +31 -2
@@ -1,20 +1,18 @@
1
- import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { Fragment, useState } from 'react';
3
- import clsx from 'clsx';
1
+ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Fragment } from 'react';
4
3
  import { useTranslation } from 'react-i18next';
5
- import { ChevronDown } from 'lucide-react';
6
4
  import { entryTimeOf, statusWordOf, subagentFacts, taskIdOf } from '../subagent-list.js';
7
5
  import { useSubagentItem } from '../subagent-view.js';
8
6
  import { StatusIcon } from './ChatActivity.js';
9
- import { Markdown } from './Markdown.js';
10
- import { Icon, useNow } from '@adecore/ui';
7
+ import { SubagentActions, SubagentBreadcrumb } from './SubagentControls.js';
8
+ import { useNow } from '@adecore/ui';
11
9
  import { useModelName } from '../../agents/model-name.js';
12
10
  import { useChatRow } from '../../state/chats.js';
13
11
  import { chatHost } from '../../host.js';
14
12
  import { useChatScope } from '../../scope.js';
15
13
  /*
16
- * What a sub-agent is, over its conversation: its state and time, the model it runs on and what it
17
- * spent, and the task it was given behind a fold. Nothing for a conversation whose row the thread lost.
14
+ * What a sub-agent is, over its conversation: the way down to it, its state and time, the model it runs on
15
+ * and what it spent, and the way out. Only the way down and out for a conversation whose row the thread lost.
18
16
  */
19
17
  export function SubagentInfo({ chatId, toolUseId }) {
20
18
  const { t } = useTranslation('agent-chat');
@@ -24,11 +22,7 @@ export function SubagentInfo({ chatId, toolUseId }) {
24
22
  const task = chatHost().tasks.useTask(id, item === null ? null : taskIdOf(item));
25
23
  const modelName = useModelName(provider, item?.model ?? '');
26
24
  const now = useNow(1000, item?.status === 'running');
27
- const [open, setOpen] = useState(false);
28
- if (item === null) {
29
- return null;
30
- }
31
- const word = statusWordOf(item, task);
32
- const facts = subagentFacts(item, item.model === undefined ? null : modelName);
33
- return (_jsx("section", { "aria-label": t('subagents.info.label'), className: "shrink-0 border-b border-border px-4 py-2", children: _jsxs("div", { className: "chat-column-content flex flex-col gap-2", children: [_jsxs("div", { className: "flex min-w-0 items-center gap-2 text-xs text-text-faint", children: [_jsx(StatusIcon, { word: word }), _jsx("span", { className: "sr-only", children: t(`common.status.${word}`) }), _jsx("span", { className: "shrink-0 text-text-muted tabular-nums", children: entryTimeOf(item, task, now) }), facts.map((fact) => (_jsxs(Fragment, { children: [_jsx("span", { "aria-hidden": "true", children: "\u00B7" }), _jsx("span", { className: "min-w-0 truncate", children: fact })] }, fact))), _jsx("span", { className: "grow" }), item.prompt && (_jsxs("button", { type: "button", className: "flex shrink-0 items-center gap-1.5 text-text-muted hover:text-text", "aria-expanded": open, onClick: () => setOpen((current) => !current), children: [_jsx(Icon, { icon: ChevronDown, size: 12, className: clsx('transition-transform', open && 'rotate-180') }), open ? t('subagents.info.hideTask') : t('subagents.info.showTask')] }))] }), open && item.prompt && (_jsx("div", { className: "max-h-60 overflow-auto rounded-md border border-border bg-surface-raised px-3 py-2 text-xs select-text", children: _jsx(Markdown, { text: item.prompt }) }))] }) }));
25
+ const word = item === null ? null : statusWordOf(item, task);
26
+ const facts = item === null ? [] : subagentFacts(item, item.model === undefined ? null : modelName);
27
+ return (_jsx("section", { "aria-label": t('subagents.info.label'), className: "shrink-0 border-b border-border px-4 py-1.5", children: _jsxs("div", { className: "flex min-w-0 items-center gap-2 text-xs text-text-faint", children: [_jsx(SubagentBreadcrumb, { chatId: chatId, className: "max-w-1/3 shrink-0 font-medium" }), item !== null && word !== null && (_jsxs(_Fragment, { children: [_jsx(StatusIcon, { word: word }), _jsx("span", { className: "sr-only", children: t(`common.status.${word}`) }), _jsx("span", { className: "shrink-0 text-text-muted tabular-nums", children: entryTimeOf(item, task, now) })] })), facts.map((fact) => (_jsxs(Fragment, { children: [_jsx("span", { "aria-hidden": "true", children: "\u00B7" }), _jsx("span", { className: "min-w-0 truncate", children: fact })] }, fact))), _jsx("span", { className: "grow" }), _jsx(SubagentActions, { chatId: chatId })] }) }));
34
28
  }
@@ -19,7 +19,8 @@ export function SubagentStopButton({ chatId, item, size = 'xs', className }) {
19
19
  }
20
20
  const send = () => {
21
21
  void actions.stopSubagent(chatId, item.toolUseId).catch((e) => {
22
- const description = e instanceof Error ? e.message : t('subagents.noAnswer');
22
+ const stale = e instanceof Error && 'code' in e && e.code === 'subagent-stale';
23
+ const description = stale ? t('subagents.stale') : e instanceof Error ? e.message : t('subagents.noAnswer');
23
24
  chatHost().notify({ kind: 'error', title: t('subagents.stopFailed'), description });
24
25
  });
25
26
  };
@@ -37,6 +37,8 @@ import { AgentIcon } from '../../agents/AgentIcon.js';
37
37
  import { useModelName } from '../../agents/model-name.js';
38
38
  import { ContextMenu, EmptyState, ErrorBoundary, Icon, SectionLabel } from '@adecore/ui';
39
39
  const ESTIMATED_ROW_PX = 56;
40
+ // How long a jump waits for a thread that is still loading before it calls the item missing.
41
+ const JUMP_THREAD_WAIT_MS = 8000;
40
42
  /* A jump puts its row at the top and stops following the end, so the reader stays where they landed. */
41
43
  function showRowAtTop(virtualizer, followRef, index) {
42
44
  followRef.current = false;
@@ -347,9 +349,16 @@ export function Timeline({ chatId, composer, overlay }) {
347
349
  if (index !== -1) {
348
350
  setSeeking(null);
349
351
  showRowAtTop(virtualizer, followRef, index);
352
+ if (seeking.options?.flash) {
353
+ useTimelineFlash.getState().flash(seeking.key, seeking.itemId, false);
354
+ }
355
+ return;
356
+ }
357
+ // The thread has not loaded yet, so nothing says the item is missing; the effect below bounds the wait.
358
+ if (items === undefined) {
350
359
  return;
351
360
  }
352
- const item = items?.[seeking.itemId];
361
+ const item = items[seeking.itemId];
353
362
  if (item === undefined && cursor !== null) {
354
363
  loadEarlier();
355
364
  return;
@@ -360,10 +369,22 @@ export function Timeline({ chatId, composer, overlay }) {
360
369
  return;
361
370
  }
362
371
  setSeeking(null);
372
+ seeking.options?.onMissing?.();
363
373
  }, [seeking, rows, items, turns, virtualizer, cursor, loadEarlier, keyOf, chatId]);
364
- useEffect(() => registerItemJumper(keyOf(chatId), (itemId) => {
374
+ const waitingForThread = seeking !== null && items === undefined;
375
+ useEffect(() => {
376
+ if (!waitingForThread) {
377
+ return;
378
+ }
379
+ const timer = window.setTimeout(() => {
380
+ setSeeking(null);
381
+ seeking?.options?.onMissing?.();
382
+ }, JUMP_THREAD_WAIT_MS);
383
+ return () => window.clearTimeout(timer);
384
+ }, [waitingForThread, seeking]);
385
+ useEffect(() => registerItemJumper(keyOf(chatId), (itemId, options) => {
365
386
  setLanding(null);
366
- setSeeking({ itemId, key: keyOf(chatId) });
387
+ setSeeking({ itemId, key: keyOf(chatId), options });
367
388
  }), [keyOf, chatId]);
368
389
  useLayoutEffect(() => {
369
390
  if (!landing || landing.key !== keyOf(chatId)) {
@@ -0,0 +1,10 @@
1
+ export interface ComposerMenuAriaInput {
2
+ label: string;
3
+ listId: string;
4
+ open: boolean;
5
+ activeIndex: number;
6
+ count: number;
7
+ }
8
+ export declare function clampMenuIndex(index: number, count: number): number;
9
+ export declare function optionIdOf(listId: string, index: number): string;
10
+ export declare function composerMenuAria({ label, listId, open, activeIndex, count }: ComposerMenuAriaInput): Record<string, string>;
@@ -0,0 +1,18 @@
1
+ /* The index that still points at an option once the list has shrunk under a stale one. */
2
+ export function clampMenuIndex(index, count) {
3
+ return Math.min(index, Math.max(count - 1, 0));
4
+ }
5
+ export function optionIdOf(listId, index) {
6
+ return `${listId}-${index}`;
7
+ }
8
+ /*
9
+ * The attributes the editor's content element takes while a suggestion menu stands beside it. The
10
+ * element keeps its `textbox` role; ARIA 1.2 lets it name the option the arrow keys are on.
11
+ */
12
+ export function composerMenuAria({ label, listId, open, activeIndex, count }) {
13
+ return {
14
+ 'aria-label': label,
15
+ 'aria-autocomplete': 'list',
16
+ ...(open && count > 0 ? { 'aria-controls': listId, 'aria-activedescendant': optionIdOf(listId, activeIndex) } : {})
17
+ };
18
+ }
@@ -2,7 +2,7 @@ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-run
2
2
  import { useId, useLayoutEffect, useRef, useState } from 'react';
3
3
  import clsx from 'clsx';
4
4
  import { useTranslation } from 'react-i18next';
5
- import { Lock, Radio, TriangleAlert, Wrench } from 'lucide-react';
5
+ import { Info, Lock, Radio, TriangleAlert } from 'lucide-react';
6
6
  import { Icon, Skeleton, Spinner, Tooltip, useTickingText } from '@adecore/ui';
7
7
  import { formatAgo, formatMoment } from '@adecore/ui/format';
8
8
  import { uiBlockHead, uiReasonText } from './node-text.js';
@@ -36,7 +36,7 @@ function LivePart({ live }) {
36
36
  return hint === null ? body : _jsx(Tooltip, { label: hint, children: body });
37
37
  }
38
38
  /*
39
- * The line under a block, only when it has something to say: live, answered, repaired or drawn as
39
+ * The line under a block, only when it has something to say: live, answered, noted or drawn as
40
40
  * text, in that order. A hairline of the soft border runs the full width of the card over it.
41
41
  */
42
42
  function UiBlockFooter({ live = null, answered = null, fixes = NO_FIXES, shownAsText = null }) {
@@ -46,7 +46,7 @@ function UiBlockFooter({ live = null, answered = null, fixes = NO_FIXES, shownAs
46
46
  if (live === null && answered === null && fixes.length === 0 && shownAsText === null) {
47
47
  return null;
48
48
  }
49
- return (_jsxs("div", { className: "-mx-2.25 mt-2.25 -mb-2.25 flex flex-col gap-1.5 border-t border-border-soft px-4.25 py-2 text-xs text-text-faint", children: [_jsxs("div", { className: "flex flex-wrap items-center gap-x-3 gap-y-1", children: [live !== null && _jsx(LivePart, { live: live }), answered !== null && (_jsxs("span", { className: "flex items-center gap-1.5", children: [_jsx("span", { children: t('blocks.answered', { label: answered.label }) }), _jsx("span", { "aria-hidden": true, children: "\u00B7" }), _jsx("time", { dateTime: new Date(answered.at).toISOString(), children: formatMoment(answered.at) })] })), fixes.length > 0 && (_jsxs("button", { type: "button", "aria-expanded": fixesOpen, "aria-controls": listId, className: "flex items-center gap-1.5 rounded-sm hover:text-text-muted", onClick: () => setFixesOpen(!fixesOpen), children: [_jsx(Icon, { icon: Wrench, size: 12 }), t('blocks.fixes', { count: fixes.length })] })), shownAsText !== null && (_jsxs("span", { className: "flex items-center gap-1.5", children: [_jsx("span", { children: t('blocks.shownAsText') }), _jsx("span", { "aria-hidden": true, children: "\u00B7" }), _jsx("span", { children: shownAsText })] }))] }), fixes.length > 0 && (_jsx("ul", { id: listId, hidden: !fixesOpen, className: "flex flex-col gap-0.5 text-text-muted", children: fixes.map((fix, index) => (_jsxs("li", { className: "flex gap-2", children: [_jsx("span", { className: "shrink-0 font-mono", children: fix.code }), _jsx("span", { className: "min-w-0", children: fix.message })] }, index))) }))] }));
49
+ return (_jsxs("div", { className: "-mx-2.25 mt-2.25 -mb-2.25 flex flex-col gap-1.5 border-t border-border-soft px-4.25 py-2 text-xs text-text-faint", children: [_jsxs("div", { className: "flex flex-wrap items-center gap-x-3 gap-y-1", children: [live !== null && _jsx(LivePart, { live: live }), answered !== null && (_jsxs("span", { className: "flex items-center gap-1.5", children: [_jsx("span", { children: t('blocks.answered', { label: answered.label }) }), _jsx("span", { "aria-hidden": true, children: "\u00B7" }), _jsx("time", { dateTime: new Date(answered.at).toISOString(), children: formatMoment(answered.at) })] })), fixes.length > 0 && (_jsxs("button", { type: "button", "aria-expanded": fixesOpen, "aria-controls": listId, className: "flex items-center gap-1.5 rounded-sm hover:text-text-muted", onClick: () => setFixesOpen(!fixesOpen), children: [_jsx(Icon, { icon: Info, size: 12 }), t('blocks.notes', { count: fixes.length })] })), shownAsText !== null && (_jsxs("span", { className: "flex items-center gap-1.5", children: [_jsx("span", { children: t('blocks.shownAsText') }), _jsx("span", { "aria-hidden": true, children: "\u00B7" }), _jsx("span", { children: shownAsText })] }))] }), fixes.length > 0 && (_jsx("ul", { id: listId, hidden: !fixesOpen, className: "flex flex-col gap-0.5 text-text-muted", children: fixes.map((fix, index) => (_jsxs("li", { className: "flex gap-2", children: [_jsx("span", { className: "shrink-0 font-mono", children: fix.code }), _jsx("span", { className: "min-w-0", children: fix.message })] }, index))) }))] }));
50
50
  }
51
51
  const RELEASE_MS = 200;
52
52
  /*
@@ -7,5 +7,5 @@ import { Markdown } from '../Markdown.js';
7
7
  */
8
8
  export function UiFallbackPart({ fallback, problem }) {
9
9
  const { t } = useTranslation('agent-chat');
10
- return (_jsxs("div", { className: "flex flex-col gap-1 rounded-md bg-surface-hover p-2", children: [_jsx("span", { className: "text-xs text-text-faint", children: problem.kind === 'unknown' ? t('blocks.unknownComponent', { component: problem.component }) : t('blocks.renderFailed') }), fallback !== '' && _jsx(Markdown, { text: fallback, fileLinks: false })] }));
10
+ return (_jsxs("div", { className: "flex flex-col gap-1 rounded-md bg-surface-hover p-2", children: [_jsx("span", { className: "text-xs text-text-faint", children: problem.kind === 'unknown' ? t('blocks.unknownComponent', { component: problem.component }) : t('blocks.renderFailed') }), fallback !== '' && (_jsx("div", { className: "min-w-0 wrap-anywhere", children: _jsx(Markdown, { text: fallback, fileLinks: false }) }))] }));
11
11
  }
@@ -1,16 +1,36 @@
1
1
  import type { UiProps } from '@adecore/intelligent-ui';
2
2
  export declare const UI_CHART_SERIES = 6;
3
3
  export declare const UI_CHART_ROWS = 60;
4
+ type ChartKind = UiProps<'Chart'>['kind'];
4
5
  export interface UiChartSeries {
5
6
  key: string;
6
7
  values: (number | null)[];
7
8
  }
8
- export interface UiChartData {
9
+ export interface UiChartValues {
9
10
  labels: string[];
10
11
  series: UiChartSeries[];
12
+ }
13
+ export interface UiChartData extends UiChartValues {
14
+ kind: ChartKind;
11
15
  min: number;
12
16
  max: number;
13
17
  truncated: boolean;
18
+ total: number;
19
+ omitted: string[];
14
20
  }
15
- export declare function uiChartData(data: UiProps<'Chart'>['data'], kind: UiProps<'Chart'>['kind']): UiChartData | null;
21
+ export declare function uiChartValues(data: UiProps<'Chart'>['data']): UiChartValues;
22
+ export declare function uiChartRange(min: number, max: number): {
23
+ low: number;
24
+ high: number;
25
+ } | null;
26
+ export declare function uiChartData(data: UiProps<'Chart'>['data'], kind: ChartKind): UiChartData | null;
27
+ export declare const UI_CHART_CHARACTER = 7.5;
28
+ export declare function uiChartCharacter(rootFontSize: number): number;
29
+ export declare function uiChartTextWidth(text: string, character?: number): number;
30
+ export declare function uiChartText(text: string, room: number, character?: number): string;
31
+ export declare function uiChartAxis(ticks: readonly string[], width: number, character?: number): {
32
+ axisWidth: number;
33
+ tickTexts: string[];
34
+ };
16
35
  export declare function niceCeiling(value: number): number;
36
+ export {};
@@ -2,38 +2,102 @@
2
2
  export const UI_CHART_SERIES = 6;
3
3
  /* Categories a chart draws; more would not fit a column of a thread. */
4
4
  export const UI_CHART_ROWS = 60;
5
- /*
6
- * The series a chart can draw: every key besides `label` with a finite number in some row, the
7
- * first six of them. A value that is missing or no finite number is a gap. Null when there is no
8
- * row or no series, which draws the fallback.
9
- */
10
- export function uiChartData(data, kind) {
11
- const rows = data.slice(0, UI_CHART_ROWS);
5
+ function numericKeys(rows) {
12
6
  const keys = [];
13
7
  for (const row of rows) {
14
8
  for (const [key, value] of Object.entries(row)) {
15
- if (key !== 'label' && !keys.includes(key) && keys.length < UI_CHART_SERIES && typeof value === 'number' && Number.isFinite(value)) {
9
+ if (key !== 'label' && !keys.includes(key) && typeof value === 'number' && Number.isFinite(value)) {
16
10
  keys.push(key);
17
11
  }
18
12
  }
19
13
  }
14
+ return keys;
15
+ }
16
+ function valuesOf(rows, keys) {
17
+ return {
18
+ labels: rows.map((row) => (typeof row.label === 'string' || typeof row.label === 'number' ? String(row.label) : '')),
19
+ series: keys.map((key) => ({
20
+ key,
21
+ values: rows.map((row) => {
22
+ const value = row[key];
23
+ return typeof value === 'number' && Number.isFinite(value) ? value : null;
24
+ })
25
+ }))
26
+ };
27
+ }
28
+ /* All of a chart's numbers, for the table a person can open beside a drawing that left some out. */
29
+ export function uiChartValues(data) {
30
+ return valuesOf(data, numericKeys(data));
31
+ }
32
+ /*
33
+ * The rounded ends of a value axis, or null when no drawing can scale to them: the span has to be
34
+ * finite and above zero, and so does one over it, which rules out a subnormal span as well.
35
+ */
36
+ export function uiChartRange(min, max) {
37
+ const low = min < 0 ? -niceCeiling(-min) : 0;
38
+ const high = max > 0 ? niceCeiling(max) : low === 0 ? 1 : 0;
39
+ const span = high - low;
40
+ return span > 0 && Number.isFinite(span) && Number.isFinite(1 / span) ? { low, high } : null;
41
+ }
42
+ /*
43
+ * The series a chart can draw: every key besides `label` with a finite number in some row, the
44
+ * first six of them. A value that is missing or no finite number is a gap. Null when there is no
45
+ * row or no series, or when the numbers are too large to scale, which draws the fallback.
46
+ */
47
+ export function uiChartData(data, kind) {
48
+ const rows = data.slice(0, UI_CHART_ROWS);
49
+ const keys = numericKeys(rows);
20
50
  if (rows.length === 0 || keys.length === 0) {
21
51
  return null;
22
52
  }
23
- const series = keys.map((key) => ({
24
- key,
25
- values: rows.map((row) => {
26
- const value = row[key];
27
- return typeof value === 'number' && Number.isFinite(value) ? value : null;
28
- })
29
- }));
30
- const labels = rows.map((row) => (typeof row.label === 'string' || typeof row.label === 'number' ? String(row.label) : ''));
31
- const extents = kind === 'stacked'
32
- ? labels.map((_, index) => series.reduce((sum, { values }) => sum + Math.max(0, values[index] ?? 0), 0))
53
+ const { labels, series } = valuesOf(rows, keys.slice(0, UI_CHART_SERIES));
54
+ const negative = series.some(({ values }) => values.some((value) => value !== null && value < 0));
55
+ const drawn = kind === 'stacked' && negative ? 'bar' : kind;
56
+ const extents = drawn === 'stacked'
57
+ ? labels.map((_, index) => series.reduce((sum, { values }) => sum + (values[index] ?? 0), 0))
33
58
  : series.flatMap(({ values }) => values.filter((value) => value !== null));
34
59
  const min = Math.min(0, ...extents);
35
60
  const max = Math.max(0, ...extents);
36
- return { labels, series, min, max: max === min ? min + 1 : max, truncated: data.length > rows.length };
61
+ if (uiChartRange(min, max) === null) {
62
+ return null;
63
+ }
64
+ return {
65
+ labels,
66
+ series,
67
+ kind: drawn,
68
+ min,
69
+ max: max === min ? min + 1 : max,
70
+ truncated: data.length > rows.length,
71
+ total: data.length,
72
+ omitted: numericKeys(data).filter((key) => !series.some((drawnSeries) => drawnSeries.key === key))
73
+ };
74
+ }
75
+ /* The width of one character of a chart's type at a 16px root, an estimate since SVG text cannot wrap or be measured before it draws. */
76
+ export const UI_CHART_CHARACTER = 7.5;
77
+ /* The narrowest a value axis is, and the gap between a tick label and the plot. */
78
+ const AXIS_WIDTH = 44;
79
+ const AXIS_GAP = 8;
80
+ /* The character width for a root font size, since chart type is set in rem and follows a person's larger text. */
81
+ export function uiChartCharacter(rootFontSize) {
82
+ return Number.isFinite(rootFontSize) && rootFontSize > 0 ? (UI_CHART_CHARACTER * rootFontSize) / 16 : UI_CHART_CHARACTER;
83
+ }
84
+ export function uiChartTextWidth(text, character = UI_CHART_CHARACTER) {
85
+ return Math.ceil(text.length * character);
86
+ }
87
+ /* Text cut to the room it has, so a label never reaches past its place; the whole of it is in the values. */
88
+ export function uiChartText(text, room, character = UI_CHART_CHARACTER) {
89
+ const fit = Math.floor(room / character);
90
+ return text.length <= fit ? text : `${text.slice(0, Math.max(1, fit - 1))}…`;
91
+ }
92
+ /* A value axis as wide as its longest tick label, at most two fifths of the chart; a label longer than that is cut. */
93
+ export function uiChartAxis(ticks, width, character = UI_CHART_CHARACTER) {
94
+ const scale = character / UI_CHART_CHARACTER;
95
+ const room = Math.max(AXIS_WIDTH * scale, Math.floor(width * 0.4));
96
+ const tickTexts = ticks.map((tick) => uiChartText(tick, room - AXIS_GAP, character));
97
+ return {
98
+ axisWidth: Math.round(Math.min(room, Math.max(AXIS_WIDTH * scale, ...tickTexts.map((text) => uiChartTextWidth(text, character) + AXIS_GAP)))),
99
+ tickTexts
100
+ };
37
101
  }
38
102
  /* A round number at or above `value`, for the top of an axis: 1, 2, 2.5 or 5 times a power of ten. */
39
103
  export function niceCeiling(value) {
@@ -1,3 +1,3 @@
1
1
  import type { UiProps } from '@adecore/intelligent-ui';
2
2
  import type { UiRendererProps } from '../render-context.js';
3
- export declare function ChartRenderer({ node }: UiRendererProps<UiProps<'Chart'>>): import("react").JSX.Element;
3
+ export declare function ChartRenderer({ node, context }: UiRendererProps<UiProps<'Chart'>>): import("react").JSX.Element;
@@ -2,17 +2,20 @@ import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-run
2
2
  import { useMemo, useState } from 'react';
3
3
  import clsx from 'clsx';
4
4
  import { useTranslation } from 'react-i18next';
5
- import { SegmentBar, useMeasuredWidth } from '@adecore/ui';
6
- import { formatRounded } from '@adecore/ui/format';
7
- import { niceCeiling, UI_CHART_ROWS, uiChartData } from '../chart-data.js';
5
+ import { Button, SegmentBar, Tooltip, useMeasuredWidth } from '@adecore/ui';
6
+ import { formatNumber, formatRounded } from '@adecore/ui/format';
7
+ import { useBlockLocal } from '../block-local.js';
8
+ import { UI_CHART_CHARACTER, UI_CHART_ROWS, uiChartCharacter, uiChartAxis, uiChartData, uiChartRange, uiChartText, uiChartTextWidth, uiChartValues } from '../chart-data.js';
8
9
  import { uiWithUnit } from '../node-text.js';
10
+ import { useTruncated } from '../use-truncated.js';
9
11
  import { UiFallbackPart } from '../UiFallbackPart.js';
10
12
  const HEIGHT = 160;
11
13
  const HBAR_ROW = 24;
12
14
  const STACKED_ROW = 28;
13
- const AXIS_WIDTH = 44;
14
15
  const PLOT_TOP = 8;
15
16
  const LABEL_ROOM = 20;
17
+ /* A unit longer than this stands once above the plot instead of beside every tick. */
18
+ const UNIT_ON_TICKS = 5;
16
19
  /* The narrowest band a category label is written under; narrower bands skip labels. */
17
20
  const LABEL_BAND = 56;
18
21
  /* Points get a dot up to this many categories; more would crowd the line. */
@@ -24,56 +27,84 @@ function seriesColor(index) {
24
27
  function valueText(value, unit) {
25
28
  return value === null ? '' : uiWithUnit(formatRounded(value, 2), unit);
26
29
  }
30
+ function unitApart(unit) {
31
+ return unit !== undefined && unit.length > UNIT_ON_TICKS;
32
+ }
33
+ /* Where a value axis stands and how much room its category labels get, from the labels it writes. */
34
+ function verticalLayout(chart, unit, width, character) {
35
+ // uiChartData only hands over data whose range is finite.
36
+ const { low, high } = uiChartRange(chart.min, chart.max);
37
+ const ticks = low === 0 ? [0, high / 2, high] : [low, 0, high];
38
+ const tickUnit = unitApart(unit) ? undefined : unit;
39
+ const { axisWidth, tickTexts } = uiChartAxis(ticks.map((tick) => valueText(tick, tickUnit)), width, character);
40
+ const band = Math.max(0, width - axisWidth) / chart.labels.length;
41
+ const labelEvery = Math.max(1, Math.ceil(LABEL_BAND / Math.max(1, band)));
42
+ return { low, high, ticks, tickTexts, axisWidth, band, labelEvery, labelRoom: Math.min(band * labelEvery, Math.max(0, width - axisWidth)) };
43
+ }
44
+ /* Whether a drawing in SVG at this width cuts a category label short, which then offers the values to read it whole; HTML rows are measured where they stand. */
45
+ function labelsCut(chart, unit, width, character) {
46
+ if (width <= 0 || chart.kind === 'hbar' || chart.kind === 'stacked') {
47
+ return false;
48
+ }
49
+ const { labelRoom } = verticalLayout(chart, unit, width, character);
50
+ return chart.labels.some((label) => uiChartTextWidth(label, character) > labelRoom);
51
+ }
52
+ /* The character width of chart type, which follows the root font size; a drawing depends on a measured width, so only a page reads it. */
53
+ function useChartCharacter() {
54
+ const [character] = useState(() => typeof document === 'undefined' ? UI_CHART_CHARACTER : uiChartCharacter(Number.parseFloat(getComputedStyle(document.documentElement).fontSize)));
55
+ return character;
56
+ }
27
57
  /* The height a chart will take, which its place holds while the node streams. */
28
58
  function chartHeight(kind, rows) {
29
59
  const count = Math.max(1, Math.min(rows, UI_CHART_ROWS));
30
60
  return kind === 'hbar' ? count * HBAR_ROW : kind === 'stacked' ? count * STACKED_ROW : HEIGHT;
31
61
  }
32
- /* One sentence with the main point, which a screen reader hears in place of the drawing. */
33
- function chartSummary(chart, unit, t) {
62
+ /* One sentence with the main point over all of the data, drawn or not, which a screen reader hears in place of the drawing. */
63
+ function chartSummary(values, unit, t) {
34
64
  let top = null;
35
- for (const series of chart.series) {
65
+ for (const series of values.series) {
36
66
  for (let i = 0; i < series.values.length; i++) {
37
67
  const value = series.values[i];
38
68
  if (value !== null && value !== undefined && (top === null || value > top.value)) {
39
- top = { label: chart.labels[i] ?? '', series: series.key, value };
69
+ top = { label: values.labels[i] ?? '', series: series.key, value };
40
70
  }
41
71
  }
42
72
  }
43
73
  if (top === null) {
44
74
  return t('blocks.chart.values');
45
75
  }
46
- return chart.series.length > 1
47
- ? t('blocks.chart.summarySeries', { count: chart.labels.length, series: top.series, label: top.label, value: valueText(top.value, unit) })
48
- : t('blocks.chart.summary', { count: chart.labels.length, label: top.label, value: valueText(top.value, unit) });
76
+ return values.series.length > 1
77
+ ? t('blocks.chart.summarySeries', { count: values.labels.length, series: top.series, label: top.label, value: valueText(top.value, unit) })
78
+ : t('blocks.chart.summary', { count: values.labels.length, label: top.label, value: valueText(top.value, unit) });
49
79
  }
50
80
  function Legend({ chart }) {
51
81
  return (_jsx("div", { "aria-hidden": true, className: "flex flex-wrap gap-x-3 gap-y-1 text-xs text-text-muted", children: chart.series.map((series, index) => (_jsxs("span", { className: "flex items-center gap-1.5", children: [_jsx("span", { className: "size-2 rounded-sm", style: { backgroundColor: seriesColor(index) } }), series.key] }, series.key))) }));
52
82
  }
53
- /* The numbers behind the drawing, for a screen reader. */
54
- function ValuesTable({ chart, unit }) {
83
+ /* Every number of the data, for a screen reader, and on screen once a person opens it. */
84
+ function ValuesTable({ values, unit, shown }) {
55
85
  const { t } = useTranslation('agent-chat');
56
- return (_jsxs("table", { className: "sr-only", children: [_jsx("caption", { children: t('blocks.chart.values') }), _jsx("thead", { children: _jsxs("tr", { children: [_jsx("td", {}), chart.series.map((series) => (_jsx("th", { scope: "col", children: series.key }, series.key)))] }) }), _jsx("tbody", { children: chart.labels.map((label, index) => (_jsxs("tr", { children: [_jsx("th", { scope: "row", children: label }), chart.series.map((series) => (_jsx("td", { children: valueText(series.values[index] ?? null, unit) }, series.key)))] }, index))) })] }));
86
+ const table = (_jsxs("table", { className: shown ? 'w-full border-collapse text-xs tabular-nums' : undefined, children: [_jsx("caption", { className: shown ? 'sr-only' : undefined, children: t('blocks.chart.values') }), _jsx("thead", { className: shown ? 'sticky top-0 z-1 bg-surface-hover' : undefined, children: _jsxs("tr", { children: [_jsx("td", {}), values.series.map((series) => (_jsx("th", { scope: "col", className: shown ? 'h-8 px-2 text-right font-medium whitespace-nowrap text-text-muted' : undefined, children: series.key }, series.key)))] }) }), _jsx("tbody", { children: values.labels.map((label, index) => (_jsxs("tr", { className: shown ? 'border-t border-border-soft' : undefined, children: [_jsx("th", { scope: "row", className: shown ? 'h-8 px-2 text-left font-normal wrap-anywhere text-text-muted' : undefined, children: label }), values.series.map((series) => (_jsx("td", { className: shown ? 'h-8 px-2 text-right whitespace-nowrap text-text' : undefined, children: valueText(series.values[index] ?? null, unit) }, series.key)))] }, index))) })] }));
87
+ // A table grows to its widest cell whatever width it is given, so it is hidden inside a block that clips.
88
+ return _jsx("div", { className: shown ? 'max-h-80 w-full overflow-auto rounded-md border border-border-soft' : 'sr-only', children: table });
57
89
  }
58
90
  /* The values of one category beside the pointer. */
59
91
  function Readout({ chart, index, left, unit }) {
60
- return (_jsxs("div", { "aria-hidden": true, className: "pointer-events-none absolute top-0 z-1 flex -translate-x-1/2 flex-col gap-0.5 rounded-md bg-surface-raised px-2 py-1 text-xs whitespace-nowrap shadow-raised", style: { left }, children: [_jsx("span", { className: "font-medium text-text", children: chart.labels[index] }), chart.series.map((series, at) => (_jsxs("span", { className: "flex items-center gap-1.5 text-text-muted tabular-nums", children: [_jsx("span", { className: "size-2 rounded-sm", style: { backgroundColor: seriesColor(at) } }), chart.series.length > 1 && _jsx("span", { children: series.key }), _jsx("span", { className: "text-text", children: valueText(series.values[index] ?? null, unit) })] }, series.key)))] }));
92
+ return (_jsxs("div", { "aria-hidden": true, className: "pointer-events-none absolute top-0 z-1 flex w-max max-w-56 -translate-x-1/2 flex-col gap-0.5 rounded-md bg-surface-raised px-2 py-1 text-xs shadow-raised", style: { left }, children: [_jsx("span", { className: "font-medium wrap-anywhere text-text", children: chart.labels[index] }), chart.series.map((series, at) => (_jsxs("span", { className: "flex items-center gap-1.5 text-text-muted tabular-nums", children: [_jsx("span", { className: "size-2 rounded-sm", style: { backgroundColor: seriesColor(at) } }), chart.series.length > 1 && _jsx("span", { children: series.key }), _jsx("span", { className: "text-text", children: valueText(series.values[index] ?? null, unit) })] }, series.key)))] }));
61
93
  }
62
94
  /* Bars and lines over a value axis, in SVG at the measured width. */
63
- function VerticalChart({ chart, kind, unit, width }) {
95
+ function VerticalChart({ chart, kind, unit, width, character }) {
64
96
  const [hover, setHover] = useState(null);
65
- const low = chart.min < 0 ? -niceCeiling(-chart.min) : 0;
66
- const high = chart.max > 0 ? niceCeiling(chart.max) : low === 0 ? 1 : 0;
67
- const plotWidth = Math.max(0, width - AXIS_WIDTH);
68
- const plotHeight = HEIGHT - PLOT_TOP - LABEL_ROOM;
69
- const band = plotWidth / chart.labels.length;
97
+ const { low, high, ticks, tickTexts, axisWidth, band, labelEvery, labelRoom } = verticalLayout(chart, unit, width, character);
98
+ const plotHeight = HEIGHT - PLOT_TOP - Math.round((LABEL_ROOM * character) / UI_CHART_CHARACTER);
70
99
  const y = (value) => Math.round(PLOT_TOP + ((high - value) / (high - low)) * plotHeight);
71
100
  const baseline = y(0);
72
- const ticks = low === 0 ? [0, high / 2, high] : [low, 0, high];
73
- const labelEvery = Math.max(1, Math.ceil(LABEL_BAND / Math.max(1, band)));
74
- const center = (index) => Math.round(AXIS_WIDTH + band * index + band / 2);
101
+ const center = (index) => Math.round(axisWidth + band * index + band / 2);
75
102
  const gap = band * 0.2;
76
103
  const barWidth = Math.max(1, (band - gap) / chart.series.length);
104
+ const labelAt = (index, text) => {
105
+ const half = uiChartTextWidth(text, character) / 2;
106
+ return Math.round(Math.min(Math.max(center(index), axisWidth + half), width - half));
107
+ };
77
108
  const segments = (values) => values
78
109
  .map((value, index) => (value === null ? null : `${center(index)} ${y(value)}`))
79
110
  .reduce((paths, point, index, all) => {
@@ -83,34 +114,67 @@ function VerticalChart({ chart, kind, unit, width }) {
83
114
  return paths;
84
115
  }, [])
85
116
  .join(' ');
86
- return (_jsxs(_Fragment, { children: [_jsxs("svg", { width: width, height: HEIGHT, "aria-hidden": true, className: "block overflow-visible", onPointerLeave: () => setHover(null), children: [hover !== null && (_jsx("rect", { x: Math.round(AXIS_WIDTH + band * hover), y: PLOT_TOP, width: Math.round(band), height: plotHeight, className: "fill-surface-hover" })), ticks.map((tick) => (_jsxs("g", { children: [_jsx("line", { x1: AXIS_WIDTH, x2: width, y1: y(tick), y2: y(tick), className: tick === 0 ? 'stroke-border' : 'stroke-border-soft', shapeRendering: "crispEdges" }), _jsx("text", { x: AXIS_WIDTH - 6, y: y(tick), dy: "0.32em", textAnchor: "end", className: "fill-text-faint text-xs tabular-nums", children: valueText(tick, unit) })] }, tick))), chart.labels.map((label, index) => index % labelEvery === 0 ? (_jsx("text", { x: center(index), y: HEIGHT - 4, textAnchor: "middle", className: "fill-text-faint text-xs", children: label }, index)) : null), kind === 'bar' ? (_jsx("g", { className: clsx(GROW, 'starting:scale-y-0'), style: { transformOrigin: `0px ${baseline}px` }, children: chart.series.map((series, at) => series.values.map((value, index) => value === null ? null : (_jsx("rect", { x: Math.round(AXIS_WIDTH + band * index + gap / 2 + barWidth * at), y: Math.min(y(value), baseline), width: Math.max(1, Math.round(barWidth) - 1), height: Math.abs(y(value) - baseline), rx: 2, style: { fill: seriesColor(at) } }, `${series.key}:${index}`)))) })) : (_jsx("g", { className: clsx(GROW, 'starting:opacity-0'), children: chart.series.map((series, at) => (_jsxs("g", { style: { color: seriesColor(at) }, children: [_jsx("path", { d: segments(series.values), fill: "none", stroke: "currentColor", strokeWidth: 2, strokeLinejoin: "round", strokeLinecap: "round" }), chart.labels.length <= DOTS_UP_TO &&
87
- series.values.map((value, index) => value === null ? null : _jsx("circle", { cx: center(index), cy: y(value), r: 3, fill: "currentColor" }, index))] }, series.key))) })), chart.labels.map((_, index) => (_jsx("rect", { x: Math.round(AXIS_WIDTH + band * index), y: 0, width: Math.max(1, Math.round(band)), height: HEIGHT, fill: "transparent", onPointerEnter: () => setHover(index) }, index)))] }), hover !== null && _jsx(Readout, { chart: chart, index: hover, unit: unit, left: Math.min(Math.max(center(hover), 64), Math.max(64, width - 64)) })] }));
117
+ return (_jsxs(_Fragment, { children: [_jsxs("svg", { width: width, height: HEIGHT, "aria-hidden": true, className: "block overflow-visible", onPointerLeave: () => setHover(null), children: [hover !== null && (_jsx("rect", { x: Math.round(axisWidth + band * hover), y: PLOT_TOP, width: Math.round(band), height: plotHeight, className: "fill-surface-hover" })), ticks.map((tick, index) => (_jsxs("g", { children: [_jsx("line", { x1: axisWidth, x2: width, y1: y(tick), y2: y(tick), className: tick === 0 ? 'stroke-border' : 'stroke-border-soft', shapeRendering: "crispEdges" }), _jsx("text", { x: axisWidth - 6, y: y(tick), dy: "0.32em", textAnchor: "end", className: "fill-text-faint text-xs tabular-nums", children: tickTexts[index] })] }, tick))), chart.labels.map((label, index) => {
118
+ if (index % labelEvery !== 0) {
119
+ return null;
120
+ }
121
+ const text = uiChartText(label, labelRoom, character);
122
+ return (_jsx("text", { x: labelAt(index, text), y: HEIGHT - 4, textAnchor: "middle", className: "fill-text-faint text-xs", children: text }, index));
123
+ }), kind === 'bar' ? (_jsx("g", { className: clsx(GROW, 'starting:scale-y-0'), style: { transformOrigin: `0px ${baseline}px` }, children: chart.series.map((series, at) => series.values.map((value, index) => value === null ? null : (_jsx("rect", { x: Math.round(axisWidth + band * index + gap / 2 + barWidth * at), y: Math.min(y(value), baseline), width: Math.max(1, Math.round(barWidth) - 1), height: Math.abs(y(value) - baseline), rx: 2, style: { fill: seriesColor(at) } }, `${series.key}:${index}`)))) })) : (_jsx("g", { className: clsx(GROW, 'starting:opacity-0'), children: chart.series.map((series, at) => (_jsxs("g", { style: { color: seriesColor(at) }, children: [_jsx("path", { d: segments(series.values), fill: "none", stroke: "currentColor", strokeWidth: 2, strokeLinejoin: "round", strokeLinecap: "round" }), chart.labels.length <= DOTS_UP_TO &&
124
+ series.values.map((value, index) => value === null ? null : _jsx("circle", { cx: center(index), cy: y(value), r: 3, fill: "currentColor" }, index))] }, series.key))) })), chart.labels.map((_, index) => (_jsx("rect", { x: Math.round(axisWidth + band * index), y: 0, width: Math.max(1, Math.round(band)), height: HEIGHT, fill: "transparent", onPointerEnter: () => setHover(index) }, index)))] }), hover !== null && _jsx(Readout, { chart: chart, index: hover, unit: unit, left: Math.min(Math.max(center(hover), 64), Math.max(64, width - 64)) })] }));
88
125
  }
89
- /* A row of 24px per category, its label beside the bars. */
126
+ /* A row of 24px per category, its label beside the bars, which grow from zero to either side. */
90
127
  function HorizontalChart({ chart, unit }) {
91
- // Bars grow right from zero only, so a chart of only negative values has no length to share and keeps a unit scale.
92
- const high = niceCeiling(chart.max) || 1;
128
+ const valueUnit = unitApart(unit) ? undefined : unit;
129
+ const { low, high } = uiChartRange(chart.min, chart.max);
130
+ const span = high - low;
131
+ const zero = (-low / span) * 100;
93
132
  const single = chart.series.length === 1;
94
- return (_jsx("div", { "aria-hidden": true, className: "flex flex-col", children: chart.labels.map((label, index) => (_jsxs("div", { className: "flex h-6 items-center gap-2 text-xs", children: [_jsx("span", { className: "w-2/5 max-w-36 shrink-0 truncate text-text-muted", children: label }), _jsx("span", { className: "flex min-w-0 grow flex-col justify-center gap-px", children: chart.series.map((series, at) => (_jsx("span", { className: clsx(GROW, 'block origin-left rounded-sm starting:scale-x-0', single ? 'h-3' : 'h-1'), style: { width: `${(Math.max(0, series.values[index] ?? 0) / high) * 100}%`, backgroundColor: seriesColor(at) } }, series.key))) }), single && (_jsx("span", { className: "w-16 shrink-0 text-right text-text-faint tabular-nums", children: valueText(chart.series[0].values[index] ?? null, unit) }))] }, index))) }));
133
+ return (_jsx("div", { "aria-hidden": true, className: "flex flex-col", children: chart.labels.map((label, index) => (_jsxs("div", { className: "flex h-6 items-center gap-2 text-xs", children: [_jsx("span", { className: "w-2/5 max-w-36 shrink-0 truncate text-text-muted", children: label }), _jsxs("span", { className: "relative flex min-w-0 grow flex-col justify-center gap-px", children: [low < 0 && _jsx("span", { className: "absolute inset-y-0 w-px bg-border", style: { left: `${zero}%` } }), chart.series.map((series, at) => {
134
+ const value = series.values[index] ?? 0;
135
+ return (_jsx("span", { className: clsx('relative block', single ? 'h-3' : 'h-1'), children: _jsx("span", { className: clsx(GROW, 'absolute inset-y-0 rounded-sm starting:scale-x-0', value < 0 ? 'origin-right' : 'origin-left'), style: {
136
+ left: `${((Math.min(value, 0) - low) / span) * 100}%`,
137
+ width: `${(Math.abs(value) / span) * 100}%`,
138
+ backgroundColor: seriesColor(at)
139
+ } }) }, series.key));
140
+ })] }), single && (_jsx("span", { className: "max-w-1/3 min-w-12 shrink-0 truncate text-right text-text-faint tabular-nums", children: valueText(chart.series[0].values[index] ?? null, valueUnit) }))] }, index))) }));
95
141
  }
96
142
  /* A bar per category split into its series, on one scale so the rows compare. */
97
143
  function StackedChart({ chart, unit }) {
98
144
  return (_jsx("div", { className: "flex flex-col gap-2", children: chart.labels.map((label, index) => (_jsxs("div", { className: "flex items-center gap-2 text-xs", children: [chart.labels.length > 1 && _jsx("span", { className: "w-2/5 max-w-36 shrink-0 truncate text-text-muted", children: label }), _jsx(SegmentBar, { size: "sm", className: "grow", label: label, range: [0, chart.max], parts: chart.series.map((series, at) => ({
99
- value: Math.max(0, series.values[index] ?? 0),
145
+ value: series.values[index] ?? 0,
100
146
  color: seriesColor(at),
101
147
  label: `${series.key} ${valueText(series.values[index] ?? 0, unit)}`
102
148
  })) })] }, index))) }));
103
149
  }
104
- function DrawnChart({ chart, kind, unit }) {
150
+ /* What the drawing leaves out or draws otherwise, said in words, with every value a press away. */
151
+ function ChartNotes({ chart, requested, cut, values, unit, context, nodeId }) {
152
+ const { t } = useTranslation('agent-chat');
153
+ const [shown, setShown] = useBlockLocal(context, `${nodeId}:values`, () => false);
154
+ const notes = [
155
+ ...(chart.truncated ? [t('blocks.chart.rowsLeftOut', { shown: formatNumber(chart.labels.length), total: formatNumber(chart.total) })] : []),
156
+ ...(chart.omitted.length > 0 ? [t('blocks.chart.seriesLeftOut', { count: chart.omitted.length, series: chart.omitted.join(', ') })] : []),
157
+ ...(requested === 'stacked' && chart.kind !== 'stacked' ? [t('blocks.chart.sideBySide')] : [])
158
+ ];
159
+ const partial = chart.truncated || chart.omitted.length > 0 || cut;
160
+ const [measure, truncated] = useTruncated();
161
+ const toggle = shown ? t('blocks.chart.hideValues') : t('blocks.chart.showValues');
162
+ return (_jsxs(_Fragment, { children: [notes.length > 0 && (_jsx("div", { className: "flex flex-col gap-0.5 text-xs text-text-muted", children: notes.map((note) => (_jsx("p", { children: note }, note))) })), partial && (_jsx(Tooltip, { label: toggle, disabled: !truncated, children: _jsx(Button, { size: "xs", variant: "secondary", className: "max-w-full self-start", "aria-expanded": shown, onClick: () => setShown(!shown), children: _jsx("span", { ref: measure, className: "min-w-0 truncate", children: toggle }) }) })), _jsx(ValuesTable, { values: values, unit: unit, shown: partial && shown })] }));
163
+ }
164
+ function DrawnChart({ chart, requested, data, unit, context, nodeId }) {
105
165
  const { t } = useTranslation('agent-chat');
106
166
  const [measure, width] = useMeasuredWidth();
107
- return (_jsxs("figure", { className: "flex flex-col gap-2 px-2", children: [chart.series.length > 1 && _jsx(Legend, { chart: chart }), _jsx("div", { ref: measure, role: "img", "aria-label": chartSummary(chart, unit, t), className: "relative", children: kind === 'hbar' ? (_jsx(HorizontalChart, { chart: chart, unit: unit })) : kind === 'stacked' ? (_jsx(StackedChart, { chart: chart, unit: unit })) : (_jsx("div", { style: { height: HEIGHT }, children: width > 0 && _jsx(VerticalChart, { chart: chart, kind: kind, unit: unit, width: width }) })) }), _jsx(ValuesTable, { chart: chart, unit: unit })] }));
167
+ const character = useChartCharacter();
168
+ const [measureRows, rowsCut] = useTruncated(true);
169
+ const values = useMemo(() => uiChartValues(data), [data]);
170
+ const { kind } = chart;
171
+ return (_jsxs("figure", { className: "flex flex-col gap-2 px-2", children: [chart.series.length > 1 && _jsx(Legend, { chart: chart }), kind !== 'stacked' && unitApart(unit) && _jsx("p", { className: "text-xs text-text-faint", children: unit }), _jsx("div", { ref: measure, role: "img", "aria-label": chartSummary(values, unit, t), className: "relative", children: kind === 'hbar' || kind === 'stacked' ? (_jsx("div", { ref: measureRows, children: kind === 'hbar' ? _jsx(HorizontalChart, { chart: chart, unit: unit }) : _jsx(StackedChart, { chart: chart, unit: unit }) })) : (_jsx("div", { style: { height: HEIGHT }, children: width > 0 && _jsx(VerticalChart, { chart: chart, kind: kind, unit: unit, width: width, character: character }) })) }), _jsx(ChartNotes, { chart: chart, requested: requested, cut: rowsCut || labelsCut(chart, unit, width, character), values: values, unit: unit, context: context, nodeId: nodeId })] }));
108
172
  }
109
173
  /*
110
174
  * Draws only once its node closed; until then a quiet surface of the height it will take holds its
111
175
  * place. It grows in once, and not at all for a person who asked for less motion.
112
176
  */
113
- export function ChartRenderer({ node }) {
177
+ export function ChartRenderer({ node, context }) {
114
178
  const { kind, data, unit } = node.props;
115
179
  const chart = useMemo(() => (node.complete ? uiChartData(data, kind) : null), [node.complete, data, kind]);
116
180
  if (!node.complete) {
@@ -119,5 +183,5 @@ export function ChartRenderer({ node }) {
119
183
  if (chart === null) {
120
184
  return _jsx(UiFallbackPart, { fallback: node.fallback, problem: { kind: 'failed' } });
121
185
  }
122
- return _jsx(DrawnChart, { chart: chart, kind: kind, unit: unit });
186
+ return _jsx(DrawnChart, { chart: chart, requested: kind, data: data, unit: unit, context: context, nodeId: node.id });
123
187
  }
@@ -1,4 +1,4 @@
1
- import type { UiProps } from '@adecore/intelligent-ui';
1
+ import { type UiProps } from '@adecore/intelligent-ui';
2
2
  import type { UiRendererProps } from '../render-context.js';
3
3
  export declare function ChoicesRenderer({ children, context }: UiRendererProps<UiProps<'Choices'>>): import("react").JSX.Element;
4
4
  export declare function ChoiceRenderer({ node, children, context }: UiRendererProps<UiProps<'Choice'>>): import("react").JSX.Element;