LukeberryPi / blog

My personal blog
https://lukeberrypi.vercel.app
2 stars 5 forks source link

add syntax highlighting to code blocks #2

Closed LukeberryPi closed 1 week ago

LukeberryPi commented 1 month ago

possibly: https://github.com/rehypejs/rehype-highlight

LukeberryPi commented 1 month ago

maybe better: https://github.com/huozhi/sugar-high

CaioHVectorA commented 1 month ago

image Using sugar-high!

my Implementation: Get into page.tsx of /articles/[slug] remove article tag create new component as the article and set use client

"use client"

import { useEffect } from "react";
import { highlight } from "sugar-high";

export function Article({ html }: { html: string }) {
    const handleFormatCode = () => {
        const codes = document.querySelectorAll("pre code");
        codes.forEach((code) => {
        if (code.innerHTML.includes("span")) return;
          console.log(code.innerHTML)
          const html = highlight(code.innerHTML);
          // console.log(html)
          code.innerHTML = html;
        });
      }
      useEffect(handleFormatCode, [])
    return (
        <article dangerouslySetInnerHTML={{ __html: html }} />
    )
}

Ps: Had to add a .replace(/&lt;/g, "<").replace(/&gt;/g, ">") in my code to handle < and > characters unicodes...

CaioHVectorA commented 1 month ago

The replace dont working with less/greater than...

Worked switching code.innerHTML on highlight calling to code.textContent

LukeberryPi commented 1 month ago

hey @CaioHVectorA can you open a PR?

CaioHVectorA commented 1 month ago

surely!