blog/scripts/image.js

41 lines
1.3 KiB
JavaScript
Raw Normal View History

2019-08-09 13:02:51 +00:00
'use strict'
/* global hexo */
2018-10-01 02:24:11 +00:00
/*
* Embed an image with responsive images in a post
* https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images
* Image is resized on-the-fly using Statically (https://statically.io/)
* Usage: ![alt](/path/to/img "title")
2018-10-01 02:24:11 +00:00
*/
2019-08-25 07:45:44 +00:00
const { join } = require('path').posix
hexo.extend.filter.register('marked:renderer', (renderer) => {
renderer.image = (href, title, alt) => {
if (!alt) alt = ''
if (!title) title = alt
2021-01-15 01:30:27 +00:00
if (href.endsWith('.svg')) return `<img class="svg" src="${href}" alt="${alt}" title="${title}">`
// embed external image
2023-02-25 06:41:45 +00:00
if (href.startsWith('http')) return `<img src="${href}" alt="${alt}" title="${title}">`
2024-10-04 10:46:57 +00:00
const fLink = (path, width = '') => {
const url = new URL(join('images', width, path), 'http://example.com/')
2024-10-04 10:46:57 +00:00
return url.pathname
}
return `<a href="${join('/img', href)}">` +
2024-10-04 10:46:57 +00:00
`<img srcset="${fLink(href, '320')} 320w,` +
`${fLink(href, '468')} 468w,` +
`${fLink(href, '768')} 768w,` +
`${fLink(href)} 800w"` +
' sizes="(max-width: 320px) 320px,' +
'(max-width: 468px) 468px,' +
'(max-width: 768px) 768px,' +
'800px"' +
` src="${fLink(href)}" title="${title}" alt="${alt}" loading="lazy"></a>`
}
})