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

fix: get image path from HTML <img src=""> tag #493

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
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
2 changes: 1 addition & 1 deletion bin/help.txt
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ Options:
--highlight-theme <theme> Highlight theme [default: zenburn]
--css <files> CSS files to inject into the page
--scripts <files> Scripts to inject into the page
--assets-dir <dirname> Defines assets directory name [default: _assets]
--assets-dir <dirname> Defines assets directory name [default: assets]
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why this change? Might be a breaking change to some and it's a bit much for one PR.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

GitHub seems to change the folder name if there is a dash at the start of the name. See Linking to a page with a dash (hyphen) in the title In GitHub wiki

--view scroll Use reveal.js scroll view feature [default: undefined]
--preprocessor <script> Markdown preprocessor script
--template <filename> Template file for reveal.js
Expand Down
5 changes: 2 additions & 3 deletions lib/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,9 @@ import { readFile } from 'node:fs/promises';
import * as fs from 'fs-extra';
import parseArgs from 'yargs-parser';
import path from 'node:path';
import url from 'node:url';
import url, { pathToFileURL } from 'node:url';
import { globSync } from 'glob';
import { isDirectory, isFile, isAbsoluteURL, tryReadJson5Configs, loadJSON } from './util.js';

const require = createRequire(import.meta.url);

const __dirname = path.dirname(url.fileURLToPath(import.meta.url));
Expand Down Expand Up @@ -112,7 +111,7 @@ export const getFaviconPath = async () => {

export const getPreprocessor = async preprocessor => {
if (preprocessor) {
const { default: defaultFunc } = await import(preprocessor);
const { default: defaultFunc } = await import(pathToFileURL(preprocessor));
return defaultFunc;
}

Expand Down
2 changes: 1 addition & 1 deletion lib/defaults.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"assetsDir": "_assets",
"assetsDir": "assets",
"css": [],
"highlightTheme": "base16/zenburn",
"host": "localhost",
Expand Down
5 changes: 3 additions & 2 deletions lib/featured-slide.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const getSlideAnchor = featuredSlide => {
export default async (initialUrl, targetDir) => {
const { featuredSlide } = getOptions();

if (!featuredSlide || !puppeteer) {
if ((!featuredSlide && featuredSlide !== 0) || !puppeteer) {
return;
}

Expand All @@ -34,7 +34,8 @@ export default async (initialUrl, targetDir) => {
const snapshotFilename = `${targetDir}/featured-slide.jpg`;

const url = `http://${host}:${port}/${initialUrl}${getSlideAnchor(featuredSlide.toString())}`;


console.log("🚀 ~ url:", url)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess this isn't supposed to be part of this PR

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yes, I should clean this before pushing

debug({ url, snapshotFilename, puppeteerLaunchConfig });

try {
Expand Down
3 changes: 2 additions & 1 deletion lib/listing.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ const getFileMeta = async filePath => {
// Exports ---------------------------------------------------------------------

export const renderListFile = async filePaths => {
const { title, listingTemplate, theme, assetsDir } = getOptions();
const { title, description, listingTemplate, theme, assetsDir } = getOptions();
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Where's description coming from? Not sure what it has to do with intention of PR?

const template = await getListingTemplate(listingTemplate);
const themeUrl = getThemeUrl(theme, assetsDir, '.');
let files = await Promise.all(filePaths.map(getFileMeta));
Expand All @@ -36,6 +36,7 @@ export const renderListFile = async filePaths => {
base: '',
themeUrl,
pageTitle: title,
description,
files,
date: new Date().toISOString()
});
Expand Down
11 changes: 7 additions & 4 deletions lib/render.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ function sanitize(entry) {
* @param {Object} extraOptions - Additional options (mostly used by tests)
* @returns {string} The rendered HTML compatible with reveal.js
*/
export const render = async (fullMarkdown, extraOptions = {}) => {
export const render = async (fullMarkdown, extraOptions = {}, filePath = undefined) => {
const { yamlOptions, markdown: contentOnlyMarkdown } = parseYamlFrontMatter(fullMarkdown);
const options = Object.assign(getSlideOptions(yamlOptions), extraOptions);

Expand All @@ -46,7 +46,8 @@ export const render = async (fullMarkdown, extraOptions = {}) => {
const highlightThemeUrl = getHighlightThemeUrl(options.highlightTheme);
const scriptPaths = getScriptPaths(options.scripts, options.assetsDir, options.base);
const cssPaths = getCssPaths(options.css, options.assetsDir, options.base);

const ogImage = filePath ? path.dirname(filePath) + '/featured-slide.jpg' : 'featured-slide.jpg'
const ogUrl = filePath.replace('.md', '.html')
const revealOptions = Object.assign({}, getRevealOptions(options.revealOptions), yamlOptions.revealOptions);

const slidifyOptions = _.pick(options, Object.keys(slidifyAttributeNames));
Expand All @@ -55,7 +56,6 @@ export const render = async (fullMarkdown, extraOptions = {}) => {
const escaped_value = value.replace(/\n/g, '\\n').replace(/\r/g, '\\r');
slidifyAttributes.push(`${slidifyAttributeNames[key]}="${escaped_value}"`);
}

const preprocessorFn = await getPreprocessor(options.preprocessor);
const processedMarkdown = await preprocessorFn(contentOnlyMarkdown, options);

Expand All @@ -67,6 +67,9 @@ export const render = async (fullMarkdown, extraOptions = {}) => {
title,
slidifyAttributes: slidifyAttributes.join(' '),
markdown: processedMarkdown,
description: options.description,
ogImage,
ogUrl,
themeUrl,
highlightThemeUrl,
scriptPaths,
Expand All @@ -83,7 +86,7 @@ export const render = async (fullMarkdown, extraOptions = {}) => {
export const renderFile = async (filePath, extraOptions) => {
try {
const content = await readFile(filePath);
return render(content.toString(), extraOptions);
return render(content.toString(), extraOptions, filePath);
} catch (e) {
return render('File not found.', extraOptions);
}
Expand Down
24 changes: 16 additions & 8 deletions lib/static.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ import featuredSlide from './featured-slide.js';

const files = new Set();

const htmlImageRE = /!\[.*?\]\((.+?)\)/g;
const markdownImageRE = /!\[.*?\]\((.+?)\)/g;
const htmlImageRE = /<img .*?src=["'](.+?)["'].*?>/g;
const htmlImageBackgroundRE = /<!--.*?data-background-image=["'](.+?)["'].*?-->/g;

const relativeDir = (from, to) => path.relative(from, to).replace(/^\.\./, '.');
Expand All @@ -28,18 +29,21 @@ const readablePath = file =>
file.replace(/^.*(reveal-md\/node_modules.+)/, '$1').replace(new RegExp(`^${process.cwd()}/`), '');

const cp = (source, target) => {
const posixSource = source.split(path.sep).join(path.posix.sep);
const posixTarget = target.split(path.sep).join(path.posix.sep);
if (!files.has(target)) {
files.add(target);
console.log(`❏ ${readablePath(source)} → ${target}`);
return fs.copy(source, target);
return fs.copy(posixSource, posixTarget);
} else {
return Promise.resolve();
}
};

const write = (target, content) => {
const posixTarget = target.split(path.sep).join(path.posix.sep);
console.log(`★ ${target}`);
return fs.outputFile(target, content);
return fs.outputFile(posixTarget, content);
};

const copyAssetsFromOptions = async function (markdown) {
Expand Down Expand Up @@ -74,15 +78,18 @@ const copyAssetsAndWriteFile = async (sourceDir, file, targetDir) => {
const base = relativeDir(file, '.');
const markup = await renderFile(path.join(sourceDir, file), { base });

const images = markdown.matchAll(htmlImageRE);
const backgroundImages = markdown.matchAll(htmlImageBackgroundRE);
const allImages = [...images, ...backgroundImages];
const markdownImages = markup.matchAll(markdownImageRE);
const htmlImages = markup.matchAll(htmlImageRE);
const backgroundImages = markup.matchAll(htmlImageBackgroundRE);
const allImages = [...markdownImages, ...htmlImages, ...backgroundImages];

for (let image of allImages) {
const [, imgPath] = image;
if (!isAbsoluteURL(imgPath)) {
const relPath = path.join(path.dirname(file), imgPath);
awaits.push(cp(path.join(sourceDir, relPath), path.join(targetDir, relPath)).catch(err => console.warn(err)));
const relPath = decodeURIComponent(path.join(path.dirname(file), imgPath.replaceAll('\\', '/')));
const sourceImgPath = path.join(sourceDir, relPath);
const targetImgPath = path.join(targetDir, relPath);
awaits.push(cp(sourceImgPath, targetImgPath).catch(err => console.warn(err)));
}
}

Expand Down Expand Up @@ -133,3 +140,4 @@ export default async () => {

console.log(`Wrote static site to ${staticDir}`);
};

13 changes: 13 additions & 0 deletions lib/template/listing.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,20 @@
<html lang="en">
<head>
<meta charset="utf-8" />

<title>{{pageTitle}}</title>
<meta name="description" content="{{{description}}}" />

<meta property="og:title" content="{{{title}}}" />
<meta property="og:description" content="{{{description}}}" />
<meta property="og:type" content="website" />
<!-- <meta property="og:image" content="{{{absoluteUrl}}}/{{{ogImage}}}" />
<meta property="og:url" content="{{{absoluteUrl}}}/{{{ogUrl}}}" /> -->
<meta property="og:type" content="article" />

<meta itemProp="name" content="{{{title}}}" />
<meta itemProp="description" content="{{{description}}}" />

<link rel="stylesheet" href="{{{themeUrl}}}" id="theme" />
</head>

Expand Down
12 changes: 9 additions & 3 deletions lib/template/reveal.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,18 @@
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />

<title>{{{title}}}</title>
<meta name="description" content="{{{description}}}" />

{{#absoluteUrl}}
<meta property="og:title" content="{{{title}}}" />
<meta property="og:description" content="{{{description}}}" />
<meta property="og:type" content="website" />
<meta property="og:image" content="{{{absoluteUrl}}}/featured-slide.jpg" />
<meta property="og:url" content="{{{absoluteUrl}}}" />
<meta property="og:image" content="{{{absoluteUrl}}}/{{{ogImage}}}" />
<meta property="og:url" content="{{{absoluteUrl}}}/{{{ogUrl}}}" />
<meta property="og:type" content="article" />

<meta itemProp="name" content="{{{title}}}" />
<meta itemProp="description" content="{{{description}}}" />
{{/absoluteUrl}}
<link rel="shortcut icon" href="{{{base}}}/favicon.ico" />
<link rel="stylesheet" href="{{{base}}}/dist/reset.css" />
Expand Down