john mangual john mangual - 5 months ago 31
jQuery Question

Syntax Highlighting with Elm

I am writing a simple app that puts a syntax-highlighted block of code. For now I am using highlightjs do to the syntax highlighting for me.

Why doesn't my call to

highlightBlock
work here?

For careful readers: my choice of
Model
and
Msg
are completely absurd, since I don't really use them right now.

import Html exposing (..)
import Html.App as Html
import Html.Attributes exposing (..)

main =
Html.program
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}

-- Model

type alias Model = { state: Int }

init : (Model, Cmd Msg)
init = (Model 1, Cmd.none)

-- view

view : Model -> Html Msg
view model = div [ ] [ codesample ]

codesample : Html Msg
codesample = pre [ myStyle ] [ code [] [ Html.text thisCode ] ]

myStyle : Html.Attribute Msg
myStyle = Html.Attributes.style [("background-color", "#F0F0F0"), ("width", "500px")]

thisCode : String
thisCode = """
import Html exposing (..)
import Html.App as Html
import Html.Events exposing (..)
import Random
import Svg exposing (..)

main =
Html.program
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
"""

-- update


type Msg
= Roll | NewFace Int

update : Msg -> Model -> (Model, Cmd Msg)
update msg model = ( model , Cmd.none )

-- subscriptions

subscriptions : Model -> Sub Msg
subscriptions model = Sub.none


Once I call
highlightjs
I have stepped outside the scope of pure Elm. I download the Elm syntax highlight bundle and call the library as follows but nothing... I suspect ports will be necessary (as mentioned on Slack)

<html>
<head>
<link rel="stylesheet" href="styles/solarized-dark.css">
<script src="highlight.pack.js"></script>
</head>
<body>

<div id="my-elm-block"></div>
<script src="block.js"></script>
<script>
var node = document.getElementById("my-elm-block");
var app = Elm.Main.embed(node);
hljs.highlightBlock(node);

</script>
</body>
</html>

Answer

For some reason, calling a function on the DOM generated by Elm directly after calling embed doesn't work, but if you wrap it in a tiny timeout, it does. Change your highlight line to this:

setTimeout(function() { hljs.highlightBlock(node); }, 1);

I've had to use this hack several times and haven't had a problem with it.