From eeb71600176fa9b3b204b0631427663ca772afc7 Mon Sep 17 00:00:00 2001 From: Justin Fagnani Date: Tue, 30 Jan 2018 17:04:02 -0800 Subject: [PATCH] Disallow non-templates as interpolations in Polymer.html (#5023) * Disallow non-templates as interpolations in Polymer.html * Adds `Polymer.htmlLiteral` Allows composition of strings into html templates constructed with `Polymer.html`. This is useful for composing values into styles or other places where an html template would not compose. ``` const css = Polymer.htmlLiteral`background: red;` Polymer.html`` ``` * lint fix and update types * Review updates. * update types. * [ci-skip] Add comment about accepting htmlLiteral values. * Update types. * Add a `toString` for output from `Polymer.htmlLiteral` Simpler for debugging --- lib/utils/html-tag.html | 84 +++++++++++++++++++++++++++++++---- test/unit/html-tag.html | 25 +++++++---- types/lib/utils/html-tag.d.ts | 55 ++++++++++++++++++++--- 3 files changed, 142 insertions(+), 22 deletions(-) diff --git a/lib/utils/html-tag.html b/lib/utils/html-tag.html index 6745e2cce4..e6189cde7c 100644 --- a/lib/utils/html-tag.html +++ b/lib/utils/html-tag.html @@ -12,28 +12,68 @@ (function() { 'use strict'; + /** + * Class representing a static string value which can be used to filter + * strings by asseting that they have been created via this class. The + * `value` property returns the string passed to the constructor. + */ + class LiteralString { + constructor(string) { + /** @type {string} */ + this.value = string.toString(); + } + /** + * @return {string} LiteralString string value + */ + toString() { + return this.value; + } + } + + /** + * @param {*} value Object to stringify into HTML + * @return {string} HTML stringified form of `obj` + */ + function literalValue(value) { + if (value instanceof LiteralString) { + return /** @type {!LiteralString} */(value).value; + } else { + throw new Error(`non-literal value passed to Polymer.htmlLiteral: ${value}`); + } + } + /** * @param {*} value Object to stringify into HTML * @return {string} HTML stringified form of `obj` */ function htmlValue(value) { if (value instanceof HTMLTemplateElement) { - return /** @type {!HTMLTemplateElement} */(value).innerHTML; + return /** @type {!HTMLTemplateElement } */(value).innerHTML; + } else if (value instanceof LiteralString) { + return literalValue(value); } else { - return String(value); + throw new Error(`non-template value passed to Polymer.html: ${value}`); } } /** - * A template literal tag that creates an HTML