From 60c6262026217908d71f5ed1d368ab40de0fcbef Mon Sep 17 00:00:00 2001 From: Erik Arvidsson Date: Wed, 16 Oct 2013 12:33:51 -0400 Subject: [PATCH] Add styleObject filter. The following expression: {width: '10px', backgroundColor: 'red'} | styleObject is transformed to: 'width: 10px; background-color: red' R=rafaelw@chromium.org Review URL: https://codereview.appspot.com/14724043 --- src/polymer-expressions.js | 22 +++++++++++++++ tests/tests.js | 58 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 80 insertions(+) diff --git a/src/polymer-expressions.js b/src/polymer-expressions.js index 1cf52ea..0e692e1 100644 --- a/src/polymer-expressions.js +++ b/src/polymer-expressions.js @@ -397,6 +397,28 @@ }; }; + /** + * Converts a style property name to a css property name. For example: + * "WebkitUserSelect" to "-webkit-user-select" + */ + function convertStylePropertyName(name) { + return String(name).replace(/[A-Z]/g, function(c) { + return '-' + c.toLowerCase(); + }); + } + + PolymerExpressions.filters.styleObject = function() { + return { + toDOM: function(value) { + var parts = []; + for (var key in value) { + parts.push(convertStylePropertyName(key) + ': ' + value[key]); + } + return parts.join('; '); + } + }; + }; + PolymerExpressions.prototype = { prepareBinding: function(pathString, name, node) { if (Path.get(pathString).valid) diff --git a/tests/tests.js b/tests/tests.js index 2dc15a8..33ad11a 100644 --- a/tests/tests.js +++ b/tests/tests.js @@ -187,6 +187,64 @@ suite('PolymerExpressions', function() { assert.strictEqual('bar bot', target.className); }); + test('styleObject', function() { + // IE removes invalid style attribute values so we use xstyle in this test. + + var div = createTestHtml( + ''); + + var model = { + object: { + width: '100px', + backgroundColor: 'blue', + WebkitUserSelect: 'none' + } + }; + recursivelySetTemplateModel(div, model); + Platform.performMicrotaskCheckpoint(); + + var target = div.childNodes[1]; + assert.strictEqual(target.getAttribute('xstyle'), + 'width: 100px; background-color: blue; -webkit-user-select: none'); + + model.object = { + left: '50px', + whiteSpace: 'pre' + }; + Platform.performMicrotaskCheckpoint(); + + assert.strictEqual(target.getAttribute('xstyle'), + 'left: 50px; white-space: pre'); + }); + + test('styleObject2', function() { + // IE removes invalid style attribute values so we use xstyle in this test. + + var div = createTestHtml( + ''); + + var model = { + w: '100px', + bc: 'blue' + }; + recursivelySetTemplateModel(div, model); + Platform.performMicrotaskCheckpoint(); + + var target = div.childNodes[1]; + assert.strictEqual(target.getAttribute('xstyle'), + 'width: 100px; background-color: blue'); + + model.w = 0; + Platform.performMicrotaskCheckpoint(); + + assert.strictEqual(target.getAttribute('xstyle'), + 'width: 0; background-color: blue'); + }); + test('Named Scope Bind', function() { var div = createTestHtml( '