From 188bc7f183eb756c2a43c16eb0b27512cec20bcf Mon Sep 17 00:00:00 2001 From: Christopher Vachon Date: Wed, 2 Nov 2022 21:22:51 -0400 Subject: [PATCH] Add If Confition Method to ClassNames --- README.md | 11 +++++++++++ package.json | 2 +- src/ClassNames.test.ts | 20 ++++++++++++++++++++ src/ClassNames.ts | 26 ++++++++++++++++++++++++++ 4 files changed, 58 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index cfe4f14..f45b3a4 100644 --- a/README.md +++ b/README.md @@ -207,6 +207,17 @@ const list = new ClassNames() // list => "p-1" ``` +## If Condition + +as of `1.2.0` you use add an If Conditions + +```js +const size = "xs"; + +const list = new ClassNames().if(size === "xs", "rounded-sm", "rounded").list(); +// list => "rounded-sm" +``` + ## Static Methods - .add() - Alias of `new ClassNames().add()` diff --git a/package.json b/package.json index 0b01758..d2c98bd 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@codevachon/classnames", - "version": "1.1.0", + "version": "1.2.0", "license": "MIT", "author": { "email": "code@christophervachon.com", diff --git a/src/ClassNames.test.ts b/src/ClassNames.test.ts index c9f05d2..8b7f8d0 100644 --- a/src/ClassNames.test.ts +++ b/src/ClassNames.test.ts @@ -369,6 +369,26 @@ describe("ClassNames", () => { }); }); + describe("if", () => { + const baseClasses = ["Beer", "Banana"]; + const isTrue = "true"; + const isFalse = "false"; + + test("Adds the expected values when condition is true", () => { + const condition = true; + expect(new ClassNames(baseClasses).if(condition, isTrue, isFalse).list()).toContain( + isTrue + ); + }); + + test("Adds the expected values when condition is false", () => { + const condition = false; + expect(new ClassNames(baseClasses).if(condition, isTrue, isFalse).list()).toContain( + isFalse + ); + }); + }); + describe("static isClassNames method", () => { test("returns true if value is an instance of ClassNames", () => { const value = ClassNames.add("me"); diff --git a/src/ClassNames.ts b/src/ClassNames.ts index 41d31a7..2160a8c 100644 --- a/src/ClassNames.ts +++ b/src/ClassNames.ts @@ -299,6 +299,32 @@ class ClassNames { return this; } + /** + * Conditionally Added Classes + * + * ```ts + * new ClassNames().if(disabled === true, "bg-gray-100", "bg-sky-700").list(); + * ``` + * + * @param condition The If Condition + * @param isTrue Values to add if the Condition is True + * @param isFalse Values to add of the Condition is False + * @returns this instance + */ + public if( + condition: boolean, + isTrue: ClassNameAddValue, + isFalse: ClassNameAddValue = "" + ): this { + if (condition) { + this.add(isTrue); + } else { + this.add(isFalse); + } + + return this; + } + /** * Static accessor to add ClassNames *