@readium/guided-navigation 1.0.0 → 1.1.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/README.md +6 -2
- package/dist/a11y.js +1 -1
- package/dist/converter.js +1 -1
- package/dist/href.js +1 -0
- package/dist/textrefFragment.js +1 -1
- package/fixtures/ROLES_COVERAGE.md +2 -1
- package/fixtures/accessible-name-labelledby-aria-hidden/gnd.json +31 -0
- package/fixtures/accessible-name-labelledby-aria-hidden/input.html +3 -0
- package/fixtures/accessible-name-labelledby-aria-hidden/meta.json +10 -0
- package/fixtures/accessible-name-labelledby-hidden-attribute/gnd.json +31 -0
- package/fixtures/accessible-name-labelledby-hidden-attribute/input.html +3 -0
- package/fixtures/accessible-name-labelledby-hidden-attribute/meta.json +10 -0
- package/fixtures/manifest.json +20 -0
- package/package.json +1 -1
- package/src/a11y.ts +1 -1
- package/src/converter.ts +7 -1
- package/src/href.ts +26 -0
- package/src/options.ts +3 -0
- package/src/textrefFragment.ts +24 -16
- package/types/src/converter.d.ts +1 -0
- package/types/src/href.d.ts +3 -0
- package/types/src/options.d.ts +1 -0
- package/types/src/textrefFragment.d.ts +1 -0
package/README.md
CHANGED
|
@@ -35,6 +35,8 @@ Malformed XHTML (an undeclared `epub:` prefix, an HTML entity like ` `…)
|
|
|
35
35
|
|
|
36
36
|
`makeGnd` returns `undefined` when the input has no navigable content, since a document's `guided` can't be empty. `parseMarkup` returns the objects without the document wrapper, and an empty array in that case.
|
|
37
37
|
|
|
38
|
+
Pass the input's own href as `{ href }` to resolve every ref (`textref`, `imgref`, `audioref`, `videoref`) against it: with `OEBPS/text/chapter.xhtml`, `#p1` becomes `OEBPS/text/chapter.xhtml#p1` and `../images/a.png` becomes `OEBPS/images/a.png`. Refs come out URL-encoded (`my chapter.xhtml` becomes `my%20chapter.xhtml`), so pass an encoded href to get it back unchanged.
|
|
39
|
+
|
|
38
40
|
Use `serialize()` on the result to get the JSON.
|
|
39
41
|
|
|
40
42
|
## Text references (`textrefs`)
|
|
@@ -90,13 +92,15 @@ If the node's text is too long, the polyfill only keeps the first few words and
|
|
|
90
92
|
Use `decodeTextref({ id, textref })` to read a `textref` back. It returns:
|
|
91
93
|
|
|
92
94
|
```typescript
|
|
93
|
-
{ cssSelector?, domRange?, text?, fragment? }
|
|
95
|
+
{ href?, cssSelector?, domRange?, text?, fragment? }
|
|
94
96
|
```
|
|
95
97
|
|
|
98
|
+
- `href` → the resource named before the fragment, when there is one (`chapter.xhtml#css(...)`)
|
|
99
|
+
|
|
96
100
|
- Exact match (one quote) → `text: { highlight, before?, after? }`
|
|
97
101
|
- Range (the `textStart`/`textEnd` case above) → `fragment` (the raw `:~:text=...` string)
|
|
98
102
|
|
|
99
|
-
It returns `undefined` if the `textref`
|
|
103
|
+
It returns `undefined` if the `textref` is navigational rather than a reference to the node's own content, e.g. a link's `href`. `#css(...)` and `#domrange(...)` are always the node's own. A `#id` is the node's own only when it matches the node's `id`. `combineDomRangeTextrefs(first, last)` joins two decoded `domRange` references into one spanning both, as long as they're in the same resource.
|
|
100
104
|
|
|
101
105
|
The lower-level pieces are exported too: `encodeCssSelectorFragment(selector)`/`decodeCssSelectorFragment(textref)` for `#css(...)`, and `encodeDomRangeFragment(domRange)`/`decodeDomRangeFragment(textref)` for `#domrange(...)` (a `DomRangeJSON`: `{ start: { cssSelector, textNodeIndex, charOffset? }, end?: {...} }`, the RWPM shape behind `@readium/shared`'s `DomRange`).
|
|
102
106
|
|
package/dist/a11y.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{normalizeWhitespace as c}from"./text.js";import{hasExplicitRole as
|
|
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};
|
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 I}from"./a11y.js";import{normalizeWhitespace as L,ctxEqual as _}from"./text.js";import{ssmlAttrEscape as A,ssmlTextEscape as v,startsWithBindingPunct as q}from"@readium/helpers";import{NavObject as w,isEmptyObj as D,finalizeToGuidedNavigationObject as X}from"./object.js";import{sniffMediaType as G,nodeLanguage as y,isInlineTag as H}from"./dom.js";import{encodeDomRangeFragment as U,encodeTextFragmentDirective as V}from"./textrefFragment.js";import{rootAnchorSelector as Y,textrefForSelector as S,selectorForElement as C}from"./selectorGenerator.js";import{generateDomRange as J}from"./domRangeGenerator.js";import{textFragmentDirectiveFor as K}from"./textFragmentGenerator.js";import{normalizeTextrefOptions as Q}from"./options.js";import{IdAllocator as Z}from"./idAllocator.js";import{prescan as tt}from"./prescan.js";import{pagebreak as et,noteref as st,link as it}from"./elementHandlers.js";const nt="http://www.w3.org/1998/Math/MathML",rt=3,ot=1,lt=new Set(["summary","dfn","span"]);function M(c,t){return lt.has(c)&&t.length>0?!0:!H(c)}class b{constructor(t){this.ids=new Map,this.suppressed=new Set,this.idAlloc=new Z,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){tt(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(){return this.resultBuilders().map(X)}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===rt){this.text(t);return}if(t.nodeType!==ot)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!et(this,t,s,i);if(e==="a"&&i.includes("noteref")&&t.getAttribute("href"))return st(this,t,i),!0;if(e==="a"&&t.getAttribute("href"))return it(this,t,i,s),!0;if(e==="img"){const o={role:i},r=t.getAttribute("src");return r&&(o.imgref=r),s&&(o.description=s),this.placeholder(t,"image",o),!0}if(e==="audio"||e==="video"){const o={role:i};let r=t.getAttribute("src");if(!r){const f=t.querySelector(":scope > source[src]");f&&(r=f.getAttribute("src"))}return e==="audio"?r&&(o.audioref=r):r&&(o.videoref=r),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 r=z(t);r&&(o.text={plain:r,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 h=this.current.object;if(i.length>0&&(h.role=i),s)h.description=s,i.includes("figure")&&(this.current.noText=!0);else if(i.includes("figure")){const o=this.implicitCaptionOf(t);if(o){const r=O(o);r&&(h.description=r,this.current.noText=!0)}}else if(i.includes("table")){const o=this.implicitCaptionOf(t);if(o){const r=O(o);r&&(h.description=r,this.foldedCaptions.add(o))}}const p=t.getAttribute("id");return p&&(h.id=p),!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 h=this.leafTextEnabled&&i.length===0&&!!this.lastFlowText;(this.selectorPredicate?.(i)||h)&&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=J(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=K(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+=L(e,this.flowEndsWithSpace),this.updateFlowSpace());return}const s=this.textContext(t);if(_(s,this.currentCtx)||(this.closeSegment(),this.currentCtx=s),this.textAcc+=L(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]=I(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,h=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}if(!t.some(n=>n.kind==="text"&&n.text.trim()!=="")){for(const n of e)this.appendChild(n);return}const o=[];for(const n of t)if(n.kind==="text"&&n.text.trim()!==""){const l=n.ctx.lang;o.includes(l)||o.push(l)}let r=y(this.current.el??null);o.length===1&&o[0]!==""&&(r=o[0]);let f=!1;for(const n of t)if(n.kind!=="text"||n.ctx.tag!==""||n.ctx.lang!==r){f=!0;break}if(f&&r===""&&(r="en"),f)for(const n of t){if(n.kind!=="placeholder")continue;let l=n.candidateID;(!l||!this.idAlloc.claim(l))&&(l=this.idAlloc.allocate(n.tag,g=>this.ids.has(g))),n.child.object.id=l}let u="",d=!1,E=!1,T=!1,R=!1;for(const n of t)if(n.kind==="text"){const l=n.text.startsWith(" "),g=n.text.replace(/^ +| +$/g,"");if(g===""){R=!0;continue}let m=!1;if(u.length>0){const x=d||R||l;E?m=!0:T?m=x&&!q(g):m=x}m&&(u+=" "),u+=g,d=n.text.endsWith(" "),E=!1,T=!1,R=!1}else n.kind==="break"?E=!0:n.kind==="placeholder"&&(T=!0);const $=t.some(n=>n.kind==="placeholder");this.lastFlowText=u.trim();const N={plain:f&&!$?"":u.trim(),ssml:"",language:r};if(f){let n="";for(const l of t)if(l.kind==="text"){let g=l.ctx.tag,m=l.ctx.attrs;if(l.ctx.lang!==r&&l.ctx.lang!==""&&(g="lang",m=void 0),g){n+=`<${g}`;for(const[x,j]of Object.entries(m??{}))n+=` ${x}="${A(j)}"`;l.ctx.lang!==r&&l.ctx.lang!==""&&(n+=` xml:lang="${A(l.ctx.lang)}"`),n+=`>${v(l.text)}</${g}>`}else n+=v(l.text)}else l.kind==="break"?n+="<break/>":l.kind==="placeholder"&&(n+=`<readium:${l.tag} id="${A(l.child.object.id)}" />`);N.ssml=n}const k=new w;k.object={text:N};for(const n of e)k.children.push(n);this.appendChild(k),s&&i&&(this.lastFlowRange={first:[s,a],last:[i,h]})}}const at=/<body[\s>]/i;function kt(c,t,e){const{predicate:s,leafText:a,domRange:i,textFragment:h}=Q(e?.textrefs);if(typeof c!="string"){const u=t??(c.ownerDocument.contentType==="text/html"?"text/html":"application/xhtml+xml"),d=new b(u==="application/xhtml+xml");return d.selectorPredicate=s,d.leafTextEnabled=a,d.domRangeEnabled=i,d.textFragmentEnabled=h,d.docRoot=c.ownerDocument,d.selectorRoot=c,d.selectorRootAnchor=Y(c),d.convert(c),d.result()}let p=t??G(c),o=new DOMParser().parseFromString(c,p);if(p==="application/xhtml+xml"){const u=o.getElementsByTagNameNS("*","parsererror")[0];if(u){if(!e?.htmlFallback)throw new Error(`XHTML parsing failed: ${u.textContent?.trim()??""}`);p="text/html",o=new DOMParser().parseFromString(c,p)}}const r=new b(p==="application/xhtml+xml");r.selectorPredicate=s,r.leafTextEnabled=a,r.textFragmentEnabled=h,r.docRoot=o;const f=o.querySelector("body");return f&&!at.test(c)?r.convertChildren(f):r.convert(f??o.documentElement),r.result()}export{b as Converter,kt as parseMarkup};
|
|
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};
|
package/dist/href.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const a=/^[a-z][a-z\d+.-]*:/i,c="https://gnd.invalid/";function n(t,e){if(a.test(t))return t;const i=t.indexOf("#"),s=i===-1?t:t.slice(0,i),r=i===-1?"":t.slice(i);if(a.test(e))return new URL(s,e).href+r;if(e.startsWith("//"))return new URL(s,"https:"+e).href.slice(6)+r;const f=new URL(s,c+e.replace(/^\/+/,"")).href;return f.startsWith(c)?f.slice(c.length)+r:t}function d(t,e){t.textref&&(t.textref=n(t.textref,e)),t.imgref&&(t.imgref=n(t.imgref,e)),t.audioref&&(t.audioref=n(t.audioref,e)),t.videoref&&(t.videoref=n(t.videoref,e)),t.children?.forEach(i=>d(i,e))}export{n as resolveRef,d as resolveRefs};
|
package/dist/textrefFragment.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const
|
|
1
|
+
const l="#css(";function C(e){return`${l}${encodeURIComponent(e)})`}function v(e){if(!(!e||!e.startsWith(l)||!e.endsWith(")")))return decodeURIComponent(e.slice(l.length,-1))}const m="#domrange(",g=")";function U(e){return`${m}${encodeURIComponent(JSON.stringify(e))}${g}`}function x(e){if(!(!e||!e.startsWith(m)||!e.endsWith(g)))try{const n=JSON.parse(decodeURIComponent(e.slice(m.length,-g.length)));return!n?.start?.cssSelector||typeof n.start.textNodeIndex!="number"?void 0:n}catch{return}}const h=":~:text=";function a(e){return encodeURIComponent(e).replace(/-/g,"%2D")}function I(e){let n="";return e.prefix&&(n+=`${a(e.prefix)}-,`),n+=a(e.textStart),e.textEnd&&(n+=`,${a(e.textEnd)}`),e.suffix&&(n+=`,-${a(e.suffix)}`),`${h}${n}`}function p(e){if(!e)return;const n=e.indexOf(h);if(n===-1)return;const o=e.slice(n+h.length).split("&")[0];if(o)try{let t=o.split(",");const i={textStart:""};return t[0].endsWith("-")&&(i.prefix=decodeURIComponent(t[0].slice(0,-1)),t=t.slice(1)),t.length>0&&t[t.length-1].startsWith("-")&&(i.suffix=decodeURIComponent(t[t.length-1].slice(1)),t=t.slice(0,-1)),t.length===0||t[0]===""?void 0:(i.textStart=decodeURIComponent(t[0]),t.length>1&&(i.textEnd=decodeURIComponent(t[1])),i)}catch{return}}function $(e,n){if(!e.domRange||!n.domRange||e.href!==n.href)return;const o={start:e.domRange.start,end:n.domRange.end??n.domRange.start};e.domRange.container!==void 0&&(o.container=e.domRange.container);const t={domRange:o,cssSelector:o.container??o.start.cssSelector};return e.href!==void 0&&(t.href=e.href),t}function F(e){if(e.startsWith("#"))try{return decodeURIComponent(e.slice(1))}catch{return}}function E(e){const n=e?.textref;if(!n)return;const o=n.indexOf(":~:"),t=o===-1?n:n.slice(0,o),i=t.indexOf("#"),S=i===-1?t:t.slice(0,i),u=i===-1?"":t.slice(i);let d,s;const f=x(u);if(f)s=f,d=f.container??f.start.cssSelector;else{const R=v(u);R!==void 0?d=R:e.id&&F(u)===e.id&&(d=`#${CSS.escape(e.id)}`)}const r=p(n);if(d===void 0&&s===void 0&&r===void 0)return;const c={};return S!==""&&(c.href=S),d!==void 0&&(c.cssSelector=d),s!==void 0&&(c.domRange=s),r?.textEnd!==void 0?c.fragment=I(r):r&&(c.text={highlight:r.textStart},r.prefix!==void 0&&(c.text.before=r.prefix),r.suffix!==void 0&&(c.text.after=r.suffix)),c}export{$ as combineDomRangeTextrefs,v as decodeCssSelectorFragment,x as decodeDomRangeFragment,p as decodeTextFragmentDirective,E as decodeTextref,C as encodeCssSelectorFragment,U as encodeDomRangeFragment,I as encodeTextFragmentDirective};
|
|
@@ -8,6 +8,7 @@ renaming, or removing a fixture.
|
|
|
8
8
|
| Role | Fixtures |
|
|
9
9
|
| --- | --- |
|
|
10
10
|
| `abstract` | `abstract-epub-type`, `abstract-role-aria` |
|
|
11
|
+
| `accessible-name` | `accessible-name-labelledby-aria-hidden`, `accessible-name-labelledby-hidden-attribute` |
|
|
11
12
|
| `acknowledgments` | `acknowledgments-epub-type`, `acknowledgments-role-aria` |
|
|
12
13
|
| `afterword` | `afterword-epub-type`, `afterword-role-aria` |
|
|
13
14
|
| `appendix` | `appendix-epub-type`, `appendix-role-aria` |
|
|
@@ -77,4 +78,4 @@ renaming, or removing a fixture.
|
|
|
77
78
|
| `toc` | `toc-epub-type`, `toc-role-aria` |
|
|
78
79
|
| `video` | `video-html-native`, `video-no-description` |
|
|
79
80
|
|
|
80
|
-
|
|
81
|
+
180 fixtures across 70 roles.
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
{
|
|
2
|
+
"children": [
|
|
3
|
+
{
|
|
4
|
+
"role": [
|
|
5
|
+
"paragraph"
|
|
6
|
+
],
|
|
7
|
+
"text": {
|
|
8
|
+
"language": "en",
|
|
9
|
+
"plain": "Into speech.",
|
|
10
|
+
"ssml": "Into speech. <readium:link id=\"link1\" />"
|
|
11
|
+
},
|
|
12
|
+
"children": [
|
|
13
|
+
{
|
|
14
|
+
"id": "link1",
|
|
15
|
+
"textref": "#gloss",
|
|
16
|
+
"text": {
|
|
17
|
+
"plain": "see glossary entry"
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
]
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
"role": [
|
|
24
|
+
"paragraph"
|
|
25
|
+
],
|
|
26
|
+
"text": {
|
|
27
|
+
"plain": "synthesized speech can be created."
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
]
|
|
31
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
{
|
|
2
|
+
"id": "accessible-name-labelledby-aria-hidden",
|
|
3
|
+
"description": "A link named via aria-labelledby pointing at an element marked aria-hidden=\"true\": the hidden label still names the link, and is not emitted on its own",
|
|
4
|
+
"role": "accessible-name",
|
|
5
|
+
"rolesCovered": [
|
|
6
|
+
"paragraph"
|
|
7
|
+
],
|
|
8
|
+
"sourceRef": "https://www.w3.org/TR/accname/#computation-steps",
|
|
9
|
+
"inputKind": "fragment"
|
|
10
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
{
|
|
2
|
+
"children": [
|
|
3
|
+
{
|
|
4
|
+
"role": [
|
|
5
|
+
"paragraph"
|
|
6
|
+
],
|
|
7
|
+
"text": {
|
|
8
|
+
"language": "en",
|
|
9
|
+
"plain": "Into speech.",
|
|
10
|
+
"ssml": "Into speech. <readium:link id=\"link1\" />"
|
|
11
|
+
},
|
|
12
|
+
"children": [
|
|
13
|
+
{
|
|
14
|
+
"id": "link1",
|
|
15
|
+
"textref": "#gloss",
|
|
16
|
+
"text": {
|
|
17
|
+
"plain": "see glossary entry"
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
]
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
"role": [
|
|
24
|
+
"paragraph"
|
|
25
|
+
],
|
|
26
|
+
"text": {
|
|
27
|
+
"plain": "synthesized speech can be created."
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
]
|
|
31
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
{
|
|
2
|
+
"id": "accessible-name-labelledby-hidden-attribute",
|
|
3
|
+
"description": "A link named via aria-labelledby pointing at an element hidden with the native hidden attribute: the hidden label still names the link, and is not emitted on its own",
|
|
4
|
+
"role": "accessible-name",
|
|
5
|
+
"rolesCovered": [
|
|
6
|
+
"paragraph"
|
|
7
|
+
],
|
|
8
|
+
"sourceRef": "https://www.w3.org/TR/accname/#computation-steps",
|
|
9
|
+
"inputKind": "fragment"
|
|
10
|
+
}
|
package/fixtures/manifest.json
CHANGED
|
@@ -19,6 +19,26 @@
|
|
|
19
19
|
"gnd": "gnd.json"
|
|
20
20
|
}
|
|
21
21
|
},
|
|
22
|
+
{
|
|
23
|
+
"id": "accessible-name-labelledby-aria-hidden",
|
|
24
|
+
"dir": "accessible-name-labelledby-aria-hidden",
|
|
25
|
+
"role": "accessible-name",
|
|
26
|
+
"description": "A link named via aria-labelledby pointing at an element marked aria-hidden=\"true\": the hidden label still names the link, and is not emitted on its own",
|
|
27
|
+
"files": {
|
|
28
|
+
"input": "input.html",
|
|
29
|
+
"gnd": "gnd.json"
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
"id": "accessible-name-labelledby-hidden-attribute",
|
|
34
|
+
"dir": "accessible-name-labelledby-hidden-attribute",
|
|
35
|
+
"role": "accessible-name",
|
|
36
|
+
"description": "A link named via aria-labelledby pointing at an element hidden with the native hidden attribute: the hidden label still names the link, and is not emitted on its own",
|
|
37
|
+
"files": {
|
|
38
|
+
"input": "input.html",
|
|
39
|
+
"gnd": "gnd.json"
|
|
40
|
+
}
|
|
41
|
+
},
|
|
22
42
|
{
|
|
23
43
|
"id": "acknowledgments-epub-type",
|
|
24
44
|
"dir": "acknowledgments-epub-type",
|
package/package.json
CHANGED
package/src/a11y.ts
CHANGED
|
@@ -69,8 +69,8 @@ export function extractNodeAria(el: Element): [string | null, boolean] {
|
|
|
69
69
|
|
|
70
70
|
if (labelNodes.length > 0) {
|
|
71
71
|
let text = "";
|
|
72
|
+
// Directly-referenced label nodes count even when hidden (AccName 2.A).
|
|
72
73
|
labelNodes.forEach((n, i) => {
|
|
73
|
-
if (nodeIsHidden(n)) return;
|
|
74
74
|
const label = n.getAttribute("aria-label");
|
|
75
75
|
text += label ? label : nodeTextExcludingExplicitRoles(n);
|
|
76
76
|
if (i < labelNodes.length - 1) text += " ";
|
package/src/converter.ts
CHANGED
|
@@ -18,6 +18,7 @@ import { ssmlAttrEscape, ssmlTextEscape, startsWithBindingPunct } from "@readium
|
|
|
18
18
|
import { type ObjBuilder, NavObject, isEmptyObj, finalizeToGuidedNavigationObject } from "./object.ts";
|
|
19
19
|
import { type GndMediaType, nodeLanguage, isInlineTag, sniffMediaType } from "./dom.ts";
|
|
20
20
|
import { encodeDomRangeFragment, encodeTextFragmentDirective } from "./textrefFragment.ts";
|
|
21
|
+
import { resolveRefs } from "./href.ts";
|
|
21
22
|
import { rootAnchorSelector, selectorForElement, textrefForSelector } from "./selectorGenerator.ts";
|
|
22
23
|
import { generateDomRange } from "./domRangeGenerator.ts";
|
|
23
24
|
import { textFragmentDirectiveFor } from "./textFragmentGenerator.ts";
|
|
@@ -70,6 +71,7 @@ export class Converter {
|
|
|
70
71
|
// See TextrefOptions.roles' leafTextRoleKeyword in options.ts.
|
|
71
72
|
leafTextEnabled = false;
|
|
72
73
|
docRoot: Document | null = null;
|
|
74
|
+
baseHref?: string;
|
|
73
75
|
// The live element selectors are climbed relative to — see
|
|
74
76
|
// selectorGenerator.ts's selectorForElement(). Only set when converting a
|
|
75
77
|
// live, already-rendered element (same caveat as domRangeEnabled).
|
|
@@ -161,7 +163,9 @@ export class Converter {
|
|
|
161
163
|
}
|
|
162
164
|
|
|
163
165
|
result(): GuidedNavigationObject[] {
|
|
164
|
-
|
|
166
|
+
const builders = this.resultBuilders();
|
|
167
|
+
if (this.baseHref) builders.forEach((b) => resolveRefs(b, this.baseHref!));
|
|
168
|
+
return builders.map(finalizeToGuidedNavigationObject);
|
|
165
169
|
}
|
|
166
170
|
|
|
167
171
|
// An explicit-role descendant is content in its own right and skips
|
|
@@ -697,6 +701,7 @@ export function parseMarkup(
|
|
|
697
701
|
converter.domRangeEnabled = domRange;
|
|
698
702
|
converter.textFragmentEnabled = textFragment;
|
|
699
703
|
converter.docRoot = input.ownerDocument;
|
|
704
|
+
converter.baseHref = options?.href;
|
|
700
705
|
converter.selectorRoot = input;
|
|
701
706
|
converter.selectorRootAnchor = rootAnchorSelector(input);
|
|
702
707
|
converter.convert(input);
|
|
@@ -720,6 +725,7 @@ export function parseMarkup(
|
|
|
720
725
|
converter.leafTextEnabled = leafText;
|
|
721
726
|
converter.textFragmentEnabled = textFragment;
|
|
722
727
|
converter.docRoot = doc;
|
|
728
|
+
converter.baseHref = options?.href;
|
|
723
729
|
const body = doc.querySelector("body");
|
|
724
730
|
if (body && !BODY_TAG_RE.test(input)) {
|
|
725
731
|
converter.convertChildren(body);
|
package/src/href.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { ObjBuilder } from "./object.ts";
|
|
2
|
+
|
|
3
|
+
const SCHEME_RE = /^[a-z][a-z\d+.-]*:/i;
|
|
4
|
+
// Placeholder origin so URL can resolve relative paths; stripped from the result.
|
|
5
|
+
const BASE = "https://gnd.invalid/";
|
|
6
|
+
|
|
7
|
+
// Resolves a ref found in the resource at `href` against it, keeping the result relative to the same base as `href`.
|
|
8
|
+
export function resolveRef(ref: string, href: string): string {
|
|
9
|
+
if (SCHEME_RE.test(ref)) return ref;
|
|
10
|
+
// The fragment is kept verbatim: URL parsing would re-encode textref fragments.
|
|
11
|
+
const hashIndex = ref.indexOf("#");
|
|
12
|
+
const path = hashIndex === -1 ? ref : ref.slice(0, hashIndex);
|
|
13
|
+
const fragment = hashIndex === -1 ? "" : ref.slice(hashIndex);
|
|
14
|
+
if (SCHEME_RE.test(href)) return new URL(path, href).href + fragment;
|
|
15
|
+
if (href.startsWith("//")) return new URL(path, "https:" + href).href.slice("https:".length) + fragment;
|
|
16
|
+
const resolved = new URL(path, BASE + href.replace(/^\/+/, "")).href;
|
|
17
|
+
return resolved.startsWith(BASE) ? resolved.slice(BASE.length) + fragment : ref;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function resolveRefs(o: ObjBuilder, href: string): void {
|
|
21
|
+
if (o.textref) o.textref = resolveRef(o.textref, href);
|
|
22
|
+
if (o.imgref) o.imgref = resolveRef(o.imgref, href);
|
|
23
|
+
if (o.audioref) o.audioref = resolveRef(o.audioref, href);
|
|
24
|
+
if (o.videoref) o.videoref = resolveRef(o.videoref, href);
|
|
25
|
+
o.children?.forEach((c) => resolveRefs(c, href));
|
|
26
|
+
}
|
package/src/options.ts
CHANGED
|
@@ -34,6 +34,9 @@ export interface GndGenerationOptions {
|
|
|
34
34
|
// Re-parse string input as text/html when XHTML parsing fails, instead of
|
|
35
35
|
// throwing.
|
|
36
36
|
htmlFallback?: boolean;
|
|
37
|
+
// The input's own href: every ref (textref, imgref, audioref, videoref) is
|
|
38
|
+
// resolved against it, e.g. "#p1" becomes "chapter.xhtml#p1".
|
|
39
|
+
href?: string;
|
|
37
40
|
}
|
|
38
41
|
|
|
39
42
|
function normalizeRoles(opt: boolean | GndRole[] | undefined): ((roles: GndRole[]) => boolean) | null {
|
package/src/textrefFragment.ts
CHANGED
|
@@ -108,6 +108,8 @@ export function decodeTextFragmentDirective(textref: string | undefined): TextFr
|
|
|
108
108
|
}
|
|
109
109
|
|
|
110
110
|
export interface DecodedTextref {
|
|
111
|
+
// The resource the reference points into, when the textref names one.
|
|
112
|
+
href?: string;
|
|
111
113
|
cssSelector?: string;
|
|
112
114
|
domRange?: DomRangeJSON;
|
|
113
115
|
text?: { highlight?: string; before?: string; after?: string };
|
|
@@ -120,9 +122,13 @@ export interface DecodedTextref {
|
|
|
120
122
|
// `domRange` to combine — a bare selector has no `textNodeIndex` to build one from.
|
|
121
123
|
export function combineDomRangeTextrefs(first: DecodedTextref, last: DecodedTextref): DecodedTextref | undefined {
|
|
122
124
|
if (!first.domRange || !last.domRange) return undefined;
|
|
125
|
+
// A DOM range can't span two documents.
|
|
126
|
+
if (first.href !== last.href) return undefined;
|
|
123
127
|
const domRange: DomRangeJSON = { start: first.domRange.start, end: last.domRange.end ?? last.domRange.start };
|
|
124
128
|
if (first.domRange.container !== undefined) domRange.container = first.domRange.container;
|
|
125
|
-
|
|
129
|
+
const combined: DecodedTextref = { domRange, cssSelector: domRange.container ?? domRange.start.cssSelector };
|
|
130
|
+
if (first.href !== undefined) combined.href = first.href;
|
|
131
|
+
return combined;
|
|
126
132
|
}
|
|
127
133
|
|
|
128
134
|
function decodeIdFragment(base: string): string | undefined {
|
|
@@ -134,33 +140,34 @@ function decodeIdFragment(base: string): string | undefined {
|
|
|
134
140
|
}
|
|
135
141
|
}
|
|
136
142
|
|
|
137
|
-
// Decodes a node's own
|
|
138
|
-
//
|
|
139
|
-
//
|
|
140
|
-
// "#css(...)"
|
|
141
|
-
// self-
|
|
142
|
-
//
|
|
143
|
-
//
|
|
144
|
-
// the above, or stand alone — so it's decoded separately from the rest of
|
|
145
|
-
// the string and merged into the result.
|
|
143
|
+
// Decodes a reference to a node's own content, distinguishing it from a
|
|
144
|
+
// navigational textref (link href, noteref target). A textref is
|
|
145
|
+
// "[href]#fragment", the href naming the resource when present (e.g.
|
|
146
|
+
// "chapter.xhtml#css(...)"). "#css(...)"/"#domrange(...)" fragments are
|
|
147
|
+
// always self-references; a bare "#id" only is when it matches the node's
|
|
148
|
+
// own id. A ":~:text=..." suffix can accompany any of the above, or stand
|
|
149
|
+
// alone, so it's decoded separately and merged into the result.
|
|
146
150
|
export function decodeTextref(node: { id?: string; textref?: string } | undefined): DecodedTextref | undefined {
|
|
147
151
|
const textref = node?.textref;
|
|
148
152
|
if (!textref) return undefined;
|
|
149
153
|
|
|
150
154
|
const markIndex = textref.indexOf(":~:");
|
|
151
155
|
const base = markIndex === -1 ? textref : textref.slice(0, markIndex);
|
|
156
|
+
const hashIndex = base.indexOf("#");
|
|
157
|
+
const href = hashIndex === -1 ? base : base.slice(0, hashIndex);
|
|
158
|
+
const fragment = hashIndex === -1 ? "" : base.slice(hashIndex);
|
|
152
159
|
|
|
153
160
|
let cssSelector: string | undefined;
|
|
154
161
|
let domRange: DomRangeJSON | undefined;
|
|
155
|
-
const
|
|
156
|
-
if (
|
|
157
|
-
domRange =
|
|
158
|
-
cssSelector =
|
|
162
|
+
const fragmentDomRange = decodeDomRangeFragment(fragment);
|
|
163
|
+
if (fragmentDomRange) {
|
|
164
|
+
domRange = fragmentDomRange;
|
|
165
|
+
cssSelector = fragmentDomRange.container ?? fragmentDomRange.start.cssSelector;
|
|
159
166
|
} else {
|
|
160
|
-
const decoded = decodeCssSelectorFragment(
|
|
167
|
+
const decoded = decodeCssSelectorFragment(fragment);
|
|
161
168
|
if (decoded !== undefined) {
|
|
162
169
|
cssSelector = decoded;
|
|
163
|
-
} else if (node
|
|
170
|
+
} else if (node.id && decodeIdFragment(fragment) === node.id) {
|
|
164
171
|
cssSelector = `#${CSS.escape(node.id)}`;
|
|
165
172
|
}
|
|
166
173
|
}
|
|
@@ -177,6 +184,7 @@ export function decodeTextref(node: { id?: string; textref?: string } | undefine
|
|
|
177
184
|
}
|
|
178
185
|
|
|
179
186
|
const result: DecodedTextref = {};
|
|
187
|
+
if (href !== "") result.href = href;
|
|
180
188
|
if (cssSelector !== undefined) result.cssSelector = cssSelector;
|
|
181
189
|
if (domRange !== undefined) result.domRange = domRange;
|
|
182
190
|
if (directive?.textEnd !== undefined) {
|
package/types/src/converter.d.ts
CHANGED
package/types/src/options.d.ts
CHANGED
|
@@ -8,6 +8,7 @@ export interface TextrefOptions {
|
|
|
8
8
|
export interface GndGenerationOptions {
|
|
9
9
|
textrefs?: boolean | GndRole[] | TextrefOptions;
|
|
10
10
|
htmlFallback?: boolean;
|
|
11
|
+
href?: string;
|
|
11
12
|
}
|
|
12
13
|
export interface NormalizedTextrefOptions {
|
|
13
14
|
predicate: ((roles: GndRole[]) => boolean) | null;
|
|
@@ -24,6 +24,7 @@ export interface TextFragmentDirective {
|
|
|
24
24
|
export declare function encodeTextFragmentDirective(fragment: TextFragmentDirective): string;
|
|
25
25
|
export declare function decodeTextFragmentDirective(textref: string | undefined): TextFragmentDirective | undefined;
|
|
26
26
|
export interface DecodedTextref {
|
|
27
|
+
href?: string;
|
|
27
28
|
cssSelector?: string;
|
|
28
29
|
domRange?: DomRangeJSON;
|
|
29
30
|
text?: {
|