@aleph-alpha/ui-library 5.8.0 → 5.10.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 (111) hide show
  1. package/README.md +8 -7
  2. package/config.js +157 -4
  3. package/dist/system/__tests__/test-utils.d.ts +24 -0
  4. package/dist/system/components/UiAutocomplete/UiAutocomplete.vue.d.ts +8 -4
  5. package/dist/system/components/UiAutocomplete/types.d.ts +11 -0
  6. package/dist/system/components/UiFadeMask/UiFadeMask.vue.d.ts +21 -0
  7. package/dist/system/components/UiFadeMask/index.d.ts +2 -0
  8. package/dist/system/components/UiFadeMask/types.d.ts +33 -0
  9. package/dist/system/components/UiFileItem/UiFileItem.vue.d.ts +3 -1
  10. package/dist/system/components/UiFileType/types.d.ts +2 -1
  11. package/dist/system/components/UiListbox/UiListboxVirtualizer.vue.d.ts +21 -0
  12. package/dist/system/components/UiListbox/index.d.ts +1 -0
  13. package/dist/system/components/UiListbox/types.d.ts +36 -0
  14. package/dist/system/components/UiSelect/UiSelectVirtualizer.vue.d.ts +21 -0
  15. package/dist/system/components/UiSelect/index.d.ts +1 -0
  16. package/dist/system/components/UiSelect/types.d.ts +36 -0
  17. package/dist/system/components/UiSwitch/UiSwitch.vue.d.ts +1 -0
  18. package/dist/system/components/UiSwitch/types.d.ts +12 -0
  19. package/dist/system/components/core/native-select/NativeSelectOptGroup.vue.d.ts +2 -2
  20. package/dist/system/components/core/native-select/NativeSelectOption.vue.d.ts +2 -2
  21. package/dist/system/components/core/switch/Switch.vue.d.ts +2 -0
  22. package/dist/system/components/core/switch/index.d.ts +8 -0
  23. package/dist/system/components/index.d.ts +1 -0
  24. package/dist/system/index.d.ts +1 -0
  25. package/dist/system/lib/scrollbar.d.ts +37 -0
  26. package/dist/system/lib/useAnchorFloat.d.ts +0 -2
  27. package/dist/system/lib/useIsTruncated.d.ts +15 -0
  28. package/dist/system/lib.js +22660 -21292
  29. package/dist/system/mobile-device-frame.png +0 -0
  30. package/dist/system/patterns/UiFloatActions/types.d.ts +2 -2
  31. package/dist/system/patterns/UiProfileCard/index.d.ts +7 -0
  32. package/dist/system/patterns/UiTopBar/UiTopBar.vue.d.ts +23 -0
  33. package/dist/system/patterns/UiTopBar/index.d.ts +2 -0
  34. package/dist/system/patterns/UiTopBar/types.d.ts +28 -0
  35. package/dist/system/patterns/index.d.ts +2 -0
  36. package/dist/system/story-sidebar-icons.json +7 -1
  37. package/docs/public-docs/foundations.md +17 -15
  38. package/package.json +4 -3
  39. package/src/__tests__/test-utils.ts +74 -0
  40. package/src/components/UiAutocomplete/UiAutocomplete.stories.ts +94 -0
  41. package/src/components/UiAutocomplete/UiAutocomplete.vue +164 -44
  42. package/src/components/UiAutocomplete/__tests__/UiAutocompleteVirtualized.test.ts +107 -0
  43. package/src/components/UiAutocomplete/types.ts +11 -0
  44. package/src/components/UiCodeBlock/UiCodeBlock.stories.ts +54 -0
  45. package/src/components/UiCodeBlock/UiCodeBlock.vue +84 -32
  46. package/src/components/UiCodeBlock/__tests__/UiCodeBlock.test.ts +65 -21
  47. package/src/components/UiDropdownMenu/UiDropdownMenu.stories.ts +760 -0
  48. package/src/components/UiFadeMask/UiFadeMask.stories.ts +563 -0
  49. package/src/components/UiFadeMask/UiFadeMask.vue +86 -0
  50. package/src/components/UiFadeMask/__tests__/UiFadeMask.test.ts +52 -0
  51. package/src/components/UiFadeMask/index.ts +6 -0
  52. package/src/components/UiFadeMask/types.ts +35 -0
  53. package/src/components/UiFileItem/UiFileItem.vue +17 -4
  54. package/src/components/UiFileItem/__tests__/UiFileItem.test.ts +49 -90
  55. package/src/components/UiFileType/UiFileType.stories.ts +13 -2
  56. package/src/components/UiFileType/UiFileType.vue +8 -0
  57. package/src/components/UiFileType/__tests__/UiFileType.test.ts +10 -0
  58. package/src/components/UiFileType/types.ts +3 -1
  59. package/src/components/UiListbox/UiListbox.stories.ts +121 -0
  60. package/src/components/UiListbox/UiListboxVirtualizer.vue +42 -0
  61. package/src/components/UiListbox/__tests__/UiListboxVirtualizer.test.ts +96 -0
  62. package/src/components/UiListbox/index.ts +1 -0
  63. package/src/components/UiListbox/types.ts +42 -0
  64. package/src/components/UiSelect/UiSelect.stories.ts +109 -1
  65. package/src/components/UiSelect/UiSelectVirtualizer.vue +373 -0
  66. package/src/components/UiSelect/__tests__/UiSelectVirtualizer.test.ts +185 -0
  67. package/src/components/UiSelect/index.ts +1 -0
  68. package/src/components/UiSelect/types.ts +38 -0
  69. package/src/components/UiSnackbar/UiSnackbar.stories.ts +4 -5
  70. package/src/components/UiSwitch/UiSwitch.stories.ts +658 -7
  71. package/src/components/UiSwitch/UiSwitch.vue +1 -0
  72. package/src/components/UiSwitch/__tests__/UiSwitch.test.ts +48 -0
  73. package/src/components/UiSwitch/types.ts +13 -0
  74. package/src/components/UiToggleGroup/UiToggleGroup.vue +1 -1
  75. package/src/components/core/dropdown-menu/DropdownMenuCheckboxItem.vue +8 -2
  76. package/src/components/core/dropdown-menu/DropdownMenuItem.vue +1 -1
  77. package/src/components/core/dropdown-menu/DropdownMenuRadioItem.vue +8 -2
  78. package/src/components/core/dropdown-menu/DropdownMenuSubTrigger.vue +1 -1
  79. package/src/components/core/field/FieldLabel.vue +1 -1
  80. package/src/components/core/label/Label.vue +1 -1
  81. package/src/components/core/listbox/ListboxItem.vue +1 -1
  82. package/src/components/core/switch/Switch.vue +23 -17
  83. package/src/components/core/switch/index.ts +36 -0
  84. package/src/components/index.ts +1 -0
  85. package/src/index.ts +3 -0
  86. package/src/lib/scrollbar.ts +295 -0
  87. package/src/lib/useAnchorFloat.ts +0 -2
  88. package/src/lib/useIsTruncated.test.ts +174 -0
  89. package/src/lib/useIsTruncated.ts +75 -0
  90. package/src/patterns/UiFileUpload/UiFileItem.stories.ts +1162 -0
  91. package/src/patterns/UiFileUpload/UiFileUpload.stories.ts +552 -1
  92. package/src/patterns/UiFileUpload/__tests__/UiFileUpload.test.ts +5 -21
  93. package/src/patterns/UiFloatActions/UiFloatActionItems.vue +0 -1
  94. package/src/patterns/UiFloatActions/UiFloatActions.stories.ts +4 -6
  95. package/src/patterns/UiFloatActions/UiFloatActions.vue +23 -12
  96. package/src/patterns/UiFloatActions/__tests__/UiFloatActions.test.ts +23 -0
  97. package/src/patterns/UiFloatActions/types.ts +2 -2
  98. package/src/patterns/UiProfileCard/UiProfileCard.stories.ts +1079 -0
  99. package/src/patterns/UiProfileCard/index.ts +7 -0
  100. package/src/patterns/UiTopBar/UiTopBar.stories.ts +1121 -0
  101. package/src/patterns/UiTopBar/UiTopBar.vue +166 -0
  102. package/src/patterns/UiTopBar/__tests__/UiTopBar.test.ts +245 -0
  103. package/src/patterns/UiTopBar/index.ts +2 -0
  104. package/src/patterns/UiTopBar/types.ts +29 -0
  105. package/src/patterns/index.ts +2 -0
  106. package/src/theme/Background.stories.ts +27 -1
  107. package/src/theme/BorderRadius.stories.ts +5 -0
  108. package/src/theme/Overlay.stories.ts +12 -1
  109. package/src/theme/Scrollbar.stories.ts +260 -0
  110. package/tokens.json +224 -2
  111. package/src/components/UiFileItem/UiFileItem.stories.ts +0 -442
@@ -0,0 +1,107 @@
1
+ import '@testing-library/jest-dom/vitest';
2
+ import { render, waitFor } from '@testing-library/vue';
3
+ import userEvent from '@testing-library/user-event';
4
+ import { afterAll, beforeAll, describe, expect, test } from 'vitest';
5
+ import { nextTick } from 'vue';
6
+ import { stubScrollLayout } from '@/__tests__/test-utils';
7
+ import { UiAutocomplete } from '../index';
8
+
9
+ const OPTION_COUNT = 500;
10
+ const VIEWPORT_HEIGHT = 300;
11
+
12
+ const options = Array.from({ length: OPTION_COUNT }, (_, index) => ({
13
+ value: `option-${index + 1}`,
14
+ label: `Option ${index + 1}`,
15
+ }));
16
+
17
+ let restoreScrollLayout: () => void;
18
+
19
+ // jsdom neither lays elements out nor scrolls them, so without a stand-in the
20
+ // virtualizer would measure a zero-height container and never see the scrolling
21
+ // that brings the options further down the list into range.
22
+ beforeAll(() => {
23
+ restoreScrollLayout = stubScrollLayout(VIEWPORT_HEIGHT);
24
+ });
25
+
26
+ afterAll(() => {
27
+ restoreScrollLayout();
28
+ });
29
+
30
+ /**
31
+ * Renders an open autocomplete over a long option list.
32
+ * @param virtualized Whether to mount only the options in view.
33
+ * @returns The testing-library render result.
34
+ */
35
+ async function renderAutocomplete(virtualized: boolean) {
36
+ const result = render(UiAutocomplete, {
37
+ props: { options, virtualized, defaultOpen: true, placeholder: 'Search' },
38
+ });
39
+
40
+ // The scroll container is only measurable once mounted, so the first render
41
+ // still comes out empty.
42
+ await nextTick();
43
+
44
+ return result;
45
+ }
46
+
47
+ describe('UiAutocomplete virtualized', () => {
48
+ test('mounts only the options in view instead of the whole list', async () => {
49
+ const { getAllByRole } = await renderAutocomplete(true);
50
+
51
+ const rendered = getAllByRole('option');
52
+ expect(rendered.length).toBeGreaterThan(0);
53
+ expect(rendered.length).toBeLessThan(OPTION_COUNT);
54
+ });
55
+
56
+ test('mounts the whole list when virtualization is off', async () => {
57
+ const { getAllByRole } = await renderAutocomplete(false);
58
+
59
+ expect(getAllByRole('option')).toHaveLength(OPTION_COUNT);
60
+ });
61
+
62
+ // Only a fraction of the options is in the DOM, so each one has to carry its
63
+ // place in the full list for screen readers to announce it correctly.
64
+ test('announces the position of an option within the full list', async () => {
65
+ const { getAllByRole } = await renderAutocomplete(true);
66
+
67
+ const [first] = getAllByRole('option');
68
+ expect(first).toHaveAttribute('aria-setsize', String(OPTION_COUNT));
69
+ expect(first).toHaveAttribute('aria-posinset', '1');
70
+ });
71
+
72
+ test('leaves the option list unannotated when virtualization is off', async () => {
73
+ const { getAllByRole } = await renderAutocomplete(false);
74
+
75
+ const [first] = getAllByRole('option');
76
+ expect(first).not.toHaveAttribute('aria-setsize');
77
+ });
78
+
79
+ // The options are stacked by transform inside a spacer, so the listbox has to
80
+ // scroll over the full list rather than only the mounted slice.
81
+ test('sizes the scroll container for the full list', async () => {
82
+ const { getByRole } = await renderAutocomplete(true);
83
+
84
+ const spacer = getByRole('listbox').firstElementChild as HTMLElement;
85
+ expect(spacer.style.height).toBe(`${OPTION_COUNT * 32}px`);
86
+ });
87
+
88
+ // The list opens on the selected option, which under virtualization is only
89
+ // in the DOM once it has been scrolled to.
90
+ test('opens on a selection that sits outside the mounted range', async () => {
91
+ const user = userEvent.setup();
92
+ const { getByRole } = render(UiAutocomplete, {
93
+ props: {
94
+ options,
95
+ virtualized: true,
96
+ defaultValue: 'option-400',
97
+ placeholder: 'Search',
98
+ },
99
+ });
100
+
101
+ await user.click(getByRole('textbox'));
102
+
103
+ await waitFor(() => {
104
+ expect(getByRole('option', { name: 'Option 400' })).toBeInTheDocument();
105
+ });
106
+ });
107
+ });
@@ -58,6 +58,17 @@ export type UiAutocompleteProps = {
58
58
  startIcon?: UiIconProps['name'];
59
59
  /** Whether to show the default right-side selected indicator. */
60
60
  showIndicator?: boolean;
61
+ /**
62
+ * Whether to mount only the options in view, for lists too long to render at
63
+ * once. Applies to `options` only, not to items provided through the slot.
64
+ */
65
+ virtualized?: boolean;
66
+ /**
67
+ * The expected height of an option in pixels while virtualizing, used to size
68
+ * the scrollbar before the options are measured. Raise it for taller custom
69
+ * items.
70
+ */
71
+ estimateSize?: number;
61
72
  };
62
73
 
63
74
  export type UiAutocompleteEmits = {
@@ -1,3 +1,4 @@
1
+ import { ref, onMounted, onUnmounted } from 'vue';
1
2
  import type { Meta, StoryObj } from '@storybook/vue3-vite';
2
3
  import UiCodeBlock from './UiCodeBlock.vue';
3
4
 
@@ -366,3 +367,56 @@ export const HtmlWithLineNumbers: Story = {
366
367
  },
367
368
  },
368
369
  };
370
+
371
+ const streamingTemplateSource = `<script setup lang="ts">
372
+ import { ref } from 'vue'
373
+ import { UiCodeBlock } from '@aleph-alpha/ui-library'
374
+
375
+ const code = ref('')
376
+
377
+ // Append each chunk as it arrives; UiCodeBlock re-highlights in place
378
+ // instead of falling back to unhighlighted text between updates.
379
+ for await (const chunk of responseStream) {
380
+ code.value += chunk
381
+ }
382
+ </script>
383
+
384
+ <template>
385
+ <UiCodeBlock :code="code" language="typescript" filename="stream.ts" />
386
+ </template>`;
387
+
388
+ /**
389
+ * The component keeps the previously highlighted output on screen while
390
+ * re-highlighting, so a code prop that grows chunk by chunk (LLM streaming)
391
+ * updates in place instead of flashing back to unhighlighted text.
392
+ */
393
+ export const Streaming: Story = {
394
+ render: () => ({
395
+ components: { UiCodeBlock },
396
+ setup() {
397
+ const code = ref('');
398
+ let timerId: ReturnType<typeof setInterval> | undefined;
399
+
400
+ onMounted(() => {
401
+ let index = 0;
402
+ timerId = setInterval(() => {
403
+ index = Math.min(index + 3, typescriptExample.length);
404
+ code.value = typescriptExample.slice(0, index);
405
+ if (index === typescriptExample.length) index = 0;
406
+ }, 40);
407
+ });
408
+
409
+ onUnmounted(() => clearInterval(timerId));
410
+
411
+ return { code };
412
+ },
413
+ template: `<UiCodeBlock :code="code" language="typescript" filename="stream.ts" />`,
414
+ }),
415
+ parameters: {
416
+ docs: {
417
+ source: {
418
+ code: streamingTemplateSource,
419
+ },
420
+ },
421
+ },
422
+ };
@@ -1,7 +1,8 @@
1
1
  <script setup lang="ts">
2
2
  import { ref, computed, watch, onMounted, onUnmounted } from 'vue';
3
- import { useClipboard } from '@vueuse/core';
4
- import { codeToHtml } from 'shiki';
3
+ import { useClipboard, useThrottleFn } from '@vueuse/core';
4
+ import { getSingletonHighlighter } from 'shiki';
5
+ import type { BundledLanguage, Highlighter } from 'shiki';
5
6
  import { cn } from '@/lib/utils';
6
7
  import { UiButton } from '@/components/UiButton';
7
8
  import { UiIcon } from '@/components/UiIcon';
@@ -23,7 +24,6 @@ const props = withDefaults(defineProps<UiCodeBlockProps>(), {
23
24
  });
24
25
 
25
26
  const highlightedHtml = ref('');
26
- const isHighlighted = ref(false);
27
27
  const isCopied = ref(false);
28
28
 
29
29
  const { copy } = useClipboard();
@@ -35,12 +35,27 @@ const shikiTokenColorOverrides = {
35
35
  '#FFAB70': TOKEN_COLOR_CONTENT_ON_SURFACE_PRIMARY,
36
36
  } as const;
37
37
 
38
+ const SHIKI_THEMES = { light: 'github-light', dark: 'github-dark' } as const;
39
+ const FALLBACK_LANGUAGE = 'text';
40
+ /** Languages Shiki renders without loading a grammar. */
41
+ const PLAIN_LANGUAGES = ['text', 'txt', 'plain', 'plaintext'];
42
+ /**
43
+ * Streaming updates `code` on every chunk, and each update re-tokenizes the
44
+ * whole block. Cap how often that happens so long blocks stay cheap.
45
+ */
46
+ const HIGHLIGHT_THROTTLE_MS = 100;
47
+
38
48
  const headerLabel = computed(() => props.filename || props.language);
39
49
  const showHeader = computed(
40
50
  () => headerLabel.value !== 'text' || props.showCopyButton,
41
51
  );
42
52
 
43
53
  let highlightRequestId = 0;
54
+ let highlighter: Highlighter | undefined;
55
+ /** `props.language` that `activeLanguage` was resolved from. */
56
+ let resolvedFor: string | undefined;
57
+ let activeLanguage: string = FALLBACK_LANGUAGE;
58
+ const loadedLanguages = new Set(PLAIN_LANGUAGES);
44
59
 
45
60
  function normalizeShikiTokenColors(html: string) {
46
61
  return Object.entries(shikiTokenColorOverrides).reduce(
@@ -49,41 +64,76 @@ function normalizeShikiTokenColors(html: string) {
49
64
  );
50
65
  }
51
66
 
67
+ // Renders synchronously, and only ever overwrites `highlightedHtml` with the
68
+ // next result. The previous output stays on screen until then, so a streamed
69
+ // update never falls back to the unhighlighted `<pre>` mid-flight.
70
+ function renderHighlighted(instance: Highlighter, language: string) {
71
+ try {
72
+ highlightedHtml.value = normalizeShikiTokenColors(
73
+ instance.codeToHtml(props.code, {
74
+ lang: language,
75
+ themes: SHIKI_THEMES,
76
+ }),
77
+ );
78
+ } catch {
79
+ highlightedHtml.value = '';
80
+ }
81
+ }
82
+
83
+ // Loads the grammar on first use, falling back to plain text if unsupported.
84
+ async function resolveLanguage(instance: Highlighter, language: string) {
85
+ if (loadedLanguages.has(language)) return language;
86
+ try {
87
+ await instance.loadLanguage(language as BundledLanguage);
88
+ loadedLanguages.add(language);
89
+ return language;
90
+ } catch {
91
+ return FALLBACK_LANGUAGE;
92
+ }
93
+ }
94
+
52
95
  async function highlightCode() {
53
96
  const requestId = ++highlightRequestId;
54
- isHighlighted.value = false;
97
+
55
98
  try {
56
- const html = await codeToHtml(props.code, {
57
- lang: props.language as Parameters<typeof codeToHtml>[1]['lang'],
58
- themes: {
59
- light: 'github-light',
60
- dark: 'github-dark',
61
- },
99
+ highlighter ??= await getSingletonHighlighter({
100
+ themes: [SHIKI_THEMES.light, SHIKI_THEMES.dark],
101
+ langs: [],
62
102
  });
63
- if (requestId !== highlightRequestId) return;
64
- highlightedHtml.value = normalizeShikiTokenColors(html);
65
- isHighlighted.value = true;
66
103
  } catch {
67
- if (requestId !== highlightRequestId) return;
68
- try {
69
- const html = await codeToHtml(props.code, {
70
- lang: 'text',
71
- themes: {
72
- light: 'github-light',
73
- dark: 'github-dark',
74
- },
75
- });
76
- if (requestId !== highlightRequestId) return;
77
- highlightedHtml.value = normalizeShikiTokenColors(html);
78
- isHighlighted.value = true;
79
- } catch {
80
- if (requestId !== highlightRequestId) return;
81
- highlightedHtml.value = '';
82
- }
104
+ if (requestId === highlightRequestId) highlightedHtml.value = '';
105
+ return;
83
106
  }
107
+ if (requestId !== highlightRequestId) return;
108
+
109
+ const language = await resolveLanguage(highlighter, props.language);
110
+ if (requestId !== highlightRequestId) return;
111
+
112
+ activeLanguage = language;
113
+ resolvedFor = props.language;
114
+ renderHighlighted(highlighter, language);
84
115
  }
85
116
 
86
- watch(() => [props.code, props.language], highlightCode);
117
+ const highlightThrottled = useThrottleFn(
118
+ () => {
119
+ // Grammar already loaded for this language, so no await is needed: the new
120
+ // HTML is set from the pre-flush watcher and lands in the same DOM update
121
+ // as the surrounding text, rather than a render pass later.
122
+ if (highlighter && resolvedFor === props.language) {
123
+ highlightRequestId++;
124
+ renderHighlighted(highlighter, activeLanguage);
125
+ return;
126
+ }
127
+ void highlightCode();
128
+ },
129
+ HIGHLIGHT_THROTTLE_MS,
130
+ // Trailing is required: without it the final chunk of a stream is dropped
131
+ // and the block stays stuck on the second-to-last update.
132
+ true,
133
+ );
134
+
135
+ watch(() => props.code, highlightThrottled);
136
+ watch(() => props.language, highlightCode);
87
137
  onMounted(highlightCode);
88
138
 
89
139
  let copyTimerId: ReturnType<typeof setTimeout> | undefined;
@@ -102,6 +152,8 @@ async function handleCopy() {
102
152
  }
103
153
 
104
154
  onUnmounted(() => {
155
+ // Not for safety — a post-unmount ref write is inert. This just drops
156
+ // in-flight highlighting instead of tokenizing for a discarded component.
105
157
  highlightRequestId++;
106
158
  clearTimeout(copyTimerId);
107
159
  });
@@ -148,7 +200,7 @@ onUnmounted(() => {
148
200
  -->
149
201
  <!-- eslint-disable vue/no-v-html, sonarjs/no-vue-bypass-sanitization -->
150
202
  <div
151
- v-if="isHighlighted && highlightedHtml"
203
+ v-if="highlightedHtml"
152
204
  :class="
153
205
  cn(
154
206
  'ui-code-block__content',
@@ -160,7 +212,7 @@ onUnmounted(() => {
160
212
  <!-- eslint-enable vue/no-v-html, sonarjs/no-vue-bypass-sanitization -->
161
213
  <pre
162
214
  v-else
163
- class="m-0 bg-background p-4 font-mono text-sm leading-relaxed text-foreground"
215
+ class="m-0 p-4 text-sm leading-relaxed"
164
216
  ><code>{{ code }}</code></pre>
165
217
  </div>
166
218
  </div>
@@ -3,14 +3,22 @@ import userEvent from '@testing-library/user-event';
3
3
  import { afterEach, describe, expect, test, vi, beforeEach } from 'vitest';
4
4
  import UiCodeBlock from '../UiCodeBlock.vue';
5
5
 
6
+ const shiki = vi.hoisted(() => ({
7
+ codeToHtml: vi.fn(),
8
+ loadLanguage: vi.fn(),
9
+ }));
10
+
6
11
  vi.mock('shiki', () => ({
7
- codeToHtml: vi
8
- .fn()
9
- .mockResolvedValue(
10
- '<pre class="shiki shiki-themes github-light github-dark"><code><span class="line">const x = 1;</span></code></pre>',
11
- ),
12
+ getSingletonHighlighter: vi.fn().mockResolvedValue({
13
+ codeToHtml: shiki.codeToHtml,
14
+ loadLanguage: shiki.loadLanguage,
15
+ }),
12
16
  }));
13
17
 
18
+ function highlightedMarkup(code: string) {
19
+ return `<pre class="shiki shiki-themes github-light github-dark"><code><span class="line">${code}</span></code></pre>`;
20
+ }
21
+
14
22
  describe('UiCodeBlock', () => {
15
23
  let originalClipboardDescriptor: PropertyDescriptor | undefined;
16
24
  let originalExecCommand: typeof document.execCommand;
@@ -18,6 +26,11 @@ describe('UiCodeBlock', () => {
18
26
  beforeEach(() => {
19
27
  vi.clearAllMocks();
20
28
 
29
+ shiki.codeToHtml.mockImplementation((code: string) =>
30
+ highlightedMarkup(code),
31
+ );
32
+ shiki.loadLanguage.mockResolvedValue(undefined);
33
+
21
34
  originalClipboardDescriptor = Object.getOwnPropertyDescriptor(
22
35
  navigator,
23
36
  'clipboard',
@@ -59,8 +72,7 @@ describe('UiCodeBlock', () => {
59
72
  });
60
73
 
61
74
  test('normalizes low-contrast Shiki token colors to theme tokens', async () => {
62
- const { codeToHtml } = await import('shiki');
63
- vi.mocked(codeToHtml).mockResolvedValueOnce(
75
+ shiki.codeToHtml.mockReturnValueOnce(
64
76
  '<pre class="shiki shiki-themes github-light github-dark"><code><span class="line"><span style="color:#E36209;--shiki-dark:#FFAB70">columns</span></span></code></pre>',
65
77
  );
66
78
 
@@ -189,13 +201,7 @@ describe('UiCodeBlock', () => {
189
201
  });
190
202
 
191
203
  test('falls back to text highlighting when language is unsupported', async () => {
192
- const { codeToHtml } = await import('shiki');
193
- const mock = vi.mocked(codeToHtml);
194
- mock
195
- .mockRejectedValueOnce(new Error('Unknown language'))
196
- .mockResolvedValueOnce(
197
- '<pre class="shiki shiki-themes github-light github-dark"><code><span class="line">code</span></code></pre>',
198
- );
204
+ shiki.loadLanguage.mockRejectedValueOnce(new Error('Unknown language'));
199
205
 
200
206
  const { container } = render(UiCodeBlock, {
201
207
  props: { code: 'code', language: 'unknown-lang' },
@@ -205,16 +211,16 @@ describe('UiCodeBlock', () => {
205
211
  expect(container.querySelector('.shiki')).toBeInTheDocument();
206
212
  });
207
213
 
208
- expect(mock).toHaveBeenCalledTimes(2);
209
- expect(mock).toHaveBeenLastCalledWith(
214
+ expect(shiki.codeToHtml).toHaveBeenLastCalledWith(
210
215
  'code',
211
216
  expect.objectContaining({ lang: 'text' }),
212
217
  );
213
218
  });
214
219
 
215
220
  test('shows plain pre/code fallback when all highlighting fails', async () => {
216
- const { codeToHtml } = await import('shiki');
217
- vi.mocked(codeToHtml).mockRejectedValue(new Error('Shiki broken'));
221
+ shiki.codeToHtml.mockImplementation(() => {
222
+ throw new Error('Shiki broken');
223
+ });
218
224
 
219
225
  const { container } = render(UiCodeBlock, {
220
226
  props: { code: 'fallback content', language: 'typescript' },
@@ -228,14 +234,12 @@ describe('UiCodeBlock', () => {
228
234
  });
229
235
 
230
236
  test('calls codeToHtml with correct language and dual themes', async () => {
231
- const { codeToHtml } = await import('shiki');
232
-
233
237
  render(UiCodeBlock, {
234
238
  props: { code: 'const x = 1;', language: 'typescript' },
235
239
  });
236
240
 
237
241
  await waitFor(() => {
238
- expect(codeToHtml).toHaveBeenCalledWith('const x = 1;', {
242
+ expect(shiki.codeToHtml).toHaveBeenCalledWith('const x = 1;', {
239
243
  lang: 'typescript',
240
244
  themes: {
241
245
  light: 'github-light',
@@ -244,4 +248,44 @@ describe('UiCodeBlock', () => {
244
248
  });
245
249
  });
246
250
  });
251
+
252
+ test('keeps highlighted output mounted while streamed code updates', async () => {
253
+ const { container, rerender } = render(UiCodeBlock, {
254
+ props: { code: 'const x = 1', language: 'typescript' },
255
+ });
256
+
257
+ await waitFor(() => {
258
+ expect(container.querySelector('.shiki')).toBeInTheDocument();
259
+ });
260
+
261
+ // A streamed chunk must not drop back to the unhighlighted fallback, which
262
+ // renders on a different background and so flashes between renders.
263
+ await rerender({ code: 'const x = 12' });
264
+
265
+ expect(container.querySelector('pre:not(.shiki)')).toBeNull();
266
+ expect(container.querySelector('.shiki')).toBeInTheDocument();
267
+ expect(container.querySelector('.shiki')?.textContent).toBe('const x = 12');
268
+ });
269
+
270
+ test('throttles re-highlighting but applies the latest streamed code', async () => {
271
+ const { container, rerender } = render(UiCodeBlock, {
272
+ props: { code: 'a', language: 'typescript' },
273
+ });
274
+
275
+ await waitFor(() => {
276
+ expect(container.querySelector('.shiki')).toBeInTheDocument();
277
+ });
278
+
279
+ shiki.codeToHtml.mockClear();
280
+
281
+ await rerender({ code: 'ab' });
282
+ await rerender({ code: 'abc' });
283
+ await rerender({ code: 'abcd' });
284
+
285
+ await waitFor(() => {
286
+ expect(container.querySelector('.shiki')?.textContent).toBe('abcd');
287
+ });
288
+
289
+ expect(shiki.codeToHtml.mock.calls.length).toBeLessThan(4);
290
+ });
247
291
  });