@nswds/ui 9.3.2 → 9.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/components/code-block.d.ts +78 -0
- package/dist/components/code-block.js +310 -0
- package/dist/components/code-block.js.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/styles.css +1 -1
- package/package.json +6 -6
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import * as class_variance_authority_types from 'class-variance-authority/types';
|
|
2
|
+
import { VariantProps } from 'class-variance-authority';
|
|
3
|
+
import * as React from 'react';
|
|
4
|
+
import { ButtonProps } from './button.js';
|
|
5
|
+
import '@base-ui/react/button';
|
|
6
|
+
import './link.js';
|
|
7
|
+
|
|
8
|
+
declare const codeBlockVariants: (props?: ({
|
|
9
|
+
variant?: "default" | "destructive" | null | undefined;
|
|
10
|
+
size?: "default" | "sm" | null | undefined;
|
|
11
|
+
} & class_variance_authority_types.ClassProp) | undefined) => string;
|
|
12
|
+
type CodeBlockProps = React.ComponentProps<'div'> & VariantProps<typeof codeBlockVariants>;
|
|
13
|
+
/** The surface that holds the header, the content and the footer. */
|
|
14
|
+
declare function CodeBlock({ className, variant: variantProp, size: sizeProp, ...props }: CodeBlockProps): React.JSX.Element;
|
|
15
|
+
/** A row above the content for a title and actions. */
|
|
16
|
+
declare function CodeBlockHeader({ className, ...props }: React.ComponentProps<'div'>): React.JSX.Element;
|
|
17
|
+
/** A filename or a label, with an optional icon. It truncates. */
|
|
18
|
+
declare function CodeBlockTitle({ className, ...props }: React.ComponentProps<'div'>): React.JSX.Element;
|
|
19
|
+
/**
|
|
20
|
+
* Holds buttons at the end of the header. As a direct child of `CodeBlock`
|
|
21
|
+
* (no header) it floats over the top corner of the code instead, and shows on
|
|
22
|
+
* hover and on keyboard focus; on a touch screen, where there is no hover, it
|
|
23
|
+
* is always shown.
|
|
24
|
+
*/
|
|
25
|
+
declare function CodeBlockActions({ className, ...props }: React.ComponentProps<'div'>): React.JSX.Element;
|
|
26
|
+
type CodeBlockCopyButtonProps = Omit<ButtonProps, 'children' | 'aria-label'> & {
|
|
27
|
+
/** The text to copy. */
|
|
28
|
+
value: string;
|
|
29
|
+
/**
|
|
30
|
+
* Accessible name of the button. It is icon-only, so this string is the
|
|
31
|
+
* only name assistive technology hears. Override to translate it.
|
|
32
|
+
*/
|
|
33
|
+
'aria-label'?: string;
|
|
34
|
+
/**
|
|
35
|
+
* The message announced after a successful copy. Override to translate it.
|
|
36
|
+
*/
|
|
37
|
+
copiedLabel?: string;
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* An icon button that copies `value` to the clipboard, then reports "Copied"
|
|
41
|
+
* for two seconds — in its icon and in a polite live region. Its accessible
|
|
42
|
+
* name does not change. It accepts the props of `Button`.
|
|
43
|
+
*/
|
|
44
|
+
declare function CodeBlockCopyButton({ value, variant, color, size, 'aria-label': ariaLabel, copiedLabel, onClick, ...props }: CodeBlockCopyButtonProps): React.JSX.Element;
|
|
45
|
+
type CodeBlockContentProps = React.ComponentProps<'pre'> & {
|
|
46
|
+
/** Wrap long lines instead of scrolling sideways. */
|
|
47
|
+
wrap?: boolean;
|
|
48
|
+
/**
|
|
49
|
+
* Number each line. Text children are split into lines at each line break.
|
|
50
|
+
* It has no effect on HTML set with `dangerouslySetInnerHTML`: set that on
|
|
51
|
+
* each `CodeBlockLine` to number it.
|
|
52
|
+
*/
|
|
53
|
+
lineNumbers?: boolean;
|
|
54
|
+
/** The number of the first line, when `lineNumbers` is set. */
|
|
55
|
+
startLine?: number;
|
|
56
|
+
};
|
|
57
|
+
/**
|
|
58
|
+
* The `pre` that scrolls or wraps. Children are text, or a list of
|
|
59
|
+
* `CodeBlockLine`; `dangerouslySetInnerHTML` sets the HTML of the `code`
|
|
60
|
+
* element instead, for a highlighter that returns a string. Code is always
|
|
61
|
+
* set left to right, whatever the page's direction, and the region is
|
|
62
|
+
* focusable so it can be scrolled by keyboard.
|
|
63
|
+
*/
|
|
64
|
+
declare function CodeBlockContent({ className, children, style, wrap, lineNumbers, startLine, dangerouslySetInnerHTML, ...props }: CodeBlockContentProps): React.JSX.Element;
|
|
65
|
+
declare const codeBlockLineVariants: (props?: ({
|
|
66
|
+
variant?: "default" | "added" | "removed" | "highlighted" | null | undefined;
|
|
67
|
+
} & class_variance_authority_types.ClassProp) | undefined) => string;
|
|
68
|
+
type CodeBlockLineProps = React.ComponentProps<'span'> & VariantProps<typeof codeBlockLineVariants>;
|
|
69
|
+
/**
|
|
70
|
+
* One line of code. Children are any nodes; `dangerouslySetInnerHTML` sets the
|
|
71
|
+
* line's HTML instead, for a highlighter that returns a string per line.
|
|
72
|
+
*/
|
|
73
|
+
declare function CodeBlockLine({ className, variant: variantProp, children, dangerouslySetInnerHTML, ...props }: CodeBlockLineProps): React.JSX.Element;
|
|
74
|
+
/** A row below the content, such as for a "Show more" button. */
|
|
75
|
+
declare function CodeBlockFooter({ className, ...props }: React.ComponentProps<'div'>): React.JSX.Element;
|
|
76
|
+
|
|
77
|
+
export { CodeBlock, CodeBlockActions, CodeBlockContent, CodeBlockCopyButton, CodeBlockFooter, CodeBlockHeader, CodeBlockLine, CodeBlockTitle, codeBlockLineVariants, codeBlockVariants };
|
|
78
|
+
export type { CodeBlockContentProps, CodeBlockCopyButtonProps, CodeBlockLineProps, CodeBlockProps };
|
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
"use client"
|
|
2
|
+
import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
|
|
3
|
+
import { cva } from 'class-variance-authority';
|
|
4
|
+
import * as React from 'react';
|
|
5
|
+
import { Button } from '../components/button.js';
|
|
6
|
+
import { IconCheck } from '../icons/check.js';
|
|
7
|
+
import { IconContentCopy } from '../icons/content-copy.js';
|
|
8
|
+
import { resolveVariant } from '../lib/resolve-variant.js';
|
|
9
|
+
import { cn } from '../lib/utils.js';
|
|
10
|
+
|
|
11
|
+
const COPIED_RESET_MS = 2e3;
|
|
12
|
+
const codeBlockVariants = cva(
|
|
13
|
+
[
|
|
14
|
+
"group/code-block relative flex w-full min-w-0 flex-col overflow-hidden rounded-md border bg-background text-base",
|
|
15
|
+
// The <pre> is the focusable scroll region, but it scrolls inside this
|
|
16
|
+
// box, so the ring is drawn here — on the edge a reader can see — rather
|
|
17
|
+
// than on an element whose own edge is clipped. Matched at any depth, so
|
|
18
|
+
// content wrapped in a Collapsible or a div keeps its ring.
|
|
19
|
+
"has-[[data-slot=code-block-content]:focus-visible]:outline-2 has-[[data-slot=code-block-content]:focus-visible]:outline-offset-2 has-[[data-slot=code-block-content]:focus-visible]:outline-ring"
|
|
20
|
+
],
|
|
21
|
+
{
|
|
22
|
+
variants: {
|
|
23
|
+
variant: {
|
|
24
|
+
default: "border-border text-foreground",
|
|
25
|
+
// `--danger-text`, not `text-destructive`: `--destructive` is the danger
|
|
26
|
+
// fill, which measures 3.81:1 as text on the dark page. The role token
|
|
27
|
+
// is the one made for text and flips with the theme. The border is not
|
|
28
|
+
// text, so it keeps the fill colour (3:1 or better in both modes).
|
|
29
|
+
destructive: "border-destructive text-(--danger-text)"
|
|
30
|
+
},
|
|
31
|
+
// One padding step, published as `--code-block-p` so the header, the
|
|
32
|
+
// content, the footer and each line's bleed read the same number. The
|
|
33
|
+
// text stays 16px at both steps (the design system's floor); `sm` is
|
|
34
|
+
// denser, not smaller.
|
|
35
|
+
size: {
|
|
36
|
+
default: "[--code-block-p:--spacing(4)]",
|
|
37
|
+
sm: "[--code-block-p:--spacing(3)]"
|
|
38
|
+
}
|
|
39
|
+
},
|
|
40
|
+
defaultVariants: {
|
|
41
|
+
variant: "default",
|
|
42
|
+
size: "default"
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
);
|
|
46
|
+
function CodeBlock({ className, variant: variantProp, size: sizeProp, ...props }) {
|
|
47
|
+
const variant = resolveVariant(variantProp, "default");
|
|
48
|
+
const size = resolveVariant(sizeProp, "default");
|
|
49
|
+
return /* @__PURE__ */ jsx(
|
|
50
|
+
"div",
|
|
51
|
+
{
|
|
52
|
+
"data-slot": "code-block",
|
|
53
|
+
className: cn(codeBlockVariants({ variant, size }), className),
|
|
54
|
+
...props,
|
|
55
|
+
"data-variant": variant,
|
|
56
|
+
"data-size": size
|
|
57
|
+
}
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
function CodeBlockHeader({ className, ...props }) {
|
|
61
|
+
return /* @__PURE__ */ jsx(
|
|
62
|
+
"div",
|
|
63
|
+
{
|
|
64
|
+
"data-slot": "code-block-header",
|
|
65
|
+
className: cn(
|
|
66
|
+
"flex min-w-0 shrink-0 items-center gap-2 px-(--code-block-p) pt-(--code-block-p) text-muted-foreground group-data-[variant=destructive]/code-block:text-(--danger-text) *:has-[>[data-slot=code-block-title]]:min-w-0",
|
|
67
|
+
className
|
|
68
|
+
),
|
|
69
|
+
...props
|
|
70
|
+
}
|
|
71
|
+
);
|
|
72
|
+
}
|
|
73
|
+
function CodeBlockTitle({ className, ...props }) {
|
|
74
|
+
return /* @__PURE__ */ jsx(
|
|
75
|
+
"div",
|
|
76
|
+
{
|
|
77
|
+
"data-slot": "code-block-title",
|
|
78
|
+
className: cn(
|
|
79
|
+
"min-w-0 truncate font-sans text-base font-semibold text-foreground group-data-[variant=destructive]/code-block:text-(--danger-text) [&_svg]:pointer-events-none [&_svg]:inline-block [&_svg]:align-middle [&_svg:not([class*='size-'])]:size-5 *:[svg]:me-2",
|
|
80
|
+
className
|
|
81
|
+
),
|
|
82
|
+
...props
|
|
83
|
+
}
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
function CodeBlockActions({ className, ...props }) {
|
|
87
|
+
return /* @__PURE__ */ jsx(
|
|
88
|
+
"div",
|
|
89
|
+
{
|
|
90
|
+
"data-slot": "code-block-actions",
|
|
91
|
+
className: cn(
|
|
92
|
+
"-my-1 ms-auto -me-1.5 flex shrink-0 items-center gap-1",
|
|
93
|
+
// Floating. The surface and hairline sit on this container rather than
|
|
94
|
+
// on each button, so a ghost button keeps its own hover and pressed
|
|
95
|
+
// tints and the code scrolling underneath never shows through. Pinned
|
|
96
|
+
// to the physical right, not the inline end: the code is set left to
|
|
97
|
+
// right on every page, so on a right-to-left page the inline end is
|
|
98
|
+
// where each line starts.
|
|
99
|
+
"[[data-slot=code-block]>&]:absolute [[data-slot=code-block]>&]:top-2 [[data-slot=code-block]>&]:right-2 [[data-slot=code-block]>&]:z-10 [[data-slot=code-block]>&]:m-0 [[data-slot=code-block]>&]:rounded-sm [[data-slot=code-block]>&]:bg-background [[data-slot=code-block]>&]:ring-1 [[data-slot=code-block]>&]:ring-foreground/10",
|
|
100
|
+
// Hidden only where a pointer can hover to reveal it.
|
|
101
|
+
"[[data-slot=code-block]>&]:not-pointer-coarse:opacity-0 [[data-slot=code-block]>&]:not-pointer-coarse:group-focus-within/code-block:opacity-100 [[data-slot=code-block]>&]:not-pointer-coarse:group-hover/code-block:opacity-100 [[data-slot=code-block]>&]:motion-safe:transition-opacity",
|
|
102
|
+
className
|
|
103
|
+
),
|
|
104
|
+
...props
|
|
105
|
+
}
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
function CodeBlockCopyButton({
|
|
109
|
+
value,
|
|
110
|
+
variant = "ghost",
|
|
111
|
+
color = "grey",
|
|
112
|
+
size = "icon",
|
|
113
|
+
"aria-label": ariaLabel = "Copy",
|
|
114
|
+
copiedLabel = "Copied",
|
|
115
|
+
onClick,
|
|
116
|
+
...props
|
|
117
|
+
}) {
|
|
118
|
+
const [copiedValue, setCopiedValue] = React.useState(void 0);
|
|
119
|
+
const [copies, setCopies] = React.useState(0);
|
|
120
|
+
const copied = copiedValue === value;
|
|
121
|
+
const timeout = React.useRef(void 0);
|
|
122
|
+
const mounted = React.useRef(true);
|
|
123
|
+
const request = React.useRef(0);
|
|
124
|
+
React.useEffect(() => {
|
|
125
|
+
mounted.current = true;
|
|
126
|
+
return () => {
|
|
127
|
+
mounted.current = false;
|
|
128
|
+
clearTimeout(timeout.current);
|
|
129
|
+
};
|
|
130
|
+
}, []);
|
|
131
|
+
const handleClick = (event) => {
|
|
132
|
+
onClick?.(event);
|
|
133
|
+
if (event.defaultPrevented) return;
|
|
134
|
+
const clipboard = typeof navigator === "undefined" ? void 0 : navigator.clipboard;
|
|
135
|
+
if (!clipboard) return;
|
|
136
|
+
const id = ++request.current;
|
|
137
|
+
clipboard.writeText(value).then(() => {
|
|
138
|
+
if (!mounted.current || id !== request.current) return;
|
|
139
|
+
setCopiedValue(value);
|
|
140
|
+
setCopies((count) => count + 1);
|
|
141
|
+
clearTimeout(timeout.current);
|
|
142
|
+
timeout.current = setTimeout(() => setCopiedValue(void 0), COPIED_RESET_MS);
|
|
143
|
+
}).catch(() => {
|
|
144
|
+
});
|
|
145
|
+
};
|
|
146
|
+
return /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
147
|
+
/* @__PURE__ */ jsx(
|
|
148
|
+
Button,
|
|
149
|
+
{
|
|
150
|
+
"data-slot": "code-block-copy-button",
|
|
151
|
+
variant,
|
|
152
|
+
color,
|
|
153
|
+
size,
|
|
154
|
+
...props,
|
|
155
|
+
"aria-label": ariaLabel,
|
|
156
|
+
"data-copied": copied || void 0,
|
|
157
|
+
onClick: handleClick,
|
|
158
|
+
children: copied ? /* @__PURE__ */ jsx(IconCheck, { "aria-hidden": "true" }) : /* @__PURE__ */ jsx(IconContentCopy, { "aria-hidden": "true" })
|
|
159
|
+
}
|
|
160
|
+
),
|
|
161
|
+
/* @__PURE__ */ jsx("span", { "aria-live": "polite", className: "sr-only", children: copied ? copies % 2 === 1 ? copiedLabel : `${copiedLabel}\xA0` : "" })
|
|
162
|
+
] });
|
|
163
|
+
}
|
|
164
|
+
function isText(node) {
|
|
165
|
+
return typeof node === "string" || typeof node === "number";
|
|
166
|
+
}
|
|
167
|
+
function flatten(children, prefix = "") {
|
|
168
|
+
return React.Children.toArray(children).flatMap((child) => {
|
|
169
|
+
if (!React.isValidElement(child)) return [child];
|
|
170
|
+
const key = `${prefix}${child.key}`;
|
|
171
|
+
if (child.type === React.Fragment) {
|
|
172
|
+
return flatten(child.props.children, `${key}/`);
|
|
173
|
+
}
|
|
174
|
+
return [prefix ? React.cloneElement(child, { key }) : child];
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
function linesOf(children) {
|
|
178
|
+
const parts = flatten(children);
|
|
179
|
+
if (!parts.some(isText)) return void 0;
|
|
180
|
+
const lines = [[]];
|
|
181
|
+
for (const part of parts) {
|
|
182
|
+
if (!isText(part)) {
|
|
183
|
+
lines[lines.length - 1].push(part);
|
|
184
|
+
continue;
|
|
185
|
+
}
|
|
186
|
+
const [first = "", ...rest] = String(part).split(/\r?\n/);
|
|
187
|
+
if (first !== "") lines[lines.length - 1].push(first);
|
|
188
|
+
for (const segment of rest) lines.push(segment === "" ? [] : [segment]);
|
|
189
|
+
}
|
|
190
|
+
if (lines.length > 1 && lines[lines.length - 1].length === 0) lines.pop();
|
|
191
|
+
return lines.map((line, index) => /* @__PURE__ */ jsx(CodeBlockLine, { children: line }, index));
|
|
192
|
+
}
|
|
193
|
+
function CodeBlockContent({
|
|
194
|
+
className,
|
|
195
|
+
children,
|
|
196
|
+
style,
|
|
197
|
+
wrap = false,
|
|
198
|
+
lineNumbers = false,
|
|
199
|
+
startLine = 1,
|
|
200
|
+
dangerouslySetInnerHTML,
|
|
201
|
+
...props
|
|
202
|
+
}) {
|
|
203
|
+
const lines = React.useMemo(
|
|
204
|
+
() => lineNumbers ? linesOf(children) : void 0,
|
|
205
|
+
[children, lineNumbers]
|
|
206
|
+
);
|
|
207
|
+
const code = dangerouslySetInnerHTML ? { dangerouslySetInnerHTML } : { children: lines ?? children };
|
|
208
|
+
return /* @__PURE__ */ jsx(
|
|
209
|
+
"pre",
|
|
210
|
+
{
|
|
211
|
+
"data-slot": "code-block-content",
|
|
212
|
+
dir: "ltr",
|
|
213
|
+
tabIndex: 0,
|
|
214
|
+
style: { counterReset: `line ${startLine - 1}`, ...style },
|
|
215
|
+
className: cn(
|
|
216
|
+
// The header and footer tighten the padding beside them through a
|
|
217
|
+
// custom property, not a padding utility of their own, so a padding
|
|
218
|
+
// class passed in `className` still wins.
|
|
219
|
+
"group/code-block-content min-h-0 min-w-0 [scrollbar-width:thin] overflow-auto px-(--code-block-p) pt-[var(--code-block-pt,var(--code-block-p))] pb-[var(--code-block-pb,var(--code-block-p))] text-start font-mono leading-relaxed outline-none group-has-data-[slot=code-block-footer]/code-block:[--code-block-pb:--spacing(2)] group-has-data-[slot=code-block-header]/code-block:[--code-block-pt:--spacing(2)] data-wrap:wrap-break-word data-wrap:whitespace-pre-wrap",
|
|
220
|
+
className
|
|
221
|
+
),
|
|
222
|
+
...props,
|
|
223
|
+
"data-wrap": wrap || void 0,
|
|
224
|
+
"data-numbered": lineNumbers && !dangerouslySetInnerHTML || void 0,
|
|
225
|
+
children: /* @__PURE__ */ jsx(
|
|
226
|
+
"code",
|
|
227
|
+
{
|
|
228
|
+
"data-slot": "code-block-code",
|
|
229
|
+
className: "block min-h-lh min-w-max group-data-numbered/code-block-content:grid group-data-numbered/code-block-content:grid-cols-[auto_1fr] group-data-numbered/code-block-content:content-start group-data-wrap/code-block-content:min-w-0 group-data-numbered/code-block-content:[&>:not([data-slot=code-block-line])]:col-span-full",
|
|
230
|
+
...code
|
|
231
|
+
}
|
|
232
|
+
)
|
|
233
|
+
}
|
|
234
|
+
);
|
|
235
|
+
}
|
|
236
|
+
const codeBlockLineVariants = cva(
|
|
237
|
+
[
|
|
238
|
+
// Bleeds to the block's edges, so a tinted line reads as a full-width band.
|
|
239
|
+
"relative -mx-(--code-block-p) block min-h-lh px-(--code-block-p)",
|
|
240
|
+
// The gutter marker (`+` / `−`) and, when numbered, the line number. Both
|
|
241
|
+
// are generated content, so neither is selected or copied with the code.
|
|
242
|
+
"before:min-w-6 before:text-end before:text-muted-foreground after:absolute after:start-1 after:top-0 after:text-muted-foreground after:select-none",
|
|
243
|
+
// The number is given empty alt text where the syntax is supported, so a
|
|
244
|
+
// screen reader reads the code without a number in front of every line.
|
|
245
|
+
"group-data-numbered/code-block-content:col-span-2 group-data-numbered/code-block-content:grid group-data-numbered/code-block-content:grid-cols-subgrid group-data-numbered/code-block-content:gap-x-4 group-data-numbered/code-block-content:[counter-increment:line] group-data-numbered/code-block-content:before:select-none group-data-numbered/code-block-content:not-supports-[content:counter(line)_/_'']:before:content-[counter(line)] group-data-numbered/code-block-content:supports-[content:counter(line)_/_'']:before:content-[counter(line)_/_'']"
|
|
246
|
+
],
|
|
247
|
+
{
|
|
248
|
+
variants: {
|
|
249
|
+
variant: {
|
|
250
|
+
default: "",
|
|
251
|
+
// Ink tints, not the muted fill: in dark mode that fill and the
|
|
252
|
+
// block's own surface are the same colour, so a muted band vanishes.
|
|
253
|
+
added: "bg-foreground/10 after:content-['+']",
|
|
254
|
+
// The marker keeps the gutter's muted ink rather than taking the danger
|
|
255
|
+
// colour: on this tint in dark mode the danger colour measures 3.56:1.
|
|
256
|
+
removed: "bg-destructive/10 after:content-['\u2212']",
|
|
257
|
+
highlighted: "bg-foreground/10"
|
|
258
|
+
}
|
|
259
|
+
},
|
|
260
|
+
defaultVariants: {
|
|
261
|
+
variant: "default"
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
);
|
|
265
|
+
function CodeBlockLine({
|
|
266
|
+
className,
|
|
267
|
+
variant: variantProp,
|
|
268
|
+
children,
|
|
269
|
+
dangerouslySetInnerHTML,
|
|
270
|
+
...props
|
|
271
|
+
}) {
|
|
272
|
+
const variant = resolveVariant(variantProp, "default");
|
|
273
|
+
const html = dangerouslySetInnerHTML?.__html;
|
|
274
|
+
const content = dangerouslySetInnerHTML ? {
|
|
275
|
+
dangerouslySetInnerHTML: typeof html === "string" ? { __html: `${html}
|
|
276
|
+
` } : dangerouslySetInnerHTML
|
|
277
|
+
} : {
|
|
278
|
+
children: /* @__PURE__ */ jsxs(Fragment, { children: [
|
|
279
|
+
children,
|
|
280
|
+
"\n"
|
|
281
|
+
] })
|
|
282
|
+
};
|
|
283
|
+
return /* @__PURE__ */ jsx(
|
|
284
|
+
"span",
|
|
285
|
+
{
|
|
286
|
+
"data-slot": "code-block-line",
|
|
287
|
+
className: cn(codeBlockLineVariants({ variant }), className),
|
|
288
|
+
...props,
|
|
289
|
+
"data-variant": variant,
|
|
290
|
+
children: /* @__PURE__ */ jsx("span", { "data-slot": "code-block-line-content", className: "min-w-0", ...content })
|
|
291
|
+
}
|
|
292
|
+
);
|
|
293
|
+
}
|
|
294
|
+
function CodeBlockFooter({ className, ...props }) {
|
|
295
|
+
return /* @__PURE__ */ jsx(
|
|
296
|
+
"div",
|
|
297
|
+
{
|
|
298
|
+
"data-slot": "code-block-footer",
|
|
299
|
+
className: cn(
|
|
300
|
+
"flex min-w-0 shrink-0 items-center gap-2 px-(--code-block-p) pb-(--code-block-p) text-muted-foreground",
|
|
301
|
+
className
|
|
302
|
+
),
|
|
303
|
+
...props
|
|
304
|
+
}
|
|
305
|
+
);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
export { CodeBlock, CodeBlockActions, CodeBlockContent, CodeBlockCopyButton, CodeBlockFooter, CodeBlockHeader, CodeBlockLine, CodeBlockTitle, codeBlockLineVariants, codeBlockVariants };
|
|
309
|
+
//# sourceMappingURL=code-block.js.map
|
|
310
|
+
//# sourceMappingURL=code-block.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/components/code-block.tsx"],"names":[],"mappings":";;;;;;;;;AAYA,MAAM,eAAA,GAAkB,GAAA;AAExB,MAAM,iBAAA,GAAoB,GAAA;AAAA,EACxB;AAAA,IACE,kHAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAKA;AAAA,GACF;AAAA,EACA;AAAA,IACE,QAAA,EAAU;AAAA,MACR,OAAA,EAAS;AAAA,QACP,OAAA,EAAS,+BAAA;AAAA;AAAA;AAAA;AAAA;AAAA,QAKT,WAAA,EAAa;AAAA,OACf;AAAA;AAAA;AAAA;AAAA;AAAA,MAKA,IAAA,EAA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A,GAAG;AACL,CAAA,EAAuB;AACrB,EAAA,MAAM,OAAA,GAAU,cAAA,CAAe,WAAA,EAAa,SAAS,CAAA;AAKrD,EAAA,MAAM,OAAO,uBAAA,EAAyB,MAAA;AACtC,EAAA,MAAM,UAAU,uBAAA,GACZ;AAAA,IACE,yBACE,OAAO,IAAA,KAAS,WAAW,EAAE,MAAA,EAAQ,GAAG,IAAI;AAAA,CAAA,EAAK,GAAI;AAAA,GACzD,GACA;AAAA,IACE,0BACE,IAAA,CAAA,QAAA,EAAA,EACG,QAAA,EAAA;AAAA,MAAA,QAAA;AAAA,MACA;AAAA,KAAA,EACH;AAAA,GAEJ;AAEJ,EAAA,uBACE,GAAA;AAAA,IAAC,MAAA;AAAA,IAAA;AAAA,MACC,WAAA,EAAU,iBAAA;AAAA,MACV,WAAW,EAAA,CAAG,qBAAA,CAAsB,EAAE,OAAA,EAAS,GAAG,SAAS,CAAA;AAAA,MAC1D,GAAG,KAAA;AAAA,MACJ,cAAA,EAAc,OAAA;AAAA,MAEd,8BAAC,MAAA,EAAA,EAAK,WAAA,EAAU,2BAA0B,SAAA,EAAU,SAAA,EAAW,GAAG,OAAA,EAAS;AAAA;AAAA,GAC7E;AAEJ;AAGA,SAAS,eAAA,CAAgB,EAAE,SAAA,EAAW,GAAG,OAAM,EAAgC;AAC7E,EAAA,uBACE,GAAA;AAAA,IAAC,KAAA;AAAA,IAAA;AAAA,MACC,WAAA,EAAU,mBAAA;AAAA,MACV,SAAA,EAAW,EAAA;AAAA,QACT,wGAAA;AAAA,QACA;AAAA,OACF;AAAA,MACC,GAAG;AAAA;AAAA,GACN;AAEJ","file":"code-block.js","sourcesContent":["'use client'\n\nimport { cva, type VariantProps } from 'class-variance-authority'\nimport * as React from 'react'\n\nimport { Button, type ButtonProps } from '../components/button.js'\nimport { IconCheck } from '../icons/check.js'\nimport { IconContentCopy } from '../icons/content-copy.js'\nimport { resolveVariant } from '../lib/resolve-variant.js'\nimport { cn } from '../lib/utils.js'\n\n/** How long the copy button reports \"Copied\" before it reverts, in ms. */\nconst COPIED_RESET_MS = 2000\n\nconst codeBlockVariants = cva(\n [\n 'group/code-block relative flex w-full min-w-0 flex-col overflow-hidden rounded-md border bg-background text-base',\n // The <pre> is the focusable scroll region, but it scrolls inside this\n // box, so the ring is drawn here — on the edge a reader can see — rather\n // than on an element whose own edge is clipped. Matched at any depth, so\n // content wrapped in a Collapsible or a div keeps its ring.\n 'has-[[data-slot=code-block-content]:focus-visible]:outline-2 has-[[data-slot=code-block-content]:focus-visible]:outline-offset-2 has-[[data-slot=code-block-content]:focus-visible]:outline-ring',\n ],\n {\n variants: {\n variant: {\n default: 'border-border text-foreground',\n // `--danger-text`, not `text-destructive`: `--destructive` is the danger\n // fill, which measures 3.81:1 as text on the dark page. The role token\n // is the one made for text and flips with the theme. The border is not\n // text, so it keeps the fill colour (3:1 or better in both modes).\n destructive: 'border-destructive text-(--danger-text)',\n },\n // One padding step, published as `--code-block-p` so the header, the\n // content, the footer and each line's bleed read the same number. The\n // text stays 16px at both steps (the design system's floor); `sm` is\n // denser, not smaller.\n size: {\n default: '[--code-block-p:--spacing(4)]',\n sm: '[--code-block-p:--spacing(3)]',\n },\n },\n defaultVariants: {\n variant: 'default',\n size: 'default',\n },\n },\n)\n\ntype CodeBlockProps = React.ComponentProps<'div'> & VariantProps<typeof codeBlockVariants>\n\n/** The surface that holds the header, the content and the footer. */\nfunction CodeBlock({ className, variant: variantProp, size: sizeProp, ...props }: CodeBlockProps) {\n const variant = resolveVariant(variantProp, 'default')\n const size = resolveVariant(sizeProp, 'default')\n\n return (\n <div\n data-slot='code-block'\n className={cn(codeBlockVariants({ variant, size }), className)}\n {...props}\n data-variant={variant}\n data-size={size}\n />\n )\n}\n\n/** A row above the content for a title and actions. */\nfunction CodeBlockHeader({ className, ...props }: React.ComponentProps<'div'>) {\n return (\n <div\n data-slot='code-block-header'\n className={cn(\n 'flex min-w-0 shrink-0 items-center gap-2 px-(--code-block-p) pt-(--code-block-p) text-muted-foreground group-data-[variant=destructive]/code-block:text-(--danger-text) *:has-[>[data-slot=code-block-title]]:min-w-0',\n className,\n )}\n {...props}\n />\n )\n}\n\n/** A filename or a label, with an optional icon. It truncates. */\nfunction CodeBlockTitle({ className, ...props }: React.ComponentProps<'div'>) {\n return (\n <div\n data-slot='code-block-title'\n className={cn(\n \"min-w-0 truncate font-sans text-base font-semibold text-foreground group-data-[variant=destructive]/code-block:text-(--danger-text) [&_svg]:pointer-events-none [&_svg]:inline-block [&_svg]:align-middle [&_svg:not([class*='size-'])]:size-5 *:[svg]:me-2\",\n className,\n )}\n {...props}\n />\n )\n}\n\n/**\n * Holds buttons at the end of the header. As a direct child of `CodeBlock`\n * (no header) it floats over the top corner of the code instead, and shows on\n * hover and on keyboard focus; on a touch screen, where there is no hover, it\n * is always shown.\n */\nfunction CodeBlockActions({ className, ...props }: React.ComponentProps<'div'>) {\n return (\n <div\n data-slot='code-block-actions'\n className={cn(\n '-my-1 ms-auto -me-1.5 flex shrink-0 items-center gap-1',\n // Floating. The surface and hairline sit on this container rather than\n // on each button, so a ghost button keeps its own hover and pressed\n // tints and the code scrolling underneath never shows through. Pinned\n // to the physical right, not the inline end: the code is set left to\n // right on every page, so on a right-to-left page the inline end is\n // where each line starts.\n '[[data-slot=code-block]>&]:absolute [[data-slot=code-block]>&]:top-2 [[data-slot=code-block]>&]:right-2 [[data-slot=code-block]>&]:z-10 [[data-slot=code-block]>&]:m-0 [[data-slot=code-block]>&]:rounded-sm [[data-slot=code-block]>&]:bg-background [[data-slot=code-block]>&]:ring-1 [[data-slot=code-block]>&]:ring-foreground/10',\n // Hidden only where a pointer can hover to reveal it.\n '[[data-slot=code-block]>&]:not-pointer-coarse:opacity-0 [[data-slot=code-block]>&]:not-pointer-coarse:group-focus-within/code-block:opacity-100 [[data-slot=code-block]>&]:not-pointer-coarse:group-hover/code-block:opacity-100 [[data-slot=code-block]>&]:motion-safe:transition-opacity',\n className,\n )}\n {...props}\n />\n )\n}\n\ntype CodeBlockCopyButtonProps = Omit<ButtonProps, 'children' | 'aria-label'> & {\n /** The text to copy. */\n value: string\n /**\n * Accessible name of the button. It is icon-only, so this string is the\n * only name assistive technology hears. Override to translate it.\n */\n 'aria-label'?: string\n /**\n * The message announced after a successful copy. Override to translate it.\n */\n copiedLabel?: string\n}\n\n/**\n * An icon button that copies `value` to the clipboard, then reports \"Copied\"\n * for two seconds — in its icon and in a polite live region. Its accessible\n * name does not change. It accepts the props of `Button`.\n */\nfunction CodeBlockCopyButton({\n value,\n variant = 'ghost',\n color = 'grey',\n size = 'icon',\n 'aria-label': ariaLabel = 'Copy',\n copiedLabel = 'Copied',\n onClick,\n ...props\n}: CodeBlockCopyButtonProps) {\n // The value that was copied, not a flag: when `value` changes inside the\n // two seconds, the button must stop claiming a copy of text it never wrote.\n const [copiedValue, setCopiedValue] = React.useState<string | undefined>(undefined)\n const [copies, setCopies] = React.useState(0)\n const copied = copiedValue === value\n const timeout = React.useRef<ReturnType<typeof setTimeout> | undefined>(undefined)\n const mounted = React.useRef(true)\n // Counts the copies started, so a write that settles after a later one was\n // started cannot overwrite the later one's state or replace its timer.\n const request = React.useRef(0)\n\n React.useEffect(() => {\n mounted.current = true\n return () => {\n mounted.current = false\n clearTimeout(timeout.current)\n }\n }, [])\n\n const handleClick: NonNullable<ButtonProps['onClick']> = (event) => {\n onClick?.(event)\n if (event.defaultPrevented) return\n\n // Absent outside a secure context (plain http, some embedded webviews).\n // Copying is a convenience over selecting the text, so fail quietly and\n // leave the button reading \"Copy\" rather than claim a copy that never\n // happened.\n const clipboard = typeof navigator === 'undefined' ? undefined : navigator.clipboard\n if (!clipboard) return\n\n const id = ++request.current\n clipboard\n .writeText(value)\n .then(() => {\n // The write can settle after the button has gone; starting a timer\n // then would leave one nothing clears.\n if (!mounted.current || id !== request.current) return\n setCopiedValue(value)\n setCopies((count) => count + 1)\n // Restart the window, so a second copy inside it gets its full two\n // seconds rather than the remainder of the first.\n clearTimeout(timeout.current)\n timeout.current = setTimeout(() => setCopiedValue(undefined), COPIED_RESET_MS)\n })\n .catch(() => {})\n }\n\n return (\n <>\n <Button\n data-slot='code-block-copy-button'\n variant={variant}\n color={color}\n size={size}\n {...props}\n // The name stays put. A screen reader that announces a rename of the\n // focused control would read \"Copied\" here and again from the live\n // region, then the old name when it reverted.\n aria-label={ariaLabel}\n data-copied={copied || undefined}\n onClick={handleClick}\n >\n {copied ? <IconCheck aria-hidden='true' /> : <IconContentCopy aria-hidden='true' />}\n </Button>\n {/* Recorded exception to \"never hand-roll ARIA\": Base UI has no\n primitive for a status message, and the result of the copy has to\n reach a screen reader (WCAG 4.1.3). A live region only speaks when\n its text changes, so a second copy inside the two seconds alternates\n a trailing no-break space to be announced as well. */}\n <span aria-live='polite' className='sr-only'>\n {copied ? (copies % 2 === 1 ? copiedLabel : `${copiedLabel}\\u00A0`) : ''}\n </span>\n </>\n )\n}\n\ntype CodeBlockContentProps = React.ComponentProps<'pre'> & {\n /** Wrap long lines instead of scrolling sideways. */\n wrap?: boolean\n /**\n * Number each line. Text children are split into lines at each line break.\n * It has no effect on HTML set with `dangerouslySetInnerHTML`: set that on\n * each `CodeBlockLine` to number it.\n */\n lineNumbers?: boolean\n /** The number of the first line, when `lineNumbers` is set. */\n startLine?: number\n}\n\nfunction isText(node: React.ReactNode): node is string | number {\n return typeof node === 'string' || typeof node === 'number'\n}\n\n/**\n * The children as a flat list, with the contents of any fragment in place of\n * the fragment: `toArray` does not look inside one, and text wrapped in `<>`\n * has to number like text that is not.\n */\nfunction flatten(children: React.ReactNode, prefix = ''): React.ReactNode[] {\n return React.Children.toArray(children).flatMap((child) => {\n if (!React.isValidElement(child)) return [child]\n // Keys restart inside each fragment, so they are joined to stay unique.\n const key = `${prefix}${child.key}`\n if (child.type === React.Fragment) {\n return flatten((child.props as { children?: React.ReactNode }).children, `${key}/`)\n }\n return [prefix ? React.cloneElement(child, { key }) : child]\n })\n}\n\n/**\n * The children as numbered lines, or `undefined` when none of them is text.\n * Text is split at each line break; an element between two pieces of text\n * (a `<mark>`, a highlighter's token) stays on the line it falls on. JSX turns\n * `npm {name}` into several text children, which number like one string.\n *\n * Children that are all elements are the caller's own `CodeBlockLine`s and\n * are left alone.\n */\nfunction linesOf(children: React.ReactNode): React.ReactNode[] | undefined {\n const parts = flatten(children)\n if (!parts.some(isText)) return undefined\n\n const lines: React.ReactNode[][] = [[]]\n for (const part of parts) {\n if (!isText(part)) {\n lines[lines.length - 1]!.push(part)\n continue\n }\n const [first = '', ...rest] = String(part).split(/\\r?\\n/)\n if (first !== '') lines[lines.length - 1]!.push(first)\n for (const segment of rest) lines.push(segment === '' ? [] : [segment])\n }\n // A trailing line break ends the last line; it does not start another.\n if (lines.length > 1 && lines[lines.length - 1]!.length === 0) lines.pop()\n\n return lines.map((line, index) => <CodeBlockLine key={index}>{line}</CodeBlockLine>)\n}\n\n/**\n * The `pre` that scrolls or wraps. Children are text, or a list of\n * `CodeBlockLine`; `dangerouslySetInnerHTML` sets the HTML of the `code`\n * element instead, for a highlighter that returns a string. Code is always\n * set left to right, whatever the page's direction, and the region is\n * focusable so it can be scrolled by keyboard.\n */\nfunction CodeBlockContent({\n className,\n children,\n style,\n wrap = false,\n lineNumbers = false,\n startLine = 1,\n dangerouslySetInnerHTML,\n ...props\n}: CodeBlockContentProps) {\n // Memoised on the children: a string child keeps its identity between\n // renders, so a long log is split, and its lines rebuilt, once per change.\n const lines = React.useMemo(\n () => (lineNumbers ? linesOf(children) : undefined),\n [children, lineNumbers],\n )\n const code = dangerouslySetInnerHTML\n ? { dangerouslySetInnerHTML }\n : { children: lines ?? children }\n\n return (\n <pre\n data-slot='code-block-content'\n dir='ltr'\n // Recorded exception to \"no custom focus management\": a region that\n // scrolls has to be reachable by keyboard to be scrolled by keyboard\n // (WCAG 2.1.1), and Base UI has no scroll-region primitive that does it.\n tabIndex={0}\n style={{ counterReset: `line ${startLine - 1}`, ...style }}\n className={cn(\n // The header and footer tighten the padding beside them through a\n // custom property, not a padding utility of their own, so a padding\n // class passed in `className` still wins.\n 'group/code-block-content min-h-0 min-w-0 [scrollbar-width:thin] overflow-auto px-(--code-block-p) pt-[var(--code-block-pt,var(--code-block-p))] pb-[var(--code-block-pb,var(--code-block-p))] text-start font-mono leading-relaxed outline-none group-has-data-[slot=code-block-footer]/code-block:[--code-block-pb:--spacing(2)] group-has-data-[slot=code-block-header]/code-block:[--code-block-pt:--spacing(2)] data-wrap:wrap-break-word data-wrap:whitespace-pre-wrap',\n className,\n )}\n {...props}\n data-wrap={wrap || undefined}\n // An HTML string has no lines to number, so it is never laid out as one.\n data-numbered={(lineNumbers && !dangerouslySetInnerHTML) || undefined}\n >\n <code\n data-slot='code-block-code'\n // A block, so text and a highlighter's inline tokens flow as they do in\n // any `code`; a grid only when numbered, for the number column. Both\n // modes key on this `pre` by its group name, not on any ancestor that\n // happens to carry `data-numbered` or `data-wrap`. A numbered child\n // that is not a line (a highlighter's wrapper) spans both columns\n // rather than landing in the number column.\n className='block min-h-lh min-w-max group-data-numbered/code-block-content:grid group-data-numbered/code-block-content:grid-cols-[auto_1fr] group-data-numbered/code-block-content:content-start group-data-wrap/code-block-content:min-w-0 group-data-numbered/code-block-content:[&>:not([data-slot=code-block-line])]:col-span-full'\n {...code}\n />\n </pre>\n )\n}\n\nconst codeBlockLineVariants = cva(\n [\n // Bleeds to the block's edges, so a tinted line reads as a full-width band.\n 'relative -mx-(--code-block-p) block min-h-lh px-(--code-block-p)',\n // The gutter marker (`+` / `−`) and, when numbered, the line number. Both\n // are generated content, so neither is selected or copied with the code.\n 'before:min-w-6 before:text-end before:text-muted-foreground after:absolute after:start-1 after:top-0 after:text-muted-foreground after:select-none',\n // The number is given empty alt text where the syntax is supported, so a\n // screen reader reads the code without a number in front of every line.\n \"group-data-numbered/code-block-content:col-span-2 group-data-numbered/code-block-content:grid group-data-numbered/code-block-content:grid-cols-subgrid group-data-numbered/code-block-content:gap-x-4 group-data-numbered/code-block-content:[counter-increment:line] group-data-numbered/code-block-content:before:select-none group-data-numbered/code-block-content:not-supports-[content:counter(line)_/_'']:before:content-[counter(line)] group-data-numbered/code-block-content:supports-[content:counter(line)_/_'']:before:content-[counter(line)_/_'']\",\n ],\n {\n variants: {\n variant: {\n default: '',\n // Ink tints, not the muted fill: in dark mode that fill and the\n // block's own surface are the same colour, so a muted band vanishes.\n added: \"bg-foreground/10 after:content-['+']\",\n // The marker keeps the gutter's muted ink rather than taking the danger\n // colour: on this tint in dark mode the danger colour measures 3.56:1.\n removed: \"bg-destructive/10 after:content-['−']\",\n highlighted: 'bg-foreground/10',\n },\n },\n defaultVariants: {\n variant: 'default',\n },\n },\n)\n\ntype CodeBlockLineProps = React.ComponentProps<'span'> & VariantProps<typeof codeBlockLineVariants>\n\n/**\n * One line of code. Children are any nodes; `dangerouslySetInnerHTML` sets the\n * line's HTML instead, for a highlighter that returns a string per line.\n */\nfunction CodeBlockLine({\n className,\n variant: variantProp,\n children,\n dangerouslySetInnerHTML,\n ...props\n}: CodeBlockLineProps) {\n const variant = resolveVariant(variantProp, 'default')\n // Every line ends with its line break, so the text of the block is the code\n // — for a copied selection, and for anything that reads `textContent`. At\n // the end of a block-level line the break draws nothing. (A TrustedHTML\n // value cannot be added to, so that one line goes without.)\n const html = dangerouslySetInnerHTML?.__html\n const content = dangerouslySetInnerHTML\n ? {\n dangerouslySetInnerHTML:\n typeof html === 'string' ? { __html: `${html}\\n` } : dangerouslySetInnerHTML,\n }\n : {\n children: (\n <>\n {children}\n {'\\n'}\n </>\n ),\n }\n\n return (\n <span\n data-slot='code-block-line'\n className={cn(codeBlockLineVariants({ variant }), className)}\n {...props}\n data-variant={variant}\n >\n <span data-slot='code-block-line-content' className='min-w-0' {...content} />\n </span>\n )\n}\n\n/** A row below the content, such as for a \"Show more\" button. */\nfunction CodeBlockFooter({ className, ...props }: React.ComponentProps<'div'>) {\n return (\n <div\n data-slot='code-block-footer'\n className={cn(\n 'flex min-w-0 shrink-0 items-center gap-2 px-(--code-block-p) pb-(--code-block-p) text-muted-foreground',\n className,\n )}\n {...props}\n />\n )\n}\n\nexport {\n CodeBlock,\n CodeBlockActions,\n CodeBlockContent,\n CodeBlockCopyButton,\n CodeBlockFooter,\n CodeBlockHeader,\n CodeBlockLine,\n codeBlockLineVariants,\n CodeBlockTitle,\n codeBlockVariants,\n}\nexport type { CodeBlockContentProps, CodeBlockCopyButtonProps, CodeBlockLineProps, CodeBlockProps }\n"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -10,6 +10,7 @@ export { Alert, AlertProps, AlertStatus, Callout, CalloutProps, CalloutStatus, a
|
|
|
10
10
|
export { Card, CardAction, CardActionProps, CardContent, CardContentProps, CardDescription, CardDescriptionProps, CardFooter, CardFooterProps, CardHeader, CardHeaderProps, CardProps, CardTitle, CardTitleProps } from './components/card.js';
|
|
11
11
|
export { Carousel, CarouselApi, CarouselContent, CarouselItem, CarouselNext, CarouselPrevious, useCarousel } from './components/carousel.js';
|
|
12
12
|
export { Checkbox } from './components/checkbox.js';
|
|
13
|
+
export { CodeBlock, CodeBlockActions, CodeBlockContent, CodeBlockContentProps, CodeBlockCopyButton, CodeBlockCopyButtonProps, CodeBlockFooter, CodeBlockHeader, CodeBlockLine, CodeBlockLineProps, CodeBlockProps, CodeBlockTitle, codeBlockLineVariants, codeBlockVariants } from './components/code-block.js';
|
|
13
14
|
export { Collapsible, CollapsibleContent, CollapsibleTrigger } from './components/collapsible.js';
|
|
14
15
|
export { Combobox, ComboboxChip, ComboboxChips, ComboboxChipsInput, ComboboxCollection, ComboboxContent, ComboboxEmpty, ComboboxGroup, ComboboxInput, ComboboxItem, ComboboxLabel, ComboboxList, ComboboxSeparator, ComboboxTrigger, ComboboxValue, useComboboxAnchor } from './components/combobox.js';
|
|
15
16
|
export { Container, ContainerProps, containerVariants } from './components/container.js';
|
package/dist/index.js
CHANGED
|
@@ -10,6 +10,7 @@ export * from './components/callout.js';
|
|
|
10
10
|
export * from './components/card.js';
|
|
11
11
|
export * from './components/carousel.js';
|
|
12
12
|
export * from './components/checkbox.js';
|
|
13
|
+
export * from './components/code-block.js';
|
|
13
14
|
export * from './components/collapsible.js';
|
|
14
15
|
export * from './components/combobox.js';
|
|
15
16
|
export * from './components/container.js';
|