@0x1js/highlighter
Version:
5 lines (4 loc) • 8.98 kB
JavaScript
var{defineProperty:N,getOwnPropertyNames:u,getOwnPropertyDescriptor:p}=Object,l=Object.prototype.hasOwnProperty;var B=new WeakMap,h=(Q)=>{var U=B.get(Q),F;if(U)return U;if(U=N({},"__esModule",{value:!0}),Q&&typeof Q==="object"||typeof Q==="function")u(Q).map((X)=>!l.call(U,X)&&N(U,X,{get:()=>Q[X],enumerable:!(F=p(Q,X))||F.enumerable}));return B.set(Q,U),U};var r=(Q,U)=>{for(var F in U)N(Q,F,{get:U[F],enumerable:!0,configurable:!0,set:(X)=>U[F]=()=>X})};var t={};r(t,{version:()=>x,useHighlight:()=>y,tokenizeJavaScript:()=>A,tokenizeBash:()=>v,highlight:()=>I,getSupportedLanguages:()=>H,default:()=>i,TypeScriptHighlighter:()=>L,SyntaxHighlighter:()=>M,JavaScriptHighlighter:()=>S,JSONHighlighter:()=>k,InlineCode:()=>f,BashHighlighter:()=>R});module.exports=h(t);var s=new Set(["abstract","async","await","break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","if","implements","import","in","instanceof","interface","let","new","null","of","public","private","protected","readonly","return","static","super","switch","this","throw","true","try","type","typeof","undefined","var","void","while","with","yield"]),a=new Set(["string","number","boolean","object","symbol","bigint","any","unknown","never","void","Array","Promise","Set","Map","Date","RegExp","Error"]),d=new Set(["console","window","document","global","process","require","module","exports","Math","JSON","parseInt","parseFloat","isNaN","isFinite"]),n=new Set(["if","then","else","elif","fi","case","esac","for","select","while","until","do","done","in","function","time","coproc","cd","echo","export","alias","unalias","set","unset","readonly","local","declare","typeset","exit","return","break","continue","shift","test","source","eval","exec","trap","kill","jobs","bg","fg","wait","suspend","true","false"]),c=new Set(["ls","cd","pwd","mkdir","rmdir","rm","cp","mv","ln","find","grep","sed","awk","sort","uniq","cut","tr","head","tail","wc","cat","less","more","file","which","whereis","locate","man","info","help","history","alias","ps","top","htop","kill","killall","nohup","screen","tmux","ssh","scp","rsync","wget","curl","git","npm","bun","node","python","pip","docker","kubectl","make","gcc","clang","java","javac"]);function A(Q){let U=[],F=0;while(F<Q.length){let X=Q[F];if(/\s/.test(X)){F++;continue}if(X==="/"&&Q[F+1]==="/"){let V=F;while(F<Q.length&&Q[F]!==`
`)F++;U.push({type:"comment",value:Q.slice(V,F),start:V,end:F});continue}if(X==="/"&&Q[F+1]==="*"){let V=F;F+=2;while(F<Q.length-1&&!(Q[F]==="*"&&Q[F+1]==="/"))F++;F+=2,U.push({type:"comment",value:Q.slice(V,F),start:V,end:F});continue}if(X==='"'||X==="'"||X==="`"){let V=X,Z=F;F++;while(F<Q.length){if(Q[F]===V&&Q[F-1]!=="\\"){F++;break}if(Q[F]==="\\")F++;F++}U.push({type:"string",value:Q.slice(Z,F),start:Z,end:F});continue}if(/\d/.test(X)||X==="."&&/\d/.test(Q[F+1])){let V=F;while(F<Q.length&&/[\d.eE+-]/.test(Q[F]))F++;U.push({type:"number",value:Q.slice(V,F),start:V,end:F});continue}if(/[a-zA-Z_$]/.test(X)){let V=F;while(F<Q.length&&/[a-zA-Z0-9_$]/.test(Q[F]))F++;let Z=Q.slice(V,F),q="plain";if(s.has(Z))q="keyword";else if(a.has(Z))q="type";else if(d.has(Z))q="constant";else if(/^[A-Z]/.test(Z))q="type";else if(Q[F]==="(")q="function";U.push({type:q,value:Z,start:V,end:F});continue}if(/[+\-*/%=<>!&|^~?:;,.[\]{}()]/.test(X)){let V=F;if(F<Q.length-1){let Z=Q.slice(F,F+2);if(["==","!=","<=",">=","&&","||","++","--","=>","??"].includes(Z))F+=2;else if(F<Q.length-2&&["===","!=="].includes(Q.slice(F,F+3)))F+=3;else F++}else F++;U.push({type:"operator",value:Q.slice(V,F),start:V,end:F});continue}U.push({type:"plain",value:X,start:F,end:F+1}),F++}return U}function v(Q){let U=[],F=0;while(F<Q.length){let X=Q[F];if(/\s/.test(X)){F++;continue}if(X==="#"){let V=F;while(F<Q.length&&Q[F]!==`
`)F++;U.push({type:"comment",value:Q.slice(V,F),start:V,end:F});continue}if(X==='"'||X==="'"){let V=X,Z=F;F++;while(F<Q.length){if(Q[F]===V&&Q[F-1]!=="\\"){F++;break}if(Q[F]==="\\")F++;F++}U.push({type:"string",value:Q.slice(Z,F),start:Z,end:F});continue}if(X==="$"){let V=F;if(F++,Q[F]==="{"){F++;while(F<Q.length&&Q[F]!=="}")F++;F++}else while(F<Q.length&&/[a-zA-Z0-9_]/.test(Q[F]))F++;U.push({type:"variable",value:Q.slice(V,F),start:V,end:F});continue}if(/\d/.test(X)){let V=F;while(F<Q.length&&/\d/.test(Q[F]))F++;U.push({type:"number",value:Q.slice(V,F),start:V,end:F});continue}if(/[a-zA-Z_]/.test(X)){let V=F;while(F<Q.length&&/[a-zA-Z0-9_-]/.test(Q[F]))F++;let Z=Q.slice(V,F),q="plain";if(n.has(Z))q="keyword";else if(c.has(Z))q="function";U.push({type:q,value:Z,start:V,end:F});continue}if(/[|&;<>()[\]{}*?~]/.test(X)){let V=F;if(F<Q.length-1){let Z=Q.slice(F,F+2);if(["&&","||",">>","<<","2>","2&"].includes(Z))F+=2;else F++}else F++;U.push({type:"operator",value:Q.slice(V,F),start:V,end:F});continue}U.push({type:"plain",value:X,start:F,end:F+1}),F++}return U}function I(Q,U){let{language:F,showLineNumbers:X=!1,startLineNumber:V=1,maxLines:Z,wrapLines:q=!0}=U,_;switch(F){case"javascript":case"typescript":_=A(Q);break;case"bash":_=v(Q);break;case"json":_=A(Q);break;default:_=[{type:"plain",value:Q,start:0,end:Q.length}]}let K="",O=Q.split(`
`),w=Z?Math.min(O.length,Z):O.length;for(let z=0;z<w;z++){let j=O.slice(0,z).reduce((G,E)=>G+E.length+1,0),D=j+O[z].length,$=_.filter((G)=>G.start>=j&&G.end<=D+1);if(K+='<div class="highlight-line">',X){let G=V+z;K+=`<span class="line-number" data-line="${G}">${G}</span>`}K+='<span class="line-content">';let W=j;for(let G of $){if(G.start>W)K+=b(Q.slice(W,G.start));K+=`<span class="token-${G.type}">${b(G.value)}</span>`,W=G.end}if(W<D)K+=b(Q.slice(W,D));K+="</span></div>"}if(Z&&O.length>Z)K+=`<div class="highlight-line truncated">... ${O.length-Z} more lines</div>`;return K}function b(Q){return Q.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function H(){return["javascript","typescript","bash","json","html","css"]}var Y=require("0x1/index.js");var P=require("0x1/jsx-runtime.js");function M({children:Q,language:U,theme:F="dark",showLineNumbers:X=!1,startLineNumber:V=1,maxLines:Z,wrapLines:q=!0,className:_="",style:K,copyable:O=!0,title:w,footer:z,onCopy:j}){let D=Y.useRef(null),$=Y.useRef(null),W=Y.useRef(null),G=Y.useMemo(()=>{return I(Q,{language:U,theme:F,showLineNumbers:X,startLineNumber:V,maxLines:Z,wrapLines:q})},[Q,U,F,X,V,Z,q]),E=async()=>{if(!O||!$.current)return;try{if(await navigator.clipboard.writeText(Q),$.current.textContent="✅",$.current.classList.add("copied"),W.current)clearTimeout(W.current);W.current=setTimeout(()=>{if($.current)$.current.textContent="\uD83D\uDCCB",$.current.classList.remove("copied")},2000)}catch(T){console.error("Failed to copy code:",T);let C=document.createElement("textarea");C.value=Q,document.body.appendChild(C),C.select();try{if(document.execCommand("copy"),$.current.textContent="✅",$.current.classList.add("copied"),W.current)clearTimeout(W.current);W.current=setTimeout(()=>{if($.current)$.current.textContent="\uD83D\uDCCB",$.current.classList.remove("copied")},2000)}catch(J){console.error("Fallback copy failed:",J)}document.body.removeChild(C)}},m=()=>{if($.current)$.current.classList.add("visible")},g=()=>{if($.current)$.current.classList.remove("visible")};return Y.useEffect(()=>{return()=>{if(W.current)clearTimeout(W.current)}},[]),Y.useEffect(()=>{let T=D.current;if(!T||!O)return;let C=(J)=>{if((J.ctrlKey||J.metaKey)&&J.key==="c")J.preventDefault(),E()};return T.addEventListener("keydown",C),()=>T.removeEventListener("keydown",C)},[Q,O]),P.jsxs("div",{className:`syntax-highlighter-wrapper ${_}`,style:K,onMouseEnter:m,onMouseLeave:g,children:[w&&P.jsxs("div",{className:"syntax-highlighter-header",children:[P.jsx("span",{className:"syntax-highlighter-title",children:w}),P.jsx("span",{className:"syntax-highlighter-language",children:U})]}),P.jsxs("div",{ref:D,className:`syntax-highlighter theme-${F}`,tabIndex:0,role:"textbox","aria-label":`Code snippet in ${U}`,"aria-readonly":"true",children:[O&&P.jsx("button",{ref:$,className:"copy-button",onClick:E,"aria-label":"Copy code to clipboard",title:"Copy code",children:"\uD83D\uDCCB"}),P.jsx("div",{className:"syntax-highlighter-content",dangerouslySetInnerHTML:{__html:G}})]}),z&&P.jsx("div",{className:"syntax-highlighter-footer",children:z})]})}function S(Q){return P.jsx(M,{...Q,language:"javascript"})}function L(Q){return P.jsx(M,{...Q,language:"typescript"})}function R(Q){return P.jsx(M,{...Q,language:"bash"})}function k(Q){return P.jsx(M,{...Q,language:"json"})}function f({children:Q,language:U="javascript",theme:F="dark"}){let X=I(Q,{language:U,theme:F});return P.jsx("code",{className:`inline-code theme-${F}`,dangerouslySetInnerHTML:{__html:X}})}function y(Q,U){let[F,X]=Y.useState("");return Y.useEffect(()=>{let V=I(Q,U);X(V)},[Q,U.language,U.theme]),F}var x="0.1.4",i={highlight:I,tokenizeJavaScript:A,tokenizeBash:v,getSupportedLanguages:H,version:x};