From 6348e533063f92260283be2dc3eb19e9e91cad95 Mon Sep 17 00:00:00 2001 From: Antonino Porcino Date: Fri, 8 Jul 2016 14:06:47 +0200 Subject: [PATCH] Added --normalize-html-whitespace CLI option --- package.json | 1 + src/options.js | 5 +++++ src/reactTemplates.js | 12 +++++++++++- 3 files changed, 17 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index eebc64a..90780bf 100644 --- a/package.json +++ b/package.json @@ -36,6 +36,7 @@ "escodegen": "^1.8.0", "esprima": "^2.7.1", "lodash": "^4.11.1", + "normalize-html-whitespace": "^0.2.0", "optionator": "^0.8.0", "text-table": "^0.2.0" }, diff --git a/src/options.js b/src/options.js index 21e8281..1195f26 100644 --- a/src/options.js +++ b/src/options.js @@ -116,5 +116,10 @@ $ rt [ ...] []`, enum: Object.keys(reactNativeSupport), default: reactNativeSupport.default, description: `React native version to generate code for (${Object.keys(reactNativeSupport).join(', ')})` + }, { + option: 'normalize-html-whitespace', + type: 'Boolean', + default: 'false', + description: 'Remove repeating whitespace from HTML text.' }] }); diff --git a/src/reactTemplates.js b/src/reactTemplates.js index 0b93952..54c906b 100644 --- a/src/reactTemplates.js +++ b/src/reactTemplates.js @@ -3,6 +3,7 @@ const cheerio = require('cheerio'); const _ = require('lodash'); const esprima = require('esprima'); const escodegen = require('escodegen'); +const normalizeHtmlWhitespace = require('normalize-html-whitespace'); const reactDOMSupport = require('./reactDOMSupport'); const reactNativeSupport = require('./reactNativeSupport'); const reactPropTemplates = require('./reactPropTemplates'); @@ -55,6 +56,7 @@ const includeSrcAttr = 'src'; const requireAttr = 'rt-require'; const importAttr = 'rt-import'; const statelessAttr = 'rt-stateless'; +const preAttr = 'rt-pre'; const reactTemplatesSelfClosingTags = [includeNode]; @@ -438,7 +440,15 @@ function convertHtmlToReact(node, context) { const sanitizedComment = node.data.split('*/').join('* /'); return commentTemplate({data: sanitizedComment}); } else if (node.type === 'text') { - return trimHtmlText(node.data) ? utils.convertText(node, context, node.data) : ''; + let text = node.data; + const parentNode = node.parent; + if (parentNode !== undefined) { + const preserveWhitespaces = parentNode.name === 'pre' || parentNode.name === 'textarea' || _.has(parentNode.attribs, preAttr); + if (context.options.normalizeHtmlWhitespace && !preserveWhitespaces) { + text = normalizeHtmlWhitespace(text); + } + } + return trimHtmlText(text) ? utils.convertText(node, context, text) : ''; } }