blog/scripts/image.js

43 lines
1.4 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}">`
const fLink = (path, width) => {
const query = new URLSearchParams('f=auto')
if (typeof width === 'number') query.set('width', width)
const url = new URL('http://example.com/' + join('img', path) + '?' + query)
return url.pathname + url.search
}
return `<a href="${join('/img', href)}">` +
`<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>`
}
})