Claude commited on
Commit
c28a145
Β·
1 Parent(s): 8fb4d34

Accessibility: term tooltips become real <a> links to glossary entries

Browse files

The narration's inline highlighter wrapped each defined term in a
<mark class="kt" title="…"> with the definition only in the title
attribute. WCAG 2.5.1 / 4.1.2 β€” touch users can't trigger hover,
keyboard users can't focus a <mark>, many screen readers skip the
title attribute entirely. Definitions were effectively unavailable
to roughly half of likely users.

Build the glossary once at the top of <main> and pass it to the
highlighter so each first-occurrence wrap becomes
<a class="kt" href="#glossary-N" title="…">term</a>
β€” focusable, touch-tappable, screen-reader announced as a link to
the named target. The bottom glossary's <dt> ids match the hrefs
the highlighter emits (build_glossary now stamps each entry with
its own `id` field so server template and JS port share the
contract). Terms with no glossary entry (defensive) fall back to
the old <mark> shape.

Mirror in buildFinalHTML: build the glossary entries before walking
sections, thread the lookup through highlightTerms, reuse the same
entries when rendering the bottom glossary section. JS uses
createElement+setAttribute+outerHTML for the wrap-element-builder
so href/title escaping comes from the browser.

Three smaller a11y improvements bundled in:

- Glossary back-link "↑ section" was non-unique link text across
14+ entries. Now reads "↑ in context" and carries an aria-label
"Go to section "<title>" where <term> is introduced" β€” distinct
in context (WCAG 2.4.4) without bloating visible text.
- <details> elements (on-screen-text, self-check) get an aria-label
that names the section they belong to, so a screen-reader user
navigating by interactive controls knows which section they're
expanding.
- "In brief:" prefix on section summaries changed from <strong>
(implies strong importance for screen-reader announcement) to
<span class="section__summary__label"> with the same visual
weight via CSS. Pure label, not an emphasis claim.

Tests cover the new link-wrap path, the no-glossary fallback to
<mark>, and the no-nesting guarantee under both shapes.

app/pipeline/html_gen.py CHANGED
@@ -133,33 +133,39 @@ def build_segments(
133
  return segments
134
 
135
 
136
- _MARK_SPAN_RE = None # lazily compiled in _highlight_terms
137
 
138
 
139
- def _highlight_terms(paragraph_text: str, key_terms: list[Any]) -> str:
140
- """Wrap occurrences of any key term in `<mark class="kt">…</mark>` so
141
- the learner sees the defined vocabulary in context. Escaping is
142
- handled here (the template `|safe`s the result).
 
 
 
 
 
143
 
144
  Conservative strategy: case-insensitive whole-word match, longest
145
  term first (so "machine learning" beats "machine"), one replacement
146
- per paragraph per term. Critically, each pass only operates on text
147
- *outside* the wraps a previous pass produced β€” otherwise a
148
- shorter sibling term ("machine") would land inside a longer wrap
149
- ("machine learning") and we'd nest <mark> tags.
150
  """
151
  import html
152
  import re as _re
153
 
154
- global _MARK_SPAN_RE
155
- if _MARK_SPAN_RE is None:
156
- _MARK_SPAN_RE = _re.compile(r'<mark class="kt"[^>]*>.*?</mark>')
 
 
 
 
157
 
158
  escaped = html.escape(paragraph_text)
159
  if not key_terms:
160
  return escaped
161
- # Normalise + sort longest-first so multi-word terms aren't shadowed
162
- # by single-word substrings.
163
  terms = sorted(
164
  [
165
  (kt.term if hasattr(kt, "term") else kt.get("term", ""),
@@ -175,20 +181,27 @@ def _highlight_terms(paragraph_text: str, key_terms: list[Any]) -> str:
175
  r"\b" + _re.escape(html.escape(term)) + r"\b", _re.IGNORECASE,
176
  )
177
  title = html.escape(definition or "")
178
- # Walk through escaped, alternating between existing <mark>
179
- # spans (kept verbatim) and the text in between (eligible for
180
- # substitution). Single replacement per paragraph stops at the
181
- # first match across all outside-text segments.
 
 
 
 
 
 
 
 
 
 
182
  out_parts: list[str] = []
183
  last_end = 0
184
  replaced = False
185
- for span in _MARK_SPAN_RE.finditer(escaped):
186
  outside = escaped[last_end:span.start()]
187
  if not replaced:
188
- outside, n = pattern.subn(
189
- rf'<mark class="kt" title="{title}">\g<0></mark>',
190
- outside, count=1,
191
- )
192
  if n:
193
  replaced = True
194
  out_parts.append(outside)
@@ -196,10 +209,7 @@ def _highlight_terms(paragraph_text: str, key_terms: list[Any]) -> str:
196
  last_end = span.end()
197
  tail = escaped[last_end:]
198
  if not replaced:
199
- tail, _ = pattern.subn(
200
- rf'<mark class="kt" title="{title}">\g<0></mark>',
201
- tail, count=1,
202
- )
203
  out_parts.append(tail)
204
  escaped = "".join(out_parts)
205
  return escaped
@@ -208,7 +218,9 @@ def _highlight_terms(paragraph_text: str, key_terms: list[Any]) -> str:
208
  def _build_glossary(segments: list["Segment"]) -> list[dict[str, Any]]:
209
  """Collect every segment's key_terms into one alphabetised list,
210
  deduped by lowercase term. Each entry remembers the first section
211
- it appeared in so the rendered glossary can anchor back.
 
 
212
 
213
  Returned list of dicts (instead of a custom dataclass) so the
214
  Jinja template can use dot-attribute *and* dict-key access; keeps
@@ -233,7 +245,22 @@ def _build_glossary(segments: list["Segment"]) -> list[dict[str, Any]]:
233
  "definition": definition,
234
  "first_section_index": getattr(seg, "index", None),
235
  }
236
- return sorted(seen.values(), key=lambda e: e["term"].lower())
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
237
 
238
 
239
  def _env() -> Environment:
 
133
  return segments
134
 
135
 
136
+ _HIGHLIGHT_SPAN_RE = None # lazily compiled in _highlight_terms
137
 
138
 
139
+ def _highlight_terms(
140
+ paragraph_text: str,
141
+ key_terms: list[Any],
142
+ glossary: list[dict[str, Any]] | None = None,
143
+ ) -> str:
144
+ """Wrap occurrences of any key term in a link to its glossary entry
145
+ so the learner can keyboard / touch-navigate to the full definition.
146
+ Falls back to a plain <mark> when no glossary is supplied (legacy
147
+ callers, or terms not in the glossary).
148
 
149
  Conservative strategy: case-insensitive whole-word match, longest
150
  term first (so "machine learning" beats "machine"), one replacement
151
+ per paragraph per term. Each pass only operates on text outside
152
+ existing highlight spans so wraps never nest.
 
 
153
  """
154
  import html
155
  import re as _re
156
 
157
+ global _HIGHLIGHT_SPAN_RE
158
+ if _HIGHLIGHT_SPAN_RE is None:
159
+ # Matches either of the two highlight shapes we produce so
160
+ # subsequent passes can skip them entirely.
161
+ _HIGHLIGHT_SPAN_RE = _re.compile(
162
+ r'<a class="kt"[^>]*>.*?</a>|<mark class="kt"[^>]*>.*?</mark>',
163
+ )
164
 
165
  escaped = html.escape(paragraph_text)
166
  if not key_terms:
167
  return escaped
168
+ glossary_ids = _glossary_id_lookup(glossary)
 
169
  terms = sorted(
170
  [
171
  (kt.term if hasattr(kt, "term") else kt.get("term", ""),
 
181
  r"\b" + _re.escape(html.escape(term)) + r"\b", _re.IGNORECASE,
182
  )
183
  title = html.escape(definition or "")
184
+ gloss_id = glossary_ids.get(term.lower(), "")
185
+ if gloss_id:
186
+ # Anchor link to the glossary entry β€” focusable, touch-tappable,
187
+ # screen-reader announced as "link, <term>".
188
+ replacement = (
189
+ rf'<a class="kt" href="#{gloss_id}" title="{title}">'
190
+ rf'\g<0></a>'
191
+ )
192
+ else:
193
+ # Term has no glossary entry (legacy call site, or the
194
+ # term was deduped after this segment). Fall back to a
195
+ # non-focusable <mark>; the tooltip is still visible to
196
+ # mouse users.
197
+ replacement = rf'<mark class="kt" title="{title}">\g<0></mark>'
198
  out_parts: list[str] = []
199
  last_end = 0
200
  replaced = False
201
+ for span in _HIGHLIGHT_SPAN_RE.finditer(escaped):
202
  outside = escaped[last_end:span.start()]
203
  if not replaced:
204
+ outside, n = pattern.subn(replacement, outside, count=1)
 
 
 
205
  if n:
206
  replaced = True
207
  out_parts.append(outside)
 
209
  last_end = span.end()
210
  tail = escaped[last_end:]
211
  if not replaced:
212
+ tail, _ = pattern.subn(replacement, tail, count=1)
 
 
 
213
  out_parts.append(tail)
214
  escaped = "".join(out_parts)
215
  return escaped
 
218
  def _build_glossary(segments: list["Segment"]) -> list[dict[str, Any]]:
219
  """Collect every segment's key_terms into one alphabetised list,
220
  deduped by lowercase term. Each entry remembers the first section
221
+ it appeared in (for back-anchoring) AND its own stable id (so the
222
+ narration highlighter can produce real <a href="#glossary-N"> links
223
+ pointing at the right entry).
224
 
225
  Returned list of dicts (instead of a custom dataclass) so the
226
  Jinja template can use dot-attribute *and* dict-key access; keeps
 
245
  "definition": definition,
246
  "first_section_index": getattr(seg, "index", None),
247
  }
248
+ entries = sorted(seen.values(), key=lambda e: e["term"].lower())
249
+ # Stable ids after sort so they line up with the rendered <dt> in
250
+ # the glossary section and with the href values produced by the
251
+ # highlighter.
252
+ for i, entry in enumerate(entries, start=1):
253
+ entry["id"] = f"glossary-{i}"
254
+ return entries
255
+
256
+
257
+ def _glossary_id_lookup(glossary: list[dict[str, Any]] | None) -> dict[str, str]:
258
+ """Lowercase-term β†’ glossary id, derived from _build_glossary's
259
+ output. Empty dict when no glossary was supplied.
260
+ """
261
+ if not glossary:
262
+ return {}
263
+ return {(e.get("term") or "").lower(): e.get("id", "") for e in glossary}
264
 
265
 
266
  def _env() -> Environment:
app/templates/_doc_styles.html CHANGED
@@ -376,16 +376,32 @@
376
  /* Inline key-term highlighting. <mark class="kt"> wraps the first
377
  occurrence of each defined term in a paragraph; hover surfaces
378
  the definition via the title attribute. */
379
- .narration__body mark.kt {
 
 
 
 
 
380
  background: transparent;
381
  color: inherit;
382
  border-bottom: 1.5px dotted var(--color-banner, #750014);
383
  padding: 0;
384
- cursor: help;
385
  }
 
386
  .narration__body mark.kt:hover, .narration__body mark.kt:focus {
387
  background: rgba(117, 0, 20, 0.06);
388
  }
 
 
 
 
 
 
 
 
 
 
389
  /* Retrieval-practice question block at the end of each section. */
390
  .self-check {
391
  margin: var(--space-md) 0;
 
376
  /* Inline key-term highlighting. <mark class="kt"> wraps the first
377
  occurrence of each defined term in a paragraph; hover surfaces
378
  the definition via the title attribute. */
379
+ /* Both the link form (default β€” focusable, navigable) and the
380
+ mark fallback (when no glossary entry exists) read the same
381
+ visually: dotted underline in the banner colour, inherits text
382
+ colour, transparent background. The link form pulls focus and
383
+ hover ring from the global :focus-visible rule. */
384
+ .narration__body a.kt, .narration__body mark.kt {
385
  background: transparent;
386
  color: inherit;
387
  border-bottom: 1.5px dotted var(--color-banner, #750014);
388
  padding: 0;
389
+ text-decoration: none;
390
  }
391
+ .narration__body a.kt:hover, .narration__body a.kt:focus,
392
  .narration__body mark.kt:hover, .narration__body mark.kt:focus {
393
  background: rgba(117, 0, 20, 0.06);
394
  }
395
+ .narration__body mark.kt { cursor: help; }
396
+ .narration__body a.kt:hover { color: var(--color-banner, #750014); }
397
+
398
+ /* Label prefix for the "In brief:" section summary. Span instead
399
+ of <strong> because <strong> implies strong importance for
400
+ screen-reader announcement; the label is just a UI affordance. */
401
+ .section__summary__label {
402
+ font-weight: 700;
403
+ color: var(--color-banner, #750014);
404
+ }
405
  /* Retrieval-practice question block at the end of each section. */
406
  .self-check {
407
  margin: var(--space-md) 0;
app/templates/guide.html CHANGED
@@ -57,6 +57,10 @@
57
  {% endif %}
58
 
59
  <main id="main-content" class="content" tabindex="-1">
 
 
 
 
60
  {% for seg in segments %}
61
  <section class="section" id="section-{{ seg.index }}" aria-labelledby="heading-{{ seg.index }}">
62
  <h2 class="section__heading" id="heading-{{ seg.index }}">{{ seg.section_title }}</h2>
@@ -68,7 +72,7 @@
68
  {# Advance organizer β€” Claude's one-sentence summary primes the
69
  learner before they hit the slide and narration. #}
70
  {% if seg.summary %}
71
- <p class="section__summary"><strong>In brief:</strong> {{ seg.summary }}</p>
72
  {% endif %}
73
 
74
  <figure class="figure">
@@ -91,7 +95,8 @@
91
  </figure>
92
 
93
  {% if seg.ocr_text %}
94
- <details class="onscreen-text">
 
95
  <summary>On-screen text from video</summary>
96
  <div class="onscreen-text__body">{{ seg.ocr_text|format_ocr }}</div>
97
  </details>
@@ -119,7 +124,7 @@
119
  <h3 class="sr-only" id="narration-label-{{ seg.index }}">Narration</h3>
120
  <div class="narration__body" id="narration-{{ seg.index }}"
121
  aria-labelledby="narration-label-{{ seg.index }}">
122
- {% for para in seg.narration %}<p>{{ para|highlight_terms(seg.key_terms)|safe }}</p>{% endfor %}
123
  </div>
124
  </div>
125
  {% endif %}
@@ -145,7 +150,8 @@
145
  provided β€” the question itself is the prompt, and the act of
146
  constructing an answer from the section is the learning gain. #}
147
  {% if seg.self_check_questions %}
148
- <details class="self-check">
 
149
  <summary>Check your understanding</summary>
150
  <ol class="self-check__list">
151
  {% for question in seg.self_check_questions %}
@@ -158,20 +164,28 @@
158
  </section>
159
  {% endfor %}
160
 
161
- {# Auto-built glossary. Collected from every segment's key_terms,
162
- deduped by lowercase term, sorted alphabetically. Anchors back
163
- to the section where the term was first introduced. #}
164
- {% set glossary = build_glossary(segments) %}
165
  {% if glossary %}
 
 
 
 
166
  <section class="glossary" id="glossary" aria-labelledby="glossary-heading">
167
  <h2 id="glossary-heading">Glossary</h2>
168
  <dl>
169
  {% for entry in glossary %}
170
- <dt id="glossary-{{ loop.index }}">{{ entry.term }}</dt>
171
  <dd>
172
  {{ entry.definition }}
173
  {% if entry.first_section_index is not none %}
174
- <a class="glossary__back" href="#section-{{ entry.first_section_index }}">↑ section</a>
 
 
 
 
175
  {% endif %}
176
  </dd>
177
  {% endfor %}
 
57
  {% endif %}
58
 
59
  <main id="main-content" class="content" tabindex="-1">
60
+ {# Build the glossary once up front so the narration highlighter
61
+ can link each defined term to its glossary entry, and the
62
+ glossary section at the bottom reuses the same ids. #}
63
+ {% set glossary = build_glossary(segments) %}
64
  {% for seg in segments %}
65
  <section class="section" id="section-{{ seg.index }}" aria-labelledby="heading-{{ seg.index }}">
66
  <h2 class="section__heading" id="heading-{{ seg.index }}">{{ seg.section_title }}</h2>
 
72
  {# Advance organizer β€” Claude's one-sentence summary primes the
73
  learner before they hit the slide and narration. #}
74
  {% if seg.summary %}
75
+ <p class="section__summary"><span class="section__summary__label">In brief:</span> {{ seg.summary }}</p>
76
  {% endif %}
77
 
78
  <figure class="figure">
 
95
  </figure>
96
 
97
  {% if seg.ocr_text %}
98
+ <details class="onscreen-text"
99
+ aria-label="On-screen text from β€œ{{ seg.section_title }}”">
100
  <summary>On-screen text from video</summary>
101
  <div class="onscreen-text__body">{{ seg.ocr_text|format_ocr }}</div>
102
  </details>
 
124
  <h3 class="sr-only" id="narration-label-{{ seg.index }}">Narration</h3>
125
  <div class="narration__body" id="narration-{{ seg.index }}"
126
  aria-labelledby="narration-label-{{ seg.index }}">
127
+ {% for para in seg.narration %}<p>{{ para|highlight_terms(seg.key_terms, glossary)|safe }}</p>{% endfor %}
128
  </div>
129
  </div>
130
  {% endif %}
 
150
  provided β€” the question itself is the prompt, and the act of
151
  constructing an answer from the section is the learning gain. #}
152
  {% if seg.self_check_questions %}
153
+ <details class="self-check"
154
+ aria-label="Self-check questions for β€œ{{ seg.section_title }}”">
155
  <summary>Check your understanding</summary>
156
  <ol class="self-check__list">
157
  {% for question in seg.self_check_questions %}
 
164
  </section>
165
  {% endfor %}
166
 
167
+ {# Glossary section. Reuses the `glossary` variable built at the
168
+ top of <main> so ids match the hrefs the narration highlighter
169
+ emitted. Back-link's accessible name names the section it
170
+ returns to (WCAG 2.4.4 distinguishable link purpose). #}
171
  {% if glossary %}
172
+ {% set sections_by_index = {} %}
173
+ {% for s in segments %}
174
+ {% if sections_by_index.update({s.index: s.section_title}) %}{% endif %}
175
+ {% endfor %}
176
  <section class="glossary" id="glossary" aria-labelledby="glossary-heading">
177
  <h2 id="glossary-heading">Glossary</h2>
178
  <dl>
179
  {% for entry in glossary %}
180
+ <dt id="{{ entry.id }}">{{ entry.term }}</dt>
181
  <dd>
182
  {{ entry.definition }}
183
  {% if entry.first_section_index is not none %}
184
+ {% set sec_title = sections_by_index.get(entry.first_section_index, '') %}
185
+ <a class="glossary__back" href="#section-{{ entry.first_section_index }}"
186
+ aria-label="Go to section{% if sec_title %} β€œ{{ sec_title }}”{% endif %} where {{ entry.term }} is introduced">
187
+ ↑ in context
188
+ </a>
189
  {% endif %}
190
  </dd>
191
  {% endfor %}
app/templates/review.html CHANGED
@@ -820,51 +820,59 @@
820
  return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
821
  }
822
 
823
- // Cache one detached <mark> per (term, definition) so we get
824
- // the browser's correct attribute serialization (entity-encoded
825
- // title) every iteration without rebuilding the element.
826
- function markHtmlFor(definition) {
827
- const m = doc.createElement('mark');
828
- m.className = 'kt';
829
- m.setAttribute('title', definition || '');
830
- // outerHTML on a freshly-created element gives us
831
- // `<mark class="kt" title="…escaped…"></mark>`
832
- // with the browser handling all attribute-value escaping. We
833
- // split that into open/close so we can drop the matched text
834
- // verbatim between them. This sidesteps two foot-guns of the
835
- // earlier `${title}` template-string approach:
836
- // 1. `$&`, `$'`, etc. as replacement-pattern specials being
837
- // interpreted in `.replace()`.
838
- // 2. any future XSS regression if escapeHtml's coverage
839
- // grew incomplete.
840
- const html = m.outerHTML;
 
 
 
 
841
  const openEnd = html.indexOf('>') + 1;
842
- return { open: html.slice(0, openEnd), close: '</mark>' };
843
  }
844
 
845
- function highlightTerms(paragraphText, keyTerms) {
846
  // Mirrors the server-side _highlight_terms filter: case-
847
- // insensitive whole-word match, longest term first, one mark
848
- // per term per paragraph, no nesting.
 
 
849
  if (!keyTerms || !keyTerms.length) return escapeHtml(paragraphText);
 
850
  let escaped = escapeHtml(paragraphText);
851
  const sorted = keyTerms
852
  .map(kt => ({ term: (kt.term || '').trim(), definition: (kt.definition || '').trim() }))
853
  .filter(kt => kt.term.length >= 3)
854
  .sort((a, b) => b.term.length - a.term.length);
855
- const markSpan = /<mark class="kt"[^>]*>.*?<\/mark>/g;
856
  for (const { term, definition } of sorted) {
857
  const pattern = new RegExp('\\b' + escapeRegex(escapeHtml(term)) + '\\b', 'i');
858
- const { open, close } = markHtmlFor(definition);
859
- // Use a function replacer so any `$` in the matched text
860
- // is treated literally instead of as a replacement pattern.
 
861
  const wrap = (m0) => open + m0 + close;
862
  let lastEnd = 0;
863
  let replaced = false;
864
  let out = '';
865
  let m;
866
- markSpan.lastIndex = 0;
867
- while ((m = markSpan.exec(escaped)) !== null) {
868
  let outside = escaped.slice(lastEnd, m.index);
869
  if (!replaced && pattern.test(outside)) {
870
  outside = outside.replace(pattern, wrap);
@@ -882,6 +890,35 @@
882
  return escaped;
883
  }
884
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
885
  clone.querySelectorAll('section.section').forEach(section => {
886
  const segState = stateBySegmentId.get(section.id);
887
  if (!segState) return;
@@ -906,7 +943,7 @@
906
  if (segState.key_terms && segState.key_terms.length) {
907
  section.querySelectorAll('.narration__body p').forEach(p => {
908
  const original = p.textContent || '';
909
- const highlighted = highlightTerms(original, segState.key_terms);
910
  if (highlighted !== escapeHtml(original)) {
911
  p.innerHTML = highlighted;
912
  }
@@ -979,56 +1016,46 @@
979
  }
980
  });
981
 
982
- // Auto-built glossary at the end of <main>. Same collection
983
- // rules as the server-side build_glossary: dedupe case-
984
- // insensitively (first occurrence wins), sort alphabetically,
985
- // anchor each entry back to the first section where the term
986
- // appeared.
987
  const glossaryMain = clone.querySelector('#main-content') || clone.querySelector('main');
988
- if (glossaryMain) {
989
- const seen = new Map();
990
- state.segments.forEach(seg => {
991
- if (seg.include === false) return;
992
- (seg.key_terms || []).forEach(kt => {
993
- const term = (kt.term || '').trim();
994
- const definition = (kt.definition || '').trim();
995
- if (!term) return;
996
- const key = term.toLowerCase();
997
- if (seen.has(key)) return;
998
- seen.set(key, { term, definition, firstSection: seg.index });
999
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1000
  });
1001
- const entries = Array.from(seen.values())
1002
- .sort((a, b) => a.term.toLowerCase().localeCompare(b.term.toLowerCase()));
1003
- if (entries.length) {
1004
- const glossSection = doc.createElement('section');
1005
- glossSection.className = 'glossary';
1006
- glossSection.id = 'glossary';
1007
- glossSection.setAttribute('aria-labelledby', 'glossary-heading');
1008
- const h = doc.createElement('h2');
1009
- h.id = 'glossary-heading';
1010
- h.textContent = 'Glossary';
1011
- glossSection.appendChild(h);
1012
- const dl = doc.createElement('dl');
1013
- entries.forEach((entry, i) => {
1014
- const dt = doc.createElement('dt');
1015
- dt.id = `glossary-${i + 1}`;
1016
- dt.textContent = entry.term;
1017
- const dd = doc.createElement('dd');
1018
- dd.appendChild(doc.createTextNode(entry.definition + ' '));
1019
- if (entry.firstSection !== undefined && entry.firstSection !== null) {
1020
- const back = doc.createElement('a');
1021
- back.className = 'glossary__back';
1022
- back.href = `#section-${entry.firstSection}`;
1023
- back.textContent = '↑ section';
1024
- dd.appendChild(back);
1025
- }
1026
- dl.appendChild(dt);
1027
- dl.appendChild(dd);
1028
- });
1029
- glossSection.appendChild(dl);
1030
- glossaryMain.appendChild(glossSection);
1031
- }
1032
  }
1033
 
1034
  // Drop excluded segments.
 
820
  return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
821
  }
822
 
823
+ // Cache one detached wrap element per (term, definition, glossaryId)
824
+ // so we get the browser's correct attribute serialization (entity-
825
+ // encoded href / title) every iteration without rebuilding the
826
+ // element. Returns {open, close} we drop the matched text between.
827
+ // Sidesteps the foot-guns of template-string interpolation:
828
+ // 1. `$&`, `$'`, etc. as replacement-pattern specials being
829
+ // interpreted in `.replace()`.
830
+ // 2. any future XSS regression if escapeHtml's coverage grew
831
+ // incomplete.
832
+ function wrapHtmlFor(definition, glossaryId) {
833
+ let el;
834
+ if (glossaryId) {
835
+ el = doc.createElement('a');
836
+ el.className = 'kt';
837
+ el.setAttribute('href', '#' + glossaryId);
838
+ if (definition) el.setAttribute('title', definition);
839
+ } else {
840
+ el = doc.createElement('mark');
841
+ el.className = 'kt';
842
+ if (definition) el.setAttribute('title', definition);
843
+ }
844
+ const html = el.outerHTML;
845
  const openEnd = html.indexOf('>') + 1;
846
+ return { open: html.slice(0, openEnd), close: glossaryId ? '</a>' : '</mark>' };
847
  }
848
 
849
+ function highlightTerms(paragraphText, keyTerms, glossaryIdByLowerTerm) {
850
  // Mirrors the server-side _highlight_terms filter: case-
851
+ // insensitive whole-word match, longest term first, one wrap
852
+ // per term per paragraph, no nesting. When a glossary id is
853
+ // available for the term, wraps as <a href="#glossary-N"> (focus-
854
+ // able + tappable); otherwise falls back to <mark> with title.
855
  if (!keyTerms || !keyTerms.length) return escapeHtml(paragraphText);
856
+ const lookup = glossaryIdByLowerTerm || {};
857
  let escaped = escapeHtml(paragraphText);
858
  const sorted = keyTerms
859
  .map(kt => ({ term: (kt.term || '').trim(), definition: (kt.definition || '').trim() }))
860
  .filter(kt => kt.term.length >= 3)
861
  .sort((a, b) => b.term.length - a.term.length);
862
+ const highlightSpan = /<a class="kt"[^>]*>.*?<\/a>|<mark class="kt"[^>]*>.*?<\/mark>/g;
863
  for (const { term, definition } of sorted) {
864
  const pattern = new RegExp('\\b' + escapeRegex(escapeHtml(term)) + '\\b', 'i');
865
+ const gloss = lookup[term.toLowerCase()] || '';
866
+ const { open, close } = wrapHtmlFor(definition, gloss);
867
+ // Function replacer so any `$` in the matched text is
868
+ // treated literally instead of as a replacement pattern.
869
  const wrap = (m0) => open + m0 + close;
870
  let lastEnd = 0;
871
  let replaced = false;
872
  let out = '';
873
  let m;
874
+ highlightSpan.lastIndex = 0;
875
+ while ((m = highlightSpan.exec(escaped)) !== null) {
876
  let outside = escaped.slice(lastEnd, m.index);
877
  if (!replaced && pattern.test(outside)) {
878
  outside = outside.replace(pattern, wrap);
 
890
  return escaped;
891
  }
892
 
893
+ // Build the glossary once up front so each narration paragraph
894
+ // can link its highlighted terms to the glossary entry by id.
895
+ // Mirrors the server-side _build_glossary contract.
896
+ function buildGlossaryEntries(stateSegments) {
897
+ const seen = new Map();
898
+ stateSegments.forEach(seg => {
899
+ if (seg.include === false) return;
900
+ (seg.key_terms || []).forEach(kt => {
901
+ const term = (kt.term || '').trim();
902
+ const definition = (kt.definition || '').trim();
903
+ if (!term) return;
904
+ const key = term.toLowerCase();
905
+ if (seen.has(key)) return;
906
+ seen.set(key, {
907
+ term, definition,
908
+ firstSection: seg.index,
909
+ firstSectionTitle: seg.section_title || '',
910
+ });
911
+ });
912
+ });
913
+ const entries = Array.from(seen.values())
914
+ .sort((a, b) => a.term.toLowerCase().localeCompare(b.term.toLowerCase()));
915
+ entries.forEach((e, i) => { e.id = `glossary-${i + 1}`; });
916
+ return entries;
917
+ }
918
+ const glossaryEntries = buildGlossaryEntries(state.segments);
919
+ const glossaryLookup = {};
920
+ glossaryEntries.forEach(e => { glossaryLookup[e.term.toLowerCase()] = e.id; });
921
+
922
  clone.querySelectorAll('section.section').forEach(section => {
923
  const segState = stateBySegmentId.get(section.id);
924
  if (!segState) return;
 
943
  if (segState.key_terms && segState.key_terms.length) {
944
  section.querySelectorAll('.narration__body p').forEach(p => {
945
  const original = p.textContent || '';
946
+ const highlighted = highlightTerms(original, segState.key_terms, glossaryLookup);
947
  if (highlighted !== escapeHtml(original)) {
948
  p.innerHTML = highlighted;
949
  }
 
1016
  }
1017
  });
1018
 
1019
+ // Render the prebuilt glossary entries (built above so the
1020
+ // narration highlighter could link into them). Each back-link
1021
+ // names its destination section in aria-label so the link's
1022
+ // purpose is distinguishable in context (WCAG 2.4.4).
 
1023
  const glossaryMain = clone.querySelector('#main-content') || clone.querySelector('main');
1024
+ if (glossaryMain && glossaryEntries.length) {
1025
+ const glossSection = doc.createElement('section');
1026
+ glossSection.className = 'glossary';
1027
+ glossSection.id = 'glossary';
1028
+ glossSection.setAttribute('aria-labelledby', 'glossary-heading');
1029
+ const h = doc.createElement('h2');
1030
+ h.id = 'glossary-heading';
1031
+ h.textContent = 'Glossary';
1032
+ glossSection.appendChild(h);
1033
+ const dl = doc.createElement('dl');
1034
+ glossaryEntries.forEach((entry) => {
1035
+ const dt = doc.createElement('dt');
1036
+ dt.id = entry.id;
1037
+ dt.textContent = entry.term;
1038
+ const dd = doc.createElement('dd');
1039
+ dd.appendChild(doc.createTextNode(entry.definition + ' '));
1040
+ if (entry.firstSection !== undefined && entry.firstSection !== null) {
1041
+ const back = doc.createElement('a');
1042
+ back.className = 'glossary__back';
1043
+ back.href = `#section-${entry.firstSection}`;
1044
+ back.textContent = '↑ in context';
1045
+ const sectionTitle = entry.firstSectionTitle || '';
1046
+ back.setAttribute(
1047
+ 'aria-label',
1048
+ sectionTitle
1049
+ ? `Go to section β€œ${sectionTitle}” where ${entry.term} is introduced`
1050
+ : `Go to the section where ${entry.term} is introduced`,
1051
+ );
1052
+ dd.appendChild(back);
1053
+ }
1054
+ dl.appendChild(dt);
1055
+ dl.appendChild(dd);
1056
  });
1057
+ glossSection.appendChild(dl);
1058
+ glossaryMain.appendChild(glossSection);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1059
  }
1060
 
1061
  // Drop excluded segments.
tests/test_html_gen.py CHANGED
@@ -424,12 +424,54 @@ def test_highlight_terms_wraps_first_occurrence_per_paragraph():
424
  KeyTerm(term="machine", definition="a generic machine"),
425
  ]
426
  out = _highlight_terms("A machine learning system uses machine learning daily.", terms)
427
- # "machine learning" wins on the first occurrence (longest-first ordering).
 
428
  assert '<mark class="kt" title="ML β€” pattern recognition">machine learning</mark>' in out
429
  # "machine" gets a mark too β€” but NOT nested inside the longer wrap.
430
  assert '<mark class="kt" title="a generic machine">machine</mark>' in out
431
- # Crucially: no nested <mark> tag inside the "machine learning" wrap.
432
- assert '"><mark' not in out
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
433
 
434
 
435
  def test_highlight_terms_skips_short_terms_and_handles_empty_list():
 
424
  KeyTerm(term="machine", definition="a generic machine"),
425
  ]
426
  out = _highlight_terms("A machine learning system uses machine learning daily.", terms)
427
+ # Without a glossary, falls back to <mark>. "machine learning" wins on
428
+ # the first occurrence (longest-first ordering).
429
  assert '<mark class="kt" title="ML β€” pattern recognition">machine learning</mark>' in out
430
  # "machine" gets a mark too β€” but NOT nested inside the longer wrap.
431
  assert '<mark class="kt" title="a generic machine">machine</mark>' in out
432
+ # No nested wrap of any shape inside the longer wrap.
433
+ assert '"><mark' not in out and '"><a class="kt"' not in out
434
+
435
+
436
+ def test_highlight_terms_emits_glossary_links_when_glossary_provided():
437
+ """With a glossary lookup supplied, each highlight becomes an
438
+ <a href="#glossary-N"> link to the matching entry β€” focusable and
439
+ screen-reader navigable, unlike the <mark> + title= fallback.
440
+ """
441
+ from app.pipeline.html_gen import _highlight_terms
442
+ from app.pipeline.metadata import KeyTerm
443
+
444
+ terms = [KeyTerm(term="Heat pump", definition="Moves heat between in/outdoors.")]
445
+ glossary = [
446
+ {
447
+ "id": "glossary-1",
448
+ "term": "Heat pump",
449
+ "definition": "Moves heat between in/outdoors.",
450
+ "first_section_index": 0,
451
+ }
452
+ ]
453
+ out = _highlight_terms("The heat pump runs on electricity.", terms, glossary=glossary)
454
+ assert '<a class="kt" href="#glossary-1"' in out
455
+ assert 'title="Moves heat between in/outdoors."' in out
456
+ assert ">heat pump</a>" in out
457
+ # No <mark> fallback when a glossary id is available.
458
+ assert "<mark" not in out
459
+
460
+
461
+ def test_highlight_terms_falls_back_to_mark_when_term_not_in_glossary():
462
+ """A term that's defined for one segment but never made it into the
463
+ glossary (defensive case β€” shouldn't happen since _build_glossary
464
+ sees all segments) should still render as a <mark> rather than
465
+ crash or produce a broken href.
466
+ """
467
+ from app.pipeline.html_gen import _highlight_terms
468
+ from app.pipeline.metadata import KeyTerm
469
+
470
+ terms = [KeyTerm(term="Orphan", definition="Has no glossary entry.")]
471
+ glossary: list = [] # explicitly empty
472
+ out = _highlight_terms("An orphan term.", terms, glossary=glossary)
473
+ assert '<mark class="kt"' in out
474
+ assert "<a class=\"kt\"" not in out
475
 
476
 
477
  def test_highlight_terms_skips_short_terms_and_handles_empty_list():