diff --git a/config/changelog.yaml b/config/changelog.yaml index 2e08b58b759..c06c4d6e5a3 100644 --- a/config/changelog.yaml +++ b/config/changelog.yaml @@ -1,3 +1,9 @@ +unreleased: + + Added: + core: + - Added the new attributes.setIfUnset() method + 2.19.5: date: 2022-11-13 diff --git a/markdown/dev/reference/api/attributes/setifunset/en.md b/markdown/dev/reference/api/attributes/setifunset/en.md new file mode 100644 index 00000000000..54042956b09 --- /dev/null +++ b/markdown/dev/reference/api/attributes/setifunset/en.md @@ -0,0 +1,24 @@ +--- +title: setIfUnset() +--- + +```js +Attributes attributes.setIfUnset(string key, string value) +``` + +Sets the attribute identified by `key` to value `value` but only if it's currently unset (`undefined`). + + + +This will never overwrite any value and thus is a safe way to set attributes + + + +```js +let { Path, paths } = part.shorthand(); + +// This will render as: class="classA" +paths.demo = new Path(); +paths.demo.attributes.set('class', 'classA'); +paths.demo.attributes.setIfUnset('class', 'classB'); +``` diff --git a/packages/core/src/attributes.js b/packages/core/src/attributes.js index dd711eeaefe..9a466b353f5 100644 --- a/packages/core/src/attributes.js +++ b/packages/core/src/attributes.js @@ -19,6 +19,13 @@ Attributes.prototype.set = function (name, value) { return this } +/** Sets an attribute, but only if it's not currently set */ +Attributes.prototype.setIfUnset = function (name, value) { + if (typeof this.list[name] === 'undefined') this.list[name] = [value] + + return this +} + /** Removes an attribute */ Attributes.prototype.remove = function (name) { delete this.list[name] diff --git a/packages/core/tests/attributes.test.js b/packages/core/tests/attributes.test.js index 7d449f41c8c..16860b3fb78 100644 --- a/packages/core/tests/attributes.test.js +++ b/packages/core/tests/attributes.test.js @@ -1,9 +1,25 @@ -let expect = require("chai").expect; -let Point = require("./dist").Point; +const expect = require("chai").expect; +const Point = require("./dist").Point; -function newAttr() { - return new Point(0, 0).attributes; -} +const newAttr = () => new Point(0, 0).attributes; + +const a = newAttr(); +it("Should set an attribute", () => { + a.set('hold', 'me') + expect(a.get("hold")).to.equal('me'); +}); + +it("Should remove an attribute", () => { + a.remove('hold') + expect(a.get("hold")).to.equal(false); +}); + +it("Should only set an unset attribute", () => { + a.setIfUnset('hold', 'me') + expect(a.get("hold")).to.equal('me'); + a.setIfUnset('hold', 'thatDudeOverThere') + expect(a.get("hold")).to.equal('me'); +}); it("Should return false when getting an unset attribute", () => { let a = newAttr();