pakx
pakx

Reputation: 236

Decoding Html.Attribute.style

n00b. This is a follow-up question to my own answer at How to get style in Elm. In the question the OP needed only a specific style item line-height, which was easy enough. In looking into getting all style items I'm at the moment stumped.

In this Ellie I've made a made an example of decoding a Json object that represents an Elm-applied style: https://ellie-app.com/VNs4WGpNDNa1/0 . So far so good.

However in this Ellie, displaying a specific style item (color) works, but displaying the entire style structure doesn't: https://ellie-app.com/VN8X9kHbBfa1/0 . (In this Ellie I'd also like to combine the colorDecoder and styleDecoder functions by somehow parameterizing them ... though that's a battle for another time!)

Guidance much sought :-) !

Upvotes: 1

Views: 179

Answers (1)

Chad Gilbert
Chad Gilbert

Reputation: 36375

The javascript value in target.style is of type CSSStyleDeclaration, which is mostly made up of fields whose values are strings, but also contains some fields that are not strings. For example length is a number and setProperty is a function.

Your decoder assumes that all values are strings, which they aren't, so it silently fails.

If you only want those values of type string, you can use Json.Decode.maybe Json.Decode.string to find those values that are of type string, then Json.Decode.andThen and List.filterMap to keep only the string values:

styleFormatDecoder =
    Json.Decode.keyValuePairs (Json.Decode.maybe Json.Decode.string)
        |> Json.Decode.map justStringVals

justStringVals : List (String, Maybe String) -> List (String, String)
justStringVals =
    List.filterMap (\(key, maybeVal) ->
        case maybeVal of
            Just val -> Just (key, val)
            Nothing -> Nothing)

Upvotes: 1

Related Questions