DEV: Add support for arrays to concatClass (#26777)

It'd be useful in cases like:

```gjs
get flagNames() {
  return this.flags?.map((flag) => flag && `flag-${flag.name}`);
  // w/o this change you'd have to handle it here:
  // return this.flags?.map((flag) => flag && `flag-${flag.name}`).filter(Boolean).join(" ");
}

<template>
  <span class={{concatClass "gadget" this.flagNames}}>
  {{! …or here: }}
  <span class={{concatClass "gadget" (concatClass this.flagNames)}}>
```

(also: replaces ember's `compact()` with `filter(Boolean)`)
This commit is contained in:
Jarek Radosz 2024-04-27 12:02:20 +02:00 committed by GitHub
parent cf11e556cb
commit 505d8b52b8
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 14 additions and 7 deletions

View File

@ -1,5 +1,5 @@
export default function concatClass(...args) {
const classes = args.compact().join(" ");
const classes = args.flat().filter(Boolean).join(" ");
if (classes.length) {
return classes;

View File

@ -2,7 +2,6 @@ import { render } from "@ember/test-helpers";
import { hbs } from "ember-cli-htmlbars";
import { assert, module, test } from "qunit";
import { setupRenderingTest } from "discourse/tests/helpers/component-test";
import { query } from "discourse/tests/helpers/qunit-helpers";
module("Integration | Helper | concat-class", function (hooks) {
setupRenderingTest(hooks);
@ -10,28 +9,28 @@ module("Integration | Helper | concat-class", function (hooks) {
test("One class given", async function () {
await render(hbs`<button class={{concat-class "foo"}} />`);
assert.equal(query("button").className, "foo");
assert.dom("button").hasAttribute("class", "foo");
});
test("Multiple class given", async function () {
this.set("bar", "bar");
await render(hbs`<button class={{concat-class "foo" this.bar}} />`);
assert.equal(query("button").className, "foo bar");
assert.dom("button").hasAttribute("class", "foo bar");
});
test("One undefined class given", async function () {
this.set("bar", null);
await render(hbs`<button class={{concat-class "foo" this.bar}} />`);
assert.equal(query("button").className, "foo");
assert.dom("button").hasAttribute("class", "foo");
});
test("Only undefined class given", async function () {
this.set("bar", null);
await render(hbs`<button class={{concat-class null this.bar}} />`);
assert.notOk(query("button").hasAttribute("class"));
assert.dom("button").doesNotHaveAttribute("class");
});
test("Helpers used", async function () {
@ -39,6 +38,14 @@ module("Integration | Helper | concat-class", function (hooks) {
hbs`<button class={{concat-class (if true "foo") (if true "bar")}} />`
);
assert.equal(query("button").className, "foo bar");
assert.dom("button").hasAttribute("class", "foo bar");
});
test("Arrays", async function () {
await render(
hbs`<button class={{concat-class (array) (array "foo" "bar") (array null)}} />`
);
assert.dom("button").hasAttribute("class", "foo bar");
});
});