rift-ds 1.32.0 → 1.33.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.
Files changed (96) hide show
  1. package/README.md +4 -4
  2. package/behaviors/clipboard.d.ts +7 -0
  3. package/behaviors/clipboard.js +35 -0
  4. package/behaviors/headingSlug.d.ts +8 -0
  5. package/behaviors/headingSlug.js +4 -0
  6. package/behaviors/shell.css +64 -0
  7. package/behaviors/syncedChoice.d.ts +2 -0
  8. package/behaviors/syncedChoice.js +48 -0
  9. package/behaviors/useLayer.d.ts +15 -2
  10. package/behaviors/useLayer.js +3 -2
  11. package/bin/templates/blocks/app/guide/PageFeedback.tsx +55 -0
  12. package/bin/templates/blocks/app/guide/page.module.css +94 -0
  13. package/bin/templates/blocks/app/guide/page.tsx +168 -0
  14. package/bin/templates/blocks/components/blocks/AppShell.module.css +3 -1
  15. package/bin/templates/blocks/components/blocks/AppShell.tsx +8 -0
  16. package/bin/templates/blocks/components/blocks/DocsShell.module.css +18 -0
  17. package/bin/templates/blocks/components/blocks/DocsShell.tsx +179 -0
  18. package/bin/templates/blocks/registry.json +13 -0
  19. package/code/highlight.d.ts +4 -0
  20. package/code/highlight.js +34 -0
  21. package/code/index.d.ts +16 -0
  22. package/code/index.js +23 -0
  23. package/components/AnchorNav/AnchorNav.d.ts +29 -3
  24. package/components/AnchorNav/AnchorNav.js +69 -5
  25. package/components/AppLayout/AppLayout.css +8 -4
  26. package/components/AppLayout/AppLayout.d.ts +13 -3
  27. package/components/AppLayout/AppLayout.js +2 -0
  28. package/components/ArtifactPanel/ArtifactPanel.css +46 -0
  29. package/components/ArtifactPanel/ArtifactPanel.d.ts +14 -4
  30. package/components/ArtifactPanel/ArtifactPanel.js +8 -5
  31. package/components/BackToTop/BackToTop.css +28 -0
  32. package/components/BackToTop/BackToTop.d.ts +28 -0
  33. package/components/BackToTop/BackToTop.js +47 -0
  34. package/components/BentoTile/BentoTile.css +3 -0
  35. package/components/CodeBlock/CodeBlock.css +63 -24
  36. package/components/CodeBlock/CodeBlock.d.ts +62 -6
  37. package/components/CodeBlock/CodeBlock.js +90 -48
  38. package/components/CopyButton/CopyButton.d.ts +42 -0
  39. package/components/CopyButton/CopyButton.js +72 -0
  40. package/components/DescriptionList/DescriptionListCopy.d.ts +2 -2
  41. package/components/DescriptionList/DescriptionListCopy.js +7 -35
  42. package/components/Figure/Figure.css +26 -0
  43. package/components/Figure/Figure.d.ts +10 -1
  44. package/components/Figure/Figure.js +15 -3
  45. package/components/Heading/Heading.css +43 -0
  46. package/components/Heading/Heading.d.ts +14 -3
  47. package/components/Heading/Heading.js +22 -4
  48. package/components/HoverCard/HoverCard.js +1 -0
  49. package/components/Link/Link.css +38 -0
  50. package/components/Link/Link.d.ts +3 -3
  51. package/components/Link/Link.js +1 -1
  52. package/components/Menubar/Menubar.css +82 -0
  53. package/components/Menubar/Menubar.d.ts +40 -0
  54. package/components/Menubar/Menubar.js +97 -0
  55. package/components/NavList/NavList.css +197 -0
  56. package/components/NavList/NavList.d.ts +54 -6
  57. package/components/NavList/NavList.js +136 -8
  58. package/components/Pagination/Pagination.css +80 -0
  59. package/components/Pagination/Pagination.d.ts +29 -3
  60. package/components/Pagination/Pagination.js +49 -5
  61. package/components/Rating/Rating.css +26 -0
  62. package/components/Rating/Rating.d.ts +18 -5
  63. package/components/Rating/Rating.js +16 -7
  64. package/components/SectionTitle/SectionTitle.css +36 -0
  65. package/components/SectionTitle/SectionTitle.d.ts +10 -1
  66. package/components/SectionTitle/SectionTitle.js +7 -2
  67. package/components/ShaderScene/ShaderScene.d.ts +2 -1
  68. package/components/ShaderScene/ShaderScene.js +20 -2
  69. package/components/SiteFooter/SiteFooter.css +157 -0
  70. package/components/SiteFooter/SiteFooter.d.ts +53 -0
  71. package/components/SiteFooter/SiteFooter.js +61 -0
  72. package/components/SiteHeader/SiteHeader.css +106 -4
  73. package/components/SiteHeader/SiteHeader.d.ts +25 -2
  74. package/components/SiteHeader/SiteHeader.js +46 -8
  75. package/components/SiteLayout/SiteLayout.css +361 -0
  76. package/components/SiteLayout/SiteLayout.d.ts +103 -0
  77. package/components/SiteLayout/SiteLayout.js +68 -0
  78. package/components/Table/Table.css +14 -0
  79. package/components/Table/Table.d.ts +2 -0
  80. package/components/Table/Table.js +1 -1
  81. package/components/Tooltip/Tooltip.js +1 -0
  82. package/components/keyboard-patterns.json.d.ts +57 -0
  83. package/components/keyboard-patterns.json.js +1 -1
  84. package/components/registry.json +89 -19
  85. package/components/registry.json.d.ts +89 -19
  86. package/components/registry.json.js +1 -1
  87. package/index.d.ts +5 -0
  88. package/index.js +14 -1
  89. package/package.json +14 -2
  90. package/tokens/breakpoints.js +3 -3
  91. package/tokens/registry.json +5 -0
  92. package/tokens/registry.json.d.ts +5 -0
  93. package/tokens/registry.json.js +1 -1
  94. package/tokens/tokens-dark.css +12 -0
  95. package/tokens/tokens-light.css +12 -0
  96. package/tokens/values.json.js +1 -1
@@ -11,6 +11,8 @@ const baseClass = "ds-artifact-panel";
11
11
  const ArtifactPanel = React.forwardRef(
12
12
  ({
13
13
  title,
14
+ layout = "panel",
15
+ lines,
14
16
  meta,
15
17
  icon,
16
18
  children,
@@ -39,7 +41,7 @@ const ArtifactPanel = React.forwardRef(
39
41
  }, ref) => {
40
42
  const titleId = useId();
41
43
  const hasPreview = Boolean(children) || html !== void 0 || Boolean(src);
42
- const hasCode = code !== void 0;
44
+ const hasCode = code !== void 0 || lines !== void 0;
43
45
  const [ownView, setOwnView] = useState(defaultView ?? "preview");
44
46
  const wanted = view ?? ownView;
45
47
  const current = wanted === "code" ? hasCode ? "code" : "preview" : hasPreview ? "preview" : "code";
@@ -53,14 +55,15 @@ const ArtifactPanel = React.forwardRef(
53
55
  "section",
54
56
  {
55
57
  ref,
58
+ "aria-label": title ? void 0 : viewLabel,
56
59
  ...rest,
57
- className: [baseClass, className].filter(Boolean).join(" "),
58
- "aria-labelledby": titleId,
60
+ className: [baseClass, layout === "inline" ? `${baseClass}--inline` : "", className].filter(Boolean).join(" "),
61
+ "aria-labelledby": title ? titleId : void 0,
59
62
  children: [
60
63
  /* @__PURE__ */ jsxs("header", { className: `${baseClass}__header`, children: [
61
64
  /* @__PURE__ */ jsxs("div", { className: `${baseClass}__heading`, children: [
62
65
  icon !== void 0 && (typeof icon === "string" ? /* @__PURE__ */ jsx("span", { className: `${baseClass}__icon material-symbols-rounded ${mirrorClass(icon)}`, "aria-hidden": "true", children: icon }) : /* @__PURE__ */ jsx("span", { className: `${baseClass}__icon`, children: icon })),
63
- /* @__PURE__ */ jsx("h2", { className: `${baseClass}__title`, id: titleId, children: title }),
66
+ title && /* @__PURE__ */ jsx("h2", { className: `${baseClass}__title`, id: titleId, children: title }),
64
67
  meta && /* @__PURE__ */ jsx("span", { className: `${baseClass}__meta`, children: meta })
65
68
  ] }),
66
69
  /* @__PURE__ */ jsxs("div", { className: `${baseClass}__controls`, children: [
@@ -102,7 +105,7 @@ const ArtifactPanel = React.forwardRef(
102
105
  )
103
106
  ] })
104
107
  ] }),
105
- /* @__PURE__ */ jsx("div", { className: `${baseClass}__body`, "data-view": current, children: current === "code" && hasCode ? /* @__PURE__ */ jsx("div", { className: `${baseClass}__code`, children: /* @__PURE__ */ jsx(CodeBlock, { ...codeBlockLabels, code: code ?? "", language }) }) : children ? /* @__PURE__ */ jsx("div", { className: `${baseClass}__content`, children }) : html !== void 0 ? /* @__PURE__ */ jsx(
108
+ /* @__PURE__ */ jsx("div", { className: `${baseClass}__body`, "data-view": current, children: current === "code" && hasCode ? /* @__PURE__ */ jsx("div", { className: `${baseClass}__code`, children: /* @__PURE__ */ jsx(CodeBlock, { ...codeBlockLabels, code, lines, language }) }) : children ? /* @__PURE__ */ jsx("div", { className: `${baseClass}__content`, children }) : html !== void 0 ? /* @__PURE__ */ jsx(
106
109
  "iframe",
107
110
  {
108
111
  className: `${baseClass}__frame`,
@@ -0,0 +1,28 @@
1
+ /* ============================================
2
+ BACK TO TOP COMPONENT
3
+ A neutral IconButton pinned to the bottom end corner,
4
+ fading and rising in once the page has scrolled.
5
+ ============================================ */
6
+
7
+ .ds-back-to-top {
8
+ position: fixed;
9
+ inset-block-end: var(--ds-back-to-top-inset, var(--gap-500));
10
+ inset-inline-end: var(--ds-back-to-top-inset, var(--gap-500));
11
+ z-index: var(--layer-sticky);
12
+ opacity: 0;
13
+ transform: translateY(var(--gap-200));
14
+ pointer-events: none;
15
+ transition:
16
+ opacity var(--motion-duration-base) var(--motion-ease-standard),
17
+ transform var(--motion-duration-base) var(--motion-ease-standard);
18
+ }
19
+
20
+ .ds-back-to-top--shown {
21
+ opacity: 1;
22
+ transform: none;
23
+ pointer-events: auto;
24
+ }
25
+
26
+ .ds-back-to-top .ds-icon-button {
27
+ box-shadow: var(--shadow-floating);
28
+ }
@@ -0,0 +1,28 @@
1
+ import { default as React } from 'react';
2
+ /** Props owned by BackToTop itself. */
3
+ type BackToTopOwnProps = {
4
+ /** How far, in px, the page scrolls before the button appears. `0` shows it at once. */
5
+ threshold?: number;
6
+ /** Accessible name and tooltip of the button. */
7
+ label?: string;
8
+ /**
9
+ * The id of the element to move focus to after the jump (the page's main
10
+ * region, say), so a keyboard reader continues from the top too. Leave it
11
+ * out to keep focus on the button.
12
+ */
13
+ focusTarget?: string;
14
+ /** Additional CSS classes */
15
+ className?: string;
16
+ };
17
+ export interface BackToTopProps extends BackToTopOwnProps, Omit<React.ComponentPropsWithRef<'div'>, keyof BackToTopOwnProps | 'children'> {
18
+ }
19
+ /**
20
+ * BackToTop: a round button pinned to the page's bottom end corner that
21
+ * appears once the reader has scrolled a long way down, and takes them
22
+ * back to the top. Smooth, unless the reader asks for reduced motion.
23
+ * The ref and native attributes go to the pinned wrapper, the node that
24
+ * appears and hides; the button inside is an IconButton named by `label`.
25
+ * While hidden it is inert, so it is never a tab stop that does nothing.
26
+ */
27
+ export declare function BackToTop({ threshold, label, focusTarget, className, ref, ...rest }: BackToTopProps): React.JSX.Element;
28
+ export {};
@@ -0,0 +1,47 @@
1
+ "use client";
2
+ import { jsx } from "react/jsx-runtime";
3
+ import { useState, useEffect } from "react";
4
+ import { IconButton } from "../IconButton/IconButton.js";
5
+ import "./BackToTop.css";
6
+ function BackToTop({
7
+ threshold = 640,
8
+ label = "Back to top",
9
+ focusTarget,
10
+ className = "",
11
+ ref,
12
+ ...rest
13
+ }) {
14
+ const [shown, setShown] = useState(false);
15
+ useEffect(() => {
16
+ let frame = 0;
17
+ const measure = () => {
18
+ frame = 0;
19
+ setShown(threshold === 0 || window.scrollY > threshold);
20
+ };
21
+ const schedule = () => {
22
+ if (frame === 0) frame = window.requestAnimationFrame(measure);
23
+ };
24
+ measure();
25
+ window.addEventListener("scroll", schedule, { passive: true });
26
+ return () => {
27
+ window.removeEventListener("scroll", schedule);
28
+ if (frame !== 0) window.cancelAnimationFrame(frame);
29
+ };
30
+ }, [threshold]);
31
+ const toTop = () => {
32
+ const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
33
+ window.scrollTo({ top: 0, behavior: reduce ? "auto" : "smooth" });
34
+ if (focusTarget) {
35
+ const target = document.getElementById(focusTarget);
36
+ if (target) {
37
+ if (!target.hasAttribute("tabindex")) target.setAttribute("tabindex", "-1");
38
+ target.focus({ preventScroll: true });
39
+ }
40
+ }
41
+ };
42
+ const classes = ["ds-back-to-top", shown ? "ds-back-to-top--shown" : "", className].filter(Boolean).join(" ");
43
+ return /* @__PURE__ */ jsx("div", { ...rest, ref, className: classes, inert: !shown, children: /* @__PURE__ */ jsx(IconButton, { icon: "arrow_upward", label, variant: "primary", tone: "neutral", tooltipPosition: "start", onClick: toTop }) });
44
+ }
45
+ export {
46
+ BackToTop
47
+ };
@@ -282,6 +282,9 @@
282
282
  .ds-bento-tile__description {
283
283
  margin: 0;
284
284
  max-width: 48ch;
285
+ /* A long unbroken run (a prop sample, a URL) breaks at the tile's edge
286
+ rather than running past it in a narrow tile. */
287
+ overflow-wrap: anywhere;
285
288
  color: var(--color-text-secondary);
286
289
  font-size: var(--font-paragraph-size);
287
290
  line-height: var(--font-paragraph-line-height);
@@ -103,39 +103,28 @@
103
103
 
104
104
  /* ============================================
105
105
  COPY BUTTON
106
+ A compact tertiary CopyButton; nothing to restyle.
106
107
  ============================================ */
107
108
 
108
109
  .ds-code-block__copy {
109
- display: inline-flex;
110
- align-items: center;
111
- gap: var(--gap-100);
112
- margin: 0;
113
- padding: var(--padding-050) var(--padding-200);
114
- border: none;
115
- border-radius: var(--radius-pill);
116
- background: none;
117
- font-family: var(--font-paragraph-sm-emphasis-family);
118
- font-size: var(--font-paragraph-sm-emphasis-size);
119
- font-weight: var(--font-paragraph-sm-emphasis-weight);
120
- line-height: var(--font-paragraph-sm-emphasis-line-height);
121
- color: var(--color-text-secondary);
122
- cursor: pointer;
123
110
  flex-shrink: 0;
124
- transition: background-color var(--motion-duration-base) var(--motion-ease-standard), color var(--motion-duration-base) var(--motion-ease-standard);
125
111
  }
126
112
 
127
- .ds-code-block__copy .material-symbols-rounded {
128
- --icon-size: var(--icon-size-500);
129
- line-height: 1;
130
- }
113
+ /* ============================================
114
+ TABS
115
+ The header's row of tabs: the Tabs component at its compact size,
116
+ sat on the header's divider so the active underline is the divider's
117
+ own segment rather than a second line above it.
118
+ ============================================ */
131
119
 
132
- .ds-code-block__copy:hover {
133
- background-color: var(--color-action-passive-bg-hover);
120
+ .ds-code-block__header--tabs {
121
+ padding-block: 0;
122
+ padding-inline-start: var(--padding-200);
134
123
  }
135
124
 
136
- .ds-code-block__copy:focus-visible {
137
- outline: 2px solid var(--color-action-primary-bg);
138
- outline-offset: 2px;
125
+ .ds-code-block__tabs {
126
+ margin-block-end: calc(-1 * var(--border-025));
127
+ border-block-end: none;
139
128
  }
140
129
 
141
130
  /* ============================================
@@ -181,6 +170,56 @@
181
170
  white-space: pre;
182
171
  }
183
172
 
173
+ /* ============================================
174
+ LINES
175
+ Rendered line by line when the code is highlighted, numbered or has
176
+ marked lines. A marked line bleeds to the block's edges, so its wash
177
+ reads as the whole row rather than a box around the text.
178
+ ============================================ */
179
+
180
+ .ds-code-block__code--lines {
181
+ display: block;
182
+ min-width: max-content;
183
+ }
184
+
185
+ .ds-code-block__line {
186
+ display: flex;
187
+ gap: var(--gap-400);
188
+ margin-inline: calc(-1 * var(--padding-400));
189
+ padding-inline: calc(var(--padding-400) - var(--border-050)) var(--padding-400);
190
+ border-inline-start: var(--border-050) solid transparent;
191
+ }
192
+
193
+ .ds-code-block__line--marked {
194
+ background-color: var(--color-bg-container-tertiary);
195
+ border-inline-start-color: var(--color-text-tertiary);
196
+ }
197
+
198
+ .ds-code-block__line-number {
199
+ flex-shrink: 0;
200
+ min-width: var(--ds-code-block-gutter, 1ch);
201
+ text-align: end;
202
+ color: var(--color-text-tertiary);
203
+ user-select: none;
204
+ }
205
+
206
+ /* An empty line keeps its height without putting a character on the
207
+ clipboard. */
208
+ .ds-code-block__line-text:empty::before {
209
+ content: ' ';
210
+ }
211
+
212
+ /* ============================================
213
+ SYNTAX ROLES
214
+ Only present when the consumer passes highlighted lines.
215
+ ============================================ */
216
+
217
+ .ds-code-block__token--keyword { color: var(--color-code-keyword); }
218
+ .ds-code-block__token--string { color: var(--color-code-string); }
219
+ .ds-code-block__token--function { color: var(--color-code-function); }
220
+ .ds-code-block__token--constant { color: var(--color-code-constant); }
221
+ .ds-code-block__token--comment { color: var(--color-code-comment); }
222
+
184
223
  /* Icons take the colour of the text around them. Explicit, not just
185
224
  inherited by default: a consumer stylesheet that sets a colour on
186
225
  .material-symbols-rounded itself (a common global default) would
@@ -1,16 +1,70 @@
1
1
  import { default as React } from 'react';
2
+ /** A syntax role a highlighter marks a run of code with. Each is coloured by its `--color-code-*` token. */
3
+ export type CodeTokenRole = 'keyword' | 'string' | 'function' | 'constant' | 'comment';
4
+ /** One run of code text, optionally marked with a syntax role. */
5
+ export interface CodeToken {
6
+ /** The text of the run, exactly as it appears in the source. */
7
+ content: string;
8
+ /** The syntax role, which picks its colour. Leave it out for plain text. */
9
+ role?: CodeTokenRole;
10
+ }
11
+ /** One line of highlighted code: its runs, in order, with no newline. */
12
+ export type CodeLine = CodeToken[];
13
+ /** One snippet in a tabbed CodeBlock. */
14
+ export interface CodeBlockTab {
15
+ /** Unique value; also the value a `syncKey` shares between blocks. */
16
+ value: string;
17
+ /** Tab label, e.g. "pnpm". */
18
+ label: string;
19
+ /** The snippet, as a plain string. Copied as is. */
20
+ code: string;
21
+ /** The snippet highlighted, as returned by `highlight()` from `rift-ds/code/highlight`. */
22
+ lines?: CodeLine[];
23
+ }
2
24
  /** Props owned by CodeBlock itself — everything else falls through to the root div. */
3
25
  type CodeBlockOwnProps = {
4
- /** The code to display, as a plain string */
5
- code: string;
26
+ /** The code to display, as a plain string. Required unless `lines` or `tabs` supply it. */
27
+ code?: string;
28
+ /**
29
+ * The code highlighted, one array of tokens per line, as returned by
30
+ * `highlight()` from `rift-ds/code/highlight`. Each token is coloured by
31
+ * its role. Without it the code is monochrome. When `code` is left out,
32
+ * the copy button copies the text of these lines.
33
+ */
34
+ lines?: CodeLine[];
6
35
  /** Language tag shown in the header, e.g. "tsx", "css" */
7
36
  language?: string;
8
37
  /** Filename shown in the header, e.g. "tokens-light.css" */
9
38
  filename?: string;
39
+ /** Show a line number before each line. */
40
+ showLineNumbers?: boolean;
41
+ /** Line numbers (counted from 1) to mark with a highlighted background, e.g. the lines a step changed. */
42
+ highlightLines?: number[];
43
+ /**
44
+ * Several snippets behind a row of tabs in the header (an install command
45
+ * for each package manager, the same example in two languages). Replaces
46
+ * the filename and language. `packageManagerTabs()` from `rift-ds/code`
47
+ * writes the install case.
48
+ */
49
+ tabs?: CodeBlockTab[];
50
+ /** The selected tab's value (controlled). */
51
+ value?: string;
52
+ /** The initially selected tab's value (uncontrolled). Defaults to the first tab. */
53
+ defaultValue?: string;
54
+ /** Called with the tab's value when the reader picks a tab. */
55
+ onValueChange?: (value: string) => void;
56
+ /**
57
+ * Share the selected tab with every CodeBlock on the page that has the
58
+ * same key, and remember it for the reader's next visit (in
59
+ * localStorage). Ignored while `value` is controlled.
60
+ */
61
+ syncKey?: string;
62
+ /** Accessible name for the tab list. */
63
+ tabsLabel?: string;
10
64
  /** Show the copy-to-clipboard button */
11
65
  showCopy?: boolean;
12
- /** Called after the code is put on the clipboard, through the async API or its textarea fallback, so a host can count copies. */
13
- onCopied?: () => void;
66
+ /** Called with the copied text (the shown tab's code, or the text of `lines`) as it is sent to the clipboard, through the async API or its textarea fallback (the write is not awaited), so a host can count copies. */
67
+ onCopied?: (value: string) => void;
14
68
  /** Max height of the block; code scrolls vertically inside while the header stays pinned. Numbers are px. */
15
69
  maxHeight?: number | string;
16
70
  /** Show a chevron beside the filename that collapses/expands the code area */
@@ -39,8 +93,10 @@ export interface CodeBlockProps extends CodeBlockOwnProps, Omit<React.ComponentP
39
93
  }
40
94
  /**
41
95
  * CodeBlock component — monospace code with an optional header row
42
- * (filename, language tag) and a copy-to-clipboard button. Forwards a ref
43
- * to the root div and spreads native attributes onto it.
96
+ * (filename, language tag, or a row of tabs) and a copy-to-clipboard
97
+ * button. Highlighted `lines`, line numbers and marked lines are opt-in;
98
+ * plain `code` renders exactly as before. Forwards a ref to the root div and
99
+ * spreads native attributes onto it.
44
100
  */
45
101
  export declare const CodeBlock: React.ForwardRefExoticComponent<CodeBlockProps & React.RefAttributes<HTMLDivElement>>;
46
102
  export {};
@@ -1,14 +1,26 @@
1
1
  "use client";
2
- import { jsxs, jsx } from "react/jsx-runtime";
2
+ import { jsxs, jsx, Fragment } from "react/jsx-runtime";
3
3
  import React, { useState, useId } from "react";
4
- import { MOTION_FEEDBACK_RESET_MS } from "../../tokens/motion.js";
4
+ import { CopyButton } from "../CopyButton/CopyButton.js";
5
+ import { Tabs } from "../Tabs/Tabs.js";
6
+ import { useSyncedChoice } from "../../behaviors/syncedChoice.js";
5
7
  import "./CodeBlock.css";
6
8
  import "../../fonts/material-symbols.css";
9
+ const linesText = (lines) => lines.map((line) => line.map((t) => t.content).join("")).join("\n");
7
10
  const CodeBlock = React.forwardRef(
8
11
  ({
9
12
  code,
13
+ lines,
10
14
  language,
11
15
  filename,
16
+ showLineNumbers = false,
17
+ highlightLines,
18
+ tabs,
19
+ value: valueProp,
20
+ defaultValue,
21
+ onValueChange,
22
+ syncKey,
23
+ tabsLabel = "Code variants",
12
24
  showCopy = true,
13
25
  onCopied,
14
26
  maxHeight,
@@ -25,43 +37,41 @@ const CodeBlock = React.forwardRef(
25
37
  ...rest
26
38
  }, ref) => {
27
39
  const baseClass = "ds-code-block";
28
- const [copied, setCopied] = useState(false);
29
40
  const [collapsed, setCollapsed] = useState(collapsible && defaultCollapsed);
30
41
  const panelId = useId();
42
+ const hasTabs = Boolean(tabs && tabs.length > 0);
43
+ const firstValue = defaultValue ?? tabs?.[0]?.value;
44
+ const [localValue, setLocalValue] = useState(firstValue);
45
+ const [syncedValue, setSyncedValue] = useSyncedChoice(hasTabs ? syncKey : void 0, firstValue);
46
+ const picked = valueProp ?? (syncKey ? syncedValue : localValue);
47
+ const activeTab = hasTabs ? tabs.find((t) => t.value === picked) ?? tabs[0] : void 0;
48
+ const selectTab = (next) => {
49
+ if (valueProp === void 0) {
50
+ if (syncKey) setSyncedValue(next);
51
+ else setLocalValue(next);
52
+ }
53
+ onValueChange?.(next);
54
+ };
55
+ const shownLines = activeTab ? activeTab.lines : lines;
56
+ const shownCode = activeTab ? activeTab.code : code ?? (lines ? linesText(lines) : "");
57
+ const marked = new Set(highlightLines ?? []);
58
+ const byLine = Boolean(shownLines || showLineNumbers || marked.size > 0);
59
+ const rows = byLine ? shownLines ?? shownCode.split("\n").map((text) => [{ content: text }]) : null;
31
60
  const classes = [
32
61
  baseClass,
33
62
  collapsed ? `${baseClass}--collapsed` : "",
63
+ showLineNumbers ? `${baseClass}--numbered` : "",
34
64
  className
35
65
  ].filter(Boolean).join(" ");
36
- const rootStyle = maxHeight !== void 0 ? {
66
+ const rootStyle = {
37
67
  ...style,
38
- "--ds-code-block-max-height": typeof maxHeight === "number" ? `${maxHeight}px` : maxHeight
39
- } : style;
40
- const hasHeader = Boolean(filename || language || showCopy || collapsible);
41
- const regionLabel = codeLabel ?? (filename ? `Code: ${filename}` : language ? `Code: ${language}` : "Code");
42
- const copy = () => {
43
- const fallback = () => {
44
- const textarea = document.createElement("textarea");
45
- textarea.value = code;
46
- textarea.setAttribute("readonly", "");
47
- textarea.style.position = "absolute";
48
- textarea.style.left = "-9999px";
49
- document.body.appendChild(textarea);
50
- textarea.select();
51
- document.execCommand("copy");
52
- document.body.removeChild(textarea);
53
- };
54
- if (navigator.clipboard?.writeText) {
55
- navigator.clipboard.writeText(code).catch(fallback);
56
- } else {
57
- fallback();
58
- }
59
- onCopied?.();
60
- setCopied(true);
61
- window.setTimeout(() => setCopied(false), MOTION_FEEDBACK_RESET_MS);
68
+ ...maxHeight !== void 0 ? { "--ds-code-block-max-height": typeof maxHeight === "number" ? `${maxHeight}px` : maxHeight } : null,
69
+ ...rows && showLineNumbers ? { "--ds-code-block-gutter": `${String(rows.length).length}ch` } : null
62
70
  };
71
+ const hasHeader = Boolean(hasTabs || filename || language || showCopy || collapsible);
72
+ const regionLabel = codeLabel ?? (activeTab ? `Code: ${activeTab.label}` : filename ? `Code: ${filename}` : language ? `Code: ${language}` : "Code");
63
73
  return /* @__PURE__ */ jsxs("div", { ...rest, ref, className: classes, style: rootStyle, children: [
64
- hasHeader && /* @__PURE__ */ jsxs("div", { className: `${baseClass}__header`, children: [
74
+ hasHeader && /* @__PURE__ */ jsxs("div", { className: `${baseClass}__header${hasTabs ? ` ${baseClass}__header--tabs` : ""}`, children: [
65
75
  /* @__PURE__ */ jsxs("div", { className: `${baseClass}__meta`, children: [
66
76
  collapsible && /* @__PURE__ */ jsx(
67
77
  "button",
@@ -75,33 +85,65 @@ const CodeBlock = React.forwardRef(
75
85
  children: /* @__PURE__ */ jsx("span", { className: "material-symbols-rounded", "aria-hidden": "true", children: "expand_more" })
76
86
  }
77
87
  ),
78
- filename && /* @__PURE__ */ jsx("code", { className: `${baseClass}__filename`, children: filename }),
79
- language && /* @__PURE__ */ jsx("span", { className: `${baseClass}__language`, children: language })
88
+ hasTabs ? /* @__PURE__ */ jsx(
89
+ Tabs,
90
+ {
91
+ className: `${baseClass}__tabs`,
92
+ size: "compact",
93
+ "aria-label": tabsLabel,
94
+ tabs: tabs.map((t) => ({ value: t.value, label: t.label, panelId })),
95
+ value: activeTab.value,
96
+ onValueChange: selectTab
97
+ }
98
+ ) : /* @__PURE__ */ jsxs(Fragment, { children: [
99
+ filename && /* @__PURE__ */ jsx("code", { className: `${baseClass}__filename`, children: filename }),
100
+ language && /* @__PURE__ */ jsx("span", { className: `${baseClass}__language`, children: language })
101
+ ] })
80
102
  ] }),
81
- showCopy && /* @__PURE__ */ jsxs(
82
- "button",
103
+ showCopy && /* @__PURE__ */ jsx(
104
+ CopyButton,
83
105
  {
84
- type: "button",
85
106
  className: `${baseClass}__copy`,
86
- onClick: copy,
87
- "aria-label": copied ? copiedLabel : copyLabel,
88
- children: [
89
- /* @__PURE__ */ jsx("span", { className: "material-symbols-rounded", "aria-hidden": "true", children: copied ? "check" : "content_copy" }),
90
- copied ? copiedLabel : copyText
91
- ]
107
+ value: shownCode,
108
+ onCopied,
109
+ copyText,
110
+ copyLabel,
111
+ copiedLabel
92
112
  }
93
113
  )
94
114
  ] }),
95
- /* @__PURE__ */ jsx("div", { id: panelId, className: `${baseClass}__panel`, "aria-hidden": collapsed || void 0, children: /* @__PURE__ */ jsx("div", { className: `${baseClass}__panel-inner`, children: /* @__PURE__ */ jsx(
96
- "pre",
115
+ /* @__PURE__ */ jsx(
116
+ "div",
97
117
  {
98
- className: `${baseClass}__pre`,
99
- tabIndex: collapsed ? -1 : 0,
100
- role: "region",
101
- "aria-label": regionLabel,
102
- children: /* @__PURE__ */ jsx("code", { className: `${baseClass}__code`, children: code })
118
+ id: panelId,
119
+ className: `${baseClass}__panel`,
120
+ "aria-hidden": collapsed || void 0,
121
+ role: hasTabs ? "tabpanel" : void 0,
122
+ "aria-label": hasTabs ? activeTab.label : void 0,
123
+ children: /* @__PURE__ */ jsx("div", { className: `${baseClass}__panel-inner`, children: /* @__PURE__ */ jsx(
124
+ "pre",
125
+ {
126
+ className: `${baseClass}__pre`,
127
+ tabIndex: collapsed ? -1 : 0,
128
+ role: hasTabs ? void 0 : "region",
129
+ "aria-label": hasTabs ? void 0 : regionLabel,
130
+ children: rows ? /* @__PURE__ */ jsx("code", { className: `${baseClass}__code ${baseClass}__code--lines`, children: rows.map((line, index) => /* @__PURE__ */ jsxs(
131
+ "span",
132
+ {
133
+ className: `${baseClass}__line${marked.has(index + 1) ? ` ${baseClass}__line--marked` : ""}`,
134
+ children: [
135
+ showLineNumbers && /* @__PURE__ */ jsx("span", { className: `${baseClass}__line-number`, "aria-hidden": "true", children: index + 1 }),
136
+ /* @__PURE__ */ jsx("span", { className: `${baseClass}__line-text`, children: line.map(
137
+ (token, t) => token.role ? /* @__PURE__ */ jsx("span", { className: `${baseClass}__token ${baseClass}__token--${token.role}`, children: token.content }, t) : token.content
138
+ ) })
139
+ ]
140
+ },
141
+ index
142
+ )) }) : /* @__PURE__ */ jsx("code", { className: `${baseClass}__code`, children: shownCode })
143
+ }
144
+ ) })
103
145
  }
104
- ) }) })
146
+ )
105
147
  ] });
106
148
  }
107
149
  );
@@ -0,0 +1,42 @@
1
+ import { default as React } from 'react';
2
+ /** Props owned by CopyButton itself. */
3
+ type CopyButtonOwnProps = {
4
+ /** The text put on the clipboard, or a function that returns it at the moment of the press (for a value that changes, such as the current URL). */
5
+ value: string | (() => string);
6
+ /** Called with the copied text as it is sent to the clipboard (the write is not awaited), so a host can count copies or announce them. */
7
+ onCopied?: (value: string) => void;
8
+ /** Visible text before a copy. When `iconOnly`, it is the accessible name and the tooltip instead, unless `copyLabel` is set. */
9
+ copyText?: string;
10
+ /** Accessible name before a copy. Defaults to `copyText`. */
11
+ copyLabel?: string;
12
+ /** Visible text and accessible name for a moment after a copy. */
13
+ copiedLabel?: string;
14
+ /** Show only the glyph, with the label in a tooltip, as an IconButton. */
15
+ iconOnly?: boolean;
16
+ /**
17
+ * Where the icon-only form's tooltip sits, as on IconButton.
18
+ * @default 'top'
19
+ */
20
+ tooltipPosition?: 'top' | 'bottom' | 'left' | 'right' | 'start' | 'end';
21
+ /** Visual emphasis, as on Button. */
22
+ variant?: 'secondary' | 'tertiary';
23
+ /** Colour, as on Button: `neutral` draws the secondary outline in the neutral greys rather than the action colour, for a utility control such as a page's "Copy link". */
24
+ tone?: 'default' | 'neutral';
25
+ /** Control size, as on Button. */
26
+ size?: 'default' | 'compact';
27
+ /** Disable the button. */
28
+ disabled?: boolean;
29
+ /** Additional CSS classes. */
30
+ className?: string;
31
+ };
32
+ export interface CopyButtonProps extends CopyButtonOwnProps, Omit<React.ComponentPropsWithRef<'button'>, keyof CopyButtonOwnProps | 'children' | 'type' | 'value' | 'aria-label'> {
33
+ }
34
+ /**
35
+ * CopyButton: puts a value on the clipboard and says so. A Button (or an
36
+ * IconButton when `iconOnly`) whose glyph turns from a copy mark to a check,
37
+ * and whose label turns to `copiedLabel`, for a moment after the press. The
38
+ * write goes through the library's one clipboard behaviour, so it falls back
39
+ * to a hidden textarea where the async API is missing.
40
+ */
41
+ export declare function CopyButton({ value, onCopied, copyText, copyLabel, copiedLabel, iconOnly, tooltipPosition, variant, tone, size, disabled, className, onClick, ref, ...rest }: CopyButtonProps): React.JSX.Element;
42
+ export {};
@@ -0,0 +1,72 @@
1
+ "use client";
2
+ import { jsx } from "react/jsx-runtime";
3
+ import "react";
4
+ import { Button } from "../Button/Button.js";
5
+ import { IconButton } from "../IconButton/IconButton.js";
6
+ import { useCopied } from "../../behaviors/clipboard.js";
7
+ function CopyButton({
8
+ value,
9
+ onCopied,
10
+ copyText = "Copy",
11
+ copyLabel,
12
+ copiedLabel = "Copied",
13
+ iconOnly = false,
14
+ tooltipPosition = "top",
15
+ variant = "tertiary",
16
+ tone = "default",
17
+ size = "compact",
18
+ disabled = false,
19
+ className = "",
20
+ onClick,
21
+ ref,
22
+ ...rest
23
+ }) {
24
+ const { copied, copy } = useCopied();
25
+ const classes = ["ds-copy-button", className].filter(Boolean).join(" ");
26
+ const icon = copied ? "check" : "content_copy";
27
+ const name = copied ? copiedLabel : copyLabel ?? copyText;
28
+ const handleClick = (event) => {
29
+ onClick?.(event);
30
+ if (event.defaultPrevented) return;
31
+ const text = typeof value === "function" ? value() : value;
32
+ copy(text);
33
+ onCopied?.(text);
34
+ };
35
+ if (iconOnly) {
36
+ return /* @__PURE__ */ jsx(
37
+ IconButton,
38
+ {
39
+ ...rest,
40
+ ref,
41
+ className: classes,
42
+ icon,
43
+ label: name,
44
+ tooltipPosition,
45
+ variant,
46
+ tone,
47
+ size,
48
+ disabled,
49
+ onClick: handleClick
50
+ }
51
+ );
52
+ }
53
+ return /* @__PURE__ */ jsx(
54
+ Button,
55
+ {
56
+ ...rest,
57
+ ref,
58
+ className: classes,
59
+ iconLeft: icon,
60
+ variant,
61
+ tone,
62
+ size,
63
+ disabled,
64
+ "aria-label": copyLabel && !copied ? copyLabel : void 0,
65
+ onClick: handleClick,
66
+ children: copied ? copiedLabel : copyText
67
+ }
68
+ );
69
+ }
70
+ export {
71
+ CopyButton
72
+ };