Skip to content

Instantly share code, notes, and snippets.

@potato4d
Last active February 19, 2021 15:27
Show Gist options
  • Save potato4d/508e2d8383b27cba889c6fdee0720398 to your computer and use it in GitHub Desktop.
Save potato4d/508e2d8383b27cba889c6fdee0720398 to your computer and use it in GitHub Desktop.
rehype プラグインとして動く img に width / height を付与するやつ (パッケージ化するかは不明)
{
"devDependencies": {
"@types/axios": "^0.14.0",
"@types/hast": "^2.3.1",
"@types/jimp": "^0.2.28",
"hast": "^1.0.0",
"rehype": "^11.0.0",
"typescript": "^4.0.2"
},
"dependencies": {
"axios": "^0.21.1",
"jimp": "^0.16.1",
"unified": "^9.2.0",
"unist-util-visit": "^2.0.3"
}
}
import { Processor, Transformer } from 'unified'
import { Node } from 'unist'
import visit from 'unist-util-visit'
import hast from 'hast'
import axios from 'axios'
import Jimp from 'jimp'
function addWidthAndHeightPlugin(this: Processor): Transformer {
async function visitor(el: hast.Element) {
const maxWidth = 650 // ここをオプション化したらよさそう
if (el.tagName !== 'img') {
return
}
const { properties } = el
if (!properties) {
return
}
const { src } = properties
if (!(src && `${src}`.startsWith('http'))) {
return
}
const response = await axios.get(`${src}`, {
responseType: 'arraybuffer'
})
const image = await Jimp.read(Buffer.from(response.data, 'binary'))
const size = {
width: image.bitmap.width,
height: image.bitmap.height,
}
if (size.width > maxWidth) {
size.height = ~~(size.height * (maxWidth / size.width))
size.width = ~~(size.width * (maxWidth / size.width))
}
el.properties = {
...size,
...(el.properties || {})
}
}
async function transformer(htmlAST: Node): Promise<Node> {
const matches: hast.Element[] = []
visit<hast.Element>(htmlAST, 'element', (el: hast.Element) => {
matches.push(el)
})
const promises = matches.map( el => visitor(el) )
await Promise.all( promises );
return htmlAST
}
return transformer
}
export default addWidthAndHeightPlugin
module.exports = addWidthAndHeightPlugin
@potato4d
Copy link
Author

本来はもっと色々できると思うんですが、とりあえずミニマルとして(オプションで渡した width にするとかやったほうが良いと思います)

@potato4d
Copy link
Author

多分 Factory 関数にしたりしたほうがいいと思います

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment