@redvars/peacock 3.16.0 → 3.17.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 (147) hide show
  1. package/dist/assets/styles.css +1 -1
  2. package/dist/assets/styles.css.map +1 -1
  3. package/dist/assets/theme.js +19 -19
  4. package/dist/assets/tokens.css +1 -1
  5. package/dist/assets/tokens.css.map +1 -1
  6. package/dist/card-content.js +8 -7
  7. package/dist/card-content.js.map +1 -1
  8. package/dist/card.js +142 -98
  9. package/dist/card.js.map +1 -1
  10. package/dist/{chart-bar-D5dGFJfK.js → cartesian-chart-DgE4USyC.js} +529 -312
  11. package/dist/cartesian-chart-DgE4USyC.js.map +1 -0
  12. package/dist/chart-area.js +78 -0
  13. package/dist/chart-area.js.map +1 -0
  14. package/dist/chart-bar.js +283 -213
  15. package/dist/chart-bar.js.map +1 -1
  16. package/dist/{transform-DSwFSqzD.js → chart-base-C2qRMF48.js} +771 -102
  17. package/dist/chart-base-C2qRMF48.js.map +1 -0
  18. package/dist/chart-doughnut.js +55 -287
  19. package/dist/chart-doughnut.js.map +1 -1
  20. package/dist/chart-line.js +626 -0
  21. package/dist/chart-line.js.map +1 -0
  22. package/dist/chart-pie.js +637 -195
  23. package/dist/chart-pie.js.map +1 -1
  24. package/dist/code-editor.js +704 -131
  25. package/dist/code-editor.js.map +1 -1
  26. package/dist/code-group.js +188 -0
  27. package/dist/code-group.js.map +1 -0
  28. package/dist/code-highlighter.js +895 -257
  29. package/dist/code-highlighter.js.map +1 -1
  30. package/dist/custom-elements-jsdocs.json +1675 -222
  31. package/dist/custom-elements.json +13351 -3970
  32. package/dist/image.js +5 -1
  33. package/dist/image.js.map +1 -1
  34. package/dist/index.js +8 -7
  35. package/dist/index.js.map +1 -1
  36. package/dist/loader-full.js +1 -1
  37. package/dist/loader.js +9 -3
  38. package/dist/loader.js.map +1 -1
  39. package/dist/{is-dark-mode-DOcaw4Yq.js → observe-theme-change-DCifz1uv.js} +2 -6
  40. package/dist/observe-theme-change-DCifz1uv.js.map +1 -0
  41. package/dist/path-CJ0Arqcy.js +166 -0
  42. package/dist/path-CJ0Arqcy.js.map +1 -0
  43. package/dist/snackbar.js +89 -34
  44. package/dist/snackbar.js.map +1 -1
  45. package/dist/src/__internal/chart/cartesian-chart.d.ts +80 -0
  46. package/dist/src/__internal/chart/chart-base.d.ts +113 -0
  47. package/dist/src/__internal/chart/paths.d.ts +5 -0
  48. package/dist/src/__internal/chart/types.d.ts +42 -0
  49. package/dist/src/card/card-content.d.ts +2 -3
  50. package/dist/src/card/card.d.ts +31 -17
  51. package/dist/src/chart-area/chart-area.d.ts +54 -0
  52. package/dist/src/chart-area/index.d.ts +1 -0
  53. package/dist/src/chart-bar/chart-bar.d.ts +44 -33
  54. package/dist/src/chart-bar/index.d.ts +0 -1
  55. package/dist/src/chart-doughnut/chart-doughnut.d.ts +33 -39
  56. package/dist/src/chart-line/chart-line.d.ts +69 -0
  57. package/dist/src/chart-line/index.d.ts +1 -0
  58. package/dist/src/chart-pie/chart-pie.d.ts +63 -28
  59. package/dist/src/code-editor/code-editor.d.ts +52 -13
  60. package/dist/src/code-editor/editor-theme.d.ts +60 -0
  61. package/dist/src/code-highlighter/code-group.d.ts +52 -0
  62. package/dist/src/code-highlighter/code-highlighter.d.ts +122 -15
  63. package/dist/src/code-highlighter/index.d.ts +1 -0
  64. package/dist/src/code-highlighter/line-ranges.d.ts +24 -0
  65. package/dist/src/code-highlighter/local.d.ts +4 -1
  66. package/dist/src/code-highlighter/token-colors.d.ts +8 -0
  67. package/dist/src/index.d.ts +4 -2
  68. package/dist/src/snackbar/snackbar.d.ts +13 -1
  69. package/dist/src/toolbar/toolbar.d.ts +56 -51
  70. package/dist/table.js +9 -4
  71. package/dist/table.js.map +1 -1
  72. package/dist/test/chart.test.d.ts +1 -0
  73. package/dist/test/code-highlighter.test.d.ts +1 -0
  74. package/dist/token-colors-0TFHWbcq.js +81 -0
  75. package/dist/token-colors-0TFHWbcq.js.map +1 -0
  76. package/dist/toolbar.js +195 -184
  77. package/dist/toolbar.js.map +1 -1
  78. package/dist/tsconfig.tsbuildinfo +1 -1
  79. package/package.json +1 -2
  80. package/readme.md +7 -6
  81. package/scss/_code-block.scss +139 -0
  82. package/scss/tokens.css +24 -0
  83. package/src/__internal/chart/cartesian-chart.ts +404 -0
  84. package/src/__internal/chart/chart-base.scss +252 -0
  85. package/src/__internal/chart/chart-base.ts +474 -0
  86. package/src/__internal/chart/paths.ts +28 -0
  87. package/src/__internal/chart/types.ts +49 -0
  88. package/src/card/card-content.ts +12 -9
  89. package/src/card/card.scss +66 -54
  90. package/src/card/card.ts +109 -73
  91. package/src/chart-area/chart-area.ts +82 -0
  92. package/src/chart-area/index.ts +1 -0
  93. package/src/chart-bar/chart-bar.ts +336 -250
  94. package/src/chart-bar/index.ts +0 -1
  95. package/src/chart-doughnut/chart-doughnut.ts +62 -262
  96. package/src/chart-doughnut/demo/index.html +14 -22
  97. package/src/chart-line/chart-line.scss +25 -0
  98. package/src/chart-line/chart-line.ts +346 -0
  99. package/src/chart-line/index.ts +1 -0
  100. package/src/chart-pie/chart-pie.scss +35 -16
  101. package/src/chart-pie/chart-pie.ts +282 -188
  102. package/src/chart-pie/demo/index.html +13 -21
  103. package/src/code-editor/code-editor.scss +132 -36
  104. package/src/code-editor/code-editor.ts +308 -88
  105. package/src/code-editor/demo/index.html +39 -12
  106. package/src/code-editor/editor-theme.ts +213 -0
  107. package/src/code-highlighter/code-group.scss +34 -0
  108. package/src/code-highlighter/code-group.ts +173 -0
  109. package/src/code-highlighter/code-highlighter.scss +226 -111
  110. package/src/code-highlighter/code-highlighter.ts +554 -199
  111. package/src/code-highlighter/demo/index.html +68 -4
  112. package/src/code-highlighter/index.ts +1 -0
  113. package/src/code-highlighter/line-ranges.ts +81 -0
  114. package/src/code-highlighter/local.ts +9 -3
  115. package/src/code-highlighter/token-colors.ts +42 -0
  116. package/src/index.ts +4 -2
  117. package/src/loader.ts +8 -2
  118. package/src/snackbar/demo/index.html +39 -4
  119. package/src/snackbar/snackbar.scss +27 -10
  120. package/src/snackbar/snackbar.ts +80 -37
  121. package/src/table/table.scss +7 -1
  122. package/src/table/table.ts +4 -3
  123. package/src/toolbar/toolbar-colors.scss +6 -7
  124. package/src/toolbar/toolbar.scss +35 -106
  125. package/src/toolbar/toolbar.ts +180 -80
  126. package/dist/array-D5vjT2Xm.js +0 -14
  127. package/dist/array-D5vjT2Xm.js.map +0 -1
  128. package/dist/chart-bar-D5dGFJfK.js.map +0 -1
  129. package/dist/chart-stacked-bar.js +0 -403
  130. package/dist/chart-stacked-bar.js.map +0 -1
  131. package/dist/copy-to-clipboard-upGx-Ueo.js +0 -39
  132. package/dist/copy-to-clipboard-upGx-Ueo.js.map +0 -1
  133. package/dist/is-dark-mode-DOcaw4Yq.js.map +0 -1
  134. package/dist/pie-Dz0IDiPt.js +0 -537
  135. package/dist/pie-Dz0IDiPt.js.map +0 -1
  136. package/dist/pierre-dark-DFWl0m-C.js +0 -4
  137. package/dist/pierre-dark-DFWl0m-C.js.map +0 -1
  138. package/dist/pierre-light-BEkAPImt.js +0 -4
  139. package/dist/pierre-light-BEkAPImt.js.map +0 -1
  140. package/dist/src/chart-bar/chart-stacked-bar.d.ts +0 -78
  141. package/dist/src/code-highlighter/constants.d.ts +0 -1
  142. package/dist/transform-DSwFSqzD.js.map +0 -1
  143. package/src/chart-bar/chart-bar.scss +0 -58
  144. package/src/chart-bar/chart-stacked-bar.ts +0 -398
  145. package/src/chart-doughnut/chart-donut.scss +0 -37
  146. package/src/code-highlighter/constants.ts +0 -117
  147. /package/dist/test/{chart-bar.test.d.ts → card.test.d.ts} +0 -0
@@ -1,272 +1,540 @@
1
- import { html, LitElement } from 'lit';
2
- import { property, state } from 'lit/decorators.js';
3
- import { unsafeHTML } from 'lit/directives/unsafe-html.js';
1
+ import { html, LitElement, nothing, PropertyValues } from 'lit';
2
+ import { property, query, state } from 'lit/decorators.js';
4
3
  import { classMap } from 'lit/directives/class-map.js';
5
- import type { BundledLanguage, ShikiTransformer } from 'shiki';
4
+ import { styleMap } from 'lit/directives/style-map.js';
5
+ import type {
6
+ BundledLanguage,
7
+ SpecialLanguage,
8
+ ThemedToken,
9
+ ThemeRegistration,
10
+ } from 'shiki';
6
11
  import IndividualComponent from '@/IndividualComponent.js';
7
12
  import { copyToClipboard } from '@/__internal/utils/copy-to-clipboard.js';
13
+ import { locale } from './local.js';
14
+ import { TOKEN_DEFAULTS } from './token-colors.js';
15
+ import {
16
+ buildLineVariants,
17
+ decodeEntities,
18
+ dedent,
19
+ LineVariant,
20
+ splitLines,
21
+ } from './line-ranges.js';
8
22
  import styles from './code-highlighter.scss';
9
23
 
10
- // Module-level promises – Rollup splits each import() specifier into a separate chunk.
11
- // Caching here prevents parallel loads when multiple instances initialise at the same time.
12
- let _shiki: Promise<typeof import('shiki')> | null = null;
13
- let _themes: Promise<
14
- [
15
- typeof import('@pierre/theme/pierre-dark'),
16
- typeof import('@pierre/theme/pierre-light'),
17
- ]
18
- > | null = null;
19
- let _prettier: Promise<typeof import('prettier/standalone')> | null = null;
20
- let _pluginBabel: Promise<typeof import('prettier/plugins/babel')> | null =
21
- null;
22
- let _pluginHtml: Promise<typeof import('prettier/plugins/html')> | null = null;
23
- let _pluginPostcss: Promise<typeof import('prettier/plugins/postcss')> | null =
24
- null;
25
- let _pluginEstree: Promise<typeof import('prettier/plugins/estree')> | null =
26
- null;
27
-
28
- const loadShiki = () => (_shiki ??= import('shiki'));
29
-
30
- const loadThemes = () =>
31
- (_themes ??= Promise.all([
32
- import('@pierre/theme/pierre-dark'),
33
- import('@pierre/theme/pierre-light'),
34
- ]));
35
-
36
- const loadPrettier = () => (_prettier ??= import('prettier/standalone'));
37
- const loadPluginBabel = () =>
38
- (_pluginBabel ??= import('prettier/plugins/babel'));
39
- const loadPluginHtml = () => (_pluginHtml ??= import('prettier/plugins/html'));
40
- const loadPluginPostcss = () =>
41
- (_pluginPostcss ??= import('prettier/plugins/postcss'));
42
- const loadPluginEstree = () =>
43
- (_pluginEstree ??= import('prettier/plugins/estree'));
44
-
45
- const locale = {
46
- loading: 'Loading code...',
47
- copyToClipboard: 'Copy to clipboard',
48
- copied: 'Copied',
49
- copiedCode: 'Copied code',
50
- };
24
+ export type CodeHighlighterLanguage = BundledLanguage | SpecialLanguage;
25
+ export type CodeHighlighterSize = 'sm' | 'md';
26
+ export type CodeHighlighterVariant = 'default' | 'error';
27
+
28
+ /** Runs a loader once and returns the same promise on every later call. */
29
+ function once<T>(load: () => Promise<T>): () => Promise<T> {
30
+ let promise: Promise<T> | null = null;
31
+ return () => {
32
+ promise ??= load();
33
+ return promise;
34
+ };
35
+ }
36
+
37
+ // Module-level loaders – Rollup splits each import() specifier into a separate chunk.
38
+ // Caching prevents parallel loads when multiple instances initialise at the same time.
39
+ const loadShiki = once(() => import('shiki'));
40
+
41
+ // Syntax colors are CSS variables that fall back to Peacock color roles; see token-colors.ts.
42
+ const loadTheme = once<ThemeRegistration>(async () => {
43
+ const { createCssVariablesTheme } = await loadShiki();
44
+ return createCssVariablesTheme({
45
+ name: 'peacock',
46
+ variablePrefix: '--code-highlighter-',
47
+ variableDefaults: TOKEN_DEFAULTS,
48
+ fontStyle: true,
49
+ });
50
+ });
51
+
52
+ const loadPrettier = once(() => import('prettier/standalone'));
53
+ const loadPluginBabel = once(() => import('prettier/plugins/babel'));
54
+ const loadPluginHtml = once(() => import('prettier/plugins/html'));
55
+ const loadPluginPostcss = once(() => import('prettier/plugins/postcss'));
56
+ const loadPluginEstree = once(() => import('prettier/plugins/estree'));
57
+
58
+ /** Formats JavaScript, HTML and CSS with Prettier; other languages pass through. */
59
+ async function formatCode(code: string, language: string): Promise<string> {
60
+ switch (language) {
61
+ case 'javascript': {
62
+ const [prettier, pluginBabel, pluginEstree] = await Promise.all([
63
+ loadPrettier(),
64
+ loadPluginBabel(),
65
+ loadPluginEstree(),
66
+ ]);
67
+ return prettier.format(code, {
68
+ parser: 'babel',
69
+ plugins: [pluginBabel, pluginEstree],
70
+ bracketSameLine: true,
71
+ htmlWhitespaceSensitivity: 'ignore',
72
+ });
73
+ }
74
+ case 'html': {
75
+ const [prettier, pluginHtml] = await Promise.all([
76
+ loadPrettier(),
77
+ loadPluginHtml(),
78
+ ]);
79
+ return prettier.format(code, {
80
+ parser: 'html',
81
+ plugins: [pluginHtml],
82
+ bracketSameLine: true,
83
+ htmlWhitespaceSensitivity: 'ignore',
84
+ });
85
+ }
86
+ case 'css': {
87
+ const [prettier, pluginPostcss] = await Promise.all([
88
+ loadPrettier(),
89
+ loadPluginPostcss(),
90
+ ]);
91
+ return prettier.format(code, {
92
+ parser: 'css',
93
+ plugins: [pluginPostcss],
94
+ });
95
+ }
96
+ default:
97
+ return code;
98
+ }
99
+ }
100
+
101
+ /** Tokenizes code with the Peacock token theme. Throws for unknown languages. */
102
+ async function tokenize(
103
+ code: string,
104
+ language: string,
105
+ ): Promise<ThemedToken[][]> {
106
+ const [{ codeToTokens }, theme] = await Promise.all([
107
+ loadShiki(),
108
+ loadTheme(),
109
+ ]);
110
+ const result = await codeToTokens(code, {
111
+ lang: language as CodeHighlighterLanguage,
112
+ theme,
113
+ });
114
+ // Plain text inherits the block color, so variants can recolor it.
115
+ return result.tokens.map(line =>
116
+ line.map(token =>
117
+ token.color === result.fg ? { ...token, color: undefined } : token,
118
+ ),
119
+ );
120
+ }
121
+
122
+ // Shiki font style bit flags.
123
+ const FONT_ITALIC = 1;
124
+ const FONT_BOLD = 2;
125
+ const FONT_UNDERLINE = 4;
126
+ const FONT_STRIKETHROUGH = 8;
127
+
128
+ /** Whether a Shiki font style value has the given flag. `-1` means not set. */
129
+ const hasFontFlag = (fontStyle: number, flag: number) =>
130
+ fontStyle > 0 && Math.floor(fontStyle / flag) % 2 === 1;
51
131
 
52
132
  /**
53
133
  * @label Code Highlighter
54
134
  * @tag wc-code-highlighter
55
135
  * @rawTag code-highlighter
56
136
  *
57
- * @summary A component that provides syntax highlighting for code snippets.
137
+ * @summary Displays a block of code with syntax highlighting, line numbers, line highlights, diffs and a copy button.
58
138
  *
59
139
  * @example
60
140
  * ```html
61
- * <wc-code-highlighter language="javascript" style="height: 9rem"><pre><code>
141
+ * <wc-code-highlighter language="javascript" label="hello.js" line-numbers highlight-lines="2"><pre><code>
62
142
  * function helloWorld() {
63
143
  * console.log('Hello, world!');
64
144
  * }</code></pre>
65
145
  * </wc-code-highlighter>
66
146
  * ```
147
+ *
148
+ * @slot title - Header title content. Overrides `label` and shows the header.
149
+ * @slot icon - Icon shown before the title in the header.
150
+ * @slot actions - Extra action buttons, shown in the header or floating at the top end.
151
+ *
152
+ * @csspart container - The outer block.
153
+ * @csspart header - The header row.
154
+ * @csspart title - The header title.
155
+ * @csspart actions - The action buttons group.
156
+ * @csspart content - The scrollable code area (`pre`).
157
+ * @csspart line - Each code line.
158
+ * @csspart footer - The footer holding the show more button.
159
+ *
160
+ * @cssprop --code-highlighter-background - Block background. Defaults to `--color-surface-container-low`.
161
+ * @cssprop --code-highlighter-border-color - Block border color. Defaults to `--color-outline-variant`.
162
+ * @cssprop --code-highlighter-shape - Block corner radius. Defaults to `--shape-corner-medium`.
163
+ * @cssprop --code-highlighter-max-height - Caps the code area height; it scrolls beyond. Defaults to `none`.
164
+ * @cssprop --code-highlighter-collapsed-height - Height of a collapsed `collapsible` block. Defaults to `16rem`.
165
+ * @cssprop --code-highlighter-foreground - Plain code color. Defaults to `--color-on-surface`.
166
+ * @cssprop --code-highlighter-token-keyword - Keyword color. Defaults to `--color-purple`.
167
+ * @cssprop --code-highlighter-token-string - String color. Defaults to `--color-green`.
168
+ * @cssprop --code-highlighter-token-function - Function color. Defaults to `--color-blue`.
169
+ * @cssprop --code-highlighter-token-constant - Constant and number color. Defaults to `--color-orange`.
170
+ * @cssprop --code-highlighter-token-comment - Comment color. Defaults to `--color-on-surface-variant`.
171
+ * @cssprop --code-highlighter-token-punctuation - Punctuation color. Defaults to `--color-on-surface-variant`.
172
+ *
173
+ * @fires {CustomEvent<{value: string}>} copied - Dispatched after the copy button copies the code.
174
+ * @fires {CustomEvent<{expanded: boolean}>} expanded-change - Dispatched when a collapsible block is expanded or collapsed.
175
+ *
67
176
  * @tags display
68
177
  */
69
178
  @IndividualComponent
70
179
  export class CodeHighlighter extends LitElement {
180
+ // ── Static ────────────────────────────────────────────────────────────────
181
+
71
182
  static styles = [styles];
72
183
 
73
- private static readonly COPY_FEEDBACK_DURATION = 3000;
184
+ private static readonly COPY_FEEDBACK_DURATION = 2000;
185
+
186
+ // ── Properties ────────────────────────────────────────────────────────────
74
187
 
188
+ /** Language of the code. Unknown languages render as plain text. */
75
189
  @property({ type: String, reflect: true })
76
- language: BundledLanguage = 'javascript';
190
+ language: CodeHighlighterLanguage = 'javascript';
191
+
192
+ /** Code to display. When empty, the code is read from a light-DOM `<pre><code>`. */
193
+ @property({ type: String })
194
+ value: string = '';
195
+
196
+ /**
197
+ * Formats JavaScript, HTML and CSS with Prettier before display.
198
+ * Set `format="false"` to show the code as written.
199
+ */
200
+ @property({
201
+ converter: { fromAttribute: (value: string | null) => value !== 'false' },
202
+ })
203
+ format: boolean = true;
204
+
205
+ /** Header title, such as a file path. Shows the header. */
206
+ @property({ type: String })
207
+ label: string = '';
77
208
 
209
+ /** Shows line numbers. */
78
210
  @property({ attribute: 'line-numbers', type: Boolean, reflect: true })
79
211
  lineNumbers: boolean = false;
80
212
 
81
- @property({ type: String })
82
- value: string = '';
213
+ /** Number of the first line when line numbers are shown. */
214
+ @property({ attribute: 'start-line', type: Number })
215
+ startLine: number = 1;
216
+
217
+ /** Wraps long lines instead of scrolling horizontally. */
218
+ @property({ type: Boolean, reflect: true })
219
+ wrap: boolean = false;
220
+
221
+ /** Shows a button that turns line wrapping on and off. */
222
+ @property({ attribute: 'wrap-toggle', type: Boolean })
223
+ wrapToggle: boolean = false;
224
+
225
+ /** Lines to highlight, such as `"1, 3-5"`. Counts displayed lines, after formatting. */
226
+ @property({ attribute: 'highlight-lines', type: String })
227
+ highlightLines: string = '';
228
+
229
+ /** Lines shown as added in a diff, such as `"4-6"`. */
230
+ @property({ attribute: 'added-lines', type: String })
231
+ addedLines: string = '';
232
+
233
+ /** Lines shown as removed in a diff, such as `"3"`. */
234
+ @property({ attribute: 'removed-lines', type: String })
235
+ removedLines: string = '';
83
236
 
237
+ /** Caps the height and adds a show more button when the code is taller. */
84
238
  @property({ type: Boolean, reflect: true })
85
- format?: boolean = true;
239
+ collapsible: boolean = false;
86
240
 
87
- @property({ type: Boolean })
241
+ /** Whether a collapsible block is expanded. */
242
+ @property({ type: Boolean, reflect: true })
243
+ expanded: boolean = false;
244
+
245
+ /** Size of the block. `sm` suits tool output and dense layouts. */
246
+ @property({ type: String, reflect: true })
247
+ size: CodeHighlighterSize = 'md';
248
+
249
+ /** Visual variant. `error` tints the block for failure output. */
250
+ @property({ type: String, reflect: true })
251
+ variant: CodeHighlighterVariant = 'default';
252
+
253
+ /** Hides the copy button. */
254
+ @property({ attribute: 'hide-copy', type: Boolean })
88
255
  hideCopy: boolean = false;
89
256
 
90
- @state() private compiledCode: string | null = null;
257
+ /** Text the copy button copies instead of the displayed code. */
258
+ @property({ attribute: 'copy-value', type: String })
259
+ copyValue?: string;
260
+
261
+ /** Renders the code inline, as a compact chip within text. */
262
+ @property({ type: Boolean, reflect: true })
263
+ inline: boolean = false;
264
+
265
+ /**
266
+ * Set by `wc-code-group`. The group draws the frame and shows the label as a
267
+ * tab, so the block drops its border and header.
268
+ */
269
+ @property({ type: Boolean, reflect: true })
270
+ grouped: boolean = false;
271
+
272
+ /** The code as displayed, after formatting, without a trailing newline. */
273
+ @state() private _code: string = '';
274
+
275
+ /** Tokens per line, or `null` until highlighting finishes. */
276
+ @state() private _tokens: ThemedToken[][] | null = null;
91
277
 
278
+ /** Whether the copy button shows its copied feedback. */
92
279
  @state() private _copied = false;
93
280
 
94
- private parsedCode: string | null = null;
281
+ /** Whether the collapsed code is taller than the collapsed height. */
282
+ @state() private _overflowing = false;
283
+
284
+ // ── Queries ───────────────────────────────────────────────────────────────
285
+
286
+ @query('.content') private __content?: HTMLElement;
287
+
288
+ @query('.code') private __codeElement?: HTMLElement;
289
+
290
+ // ── Private fields ────────────────────────────────────────────────────────
291
+
292
+ /** Source read from `value` or the light DOM, before formatting. */
293
+ private __source = '';
294
+
295
+ /** Line variants keyed by 1-based line number. */
296
+ private __lineVariants = new Map<number, LineVariant>();
95
297
 
96
- private _copyFeedbackTimeout: number | null = null;
298
+ /** Increments per highlight run so stale async results are dropped. */
299
+ private __run = 0;
97
300
 
98
- async connectedCallback() {
99
- // eslint-disable-next-line wc/guard-super-call
301
+ /** Timer that resets the copy feedback. */
302
+ private __copyFeedbackTimeout: number | null = null;
303
+
304
+ /** Measures whether collapsed code overflows. */
305
+ private __resizeObserver?: ResizeObserver;
306
+
307
+ /** Element currently measured by the resize observer. */
308
+ private __observedContent?: HTMLElement;
309
+
310
+ /** Re-renders when slotted header content is added or removed. */
311
+ private __childObserver?: MutationObserver;
312
+
313
+ // ── Lifecycle ─────────────────────────────────────────────────────────────
314
+
315
+ connectedCallback() {
100
316
  super.connectedCallback();
317
+ this.__childObserver = new MutationObserver(() => this.requestUpdate());
318
+ this.__childObserver.observe(this, {
319
+ childList: true,
320
+ attributes: true,
321
+ attributeFilter: ['slot'],
322
+ subtree: true,
323
+ });
101
324
  }
102
325
 
103
326
  disconnectedCallback() {
104
- if (this._copyFeedbackTimeout !== null) {
105
- window.clearTimeout(this._copyFeedbackTimeout);
106
- this._copyFeedbackTimeout = null;
327
+ if (this.__copyFeedbackTimeout !== null) {
328
+ window.clearTimeout(this.__copyFeedbackTimeout);
329
+ this.__copyFeedbackTimeout = null;
107
330
  }
331
+ this.__childObserver?.disconnect();
332
+ this.__resizeObserver?.disconnect();
333
+ this.__observedContent = undefined;
108
334
  super.disconnectedCallback();
109
335
  }
110
336
 
111
- firstUpdated() {
112
- this.__highlightCode();
113
- }
337
+ protected willUpdate(changed: PropertyValues<this>) {
338
+ if (
339
+ !this.hasUpdated ||
340
+ changed.has('value') ||
341
+ changed.has('language') ||
342
+ changed.has('format') ||
343
+ changed.has('inline')
344
+ ) {
345
+ this.__source = this.__readSource();
346
+ this._code = splitLines(this.__source).join('\n');
347
+ this._tokens = null;
348
+ this.__highlight();
349
+ }
114
350
 
115
- // eslint-disable-next-line class-methods-use-this
116
- private decode(str: string) {
117
- return str.replace(/&lt;/g, '<').replace(/&gt;/g, '>');
351
+ if (
352
+ !this.hasUpdated ||
353
+ changed.has('highlightLines') ||
354
+ changed.has('addedLines') ||
355
+ changed.has('removedLines')
356
+ ) {
357
+ this.__lineVariants = buildLineVariants({
358
+ highlighted: this.highlightLines,
359
+ added: this.addedLines,
360
+ removed: this.removedLines,
361
+ });
362
+ }
118
363
  }
119
364
 
120
- private async __highlightCode() {
121
- let codeString = '';
122
- if (this.value) {
123
- codeString = this.value;
124
- } else {
125
- // Accessing light DOM children
126
- const codeTag = this.querySelector('code');
127
- if (codeTag) {
128
- codeString = codeTag.innerHTML;
129
- } else if (this.childNodes.length > 0) {
130
- codeString = (this as HTMLElement).innerText;
131
- }
365
+ protected updated() {
366
+ // The resize observer measures overflow after layout, including when
367
+ // collapsing or expanding changes the code area's height.
368
+ if (this.__content !== this.__observedContent) {
369
+ this.__observeContent();
132
370
  }
371
+ }
133
372
 
134
- codeString = this.decode(codeString);
135
-
136
- if (this.format !== false) {
137
- // eslint-disable-next-line default-case
138
- switch (this.language) {
139
- case 'javascript': {
140
- const [prettier, pluginBabel, pluginEstree] = await Promise.all([
141
- loadPrettier(),
142
- loadPluginBabel(),
143
- loadPluginEstree(),
144
- ]);
145
- codeString = await prettier.format(codeString, {
146
- parser: 'babel',
147
- plugins: [pluginBabel, pluginEstree],
148
- bracketSameLine: true,
149
- htmlWhitespaceSensitivity: 'ignore',
150
- });
151
- break;
152
- }
153
- case 'html': {
154
- const [prettier, pluginHtml] = await Promise.all([
155
- loadPrettier(),
156
- loadPluginHtml(),
157
- ]);
158
- codeString = await prettier.format(codeString, {
159
- parser: 'html',
160
- plugins: [pluginHtml],
161
- bracketSameLine: true,
162
- htmlWhitespaceSensitivity: 'ignore',
163
- });
164
- break;
165
- }
166
- case 'css': {
167
- const [prettier, pluginPostcss] = await Promise.all([
168
- loadPrettier(),
169
- loadPluginPostcss(),
170
- ]);
171
- codeString = await prettier.format(codeString, {
172
- parser: 'css',
173
- plugins: [pluginPostcss],
174
- });
175
- break;
176
- }
373
+ // ── Private methods ───────────────────────────────────────────────────────
374
+
375
+ /** Reads the source from `value`, or from the light DOM. */
376
+ private __readSource(): string {
377
+ if (this.value) return this.value;
378
+ const codeTag = this.querySelector('code');
379
+ if (codeTag) return dedent(decodeEntities(codeTag.innerHTML));
380
+ const text = Array.from(this.childNodes)
381
+ .filter(node => node.nodeType === Node.TEXT_NODE)
382
+ .map(node => node.textContent ?? '')
383
+ .join('');
384
+ return dedent(text);
385
+ }
386
+
387
+ /** Formats then tokenizes the source; plain lines stay until both finish. */
388
+ private async __highlight() {
389
+ this.__run += 1;
390
+ const run = this.__run;
391
+ const { language } = this;
392
+ let code = this.__source;
393
+
394
+ if (this.format && !this.inline) {
395
+ try {
396
+ code = await formatCode(code, language);
397
+ } catch {
398
+ // Invalid code cannot be formatted; show it as written.
177
399
  }
400
+ if (run !== this.__run) return;
401
+ this._code = splitLines(code).join('\n');
178
402
  }
179
403
 
180
- this.parsedCode = codeString;
181
-
182
- const transformers: ShikiTransformer[] = [];
183
-
184
- // If line numbers are enabled, we inject a transformer
185
- // that adds the 'line' class to every line node.
186
- if (this.lineNumbers) {
187
- transformers.push({
188
- name: 'add-line-class',
189
- line(node) {
190
- // Shiki v1 helper to add classes to the AST
191
- this.addClassToHast(node, 'line');
192
- },
193
- });
404
+ try {
405
+ const tokens = await tokenize(this._code, language);
406
+ if (run === this.__run) this._tokens = tokens;
407
+ } catch {
408
+ // Unknown language: keep the plain lines.
194
409
  }
195
-
196
- const [
197
- { codeToHtml },
198
- [{ default: pierreDark }, { default: pierreLight }],
199
- ] = await Promise.all([loadShiki(), loadThemes()]);
200
-
201
- this.compiledCode = await codeToHtml(codeString, {
202
- lang: this.language,
203
- themes: {
204
- // @ts-ignore
205
- light: pierreLight,
206
- // @ts-ignore
207
- dark: pierreDark,
208
- },
209
- transformers,
210
- });
211
410
  }
212
411
 
213
- protected updated(changed: Map<PropertyKey, unknown>) {
214
- // Only re-highlight when the source content or rendering options change,
215
- // not on unrelated state updates like the copy-button feedback toggle.
216
- if (
217
- changed.has('value') ||
218
- changed.has('language') ||
219
- changed.has('lineNumbers') ||
220
- changed.has('format')
221
- ) {
222
- this.__highlightCode();
223
- }
412
+ /** Watches the code area so the show more button appears only when needed. */
413
+ private __observeContent() {
414
+ this.__resizeObserver?.disconnect();
415
+ this.__observedContent = this.__content;
416
+ if (!this.__content || typeof ResizeObserver === 'undefined') return;
417
+ this.__resizeObserver ??= new ResizeObserver(() => this.__measure());
418
+ this.__resizeObserver.observe(this.__content);
419
+ if (this.__codeElement) this.__resizeObserver.observe(this.__codeElement);
224
420
  }
225
421
 
226
- private async __handleCopyClick() {
227
- if (this.parsedCode == null) {
422
+ /** Checks whether the collapsed code is taller than its cap. */
423
+ private __measure() {
424
+ const content = this.__content;
425
+ if (!content || !this.collapsible) {
426
+ this._overflowing = false;
228
427
  return;
229
428
  }
429
+ if (this.expanded) return;
430
+ this._overflowing = content.scrollHeight > content.clientHeight + 1;
431
+ }
230
432
 
231
- await copyToClipboard(this.parsedCode);
232
- this._copied = true;
433
+ /** Whether light-DOM children are assigned to the named slot. */
434
+ private __hasSlotted(name: string): boolean {
435
+ return Array.from(this.children).some(
436
+ child => child.getAttribute('slot') === name,
437
+ );
438
+ }
233
439
 
234
- if (this._copyFeedbackTimeout !== null) {
235
- window.clearTimeout(this._copyFeedbackTimeout);
440
+ private async __handleCopyClick() {
441
+ const value = this.copyValue ?? this._code;
442
+ await copyToClipboard(value);
443
+ this._copied = true;
444
+ this.dispatchEvent(
445
+ new CustomEvent('copied', {
446
+ detail: { value },
447
+ bubbles: true,
448
+ composed: true,
449
+ }),
450
+ );
451
+
452
+ if (this.__copyFeedbackTimeout !== null) {
453
+ window.clearTimeout(this.__copyFeedbackTimeout);
236
454
  }
237
-
238
- this._copyFeedbackTimeout = window.setTimeout(() => {
455
+ this.__copyFeedbackTimeout = window.setTimeout(() => {
239
456
  this._copied = false;
240
- this._copyFeedbackTimeout = null;
457
+ this.__copyFeedbackTimeout = null;
241
458
  }, CodeHighlighter.COPY_FEEDBACK_DURATION);
242
459
  }
243
460
 
244
- render() {
245
- if (this.compiledCode === null) {
246
- return html`
247
- <div class="code-loader">
248
- <wc-circular-progress indeterminate></wc-circular-progress>
249
- ${locale.loading}
250
- </div>
251
- `;
252
- }
461
+ private __handleWrapClick() {
462
+ this.wrap = !this.wrap;
463
+ }
464
+
465
+ private __handleExpandClick() {
466
+ this.expanded = !this.expanded;
467
+ if (!this.expanded && this.__content) this.__content.scrollTop = 0;
468
+ this.dispatchEvent(
469
+ new CustomEvent('expanded-change', {
470
+ detail: { expanded: this.expanded },
471
+ bubbles: true,
472
+ composed: true,
473
+ }),
474
+ );
475
+ }
253
476
 
477
+ // ── Render helpers ────────────────────────────────────────────────────────
478
+
479
+ // eslint-disable-next-line class-methods-use-this
480
+ private __renderToken(token: ThemedToken) {
481
+ const fontStyle = token.fontStyle ?? 0;
482
+ if (!token.color && fontStyle <= 0) return token.content;
483
+ return html`<span
484
+ class=${classMap({
485
+ italic: hasFontFlag(fontStyle, FONT_ITALIC),
486
+ bold: hasFontFlag(fontStyle, FONT_BOLD),
487
+ underline: hasFontFlag(fontStyle, FONT_UNDERLINE),
488
+ strikethrough: hasFontFlag(fontStyle, FONT_STRIKETHROUGH),
489
+ })}
490
+ style=${styleMap({ color: token.color })}
491
+ >${token.content}</span
492
+ >`;
493
+ }
494
+
495
+ private __renderLine(line: string, index: number) {
496
+ const tokens = this._tokens?.[index];
497
+ const variant = this.__lineVariants.get(index + 1);
498
+ let content: unknown = line;
499
+ if (line === '') content = '\n';
500
+ else if (tokens) content = tokens.map(token => this.__renderToken(token));
501
+ // No whitespace between tags: this renders inside <pre>.
502
+ return html`<span
503
+ class="line"
504
+ part="line"
505
+ data-variant=${variant ?? nothing}
506
+ ><span class="line-content">${content}</span></span
507
+ >`;
508
+ }
509
+
510
+ private __renderActions(floating: boolean) {
254
511
  return html`
255
- <div
256
- class=${classMap({
257
- 'code-highlighter': true,
258
- 'line-numbers': this.lineNumbers,
259
- })}
260
- >
261
- <div class="header">
262
- <div class="header-title">
263
- <slot name="title">${this.language?.toUpperCase()}</slot>
264
- </div>
265
- <div class="header-actions">
266
- <wc-icon-button
267
- color=${this._copied ? 'success' : 'surface'}
512
+ <div class=${classMap({ actions: true, floating })} part="actions">
513
+ <slot name="actions"></slot>
514
+ ${this.wrapToggle
515
+ ? html`<wc-icon-button
516
+ class="wrap-button"
268
517
  variant="text"
269
518
  size="xs"
519
+ shape="round"
520
+ color="surface"
521
+ toggle
522
+ ?selected=${this.wrap}
523
+ aria-label=${this.wrap ? locale.unwrapLines : locale.wrapLines}
524
+ tooltip=${this.wrap ? locale.unwrapLines : locale.wrapLines}
525
+ @click=${this.__handleWrapClick}
526
+ >
527
+ <wc-icon name="wrap_text"></wc-icon>
528
+ </wc-icon-button>`
529
+ : nothing}
530
+ ${this.hideCopy
531
+ ? nothing
532
+ : html`<wc-icon-button
533
+ class="copy-button"
534
+ variant="text"
535
+ size="xs"
536
+ shape="round"
537
+ color=${this._copied ? 'success' : 'surface'}
270
538
  aria-label=${this._copied
271
539
  ? locale.copied
272
540
  : locale.copyToClipboard}
@@ -276,13 +544,100 @@ export class CodeHighlighter extends LitElement {
276
544
  <wc-icon
277
545
  name=${this._copied ? 'check' : 'content_copy'}
278
546
  ></wc-icon>
279
- </wc-icon-button>
280
- </div>
281
- </div>
547
+ </wc-icon-button>`}
548
+ </div>
549
+ `;
550
+ }
282
551
 
283
- <div class="scroll-wrapper">
284
- <div class="highlighter">${unsafeHTML(this.compiledCode || '')}</div>
552
+ private __renderHeader() {
553
+ return html`
554
+ <div class="header" part="header">
555
+ <slot name="icon"></slot>
556
+ <div class="title" part="title">
557
+ <slot name="title">${this.label}</slot>
285
558
  </div>
559
+ ${this.__renderActions(false)}
560
+ </div>
561
+ `;
562
+ }
563
+
564
+ private __renderFooter() {
565
+ return html`
566
+ <div class="footer" part="footer">
567
+ <wc-button
568
+ class="expand-button"
569
+ variant="text"
570
+ size="xs"
571
+ trailing-icon
572
+ aria-expanded=${this.expanded ? 'true' : 'false'}
573
+ @click=${this.__handleExpandClick}
574
+ >
575
+ <wc-icon
576
+ slot="icon"
577
+ class=${classMap({ 'expand-icon': true, flipped: this.expanded })}
578
+ name="keyboard_arrow_down"
579
+ ></wc-icon>
580
+ ${this.expanded ? locale.showLess : locale.showMore}
581
+ </wc-button>
582
+ </div>
583
+ `;
584
+ }
585
+
586
+ private __renderInline() {
587
+ const lines = splitLines(this._code);
588
+ return html`<code class="inline" part="content"
589
+ >${lines.map((line, index) => {
590
+ const tokens = this._tokens?.[index];
591
+ const content = tokens
592
+ ? tokens.map(token => this.__renderToken(token))
593
+ : line;
594
+ return index === 0 ? content : [' ', content];
595
+ })}</code
596
+ >`;
597
+ }
598
+
599
+ // ── Render ────────────────────────────────────────────────────────────────
600
+
601
+ render() {
602
+ if (this.inline) return this.__renderInline();
603
+
604
+ const lines = splitLines(this._code);
605
+ const hasHeader =
606
+ !this.grouped && (!!this.label || this.__hasSlotted('title'));
607
+ const hasActions =
608
+ !this.hideCopy || this.wrapToggle || this.__hasSlotted('actions');
609
+ const showFooter = this.collapsible && (this._overflowing || this.expanded);
610
+ const collapsed = this.collapsible && !this.expanded;
611
+
612
+ return html`
613
+ <div
614
+ class=${classMap({
615
+ 'code-block': true,
616
+ 'has-header': hasHeader,
617
+ 'has-footer': showFooter,
618
+ 'line-numbers': this.lineNumbers,
619
+ wrap: this.wrap,
620
+ collapsed,
621
+ overflowing: collapsed && this._overflowing,
622
+ })}
623
+ part="container"
624
+ >
625
+ ${hasHeader ? this.__renderHeader() : nothing}
626
+ ${!hasHeader && hasActions ? this.__renderActions(true) : nothing}
627
+ <pre
628
+ class="content"
629
+ part="content"
630
+ dir="ltr"
631
+ tabindex="0"
632
+ ><code class="code" style=${styleMap({
633
+ counterReset: `line ${this.startLine - 1}`,
634
+ })}>${lines.map((line, index) =>
635
+ this.__renderLine(line, index),
636
+ )}</code></pre>
637
+ ${showFooter ? this.__renderFooter() : nothing}
638
+ <span class="sr-only" aria-live="polite"
639
+ >${this._copied ? locale.copiedCode : ''}</span
640
+ >
286
641
  </div>
287
642
  `;
288
643
  }