From 2c0f8a765ec525a32d2de0bf8a55d4e9ce0de418 Mon Sep 17 00:00:00 2001 From: Philip Peitsch Date: Thu, 17 Apr 2014 19:06:23 +1000 Subject: [PATCH] Escape list prefix, suffix and bullet chars in the CSS rules Various browser cope differently with unescaped characters in a CSS content block, though all browsers agree it is a bad thing. WebKit will throw an error, Chrome & FF will "guess" where the rule ends (and usually get it wrong). This patch does 2 things to fix this: - Consistently use double-quotes to quote strings - Escape backspace and double-quote chars in the CSS-related content The vast amount of testing code is primarily creating a string tokenizer able to parse out the displayed text across Chrome/WebKit + FF. As there is no simple way to get the "rendered text" from a pseudo-element, a lot of code is required to compute this. There are tests included for the hand-rolled tokenizer as well to ensure proper function. No tests have been added for OdfCanvas, as the existing list logic in here is destined (sooner rather than later) to be merged into the newer list CSS translation class. --- webodf/lib/odf/ListStylesToCss.js | 17 +- webodf/lib/odf/OdfCanvas.js | 40 +++- webodf/tests/odf/ListStyleToCssTests.js | 264 +++++++++++++++++++++++- 3 files changed, 301 insertions(+), 20 deletions(-) diff --git a/webodf/lib/odf/ListStylesToCss.js b/webodf/lib/odf/ListStylesToCss.js index 85417a86..8a867e82 100644 --- a/webodf/lib/odf/ListStylesToCss.js +++ b/webodf/lib/odf/ListStylesToCss.js @@ -84,6 +84,15 @@ } } + /** + * Return the supplied value with any backslashes escaped, and double-quotes escaped + * @param {!string} value + * @return {!string} + */ + function escapeCSSString(value) { + return value.replace(/\\/g, "\\\\").replace(/"/g, "\\\""); + } + /** * Gets the CSS content for a numbered list * @param {!Element} node @@ -98,16 +107,16 @@ /**@type{!string}*/ content = ""; if (prefix) { - content += ' "' + prefix + '"'; + content += '"' + escapeCSSString(prefix) + '"'; } if (stylemap.hasOwnProperty(style)) { content += " counter(list, " + stylemap[style] + ")"; } else if (style) { content += ' "' + style + '"'; } else { - content += " ''"; + content += ' ""'; } - return 'content:' + content + ' "' + suffix + '"'; + return 'content:' + content + ' "' + escapeCSSString(suffix) + '"'; } /** @@ -125,7 +134,7 @@ */ function getBulletRule(node) { var bulletChar = node.getAttributeNS(textns, "bullet-char"); - return "content: '" + bulletChar + "'"; + return 'content: "' + escapeCSSString(bulletChar) + '"'; } /** diff --git a/webodf/lib/odf/OdfCanvas.js b/webodf/lib/odf/OdfCanvas.js index 8bb0079e..b9db4220 100644 --- a/webodf/lib/odf/OdfCanvas.js +++ b/webodf/lib/odf/OdfCanvas.js @@ -716,6 +716,30 @@ } } + /** + * COPIED FROM ListStylesToCss - Will be removed when this logic is deduped + * Appends the rule into the stylesheets and logs any errors that occur + * @param {!CSSStyleSheet} styleSheet + * @param {!string} rule + */ + function appendRule(styleSheet, rule) { + try { + styleSheet.insertRule(rule, styleSheet.cssRules.length); + } catch (/**@type{!DOMException}*/e) { + runtime.log("cannot load rule: " + rule + " - " + e); + } + } + + /** + * COPIED FROM ListStylesToCss - Will be removed when this logic is deduped + * Return the supplied value with any backslashes escaped, and double-quotes escaped + * @param {!string} value + * @return {!string} + */ + function escapeCSSString(value) { + return value.replace(/\\/g, "\\\\").replace(/"/g, "\\\""); + } + /** * @param {!Element} node * @return {!string} @@ -735,19 +759,21 @@ }, content; - content = prefix; + if (prefix) { + content = '"' + escapeCSSString(prefix) + '"'; + } if (stylemap.hasOwnProperty(style)) { content += " counter(list, " + stylemap[style] + ")"; } else if (style) { content += "'" + style + "';"; } else { - content += " ''"; + content += ' ""'; } if (suffix) { - content += " '" + suffix + "'"; + content += ' "' + escapeCSSString(suffix) + '"'; } - rule = "content: " + content + ";"; + rule = 'content:' + content + ';'; return rule; } /** @@ -763,7 +789,7 @@ */ function getBulletRule(node) { var bulletChar = node.getAttributeNS(textns, "bullet-char"); - return "content: '" + bulletChar + "';"; + return 'content: "' + escapeCSSString(bulletChar) + '";'; } /** @@ -859,7 +885,7 @@ rule += 'content: counter(' + id + ');'; } rule += 'counter-increment:' + id + ';'; - stylesheet.insertRule('text|list#' + id + ' {counter-reset:' + id + '}', stylesheet.cssRules.length); + appendRule(stylesheet, 'text|list#' + id + ' {counter-reset:' + id + '}'); } rule += '}'; @@ -867,7 +893,7 @@ if (rule) { // Add this stylesheet - stylesheet.insertRule(rule, stylesheet.cssRules.length); + appendRule(stylesheet, rule); } } } diff --git a/webodf/tests/odf/ListStyleToCssTests.js b/webodf/tests/odf/ListStyleToCssTests.js index 395d4a54..09401b00 100644 --- a/webodf/tests/odf/ListStyleToCssTests.js +++ b/webodf/tests/odf/ListStyleToCssTests.js @@ -34,7 +34,8 @@ odf.ListStyleToCssTests = function ListStyleToCssTests(runner) { "use strict"; var t, r = runner, - namespaceMap = odf.Namespaces.namespaceMap; + namespaceMap = odf.Namespaces.namespaceMap, + document = runtime.getWindow().document; /** * @extends {CSSRuleList} Well.... we don't really, but please shut your face closure compiler :) @@ -54,6 +55,7 @@ odf.ListStyleToCssTests = function ListStyleToCssTests(runner) { var cssRules = new MockCSSRuleList(); this.cssRules = cssRules; + /** * @param {!string} rule * @param {!number} index @@ -64,18 +66,24 @@ odf.ListStyleToCssTests = function ListStyleToCssTests(runner) { runtime.log("surprise, not appended!"); } cssRules.length += 1; - cssRules.rules.push(rule); + t.styleSheetImpl.insertRule(rule, t.styleSheetImpl.cssRules.length); + cssRules.rules.push({ + ruleText: rule, + cssRule: t.styleSheetImpl.cssRules[t.styleSheetImpl.cssRules.length - 1] + }); return cssRules.length; }; } this.setUp = function () { t = { - list2css : new odf.ListStyleToCss() + list2css : new odf.ListStyleToCss(), + testArea: core.UnitTest.provideTestAreaDiv() }; }; this.tearDown = function () { t = {}; + core.UnitTest.cleanupTestAreaDiv(); }; /** @@ -85,16 +93,24 @@ odf.ListStyleToCssTests = function ListStyleToCssTests(runner) { */ function applyListStyles(styles, automaticStyles) { var stylesTree, - automaticStylesTree; + automaticStylesTree, + styleElement, + text = ""; stylesTree = core.UnitTest.createXmlDocument('office:styles', styles, namespaceMap).documentElement; automaticStylesTree = core.UnitTest.createXmlDocument('office:automatic-styles', automaticStyles, namespaceMap).documentElement; + styleElement = document.createElement("style"); + odf.Namespaces.forEachPrefix(function(prefix, ns) { + text += "@namespace " + prefix + " url(" + ns + ");\n"; + }); + styleElement.appendChild(document.createTextNode(text)); + t.testArea.appendChild(styleElement); + t.styleSheetImpl = styleElement.sheet; t.styleSheet = new MockCSSStyleSheet(); t.styleTree = new odf.StyleTree(stylesTree, automaticStylesTree).getStyleTree(); t.list2css.applyListStyles(t.styleSheet, t.styleTree); - } function style_list_level_label_alignment_WithNo_fo_margin_left() { @@ -109,15 +125,245 @@ odf.ListStyleToCssTests = function ListStyleToCssTests(runner) { '', ""); r.shouldBe(t, "t.styleSheet.cssRules.length", "3"); - r.shouldBe(t, "t.styleSheet.cssRules.rules[0]", "'text|list[text|style-name=\"lijst\"] > text|list-item{margin-left: 0px;}'"); - r.shouldBe(t, "t.styleSheet.cssRules.rules[1]", "'text|list[text|style-name=\"lijst\"] > text|list-item > text|list{margin-left: 0px;}'"); - r.shouldBe(t, "t.styleSheet.cssRules.rules[2]", "'text|list[text|style-name=\"lijst\"] > text|list-item > *:not(text|list):first-child:before{text-align: left;counter-increment:list;display: inline-block;margin-left: 0px;padding-right: 0.2cm;content: \\'-\\';}'"); + r.shouldBe(t, "t.styleSheet.cssRules.rules[0].ruleText", "'text|list[text|style-name=\"lijst\"] > text|list-item{margin-left: 0px;}'"); + r.shouldBe(t, "t.styleSheet.cssRules.rules[1].ruleText", "'text|list[text|style-name=\"lijst\"] > text|list-item > text|list{margin-left: 0px;}'"); + r.shouldBe(t, "t.styleSheet.cssRules.rules[2].ruleText", "'text|list[text|style-name=\"lijst\"] > text|list-item > *:not(text|list):first-child:before{text-align: left;counter-increment:list;display: inline-block;margin-left: 0px;padding-right: 0.2cm;content: \"-\";}'"); } + /** + * WebKit, Chrome + FF all have radically different ways of joining & quoting CSS content. + * The tests being created depend on a predictable string being parsed out for comparison, hence + * the need for this function. + * + * This function takes a string input, and tokenizes it based on the following rules: + * + * 1. strings (either single or double) + * - both single and double-quoted strings are parsed + * - for easier readability, the new string is surrounded by square brackets (i.e., "ab" => [ab]) to reduce + * quoting confusion + * - any escaped quotes in the string are replaced (e.g., "a\"b\'" => [a"b'] or 'a\'b\"' => [a'b"]) + * + * 2. joining commas (i.e., commas between strings) are removed completely (some browsers separate content parts with commas) + * 3. no whitespace trimming or normalization is performed + * + * @param {!string} content + * @return {!string} Returns a normalized string. String values are surrounded with square brackets. + */ + /*jslint regexp:true*/ + function normalizeCSSContent(content) { + var tokens = [], + isEscaped = false, + regionEndDelim, + isQuote = /["']/, + stringStartIndex, + currentCharIndex, + currentCharacter, + contentSubstring; + + for (stringStartIndex = 0, currentCharIndex = 0; currentCharIndex < content.length; currentCharIndex += 1) { + currentCharacter = content[currentCharIndex]; + + if (regionEndDelim) { + // Inside a region that can only be exited by matching the region end delimiter + if (isEscaped) { + isEscaped = false; + } else if (currentCharacter === "\\") { + isEscaped = true; + } else if(currentCharacter === regionEndDelim) { + if (regionEndDelim === ")") { + // Include the closing bracket in the resulting string + contentSubstring = content.substring(stringStartIndex, currentCharIndex + 1); + } else { + contentSubstring = '[' + content.substring(stringStartIndex, currentCharIndex) + ']'; + // Replace any escaped quotes with unescaped quotes. This allows us to cope with FF always + // escaping any type of quote, whilst Chrome/WebKit only escaping if the quote is the same as + // the delimiter + // Regex matches + // (line start OR backslash followed by char OR non-backslash) + // followed by a backslash followed by a quote + contentSubstring = contentSubstring.replace(/(^|(?:\\.)|[^\\])\\(["'])/g, "$1$2"); + } + tokens.push(contentSubstring); + regionEndDelim = undefined; + // Start next string just after the current region delimiter + stringStartIndex = currentCharIndex + 1; + } + } else if (currentCharacter === "(") { + // Open bracket found, which generally indicates a css function (e.g., counter(...)). Treat everything + // inside as part of this same string and don't split at commas or other things + regionEndDelim = ")"; + // Don't reset the segment start as this is just adding on to the existing string + } else if (currentCharacter === ",") { + // Commas may separate components when not in a string region. Save the current region and start a new one + if (stringStartIndex !== currentCharIndex) { + tokens.push(content.substring(stringStartIndex, currentCharIndex)); + } + // Trim the comma off the start of the next region + stringStartIndex = currentCharIndex + 1; + } else if (isQuote.test(currentCharacter)) { + // Quote character outside a string. Sae the current region and start a new one + if (stringStartIndex !== currentCharIndex) { + tokens.push(content.substring(stringStartIndex, currentCharIndex)); + } + regionEndDelim = currentCharacter; + // Trim the quote from the start of the next string + stringStartIndex = currentCharIndex + 1; + } + } + if (stringStartIndex !== currentCharIndex) { + tokens.push(content.substring(stringStartIndex, currentCharIndex)); + } + return tokens.join(""); + } + /*jslint regexp:false*/ + + /** + * Tests to ensure the CSS content normalization is robust enough to be used for the prefix + * checking below. Because someone has to watch the watchers :) + * @return {undefined} + */ + function verifyCSSContentNormalization() { + var contentTests = [ + { + output: '[a] b [c]', + inputs: ['"a" b "c"', '"a", b, "c"', "'a' b 'c'"] + }, + { + output: '[a] [c]', + inputs: ['"a", "c"', "'a', 'c'"] + }, + { + output: '[a] counter(a, b)', + inputs: ['"a" counter(a, b)', "'a', counter(a, b)"] + }, + { + output: '[a, \'b\'] [c, "d"]', + inputs: ['"a, \'b\'" \'c, "d"\''] + }, + { + output: '[] b []', + inputs: ['"" b ""', '"", b, ""', "'', b, ''"] + }, + { + output: '["]', + inputs: ["'\"'", '"\\""', "'\\\"'"] + }, + { + output: '[\']', + inputs: ['"\'"', "'\\''", '"\\\'"'] + }, + { + output: '[\\\\"]', + inputs: ["'\\\\\"'"] + } + ]; + contentTests.forEach(function(testSetup) { + t.output = testSetup.output; + testSetup.inputs.forEach(function(input) { + t.input = normalizeCSSContent(input); + r.shouldBe(t, "t.input", "t.output"); + }); + }); + } + + /** + * Searches in the present stylesheet rules for a rule intended for the supplied style + * name who's normalized style.content value matches the expected value + * @param {!string} styleName + * @param {!string} normalizedContentValue + * @return {undefined} + */ + function matchContentBlock(styleName, normalizedContentValue) { + var contentFound, + ruleIndex, + rule; + + t.expectedContent = normalizedContentValue; + for (ruleIndex = 0; ruleIndex < t.styleSheet.cssRules.length; ruleIndex += 1) { + rule = t.styleSheet.cssRules.rules[ruleIndex]; + if (rule.cssRule.selectorText.indexOf(styleName) !== -1 && rule.cssRule.style.content) { + contentFound = true; + t.actualContent = normalizeCSSContent(rule.cssRule.style.content); + r.shouldBe(t, "t.actualContent", "t.expectedContent"); + break; + } + } + if (!contentFound) { + r.testFailed("Non-empty CSS content attribute expected in stylesheet"); + } + } + + /** + * @param {!string} attribute + * @param {!string} value + * @param {!string} expectedContentValue + * @return {undefined} + */ + function checkListLevelStyleNumberAttribute(attribute, value, expectedContentValue) { + applyListStyles( + '' + + '' + + '' + + '' + + '' + + '' + + '', + ""); + + matchContentBlock("check_stylenumber_attribute", expectedContentValue); + } + + function numberedListPrefixes() { + var numberPrefix = "style:num-prefix"; + checkListLevelStyleNumberAttribute(numberPrefix, "a b", '[a b] counter(list, decimal) []'); + checkListLevelStyleNumberAttribute(numberPrefix, "'", '[\'] counter(list, decimal) []'); + checkListLevelStyleNumberAttribute(numberPrefix, """, '["] counter(list, decimal) []'); + checkListLevelStyleNumberAttribute(numberPrefix, "\\", '[\\\\] counter(list, decimal) []'); + checkListLevelStyleNumberAttribute(numberPrefix, ";", '[;] counter(list, decimal) []'); + checkListLevelStyleNumberAttribute(numberPrefix, ",", '[,] counter(list, decimal) []'); + } + + function numberedListSuffixes() { + var numberSuffix = "style:num-suffix"; + checkListLevelStyleNumberAttribute(numberSuffix, "a b", 'counter(list, decimal) [a b]'); + checkListLevelStyleNumberAttribute(numberSuffix, "'", 'counter(list, decimal) [\']'); + checkListLevelStyleNumberAttribute(numberSuffix, """, 'counter(list, decimal) ["]'); + checkListLevelStyleNumberAttribute(numberSuffix, "\\", 'counter(list, decimal) [\\\\]'); + checkListLevelStyleNumberAttribute(numberSuffix, ";", 'counter(list, decimal) [;]'); + checkListLevelStyleNumberAttribute(numberSuffix, ",", 'counter(list, decimal) [,]'); + } + + function checkBulletCharacter(value, expectedContentValue) { + applyListStyles( + '' + + '' + + '' + + '' + + '' + + '' + + '', + ""); + + matchContentBlock("checkBulletCharacter", expectedContentValue); + } + + function bulletCharacters() { + checkBulletCharacter("a b", "[a b]"); + checkBulletCharacter("'", "[']"); + checkBulletCharacter(""", "[\"]"); + checkBulletCharacter("\\", "[\\\\]"); + checkBulletCharacter(";", "[;]"); + checkBulletCharacter(",", "[,]"); + } + this.tests = function () { return r.name([ - style_list_level_label_alignment_WithNo_fo_margin_left + verifyCSSContentNormalization, + style_list_level_label_alignment_WithNo_fo_margin_left, + numberedListPrefixes, + numberedListSuffixes, + bulletCharacters ]); }; this.asyncTests = function () {