@kumix/ui 0.3.8 → 0.3.10

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 (102) hide show
  1. package/README.md +16 -15
  2. package/dist/components/agents/ai-sidebar.js +3 -5
  3. package/dist/components/agents/ai-sidebar.js.map +1 -1
  4. package/dist/components/motion/animated-sidebar.d.ts.map +1 -1
  5. package/dist/components/motion/animated-sidebar.js.map +1 -1
  6. package/dist/components/motion/availability-scheduler/copy-menu.js +1 -1
  7. package/dist/components/motion/availability-scheduler/day-row.d.ts.map +1 -1
  8. package/dist/components/motion/availability-scheduler/day-row.js +15 -7
  9. package/dist/components/motion/availability-scheduler/day-row.js.map +1 -1
  10. package/dist/components/motion/availability-scheduler/index.js +1 -1
  11. package/dist/components/motion/button/index.d.ts +2 -1
  12. package/dist/components/motion/button/index.js +2 -1
  13. package/dist/components/motion/button/metallic.d.ts +10 -0
  14. package/dist/components/motion/button/metallic.d.ts.map +1 -0
  15. package/dist/components/motion/button/metallic.js +71 -0
  16. package/dist/components/motion/button/metallic.js.map +1 -0
  17. package/dist/components/motion/combobox/content.js +1 -1
  18. package/dist/components/motion/combobox/context.d.ts +6 -0
  19. package/dist/components/motion/combobox/context.d.ts.map +1 -1
  20. package/dist/components/motion/combobox/context.js +1 -233
  21. package/dist/components/motion/combobox/list.js +1 -1
  22. package/dist/components/motion/combobox/trigger.js +7 -8
  23. package/dist/components/motion/combobox/trigger.js.map +1 -1
  24. package/dist/components/motion/combobox.js +1 -1
  25. package/dist/components/motion/command-palette.d.ts.map +1 -1
  26. package/dist/components/motion/command-palette.js +21 -26
  27. package/dist/components/motion/command-palette.js.map +1 -1
  28. package/dist/components/motion/expandable-control.d.ts +28 -0
  29. package/dist/components/motion/expandable-control.d.ts.map +1 -0
  30. package/dist/components/motion/expandable-control.js +149 -0
  31. package/dist/components/motion/expandable-control.js.map +1 -0
  32. package/dist/components/motion/expanding-arrow-button.d.ts +12 -0
  33. package/dist/components/motion/expanding-arrow-button.d.ts.map +1 -0
  34. package/dist/components/motion/expanding-arrow-button.js +142 -0
  35. package/dist/components/motion/expanding-arrow-button.js.map +1 -0
  36. package/dist/components/motion/file-tree.d.ts +42 -0
  37. package/dist/components/motion/file-tree.d.ts.map +1 -0
  38. package/dist/components/motion/file-tree.js +272 -0
  39. package/dist/components/motion/file-tree.js.map +1 -0
  40. package/dist/components/motion/morphing-search.d.ts.map +1 -1
  41. package/dist/components/motion/morphing-search.js +27 -23
  42. package/dist/components/motion/morphing-search.js.map +1 -1
  43. package/dist/components/reui/alert.d.ts +1 -1
  44. package/dist/components/reui/badge.d.ts +1 -1
  45. package/dist/components/reui/code-block/code-block-highlight.d.ts +216 -0
  46. package/dist/components/reui/code-block/code-block-highlight.d.ts.map +1 -0
  47. package/dist/components/reui/code-block/code-block-highlight.js +792 -0
  48. package/dist/components/reui/code-block/code-block-highlight.js.map +1 -0
  49. package/dist/components/reui/code-block/code-block.d.ts +197 -0
  50. package/dist/components/reui/code-block/code-block.d.ts.map +1 -0
  51. package/dist/components/reui/code-block/code-block.js +1150 -0
  52. package/dist/components/reui/code-block/code-block.js.map +1 -0
  53. package/dist/components/reui/filters/filters-builder.js +1 -1
  54. package/dist/components/reui/filters/filters-chip.js.map +1 -1
  55. package/dist/components/reui/filters/filters-editors.js +2 -2
  56. package/dist/components/reui/filters/filters-editors.js.map +1 -1
  57. package/dist/components/reui/gantt/gantt-bar.js +42 -12
  58. package/dist/components/reui/gantt/gantt-bar.js.map +1 -1
  59. package/dist/components/reui/gantt/gantt-dnd.d.ts.map +1 -1
  60. package/dist/components/reui/gantt/gantt-dnd.js +22 -7
  61. package/dist/components/reui/gantt/gantt-dnd.js.map +1 -1
  62. package/dist/components/reui/gantt/gantt-i18n.d.ts +8 -0
  63. package/dist/components/reui/gantt/gantt-i18n.d.ts.map +1 -1
  64. package/dist/components/reui/gantt/gantt-i18n.js +6 -1
  65. package/dist/components/reui/gantt/gantt-i18n.js.map +1 -1
  66. package/dist/components/reui/gantt/gantt-lib.d.ts +59 -2
  67. package/dist/components/reui/gantt/gantt-lib.d.ts.map +1 -1
  68. package/dist/components/reui/gantt/gantt-lib.js +67 -2
  69. package/dist/components/reui/gantt/gantt-lib.js.map +1 -1
  70. package/dist/components/reui/gantt/gantt-recurrence.js +3 -3
  71. package/dist/components/reui/gantt/gantt-recurrence.js.map +1 -1
  72. package/dist/components/reui/gantt/gantt-types.d.ts +32 -1
  73. package/dist/components/reui/gantt/gantt-types.d.ts.map +1 -1
  74. package/dist/components/reui/gantt/gantt-view.d.ts.map +1 -1
  75. package/dist/components/reui/gantt/gantt-view.js +324 -35
  76. package/dist/components/reui/gantt/gantt-view.js.map +1 -1
  77. package/dist/components/reui/gantt/gantt.d.ts +71 -2
  78. package/dist/components/reui/gantt/gantt.d.ts.map +1 -1
  79. package/dist/components/reui/gantt/gantt.js +8 -0
  80. package/dist/components/reui/gantt/gantt.js.map +1 -1
  81. package/dist/components/ui/badge.d.ts +1 -1
  82. package/dist/components/ui/bubble.d.ts +1 -1
  83. package/dist/components/ui/button.d.ts +1 -1
  84. package/dist/components/ui/item.d.ts +1 -1
  85. package/dist/components/ui/marker.d.ts +1 -1
  86. package/dist/components/ui/tabs.d.ts +1 -1
  87. package/dist/context-BizvUNZv.js +298 -0
  88. package/dist/context-BizvUNZv.js.map +1 -0
  89. package/dist/{copy-menu-1FKoMc9o.js → copy-menu-C5GaT4Z-.js} +67 -2
  90. package/dist/copy-menu-C5GaT4Z-.js.map +1 -0
  91. package/dist/hooks/use-on-open.d.ts +18 -0
  92. package/dist/hooks/use-on-open.d.ts.map +1 -0
  93. package/dist/hooks/use-on-open.js +27 -0
  94. package/dist/hooks/use-on-open.js.map +1 -0
  95. package/dist/hooks/use-row-cursor.d.ts +39 -0
  96. package/dist/hooks/use-row-cursor.d.ts.map +1 -0
  97. package/dist/hooks/use-row-cursor.js +77 -0
  98. package/dist/hooks/use-row-cursor.js.map +1 -0
  99. package/dist/types-smkWN_7x.d.ts.map +1 -1
  100. package/package.json +7 -13
  101. package/dist/components/motion/combobox/context.js.map +0 -1
  102. package/dist/copy-menu-1FKoMc9o.js.map +0 -1
@@ -0,0 +1,1150 @@
1
+ "use client";
2
+ import { Button } from "../../ui/button.js";
3
+ import { ansiToLines, highlightCode, markdownCodeProps, markdownFences, parseUnifiedDiff, resolveCodeBlockLanguage, stripNotationComments, toPlainLines } from "./code-block-highlight.js";
4
+ import { Children, createContext, isValidElement, memo, useCallback, useContext, useDeferredValue, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
5
+ import { cn } from "@kumix/utils";
6
+ import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
7
+ //#region src/components/reui/code-block/code-block.tsx
8
+ /** biome-ignore-all assist/source/organizeImports: <> */
9
+ const CodeBlockConfigContext = createContext(null);
10
+ const CodeBlockDocumentContext = createContext(null);
11
+ /** Lets the copy button tell a header placement from a floating one. */
12
+ const CodeBlockHeaderContext = createContext(false);
13
+ /**
14
+ * The root prepares every prop the code surface needs and publishes the
15
+ * bundle here. `CodeBlockContent` reads it to render the surface wherever the
16
+ * consumer composed it - typically inside their own ScrollArea - and the root
17
+ * renders its built-in scrolling surface only when no `CodeBlockContent` is
18
+ * found among its children.
19
+ */
20
+ const CodeBlockSurfacePropsContext = createContext(null);
21
+ const CodeBlockActionsContext = createContext(null);
22
+ const useIsoLayoutEffect = typeof window !== "undefined" ? useLayoutEffect : useEffect;
23
+ function useInternalConfig(part) {
24
+ const context = useContext(CodeBlockConfigContext);
25
+ if (!context) throw new Error(`${part} must be used within a CodeBlock`);
26
+ return context;
27
+ }
28
+ function useCodeBlockConfig(part) {
29
+ const context = useContext(CodeBlockConfigContext);
30
+ const document = useContext(CodeBlockDocumentContext);
31
+ if (!context || !document) throw new Error(`${part} must be used within a CodeBlock`);
32
+ return useMemo(() => ({
33
+ ...context,
34
+ code: document.code
35
+ }), [context, document.code]);
36
+ }
37
+ const ROOT_GHOST_CLASS = "[--code-block-bg:transparent]";
38
+ const ROOT_RADIUS_CLASS = "[--code-block-radius:var(--radius-lg)]";
39
+ const ROOT_TOKEN_CLASS = [
40
+ "[--code-block-padding:--spacing(3)]",
41
+ "[--code-block-gutter-width:--spacing(9)]",
42
+ "[--code-block-gutter-gap:--spacing(2.5)]",
43
+ "[--code-block-fold-width:--spacing(4.5)]",
44
+ "[--code-block-number-pad:var(--code-block-gutter-gap)]",
45
+ "data-[gutter-channel]:[--code-block-number-pad:calc(var(--code-block-gutter-gap)+var(--code-block-fold-width))]",
46
+ "data-[has-diff]:[--code-block-gutter-gap:--spacing(4)]",
47
+ "[--code-block-line-height:1.5rem]",
48
+ "[--code-block-font-size:0.8125rem]",
49
+ "[--code-block-copy-inset:--spacing(2)]",
50
+ "[--code-block-header-height:--spacing(9)]",
51
+ "[--code-block-copy-top:var(--code-block-copy-inset)]",
52
+ "data-[has-header]:[--code-block-copy-top:calc(var(--code-block-header-height)+1px+var(--code-block-copy-inset))]",
53
+ "[--code-block-expand-clearance:--spacing(9)]",
54
+ "[--code-block-bg:var(--card)]",
55
+ "[--code-block-highlight-bg:color-mix(in_oklch,var(--primary)_6%,transparent)]",
56
+ "dark:[--code-block-highlight-bg:color-mix(in_oklch,var(--primary)_12%,transparent)]",
57
+ "[--code-block-highlight-bar:color-mix(in_oklch,var(--primary)_60%,transparent)]",
58
+ "[--code-block-diff-add-bg:color-mix(in_oklch,var(--success)_8%,transparent)]",
59
+ "dark:[--code-block-diff-add-bg:color-mix(in_oklch,var(--success)_12%,transparent)]",
60
+ "[--code-block-diff-remove-bg:color-mix(in_oklch,var(--destructive)_8%,transparent)]",
61
+ "dark:[--code-block-diff-remove-bg:color-mix(in_oklch,var(--destructive)_12%,transparent)]",
62
+ "[--code-block-error-bg:color-mix(in_oklch,var(--destructive)_8%,transparent)]",
63
+ "dark:[--code-block-error-bg:color-mix(in_oklch,var(--destructive)_12%,transparent)]",
64
+ "[--code-block-warning-bg:color-mix(in_oklch,var(--warning)_10%,transparent)]",
65
+ "dark:[--code-block-warning-bg:color-mix(in_oklch,var(--warning)_14%,transparent)]",
66
+ "[--code-block-info-bg:color-mix(in_oklch,var(--info)_8%,transparent)]",
67
+ "dark:[--code-block-info-bg:color-mix(in_oklch,var(--info)_12%,transparent)]",
68
+ "[--code-block-caret-color:var(--primary)]"
69
+ ].join(" ");
70
+ const ROOT_BASE_CLASS = "group/code-block relative flex min-w-0 flex-col rounded-(--code-block-radius) text-left";
71
+ const ROOT_SURFACE_CLASS = "border border-border bg-card text-card-foreground bg-clip-padding";
72
+ /**
73
+ * The token colour switch: tokens carry only `--cb-c` / `--cb-cd`, and these
74
+ * two rules recolour the whole block per theme instead of a `dark:` utility on
75
+ * every span. The `color:` hint is load-bearing: `text-[var(--x)]` is
76
+ * type-ambiguous to Tailwind and emits NO rule at all, which renders as a
77
+ * highlighter that silently failed. Same reason the font size uses `length:`.
78
+ */
79
+ const TOKEN_COLOR_CLASS = "[&_[data-slot=code-block-token]]:text-[color:var(--cb-c,currentColor)] dark:[&_[data-slot=code-block-token]]:text-[color:var(--cb-cd,currentColor)]";
80
+ /**
81
+ * Line numbers are a CSS counter, never DOM: a pseudo-element cannot join a
82
+ * text selection, so copying yields exact source, and the gutter costs zero
83
+ * elements. `startLine` is a counter reset on the pre.
84
+ */
85
+ const LINE_NUMBER_CLASS = [
86
+ "[[data-code-line-numbers]_&]:before:pointer-events-none",
87
+ "[[data-code-line-numbers]_&]:before:sticky",
88
+ "[[data-code-line-numbers]_&]:before:left-0",
89
+ "[[data-code-line-numbers]_&]:before:z-10",
90
+ "[[data-code-line-numbers]_&]:before:-ml-(--code-block-gutter-width)",
91
+ "[[data-code-line-numbers]_&]:before:inline-block",
92
+ "[[data-code-line-numbers]_&]:before:w-(--code-block-gutter-width)",
93
+ "[[data-code-line-numbers]_&]:before:pl-(--code-block-padding)",
94
+ "[[data-code-line-numbers]_&]:before:pr-(--code-block-number-pad)",
95
+ "[[data-code-line-numbers]_&]:before:bg-(--code-block-bg)",
96
+ "[[data-code-line-numbers]_&]:before:text-right",
97
+ "[[data-code-line-numbers]_&]:before:tabular-nums",
98
+ "[[data-code-line-numbers]_&]:before:text-muted-foreground/50",
99
+ "[[data-code-line-numbers]_&]:before:select-none",
100
+ "[[data-code-line-numbers]_&]:before:[counter-increment:cb-line]",
101
+ "[[data-code-line-numbers]_&]:before:content-[counter(cb-line)]",
102
+ "[[data-code-line-numbers]_&[data-gutter]]:before:content-[attr(data-gutter)]",
103
+ "[[data-code-line-numbers]_&[data-gutter]]:before:whitespace-pre"
104
+ ].join(" ");
105
+ /** Diff glyphs ride in the same pseudo-element family, so they never copy. */
106
+ /**
107
+ * The diff glyph gets its own channel, centred in the left padding (no
108
+ * numbers) or in the number-to-code gap. A fixed `left-1` had ~1px of
109
+ * clearance and would land on the first character.
110
+ */
111
+ const LINE_DIFF_CLASS = [
112
+ "data-[diff]:after:absolute",
113
+ "data-[diff]:after:z-20",
114
+ "data-[diff]:after:left-0",
115
+ "data-[diff]:after:w-(--code-block-padding)",
116
+ "data-[diff]:after:text-center",
117
+ "[[data-code-line-numbers]_&]:data-[diff]:after:-left-(--code-block-gutter-gap)",
118
+ "[[data-code-line-numbers]_&]:data-[diff]:after:w-(--code-block-gutter-gap)",
119
+ "data-[diff]:after:select-none",
120
+ "data-[diff=add]:after:text-success",
121
+ "data-[diff=remove]:after:text-destructive",
122
+ "data-[diff=add]:after:content-['+']",
123
+ "data-[diff=remove]:after:content-['-']"
124
+ ].join(" ");
125
+ const LINE_STATE_CLASS = [
126
+ "data-[highlighted]:bg-(--code-block-highlight-bg)",
127
+ "data-[highlighted]:shadow-[inset_2px_0_0_0_var(--code-block-highlight-bar)]",
128
+ "data-[diff=add]:bg-(--code-block-diff-add-bg)",
129
+ "data-[diff=remove]:bg-(--code-block-diff-remove-bg)",
130
+ "data-[level=error]:bg-(--code-block-error-bg)",
131
+ "data-[level=warning]:bg-(--code-block-warning-bg)",
132
+ "data-[level=info]:bg-(--code-block-info-bg)",
133
+ "data-[selected]:bg-accent",
134
+ "[[data-selectable]_&]:data-[active]:bg-muted/40"
135
+ ].join(" ");
136
+ /**
137
+ * Focus mode dims the rest and clears on hover.
138
+ *
139
+ * Blur alone makes a snippet unreadable if the reader wanted the surrounding
140
+ * context after all, so hovering the block restores everything.
141
+ */
142
+ /**
143
+ * Motion is streaming-only and compositor-only: rows keep identity across
144
+ * chunks, so the entry animation fires once per NEW line and a static block
145
+ * never animates. Tokens deliberately do not animate (the plain tail gaining
146
+ * colour remounts them mid-read). Reduced motion disables the row entry.
147
+ */
148
+ const LINE_MOTION_CLASS = "[[data-streaming]_&]:animate-in [[data-streaming]_&]:fade-in-0 [[data-streaming]_&]:slide-in-from-bottom-1 [[data-streaming]_&]:duration-150 [[data-streaming]_&]:ease-out motion-reduce:animate-none";
149
+ /**
150
+ * Deliberately no per-token animation. The highlighter runs a chunk behind
151
+ * the stream and REPLACES the plain-text fallback lines with tokenised ones,
152
+ * which remounts every token span; a mount-keyed fade therefore re-flashed
153
+ * whole lines that were already readable, 300ms behind the caret. Colour
154
+ * arriving instantly reads as highlighting; re-fading reads as a glitch.
155
+ */
156
+ const TOKEN_MOTION_CLASS = "";
157
+ const LINE_FOCUS_CLASS = "data-[blurred]:opacity-40 data-[blurred]:blur-[1.5px] data-[blurred]:transition-[opacity,filter] group-hover/code-block:data-[blurred]:opacity-100 group-hover/code-block:data-[blurred]:blur-none";
158
+ /**
159
+ * `data-code-line`, not `data-line`: rehype-pretty-code apps ship a global
160
+ * `[data-line] span { color !important }` rule, and reusing its attribute
161
+ * rendered every token monochrome. Cost a real investigation.
162
+ */
163
+ const LINE_BASE_CLASS = cn("relative block min-h-(--code-block-line-height) w-full px-(--code-block-padding) leading-(--code-block-line-height)", "[[data-code-line-numbers]_&]:pl-0");
164
+ const INDENT_RE = /^[ \t]*/;
165
+ /**
166
+ * Regions come from indentation, not the grammar: shiki returns tokens, no
167
+ * AST, and indentation is language-agnostic where a brace matcher is not.
168
+ * A tab counts as two columns; only self-consistency matters.
169
+ */
170
+ function computeFoldRegions(lines) {
171
+ const indent = (text) => (INDENT_RE.exec(text)?.[0] ?? "").replace(/\t/g, " ").length;
172
+ const blank = (text) => text.trim().length === 0;
173
+ const regions = [];
174
+ const stack = [];
175
+ let previous = null;
176
+ for (const line of lines) {
177
+ if (blank(line.text)) continue;
178
+ const own = indent(line.text);
179
+ while (stack.length && own <= stack[stack.length - 1].indent) {
180
+ const open = stack.pop();
181
+ if (open.last > open.start) regions.push({
182
+ start: open.start,
183
+ end: open.last
184
+ });
185
+ }
186
+ for (const open of stack) open.last = line.number;
187
+ if (previous && own > previous.indent) stack.push({
188
+ start: previous.number,
189
+ indent: previous.indent,
190
+ last: line.number
191
+ });
192
+ previous = {
193
+ number: line.number,
194
+ indent: own
195
+ };
196
+ }
197
+ while (stack.length) {
198
+ const open = stack.pop();
199
+ if (open.last > open.start) regions.push({
200
+ start: open.start,
201
+ end: open.last
202
+ });
203
+ }
204
+ return regions.sort((a, b) => a.start - b.start);
205
+ }
206
+ /** Frozen so the disabled path keeps a stable identity across renders. */
207
+ const EMPTY_FOLD_REGIONS = [];
208
+ function tokenStyle(token) {
209
+ if (!token.color && !token.colorDark && !token.fontStyle) return void 0;
210
+ const style = {};
211
+ if (token.color) style["--cb-c"] = token.color;
212
+ if (token.colorDark) style["--cb-cd"] = token.colorDark;
213
+ if (token.fontStyle === "italic") style.fontStyle = "italic";
214
+ if (token.fontStyle === "bold") style.fontWeight = 700;
215
+ if (token.fontStyle === "underline") style.textDecoration = "underline";
216
+ return style;
217
+ }
218
+ function CodeBlockTokens({ tokens }) {
219
+ return /* @__PURE__ */ jsx(Fragment$1, { children: tokens.map((token, index) => {
220
+ const style = tokenStyle(token);
221
+ if (!style && !token.word) return /* @__PURE__ */ jsx("span", { children: token.content }, index);
222
+ return /* @__PURE__ */ jsx("span", {
223
+ "data-slot": "code-block-token",
224
+ "data-word": token.word || void 0,
225
+ className: cn(token.word && "rounded-sm bg-primary/10 px-0.5 py-px ring-1 ring-primary/20 ring-inset"),
226
+ style,
227
+ children: token.content
228
+ }, index);
229
+ }) });
230
+ }
231
+ /**
232
+ * Plain reference-equality `memo`, on purpose: the highlighter returns the
233
+ * SAME object for an unchanged line, so a streamed chunk re-renders one row.
234
+ * A custom comparator would spend that win walking every token.
235
+ */
236
+ const CodeBlockLineRow = memo(function CodeBlockLineRow({ line, selectable, selected, focusMode, active, caret, actions, actionsSide = "end", domIdBase, startLine = 1, onSelect, foldRegion, folded, onToggleFold }) {
237
+ const state = line.state;
238
+ const blurred = focusMode && !state?.focused;
239
+ const lineDomId = domIdBase ? `${domIdBase}-L${line.number}` : void 0;
240
+ const hiddenCount = foldRegion ? foldRegion.end - foldRegion.start : 0;
241
+ const inGutter = actionsSide === "gutter" && !foldRegion;
242
+ return /* @__PURE__ */ jsxs("span", {
243
+ "data-slot": "code-block-line",
244
+ "data-code-line": line.number,
245
+ "data-gutter": line.gutter,
246
+ id: lineDomId,
247
+ "data-active": active || void 0,
248
+ "data-highlighted": state?.highlighted || void 0,
249
+ "data-diff": state?.diff,
250
+ "data-focused": state?.focused || void 0,
251
+ "data-blurred": blurred || void 0,
252
+ "data-level": state?.level,
253
+ "data-selected": selected || void 0,
254
+ role: selectable ? "option" : void 0,
255
+ "aria-selected": selectable ? selected : void 0,
256
+ tabIndex: selectable ? -1 : void 0,
257
+ onMouseDown: selectable ? (event) => {
258
+ if (event.shiftKey) event.preventDefault();
259
+ } : void 0,
260
+ onClick: selectable && onSelect ? (event) => onSelect(line.number, event.shiftKey) : void 0,
261
+ className: cn(LINE_BASE_CLASS, LINE_NUMBER_CLASS, LINE_STATE_CLASS, LINE_DIFF_CLASS, LINE_FOCUS_CLASS, LINE_MOTION_CLASS, selectable && "cursor-pointer"),
262
+ /**
263
+ * Every row re-seeds the counter, making its number absolute rather
264
+ * than ordinal. That serves two features at once: folding can remove
265
+ * rows without renumbering the tail, and `content-visibility` can skip
266
+ * offscreen rows - a style-contained row cannot read a shared counter,
267
+ * which once rendered every gutter number as 1.
268
+ */
269
+ style: { counterReset: `cb-line ${line.number - 1}` },
270
+ children: [
271
+ foldRegion && onToggleFold ? /* @__PURE__ */ jsx("button", {
272
+ type: "button",
273
+ tabIndex: selectable ? -1 : void 0,
274
+ "data-slot": "code-block-fold-toggle",
275
+ "data-state": folded ? "folded" : "unfolded",
276
+ "aria-expanded": !folded,
277
+ "aria-label": folded ? `Unfold lines ${foldRegion.start + startLine - 1} to ${foldRegion.end + startLine - 1}` : `Fold lines ${foldRegion.start + startLine - 1} to ${foldRegion.end + startLine - 1}`,
278
+ onClick: (event) => {
279
+ event.stopPropagation();
280
+ onToggleFold(foldRegion.start);
281
+ },
282
+ className: cn("sticky z-20 inline-flex size-(--code-block-fold-width) shrink-0 translate-y-[calc((var(--code-block-line-height)-var(--code-block-fold-width))/2)] cursor-pointer items-center justify-center rounded-[4px] align-top text-muted-foreground outline-none hover:bg-muted hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50", "-ml-[calc(var(--code-block-fold-width)+0.25rem)]", "mr-[0.25rem]", "left-[calc(var(--code-block-gutter-width)-var(--code-block-fold-width)-0.25rem)]", folded && "text-muted-foreground/60"),
283
+ children: /* @__PURE__ */ jsx("svg", {
284
+ "aria-hidden": "true",
285
+ viewBox: "0 0 24 24",
286
+ fill: "none",
287
+ stroke: "currentColor",
288
+ strokeWidth: "2.5",
289
+ strokeLinecap: "round",
290
+ strokeLinejoin: "round",
291
+ className: "size-3",
292
+ children: /* @__PURE__ */ jsx("path", { d: folded ? "m9 18 6-6-6-6" : "m6 9 6 6 6-6" })
293
+ })
294
+ }) : null,
295
+ actions && active ? /* @__PURE__ */ jsx("span", {
296
+ "data-slot": "code-block-line-actions",
297
+ "data-side": inGutter ? "gutter" : "end",
298
+ contentEditable: false,
299
+ onClick: (event) => event.stopPropagation(),
300
+ className: cn("z-20 select-none items-center gap-1 whitespace-normal font-sans text-foreground", !inGutter && "absolute end-2 top-0 flex h-(--code-block-line-height)", inGutter && "absolute top-1/2 left-0 flex -translate-x-1/2 -translate-y-1/2 items-center justify-center"),
301
+ children: actions({
302
+ line: line.number,
303
+ text: line.text,
304
+ state
305
+ })
306
+ }) : null,
307
+ /* @__PURE__ */ jsxs("span", {
308
+ "data-slot": "code-block-line-content",
309
+ children: [
310
+ line.tokens.length === 0 ? /* @__PURE__ */ jsx("br", {}) : null,
311
+ /* @__PURE__ */ jsx(CodeBlockTokens, { tokens: line.tokens }),
312
+ folded && hiddenCount > 0 ? /* @__PURE__ */ jsx("button", {
313
+ type: "button",
314
+ tabIndex: selectable ? -1 : void 0,
315
+ "data-slot": "code-block-fold-marker",
316
+ "aria-label": `Unfold ${hiddenCount} hidden lines`,
317
+ onClick: (event) => {
318
+ event.stopPropagation();
319
+ onToggleFold?.(line.number);
320
+ },
321
+ className: "ml-2 inline-flex h-(--code-block-fold-width) translate-y-[calc((var(--code-block-line-height)-var(--code-block-fold-width))/2)] cursor-pointer select-none items-center rounded-sm bg-muted/80 px-1.5 align-top text-[0.8em] text-muted-foreground leading-none hover:bg-muted",
322
+ children: `... ${hiddenCount} lines`
323
+ }) : null,
324
+ caret ? /* @__PURE__ */ jsx("span", {
325
+ "data-slot": "code-block-caret",
326
+ "aria-hidden": "true",
327
+ className: "ml-0.5 inline-block h-[0.12em] w-[0.55em] translate-y-[0.02em] animate-pulse rounded-[1px] bg-(--code-block-caret-color) motion-reduce:animate-none"
328
+ }) : null
329
+ ]
330
+ })
331
+ ]
332
+ });
333
+ });
334
+ /**
335
+ * The root. `<CodeBlock code={code} language="tsx" />` is a complete block;
336
+ * passing `lines` from a server component skips the client highlighter and
337
+ * shiki entirely. Children are CHROME ONLY: the root renders the code surface
338
+ * itself, so child order never matters and a wrapper cannot break scrolling.
339
+ */
340
+ function CodeBlock({ code, language, lines: linesProp, themes, highlight = true, showLineNumbers = false, startLine = 1, wrap: wrapProp, defaultWrap = false, onWrapChange, maxLines, variant = "default", label, highlightedLines, highlightedWords, focusedLines, diff, lineLevels, transformers, streaming = false, selectable = false, selectedLines, defaultSelectedLines, onSelectedLinesChange, completeAnnouncement, expanded: expandedProp, defaultExpanded = false, onExpandedChange, foldable = false, foldRegions: foldRegionsProp, folded, defaultFolded, onFoldedChange, className, children, ...props }) {
341
+ const contentId = useId();
342
+ const source = code ?? "";
343
+ const resolvedLanguage = resolveCodeBlockLanguage(language);
344
+ const deferredSource = useDeferredValue(source);
345
+ const plainLines = useMemo(() => toPlainLines(deferredSource, startLine), [deferredSource, startLine]);
346
+ const [highlighted, setHighlighted] = useState(null);
347
+ const shouldHighlight = !linesProp && highlight && Boolean(resolvedLanguage) && source.length > 0;
348
+ const specKey = JSON.stringify([
349
+ themes ?? null,
350
+ startLine,
351
+ highlightedLines ?? null,
352
+ highlightedWords ?? null,
353
+ focusedLines ?? null,
354
+ diff ?? null,
355
+ lineLevels ?? null
356
+ ]);
357
+ const transformersWarnedRef = useRef(false);
358
+ const previousTransformersRef = useRef(transformers);
359
+ useEffect(() => {
360
+ if (process.env.NODE_ENV !== "production" && streaming && previousTransformersRef.current !== transformers && !transformersWarnedRef.current) {
361
+ transformersWarnedRef.current = true;
362
+ console.warn("[code-block] `transformers` changed identity during a stream, which re-tokenizes the whole document per chunk. Hoist the array to module scope or memoize it.");
363
+ }
364
+ previousTransformersRef.current = transformers;
365
+ }, [transformers, streaming]);
366
+ useEffect(() => {
367
+ if (!shouldHighlight) {
368
+ setHighlighted(null);
369
+ return;
370
+ }
371
+ const [specThemes, specStartLine, specHighlightedLines, specHighlightedWords, specFocusedLines, specDiff, specLineLevels] = JSON.parse(specKey);
372
+ let active = true;
373
+ highlightCode(deferredSource, {
374
+ language,
375
+ instanceKey: contentId,
376
+ themes: specThemes ?? void 0,
377
+ transformers,
378
+ startLine: specStartLine,
379
+ highlightedLines: specHighlightedLines ?? void 0,
380
+ highlightedWords: specHighlightedWords ?? void 0,
381
+ focusedLines: specFocusedLines ?? void 0,
382
+ diff: specDiff ?? void 0,
383
+ lineLevels: specLineLevels ?? void 0
384
+ }).then((next) => {
385
+ if (active) setHighlighted({
386
+ source: deferredSource,
387
+ spec: specKey,
388
+ lines: next
389
+ });
390
+ });
391
+ return () => {
392
+ active = false;
393
+ };
394
+ }, [
395
+ shouldHighlight,
396
+ deferredSource,
397
+ language,
398
+ transformers,
399
+ specKey
400
+ ]);
401
+ const lines = useMemo(() => {
402
+ if (linesProp) return linesProp;
403
+ if (!shouldHighlight || !highlighted) return plainLines;
404
+ if (highlighted.spec !== specKey || !deferredSource.startsWith(highlighted.source)) return plainLines;
405
+ if (highlighted.lines.length >= plainLines.length) return highlighted.lines;
406
+ return [...highlighted.lines, ...plainLines.slice(highlighted.lines.length)];
407
+ }, [
408
+ linesProp,
409
+ shouldHighlight,
410
+ highlighted,
411
+ plainLines,
412
+ deferredSource,
413
+ specKey
414
+ ]);
415
+ const focusMode = useMemo(() => lines.some((line) => line.state?.focused), [lines]);
416
+ const hasDiff = useMemo(() => lines.some((line) => line.state?.diff), [lines]);
417
+ const [internalWrap, setInternalWrap] = useState(defaultWrap);
418
+ const wrap = wrapProp ?? internalWrap;
419
+ const setWrap = useCallback((next) => {
420
+ if (wrapProp === void 0) setInternalWrap(next);
421
+ onWrapChange?.(next);
422
+ }, [wrapProp, onWrapChange]);
423
+ const collapsible = typeof maxLines === "number" && lines.length > maxLines;
424
+ const [internalExpanded, setInternalExpanded] = useState(defaultExpanded);
425
+ const expanded = expandedProp ?? internalExpanded;
426
+ const setExpanded = useCallback((next) => {
427
+ if (expandedProp === void 0) setInternalExpanded(next);
428
+ onExpandedChange?.(next);
429
+ }, [expandedProp, onExpandedChange]);
430
+ const isExpanded = collapsible ? expanded : true;
431
+ const [internalSelected, setInternalSelected] = useState(defaultSelectedLines ?? []);
432
+ const selection = selectedLines ?? internalSelected;
433
+ const selectedSet = useMemo(() => new Set(selection), [selection]);
434
+ const lastSelectedRef = useRef(null);
435
+ const selectionStateRef = useRef({
436
+ selection,
437
+ selectedSet,
438
+ controlled: selectedLines !== void 0,
439
+ onSelectedLinesChange
440
+ });
441
+ selectionStateRef.current = {
442
+ selection,
443
+ selectedSet,
444
+ controlled: selectedLines !== void 0,
445
+ onSelectedLinesChange
446
+ };
447
+ const commitSelection = useCallback((next) => {
448
+ if (!selectionStateRef.current.controlled) setInternalSelected(next);
449
+ selectionStateRef.current.onSelectedLinesChange?.(next);
450
+ }, []);
451
+ const toggleLine = useCallback((line, extend) => {
452
+ const anchor = lastSelectedRef.current;
453
+ const { selection, selectedSet } = selectionStateRef.current;
454
+ if (extend && anchor !== null) {
455
+ const from = Math.min(anchor, line);
456
+ const to = Math.max(anchor, line);
457
+ const range = [];
458
+ for (let value = from; value <= to; value += 1) range.push(value);
459
+ commitSelection(range);
460
+ return;
461
+ }
462
+ lastSelectedRef.current = line;
463
+ commitSelection(selectedSet.has(line) ? selection.filter((value) => value !== line) : [...selection, line].sort((a, b) => a - b));
464
+ }, [commitSelection]);
465
+ const foldRegions = useMemo(() => {
466
+ if (!foldable) return EMPTY_FOLD_REGIONS;
467
+ if (foldRegionsProp) return foldRegionsProp;
468
+ return computeFoldRegions(lines).map((region) => ({
469
+ start: region.start - startLine + 1,
470
+ end: region.end - startLine + 1
471
+ }));
472
+ }, [
473
+ foldable,
474
+ foldRegionsProp,
475
+ lines,
476
+ startLine
477
+ ]);
478
+ const foldStarts = useMemo(() => new Map(foldRegions.map((region) => [region.start, region])), [foldRegions]);
479
+ const [internalFolded, setInternalFolded] = useState(defaultFolded ?? []);
480
+ const foldedValue = folded ?? internalFolded;
481
+ const foldedSet = useMemo(() => new Set(foldedValue), [foldedValue]);
482
+ const foldStateRef = useRef({
483
+ foldedValue,
484
+ foldedSet,
485
+ controlled: folded !== void 0,
486
+ onFoldedChange
487
+ });
488
+ foldStateRef.current = {
489
+ foldedValue,
490
+ foldedSet,
491
+ controlled: folded !== void 0,
492
+ onFoldedChange
493
+ };
494
+ const commitFolded = useCallback((next) => {
495
+ if (!foldStateRef.current.controlled) setInternalFolded(next);
496
+ foldStateRef.current.onFoldedChange?.(next);
497
+ }, []);
498
+ const toggleFold = useCallback((start) => {
499
+ const { foldedValue, foldedSet } = foldStateRef.current;
500
+ commitFolded(foldedSet.has(start) ? foldedValue.filter((value) => value !== start) : [...foldedValue, start].sort((a, b) => a - b));
501
+ }, [commitFolded]);
502
+ /**
503
+ * A line is hidden when ANY folded region covers it, and that one rule is
504
+ * what makes nesting work without a tree: folding an outer region swallows
505
+ * the inner toggles as well, their own folded state survives untouched
506
+ * underneath, and unfolding the outer one restores exactly what the reader
507
+ * left behind rather than a flattened block.
508
+ */
509
+ const renderedLines = useMemo(() => {
510
+ if (!foldable || foldedSet.size === 0) return lines;
511
+ const hidden = /* @__PURE__ */ new Set();
512
+ for (const start of foldedSet) {
513
+ const region = foldStarts.get(start);
514
+ if (!region) continue;
515
+ for (let n = region.start + 1; n <= region.end; n += 1) hidden.add(n + startLine - 1);
516
+ }
517
+ return lines.filter((line) => !hidden.has(line.number));
518
+ }, [
519
+ foldable,
520
+ foldedSet,
521
+ foldStarts,
522
+ lines,
523
+ startLine
524
+ ]);
525
+ const configValue = useMemo(() => ({
526
+ language,
527
+ resolvedLanguage,
528
+ showLineNumbers,
529
+ wrap,
530
+ setWrap,
531
+ wrapControlled: wrapProp !== void 0,
532
+ expanded: isExpanded,
533
+ setExpanded,
534
+ collapsible,
535
+ streaming,
536
+ contentId
537
+ }), [
538
+ language,
539
+ resolvedLanguage,
540
+ showLineNumbers,
541
+ wrap,
542
+ setWrap,
543
+ wrapProp,
544
+ isExpanded,
545
+ collapsible,
546
+ streaming,
547
+ contentId
548
+ ]);
549
+ const clearSelection = useCallback(() => commitSelection([]), [commitSelection]);
550
+ const documentValue = useMemo(() => ({
551
+ code: source,
552
+ lines,
553
+ selected: selectedSet,
554
+ selectable,
555
+ toggleLine,
556
+ clearSelection,
557
+ foldable,
558
+ foldRegions,
559
+ folded: foldedSet,
560
+ toggleFold,
561
+ setFolded: commitFolded
562
+ }), [
563
+ source,
564
+ lines,
565
+ selectedSet,
566
+ selectable,
567
+ toggleLine,
568
+ clearSelection,
569
+ foldable,
570
+ foldRegions,
571
+ foldedSet,
572
+ toggleFold,
573
+ commitFolded
574
+ ]);
575
+ const visibleLines = collapsible && !isExpanded ? maxLines : void 0;
576
+ const hasHeader = containsElementType(children, CodeBlockHeader);
577
+ const [lineActions, setLineActions] = useState(null);
578
+ const [actionsSide, setActionsSide] = useState("end");
579
+ const actionsOwnerRef = useRef(null);
580
+ const actionsRegistry = useMemo(() => ({ register: (owner, render, side = "end") => {
581
+ if (render) {
582
+ if (process.env.NODE_ENV !== "production" && actionsOwnerRef.current && actionsOwnerRef.current !== owner) console.warn("[code-block] Two CodeBlockLineActions are mounted; the block renders ONE action group and the later mount replaces the earlier one.");
583
+ actionsOwnerRef.current = owner;
584
+ } else if (actionsOwnerRef.current !== owner) return;
585
+ else actionsOwnerRef.current = null;
586
+ setLineActions(() => render);
587
+ setActionsSide(side);
588
+ } }), []);
589
+ const gutterChannel = foldable;
590
+ const hasContent = containsElementType(children, CodeBlockContent);
591
+ const surfaceProps = {
592
+ lines: renderedLines,
593
+ gutterMax: lines[lines.length - 1]?.number ?? startLine,
594
+ foldable,
595
+ gutterChannel,
596
+ actionsSide,
597
+ foldStarts,
598
+ foldedSet,
599
+ onToggleFold: toggleFold,
600
+ expandClearance: collapsible && isExpanded,
601
+ wrap,
602
+ startLine,
603
+ showLineNumbers,
604
+ focusMode,
605
+ selectable,
606
+ selectedSet,
607
+ toggleLine,
608
+ visibleLines,
609
+ streaming,
610
+ label: label ?? (language ? `${language} code` : "Code"),
611
+ contentId,
612
+ actions: lineActions,
613
+ completeAnnouncement,
614
+ builtInSurfaceRendered: !hasContent
615
+ };
616
+ return /* @__PURE__ */ jsx(CodeBlockConfigContext.Provider, {
617
+ value: configValue,
618
+ children: /* @__PURE__ */ jsx(CodeBlockDocumentContext.Provider, {
619
+ value: documentValue,
620
+ children: /* @__PURE__ */ jsx(CodeBlockActionsContext.Provider, {
621
+ value: actionsRegistry,
622
+ children: /* @__PURE__ */ jsx("div", {
623
+ "data-slot": "code-block",
624
+ "data-variant": variant,
625
+ "data-streaming": streaming || void 0,
626
+ "data-has-diff": hasDiff || void 0,
627
+ "data-foldable": foldable || void 0,
628
+ "data-gutter-channel": gutterChannel || void 0,
629
+ "data-has-header": hasHeader || void 0,
630
+ className: cn(ROOT_BASE_CLASS, ROOT_RADIUS_CLASS, ROOT_TOKEN_CLASS, variant === "default" && ROOT_SURFACE_CLASS, variant === "ghost" && ROOT_GHOST_CLASS, className),
631
+ ...props,
632
+ children: /* @__PURE__ */ jsxs(CodeBlockSurfacePropsContext.Provider, {
633
+ value: surfaceProps,
634
+ children: [children, !hasContent && /* @__PURE__ */ jsx(CodeBlockSurface, { ...surfaceProps })]
635
+ })
636
+ })
637
+ })
638
+ })
639
+ });
640
+ }
641
+ /**
642
+ * The code surface as a composable part: inside your own ScrollArea the block
643
+ * stops scrolling internally and the ancestor owns both axes (`maxLines`'
644
+ * height cap no longer applies). Omitted, the root renders the same surface
645
+ * itself, exactly as before.
646
+ */
647
+ function CodeBlockContent({ className }) {
648
+ const surface = useContext(CodeBlockSurfacePropsContext);
649
+ if (!surface) throw new Error("CodeBlockContent must be used within a CodeBlock");
650
+ useEffect(() => {
651
+ if (process.env.NODE_ENV === "production") return;
652
+ if (surface.builtInSurfaceRendered) console.error("CodeBlockContent is hidden behind a component boundary, so CodeBlock also rendered its built-in surface and the code appears twice. Compose <CodeBlockContent /> directly in the CodeBlock's children (plain wrappers like a ScrollArea are fine).");
653
+ }, [surface.builtInSurfaceRendered]);
654
+ return /* @__PURE__ */ jsx(CodeBlockSurface, {
655
+ ...surface,
656
+ scroll: false,
657
+ className
658
+ });
659
+ }
660
+ /**
661
+ * Sees through plain element wrappers (a ScrollArea, a div) but not through a
662
+ * consumer's own component boundary - unrendered children are opaque. Compose
663
+ * `CodeBlockContent` directly in the block's subtree.
664
+ */
665
+ function containsElementType(node, type) {
666
+ for (const child of Children.toArray(node)) {
667
+ if (!isValidElement(child)) continue;
668
+ if (child.type === type) return true;
669
+ const inner = child.props.children;
670
+ if (inner && containsElementType(inner, type)) return true;
671
+ }
672
+ return false;
673
+ }
674
+ function CodeBlockSurface({ lines, wrap, startLine, showLineNumbers, focusMode, selectable, selectedSet, toggleLine, visibleLines, gutterMax, foldable, gutterChannel, actionsSide, foldStarts, foldedSet, onToggleFold, expandClearance, streaming, label, contentId, actions, completeAnnouncement, scroll = true, className }) {
675
+ const viewportRef = useRef(null);
676
+ const preRef = useRef(null);
677
+ const [activeLine, setActiveLine] = useState(null);
678
+ const stickRef = useRef(true);
679
+ const [announcement, setAnnouncement] = useState("");
680
+ const wasStreaming = useRef(streaming);
681
+ useEffect(() => {
682
+ if (wasStreaming.current && !streaming) setAnnouncement(completeAnnouncement ?? `Code generation complete, ${lines.length} lines.`);
683
+ wasStreaming.current = streaming;
684
+ }, [
685
+ streaming,
686
+ lines.length,
687
+ completeAnnouncement
688
+ ]);
689
+ const resolveScroller = useCallback(() => {
690
+ const viewport = viewportRef.current;
691
+ if (!viewport) return null;
692
+ if (viewport.scrollHeight > viewport.clientHeight + 1) return viewport;
693
+ let node = viewport.parentElement;
694
+ while (node && node !== document.body) {
695
+ const overflowY = getComputedStyle(node).overflowY;
696
+ if ((overflowY === "auto" || overflowY === "scroll" || overflowY === "overlay") && node.scrollHeight > node.clientHeight + 1) return node;
697
+ node = node.parentElement;
698
+ }
699
+ const page = document.scrollingElement;
700
+ if (page && page.scrollHeight > page.clientHeight + 1) return page;
701
+ return viewport;
702
+ }, []);
703
+ const handleScroll = useCallback(() => {
704
+ const viewport = viewportRef.current;
705
+ if (!viewport) return;
706
+ const distance = viewport.scrollHeight - viewport.scrollTop - viewport.clientHeight;
707
+ stickRef.current = distance < 24;
708
+ }, []);
709
+ useEffect(() => {
710
+ if (!streaming) return;
711
+ const scroller = resolveScroller();
712
+ if (!scroller || scroller === viewportRef.current) return;
713
+ const onScroll = () => {
714
+ const distance = scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight;
715
+ stickRef.current = distance < 24;
716
+ };
717
+ const target = scroller === document.scrollingElement ? window : scroller;
718
+ target.addEventListener("scroll", onScroll, { passive: true });
719
+ return () => target.removeEventListener("scroll", onScroll);
720
+ }, [
721
+ streaming,
722
+ lines.length,
723
+ resolveScroller
724
+ ]);
725
+ useIsoLayoutEffect(() => {
726
+ if (!streaming || !stickRef.current) return;
727
+ const scroller = resolveScroller();
728
+ if (scroller) scroller.scrollTop = scroller.scrollHeight;
729
+ }, [
730
+ lines,
731
+ streaming,
732
+ resolveScroller
733
+ ]);
734
+ const trackActive = useCallback((event) => {
735
+ if (!actions && !selectable) return;
736
+ const value = (event.target?.closest?.("[data-code-line]"))?.getAttribute("data-code-line");
737
+ if (!value) return;
738
+ setActiveLine(Number(value));
739
+ }, [actions, selectable]);
740
+ const clearActive = useCallback(() => setActiveLine(null), []);
741
+ const toggleDisplayed = useCallback((displayed, extend) => toggleLine(displayed - startLine + 1, extend), [toggleLine, startLine]);
742
+ const handleKeyDown = useCallback((event) => {
743
+ if (!selectable) return;
744
+ if (event.key === "Escape") {
745
+ setActiveLine(null);
746
+ return;
747
+ }
748
+ if ((event.key === "Enter" || event.key === " ") && activeLine !== null) {
749
+ event.preventDefault();
750
+ toggleDisplayed(activeLine, event.shiftKey);
751
+ return;
752
+ }
753
+ const isArrow = event.key === "ArrowDown" || event.key === "ArrowUp";
754
+ if (!isArrow && event.key !== "Home" && event.key !== "End") return;
755
+ event.preventDefault();
756
+ let next;
757
+ if (event.key === "Home") next = lines[0]?.number ?? startLine;
758
+ else if (event.key === "End") next = lines[lines.length - 1]?.number ?? startLine;
759
+ else {
760
+ const step = event.key === "ArrowDown" ? 1 : -1;
761
+ const index = lines.findIndex((line) => line.number === activeLine);
762
+ next = lines[index === -1 ? step === 1 ? 0 : lines.length - 1 : Math.min(lines.length - 1, Math.max(0, index + step))]?.number ?? startLine;
763
+ }
764
+ setActiveLine(next);
765
+ (preRef.current?.querySelector(`[data-code-line="${next}"]`))?.scrollIntoView({ block: "nearest" });
766
+ if (isArrow && event.shiftKey) toggleDisplayed(next, true);
767
+ }, [
768
+ selectable,
769
+ lines,
770
+ startLine,
771
+ activeLine,
772
+ toggleDisplayed
773
+ ]);
774
+ const lastLineNumber = lines[lines.length - 1]?.number;
775
+ const gutterDigits = Math.max(2, String(gutterMax ?? startLine).length, ...lines.map((line) => line.gutter?.length ?? 0));
776
+ const surfaceStyle = {
777
+ "--code-block-gutter-width": gutterChannel ? `calc(${gutterDigits}ch + var(--code-block-fold-width) + var(--code-block-gutter-gap) + var(--code-block-padding))` : `calc(${gutterDigits}ch + var(--code-block-gutter-gap) + var(--code-block-padding))`,
778
+ counterReset: `cb-line ${startLine - 1}`
779
+ };
780
+ return /* @__PURE__ */ jsxs("div", {
781
+ "data-slot": "code-block-content",
782
+ className: cn("relative min-w-0 rounded-[inherit]", scroll && "flex-1 overflow-hidden"),
783
+ children: [/* @__PURE__ */ jsx("span", {
784
+ role: "status",
785
+ "aria-live": "polite",
786
+ className: "sr-only",
787
+ children: announcement
788
+ }), /* @__PURE__ */ jsx("div", {
789
+ ref: viewportRef,
790
+ "data-slot": "code-block-viewport",
791
+ id: contentId,
792
+ role: "region",
793
+ "aria-label": label,
794
+ "aria-busy": streaming || void 0,
795
+ "aria-activedescendant": selectable && activeLine !== null ? `${contentId}-L${activeLine}` : void 0,
796
+ tabIndex: 0,
797
+ onScroll: handleScroll,
798
+ onKeyDown: handleKeyDown,
799
+ className: cn("relative min-w-0 rounded-[inherit] outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50", scroll && "overflow-auto [scrollbar-width:thin]", scroll && visibleLines && "max-h-(--cb-max-height)", className),
800
+ style: scroll && visibleLines ? { "--cb-max-height": `calc(${visibleLines} * var(--code-block-line-height) + 2 * var(--code-block-padding))` } : void 0,
801
+ children: /* @__PURE__ */ jsx("pre", {
802
+ ref: preRef,
803
+ dir: "ltr",
804
+ "data-code-line-numbers": showLineNumbers || void 0,
805
+ "data-wrap": wrap || void 0,
806
+ role: selectable ? "listbox" : void 0,
807
+ "data-selectable": selectable || void 0,
808
+ "aria-multiselectable": selectable || void 0,
809
+ "aria-label": selectable ? `${label} lines` : void 0,
810
+ onPointerOver: trackActive,
811
+ onPointerLeave: clearActive,
812
+ onFocus: trackActive,
813
+ className: cn("text-(length:--code-block-font-size) w-max min-w-full py-(--code-block-padding) font-mono", TOKEN_COLOR_CLASS, TOKEN_MOTION_CLASS, wrap && "wrap-break-word w-full min-w-0 max-w-full whitespace-pre-wrap", showLineNumbers && "pl-(--code-block-gutter-width)", expandClearance && "pb-(--code-block-expand-clearance)"),
814
+ style: surfaceStyle,
815
+ children: /* @__PURE__ */ jsx("code", {
816
+ "data-slot": "code-block-code",
817
+ role: selectable ? "presentation" : void 0,
818
+ children: lines.map((line) => /* @__PURE__ */ jsx(CodeBlockLineRow, {
819
+ line,
820
+ selectable,
821
+ selected: selectedSet.has(line.number - startLine + 1),
822
+ focusMode,
823
+ active: activeLine === line.number,
824
+ caret: streaming && line.number === lastLineNumber,
825
+ actions: activeLine === line.number ? actions : null,
826
+ actionsSide,
827
+ domIdBase: contentId,
828
+ startLine,
829
+ onSelect: toggleDisplayed,
830
+ foldable,
831
+ foldRegion: foldStarts.get(line.number - startLine + 1),
832
+ folded: foldedSet.has(line.number - startLine + 1),
833
+ onToggleFold
834
+ }, line.number))
835
+ })
836
+ })
837
+ })]
838
+ });
839
+ }
840
+ /**
841
+ * Opt-in header. Absent, the block renders no chrome, so it nests in a Card or
842
+ * Frame without a doubled bar. Presence flips `data-has-header` on the root,
843
+ * detected from the element type rather than a `:has()` selector.
844
+ */
845
+ function CodeBlockHeader({ className, ...props }) {
846
+ return /* @__PURE__ */ jsx(CodeBlockHeaderContext.Provider, {
847
+ value: true,
848
+ children: /* @__PURE__ */ jsx("div", {
849
+ "data-slot": "code-block-header",
850
+ className: cn("flex min-h-9 shrink-0 items-center gap-2 border-border border-b px-3 py-0 text-sm", className),
851
+ ...props
852
+ })
853
+ });
854
+ }
855
+ function CodeBlockTitle({ className, ...props }) {
856
+ return /* @__PURE__ */ jsx("div", {
857
+ "data-slot": "code-block-title",
858
+ className: cn("min-w-0 truncate font-mono text-muted-foreground text-xs", className),
859
+ ...props
860
+ });
861
+ }
862
+ /**
863
+ * The resolved language as a label, no props needed. It shows what the
864
+ * highlighter actually resolved, so an unsupported grammar becomes visible
865
+ * instead of silently rendering plain.
866
+ */
867
+ function CodeBlockLanguage({ className, children, ...props }) {
868
+ const { language, resolvedLanguage } = useInternalConfig("CodeBlockLanguage");
869
+ const label = children ?? resolvedLanguage ?? language;
870
+ if (!label) return null;
871
+ return /* @__PURE__ */ jsx("span", {
872
+ "data-slot": "code-block-language",
873
+ "data-unsupported": !resolvedLanguage || void 0,
874
+ className: cn("inline-flex shrink-0 items-center rounded-md border border-border bg-muted/60 px-1.5 py-0.5 font-mono text-[0.6875rem] text-muted-foreground uppercase leading-none", className),
875
+ ...props,
876
+ children: label
877
+ });
878
+ }
879
+ function CopyIcon({ copied }) {
880
+ return copied ? /* @__PURE__ */ jsx("svg", {
881
+ viewBox: "0 0 24 24",
882
+ fill: "none",
883
+ stroke: "currentColor",
884
+ strokeWidth: "2",
885
+ strokeLinecap: "round",
886
+ strokeLinejoin: "round",
887
+ "aria-hidden": "true",
888
+ children: /* @__PURE__ */ jsx("path", { d: "M20 6 9 17l-5-5" })
889
+ }) : /* @__PURE__ */ jsxs("svg", {
890
+ viewBox: "0 0 24 24",
891
+ fill: "none",
892
+ stroke: "currentColor",
893
+ strokeWidth: "2",
894
+ strokeLinecap: "round",
895
+ strokeLinejoin: "round",
896
+ "aria-hidden": "true",
897
+ children: [/* @__PURE__ */ jsx("rect", {
898
+ width: "14",
899
+ height: "14",
900
+ x: "8",
901
+ y: "8",
902
+ rx: "2",
903
+ ry: "2"
904
+ }), /* @__PURE__ */ jsx("path", { d: "M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2" })]
905
+ });
906
+ }
907
+ /**
908
+ * Copy button. Inline inside a header, pinned over the surface anywhere else.
909
+ * Pinning is absolute against the root, not `position: sticky`: sticky still
910
+ * slides away under HORIZONTAL scroll, and code scrolls sideways constantly.
911
+ * Notation comments are stripped from the payload, matching what is rendered.
912
+ */
913
+ function CodeBlockCopyButton({ value, timeout = 2e3, onCopy, onCopyError, labels, position = "auto", alwaysVisible = false, className, variant = "ghost", size, children, ...props }) {
914
+ const context = useContext(CodeBlockConfigContext);
915
+ const inHeader = useContext(CodeBlockHeaderContext);
916
+ const [copied, setCopied] = useState(false);
917
+ const [copyFailed, setCopyFailed] = useState(false);
918
+ const resolvedPosition = position === "auto" ? inHeader ? "inline" : "pinned" : position;
919
+ const resolvedSize = size ?? (resolvedPosition === "inline" ? "icon-sm" : "icon");
920
+ useEffect(() => {
921
+ if (!copied || timeout === 0) return;
922
+ const id = window.setTimeout(() => setCopied(false), timeout);
923
+ return () => window.clearTimeout(id);
924
+ }, [copied, timeout]);
925
+ useEffect(() => {
926
+ if (!copyFailed) return;
927
+ const id = window.setTimeout(() => setCopyFailed(false), 2e3);
928
+ return () => window.clearTimeout(id);
929
+ }, [copyFailed]);
930
+ const document_ = useContext(CodeBlockDocumentContext);
931
+ const handleClick = useCallback(() => {
932
+ const fallback = document_?.code || document_?.lines.map((line) => line.text).join("\n");
933
+ const payload = stripNotationComments(value ?? fallback ?? "");
934
+ if (!payload) return;
935
+ if (typeof navigator === "undefined" || !navigator.clipboard?.writeText) return;
936
+ navigator.clipboard.writeText(payload).then(() => {
937
+ setCopied(true);
938
+ onCopy?.(payload);
939
+ }, (error) => {
940
+ setCopyFailed(true);
941
+ onCopyError?.(error);
942
+ });
943
+ }, [
944
+ value,
945
+ context,
946
+ document_,
947
+ onCopy,
948
+ onCopyError
949
+ ]);
950
+ return /* @__PURE__ */ jsx(Button, {
951
+ type: "button",
952
+ "data-slot": "code-block-copy",
953
+ "data-copied": copied || void 0,
954
+ "data-copy-failed": copyFailed || void 0,
955
+ "data-position": resolvedPosition,
956
+ "aria-label": copied ? labels?.copied ?? "Copied" : labels?.copy ?? "Copy code",
957
+ variant,
958
+ size: resolvedSize,
959
+ onClick: handleClick,
960
+ className: cn("shrink-0 [&_svg]:size-3.5", resolvedPosition === "pinned" && "absolute top-(--code-block-copy-top) right-(--code-block-copy-inset) z-20", resolvedPosition === "pinned" && !alwaysVisible && "opacity-0 transition-opacity focus-visible:opacity-100 group-hover/code-block:opacity-100", className),
961
+ ...props,
962
+ children: children ?? /* @__PURE__ */ jsx(CopyIcon, { copied })
963
+ });
964
+ }
965
+ function CodeBlockWrapToggle({ className, children, variant = "ghost", size = "sm", onClick, ...props }) {
966
+ const { wrap, setWrap } = useInternalConfig("CodeBlockWrapToggle");
967
+ return /* @__PURE__ */ jsx(Button, {
968
+ type: "button",
969
+ "data-slot": "code-block-wrap-toggle",
970
+ "data-state": wrap ? "on" : "off",
971
+ "aria-pressed": wrap,
972
+ variant,
973
+ size,
974
+ onClick: (event) => {
975
+ onClick?.(event);
976
+ if (!event.defaultPrevented) setWrap(!wrap);
977
+ },
978
+ className: cn("shrink-0", className),
979
+ ...props,
980
+ children: children ?? (wrap ? "No wrap" : "Wrap")
981
+ });
982
+ }
983
+ /**
984
+ * Expands a block collapsed by `maxLines`.
985
+ *
986
+ * Renders nothing when the content is shorter than the cut, so a consumer can
987
+ * always compose it without guarding on line count themselves.
988
+ */
989
+ function CodeBlockExpandButton({ className, children, variant = "ghost", size = "sm", onClick, ...props }) {
990
+ const { expanded, setExpanded, collapsible, contentId } = useInternalConfig("CodeBlockExpandButton");
991
+ if (!collapsible) return null;
992
+ return /* @__PURE__ */ jsx("div", {
993
+ "data-slot": "code-block-expand",
994
+ "data-state": expanded ? "expanded" : "collapsed",
995
+ className: cn("absolute inset-x-0 bottom-0 z-10 order-last flex items-end justify-center pt-10 pb-2", !expanded && "bg-linear-to-t from-card via-card/85 to-transparent", className),
996
+ children: /* @__PURE__ */ jsx(Button, {
997
+ type: "button",
998
+ "aria-expanded": expanded,
999
+ "aria-controls": contentId,
1000
+ variant,
1001
+ size,
1002
+ onClick: (event) => {
1003
+ onClick?.(event);
1004
+ if (!event.defaultPrevented) setExpanded(!expanded);
1005
+ },
1006
+ ...props,
1007
+ children: children ?? (expanded ? "Show less" : "Show more")
1008
+ })
1009
+ });
1010
+ }
1011
+ /**
1012
+ * Actions on the hovered or focused line. ONE group exists for the whole
1013
+ * block, rendered inside the active row: a 2,000 line file mounts one button
1014
+ * group, not 2,000.
1015
+ */
1016
+ const LANGUAGE_EXTENSIONS = {
1017
+ bash: "sh",
1018
+ c: "c",
1019
+ cpp: "cpp",
1020
+ csharp: "cs",
1021
+ css: "css",
1022
+ diff: "patch",
1023
+ docker: "dockerfile",
1024
+ go: "go",
1025
+ graphql: "graphql",
1026
+ html: "html",
1027
+ java: "java",
1028
+ javascript: "js",
1029
+ json: "json",
1030
+ jsx: "jsx",
1031
+ kotlin: "kt",
1032
+ markdown: "md",
1033
+ php: "php",
1034
+ python: "py",
1035
+ ruby: "rb",
1036
+ rust: "rs",
1037
+ sql: "sql",
1038
+ swift: "swift",
1039
+ toml: "toml",
1040
+ tsx: "tsx",
1041
+ typescript: "ts",
1042
+ xml: "xml",
1043
+ yaml: "yaml"
1044
+ };
1045
+ /**
1046
+ * Saves the block's code as a file - the sibling the copy button was missing
1047
+ * for builder-style output, where the result IS a file and disk is the next
1048
+ * step. Same placement contract as the copy button.
1049
+ */
1050
+ function CodeBlockDownloadButton({ value, filename, onDownload, position = "auto", alwaysVisible = false, label, className, variant = "ghost", size, children, ...props }) {
1051
+ const context = useContext(CodeBlockConfigContext);
1052
+ const document_ = useContext(CodeBlockDocumentContext);
1053
+ const inHeader = useContext(CodeBlockHeaderContext);
1054
+ const resolvedPosition = position === "auto" ? inHeader ? "inline" : "pinned" : position;
1055
+ const resolvedSize = size ?? (resolvedPosition === "inline" ? "icon-sm" : "icon");
1056
+ const handleClick = useCallback(() => {
1057
+ const fallback = document_?.code || document_?.lines.map((line) => line.text).join("\n");
1058
+ const payload = stripNotationComments(value ?? fallback ?? "");
1059
+ if (!payload || typeof window === "undefined") return;
1060
+ const extension = LANGUAGE_EXTENSIONS[context?.resolvedLanguage ?? ""] ?? "txt";
1061
+ const name = filename ?? `code.${extension}`;
1062
+ const url = URL.createObjectURL(new Blob([payload], { type: "text/plain;charset=utf-8" }));
1063
+ const anchor = window.document.createElement("a");
1064
+ anchor.href = url;
1065
+ anchor.download = name;
1066
+ anchor.click();
1067
+ window.setTimeout(() => URL.revokeObjectURL(url), 1e3);
1068
+ onDownload?.(name);
1069
+ }, [
1070
+ value,
1071
+ filename,
1072
+ context,
1073
+ document_,
1074
+ onDownload
1075
+ ]);
1076
+ return /* @__PURE__ */ jsx(Button, {
1077
+ type: "button",
1078
+ "data-slot": "code-block-download",
1079
+ "data-position": resolvedPosition,
1080
+ "aria-label": label ?? "Download code",
1081
+ variant,
1082
+ size: resolvedSize,
1083
+ onClick: handleClick,
1084
+ className: cn("shrink-0 [&_svg]:size-3.5", resolvedPosition === "pinned" && "absolute top-(--code-block-copy-top) right-(--code-block-copy-inset) z-20", resolvedPosition === "pinned" && !alwaysVisible && "opacity-0 transition-opacity focus-visible:opacity-100 group-hover/code-block:opacity-100", className),
1085
+ ...props,
1086
+ children: children ?? /* @__PURE__ */ jsx("svg", {
1087
+ "aria-hidden": "true",
1088
+ viewBox: "0 0 24 24",
1089
+ fill: "none",
1090
+ stroke: "currentColor",
1091
+ strokeWidth: "2",
1092
+ strokeLinecap: "round",
1093
+ strokeLinejoin: "round",
1094
+ children: /* @__PURE__ */ jsx("path", { d: "M12 3v12m0 0 4-4m-4 4-4-4M4 17v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2" })
1095
+ })
1096
+ });
1097
+ }
1098
+ function CodeBlockLineActions({ children, side = "end" }) {
1099
+ const registry = useContext(CodeBlockActionsContext);
1100
+ const owner = useRef({}).current;
1101
+ useEffect(() => {
1102
+ registry?.register(owner, children, side);
1103
+ return () => registry?.register(owner, null);
1104
+ }, [
1105
+ registry,
1106
+ owner,
1107
+ children,
1108
+ side
1109
+ ]);
1110
+ return null;
1111
+ }
1112
+ /**
1113
+ * Live folding for anything composed inside the block - a "fold all" control,
1114
+ * a region count. Mirrors `useCodeBlockSelection`; region and start numbers
1115
+ * are source-based like every line spec.
1116
+ */
1117
+ function useCodeBlockFolding() {
1118
+ const document = useContext(CodeBlockDocumentContext);
1119
+ if (!document) throw new Error("useCodeBlockFolding must be used within a CodeBlock");
1120
+ const { foldable, foldRegions, folded, toggleFold, setFolded } = document;
1121
+ return {
1122
+ foldable,
1123
+ regions: foldRegions,
1124
+ foldedStarts: useMemo(() => [...folded].sort((a, b) => a - b), [folded]),
1125
+ toggleFold,
1126
+ foldAll: useCallback(() => setFolded(foldRegions.map((region) => region.start)), [setFolded, foldRegions]),
1127
+ unfoldAll: useCallback(() => setFolded([]), [setFolded])
1128
+ };
1129
+ }
1130
+ /**
1131
+ * Live selection for anything composed inside the block - a line action, a
1132
+ * header control. Returns the selected lines as a sorted array plus the same
1133
+ * toggle the rows use, so an "add selection to chat" affordance can act on the
1134
+ * whole range instead of only the hovered line.
1135
+ */
1136
+ function useCodeBlockSelection() {
1137
+ const document = useContext(CodeBlockDocumentContext);
1138
+ if (!document) throw new Error("useCodeBlockSelection must be used within a CodeBlock");
1139
+ const { selected, selectable, toggleLine, clearSelection } = document;
1140
+ return {
1141
+ selectable,
1142
+ selectedLines: useMemo(() => [...selected].sort((a, b) => a - b), [selected]),
1143
+ toggleLine,
1144
+ clearSelection
1145
+ };
1146
+ }
1147
+ //#endregion
1148
+ export { CodeBlock, CodeBlockContent, CodeBlockCopyButton, CodeBlockDownloadButton, CodeBlockExpandButton, CodeBlockHeader, CodeBlockLanguage, CodeBlockLineActions, CodeBlockTitle, CodeBlockWrapToggle, ansiToLines, markdownCodeProps, markdownFences, parseUnifiedDiff, useCodeBlockConfig, useCodeBlockFolding, useCodeBlockSelection };
1149
+
1150
+ //# sourceMappingURL=code-block.js.map