File size: 1,702 Bytes
1e92f2d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
/**
* @file Utility for retrieving the final translatable string from an AST
* node for tests that focus on the strings themselves.
* @author Automattic
* @copyright 2016 Automattic. All rights reserved.
* See LICENSE.md file in root directory for full license.
*/
/**
* Approximates the string that the i18n system will process, by abstracting
* away the difference between TemplateLiteral and Literal strings and
* processing literal string concatenation.
*
* Note that TemplateLiterals with expressions are not supported, because
* they don't work in our translation system.
* @param {Object} node A Literal, TemplateLiteral or BinaryExpression (+) node
* @returns {string|boolean} The concatenated string or the value false.
*/
function getTextContentFromNode( node ) {
// We need to handle two cases:
// TemplateLiteral quasis => node.value.raw
// Literal strings => node.value
// We don't need to handle TeplateLiterals with multiple quasis, because
// we don't support expressions in literals.
let left;
let right;
if ( node.type === 'BinaryExpression' && node.operator === '+' ) {
left = getTextContentFromNode( node.left );
right = getTextContentFromNode( node.right );
if ( left === false || right === false ) {
return false;
}
return left + right;
}
if ( node.type === 'Literal' && 'string' === typeof node.value ) {
return node.value;
}
// template literals are specced at https://github.com/babel/babylon/blob/HEAD/ast/spec.md
if ( node.type === 'TemplateLiteral' ) {
return node.quasis
.map( function ( quasis ) {
return quasis.value.raw;
} )
.join( '' );
}
return false;
}
module.exports = getTextContentFromNode;
|