ui: style-map helper (#12203)

This commit is contained in:
John Cowen 2022-02-01 16:39:02 +00:00 committed by GitHub
parent bcd841a2ed
commit 23d45f5ef5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 80 additions and 0 deletions

View File

@ -0,0 +1,22 @@
import { helper } from '@ember/component/helper';
/**
* Conditionally maps styles to a string ready for typical DOM
* usage (i.e. semi-colon delimited)
*
* @typedef {([string, (string | undefined), string] | [string, (string | undefined)])} styleInfo
* @param {styleInfo[]} entries - An array of `styleInfo`s to map
* @param {boolean} transform=true - whether to perform the build-time 'helper
* to modifier' transpilation. Note a transpiler needs installing separately.
*/
const styleMap = (entries, transform = true) => {
const str = entries.reduce((prev, [prop, value, unit = '']) => {
if (value == null) {
return prev;
}
return `${prev}${prop}:${value.toString()}${unit};`;
}, '');
return str.length > 0 ? str : undefined;
};
export default helper(styleMap);

View File

@ -0,0 +1,58 @@
# style-map
`{{style-map}}` is used to easily add a list of styles, conditionally, and
have them all formatted nicely to be printed in a DOM `style` attribute.
As well as an entry-like array you can also pass an additional `unit` property
as the 3rd item in the array. This is to make it easier to do mathamatical
calculations for units without having to use `(concat)`.
If any property has a value of `null` or `undefined`, that style property will
not be included in the resulting string.
```hbs preview-template
<figure>
<figcaption>
This div has the correct style added/omitted.
</figcaption>
<div
style={{style-map
(array 'outline' '1px solid red')
(array 'width' '600px')
(array 'height' 100 'px')
(array 'padding' 1 'rem')
(array 'background' null)
}}
>
<code>
style={{style-map
(array 'outline' '1px solid red')
(array 'width' '600px')
(array 'height' 100 'px')
(array 'padding' 1 'rem')
(array 'background' null)
}}
</code>
</div>
</figure>
```
## Positional Arguments
| Argument | Type | Default | Description |
| --- | --- | --- | --- |
| `entries` | `styleInfo[]` | | An array of `styleInfo`s to map |
## Named Arguments
| Argument | Type | Default | Description |
| --- | --- | --- | --- |
| `transform` | `boolean` | true | whether to perform the build-time 'helper to modifier' transpilation |
## Types
| Type | Default | Description |
| --- | --- | --- |
| `styleInfo` | `([string, (string \| undefined), string] \| [string, (string \| undefined)])` | |