Cover image for Refractor Test

Refractor Test

A testing page for demonstrating my approach to syntax highlighting
Avatar of Jane Manchun Wong
Jane Manchun Wong

I wondered if it is possible to do syntax highlighting under these two criterias: Without shipping syntax parser to the client (huge bundle size) nor Without doing dangerouslySetInnerHTML (prone to XSS)

So I figured to use refractor to do the syntax highlighting, which converts the code using Prism.js into unist AST in compile time / on server side. On client side, this AST is hydrated using rehype-react

twoSum::(Num a,Ord a) => a -> [a] -> [Int]

twoSum num list = sol ls (reverse ls)
ls = zip list [0..]
sol [] _ = []
sol _ [] = []
sol xs@((x,i):us) ys@((y,j):vs) = ans
s = x + y
ans | s == num = [i,j]
| j <= i = []
| s < num = sol (dropWhile ((<num).(+y).fst) us) ys
| otherwise = sol xs $ dropWhile ((num <).(+x).fst) vs

main = print $ twoSum 21 [0, 2, 11, 19, 90]

Even the styling for this code block above is encapsulated into a CSS Module so it won’t increase the CSS file size for the rest of the site.