@diegopluna/narvi 0.5.9 → 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 (33) hide show
  1. package/dist/components/markdown/Markdown.svelte +68 -7
  2. package/dist/components/markdown/Markdown.svelte.d.ts +9 -0
  3. package/dist/components/markdown/MarkdownBlocks.svelte +4 -3
  4. package/dist/components/markdown/MarkdownCode.svelte +108 -9
  5. package/dist/components/markdown/MarkdownCode.svelte.d.ts +5 -1
  6. package/dist/components/markdown/MarkdownHtmlPreview.svelte +186 -0
  7. package/dist/components/markdown/MarkdownHtmlPreview.svelte.d.ts +11 -0
  8. package/dist/components/markdown/MarkdownPreview.svelte +17 -0
  9. package/dist/components/markdown/MarkdownPreview.svelte.d.ts +6 -0
  10. package/dist/components/markdown/MarkdownTable.svelte +61 -4
  11. package/dist/components/markdown/context.d.ts +21 -0
  12. package/dist/components/markdown/labels.d.ts +12 -0
  13. package/dist/components/markdown/labels.js +5 -0
  14. package/dist/components/markdown/preview.d.ts +9 -0
  15. package/dist/components/markdown/preview.js +14 -0
  16. package/dist/components/markdown/static.d.ts +2 -0
  17. package/dist/components/markdown/static.js +5 -1
  18. package/dist/components/markdown/table-image.d.ts +15 -0
  19. package/dist/components/markdown/table-image.js +342 -0
  20. package/dist/components/message/MessageAction.svelte +17 -2
  21. package/dist/components/message/MessageAction.svelte.d.ts +7 -0
  22. package/dist/markdown/html.d.ts +3 -1
  23. package/dist/markdown/html.js +6 -0
  24. package/dist/markdown/index.d.ts +2 -2
  25. package/dist/markdown/index.js +2 -2
  26. package/dist/markdown/table.d.ts +20 -1
  27. package/dist/markdown/table.js +111 -0
  28. package/package.json +1 -1
  29. package/skills/building-ui/SKILL.md +1 -1
  30. package/skills/markdown/SKILL.md +24 -5
  31. package/skills/setup/SKILL.md +1 -1
  32. package/skills/styling/SKILL.md +1 -1
  33. package/skills/theming/SKILL.md +1 -1
@@ -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) {
@@ -8,6 +8,10 @@
8
8
  would cost more than the rest of the reply together. The markup is Narvi's own: a
9
9
  `<span>` with one of its own classes, around text that has been escaped (`tokensHtml`).
10
10
  Nothing of the code's text is ever read as markup.
11
+
12
+ With `previews`, a finished Markdown or HTML block can be shown rendered: Markdown by Narvi's
13
+ own Markdown, HTML in a sandboxed frame that runs no script. What draws either is loaded the
14
+ first time a block is shown so.
11
15
  -->
12
16
  <script lang="ts" module>
13
17
  import * as stylex from '@stylexjs/stylex';
@@ -19,7 +23,9 @@
19
23
  import { attrs, classes } from '../../internal/sx.js';
20
24
  import { escapeHtml } from '../../markdown/html.js';
21
25
  import { colors, font, radius } from '../../tokens.stylex.js';
22
- import { actionHtml } from '../message/MessageAction.svelte';
26
+ import { actionClass, actionHtml } from '../message/MessageAction.svelte';
27
+ import type { Component } from 'svelte';
28
+ import type { PreviewKind } from './preview.js';
23
29
  import { copyHtml } from '../message/MessageCopy.svelte';
24
30
  import { getMarkdownContext } from './context.js';
25
31
  import { showHidden } from './hidden.js';
@@ -128,9 +134,41 @@
128
134
  },
129
135
  barePre: { paddingBlockStart: '0.75rem', paddingInlineEnd: '2.5rem' },
130
136
  actions: { display: 'inline-flex', flexShrink: 0, gap: '0.125rem' },
131
- copy: { flexShrink: 0 }
137
+ copy: { flexShrink: 0 },
138
+ // Shown rendered, the block is a page set into the reply: an edge and no fill, so the
139
+ // code blocks in it keep their own well
140
+ rendered: {
141
+ backgroundColor: 'transparent',
142
+ boxShadow: `inset 0 0 0 1px ${colors.border}`
143
+ },
144
+ preview: { minWidth: 0, paddingInline: '0.75rem', paddingBlockEnd: '0.75rem' }
132
145
  });
133
146
 
147
+ /** What draws each kind of block rendered, once it has loaded: one for the whole page. */
148
+ const previewParts: Partial<Record<PreviewKind, Component<{ source: string }>>> = {};
149
+ const loadingParts: Partial<Record<PreviewKind, Promise<Component<{ source: string }>>>> = {};
150
+
151
+ function loadPreview(kind: PreviewKind): Promise<Component<{ source: string }>> {
152
+ loadingParts[kind] ??= (
153
+ kind === 'markdown'
154
+ ? import('./MarkdownPreview.svelte')
155
+ : import('./MarkdownHtmlPreview.svelte')
156
+ ).then(
157
+ (module) => (previewParts[kind] = module.default),
158
+ (cause: unknown) => {
159
+ // Asked again the next time, after it failed to load
160
+ delete loadingParts[kind];
161
+ throw cause;
162
+ }
163
+ );
164
+ return loadingParts[kind];
165
+ }
166
+
167
+ /** The name of a block's preview toggle: the same whether it is pressed or not. */
168
+ function previewLabel(title: string | null, labels: { showRendered: string }): string {
169
+ return title ? `${labels.showRendered}: ${title}` : labels.showRendered;
170
+ }
171
+
134
172
  /** Token kinds a highlighter names, and the colours Narvi gives them. */
135
173
  const kinds = stylex.create({
136
174
  keyword: { color: colors.codeLiteral },
@@ -321,11 +359,22 @@
321
359
  */
322
360
  function actionsHtml(
323
361
  title: string | null,
324
- labels: { copyCode: string; downloadCode: string },
325
- download: boolean
362
+ labels: { copyCode: string; downloadCode: string; showRendered: string },
363
+ download: boolean,
364
+ preview = false
326
365
  ): string {
327
366
  const label = (words: string) => escapeHtml(title ? `${words}: ${title}` : words);
328
367
  return (
368
+ // A block that can be shown rendered starts as its source. Pressed, the document draws
369
+ // it by its component, which holds which of the two it shows
370
+ (preview
371
+ ? actionHtml({
372
+ label: escapeHtml(previewLabel(title, labels)),
373
+ attributes: ' aria-pressed="false" data-markdown-action="preview"',
374
+ bare: true,
375
+ inner: glyphHtml('eye')
376
+ })
377
+ : '') +
329
378
  (download
330
379
  ? actionHtml({
331
380
  label: label(labels.downloadCode),
@@ -350,10 +399,12 @@
350
399
  export function codeHtml(
351
400
  node: CodeBlock,
352
401
  options: {
353
- labels: { copyCode: string; downloadCode: string };
402
+ labels: { copyCode: string; downloadCode: string; showRendered: string };
354
403
  highlight: Highlighter | null;
355
404
  lineNumbers: boolean;
356
405
  download: boolean;
406
+ /** Whether the block has a toggle that shows it rendered. */
407
+ preview?: boolean | undefined;
357
408
  }
358
409
  ): string {
359
410
  const lang = node.lang;
@@ -393,7 +444,7 @@
393
444
  (named || escapeHtml(lang ?? '')) +
394
445
  '</span>' +
395
446
  `<span class="${classes(styles.actions)}">` +
396
- actionsHtml(title, options.labels, options.download) +
447
+ actionsHtml(title, options.labels, options.download, options.preview) +
397
448
  '</span></div>' +
398
449
  `<pre dir="ltr" data-markdown-scroll class="${classes(styles.pre, lang === null && styles.laidOut, lang === null && styles.wrap, bare && styles.barePre, numbered && styles.numbered)}"${lang === null ? '' : ` style="--narvi-code-lines: ${countLines(code)};"`}>` +
399
450
  gutter +
@@ -418,6 +469,31 @@
418
469
  const title = $derived(named ? codeTitle(node) : null);
419
470
  const bare = $derived(title === null && lang === null);
420
471
 
472
+ // A Markdown or HTML block can be shown rendered once its fence has closed. It starts as its
473
+ // source; which it shows is kept by the document, so the static path's button can say it
474
+ const kind = $derived(live ? null : md.preview(node.lang));
475
+ const rendered = $derived(kind !== null && md.previewed(node.id));
476
+ let Preview = $state<Component<{ source: string }> | null>(null);
477
+ $effect(() => {
478
+ if (!rendered || !kind) return;
479
+ const part = previewParts[kind];
480
+ if (part) {
481
+ Preview = part;
482
+ return;
483
+ }
484
+ let gone = false;
485
+ loadPreview(kind).then(
486
+ (loaded) => {
487
+ if (!gone) Preview = loaded;
488
+ },
489
+ // What could not load leaves the source showing
490
+ () => {}
491
+ );
492
+ return () => {
493
+ gone = true;
494
+ };
495
+ });
496
+
421
497
  // A block that streams is highlighted as it arrives: the stream keeps its place, so only
422
498
  // new lines are tokenized, and the lines already drawn are never drawn again
423
499
  let session: {
@@ -557,7 +633,13 @@
557
633
  data-markdown-code
558
634
  data-markdown-block={node.id}
559
635
  data-open={live || undefined}
560
- {...attrs([prose.block, styles.frame, bare && styles.bare, enter && prose.enter])}
636
+ {...attrs([
637
+ prose.block,
638
+ styles.frame,
639
+ bare && styles.bare,
640
+ rendered && Preview && styles.rendered,
641
+ enter && prose.enter
642
+ ])}
561
643
  >
562
644
  <!-- Always there, so the code does not move down when the fence closes and the button arrives -->
563
645
  <div data-markdown-chrome {...attrs([styles.header, bare && styles.bareHeader])}>
@@ -570,13 +652,30 @@
570
652
  <!-- Markup, pressed through the document's root: see `actionsHtml` -->
571
653
  <!-- eslint-disable svelte/no-at-html-tags -->
572
654
  <span {...attrs([styles.actions])}
573
- >{@html actionsHtml(title, md.labels, md.code().download)}</span
655
+ >{#if kind}<!-- An element of its own, which stays as it is pressed, so focus stays on it --><button
656
+ type="button"
657
+ aria-label={previewLabel(title, md.labels)}
658
+ aria-pressed={rendered}
659
+ data-slot="message-action"
660
+ data-markdown-action="preview"
661
+ class={actionClass({ pressed: rendered })}>{@html glyphHtml('eye')}</button
662
+ >{/if}{@html actionsHtml(title, md.labels, md.code().download)}</span
574
663
  >
575
664
  <!-- eslint-enable svelte/no-at-html-tags -->
576
665
  {/if}
577
666
  </div>
667
+ {#if rendered && Preview}
668
+ <div data-markdown-preview={kind} {...attrs([styles.preview])}>
669
+ <Preview source={code} />
670
+ </div>
671
+ {:else}
672
+ {@render source()}
673
+ {/if}
674
+ </div>
675
+
676
+ {#snippet source()}
578
677
  <!-- Narvi's own markup around escaped text: see `tokensHtml` -->
579
678
  <!-- eslint-disable svelte/no-at-html-tags -->
580
679
  <!-- prettier-ignore -->
581
680
  <pre dir="ltr" use:scrollable style:--narvi-code-lines={lineCount} {...attrs([styles.pre, (live || node.lang === null) && styles.laidOut, node.lang === null && styles.wrap, bare && styles.barePre, numbers !== null && styles.numbered])}>{#if numbers}<span aria-hidden="true" data-markdown-chrome {...attrs([styles.numbers])}>{#each numbers as group, g (g)}<span {...attrs([styles.lines])}>{group}</span>{/each}</span>{/if}<code {...attrs([styles.code, numbers !== null && styles.numberedCode])}>{#if view.kind === 'text'}{view.text}{:else if view.kind === 'whole'}{@html view.html}{:else}{#each view.groups as group, g (g)}<span data-markdown-lines {...attrs([styles.lines])}>{#each group.lines as line, i (i)}{@html i > 0 ? NEWLINE + line : line}{/each}{#if g === view.groups.length - 1}{@html view.tail}{:else}{NEWLINE}{/if}</span>{/each}{/if}</code></pre>
582
- </div>
681
+ {/snippet}
@@ -1,5 +1,6 @@
1
1
  import type { CodeBlock } from '../../markdown/ast.js';
2
2
  import type { Highlighter } from '../../markdown/plugin.js';
3
+ import type { Component } from 'svelte';
3
4
  export type MarkdownCodeProps = {
4
5
  node: CodeBlock;
5
6
  enter?: boolean | undefined;
@@ -13,11 +14,14 @@ export declare function codeHtml(node: CodeBlock, options: {
13
14
  labels: {
14
15
  copyCode: string;
15
16
  downloadCode: string;
17
+ showRendered: string;
16
18
  };
17
19
  highlight: Highlighter | null;
18
20
  lineNumbers: boolean;
19
21
  download: boolean;
22
+ /** Whether the block has a toggle that shows it rendered. */
23
+ preview?: boolean | undefined;
20
24
  }): string;
21
- declare const MarkdownCode: import("svelte").Component<MarkdownCodeProps, {}, "">;
25
+ declare const MarkdownCode: Component<MarkdownCodeProps, {}, "">;
22
26
  type MarkdownCode = ReturnType<typeof MarkdownCode>;
23
27
  export default MarkdownCode;
@@ -0,0 +1,186 @@
1
+ <!--
2
+ An HTML code block, shown rendered, in a frame of its own. Loaded the first time a block is
3
+ shown rendered.
4
+
5
+ The frame is sandboxed with `allow-same-origin` and nothing else: no script in it runs, it
6
+ cannot submit a form, open a window or navigate the page, and this page can still reach into
7
+ it to measure it and to take its link clicks. What goes into it is read first by the
8
+ browser's inert parser, which runs nothing, and loses what could navigate it or reach the
9
+ network on its own: a `<meta http-equiv>` (a refresh) and a `<base>`. A content security
10
+ policy then lets it load nothing from the network, so a preview cannot tell a server it was
11
+ seen: pictures and fonts written into the HTML itself (`data:`) still show.
12
+
13
+ Every link in it is made to open a new window, which the sandbox refuses, so the browser
14
+ itself follows none of them, in the frame or out of it. Where this page's listeners run in
15
+ the frame (Chromium and Firefox), a link the document's link policy allows is offered to the
16
+ app's `open`, and otherwise opens in a new tab, as a link in the reply would. WebKit runs no
17
+ listener in a frame that runs no script, so in Safari a link in a preview does nothing.
18
+
19
+ The frame is as tall as what is in it, up to a limit, past which it scrolls. It takes the
20
+ reply's colour scheme, text colour and face, which the HTML's own styles override.
21
+ -->
22
+ <script lang="ts" module>
23
+ import * as stylex from '@stylexjs/stylex';
24
+ import { attrs } from '../../internal/sx.js';
25
+ import type { Link } from '../../markdown/ast.js';
26
+ import { colors } from '../../tokens.stylex.js';
27
+ import { getMarkdownContext } from './context.js';
28
+
29
+ /** What the frame may load: nothing from the network, nothing that runs. */
30
+ const POLICY =
31
+ "default-src 'none'; style-src 'unsafe-inline'; img-src data: blob:; font-src data:; " +
32
+ "media-src data: blob:; form-action 'none'; base-uri 'none'";
33
+
34
+ const BASE_ID = 'narvi-preview-base';
35
+
36
+ const styles = stylex.create({
37
+ frame: {
38
+ display: 'block',
39
+ width: '100%',
40
+ // Until it has been measured, about the height of a few lines
41
+ height: '6rem',
42
+ maxHeight: 'min(32rem, 70vh)',
43
+ borderWidth: 0,
44
+ borderRadius: 0,
45
+ backgroundColor: 'transparent',
46
+ // The theme's text colour, read into the frame. A change of theme changes it, and the
47
+ // change is heard as the end of this transition, which is not seen: it moves nothing
48
+ color: colors.text,
49
+ transitionProperty: 'color',
50
+ transitionDuration: '1ms'
51
+ }
52
+ });
53
+
54
+ /** The look the frame starts from: the reply's, under anything the HTML says. */
55
+ function baseCss(frame: HTMLIFrameElement): string {
56
+ const style = getComputedStyle(frame);
57
+ const scheme = /dark/.test(style.colorScheme)
58
+ ? /light/.test(style.colorScheme)
59
+ ? // Both: the one the reply is drawn in now, which its text colour gives away
60
+ brightness(style.color) > 0.5
61
+ ? 'dark'
62
+ : 'light'
63
+ : 'dark'
64
+ : 'light';
65
+ const text = style.color.replace(/[<>;{}]/g, '');
66
+ const face = style.fontFamily.replace(/[<>;{}]/g, '');
67
+ return (
68
+ `:root{color-scheme:${scheme};color:${text};font-family:${face};line-height:1.5}` +
69
+ ':where(body){margin:0;overflow-wrap:break-word}' +
70
+ ':where(img,video,svg){max-width:100%;height:auto}'
71
+ );
72
+ }
73
+
74
+ /** How light a computed colour is, 0 to 1, by its sRGB channels. */
75
+ function brightness(color: string): number {
76
+ const channels = /rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)/.exec(color);
77
+ if (!channels) return 0;
78
+ const [r, g, b] = channels.slice(1).map(Number) as [number, number, number];
79
+ return (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
80
+ }
81
+
82
+ /**
83
+ * The HTML as the frame's document: read by the inert parser, without what could navigate
84
+ * the frame or point its addresses elsewhere, with the policy first in its head.
85
+ */
86
+ export function previewDocument(source: string, css: string): string {
87
+ const doc = new DOMParser().parseFromString(source, 'text/html');
88
+ for (const element of doc.querySelectorAll('meta[http-equiv], base, script')) element.remove();
89
+ // A new window, which the sandbox refuses: a link that is followed goes nowhere
90
+ for (const link of doc.querySelectorAll('a, area')) link.setAttribute('target', '_blank');
91
+ const policy = doc.createElement('meta');
92
+ policy.httpEquiv = 'Content-Security-Policy';
93
+ policy.content = POLICY;
94
+ const charset = doc.createElement('meta');
95
+ charset.setAttribute('charset', 'utf-8');
96
+ const base = doc.createElement('style');
97
+ base.id = BASE_ID;
98
+ base.textContent = css;
99
+ doc.head.prepend(charset, policy, base);
100
+ return `<!doctype html>${doc.documentElement.outerHTML}`;
101
+ }
102
+ </script>
103
+
104
+ <script lang="ts">
105
+ let { source }: { source: string } = $props();
106
+
107
+ const md = getMarkdownContext();
108
+ let frame = $state<HTMLIFrameElement | null>(null);
109
+ let srcdoc = $state<string | undefined>(undefined);
110
+ let height = $state<number | undefined>(undefined);
111
+
112
+ // Written once the frame is on the page, whose look it takes
113
+ $effect(() => {
114
+ if (frame) srcdoc = previewDocument(source, baseCss(frame));
115
+ });
116
+
117
+ /** A link in the frame, pressed: never followed there, offered to the app or a new tab. */
118
+ function follow(event: MouseEvent) {
119
+ const target = event.target as Element | null;
120
+ const link = target?.closest?.('a[href], area[href]');
121
+ if (!link) return;
122
+ const raw = link.getAttribute('href') ?? '';
123
+ // A place in the frame's own page is the frame's own business
124
+ if (raw.startsWith('#')) return;
125
+ event.preventDefault();
126
+ const node: Link = { type: 'link', url: raw, title: null, kind: 'inline', children: [] };
127
+ const href = md.links.href(raw, node);
128
+ if (href === null || href.startsWith('#')) return;
129
+ md.links.open?.(href, event);
130
+ if (event.defaultPrevented && md.links.open) return;
131
+ if (event.type === 'click' && md.links.external(href))
132
+ window.open(href, '_blank', 'noopener,noreferrer');
133
+ }
134
+
135
+ function measure(doc: Document) {
136
+ // The document's own height, not the frame's: the root is as tall as what is in it
137
+ const content = Math.ceil(doc.documentElement.getBoundingClientRect().height);
138
+ if (content > 0) height = content;
139
+ }
140
+
141
+ let watching: (() => void) | null = null;
142
+
143
+ function loaded() {
144
+ watching?.();
145
+ watching = null;
146
+ const doc = frame?.contentDocument;
147
+ if (!doc?.documentElement) return;
148
+ // Listened to from here: these run although nothing in the frame may
149
+ const capture = { capture: true };
150
+ const submit = (event: Event) => event.preventDefault();
151
+ doc.addEventListener('click', follow, capture);
152
+ doc.addEventListener('auxclick', follow, capture);
153
+ doc.addEventListener('submit', submit, capture);
154
+ const observer = new ResizeObserver(() => measure(doc));
155
+ observer.observe(doc.documentElement);
156
+ if (doc.body) observer.observe(doc.body);
157
+ measure(doc);
158
+ watching = () => {
159
+ observer.disconnect();
160
+ doc.removeEventListener('click', follow, capture);
161
+ doc.removeEventListener('auxclick', follow, capture);
162
+ doc.removeEventListener('submit', submit, capture);
163
+ };
164
+ }
165
+
166
+ /** The theme changed: the frame's base look follows, in place, without loading it again. */
167
+ function restyle() {
168
+ const base = frame?.contentDocument?.getElementById(BASE_ID);
169
+ if (frame && base) base.textContent = baseCss(frame);
170
+ }
171
+
172
+ $effect(() => () => watching?.());
173
+ </script>
174
+
175
+ <iframe
176
+ bind:this={frame}
177
+ title={md.labels.htmlPreview}
178
+ sandbox="allow-same-origin"
179
+ referrerpolicy="no-referrer"
180
+ {srcdoc}
181
+ onload={loaded}
182
+ ontransitionend={restyle}
183
+ data-markdown-html-preview
184
+ style:height={height === undefined ? undefined : `${height}px`}
185
+ {...attrs([styles.frame])}
186
+ ></iframe>
@@ -0,0 +1,11 @@
1
+ /**
2
+ * The HTML as the frame's document: read by the inert parser, without what could navigate
3
+ * the frame or point its addresses elsewhere, with the policy first in its head.
4
+ */
5
+ export declare function previewDocument(source: string, css: string): string;
6
+ type $$ComponentProps = {
7
+ source: string;
8
+ };
9
+ declare const MarkdownHtmlPreview: import("svelte").Component<$$ComponentProps, {}, "">;
10
+ type MarkdownHtmlPreview = ReturnType<typeof MarkdownHtmlPreview>;
11
+ export default MarkdownHtmlPreview;
@@ -0,0 +1,17 @@
1
+ <!--
2
+ A Markdown code block, shown rendered: by Narvi's own Markdown, with the options and plugins
3
+ of the document it is in. Nothing in it streams, its tasks cannot be ticked (they are not
4
+ the document's text), and a Markdown block inside it shows as its source, so a block can't
5
+ be shown rendered inside itself. Loaded the first time a block is shown rendered.
6
+ -->
7
+ <script lang="ts">
8
+ import { getMarkdownContext } from './context.js';
9
+ import Markdown from './Markdown.svelte';
10
+
11
+ let { source }: { source: string } = $props();
12
+
13
+ const md = getMarkdownContext();
14
+ const options = $derived(md.nested());
15
+ </script>
16
+
17
+ <Markdown value={source} {...options} previews={false} />
@@ -0,0 +1,6 @@
1
+ type $$ComponentProps = {
2
+ source: string;
3
+ };
4
+ declare const MarkdownPreview: import("svelte").Component<$$ComponentProps, {}, "">;
5
+ type MarkdownPreview = ReturnType<typeof MarkdownPreview>;
6
+ export default MarkdownPreview;