react-shiki 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Bassim Shahidy
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,50 @@
1
+ # react-shiki
2
+ Syntax highlighting component for react using [Shiki](https://shiki.matsu.io/)
3
+
4
+ ## Installation
5
+ ```bash
6
+ (pnpm|bun|yarn) add react-shiki
7
+ ```
8
+ ```bash
9
+ npm install react-shiki
10
+ ```
11
+
12
+ ## Usage
13
+
14
+ ```tsx
15
+ import type { ReactNode } from 'react';
16
+ import type { BundledLanguage } from 'shiki';
17
+ import ShikiHighlighter, { isInlineCode, type Element } from 'react-shiki';
18
+
19
+ interface CodeHighlightProps {
20
+ className?: string | undefined;
21
+ children?: ReactNode | undefined;
22
+ node?: Element | undefined;
23
+ }
24
+
25
+ export const CodeHighlight = ({
26
+ className,
27
+ children,
28
+ node,
29
+ ...props
30
+ }: CodeHighlightProps): JSX.Element => {
31
+ const match = className?.match(/language-(\w+)/);
32
+ // TODO: remove need for consumer use of BundledLanguage from shiki
33
+ const language = match ? (match[1] as BundledLanguage) : undefined;
34
+
35
+ const isInline: boolean | undefined = node ? isInlineCode(node) : undefined;
36
+
37
+ return !isInline ? (
38
+ <ShikiHighlighter
39
+ language={language as BundledLanguage}
40
+ theme={'houston'}
41
+ {...props}>
42
+ {String(children)}
43
+ </ShikiHighlighter>
44
+ ) : (
45
+ <code className={className} {...props}>
46
+ {children}
47
+ </code>
48
+ );
49
+ };
50
+ ```
@@ -0,0 +1,22 @@
1
+ import React, { ReactNode } from 'react';
2
+ import { BundledLanguage, BundledTheme } from 'shiki';
3
+ import { Element } from 'hast';
4
+ export { Element } from 'hast';
5
+
6
+ interface ShikiHighlighterProps {
7
+ language: BundledLanguage;
8
+ children: string;
9
+ theme: BundledTheme;
10
+ addDefaultStyles?: boolean;
11
+ style?: React.CSSProperties;
12
+ className?: string;
13
+ showLanguage?: boolean;
14
+ as?: React.ElementType;
15
+ }
16
+ declare const ShikiHighlighter: ({ language, theme, addDefaultStyles, style, className, showLanguage, children: code, as: Element, }: ShikiHighlighterProps) => React.JSX.Element;
17
+
18
+ declare const useShikiHighlighter: (code: string, lang: BundledLanguage | undefined, theme: BundledTheme) => ReactNode;
19
+
20
+ declare const isInlineCode: (node: Element) => boolean;
21
+
22
+ export { ShikiHighlighter as default, isInlineCode, useShikiHighlighter };
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ function a(e,{insertAt:i}={}){if(!e||typeof document>"u")return;let r=document.head||document.getElementsByTagName("head")[0],t=document.createElement("style");t.type="text/css",i==="top"&&r.firstChild?r.insertBefore(t,r.firstChild):r.appendChild(t),t.styleSheet?t.styleSheet.cssText=e:t.appendChild(document.createTextNode(e))}a(`.relative{position:relative}.container pre{overflow:auto;border-radius:.5rem;padding:1.25rem 1.5rem}.languageLabel{position:absolute;right:.75rem;top:.5rem;font-family:monospace;font-size:.75rem;letter-spacing:-.05em;color:#6b7280d9}
2
+ `);import g from"react";import p from"html-react-parser";import{useEffect as f,useState as y}from"react";import{codeToHtml as h}from"shiki";var c=e=>e.position?.start.line===e.position?.end.line,s={pre(e){e.properties.tabindex="-1"}};var d=(e,i,r)=>{let[t,o]=y(null);return f(()=>{(async()=>{try{let n=await h(e,{lang:i,theme:r,transformers:[s]});o(p(n))}catch{let l=await h(e,{lang:"plaintext",theme:r,transformers:[s]});o(p(l))}})()},[e,r,i]),t};import{clsx as x}from"clsx";var C=({language:e,theme:i,addDefaultStyles:r=!0,style:t,className:o,showLanguage:m=!0,children:n,as:l="pre"})=>{let u=d(n,e,i);return g.createElement(l,{className:x("relative",r&&"container",o),style:t},m&&e?g.createElement("span",{className:"languageLabel",style:t},e):null,u)};export{C as default,c as isInlineCode,d as useShikiHighlighter};
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["#style-inject:#style-inject","../src/styles.css","../src/ShikiHighlighter.tsx","../src/useShiki.ts","../src/utils.ts"],"sourcesContent":["\n export default function styleInject(css, { insertAt } = {}) {\n if (!css || typeof document === 'undefined') return\n \n const head = document.head || document.getElementsByTagName('head')[0]\n const style = document.createElement('style')\n style.type = 'text/css'\n \n if (insertAt === 'top') {\n if (head.firstChild) {\n head.insertBefore(style, head.firstChild)\n } else {\n head.appendChild(style)\n }\n } else {\n head.appendChild(style)\n }\n \n if (style.styleSheet) {\n style.styleSheet.cssText = css\n } else {\n style.appendChild(document.createTextNode(css))\n }\n }\n ","import styleInject from '#style-inject';styleInject(\".relative{position:relative}.container pre{overflow:auto;border-radius:.5rem;padding:1.25rem 1.5rem}.languageLabel{position:absolute;right:.75rem;top:.5rem;font-family:monospace;font-size:.75rem;letter-spacing:-.05em;color:#6b7280d9}\\n\")","import './styles.css';\n// biome-ignore lint/style/useImportType: Package needs React to be imported\nimport React from 'react';\nimport type { BundledLanguage, BundledTheme } from 'shiki';\nimport { useShikiHighlighter } from '@/useShiki';\nimport { clsx } from 'clsx';\n\ninterface ShikiHighlighterProps {\n language: BundledLanguage;\n children: string;\n theme: BundledTheme;\n addDefaultStyles?: boolean;\n style?: React.CSSProperties;\n className?: string;\n showLanguage?: boolean;\n as?: React.ElementType;\n}\n\nexport const ShikiHighlighter = ({\n language,\n theme,\n addDefaultStyles = true,\n style,\n className,\n showLanguage = true,\n children: code,\n as: Element = 'pre',\n}: ShikiHighlighterProps) => {\n const highlightedCode = useShikiHighlighter(code, language, theme);\n\n return (\n <Element\n className={clsx(\n 'relative',\n addDefaultStyles && 'container',\n className\n )}\n style={style}\n >\n {showLanguage && language ? (\n <span className=\"languageLabel\" style={style}>\n {language}\n </span>\n ) : null}\n {highlightedCode}\n </Element>\n );\n};\n","import parse from 'html-react-parser';\nimport { type ReactNode, useEffect, useState } from 'react';\nimport { type BundledLanguage, type BundledTheme, codeToHtml } from 'shiki';\nimport { removeTabIndexFromPre } from '@/utils';\n\nexport const useShikiHighlighter = (\n code: string,\n lang: BundledLanguage | undefined,\n theme: BundledTheme\n) => {\n const [highlightedCode, setHighlightedCode] = useState<ReactNode | null>(\n null\n );\n\n useEffect(() => {\n const highlightCode = async () => {\n try {\n const html = await codeToHtml(code, {\n lang: lang as BundledLanguage,\n theme,\n transformers: [removeTabIndexFromPre],\n });\n setHighlightedCode(parse(html));\n } catch (error) {\n const fallbackHtml = await codeToHtml(code, {\n lang: 'plaintext',\n theme,\n transformers: [removeTabIndexFromPre],\n });\n setHighlightedCode(parse(fallbackHtml));\n }\n };\n\n highlightCode();\n }, [code, theme, lang]);\n\n return highlightedCode;\n};\n","import type { Element } from 'hast';\n\nexport const isInlineCode = (node: Element): boolean => {\n return node.position?.start.line === node.position?.end.line;\n};\n\n\nexport const removeTabIndexFromPre = {\n pre(node: Element) {\n node.properties.tabindex = '-1';\n },\n};\n\nexport type { Element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IAAMC,EAAmB,CAAC,CAC/B,SAAAC,EACA,MAAAC,EACA,iBAAAC,EAAmB,GACnB,MAAAC,EACA,UAAAC,EACA,aAAAC,EAAe,GACf,SAAUC,EACV,GAAIC,EAAU,KAChB,IAA6B,CAC3B,IAAMC,EAAkBC,EAAoBH,EAAMN,EAAUC,CAAK,EAEjE,OACES,EAAA,cAACH,EAAA,CACC,UAAWT,EACT,WACAI,GAAoB,YACpBE,CACF,EACA,MAAOD,GAENE,GAAgBL,EACfU,EAAA,cAAC,QAAK,UAAU,gBAAgB,MAAOP,GACpCH,CACH,EACE,KACHQ,CACH,CAEJ","names":["styleInject","css","insertAt","head","style","styleInject","React","parse","useEffect","useState","codeToHtml","isInlineCode","node","removeTabIndexFromPre","useShikiHighlighter","code","lang","theme","highlightedCode","setHighlightedCode","useState","useEffect","html","codeToHtml","removeTabIndexFromPre","parse","fallbackHtml","clsx","ShikiHighlighter","language","theme","addDefaultStyles","style","className","showLanguage","code","Element","highlightedCode","useShikiHighlighter","React"]}
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "react-shiki",
3
+ "description": "Syntax highlighter component for react using shiki",
4
+ "version": "0.1.0",
5
+ "license": "MIT",
6
+ "author": {
7
+ "name": "Bassim Shahidy",
8
+ "email": "bassim@shahidy.com",
9
+ "url": "https://bassim.build"
10
+ },
11
+ "repository": "https://github.com/avgvstvs96/react-shiki",
12
+ "keywords": [
13
+ "react",
14
+ "shiki",
15
+ "code",
16
+ "syntax",
17
+ "highlighter",
18
+ "syntax-highlighter",
19
+ "react-syntax-highlighter"
20
+ ],
21
+ "type": "module",
22
+ "main": "./dist/index.js",
23
+ "types": "./dist/index.d.ts",
24
+ "files": [
25
+ "dist"
26
+ ],
27
+ "exports": {
28
+ ".": {
29
+ "types": "./dist/index.d.ts",
30
+ "default": "./dist/index.js"
31
+ }
32
+ },
33
+ "peerDependencies": {
34
+ "react": ">= 15.0.0",
35
+ "react-dom": ">= 15.0.0"
36
+ },
37
+ "dependencies": {
38
+ "clsx": "^2.1.1",
39
+ "html-react-parser": "^5.1.12",
40
+ "shiki": "^1.12.1"
41
+ },
42
+ "devDependencies": {
43
+ "@types/hast": "^3.0.4",
44
+ "@types/react": "^18.3.3",
45
+ "tsup": "^8.2.4"
46
+ },
47
+ "scripts": {
48
+ "dev": "tsup --watch",
49
+ "build": "tsup"
50
+ }
51
+ }