Created
May 1, 2020 13:50
-
-
Save JakeTheCorn/c96c4bf7a8d6e23c5a4c963b3e2d83d9 to your computer and use it in GitHub Desktop.
lil Primitive ts code snippet display
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// todo: write tests | |
interface SnippetProps { | |
val: string | |
} | |
export const Snippet = ({ | |
val | |
}: SnippetProps): JSX.Element => { | |
const elements = [] | |
const lines = val.split('\n') | |
for (var i = 0; i < lines.length; i++) { | |
const line = lines[i] | |
if (i === 0 && line === '') { | |
continue | |
} | |
let leadingSpaceCount = 0 | |
for (var j = 0; j < line.length; j++) { | |
const char = line[j] | |
if (/\s/.test(char)) { | |
leadingSpaceCount++ | |
continue | |
} | |
break | |
} | |
elements.push( | |
<span key={i}> | |
{space(leadingSpaceCount)}{line} | |
<br /> | |
</span> | |
) | |
} | |
return ( | |
<code> | |
{elements} | |
</code> | |
) | |
} | |
function space(n: number): JSX.Element { | |
return <>{Array(n).fill(<> </>)}</> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment