@readium/guided-navigation 1.1.2 → 1.1.3

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/dist/a11y.js CHANGED
@@ -1 +1 @@
1
- import{normalizeWhitespace as c}from"./text.js";import{hasExplicitRole as b}from"./roles.js";function g(t){return!!(t.getAttribute("aria-hidden")==="true"||t.hasAttribute("hidden"))}function x(t){let s="";const a=r=>{r.nodeType===3&&(s+=r.nodeValue??"");for(let i=r.firstChild;i;i=i.nextSibling)a(i)};return a(t),s}function h(t){return c(x(t),!0).trim()}function d(t){let s="";const a=(r,i)=>{if(r.nodeType===3){s+=r.nodeValue??"";return}if(!(r.nodeType===1&&!i&&b(r)))for(let e=r.firstChild;e;e=e.nextSibling)a(e,!1)};return a(t,!0),s}function T(t){return c(d(t),!0).trim()}function w(t){if(g(t))return[null,!1];const s=(t.getAttribute("aria-labelledby")??"").trim();if(s){const e=[...new Set(s.split(/\s+/).filter(Boolean))],n=t.ownerDocument,l=e.map(o=>n.getElementById(o)).filter(o=>o!==null);if(l.length>0){let o="";l.forEach((f,p)=>{const m=f.getAttribute("aria-label");o+=m||d(f),p<l.length-1&&(o+=" ")});const u=c(o,!0).trim();if(u!=="")return[u,!0]}}const a=(t.getAttribute("aria-label")??"").trim();if(a)return[a,!0];const r=(t.getAttribute("aria-describedby")??"").trim();if(r){const n=[...new Set(r.split(/\s+/).filter(Boolean))].map(l=>t.ownerDocument.getElementById(l)).filter(l=>l!==null);if(n.length>0){const l=n.map(u=>d(u)).join(" "),o=c(l,!0).trim();if(o!=="")return[o,!0]}}const i=t.tagName.toLowerCase();if(i==="img"){const e=(t.getAttribute("alt")??"").trim();if(e)return[e,!0];const n=(t.getAttribute("title")??"").trim();if(n)return[n,!0]}else if(i==="svg"){const e=t.querySelector(":scope > title");if(e){const n=h(e);if(n)return[n,!0]}}else if(i==="math"){const e=(t.getAttribute("alttext")??"").trim();if(e)return[e,!0]}return[null,!0]}const y={em:["emphasis"],b:["emphasis"],i:["emphasis",{level:"reduced"}],strong:["emphasis",{level:"strong"}],br:["break"]};function S(t){return y[t]??["",void 0]}const B=new Set(["script","style","template","noscript","textarea","select","datalist","iframe","rt","rp","rtc"]);export{S as convertElementToSSMLTag,w as extractNodeAria,h as normalizedNodeText,T as normalizedNodeTextExcludingExplicitRoles,B as skippedElements};
1
+ import{normalizeWhitespace as m}from"./text.js";import{hasExplicitRole as w}from"./roles.js";import{nodeLanguage as c,sharedLanguage as g}from"./language.js";function y(t){return!!(t.getAttribute("aria-hidden")==="true"||t.hasAttribute("hidden"))}function p(t,o,a){let s="";const l=(r,n)=>{if(r.nodeType===3){const e=r.nodeValue??"";s+=e,e.trim()&&a.add(c(r.parentElement));return}if(!(o&&r.nodeType===1&&!n&&w(r)))for(let e=r.firstChild;e;e=e.nextSibling)l(e,!1)};return l(t,!0),s}function x(t,o){const a=new Set;return{text:m(p(t,o,a),!0).trim(),language:g(a)}}function A(t){return x(t,!1)}function z(t){return x(t,!0)}function B(t){if(y(t))return[null,!1,""];const o=(t.getAttribute("aria-labelledby")??"").trim();if(o){const r=[...new Set(o.split(/\s+/).filter(Boolean))],n=t.ownerDocument,e=r.map(i=>n.getElementById(i)).filter(i=>i!==null);if(e.length>0){let i="";const u=new Set;e.forEach((f,h)=>{const b=f.getAttribute("aria-label");b?(i+=b,u.add(c(f))):i+=p(f,!0,u),h<e.length-1&&(i+=" ")});const d=m(i,!0).trim();if(d!=="")return[d,!0,g(u)]}}const a=(t.getAttribute("aria-label")??"").trim();if(a)return[a,!0,c(t)];const s=(t.getAttribute("aria-describedby")??"").trim();if(s){const n=[...new Set(s.split(/\s+/).filter(Boolean))].map(e=>t.ownerDocument.getElementById(e)).filter(e=>e!==null);if(n.length>0){const e=new Set,i=n.map(d=>p(d,!0,e)).join(" "),u=m(i,!0).trim();if(u!=="")return[u,!0,g(e)]}}const l=t.tagName.toLowerCase();if(l==="img"){const r=(t.getAttribute("alt")??"").trim();if(r)return[r,!0,c(t)];const n=(t.getAttribute("title")??"").trim();if(n)return[n,!0,c(t)]}else if(l==="svg"){const r=t.querySelector(":scope > title");if(r){const{text:n,language:e}=A(r);if(n)return[n,!0,e]}}else if(l==="math"){const r=(t.getAttribute("alttext")??"").trim();if(r)return[r,!0,c(t)]}return[null,!0,""]}const S={em:["emphasis"],b:["emphasis"],i:["emphasis",{level:"reduced"}],strong:["emphasis",{level:"strong"}],br:["break"]};function N(t){return S[t]??["",void 0]}const L=new Set(["script","style","template","noscript","textarea","select","datalist","iframe","rt","rp","rtc"]);export{N as convertElementToSSMLTag,B as extractNodeAria,A as normalizedNodeText,z as normalizedNodeTextExcludingExplicitRoles,L as skippedElements};
package/dist/converter.js CHANGED
@@ -1 +1 @@
1
- import{hasExplicitRole as P,extractNodeRoles as F}from"./roles.js";import{skippedElements as W,extractNodeAria as B,normalizedNodeText as z,normalizedNodeTextExcludingExplicitRoles as O,convertElementToSSMLTag as H}from"./a11y.js";import{normalizeWhitespace as v,ctxEqual as I}from"./text.js";import{ssmlAttrEscape as A,ssmlTextEscape as L,startsWithBindingPunct as _}from"@readium/helpers";import{NavObject as w,isEmptyObj as D,finalizeToGuidedNavigationObject as q}from"./object.js";import{sniffMediaType as X,nodeLanguage as y,isInlineTag as G}from"./dom.js";import{encodeDomRangeFragment as U,encodeTextFragmentDirective as V}from"./textrefFragment.js";import{resolveRefs as Y}from"./href.js";import{rootAnchorSelector as J,textrefForSelector as S,selectorForElement as C}from"./selectorGenerator.js";import{generateDomRange as K}from"./domRangeGenerator.js";import{textFragmentDirectiveFor as Q}from"./textFragmentGenerator.js";import{normalizeTextrefOptions as Z}from"./options.js";import{IdAllocator as tt}from"./idAllocator.js";import{prescan as et}from"./prescan.js";import{pagebreak as st,noteref as it,link as rt}from"./elementHandlers.js";const nt="http://www.w3.org/1998/Math/MathML",ot=3,lt=1,at=new Set(["summary","dfn","span"]);function M(c,t){return at.has(c)&&t.length>0?!0:!G(c)}class b{constructor(t){this.ids=new Map,this.suppressed=new Set,this.idAlloc=new tt,this.noterefDepth=0,this.allowNode=null,this.selectorPredicate=null,this.domRangeEnabled=!1,this.textFragmentEnabled=!1,this.leafTextEnabled=!1,this.docRoot=null,this.selectorRoot=null,this.selectorRootAnchor=null,this.root=new w,this.current=this.root,this.foldedCaptions=new Set,this.segments=[],this.textAcc="",this.currentCtx={lang:"",tag:""},this.flowEndsWithSpace=!0,this.pendingChildren=[],this.flowFirstNode=null,this.flowFirstOffset=0,this.flowLastNode=null,this.flowLastOffset=0,this.lastFlowRange=null,this.lastFlowText=null,this.xmlParsed=t}spawnChild(t,e=1){const s=new b(this.xmlParsed);return s.ids=this.ids,s.suppressed=this.suppressed,s.idAlloc=this.idAlloc,s.noterefDepth=this.noterefDepth+e,s.allowNode=t,s.docRoot=this.docRoot,s.selectorRoot=this.selectorRoot,s.selectorRootAnchor=this.selectorRootAnchor,s.selectorPredicate=this.selectorPredicate,s.domRangeEnabled=this.domRangeEnabled,s.textFragmentEnabled=this.textFragmentEnabled,s.leafTextEnabled=this.leafTextEnabled,s}prescan(t){et(t,this.ids,this.suppressed)}convert(t){this.prescan(t),this.walk(t),this.flushText()}convertChildren(t){this.prescan(t);for(let e=t.firstChild;e;e=e.nextSibling)this.walk(e);this.flushText()}resultBuilders(){const t=this.root.finalize(e=>S(C(e,this.selectorRoot,this.selectorRootAnchor),e));return!t.children||t.children.length===0?D(t)?[]:[t]:t.children}result(){const t=this.resultBuilders();return this.baseHref&&t.forEach(e=>Y(e,this.baseHref)),t.map(q)}descend(t,e){const s=new w;s.el=t,s.noText=this.foldedCaptions.has(t)||(!P(t)||e.includes("caption"))&&this.current.noText,this.current.children.push(s),this.current.hasChildBlock=!0,this.current=s}appendChild(t){t.noText=this.current.noText,this.current.children.push(t)}walk(t){if(t.nodeType===ot){this.text(t);return}if(t.nodeType!==lt)return;const e=t,s=this.current,a=this.head(e);if(!a)for(let i=e.firstChild;i;i=i.nextSibling)this.walk(i);this.tail(e,a,s)}head(t){const e=t.tagName.toLowerCase();if(W.has(e)||this.suppressed.has(t)&&t!==this.allowNode)return!0;const[s,a]=B(t);if(!a&&t!==this.allowNode)return!0;const i=F(t);if((e==="img"||e==="svg")&&(i.includes("presentation")||s===null&&t.hasAttribute("alt")&&t.getAttribute("alt").trim()===""))return!0;if(e==="br")return this.current.noText||(this.closeSegment(),this.segments.push({kind:"break"}),this.flowEndsWithSpace=!0),!0;if(i.includes("pagebreak"))return!st(this,t,s,i);if(e==="a"&&i.includes("noteref")&&t.getAttribute("href"))return it(this,t,i),!0;if(e==="a"&&t.getAttribute("href"))return rt(this,t,i,s),!0;if(e==="img"){const o={role:i},n=t.getAttribute("src");return n&&(o.imgref=n),s&&(o.description=s),this.placeholder(t,"image",o),!0}if(e==="audio"||e==="video"){const o={role:i};let n=t.getAttribute("src");if(!n){const d=t.querySelector(":scope > source[src]");d&&(n=d.getAttribute("src"))}return e==="audio"?n&&(o.audioref=n):n&&(o.videoref=n),s&&(o.description=s),this.placeholder(t,e,o),!0}if(i.includes("image")||i.includes("math")){const o={role:i};if(s&&(o.description=s),i.includes("math")){if(t.namespaceURI===nt)o.text={plain:"",ssml:new XMLSerializer().serializeToString(t),language:""};else{const n=z(t);n&&(o.text={plain:n,ssml:"",language:""})}o.textref=S(C(t,this.selectorRoot,this.selectorRootAnchor),t)}return this.placeholder(t,i.includes("math")?"math":"image",o),!0}if(!M(e,i))return!1;this.flushText(),this.descend(t,i);const f=this.current.object;if(i.length>0&&(f.role=i),s)f.description=s,i.includes("figure")&&(this.current.noText=!0);else if(i.includes("figure")){const o=this.implicitCaptionOf(t);if(o){const n=O(o);n&&(f.description=n,this.current.noText=!0)}}else if(i.includes("table")){const o=this.implicitCaptionOf(t);if(o){const n=O(o);n&&(f.description=n,this.foldedCaptions.add(o))}}const m=t.getAttribute("id");return m&&(f.id=m),!1}implicitCaptionOf(t){for(let e=t.firstElementChild;e;e=e.nextElementSibling)if(F(e).includes("caption")&&!e.getAttribute("aria-labelledby"))return e;return null}tail(t,e,s){if(e)return;const a=t.tagName.toLowerCase(),i=F(t);if(!i.includes("pagebreak")&&M(a,i)){this.flushText(),this.current.hasChildBlock&&(this.lastFlowRange=null,this.lastFlowText=null);const f=this.leafTextEnabled&&i.length===0&&!!this.lastFlowText;(this.selectorPredicate?.(i)||f)&&this.applyTextref(t),this.current=s}}applyTextref(t){const e=this.current.object,s=C(t,this.selectorRoot,this.selectorRootAnchor);if(e.textref=S(s,t),this.domRangeEnabled&&this.lastFlowRange){const a=s?{el:t,selector:s}:void 0,i=K(this.lastFlowRange,this.selectorRoot,this.selectorRootAnchor,a);i&&(e.textref=U({...i,container:s}))}if(this.textFragmentEnabled&&this.lastFlowRange&&this.docRoot){const a=this.docRoot.createRange();a.setStart(...this.lastFlowRange.first),a.setEnd(...this.lastFlowRange.last);const i=Q(a);i&&(e.textref=`${e.textref??"#"}${V(i)}`)}}text(t){if(this.current.noText)return;const e=t.nodeValue??"";if(/^\s*$/.test(e)){(this.textAcc.length>0||this.segments.length>0)&&(this.textAcc+=v(e,this.flowEndsWithSpace),this.updateFlowSpace());return}const s=this.textContext(t);if(I(s,this.currentCtx)||(this.closeSegment(),this.currentCtx=s),this.textAcc+=v(e,this.flowEndsWithSpace),this.updateFlowSpace(),this.domRangeEnabled||this.textFragmentEnabled){const a=t;this.flowFirstNode===null&&(this.flowFirstNode=a,this.flowFirstOffset=e.search(/\S/)),this.flowLastNode=a,this.flowLastOffset=e.length-(e.match(/\s+$/)?.[0].length??0)}}textContext(t){const e={lang:y(t.parentElement),tag:""};for(let s=t.parentElement;s&&s!==this.current.el;s=s.parentElement){const[a,i]=H(s.tagName.toLowerCase());if(a&&a!=="break"){e.tag=a,e.attrs=i;break}}return e}updateFlowSpace(){this.textAcc.length>0&&(this.flowEndsWithSpace=this.textAcc.endsWith(" "))}closeSegment(){this.textAcc.length!==0&&(this.segments.push({kind:"text",text:this.textAcc,ctx:this.currentCtx}),this.textAcc="")}resetFlow(){this.segments=[],this.textAcc="",this.currentCtx={lang:"",tag:""},this.flowEndsWithSpace=!0,this.pendingChildren=[],this.flowFirstNode=null,this.flowFirstOffset=0,this.flowLastNode=null,this.flowLastOffset=0}placeholder(t,e,s,a){if(D(s))return;const i=new w;if(i.el=t,i.object=s,this.current.noText){this.appendChild(i);return}this.closeSegment(),this.pendingChildren.push(i),this.segments.push({kind:"placeholder",tag:e,child:i,candidateID:a??t.getAttribute("id")??void 0}),this.flowEndsWithSpace=!1}flushText(){this.closeSegment();let t=this.segments;const e=this.pendingChildren,s=this.flowFirstNode,a=this.flowFirstOffset,i=this.flowLastNode,f=this.flowLastOffset;if(this.resetFlow(),this.lastFlowRange=null,this.lastFlowText=null,t.length===0)return;for(;t.length>0;){const r=t[0];if(r.kind==="break"){t=t.slice(1);continue}if(r.kind==="text"){const l=r.text.replace(/^\s+/,"");if(l===""){t=t.slice(1);continue}t=[{...r,text:l},...t.slice(1)]}break}for(;t.length>0;){const r=t[t.length-1];if(r.kind==="break"){t=t.slice(0,-1);continue}if(r.kind==="text"){const l=r.text.replace(/\s+$/,"");if(l===""){t=t.slice(0,-1);continue}t=[...t.slice(0,-1),{...r,text:l}]}break}if(!t.some(r=>r.kind==="text"&&r.text.trim()!=="")){for(const r of e)this.appendChild(r);return}const o=[];for(const r of t)if(r.kind==="text"&&r.text.trim()!==""){const l=r.ctx.lang;o.includes(l)||o.push(l)}let n=y(this.current.el??null);o.length===1&&o[0]!==""&&(n=o[0]);let d=!1;for(const r of t)if(r.kind!=="text"||r.ctx.tag!==""||r.ctx.lang!==n){d=!0;break}if(d&&n===""&&(n="en"),d)for(const r of t){if(r.kind!=="placeholder")continue;let l=r.candidateID;(!l||!this.idAlloc.claim(l))&&(l=this.idAlloc.allocate(r.tag,g=>this.ids.has(g))),r.child.object.id=l}let u="",h=!1,E=!1,T=!1,R=!1;for(const r of t)if(r.kind==="text"){const l=r.text.startsWith(" "),g=r.text.replace(/^ +| +$/g,"");if(g===""){R=!0;continue}let p=!1;if(u.length>0){const x=h||R||l;E?p=!0:T?p=x&&!_(g):p=x}p&&(u+=" "),u+=g,h=r.text.endsWith(" "),E=!1,T=!1,R=!1}else r.kind==="break"?E=!0:r.kind==="placeholder"&&(T=!0);const $=t.some(r=>r.kind==="placeholder");this.lastFlowText=u.trim();const N={plain:d&&!$?"":u.trim(),ssml:"",language:n};if(d){let r="";for(const l of t)if(l.kind==="text"){let g=l.ctx.tag,p=l.ctx.attrs;if(l.ctx.lang!==n&&l.ctx.lang!==""&&(g="lang",p=void 0),g){r+=`<${g}`;for(const[x,j]of Object.entries(p??{}))r+=` ${x}="${A(j)}"`;l.ctx.lang!==n&&l.ctx.lang!==""&&(r+=` xml:lang="${A(l.ctx.lang)}"`),r+=`>${L(l.text)}</${g}>`}else r+=L(l.text)}else l.kind==="break"?r+="<break/>":l.kind==="placeholder"&&(r+=`<readium:${l.tag} id="${A(l.child.object.id)}" />`);N.ssml=r}const k=new w;k.object={text:N};for(const r of e)k.children.push(r);this.appendChild(k),s&&i&&(this.lastFlowRange={first:[s,a],last:[i,f]})}}const ct=/<body[\s>]/i;function At(c,t,e){const{predicate:s,leafText:a,domRange:i,textFragment:f}=Z(e?.textrefs);if(typeof c!="string"){const u=t??(c.ownerDocument.contentType==="text/html"?"text/html":"application/xhtml+xml"),h=new b(u==="application/xhtml+xml");return h.selectorPredicate=s,h.leafTextEnabled=a,h.domRangeEnabled=i,h.textFragmentEnabled=f,h.docRoot=c.ownerDocument,h.baseHref=e?.href,h.selectorRoot=c,h.selectorRootAnchor=J(c),h.convert(c),h.result()}let m=t??X(c),o=new DOMParser().parseFromString(c,m);if(m==="application/xhtml+xml"){const u=o.getElementsByTagNameNS("*","parsererror")[0];if(u){if(!e?.htmlFallback)throw new Error(`XHTML parsing failed: ${u.textContent?.trim()??""}`);m="text/html",o=new DOMParser().parseFromString(c,m)}}const n=new b(m==="application/xhtml+xml");n.selectorPredicate=s,n.leafTextEnabled=a,n.textFragmentEnabled=f,n.docRoot=o,n.baseHref=e?.href;const d=o.querySelector("body");return d&&!ct.test(c)?n.convertChildren(d):n.convert(d??o.documentElement),n.result()}export{b as Converter,At as parseMarkup};
1
+ import{hasExplicitRole as z,extractNodeRoles as A}from"./roles.js";import{skippedElements as H,extractNodeAria as I,normalizedNodeText as _,normalizedNodeTextExcludingExplicitRoles as D,convertElementToSSMLTag as q}from"./a11y.js";import{normalizeWhitespace as y,ctxEqual as X}from"./text.js";import{ssmlAttrEscape as S,ssmlTextEscape as M,startsWithBindingPunct as G}from"@readium/helpers";import{NavObject as b,isEmptyObj as $,finalizeToGuidedNavigationObject as U,setDescription as x}from"./object.js";import{sniffMediaType as V,isInlineTag as Y}from"./dom.js";import{nodeLanguage as J,declaredLanguage as j,sameLanguage as C}from"./language.js";import{encodeDomRangeFragment as K,encodeTextFragmentDirective as Q}from"./textrefFragment.js";import{resolveRefs as Z}from"./href.js";import{rootAnchorSelector as tt,textrefForSelector as N,selectorForElement as v}from"./selectorGenerator.js";import{generateDomRange as et}from"./domRangeGenerator.js";import{textFragmentDirectiveFor as st}from"./textFragmentGenerator.js";import{normalizeTextrefOptions as it}from"./options.js";import{IdAllocator as rt}from"./idAllocator.js";import{prescan as nt}from"./prescan.js";import{pagebreak as ot,noteref as lt,link as at}from"./elementHandlers.js";const ct="http://www.w3.org/1998/Math/MathML",ht=3,ft=1,dt=new Set(["summary","dfn","span"]);function P(d,t){return dt.has(d)&&t.length>0?!0:!Y(d)}class E{constructor(t){this.ids=new Map,this.suppressed=new Set,this.idAlloc=new rt,this.noterefDepth=0,this.allowNode=null,this.selectorPredicate=null,this.domRangeEnabled=!1,this.textFragmentEnabled=!1,this.leafTextEnabled=!1,this.docRoot=null,this.selectorRoot=null,this.selectorRootAnchor=null,this.root=new b,this.current=this.root,this.foldedCaptions=new Set,this.segments=[],this.textAcc="",this.currentCtx={lang:void 0,tag:""},this.flowEndsWithSpace=!0,this.pendingChildren=[],this.flowFirstNode=null,this.flowFirstOffset=0,this.flowLastNode=null,this.flowLastOffset=0,this.lastFlowRange=null,this.lastFlowText=null,this.xmlParsed=t}spawnChild(t,e=1){const s=new E(this.xmlParsed);return s.ids=this.ids,s.suppressed=this.suppressed,s.idAlloc=this.idAlloc,s.noterefDepth=this.noterefDepth+e,s.allowNode=t,s.docRoot=this.docRoot,s.selectorRoot=this.selectorRoot,s.selectorRootAnchor=this.selectorRootAnchor,s.selectorPredicate=this.selectorPredicate,s.domRangeEnabled=this.domRangeEnabled,s.textFragmentEnabled=this.textFragmentEnabled,s.leafTextEnabled=this.leafTextEnabled,s}prescan(t){nt(t,this.ids,this.suppressed)}convert(t){this.prescan(t),this.walk(t),this.flushText()}convertChildren(t){this.prescan(t);for(let e=t.firstChild;e;e=e.nextSibling)this.walk(e);this.flushText()}resultBuilders(){const t=this.root.finalize(e=>N(v(e,this.selectorRoot,this.selectorRootAnchor),e));return!t.children||t.children.length===0?$(t)?[]:[t]:t.children}result(){const t=this.resultBuilders();return this.baseHref&&t.forEach(e=>Z(e,this.baseHref)),t.map(U)}descend(t,e){const s=new b;s.el=t,s.noText=this.foldedCaptions.has(t)||(!z(t)||e.includes("caption"))&&this.current.noText,this.current.children.push(s),this.current.hasChildBlock=!0,this.current=s}appendChild(t){t.noText=this.current.noText,this.current.children.push(t)}walk(t){if(t.nodeType===ht){this.text(t);return}if(t.nodeType!==ft)return;const e=t,s=this.current,c=this.head(e);if(!c)for(let n=e.firstChild;n;n=n.nextSibling)this.walk(n);this.tail(e,c,s)}head(t){const e=t.tagName.toLowerCase();if(H.has(e)||this.suppressed.has(t)&&t!==this.allowNode)return!0;const[s,c,n]=I(t);if(!c&&t!==this.allowNode)return!0;const a=A(t);if((e==="img"||e==="svg")&&(a.includes("presentation")||s===null&&t.hasAttribute("alt")&&t.getAttribute("alt").trim()===""))return!0;if(e==="br")return this.current.noText||(this.closeSegment(),this.segments.push({kind:"break"}),this.flowEndsWithSpace=!0),!0;if(a.includes("pagebreak"))return!ot(this,t,s,n,a);if(e==="a"&&a.includes("noteref")&&t.getAttribute("href"))return lt(this,t,a),!0;if(e==="a"&&t.getAttribute("href"))return at(this,t,a,s,n),!0;if(e==="img"){const r={role:a},o=t.getAttribute("src");return o&&(r.imgref=o),s&&x(r,s,n),this.placeholder(t,"image",r),!0}if(e==="audio"||e==="video"){const r={role:a};let o=t.getAttribute("src");if(!o){const h=t.querySelector(":scope > source[src]");h&&(o=h.getAttribute("src"))}return e==="audio"?o&&(r.audioref=o):o&&(r.videoref=o),s&&x(r,s,n),this.placeholder(t,e,r),!0}if(a.includes("image")||a.includes("math")){const r={role:a};if(s&&x(r,s,n),a.includes("math")){if(t.namespaceURI===ct)r.text={plain:"",ssml:new XMLSerializer().serializeToString(t),language:J(t)};else{const{text:o,language:h}=_(t);o&&(r.text={plain:o,ssml:"",language:h})}r.textref=N(v(t,this.selectorRoot,this.selectorRootAnchor),t)}return this.placeholder(t,a.includes("math")?"math":"image",r),!0}if(!P(e,a))return!1;this.flushText(),this.descend(t,a);const g=this.current.object;if(a.length>0&&(g.role=a),s)x(g,s,n),a.includes("figure")&&(this.current.noText=!0);else if(a.includes("figure")){const r=this.implicitCaptionOf(t);if(r){const{text:o,language:h}=D(r);o&&(x(g,o,h),this.current.noText=!0)}}else if(a.includes("table")){const r=this.implicitCaptionOf(t);if(r){const{text:o,language:h}=D(r);o&&(x(g,o,h),this.foldedCaptions.add(r))}}const u=t.getAttribute("id");return u&&(g.id=u),!1}implicitCaptionOf(t){for(let e=t.firstElementChild;e;e=e.nextElementSibling)if(A(e).includes("caption")&&!e.getAttribute("aria-labelledby"))return e;return null}tail(t,e,s){if(e)return;const c=t.tagName.toLowerCase(),n=A(t);if(!n.includes("pagebreak")&&P(c,n)){this.flushText(),this.current.hasChildBlock&&(this.lastFlowRange=null,this.lastFlowText=null);const a=this.leafTextEnabled&&n.length===0&&!!this.lastFlowText;(this.selectorPredicate?.(n)||a)&&this.applyTextref(t),this.current=s}}applyTextref(t){const e=this.current.object,s=v(t,this.selectorRoot,this.selectorRootAnchor);if(e.textref=N(s,t),this.domRangeEnabled&&this.lastFlowRange){const c=s?{el:t,selector:s}:void 0,n=et(this.lastFlowRange,this.selectorRoot,this.selectorRootAnchor,c);n&&(e.textref=K({...n,container:s}))}if(this.textFragmentEnabled&&this.lastFlowRange&&this.docRoot){const c=this.docRoot.createRange();c.setStart(...this.lastFlowRange.first),c.setEnd(...this.lastFlowRange.last);const n=st(c);n&&(e.textref=`${e.textref??"#"}${Q(n)}`)}}text(t){if(this.current.noText)return;const e=t.nodeValue??"";if(/^\s*$/.test(e)){(this.textAcc.length>0||this.segments.length>0)&&(this.textAcc+=y(e,this.flowEndsWithSpace),this.updateFlowSpace());return}const s=this.textContext(t);if(X(s,this.currentCtx)||(this.closeSegment(),this.currentCtx=s),this.textAcc+=y(e,this.flowEndsWithSpace),this.updateFlowSpace(),this.domRangeEnabled||this.textFragmentEnabled){const c=t;this.flowFirstNode===null&&(this.flowFirstNode=c,this.flowFirstOffset=e.search(/\S/)),this.flowLastNode=c,this.flowLastOffset=e.length-(e.match(/\s+$/)?.[0].length??0)}}textContext(t){const e={lang:j(t.parentElement),tag:""};for(let s=t.parentElement;s&&s!==this.current.el;s=s.parentElement){const[c,n]=q(s.tagName.toLowerCase());if(c&&c!=="break"){e.tag=c,e.attrs=n;break}}return e}updateFlowSpace(){this.textAcc.length>0&&(this.flowEndsWithSpace=this.textAcc.endsWith(" "))}closeSegment(){this.textAcc.length!==0&&(this.segments.push({kind:"text",text:this.textAcc,ctx:this.currentCtx}),this.textAcc="")}resetFlow(){this.segments=[],this.textAcc="",this.currentCtx={lang:void 0,tag:""},this.flowEndsWithSpace=!0,this.pendingChildren=[],this.flowFirstNode=null,this.flowFirstOffset=0,this.flowLastNode=null,this.flowLastOffset=0}placeholder(t,e,s,c){if($(s))return;const n=new b;if(n.el=t,n.object=s,this.current.noText){this.appendChild(n);return}this.closeSegment(),this.pendingChildren.push(n),this.segments.push({kind:"placeholder",tag:e,child:n,candidateID:c??t.getAttribute("id")??void 0}),this.flowEndsWithSpace=!1}flushText(){this.closeSegment();let t=this.segments;const e=this.pendingChildren,s=this.flowFirstNode,c=this.flowFirstOffset,n=this.flowLastNode,a=this.flowLastOffset;if(this.resetFlow(),this.lastFlowRange=null,this.lastFlowText=null,t.length===0)return;for(;t.length>0;){const i=t[0];if(i.kind==="break"){t=t.slice(1);continue}if(i.kind==="text"){const l=i.text.replace(/^\s+/,"");if(l===""){t=t.slice(1);continue}t=[{...i,text:l},...t.slice(1)]}break}for(;t.length>0;){const i=t[t.length-1];if(i.kind==="break"){t=t.slice(0,-1);continue}if(i.kind==="text"){const l=i.text.replace(/\s+$/,"");if(l===""){t=t.slice(0,-1);continue}t=[...t.slice(0,-1),{...i,text:l}]}break}if(!t.some(i=>i.kind==="text"&&i.text.trim()!=="")){for(const i of e)this.appendChild(i);return}const u=[];for(const i of t)if(i.kind==="text"&&i.text.trim()!==""){const l=i.ctx.lang;u.some(m=>C(m,l))||u.push(l)}let r=j(this.current.el??null);u.length===1&&(r=u[0]);let o=!1;for(const i of t)if(i.kind!=="text"||i.ctx.tag!==""||!C(i.ctx.lang,r)){o=!0;break}o&&r===void 0&&(r="en");const h=i=>i!==void 0&&!C(i,r);if(o)for(const i of t){if(i.kind!=="placeholder")continue;let l=i.candidateID;(!l||!this.idAlloc.claim(l))&&(l=this.idAlloc.allocate(i.tag,m=>this.ids.has(m))),i.child.object.id=l}let f="",L=!1,T=!1,R=!1,k=!1;for(const i of t)if(i.kind==="text"){const l=i.text.startsWith(" "),m=i.text.replace(/^ +| +$/g,"");if(m===""){k=!0;continue}let p=!1;if(f.length>0){const w=L||k||l;T?p=!0:R?p=w&&!G(m):p=w}p&&(f+=" "),f+=m,L=i.text.endsWith(" "),T=!1,R=!1,k=!1}else i.kind==="break"?T=!0:i.kind==="placeholder"&&(R=!0);const W=t.some(i=>i.kind==="placeholder");this.lastFlowText=f.trim();const O={plain:o&&!W?"":f.trim(),ssml:"",language:r??""};if(o){let i="";for(const l of t)if(l.kind==="text"){let m=l.ctx.tag,p=l.ctx.attrs;if(h(l.ctx.lang)&&(m="lang",p=void 0),m){i+=`<${m}`;for(const[w,B]of Object.entries(p??{}))i+=` ${w}="${S(B)}"`;h(l.ctx.lang)&&(i+=` xml:lang="${S(l.ctx.lang)}"`),i+=`>${M(l.text)}</${m}>`}else i+=M(l.text)}else l.kind==="break"?i+="<break/>":l.kind==="placeholder"&&(i+=`<readium:${l.tag} id="${S(l.child.object.id)}" />`);O.ssml=i}const F=new b;F.object={text:O};for(const i of e)F.children.push(i);this.appendChild(F),s&&n&&(this.lastFlowRange={first:[s,c],last:[n,a]})}}const ut=/<body[\s>]/i;function Lt(d,t,e){const{predicate:s,leafText:c,domRange:n,textFragment:a}=it(e?.textrefs);if(typeof d!="string"){const h=t??(d.ownerDocument.contentType==="text/html"?"text/html":"application/xhtml+xml"),f=new E(h==="application/xhtml+xml");return f.selectorPredicate=s,f.leafTextEnabled=c,f.domRangeEnabled=n,f.textFragmentEnabled=a,f.docRoot=d.ownerDocument,f.baseHref=e?.href,f.selectorRoot=d,f.selectorRootAnchor=tt(d),f.convert(d),f.result()}let g=t??V(d),u=new DOMParser().parseFromString(d,g);if(g==="application/xhtml+xml"){const h=u.getElementsByTagNameNS("*","parsererror")[0];if(h){if(!e?.htmlFallback)throw new Error(`XHTML parsing failed: ${h.textContent?.trim()??""}`);g="text/html",u=new DOMParser().parseFromString(d,g)}}const r=new E(g==="application/xhtml+xml");r.selectorPredicate=s,r.leafTextEnabled=c,r.textFragmentEnabled=a,r.docRoot=u,r.baseHref=e?.href;const o=u.querySelector("body");return o&&!ut.test(d)?r.convertChildren(o):r.convert(o??u.documentElement),r.result()}export{E as Converter,Lt as parseMarkup};
package/dist/dom.js CHANGED
@@ -1 +1 @@
1
- function i(e){for(let t=e;t;t=t.parentElement){const n=t.getAttribute("xml:lang");if(n)return n;const r=t.getAttribute("lang");if(r)return r}return""}function s(e){for(let t=e.firstChild;t;t=t.nextSibling)if(t.nodeType===1)return!0;return!1}function o(e,t){for(let n=t;n;n=n.parentElement)if(n===e)return!0;return!1}const a=new Set(["object","base","font","tt","i","b","u","big","small","em","strong","dfn","code","samp","kbd","var","cite","abbr","time","acronym","mark","ruby","rt","rp","rtc","a","img","br","wbr","map","q","sub","sup","bdo","iframe","embed","span","input","select","textarea","label","button","optgroup","option","legend","datalist","keygen","output","progress","meter","area","param","source","track","summary","command","basefont","bgsound","menuitem","data","bdi","s","strike","nobr","rb"]);function u(e){return a.has(e)}function l(e){const t=e.slice(0,500);return/<\?xml\b/.test(t)||/xmlns:epub=/.test(t)||/DOCTYPE\s+html\s+PUBLIC\s+"-\/\/W3C\/\/DTD XHTML/i.test(t)?"application/xhtml+xml":"text/html"}export{s as hasElementChild,o as isAncestorOf,u as isInlineTag,i as nodeLanguage,l as sniffMediaType};
1
+ function s(e){for(let t=e.firstChild;t;t=t.nextSibling)if(t.nodeType===1)return!0;return!1}function a(e,t){for(let n=t;n;n=n.parentElement)if(n===e)return!0;return!1}const r=new Set(["object","base","font","tt","i","b","u","big","small","em","strong","dfn","code","samp","kbd","var","cite","abbr","time","acronym","mark","ruby","rt","rp","rtc","a","img","br","wbr","map","q","sub","sup","bdo","iframe","embed","span","input","select","textarea","label","button","optgroup","option","legend","datalist","keygen","output","progress","meter","area","param","source","track","summary","command","basefont","bgsound","menuitem","data","bdi","s","strike","nobr","rb"]);function i(e){return r.has(e)}function o(e){const t=e.slice(0,500);return/<\?xml\b/.test(t)||/xmlns:epub=/.test(t)||/DOCTYPE\s+html\s+PUBLIC\s+"-\/\/W3C\/\/DTD XHTML/i.test(t)?"application/xhtml+xml":"text/html"}export{s as hasElementChild,a as isAncestorOf,i as isInlineTag,o as sniffMediaType};
@@ -1 +1 @@
1
- import{normalizedNodeText as d}from"./a11y.js";import{textIsEmpty as m}from"./text.js";import{ariaSubstitutedBuilders as g,substitutedOwnSelectorBuilders as p}from"./object.js";import{hasElementChild as x,isAncestorOf as b}from"./dom.js";import{selectorForElement as u,textrefForSelector as A}from"./selectorGenerator.js";function E(s,e,n,l){const t={role:l},i=(e.getAttribute("title")??"").trim();i?t.text={plain:i,ssml:"",language:""}:n&&(t.text={plain:n,ssml:"",language:""},g.add(t));const o=!!(t.text&&!m(t.text)),r=!s.xmlParsed&&(x(e)||o&&e.firstChild!==null);if(!o&&!r){const c=d(e);c&&(t.text={plain:c,ssml:"",language:""})}const f=u(e,s.selectorRoot,s.selectorRootAnchor),a=A(f,e);return a&&(t.textref=a),s.placeholder(e,"pagebreak",t),r}function S(s,e,n){const l={role:n},t=d(e);t&&(l.text={plain:t,ssml:"",language:""});const i=e.getAttribute("href")??"";let o=e.getAttribute("id")??"";if(!o&&i.startsWith("#")){const r=s.ids.get(i.slice(1));(!r||s.suppressed.has(r))&&(o=i.slice(1))}if(i.startsWith("#")){const r=i.slice(1),f=s.ids.get(r);if(f&&!b(f,e)&&s.noterefDepth<3){const a=s.spawnChild(f);a.convert(f);const c=a.resultBuilders();if(c.length>0){for(const h of c)delete h.id;l.children=c}}}!l.children&&i&&(l.children=[{textref:i}]),s.placeholder(e,"noteref",l,o||void 0)}function w(s,e,n,l){const t={};if(n.length>0&&(t.role=n),l){t.text={plain:l,ssml:"",language:""},g.add(t);const o=u(e,s.selectorRoot,s.selectorRootAnchor);o&&p.set(t,o)}else{const o=d(e);o&&(t.text={plain:o,ssml:"",language:""})}const i=e.getAttribute("href");i&&(t.textref=i),s.placeholder(e,n[0]??"link",t)}export{w as link,S as noteref,E as pagebreak};
1
+ import{normalizedNodeText as u}from"./a11y.js";import{textIsEmpty as p}from"./text.js";import{ariaSubstitutedBuilders as m,substitutedOwnSelectorBuilders as x}from"./object.js";import{hasElementChild as b,isAncestorOf as A}from"./dom.js";import{nodeLanguage as k}from"./language.js";import{selectorForElement as h,textrefForSelector as R}from"./selectorGenerator.js";function D(s,t,r,n,f){const e={role:f},i=(t.getAttribute("title")??"").trim();i?e.text={plain:i,ssml:"",language:k(t)}:r&&(e.text={plain:r,ssml:"",language:n},m.add(e));const o=!!(e.text&&!p(e.text)),l=!s.xmlParsed&&(b(t)||o&&t.firstChild!==null);if(!o&&!l){const{text:c,language:g}=u(t);c&&(e.text={plain:c,ssml:"",language:g})}const a=h(t,s.selectorRoot,s.selectorRootAnchor),d=R(a,t);return d&&(e.textref=d),s.placeholder(t,"pagebreak",e),l}function F(s,t,r){const n={role:r},{text:f,language:e}=u(t);f&&(n.text={plain:f,ssml:"",language:e});const i=t.getAttribute("href")??"";let o=t.getAttribute("id")??"";if(!o&&i.startsWith("#")){const l=s.ids.get(i.slice(1));(!l||s.suppressed.has(l))&&(o=i.slice(1))}if(i.startsWith("#")){const l=i.slice(1),a=s.ids.get(l);if(a&&!A(a,t)&&s.noterefDepth<3){const d=s.spawnChild(a);d.convert(a);const c=d.resultBuilders();if(c.length>0){for(const g of c)delete g.id;n.children=c}}}!n.children&&i&&(n.children=[{textref:i}]),s.placeholder(t,"noteref",n,o||void 0)}function I(s,t,r,n,f){const e={};if(r.length>0&&(e.role=r),n){e.text={plain:n,ssml:"",language:f},m.add(e);const o=h(t,s.selectorRoot,s.selectorRootAnchor);o&&x.set(e,o)}else{const{text:o,language:l}=u(t);o&&(e.text={plain:o,ssml:"",language:l})}const i=t.getAttribute("href");i&&(e.textref=i),s.placeholder(t,r[0]??"link",e)}export{I as link,F as noteref,D as pagebreak};
@@ -0,0 +1 @@
1
+ const r="http://www.w3.org/XML/1998/namespace";function a(t){return t.getAttributeNS(r,"lang")??(t.getAttribute("xml:lang")?.trim()||null)??t.getAttribute("lang")}function o(t){for(let n=t;n;n=n.parentElement){const e=a(n);if(e!==null)return e.trim()}}function g(t){return o(t)??""}function u(t,n){return t===n||t!==void 0&&n!==void 0&&t.toLowerCase()===n.toLowerCase()}function i(t){let n;for(const e of t)if(n===void 0)n=e;else if(!u(n,e))return"";return n??""}export{o as declaredLanguage,g as nodeLanguage,u as sameLanguage,i as sharedLanguage};
package/dist/object.js CHANGED
@@ -1 +1 @@
1
- import{GuidedNavigationObject as h,GuidedNavigationDescription as u,GuidedNavigationText as a}from"@readium/shared";import{textIsEmpty as l,finalizeText as o}from"./text.js";const x=["math","separator"],g=new WeakSet,s=new WeakSet,p=new WeakMap,f=new WeakMap;function N(e){return s.has(e)}function j(e){return f.get(e)}function c(e){return e.role?.some(n=>x.includes(n))?!1:!e.audioref&&!e.imgref&&!e.textref&&!e.videoref&&(!e.text||l(e.text))&&!(e.children&&e.children.length>0)&&!e.description}function v(e){return!e.audioref&&!e.imgref&&!e.textref&&!e.videoref&&(!e.text||l(e.text))&&!!(e.children&&e.children.length>0)&&!(e.role&&e.role.length>0)&&!e.id&&!e.description}function m(e){return!(e.role&&e.role.length>0)&&!e.id&&!e.description&&!e.textref&&!e.imgref&&!e.audioref&&!e.videoref}class k{constructor(){this.object={},this.children=[],this.noText=!1,this.hasChildBlock=!1}finalize(n){const t=this.object,d=[];for(const i of this.children){const r=i.finalize(n);if(!c(r)){if(v(r)){d.push(...r.children??[]);continue}d.push(r)}}if(d.length>0&&(t.children=d),t.role?.length&&t.children?.length===1&&!t.role.includes("presentation")){const i=t.children[0];i.role?.length&&t.role.every(r=>i.role.includes(r))&&delete t.role}if((!t.text||l(t.text))&&t.children?.length===1){const i=t.children[0];m(i)&&(i.text&&(t.text=i.text),t.children=i.children)}if(this.el&&n&&!c(t)&&!b(t)){const i=n(this.el);i&&(t.textref=i)}return t}}function b(e){return!!e.audioref||!!e.imgref||!!e.textref||!!e.videoref||!!(e.text&&(e.text.plain!==""||e.text.ssml!==""))||!!(e.children&&e.children.length>0)}function w(e){const n=new h({id:e.id||void 0,textref:e.textref||void 0,imgref:e.imgref||void 0,audioref:e.audioref||void 0,videoref:e.videoref||void 0,text:o(e.text),role:e.role&&e.role.length>0?new Set(e.role):void 0,children:e.children&&e.children.length>0?e.children.map(w):void 0,description:e.description?new u({text:new a({plain:e.description})}):void 0});g.has(e)&&s.add(n);const t=p.get(e);return t&&f.set(n,t),n}export{k as NavObject,g as ariaSubstitutedBuilders,w as finalizeToGuidedNavigationObject,N as isAriaSubstituted,c as isEmptyObj,j as substitutedOwnSelector,p as substitutedOwnSelectorBuilders};
1
+ import{GuidedNavigationObject as a,GuidedNavigationDescription as u,GuidedNavigationText as h}from"@readium/shared";import{textIsEmpty as l,finalizeText as o}from"./text.js";function N(e,n,t){e.description=n,e.descriptionLanguage=t}const g=["math","separator"],x=new WeakSet,s=new WeakSet,p=new WeakMap,f=new WeakMap;function j(e){return s.has(e)}function k(e){return f.get(e)}function c(e){return e.role?.some(n=>g.includes(n))?!1:!e.audioref&&!e.imgref&&!e.textref&&!e.videoref&&(!e.text||l(e.text))&&!(e.children&&e.children.length>0)&&!e.description}function v(e){return!e.audioref&&!e.imgref&&!e.textref&&!e.videoref&&(!e.text||l(e.text))&&!!(e.children&&e.children.length>0)&&!(e.role&&e.role.length>0)&&!e.id&&!e.description}function m(e){return!(e.role&&e.role.length>0)&&!e.id&&!e.description&&!e.textref&&!e.imgref&&!e.audioref&&!e.videoref}class y{constructor(){this.object={},this.children=[],this.noText=!1,this.hasChildBlock=!1}finalize(n){const t=this.object,d=[];for(const i of this.children){const r=i.finalize(n);if(!c(r)){if(v(r)){d.push(...r.children??[]);continue}d.push(r)}}if(d.length>0&&(t.children=d),t.role?.length&&t.children?.length===1&&!t.role.includes("presentation")){const i=t.children[0];i.role?.length&&t.role.every(r=>i.role.includes(r))&&delete t.role}if((!t.text||l(t.text))&&t.children?.length===1){const i=t.children[0];m(i)&&(i.text&&(t.text=i.text),t.children=i.children)}if(this.el&&n&&!c(t)&&!b(t)){const i=n(this.el);i&&(t.textref=i)}return t}}function b(e){return!!e.audioref||!!e.imgref||!!e.textref||!!e.videoref||!!(e.text&&(e.text.plain!==""||e.text.ssml!==""))||!!(e.children&&e.children.length>0)}function w(e){const n=new a({id:e.id||void 0,textref:e.textref||void 0,imgref:e.imgref||void 0,audioref:e.audioref||void 0,videoref:e.videoref||void 0,text:o(e.text),role:e.role&&e.role.length>0?new Set(e.role):void 0,children:e.children&&e.children.length>0?e.children.map(w):void 0,description:e.description?new u({text:new h({plain:e.description,language:e.descriptionLanguage||void 0})}):void 0});x.has(e)&&s.add(n);const t=p.get(e);return t&&f.set(n,t),n}export{y as NavObject,x as ariaSubstitutedBuilders,w as finalizeToGuidedNavigationObject,j as isAriaSubstituted,c as isEmptyObj,N as setDescription,k as substitutedOwnSelector,p as substitutedOwnSelectorBuilders};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@readium/guided-navigation",
3
- "version": "1.1.2",
3
+ "version": "1.1.3",
4
4
  "type": "module",
5
5
  "description": "Guided Navigation document generation from HTML and XHTML content",
6
6
  "author": "readium",
package/src/a11y.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { normalizeWhitespace } from "./text.ts";
2
2
  import { hasExplicitRole } from "./roles.ts";
3
+ import { nodeLanguage, sharedLanguage } from "./language.ts";
3
4
 
4
5
  function nodeIsHidden(el: Element): boolean {
5
6
  if (el.getAttribute("aria-hidden") === "true") return true;
@@ -7,42 +8,44 @@ function nodeIsHidden(el: Element): boolean {
7
8
  return false;
8
9
  }
9
10
 
10
- function nodeText(el: Node): string {
11
- let text = "";
12
- const walk = (n: Node) => {
13
- if (n.nodeType === 3 /* TEXT_NODE */) {
14
- text += n.nodeValue ?? "";
15
- }
16
- for (let c = n.firstChild; c; c = c.nextSibling) walk(c);
17
- };
18
- walk(el);
19
- return text;
11
+ export interface NodeText {
12
+ text: string;
13
+ // Shared by all of the text, unknown ("") when parts of it are in different languages.
14
+ language: string;
20
15
  }
21
16
 
22
- /** Normalized (whitespace-coalesced and trimmed) text content of a node's subtree. */
23
- export function normalizedNodeText(el: Node): string {
24
- return normalizeWhitespace(nodeText(el), true).trim();
25
- }
26
-
27
- // Same as `nodeText`, skipping descendants with an explicit role — those are
28
- // walked/spoken separately, so folding their text in here would double it up.
29
- function nodeTextExcludingExplicitRoles(root: Node): string {
17
+ // Raw text of a subtree, adding each non-blank text node's language to `languages`. Explicit-role
18
+ // descendants can be skipped: they're spoken separately, so their text would be doubled up.
19
+ function nodeText(root: Node, excludeExplicitRoles: boolean, languages: Set<string>): string {
30
20
  let text = "";
31
21
  const walk = (n: Node, isRoot: boolean) => {
32
22
  if (n.nodeType === 3 /* TEXT_NODE */) {
33
- text += n.nodeValue ?? "";
23
+ const value = n.nodeValue ?? "";
24
+ text += value;
25
+ if (value.trim()) languages.add(nodeLanguage(n.parentElement));
34
26
  return;
35
27
  }
36
- if (n.nodeType === 1 /* ELEMENT_NODE */ && !isRoot && hasExplicitRole(n as Element)) return;
28
+ if (excludeExplicitRoles && n.nodeType === 1 /* ELEMENT_NODE */ && !isRoot && hasExplicitRole(n as Element)) return;
37
29
  for (let c = n.firstChild; c; c = c.nextSibling) walk(c, false);
38
30
  };
39
31
  walk(root, true);
40
32
  return text;
41
33
  }
42
34
 
35
+ function normalizedText(root: Node, excludeExplicitRoles: boolean): NodeText {
36
+ const languages = new Set<string>();
37
+ const text = normalizeWhitespace(nodeText(root, excludeExplicitRoles, languages), true).trim();
38
+ return { text, language: sharedLanguage(languages) };
39
+ }
40
+
41
+ /** Normalized (whitespace-coalesced and trimmed) text content of a node's subtree, and its language. */
42
+ export function normalizedNodeText(el: Node): NodeText {
43
+ return normalizedText(el, false);
44
+ }
45
+
43
46
  /** Same as `normalizedNodeText`, excluding explicitly-role-bearing descendants. */
44
- export function normalizedNodeTextExcludingExplicitRoles(el: Node): string {
45
- return normalizeWhitespace(nodeTextExcludingExplicitRoles(el), true).trim();
47
+ export function normalizedNodeTextExcludingExplicitRoles(el: Node): NodeText {
48
+ return normalizedText(el, true);
46
49
  }
47
50
 
48
51
  /**
@@ -51,11 +54,12 @@ export function normalizedNodeTextExcludingExplicitRoles(el: Node): string {
51
54
  * precedence order (https://www.w3.org/TR/accname/#terminology, 2.A-2.D)
52
55
  * for its accessible-name sources, with a non-AccName `aria-describedby`
53
56
  * fallback spliced in between 2.C and 2.D — see that branch below.
57
+ * Also returns that text's language.
54
58
  */
55
- export function extractNodeAria(el: Element): [string | null, boolean] {
59
+ export function extractNodeAria(el: Element): [string | null, boolean, string] {
56
60
  // 2.A
57
61
  if (nodeIsHidden(el)) {
58
- return [null, false];
62
+ return [null, false, ""];
59
63
  }
60
64
 
61
65
  // 2.B
@@ -69,15 +73,21 @@ export function extractNodeAria(el: Element): [string | null, boolean] {
69
73
 
70
74
  if (labelNodes.length > 0) {
71
75
  let text = "";
76
+ const languages = new Set<string>();
72
77
  // Directly-referenced label nodes count even when hidden (AccName 2.A).
73
78
  labelNodes.forEach((n, i) => {
74
79
  const label = n.getAttribute("aria-label");
75
- text += label ? label : nodeTextExcludingExplicitRoles(n);
80
+ if (label) {
81
+ text += label;
82
+ languages.add(nodeLanguage(n));
83
+ } else {
84
+ text += nodeText(n, true, languages);
85
+ }
76
86
  if (i < labelNodes.length - 1) text += " ";
77
87
  });
78
88
  const normalized = normalizeWhitespace(text, true).trim();
79
89
  if (normalized !== "") {
80
- return [normalized, true];
90
+ return [normalized, true, sharedLanguage(languages)];
81
91
  }
82
92
  }
83
93
  }
@@ -85,7 +95,7 @@ export function extractNodeAria(el: Element): [string | null, boolean] {
85
95
  // 2.C
86
96
  const label = (el.getAttribute("aria-label") ?? "").trim();
87
97
  if (label) {
88
- return [label, true];
98
+ return [label, true, nodeLanguage(el)];
89
99
  }
90
100
 
91
101
  // Not part of the AccName algorithm proper (which computes a name, not a
@@ -99,10 +109,11 @@ export function extractNodeAria(el: Element): [string | null, boolean] {
99
109
  .map((id) => el.ownerDocument.getElementById(id))
100
110
  .filter((n): n is HTMLElement => n !== null);
101
111
  if (nodes.length > 0) {
102
- const text = nodes.map((n) => nodeTextExcludingExplicitRoles(n)).join(" ");
112
+ const languages = new Set<string>();
113
+ const text = nodes.map((n) => nodeText(n, true, languages)).join(" ");
103
114
  const normalized = normalizeWhitespace(text, true).trim();
104
115
  if (normalized !== "") {
105
- return [normalized, true];
116
+ return [normalized, true, sharedLanguage(languages)];
106
117
  }
107
118
  }
108
119
  }
@@ -111,24 +122,24 @@ export function extractNodeAria(el: Element): [string | null, boolean] {
111
122
  const tagName = el.tagName.toLowerCase();
112
123
  if (tagName === "img") {
113
124
  const alt = (el.getAttribute("alt") ?? "").trim();
114
- if (alt) return [alt, true];
125
+ if (alt) return [alt, true, nodeLanguage(el)];
115
126
  // 2.I fallback for images: the title attribute
116
127
  const title = (el.getAttribute("title") ?? "").trim();
117
- if (title) return [title, true];
128
+ if (title) return [title, true, nodeLanguage(el)];
118
129
  } else if (tagName === "svg") {
119
130
  // The accessible name of an SVG comes from its <title> child
120
131
  const title = el.querySelector(":scope > title");
121
132
  if (title) {
122
- const text = normalizedNodeText(title);
123
- if (text) return [text, true];
133
+ const { text, language } = normalizedNodeText(title);
134
+ if (text) return [text, true, language];
124
135
  }
125
136
  } else if (tagName === "math") {
126
137
  // MathML Core's spoken-form fallback (not part of the ARIA AccName algorithm)
127
138
  const alttext = (el.getAttribute("alttext") ?? "").trim();
128
- if (alttext) return [alttext, true];
139
+ if (alttext) return [alttext, true, nodeLanguage(el)];
129
140
  }
130
141
 
131
- return [null, true];
142
+ return [null, true, ""];
132
143
  }
133
144
 
134
145
  const ssmlTags: Record<string, [string, Record<string, string>?]> = {
package/src/converter.ts CHANGED
@@ -15,8 +15,9 @@ import {
15
15
  normalizeWhitespace,
16
16
  } from "./text.ts";
17
17
  import { ssmlAttrEscape, ssmlTextEscape, startsWithBindingPunct } from "@readium/helpers";
18
- import { type ObjBuilder, NavObject, isEmptyObj, finalizeToGuidedNavigationObject } from "./object.ts";
19
- import { type GndMediaType, nodeLanguage, isInlineTag, sniffMediaType } from "./dom.ts";
18
+ import { type ObjBuilder, NavObject, isEmptyObj, finalizeToGuidedNavigationObject, setDescription } from "./object.ts";
19
+ import { type GndMediaType, isInlineTag, sniffMediaType } from "./dom.ts";
20
+ import { declaredLanguage, nodeLanguage, sameLanguage } from "./language.ts";
20
21
  import { encodeDomRangeFragment, encodeTextFragmentDirective } from "./textrefFragment.ts";
21
22
  import { resolveRefs } from "./href.ts";
22
23
  import { rootAnchorSelector, selectorForElement, textrefForSelector } from "./selectorGenerator.ts";
@@ -89,7 +90,7 @@ export class Converter {
89
90
 
90
91
  private segments: Segment[] = [];
91
92
  private textAcc = "";
92
- private currentCtx: SSMLContext = { lang: "", tag: "" };
93
+ private currentCtx: SSMLContext = { lang: undefined, tag: "" };
93
94
  private flowEndsWithSpace = true;
94
95
  private pendingChildren: NavObject[] = [];
95
96
 
@@ -209,7 +210,7 @@ export class Converter {
209
210
  if (skippedElements.has(tagName)) return true;
210
211
  if (this.suppressed.has(el) && el !== this.allowNode) return true;
211
212
 
212
- const [aria, visible] = extractNodeAria(el);
213
+ const [aria, visible, ariaLanguage] = extractNodeAria(el);
213
214
  if (!visible && el !== this.allowNode) return true;
214
215
 
215
216
  const roles = extractNodeRoles(el);
@@ -232,7 +233,7 @@ export class Converter {
232
233
  }
233
234
 
234
235
  if (roles.includes("pagebreak")) {
235
- return !pagebreak(this, el, aria, roles);
236
+ return !pagebreak(this, el, aria, ariaLanguage, roles);
236
237
  }
237
238
  if (tagName === "a" && roles.includes("noteref") && el.getAttribute("href")) {
238
239
  noteref(this, el, roles);
@@ -245,14 +246,14 @@ export class Converter {
245
246
  // case for list items), the hoist rule promotes it onto that block;
246
247
  // otherwise it becomes an inline SSML placeholder like any other
247
248
  // embedded object.
248
- link(this, el, roles, aria);
249
+ link(this, el, roles, aria, ariaLanguage);
249
250
  return true;
250
251
  }
251
252
  if (tagName === "img") {
252
253
  const obj: ObjBuilder = { role: roles };
253
254
  const src = el.getAttribute("src");
254
255
  if (src) obj.imgref = src;
255
- if (aria) obj.description = aria;
256
+ if (aria) setDescription(obj, aria, ariaLanguage);
256
257
  this.placeholder(el, "image", obj);
257
258
  return true;
258
259
  }
@@ -268,7 +269,7 @@ export class Converter {
268
269
  } else if (src) {
269
270
  obj.videoref = src;
270
271
  }
271
- if (aria) obj.description = aria;
272
+ if (aria) setDescription(obj, aria, ariaLanguage);
272
273
  this.placeholder(el, tagName, obj);
273
274
  return true;
274
275
  }
@@ -276,14 +277,14 @@ export class Converter {
276
277
  // Elements acting as images without being one, e.g. <span role="img">:
277
278
  // their content is replaced by their accessible name.
278
279
  const obj: ObjBuilder = { role: roles };
279
- if (aria) obj.description = aria;
280
+ if (aria) setDescription(obj, aria, ariaLanguage);
280
281
  if (roles.includes("math")) {
281
282
  // MathML is carried as-is in SSML, other math markup as plain text.
282
283
  if (el.namespaceURI === MATHML_NS) {
283
- obj.text = { plain: "", ssml: new XMLSerializer().serializeToString(el), language: "" };
284
+ obj.text = { plain: "", ssml: new XMLSerializer().serializeToString(el), language: nodeLanguage(el) };
284
285
  } else {
285
- const text = normalizedNodeText(el);
286
- if (text) obj.text = { plain: text, ssml: "", language: "" };
286
+ const { text, language } = normalizedNodeText(el);
287
+ if (text) obj.text = { plain: text, ssml: "", language };
287
288
  }
288
289
  obj.textref = textrefForSelector(selectorForElement(el, this.selectorRoot, this.selectorRootAnchor), el);
289
290
  }
@@ -301,7 +302,7 @@ export class Converter {
301
302
  const cur = this.current.object;
302
303
  if (roles.length > 0) cur.role = roles;
303
304
  if (aria) {
304
- cur.description = aria;
305
+ setDescription(cur, aria, ariaLanguage);
305
306
  if (roles.includes("figure")) {
306
307
  this.current.noText = true;
307
308
  }
@@ -310,18 +311,18 @@ export class Converter {
310
311
  if (caption) {
311
312
  // Not suppressed — walked normally so a nested explicit-role
312
313
  // descendant (e.g. a credit) still speaks.
313
- const text = normalizedNodeTextExcludingExplicitRoles(caption);
314
+ const { text, language } = normalizedNodeTextExcludingExplicitRoles(caption);
314
315
  if (text) {
315
- cur.description = text;
316
+ setDescription(cur, text, language);
316
317
  this.current.noText = true;
317
318
  }
318
319
  }
319
320
  } else if (roles.includes("table")) {
320
321
  const caption = this.implicitCaptionOf(el);
321
322
  if (caption) {
322
- const text = normalizedNodeTextExcludingExplicitRoles(caption);
323
+ const { text, language } = normalizedNodeTextExcludingExplicitRoles(caption);
323
324
  if (text) {
324
- cur.description = text;
325
+ setDescription(cur, text, language);
325
326
  this.foldedCaptions.add(caption);
326
327
  }
327
328
  }
@@ -422,7 +423,7 @@ export class Converter {
422
423
  }
423
424
 
424
425
  private textContext(node: Node): SSMLContext {
425
- const ctx: SSMLContext = { lang: nodeLanguage(node.parentElement), tag: "" };
426
+ const ctx: SSMLContext = { lang: declaredLanguage(node.parentElement), tag: "" };
426
427
  for (let p = node.parentElement; p && p !== this.current.el; p = p.parentElement) {
427
428
  const [tag, attrs] = convertElementToSSMLTag(p.tagName.toLowerCase());
428
429
  if (tag && tag !== "break") {
@@ -449,7 +450,7 @@ export class Converter {
449
450
  private resetFlow() {
450
451
  this.segments = [];
451
452
  this.textAcc = "";
452
- this.currentCtx = { lang: "", tag: "" };
453
+ this.currentCtx = { lang: undefined, tag: "" };
453
454
  this.flowEndsWithSpace = true;
454
455
  this.pendingChildren = [];
455
456
  this.flowFirstNode = null;
@@ -532,21 +533,21 @@ export class Converter {
532
533
  return;
533
534
  }
534
535
 
535
- const textLangs: string[] = [];
536
+ const textLangs: (string | undefined)[] = [];
536
537
  for (const seg of segments) {
537
538
  if (seg.kind === "text" && seg.text!.trim() !== "") {
538
539
  const lang = seg.ctx!.lang;
539
- if (!textLangs.includes(lang)) textLangs.push(lang);
540
+ if (!textLangs.some((other) => sameLanguage(other, lang))) textLangs.push(lang);
540
541
  }
541
542
  }
542
- let baseLang = nodeLanguage(this.current.el ?? null);
543
- if (textLangs.length === 1 && textLangs[0] !== "") {
543
+ let baseLang = declaredLanguage(this.current.el ?? null);
544
+ if (textLangs.length === 1) {
544
545
  baseLang = textLangs[0];
545
546
  }
546
547
 
547
548
  let needSSML = false;
548
549
  for (const seg of segments) {
549
- if (seg.kind !== "text" || seg.ctx!.tag !== "" || seg.ctx!.lang !== baseLang) {
550
+ if (seg.kind !== "text" || seg.ctx!.tag !== "" || !sameLanguage(seg.ctx!.lang, baseLang)) {
550
551
  needSSML = true;
551
552
  break;
552
553
  }
@@ -555,9 +556,11 @@ export class Converter {
555
556
  // Default to English when an SSML representation is required (mixed
556
557
  // formatting, embedded objects, or a language shift) but no explicit
557
558
  // language was declared anywhere in the document.
558
- if (needSSML && baseLang === "") {
559
+ if (needSSML && baseLang === undefined) {
559
560
  baseLang = "en";
560
561
  }
562
+ // Undeclared text is in the base language; an empty declaration is a shift to an unknown one.
563
+ const shiftsLanguage = (lang: string | undefined): lang is string => lang !== undefined && !sameLanguage(lang, baseLang);
561
564
 
562
565
  if (needSSML) {
563
566
  for (const seg of segments) {
@@ -613,7 +616,7 @@ export class Converter {
613
616
  const text: TextBuilder = {
614
617
  plain: needSSML && !hasPlaceholder ? "" : plainB.trim(),
615
618
  ssml: "",
616
- language: baseLang,
619
+ language: baseLang ?? "",
617
620
  };
618
621
 
619
622
  if (needSSML) {
@@ -622,7 +625,7 @@ export class Converter {
622
625
  if (seg.kind === "text") {
623
626
  let tag = seg.ctx!.tag;
624
627
  let attrs = seg.ctx!.attrs;
625
- if (seg.ctx!.lang !== baseLang && seg.ctx!.lang !== "") {
628
+ if (shiftsLanguage(seg.ctx!.lang)) {
626
629
  // A language shift takes priority over whatever SSML tag the
627
630
  // shifting element would otherwise map to.
628
631
  tag = "lang";
@@ -633,7 +636,7 @@ export class Converter {
633
636
  for (const [k, v] of Object.entries(attrs ?? {})) {
634
637
  sb += ` ${k}="${ssmlAttrEscape(v)}"`;
635
638
  }
636
- if (seg.ctx!.lang !== baseLang && seg.ctx!.lang !== "") {
639
+ if (shiftsLanguage(seg.ctx!.lang)) {
637
640
  sb += ` xml:lang="${ssmlAttrEscape(seg.ctx!.lang)}"`;
638
641
  }
639
642
  sb += `>${ssmlTextEscape(seg.text!)}</${tag}>`;
package/src/dom.ts CHANGED
@@ -1,15 +1,5 @@
1
1
  const ELEMENT_NODE = 1;
2
2
 
3
- export function nodeLanguage(el: Element | null): string {
4
- for (let n: Element | null = el; n; n = n.parentElement) {
5
- const xmlLang = n.getAttribute("xml:lang");
6
- if (xmlLang) return xmlLang;
7
- const lang = n.getAttribute("lang");
8
- if (lang) return lang;
9
- }
10
- return "";
11
- }
12
-
13
3
  export function hasElementChild(el: Element): boolean {
14
4
  for (let c = el.firstChild; c; c = c.nextSibling) {
15
5
  if (c.nodeType === ELEMENT_NODE) return true;
@@ -7,25 +7,26 @@ import { normalizedNodeText } from "./a11y.ts";
7
7
  import { textIsEmpty } from "./text.ts";
8
8
  import { type ObjBuilder, ariaSubstitutedBuilders, substitutedOwnSelectorBuilders } from "./object.ts";
9
9
  import { hasElementChild, isAncestorOf } from "./dom.ts";
10
+ import { nodeLanguage } from "./language.ts";
10
11
  import { Converter } from "./converter.ts";
11
12
  import { selectorForElement, textrefForSelector } from "./selectorGenerator.ts";
12
13
 
13
14
  // Returns true if el's children should still be descended into (a
14
15
  // pagebreak with element children of its own, in HTML parsing).
15
- export function pagebreak(converter: Converter, el: Element, aria: string | null, roles: GndRole[]): boolean {
16
+ export function pagebreak(converter: Converter, el: Element, aria: string | null, ariaLanguage: string, roles: GndRole[]): boolean {
16
17
  const obj: ObjBuilder = { role: roles };
17
18
  const title = (el.getAttribute("title") ?? "").trim();
18
19
  if (title) {
19
- obj.text = { plain: title, ssml: "", language: "" };
20
+ obj.text = { plain: title, ssml: "", language: nodeLanguage(el) };
20
21
  } else if (aria) {
21
- obj.text = { plain: aria, ssml: "", language: "" };
22
+ obj.text = { plain: aria, ssml: "", language: ariaLanguage };
22
23
  ariaSubstitutedBuilders.add(obj);
23
24
  }
24
25
  const labelled = !!(obj.text && !textIsEmpty(obj.text));
25
26
  const descend = !converter.xmlParsed && (hasElementChild(el) || (labelled && el.firstChild !== null));
26
27
  if (!labelled && !descend) {
27
- const text = normalizedNodeText(el);
28
- if (text) obj.text = { plain: text, ssml: "", language: "" };
28
+ const { text, language } = normalizedNodeText(el);
29
+ if (text) obj.text = { plain: text, ssml: "", language };
29
30
  }
30
31
  const selector = selectorForElement(el, converter.selectorRoot, converter.selectorRootAnchor);
31
32
  const textref = textrefForSelector(selector, el);
@@ -36,8 +37,8 @@ export function pagebreak(converter: Converter, el: Element, aria: string | null
36
37
 
37
38
  export function noteref(converter: Converter, el: Element, roles: GndRole[]): void {
38
39
  const obj: ObjBuilder = { role: roles };
39
- const text = normalizedNodeText(el);
40
- if (text) obj.text = { plain: text, ssml: "", language: "" };
40
+ const { text, language } = normalizedNodeText(el);
41
+ if (text) obj.text = { plain: text, ssml: "", language };
41
42
 
42
43
  const href = el.getAttribute("href") ?? "";
43
44
  let candidateID = el.getAttribute("id") ?? "";
@@ -70,17 +71,17 @@ export function noteref(converter: Converter, el: Element, roles: GndRole[]): vo
70
71
  converter.placeholder(el, "noteref", obj, candidateID || undefined);
71
72
  }
72
73
 
73
- export function link(converter: Converter, el: Element, roles: GndRole[], aria: string | null): void {
74
+ export function link(converter: Converter, el: Element, roles: GndRole[], aria: string | null, ariaLanguage: string): void {
74
75
  const obj: ObjBuilder = {};
75
76
  if (roles.length > 0) obj.role = roles;
76
77
  if (aria) {
77
- obj.text = { plain: aria, ssml: "", language: "" };
78
+ obj.text = { plain: aria, ssml: "", language: ariaLanguage };
78
79
  ariaSubstitutedBuilders.add(obj);
79
80
  const selector = selectorForElement(el, converter.selectorRoot, converter.selectorRootAnchor);
80
81
  if (selector) substitutedOwnSelectorBuilders.set(obj, selector);
81
82
  } else {
82
- const text = normalizedNodeText(el);
83
- if (text) obj.text = { plain: text, ssml: "", language: "" };
83
+ const { text, language } = normalizedNodeText(el);
84
+ if (text) obj.text = { plain: text, ssml: "", language };
84
85
  }
85
86
  const href = el.getAttribute("href");
86
87
  if (href) obj.textref = href;
@@ -0,0 +1,37 @@
1
+ const XML_NS = "http://www.w3.org/XML/1998/namespace";
2
+
3
+ // An element's own language declaration, `null` when it has none. An HTML `xml:lang` (no namespace)
4
+ // isn't in the XML namespace, so it only counts when not empty, as it never makes a language unknown.
5
+ function ownLanguage(el: Element): string | null {
6
+ const xmlLang = el.getAttributeNS(XML_NS, "lang") ?? (el.getAttribute("xml:lang")?.trim() || null);
7
+ return xmlLang ?? el.getAttribute("lang");
8
+ }
9
+
10
+ // The language declared on `el` or its nearest ancestor, `undefined` when none is.
11
+ // An empty declaration (`lang=""`) means the language is unknown, so it isn't inherited past it.
12
+ export function declaredLanguage(el: Element | null): string | undefined {
13
+ for (let n: Element | null = el; n; n = n.parentElement) {
14
+ const language = ownLanguage(n);
15
+ if (language !== null) return language.trim();
16
+ }
17
+ return undefined;
18
+ }
19
+
20
+ export function nodeLanguage(el: Element | null): string {
21
+ return declaredLanguage(el) ?? "";
22
+ }
23
+
24
+ // BCP 47 tags are case-insensitive: "en-US" and "en-us" are the same language.
25
+ export function sameLanguage(a: string | undefined, b: string | undefined): boolean {
26
+ return a === b || (a !== undefined && b !== undefined && a.toLowerCase() === b.toLowerCase());
27
+ }
28
+
29
+ // The language all of `languages` are in, as first spelled, unknown ("") when they differ.
30
+ export function sharedLanguage(languages: Iterable<string>): string {
31
+ let shared: string | undefined;
32
+ for (const language of languages) {
33
+ if (shared === undefined) shared = language;
34
+ else if (!sameLanguage(shared, language)) return "";
35
+ }
36
+ return shared ?? "";
37
+ }
package/src/object.ts CHANGED
@@ -12,6 +12,12 @@ export interface ObjBuilder {
12
12
  role?: GndRole[];
13
13
  children?: ObjBuilder[];
14
14
  description?: string;
15
+ descriptionLanguage?: string;
16
+ }
17
+
18
+ export function setDescription(o: ObjBuilder, text: string, language: string): void {
19
+ o.description = text;
20
+ o.descriptionLanguage = language;
15
21
  }
16
22
 
17
23
  // Roles whose entire information is the role itself, with no ref/text/
@@ -165,7 +171,7 @@ export function finalizeToGuidedNavigationObject(o: ObjBuilder): GuidedNavigatio
165
171
  role: o.role && o.role.length > 0 ? new Set(o.role) : undefined,
166
172
  children: o.children && o.children.length > 0 ? o.children.map(finalizeToGuidedNavigationObject) : undefined,
167
173
  description: o.description
168
- ? new GuidedNavigationDescription({ text: new GuidedNavigationText({ plain: o.description }) })
174
+ ? new GuidedNavigationDescription({ text: new GuidedNavigationText({ plain: o.description, language: o.descriptionLanguage || undefined }) })
169
175
  : undefined,
170
176
  });
171
177
  if (ariaSubstitutedBuilders.has(o)) ariaSubstitutedNodes.add(node);
package/src/text.ts CHANGED
@@ -20,7 +20,8 @@ export function finalizeText(t?: TextBuilder): GuidedNavigationText | undefined
20
20
  }
21
21
 
22
22
  export interface SSMLContext {
23
- lang: string;
23
+ // `undefined` when no language is declared, "" when it's declared unknown.
24
+ lang: string | undefined;
24
25
  tag: string;
25
26
  attrs?: Record<string, string>;
26
27
  }
@@ -1,15 +1,20 @@
1
- /** Normalized (whitespace-coalesced and trimmed) text content of a node's subtree. */
2
- export declare function normalizedNodeText(el: Node): string;
1
+ export interface NodeText {
2
+ text: string;
3
+ language: string;
4
+ }
5
+ /** Normalized (whitespace-coalesced and trimmed) text content of a node's subtree, and its language. */
6
+ export declare function normalizedNodeText(el: Node): NodeText;
3
7
  /** Same as `normalizedNodeText`, excluding explicitly-role-bearing descendants. */
4
- export declare function normalizedNodeTextExcludingExplicitRoles(el: Node): string;
8
+ export declare function normalizedNodeTextExcludingExplicitRoles(el: Node): NodeText;
5
9
  /**
6
10
  * Computes the text that becomes a node's `GuidedNavigationObject.description`, and
7
11
  * whether the node is visible in the first place. Follows the AccName
8
12
  * precedence order (https://www.w3.org/TR/accname/#terminology, 2.A-2.D)
9
13
  * for its accessible-name sources, with a non-AccName `aria-describedby`
10
14
  * fallback spliced in between 2.C and 2.D — see that branch below.
15
+ * Also returns that text's language.
11
16
  */
12
- export declare function extractNodeAria(el: Element): [string | null, boolean];
17
+ export declare function extractNodeAria(el: Element): [string | null, boolean, string];
13
18
  /**
14
19
  * Maps an HTML element to the SSML tag its text should be wrapped in.
15
20
  * https://www.w3.org/TR/speech-synthesis11/#S3.2.2
@@ -1,4 +1,3 @@
1
- export declare function nodeLanguage(el: Element | null): string;
2
1
  export declare function hasElementChild(el: Element): boolean;
3
2
  export declare function isAncestorOf(anc: Element, n: Element): boolean;
4
3
  export declare function isInlineTag(tagName: string): boolean;
@@ -1,5 +1,5 @@
1
1
  import type { GndRole } from "./types.ts";
2
2
  import { Converter } from "./converter.ts";
3
- export declare function pagebreak(converter: Converter, el: Element, aria: string | null, roles: GndRole[]): boolean;
3
+ export declare function pagebreak(converter: Converter, el: Element, aria: string | null, ariaLanguage: string, roles: GndRole[]): boolean;
4
4
  export declare function noteref(converter: Converter, el: Element, roles: GndRole[]): void;
5
- export declare function link(converter: Converter, el: Element, roles: GndRole[], aria: string | null): void;
5
+ export declare function link(converter: Converter, el: Element, roles: GndRole[], aria: string | null, ariaLanguage: string): void;
@@ -0,0 +1,4 @@
1
+ export declare function declaredLanguage(el: Element | null): string | undefined;
2
+ export declare function nodeLanguage(el: Element | null): string;
3
+ export declare function sameLanguage(a: string | undefined, b: string | undefined): boolean;
4
+ export declare function sharedLanguage(languages: Iterable<string>): string;
@@ -11,7 +11,9 @@ export interface ObjBuilder {
11
11
  role?: GndRole[];
12
12
  children?: ObjBuilder[];
13
13
  description?: string;
14
+ descriptionLanguage?: string;
14
15
  }
16
+ export declare function setDescription(o: ObjBuilder, text: string, language: string): void;
15
17
  export declare const ariaSubstitutedBuilders: WeakSet<ObjBuilder>;
16
18
  export declare const substitutedOwnSelectorBuilders: WeakMap<ObjBuilder, string>;
17
19
  export declare function isAriaSubstituted(node: GuidedNavigationObject): boolean;
@@ -7,7 +7,7 @@ export interface TextBuilder {
7
7
  export declare function textIsEmpty(t: TextBuilder): boolean;
8
8
  export declare function finalizeText(t?: TextBuilder): GuidedNavigationText | undefined;
9
9
  export interface SSMLContext {
10
- lang: string;
10
+ lang: string | undefined;
11
11
  tag: string;
12
12
  attrs?: Record<string, string>;
13
13
  }