UNPKG

gatsby-remark-image-attributes

Version:

Creates HTML image markup with style and data-* attributes from [`mdAST Image`](https://github.com/syntax-tree/mdast#image) nodes with attributes in their title.

60 lines (59 loc) 2.41 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const image_attributes_1 = __importDefault(require("../image-attributes")); class AttributeImage { constructor(node) { this.node = node; this.attributes = new image_attributes_1.default(node); } get width() { const defaultWidth = ['', '100%']; const value = this.node.value; return (value.match(/width: (\d*(px|%|vw))/) || defaultWidth)[1]; } get data() { return Object.keys(this.attributes.dataAttributes).reduce((value, key) => key !== 'title' ? `${value} data-${key}="${this.attributes.dataAttributes[key]}"` : value, ''); } get style() { let styleString = Object.keys(this.attributes.styleAttributes).reduce((style, key) => `${style}${key}: ${this.attributes.styleAttributes[key]};`, ''); if (this.attributes.inline && !this.attributes.styleAttributes.width && !this.attributes.styleAttributes.height) { styleString += `width: ${this.width};`; } return styleString; } get mdastNode() { this.node.type = 'html'; this.node.value = this.html; return this.node; } get html() { this.sanitizeTitle(); return `<img src="${this.node.url}" class="gatsby-img-attributes" style="${this.style || 'width: 100%;'}" alt="${this.node.alt}" title="${this.node.title || ''}"${this.data}/>`; } applyDataAttributes() { this.node.value = this.node.value.replace(/<img[^>]*/, `$& ${this.data}`); return this; } sanitizeTitle() { this.node.title = this.attributes.dataAttributes.title || this.node.title; if (this.attributes.length && this.node.title.startsWith('#')) { this.node.title = null; } if (this.node.value && this.attributes.originalTitle) { const rx = new RegExp(`#?${this.attributes.originalTitle.replace(/[\/\\^$*+?.()|[\]{}]/g, '\\$&')}`, 'g'); this.node.value = this.node.value.replace(rx, this.node.title || ''); } return this; } static hasAttributes(title) { return /^#(.*?)=(.*?);?/.test(title); } } exports.default = AttributeImage;