Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

MDX remark image props #9753

Merged
merged 8 commits into from
Jan 23, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
5 changes: 5 additions & 0 deletions .changeset/quick-cars-kneel.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@astrojs/mdx": minor
---

Allows remark plugins to pass options specifying how images in .mdx files will be optimized
2 changes: 1 addition & 1 deletion packages/integrations/mdx/src/plugins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ function getRemarkPlugins(mdxOptions: MdxOptions): PluggableList {
}
}

remarkPlugins = [...remarkPlugins, ...mdxOptions.remarkPlugins];
remarkPlugins = [...mdxOptions.remarkPlugins, ...remarkPlugins];
Princesseuh marked this conversation as resolved.
Show resolved Hide resolved

if (!isPerformanceBenchmark) {
// Apply syntax highlighters after user plugins to match `markdown/remark` behavior
Expand Down
57 changes: 56 additions & 1 deletion packages/integrations/mdx/src/remark-images-to-component.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
import type { MarkdownVFile } from '@astrojs/markdown-remark';
import type { Image, Parent } from 'mdast';
import type { MdxJsxFlowElement, MdxjsEsm } from 'mdast-util-mdx';
import type { MdxJsxFlowElement, MdxjsEsm, MdxJsxAttribute } from 'mdast-util-mdx';
import { visit } from 'unist-util-visit';
import { jsToTreeNode } from './utils.js';

export const ASTRO_IMAGE_ELEMENT = 'astro-image';
export const ASTRO_IMAGE_IMPORT = '__AstroImage__';
export const USES_ASTRO_IMAGE_FLAG = '__usesAstroImage';

type imgArgs = {
[key in 'widths' | 'densities']: string[] | undefined;
} & {
[key: string]: string;
};

export function remarkImageToComponent() {
return function (tree: any, file: MarkdownVFile) {
if (!file.data.imagePaths) return;
Expand Down Expand Up @@ -89,6 +95,55 @@ export function remarkImageToComponent() {
});
}

if (node.data && node.data.hProperties) {
const { widths, densities, ...prop } = node.data.hProperties as imgArgs;
OliverSpeir marked this conversation as resolved.
Show resolved Hide resolved
const createArrayAttribute = (name: string, values: string[]): MdxJsxAttribute => {
return {
type: 'mdxJsxAttribute',
name: name,
value: {
type: 'mdxJsxAttributeValueExpression',
value: name,
data: {
estree: {
type: 'Program',
body: [
{
type: 'ExpressionStatement',
expression: {
type: 'ArrayExpression',
elements: values.map((value) => ({
type: 'Literal',
value: value,
raw: String(value),
})),
},
},
],
sourceType: 'module',
comments: [],
},
},
},
};
};
if (densities) {
componentElement.attributes.push(createArrayAttribute('densities', densities));
}
if (widths) {
componentElement.attributes.push(createArrayAttribute('widths', widths));
}
if (prop && Object.keys(prop).length > 0) {
Object.entries(prop).forEach(([key, value]) => {
componentElement.attributes.push({
name: key,
type: 'mdxJsxAttribute',
value: String(value),
});
});
}
}

parent!.children.splice(index!, 1, componentElement);
}
});
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { defineConfig } from 'astro/config';
import mdx from '@astrojs/mdx';
import plugin from "./remarkPlugin"

// https://astro.build/config
export default defineConfig({
integrations: [mdx({remarkPlugins:[plugin]})],
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"name": "@test/image-remark-imgattr",
"version": "0.0.0",
"private": true,
"dependencies": {
"@astrojs/mdx": "workspace:*",
"astro": "workspace:*"
},
"scripts": {
"dev": "astro dev"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
export default function plugin() {
return transformer;

function transformer(tree) {
function traverse(node) {
if (node.type === "image") {
node.data = node.data || {};
node.data.hProperties = node.data.hProperties || {};
node.data.hProperties.loading = "eager";
node.data.hProperties.width = "50";
}

if (node.children) {
node.children.forEach(traverse);
}
}

traverse(tree);
}
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
![alt](../assets/penguin2.jpg)
64 changes: 64 additions & 0 deletions packages/integrations/mdx/test/remark-imgattr.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { expect } from 'chai';
import * as cheerio from 'cheerio';
import { Writable } from 'node:stream';

import { Logger } from '../../../astro/dist/core/logger/core.js';
import { loadFixture } from '../../../astro/test/test-utils.js';

const FIXTURE_ROOT = new URL('./fixtures/image-remark-imgattr/', import.meta.url);

describe('remarktesting', () => {
/** @type {import('./test-utils').Fixture} */
let fixture;

describe('dev', () => {
/** @type {import('./test-utils').DevServer} */
let devServer;
/** @type {Array<{ type: any, level: 'error', message: string; }>} */
let logs = [];

before(async () => {
fixture = await loadFixture({
root: FIXTURE_ROOT,
});

devServer = await fixture.startDevServer({
logger: new Logger({
level: 'error',
dest: new Writable({
objectMode: true,
write(event, _, callback) {
logs.push(event);
callback();
},
}),
}),
});
OliverSpeir marked this conversation as resolved.
Show resolved Hide resolved
});

after(async () => {
await devServer.stop();
});

describe('Test image attributes can be added by remark plugins', () => {
let $;
before(async () => {
let res = await fixture.fetch('/');
let html = await res.text();
$ = cheerio.load(html);
});

it('Image has eager loading meaning getImage passed props it doesnt use through it', async () => {
let $img = $('img');
expect($img.attr('loading')).to.equal('eager');
});

it('Image src contains w=50 meaning getImage correctly used props added through the remark plugin', async () => {
let $img = $('img');
expect(new URL($img.attr('src'), 'http://example.com').searchParams.get('w')).to.equal(
'50'
);
});
});
});
});
9 changes: 9 additions & 0 deletions pnpm-lock.yaml

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