@ruckc/truss-markdown 1.48.0 → 1.49.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.
@@ -3,13 +3,14 @@
3
3
  import type { HTMLAttributes } from 'svelte/elements';
4
4
  import { parseMarkdown } from './parse.js';
5
5
  import MarkdownBlocks from './MarkdownBlocks.svelte';
6
- import { provide } from './context.js';
6
+ import { provide, type MarkdownLabels } from './context.js';
7
7
 
8
8
  let {
9
9
  text,
10
10
  headingOffset = 2,
11
11
  code,
12
12
  link,
13
+ labels,
13
14
  class: klass = '',
14
15
  ...rest
15
16
  }: Omit<HTMLAttributes<HTMLDivElement>, 'children' | 'class'> & {
@@ -21,11 +22,13 @@
21
22
  code?: Snippet<[{ lang: string; text: string }]>;
22
23
  /** Renders a link in place of the default `<a target="_blank" rel="noopener noreferrer">`, for client-side routing or a link preview. Only http, https and mailto links reach it; `children` is the link text. */
23
24
  link?: Snippet<[{ href: string; children: Snippet }]>;
25
+ /** Replaces the built-in texts (translation). Missing keys keep the defaults. */
26
+ labels?: Partial<MarkdownLabels>;
24
27
  /** Other attributes (`data-testid`, `id`, ...) go to the root `<div>`. `class` is added to it. */
25
28
  class?: string;
26
29
  } = $props();
27
30
 
28
- provide({ get headingOffset() { return headingOffset; }, get code() { return code; }, get link() { return link; } });
31
+ provide({ get labels() { return labels; }, get headingOffset() { return headingOffset; }, get code() { return code; }, get link() { return link; } });
29
32
  const nodes = $derived(parseMarkdown(text));
30
33
  </script>
31
34
 
@@ -1,5 +1,6 @@
1
1
  import type { Snippet } from 'svelte';
2
2
  import type { HTMLAttributes } from 'svelte/elements';
3
+ import { type MarkdownLabels } from './context.js';
3
4
  type $$ComponentProps = Omit<HTMLAttributes<HTMLDivElement>, 'children' | 'class'> & {
4
5
  /** The Markdown source: paragraphs, headings, bold/italic/strikethrough, inline code, fenced code blocks, lists (with task items), quotes, tables, rules, and http/https/mailto links including bare URLs. Images show their alt text and a link. HTML in it is shown as text; nothing is injected as markup. */
5
6
  text: string;
@@ -15,6 +16,8 @@ type $$ComponentProps = Omit<HTMLAttributes<HTMLDivElement>, 'children' | 'class
15
16
  href: string;
16
17
  children: Snippet;
17
18
  }]>;
19
+ /** Replaces the built-in texts (translation). Missing keys keep the defaults. */
20
+ labels?: Partial<MarkdownLabels>;
18
21
  /** Other attributes (`data-testid`, `id`, ...) go to the root `<div>`. `class` is added to it. */
19
22
  class?: string;
20
23
  };
@@ -3,15 +3,16 @@
3
3
  import MarkdownBlocks from './MarkdownBlocks.svelte';
4
4
  import MarkdownInlines from './MarkdownInlines.svelte';
5
5
  import MarkdownCode from './MarkdownCode.svelte';
6
- import { use } from './context.js';
6
+ import { use, MARKDOWN_DEFAULTS } from './context.js';
7
+ import { useLabels } from './labels.js';
7
8
 
8
9
  /** Renders block nodes (paragraph, heading, list, code block, blockquote, rule) with plain elements. */
9
10
  let { nodes }: { nodes: BlockNode[] } = $props();
10
11
  const ctx = use();
12
+ const L = useLabels('Markdown', MARKDOWN_DEFAULTS, () => ctx.labels);
11
13
 
12
14
  /** A scrolling region must be reachable by keyboard so it can be scrolled with the arrow keys. */
13
15
  const focusable = (node: HTMLElement) => void (node.tabIndex = 0);
14
- const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? '' : 's'}`;
15
16
  </script>
16
17
 
17
18
  {#each nodes as n}
@@ -32,7 +33,7 @@
32
33
  {:else if n.type === 'code'}
33
34
  <MarkdownCode lang={n.lang} text={n.text} />
34
35
  {:else if n.type === 'table'}
35
- <div class="table" role="region" {@attach focusable} aria-label={`Table, ${plural(n.head.length, 'column')}, ${plural(n.rows.length, 'row')}`}>
36
+ <div class="table" role="region" {@attach focusable} aria-label={L.table(n.head.length, n.rows.length)}>
36
37
  <table>
37
38
  <thead>
38
39
  <tr>{#each n.head as cell, k}<th scope="col" data-align={n.align[k] ?? undefined}><MarkdownInlines nodes={cell} /></th>{/each}</tr>
@@ -2,16 +2,18 @@
2
2
  import { onDestroy } from 'svelte';
3
3
  import { Button, Tooltip } from '@ruckc/truss-ui';
4
4
  import { highlight, resolveLanguage, type Token } from './highlight.js';
5
- import { use } from './context.js';
5
+ import { use, MARKDOWN_DEFAULTS } from './context.js';
6
+ import { useLabels } from './labels.js';
6
7
 
7
8
  /** A fenced code block: highlighted tokens inside a scrollable `<pre>`, a language label and a Copy button, or the caller's `code` snippet. */
8
9
  let { lang, text }: { lang: string; text: string } = $props();
9
10
  const ctx = use();
11
+ const L = useLabels('Markdown', MARKDOWN_DEFAULTS, () => ctx.labels);
10
12
 
11
13
  /** One flat run of tokens, with a plain "\n" token between lines. */
12
14
  const tokens = $derived(highlight(text, lang).flatMap((line, i): Token[] => (i ? [{ type: 'plain', text: '\n' }, ...line] : line)));
13
- const label = $derived(lang || 'text');
14
- let status = $state('');
15
+ const label = $derived(lang || L.plainText);
16
+ let status = $state<'' | 'copied' | 'failed'>('');
15
17
  let timer: ReturnType<typeof setTimeout>;
16
18
  onDestroy(() => clearTimeout(timer));
17
19
 
@@ -21,9 +23,9 @@
21
23
  async function copy() {
22
24
  try {
23
25
  await navigator.clipboard.writeText(text);
24
- status = 'Copied';
26
+ status = 'copied';
25
27
  } catch {
26
- status = 'Copy failed';
28
+ status = 'failed';
27
29
  }
28
30
  clearTimeout(timer);
29
31
  timer = setTimeout(() => (status = ''), 2000);
@@ -36,12 +38,12 @@
36
38
  <figure class="code" data-lang={resolveLanguage(lang) ?? 'plain'}>
37
39
  <figcaption>
38
40
  <span class="lang">{label}</span>
39
- <Tooltip text="Copy code">
40
- <Button variant="minimal" size="sm" icon={status === 'Copied' ? 'tick' : 'copy'} aria-label="Copy code" tooltip={false} onclick={copy} />
41
+ <Tooltip text={L.copyCode}>
42
+ <Button variant="minimal" size="sm" icon={status === 'copied' ? 'tick' : 'copy'} aria-label={L.copyCode} tooltip={false} onclick={copy} />
41
43
  </Tooltip>
42
- <span class="tr-visually-hidden" role="status" aria-live="polite">{status}</span>
44
+ <span class="tr-visually-hidden" role="status" aria-live="polite">{status === 'copied' ? L.copied : status === 'failed' ? L.copyFailed : ''}</span>
43
45
  </figcaption>
44
- <pre role="region" {@attach focusable} aria-label={`${label} code`}><code class={lang ? `language-${lang}` : undefined}
46
+ <pre role="region" {@attach focusable} aria-label={L.codeRegion(label)}><code class={lang ? `language-${lang}` : undefined}
45
47
  >{#each tokens as t}{#if t.type === 'plain'}{t.text}{:else}<span class="tok-{t.type}">{t.text}</span>{/if}{/each}</code></pre>
46
48
  </figure>
47
49
  {/if}
package/dist/context.d.ts CHANGED
@@ -1,6 +1,23 @@
1
1
  import { type Snippet } from 'svelte';
2
+ /** The built-in texts of the rendered Markdown (the component name for `configureLabels` and `setLabels` is `Markdown`). */
3
+ export type MarkdownLabels = {
4
+ /** Accessible name and tooltip of a code block's copy button. */
5
+ copyCode: string;
6
+ /** Live-region text after a successful copy. */
7
+ copied: string;
8
+ /** Live-region text when copying failed. */
9
+ copyFailed: string;
10
+ /** Name shown for a code block without a language, and used in its accessible name. */
11
+ plainText: string;
12
+ /** Accessible name of a code block's scrollable region: its language (or `plainText`). */
13
+ codeRegion: (language: string) => string;
14
+ /** Accessible name of a table's scrollable region: how many columns and rows it has. */
15
+ table: (columns: number, rows: number) => string;
16
+ };
17
+ export declare const MARKDOWN_DEFAULTS: MarkdownLabels;
2
18
  /** What a `Markdown` root hands to the nodes below it, read lazily so the overrides stay reactive. */
3
19
  export type MarkdownContext = {
20
+ readonly labels: Partial<MarkdownLabels> | undefined;
4
21
  readonly headingOffset: number;
5
22
  readonly code: Snippet<[{
6
23
  lang: string;
package/dist/context.js CHANGED
@@ -1,4 +1,12 @@
1
1
  import { getContext, setContext } from 'svelte';
2
+ export const MARKDOWN_DEFAULTS = {
3
+ copyCode: 'Copy code',
4
+ copied: 'Copied',
5
+ copyFailed: 'Copy failed',
6
+ plainText: 'text',
7
+ codeRegion: (language) => `${language} code`,
8
+ table: (columns, rows) => `Table, ${columns} ${columns === 1 ? 'column' : 'columns'}, ${rows} ${rows === 1 ? 'row' : 'rows'}`
9
+ };
2
10
  const KEY = Symbol('truss-markdown');
3
11
  export const provide = (c) => setContext(KEY, c);
4
12
  export const use = () => getContext(KEY);
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  export { default as Markdown } from './Markdown.svelte';
2
2
  export { parseMarkdown, parseInline, isSafeUrl } from './parse.js';
3
3
  export type { BlockNode, InlineNode, ListItemNode, TableAlign } from './parse.js';
4
+ export type { MarkdownLabels } from './context.js';
@@ -0,0 +1,6 @@
1
+ /** One label: a string, or a function for a string with values (`(n: number) => \`${n} selected\``). That covers plurals and word order without an ICU dependency. */
2
+ export type LabelValue = string | ((...args: never[]) => string);
3
+ /** @internal The labels of a component: `prop` over the context over `configureLabels` over `defaults`, read at the moment a key is used. Call during component initialisation (it reads context). */
4
+ export declare function useLabels<T extends object>(component: string, defaults: T, prop: () => Partial<T> | undefined): T;
5
+ /** @internal One app-wide label for code outside a component (no context there): `configureLabels` over `fallback`. */
6
+ export declare function labelFor<T extends LabelValue>(component: string, key: string, fallback: T): T;
package/dist/labels.js ADDED
@@ -0,0 +1,23 @@
1
+ import { getContext } from 'svelte';
2
+ const KEY = Symbol.for('@ruckc/truss-ui:labels');
3
+ const STATE = Symbol.for('@ruckc/truss-ui:labels-config');
4
+ // What `configureLabels` set for a component. Read-only here (no copy of this file has to create the state), and `Object(undefined)` is `{}`.
5
+ const config = (component) => Object(Object(globalThis[STATE])[component]);
6
+ // The strongest defined value wins (layers run from the weakest to the strongest). This reader is written without branches on purpose
7
+ // (`filter`, `Object(x)`, no `?.` / `??` / `if`): it is copied into every package, and V8 coverage counts each short-circuit as a branch,
8
+ // so a copy would need a test under every combination of context and config to reach the per-file coverage floor.
9
+ const none = () => undefined;
10
+ const pick = (...layers) => layers.filter((v) => v !== undefined).at(-1);
11
+ /** @internal The labels of a component: `prop` over the context over `configureLabels` over `defaults`, read at the moment a key is used. Call during component initialisation (it reads context). */
12
+ export function useLabels(component, defaults, prop) {
13
+ const lookup = [getContext(KEY), none].filter(Boolean)[0];
14
+ const out = {};
15
+ for (const k of Object.keys(defaults))
16
+ Object.defineProperty(out, k, { enumerable: true, get: () => pick(labelFor(component, k, defaults[k]), Object(lookup(component))[k], Object(prop())[k]) });
17
+ return out;
18
+ }
19
+ /** @internal One app-wide label for code outside a component (no context there): `configureLabels` over `fallback`. */
20
+ export function labelFor(component, key, fallback) {
21
+ return pick(fallback, config(component)[key]);
22
+ }
23
+ // </reader>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ruckc/truss-markdown",
3
- "version": "1.48.0",
3
+ "version": "1.49.0",
4
4
  "description": "A safe Markdown renderer for Truss UI: a typed AST rendered with Svelte components, never HTML strings",
5
5
  "type": "module",
6
6
  "license": "MIT",