@diegopluna/narvi 0.5.8 → 0.5.10

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 (47) hide show
  1. package/dist/components/dialog/ConfirmDialog.svelte +1 -2
  2. package/dist/components/dialog/DialogDescription.svelte +2 -2
  3. package/dist/components/dialog/DialogTitle.svelte +2 -2
  4. package/dist/components/input/Input.svelte +156 -15
  5. package/dist/components/input/Input.svelte.d.ts +17 -3
  6. package/dist/components/markdown/Markdown.svelte +68 -7
  7. package/dist/components/markdown/Markdown.svelte.d.ts +9 -0
  8. package/dist/components/markdown/MarkdownBlocks.svelte +4 -3
  9. package/dist/components/markdown/MarkdownCode.svelte +108 -9
  10. package/dist/components/markdown/MarkdownCode.svelte.d.ts +5 -1
  11. package/dist/components/markdown/MarkdownHtmlPreview.svelte +186 -0
  12. package/dist/components/markdown/MarkdownHtmlPreview.svelte.d.ts +11 -0
  13. package/dist/components/markdown/MarkdownPreview.svelte +17 -0
  14. package/dist/components/markdown/MarkdownPreview.svelte.d.ts +6 -0
  15. package/dist/components/markdown/MarkdownTable.svelte +61 -4
  16. package/dist/components/markdown/context.d.ts +21 -0
  17. package/dist/components/markdown/labels.d.ts +12 -0
  18. package/dist/components/markdown/labels.js +5 -0
  19. package/dist/components/markdown/preview.d.ts +9 -0
  20. package/dist/components/markdown/preview.js +14 -0
  21. package/dist/components/markdown/static.d.ts +2 -0
  22. package/dist/components/markdown/static.js +5 -1
  23. package/dist/components/markdown/table-image.d.ts +15 -0
  24. package/dist/components/markdown/table-image.js +342 -0
  25. package/dist/components/message/MessageAction.svelte +17 -2
  26. package/dist/components/message/MessageAction.svelte.d.ts +7 -0
  27. package/dist/internal/Glyph.svelte +11 -0
  28. package/dist/internal/Glyph.svelte.d.ts +2 -0
  29. package/dist/internal/closing.svelte.d.ts +0 -6
  30. package/dist/internal/closing.svelte.js +0 -33
  31. package/dist/internal/markers.stylex.d.ts +4 -0
  32. package/dist/internal/markers.stylex.js +2 -0
  33. package/dist/markdown/highlight.d.ts +2 -2
  34. package/dist/markdown/highlight.js +2 -2
  35. package/dist/markdown/html.d.ts +3 -1
  36. package/dist/markdown/html.js +6 -0
  37. package/dist/markdown/index.d.ts +2 -2
  38. package/dist/markdown/index.js +2 -2
  39. package/dist/markdown/table.d.ts +20 -1
  40. package/dist/markdown/table.js +111 -0
  41. package/package.json +19 -19
  42. package/skills/building-ui/SKILL.md +5 -5
  43. package/skills/building-ui/references/components.md +26 -26
  44. package/skills/markdown/SKILL.md +26 -7
  45. package/skills/setup/SKILL.md +1 -1
  46. package/skills/styling/SKILL.md +1 -1
  47. package/skills/theming/SKILL.md +1 -1
@@ -23,7 +23,6 @@
23
23
  import Button from '../button/Button.svelte';
24
24
  import Notice from '../notice/Notice.svelte';
25
25
  import { nestDialog, popupContainer } from '../../internal/popup.js';
26
- import { unbindLater } from '../../internal/closing.svelte.js';
27
26
  import { dialog } from './styles.js';
28
27
 
29
28
  export type ConfirmDialogProps = {
@@ -186,7 +185,7 @@
186
185
  {#if words.description || words.warning}
187
186
  <AlertDialogDescription {...stylex.attrs(styles.describe)}>
188
187
  {#snippet render({ props })}
189
- <div {...unbindLater(props)}>
188
+ <div {...props}>
190
189
  {#if words.description}
191
190
  <p {...stylex.attrs(dialog.description)}>{words.description}</p>
192
191
  {/if}
@@ -3,7 +3,7 @@
3
3
  import { DialogDescription as UiDialogDescription } from '@ui-sdk/svelte/dialog';
4
4
  import type { Snippet } from 'svelte';
5
5
  import * as stylex from '@stylexjs/stylex';
6
- import { keepWhileClosing, place, unbindLater } from '../../internal/closing.svelte.js';
6
+ import { keepWhileClosing, place } from '../../internal/closing.svelte.js';
7
7
  import { attrs, type Sx } from '../../internal/sx.js';
8
8
  import { dialog } from './styles.js';
9
9
 
@@ -26,7 +26,7 @@
26
26
  <!-- A div, as bits-ui's was, so a description can hold more than a line of text -->
27
27
  <UiDialogDescription {...rest} {...attrs([dialog.description, sx], className)}>
28
28
  {#snippet render({ props })}
29
- <div bind:this={element} {...unbindLater(props)}>
29
+ <div bind:this={element} {...props}>
30
30
  {#if kept()}
31
31
  <span {...stylex.attrs(dialog.kept)} {@attach place(kept()!)}></span>
32
32
  {:else}
@@ -3,7 +3,7 @@
3
3
  import { DialogTitle as UiDialogTitle } from '@ui-sdk/svelte/dialog';
4
4
  import type { Snippet } from 'svelte';
5
5
  import * as stylex from '@stylexjs/stylex';
6
- import { keepWhileClosing, place, unbindLater } from '../../internal/closing.svelte.js';
6
+ import { keepWhileClosing, place } from '../../internal/closing.svelte.js';
7
7
  import { attrs, type Sx } from '../../internal/sx.js';
8
8
  import { dialog } from './styles.js';
9
9
 
@@ -28,7 +28,7 @@
28
28
  <!-- Names the dialog for assistive technology -->
29
29
  <UiDialogTitle {...rest} {...attrs([dialog.title, sx], className)}>
30
30
  {#snippet render({ props })}
31
- <svelte:element this={`h${level}`} bind:this={element} {...unbindLater(props)}>
31
+ <svelte:element this={`h${level}`} bind:this={element} {...props}>
32
32
  {#if kept()}
33
33
  <span {...stylex.attrs(dialog.kept)} {@attach place(kept()!)}></span>
34
34
  {:else}
@@ -1,11 +1,16 @@
1
1
  <script lang="ts" module>
2
2
  import * as stylex from '@stylexjs/stylex';
3
- import type { Snippet } from 'svelte';
3
+ import { DEV } from 'esm-env';
4
+ import { tick, type Snippet } from 'svelte';
4
5
  import type { ClassValue, HTMLInputAttributes } from 'svelte/elements';
5
6
  import '../../internal/icons.css';
6
7
  import { colors, density } from '../../tokens.stylex.js';
8
+ import { media } from '../../media.stylex.js';
7
9
  import { control, type ControlSize } from '../../internal/control.js';
10
+ import Glyph from '../../internal/Glyph.svelte';
11
+ import { inputMarker } from '../../internal/markers.stylex.js';
8
12
  import { attrs, type Sx } from '../../internal/sx.js';
13
+ import Button from '../button/Button.svelte';
9
14
  import { getFieldContext } from '../field/context.js';
10
15
 
11
16
  export type InputSize = ControlSize;
@@ -20,10 +25,24 @@
20
25
  * the field itself.
21
26
  */
22
27
  icon?: Snippet | undefined;
28
+ /**
29
+ * Controls at the end of the field, inside its edge, such as a `Button size="xs" iconOnly
30
+ * variant="ghost"` that clears it. They keep their own names and take the pointer; the
31
+ * text stops before them. With one, `sx` and `class` style the element around the field,
32
+ * as with `icon`.
33
+ */
34
+ end?: Snippet | undefined;
35
+ /**
36
+ * A password field with an eye at its end that shows and hides what is typed, whatever
37
+ * `type` says. It takes the place of `end`, which is not drawn beside it.
38
+ */
39
+ reveal?: boolean | undefined;
40
+ /** The eye's name, which stays the same while it is pressed. "Show password" by default. */
41
+ revealLabel?: string | undefined;
23
42
  sx?: Sx | undefined;
24
43
  /**
25
- * Styles for the field itself, whether or not there is an `icon`: its text, its fill,
26
- * its edge. Without an icon they go after `sx`.
44
+ * Styles for the field itself, whether or not there is an `icon` or an `end`: its text, its
45
+ * fill, its edge. Without either they go after `sx`.
27
46
  */
28
47
  inputSx?: Sx | undefined;
29
48
  /** Classes for the field itself, as `inputSx`. */
@@ -31,9 +50,18 @@
31
50
  ref?: HTMLInputElement | null | undefined;
32
51
  };
33
52
 
53
+ // Hover and focus as they happen, or as the catalog shows them, as in `internal/control.ts`
54
+ const HOVER = ':is(:hover, [data-preview~="hover"])';
55
+ const FOCUS = ':is(:focus-visible, [data-preview~="focus"])';
56
+
34
57
  /** A length at the window's density (`density` in the tokens). */
35
58
  const d = (rem: string) => `calc(${rem} * ${density.factor})`;
36
59
 
60
+ // What sits at the end is as wide as it measures; until it has been measured, one xs button
61
+ const END_WIDTH = `var(--narvi-input-end-width, ${d('1.5rem')})`;
62
+ // Between the end of the text and what sits at the end
63
+ const END_GAP = '0.25rem';
64
+
37
65
  const styles = stylex.create({
38
66
  frame: { position: 'relative', display: 'block', width: '100%', minWidth: 0 },
39
67
  // In the field's start padding, where the pointer passes through to the field
@@ -52,19 +80,57 @@
52
80
  // gap of 6px, which keep theirs
53
81
  besideSm: { paddingInlineStart: `calc(${d('0.5rem')} + 1.25rem)` },
54
82
  besideMd: { paddingInlineStart: `calc(${d('0.625rem')} + 1.375rem)` },
55
- besideLg: { paddingInlineStart: `calc(${d('0.75rem')} + 1.375rem)` }
83
+ besideLg: { paddingInlineStart: `calc(${d('0.75rem')} + 1.375rem)` },
84
+ // Inside the field's end, centred in its height. An xs button (24px) sits as far from the
85
+ // end as from the top and the bottom.
86
+ end: {
87
+ position: 'absolute',
88
+ insetBlock: 0,
89
+ display: 'flex',
90
+ alignItems: 'center',
91
+ gap: '0.125rem',
92
+ color: colors.textSubtle
93
+ },
94
+ endSm: { '--narvi-icon-size': '0.875rem', insetInlineEnd: d('0.125rem') },
95
+ endMd: { '--narvi-icon-size': '1rem', insetInlineEnd: d('0.3125rem') },
96
+ endLg: { '--narvi-icon-size': '1rem', insetInlineEnd: d('0.5rem') },
97
+ // The text stops before what sits at the end: its inset, its width and a gap
98
+ beforeSm: { paddingInlineEnd: `calc(${d('0.125rem')} + ${END_WIDTH} + ${END_GAP})` },
99
+ beforeMd: { paddingInlineEnd: `calc(${d('0.3125rem')} + ${END_WIDTH} + ${END_GAP})` },
100
+ beforeLg: { paddingInlineEnd: `calc(${d('0.5rem')} + ${END_WIDTH} + ${END_GAP})` },
101
+ // The pointer on a control at the end is still on the field: its edge stays firm
102
+ held: {
103
+ borderColor: {
104
+ default: colors.borderControl,
105
+ [HOVER]: { default: null, [media.hover]: colors.borderControlHover },
106
+ // The ancestor's hover outranks the field's own focus, so focus is said again in it
107
+ [stylex.when.ancestor(':hover', inputMarker)]: {
108
+ default: null,
109
+ [media.hover]: { default: colors.borderControlHover, [FOCUS]: colors.focusRing }
110
+ },
111
+ [FOCUS]: colors.focusRing
112
+ }
113
+ },
114
+ // Edge's own eye in a password field, beside Narvi's
115
+ noNativeReveal: { '::-ms-reveal': { display: 'none' } }
56
116
  });
57
117
 
58
118
  const iconStyles = { sm: styles.iconSm, md: styles.iconMd, lg: styles.iconLg };
59
119
  const besideStyles = { sm: styles.besideSm, md: styles.besideMd, lg: styles.besideLg };
120
+ const endStyles = { sm: styles.endSm, md: styles.endMd, lg: styles.endLg };
121
+ const beforeStyles = { sm: styles.beforeSm, md: styles.beforeMd, lg: styles.beforeLg };
60
122
  </script>
61
123
 
62
124
  <script lang="ts">
63
125
  let {
64
126
  value = $bindable(),
65
127
  size = 'md',
128
+ type,
66
129
  invalid,
67
130
  icon,
131
+ end,
132
+ reveal = false,
133
+ revealLabel = 'Show password',
68
134
  disabled,
69
135
  required,
70
136
  id,
@@ -77,31 +143,106 @@
77
143
  ...rest
78
144
  }: InputProps = $props();
79
145
 
146
+ $effect(() => {
147
+ if (DEV && reveal && end) {
148
+ console.warn(
149
+ 'Input: `reveal` draws its own eye at the end, so the `end` snippet is not drawn.'
150
+ );
151
+ }
152
+ });
153
+
80
154
  const field = getFieldContext();
81
155
  const isInvalid = $derived(invalid ?? field?.invalid ?? false);
156
+ const isDisabled = $derived(disabled ?? field?.disabled);
157
+ const inputId = $derived(id ?? field?.id);
158
+
159
+ let shown = $state(false);
160
+ const inputType = $derived(reveal ? (shown ? 'text' : 'password') : type);
161
+
162
+ const hasEnd = $derived(reveal || end !== undefined);
163
+ // Measured once it renders; 0 when the snippet renders nothing, as a clear button does once
164
+ // the field is empty, and the field takes its own padding back
165
+ let endWidth = $state<number | undefined>(undefined);
166
+ const endTaken = $derived(hasEnd && endWidth !== 0);
167
+
168
+ /** Shows or hides the password, keeping the caret and the selection where they were. */
169
+ async function toggle() {
170
+ const input = ref;
171
+ const focused = input !== null && input === document.activeElement;
172
+ const start = input?.selectionStart ?? null;
173
+ const finish = input?.selectionEnd ?? null;
174
+ const direction = input?.selectionDirection ?? undefined;
175
+ shown = !shown;
176
+ if (!focused || start === null || finish === null) return;
177
+ await tick();
178
+ input.setSelectionRange(start, finish, direction);
179
+ }
82
180
  </script>
83
181
 
84
- {#snippet input(own: Sx[], className?: ClassValue | null)}
182
+ {#snippet textField(own: Sx[], className?: ClassValue | null)}
85
183
  <input
86
184
  bind:this={ref}
87
185
  bind:value
88
- id={id ?? field?.id}
89
- disabled={disabled ?? field?.disabled}
186
+ type={inputType}
187
+ id={inputId}
188
+ disabled={isDisabled}
90
189
  required={required ?? field?.required}
91
190
  aria-invalid={isInvalid ? true : undefined}
92
191
  aria-describedby={describedBy ?? field?.describedBy}
93
192
  {...rest}
94
- {...attrs([control.base, control[size], isInvalid && control.invalid, ...own], className)}
193
+ {...attrs(
194
+ [
195
+ control.base,
196
+ control[size],
197
+ hasEnd && styles.held,
198
+ isInvalid && control.invalid,
199
+ reveal && styles.noNativeReveal,
200
+ ...own
201
+ ],
202
+ className
203
+ )}
204
+ style:--narvi-input-end-width={endWidth === undefined ? undefined : `${endWidth}px`}
95
205
  />
96
206
  {/snippet}
97
207
 
98
- {#if icon}
99
- <span data-slot="input" {...attrs([styles.frame, sx], className)}>
100
- <span data-icons aria-hidden="true" {...stylex.attrs(styles.icon, iconStyles[size])}>
101
- {@render icon()}
102
- </span>
103
- {@render input([besideStyles[size], inputSx], inputClass)}
208
+ {#if icon || hasEnd}
209
+ <span data-slot="input" {...attrs([styles.frame, hasEnd && inputMarker, sx], className)}>
210
+ {#if icon}
211
+ <span data-icons aria-hidden="true" {...stylex.attrs(styles.icon, iconStyles[size])}>
212
+ {@render icon()}
213
+ </span>
214
+ {/if}
215
+ {@render textField(
216
+ [icon && besideStyles[size], endTaken && beforeStyles[size], inputSx],
217
+ inputClass
218
+ )}
219
+ {#if hasEnd}
220
+ <span
221
+ data-slot="input-end"
222
+ data-icons
223
+ bind:offsetWidth={endWidth}
224
+ {...stylex.attrs(styles.end, endStyles[size])}
225
+ >
226
+ {#if reveal}
227
+ <Button
228
+ size="xs"
229
+ iconOnly
230
+ variant="ghost"
231
+ aria-label={revealLabel}
232
+ aria-controls={inputId}
233
+ pressed={shown}
234
+ disabled={isDisabled}
235
+ onmousedown={(event: MouseEvent) => event.preventDefault()}
236
+ onclick={toggle}
237
+ >
238
+ <Glyph name={shown ? 'conceal' : 'reveal'} size={14} stroke={1.75} />
239
+ </Button>
240
+ {:else}
241
+ {@render end?.()}
242
+ {/if}
243
+ </span>
244
+ {/if}
104
245
  </span>
105
246
  {:else}
106
- {@render input([sx, inputSx], [className, inputClass])}
247
+ {@render textField([sx, inputSx], [className, inputClass])}
107
248
  {/if}
@@ -1,4 +1,4 @@
1
- import type { Snippet } from 'svelte';
1
+ import { type Snippet } from 'svelte';
2
2
  import type { ClassValue, HTMLInputAttributes } from 'svelte/elements';
3
3
  import '../../internal/icons.css';
4
4
  import { type ControlSize } from '../../internal/control.js';
@@ -14,10 +14,24 @@ export type InputProps = Omit<HTMLInputAttributes, 'size' | 'children'> & {
14
14
  * the field itself.
15
15
  */
16
16
  icon?: Snippet | undefined;
17
+ /**
18
+ * Controls at the end of the field, inside its edge, such as a `Button size="xs" iconOnly
19
+ * variant="ghost"` that clears it. They keep their own names and take the pointer; the
20
+ * text stops before them. With one, `sx` and `class` style the element around the field,
21
+ * as with `icon`.
22
+ */
23
+ end?: Snippet | undefined;
24
+ /**
25
+ * A password field with an eye at its end that shows and hides what is typed, whatever
26
+ * `type` says. It takes the place of `end`, which is not drawn beside it.
27
+ */
28
+ reveal?: boolean | undefined;
29
+ /** The eye's name, which stays the same while it is pressed. "Show password" by default. */
30
+ revealLabel?: string | undefined;
17
31
  sx?: Sx | undefined;
18
32
  /**
19
- * Styles for the field itself, whether or not there is an `icon`: its text, its fill,
20
- * its edge. Without an icon they go after `sx`.
33
+ * Styles for the field itself, whether or not there is an `icon` or an `end`: its text, its
34
+ * fill, its edge. Without either they go after `sx`.
21
35
  */
22
36
  inputSx?: Sx | undefined;
23
37
  /** Classes for the field itself, as `inputSx`. */
@@ -5,7 +5,7 @@
5
5
  finishes in place, without being rebuilt.
6
6
  -->
7
7
  <script lang="ts" module>
8
- import { untrack } from 'svelte';
8
+ import { tick, untrack } from 'svelte';
9
9
  import type { HTMLAttributes } from 'svelte/elements';
10
10
  import type {
11
11
  Block,
@@ -31,6 +31,7 @@
31
31
  import MarkdownFootnotes from './MarkdownFootnotes.svelte';
32
32
  import { SvelteSet } from 'svelte/reactivity';
33
33
  import { codeTitle } from '../../markdown/code-info.js';
34
+ import { previewKind, type PreviewKind } from './preview.js';
34
35
  import { showCopied } from '../message/MessageCopy.svelte';
35
36
  import { withoutControls } from './hidden.js';
36
37
  import { codeFileName, saveFile } from './save.js';
@@ -81,6 +82,14 @@
81
82
  lineNumbers?: boolean | undefined;
82
83
  /** Whether a code block has a button that saves it as a file. Off by default. */
83
84
  download?: boolean | undefined;
85
+ /**
86
+ * Whether a finished code block tagged `markdown`, `md` or `html` has a toggle that shows
87
+ * it rendered: `true` for both, or the kinds to allow. Markdown is drawn by this
88
+ * component, with the same options and plugins; HTML in a sandboxed frame that runs no
89
+ * script, loads nothing from the network and cannot navigate. Blocks start as their
90
+ * source, and Copy copies the source. Off by default.
91
+ */
92
+ previews?: boolean | ReadonlyArray<PreviewKind> | undefined;
84
93
  /**
85
94
  * Shows a caret at the end of the text while it streams: `true` or `'block'` for a
86
95
  * block, `'circle'` for a dot. Off by default.
@@ -209,6 +218,7 @@
209
218
  frontmatter = false,
210
219
  lineNumbers = false,
211
220
  download = false,
221
+ previews = false,
212
222
  caret = false,
213
223
  animated = false,
214
224
  static: asked,
@@ -362,6 +372,17 @@
362
372
  /** Blocks that `static` wrote and that have since been asked for as parts. */
363
373
  const woken = new SvelteSet<number>();
364
374
 
375
+ /** Code blocks shown rendered, by id. */
376
+ const previewed = new SvelteSet<number>();
377
+
378
+ /**
379
+ * Whether an element is this document's own, not one of a Markdown block shown rendered
380
+ * inside it: that document handles its own clicks, and its blocks' ids are its own.
381
+ */
382
+ function mine(element: Element): boolean {
383
+ return element.closest('[data-markdown]') === root;
384
+ }
385
+
365
386
  /** Whether a formula has been drawn in this document: only then are its blocks clipped. */
366
387
  let formulas = $state(false);
367
388
 
@@ -385,6 +406,7 @@
385
406
  highlight: resolved.highlight,
386
407
  labels: words,
387
408
  code: { lineNumbers, download },
409
+ preview: (lang: string | null) => previewKind(lang, previews) !== null,
388
410
  tickable: ontaskchange !== undefined,
389
411
  woken: (id: number) => woken.has(id)
390
412
  } satisfies StaticContext);
@@ -409,7 +431,9 @@
409
431
  ontaskchange !== undefined
410
432
  ]
411
433
  .map(Number)
412
- .join(',') + `;${serialOf(labels)};${plugins.map(serialOf).join(',')}`
434
+ .join(',') +
435
+ `;${previews === true ? 'all' : previews ? previews.join('+') : ''}` +
436
+ `;${serialOf(labels)};${plugins.map(serialOf).join(',')}`
413
437
  );
414
438
  const text = $derived(typeof value === 'string' ? value : '');
415
439
  // The document as markup written before, when this text has been drawn already. A table
@@ -445,7 +469,7 @@
445
469
  const target = event.target instanceof Element ? event.target : null;
446
470
  if (!target || !root) return;
447
471
  const part = target.closest<HTMLElement>('[data-markdown-part]');
448
- if (part && root.contains(part)) {
472
+ if (part && mine(part)) {
449
473
  try {
450
474
  resolved.statics.get(part.getAttribute('data-markdown-part')!)?.click?.(part, event);
451
475
  } catch {
@@ -456,12 +480,14 @@
456
480
  if (event.type !== 'click') return;
457
481
  const button = target.closest<HTMLElement>('[data-markdown-action]');
458
482
  const frame = button?.closest<HTMLElement>('[data-markdown-block]');
459
- if (!button || !frame || !root.contains(button)) return;
483
+ if (!button || !frame || !mine(frame)) return;
460
484
  const block = blockById(Number(frame.getAttribute('data-markdown-block')));
461
485
  const action = button.getAttribute('data-markdown-action');
462
486
  if (block?.type === 'table' && action === 'table') {
463
487
  // Drawn again by its component, with its menu open
464
488
  woken.add(block.id);
489
+ } else if (block?.type === 'code' && action === 'preview') {
490
+ togglePreview(block.id, button);
465
491
  } else if (action === 'copy' || action === 'download') {
466
492
  // The block's own text. A block a plugin made, which the document does not know by
467
493
  // that id, gives what it shows
@@ -480,6 +506,28 @@
480
506
  }
481
507
  }
482
508
 
509
+ /**
510
+ * Shows a code block rendered, or as its source again. A block that `static` wrote is drawn
511
+ * by its component from then on, and the toggle it draws takes the focus the pressed one had.
512
+ */
513
+ function togglePreview(id: number, button: HTMLElement) {
514
+ if (previewed.has(id)) previewed.delete(id);
515
+ else previewed.add(id);
516
+ if (woken.has(id)) return;
517
+ const focused = window.document.activeElement === button;
518
+ woken.add(id);
519
+ void tick().then(() => {
520
+ if (button.isConnected || !root) return;
521
+ if (!focused && window.document.activeElement !== window.document.body) return;
522
+ const toggle = [
523
+ ...root.querySelectorAll<HTMLElement>(
524
+ `[data-markdown-block="${id}"] [data-markdown-action="preview"]`
525
+ )
526
+ ].find(mine);
527
+ toggle?.focus();
528
+ });
529
+ }
530
+
483
531
  /**
484
532
  * The arrow key on the button of a table that `static` wrote opens its menu, as it does on
485
533
  * the button a part draws.
@@ -488,7 +536,7 @@
488
536
  if (event.key !== 'ArrowDown' || !(event.target instanceof Element)) return;
489
537
  const button = event.target.closest('[data-markdown-action="table"]');
490
538
  const frame = button?.closest('[data-markdown-block]');
491
- if (!frame || !root?.contains(frame)) return;
539
+ if (!frame || !root || !mine(frame)) return;
492
540
  const block = blockById(Number(frame.getAttribute('data-markdown-block')));
493
541
  if (block?.type !== 'table') return;
494
542
  event.preventDefault();
@@ -499,7 +547,7 @@
499
547
  function taskTicked(event: Event) {
500
548
  const input = event.target instanceof HTMLInputElement ? event.target : null;
501
549
  const id = input?.getAttribute('data-markdown-task');
502
- if (!input || !id || !ontaskchange) return;
550
+ if (!input || !id || !ontaskchange || !mine(input)) return;
503
551
  const item = blockById(Number(id));
504
552
  if (item?.type !== 'listItem') return;
505
553
  const revert = () => (input.checked = item.checked === true);
@@ -520,7 +568,7 @@
520
568
  function linkClicked(event: MouseEvent) {
521
569
  const target = event.target instanceof Element ? event.target : null;
522
570
  const link = target?.closest('a[data-markdown-href]');
523
- if (!link || !root?.contains(link)) return;
571
+ if (!link || !root || !mine(link)) return;
524
572
  const href = link.getAttribute('data-markdown-href')!;
525
573
  if (event.type === 'click') {
526
574
  const plain = !(event.metaKey || event.ctrlKey || event.shiftKey || event.altKey);
@@ -625,6 +673,19 @@
625
673
  }
626
674
  },
627
675
  code: () => ({ lineNumbers, download }),
676
+ preview: (lang) => previewKind(lang, previews),
677
+ previewed: (id) => previewed.has(id),
678
+ nested: () => ({
679
+ gfm,
680
+ breaks,
681
+ singleTilde,
682
+ frontmatter,
683
+ plugins,
684
+ lineNumbers,
685
+ download,
686
+ labels,
687
+ headingOffset
688
+ }),
628
689
  static: () => finished && !streaming,
629
690
  kept: () => before,
630
691
  keep(runs) {
@@ -3,6 +3,7 @@ import type { ListItem } from '../../markdown/ast.js';
3
3
  import { type MarkdownLabels } from './labels.js';
4
4
  import type { MarkdownPlugin } from '../../markdown/plugin.js';
5
5
  import { type Sx } from '../../internal/sx.js';
6
+ import { type PreviewKind } from './preview.js';
6
7
  export type MarkdownProps = Omit<HTMLAttributes<HTMLDivElement>, 'children'> & {
7
8
  /** The Markdown text: all of it so far, while it streams. */
8
9
  value: string;
@@ -44,6 +45,14 @@ export type MarkdownProps = Omit<HTMLAttributes<HTMLDivElement>, 'children'> & {
44
45
  lineNumbers?: boolean | undefined;
45
46
  /** Whether a code block has a button that saves it as a file. Off by default. */
46
47
  download?: boolean | undefined;
48
+ /**
49
+ * Whether a finished code block tagged `markdown`, `md` or `html` has a toggle that shows
50
+ * it rendered: `true` for both, or the kinds to allow. Markdown is drawn by this
51
+ * component, with the same options and plugins; HTML in a sandboxed frame that runs no
52
+ * script, loads nothing from the network and cannot navigate. Blocks start as their
53
+ * source, and Copy copies the source. Off by default.
54
+ */
55
+ previews?: boolean | ReadonlyArray<PreviewKind> | undefined;
47
56
  /**
48
57
  * Shows a caret at the end of the text while it streams: `true` or `'block'` for a
49
58
  * block, `'circle'` for a dot. Off by default.
@@ -54,9 +54,10 @@
54
54
  if (html === null) {
55
55
  open = null;
56
56
  list.push(item);
57
- } else if (item.type === 'table') {
58
- // A table can be asked for as a part (its menu), and then it alone is drawn again:
59
- // what is written around it stays as it is, with the reader's selection in it
57
+ } else if (item.type === 'table' || (item.type === 'code' && md.preview(item.lang))) {
58
+ // A table can be asked for as a part (its menu), and a code block that can be shown
59
+ // rendered can be too, and then it alone is drawn again: what is written around it
60
+ // stays as it is, with the reader's selection in it
60
61
  open = null;
61
62
  list.push({ type: 'run', id: item.id, html });
62
63
  } else if (open) {