microdata-tooling
Version:
Provides tooling to help using micro data from TypeScript/JavaScript.
3 lines (2 loc) • 1.81 kB
JavaScript
import{isElement,pushMany}from"https://unpkg.com/microdata-tooling@1.0.4/dist/utils.min.js";import{compareOrder}from"https://unpkg.com/microdata-tooling@1.0.4/dist/sort-nodes.min.js";export function jsonify(t){const e={items:[]};for(const i of t)i.hasAttribute("itemprop")||e.items.push(getTheObject(i));return e}function getTheObject(t,e=[]){const i={properties:{}};e.push(t),t.hasAttribute("itemtype")&&(i.type=t.getAttribute("itemtype").split(" ")),t.hasAttribute("itemid")&&(i.id=t.getAttribute("itemid"));for(const r of thePropertiesOfAnItem(t)){const t=r.getAttribute("itemprop");if(null===t)throw new Error;let o=getElementValue(r);"string"!=typeof o&&(o=-1!==e.indexOf(o)?"ERROR":getTheObject(o,e)),t in i.properties||(i.properties[t]=[]),i.properties[t].push(o)}return i}function thePropertiesOfAnItem(t){const e=[],i=[],r=[];if(i.push(t),pushMany(r,Array.from(t.children)),t.hasAttribute("itemref"))for(const e of t.getAttribute("itemref").split(" ")){const i=t.querySelector("#"+e);i&&r.push(i)}for(;r.length>0;){const t=r.pop();if(-1===i.indexOf(t)){if(i.push(t),t.hasAttribute("itemscope")||r.push.apply(r,Array.from(t.children)),t.hasAttribute("itemprop")){const i=t.getAttribute("itemprop");null!==i&&i.length>0&&e.push(t)}}else console.log("Microdata Error",t)}return e.sort(compareOrder),e}function getElementValue(t){return t.hasAttribute("itemscope")?t:isElement(t,"meta")?t.content:isElement(t,"img")||isElement(t,"audio")||isElement(t,"embed")||isElement(t,"iframe")||isElement(t,"source")||isElement(t,"track")||isElement(t,"video")?t.src:isElement(t,"a")||isElement(t,"area")||isElement(t,"link")?t.href:isElement(t,"object")?t.data:isElement(t,"data")?t.value:isElement(t,"meter")?t.value.toString():isElement(t,"time")?t.dateTime:t.textContent||""}
//# sourceMappingURL=jsonify.min.js.map