Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 15 additions & 13 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
"@diplodoc/cut-extension": "^0.7.2",
"@diplodoc/file-extension": "^0.2.1",
"@diplodoc/tabs-extension": "^3.7.2",
"@diplodoc/utils": "^2.1.0",
"chalk": "^4.1.2",
"cheerio": "^1.0.0",
"css": "^3.0.0",
Expand Down
87 changes: 87 additions & 0 deletions src/transform/plugins/image-attrs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
/* eslint-disable valid-jsdoc */
import MarkdownIt from 'markdown-it';
import {parseMdAttrs} from '@diplodoc/utils';

import {applyInlineStyling} from './imsize/inline-styles';

export type ImageAttributesPluginOptions = {
enableInlineStyling?: boolean;
/**
* Additional allowed attributes
*
* Attributes `width` and `height` always allowed
*/
allowedAttributes?: string[];
};

const defaultAllowedAttrs = ['width', 'height'] as const;

/**
* Plugin for parsing image node attributes.
*
* Example of markup:
*
* ```md
* ![alt](_images/image.png "title"){width=100 height=100}
* ```
*/
export const imageAttrsPlugin: MarkdownIt.PluginWithOptions<ImageAttributesPluginOptions> = (
md,
opts = {},
) => {
const allowedAttrs = new Set<string>(defaultAllowedAttrs);
if (Array.isArray(opts.allowedAttributes)) {
for (const val of opts.allowedAttributes) {
allowedAttrs.add(val);
}
}

md.core.ruler.push('image-attributes', (state) => {
for (const token of state.tokens) {
if (token.type !== 'inline') {
continue;
}

const children = token.children || [];
for (let i = 0; i < children.length; i++) {
const imgToken = children[i];
if (imgToken.type !== 'image') {
continue;
}

const nextTextToken = children[i + 1];
if (nextTextToken?.type !== 'text') {
continue;
}

const res = parseMdAttrs(
md,
nextTextToken.content,
0,
nextTextToken.content.length,
);
if (!res) {
continue;
}

nextTextToken.content = nextTextToken.content.slice(res.pos);

for (const key of allowedAttrs) {
if (res.attrs[key]) {
if (key === 'class') {
const values = res.attrs[key];
values.forEach((val) => imgToken.attrJoin(key, val));
} else {
const value = res.attrs[key][0];
imgToken.attrSet(key, value);
}
}
}

if (opts.enableInlineStyling) {
applyInlineStyling(imgToken, state.env);
}
}
}
});
};
34 changes: 34 additions & 0 deletions src/transform/plugins/imsize/inline-styles.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import type {Token} from 'markdown-it';

import {ImsizeAttr} from './const';

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function applyInlineStyling(token: Token, env: any) {
let style: string | undefined = '';

const width = token.attrGet(ImsizeAttr.Width) || '';
const height = token.attrGet(ImsizeAttr.Height) || '';

const widthWithPercent = width.includes('%');
const heightWithPercent = height.includes('%');

if (width !== '') {
const widthString = widthWithPercent ? width : `${width}px`;
style += `width: ${widthString};`;
}

if (height !== '') {
if (width !== '' && !heightWithPercent && !widthWithPercent) {
style += `aspect-ratio: ${width} / ${height};height: auto;`;
env.additionalOptionsCssWhiteList ??= {};
env.additionalOptionsCssWhiteList['aspect-ratio'] = true;
} else {
const heightString = heightWithPercent ? height : `${height}px`;
style += `height: ${heightString};`;
}
}

if (style) {
token.attrPush([ImsizeAttr.Style, style]);
}
}
26 changes: 2 additions & 24 deletions src/transform/plugins/imsize/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type Token from 'markdown-it/lib/token';

import {ImsizeAttr} from './const';
import {parseImageSize} from './helpers';
import {applyInlineStyling} from './inline-styles';

export type ImsizeOptions = {
enableInlineStyling?: boolean;
Expand Down Expand Up @@ -212,30 +213,7 @@ export const imageWithSize = (md: MarkdownIt, opts?: ImsizeOptions): ParserInlin
}

if (opts?.enableInlineStyling) {
let style: string | undefined = '';

const widthWithPercent = width.includes('%');
const heightWithPercent = height.includes('%');

if (width !== '') {
const widthString = widthWithPercent ? width : `${width}px`;
style += `width: ${widthString};`;
}

if (height !== '') {
if (width !== '' && !heightWithPercent && !widthWithPercent) {
style += `aspect-ratio: ${width} / ${height};height: auto;`;
state.env.additionalOptionsCssWhiteList ??= {};
state.env.additionalOptionsCssWhiteList['aspect-ratio'] = true;
} else {
const heightString = heightWithPercent ? height : `${height}px`;
style += `height: ${heightString};`;
}
}

if (style) {
token.attrs.push([ImsizeAttr.Style, style]);
}
applyInlineStyling(token, state.env);
}
}

Expand Down
56 changes: 56 additions & 0 deletions test/data/image-attrs/fixtures.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
Coverage. Image with attributes
.
![test]( x ){width=100 height=200}
.
<p><img src="x" alt="test" width="100" height="200" style="width: 100px;aspect-ratio: 100 / 200;height: auto;"></p>
.
.
![test]( x ){width=100}
.
<p><img src="x" alt="test" width="100" style="width: 100px;"></p>
.
.
![test]( x ){height=200}
.
<p><img src="x" alt="test" height="200" style="height: 200px;"></p>
.
.
![test]( x "title"){width=100 height=200}
.
<p><img src="x" alt="test" title="title" width="100" height="200" style="width: 100px;aspect-ratio: 100 / 200;height: auto;"></p>
.
.
![test](http://this.is.test.jpg){width=100 height=200}
.
<p><img src="http://this.is.test.jpg" alt="test" width="100" height="200" style="width: 100px;aspect-ratio: 100 / 200;height: auto;"></p>
.
.
![test](<x>){width=100 height=200}
.
<p><img src="x" alt="test" width="100" height="200" style="width: 100px;aspect-ratio: 100 / 200;height: auto;"></p>
.
.
![test](test){width="100%"}
.
<p><img src="test" alt="test" width="100%" style="width: 100%;"></p>
.
.
![test](test){height="100%"}
.
<p><img src="test" alt="test" height="100%" style="height: 100%;"></p>
.
.
![test](test){width="100%" height="100%"}
.
<p><img src="test" alt="test" width="100%" height="100%" style="width: 100%;height: 100%;"></p>
.
.
![test](test){width="100%" height=200}
.
<p><img src="test" alt="test" width="100%" height="200" style="width: 100%;height: 200px;"></p>
.
.
![test](test){width=100 height="100%"}
.
<p><img src="test" alt="test" width="100" height="100%" style="width: 100px;height: 100%;"></p>
.
16 changes: 16 additions & 0 deletions test/image-attrs.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import {join} from 'node:path';
import MarkdownIt from 'markdown-it';

import {ImageAttributesPluginOptions, imageAttrsPlugin} from '../src/transform/plugins/image-attrs';

const generate = require('markdown-it-testgen');

describe('image with attributes (inlineStyling is enabled)', () => {
const md = new MarkdownIt({
html: true,
linkify: false,
typographer: false,
}).use<ImageAttributesPluginOptions>(imageAttrsPlugin, {enableInlineStyling: true});

generate(join(__dirname, 'data/image-attrs/fixtures.txt'), md);
});
Loading