Skip to content

Commit

Permalink
Force markdown img lazy loading (#232)
Browse files Browse the repository at this point in the history
Code is taken from
https://github.com/potato4d/rehype-plugin-image-native-lazy-loading to
avoid pulling a new dependency for a single function
  • Loading branch information
nicolaskempf57 authored Dec 31, 2024
1 parent 696af36 commit 8da7ed7
Showing 1 changed file with 26 additions and 2 deletions.
28 changes: 26 additions & 2 deletions utils/markdown.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { RiLinksLine } from '@remixicon/vue'
import type hast from 'hast'
import behead from 'remark-behead'
import remarkBreaks from 'remark-breaks'
import rehypeHighlight from 'rehype-highlight'
Expand All @@ -8,8 +10,9 @@ import rehypeRaw from 'rehype-raw'
import rehypeSanitize from 'rehype-sanitize'
import rehypeSlug from 'rehype-slug'
import rehypeStringify from 'rehype-stringify'
import { unified } from 'unified'
import { RiLinksLine } from '@remixicon/vue'
import { unified, type Processor, type Transformer } from 'unified'
import type { Node } from 'unist'
import { visit } from 'unist-util-visit'
import { render } from 'vue'

const prose = 'prose prose-neutral max-w-none prose-strong:text-gray-plain'
Expand All @@ -21,6 +24,26 @@ const proseOthers = 'prose-blockquote:border-neutral-800 prose-a:no-underline pr

export const markdownClasses = [prose, proseTable, proseHeading, proseList, proseCode, proseOthers].join(' ')

// Copied from https://github.com/potato4d/rehype-plugin-image-native-lazy-loading/blob/v1.2.0/src/index.ts
function lazyLoadPlugin(this: Processor): Transformer {
function visitor(el: hast.Element) {
if (el.tagName !== 'img') {
return
}
el.properties = {
...(el.properties || {}),
loading: 'lazy',
}
}

function transformer(htmlAST: Node): Node {
visit(htmlAST, 'element', visitor)
return htmlAST
}

return transformer
}

export function formatMarkdown(md: string, minDepth = 3) {
let el: HTMLElement | string = ''
if (document) {
Expand Down Expand Up @@ -49,6 +72,7 @@ export function formatMarkdown(md: string, minDepth = 3) {
.use(rehypeSanitize)
// Serialize syntax tree to HTML
.use(rehypeStringify)
.use(lazyLoadPlugin)
// And finally, process the input
.processSync(md)
}

0 comments on commit 8da7ed7

Please sign in to comment.