Skip to content

Commit bcfe3ba

Browse files
committed
move image tag replacement to imageDims.js
also made this function recursive. related: #25
1 parent a29e836 commit bcfe3ba

File tree

3 files changed

+23
-23
lines changed

3 files changed

+23
-23
lines changed

src/ampl.js

+7-22
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import Remarkable from 'remarkable';
22
import htmlparser from 'htmlparser2';
33

4-
import { getDims } from './imageDims.js';
4+
import { getDims, updateImgTags } from './imageDims.js';
55
import { createAmpPage } from './templates.js';
66

77
const remarkable = new Remarkable('full');
@@ -16,27 +16,12 @@ export const parse = (markdown, optsOrStyle, callback) => {
1616

1717
export const markdown2AmpHTML = (opts, callback) => {
1818
const { markdown } = opts;
19-
console.log(opts, markdown);
20-
console.log(markdown);
2119
const htmlRaw = remarkable.render(markdown);
22-
parseHtml(htmlRaw, (html, data) => {
23-
getDims(data.urls, (dimensions) => {
24-
const imageTagRegex = /(<img)/;
25-
let htmlAml = html;
26-
let i = 0;
27-
// todo remove while loop
28-
while(imageTagRegex.test(htmlAml)) {
29-
const newTag = `
30-
<amp-img
31-
width="${dimensions[i].width}"
32-
height="${dimensions[i].height}"
33-
layout="responsive"`;
34-
htmlAml = htmlAml.replace(imageTagRegex, newTag);
35-
i += 1;
36-
}
37-
callback(htmlAml);
38-
});
39-
});
20+
parseHtml(htmlRaw, (html, { imageUrls }) =>
21+
getDims(imageUrls, (dimensions) =>
22+
callback(updateImgTags(html, dimensions))
23+
)
24+
);
4025
}
4126

4227
var attribStr = attribs => Object.keys(attribs).map(attribKey => (
@@ -47,7 +32,7 @@ var attribStr = attribs => Object.keys(attribs).map(attribKey => (
4732

4833
var createParseRules = () => [
4934
(urls => ({
50-
label: "urls",
35+
label: "imageUrls",
5136
target: "img",
5237
onOpenTag: attribs => urls.push(attribs.src),
5338
getResults: () => urls

src/imageDims.js

+10-1
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,16 @@ export var getDims = (imageUrls, callback) => {
5050
callback(dimsArray);
5151
}
5252
}
53-
}
53+
};
54+
55+
const imageTagRegex = /(<img)/;
56+
export const updateImgTags = (html, dimensions) => imageTagRegex.test(html)
57+
? updateImgTags(html.replace(imageTagRegex, `<amp-img
58+
width="${dimensions[0].width}"
59+
height="${dimensions[0].height}"
60+
layout="responsive"`
61+
), dimensions.slice(1))
62+
: html;
5463

5564
var getBody = function(response, callback) {
5665
var chunks = [];

test.html

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
hey
2+
<body>
3+
<!doctype html><p >#h1</p>
4+
5+
</body>
6+
</html>

0 commit comments

Comments
 (0)