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

Adding support for custom HTML markup #4

Merged
merged 2 commits into from
Feb 8, 2023
Merged
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
3 changes: 2 additions & 1 deletion index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export { remarkEleventyImage } from "./src/astro-remark-images";
export { remarkEleventyImage } from "./src/astro-remark-images";
export type { createHTMLProps, MarkupValues } from "./src/types";
4 changes: 2 additions & 2 deletions package-lock.json

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

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "astro-remark-eleventy-image",
"version": "1.1.2",
"version": "1.2.0",
"description": "Remark plugin for Astro that automatically optimizes images referenced in markdown files.",
"author": "ChrisOh431",
"license": "MIT",
Expand Down
78 changes: 22 additions & 56 deletions src/astro-remark-images.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import Image from "@11ty/eleventy-img";

// @ts-ignore
import config from "./astro.config.mjs";
import { createHTML } from "./markupUtil.js";
import { MarkupValues } from "./types.js";

/*
ONlY do this work in prod; don't want to mess up the dev build in any way
Expand All @@ -14,15 +16,22 @@ import config from "./astro.config.mjs";
4. Automagically optimized images!
*/

type RemarkImagesConfig = {
sizes?: string,
remoteImages?: boolean,
eleventyImageConfig?: Image.ImageOptions,
customMarkup?: ((attributes: MarkupValues) => string),
};
function remarkEleventyImage()
{
const publicDir = config.publicDir || "./public/";
const outDir = config.outDir || "./dist/";

const ricfg = (config?.markdown?.remarkImages) ? config.markdown.remarkImages : null;
const ricfg: RemarkImagesConfig = (config?.markdown?.remarkImages) ? config.markdown.remarkImages : null;
const ricfgContainerSizes = (ricfg?.sizes) ? ricfg.sizes : "(max-width: 700px) 100vw, 700px";
const ricfgRemoteEnabled = (ricfg?.remoteImages) ? ricfg.remoteImages : false;
const ricfgEleventyImageConfig: Image.ImageOptions = (ricfg?.eleventyImageConfig) ? ricfg.eleventyImageConfig : null;
const ricfgCustomMarkup = (ricfg?.customMarkup) ? ricfg.customMarkup : null;
const ricfgEleventyImageConfig = (ricfg?.eleventyImageConfig) ? ricfg.eleventyImageConfig : null;

// setup eleventy image config obj, overwrite with settings from astro.config.mjs
const baseEleventyConfig: Image.ImageOptions = Object.assign({
Expand Down Expand Up @@ -97,6 +106,7 @@ function remarkEleventyImage()
try
{
console.log(`(astro-remark-images) Optimizing image: ${path.basename(node.url)} referenced in file: ${path.basename(file.path)}`);

if (Image.Util.isRemoteUrl(node.url))
{
// Remote image. In this case the optimized images are put
Expand Down Expand Up @@ -131,14 +141,15 @@ function remarkEleventyImage()
currentConfig.outputDir = outputImageDir;

const stats: Image.Metadata = await Image(originalImagePath, Object.assign(currentConfig, baseEleventyConfig));
const responsiveHTML = createPicture(
{
imageDir: outputImageDirHTML,
metadata: stats,
alt: node.alt,
sizes: ricfgContainerSizes
}
);
const responsiveHTML = createHTML({
imageDir: outputImageDirHTML,
metadata: stats,
alt: node.alt,
sizes: ricfgContainerSizes,
isRemote: Image.Util.isRemoteUrl(node.url),
mdFilePath: file.path,
customMarkup: ricfgCustomMarkup,
});

if (responsiveHTML)
{
Expand All @@ -157,49 +168,4 @@ function remarkEleventyImage()
}
};

export { remarkEleventyImage };

interface createPictureProps
{
imageDir: string,
metadata: Image.Metadata,
alt: string,
sizes: string,
}
function createPicture({ imageDir, metadata, alt, sizes }: createPictureProps)
{
let baseSource: Image.MetadataEntry[];
let highsrc: Image.MetadataEntry;

if (metadata.jpeg && metadata.jpeg.length > 0)
{
baseSource = metadata.jpeg;
highsrc = metadata.jpeg[metadata.jpeg.length - 1];
}
else
{
baseSource = Object.values(metadata)[0] as Image.MetadataEntry[];
highsrc = baseSource[baseSource.length - 1];
}

function correctSrcset(entry: Image.MetadataEntry)
{
const filename = path.join(imageDir, path.basename(entry.url)) + ` ${entry.width}w`;
return filename;
}

return `
<picture>
${Object.values(metadata).map(imageFormat =>
{
return ` <source type="${imageFormat[0].sourceType}" srcset="${imageFormat.map(entry => correctSrcset(entry)).join(", ")}" sizes="${sizes}">\n`;
}).join("\n")}
<img
src="${path.join(imageDir, path.basename(highsrc.url))}"
width="${highsrc.width}"
height="${highsrc.height}"
alt="${alt}"
loading="lazy"
decoding="async">
</picture>`;
}
export { remarkEleventyImage };
71 changes: 71 additions & 0 deletions src/markupUtil.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { MarkupValues } from "./types";
import path from "path";
import Image from "@11ty/eleventy-img";

export function defaultMarkup({ src, sources, width, height, alt }: MarkupValues)
{
return `
<picture>
${sources}
<img
src="${src}"
width="${width}"
height="${height}"
alt="${alt}"
loading="lazy"
decoding="async">
</picture>`;
}

interface CreateHTMLProps
{
imageDir: string,
metadata: Image.Metadata,
alt: string,
sizes: string,
isRemote: boolean,
mdFilePath: string,
customMarkup: ((attributes: MarkupValues) => string) | null,
}
export function createHTML({ imageDir, metadata, alt, sizes, isRemote, mdFilePath, customMarkup }: CreateHTMLProps)
{
let baseSource: Image.MetadataEntry[];
let highsrc: Image.MetadataEntry;

// picking the src for the base <img> tag
if (metadata.jpeg && metadata.jpeg.length > 0)
{
baseSource = metadata.jpeg;
highsrc = metadata.jpeg[metadata.jpeg.length - 1];
}
else
{
// when the image is remote, there's no jpeg, so just use the first format there is
baseSource = Object.values(metadata)[0] as Image.MetadataEntry[];
highsrc = baseSource[baseSource.length - 1];
}

function generateSrcsets(metadata: Image.Metadata)
{
function correctSrcset(entry: Image.MetadataEntry)
{
const filename = path.join(imageDir, path.basename(entry.url)) + ` ${entry.width}w`;
return filename;
}

return Object.values(metadata).map(imageFormat =>
{
return ` <source type="${imageFormat[0].sourceType}" srcset="${imageFormat.map(entry => correctSrcset(entry)).join(", ")}" sizes="${sizes}">\n`;
}).join("\n");
}

if (customMarkup)
{
return customMarkup({ src: path.join(imageDir, path.basename(highsrc.url)), width: highsrc.width, height: highsrc.height, alt: alt, format: baseSource[0].format, sources: generateSrcsets(metadata), isRemote: isRemote, mdFilePath: mdFilePath });
}
else
{
return defaultMarkup({ src: path.join(imageDir, path.basename(highsrc.url)), width: highsrc.width, height: highsrc.height, alt: alt, format: baseSource[0].format, sources: generateSrcsets(metadata), isRemote: isRemote, mdFilePath: mdFilePath });
}
}

24 changes: 24 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import type Image from "@11ty/eleventy-img";

type MarkupValues = {
src: string,
width: number,
height: number,
alt: string,
format: string,
sources: string,
isRemote: boolean,
mdFilePath: string,
};

interface createHTMLProps
{
imageDir: string,
metadata: Image.Metadata,
alt: string,
sizes: string,
isRemote: boolean,
mdFilePath: string;
}

export type { MarkupValues, createHTMLProps };