From eac0f5b860951cf3b51fd11d4d65b8f64e9bfb24 Mon Sep 17 00:00:00 2001 From: John Cowen Date: Thu, 27 Jan 2022 11:21:12 +0000 Subject: [PATCH] ui: class-map helper (#12202) {{class-map}} is used to easily add a list of classes, conditionally, and have them all formatted nicely ready to be printed in a DOM class attribute. For ease, as well as using entries, you can also just provide a simple string without the boolean and that class will always be added. --- .../consul-ui/app/helpers/class-map.js | 17 +++++++ .../consul-ui/app/helpers/class-map.mdx | 45 +++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 ui/packages/consul-ui/app/helpers/class-map.js create mode 100644 ui/packages/consul-ui/app/helpers/class-map.mdx diff --git a/ui/packages/consul-ui/app/helpers/class-map.js b/ui/packages/consul-ui/app/helpers/class-map.js new file mode 100644 index 0000000000..c698dd7a63 --- /dev/null +++ b/ui/packages/consul-ui/app/helpers/class-map.js @@ -0,0 +1,17 @@ +import { helper } from '@ember/component/helper'; + +/** + * Conditionally maps classInfos (classes) to a string ready for typical DOM + * usage (i.e. space delimited) + * + * @typedef {([string, boolean] | [string])} classInfo + * @param {(classInfo | string)[]} entries - An array of 'entry-like' arrays of `classInfo`s to map + */ +const classMap = entries => { + const str = entries + .filter(entry => (typeof entry === 'string' ? true : entry[entry.length - 1])) + .map(entry => (typeof entry === 'string' ? entry : entry[0])) + .join(' '); + return str.length > 0 ? str : undefined; +}; +export default helper(classMap); diff --git a/ui/packages/consul-ui/app/helpers/class-map.mdx b/ui/packages/consul-ui/app/helpers/class-map.mdx new file mode 100644 index 0000000000..21db053f8f --- /dev/null +++ b/ui/packages/consul-ui/app/helpers/class-map.mdx @@ -0,0 +1,45 @@ +# class-map + +`{{class-map}}` is used to easily add a list of classes, conditionally, and +have them all formatted nicely ready to be printed in a DOM `class` attribute. + +For ease, as well as using entries, you can also just provide a simple string +without the boolean and that class will always be added. + +```hbs preview-template +
+
+ The correct classes added/omitted +
+
+ + class="{{class-map + (array 'add-this-class' true) + (array 'dont-add-this-class' false) + 'simple-string-class' + }}" + +
+
+``` + +## Positional Arguments + +| Argument | Type | Default | Description | +| --- | --- | --- | --- | +| `entries` | `(classInfo \| string)[]` | | An array of 'entry-like' arrays of `classInfo`s to map | + +## Types + +| Type | Default | Description | +| --- | --- | --- | +| `classInfo` | `([string, boolean] \| [string])` | | +