@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
@@ -6,7 +6,7 @@ import BaseInput from '../input/BaseInput.js';
6
6
  import { observeThemeChange } from '../__internal/utils/observe-theme-change.js';
7
7
  import { redispatchEvent } from '../__internal/utils/dispatch-event-utils.js';
8
8
  import { copyToClipboard } from '../__internal/utils/copy-to-clipboard.js';
9
- import { isDarkMode } from '@/__internal/utils/is-dark-mode.js';
9
+ import { buildEditorTheme, resolvePalette } from './editor-theme.js';
10
10
 
11
11
  import styles from './code-editor.scss';
12
12
 
@@ -19,6 +19,8 @@ export type CodeEditorLanguage =
19
19
  | 'scss'
20
20
  | 'markdown';
21
21
 
22
+ export type CodeEditorSize = 'sm' | 'md';
23
+
22
24
  /** A problem shown in the editor: a squiggle under the text and a mark in the scroll bar. Lines and columns count from 1. */
23
25
  export type CodeEditorMarker = {
24
26
  line: number;
@@ -34,7 +36,11 @@ type Monaco = typeof import('./monaco.js');
34
36
  const locale = {
35
37
  copied: 'Copied',
36
38
  copyToClipboard: 'Copy to clipboard',
37
- readOnly: 'Read Only',
39
+ copiedCode: 'Copied code to clipboard',
40
+ readOnly: 'Read only',
41
+ wrapLines: 'Wrap lines',
42
+ unwrapLines: 'Turn off line wrap',
43
+ editorLabel: 'Code editor',
38
44
  breakpoint: 'Breakpoint',
39
45
  currentLine: 'Paused here',
40
46
  };
@@ -49,34 +55,52 @@ const EXTENSIONS: Record<CodeEditorLanguage, string> = {
49
55
  markdown: 'md',
50
56
  };
51
57
 
58
+ /** Monaco has one theme per page; every editor defines it from the tokens around it. */
59
+ const THEME_NAME = 'peacock';
60
+
61
+ /** How long the copy button shows its check. */
62
+ const COPY_FEEDBACK_DURATION = 2000;
63
+
52
64
  /** Where the language workers are: `monaco/` beside the built component. */
53
65
  const WORKERS = new URL('./monaco/', import.meta.url);
54
66
 
55
67
  let loading: Promise<Monaco> | undefined;
56
68
  let instances = 0;
57
69
 
70
+ /** The worker file for a Monaco language service label. */
71
+ function workerFile(label: string): string {
72
+ if (label === 'typescript' || label === 'javascript') return 'ts.worker.js';
73
+ if (label === 'json') return 'json.worker.js';
74
+ return 'editor.worker.js';
75
+ }
76
+
77
+ /** The next editor's model number. */
78
+ function nextInstanceId(): number {
79
+ instances += 1;
80
+ return instances;
81
+ }
82
+
58
83
  /**
59
84
  * Loads Monaco once per page: its workers come from this origin, and the icon font is declared in
60
85
  * the document, since a shadow root ignores `@font-face`.
61
86
  */
62
87
  function loadMonaco(): Promise<Monaco> {
63
88
  loading ??= (async () => {
64
- Reflect.set(globalThis, 'MonacoEnvironment', {
89
+ Reflect.set(window, 'MonacoEnvironment', {
65
90
  getWorker(_id: string, label: string) {
66
- const file =
67
- label === 'typescript' || label === 'javascript'
68
- ? 'ts.worker.js'
69
- : label === 'json'
70
- ? 'json.worker.js'
71
- : 'editor.worker.js';
72
- return new Worker(new URL(file, WORKERS), { type: 'module' });
91
+ return new Worker(new URL(workerFile(label), WORKERS), {
92
+ type: 'module',
93
+ });
73
94
  },
74
95
  });
75
- const font = (styles as CSSResult).cssText.match(/@font-face\s*\{[^}]*font-family:\s*codicon[^}]*\}/);
96
+ const font = (styles as CSSResult).cssText.match(
97
+ /@font-face\s*\{[^}]*font-family:\s*codicon[^}]*\}/,
98
+ );
76
99
  if (font && !document.getElementById('wc-code-editor-codicon')) {
100
+ const [declaration] = font;
77
101
  const style = document.createElement('style');
78
102
  style.id = 'wc-code-editor-codicon';
79
- style.textContent = font[0];
103
+ style.textContent = declaration;
80
104
  document.head.append(style);
81
105
  }
82
106
  return import('./monaco.js');
@@ -91,16 +115,30 @@ function loadMonaco(): Promise<Monaco> {
91
115
  *
92
116
  * @summary A Monaco-based code editing component with syntax highlighting, completions and debugging marks.
93
117
  * @overview
94
- * - CodeEditor wraps Monaco Editor as a web component. Monaco is bundled with Peacock and loaded when the first editor appears; nothing comes from a CDN, so it works under a content security policy that allows only its own origin.
95
- * - Supports TypeScript, JavaScript, JSON, HTML, CSS, SCSS and Markdown, with completions and errors for TypeScript, JavaScript and JSON; read-only mode, line numbers, minimap, and dark/light theme.
118
+ * - CodeEditor wraps Monaco Editor as a web component, in the same frame as `wc-code-highlighter`: an optional header with a title and actions, or a copy button that floats at the top end. Monaco is bundled with Peacock and loaded when the first editor appears; nothing comes from a CDN, so it works under a content security policy that allows only its own origin. The code shows as plain text until Monaco is ready.
119
+ * - Its colors come from the theme's color roles and the code highlighter's syntax colors, so light, dark, the system color scheme and custom themes all follow the tokens.
120
+ * - Supports TypeScript, JavaScript, JSON, HTML, CSS, SCSS and Markdown, with completions and errors for TypeScript, JavaScript and JSON; read-only mode, line numbers, line wrapping and a minimap.
96
121
  * - `lib-source` adds TypeScript declarations for completions, such as the modules a script may import.
97
122
  * - With `breakpoint-gutter`, a click in the gutter fires `breakpoint-toggle`; `breakpoints` and `current-line` draw the marks a debugger shows.
98
123
  * - `markers` underline problems, such as where a run failed.
99
- * - With `fill`, the editor takes the height of its container.
100
- * - Has a copy button; hide it with `hide-copy`.
124
+ * - With `fill`, the editor drops its frame and takes the height of its container, as a pane of its own.
101
125
  * - Emits `change` when content is edited and updates value from property changes.
102
126
  *
103
- * @cssprop --code-editor-height - Height of the editor. Defaults to 300px.
127
+ * @slot title - Header title content. Overrides `label` and shows the header.
128
+ * @slot icon - Icon shown before the title in the header.
129
+ * @slot actions - Extra action buttons, shown in the header or floating at the top end.
130
+ *
131
+ * @csspart container - The outer frame.
132
+ * @csspart header - The header row.
133
+ * @csspart title - The header title.
134
+ * @csspart actions - The action buttons group.
135
+ * @csspart editor - The area Monaco renders into.
136
+ *
137
+ * @cssprop --code-editor-height - Height of the editing area. Defaults to 300px. Ignored with `fill`.
138
+ * @cssprop --code-editor-background - Frame background. Defaults to `--color-surface-container-low`.
139
+ * @cssprop --code-editor-border-color - Frame border color. Defaults to `--color-outline-variant`.
140
+ * @cssprop --code-editor-shape - Frame corner radius. Defaults to `--shape-corner-medium`.
141
+ * @cssprop --code-highlighter-token-keyword - Keyword color, shared with `wc-code-highlighter`, like the other `--code-highlighter-token-*` colors.
104
142
  *
105
143
  * @fires {Event} change - Dispatched when the user edits the content.
106
144
  * @fires {CustomEvent<{value: string}>} copied - Dispatched after the copy button copies the content.
@@ -110,6 +148,7 @@ function loadMonaco(): Promise<Monaco> {
110
148
  * ```html
111
149
  * <wc-code-editor
112
150
  * language="css"
151
+ * label="theme.css"
113
152
  * readonly
114
153
  * style="width: 100%; --code-editor-height: 10rem;"
115
154
  * value=":root { --color-primary: #6341d5; }">
@@ -135,6 +174,10 @@ export default class CodeEditor extends BaseInput {
135
174
  @property({ type: String })
136
175
  language: CodeEditorLanguage = 'javascript';
137
176
 
177
+ /** Header title, such as a file name. Shows the header. */
178
+ @property({ type: String })
179
+ label = '';
180
+
138
181
  /** TypeScript declarations (a `.d.ts`) for completions in TypeScript and JavaScript, such as the modules the code may import. */
139
182
  @property({ type: String, attribute: 'lib-source' })
140
183
  libSource: string | undefined;
@@ -144,18 +187,30 @@ export default class CodeEditor extends BaseInput {
144
187
  compilerOptions: Record<string, unknown> | undefined;
145
188
 
146
189
  /** Whether line numbers show in the gutter. */
147
- @property({ type: String })
190
+ @property({ type: String, attribute: 'line-numbers' })
148
191
  lineNumbers: 'off' | 'on' = 'on';
149
192
 
193
+ /** Wraps long lines instead of scrolling horizontally. */
194
+ @property({ type: Boolean, reflect: true })
195
+ wrap = false;
196
+
197
+ /** Shows a button that turns line wrapping on and off. */
198
+ @property({ type: Boolean, attribute: 'wrap-toggle' })
199
+ wrapToggle = false;
200
+
150
201
  /** Shows the minimap. Leave the attribute out to hide it. */
151
202
  @property({ type: Boolean })
152
203
  minimap = false;
153
204
 
205
+ /** Size of the editor. `sm` uses smaller text and padding. */
206
+ @property({ type: String, reflect: true })
207
+ size: CodeEditorSize = 'md';
208
+
154
209
  /** Hides the copy button. */
155
210
  @property({ type: Boolean, attribute: 'hide-copy' })
156
211
  hideCopy = false;
157
212
 
158
- /** Shows a "Read Only" badge while the editor is read-only or disabled. */
213
+ /** Shows a "Read only" badge while the editor is read-only or disabled. */
159
214
  @property({ type: Boolean, attribute: 'show-readonly-badge' })
160
215
  showReadonlyBadge = false;
161
216
 
@@ -175,17 +230,14 @@ export default class CodeEditor extends BaseInput {
175
230
  @property({ type: Array, attribute: false })
176
231
  markers: CodeEditorMarker[] = [];
177
232
 
178
- /** Takes the height of the container instead of `--code-editor-height`. */
233
+ /** Drops the frame and takes the height of the container instead of `--code-editor-height`. */
179
234
  @property({ type: Boolean, reflect: true })
180
235
  fill = false;
181
236
 
182
- /** Whether the page is in dark mode; picks the Monaco theme. */
183
- @state() private _isDarkMode: boolean = isDarkMode();
184
-
185
237
  /** Whether the editor text has focus. */
186
238
  @state() private hasFocus = false;
187
239
 
188
- /** Whether the copy button was just used; shows a check for a few seconds. */
240
+ /** Whether the copy button was just used; shows a check for a moment. */
189
241
  @state() private _copied = false;
190
242
 
191
243
  /** The Monaco editor instance, once loaded. */
@@ -193,7 +245,9 @@ export default class CodeEditor extends BaseInput {
193
245
 
194
246
  // ── Queries
195
247
 
196
- @query('.editor') private editorElement!: HTMLElement;
248
+ @query('.editor') private editorElement?: HTMLElement;
249
+
250
+ @query('.probe') private probeElement?: HTMLElement;
197
251
 
198
252
  // ── Private fields
199
253
 
@@ -201,11 +255,17 @@ export default class CodeEditor extends BaseInput {
201
255
  monaco: Monaco | undefined;
202
256
 
203
257
  /** This editor's model's address, unique on the page so two editors never share a model. */
204
- private readonly __id = ++instances;
258
+ private readonly __id = nextInstanceId();
205
259
 
206
260
  /** Stops listening for theme changes. */
207
261
  private __unobserveTheme?: () => void;
208
262
 
263
+ /** The system color scheme, watched so the editor follows it. */
264
+ private __colorScheme?: MediaQueryList;
265
+
266
+ /** Re-renders when slotted header content is added or removed. */
267
+ private __childObserver?: MutationObserver;
268
+
209
269
  /** Resets the copied state of the copy button. */
210
270
  private __copiedTimer?: ReturnType<typeof setTimeout>;
211
271
 
@@ -215,19 +275,30 @@ export default class CodeEditor extends BaseInput {
215
275
  /** The breakpoint and current-line marks. */
216
276
  private __decorations?: { set(decorations: unknown[]): void; clear(): void };
217
277
 
278
+ /** The font and padding last given to Monaco, to skip unchanged updates. */
279
+ private __layoutKey = '';
280
+
218
281
  // ── Lifecycle
219
282
 
220
283
  connectedCallback() {
221
284
  super.connectedCallback();
222
- this.__unobserveTheme = observeThemeChange(() => {
223
- this._isDarkMode = isDarkMode();
224
- this.monaco?.editor.setTheme(this.getTheme());
285
+ this.__unobserveTheme = observeThemeChange(this.__applyTheme);
286
+ this.__colorScheme = window.matchMedia?.('(prefers-color-scheme: dark)');
287
+ this.__colorScheme?.addEventListener('change', this.__applyTheme);
288
+ this.__childObserver = new MutationObserver(() => this.requestUpdate());
289
+ this.__childObserver.observe(this, {
290
+ childList: true,
291
+ attributes: true,
292
+ attributeFilter: ['slot'],
293
+ subtree: true,
225
294
  });
226
295
  }
227
296
 
228
297
  disconnectedCallback() {
229
298
  super.disconnectedCallback();
230
299
  this.__unobserveTheme?.();
300
+ this.__colorScheme?.removeEventListener('change', this.__applyTheme);
301
+ this.__childObserver?.disconnect();
231
302
  clearTimeout(this.__copiedTimer);
232
303
  this.__lib?.forEach(lib => lib.dispose());
233
304
  this.__lib = undefined;
@@ -242,27 +313,41 @@ export default class CodeEditor extends BaseInput {
242
313
  }
243
314
 
244
315
  protected updated(changedProperties: PropertyValues<this>) {
245
- if (changedProperties.has('libSource') || changedProperties.has('compilerOptions')) this.libSourceChanged();
316
+ if (
317
+ changedProperties.has('libSource') ||
318
+ changedProperties.has('compilerOptions')
319
+ )
320
+ this.libSourceChanged();
246
321
 
247
322
  const editor = this.editorMonacoInstance;
248
323
  if (!editor || !this.monaco) return;
249
324
 
250
- if (changedProperties.has('disabled') || changedProperties.has('readonly')) {
325
+ if (
326
+ changedProperties.has('disabled') ||
327
+ changedProperties.has('readonly')
328
+ ) {
251
329
  editor.updateOptions({ readOnly: this.disabled || this.readonly });
252
330
  }
253
331
 
254
332
  if (
255
333
  changedProperties.has('lineNumbers') ||
256
334
  changedProperties.has('minimap') ||
257
- changedProperties.has('breakpointGutter')
335
+ changedProperties.has('breakpointGutter') ||
336
+ changedProperties.has('wrap') ||
337
+ changedProperties.has('label')
258
338
  ) {
259
339
  editor.updateOptions({
260
340
  lineNumbers: this.lineNumbers,
261
341
  minimap: { enabled: this.minimap },
262
342
  glyphMargin: this.breakpointGutter,
343
+ wordWrap: this.wrap ? 'on' : 'off',
344
+ ariaLabel: this.label || locale.editorLabel,
263
345
  });
264
346
  }
265
347
 
348
+ // The header and size set the font and padding; read them back from the styles.
349
+ this.__applyLayout();
350
+
266
351
  if (changedProperties.has('language')) {
267
352
  this.monaco.editor.setModelLanguage(editor.getModel(), this.language);
268
353
  }
@@ -271,7 +356,10 @@ export default class CodeEditor extends BaseInput {
271
356
  editor.setValue(this.value || '');
272
357
  }
273
358
 
274
- if (changedProperties.has('breakpoints') || changedProperties.has('currentLine')) {
359
+ if (
360
+ changedProperties.has('breakpoints') ||
361
+ changedProperties.has('currentLine')
362
+ ) {
275
363
  this.drawDecorations();
276
364
  }
277
365
  if (changedProperties.has('currentLine') && this.currentLine) {
@@ -288,24 +376,49 @@ export default class CodeEditor extends BaseInput {
288
376
  // Disconnected while Monaco loaded: nothing to put it in.
289
377
  if (!this.isConnected || !this.editorElement) return;
290
378
  this.monaco = monaco;
379
+ this.__applyTheme();
291
380
 
292
381
  const model = monaco.editor.createModel(
293
382
  this.value,
294
383
  this.language,
295
- monaco.Uri.parse(`file:///wc-code-editor/${this.__id}/index.${EXTENSIONS[this.language] ?? 'txt'}`),
384
+ monaco.Uri.parse(
385
+ `file:///wc-code-editor/${this.__id}/index.${EXTENSIONS[this.language] ?? 'txt'}`,
386
+ ),
296
387
  );
388
+ const layout = this.__readLayout();
389
+ this.__layoutKey = JSON.stringify(layout);
297
390
  this.editorMonacoInstance = monaco.editor.create(this.editorElement, {
298
391
  model,
392
+ ...layout,
299
393
  lineNumbers: this.lineNumbers,
300
394
  minimap: { enabled: this.minimap },
301
395
  glyphMargin: this.breakpointGutter,
302
- theme: this.getTheme(),
396
+ wordWrap: this.wrap ? 'on' : 'off',
397
+ theme: THEME_NAME,
303
398
  readOnly: this.disabled || this.readonly,
399
+ ariaLabel: this.label || locale.editorLabel,
304
400
  automaticLayout: true,
305
401
  fixedOverflowWidgets: true,
306
402
  scrollBeyondLastLine: false,
403
+ lineNumbersMinChars: 3,
404
+ lineDecorationsWidth: 8,
405
+ renderLineHighlight: 'line',
406
+ renderLineHighlightOnlyWhenFocus: true,
407
+ overviewRulerBorder: false,
408
+ hideCursorInOverviewRuler: true,
409
+ stickyScroll: { enabled: false },
410
+ scrollbar: {
411
+ useShadows: false,
412
+ verticalScrollbarSize: 10,
413
+ horizontalScrollbarSize: 10,
414
+ },
307
415
  });
308
- this.__decorations = this.editorMonacoInstance.createDecorationsCollection([]);
416
+ this.__decorations = this.editorMonacoInstance.createDecorationsCollection(
417
+ [],
418
+ );
419
+
420
+ // Monaco measures the font when it starts; measure again once web fonts have loaded.
421
+ document.fonts?.ready.then(() => this.monaco?.editor.remeasureFonts());
309
422
 
310
423
  this.libSourceChanged();
311
424
  this.drawDecorations();
@@ -326,7 +439,11 @@ export default class CodeEditor extends BaseInput {
326
439
  if (!this.breakpointGutter) return;
327
440
  const type = e.target?.type;
328
441
  const { MouseTargetType } = monaco.editor;
329
- if (type !== MouseTargetType.GUTTER_GLYPH_MARGIN && type !== MouseTargetType.GUTTER_LINE_NUMBERS) return;
442
+ if (
443
+ type !== MouseTargetType.GUTTER_GLYPH_MARGIN &&
444
+ type !== MouseTargetType.GUTTER_LINE_NUMBERS
445
+ )
446
+ return;
330
447
  const line = e.target.position?.lineNumber;
331
448
  if (!line) return;
332
449
  this.dispatchEvent(
@@ -369,10 +486,57 @@ export default class CodeEditor extends BaseInput {
369
486
 
370
487
  // ── Private methods
371
488
 
489
+ /** Defines the page's editor theme from the tokens around this editor. */
490
+ private __applyTheme = () => {
491
+ const { monaco, probeElement } = this;
492
+ if (!monaco || !probeElement) return;
493
+ monaco.editor.defineTheme(
494
+ THEME_NAME,
495
+ buildEditorTheme(resolvePalette(probeElement)),
496
+ );
497
+ monaco.editor.setTheme(THEME_NAME);
498
+ };
499
+
500
+ /** The font and padding the styles give the code, for Monaco's options. */
501
+ private __readLayout() {
502
+ const probe = this.probeElement;
503
+ if (!probe) return {};
504
+ const style = getComputedStyle(probe);
505
+ const fontSize = parseFloat(style.fontSize) || 14;
506
+ return {
507
+ fontFamily: style.fontFamily,
508
+ fontSize,
509
+ lineHeight: parseFloat(style.lineHeight) || Math.round(fontSize * 1.43),
510
+ padding: {
511
+ top: parseFloat(style.paddingTop) || 0,
512
+ bottom: parseFloat(style.paddingBottom) || 0,
513
+ },
514
+ };
515
+ }
516
+
517
+ /** Gives Monaco the font and padding when the header or size changed them. */
518
+ private __applyLayout() {
519
+ const layout = this.__readLayout();
520
+ const key = JSON.stringify(layout);
521
+ if (key === this.__layoutKey) return;
522
+ this.__layoutKey = key;
523
+ this.editorMonacoInstance?.updateOptions(layout);
524
+ }
525
+
526
+ /** Whether light-DOM children are assigned to the named slot. */
527
+ private __hasSlotted(name: string): boolean {
528
+ return Array.from(this.children).some(
529
+ child => child.getAttribute('slot') === name,
530
+ );
531
+ }
532
+
372
533
  private libSourceChanged() {
373
534
  const typescript = this.monaco?.typescript;
374
535
  if (!typescript) return;
375
- const defaults = [typescript.typescriptDefaults, typescript.javascriptDefaults];
536
+ const defaults = [
537
+ typescript.typescriptDefaults,
538
+ typescript.javascriptDefaults,
539
+ ];
376
540
  for (const found of defaults) {
377
541
  found.setCompilerOptions({
378
542
  target: typescript.ScriptTarget.ESNext,
@@ -386,12 +550,17 @@ export default class CodeEditor extends BaseInput {
386
550
  }
387
551
  this.__lib?.forEach(lib => lib.dispose());
388
552
  this.__lib = this.libSource
389
- ? defaults.map(found => found.addExtraLib(this.libSource!, `file:///wc-code-editor/${this.__id}/lib.d.ts`))
553
+ ? defaults.map(found =>
554
+ found.addExtraLib(
555
+ this.libSource!,
556
+ `file:///wc-code-editor/${this.__id}/lib.d.ts`,
557
+ ),
558
+ )
390
559
  : undefined;
391
560
  }
392
561
 
393
562
  private drawDecorations() {
394
- const monaco = this.monaco;
563
+ const { monaco } = this;
395
564
  if (!monaco || !this.__decorations) return;
396
565
  const range = (line: number) => new monaco.Range(line, 1, line, 1);
397
566
  const decorations: unknown[] = this.breakpoints.map(line => ({
@@ -417,7 +586,7 @@ export default class CodeEditor extends BaseInput {
417
586
  }
418
587
 
419
588
  private drawMarkers() {
420
- const monaco = this.monaco;
589
+ const { monaco } = this;
421
590
  const model = this.editorMonacoInstance?.getModel();
422
591
  if (!monaco || !model) return;
423
592
  const severity = {
@@ -434,7 +603,9 @@ export default class CodeEditor extends BaseInput {
434
603
  startLineNumber: marker.line,
435
604
  startColumn: marker.column ?? 1,
436
605
  endLineNumber: endLine,
437
- endColumn: marker.endColumn ?? model.getLineMaxColumn(Math.min(endLine, model.getLineCount())),
606
+ endColumn:
607
+ marker.endColumn ??
608
+ model.getLineMaxColumn(Math.min(endLine, model.getLineCount())),
438
609
  message: marker.message,
439
610
  severity: severity[marker.severity ?? 'error'],
440
611
  };
@@ -442,10 +613,6 @@ export default class CodeEditor extends BaseInput {
442
613
  );
443
614
  }
444
615
 
445
- private getTheme() {
446
- return this._isDarkMode ? 'vs-dark' : 'vs';
447
- }
448
-
449
616
  private async __handleCopyClick() {
450
617
  const value = this.editorMonacoInstance?.getValue() ?? this.value ?? '';
451
618
  await copyToClipboard(value);
@@ -453,7 +620,7 @@ export default class CodeEditor extends BaseInput {
453
620
  clearTimeout(this.__copiedTimer);
454
621
  this.__copiedTimer = setTimeout(() => {
455
622
  this._copied = false;
456
- }, 3000);
623
+ }, COPY_FEEDBACK_DURATION);
457
624
  this.dispatchEvent(
458
625
  new CustomEvent('copied', {
459
626
  detail: { value },
@@ -463,73 +630,126 @@ export default class CodeEditor extends BaseInput {
463
630
  );
464
631
  }
465
632
 
633
+ private __handleWrapClick() {
634
+ this.wrap = !this.wrap;
635
+ }
636
+
466
637
  // ── Render helpers
467
638
 
468
- private renderToolbar() {
469
- const showBadge = this.showReadonlyBadge && (this.disabled || this.readonly);
470
- if (this.hideCopy && !showBadge) return nothing;
639
+ private renderBadge() {
640
+ return html`<span class="read-only-badge">
641
+ <wc-icon name="lock"></wc-icon>${locale.readOnly}
642
+ </span>`;
643
+ }
471
644
 
645
+ private renderActions(floating: boolean, showBadge: boolean) {
472
646
  return html`
473
- <div class="toolbar">
474
- ${showBadge
475
- ? html`<wc-tag class="read-only-tag" color="red">${locale.readOnly}</wc-tag>`
647
+ <div
648
+ class=${classMap({
649
+ actions: true,
650
+ floating,
651
+ pinned: floating && showBadge,
652
+ })}
653
+ part="actions"
654
+ >
655
+ ${showBadge ? this.renderBadge() : nothing}
656
+ <slot name="actions"></slot>
657
+ ${this.wrapToggle
658
+ ? html`<wc-icon-button
659
+ class="wrap-button"
660
+ variant="text"
661
+ size="xs"
662
+ shape="round"
663
+ color="surface"
664
+ toggle
665
+ ?selected=${this.wrap}
666
+ aria-label=${this.wrap ? locale.unwrapLines : locale.wrapLines}
667
+ tooltip=${this.wrap ? locale.unwrapLines : locale.wrapLines}
668
+ @click=${this.__handleWrapClick}
669
+ >
670
+ <wc-icon name="wrap_text"></wc-icon>
671
+ </wc-icon-button>`
476
672
  : nothing}
477
673
  ${this.hideCopy
478
674
  ? nothing
479
675
  : html`<wc-icon-button
480
676
  class="copy-button"
481
- color=${this._copied ? 'success' : 'surface'}
482
677
  variant="text"
483
678
  size="xs"
484
- aria-label=${this._copied ? locale.copied : locale.copyToClipboard}
679
+ shape="round"
680
+ color=${this._copied ? 'success' : 'surface'}
681
+ aria-label=${this._copied
682
+ ? locale.copied
683
+ : locale.copyToClipboard}
485
684
  tooltip=${this._copied ? locale.copied : locale.copyToClipboard}
486
685
  @click=${this.__handleCopyClick}
487
686
  >
488
- <wc-icon name=${this._copied ? 'check' : 'content_copy'}></wc-icon>
687
+ <wc-icon
688
+ name=${this._copied ? 'check' : 'content_copy'}
689
+ ></wc-icon>
489
690
  </wc-icon-button>`}
490
691
  </div>
491
692
  `;
492
693
  }
493
694
 
695
+ private renderHeader(showBadge: boolean) {
696
+ return html`
697
+ <div class="header" part="header">
698
+ <slot name="icon"></slot>
699
+ <div class="title" part="title">
700
+ <slot name="title">${this.label}</slot>
701
+ </div>
702
+ ${this.renderActions(false, showBadge)}
703
+ </div>
704
+ `;
705
+ }
706
+
494
707
  // ── Render
495
708
 
496
709
  render() {
497
- if (this.fill) {
498
- // A pane of its own, such as an IDE's: no field outline, as tall as its container.
499
- return html`
500
- <div class="code-editor-component fill">
501
- ${this.renderToolbar()}
502
- <div class="editor"></div>
503
- ${!this.editorMonacoInstance
504
- ? html`<div class="code-editor-loader"><wc-spinner></wc-spinner> Loading...</div>`
505
- : nothing}
506
- </div>
507
- `;
508
- }
509
- // The field isn't marked read-only: its read-only look dims the
510
- // container, and a read-only editor is still meant to be read.
710
+ const hasHeader = !!this.label || this.__hasSlotted('title');
711
+ const showBadge =
712
+ this.showReadonlyBadge && (this.disabled || this.readonly);
713
+ const hasActions =
714
+ !this.hideCopy ||
715
+ this.wrapToggle ||
716
+ showBadge ||
717
+ this.__hasSlotted('actions');
718
+ const loaded = !!this.editorMonacoInstance;
719
+
720
+ // A read-only editor keeps full contrast: it is still meant to be read.
511
721
  return html`
512
- <wc-field
513
- ?required=${this.required}
514
- ?disabled=${this.disabled}
515
- ?skeleton=${this.skeleton}
516
- ?focused=${this.hasFocus}
517
- .host=${this}
518
- class="${classMap({
519
- 'code-editor-component': true,
722
+ <div
723
+ class=${classMap({
724
+ 'code-block': true,
725
+ 'has-header': hasHeader,
726
+ focused: this.hasFocus,
520
727
  disabled: this.disabled,
521
- })}"
728
+ numbered: this.lineNumbers !== 'off',
729
+ 'breakpoint-gutter': this.breakpointGutter,
730
+ })}
731
+ part="container"
522
732
  >
523
- ${this.renderToolbar()}
524
- <div class="editor"></div>
525
- ${!this.editorMonacoInstance
526
- ? html`
527
- <div class="code-editor-loader">
528
- <wc-spinner></wc-spinner> Loading...
529
- </div>
530
- `
733
+ ${hasHeader ? this.renderHeader(showBadge) : nothing}
734
+ ${!hasHeader && hasActions
735
+ ? this.renderActions(true, showBadge)
531
736
  : nothing}
532
- </wc-field>
737
+ <div class="editor-area">
738
+ <div class="editor" part="editor"></div>
739
+ ${loaded
740
+ ? nothing
741
+ : html`<pre class="placeholder" aria-hidden="true">
742
+ ${this.value}</pre
743
+ >`}
744
+ ${this.skeleton
745
+ ? html`<wc-skeleton class="skeleton" visible></wc-skeleton>`
746
+ : nothing}
747
+ </div>
748
+ <span class="probe" aria-hidden="true"></span>
749
+ <span class="sr-only" aria-live="polite"
750
+ >${this._copied ? locale.copiedCode : ''}</span
751
+ >
752
+ </div>
533
753
  `;
534
754
  }
535
755
  }