@readium/guided-navigation 1.4.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/converter.js CHANGED
@@ -1 +1 @@
1
- import{hasExplicitRole as J,extractNodeRoles as R}from"./roles.js";import{skippedElements as $,extractNodeAria as G,normalizedNodeText as K,convertElementToSSMLTag as Q}from"./a11y.js";import{normalizeWhitespace as v,ctxEqual as Z}from"./text.js";import{ssmlTextEscape as B,ssmlAttrEscape as I}from"@readium/helpers";import{NavObject as F,isEmptyObj as V,finalizeToGuidedNavigationObject as _,setDescription as S}from"./object.js";import{sniffMediaType as tt,isInlineTag as z,isAncestorOf as et}from"./dom.js";import{nodeLanguage as st,declaredLanguage as j,sameLanguage as M}from"./language.js";import{encodeDomRangeFragment as it,encodeTextFragmentDirective as nt}from"./textrefFragment.js";import{resolveRefs as rt}from"./href.js";import{rootAnchorSelector as ot,textrefForSelector as A,selectorForElement as O}from"./selectorGenerator.js";import{generateDomRange as lt}from"./domRangeGenerator.js";import{textFragmentDirectiveFor as at}from"./textFragmentGenerator.js";import{normalizeTextrefOptions as ct}from"./options.js";import{IdAllocator as ht}from"./idAllocator.js";import{prescan as ft}from"./prescan.js";import{pagebreak as dt,noteref as ut,reference as gt,link as pt}from"./elementHandlers.js";import{removeDropped as mt,bindsToPrevious as xt,DROPPED as bt}from"./emptyPairs.js";const wt="http://www.w3.org/1998/Math/MathML",N=3,X=1,kt=4,Et=new Set(["summary","dfn","span"]);function L(f,t){return Et.has(f)&&t.length>0?!0:!z(f)}class d{constructor(t){this.ids=new Map,this.suppressed=new Set,this.idAlloc=new ht,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.copy=!1,this.root=new F,this.current=this.root,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.words=null,this.xmlParsed=t}spawnChild(t,e=1){const s=new d(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.copy=this.copy,s}prescan(t){ft(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=>A(O(e,this.selectorRoot,this.selectorRootAnchor),e));return!t.children||t.children.length===0||t.text?V(t)?[]:[t]:t.children}result(){const t=this.resultBuilders();return this.baseHref&&t.forEach(e=>rt(e,this.baseHref)),t.map(_)}descend(t,e){const s=new F;s.el=t,s.noText=(!J(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===N){d.punctuationOwner(t)||this.text(t);return}if(t.nodeType!==X)return;const e=t,s=this.current,o=this.head(e);if(!o){const i=this.current!==s&&this.current.el===e?d.ownPunctuation(e):[],r=a=>(a.compareDocumentPosition(e)&kt)!==0;for(const a of i)r(a)&&this.text(a);for(let a=e.firstChild;a;a=a.nextSibling)this.walk(a);for(const a of i)r(a)||this.text(a)}this.tail(e,o,s)}head(t){const e=t.tagName.toLowerCase();if($.has(e)||this.suppressed.has(t)&&t!==this.allowNode)return!0;const[s,o,i]=G(t);if(!o&&t!==this.allowNode)return!0;const r=R(t);if((e==="img"||e==="svg")&&(r.includes("presentation")||s===null&&t.hasAttribute("alt")&&t.getAttribute("alt").trim()===""))return!0;if(e==="br")return!this.current.noText&&!this.textContext(t).abbr&&(this.closeSegment(),this.segments.push({kind:"break"}),this.words?.push({kind:"break"}),this.flowEndsWithSpace=!0),!0;if(r.includes("pagebreak"))return!dt(this,t,s,i,r);if(e==="a"&&r.includes("noteref")&&t.getAttribute("href"))return ut(this,t,r),!0;if(e==="a"&&(r.includes("glossref")||r.includes("biblioref"))&&t.getAttribute("href"))return gt(this,t,r,s,i),!0;if(e==="a"&&t.getAttribute("href"))return pt(this,t,r,s,i),!0;if(e==="img"){const c={role:r},h=t.getAttribute("src");return h&&(c.imgref=h),s&&S(c,s,i),this.placeholder(t,"image",c),!0}if(e==="audio"||e==="video"){const c={role:r};let h=t.getAttribute("src");if(!h){const g=t.querySelector(":scope > source[src]");g&&(h=g.getAttribute("src"))}return e==="audio"?h&&(c.audioref=h):h&&(c.videoref=h),s&&S(c,s,i),this.placeholder(t,e,c),!0}if(r.includes("image")||r.includes("math")){const c={role:r};if(s&&S(c,s,i),r.includes("math")){if(t.namespaceURI===wt)c.text={plain:"",ssml:new XMLSerializer().serializeToString(t),language:st(t)};else{const{text:h,language:g}=K(t);h&&(c.text={plain:h,ssml:"",language:g})}c.textref=A(O(t,this.selectorRoot,this.selectorRootAnchor),t)}return this.placeholder(t,r.includes("math")?"math":"image",c),!0}if(!L(e,r))return!1;this.flushText(),z(e)||this.words?.push({kind:"break"}),this.descend(t,r);const a=this.current.object;r.length>0&&(a.role=r),s&&(S(a,s,i),r.includes("figure")&&(this.current.noText=!0));const b=t.getAttribute("id");return b&&(a.id=b),!1}tail(t,e,s){if(e)return;const o=t.tagName.toLowerCase(),i=R(t);if(!i.includes("pagebreak")&&L(o,i)){this.flushText(),z(o)||this.words?.push({kind:"break"}),this.current.hasChildBlock&&(this.lastFlowRange=null,this.lastFlowText=null);const r=this.leafTextEnabled&&i.length===0&&!!this.lastFlowText;(this.selectorPredicate?.(i)||r)&&this.applyTextref(t),this.current=s}}applyTextref(t){const e=this.current.object,s=O(t,this.selectorRoot,this.selectorRootAnchor);if(e.textref=A(s,t),this.domRangeEnabled&&this.lastFlowRange){const o=s?{el:t,selector:s}:void 0,i=lt(this.lastFlowRange,this.selectorRoot,this.selectorRootAnchor,o);i&&(e.textref=it({...i,container:s}))}if(this.textFragmentEnabled&&this.lastFlowRange&&this.docRoot){const o=this.docRoot.createRange();o.setStart(...this.lastFlowRange.first),o.setEnd(...this.lastFlowRange.last);const i=at(o);i&&(e.textref=`${e.textref??"#"}${nt(i)}`)}}text(t){if(this.current.noText)return;const e=t.nodeValue??"";if(this.words?.push({kind:"text",text:v(e,!1)}),/^\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(Z(s,this.currentCtx)||(this.closeSegment(),this.currentCtx=s),this.textAcc+=v(e,this.flowEndsWithSpace),this.updateFlowSpace(),this.domRangeEnabled||this.textFragmentEnabled){const o=t;this.flowFirstNode===null&&(this.flowFirstNode=o,this.flowFirstOffset=e.search(/\S/)),this.flowLastNode=o,this.flowLastOffset=e.length-(e.match(/\s+$/)?.[0].length??0)}}textContext(t){const e=d.punctuationOwner(t);let s=e?d.abbreviationOver(e):null;if(!e){let i=t.parentElement;for(;i&&i!==this.current.el;i=i.parentElement)if(W(i)){if(d.containsObject(i))break;s=i}i&&i===this.current.el&&(s=d.abbreviationOver(i)??s)}if(s)return{lang:j(s),tag:"sub",attrs:{alias:W(s)},abbr:s};const o={lang:j(t.parentElement),tag:""};for(let i=t.parentElement;i&&i!==this.current.el;i=i.parentElement){const[r,a]=Q(i.tagName.toLowerCase());if(r&&r!=="break"){o.tag=r,o.attrs=a;break}}return o}static containsObject(t){for(let e=t.firstElementChild;e;e=e.nextElementSibling){const s=e.tagName.toLowerCase(),o=R(e);if(!($.has(s)||d.isPlaceholder(e,s,o))&&(L(s,o)||d.containsObject(e)))return!0}return!1}static isPlaceholder(t,e,s){return s.includes("pagebreak")||s.includes("image")||s.includes("math")?!0:["img","svg","audio","video"].includes(e)||e==="a"&&!!t.getAttribute("href")}static abbreviationOver(t){let e=null;for(let s=t;s&&(W(s)&&(e=s),!!d.isSoleContent(s));s=s.parentElement);return e}static punctuationOwner(t){const e=t.nodeValue??"";if(t.nodeType!==N||!/\S/.test(e)||!/^[\s\p{P}]*$/u.test(e))return null;let s=null;for(let o=t.parentElement?.firstElementChild??null;o&&d.isSoleContent(o);o=o.firstElementChild){const i=o.tagName.toLowerCase(),r=R(o);if($.has(i)||d.isPlaceholder(o,i,r)||!G(o)[1])break;L(i,r)&&(s=o)}return s&&d.abbreviationOver(s)?.contains(t)?s:null}static ownPunctuation(t){const e=d.abbreviationOver(t),s=[],o=i=>{if(i!==t){i.nodeType===N&&d.punctuationOwner(i)===t&&s.push(i);for(let r=i.firstChild;r;r=r.nextSibling)o(r)}};return e&&o(e),s}static isSoleContent(t){for(let e=t.parentNode?.firstChild;e;e=e.nextSibling)if(e!==t&&(e.nodeType===X||e.nodeType===N&&!/^[\s\p{P}]*$/u.test(e.nodeValue??"")))return!1;return!0}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,{candidateID:o,words:i}={}){if(V(s))return;!s.textref&&this.selectorPredicate?.(s.role??[])&&(s.textref=A(O(t,this.selectorRoot,this.selectorRootAnchor),t));const r=new F;if(r.el=t,r.object=s,this.current.noText){this.appendChild(r);return}this.closeSegment(),this.pendingChildren.push(r),this.segments.push({kind:"placeholder",tag:e,child:r,candidateID:o??t.getAttribute("id")??void 0,words:i?.length?i:void 0}),this.words?.push(...i?.length?i:[{kind:"placeholder"}]),this.flowEndsWithSpace=!1}flushText(){this.closeSegment();let t=this.segments;const e=this.pendingChildren,s=this.flowFirstNode,o=this.flowFirstOffset,i=this.flowLastNode,r=this.flowLastOffset;if(this.resetFlow(),this.lastFlowRange=null,this.lastFlowText=null,t.length===0)return;for(;t.length>0;){const n=t[0];if(n.kind==="break"){t=t.slice(1);continue}if(n.kind==="text"){const l=n.text.replace(/^\s+/,"");if(l===""){t=t.slice(1);continue}t=[{...n,text:l},...t.slice(1)]}break}for(;t.length>0;){const n=t[t.length-1];if(n.kind==="break"){t=t.slice(0,-1);continue}if(n.kind==="text"){const l=n.text.replace(/\s+$/,"");if(l===""){t=t.slice(0,-1);continue}t=[...t.slice(0,-1),{...n,text:l}]}break}const a=[];for(let n=0;n<t.length;n++){const l=t[n],u=l.kind==="text"?l.ctx.abbr:void 0;if(!u){a.push(l);continue}let m=l.text;const E=[];let w=[];for(let x=n+1;x<t.length;x++){const T=t[x];if(T.kind==="placeholder"&&et(u,T.child.el)){w.push(T);continue}if(T.kind!=="text"||T.ctx.abbr!==u)break;m+=T.text,E.push(...w),w=[],n=x}a.push({...l,text:m},...E)}if(t=a,!t.some(n=>n.kind==="text"&&n.text.trim()!=="")){for(const n of e)this.appendChild(n);return}const c=[];for(const n of t)if(n.kind==="text"&&n.text.trim()!==""){const l=n.ctx.lang;c.some(u=>M(u,l))||c.push(l)}let h=j(this.current.el??this.allowNode);c.length===1&&(h=c[0]);let g=!1;for(const n of t)if(n.kind!=="text"||n.ctx.tag!==""||!M(n.ctx.lang,h)){g=!0;break}g&&h===void 0&&(h="en");const p=n=>n!==void 0&&!M(n,h);if(g)for(const n of t){if(n.kind!=="placeholder")continue;let l=this.copy?void 0:n.candidateID;(!l||!this.idAlloc.claim(l))&&(l=this.idAlloc.allocate(n.tag,u=>this.ids.has(u))),n.child.object.id=l}let k="",H=!1,P=!1,C=!1,y=!1;for(const n of t.flatMap(l=>l.words??[l]))if(n.kind==="text"){const l=n.text.startsWith(" "),u=n.text.replace(/^ +| +$/g,"");if(u===""){y=!0;continue}let m=!1;if(k.length>0){const E=H||y||l;P?m=!0:C?m=E&&!xt(u,h):m=E}m&&(k+=" "),k+=u,H=n.text.endsWith(" "),P=!1,C=!1,y=!1}else n.kind==="break"?P=!0:n.kind==="placeholder"&&(k+=bt,C=!0);k=mt(k,h);const Y=t.some(n=>n.kind==="placeholder");this.lastFlowText=k.trim();const q={plain:g&&!Y?"":k.trim(),ssml:"",language:h??""};if(g){let n="";for(const l of t)if(l.kind==="text"){const{tag:u,attrs:m,lang:E}=l.ctx,w=u==="sub"?/^( *)([^]*?)( *)$/.exec(l.text):null,x=w?w[2]:l.text;if(w&&x===""){n+=l.text;continue}if(n+=w?.[1]??"",p(E)){const T=u==="sub"?U(u,m,x):B(x);n+=`<lang xml:lang="${I(E)}">${T}</lang>`}else n+=u?U(u,m,x):B(x);n+=w?.[3]??""}else l.kind==="break"?n+="<break/>":l.kind==="placeholder"&&(n+=`<readium:${l.tag} id="${I(l.child.object.id)}" />`);q.ssml=n}const D=new F;D.object={text:q};for(const n of e)D.children.push(n);this.appendChild(D),s&&i&&(this.lastFlowRange={first:[s,o],last:[i,r]})}}function W(f){return R(f).includes("abbreviation")?v(f.getAttribute("title")??"",!0).trim():""}function U(f,t,e){const s=Object.entries(t??{}).map(([o,i])=>` ${o}="${I(i)}"`).join("");return`<${f}${s}>${B(e)}</${f}>`}const Tt=/<body[\s>]/i;function It(f,t,e){const{predicate:s,leafText:o,domRange:i,textFragment:r}=ct(e?.textrefs);if(typeof f!="string"){const g=t??(f.ownerDocument.contentType==="text/html"?"text/html":"application/xhtml+xml"),p=new d(g==="application/xhtml+xml");return p.selectorPredicate=s,p.leafTextEnabled=o,p.domRangeEnabled=i,p.textFragmentEnabled=r,p.docRoot=f.ownerDocument,p.baseHref=e?.href,p.selectorRoot=f,p.selectorRootAnchor=ot(f),p.convert(f),p.result()}let a=t??tt(f),b=new DOMParser().parseFromString(f,a);if(a==="application/xhtml+xml"){const g=b.getElementsByTagNameNS("*","parsererror")[0];if(g){if(!e?.htmlFallback)throw new Error(`XHTML parsing failed: ${g.textContent?.trim()??""}`);a="text/html",b=new DOMParser().parseFromString(f,a)}}const c=new d(a==="application/xhtml+xml");c.selectorPredicate=s,c.leafTextEnabled=o,c.textFragmentEnabled=r,c.docRoot=b,c.baseHref=e?.href;const h=b.querySelector("body");return h&&!Tt.test(f)?c.convertChildren(h):c.convert(h??b.documentElement),c.result()}export{d as Converter,It as parseMarkup};
1
+ import{hasExplicitRole as J,extractNodeRoles as F}from"./roles.js";import{skippedElements as $,extractNodeAria as q,normalizedNodeText as K,convertElementToSSMLTag as Q}from"./a11y.js";import{normalizeWhitespace as v,ctxEqual as Z}from"./text.js";import{ssmlTextEscape as W,ssmlAttrEscape as B}from"@readium/helpers";import{NavObject as A,isEmptyObj as V,finalizeToGuidedNavigationObject as _,setDescription as S}from"./object.js";import{sniffMediaType as tt,isInlineTag as z,isAncestorOf as et}from"./dom.js";import{nodeLanguage as st,declaredLanguage as j,sameLanguage as M}from"./language.js";import{encodeDomRangeFragment as it,encodeTextFragmentDirective as nt}from"./textrefFragment.js";import{resolveRefs as rt}from"./href.js";import{rootAnchorSelector as ot,textrefForSelector as O,selectorForElement as N}from"./selectorGenerator.js";import{generateDomRange as lt}from"./domRangeGenerator.js";import{textFragmentDirectiveFor as at}from"./textFragmentGenerator.js";import{normalizeTextrefOptions as ct}from"./options.js";import{IdAllocator as ht}from"./idAllocator.js";import{prescan as ft}from"./prescan.js";import{pagebreak as dt,noteref as ut,reference as gt,link as pt}from"./elementHandlers.js";import{removeDropped as mt,bindsToPrevious as xt,DROPPED as bt}from"./emptyPairs.js";const wt="http://www.w3.org/1998/Math/MathML",L=3,X=1,kt=4,Et=new Set(["summary","dfn","span"]);function R(d,t){return Et.has(d)&&t.length>0?!0:!z(d)}class f{constructor(t){this.ids=new Map,this.suppressed=new Set,this.idAlloc=new ht,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.copy=!1,this.root=new A,this.current=this.root,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.words=null,this.xmlParsed=t}spawnChild(t,e=1){const s=new f(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.copy=this.copy,s}prescan(t){ft(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=>O(N(e,this.selectorRoot,this.selectorRootAnchor),e));return!t.children||t.children.length===0||t.text?V(t)?[]:[t]:t.children}result(){const t=this.resultBuilders();return this.baseHref&&t.forEach(e=>rt(e,this.baseHref)),t.map(_)}descend(t,e){const s=new A;s.el=t,s.noText=(!J(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===L){f.punctuationOwner(t)||this.text(t);return}if(t.nodeType!==X)return;const e=t,s=this.current,o=this.head(e);if(!o){const i=this.current!==s&&this.current.el===e?f.ownPunctuation(e):[],r=a=>(a.compareDocumentPosition(e)&kt)!==0;for(const a of i)r(a)&&this.text(a);for(let a=e.firstChild;a;a=a.nextSibling)this.walk(a);for(const a of i)r(a)||this.text(a)}this.tail(e,o,s)}head(t){const e=t.tagName.toLowerCase();if($.has(e)||this.suppressed.has(t)&&t!==this.allowNode)return!0;const[s,o,i]=q(t);if(!o&&t!==this.allowNode)return!0;const r=F(t);if((e==="img"||e==="svg")&&(r.includes("presentation")||s===null&&t.hasAttribute("alt")&&t.getAttribute("alt").trim()===""))return!0;if(e==="br")return!this.current.noText&&!this.textContext(t).abbr&&(this.closeSegment(),this.segments.push({kind:"break"}),this.words?.push({kind:"break"}),this.flowEndsWithSpace=!0),!0;if(r.includes("pagebreak"))return!dt(this,t,s,i,r);if(e==="a"&&r.includes("noteref")&&t.getAttribute("href"))return ut(this,t,r),!0;if(e==="a"&&(r.includes("glossref")||r.includes("biblioref"))&&t.getAttribute("href"))return gt(this,t,r,s,i),!0;if(e==="a"&&t.getAttribute("href"))return pt(this,t,r,s,i),!0;if(e==="img"){const c={role:r},h=t.getAttribute("src");return h&&(c.imgref=h),s&&S(c,s,i),this.placeholder(t,"image",c),!0}if(e==="audio"||e==="video"){const c={role:r};let h=t.getAttribute("src");if(!h){const g=t.querySelector(":scope > source[src]");g&&(h=g.getAttribute("src"))}return e==="audio"?h&&(c.audioref=h):h&&(c.videoref=h),s&&S(c,s,i),this.placeholder(t,e,c),!0}if(f.actsAsImage(e,r)||r.includes("math")){const c={role:r};if(s&&S(c,s,i),r.includes("math")){if(t.namespaceURI===wt)c.text={plain:"",ssml:new XMLSerializer().serializeToString(t),language:st(t)};else{const{text:h,language:g}=K(t);h&&(c.text={plain:h,ssml:"",language:g})}c.textref=O(N(t,this.selectorRoot,this.selectorRootAnchor),t)}return this.placeholder(t,r.includes("math")?"math":"image",c),!0}if(!R(e,r))return!1;this.flushText(),z(e)||this.words?.push({kind:"break"}),this.descend(t,r);const a=this.current.object;r.length>0&&(a.role=r),s&&(S(a,s,i),r.includes("figure")&&(this.current.noText=!0));const b=t.getAttribute("id");return b&&(a.id=b),!1}tail(t,e,s){if(e)return;const o=t.tagName.toLowerCase(),i=F(t);if(!i.includes("pagebreak")&&R(o,i)){this.flushText(),z(o)||this.words?.push({kind:"break"}),this.current.hasChildBlock&&(this.lastFlowRange=null,this.lastFlowText=null);const r=this.leafTextEnabled&&i.length===0&&!!this.lastFlowText;(this.selectorPredicate?.(i)||r)&&this.applyTextref(t),this.current=s}}applyTextref(t){const e=this.current.object,s=N(t,this.selectorRoot,this.selectorRootAnchor);if(e.textref=O(s,t),this.domRangeEnabled&&this.lastFlowRange){const o=s?{el:t,selector:s}:void 0,i=lt(this.lastFlowRange,this.selectorRoot,this.selectorRootAnchor,o);i&&(e.textref=it({...i,container:s}))}if(this.textFragmentEnabled&&this.lastFlowRange&&this.docRoot){const o=this.docRoot.createRange();o.setStart(...this.lastFlowRange.first),o.setEnd(...this.lastFlowRange.last);const i=at(o);i&&(e.textref=`${e.textref??"#"}${nt(i)}`)}}text(t){if(this.current.noText)return;const e=t.nodeValue??"";if(this.words?.push({kind:"text",text:v(e,!1)}),/^\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(Z(s,this.currentCtx)||(this.closeSegment(),this.currentCtx=s),this.textAcc+=v(e,this.flowEndsWithSpace),this.updateFlowSpace(),this.domRangeEnabled||this.textFragmentEnabled){const o=t;this.flowFirstNode===null&&(this.flowFirstNode=o,this.flowFirstOffset=e.search(/\S/)),this.flowLastNode=o,this.flowLastOffset=e.length-(e.match(/\s+$/)?.[0].length??0)}}textContext(t){const e=f.punctuationOwner(t);let s=e?f.abbreviationOver(e):null;if(!e){let i=t.parentElement;for(;i&&i!==this.current.el;i=i.parentElement)if(I(i)){if(f.containsObject(i))break;s=i}i&&i===this.current.el&&(s=f.abbreviationOver(i)??s)}if(s)return{lang:j(s),tag:"sub",attrs:{alias:I(s)},abbr:s};const o={lang:j(t.parentElement),tag:""};for(let i=t.parentElement;i&&i!==this.current.el;i=i.parentElement){const[r,a]=Q(i.tagName.toLowerCase());if(r&&r!=="break"){o.tag=r,o.attrs=a;break}}return o}static containsObject(t){for(let e=t.firstElementChild;e;e=e.nextElementSibling){const s=e.tagName.toLowerCase(),o=F(e);if(!($.has(s)||f.isPlaceholder(e,s,o))&&(R(s,o)||f.containsObject(e)))return!0}return!1}static isPlaceholder(t,e,s){return s.includes("pagebreak")||f.actsAsImage(e,s)||s.includes("math")?!0:["img","svg","audio","video"].includes(e)||e==="a"&&!!t.getAttribute("href")}static actsAsImage(t,e){const s=e.includes("panel")||e.includes("panelGroup");return e.includes("image")&&(t==="svg"||!s||!R(t,e))}static abbreviationOver(t){let e=null;for(let s=t;s&&(I(s)&&(e=s),!!f.isSoleContent(s));s=s.parentElement);return e}static punctuationOwner(t){const e=t.nodeValue??"";if(t.nodeType!==L||!/\S/.test(e)||!/^[\s\p{P}]*$/u.test(e))return null;let s=null;for(let o=t.parentElement?.firstElementChild??null;o&&f.isSoleContent(o);o=o.firstElementChild){const i=o.tagName.toLowerCase(),r=F(o);if($.has(i)||f.isPlaceholder(o,i,r)||!q(o)[1])break;R(i,r)&&(s=o)}return s&&f.abbreviationOver(s)?.contains(t)?s:null}static ownPunctuation(t){const e=f.abbreviationOver(t),s=[],o=i=>{if(i!==t){i.nodeType===L&&f.punctuationOwner(i)===t&&s.push(i);for(let r=i.firstChild;r;r=r.nextSibling)o(r)}};return e&&o(e),s}static isSoleContent(t){for(let e=t.parentNode?.firstChild;e;e=e.nextSibling)if(e!==t&&(e.nodeType===X||e.nodeType===L&&!/^[\s\p{P}]*$/u.test(e.nodeValue??"")))return!1;return!0}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,{candidateID:o,words:i}={}){if(V(s))return;!s.textref&&this.selectorPredicate?.(s.role??[])&&(s.textref=O(N(t,this.selectorRoot,this.selectorRootAnchor),t));const r=new A;if(r.el=t,r.object=s,this.current.noText){this.appendChild(r);return}this.closeSegment(),this.pendingChildren.push(r),this.segments.push({kind:"placeholder",tag:e,child:r,candidateID:o??t.getAttribute("id")??void 0,words:i?.length?i:void 0}),this.words?.push(...i?.length?i:[{kind:"placeholder"}]),this.flowEndsWithSpace=!1}flushText(){this.closeSegment();let t=this.segments;const e=this.pendingChildren,s=this.flowFirstNode,o=this.flowFirstOffset,i=this.flowLastNode,r=this.flowLastOffset;if(this.resetFlow(),this.lastFlowRange=null,this.lastFlowText=null,t.length===0)return;for(;t.length>0;){const n=t[0];if(n.kind==="break"){t=t.slice(1);continue}if(n.kind==="text"){const l=n.text.replace(/^\s+/,"");if(l===""){t=t.slice(1);continue}t=[{...n,text:l},...t.slice(1)]}break}for(;t.length>0;){const n=t[t.length-1];if(n.kind==="break"){t=t.slice(0,-1);continue}if(n.kind==="text"){const l=n.text.replace(/\s+$/,"");if(l===""){t=t.slice(0,-1);continue}t=[...t.slice(0,-1),{...n,text:l}]}break}const a=[];for(let n=0;n<t.length;n++){const l=t[n],u=l.kind==="text"?l.ctx.abbr:void 0;if(!u){a.push(l);continue}let m=l.text;const E=[];let w=[];for(let x=n+1;x<t.length;x++){const T=t[x];if(T.kind==="placeholder"&&et(u,T.child.el)){w.push(T);continue}if(T.kind!=="text"||T.ctx.abbr!==u)break;m+=T.text,E.push(...w),w=[],n=x}a.push({...l,text:m},...E)}if(t=a,!t.some(n=>n.kind==="text"&&n.text.trim()!=="")){for(const n of e)this.appendChild(n);return}const c=[];for(const n of t)if(n.kind==="text"&&n.text.trim()!==""){const l=n.ctx.lang;c.some(u=>M(u,l))||c.push(l)}let h=j(this.current.el??this.allowNode);c.length===1&&(h=c[0]);let g=!1;for(const n of t)if(n.kind!=="text"||n.ctx.tag!==""||!M(n.ctx.lang,h)){g=!0;break}g&&h===void 0&&(h="en");const p=n=>n!==void 0&&!M(n,h);if(g)for(const n of t){if(n.kind!=="placeholder")continue;let l=this.copy?void 0:n.candidateID;(!l||!this.idAlloc.claim(l))&&(l=this.idAlloc.allocate(n.tag,u=>this.ids.has(u))),n.child.object.id=l}let k="",H=!1,P=!1,y=!1,C=!1;for(const n of t.flatMap(l=>l.words??[l]))if(n.kind==="text"){const l=n.text.startsWith(" "),u=n.text.replace(/^ +| +$/g,"");if(u===""){C=!0;continue}let m=!1;if(k.length>0){const E=H||C||l;P?m=!0:y?m=E&&!xt(u,h):m=E}m&&(k+=" "),k+=u,H=n.text.endsWith(" "),P=!1,y=!1,C=!1}else n.kind==="break"?P=!0:n.kind==="placeholder"&&(k+=bt,y=!0);k=mt(k,h);const Y=t.some(n=>n.kind==="placeholder");this.lastFlowText=k.trim();const G={plain:g&&!Y?"":k.trim(),ssml:"",language:h??""};if(g){let n="";for(const l of t)if(l.kind==="text"){const{tag:u,attrs:m,lang:E}=l.ctx,w=u==="sub"?/^( *)([^]*?)( *)$/.exec(l.text):null,x=w?w[2]:l.text;if(w&&x===""){n+=l.text;continue}if(n+=w?.[1]??"",p(E)){const T=u==="sub"?U(u,m,x):W(x);n+=`<lang xml:lang="${B(E)}">${T}</lang>`}else n+=u?U(u,m,x):W(x);n+=w?.[3]??""}else l.kind==="break"?n+="<break/>":l.kind==="placeholder"&&(n+=`<readium:${l.tag} id="${B(l.child.object.id)}" />`);G.ssml=n}const D=new A;D.object={text:G};for(const n of e)D.children.push(n);this.appendChild(D),s&&i&&(this.lastFlowRange={first:[s,o],last:[i,r]})}}function I(d){return F(d).includes("abbreviation")?v(d.getAttribute("title")??"",!0).trim():""}function U(d,t,e){const s=Object.entries(t??{}).map(([o,i])=>` ${o}="${B(i)}"`).join("");return`<${d}${s}>${W(e)}</${d}>`}const Tt=/<body[\s>]/i;function Bt(d,t,e){const{predicate:s,leafText:o,domRange:i,textFragment:r}=ct(e?.textrefs);if(typeof d!="string"){const g=t??(d.ownerDocument.contentType==="text/html"?"text/html":"application/xhtml+xml"),p=new f(g==="application/xhtml+xml");return p.selectorPredicate=s,p.leafTextEnabled=o,p.domRangeEnabled=i,p.textFragmentEnabled=r,p.docRoot=d.ownerDocument,p.baseHref=e?.href,p.selectorRoot=d,p.selectorRootAnchor=ot(d),p.convert(d),p.result()}let a=t??tt(d),b=new DOMParser().parseFromString(d,a);if(a==="application/xhtml+xml"){const g=b.getElementsByTagNameNS("*","parsererror")[0];if(g){if(!e?.htmlFallback)throw new Error(`XHTML parsing failed: ${g.textContent?.trim()??""}`);a="text/html",b=new DOMParser().parseFromString(d,a)}}const c=new f(a==="application/xhtml+xml");c.selectorPredicate=s,c.leafTextEnabled=o,c.textFragmentEnabled=r,c.docRoot=b,c.baseHref=e?.href;const h=b.querySelector("body");return h&&!Tt.test(d)?c.convertChildren(h):c.convert(h??b.documentElement),c.result()}export{f as Converter,Bt as parseMarkup};
package/dist/roles.js CHANGED
@@ -1 +1 @@
1
- const p=["heading1","heading2","heading3","heading4","heading5","heading6"],s={"doc-abstract":"abstract","doc-acknowledgments":"acknowledgments","doc-afterword":"afterword","doc-appendix":"appendix",article:"article","doc-backlink":"backlink","doc-biblioentry":"listItem","doc-bibliography":"bibliography","doc-biblioref":"biblioref",blockquote:"blockquote",caption:"caption",cell:"cell","doc-chapter":"chapter","doc-colophon":"colophon",columnheader:"columnheader",complementary:"complementary","doc-conclusion":"conclusion","doc-cover":"cover","doc-credit":"credit","doc-credits":"credits","doc-dedication":"dedication",definition:"definition","doc-endnote":"footnote","doc-endnotes":"endnotes","doc-epigraph":"epigraph","doc-epilogue":"epilogue","doc-errata":"errata","doc-example":"example",figure:"figure","doc-footnote":"footnote","doc-foreword":"foreword","doc-glossary":"glossary","doc-glossref":"glossref",img:"image",image:"image","doc-index":"index","doc-introduction":"introduction",list:"list",listitem:"listItem",main:"main",math:"math",navigation:"navigation","doc-noteref":"noteref","doc-notice":"notice","doc-pagebreak":"pagebreak","doc-pagelist":"pagelist",paragraph:"paragraph","doc-part":"part","doc-preface":"preface","doc-prologue":"prologue","doc-pullquote":"pullquote",grid:"table",gridcell:"cell",presentation:"presentation",none:"presentation","doc-qna":"qna",qna:"qna",region:"region",row:"row",rowheader:"rowheader",separator:"separator","doc-subtitle":"subtitle",table:"table",term:"term","doc-tip":"tip","doc-toc":"toc"},f={abstract:"abstract",acknowledgments:"acknowledgments",afterword:"afterword",appendix:"appendix",aside:"aside",backlink:"backlink",biblioentry:"listItem",bibliography:"bibliography",biblioref:"biblioref","table-cell":"cell",chapter:"chapter",colophon:"colophon",conclusion:"conclusion",cover:"cover",credit:"credit",credits:"credits",dedication:"dedication",glossdef:"definition",endnote:"footnote",endnotes:"endnotes",rearnote:"footnote",rearnotes:"endnotes",epigraph:"epigraph",epilogue:"epilogue",errata:"errata",example:"example",figure:"figure",footnote:"footnote",foreword:"foreword",glossary:"glossary",glossref:"glossref",index:"index",introduction:"introduction",landmarks:"landmarks",list:"list","list-item":"listItem",loa:"loa",loi:"loi",lot:"lot",lov:"lov",noteref:"noteref",notice:"notice",pagebreak:"pagebreak","page-list":"pagelist",pagelist:"pagelist",part:"part",preface:"preface",prologue:"prologue",pullquote:"pullquote",qna:"qna","table-row":"row",subtitle:"subtitle",table:"table",glossterm:"term",tip:"tip",toc:"toc"},g={abbr:"abbreviation",acronym:"abbreviation",article:"article",aside:"aside",audio:"audio",blockquote:"blockquote",caption:"caption",figcaption:"caption",td:"cell",dd:"definition",details:"details",figure:"figure",header:"header",h1:"heading1",h2:"heading2",h3:"heading3",h4:"heading4",h5:"heading5",h6:"heading6",img:"image",ul:"list",ol:"list",li:"listItem",main:"main",math:"math",nav:"navigation",p:"paragraph",pre:"preformatted",tr:"row",section:"section",hr:"separator",summary:"summary",table:"table",dfn:"term",dt:"term",video:"video",svg:"image"},x=new Set(["abbreviation","abstract","acknowledgments","afterword","bibliography","body","caption","cell","chapter","colophon","columnheader","conclusion","cover","credit","credits","dedication","definition","endnotes","epigraph","epilogue","errata","footnote","foreword","glossary",...p,"index","introduction","landmarks","listItem","loa","loi","lot","lov","main","pagelist","paragraph","preface","prologue","pullquote","row","rowheader","subtitle","summary","term","toc"]),b=new Set(["tr","td","th"]),m=new Set(["tr","thead","tbody","tfoot"]);function h(e){const o=e.getAttribute("role");if(!o)return!1;const t=o.split(/\s+/).filter(Boolean);return t.includes("presentation")||t.includes("none")}function d(e){return(e.getAttribute("role")??"").trim()!==""}function w(e,o){if(!b.has(o)||d(e))return!1;for(let t=e.parentElement;t;t=t.parentElement){const a=t.tagName.toLowerCase();if(a!=="table"&&!m.has(a))return!1;if(h(t))return!0;if(a==="table"||d(t))return!1}return!1}function l(e,o){const t=e.getAttribute("role");return t?t.split(/\s+/).filter(Boolean).includes(o):!1}function k(e){return e.tagName.toLowerCase()==="table"||l(e,"table")||l(e,"grid")||l(e,"treegrid")}function y(e){return e.tagName.toLowerCase()==="tr"||l(e,"row")}function v(e){let o=null;for(let a=e.parentElement;a;a=a.parentElement)if(k(a)){o=a;break}return o?o.ownerDocument.createTreeWalker(o,NodeFilter.SHOW_ELEMENT,{acceptNode:a=>y(a)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}).nextNode()===e:!1}function u(e){const o=[];let t=!1;const a=e.getAttribute("role");if(a)for(const i of a.split(/\s+/).filter(Boolean))if((i==="presentation"||i==="none")&&(t=!0),i==="heading"){let r=2;const c=parseInt(e.getAttribute("aria-level")??"",10);Number.isFinite(c)&&c>=1&&(r=Math.min(c,6)),o.push(p[r-1])}else s[i]&&o.push(s[i]);const n=e.getAttribute("epub:type");if(n)for(const i of n.split(/\s+/).filter(Boolean)){const r=f[i];r&&o.push(r)}return{attrRoles:o,presentational:t}}function E(e){const{attrRoles:o,presentational:t}=u(e);return o.length>0||t}function R(e){const o=[],t=r=>{o.includes(r)||o.push(r)},{attrRoles:a,presentational:n}=u(e),i=e.tagName.toLowerCase();if(n)return["presentation"];if(w(e,i))return["presentation"];if(i==="body")t("body");else if(i==="th")switch(e.getAttribute("scope")){case"col":t("columnheader");break;case"row":t("rowheader");break;default:{const r=e.parentElement;r&&v(r)?t("columnheader"):e.previousElementSibling===null?t("rowheader"):t("cell")}}else{const r=g[i];r&&t(r)}for(const r of a)t(r);return o}export{R as extractNodeRoles,E as hasExplicitRole,x as nonSelfNestingRoles};
1
+ const p=["heading1","heading2","heading3","heading4","heading5","heading6"],c={"doc-abstract":"abstract","doc-acknowledgments":"acknowledgments","doc-afterword":"afterword","doc-appendix":"appendix",article:"article","doc-backlink":"backlink","doc-biblioentry":"listItem","doc-bibliography":"bibliography","doc-biblioref":"biblioref",blockquote:"blockquote",caption:"caption",cell:"cell","doc-chapter":"chapter","doc-colophon":"colophon",columnheader:"columnheader",complementary:"complementary","doc-conclusion":"conclusion","doc-cover":"cover","doc-credit":"credit","doc-credits":"credits","doc-dedication":"dedication",definition:"definition","doc-endnote":"footnote","doc-endnotes":"endnotes","doc-epigraph":"epigraph","doc-epilogue":"epilogue","doc-errata":"errata","doc-example":"example",figure:"figure","doc-footnote":"footnote","doc-foreword":"foreword","doc-glossary":"glossary","doc-glossref":"glossref",img:"image",image:"image","doc-index":"index","doc-introduction":"introduction",list:"list",listitem:"listItem",main:"main",math:"math",navigation:"navigation","doc-noteref":"noteref","doc-notice":"notice","doc-pagebreak":"pagebreak","doc-pagelist":"pagelist",paragraph:"paragraph","doc-part":"part","doc-preface":"preface","doc-prologue":"prologue","doc-pullquote":"pullquote",grid:"table",gridcell:"cell",presentation:"presentation",none:"presentation","doc-qna":"qna",qna:"qna",region:"region",row:"row",rowheader:"rowheader",separator:"separator","doc-subtitle":"subtitle",table:"table",term:"term","doc-tip":"tip","doc-toc":"toc"},g={abstract:"abstract",acknowledgments:"acknowledgments",afterword:"afterword",appendix:"appendix",aside:"aside",backlink:"backlink",balloon:"bubble",biblioentry:"listItem",bibliography:"bibliography",biblioref:"biblioref","table-cell":"cell",chapter:"chapter",colophon:"colophon",conclusion:"conclusion",cover:"cover",credit:"credit",credits:"credits",dedication:"dedication",glossdef:"definition",endnote:"footnote",endnotes:"endnotes",rearnote:"footnote",rearnotes:"endnotes",epigraph:"epigraph",epilogue:"epilogue",errata:"errata",example:"example",figure:"figure",footnote:"footnote",foreword:"foreword",glossary:"glossary",glossref:"glossref",index:"index",introduction:"introduction",landmarks:"landmarks",list:"list","list-item":"listItem",loa:"loa",loi:"loi",lot:"lot",lov:"lov",noteref:"noteref",notice:"notice",pagebreak:"pagebreak","page-list":"pagelist",panel:"panel","panel-group":"panelGroup",pagelist:"pagelist",part:"part",preface:"preface",prologue:"prologue",pullquote:"pullquote",qna:"qna","sound-area":"sound","table-row":"row",subtitle:"subtitle",table:"table",glossterm:"term",tip:"tip",toc:"toc"},f={abbr:"abbreviation",acronym:"abbreviation",article:"article",aside:"aside",audio:"audio",blockquote:"blockquote",caption:"caption",figcaption:"caption",td:"cell",dd:"definition",details:"details",figure:"figure",header:"header",h1:"heading1",h2:"heading2",h3:"heading3",h4:"heading4",h5:"heading5",h6:"heading6",img:"image",ul:"list",ol:"list",li:"listItem",main:"main",math:"math",nav:"navigation",p:"paragraph",pre:"preformatted",tr:"row",section:"section",hr:"separator",summary:"summary",table:"table",dfn:"term",dt:"term",video:"video",svg:"image"},x=new Set(["abbreviation","abstract","acknowledgments","afterword","bibliography","body","bubble","caption","cell","chapter","colophon","columnheader","conclusion","cover","credit","credits","dedication","definition","endnotes","epigraph","epilogue","errata","footnote","foreword","glossary",...p,"index","introduction","landmarks","listItem","loa","loi","lot","lov","main","pagelist","panel","paragraph","preface","prologue","pullquote","row","rowheader","sound","subtitle","summary","term","toc"]),b=new Set(["tr","td","th"]),m=new Set(["tr","thead","tbody","tfoot"]);function h(e){const o=e.getAttribute("role");if(!o)return!1;const t=o.split(/\s+/).filter(Boolean);return t.includes("presentation")||t.includes("none")}function d(e){return(e.getAttribute("role")??"").trim()!==""}function w(e,o){if(!b.has(o)||d(e))return!1;for(let t=e.parentElement;t;t=t.parentElement){const a=t.tagName.toLowerCase();if(a!=="table"&&!m.has(a))return!1;if(h(t))return!0;if(a==="table"||d(t))return!1}return!1}function l(e,o){const t=e.getAttribute("role");return t?t.split(/\s+/).filter(Boolean).includes(o):!1}function k(e){return e.tagName.toLowerCase()==="table"||l(e,"table")||l(e,"grid")||l(e,"treegrid")}function y(e){return e.tagName.toLowerCase()==="tr"||l(e,"row")}function v(e){let o=null;for(let a=e.parentElement;a;a=a.parentElement)if(k(a)){o=a;break}return o?o.ownerDocument.createTreeWalker(o,NodeFilter.SHOW_ELEMENT,{acceptNode:a=>y(a)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}).nextNode()===e:!1}function u(e){const o=[];let t=!1;const a=e.getAttribute("role");if(a)for(const n of a.split(/\s+/).filter(Boolean))if((n==="presentation"||n==="none")&&(t=!0),n==="heading"){let r=2;const s=parseInt(e.getAttribute("aria-level")??"",10);Number.isFinite(s)&&s>=1&&(r=Math.min(s,6)),o.push(p[r-1])}else c[n]&&o.push(c[n]);const i=e.getAttribute("epub:type");if(i)for(const n of i.split(/\s+/).filter(Boolean)){const r=g[n];r&&o.push(r)}return{attrRoles:o,presentational:t}}function E(e){const{attrRoles:o,presentational:t}=u(e);return o.length>0||t}function R(e){const o=[],t=r=>{o.includes(r)||o.push(r)},{attrRoles:a,presentational:i}=u(e),n=e.tagName.toLowerCase();if(i)return["presentation"];if(w(e,n))return["presentation"];if(n==="body")t("body");else if(n==="th")switch(e.getAttribute("scope")){case"col":t("columnheader");break;case"row":t("rowheader");break;default:{const r=e.parentElement;r&&v(r)?t("columnheader"):e.previousElementSibling===null?t("rowheader"):t("cell")}}else{const r=f[n];r&&t(r)}for(const r of a)t(r);return o}export{R as extractNodeRoles,E as hasExplicitRole,x as nonSelfNestingRoles};
@@ -21,6 +21,7 @@ renaming, or removing a fixture.
21
21
  | `biblioref` | `biblioref-epub-type`, `biblioref-role-aria`, `biblioref-target-descendant-ids`, `biblioref-target-in-bibliography-role-aria`, `biblioref-target-mixed-content` |
22
22
  | `blockquote` | `blockquote-html-native`, `blockquote-role-aria`, `nested-blockquote` |
23
23
  | `body` | `body-html-native` |
24
+ | `bubble` | `bubble-epub-type` |
24
25
  | `chapter` | `chapter-epub-type`, `chapter-role-aria`, `redundant-role-body-chapter`, `redundant-role-nested-chapter` |
25
26
  | `colophon` | `colophon-epub-type`, `colophon-role-aria` |
26
27
  | `complementary` | `complementary-role-aria` |
@@ -62,6 +63,8 @@ renaming, or removing a fixture.
62
63
  | `notice` | `notice-epub-type`, `notice-role-aria` |
63
64
  | `pagebreak` | `language-pagebreak-label`, `pagebreak-epub-type`, `pagebreak-role-aria` |
64
65
  | `pagelist` | `pagelist-epub-type`, `pagelist-role-aria` |
66
+ | `panel` | `panel-epub-type`, `panel-object-role-img`, `panel-role-img-labelled`, `panel-svg-epub-type` |
67
+ | `panelGroup` | `panel-group-epub-type` |
65
68
  | `paragraph` | `paragraph-basic` |
66
69
  | `part` | `part-epub-type`, `part-role-aria` |
67
70
  | `preface` | `preface-epub-type`, `preface-role-aria` |
@@ -73,6 +76,7 @@ renaming, or removing a fixture.
73
76
  | `region` | `region-role-aria` |
74
77
  | `section` | `nested-section`, `section-html-native` |
75
78
  | `separator` | `separator-html-native`, `separator-role-aria`, `separator-with-glyphs` |
79
+ | `sound` | `sound-epub-type` |
76
80
  | `subtitle` | `subtitle-epub-type`, `subtitle-role-aria` |
77
81
  | `summary` | `summary-html-native` |
78
82
  | `table` | `table-aria-label-caption`, `table-caption`, `table-caption-aria-labelledby`, `table-caption-element-html-native`, `table-caption-role-aria`, `table-cell-abbreviation`, `table-cell-noteref`, `table-colspan-html-native`, `table-colspan-role-aria`, `table-epub-type`, `table-html-native`, `table-in-role-none-wrapper`, `table-nested-html-native`, `table-nested-role-aria`, `table-no-headers`, `table-role-aria`, `table-rowgroup-role-aria`, `table-rowspan-html-native`, `table-rowspan-role-aria`, `table-sectioning`, `table-th-no-scope` |
@@ -81,4 +85,4 @@ renaming, or removing a fixture.
81
85
  | `toc` | `toc-epub-type`, `toc-role-aria` |
82
86
  | `video` | `video-html-native`, `video-no-description` |
83
87
 
84
- 263 fixtures across 73 roles.
88
+ 270 fixtures across 77 roles.
@@ -0,0 +1,11 @@
1
+ {
2
+ "role": ["body"],
3
+ "children": [
4
+ {
5
+ "role": ["paragraph", "bubble"],
6
+ "text": {
7
+ "plain": "The keeper says: \"Nearly there.\""
8
+ }
9
+ }
10
+ ]
11
+ }
@@ -0,0 +1,11 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <!DOCTYPE html>
3
+ <html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops">
4
+ <head>
5
+ <meta charset="utf-8"/>
6
+ <title>Fixture</title>
7
+ </head>
8
+ <body>
9
+ <p epub:type="balloon">The keeper says: "Nearly there."</p>
10
+ </body>
11
+ </html>
@@ -0,0 +1,10 @@
1
+ {
2
+ "id": "bubble-epub-type",
3
+ "description": "bubble role via epub:type=\"balloon\" on a <p>",
4
+ "role": "bubble",
5
+ "rolesCovered": [
6
+ "bubble"
7
+ ],
8
+ "sourceRef": "https://www.w3.org/TR/epub-ssv-11/#sec-comics",
9
+ "inputKind": "document"
10
+ }
@@ -439,6 +439,16 @@
439
439
  "gnd": "gnd.json"
440
440
  }
441
441
  },
442
+ {
443
+ "id": "bubble-epub-type",
444
+ "dir": "bubble-epub-type",
445
+ "role": "bubble",
446
+ "description": "bubble role via epub:type=\"balloon\" on a <p>",
447
+ "files": {
448
+ "input": "input.xhtml",
449
+ "gnd": "gnd.json"
450
+ }
451
+ },
442
452
  {
443
453
  "id": "chapter-epub-type",
444
454
  "dir": "chapter-epub-type",
@@ -2039,6 +2049,56 @@
2039
2049
  "gnd": "gnd.json"
2040
2050
  }
2041
2051
  },
2052
+ {
2053
+ "id": "panel-epub-type",
2054
+ "dir": "panel-epub-type",
2055
+ "role": "panel",
2056
+ "description": "A comic panel via epub:type=\"panel\" on a labelled region <section>, holding a description and a balloon",
2057
+ "files": {
2058
+ "input": "input.xhtml",
2059
+ "gnd": "gnd.json"
2060
+ }
2061
+ },
2062
+ {
2063
+ "id": "panel-group-epub-type",
2064
+ "dir": "panel-group-epub-type",
2065
+ "role": "panelGroup",
2066
+ "description": "panelGroup role via epub:type=\"panel-group\" on a <div> grouping two panels",
2067
+ "files": {
2068
+ "input": "input.xhtml",
2069
+ "gnd": "gnd.json"
2070
+ }
2071
+ },
2072
+ {
2073
+ "id": "panel-object-role-img",
2074
+ "dir": "panel-object-role-img",
2075
+ "role": "panel",
2076
+ "description": "A comic panel via epub:type=\"panel\" on an inline <object> with role=\"img\" — it stays an image placeholder described by its label, its fallback content not read",
2077
+ "files": {
2078
+ "input": "input.xhtml",
2079
+ "gnd": "gnd.json"
2080
+ }
2081
+ },
2082
+ {
2083
+ "id": "panel-role-img-labelled",
2084
+ "dir": "panel-role-img-labelled",
2085
+ "role": "panel",
2086
+ "description": "A panel with role=\"img\" and an aria-label — the label becomes its description and its balloon is kept, unlike an image",
2087
+ "files": {
2088
+ "input": "input.xhtml",
2089
+ "gnd": "gnd.json"
2090
+ }
2091
+ },
2092
+ {
2093
+ "id": "panel-svg-epub-type",
2094
+ "dir": "panel-svg-epub-type",
2095
+ "role": "panel",
2096
+ "description": "A comic panel via epub:type=\"panel\" on an <svg> — it stays an image placeholder described by its label, its inner SVG text not read",
2097
+ "files": {
2098
+ "input": "input.xhtml",
2099
+ "gnd": "gnd.json"
2100
+ }
2101
+ },
2042
2102
  {
2043
2103
  "id": "paragraph-basic",
2044
2104
  "dir": "paragraph-basic",
@@ -2239,6 +2299,16 @@
2239
2299
  "gnd": "gnd.json"
2240
2300
  }
2241
2301
  },
2302
+ {
2303
+ "id": "sound-epub-type",
2304
+ "dir": "sound-epub-type",
2305
+ "role": "sound",
2306
+ "description": "sound role via epub:type=\"sound-area\" on a <p>",
2307
+ "files": {
2308
+ "input": "input.xhtml",
2309
+ "gnd": "gnd.json"
2310
+ }
2311
+ },
2242
2312
  {
2243
2313
  "id": "subtitle-epub-type",
2244
2314
  "dir": "subtitle-epub-type",
@@ -0,0 +1,27 @@
1
+ {
2
+ "role": ["body"],
3
+ "children": [
4
+ {
5
+ "role": ["section", "region", "panel"],
6
+ "description": {
7
+ "text": {
8
+ "plain": "Panel 2"
9
+ }
10
+ },
11
+ "children": [
12
+ {
13
+ "role": ["paragraph"],
14
+ "text": {
15
+ "plain": "The keeper climbs the last steps of the lighthouse, lantern in hand."
16
+ }
17
+ },
18
+ {
19
+ "role": ["paragraph", "bubble"],
20
+ "text": {
21
+ "plain": "The keeper says: \"Nearly there.\""
22
+ }
23
+ }
24
+ ]
25
+ }
26
+ ]
27
+ }
@@ -0,0 +1,14 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <!DOCTYPE html>
3
+ <html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops">
4
+ <head>
5
+ <meta charset="utf-8"/>
6
+ <title>Fixture</title>
7
+ </head>
8
+ <body>
9
+ <section epub:type="panel" role="region" aria-label="Panel 2">
10
+ <p>The keeper climbs the last steps of the lighthouse, lantern in hand.</p>
11
+ <p epub:type="balloon">The keeper says: "Nearly there."</p>
12
+ </section>
13
+ </body>
14
+ </html>
@@ -0,0 +1,13 @@
1
+ {
2
+ "id": "panel-epub-type",
3
+ "description": "A comic panel via epub:type=\"panel\" on a labelled region <section>, holding a description and a balloon",
4
+ "role": "panel",
5
+ "rolesCovered": [
6
+ "panel",
7
+ "bubble",
8
+ "region",
9
+ "section"
10
+ ],
11
+ "sourceRef": "https://www.w3.org/TR/epub-ssv-11/#sec-comics",
12
+ "inputKind": "document"
13
+ }
@@ -0,0 +1,32 @@
1
+ {
2
+ "role": ["body"],
3
+ "children": [
4
+ {
5
+ "role": ["panelGroup"],
6
+ "children": [
7
+ {
8
+ "role": ["panel"],
9
+ "children": [
10
+ {
11
+ "role": ["paragraph"],
12
+ "text": {
13
+ "plain": "The lamp flickers."
14
+ }
15
+ }
16
+ ]
17
+ },
18
+ {
19
+ "role": ["panel"],
20
+ "children": [
21
+ {
22
+ "role": ["paragraph"],
23
+ "text": {
24
+ "plain": "The lamp goes dark."
25
+ }
26
+ }
27
+ ]
28
+ }
29
+ ]
30
+ }
31
+ ]
32
+ }
@@ -0,0 +1,14 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <!DOCTYPE html>
3
+ <html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops">
4
+ <head>
5
+ <meta charset="utf-8"/>
6
+ <title>Fixture</title>
7
+ </head>
8
+ <body>
9
+ <div epub:type="panel-group">
10
+ <div epub:type="panel"><p>The lamp flickers.</p></div>
11
+ <div epub:type="panel"><p>The lamp goes dark.</p></div>
12
+ </div>
13
+ </body>
14
+ </html>
@@ -0,0 +1,11 @@
1
+ {
2
+ "id": "panel-group-epub-type",
3
+ "description": "panelGroup role via epub:type=\"panel-group\" on a <div> grouping two panels",
4
+ "role": "panelGroup",
5
+ "rolesCovered": [
6
+ "panelGroup",
7
+ "panel"
8
+ ],
9
+ "sourceRef": "https://www.w3.org/TR/epub-ssv-11/#sec-comics",
10
+ "inputKind": "document"
11
+ }
@@ -0,0 +1,14 @@
1
+ {
2
+ "role": ["body"],
3
+ "children": [
4
+ {
5
+ "role": ["image", "panel"],
6
+ "description": {
7
+ "text": {
8
+ "plain": "The keeper at the top of the stairs"
9
+ }
10
+ },
11
+ "textref": "#css(object)"
12
+ }
13
+ ]
14
+ }
@@ -0,0 +1,11 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <!DOCTYPE html>
3
+ <html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops">
4
+ <head>
5
+ <meta charset="utf-8"/>
6
+ <title>Fixture</title>
7
+ </head>
8
+ <body>
9
+ <object data="panel1.svg" type="image/svg+xml" epub:type="panel" role="img" aria-label="The keeper at the top of the stairs">Panel artwork</object>
10
+ </body>
11
+ </html>
@@ -0,0 +1,11 @@
1
+ {
2
+ "id": "panel-object-role-img",
3
+ "description": "A comic panel via epub:type=\"panel\" on an inline <object> with role=\"img\" — it stays an image placeholder described by its label, its fallback content not read",
4
+ "role": "panel",
5
+ "rolesCovered": [
6
+ "panel",
7
+ "image"
8
+ ],
9
+ "sourceRef": "https://www.w3.org/TR/epub-ssv-11/#sec-comics",
10
+ "inputKind": "document"
11
+ }
@@ -0,0 +1,21 @@
1
+ {
2
+ "role": ["body"],
3
+ "children": [
4
+ {
5
+ "role": ["image", "panel"],
6
+ "description": {
7
+ "text": {
8
+ "plain": "The keeper at the top of the stairs"
9
+ }
10
+ },
11
+ "children": [
12
+ {
13
+ "role": ["paragraph", "bubble"],
14
+ "text": {
15
+ "plain": "The keeper says: \"Nearly there.\""
16
+ }
17
+ }
18
+ ]
19
+ }
20
+ ]
21
+ }
@@ -0,0 +1,13 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <!DOCTYPE html>
3
+ <html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops">
4
+ <head>
5
+ <meta charset="utf-8"/>
6
+ <title>Fixture</title>
7
+ </head>
8
+ <body>
9
+ <div epub:type="panel" role="img" aria-label="The keeper at the top of the stairs">
10
+ <p epub:type="balloon">The keeper says: "Nearly there."</p>
11
+ </div>
12
+ </body>
13
+ </html>
@@ -0,0 +1,12 @@
1
+ {
2
+ "id": "panel-role-img-labelled",
3
+ "description": "A panel with role=\"img\" and an aria-label — the label becomes its description and its balloon is kept, unlike an image",
4
+ "role": "panel",
5
+ "rolesCovered": [
6
+ "panel",
7
+ "image",
8
+ "bubble"
9
+ ],
10
+ "sourceRef": "https://www.w3.org/TR/epub-ssv-11/#sec-comics",
11
+ "inputKind": "document"
12
+ }
@@ -0,0 +1,14 @@
1
+ {
2
+ "role": ["body"],
3
+ "children": [
4
+ {
5
+ "role": ["image", "panel"],
6
+ "description": {
7
+ "text": {
8
+ "plain": "Panel 1"
9
+ }
10
+ },
11
+ "textref": "#css(svg)"
12
+ }
13
+ ]
14
+ }
@@ -0,0 +1,11 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <!DOCTYPE html>
3
+ <html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops">
4
+ <head>
5
+ <meta charset="utf-8"/>
6
+ <title>Fixture</title>
7
+ </head>
8
+ <body>
9
+ <svg xmlns="http://www.w3.org/2000/svg" epub:type="panel" aria-label="Panel 1"><title>Panel artwork</title><text>Crash!</text></svg>
10
+ </body>
11
+ </html>
@@ -0,0 +1,11 @@
1
+ {
2
+ "id": "panel-svg-epub-type",
3
+ "description": "A comic panel via epub:type=\"panel\" on an <svg> — it stays an image placeholder described by its label, its inner SVG text not read",
4
+ "role": "panel",
5
+ "rolesCovered": [
6
+ "panel",
7
+ "image"
8
+ ],
9
+ "sourceRef": "https://www.w3.org/TR/epub-ssv-11/#sec-comics",
10
+ "inputKind": "document"
11
+ }
@@ -0,0 +1,11 @@
1
+ {
2
+ "role": ["body"],
3
+ "children": [
4
+ {
5
+ "role": ["paragraph", "sound"],
6
+ "text": {
7
+ "plain": "Crash!"
8
+ }
9
+ }
10
+ ]
11
+ }
@@ -0,0 +1,11 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <!DOCTYPE html>
3
+ <html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops">
4
+ <head>
5
+ <meta charset="utf-8"/>
6
+ <title>Fixture</title>
7
+ </head>
8
+ <body>
9
+ <p epub:type="sound-area">Crash!</p>
10
+ </body>
11
+ </html>
@@ -0,0 +1,10 @@
1
+ {
2
+ "id": "sound-epub-type",
3
+ "description": "sound role via epub:type=\"sound-area\" on a <p>",
4
+ "role": "sound",
5
+ "rolesCovered": [
6
+ "sound"
7
+ ],
8
+ "sourceRef": "https://www.w3.org/TR/epub-ssv-11/#sec-comics",
9
+ "inputKind": "document"
10
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@readium/guided-navigation",
3
- "version": "1.4.0",
3
+ "version": "1.5.0",
4
4
  "type": "module",
5
5
  "description": "Guided Navigation document generation from HTML and XHTML content",
6
6
  "author": "readium",
package/src/converter.ts CHANGED
@@ -286,7 +286,7 @@ export class Converter {
286
286
  this.placeholder(el, tagName, obj);
287
287
  return true;
288
288
  }
289
- if (roles.includes("image") || roles.includes("math")) {
289
+ if (Converter.actsAsImage(tagName, roles) || roles.includes("math")) {
290
290
  // Elements acting as images without being one, e.g. <span role="img">:
291
291
  // their content is replaced by their accessible name.
292
292
  const obj: ObjBuilder = { role: roles };
@@ -448,10 +448,16 @@ export class Converter {
448
448
 
449
449
  // What head() embeds as a placeholder in the flow, rather than descending into.
450
450
  private static isPlaceholder(el: Element, tagName: string, roles: GndRole[]): boolean {
451
- if (roles.includes("pagebreak") || roles.includes("image") || roles.includes("math")) return true;
451
+ if (roles.includes("pagebreak") || Converter.actsAsImage(tagName, roles) || roles.includes("math")) return true;
452
452
  return ["img", "svg", "audio", "video"].includes(tagName) || (tagName === "a" && !!el.getAttribute("href"));
453
453
  }
454
454
 
455
+ // A block comic panel holds its bubbles: an image role on it doesn't replace its content, unless it's an <svg>.
456
+ private static actsAsImage(tagName: string, roles: GndRole[]): boolean {
457
+ const isPanel = roles.includes("panel") || roles.includes("panelGroup");
458
+ return roles.includes("image") && (tagName === "svg" || !isPanel || !isBlockNode(tagName, roles));
459
+ }
460
+
455
461
  // The outermost abbreviation whose text is all in obj, apart from punctuation alongside it.
456
462
  private static abbreviationOver(obj: Element): Element | null {
457
463
  let abbr: Element | null = null;
package/src/roles.ts CHANGED
@@ -89,6 +89,7 @@ const epubTypeRoles: Record<string, GndRole> = {
89
89
  appendix: "appendix",
90
90
  aside: "aside",
91
91
  backlink: "backlink",
92
+ balloon: "bubble",
92
93
  biblioentry: "listItem", // Deprecated in DPUB-ARIA 1.1
93
94
  bibliography: "bibliography",
94
95
  biblioref: "biblioref",
@@ -127,12 +128,15 @@ const epubTypeRoles: Record<string, GndRole> = {
127
128
  notice: "notice",
128
129
  pagebreak: "pagebreak",
129
130
  "page-list": "pagelist",
131
+ panel: "panel",
132
+ "panel-group": "panelGroup",
130
133
  pagelist: "pagelist",
131
134
  part: "part",
132
135
  preface: "preface",
133
136
  prologue: "prologue",
134
137
  pullquote: "pullquote",
135
138
  qna: "qna",
139
+ "sound-area": "sound",
136
140
  "table-row": "row",
137
141
  subtitle: "subtitle",
138
142
  table: "table",
@@ -190,6 +194,7 @@ export const nonSelfNestingRoles: ReadonlySet<GndRole> = new Set([
190
194
  "afterword",
191
195
  "bibliography",
192
196
  "body",
197
+ "bubble",
193
198
  "caption",
194
199
  "cell",
195
200
  "chapter",
@@ -219,12 +224,14 @@ export const nonSelfNestingRoles: ReadonlySet<GndRole> = new Set([
219
224
  "lov",
220
225
  "main",
221
226
  "pagelist",
227
+ "panel",
222
228
  "paragraph",
223
229
  "preface",
224
230
  "prologue",
225
231
  "pullquote",
226
232
  "row",
227
233
  "rowheader",
234
+ "sound",
228
235
  "subtitle",
229
236
  "summary",
230
237
  "term",
@@ -63,6 +63,7 @@ export declare class Converter {
63
63
  private textContext;
64
64
  private static containsObject;
65
65
  private static isPlaceholder;
66
+ private static actsAsImage;
66
67
  private static abbreviationOver;
67
68
  private static punctuationOwner;
68
69
  private static ownPunctuation;