YAMLExceptions on multiline JavaScript - using button-card

So I decided I wanted my sensors to go Orange if they had seen motion within the last 10 mins. Red if now and Green otherwise. Using button-card.

If I put multi-line JavaScript under the color attribute of an icon (e.g. for the on State in a button-card template) I get “YAMLException: missed comma between flow collection entries” or when I’m fiddling with the code, most of the time “YAMLException: can not read a block mapping entry; a multiline key may not be an implicit key.”


Now this didn’t happen when I only had the one line surrounded by quotes. In fact after I saved and went to have a look it had auto reformatted it like this:

            - color: >-
                [[[var dateTimeNow = Date.now(); var entityLastChanged = new
                Date(entity.last_changed); if (entityLastChanged instanceof
                Date){ var diff = dateTimeNow - entityLastChanged; diff =
                ~~(diff / 60000)} else {diff = -1} if (diff > 10){return
                "green";} else {return "orange"}]]]

I guess I’m wondering why that is necessary?

Ultimately I made a variable (as per below) and did it there and it was perfectly happy with my indentation. Is it the YAML parser being finicky or is it something to do with button-card not fully supporting JS on the color attribute of an icon?

  button_motion:
    template: button_body
    variables:
      motion_colour: |-
        [[[
          var dateTimeNow = Date.now();
          var entityLastChanged = new Date(entity.last_changed);
          if (entityLastChanged instanceof Date){
            var diff = dateTimeNow - entityLastChanged;
            diff = ~~(diff / 60000)
          } else {diff = -1}
          if (diff == -1) {return "purple"}
          else if (diff < 10){return "orange"}
          else {return "green"}
        ]]]]

then further down:

          icon:
            - color: '[[[ return variables.motion_colour ]]]'