ha-nunjucks 1.3.0-beta.21 → 1.3.0-beta.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -7,7 +7,7 @@
7
7
 
8
8
  [![Github][github]][github]
9
9
 
10
- A simple wrapper for [nunjucks](https://www.npmjs.com/package/nunjucks) for use with Home Assistant frontend custom components to render [templates](https://www.home-assistant.io/docs/configuration/templating/) instanteneously at HTML render time. This repository offers an easy way for developers to add templating support to Home Assistant custom cards.
10
+ A wrapper for [nunjucks](https://www.npmjs.com/package/nunjucks) for use with Home Assistant frontend custom components to render [templates](https://www.home-assistant.io/docs/configuration/templating/) instanteneously at HTML render time. This repository offers an easy way for developers to add templating support to Home Assistant custom cards.
11
11
 
12
12
  ## What is nunjucks?
13
13
 
@@ -58,15 +58,13 @@ When the return type is expected to be a number, end users should cast these val
58
58
 
59
59
  ## Available Extensions
60
60
 
61
- The catch to this approach of rendering jinja2/nunjucks templates is that we have to reimplement all of the [Home Assistant template extension](https://www.home-assistant.io/docs/configuration/templating/#home-assistant-template-extensions) functions. If there are functions that you use that are not currently supported, please make a feature request or try adding it to the project yourself and create a pull request.
61
+ The vast majority of the [Home Assistant template extensions](https://www.home-assistant.io/docs/configuration/templating/#home-assistant-template-extensions) have been implemented into this package. If there are functions that you use that are not currently supported or don't behave exactly like their jinja2 versions, please make a feature request or try adding it to the project yourself and create a pull request.
62
62
 
63
- So far a subset of the Home Assistant template extension functions have been implemented as documented below.
63
+ Template extensions can be functions, tests, filters, or constants. Functions are called inline like a regular programming function, such as `states()` or `floors()`. Filters are added to the end of a string using a pipe (`|`) character. Many filters are also available as functions. Tests are functions which return booleans and can be used in an if statement like `if foo has_value`. Contants are static values, and are just called as is like `{{ True }}` or `{{ pi }}`.
64
64
 
65
- **NOTE**: The following implemented functions cannot be used as filters.
65
+ ### Python Constants
66
66
 
67
- ### Variables
68
-
69
- These variables just remap Python built-in constants to JavaScript ones.
67
+ These just remap Python built-in constants to JavaScript ones.
70
68
 
71
69
  | Python | JavaScript |
72
70
  | ------ | ---------- |
@@ -78,95 +76,95 @@ These variables just remap Python built-in constants to JavaScript ones.
78
76
 
79
77
  The frontend data `hass` object has been exposed to users to call upon.
80
78
 
81
- Because entity IDs contain periods in them, it's better to access it using bracket notation like so:
79
+ Because entity IDs contain periods in them, you cannot use dot notation when accessing an entity's state object using it. You have to use bracket notation like so:
82
80
 
83
- `{{ hass["states"]["light.sunroom_ceiling"]["state"] }}`
81
+ `{{ hass.states["light.sunroom_ceiling"].state }}`
84
82
 
85
- You can also use dot notation for everything but the entity ID.
83
+ For convenience, the `hass states` object is rebuilt as a separate object that can be accessed with dot notation. Because of JavaScript limitations, it's name has been changed to `_states`.
86
84
 
87
- `{{ hass.states["light.sunroom_ceiling"].state }}`
85
+ `{{ _states.light.sunroom_ceiling.state }}`
88
86
 
89
87
  ### [States](https://www.home-assistant.io/docs/configuration/templating/#states)
90
88
 
91
89
  Functions used to determine an entity's state or an attribute.
92
90
 
93
- | Name | Arguments | Description |
94
- | ------------- | --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
95
- | states | entity_id, rounded (optional), with_unit (optional) | Returns the state string of the given entity. Optionally round numerical states and append the unit of measurement. |
96
- | is_state | entity_id, value | Compares an entity's state with a specified state or list of states and returns `true` or `false`. |
97
- | state_attr | entity_id, attribute | Returns the value of the attribute or `undefined` if it doesn't exist. |
98
- | is_state_attr | entity_id, attribute, value | Tests if the given entity attribute is the specified value. |
99
- | has_value | entity_id | Tests if the given entity is not unknown or unavailable. |
91
+ | Name | Type | Arguments | Description |
92
+ | ------------- | ---------------------- | --------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
93
+ | states | function | entity_id, rounded (optional), with_unit (optional) | Returns the state string of the given entity. Optionally round numerical states and append the unit of measurement. |
94
+ | is_state | function, test | entity_id, value | Compares an entity's state with a specified state or list of states and returns `true` or `false`. |
95
+ | state_attr | function | entity_id, attribute | Returns the value of the attribute or `undefined` if it doesn't exist. |
96
+ | is_state_attr | function, test | entity_id, attribute, value | Tests if the given entity attribute is the specified value. |
97
+ | has_value | function, filter, test | entity_id | Tests if the given entity is not unknown or unavailable. |
100
98
 
101
99
  ### [State Translated](https://www.home-assistant.io/docs/configuration/templating/#state-translated)
102
100
 
103
- | Name | Arguments | Description |
104
- | --------------------- | ----------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
105
- | state_translated | entity_id, state (optional) | Returns the formatted and translated state of an entity or provided state using a language that is currently configured in the general settings. |
106
- | attr_name_translated | entity_id, attr_name (optional) attr_value (optional) | Returns the formatted and translated attribute name of an entity or provided attribute name using a language that is currently configured in the general settings. |
107
- | attr_value_translated | entity_id, attr_name (optional) attr_value (optional) | Returns the formatted and translated attribute value of an entity or provided attribute value using a language that is currently configured in the general settings. |
101
+ | Name | Type | Arguments | Description |
102
+ | --------------------- | -------- | ----------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
103
+ | state_translated | function | entity_id, state (optional) | Returns the formatted and translated state of an entity or provided state using a language that is currently configured in the general settings. |
104
+ | attr_name_translated | function | entity_id, attr_name (optional) attr_value (optional) | Returns the formatted and translated attribute name of an entity or provided attribute name using a language that is currently configured in the general settings. |
105
+ | attr_value_translated | function | entity_id, attr_name (optional) attr_value (optional) | Returns the formatted and translated attribute value of an entity or provided attribute value using a language that is currently configured in the general settings. |
108
106
 
109
107
  ### [Groups](https://www.home-assistant.io/docs/configuration/templating/#working-with-groups)
110
108
 
111
- | Name | Arguments | Description |
112
- | ------ | --------- | ------------------------------------------------------------------------------------------------- |
113
- | expand | args | Retrieve state objects for provided entities and sort. Expands group entities into their members. |
109
+ | Name | Type | Arguments | Description |
110
+ | ------ | ---------------- | --------- | ------------------------------------------------------------------------------------------------- |
111
+ | expand | function, filter | args | Retrieve state objects for provided entities and sort. Expands group entities into their members. |
114
112
 
115
113
  ### [Entities](https://www.home-assistant.io/docs/configuration/templating/#entities)
116
114
 
117
- | Name | Arguments | Description |
118
- | ---------------- | --------- | ------------------------------------------ |
119
- | is_hidden_entity | entity_id | Returns whether an entity has been hidden. |
115
+ | Name | Type | Arguments | Description |
116
+ | ---------------- | -------------- | --------- | ------------------------------------------ |
117
+ | is_hidden_entity | function, test | entity_id | Returns whether an entity has been hidden. |
120
118
 
121
119
  ### [Devices](https://www.home-assistant.io/docs/configuration/templating/#devices)
122
120
 
123
- | Name | Arguments | Description |
124
- | --------------- | ------------------------------------------ | -------------------------------------------------------------------------------------------- |
125
- | device_entities | device_id | Returns a list of entities that are associated with a given device ID. |
126
- | device_attr | device_or_entity_id, attr_name | Returns the value of attr_name for the given device or entity ID. |
127
- | is_device_attr | device_or_entity_id, attr_name, attr_value | Returns whether the value of attr_name for the given device or entity ID matches attr_value. |
128
- | device_id | entity_id | Returns the device ID for a given entity ID or device name. |
121
+ | Name | Type | Arguments | Description |
122
+ | --------------- | ---------------- | ------------------------------------------ | -------------------------------------------------------------------------------------------- |
123
+ | device_entities | function, filter | device_id | Returns a list of entities that are associated with a given device ID. |
124
+ | device_attr | function, filter | device_or_entity_id, attr_name | Returns the value of attr_name for the given device or entity ID. |
125
+ | is_device_attr | function, test | device_or_entity_id, attr_name, attr_value | Returns whether the value of attr_name for the given device or entity ID matches attr_value. |
126
+ | device_id | function, filter | entity_id | Returns the device ID for a given entity ID or device name. |
129
127
 
130
128
  ### [Floors](https://www.home-assistant.io/docs/configuration/templating/#floors)
131
129
 
132
- | Name | Arguments | Description |
133
- | ----------- | ------------ | ----------------------------------------------------------------------------- |
134
- | floors | | Returns the full list of floor IDs that include an area. |
135
- | floor_id | lookup_value | Returns the floor ID for a given device ID, entity ID, area ID, or area name. |
136
- | floor_areas | floor_id | Returns the list of area IDs tied to a given floor ID. |
130
+ | Name | Type | Arguments | Description |
131
+ | ----------- | ---------------- | ------------ | ----------------------------------------------------------------------------- |
132
+ | floors | function | | Returns the full list of floor IDs that include an area. |
133
+ | floor_id | function, filter | lookup_value | Returns the floor ID for a given device ID, entity ID, area ID, or area name. |
134
+ | floor_areas | function, filter | floor_id | Returns the list of area IDs tied to a given floor ID. |
137
135
 
138
136
  ### [Areas](https://www.home-assistant.io/docs/configuration/templating/#areas)
139
137
 
140
- | Name | Arguments | Description |
141
- | ------------- | --------------- | ------------------------------------------------------------------- |
142
- | areas | | Returns the full list of area IDs. |
143
- | area_id | lookup_value | Returns the area ID for a given device ID, entity ID, or area name. |
144
- | area_name | lookup_value | Returns the area name for a given device ID, entity ID, or area ID. |
145
- | area_entities | area_name_or_id | Returns the list of entity IDs tied to a given area ID or name. |
146
- | area_devices | area_name_or_id | Returns the list of device IDs tied to a given area ID or name. |
138
+ | Name | Type | Arguments | Description |
139
+ | ------------- | ---------------- | --------------- | ------------------------------------------------------------------- |
140
+ | areas | function | | Returns the full list of area IDs. |
141
+ | area_id | function, filter | lookup_value | Returns the area ID for a given device ID, entity ID, or area name. |
142
+ | area_name | function, filter | lookup_value | Returns the area name for a given device ID, entity ID, or area ID. |
143
+ | area_entities | function, filter | area_name_or_id | Returns the list of entity IDs tied to a given area ID or name. |
144
+ | area_devices | function, filter | area_name_or_id | Returns the list of device IDs tied to a given area ID or name. |
147
145
 
148
146
  ### [Entities For An Integration](https://www.home-assistant.io/docs/configuration/templating/#entities-for-an-integration)
149
147
 
150
- | Name | Arguments | Description |
151
- | -------------------- | ----------- | ------------------------------------------------------------------------ |
152
- | integration_entities | integration | Returns a list of entities that are associated with a given integration. |
148
+ | Name | Type | Arguments | Description |
149
+ | -------------------- | -------- | ----------- | ------------------------------------------------------------------------ |
150
+ | integration_entities | function | integration | Returns a list of entities that are associated with a given integration. |
153
151
 
154
152
  ### [Labels](https://www.home-assistant.io/docs/configuration/templating/#labels)
155
153
 
156
- | Name | Arguments | Description |
157
- | -------------- | ----------------------- | ------------------------------------------------------------------------------------------ |
158
- | labels | lookup_value (optional) | Returns the full list of label IDs, or those for a given area ID, device ID, or entity ID. |
159
- | label_areas | label_id | Returns the list of area IDs tied to a given label ID. |
160
- | label_devices | label_id | Returns the list of device IDs tied to a given label ID. |
161
- | label_entities | label_id | Returns the list of entity IDs tied to a given label ID. |
154
+ | Name | Type | Arguments | Description |
155
+ | -------------- | ---------------- | ----------------------- | ------------------------------------------------------------------------------------------ |
156
+ | labels | function, filter | lookup_value (optional) | Returns the full list of label IDs, or those for a given area ID, device ID, or entity ID. |
157
+ | label_areas | function, filter | label_id | Returns the list of area IDs tied to a given label ID. |
158
+ | label_devices | function, filter | label_id | Returns the list of device IDs tied to a given label ID. |
159
+ | label_entities | function, filter | label_id | Returns the list of entity IDs tied to a given label ID. |
162
160
 
163
161
  ### [Immediate If](https://www.home-assistant.io/docs/configuration/templating/#immediate-if-iif)
164
162
 
165
163
  A shorthand for an if else statement.
166
164
 
167
- | Name | Arguments | Description |
168
- | ---- | ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
169
- | iif | condition, if_true, if_false, if_none | Immediate if. Returns the value of `if_true` if the condition is true, the value of `if_false` if it's false, and the value of `if_none` if it's `undefined`, `null`, or an empty string. All arguments except `condition` are optional. Cannot be used as a filter. |
165
+ | Name | Type | Arguments | Description |
166
+ | ---- | ---------------- | ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
167
+ | iif | function, filter | condition, if_true, if_false, if_none | Immediate if. Returns the value of `if_true` if the condition is true, the value of `if_false` if it's false, and the value of `if_none` if it's `undefined`, `null`, or an empty string. All arguments except `condition` are optional. Cannot be used as a filter. |
170
168
 
171
169
  ### [Time](https://www.home-assistant.io/docs/configuration/templating/#time)
172
170
 
@@ -175,88 +173,124 @@ A shorthand for an if else statement.
175
173
  - JS Date does not support time precision below 1 millisecond, while Python datetime supports microsecond precision. While some of these functions allow you to input microseconds, any time unit below 1 millisecond will be lost.
176
174
  - JS Date is not as good at handling timezones as Python datetime. Be careful about timezone differences! You can try to account for this using the `utc` flags and/or by including a timezone offset in a datetime string to parse using `as_datetime` or `strptime`.
177
175
 
178
- | Name | Arguments | Description |
179
- | ------------ | --------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
180
- | now | | Returns a datetime object that represents the current time in your time zone. |
181
- | utcnow | | Returns a datetime object of the current time in the UTC timezone. |
182
- | today_at | value | Converts a string containing a military time format to a datetime object with today’s date in your time zone. Defaults to midnight (00:00). |
183
- | as_datetime | value, fallback (optional), utc (default true) | Converts a string containing a timestamp, or valid UNIX timestamp, to a datetime object. If that fails, it returns the fallback value or, if omitted, raises an error. When the input is already a datetime object it will be returned as is. in case the input is a datetime.date object, midnight will be added as time. |
184
- | as_timestamp | value, fallback (optional) | Converts a datetime object or string to UNIX timestamp. If that fails, returns the fallback value, or if omitted raises an error. |
185
- | as_local | value | Converts a datetime object to local time. |
186
- | strptime | value, format, fallback (optional), utc (default false) | Parses a string based on a [format](https://docs.python.org/3.10/library/datetime.html#strftime-and-strptime-behavior) and returns a datetime object. If that fails, it returns the default value or, if omitted, raises an error. |
187
- | time_since | value, precision (default 1) | Returns a human readable string indicating the difference between now and an input past datetime object. `precision` indicates how many units (years, months, days, hours, minutes, seconds) to use, with the last unit being rounded and 0 being the same as 6. If the input datetime is in the past it returns the input. If the input datetime is not a datetime object it returns nothing. |
188
- | time_until | value, precision (default 1) | Returns a human readable string indicating the difference between now and an input future datetime object. `precision` indicates how many units (years, months, days, hours, minutes, seconds) to use, with the last unit being rounded and 0 being the same as 6. If the input datetime is in the future it returns the input. If the input datetime is not a datetime object it returns nothing. |
189
- | timedelta | days (optional), seconds (optional), microseconds (optional), milliseconds (optional), minutes (optional), hours (optional), weeks (optional) | Returns a timedelta object, which represents a duration (an amount of time between two datetimes). It accepts the same arguments as the Python datetime.timedelta function – days, seconds, microseconds, milliseconds, minutes, hours, weeks. JS Date does not support microsecond precision, and precision below 1 millisecond is lost. |
190
- | as_timedelta | value | Converts a string to a timedelta object. Expects data in the format `DD HH:MM:SS.uuuuuu`, `DD HH:MM:SS,uuuuuu`, or as specified by ISO 8601 (e.g. `P4DT1H15M20S` which is equivalent to `4 1:15:20`) or PostgreSQL’s day-time interval format (e.g. `3 days 04:05:06`). |
176
+ | Name | Type | Arguments | Description |
177
+ | ---------------- | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
178
+ | now | function | | Returns a datetime object that represents the current time in your time zone. |
179
+ | utcnow | function | | Returns a datetime object of the current time in the UTC timezone. |
180
+ | today_at | function, filter | value | Converts a string containing a military time format to a datetime object with today’s date in your time zone. Defaults to midnight (00:00). |
181
+ | as_datetime | function, filter | value, fallback (optional), utc (default true) | Converts a string containing a timestamp, or valid UNIX timestamp, to a datetime object. If that fails, it returns the fallback value or, if omitted, raises an error. When the input is already a datetime object it will be returned as is. in case the input is a datetime.date object, midnight will be added as time. |
182
+ | as_timestamp | function, filter | value, fallback (optional) | Converts a datetime object or string to UNIX timestamp. If that fails, returns the fallback value, or if omitted raises an error. |
183
+ | as_local | function, filter | value | Converts a datetime object to local time. |
184
+ | strptime | function | value, format, fallback (optional), utc (default false) | Parses a string based on a [format](https://docs.python.org/3.10/library/datetime.html#strftime-and-strptime-behavior) and returns a datetime object. If that fails, it returns the default value or, if omitted, raises an error. |
185
+ | time_since | function, filter | value, precision (default 1) | Returns a human readable string indicating the difference between now and an input past datetime object. `precision` indicates how many units (years, months, days, hours, minutes, seconds) to use, with the last unit being rounded and 0 being the same as 6. If the input datetime is in the past it returns the input. If the input datetime is not a datetime object it returns nothing. |
186
+ | time_until | function, filter | value, precision (default 1) | Returns a human readable string indicating the difference between now and an input future datetime object. `precision` indicates how many units (years, months, days, hours, minutes, seconds) to use, with the last unit being rounded and 0 being the same as 6. If the input datetime is in the future it returns the input. If the input datetime is not a datetime object it returns nothing. |
187
+ | timedelta | function | days (optional), seconds (optional), microseconds (optional), milliseconds (optional), minutes (optional), hours (optional), weeks (optional) | Returns a timedelta object, which represents a duration (an amount of time between two datetimes). It accepts the same arguments as the Python datetime.timedelta function – days, seconds, microseconds, milliseconds, minutes, hours, weeks. JS Date does not support microsecond precision, and precision below 1 millisecond is lost. |
188
+ | as_timedelta | function, filter | value | Converts a string to a timedelta object. Expects data in the format `DD HH:MM:SS.uuuuuu`, `DD HH:MM:SS,uuuuuu`, or as specified by ISO 8601 (e.g. `P4DT1H15M20S` which is equivalent to `4 1:15:20`) or PostgreSQL’s day-time interval format (e.g. `3 days 04:05:06`). |
189
+ | timestamp_local | filter | value, fallback (optional) | Converts a UNIX timestamp to the ISO format string representation as date/time in your local timezone. If that fails, returns the `fallback` value, or if omitted raises an error. |
190
+ | timestamp_utc | filter | value, fallback (optional) | Converts a UNIX timestamp to the ISO format string representation as date/time in UTC timezone. If that fails, returns the `fallback` value, or if omitted raises an error. |
191
+ | timestamp_custom | filter | value, format, local (default true), fallback (optional) | Converts a UNIX timestamp to its string representation based on a custom format. Uses the local timezone by default. If that fails, returns the `fallback` value, or if omitted raises an error. |
191
192
 
192
193
  ### [To/From JSON](https://www.home-assistant.io/docs/configuration/templating/#tofrom-json)
193
194
 
194
- | Name | Arguments | Description |
195
- | --------- | ------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
196
- | to_json | obj, ensure_ascii, pretty_print, sort_keys | Turn an object into a JSON string. `ensure_ascii` converts unicode characters into escape sequences. `pretty_print` formats the output with new lines and an indent of two spaces. `sort_keys` sorts the keys of the JSON object. |
197
- | from_json | value | Parse a string as JSON. |
198
- | str | value | Return the string representation of the input. |
195
+ | Name | Type | Arguments | Description |
196
+ | --------- | ------ | ------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
197
+ | to_json | filter | obj, ensure_ascii, pretty_print, sort_keys | Turn an object into a JSON string. `ensure_ascii` converts unicode characters into escape sequences. `pretty_print` formats the output with new lines and an indent of two spaces. `sort_keys` sorts the keys of the JSON object. **Consider using the nunjucks `dump` filter instead** |
198
+ | from_json | filter | value | Parse a string as JSON. |
199
199
 
200
200
  ### [Distance](https://www.home-assistant.io/docs/configuration/templating/#distance)
201
201
 
202
- | Name | Arguments | Description |
203
- | -------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
204
- | distance | args | Measures the distance between home, an entity, or coordinates. The unit of measurement (kilometers or miles) depends on the system’s configuration settings. Does not work with groups. |
205
- | closest | args | Finds the closest entity to home, or the first entity or coordinate if multiple provided. Arguments can be entity IDs, domains, entity state objects, coordinate pairs, or arrays. Does not work with groups. |
202
+ | Name | Type | Arguments | Description |
203
+ | -------- | ---------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
204
+ | distance | function | args | Measures the distance between home, an entity, or coordinates. The unit of measurement (kilometers or miles) depends on the system’s configuration settings. Does not work with groups. |
205
+ | closest | function, filter | args | Finds the closest entity to home, or the first entity or coordinate if multiple provided. Arguments can be entity IDs, domains, entity state objects, coordinate pairs, or arrays. Does not work with groups. |
206
206
 
207
207
  ### [Contains](https://www.home-assistant.io/docs/configuration/templating/#contains)
208
208
 
209
- | Name | Arguments | Description |
210
- | -------- | ----------- | ----------------------------------- |
211
- | contains | list, value | Returns if an element is in a list. |
209
+ | Name | Type | Arguments | Description |
210
+ | -------- | ------------ | ----------- | ----------------------------------- |
211
+ | contains | filter, test | list, value | Returns if an element is in a list. |
212
212
 
213
213
  ### [Numeric](https://www.home-assistant.io/docs/configuration/templating/#numeric-functions-and-filters)
214
214
 
215
- | Name | Arguments | Description |
216
- | ---------------- | -------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
217
- | float | value, fallback (optional) | Converts a value to a float. If that fails, it returns the fallback value or, if omitted, raises an error. |
218
- | is_number | value | Returns true if a value can be parsed as a number. |
219
- | int | value, fallback (optional) | Converts a value to an integer. If that fails, it returns the fallback value or, if omitted, raises an error. |
220
- | bool | value, fallback (optional ) | Converts a value to a boolean based on the human readable truthiness of it, case insensitive. Non-zero integers, `true`, `yes`, `on`, `enable`, and `1` return true. 0, `false`, `no`, `off`, `disable` and `0` return false. If the value's human readable truthiness cannot be determined, returns the fallback value or, if omitted, raises an error. |
221
- | log | value, base (default e), fallback (optional) | Returns the logarithm of a value, defaulting to the natural logarithm if no base is provided. If that fails, it returns the fallback value or, if omitted, raises an error. |
222
- | sin | value, fallback (optional) | Returns the sine of a value. If that fails, it returns the fallback value or, if omitted, raises an error. |
223
- | cos | value, fallback (optional) | Returns the cosine of a value. If that fails, it returns the fallback value or, if omitted, raises an error. |
224
- | tan | value, fallback (optional) | Returns the tangent of a value. If that fails, it returns the fallback value or, if omitted, raises an error. |
225
- | asin | value, fallback (optional) | Returns the arcus sine of a value. If that fails, it returns the fallback value or, if omitted, raises an error. |
226
- | acos | value, fallback (optional) | Returns the arcus cosine of a value. If that fails, it returns the fallback value or, if omitted, raises an error. |
227
- | atan | value, fallback (optional) | Returns the arcus tangent of a value. If that fails, it returns the fallback value or, if omitted, raises an error. |
228
- | atan2 | y, x, fallback (optional) | Returns the four quadrant arcus tangent of y / x. If that fails, it returns the fallback value or, if omitted, raises an error. |
229
- | sqrt | value, fallback (optional) | Returns the square root of a value. If that fails, it returns the fallback value or, if omitted, raises an error. |
230
- | max | args | Returns the largest argument provided, flattening any arrays. |
231
- | min | args | Returns the smallest argument provided, flattening any arrays. |
232
- | average | values, fallback(optional) | Returns the average of an array, flattening any subarrays. If a non-numeric value is detected or the array is empty, it returns the fallback value or, if omitted, raises an error. |
233
- | median | values, fallback(optional) | Returns the median of an array, flattening any subarrays. If a non-numeric value is detected or the array is empty, it returns the fallback value or, if omitted, raises an error. |
234
- | statistical_mode | values, fallback(optional) | Returns the mode of an array, flattening any subarrays. If a non-numeric value is detected or the array is empty, it returns the fallback value or, if omitted, raises an error. |
235
- | e | | Mathematical constant Euler's number. |
236
- | pi | | Mathematical constant pi. |
237
- | tau | | Mathematical constant tau. |
238
- | inf | | Mathematical conceptual value infinity. |
215
+ | Name | Type | Arguments | Description |
216
+ | ---------------- | ---------------- | --------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
217
+ | float | function, filter | value, fallback (optional) | Converts a value to a float. If that fails, it returns the fallback value or, if omitted, raises an error. |
218
+ | is_number | function, filter | value | Returns true if a value can be parsed as a number. |
219
+ | int | function, filter | value, fallback (optional) | Converts a value to an integer. If that fails, it returns the fallback value or, if omitted, raises an error. |
220
+ | bool | function, filter | value, fallback (optional ) | Converts a value to a boolean based on the human readable truthiness of it, case insensitive. Non-zero integers, `true`, `yes`, `on`, `enable`, and `1` return true. 0, `false`, `no`, `off`, `disable` and `0` return false. If the value's human readable truthiness cannot be determined, returns the fallback value or, if omitted, raises an error. |
221
+ | log | function, filter | value, base (default e), fallback (optional) | Returns the logarithm of a value, defaulting to the natural logarithm if no base is provided. If that fails, it returns the fallback value or, if omitted, raises an error. |
222
+ | sin | function, filter | value, fallback (optional) | Returns the sine of a value. If that fails, it returns the fallback value or, if omitted, raises an error. |
223
+ | cos | function, filter | value, fallback (optional) | Returns the cosine of a value. If that fails, it returns the fallback value or, if omitted, raises an error. |
224
+ | tan | function, filter | value, fallback (optional) | Returns the tangent of a value. If that fails, it returns the fallback value or, if omitted, raises an error. |
225
+ | asin | function, filter | value, fallback (optional) | Returns the arcus sine of a value. If that fails, it returns the fallback value or, if omitted, raises an error. |
226
+ | acos | function, filter | value, fallback (optional) | Returns the arcus cosine of a value. If that fails, it returns the fallback value or, if omitted, raises an error. |
227
+ | atan | function, filter | value, fallback (optional) | Returns the arcus tangent of a value. If that fails, it returns the fallback value or, if omitted, raises an error. |
228
+ | atan2 | function, filter | y, x, fallback (optional) | Returns the four quadrant arcus tangent of y / x. If that fails, it returns the fallback value or, if omitted, raises an error. |
229
+ | sqrt | function, filter | value, fallback (optional) | Returns the square root of a value. If that fails, it returns the fallback value or, if omitted, raises an error. |
230
+ | max | function, filter | args | Returns the largest argument provided, flattening any arrays. |
231
+ | min | function, filter | args | Returns the smallest argument provided, flattening any arrays. |
232
+ | average | function, filter | values, fallback (optional) | Returns the average of an array, flattening any subarrays. If a non-numeric value is detected or the array is empty, it returns the fallback value or, if omitted, raises an error. |
233
+ | median | function, filter | values, fallback (optional) | Returns the median of an array, flattening any subarrays. If a non-numeric value is detected or the array is empty, it returns the fallback value or, if omitted, raises an error. |
234
+ | statistical_mode | function, filter | values, fallback (optional) | Returns the mode of an array, flattening any subarrays. If a non-numeric value is detected or the array is empty, it returns the fallback value or, if omitted, raises an error. |
235
+ | e | constant | | Mathematical constant Euler's number. |
236
+ | pi | constant | | Mathematical constant pi. |
237
+ | tau | constant | | Mathematical constant tau. |
238
+ | inf | constant | | Mathematical conceptual value infinity. |
239
+ | round | filter | value, precision, method, fallback (optional) | Converts the input to a number and rounds it to `precision` decimals. It has four modes - `even`, `floor`, `ceil`, and `half`. If the input value is not a number, it returns the fallback value, or, if omitted, raises an error. |
240
+ | bitwise_and | filter | value_one, value_two | Performs a bitwise and(&) operation with two values. |
241
+ | bitwise_or | filter | value_one, value_two | Performs a bitwise or(\|) operation with two values. |
242
+ | bitwise_xor | filter | value_one, value_two | Performs a bitwise xor(^) operation with two values. |
243
+ | ord | filter | value | Returns an integer representing a character's (string of length one) Unicode code point when the argument is a Unicode object, or the value of the byte when the argument is an 8-bit string. |
244
+ | multiply | filter | value, arg | Converts the input to a number and multiplies it by the argument. |
245
+ | add | filter | value, arg | Converts the input to a number and adds it to the argument. |
239
246
 
240
247
  ### [Type Conversions](https://www.home-assistant.io/docs/configuration/templating/#type-conversions)
241
248
 
242
- | Name | Arguments | Description |
243
- | ---- | --------- | ---------------------------------------------------------- |
244
- | set | args | Convert a list/array to a set. Removes duplicates. |
245
- | list | args | Convert a set to a list/array. Does not remove duplicates. |
249
+ | Name | Type | Arguments | Description |
250
+ | ---- | -------- | --------- | ------------------------------------------------------ |
251
+ | set | function | args | Convert a list/array to a set. Removes duplicates. |
252
+ | list | function | args | Convert a set to an array. Does not remove duplicates. |
246
253
 
247
254
  ### [Iterating Multiple Objects](https://www.home-assistant.io/docs/configuration/templating/#iterating-multiple-objects)
248
255
 
249
- | Name | Arguments | Description |
250
- | ---- | --------- | ---------------------------------------------------------------------------------------------------------------------------------- |
251
- | zip | args | Use to iterate over multiple collections in one operation. If given one array will perform the opposite action and unzip the list. |
256
+ | Name | Type | Arguments | Description |
257
+ | ---- | -------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------- |
258
+ | zip | function | args | Use to iterate over multiple collections in one operation. If given one array will perform the opposite action and unzip the list. |
259
+
260
+ ### [Functions and Filters to Process Raw Data](https://www.home-assistant.io/docs/configuration/templating/#functions-and-filters-to-process-raw-data)
261
+
262
+ | Name | Type | Arguments | Description |
263
+ | ------ | ---------------- | --------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
264
+ | pack | filter | value, format | Converts a native type to a bytes type object. Returns nothing on error. |
265
+ | unpack | function, filter | value, format, offset (default 0) | Converts a bytes object into a native type. The offset parameter determines the offset position in bytes from the start of the input bytes based buffer. Returns nothing on error. Only returns the first bytes object. |
266
+
267
+ ### [Strings] (https://www.home-assistant.io/docs/configuration/templating/#string-filters)
268
+
269
+ | Name | Type | Arguments | Description |
270
+ | ------------- | ------ | --------------------------------- | -------------------------------------------------------------------------------------- |
271
+ | urlencode | filter | value | Converts an object to a percent-encoded ASCII text string. |
272
+ | slugify | filter | value, separator ( default -) | Converts a given string into a "slug". |
273
+ | ordinal | filter | value | Converts an integer into a number defining a position in a series. |
274
+ | base64_decode | filter | value, encoding (default 'utf-8') | Decodes a base 64 string to a string. Encoding can be `utf-8`, `ascii`, or `raw/None`. |
275
+
276
+ ### [Regular Expressions] (https://www.home-assistant.io/docs/configuration/templating/#regular-expressions)
277
+
278
+ | Name | Type | Arguments | Description |
279
+ | ------------------- | ------ | -------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------- |
280
+ | match | test | value, find, ignorecase (default false) | Matches the find expression at the beginning of the string using regex. |
281
+ | search | test | value, find, ignorecase (default false) | Matches the find expression anywhere in the string using regex. |
282
+ | regex_replace | filter | value, find (default ''), replace (default ''), ignorecase (default false) | Replaces the find expression with the replace expression string using RegEx. |
283
+ | regex_findall | filter | value, find (default ''), ignorecase (default false) | Finds all RegEx matches of the find expression in value and returns an array of matches. |
284
+ | regex_findall_index | filter | value, find (default ''), index (default 0), ignorecase(default false) | Performs a RegEx find all but returns the match at a provided index. |
252
285
 
253
- ### Other
286
+ ### Miscellaneous
254
287
 
255
288
  Functions that are not from the Home Assistant templating documentation
256
289
 
257
290
  | Name | Arguments | Description |
258
291
  | ----------- | ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
259
292
  | match_media | mediaquery | Returns the boolean result of the provided [CSS media query](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_media_queries/Using_media_queries). |
293
+ | str | value | Return the string representation of the input. |
260
294
 
261
295
  [last-commit-shield]: https://img.shields.io/github/last-commit/Nerwyn/ha-nunjucks?style=for-the-badge
262
296
  [commits]: https://github.com/Nerwyn/ha-nunjucks/commits/main
package/dist/filters.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export declare const HASS_FILTERS: Record<string, CallableFunction>;
2
- export declare const FILTERS: Record<string, CallableFunction>;
1
+ import { Environment } from 'nunjucks';
2
+ export declare function addFilters(env: Environment): Environment;
package/dist/filters.js CHANGED
@@ -12,7 +12,24 @@ import { regex_findall, regex_findall_index, regex_replace, } from './utils/rege
12
12
  import { has_value } from './utils/states';
13
13
  import { base64_decode, ordinal, slugify, urlencode } from './utils/string';
14
14
  import { as_datetime, as_local, as_timestamp, time_since, time_until, timestamp_custom, timestamp_local, timestamp_utc, } from './utils/time';
15
- export const HASS_FILTERS = {
15
+ import { Template } from 'nunjucks';
16
+ export function addFilters(env) {
17
+ for (const func in FILTERS) {
18
+ env.addFilter(func, function (...args) {
19
+ return FILTERS[func](...args);
20
+ });
21
+ }
22
+ for (const func in HASS_FILTERS) {
23
+ env.addFilter(func, function (...args) {
24
+ const hass = JSON.parse(new Template('{{ hass | dump | safe }}').render(
25
+ // @ts-ignore
26
+ this.getVariables()));
27
+ return HASS_FILTERS[func](hass, ...args);
28
+ });
29
+ }
30
+ return env;
31
+ }
32
+ const HASS_FILTERS = {
16
33
  // States
17
34
  has_value,
18
35
  // Groups
@@ -37,7 +54,7 @@ export const HASS_FILTERS = {
37
54
  // Distance
38
55
  closest,
39
56
  };
40
- export const FILTERS = {
57
+ const FILTERS = {
41
58
  // Time
42
59
  as_datetime,
43
60
  as_timestamp,
@@ -0,0 +1,2 @@
1
+ import { Environment } from 'nunjucks';
2
+ export declare function addGlobals(env: Environment): Environment;
@@ -0,0 +1,126 @@
1
+ import { area_devices, area_entities, area_id, area_name, areas, } from './utils/areas';
2
+ import { device_attr, device_entities, device_id, is_device_attr, } from './utils/devices';
3
+ import { closest, distance } from './utils/distance';
4
+ import { is_hidden_entity } from './utils/entities';
5
+ import { floor_areas, floor_id, floors } from './utils/floors';
6
+ import { expand } from './utils/groups';
7
+ import { iif } from './utils/iif';
8
+ import { integration_entities } from './utils/integrations';
9
+ import { label_areas, label_devices, label_entities, labels, } from './utils/labels';
10
+ import { match_media, str } from './utils/miscellaneous';
11
+ import { acos, asin, atan, atan2, average, bool, cos, e, float, inf, int, is_number, log, max, median, min, pi, sin, sqrt, statistical_mode, tan, tau, } from './utils/numeric';
12
+ import { attr_name_translated, attr_value_translated, state_translated, } from './utils/state_translated';
13
+ import { has_value, is_state, is_state_attr, state_attr, states, } from './utils/states';
14
+ import { as_datetime, as_local, as_timedelta, as_timestamp, now, strptime, time_since, time_until, timedelta, today_at, utcnow, } from './utils/time';
15
+ import { list, set } from './utils/type';
16
+ import { zip } from './utils/zip';
17
+ import { Template } from 'nunjucks';
18
+ export function addGlobals(env) {
19
+ for (const func in GLOBALS) {
20
+ env.addGlobal(func, function (...args) {
21
+ return GLOBALS[func](...args);
22
+ });
23
+ }
24
+ for (const func in HASS_GLOBALS) {
25
+ env.addGlobal(func, function (...args) {
26
+ const hass = JSON.parse(new Template('{{ hass | dump | safe }}').render(
27
+ // @ts-ignore
28
+ this.getVariables()));
29
+ return HASS_GLOBALS[func](hass, ...args);
30
+ });
31
+ }
32
+ for (const c in CONST_GLOBALS) {
33
+ env.addGlobal(c, CONST_GLOBALS[c]);
34
+ }
35
+ return env;
36
+ }
37
+ const HASS_GLOBALS = {
38
+ // States
39
+ states,
40
+ is_state,
41
+ state_attr,
42
+ is_state_attr,
43
+ has_value,
44
+ // State Translated
45
+ state_translated,
46
+ attr_name_translated,
47
+ attr_value_translated,
48
+ // Groups
49
+ expand,
50
+ // Entities
51
+ is_hidden_entity,
52
+ // Devices
53
+ device_entities,
54
+ device_attr,
55
+ is_device_attr,
56
+ device_id,
57
+ // Floors
58
+ floors,
59
+ floor_id,
60
+ floor_areas,
61
+ // Areas
62
+ areas,
63
+ area_id,
64
+ area_name,
65
+ area_entities,
66
+ area_devices,
67
+ // Integrations
68
+ integration_entities,
69
+ // Labels
70
+ labels,
71
+ label_areas,
72
+ label_devices,
73
+ label_entities,
74
+ // Immediate If
75
+ iif,
76
+ // Distance
77
+ distance,
78
+ closest,
79
+ };
80
+ const GLOBALS = {
81
+ // Time
82
+ now,
83
+ utcnow,
84
+ today_at,
85
+ as_datetime,
86
+ as_timestamp,
87
+ as_local,
88
+ strptime,
89
+ time_since,
90
+ time_until,
91
+ timedelta,
92
+ as_timedelta,
93
+ // Numeric,
94
+ float,
95
+ is_number,
96
+ int,
97
+ bool,
98
+ log,
99
+ sin,
100
+ cos,
101
+ tan,
102
+ asin,
103
+ acos,
104
+ atan,
105
+ atan2,
106
+ sqrt,
107
+ max,
108
+ min,
109
+ average,
110
+ median,
111
+ statistical_mode,
112
+ // Type Conversions
113
+ set,
114
+ list,
115
+ // Iterating Multiple Objects
116
+ zip,
117
+ // Miscellaneous
118
+ match_media,
119
+ str,
120
+ };
121
+ const CONST_GLOBALS = {
122
+ e,
123
+ pi,
124
+ tau,
125
+ inf,
126
+ };
package/dist/index.js CHANGED
@@ -1,35 +1,10 @@
1
1
  import nunjucks from 'nunjucks';
2
- import { CONTEXT } from './context';
3
- import { FILTERS, HASS_FILTERS } from './filters';
4
- import { HASS_TESTS, TESTS } from './tests';
2
+ import { addFilters } from './filters';
3
+ import { addGlobals } from './globals';
4
+ import { addTests } from './tests';
5
+ import { buildStatesObject } from './utils/states';
5
6
  nunjucks.installJinjaCompat();
6
- const env = new nunjucks.Environment();
7
- for (const f in FILTERS) {
8
- env.addFilter(f, function (...args) {
9
- return FILTERS[f](...args);
10
- });
11
- }
12
- for (const f in HASS_FILTERS) {
13
- env.addFilter(f, function (...args) {
14
- const hass = JSON.parse(decodeURIComponent(new nunjucks.Template('{{ to_json(hass) }}').render(
15
- // @ts-ignore
16
- this.getVariables())));
17
- return HASS_FILTERS[f](hass, ...args);
18
- });
19
- }
20
- for (const t in TESTS) {
21
- env.addTest(t, function (...args) {
22
- return TESTS[t](...args);
23
- });
24
- }
25
- for (const t in HASS_TESTS) {
26
- env.addTest(t, function (...args) {
27
- const hass = JSON.parse(decodeURIComponent(new nunjucks.Template('{{ to_json(hass) }}').render(
28
- // @ts-ignore
29
- this.getVariables())));
30
- return HASS_TESTS[t](hass, ...args);
31
- });
32
- }
7
+ const env = addTests(addFilters(addGlobals(new nunjucks.Environment())));
33
8
  /**
34
9
  * Render a Home Assistant template string using nunjucks
35
10
  * @param {HomeAssistant} hass The Home Assistant object
@@ -43,7 +18,8 @@ export function renderTemplate(hass, str, context) {
43
18
  (str.includes('{%') && str.includes('%}')))) {
44
19
  str = env
45
20
  .renderString(structuredClone(str), {
46
- ...CONTEXT(hass),
21
+ hass,
22
+ _states: buildStatesObject(hass),
47
23
  ...context,
48
24
  })
49
25
  .trim();
package/dist/tests.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export declare const HASS_TESTS: Record<string, CallableFunction>;
2
- export declare const TESTS: Record<string, CallableFunction>;
1
+ import { Environment } from 'nunjucks';
2
+ export declare function addTests(env: Environment): Environment;
package/dist/tests.js CHANGED
@@ -1,3 +1,38 @@
1
- // TODO add tests
2
- export const HASS_TESTS = {};
3
- export const TESTS = {};
1
+ import { Template } from 'nunjucks';
2
+ import { contains } from './utils/contains';
3
+ import { is_device_attr } from './utils/devices';
4
+ import { is_hidden_entity } from './utils/entities';
5
+ import { match, search } from './utils/regexp';
6
+ import { has_value, is_state, is_state_attr } from './utils/states';
7
+ export function addTests(env) {
8
+ for (const t in TESTS) {
9
+ env.addTest(t, function (...args) {
10
+ return TESTS[t](...args);
11
+ });
12
+ }
13
+ for (const t in HASS_TESTS) {
14
+ env.addTest(t, function (...args) {
15
+ const hass = JSON.parse(new Template('{{ hass | dump | safe }}').render(
16
+ // @ts-ignore
17
+ this.getVariables()));
18
+ return HASS_TESTS[t](hass, ...args);
19
+ });
20
+ }
21
+ return env;
22
+ }
23
+ const HASS_TESTS = {
24
+ // States
25
+ is_state,
26
+ is_state_attr,
27
+ has_value,
28
+ // Entities
29
+ is_hidden_entity,
30
+ // Devices
31
+ is_device_attr,
32
+ // Contains
33
+ contains,
34
+ // Regular Expressions
35
+ match,
36
+ search,
37
+ };
38
+ const TESTS = {};
@@ -1,4 +1,4 @@
1
1
  import { HomeAssistant } from 'custom-card-helpers';
2
2
  import { HassEntities, HassEntity } from 'home-assistant-js-websocket';
3
- export declare function distance(hass: HomeAssistant, ...args: (string | number)[]): number | null | undefined;
3
+ export declare function distance(hass: HomeAssistant, ...args: (string | HassEntity | number)[]): number | null | undefined;
4
4
  export declare function closest(hass: HomeAssistant, ...args: (string | string[] | HassEntity | HassEntities)[]): HassEntity | null;
@@ -91,6 +91,11 @@ export function distance(hass, ...args) {
91
91
  lon1 = hass.states[args[0]].attributes.longitude;
92
92
  i = 1;
93
93
  }
94
+ else if (typeof args[0] == 'object' && !Array.isArray(args[0])) {
95
+ lat1 = args[0].attributes.latitude;
96
+ lon1 = args[0].attributes.longitude;
97
+ i = 1;
98
+ }
94
99
  else if (typeof args[0] == 'number') {
95
100
  if (!(typeof args[1] == 'number')) {
96
101
  throw Error('Latitude provided but not longitude 1');
@@ -106,6 +111,10 @@ export function distance(hass, ...args) {
106
111
  lat2 = hass.states[args[i]].attributes.latitude;
107
112
  lon2 = hass.states[args[i]].attributes.longitude;
108
113
  }
114
+ else if (typeof args[0] == 'object' && !Array.isArray(args[0])) {
115
+ lat2 = args[i].attributes.latitude;
116
+ lon2 = args[i].attributes.longitude;
117
+ }
109
118
  else if (typeof args[i] == 'number') {
110
119
  if (!(typeof args[i + 1] == 'number')) {
111
120
  throw Error('Latitude provided but not longitude 2');
@@ -158,10 +167,10 @@ export function closest(hass, ...args) {
158
167
  start = 2;
159
168
  }
160
169
  else if (typeof args[0] == 'object') {
161
- if (Array.isArray(args[0])) {
170
+ if (Array.isArray(args[0]) || !args[0].attributes) {
162
171
  return null;
163
172
  }
164
- // Assume is stateobj
173
+ // Is state object
165
174
  home = [
166
175
  args[0].attributes.latitude,
167
176
  args[0].attributes.longitude,
@@ -194,7 +203,15 @@ export function closest(hass, ...args) {
194
203
  }
195
204
  }
196
205
  else {
197
- entityIds0 = Object.keys(args[i]);
206
+ const entities = Object.keys(args[i]);
207
+ if (args[i][entities[0]].entity_id) {
208
+ entityIds0 = entities.map((key) => args[i][key].entity_id);
209
+ }
210
+ else {
211
+ for (const domain of entities) {
212
+ entityIds0.push(...Object.keys(args[i][domain]).map((key) => args[i][domain][key].entity_id));
213
+ }
214
+ }
198
215
  }
199
216
  for (const entity of entityIds0) {
200
217
  entityIds.push(...getEntityIdsByString(entity));
@@ -1,3 +1,3 @@
1
1
  import { HomeAssistant } from 'custom-card-helpers';
2
- import { HassEntity } from 'home-assistant-js-websocket';
3
- export declare function expand(hass: HomeAssistant, ...args: (string | HassEntity)[]): HassEntity[];
2
+ import { HassEntities, HassEntity } from 'home-assistant-js-websocket';
3
+ export declare function expand(hass: HomeAssistant, ...args: (string | HassEntity | HassEntities)[]): HassEntity[];
@@ -8,13 +8,37 @@ export function expand(hass, ...args) {
8
8
  if (Array.isArray(entity.attributes?.entity_id)) {
9
9
  res.push(...expand(hass, ...entity.attributes?.entity_id));
10
10
  }
11
- else if (entity.attributes?.persons) {
12
- res.push(...expand(hass, ...entity.attributes?.persons));
11
+ else if (entity?.attributes?.persons) {
12
+ res.push(...expand(hass, ...entity.attributes.persons));
13
13
  }
14
14
  else {
15
- res.push(entity);
15
+ if (entity.entity_id) {
16
+ res.push(entity);
17
+ }
18
+ else {
19
+ const entities = Object.values(entity);
20
+ if (entities[0]?.entity_id) {
21
+ res.push(...entities);
22
+ }
23
+ else {
24
+ for (const domain of entities) {
25
+ const stateObjects = Object.values(domain);
26
+ for (const stateObj of stateObjects) {
27
+ if (stateObj?.attributes?.persons) {
28
+ res.push(...expand(hass, ...stateObj.attributes.persons));
29
+ }
30
+ else {
31
+ res.push(stateObj);
32
+ }
33
+ }
34
+ }
35
+ }
36
+ }
16
37
  }
17
38
  }
18
39
  }
19
- return Array.from(new Set(res)).sort((a, b) => a.entity_id.localeCompare(b.entity_id));
40
+ return res
41
+ .filter((value, index, self) => index ==
42
+ self.findIndex((obj) => obj.entity_id == value.entity_id))
43
+ .sort((a, b) => a.entity_id.localeCompare(b.entity_id));
20
44
  }
@@ -1,3 +1,2 @@
1
1
  export declare function to_json(obj: object, ensure_ascii?: boolean | Record<string, boolean>, pretty_print?: boolean, sort_keys?: boolean): string;
2
2
  export declare function from_json(value: string): any;
3
- export declare function str(value: string): string;
@@ -1,8 +1,8 @@
1
- export function to_json(obj, ensure_ascii = true, pretty_print = false, sort_keys = false) {
1
+ export function to_json(obj, ensure_ascii = false, pretty_print = false, sort_keys = false) {
2
2
  if (typeof ensure_ascii == 'object' && !Array.isArray(ensure_ascii)) {
3
3
  sort_keys = ensure_ascii.sort_keys ?? sort_keys;
4
4
  pretty_print = ensure_ascii.pretty_print ?? pretty_print;
5
- ensure_ascii = ensure_ascii.ensure_ascii ?? ensure_ascii;
5
+ ensure_ascii = ensure_ascii.ensure_ascii ?? false;
6
6
  }
7
7
  if (sort_keys) {
8
8
  obj = Object.keys(obj)
@@ -21,6 +21,3 @@ export function to_json(obj, ensure_ascii = true, pretty_print = false, sort_key
21
21
  export function from_json(value) {
22
22
  return JSON.parse(value);
23
23
  }
24
- export function str(value) {
25
- return value.toString();
26
- }
@@ -0,0 +1,2 @@
1
+ export declare function match_media(mediaquery: string): boolean;
2
+ export declare function str(value: string): string;
@@ -0,0 +1,6 @@
1
+ export function match_media(mediaquery) {
2
+ return window.matchMedia(mediaquery).matches;
3
+ }
4
+ export function str(value) {
5
+ return value.toString();
6
+ }
@@ -1,6 +1,8 @@
1
1
  import { HomeAssistant } from 'custom-card-helpers';
2
+ import { HassEntity } from 'home-assistant-js-websocket';
2
3
  export declare function states(hass: HomeAssistant, entity_id: string, rounded?: boolean | Record<string, boolean>, with_unit?: boolean): string | undefined;
3
4
  export declare function is_state(hass: HomeAssistant, entity_id: string, value: string | string[]): boolean;
4
5
  export declare function state_attr(hass: HomeAssistant, entity_id: string, attribute: string): any;
5
6
  export declare function is_state_attr(hass: HomeAssistant, entity_id: string, attribute: string, value: string | string[]): boolean;
6
7
  export declare function has_value(hass: HomeAssistant, entity_id: string): boolean;
8
+ export declare function buildStatesObject(hass: HomeAssistant): Record<string, Record<string, HassEntity>>;
@@ -6,7 +6,6 @@ export function states(hass, entity_id, rounded, with_unit) {
6
6
  try {
7
7
  const stateObj = hass.states[entity_id];
8
8
  let state = stateObj?.state;
9
- // https://www.home-assistant.io/docs/configuration/templating/#formatting-sensor-states
10
9
  if (with_unit && rounded == undefined) {
11
10
  rounded = true;
12
11
  }
@@ -74,3 +73,12 @@ export function has_value(hass, entity_id) {
74
73
  return false;
75
74
  }
76
75
  }
76
+ export function buildStatesObject(hass) {
77
+ const states = {};
78
+ for (const entityId in hass.states) {
79
+ const [domain, entity] = entityId.split('.');
80
+ states[domain] = states[domain] ?? {};
81
+ states[domain][entity] = hass.states[entityId];
82
+ }
83
+ return states;
84
+ }
@@ -0,0 +1,2 @@
1
+ export declare function set(...args: string[]): Set<string>;
2
+ export declare function list(...args: string[][]): FlatArray<string[], 0 | 1 | 2 | 16 | 4 | 3 | -1 | 6 | 5 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 17 | 18 | 19 | 20>[];
@@ -0,0 +1,7 @@
1
+ // TODO - validate and possibly add https://www.home-assistant.io/docs/configuration/templating/#complex-type-checking
2
+ export function set(...args) {
3
+ return new Set(args.flat(Infinity));
4
+ }
5
+ export function list(...args) {
6
+ return args.map((arg) => Array.from(arg)).flat(Infinity);
7
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ha-nunjucks",
3
- "version": "1.3.0-beta.21",
3
+ "version": "1.3.0-beta.23",
4
4
  "description": "Wrapper for nunjucks for use with Home Assistant frontend custom components to render templates",
5
5
  "main": "./dist/index.js",
6
6
  "type": "module",