chore(copyright): 2024
[curben-blog.git] / scripts / image.js
blobeb82a893148ab3165bfda821a1c3f45ed868e5ba
1 'use strict'
2 /* global hexo */
4 /*
5 *  Embed an image with responsive images in a post
6 *  https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images
7 *  Image is resized on-the-fly using Statically (https://statically.io/)
8 *  Usage: ![alt](/path/to/img "title")
9 */
11 const { join } = require('path').posix
13 hexo.extend.filter.register('marked:renderer', (renderer) => {
14   renderer.image = (href, title, alt) => {
15     if (!alt) alt = ''
16     if (!title) title = alt
18     if (href.endsWith('.svg')) return `<img class="svg" src="${href}" alt="${alt}" title="${title}">`
20     // embed external image
21     if (href.startsWith('http')) return `<img src="${href}" alt="${alt}" title="${title}">`
23     const fLink = (path, width) => {
24       const query = new URLSearchParams('f=auto')
25       if (typeof width === 'number') query.set('width', width)
26       const url = new URL('http://example.com/' + join('img', path) + '?' + query)
28       return url.pathname + url.search
29     }
31     return `<a href="${join('/img', href)}">` +
32       `<img srcset="${fLink(href, 320)} 320w,` +
33       `${fLink(href, 468)} 468w,` +
34       `${fLink(href, 768)} 768w,` +
35       `${fLink(href)} 800w"` +
36       ' sizes="(max-width: 320px) 320px,' +
37       '(max-width: 468px) 468px,' +
38       '(max-width: 768px) 768px,' +
39       '800px"' +
40       ` src="${fLink(href)}" title="${title}" alt="${alt}" loading="lazy"></a>`
41   }