UNPKG

markdown-it-image-figures

Version:

Render images occurring by itself in a paragraph as a figure with support for figcaptions.

2 lines (1 loc) 2.31 kB
const t=new Set([!0,!1,"alt","title"]);function e(t,e){return(Array.isArray(t)?t:[]).filter(([t])=>t!==e)}function n(t,n){t&&t.attrs&&(t.attrs=e(t.attrs,n))}function i(e,i){if(!t.has(e))throw new TypeError(`figcaption must be one of: ${[...t]}.`);if("alt"===e)return i.content;const r=i.attrs.find(([t])=>"title"===t);return Array.isArray(r)&&r[1]?(n(i,"title"),r[1]):void 0}function r(t,r){r=r||{},t.core.ruler.before("linkify","image_figures",function(s){let a=1;for(let o=1,c=s.tokens.length;o<c-1;++o){const l=s.tokens[o];if("inline"!==l.type)continue;if(!l.children||1!==l.children.length&&3!==l.children.length)continue;if(1===l.children.length&&"image"!==l.children[0].type)continue;if(3===l.children.length){const[t,e,n]=l.children;if("link_open"!==t.type||"image"!==e.type||"link_close"!==n.type)continue}if(0!==o&&"paragraph_open"!==s.tokens[o-1].type)continue;if(o!==c-1&&"paragraph_close"!==s.tokens[o+1].type)continue;const f=s.tokens[o-1];let h;if(f.type="figure_open",f.tag="figure",s.tokens[o+1].type="figure_close",s.tokens[o+1].tag="figure",r.dataType&&s.tokens[o-1].attrPush(["data-type","image"]),r.link&&1===l.children.length){[h]=l.children;const t=new s.Token("link_open","a",1);t.attrPush(["href",h.attrGet("src")]),l.children.unshift(t),l.children.push(new s.Token("link_close","a",-1))}if(h=1===l.children.length?l.children[0]:l.children[1],r.figcaption){const n=i(r.figcaption,h);if(n){const[i]=t.parseInline(n,s.env);l.children.push(new s.Token("figcaption_open","figcaption",1)),l.children.push(...i.children),l.children.push(new s.Token("figcaption_close","figcaption",-1)),h.attrs&&(h.attrs=e(h.attrs,"title"))}}if(r.copyAttrs&&h.attrs){const t=!0===r.copyAttrs?"":r.copyAttrs;f.attrs=h.attrs.filter(([e])=>e.match(t)).map(t=>Array.from(t))}if(r.tabindex&&(s.tokens[o-1].attrPush(["tabindex",a]),a++),r.lazy&&(h.attrs.some(([t])=>"loading"===t)||h.attrs.push(["loading","lazy"])),r.async&&(h.attrs.some(([t])=>"decoding"===t)||h.attrs.push(["decoding","async"])),r.classes&&"string"==typeof r.classes){let t=!1;for(let e=0,n=h.attrs.length;e<n&&!t;e++){const n=h.attrs[e];"class"===n[0]&&(n[1]=`${n[1]} ${r.classes}`,t=!0)}t||h.attrs.push(["class",r.classes])}if(r.removeSrc){const t=h.attrs.find(([t])=>"src"===t);h.attrs.push(["data-src",t[1]]),n(h,"src")}}})}export{r as default};