code.js 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import { useEffect, useState } from "react";
  2. import { codeToHtml } from "shiki";
  3. import { jsx } from "@emotion/react";
  4. /**
  5. * Code component that uses Shiki to convert code to HTML and render it.
  6. *
  7. * @param code - The code to be highlighted.
  8. * @param theme - The theme to be used for highlighting.
  9. * @param language - The language of the code.
  10. * @param transformers - The transformers to be applied to the code.
  11. * @param decorations - The decorations to be applied to the code.
  12. * @param divProps - Additional properties to be passed to the div element.
  13. * @returns The rendered code block.
  14. */
  15. export function Code({
  16. code,
  17. theme,
  18. language,
  19. transformers,
  20. decorations,
  21. ...divProps
  22. }) {
  23. const [codeResult, setCodeResult] = useState("");
  24. useEffect(() => {
  25. async function fetchCode() {
  26. const result = await codeToHtml(code, {
  27. lang: language,
  28. theme,
  29. transformers,
  30. decorations,
  31. });
  32. setCodeResult(result);
  33. }
  34. fetchCode();
  35. }, [code, language, theme, transformers, decorations]);
  36. return jsx("div", {
  37. dangerouslySetInnerHTML: { __html: codeResult },
  38. ...divProps,
  39. });
  40. }