pretty-format
Version:
Stringify any JavaScript value.
126 lines (80 loc) • 3.34 kB
JavaScript
;Object.defineProperty(exports, "__esModule", { value: true });exports.serialize = exports.test = undefined;
var _escape_html = require('./lib/escape_html');var _escape_html2 = _interopRequireDefault(_escape_html);
var _markup = require('./lib/markup');function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };}
const HTML_ELEMENT_REGEXP = /(HTML\w*?Element)|Text|Comment/; /**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
*/const test = exports.test = val => val !== undefined && val !== null && (val.nodeType === 1 || val.nodeType === 3 || val.nodeType === 8) && val.constructor !== undefined && val.constructor.name !== undefined && HTML_ELEMENT_REGEXP.test(val.constructor.name);
// Return empty string if children is empty.
function printChildren(children, config, indentation, depth, refs, printer) {
const colors = config.colors;
return children.
map(
node =>
typeof node === 'string' ?
colors.content.open + (0, _escape_html2.default)(node) + colors.content.close :
printer(node, config, indentation, depth, refs)).
filter(value => value.trim().length).
map(value => config.spacingOuter + indentation + value).
join('');
}
const getType = element => element.tagName.toLowerCase();
// Convert array of attribute objects to keys array and props object.
const keysMapper = attribute => attribute.name;
const propsReducer = (props, attribute) => {
props[attribute.name] = attribute.value;
return props;
};
const serialize = exports.serialize = (
element,
config,
indentation,
depth,
refs,
printer) =>
{
if (element.nodeType === 3) {
return element.data.
split('\n').
map(text => text.trimLeft()).
filter(text => text.length).
join(' ');
}
const colors = config.colors;
if (element.nodeType === 8) {
return (
colors.comment.open +
'<!-- ' +
element.data.trim() +
' -->' +
colors.comment.close);
}
if (++depth > config.maxDepth) {
return (0, _markup.printElementAsLeaf)(getType(element), config);
}
return (0, _markup.printElement)(
getType(element),
(0, _markup.printProps)(
Array.prototype.map.call(element.attributes, keysMapper).sort(),
Array.prototype.reduce.call(element.attributes, propsReducer, {}),
config,
indentation + config.indent,
depth,
refs,
printer),
printChildren(
Array.prototype.slice.call(element.childNodes),
config,
indentation + config.indent,
depth,
refs,
printer),
config,
indentation);
};exports.default =
{ serialize, test };