From 83a9934c4bda0bfe6ba711b92ddee6a064dfb0e5 Mon Sep 17 00:00:00 2001 From: jorenbroekema Date: Tue, 24 Oct 2023 15:00:48 +0200 Subject: [PATCH] fix: allow falsy token values for outputReferences, e.g. 0 --- .../createPropertyFormatter.test.js | 34 +++++++++++++++++++ .../formatHelpers/createPropertyFormatter.js | 5 ++- 2 files changed, 38 insertions(+), 1 deletion(-) diff --git a/__tests__/common/formatHelpers/createPropertyFormatter.test.js b/__tests__/common/formatHelpers/createPropertyFormatter.test.js index a80e0c264..b3864d266 100644 --- a/__tests__/common/formatHelpers/createPropertyFormatter.test.js +++ b/__tests__/common/formatHelpers/createPropertyFormatter.test.js @@ -114,6 +114,34 @@ const numberDictionary = createDictionary({ value: 10, type: 'dimension' }, + zero: { + original: { + value: 0, + type: 'dimension', + }, + attributes: { + category: 'tokens', + type: 'zero', + }, + name: 'tokens-zero', + path: ['tokens', 'zero'], + value: 0, + type: 'dimension', + }, + 'ref-zero': { + original: { + value: '{tokens.zero}', + type: 'dimension', + }, + attributes: { + category: 'tokens', + type: 'ref-zero', + }, + name: 'tokens-ref-zero', + path: ['tokens', 'ref-zero'], + value: 0, + type: 'dimension', + }, } } }) @@ -229,6 +257,12 @@ describe('common', () => { expect(propFormatter(numberDictionary.tokens.tokens.ref)).toEqual(' --tokens-ref: var(--tokens-foo);'); }) + it('should support valid falsy values for outputReferences', () => { + const propFormatter = createPropertyFormatter({ outputReferences: true, dictionary: numberDictionary, format: 'css' }) + expect(propFormatter(numberDictionary.tokens.tokens.zero)).toEqual(' --tokens-zero: 0;'); + expect(propFormatter(numberDictionary.tokens.tokens['ref-zero'])).toEqual(' --tokens-ref-zero: var(--tokens-zero);'); + }) + it('should support multiple references for outputReferences', () => { const propFormatter = createPropertyFormatter({ outputReferences: true, dictionary: multiDictionary, format: 'css' }) expect(propFormatter(multiDictionary.tokens.tokens.foo)).toEqual(' --tokens-foo: 10px;'); diff --git a/lib/common/formatHelpers/createPropertyFormatter.js b/lib/common/formatHelpers/createPropertyFormatter.js index 2e28ea718..e41eaad94 100644 --- a/lib/common/formatHelpers/createPropertyFormatter.js +++ b/lib/common/formatHelpers/createPropertyFormatter.js @@ -184,7 +184,10 @@ function createPropertyFormatter({ // because Style Dictionary resolved this in the resolution step. // Here we are undoing that by replacing the value with // the reference's name - if (ref.value && ref.name) { + + // Safe way to check if object contains a property. + // below can be replaced with the new safe Object.hasOwn() in evergreen browsers / Node 16.9.0 onwards + if (Object.prototype.hasOwnProperty.call(ref, 'value') && Object.prototype.hasOwnProperty.call(ref, 'name')) { const replaceFunc = function() { if (format === 'css') { if (outputReferenceFallbacks) {