fix: 修复机核文章中多图没有显示的问题 (#6315)

This commit is contained in:
Botao Wang
2020-12-06 18:02:40 +00:00
committed by GitHub
parent e2c4eb7c41
commit 8284ff95c1
+48 -5
View File
@@ -51,12 +51,28 @@ module.exports = async (ctx) => {
// replace figure with img
const articleContent = JSON.parse(articleData.attributes.content);
const imgs = Object.values(articleContent.entityMap)
.filter((e) => e.type === 'IMAGE')
.map((e) => e.data.path);
const entityRangeMap = {};
for (const block of articleContent.blocks || []) {
if (block.entityRanges.length) {
entityRangeMap[block.key] = block.entityRanges;
}
}
$('figure').each((i, elem) => {
if (imgs[i]) {
$(elem).replaceWith($(`<img src="https://image.gcores.com/${imgs[i]}" />`));
const keyAttr = elem.attribs['data-offset-key'];
const keyMatch = /^(\w+)-(\d+)-(\d)$/.exec(keyAttr);
let actualContent = '';
if (keyMatch) {
const [, key, index] = keyMatch;
if (entityRangeMap[key] && entityRangeMap[key][index]) {
const entityKey = entityRangeMap[key] && entityRangeMap[key][index].key;
const entity = articleContent.entityMap[entityKey];
actualContent = convertEntityToContent(entity);
}
}
if (actualContent) {
$(elem).replaceWith(actualContent);
}
});
@@ -82,3 +98,30 @@ module.exports = async (ctx) => {
item: out,
};
};
function convertEntityToContent(entity) {
const { type, data } = entity;
switch (type) {
case 'IMAGE':
return `
<figure>
<img src="https://image.gcores.com/${data.path}" alt="${data.caption || ''}">
${data.caption ? `<figcaption>${data.caption}</figcaption>` : ''}
</figure>`;
case 'GALLERY':
return data.images
.map(
(image, i, arr) => `
<figure>
<img src="https://image.gcores.com/${image.path}" alt="${image.caption || ''}">
<figcaption>${data.caption || ''} (${i + 1}/${arr.length}) ${image.caption || ''}</figcaption>
</figure>
`
)
.join('');
default:
return '';
}
}