UNPKG

@vivliostyle/vfm

Version:

Custom Markdown syntax specialized in book authoring.

50 lines (49 loc) 2.32 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.hast = void 0; var hast_util_is_element_1 = __importDefault(require("hast-util-is-element")); var hastscript_1 = __importDefault(require("hastscript")); var unist_util_visit_1 = __importDefault(require("unist-util-visit")); /** * Wrap the single line `<img>` in `<figure>` and generate `<figcaption>` from the `alt` attribute. * * A single line `<img>` is a child of `<p>` with no sibling elements. Also, `<figure>` cannot be a child of `<p>`. So convert the parent `<p>` to `<figure>`. * @param img `<img>` tag. * @param parent `<p>` tag. */ var wrapFigureImg = function (img, parent) { if (!(img.properties && parent.properties)) { return; } parent.tagName = 'figure'; parent.children.push((0, hastscript_1.default)('figcaption', { 'aria-hidden': 'true' }, [img.properties.alt])); }; var hast = function () { return function (tree) { (0, unist_util_visit_1.default)(tree, 'element', function (node, index, parent) { var _a, _b; // handle captioned code block var maybeCode = (_a = node.children) === null || _a === void 0 ? void 0 : _a[0]; if ((0, hast_util_is_element_1.default)(node, 'pre') && (maybeCode === null || maybeCode === void 0 ? void 0 : maybeCode.properties) && maybeCode.properties.title) { var maybeTitle = maybeCode.properties.title; delete maybeCode.properties.title; if (Array.isArray(maybeCode.properties.className)) { parent.children[index] = (0, hastscript_1.default)('figure', { class: maybeCode.properties.className[0] }, (0, hastscript_1.default)('figcaption', maybeTitle), node); } return; } // handle captioned and single line (like a block) img if ((0, hast_util_is_element_1.default)(node, 'img') && ((_b = node.properties) === null || _b === void 0 ? void 0 : _b.alt) && parent && parent.tagName === 'p' && parent.children.length === 1) { wrapFigureImg(node, parent); } }); }; }; exports.hast = hast;