@ruckc/truss-code 1.50.1 → 1.51.1

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.
package/README.md CHANGED
@@ -29,7 +29,7 @@ npm install monaco-editor # only if you use the editors
29
29
 
30
30
  ## Strict CSP
31
31
 
32
- Under `style-src 'self' 'nonce-…'` (no `'unsafe-inline'`) the editors work once a nonce is configured: `setCspNonce(nonce)` from `@ruckc/truss-ui` in the root layout, `configureCsp({ nonce })`, or `<meta property="csp-nonce" nonce="…">`. Monaco 0.57 has no nonce support of its own, so with a nonce present the package wraps `document.createElement('style')` (the element gets the nonce), `setAttribute('style', …)` (becomes a CSSOM assignment) and `innerHTML` / `insertAdjacentHTML` strings that contain `style="…"` (parsed in a policy-free document, with each style attribute moved to the CSSOM). Without a nonce nothing is wrapped. Monaco's own CSS is a normal stylesheet in a production build; in Vite dev, Vite reads its nonce from the same meta tag (or `html.cspNonce`). The Truss documentation has a Content Security Policy page with the details.
32
+ Under `style-src 'self' 'nonce-…'` (no `'unsafe-inline'`) the editors work once a nonce is configured: `setCspNonce(nonce)` from `@ruckc/truss-ui` in the root layout, `configureCsp({ nonce })`, or `<meta property="csp-nonce" nonce="…">`. Monaco 0.57 has no nonce support of its own, so with a nonce present the package wraps four page-wide functions, and applies the conversion only to Monaco's own DOM (an editor root, `.monaco-editor` / `.monaco-diff-editor`, or the `.context-view` Monaco appends to `body`): `setAttribute('style', …)` becomes a CSSOM assignment, and `innerHTML` / `insertAdjacentHTML` strings that contain `style="…"` are parsed in a policy-free document with each style attribute moved to the CSSOM. Monaco also fills a detached scratch element before moving the nodes in; that is converted only for Monaco's own line markup (a `<div style="top:…` start and layout-only declarations such as `top`, `left`, `width`, `height`, `line-height`). Every other call, such as injected `<b style="…">` markup elsewhere on the page, takes the browser's native path and is blocked by the policy as usual. `document.createElement('style')` gives the element the nonce and is not scoped: it cannot be told apart from page code's, so the residual risk is limited to script that is already running (which `script-src` governs). SvelteKit's own `#svelte-announcer` template is converted too, as an exact-string exception. Without a nonce nothing is wrapped. Monaco's own CSS is a normal stylesheet in a production build; in Vite dev, Vite reads its nonce from the same meta tag (or `html.cspNonce`). The Truss documentation has a Content Security Policy page with the details.
33
33
 
34
34
  ## License
35
35
 
@@ -14,6 +14,7 @@
14
14
 
15
15
  <script lang="ts">
16
16
  import { useLabels } from './labels.js';
17
+ import { scrollFocus } from './scrollfocus.js';
17
18
  import { csstext } from './cssvars.js';
18
19
  import SsrStyle from './SsrStyle.svelte';
19
20
  import { prepareMonacoCsp } from './monaco-csp.js';
@@ -164,8 +165,7 @@
164
165
 
165
166
  {#snippet block()}
166
167
  <SsrStyle {uid} rules={{ '': style }} />
167
- <!-- svelte-ignore a11y_no_noninteractive_tabindex -->
168
- <pre {...rest} bind:this={el} data-sv={uid} role="region" class={['cb', klass]} class:wrap class:nums={lineNumbers} {@attach csstext(() => style)} {onscroll} tabindex="0" aria-label={label ?? L.code}><code>{#each lines as segs, i (i)}<span class="ln">{#if lineNumbers}<span class="no" aria-hidden="true">{i + 1}</span>{/if}<span class="tx">{#each segs as s}<span class={s.role ? `s-${s.role}` : undefined}>{s.text}</span>{/each}{'\n'}</span></span>{/each}</code></pre>
168
+ <pre {...rest} bind:this={el} data-sv={uid} class={['cb', klass]} class:wrap class:nums={lineNumbers} {@attach csstext(() => style)} {onscroll} {@attach scrollFocus(() => ({ label: label ?? L.code }))}><code>{#each lines as segs, i (i)}<span class="ln">{#if lineNumbers}<span class="no" aria-hidden="true">{i + 1}</span>{/if}<span class="tx">{#each segs as s}<span class={s.role ? `s-${s.role}` : undefined}>{s.text}</span>{/each}{'\n'}</span></span>{/each}</code></pre>
169
169
  {/snippet}
170
170
 
171
171
  {#if copy}
@@ -215,6 +215,7 @@
215
215
 
216
216
  <script lang="ts">
217
217
  import { useLabels } from './labels.js';
218
+ import { scrollFocus } from './scrollfocus.js';
218
219
  import { csstext } from './cssvars.js';
219
220
  import SsrStyle from './SsrStyle.svelte';
220
221
  import { prepareMonacoCsp } from './monaco-csp.js';
@@ -615,6 +616,7 @@
615
616
  {/if}
616
617
 
617
618
  {#if showTable && !whole}
619
+ <!-- the keyboard entry point of the merge (n / p / F7 are handled for focus anywhere inside it), so it stays a tab stop even when it does not scroll -->
618
620
  <!-- svelte-ignore a11y_no_noninteractive_tabindex -->
619
621
  <div class="scroll" role="region" aria-label={L.versionsRegion} tabindex="0">
620
622
  <table class="tbl" data-show={narrow ? tab : 'all'} aria-label={name ? L.versionsOf(name) : L.versions}>
@@ -670,8 +672,7 @@
670
672
  {/if}
671
673
 
672
674
  {#if showResult && !whole}
673
- <!-- svelte-ignore a11y_no_noninteractive_tabindex -->
674
- <div class="result" role="region" aria-label={L.result} tabindex="0">
675
+ <div class="result" {@attach scrollFocus(() => ({ label: L.result }))}>
675
676
  <div class="rhead" aria-hidden="true">{L.result}</div>
676
677
  <table class="tbl res" aria-label={name ? L.mergedOf(name) : L.merged}>
677
678
  <colgroup><col class="c-no" /><col class="c-sym" /><col class="c-code" /></colgroup>
@@ -729,7 +730,7 @@
729
730
  .mv[data-height='fill'], .mv[data-height='fixed'] { display: flex; flex-direction: column; min-height: 0; }
730
731
  .mv[data-height='fill'] { height: 100%; }
731
732
  .mv[data-height='fill'] .scroll, .mv[data-height='fixed'] .scroll, .mv[data-height='fill'] .result, .mv[data-height='fixed'] .result { max-height: none; min-height: 0; flex: 1 1 auto; }
732
- .scroll:focus-visible, .result:focus-visible { outline: none; box-shadow: inset var(--tr-focus-ring); }
733
+ .scroll:focus-visible, .result:focus-visible { outline: none; box-shadow: var(--tr-focus-ring-inset); }
733
734
  .tbl { border-collapse: collapse; width: 100%; table-layout: fixed; font-family: var(--tr-font-mono); font-size: var(--mv-font, var(--tr-text-sm)); line-height: 1.5; tab-size: 4; }
734
735
  .c-no { width: 5ch; } .c-sym { width: 3ch; }
735
736
  th { position: sticky; top: 0; z-index: 1; text-align: left; padding: var(--tr-space-1) var(--tr-space-2); background: var(--tr-surface-container); border-bottom: 1px solid var(--tr-outline-variant); font-family: var(--tr-font-sans); font-size: var(--tr-text-sm); }
@@ -12,6 +12,7 @@
12
12
 
13
13
  <script lang="ts">
14
14
  import { useLabels } from './labels.js';
15
+ import { scrollFocus } from './scrollfocus.js';
15
16
  import { csstext } from './cssvars.js';
16
17
  import SsrStyle from './SsrStyle.svelte';
17
18
  const uid = $props.id();
@@ -48,8 +49,7 @@
48
49
  </script>
49
50
 
50
51
  <SsrStyle {uid} rules={{ '': style ?? '' }} />
51
- <!-- svelte-ignore a11y_no_noninteractive_tabindex -->
52
- <pre {...rest} data-sv={uid} role="region" class="pt" class:wrap class:nums={lineNumbers} {@attach csstext(() => style)} tabindex="0" aria-label={label ?? L.patchText}><code>{#each lines as l, i (i)}<span class={"ln " + l.kind} data-kind={l.kind}>{#if lineNumbers}<span class="no" aria-hidden="true">{i + 1}</span>{/if}<span class="sym">{#if l.mark}<span aria-hidden="true">{l.mark.sym}</span><span class="vh">{l.mark.sr + ": "}</span>{/if}</span><span class="tx">{l.body + '\n'}</span></span>{/each}</code></pre>
52
+ <pre {...rest} data-sv={uid} class="pt" class:wrap class:nums={lineNumbers} {@attach csstext(() => style)} {@attach scrollFocus(() => ({ label: label ?? L.patchText }))}><code>{#each lines as l, i (i)}<span class={"ln " + l.kind} data-kind={l.kind}>{#if lineNumbers}<span class="no" aria-hidden="true">{i + 1}</span>{/if}<span class="sym">{#if l.mark}<span aria-hidden="true">{l.mark.sym}</span><span class="vh">{l.mark.sr + ": "}</span>{/if}</span><span class="tx">{l.body + '\n'}</span></span>{/each}</code></pre>
53
53
 
54
54
  <style>
55
55
  .pt {
@@ -3,13 +3,21 @@
3
3
  * elements with `document.createElement('style')`, sets `style` attributes with `setAttribute('style', …)`, and renders every text line
4
4
  * through `innerHTML` / `insertAdjacentHTML` strings that carry `style="top:…"`. All three are blocked by such a policy.
5
5
  *
6
- * `installMonacoCsp(nonce)` wraps those entry points (only once a nonce is known; without one nothing is touched):
7
- * - `document.createElement('style')` gives the element the nonce before Monaco fills or inserts it;
8
- * - `Element.setAttribute('style', v)` becomes `el.style.cssText = v` (CSSOM, which CSP allows);
9
- * - `innerHTML = …` and `insertAdjacentHTML(…)` strings holding `style="…"` are parsed in an policy-free document (`DOMParser`),
10
- * each style attribute is moved to the CSSOM, and the finished nodes are inserted.
11
- * A `<template>` (frameworks fill those through `innerHTML`) gets the converted nodes in its `content`. Everything else, including HTML without a style attribute, passes straight through.
6
+ * `installMonacoCsp(nonce)` wraps those entry points (only once a nonce is known; without one nothing is touched). The wrappers are
7
+ * page-wide functions, so every conversion is limited to Monaco's own DOM; anything else takes the browser's native path, where the
8
+ * policy blocks `style` attributes in injected markup as usual:
9
+ * - `Element.setAttribute('style', v)` becomes `el.style.cssText = v` (CSSOM, which CSP allows) only inside a Monaco root (`isMonacoDom`);
10
+ * - `innerHTML = …` and `insertAdjacentHTML(…)` strings holding `style="…"` are parsed in a policy-free document (`DOMParser`), each
11
+ * style attribute is moved to the CSSOM, and the finished nodes are inserted, only when the target is inside a Monaco root.
12
+ * Monaco also renders lines into a detached scratch `<div>` and moves the result in; that target is in no root yet, so a detached
13
+ * target (a `<template>` included, its nodes go to `content`) is converted only for Monaco's own line markup: the string starts with
14
+ * `<div style="top:` / `width:` / `text-indent:` and every declaration is a layout property with a plain value (`SAFE_DECLARATION`);
15
+ * One exact string that is not Monaco's is also converted: SvelteKit's `#svelte-announcer` template (`KIT_ANNOUNCER`).
16
+ * - `document.createElement('style')` gives the element the nonce before Monaco fills or inserts it. This one is not scoped: the
17
+ * element cannot be told apart from page code's when it is created (see the "residual risk" note in the truss-code README).
12
18
  */
19
+ /** Whether `node` is part of Monaco's own DOM: inside an editor root or the context view. */
20
+ export declare function isMonacoDom(node: Node | null): boolean;
13
21
  /** Wraps Monaco's style creation so that it works under a nonce-only `style-src`. Idempotent; a later call replaces the nonce. Returns `uninstallMonacoCsp`. */
14
22
  export declare function installMonacoCsp(nonce: string | undefined): () => void;
15
23
  /** Restores the browser's own functions. Meant for tests; Monaco is global, so the editors leave the wrappers installed. */
@@ -3,22 +3,77 @@
3
3
  * elements with `document.createElement('style')`, sets `style` attributes with `setAttribute('style', …)`, and renders every text line
4
4
  * through `innerHTML` / `insertAdjacentHTML` strings that carry `style="top:…"`. All three are blocked by such a policy.
5
5
  *
6
- * `installMonacoCsp(nonce)` wraps those entry points (only once a nonce is known; without one nothing is touched):
7
- * - `document.createElement('style')` gives the element the nonce before Monaco fills or inserts it;
8
- * - `Element.setAttribute('style', v)` becomes `el.style.cssText = v` (CSSOM, which CSP allows);
9
- * - `innerHTML = …` and `insertAdjacentHTML(…)` strings holding `style="…"` are parsed in an policy-free document (`DOMParser`),
10
- * each style attribute is moved to the CSSOM, and the finished nodes are inserted.
11
- * A `<template>` (frameworks fill those through `innerHTML`) gets the converted nodes in its `content`. Everything else, including HTML without a style attribute, passes straight through.
6
+ * `installMonacoCsp(nonce)` wraps those entry points (only once a nonce is known; without one nothing is touched). The wrappers are
7
+ * page-wide functions, so every conversion is limited to Monaco's own DOM; anything else takes the browser's native path, where the
8
+ * policy blocks `style` attributes in injected markup as usual:
9
+ * - `Element.setAttribute('style', v)` becomes `el.style.cssText = v` (CSSOM, which CSP allows) only inside a Monaco root (`isMonacoDom`);
10
+ * - `innerHTML = …` and `insertAdjacentHTML(…)` strings holding `style="…"` are parsed in a policy-free document (`DOMParser`), each
11
+ * style attribute is moved to the CSSOM, and the finished nodes are inserted, only when the target is inside a Monaco root.
12
+ * Monaco also renders lines into a detached scratch `<div>` and moves the result in; that target is in no root yet, so a detached
13
+ * target (a `<template>` included, its nodes go to `content`) is converted only for Monaco's own line markup: the string starts with
14
+ * `<div style="top:` / `width:` / `text-indent:` and every declaration is a layout property with a plain value (`SAFE_DECLARATION`);
15
+ * One exact string that is not Monaco's is also converted: SvelteKit's `#svelte-announcer` template (`KIT_ANNOUNCER`).
16
+ * - `document.createElement('style')` gives the element the nonce before Monaco fills or inserts it. This one is not scoped: the
17
+ * element cannot be told apart from page code's when it is created (see the "residual risk" note in the truss-code README).
12
18
  */
13
19
  import { cspNonce } from './csp.js';
14
20
  let current;
15
21
  const HAS_STYLE = /\sstyle\s*=/i;
22
+ /** What Monaco builds: its editor roots, plus the context view it appends to `body`. */
23
+ const MONACO_ROOT = '.monaco-editor, .monaco-diff-editor, .context-view';
24
+ /** Where Monaco's own line markup starts (viewLine, viewOverlays, the word-wrap measuring container). */
25
+ const MONACO_MARKUP = /^\s*<div style="(?:top|width|text-indent):/;
26
+ /** The declarations Monaco writes into those strings, with the values it writes: positions and sizes, never colours, `position` or `display: none`. */
27
+ const SAFE_DECLARATION = {
28
+ top: /^-?[\d.]+(px)?$/, left: /^-?[\d.]+(px|%)?$/, width: /^[\d.]+(px|%)?$/, height: /^[\d.]+(px)?$/, 'line-height': /^[\d.]+(px)?$/,
29
+ 'text-indent': /^-?[\d.]+(px)?$/, display: /^inline-block$/, 'box-sizing': /^border-box$/, 'white-space': /^(nowrap|pre)$/, 'unicode-bidi': /^isolate$/
30
+ };
31
+ /** The page-free document a style-bearing string is parsed in (no browsing context, so no CSP applies while parsing). */
32
+ const parse = (html) => new DOMParser().parseFromString(`<!doctype html><body>${html}`, 'text/html').body;
33
+ /**
34
+ * Whether every element the parser produced with a `style` attribute holds only declarations Monaco writes itself. This checks the parsed
35
+ * DOM, not the string: the HTML parser accepts forms a string scan misses (`<b/style="…">`, entity-encoded values), so only what the
36
+ * browser would actually apply is judged.
37
+ */
38
+ function onlyMonacoDeclarations(body) {
39
+ for (const el of body.querySelectorAll('[style]')) {
40
+ for (const d of el.getAttribute('style').split(';')) {
41
+ if (!d.trim())
42
+ continue;
43
+ const i = d.indexOf(':');
44
+ if (!(i > 0 && SAFE_DECLARATION[d.slice(0, i).trim().toLowerCase()]?.test(d.slice(i + 1).trim())))
45
+ return false;
46
+ }
47
+ }
48
+ return true;
49
+ }
50
+ /** Whether `node` is part of Monaco's own DOM: inside an editor root or the context view. */
51
+ export function isMonacoDom(node) {
52
+ const el = node instanceof Element ? node : node?.parentElement;
53
+ return !!el?.closest(MONACO_ROOT);
54
+ }
55
+ /**
56
+ * SvelteKit's own screen-reader announcer, `<div id="svelte-announcer" … style="…">`, is a static template with an inline style (a visually hidden
57
+ * element). Before the shim was scoped it was converted along with everything else, so keep it working: this exact string, and no other style attribute.
58
+ */
59
+ const KIT_ANNOUNCER = '<div id="svelte-announcer" aria-live="assertive" aria-atomic="true" style="position: absolute; left: 0; top: 0; clip: rect(0 0 0 0); clip-path: inset(50%); overflow: hidden; white-space: nowrap; width: 1px; height: 1px">';
60
+ // exactly the announcer: the only element the parser gives a style attribute is the announcer itself
61
+ const isKitAnnouncer = (html, body) => html.startsWith(KIT_ANNOUNCER) && body.querySelectorAll('[style]').length === 1;
62
+ /** Whether a style string may be converted for this target: Monaco's DOM, or a detached scratch element given Monaco's own markup. */
63
+ function mayConvert(target, html) {
64
+ if (isMonacoDom(target))
65
+ return true;
66
+ if (!target || target.isConnected)
67
+ return false;
68
+ const body = parse(html);
69
+ return (MONACO_MARKUP.test(html) && onlyMonacoDeclarations(body)) || isKitAnnouncer(html, body);
70
+ }
16
71
  /** Parses `html` in a policy-free document and replaces every `style="…"` attribute with the equivalent CSSOM declarations. */
17
72
  function toFragment(html) {
18
73
  // DOMParser documents have no browsing context, so no CSP applies to the attributes while parsing (a <template> in the page is not exempt)
19
- const body = new DOMParser().parseFromString(`<!doctype html><body>${html}`, 'text/html').body;
74
+ const body = parse(html);
20
75
  for (const el of body.querySelectorAll('[style]')) {
21
- const css = el.getAttribute('style') ?? '';
76
+ const css = el.getAttribute('style');
22
77
  el.removeAttribute('style');
23
78
  el.style.cssText = css;
24
79
  }
@@ -49,7 +104,7 @@ export function installMonacoCsp(nonce) {
49
104
  return el;
50
105
  };
51
106
  Element.prototype.setAttribute = function (name, value) {
52
- if (String(name).toLowerCase() === 'style' && 'style' in this)
107
+ if (String(name).toLowerCase() === 'style' && 'style' in this && isMonacoDom(this))
53
108
  this.style.cssText = String(value);
54
109
  else
55
110
  undo.setAttribute.call(this, name, value);
@@ -58,7 +113,7 @@ export function installMonacoCsp(nonce) {
58
113
  ...undo.innerHTML,
59
114
  set(v) {
60
115
  const html = String(v);
61
- if (!HAS_STYLE.test(html))
116
+ if (!HAS_STYLE.test(html) || !mayConvert(this, html))
62
117
  rawSet.call(this, v);
63
118
  else
64
119
  (this instanceof HTMLTemplateElement ? this.content : this).replaceChildren(toFragment(html));
@@ -66,7 +121,9 @@ export function installMonacoCsp(nonce) {
66
121
  });
67
122
  Element.prototype.insertAdjacentHTML = function (where, v) {
68
123
  const html = String(v);
69
- if (!HAS_STYLE.test(html))
124
+ // beforebegin / afterend put the markup next to the target, so it is the parent that has to be Monaco's
125
+ const beside = /^(beforebegin|afterend)$/i.test(String(where));
126
+ if (!HAS_STYLE.test(html) || !mayConvert(beside ? this.parentElement : this, html))
70
127
  return undo.insertAdjacentHTML.call(this, where, v);
71
128
  const frag = toFragment(html);
72
129
  switch (String(where).toLowerCase()) {
@@ -0,0 +1,18 @@
1
+ import type { Attachment } from 'svelte/attachments';
2
+ /**
3
+ * @internal Makes a scroll container reachable by keyboard while (and only while) it scrolls and has nothing of its own to Tab to (axe `scrollable-region-focusable`, #269).
4
+ *
5
+ * A keyboard user can scroll a region only when it, or something inside it, can take focus. So while the content overflows and holds no tabbable control, the element gets
6
+ * `tabindex="0"`, `role="region"` and an accessible name, and a focus ring from its component's CSS (`:focus-visible`). With a tabbable control inside, the control is the tab stop
7
+ * (focusing it scrolls it into view, and axe accepts that), and an extra stop on the container would only make Tab slower. When nothing overflows there is no tab stop at all.
8
+ * Re-measured when the element or its children resize and when its content changes. It writes nothing on the server (attachments run in the browser), so the markup carries no
9
+ * tab stop until it has been measured and there is no hydration mismatch.
10
+ *
11
+ * `get` supplies the name: `labelledby` (an element id, preferred) or `label` (text). Without either, the role is left off (a nameless region is noise) and only the tab stop is added.
12
+ * `role: false` keeps the element's own role (`main`). Attributes the app set itself (`tabindex` other than `-1`, `role`, `aria-label`, `aria-labelledby`) are never overwritten.
13
+ */
14
+ export declare function scrollFocus(get?: () => {
15
+ labelledby?: string;
16
+ label?: string;
17
+ role?: boolean;
18
+ }): Attachment<HTMLElement>;
@@ -0,0 +1,92 @@
1
+ /** Elements a keyboard user can Tab to on their own. A `tabindex="-1"` element is only focusable by script, so it does not count. */
2
+ const TABBABLE = 'a[href],area[href],button,input:not([type="hidden"]),select,textarea,summary,iframe,audio[controls],video[controls],[contenteditable]:not([contenteditable="false"]),[tabindex]';
3
+ function tabbableWithin(el) {
4
+ for (const c of el.querySelectorAll(TABBABLE)) {
5
+ const t = c.getAttribute('tabindex');
6
+ if (t !== null && Number(t) < 0)
7
+ continue;
8
+ if (c.matches(':disabled') || c.closest('[hidden],[inert]') || c.getClientRects().length === 0)
9
+ continue;
10
+ return true;
11
+ }
12
+ return false;
13
+ }
14
+ /** Whether `el` scrolls right now: it clips its overflow (`auto`/`scroll`) and its content is larger than its box. */
15
+ function scrolls(el) {
16
+ const cs = getComputedStyle(el);
17
+ return (/auto|scroll/.test(cs.overflowY) && el.scrollHeight > el.clientHeight + 1) || (/auto|scroll/.test(cs.overflowX) && el.scrollWidth > el.clientWidth + 1);
18
+ }
19
+ /**
20
+ * @internal Makes a scroll container reachable by keyboard while (and only while) it scrolls and has nothing of its own to Tab to (axe `scrollable-region-focusable`, #269).
21
+ *
22
+ * A keyboard user can scroll a region only when it, or something inside it, can take focus. So while the content overflows and holds no tabbable control, the element gets
23
+ * `tabindex="0"`, `role="region"` and an accessible name, and a focus ring from its component's CSS (`:focus-visible`). With a tabbable control inside, the control is the tab stop
24
+ * (focusing it scrolls it into view, and axe accepts that), and an extra stop on the container would only make Tab slower. When nothing overflows there is no tab stop at all.
25
+ * Re-measured when the element or its children resize and when its content changes. It writes nothing on the server (attachments run in the browser), so the markup carries no
26
+ * tab stop until it has been measured and there is no hydration mismatch.
27
+ *
28
+ * `get` supplies the name: `labelledby` (an element id, preferred) or `label` (text). Without either, the role is left off (a nameless region is noise) and only the tab stop is added.
29
+ * `role: false` keeps the element's own role (`main`). Attributes the app set itself (`tabindex` other than `-1`, `role`, `aria-label`, `aria-labelledby`) are never overwritten.
30
+ */
31
+ export function scrollFocus(get) {
32
+ return (el) => {
33
+ let added = [];
34
+ let restore; // a programmatic-only `tabindex="-1"` (Shell's `main`) is replaced while the tab stop is on
35
+ let queued = false;
36
+ const clear = () => {
37
+ for (const a of added)
38
+ el.removeAttribute(a);
39
+ added = [];
40
+ if (restore !== undefined) {
41
+ el.setAttribute('tabindex', restore);
42
+ restore = undefined;
43
+ }
44
+ };
45
+ const set = (name, value) => { if (!el.hasAttribute(name)) {
46
+ el.setAttribute(name, value);
47
+ added.push(name);
48
+ } };
49
+ const measure = () => {
50
+ queued = false;
51
+ const on = scrolls(el) && !tabbableWithin(el);
52
+ if (!on) {
53
+ clear();
54
+ return;
55
+ }
56
+ if (added.length)
57
+ return;
58
+ const { labelledby, label, role = true } = get?.() ?? {};
59
+ const named = !!(labelledby || label) && !el.hasAttribute('aria-label') && !el.hasAttribute('aria-labelledby');
60
+ if (el.getAttribute('tabindex') === '-1') {
61
+ restore = '-1';
62
+ el.removeAttribute('tabindex');
63
+ }
64
+ set('tabindex', '0');
65
+ if (role && (named || el.hasAttribute('aria-label') || el.hasAttribute('aria-labelledby')))
66
+ set('role', 'region');
67
+ if (named) {
68
+ if (labelledby)
69
+ set('aria-labelledby', labelledby);
70
+ else
71
+ set('aria-label', label);
72
+ }
73
+ };
74
+ // coalesce bursts (a virtual list scrolling, many nodes added) into one measurement per microtask
75
+ const schedule = () => { if (!queued) {
76
+ queued = true;
77
+ queueMicrotask(measure);
78
+ } };
79
+ const ro = typeof ResizeObserver === 'undefined' ? undefined : new ResizeObserver(schedule);
80
+ const watchKids = () => { if (ro) {
81
+ ro.disconnect();
82
+ ro.observe(el);
83
+ for (const k of el.children)
84
+ ro.observe(k);
85
+ } };
86
+ const mo = new MutationObserver(() => { watchKids(); schedule(); });
87
+ mo.observe(el, { childList: true, subtree: true, characterData: true, attributes: true, attributeFilter: ['tabindex', 'disabled', 'hidden', 'inert', 'href'] });
88
+ watchKids();
89
+ measure();
90
+ return () => { ro?.disconnect(); mo.disconnect(); clear(); };
91
+ };
92
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ruckc/truss-code",
3
- "version": "1.50.1",
3
+ "version": "1.51.1",
4
4
  "description": "Read-only code blocks, diff and merge views, plus an optional Monaco code editor, styled with Truss UI",
5
5
  "type": "module",
6
6
  "license": "MIT",